@bastani/atomic 0.10.11-alpha.2 → 0.10.11-alpha.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 (432) hide show
  1. package/CHANGELOG.md +99 -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} +14 -2
  14. package/dist/_shared/{p1b-elig-ENCUPKKJ.js.map → p1b-elig-TVB5CBLL.js.map} +1 -1
  15. package/dist/_shared/runtime-O4KCSG4C.js +3 -3
  16. package/dist/_shared/{sdk-IQMULKFU.js → sdk-B5LEWGGI.js} +340 -163
  17. package/dist/_shared/sdk-B5LEWGGI.js.map +1 -0
  18. package/dist/_shared/session-data-AHTU7IS6.js +2 -2
  19. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  20. package/dist/_shared/{startup-0-0-3IXNMFM2.js → startup-0-0-EZUKEP4Q.js} +48 -40
  21. package/dist/_shared/startup-0-0-EZUKEP4Q.js.map +1 -0
  22. package/dist/_shared/{startup-0-1-7T2IAE7J.js → startup-0-1-RTOHJFDJ.js} +195 -42
  23. package/dist/_shared/startup-0-1-RTOHJFDJ.js.map +1 -0
  24. package/dist/_shared/startup-0-2-5QHPCEON.js +33 -43
  25. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -1
  26. package/dist/_shared/startup-0-3-4ZYBYQNM.js +5 -5
  27. package/dist/_shared/startup-0-4-ZMJV547D.js +12 -7
  28. package/dist/_shared/startup-0-4-ZMJV547D.js.map +1 -1
  29. package/dist/_shared/startup-0-5-YDW47QX6.js +7 -7
  30. package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -1
  31. package/dist/_shared/startup-10-0-TDQNBDDL.js +6 -6
  32. package/dist/_shared/startup-12-0-55AAXBJZ.js +2 -2
  33. package/dist/_shared/startup-14-0-MLX36RBG.js +4 -5
  34. package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
  35. package/dist/_shared/startup-15-0-YUKGAC63.js +4 -4
  36. package/dist/_shared/startup-15-1-4S7FLMNG.js +19 -27
  37. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  38. package/dist/_shared/startup-8-0-34CBHPZH.js +39 -23
  39. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  40. package/dist/_shared/{startup-8-1-X32CYSXB.js → startup-8-1-LZFXSD3Z.js} +90 -1176
  41. package/dist/_shared/startup-8-1-LZFXSD3Z.js.map +1 -0
  42. package/dist/_shared/storage-command-7MGXLJGZ.js +186 -35
  43. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  44. package/dist/_shared/storage-status-K7PX2RXA.js +557 -0
  45. package/dist/_shared/storage-status-K7PX2RXA.js.map +1 -0
  46. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  47. package/dist/_shared/team-DOQKICG2.js +376 -0
  48. package/dist/_shared/team-DOQKICG2.js.map +1 -0
  49. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  50. package/dist/builtin/intercom/CHANGELOG.md +23 -0
  51. package/dist/builtin/intercom/README.md +2 -2
  52. package/dist/builtin/intercom/broker/broker.bundle.mjs +913 -289
  53. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +243 -64
  54. package/dist/builtin/intercom/broker/multinode-router.ts +154 -22
  55. package/dist/builtin/intercom/broker/multinode-state-store.ts +30 -3
  56. package/dist/builtin/intercom/broker/open-broker-state.ts +14 -0
  57. package/dist/builtin/intercom/broker/sql-add-column.ts +29 -5
  58. package/dist/builtin/intercom/broker/sql-ended-child-queue-store.ts +3 -2
  59. package/dist/builtin/intercom/broker/sql-held-send-store.ts +2 -2
  60. package/dist/builtin/intercom/broker/sql-known-session-store.ts +43 -19
  61. package/dist/builtin/intercom/broker/sql-lease-store.ts +170 -74
  62. package/dist/builtin/intercom/broker/sql-outbox-store.ts +298 -47
  63. package/dist/builtin/intercom/broker/sql-pending-ask-store.ts +8 -5
  64. package/dist/builtin/intercom/broker/sql-released-ask-store.ts +12 -5
  65. package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +24 -7
  66. package/dist/builtin/intercom/broker/sql-retention.ts +141 -0
  67. package/dist/builtin/intercom/broker/sql-schema.ts +136 -19
  68. package/dist/builtin/intercom/broker/sql-sent-message-authority.ts +74 -19
  69. package/dist/builtin/intercom/broker/wake-up-bus.ts +6 -0
  70. package/dist/builtin/intercom/index.bundle.mjs +2 -3
  71. package/dist/builtin/intercom/package.json +1 -1
  72. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  73. package/dist/builtin/mcp/package.json +1 -1
  74. package/dist/builtin/subagents/package.json +1 -1
  75. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  76. package/dist/builtin/web-access/index.bundle.mjs +2 -10
  77. package/dist/builtin/web-access/package.json +1 -1
  78. package/dist/bun/bundled-sqlite.js +41 -0
  79. package/dist/bun/bundled-sqlite.js.map +1 -0
  80. package/dist/cli/args.js +2 -2
  81. package/dist/cli/auth-cli.code.js +4 -4
  82. package/dist/cli/auth-cli.impl.js +3 -3
  83. package/dist/cli/auth-cli.js +3 -3
  84. package/dist/cli/blueprint-command.code.js +3 -3
  85. package/dist/cli/blueprint-command.impl.js +3 -3
  86. package/dist/cli/blueprint-command.js +3 -3
  87. package/dist/cli/intercom-command.code.js +3 -3
  88. package/dist/cli/intercom-command.code.js.map +1 -1
  89. package/dist/cli/intercom-command.impl.js +3 -3
  90. package/dist/cli/intercom-command.js +3 -3
  91. package/dist/cli/list-models.code.js +2 -2
  92. package/dist/cli/list-models.impl.js +3 -3
  93. package/dist/cli/list-models.js +3 -3
  94. package/dist/cli/session-picker.code.js +1 -1
  95. package/dist/cli/session-picker.impl.js +3 -3
  96. package/dist/cli/session-picker.js +3 -3
  97. package/dist/cli/startup-ui.code.js +1 -1
  98. package/dist/cli/startup-ui.impl.js +3 -3
  99. package/dist/cli/startup-ui.js +3 -3
  100. package/dist/cli/storage-command.impl.js +3 -3
  101. package/dist/cli/storage-command.js +3 -3
  102. package/dist/cli/storage-search-session.code.js +3 -3
  103. package/dist/cli/storage-search-session.impl.js +3 -3
  104. package/dist/cli/storage-search-session.js +3 -3
  105. package/dist/cli/team-command.code.js +19 -113
  106. package/dist/cli/team-command.code.js.map +1 -1
  107. package/dist/cli/team-command.impl.js +3 -3
  108. package/dist/cli/team-command.js +3 -3
  109. package/dist/cli.js +5 -18
  110. package/dist/cli.js.map +1 -1
  111. package/dist/core/agent-rehydrate-errors.d.ts +4 -9
  112. package/dist/core/compaction/compactor.d.ts +3 -3
  113. package/dist/core/debug.code.js +1 -1
  114. package/dist/core/debug.impl.js +3 -3
  115. package/dist/core/debug.js +3 -3
  116. package/dist/core/export-html/card-projection.impl.js +3 -3
  117. package/dist/core/export-html/card-projection.js +3 -3
  118. package/dist/core/export-html/index.code.js +2 -2
  119. package/dist/core/export-html/index.impl.js +3 -3
  120. package/dist/core/export-html/index.js +3 -3
  121. package/dist/core/export-html/json-spans.impl.js +3 -3
  122. package/dist/core/export-html/json-spans.js +3 -3
  123. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  124. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  125. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  126. package/dist/core/export-html/tool-renderer.js +3 -3
  127. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  128. package/dist/core/extensions/jiti-loader.js +3 -3
  129. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  130. package/dist/core/extensions/jiti-static-loader.js +3 -3
  131. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  132. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  133. package/dist/core/extensions/loader-host-modules.js +3 -3
  134. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  135. package/dist/core/extensions/runner-context.js +2 -2
  136. package/dist/core/intercom-broker-control-host.code.js +2 -2
  137. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  138. package/dist/core/intercom-broker-control-host.js +3 -3
  139. package/dist/core/intercom-broker-control.code.js +3 -3
  140. package/dist/core/intercom-broker-control.impl.js +3 -3
  141. package/dist/core/intercom-broker-control.js +3 -3
  142. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  143. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  144. package/dist/core/package-manager-storage-adapters.js +3 -3
  145. package/dist/core/process-start-token.d.ts +8 -0
  146. package/dist/core/process-tree-containment.d.ts +16 -0
  147. package/dist/core/sdk-types.d.ts +1 -2
  148. package/dist/core/sdk-types.js.map +1 -1
  149. package/dist/core/sdk.code.js +3 -3
  150. package/dist/core/sdk.impl.js +3 -3
  151. package/dist/core/sdk.js +3 -3
  152. package/dist/core/session-manager-core.js +5 -5
  153. package/dist/core/session-manager-list.impl.js +3 -3
  154. package/dist/core/session-manager-list.js +3 -3
  155. package/dist/core/session-manager.code.js +1 -1
  156. package/dist/core/session-manager.impl.js +3 -3
  157. package/dist/core/session-manager.js +3 -3
  158. package/dist/core/session-storage.code.js +1 -1
  159. package/dist/core/session-storage.impl.js +3 -3
  160. package/dist/core/session-storage.js +3 -3
  161. package/dist/core/settings-schema.d.ts +0 -3
  162. package/dist/core/storage/added-exports-0-10-11.js +19 -0
  163. package/dist/core/storage/added-exports-0-10-11.js.map +1 -0
  164. package/dist/core/storage/creation-time.js +105 -0
  165. package/dist/core/storage/creation-time.js.map +1 -0
  166. package/dist/core/storage/database.d.ts +19 -5
  167. package/dist/core/storage/database.js.map +1 -1
  168. package/dist/core/storage/dialect.d.ts +1 -1
  169. package/dist/core/storage/dialect.js +1 -1
  170. package/dist/core/storage/dialect.js.map +1 -1
  171. package/dist/core/storage/errors.d.ts +13 -13
  172. package/dist/core/storage/errors.js +10 -16
  173. package/dist/core/storage/errors.js.map +1 -1
  174. package/dist/core/storage/fenced-paths.d.ts +11 -0
  175. package/dist/core/storage/fenced-paths.js +11 -0
  176. package/dist/core/storage/fenced-paths.js.map +1 -1
  177. package/dist/core/storage/file-identity.d.ts +2 -0
  178. package/dist/core/storage/file-identity.js +24 -8
  179. package/dist/core/storage/file-identity.js.map +1 -1
  180. package/dist/core/storage/index.d.ts +3 -2
  181. package/dist/core/storage/index.js +5 -3
  182. package/dist/core/storage/index.js.map +1 -1
  183. package/dist/core/storage/libsql-removed.d.ts +71 -0
  184. package/dist/core/storage/libsql-removed.js +123 -0
  185. package/dist/core/storage/libsql-removed.js.map +1 -0
  186. package/dist/core/storage/migrations.d.ts +78 -14
  187. package/dist/core/storage/migrations.js +375 -49
  188. package/dist/core/storage/migrations.js.map +1 -1
  189. package/dist/core/storage/node-sqlite-file-gate.js +0 -15
  190. package/dist/core/storage/node-sqlite-file-gate.js.map +1 -1
  191. package/dist/core/storage/node-sqlite-thread.js +8 -13
  192. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  193. package/dist/core/storage/node-sqlite.js +51 -3
  194. package/dist/core/storage/node-sqlite.js.map +1 -1
  195. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  196. package/dist/core/storage/offline-snapshot-file.js +3 -3
  197. package/dist/core/storage/prefix.d.ts +1 -1
  198. package/dist/core/storage/prefix.js +9 -2
  199. package/dist/core/storage/prefix.js.map +1 -1
  200. package/dist/core/storage/process-selection.d.ts +5 -5
  201. package/dist/core/storage/provider.js +2 -2
  202. package/dist/core/storage/schema-catalog.d.ts +7 -8
  203. package/dist/core/storage/schema-catalog.js +8 -8
  204. package/dist/core/storage/schema-catalog.js.map +1 -1
  205. package/dist/core/storage/selection.d.ts +7 -82
  206. package/dist/core/storage/selection.js +20 -235
  207. package/dist/core/storage/selection.js.map +1 -1
  208. package/dist/core/storage/session/branch-fork-source.code.js +2 -2
  209. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  210. package/dist/core/storage/session/branch-fork-source.js +3 -3
  211. package/dist/core/storage/session/card-view.impl.js +3 -3
  212. package/dist/core/storage/session/card-view.js +3 -3
  213. package/dist/core/storage/session/child-reader.code.js +3 -3
  214. package/dist/core/storage/session/child-reader.impl.js +3 -3
  215. package/dist/core/storage/session/child-reader.js +3 -3
  216. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  217. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  218. package/dist/core/storage/session/expanded-child-details.code.js +2 -2
  219. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  220. package/dist/core/storage/session/expanded-child-details.js +3 -3
  221. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  222. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  223. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  224. package/dist/core/storage/session/fork-row-index.js +3 -3
  225. package/dist/core/storage/session/fork-staging.code.js +4 -7
  226. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  227. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  228. package/dist/core/storage/session/fork-staging.js +3 -3
  229. package/dist/core/storage/session/fork-window.code.js +3 -3
  230. package/dist/core/storage/session/fork-window.impl.js +3 -3
  231. package/dist/core/storage/session/fork-window.js +3 -3
  232. package/dist/core/storage/session/history-pages.impl.js +3 -3
  233. package/dist/core/storage/session/history-pages.js +3 -3
  234. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  235. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  236. package/dist/core/storage/session/jsonl-session-store.d.ts +5 -1
  237. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  238. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  239. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  240. package/dist/core/storage/session/memory-session-store.js +3 -3
  241. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  242. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  243. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  244. package/dist/core/storage/session/released-history-files.code.js +3 -3
  245. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  246. package/dist/core/storage/session/released-history-files.js +3 -3
  247. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  248. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  249. package/dist/core/storage/session/session-resume.impl.js +3 -3
  250. package/dist/core/storage/session/session-resume.js +3 -3
  251. package/dist/core/storage/session/session-search-index.d.ts +43 -4
  252. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  253. package/dist/core/storage/session/snapshot-cut.js +3 -3
  254. package/dist/core/storage/session/snapshot-history.code.js +3 -3
  255. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  256. package/dist/core/storage/session/snapshot-history.js +3 -3
  257. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  258. package/dist/core/storage/session/sql-session-store.d.ts +48 -11
  259. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  260. package/dist/core/storage/session/sql-session-store.js +3 -3
  261. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  262. package/dist/core/storage/session/tree-outline.js +3 -3
  263. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  264. package/dist/core/storage/session/tree-presentation.js +3 -3
  265. package/dist/core/storage/sqlite-facade.d.ts +6 -1
  266. package/dist/core/storage/sqlite-facade.js +1 -0
  267. package/dist/core/storage/sqlite-facade.js.map +1 -1
  268. package/dist/core/storage/storage-status.code.js +1 -1
  269. package/dist/core/storage/storage-status.impl.js +3 -3
  270. package/dist/core/storage/storage-status.js +3 -3
  271. package/dist/core/storage/team.code.js +1 -1
  272. package/dist/core/storage/team.d.ts +26 -115
  273. package/dist/core/storage/team.impl.js +3 -3
  274. package/dist/core/storage/team.js +3 -3
  275. package/dist/core/structured-output/index.code.js +1 -1
  276. package/dist/core/structured-output/index.impl.js +3 -3
  277. package/dist/core/structured-output/index.js +3 -3
  278. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  279. package/dist/core/tasks/task-completion-entry.js +3 -3
  280. package/dist/core/tasks/task-file-history.code.js +3 -3
  281. package/dist/core/tasks/task-file-history.impl.js +3 -3
  282. package/dist/core/tasks/task-file-history.js +3 -3
  283. package/dist/core/tasks/task-reference-archive.code.js +4 -4
  284. package/dist/core/tasks/task-reference-archive.js +3 -3
  285. package/dist/core/tasks/task-reference-identity.js +3 -3
  286. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  287. package/dist/core/tasks/task-reference-stream.js +3 -3
  288. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  289. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  290. package/dist/core/tasks/task-view-source.code.js +1 -1
  291. package/dist/core/tasks/task-view-source.impl.js +3 -3
  292. package/dist/core/tasks/task-view-source.js +3 -3
  293. package/dist/core/tools/history-tasks.d.ts +3 -2
  294. package/dist/core/tools/read-url.code.js +4 -4
  295. package/dist/core/tools/read-url.impl.js +3 -3
  296. package/dist/core/tools/read-url.js +3 -3
  297. package/dist/core/worktree-snapshot/blob-store.d.ts +40 -3
  298. package/dist/core/worktree-snapshot/blob-store.js +414 -21
  299. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  300. package/dist/core/worktree-snapshot/errors.code.js +2 -2
  301. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  302. package/dist/core/worktree-snapshot/errors.js +3 -3
  303. package/dist/core/worktree-snapshot/fork-blob-guard.js +81 -0
  304. package/dist/core/worktree-snapshot/fork-blob-guard.js.map +1 -0
  305. package/dist/core/worktree-snapshot/fork-snapshot-index.js +79 -38
  306. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -1
  307. package/dist/core/worktree-snapshot/session-index-reset.code.js +4 -0
  308. package/dist/core/worktree-snapshot/session-index-reset.code.js.map +1 -1
  309. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  310. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  311. package/dist/extensions/codemode/execute.code.js +1 -1
  312. package/dist/extensions/codemode/execute.impl.js +3 -3
  313. package/dist/extensions/codemode/execute.js +3 -3
  314. package/dist/extensions/codemode/renderer.code.js +2 -2
  315. package/dist/extensions/codemode/renderer.impl.js +3 -3
  316. package/dist/extensions/codemode/renderer.js +3 -3
  317. package/dist/extensions/mcp/cli.code.js +3 -3
  318. package/dist/extensions/mcp/cli.impl.js +3 -3
  319. package/dist/extensions/mcp/cli.js +3 -3
  320. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  321. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  322. package/dist/extensions/mcp/cli.lazy.js +3 -3
  323. package/dist/extensions/mcp/runtime.code.js +1 -1
  324. package/dist/extensions/mcp/runtime.impl.js +3 -3
  325. package/dist/extensions/mcp/runtime.js +3 -3
  326. package/dist/index.d.ts +3 -1
  327. package/dist/index.js +5 -5
  328. package/dist/main-first-time-setup.code.js +1 -1
  329. package/dist/main-first-time-setup.impl.js +3 -3
  330. package/dist/main-first-time-setup.js +3 -3
  331. package/dist/main.js +1 -1
  332. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  333. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  334. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  335. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  336. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  337. package/dist/modes/interactive/startup-shell-eligibility.js +1 -1
  338. package/dist/modes/interactive-engine/engine-prewarm.d.ts +1 -1
  339. package/dist/modes/print-mode.js +1 -1
  340. package/dist/package-manager-cli.code.js +6 -6
  341. package/dist/package-manager-cli.impl.js +3 -3
  342. package/dist/package-manager-cli.js +3 -3
  343. package/dist/rpc-entry.js +1 -1
  344. package/dist/startup-files.json +1 -1
  345. package/dist/startup-stages/10.js +1 -1
  346. package/dist/startup-stages/11.js +1 -1
  347. package/dist/startup-stages/12.js +1 -1
  348. package/dist/startup-stages/2.js +2 -4
  349. package/dist/startup-stages/3.js +1 -3
  350. package/dist/startup-stages/4.js +1 -2
  351. package/dist/startup-stages/5.js +1 -1
  352. package/dist/startup-stages/6.js +5 -7
  353. package/dist/startup-stages/7.js +3 -10
  354. package/dist/startup-stages/8.js +7 -2
  355. package/dist/startup-stages/9.js +1 -7
  356. package/dist/startup-stages/stages.json +1 -1
  357. package/dist/utils/compile-cache-deferral.js +8 -13
  358. package/dist/utils/compile-cache-deferral.js.map +1 -1
  359. package/dist/utils/compile-cache-warmup-host.js +3 -4
  360. package/dist/utils/compile-cache-warmup-host.js.map +1 -1
  361. package/dist/utils/compile-cache.js +12 -100
  362. package/dist/utils/compile-cache.js.map +1 -1
  363. package/dist/utils/startup-database-spare.code.js +2 -2
  364. package/dist/utils/startup-database-spare.impl.js +3 -3
  365. package/dist/utils/startup-database-spare.js +3 -3
  366. package/dist/utils/tools-manager.code.js +1 -1
  367. package/dist/utils/tools-manager.impl.js +3 -3
  368. package/dist/utils/tools-manager.js +3 -3
  369. package/dist/utils/worker-threads.js +2 -15
  370. package/dist/utils/worker-threads.js.map +1 -1
  371. package/docs/build.md +3 -3
  372. package/docs/changelog.mdx +1421 -69
  373. package/docs/compaction/reference.md +5 -5
  374. package/docs/compaction.md +7 -9
  375. package/docs/containerization.md +2 -2
  376. package/docs/custom-provider/api-reference.md +1 -1
  377. package/docs/docs.json +37 -10
  378. package/docs/environment-variables.md +0 -2
  379. package/docs/extensions/api-reference.md +4 -4
  380. package/docs/getting-started/installation.md +3 -0
  381. package/docs/guides/configuration.md +1 -1
  382. package/docs/guides/non-interactive.md +1 -1
  383. package/docs/guides/resume-on-any-machine.md +14 -22
  384. package/docs/guides/team-setup.md +56 -83
  385. package/docs/guides.md +2 -4
  386. package/docs/herdr.md +1 -1
  387. package/docs/index.md +1 -1
  388. package/docs/intercom/operations.md +26 -21
  389. package/docs/intercom/reference.md +2 -2
  390. package/docs/intercom.md +1 -1
  391. package/docs/libraries/storage-postgres.md +9 -9
  392. package/docs/libraries.md +2 -3
  393. package/docs/models-configuration.md +2 -2
  394. package/docs/models.md +2 -3
  395. package/docs/packages/authoring.md +7 -7
  396. package/docs/packages.md +1 -1
  397. package/docs/programmatic.md +2 -2
  398. package/docs/quickstart.md +1 -1
  399. package/docs/reference/cli.md +6 -11
  400. package/docs/reference.md +2 -2
  401. package/docs/rpc/extension-ui.md +2 -2
  402. package/docs/sdk/reference.md +5 -4
  403. package/docs/sdk/storage.md +8 -92
  404. package/docs/sdk/structured-decisions.md +1 -1
  405. package/docs/sdk/web-server.md +3 -3
  406. package/docs/sdk.md +14 -4
  407. package/docs/security.md +1 -1
  408. package/docs/session-format.md +5 -5
  409. package/docs/sessions.md +29 -49
  410. package/docs/settings.md +7 -8
  411. package/docs/storage/custom-adapters.md +255 -0
  412. package/docs/storage/jsonl.md +117 -0
  413. package/docs/{guides/postgres-pgbouncer.md → storage/postgres/pgbouncer.md} +66 -68
  414. package/docs/storage/postgres/tuning.md +337 -0
  415. package/docs/storage/postgres.md +556 -0
  416. package/docs/storage/sqlite.md +99 -0
  417. package/docs/storage.md +326 -990
  418. package/docs/subagents/authoring.md +1 -1
  419. package/docs/subagents.md +2 -2
  420. package/docs/tools.md +1 -1
  421. package/docs/worktree-snapshots.md +2 -2
  422. package/package.json +9 -9
  423. package/schemas/models.schema.json +2 -2
  424. package/schemas/settings.schema.json +0 -14
  425. package/dist/_shared/sdk-IQMULKFU.js.map +0 -1
  426. package/dist/_shared/startup-0-0-3IXNMFM2.js.map +0 -1
  427. package/dist/_shared/startup-0-1-7T2IAE7J.js.map +0 -1
  428. package/dist/_shared/startup-8-1-X32CYSXB.js.map +0 -1
  429. package/dist/core/intercom-broker-control.d.ts +0 -129
  430. package/dist/startup-stages/13.js +0 -1
  431. package/docs/guides/postgres-tuning.md +0 -311
  432. package/docs/libraries/storage-libsql.md +0 -97
@@ -30,10 +30,28 @@ import {
30
30
  type OutboxStore,
31
31
  type StateStoreInvalidReason,
32
32
  } from "./multinode-state-store.js";
33
+ import { wakeUpNotices } from "./database-wake-up-bus.js";
33
34
  import { addMissingColumns } from "./sql-add-column.js";
34
- import { ensureBrokerSchema, withBrokerSchemaCatalog } from "./sql-schema.js";
35
+ import { deleteInBatches, SETTLED, storeNow, UNDELIVERED } from "./sql-retention.js";
36
+ import type { OutboxReservation } from "./sql-sent-message-authority.js";
37
+ import { ensureBrokerSchema, RETRY_UNAPPLIED, withBrokerSchemaCatalog } from "./sql-schema.js";
35
38
 
36
- const UNDELIVERED = "state IN ('queued', 'claimed')";
39
+ /**
40
+ * The settings a PostgreSQL send that runs in one round trip (`enqueueAtOnce`) records its decisions in, for the
41
+ * statements after the one that made them: whether the recipient's queue has room for the row, and which reservation
42
+ * of the message the send deletes if its row is not queued.
43
+ */
44
+ const SEND_ROOM = "atomic.intercom_send_room";
45
+ const SEND_FORGET = "atomic.intercom_send_forget";
46
+ /**
47
+ * The settings a one-round-trip send to a recipient its sender found offline records, for the statements after the row's
48
+ * insert: the broker holding the recipient's live presence, read with the insert, the row's sequence and recipient, and whether the
49
+ * hint log took the send's lock without waiting, so its wake-up hint was written.
50
+ */
51
+ const SEND_WAKE = "atomic.intercom_send_wake";
52
+ const SEND_WAKE_VERSION = "atomic.intercom_send_wake_version";
53
+ const SEND_WAKE_TARGET = "atomic.intercom_send_wake_target";
54
+ const SEND_HINT = "atomic.intercom_send_hint";
37
55
  /** The setting a PostgreSQL claim transaction records in that its recipient has undelivered rows, and its locks are held. */
38
56
  const CLAIM_GATE = "atomic.intercom_outbox_claim";
39
57
  /** The most `markDelivered` calls one transaction settles together (#6560). */
@@ -117,6 +135,16 @@ export interface SqlOutboxStore extends OutboxStore {
117
135
  * connection sends them with the transaction's start instead of a round trip each (#6560).
118
136
  */
119
137
  enqueueLeading(request: OutboxEnqueueRequest): readonly SqliteStatement[];
138
+ /**
139
+ * PostgreSQL: `enqueue`, and with `reservation` a send that reserves its message with it as `enqueueIn` does under
140
+ * its guard, in one transaction of the recipient's domain whose every decision the database makes, so it is one round
141
+ * trip and holds the recipient's lock domain for no round trip at all, a wake-up hint for an offline recipient's host
142
+ * included. Undefined for a request that `enqueueIn` refuses, which takes `enqueueIn`'s way.
143
+ */
144
+ enqueueAtOnce?(
145
+ request: OutboxEnqueueRequest,
146
+ reservation?: OutboxReservation,
147
+ ): Promise<OutboxEnqueueResult> | undefined;
120
148
  }
121
149
 
122
150
  /**
@@ -157,7 +185,15 @@ export async function withoutFailedWake<T>(
157
185
  * The lock domain of one recipient's sends, `<outbox>:<recipient>`: a send reserves its message and queues its row in
158
186
  * one transaction of it (`reserveAndEnqueue`, `enqueue`), so sends to one recipient run one at a time, and commit their
159
187
  * rows in the order of their sequence, and a send's checks of that recipient's queue (its size budget) hold until it
160
- * commits. Sends to other recipients, claims and every write of one row run beside them (#6560).
188
+ * commits. Sends to other recipients, claims and every write of one row run beside them (#6560). A send that a lock
189
+ * timeout ended runs again before the next send to that recipient this process makes starts (`RETRY_UNAPPLIED`).
190
+ *
191
+ * Sends to one recipient deliberately exclude one another, though a send holds the lock only while the database runs its
192
+ * statements, never across a round trip. Letting them share it (with a claim excluding them instead) would let them run
193
+ * side by side, but rows would then commit out of sequence order: a broker of an earlier release, which claims without
194
+ * waiting for sends, could hand a recipient's later message out before an earlier one during a rolling upgrade, and two
195
+ * sends could both see room for the last message the recipient's queue accepts and exceed its size budget. The time it
196
+ * would save, a few milliseconds per send, is not worth either.
161
197
  */
162
198
  export function recipientTransaction(
163
199
  database: SqliteDatabase,
@@ -165,7 +201,7 @@ export function recipientTransaction(
165
201
  targetIdentity: string,
166
202
  ): SqliteTransactionOptions {
167
203
  const outbox = `${validateStoragePrefix(prefix, dialectOf(database).name)}intercom_outbox`;
168
- return { concurrency: { kind: "serial", domain: `${outbox}:${targetIdentity}` } };
204
+ return { ...RETRY_UNAPPLIED, concurrency: { kind: "serial", domain: `${outbox}:${targetIdentity}` } };
169
205
  }
170
206
 
171
207
  /**
@@ -174,7 +210,10 @@ export function recipientTransaction(
174
210
  * transactions an older broker runs on these tables (#6560).
175
211
  */
176
212
  export function rowTransaction(): SqliteTransactionOptions {
177
- return { concurrency: { kind: "fenced", audit: fencedPath("intercom-outbox-row"), excludesSerial: true } };
213
+ return {
214
+ ...RETRY_UNAPPLIED,
215
+ concurrency: { kind: "fenced", audit: fencedPath("intercom-outbox-row"), excludesSerial: true },
216
+ };
178
217
  }
179
218
 
180
219
  /**
@@ -214,18 +253,14 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
214
253
  failure_reason TEXT,
215
254
  settled_at ${types.int}
216
255
  );
217
- CREATE INDEX IF NOT EXISTS ${table}_target ON ${table}(target_identity, state, sequence);
218
256
  `;
219
257
  await ensureBrokerSchema(database, options.prefix, "outbox", (tx) => tx.exec(schema));
220
258
  // #3983: added later; a table from an older broker gets the column, and an older broker ignores it.
221
259
  await addMissingColumns(database, table, { saving_at: types.int });
222
260
  // #4896: when the row was queued and the size of its frame; rows an older broker wrote have neither.
223
261
  await addMissingColumns(database, table, { queued_at: types.int, frame_bytes: types.int });
224
- // The per-recipient cap is summed from this index alone. Summed from the rows, `frame_bytes`, stored after the
225
- // frame, cost a read of every queued frame (overflow pages and all) on every enqueue. In a serial transaction (#5054).
226
- await ensureBrokerSchema(database, options.prefix, "outbox-indexes", (tx) =>
227
- tx.exec(`CREATE INDEX IF NOT EXISTS ${table}_target_bytes ON ${table}(target_identity, state, frame_bytes)`),
228
- );
262
+ // Its partial indexes, and its fillfactor on PostgreSQL, are set at the end of a broker's open
263
+ // (`ensureRetentionIndexes`), where the other stores' tables are there too.
229
264
 
230
265
  const columns = `sequence, message_id, target_identity, origin_broker_id, digest, frame_json, state,
231
266
  claim_attempts, claimant_id, claim_token, failure_reason,
@@ -270,6 +305,7 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
270
305
  assignments: string,
271
306
  params: readonly SqliteValue[],
272
307
  answer: (written: OutboxRecord) => Result,
308
+ relaxedDurability = false,
273
309
  ): Promise<Result | OutboxClaimWriteRejection> => {
274
310
  if (claim.messageId.length === 0) return Promise.resolve(invalid("empty-message-id"));
275
311
  if (claim.claimantId.length === 0) return Promise.resolve(invalid("empty-claimant-id"));
@@ -288,7 +324,7 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
288
324
  if (isSettled(record)) return { status: "settled", row: toRow(record) } as const;
289
325
  return { status: "stale" } as const;
290
326
  },
291
- { ...fenced, leading: [write] },
327
+ { ...fenced, leading: [write], ...(relaxedDurability ? { relaxedDurability } : {}) },
292
328
  );
293
329
  };
294
330
 
@@ -301,16 +337,22 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
301
337
  * current. Only when it changed fewer rows than it was given are the others read, to report why (#6560).
302
338
  */
303
339
  const markDeliveredTogether = (claims: readonly OutboxClaim[]): Promise<OutboxDeliveredResult[]> => {
304
- const current = claims.map(() => "(message_id = ? AND claim_token = ? AND claimant_id = ?)").join(" OR ");
305
- const keys = claims.flatMap((claim) => [claim.messageId, claim.token, claim.claimantId]);
340
+ // The claims go as one JSON parameter, so the statement's text is the same however many it settles: a server that
341
+ // keeps prepared statements, and pg_stat_statements, see one statement, not one per count (#6560). Each row is
342
+ // found by its key, then checked against its claim.
343
+ const current = "(message_id, claim_token, claimant_id) IN (SELECT message_id, claim_token, claimant_id FROM claims)";
306
344
  const write: SqliteStatement = {
307
- sql: `UPDATE ${table} SET state = 'delivered', ${settled}
308
- WHERE message_id IN (
309
- SELECT message_id FROM ${table} WHERE state = 'claimed' AND (${current})
345
+ sql: `WITH claims AS (
346
+ SELECT c ->> 0 AS message_id, c ->> 1 AS claim_token, c ->> 2 AS claimant_id FROM jsonb_array_elements(?::jsonb) AS c
347
+ )
348
+ UPDATE ${table} SET state = 'delivered', ${settled}
349
+ WHERE message_id = ANY(ARRAY(
350
+ SELECT message_id FROM ${table} WHERE state = 'claimed'
351
+ AND message_id = ANY(ARRAY(SELECT message_id FROM claims)) AND ${current}
310
352
  ORDER BY sequence${lockClause("update")}
311
- ) AND state = 'claimed' AND (${current})
353
+ )) AND state = 'claimed' AND ${current}
312
354
  RETURNING ${columns}`,
313
- params: [null, ...keys, ...keys],
355
+ params: [JSON.stringify(claims.map((claim) => [claim.messageId, claim.token, claim.claimantId])), null],
314
356
  };
315
357
  return database.transaction(
316
358
  async (executor) => {
@@ -324,8 +366,8 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
324
366
  : new Map(
325
367
  (
326
368
  await executor.all<OutboxRecord>(
327
- `SELECT ${columns} FROM ${table} WHERE message_id IN (${others.map(() => "?").join(", ")})`,
328
- ...others.map((claim) => claim.messageId),
369
+ `SELECT ${columns} FROM ${table} WHERE message_id = ANY(ARRAY(SELECT jsonb_array_elements_text(?::jsonb)))`,
370
+ JSON.stringify(others.map((claim) => claim.messageId)),
329
371
  )
330
372
  ).map((record) => [record.message_id, record]),
331
373
  );
@@ -379,7 +421,7 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
379
421
  };
380
422
 
381
423
  /**
382
- * #4896: the recipient's undelivered rows and their frame bytes, read from `<table>_target_bytes` alone. Only rows an
424
+ * #4896: the recipient's undelivered rows and their frame bytes, read from `<table>_undelivered` alone. Only rows an
383
425
  * older broker wrote, without `frame_bytes`, are measured from their frames.
384
426
  */
385
427
  const sizedTotalsStatement = (targetIdentity: string): SqliteStatement => ({
@@ -496,16 +538,23 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
496
538
  const hint = async () => {
497
539
  // PostgreSQL: never wait behind another session's lock on the hint log; such a hint goes without. The hint
498
540
  // is a new row, so it needs no lock domain of its own (#6560): see `fencedPath("intercom-wakeup-hint")`.
499
- if (dialect === "postgres") await executor.run(`LOCK TABLE ${wakeups} IN ROW EXCLUSIVE MODE NOWAIT`);
500
- await executor.run(
501
- `INSERT INTO ${wakeups}(broker_id, reason, version, created_at) VALUES (?, 'outbox', ?, ${nowMs})`,
502
- host,
503
- Number(inserted.sequence),
504
- );
505
- // Notified when it commits, as the wake-up bus's own hints are, so the host does not wait for its backup
506
- // poll (#6560).
507
- const notify = database.notifications?.notify(wakeups, host);
508
- if (notify !== undefined) await executor.run(notify.sql, ...notify.params);
541
+ // Notified once it commits, as the wake-up bus's own hints are, so the host does not wait for its backup
542
+ // poll (#6560); on Postgres the notifications go right behind the commit, outside it.
543
+ const notifications = database.notifications;
544
+ const statements: SqliteStatement[] = [
545
+ ...(dialect === "postgres" ? [{ sql: `LOCK TABLE ${wakeups} IN ROW EXCLUSIVE MODE NOWAIT`, params: [] }] : []),
546
+ {
547
+ sql: `INSERT INTO ${wakeups}(broker_id, reason, version, created_at, target_identity)
548
+ VALUES (?, 'outbox', ?, ${nowMs}, ?)`,
549
+ params: [host, Number(inserted.sequence), request.targetIdentity],
550
+ },
551
+ ...(notifications === undefined ? [] : wakeUpNotices(notifications, wakeups, leases, host)),
552
+ ];
553
+ // Together, in one round trip, on a pipelined transaction's own handle, which sends calls in the order they
554
+ // are made: a lock refused aborts the transaction, so the insert after it fails too.
555
+ if (finisherOf?.(executor) !== undefined)
556
+ await Promise.all(statements.map(({ sql, params }) => executor.run(sql, ...params)));
557
+ else for (const { sql, params } of statements) await executor.run(sql, ...params);
509
558
  };
510
559
  await hint().catch((cause: unknown) => {
511
560
  throw new OutboxWakeFailedError(cause);
@@ -519,15 +568,206 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
519
568
  ...(request.owed === true ? [] : [sizedTotalsStatement(request.targetIdentity)]),
520
569
  ];
521
570
 
571
+ /**
572
+ * PostgreSQL: a send in statements that the database decides alone, sent together with the transaction's start and
573
+ * commit. The recipient's lock domain, taken with the start, is held while the server runs them and never across a
574
+ * round trip to the broker, so sends to one busy recipient wait for each other only that long. Under the lock, as
575
+ * `enqueueIn` and the guard decide it across round trips:
576
+ * 1. `decide` reads the message's row and reservation and the recipient's queue, and records in the transaction whether
577
+ * the queue has room for the row, and whether the send's earlier reservation goes because it has not.
578
+ * 2. With a reservation, it is written only while no row of the message with another digest is queued, and either the
579
+ * queue has room or the send's own row is queued already; a reservation of the message already there is left as it is.
580
+ * 3. The row is inserted only while the queue has room and the send's digest holds the reservation. For a recipient its
581
+ * sender found offline (`wakeHostWithinMs`), the insert also reads, and locks shared, the recipient's live presence,
582
+ * as `enqueueIn` does, and records the broker holding it.
583
+ * 4. With such a broker, a block locks the hint log without waiting and writes the hint, naming the broker and the row's
584
+ * sequence, and records that it did: a hint log another session holds locked leaves the send without its hint, as
585
+ * in `enqueueIn`, and fails nothing.
586
+ * 5. A read of whether it did.
587
+ * 6. A reservation the send wrote is deleted again when its row is not queued, and an earlier one when the queue was full.
588
+ * 7. The message's row is read, to answer a send whose row was not inserted.
589
+ * Each statement sees what every transaction that committed before it wrote, as each of `enqueueIn`'s does. The hint's
590
+ * notification goes out after the commit, so the transaction ends without waiting for it.
591
+ */
592
+ const enqueueAtOnce = (
593
+ request: OutboxEnqueueRequest,
594
+ reservation?: OutboxReservation,
595
+ ): Promise<OutboxEnqueueResult> | undefined => {
596
+ const messageId = request.frame.message.id;
597
+ if (request.targetIdentity.length === 0 || request.originBrokerId.length === 0 || messageId.length === 0)
598
+ return undefined;
599
+ const frameJson = JSON.stringify(request.frame);
600
+ const frameBytes = Buffer.byteLength(frameJson);
601
+ const queuedTotals =
602
+ request.owed === true
603
+ ? { sql: "(SELECT 1) AS totals", params: [] as SqliteValue[] }
604
+ : {
605
+ sql: `(SELECT COUNT(*) AS row_count, COALESCE(SUM(frame_bytes), 0) + COALESCE((
606
+ SELECT SUM(LENGTH(frame_json)) FROM ${table}
607
+ WHERE target_identity = ? AND ${UNDELIVERED} AND frame_bytes IS NULL
608
+ ), 0) AS byte_count
609
+ FROM ${table} WHERE target_identity = ? AND ${UNDELIVERED}) AS totals`,
610
+ params: [request.targetIdentity, request.targetIdentity],
611
+ };
612
+ const room =
613
+ request.owed === true
614
+ ? { sql: "1", params: [] as SqliteValue[] }
615
+ : {
616
+ sql: "CASE WHEN totals.row_count < ? AND totals.byte_count + ? <= ? THEN 1 ELSE 0 END",
617
+ params: [OUTBOX_TARGET_MAX_ROWS, frameBytes, OUTBOX_TARGET_MAX_BYTES],
618
+ };
619
+ const holder = reservation?.holder ?? { sql: "SELECT CAST(NULL AS TEXT)", params: [] };
620
+ const decide: SqliteStatement = {
621
+ sql: `SELECT decided.room, decided.queued_digest, decided.reserved_digest,
622
+ set_config('${SEND_ROOM}', CASE WHEN decided.room = 1 THEN 'room' ELSE 'full' END, true) AS room_gate,
623
+ set_config('${SEND_FORGET}', CASE WHEN decided.room = 0 AND decided.queued_digest IS NULL
624
+ AND decided.reserved_digest = ? THEN 'earlier' ELSE '' END, true) AS forget_gate
625
+ FROM (
626
+ SELECT ${room.sql} AS room, (SELECT digest FROM ${table} WHERE message_id = ?) AS queued_digest,
627
+ (${holder.sql}) AS reserved_digest
628
+ FROM ${queuedTotals.sql}
629
+ ) AS decided`,
630
+ params: [reservation?.digest ?? null, ...room.params, messageId, ...holder.params, ...queuedTotals.params],
631
+ };
632
+ const hasRoom = `current_setting('${SEND_ROOM}', true) = 'room'`;
633
+ const reserve = reservation?.reserveWhere(
634
+ {
635
+ sql: `NOT EXISTS (SELECT 1 FROM ${table} WHERE message_id = ? AND digest <> ?)
636
+ AND (${hasRoom} OR EXISTS (SELECT 1 FROM ${table} WHERE message_id = ? AND digest = ?))`,
637
+ params: [messageId, request.digest, messageId, request.digest],
638
+ },
639
+ `set_config('${SEND_FORGET}', 'new', true) AS reserved`,
640
+ );
641
+ const held = reservation?.held ?? { sql: "1 = 1", params: [] };
642
+ const wakes = request.wakeHostWithinMs !== undefined;
643
+ // #5607: read in this transaction, under the row's insert, as `enqueueIn` reads it: see there.
644
+ const presence = wakes
645
+ ? {
646
+ sql: `, set_config('${SEND_WAKE}', COALESCE((
647
+ SELECT presence.holder_id FROM ${leases} presence
648
+ WHERE presence.kind = 'presence' AND presence.key = ? AND presence.holder_id IS NOT NULL
649
+ AND ${greatest("0", `${nowMs} - presence.renewed_at`)} <= ?${lockClause("share")}
650
+ ), ''), true) AS presence_holder, set_config('${SEND_WAKE_VERSION}', CAST(sequence AS TEXT), true) AS hint_version,
651
+ set_config('${SEND_WAKE_TARGET}', target_identity, true) AS hint_target`,
652
+ params: [request.targetIdentity, request.wakeHostWithinMs!] as SqliteValue[],
653
+ }
654
+ : { sql: "", params: [] as SqliteValue[] };
655
+ const insert: SqliteStatement = {
656
+ sql: `INSERT INTO ${table}(message_id, target_identity, origin_broker_id, digest, frame_json, state, queued_at,
657
+ frame_bytes)
658
+ SELECT ?, ?, ?, ?, ?, 'queued', ${nowMs}, CAST(? AS ${types.int})
659
+ WHERE ${hasRoom} AND ${held.sql}
660
+ ON CONFLICT(message_id) DO NOTHING
661
+ RETURNING ${columns}${presence.sql}`,
662
+ params: [
663
+ messageId,
664
+ request.targetIdentity,
665
+ request.originBrokerId,
666
+ request.digest,
667
+ frameJson,
668
+ frameBytes,
669
+ ...held.params,
670
+ ...presence.params,
671
+ ],
672
+ };
673
+ const woken = `COALESCE(current_setting('${SEND_WAKE}', true), '')`;
674
+ // Locks the hint log and writes the hint only with such a broker, and never waits behind another session's lock on
675
+ // the log: such a send goes without its hint (#5607). A hint is a new row, so it needs no lock domain of its own
676
+ // (#6560): see `fencedPath("intercom-wakeup-hint")`. Even an insert of no row would wait for the log's lock, so the
677
+ // insert is made in the block, only once the lock is held.
678
+ const writeHint: SqliteStatement = {
679
+ sql: `DO $atomic_send$ BEGIN
680
+ IF ${woken} <> '' THEN
681
+ LOCK TABLE ${wakeups} IN ROW EXCLUSIVE MODE NOWAIT;
682
+ INSERT INTO ${wakeups}(broker_id, reason, version, created_at, target_identity)
683
+ VALUES (${woken}, 'outbox', CAST(current_setting('${SEND_WAKE_VERSION}') AS BIGINT), ${nowMs},
684
+ current_setting('${SEND_WAKE_TARGET}'));
685
+ PERFORM set_config('${SEND_HINT}', 'written', true);
686
+ END IF;
687
+ EXCEPTION WHEN lock_not_available THEN NULL;
688
+ END $atomic_send$`,
689
+ params: [],
690
+ };
691
+ const hint: SqliteStatement = {
692
+ sql: `SELECT ${woken} AS broker_id WHERE COALESCE(current_setting('${SEND_HINT}', true), '') = 'written'`,
693
+ params: [],
694
+ };
695
+ const forget = reservation?.forgetWhere({
696
+ sql: `current_setting('${SEND_FORGET}', true) = 'earlier' OR (current_setting('${SEND_FORGET}', true) = 'new'
697
+ AND NOT EXISTS (SELECT 1 FROM ${table} WHERE message_id = ? AND digest = ?))`,
698
+ params: [messageId, request.digest],
699
+ });
700
+ const queued = selectStatement(messageId);
701
+ const leading = [
702
+ decide,
703
+ ...(reserve === undefined ? [] : [reserve]),
704
+ insert,
705
+ ...(wakes ? [writeHint, hint] : []),
706
+ ...(forget === undefined ? [] : [forget]),
707
+ queued,
708
+ ];
709
+ const answer = async (executor: SqliteExecutor): Promise<OutboxEnqueueResult> => {
710
+ // In the order of `leading`, each answered with the transaction's start: no call waits for a round trip.
711
+ const decided = (await executor.get<SqliteRow & { room: SqliteValue; reserved_digest: string | null }>(
712
+ decide.sql,
713
+ ...decide.params,
714
+ ))!;
715
+ if (reserve !== undefined) await executor.all(reserve.sql, ...reserve.params);
716
+ const row = await executor.get<OutboxRecord>(insert.sql, ...insert.params);
717
+ let woke: string | undefined;
718
+ if (wakes) {
719
+ // A database that cannot run the block (no PL/pgSQL for this role) writes the send again without its hint.
720
+ await executor.run(writeHint.sql).catch((cause: unknown) => {
721
+ throw new OutboxWakeFailedError(cause);
722
+ });
723
+ woke = (await executor.get<SqliteRow & { broker_id: string }>(hint.sql, ...hint.params))?.broker_id;
724
+ }
725
+ if (forget !== undefined) await executor.run(forget.sql, ...forget.params);
726
+ const found = await executor.get<OutboxRecord>(queued.sql, ...queued.params);
727
+ if (row !== undefined)
728
+ return { status: "inserted", row: toRow(row), ...(woke === undefined ? {} : { woke }) } as const;
729
+ // Another digest held the message's reservation: the send is refused, as before it wrote anything.
730
+ if (decided.reserved_digest !== null && decided.reserved_digest !== reservation?.digest)
731
+ return { status: "conflict", messageId };
732
+ if (found !== undefined)
733
+ return found.digest === request.digest
734
+ ? { status: "duplicate", row: toRow(found) }
735
+ : { status: "conflict", messageId };
736
+ if (Number(decided.room) === 0)
737
+ return { status: "full", limit: OUTBOX_TARGET_MAX_ROWS, byteLimit: OUTBOX_TARGET_MAX_BYTES };
738
+ return { status: "conflict", messageId };
739
+ };
740
+ return database
741
+ .transaction(answer, {
742
+ ...recipientTransaction(database, options.prefix, request.targetIdentity),
743
+ leading,
744
+ leadingOnly: true,
745
+ })
746
+ .then((result) => {
747
+ // Notified once the hint committed, on the host's own channel (and the shared one only for a host of an
748
+ // earlier release), as the wake-up bus's own hints are, so the host does not wait for its backup poll
749
+ // (#6560); the hint is there for its poll if a notification is lost.
750
+ const notifications = database.notifications;
751
+ if (result.status === "inserted" && result.woke !== undefined && notifications !== undefined)
752
+ for (const { sql, params } of wakeUpNotices(notifications, wakeups, leases, result.woke))
753
+ void database.run(sql, ...params).catch(() => {});
754
+ return result;
755
+ });
756
+ };
757
+
758
+ const enqueueAtOnceIfPostgres = (request: OutboxEnqueueRequest, reservation?: OutboxReservation) =>
759
+ dialect === "postgres" ? enqueueAtOnce(request, reservation) : undefined;
760
+
522
761
  return {
523
762
  enqueueIn,
524
763
  enqueueLeading,
764
+ ...(dialect === "postgres" ? { enqueueAtOnce } : {}),
525
765
  async enqueue(request) {
526
766
  if (request.targetIdentity.length === 0) return invalid("empty-target-identity");
527
767
  if (request.originBrokerId.length === 0) return invalid("empty-broker-id");
528
768
  if (request.frame.message.id.length === 0) return invalid("empty-message-id");
529
769
  return withoutFailedWake(request, (attempt) =>
530
- database.transaction((executor) => enqueueIn(executor, attempt), {
770
+ enqueueAtOnceIfPostgres(attempt) ?? database.transaction((executor) => enqueueIn(executor, attempt), {
531
771
  ...recipientTransaction(database, options.prefix, attempt.targetIdentity),
532
772
  leading: enqueueLeading(attempt),
533
773
  }),
@@ -612,6 +852,7 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
612
852
  return claimed(records.filter((record) => record.message_id !== null));
613
853
  },
614
854
  {
855
+ ...RETRY_UNAPPLIED,
615
856
  concurrency: { kind: "serial", domain: `${table}_claims:${targetIdentity}` },
616
857
  leading: [waiting, statement],
617
858
  leadingOnly: true,
@@ -619,7 +860,7 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
619
860
  },
620
861
  );
621
862
  }
622
- // SQLite and libSQL: a write statement takes the database's write lock even when it changes nothing, so a read
863
+ // SQLite: a write statement takes the database's write lock even when it changes nothing, so a read
623
864
  // decides first, without it, whether there is anything to claim: empty scans (such as fan-out wake-up polls across
624
865
  // idle sessions) cost one read. Linearizable: if a row commits after this snapshot, its enqueue writes a new
625
866
  // wake-up hint. The same read answers a claim another claimant holds, or one of only the claimant's own rows in
@@ -665,7 +906,10 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
665
906
  },
666
907
 
667
908
  renewClaim(claim) {
668
- return withClaim(claim, `claim_renewed_at = ${nowMs}`, [], () => ({ status: "renewed" }) as const);
909
+ // Its claimant renews again within the renewal interval, far inside the claim's staleness limit: a renewal lost
910
+ // in a crash of the database server leaves the claim a renewal older and still current, so its commit does not
911
+ // wait for the disk.
912
+ return withClaim(claim, `claim_renewed_at = ${nowMs}`, [], () => ({ status: "renewed" }) as const, true);
669
913
  },
670
914
 
671
915
  reportSaving(claim) {
@@ -731,7 +975,7 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
731
975
  async undeliveredPosition(targetIdentity, messageId) {
732
976
  if (targetIdentity.length === 0) return invalid("empty-target-identity");
733
977
  if (messageId.length === 0) return invalid("empty-message-id");
734
- // Counted on the (target_identity, state, sequence) index: no row, and no frame, is read.
978
+ // Counted on `<outbox>_undelivered`: no row, and no frame, is read.
735
979
  const counted = await database.get<{ position: SqliteValue }>(
736
980
  `SELECT COUNT(*) AS position FROM ${table}
737
981
  WHERE target_identity = ? AND ${UNDELIVERED} AND sequence <= (
@@ -746,11 +990,16 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
746
990
  },
747
991
 
748
992
  async prune(settledOlderThanMs, queuedOlderThanMs) {
993
+ // Each age compared as `column < now - age`, so an index on the column answers it.
994
+ const now = storeNow(database);
749
995
  if (queuedOlderThanMs !== undefined) {
750
996
  // Every recipient's rows, each locked in sequence order and decided on in its newest version, as a claim
751
- // locks them: a renewal that commits first keeps its row, and expiry waits for no lock domain (#6560).
752
- const lockedWhere = (where: string) =>
753
- `message_id IN (SELECT message_id FROM ${table} WHERE ${where} ORDER BY sequence${lockClause("update")})`;
997
+ // locks them: a renewal that commits first keeps its row, and expiry waits for no lock domain (#6560). PostgreSQL
998
+ // takes the locked rows' ids as one array, so the update finds each by its key rather than joining the table.
999
+ const lockedWhere = (where: string) => {
1000
+ const locked = `SELECT message_id FROM ${table} WHERE ${where} ORDER BY sequence${lockClause("update")}`;
1001
+ return dialect === "postgres" ? `message_id = ANY(ARRAY(${locked}))` : `message_id IN (${locked})`;
1002
+ };
754
1003
  await database.transaction(async (executor) => {
755
1004
  // A row an older broker queued has no time: its retention starts now.
756
1005
  await executor.run(
@@ -759,8 +1008,8 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
759
1008
  await executor.run(
760
1009
  `UPDATE ${table} SET state = 'failed', ${settled}
761
1010
  WHERE ${lockedWhere(
762
- `${UNDELIVERED} AND ${ageSince("queued_at")} > ?
763
- AND (claim_renewed_at IS NULL OR ${ageSince("claim_renewed_at")} > ?)`,
1011
+ `${UNDELIVERED} AND queued_at < ${now} - ?
1012
+ AND (claim_renewed_at IS NULL OR claim_renewed_at < ${now} - ?)`,
764
1013
  )}`,
765
1014
  JSON.stringify(OUTBOX_EXPIRED_REASON),
766
1015
  queuedOlderThanMs,
@@ -768,12 +1017,14 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
768
1017
  );
769
1018
  }, fenced);
770
1019
  }
771
- const result = await database.run(
772
- `DELETE FROM ${table}
773
- WHERE state IN ('delivered', 'failed') AND ${ageSince("settled_at")} > ?`,
774
- settledOlderThanMs,
775
- );
776
- return result.changes;
1020
+ // Oldest first, from `<outbox>_settled`, in batches.
1021
+ return deleteInBatches(database, {
1022
+ table,
1023
+ key: "sequence",
1024
+ where: `${SETTLED} AND settled_at < ${now} - ?`,
1025
+ params: [settledOlderThanMs],
1026
+ orderBy: "settled_at",
1027
+ });
777
1028
  },
778
1029
  };
779
1030
  }
@@ -19,7 +19,8 @@ import type {
19
19
  } from "./multinode-state-store.js";
20
20
  import { SETTLED_ASK_RETENTION_MS } from "./multinode-state-store.js";
21
21
  import { addMissingColumns } from "./sql-add-column.js";
22
- import { ensureBrokerSchema, withBrokerSchemaCatalog } from "./sql-schema.js";
22
+ import { storeNow } from "./sql-retention.js";
23
+ import { ensureBrokerSchema, RETRY_UNAPPLIED, withBrokerSchemaCatalog } from "./sql-schema.js";
23
24
 
24
25
  type AskRow = SqliteRow & { sender_session_id: string; target_session_id: string; message_id: string };
25
26
 
@@ -60,12 +61,12 @@ async function openPendingAskStoreInCatalog({
60
61
  prefix,
61
62
  }: IntercomBrokerStateOptions): Promise<PendingAskStore> {
62
63
  const table = `${validateStoragePrefix(prefix, dialectOf(database).name)}intercom_pending_asks`;
63
- const { types, nowMs, greatest } = dialectOf(database);
64
+ const { types, nowMs } = dialectOf(database);
64
65
  /**
65
66
  * Its transactions read and write this table and the settled asks alone, which no other store touches, so they
66
67
  * exclude one another, not every writer of the database (#6560).
67
68
  */
68
- const serial = { concurrency: { kind: "serial", domain: table } } as const;
69
+ const serial = { ...RETRY_UNAPPLIED, concurrency: { kind: "serial", domain: table } } as const;
69
70
  await ensureBrokerSchema(database, prefix, "pending-asks", (tx) =>
70
71
  tx.exec(`
71
72
  CREATE TABLE IF NOT EXISTS ${table}(
@@ -87,6 +88,8 @@ async function openPendingAskStoreInCatalog({
87
88
  replied: types.int,
88
89
  ended_at: types.int,
89
90
  });
91
+ /** The database clock, read once per statement: a column compared with it is answered by its index. */
92
+ const now = storeNow(database);
90
93
  // #4997: asks answered or failed, remembered so a stopped broker's copy of one is not recorded again.
91
94
  const settled = `${validateStoragePrefix(prefix)}intercom_settled_asks`;
92
95
  await ensureBrokerSchema(database, prefix, "settled-asks", (tx) =>
@@ -141,7 +144,7 @@ async function openPendingAskStoreInCatalog({
141
144
  ON CONFLICT DO NOTHING`,
142
145
  ...reverseParams(route),
143
146
  );
144
- await tx.run(`DELETE FROM ${settled} WHERE settled_at < ${nowMs} - ?`, SETTLED_ASK_RETENTION_MS);
147
+ await tx.run(`DELETE FROM ${settled} WHERE settled_at < ${now} - ?`, SETTLED_ASK_RETENTION_MS);
145
148
  return changes === 0 ? ({ status: "no-match" } as const) : ({ status: "cleared" } as const);
146
149
  }, serial);
147
150
  },
@@ -279,7 +282,7 @@ async function openPendingAskStoreInCatalog({
279
282
  async listEnded(olderThanMs): Promise<PendingAskListResult> {
280
283
  const rows = await database.all<AskRow>(
281
284
  `SELECT sender_session_id, target_session_id, message_id FROM ${table}
282
- WHERE ended_at IS NOT NULL AND replied IS NULL AND ${greatest("0", `${nowMs} - ended_at`)} >= ?
285
+ WHERE ended_at IS NOT NULL AND replied IS NULL AND ended_at <= ${now} - ?
283
286
  ORDER BY ended_at, "order"`,
284
287
  olderThanMs,
285
288
  );
@@ -17,7 +17,8 @@ import type {
17
17
  ReleasedAskSupersede,
18
18
  StateStoreInvalidReason,
19
19
  } from "./multinode-state-store.js";
20
- import { ensureBrokerSchema, withBrokerSchemaCatalog } from "./sql-schema.js";
20
+ import { deleteInBatches, storeNow } from "./sql-retention.js";
21
+ import { ensureBrokerSchema, RETRY_UNAPPLIED, withBrokerSchemaCatalog } from "./sql-schema.js";
21
22
 
22
23
  interface ReleasedAskRow extends SqliteRow {
23
24
  readonly question_id: string;
@@ -79,7 +80,7 @@ async function openReleasedAskStoreInCatalog({ database, prefix }: IntercomBroke
79
80
  const table = `${validateStoragePrefix(prefix, dialectOf(database).name)}intercom_released_asks`;
80
81
  const { types, nowMs, greatest } = dialectOf(database);
81
82
  /** Its transactions read and write this table alone, so they exclude one another, not every writer (#6560). */
82
- const serial = { concurrency: { kind: "serial", domain: table } } as const;
83
+ const serial = { ...RETRY_UNAPPLIED, concurrency: { kind: "serial", domain: table } } as const;
83
84
  await ensureBrokerSchema(database, prefix, "released-asks", (tx) =>
84
85
  tx.exec(`
85
86
  CREATE TABLE IF NOT EXISTS ${table}(
@@ -189,9 +190,15 @@ async function openReleasedAskStoreInCatalog({ database, prefix }: IntercomBroke
189
190
  if (bad !== undefined) return bad;
190
191
  return settle(claim, "open", ["claimed"]);
191
192
  },
192
- async prune(olderThanMs) {
193
- const { changes } = await database.run(`DELETE FROM ${table} WHERE expires_at + ? < ${nowMs}`, olderThanMs);
194
- return changes;
193
+ prune(olderThanMs) {
194
+ // Oldest first, from `<table>_expires`, in batches.
195
+ return deleteInBatches(database, {
196
+ table,
197
+ key: '"order"',
198
+ where: `expires_at < ${storeNow(database)} - ?`,
199
+ params: [olderThanMs],
200
+ orderBy: "expires_at",
201
+ });
195
202
  },
196
203
  };
197
204