@myclaw163/clawclaw-cli 0.6.112 → 0.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (422) hide show
  1. package/QUICKSTART.md +46 -0
  2. package/QUICKSTART_HERMES.md +134 -0
  3. package/QUICKSTART_OPENCLAW.md +134 -0
  4. package/QUICKSTART_OTHER.md +134 -0
  5. package/README.md +23 -398
  6. package/bin/clawclaw-cli.mjs +9 -1
  7. package/docs/configuration.md +197 -0
  8. package/docs/runtime/README.md +52 -0
  9. package/docs/runtime/agent-notifications.md +55 -0
  10. package/docs/runtime/components-and-boundaries.md +213 -0
  11. package/docs/runtime/events-and-state.md +105 -0
  12. package/docs/runtime/owner-lifecycle-and-observability.md +69 -0
  13. package/docs/runtime/perception-replay.md +51 -0
  14. package/docs/runtime/short-commands-and-capabilities.md +55 -0
  15. package/docs/runtime/strategy-runtime.md +111 -0
  16. package/docs//350/207/252/345/256/232/344/271/211/346/204/237/347/237/245.md +488 -0
  17. package/docs//350/207/252/345/256/232/344/271/211/347/255/226/347/225/245.md +395 -0
  18. package/package.json +26 -8
  19. package/scripts/check-skill-command-surface.mjs +16 -7
  20. package/scripts/compare-perception-replays.test.ts +188 -0
  21. package/scripts/compare-perception-replays.ts +589 -0
  22. package/scripts/generate-spatial-facts.py +246 -0
  23. package/scripts/package-readme.mjs +48 -0
  24. package/scripts/replay-perception.ts +347 -0
  25. package/scripts/sync-frontend-map.mjs +195 -0
  26. package/scripts/watch-perception-events.test.ts +43 -0
  27. package/scripts/watch-perception-events.ts +162 -0
  28. package/skills/clawclaw/SKILL.md +121 -65
  29. package/skills/clawclaw/references/CHATTERBOX.md +2 -4
  30. package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +1 -1
  31. package/skills/clawclaw/references/COMMANDS.md +95 -61
  32. package/skills/clawclaw/references/GAME-MECHANICS.md +19 -9
  33. package/skills/clawclaw/references/HUB.md +5 -5
  34. package/skills/clawclaw/references/STRATEGIES.md +34 -17
  35. package/skills/clawclaw/references/STREAM.md +82 -46
  36. package/src/assets/clawclaw-map.json +1692 -0
  37. package/src/assets/clawclaw-spatial-facts.json +1291 -0
  38. package/src/assets/clawclaw-spatial-model.txt +142 -0
  39. package/src/cli.ts +21 -47
  40. package/src/commands/account.test.ts +229 -50
  41. package/src/commands/account.ts +456 -223
  42. package/src/commands/communication.test.ts +259 -0
  43. package/src/commands/communication.ts +391 -0
  44. package/src/commands/competition.test.ts +116 -0
  45. package/src/commands/competition.ts +50 -28
  46. package/src/commands/data.test.ts +57 -1
  47. package/src/commands/data.ts +79 -4
  48. package/src/commands/events-canonical-state.test.ts +187 -0
  49. package/src/commands/events.test.ts +50 -136
  50. package/src/commands/events.ts +175 -241
  51. package/src/commands/game/index.test.ts +510 -0
  52. package/src/commands/game/index.ts +556 -0
  53. package/src/commands/game-map.test.ts +48 -7
  54. package/src/commands/hub.test.ts +2 -23
  55. package/src/commands/hub.ts +4 -16
  56. package/src/commands/load.test.ts +10 -22
  57. package/src/commands/load.ts +15 -2
  58. package/src/commands/peek.ts +2 -3
  59. package/src/commands/perception.test.ts +46 -0
  60. package/src/commands/perception.ts +92 -0
  61. package/src/commands/setup/codex.ts +0 -1
  62. package/src/commands/strategy.test.ts +139 -102
  63. package/src/commands/strategy.ts +175 -103
  64. package/src/commands/upgrade.ts +0 -21
  65. package/src/lib/auth.test.ts +35 -0
  66. package/src/lib/auth.ts +45 -6
  67. package/src/lib/diagnostics-config.test.ts +59 -0
  68. package/src/lib/diagnostics-config.ts +76 -0
  69. package/src/lib/game-client.test.ts +166 -0
  70. package/src/lib/game-client.ts +316 -87
  71. package/src/lib/game-context.ts +33 -4
  72. package/src/lib/gameplay-config.test.ts +66 -0
  73. package/src/lib/gameplay-config.ts +151 -0
  74. package/src/lib/http-transport.test.ts +63 -0
  75. package/src/lib/http-transport.ts +76 -10
  76. package/src/lib/init-command.test.ts +25 -1
  77. package/src/lib/init-command.ts +66 -1
  78. package/src/lib/participation-leave.ts +78 -0
  79. package/src/lib/perception-config.test.ts +138 -0
  80. package/src/lib/perception-config.ts +101 -0
  81. package/src/lib/room.test.ts +14 -0
  82. package/src/lib/room.ts +28 -2
  83. package/src/lib/server-registry.test.ts +15 -5
  84. package/src/lib/server-registry.ts +9 -10
  85. package/src/lib/strategy-export.test.ts +123 -44
  86. package/src/lib/strategy-export.ts +110 -81
  87. package/src/lib/user-data.test.ts +2 -0
  88. package/src/lib/user-data.ts +17 -16
  89. package/src/pipeline/canonical-event-presentation.test.ts +196 -0
  90. package/src/pipeline/canonical-event-presentation.ts +71 -0
  91. package/src/pipeline/event-format.test.ts +357 -59
  92. package/src/pipeline/event-format.ts +365 -80
  93. package/src/pipeline/event-hints.test.ts +241 -0
  94. package/src/pipeline/event-hints.ts +202 -51
  95. package/src/pipeline/game-sync-event-normalization.test.ts +239 -0
  96. package/src/pipeline/game-sync-event-normalization.ts +215 -0
  97. package/src/pipeline/player-projection.test.ts +164 -102
  98. package/src/pipeline/player-projection.ts +194 -235
  99. package/src/runtime/canonical-event-emitter.test.ts +70 -0
  100. package/src/runtime/canonical-event-emitter.ts +78 -0
  101. package/src/runtime/canonical-monitor.test.ts +575 -0
  102. package/src/runtime/canonical-monitor.ts +388 -0
  103. package/src/runtime/clawclaw/agent-event-policy.test.ts +27 -0
  104. package/src/runtime/clawclaw/agent-event-policy.ts +35 -0
  105. package/src/runtime/clawclaw/index.ts +4 -0
  106. package/src/runtime/clawclaw/notifications.test.ts +47 -0
  107. package/src/runtime/clawclaw/notifications.ts +65 -0
  108. package/src/runtime/clawclaw/owner-lock.test.ts +221 -0
  109. package/src/runtime/clawclaw/owner.ts +945 -0
  110. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +299 -0
  111. package/src/runtime/clawclaw/plugins/action/index.ts +1 -0
  112. package/src/runtime/clawclaw/plugins/assembly.test.ts +81 -0
  113. package/src/runtime/clawclaw/plugins/assembly.ts +116 -0
  114. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.test.ts +150 -0
  115. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +100 -0
  116. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +162 -0
  117. package/src/runtime/clawclaw/plugins/derived-event/index.ts +2 -0
  118. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.test.ts +223 -0
  119. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +236 -0
  120. package/src/runtime/clawclaw/plugins/game-query/index.ts +1 -0
  121. package/src/runtime/clawclaw/plugins/index.ts +7 -0
  122. package/src/runtime/clawclaw/plugins/mailbox/index.ts +3 -0
  123. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +77 -0
  124. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +91 -0
  125. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +1008 -0
  126. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +475 -0
  127. package/src/runtime/clawclaw/plugins/perception/contracts.ts +32 -0
  128. package/src/runtime/clawclaw/plugins/perception/index.ts +8 -0
  129. package/src/runtime/clawclaw/plugins/perception/module-runner.test.ts +204 -0
  130. package/src/runtime/clawclaw/plugins/perception/module-runner.ts +290 -0
  131. package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +324 -0
  132. package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +365 -0
  133. package/src/runtime/clawclaw/plugins/perception/modules/index.ts +7 -0
  134. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.test.ts +341 -0
  135. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +447 -0
  136. package/src/runtime/clawclaw/plugins/perception/modules/parallel-module-test-helpers.ts +30 -0
  137. package/src/runtime/clawclaw/plugins/perception/modules/relation-stability.test.ts +289 -0
  138. package/src/runtime/clawclaw/plugins/perception/modules/route-module.test.ts +180 -0
  139. package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +329 -0
  140. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.test.ts +82 -0
  141. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +172 -0
  142. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.test.ts +212 -0
  143. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +256 -0
  144. package/src/runtime/clawclaw/plugins/perception/modules/temporal-evidence.test.ts +121 -0
  145. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.test.ts +106 -0
  146. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +225 -0
  147. package/src/runtime/clawclaw/plugins/perception/official-module-ids.ts +11 -0
  148. package/src/runtime/clawclaw/plugins/perception/official-modules.ts +31 -0
  149. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.test.ts +759 -0
  150. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +707 -0
  151. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +215 -0
  152. package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +61 -0
  153. package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +1516 -0
  154. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1529 -0
  155. package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +119 -0
  156. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +244 -0
  157. package/src/runtime/clawclaw/plugins/perception/replay.test.ts +65 -0
  158. package/src/runtime/clawclaw/plugins/perception/replay.ts +86 -0
  159. package/src/runtime/clawclaw/plugins/perception/shared/math.ts +107 -0
  160. package/src/runtime/clawclaw/plugins/perception/spatial-facts.ts +114 -0
  161. package/src/runtime/clawclaw/plugins/perception/visual-state-projector.ts +98 -0
  162. package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +1019 -0
  163. package/src/runtime/clawclaw/plugins/source/game-transport.test.ts +287 -0
  164. package/src/runtime/clawclaw/plugins/source/game-transport.ts +281 -0
  165. package/src/runtime/clawclaw/plugins/source/index.ts +5 -0
  166. package/src/runtime/clawclaw/plugins/source/player-change-tracker.test.ts +270 -0
  167. package/src/runtime/clawclaw/plugins/source/player-change-tracker.ts +151 -0
  168. package/src/runtime/clawclaw/plugins/source/room-transport.test.ts +307 -0
  169. package/src/runtime/clawclaw/plugins/source/room-transport.ts +480 -0
  170. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +1909 -0
  171. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +2055 -0
  172. package/src/runtime/clawclaw/plugins/source/source-transports.ts +30 -0
  173. package/src/runtime/clawclaw/plugins/source/types.ts +79 -0
  174. package/src/runtime/clawclaw/plugins/strategy/context-capabilities.ts +5 -0
  175. package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.test.ts +177 -0
  176. package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.ts +185 -0
  177. package/src/runtime/clawclaw/plugins/strategy/index.ts +8 -0
  178. package/src/runtime/clawclaw/plugins/strategy/local-strategy-executor.ts +412 -0
  179. package/src/runtime/clawclaw/plugins/strategy/strategy-action.ts +73 -0
  180. package/src/runtime/clawclaw/plugins/strategy/strategy-analysis-thread-host.ts +183 -0
  181. package/src/runtime/clawclaw/plugins/strategy/strategy-executor-types.ts +25 -0
  182. package/src/runtime/clawclaw/plugins/strategy/strategy-executor.test.ts +693 -0
  183. package/src/runtime/clawclaw/plugins/strategy/strategy-game-api.ts +57 -0
  184. package/src/runtime/clawclaw/plugins/strategy/strategy-module-loader.ts +164 -0
  185. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.test.ts +1936 -0
  186. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.ts +1557 -0
  187. package/src/runtime/clawclaw/plugins/strategy/strategy-source.test.ts +131 -0
  188. package/src/runtime/clawclaw/plugins/strategy/strategy-source.ts +413 -0
  189. package/src/runtime/clawclaw/plugins/strategy/thread-strategy-executor.ts +792 -0
  190. package/src/runtime/clawclaw/runtime-data-export.test.ts +249 -0
  191. package/src/runtime/clawclaw/runtime-data-export.ts +402 -0
  192. package/src/runtime/clawclaw/runtime-state.ts +98 -0
  193. package/src/runtime/clawclaw/runtime.ts +133 -0
  194. package/src/runtime/clawclaw-event-catalog.test.ts +74 -0
  195. package/src/runtime/clawclaw-event-catalog.ts +266 -0
  196. package/src/runtime/clawclaw-position.ts +4 -0
  197. package/src/runtime/clawclaw-room-state.ts +51 -0
  198. package/src/runtime/framework/action-diagnostics.test.ts +81 -0
  199. package/src/runtime/framework/action-diagnostics.ts +146 -0
  200. package/src/runtime/framework/capability-registry.test.ts +282 -0
  201. package/src/runtime/framework/capability-registry.ts +283 -0
  202. package/src/runtime/framework/contracts.ts +118 -0
  203. package/src/runtime/framework/control/control-scheduler.ts +1260 -0
  204. package/src/runtime/framework/control/domain-set.ts +81 -0
  205. package/src/runtime/framework/control/index.ts +3 -0
  206. package/src/runtime/framework/control/types.ts +184 -0
  207. package/src/runtime/framework/control-coordinator.test.ts +660 -0
  208. package/src/runtime/framework/control-coordinator.ts +11 -0
  209. package/src/runtime/framework/events/event-catalog.ts +74 -0
  210. package/src/runtime/framework/events/event-delivery-service.test.ts +84 -0
  211. package/src/runtime/framework/events/event-delivery-service.ts +198 -0
  212. package/src/runtime/framework/events/event-ingress.test.ts +178 -0
  213. package/src/runtime/framework/events/event-ingress.ts +97 -0
  214. package/src/runtime/framework/events/event-repository.ts +59 -0
  215. package/src/runtime/framework/events/index.ts +7 -0
  216. package/src/runtime/framework/events/mailbox-event-repositories.test.ts +594 -0
  217. package/src/runtime/framework/events/memory-event-repository.ts +928 -0
  218. package/src/runtime/framework/events/sqlite-event-repository.test.ts +200 -0
  219. package/src/runtime/framework/events/sqlite-event-repository.ts +1681 -0
  220. package/src/runtime/framework/events/test-helpers.ts +78 -0
  221. package/src/runtime/framework/events/types.ts +286 -0
  222. package/src/runtime/framework/index.ts +7 -0
  223. package/src/runtime/framework/load-node-sqlite.ts +17 -0
  224. package/src/runtime/framework/mailbox/coalescer.test.ts +55 -0
  225. package/src/runtime/framework/mailbox/coalescer.ts +83 -0
  226. package/src/runtime/framework/mailbox/host-notification-sink.ts +44 -0
  227. package/src/runtime/framework/mailbox/identity.test.ts +38 -0
  228. package/src/runtime/framework/mailbox/identity.ts +38 -0
  229. package/src/runtime/framework/mailbox/index.ts +7 -0
  230. package/src/runtime/framework/mailbox/mailbox-dispatcher.test.ts +513 -0
  231. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +282 -0
  232. package/src/runtime/framework/mailbox/mailbox-repository.ts +44 -0
  233. package/src/runtime/framework/mailbox/notification-projector.test.ts +77 -0
  234. package/src/runtime/framework/mailbox/notification-projector.ts +65 -0
  235. package/src/runtime/framework/mailbox/types.ts +139 -0
  236. package/src/runtime/framework/modules/runtime-module-loader-hooks.d.mts +19 -0
  237. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +117 -0
  238. package/src/runtime/framework/modules/runtime-module-loader.test.ts +209 -0
  239. package/src/runtime/framework/modules/runtime-module-loader.ts +71 -0
  240. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +23 -0
  241. package/src/runtime/framework/participation-manager.test.ts +108 -0
  242. package/src/runtime/framework/participation-manager.ts +244 -0
  243. package/src/runtime/framework/plugins/contracts.ts +382 -0
  244. package/src/runtime/framework/plugins/index.ts +4 -0
  245. package/src/runtime/framework/plugins/runtime-event-identity.ts +17 -0
  246. package/src/runtime/framework/plugins/runtime-input-journal.test.ts +179 -0
  247. package/src/runtime/framework/plugins/runtime-input-journal.ts +693 -0
  248. package/src/runtime/framework/plugins/runtime-plugin-scheduler.test.ts +1994 -0
  249. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +1860 -0
  250. package/src/runtime/framework/runtime.ts +1756 -0
  251. package/src/runtime/framework/serial-task-queue.ts +14 -0
  252. package/src/runtime/framework/state/contracts.ts +49 -0
  253. package/src/runtime/framework/state/current-state-store.ts +184 -0
  254. package/src/runtime/framework/state/durable-agent-state-snapshot.test.ts +144 -0
  255. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +209 -0
  256. package/src/runtime/framework/state/freshness.ts +72 -0
  257. package/src/runtime/framework/state/history/contracts.ts +150 -0
  258. package/src/runtime/framework/state/history/history-writer.ts +194 -0
  259. package/src/runtime/framework/state/history/memory-state-history-repository.ts +178 -0
  260. package/src/runtime/framework/state/history/sqlite-state-history-repository.test.ts +157 -0
  261. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +629 -0
  262. package/src/runtime/framework/state/history/state-history.test.ts +251 -0
  263. package/src/runtime/framework/state/history/trajectory-projector.ts +209 -0
  264. package/src/runtime/framework/state/index.ts +13 -0
  265. package/src/runtime/framework/state/state-core.test.ts +197 -0
  266. package/src/runtime/framework/state/state-ingress.ts +95 -0
  267. package/src/runtime/framework/state/state-provider.ts +62 -0
  268. package/src/runtime/framework/state/types.ts +155 -0
  269. package/src/runtime/game-sync-protocol.test.ts +123 -0
  270. package/src/runtime/game-sync-protocol.ts +261 -0
  271. package/src/runtime/mailbox-host-relay.test.ts +248 -0
  272. package/src/runtime/mailbox-host-relay.ts +300 -0
  273. package/src/runtime/observability/factory.ts +188 -0
  274. package/src/runtime/observability/index.ts +6 -0
  275. package/src/runtime/observability/observability.test.ts +561 -0
  276. package/src/runtime/observability/recorder.ts +209 -0
  277. package/src/runtime/observability/redaction.ts +154 -0
  278. package/src/runtime/observability/reporter.ts +154 -0
  279. package/src/runtime/observability/sinks.ts +135 -0
  280. package/src/runtime/observability/types.ts +92 -0
  281. package/src/runtime/owner-control.test.ts +153 -0
  282. package/src/runtime/owner-control.ts +206 -42
  283. package/src/runtime/parent-process-watch.test.ts +27 -0
  284. package/src/runtime/parent-process-watch.ts +51 -0
  285. package/src/runtime/pending-event-handoff.test.ts +29 -0
  286. package/src/runtime/pending-event-handoff.ts +61 -0
  287. package/src/runtime/raw-ws-log.test.ts +86 -17
  288. package/src/runtime/raw-ws-log.ts +230 -21
  289. package/src/runtime/runtime-logger.test.ts +58 -0
  290. package/src/runtime/runtime-logger.ts +10 -13
  291. package/src/runtime/runtime-persistence.test.ts +26 -0
  292. package/src/runtime/runtime.test.ts +1704 -0
  293. package/src/runtime/ws-client.test.ts +496 -103
  294. package/src/runtime/ws-client.ts +546 -166
  295. package/src/sdk/action.ts +3 -1
  296. package/src/sdk/index.ts +4 -19
  297. package/src/sdk/perception-plugin/index.test.ts +22 -0
  298. package/src/sdk/perception-plugin/index.ts +285 -0
  299. package/src/sdk/strategy-plugin/index.test.ts +952 -0
  300. package/src/sdk/strategy-plugin/index.ts +1324 -0
  301. package/src/sdk/types.ts +3 -1
  302. package/src/short-command/classifier.test.ts +107 -0
  303. package/src/short-command/classifier.ts +169 -0
  304. package/src/short-command/index.ts +7 -0
  305. package/src/short-command/presenter.test.ts +119 -0
  306. package/src/short-command/presenter.ts +308 -0
  307. package/src/short-command/process-io.ts +13 -0
  308. package/src/short-command/response-contract.ts +58 -0
  309. package/src/short-command/runner.test.ts +78 -0
  310. package/src/short-command/runner.ts +164 -0
  311. package/src/short-command/sensitive-data-filter.test.ts +56 -0
  312. package/src/short-command/sensitive-data-filter.ts +123 -0
  313. package/src/short-command/transport-response.test.ts +39 -0
  314. package/src/short-command/transport-response.ts +89 -0
  315. package/src/short-command/types.ts +92 -0
  316. package/src/strategies/avoid-lone.ts +18 -11
  317. package/src/strategies/avoid-players.ts +29 -13
  318. package/src/strategies/corpse-patrol.ts +29 -11
  319. package/src/strategies/crab-sabotage.ts +31 -18
  320. package/src/strategies/custom-module.test.ts +3 -5
  321. package/src/strategies/find-player.ts +34 -15
  322. package/src/strategies/game-utils.test.ts +42 -0
  323. package/src/strategies/game-utils.ts +143 -53
  324. package/src/strategies/goals/avoid-lone-top.ts +22 -1
  325. package/src/strategies/goals/avoid-players-top.test.ts +13 -0
  326. package/src/strategies/goals/avoid-players-top.ts +6 -5
  327. package/src/strategies/goals/corpse-patrol-top.ts +9 -2
  328. package/src/strategies/goals/crab-octopus-reflexes.ts +6 -2
  329. package/src/strategies/goals/crab-sabotage-top.ts +7 -1
  330. package/src/strategies/goals/emergency-hunt-goal.ts +15 -3
  331. package/src/strategies/goals/find-player-top.ts +47 -3
  332. package/src/strategies/goals/flee-players-goal.ts +2 -0
  333. package/src/strategies/goals/follow-companion-goal.ts +27 -3
  334. package/src/strategies/goals/hide-top.ts +47 -5
  335. package/src/strategies/goals/keep-away-goal.ts +24 -2
  336. package/src/strategies/goals/kill-frenzy-top.ts +12 -2
  337. package/src/strategies/goals/kill-lone-top.test.ts +72 -0
  338. package/src/strategies/goals/kill-lone-top.ts +8 -6
  339. package/src/strategies/goals/kill-target-goal.ts +16 -7
  340. package/src/strategies/goals/kill-target-top.ts +16 -2
  341. package/src/strategies/goals/linger-corpse-goal.ts +11 -3
  342. package/src/strategies/goals/lone-kill-core.ts +4 -2
  343. package/src/strategies/goals/move-room-goal.ts +46 -4
  344. package/src/strategies/goals/normal-shrimp-top.test.ts +16 -0
  345. package/src/strategies/goals/normal-shrimp-top.ts +18 -18
  346. package/src/strategies/goals/paradise-fish-top.test.ts +78 -0
  347. package/src/strategies/goals/paradise-fish-top.ts +16 -6
  348. package/src/strategies/goals/patrol-top.ts +14 -3
  349. package/src/strategies/goals/report-patrol-top.ts +14 -3
  350. package/src/strategies/goals/safe-task-goal.ts +32 -4
  351. package/src/strategies/goals/social-task-top.ts +39 -8
  352. package/src/strategies/goals/task-kill-report-top.ts +33 -10
  353. package/src/strategies/goals/task-only-top.test.ts +89 -0
  354. package/src/strategies/goals/task-only-top.ts +9 -2
  355. package/src/strategies/goals/task-or-patrol-goal.ts +21 -3
  356. package/src/strategies/goals/warrior-shrimp-top.test.ts +75 -23
  357. package/src/strategies/goals/warrior-shrimp-top.ts +34 -13
  358. package/src/strategies/greeting.ts +10 -3
  359. package/src/strategies/hide-spots.ts +4 -0
  360. package/src/strategies/hide.ts +35 -20
  361. package/src/strategies/kill-frenzy.ts +18 -12
  362. package/src/strategies/kill-lone.ts +43 -12
  363. package/src/strategies/kill-target.ts +34 -17
  364. package/src/strategies/lone-kill-task.ts +31 -18
  365. package/src/strategies/move-room.ts +32 -15
  366. package/src/strategies/off-route-points.ts +12 -4
  367. package/src/strategies/paradise-fish.ts +49 -14
  368. package/src/strategies/pathfind/astar-path.test.ts +73 -0
  369. package/src/strategies/pathfind/astar-path.ts +196 -0
  370. package/src/strategies/pathfind/escape-planner.test.ts +27 -1
  371. package/src/strategies/pathfind/escape-planner.ts +108 -0
  372. package/src/strategies/patrol.ts +18 -11
  373. package/src/strategies/report-patrol.ts +18 -11
  374. package/src/strategies/shrimp-memory.ts +66 -14
  375. package/src/strategies/social-task.ts +49 -45
  376. package/src/strategies/task-kill-report.ts +34 -16
  377. package/src/strategies/task-only.test.ts +124 -0
  378. package/src/strategies/task-only.ts +20 -11
  379. package/src/strategies/task-report.ts +29 -11
  380. package/src/strategies/types.ts +29 -62
  381. package/src/strategies/warrior-memory.ts +44 -14
  382. package/scripts/check_monitor.test.mjs +0 -212
  383. package/skills/clawclaw/references/KNOWLEDGE.md +0 -42
  384. package/src/assets/clawclaw-ascii-map.txt +0 -40
  385. package/src/commands/do.test.ts +0 -117
  386. package/src/commands/do.ts +0 -195
  387. package/src/commands/game-monitor-status.test.ts +0 -58
  388. package/src/commands/game-start-plan.test.ts +0 -356
  389. package/src/commands/game.ts +0 -2046
  390. package/src/commands/history-player.test.ts +0 -105
  391. package/src/commands/history.ts +0 -573
  392. package/src/commands/knowledge.test.ts +0 -13
  393. package/src/commands/knowledge.ts +0 -176
  394. package/src/commands/meeting-history.test.ts +0 -106
  395. package/src/commands/state.ts +0 -46
  396. package/src/commands/watch.test.ts +0 -1313
  397. package/src/commands/watch.ts +0 -824
  398. package/src/lib/knowledge-store.test.ts +0 -170
  399. package/src/lib/knowledge-store.ts +0 -369
  400. package/src/perception/player-history-store.test.ts +0 -177
  401. package/src/perception/player-history-store.ts +0 -262
  402. package/src/pipeline/event-store.test.ts +0 -28
  403. package/src/pipeline/event-store.ts +0 -193
  404. package/src/pipeline/pipeline.ts +0 -35
  405. package/src/runtime/event-daemon.test.ts +0 -268
  406. package/src/runtime/event-daemon.ts +0 -531
  407. package/src/runtime/room-lobby-runtime.test.ts +0 -95
  408. package/src/runtime/room-lobby-runtime.ts +0 -367
  409. package/src/strategies/avoid-players.knowledge.md +0 -19
  410. package/src/strategies/kill-lone.knowledge.md +0 -17
  411. package/src/strategies/knowledge-contract.ts +0 -85
  412. package/src/strategies/loader.test.ts +0 -710
  413. package/src/strategies/loader.ts +0 -183
  414. package/src/strategies/new-events-backfill.ts +0 -98
  415. package/src/strategies/paradise-fish.knowledge.md +0 -19
  416. package/src/strategies/scanner.ts +0 -238
  417. package/src/strategies/shrimp-memory.knowledge.md +0 -19
  418. package/src/strategies/social-task.test.ts +0 -28
  419. package/src/strategies/spawn.ts +0 -82
  420. package/src/strategies/strategy-loop.test.ts +0 -15
  421. package/src/strategies/strategy-loop.ts +0 -748
  422. package/src/strategies/warrior-memory.knowledge.md +0 -21
@@ -0,0 +1,1681 @@
1
+ import { createRequire } from 'module';
2
+ import { randomUUID } from 'crypto';
3
+ import { mkdirSync } from 'fs';
4
+ import { dirname } from 'path';
5
+ import { loadNodeSqliteModule } from '../load-node-sqlite.js';
6
+ import type { MailboxRepository } from '../mailbox/mailbox-repository.js';
7
+ import type {
8
+ AckMailboxClaimRequest,
9
+ AckMailboxClaimResult,
10
+ ClaimMailboxItemsRequest,
11
+ EnqueueMailboxItem,
12
+ EnqueueMailboxResult,
13
+ MailboxClaim,
14
+ MailboxDeliveryMode,
15
+ MailboxItem,
16
+ MailboxPeekFilter,
17
+ NackMailboxClaimRequest,
18
+ NackMailboxClaimResult,
19
+ SuppressMailboxItemsFilter,
20
+ } from '../mailbox/types.js';
21
+ import { DeliveryLeaseLostError, type EventRepository } from './event-repository.js';
22
+ import {
23
+ cloneRecord,
24
+ initialDeliveryFor,
25
+ type AcquireLeaseRequest,
26
+ type BacklogSummary,
27
+ type CanonicalEvent,
28
+ type CommittedEventListFilter,
29
+ type CommitEventRequest,
30
+ type CommitEventResult,
31
+ type ConsumerLease,
32
+ type CurrentEventScope,
33
+ type DetailStateTransition,
34
+ type EventAccountScope,
35
+ type EventDeliveryRecord,
36
+ type EventListFilter,
37
+ type EventSegmentRecord,
38
+ type EventWithDelivery,
39
+ type LatestEventScopeOptions,
40
+ type MonitorDeliveryAttempt,
41
+ type MonitorStateTransition,
42
+ type PlaySessionRecord,
43
+ type SourceCheckpointRecord,
44
+ } from './types.js';
45
+
46
+ interface StatementLike {
47
+ run(...params: unknown[]): { changes?: number | bigint; lastInsertRowid?: number | bigint };
48
+ get(...params: unknown[]): Record<string, unknown> | undefined;
49
+ all(...params: unknown[]): Array<Record<string, unknown>>;
50
+ }
51
+
52
+ interface DatabaseLike {
53
+ exec(sql: string): void;
54
+ prepare(sql: string): StatementLike;
55
+ close(): void;
56
+ }
57
+
58
+ interface SqliteModuleLike {
59
+ DatabaseSync?: new (path: string) => DatabaseLike;
60
+ }
61
+
62
+ export interface SqliteUnavailable {
63
+ code: 'SQLITE_UNAVAILABLE' | 'SQLITE_OPEN_FAILED';
64
+ message: string;
65
+ cause?: string;
66
+ }
67
+
68
+ export type SqliteRepositoryOpenResult =
69
+ | { ok: true; repository: SqliteEventRepository }
70
+ | { ok: false; unavailable: SqliteUnavailable };
71
+
72
+ const require = createRequire(import.meta.url);
73
+
74
+ function loadSqlite(): { ok: true; module: SqliteModuleLike } | { ok: false; unavailable: SqliteUnavailable } {
75
+ try {
76
+ const module = loadNodeSqliteModule<SqliteModuleLike>(require);
77
+ if (typeof module.DatabaseSync !== 'function') {
78
+ return {
79
+ ok: false,
80
+ unavailable: {
81
+ code: 'SQLITE_UNAVAILABLE',
82
+ message: 'This Node.js runtime does not expose node:sqlite DatabaseSync.',
83
+ },
84
+ };
85
+ }
86
+ return { ok: true, module };
87
+ } catch (error) {
88
+ return {
89
+ ok: false,
90
+ unavailable: {
91
+ code: 'SQLITE_UNAVAILABLE',
92
+ message: 'SQLite event storage is unavailable in this Node.js runtime. Use MemoryEventRepository or a Node build with node:sqlite.',
93
+ cause: error instanceof Error ? error.message : String(error),
94
+ },
95
+ };
96
+ }
97
+ }
98
+
99
+ export function detectSqliteAvailability(): SqliteUnavailable | null {
100
+ const result = loadSqlite();
101
+ return result.ok ? null : result.unavailable;
102
+ }
103
+
104
+ function booleanInt(value: boolean): number {
105
+ return value ? 1 : 0;
106
+ }
107
+
108
+ function numberValue(value: unknown): number {
109
+ return typeof value === 'bigint' ? Number(value) : Number(value ?? 0);
110
+ }
111
+
112
+ function optionalString(value: unknown): string | undefined {
113
+ return typeof value === 'string' ? value : undefined;
114
+ }
115
+
116
+ function sessionFromRow(row: Record<string, unknown>): PlaySessionRecord {
117
+ return {
118
+ sessionId: String(row.session_id),
119
+ adapterId: String(row.adapter_id),
120
+ accountId: String(row.account_id),
121
+ resumeKey: optionalString(row.resume_key),
122
+ mode: optionalString(row.mode),
123
+ status: row.status === 'sealed' ? 'sealed' : 'open',
124
+ isCurrent: numberValue(row.is_current) === 1,
125
+ openedAt: String(row.opened_at),
126
+ sealedAt: optionalString(row.sealed_at),
127
+ };
128
+ }
129
+
130
+ function segmentFromRow(row: Record<string, unknown>): EventSegmentRecord {
131
+ return {
132
+ segmentId: String(row.segment_id),
133
+ sessionId: String(row.session_id),
134
+ sequence: numberValue(row.segment_seq),
135
+ kind: String(row.kind),
136
+ scopeRef: optionalString(row.scope_ref),
137
+ status: row.status === 'closed' ? 'closed' : 'open',
138
+ isCurrent: numberValue(row.is_current) === 1,
139
+ openedAt: String(row.opened_at),
140
+ closedAt: optionalString(row.closed_at),
141
+ };
142
+ }
143
+
144
+ function eventFromRow(row: Record<string, unknown>): CanonicalEvent {
145
+ const payload = JSON.parse(String(row.payload_json)) as Record<string, unknown>;
146
+ return {
147
+ commitSeq: numberValue(row.commit_seq),
148
+ ...(row.epoch_seq === null || row.epoch_seq === undefined
149
+ ? {}
150
+ : { epochSeq: numberValue(row.epoch_seq) }),
151
+ eventId: String(row.event_id),
152
+ sessionId: String(row.session_id),
153
+ segmentId: String(row.segment_id),
154
+ type: String(row.type),
155
+ producer: row.producer === 'local_synth' ? 'local_synth' : 'backend_push',
156
+ ...(optionalString(row.producer_plugin_id) === undefined
157
+ ? {}
158
+ : { producerPluginId: optionalString(row.producer_plugin_id) }),
159
+ ...(row.producer_output_index === null || row.producer_output_index === undefined
160
+ ? {}
161
+ : { producerOutputIndex: numberValue(row.producer_output_index) }),
162
+ deliveryClass: row.delivery_class === 'monitor_and_events'
163
+ ? 'monitor_and_events'
164
+ : row.delivery_class === 'events_only'
165
+ ? 'events_only'
166
+ : 'internal_only',
167
+ occurredAt: String(row.occurred_at),
168
+ receivedAt: String(row.received_at),
169
+ payload,
170
+ sourceId: String(row.source_id),
171
+ sourceEventId: optionalString(row.source_event_id),
172
+ sourceSequence: optionalString(row.source_sequence),
173
+ connectionId: optionalString(row.connection_id),
174
+ replayed: numberValue(row.replayed) === 1,
175
+ };
176
+ }
177
+
178
+ function deliveryFromRow(row: Record<string, unknown>): EventDeliveryRecord {
179
+ return {
180
+ eventId: String(row.event_id),
181
+ consumerId: String(row.consumer_id),
182
+ monitorState: row.monitor_state as EventDeliveryRecord['monitorState'],
183
+ monitorAttemptCount: numberValue(row.monitor_attempt_count),
184
+ monitorLastAttemptAt: optionalString(row.monitor_last_attempt_at),
185
+ monitorDeliveredAt: optionalString(row.monitor_delivered_at),
186
+ detailState: row.detail_state as EventDeliveryRecord['detailState'],
187
+ detailDeliveredAt: optionalString(row.detail_delivered_at),
188
+ detailDeliveryVia: row.detail_delivery_via as EventDeliveryRecord['detailDeliveryVia'],
189
+ };
190
+ }
191
+
192
+ function checkpointFromRow(row: Record<string, unknown>): SourceCheckpointRecord {
193
+ return {
194
+ sourceId: String(row.source_id),
195
+ checkpoint: String(row.checkpoint),
196
+ sourceSequence: optionalString(row.source_sequence),
197
+ eventId: String(row.event_id),
198
+ committedAt: String(row.committed_at),
199
+ };
200
+ }
201
+
202
+ function mailboxItemFromRow<T = unknown>(row: Record<string, unknown>): MailboxItem<T> {
203
+ return {
204
+ itemId: String(row.item_id),
205
+ schemaVersion: numberValue(row.schema_version),
206
+ formatterVersion: String(row.formatter_version),
207
+ consumerId: String(row.consumer_id),
208
+ sessionId: String(row.session_id),
209
+ segmentId: String(row.segment_id),
210
+ eventId: String(row.event_id),
211
+ eventCommitSeq: numberValue(row.event_commit_seq),
212
+ // New runtime code only creates short notifications. The SQLite schema
213
+ // still accepts historical full rows so existing ledgers open in place.
214
+ mode: 'short',
215
+ coalesceKey: String(row.coalesce_key),
216
+ payload: JSON.parse(String(row.payload_json)) as T,
217
+ state: row.state as MailboxItem<T>['state'],
218
+ attemptCount: numberValue(row.attempt_count),
219
+ availableAtMs: numberValue(row.available_at),
220
+ createdAt: String(row.created_at),
221
+ updatedAt: String(row.updated_at),
222
+ lastAttemptAt: optionalString(row.last_attempt_at),
223
+ claimOwner: optionalString(row.claim_owner),
224
+ claimToken: optionalString(row.claim_token),
225
+ claimExpiresAtMs: row.claim_expires_at === null || row.claim_expires_at === undefined
226
+ ? undefined
227
+ : numberValue(row.claim_expires_at),
228
+ acceptedAt: optionalString(row.accepted_at),
229
+ acceptanceLevel: row.acceptance_level === 'host_accepted'
230
+ ? 'host_accepted'
231
+ : row.acceptance_level === 'sink_emitted'
232
+ ? 'sink_emitted'
233
+ : undefined,
234
+ receiptId: optionalString(row.receipt_id),
235
+ lastErrorCode: optionalString(row.last_error_code),
236
+ };
237
+ }
238
+
239
+ function placeholders(count: number): string {
240
+ return new Array(count).fill('?').join(', ');
241
+ }
242
+
243
+ export class SqliteEventRepository implements EventRepository, MailboxRepository {
244
+ static open(path: string): SqliteRepositoryOpenResult {
245
+ const loaded = loadSqlite();
246
+ if (!loaded.ok) return loaded;
247
+ let db: DatabaseLike | undefined;
248
+ try {
249
+ if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true });
250
+ const DatabaseSync = loaded.module.DatabaseSync;
251
+ if (!DatabaseSync) {
252
+ return {
253
+ ok: false,
254
+ unavailable: {
255
+ code: 'SQLITE_UNAVAILABLE',
256
+ message: 'This Node.js runtime does not expose node:sqlite DatabaseSync.',
257
+ },
258
+ };
259
+ }
260
+ db = new DatabaseSync(path);
261
+ const repository = new SqliteEventRepository(db);
262
+ repository.configure();
263
+ repository.migrate();
264
+ return { ok: true, repository };
265
+ } catch (error) {
266
+ try { db?.close(); } catch {}
267
+ return {
268
+ ok: false,
269
+ unavailable: {
270
+ code: 'SQLITE_OPEN_FAILED',
271
+ message: `Unable to open the SQLite event repository at ${path}.`,
272
+ cause: error instanceof Error ? error.message : String(error),
273
+ },
274
+ };
275
+ }
276
+ }
277
+
278
+ private constructor(private readonly db: DatabaseLike) {}
279
+
280
+ close(): void {
281
+ this.db.close();
282
+ }
283
+
284
+ schemaVersion(): number {
285
+ const row = this.db.prepare('SELECT MAX(version) AS version FROM schema_migrations').get();
286
+ return numberValue(row?.version);
287
+ }
288
+
289
+ journalMode(): string {
290
+ const row = this.db.prepare('PRAGMA journal_mode').get();
291
+ return String(row?.journal_mode ?? 'unknown').toLowerCase();
292
+ }
293
+
294
+ saveSession(session: PlaySessionRecord): void {
295
+ this.transaction(() => {
296
+ const existing = this.db.prepare(`
297
+ SELECT is_current FROM play_sessions WHERE session_id = ?
298
+ `).get(session.sessionId);
299
+ if (numberValue(existing?.is_current) === 1 && !session.isCurrent) {
300
+ this.retireMailboxScope(
301
+ 'session_id',
302
+ session.sessionId,
303
+ session.sealedAt ?? session.openedAt,
304
+ );
305
+ }
306
+ if (session.isCurrent) {
307
+ this.db.prepare(`
308
+ UPDATE mailbox_items
309
+ SET state = 'suppressed', updated_at = ?
310
+ WHERE state = 'pending'
311
+ AND session_id IN (
312
+ SELECT session_id
313
+ FROM play_sessions
314
+ WHERE adapter_id = ?
315
+ AND account_id = ?
316
+ AND session_id <> ?
317
+ AND is_current = 1
318
+ )
319
+ `).run(session.openedAt, session.adapterId, session.accountId, session.sessionId);
320
+ this.db.prepare(`
321
+ UPDATE event_deliveries
322
+ SET detail_state = CASE
323
+ WHEN detail_state = 'pending' THEN 'deferred'
324
+ ELSE detail_state
325
+ END,
326
+ monitor_state = CASE
327
+ WHEN monitor_state = 'pending'
328
+ AND NOT EXISTS (
329
+ SELECT 1
330
+ FROM mailbox_items m
331
+ WHERE m.event_id = event_deliveries.event_id
332
+ AND m.consumer_id = event_deliveries.consumer_id
333
+ AND m.state = 'claimed'
334
+ ) THEN 'suppressed'
335
+ ELSE monitor_state
336
+ END
337
+ WHERE event_id IN (
338
+ SELECT e.event_id
339
+ FROM events e
340
+ JOIN play_sessions p ON p.session_id = e.session_id
341
+ WHERE p.adapter_id = ?
342
+ AND p.account_id = ?
343
+ AND p.session_id <> ?
344
+ AND p.is_current = 1
345
+ )
346
+ `).run(session.adapterId, session.accountId, session.sessionId);
347
+ this.db.prepare(`
348
+ UPDATE play_sessions
349
+ SET is_current = 0
350
+ WHERE adapter_id = ? AND account_id = ? AND session_id <> ? AND is_current = 1
351
+ `).run(session.adapterId, session.accountId, session.sessionId);
352
+ }
353
+ this.db.prepare(`
354
+ INSERT INTO play_sessions(
355
+ session_id, adapter_id, account_id, resume_key, mode, status,
356
+ is_current, opened_at, sealed_at
357
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
358
+ ON CONFLICT(session_id) DO UPDATE SET
359
+ adapter_id = excluded.adapter_id,
360
+ account_id = excluded.account_id,
361
+ resume_key = excluded.resume_key,
362
+ mode = excluded.mode,
363
+ status = excluded.status,
364
+ is_current = excluded.is_current,
365
+ opened_at = excluded.opened_at,
366
+ sealed_at = excluded.sealed_at
367
+ `).run(
368
+ session.sessionId,
369
+ session.adapterId,
370
+ session.accountId,
371
+ session.resumeKey ?? null,
372
+ session.mode ?? null,
373
+ session.status,
374
+ booleanInt(session.isCurrent),
375
+ session.openedAt,
376
+ session.sealedAt ?? null,
377
+ );
378
+ });
379
+ }
380
+
381
+ saveSegment(segment: EventSegmentRecord): void {
382
+ this.transaction(() => {
383
+ const existing = this.db.prepare(`
384
+ SELECT is_current FROM event_segments WHERE segment_id = ?
385
+ `).get(segment.segmentId);
386
+ if (numberValue(existing?.is_current) === 1 && !segment.isCurrent) {
387
+ this.db.prepare(`
388
+ UPDATE mailbox_items
389
+ SET available_at = 0, updated_at = ?
390
+ WHERE state = 'pending' AND segment_id = ?
391
+ `).run(segment.closedAt ?? segment.openedAt, segment.segmentId);
392
+ this.db.prepare(`
393
+ UPDATE event_deliveries
394
+ SET detail_state = 'deferred'
395
+ WHERE detail_state = 'pending'
396
+ AND event_id IN (SELECT event_id FROM events WHERE segment_id = ?)
397
+ `).run(segment.segmentId);
398
+ }
399
+ if (segment.isCurrent) {
400
+ this.db.prepare(`
401
+ UPDATE mailbox_items
402
+ SET available_at = 0, updated_at = ?
403
+ WHERE state = 'pending'
404
+ AND segment_id IN (
405
+ SELECT segment_id
406
+ FROM event_segments
407
+ WHERE session_id = ?
408
+ AND is_current = 1
409
+ AND segment_id <> ?
410
+ )
411
+ `).run(segment.openedAt, segment.sessionId, segment.segmentId);
412
+ this.db.prepare(`
413
+ UPDATE event_deliveries
414
+ SET detail_state = 'deferred'
415
+ WHERE detail_state = 'pending'
416
+ AND event_id IN (
417
+ SELECT e.event_id
418
+ FROM events e
419
+ JOIN event_segments s ON s.segment_id = e.segment_id
420
+ WHERE s.session_id = ?
421
+ AND s.is_current = 1
422
+ AND s.segment_id <> ?
423
+ )
424
+ `).run(segment.sessionId, segment.segmentId);
425
+ this.db.prepare(`
426
+ UPDATE event_segments
427
+ SET is_current = 0
428
+ WHERE session_id = ? AND segment_id <> ? AND is_current = 1
429
+ `).run(segment.sessionId, segment.segmentId);
430
+ }
431
+ this.db.prepare(`
432
+ INSERT INTO event_segments(
433
+ segment_id, session_id, segment_seq, kind, scope_ref, status,
434
+ is_current, opened_at, closed_at
435
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
436
+ ON CONFLICT(segment_id) DO UPDATE SET
437
+ session_id = excluded.session_id,
438
+ segment_seq = excluded.segment_seq,
439
+ kind = excluded.kind,
440
+ scope_ref = excluded.scope_ref,
441
+ status = excluded.status,
442
+ is_current = excluded.is_current,
443
+ opened_at = excluded.opened_at,
444
+ closed_at = excluded.closed_at
445
+ `).run(
446
+ segment.segmentId,
447
+ segment.sessionId,
448
+ segment.sequence,
449
+ segment.kind,
450
+ segment.scopeRef ?? null,
451
+ segment.status,
452
+ booleanInt(segment.isCurrent),
453
+ segment.openedAt,
454
+ segment.closedAt ?? null,
455
+ );
456
+ });
457
+ }
458
+
459
+ currentScope(account?: EventAccountScope): CurrentEventScope | null {
460
+ const where = account ? 'WHERE is_current = 1 AND adapter_id = ? AND account_id = ?' : 'WHERE is_current = 1';
461
+ const params = account ? [account.adapterId, account.accountId] : [];
462
+ const sessions = this.db.prepare(`
463
+ SELECT * FROM play_sessions ${where} ORDER BY opened_at DESC LIMIT 2
464
+ `).all(...params);
465
+ if (sessions.length > 1) {
466
+ throw new Error('Multiple current event sessions exist; provide adapterId and accountId.');
467
+ }
468
+ if (sessions.length === 0) return null;
469
+ const session = sessionFromRow(sessions[0]);
470
+ const segmentRow = this.db.prepare(`
471
+ SELECT * FROM event_segments
472
+ WHERE session_id = ? AND is_current = 1
473
+ ORDER BY segment_seq DESC LIMIT 1
474
+ `).get(session.sessionId);
475
+ if (!segmentRow) return null;
476
+ return { session, segment: segmentFromRow(segmentRow) };
477
+ }
478
+
479
+ latestScope(account: EventAccountScope, options: LatestEventScopeOptions = {}): CurrentEventScope | null {
480
+ const sessionRow = this.db.prepare(`
481
+ SELECT * FROM play_sessions
482
+ WHERE adapter_id = ? AND account_id = ?
483
+ ORDER BY is_current DESC, opened_at DESC
484
+ LIMIT 1
485
+ `).get(account.adapterId, account.accountId);
486
+ if (!sessionRow) return null;
487
+ const session = sessionFromRow(sessionRow);
488
+ const clauses = ['session_id = ?'];
489
+ const params: unknown[] = [session.sessionId];
490
+ if (options.segmentKinds?.length) {
491
+ clauses.push(`kind IN (${options.segmentKinds.map(() => '?').join(', ')})`);
492
+ params.push(...options.segmentKinds);
493
+ }
494
+ const segmentRow = this.db.prepare(`
495
+ SELECT * FROM event_segments
496
+ WHERE ${clauses.join(' AND ')}
497
+ ORDER BY is_current DESC, segment_seq DESC
498
+ LIMIT 1
499
+ `).get(...params);
500
+ return segmentRow ? { session, segment: segmentFromRow(segmentRow) } : null;
501
+ }
502
+
503
+ commitEvent(request: CommitEventRequest): CommitEventResult {
504
+ return this.transaction(() => {
505
+ const duplicateById = request.event.sourceEventId
506
+ ? this.findByRemoteId(request.event.sourceId, request.event.sourceEventId)
507
+ : null;
508
+ const duplicateBySequence = request.event.sourceSequence
509
+ ? this.findByRemoteSequence(
510
+ request.event.sourceId,
511
+ request.event.sessionId,
512
+ request.event.segmentId,
513
+ request.event.sourceSequence,
514
+ )
515
+ : null;
516
+ if (duplicateById && duplicateBySequence && duplicateById.eventId !== duplicateBySequence.eventId) {
517
+ throw new Error('Conflicting source event ID and source sequence identities.');
518
+ }
519
+ const duplicate = duplicateById ?? duplicateBySequence;
520
+ if (duplicate) {
521
+ for (const consumerId of new Set(request.consumerIds)) {
522
+ this.insertInitialDelivery(duplicate, consumerId);
523
+ }
524
+ return { inserted: false, event: duplicate };
525
+ }
526
+ if (this.eventById(request.event.eventId)) {
527
+ throw new Error(`Event ID already exists: ${request.event.eventId}`);
528
+ }
529
+
530
+ const result = this.db.prepare(`
531
+ INSERT INTO events(
532
+ event_id, epoch_seq, session_id, segment_id, type, producer,
533
+ producer_plugin_id, producer_output_index, delivery_class,
534
+ occurred_at, received_at, payload_json, source_id, source_event_id,
535
+ source_sequence, connection_id, replayed
536
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
537
+ `).run(
538
+ request.event.eventId,
539
+ request.event.epochSeq ?? null,
540
+ request.event.sessionId,
541
+ request.event.segmentId,
542
+ request.event.type,
543
+ request.event.producer,
544
+ request.event.producerPluginId ?? null,
545
+ request.event.producerOutputIndex ?? null,
546
+ request.event.deliveryClass,
547
+ request.event.occurredAt,
548
+ request.event.receivedAt,
549
+ JSON.stringify(request.event.payload),
550
+ request.event.sourceId,
551
+ request.event.sourceEventId ?? null,
552
+ request.event.sourceSequence ?? null,
553
+ request.event.connectionId ?? null,
554
+ booleanInt(request.event.replayed),
555
+ );
556
+ const event: CanonicalEvent = {
557
+ ...cloneRecord(request.event),
558
+ commitSeq: numberValue(result.lastInsertRowid),
559
+ };
560
+ for (const consumerId of new Set(request.consumerIds)) {
561
+ this.insertInitialDelivery(event, consumerId);
562
+ }
563
+ if (request.checkpoint) this.upsertCheckpoint(request.checkpoint);
564
+ return { inserted: true, event: cloneRecord(event) };
565
+ });
566
+ }
567
+
568
+ eventById(eventId: string): CanonicalEvent | null {
569
+ const row = this.db.prepare('SELECT * FROM events WHERE event_id = ?').get(eventId);
570
+ return row ? eventFromRow(row) : null;
571
+ }
572
+
573
+ latestEventByType(sessionId: string, type: string, segmentId?: string): CanonicalEvent | null {
574
+ const row = segmentId
575
+ ? this.db.prepare(`
576
+ SELECT * FROM events
577
+ WHERE session_id = ? AND segment_id = ? AND type = ?
578
+ ORDER BY commit_seq DESC LIMIT 1
579
+ `).get(sessionId, segmentId, type)
580
+ : this.db.prepare(`
581
+ SELECT * FROM events WHERE session_id = ? AND type = ? ORDER BY commit_seq DESC LIMIT 1
582
+ `).get(sessionId, type);
583
+ return row ? eventFromRow(row) : null;
584
+ }
585
+
586
+ highWaterCommitSeq(sessionId: string, segmentId?: string): number {
587
+ const row = segmentId
588
+ ? this.db.prepare('SELECT MAX(commit_seq) AS high_water FROM events WHERE session_id = ? AND segment_id = ?').get(sessionId, segmentId)
589
+ : this.db.prepare('SELECT MAX(commit_seq) AS high_water FROM events WHERE session_id = ?').get(sessionId);
590
+ return numberValue(row?.high_water);
591
+ }
592
+
593
+ listCommittedEvents(filter: CommittedEventListFilter): CanonicalEvent[] {
594
+ const clauses = ['session_id = ?'];
595
+ const params: unknown[] = [filter.sessionId];
596
+ if (filter.segmentId) {
597
+ clauses.push('segment_id = ?');
598
+ params.push(filter.segmentId);
599
+ }
600
+ if (filter.types?.length) {
601
+ clauses.push(`type IN (${filter.types.map(() => '?').join(', ')})`);
602
+ params.push(...filter.types);
603
+ }
604
+ if (filter.epochSeq !== undefined) {
605
+ clauses.push('epoch_seq = ?');
606
+ params.push(filter.epochSeq);
607
+ }
608
+ if (filter.afterCommitSeq !== undefined) {
609
+ clauses.push('commit_seq > ?');
610
+ params.push(filter.afterCommitSeq);
611
+ }
612
+ if (filter.maxCommitSeq !== undefined) {
613
+ clauses.push('commit_seq <= ?');
614
+ params.push(filter.maxCommitSeq);
615
+ }
616
+ if (filter.maxEpochSeq !== undefined) {
617
+ clauses.push('(epoch_seq IS NULL OR epoch_seq <= ?)');
618
+ params.push(filter.maxEpochSeq);
619
+ }
620
+ const order = filter.order === 'desc' ? 'DESC' : 'ASC';
621
+ const limit = filter.limit === undefined
622
+ ? ''
623
+ : ' LIMIT ?';
624
+ if (filter.limit !== undefined) params.push(Math.max(0, Math.trunc(filter.limit)));
625
+ return this.db.prepare(`
626
+ SELECT * FROM events
627
+ WHERE ${clauses.join(' AND ')}
628
+ ORDER BY commit_seq ${order}${limit}
629
+ `).all(...params).map((row) => eventFromRow(row));
630
+ }
631
+
632
+ ensureDeliveries(sessionId: string, consumerId: string): void {
633
+ this.db.prepare(`
634
+ INSERT OR IGNORE INTO event_deliveries(
635
+ event_id, consumer_id, monitor_state, detail_state
636
+ )
637
+ SELECT
638
+ event_id,
639
+ ?,
640
+ CASE
641
+ WHEN delivery_class <> 'monitor_and_events' THEN 'not_applicable'
642
+ WHEN p.is_current = 1 THEN 'pending'
643
+ ELSE 'suppressed'
644
+ END,
645
+ CASE
646
+ WHEN delivery_class = 'internal_only' THEN 'not_applicable'
647
+ WHEN p.is_current = 1 AND s.is_current = 1 THEN 'pending'
648
+ ELSE 'deferred'
649
+ END
650
+ FROM events e
651
+ JOIN event_segments s ON s.segment_id = e.segment_id
652
+ JOIN play_sessions p ON p.session_id = e.session_id
653
+ WHERE e.session_id = ?
654
+ `).run(consumerId, sessionId);
655
+ }
656
+
657
+ delivery(eventId: string, consumerId: string): EventDeliveryRecord | null {
658
+ const event = this.eventById(eventId);
659
+ if (!event) return null;
660
+ this.insertInitialDelivery(event, consumerId);
661
+ const row = this.db.prepare(`
662
+ SELECT * FROM event_deliveries WHERE event_id = ? AND consumer_id = ?
663
+ `).get(eventId, consumerId);
664
+ return row ? deliveryFromRow(row) : null;
665
+ }
666
+
667
+ listEvents(filter: EventListFilter, consumerId: string): EventWithDelivery[] {
668
+ this.ensureDeliveries(filter.sessionId, consumerId);
669
+ const clauses = ['e.session_id = ?', 'd.consumer_id = ?'];
670
+ const params: unknown[] = [filter.sessionId, consumerId];
671
+ if (filter.segmentId) {
672
+ clauses.push('e.segment_id = ?');
673
+ params.push(filter.segmentId);
674
+ }
675
+ if (filter.excludeSegmentId) {
676
+ clauses.push('e.segment_id <> ?');
677
+ params.push(filter.excludeSegmentId);
678
+ }
679
+ this.addInFilter(clauses, params, 'e.type', filter.types);
680
+ this.addInFilter(clauses, params, 'e.delivery_class', filter.deliveryClasses);
681
+ this.addInFilter(clauses, params, 'd.detail_state', filter.detailStates);
682
+ this.addInFilter(clauses, params, 'd.monitor_state', filter.monitorStates);
683
+ if (filter.maxCommitSeq !== undefined) {
684
+ clauses.push('e.commit_seq <= ?');
685
+ params.push(filter.maxCommitSeq);
686
+ }
687
+ if (filter.maxEpochSeq !== undefined) {
688
+ clauses.push('(e.epoch_seq IS NULL OR e.epoch_seq <= ?)');
689
+ params.push(filter.maxEpochSeq);
690
+ }
691
+ const order = filter.order === 'desc' ? 'DESC' : 'ASC';
692
+ const rows = this.db.prepare(`
693
+ SELECT
694
+ e.*,
695
+ d.consumer_id,
696
+ d.monitor_state,
697
+ d.monitor_attempt_count,
698
+ d.monitor_last_attempt_at,
699
+ d.monitor_delivered_at,
700
+ d.detail_state,
701
+ d.detail_delivered_at,
702
+ d.detail_delivery_via
703
+ FROM events e
704
+ JOIN event_deliveries d ON d.event_id = e.event_id
705
+ WHERE ${clauses.join(' AND ')}
706
+ ORDER BY e.commit_seq ${order}
707
+ `).all(...params);
708
+ return rows.map((row) => ({ event: eventFromRow(row), delivery: deliveryFromRow(row) }));
709
+ }
710
+
711
+ backlogSummary(sessionId: string, consumerId: string): BacklogSummary {
712
+ const rows = this.listEvents({ sessionId, detailStates: ['deferred'], order: 'asc' }, consumerId);
713
+ return {
714
+ unreadCount: rows.length,
715
+ segmentCount: new Set(rows.map((row) => row.event.segmentId)).size,
716
+ oldestAt: rows[0]?.event.occurredAt,
717
+ newestAt: rows.at(-1)?.event.occurredAt,
718
+ available: rows.length > 0,
719
+ };
720
+ }
721
+
722
+ transitionDetails(transition: DetailStateTransition): number {
723
+ this.assertLeaseIfPresent(transition.lease, transition.nowMs);
724
+ if (transition.eventIds.length === 0 || transition.from.length === 0) return 0;
725
+ if (transition.to === 'delivered' && (!transition.deliveredAt || !transition.deliveryVia)) {
726
+ throw new Error('Delivered event details require deliveredAt and deliveryVia.');
727
+ }
728
+ const params: unknown[] = [
729
+ transition.to,
730
+ transition.to === 'delivered' ? transition.deliveredAt : null,
731
+ transition.to === 'delivered' ? transition.deliveryVia : null,
732
+ transition.consumerId,
733
+ ...transition.eventIds,
734
+ ...transition.from,
735
+ ];
736
+ const result = this.db.prepare(`
737
+ UPDATE event_deliveries
738
+ SET detail_state = ?, detail_delivered_at = ?, detail_delivery_via = ?
739
+ WHERE consumer_id = ?
740
+ AND event_id IN (${placeholders(transition.eventIds.length)})
741
+ AND detail_state IN (${placeholders(transition.from.length)})
742
+ `).run(...params);
743
+ return numberValue(result.changes);
744
+ }
745
+
746
+ transitionMonitor(transition: MonitorStateTransition): number {
747
+ this.assertLeaseIfPresent(transition.lease, transition.nowMs);
748
+ if (transition.eventIds.length === 0 || transition.from.length === 0) return 0;
749
+ if (transition.to === 'notified' && !transition.deliveredAt) {
750
+ throw new Error('Notified Monitor events require deliveredAt.');
751
+ }
752
+ const params: unknown[] = [
753
+ transition.to,
754
+ transition.to === 'notified' ? transition.deliveredAt : null,
755
+ transition.consumerId,
756
+ ...transition.eventIds,
757
+ ...transition.from,
758
+ ];
759
+ const result = this.db.prepare(`
760
+ UPDATE event_deliveries
761
+ SET monitor_state = ?, monitor_delivered_at = ?
762
+ WHERE consumer_id = ?
763
+ AND event_id IN (${placeholders(transition.eventIds.length)})
764
+ AND monitor_state IN (${placeholders(transition.from.length)})
765
+ `).run(...params);
766
+ return numberValue(result.changes);
767
+ }
768
+
769
+ recordMonitorAttempt(attempt: MonitorDeliveryAttempt): boolean {
770
+ this.assertLeaseIfPresent(attempt.lease, attempt.nowMs);
771
+ const result = this.db.prepare(`
772
+ UPDATE event_deliveries
773
+ SET monitor_attempt_count = monitor_attempt_count + 1,
774
+ monitor_last_attempt_at = ?
775
+ WHERE event_id = ?
776
+ AND consumer_id = ?
777
+ AND monitor_state = 'pending'
778
+ `).run(attempt.attemptedAt, attempt.eventId, attempt.consumerId);
779
+ return numberValue(result.changes) === 1;
780
+ }
781
+
782
+ acquireLease(request: AcquireLeaseRequest): ConsumerLease | null {
783
+ const nowMs = request.nowMs ?? Date.now();
784
+ return this.transaction(() => {
785
+ const row = this.db.prepare(`
786
+ SELECT * FROM consumer_leases WHERE consumer_id = ? AND channel = ?
787
+ `).get(request.consumerId, request.channel);
788
+ if (row && numberValue(row.expires_at) > nowMs && row.owner_id !== request.ownerId) return null;
789
+ const lease: ConsumerLease = {
790
+ consumerId: request.consumerId,
791
+ channel: request.channel,
792
+ ownerId: request.ownerId,
793
+ expiresAt: nowMs + Math.max(1, request.ttlMs),
794
+ };
795
+ this.db.prepare(`
796
+ INSERT INTO consumer_leases(consumer_id, channel, owner_id, expires_at)
797
+ VALUES (?, ?, ?, ?)
798
+ ON CONFLICT(consumer_id, channel) DO UPDATE SET
799
+ owner_id = excluded.owner_id,
800
+ expires_at = excluded.expires_at
801
+ `).run(lease.consumerId, lease.channel, lease.ownerId, lease.expiresAt);
802
+ return lease;
803
+ });
804
+ }
805
+
806
+ leaseIsValid(lease: ConsumerLease, nowMs = Date.now()): boolean {
807
+ const row = this.db.prepare(`
808
+ SELECT owner_id, expires_at FROM consumer_leases WHERE consumer_id = ? AND channel = ?
809
+ `).get(lease.consumerId, lease.channel);
810
+ return !!row && row.owner_id === lease.ownerId && numberValue(row.expires_at) > nowMs;
811
+ }
812
+
813
+ releaseLease(lease: ConsumerLease): boolean {
814
+ const result = this.db.prepare(`
815
+ DELETE FROM consumer_leases WHERE consumer_id = ? AND channel = ? AND owner_id = ?
816
+ `).run(lease.consumerId, lease.channel, lease.ownerId);
817
+ return numberValue(result.changes) === 1;
818
+ }
819
+
820
+ enqueueMailboxItem<T = unknown>(request: EnqueueMailboxItem<T>): EnqueueMailboxResult<T> {
821
+ return this.transaction(() => {
822
+ const existing = this.db.prepare(`
823
+ SELECT * FROM mailbox_items
824
+ WHERE consumer_id = ? AND event_id = ? AND mode = ?
825
+ LIMIT 1
826
+ `).get(request.consumerId, request.eventId, request.mode);
827
+ if (existing) return { inserted: false, item: mailboxItemFromRow<T>(existing) };
828
+ if (this.db.prepare('SELECT item_id FROM mailbox_items WHERE item_id = ?').get(request.itemId)) {
829
+ throw new Error(`Mailbox item ID already exists: ${request.itemId}`);
830
+ }
831
+
832
+ const event = this.eventById(request.eventId);
833
+ if (!event) throw new Error(`Unknown Mailbox event: ${request.eventId}`);
834
+ if (
835
+ event.sessionId !== request.sessionId
836
+ || event.segmentId !== request.segmentId
837
+ || event.commitSeq !== request.eventCommitSeq
838
+ ) {
839
+ throw new Error(`Mailbox scope does not match Event ${request.eventId}.`);
840
+ }
841
+ if (event.deliveryClass !== 'monitor_and_events') {
842
+ throw new Error(`Short Mailbox delivery is not applicable to Event ${request.eventId}.`);
843
+ }
844
+
845
+ const createdAt = request.createdAt ?? new Date().toISOString();
846
+ const state = this.mailboxSessionIsCurrent(request.sessionId, request.segmentId)
847
+ ? 'pending'
848
+ : 'suppressed';
849
+ this.insertInitialDelivery(event, request.consumerId);
850
+ this.db.prepare(`
851
+ INSERT INTO mailbox_items(
852
+ item_id, schema_version, formatter_version, consumer_id, session_id,
853
+ segment_id, event_id, event_commit_seq, mode, coalesce_key,
854
+ payload_json, state, attempt_count, available_at, created_at, updated_at
855
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?)
856
+ `).run(
857
+ request.itemId,
858
+ request.schemaVersion ?? 1,
859
+ request.formatterVersion,
860
+ request.consumerId,
861
+ request.sessionId,
862
+ request.segmentId,
863
+ request.eventId,
864
+ request.eventCommitSeq,
865
+ request.mode,
866
+ request.coalesceKey,
867
+ JSON.stringify(request.payload) ?? 'null',
868
+ state,
869
+ request.availableAtMs ?? 0,
870
+ createdAt,
871
+ createdAt,
872
+ );
873
+ const inserted = this.db.prepare('SELECT * FROM mailbox_items WHERE item_id = ?')
874
+ .get(request.itemId);
875
+ if (!inserted) throw new Error(`Unable to read inserted Mailbox item ${request.itemId}.`);
876
+ return { inserted: true, item: mailboxItemFromRow<T>(inserted) };
877
+ });
878
+ }
879
+
880
+ mailboxItem<T = unknown>(itemId: string): MailboxItem<T> | null {
881
+ const row = this.db.prepare('SELECT * FROM mailbox_items WHERE item_id = ?').get(itemId);
882
+ return row ? mailboxItemFromRow<T>(row) : null;
883
+ }
884
+
885
+ mailboxItemForEvent<T = unknown>(
886
+ consumerId: string,
887
+ eventId: string,
888
+ mode: MailboxDeliveryMode,
889
+ ): MailboxItem<T> | null {
890
+ const row = this.db.prepare(`
891
+ SELECT * FROM mailbox_items
892
+ WHERE consumer_id = ? AND event_id = ? AND mode = ?
893
+ LIMIT 1
894
+ `).get(consumerId, eventId, mode);
895
+ return row ? mailboxItemFromRow<T>(row) : null;
896
+ }
897
+
898
+ peekMailbox<T = unknown>(filter: MailboxPeekFilter): MailboxItem<T>[] {
899
+ const clauses = ['consumer_id = ?'];
900
+ const params: unknown[] = [filter.consumerId];
901
+ if (filter.sessionId) {
902
+ clauses.push('session_id = ?');
903
+ params.push(filter.sessionId);
904
+ }
905
+ if (filter.segmentId) {
906
+ clauses.push('segment_id = ?');
907
+ params.push(filter.segmentId);
908
+ }
909
+ this.addInFilter(clauses, params, 'event_id', filter.eventIds);
910
+ this.addInFilter(clauses, params, 'mode', filter.modes);
911
+ this.addInFilter(clauses, params, 'state', filter.states);
912
+ const order = filter.order === 'desc' ? 'DESC' : 'ASC';
913
+ const limit = filter.limit === undefined ? '' : ' LIMIT ?';
914
+ if (filter.limit !== undefined) params.push(Math.max(0, Math.trunc(filter.limit)));
915
+ return this.db.prepare(`
916
+ SELECT * FROM mailbox_items
917
+ WHERE ${clauses.join(' AND ')}
918
+ ORDER BY event_commit_seq ${order}, item_id ${order}${limit}
919
+ `).all(...params).map((row) => mailboxItemFromRow<T>(row));
920
+ }
921
+
922
+ claimMailbox<T = unknown>(request: ClaimMailboxItemsRequest): MailboxClaim<T> | null {
923
+ const nowMs = request.nowMs ?? Date.now();
924
+ return this.transaction(() => {
925
+ this.suppressExpiredMailboxClaimsOutsideCurrentSession(request.consumerId, nowMs);
926
+ if (!this.mailboxSessionIsCurrent(request.sessionId, request.segmentId)) return null;
927
+
928
+ const rawRows = this.db.prepare(`
929
+ SELECT m.*, d.monitor_state, d.detail_state
930
+ FROM mailbox_items m
931
+ JOIN event_deliveries d
932
+ ON d.event_id = m.event_id AND d.consumer_id = m.consumer_id
933
+ WHERE m.consumer_id = ?
934
+ AND m.session_id = ?
935
+ AND m.segment_id = ?
936
+ AND m.mode = ?
937
+ AND m.state IN ('pending', 'claimed')
938
+ ORDER BY m.event_commit_seq ASC, m.item_id ASC
939
+ `).all(request.consumerId, request.sessionId, request.segmentId, request.mode);
940
+
941
+ const activeRows: Array<Record<string, unknown>> = [];
942
+ const reconciledAt = new Date(nowMs).toISOString();
943
+ for (const row of rawRows) {
944
+ const state = String(row.state);
945
+ const expired = state === 'claimed' && numberValue(row.claim_expires_at) <= nowMs;
946
+ const matchesDelivery = request.mode === 'short'
947
+ ? row.monitor_state === 'pending'
948
+ : row.detail_state === 'pending' || row.detail_state === 'deferred';
949
+ if ((state === 'pending' || expired) && !matchesDelivery) {
950
+ this.db.prepare(`
951
+ UPDATE mailbox_items
952
+ SET state = 'suppressed', claim_owner = NULL, claim_token = NULL,
953
+ claim_expires_at = NULL, updated_at = ?
954
+ WHERE item_id = ?
955
+ `).run(reconciledAt, row.item_id);
956
+ continue;
957
+ }
958
+ activeRows.push(row);
959
+ }
960
+
961
+ const first = activeRows[0];
962
+ if (!first || !this.sqliteMailboxRowIsClaimable(first, nowMs)) return null;
963
+ const maxItems = Math.max(1, Math.trunc(request.maxItems ?? 1));
964
+ const selected: Array<Record<string, unknown>> = [];
965
+ for (const row of activeRows) {
966
+ if (selected.length >= maxItems) break;
967
+ if (
968
+ row.coalesce_key !== first.coalesce_key
969
+ || row.formatter_version !== first.formatter_version
970
+ || !this.sqliteMailboxRowIsClaimable(row, nowMs)
971
+ ) break;
972
+ selected.push(row);
973
+ }
974
+ const itemIds = selected.map((row) => String(row.item_id));
975
+ const eventIds = selected.map((row) => String(row.event_id));
976
+ const claimToken = randomUUID();
977
+ const claimExpiresAtMs = nowMs + Math.max(1, request.leaseTtlMs);
978
+ const attemptedAt = new Date(nowMs).toISOString();
979
+ this.db.prepare(`
980
+ UPDATE mailbox_items
981
+ SET state = 'claimed', attempt_count = attempt_count + 1,
982
+ last_attempt_at = ?, claim_owner = ?, claim_token = ?,
983
+ claim_expires_at = ?, updated_at = ?
984
+ WHERE item_id IN (${placeholders(itemIds.length)})
985
+ `).run(
986
+ attemptedAt,
987
+ request.ownerId,
988
+ claimToken,
989
+ claimExpiresAtMs,
990
+ attemptedAt,
991
+ ...itemIds,
992
+ );
993
+ this.db.prepare(`
994
+ UPDATE event_deliveries
995
+ SET monitor_attempt_count = monitor_attempt_count + 1,
996
+ monitor_last_attempt_at = ?
997
+ WHERE consumer_id = ?
998
+ AND monitor_state = 'pending'
999
+ AND event_id IN (${placeholders(eventIds.length)})
1000
+ `).run(attemptedAt, request.consumerId, ...eventIds);
1001
+ const claimedRows = this.db.prepare(`
1002
+ SELECT * FROM mailbox_items
1003
+ WHERE item_id IN (${placeholders(itemIds.length)})
1004
+ ORDER BY event_commit_seq ASC, item_id ASC
1005
+ `).all(...itemIds);
1006
+ return {
1007
+ ownerId: request.ownerId,
1008
+ claimToken,
1009
+ claimExpiresAtMs,
1010
+ items: claimedRows.map((row) => mailboxItemFromRow<T>(row)),
1011
+ };
1012
+ });
1013
+ }
1014
+
1015
+ ackMailboxClaim(request: AckMailboxClaimRequest): AckMailboxClaimResult {
1016
+ const nowMs = request.nowMs ?? Date.now();
1017
+ return this.transaction(() => {
1018
+ const rows = this.db.prepare(`
1019
+ SELECT * FROM mailbox_items
1020
+ WHERE claim_owner = ? AND claim_token = ?
1021
+ ORDER BY event_commit_seq ASC, item_id ASC
1022
+ `).all(request.ownerId, request.claimToken);
1023
+ if (rows.length === 0) return { status: 'claim_lost', itemIds: [], eventIds: [] };
1024
+ const itemIds = rows.map((row) => String(row.item_id));
1025
+ const eventIds = rows.map((row) => String(row.event_id));
1026
+ if (rows.every((row) => row.state === 'accepted')) {
1027
+ return { status: 'already_accepted', itemIds, eventIds };
1028
+ }
1029
+ if (
1030
+ rows.some((row) => row.state !== 'claimed')
1031
+ || rows.some((row) => numberValue(row.claim_expires_at) <= nowMs)
1032
+ ) {
1033
+ return { status: 'claim_lost', itemIds: [], eventIds: [] };
1034
+ }
1035
+
1036
+ const acceptedAt = request.acceptedAt ?? new Date(nowMs).toISOString();
1037
+ const acceptanceLevel = request.acceptanceLevel ?? 'sink_emitted';
1038
+ const updatedAt = new Date(nowMs).toISOString();
1039
+ this.db.prepare(`
1040
+ UPDATE mailbox_items
1041
+ SET state = 'accepted', accepted_at = ?, acceptance_level = ?,
1042
+ receipt_id = ?, last_error_code = NULL, updated_at = ?
1043
+ WHERE item_id IN (${placeholders(itemIds.length)})
1044
+ `).run(acceptedAt, acceptanceLevel, request.receiptId ?? null, updatedAt, ...itemIds);
1045
+
1046
+ const consumerId = String(rows[0].consumer_id);
1047
+ this.db.prepare(`
1048
+ UPDATE event_deliveries
1049
+ SET monitor_state = 'notified', monitor_delivered_at = ?
1050
+ WHERE consumer_id = ?
1051
+ AND monitor_state = 'pending'
1052
+ AND event_id IN (${placeholders(eventIds.length)})
1053
+ `).run(acceptedAt, consumerId, ...eventIds);
1054
+ return { status: 'accepted', itemIds, eventIds };
1055
+ });
1056
+ }
1057
+
1058
+ nackMailboxClaim(request: NackMailboxClaimRequest): NackMailboxClaimResult {
1059
+ const nowMs = request.nowMs ?? Date.now();
1060
+ return this.transaction(() => {
1061
+ const rows = this.db.prepare(`
1062
+ SELECT * FROM mailbox_items
1063
+ WHERE claim_owner = ? AND claim_token = ? AND state = 'claimed'
1064
+ ORDER BY event_commit_seq ASC, item_id ASC
1065
+ `).all(request.ownerId, request.claimToken);
1066
+ if (
1067
+ rows.length === 0
1068
+ || rows.some((row) => numberValue(row.claim_expires_at) <= nowMs)
1069
+ ) return { status: 'claim_lost', itemIds: [] };
1070
+ const remainsCurrent = rows.every((row) => this.mailboxSessionIsCurrent(
1071
+ String(row.session_id),
1072
+ String(row.segment_id),
1073
+ ));
1074
+ const itemIds = rows.map((row) => String(row.item_id));
1075
+ const updatedAt = new Date(nowMs).toISOString();
1076
+ this.db.prepare(`
1077
+ UPDATE mailbox_items
1078
+ SET state = ?, available_at = ?, claim_owner = NULL,
1079
+ claim_token = NULL, claim_expires_at = NULL,
1080
+ last_error_code = ?, updated_at = ?
1081
+ WHERE item_id IN (${placeholders(itemIds.length)})
1082
+ `).run(
1083
+ remainsCurrent ? 'pending' : 'suppressed',
1084
+ request.retryAtMs,
1085
+ request.errorCode ?? null,
1086
+ updatedAt,
1087
+ ...itemIds,
1088
+ );
1089
+ if (!remainsCurrent) {
1090
+ for (const row of rows) this.suppressMailboxEventDeliveryRow(row, true);
1091
+ }
1092
+ return {
1093
+ status: remainsCurrent ? 'released' : 'suppressed',
1094
+ itemIds,
1095
+ };
1096
+ });
1097
+ }
1098
+
1099
+ suppressMailboxItems(filter: SuppressMailboxItemsFilter): number {
1100
+ const nowMs = filter.nowMs ?? Date.now();
1101
+ return this.transaction(() => {
1102
+ const clauses = ['consumer_id = ?'];
1103
+ const params: unknown[] = [filter.consumerId];
1104
+ if (filter.sessionId) {
1105
+ clauses.push('session_id = ?');
1106
+ params.push(filter.sessionId);
1107
+ }
1108
+ if (filter.segmentId) {
1109
+ clauses.push('segment_id = ?');
1110
+ params.push(filter.segmentId);
1111
+ }
1112
+ if (filter.excludeSegmentId) {
1113
+ clauses.push('segment_id <> ?');
1114
+ params.push(filter.excludeSegmentId);
1115
+ }
1116
+ this.addInFilter(clauses, params, 'event_id', filter.eventIds);
1117
+ this.addInFilter(clauses, params, 'mode', filter.modes);
1118
+ if (filter.includeExpiredClaims) {
1119
+ clauses.push(`(state = 'pending' OR (state = 'claimed' AND claim_expires_at <= ?))`);
1120
+ params.push(nowMs);
1121
+ } else {
1122
+ clauses.push(`state = 'pending'`);
1123
+ }
1124
+ const rows = this.db.prepare(`
1125
+ SELECT * FROM mailbox_items WHERE ${clauses.join(' AND ')}
1126
+ `).all(...params);
1127
+ if (rows.length === 0) return 0;
1128
+ const itemIds = rows.map((row) => String(row.item_id));
1129
+ const updatedAt = new Date(nowMs).toISOString();
1130
+ this.db.prepare(`
1131
+ UPDATE mailbox_items
1132
+ SET state = 'suppressed', claim_owner = NULL, claim_token = NULL,
1133
+ claim_expires_at = NULL, updated_at = ?
1134
+ WHERE item_id IN (${placeholders(itemIds.length)})
1135
+ `).run(updatedAt, ...itemIds);
1136
+ for (const row of rows) {
1137
+ const deferDetails = !this.deliveryScopeIsCurrent(
1138
+ String(row.session_id),
1139
+ String(row.segment_id),
1140
+ );
1141
+ this.suppressMailboxEventDeliveryRow(row, deferDetails);
1142
+ }
1143
+ return rows.length;
1144
+ });
1145
+ }
1146
+
1147
+ sourceCheckpoint(sourceId: string): SourceCheckpointRecord | null {
1148
+ const row = this.db.prepare('SELECT * FROM source_checkpoints WHERE source_id = ?').get(sourceId);
1149
+ return row ? checkpointFromRow(row) : null;
1150
+ }
1151
+
1152
+ private configure(): void {
1153
+ this.db.exec('PRAGMA foreign_keys = ON');
1154
+ this.db.exec('PRAGMA busy_timeout = 5000');
1155
+ this.db.exec('PRAGMA journal_mode = WAL');
1156
+ this.db.exec('PRAGMA synchronous = FULL');
1157
+ }
1158
+
1159
+ private migrate(): void {
1160
+ this.db.exec(`
1161
+ CREATE TABLE IF NOT EXISTS schema_migrations(
1162
+ version INTEGER PRIMARY KEY,
1163
+ applied_at TEXT NOT NULL
1164
+ );
1165
+
1166
+ CREATE TABLE IF NOT EXISTS play_sessions(
1167
+ session_id TEXT PRIMARY KEY,
1168
+ adapter_id TEXT NOT NULL,
1169
+ account_id TEXT NOT NULL,
1170
+ resume_key TEXT,
1171
+ mode TEXT,
1172
+ status TEXT NOT NULL CHECK(status IN ('open', 'sealed')),
1173
+ is_current INTEGER NOT NULL DEFAULT 0 CHECK(is_current IN (0, 1)),
1174
+ opened_at TEXT NOT NULL,
1175
+ sealed_at TEXT
1176
+ );
1177
+ CREATE UNIQUE INDEX IF NOT EXISTS one_current_session_per_account
1178
+ ON play_sessions(adapter_id, account_id) WHERE is_current = 1;
1179
+ CREATE INDEX IF NOT EXISTS sessions_by_resume_key
1180
+ ON play_sessions(adapter_id, account_id, resume_key);
1181
+
1182
+ CREATE TABLE IF NOT EXISTS event_segments(
1183
+ segment_id TEXT PRIMARY KEY,
1184
+ session_id TEXT NOT NULL REFERENCES play_sessions(session_id),
1185
+ segment_seq INTEGER NOT NULL,
1186
+ kind TEXT NOT NULL,
1187
+ scope_ref TEXT,
1188
+ status TEXT NOT NULL CHECK(status IN ('open', 'closed')),
1189
+ is_current INTEGER NOT NULL DEFAULT 0 CHECK(is_current IN (0, 1)),
1190
+ opened_at TEXT NOT NULL,
1191
+ closed_at TEXT,
1192
+ UNIQUE(session_id, segment_seq)
1193
+ );
1194
+ CREATE UNIQUE INDEX IF NOT EXISTS one_current_segment_per_session
1195
+ ON event_segments(session_id) WHERE is_current = 1;
1196
+
1197
+ CREATE TABLE IF NOT EXISTS events(
1198
+ commit_seq INTEGER PRIMARY KEY AUTOINCREMENT,
1199
+ event_id TEXT NOT NULL UNIQUE,
1200
+ epoch_seq INTEGER,
1201
+ session_id TEXT NOT NULL REFERENCES play_sessions(session_id),
1202
+ segment_id TEXT NOT NULL REFERENCES event_segments(segment_id),
1203
+ type TEXT NOT NULL,
1204
+ producer TEXT NOT NULL CHECK(producer IN ('backend_push', 'local_synth')),
1205
+ producer_plugin_id TEXT,
1206
+ producer_output_index INTEGER,
1207
+ delivery_class TEXT NOT NULL CHECK(delivery_class IN ('monitor_and_events', 'events_only', 'internal_only')),
1208
+ occurred_at TEXT NOT NULL,
1209
+ received_at TEXT NOT NULL,
1210
+ payload_json TEXT NOT NULL,
1211
+ source_id TEXT NOT NULL,
1212
+ source_event_id TEXT,
1213
+ source_sequence TEXT,
1214
+ connection_id TEXT,
1215
+ replayed INTEGER NOT NULL DEFAULT 0 CHECK(replayed IN (0, 1))
1216
+ );
1217
+ CREATE UNIQUE INDEX IF NOT EXISTS events_by_remote_id
1218
+ ON events(source_id, source_event_id) WHERE source_event_id IS NOT NULL;
1219
+ CREATE INDEX IF NOT EXISTS events_by_scope
1220
+ ON events(session_id, segment_id, commit_seq);
1221
+ CREATE INDEX IF NOT EXISTS events_by_type
1222
+ ON events(session_id, type, commit_seq DESC);
1223
+
1224
+ CREATE TABLE IF NOT EXISTS event_deliveries(
1225
+ event_id TEXT NOT NULL REFERENCES events(event_id),
1226
+ consumer_id TEXT NOT NULL,
1227
+ monitor_state TEXT NOT NULL CHECK(monitor_state IN ('not_applicable', 'pending', 'notified', 'suppressed')),
1228
+ monitor_attempt_count INTEGER NOT NULL DEFAULT 0 CHECK(monitor_attempt_count >= 0),
1229
+ monitor_last_attempt_at TEXT,
1230
+ monitor_delivered_at TEXT,
1231
+ detail_state TEXT NOT NULL CHECK(detail_state IN ('not_applicable', 'pending', 'deferred', 'delivered')),
1232
+ detail_delivered_at TEXT,
1233
+ detail_delivery_via TEXT CHECK(detail_delivery_via IS NULL OR detail_delivery_via IN ('stdout_full', 'mailbox_full', 'ccl_events', 'ccl_events_backlog')),
1234
+ PRIMARY KEY(event_id, consumer_id),
1235
+ CHECK(
1236
+ (detail_state = 'delivered' AND detail_delivered_at IS NOT NULL AND detail_delivery_via IS NOT NULL)
1237
+ OR
1238
+ (detail_state <> 'delivered' AND detail_delivered_at IS NULL AND detail_delivery_via IS NULL)
1239
+ )
1240
+ );
1241
+ CREATE INDEX IF NOT EXISTS pending_details
1242
+ ON event_deliveries(consumer_id, detail_state, event_id);
1243
+
1244
+ CREATE TABLE IF NOT EXISTS source_checkpoints(
1245
+ source_id TEXT PRIMARY KEY,
1246
+ checkpoint TEXT NOT NULL,
1247
+ source_sequence TEXT,
1248
+ event_id TEXT NOT NULL REFERENCES events(event_id),
1249
+ committed_at TEXT NOT NULL
1250
+ );
1251
+
1252
+ CREATE TABLE IF NOT EXISTS consumer_leases(
1253
+ consumer_id TEXT NOT NULL,
1254
+ channel TEXT NOT NULL CHECK(channel IN ('monitor', 'details')),
1255
+ owner_id TEXT NOT NULL,
1256
+ expires_at INTEGER NOT NULL,
1257
+ PRIMARY KEY(consumer_id, channel)
1258
+ );
1259
+ `);
1260
+ this.db.prepare(`
1261
+ INSERT OR IGNORE INTO schema_migrations(version, applied_at) VALUES (1, ?)
1262
+ `).run(new Date().toISOString());
1263
+
1264
+ const sequenceScopeMigration = this.db.prepare(`
1265
+ SELECT version FROM schema_migrations WHERE version = 2
1266
+ `).get();
1267
+ if (!sequenceScopeMigration) {
1268
+ this.transaction(() => {
1269
+ // Version 1 treated source sequence as globally unique for a source.
1270
+ // Many transports restart their sequence each connection/game, so the
1271
+ // durable identity must include the logical event scope.
1272
+ this.db.exec('DROP INDEX IF EXISTS events_by_remote_sequence');
1273
+ this.db.exec(`
1274
+ CREATE UNIQUE INDEX events_by_remote_sequence
1275
+ ON events(source_id, session_id, segment_id, source_sequence)
1276
+ WHERE source_sequence IS NOT NULL
1277
+ `);
1278
+ this.db.prepare(`
1279
+ INSERT INTO schema_migrations(version, applied_at) VALUES (2, ?)
1280
+ `).run(new Date().toISOString());
1281
+ });
1282
+ }
1283
+
1284
+ const monitorAttemptMigration = this.db.prepare(`
1285
+ SELECT version FROM schema_migrations WHERE version = 4
1286
+ `).get();
1287
+ if (!monitorAttemptMigration) {
1288
+ this.transaction(() => {
1289
+ const columns = new Set(
1290
+ this.db.prepare('PRAGMA table_info(event_deliveries)')
1291
+ .all()
1292
+ .map((row) => String(row.name)),
1293
+ );
1294
+ if (!columns.has('monitor_attempt_count')) {
1295
+ this.db.exec(`
1296
+ ALTER TABLE event_deliveries
1297
+ ADD COLUMN monitor_attempt_count INTEGER NOT NULL DEFAULT 0
1298
+ CHECK(monitor_attempt_count >= 0)
1299
+ `);
1300
+ }
1301
+ if (!columns.has('monitor_last_attempt_at')) {
1302
+ this.db.exec(`
1303
+ ALTER TABLE event_deliveries
1304
+ ADD COLUMN monitor_last_attempt_at TEXT
1305
+ `);
1306
+ }
1307
+ this.db.prepare(`
1308
+ INSERT INTO schema_migrations(version, applied_at) VALUES (4, ?)
1309
+ `).run(new Date().toISOString());
1310
+ });
1311
+ }
1312
+
1313
+ const mailboxMigration = this.db.prepare(`
1314
+ SELECT version FROM schema_migrations WHERE version = 5
1315
+ `).get();
1316
+ if (!mailboxMigration) {
1317
+ this.transaction(() => {
1318
+ const deliverySchema = this.db.prepare(`
1319
+ SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'event_deliveries'
1320
+ `).get();
1321
+ if (!String(deliverySchema?.sql ?? '').includes('mailbox_full')) {
1322
+ this.db.exec(`
1323
+ ALTER TABLE event_deliveries RENAME TO event_deliveries_v4;
1324
+ CREATE TABLE event_deliveries(
1325
+ event_id TEXT NOT NULL REFERENCES events(event_id),
1326
+ consumer_id TEXT NOT NULL,
1327
+ monitor_state TEXT NOT NULL CHECK(monitor_state IN ('not_applicable', 'pending', 'notified', 'suppressed')),
1328
+ monitor_attempt_count INTEGER NOT NULL DEFAULT 0 CHECK(monitor_attempt_count >= 0),
1329
+ monitor_last_attempt_at TEXT,
1330
+ monitor_delivered_at TEXT,
1331
+ detail_state TEXT NOT NULL CHECK(detail_state IN ('not_applicable', 'pending', 'deferred', 'delivered')),
1332
+ detail_delivered_at TEXT,
1333
+ detail_delivery_via TEXT CHECK(detail_delivery_via IS NULL OR detail_delivery_via IN ('stdout_full', 'mailbox_full', 'ccl_events', 'ccl_events_backlog')),
1334
+ PRIMARY KEY(event_id, consumer_id),
1335
+ CHECK(
1336
+ (detail_state = 'delivered' AND detail_delivered_at IS NOT NULL AND detail_delivery_via IS NOT NULL)
1337
+ OR
1338
+ (detail_state <> 'delivered' AND detail_delivered_at IS NULL AND detail_delivery_via IS NULL)
1339
+ )
1340
+ );
1341
+ INSERT INTO event_deliveries(
1342
+ event_id, consumer_id, monitor_state, monitor_attempt_count,
1343
+ monitor_last_attempt_at, monitor_delivered_at, detail_state,
1344
+ detail_delivered_at, detail_delivery_via
1345
+ )
1346
+ SELECT
1347
+ event_id, consumer_id, monitor_state, monitor_attempt_count,
1348
+ monitor_last_attempt_at, monitor_delivered_at, detail_state,
1349
+ detail_delivered_at, detail_delivery_via
1350
+ FROM event_deliveries_v4;
1351
+ DROP TABLE event_deliveries_v4;
1352
+ CREATE INDEX pending_details
1353
+ ON event_deliveries(consumer_id, detail_state, event_id);
1354
+ `);
1355
+ }
1356
+ this.db.exec(`
1357
+ CREATE TABLE IF NOT EXISTS mailbox_items(
1358
+ item_id TEXT PRIMARY KEY,
1359
+ schema_version INTEGER NOT NULL CHECK(schema_version >= 1),
1360
+ formatter_version TEXT NOT NULL,
1361
+ consumer_id TEXT NOT NULL,
1362
+ session_id TEXT NOT NULL REFERENCES play_sessions(session_id),
1363
+ segment_id TEXT NOT NULL REFERENCES event_segments(segment_id),
1364
+ event_id TEXT NOT NULL REFERENCES events(event_id),
1365
+ event_commit_seq INTEGER NOT NULL,
1366
+ mode TEXT NOT NULL CHECK(mode IN ('short', 'full')),
1367
+ coalesce_key TEXT NOT NULL,
1368
+ payload_json TEXT NOT NULL,
1369
+ state TEXT NOT NULL CHECK(state IN ('pending', 'claimed', 'accepted', 'suppressed')),
1370
+ attempt_count INTEGER NOT NULL DEFAULT 0 CHECK(attempt_count >= 0),
1371
+ available_at INTEGER NOT NULL DEFAULT 0,
1372
+ created_at TEXT NOT NULL,
1373
+ updated_at TEXT NOT NULL,
1374
+ last_attempt_at TEXT,
1375
+ claim_owner TEXT,
1376
+ claim_token TEXT,
1377
+ claim_expires_at INTEGER,
1378
+ accepted_at TEXT,
1379
+ acceptance_level TEXT CHECK(acceptance_level IS NULL OR acceptance_level IN ('sink_emitted', 'host_accepted')),
1380
+ receipt_id TEXT,
1381
+ last_error_code TEXT,
1382
+ UNIQUE(consumer_id, event_id, mode),
1383
+ CHECK(
1384
+ state <> 'claimed'
1385
+ OR (claim_owner IS NOT NULL AND claim_token IS NOT NULL AND claim_expires_at IS NOT NULL)
1386
+ ),
1387
+ CHECK(
1388
+ state <> 'accepted'
1389
+ OR (accepted_at IS NOT NULL AND acceptance_level IS NOT NULL)
1390
+ )
1391
+ );
1392
+ CREATE INDEX IF NOT EXISTS mailbox_fifo
1393
+ ON mailbox_items(
1394
+ consumer_id, session_id, segment_id, mode, event_commit_seq, item_id
1395
+ );
1396
+ CREATE INDEX IF NOT EXISTS mailbox_by_claim
1397
+ ON mailbox_items(claim_token, claim_owner, state);
1398
+ `);
1399
+ this.db.prepare(`
1400
+ INSERT INTO schema_migrations(version, applied_at) VALUES (5, ?)
1401
+ `).run(new Date().toISOString());
1402
+ });
1403
+ }
1404
+
1405
+ const epochMigration = this.db.prepare(`
1406
+ SELECT version FROM schema_migrations WHERE version = 6
1407
+ `).get();
1408
+ if (!epochMigration) {
1409
+ this.transaction(() => {
1410
+ const columns = new Set(
1411
+ this.db.prepare('PRAGMA table_info(events)')
1412
+ .all()
1413
+ .map((row) => String(row.name)),
1414
+ );
1415
+ if (!columns.has('epoch_seq')) {
1416
+ this.db.exec('ALTER TABLE events ADD COLUMN epoch_seq INTEGER');
1417
+ }
1418
+ this.db.exec(`
1419
+ CREATE INDEX IF NOT EXISTS events_by_epoch
1420
+ ON events(session_id, segment_id, epoch_seq, commit_seq)
1421
+ `);
1422
+ this.db.prepare(`
1423
+ INSERT INTO schema_migrations(version, applied_at) VALUES (6, ?)
1424
+ `).run(new Date().toISOString());
1425
+ });
1426
+ }
1427
+
1428
+ const pluginProducerMigration = this.db.prepare(`
1429
+ SELECT version FROM schema_migrations WHERE version = 7
1430
+ `).get();
1431
+ if (!pluginProducerMigration) {
1432
+ this.transaction(() => {
1433
+ const columns = new Set(
1434
+ this.db.prepare('PRAGMA table_info(events)')
1435
+ .all()
1436
+ .map((row) => String(row.name)),
1437
+ );
1438
+ if (!columns.has('producer_plugin_id')) {
1439
+ this.db.exec('ALTER TABLE events ADD COLUMN producer_plugin_id TEXT');
1440
+ }
1441
+ if (!columns.has('producer_output_index')) {
1442
+ this.db.exec('ALTER TABLE events ADD COLUMN producer_output_index INTEGER');
1443
+ }
1444
+ this.db.prepare(`
1445
+ INSERT INTO schema_migrations(version, applied_at) VALUES (7, ?)
1446
+ `).run(new Date().toISOString());
1447
+ });
1448
+ }
1449
+ }
1450
+
1451
+ private insertInitialDelivery(event: CanonicalEvent, consumerId: string): void {
1452
+ const delivery = initialDeliveryFor(event, consumerId);
1453
+ const scope = this.db.prepare(`
1454
+ SELECT s.is_current AS segment_is_current, p.is_current AS session_is_current
1455
+ FROM event_segments s
1456
+ JOIN play_sessions p ON p.session_id = s.session_id
1457
+ WHERE s.segment_id = ? AND s.session_id = ?
1458
+ `).get(event.segmentId, event.sessionId);
1459
+ if (
1460
+ delivery.detailState === 'pending'
1461
+ && (
1462
+ numberValue(scope?.session_is_current) !== 1
1463
+ || numberValue(scope?.segment_is_current) !== 1
1464
+ )
1465
+ ) {
1466
+ delivery.detailState = 'deferred';
1467
+ }
1468
+ if (
1469
+ delivery.monitorState === 'pending'
1470
+ && numberValue(scope?.session_is_current) !== 1
1471
+ ) {
1472
+ delivery.monitorState = 'suppressed';
1473
+ }
1474
+ this.db.prepare(`
1475
+ INSERT OR IGNORE INTO event_deliveries(
1476
+ event_id, consumer_id, monitor_state, monitor_delivered_at,
1477
+ detail_state, detail_delivered_at, detail_delivery_via
1478
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
1479
+ `).run(
1480
+ delivery.eventId,
1481
+ delivery.consumerId,
1482
+ delivery.monitorState,
1483
+ delivery.monitorDeliveredAt ?? null,
1484
+ delivery.detailState,
1485
+ delivery.detailDeliveredAt ?? null,
1486
+ delivery.detailDeliveryVia ?? null,
1487
+ );
1488
+ }
1489
+
1490
+ private upsertCheckpoint(checkpoint: SourceCheckpointRecord): void {
1491
+ this.db.prepare(`
1492
+ INSERT INTO source_checkpoints(source_id, checkpoint, source_sequence, event_id, committed_at)
1493
+ VALUES (?, ?, ?, ?, ?)
1494
+ ON CONFLICT(source_id) DO UPDATE SET
1495
+ checkpoint = excluded.checkpoint,
1496
+ source_sequence = excluded.source_sequence,
1497
+ event_id = excluded.event_id,
1498
+ committed_at = excluded.committed_at
1499
+ `).run(
1500
+ checkpoint.sourceId,
1501
+ checkpoint.checkpoint,
1502
+ checkpoint.sourceSequence ?? null,
1503
+ checkpoint.eventId,
1504
+ checkpoint.committedAt,
1505
+ );
1506
+ }
1507
+
1508
+ private findByRemoteId(sourceId: string, remoteEventId: string): CanonicalEvent | null {
1509
+ const row = this.db.prepare(`
1510
+ SELECT * FROM events WHERE source_id = ? AND source_event_id = ? LIMIT 1
1511
+ `).get(sourceId, remoteEventId);
1512
+ return row ? eventFromRow(row) : null;
1513
+ }
1514
+
1515
+ private findByRemoteSequence(
1516
+ sourceId: string,
1517
+ sessionId: string,
1518
+ segmentId: string,
1519
+ sequence: string,
1520
+ ): CanonicalEvent | null {
1521
+ const row = this.db.prepare(`
1522
+ SELECT * FROM events
1523
+ WHERE source_id = ?
1524
+ AND session_id = ?
1525
+ AND segment_id = ?
1526
+ AND source_sequence = ?
1527
+ LIMIT 1
1528
+ `).get(sourceId, sessionId, segmentId, sequence);
1529
+ return row ? eventFromRow(row) : null;
1530
+ }
1531
+
1532
+ private mailboxSessionIsCurrent(sessionId: string, segmentId: string): boolean {
1533
+ return !!this.db.prepare(`
1534
+ SELECT 1
1535
+ FROM play_sessions p
1536
+ JOIN event_segments s ON s.session_id = p.session_id
1537
+ WHERE p.session_id = ?
1538
+ AND p.is_current = 1
1539
+ AND s.segment_id = ?
1540
+ LIMIT 1
1541
+ `).get(sessionId, segmentId);
1542
+ }
1543
+
1544
+ private deliveryScopeIsCurrent(sessionId: string, segmentId: string): boolean {
1545
+ return !!this.db.prepare(`
1546
+ SELECT 1
1547
+ FROM play_sessions p
1548
+ JOIN event_segments s ON s.session_id = p.session_id
1549
+ WHERE p.session_id = ?
1550
+ AND p.is_current = 1
1551
+ AND s.segment_id = ?
1552
+ AND s.is_current = 1
1553
+ LIMIT 1
1554
+ `).get(sessionId, segmentId);
1555
+ }
1556
+
1557
+ private retireMailboxScope(
1558
+ column: 'session_id' | 'segment_id',
1559
+ value: string,
1560
+ updatedAt: string,
1561
+ ): void {
1562
+ this.db.prepare(`
1563
+ UPDATE mailbox_items
1564
+ SET state = 'suppressed', updated_at = ?
1565
+ WHERE state = 'pending' AND ${column} = ?
1566
+ `).run(updatedAt, value);
1567
+ this.db.prepare(`
1568
+ UPDATE event_deliveries
1569
+ SET detail_state = CASE
1570
+ WHEN detail_state = 'pending' THEN 'deferred'
1571
+ ELSE detail_state
1572
+ END,
1573
+ monitor_state = CASE
1574
+ WHEN monitor_state = 'pending'
1575
+ AND NOT EXISTS (
1576
+ SELECT 1
1577
+ FROM mailbox_items m
1578
+ WHERE m.event_id = event_deliveries.event_id
1579
+ AND m.consumer_id = event_deliveries.consumer_id
1580
+ AND m.state = 'claimed'
1581
+ ) THEN 'suppressed'
1582
+ ELSE monitor_state
1583
+ END
1584
+ WHERE event_id IN (
1585
+ SELECT event_id FROM events WHERE ${column} = ?
1586
+ )
1587
+ `).run(value);
1588
+ }
1589
+
1590
+ private sqliteMailboxRowIsClaimable(row: Record<string, unknown>, nowMs: number): boolean {
1591
+ return row.state === 'pending'
1592
+ ? numberValue(row.available_at) <= nowMs
1593
+ : row.state === 'claimed' && numberValue(row.claim_expires_at) <= nowMs;
1594
+ }
1595
+
1596
+ private suppressMailboxEventDeliveryRow(
1597
+ row: Record<string, unknown>,
1598
+ deferDetails: boolean,
1599
+ ): void {
1600
+ this.db.prepare(`
1601
+ UPDATE event_deliveries
1602
+ SET monitor_state = CASE
1603
+ WHEN monitor_state = 'pending' THEN 'suppressed'
1604
+ ELSE monitor_state
1605
+ END,
1606
+ detail_state = CASE
1607
+ WHEN ? = 1 AND detail_state = 'pending' THEN 'deferred'
1608
+ ELSE detail_state
1609
+ END
1610
+ WHERE event_id = ? AND consumer_id = ?
1611
+ `).run(
1612
+ booleanInt(deferDetails),
1613
+ String(row.event_id),
1614
+ String(row.consumer_id),
1615
+ );
1616
+ }
1617
+
1618
+ private suppressExpiredMailboxClaimsOutsideCurrentSession(
1619
+ consumerId: string,
1620
+ nowMs: number,
1621
+ ): void {
1622
+ const rows = this.db.prepare(`
1623
+ SELECT m.*
1624
+ FROM mailbox_items m
1625
+ WHERE m.consumer_id = ?
1626
+ AND m.state = 'claimed'
1627
+ AND m.claim_expires_at <= ?
1628
+ AND NOT EXISTS (
1629
+ SELECT 1
1630
+ FROM play_sessions p
1631
+ JOIN event_segments s ON s.session_id = p.session_id
1632
+ WHERE p.session_id = m.session_id
1633
+ AND p.is_current = 1
1634
+ AND s.segment_id = m.segment_id
1635
+ )
1636
+ `).all(consumerId, nowMs);
1637
+ if (rows.length === 0) return;
1638
+ const itemIds = rows.map((row) => String(row.item_id));
1639
+ this.db.prepare(`
1640
+ UPDATE mailbox_items
1641
+ SET state = 'suppressed', claim_owner = NULL, claim_token = NULL,
1642
+ claim_expires_at = NULL, updated_at = ?
1643
+ WHERE item_id IN (${placeholders(itemIds.length)})
1644
+ `).run(new Date(nowMs).toISOString(), ...itemIds);
1645
+ for (const row of rows) this.suppressMailboxEventDeliveryRow(row, true);
1646
+ }
1647
+
1648
+ private addInFilter(
1649
+ clauses: string[],
1650
+ params: unknown[],
1651
+ column: string,
1652
+ values: readonly unknown[] | undefined,
1653
+ ): void {
1654
+ if (!values) return;
1655
+ // An explicitly empty filter means "match nothing", matching the Memory
1656
+ // repository. Treating it as absent is especially dangerous for suppress
1657
+ // operations because it would broaden the update to every Mailbox item.
1658
+ if (values.length === 0) {
1659
+ clauses.push('0 = 1');
1660
+ return;
1661
+ }
1662
+ clauses.push(`${column} IN (${placeholders(values.length)})`);
1663
+ params.push(...values);
1664
+ }
1665
+
1666
+ private assertLeaseIfPresent(lease: ConsumerLease | undefined, nowMs?: number): void {
1667
+ if (lease && !this.leaseIsValid(lease, nowMs)) throw new DeliveryLeaseLostError(lease);
1668
+ }
1669
+
1670
+ private transaction<T>(fn: () => T): T {
1671
+ this.db.exec('BEGIN IMMEDIATE');
1672
+ try {
1673
+ const result = fn();
1674
+ this.db.exec('COMMIT');
1675
+ return result;
1676
+ } catch (error) {
1677
+ try { this.db.exec('ROLLBACK'); } catch {}
1678
+ throw error;
1679
+ }
1680
+ }
1681
+ }