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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (447) hide show
  1. package/CHANGELOG.md +150 -0
  2. package/README.md +5 -8
  3. package/dist/_shared/dist-KOELCESV.js +2 -2
  4. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  5. package/dist/_shared/lib-4PES5P4V.js +2 -2
  6. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +6 -6
  7. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +5 -5
  8. package/dist/_shared/mode-shared-2QJSCUM6.js +6 -6
  9. package/dist/_shared/p0-cli-BB45ZQY6.js +46 -67
  10. package/dist/_shared/p0-cli-BB45ZQY6.js.map +1 -1
  11. package/dist/_shared/p1a-prewarm-XIU57JHF.js +7 -8
  12. package/dist/_shared/p1a-prewarm-XIU57JHF.js.map +1 -1
  13. package/dist/_shared/{p1b-elig-ENCUPKKJ.js → p1b-elig-TVB5CBLL.js} +36 -8
  14. package/dist/_shared/p1b-elig-TVB5CBLL.js.map +1 -0
  15. package/dist/_shared/p2-shell-main-B2WIALFD.js +6 -3
  16. package/dist/_shared/p2-shell-main-B2WIALFD.js.map +1 -1
  17. package/dist/_shared/runtime-O4KCSG4C.js +3 -3
  18. package/dist/_shared/{sdk-IQMULKFU.js → sdk-B5LEWGGI.js} +1218 -657
  19. package/dist/_shared/sdk-B5LEWGGI.js.map +1 -0
  20. package/dist/_shared/session-data-AHTU7IS6.js +2 -2
  21. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  22. package/dist/_shared/{startup-0-0-3IXNMFM2.js → startup-0-0-XJJDOIEC.js} +50 -48
  23. package/dist/_shared/startup-0-0-XJJDOIEC.js.map +1 -0
  24. package/dist/_shared/{startup-0-1-7T2IAE7J.js → startup-0-1-M6OWAYHH.js} +540 -136
  25. package/dist/_shared/startup-0-1-M6OWAYHH.js.map +1 -0
  26. package/dist/_shared/startup-0-2-5QHPCEON.js +47 -48
  27. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -1
  28. package/dist/_shared/startup-0-3-4ZYBYQNM.js +5 -5
  29. package/dist/_shared/startup-0-4-ZMJV547D.js +12 -7
  30. package/dist/_shared/startup-0-4-ZMJV547D.js.map +1 -1
  31. package/dist/_shared/startup-0-5-YDW47QX6.js +7 -7
  32. package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -1
  33. package/dist/_shared/startup-10-0-TDQNBDDL.js +6 -6
  34. package/dist/_shared/startup-12-0-55AAXBJZ.js +2 -2
  35. package/dist/_shared/startup-14-0-MLX36RBG.js +4 -5
  36. package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
  37. package/dist/_shared/startup-15-0-YUKGAC63.js +4 -4
  38. package/dist/_shared/startup-15-1-4S7FLMNG.js +19 -27
  39. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  40. package/dist/_shared/startup-8-0-34CBHPZH.js +2144 -249
  41. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  42. package/dist/_shared/{startup-8-1-X32CYSXB.js → startup-8-1-LZFXSD3Z.js} +98 -1184
  43. package/dist/_shared/startup-8-1-LZFXSD3Z.js.map +1 -0
  44. package/dist/_shared/storage-command-7MGXLJGZ.js +188 -37
  45. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  46. package/dist/_shared/storage-status-K7PX2RXA.js +557 -0
  47. package/dist/_shared/storage-status-K7PX2RXA.js.map +1 -0
  48. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  49. package/dist/_shared/team-DOQKICG2.js +376 -0
  50. package/dist/_shared/team-DOQKICG2.js.map +1 -0
  51. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  52. package/dist/builtin/intercom/CHANGELOG.md +42 -0
  53. package/dist/builtin/intercom/README.md +2 -2
  54. package/dist/builtin/intercom/broker/broker.bundle.mjs +1917 -381
  55. package/dist/builtin/intercom/broker/client.ts +8 -0
  56. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +324 -68
  57. package/dist/builtin/intercom/broker/multinode-router.ts +256 -39
  58. package/dist/builtin/intercom/broker/multinode-state-store.ts +71 -5
  59. package/dist/builtin/intercom/broker/open-broker-state.ts +14 -0
  60. package/dist/builtin/intercom/broker/send-order-gate.ts +5 -2
  61. package/dist/builtin/intercom/broker/sql-add-column.ts +50 -5
  62. package/dist/builtin/intercom/broker/sql-ended-child-queue-store.ts +3 -2
  63. package/dist/builtin/intercom/broker/sql-held-send-store.ts +2 -2
  64. package/dist/builtin/intercom/broker/sql-known-session-store.ts +43 -19
  65. package/dist/builtin/intercom/broker/sql-lease-store.ts +473 -121
  66. package/dist/builtin/intercom/broker/sql-outbox-store.ts +821 -79
  67. package/dist/builtin/intercom/broker/sql-pending-ask-store.ts +8 -5
  68. package/dist/builtin/intercom/broker/sql-released-ask-store.ts +12 -5
  69. package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +256 -8
  70. package/dist/builtin/intercom/broker/sql-retention.ts +150 -0
  71. package/dist/builtin/intercom/broker/sql-schema.ts +175 -24
  72. package/dist/builtin/intercom/broker/sql-sent-message-authority.ts +74 -19
  73. package/dist/builtin/intercom/broker/wake-up-bus.ts +6 -0
  74. package/dist/builtin/intercom/index.bundle.mjs +14 -4
  75. package/dist/builtin/intercom/package.json +1 -1
  76. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  77. package/dist/builtin/mcp/package.json +1 -1
  78. package/dist/builtin/subagents/CHANGELOG.md +6 -0
  79. package/dist/builtin/subagents/package.json +1 -1
  80. package/dist/builtin/subagents/skills/skill-creator/eval-viewer/generate_review.py +8 -1
  81. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  82. package/dist/builtin/web-access/index.bundle.mjs +2 -10
  83. package/dist/builtin/web-access/package.json +1 -1
  84. package/dist/bun/bundled-sqlite.js +41 -0
  85. package/dist/bun/bundled-sqlite.js.map +1 -0
  86. package/dist/cli/args.js +2 -2
  87. package/dist/cli/auth-cli.code.js +4 -4
  88. package/dist/cli/auth-cli.impl.js +3 -3
  89. package/dist/cli/auth-cli.js +3 -3
  90. package/dist/cli/blueprint-command.code.js +3 -3
  91. package/dist/cli/blueprint-command.impl.js +3 -3
  92. package/dist/cli/blueprint-command.js +3 -3
  93. package/dist/cli/intercom-command.code.js +3 -3
  94. package/dist/cli/intercom-command.code.js.map +1 -1
  95. package/dist/cli/intercom-command.impl.js +3 -3
  96. package/dist/cli/intercom-command.js +3 -3
  97. package/dist/cli/list-models.code.js +2 -2
  98. package/dist/cli/list-models.impl.js +3 -3
  99. package/dist/cli/list-models.js +3 -3
  100. package/dist/cli/session-picker.code.js +1 -1
  101. package/dist/cli/session-picker.impl.js +3 -3
  102. package/dist/cli/session-picker.js +3 -3
  103. package/dist/cli/startup-ui.code.js +1 -1
  104. package/dist/cli/startup-ui.impl.js +3 -3
  105. package/dist/cli/startup-ui.js +3 -3
  106. package/dist/cli/storage-command.impl.js +3 -3
  107. package/dist/cli/storage-command.js +3 -3
  108. package/dist/cli/storage-search-session.code.js +3 -3
  109. package/dist/cli/storage-search-session.impl.js +3 -3
  110. package/dist/cli/storage-search-session.js +3 -3
  111. package/dist/cli/team-command.code.js +19 -113
  112. package/dist/cli/team-command.code.js.map +1 -1
  113. package/dist/cli/team-command.impl.js +3 -3
  114. package/dist/cli/team-command.js +3 -3
  115. package/dist/cli.js +5 -18
  116. package/dist/cli.js.map +1 -1
  117. package/dist/core/agent-rehydrate-errors.d.ts +4 -9
  118. package/dist/core/compaction/compactor.d.ts +3 -3
  119. package/dist/core/debug.code.js +1 -1
  120. package/dist/core/debug.impl.js +3 -3
  121. package/dist/core/debug.js +3 -3
  122. package/dist/core/export-html/card-projection.impl.js +3 -3
  123. package/dist/core/export-html/card-projection.js +3 -3
  124. package/dist/core/export-html/index.code.js +4 -4
  125. package/dist/core/export-html/index.code.js.map +1 -1
  126. package/dist/core/export-html/index.impl.js +3 -3
  127. package/dist/core/export-html/index.js +3 -3
  128. package/dist/core/export-html/json-spans.impl.js +3 -3
  129. package/dist/core/export-html/json-spans.js +3 -3
  130. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  131. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  132. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  133. package/dist/core/export-html/tool-renderer.js +3 -3
  134. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  135. package/dist/core/extensions/jiti-loader.js +3 -3
  136. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  137. package/dist/core/extensions/jiti-static-loader.js +3 -3
  138. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  139. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  140. package/dist/core/extensions/loader-host-modules.js +3 -3
  141. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  142. package/dist/core/extensions/runner-context.js +2 -2
  143. package/dist/core/intercom-broker-control-host.code.js +2 -2
  144. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  145. package/dist/core/intercom-broker-control-host.js +3 -3
  146. package/dist/core/intercom-broker-control.code.js +3 -3
  147. package/dist/core/intercom-broker-control.impl.js +3 -3
  148. package/dist/core/intercom-broker-control.js +3 -3
  149. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  150. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  151. package/dist/core/package-manager-storage-adapters.js +3 -3
  152. package/dist/core/process-start-token.d.ts +12 -3
  153. package/dist/core/process-tree-containment.d.ts +16 -0
  154. package/dist/core/sdk-types.d.ts +1 -2
  155. package/dist/core/sdk-types.js.map +1 -1
  156. package/dist/core/sdk.code.js +3 -3
  157. package/dist/core/sdk.impl.js +3 -3
  158. package/dist/core/sdk.js +3 -3
  159. package/dist/core/session-manager-core.js +5 -5
  160. package/dist/core/session-manager-list.impl.js +3 -3
  161. package/dist/core/session-manager-list.js +3 -3
  162. package/dist/core/session-manager.code.js +1 -1
  163. package/dist/core/session-manager.impl.js +3 -3
  164. package/dist/core/session-manager.js +3 -3
  165. package/dist/core/session-storage.code.js +1 -1
  166. package/dist/core/session-storage.impl.js +3 -3
  167. package/dist/core/session-storage.js +3 -3
  168. package/dist/core/settings-schema.d.ts +0 -3
  169. package/dist/core/storage/added-exports-0-10-11.js +19 -0
  170. package/dist/core/storage/added-exports-0-10-11.js.map +1 -0
  171. package/dist/core/storage/creation-time.js +105 -0
  172. package/dist/core/storage/creation-time.js.map +1 -0
  173. package/dist/core/storage/database.d.ts +25 -5
  174. package/dist/core/storage/database.js.map +1 -1
  175. package/dist/core/storage/dialect.d.ts +1 -1
  176. package/dist/core/storage/dialect.js +1 -1
  177. package/dist/core/storage/dialect.js.map +1 -1
  178. package/dist/core/storage/errors.d.ts +13 -13
  179. package/dist/core/storage/errors.js +10 -16
  180. package/dist/core/storage/errors.js.map +1 -1
  181. package/dist/core/storage/fenced-paths.d.ts +18 -6
  182. package/dist/core/storage/fenced-paths.js +18 -6
  183. package/dist/core/storage/fenced-paths.js.map +1 -1
  184. package/dist/core/storage/file-identity.d.ts +2 -0
  185. package/dist/core/storage/file-identity.js +24 -8
  186. package/dist/core/storage/file-identity.js.map +1 -1
  187. package/dist/core/storage/index.d.ts +3 -2
  188. package/dist/core/storage/index.js +5 -3
  189. package/dist/core/storage/index.js.map +1 -1
  190. package/dist/core/storage/libsql-removed.d.ts +71 -0
  191. package/dist/core/storage/libsql-removed.js +123 -0
  192. package/dist/core/storage/libsql-removed.js.map +1 -0
  193. package/dist/core/storage/migrations.d.ts +78 -14
  194. package/dist/core/storage/migrations.js +375 -49
  195. package/dist/core/storage/migrations.js.map +1 -1
  196. package/dist/core/storage/node-sqlite-file-gate.js +0 -15
  197. package/dist/core/storage/node-sqlite-file-gate.js.map +1 -1
  198. package/dist/core/storage/node-sqlite-thread.js +215 -30
  199. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  200. package/dist/core/storage/node-sqlite.js +484 -72
  201. package/dist/core/storage/node-sqlite.js.map +1 -1
  202. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  203. package/dist/core/storage/offline-snapshot-file.js +3 -3
  204. package/dist/core/storage/prefix.d.ts +1 -1
  205. package/dist/core/storage/prefix.js +9 -2
  206. package/dist/core/storage/prefix.js.map +1 -1
  207. package/dist/core/storage/process-selection.d.ts +5 -5
  208. package/dist/core/storage/provider.js +2 -2
  209. package/dist/core/storage/schema-catalog.d.ts +76 -15
  210. package/dist/core/storage/schema-catalog.js +359 -68
  211. package/dist/core/storage/schema-catalog.js.map +1 -1
  212. package/dist/core/storage/selection.d.ts +7 -82
  213. package/dist/core/storage/selection.js +20 -235
  214. package/dist/core/storage/selection.js.map +1 -1
  215. package/dist/core/storage/session/branch-fork-source.code.js +2 -2
  216. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  217. package/dist/core/storage/session/branch-fork-source.js +3 -3
  218. package/dist/core/storage/session/card-view.impl.js +3 -3
  219. package/dist/core/storage/session/card-view.js +3 -3
  220. package/dist/core/storage/session/child-reader.code.js +3 -3
  221. package/dist/core/storage/session/child-reader.impl.js +3 -3
  222. package/dist/core/storage/session/child-reader.js +3 -3
  223. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  224. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  225. package/dist/core/storage/session/expanded-child-details.code.js +2 -2
  226. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  227. package/dist/core/storage/session/expanded-child-details.js +3 -3
  228. package/dist/core/storage/session/fork-detach.d.ts +11 -1
  229. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  230. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  231. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  232. package/dist/core/storage/session/fork-row-index.js +3 -3
  233. package/dist/core/storage/session/fork-staging.code.js +4 -7
  234. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  235. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  236. package/dist/core/storage/session/fork-staging.js +3 -3
  237. package/dist/core/storage/session/fork-sweep.js +31 -7
  238. package/dist/core/storage/session/fork-sweep.js.map +1 -1
  239. package/dist/core/storage/session/fork-window.code.js +3 -3
  240. package/dist/core/storage/session/fork-window.impl.js +3 -3
  241. package/dist/core/storage/session/fork-window.js +3 -3
  242. package/dist/core/storage/session/history-pages.impl.js +3 -3
  243. package/dist/core/storage/session/history-pages.js +3 -3
  244. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  245. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  246. package/dist/core/storage/session/jsonl-session-lock.d.ts +100 -0
  247. package/dist/core/storage/session/jsonl-session-store.d.ts +46 -24
  248. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  249. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  250. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  251. package/dist/core/storage/session/memory-session-store.js +3 -3
  252. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  253. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  254. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  255. package/dist/core/storage/session/released-history-files.code.js +9 -9
  256. package/dist/core/storage/session/released-history-files.code.js.map +1 -1
  257. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  258. package/dist/core/storage/session/released-history-files.js +3 -3
  259. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  260. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  261. package/dist/core/storage/session/session-resume.impl.js +3 -3
  262. package/dist/core/storage/session/session-resume.js +3 -3
  263. package/dist/core/storage/session/session-search-index.d.ts +52 -5
  264. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  265. package/dist/core/storage/session/snapshot-cut.js +3 -3
  266. package/dist/core/storage/session/snapshot-history.code.js +3 -3
  267. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  268. package/dist/core/storage/session/snapshot-history.js +3 -3
  269. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  270. package/dist/core/storage/session/sql-session-store.d.ts +99 -18
  271. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  272. package/dist/core/storage/session/sql-session-store.js +3 -3
  273. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  274. package/dist/core/storage/session/tree-outline.js +3 -3
  275. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  276. package/dist/core/storage/session/tree-presentation.js +3 -3
  277. package/dist/core/storage/sqlite-facade.d.ts +12 -1
  278. package/dist/core/storage/sqlite-facade.js +310 -33
  279. package/dist/core/storage/sqlite-facade.js.map +1 -1
  280. package/dist/core/storage/sqlite-open-batch.js +10 -0
  281. package/dist/core/storage/sqlite-open-batch.js.map +1 -0
  282. package/dist/core/storage/storage-status.code.js +1 -1
  283. package/dist/core/storage/storage-status.impl.js +3 -3
  284. package/dist/core/storage/storage-status.js +3 -3
  285. package/dist/core/storage/team.code.js +1 -1
  286. package/dist/core/storage/team.d.ts +26 -115
  287. package/dist/core/storage/team.impl.js +3 -3
  288. package/dist/core/storage/team.js +3 -3
  289. package/dist/core/structured-output/index.code.js +1 -1
  290. package/dist/core/structured-output/index.impl.js +3 -3
  291. package/dist/core/structured-output/index.js +3 -3
  292. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  293. package/dist/core/tasks/task-completion-entry.js +3 -3
  294. package/dist/core/tasks/task-file-history.code.js +3 -3
  295. package/dist/core/tasks/task-file-history.impl.js +3 -3
  296. package/dist/core/tasks/task-file-history.js +3 -3
  297. package/dist/core/tasks/task-reference-archive.code.js +4 -4
  298. package/dist/core/tasks/task-reference-archive.js +3 -3
  299. package/dist/core/tasks/task-reference-identity.js +3 -3
  300. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  301. package/dist/core/tasks/task-reference-stream.js +3 -3
  302. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  303. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  304. package/dist/core/tasks/task-view-source.code.js +1 -1
  305. package/dist/core/tasks/task-view-source.impl.js +3 -3
  306. package/dist/core/tasks/task-view-source.js +3 -3
  307. package/dist/core/tools/history-tasks.d.ts +3 -2
  308. package/dist/core/tools/read-url.code.js +4 -4
  309. package/dist/core/tools/read-url.impl.js +3 -3
  310. package/dist/core/tools/read-url.js +3 -3
  311. package/dist/core/worktree-snapshot/blob-store.d.ts +44 -5
  312. package/dist/core/worktree-snapshot/blob-store.js +553 -30
  313. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  314. package/dist/core/worktree-snapshot/errors.code.js +2 -2
  315. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  316. package/dist/core/worktree-snapshot/errors.js +3 -3
  317. package/dist/core/worktree-snapshot/fork-blob-guard.js +81 -0
  318. package/dist/core/worktree-snapshot/fork-blob-guard.js.map +1 -0
  319. package/dist/core/worktree-snapshot/fork-snapshot-index.js +208 -50
  320. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -1
  321. package/dist/core/worktree-snapshot/session-index-reset.code.js +4 -0
  322. package/dist/core/worktree-snapshot/session-index-reset.code.js.map +1 -1
  323. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  324. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  325. package/dist/extensions/codemode/execute.code.js +1 -1
  326. package/dist/extensions/codemode/execute.impl.js +3 -3
  327. package/dist/extensions/codemode/execute.js +3 -3
  328. package/dist/extensions/codemode/renderer.code.js +2 -2
  329. package/dist/extensions/codemode/renderer.impl.js +3 -3
  330. package/dist/extensions/codemode/renderer.js +3 -3
  331. package/dist/extensions/mcp/cli.code.js +3 -3
  332. package/dist/extensions/mcp/cli.impl.js +3 -3
  333. package/dist/extensions/mcp/cli.js +3 -3
  334. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  335. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  336. package/dist/extensions/mcp/cli.lazy.js +3 -3
  337. package/dist/extensions/mcp/runtime.code.js +1 -1
  338. package/dist/extensions/mcp/runtime.impl.js +3 -3
  339. package/dist/extensions/mcp/runtime.js +3 -3
  340. package/dist/index.d.ts +3 -1
  341. package/dist/index.js +5 -5
  342. package/dist/main-first-time-setup.code.js +1 -1
  343. package/dist/main-first-time-setup.impl.js +3 -3
  344. package/dist/main-first-time-setup.js +3 -3
  345. package/dist/main.js +1 -1
  346. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  347. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  348. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  349. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  350. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  351. package/dist/modes/interactive/startup-shell-eligibility.js +1 -1
  352. package/dist/modes/interactive-engine/engine-prewarm.d.ts +1 -1
  353. package/dist/modes/print-mode.js +1 -1
  354. package/dist/package-manager-cli.code.js +6 -6
  355. package/dist/package-manager-cli.impl.js +3 -3
  356. package/dist/package-manager-cli.js +3 -3
  357. package/dist/rpc-entry.js +1 -1
  358. package/dist/startup-files.json +1 -1
  359. package/dist/startup-stages/10.js +1 -1
  360. package/dist/startup-stages/11.js +1 -1
  361. package/dist/startup-stages/12.js +1 -1
  362. package/dist/startup-stages/2.js +2 -4
  363. package/dist/startup-stages/3.js +1 -3
  364. package/dist/startup-stages/4.js +1 -2
  365. package/dist/startup-stages/5.js +1 -1
  366. package/dist/startup-stages/6.js +5 -7
  367. package/dist/startup-stages/7.js +3 -10
  368. package/dist/startup-stages/8.js +7 -2
  369. package/dist/startup-stages/9.js +1 -7
  370. package/dist/startup-stages/stages.json +1 -1
  371. package/dist/utils/compile-cache-deferral.js +8 -13
  372. package/dist/utils/compile-cache-deferral.js.map +1 -1
  373. package/dist/utils/compile-cache-warmup-host.js +3 -4
  374. package/dist/utils/compile-cache-warmup-host.js.map +1 -1
  375. package/dist/utils/compile-cache.js +12 -100
  376. package/dist/utils/compile-cache.js.map +1 -1
  377. package/dist/utils/startup-database-spare.code.js +2 -2
  378. package/dist/utils/startup-database-spare.impl.js +3 -3
  379. package/dist/utils/startup-database-spare.js +3 -3
  380. package/dist/utils/tools-manager.code.js +1 -1
  381. package/dist/utils/tools-manager.impl.js +3 -3
  382. package/dist/utils/tools-manager.js +3 -3
  383. package/dist/utils/worker-threads.js +2 -15
  384. package/dist/utils/worker-threads.js.map +1 -1
  385. package/docs/build.md +3 -3
  386. package/docs/changelog.mdx +1470 -69
  387. package/docs/compaction/reference.md +5 -5
  388. package/docs/compaction.md +7 -9
  389. package/docs/containerization.md +2 -2
  390. package/docs/custom-provider/api-reference.md +1 -1
  391. package/docs/docs.json +37 -10
  392. package/docs/environment-variables.md +0 -2
  393. package/docs/extensions/api-reference.md +4 -4
  394. package/docs/getting-started/installation.md +3 -0
  395. package/docs/guides/configuration.md +1 -1
  396. package/docs/guides/non-interactive.md +1 -1
  397. package/docs/guides/resume-on-any-machine.md +14 -22
  398. package/docs/guides/team-setup.md +56 -83
  399. package/docs/guides.md +2 -4
  400. package/docs/herdr.md +1 -1
  401. package/docs/index.md +1 -1
  402. package/docs/intercom/operations.md +26 -21
  403. package/docs/intercom/reference.md +2 -2
  404. package/docs/intercom.md +1 -1
  405. package/docs/libraries/storage-postgres.md +9 -9
  406. package/docs/libraries.md +2 -3
  407. package/docs/models-configuration.md +2 -2
  408. package/docs/models.md +2 -3
  409. package/docs/packages/authoring.md +7 -7
  410. package/docs/packages.md +1 -1
  411. package/docs/programmatic.md +2 -2
  412. package/docs/quickstart.md +1 -1
  413. package/docs/reference/cli.md +6 -11
  414. package/docs/reference.md +2 -2
  415. package/docs/rpc/extension-ui.md +2 -2
  416. package/docs/sdk/reference.md +5 -4
  417. package/docs/sdk/storage.md +8 -92
  418. package/docs/sdk/structured-decisions.md +1 -1
  419. package/docs/sdk/web-server.md +3 -3
  420. package/docs/sdk.md +14 -4
  421. package/docs/security.md +1 -1
  422. package/docs/session-format.md +5 -5
  423. package/docs/sessions.md +29 -49
  424. package/docs/settings.md +7 -8
  425. package/docs/storage/custom-adapters.md +255 -0
  426. package/docs/storage/jsonl.md +117 -0
  427. package/docs/{guides/postgres-pgbouncer.md → storage/postgres/pgbouncer.md} +66 -68
  428. package/docs/storage/postgres/tuning.md +337 -0
  429. package/docs/storage/postgres.md +556 -0
  430. package/docs/storage/sqlite.md +99 -0
  431. package/docs/storage.md +326 -990
  432. package/docs/subagents/authoring.md +1 -1
  433. package/docs/subagents.md +2 -2
  434. package/docs/tools.md +1 -1
  435. package/docs/worktree-snapshots.md +2 -2
  436. package/package.json +9 -9
  437. package/schemas/models.schema.json +2 -2
  438. package/schemas/settings.schema.json +0 -14
  439. package/dist/_shared/p1b-elig-ENCUPKKJ.js.map +0 -1
  440. package/dist/_shared/sdk-IQMULKFU.js.map +0 -1
  441. package/dist/_shared/startup-0-0-3IXNMFM2.js.map +0 -1
  442. package/dist/_shared/startup-0-1-7T2IAE7J.js.map +0 -1
  443. package/dist/_shared/startup-8-1-X32CYSXB.js.map +0 -1
  444. package/dist/core/intercom-broker-control.d.ts +0 -129
  445. package/dist/startup-stages/13.js +0 -1
  446. package/docs/guides/postgres-tuning.md +0 -311
  447. package/docs/libraries/storage-libsql.md +0 -97
@@ -5,7 +5,7 @@ import {
5
5
  type SqliteDatabase,
6
6
  type SqliteExecutor,
7
7
  type SqliteRow,
8
- type SqliteRunResult,
8
+ type SqliteStatement,
9
9
  type StorageDialect,
10
10
  storageMigrationTable,
11
11
  validateStoragePrefix,
@@ -25,8 +25,11 @@ import type {
25
25
  import { isMissingPrivilege } from "./sql-add-column.js";
26
26
  import { recipientTransaction } from "./sql-outbox-store.js";
27
27
  import {
28
+ brokerSchemaCurrent,
28
29
  ensureBrokerSchema,
29
30
  openCatalogOf,
31
+ queueBrokerSqliteSetup,
32
+ RETRY_UNAPPLIED,
30
33
  stampBrokerSchemaAtOpenEnd,
31
34
  withBrokerSchemaCatalog,
32
35
  } from "./sql-schema.js";
@@ -46,6 +49,18 @@ const fillfactorApi: Partial<Pick<typeof storage, "ensureTableFillfactor">> = st
46
49
  */
47
50
  const LEASE_FILLFACTOR = 80;
48
51
 
52
+ /**
53
+ * How long a lease write waits for a row lock on PostgreSQL before it fails and runs again. Five runs that each wait
54
+ * 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
55
+ * within the lease's 30 s stale bound (`BROKER_LEASE_STALE_AFTER_MS`).
56
+ */
57
+ const LEASE_LOCK_WAIT_MS = 2_000;
58
+
59
+ /** The statement of a presence acquisition's wait for the sends to its recipient under way: it only takes the lock. */
60
+ const SENDS_PASSED = { sql: "SELECT 1 AS passed", params: [] };
61
+ /** The setting a PostgreSQL batched lease renewal sets when any lease missed, so its follow-up read runs. */
62
+ const LEASE_RENEW_MISSES = "atomic.intercom_lease_renew_misses";
63
+
49
64
  /**
50
65
  * The kind of the row whose `last_token` counts acquisitions on PostgreSQL where the order sequence is missing: see
51
66
  * `nextOrder`.
@@ -55,29 +70,46 @@ const ACQUISITION_ORDER_KIND = "acquisition-order";
55
70
  /**
56
71
  * Creates the sequence first acquisitions take their order from on PostgreSQL, `<table>_order`, once per database
57
72
  * (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).
73
+ * included. Where the ledger records the step but the catalog the open read has no sequence, someone dropped it: it is
74
+ * created again, under the schema lock, if it is still missing. Where this role may not create it, as a runtime role
75
+ * before `atomic storage migrate`, acquisitions take their order from the counter row instead (#6560).
60
76
  */
61
- async function ensureOrderSequence(
62
- database: SqliteDatabase,
63
- prefix: string | undefined,
64
- table: string,
65
- ): Promise<boolean> {
77
+ async function ensureOrderSequence(database: SqliteDatabase, prefix: string | undefined, table: string): Promise<void> {
78
+ const sequence = `${table}_order`;
79
+ const create = async (tx: SqliteExecutor) => {
80
+ await tx.exec(`CREATE SEQUENCE IF NOT EXISTS ${sequence} AS BIGINT`);
81
+ await tx.get(
82
+ `SELECT setval('${sequence}', GREATEST(
83
+ (SELECT COALESCE(MAX(first_acquired_order), 0) FROM ${table}),
84
+ (SELECT COALESCE(MAX(last_token), 0) FROM ${table} WHERE kind = '${ACQUISITION_ORDER_KIND}'),
85
+ 1
86
+ ))`,
87
+ );
88
+ };
89
+ const catalog = await openCatalogOf(database);
90
+ const dropped =
91
+ catalog !== undefined &&
92
+ catalog.recordedVersion("schema:intercom-lease-order") >= 1 &&
93
+ !catalog.hasObject(sequence);
66
94
  try {
67
- await ensureBrokerSchema(database, prefix, "lease-order", async (tx) => {
68
- await tx.exec(`CREATE SEQUENCE IF NOT EXISTS ${table}_order AS BIGINT`);
95
+ if (!dropped) {
96
+ await ensureBrokerSchema(database, prefix, "lease-order", create);
97
+ return;
98
+ }
99
+ await database.transaction(async (tx) => {
100
+ // The lock `ensureStorageSchema` takes, so processes that find it dropped create it once.
69
101
  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
- ))`,
102
+ "SELECT pg_advisory_xact_lock(hashtextextended(?, 0)) AS locked",
103
+ `${storageMigrationTable(prefix)}:schema`,
75
104
  );
105
+ const found = await tx.get<SqliteRow & { missing: boolean | number }>(
106
+ "SELECT to_regclass(?) IS NULL AS missing",
107
+ sequence,
108
+ );
109
+ if (found?.missing === true || Number(found?.missing) === 1) await create(tx);
76
110
  });
77
- return true;
78
111
  } catch (error) {
79
- if (isMissingPrivilege(error)) return false;
80
- throw error;
112
+ if (!isMissingPrivilege(error)) throw error;
81
113
  }
82
114
  }
83
115
 
@@ -186,21 +218,41 @@ async function ensureAddressColumns(database: SqliteDatabase, prefix: string | u
186
218
  );
187
219
  await tx.exec(indexes);
188
220
  };
189
- // On SQLite, which records no step, the catalog an open read finds the columns and their indexes, so a current
190
- // table costs no write transaction (#6560); the open's end stamps it, so the next open answers from the stamp.
191
- const catalog = dialect.versionedMigrations ? undefined : await openCatalogOf(database);
192
- if (
193
- catalog?.sqliteObjectType !== undefined &&
194
- ADDRESS_COLUMNS.every(
195
- (column) => catalog.hasColumn(table, column) && catalog.sqliteObjectType?.(`${table}_${column}`) === "index",
196
- )
197
- ) {
198
- await stampBrokerSchemaAtOpenEnd(database, prefix, "lease-addresses", setup, (found) =>
221
+ // On SQLite, which records no step, the catalog or stamp an open read decides: a current table costs no write
222
+ // transaction (#6560), and missing columns/indexes queue into the open's single write transaction (#6709).
223
+ if (!dialect.versionedMigrations) {
224
+ if (await brokerSchemaCurrent(database, prefix, "lease-addresses")) return true;
225
+ const verify = (found: storage.StorageSchemaCatalog) =>
199
226
  ADDRESS_COLUMNS.every(
200
227
  (column) => found.hasColumn(table, column) && found.sqliteObjectType?.(`${table}_${column}`) === "index",
201
- ),
202
- );
203
- return true;
228
+ );
229
+ const schema = { ledger: storageMigrationTable(prefix), domain: "intercom-lease-addresses", revision: 1 };
230
+ if (
231
+ queueBrokerSqliteSetup(database, prefix ?? "", {
232
+ stamp: schema,
233
+ verify,
234
+ run(ctx) {
235
+ if (ctx.catalog !== undefined && verify(ctx.catalog)) return;
236
+ for (const column of ADDRESS_COLUMNS) {
237
+ if (ctx.hasColumn(table, column)) continue;
238
+ ctx.enqueue(
239
+ `ALTER TABLE ${table} ADD COLUMN ${column} TEXT GENERATED ALWAYS AS (${expressions[column]}) VIRTUAL`,
240
+ );
241
+ ctx.noteColumnAdded(table, column);
242
+ }
243
+ for (const column of ADDRESS_COLUMNS) {
244
+ if (ctx.catalog?.sqliteObjectType?.(`${table}_${column}`) === "index") continue;
245
+ ctx.enqueue(`CREATE INDEX IF NOT EXISTS ${table}_${column} ON ${table}(${column})`);
246
+ }
247
+ },
248
+ })
249
+ )
250
+ return true;
251
+ const catalog = await openCatalogOf(database);
252
+ if (catalog?.sqliteObjectType !== undefined && verify(catalog)) {
253
+ await stampBrokerSchemaAtOpenEnd(database, prefix, "lease-addresses", setup, verify);
254
+ return true;
255
+ }
204
256
  }
205
257
  try {
206
258
  await ensureBrokerSchema(database, prefix, "lease-addresses", setup);
@@ -240,6 +292,20 @@ type HolderRow = SqliteRow & {
240
292
  age_ms: number | bigint | null;
241
293
  };
242
294
 
295
+ type RenewedLeaseRow = SqliteRow & {
296
+ kind: string | null;
297
+ key: string | null;
298
+ holder_id: string | null;
299
+ fencing_token: number | bigint | null;
300
+ };
301
+
302
+ type MissedHolderRow = SqliteRow & {
303
+ kind: string;
304
+ key: string;
305
+ holder_id: string | null;
306
+ fencing_token: number | bigint | null;
307
+ };
308
+
243
309
  type StateRow = SqliteRow & {
244
310
  kind: string;
245
311
  key: string;
@@ -254,22 +320,41 @@ const compare = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
254
320
  const invalid = (reason: StateStoreInvalidReason): InvalidStateInput => ({ status: "invalid", reason });
255
321
 
256
322
  function keyOf(subject: LeaseSubject): LeaseKey {
257
- return subject.kind === "broker"
258
- ? { kind: "broker", brokerId: subject.brokerId }
259
- : { kind: "presence", targetIdentity: subject.targetIdentity };
323
+ switch (subject.kind) {
324
+ case "broker":
325
+ return { kind: "broker", brokerId: subject.brokerId };
326
+ case "maintenance":
327
+ return { kind: "maintenance", task: subject.task };
328
+ default:
329
+ return { kind: "presence", targetIdentity: subject.targetIdentity };
330
+ }
260
331
  }
261
332
 
262
333
  function keyId(key: LeaseKey): string {
263
- return key.kind === "broker" ? key.brokerId : key.targetIdentity;
334
+ switch (key.kind) {
335
+ case "broker":
336
+ return key.brokerId;
337
+ case "maintenance":
338
+ return key.task;
339
+ default:
340
+ return key.targetIdentity;
341
+ }
264
342
  }
265
343
 
266
344
  function keyFor(kind: LeaseKind, id: string): LeaseKey {
267
- return kind === "broker" ? { kind, brokerId: id } : { kind, targetIdentity: id };
345
+ switch (kind) {
346
+ case "broker":
347
+ return { kind, brokerId: id };
348
+ case "maintenance":
349
+ return { kind, task: id };
350
+ default:
351
+ return { kind, targetIdentity: id };
352
+ }
268
353
  }
269
354
 
270
355
  function invalidKey(key: LeaseKey): InvalidStateInput | undefined {
271
356
  if (keyId(key).length > 0) return undefined;
272
- return invalid(key.kind === "broker" ? "empty-broker-id" : "empty-target-identity");
357
+ return invalid(key.kind === "broker" ? "empty-broker-id" : key.kind === "maintenance" ? "empty-task" : "empty-target-identity");
273
358
  }
274
359
 
275
360
  /**
@@ -290,7 +375,7 @@ function stateFromRow(row: StateRow): LeaseState {
290
375
  // A row an earlier broker wrote may hold half a surrogate pair: it reads as a stored one would.
291
376
  const subject: LeaseSubject = JSON.parse(row.subject_json, wellFormed);
292
377
  return {
293
- key: keyFor(row.kind === "broker" ? "broker" : "presence", row.key),
378
+ key: keyFor(row.kind === "broker" || row.kind === "maintenance" ? row.kind : "presence", row.key),
294
379
  holderId: row.holder_id,
295
380
  fencingToken: Number(row.fencing_token),
296
381
  subject,
@@ -340,8 +425,7 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
340
425
  )
341
426
  `;
342
427
  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));
428
+ if (dialect.name === "postgres") await ensureOrderSequence(database, options.prefix, table);
345
429
  const addressed = await ensureAddressColumns(database, options.prefix, table);
346
430
  await fillfactorApi.ensureTableFillfactor?.(database, {
347
431
  ledger: storageMigrationTable(options.prefix),
@@ -351,13 +435,15 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
351
435
  fillfactor: LEASE_FILLFACTOR,
352
436
  });
353
437
 
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
- );
360
- const stale = (row: HolderRow | undefined) =>
438
+ const holderStatement = (key: LeaseKey): SqliteStatement => ({
439
+ sql: `SELECT holder_id, fencing_token, last_token, ${leaseAge} AS age_ms FROM ${table} WHERE kind = ? AND key = ?`,
440
+ params: [key.kind, keyId(key)],
441
+ });
442
+ const holderOf = (executor: SqliteExecutor, key: LeaseKey) => {
443
+ const { sql, params } = holderStatement(key);
444
+ return executor.get<HolderRow>(sql, ...params);
445
+ };
446
+ const stale = (row: Pick<HolderRow, "holder_id" | "fencing_token"> | undefined) =>
361
447
  row?.holder_id === null || row?.holder_id === undefined
362
448
  ? ({ status: "stale" } as const)
363
449
  : ({ status: "stale", currentFencingToken: Number(row.fencing_token) } as const);
@@ -371,32 +457,68 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
371
457
  const rowAge = dialect.greatest("0", `${nowMs} - ${table}.renewed_at`);
372
458
  /**
373
459
  * 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")`.
460
+ * which a broker's renewals must not wait behind (#6560): see `fencedPath("intercom-lease")`. On PostgreSQL a write
461
+ * waits for a row lock at most `LEASE_LOCK_WAIT_MS`, then runs again (`RETRY_UNAPPLIED`): a renewal stuck behind
462
+ * the database's lock timeout, as long as the lease's whole life, would let the lease go stale however it ended.
463
+ */
464
+ const fenced = {
465
+ ...RETRY_UNAPPLIED,
466
+ ...(dialect.name === "postgres" ? { lockWaitMs: LEASE_LOCK_WAIT_MS } : {}),
467
+ concurrency: { kind: "fenced", audit: fencedPath("intercom-lease") },
468
+ } as const;
469
+ /**
470
+ * A renewal only moves `renewed_at` forward, and its holder renews again within the renewal interval, far inside the
471
+ * staleness limit: one lost in a crash of the database server leaves the lease a renewal older, still live, and no
472
+ * fencing token changes. A renewal that carries a subject writes all of it, and the next renewal writes it again. So
473
+ * its commit does not wait for the disk (PostgreSQL's `synchronous_commit = off`), which
474
+ * spares the server a log flush per broker and per session every interval. Acquisitions and releases stay durable.
375
475
  */
376
- const fenced = { concurrency: { kind: "fenced", audit: fencedPath("intercom-lease") } } as const;
476
+ const renewal = { ...fenced, relaxedDurability: true } as const;
377
477
  /**
378
478
  * The order of a key acquired for the first time. A serial database runs one acquisition at a time, so the
379
479
  * 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.
480
+ * next value of the order sequence, which no acquisition waits for (#6560). Where the sequence is missing, because
481
+ * `atomic storage migrate` has not created it yet and this role may not, or because someone dropped it, each takes
482
+ * the next value of a counter row instead, upserted by the statement itself, whose row lock orders them, and which
483
+ * never falls behind an order already taken; the counter's kind is no lease's, so no lease query reads it. Each
484
+ * statement looks the sequence up itself, so a store opened before the sequence existed takes it from then on, as
485
+ * one opened after does, and one opened before it was dropped takes the counter rather than fail: only acquisitions
486
+ * made while the sequence is created can share an order, which their keys then decide.
383
487
  */
384
488
  const largestOrder = `(SELECT COALESCE(MAX(first_acquired_order), 0) FROM ${table})`;
385
- const nextOrder = sequenced
386
- ? { with: "", value: `nextval('${orderSequence}')` }
387
- : dialect.name === "postgres"
489
+ const sequence = `to_regclass('${table}_order')`;
490
+ const nextOrder =
491
+ dialect.name === "postgres"
388
492
  ? {
389
493
  with: `WITH next_order AS (
390
494
  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
495
+ SELECT '${ACQUISITION_ORDER_KIND}', '', ${largestOrder} + 1, 0 WHERE ${sequence} IS NULL
496
+ ON CONFLICT(kind, key) DO UPDATE SET
497
+ last_token = GREATEST(${table}.last_token, excluded.last_token - 1) + 1
393
498
  RETURNING last_token
394
499
  ) `,
395
- value: "(SELECT last_token FROM next_order)",
500
+ value: `COALESCE(nextval(${sequence}), (SELECT last_token FROM next_order), ${largestOrder} + 1)`,
396
501
  }
397
502
  : { with: "", value: `${largestOrder} + 1` };
398
503
  /** Latency-bound reads, which must not queue behind this database's writes (#6560). */
399
504
  const reader = options.reader ?? database;
505
+ /**
506
+ * This store's acquisitions and releases, and retirements of a holder, started and not committed. The reads go
507
+ * through the reader, which no write of this store is queued on, so they first wait for these: a caller that starts
508
+ * one and then reads, without awaiting it, reads who holds the lease after it. With none unfinished they wait for
509
+ * nothing. Renewals are not among them: one only moves a held lease's age, which the renewal before it keeps within
510
+ * the bound every read applies, and they run every few seconds, so reads would often wait for one.
511
+ */
512
+ const unfinished = new Set<Promise<void>>();
513
+ const holding = <T>(write: Promise<T>): Promise<T> => {
514
+ const settled = write.then(
515
+ () => {},
516
+ () => {},
517
+ );
518
+ unfinished.add(settled);
519
+ void settled.then(() => unfinished.delete(settled));
520
+ return write;
521
+ };
400
522
  const clockAge = dialect.greatest("0", "(SELECT now FROM clock) - renewed_at");
401
523
  /**
402
524
  * `listLiveFor`'s read: each term is one indexed column's lookup, so SQLite takes the union of five index searches
@@ -410,6 +532,7 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
410
532
  AND holder_id IS NOT NULL AND ${clockAge} <= ? ORDER BY first_acquired_order, key`;
411
533
 
412
534
  const listLive = async (kind: LeaseKind, staleAfterMs: number): Promise<LeaseState[]> => {
535
+ if (unfinished.size > 0) await Promise.all(unfinished);
413
536
  const rows = await reader.all<StateRow>(liveLeases(dialect, table), kind, staleAfterMs);
414
537
  return rows.map(stateFromRow);
415
538
  };
@@ -426,12 +549,11 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
426
549
  // acquisition therefore waits, once it committed, for every send to that recipient under way, holding the
427
550
  // recipient's lock domain for an instant: the registration's first outbox scan, which follows, then finds
428
551
  // 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,
552
+ // One guarded statement takes the lease: a new key, or a row that is free, stale or already this holder's; a
553
+ // steal gets the key's next token, a re-acquisition keeps its own. Renewals run beside it, so the decision is
554
+ // never made on an earlier read (#6560).
555
+ const take: SqliteStatement = {
556
+ sql: `${nextOrder.with}INSERT INTO ${table}(kind, key, holder_id, fencing_token, last_token, subject_json,
435
557
  renewed_at, first_acquired_order)
436
558
  VALUES (?, ?, ?, 1, 1, ?, ${nowMs}, ${nextOrder.value})
437
559
  ON CONFLICT(kind, key) DO UPDATE SET
@@ -440,28 +562,34 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
440
562
  holder_id = excluded.holder_id, subject_json = excluded.subject_json, renewed_at = excluded.renewed_at
441
563
  WHERE ${table}.holder_id IS NULL OR ${mine} OR ${rowAge} > ?
442
564
  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);
565
+ params: [key.kind, keyId(key), holderId, stored, staleAfterMs],
566
+ };
567
+ // Held by another live holder: PostgreSQL locks the row whose guard failed until the transaction ends, so this
568
+ // read, which follows the statement, finds the holder that refused it. The statement and the read go with the
569
+ // transaction's start and its commit, in one round trip, on a pipelined connection.
570
+ const holder = holderStatement(key);
571
+ const taking = database.transaction(
572
+ async (tx) => {
573
+ const taken = await tx.get<SqliteRow & { fencing_token: number | bigint }>(take.sql, ...take.params);
574
+ const row = (await tx.get<HolderRow>(holder.sql, ...holder.params))!;
575
+ if (taken !== undefined) {
576
+ return {
577
+ status: "acquired",
578
+ lease: { key, holderId, fencingToken: Number(taken.fencing_token) },
579
+ } as const;
580
+ }
581
+ return { status: "held", holderId: row.holder_id!, fencingToken: Number(row.fencing_token) } as const;
582
+ },
583
+ { ...fenced, leading: [take, holder], leadingOnly: true },
584
+ );
585
+ const acquired = await holding(taking);
586
+ // The lock goes with the transaction's start and its commit, in one round trip, so it is held for none.
460
587
  if (acquired.status === "acquired" && subject.kind === "presence" && dialect.name === "postgres")
461
- await database.transaction(
462
- async () => {},
463
- recipientTransaction(database, options.prefix, subject.targetIdentity),
464
- );
588
+ await database.transaction((tx) => tx.get(SENDS_PASSED.sql), {
589
+ ...recipientTransaction(database, options.prefix, subject.targetIdentity),
590
+ leading: [SENDS_PASSED],
591
+ leadingOnly: true,
592
+ });
465
593
  return acquired;
466
594
  },
467
595
  async renew(lease, subject) {
@@ -480,62 +608,281 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
480
608
  ...ownedParams(lease),
481
609
  );
482
610
  return changes === 1 ? ({ status: "renewed" } as const) : stale(await holderOf(tx, lease.key));
483
- }, fenced);
611
+ }, renewal);
484
612
  },
485
613
  async renewMany(requests) {
486
614
  if (requests.length === 0) return [];
487
- const results: Array<LeaseRenewResult | undefined> = new Array(requests.length);
615
+ const invalidResults: Array<InvalidStateInput | undefined> = new Array(requests.length);
488
616
  let validCount = 0;
489
617
  for (let i = 0; i < requests.length; i++) {
490
618
  const { lease, subject } = requests[i]!;
491
619
  const bad = validLease(lease);
492
620
  if (bad !== undefined) {
493
- results[i] = bad;
621
+ invalidResults[i] = bad;
494
622
  } else if (
495
623
  subject !== undefined &&
496
624
  (subject.kind !== lease.key.kind || keyId(keyOf(subject)) !== keyId(lease.key))
497
625
  ) {
498
- results[i] = invalid("subject-key-mismatch");
626
+ invalidResults[i] = invalid("subject-key-mismatch");
499
627
  } else {
500
628
  validCount++;
501
629
  }
502
630
  }
503
- if (validCount === 0) return results as LeaseRenewResult[];
504
- // Rows locked in one order on every broker, so two renewals of overlapping leases never deadlock.
505
- const order = requests
506
- .map((request, index) => ({ index, kind: request.lease.key.kind, id: keyId(request.lease.key) }))
507
- .filter(({ index }) => results[index] === undefined)
508
- .sort((a, b) => compare(a.kind, b.kind) || compare(a.id, b.id))
509
- .map(({ index }) => index);
510
- await database.transaction(async (tx) => {
511
- // Every update is sent before any answer is awaited, in the lock order: a pipelined connection sends them
512
- // in one round trip, and the server runs them in the order sent (#6560).
513
- const renewals = order.map((i) => {
514
- const { lease, subject } = requests[i]!;
515
- return subject === undefined
516
- ? tx.run(`UPDATE ${table} SET renewed_at = ${nowMs} WHERE ${owned}`, ...ownedParams(lease))
517
- : tx.run(
518
- `UPDATE ${table} SET renewed_at = ${nowMs}, subject_json = ? WHERE ${owned}`,
519
- subjectJson(subject),
520
- ...ownedParams(lease),
521
- );
631
+ if (validCount === 0) return invalidResults as LeaseRenewResult[];
632
+ const tupleKey = (kind: string, id: string, holderId: string, fencingToken: number) =>
633
+ JSON.stringify([kind, id.toWellFormed(), holderId.toWellFormed(), fencingToken]);
634
+ const pairKey = (kind: string, id: string) => JSON.stringify([kind, id.toWellFormed()]);
635
+ // Deduplicate exact (kind, key, holder, fencing_token) tuples, keeping the last subject in input order so the
636
+ // single UPDATE matches each target row at most once and matches serial renewal semantics (#6714).
637
+ const byTuple = new Map<
638
+ string,
639
+ {
640
+ readonly kind: LeaseKind;
641
+ readonly id: string;
642
+ readonly holderId: string;
643
+ readonly fencingToken: number;
644
+ subjectJson: string | null;
645
+ }
646
+ >();
647
+ const validPairs = new Map<string, readonly [LeaseKind, string]>();
648
+ let hasNonSafeIntToken = false;
649
+ for (let i = 0; i < requests.length; i++) {
650
+ if (invalidResults[i] !== undefined) continue;
651
+ const { lease, subject } = requests[i]!;
652
+ const id = keyId(lease.key);
653
+ const pKey = pairKey(lease.key.kind, id);
654
+ if (!validPairs.has(pKey)) validPairs.set(pKey, [lease.key.kind, id]);
655
+ if (!Number.isSafeInteger(lease.fencingToken)) {
656
+ hasNonSafeIntToken = true;
657
+ continue;
658
+ }
659
+ const tKey = tupleKey(lease.key.kind, id, lease.holderId, lease.fencingToken);
660
+ const nextSubject = subject === undefined ? undefined : subjectJson(subject);
661
+ const existing = byTuple.get(tKey);
662
+ if (existing === undefined) {
663
+ byTuple.set(tKey, {
664
+ kind: lease.key.kind,
665
+ id,
666
+ holderId: lease.holderId,
667
+ fencingToken: lease.fencingToken,
668
+ subjectJson: nextSubject ?? null,
669
+ });
670
+ } else if (nextSubject !== undefined) {
671
+ existing.subjectJson = nextSubject;
672
+ }
673
+ }
674
+ const entries = [...byTuple.values()].sort((a, b) => compare(a.kind, b.kind) || compare(a.id, b.id));
675
+ const answer = (
676
+ renewed: ReadonlySet<string>,
677
+ found: ReadonlyMap<string, MissedHolderRow>,
678
+ ): LeaseRenewResult[] =>
679
+ requests.map(({ lease }, index): LeaseRenewResult => {
680
+ const bad = invalidResults[index];
681
+ if (bad !== undefined) return bad;
682
+ const id = keyId(lease.key);
683
+ if (
684
+ Number.isSafeInteger(lease.fencingToken) &&
685
+ renewed.has(tupleKey(lease.key.kind, id, lease.holderId, lease.fencingToken))
686
+ )
687
+ return { status: "renewed" } as const;
688
+ return stale(found.get(pairKey(lease.key.kind, id)));
522
689
  });
523
- const settled = await Promise.allSettled(renewals);
524
- const failed = settled.find((outcome) => outcome.status === "rejected");
525
- if (failed !== undefined) throw failed.reason;
526
- const renewed = settled.map((outcome) => (outcome as PromiseFulfilledResult<SqliteRunResult>).value);
527
- for (const [position, i] of order.entries())
528
- results[i] =
529
- renewed[position]!.changes === 1
530
- ? ({ status: "renewed" } as const)
531
- : stale(await holderOf(tx, requests[i]!.lease.key));
532
- }, fenced);
533
- return results as LeaseRenewResult[];
690
+ if (dialect.name === "postgres") {
691
+ const pairsParam = JSON.stringify([...validPairs.values()], wellFormed);
692
+ if (entries.length === 0) {
693
+ const readAll: SqliteStatement = {
694
+ sql: `WITH missed AS MATERIALIZED (
695
+ SELECT entry ->> 0 AS kind, entry ->> 1 AS key
696
+ FROM jsonb_array_elements((?)::jsonb) AS entry
697
+ )
698
+ SELECT t.kind, t.key, t.holder_id, t.fencing_token
699
+ FROM ${table} AS t
700
+ JOIN missed ON t.kind = missed.kind AND t.key = missed.key
701
+ WHERE t.kind = ANY(ARRAY(SELECT DISTINCT kind FROM missed))
702
+ AND t.key = ANY(ARRAY(SELECT DISTINCT key FROM missed))`,
703
+ params: [pairsParam],
704
+ };
705
+ return database.transaction(
706
+ async (tx) => {
707
+ const found = new Map<string, MissedHolderRow>();
708
+ for (const row of await tx.all<MissedHolderRow>(readAll.sql, ...readAll.params))
709
+ found.set(pairKey(row.kind, row.key), row);
710
+ return answer(new Set(), found);
711
+ },
712
+ { ...renewal, leading: [readAll], leadingOnly: true },
713
+ );
714
+ }
715
+ const write: SqliteStatement = {
716
+ sql: `WITH requested AS MATERIALIZED (
717
+ SELECT
718
+ entry ->> 0 AS kind,
719
+ entry ->> 1 AS key,
720
+ entry ->> 2 AS holder_id,
721
+ (entry ->> 3)::bigint AS fencing_token,
722
+ entry ->> 4 AS subject_json
723
+ FROM jsonb_array_elements((?)::jsonb) AS entry
724
+ ),
725
+ locked AS MATERIALIZED (
726
+ SELECT t.kind, t.key, requested.holder_id, requested.fencing_token, requested.subject_json
727
+ FROM ${table} AS t
728
+ JOIN requested
729
+ ON t.kind = requested.kind
730
+ AND t.key = requested.key
731
+ AND t.holder_id = requested.holder_id
732
+ AND t.fencing_token = requested.fencing_token
733
+ WHERE t.kind = ANY(ARRAY(SELECT DISTINCT kind FROM requested))
734
+ AND t.key = ANY(ARRAY(SELECT DISTINCT key FROM requested))
735
+ ORDER BY t.kind, t.key
736
+ FOR UPDATE OF t
737
+ ),
738
+ renewed AS (
739
+ UPDATE ${table} AS t
740
+ SET renewed_at = ${nowMs}, subject_json = COALESCE(locked.subject_json, t.subject_json)
741
+ FROM locked
742
+ WHERE t.kind = locked.kind
743
+ AND t.key = locked.key
744
+ AND t.holder_id = locked.holder_id
745
+ AND t.fencing_token = locked.fencing_token
746
+ RETURNING t.kind, t.key, t.holder_id, t.fencing_token
747
+ ),
748
+ gate AS MATERIALIZED (
749
+ SELECT set_config('${LEASE_RENEW_MISSES}',
750
+ CASE WHEN (SELECT COUNT(*) FROM renewed) < CAST(? AS ${types.int}) THEN '1' ELSE '' END,
751
+ true) AS misses
752
+ )
753
+ SELECT renewed.kind, renewed.key, renewed.holder_id, renewed.fencing_token
754
+ FROM gate LEFT JOIN renewed ON TRUE`,
755
+ params: [
756
+ JSON.stringify(
757
+ entries.map((entry) => [
758
+ entry.kind,
759
+ entry.id,
760
+ entry.holderId,
761
+ entry.fencingToken,
762
+ entry.subjectJson,
763
+ ]),
764
+ wellFormed,
765
+ ),
766
+ entries.length + (hasNonSafeIntToken ? 1 : 0),
767
+ ],
768
+ };
769
+ const readMisses: SqliteStatement = {
770
+ sql: `WITH missed AS MATERIALIZED (
771
+ SELECT entry ->> 0 AS kind, entry ->> 1 AS key
772
+ FROM jsonb_array_elements((?)::jsonb) AS entry
773
+ WHERE current_setting('${LEASE_RENEW_MISSES}', true) = '1'
774
+ )
775
+ SELECT t.kind, t.key, t.holder_id, t.fencing_token
776
+ FROM ${table} AS t
777
+ JOIN missed ON t.kind = missed.kind AND t.key = missed.key
778
+ WHERE current_setting('${LEASE_RENEW_MISSES}', true) = '1'
779
+ AND t.kind = ANY(ARRAY(SELECT DISTINCT kind FROM missed))
780
+ AND t.key = ANY(ARRAY(SELECT DISTINCT key FROM missed))`,
781
+ params: [pairsParam],
782
+ };
783
+ return database.transaction(
784
+ async (tx) => {
785
+ const renewed = new Set<string>();
786
+ for (const row of await tx.all<RenewedLeaseRow>(write.sql, ...write.params))
787
+ if (
788
+ row.kind !== null &&
789
+ row.key !== null &&
790
+ row.holder_id !== null &&
791
+ row.fencing_token !== null
792
+ )
793
+ renewed.add(tupleKey(row.kind, row.key, row.holder_id, Number(row.fencing_token)));
794
+ const found = new Map<string, MissedHolderRow>();
795
+ for (const row of await tx.all<MissedHolderRow>(readMisses.sql, ...readMisses.params))
796
+ found.set(pairKey(row.kind, row.key), row);
797
+ return answer(renewed, found);
798
+ },
799
+ { ...renewal, leading: [write, readMisses], leadingOnly: true },
800
+ );
801
+ }
802
+ const write: SqliteStatement | undefined =
803
+ entries.length === 0
804
+ ? undefined
805
+ : {
806
+ sql: `WITH requested AS (
807
+ SELECT
808
+ json_extract(value, '$[0]') AS req_kind,
809
+ json_extract(value, '$[1]') AS req_key,
810
+ json_extract(value, '$[2]') AS req_holder_id,
811
+ json_extract(value, '$[3]') AS req_fencing_token,
812
+ json_extract(value, '$[4]') AS req_subject_json
813
+ FROM json_each(?)
814
+ )
815
+ UPDATE ${table}
816
+ SET renewed_at = ${nowMs}, subject_json = COALESCE(requested.req_subject_json, ${table}.subject_json)
817
+ FROM requested
818
+ WHERE ${table}.kind = requested.req_kind
819
+ AND ${table}.key = requested.req_key
820
+ AND ${table}.holder_id = requested.req_holder_id
821
+ AND ${table}.fencing_token = requested.req_fencing_token
822
+ RETURNING kind, key, holder_id, fencing_token`,
823
+ params: [
824
+ JSON.stringify(
825
+ entries.map((entry) => [
826
+ entry.kind,
827
+ entry.id,
828
+ entry.holderId,
829
+ entry.fencingToken,
830
+ entry.subjectJson,
831
+ ]),
832
+ wellFormed,
833
+ ),
834
+ ],
835
+ };
836
+ const readMissedSql = `SELECT t.kind, t.key, t.holder_id, t.fencing_token
837
+ FROM ${table} AS t
838
+ JOIN (
839
+ SELECT json_extract(value, '$[0]') AS kind, json_extract(value, '$[1]') AS key
840
+ FROM json_each(?)
841
+ ) AS missed
842
+ ON t.kind = missed.kind AND t.key = missed.key`;
843
+ return database.transaction(
844
+ async (tx) => {
845
+ const renewed = new Set<string>();
846
+ if (write !== undefined) {
847
+ for (const row of await tx.all<RenewedLeaseRow>(write.sql, ...write.params))
848
+ if (
849
+ row.kind !== null &&
850
+ row.key !== null &&
851
+ row.holder_id !== null &&
852
+ row.fencing_token !== null
853
+ )
854
+ renewed.add(tupleKey(row.kind, row.key, row.holder_id, Number(row.fencing_token)));
855
+ }
856
+ const missedByPair = new Map<string, readonly [LeaseKind, string]>();
857
+ for (let i = 0; i < requests.length; i++) {
858
+ if (invalidResults[i] !== undefined) continue;
859
+ const { lease } = requests[i]!;
860
+ const id = keyId(lease.key);
861
+ if (
862
+ Number.isSafeInteger(lease.fencingToken) &&
863
+ renewed.has(tupleKey(lease.key.kind, id, lease.holderId, lease.fencingToken))
864
+ )
865
+ continue;
866
+ const pKey = pairKey(lease.key.kind, id);
867
+ if (!missedByPair.has(pKey)) missedByPair.set(pKey, [lease.key.kind, id]);
868
+ }
869
+ const found = new Map<string, MissedHolderRow>();
870
+ if (missedByPair.size > 0) {
871
+ const rows = await tx.all<MissedHolderRow>(
872
+ readMissedSql,
873
+ JSON.stringify([...missedByPair.values()], wellFormed),
874
+ );
875
+ for (const row of rows) found.set(pairKey(row.kind, row.key), row);
876
+ }
877
+ return answer(renewed, found);
878
+ },
879
+ renewal,
880
+ );
534
881
  },
535
882
  async release(lease) {
536
883
  const bad = validLease(lease);
537
884
  if (bad !== undefined) return bad;
538
- return database.transaction(async (tx) => {
885
+ const releasing = database.transaction(async (tx) => {
539
886
  const { changes } = await tx.run(
540
887
  `UPDATE ${table} SET holder_id = NULL, fencing_token = NULL, subject_json = NULL, renewed_at = NULL
541
888
  WHERE ${owned}`,
@@ -543,10 +890,12 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
543
890
  );
544
891
  return changes === 1 ? ({ status: "released" } as const) : stale(await holderOf(tx, lease.key));
545
892
  }, fenced);
893
+ return holding(releasing);
546
894
  },
547
895
  async read(key) {
548
896
  const bad = invalidKey(key);
549
897
  if (bad !== undefined) return bad;
898
+ if (unfinished.size > 0) await Promise.all(unfinished);
550
899
  const row = await reader.get<StateRow>(
551
900
  `SELECT kind, key, holder_id, fencing_token, subject_json, ${leaseAge} AS age_ms FROM ${table}
552
901
  WHERE kind = ? AND key = ? AND holder_id IS NOT NULL`,
@@ -566,6 +915,7 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
566
915
  const target = named.toWellFormed();
567
916
  const trimmed = target.trim();
568
917
  const head = /^[0-9a-f]{8}$/i.test(trimmed) ? trimmed.toLowerCase() : null;
918
+ if (unfinished.size > 0) await Promise.all(unfinished);
569
919
  const rows = await reader.all<StateRow>(
570
920
  liveAddressed,
571
921
  target,
@@ -582,15 +932,17 @@ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions
582
932
  }
583
933
  : {}),
584
934
  async listAged(kind, minAgeMs) {
935
+ if (unfinished.size > 0) await Promise.all(unfinished);
585
936
  const rows = await reader.all<StateRow>(leasesByAge(dialect, table, ">="), kind, minAgeMs);
586
937
  return rows.map(stateFromRow);
587
938
  },
588
939
  async retireHolder(holderId) {
589
- const { changes } = await database.run(
940
+ const retiring = database.run(
590
941
  `UPDATE ${table} SET holder_id = NULL, fencing_token = NULL, subject_json = NULL, renewed_at = NULL
591
942
  WHERE holder_id = ?`,
592
943
  holderId,
593
944
  );
945
+ const { changes } = await holding(retiring);
594
946
  return changes;
595
947
  },
596
948
  };