@bastani/atomic 0.10.11-alpha.1 → 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 (457) hide show
  1. package/CHANGELOG.md +155 -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 +9 -9
  7. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +8 -8
  8. package/dist/_shared/mode-shared-2QJSCUM6.js +9 -9
  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 +5 -5
  16. package/dist/_shared/{sdk-AVFII7NK.js → sdk-B5LEWGGI.js} +2633 -488
  17. package/dist/_shared/sdk-B5LEWGGI.js.map +1 -0
  18. package/dist/_shared/session-data-AHTU7IS6.js +3 -3
  19. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  20. package/dist/_shared/settings-startup-8-DNZ2RIHM.js +1 -1
  21. package/dist/_shared/{settings-startup-4QCVCI53.js → settings-startup-HXQLSUWM.js} +8 -2
  22. package/dist/_shared/settings-startup-HXQLSUWM.js.map +1 -0
  23. package/dist/_shared/{startup-0-0-57KF6LZH.js → startup-0-0-EZUKEP4Q.js} +436 -51
  24. package/dist/_shared/startup-0-0-EZUKEP4Q.js.map +1 -0
  25. package/dist/_shared/{startup-0-1-GIY75K46.js → startup-0-1-RTOHJFDJ.js} +240 -279
  26. package/dist/_shared/startup-0-1-RTOHJFDJ.js.map +1 -0
  27. package/dist/_shared/{startup-0-2-27OWFHV6.js → startup-0-2-5QHPCEON.js} +254 -46
  28. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -0
  29. package/dist/_shared/{startup-0-3-T4DVFYWX.js → startup-0-3-4ZYBYQNM.js} +273 -14
  30. package/dist/_shared/startup-0-3-4ZYBYQNM.js.map +1 -0
  31. package/dist/_shared/startup-0-4-ZMJV547D.js +14 -9
  32. package/dist/_shared/startup-0-4-ZMJV547D.js.map +1 -1
  33. package/dist/_shared/startup-0-5-YDW47QX6.js +10 -10
  34. package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -1
  35. package/dist/_shared/startup-10-0-TDQNBDDL.js +9 -9
  36. package/dist/_shared/startup-12-0-55AAXBJZ.js +3 -3
  37. package/dist/_shared/startup-14-0-MLX36RBG.js +6 -7
  38. package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
  39. package/dist/_shared/startup-15-0-YUKGAC63.js +7 -7
  40. package/dist/_shared/startup-15-1-4S7FLMNG.js +22 -30
  41. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  42. package/dist/_shared/startup-8-0-34CBHPZH.js +455 -102
  43. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  44. package/dist/_shared/{startup-8-1-X32CYSXB.js → startup-8-1-LZFXSD3Z.js} +162 -1184
  45. package/dist/_shared/startup-8-1-LZFXSD3Z.js.map +1 -0
  46. package/dist/_shared/storage-command-7MGXLJGZ.js +189 -36
  47. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  48. package/dist/_shared/storage-status-K7PX2RXA.js +557 -0
  49. package/dist/_shared/storage-status-K7PX2RXA.js.map +1 -0
  50. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  51. package/dist/_shared/team-DOQKICG2.js +376 -0
  52. package/dist/_shared/team-DOQKICG2.js.map +1 -0
  53. package/dist/_shared/tree-outline-MUEPK5B7.js +3 -3
  54. package/dist/builtin/intercom/CHANGELOG.md +34 -0
  55. package/dist/builtin/intercom/README.md +2 -2
  56. package/dist/builtin/intercom/broker/broker.bundle.mjs +1091 -344
  57. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +243 -64
  58. package/dist/builtin/intercom/broker/multinode-router.ts +154 -22
  59. package/dist/builtin/intercom/broker/multinode-state-store.ts +30 -3
  60. package/dist/builtin/intercom/broker/open-broker-state.ts +14 -0
  61. package/dist/builtin/intercom/broker/sql-add-column.ts +29 -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 +208 -101
  66. package/dist/builtin/intercom/broker/sql-outbox-store.ts +516 -102
  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 +24 -7
  70. package/dist/builtin/intercom/broker/sql-retention.ts +141 -0
  71. package/dist/builtin/intercom/broker/sql-schema.ts +199 -27
  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 +2 -3
  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/src/extension/index.bundle.mjs +1 -1
  81. package/dist/builtin/web-access/index.bundle.mjs +2 -10
  82. package/dist/builtin/web-access/package.json +1 -1
  83. package/dist/bun/bundled-sqlite.js +41 -0
  84. package/dist/bun/bundled-sqlite.js.map +1 -0
  85. package/dist/cli/args.js +2 -2
  86. package/dist/cli/auth-cli.code.js +6 -6
  87. package/dist/cli/auth-cli.impl.js +3 -3
  88. package/dist/cli/auth-cli.js +3 -3
  89. package/dist/cli/blueprint-command.code.js +4 -4
  90. package/dist/cli/blueprint-command.impl.js +3 -3
  91. package/dist/cli/blueprint-command.js +3 -3
  92. package/dist/cli/intercom-command.code.js +4 -4
  93. package/dist/cli/intercom-command.code.js.map +1 -1
  94. package/dist/cli/intercom-command.impl.js +3 -3
  95. package/dist/cli/intercom-command.js +3 -3
  96. package/dist/cli/list-models.code.js +2 -2
  97. package/dist/cli/list-models.impl.js +3 -3
  98. package/dist/cli/list-models.js +3 -3
  99. package/dist/cli/session-picker.code.js +2 -2
  100. package/dist/cli/session-picker.impl.js +3 -3
  101. package/dist/cli/session-picker.js +3 -3
  102. package/dist/cli/startup-ui.code.js +2 -2
  103. package/dist/cli/startup-ui.impl.js +3 -3
  104. package/dist/cli/startup-ui.js +3 -3
  105. package/dist/cli/storage-command.impl.js +3 -3
  106. package/dist/cli/storage-command.js +3 -3
  107. package/dist/cli/storage-search-session.code.js +3 -3
  108. package/dist/cli/storage-search-session.impl.js +3 -3
  109. package/dist/cli/storage-search-session.js +3 -3
  110. package/dist/cli/team-command.code.js +20 -114
  111. package/dist/cli/team-command.code.js.map +1 -1
  112. package/dist/cli/team-command.impl.js +3 -3
  113. package/dist/cli/team-command.js +3 -3
  114. package/dist/cli.js +5 -18
  115. package/dist/cli.js.map +1 -1
  116. package/dist/core/agent-rehydrate-errors.d.ts +4 -9
  117. package/dist/core/compaction/compactor.d.ts +3 -3
  118. package/dist/core/debug.code.js +1 -1
  119. package/dist/core/debug.impl.js +3 -3
  120. package/dist/core/debug.js +3 -3
  121. package/dist/core/export-html/card-projection.impl.js +3 -3
  122. package/dist/core/export-html/card-projection.js +3 -3
  123. package/dist/core/export-html/index.code.js +2 -2
  124. package/dist/core/export-html/index.impl.js +3 -3
  125. package/dist/core/export-html/index.js +3 -3
  126. package/dist/core/export-html/json-spans.impl.js +3 -3
  127. package/dist/core/export-html/json-spans.js +3 -3
  128. package/dist/core/export-html/oversized-render-inputs.code.js +1 -1
  129. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  130. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  131. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  132. package/dist/core/export-html/tool-renderer.js +3 -3
  133. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  134. package/dist/core/extensions/jiti-loader.js +3 -3
  135. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  136. package/dist/core/extensions/jiti-static-loader.js +3 -3
  137. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  138. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  139. package/dist/core/extensions/loader-host-modules.js +3 -3
  140. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  141. package/dist/core/extensions/runner-context.js +3 -3
  142. package/dist/core/intercom-broker-control-host.code.js +2 -2
  143. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  144. package/dist/core/intercom-broker-control-host.js +3 -3
  145. package/dist/core/intercom-broker-control.code.js +3 -3
  146. package/dist/core/intercom-broker-control.impl.js +3 -3
  147. package/dist/core/intercom-broker-control.js +3 -3
  148. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  149. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  150. package/dist/core/package-manager-storage-adapters.js +3 -3
  151. package/dist/core/process-start-token.d.ts +8 -0
  152. package/dist/core/process-tree-containment.d.ts +16 -0
  153. package/dist/core/sdk-types.d.ts +1 -2
  154. package/dist/core/sdk-types.js.map +1 -1
  155. package/dist/core/sdk.code.js +4 -4
  156. package/dist/core/sdk.impl.js +3 -3
  157. package/dist/core/sdk.js +3 -3
  158. package/dist/core/session-manager-core.js +27 -15
  159. package/dist/core/session-manager-core.js.map +1 -1
  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 +3 -3
  163. package/dist/core/session-manager.impl.js +3 -3
  164. package/dist/core/session-manager.js +3 -3
  165. package/dist/core/session-open-markers.js +3 -0
  166. package/dist/core/session-open-markers.js.map +1 -0
  167. package/dist/core/session-storage.code.js +1 -1
  168. package/dist/core/session-storage.impl.js +3 -3
  169. package/dist/core/session-storage.js +3 -3
  170. package/dist/core/settings-schema.d.ts +0 -3
  171. package/dist/core/storage/added-exports-0-10-11.js +19 -0
  172. package/dist/core/storage/added-exports-0-10-11.js.map +1 -0
  173. package/dist/core/storage/added-exports.js +3 -0
  174. package/dist/core/storage/added-exports.js.map +1 -1
  175. package/dist/core/storage/creation-time.js +105 -0
  176. package/dist/core/storage/creation-time.js.map +1 -0
  177. package/dist/core/storage/database.d.ts +56 -5
  178. package/dist/core/storage/database.js.map +1 -1
  179. package/dist/core/storage/dialect.d.ts +1 -1
  180. package/dist/core/storage/dialect.js +1 -1
  181. package/dist/core/storage/dialect.js.map +1 -1
  182. package/dist/core/storage/errors.d.ts +13 -13
  183. package/dist/core/storage/errors.js +10 -16
  184. package/dist/core/storage/errors.js.map +1 -1
  185. package/dist/core/storage/fenced-paths.d.ts +11 -0
  186. package/dist/core/storage/fenced-paths.js +11 -0
  187. package/dist/core/storage/fenced-paths.js.map +1 -1
  188. package/dist/core/storage/file-identity.d.ts +2 -0
  189. package/dist/core/storage/file-identity.js +24 -8
  190. package/dist/core/storage/file-identity.js.map +1 -1
  191. package/dist/core/storage/index.d.ts +4 -3
  192. package/dist/core/storage/index.js +5 -3
  193. package/dist/core/storage/index.js.map +1 -1
  194. package/dist/core/storage/libsql-removed.d.ts +71 -0
  195. package/dist/core/storage/libsql-removed.js +123 -0
  196. package/dist/core/storage/libsql-removed.js.map +1 -0
  197. package/dist/core/storage/migrations.d.ts +81 -8
  198. package/dist/core/storage/migrations.js +386 -47
  199. package/dist/core/storage/migrations.js.map +1 -1
  200. package/dist/core/storage/node-sqlite-file-gate.js +0 -15
  201. package/dist/core/storage/node-sqlite-file-gate.js.map +1 -1
  202. package/dist/core/storage/node-sqlite-thread.js +36 -12
  203. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  204. package/dist/core/storage/node-sqlite.js +135 -3
  205. package/dist/core/storage/node-sqlite.js.map +1 -1
  206. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  207. package/dist/core/storage/offline-snapshot-file.js +3 -3
  208. package/dist/core/storage/prefix.d.ts +1 -1
  209. package/dist/core/storage/prefix.js +14 -2
  210. package/dist/core/storage/prefix.js.map +1 -1
  211. package/dist/core/storage/process-selection.d.ts +5 -5
  212. package/dist/core/storage/provider.js +2 -2
  213. package/dist/core/storage/schema-catalog.d.ts +82 -5
  214. package/dist/core/storage/schema-catalog.js +244 -34
  215. package/dist/core/storage/schema-catalog.js.map +1 -1
  216. package/dist/core/storage/selection.d.ts +7 -82
  217. package/dist/core/storage/selection.js +20 -235
  218. package/dist/core/storage/selection.js.map +1 -1
  219. package/dist/core/storage/session/branch-fork-source.code.js +9 -8
  220. package/dist/core/storage/session/branch-fork-source.code.js.map +1 -1
  221. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  222. package/dist/core/storage/session/branch-fork-source.js +3 -3
  223. package/dist/core/storage/session/card-view.impl.js +3 -3
  224. package/dist/core/storage/session/card-view.js +3 -3
  225. package/dist/core/storage/session/child-reader.code.js +4 -4
  226. package/dist/core/storage/session/child-reader.impl.js +3 -3
  227. package/dist/core/storage/session/child-reader.js +3 -3
  228. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  229. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  230. package/dist/core/storage/session/errors.js +1 -1
  231. package/dist/core/storage/session/expanded-child-details.code.js +3 -3
  232. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  233. package/dist/core/storage/session/expanded-child-details.js +3 -3
  234. package/dist/core/storage/session/fork-detach.d.ts +118 -0
  235. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  236. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  237. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  238. package/dist/core/storage/session/fork-row-index.js +3 -3
  239. package/dist/core/storage/session/fork-schema.js +53 -0
  240. package/dist/core/storage/session/fork-schema.js.map +1 -0
  241. package/dist/core/storage/session/fork-segments.d.ts +58 -0
  242. package/dist/core/storage/session/fork-staging.code.js +5 -8
  243. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  244. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  245. package/dist/core/storage/session/fork-staging.js +3 -3
  246. package/dist/core/storage/session/fork-sweep.js +61 -0
  247. package/dist/core/storage/session/fork-sweep.js.map +1 -0
  248. package/dist/core/storage/session/fork-window.code.js +4 -4
  249. package/dist/core/storage/session/fork-window.impl.js +3 -3
  250. package/dist/core/storage/session/fork-window.js +3 -3
  251. package/dist/core/storage/session/history-pages.impl.js +3 -3
  252. package/dist/core/storage/session/history-pages.js +3 -3
  253. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  254. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  255. package/dist/core/storage/session/jsonl-session-store.d.ts +42 -2
  256. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  257. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  258. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  259. package/dist/core/storage/session/memory-session-store.js +3 -3
  260. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  261. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  262. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  263. package/dist/core/storage/session/released-history-files.code.js +4 -4
  264. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  265. package/dist/core/storage/session/released-history-files.js +3 -3
  266. package/dist/core/storage/session/resident-fork-rows.code.js +1 -1
  267. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  268. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  269. package/dist/core/storage/session/session-resume.impl.js +3 -3
  270. package/dist/core/storage/session/session-resume.js +3 -3
  271. package/dist/core/storage/session/session-search-index.d.ts +43 -4
  272. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  273. package/dist/core/storage/session/snapshot-cut.js +3 -3
  274. package/dist/core/storage/session/snapshot-history.code.js +4 -4
  275. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  276. package/dist/core/storage/session/snapshot-history.js +3 -3
  277. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  278. package/dist/core/storage/session/sql-session-store.d.ts +394 -20
  279. package/dist/core/storage/session/sql-session-store.impl.js +4 -4
  280. package/dist/core/storage/session/sql-session-store.js +4 -4
  281. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  282. package/dist/core/storage/session/tree-outline.js +3 -3
  283. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  284. package/dist/core/storage/session/tree-presentation.js +3 -3
  285. package/dist/core/storage/session/types.d.ts +22 -0
  286. package/dist/core/storage/sqlite-facade.d.ts +23 -2
  287. package/dist/core/storage/sqlite-facade.js +34 -0
  288. package/dist/core/storage/sqlite-facade.js.map +1 -1
  289. package/dist/core/storage/storage-status.code.js +1 -1
  290. package/dist/core/storage/storage-status.impl.js +3 -3
  291. package/dist/core/storage/storage-status.js +3 -3
  292. package/dist/core/storage/team.code.js +1 -1
  293. package/dist/core/storage/team.d.ts +26 -115
  294. package/dist/core/storage/team.impl.js +3 -3
  295. package/dist/core/storage/team.js +3 -3
  296. package/dist/core/structured-output/index.code.js +1 -1
  297. package/dist/core/structured-output/index.impl.js +3 -3
  298. package/dist/core/structured-output/index.js +3 -3
  299. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  300. package/dist/core/tasks/task-completion-entry.js +3 -3
  301. package/dist/core/tasks/task-file-history.code.js +4 -4
  302. package/dist/core/tasks/task-file-history.impl.js +3 -3
  303. package/dist/core/tasks/task-file-history.js +3 -3
  304. package/dist/core/tasks/task-reference-archive.code.js +5 -5
  305. package/dist/core/tasks/task-reference-archive.js +3 -3
  306. package/dist/core/tasks/task-reference-identity.js +3 -3
  307. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  308. package/dist/core/tasks/task-reference-stream.js +3 -3
  309. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  310. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  311. package/dist/core/tasks/task-view-source.code.js +1 -1
  312. package/dist/core/tasks/task-view-source.impl.js +3 -3
  313. package/dist/core/tasks/task-view-source.js +3 -3
  314. package/dist/core/tools/history-session.d.ts +2 -0
  315. package/dist/core/tools/history-tasks.d.ts +3 -2
  316. package/dist/core/tools/read-url.code.js +4 -4
  317. package/dist/core/tools/read-url.impl.js +3 -3
  318. package/dist/core/tools/read-url.js +3 -3
  319. package/dist/core/worktree-snapshot/blob-store.d.ts +71 -3
  320. package/dist/core/worktree-snapshot/blob-store.js +575 -67
  321. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  322. package/dist/core/worktree-snapshot/errors.code.js +3 -3
  323. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  324. package/dist/core/worktree-snapshot/errors.js +3 -3
  325. package/dist/core/worktree-snapshot/fork-blob-guard.js +81 -0
  326. package/dist/core/worktree-snapshot/fork-blob-guard.js.map +1 -0
  327. package/dist/core/worktree-snapshot/fork-snapshot-index.js +162 -0
  328. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -0
  329. package/dist/core/worktree-snapshot/session-index-reset.code.js +4 -0
  330. package/dist/core/worktree-snapshot/session-index-reset.code.js.map +1 -1
  331. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  332. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  333. package/dist/extensions/codemode/execute.code.js +2 -2
  334. package/dist/extensions/codemode/execute.impl.js +3 -3
  335. package/dist/extensions/codemode/execute.js +3 -3
  336. package/dist/extensions/codemode/renderer.code.js +2 -2
  337. package/dist/extensions/codemode/renderer.impl.js +3 -3
  338. package/dist/extensions/codemode/renderer.js +3 -3
  339. package/dist/extensions/mcp/cli.code.js +3 -3
  340. package/dist/extensions/mcp/cli.impl.js +3 -3
  341. package/dist/extensions/mcp/cli.js +3 -3
  342. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  343. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  344. package/dist/extensions/mcp/cli.lazy.js +3 -3
  345. package/dist/extensions/mcp/runtime.code.js +1 -1
  346. package/dist/extensions/mcp/runtime.impl.js +3 -3
  347. package/dist/extensions/mcp/runtime.js +3 -3
  348. package/dist/index.d.ts +3 -1
  349. package/dist/index.js +8 -8
  350. package/dist/main-first-time-setup.code.js +2 -2
  351. package/dist/main-first-time-setup.impl.js +3 -3
  352. package/dist/main-first-time-setup.js +3 -3
  353. package/dist/main.js +1 -1
  354. package/dist/modes/interactive/components/stored-tree-view.code.js +3 -3
  355. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  356. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  357. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  358. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  359. package/dist/modes/interactive/startup-shell-eligibility.js +1 -1
  360. package/dist/modes/interactive-engine/engine-prewarm.d.ts +1 -1
  361. package/dist/modes/print-mode.js +1 -1
  362. package/dist/package-manager-cli.code.js +7 -7
  363. package/dist/package-manager-cli.impl.js +3 -3
  364. package/dist/package-manager-cli.js +3 -3
  365. package/dist/rpc-entry.js +1 -1
  366. package/dist/startup-files.json +1 -1
  367. package/dist/startup-stages/10.js +1 -1
  368. package/dist/startup-stages/11.js +1 -1
  369. package/dist/startup-stages/12.js +1 -1
  370. package/dist/startup-stages/2.js +2 -3
  371. package/dist/startup-stages/3.js +1 -3
  372. package/dist/startup-stages/4.js +1 -2
  373. package/dist/startup-stages/5.js +1 -1
  374. package/dist/startup-stages/6.js +5 -7
  375. package/dist/startup-stages/7.js +3 -6
  376. package/dist/startup-stages/8.js +7 -2
  377. package/dist/startup-stages/9.js +1 -7
  378. package/dist/startup-stages/stages.json +1 -1
  379. package/dist/utils/compile-cache-deferral.js +8 -13
  380. package/dist/utils/compile-cache-deferral.js.map +1 -1
  381. package/dist/utils/compile-cache-warmup-host.js +3 -4
  382. package/dist/utils/compile-cache-warmup-host.js.map +1 -1
  383. package/dist/utils/compile-cache.js +12 -100
  384. package/dist/utils/compile-cache.js.map +1 -1
  385. package/dist/utils/startup-database-spare.code.js +3 -3
  386. package/dist/utils/startup-database-spare.impl.js +3 -3
  387. package/dist/utils/startup-database-spare.js +3 -3
  388. package/dist/utils/tools-manager.code.js +1 -1
  389. package/dist/utils/tools-manager.impl.js +3 -3
  390. package/dist/utils/tools-manager.js +3 -3
  391. package/dist/utils/worker-threads.js +2 -15
  392. package/dist/utils/worker-threads.js.map +1 -1
  393. package/docs/build.md +3 -3
  394. package/docs/changelog.mdx +1421 -69
  395. package/docs/compaction/reference.md +5 -5
  396. package/docs/compaction.md +7 -9
  397. package/docs/containerization.md +2 -2
  398. package/docs/custom-provider/api-reference.md +1 -1
  399. package/docs/docs.json +37 -10
  400. package/docs/environment-variables.md +0 -2
  401. package/docs/extensions/api-reference.md +4 -4
  402. package/docs/getting-started/installation.md +3 -0
  403. package/docs/guides/configuration.md +1 -1
  404. package/docs/guides/non-interactive.md +1 -1
  405. package/docs/guides/resume-on-any-machine.md +14 -22
  406. package/docs/guides/team-setup.md +56 -83
  407. package/docs/guides.md +2 -4
  408. package/docs/herdr.md +1 -1
  409. package/docs/index.md +1 -1
  410. package/docs/intercom/operations.md +26 -21
  411. package/docs/intercom/reference.md +2 -2
  412. package/docs/intercom.md +1 -1
  413. package/docs/libraries/storage-postgres.md +9 -9
  414. package/docs/libraries.md +2 -3
  415. package/docs/models-configuration.md +2 -2
  416. package/docs/models.md +2 -3
  417. package/docs/packages/authoring.md +7 -7
  418. package/docs/packages.md +1 -1
  419. package/docs/programmatic.md +2 -2
  420. package/docs/quickstart.md +1 -1
  421. package/docs/reference/cli.md +6 -11
  422. package/docs/reference.md +2 -2
  423. package/docs/rpc/extension-ui.md +2 -2
  424. package/docs/sdk/reference.md +5 -4
  425. package/docs/sdk/storage.md +8 -92
  426. package/docs/sdk/structured-decisions.md +1 -1
  427. package/docs/sdk/web-server.md +3 -3
  428. package/docs/sdk.md +14 -4
  429. package/docs/security.md +1 -1
  430. package/docs/session-format.md +5 -5
  431. package/docs/sessions.md +31 -42
  432. package/docs/settings.md +7 -8
  433. package/docs/storage/custom-adapters.md +255 -0
  434. package/docs/storage/jsonl.md +117 -0
  435. package/docs/{guides/postgres-pgbouncer.md → storage/postgres/pgbouncer.md} +73 -68
  436. package/docs/storage/postgres/tuning.md +337 -0
  437. package/docs/storage/postgres.md +556 -0
  438. package/docs/storage/sqlite.md +99 -0
  439. package/docs/storage.md +333 -956
  440. package/docs/subagents/authoring.md +1 -1
  441. package/docs/subagents.md +2 -2
  442. package/docs/tools.md +1 -1
  443. package/docs/worktree-snapshots.md +2 -2
  444. package/package.json +9 -9
  445. package/schemas/models.schema.json +2 -2
  446. package/schemas/settings.schema.json +0 -14
  447. package/dist/_shared/sdk-AVFII7NK.js.map +0 -1
  448. package/dist/_shared/settings-startup-4QCVCI53.js.map +0 -1
  449. package/dist/_shared/startup-0-0-57KF6LZH.js.map +0 -1
  450. package/dist/_shared/startup-0-1-GIY75K46.js.map +0 -1
  451. package/dist/_shared/startup-0-2-27OWFHV6.js.map +0 -1
  452. package/dist/_shared/startup-0-3-T4DVFYWX.js.map +0 -1
  453. package/dist/_shared/startup-8-1-X32CYSXB.js.map +0 -1
  454. package/dist/core/intercom-broker-control.d.ts +0 -129
  455. package/dist/startup-stages/13.js +0 -1
  456. package/docs/guides/postgres-tuning.md +0 -311
  457. package/docs/libraries/storage-libsql.md +0 -97
@@ -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
 
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  dialectOf,
3
3
  type StorageDialect,
4
+ type StorageSchemaCatalog,
4
5
  type SqliteExecutor,
5
6
  type SqliteRow,
6
7
  validateStoragePrefix,
@@ -27,7 +28,14 @@ import type {
27
28
  import { reservationAdmitsSender } from "./group-membership.js";
28
29
  import { isReleasedReservationKey } from "./released-children.js";
29
30
  import { addMissingColumns } from "./sql-add-column.js";
30
- import { ensureBrokerSchema, openCatalogOf, withBrokerSchemaCatalog } from "./sql-schema.js";
31
+ import {
32
+ ensureBrokerSchema,
33
+ foundInCatalogAgain,
34
+ openCatalogOf,
35
+ RETRY_UNAPPLIED,
36
+ setUpBrokerSchemaOnce,
37
+ withBrokerSchemaCatalog,
38
+ } from "./sql-schema.js";
31
39
 
32
40
  type ReservationRow = SqliteRow & {
33
41
  reservation_key: string;
@@ -142,7 +150,7 @@ async function openRestoringReservationStoreInCatalog({
142
150
  * Its transactions read and write this table, its counters and its wake claims alone, which no other store
143
151
  * touches, so they exclude one another, not every writer of the database (#6560).
144
152
  */
145
- const serial = { concurrency: { kind: "serial", domain: table } } as const;
153
+ const serial = { ...RETRY_UNAPPLIED, concurrency: { kind: "serial", domain: table } } as const;
146
154
  await ensureBrokerSchema(database, prefix, "restoring-reservations", (tx) =>
147
155
  tx.exec(`
148
156
  CREATE TABLE IF NOT EXISTS ${table}(
@@ -185,11 +193,18 @@ async function openRestoringReservationStoreInCatalog({
185
193
  );
186
194
  // Probed every time, as an earlier broker may recreate its index meanwhile; a current one runs no DDL (#5218). The
187
195
  // catalog an open read answers that probe, so a current index costs no transaction (#6560).
188
- const catalog = await openCatalogOf(database);
189
- const wakeIndexCurrent =
190
- catalog?.hasObject(`${table}_wake`) === true &&
196
+ const wakeIndexCurrent = (catalog: StorageSchemaCatalog) =>
197
+ catalog.hasObject(`${table}_wake`) &&
191
198
  !catalog.hasObject(`${table}_wake_requested`.slice(0, dialectOf(database).name === "postgres" ? 63 : undefined));
192
- if (!wakeIndexCurrent) await database.transaction((tx) => renameWakeIndex(tx, dialectOf(database), table));
199
+ const catalog = await openCatalogOf(database);
200
+ // Brokers that open a new database at once create it once; the others wait for it without its lock (#6560).
201
+ if (catalog === undefined || !wakeIndexCurrent(catalog))
202
+ await setUpBrokerSchemaOnce(
203
+ database,
204
+ `${table}:wake-index`,
205
+ () => foundInCatalogAgain(database, wakeIndexCurrent),
206
+ (tx) => renameWakeIndex(tx, dialectOf(database), table),
207
+ );
193
208
  const columns = `reservation_key, owner_session_id, owner_broker_id, child_name AS child_name_json, child_target,
194
209
  targets_json, "group" AS reservation_group, dormant, wake, wake_generation, fencing_token, "order" AS reservation_order,
195
210
  gone AS gone_json, end_json,
@@ -395,6 +410,8 @@ async function openRestoringReservationStoreInCatalog({
395
410
  async renew(lease): Promise<RestoringReservationRenewResult> {
396
411
  const bad = invalidLease(lease);
397
412
  if (bad !== undefined) return bad;
413
+ // Renewed again within the renewal interval, far inside the staleness limit: a renewal lost in a crash of the
414
+ // database server leaves the reservation a renewal older and still held, so its commit does not wait for the disk.
398
415
  return database.transaction(async (tx) => {
399
416
  const stale = await owned(tx, lease);
400
417
  if (stale !== undefined) return stale;
@@ -403,7 +420,7 @@ async function openRestoringReservationStoreInCatalog({
403
420
  lease.reservationKey,
404
421
  );
405
422
  return { status: "renewed" };
406
- }, serial);
423
+ }, { ...serial, relaxedDurability: true });
407
424
  },
408
425
  async release(lease, outcome): Promise<RestoringReservationReleaseResult> {
409
426
  const bad = invalidLease(lease);
@@ -0,0 +1,141 @@
1
+ import {
2
+ dialectOf,
3
+ type SqliteDatabase,
4
+ type SqliteRow,
5
+ type SqliteValue,
6
+ type StorageDialect,
7
+ validateStoragePrefix,
8
+ } from "@bastani/atomic/storage";
9
+ import { isMissingPrivilege } from "./sql-add-column.js";
10
+ import { brokerSchemaCurrent, ensureBrokerSchema, openCatalogOf } from "./sql-schema.js";
11
+
12
+ /** The most rows one retention statement deletes, as River's job cleaner and Oban's pruner bound theirs. */
13
+ export const RETENTION_DELETE_BATCH = 1_000;
14
+ /** The most batches one prune of a table deletes; older rows left over wait for the next maintenance. */
15
+ const RETENTION_DELETE_BATCHES = 100;
16
+
17
+ /**
18
+ * The database clock in milliseconds, read once for the whole statement. A retention filter compares a column to it,
19
+ * `column < ${storeNow} - ?`, so the column's index answers the filter: PostgreSQL's clock (`clock_timestamp()`) is
20
+ * volatile, and a comparison with a volatile expression is never an index condition, while a subquery's value is.
21
+ */
22
+ export function storeNow(database: SqliteDatabase): string {
23
+ return `(SELECT ${dialectOf(database).nowMs})`;
24
+ }
25
+
26
+ /** The rows of `table` that one retention prune deletes. */
27
+ export interface RetentionDelete {
28
+ readonly table: string;
29
+ /** A column that names each row on its own, such as the primary key. */
30
+ readonly key: string;
31
+ /** The rows to delete: `where`, with `params`, in which `orderBy` is the column an index orders them by. */
32
+ readonly where: string;
33
+ readonly params: readonly SqliteValue[];
34
+ readonly orderBy: string;
35
+ }
36
+
37
+ /**
38
+ * Deletes the rows `request` names, at most `RETENTION_DELETE_BATCH` per statement, until a batch finds fewer, as River's
39
+ * `JobDeleteBefore` and Oban's `prune_jobs` do: each statement reads its rows from the index `orderBy` is the column of
40
+ * and holds their locks only while it runs, so a large backlog never becomes one long statement. Resolves to the number
41
+ * of rows deleted.
42
+ */
43
+ export async function deleteInBatches(database: SqliteDatabase, request: RetentionDelete): Promise<number> {
44
+ const { table, key, where, params, orderBy } = request;
45
+ const batch = `SELECT ${key} FROM ${table} WHERE ${where} ORDER BY ${orderBy} LIMIT ?`;
46
+ // PostgreSQL: the keys as one array, so the delete finds each row by its key's index; `IN (SELECT …)` can join the
47
+ // whole table instead.
48
+ const sql =
49
+ dialectOf(database).name === "postgres"
50
+ ? `DELETE FROM ${table} WHERE ${key} = ANY(ARRAY(${batch}))`
51
+ : `DELETE FROM ${table} WHERE ${key} IN (${batch})`;
52
+ let deleted = 0;
53
+ for (let round = 0; round < RETENTION_DELETE_BATCHES; round++) {
54
+ const { changes } = await database.run(sql, ...params, RETENTION_DELETE_BATCH);
55
+ deleted += changes;
56
+ if (changes < RETENTION_DELETE_BATCH) break;
57
+ }
58
+ return deleted;
59
+ }
60
+
61
+ /** The rows still to deliver: every query of a recipient's undelivered rows names them with this text exactly. */
62
+ export const UNDELIVERED = "state IN ('queued', 'claimed')";
63
+ /** The settled outbox rows, which retention deletes. */
64
+ export const SETTLED = "state IN ('delivered', 'failed')";
65
+ /**
66
+ * The outbox's fillfactor on PostgreSQL: each page keeps room for new versions of its rows, so a claim's renewal or a
67
+ * save report, which changes no indexed column, stays on its page as a HOT update.
68
+ */
69
+ const OUTBOX_FILLFACTOR = 85;
70
+
71
+ /**
72
+ * The indexes that keep the broker state's maintenance and sweeps off full scans, created once per database at the end
73
+ * of a broker's open, when every table and column they need is there, as one schema step: `intercom-outbox-indexes`,
74
+ * revision 2, so an older broker, which recorded revision 1 of it, creates nothing of its own again. On a new database
75
+ * it is the one schema transaction the outbox's indexes always took.
76
+ * - `<outbox>_undelivered`, `(target_identity, sequence)` over the undelivered rows only, with `frame_bytes` alongside:
77
+ * every claim, scan and send reads a recipient's undelivered rows in sequence order and sums their sizes from it. It
78
+ * holds no settled row, so it stays the size of what is still to deliver. SQLite has no `INCLUDE`: there `frame_bytes`
79
+ * is its last column.
80
+ * - `<outbox>_settled`, `settled_at` over the settled rows, which retention deletes oldest first.
81
+ * - `<released asks>_expires`, by which retention finds the expired released asks.
82
+ * - `<known sessions>_lost` and `<pending asks>_ended`, partial: every broker's backup poll sweeps for the recipients
83
+ * and asks a stopped broker left, and reads only those, rather than every known session and pending ask.
84
+ * The outbox's earlier indexes, `<outbox>_target` and `<outbox>_target_bytes`, keyed by `(target_identity, state, …)`,
85
+ * are dropped: every claim and settlement changed a key of both. On PostgreSQL the outbox's fillfactor is set too.
86
+ * A role that does not own the tables (a runtime role with only DML privileges) leaves all of it to `atomic storage
87
+ * migrate`, run as the owner role, without trying; every query works without them.
88
+ */
89
+ export async function ensureRetentionIndexes(database: SqliteDatabase, prefix: string | undefined): Promise<void> {
90
+ const dialect = dialectOf(database);
91
+ const named = validateStoragePrefix(prefix, dialect.name);
92
+ const outbox = `${named}intercom_outbox`;
93
+ const released = `${named}intercom_released_asks`;
94
+ const known = `${named}intercom_known_sessions`;
95
+ const pending = `${named}intercom_pending_asks`;
96
+ const postgres = dialect.name === "postgres";
97
+ if (await brokerSchemaCurrent(database, prefix, "outbox-indexes", 2)) return;
98
+ const catalog = await openCatalogOf(database);
99
+ // PostgreSQL: a table this open created is this role's; otherwise the role must own the outbox to change it.
100
+ if (postgres && (catalog === undefined || catalog.hasTable(outbox))) {
101
+ // A host whose storage API predates identifier hashing names every table as given.
102
+ const name = (dialect as Partial<StorageDialect>).identifier?.(outbox) ?? outbox;
103
+ const found = await database.get<SqliteRow & { owned: boolean | number }>(
104
+ `SELECT pg_catalog.pg_has_role(current_user, c.relowner, 'USAGE') AS owned FROM pg_catalog.pg_class c
105
+ WHERE c.relnamespace = current_schema()::regnamespace AND c.relname = ?`,
106
+ name,
107
+ );
108
+ if (found === undefined || !(found.owned === true || Number(found.owned) === 1)) return;
109
+ }
110
+ const retired = [`${outbox}_target`, `${outbox}_target_bytes`];
111
+ const undelivered = postgres
112
+ ? "(target_identity, sequence) INCLUDE (frame_bytes)"
113
+ : "(target_identity, sequence, frame_bytes)";
114
+ const created = [
115
+ `CREATE INDEX IF NOT EXISTS ${outbox}_undelivered ON ${outbox}${undelivered} WHERE ${UNDELIVERED}`,
116
+ `CREATE INDEX IF NOT EXISTS ${outbox}_settled ON ${outbox}(settled_at) WHERE ${SETTLED}`,
117
+ `CREATE INDEX IF NOT EXISTS ${released}_expires ON ${released}(expires_at)`,
118
+ `CREATE INDEX IF NOT EXISTS ${known}_lost ON ${known}(lost_at) WHERE lost_at IS NOT NULL`,
119
+ `CREATE INDEX IF NOT EXISTS ${pending}_ended ON ${pending}(ended_at) WHERE ended_at IS NOT NULL AND replied IS NULL`,
120
+ ];
121
+ const drops = retired.map((index) => `DROP INDEX IF EXISTS ${index}`);
122
+ // SQLite, which records no step, runs only the creations in it, so an open whose catalog finds every index takes no
123
+ // write transaction; the retired indexes are dropped apart.
124
+ const script = postgres
125
+ ? [...created, ...drops, `ALTER TABLE ${outbox} SET (fillfactor = ${OUTBOX_FILLFACTOR})`]
126
+ : created;
127
+ try {
128
+ await ensureBrokerSchema(database, prefix, "outbox-indexes", (tx) => tx.exec(script.join(";\n")), 2);
129
+ } catch (error) {
130
+ if (isMissingPrivilege(error)) return;
131
+ throw error;
132
+ }
133
+ if (postgres) return;
134
+ // An older broker's open recreates them where it records no step.
135
+ const present =
136
+ catalog?.sqliteObjectType === undefined
137
+ ? (await database.all("SELECT name FROM sqlite_master WHERE type = 'index' AND name IN (?, ?)", ...retired))
138
+ .length > 0
139
+ : retired.some((index) => catalog.sqliteObjectType?.(index) === "index");
140
+ if (present) await database.transaction((tx) => tx.exec(drops.join(";\n")));
141
+ }
@@ -1,5 +1,12 @@
1
1
  import * as storage from "@bastani/atomic/storage";
2
- import { dialectOf, ensureStorageSchema, type SqliteDatabase, type SqliteExecutor, storageMigrationTable } from "@bastani/atomic/storage";
2
+ import {
3
+ dialectOf,
4
+ ensureStorageSchema,
5
+ type SqliteDatabase,
6
+ type SqliteExecutor,
7
+ type SqliteStatement,
8
+ storageMigrationTable,
9
+ } from "@bastani/atomic/storage";
3
10
 
4
11
  /**
5
12
  * `storageSchemaCurrent`, `schemaCatalogOf` and `withStorageSchemaCatalog` of the storage API, which an Atomic
@@ -7,9 +14,27 @@ import { dialectOf, ensureStorageSchema, type SqliteDatabase, type SqliteExecuto
7
14
  * namespace, and without them every open checks its schema in a transaction, as before.
8
15
  */
9
16
  const catalogApi: Partial<
10
- Pick<typeof storage, "storageSchemaCurrent" | "schemaCatalogOf" | "withStorageSchemaCatalog">
17
+ Pick<
18
+ typeof storage,
19
+ | "storageSchemaCurrent"
20
+ | "schemaCatalogOf"
21
+ | "withStorageSchemaCatalog"
22
+ | "restampStorageSchemaAtOpenEnd"
23
+ | "refreshStorageSchemaCatalog"
24
+ | "setUpStorageOnce"
25
+ | "ensureStorageSchemaOnce"
26
+ >
11
27
  > = storage;
12
28
 
29
+ /**
30
+ * What every transaction of the broker's state asks of the database besides its locks: run again, after a short
31
+ * randomized wait, when a lock wait that outlasted the database's lock timeout, a deadlock or a serialization failure
32
+ * ended it before it wrote anything, rather than failing the send, renewal, claim or delivery it makes. A busy shared
33
+ * database ends one now and then even when nothing is wrong. Each callback only uses its transaction handle, so running
34
+ * it again repeats nothing else; a database that cannot tell what a failure applied ignores it.
35
+ */
36
+ export const RETRY_UNAPPLIED = { retryTransientFailures: true } as const;
37
+
13
38
  /**
14
39
  * Runs `open`, a broker store's open on `database`, with one read of the prefix's schema catalog, which its schema
15
40
  * checks answer from: a store whose schema is current opens with no schema transaction and no lock, whether the broker
@@ -30,7 +55,12 @@ export async function withBrokerSchemaCatalog<T>(
30
55
  * Runs `setup`, a broker store's idempotent schema statements, in a transaction of its own, unless the prefix's ledger
31
56
  * records `revision` for `store` already (#5218): on PostgreSQL a current schema runs no DDL, so a role with only DML
32
57
  * privileges opens the store. Raise `revision` whenever `setup` creates or alters anything new. Inside an open that read
33
- * the catalog (`withStorageSchemaCatalog`), a revision it found recorded skips the transaction too (#6560).
58
+ * the catalog (`withStorageSchemaCatalog`), a revision it found recorded skips the transaction too (#6560). On SQLite the
59
+ * store's stamp records it. A setup that runs stamps nothing: later setups of the same open would leave its
60
+ * stamp behind, and stamping costs a new database's first open statements and a transaction. The next open finds the
61
+ * store in the catalog instead; there a setup whose objects the catalog holds is checked again, and a counter it seeds
62
+ * seeded, in the one transaction the open's end stamps every such store in, so later opens of a current schema take no
63
+ * write lock and answer every store from its stamp.
34
64
  */
35
65
  export async function ensureBrokerSchema(
36
66
  database: SqliteDatabase,
@@ -41,30 +71,165 @@ export async function ensureBrokerSchema(
41
71
  ): Promise<void> {
42
72
  const schema = { ledger: storageMigrationTable(prefix), domain: `intercom-${store}`, revision };
43
73
  if (await catalogApi.storageSchemaCurrent?.(database, schema)) return;
44
- if (await createsNothingNew(database, setup)) return;
45
- await database.transaction((tx) =>
46
- ensureStorageSchema(tx, dialectOf(database), schema, async () => {
74
+ const found = await foundInCatalog(database, setup);
75
+ if (foundSetUp(database, schema, setup, found)) return;
76
+ const dialect = dialectOf(database);
77
+ // Idempotent, and run again when a busy database ended it before it wrote anything. Brokers that open a new
78
+ // database at once set each store up once: the others wait for it without its lock, and find
79
+ // it set up in the catalog they read again (#6560).
80
+ const ensureOnce = catalogApi.ensureStorageSchemaOnce;
81
+ if (dialect.versionedMigrations && ensureOnce !== undefined) {
82
+ await ensureOnce(database, schema, async (tx) => {
47
83
  await setup(tx);
48
- }),
49
- );
84
+ });
85
+ return;
86
+ }
87
+ const once = catalogApi.setUpStorageOnce;
88
+ const refresh = catalogApi.refreshStorageSchemaCatalog;
89
+ const run = async (tx: SqliteExecutor) => {
90
+ if (!dialect.versionedMigrations) await setup(tx);
91
+ else
92
+ await ensureStorageSchema(tx, dialect, schema, async () => {
93
+ await setup(tx);
94
+ });
95
+ return "ran" as const;
96
+ };
97
+ const outcome =
98
+ dialect.versionedMigrations || once === undefined || refresh === undefined
99
+ ? await database.transaction(run, RETRY_UNAPPLIED)
100
+ : await once(database, {
101
+ locks: [],
102
+ done: async () => {
103
+ refresh(database);
104
+ if (await catalogApi.storageSchemaCurrent?.(database, schema)) return "found" as const;
105
+ return foundSetUp(database, schema, setup, await foundInCatalog(database, setup)) ? "found" : undefined;
106
+ },
107
+ setup: run,
108
+ concurrency: { kind: "serial" },
109
+ });
110
+ // Stamped where the end of the open takes a transaction for other stores anyway, as after a repair or an upgrade.
111
+ if (outcome === "ran" && !dialect.versionedMigrations)
112
+ catalogApi.restampStorageSchemaAtOpenEnd?.(database, schema, setup, { verify: found?.verify, alongside: true });
113
+ }
114
+
115
+ /**
116
+ * Whether the ledger, or the catalog an open in progress read, records `revision` of `store`'s setup, without a
117
+ * transaction; false where the storage API cannot tell.
118
+ */
119
+ export async function brokerSchemaCurrent(
120
+ database: SqliteDatabase,
121
+ prefix: string | undefined,
122
+ store: string,
123
+ revision = 1,
124
+ ): Promise<boolean> {
125
+ const schema = { ledger: storageMigrationTable(prefix), domain: `intercom-${store}`, revision };
126
+ return (await catalogApi.storageSchemaCurrent?.(database, schema)) === true;
50
127
  }
51
128
 
52
129
  /**
53
- * Whether `setup` would change nothing on a SQLite or libSQL database: where it only runs `CREATE TABLE` and
54
- * `CREATE INDEX` statements with `IF NOT EXISTS`, and the catalog an open in progress read found each object, as a
55
- * table or an index as the statement names it. SQLite records no versions, so such a setup ran at every open in a
56
- * write transaction of its own, which took the database's write lock and, on a server, three round trips (#6560).
57
- * Statements on an existing object of that kind do nothing, so skipping them is the same. The setup runs against a
58
- * handle that only collects the SQL it would run; any other call, or a statement of another form, and it runs as
59
- * before. False outside such an open, and on PostgreSQL, whose ledger decides.
130
+ * Whether `found`, what the open's catalog holds of a setup on SQLite ({@link foundInCatalog}), leaves the setup nothing
131
+ * to do now: every object it creates is there, and the open's end stamps it, or it seeds no rows. A setup that seeds
132
+ * rows, outside an open, still runs.
60
133
  */
61
- async function createsNothingNew(
134
+ function foundSetUp(
62
135
  database: SqliteDatabase,
136
+ schema: { readonly ledger: string; readonly domain: string; readonly revision: number },
63
137
  setup: (tx: SqliteExecutor) => Promise<unknown>,
138
+ found: Awaited<ReturnType<typeof foundInCatalog>>,
139
+ ): boolean {
140
+ if (found?.present !== true) return false;
141
+ const options = { verify: found.verify, deferred: found.seeds };
142
+ return catalogApi.restampStorageSchemaAtOpenEnd?.(database, schema, setup, options) === true || !found.seeds;
143
+ }
144
+
145
+ /**
146
+ * Runs `setup`, schema statements no ledger records, such as columns a store adds, once among the brokers that open a
147
+ * new database at once: the one that takes the lock `scope` names runs it, and the others wait without it until `done`,
148
+ * read again outside any transaction, finds it done (#6560). Without the storage API for it, an installation older than
149
+ * #6560, it runs in a serial transaction of the whole database, as before.
150
+ */
151
+ export async function setUpBrokerSchemaOnce(
152
+ database: SqliteDatabase,
153
+ scope: string,
154
+ done: () => Promise<boolean>,
155
+ setup: (tx: SqliteExecutor) => Promise<unknown>,
156
+ /** The reads `setup` makes first, in this order: on PostgreSQL they go out with the transaction's start. */
157
+ leading: readonly SqliteStatement[] = [],
158
+ ): Promise<void> {
159
+ const once = catalogApi.setUpStorageOnce;
160
+ if (once === undefined) {
161
+ await database.transaction(setup, RETRY_UNAPPLIED);
162
+ return;
163
+ }
164
+ await once(database, {
165
+ locks: [{ scope }],
166
+ leading,
167
+ done: async () => ((await done()) ? true : undefined),
168
+ setup: async (tx) => {
169
+ await setup(tx);
170
+ return true;
171
+ },
172
+ concurrency: { kind: "serial" },
173
+ });
174
+ }
175
+
176
+ /**
177
+ * Whether the schema, read again into the catalog of the open in progress, satisfies `check`: for a setup another broker
178
+ * may have run since the open read it. False outside an open, and without the storage API to read it again.
179
+ */
180
+ export async function foundInCatalogAgain(
181
+ database: SqliteDatabase,
182
+ check: (catalog: storage.StorageSchemaCatalog) => boolean,
64
183
  ): Promise<boolean> {
65
- if (dialectOf(database).versionedMigrations) return false;
66
- const typeOf = (await openCatalogOf(database))?.sqliteObjectType;
67
- if (typeOf === undefined) return false;
184
+ if (catalogApi.refreshStorageSchemaCatalog === undefined) return false;
185
+ catalogApi.refreshStorageSchemaCatalog(database);
186
+ const catalog = await openCatalogOf(database);
187
+ return catalog !== undefined && check(catalog);
188
+ }
189
+
190
+ /**
191
+ * Asks the open of `database` in progress to stamp `store`'s `setup` at its end, on SQLite, where the open
192
+ * found the store current in the catalog, `verify` says, rather than by its stamp, which a schema change since left
193
+ * behind: the next open then answers from the stamp (#6560). Does nothing where the stamp is current, elsewhere, and
194
+ * outside an open.
195
+ */
196
+ export async function stampBrokerSchemaAtOpenEnd(
197
+ database: SqliteDatabase,
198
+ prefix: string | undefined,
199
+ store: string,
200
+ setup: (tx: SqliteExecutor) => Promise<unknown>,
201
+ verify: (catalog: storage.StorageSchemaCatalog) => boolean,
202
+ revision = 1,
203
+ ): Promise<void> {
204
+ const schema = { ledger: storageMigrationTable(prefix), domain: `intercom-${store}`, revision };
205
+ if (await catalogApi.storageSchemaCurrent?.(database, schema)) return;
206
+ catalogApi.restampStorageSchemaAtOpenEnd?.(database, schema, setup, { verify });
207
+ }
208
+
209
+ /**
210
+ * What `setup` creates on a SQLite database, where it only runs `CREATE TABLE` and `CREATE INDEX` statements
211
+ * with `IF NOT EXISTS` and seeds rows with `INSERT … ON CONFLICT … DO NOTHING`: `present`, whether the catalog an open
212
+ * in progress read found each object, as a table or an index as the statement names it; `verify`, the same check
213
+ * against another catalog; and `seeds`, whether it seeds rows, which still have to be written. SQLite records no
214
+ * versions, so such a setup ran at every open in a write transaction of its own, which took the database's write lock
215
+ * and, on a server, three round trips (#6560); statements on an existing object of that kind do nothing. The setup runs
216
+ * against a handle that only collects the SQL it would run. Undefined for any other call or statement, outside such an
217
+ * open, and on PostgreSQL, whose ledger decides.
218
+ */
219
+ async function foundInCatalog(
220
+ database: SqliteDatabase,
221
+ setup: (tx: SqliteExecutor) => Promise<unknown>,
222
+ ): Promise<
223
+ | {
224
+ readonly verify: (catalog: storage.StorageSchemaCatalog) => boolean;
225
+ readonly seeds: boolean;
226
+ readonly present: boolean;
227
+ }
228
+ | undefined
229
+ > {
230
+ if (dialectOf(database).versionedMigrations) return undefined;
231
+ const catalog = await openCatalogOf(database);
232
+ if (catalog?.sqliteObjectType === undefined) return undefined;
68
233
  const scripts: string[] = [];
69
234
  let other = false;
70
235
  const refuse = () => {
@@ -83,22 +248,29 @@ async function createsNothingNew(
83
248
  try {
84
249
  await setup(collecting);
85
250
  } catch {
86
- return false;
251
+ return undefined;
87
252
  }
88
- if (other) return false;
253
+ if (other) return undefined;
254
+ const created: { readonly name: string; readonly type: string }[] = [];
255
+ let seeds = false;
89
256
  for (const script of scripts) {
90
257
  const statements = splitStatements(script);
91
- if (statements === undefined) return false;
258
+ if (statements === undefined) return undefined;
92
259
  for (const statement of statements) {
93
- const created = CREATE_IF_NOT_EXISTS.exec(statement);
94
- if (created === null) return false;
95
- const name = created[3] ?? created[4]!;
96
- if (typeOf(name) !== created[2]!.toLowerCase()) return false;
260
+ const create = CREATE_IF_NOT_EXISTS.exec(statement);
261
+ if (create !== null) created.push({ name: create[3] ?? create[4]!, type: create[2]!.toLowerCase() });
262
+ else if (SEED.test(statement)) seeds = true;
263
+ else return undefined;
97
264
  }
98
265
  }
99
- return true;
266
+ const verify = (found: storage.StorageSchemaCatalog) =>
267
+ created.every(({ name, type }) => found.sqliteObjectType?.(name) === type);
268
+ return { verify, seeds, present: verify(catalog) };
100
269
  }
101
270
 
271
+ /** `INSERT INTO … ON CONFLICT … DO NOTHING`: rows a setup seeds once, which writing again leaves as they are. */
272
+ const SEED = /^INSERT\s+INTO\s[\s\S]*\sON\s+CONFLICT\b[\s\S]*\sDO\s+NOTHING$/i;
273
+
102
274
  /** `CREATE [UNIQUE] TABLE|INDEX IF NOT EXISTS <name>`, the name plain or double-quoted and never schema-qualified. */
103
275
  const CREATE_IF_NOT_EXISTS =
104
276
  /^CREATE\s+(UNIQUE\s+)?(TABLE|INDEX)\s+IF\s+NOT\s+EXISTS\s+(?:"([^"]+)"|([A-Za-z_][A-Za-z0-9_]*))(?![A-Za-z0-9_$."])/i;