@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
@@ -1,6 +1,6 @@
1
1
  import "../../_shared/rolldown-runtime-BGM3D5V3.js";
2
- import { GitUnavailableError, isGitUnavailableError } from "../../_shared/startup-0-0-3IXNMFM2.js";
3
- import { WorkspaceBindingError, WorkspaceCollectionError, WorkspaceConfigError, WorkspaceDriftError, WorkspaceError, WorkspaceGitError, WorkspacePublicationError, WorkspaceRestoreError, WorkspaceSandboxError, WorkspaceSnapshotError, WorkspaceTimeoutError, attachCleanupCause, findWorkspaceError, gitInstallCommand, isRetryableWorkspaceError, isWorkspaceBindingError, isWorkspaceCollectionError, isWorkspaceConfigError, isWorkspaceDriftError, isWorkspaceError, isWorkspaceGitError, isWorkspacePublicationError, isWorkspaceRestoreError, isWorkspaceSandboxError, isWorkspaceSnapshotError, isWorkspaceTimeoutError, rehydrateWorkspaceError, serializeWorkspaceError, unreadablePathError, unwritablePathError } from "../../_shared/startup-0-1-7T2IAE7J.js";
2
+ import { GitUnavailableError, isGitUnavailableError } from "../../_shared/startup-0-0-XJJDOIEC.js";
3
+ import { WorkspaceBindingError, WorkspaceCollectionError, WorkspaceConfigError, WorkspaceDriftError, WorkspaceError, WorkspaceGitError, WorkspacePublicationError, WorkspaceRestoreError, WorkspaceSandboxError, WorkspaceSnapshotError, WorkspaceTimeoutError, attachCleanupCause, findWorkspaceError, gitInstallCommand, isRetryableWorkspaceError, isWorkspaceBindingError, isWorkspaceCollectionError, isWorkspaceConfigError, isWorkspaceDriftError, isWorkspaceError, isWorkspaceGitError, isWorkspacePublicationError, isWorkspaceRestoreError, isWorkspaceSandboxError, isWorkspaceSnapshotError, isWorkspaceTimeoutError, rehydrateWorkspaceError, serializeWorkspaceError, unreadablePathError, unwritablePathError } from "../../_shared/startup-0-1-M6OWAYHH.js";
4
4
  import "../../_shared/startup-0-2-5QHPCEON.js";
5
5
  export { GitUnavailableError, WorkspaceBindingError, WorkspaceCollectionError, WorkspaceConfigError, WorkspaceDriftError, WorkspaceError, WorkspaceGitError, WorkspacePublicationError, WorkspaceRestoreError, WorkspaceSandboxError, WorkspaceSnapshotError, WorkspaceTimeoutError, attachCleanupCause, findWorkspaceError, gitInstallCommand, isGitUnavailableError, isRetryableWorkspaceError, isWorkspaceBindingError, isWorkspaceCollectionError, isWorkspaceConfigError, isWorkspaceDriftError, isWorkspaceError, isWorkspaceGitError, isWorkspacePublicationError, isWorkspaceRestoreError, isWorkspaceSandboxError, isWorkspaceSnapshotError, isWorkspaceTimeoutError, rehydrateWorkspaceError, serializeWorkspaceError, unreadablePathError, unwritablePathError };
6
6
  //# sourceMappingURL=errors.code.js.map
@@ -6,7 +6,7 @@ try {
6
6
  } catch (error) {
7
7
  const root = new URL("../../", import.meta.url);
8
8
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
9
- const key = `${root.href}#0.10.11-alpha.2`;
9
+ const key = `${root.href}#0.10.11-alpha.4`;
10
10
  let release = releases.get(key);
11
11
  if (release === undefined) {
12
12
  const current = (async () => {
@@ -27,8 +27,8 @@ try {
27
27
  release = current;
28
28
  }
29
29
  const running = await release;
30
- if (running === undefined || running.version === "0.10.11-alpha.2") throw error;
31
- throw new Error((typeof running.name === "string" ? running.name : "atomic") + " was updated to 0.10.11-alpha.2 while this session was running; restart it to keep using worktree snapshots.", {
30
+ if (running === undefined || running.version === "0.10.11-alpha.4") throw error;
31
+ throw new Error((typeof running.name === "string" ? running.name : "atomic") + " was updated to 0.10.11-alpha.4 while this session was running; restart it to keep using worktree snapshots.", {
32
32
  cause: error,
33
33
  });
34
34
  }
@@ -6,7 +6,7 @@ try {
6
6
  } catch (error) {
7
7
  const root = new URL("../../", import.meta.url);
8
8
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
9
- const key = `${root.href}#0.10.11-alpha.2`;
9
+ const key = `${root.href}#0.10.11-alpha.4`;
10
10
  let release = releases.get(key);
11
11
  if (release === undefined) {
12
12
  const current = (async () => {
@@ -27,8 +27,8 @@ try {
27
27
  release = current;
28
28
  }
29
29
  const running = await release;
30
- if (running === undefined || running.version === "0.10.11-alpha.2") throw error;
31
- throw new Error((typeof running.name === "string" ? running.name : "atomic") + " was updated to 0.10.11-alpha.2 while this session was running; restart it to keep using worktree snapshots.", {
30
+ if (running === undefined || running.version === "0.10.11-alpha.4") throw error;
31
+ throw new Error((typeof running.name === "string" ? running.name : "atomic") + " was updated to 0.10.11-alpha.4 while this session was running; restart it to keep using worktree snapshots.", {
32
32
  cause: error,
33
33
  });
34
34
  }
@@ -0,0 +1,81 @@
1
+ import { dialectOf } from "../storage/dialect.js";
2
+ import { withShortSchemaLockWaits } from "../storage/migrations.js";
3
+ import { schemaCatalogOf } from "../storage/schema-catalog.js";
4
+ /** The name of {@link forkInheritedBlobGuard} on the snapshot blob table `blobs`. */
5
+ export function forkInheritedBlobGuardName(blobs) {
6
+ return `${blobs}_fork_keep`;
7
+ }
8
+ /**
9
+ * The statements that install, on the snapshot blob table, a trigger that keeps every blob a fork inherits (#6560): a
10
+ * DELETE of the blob's row skips it, as long as a session record names it at a seq a fork segment covers, so that the
11
+ * fork's history still has the snapshot. A release without shared-history forks collects blobs by the snapshots each
12
+ * session retains, which never count the ones a fork inherits, and a process of one that an in-place update caught
13
+ * holds that collection while its session store, from the update, makes shared forks: the database refuses that
14
+ * collection what this build's own collection keeps (`SqlSnapshotBlobStore.sweep`), by the same condition, so that
15
+ * collection never meets it. Once the forks that inherit a blob are deleted, or have their own copy, their segments no
16
+ * longer name it, and the blob goes as any other. Only a DELETE of a blob runs it, and its check reads the session
17
+ * records by hash and the segments by source, through their indexes. The chunks of a blob go with its row, by the
18
+ * trigger that deletes them after it.
19
+ */
20
+ export function forkInheritedBlobGuard(dialect, tables, forkSegments) {
21
+ return dialect.renderTrigger({
22
+ name: forkInheritedBlobGuardName(tables.blobs),
23
+ table: tables.blobs,
24
+ timing: "BEFORE",
25
+ event: "DELETE",
26
+ when: `EXISTS (SELECT 1 FROM ${tables.sessionRecords} AS record JOIN ${forkSegments} AS segment ON segment.source_id = record.session_id AND record.seq BETWEEN segment.from_seq AND segment.to_seq WHERE record.hash = OLD.hash)`,
27
+ // Skips the row and goes on with the statement: SQLite's RAISE(IGNORE), a PostgreSQL BEFORE trigger's NULL.
28
+ statements: [dialect.name === "postgres" ? "RETURN NULL" : "SELECT RAISE(IGNORE)"],
29
+ });
30
+ }
31
+ /**
32
+ * Installs {@link forkInheritedBlobGuard} in the transaction `tx`, unless it is there, or the snapshot tables or the
33
+ * fork segments table are not there yet. The switch to shared-history forks installs it with the fork tables, so no
34
+ * fork shares a history before the database keeps what it inherits; the snapshot store installs it with its tables on
35
+ * a new database, whose fork tables come first.
36
+ */
37
+ export async function installForkInheritedBlobGuard(tx, dialect, tables, forkSegments) {
38
+ const name = forkInheritedBlobGuardName(tables.blobs);
39
+ const probe = dialect.schemaObjects([tables.blobs, tables.sessionRecords, forkSegments, name]);
40
+ const found = new Set((await tx.all(probe.sql, ...probe.params)).map((row) => row.name));
41
+ if (found.has(name) || ![tables.blobs, tables.sessionRecords, forkSegments].every((table) => found.has(table)))
42
+ return;
43
+ const guard = forkInheritedBlobGuard(dialect, tables, forkSegments);
44
+ await withShortSchemaLockWaits(tx, dialect, () => tx.exec(guard));
45
+ }
46
+ /**
47
+ * Installs {@link forkInheritedBlobGuard} where a session store's open finds forks sharing history, once its snapshot
48
+ * store is open, unless the schema the open read holds it (`schemaCatalogOf`), as it does on every open after the
49
+ * first: a database switched by a build before the guard, or whose snapshot store came from an earlier release, as in
50
+ * a process an in-place update caught, which creates its tables without it. Housekeeping: where it cannot be
51
+ * installed, such as for a PostgreSQL role that does not own the snapshot tables, the open goes on, and
52
+ * `atomic storage migrate`, run as the owner, installs it.
53
+ */
54
+ export async function ensureForkInheritedBlobGuard(database, tables, forkSegments, ledger) {
55
+ if (database.readOnly === true)
56
+ return;
57
+ const dialect = dialectOf(database);
58
+ const name = forkInheritedBlobGuardName(tables.blobs);
59
+ const catalog = await schemaCatalogOf(database);
60
+ if (catalog !== undefined) {
61
+ if (catalog.hasObject(name))
62
+ return;
63
+ }
64
+ else {
65
+ const probe = dialect.schemaObjects([name]);
66
+ if ((await database.all(probe.sql, ...probe.params)).length > 0)
67
+ return;
68
+ }
69
+ try {
70
+ await database.transaction(async (tx) => {
71
+ // Serialized with the other stores' schema setups under the prefix, so hosts that open together install it once.
72
+ if (dialect.name === "postgres")
73
+ await tx.get("SELECT pg_advisory_xact_lock(hashtextextended(?, 0)) AS locked", `${ledger}:schema`);
74
+ await installForkInheritedBlobGuard(tx, dialect, tables, forkSegments);
75
+ }, { retryTransientFailures: true, concurrency: { kind: "serial", domain: ledger } });
76
+ }
77
+ catch {
78
+ // Left for a later open or `atomic storage migrate`.
79
+ }
80
+ }
81
+ //# sourceMappingURL=fork-blob-guard.js.map
@@ -0,0 +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G,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC;YAAE,OAAO;IACzE,CAAC;IACD,IAAI,CAAC;QACJ,MAAM,QAAQ,CAAC,WAAW,CACzB,KAAK,EAAE,EAAE,EAAE,EAAE;YACZ,iHAAiH;YACjH,IAAI,OAAO,CAAC,IAAI,KAAK,UAAU;gBAC9B,MAAM,EAAE,CAAC,GAAG,CAAC,gEAAgE,EAAE,GAAG,MAAM,SAAS,CAAC,CAAC;YACpG,MAAM,6BAA6B,CAAC,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,YAAY,CAAC,CAAC;QACxE,CAAC,EACD,EAAE,sBAAsB,EAAE,IAAI,EAAE,WAAW,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,CACjF,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QACR,qDAAqD;IACtD,CAAC;AACF,CAAC","sourcesContent":["import type { SqliteDatabase, SqliteExecutor, SqliteRow } from \"../storage/database.js\";\nimport { dialectOf, type StorageDialect } from \"../storage/dialect.js\";\nimport { withShortSchemaLockWaits } from \"../storage/migrations.js\";\nimport { schemaCatalogOf } from \"../storage/schema-catalog.js\";\n\n/** The snapshot blob table and the session records of the snapshot index that {@link forkInheritedBlobGuard} reads. */\nexport interface ForkInheritedBlobTables {\n\treadonly blobs: string;\n\treadonly sessionRecords: string;\n}\n\n/** The name of {@link forkInheritedBlobGuard} on the snapshot blob table `blobs`. */\nexport function forkInheritedBlobGuardName(blobs: string): string {\n\treturn `${blobs}_fork_keep`;\n}\n\n/**\n * The statements that install, on the snapshot blob table, a trigger that keeps every blob a fork inherits (#6560): a\n * DELETE of the blob's row skips it, as long as a session record names it at a seq a fork segment covers, so that the\n * fork's history still has the snapshot. A release without shared-history forks collects blobs by the snapshots each\n * session retains, which never count the ones a fork inherits, and a process of one that an in-place update caught\n * holds that collection while its session store, from the update, makes shared forks: the database refuses that\n * collection what this build's own collection keeps (`SqlSnapshotBlobStore.sweep`), by the same condition, so that\n * collection never meets it. Once the forks that inherit a blob are deleted, or have their own copy, their segments no\n * longer name it, and the blob goes as any other. Only a DELETE of a blob runs it, and its check reads the session\n * records by hash and the segments by source, through their indexes. The chunks of a blob go with its row, by the\n * trigger that deletes them after it.\n */\nexport function forkInheritedBlobGuard(\n\tdialect: StorageDialect,\n\ttables: ForkInheritedBlobTables,\n\tforkSegments: string,\n): string {\n\treturn dialect.renderTrigger({\n\t\tname: forkInheritedBlobGuardName(tables.blobs),\n\t\ttable: tables.blobs,\n\t\ttiming: \"BEFORE\",\n\t\tevent: \"DELETE\",\n\t\twhen: `EXISTS (SELECT 1 FROM ${tables.sessionRecords} AS record JOIN ${forkSegments} AS segment ON segment.source_id = record.session_id AND record.seq BETWEEN segment.from_seq AND segment.to_seq WHERE record.hash = OLD.hash)`,\n\t\t// Skips the row and goes on with the statement: SQLite's RAISE(IGNORE), a PostgreSQL BEFORE trigger's NULL.\n\t\tstatements: [dialect.name === \"postgres\" ? \"RETURN NULL\" : \"SELECT RAISE(IGNORE)\"],\n\t});\n}\n\n/**\n * Installs {@link forkInheritedBlobGuard} in the transaction `tx`, unless it is there, or the snapshot tables or the\n * fork segments table are not there yet. The switch to shared-history forks installs it with the fork tables, so no\n * fork shares a history before the database keeps what it inherits; the snapshot store installs it with its tables on\n * a new database, whose fork tables come first.\n */\nexport async function installForkInheritedBlobGuard(\n\ttx: SqliteExecutor,\n\tdialect: StorageDialect,\n\ttables: ForkInheritedBlobTables,\n\tforkSegments: string,\n): Promise<void> {\n\tconst name = forkInheritedBlobGuardName(tables.blobs);\n\tconst probe = dialect.schemaObjects([tables.blobs, tables.sessionRecords, forkSegments, name]);\n\tconst found = new Set(\n\t\t(await tx.all<SqliteRow & { name: string }>(probe.sql, ...probe.params)).map((row) => row.name),\n\t);\n\tif (found.has(name) || ![tables.blobs, tables.sessionRecords, forkSegments].every((table) => found.has(table)))\n\t\treturn;\n\tconst guard = forkInheritedBlobGuard(dialect, tables, forkSegments);\n\tawait withShortSchemaLockWaits(tx, dialect, () => tx.exec(guard));\n}\n\n/**\n * Installs {@link forkInheritedBlobGuard} where a session store's open finds forks sharing history, once its snapshot\n * store is open, unless the schema the open read holds it (`schemaCatalogOf`), as it does on every open after the\n * first: a database switched by a build before the guard, or whose snapshot store came from an earlier release, as in\n * a process an in-place update caught, which creates its tables without it. Housekeeping: where it cannot be\n * installed, such as for a PostgreSQL role that does not own the snapshot tables, the open goes on, and\n * `atomic storage migrate`, run as the owner, installs it.\n */\nexport async function ensureForkInheritedBlobGuard(\n\tdatabase: SqliteDatabase,\n\ttables: ForkInheritedBlobTables,\n\tforkSegments: string,\n\tledger: string,\n): Promise<void> {\n\tif (database.readOnly === true) return;\n\tconst dialect = dialectOf(database);\n\tconst name = forkInheritedBlobGuardName(tables.blobs);\n\tconst catalog = await schemaCatalogOf(database);\n\tif (catalog !== undefined) {\n\t\tif (catalog.hasObject(name)) return;\n\t} else {\n\t\tconst probe = dialect.schemaObjects([name]);\n\t\tif ((await database.all(probe.sql, ...probe.params)).length > 0) return;\n\t}\n\ttry {\n\t\tawait database.transaction(\n\t\t\tasync (tx) => {\n\t\t\t\t// Serialized with the other stores' schema setups under the prefix, so hosts that open together install it once.\n\t\t\t\tif (dialect.name === \"postgres\")\n\t\t\t\t\tawait tx.get(\"SELECT pg_advisory_xact_lock(hashtextextended(?, 0)) AS locked\", `${ledger}:schema`);\n\t\t\t\tawait installForkInheritedBlobGuard(tx, dialect, tables, forkSegments);\n\t\t\t},\n\t\t\t{ retryTransientFailures: true, concurrency: { kind: \"serial\", domain: ledger } },\n\t\t);\n\t} catch {\n\t\t// Left for a later open or `atomic storage migrate`.\n\t}\n}\n"]}
@@ -10,88 +10,249 @@ export function forkSegmentsTable(prefix = "") {
10
10
  /**
11
11
  * The trigger that earlier builds of #6560 installed to link each entry a session with fork segments writes. Each
12
12
  * INSERT into the session entries table ran it, a plain session's too, so the store now writes those links itself
13
- * (`forkEntryLink`, `materializedForkLinks`), and a store's open drops the trigger where it finds it.
13
+ * (`forkLinkWrites`, `materializedForkLinks`), and a store's open drops the trigger where it finds it.
14
14
  */
15
15
  export function legacyForkLinksTriggerName(entries) {
16
16
  return `${entries}_fork_links_v1`;
17
17
  }
18
18
  /** The view seq one past a segment's last, for the segment aliased `alias`. */
19
19
  const segmentEnd = (alias) => `${alias}.base_seq + ${alias}.to_seq - ${alias}.from_seq + 1`;
20
+ /**
21
+ * The seq of the link that is the parent of entry `r` among the links its session stores, or null: of the links before
22
+ * `r` with the parent's id, the first. `r` has the columns {@link parentColumns} names. A save and a rebuild of the
23
+ * index both link an entry with this lookup, so an entry whose parent is written after it, or whose parent's id more
24
+ * than one entry has, is linked the same by both (#6560).
25
+ */
26
+ export function ownParentSeq(links) {
27
+ // `+seq`: the lookup goes by the entry's id, never in seq order, which SQLite would read row by row.
28
+ return `(SELECT min(+p.seq) FROM ${links} AS p WHERE p.session_id = r.session_id AND p.entry_id = r.parent_id AND r.parent_type = 'text' AND +p.seq < r.seq)`;
29
+ }
30
+ /** Whether a link before entry `r` in its session has `r`'s id: such an entry is linked broken, as in a copy. */
31
+ export function ownDuplicate(links) {
32
+ return `EXISTS (SELECT 1 FROM ${links} AS other WHERE other.session_id = r.session_id AND other.entry_id = r.entry_id AND +other.seq < r.seq)`;
33
+ }
20
34
  /**
21
35
  * The seq in session `child`'s view of the entry at seq `seq` of session `source`'s view, where `source` stores a row
22
36
  * `child` inherits. Segments are composed when a fork is made, so a segment's source stores the rows it names itself:
23
37
  * `seq` is either a row `source` stores, which a segment of `child` names, or a row `source` inherits, from the source
24
38
  * of one of its own segments, which a segment of `child` names by that source. An entry that `child`, or a fork
25
- * between `source` and `child`, stores itself, such as one a fork edited, is found by its id.
39
+ * between `source` and `child`, stores itself, such as one a fork edited, is found by its id among the rows of
40
+ * `child`'s view before `bound`, the entry being linked.
26
41
  */
27
- function childViewSeq(links, segments, child, source, seq) {
42
+ function childViewSeq(links, segments, child, source, seq, bound) {
28
43
  const inheritedBy = `ss.session_id = ${source} AND ${seq} BETWEEN ss.base_seq + 1 AND ${segmentEnd("ss")}`;
29
44
  const stored = `${seq} - ss.base_seq - 1 + ss.from_seq`;
30
45
  const entryId = `COALESCE((SELECT a.entry_id FROM ${links} AS a WHERE a.session_id = ${source} AND a.seq = ${seq}), (SELECT a.entry_id FROM ${segments} AS ss JOIN ${links} AS a ON a.session_id = ss.source_id AND a.seq = ${stored} WHERE ${inheritedBy}))`;
31
46
  return `COALESCE(
32
47
  (SELECT ${seq} - cs.from_seq + cs.base_seq + 1 FROM ${segments} AS cs WHERE cs.session_id = ${child} AND cs.source_id = ${source} AND ${seq} BETWEEN cs.from_seq AND cs.to_seq),
33
48
  (SELECT ${stored} - cs.from_seq + cs.base_seq + 1 FROM ${segments} AS ss JOIN ${segments} AS cs ON cs.session_id = ${child} AND cs.source_id = ss.source_id AND ${stored} BETWEEN cs.from_seq AND cs.to_seq WHERE ${inheritedBy}),
34
- (SELECT own.seq FROM ${links} AS own WHERE own.session_id = ${child} AND own.entry_id = ${entryId} ORDER BY own.seq LIMIT 1),
35
- (SELECT x.seq - cs.from_seq + cs.base_seq + 1 FROM ${segments} AS cs JOIN ${links} AS x ON x.session_id = cs.source_id AND x.entry_id = ${entryId} AND x.seq BETWEEN cs.from_seq AND cs.to_seq WHERE cs.session_id = ${child} ORDER BY cs.base_seq, x.seq LIMIT 1)
49
+ (SELECT min(+own.seq) FROM ${links} AS own WHERE own.session_id = ${child} AND own.entry_id = ${entryId} AND +own.seq < ${bound}),
50
+ (SELECT x.seq - cs.from_seq + cs.base_seq + 1 FROM ${segments} AS cs JOIN ${links} AS x ON x.session_id = cs.source_id AND x.entry_id = ${entryId} AND +x.seq BETWEEN cs.from_seq AND cs.to_seq WHERE cs.session_id = ${child} AND cs.base_seq < ${bound} ORDER BY cs.base_seq, x.seq LIMIT 1)
36
51
  )`;
37
52
  }
38
53
  /**
39
- * The statement that indexes the link of one entry of a session with fork segments, as a copy of the session would
40
- * have it. `rows` yields that entry as `r`, with its parent's id and JSON type as `parent_id` and `parent_type`;
41
- * `isSnapshot` tells whether `r` is a snapshot entry.
54
+ * The statement that links one entry of a session with fork segments, as a copy of the session would have it. `rows`
55
+ * yields that entry as `r`, with its parent's id and JSON type as `parent_id` and `parent_type`; `isSnapshot` tells
56
+ * whether `r` is a snapshot entry. It runs after the released link statement of the entry, and writes over that row's
57
+ * anchor and broken mark; the released statements keep the children count.
42
58
  *
43
59
  * The released link statement finds an entry's parent only among the links the session stores, so it marks an entry
44
60
  * whose parent the session inherits broken, without an anchor. This one also finds the parent among the links of the
45
61
  * rows the session's segments name, and takes the parent's anchor in the session's view. An entry whose id an entry
46
- * the session inherits also has is broken, as in a copy. It writes over the released statement's row, so it ends the
47
- * same whichever of the two runs first.
62
+ * the session inherits also has is broken, as in a copy.
48
63
  *
49
- * With `written`, the store runs it after the statement that inserted the entry, whose rows and segments after it may
50
- * be there already (#6560): it then reads only the session's rows and segments before the entry, which are what a copy
51
- * had when it inserted the entry, and leaves the children count to the released statements, which count each child as
52
- * it is inserted. Without, as the index's backfill runs it, it counts the children an entry written below the
53
- * session's last row already has, as when a fork's inherited rows are copied into it.
64
+ * It reads only the rows of the session's view before the entry, the links the session stores and those its segments
65
+ * name, as a copy had when it inserted the entry: a parent written after its child, or an entry of the same id after
66
+ * it, changes nothing. A save runs it as it writes an entry, the index's rebuild as it links a stored row again, and
67
+ * both meet the rows before the entry linked already (`relinkSessionEntries`), so both link every entry the same
68
+ * (#6560).
54
69
  *
55
70
  * The snapshot references of such an entry stay as the released statements index them: a reference's `prev_seq` that
56
71
  * would name an inherited entry is empty. Collection walks a session's references only through the rows the session
57
72
  * stores, and keeps every snapshot record a segment names (see `SqlSnapshotBlobStore.sweep`), so it never needs it.
58
73
  */
59
- export function forkSessionLink(links, segments, rows, isSnapshot, written = false) {
60
- const before = (alias) => (written ? ` AND ${alias}.seq < r.seq` : "");
61
- const segmentBefore = written ? " AND seg.base_seq < r.seq" : "";
62
- const own = (column) => `(SELECT p.${column} FROM ${links} AS p WHERE p.session_id = r.session_id AND p.entry_id = r.parent_id AND r.parent_type = 'text'${before("p")} ORDER BY p.seq LIMIT 1)`;
63
- const ownParent = `EXISTS (SELECT 1 FROM ${links} AS p WHERE p.session_id = r.session_id AND p.entry_id = r.parent_id AND r.parent_type = 'text'${before("p")})`;
64
- const inherited = (select) => `(SELECT ${select} FROM ${segments} AS seg JOIN ${links} AS up ON up.session_id = seg.source_id AND up.entry_id = r.parent_id AND up.seq BETWEEN seg.from_seq AND seg.to_seq WHERE seg.session_id = r.session_id AND r.parent_type = 'text'${segmentBefore} ORDER BY seg.base_seq, up.seq LIMIT 1)`;
65
- const anchor = `CASE WHEN up.anchor_seq IS NOT NULL THEN ${childViewSeq(links, segments, "r.session_id", "up.session_id", "up.anchor_seq")} END`;
66
- const duplicate = `EXISTS (SELECT 1 FROM ${links} AS other WHERE other.session_id = r.session_id AND other.entry_id = r.entry_id AND other.seq <> r.seq${before("other")}) OR EXISTS (SELECT 1 FROM ${segments} AS seg JOIN ${links} AS other ON other.session_id = seg.source_id AND other.entry_id = r.entry_id AND other.seq BETWEEN seg.from_seq AND seg.to_seq WHERE seg.session_id = r.session_id${segmentBefore})`;
67
- const children = written
68
- ? "0"
69
- : `CASE WHEN EXISTS (SELECT 1 FROM ${links} AS later WHERE later.session_id = r.session_id AND later.seq > r.seq) THEN (SELECT count(*) FROM ${links} AS c WHERE c.session_id = r.session_id AND c.parent_id = r.entry_id AND c.seq <> r.seq) ELSE 0 END`;
74
+ export function forkSessionLink(links, segments, rows, isSnapshot) {
75
+ const { parent, columns, anchor, broken } = forkLinkValues(links, segments, isSnapshot, {
76
+ isSnapshotOut: "t.is_snapshot = 1",
77
+ });
70
78
  return `INSERT INTO ${links} (session_id, seq, entry_id, parent_id, anchor_seq, children, broken)
71
- SELECT r.session_id, r.seq, r.entry_id, CASE WHEN r.parent_type = 'text' THEN r.parent_id END,
72
- CASE WHEN ${isSnapshot} THEN r.seq WHEN ${ownParent} THEN ${own("anchor_seq")} ELSE ${inherited(anchor)} END,
73
- ${children},
74
- CASE WHEN ${duplicate} THEN 1 WHEN r.parent_type IS NULL OR r.parent_type = 'null' THEN 0 WHEN ${ownParent} THEN ${own("broken")} ELSE COALESCE(${inherited("up.broken")}, 1) END
75
- FROM ${rows} AS r WHERE EXISTS (SELECT 1 FROM ${segments} AS any_segment WHERE any_segment.session_id = r.session_id)
76
- ON CONFLICT (session_id, seq) DO UPDATE SET anchor_seq = excluded.anchor_seq, ${written ? "" : "children = excluded.children, "}broken = excluded.broken`;
79
+ SELECT t.session_id, t.seq, t.entry_id, CASE WHEN t.parent_type = 'text' THEN t.parent_id END, ${anchor}, 0, ${broken}
80
+ FROM (SELECT r.session_id, r.seq, r.entry_id, r.parent_id, r.parent_type,
81
+ CASE WHEN ${isSnapshot} THEN 1 ELSE 0 END AS is_snapshot,
82
+ ${columns}
83
+ FROM ${rows} AS r ${parent}
84
+ WHERE EXISTS (SELECT 1 FROM ${segments} AS any_segment WHERE any_segment.session_id = r.session_id)) AS t
85
+ WHERE true
86
+ ON CONFLICT (session_id, seq) DO UPDATE SET anchor_seq = excluded.anchor_seq, broken = excluded.broken`;
87
+ }
88
+ /**
89
+ * The anchor and the broken mark of entry `r` as {@link forkSessionLink} links it, from the links before it, its
90
+ * session's and those its segments name: the one function a save, the index's rebuild and the check of a
91
+ * materialization's links ({@link forkLinksCheck}) all compute them with (#6560). For a session without segments it
92
+ * is what the released link statement writes.
93
+ *
94
+ * `parent` is the join that follows `r` in the inner SELECT's FROM: it finds `r`'s parent among the links its session
95
+ * stores ({@link ownParentSeq}) once, as `par`. `columns` projects `par`, the duplicate check and—when segments may
96
+ * exist—a single inherited-parent lookup packing `(COALESCE(anchor + 1, 0) * 2 + broken)` into `inh`, so a row whose
97
+ * parent comes from a segment looks the segment up once for both `anchor` and `broken`. The outer SELECT aliases that
98
+ * projection as `t` and evaluates `anchor` and `broken`.
99
+ */
100
+ export function forkLinkValues(links, segments, isSnapshot, options = {}) {
101
+ const isSnapshotOut = options.isSnapshotOut ?? isSnapshot;
102
+ const hasSegments = options.hasSegments ?? true;
103
+ const segmentBefore = options.segmentBefore;
104
+ // The first link with the parent's id, if it is before `r`: the link `ownParentSeq` finds, joined as a plain row, so
105
+ // that no lookup is a join key the database computes for each comparison.
106
+ const parent = `LEFT JOIN ${links} AS par ON par.session_id = r.session_id AND par.entry_id = r.parent_id AND r.parent_type = 'text' AND +par.seq < r.seq AND NOT EXISTS (SELECT 1 FROM ${links} AS earlier WHERE earlier.session_id = par.session_id AND earlier.entry_id = par.entry_id AND +earlier.seq < par.seq)`;
107
+ if (!hasSegments) {
108
+ return {
109
+ parent,
110
+ columns: `par.anchor_seq AS par_anchor, par.broken AS par_broken, CASE WHEN ${ownDuplicate(links)} THEN 1 ELSE 0 END AS dup`,
111
+ anchor: `CASE WHEN ${isSnapshotOut} THEN t.seq ELSE t.par_anchor END`,
112
+ broken: `CASE WHEN t.dup = 1 THEN 1 WHEN t.parent_type IS NULL OR t.parent_type = 'null' THEN 0 ELSE COALESCE(t.par_broken, 1) END`,
113
+ };
114
+ }
115
+ const inhAnchor = `CASE WHEN ${isSnapshot} THEN 0 WHEN up.anchor_seq IS NOT NULL THEN COALESCE(${childViewSeq(links, segments, "r.session_id", "up.session_id", "up.anchor_seq", "r.seq")} + 1, 0) ELSE 0 END`;
116
+ const inhSub = `(SELECT ${inhAnchor} * 2 + up.broken FROM ${segments} AS seg JOIN ${links} AS up ON up.session_id = seg.source_id AND up.entry_id = r.parent_id AND +up.seq BETWEEN seg.from_seq AND seg.to_seq WHERE seg.session_id = r.session_id AND seg.base_seq < r.seq ORDER BY seg.base_seq, up.seq LIMIT 1)`;
117
+ const inherited = segmentBefore === undefined
118
+ ? `CASE WHEN par.seq IS NULL AND r.parent_type = 'text' THEN ${inhSub} END`
119
+ : `CASE WHEN par.seq IS NULL AND r.parent_type = 'text' THEN CASE WHEN ${segmentBefore} THEN ${inhSub} END END`;
120
+ const segDupExists = `EXISTS (SELECT 1 FROM ${segments} AS seg JOIN ${links} AS other ON other.session_id = seg.source_id AND other.entry_id = r.entry_id AND +other.seq BETWEEN seg.from_seq AND seg.to_seq WHERE seg.session_id = r.session_id AND seg.base_seq < r.seq)`;
121
+ const segDup = segmentBefore === undefined
122
+ ? `CASE WHEN ${segDupExists} THEN 1 ELSE 0 END`
123
+ : `CASE WHEN ${segmentBefore} THEN CASE WHEN ${segDupExists} THEN 1 ELSE 0 END ELSE 0 END`;
124
+ return {
125
+ parent,
126
+ columns: `par.seq AS par_seq, par.anchor_seq AS par_anchor, par.broken AS par_broken, ${inherited} AS inh, CASE WHEN ${ownDuplicate(links)} THEN 1 ELSE ${segDup} END AS dup`,
127
+ anchor: `CASE WHEN ${isSnapshotOut} THEN t.seq WHEN t.par_seq IS NOT NULL THEN t.par_anchor ELSE NULLIF(t.inh / 2, 0) - 1 END`,
128
+ broken: `CASE WHEN t.dup = 1 THEN 1 WHEN t.parent_type IS NULL OR t.parent_type = 'null' THEN 0 WHEN t.par_seq IS NOT NULL THEN t.par_broken ELSE COALESCE(t.inh % 2, 1) END`,
129
+ };
77
130
  }
78
131
  /**
79
132
  * The statement that links the rows a materialization just copied into a fork (#6560), one piece of one source at a
80
133
  * time, all of them in one statement: each row is linked as its source links it, its anchor taken into the fork's
81
- * view, and its children counted among the rows the fork now stores. It runs after the piece's rows are inserted and
82
- * before the fork's segments lose the piece, so they still map the source's seqs. `complete` is the condition that the
83
- * index's backfill is done: until then the backfill links the rows. Parameters: the fork's id, the shift from the
84
- * source's seqs to the fork's, the source's id, the first and last seq of the piece in the source, and the fork's id.
134
+ * view, and its children counted among the rows the fork now stores past the piece's start whose parent ID the piece
135
+ * names. It runs after the piece's rows are inserted and before the fork's segments lose the piece, so they still map
136
+ * the source's seqs. These links are what {@link forkLinkValues} computes for every history but a few:
137
+ * {@link forkLinksCheck} tells, once the segments lost the pieces, and the fork is linked again row by row where it
138
+ * does not hold. `complete` is the condition that the index's backfill is done: until then the backfill links the rows.
139
+ * Parameters (bound in the leading CTE so the order stays fixed across mixed versions): the fork's id, the shift from
140
+ * the source's seqs to the fork's, the source's id, the first and last seq of the piece in the source, and the fork's
141
+ * id.
85
142
  */
86
- export function materializedForkLinks(links, segments, complete, int) {
87
- const anchor = `CASE WHEN up.anchor_seq IS NOT NULL THEN ${childViewSeq(links, segments, "m.child", "up.session_id", "up.anchor_seq")} END`;
88
- return `INSERT INTO ${links} (session_id, seq, entry_id, parent_id, anchor_seq, children, broken)
89
- SELECT m.child, up.seq + m.shift, up.entry_id, up.parent_id, ${anchor}, COALESCE(kids.n, 0), up.broken
90
- FROM (SELECT CAST(? AS text) AS child, CAST(? AS ${int}) AS shift) AS m
91
- JOIN ${links} AS up ON up.session_id = ? AND up.seq BETWEEN ? AND ?
92
- LEFT JOIN (SELECT parent_id, count(*) AS n FROM ${links} WHERE session_id = ? GROUP BY parent_id) AS kids ON kids.parent_id = up.entry_id
93
- WHERE ${complete}
94
- ON CONFLICT (session_id, seq) DO UPDATE SET anchor_seq = excluded.anchor_seq, children = excluded.children, broken = excluded.broken`;
143
+ export function materializedForkLinks(links, segments, complete, int, dialectName) {
144
+ const mCte = `WITH m AS (
145
+ SELECT CAST(? AS text) AS child, CAST(? AS ${int}) AS shift,
146
+ CAST(? AS text) AS source, CAST(? AS ${int}) AS from_seq, CAST(? AS ${int}) AS to_seq,
147
+ CAST(? AS text) AS kids_child
148
+ )`;
149
+ if (dialectName === "postgres") {
150
+ const anchor = `CASE WHEN counted.anchor_seq IS NOT NULL THEN ${childViewSeq(links, segments, "counted.child", "counted.session_id", "counted.anchor_seq", "counted.seq + counted.shift")} END`;
151
+ // On PostgreSQL, unioning the piece's rows (is_kid = 0) with the fork's later links (is_kid = 1) and summing over
152
+ // PARTITION BY entry_id avoids a LEFT JOIN on an aggregated subquery, which PostgreSQL can plan as a quadratic
153
+ // nested loop on fresh tables whose statistics have not been analyzed yet.
154
+ return `${mCte},
155
+ counted AS (
156
+ SELECT child, shift, session_id, seq, entry_id, parent_id, anchor_seq, broken, is_kid,
157
+ sum(is_kid) OVER (PARTITION BY entry_id) AS n
158
+ FROM (
159
+ SELECT m.child, m.shift, up.session_id, up.seq, up.entry_id, up.parent_id, up.anchor_seq, up.broken, 0 AS is_kid
160
+ FROM m CROSS JOIN ${links} AS up
161
+ WHERE up.session_id = m.source AND up.seq BETWEEN m.from_seq AND m.to_seq
162
+ UNION ALL
163
+ SELECT NULL, NULL, NULL, NULL, l.parent_id, NULL, NULL, NULL, 1 AS is_kid
164
+ FROM m CROSS JOIN ${links} AS l
165
+ WHERE l.session_id = m.kids_child AND l.seq > m.from_seq + m.shift AND l.parent_id IS NOT NULL
166
+ ) AS u
167
+ )
168
+ INSERT INTO ${links} (session_id, seq, entry_id, parent_id, anchor_seq, children, broken)
169
+ SELECT counted.child, counted.seq + counted.shift, counted.entry_id, counted.parent_id, ${anchor}, counted.n, counted.broken
170
+ FROM counted
171
+ WHERE counted.is_kid = 0 AND ${complete}
172
+ ON CONFLICT (session_id, seq) DO UPDATE SET anchor_seq = excluded.anchor_seq, children = excluded.children, broken = excluded.broken`;
173
+ }
174
+ const anchor = `CASE WHEN up.anchor_seq IS NOT NULL THEN ${childViewSeq(links, segments, "m.child", "up.session_id", "up.anchor_seq", "up.seq + m.shift")} END`;
175
+ return `${mCte}
176
+ INSERT INTO ${links} (session_id, seq, entry_id, parent_id, anchor_seq, children, broken)
177
+ SELECT m.child, up.seq + m.shift, up.entry_id, up.parent_id, ${anchor}, COALESCE(kids.n, 0), up.broken
178
+ FROM m
179
+ CROSS JOIN ${links} AS up
180
+ LEFT JOIN (
181
+ SELECT l.parent_id, count(*) AS n
182
+ FROM m AS km
183
+ CROSS JOIN ${links} AS l
184
+ WHERE l.session_id = km.kids_child AND l.seq > km.from_seq + km.shift
185
+ AND l.parent_id IN (
186
+ SELECT p.entry_id FROM m AS pm CROSS JOIN ${links} AS p
187
+ WHERE p.session_id = pm.source AND p.seq BETWEEN pm.from_seq AND pm.to_seq
188
+ )
189
+ GROUP BY l.parent_id
190
+ ) AS kids ON kids.parent_id = up.entry_id
191
+ WHERE up.session_id = m.source AND up.seq BETWEEN m.from_seq AND m.to_seq AND ${complete}
192
+ ON CONFLICT (session_id, seq) DO UPDATE SET anchor_seq = excluded.anchor_seq, children = excluded.children, broken = excluded.broken`;
193
+ }
194
+ /**
195
+ * The read that tells whether the links of session `?` from seq `?` on are the ones {@link forkLinkValues} computes,
196
+ * one statement for them all, in one pass over those links (#6560): `seq`, the first row whose anchor or broken mark
197
+ * is not, or null; `children`, whether a row from that seq on has a child stored before it (or names itself as its own
198
+ * parent), whose count {@link materializedForkLinks} and a save may tell apart; and `refs`, whether a snapshot entry's
199
+ * reference names another previous snapshot than its parent's anchor. It reads the rows' links, which name each
200
+ * entry's id and its parent's, so no entry's JSON is parsed: a link without a parent is taken for a root (one whose
201
+ * parent is a value of another type, which no store writes, is linked broken, so the check finds it), and a snapshot
202
+ * entry is its own anchor, as no other entry is. `refs` is the snapshot references' table. Nothing is read until the
203
+ * index's backfill is done (`complete`).
204
+ *
205
+ * When `hasSegments` is false (no segments remain for the session), segment lookups and segment duplicate checks are
206
+ * omitted altogether; parameters are `(sessionId, fromSeq, sessionId, fromSeq)` when `materialize` is true (default),
207
+ * or `(sessionId, fromSeq, sessionId, fromSeq, sessionId, fromSeq)` when `materialize` is false (streamed without a
208
+ * temporary table). When `hasSegments` is true (default), the session's earliest segment `base_seq` is read once to
209
+ * skip segment lookups and duplicate checks for rows before it (and when no segments remain); parameters are
210
+ * `(sessionId, sessionId, fromSeq, sessionId, fromSeq)`.
211
+ */
212
+ export function forkLinksCheck(tables, complete, options = {}) {
213
+ const { links, segments, refs } = tables;
214
+ const hasSegments = options.hasSegments ?? true;
215
+ const materialize = options.materialize ?? true;
216
+ const rows = `(SELECT l.session_id, l.seq, l.entry_id, l.parent_id, CASE WHEN l.parent_id IS NOT NULL THEN 'text' ELSE 'null' END AS parent_type, l.anchor_seq AS own_anchor, l.broken AS own_broken FROM ${links} AS l WHERE l.session_id = ? AND l.seq >= ?)`;
217
+ if (!hasSegments && !materialize) {
218
+ const { parent } = forkLinkValues(links, segments, "r.own_anchor = r.seq", { hasSegments: false });
219
+ const anchor = "CASE WHEN r.own_anchor = r.seq THEN r.seq ELSE par.anchor_seq END";
220
+ const broken = `CASE WHEN ${ownDuplicate(links)} THEN 1 WHEN r.parent_type IS NULL OR r.parent_type = 'null' THEN 0 ELSE COALESCE(par.broken, 1) END`;
221
+ return `SELECT v.seq,
222
+ CASE WHEN v.children = 1 OR EXISTS (SELECT 1 FROM ${links} AS c WHERE c.session_id = ? AND c.seq < ? AND c.parent_id IN (SELECT q.entry_id FROM ${links} AS q WHERE q.session_id = ? AND q.seq >= ?)) THEN 1 ELSE 0 END AS children,
223
+ v.refs
224
+ FROM (SELECT
225
+ min(CASE WHEN COALESCE(r.own_anchor, -1) <> COALESCE(${anchor}, -1) OR r.own_broken <> ${broken} THEN r.seq END) AS seq,
226
+ max(CASE WHEN r.parent_id IS NOT NULL AND (r.parent_id = r.entry_id OR EXISTS (SELECT 1 FROM ${links} AS q WHERE q.session_id = r.session_id AND q.entry_id = r.parent_id AND +q.seq > r.seq)) THEN 1 ELSE 0 END) AS children,
227
+ max(CASE WHEN r.own_anchor = r.seq AND ref.seq IS NOT NULL AND COALESCE(ref.prev_seq, -1) <> COALESCE(par.anchor_seq, -1) THEN 1 ELSE 0 END) AS refs
228
+ FROM ${rows} AS r ${parent} LEFT JOIN ${refs} AS ref ON ref.session_id = r.session_id AND ref.seq = r.seq) AS v
229
+ WHERE ${complete}`;
230
+ }
231
+ const { parent, columns, anchor, broken } = forkLinkValues(links, segments, "r.own_anchor = r.seq", {
232
+ isSnapshotOut: "t.own_anchor = t.seq",
233
+ hasSegments,
234
+ segmentBefore: hasSegments ? "s.first_seg < r.seq" : undefined,
235
+ });
236
+ const fromChecked = hasSegments
237
+ ? `(SELECT min(seg.base_seq) AS first_seg FROM ${segments} AS seg WHERE seg.session_id = ?) AS s CROSS JOIN ${rows} AS r`
238
+ : `${rows} AS r`;
239
+ // Materialize the checked rows once as `t` so that the packed inherited-parent lookup evaluates at most once per row
240
+ // and the earlier-row child probe tests `c.parent_id` against `t.entry_id` without scanning the checked rows again.
241
+ return `WITH t AS MATERIALIZED (
242
+ SELECT r.session_id, r.seq, r.entry_id, r.parent_id, r.parent_type, r.own_anchor, r.own_broken,
243
+ ${columns},
244
+ ref.seq AS ref_seq, ref.prev_seq AS ref_prev
245
+ FROM ${fromChecked} ${parent} LEFT JOIN ${refs} AS ref ON ref.session_id = r.session_id AND ref.seq = r.seq
246
+ )
247
+ SELECT v.seq,
248
+ CASE WHEN v.children = 1 OR EXISTS (SELECT 1 FROM ${links} AS c WHERE c.session_id = ? AND c.seq < ? AND c.parent_id IN (SELECT entry_id FROM t)) THEN 1 ELSE 0 END AS children,
249
+ v.refs
250
+ FROM (SELECT
251
+ min(CASE WHEN COALESCE(t.own_anchor, -1) <> COALESCE(${anchor}, -1) OR t.own_broken <> ${broken} THEN t.seq END) AS seq,
252
+ max(CASE WHEN t.parent_id IS NOT NULL AND (t.parent_id = t.entry_id OR EXISTS (SELECT 1 FROM ${links} AS q WHERE q.session_id = t.session_id AND q.entry_id = t.parent_id AND +q.seq > t.seq)) THEN 1 ELSE 0 END) AS children,
253
+ max(CASE WHEN t.own_anchor = t.seq AND t.ref_seq IS NOT NULL AND COALESCE(t.ref_prev, -1) <> COALESCE(t.par_anchor, -1) THEN 1 ELSE 0 END) AS refs
254
+ FROM t) AS v
255
+ WHERE ${complete}`;
95
256
  }
96
257
  /** Whether `column(name)`'s row is a snapshot entry, whose snapshot the index records. */
97
258
  export function snapshotEntryCondition(d, column) {
@@ -112,10 +273,7 @@ export function entriesIndexComplete(sources) {
112
273
  export function forkLinkWrites(tables, d) {
113
274
  const complete = entriesIndexComplete(tables.sources);
114
275
  const rows = `(SELECT session_id, seq, entry_id, entry_json, ${parentColumns(d, "entry_json")} FROM ${tables.entries} WHERE session_id = ? AND seq = ? AND ${complete})`;
115
- const sql = forkSessionLink(tables.sessionLinks, tables.forkSegments, rows, snapshotEntryCondition(d, (name) => `r.${name}`), true);
116
- return {
117
- entry: (sessionId, seq) => ({ sql, params: [sessionId, seq] }),
118
- materialized: materializedForkLinks(tables.sessionLinks, tables.forkSegments, complete, d.types.int),
119
- };
276
+ const sql = forkSessionLink(tables.sessionLinks, tables.forkSegments, rows, snapshotEntryCondition(d, (name) => `r.${name}`));
277
+ return { entry: (sessionId, seq) => ({ sql, params: [sessionId, seq] }) };
120
278
  }
121
279
  //# sourceMappingURL=fork-snapshot-index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"fork-snapshot-index.js","sourceRoot":"","sources":["../../../src/core/worktree-snapshot/fork-snapshot-index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AAEtE;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAAC,MAAM,GAAG,EAAE;IAC5C,OAAO,iBAAiB,CAAC,MAAM,CAAC,CAAC,YAAY,CAAC;AAC/C,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,0BAA0B,CAAC,OAAe;IACzD,OAAO,GAAG,OAAO,gBAAgB,CAAC;AACnC,CAAC;AAED,+EAA+E;AAC/E,MAAM,UAAU,GAAG,CAAC,KAAa,EAAE,EAAE,CAAC,GAAG,KAAK,eAAe,KAAK,aAAa,KAAK,eAAe,CAAC;AAEpG;;;;;;GAMG;AACH,SAAS,YAAY,CAAC,KAAa,EAAE,QAAgB,EAAE,KAAa,EAAE,MAAc,EAAE,GAAW;IAChG,MAAM,WAAW,GAAG,mBAAmB,MAAM,QAAQ,GAAG,gCAAgC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;IAC3G,MAAM,MAAM,GAAG,GAAG,GAAG,kCAAkC,CAAC;IACxD,MAAM,OAAO,GAAG,oCAAoC,KAAK,8BAA8B,MAAM,gBAAgB,GAAG,8BAA8B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C;AAC7M,CAAC;AAED,0HAA0H;AAC1H,MAAM,UAAU,aAAa,CAAC,CAAiB,EAAE,IAAY;IAC5D,OAAO,GAAG,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC,kBAAkB,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC,iBAAiB,CAAC;AACvG,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,oBAAoB,CAAC,OAAe;IACnD,OAAO,gDAAgD,OAAO,oCAAoC,CAAC;AACpG,CAAC;AA0BD,MAAM,UAAU,cAAc,CAAC,MAAsB,EAAE,CAAiB;IACvE,MAAM,QAAQ,GAAG,oBAAoB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IACtD,MAAM,IAAI,GAAG,kDAAkD,aAAa,CAAC,CAAC,EAAE,YAAY,CAAC,SAAS,MAAM,CAAC,OAAO,yCAAyC,QAAQ,GAAG,CAAC;IACzK,MAAM,GAAG,GAAG,eAAe,CAC1B,MAAM,CAAC,YAAY,EACnB,MAAM,CAAC,YAAY,EACnB,IAAI,EACJ,sBAAsB,CAAC,CAAC,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,IAAI,EAAE,CAAC,EAChD,IAAI,CACJ,CAAC;IACF,OAAO;QACN,KAAK,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,CAAC,SAAS,EAAE,GAAG,CAAC,EAAE,CAAC;QAC9D,YAAY,EAAE,qBAAqB,CAAC,MAAM,CAAC,YAAY,EAAE,MAAM,CAAC,YAAY,EAAE,QAAQ,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC;KACpG,CAAC;AACH,CAAC","sourcesContent":["import type { SqliteStatement } from \"../storage/database.js\";\nimport type { StorageDialect } from \"../storage/dialect.js\";\nimport { sessionForkTables } from \"../storage/session/fork-schema.js\";\n\n/**\n * The fork segments of the sessions under `prefix` (#6560): `(session_id, idx, source_id, from_seq, to_seq, base_seq)`,\n * one row per run of a session's view that another session stores. `atomic storage migrate` creates the table when it\n * turns shared-history forks on; until then no session has a segment.\n */\nexport function forkSegmentsTable(prefix = \"\"): string {\n\treturn sessionForkTables(prefix).forkSegments;\n}\n\n/**\n * The trigger that earlier builds of #6560 installed to link each entry a session with fork segments writes. Each\n * INSERT into the session entries table ran it, a plain session's too, so the store now writes those links itself\n * (`forkEntryLink`, `materializedForkLinks`), and a store's open drops the trigger where it finds it.\n */\nexport function legacyForkLinksTriggerName(entries: string): string {\n\treturn `${entries}_fork_links_v1`;\n}\n\n/** The view seq one past a segment's last, for the segment aliased `alias`. */\nconst segmentEnd = (alias: string) => `${alias}.base_seq + ${alias}.to_seq - ${alias}.from_seq + 1`;\n\n/**\n * The seq in session `child`'s view of the entry at seq `seq` of session `source`'s view, where `source` stores a row\n * `child` inherits. Segments are composed when a fork is made, so a segment's source stores the rows it names itself:\n * `seq` is either a row `source` stores, which a segment of `child` names, or a row `source` inherits, from the source\n * of one of its own segments, which a segment of `child` names by that source. An entry that `child`, or a fork\n * between `source` and `child`, stores itself, such as one a fork edited, is found by its id.\n */\nfunction childViewSeq(links: string, segments: string, child: string, source: string, seq: string): string {\n\tconst inheritedBy = `ss.session_id = ${source} AND ${seq} BETWEEN ss.base_seq + 1 AND ${segmentEnd(\"ss\")}`;\n\tconst stored = `${seq} - ss.base_seq - 1 + ss.from_seq`;\n\tconst entryId = `COALESCE((SELECT a.entry_id FROM ${links} AS a WHERE a.session_id = ${source} AND a.seq = ${seq}), (SELECT a.entry_id FROM ${segments} AS ss JOIN ${links} AS a ON a.session_id = ss.source_id AND a.seq = ${stored} WHERE ${inheritedBy}))`;\n\treturn `COALESCE(\n\t\t(SELECT ${seq} - cs.from_seq + cs.base_seq + 1 FROM ${segments} AS cs WHERE cs.session_id = ${child} AND cs.source_id = ${source} AND ${seq} BETWEEN cs.from_seq AND cs.to_seq),\n\t\t(SELECT ${stored} - cs.from_seq + cs.base_seq + 1 FROM ${segments} AS ss JOIN ${segments} AS cs ON cs.session_id = ${child} AND cs.source_id = ss.source_id AND ${stored} BETWEEN cs.from_seq AND cs.to_seq WHERE ${inheritedBy}),\n\t\t(SELECT own.seq FROM ${links} AS own WHERE own.session_id = ${child} AND own.entry_id = ${entryId} ORDER BY own.seq LIMIT 1),\n\t\t(SELECT x.seq - cs.from_seq + cs.base_seq + 1 FROM ${segments} AS cs JOIN ${links} AS x ON x.session_id = cs.source_id AND x.entry_id = ${entryId} AND x.seq BETWEEN cs.from_seq AND cs.to_seq WHERE cs.session_id = ${child} ORDER BY cs.base_seq, x.seq LIMIT 1)\n\t)`;\n}\n\n/**\n * The statement that indexes the link of one entry of a session with fork segments, as a copy of the session would\n * have it. `rows` yields that entry as `r`, with its parent's id and JSON type as `parent_id` and `parent_type`;\n * `isSnapshot` tells whether `r` is a snapshot entry.\n *\n * The released link statement finds an entry's parent only among the links the session stores, so it marks an entry\n * whose parent the session inherits broken, without an anchor. This one also finds the parent among the links of the\n * rows the session's segments name, and takes the parent's anchor in the session's view. An entry whose id an entry\n * the session inherits also has is broken, as in a copy. It writes over the released statement's row, so it ends the\n * same whichever of the two runs first.\n *\n * With `written`, the store runs it after the statement that inserted the entry, whose rows and segments after it may\n * be there already (#6560): it then reads only the session's rows and segments before the entry, which are what a copy\n * had when it inserted the entry, and leaves the children count to the released statements, which count each child as\n * it is inserted. Without, as the index's backfill runs it, it counts the children an entry written below the\n * session's last row already has, as when a fork's inherited rows are copied into it.\n *\n * The snapshot references of such an entry stay as the released statements index them: a reference's `prev_seq` that\n * would name an inherited entry is empty. Collection walks a session's references only through the rows the session\n * stores, and keeps every snapshot record a segment names (see `SqlSnapshotBlobStore.sweep`), so it never needs it.\n */\nexport function forkSessionLink(\n\tlinks: string,\n\tsegments: string,\n\trows: string,\n\tisSnapshot: string,\n\twritten = false,\n): string {\n\tconst before = (alias: string) => (written ? ` AND ${alias}.seq < r.seq` : \"\");\n\tconst segmentBefore = written ? \" AND seg.base_seq < r.seq\" : \"\";\n\tconst own = (column: string) =>\n\t\t`(SELECT p.${column} FROM ${links} AS p WHERE p.session_id = r.session_id AND p.entry_id = r.parent_id AND r.parent_type = 'text'${before(\"p\")} ORDER BY p.seq LIMIT 1)`;\n\tconst ownParent = `EXISTS (SELECT 1 FROM ${links} AS p WHERE p.session_id = r.session_id AND p.entry_id = r.parent_id AND r.parent_type = 'text'${before(\"p\")})`;\n\tconst inherited = (select: string) =>\n\t\t`(SELECT ${select} FROM ${segments} AS seg JOIN ${links} AS up ON up.session_id = seg.source_id AND up.entry_id = r.parent_id AND up.seq BETWEEN seg.from_seq AND seg.to_seq WHERE seg.session_id = r.session_id AND r.parent_type = 'text'${segmentBefore} ORDER BY seg.base_seq, up.seq LIMIT 1)`;\n\tconst anchor = `CASE WHEN up.anchor_seq IS NOT NULL THEN ${childViewSeq(links, segments, \"r.session_id\", \"up.session_id\", \"up.anchor_seq\")} END`;\n\tconst duplicate = `EXISTS (SELECT 1 FROM ${links} AS other WHERE other.session_id = r.session_id AND other.entry_id = r.entry_id AND other.seq <> r.seq${before(\"other\")}) OR EXISTS (SELECT 1 FROM ${segments} AS seg JOIN ${links} AS other ON other.session_id = seg.source_id AND other.entry_id = r.entry_id AND other.seq BETWEEN seg.from_seq AND seg.to_seq WHERE seg.session_id = r.session_id${segmentBefore})`;\n\tconst children = written\n\t\t? \"0\"\n\t\t: `CASE WHEN EXISTS (SELECT 1 FROM ${links} AS later WHERE later.session_id = r.session_id AND later.seq > r.seq) THEN (SELECT count(*) FROM ${links} AS c WHERE c.session_id = r.session_id AND c.parent_id = r.entry_id AND c.seq <> r.seq) ELSE 0 END`;\n\treturn `INSERT INTO ${links} (session_id, seq, entry_id, parent_id, anchor_seq, children, broken)\n\t\tSELECT r.session_id, r.seq, r.entry_id, CASE WHEN r.parent_type = 'text' THEN r.parent_id END,\n\t\t\tCASE WHEN ${isSnapshot} THEN r.seq WHEN ${ownParent} THEN ${own(\"anchor_seq\")} ELSE ${inherited(anchor)} END,\n\t\t\t${children},\n\t\t\tCASE WHEN ${duplicate} THEN 1 WHEN r.parent_type IS NULL OR r.parent_type = 'null' THEN 0 WHEN ${ownParent} THEN ${own(\"broken\")} ELSE COALESCE(${inherited(\"up.broken\")}, 1) END\n\t\tFROM ${rows} AS r WHERE EXISTS (SELECT 1 FROM ${segments} AS any_segment WHERE any_segment.session_id = r.session_id)\n\t\tON CONFLICT (session_id, seq) DO UPDATE SET anchor_seq = excluded.anchor_seq, ${written ? \"\" : \"children = excluded.children, \"}broken = excluded.broken`;\n}\n\n/**\n * The statement that links the rows a materialization just copied into a fork (#6560), one piece of one source at a\n * time, all of them in one statement: each row is linked as its source links it, its anchor taken into the fork's\n * view, and its children counted among the rows the fork now stores. It runs after the piece's rows are inserted and\n * before the fork's segments lose the piece, so they still map the source's seqs. `complete` is the condition that the\n * index's backfill is done: until then the backfill links the rows. Parameters: the fork's id, the shift from the\n * source's seqs to the fork's, the source's id, the first and last seq of the piece in the source, and the fork's id.\n */\nexport function materializedForkLinks(links: string, segments: string, complete: string, int: string): string {\n\tconst anchor = `CASE WHEN up.anchor_seq IS NOT NULL THEN ${childViewSeq(links, segments, \"m.child\", \"up.session_id\", \"up.anchor_seq\")} END`;\n\treturn `INSERT INTO ${links} (session_id, seq, entry_id, parent_id, anchor_seq, children, broken)\n\t\tSELECT m.child, up.seq + m.shift, up.entry_id, up.parent_id, ${anchor}, COALESCE(kids.n, 0), up.broken\n\t\tFROM (SELECT CAST(? AS text) AS child, CAST(? AS ${int}) AS shift) AS m\n\t\tJOIN ${links} AS up ON up.session_id = ? AND up.seq BETWEEN ? AND ?\n\t\tLEFT JOIN (SELECT parent_id, count(*) AS n FROM ${links} WHERE session_id = ? GROUP BY parent_id) AS kids ON kids.parent_id = up.entry_id\n\t\tWHERE ${complete}\n\t\tON CONFLICT (session_id, seq) DO UPDATE SET anchor_seq = excluded.anchor_seq, children = excluded.children, broken = excluded.broken`;\n}\n\n/** Whether `column(name)`'s row is a snapshot entry, whose snapshot the index records. */\nexport function snapshotEntryCondition(d: StorageDialect, column: (name: string) => string): string {\n\tconst entry = column(\"entry_json\");\n\treturn `${d.contains(entry, `'\"worktree_snapshot\"'`)} AND ${d.jsonText(entry, \"type\")} = 'worktree_snapshot' AND ${d.jsonHasType(\"text\", entry, \"root\")} AND ${d.jsonHasType(\"text\", entry, \"snapshotId\")}`;\n}\n\n/** The columns of one entry as `r` that name its parent once, so a statement parses the entry's JSON for it only once. */\nexport function parentColumns(d: StorageDialect, json: string): string {\n\treturn `${d.jsonText(json, \"parentId\")} AS parent_id, ${d.jsonType(json, \"parentId\")} AS parent_type`;\n}\n\n/**\n * Whether the session entries' index is complete, by its progress row in `sources`: until then their backfill indexes\n * what the triggers and the session store do not.\n */\nexport function entriesIndexComplete(sources: string): string {\n\treturn `(SELECT backfilled_through >= watermark FROM ${sources} WHERE source = 'session-entries')`;\n}\n\n/** The tables {@link forkLinkWrites} reads and writes. */\nexport interface ForkLinkTables {\n\t/** The session entries. */\n\treadonly entries: string;\n\t/** The snapshot index's session links and progress rows. */\n\treadonly sessionLinks: string;\n\treadonly sources: string;\n\treadonly forkSegments: string;\n}\n\n/**\n * The statements with which a session store links the entries a session with fork segments stores (#6560). The\n * released triggers, which every entry runs, link an entry whose parent the session inherits as broken, without an\n * anchor, and an entry below it the same; so the store writes the link over theirs in the transaction that writes the\n * entry, behind it and the entries before it, in seq order. A plain session's writes run none of them. Each waits for\n * the index's backfill, which links what they would.\n */\nexport interface ForkLinkWrites {\n\t/** The link of the entry at `seq` of session `sessionId`, run after the statements that wrote it. */\n\tentry(sessionId: string, seq: number): SqliteStatement;\n\t/** The links of a piece a materialization copied into a fork, in one statement: see {@link materializedForkLinks}. */\n\treadonly materialized: string;\n}\n\nexport function forkLinkWrites(tables: ForkLinkTables, d: StorageDialect): ForkLinkWrites {\n\tconst complete = entriesIndexComplete(tables.sources);\n\tconst rows = `(SELECT session_id, seq, entry_id, entry_json, ${parentColumns(d, \"entry_json\")} FROM ${tables.entries} WHERE session_id = ? AND seq = ? AND ${complete})`;\n\tconst sql = forkSessionLink(\n\t\ttables.sessionLinks,\n\t\ttables.forkSegments,\n\t\trows,\n\t\tsnapshotEntryCondition(d, (name) => `r.${name}`),\n\t\ttrue,\n\t);\n\treturn {\n\t\tentry: (sessionId, seq) => ({ sql, params: [sessionId, seq] }),\n\t\tmaterialized: materializedForkLinks(tables.sessionLinks, tables.forkSegments, complete, d.types.int),\n\t};\n}\n"]}
1
+ {"version":3,"file":"fork-snapshot-index.js","sourceRoot":"","sources":["../../../src/core/worktree-snapshot/fork-snapshot-index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AAEtE;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAAC,MAAM,GAAG,EAAE;IAC5C,OAAO,iBAAiB,CAAC,MAAM,CAAC,CAAC,YAAY,CAAC;AAC/C,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,0BAA0B,CAAC,OAAe;IACzD,OAAO,GAAG,OAAO,gBAAgB,CAAC;AACnC,CAAC;AAED,+EAA+E;AAC/E,MAAM,UAAU,GAAG,CAAC,KAAa,EAAE,EAAE,CAAC,GAAG,KAAK,eAAe,KAAK,aAAa,KAAK,eAAe,CAAC;AAEpG;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,KAAa;IACzC,qGAAqG;IACrG,OAAO,4BAA4B,KAAK,qHAAqH,CAAC;AAC/J,CAAC;AAED,iHAAiH;AACjH,MAAM,UAAU,YAAY,CAAC,KAAa;IACzC,OAAO,yBAAyB,KAAK,yGAAyG,CAAC;AAChJ,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,YAAY,CACpB,KAAa,EACb,QAAgB,EAChB,KAAa,EACb,MAAc,EACd,GAAW,EACX,KAAa;IAEb,MAAM,WAAW,GAAG,mBAAmB,MAAM,QAAQ,GAAG,gCAAgC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;I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,EAAE,IAAY;IAC5D,OAAO,GAAG,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC,kBAAkB,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC,iBAAiB,CAAC;AACvG,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,oBAAoB,CAAC,OAAe;IACnD,OAAO,gDAAgD,OAAO,oCAAoC,CAAC;AACpG,CAAC;AAwBD,MAAM,UAAU,cAAc,CAAC,MAAsB,EAAE,CAAiB;IACvE,MAAM,QAAQ,GAAG,oBAAoB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IACtD,MAAM,IAAI,GAAG,kDAAkD,aAAa,CAAC,CAAC,EAAE,YAAY,CAAC,SAAS,MAAM,CAAC,OAAO,yCAAyC,QAAQ,GAAG,CAAC;IACzK,MAAM,GAAG,GAAG,eAAe,CAC1B,MAAM,CAAC,YAAY,EACnB,MAAM,CAAC,YAAY,EACnB,IAAI,EACJ,sBAAsB,CAAC,CAAC,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,IAAI,EAAE,CAAC,CAChD,CAAC;IACF,OAAO,EAAE,KAAK,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,CAAC,SAAS,EAAE,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC;AAC3E,CAAC","sourcesContent":["import type { SqliteStatement } from \"../storage/database.js\";\nimport type { StorageDialect } from \"../storage/dialect.js\";\nimport { sessionForkTables } from \"../storage/session/fork-schema.js\";\n\n/**\n * The fork segments of the sessions under `prefix` (#6560): `(session_id, idx, source_id, from_seq, to_seq, base_seq)`,\n * one row per run of a session's view that another session stores. `atomic storage migrate` creates the table when it\n * turns shared-history forks on; until then no session has a segment.\n */\nexport function forkSegmentsTable(prefix = \"\"): string {\n\treturn sessionForkTables(prefix).forkSegments;\n}\n\n/**\n * The trigger that earlier builds of #6560 installed to link each entry a session with fork segments writes. Each\n * INSERT into the session entries table ran it, a plain session's too, so the store now writes those links itself\n * (`forkLinkWrites`, `materializedForkLinks`), and a store's open drops the trigger where it finds it.\n */\nexport function legacyForkLinksTriggerName(entries: string): string {\n\treturn `${entries}_fork_links_v1`;\n}\n\n/** The view seq one past a segment's last, for the segment aliased `alias`. */\nconst segmentEnd = (alias: string) => `${alias}.base_seq + ${alias}.to_seq - ${alias}.from_seq + 1`;\n\n/**\n * The seq of the link that is the parent of entry `r` among the links its session stores, or null: of the links before\n * `r` with the parent's id, the first. `r` has the columns {@link parentColumns} names. A save and a rebuild of the\n * index both link an entry with this lookup, so an entry whose parent is written after it, or whose parent's id more\n * than one entry has, is linked the same by both (#6560).\n */\nexport function ownParentSeq(links: string): string {\n\t// `+seq`: the lookup goes by the entry's id, never in seq order, which SQLite would read row by row.\n\treturn `(SELECT min(+p.seq) FROM ${links} AS p WHERE p.session_id = r.session_id AND p.entry_id = r.parent_id AND r.parent_type = 'text' AND +p.seq < r.seq)`;\n}\n\n/** Whether a link before entry `r` in its session has `r`'s id: such an entry is linked broken, as in a copy. */\nexport function ownDuplicate(links: string): string {\n\treturn `EXISTS (SELECT 1 FROM ${links} AS other WHERE other.session_id = r.session_id AND other.entry_id = r.entry_id AND +other.seq < r.seq)`;\n}\n\n/**\n * The seq in session `child`'s view of the entry at seq `seq` of session `source`'s view, where `source` stores a row\n * `child` inherits. Segments are composed when a fork is made, so a segment's source stores the rows it names itself:\n * `seq` is either a row `source` stores, which a segment of `child` names, or a row `source` inherits, from the source\n * of one of its own segments, which a segment of `child` names by that source. An entry that `child`, or a fork\n * between `source` and `child`, stores itself, such as one a fork edited, is found by its id among the rows of\n * `child`'s view before `bound`, the entry being linked.\n */\nfunction childViewSeq(\n\tlinks: string,\n\tsegments: string,\n\tchild: string,\n\tsource: string,\n\tseq: string,\n\tbound: string,\n): string {\n\tconst inheritedBy = `ss.session_id = ${source} AND ${seq} BETWEEN ss.base_seq + 1 AND ${segmentEnd(\"ss\")}`;\n\tconst stored = `${seq} - ss.base_seq - 1 + ss.from_seq`;\n\tconst entryId = `COALESCE((SELECT a.entry_id FROM ${links} AS a WHERE a.session_id = ${source} AND a.seq = ${seq}), (SELECT a.entry_id FROM ${segments} AS ss JOIN ${links} AS a ON a.session_id = ss.source_id AND a.seq = ${stored} WHERE ${inheritedBy}))`;\n\treturn `COALESCE(\n\t\t(SELECT ${seq} - cs.from_seq + cs.base_seq + 1 FROM ${segments} AS cs WHERE cs.session_id = ${child} AND cs.source_id = ${source} AND ${seq} BETWEEN cs.from_seq AND cs.to_seq),\n\t\t(SELECT ${stored} - cs.from_seq + cs.base_seq + 1 FROM ${segments} AS ss JOIN ${segments} AS cs ON cs.session_id = ${child} AND cs.source_id = ss.source_id AND ${stored} BETWEEN cs.from_seq AND cs.to_seq WHERE ${inheritedBy}),\n\t\t(SELECT min(+own.seq) FROM ${links} AS own WHERE own.session_id = ${child} AND own.entry_id = ${entryId} AND +own.seq < ${bound}),\n\t\t(SELECT x.seq - cs.from_seq + cs.base_seq + 1 FROM ${segments} AS cs JOIN ${links} AS x ON x.session_id = cs.source_id AND x.entry_id = ${entryId} AND +x.seq BETWEEN cs.from_seq AND cs.to_seq WHERE cs.session_id = ${child} AND cs.base_seq < ${bound} ORDER BY cs.base_seq, x.seq LIMIT 1)\n\t)`;\n}\n\n/**\n * The statement that links one entry of a session with fork segments, as a copy of the session would have it. `rows`\n * yields that entry as `r`, with its parent's id and JSON type as `parent_id` and `parent_type`; `isSnapshot` tells\n * whether `r` is a snapshot entry. It runs after the released link statement of the entry, and writes over that row's\n * anchor and broken mark; the released statements keep the children count.\n *\n * The released link statement finds an entry's parent only among the links the session stores, so it marks an entry\n * whose parent the session inherits broken, without an anchor. This one also finds the parent among the links of the\n * rows the session's segments name, and takes the parent's anchor in the session's view. An entry whose id an entry\n * the session inherits also has is broken, as in a copy.\n *\n * It reads only the rows of the session's view before the entry, the links the session stores and those its segments\n * name, as a copy had when it inserted the entry: a parent written after its child, or an entry of the same id after\n * it, changes nothing. A save runs it as it writes an entry, the index's rebuild as it links a stored row again, and\n * both meet the rows before the entry linked already (`relinkSessionEntries`), so both link every entry the same\n * (#6560).\n *\n * The snapshot references of such an entry stay as the released statements index them: a reference's `prev_seq` that\n * would name an inherited entry is empty. Collection walks a session's references only through the rows the session\n * stores, and keeps every snapshot record a segment names (see `SqlSnapshotBlobStore.sweep`), so it never needs it.\n */\nexport function forkSessionLink(links: string, segments: string, rows: string, isSnapshot: string): string {\n\tconst { parent, columns, anchor, broken } = forkLinkValues(links, segments, isSnapshot, {\n\t\tisSnapshotOut: \"t.is_snapshot = 1\",\n\t});\n\treturn `INSERT INTO ${links} (session_id, seq, entry_id, parent_id, anchor_seq, children, broken)\n\t\tSELECT t.session_id, t.seq, t.entry_id, CASE WHEN t.parent_type = 'text' THEN t.parent_id END, ${anchor}, 0, ${broken}\n\t\tFROM (SELECT r.session_id, r.seq, r.entry_id, r.parent_id, r.parent_type,\n\t\t\tCASE WHEN ${isSnapshot} THEN 1 ELSE 0 END AS is_snapshot,\n\t\t\t${columns}\n\t\t\tFROM ${rows} AS r ${parent}\n\t\t\tWHERE EXISTS (SELECT 1 FROM ${segments} AS any_segment WHERE any_segment.session_id = r.session_id)) AS t\n\t\tWHERE true\n\t\tON CONFLICT (session_id, seq) DO UPDATE SET anchor_seq = excluded.anchor_seq, broken = excluded.broken`;\n}\n\n/**\n * The anchor and the broken mark of entry `r` as {@link forkSessionLink} links it, from the links before it, its\n * session's and those its segments name: the one function a save, the index's rebuild and the check of a\n * materialization's links ({@link forkLinksCheck}) all compute them with (#6560). For a session without segments it\n * is what the released link statement writes.\n *\n * `parent` is the join that follows `r` in the inner SELECT's FROM: it finds `r`'s parent among the links its session\n * stores ({@link ownParentSeq}) once, as `par`. `columns` projects `par`, the duplicate check and—when segments may\n * exist—a single inherited-parent lookup packing `(COALESCE(anchor + 1, 0) * 2 + broken)` into `inh`, so a row whose\n * parent comes from a segment looks the segment up once for both `anchor` and `broken`. The outer SELECT aliases that\n * projection as `t` and evaluates `anchor` and `broken`.\n */\nexport function forkLinkValues(\n\tlinks: string,\n\tsegments: string,\n\tisSnapshot: string,\n\toptions: {\n\t\treadonly isSnapshotOut?: string;\n\t\treadonly hasSegments?: boolean;\n\t\treadonly segmentBefore?: string;\n\t} = {},\n): {\n\treadonly parent: string;\n\treadonly columns: string;\n\treadonly anchor: string;\n\treadonly broken: string;\n} {\n\tconst isSnapshotOut = options.isSnapshotOut ?? isSnapshot;\n\tconst hasSegments = options.hasSegments ?? true;\n\tconst segmentBefore = options.segmentBefore;\n\t// The first link with the parent's id, if it is before `r`: the link `ownParentSeq` finds, joined as a plain row, so\n\t// that no lookup is a join key the database computes for each comparison.\n\tconst parent = `LEFT JOIN ${links} AS par ON par.session_id = r.session_id AND par.entry_id = r.parent_id AND r.parent_type = 'text' AND +par.seq < r.seq AND NOT EXISTS (SELECT 1 FROM ${links} AS earlier WHERE earlier.session_id = par.session_id AND earlier.entry_id = par.entry_id AND +earlier.seq < par.seq)`;\n\tif (!hasSegments) {\n\t\treturn {\n\t\t\tparent,\n\t\t\tcolumns: `par.anchor_seq AS par_anchor, par.broken AS par_broken, CASE WHEN ${ownDuplicate(links)} THEN 1 ELSE 0 END AS dup`,\n\t\t\tanchor: `CASE WHEN ${isSnapshotOut} THEN t.seq ELSE t.par_anchor END`,\n\t\t\tbroken: `CASE WHEN t.dup = 1 THEN 1 WHEN t.parent_type IS NULL OR t.parent_type = 'null' THEN 0 ELSE COALESCE(t.par_broken, 1) END`,\n\t\t};\n\t}\n\tconst inhAnchor = `CASE WHEN ${isSnapshot} THEN 0 WHEN up.anchor_seq IS NOT NULL THEN COALESCE(${childViewSeq(links, segments, \"r.session_id\", \"up.session_id\", \"up.anchor_seq\", \"r.seq\")} + 1, 0) ELSE 0 END`;\n\tconst inhSub = `(SELECT ${inhAnchor} * 2 + up.broken FROM ${segments} AS seg JOIN ${links} AS up ON up.session_id = seg.source_id AND up.entry_id = r.parent_id AND +up.seq BETWEEN seg.from_seq AND seg.to_seq WHERE seg.session_id = r.session_id AND seg.base_seq < r.seq ORDER BY seg.base_seq, up.seq LIMIT 1)`;\n\tconst inherited =\n\t\tsegmentBefore === undefined\n\t\t\t? `CASE WHEN par.seq IS NULL AND r.parent_type = 'text' THEN ${inhSub} END`\n\t\t\t: `CASE WHEN par.seq IS NULL AND r.parent_type = 'text' THEN CASE WHEN ${segmentBefore} THEN ${inhSub} END END`;\n\tconst segDupExists = `EXISTS (SELECT 1 FROM ${segments} AS seg JOIN ${links} AS other ON other.session_id = seg.source_id AND other.entry_id = r.entry_id AND +other.seq BETWEEN seg.from_seq AND seg.to_seq WHERE seg.session_id = r.session_id AND seg.base_seq < r.seq)`;\n\tconst segDup =\n\t\tsegmentBefore === undefined\n\t\t\t? `CASE WHEN ${segDupExists} THEN 1 ELSE 0 END`\n\t\t\t: `CASE WHEN ${segmentBefore} THEN CASE WHEN ${segDupExists} THEN 1 ELSE 0 END ELSE 0 END`;\n\treturn {\n\t\tparent,\n\t\tcolumns: `par.seq AS par_seq, par.anchor_seq AS par_anchor, par.broken AS par_broken, ${inherited} AS inh, CASE WHEN ${ownDuplicate(links)} THEN 1 ELSE ${segDup} END AS dup`,\n\t\tanchor: `CASE WHEN ${isSnapshotOut} THEN t.seq WHEN t.par_seq IS NOT NULL THEN t.par_anchor ELSE NULLIF(t.inh / 2, 0) - 1 END`,\n\t\tbroken: `CASE WHEN t.dup = 1 THEN 1 WHEN t.parent_type IS NULL OR t.parent_type = 'null' THEN 0 WHEN t.par_seq IS NOT NULL THEN t.par_broken ELSE COALESCE(t.inh % 2, 1) END`,\n\t};\n}\n\n/**\n * The statement that links the rows a materialization just copied into a fork (#6560), one piece of one source at a\n * time, all of them in one statement: each row is linked as its source links it, its anchor taken into the fork's\n * view, and its children counted among the rows the fork now stores past the piece's start whose parent ID the piece\n * names. It runs after the piece's rows are inserted and before the fork's segments lose the piece, so they still map\n * the source's seqs. These links are what {@link forkLinkValues} computes for every history but a few:\n * {@link forkLinksCheck} tells, once the segments lost the pieces, and the fork is linked again row by row where it\n * does not hold. `complete` is the condition that the index's backfill is done: until then the backfill links the rows.\n * Parameters (bound in the leading CTE so the order stays fixed across mixed versions): the fork's id, the shift from\n * the source's seqs to the fork's, the source's id, the first and last seq of the piece in the source, and the fork's\n * id.\n */\nexport function materializedForkLinks(\n\tlinks: string,\n\tsegments: string,\n\tcomplete: string,\n\tint: string,\n\tdialectName?: StorageDialect[\"name\"],\n): string {\n\tconst mCte = `WITH m AS (\n\t\tSELECT CAST(? AS text) AS child, CAST(? AS ${int}) AS shift,\n\t\t\tCAST(? AS text) AS source, CAST(? AS ${int}) AS from_seq, CAST(? AS ${int}) AS to_seq,\n\t\t\tCAST(? AS text) AS kids_child\n\t)`;\n\tif (dialectName === \"postgres\") {\n\t\tconst anchor = `CASE WHEN counted.anchor_seq IS NOT NULL THEN ${childViewSeq(links, segments, \"counted.child\", \"counted.session_id\", \"counted.anchor_seq\", \"counted.seq + counted.shift\")} END`;\n\t\t// On PostgreSQL, unioning the piece's rows (is_kid = 0) with the fork's later links (is_kid = 1) and summing over\n\t\t// PARTITION BY entry_id avoids a LEFT JOIN on an aggregated subquery, which PostgreSQL can plan as a quadratic\n\t\t// nested loop on fresh tables whose statistics have not been analyzed yet.\n\t\treturn `${mCte},\n\tcounted AS (\n\t\tSELECT child, shift, session_id, seq, entry_id, parent_id, anchor_seq, broken, is_kid,\n\t\t\tsum(is_kid) OVER (PARTITION BY entry_id) AS n\n\t\tFROM (\n\t\t\tSELECT m.child, m.shift, up.session_id, up.seq, up.entry_id, up.parent_id, up.anchor_seq, up.broken, 0 AS is_kid\n\t\t\tFROM m CROSS JOIN ${links} AS up\n\t\t\tWHERE up.session_id = m.source AND up.seq BETWEEN m.from_seq AND m.to_seq\n\t\t\tUNION ALL\n\t\t\tSELECT NULL, NULL, NULL, NULL, l.parent_id, NULL, NULL, NULL, 1 AS is_kid\n\t\t\tFROM m CROSS JOIN ${links} AS l\n\t\t\tWHERE l.session_id = m.kids_child AND l.seq > m.from_seq + m.shift AND l.parent_id IS NOT NULL\n\t\t) AS u\n\t)\n\tINSERT INTO ${links} (session_id, seq, entry_id, parent_id, anchor_seq, children, broken)\n\tSELECT counted.child, counted.seq + counted.shift, counted.entry_id, counted.parent_id, ${anchor}, counted.n, counted.broken\n\tFROM counted\n\tWHERE counted.is_kid = 0 AND ${complete}\n\tON CONFLICT (session_id, seq) DO UPDATE SET anchor_seq = excluded.anchor_seq, children = excluded.children, broken = excluded.broken`;\n\t}\n\tconst anchor = `CASE WHEN up.anchor_seq IS NOT NULL THEN ${childViewSeq(links, segments, \"m.child\", \"up.session_id\", \"up.anchor_seq\", \"up.seq + m.shift\")} END`;\n\treturn `${mCte}\n\tINSERT INTO ${links} (session_id, seq, entry_id, parent_id, anchor_seq, children, broken)\n\tSELECT m.child, up.seq + m.shift, up.entry_id, up.parent_id, ${anchor}, COALESCE(kids.n, 0), up.broken\n\tFROM m\n\tCROSS JOIN ${links} AS up\n\tLEFT JOIN (\n\t\tSELECT l.parent_id, count(*) AS n\n\t\tFROM m AS km\n\t\tCROSS JOIN ${links} AS l\n\t\tWHERE l.session_id = km.kids_child AND l.seq > km.from_seq + km.shift\n\t\t\tAND l.parent_id IN (\n\t\t\t\tSELECT p.entry_id FROM m AS pm CROSS JOIN ${links} AS p\n\t\t\t\tWHERE p.session_id = pm.source AND p.seq BETWEEN pm.from_seq AND pm.to_seq\n\t\t\t)\n\t\tGROUP BY l.parent_id\n\t) AS kids ON kids.parent_id = up.entry_id\n\tWHERE up.session_id = m.source AND up.seq BETWEEN m.from_seq AND m.to_seq AND ${complete}\n\tON CONFLICT (session_id, seq) DO UPDATE SET anchor_seq = excluded.anchor_seq, children = excluded.children, broken = excluded.broken`;\n}\n\n/**\n * The read that tells whether the links of session `?` from seq `?` on are the ones {@link forkLinkValues} computes,\n * one statement for them all, in one pass over those links (#6560): `seq`, the first row whose anchor or broken mark\n * is not, or null; `children`, whether a row from that seq on has a child stored before it (or names itself as its own\n * parent), whose count {@link materializedForkLinks} and a save may tell apart; and `refs`, whether a snapshot entry's\n * reference names another previous snapshot than its parent's anchor. It reads the rows' links, which name each\n * entry's id and its parent's, so no entry's JSON is parsed: a link without a parent is taken for a root (one whose\n * parent is a value of another type, which no store writes, is linked broken, so the check finds it), and a snapshot\n * entry is its own anchor, as no other entry is. `refs` is the snapshot references' table. Nothing is read until the\n * index's backfill is done (`complete`).\n *\n * When `hasSegments` is false (no segments remain for the session), segment lookups and segment duplicate checks are\n * omitted altogether; parameters are `(sessionId, fromSeq, sessionId, fromSeq)` when `materialize` is true (default),\n * or `(sessionId, fromSeq, sessionId, fromSeq, sessionId, fromSeq)` when `materialize` is false (streamed without a\n * temporary table). When `hasSegments` is true (default), the session's earliest segment `base_seq` is read once to\n * skip segment lookups and duplicate checks for rows before it (and when no segments remain); parameters are\n * `(sessionId, sessionId, fromSeq, sessionId, fromSeq)`.\n */\nexport function forkLinksCheck(\n\ttables: { readonly links: string; readonly segments: string; readonly refs: string },\n\tcomplete: string,\n\toptions: { readonly hasSegments?: boolean; readonly materialize?: boolean } = {},\n): string {\n\tconst { links, segments, refs } = tables;\n\tconst hasSegments = options.hasSegments ?? true;\n\tconst materialize = options.materialize ?? true;\n\tconst rows = `(SELECT l.session_id, l.seq, l.entry_id, l.parent_id, CASE WHEN l.parent_id IS NOT NULL THEN 'text' ELSE 'null' END AS parent_type, l.anchor_seq AS own_anchor, l.broken AS own_broken FROM ${links} AS l WHERE l.session_id = ? AND l.seq >= ?)`;\n\tif (!hasSegments && !materialize) {\n\t\tconst { parent } = forkLinkValues(links, segments, \"r.own_anchor = r.seq\", { hasSegments: false });\n\t\tconst anchor = \"CASE WHEN r.own_anchor = r.seq THEN r.seq ELSE par.anchor_seq END\";\n\t\tconst broken = `CASE WHEN ${ownDuplicate(links)} THEN 1 WHEN r.parent_type IS NULL OR r.parent_type = 'null' THEN 0 ELSE COALESCE(par.broken, 1) END`;\n\t\treturn `SELECT v.seq,\n\t\t\tCASE WHEN v.children = 1 OR EXISTS (SELECT 1 FROM ${links} AS c WHERE c.session_id = ? AND c.seq < ? AND c.parent_id IN (SELECT q.entry_id FROM ${links} AS q WHERE q.session_id = ? AND q.seq >= ?)) THEN 1 ELSE 0 END AS children,\n\t\t\tv.refs\n\t\tFROM (SELECT\n\t\t\tmin(CASE WHEN COALESCE(r.own_anchor, -1) <> COALESCE(${anchor}, -1) OR r.own_broken <> ${broken} THEN r.seq END) AS seq,\n\t\t\tmax(CASE WHEN r.parent_id IS NOT NULL AND (r.parent_id = r.entry_id OR EXISTS (SELECT 1 FROM ${links} AS q WHERE q.session_id = r.session_id AND q.entry_id = r.parent_id AND +q.seq > r.seq)) THEN 1 ELSE 0 END) AS children,\n\t\t\tmax(CASE WHEN r.own_anchor = r.seq AND ref.seq IS NOT NULL AND COALESCE(ref.prev_seq, -1) <> COALESCE(par.anchor_seq, -1) THEN 1 ELSE 0 END) AS refs\n\t\t\tFROM ${rows} AS r ${parent} LEFT JOIN ${refs} AS ref ON ref.session_id = r.session_id AND ref.seq = r.seq) AS v\n\t\tWHERE ${complete}`;\n\t}\n\tconst { parent, columns, anchor, broken } = forkLinkValues(links, segments, \"r.own_anchor = r.seq\", {\n\t\tisSnapshotOut: \"t.own_anchor = t.seq\",\n\t\thasSegments,\n\t\tsegmentBefore: hasSegments ? \"s.first_seg < r.seq\" : undefined,\n\t});\n\tconst fromChecked = hasSegments\n\t\t? `(SELECT min(seg.base_seq) AS first_seg FROM ${segments} AS seg WHERE seg.session_id = ?) AS s CROSS JOIN ${rows} AS r`\n\t\t: `${rows} AS r`;\n\t// Materialize the checked rows once as `t` so that the packed inherited-parent lookup evaluates at most once per row\n\t// and the earlier-row child probe tests `c.parent_id` against `t.entry_id` without scanning the checked rows again.\n\treturn `WITH t AS MATERIALIZED (\n\t\tSELECT r.session_id, r.seq, r.entry_id, r.parent_id, r.parent_type, r.own_anchor, r.own_broken,\n\t\t\t${columns},\n\t\t\tref.seq AS ref_seq, ref.prev_seq AS ref_prev\n\t\tFROM ${fromChecked} ${parent} LEFT JOIN ${refs} AS ref ON ref.session_id = r.session_id AND ref.seq = r.seq\n\t)\n\tSELECT v.seq,\n\t\tCASE WHEN v.children = 1 OR EXISTS (SELECT 1 FROM ${links} AS c WHERE c.session_id = ? AND c.seq < ? AND c.parent_id IN (SELECT entry_id FROM t)) THEN 1 ELSE 0 END AS children,\n\t\tv.refs\n\tFROM (SELECT\n\t\tmin(CASE WHEN COALESCE(t.own_anchor, -1) <> COALESCE(${anchor}, -1) OR t.own_broken <> ${broken} THEN t.seq END) AS seq,\n\t\tmax(CASE WHEN t.parent_id IS NOT NULL AND (t.parent_id = t.entry_id OR EXISTS (SELECT 1 FROM ${links} AS q WHERE q.session_id = t.session_id AND q.entry_id = t.parent_id AND +q.seq > t.seq)) THEN 1 ELSE 0 END) AS children,\n\t\tmax(CASE WHEN t.own_anchor = t.seq AND t.ref_seq IS NOT NULL AND COALESCE(t.ref_prev, -1) <> COALESCE(t.par_anchor, -1) THEN 1 ELSE 0 END) AS refs\n\t\tFROM t) AS v\n\tWHERE ${complete}`;\n}\n\n/** Whether `column(name)`'s row is a snapshot entry, whose snapshot the index records. */\nexport function snapshotEntryCondition(d: StorageDialect, column: (name: string) => string): string {\n\tconst entry = column(\"entry_json\");\n\treturn `${d.contains(entry, `'\"worktree_snapshot\"'`)} AND ${d.jsonText(entry, \"type\")} = 'worktree_snapshot' AND ${d.jsonHasType(\"text\", entry, \"root\")} AND ${d.jsonHasType(\"text\", entry, \"snapshotId\")}`;\n}\n\n/** The columns of one entry as `r` that name its parent once, so a statement parses the entry's JSON for it only once. */\nexport function parentColumns(d: StorageDialect, json: string): string {\n\treturn `${d.jsonText(json, \"parentId\")} AS parent_id, ${d.jsonType(json, \"parentId\")} AS parent_type`;\n}\n\n/**\n * Whether the session entries' index is complete, by its progress row in `sources`: until then their backfill indexes\n * what the triggers and the session store do not.\n */\nexport function entriesIndexComplete(sources: string): string {\n\treturn `(SELECT backfilled_through >= watermark FROM ${sources} WHERE source = 'session-entries')`;\n}\n\n/** The tables {@link forkLinkWrites} reads and writes. */\nexport interface ForkLinkTables {\n\t/** The session entries. */\n\treadonly entries: string;\n\t/** The snapshot index's session links and progress rows. */\n\treadonly sessionLinks: string;\n\treadonly sources: string;\n\treadonly forkSegments: string;\n}\n\n/**\n * The statement with which a session store links the entries a session with fork segments stores (#6560). The\n * released triggers, which every entry runs, link an entry whose parent the session inherits as broken, without an\n * anchor, and an entry below it the same; so the store writes the link over theirs in the transaction that writes the\n * entry, behind it and the entries before it, in seq order. A plain session's writes run none of them. It waits for\n * the index's backfill, which links what it would.\n */\nexport interface ForkLinkWrites {\n\t/** The link of the entry at `seq` of session `sessionId`, run after the statements that wrote it. */\n\tentry(sessionId: string, seq: number): SqliteStatement;\n}\n\nexport function forkLinkWrites(tables: ForkLinkTables, d: StorageDialect): ForkLinkWrites {\n\tconst complete = entriesIndexComplete(tables.sources);\n\tconst rows = `(SELECT session_id, seq, entry_id, entry_json, ${parentColumns(d, \"entry_json\")} FROM ${tables.entries} WHERE session_id = ? AND seq = ? AND ${complete})`;\n\tconst sql = forkSessionLink(\n\t\ttables.sessionLinks,\n\t\ttables.forkSegments,\n\t\trows,\n\t\tsnapshotEntryCondition(d, (name) => `r.${name}`),\n\t);\n\treturn { entry: (sessionId, seq) => ({ sql, params: [sessionId, seq] }) };\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import "../../_shared/rolldown-runtime-BGM3D5V3.js";
2
2
  import { SESSION_INDEX_RETIRED_PREFIX } from "./blob-store.js";
3
+ import { forkInheritedBlobGuardName } from "./fork-blob-guard.js";
3
4
  // dist/core/worktree-snapshot/session-index-reset.js
4
5
  /** Old index rows a single cleanup transaction can release. */
5
6
  const SESSION_RESET_BATCH = 1e3;
@@ -99,7 +100,10 @@ async function detachSessionIndex(tx, t, triggers, available) {
99
100
  let ok = false;
100
101
  try {
101
102
  for (const name of triggers) await tx.exec(`DROP TRIGGER IF EXISTS ${name}`);
103
+ const carried = await tx.all("SELECT type, name, tbl_name, sql FROM sqlite_schema WHERE type = 'trigger' AND name = ?", forkInheritedBlobGuardName(t.blobs));
104
+ for (const { name } of carried) await tx.exec(`DROP TRIGGER ${name}`);
102
105
  for (const family of TYPES) if (!await detach(tx, t, family, token)) return false;
106
+ for (const { sql } of carried) if (sql !== null) await tx.exec(sql);
103
107
  ok = true;
104
108
  return true;
105
109
  } catch (error) {