@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
@@ -13,7 +13,8 @@ import type {
13
13
  SessionIdReclaim,
14
14
  SessionIdReclaimResult,
15
15
  } from "./multinode-state-store.js";
16
- import { ensureBrokerSchema, withBrokerSchemaCatalog } from "./sql-schema.js";
16
+ import { deleteInBatches, storeNow } from "./sql-retention.js";
17
+ import { ensureBrokerSchema, RETRY_UNAPPLIED, withBrokerSchemaCatalog } from "./sql-schema.js";
17
18
 
18
19
  type BindingRow = SqliteRow & { return_address: string; owner_token?: string | null; owner_broker?: string | null };
19
20
 
@@ -83,6 +84,8 @@ async function openKnownSessionStoreInCatalog({
83
84
  const leases = `${validateStoragePrefix(prefix, dialectOf(database).name)}intercom_leases`;
84
85
  const { types, nowMs, greatest } = dialectOf(database);
85
86
  const age = greatest("0", `${nowMs} - recorded_at`);
87
+ /** The database clock, read once per statement: `recorded_at` compared with it is answered by its index. */
88
+ const now = storeNow(database);
86
89
  /** `age` at the statement's one reading of the clock, from `WITH clock`. */
87
90
  const clockAge = greatest("0", "(SELECT now FROM clock) - recorded_at");
88
91
  await ensureBrokerSchema(database, prefix, "known-sessions", (tx) =>
@@ -196,7 +199,7 @@ async function openKnownSessionStoreInCatalog({
196
199
  owner: KnownSessionOwner | undefined,
197
200
  ): Promise<KnownSessionBindResult> => {
198
201
  await tx.run(
199
- `DELETE FROM ${bindings} WHERE intercom_session_id = ? AND ${nowMs} - recorded_at > ?`,
202
+ `DELETE FROM ${bindings} WHERE intercom_session_id = ? AND recorded_at < ${now} - ?`,
200
203
  intercomSessionId,
201
204
  retentionMs,
202
205
  );
@@ -255,11 +258,27 @@ async function openKnownSessionStoreInCatalog({
255
258
  return { status: "bound" };
256
259
  };
257
260
 
261
+ /**
262
+ * The writes of this store that `lookup` and `binding` read, started and not finished. Those reads go through the
263
+ * reader, which no write of this store is queued on, so they first wait for these: a caller that starts a write and
264
+ * then reads, without awaiting the write, reads it. With none unfinished they wait for nothing.
265
+ */
266
+ const unfinished = new Set<Promise<void>>();
267
+ const writing = <T>(write: Promise<T>): Promise<T> => {
268
+ const settled = write.then(
269
+ () => {},
270
+ () => {},
271
+ );
272
+ unfinished.add(settled);
273
+ void settled.then(() => unfinished.delete(settled));
274
+ return write;
275
+ };
276
+
258
277
  const reclaim = async (request: SessionIdReclaim): Promise<SessionIdReclaimResult> => {
259
278
  if (request.intercomSessionId.length === 0 || request.freshId.length === 0)
260
279
  return { status: "invalid", reason: "empty-session-id" };
261
280
  const owning = owned ? request.owner : undefined;
262
- return database.transaction(
281
+ const reclaiming = database.transaction(
263
282
  async (tx) => {
264
283
  // A session of this return address that another broker presents, in any group, holds the id there.
265
284
  const identities = returnIdentityPrefix(request.returnAddress);
@@ -267,7 +286,7 @@ async function openKnownSessionStoreInCatalog({
267
286
  `UPDATE ${bindings} SET recorded_at = ${nowMs}${
268
287
  owning === undefined ? "" : `, owner_token = ?, owner_broker = ?, owner_renewed_at = ${nowMs}`
269
288
  }
270
- WHERE intercom_session_id = ? AND return_address = ? AND latest_claim = ? AND ${nowMs} - recorded_at <= ?
289
+ WHERE intercom_session_id = ? AND return_address = ? AND latest_claim = ? AND recorded_at >= ${now} - ?
271
290
  AND NOT EXISTS (
272
291
  SELECT 1 FROM ${leases} presence
273
292
  WHERE presence.kind = 'presence' AND substr(presence.key, 1, length(?)) = ? AND presence.holder_id IS NOT NULL
@@ -315,8 +334,9 @@ async function openKnownSessionStoreInCatalog({
315
334
  : await bindIn(tx, request.freshId, request.returnAddress, request.retentionMs, undefined, owning);
316
335
  return { status: "fresh", binding } as const;
317
336
  },
318
- { concurrency: { kind: "serial", domain: bindings } },
337
+ { ...RETRY_UNAPPLIED, concurrency: { kind: "serial", domain: bindings } },
319
338
  );
339
+ return writing(reclaiming);
320
340
  };
321
341
 
322
342
  return {
@@ -325,7 +345,7 @@ async function openKnownSessionStoreInCatalog({
325
345
  if (session.targetIdentity.length === 0) return { status: "invalid", reason: "empty-target-identity" };
326
346
  if (session.intercomSessionId.length === 0) return { status: "invalid", reason: "empty-session-id" };
327
347
  if (session.group.length === 0) return { status: "invalid", reason: "empty-group" };
328
- await database.run(
348
+ const recording = database.run(
329
349
  `INSERT INTO ${table}(target_identity, intercom_session_id, name_json, name_key, atomic_session_id,
330
350
  group_name, groups_json, recipient_purpose, reply_capability, recorded_at${aliasColumn})
331
351
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ${nowMs}${aliased ? ", ?" : ""})
@@ -352,11 +372,13 @@ async function openKnownSessionStoreInCatalog({
352
372
  // #5607: last, so every earlier value keeps its place.
353
373
  ...(aliased ? [session.aliasSessionId ?? null] : []),
354
374
  );
375
+ await writing(recording);
355
376
  return { status: "recorded" };
356
377
  },
357
378
  async lookup(target, retentionMs): Promise<KnownSessionLookupResult> {
358
379
  if (target.length === 0) return { status: "invalid", reason: "empty-target" };
359
- // Through the reader, which never waits behind this database's writes (#6560).
380
+ // Through the reader, which never waits behind this database's writes (#6560), only for this store's own.
381
+ if (unfinished.size > 0) await Promise.all(unfinished);
360
382
  const rows = await reader.all<KnownRow>(
361
383
  // One reading of the clock, so a session found within the retention reports an age within it too.
362
384
  `WITH clock AS (SELECT ${nowMs} AS now)
@@ -376,27 +398,29 @@ async function openKnownSessionStoreInCatalog({
376
398
  },
377
399
  async bind(intercomSessionId, returnAddress, retentionMs, claim, owner): Promise<KnownSessionBindResult> {
378
400
  if (intercomSessionId.length === 0) return { status: "invalid", reason: "empty-session-id" };
379
- return database.transaction((tx) => bindIn(tx, intercomSessionId, returnAddress, retentionMs, claim, owner), {
380
- concurrency: { kind: "serial", domain: bindings },
381
- });
401
+ return writing(
402
+ database.transaction((tx) => bindIn(tx, intercomSessionId, returnAddress, retentionMs, claim, owner), {
403
+ ...RETRY_UNAPPLIED,
404
+ concurrency: { kind: "serial", domain: bindings },
405
+ }),
406
+ );
382
407
  },
383
408
  ...(owned ? { owners } : {}),
384
409
  async binding(intercomSessionId, retentionMs): Promise<KnownSessionBindingResult> {
385
410
  if (intercomSessionId.length === 0) return { status: "invalid", reason: "empty-session-id" };
411
+ if (unfinished.size > 0) await Promise.all(unfinished);
386
412
  const bound = await reader.get<BindingRow>(
387
- `SELECT return_address FROM ${bindings} WHERE intercom_session_id = ? AND ${nowMs} - recorded_at <= ?`,
413
+ `SELECT return_address FROM ${bindings} WHERE intercom_session_id = ? AND recorded_at >= ${now} - ?`,
388
414
  intercomSessionId,
389
415
  retentionMs,
390
416
  );
391
417
  return bound === undefined ? { status: "unbound" } : { status: "bound", returnAddress: bound.return_address };
392
418
  },
393
419
  async prune(olderThanMs): Promise<number> {
394
- await database.run(`DELETE FROM ${bindings} WHERE ${nowMs} - recorded_at > ?`, olderThanMs);
395
- const { changes } = await database.run(
396
- `DELETE FROM ${table} WHERE ${nowMs} - recorded_at > ?`,
397
- olderThanMs,
398
- );
399
- return changes;
420
+ // Oldest first, from each table's `_recorded` index, in batches.
421
+ const older = { where: `recorded_at < ${now} - ?`, params: [olderThanMs], orderBy: "recorded_at" };
422
+ await deleteInBatches(database, { table: bindings, key: "intercom_session_id", ...older });
423
+ return deleteInBatches(database, { table, key: "record_order", ...older });
400
424
  },
401
425
  async markLost(targetIdentities): Promise<void> {
402
426
  if (targetIdentities.length === 0) return;
@@ -410,13 +434,13 @@ async function openKnownSessionStoreInCatalog({
410
434
  );
411
435
  }
412
436
  },
413
- { concurrency: { kind: "serial", domain: table } },
437
+ { ...RETRY_UNAPPLIED, concurrency: { kind: "serial", domain: table } },
414
438
  );
415
439
  },
416
440
  async listLost(olderThanMs): Promise<KnownSessionState[]> {
417
441
  const rows = await database.all<KnownRow>(
418
442
  `SELECT ${columns} FROM ${table}
419
- WHERE lost_at IS NOT NULL AND ${greatest("0", `${nowMs} - lost_at`)} >= ?
443
+ WHERE lost_at IS NOT NULL AND lost_at <= ${now} - ?
420
444
  ORDER BY record_order`,
421
445
  olderThanMs,
422
446
  );
@@ -6,6 +6,7 @@ import {
6
6
  type SqliteExecutor,
7
7
  type SqliteRow,
8
8
  type SqliteRunResult,
9
+ type SqliteStatement,
9
10
  type StorageDialect,
10
11
  storageMigrationTable,
11
12
  validateStoragePrefix,
@@ -24,7 +25,13 @@ import type {
24
25
  } from "./multinode-state-store.js";
25
26
  import { isMissingPrivilege } from "./sql-add-column.js";
26
27
  import { recipientTransaction } from "./sql-outbox-store.js";
27
- import { ensureBrokerSchema, openCatalogOf, withBrokerSchemaCatalog } from "./sql-schema.js";
28
+ import {
29
+ ensureBrokerSchema,
30
+ openCatalogOf,
31
+ RETRY_UNAPPLIED,
32
+ stampBrokerSchemaAtOpenEnd,
33
+ withBrokerSchemaCatalog,
34
+ } from "./sql-schema.js";
28
35
 
29
36
  /** Store-clock milliseconds since the lease was renewed, never negative. */
30
37
  const age = ({ greatest, nowMs }: StorageDialect) => greatest("0", `${nowMs} - renewed_at`);
@@ -41,6 +48,16 @@ const fillfactorApi: Partial<Pick<typeof storage, "ensureTableFillfactor">> = st
41
48
  */
42
49
  const LEASE_FILLFACTOR = 80;
43
50
 
51
+ /**
52
+ * How long a lease write waits for a row lock on PostgreSQL before it fails and runs again. Five runs that each wait
53
+ * this long, and the waits between them, about 4 s, take about 14 s: a renewal made 10 s after the last one still ends
54
+ * within the lease's 30 s stale bound (`BROKER_LEASE_STALE_AFTER_MS`).
55
+ */
56
+ const LEASE_LOCK_WAIT_MS = 2_000;
57
+
58
+ /** The statement of a presence acquisition's wait for the sends to its recipient under way: it only takes the lock. */
59
+ const SENDS_PASSED = { sql: "SELECT 1 AS passed", params: [] };
60
+
44
61
  /**
45
62
  * The kind of the row whose `last_token` counts acquisitions on PostgreSQL where the order sequence is missing: see
46
63
  * `nextOrder`.
@@ -50,29 +67,46 @@ const ACQUISITION_ORDER_KIND = "acquisition-order";
50
67
  /**
51
68
  * Creates the sequence first acquisitions take their order from on PostgreSQL, `<table>_order`, once per database
52
69
  * (recorded as the `intercom-lease-order` schema step), starting past every order taken so far, the counter row's
53
- * included. False where it is missing and this role may not create it: a runtime role on a database `atomic storage
54
- * migrate` has not upgraded yet keeps the counter row (#6560).
70
+ * included. Where the ledger records the step but the catalog the open read has no sequence, someone dropped it: it is
71
+ * created again, under the schema lock, if it is still missing. Where this role may not create it, as a runtime role
72
+ * before `atomic storage migrate`, acquisitions take their order from the counter row instead (#6560).
55
73
  */
56
- async function ensureOrderSequence(
57
- database: SqliteDatabase,
58
- prefix: string | undefined,
59
- table: string,
60
- ): Promise<boolean> {
74
+ async function ensureOrderSequence(database: SqliteDatabase, prefix: string | undefined, table: string): Promise<void> {
75
+ const sequence = `${table}_order`;
76
+ const create = async (tx: SqliteExecutor) => {
77
+ await tx.exec(`CREATE SEQUENCE IF NOT EXISTS ${sequence} AS BIGINT`);
78
+ await tx.get(
79
+ `SELECT setval('${sequence}', GREATEST(
80
+ (SELECT COALESCE(MAX(first_acquired_order), 0) FROM ${table}),
81
+ (SELECT COALESCE(MAX(last_token), 0) FROM ${table} WHERE kind = '${ACQUISITION_ORDER_KIND}'),
82
+ 1
83
+ ))`,
84
+ );
85
+ };
86
+ const catalog = await openCatalogOf(database);
87
+ const dropped =
88
+ catalog !== undefined &&
89
+ catalog.recordedVersion("schema:intercom-lease-order") >= 1 &&
90
+ !catalog.hasObject(sequence);
61
91
  try {
62
- await ensureBrokerSchema(database, prefix, "lease-order", async (tx) => {
63
- await tx.exec(`CREATE SEQUENCE IF NOT EXISTS ${table}_order AS BIGINT`);
92
+ if (!dropped) {
93
+ await ensureBrokerSchema(database, prefix, "lease-order", create);
94
+ return;
95
+ }
96
+ await database.transaction(async (tx) => {
97
+ // The lock `ensureStorageSchema` takes, so processes that find it dropped create it once.
64
98
  await tx.get(
65
- `SELECT setval('${table}_order', GREATEST(
66
- (SELECT COALESCE(MAX(first_acquired_order), 0) FROM ${table}),
67
- (SELECT COALESCE(MAX(last_token), 0) FROM ${table} WHERE kind = '${ACQUISITION_ORDER_KIND}'),
68
- 1
69
- ))`,
99
+ "SELECT pg_advisory_xact_lock(hashtextextended(?, 0)) AS locked",
100
+ `${storageMigrationTable(prefix)}:schema`,
101
+ );
102
+ const found = await tx.get<SqliteRow & { missing: boolean | number }>(
103
+ "SELECT to_regclass(?) IS NULL AS missing",
104
+ sequence,
70
105
  );
106
+ if (found?.missing === true || Number(found?.missing) === 1) await create(tx);
71
107
  });
72
- return true;
73
108
  } catch (error) {
74
- if (isMissingPrivilege(error)) return false;
75
- throw error;
109
+ if (!isMissingPrivilege(error)) throw error;
76
110
  }
77
111
  }
78
112
 
@@ -158,41 +192,47 @@ async function ensureAddressColumns(database: SqliteDatabase, prefix: string | u
158
192
  const indexes = ADDRESS_COLUMNS.map(
159
193
  (column) => `CREATE INDEX IF NOT EXISTS ${table}_${column} ON ${table}(${column})`,
160
194
  ).join(";\n");
195
+ const setup = async (tx: SqliteExecutor) => {
196
+ if (dialect.name === "postgres") {
197
+ // One statement, so the table is rewritten once.
198
+ await tx.exec(
199
+ `ALTER TABLE ${table} ${ADDRESS_COLUMNS.map(
200
+ (column) => `ADD COLUMN IF NOT EXISTS ${column} TEXT GENERATED ALWAYS AS (${expressions[column]}) STORED`,
201
+ ).join(", ")};\n${indexes}`,
202
+ );
203
+ return;
204
+ }
205
+ // SQLite runs this on every open: `pragma_table_xinfo` lists generated columns, which `pragma_table_info` hides.
206
+ const present = new Set(
207
+ (await tx.all<SqliteRow & { name: string }>("SELECT name FROM pragma_table_xinfo(?)", table)).map(
208
+ (row) => row.name,
209
+ ),
210
+ );
211
+ for (const column of ADDRESS_COLUMNS)
212
+ if (!present.has(column))
213
+ await tx.exec(
214
+ `ALTER TABLE ${table} ADD COLUMN ${column} TEXT GENERATED ALWAYS AS (${expressions[column]}) VIRTUAL`,
215
+ );
216
+ await tx.exec(indexes);
217
+ };
161
218
  // On SQLite, which records no step, the catalog an open read finds the columns and their indexes, so a current
162
- // table costs no write transaction (#6560).
219
+ // table costs no write transaction (#6560); the open's end stamps it, so the next open answers from the stamp.
163
220
  const catalog = dialect.versionedMigrations ? undefined : await openCatalogOf(database);
164
221
  if (
165
222
  catalog?.sqliteObjectType !== undefined &&
166
223
  ADDRESS_COLUMNS.every(
167
224
  (column) => catalog.hasColumn(table, column) && catalog.sqliteObjectType?.(`${table}_${column}`) === "index",
168
225
  )
169
- )
226
+ ) {
227
+ await stampBrokerSchemaAtOpenEnd(database, prefix, "lease-addresses", setup, (found) =>
228
+ ADDRESS_COLUMNS.every(
229
+ (column) => found.hasColumn(table, column) && found.sqliteObjectType?.(`${table}_${column}`) === "index",
230
+ ),
231
+ );
170
232
  return true;
233
+ }
171
234
  try {
172
- await ensureBrokerSchema(database, prefix, "lease-addresses", async (tx) => {
173
- if (dialect.name === "postgres") {
174
- // One statement, so the table is rewritten once.
175
- await tx.exec(
176
- `ALTER TABLE ${table} ${ADDRESS_COLUMNS.map(
177
- (column) =>
178
- `ADD COLUMN IF NOT EXISTS ${column} TEXT GENERATED ALWAYS AS (${expressions[column]}) STORED`,
179
- ).join(", ")};\n${indexes}`,
180
- );
181
- return;
182
- }
183
- // SQLite runs this on every open: `pragma_table_xinfo` lists generated columns, which `pragma_table_info` hides.
184
- const present = new Set(
185
- (
186
- await tx.all<SqliteRow & { name: string }>("SELECT name FROM pragma_table_xinfo(?)", table)
187
- ).map((row) => row.name),
188
- );
189
- for (const column of ADDRESS_COLUMNS)
190
- if (!present.has(column))
191
- await tx.exec(
192
- `ALTER TABLE ${table} ADD COLUMN ${column} TEXT GENERATED ALWAYS AS (${expressions[column]}) VIRTUAL`,
193
- );
194
- await tx.exec(indexes);
195
- });
235
+ await ensureBrokerSchema(database, prefix, "lease-addresses", setup);
196
236
  return true;
197
237
  } catch (error) {
198
238
  if (isMissingPrivilege(error)) return false;
@@ -243,22 +283,41 @@ const compare = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
243
283
  const invalid = (reason: StateStoreInvalidReason): InvalidStateInput => ({ status: "invalid", reason });
244
284
 
245
285
  function keyOf(subject: LeaseSubject): LeaseKey {
246
- return subject.kind === "broker"
247
- ? { kind: "broker", brokerId: subject.brokerId }
248
- : { kind: "presence", targetIdentity: subject.targetIdentity };
286
+ switch (subject.kind) {
287
+ case "broker":
288
+ return { kind: "broker", brokerId: subject.brokerId };
289
+ case "maintenance":
290
+ return { kind: "maintenance", task: subject.task };
291
+ default:
292
+ return { kind: "presence", targetIdentity: subject.targetIdentity };
293
+ }
249
294
  }
250
295
 
251
296
  function keyId(key: LeaseKey): string {
252
- return key.kind === "broker" ? key.brokerId : key.targetIdentity;
297
+ switch (key.kind) {
298
+ case "broker":
299
+ return key.brokerId;
300
+ case "maintenance":
301
+ return key.task;
302
+ default:
303
+ return key.targetIdentity;
304
+ }
253
305
  }
254
306
 
255
307
  function keyFor(kind: LeaseKind, id: string): LeaseKey {
256
- return kind === "broker" ? { kind, brokerId: id } : { kind, targetIdentity: id };
308
+ switch (kind) {
309
+ case "broker":
310
+ return { kind, brokerId: id };
311
+ case "maintenance":
312
+ return { kind, task: id };
313
+ default:
314
+ return { kind, targetIdentity: id };
315
+ }
257
316
  }
258
317
 
259
318
  function invalidKey(key: LeaseKey): InvalidStateInput | undefined {
260
319
  if (keyId(key).length > 0) return undefined;
261
- return invalid(key.kind === "broker" ? "empty-broker-id" : "empty-target-identity");
320
+ return invalid(key.kind === "broker" ? "empty-broker-id" : key.kind === "maintenance" ? "empty-task" : "empty-target-identity");
262
321
  }
263
322
 
264
323
  /**
@@ -279,7 +338,7 @@ function stateFromRow(row: StateRow): LeaseState {
279
338
  // A row an earlier broker wrote may hold half a surrogate pair: it reads as a stored one would.
280
339
  const subject: LeaseSubject = JSON.parse(row.subject_json, wellFormed);
281
340
  return {
282
- key: keyFor(row.kind === "broker" ? "broker" : "presence", row.key),
341
+ key: keyFor(row.kind === "broker" || row.kind === "maintenance" ? row.kind : "presence", row.key),
283
342
  holderId: row.holder_id,
284
343
  fencingToken: Number(row.fencing_token),
285
344
  subject,
@@ -329,8 +388,7 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
329
388
  )
330
389
  `;
331
390
  await ensureBrokerSchema(database, options.prefix, "leases", (tx) => tx.exec(schema));
332
- const orderSequence = `${table}_order`;
333
- const sequenced = dialect.name === "postgres" && (await ensureOrderSequence(database, options.prefix, table));
391
+ if (dialect.name === "postgres") await ensureOrderSequence(database, options.prefix, table);
334
392
  const addressed = await ensureAddressColumns(database, options.prefix, table);
335
393
  await fillfactorApi.ensureTableFillfactor?.(database, {
336
394
  ledger: storageMigrationTable(options.prefix),
@@ -340,12 +398,14 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
340
398
  fillfactor: LEASE_FILLFACTOR,
341
399
  });
342
400
 
343
- const holderOf = (executor: SqliteExecutor, key: LeaseKey) =>
344
- executor.get<HolderRow>(
345
- `SELECT holder_id, fencing_token, last_token, ${leaseAge} AS age_ms FROM ${table} WHERE kind = ? AND key = ?`,
346
- key.kind,
347
- keyId(key),
348
- );
401
+ const holderStatement = (key: LeaseKey): SqliteStatement => ({
402
+ sql: `SELECT holder_id, fencing_token, last_token, ${leaseAge} AS age_ms FROM ${table} WHERE kind = ? AND key = ?`,
403
+ params: [key.kind, keyId(key)],
404
+ });
405
+ const holderOf = (executor: SqliteExecutor, key: LeaseKey) => {
406
+ const { sql, params } = holderStatement(key);
407
+ return executor.get<HolderRow>(sql, ...params);
408
+ };
349
409
  const stale = (row: HolderRow | undefined) =>
350
410
  row?.holder_id === null || row?.holder_id === undefined
351
411
  ? ({ status: "stale" } as const)
@@ -360,32 +420,68 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
360
420
  const rowAge = dialect.greatest("0", `${nowMs} - ${table}.renewed_at`);
361
421
  /**
362
422
  * Every write decides on its own row in one guarded statement, so leases never wait for the database's serial lock,
363
- * which a broker's renewals must not wait behind (#6560): see `fencedPath("intercom-lease")`.
423
+ * which a broker's renewals must not wait behind (#6560): see `fencedPath("intercom-lease")`. On PostgreSQL a write
424
+ * waits for a row lock at most `LEASE_LOCK_WAIT_MS`, then runs again (`RETRY_UNAPPLIED`): a renewal stuck behind
425
+ * the database's lock timeout, as long as the lease's whole life, would let the lease go stale however it ended.
426
+ */
427
+ const fenced = {
428
+ ...RETRY_UNAPPLIED,
429
+ ...(dialect.name === "postgres" ? { lockWaitMs: LEASE_LOCK_WAIT_MS } : {}),
430
+ concurrency: { kind: "fenced", audit: fencedPath("intercom-lease") },
431
+ } as const;
432
+ /**
433
+ * A renewal only moves `renewed_at` forward, and its holder renews again within the renewal interval, far inside the
434
+ * staleness limit: one lost in a crash of the database server leaves the lease a renewal older, still live, and no
435
+ * fencing token changes. A renewal that carries a subject writes all of it, and the next renewal writes it again. So
436
+ * its commit does not wait for the disk (PostgreSQL's `synchronous_commit = off`), which
437
+ * spares the server a log flush per broker and per session every interval. Acquisitions and releases stay durable.
364
438
  */
365
- const fenced = { concurrency: { kind: "fenced", audit: fencedPath("intercom-lease") } } as const;
439
+ const renewal = { ...fenced, relaxedDurability: true } as const;
366
440
  /**
367
441
  * The order of a key acquired for the first time. A serial database runs one acquisition at a time, so the
368
442
  * largest order so far, plus one, is unique. PostgreSQL runs acquisitions beside one another, so each takes the
369
- * next value of the order sequence, which no acquisition waits for (#6560). Where `atomic storage migrate` has not
370
- * created it yet and this role may not, each takes the next value of a counter row, upserted by the statement
371
- * itself, whose row lock orders them; the counter's kind is no lease's, so no lease query reads it.
443
+ * next value of the order sequence, which no acquisition waits for (#6560). Where the sequence is missing, because
444
+ * `atomic storage migrate` has not created it yet and this role may not, or because someone dropped it, each takes
445
+ * the next value of a counter row instead, upserted by the statement itself, whose row lock orders them, and which
446
+ * never falls behind an order already taken; the counter's kind is no lease's, so no lease query reads it. Each
447
+ * statement looks the sequence up itself, so a store opened before the sequence existed takes it from then on, as
448
+ * one opened after does, and one opened before it was dropped takes the counter rather than fail: only acquisitions
449
+ * made while the sequence is created can share an order, which their keys then decide.
372
450
  */
373
451
  const largestOrder = `(SELECT COALESCE(MAX(first_acquired_order), 0) FROM ${table})`;
374
- const nextOrder = sequenced
375
- ? { with: "", value: `nextval('${orderSequence}')` }
376
- : dialect.name === "postgres"
452
+ const sequence = `to_regclass('${table}_order')`;
453
+ const nextOrder =
454
+ dialect.name === "postgres"
377
455
  ? {
378
456
  with: `WITH next_order AS (
379
457
  INSERT INTO ${table}(kind, key, last_token, first_acquired_order)
380
- VALUES ('${ACQUISITION_ORDER_KIND}', '', ${largestOrder} + 1, 0)
381
- ON CONFLICT(kind, key) DO UPDATE SET last_token = ${table}.last_token + 1
458
+ SELECT '${ACQUISITION_ORDER_KIND}', '', ${largestOrder} + 1, 0 WHERE ${sequence} IS NULL
459
+ ON CONFLICT(kind, key) DO UPDATE SET
460
+ last_token = GREATEST(${table}.last_token, excluded.last_token - 1) + 1
382
461
  RETURNING last_token
383
462
  ) `,
384
- value: "(SELECT last_token FROM next_order)",
463
+ value: `COALESCE(nextval(${sequence}), (SELECT last_token FROM next_order), ${largestOrder} + 1)`,
385
464
  }
386
465
  : { with: "", value: `${largestOrder} + 1` };
387
466
  /** Latency-bound reads, which must not queue behind this database's writes (#6560). */
388
467
  const reader = options.reader ?? database;
468
+ /**
469
+ * This store's acquisitions and releases, and retirements of a holder, started and not committed. The reads go
470
+ * through the reader, which no write of this store is queued on, so they first wait for these: a caller that starts
471
+ * one and then reads, without awaiting it, reads who holds the lease after it. With none unfinished they wait for
472
+ * nothing. Renewals are not among them: one only moves a held lease's age, which the renewal before it keeps within
473
+ * the bound every read applies, and they run every few seconds, so reads would often wait for one.
474
+ */
475
+ const unfinished = new Set<Promise<void>>();
476
+ const holding = <T>(write: Promise<T>): Promise<T> => {
477
+ const settled = write.then(
478
+ () => {},
479
+ () => {},
480
+ );
481
+ unfinished.add(settled);
482
+ void settled.then(() => unfinished.delete(settled));
483
+ return write;
484
+ };
389
485
  const clockAge = dialect.greatest("0", "(SELECT now FROM clock) - renewed_at");
390
486
  /**
391
487
  * `listLiveFor`'s read: each term is one indexed column's lookup, so SQLite takes the union of five index searches
@@ -399,6 +495,7 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
399
495
  AND holder_id IS NOT NULL AND ${clockAge} <= ? ORDER BY first_acquired_order, key`;
400
496
 
401
497
  const listLive = async (kind: LeaseKind, staleAfterMs: number): Promise<LeaseState[]> => {
498
+ if (unfinished.size > 0) await Promise.all(unfinished);
402
499
  const rows = await reader.all<StateRow>(liveLeases(dialect, table), kind, staleAfterMs);
403
500
  return rows.map(stateFromRow);
404
501
  };
@@ -415,12 +512,11 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
415
512
  // acquisition therefore waits, once it committed, for every send to that recipient under way, holding the
416
513
  // recipient's lock domain for an instant: the registration's first outbox scan, which follows, then finds
417
514
  // their rows; a later send reads the live presence and wakes its holder (#6560).
418
- const acquired = await database.transaction(async (tx) => {
419
- // One guarded statement takes the lease: a new key, or a row that is free, stale or already this
420
- // holder's; a steal gets the key's next token, a re-acquisition keeps its own. Renewals run beside it,
421
- // so the decision is never made on an earlier read (#6560).
422
- const taken = await tx.get<SqliteRow & { fencing_token: number | bigint }>(
423
- `${nextOrder.with}INSERT INTO ${table}(kind, key, holder_id, fencing_token, last_token, subject_json,
515
+ // One guarded statement takes the lease: a new key, or a row that is free, stale or already this holder's; a
516
+ // steal gets the key's next token, a re-acquisition keeps its own. Renewals run beside it, so the decision is
517
+ // never made on an earlier read (#6560).
518
+ const take: SqliteStatement = {
519
+ sql: `${nextOrder.with}INSERT INTO ${table}(kind, key, holder_id, fencing_token, last_token, subject_json,
424
520
  renewed_at, first_acquired_order)
425
521
  VALUES (?, ?, ?, 1, 1, ?, ${nowMs}, ${nextOrder.value})
426
522
  ON CONFLICT(kind, key) DO UPDATE SET
@@ -429,28 +525,34 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
429
525
  holder_id = excluded.holder_id, subject_json = excluded.subject_json, renewed_at = excluded.renewed_at
430
526
  WHERE ${table}.holder_id IS NULL OR ${mine} OR ${rowAge} > ?
431
527
  RETURNING fencing_token`,
432
- key.kind,
433
- keyId(key),
434
- holderId,
435
- stored,
436
- staleAfterMs,
437
- );
438
- if (taken !== undefined) {
439
- return {
440
- status: "acquired",
441
- lease: { key, holderId, fencingToken: Number(taken.fencing_token) },
442
- } as const;
443
- }
444
- // Held by another live holder. PostgreSQL locks the row whose guard failed until this transaction
445
- // ends, so this reads the holder that refused it.
446
- const row = (await holderOf(tx, key))!;
447
- return { status: "held", holderId: row.holder_id!, fencingToken: Number(row.fencing_token) } as const;
448
- }, fenced);
528
+ params: [key.kind, keyId(key), holderId, stored, staleAfterMs],
529
+ };
530
+ // Held by another live holder: PostgreSQL locks the row whose guard failed until the transaction ends, so this
531
+ // read, which follows the statement, finds the holder that refused it. The statement and the read go with the
532
+ // transaction's start and its commit, in one round trip, on a pipelined connection.
533
+ const holder = holderStatement(key);
534
+ const taking = database.transaction(
535
+ async (tx) => {
536
+ const taken = await tx.get<SqliteRow & { fencing_token: number | bigint }>(take.sql, ...take.params);
537
+ const row = (await tx.get<HolderRow>(holder.sql, ...holder.params))!;
538
+ if (taken !== undefined) {
539
+ return {
540
+ status: "acquired",
541
+ lease: { key, holderId, fencingToken: Number(taken.fencing_token) },
542
+ } as const;
543
+ }
544
+ return { status: "held", holderId: row.holder_id!, fencingToken: Number(row.fencing_token) } as const;
545
+ },
546
+ { ...fenced, leading: [take, holder], leadingOnly: true },
547
+ );
548
+ const acquired = await holding(taking);
549
+ // The lock goes with the transaction's start and its commit, in one round trip, so it is held for none.
449
550
  if (acquired.status === "acquired" && subject.kind === "presence" && dialect.name === "postgres")
450
- await database.transaction(
451
- async () => {},
452
- recipientTransaction(database, options.prefix, subject.targetIdentity),
453
- );
551
+ await database.transaction((tx) => tx.get(SENDS_PASSED.sql), {
552
+ ...recipientTransaction(database, options.prefix, subject.targetIdentity),
553
+ leading: [SENDS_PASSED],
554
+ leadingOnly: true,
555
+ });
454
556
  return acquired;
455
557
  },
456
558
  async renew(lease, subject) {
@@ -469,7 +571,7 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
469
571
  ...ownedParams(lease),
470
572
  );
471
573
  return changes === 1 ? ({ status: "renewed" } as const) : stale(await holderOf(tx, lease.key));
472
- }, fenced);
574
+ }, renewal);
473
575
  },
474
576
  async renewMany(requests) {
475
577
  if (requests.length === 0) return [];
@@ -518,13 +620,13 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
518
620
  renewed[position]!.changes === 1
519
621
  ? ({ status: "renewed" } as const)
520
622
  : stale(await holderOf(tx, requests[i]!.lease.key));
521
- }, fenced);
623
+ }, renewal);
522
624
  return results as LeaseRenewResult[];
523
625
  },
524
626
  async release(lease) {
525
627
  const bad = validLease(lease);
526
628
  if (bad !== undefined) return bad;
527
- return database.transaction(async (tx) => {
629
+ const releasing = database.transaction(async (tx) => {
528
630
  const { changes } = await tx.run(
529
631
  `UPDATE ${table} SET holder_id = NULL, fencing_token = NULL, subject_json = NULL, renewed_at = NULL
530
632
  WHERE ${owned}`,
@@ -532,10 +634,12 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
532
634
  );
533
635
  return changes === 1 ? ({ status: "released" } as const) : stale(await holderOf(tx, lease.key));
534
636
  }, fenced);
637
+ return holding(releasing);
535
638
  },
536
639
  async read(key) {
537
640
  const bad = invalidKey(key);
538
641
  if (bad !== undefined) return bad;
642
+ if (unfinished.size > 0) await Promise.all(unfinished);
539
643
  const row = await reader.get<StateRow>(
540
644
  `SELECT kind, key, holder_id, fencing_token, subject_json, ${leaseAge} AS age_ms FROM ${table}
541
645
  WHERE kind = ? AND key = ? AND holder_id IS NOT NULL`,
@@ -555,6 +659,7 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
555
659
  const target = named.toWellFormed();
556
660
  const trimmed = target.trim();
557
661
  const head = /^[0-9a-f]{8}$/i.test(trimmed) ? trimmed.toLowerCase() : null;
662
+ if (unfinished.size > 0) await Promise.all(unfinished);
558
663
  const rows = await reader.all<StateRow>(
559
664
  liveAddressed,
560
665
  target,
@@ -571,15 +676,17 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
571
676
  }
572
677
  : {}),
573
678
  async listAged(kind, minAgeMs) {
679
+ if (unfinished.size > 0) await Promise.all(unfinished);
574
680
  const rows = await reader.all<StateRow>(leasesByAge(dialect, table, ">="), kind, minAgeMs);
575
681
  return rows.map(stateFromRow);
576
682
  },
577
683
  async retireHolder(holderId) {
578
- const { changes } = await database.run(
684
+ const retiring = database.run(
579
685
  `UPDATE ${table} SET holder_id = NULL, fencing_token = NULL, subject_json = NULL, renewed_at = NULL
580
686
  WHERE holder_id = ?`,
581
687
  holderId,
582
688
  );
689
+ const { changes } = await holding(retiring);
583
690
  return changes;
584
691
  },
585
692
  };