@bastani/atomic 0.10.11-alpha.2 → 0.10.11-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (447) hide show
  1. package/CHANGELOG.md +150 -0
  2. package/README.md +5 -8
  3. package/dist/_shared/dist-KOELCESV.js +2 -2
  4. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  5. package/dist/_shared/lib-4PES5P4V.js +2 -2
  6. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +6 -6
  7. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +5 -5
  8. package/dist/_shared/mode-shared-2QJSCUM6.js +6 -6
  9. package/dist/_shared/p0-cli-BB45ZQY6.js +46 -67
  10. package/dist/_shared/p0-cli-BB45ZQY6.js.map +1 -1
  11. package/dist/_shared/p1a-prewarm-XIU57JHF.js +7 -8
  12. package/dist/_shared/p1a-prewarm-XIU57JHF.js.map +1 -1
  13. package/dist/_shared/{p1b-elig-ENCUPKKJ.js → p1b-elig-TVB5CBLL.js} +36 -8
  14. package/dist/_shared/p1b-elig-TVB5CBLL.js.map +1 -0
  15. package/dist/_shared/p2-shell-main-B2WIALFD.js +6 -3
  16. package/dist/_shared/p2-shell-main-B2WIALFD.js.map +1 -1
  17. package/dist/_shared/runtime-O4KCSG4C.js +3 -3
  18. package/dist/_shared/{sdk-IQMULKFU.js → sdk-B5LEWGGI.js} +1218 -657
  19. package/dist/_shared/sdk-B5LEWGGI.js.map +1 -0
  20. package/dist/_shared/session-data-AHTU7IS6.js +2 -2
  21. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  22. package/dist/_shared/{startup-0-0-3IXNMFM2.js → startup-0-0-XJJDOIEC.js} +50 -48
  23. package/dist/_shared/startup-0-0-XJJDOIEC.js.map +1 -0
  24. package/dist/_shared/{startup-0-1-7T2IAE7J.js → startup-0-1-M6OWAYHH.js} +540 -136
  25. package/dist/_shared/startup-0-1-M6OWAYHH.js.map +1 -0
  26. package/dist/_shared/startup-0-2-5QHPCEON.js +47 -48
  27. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -1
  28. package/dist/_shared/startup-0-3-4ZYBYQNM.js +5 -5
  29. package/dist/_shared/startup-0-4-ZMJV547D.js +12 -7
  30. package/dist/_shared/startup-0-4-ZMJV547D.js.map +1 -1
  31. package/dist/_shared/startup-0-5-YDW47QX6.js +7 -7
  32. package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -1
  33. package/dist/_shared/startup-10-0-TDQNBDDL.js +6 -6
  34. package/dist/_shared/startup-12-0-55AAXBJZ.js +2 -2
  35. package/dist/_shared/startup-14-0-MLX36RBG.js +4 -5
  36. package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
  37. package/dist/_shared/startup-15-0-YUKGAC63.js +4 -4
  38. package/dist/_shared/startup-15-1-4S7FLMNG.js +19 -27
  39. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  40. package/dist/_shared/startup-8-0-34CBHPZH.js +2144 -249
  41. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  42. package/dist/_shared/{startup-8-1-X32CYSXB.js → startup-8-1-LZFXSD3Z.js} +98 -1184
  43. package/dist/_shared/startup-8-1-LZFXSD3Z.js.map +1 -0
  44. package/dist/_shared/storage-command-7MGXLJGZ.js +188 -37
  45. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  46. package/dist/_shared/storage-status-K7PX2RXA.js +557 -0
  47. package/dist/_shared/storage-status-K7PX2RXA.js.map +1 -0
  48. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  49. package/dist/_shared/team-DOQKICG2.js +376 -0
  50. package/dist/_shared/team-DOQKICG2.js.map +1 -0
  51. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  52. package/dist/builtin/intercom/CHANGELOG.md +42 -0
  53. package/dist/builtin/intercom/README.md +2 -2
  54. package/dist/builtin/intercom/broker/broker.bundle.mjs +1917 -381
  55. package/dist/builtin/intercom/broker/client.ts +8 -0
  56. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +324 -68
  57. package/dist/builtin/intercom/broker/multinode-router.ts +256 -39
  58. package/dist/builtin/intercom/broker/multinode-state-store.ts +71 -5
  59. package/dist/builtin/intercom/broker/open-broker-state.ts +14 -0
  60. package/dist/builtin/intercom/broker/send-order-gate.ts +5 -2
  61. package/dist/builtin/intercom/broker/sql-add-column.ts +50 -5
  62. package/dist/builtin/intercom/broker/sql-ended-child-queue-store.ts +3 -2
  63. package/dist/builtin/intercom/broker/sql-held-send-store.ts +2 -2
  64. package/dist/builtin/intercom/broker/sql-known-session-store.ts +43 -19
  65. package/dist/builtin/intercom/broker/sql-lease-store.ts +473 -121
  66. package/dist/builtin/intercom/broker/sql-outbox-store.ts +821 -79
  67. package/dist/builtin/intercom/broker/sql-pending-ask-store.ts +8 -5
  68. package/dist/builtin/intercom/broker/sql-released-ask-store.ts +12 -5
  69. package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +256 -8
  70. package/dist/builtin/intercom/broker/sql-retention.ts +150 -0
  71. package/dist/builtin/intercom/broker/sql-schema.ts +175 -24
  72. package/dist/builtin/intercom/broker/sql-sent-message-authority.ts +74 -19
  73. package/dist/builtin/intercom/broker/wake-up-bus.ts +6 -0
  74. package/dist/builtin/intercom/index.bundle.mjs +14 -4
  75. package/dist/builtin/intercom/package.json +1 -1
  76. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  77. package/dist/builtin/mcp/package.json +1 -1
  78. package/dist/builtin/subagents/CHANGELOG.md +6 -0
  79. package/dist/builtin/subagents/package.json +1 -1
  80. package/dist/builtin/subagents/skills/skill-creator/eval-viewer/generate_review.py +8 -1
  81. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  82. package/dist/builtin/web-access/index.bundle.mjs +2 -10
  83. package/dist/builtin/web-access/package.json +1 -1
  84. package/dist/bun/bundled-sqlite.js +41 -0
  85. package/dist/bun/bundled-sqlite.js.map +1 -0
  86. package/dist/cli/args.js +2 -2
  87. package/dist/cli/auth-cli.code.js +4 -4
  88. package/dist/cli/auth-cli.impl.js +3 -3
  89. package/dist/cli/auth-cli.js +3 -3
  90. package/dist/cli/blueprint-command.code.js +3 -3
  91. package/dist/cli/blueprint-command.impl.js +3 -3
  92. package/dist/cli/blueprint-command.js +3 -3
  93. package/dist/cli/intercom-command.code.js +3 -3
  94. package/dist/cli/intercom-command.code.js.map +1 -1
  95. package/dist/cli/intercom-command.impl.js +3 -3
  96. package/dist/cli/intercom-command.js +3 -3
  97. package/dist/cli/list-models.code.js +2 -2
  98. package/dist/cli/list-models.impl.js +3 -3
  99. package/dist/cli/list-models.js +3 -3
  100. package/dist/cli/session-picker.code.js +1 -1
  101. package/dist/cli/session-picker.impl.js +3 -3
  102. package/dist/cli/session-picker.js +3 -3
  103. package/dist/cli/startup-ui.code.js +1 -1
  104. package/dist/cli/startup-ui.impl.js +3 -3
  105. package/dist/cli/startup-ui.js +3 -3
  106. package/dist/cli/storage-command.impl.js +3 -3
  107. package/dist/cli/storage-command.js +3 -3
  108. package/dist/cli/storage-search-session.code.js +3 -3
  109. package/dist/cli/storage-search-session.impl.js +3 -3
  110. package/dist/cli/storage-search-session.js +3 -3
  111. package/dist/cli/team-command.code.js +19 -113
  112. package/dist/cli/team-command.code.js.map +1 -1
  113. package/dist/cli/team-command.impl.js +3 -3
  114. package/dist/cli/team-command.js +3 -3
  115. package/dist/cli.js +5 -18
  116. package/dist/cli.js.map +1 -1
  117. package/dist/core/agent-rehydrate-errors.d.ts +4 -9
  118. package/dist/core/compaction/compactor.d.ts +3 -3
  119. package/dist/core/debug.code.js +1 -1
  120. package/dist/core/debug.impl.js +3 -3
  121. package/dist/core/debug.js +3 -3
  122. package/dist/core/export-html/card-projection.impl.js +3 -3
  123. package/dist/core/export-html/card-projection.js +3 -3
  124. package/dist/core/export-html/index.code.js +4 -4
  125. package/dist/core/export-html/index.code.js.map +1 -1
  126. package/dist/core/export-html/index.impl.js +3 -3
  127. package/dist/core/export-html/index.js +3 -3
  128. package/dist/core/export-html/json-spans.impl.js +3 -3
  129. package/dist/core/export-html/json-spans.js +3 -3
  130. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  131. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  132. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  133. package/dist/core/export-html/tool-renderer.js +3 -3
  134. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  135. package/dist/core/extensions/jiti-loader.js +3 -3
  136. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  137. package/dist/core/extensions/jiti-static-loader.js +3 -3
  138. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  139. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  140. package/dist/core/extensions/loader-host-modules.js +3 -3
  141. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  142. package/dist/core/extensions/runner-context.js +2 -2
  143. package/dist/core/intercom-broker-control-host.code.js +2 -2
  144. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  145. package/dist/core/intercom-broker-control-host.js +3 -3
  146. package/dist/core/intercom-broker-control.code.js +3 -3
  147. package/dist/core/intercom-broker-control.impl.js +3 -3
  148. package/dist/core/intercom-broker-control.js +3 -3
  149. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  150. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  151. package/dist/core/package-manager-storage-adapters.js +3 -3
  152. package/dist/core/process-start-token.d.ts +12 -3
  153. package/dist/core/process-tree-containment.d.ts +16 -0
  154. package/dist/core/sdk-types.d.ts +1 -2
  155. package/dist/core/sdk-types.js.map +1 -1
  156. package/dist/core/sdk.code.js +3 -3
  157. package/dist/core/sdk.impl.js +3 -3
  158. package/dist/core/sdk.js +3 -3
  159. package/dist/core/session-manager-core.js +5 -5
  160. package/dist/core/session-manager-list.impl.js +3 -3
  161. package/dist/core/session-manager-list.js +3 -3
  162. package/dist/core/session-manager.code.js +1 -1
  163. package/dist/core/session-manager.impl.js +3 -3
  164. package/dist/core/session-manager.js +3 -3
  165. package/dist/core/session-storage.code.js +1 -1
  166. package/dist/core/session-storage.impl.js +3 -3
  167. package/dist/core/session-storage.js +3 -3
  168. package/dist/core/settings-schema.d.ts +0 -3
  169. package/dist/core/storage/added-exports-0-10-11.js +19 -0
  170. package/dist/core/storage/added-exports-0-10-11.js.map +1 -0
  171. package/dist/core/storage/creation-time.js +105 -0
  172. package/dist/core/storage/creation-time.js.map +1 -0
  173. package/dist/core/storage/database.d.ts +25 -5
  174. package/dist/core/storage/database.js.map +1 -1
  175. package/dist/core/storage/dialect.d.ts +1 -1
  176. package/dist/core/storage/dialect.js +1 -1
  177. package/dist/core/storage/dialect.js.map +1 -1
  178. package/dist/core/storage/errors.d.ts +13 -13
  179. package/dist/core/storage/errors.js +10 -16
  180. package/dist/core/storage/errors.js.map +1 -1
  181. package/dist/core/storage/fenced-paths.d.ts +18 -6
  182. package/dist/core/storage/fenced-paths.js +18 -6
  183. package/dist/core/storage/fenced-paths.js.map +1 -1
  184. package/dist/core/storage/file-identity.d.ts +2 -0
  185. package/dist/core/storage/file-identity.js +24 -8
  186. package/dist/core/storage/file-identity.js.map +1 -1
  187. package/dist/core/storage/index.d.ts +3 -2
  188. package/dist/core/storage/index.js +5 -3
  189. package/dist/core/storage/index.js.map +1 -1
  190. package/dist/core/storage/libsql-removed.d.ts +71 -0
  191. package/dist/core/storage/libsql-removed.js +123 -0
  192. package/dist/core/storage/libsql-removed.js.map +1 -0
  193. package/dist/core/storage/migrations.d.ts +78 -14
  194. package/dist/core/storage/migrations.js +375 -49
  195. package/dist/core/storage/migrations.js.map +1 -1
  196. package/dist/core/storage/node-sqlite-file-gate.js +0 -15
  197. package/dist/core/storage/node-sqlite-file-gate.js.map +1 -1
  198. package/dist/core/storage/node-sqlite-thread.js +215 -30
  199. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  200. package/dist/core/storage/node-sqlite.js +484 -72
  201. package/dist/core/storage/node-sqlite.js.map +1 -1
  202. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  203. package/dist/core/storage/offline-snapshot-file.js +3 -3
  204. package/dist/core/storage/prefix.d.ts +1 -1
  205. package/dist/core/storage/prefix.js +9 -2
  206. package/dist/core/storage/prefix.js.map +1 -1
  207. package/dist/core/storage/process-selection.d.ts +5 -5
  208. package/dist/core/storage/provider.js +2 -2
  209. package/dist/core/storage/schema-catalog.d.ts +76 -15
  210. package/dist/core/storage/schema-catalog.js +359 -68
  211. package/dist/core/storage/schema-catalog.js.map +1 -1
  212. package/dist/core/storage/selection.d.ts +7 -82
  213. package/dist/core/storage/selection.js +20 -235
  214. package/dist/core/storage/selection.js.map +1 -1
  215. package/dist/core/storage/session/branch-fork-source.code.js +2 -2
  216. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  217. package/dist/core/storage/session/branch-fork-source.js +3 -3
  218. package/dist/core/storage/session/card-view.impl.js +3 -3
  219. package/dist/core/storage/session/card-view.js +3 -3
  220. package/dist/core/storage/session/child-reader.code.js +3 -3
  221. package/dist/core/storage/session/child-reader.impl.js +3 -3
  222. package/dist/core/storage/session/child-reader.js +3 -3
  223. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  224. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  225. package/dist/core/storage/session/expanded-child-details.code.js +2 -2
  226. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  227. package/dist/core/storage/session/expanded-child-details.js +3 -3
  228. package/dist/core/storage/session/fork-detach.d.ts +11 -1
  229. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  230. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  231. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  232. package/dist/core/storage/session/fork-row-index.js +3 -3
  233. package/dist/core/storage/session/fork-staging.code.js +4 -7
  234. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  235. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  236. package/dist/core/storage/session/fork-staging.js +3 -3
  237. package/dist/core/storage/session/fork-sweep.js +31 -7
  238. package/dist/core/storage/session/fork-sweep.js.map +1 -1
  239. package/dist/core/storage/session/fork-window.code.js +3 -3
  240. package/dist/core/storage/session/fork-window.impl.js +3 -3
  241. package/dist/core/storage/session/fork-window.js +3 -3
  242. package/dist/core/storage/session/history-pages.impl.js +3 -3
  243. package/dist/core/storage/session/history-pages.js +3 -3
  244. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  245. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  246. package/dist/core/storage/session/jsonl-session-lock.d.ts +100 -0
  247. package/dist/core/storage/session/jsonl-session-store.d.ts +46 -24
  248. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  249. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  250. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  251. package/dist/core/storage/session/memory-session-store.js +3 -3
  252. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  253. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  254. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  255. package/dist/core/storage/session/released-history-files.code.js +9 -9
  256. package/dist/core/storage/session/released-history-files.code.js.map +1 -1
  257. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  258. package/dist/core/storage/session/released-history-files.js +3 -3
  259. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  260. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  261. package/dist/core/storage/session/session-resume.impl.js +3 -3
  262. package/dist/core/storage/session/session-resume.js +3 -3
  263. package/dist/core/storage/session/session-search-index.d.ts +52 -5
  264. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  265. package/dist/core/storage/session/snapshot-cut.js +3 -3
  266. package/dist/core/storage/session/snapshot-history.code.js +3 -3
  267. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  268. package/dist/core/storage/session/snapshot-history.js +3 -3
  269. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  270. package/dist/core/storage/session/sql-session-store.d.ts +99 -18
  271. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  272. package/dist/core/storage/session/sql-session-store.js +3 -3
  273. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  274. package/dist/core/storage/session/tree-outline.js +3 -3
  275. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  276. package/dist/core/storage/session/tree-presentation.js +3 -3
  277. package/dist/core/storage/sqlite-facade.d.ts +12 -1
  278. package/dist/core/storage/sqlite-facade.js +310 -33
  279. package/dist/core/storage/sqlite-facade.js.map +1 -1
  280. package/dist/core/storage/sqlite-open-batch.js +10 -0
  281. package/dist/core/storage/sqlite-open-batch.js.map +1 -0
  282. package/dist/core/storage/storage-status.code.js +1 -1
  283. package/dist/core/storage/storage-status.impl.js +3 -3
  284. package/dist/core/storage/storage-status.js +3 -3
  285. package/dist/core/storage/team.code.js +1 -1
  286. package/dist/core/storage/team.d.ts +26 -115
  287. package/dist/core/storage/team.impl.js +3 -3
  288. package/dist/core/storage/team.js +3 -3
  289. package/dist/core/structured-output/index.code.js +1 -1
  290. package/dist/core/structured-output/index.impl.js +3 -3
  291. package/dist/core/structured-output/index.js +3 -3
  292. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  293. package/dist/core/tasks/task-completion-entry.js +3 -3
  294. package/dist/core/tasks/task-file-history.code.js +3 -3
  295. package/dist/core/tasks/task-file-history.impl.js +3 -3
  296. package/dist/core/tasks/task-file-history.js +3 -3
  297. package/dist/core/tasks/task-reference-archive.code.js +4 -4
  298. package/dist/core/tasks/task-reference-archive.js +3 -3
  299. package/dist/core/tasks/task-reference-identity.js +3 -3
  300. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  301. package/dist/core/tasks/task-reference-stream.js +3 -3
  302. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  303. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  304. package/dist/core/tasks/task-view-source.code.js +1 -1
  305. package/dist/core/tasks/task-view-source.impl.js +3 -3
  306. package/dist/core/tasks/task-view-source.js +3 -3
  307. package/dist/core/tools/history-tasks.d.ts +3 -2
  308. package/dist/core/tools/read-url.code.js +4 -4
  309. package/dist/core/tools/read-url.impl.js +3 -3
  310. package/dist/core/tools/read-url.js +3 -3
  311. package/dist/core/worktree-snapshot/blob-store.d.ts +44 -5
  312. package/dist/core/worktree-snapshot/blob-store.js +553 -30
  313. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  314. package/dist/core/worktree-snapshot/errors.code.js +2 -2
  315. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  316. package/dist/core/worktree-snapshot/errors.js +3 -3
  317. package/dist/core/worktree-snapshot/fork-blob-guard.js +81 -0
  318. package/dist/core/worktree-snapshot/fork-blob-guard.js.map +1 -0
  319. package/dist/core/worktree-snapshot/fork-snapshot-index.js +208 -50
  320. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -1
  321. package/dist/core/worktree-snapshot/session-index-reset.code.js +4 -0
  322. package/dist/core/worktree-snapshot/session-index-reset.code.js.map +1 -1
  323. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  324. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  325. package/dist/extensions/codemode/execute.code.js +1 -1
  326. package/dist/extensions/codemode/execute.impl.js +3 -3
  327. package/dist/extensions/codemode/execute.js +3 -3
  328. package/dist/extensions/codemode/renderer.code.js +2 -2
  329. package/dist/extensions/codemode/renderer.impl.js +3 -3
  330. package/dist/extensions/codemode/renderer.js +3 -3
  331. package/dist/extensions/mcp/cli.code.js +3 -3
  332. package/dist/extensions/mcp/cli.impl.js +3 -3
  333. package/dist/extensions/mcp/cli.js +3 -3
  334. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  335. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  336. package/dist/extensions/mcp/cli.lazy.js +3 -3
  337. package/dist/extensions/mcp/runtime.code.js +1 -1
  338. package/dist/extensions/mcp/runtime.impl.js +3 -3
  339. package/dist/extensions/mcp/runtime.js +3 -3
  340. package/dist/index.d.ts +3 -1
  341. package/dist/index.js +5 -5
  342. package/dist/main-first-time-setup.code.js +1 -1
  343. package/dist/main-first-time-setup.impl.js +3 -3
  344. package/dist/main-first-time-setup.js +3 -3
  345. package/dist/main.js +1 -1
  346. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  347. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  348. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  349. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  350. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  351. package/dist/modes/interactive/startup-shell-eligibility.js +1 -1
  352. package/dist/modes/interactive-engine/engine-prewarm.d.ts +1 -1
  353. package/dist/modes/print-mode.js +1 -1
  354. package/dist/package-manager-cli.code.js +6 -6
  355. package/dist/package-manager-cli.impl.js +3 -3
  356. package/dist/package-manager-cli.js +3 -3
  357. package/dist/rpc-entry.js +1 -1
  358. package/dist/startup-files.json +1 -1
  359. package/dist/startup-stages/10.js +1 -1
  360. package/dist/startup-stages/11.js +1 -1
  361. package/dist/startup-stages/12.js +1 -1
  362. package/dist/startup-stages/2.js +2 -4
  363. package/dist/startup-stages/3.js +1 -3
  364. package/dist/startup-stages/4.js +1 -2
  365. package/dist/startup-stages/5.js +1 -1
  366. package/dist/startup-stages/6.js +5 -7
  367. package/dist/startup-stages/7.js +3 -10
  368. package/dist/startup-stages/8.js +7 -2
  369. package/dist/startup-stages/9.js +1 -7
  370. package/dist/startup-stages/stages.json +1 -1
  371. package/dist/utils/compile-cache-deferral.js +8 -13
  372. package/dist/utils/compile-cache-deferral.js.map +1 -1
  373. package/dist/utils/compile-cache-warmup-host.js +3 -4
  374. package/dist/utils/compile-cache-warmup-host.js.map +1 -1
  375. package/dist/utils/compile-cache.js +12 -100
  376. package/dist/utils/compile-cache.js.map +1 -1
  377. package/dist/utils/startup-database-spare.code.js +2 -2
  378. package/dist/utils/startup-database-spare.impl.js +3 -3
  379. package/dist/utils/startup-database-spare.js +3 -3
  380. package/dist/utils/tools-manager.code.js +1 -1
  381. package/dist/utils/tools-manager.impl.js +3 -3
  382. package/dist/utils/tools-manager.js +3 -3
  383. package/dist/utils/worker-threads.js +2 -15
  384. package/dist/utils/worker-threads.js.map +1 -1
  385. package/docs/build.md +3 -3
  386. package/docs/changelog.mdx +1470 -69
  387. package/docs/compaction/reference.md +5 -5
  388. package/docs/compaction.md +7 -9
  389. package/docs/containerization.md +2 -2
  390. package/docs/custom-provider/api-reference.md +1 -1
  391. package/docs/docs.json +37 -10
  392. package/docs/environment-variables.md +0 -2
  393. package/docs/extensions/api-reference.md +4 -4
  394. package/docs/getting-started/installation.md +3 -0
  395. package/docs/guides/configuration.md +1 -1
  396. package/docs/guides/non-interactive.md +1 -1
  397. package/docs/guides/resume-on-any-machine.md +14 -22
  398. package/docs/guides/team-setup.md +56 -83
  399. package/docs/guides.md +2 -4
  400. package/docs/herdr.md +1 -1
  401. package/docs/index.md +1 -1
  402. package/docs/intercom/operations.md +26 -21
  403. package/docs/intercom/reference.md +2 -2
  404. package/docs/intercom.md +1 -1
  405. package/docs/libraries/storage-postgres.md +9 -9
  406. package/docs/libraries.md +2 -3
  407. package/docs/models-configuration.md +2 -2
  408. package/docs/models.md +2 -3
  409. package/docs/packages/authoring.md +7 -7
  410. package/docs/packages.md +1 -1
  411. package/docs/programmatic.md +2 -2
  412. package/docs/quickstart.md +1 -1
  413. package/docs/reference/cli.md +6 -11
  414. package/docs/reference.md +2 -2
  415. package/docs/rpc/extension-ui.md +2 -2
  416. package/docs/sdk/reference.md +5 -4
  417. package/docs/sdk/storage.md +8 -92
  418. package/docs/sdk/structured-decisions.md +1 -1
  419. package/docs/sdk/web-server.md +3 -3
  420. package/docs/sdk.md +14 -4
  421. package/docs/security.md +1 -1
  422. package/docs/session-format.md +5 -5
  423. package/docs/sessions.md +29 -49
  424. package/docs/settings.md +7 -8
  425. package/docs/storage/custom-adapters.md +255 -0
  426. package/docs/storage/jsonl.md +117 -0
  427. package/docs/{guides/postgres-pgbouncer.md → storage/postgres/pgbouncer.md} +66 -68
  428. package/docs/storage/postgres/tuning.md +337 -0
  429. package/docs/storage/postgres.md +556 -0
  430. package/docs/storage/sqlite.md +99 -0
  431. package/docs/storage.md +326 -990
  432. package/docs/subagents/authoring.md +1 -1
  433. package/docs/subagents.md +2 -2
  434. package/docs/tools.md +1 -1
  435. package/docs/worktree-snapshots.md +2 -2
  436. package/package.json +9 -9
  437. package/schemas/models.schema.json +2 -2
  438. package/schemas/settings.schema.json +0 -14
  439. package/dist/_shared/p1b-elig-ENCUPKKJ.js.map +0 -1
  440. package/dist/_shared/sdk-IQMULKFU.js.map +0 -1
  441. package/dist/_shared/startup-0-0-3IXNMFM2.js.map +0 -1
  442. package/dist/_shared/startup-0-1-7T2IAE7J.js.map +0 -1
  443. package/dist/_shared/startup-8-1-X32CYSXB.js.map +0 -1
  444. package/dist/core/intercom-broker-control.d.ts +0 -129
  445. package/dist/startup-stages/13.js +0 -1
  446. package/docs/guides/postgres-tuning.md +0 -311
  447. package/docs/libraries/storage-libsql.md +0 -97
@@ -2126,6 +2126,14 @@ export class IntercomClient extends EventEmitter {
2126
2126
  writeMessage(this.requireActiveSocket(), { type: "received", messageId, ...(paused ? { paused: true as const } : {}) });
2127
2127
  }
2128
2128
 
2129
+ /**
2130
+ * #5145, #6712: clears an outcome that was heard on this registration but not saved, so a redelivery on the same
2131
+ * connection is heard and saved again instead of dropped. Already-saved outcomes stay recorded.
2132
+ */
2133
+ forgetUnsavedOutcome(messageId: string): void {
2134
+ if (this.heardOutcomes.get(messageId) === "heard") this.heardOutcomes.delete(messageId);
2135
+ }
2136
+
2129
2137
  /**
2130
2138
  * #5145: whether `message` is an outcome this client already heard, so it is not heard twice. A copy of one already
2131
2139
  * saved is confirmed again, so the broker that sent it stops holding it.
@@ -1,10 +1,17 @@
1
+ import { createHash } from "node:crypto";
2
+ import * as storage from "@bastani/atomic/storage";
1
3
  import {
2
4
  dialectOf,
5
+ ensureStorageSchema,
3
6
  fencedPath,
4
7
  type SqliteDatabase,
5
8
  type SqliteExecutor,
6
9
  type SqliteRow,
10
+ type SqliteStatement,
11
+ type StorageNotificationEvent,
12
+ type StorageNotifications,
7
13
  type StorageNotificationSubscription,
14
+ storageMigrationTable,
8
15
  validateStoragePrefix,
9
16
  } from "@bastani/atomic/storage";
10
17
  import { OUTBOX_BACKUP_POLL_INTERVAL_MS } from "./multinode-state-store.js";
@@ -17,7 +24,14 @@ import type {
17
24
  WakeUpSubscribeResult,
18
25
  WakeUpSubscription,
19
26
  } from "./wake-up-bus.js";
20
- import { ensureBrokerSchema, withBrokerSchemaCatalog } from "./sql-schema.js";
27
+ import { addMissingColumns } from "./sql-add-column.js";
28
+ import {
29
+ ensureBrokerSchema,
30
+ openCatalogOf,
31
+ queueBrokerSqliteSetup,
32
+ RETRY_UNAPPLIED,
33
+ withBrokerSchemaCatalog,
34
+ } from "./sql-schema.js";
21
35
 
22
36
  /**
23
37
  * S4 wake-up bus (specs/2026-10-19-intercom-multi-node.md §5.6): a hint log in the shared storage database. Each
@@ -26,12 +40,15 @@ import { ensureBrokerSchema, withBrokerSchemaCatalog } from "./sql-schema.js";
26
40
  * hints written meanwhile may have been pruned or missed. While the database stays unavailable, reopening backs off
27
41
  * exponentially from the poll interval up to `WAKE_UP_RECONNECT_MAX_DELAY_MS`.
28
42
  *
29
- * On a database that delivers notifications (Postgres), a publish also notifies the channel named like the table, in
30
- * the transaction that writes the hint, and a subscribed connection polls as soon as a notification for one of its
31
- * brokers arrives (#5103). The interval poll stays: notifications are lost while the listening connection is down, and
32
- * none arrive through a transaction pooler. While the database reports its listening connection live, the poll only
33
- * backs the notifications up and runs at `WAKE_UP_LISTENING_POLL_INTERVAL_MS`; the listener's `listening` event, sent
34
- * when it listens again after an outage, polls at once (#6560).
43
+ * On a database that delivers notifications (Postgres), a publish also notifies the hint's broker once the hint
44
+ * commits, and a subscribed connection polls as soon as a notification for one of its brokers arrives (#5103). Each
45
+ * broker has a channel of its own (`brokerWakeUpChannel`), so a notification reaches only the connection that hosts it;
46
+ * brokers of earlier releases listen on the channel named like the table instead, which is notified too while the
47
+ * broker's membership does not say it listens on its own (`wakeUpNotices`). A connection listens on both. The interval
48
+ * poll stays: notifications are lost while the listening connection is down, and none arrive through a transaction
49
+ * pooler. While the database reports its listening connection live, the poll only backs the notifications up and runs
50
+ * at `WAKE_UP_LISTENING_POLL_INTERVAL_MS`; the listener's `listening` event, sent when it listens again after an
51
+ * outage, polls at once (#6560).
35
52
  */
36
53
 
37
54
  /** How often a connection with subscriptions reads its hints when no notification would announce them. */
@@ -41,21 +58,64 @@ export const WAKE_UP_POLL_INTERVAL_MS = 500;
41
58
  * in an outage the listener has not noticed yet waits for this poll.
42
59
  */
43
60
  export const WAKE_UP_LISTENING_POLL_INTERVAL_MS = 5_000;
44
- /** Hints nobody consumed (their broker exited) are deleted after this age; the backup poll has covered them. */
61
+ /**
62
+ * The longest a hint nobody consumed (its broker exited) stays in the table, while brokers publish: by then the backup
63
+ * poll has covered it. The prune runs at most every {@link WAKE_UP_PRUNE_INTERVAL_MS}, so it deletes the hints older
64
+ * than the retention less that interval: one that just missed a prune is gone by the next, at most the retention old.
65
+ */
45
66
  export const WAKE_UP_HINT_RETENTION_MS = OUTBOX_BACKUP_POLL_INTERVAL_MS;
46
67
  /**
47
- * How often at most one connection deletes the hints past the retention, at a publish (#6560): a hint nobody consumed
48
- * then stays at most this much longer than the retention.
68
+ * How often at most one connection deletes old hints, at a publish (#6560): each prune is a write every broker would
69
+ * otherwise send at every publish.
49
70
  */
50
71
  export const WAKE_UP_PRUNE_INTERVAL_MS = 10_000;
72
+ /** The age past which a prune deletes a hint, so that no hint outlives {@link WAKE_UP_HINT_RETENTION_MS}. */
73
+ const WAKE_UP_PRUNE_AGE_MS = WAKE_UP_HINT_RETENTION_MS - WAKE_UP_PRUNE_INTERVAL_MS;
51
74
  /**
52
- * Hints read and deleted per statement; a poll repeats until a batch comes back short. Each batch's delete binds one
53
- * parameter per hint, so a backlog never exceeds SQLite's bound-parameter limit (999 on old builds).
75
+ * Hints read and deleted per statement; a poll repeats until a batch comes back short, so a backlog is taken in
76
+ * statements of bounded size.
54
77
  */
55
78
  export const WAKE_UP_POLL_BATCH_SIZE = 500;
79
+ /** The most hints one publish transaction writes together (#6715). */
80
+ const WAKE_UP_PUBLISH_BATCH_MAX = 500;
56
81
  /** Longest wait between attempts to reopen an unavailable database; the backup poll covers the gap. */
57
82
  export const WAKE_UP_RECONNECT_MAX_DELAY_MS = OUTBOX_BACKUP_POLL_INTERVAL_MS;
58
83
 
84
+ /**
85
+ * What a broker's membership subject holds, as the lease table stores it, when the broker listens on its own wake-up
86
+ * channel (`BrokerMembershipSubject.ownWakeUpChannel`). A JSON string escapes its quotes, so only that field matches.
87
+ */
88
+ export const OWN_WAKE_UP_CHANNEL_MARK = '"ownWakeUpChannel":true';
89
+
90
+ /**
91
+ * The channel only `brokerId`'s connections listen on: the hint table's name and 64 bits of a hash of the broker id, so
92
+ * it stays a short identifier whatever the id, as Que's `que_listener_<pid>`. A notification on it reaches that broker's
93
+ * connection alone, where one on the table's channel reaches every broker's.
94
+ */
95
+ export function brokerWakeUpChannel(table: string, brokerId: string): string {
96
+ return `${table}_${createHash("sha256").update(brokerId).digest("hex").slice(0, 16)}`;
97
+ }
98
+
99
+ /**
100
+ * The notifications that wake `brokerId` once the transaction that runs them commits: one on its own channel, and one on
101
+ * the table's channel, where brokers of earlier releases listen, unless `brokerId`'s membership lease, in `leases`, says
102
+ * it listens on its own. Both carry the broker id, which a listener checks.
103
+ */
104
+ export function wakeUpNotices(
105
+ notifications: StorageNotifications,
106
+ table: string,
107
+ leases: string,
108
+ brokerId: string,
109
+ ): SqliteStatement[] {
110
+ return [
111
+ notifications.notify(brokerWakeUpChannel(table, brokerId), brokerId),
112
+ notifications.notify(table, brokerId, {
113
+ sql: `SELECT 1 FROM ${leases} WHERE kind = 'broker' AND key = ? AND strpos(subject_json, ?) > 0`,
114
+ params: [brokerId, OWN_WAKE_UP_CHANNEL_MARK],
115
+ }),
116
+ ];
117
+ }
118
+
59
119
  /** Runs `callback` once after `delayMs` and returns a function that cancels it. */
60
120
  export type WakeUpPollScheduler = (callback: () => void, delayMs: number) => () => void;
61
121
 
@@ -69,9 +129,9 @@ export interface DatabaseWakeUpBusOptions {
69
129
  readonly schedule?: WakeUpPollScheduler;
70
130
  /**
71
131
  * A separate handle on the same database that the poll reads its hints through, so a poll never queues behind the
72
- * database's writes (#6560); the bus does not close it. On PostgreSQL the poll takes and deletes its hints through
73
- * it in one statement (`DELETE … RETURNING`), so it must accept writes. Absent: the poll runs on the database it
74
- * opened.
132
+ * database's writes (#6560); the bus does not close it, and writes nothing through it. On PostgreSQL the poll reads
133
+ * nothing through it: it takes and deletes its hints in one statement (`DELETE … RETURNING`) on the database it
134
+ * opened. Absent: the poll runs on the database it opened.
75
135
  */
76
136
  readonly reader?: SqliteExecutor;
77
137
  }
@@ -81,6 +141,15 @@ interface HintRow extends SqliteRow {
81
141
  readonly broker_id: string;
82
142
  readonly reason: string;
83
143
  readonly version: number;
144
+ readonly target_identity: string | null;
145
+ }
146
+
147
+ /** The channels a connection listens on, each with its subscription, and the database it listens through. */
148
+ interface Listening {
149
+ readonly database: SqliteDatabase;
150
+ readonly channels: Map<string, StorageNotificationSubscription>;
151
+ /** The database reported its listening connection live, as of the latest check. */
152
+ live: boolean;
84
153
  }
85
154
 
86
155
  interface DatabaseSubscription {
@@ -95,19 +164,112 @@ const scheduleTimeout: WakeUpPollScheduler = (callback, delayMs) => {
95
164
  return () => clearTimeout(timer);
96
165
  };
97
166
 
167
+ /**
168
+ * `storageSchemaCurrent` of the storage API, which an Atomic installation older than #6560 lacks: a named import would
169
+ * fail to link there, so it is taken from the module namespace, and without it the hint log's persistence is read from
170
+ * the catalog at every open.
171
+ */
172
+ const schemaApi: Partial<Pick<typeof storage, "storageSchemaCurrent" | "ensureStorageSchemaOnce">> = storage;
173
+
174
+ /** The ledger step, `schema:intercom-wakeups-unlogged`, that makes a hint log created as a logged table unlogged. */
175
+ const UNLOGGED_HINTS_DOMAIN = "intercom-wakeups-unlogged";
176
+
98
177
  async function createSchema(database: SqliteDatabase, table: string, prefix: string | undefined): Promise<void> {
99
- const { types } = dialectOf(database);
100
- // In a serial transaction, so brokers opening a new bus at once take turns creating it (#5054).
101
- const schema = `CREATE TABLE IF NOT EXISTS ${table} (
178
+ const { types, name } = dialectOf(database);
179
+ // On PostgreSQL the hint log is unlogged: its rows skip the write-ahead log, so a hint costs no log write and its
180
+ // commit no flush to disk. A crash of the server empties it, which loses only hints, and the backup poll finds
181
+ // every message they announced. In a serial transaction, so brokers opening a new bus at once take turns creating
182
+ // it (#5054).
183
+ const schema = `CREATE ${name === "postgres" ? "UNLOGGED " : ""}TABLE IF NOT EXISTS ${table} (
102
184
  id ${types.serialKey},
103
185
  broker_id TEXT NOT NULL,
104
186
  reason TEXT NOT NULL CHECK (reason IN ('outbox', 'outcome')),
105
187
  version ${types.int} NOT NULL,
106
- created_at ${types.int} NOT NULL
188
+ created_at ${types.int} NOT NULL,
189
+ target_identity TEXT
107
190
  );
108
191
  CREATE INDEX IF NOT EXISTS ${table}_broker ON ${table} (broker_id, id);
109
192
  CREATE INDEX IF NOT EXISTS ${table}_created ON ${table} (created_at);`;
193
+ // `target_identity`, the recipient a hint is about (`WakeUpHint.targetIdentity`), came later: a table an earlier
194
+ // release created gets it here, and an earlier broker's hints leave it null. A table this open creates has it, so a
195
+ // new database's first open spends nothing on it.
196
+ const catalog = await openCatalogOf(database);
197
+ const existed = catalog === undefined || catalog.hasTable(table);
110
198
  await ensureBrokerSchema(database, prefix, "wakeups", (tx) => tx.exec(schema));
199
+ if (dialectOf(database).name === "sqlite") {
200
+ if (
201
+ !(catalog !== undefined && catalog.hasColumn(table, "target_identity")) &&
202
+ !queueBrokerSqliteSetup(database, prefix ?? "", {
203
+ verify: (found) => found.hasColumn(table, "target_identity"),
204
+ run(ctx) {
205
+ // Add target_identity only when an older build created the table before this transaction without it.
206
+ if (ctx.tableExisted(table) && !ctx.hasColumn(table, "target_identity")) {
207
+ ctx.enqueue(`ALTER TABLE ${table} ADD COLUMN target_identity TEXT`);
208
+ ctx.noteColumnAdded(table, "target_identity");
209
+ }
210
+ },
211
+ })
212
+ ) {
213
+ if (existed) await addMissingColumns(database, table, { target_identity: "TEXT" });
214
+ }
215
+ } else if (existed) {
216
+ await addMissingColumns(database, table, { target_identity: "TEXT" });
217
+ }
218
+ await ensureUnloggedHints(database, table, prefix);
219
+ }
220
+
221
+ /**
222
+ * Makes a hint log that an earlier Atomic created as a logged table unlogged on PostgreSQL, once per database, recorded
223
+ * in the ledger as `schema:intercom-wakeups-unlogged`. `ALTER TABLE … SET UNLOGGED` needs the table's owner, so a
224
+ * runtime role without DDL leaves it logged, as before, until `atomic storage migrate` runs as the owner. Earlier
225
+ * Atomic releases use the unlogged table unchanged. The rewrite locks the table, which holds only hints younger than
226
+ * the retention: when another broker holds it longer than the schema lock wait, the next open tries again. A table
227
+ * that is unlogged already, as every table this build creates, needs only the step recorded: the statement that reads
228
+ * the table's persistence records it too, so a new database's open pays one round trip for it and no transaction
229
+ * (#6560).
230
+ */
231
+ async function ensureUnloggedHints(database: SqliteDatabase, table: string, prefix: string | undefined): Promise<void> {
232
+ const dialect = dialectOf(database);
233
+ if (dialect.name !== "postgres" || database.readOnly === true) return;
234
+ const schema = { ledger: storageMigrationTable(prefix), domain: UNLOGGED_HINTS_DOMAIN, revision: 1 };
235
+ if (await schemaApi.storageSchemaCurrent?.(database, schema)) return;
236
+ const yes = (value: boolean | number | undefined) => value === true || Number(value) === 1;
237
+ let found: (SqliteRow & { owned: boolean | number; unlogged: boolean | number }) | undefined;
238
+ try {
239
+ // The ledger exists: the hint log's own setup recorded itself there. Recording a step that holds, whoever else
240
+ // records it at once, needs no lock.
241
+ found = await database.get(
242
+ `WITH found AS (
243
+ SELECT pg_catalog.pg_has_role(current_user, c.relowner, 'USAGE') AS owned, c.relpersistence = 'u' AS unlogged
244
+ FROM pg_catalog.pg_class c WHERE c.relnamespace = current_schema()::regnamespace AND c.relname = ?
245
+ ), recorded AS (
246
+ INSERT INTO ${schema.ledger} (domain, version, applied_at)
247
+ SELECT ?, ?, ${dialect.nowMs} FROM found WHERE found.unlogged ON CONFLICT DO NOTHING RETURNING 1
248
+ )
249
+ SELECT owned, unlogged FROM found`,
250
+ dialect.identifier(table),
251
+ `schema:${schema.domain}`,
252
+ schema.revision,
253
+ );
254
+ } catch {
255
+ // A role that may not write the ledger leaves the step to `atomic storage migrate`.
256
+ return;
257
+ }
258
+ if (found === undefined || yes(found.unlogged) || !yes(found.owned)) return;
259
+ const setup = async (tx: SqliteExecutor) => {
260
+ await tx.exec(`ALTER TABLE ${table} SET UNLOGGED`);
261
+ };
262
+ try {
263
+ // Brokers that open the database at once make it unlogged once: the others wait for it without its lock (#6560).
264
+ const ensureOnce = schemaApi.ensureStorageSchemaOnce;
265
+ if (ensureOnce !== undefined) await ensureOnce(database, schema, setup);
266
+ else
267
+ await database.transaction((tx) => ensureStorageSchema(tx, dialect, schema, () => setup(tx)), {
268
+ concurrency: { kind: "serial", domain: schema.ledger },
269
+ });
270
+ } catch {
271
+ // The table stays as it was: hints work the same in a logged table.
272
+ }
111
273
  }
112
274
 
113
275
  /**
@@ -137,6 +299,8 @@ class DatabaseWakeUpBus implements WakeUpBus {
137
299
  private readonly subscriptions = new Set<DatabaseSubscription>();
138
300
  private readonly options: DatabaseWakeUpBusOptions;
139
301
  private readonly table: string;
302
+ /** The lease table, whose membership leases say which brokers listen on their own channels. */
303
+ private readonly leases: string;
140
304
  private readonly pollIntervalMs: number;
141
305
  private readonly listeningPollIntervalMs: number;
142
306
  private readonly schedule: WakeUpPollScheduler;
@@ -149,57 +313,112 @@ class DatabaseWakeUpBus implements WakeUpBus {
149
313
  /** Consecutive failed attempts to reopen the database; each doubles the wait before the next. */
150
314
  private reconnectFailures = 0;
151
315
  private reconnectNotBefore = 0;
152
- /** The notification channel this connection listens on, and the database it listens through. */
153
- private listening:
154
- | {
155
- readonly database: SqliteDatabase;
156
- readonly subscription: StorageNotificationSubscription;
157
- /** The database reported its listening connection live, as of the latest check. */
158
- live: boolean;
159
- }
160
- | undefined;
316
+ /**
317
+ * The notification channels this connection listens on, each with its subscription: the table's and each subscribed
318
+ * broker's own (`brokerWakeUpChannel`). And the database it listens through.
319
+ */
320
+ private listening: Listening | undefined;
161
321
  /** A notification arrived during a poll: the next poll runs as soon as that one ends. */
162
322
  private pollAgain = false;
163
323
  /** When a publish last deleted the hints past the retention, by this process's clock. */
164
324
  private prunedAt: number | undefined;
325
+ /** Publishes waiting for the next batch transaction, in the order they were made (#6715). */
326
+ private readonly pendingPublishes: {
327
+ readonly hint: WakeUpHint;
328
+ readonly resolve: (result: WakeUpPublishResult) => void;
329
+ }[] = [];
330
+ /** The drain loop currently writing batches of queued publishes, if any. */
331
+ private publishing: Promise<void> | undefined;
165
332
 
166
333
  constructor(options: DatabaseWakeUpBusOptions, table: string, database: SqliteDatabase) {
167
334
  this.options = options;
168
335
  this.table = table;
336
+ this.leases = `${validateStoragePrefix(options.prefix)}intercom_leases`;
169
337
  this.database = database;
170
338
  this.pollIntervalMs = options.pollIntervalMs ?? WAKE_UP_POLL_INTERVAL_MS;
171
339
  this.listeningPollIntervalMs = options.listeningPollIntervalMs ?? WAKE_UP_LISTENING_POLL_INTERVAL_MS;
172
340
  this.schedule = options.schedule ?? scheduleTimeout;
173
341
  }
174
342
 
175
- async publish(hint: WakeUpHint): Promise<WakeUpPublishResult> {
176
- if (hint.brokerId.length === 0) return { status: "invalid", reason: "empty-broker-id" };
343
+ publish(hint: WakeUpHint): Promise<WakeUpPublishResult> {
344
+ if (hint.brokerId.length === 0) return Promise.resolve({ status: "invalid", reason: "empty-broker-id" });
345
+ if (this.closed) return Promise.resolve({ status: "unavailable" });
346
+ return new Promise<WakeUpPublishResult>((resolve) => {
347
+ this.pendingPublishes.push({ hint, resolve });
348
+ if (this.publishing === undefined) this.publishing = this.drainPublishes();
349
+ });
350
+ }
351
+
352
+ private async drainPublishes(): Promise<void> {
353
+ try {
354
+ // Publishes made in the same turn as the first go with it.
355
+ await undefined;
356
+ while (this.pendingPublishes.length > 0) {
357
+ if (this.closed) {
358
+ for (const { resolve } of this.pendingPublishes.splice(0)) resolve({ status: "unavailable" });
359
+ return;
360
+ }
361
+ const batch = this.pendingPublishes.splice(0, WAKE_UP_PUBLISH_BATCH_MAX);
362
+ const result = await this.publishBatch(batch.map(({ hint }) => hint));
363
+ for (const { resolve } of batch) resolve(result);
364
+ }
365
+ } finally {
366
+ this.publishing = undefined;
367
+ }
368
+ }
369
+
370
+ private async publishBatch(hints: readonly WakeUpHint[]): Promise<WakeUpPublishResult> {
177
371
  const database = await this.connection(false);
178
372
  if (database === undefined) return { status: "unavailable" };
179
- const { nowMs } = dialectOf(database);
180
- const insert = `INSERT INTO ${this.table} (broker_id, reason, version, created_at) VALUES (?, ?, ?, ${nowMs})`;
373
+ const { name: dialect, nowMs, types } = dialectOf(database);
374
+ const payload = JSON.stringify(
375
+ hints.map((hint) => [hint.brokerId, hint.reason, hint.version, hint.targetIdentity ?? null]),
376
+ );
377
+ const insert: SqliteStatement =
378
+ dialect === "postgres"
379
+ ? {
380
+ sql: `INSERT INTO ${this.table} (broker_id, reason, version, created_at, target_identity)
381
+ SELECT h ->> 0, h ->> 1, CAST(h ->> 2 AS ${types.int}), ${nowMs}, h ->> 3
382
+ FROM jsonb_array_elements(?::jsonb) WITH ORDINALITY AS t(h, ord)
383
+ ORDER BY ord`,
384
+ params: [payload],
385
+ }
386
+ : {
387
+ sql: `INSERT INTO ${this.table} (broker_id, reason, version, created_at, target_identity)
388
+ SELECT json_extract(value, '$[0]'), json_extract(value, '$[1]'),
389
+ CAST(json_extract(value, '$[2]') AS ${types.int}), ${nowMs}, json_extract(value, '$[3]')
390
+ FROM json_each(?)
391
+ ORDER BY key`,
392
+ params: [payload],
393
+ };
181
394
  const notifications = database.notifications;
182
395
  try {
183
- if (notifications === undefined) await database.run(insert, hint.brokerId, hint.reason, hint.version);
396
+ if (notifications === undefined) await database.run(insert.sql, ...insert.params);
184
397
  else {
185
- // The notification goes out when the hint commits, so the poll it starts finds the hint. A hint is a new
186
- // row that no write checks first, so its writers take no lock domain (#6560): see
187
- // `fencedPath("intercom-wakeup-hint")`.
188
- const notify = notifications.notify(this.table, hint.brokerId);
398
+ // The notifications go out once the hints commit, one per distinct broker, so the poll they start finds
399
+ // them: on Postgres right behind the commit, in the same round trip, and the batch insert goes with the
400
+ // transaction's start (#6560, #6715). Hints are new rows that no write checks first, so their writers take
401
+ // no lock domain: see `fencedPath("intercom-wakeup-hint")`.
402
+ const brokers = [...new Set(hints.map((hint) => hint.brokerId))];
403
+ const notices = brokers.flatMap((brokerId) => wakeUpNotices(notifications, this.table, this.leases, brokerId));
189
404
  await database.transaction(
190
405
  async (tx) => {
191
- await tx.run(insert, hint.brokerId, hint.reason, hint.version);
192
- await tx.run(notify.sql, ...notify.params);
406
+ await Promise.all([insert, ...notices].map(({ sql, params }) => tx.run(sql, ...params)));
407
+ },
408
+ {
409
+ ...RETRY_UNAPPLIED,
410
+ concurrency: { kind: "fenced", audit: fencedPath("intercom-wakeup-hint") },
411
+ leading: [insert],
193
412
  },
194
- { concurrency: { kind: "fenced", audit: fencedPath("intercom-wakeup-hint") } },
195
413
  );
196
414
  }
197
415
  // #6560: at most once per interval, not at every publish: each prune is a write every broker would send.
198
416
  if (this.prunedAt === undefined || Date.now() - this.prunedAt >= WAKE_UP_PRUNE_INTERVAL_MS) {
199
417
  this.prunedAt = Date.now();
418
+ // The clock is read once, in a subquery: PostgreSQL's is volatile, and a volatile bound uses no index.
200
419
  await database.run(
201
- `DELETE FROM ${this.table} WHERE created_at < ${nowMs} - ?`,
202
- WAKE_UP_HINT_RETENTION_MS,
420
+ `DELETE FROM ${this.table} WHERE created_at < (SELECT ${nowMs}) - ?`,
421
+ WAKE_UP_PRUNE_AGE_MS,
203
422
  );
204
423
  }
205
424
  } catch {
@@ -222,6 +441,7 @@ class DatabaseWakeUpBus implements WakeUpBus {
222
441
  close: async () => {
223
442
  subscription.open = false;
224
443
  this.subscriptions.delete(subscription);
444
+ this.listen();
225
445
  },
226
446
  };
227
447
  return { status: "subscribed", subscription: handle };
@@ -236,10 +456,10 @@ class DatabaseWakeUpBus implements WakeUpBus {
236
456
  this.closed = true;
237
457
  this.cancelPoll?.();
238
458
  this.cancelPoll = undefined;
239
- this.listening?.subscription.close();
240
- this.listening = undefined;
459
+ this.stopListening();
241
460
  for (const subscription of this.subscriptions) subscription.open = false;
242
461
  this.subscriptions.clear();
462
+ await this.publishing;
243
463
  await this.polling;
244
464
  await this.opening;
245
465
  const database = this.database;
@@ -253,22 +473,45 @@ class DatabaseWakeUpBus implements WakeUpBus {
253
473
  });
254
474
  }
255
475
 
256
- /** Listens for notifications through the current database, when it delivers them. */
476
+ /**
477
+ * Listens for notifications through the current database, when it delivers them: on each subscribed broker's own
478
+ * channel, and on the table's, where brokers of earlier releases send them. A channel no subscription needs any more
479
+ * is left.
480
+ */
257
481
  private listen(): void {
258
482
  const database = this.database;
259
- if (this.closed || database === undefined || this.listening?.database === database) return;
260
- this.listening?.subscription.close();
261
- this.listening = undefined;
483
+ if (this.closed || database === undefined) return;
484
+ if (this.listening !== undefined && this.listening.database !== database) this.stopListening();
262
485
  const notifications = database.notifications;
263
486
  if (notifications === undefined) return;
264
- const subscription = notifications.listen(this.table, (event) => {
265
- if (event.kind === "listening") {
266
- if (this.listening?.subscription === subscription) this.listening.live = true;
267
- this.pollNow();
268
- } else if ([...this.subscriptions].some((open) => open.brokerId === event.payload)) this.pollNow();
269
- });
270
- this.listening = { database, subscription, live: false };
271
- void this.checkListening();
487
+ const fresh = this.listening === undefined;
488
+ const listening = (this.listening ??= { database, channels: new Map(), live: false });
489
+ const wanted = new Set([
490
+ this.table,
491
+ ...[...this.subscriptions].map((subscription) => brokerWakeUpChannel(this.table, subscription.brokerId)),
492
+ ]);
493
+ for (const [channel, subscription] of listening.channels) {
494
+ if (wanted.has(channel)) continue;
495
+ subscription.close();
496
+ listening.channels.delete(channel);
497
+ }
498
+ for (const channel of wanted) {
499
+ if (!listening.channels.has(channel))
500
+ listening.channels.set(channel, notifications.listen(channel, (event) => this.notified(listening, event)));
501
+ }
502
+ if (fresh) void this.checkListening();
503
+ }
504
+
505
+ private notified(listening: Listening, event: StorageNotificationEvent): void {
506
+ if (event.kind === "listening") {
507
+ if (this.listening === listening) listening.live = true;
508
+ this.pollNow();
509
+ } else if ([...this.subscriptions].some((open) => open.brokerId === event.payload)) this.pollNow();
510
+ }
511
+
512
+ private stopListening(): void {
513
+ for (const subscription of this.listening?.channels.values() ?? []) subscription.close();
514
+ this.listening = undefined;
272
515
  }
273
516
 
274
517
  /** Asks the database whether its listening connection is live, for the interval of the next poll. */
@@ -321,26 +564,38 @@ class DatabaseWakeUpBus implements WakeUpBus {
321
564
  const database = await this.connection(true);
322
565
  const brokerIds = [...new Set([...this.subscriptions].map((subscription) => subscription.brokerId))];
323
566
  if (database === undefined || brokerIds.length === 0) return;
324
- const placeholders = brokerIds.map(() => "?").join(", ");
325
- const batch = `FROM ${this.table} WHERE broker_id IN (${placeholders}) ORDER BY id LIMIT ${WAKE_UP_POLL_BATCH_SIZE}`;
567
+ const dialect = dialectOf(database);
568
+ // One statement text whatever the number of brokers, so the server plans it once: their ids go as one JSON array.
569
+ const batch = `FROM ${this.table} WHERE broker_id IN (SELECT value FROM ${dialect.jsonValues("?")}) ORDER BY id LIMIT ${WAKE_UP_POLL_BATCH_SIZE}`;
570
+ const ids = JSON.stringify(brokerIds);
326
571
  const reader = this.options.reader ?? database;
327
572
  for (;;) {
328
573
  let rows: HintRow[];
329
574
  try {
330
- if (dialectOf(database).name === "postgres") {
331
- // #6560: one statement takes the batch and deletes it, through the reader, whose calls never queue
332
- // behind this database's writes. It returns the hints in no particular order.
333
- rows = await reader.all<HintRow>(
334
- `DELETE FROM ${this.table} WHERE id IN (SELECT id ${batch}) RETURNING id, broker_id, reason, version`,
335
- ...brokerIds,
336
- );
575
+ if (dialect.name === "postgres") {
576
+ // #6560: one statement takes the batch and deletes it. It is a write, so it goes through the database,
577
+ // never the reader, as a statement of its own in the wake-up table's domain: one round trip, queued
578
+ // behind neither other domains' writes nor read-only transactions. It returns the hints in no
579
+ // particular order.
580
+ const take = {
581
+ sql: `DELETE FROM ${this.table} WHERE id IN (SELECT id ${batch}) RETURNING id, broker_id, reason, version, target_identity`,
582
+ params: [ids],
583
+ };
584
+ rows = (
585
+ database.autocommit === undefined
586
+ ? await database.all(take.sql, ...take.params)
587
+ : await database.autocommit(take, { kind: "serial", domain: this.table })
588
+ ) as HintRow[];
337
589
  rows.sort((left, right) => Number(left.id) - Number(right.id));
338
590
  } else {
339
- rows = await reader.all<HintRow>(`SELECT id, broker_id, reason, version ${batch}`, ...brokerIds);
591
+ rows = await reader.all<HintRow>(
592
+ `SELECT id, broker_id, reason, version, target_identity ${batch}`,
593
+ ids,
594
+ );
340
595
  if (rows.length > 0) {
341
596
  await database.run(
342
- `DELETE FROM ${this.table} WHERE id IN (${rows.map(() => "?").join(", ")})`,
343
- ...rows.map((row) => row.id),
597
+ `DELETE FROM ${this.table} WHERE id IN (SELECT value FROM ${dialect.jsonValues("?")})`,
598
+ JSON.stringify(rows.map((row) => Number(row.id))),
344
599
  );
345
600
  }
346
601
  }
@@ -353,6 +608,7 @@ class DatabaseWakeUpBus implements WakeUpBus {
353
608
  brokerId: row.broker_id,
354
609
  reason: row.reason === "outcome" ? "outcome" : "outbox",
355
610
  version: row.version,
611
+ ...(row.target_identity === null ? {} : { targetIdentity: row.target_identity }),
356
612
  };
357
613
  for (const subscription of this.subscriptions) {
358
614
  if (subscription.brokerId === hint.brokerId) this.deliver(subscription, { kind: "hint", hint });