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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (432) hide show
  1. package/CHANGELOG.md +99 -0
  2. package/README.md +5 -8
  3. package/dist/_shared/dist-KOELCESV.js +2 -2
  4. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  5. package/dist/_shared/lib-4PES5P4V.js +2 -2
  6. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +6 -6
  7. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +5 -5
  8. package/dist/_shared/mode-shared-2QJSCUM6.js +6 -6
  9. package/dist/_shared/p0-cli-BB45ZQY6.js +46 -67
  10. package/dist/_shared/p0-cli-BB45ZQY6.js.map +1 -1
  11. package/dist/_shared/p1a-prewarm-XIU57JHF.js +7 -8
  12. package/dist/_shared/p1a-prewarm-XIU57JHF.js.map +1 -1
  13. package/dist/_shared/{p1b-elig-ENCUPKKJ.js → p1b-elig-TVB5CBLL.js} +14 -2
  14. package/dist/_shared/{p1b-elig-ENCUPKKJ.js.map → p1b-elig-TVB5CBLL.js.map} +1 -1
  15. package/dist/_shared/runtime-O4KCSG4C.js +3 -3
  16. package/dist/_shared/{sdk-IQMULKFU.js → sdk-B5LEWGGI.js} +340 -163
  17. package/dist/_shared/sdk-B5LEWGGI.js.map +1 -0
  18. package/dist/_shared/session-data-AHTU7IS6.js +2 -2
  19. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  20. package/dist/_shared/{startup-0-0-3IXNMFM2.js → startup-0-0-EZUKEP4Q.js} +48 -40
  21. package/dist/_shared/startup-0-0-EZUKEP4Q.js.map +1 -0
  22. package/dist/_shared/{startup-0-1-7T2IAE7J.js → startup-0-1-RTOHJFDJ.js} +195 -42
  23. package/dist/_shared/startup-0-1-RTOHJFDJ.js.map +1 -0
  24. package/dist/_shared/startup-0-2-5QHPCEON.js +33 -43
  25. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -1
  26. package/dist/_shared/startup-0-3-4ZYBYQNM.js +5 -5
  27. package/dist/_shared/startup-0-4-ZMJV547D.js +12 -7
  28. package/dist/_shared/startup-0-4-ZMJV547D.js.map +1 -1
  29. package/dist/_shared/startup-0-5-YDW47QX6.js +7 -7
  30. package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -1
  31. package/dist/_shared/startup-10-0-TDQNBDDL.js +6 -6
  32. package/dist/_shared/startup-12-0-55AAXBJZ.js +2 -2
  33. package/dist/_shared/startup-14-0-MLX36RBG.js +4 -5
  34. package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
  35. package/dist/_shared/startup-15-0-YUKGAC63.js +4 -4
  36. package/dist/_shared/startup-15-1-4S7FLMNG.js +19 -27
  37. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  38. package/dist/_shared/startup-8-0-34CBHPZH.js +39 -23
  39. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  40. package/dist/_shared/{startup-8-1-X32CYSXB.js → startup-8-1-LZFXSD3Z.js} +90 -1176
  41. package/dist/_shared/startup-8-1-LZFXSD3Z.js.map +1 -0
  42. package/dist/_shared/storage-command-7MGXLJGZ.js +186 -35
  43. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  44. package/dist/_shared/storage-status-K7PX2RXA.js +557 -0
  45. package/dist/_shared/storage-status-K7PX2RXA.js.map +1 -0
  46. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  47. package/dist/_shared/team-DOQKICG2.js +376 -0
  48. package/dist/_shared/team-DOQKICG2.js.map +1 -0
  49. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  50. package/dist/builtin/intercom/CHANGELOG.md +23 -0
  51. package/dist/builtin/intercom/README.md +2 -2
  52. package/dist/builtin/intercom/broker/broker.bundle.mjs +913 -289
  53. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +243 -64
  54. package/dist/builtin/intercom/broker/multinode-router.ts +154 -22
  55. package/dist/builtin/intercom/broker/multinode-state-store.ts +30 -3
  56. package/dist/builtin/intercom/broker/open-broker-state.ts +14 -0
  57. package/dist/builtin/intercom/broker/sql-add-column.ts +29 -5
  58. package/dist/builtin/intercom/broker/sql-ended-child-queue-store.ts +3 -2
  59. package/dist/builtin/intercom/broker/sql-held-send-store.ts +2 -2
  60. package/dist/builtin/intercom/broker/sql-known-session-store.ts +43 -19
  61. package/dist/builtin/intercom/broker/sql-lease-store.ts +170 -74
  62. package/dist/builtin/intercom/broker/sql-outbox-store.ts +298 -47
  63. package/dist/builtin/intercom/broker/sql-pending-ask-store.ts +8 -5
  64. package/dist/builtin/intercom/broker/sql-released-ask-store.ts +12 -5
  65. package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +24 -7
  66. package/dist/builtin/intercom/broker/sql-retention.ts +141 -0
  67. package/dist/builtin/intercom/broker/sql-schema.ts +136 -19
  68. package/dist/builtin/intercom/broker/sql-sent-message-authority.ts +74 -19
  69. package/dist/builtin/intercom/broker/wake-up-bus.ts +6 -0
  70. package/dist/builtin/intercom/index.bundle.mjs +2 -3
  71. package/dist/builtin/intercom/package.json +1 -1
  72. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  73. package/dist/builtin/mcp/package.json +1 -1
  74. package/dist/builtin/subagents/package.json +1 -1
  75. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  76. package/dist/builtin/web-access/index.bundle.mjs +2 -10
  77. package/dist/builtin/web-access/package.json +1 -1
  78. package/dist/bun/bundled-sqlite.js +41 -0
  79. package/dist/bun/bundled-sqlite.js.map +1 -0
  80. package/dist/cli/args.js +2 -2
  81. package/dist/cli/auth-cli.code.js +4 -4
  82. package/dist/cli/auth-cli.impl.js +3 -3
  83. package/dist/cli/auth-cli.js +3 -3
  84. package/dist/cli/blueprint-command.code.js +3 -3
  85. package/dist/cli/blueprint-command.impl.js +3 -3
  86. package/dist/cli/blueprint-command.js +3 -3
  87. package/dist/cli/intercom-command.code.js +3 -3
  88. package/dist/cli/intercom-command.code.js.map +1 -1
  89. package/dist/cli/intercom-command.impl.js +3 -3
  90. package/dist/cli/intercom-command.js +3 -3
  91. package/dist/cli/list-models.code.js +2 -2
  92. package/dist/cli/list-models.impl.js +3 -3
  93. package/dist/cli/list-models.js +3 -3
  94. package/dist/cli/session-picker.code.js +1 -1
  95. package/dist/cli/session-picker.impl.js +3 -3
  96. package/dist/cli/session-picker.js +3 -3
  97. package/dist/cli/startup-ui.code.js +1 -1
  98. package/dist/cli/startup-ui.impl.js +3 -3
  99. package/dist/cli/startup-ui.js +3 -3
  100. package/dist/cli/storage-command.impl.js +3 -3
  101. package/dist/cli/storage-command.js +3 -3
  102. package/dist/cli/storage-search-session.code.js +3 -3
  103. package/dist/cli/storage-search-session.impl.js +3 -3
  104. package/dist/cli/storage-search-session.js +3 -3
  105. package/dist/cli/team-command.code.js +19 -113
  106. package/dist/cli/team-command.code.js.map +1 -1
  107. package/dist/cli/team-command.impl.js +3 -3
  108. package/dist/cli/team-command.js +3 -3
  109. package/dist/cli.js +5 -18
  110. package/dist/cli.js.map +1 -1
  111. package/dist/core/agent-rehydrate-errors.d.ts +4 -9
  112. package/dist/core/compaction/compactor.d.ts +3 -3
  113. package/dist/core/debug.code.js +1 -1
  114. package/dist/core/debug.impl.js +3 -3
  115. package/dist/core/debug.js +3 -3
  116. package/dist/core/export-html/card-projection.impl.js +3 -3
  117. package/dist/core/export-html/card-projection.js +3 -3
  118. package/dist/core/export-html/index.code.js +2 -2
  119. package/dist/core/export-html/index.impl.js +3 -3
  120. package/dist/core/export-html/index.js +3 -3
  121. package/dist/core/export-html/json-spans.impl.js +3 -3
  122. package/dist/core/export-html/json-spans.js +3 -3
  123. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  124. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  125. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  126. package/dist/core/export-html/tool-renderer.js +3 -3
  127. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  128. package/dist/core/extensions/jiti-loader.js +3 -3
  129. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  130. package/dist/core/extensions/jiti-static-loader.js +3 -3
  131. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  132. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  133. package/dist/core/extensions/loader-host-modules.js +3 -3
  134. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  135. package/dist/core/extensions/runner-context.js +2 -2
  136. package/dist/core/intercom-broker-control-host.code.js +2 -2
  137. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  138. package/dist/core/intercom-broker-control-host.js +3 -3
  139. package/dist/core/intercom-broker-control.code.js +3 -3
  140. package/dist/core/intercom-broker-control.impl.js +3 -3
  141. package/dist/core/intercom-broker-control.js +3 -3
  142. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  143. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  144. package/dist/core/package-manager-storage-adapters.js +3 -3
  145. package/dist/core/process-start-token.d.ts +8 -0
  146. package/dist/core/process-tree-containment.d.ts +16 -0
  147. package/dist/core/sdk-types.d.ts +1 -2
  148. package/dist/core/sdk-types.js.map +1 -1
  149. package/dist/core/sdk.code.js +3 -3
  150. package/dist/core/sdk.impl.js +3 -3
  151. package/dist/core/sdk.js +3 -3
  152. package/dist/core/session-manager-core.js +5 -5
  153. package/dist/core/session-manager-list.impl.js +3 -3
  154. package/dist/core/session-manager-list.js +3 -3
  155. package/dist/core/session-manager.code.js +1 -1
  156. package/dist/core/session-manager.impl.js +3 -3
  157. package/dist/core/session-manager.js +3 -3
  158. package/dist/core/session-storage.code.js +1 -1
  159. package/dist/core/session-storage.impl.js +3 -3
  160. package/dist/core/session-storage.js +3 -3
  161. package/dist/core/settings-schema.d.ts +0 -3
  162. package/dist/core/storage/added-exports-0-10-11.js +19 -0
  163. package/dist/core/storage/added-exports-0-10-11.js.map +1 -0
  164. package/dist/core/storage/creation-time.js +105 -0
  165. package/dist/core/storage/creation-time.js.map +1 -0
  166. package/dist/core/storage/database.d.ts +19 -5
  167. package/dist/core/storage/database.js.map +1 -1
  168. package/dist/core/storage/dialect.d.ts +1 -1
  169. package/dist/core/storage/dialect.js +1 -1
  170. package/dist/core/storage/dialect.js.map +1 -1
  171. package/dist/core/storage/errors.d.ts +13 -13
  172. package/dist/core/storage/errors.js +10 -16
  173. package/dist/core/storage/errors.js.map +1 -1
  174. package/dist/core/storage/fenced-paths.d.ts +11 -0
  175. package/dist/core/storage/fenced-paths.js +11 -0
  176. package/dist/core/storage/fenced-paths.js.map +1 -1
  177. package/dist/core/storage/file-identity.d.ts +2 -0
  178. package/dist/core/storage/file-identity.js +24 -8
  179. package/dist/core/storage/file-identity.js.map +1 -1
  180. package/dist/core/storage/index.d.ts +3 -2
  181. package/dist/core/storage/index.js +5 -3
  182. package/dist/core/storage/index.js.map +1 -1
  183. package/dist/core/storage/libsql-removed.d.ts +71 -0
  184. package/dist/core/storage/libsql-removed.js +123 -0
  185. package/dist/core/storage/libsql-removed.js.map +1 -0
  186. package/dist/core/storage/migrations.d.ts +78 -14
  187. package/dist/core/storage/migrations.js +375 -49
  188. package/dist/core/storage/migrations.js.map +1 -1
  189. package/dist/core/storage/node-sqlite-file-gate.js +0 -15
  190. package/dist/core/storage/node-sqlite-file-gate.js.map +1 -1
  191. package/dist/core/storage/node-sqlite-thread.js +8 -13
  192. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  193. package/dist/core/storage/node-sqlite.js +51 -3
  194. package/dist/core/storage/node-sqlite.js.map +1 -1
  195. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  196. package/dist/core/storage/offline-snapshot-file.js +3 -3
  197. package/dist/core/storage/prefix.d.ts +1 -1
  198. package/dist/core/storage/prefix.js +9 -2
  199. package/dist/core/storage/prefix.js.map +1 -1
  200. package/dist/core/storage/process-selection.d.ts +5 -5
  201. package/dist/core/storage/provider.js +2 -2
  202. package/dist/core/storage/schema-catalog.d.ts +7 -8
  203. package/dist/core/storage/schema-catalog.js +8 -8
  204. package/dist/core/storage/schema-catalog.js.map +1 -1
  205. package/dist/core/storage/selection.d.ts +7 -82
  206. package/dist/core/storage/selection.js +20 -235
  207. package/dist/core/storage/selection.js.map +1 -1
  208. package/dist/core/storage/session/branch-fork-source.code.js +2 -2
  209. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  210. package/dist/core/storage/session/branch-fork-source.js +3 -3
  211. package/dist/core/storage/session/card-view.impl.js +3 -3
  212. package/dist/core/storage/session/card-view.js +3 -3
  213. package/dist/core/storage/session/child-reader.code.js +3 -3
  214. package/dist/core/storage/session/child-reader.impl.js +3 -3
  215. package/dist/core/storage/session/child-reader.js +3 -3
  216. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  217. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  218. package/dist/core/storage/session/expanded-child-details.code.js +2 -2
  219. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  220. package/dist/core/storage/session/expanded-child-details.js +3 -3
  221. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  222. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  223. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  224. package/dist/core/storage/session/fork-row-index.js +3 -3
  225. package/dist/core/storage/session/fork-staging.code.js +4 -7
  226. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  227. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  228. package/dist/core/storage/session/fork-staging.js +3 -3
  229. package/dist/core/storage/session/fork-window.code.js +3 -3
  230. package/dist/core/storage/session/fork-window.impl.js +3 -3
  231. package/dist/core/storage/session/fork-window.js +3 -3
  232. package/dist/core/storage/session/history-pages.impl.js +3 -3
  233. package/dist/core/storage/session/history-pages.js +3 -3
  234. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  235. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  236. package/dist/core/storage/session/jsonl-session-store.d.ts +5 -1
  237. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  238. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  239. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  240. package/dist/core/storage/session/memory-session-store.js +3 -3
  241. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  242. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  243. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  244. package/dist/core/storage/session/released-history-files.code.js +3 -3
  245. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  246. package/dist/core/storage/session/released-history-files.js +3 -3
  247. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  248. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  249. package/dist/core/storage/session/session-resume.impl.js +3 -3
  250. package/dist/core/storage/session/session-resume.js +3 -3
  251. package/dist/core/storage/session/session-search-index.d.ts +43 -4
  252. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  253. package/dist/core/storage/session/snapshot-cut.js +3 -3
  254. package/dist/core/storage/session/snapshot-history.code.js +3 -3
  255. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  256. package/dist/core/storage/session/snapshot-history.js +3 -3
  257. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  258. package/dist/core/storage/session/sql-session-store.d.ts +48 -11
  259. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  260. package/dist/core/storage/session/sql-session-store.js +3 -3
  261. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  262. package/dist/core/storage/session/tree-outline.js +3 -3
  263. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  264. package/dist/core/storage/session/tree-presentation.js +3 -3
  265. package/dist/core/storage/sqlite-facade.d.ts +6 -1
  266. package/dist/core/storage/sqlite-facade.js +1 -0
  267. package/dist/core/storage/sqlite-facade.js.map +1 -1
  268. package/dist/core/storage/storage-status.code.js +1 -1
  269. package/dist/core/storage/storage-status.impl.js +3 -3
  270. package/dist/core/storage/storage-status.js +3 -3
  271. package/dist/core/storage/team.code.js +1 -1
  272. package/dist/core/storage/team.d.ts +26 -115
  273. package/dist/core/storage/team.impl.js +3 -3
  274. package/dist/core/storage/team.js +3 -3
  275. package/dist/core/structured-output/index.code.js +1 -1
  276. package/dist/core/structured-output/index.impl.js +3 -3
  277. package/dist/core/structured-output/index.js +3 -3
  278. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  279. package/dist/core/tasks/task-completion-entry.js +3 -3
  280. package/dist/core/tasks/task-file-history.code.js +3 -3
  281. package/dist/core/tasks/task-file-history.impl.js +3 -3
  282. package/dist/core/tasks/task-file-history.js +3 -3
  283. package/dist/core/tasks/task-reference-archive.code.js +4 -4
  284. package/dist/core/tasks/task-reference-archive.js +3 -3
  285. package/dist/core/tasks/task-reference-identity.js +3 -3
  286. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  287. package/dist/core/tasks/task-reference-stream.js +3 -3
  288. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  289. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  290. package/dist/core/tasks/task-view-source.code.js +1 -1
  291. package/dist/core/tasks/task-view-source.impl.js +3 -3
  292. package/dist/core/tasks/task-view-source.js +3 -3
  293. package/dist/core/tools/history-tasks.d.ts +3 -2
  294. package/dist/core/tools/read-url.code.js +4 -4
  295. package/dist/core/tools/read-url.impl.js +3 -3
  296. package/dist/core/tools/read-url.js +3 -3
  297. package/dist/core/worktree-snapshot/blob-store.d.ts +40 -3
  298. package/dist/core/worktree-snapshot/blob-store.js +414 -21
  299. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  300. package/dist/core/worktree-snapshot/errors.code.js +2 -2
  301. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  302. package/dist/core/worktree-snapshot/errors.js +3 -3
  303. package/dist/core/worktree-snapshot/fork-blob-guard.js +81 -0
  304. package/dist/core/worktree-snapshot/fork-blob-guard.js.map +1 -0
  305. package/dist/core/worktree-snapshot/fork-snapshot-index.js +79 -38
  306. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -1
  307. package/dist/core/worktree-snapshot/session-index-reset.code.js +4 -0
  308. package/dist/core/worktree-snapshot/session-index-reset.code.js.map +1 -1
  309. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  310. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  311. package/dist/extensions/codemode/execute.code.js +1 -1
  312. package/dist/extensions/codemode/execute.impl.js +3 -3
  313. package/dist/extensions/codemode/execute.js +3 -3
  314. package/dist/extensions/codemode/renderer.code.js +2 -2
  315. package/dist/extensions/codemode/renderer.impl.js +3 -3
  316. package/dist/extensions/codemode/renderer.js +3 -3
  317. package/dist/extensions/mcp/cli.code.js +3 -3
  318. package/dist/extensions/mcp/cli.impl.js +3 -3
  319. package/dist/extensions/mcp/cli.js +3 -3
  320. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  321. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  322. package/dist/extensions/mcp/cli.lazy.js +3 -3
  323. package/dist/extensions/mcp/runtime.code.js +1 -1
  324. package/dist/extensions/mcp/runtime.impl.js +3 -3
  325. package/dist/extensions/mcp/runtime.js +3 -3
  326. package/dist/index.d.ts +3 -1
  327. package/dist/index.js +5 -5
  328. package/dist/main-first-time-setup.code.js +1 -1
  329. package/dist/main-first-time-setup.impl.js +3 -3
  330. package/dist/main-first-time-setup.js +3 -3
  331. package/dist/main.js +1 -1
  332. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  333. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  334. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  335. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  336. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  337. package/dist/modes/interactive/startup-shell-eligibility.js +1 -1
  338. package/dist/modes/interactive-engine/engine-prewarm.d.ts +1 -1
  339. package/dist/modes/print-mode.js +1 -1
  340. package/dist/package-manager-cli.code.js +6 -6
  341. package/dist/package-manager-cli.impl.js +3 -3
  342. package/dist/package-manager-cli.js +3 -3
  343. package/dist/rpc-entry.js +1 -1
  344. package/dist/startup-files.json +1 -1
  345. package/dist/startup-stages/10.js +1 -1
  346. package/dist/startup-stages/11.js +1 -1
  347. package/dist/startup-stages/12.js +1 -1
  348. package/dist/startup-stages/2.js +2 -4
  349. package/dist/startup-stages/3.js +1 -3
  350. package/dist/startup-stages/4.js +1 -2
  351. package/dist/startup-stages/5.js +1 -1
  352. package/dist/startup-stages/6.js +5 -7
  353. package/dist/startup-stages/7.js +3 -10
  354. package/dist/startup-stages/8.js +7 -2
  355. package/dist/startup-stages/9.js +1 -7
  356. package/dist/startup-stages/stages.json +1 -1
  357. package/dist/utils/compile-cache-deferral.js +8 -13
  358. package/dist/utils/compile-cache-deferral.js.map +1 -1
  359. package/dist/utils/compile-cache-warmup-host.js +3 -4
  360. package/dist/utils/compile-cache-warmup-host.js.map +1 -1
  361. package/dist/utils/compile-cache.js +12 -100
  362. package/dist/utils/compile-cache.js.map +1 -1
  363. package/dist/utils/startup-database-spare.code.js +2 -2
  364. package/dist/utils/startup-database-spare.impl.js +3 -3
  365. package/dist/utils/startup-database-spare.js +3 -3
  366. package/dist/utils/tools-manager.code.js +1 -1
  367. package/dist/utils/tools-manager.impl.js +3 -3
  368. package/dist/utils/tools-manager.js +3 -3
  369. package/dist/utils/worker-threads.js +2 -15
  370. package/dist/utils/worker-threads.js.map +1 -1
  371. package/docs/build.md +3 -3
  372. package/docs/changelog.mdx +1421 -69
  373. package/docs/compaction/reference.md +5 -5
  374. package/docs/compaction.md +7 -9
  375. package/docs/containerization.md +2 -2
  376. package/docs/custom-provider/api-reference.md +1 -1
  377. package/docs/docs.json +37 -10
  378. package/docs/environment-variables.md +0 -2
  379. package/docs/extensions/api-reference.md +4 -4
  380. package/docs/getting-started/installation.md +3 -0
  381. package/docs/guides/configuration.md +1 -1
  382. package/docs/guides/non-interactive.md +1 -1
  383. package/docs/guides/resume-on-any-machine.md +14 -22
  384. package/docs/guides/team-setup.md +56 -83
  385. package/docs/guides.md +2 -4
  386. package/docs/herdr.md +1 -1
  387. package/docs/index.md +1 -1
  388. package/docs/intercom/operations.md +26 -21
  389. package/docs/intercom/reference.md +2 -2
  390. package/docs/intercom.md +1 -1
  391. package/docs/libraries/storage-postgres.md +9 -9
  392. package/docs/libraries.md +2 -3
  393. package/docs/models-configuration.md +2 -2
  394. package/docs/models.md +2 -3
  395. package/docs/packages/authoring.md +7 -7
  396. package/docs/packages.md +1 -1
  397. package/docs/programmatic.md +2 -2
  398. package/docs/quickstart.md +1 -1
  399. package/docs/reference/cli.md +6 -11
  400. package/docs/reference.md +2 -2
  401. package/docs/rpc/extension-ui.md +2 -2
  402. package/docs/sdk/reference.md +5 -4
  403. package/docs/sdk/storage.md +8 -92
  404. package/docs/sdk/structured-decisions.md +1 -1
  405. package/docs/sdk/web-server.md +3 -3
  406. package/docs/sdk.md +14 -4
  407. package/docs/security.md +1 -1
  408. package/docs/session-format.md +5 -5
  409. package/docs/sessions.md +29 -49
  410. package/docs/settings.md +7 -8
  411. package/docs/storage/custom-adapters.md +255 -0
  412. package/docs/storage/jsonl.md +117 -0
  413. package/docs/{guides/postgres-pgbouncer.md → storage/postgres/pgbouncer.md} +66 -68
  414. package/docs/storage/postgres/tuning.md +337 -0
  415. package/docs/storage/postgres.md +556 -0
  416. package/docs/storage/sqlite.md +99 -0
  417. package/docs/storage.md +326 -990
  418. package/docs/subagents/authoring.md +1 -1
  419. package/docs/subagents.md +2 -2
  420. package/docs/tools.md +1 -1
  421. package/docs/worktree-snapshots.md +2 -2
  422. package/package.json +9 -9
  423. package/schemas/models.schema.json +2 -2
  424. package/schemas/settings.schema.json +0 -14
  425. package/dist/_shared/sdk-IQMULKFU.js.map +0 -1
  426. package/dist/_shared/startup-0-0-3IXNMFM2.js.map +0 -1
  427. package/dist/_shared/startup-0-1-7T2IAE7J.js.map +0 -1
  428. package/dist/_shared/startup-8-1-X32CYSXB.js.map +0 -1
  429. package/dist/core/intercom-broker-control.d.ts +0 -129
  430. package/dist/startup-stages/13.js +0 -1
  431. package/docs/guides/postgres-tuning.md +0 -311
  432. package/docs/libraries/storage-libsql.md +0 -97
@@ -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,
@@ -27,6 +28,7 @@ import { recipientTransaction } from "./sql-outbox-store.js";
27
28
  import {
28
29
  ensureBrokerSchema,
29
30
  openCatalogOf,
31
+ RETRY_UNAPPLIED,
30
32
  stampBrokerSchemaAtOpenEnd,
31
33
  withBrokerSchemaCatalog,
32
34
  } from "./sql-schema.js";
@@ -46,6 +48,16 @@ const fillfactorApi: Partial<Pick<typeof storage, "ensureTableFillfactor">> = st
46
48
  */
47
49
  const LEASE_FILLFACTOR = 80;
48
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
+
49
61
  /**
50
62
  * The kind of the row whose `last_token` counts acquisitions on PostgreSQL where the order sequence is missing: see
51
63
  * `nextOrder`.
@@ -55,29 +67,46 @@ const ACQUISITION_ORDER_KIND = "acquisition-order";
55
67
  /**
56
68
  * Creates the sequence first acquisitions take their order from on PostgreSQL, `<table>_order`, once per database
57
69
  * (recorded as the `intercom-lease-order` schema step), starting past every order taken so far, the counter row's
58
- * included. False where it is missing and this role may not create it: a runtime role on a database `atomic storage
59
- * 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).
60
73
  */
61
- async function ensureOrderSequence(
62
- database: SqliteDatabase,
63
- prefix: string | undefined,
64
- table: string,
65
- ): 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);
66
91
  try {
67
- await ensureBrokerSchema(database, prefix, "lease-order", async (tx) => {
68
- 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.
69
98
  await tx.get(
70
- `SELECT setval('${table}_order', GREATEST(
71
- (SELECT COALESCE(MAX(first_acquired_order), 0) FROM ${table}),
72
- (SELECT COALESCE(MAX(last_token), 0) FROM ${table} WHERE kind = '${ACQUISITION_ORDER_KIND}'),
73
- 1
74
- ))`,
99
+ "SELECT pg_advisory_xact_lock(hashtextextended(?, 0)) AS locked",
100
+ `${storageMigrationTable(prefix)}:schema`,
75
101
  );
102
+ const found = await tx.get<SqliteRow & { missing: boolean | number }>(
103
+ "SELECT to_regclass(?) IS NULL AS missing",
104
+ sequence,
105
+ );
106
+ if (found?.missing === true || Number(found?.missing) === 1) await create(tx);
76
107
  });
77
- return true;
78
108
  } catch (error) {
79
- if (isMissingPrivilege(error)) return false;
80
- throw error;
109
+ if (!isMissingPrivilege(error)) throw error;
81
110
  }
82
111
  }
83
112
 
@@ -254,22 +283,41 @@ const compare = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
254
283
  const invalid = (reason: StateStoreInvalidReason): InvalidStateInput => ({ status: "invalid", reason });
255
284
 
256
285
  function keyOf(subject: LeaseSubject): LeaseKey {
257
- return subject.kind === "broker"
258
- ? { kind: "broker", brokerId: subject.brokerId }
259
- : { 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
+ }
260
294
  }
261
295
 
262
296
  function keyId(key: LeaseKey): string {
263
- 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
+ }
264
305
  }
265
306
 
266
307
  function keyFor(kind: LeaseKind, id: string): LeaseKey {
267
- 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
+ }
268
316
  }
269
317
 
270
318
  function invalidKey(key: LeaseKey): InvalidStateInput | undefined {
271
319
  if (keyId(key).length > 0) return undefined;
272
- 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");
273
321
  }
274
322
 
275
323
  /**
@@ -290,7 +338,7 @@ function stateFromRow(row: StateRow): LeaseState {
290
338
  // A row an earlier broker wrote may hold half a surrogate pair: it reads as a stored one would.
291
339
  const subject: LeaseSubject = JSON.parse(row.subject_json, wellFormed);
292
340
  return {
293
- key: keyFor(row.kind === "broker" ? "broker" : "presence", row.key),
341
+ key: keyFor(row.kind === "broker" || row.kind === "maintenance" ? row.kind : "presence", row.key),
294
342
  holderId: row.holder_id,
295
343
  fencingToken: Number(row.fencing_token),
296
344
  subject,
@@ -340,8 +388,7 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
340
388
  )
341
389
  `;
342
390
  await ensureBrokerSchema(database, options.prefix, "leases", (tx) => tx.exec(schema));
343
- const orderSequence = `${table}_order`;
344
- const sequenced = dialect.name === "postgres" && (await ensureOrderSequence(database, options.prefix, table));
391
+ if (dialect.name === "postgres") await ensureOrderSequence(database, options.prefix, table);
345
392
  const addressed = await ensureAddressColumns(database, options.prefix, table);
346
393
  await fillfactorApi.ensureTableFillfactor?.(database, {
347
394
  ledger: storageMigrationTable(options.prefix),
@@ -351,12 +398,14 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
351
398
  fillfactor: LEASE_FILLFACTOR,
352
399
  });
353
400
 
354
- const holderOf = (executor: SqliteExecutor, key: LeaseKey) =>
355
- executor.get<HolderRow>(
356
- `SELECT holder_id, fencing_token, last_token, ${leaseAge} AS age_ms FROM ${table} WHERE kind = ? AND key = ?`,
357
- key.kind,
358
- keyId(key),
359
- );
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
+ };
360
409
  const stale = (row: HolderRow | undefined) =>
361
410
  row?.holder_id === null || row?.holder_id === undefined
362
411
  ? ({ status: "stale" } as const)
@@ -371,32 +420,68 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
371
420
  const rowAge = dialect.greatest("0", `${nowMs} - ${table}.renewed_at`);
372
421
  /**
373
422
  * Every write decides on its own row in one guarded statement, so leases never wait for the database's serial lock,
374
- * 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.
375
426
  */
376
- const fenced = { concurrency: { kind: "fenced", audit: fencedPath("intercom-lease") } } as const;
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.
438
+ */
439
+ const renewal = { ...fenced, relaxedDurability: true } as const;
377
440
  /**
378
441
  * The order of a key acquired for the first time. A serial database runs one acquisition at a time, so the
379
442
  * largest order so far, plus one, is unique. PostgreSQL runs acquisitions beside one another, so each takes the
380
- * next value of the order sequence, which no acquisition waits for (#6560). Where `atomic storage migrate` has not
381
- * created it yet and this role may not, each takes the next value of a counter row, upserted by the statement
382
- * 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.
383
450
  */
384
451
  const largestOrder = `(SELECT COALESCE(MAX(first_acquired_order), 0) FROM ${table})`;
385
- const nextOrder = sequenced
386
- ? { with: "", value: `nextval('${orderSequence}')` }
387
- : dialect.name === "postgres"
452
+ const sequence = `to_regclass('${table}_order')`;
453
+ const nextOrder =
454
+ dialect.name === "postgres"
388
455
  ? {
389
456
  with: `WITH next_order AS (
390
457
  INSERT INTO ${table}(kind, key, last_token, first_acquired_order)
391
- VALUES ('${ACQUISITION_ORDER_KIND}', '', ${largestOrder} + 1, 0)
392
- 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
393
461
  RETURNING last_token
394
462
  ) `,
395
- value: "(SELECT last_token FROM next_order)",
463
+ value: `COALESCE(nextval(${sequence}), (SELECT last_token FROM next_order), ${largestOrder} + 1)`,
396
464
  }
397
465
  : { with: "", value: `${largestOrder} + 1` };
398
466
  /** Latency-bound reads, which must not queue behind this database's writes (#6560). */
399
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
+ };
400
485
  const clockAge = dialect.greatest("0", "(SELECT now FROM clock) - renewed_at");
401
486
  /**
402
487
  * `listLiveFor`'s read: each term is one indexed column's lookup, so SQLite takes the union of five index searches
@@ -410,6 +495,7 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
410
495
  AND holder_id IS NOT NULL AND ${clockAge} <= ? ORDER BY first_acquired_order, key`;
411
496
 
412
497
  const listLive = async (kind: LeaseKind, staleAfterMs: number): Promise<LeaseState[]> => {
498
+ if (unfinished.size > 0) await Promise.all(unfinished);
413
499
  const rows = await reader.all<StateRow>(liveLeases(dialect, table), kind, staleAfterMs);
414
500
  return rows.map(stateFromRow);
415
501
  };
@@ -426,12 +512,11 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
426
512
  // acquisition therefore waits, once it committed, for every send to that recipient under way, holding the
427
513
  // recipient's lock domain for an instant: the registration's first outbox scan, which follows, then finds
428
514
  // their rows; a later send reads the live presence and wakes its holder (#6560).
429
- const acquired = await database.transaction(async (tx) => {
430
- // One guarded statement takes the lease: a new key, or a row that is free, stale or already this
431
- // holder's; a steal gets the key's next token, a re-acquisition keeps its own. Renewals run beside it,
432
- // so the decision is never made on an earlier read (#6560).
433
- const taken = await tx.get<SqliteRow & { fencing_token: number | bigint }>(
434
- `${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,
435
520
  renewed_at, first_acquired_order)
436
521
  VALUES (?, ?, ?, 1, 1, ?, ${nowMs}, ${nextOrder.value})
437
522
  ON CONFLICT(kind, key) DO UPDATE SET
@@ -440,28 +525,34 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
440
525
  holder_id = excluded.holder_id, subject_json = excluded.subject_json, renewed_at = excluded.renewed_at
441
526
  WHERE ${table}.holder_id IS NULL OR ${mine} OR ${rowAge} > ?
442
527
  RETURNING fencing_token`,
443
- key.kind,
444
- keyId(key),
445
- holderId,
446
- stored,
447
- staleAfterMs,
448
- );
449
- if (taken !== undefined) {
450
- return {
451
- status: "acquired",
452
- lease: { key, holderId, fencingToken: Number(taken.fencing_token) },
453
- } as const;
454
- }
455
- // Held by another live holder. PostgreSQL locks the row whose guard failed until this transaction
456
- // ends, so this reads the holder that refused it.
457
- const row = (await holderOf(tx, key))!;
458
- return { status: "held", holderId: row.holder_id!, fencingToken: Number(row.fencing_token) } as const;
459
- }, 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.
460
550
  if (acquired.status === "acquired" && subject.kind === "presence" && dialect.name === "postgres")
461
- await database.transaction(
462
- async () => {},
463
- recipientTransaction(database, options.prefix, subject.targetIdentity),
464
- );
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
+ });
465
556
  return acquired;
466
557
  },
467
558
  async renew(lease, subject) {
@@ -480,7 +571,7 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
480
571
  ...ownedParams(lease),
481
572
  );
482
573
  return changes === 1 ? ({ status: "renewed" } as const) : stale(await holderOf(tx, lease.key));
483
- }, fenced);
574
+ }, renewal);
484
575
  },
485
576
  async renewMany(requests) {
486
577
  if (requests.length === 0) return [];
@@ -529,13 +620,13 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
529
620
  renewed[position]!.changes === 1
530
621
  ? ({ status: "renewed" } as const)
531
622
  : stale(await holderOf(tx, requests[i]!.lease.key));
532
- }, fenced);
623
+ }, renewal);
533
624
  return results as LeaseRenewResult[];
534
625
  },
535
626
  async release(lease) {
536
627
  const bad = validLease(lease);
537
628
  if (bad !== undefined) return bad;
538
- return database.transaction(async (tx) => {
629
+ const releasing = database.transaction(async (tx) => {
539
630
  const { changes } = await tx.run(
540
631
  `UPDATE ${table} SET holder_id = NULL, fencing_token = NULL, subject_json = NULL, renewed_at = NULL
541
632
  WHERE ${owned}`,
@@ -543,10 +634,12 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
543
634
  );
544
635
  return changes === 1 ? ({ status: "released" } as const) : stale(await holderOf(tx, lease.key));
545
636
  }, fenced);
637
+ return holding(releasing);
546
638
  },
547
639
  async read(key) {
548
640
  const bad = invalidKey(key);
549
641
  if (bad !== undefined) return bad;
642
+ if (unfinished.size > 0) await Promise.all(unfinished);
550
643
  const row = await reader.get<StateRow>(
551
644
  `SELECT kind, key, holder_id, fencing_token, subject_json, ${leaseAge} AS age_ms FROM ${table}
552
645
  WHERE kind = ? AND key = ? AND holder_id IS NOT NULL`,
@@ -566,6 +659,7 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
566
659
  const target = named.toWellFormed();
567
660
  const trimmed = target.trim();
568
661
  const head = /^[0-9a-f]{8}$/i.test(trimmed) ? trimmed.toLowerCase() : null;
662
+ if (unfinished.size > 0) await Promise.all(unfinished);
569
663
  const rows = await reader.all<StateRow>(
570
664
  liveAddressed,
571
665
  target,
@@ -582,15 +676,17 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
582
676
  }
583
677
  : {}),
584
678
  async listAged(kind, minAgeMs) {
679
+ if (unfinished.size > 0) await Promise.all(unfinished);
585
680
  const rows = await reader.all<StateRow>(leasesByAge(dialect, table, ">="), kind, minAgeMs);
586
681
  return rows.map(stateFromRow);
587
682
  },
588
683
  async retireHolder(holderId) {
589
- const { changes } = await database.run(
684
+ const retiring = database.run(
590
685
  `UPDATE ${table} SET holder_id = NULL, fencing_token = NULL, subject_json = NULL, renewed_at = NULL
591
686
  WHERE holder_id = ?`,
592
687
  holderId,
593
688
  );
689
+ const { changes } = await holding(retiring);
594
690
  return changes;
595
691
  },
596
692
  };