synabun 2.4.1 → 2.4.3

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 (345) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +46 -6
  4. package/lib/data-home-files.js +4 -2
  5. package/lib/first-launch-protection.js +8 -2
  6. package/lib/release-npm-ci.mjs +23 -1
  7. package/lib/update-snapshot.js +11 -4
  8. package/mcp-server/dist/http.d.ts.map +1 -1
  9. package/mcp-server/dist/http.js +25 -2
  10. package/mcp-server/dist/http.js.map +1 -1
  11. package/mcp-server/dist/index.d.ts.map +1 -1
  12. package/mcp-server/dist/index.js +62 -17
  13. package/mcp-server/dist/index.js.map +1 -1
  14. package/mcp-server/dist/services/browser-bench.d.ts +22 -22
  15. package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
  16. package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
  17. package/mcp-server/dist/services/memory-maintenance.js +34 -45
  18. package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
  19. package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
  20. package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
  21. package/mcp-server/dist/services/memory-migration-copy.js +467 -0
  22. package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
  23. package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
  24. package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
  25. package/mcp-server/dist/services/memory-migration-worker.js +60 -0
  26. package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
  27. package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
  28. package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
  29. package/mcp-server/dist/services/memory-retrieval.js +188 -40
  30. package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
  31. package/mcp-server/dist/services/memory-schema.d.ts +58 -2
  32. package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
  33. package/mcp-server/dist/services/memory-schema.js +190 -13
  34. package/mcp-server/dist/services/memory-schema.js.map +1 -1
  35. package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
  36. package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
  37. package/mcp-server/dist/services/memory-sessions.js +56 -20
  38. package/mcp-server/dist/services/memory-sessions.js.map +1 -1
  39. package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
  40. package/mcp-server/dist/services/memory-verification.js +8 -5
  41. package/mcp-server/dist/services/memory-verification.js.map +1 -1
  42. package/mcp-server/dist/services/neural-interface.d.ts +5 -0
  43. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  44. package/mcp-server/dist/services/neural-interface.js +19 -2
  45. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  46. package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
  47. package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
  48. package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
  49. package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
  50. package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
  51. package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
  52. package/mcp-server/dist/services/retrieval-reader.js +145 -0
  53. package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
  54. package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
  55. package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
  56. package/mcp-server/dist/services/sqlite-write.js +94 -0
  57. package/mcp-server/dist/services/sqlite-write.js.map +1 -0
  58. package/mcp-server/dist/services/sqlite.d.ts +39 -0
  59. package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
  60. package/mcp-server/dist/services/sqlite.js +249 -8
  61. package/mcp-server/dist/services/sqlite.js.map +1 -1
  62. package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
  63. package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
  64. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  65. package/mcp-server/dist/services/typesafe-config.js +32 -10
  66. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  67. package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
  68. package/mcp-server/dist/services/typesafe.js +9 -7
  69. package/mcp-server/dist/services/typesafe.js.map +1 -1
  70. package/mcp-server/dist/services/vector-cache.d.ts +32 -0
  71. package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
  72. package/mcp-server/dist/services/vector-cache.js +161 -8
  73. package/mcp-server/dist/services/vector-cache.js.map +1 -1
  74. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  75. package/mcp-server/dist/tools/agents.d.ts +11 -7
  76. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  77. package/mcp-server/dist/tools/agents.js +27 -9
  78. package/mcp-server/dist/tools/agents.js.map +1 -1
  79. package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
  80. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  81. package/mcp-server/dist/tools/browser-advanced.js +10 -3
  82. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  83. package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
  84. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
  85. package/mcp-server/dist/tools/browser-extension-setup.js +29 -0
  86. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
  87. package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
  88. package/mcp-server/dist/tools/browser-interact.js +6 -1
  89. package/mcp-server/dist/tools/browser-interact.js.map +1 -1
  90. package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
  91. package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
  92. package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
  93. package/mcp-server/package-lock.json +5 -5
  94. package/mcp-server/package.json +1 -1
  95. package/mcp-server/src/http.ts +20 -2
  96. package/mcp-server/src/index.ts +59 -17
  97. package/mcp-server/src/services/memory-maintenance.ts +31 -28
  98. package/mcp-server/src/services/memory-migration-copy.ts +419 -0
  99. package/mcp-server/src/services/memory-migration-worker.ts +55 -0
  100. package/mcp-server/src/services/memory-retrieval.ts +173 -32
  101. package/mcp-server/src/services/memory-schema.ts +194 -12
  102. package/mcp-server/src/services/memory-sessions.ts +54 -21
  103. package/mcp-server/src/services/memory-verification.ts +7 -4
  104. package/mcp-server/src/services/neural-interface.ts +22 -2
  105. package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
  106. package/mcp-server/src/services/retrieval-reader.ts +131 -0
  107. package/mcp-server/src/services/sqlite-write.ts +60 -0
  108. package/mcp-server/src/services/sqlite.ts +246 -8
  109. package/mcp-server/src/services/typesafe-config.ts +25 -6
  110. package/mcp-server/src/services/typesafe.ts +9 -7
  111. package/mcp-server/src/services/vector-cache.ts +154 -9
  112. package/mcp-server/src/tools/agents.ts +26 -9
  113. package/mcp-server/src/tools/browser-advanced.ts +10 -3
  114. package/mcp-server/src/tools/browser-extension-setup.ts +36 -0
  115. package/mcp-server/src/tools/browser-interact.ts +5 -1
  116. package/neural-interface/i18n/en.json +313 -2
  117. package/neural-interface/i18n/pt-BR.json +321 -10
  118. package/neural-interface/lib/agents/split.js +32 -4
  119. package/neural-interface/lib/assistant-api.js +52 -8
  120. package/neural-interface/lib/assistant-brains/claude.js +2 -0
  121. package/neural-interface/lib/assistant-brains/opencode.js +121 -7
  122. package/neural-interface/lib/assistant-catalog.js +2 -2
  123. package/neural-interface/lib/assistant-config.js +0 -7
  124. package/neural-interface/lib/assistant-dispatch.js +281 -95
  125. package/neural-interface/lib/assistant-envelope.js +40 -0
  126. package/neural-interface/lib/assistant-persona.js +16 -4
  127. package/neural-interface/lib/assistant-pricing.js +65 -14
  128. package/neural-interface/lib/assistant-router.js +131 -47
  129. package/neural-interface/lib/assistant-run-wait.js +45 -28
  130. package/neural-interface/lib/assistant-runtime.js +133 -42
  131. package/neural-interface/lib/backup-contents.js +158 -0
  132. package/neural-interface/lib/backup-crypto-io.js +330 -0
  133. package/neural-interface/lib/backup-crypto-worker.js +130 -0
  134. package/neural-interface/lib/backup-crypto.js +525 -0
  135. package/neural-interface/lib/backup-download.js +268 -0
  136. package/neural-interface/lib/backup-encryption.js +318 -0
  137. package/neural-interface/lib/backup-groups.js +287 -0
  138. package/neural-interface/lib/backup-restore-session.js +176 -0
  139. package/neural-interface/lib/backup-restore-stage.js +60 -0
  140. package/neural-interface/lib/backup-service.js +788 -233
  141. package/neural-interface/lib/backup-zip-reader.js +30 -18
  142. package/neural-interface/lib/backup-zip-writer.js +34 -10
  143. package/neural-interface/lib/browser-extension-adapter.js +89 -15
  144. package/neural-interface/lib/browser-extension-archive.js +149 -0
  145. package/neural-interface/lib/browser-extension-bridge.js +24 -10
  146. package/neural-interface/lib/browser-extension-folder.js +596 -76
  147. package/neural-interface/lib/browser-extension-package.js +200 -0
  148. package/neural-interface/lib/browser-extension-pin.js +84 -0
  149. package/neural-interface/lib/browser-extension-pin.json +33 -0
  150. package/{browser-extension/protocol.js → neural-interface/lib/browser-extension-protocol.js} +91 -6
  151. package/neural-interface/lib/browser-extension-setup.js +105 -18
  152. package/neural-interface/lib/claude-agent-bridge.js +1 -0
  153. package/neural-interface/lib/claude-session-cleanup.js +5 -1
  154. package/neural-interface/lib/cli-install.js +23 -3
  155. package/neural-interface/lib/cli-update-planner.js +171 -9
  156. package/neural-interface/lib/client-diagnostics.js +42 -0
  157. package/neural-interface/lib/confined-fs.js +7 -2
  158. package/neural-interface/lib/coordination/README.md +8 -2
  159. package/neural-interface/lib/coordination/contract.js +161 -0
  160. package/neural-interface/lib/coordination/database.js +999 -0
  161. package/neural-interface/lib/coordination/operations.js +436 -0
  162. package/neural-interface/lib/coordination/service.js +68 -537
  163. package/neural-interface/lib/coordination/storage-worker.js +101 -0
  164. package/neural-interface/lib/coordination/store.js +219 -1111
  165. package/neural-interface/lib/db.js +70 -32
  166. package/neural-interface/lib/health-count.js +37 -0
  167. package/neural-interface/lib/loop-stall.js +139 -0
  168. package/neural-interface/lib/maritaca/client.js +2 -2
  169. package/neural-interface/lib/maritaca/models.js +12 -17
  170. package/neural-interface/lib/maritaca/opencode.js +4 -2
  171. package/neural-interface/lib/memory-api.js +9 -1
  172. package/neural-interface/lib/memory-session-capture.js +42 -10
  173. package/neural-interface/lib/memory-store-gate.js +313 -0
  174. package/neural-interface/lib/memory-store-migrate.js +65 -0
  175. package/neural-interface/lib/memory-timers.js +7 -7
  176. package/neural-interface/lib/native-loop-providers.js +23 -17
  177. package/neural-interface/lib/native-loop-runtime.js +48 -9
  178. package/neural-interface/lib/opencode-build-preflight.js +18 -1
  179. package/neural-interface/lib/opencode-native-boundary.js +69 -8
  180. package/neural-interface/lib/opencode-provider-view.js +14 -3
  181. package/neural-interface/lib/opencode-shell-read.js +107 -0
  182. package/neural-interface/lib/opencode-stop-failures.js +40 -0
  183. package/neural-interface/lib/opencode-turn-release.js +173 -0
  184. package/neural-interface/lib/opencode-v2-client.js +4 -1
  185. package/neural-interface/lib/opencode-v2-ws-requests.js +65 -1
  186. package/neural-interface/lib/opencode2-client.js +343 -7
  187. package/neural-interface/lib/opencode2-translate.js +161 -4
  188. package/neural-interface/lib/recall-impact.js +122 -0
  189. package/neural-interface/lib/scratch-evidence.js +420 -0
  190. package/neural-interface/lib/scratch-process-guard.js +139 -0
  191. package/neural-interface/lib/scratch-references.js +279 -0
  192. package/neural-interface/lib/scratch-retention-core.js +385 -0
  193. package/neural-interface/lib/scratch-retention-worker.js +37 -0
  194. package/neural-interface/lib/scratch-retention.js +151 -0
  195. package/neural-interface/lib/session-cache-builder.js +31 -43
  196. package/neural-interface/lib/session-cache-worker.js +157 -0
  197. package/neural-interface/lib/session-indexer.js +28 -21
  198. package/neural-interface/lib/session-search-index.js +85 -0
  199. package/neural-interface/lib/skills/creation.js +1 -1
  200. package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
  201. package/neural-interface/lib/style-guide/store.js +43 -3
  202. package/neural-interface/lib/system-restore.js +50 -0
  203. package/neural-interface/lib/teams/api.js +15 -6
  204. package/neural-interface/lib/teams/claims.js +67 -31
  205. package/neural-interface/lib/teams/index.js +7 -7
  206. package/neural-interface/lib/teams/integration.js +40 -40
  207. package/neural-interface/lib/teams/landing.js +6 -6
  208. package/neural-interface/lib/teams/recovery.js +24 -23
  209. package/neural-interface/lib/teams/scheduler.js +194 -95
  210. package/neural-interface/lib/teams/state.js +14 -14
  211. package/neural-interface/lib/teams/worktrees.js +27 -27
  212. package/neural-interface/lib/terminal-token-redaction.js +83 -0
  213. package/neural-interface/lib/whatsapp/bridge.js +54 -7
  214. package/neural-interface/lib/worker-confinement.js +47 -2
  215. package/neural-interface/lib/worker-mcp-channel.js +2 -0
  216. package/neural-interface/lib/worker-resume.js +5 -0
  217. package/neural-interface/lib/worker-stop.js +86 -0
  218. package/neural-interface/package-lock.json +5 -5
  219. package/neural-interface/package.json +1 -1
  220. package/neural-interface/public/extension-setup.html +5 -2
  221. package/neural-interface/public/index.html +233 -24
  222. package/neural-interface/public/onboarding.html +259 -34
  223. package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
  224. package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
  225. package/neural-interface/public/shared/agy/agy-options.js +11 -0
  226. package/neural-interface/public/shared/agy/agy-panel.js +67 -20
  227. package/neural-interface/public/shared/agy/agy-styles.js +14 -12
  228. package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
  229. package/neural-interface/public/shared/api.js +1 -1
  230. package/neural-interface/public/shared/assistant/asst-api.js +28 -3
  231. package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
  232. package/neural-interface/public/shared/assistant/asst-control.js +2 -0
  233. package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
  234. package/neural-interface/public/shared/assistant/asst-panel.js +87 -3
  235. package/neural-interface/public/shared/assistant/asst-rack-styles.js +27 -0
  236. package/neural-interface/public/shared/assistant/asst-render.js +243 -44
  237. package/neural-interface/public/shared/assistant/asst-route.js +100 -21
  238. package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
  239. package/neural-interface/public/shared/assistant/asst-shell-logic.js +200 -0
  240. package/neural-interface/public/shared/assistant/asst-shell.js +111 -0
  241. package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
  242. package/neural-interface/public/shared/assistant/asst-state.js +11 -0
  243. package/neural-interface/public/shared/assistant/asst-styles.js +11 -23
  244. package/neural-interface/public/shared/assistant/route-identity.js +2 -1
  245. package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
  246. package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
  247. package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
  248. package/neural-interface/public/shared/cdx/cdx-tabs.js +54 -9
  249. package/neural-interface/public/shared/client-diagnostics.js +94 -0
  250. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  251. package/neural-interface/public/shared/cp/cp-styles.js +1 -1
  252. package/neural-interface/public/shared/effort-i18n.js +118 -0
  253. package/neural-interface/public/shared/extension-setup/es-page.js +10 -4
  254. package/neural-interface/public/shared/extension-setup/es-view.js +25 -10
  255. package/neural-interface/public/shared/html-shell.js +4 -52
  256. package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
  257. package/neural-interface/public/shared/memory-store-wait.js +52 -0
  258. package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
  259. package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
  260. package/neural-interface/public/shared/mtc/mtc-panel.js +25 -3
  261. package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
  262. package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
  263. package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +5 -0
  264. package/neural-interface/public/shared/ocp-v2/ocp-v2-location-logic.js +109 -0
  265. package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +1 -0
  266. package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
  267. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +152 -8
  268. package/neural-interface/public/shared/ocp-v2/ocp-v2-rehydrate.js +7 -1
  269. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +53 -4
  270. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +52 -6
  271. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +22 -2
  272. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-block.js +165 -0
  273. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +346 -0
  274. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell.js +108 -0
  275. package/neural-interface/public/shared/ocp-v2/ocp-v2-state.js +49 -3
  276. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +67 -93
  277. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools-logic.js +20 -5
  278. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools.js +7 -1
  279. package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
  280. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +7 -2
  281. package/neural-interface/public/shared/output-format.js +294 -0
  282. package/neural-interface/public/shared/provider-icons.js +6 -0
  283. package/neural-interface/public/shared/schedules-view.js +2 -1
  284. package/neural-interface/public/shared/server-presence.js +77 -0
  285. package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
  286. package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
  287. package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
  288. package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
  289. package/neural-interface/public/shared/settings/settings-browser-extension.js +54 -12
  290. package/neural-interface/public/shared/settings/settings-ia.js +1 -1
  291. package/neural-interface/public/shared/shell-stop-view.js +83 -0
  292. package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
  293. package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
  294. package/neural-interface/public/shared/studio-attention.js +6 -0
  295. package/neural-interface/public/shared/styles.css +341 -437
  296. package/neural-interface/public/shared/tour/tour-actor.js +14 -3
  297. package/neural-interface/public/shared/transcript-rows.js +28 -3
  298. package/neural-interface/public/shared/tray-auto-close.js +49 -6
  299. package/neural-interface/public/shared/ui-agents.js +1 -2
  300. package/neural-interface/public/shared/ui-automation-studio.js +168 -108
  301. package/neural-interface/public/shared/ui-claude-panel.js +62 -65
  302. package/neural-interface/public/shared/ui-loading.js +124 -17
  303. package/neural-interface/public/shared/ui-native-loop-router.js +52 -0
  304. package/neural-interface/public/shared/ui-navbar.js +2 -1
  305. package/neural-interface/public/shared/ui-output.js +533 -0
  306. package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
  307. package/neural-interface/public/shared/ui-scroll-follow.js +101 -6
  308. package/neural-interface/public/shared/ui-sessions.js +2 -2
  309. package/neural-interface/public/shared/ui-settings-entry.js +18 -0
  310. package/neural-interface/public/shared/ui-settings.js +224 -65
  311. package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
  312. package/neural-interface/public/shared/ui-tooltip.js +16 -0
  313. package/neural-interface/public/shared/ui-tutorial.js +5 -6
  314. package/neural-interface/public/shared/ui-worker-end.js +27 -8
  315. package/neural-interface/public/shared/worker-end.js +9 -4
  316. package/neural-interface/public/variant/2d/main.js +5 -0
  317. package/neural-interface/public/variant/3d/app.js +10 -0
  318. package/neural-interface/public/variant/3d/main.js +5 -1
  319. package/neural-interface/scripts/scratch-retention.mjs +20 -0
  320. package/neural-interface/server.js +725 -173
  321. package/npm-shrinkwrap.json +5 -5
  322. package/package.json +1 -2
  323. package/scripts/restore-data-home-from-backup.mjs +175 -8
  324. package/setup.js +18 -4
  325. package/browser-extension/content.js +0 -189
  326. package/browser-extension/engine.js +0 -508
  327. package/browser-extension/icons/icon-128.png +0 -0
  328. package/browser-extension/icons/icon-16.png +0 -0
  329. package/browser-extension/icons/icon-32.png +0 -0
  330. package/browser-extension/icons/icon-48.png +0 -0
  331. package/browser-extension/icons/status-off-16.png +0 -0
  332. package/browser-extension/icons/status-off-32.png +0 -0
  333. package/browser-extension/icons/status-off-48.png +0 -0
  334. package/browser-extension/icons/status-on-16.png +0 -0
  335. package/browser-extension/icons/status-on-32.png +0 -0
  336. package/browser-extension/icons/status-on-48.png +0 -0
  337. package/browser-extension/manifest.json +0 -56
  338. package/browser-extension/popup-strings.js +0 -250
  339. package/browser-extension/popup-view.js +0 -151
  340. package/browser-extension/popup.css +0 -166
  341. package/browser-extension/popup.html +0 -108
  342. package/browser-extension/popup.js +0 -359
  343. package/browser-extension/service-worker.js +0 -275
  344. package/browser-extension/setup-content.js +0 -36
  345. package/browser-extension/tokens.css +0 -326
@@ -0,0 +1,999 @@
1
+ // ═══════════════════════════════════════════
2
+ // SynaBun — Coordination store
3
+ // ═══════════════════════════════════════════
4
+ //
5
+ // What agents that work together tell each other, kept on disk. The Assistant's mailbox was a list in memory
6
+ // (assistant-runtime.js enqueueMailbox): cut at 40 items, gone at a restart, and "something changed" was the only
7
+ // thing a wait could ask for. This is its durable replacement: one SQLite file in WAL mode holding
8
+ //
9
+ // events an append-only log. Every event gets a `seq` that only ever grows; an event appended twice under
10
+ // the same caller-supplied `id` is stored once.
11
+ // deliveries one row per event and recipient it is addressed to: when it was first handed out and when the
12
+ // recipient acknowledged it. Nothing is acknowledged by being read, so an event a recipient never
13
+ // acknowledged is handed out again, also after a restart (at-least-once).
14
+ // cursors per recipient, the seq up to which everything addressed to it is acknowledged.
15
+ // claims which slice of a team holds which files while it works (overlap is refused).
16
+ // team_tasks the journal of a team's and its slices' states, for recovery after a crash.
17
+ // outbox follow-ups queued for a run, kept until the run took them.
18
+ // migrations which schema versions this file has had applied.
19
+ //
20
+ // Waiting is a wake-up, never a poll: `subscribe` and `waitFor` are called back after the transaction that
21
+ // appended an event has committed, in this process. The file is its own (DATA_HOME/data/coordination.db), apart
22
+ // from memory.db: that one is shared with the MCP server and backed up, and coordination churn has no place in it.
23
+ //
24
+ // The storage worker owns this connection. Everything here is synchronous
25
+ // except `waitFor`, so a JavaScript turn is never interleaved with another's. The Assistant's dispatcher and runtime
26
+ // use it through service.js (the mailbox, typed waits, the follow-up outbox); README.md beside this file is the
27
+ // reference for the phases that build on it.
28
+
29
+ import { randomUUID } from 'node:crypto';
30
+ import { mkdirSync } from 'node:fs';
31
+ import { dirname } from 'node:path';
32
+ import { DatabaseSync } from 'node:sqlite';
33
+ import { globsOverlap, isTeamSlug, matchesOwnedPath, normalizeOwnedPath, normalizeRelPath, ownedPathProblem } from '../teams/schema.js';
34
+
35
+ import { COORDINATION_LIMITS, CoordinationError, DEFAULT_EVENT_PRIORITY, EVENT_PRIORITIES, KIND_PRIORITY, MIGRATIONS } from './contract.js';
36
+
37
+ const KIND_RE = /^[a-z][a-z0-9_.:-]{0,63}$/;
38
+ // eslint-disable-next-line no-control-regex
39
+ const CONTROL_RE = /[\u0000-\u001f\u007f]/;
40
+ const iso = (ms) => (ms === null || ms === undefined ? null : new Date(Number(ms)).toISOString());
41
+ const isObject = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
42
+ const fail = (code, message, extra) => new CoordinationError(code, message, extra);
43
+
44
+ function idText(value, field, { required = false } = {}) {
45
+ if (value === null || value === undefined || value === '') {
46
+ if (required) throw fail('FIELD_REQUIRED', `${field} is required.`, { field });
47
+ return null;
48
+ }
49
+ if (typeof value !== 'string' || value.length > COORDINATION_LIMITS.id || CONTROL_RE.test(value)) {
50
+ throw fail('FIELD_INVALID', `${field} must be text of at most ${COORDINATION_LIMITS.id} characters with no control character.`, { field });
51
+ }
52
+ return value;
53
+ }
54
+ function recipientText(value) {
55
+ if (typeof value !== 'string' || !value || value.length > COORDINATION_LIMITS.recipient || CONTROL_RE.test(value)) {
56
+ throw fail('RECIPIENT_INVALID', `A recipient is a name of at most ${COORDINATION_LIMITS.recipient} characters, like "session:<id>" or "run:<id>".`, { field: 'recipient' });
57
+ }
58
+ return value;
59
+ }
60
+ function kindList(kinds) {
61
+ if (kinds === null || kinds === undefined) return null;
62
+ const list = (Array.isArray(kinds) ? kinds : [kinds]).map((kind) => String(kind));
63
+ for (const kind of list) if (!KIND_RE.test(kind)) throw fail('KIND_INVALID', `"${kind.slice(0, 80)}" is not an event kind.`, { field: 'kinds' });
64
+ return list.length ? [...new Set(list)] : null;
65
+ }
66
+ function limitOf(value, fallback = COORDINATION_LIMITS.defaultReadLimit) {
67
+ const n = Math.floor(Number(value));
68
+ return Number.isFinite(n) && n >= 1 ? Math.min(n, COORDINATION_LIMITS.readLimit) : fallback;
69
+ }
70
+ function seqOf(value, field = 'afterSeq') {
71
+ const n = Number(value);
72
+ if (!Number.isInteger(n) || n < 0) throw fail('SEQ_INVALID', `${field} must be a whole number from 0.`, { field });
73
+ return n;
74
+ }
75
+ function jsonText(value, field, maxBytes) {
76
+ let out;
77
+ try { out = JSON.stringify(value === undefined ? null : value); } catch (error) { throw fail('PAYLOAD_INVALID', `${field} cannot be written as JSON: ${error?.message || error}`, { field }); }
78
+ if (out === undefined) throw fail('PAYLOAD_INVALID', `${field} cannot be written as JSON.`, { field });
79
+ if (Buffer.byteLength(out, 'utf8') > maxBytes) throw fail('PAYLOAD_TOO_LARGE', `${field} is larger than ${Math.round(maxBytes / 1024)} KB.`, { field });
80
+ return out;
81
+ }
82
+ function parseJson(textValue, fallback = null) {
83
+ try { return JSON.parse(textValue); } catch { return fallback; }
84
+ }
85
+
86
+ function applyMigrations(db, migrations, now) {
87
+ db.exec('CREATE TABLE IF NOT EXISTS migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at INTEGER NOT NULL)');
88
+ const ordered = [...migrations].sort((a, b) => a.version - b.version);
89
+ const latest = ordered.length ? ordered[ordered.length - 1].version : 0;
90
+ const applied = Number(db.prepare('SELECT MAX(version) AS version FROM migrations').get()?.version) || 0;
91
+ // A file a newer SynaBun wrote is never read with older rules: its tables may mean something else by now.
92
+ if (applied > latest) throw fail('SCHEMA_NEWER', `The coordination store was written by a newer SynaBun (schema ${applied}; this one knows ${latest}).`, { found: applied, known: latest });
93
+ for (const migration of ordered) {
94
+ if (migration.version <= applied) continue;
95
+ db.exec('BEGIN IMMEDIATE');
96
+ try {
97
+ // Another opener may have applied this step while we waited for the writer.
98
+ if (db.prepare('SELECT 1 FROM migrations WHERE version = ?').get(migration.version)) {
99
+ db.exec('COMMIT');
100
+ continue;
101
+ }
102
+ migration.up(db);
103
+ db.prepare('INSERT INTO migrations (version, name, applied_at) VALUES (?, ?, ?)').run(migration.version, String(migration.name || ''), now());
104
+ db.exec('COMMIT');
105
+ } catch (error) {
106
+ try { db.exec('ROLLBACK'); } catch { /* the failure below is the one to report */ }
107
+ throw fail('MIGRATION_FAILED', `Coordination store migration ${migration.version} failed: ${error?.message || error}`, { version: migration.version, cause: error });
108
+ }
109
+ }
110
+ return latest;
111
+ }
112
+
113
+ /**
114
+ * Open (and create or upgrade) the coordination store.
115
+ *
116
+ * @param {object} options
117
+ * @param {string} options.path the database file (`coordinationDbPath(dataDir)`); a test passes its own
118
+ * @param {() => number} [options.now] epoch milliseconds
119
+ * @param {() => string} [options.newId] ids for events, claims' rows and outbox items the caller did not name
120
+ * @param {number} [options.busyTimeoutMs] how long a statement waits for another connection's lock
121
+ * @param {'FULL'|'NORMAL'} [options.synchronous] FULL (default): a committed event survives a power cut
122
+ * @param {(tag: string, detail: any) => void} [options.log]
123
+ * @param {readonly object[]} [options.migrations] the schema steps (tests add one to try an upgrade)
124
+ */
125
+ export function openCoordinationDatabase({
126
+ path,
127
+ now = Date.now,
128
+ newId = randomUUID,
129
+ busyTimeoutMs = 5000,
130
+ synchronous = 'FULL',
131
+ log = () => {},
132
+ migrations = MIGRATIONS,
133
+ retry = fn => fn(),
134
+ } = {}) {
135
+ if (typeof path !== 'string' || !path) throw fail('PATH_REQUIRED', 'createCoordinationStore needs the path of its database file.');
136
+ if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true });
137
+ const db = new DatabaseSync(path);
138
+ let schemaVersion;
139
+ try {
140
+ db.exec('PRAGMA journal_mode = WAL');
141
+ db.exec(`PRAGMA synchronous = ${synchronous === 'NORMAL' ? 'NORMAL' : 'FULL'}`);
142
+ db.exec(`PRAGMA busy_timeout = ${Math.max(0, Math.floor(Number(busyTimeoutMs) || 0))}`);
143
+ db.exec('PRAGMA foreign_keys = ON');
144
+ schemaVersion = applyMigrations(db, migrations, now);
145
+ } catch (error) {
146
+ try { db.close(); } catch { /* already unusable */ }
147
+ throw error;
148
+ }
149
+
150
+ let closed = false;
151
+ let inTransaction = false;
152
+ const subscribers = new Set(); // { filter, fn }
153
+ const waiters = new Set(); // { matches(notice), wake(), finish(result) }
154
+ const notices = []; // committed appends not yet told to subscribers and waiters
155
+ let publishing = false;
156
+
157
+ function open() { if (closed) throw fail('CLOSED', 'The coordination store is closed.'); }
158
+
159
+ /** One write transaction. A call made inside another joins it. */
160
+ function transaction(fn) {
161
+ return retry(() => runTransaction(fn));
162
+ }
163
+
164
+ function runTransaction(fn) {
165
+ open();
166
+ if (inTransaction) return fn();
167
+ db.exec('BEGIN IMMEDIATE');
168
+ inTransaction = true;
169
+ let out;
170
+ try {
171
+ out = fn();
172
+ db.exec('COMMIT');
173
+ } catch (error) {
174
+ try { db.exec('ROLLBACK'); } catch { /* nothing was open any more */ }
175
+ throw error;
176
+ } finally {
177
+ inTransaction = false;
178
+ }
179
+ return out;
180
+ }
181
+
182
+ // ── rows → what callers get ────────────────────────────────────────────────
183
+ const eventView = (row) => ({
184
+ id: row.id,
185
+ seq: Number(row.seq),
186
+ sessionId: row.session_id ?? null,
187
+ teamId: row.team_id ?? null,
188
+ runId: row.run_id ?? null,
189
+ kind: row.kind,
190
+ priority: row.priority,
191
+ payload: parseJson(row.payload),
192
+ createdAt: iso(row.created_at),
193
+ });
194
+ const deliveryView = (row) => ({
195
+ ...eventView(row),
196
+ delivery: {
197
+ recipient: row.recipient,
198
+ deliveredAt: iso(row.delivered_at),
199
+ ackedAt: iso(row.acked_at),
200
+ attempts: Number(row.attempts) || 0,
201
+ // Handed out before and not acknowledged then: the consumer may have seen it already.
202
+ redelivered: (Number(row.attempts) || 0) > 1,
203
+ // How many older low-priority events this one stands for (coalesce).
204
+ merged: Number(row.merged) || 0,
205
+ },
206
+ });
207
+ const claimView = (row) => ({
208
+ id: Number(row.id), teamId: row.team_id, sliceId: row.slice_id, glob: row.glob, runId: row.run_id ?? null,
209
+ createdAt: iso(row.created_at), releasedAt: iso(row.released_at),
210
+ });
211
+ const journalView = (row) => ({
212
+ id: Number(row.id), teamId: row.team_id, sliceId: row.slice_id || null, state: row.state, runId: row.run_id ?? null,
213
+ data: parseJson(row.data, {}), createdAt: iso(row.created_at),
214
+ });
215
+ const outboxView = (row) => ({
216
+ id: row.id, runId: row.run_id, text: row.text, sessionId: row.session_id ?? null, meta: parseJson(row.meta, {}),
217
+ createdAt: iso(row.created_at), sentAt: iso(row.sent_at), attempts: Number(row.attempts) || 0,
218
+ });
219
+
220
+ // ── events ─────────────────────────────────────────────────────────────────
221
+ const selectEventById = db.prepare('SELECT * FROM events WHERE id = ?');
222
+ const insertEvent = db.prepare('INSERT INTO events (id, session_id, team_id, run_id, kind, priority, payload, coalesce_key, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
223
+ const insertDelivery = db.prepare('INSERT INTO deliveries (recipient, event_id, seq) VALUES (?, ?, ?)');
224
+ const selectRecipientsOfEvent = db.prepare('SELECT recipient FROM deliveries WHERE event_id = ? ORDER BY recipient');
225
+
226
+ function readEventInput(event) {
227
+ if (!isObject(event)) throw fail('EVENT_INVALID', 'An event is an object with at least a kind.');
228
+ const kind = typeof event.kind === 'string' ? event.kind.trim() : '';
229
+ if (!KIND_RE.test(kind)) throw fail('KIND_INVALID', 'kind is a lower-case name like "run.result" (letters, digits, ".", "_", ":" and "-", at most 64).', { field: 'kind' });
230
+ const priority = event.priority === undefined || event.priority === null || event.priority === '' ? (KIND_PRIORITY[kind] || DEFAULT_EVENT_PRIORITY) : String(event.priority).toLowerCase();
231
+ if (!EVENT_PRIORITIES.includes(priority)) throw fail('PRIORITY_INVALID', `priority must be one of ${EVENT_PRIORITIES.join(', ')}.`, { field: 'priority' });
232
+ const to = event.to === undefined || event.to === null ? [] : (Array.isArray(event.to) ? event.to : [event.to]);
233
+ if (to.length > COORDINATION_LIMITS.recipients) throw fail('RECIPIENTS_TOO_MANY', `An event is addressed to at most ${COORDINATION_LIMITS.recipients} recipients.`, { field: 'to' });
234
+ return {
235
+ id: idText(event.id, 'id') || String(newId()),
236
+ sessionId: idText(event.sessionId, 'sessionId'),
237
+ teamId: idText(event.teamId, 'teamId'),
238
+ runId: idText(event.runId, 'runId'),
239
+ kind,
240
+ priority,
241
+ payload: jsonText(event.payload, 'payload', COORDINATION_LIMITS.payloadBytes),
242
+ coalesceKey: idText(event.coalesceKey, 'coalesceKey'),
243
+ to: [...new Set(to.map(recipientText))],
244
+ };
245
+ }
246
+
247
+ function appendOne(input) {
248
+ const existing = selectEventById.get(input.id);
249
+ // The same id again: the event is there already. Nothing is written and nobody is woken a second time.
250
+ if (existing) return { result: { id: existing.id, seq: Number(existing.seq), duplicate: true }, notice: null };
251
+ const createdAt = now();
252
+ const seq = Number(insertEvent.run(input.id, input.sessionId, input.teamId, input.runId, input.kind, input.priority, input.payload, input.coalesceKey, createdAt).lastInsertRowid);
253
+ for (const recipient of input.to) insertDelivery.run(recipient, input.id, seq);
254
+ const event = { id: input.id, seq, sessionId: input.sessionId, teamId: input.teamId, runId: input.runId, kind: input.kind, priority: input.priority, payload: parseJson(input.payload), createdAt: iso(createdAt) };
255
+ return { result: { id: input.id, seq, duplicate: false }, notice: { event, recipients: input.to } };
256
+ }
257
+
258
+ /**
259
+ * Add an event to the log and address it.
260
+ * @param {object} event
261
+ * @param {string} [event.id] the caller's own id: appending it again stores nothing new (`duplicate: true`)
262
+ * @param {string} event.kind "run.result", "slice.state", …
263
+ * @param {'critical'|'normal'|'low'} [event.priority] default: KIND_PRIORITY of the kind, else normal
264
+ * @param {string} [event.sessionId] the Assistant session it belongs to
265
+ * @param {string} [event.teamId]
266
+ * @param {string} [event.runId]
267
+ * @param {any} [event.payload] JSON, at most 256 KB
268
+ * @param {string|string[]} [event.to] recipients: each gets a delivery it must acknowledge. None: logged only.
269
+ * @param {string} [event.coalesceKey] low priority only: events of one key are merged by `coalesce` (default key: kind, run, team and session)
270
+ * @returns {{ id: string, seq: number, duplicate: boolean }}
271
+ */
272
+ function append(event) {
273
+ const input = readEventInput(event);
274
+ const { result, notice } = transaction(() => appendOne(input));
275
+ if (notice) publish(notice);
276
+ return result;
277
+ }
278
+
279
+ /** Several events in one transaction: all of them are stored, or none. Same answers as `append`, in order. */
280
+ function appendMany(events) {
281
+ if (!Array.isArray(events)) throw fail('EVENT_INVALID', 'appendMany takes a list of events.');
282
+ const inputs = events.map(readEventInput);
283
+ const done = transaction(() => inputs.map(appendOne));
284
+ for (const { notice } of done) if (notice) publish(notice);
285
+ return done.map(({ result }) => result);
286
+ }
287
+
288
+ /** One event by its id (with the recipients it was addressed to), or null. */
289
+ function get(id) {
290
+ open();
291
+ const row = selectEventById.get(String(id));
292
+ return row ? { ...eventView(row), to: selectRecipientsOfEvent.all(row.id).map((r) => r.recipient) } : null;
293
+ }
294
+
295
+ /** The seq of the newest event (0 for an empty log). */
296
+ function lastSeq() {
297
+ open();
298
+ return Number(db.prepare('SELECT MAX(seq) AS seq FROM events').get()?.seq) || 0;
299
+ }
300
+
301
+ /**
302
+ * The log itself, oldest first: every event after `afterSeq` that matches, whoever it was addressed to. Reading
303
+ * it delivers and acknowledges nothing (a timeline, a scheduler's replay). `read` is the mailbox.
304
+ */
305
+ function events({ afterSeq = 0, teamId = null, sessionId = null, runId = null, runIds = null, kinds = null, limit = null } = {}) {
306
+ open();
307
+ const where = ['seq > ?'];
308
+ const args = [seqOf(afterSeq)];
309
+ for (const [column, value, field] of [['team_id', teamId, 'teamId'], ['session_id', sessionId, 'sessionId'], ['run_id', runId, 'runId']]) {
310
+ const wanted = idText(value, field);
311
+ if (wanted !== null) { where.push(`${column} = ?`); args.push(wanted); }
312
+ }
313
+ // Several runs at once (a workflow's wait): an empty list matches nothing.
314
+ if (runIds !== null && runIds !== undefined) {
315
+ const runs = [...new Set((Array.isArray(runIds) ? runIds : [runIds]).map((id) => idText(id, 'runIds', { required: true })))];
316
+ if (!runs.length) return [];
317
+ if (runs.length > COORDINATION_LIMITS.runIds) throw fail('FIELD_INVALID', `runIds names at most ${COORDINATION_LIMITS.runIds} runs.`, { field: 'runIds' });
318
+ where.push(`run_id IN (${runs.map(() => '?').join(', ')})`);
319
+ args.push(...runs);
320
+ }
321
+ const list = kindList(kinds);
322
+ if (list) { where.push(`kind IN (${list.map(() => '?').join(', ')})`); args.push(...list); }
323
+ return db.prepare(`SELECT * FROM events WHERE ${where.join(' AND ')} ORDER BY seq ASC LIMIT ?`).all(...args, limitOf(limit)).map(eventView);
324
+ }
325
+
326
+ // ── the mailbox: deliveries, acknowledgements, the cursor ──────────────────
327
+ const selectCursor = db.prepare('SELECT seq FROM cursors WHERE recipient = ?');
328
+ const selectOpenFloor = db.prepare('SELECT MIN(seq) AS seq FROM deliveries WHERE recipient = ? AND acked_at IS NULL');
329
+ const selectCeiling = db.prepare('SELECT MAX(seq) AS seq FROM deliveries WHERE recipient = ?');
330
+ const upsertCursor = db.prepare('INSERT INTO cursors (recipient, seq, updated_at) VALUES (?, ?, ?) ON CONFLICT (recipient) DO UPDATE SET seq = excluded.seq, updated_at = excluded.updated_at');
331
+ const markDelivered = db.prepare('UPDATE deliveries SET delivered_at = COALESCE(delivered_at, ?), attempts = attempts + 1 WHERE recipient = ? AND event_id = ?');
332
+ const ackOne = db.prepare('UPDATE deliveries SET acked_at = ? WHERE recipient = ? AND event_id = ? AND acked_at IS NULL');
333
+ const ackUpTo = db.prepare('UPDATE deliveries SET acked_at = ? WHERE recipient = ? AND seq <= ? AND acked_at IS NULL');
334
+
335
+ /** The seq up to which everything addressed to the recipient is acknowledged (0: nothing yet). */
336
+ function cursor(recipient) {
337
+ open();
338
+ return Number(selectCursor.get(recipientText(recipient))?.seq) || 0;
339
+ }
340
+ /**
341
+ * How many events a recipient has not acknowledged (nothing is handed out or recorded).
342
+ * @param {string} recipient
343
+ * @param {{ kinds?: string|string[], priority?: string|string[] }} [options]
344
+ */
345
+ function openCount(recipient, { kinds = null, priority = null } = {}) {
346
+ open();
347
+ const who = recipientText(recipient);
348
+ const list = kindList(kinds);
349
+ const levels = priority === null || priority === undefined ? null : (Array.isArray(priority) ? priority : [priority]).map((level) => String(level));
350
+ if (levels) for (const level of levels) if (!EVENT_PRIORITIES.includes(level)) throw fail('PRIORITY_INVALID', `priority must be one of ${EVENT_PRIORITIES.join(', ')}.`, { field: 'priority' });
351
+ if (!list && !levels) return Number(db.prepare('SELECT COUNT(*) AS n FROM deliveries WHERE recipient = ? AND acked_at IS NULL').get(who)?.n) || 0;
352
+ const where = ['d.recipient = ?', 'd.acked_at IS NULL'];
353
+ const args = [who];
354
+ if (list) { where.push(`e.kind IN (${list.map(() => '?').join(', ')})`); args.push(...list); }
355
+ if (levels) { where.push(`e.priority IN (${levels.map(() => '?').join(', ')})`); args.push(...levels); }
356
+ return Number(db.prepare(`SELECT COUNT(*) AS n FROM deliveries d JOIN events e ON e.id = d.event_id WHERE ${where.join(' AND ')}`).get(...args)?.n) || 0;
357
+ }
358
+ /**
359
+ * The recipients that have something open, with how many (after a restart: whose mailbox still holds events).
360
+ * @param {{ prefix?: string }} [query] `prefix`: only names that start with it ("session:")
361
+ * @returns {{ recipient: string, open: number, oldestSeq: number }[]}
362
+ */
363
+ function recipients({ prefix = null } = {}) {
364
+ open();
365
+ const rows = db.prepare('SELECT recipient, COUNT(*) AS n, MIN(seq) AS seq FROM deliveries WHERE acked_at IS NULL GROUP BY recipient ORDER BY MIN(seq) ASC').all();
366
+ const start = prefix === null || prefix === undefined ? '' : String(prefix);
367
+ return rows.filter((row) => !start || String(row.recipient).startsWith(start)).map((row) => ({ recipient: row.recipient, open: Number(row.n) || 0, oldestSeq: Number(row.seq) || 0 }));
368
+ }
369
+ /** After acknowledgements: the cursor is just below the oldest event still open, or at the newest when none is. */
370
+ function settleCursor(recipient) {
371
+ const floor = selectOpenFloor.get(recipient)?.seq;
372
+ const next = floor === null || floor === undefined ? (Number(selectCeiling.get(recipient)?.seq) || 0) : Number(floor) - 1;
373
+ const current = Number(selectCursor.get(recipient)?.seq) || 0;
374
+ // Deliveries are only ever added above every earlier one, so the cursor never has a reason to move back.
375
+ const seq = Math.max(current, next);
376
+ if (seq !== current || !selectCursor.get(recipient)) upsertCursor.run(recipient, seq, now());
377
+ return seq;
378
+ }
379
+
380
+ function handOut(rows, recipient, peek) {
381
+ if (!peek && rows.length) {
382
+ const at = now();
383
+ for (const row of rows) {
384
+ markDelivered.run(at, recipient, row.id);
385
+ row.delivered_at = row.delivered_at ?? at;
386
+ row.attempts = (Number(row.attempts) || 0) + 1;
387
+ }
388
+ }
389
+ return rows.map(deliveryView);
390
+ }
391
+
392
+ const DELIVERY_COLUMNS = 'e.*, d.recipient, d.delivered_at, d.acked_at, d.attempts, d.merged';
393
+
394
+ /**
395
+ * A recipient's events after a position, oldest first: the cursor read.
396
+ * By default from the recipient's cursor and only what it has not acknowledged, so a consumer that starts again
397
+ * (a restart, a new turn) gets every open event once more. Handing an event out records `deliveredAt` and counts
398
+ * an attempt; it acknowledges nothing.
399
+ * @param {object} query
400
+ * @param {string} query.recipient
401
+ * @param {number} [query.afterSeq] default: the recipient's cursor
402
+ * @param {string|string[]} [query.kinds]
403
+ * @param {number} [query.limit] default 100, at most 1000
404
+ * @param {boolean} [query.includeAcked] also what was acknowledged (a history view)
405
+ * @param {boolean} [query.peek] look without recording a delivery
406
+ */
407
+ function read({ recipient, afterSeq = null, kinds = null, limit = null, includeAcked = false, peek = false } = {}) {
408
+ const who = recipientText(recipient);
409
+ const list = kindList(kinds);
410
+ const max = limitOf(limit);
411
+ return transaction(() => {
412
+ const from = afterSeq === null || afterSeq === undefined ? (Number(selectCursor.get(who)?.seq) || 0) : seqOf(afterSeq);
413
+ const where = ['d.recipient = ?', 'd.seq > ?'];
414
+ const args = [who, from];
415
+ if (!includeAcked) where.push('d.acked_at IS NULL');
416
+ if (list) { where.push(`e.kind IN (${list.map(() => '?').join(', ')})`); args.push(...list); }
417
+ const rows = db.prepare(`SELECT ${DELIVERY_COLUMNS} FROM deliveries d JOIN events e ON e.id = d.event_id WHERE ${where.join(' AND ')} ORDER BY d.seq ASC LIMIT ?`).all(...args, max);
418
+ // An acknowledged event shown as history is not handed out again.
419
+ return includeAcked ? rows.map(deliveryView) : handOut(rows, who, peek);
420
+ });
421
+ }
422
+
423
+ /**
424
+ * Everything a recipient has not acknowledged, in the order to deal with it: critical events first, then the rest,
425
+ * each group oldest first. This is what a turn is composed from; like `read` it records the delivery.
426
+ * @param {string} recipient
427
+ * @param {object} [options]
428
+ * @param {string|string[]} [options.kinds]
429
+ * @param {number} [options.limit] default 100, at most 1000
430
+ * @param {boolean} [options.peek] look without recording a delivery
431
+ * @param {boolean} [options.coalesce] merge low-priority events first (`coalesce`)
432
+ */
433
+ function pending(recipient, { kinds = null, limit = null, peek = false, coalesce: merge = false } = {}) {
434
+ const who = recipientText(recipient);
435
+ const list = kindList(kinds);
436
+ const max = limitOf(limit);
437
+ return transaction(() => {
438
+ if (merge) coalesce(who);
439
+ const where = ['d.recipient = ?', 'd.acked_at IS NULL'];
440
+ const args = [who];
441
+ if (list) { where.push(`e.kind IN (${list.map(() => '?').join(', ')})`); args.push(...list); }
442
+ const rows = db.prepare(`SELECT ${DELIVERY_COLUMNS} FROM deliveries d JOIN events e ON e.id = d.event_id WHERE ${where.join(' AND ')} ORDER BY (e.priority = 'critical') DESC, d.seq ASC LIMIT ?`).all(...args, max);
443
+ return handOut(rows, who, peek);
444
+ });
445
+ }
446
+
447
+ /**
448
+ * The recipient dealt with these events: they are not handed out again. Ids it was never sent, or already
449
+ * acknowledged, are skipped, so acknowledging twice is harmless.
450
+ * @returns {{ acked: number, cursor: number }}
451
+ */
452
+ function ack(recipient, eventIds) {
453
+ const who = recipientText(recipient);
454
+ const ids = (Array.isArray(eventIds) ? eventIds : [eventIds]).filter((id) => id !== null && id !== undefined).map((id) => String(id));
455
+ return transaction(() => {
456
+ const at = now();
457
+ let acked = 0;
458
+ for (const id of new Set(ids)) acked += Number(ackOne.run(at, who, id).changes) || 0;
459
+ return { acked, cursor: settleCursor(who) };
460
+ });
461
+ }
462
+
463
+ /** Acknowledge everything addressed to the recipient up to and including `seq`. */
464
+ function ackThrough(recipient, seq) {
465
+ const who = recipientText(recipient);
466
+ const upTo = seqOf(seq, 'seq');
467
+ return transaction(() => {
468
+ const acked = Number(ackUpTo.run(now(), who, upTo).changes) || 0;
469
+ return { acked, cursor: settleCursor(who) };
470
+ });
471
+ }
472
+
473
+ /**
474
+ * Fold a recipient's open low-priority events: of every group that says the same kind of thing (same
475
+ * `coalesceKey`, else same kind, run, team and session) only the newest stays open, and it says how many it stands
476
+ * for (`delivery.merged`). The older ones are settled, not deleted: the log keeps them. Critical and normal events
477
+ * are never touched.
478
+ * @returns {{ merged: number, kept: { id: string, seq: number, merged: number }[] }}
479
+ */
480
+ function coalesce(recipient) {
481
+ const who = recipientText(recipient);
482
+ return transaction(() => {
483
+ const rows = db.prepare(`SELECT d.event_id, d.seq, d.merged, e.kind, e.run_id, e.team_id, e.session_id, e.coalesce_key
484
+ FROM deliveries d JOIN events e ON e.id = d.event_id
485
+ WHERE d.recipient = ? AND d.acked_at IS NULL AND e.priority = 'low' ORDER BY d.seq ASC`).all(who);
486
+ const groups = new Map();
487
+ for (const row of rows) {
488
+ const key = row.coalesce_key !== null && row.coalesce_key !== undefined
489
+ ? `key\u0000${row.coalesce_key}`
490
+ : ['kind', row.kind, row.run_id ?? '', row.team_id ?? '', row.session_id ?? ''].join('\u0000');
491
+ if (!groups.has(key)) groups.set(key, []);
492
+ groups.get(key).push(row);
493
+ }
494
+ const settle = db.prepare('UPDATE deliveries SET acked_at = ?, coalesced_into = ? WHERE recipient = ? AND event_id = ? AND acked_at IS NULL');
495
+ const grow = db.prepare('UPDATE deliveries SET merged = merged + ? WHERE recipient = ? AND event_id = ?');
496
+ const at = now();
497
+ let merged = 0;
498
+ const kept = [];
499
+ for (const group of groups.values()) {
500
+ if (group.length < 2) continue;
501
+ const newest = group[group.length - 1];
502
+ let folded = 0;
503
+ for (const older of group.slice(0, -1)) {
504
+ settle.run(at, newest.event_id, who, older.event_id);
505
+ folded += 1 + (Number(older.merged) || 0);
506
+ }
507
+ grow.run(folded, who, newest.event_id);
508
+ merged += group.length - 1;
509
+ kept.push({ id: newest.event_id, seq: Number(newest.seq), merged: (Number(newest.merged) || 0) + folded });
510
+ }
511
+ if (merged) settleCursor(who);
512
+ return { merged, kept };
513
+ });
514
+ }
515
+
516
+ // ── wake-ups ───────────────────────────────────────────────────────────────
517
+ function matchesFilter(filter, notice) {
518
+ if (typeof filter === 'function') return !!filter(notice.event, { recipients: notice.recipients });
519
+ if (!filter) return true;
520
+ const { event, recipients } = notice;
521
+ const among = (wanted, value) => (Array.isArray(wanted) ? wanted.includes(value) : wanted === value);
522
+ if (filter.recipient !== undefined && filter.recipient !== null && !recipients.includes(filter.recipient)) return false;
523
+ if (filter.kinds !== undefined && filter.kinds !== null && !among(filter.kinds, event.kind)) return false;
524
+ if (filter.priority !== undefined && filter.priority !== null && !among(filter.priority, event.priority)) return false;
525
+ for (const field of ['teamId', 'sessionId', 'runId']) {
526
+ if (filter[field] !== undefined && filter[field] !== null && filter[field] !== event[field]) return false;
527
+ }
528
+ return true;
529
+ }
530
+
531
+ /**
532
+ * Tell everyone who listens about committed events, oldest first. An event appended by a listener is told after
533
+ * the one that is being told now, so every listener sees events in seq order.
534
+ */
535
+ function publish(notice) {
536
+ notices.push(notice);
537
+ if (publishing) return;
538
+ publishing = true;
539
+ try {
540
+ while (notices.length) {
541
+ const next = notices.shift();
542
+ for (const subscriber of [...subscribers]) {
543
+ if (!subscribers.has(subscriber)) continue;
544
+ try { if (matchesFilter(subscriber.filter, next)) subscriber.fn(next.event, { recipients: [...next.recipients] }); }
545
+ catch (error) { try { log('coordination:subscriber-error', error?.message || String(error)); } catch { /* a logger must not stop delivery */ } }
546
+ }
547
+ for (const waiter of [...waiters]) {
548
+ if (!waiters.has(waiter)) continue;
549
+ try { if (waiter.matches(next)) waiter.wake(); }
550
+ catch (error) { waiter.finish(null, error); }
551
+ }
552
+ }
553
+ } finally {
554
+ publishing = false;
555
+ }
556
+ }
557
+
558
+ /**
559
+ * Be called for every event appended in this process from now on that matches, right after its transaction
560
+ * committed (never for one that was rolled back, never for a duplicate id). A wake-up, not a delivery: it records
561
+ * nothing and a listener that throws harms nobody else. What must not be missed is read from the mailbox.
562
+ * @param {object|((event: object, info: { recipients: string[] }) => boolean)|null} filter
563
+ * `{ recipient, kinds, priority, teamId, sessionId, runId }` (each optional; `kinds` and `priority` take one or a list), a predicate, or null for every event
564
+ * @param {(event: object, info: { recipients: string[] }) => void} fn
565
+ * @returns {() => void} stop listening
566
+ */
567
+ function subscribe(filter, fn) {
568
+ open();
569
+ if (typeof fn !== 'function') throw fail('SUBSCRIBER_INVALID', 'subscribe needs a function to call.');
570
+ if (isObject(filter) && filter.kinds !== undefined && filter.kinds !== null) kindList(filter.kinds);
571
+ const subscriber = { filter: filter ?? null, fn };
572
+ subscribers.add(subscriber);
573
+ return () => { subscribers.delete(subscriber); };
574
+ }
575
+
576
+ /**
577
+ * Wait until there is something to read, then read it.
578
+ * With `recipient`: the mailbox, like `read` (open events after `afterSeq`, default the cursor). Without one: the
579
+ * log, like `events` (events after `afterSeq`, default the newest now, so only what comes).
580
+ * Resolves at once when something is there already. Never rejects for a timeout: `timedOut: true` and no events.
581
+ * @param {object} query
582
+ * @param {string} [query.recipient]
583
+ * @param {string|string[]} [query.kinds]
584
+ * @param {number} [query.afterSeq]
585
+ * @param {number} [query.timeoutMs] default 30 s, at most 10 minutes; 0 only looks
586
+ * @param {number} [query.limit]
587
+ * @param {string} [query.teamId] the log only
588
+ * @param {string} [query.sessionId] the log only
589
+ * @param {string} [query.runId] the log only
590
+ * @param {AbortSignal} [query.signal] give up early (`aborted: true`)
591
+ * @param {number} [query.pollMs] also look every so often: only for a file another process appends to, which
592
+ * cannot wake this one
593
+ * @returns {Promise<{ events: object[], timedOut: boolean, closed: boolean, aborted: boolean }>}
594
+ */
595
+ function waitFor({ recipient = null, kinds = null, afterSeq = null, timeoutMs = COORDINATION_LIMITS.defaultWaitMs, limit = null, teamId = null, sessionId = null, runId = null, signal = null, pollMs = null } = {}) {
596
+ const answer = (events_, extra = {}) => ({ events: events_, timedOut: false, closed: false, aborted: false, ...extra });
597
+ let look;
598
+ let matches;
599
+ try {
600
+ if (closed) return Promise.resolve(answer([], { closed: true }));
601
+ const list = kindList(kinds);
602
+ if (recipient !== null && recipient !== undefined) {
603
+ const who = recipientText(recipient);
604
+ const from = afterSeq === null || afterSeq === undefined ? cursor(who) : seqOf(afterSeq);
605
+ look = () => read({ recipient: who, afterSeq: from, kinds: list, limit });
606
+ matches = (notice) => notice.event.seq > from && notice.recipients.includes(who) && (!list || list.includes(notice.event.kind));
607
+ } else {
608
+ const from = afterSeq === null || afterSeq === undefined ? lastSeq() : seqOf(afterSeq);
609
+ const scope = { teamId: idText(teamId, 'teamId'), sessionId: idText(sessionId, 'sessionId'), runId: idText(runId, 'runId') };
610
+ look = () => events({ afterSeq: from, kinds: list, limit, ...scope });
611
+ matches = (notice) => notice.event.seq > from && (!list || list.includes(notice.event.kind))
612
+ && Object.entries(scope).every(([field, value]) => value === null || notice.event[field] === value);
613
+ }
614
+ const first = look();
615
+ if (first.length) return Promise.resolve(answer(first));
616
+ } catch (error) {
617
+ return Promise.reject(error);
618
+ }
619
+ const asked = Number(timeoutMs);
620
+ const budget = Math.max(0, Math.min(COORDINATION_LIMITS.maxWaitMs, Number.isFinite(asked) ? asked : COORDINATION_LIMITS.defaultWaitMs));
621
+ if (budget === 0) return Promise.resolve(answer([], { timedOut: true }));
622
+ if (signal?.aborted) return Promise.resolve(answer([], { aborted: true }));
623
+ return new Promise((resolveWait, rejectWait) => {
624
+ let timer = null;
625
+ let poll = null;
626
+ const onAbort = () => waiter.finish(answer([], { aborted: true }));
627
+ const waiter = {
628
+ matches,
629
+ wake() {
630
+ const found = look();
631
+ if (found.length) waiter.finish(answer(found));
632
+ },
633
+ finish(result, error = null) {
634
+ if (!waiters.delete(waiter)) return;
635
+ if (timer) clearTimeout(timer);
636
+ if (poll) clearInterval(poll);
637
+ signal?.removeEventListener?.('abort', onAbort);
638
+ if (error) rejectWait(error); else resolveWait(result);
639
+ },
640
+ };
641
+ waiters.add(waiter);
642
+ // A wait is never what keeps a process alive (a server that is going down, a script that is done): its timers
643
+ // are unreferenced, as the dispatcher's own waits are (lib/assistant-run-wait.js). `close()` answers it.
644
+ timer = setTimeout(() => waiter.finish(answer([], { timedOut: true })), budget);
645
+ timer.unref?.();
646
+ const every = Number(pollMs);
647
+ if (Number.isFinite(every) && every > 0) {
648
+ poll = setInterval(() => { try { waiter.wake(); } catch (error) { waiter.finish(null, error); } }, Math.max(20, every));
649
+ poll.unref?.();
650
+ }
651
+ signal?.addEventListener?.('abort', onAbort, { once: true });
652
+ });
653
+ }
654
+
655
+ // ── claims ─────────────────────────────────────────────────────────────────
656
+ const selectActiveClaims = db.prepare('SELECT * FROM claims WHERE team_id = ? AND released_at IS NULL ORDER BY id ASC');
657
+ const insertClaim = db.prepare('INSERT INTO claims (team_id, slice_id, glob, run_id, created_at) VALUES (?, ?, ?, ?, ?)');
658
+ const moveClaim = db.prepare('UPDATE claims SET run_id = ? WHERE id = ?');
659
+
660
+ function slugText(value, field) {
661
+ if (!isTeamSlug(value)) throw fail('FIELD_INVALID', `${field} is a lower-case name of letters, digits and hyphens (lib/teams/schema.js).`, { field });
662
+ return value;
663
+ }
664
+ function globList(globs, { required = true } = {}) {
665
+ if (globs === null || globs === undefined) {
666
+ if (required) throw fail('FIELD_REQUIRED', 'globs is required: the patterns to claim.', { field: 'globs' });
667
+ return null;
668
+ }
669
+ const list = [...new Set((Array.isArray(globs) ? globs : [globs]).map((glob) => normalizeOwnedPath(glob)))];
670
+ if (!list.length && required) throw fail('FIELD_REQUIRED', 'globs is required: the patterns to claim.', { field: 'globs' });
671
+ if (list.length > COORDINATION_LIMITS.claimGlobs) throw fail('CLAIM_INVALID', `One claim names at most ${COORDINATION_LIMITS.claimGlobs} patterns.`, { field: 'globs' });
672
+ const problems = list.map((glob) => ({ glob, problem: ownedPathProblem(glob) })).filter((entry) => entry.problem);
673
+ if (problems.length) throw fail('CLAIM_INVALID', problems[0].problem.message, { field: 'globs', problems: problems.map(({ glob, problem }) => ({ glob, ...problem })) });
674
+ return list;
675
+ }
676
+
677
+ /**
678
+ * A slice takes files for itself while it works. All of the patterns are taken, or none: when one of them overlaps
679
+ * a pattern another slice of the team holds, nothing is written and the answer names every clash. The same slice
680
+ * claiming a pattern it already holds keeps the one claim (a later run of the slice takes it over).
681
+ * Patterns are owned paths (lib/teams/schema.js): project-relative, `*`, `?` and `**`, never outside the project.
682
+ * @param {object} input
683
+ * @param {string} input.teamId
684
+ * @param {string} input.sliceId
685
+ * @param {string} [input.runId] the run that works the slice now
686
+ * @param {string|string[]} input.globs
687
+ * @returns {{ ok: true, claims: object[] } | { ok: false, code: 'CLAIM_CONFLICT', conflicts: { glob: string, heldBy: object }[] }}
688
+ * @throws {CoordinationError} `CLAIM_INVALID` for a pattern that is not an owned path
689
+ */
690
+ function claim({ teamId, sliceId, runId = null, globs } = {}) {
691
+ const team = slugText(teamId, 'teamId');
692
+ const slice = slugText(sliceId, 'sliceId');
693
+ const run = idText(runId, 'runId');
694
+ const list = globList(globs);
695
+ return transaction(() => {
696
+ const active = selectActiveClaims.all(team);
697
+ const conflicts = [];
698
+ for (const glob of list) {
699
+ for (const row of active) {
700
+ if (row.slice_id !== slice && globsOverlap(glob, row.glob)) conflicts.push({ glob, heldBy: claimView(row) });
701
+ }
702
+ }
703
+ if (conflicts.length) return { ok: false, code: 'CLAIM_CONFLICT', conflicts };
704
+ const at = now();
705
+ const claims = list.map((glob) => {
706
+ const mine = active.find((row) => row.slice_id === slice && row.glob === glob);
707
+ if (mine) {
708
+ if (run && mine.run_id !== run) { moveClaim.run(run, mine.id); mine.run_id = run; }
709
+ return claimView(mine);
710
+ }
711
+ const id = Number(insertClaim.run(team, slice, glob, run, at).lastInsertRowid);
712
+ return claimView({ id, team_id: team, slice_id: slice, glob, run_id: run, created_at: at, released_at: null });
713
+ });
714
+ return { ok: true, claims };
715
+ });
716
+ }
717
+
718
+ /**
719
+ * Give claims back. `teamId` alone releases the whole team's; `sliceId`, `runId` and `globs` narrow it.
720
+ * @returns {{ released: number }}
721
+ */
722
+ function release({ teamId, sliceId = null, runId = null, globs = null } = {}) {
723
+ const where = ['team_id = ?', 'released_at IS NULL'];
724
+ const args = [slugText(teamId, 'teamId')];
725
+ if (sliceId !== null && sliceId !== undefined) { where.push('slice_id = ?'); args.push(slugText(sliceId, 'sliceId')); }
726
+ const run = idText(runId, 'runId');
727
+ if (run !== null) { where.push('run_id = ?'); args.push(run); }
728
+ const list = globList(globs, { required: false });
729
+ if (list && !list.length) return { released: 0 };
730
+ if (list) { where.push(`glob IN (${list.map(() => '?').join(', ')})`); args.push(...list); }
731
+ return transaction(() => ({ released: Number(db.prepare(`UPDATE claims SET released_at = ? WHERE ${where.join(' AND ')}`).run(now(), ...args).changes) || 0 }));
732
+ }
733
+
734
+ /**
735
+ * The claims of a team, oldest first. `path`: only those that hold this project-relative file ("who has it?").
736
+ * @param {object} query
737
+ * @param {string} query.teamId
738
+ * @param {string} [query.sliceId]
739
+ * @param {string} [query.runId]
740
+ * @param {string} [query.path]
741
+ * @param {boolean} [query.includeReleased] also claims given back (history)
742
+ */
743
+ function claimsFor({ teamId, sliceId = null, runId = null, path = null, includeReleased = false } = {}) {
744
+ open();
745
+ const where = ['team_id = ?'];
746
+ const args = [slugText(teamId, 'teamId')];
747
+ if (!includeReleased) where.push('released_at IS NULL');
748
+ if (sliceId !== null && sliceId !== undefined) { where.push('slice_id = ?'); args.push(slugText(sliceId, 'sliceId')); }
749
+ const run = idText(runId, 'runId');
750
+ if (run !== null) { where.push('run_id = ?'); args.push(run); }
751
+ let rows = db.prepare(`SELECT * FROM claims WHERE ${where.join(' AND ')} ORDER BY id ASC`).all(...args);
752
+ if (path !== null && path !== undefined) {
753
+ const file = normalizeRelPath(path);
754
+ if (file === null) throw fail('FIELD_INVALID', 'path is a file path relative to the project.', { field: 'path' });
755
+ rows = rows.filter((row) => matchesOwnedPath(row.glob, file));
756
+ }
757
+ return rows.map(claimView);
758
+ }
759
+
760
+ // ── the journal of team tasks ──────────────────────────────────────────────
761
+ const insertJournal = db.prepare('INSERT INTO team_tasks (team_id, slice_id, state, run_id, data, created_at) VALUES (?, ?, ?, ?, ?, ?)');
762
+
763
+ function stateText(value) {
764
+ if (typeof value !== 'string' || !/^[a-z][a-z0-9_-]{0,39}$/.test(value)) throw fail('FIELD_INVALID', `state is a lower-case name of at most ${COORDINATION_LIMITS.state} characters, like "running".`, { field: 'state' });
765
+ return value;
766
+ }
767
+
768
+ const journal = Object.freeze({
769
+ /**
770
+ * Record that a team (no `sliceId`) or one of its slices is in a state now. Entries are only ever added: the
771
+ * newest one of a team or slice is its state, the ones before it are how it got there.
772
+ * @param {{ teamId: string, sliceId?: string|null, state: string, runId?: string|null, data?: object, claimGlobs?: string[] }} entry
773
+ * `data`: what recovery needs to carry on (the plan, a branch, a commit, an error), JSON, at most 64 KB
774
+ * @returns {object} the entry as stored
775
+ */
776
+ write({ teamId, sliceId = null, state, runId = null, data = {}, claimGlobs = null } = {}) {
777
+ const team = slugText(teamId, 'teamId');
778
+ const slice = sliceId === null || sliceId === undefined || sliceId === '' ? '' : slugText(sliceId, 'sliceId');
779
+ const name = stateText(state);
780
+ const run = idText(runId, 'runId');
781
+ if (!isObject(data)) throw fail('FIELD_INVALID', 'data is an object.', { field: 'data' });
782
+ const body = jsonText(data, 'data', COORDINATION_LIMITS.journalDataBytes);
783
+ return transaction(() => {
784
+ // A running slice's ownership amendment and its write claims must survive a restart together.
785
+ if (claimGlobs) {
786
+ const result = claim({ teamId: team, sliceId: slice, runId: run, globs: claimGlobs });
787
+ if (!result.ok) throw fail('CLAIM_CONFLICT', 'Another slice holds a requested path.', { conflicts: result.conflicts });
788
+ }
789
+ const at = now();
790
+ const id = Number(insertJournal.run(team, slice, name, run, body, at).lastInsertRowid);
791
+ return journalView({ id, team_id: team, slice_id: slice, state: name, run_id: run, data: body, created_at: at });
792
+ });
793
+ },
794
+ /**
795
+ * A team's entries, oldest first. `sliceId` undefined: the team's and every slice's; null: the team's own only.
796
+ * @param {{ teamId: string, sliceId?: string|null, afterId?: number, limit?: number }} query
797
+ */
798
+ read({ teamId, sliceId, afterId = 0, limit = null } = {}) {
799
+ open();
800
+ const where = ['team_id = ?', 'id > ?'];
801
+ const args = [slugText(teamId, 'teamId'), seqOf(afterId, 'afterId')];
802
+ if (sliceId !== undefined) { where.push('slice_id = ?'); args.push(sliceId === null || sliceId === '' ? '' : slugText(sliceId, 'sliceId')); }
803
+ return db.prepare(`SELECT * FROM team_tasks WHERE ${where.join(' AND ')} ORDER BY id ASC LIMIT ?`).all(...args, limitOf(limit, 500)).map(journalView);
804
+ },
805
+ /**
806
+ * Where a team stands: its own newest entry and the newest entry of each slice.
807
+ * @returns {{ teamId: string, team: object|null, slices: Record<string, object> }}
808
+ */
809
+ state(teamId) {
810
+ open();
811
+ const rows = db.prepare('SELECT * FROM team_tasks WHERE id IN (SELECT MAX(id) FROM team_tasks WHERE team_id = ? GROUP BY slice_id) ORDER BY id ASC').all(slugText(teamId, 'teamId'));
812
+ const out = { teamId, team: null, slices: {} };
813
+ for (const row of rows) {
814
+ if (row.slice_id) out.slices[row.slice_id] = journalView(row);
815
+ else out.team = journalView(row);
816
+ }
817
+ return out;
818
+ },
819
+ /**
820
+ * Every team the journal knows, by its own newest entry, oldest team first. `states`: only teams whose newest
821
+ * state is one of these (after a restart: the teams that were under way).
822
+ * @param {{ states?: string[] }} [query]
823
+ */
824
+ teams({ states = null } = {}) {
825
+ open();
826
+ const rows = db.prepare("SELECT * FROM team_tasks WHERE id IN (SELECT MAX(id) FROM team_tasks WHERE slice_id = '' GROUP BY team_id) ORDER BY id ASC").all();
827
+ const wanted = Array.isArray(states) ? new Set(states) : null;
828
+ return rows.filter((row) => !wanted || wanted.has(row.state)).map(journalView);
829
+ },
830
+ });
831
+
832
+ // ── the outbox: follow-ups for runs ────────────────────────────────────────
833
+ const selectOutboxById = db.prepare('SELECT * FROM outbox WHERE id = ?');
834
+ const insertOutbox = db.prepare('INSERT INTO outbox (id, run_id, text, session_id, meta, created_at) VALUES (?, ?, ?, ?, ?, ?)');
835
+ const selectUnsent = db.prepare('SELECT * FROM outbox WHERE run_id = ? AND sent_at IS NULL ORDER BY n ASC LIMIT ?');
836
+ const countAttempt = db.prepare('UPDATE outbox SET attempts = attempts + 1 WHERE id = ?');
837
+ const markSent = db.prepare('UPDATE outbox SET sent_at = ? WHERE id = ? AND sent_at IS NULL');
838
+ const countUnsent = db.prepare('SELECT COUNT(*) AS n FROM outbox WHERE run_id = ? AND sent_at IS NULL');
839
+ const selectAllUnsent = db.prepare('SELECT * FROM outbox WHERE run_id = ? AND sent_at IS NULL ORDER BY n ASC');
840
+ const deleteUnsent = db.prepare('DELETE FROM outbox WHERE id = ? AND sent_at IS NULL');
841
+
842
+ const outbox = Object.freeze({
843
+ /**
844
+ * Queue a follow-up for a run. It stays queued until `markSent` says the run took it, across restarts.
845
+ * @param {{ id?: string, runId: string, text: string, sessionId?: string|null, meta?: object, maxQueued?: number }} item
846
+ * `id`: the caller's own; queueing it again stores nothing new (`duplicate: true`)
847
+ * `maxQueued`: the admission bound: with that many of the run's items still unsent, nothing is stored and
848
+ * `OUTBOX_FULL` (409, with `queued` and `limit`) is thrown
849
+ * @returns {{ id: string, duplicate: boolean }}
850
+ */
851
+ enqueue({ id = null, runId, text, sessionId = null, meta = {}, maxQueued = null } = {}) {
852
+ const run = idText(runId, 'runId', { required: true });
853
+ if (typeof text !== 'string' || !text.trim()) throw fail('FIELD_REQUIRED', 'text is required: what the run is told.', { field: 'text' });
854
+ if (text.length > COORDINATION_LIMITS.outboxText) throw fail('FIELD_INVALID', `text is at most ${COORDINATION_LIMITS.outboxText} characters.`, { field: 'text' });
855
+ const session = idText(sessionId, 'sessionId');
856
+ if (!isObject(meta)) throw fail('FIELD_INVALID', 'meta is an object.', { field: 'meta' });
857
+ const body = jsonText(meta, 'meta', COORDINATION_LIMITS.journalDataBytes);
858
+ const key = idText(id, 'id') || String(newId());
859
+ const bound = maxQueued === null || maxQueued === undefined ? null : Math.floor(Number(maxQueued));
860
+ if (bound !== null && (!Number.isFinite(bound) || bound < 1)) throw fail('FIELD_INVALID', 'maxQueued is a whole number from 1.', { field: 'maxQueued' });
861
+ return transaction(() => {
862
+ if (selectOutboxById.get(key)) return { id: key, duplicate: true };
863
+ const queued = bound === null ? 0 : Number(countUnsent.get(run)?.n) || 0;
864
+ if (bound !== null && queued >= bound) {
865
+ throw fail('OUTBOX_FULL', `Run ${run} already has ${queued} follow-up${queued === 1 ? '' : 's'} waiting (at most ${bound}): wait until it took some, or send one message that says it all.`, { status: 409, runId: run, queued, limit: bound });
866
+ }
867
+ insertOutbox.run(key, run, text, session, body, now());
868
+ return { id: key, duplicate: false };
869
+ });
870
+ },
871
+ /** How many of a run's items are still unsent. */
872
+ count(runId) {
873
+ open();
874
+ return Number(countUnsent.get(idText(runId, 'runId', { required: true }))?.n) || 0;
875
+ },
876
+ /**
877
+ * Take unsent items out of the queue for good: the run ended, or was stopped, before it could take them. Sent
878
+ * items are left alone. `ids` narrows it to those of the run's items.
879
+ * @param {{ runId: string, ids?: string[] }} query
880
+ * @returns {{ cancelled: object[] }} the items that were removed, in the order they were queued
881
+ */
882
+ cancel({ runId, ids = null } = {}) {
883
+ const run = idText(runId, 'runId', { required: true });
884
+ const only = ids === null || ids === undefined ? null : new Set((Array.isArray(ids) ? ids : [ids]).map((id) => String(id)));
885
+ return transaction(() => {
886
+ const rows = selectAllUnsent.all(run).filter((row) => !only || only.has(row.id));
887
+ for (const row of rows) deleteUnsent.run(row.id);
888
+ return { cancelled: rows.map(outboxView) };
889
+ });
890
+ },
891
+ /**
892
+ * What is queued for a run and not sent yet, in the order it was queued. Taking marks nothing as sent: an item
893
+ * comes back from every take until `markSent` names it (a crash between the two sends it again, never loses it).
894
+ * @param {string} runId
895
+ * @param {{ limit?: number }} [options]
896
+ */
897
+ take(runId, { limit = null } = {}) {
898
+ const run = idText(runId, 'runId', { required: true });
899
+ return transaction(() => {
900
+ const rows = selectUnsent.all(run, limitOf(limit));
901
+ for (const row of rows) { countAttempt.run(row.id); row.attempts = (Number(row.attempts) || 0) + 1; }
902
+ return rows.map(outboxView);
903
+ });
904
+ },
905
+ /** These items reached their run. @returns {{ sent: number }} */
906
+ markSent(ids) {
907
+ const list = (Array.isArray(ids) ? ids : [ids]).filter((id) => id !== null && id !== undefined).map((id) => String(id));
908
+ return transaction(() => {
909
+ const at = now();
910
+ let sent = 0;
911
+ for (const id of new Set(list)) sent += Number(markSent.run(at, id).changes) || 0;
912
+ return { sent };
913
+ });
914
+ },
915
+ /** One item by its id, or null. */
916
+ get(id) {
917
+ open();
918
+ const row = selectOutboxById.get(String(id));
919
+ return row ? outboxView(row) : null;
920
+ },
921
+ /** The runs that have something queued (after a restart: who still has to be told something). */
922
+ runs() {
923
+ open();
924
+ return db.prepare('SELECT run_id FROM outbox WHERE sent_at IS NULL GROUP BY run_id ORDER BY MIN(n) ASC').all().map((row) => row.run_id);
925
+ },
926
+ });
927
+
928
+ // ── housekeeping ───────────────────────────────────────────────────────────
929
+ /**
930
+ * Drop what is settled and old: events older than `olderThanMs` whose every delivery is acknowledged (their
931
+ * deliveries go with them), claims given back that long ago, outbox items sent that long ago. An event somebody
932
+ * has not acknowledged is kept however old it is; the journal is never pruned.
933
+ * @returns {{ events: number, claims: number, outbox: number }}
934
+ */
935
+ function prune({ olderThanMs = 14 * 24 * 60 * 60 * 1000 } = {}) {
936
+ const age = Number(olderThanMs);
937
+ if (!Number.isFinite(age) || age < 0) throw fail('FIELD_INVALID', 'olderThanMs must be a number of milliseconds.', { field: 'olderThanMs' });
938
+ return transaction(() => {
939
+ const before = now() - age;
940
+ return {
941
+ events: Number(db.prepare('DELETE FROM events WHERE created_at < ? AND NOT EXISTS (SELECT 1 FROM deliveries d WHERE d.event_id = events.id AND d.acked_at IS NULL)').run(before).changes) || 0,
942
+ claims: Number(db.prepare('DELETE FROM claims WHERE released_at IS NOT NULL AND released_at < ?').run(before).changes) || 0,
943
+ outbox: Number(db.prepare('DELETE FROM outbox WHERE sent_at IS NOT NULL AND sent_at < ?').run(before).changes) || 0,
944
+ };
945
+ });
946
+ }
947
+
948
+ /** Counts for a diagnostics view. */
949
+ function stats() {
950
+ open();
951
+ const count = (sql) => Number(db.prepare(sql).get()?.n) || 0;
952
+ return {
953
+ schemaVersion,
954
+ events: count('SELECT COUNT(*) AS n FROM events'),
955
+ lastSeq: lastSeq(),
956
+ openDeliveries: count('SELECT COUNT(*) AS n FROM deliveries WHERE acked_at IS NULL'),
957
+ activeClaims: count('SELECT COUNT(*) AS n FROM claims WHERE released_at IS NULL'),
958
+ queuedFollowUps: count('SELECT COUNT(*) AS n FROM outbox WHERE sent_at IS NULL'),
959
+ journalEntries: count('SELECT COUNT(*) AS n FROM team_tasks'),
960
+ subscribers: subscribers.size,
961
+ waiters: waiters.size,
962
+ };
963
+ }
964
+
965
+ /** The schema versions applied to this file, oldest first. */
966
+ function appliedMigrations() {
967
+ open();
968
+ return db.prepare('SELECT version, name, applied_at FROM migrations ORDER BY version ASC').all().map((row) => ({ version: Number(row.version), name: row.name, appliedAt: iso(row.applied_at) }));
969
+ }
970
+
971
+ /**
972
+ * Stop: everyone waiting is answered (`closed: true`), listeners are dropped and the file is closed. What was not
973
+ * acknowledged stays in the file and is handed out again by the next store opened on it. Safe to call twice.
974
+ */
975
+ function close() {
976
+ if (closed) return;
977
+ closed = true;
978
+ for (const waiter of [...waiters]) waiter.finish({ events: [], timedOut: false, closed: true, aborted: false });
979
+ subscribers.clear();
980
+ notices.length = 0;
981
+ try { db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch { /* another connection reads it: the WAL stays, nothing is lost */ }
982
+ try { db.close(); } catch (error) { try { log('coordination:close-error', error?.message || String(error)); } catch { /* nothing to tell */ } }
983
+ }
984
+
985
+ const query = fn => (...args) => retry(() => fn(...args));
986
+ return Object.freeze({
987
+ path,
988
+ activeClaimTeams: query(() => db.prepare('SELECT DISTINCT team_id FROM claims WHERE released_at IS NULL').all().map(row => row.team_id)),
989
+ schemaVersion,
990
+ append, appendMany, get: query(get), events: query(events), lastSeq: query(lastSeq),
991
+ read, pending, ack, ackThrough, cursor: query(cursor), coalesce, openCount: query(openCount), recipients: query(recipients),
992
+ subscribe, waitFor,
993
+ claim, release, claimsFor: query(claimsFor),
994
+ journal: { ...journal, read: query(journal.read), state: query(journal.state), teams: query(journal.teams) },
995
+ outbox: { ...outbox, count: query(outbox.count), get: query(outbox.get), runs: query(outbox.runs) },
996
+ prune, stats: query(stats), appliedMigrations: query(appliedMigrations), close,
997
+ get closed() { return closed; },
998
+ });
999
+ }