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

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 (303) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/dist/_shared/dist-KOELCESV.js +2 -2
  3. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  4. package/dist/_shared/lib-4PES5P4V.js +2 -2
  5. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +7 -7
  6. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +7 -7
  7. package/dist/_shared/mode-shared-2QJSCUM6.js +7 -7
  8. package/dist/_shared/p1a-prewarm-XIU57JHF.js +3 -3
  9. package/dist/_shared/runtime-O4KCSG4C.js +5 -5
  10. package/dist/_shared/{sdk-AVFII7NK.js → sdk-IQMULKFU.js} +2438 -470
  11. package/dist/_shared/sdk-IQMULKFU.js.map +1 -0
  12. package/dist/_shared/session-data-AHTU7IS6.js +3 -3
  13. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  14. package/dist/_shared/settings-startup-8-DNZ2RIHM.js +1 -1
  15. package/dist/_shared/{settings-startup-4QCVCI53.js → settings-startup-HXQLSUWM.js} +8 -2
  16. package/dist/_shared/settings-startup-HXQLSUWM.js.map +1 -0
  17. package/dist/_shared/{startup-0-0-57KF6LZH.js → startup-0-0-3IXNMFM2.js} +392 -15
  18. package/dist/_shared/startup-0-0-3IXNMFM2.js.map +1 -0
  19. package/dist/_shared/{startup-0-1-GIY75K46.js → startup-0-1-7T2IAE7J.js} +51 -243
  20. package/dist/_shared/startup-0-1-7T2IAE7J.js.map +1 -0
  21. package/dist/_shared/{startup-0-2-27OWFHV6.js → startup-0-2-5QHPCEON.js} +225 -7
  22. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -0
  23. package/dist/_shared/{startup-0-3-T4DVFYWX.js → startup-0-3-4ZYBYQNM.js} +273 -14
  24. package/dist/_shared/startup-0-3-4ZYBYQNM.js.map +1 -0
  25. package/dist/_shared/startup-0-4-ZMJV547D.js +6 -6
  26. package/dist/_shared/startup-0-5-YDW47QX6.js +7 -7
  27. package/dist/_shared/startup-10-0-TDQNBDDL.js +7 -7
  28. package/dist/_shared/startup-12-0-55AAXBJZ.js +2 -2
  29. package/dist/_shared/startup-14-0-MLX36RBG.js +4 -4
  30. package/dist/_shared/startup-15-0-YUKGAC63.js +5 -5
  31. package/dist/_shared/startup-15-1-4S7FLMNG.js +7 -7
  32. package/dist/_shared/startup-8-0-34CBHPZH.js +421 -84
  33. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  34. package/dist/_shared/startup-8-1-X32CYSXB.js +77 -13
  35. package/dist/_shared/startup-8-1-X32CYSXB.js.map +1 -1
  36. package/dist/_shared/storage-command-7MGXLJGZ.js +7 -5
  37. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  38. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  39. package/dist/_shared/tree-outline-MUEPK5B7.js +3 -3
  40. package/dist/builtin/intercom/CHANGELOG.md +11 -0
  41. package/dist/builtin/intercom/broker/broker.bundle.mjs +205 -82
  42. package/dist/builtin/intercom/broker/sql-lease-store.ts +38 -27
  43. package/dist/builtin/intercom/broker/sql-outbox-store.ts +228 -65
  44. package/dist/builtin/intercom/broker/sql-schema.ts +82 -27
  45. package/dist/builtin/intercom/index.bundle.mjs +1 -1
  46. package/dist/builtin/intercom/package.json +1 -1
  47. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  48. package/dist/builtin/mcp/package.json +1 -1
  49. package/dist/builtin/subagents/CHANGELOG.md +6 -0
  50. package/dist/builtin/subagents/package.json +1 -1
  51. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  52. package/dist/builtin/web-access/index.bundle.mjs +1 -1
  53. package/dist/builtin/web-access/package.json +1 -1
  54. package/dist/cli/args.js +2 -2
  55. package/dist/cli/auth-cli.code.js +4 -4
  56. package/dist/cli/auth-cli.impl.js +3 -3
  57. package/dist/cli/auth-cli.js +3 -3
  58. package/dist/cli/blueprint-command.code.js +2 -2
  59. package/dist/cli/blueprint-command.impl.js +3 -3
  60. package/dist/cli/blueprint-command.js +3 -3
  61. package/dist/cli/intercom-command.code.js +3 -3
  62. package/dist/cli/intercom-command.impl.js +3 -3
  63. package/dist/cli/intercom-command.js +3 -3
  64. package/dist/cli/list-models.code.js +2 -2
  65. package/dist/cli/list-models.impl.js +3 -3
  66. package/dist/cli/list-models.js +3 -3
  67. package/dist/cli/session-picker.code.js +2 -2
  68. package/dist/cli/session-picker.impl.js +3 -3
  69. package/dist/cli/session-picker.js +3 -3
  70. package/dist/cli/startup-ui.code.js +2 -2
  71. package/dist/cli/startup-ui.impl.js +3 -3
  72. package/dist/cli/startup-ui.js +3 -3
  73. package/dist/cli/storage-command.impl.js +3 -3
  74. package/dist/cli/storage-command.js +3 -3
  75. package/dist/cli/storage-search-session.code.js +2 -2
  76. package/dist/cli/storage-search-session.impl.js +3 -3
  77. package/dist/cli/storage-search-session.js +3 -3
  78. package/dist/cli/team-command.code.js +2 -2
  79. package/dist/cli/team-command.impl.js +3 -3
  80. package/dist/cli/team-command.js +3 -3
  81. package/dist/cli.js +2 -2
  82. package/dist/core/debug.impl.js +3 -3
  83. package/dist/core/debug.js +3 -3
  84. package/dist/core/export-html/card-projection.impl.js +3 -3
  85. package/dist/core/export-html/card-projection.js +3 -3
  86. package/dist/core/export-html/index.code.js +2 -2
  87. package/dist/core/export-html/index.impl.js +3 -3
  88. package/dist/core/export-html/index.js +3 -3
  89. package/dist/core/export-html/json-spans.impl.js +3 -3
  90. package/dist/core/export-html/json-spans.js +3 -3
  91. package/dist/core/export-html/oversized-render-inputs.code.js +1 -1
  92. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  93. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  94. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  95. package/dist/core/export-html/tool-renderer.js +3 -3
  96. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  97. package/dist/core/extensions/jiti-loader.js +3 -3
  98. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  99. package/dist/core/extensions/jiti-static-loader.js +3 -3
  100. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  101. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  102. package/dist/core/extensions/loader-host-modules.js +3 -3
  103. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  104. package/dist/core/extensions/runner-context.js +2 -2
  105. package/dist/core/intercom-broker-control-host.code.js +1 -1
  106. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  107. package/dist/core/intercom-broker-control-host.js +3 -3
  108. package/dist/core/intercom-broker-control.code.js +3 -3
  109. package/dist/core/intercom-broker-control.impl.js +3 -3
  110. package/dist/core/intercom-broker-control.js +3 -3
  111. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  112. package/dist/core/package-manager-storage-adapters.js +3 -3
  113. package/dist/core/sdk.code.js +3 -3
  114. package/dist/core/sdk.impl.js +3 -3
  115. package/dist/core/sdk.js +3 -3
  116. package/dist/core/session-manager-core.js +26 -14
  117. package/dist/core/session-manager-core.js.map +1 -1
  118. package/dist/core/session-manager-list.impl.js +3 -3
  119. package/dist/core/session-manager-list.js +3 -3
  120. package/dist/core/session-manager.code.js +3 -3
  121. package/dist/core/session-manager.impl.js +3 -3
  122. package/dist/core/session-manager.js +3 -3
  123. package/dist/core/session-open-markers.js +3 -0
  124. package/dist/core/session-open-markers.js.map +1 -0
  125. package/dist/core/session-storage.impl.js +3 -3
  126. package/dist/core/session-storage.js +3 -3
  127. package/dist/core/storage/added-exports.js +3 -0
  128. package/dist/core/storage/added-exports.js.map +1 -1
  129. package/dist/core/storage/database.d.ts +37 -0
  130. package/dist/core/storage/database.js.map +1 -1
  131. package/dist/core/storage/index.d.ts +1 -1
  132. package/dist/core/storage/index.js +2 -2
  133. package/dist/core/storage/index.js.map +1 -1
  134. package/dist/core/storage/migrations.d.ts +12 -3
  135. package/dist/core/storage/migrations.js +24 -11
  136. package/dist/core/storage/migrations.js.map +1 -1
  137. package/dist/core/storage/node-sqlite-thread.js +31 -2
  138. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  139. package/dist/core/storage/node-sqlite.js +86 -2
  140. package/dist/core/storage/node-sqlite.js.map +1 -1
  141. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  142. package/dist/core/storage/offline-snapshot-file.js +3 -3
  143. package/dist/core/storage/prefix.js +5 -0
  144. package/dist/core/storage/prefix.js.map +1 -1
  145. package/dist/core/storage/provider.js +2 -2
  146. package/dist/core/storage/schema-catalog.d.ts +82 -4
  147. package/dist/core/storage/schema-catalog.js +242 -32
  148. package/dist/core/storage/schema-catalog.js.map +1 -1
  149. package/dist/core/storage/selection.js +2 -2
  150. package/dist/core/storage/session/branch-fork-source.code.js +9 -8
  151. package/dist/core/storage/session/branch-fork-source.code.js.map +1 -1
  152. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  153. package/dist/core/storage/session/branch-fork-source.js +3 -3
  154. package/dist/core/storage/session/card-view.impl.js +3 -3
  155. package/dist/core/storage/session/card-view.js +3 -3
  156. package/dist/core/storage/session/child-reader.code.js +4 -4
  157. package/dist/core/storage/session/child-reader.impl.js +3 -3
  158. package/dist/core/storage/session/child-reader.js +3 -3
  159. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  160. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  161. package/dist/core/storage/session/errors.js +1 -1
  162. package/dist/core/storage/session/expanded-child-details.code.js +3 -3
  163. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  164. package/dist/core/storage/session/expanded-child-details.js +3 -3
  165. package/dist/core/storage/session/fork-detach.d.ts +118 -0
  166. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  167. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  168. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  169. package/dist/core/storage/session/fork-row-index.js +3 -3
  170. package/dist/core/storage/session/fork-schema.js +53 -0
  171. package/dist/core/storage/session/fork-schema.js.map +1 -0
  172. package/dist/core/storage/session/fork-segments.d.ts +58 -0
  173. package/dist/core/storage/session/fork-staging.code.js +3 -3
  174. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  175. package/dist/core/storage/session/fork-staging.js +3 -3
  176. package/dist/core/storage/session/fork-sweep.js +61 -0
  177. package/dist/core/storage/session/fork-sweep.js.map +1 -0
  178. package/dist/core/storage/session/fork-window.code.js +4 -4
  179. package/dist/core/storage/session/fork-window.impl.js +3 -3
  180. package/dist/core/storage/session/fork-window.js +3 -3
  181. package/dist/core/storage/session/history-pages.impl.js +3 -3
  182. package/dist/core/storage/session/history-pages.js +3 -3
  183. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  184. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  185. package/dist/core/storage/session/jsonl-session-store.d.ts +37 -1
  186. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  187. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  188. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  189. package/dist/core/storage/session/memory-session-store.js +3 -3
  190. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  191. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  192. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  193. package/dist/core/storage/session/released-history-files.code.js +3 -3
  194. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  195. package/dist/core/storage/session/released-history-files.js +3 -3
  196. package/dist/core/storage/session/resident-fork-rows.code.js +1 -1
  197. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  198. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  199. package/dist/core/storage/session/session-resume.impl.js +3 -3
  200. package/dist/core/storage/session/session-resume.js +3 -3
  201. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  202. package/dist/core/storage/session/snapshot-cut.js +3 -3
  203. package/dist/core/storage/session/snapshot-history.code.js +4 -4
  204. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  205. package/dist/core/storage/session/snapshot-history.js +3 -3
  206. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  207. package/dist/core/storage/session/sql-session-store.d.ts +349 -12
  208. package/dist/core/storage/session/sql-session-store.impl.js +4 -4
  209. package/dist/core/storage/session/sql-session-store.js +4 -4
  210. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  211. package/dist/core/storage/session/tree-outline.js +3 -3
  212. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  213. package/dist/core/storage/session/tree-presentation.js +3 -3
  214. package/dist/core/storage/session/types.d.ts +22 -0
  215. package/dist/core/storage/sqlite-facade.d.ts +17 -1
  216. package/dist/core/storage/sqlite-facade.js +33 -0
  217. package/dist/core/storage/sqlite-facade.js.map +1 -1
  218. package/dist/core/storage/storage-status.impl.js +3 -3
  219. package/dist/core/storage/storage-status.js +3 -3
  220. package/dist/core/storage/team.impl.js +3 -3
  221. package/dist/core/storage/team.js +3 -3
  222. package/dist/core/structured-output/index.code.js +1 -1
  223. package/dist/core/structured-output/index.impl.js +3 -3
  224. package/dist/core/structured-output/index.js +3 -3
  225. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  226. package/dist/core/tasks/task-completion-entry.js +3 -3
  227. package/dist/core/tasks/task-file-history.code.js +4 -4
  228. package/dist/core/tasks/task-file-history.impl.js +3 -3
  229. package/dist/core/tasks/task-file-history.js +3 -3
  230. package/dist/core/tasks/task-reference-archive.code.js +4 -4
  231. package/dist/core/tasks/task-reference-archive.js +3 -3
  232. package/dist/core/tasks/task-reference-identity.js +3 -3
  233. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  234. package/dist/core/tasks/task-reference-stream.js +3 -3
  235. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  236. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  237. package/dist/core/tasks/task-view-source.impl.js +3 -3
  238. package/dist/core/tasks/task-view-source.js +3 -3
  239. package/dist/core/tools/history-session.d.ts +2 -0
  240. package/dist/core/tools/read-url.code.js +2 -2
  241. package/dist/core/tools/read-url.impl.js +3 -3
  242. package/dist/core/tools/read-url.js +3 -3
  243. package/dist/core/worktree-snapshot/blob-store.d.ts +31 -0
  244. package/dist/core/worktree-snapshot/blob-store.js +164 -49
  245. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  246. package/dist/core/worktree-snapshot/errors.code.js +3 -3
  247. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  248. package/dist/core/worktree-snapshot/errors.js +3 -3
  249. package/dist/core/worktree-snapshot/fork-snapshot-index.js +121 -0
  250. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -0
  251. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  252. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  253. package/dist/extensions/codemode/execute.code.js +2 -2
  254. package/dist/extensions/codemode/execute.impl.js +3 -3
  255. package/dist/extensions/codemode/execute.js +3 -3
  256. package/dist/extensions/codemode/renderer.code.js +1 -1
  257. package/dist/extensions/codemode/renderer.impl.js +3 -3
  258. package/dist/extensions/codemode/renderer.js +3 -3
  259. package/dist/extensions/mcp/cli.code.js +2 -2
  260. package/dist/extensions/mcp/cli.impl.js +3 -3
  261. package/dist/extensions/mcp/cli.js +3 -3
  262. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  263. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  264. package/dist/extensions/mcp/cli.lazy.js +3 -3
  265. package/dist/extensions/mcp/runtime.code.js +1 -1
  266. package/dist/extensions/mcp/runtime.impl.js +3 -3
  267. package/dist/extensions/mcp/runtime.js +3 -3
  268. package/dist/index.js +6 -6
  269. package/dist/main-first-time-setup.code.js +2 -2
  270. package/dist/main-first-time-setup.impl.js +3 -3
  271. package/dist/main-first-time-setup.js +3 -3
  272. package/dist/modes/interactive/components/stored-tree-view.code.js +3 -3
  273. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  274. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  275. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  276. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  277. package/dist/modes/print-mode.js +1 -1
  278. package/dist/package-manager-cli.code.js +5 -5
  279. package/dist/package-manager-cli.impl.js +3 -3
  280. package/dist/package-manager-cli.js +3 -3
  281. package/dist/rpc-entry.js +1 -1
  282. package/dist/startup-files.json +1 -1
  283. package/dist/startup-stages/2.js +1 -0
  284. package/dist/startup-stages/5.js +1 -1
  285. package/dist/startup-stages/7.js +5 -1
  286. package/dist/startup-stages/8.js +2 -2
  287. package/dist/utils/startup-database-spare.code.js +3 -3
  288. package/dist/utils/startup-database-spare.impl.js +3 -3
  289. package/dist/utils/startup-database-spare.js +3 -3
  290. package/dist/utils/tools-manager.code.js +1 -1
  291. package/dist/utils/tools-manager.impl.js +3 -3
  292. package/dist/utils/tools-manager.js +3 -3
  293. package/docs/guides/postgres-pgbouncer.md +14 -7
  294. package/docs/guides/postgres-tuning.md +9 -9
  295. package/docs/sessions.md +9 -0
  296. package/docs/storage.md +47 -6
  297. package/package.json +8 -8
  298. package/dist/_shared/sdk-AVFII7NK.js.map +0 -1
  299. package/dist/_shared/settings-startup-4QCVCI53.js.map +0 -1
  300. package/dist/_shared/startup-0-0-57KF6LZH.js.map +0 -1
  301. package/dist/_shared/startup-0-1-GIY75K46.js.map +0 -1
  302. package/dist/_shared/startup-0-2-27OWFHV6.js.map +0 -1
  303. package/dist/_shared/startup-0-3-T4DVFYWX.js.map +0 -1
@@ -1,12 +1,12 @@
1
1
  import { __name } from "./rolldown-runtime-BGM3D5V3.js";
2
2
  import { APP_NAME, CONFIG_DIR_NAME, createChildProcessEnvironment, findHelperExecutable, getAgentDir, helperLaunch, helperLaunchAsync, missingHelperOptions, startedWithHangupIgnored, stripBom } from "./p0-cli-BB45ZQY6.js";
3
- import { CONTINUE_AFTER_FAILURE, DynamicBorder, EventSourceError, FramedSelector, LATEST_PROTOCOL_VERSION, SubscriptionClosedError, SubscriptionConfigError, SubscriptionSetupError, SubscriptionTimeoutError, abortFailure, announceHistoryLoad, applySessionSummaryEntries, bindChatEpoch, blueprintBuildsSettled, boundedChatRecord, canonicalEventBusFor, collectDeclaredDisplaySecrets, decodeChatOrder, decodeChatRecord, encodeChatOrder, extractHeaderSecrets, firstChatOrders, flushRawStdout, forkStoreRelation, hasHistoryLoadObserver, isObject, isSensitiveKeyNameForMasking, materializeSessionSummaryMetadata, nativeForkReader, noteSnapshotGeneration, onBlueprintBuildFinished, onBlueprintBuildWaiting, raceWithAbortSignal, redactAuthorizationUrlForDisplay, redactCredentials, redactOAuthErrorText, redactUrlForDisplay, redactUrlForTransportDisplay, registerArchiveLoad, registerForkScope, registerHistorySnapshot, resolveDecisionDeadlineMs, scrubFetchError, sessionWriteTransaction, sha256Hex, sharedWakeDispatcher, sliceHead, stripUrlUserinfoAndHash, whenAborted, withinDecisionDeadline, writeRawStdout, yieldTurn } from "./startup-0-0-57KF6LZH.js";
4
- import { CommandDeliveries, SqlSessionSearchIndex, WorkspacePublicationError, collectCommandDeliveries, normalizeModelFailureSignal, reportDiagnostics, requireTimerMs } from "./startup-0-1-GIY75K46.js";
3
+ import { CONTINUE_AFTER_FAILURE, DynamicBorder, EventSourceError, ForkSourceIncompleteError, FramedSelector, LATEST_PROTOCOL_VERSION, SubscriptionClosedError, SubscriptionConfigError, SubscriptionSetupError, SubscriptionTimeoutError, abortFailure, announceHistoryLoad, applySessionSummaryEntries, assertForkSegments, bindChatEpoch, blueprintBuildsSettled, boundedChatRecord, canonicalEventBusFor, collectDeclaredDisplaySecrets, decodeChatOrder, decodeChatRecord, dropStoredNotes, encodeChatOrder, extractHeaderSecrets, firstChatOrders, flushRawStdout, forkRunSegments, forkStoreRelation, hasHistoryLoadObserver, isObject, isSensitiveKeyNameForMasking, materializeSessionSummaryMetadata, nativeForkReader, noteSnapshotGeneration, onBlueprintBuildFinished, onBlueprintBuildWaiting, prefixForkSegments, raceWithAbortSignal, redactAuthorizationUrlForDisplay, redactCredentials, redactOAuthErrorText, redactUrlForDisplay, redactUrlForTransportDisplay, registerArchiveLoad, registerForkScope, registerHistorySnapshot, resolveDecisionDeadlineMs, scrubFetchError, segmentLength, sessionWriteTransaction, sha256Hex, sharedHistorySwitchHost, sharedWakeDispatcher, sliceHead, storedEntryNotes, storedRows, stripUrlUserinfoAndHash, whenAborted, withinDecisionDeadline, writeRawStdout, yieldTurn } from "./startup-0-0-3IXNMFM2.js";
4
+ import { CommandDeliveries, SqlSessionSearchIndex, WorkspacePublicationError, collectCommandDeliveries, normalizeModelFailureSignal, reportDiagnostics, requireTimerMs } from "./startup-0-1-7T2IAE7J.js";
5
5
  import { getAvailableThemes, keyHint } from "./p2-shell-main-B2WIALFD.js";
6
6
  import { releaseLock, reportDebugAsync, waitForLock } from "./p1b-elig-ENCUPKKJ.js";
7
- import { FileAuthStorageBackend, ResumePreconditionError, STRUCTURED_OUTPUT_TOOL_NAME, asyncAuthStorageReads, classifyRepository, killTrackedDetachedChildren, markNativeMcpToolDefinition, matchesMcpDirectToolSelection, providerRetryHint } from "./startup-0-2-27OWFHV6.js";
8
- import { CODEMODE_TOOL_NAME, assistantRetryAttempt, runWorkspaceProcess } from "./startup-0-3-T4DVFYWX.js";
9
- import { DecisionConfigError, DecisionModelUnavailableError, DecisionOutputError, DecisionProviderError, DecisionRequestError, SESSION_HISTORY_CHUNK_BYTES, SESSION_HISTORY_PAGE_BYTES, entrySizeLimit, isDecisionError, isDecisionProviderError } from "./settings-startup-4QCVCI53.js";
7
+ import { FileAuthStorageBackend, ResumePreconditionError, STRUCTURED_OUTPUT_TOOL_NAME, asyncAuthStorageReads, classifyRepository, detachForkChildren, detachForkWithin, isTombstoned, killTrackedDetachedChildren, lockedReferrers, markNativeMcpToolDefinition, matchesMcpDirectToolSelection, noteForkCopyRefusal, providerRetryHint, removeStoredRows, resumeForkDetaches } from "./startup-0-2-5QHPCEON.js";
8
+ import { CODEMODE_TOOL_NAME, assistantRetryAttempt, runWorkspaceProcess } from "./startup-0-3-4ZYBYQNM.js";
9
+ import { DecisionConfigError, DecisionModelUnavailableError, DecisionOutputError, DecisionProviderError, DecisionRequestError, SESSION_HISTORY_CHUNK_BYTES, SESSION_HISTORY_PAGE_BYTES, entrySizeLimit, isDecisionError, isDecisionProviderError } from "./settings-startup-HXQLSUWM.js";
10
10
  import { RESUME_UPGRADE_SOURCES, branchRanges, childCatalogCut, foldSessionResume, foreignResumeIds, isSessionResumeIndex, isUpgradableSessionResumeIndex, latestCompactionOf, readEarlierCompletionIntents, selectedPagePlan, sessionResumeFrom, sessionResumePlan, sessionResumeUpgrade, sessionTailFrom, snapshotCutOf, stateSeqsBefore, transcriptBranchSpan, validateSessionEntries, validateSessionHeader, validateSessionText } from "./startup-8-0-34CBHPZH.js";
11
11
  import { LIST_MCP_RESOURCES_TOOL, LIST_MCP_RESOURCE_TEMPLATES_TOOL, READ_MCP_RESOURCE_TOOL, TOOL_SEARCH_TOOL_NAME, createMcpResourceToolDefinitions, createMcpToolDefinition, createMcpToolName, createMcpToolRenderers, defaultResumePreflightIo, enablePrintModelSelection, gitUnavailableProblem, hasPrintModelSelection, openWorkspaceRepository, ranOnModelLine, removeRestoredWorktree } from "./startup-0-5-YDW47QX6.js";
12
12
  import { assertWorkspaceGitAvailable, formatModelLabel, gitOutput, runWorkspaceGit } from "./startup-0-4-ZMJV547D.js";
@@ -41,13 +41,17 @@ import { Type as Type$1 } from "@bastani/atomic-ai/utils/typebox/index";
41
41
  import { ModelRegistry } from "../core/model-registry.js";
42
42
  import { dialectOf, postgresJsonb } from "../core/storage/dialect.js";
43
43
  import { ensureStorageSchema } from "../core/storage/migrations.js";
44
+ import * as schemaCatalog from "../core/storage/schema-catalog.js";
44
45
  import { schemaCatalogOf, withStorageSchemaCatalog } from "../core/storage/schema-catalog.js";
46
+ import * as statementSequence from "../core/storage/statement-sequence.js";
45
47
  import { sequenceRunner } from "../core/storage/statement-sequence.js";
46
48
  import { createServer } from "node:http";
47
49
  import { Check, Errors } from "@bastani/atomic-ai/utils/typebox/value";
50
+ import { forkLinkWrites, legacyForkLinksTriggerName } from "../core/worktree-snapshot/fork-snapshot-index.js";
48
51
  import { ensureTableFillfactor, storageSchemaCurrent, transactionFinisher } from "../core/storage/added-exports.js";
49
52
  import { assertStorageSchemaVersion, assertStoredSchemaVersion } from "../core/storage/schema.js";
50
53
  import { applyStorageMigrationsTogether, statementBatch } from "../core/storage/statement-batches.js";
54
+ import { createSharedHistoryTables, sessionForkTables, sharedHistoryTablesScript } from "../core/storage/session/fork-schema.js";
51
55
  import { CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL, createGatewayBindingFetch } from "@bastani/atomic-ai/api/cloudflare-gateway-binding";
52
56
  import { configuredSecretRedactor } from "../core/storage/sqlite-facade.js";
53
57
  import { oauthErrorHtml, oauthSuccessHtml } from "@bastani/atomic-ai/utils/oauth-page";
@@ -917,12 +921,36 @@ async function restoreRunWorktree(remotes, restore, options = {}) {
917
921
  }], options);
918
922
  return root;
919
923
  }
924
+ // dist/core/storage/added-exports-0-10-11.js
925
+ /**
926
+ * `noteStorageSchemaTables` and `refreshStorageSchemaCatalog` of `schema-catalog.ts`, which the copy 0.10.11-alpha.1
927
+ * loaded lacks, and `MAX_SEQUENCE_REQUEST_STATEMENTS` of `statement-sequence.ts`, which the copies 0.10.3 and 0.10.4's
928
+ * prereleases loaded lack. A process that loaded those copies, or 0.10.11-alpha.1's `added-exports.js`, before an
929
+ * in-place update replaced the installation keeps them, and can load the modules that use these from the update: a
930
+ * named import of any of them would fail to link there, so they take them from here, a path no earlier release has
931
+ * (#6560). With 0.10.11-alpha.1's catalog, which knows nothing of fork tables, an open keeps the catalog it read, as
932
+ * there.
933
+ */
934
+ const catalogUpdates = schemaCatalog;
935
+ const sequences = statementSequence;
936
+ const noteStorageSchemaTables = catalogUpdates.noteStorageSchemaTables ?? (() => {});
937
+ const refreshStorageSchemaCatalog = catalogUpdates.refreshStorageSchemaCatalog ?? (() => {});
938
+ /** The most statements one request of a sequence carries (#6560). */
939
+ const MAX_SEQUENCE_REQUEST_STATEMENTS = sequences.MAX_SEQUENCE_REQUEST_STATEMENTS ?? 256;
920
940
  // dist/core/storage/session/fork-row-copy.js
921
941
  /** How many entry IDs a run builder holds for lookups before it sends its runs, bounding what a fork holds. */
922
942
  const HELD_RUN_ROWS = 4096;
923
943
  /** How many hashes one blob statement names, so a statement stays small whatever the session holds. */
924
944
  const BLOB_HASHES_PER_STATEMENT = 256;
925
945
  /**
946
+ * The chunk rows `INSERT … SELECT` copies of the entries of session `?` at seqs `?` to `?`: only each entry's chunks 0 to
947
+ * `chunks - 1`, as the copy one chunk at a time did, never a row an older version left past them or at an entry stored
948
+ * whole. `incompleteEntryRead` then finds an entry missing any of those.
949
+ */
950
+ function entryChunkRows(tables, seqs) {
951
+ return `FROM ${tables.entryChunks} c JOIN ${tables.entries} e ON e.session_id = c.session_id AND e.seq = c.seq WHERE c.session_id = ? AND c.seq ${seqs} AND c.idx >= 0 AND c.idx < e.chunks ORDER BY c.seq, c.idx`;
952
+ }
953
+ /**
926
954
  * The source's stored rows a fork copies, gathered into runs of consecutive seqs and copied a run at a time, each run in
927
955
  * one `INSERT … SELECT` for its entries and one for their chunks (#6560), not one statement per row and chunk. Rows are
928
956
  * copied in seq order, so the snapshot index's triggers meet a parent before its children, as they do for an append.
@@ -981,7 +1009,7 @@ var ForkRowRuns = class {
981
1009
  changes: count,
982
1010
  mismatch: () => new SessionConflictError$1(this.source, sourceFrom, sourceFrom + count - 1)
983
1011
  }, {
984
- sql: `INSERT INTO ${entryChunks} (session_id, seq, idx, data) SELECT ?, seq + ?, idx, data FROM ${entryChunks} WHERE session_id = ? AND seq BETWEEN ? AND ? ORDER BY seq, idx`,
1012
+ sql: `INSERT INTO ${entryChunks} (session_id, seq, idx, data) SELECT ?, c.seq + ?, c.idx, c.data ${entryChunkRows(this.tables, "BETWEEN ? AND ?")}`,
985
1013
  params
986
1014
  });
987
1015
  }
@@ -993,11 +1021,12 @@ var ForkRowRuns = class {
993
1021
  };
994
1022
  /**
995
1023
  * The read that finds a stored entry of `child` missing any of its chunks, which the fork checks before it commits: an
996
- * entry copied from the source names its chunk count, and the chunks were copied in the same statements.
1024
+ * entry copied from the source names its chunk count, and the chunks were copied in the same statements. It counts the
1025
+ * entry's chunk rows from 0 to `chunks - 1`, keyed by their index, so a count of `chunks` is each of them.
997
1026
  */
998
1027
  function incompleteEntryRead(tables, child) {
999
1028
  return {
1000
- sql: `SELECT e.seq FROM ${tables.entries} e WHERE e.session_id = ? AND e.chunks > 0 AND e.chunks <> (SELECT count(*) FROM ${tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq) LIMIT 1`,
1029
+ sql: `SELECT e.seq FROM ${tables.entries} e WHERE e.session_id = ? AND e.chunks > 0 AND e.chunks <> (SELECT count(*) FROM ${tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx >= 0 AND c.idx < e.chunks) LIMIT 1`,
1001
1030
  params: [child]
1002
1031
  };
1003
1032
  }
@@ -1066,6 +1095,357 @@ function forkBlobCopy(tables, options, source, child, hashes) {
1066
1095
  }
1067
1096
  };
1068
1097
  }
1098
+ // dist/core/storage/session/fork-lineage.js
1099
+ /** Segment rows one statement inserts at most: six parameters each, well under every backend's parameter limit. */
1100
+ const SEGMENT_ROWS_PER_INSERT = 500;
1101
+ /** Session `sessionId`'s segments, in view order, read through `tx`. None for a session that inherits nothing. */
1102
+ async function readForkSegments(tx, tables, sessionId) {
1103
+ return (await tx.all(`SELECT source_id, from_seq, to_seq, base_seq FROM ${tables.forkSegments} WHERE session_id = ? ORDER BY idx`, sessionId)).map((row) => ({
1104
+ sourceId: String(row.source_id),
1105
+ fromSeq: Number(row.from_seq),
1106
+ toSeq: Number(row.to_seq),
1107
+ baseSeq: Number(row.base_seq)
1108
+ }));
1109
+ }
1110
+ /**
1111
+ * The statements that make `segments` session `sessionId`'s segments, in place of any it had, and give its lineage row a
1112
+ * new generation: with `lineage`, the parent and cut-off a new fork records; without, the row keeps them. Throws unless
1113
+ * `segments` are well formed for a view of `length` seqs. The session's own rows must not sit at a seq they cover:
1114
+ * a view is the rows its segments name and the session's own rows, both read.
1115
+ */
1116
+ function forkSegmentWrites(tables, sessionId, segments, length, lineage) {
1117
+ assertForkSegments(sessionId, segments, length);
1118
+ return [
1119
+ {
1120
+ sql: `DELETE FROM ${tables.forkSegments} WHERE session_id = ?`,
1121
+ params: [sessionId]
1122
+ },
1123
+ ...forkSegmentInserts(tables, sessionId, 0, segments),
1124
+ forkLineageWrite(tables, sessionId, lineage)
1125
+ ];
1126
+ }
1127
+ /** The statements that insert `segments` as session `sessionId`'s segments from index `firstIndex` on. */
1128
+ function forkSegmentInserts(tables, sessionId, firstIndex, segments) {
1129
+ const statements = [];
1130
+ for (let start = 0; start < segments.length; start += SEGMENT_ROWS_PER_INSERT) {
1131
+ const batch = segments.slice(start, start + SEGMENT_ROWS_PER_INSERT);
1132
+ statements.push({
1133
+ sql: `INSERT INTO ${tables.forkSegments} (session_id, idx, source_id, from_seq, to_seq, base_seq) VALUES ${batch.map(() => "(?, ?, ?, ?, ?, ?)").join(", ")}`,
1134
+ params: batch.flatMap((segment, index) => [
1135
+ sessionId,
1136
+ firstIndex + start + index,
1137
+ segment.sourceId,
1138
+ segment.fromSeq,
1139
+ segment.toSeq,
1140
+ segment.baseSeq
1141
+ ])
1142
+ });
1143
+ }
1144
+ return statements;
1145
+ }
1146
+ /**
1147
+ * The statement that gives session `sessionId`'s lineage row a new generation, as every change to its segments must:
1148
+ * with `lineage`, the parent and cut-off a new fork records; without, the row keeps them.
1149
+ */
1150
+ function forkLineageWrite(tables, sessionId, lineage) {
1151
+ return {
1152
+ sql: `INSERT INTO ${tables.forkLineage} (session_id, parent_id, cut_seq, generation) VALUES (?, ?, ?, ?)
1153
+ ON CONFLICT(session_id) DO UPDATE SET generation = excluded.generation${lineage === void 0 ? "" : ", parent_id = excluded.parent_id, cut_seq = excluded.cut_seq"}`,
1154
+ params: [
1155
+ sessionId,
1156
+ lineage?.parentId ?? null,
1157
+ lineage?.cutSeq ?? null,
1158
+ crypto.randomUUID()
1159
+ ]
1160
+ };
1161
+ }
1162
+ /** Runs {@link forkSegmentWrites} through `tx`. */
1163
+ async function writeForkSegments(tx, tables, sessionId, segments, length, lineage) {
1164
+ for (const { sql, params } of forkSegmentWrites(tables, sessionId, segments, length, lineage)) await tx.run(sql, ...params);
1165
+ }
1166
+ /** The sessions with a segment that names `sourceId`, by id: the forks that read rows `sourceId` stores. */
1167
+ async function forkChildren(tx, tables, sourceId) {
1168
+ return (await tx.all(`SELECT DISTINCT session_id FROM ${tables.forkSegments} WHERE source_id = ? ORDER BY session_id`, sourceId)).map((row) => String(row.session_id));
1169
+ }
1170
+ /**
1171
+ * Locks the sessions rows of `ids`, in id order so that two transactions never wait for each other: `key-share` keeps
1172
+ * them from being deleted or locked `update` while the transaction lasts, as a fork that names them in its segments
1173
+ * needs; `update` excludes those. Nothing on SQLite, whose write transactions already run one at a time.
1174
+ */
1175
+ async function lockForkSources(tx, dialect, tables, ids, mode) {
1176
+ const sorted = [...new Set(ids)].sort();
1177
+ if (dialect.name === "sqlite" || sorted.length === 0) return;
1178
+ await tx.all(`SELECT id FROM ${tables.sessions} WHERE id IN (${sorted.map(() => "?").join(", ")}) ORDER BY id${dialect.lockClause(mode)}`, ...sorted);
1179
+ }
1180
+ /**
1181
+ * The segments of a fork that shares its parent's history, gathered as the fork's rows stream past (#6560): each row the
1182
+ * parent stores unchanged extends a run of the parent's view, and `drain` composes the runs gathered since the last
1183
+ * one with the parent's own segments, so that each segment names the session that stores its rows, and returns the
1184
+ * statements that insert them. Drain before the fork writes a row of its own, so that its segments come first in seq
1185
+ * order. `heldSeq` answers for the rows of runs not yet drained.
1186
+ */
1187
+ var ForkSegmentRuns = class {
1188
+ segments = [];
1189
+ runs = [];
1190
+ held = /* @__PURE__ */ new Map();
1191
+ tables;
1192
+ child;
1193
+ parent;
1194
+ constructor(tables, child, parent) {
1195
+ this.tables = tables;
1196
+ this.child = child;
1197
+ this.parent = parent;
1198
+ }
1199
+ /** The parent's row at view seq `parentSeq` is the child's row at `childSeq`, entry `id`. */
1200
+ add(parentSeq, childSeq, id) {
1201
+ const run = this.runs.at(-1);
1202
+ if (run && parentSeq === run.toSeq + 1 && childSeq === run.baseSeq + (run.toSeq - run.fromSeq) + 2) run.toSeq++;
1203
+ else this.runs.push({
1204
+ fromSeq: parentSeq,
1205
+ toSeq: parentSeq,
1206
+ baseSeq: childSeq - 1
1207
+ });
1208
+ this.held.set(id, childSeq);
1209
+ }
1210
+ /** The child seq of entry `id` among the rows not yet drained, the latest when several hold it. */
1211
+ heldSeq(id) {
1212
+ return this.held.get(id);
1213
+ }
1214
+ /** Whether enough rows wait that they should be drained before more are added. */
1215
+ get full() {
1216
+ return this.held.size >= 8192;
1217
+ }
1218
+ /** The statements that insert the segments of the runs gathered since the last drain. */
1219
+ drain() {
1220
+ if (this.runs.length === 0) return [];
1221
+ const composed = this.runs.flatMap((run) => forkRunSegments(this.parent.id, this.parent.segments, this.parent.length, run));
1222
+ const first = this.segments.length;
1223
+ this.segments.push(...composed);
1224
+ this.runs.length = 0;
1225
+ this.held.clear();
1226
+ return forkSegmentInserts(this.tables, this.child, first, composed);
1227
+ }
1228
+ };
1229
+ /**
1230
+ * `segments` without the view seqs `pieces` cover: each piece must lie within one segment, naming the same rows of the
1231
+ * same source. Throws otherwise.
1232
+ */
1233
+ function withoutForkPieces(segments, pieces) {
1234
+ const end = (segment) => segment.baseSeq + segmentLength(segment);
1235
+ const remaining = [];
1236
+ for (const segment of segments) {
1237
+ const inside = pieces.filter((piece) => piece.baseSeq >= segment.baseSeq && end(piece) <= end(segment) && piece.sourceId === segment.sourceId).sort((a, b) => a.baseSeq - b.baseSeq);
1238
+ let view = segment.baseSeq;
1239
+ for (const piece of inside) {
1240
+ if (piece.fromSeq - piece.baseSeq !== segment.fromSeq - segment.baseSeq || piece.baseSeq < view) throw new RangeError(`Fork piece ${JSON.stringify(piece)} does not lie within ${JSON.stringify(segment)}`);
1241
+ if (piece.baseSeq > view) remaining.push({
1242
+ ...segment,
1243
+ fromSeq: segment.fromSeq + (view - segment.baseSeq),
1244
+ toSeq: piece.fromSeq - 1,
1245
+ baseSeq: view
1246
+ });
1247
+ view = end(piece);
1248
+ }
1249
+ if (view < end(segment)) remaining.push({
1250
+ ...segment,
1251
+ fromSeq: segment.fromSeq + (view - segment.baseSeq),
1252
+ baseSeq: view
1253
+ });
1254
+ }
1255
+ const covered = pieces.reduce((sum, piece) => sum + segmentLength(piece), 0);
1256
+ if (segments.reduce((sum, segment) => sum + segmentLength(segment), 0) - remaining.reduce((sum, segment) => sum + segmentLength(segment), 0) !== covered) throw new RangeError("Fork pieces overlap or lie outside the fork's segments");
1257
+ return remaining;
1258
+ }
1259
+ /** The first seq of `piece` whose entry its source lacks, or holds without one of its chunks: why its copy was refused. */
1260
+ async function firstIncomplete(tx, tables, piece) {
1261
+ const rows = await tx.all(`SELECT e.seq, e.chunks, (SELECT count(*) FROM ${tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx >= 0 AND c.idx < e.chunks) AS held FROM ${tables.entries} e WHERE e.session_id = ? AND e.seq BETWEEN ? AND ? ORDER BY e.seq`, piece.sourceId, piece.fromSeq, piece.toSeq);
1262
+ let expected = piece.fromSeq;
1263
+ for (const row of rows) {
1264
+ if (Number(row.seq) !== expected || Number(row.chunks) > 0 && Number(row.held) !== Number(row.chunks)) return expected;
1265
+ expected++;
1266
+ }
1267
+ return expected;
1268
+ }
1269
+ /**
1270
+ * Copies into session `childId`, a fork that shares history, the rows `pieces` of its segments name, with their chunks,
1271
+ * search texts and the blobs their tool outputs name, and links them in the snapshot index with `links` (see
1272
+ * `materializedForkLinks`), a statement a piece, then writes its segments without them, with a new generation, so
1273
+ * its view stays as it was at every commit (#6560). Each piece lies within one of the child's segments: a sub-range of
1274
+ * it, or all of it. The caller holds the child's row locked `update`, and the sources' rows locked, so neither its
1275
+ * segments nor the rows they name change meanwhile; `length` is the child's last seq.
1276
+ */
1277
+ async function materializeForkSegments(tx, dialect, tables, blobs, links, childId, length, pieces) {
1278
+ const remaining = withoutForkPieces(await readForkSegments(tx, tables, childId), pieces);
1279
+ const text = (...path) => dialect.jsonText("entry_json", ...path);
1280
+ for (const piece of [...pieces].sort((a, b) => a.baseSeq - b.baseSeq)) {
1281
+ const shift = piece.baseSeq - piece.fromSeq + 1;
1282
+ const range = [
1283
+ piece.sourceId,
1284
+ piece.fromSeq,
1285
+ piece.toSeq
1286
+ ];
1287
+ const copied = await tx.run(`INSERT INTO ${tables.entries} (session_id, seq, entry_id, entry_json, chunks) SELECT ?, e.seq + ?, e.entry_id, e.entry_json, e.chunks FROM ${tables.entries} e WHERE e.session_id = ? AND e.seq BETWEEN ? AND ? AND (e.chunks = 0 OR e.chunks = (SELECT count(*) FROM ${tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx >= 0 AND c.idx < e.chunks)) ORDER BY e.seq`, childId, shift, ...range);
1288
+ if (Number(copied.changes) !== segmentLength(piece)) throw new ForkSourceIncompleteError(childId, piece.sourceId, await firstIncomplete(tx, tables, piece));
1289
+ await Promise.all([tx.run(links, childId, shift, ...range, childId), tx.run(`INSERT INTO ${tables.entryChunks} (session_id, seq, idx, data) SELECT ?, c.seq + ?, c.idx, c.data FROM ${tables.entryChunks} c JOIN ${tables.entries} e ON e.session_id = c.session_id AND e.seq = c.seq WHERE c.session_id = ? AND c.seq BETWEEN ? AND ? AND c.idx >= 0 AND c.idx < e.chunks ORDER BY c.seq, c.idx`, childId, shift, ...range)]);
1290
+ await tx.run(`INSERT INTO ${tables.searchTexts} (session_id, seq, text_json) SELECT ?, seq + ?, text_json FROM ${tables.searchTexts} WHERE session_id = ? AND seq BETWEEN ? AND ? ORDER BY seq`, childId, shift, ...range);
1291
+ const named = await tx.all(`SELECT DISTINCT ${text("data", "hash")} AS hash FROM ${tables.entries} WHERE session_id = ? AND seq BETWEEN ? AND ?
1292
+ AND chunks = 0 AND ${text("type")} = 'custom' AND ${text("customType")} = 'atomic.tool-output' AND ${text("data", "hash")} IS NOT NULL`, ...range);
1293
+ const copy = forkBlobCopy(tables, blobs, piece.sourceId, childId, named.map((row) => String(row.hash)));
1294
+ for (const { sql, params } of copy.statements) await tx.run(sql, ...params);
1295
+ const answers = [];
1296
+ for (const { sql, params } of copy.checks) answers.push(await tx.all(sql, ...params));
1297
+ copy.remaining(answers);
1298
+ }
1299
+ await writeForkSegments(tx, tables, childId, remaining, length);
1300
+ }
1301
+ // dist/core/storage/session/fork-detach-host.js
1302
+ /**
1303
+ * The SQL session store's side of detaching and pinning shared fork history (#6560): its fork segments, read and
1304
+ * written through fork-lineage.ts, in transactions of the store.
1305
+ */
1306
+ /** The fork host of a store whose sessions schema has shared-history forks. */
1307
+ function forkDetachHost(store) {
1308
+ const { dialect, tables, forkTables } = store;
1309
+ const lineage = {
1310
+ sessions: tables.sessions,
1311
+ forkSegments: forkTables.forkSegments,
1312
+ forkLineage: forkTables.forkLineage
1313
+ };
1314
+ const materialize = {
1315
+ ...tables,
1316
+ ...lineage
1317
+ };
1318
+ /** A session's last seq: the length of its view. A deleted session's tombstone has no row, and no view to keep. */
1319
+ const length = async (tx, sessionId) => {
1320
+ const row = await tx.get(`SELECT last_seq FROM ${tables.sessions} WHERE id = ?`, sessionId);
1321
+ return row === void 0 ? 0 : Number(row.last_seq);
1322
+ };
1323
+ return {
1324
+ forkDetachTable: forkTables.forkDetach,
1325
+ pinTables: {
1326
+ entries: tables.entries,
1327
+ entryChunks: tables.entryChunks,
1328
+ searchTexts: tables.searchTexts,
1329
+ blobs: tables.blobs,
1330
+ blobChunks: tables.blobChunks,
1331
+ tombstones: forkTables.forkTombstones,
1332
+ forkSegments: forkTables.forkSegments,
1333
+ forkLineage: forkTables.forkLineage
1334
+ },
1335
+ forkTransaction: (body) => store.transaction(body),
1336
+ lockClause: (mode) => dialect.lockClause(mode),
1337
+ forkSegments: (tx, sessionId) => readForkSegments(tx, lineage, sessionId),
1338
+ forkChildren: (tx, sourceId) => forkChildren(tx, lineage, sourceId),
1339
+ async materializeForkSegments(tx, childId, pieces) {
1340
+ await materializeForkSegments(tx, dialect, materialize, store.blobs, store.materializedLinks, childId, await length(tx, childId), pieces);
1341
+ },
1342
+ async writeForkSegments(tx, sessionId, segments) {
1343
+ if (segments.length > 0 || (await readForkSegments(tx, lineage, sessionId)).length > 0) await writeForkSegments(tx, lineage, sessionId, segments, await length(tx, sessionId));
1344
+ },
1345
+ async lockForkSources(tx, ids, mode) {
1346
+ await lockForkSources(tx, dialect, lineage, ids, mode);
1347
+ const sorted = [...new Set(ids)].sort();
1348
+ if (dialect.name !== "sqlite" && sorted.length > 0) await tx.all(`SELECT session_id FROM ${forkTables.forkTombstones} WHERE session_id IN (${sorted.map(() => "?").join(", ")}) ORDER BY session_id${dialect.lockClause(mode)}`, ...sorted);
1349
+ },
1350
+ async forkRewriteEpoch(tx, sessionId) {
1351
+ return (await tx.get(`SELECT COALESCE(${dialect.jsonText("summary_state", "epoch")}, ${dialect.jsonText("summary_state", "resume", "epoch")}) AS epoch FROM ${tables.sessions} WHERE id = ?`, sessionId))?.epoch ?? void 0;
1352
+ }
1353
+ };
1354
+ }
1355
+ // dist/core/storage/session/fork-pins.js
1356
+ /**
1357
+ * What deleting, replacing and re-creating a session does when forks read rows it stores. A fork's segments name the
1358
+ * session that stores each row it inherited, so those rows stay for as long as any segment names them:
1359
+ *
1360
+ * - Deleting a session that forks still read removes it from every read (its sessions row and its search texts go)
1361
+ * but keeps the rows they read, its entries, entry chunks and blobs, under a tombstone. The rows go with the
1362
+ * tombstone once nothing names them any more: when the last fork reading them is deleted, replaced or detached.
1363
+ * - Replacing a session that forks still read first gives each of them its own copy of the rows it read (detach),
1364
+ * since the replace deletes those rows.
1365
+ * - Creating a session under the ID of a tombstone first detaches the forks that still read the old rows, then removes
1366
+ * them, so the new session starts empty.
1367
+ *
1368
+ * A session's own segments go when it is deleted or replaced, which may leave a deleted source no fork reads; the caller
1369
+ * sweeps it once its transaction commits (fork-sweep.ts). A delete and a replace lock the session's row for update
1370
+ * before they read anything of its fork history, as the first read of their transaction ({@link forkPinReads}), so
1371
+ * they drop its own segments and list the forks that name it only under that lock. A fork locks every session its
1372
+ * segments name for key share, tombstones included, so a fork being made either commits first and is listed, or waits
1373
+ * and finds the session gone.
1374
+ */
1375
+ /**
1376
+ * The statements a delete or a replace of `sessionId` reads its fork history with, as the first reads of its
1377
+ * transaction: where writers can run together, the session's row, locked for update so that no fork of it starts
1378
+ * meanwhile, then the listing. Sent with the transaction's start, they cost no round trip of their own.
1379
+ */
1380
+ function forkPinReads(host, sessions, sessionId) {
1381
+ const { forkSegments, forkLineage } = host.pinTables;
1382
+ const lock = host.lockClause("update");
1383
+ return [...lock === "" ? [] : [{
1384
+ sql: `SELECT id FROM ${sessions} WHERE id = ?${lock}`,
1385
+ params: [sessionId]
1386
+ }], {
1387
+ sql: `SELECT 's' AS kind, source_id AS id FROM ${forkSegments} WHERE session_id = ?
1388
+ UNION SELECT 'r', session_id FROM ${forkSegments} WHERE source_id = ? AND session_id <> ?
1389
+ UNION SELECT 'l', session_id FROM ${forkLineage} WHERE session_id = ?`,
1390
+ params: [
1391
+ sessionId,
1392
+ sessionId,
1393
+ sessionId,
1394
+ sessionId
1395
+ ]
1396
+ }];
1397
+ }
1398
+ /** Reads `sessionId`'s fork history through the statements of {@link forkPinReads}, in order. */
1399
+ async function readForkPins(tx, reads) {
1400
+ const listing = reads.at(-1);
1401
+ for (const lock of reads.slice(0, -1)) await tx.get(lock.sql, ...lock.params);
1402
+ const rows = await tx.all(listing.sql, ...listing.params);
1403
+ const of = (kind) => [...new Set(rows.filter((row) => row.kind === kind).map((row) => String(row.id)))].sort();
1404
+ return {
1405
+ sources: of("s"),
1406
+ readers: of("r"),
1407
+ lineage: rows.some((row) => row.kind === "l")
1408
+ };
1409
+ }
1410
+ /**
1411
+ * In `delete`'s transaction, before the session's rows go, given what {@link readForkPins} read. `keepRows` when forks
1412
+ * still read rows the session stores: the caller then removes only its sessions row, and the rows stay under a
1413
+ * tombstone. `released` are the sources the session's own segments named, to sweep once the transaction commits. A
1414
+ * session no fork history names costs no statement.
1415
+ */
1416
+ async function deleteForkedSessionWithin(host, tx, sessionId, deletedAt, pins) {
1417
+ if (pins.sources.length > 0) await tx.run(`DELETE FROM ${host.pinTables.forkSegments} WHERE session_id = ?`, sessionId);
1418
+ if (pins.lineage) await tx.run(`DELETE FROM ${host.pinTables.forkLineage} WHERE session_id = ?`, sessionId);
1419
+ if (pins.readers.length === 0) return {
1420
+ keepRows: false,
1421
+ released: pins.sources
1422
+ };
1423
+ await tx.run(`INSERT INTO ${host.pinTables.tombstones} (session_id, deleted_at) VALUES (?, ?) ON CONFLICT DO NOTHING`, sessionId, deletedAt);
1424
+ return {
1425
+ keepRows: true,
1426
+ released: pins.sources
1427
+ };
1428
+ }
1429
+ /**
1430
+ * In `replace`'s transaction, before the session's rows go, given what {@link readForkPins} read: each fork reading
1431
+ * them gets its own copy, and the session drops its own segments, as a replaced session holds every row of its view
1432
+ * itself. Resolves with the sources those segments named, to sweep once the transaction commits. A session no fork
1433
+ * history names costs no statement.
1434
+ */
1435
+ async function replaceForkedSessionWithin(host, tx, sessionId, pins) {
1436
+ if (pins.sources.length > 0) await host.writeForkSegments(tx, sessionId, []);
1437
+ for (const child of pins.readers) await detachForkWithin(host, tx, sessionId, child, false);
1438
+ return pins.sources;
1439
+ }
1440
+ /**
1441
+ * In `create`'s transaction, before the session is written: when a deleted session with this ID left a tombstone,
1442
+ * the forks still reading its rows get their own copy, and the rows go.
1443
+ */
1444
+ async function createOverTombstoneWithin(host, tx, sessionId) {
1445
+ if (!await isTombstoned(host, tx, sessionId)) return;
1446
+ for (const child of await lockedReferrers(host, tx, sessionId)) await detachForkWithin(host, tx, sessionId, child, false);
1447
+ await removeStoredRows(host, tx, sessionId);
1448
+ }
1069
1449
  /** Never load the clone writer in an ordinary open. Fence a lapsed transfer before deleting so a paused donor
1070
1450
  * cannot publish a partially swept transfer. When more rows remain, the new token stays expired. */
1071
1451
  async function tryCleanupForkStaging(database, dialect, table) {
@@ -1081,6 +1461,90 @@ async function tryCleanupForkStaging(database, dialect, table) {
1081
1461
  if ((await tx.run(`DELETE FROM ${table} WHERE transfer_id=? AND kind>${lease} AND (kind,seq,idx) IN (SELECT kind,seq,idx FROM ${table} WHERE transfer_id=? AND kind>${lease} LIMIT ?)`, id, id, 32)).changes < 32) await tx.run(`DELETE FROM ${table} WHERE transfer_id=? AND kind=${lease}`, id);
1082
1462
  });
1083
1463
  }
1464
+ // dist/core/storage/session/fork-view.js
1465
+ /** The largest view seq a range reads when it has no upper bound. */
1466
+ const FORK_VIEW_END = Number.MAX_SAFE_INTEGER;
1467
+ /**
1468
+ * The common table expression `name`: session `sessionId`'s rows of `table`, a table keyed by `(session_id, seq)` and
1469
+ * maybe more, whose view seqs are after `after` and at most `through`, with `columns` and `session_id`, `seq`, `src_id`
1470
+ * and `src_seq`. Bounding the range lets each source's index read only the rows asked for.
1471
+ */
1472
+ function forkView(tables, view) {
1473
+ const { name, table, sessionId, after, through, match } = view;
1474
+ const int = tables.dialect.types.int;
1475
+ const guard = tables.guard === void 0 ? "" : ` AND ${tables.guard}`;
1476
+ const matching = (alias) => match === void 0 ? "" : ` AND ${alias}${match.column} = ?`;
1477
+ const matched = match === void 0 ? [] : [match.value];
1478
+ const own = `SELECT session_id, seq${view.columns.map((column) => `, ${column}`).join("")}, session_id AS src_id, seq AS src_seq
1479
+ FROM ${table} WHERE session_id = ? AND seq > CAST(? AS ${int}) AND seq <= CAST(? AS ${int})${matching("")}${guard}`;
1480
+ if (tables.segments === void 0) return {
1481
+ cte: `${name} AS NOT MATERIALIZED (${own})`,
1482
+ params: [
1483
+ sessionId,
1484
+ after,
1485
+ through,
1486
+ ...matched
1487
+ ]
1488
+ };
1489
+ const { greatest, least } = tables.dialect;
1490
+ const rows = sourceRows(tables, table, view.columns, (x) => `${x}.seq >= ${greatest("f.from_seq", `CAST(? AS ${int}) + f.from_seq - f.base_seq`)}
1491
+ AND ${x}.seq <= ${least("f.to_seq", `CAST(? AS ${int}) + f.from_seq - f.base_seq - 1`)}${matching(`${x}.`)}`);
1492
+ return {
1493
+ cte: `${name} AS NOT MATERIALIZED (${`SELECT f.session_id AS session_id, f.base_seq + (x.seq - f.from_seq) + 1 AS seq${view.columns.map((column) => `, x.${column} AS ${column}`).join("")}, x.session_id AS src_id, x.seq AS src_seq
1494
+ FROM ${rows}
1495
+ WHERE f.session_id = ? AND f.base_seq < CAST(? AS ${int})
1496
+ AND f.base_seq + (f.to_seq - f.from_seq) + 1 > CAST(? AS ${int})${guard}`} UNION ALL ${own})`,
1497
+ params: [
1498
+ after,
1499
+ through,
1500
+ ...matched,
1501
+ sessionId,
1502
+ through,
1503
+ after,
1504
+ sessionId,
1505
+ after,
1506
+ through,
1507
+ ...matched
1508
+ ]
1509
+ };
1510
+ }
1511
+ /**
1512
+ * The segments `f` joined with the rows `x` of `table` each names that hold to `condition`, of the rows' alias and
1513
+ * `f`. On PostgreSQL the rows are read per segment through the table's index, as a lateral subquery
1514
+ * behind `OFFSET 0`, rather than by a hash join that would read the whole table; SQLite joins them that way itself.
1515
+ */
1516
+ function sourceRows(tables, table, columns, condition) {
1517
+ if (tables.dialect.name !== "postgres") return `${tables.segments} f JOIN ${table} x ON x.session_id = f.source_id AND ${condition("x")}`;
1518
+ return `${tables.segments} f CROSS JOIN LATERAL (SELECT r.session_id, r.seq${columns.map((column) => `, r.${column}`).join("")}
1519
+ FROM ${table} r WHERE r.session_id = f.source_id AND ${condition("r")} OFFSET 0) x`;
1520
+ }
1521
+ /**
1522
+ * The rows of `table` through the view of the session that `session`, an SQL expression such as a column of an outer
1523
+ * query, names: a derived table with `columns`, `session_id` and `seq`, and no parameters, for a statement that reads
1524
+ * the rows of many sessions, each in a subquery of its own. Each half of the union looks the session up by its key
1525
+ * itself, so neither reads the rows of every session to find one's.
1526
+ */
1527
+ function forkViewOf(tables, view, session) {
1528
+ const { table } = view;
1529
+ const guard = tables.guard === void 0 ? "" : ` AND ${tables.guard}`;
1530
+ const own = `SELECT session_id, seq${view.columns.map((column) => `, ${column}`).join("")} FROM ${table} WHERE session_id = ${session}${guard}`;
1531
+ if (tables.segments === void 0) return `(${own})`;
1532
+ return `(SELECT f.session_id AS session_id, f.base_seq + (x.seq - f.from_seq) + 1 AS seq${view.columns.map((column) => `, x.${column} AS ${column}`).join("")}
1533
+ FROM ${sourceRows(tables, table, view.columns, (x) => `${x}.seq >= f.from_seq AND ${x}.seq <= f.to_seq`)}
1534
+ WHERE f.session_id = ${session}${guard}
1535
+ UNION ALL ${own})`;
1536
+ }
1537
+ /** `sql`, a statement that may begin with `WITH`, with `views` first in its `WITH`. */
1538
+ function withForkViews(views, sql) {
1539
+ if (views.length === 0) return sql;
1540
+ const ctes = views.map((view) => view.cte).join(", ");
1541
+ const body = sql.trimStart();
1542
+ return /^WITH\s/i.test(body) ? `WITH ${ctes}, ${body.slice(4).trimStart()}` : `WITH ${ctes} ${body}`;
1543
+ }
1544
+ /** The parameters of `views`, in order, for the start of the statement's parameters. */
1545
+ function forkViewParams(views) {
1546
+ return views.flatMap((view) => view.params);
1547
+ }
1084
1548
  // dist/core/storage/session/sql-chat-records.js
1085
1549
  /** Rows one read fetches at most. */
1086
1550
  const READ_PAGE_ROWS = 64;
@@ -1211,10 +1675,22 @@ function sqlChatRecords(database, sessions, table, index, ledger) {
1211
1675
  * that knows only version 1 would read as stubs. A database stays at version 1, which older builds still open, until
1212
1676
  * this build writes its first chunked entry: that transaction moves the sessions meta to 2, and older builds refuse it
1213
1677
  * when next opened with `StorageSchemaVersionError`. Builds before 2 check only the meta row, on SQLite and Postgres alike.
1678
+ * Version 3 turns on forks that share their parent's history ({@link SESSION_SCHEMA_VERSION_SHARED_HISTORY}).
1214
1679
  */
1215
- const SESSION_SCHEMA_VERSION = 2;
1680
+ const SESSION_SCHEMA_VERSION = 3;
1216
1681
  /** The sessions schema of a database without chunked entries, which older builds read too. */
1217
1682
  const SESSION_SCHEMA_VERSION_UNCHUNKED = 1;
1683
+ /** The sessions schema the first chunked entry raises a version 1 database to, which builds since #4954 read. */
1684
+ const SESSION_SCHEMA_VERSION_CHUNKED = 2;
1685
+ /**
1686
+ * The sessions schema in which a fork shares its parent's history instead of copying it (#6560). A new database's
1687
+ * sessions schema starts at it; a store's open, or `atomic storage migrate`, raises an older one to it by itself once
1688
+ * no session of an older build runs there (`SqlSessionStore.enableSharedHistoryForks`); a fork or any other write never
1689
+ * does. Builds that know only versions 1
1690
+ * and 2 refuse it, at their open and in every transaction, rather than read a fork's own rows as its whole history.
1691
+ * `SqlSessionStore.sharedHistoryForks(tx)` tells a transaction whether its database is there.
1692
+ */
1693
+ const SESSION_SCHEMA_VERSION_SHARED_HISTORY = 3;
1218
1694
  /** The schema domain of the session tables in the prefix's migration ledger. */
1219
1695
  const SESSION_DOMAIN = "sessions";
1220
1696
  /** The ledger step, `schema:session-fillfactor`, that sets the sessions table's fillfactor on PostgreSQL (#6560). */
@@ -1222,6 +1698,19 @@ const SESSION_FILLFACTOR_DOMAIN = "session-fillfactor";
1222
1698
  /** The fillfactor of the sessions table on PostgreSQL: a fifth of each page stays free for head row updates. */
1223
1699
  const SESSION_ROW_FILLFACTOR = 80;
1224
1700
  /**
1701
+ * The ledger step, `schema:session-append-function`, that creates the session append function on PostgreSQL (#6599).
1702
+ * Raise its revision whenever the function's body changes: `atomic storage migrate` of an older build then leaves the
1703
+ * newer body in place.
1704
+ */
1705
+ const SESSION_APPEND_FUNCTION_DOMAIN = "session-append-function";
1706
+ const SESSION_APPEND_FUNCTION_REVISION = 1;
1707
+ /**
1708
+ * The session append function's name under the store's prefix. The version in the name is the function's contract:
1709
+ * its arguments and what it answers. A build that needs another contract creates a function of a new name beside
1710
+ * this one, which builds that call this one keep using.
1711
+ */
1712
+ const SESSION_APPEND_FUNCTION = "append_v1";
1713
+ /**
1225
1714
  * The most bytes of a chunked session blob one row holds. New blobs use a header row and rows of at most this size,
1226
1715
  * so their bound and returned values stay within it: libSQL servers cap a row and a bound value (sqld's default is
1227
1716
  * 5 MB) and a statement's response (10 MB), and the HTTP protocol carries a blob as base64 in JSON, about 1.4 MB for
@@ -1268,6 +1757,12 @@ const SESSION_FORK_STAGING_TABLES = Object.freeze({ forkStaging: "fork_staging"
1268
1757
  /** The schema domain, in the prefix's migration ledger, of the table of open sessions (#4971). */
1269
1758
  const SESSION_PRESENCE_DOMAIN = "session-presence";
1270
1759
  const SESSION_PRESENCE_TABLES = Object.freeze({ open: "open" });
1760
+ /** The donor's segments name a session the fork did not lock: the fork runs again, locking it too (#6560). */
1761
+ var ForkSourcesMoved = class extends Error {
1762
+ constructor() {
1763
+ super("The fork's source moved its history while the fork read it");
1764
+ }
1765
+ };
1271
1766
  function windowIndex(state, seq) {
1272
1767
  return isSessionResumeIndex(state.windowResume, seq) ? state.windowResume : isSessionResumeIndex(state.resume, seq) ? state.resume : void 0;
1273
1768
  }
@@ -1295,6 +1790,11 @@ const SESSION_READ_FETCH = {
1295
1790
  min: 1,
1296
1791
  max: 8192
1297
1792
  };
1793
+ /**
1794
+ * The seqs of a shared history one page of a selective scan reads at most (#6560): the page then accounts for the range
1795
+ * through them, and the next page reads the next ones.
1796
+ */
1797
+ const SCAN_SELECT_WINDOW = 4096;
1298
1798
  const SESSION_READ_INLINE_BYTES = 4096;
1299
1799
  function nextFetch(limit, rows) {
1300
1800
  const kept = rows.length;
@@ -1470,9 +1970,11 @@ async function entryByteLengthOf(database) {
1470
1970
  }
1471
1971
  /**
1472
1972
  * The most bytes of statements a session write sends as one batch: an ordinary message's are far fewer. A larger
1473
- * write, an import or a fork's whole window, runs its statements one at a time as they are made.
1973
+ * write, an import or a fork's whole window, sends its statements a request's worth at a time as they are made.
1474
1974
  */
1475
1975
  const STATEMENT_BATCH_BYTES = 1048576;
1976
+ /** The most sessions whose last written row a store remembers for appends through the append function. */
1977
+ const WRITTEN_ROWS = 64;
1476
1978
  /** About how many bytes `statement` carries: its text and its parameters. */
1477
1979
  function statementBytes(statement) {
1478
1980
  let bytes = statement.sql.length;
@@ -1481,6 +1983,80 @@ function statementBytes(statement) {
1481
1983
  else bytes += 8;
1482
1984
  return bytes;
1483
1985
  }
1986
+ const ENTRY_COLUMNS = [
1987
+ "session_id",
1988
+ "seq",
1989
+ "entry_id",
1990
+ "entry_json",
1991
+ "chunks"
1992
+ ];
1993
+ const TEXT_COLUMNS = [
1994
+ "session_id",
1995
+ "seq",
1996
+ "text_json"
1997
+ ];
1998
+ /** The most rows one insert of {@link RowInserts} names: 320 parameters for an entry's five, below SQLite's old 999. */
1999
+ const ROWS_PER_INSERT = 64;
2000
+ /** The most bytes of values one insert of {@link RowInserts} takes, unless one row's alone are more. */
2001
+ const ROW_INSERT_BYTES = 262144;
2002
+ /**
2003
+ * Rows of `table` inserted several to a statement (#6560): one statement's SQL prepared, and its triggers compiled, for
2004
+ * up to {@link ROWS_PER_INSERT} rows, not for each, so an append of a burst prepares once on a server that keeps no
2005
+ * prepared statements. The rows go in in the order they are added, each as its own insert would, the triggers firing
2006
+ * for each in turn: the triggers read only what the triggers of the rows before wrote, not the rows themselves.
2007
+ */
2008
+ var RowInserts = class {
2009
+ table;
2010
+ columns;
2011
+ sqls = [];
2012
+ rows = [];
2013
+ bytes = 0;
2014
+ constructor(table, columns) {
2015
+ this.table = table;
2016
+ this.columns = columns;
2017
+ }
2018
+ /** The insert of `count` rows. */
2019
+ sql(count) {
2020
+ let sql = this.sqls[count];
2021
+ if (sql === void 0) {
2022
+ const row = `(${this.columns.map(() => "?").join(", ")})`;
2023
+ sql = `INSERT INTO ${this.table} (${this.columns.join(", ")}) VALUES ${Array(count).fill(row).join(", ")}`;
2024
+ this.sqls[count] = sql;
2025
+ }
2026
+ return sql;
2027
+ }
2028
+ /** Adds `row`, and yields the inserts of the rows before it once they are as many, or as large, as one takes. */
2029
+ *add(row) {
2030
+ const bytes = statementBytes({
2031
+ sql: "",
2032
+ params: row
2033
+ });
2034
+ if (this.rows.length === ROWS_PER_INSERT || this.rows.length > 0 && this.bytes + bytes > ROW_INSERT_BYTES) yield* this.drain();
2035
+ this.rows.push(row);
2036
+ this.bytes += bytes;
2037
+ }
2038
+ /** The inserts of the rows added and not yet yielded. */
2039
+ *drain() {
2040
+ const rows = this.rows;
2041
+ if (rows.length === 0) return;
2042
+ this.rows = [];
2043
+ this.bytes = 0;
2044
+ yield {
2045
+ sql: this.sql(rows.length),
2046
+ params: rows.flat()
2047
+ };
2048
+ }
2049
+ };
2050
+ /** What `first` yields, then `last`. */
2051
+ function* thenAll(first, last) {
2052
+ yield* first;
2053
+ yield* last;
2054
+ }
2055
+ /** `first`, then what is left of `rest`. */
2056
+ function* withRest(first, rest) {
2057
+ yield* first;
2058
+ for (let next = rest.next(); next.done !== true; next = rest.next()) yield next.value;
2059
+ }
1484
2060
  /**
1485
2061
  * Writes of one transaction sent without waiting for each answer: the connection runs them in the order they were
1486
2062
  * sent, behind the transaction's earlier calls and ahead of its later ones, so a read made after `send` sees them. On a
@@ -1543,6 +2119,24 @@ var SqlSessionStore = class SqlSessionStore {
1543
2119
  chatStore;
1544
2120
  /** The database's reader handle, once a read opened it: see `readerDatabase`. */
1545
2121
  reader;
2122
+ /** The sessions schema version each transaction read first, by its handle: see `sharedHistoryForks`. */
2123
+ schemaVersions = /* @__PURE__ */ new WeakMap();
2124
+ /** The fork tables under this store's prefix, which exist once its sessions schema is version 3 (#6560). */
2125
+ forkTables;
2126
+ /** See {@link forkLinks}. */
2127
+ forkLinkStatements;
2128
+ /**
2129
+ * Whether a read of this store found its sessions schema at {@link SESSION_SCHEMA_VERSION_SHARED_HISTORY}: one way,
2130
+ * as the switch is. A read outside a transaction reads sessions through their views once it is set, and before that
2131
+ * reads the tables themselves on the condition, checked in the read's own snapshot, that the schema is older.
2132
+ */
2133
+ sharedHistorySeen = false;
2134
+ /** For each transaction, whether each session whose row it read has fork segments, as that read found (#6560). */
2135
+ forkedIn = /* @__PURE__ */ new WeakMap();
2136
+ /** Whether each recently read session had fork segments: only a first guess, which a read checks (#6560). */
2137
+ forkedSessions = /* @__PURE__ */ new Map();
2138
+ /** The sessions each recently forked session's segments named when this store last read them (#6560). */
2139
+ forkSources = /* @__PURE__ */ new Map();
1546
2140
  /**
1547
2141
  * Absent on a local libSQL file, which then behaves as before: @libsql/client waits for another process's write
1548
2142
  * lock on the calling thread, even to begin a transaction, so a side write would stop the event loop where an
@@ -1575,8 +2169,16 @@ var SqlSessionStore = class SqlSessionStore {
1575
2169
  forkStagingTable;
1576
2170
  /** The generation each recently read session's row held at a revision: see `generation`. */
1577
2171
  generations = /* @__PURE__ */ new Map();
1578
- constructor(database, tables, prefix, cwdMatcher, snapshotBlobs, legacyBlobData, searchIndex, entryByteLength) {
2172
+ /**
2173
+ * The session append function of this store's tables, when the open found it and this role may run it (#6599):
2174
+ * `atomic storage migrate` creates it. Absent elsewhere, where appends take their two round trips as before.
2175
+ */
2176
+ appendFunction;
2177
+ /** The row each recent write of this store left for its session, which an append through the function plans from. */
2178
+ writtenRows = /* @__PURE__ */ new Map();
2179
+ constructor(database, tables, prefix, cwdMatcher, snapshotBlobs, legacyBlobData, searchIndex, entryByteLength, appendFunction) {
1579
2180
  this.database = database;
2181
+ if (appendFunction !== void 0) this.appendFunction = appendFunction;
1580
2182
  this.dialect = dialectOf(database);
1581
2183
  this.entryByteLength = entryByteLength;
1582
2184
  this.tables = tables;
@@ -1604,6 +2206,7 @@ var SqlSessionStore = class SqlSessionStore {
1604
2206
  });
1605
2207
  });
1606
2208
  this.forkStagingTable = renderStorageIdentifiers("sessions", SESSION_FORK_STAGING_TABLES, prefix).forkStaging;
2209
+ this.forkTables = sessionForkTables(prefix);
1607
2210
  }
1608
2211
  /** Bind an existing transcript for the storage search command. No schema setup, markers or search index. */
1609
2212
  static async openTranscriptReader(database) {
@@ -1619,6 +2222,8 @@ var SqlSessionStore = class SqlSessionStore {
1619
2222
  static async openWithCatalog(database, options) {
1620
2223
  const tables = renderStorageIdentifiers("sessions", SESSION_TABLES, options.prefix);
1621
2224
  let legacyBlobData = false;
2225
+ const forkTables = sessionForkTables(options.prefix);
2226
+ let createdShared = false;
1622
2227
  const createTables = async (tx, dialect) => {
1623
2228
  const { int, text, blob } = dialect.types;
1624
2229
  const strict = dialect.tableOptions;
@@ -1628,7 +2233,7 @@ var SqlSessionStore = class SqlSessionStore {
1628
2233
  return async () => await tx.get(probe.sql, ...probe.params) !== void 0;
1629
2234
  };
1630
2235
  const [versions] = await statementBatch(tx, [`CREATE TABLE IF NOT EXISTS ${tables.meta} (schema_version ${int} NOT NULL)${strict}`], [() => tx.all(`SELECT schema_version FROM ${tables.meta}`)]);
1631
- for (const version of versions) assertStorageSchemaVersion("sessions", version.schema_version, 2, SESSION_SCHEMA_VERSION_UNCHUNKED);
2236
+ for (const version of versions) assertStorageSchemaVersion("sessions", version.schema_version, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
1632
2237
  const tablesScript = `
1633
2238
  CREATE TABLE IF NOT EXISTS ${tables.sessions} (
1634
2239
  id ${text} PRIMARY KEY, cwd ${text} NOT NULL, created_at ${text} NOT NULL,
@@ -1656,10 +2261,19 @@ var SqlSessionStore = class SqlSessionStore {
1656
2261
  PRIMARY KEY(session_id, hash, idx)
1657
2262
  )${strict};
1658
2263
  `;
1659
- const [revision, data] = await statementBatch(tx, [versions.length === 0 && {
1660
- sql: `INSERT INTO ${tables.meta} VALUES (?)`,
1661
- params: [SESSION_SCHEMA_VERSION_UNCHUNKED]
1662
- }, tablesScript], [columnExists(tables.sessions, "revision"), columnExists(tables.blobs, "data")]);
2264
+ const created = versions.length === 0;
2265
+ const [revision, data] = await statementBatch(tx, [
2266
+ created && {
2267
+ sql: `INSERT INTO ${tables.meta} VALUES (?)`,
2268
+ params: [3]
2269
+ },
2270
+ created ? `${tablesScript}\n${sharedHistoryTablesScript(dialect, forkTables)}` : tablesScript,
2271
+ created && dialect.versionedMigrations && {
2272
+ sql: `INSERT INTO ${storageMigrationTable(options.prefix)} (domain, version, applied_at) VALUES (?, ?, ${dialect.nowMs}) ON CONFLICT DO NOTHING`,
2273
+ params: ["sessions", 3]
2274
+ }
2275
+ ], [columnExists(tables.sessions, "revision"), columnExists(tables.blobs, "data")]);
2276
+ createdShared = created;
1663
2277
  legacyBlobData = data;
1664
2278
  const [chunks] = legacyBlobData ? await statementBatch(tx, [], [columnExists(tables.blobs, "chunks")]) : [true];
1665
2279
  await statementBatch(tx, [!revision && `ALTER TABLE ${tables.sessions} ADD COLUMN revision ${text} NOT NULL DEFAULT ''`, !chunks && `ALTER TABLE ${tables.blobs} ADD COLUMN chunks ${int} NOT NULL DEFAULT -1`], []);
@@ -1693,38 +2307,56 @@ var SqlSessionStore = class SqlSessionStore {
1693
2307
  };
1694
2308
  const presence = renderStorageIdentifiers("sessions", SESSION_PRESENCE_TABLES, options.prefix);
1695
2309
  const current = await SqlSessionStore.currentSchema(database, tables, presence.open, database.readOnly === true ? void 0 : orphanedEntryKeys);
2310
+ let sharedHistory;
1696
2311
  if (current !== void 0) {
1697
2312
  legacyBlobData = current.legacyBlobData;
2313
+ sharedHistory = current.sharedHistory;
1698
2314
  if (current.orphaned) await database.transaction(async (tx) => {
1699
- await assertStoredSchemaVersion(tx, { sql: `SELECT schema_version FROM ${tables.meta}` }, "sessions", 2, "schema_version", SESSION_SCHEMA_VERSION_UNCHUNKED);
2315
+ await assertStoredSchemaVersion(tx, { sql: `SELECT schema_version FROM ${tables.meta}` }, "sessions", 3, "schema_version", SESSION_SCHEMA_VERSION_UNCHUNKED);
1700
2316
  await tx.run(removeOrphanedEntryChunks.sql);
1701
2317
  }).catch((error) => {
1702
2318
  if (error instanceof StorageSchemaVersionError) throw error;
1703
2319
  });
1704
- } else await applyStorageMigrationsTogether(database, [{
1705
- domain: SESSION_DOMAIN,
1706
- steps: [{
1707
- version: 1,
1708
- up: createTables
1709
- }, {
1710
- version: 2,
1711
- up: addEntryChunks
1712
- }],
1713
- options: { table: storageMigrationTable(options.prefix) }
1714
- }, {
1715
- domain: SESSION_PRESENCE_DOMAIN,
1716
- steps: [{
1717
- version: 1,
1718
- up: (tx, dialect) => SqlSessionOpenMarkers.createTable(tx, dialect, presence.open)
2320
+ } else {
2321
+ const [sessionsSchema] = await applyStorageMigrationsTogether(database, [{
2322
+ domain: SESSION_DOMAIN,
2323
+ steps: [{
2324
+ version: 1,
2325
+ up: createTables
2326
+ }, {
2327
+ version: 2,
2328
+ up: addEntryChunks
2329
+ }],
2330
+ options: {
2331
+ table: storageMigrationTable(options.prefix),
2332
+ recordedThrough: 3
2333
+ }
1719
2334
  }, {
1720
- version: 2,
1721
- up: (tx, dialect) => SqlSessionOpenMarkers.addSchemaVersion(tx, dialect, presence.open)
1722
- }],
1723
- options: {
1724
- table: storageMigrationTable(options.prefix),
1725
- acceptNewer: true
1726
- }
1727
- }]);
2335
+ domain: SESSION_PRESENCE_DOMAIN,
2336
+ steps: [
2337
+ {
2338
+ version: 1,
2339
+ up: (tx, dialect) => SqlSessionOpenMarkers.createTable(tx, dialect, presence.open)
2340
+ },
2341
+ {
2342
+ version: 2,
2343
+ up: (tx, dialect) => SqlSessionOpenMarkers.addSchemaVersion(tx, dialect, presence.open)
2344
+ },
2345
+ {
2346
+ version: 3,
2347
+ up: (tx, dialect) => SqlSessionOpenMarkers.addBuild(tx, dialect, presence.open)
2348
+ }
2349
+ ],
2350
+ options: {
2351
+ table: storageMigrationTable(options.prefix),
2352
+ acceptNewer: true
2353
+ }
2354
+ }]);
2355
+ if (createdShared) {
2356
+ sharedHistory = true;
2357
+ noteStorageSchemaTables(database, Object.values(forkTables));
2358
+ } else if (dialectOf(database).versionedMigrations) sharedHistory = (sessionsSchema?.version ?? 0) >= 3;
2359
+ }
1728
2360
  await ensureTableFillfactor(database, {
1729
2361
  ledger: storageMigrationTable(options.prefix),
1730
2362
  domain: SESSION_FILLFACTOR_DOMAIN,
@@ -1732,6 +2364,13 @@ var SqlSessionStore = class SqlSessionStore {
1732
2364
  table: tables.sessions,
1733
2365
  fillfactor: SESSION_ROW_FILLFACTOR
1734
2366
  });
2367
+ const markers = new SqlSessionOpenMarkers(database, presence.open, () => store.assertOpen());
2368
+ let shared = sharedHistory === true;
2369
+ if (sharedHistory !== true && database.readOnly !== true) {
2370
+ const switched = await SqlSessionStore.switchAtOpen(database, options.prefix ?? "", tables, markers, sharedHistory === false);
2371
+ if (switched) refreshStorageSchemaCatalog(database);
2372
+ shared = switched;
2373
+ }
1735
2374
  const staging = renderStorageIdentifiers("sessions", SESSION_FORK_STAGING_TABLES, options.prefix).forkStaging;
1736
2375
  const stagingProbe = dialectOf(database).tableExists(staging);
1737
2376
  const catalog = await schemaCatalogOf(database);
@@ -1742,8 +2381,11 @@ var SqlSessionStore = class SqlSessionStore {
1742
2381
  SqlSessionSearchIndex.open(database, tables, options.prefix),
1743
2382
  entryByteLengthOf(database)
1744
2383
  ]);
1745
- const store = new SqlSessionStore(database, tables, options.prefix, options.cwdMatcher, blobs, legacyBlobData, searchIndex, entryByteLength);
1746
- store.openMarkers = new SqlSessionOpenMarkers(database, presence.open, () => store.assertOpen());
2384
+ const appendFunction = renderStorageIdentifiers("sessions", { append: SESSION_APPEND_FUNCTION }, options.prefix).append;
2385
+ const appendsThroughFunction = catalog?.hasFunction?.(appendFunction) === true && database.autocommit !== void 0 && typeof blobs.storedBlobsQuery === "function";
2386
+ const store = new SqlSessionStore(database, tables, options.prefix, options.cwdMatcher, blobs, legacyBlobData, searchIndex, entryByteLength, appendsThroughFunction ? appendFunction : void 0);
2387
+ store.openMarkers = markers;
2388
+ if (shared) store.noteSchemaVersion(3);
1747
2389
  if (await staged) await store.cleanupForkStaging();
1748
2390
  return store;
1749
2391
  }
@@ -1772,7 +2414,8 @@ var SqlSessionStore = class SqlSessionStore {
1772
2414
  [tables.sessions, "revision"],
1773
2415
  [tables.entries, "chunks"],
1774
2416
  [tables.blobs, "chunks"],
1775
- [open, "schema_version"]
2417
+ [open, "schema_version"],
2418
+ [open, "build"]
1776
2419
  ];
1777
2420
  const reading = schemaCatalogOf(database);
1778
2421
  const orphaned = orphans === void 0 ? void 0 : database.get(`SELECT 1 FROM (${orphans}) AS orphaned LIMIT 1`);
@@ -1792,10 +2435,11 @@ var SqlSessionStore = class SqlSessionStore {
1792
2435
  legacyBlobs = legacyFound !== void 0;
1793
2436
  }
1794
2437
  const versions = await versionsRead;
1795
- if (versions.length === 0 || versions.some((row) => row.schema_version !== SESSION_SCHEMA_VERSION_UNCHUNKED && row.schema_version !== 2)) return void 0;
2438
+ if (versions.length === 0 || versions.some((row) => typeof row.schema_version !== "number" || !Number.isInteger(row.schema_version) || row.schema_version < SESSION_SCHEMA_VERSION_UNCHUNKED || row.schema_version > 3)) return void 0;
1796
2439
  return {
1797
2440
  legacyBlobData: legacyBlobs,
1798
- orphaned: await orphaned !== void 0
2441
+ orphaned: await orphaned !== void 0,
2442
+ sharedHistory: versions.every((row) => Number(row.schema_version) >= 3)
1799
2443
  };
1800
2444
  }
1801
2445
  /**
@@ -1883,8 +2527,215 @@ var SqlSessionStore = class SqlSessionStore {
1883
2527
  params: []
1884
2528
  };
1885
2529
  }
2530
+ /**
2531
+ * Reads the sessions schema version through `executor` and refuses one this build does not read. The answer is kept
2532
+ * for `executor`, a transaction's own handle, so {@link sharedHistoryForks} costs that transaction no read.
2533
+ */
1886
2534
  assertReadableSchema(executor) {
1887
- return assertStoredSchemaVersion(executor, this.schemaCheck(), "sessions", 2, "schema_version", SESSION_SCHEMA_VERSION_UNCHUNKED);
2535
+ const check = this.schemaCheck();
2536
+ const version = executor.get(check.sql, ...check.params).then((row) => {
2537
+ const found = row?.schema_version ?? null;
2538
+ assertStorageSchemaVersion("sessions", found, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
2539
+ this.noteSchemaVersion(found);
2540
+ return found;
2541
+ });
2542
+ this.schemaVersions.set(executor, version);
2543
+ return version.then(() => {});
2544
+ }
2545
+ /**
2546
+ * Whether the database `tx` runs in has forks that share their parent's history turned on: its sessions schema, as
2547
+ * `tx` read it, is {@link SESSION_SCHEMA_VERSION_SHARED_HISTORY} (#6560). Every transaction of this store reads the
2548
+ * version first, so this costs no further read there; `tx` of any other transaction reads it once. Asked again in each
2549
+ * transaction, never kept on the store: another process may turn the forks on at any time, and the switch is one way,
2550
+ * so an answer read before it only means a fork is copied.
2551
+ */
2552
+ async sharedHistoryForks(tx) {
2553
+ if (!this.schemaVersions.has(tx)) await this.assertReadableSchema(tx);
2554
+ return await this.schemaVersions.get(tx) >= 3;
2555
+ }
2556
+ /** Notes a sessions schema version a read of this store found: see {@link sharedHistorySeen}. */
2557
+ noteSchemaVersion(version) {
2558
+ if (typeof version === "number" && version >= 3) this.sharedHistorySeen = true;
2559
+ }
2560
+ /** How transaction `tx` reads a session's rows: through its view where its database has shared history (#6560). */
2561
+ async viewTables(tx, sessionId) {
2562
+ return {
2563
+ segments: !(sessionId !== void 0 && this.forkedIn.get(tx)?.get(sessionId) === false) && await this.sharedHistoryForks(tx) ? this.forkTables.forkSegments : void 0,
2564
+ dialect: this.dialect
2565
+ };
2566
+ }
2567
+ /**
2568
+ * A column, `forked`, of a read of a sessions row whose id is `id`: 1 when the session has fork segments (#6560),
2569
+ * found by the segments' key. Only where `segments`, the fork segments table, exists.
2570
+ */
2571
+ forkedColumn(segments, id = "id") {
2572
+ return segments === void 0 ? "" : `, CASE WHEN EXISTS (SELECT 1 FROM ${segments} WHERE session_id = ${id}) THEN 1 ELSE 0 END AS forked`;
2573
+ }
2574
+ /**
2575
+ * Notes what a read of session `sessionId`'s row in transaction `tx` found, `forked` from {@link forkedColumn}: the
2576
+ * transaction's later reads of a session without segments read its tables directly. The store remembers it too, as a
2577
+ * first guess for a read that sends its statements before that row's answer, and checks it against that answer.
2578
+ */
2579
+ noteForked(tx, sessionId, forked) {
2580
+ if (forked === void 0 || forked === null) return;
2581
+ const value = Number(forked) === 1;
2582
+ if (tx !== void 0) {
2583
+ const known = this.forkedIn.get(tx) ?? /* @__PURE__ */ new Map();
2584
+ this.forkedIn.set(tx, known);
2585
+ known.set(sessionId, value);
2586
+ }
2587
+ this.forkedSessions.delete(sessionId);
2588
+ this.forkedSessions.set(sessionId, value);
2589
+ while (this.forkedSessions.size > 256) this.forkedSessions.delete(this.forkedSessions.keys().next().value);
2590
+ }
2591
+ /**
2592
+ * How a read outside a transaction reads a session's rows: through its view once this store has seen shared history,
2593
+ * and otherwise from the tables themselves, but only while the schema, read in the same statement, is older. Such a
2594
+ * read that finds nothing asks `outsideTransaction` to try again.
2595
+ */
2596
+ outsideViewTables() {
2597
+ const version = `(SELECT max(schema_version) FROM ${this.tables.meta})`;
2598
+ return this.sharedHistorySeen ? {
2599
+ segments: this.forkTables.forkSegments,
2600
+ dialect: this.dialect,
2601
+ guard: `${version} <= 3`
2602
+ } : {
2603
+ segments: void 0,
2604
+ dialect: this.dialect,
2605
+ guard: `${version} < 3`
2606
+ };
2607
+ }
2608
+ /**
2609
+ * `read`, a read outside a transaction of a session's rows through `outsideViewTables`, once more through the views
2610
+ * when it found nothing (`found` says) before this store had seen shared history, and the schema, read after it, is
2611
+ * now at version 3: the read's own check then held its rows back. The switch is one way, so a schema older than 3
2612
+ * read after the read was older at the read too, and its answer stands.
2613
+ */
2614
+ async outsideTransaction(read, found) {
2615
+ const seen = this.sharedHistorySeen;
2616
+ const value = await read(this.outsideViewTables());
2617
+ if (found(value)) return value;
2618
+ return await this.schemaNowShared(seen) ? read(this.outsideViewTables()) : value;
2619
+ }
2620
+ /**
2621
+ * `read`, a read outside a transaction of session `sessionId`'s rows that also reads, as `forked`, whether the
2622
+ * session has fork segments, through `outsideTransaction` (#6560): from the tables themselves when this store last
2623
+ * found the session without segments, and through its view again when the read's own answer says it now has them.
2624
+ */
2625
+ outsideSessionRead(sessionId, read, found, forkedOf) {
2626
+ return this.outsideTransaction(async (tables) => {
2627
+ const plain = tables.segments !== void 0 && this.forkedSessions.get(sessionId) === false;
2628
+ const value = await read(plain ? {
2629
+ ...tables,
2630
+ segments: void 0
2631
+ } : tables);
2632
+ const forked = forkedOf(value);
2633
+ this.noteForked(void 0, sessionId, forked);
2634
+ return plain && Number(forked) === 1 ? read(tables) : value;
2635
+ }, found);
2636
+ }
2637
+ /** The `forked` column of a read outside a transaction of the sessions row `id` names: see `outsideSessionRead`. */
2638
+ outsideForkedColumn(id) {
2639
+ return this.forkedColumn(this.sharedHistorySeen ? this.forkTables.forkSegments : void 0, id);
2640
+ }
2641
+ /**
2642
+ * After a read outside a transaction found nothing: reads the sessions schema, refuses one this build does not read,
2643
+ * and tells whether shared history is on now where the read, made with `seen` as it was, read the tables themselves.
2644
+ */
2645
+ async schemaNowShared(seen) {
2646
+ const row = await this.database.get(`SELECT max(schema_version) AS version FROM ${this.tables.meta}`);
2647
+ const version = row?.version == null ? null : Number(row.version);
2648
+ assertStorageSchemaVersion("sessions", version, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
2649
+ this.noteSchemaVersion(version);
2650
+ return this.sharedHistorySeen && !seen;
2651
+ }
2652
+ /**
2653
+ * Turns on forks that share their parent's history (#6560), as a store's open does by itself: see
2654
+ * {@link SqlSessionStore.switchSharedHistory}. `live` judges whether the process of an older build's open-session
2655
+ * marker still runs; the application's judge by default.
2656
+ */
2657
+ enableSharedHistoryForks(options = {}) {
2658
+ this.assertOpen();
2659
+ return SqlSessionStore.switchSharedHistory(this.database, this.prefix, this.tables, this.openMarkers, options.live ?? sharedHistorySwitchHost().live);
2660
+ }
2661
+ /**
2662
+ * The switch to shared-history forks (#6560), in one transaction: creates the fork tables, records version 3 in the
2663
+ * migration ledger where there is one, and raises the sessions schema to it, so that builds which do not read it
2664
+ * refuse the database at their next open or transaction. One way: nothing lowers it again.
2665
+ *
2666
+ * It never leaves an older process reading what it cannot read: while `live` judges any open-session marker of an
2667
+ * older build to be a running process, it changes nothing and is `deferred`, and the next open tries again. The
2668
+ * transaction is the only writer of the whole database while it runs, so every session write either finished before
2669
+ * it, or starts after it and reads the new version first. Two hosts switching at once run one after the other, and
2670
+ * the second finds it `already` done.
2671
+ */
2672
+ static switchSharedHistory(database, prefix, tables, markers, live) {
2673
+ const dialect = dialectOf(database);
2674
+ return database.transaction(async (tx) => {
2675
+ const [row, older] = await statementBatch(tx, [], [() => tx.get(`SELECT max(schema_version) AS schema_version FROM ${tables.meta}`), () => markers.olderThan(tx, 3)]);
2676
+ const version = row?.schema_version ?? null;
2677
+ assertStorageSchemaVersion("sessions", version, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
2678
+ if (Number(version) >= 3) return { status: "already" };
2679
+ const holders = await liveMarkers(older, live);
2680
+ if (holders.length > 0) return {
2681
+ status: "deferred",
2682
+ holders
2683
+ };
2684
+ await createSharedHistoryTables(tx, dialect, sessionForkTables(prefix));
2685
+ await statementBatch(tx, [
2686
+ dialect.dropTrigger(legacyForkLinksTriggerName(tables.entries), tables.entries, true),
2687
+ dialect.versionedMigrations && {
2688
+ sql: `INSERT INTO ${storageMigrationTable(prefix)} (domain, version, applied_at) VALUES (?, ?, ${dialect.nowMs}) ON CONFLICT DO NOTHING`,
2689
+ params: ["sessions", 3]
2690
+ },
2691
+ {
2692
+ sql: `UPDATE ${tables.meta} SET schema_version = ? WHERE schema_version < ?`,
2693
+ params: [3, 3]
2694
+ }
2695
+ ], []);
2696
+ return { status: "enabled" };
2697
+ }, {
2698
+ retryTransientFailures: true,
2699
+ concurrency: { kind: "serial" }
2700
+ });
2701
+ }
2702
+ /**
2703
+ * An open's switch to shared-history forks, true when it switched the database. With `precheck`, for an open that
2704
+ * read the schema without a lock, it first reads, still without one, the version and the markers of older builds
2705
+ * together, so an open that must leave the switch for later, while an older build runs a session, takes no lock and
2706
+ * writes nothing; an open that set the schema up under the write lock goes straight to the switch. A switch that cannot run, such as for a role without the
2707
+ * privilege to create tables, is left for a later open or `atomic storage migrate`; forks copy meanwhile. Either way
2708
+ * the open goes on, and only the debug log notes it.
2709
+ */
2710
+ static async switchAtOpen(database, prefix, tables, markers, precheck) {
2711
+ const host = sharedHistorySwitchHost();
2712
+ const deferred = (holders) => host.skipped({
2713
+ reason: "older-sessions-running",
2714
+ prefix,
2715
+ sessions: holders.length,
2716
+ holders: holders.map((holder) => `${holder.host}:${holder.pid}`).join(", ")
2717
+ });
2718
+ try {
2719
+ if (precheck) {
2720
+ const [found, older] = await statementBatch(database, [], [() => database.get(`SELECT max(schema_version) AS schema_version FROM ${tables.meta}`), () => markers.olderThan(database, 3)]);
2721
+ if (Number(found?.schema_version) >= 3) return false;
2722
+ const holders = await liveMarkers(older, host.live);
2723
+ if (holders.length > 0) {
2724
+ deferred(holders);
2725
+ return false;
2726
+ }
2727
+ }
2728
+ const outcome = await SqlSessionStore.switchSharedHistory(database, prefix, tables, markers, host.live);
2729
+ if (outcome.status === "deferred") deferred(outcome.holders);
2730
+ return outcome.status === "enabled";
2731
+ } catch (error) {
2732
+ host.skipped({
2733
+ reason: "switch-failed",
2734
+ prefix,
2735
+ error: error.message
2736
+ });
2737
+ return false;
2738
+ }
1888
2739
  }
1889
2740
  get descriptor() {
1890
2741
  return {
@@ -1896,24 +2747,41 @@ var SqlSessionStore = class SqlSessionStore {
1896
2747
  this.assertOpen();
1897
2748
  validateSessionHeader(header);
1898
2749
  validateSessionEntries(entries);
1899
- const existing = {
2750
+ const tombstones = this.sharedHistorySeen;
2751
+ const existing = tombstones ? {
2752
+ sql: `SELECT (SELECT id FROM ${this.tables.sessions} WHERE id = ?) AS id, (SELECT session_id FROM ${this.forkTables.forkTombstones} WHERE session_id = ?) AS tombstone`,
2753
+ params: [header.id, header.id]
2754
+ } : {
1900
2755
  sql: `SELECT id FROM ${this.tables.sessions} WHERE id = ?`,
1901
2756
  params: [header.id]
1902
2757
  };
1903
- return this.transactionCheckedAlongside(async (tx, checked) => {
1904
- if (await tx.get(existing.sql, ...existing.params)) throw new SessionExistsError$1(header.id);
2758
+ let written = [];
2759
+ let writtenRow;
2760
+ const created = await this.transactionCheckedAlongside(async (tx, checked) => {
2761
+ writtenRow = void 0;
2762
+ const found = await tx.get(existing.sql, ...existing.params);
2763
+ if (found?.id != null) throw new SessionExistsError$1(header.id);
2764
+ if (await this.sharedHistoryForks(tx) && (tombstones ? found?.tombstone != null : await this.hasForkTombstone(tx, header.id))) await createOverTombstoneWithin(this.forkHost(), tx, header.id).catch((error) => {
2765
+ noteForkCopyRefusal(error, "create");
2766
+ throw error;
2767
+ });
1905
2768
  const summary = this.summaryWrite(header.id, {
1906
2769
  header,
1907
2770
  entries,
1908
2771
  lastSeq: entries.length
1909
2772
  });
1910
2773
  await checked;
1911
- await this.writeEntries(tx, summary.statement, this.entryWrites(header.id, entries, 0, summary.texts));
2774
+ written = [];
2775
+ writtenRow = summary.row;
2776
+ await this.writeEntries(tx, summary.statement, this.entryWrites(header.id, entries, 0, summary.texts, true, written));
1912
2777
  return {
1913
2778
  lastSeq: entries.length,
1914
2779
  epoch: summary.epoch
1915
2780
  };
1916
2781
  }, this.sessionWrite(header.id, existing));
2782
+ this.noteWritten(header.id, created.epoch, written);
2783
+ this.rememberWritten(header.id, writtenRow);
2784
+ return created;
1917
2785
  }
1918
2786
  async createFork(header, entries, source) {
1919
2787
  if (this.create !== SqlSessionStore.prototype.create) return void 0;
@@ -1931,22 +2799,64 @@ var SqlSessionStore = class SqlSessionStore {
1931
2799
  this.assertOpen();
1932
2800
  validateSessionHeader(header);
1933
2801
  validateSessionEntries(entries);
1934
- return this.transaction(async (tx) => {
1935
- const donor = await this.forkDonor(tx, header.id, source);
1936
- for (const entry of entries) {
1937
- const ref = source.receipts.get(entry.id);
1938
- if (ref && (source.sessionId !== ref.sessionId || donor.epoch !== ref.epoch || donor.lastSeq < ref.seq)) throw new SessionConflictError$1(ref.sessionId, ref.seq, donor.lastSeq);
2802
+ if (source.receipts.size === 0 && source.hashes.length === 0 && (!this.sharedHistorySeen || source.epoch === void 0)) return void 0;
2803
+ for (let attempt = 0;; attempt++) {
2804
+ const reads = this.sharedHistorySeen ? this.sharedForkReads(header.id, source.sessionId, false) : void 0;
2805
+ try {
2806
+ return await this.transactionCheckedAlongside((tx, checked) => this.writeEntriesFork(tx, checked, header, entries, source, reads), this.sessionWrite(header.id, ...reads === void 0 ? [] : [
2807
+ reads.exists,
2808
+ reads.lock,
2809
+ reads.tombstones,
2810
+ reads.segments
2811
+ ]));
2812
+ } catch (error) {
2813
+ if (!(error instanceof ForkSourcesMoved) || attempt >= 3) throw error;
1939
2814
  }
1940
- const summary = this.summaryWrite(header.id, {
1941
- header,
1942
- entries,
1943
- lastSeq: entries.length
1944
- });
2815
+ }
2816
+ }
2817
+ /**
2818
+ * A fork from the entries a caller holds. Where the database has shared history (#6560) and the source is still in
2819
+ * the generation the fork read it in, every entry the store read from the source and the caller kept unchanged, and
2820
+ * every receipt, is named by the child's segments, not stored again: the child stores only the entries it changed or
2821
+ * added, and their blobs. Otherwise the entries are stored as `create` stores them, receipts as the source stores
2822
+ * them. Undefined, with nothing written, for entries with neither receipts nor blobs that share nothing: `create`
2823
+ * then stores them, needing nothing of the source, so a source that changed or went away meanwhile does not fail it.
2824
+ */
2825
+ async writeEntriesFork(tx, checked, header, entries, source, reads) {
2826
+ const needsSource = source.receipts.size > 0 || source.hashes.length > 0;
2827
+ let shared;
2828
+ const unchecked = {
2829
+ ...source,
2830
+ epoch: void 0
2831
+ };
2832
+ const sharedRead = this.leadingForkDonor(tx, header.id, unchecked, reads);
2833
+ if (await this.sharedHistoryForks(tx)) try {
2834
+ shared = await (sharedRead ?? this.sharedForkDonor(tx, header.id, unchecked, this.sharedForkReads(header.id, source.sessionId, false)));
2835
+ } catch (error) {
2836
+ if (needsSource || !(error instanceof SessionNotFoundError$1)) throw error;
2837
+ return;
2838
+ }
2839
+ const sharing = shared !== void 0 && source.epoch !== void 0 && shared.epoch === source.epoch;
2840
+ if (!sharing && !needsSource) return void 0;
2841
+ if (shared !== void 0 && source.epoch !== void 0 && shared.epoch !== source.epoch) throw new SessionConflictError$1(source.sessionId, 0, shared.lastSeq);
2842
+ const donor = shared ?? await this.forkDonor(tx, header.id, source);
2843
+ for (const entry of entries) {
2844
+ const ref = source.receipts.get(entry.id);
2845
+ if (ref && (source.sessionId !== ref.sessionId || donor.epoch !== ref.epoch || donor.lastSeq < ref.seq)) throw new SessionConflictError$1(ref.sessionId, ref.seq, donor.lastSeq);
2846
+ }
2847
+ const summary = this.summaryWrite(header.id, {
2848
+ header,
2849
+ entries,
2850
+ lastSeq: entries.length
2851
+ });
2852
+ await checked;
2853
+ const tables = await this.viewTables(tx);
2854
+ const writes = new SentWrites(tx);
2855
+ if (!sharing) {
1945
2856
  const blobs = this.forkBlobCopy(source.sessionId, header.id, source.hashes);
1946
- const writes = new SentWrites(tx);
1947
2857
  const remainingBlobs = await writes.around(async () => {
1948
2858
  await writes.send([summary.statement]);
1949
- await writes.send(this.receiptForkWrites(header.id, entries, source, donor.lastSeq));
2859
+ await writes.send(this.receiptForkWrites(tables, header.id, entries, source, donor.lastSeq));
1950
2860
  await writes.send(this.entryWrites(header.id, [], 0, summary.texts, false));
1951
2861
  return this.finishForkCopy(tx, writes, header.id, blobs, source.hashes);
1952
2862
  });
@@ -1956,7 +2866,69 @@ var SqlSessionStore = class SqlSessionStore {
1956
2866
  epoch: summary.epoch,
1957
2867
  remainingBlobs
1958
2868
  };
1959
- }, this.sessionWrite(header.id));
2869
+ }
2870
+ const places = [];
2871
+ const stored = storedRows(source.sessionId, source.epoch);
2872
+ let sharedThrough = 0;
2873
+ for (const entry of entries) {
2874
+ const seq = source.receipts.get(entry.id)?.seq ?? stored?.seqOf(entry, sharedThrough);
2875
+ const shares = seq !== void 0 && seq > sharedThrough && seq <= donor.lastSeq;
2876
+ if (shares) sharedThrough = seq;
2877
+ places.push(shares ? seq : void 0);
2878
+ }
2879
+ const hashes = /* @__PURE__ */ new Set();
2880
+ let copiesReceipts = false;
2881
+ for (const [index, entry] of entries.entries()) {
2882
+ if (places[index] !== void 0) continue;
2883
+ copiesReceipts ||= source.receipts.has(entry.id);
2884
+ if (entry.type !== "custom" || entry.customType !== "atomic.tool-output") continue;
2885
+ const hash = entry.data?.hash;
2886
+ if (typeof hash === "string" && source.hashes.includes(hash)) hashes.add(hash);
2887
+ }
2888
+ const statements = this.sharedEntriesForkWrites(tables, header, entries, places, source, shared, summary.texts);
2889
+ if (!copiesReceipts && hashes.size === 0) {
2890
+ await this.writeEntries(tx, summary.statement, [...statements, this.forkVersionStep(header.id)]);
2891
+ return {
2892
+ lastSeq: entries.length,
2893
+ epoch: summary.epoch,
2894
+ remainingBlobs: []
2895
+ };
2896
+ }
2897
+ const remainingBlobs = await writes.around(async () => {
2898
+ await writes.send([summary.statement]);
2899
+ await writes.send(statements);
2900
+ return this.finishForkCopy(tx, writes, header.id, this.forkBlobCopy(source.sessionId, header.id, hashes), hashes);
2901
+ });
2902
+ await this.finishFork(tx, header.id);
2903
+ return {
2904
+ lastSeq: entries.length,
2905
+ epoch: summary.epoch,
2906
+ remainingBlobs
2907
+ };
2908
+ }
2909
+ /**
2910
+ * The statements of a fork from `entries` with shared history (#6560), in seq order, after its session row: the
2911
+ * segments that name the rows `places` puts in the source, each entry it does not as {@link entryForkWrites} stores it,
2912
+ * the search texts of those, and the lineage row. Throws, before the last of them, unless the segments are well formed.
2913
+ */
2914
+ *sharedEntriesForkWrites(tables, header, entries, places, source, donor, texts) {
2915
+ const lineage = this.lineageTables();
2916
+ const runs = new ForkSegmentRuns(lineage, header.id, {
2917
+ id: source.sessionId,
2918
+ segments: donor.segments,
2919
+ length: donor.lastSeq
2920
+ });
2921
+ yield* this.receiptForkWrites(tables, header.id, entries, source, donor.lastSeq, places, runs);
2922
+ yield* runs.drain();
2923
+ yield* this.entryWrites(header.id, [], 0, texts.filter((text) => places[text.index] === void 0), false);
2924
+ assertForkSegments(header.id, runs.segments, entries.length);
2925
+ yield forkLineageWrite(lineage, header.id, {
2926
+ parentId: source.sessionId,
2927
+ cutSeq: donor.lastSeq
2928
+ });
2929
+ if (runs.segments.length > 0) {
2930
+ for (const [index, place] of places.entries()) if (place === void 0) yield this.forkLinks().entry(header.id, index + 1);
2931
+ }
1960
2932
  }
1961
2933
  /**
1962
2934
  * The source session's head, its row locked for share, once the child is known to be new: both reads go out together,
@@ -1974,38 +2946,63 @@ var SqlSessionStore = class SqlSessionStore {
1974
2946
  }
1975
2947
  /**
1976
2948
  * The statements that store a fork's `entries`, in seq order: an entry with a receipt as the source stores it, its row
1977
- * and chunks copied in two statements whatever their size, and any other as `create` stores it. A receipt's row that
1978
- * names another entry fails the fork: the source changed under it.
2949
+ * and chunks copied in two statements whatever their size, and a run of others as `create` stores them, several rows
2950
+ * a statement. A receipt's row that names another entry fails the fork: the source changed under it. With `places`
2951
+ * and `runs`, an entry `places` puts in the source is named by `runs`' segments instead, and the segments before an
2952
+ * entry the child stores go first, for the snapshot index's triggers.
1979
2953
  */
1980
- *receiptForkWrites(child, entries, source, donorLastSeq) {
2954
+ *receiptForkWrites(tables, child, entries, source, donorLastSeq, places = [], runs) {
2955
+ let from = 0;
2956
+ let own = 0;
1981
2957
  for (const [index, entry] of entries.entries()) {
1982
- const ref = source.receipts.get(entry.id);
1983
- if (ref === void 0) {
1984
- yield* this.entryWrites(child, [entry], index, [], false);
2958
+ const seq = places[index];
2959
+ if (seq === void 0 && !source.receipts.has(entry.id)) {
2960
+ if (own === 0) {
2961
+ if (runs !== void 0) yield* runs.drain();
2962
+ from = index;
2963
+ }
2964
+ own++;
1985
2965
  continue;
1986
2966
  }
1987
- yield {
1988
- sql: `INSERT INTO ${this.tables.entries} (session_id, seq, entry_id, entry_json, chunks) SELECT ?, ?, entry_id, entry_json, chunks FROM ${this.tables.entries} WHERE session_id = ? AND seq = ? AND entry_id = ?`,
1989
- params: [
1990
- child,
1991
- index + 1,
1992
- ref.sessionId,
1993
- ref.seq,
1994
- entry.id
1995
- ],
1996
- changes: 1,
1997
- mismatch: () => new SessionConflictError$1(ref.sessionId, ref.seq, donorLastSeq)
1998
- };
1999
- yield {
2000
- sql: `INSERT INTO ${this.tables.entryChunks} (session_id, seq, idx, data) SELECT ?, ?, idx, data FROM ${this.tables.entryChunks} WHERE session_id = ? AND seq = ? ORDER BY idx`,
2001
- params: [
2002
- child,
2003
- index + 1,
2004
- ref.sessionId,
2005
- ref.seq
2006
- ]
2007
- };
2967
+ if (own > 0) yield* this.entryWrites(child, entries.slice(from, from + own), from, [], false);
2968
+ own = 0;
2969
+ if (seq !== void 0) {
2970
+ runs.add(seq, index + 1, entry.id);
2971
+ if (runs.full) yield* runs.drain();
2972
+ continue;
2973
+ }
2974
+ if (runs !== void 0) yield* runs.drain();
2975
+ yield* this.entryForkWrites(tables, child, index, entry, source, donorLastSeq);
2008
2976
  }
2977
+ if (own > 0) yield* this.entryWrites(child, entries.slice(from, from + own), from, [], false);
2978
+ }
2979
+ /** The statements of {@link receiptForkWrites} that store `entry`, at index `index` of the fork's entries. */
2980
+ *entryForkWrites(tables, child, index, entry, source, donorLastSeq) {
2981
+ const ref = source.receipts.get(entry.id);
2982
+ if (ref === void 0) {
2983
+ yield* this.entryWrites(child, [entry], index, [], false);
2984
+ return;
2985
+ }
2986
+ const view = this.entriesView(tables, ref.sessionId, ref.seq - 1, ref.seq);
2987
+ yield {
2988
+ sql: withForkViews([view], `INSERT INTO ${this.tables.entries} (session_id, seq, entry_id, entry_json, chunks) SELECT ?, ?, entry_id, entry_json, chunks FROM ${view.name} WHERE entry_id = ?`),
2989
+ params: [
2990
+ ...view.params,
2991
+ child,
2992
+ index + 1,
2993
+ entry.id
2994
+ ],
2995
+ changes: 1,
2996
+ mismatch: () => new SessionConflictError$1(ref.sessionId, ref.seq, donorLastSeq)
2997
+ };
2998
+ yield {
2999
+ sql: withForkViews([view], `INSERT INTO ${this.tables.entryChunks} (session_id, seq, idx, data) SELECT ?, ?, c.idx, c.data FROM ${view.name} v JOIN ${this.tables.entryChunks} c ON c.session_id = v.src_id AND c.seq = v.src_seq WHERE c.idx >= 0 AND c.idx < v.chunks ORDER BY c.idx`),
3000
+ params: [
3001
+ ...view.params,
3002
+ child,
3003
+ index + 1
3004
+ ]
3005
+ };
2009
3006
  }
2010
3007
  /**
2011
3008
  * The blob copy of a fork from session `source` of this store's tables (#6560), or undefined when a subclass stores
@@ -2069,6 +3066,73 @@ var SqlSessionStore = class SqlSessionStore {
2069
3066
  this.assertOpen();
2070
3067
  await this.chatRecords?.initialize();
2071
3068
  }
3069
+ /** Whether a deleted session with ID `sessionId` left rows forks still read. */
3070
+ async hasForkTombstone(tx, sessionId) {
3071
+ return await tx.get(`SELECT session_id FROM ${this.forkTables.forkTombstones} WHERE session_id = ?`, sessionId) !== void 0;
3072
+ }
3073
+ /** This store's side of detaching and pinning shared fork history: see fork-detach-host.ts. */
3074
+ forkHost() {
3075
+ return forkDetachHost({
3076
+ dialect: this.dialect,
3077
+ tables: this.tables,
3078
+ forkTables: this.forkTables,
3079
+ blobs: {
3080
+ legacyBlobData: this.legacyBlobData,
3081
+ chunkBytes: SESSION_BLOB_CHUNK_BYTES
3082
+ },
3083
+ materializedLinks: this.forkLinks().materialized,
3084
+ transaction: (body) => this.transaction(body, SESSION_TRANSACTION)
3085
+ });
3086
+ }
3087
+ /** The statements that link the entries a session with fork segments stores, as a copy links them (#6560). */
3088
+ forkLinks() {
3089
+ const index = snapshotIndexTables$1(this.prefix);
3090
+ this.forkLinkStatements ??= forkLinkWrites({
3091
+ entries: this.tables.entries,
3092
+ sessionLinks: index.sessionLinks,
3093
+ sources: index.sources,
3094
+ forkSegments: this.forkTables.forkSegments
3095
+ }, this.dialect);
3096
+ return this.forkLinkStatements;
3097
+ }
3098
+ /**
3099
+ * @internal Gives every fork that shares history with `sessionId` its own copy of what it reads, so the session's
3100
+ * rows no longer stay for them; see fork-detach.ts. Detaches a crash stopped are finished first. Nothing to do where
3101
+ * shared-history forks are off.
3102
+ */
3103
+ async detachForks(sessionId, options = {}) {
3104
+ this.assertOpen();
3105
+ validateSessionText("sessionId", sessionId);
3106
+ if (!await this.transaction((tx) => this.sharedHistoryForks(tx), SESSION_TRANSACTION)) return {
3107
+ detached: [],
3108
+ reparented: []
3109
+ };
3110
+ const report = await detachForkChildren(this.forkHost(), sessionId, options).catch((error) => {
3111
+ noteForkCopyRefusal(error, "detach");
3112
+ throw error;
3113
+ });
3114
+ await this.sweepReleasedForkRows([sessionId]);
3115
+ return report;
3116
+ }
3117
+ /** @internal Finishes every detach a crash stopped. Nothing to do where shared-history forks are off. */
3118
+ async resumeForkDetaches() {
3119
+ this.assertOpen();
3120
+ if (!await this.transaction((tx) => this.sharedHistoryForks(tx), SESSION_TRANSACTION)) return {
3121
+ detached: [],
3122
+ reparented: []
3123
+ };
3124
+ return resumeForkDetaches(this.forkHost());
3125
+ }
3126
+ /**
3127
+ * @internal Removes the rows of deleted sessions that no fork reads any more, a batch per transaction: `sessionIds`,
3128
+ * and a few any earlier sweep left. Resolves with the sessions whose rows went.
3129
+ */
3130
+ async sweepForkTombstones(sessionIds = [], batchEntries) {
3131
+ this.assertOpen();
3132
+ if (!await this.transaction((tx) => this.sharedHistoryForks(tx), SESSION_TRANSACTION)) return [];
3133
+ const { sweepForkTombstones } = await import("../core/storage/session/fork-sweep.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
3134
+ return sweepForkTombstones(this.forkHost(), sessionIds, batchEntries === void 0 ? {} : { batchEntries });
3135
+ }
2072
3136
  forkStagingTarget() {
2073
3137
  return {
2074
3138
  database: this.database,
@@ -2121,8 +3185,9 @@ var SqlSessionStore = class SqlSessionStore {
2121
3185
  const { sessionId, epoch, seq } = reference;
2122
3186
  const head = await this.historyHead(tx, sessionId, true);
2123
3187
  if (head.epoch !== epoch) throw new SessionConflictError$1(sessionId, seq, head.lastSeq);
2124
- const row = await tx.get(`SELECT e.chunks, c.data FROM ${this.tables.entries} e LEFT JOIN ${this.tables.entryChunks} c
2125
- ON c.session_id = e.session_id AND c.seq = e.seq AND c.idx = ? WHERE e.session_id = ? AND e.seq = ?`, index, sessionId, seq);
3188
+ const view = this.entriesView(await this.viewTables(tx, sessionId), sessionId, seq - 1, seq);
3189
+ const row = await tx.get(withForkViews([view], `SELECT e.chunks, c.data FROM ${view.name} e LEFT JOIN ${this.tables.entryChunks} c
3190
+ ON c.session_id = e.src_id AND c.seq = e.src_seq AND c.idx = ?`), ...view.params, index);
2126
3191
  if (!row) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing session entry ${seq}`));
2127
3192
  if (Number(row.chunks) === 0) return void 0;
2128
3193
  if (row.data == null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing chunk of session entry ${seq}`));
@@ -2136,174 +3201,403 @@ var SqlSessionStore = class SqlSessionStore {
2136
3201
  const { sessionId, epoch, seq } = reference;
2137
3202
  const head = await this.historyHead(tx, sessionId, true);
2138
3203
  if (head.epoch !== epoch) throw new SessionConflictError$1(sessionId, seq, head.lastSeq);
2139
- const row = await tx.get(`SELECT chunks FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, seq);
3204
+ const view = this.entriesView(await this.viewTables(tx, sessionId), sessionId, seq - 1, seq);
3205
+ const row = await tx.get(withForkViews([view], `SELECT chunks FROM ${view.name}`), ...view.params);
2140
3206
  if (!row) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing session entry ${seq}`));
2141
3207
  return Number(row.chunks);
2142
3208
  });
2143
3209
  }
2144
3210
  /**
2145
- * The headers of the blobs `hashes` of session `sessionId` in one read (#6560), each with its first chunk row when it
2146
- * is stored in chunks of at most `maxBytes` in all, as `readBlobPart` reads them at offset 0. A blob the session does
2147
- * not hold is left out; one in the legacy one-row layout comes without its value.
3211
+ * The headers of the blobs `hashes` of session `sessionId` in one read (#6560), each with its first chunk row when it
3212
+ * is stored in chunks of at most `maxBytes` in all, as `readBlobPart` reads them at offset 0. A blob the session does
3213
+ * not hold is left out; one in the legacy one-row layout comes without its value.
3214
+ */
3215
+ async readBlobFirstParts(sessionId, hashes, maxBytes) {
3216
+ this.assertOpen();
3217
+ const parts = /* @__PURE__ */ new Map();
3218
+ if (hashes.length === 0) return parts;
3219
+ const rows = await this.outsideTransaction((tables) => this.database.all(`SELECT b.hash, b.bytes, b.chunks, CASE WHEN b.chunks >= 0 AND b.bytes <= ? THEN c.data END AS data,
3220
+ CASE WHEN w.place = 0 THEN 1 ELSE 0 END AS own
3221
+ FROM ${this.blobPlaces(tables)} w JOIN ${this.tables.blobs} b
3222
+ ON b.session_id = w.owner AND b.hash IN (${hashes.map(() => "?").join(", ")})
3223
+ LEFT JOIN ${this.tables.blobChunks} c ON c.session_id = b.session_id AND c.hash = b.hash AND c.idx = 0
3224
+ ${tables.guard === void 0 ? "" : `WHERE ${tables.guard}`}
3225
+ ORDER BY own DESC, b.session_id`, maxBytes, ...this.blobPlaceParams(tables, sessionId), ...hashes), (found) => found.length > 0);
3226
+ for (const row of rows) if (!parts.has(String(row.hash))) parts.set(String(row.hash), {
3227
+ bytes: Number(row.bytes),
3228
+ chunks: Number(row.chunks),
3229
+ ...row.data == null ? {} : { data: row.data }
3230
+ });
3231
+ return parts;
3232
+ }
3233
+ /**
3234
+ * The bytes of a blob from `offset`, a multiple of {@link SESSION_BLOB_CHUNK_BYTES}, so a staged clone never holds
3235
+ * the whole of a large one (#5594): the stored chunk row there, or for a blob in the legacy one-row layout (`chunks`
3236
+ * -1), at most `legacyBytes` cut from its data column by the database, which loads that one value itself for each
3237
+ * cut; with `legacyBytes` 0, only its header. Nothing is converted or written.
3238
+ */
3239
+ async readBlobPart(sessionId, hash, offset, legacyBytes) {
3240
+ this.assertOpen();
3241
+ const cut = this.legacyBlobData && legacyBytes > 0;
3242
+ const legacy = cut ? "CASE WHEN b.chunks = -1 THEN substr(b.data, ?, ?) ELSE c.data END" : "c.data";
3243
+ const row = await this.outsideTransaction((tables) => this.database.get(`SELECT b.bytes, b.chunks, ${legacy} AS data
3244
+ FROM ${this.blobPlaces(tables)} w JOIN ${this.tables.blobs} b ON b.session_id = w.owner AND b.hash = ?
3245
+ LEFT JOIN ${this.tables.blobChunks} c ON c.session_id = b.session_id AND c.hash = b.hash AND c.idx = ?
3246
+ ${tables.guard === void 0 ? "" : `WHERE ${tables.guard}`}
3247
+ ORDER BY w.place, b.session_id LIMIT 1`, ...cut ? [offset + 1, legacyBytes] : [], ...this.blobPlaceParams(tables, sessionId), hash, Math.floor(offset / SESSION_BLOB_CHUNK_BYTES)), (found) => found !== void 0);
3248
+ if (row === void 0) return void 0;
3249
+ return {
3250
+ bytes: Number(row.bytes),
3251
+ chunks: Number(row.chunks),
3252
+ ...row.data == null ? {} : { data: row.data }
3253
+ };
3254
+ }
3255
+ /**
3256
+ * A fork from a stream of the source's rows. Where the database has shared history (#6560), the child stores no copy
3257
+ * of the rows the source stores unchanged: its segments name them, and it stores only the rows the stream changed or
3258
+ * added. A stream of the source's whole history, as it stands, reads no row at all.
3259
+ */
3260
+ async createStreamedFork(header, stream, source) {
3261
+ this.assertOpen();
3262
+ validateSessionHeader(header);
3263
+ for (let attempt = 0;; attempt++) {
3264
+ const reads = this.sharedHistorySeen ? this.sharedForkReads(header.id, source.sessionId, stream.prefix !== void 0) : void 0;
3265
+ try {
3266
+ return await this.transactionCheckedAlongside((tx, checked) => this.writeStreamedFork(tx, checked, header, stream, source, reads), this.sessionWrite(header.id, ...reads === void 0 ? [] : [
3267
+ reads.exists,
3268
+ reads.lock,
3269
+ reads.tombstones,
3270
+ reads.segments
3271
+ ]));
3272
+ } catch (error) {
3273
+ if (!(error instanceof ForkSourcesMoved) || attempt >= 3) throw error;
3274
+ }
3275
+ }
3276
+ }
3277
+ async writeStreamedFork(tx, checked, header, stream, source, reads) {
3278
+ const sharedRead = this.leadingForkDonor(tx, header.id, source, reads);
3279
+ const shared = await this.sharedHistoryForks(tx) ? await (sharedRead ?? this.sharedForkDonor(tx, header.id, source, this.sharedForkReads(header.id, source.sessionId, stream.prefix !== void 0))) : void 0;
3280
+ const head = shared ?? await this.forkDonor(tx, header.id, source);
3281
+ await checked;
3282
+ const { encodedForkRow } = await import("../core/storage/session/fork-row-bytes.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
3283
+ const { foldForkRow } = await import("../core/storage/session/fork-row-index.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
3284
+ const prefix = stream.prefix;
3285
+ if (shared !== void 0 && prefix !== void 0 && prefix.sessionId === source.sessionId && prefix.through === shared.lastSeq && (prefix.epoch === void 0 || prefix.epoch === shared.epoch)) {
3286
+ const whole = await this.writeSharedPrefixFork(tx, header, source.sessionId, shared);
3287
+ if (whole !== void 0) return whole;
3288
+ }
3289
+ const reader = new SqlSessionStore({
3290
+ descriptor: this.database.descriptor,
3291
+ dialect: this.dialect,
3292
+ readOnly: true,
3293
+ exec: tx.exec.bind(tx),
3294
+ get: tx.get.bind(tx),
3295
+ run: tx.run.bind(tx),
3296
+ all: tx.all.bind(tx),
3297
+ transaction: async (cb) => cb(tx),
3298
+ close: async () => {}
3299
+ }, this.tables, this.prefix, this.cwdMatcher, this.blobTable, this.legacyBlobData, void 0, this.entryByteLength);
3300
+ reader.sharedHistorySeen = await this.sharedHistoryForks(tx);
3301
+ let donorIndex;
3302
+ reader.readBranchSpan = async (id, cut) => {
3303
+ donorIndex ??= reader.prepareResume(source.sessionId).then((prepared) => prepared.index);
3304
+ return transcriptBranchSpan(id, await donorIndex, cut);
3305
+ };
3306
+ reader.readEntryChunk = this.forkChunkReader(tx, await this.viewTables(tx), reader, source.sessionId, head.epoch);
3307
+ const copies = new ForkRowRuns(this.tables, header.id, source.sessionId);
3308
+ const lineage = this.lineageTables();
3309
+ const runs = shared === void 0 ? void 0 : new ForkSegmentRuns(lineage, header.id, {
3310
+ id: source.sessionId,
3311
+ segments: shared.segments,
3312
+ length: shared.lastSeq
3313
+ });
3314
+ const viewTables = await this.viewTables(tx);
3315
+ const lookup = async (id) => (runs ?? copies).heldSeq(id) ?? this.seqOfEntry(tx, viewTables, header.id, id);
3316
+ let summary = applySessionSummaryEntries(void 0, []).state;
3317
+ let index = foldSessionResume(void 0, []);
3318
+ let seq = 0;
3319
+ const hashes = /* @__PURE__ */ new Set();
3320
+ const inlineSnapshot = async (ref) => {
3321
+ const text = (key) => this.dialect.jsonText("entry_json", key);
3322
+ const ty = (key) => this.dialect.jsonType("entry_json", key);
3323
+ const view = this.entriesView(await this.viewTables(tx), ref.sessionId, ref.seq - 1, ref.seq);
3324
+ const s = await tx.get(withForkViews([view], `SELECT entry_id AS id,${text("parentId")} AS parent,${text("timestamp")} AS stamp,${text("root")} AS root,${text("snapshotId")} AS snapshot,${text("captureMs")} AS capture,${ty("snapshot")} AS record,${ty("restore")} AS restore,${ty("unrestored")} AS unrestored,${text("degradedFrom")} AS degraded FROM ${view.name} WHERE chunks=0 AND ${text("type")}='worktree_snapshot'`), ...view.params);
3325
+ if (!s) return void 0;
3326
+ return {
3327
+ type: "worktree_snapshot",
3328
+ id: s.id,
3329
+ parentId: s.parent,
3330
+ timestamp: s.stamp,
3331
+ root: s.root,
3332
+ snapshotId: s.snapshot,
3333
+ ...s.capture !== null ? { captureMs: Number(s.capture) } : {},
3334
+ ...s.record === "object" ? { snapshot: {} } : {},
3335
+ ...s.restore === "object" ? { restore: {} } : {},
3336
+ ...s.unrestored === "object" ? { unrestored: {} } : {},
3337
+ ...s.degraded ? { degradedFrom: s.degraded } : {}
3338
+ };
3339
+ };
3340
+ const writes = new SentWrites(tx);
3341
+ const blobs = {};
3342
+ let copiedRows = false;
3343
+ const ownSeqs = [];
3344
+ const remainingBlobs = await writes.around(async () => {
3345
+ for await (const row of stream.read(reader, async (id) => await lookup(id) !== void 0, inlineSnapshot)) {
3346
+ index = await foldForkRow(index, row, lookup);
3347
+ const entry = row.entry;
3348
+ const listed = applySessionSummaryEntries(summary, [entry]);
3349
+ summary = listed.state;
3350
+ const unchanged = row.stored?.sessionId === source.sessionId && row.edits === void 0;
3351
+ if (entry.type === "custom" && entry.customType === "atomic.tool-output" && !(unchanged && runs)) {
3352
+ const hash = entry.data?.hash;
3353
+ if (typeof hash === "string") hashes.add(hash);
3354
+ }
3355
+ if (unchanged && runs !== void 0) {
3356
+ runs.add(row.stored.seq, seq + 1, entry.id);
3357
+ if (runs.full) await writes.send(runs.drain());
3358
+ seq++;
3359
+ continue;
3360
+ }
3361
+ if (row.stored?.sessionId === source.sessionId && row.edits === void 0) {
3362
+ copiedRows = true;
3363
+ copies.add(row.stored.seq, seq + 1, entry.id);
3364
+ await writes.send(this.entryWrites(header.id, [], seq, listed.texts, false));
3365
+ if (copies.full) await writes.send(copies.drain());
3366
+ seq++;
3367
+ continue;
3368
+ }
3369
+ await writes.send(runs?.drain() ?? copies.drain());
3370
+ if (runs !== void 0) ownSeqs.push(seq + 1);
3371
+ if (!row.reference) await writes.send(this.entryWrites(header.id, [entry], seq, listed.texts, false));
3372
+ else if (row.inlineSnapshot) await this.writeInlineForkSnapshot(tx, reader, row.reference, header.id, seq, listed.texts, row.edits);
3373
+ else {
3374
+ copiedRows = true;
3375
+ const encoded = await encodedForkRow(reader, row);
3376
+ const chunks = Math.ceil(encoded.size / SESSION_ENTRY_CHUNK_BYTES);
3377
+ await tx.run(`INSERT INTO ${this.tables.entries} (session_id,seq,entry_id,entry_json,chunks) VALUES (?,?,?,?,?)`, header.id, seq + 1, entry.id, JSON.stringify({
3378
+ type: entry.type,
3379
+ id: entry.id,
3380
+ parentId: entry.parentId ?? null
3381
+ }), chunks);
3382
+ let n = 0;
3383
+ let used = 0;
3384
+ let buffer = new Uint8Array(SESSION_ENTRY_CHUNK_BYTES);
3385
+ const write = async () => {
3386
+ await tx.run(`INSERT INTO ${this.tables.entryChunks} (session_id,seq,idx,data) VALUES (?,?,?,?)`, header.id, seq + 1, n++, buffer.subarray(0, used));
3387
+ used = 0;
3388
+ };
3389
+ for await (const part of encoded.chunks()) for (let start = 0; start < part.length;) {
3390
+ const count = Math.min(part.length - start, buffer.length - used);
3391
+ buffer.set(part.subarray(start, start + count), used);
3392
+ start += count;
3393
+ used += count;
3394
+ if (used === buffer.length) await write();
3395
+ }
3396
+ if (used) await write();
3397
+ if (n !== chunks) throw new StorageError("Incomplete historical entry in fork");
3398
+ await writes.send(this.entryWrites(header.id, [], seq, listed.texts, false));
3399
+ }
3400
+ seq++;
3401
+ }
3402
+ const last = [...runs?.drain() ?? copies.drain()];
3403
+ if (runs !== void 0) {
3404
+ assertForkSegments(header.id, runs.segments, seq);
3405
+ last.push(forkLineageWrite(lineage, header.id, {
3406
+ parentId: source.sessionId,
3407
+ cutSeq: head.lastSeq
3408
+ }));
3409
+ if (runs.segments.length > 0) for (const own of ownSeqs) last.push(this.forkLinks().entry(header.id, own));
3410
+ }
3411
+ const statement = this.summaryWrite(header.id, {
3412
+ header,
3413
+ entries: [],
3414
+ lastSeq: seq
3415
+ }, summary, index);
3416
+ last.push(statement.statement);
3417
+ if (!copiedRows && hashes.size === 0) {
3418
+ last.push(this.forkVersionStep(header.id));
3419
+ if (transactionFinisher(tx)?.(last) !== true) await writes.send(last);
3420
+ return {
3421
+ remaining: [],
3422
+ epoch: statement.epoch,
3423
+ finished: true
3424
+ };
3425
+ }
3426
+ await writes.send(last);
3427
+ blobs.copy = this.forkBlobCopy(source.sessionId, header.id, hashes);
3428
+ return {
3429
+ remaining: await this.finishForkCopy(tx, writes, header.id, blobs.copy, hashes),
3430
+ epoch: statement.epoch,
3431
+ finished: false
3432
+ };
3433
+ });
3434
+ if (!remainingBlobs.finished) await this.finishFork(tx, header.id);
3435
+ return {
3436
+ lastSeq: seq,
3437
+ epoch: remainingBlobs.epoch,
3438
+ remainingBlobs: remainingBlobs.remaining
3439
+ };
3440
+ }
3441
+ /**
3442
+ * The donor `reads` read, when the fork made them, asked for at once: its reads then go out beside the schema check,
3443
+ * in one wait for the connection, as a `create`'s first read does. The fork uses it only once the schema it checks in
3444
+ * this transaction has shared history: a store that saw shared history may meet a database whose schema says
3445
+ * otherwise, and a fork there never names its source's rows. Unused, its failure is nobody's.
3446
+ */
3447
+ leadingForkDonor(tx, child, source, reads) {
3448
+ if (reads === void 0) return void 0;
3449
+ const read = this.sharedForkDonor(tx, child, source, reads);
3450
+ read.catch(() => {});
3451
+ return read;
3452
+ }
3453
+ /** Notes the sessions session `id`'s segments name, which a fork of it locks. */
3454
+ noteForkSources(id, sources) {
3455
+ this.forkSources.delete(id);
3456
+ this.forkSources.set(id, sources);
3457
+ while (this.forkSources.size > 16) this.forkSources.delete(this.forkSources.keys().next().value);
3458
+ }
3459
+ /** The fork tables of this store's database, which exist once it has shared history (#6560). */
3460
+ lineageTables() {
3461
+ return {
3462
+ sessions: this.tables.sessions,
3463
+ forkSegments: this.forkTables.forkSegments,
3464
+ forkLineage: this.forkTables.forkLineage
3465
+ };
3466
+ }
3467
+ /**
3468
+ * The reads that begin a fork of session `donor` into `child` with shared history (#6560), in order: whether the child
3469
+ * exists; the rows of the donor and of the sessions its segments name, as the statement starts or as this store last
3470
+ * saw them, each locked `key-share` in id order, unless the child exists, with the donor's watermark and generation,
3471
+ * and with `withState` its summary state; then the donor's segments, read once those locks are held.
3472
+ */
3473
+ sharedForkReads(child, donor, withState) {
3474
+ const ids = [.../* @__PURE__ */ new Set([donor, ...this.forkSources.get(donor) ?? []])].sort();
3475
+ const epoch = `COALESCE(${this.dialect.jsonText("summary_state", "epoch")}, ${this.dialect.jsonText("summary_state", "resume", "epoch")}, revision)`;
3476
+ return {
3477
+ ids,
3478
+ exists: {
3479
+ sql: `SELECT id FROM ${this.tables.sessions} WHERE id = ?`,
3480
+ params: [child]
3481
+ },
3482
+ lock: {
3483
+ sql: `SELECT id, last_seq, CASE WHEN id = ? THEN ${epoch} END AS epoch${withState ? ", CASE WHEN id = ? THEN summary_state END AS summary_state" : ""}
3484
+ FROM ${this.tables.sessions} WHERE (id IN (${ids.map(() => "?").join(", ")})
3485
+ OR id IN (SELECT source_id FROM ${this.forkTables.forkSegments} WHERE session_id = ?))
3486
+ AND NOT EXISTS (SELECT 1 FROM ${this.tables.sessions} c WHERE c.id = ?) ORDER BY id${this.dialect.lockClause("key-share")}`,
3487
+ params: [
3488
+ donor,
3489
+ ...withState ? [donor] : [],
3490
+ ...ids,
3491
+ donor,
3492
+ child
3493
+ ]
3494
+ },
3495
+ tombstones: {
3496
+ sql: `SELECT session_id FROM ${this.forkTables.forkTombstones} WHERE session_id IN (${ids.map(() => "?").join(", ")})
3497
+ OR session_id IN (SELECT source_id FROM ${this.forkTables.forkSegments} WHERE session_id = ?)
3498
+ ORDER BY session_id${this.dialect.lockClause("key-share")}`,
3499
+ params: [...ids, donor]
3500
+ },
3501
+ segments: {
3502
+ sql: `SELECT source_id, from_seq, to_seq, base_seq FROM ${this.forkTables.forkSegments} WHERE session_id = ? ORDER BY idx`,
3503
+ params: [donor]
3504
+ }
3505
+ };
3506
+ }
3507
+ /**
3508
+ * The donor of a fork with shared history (#6560), from `reads`: its watermark, as the locking read found it, is the
3509
+ * fork's cut-off. Throws `ForkSourcesMoved`, for the fork to run again, when the donor's segments name a session the
3510
+ * reads did not lock: the donor's segments changed since this store last forked it.
2148
3511
  */
2149
- async readBlobFirstParts(sessionId, hashes, maxBytes) {
2150
- this.assertOpen();
2151
- const parts = /* @__PURE__ */ new Map();
2152
- if (hashes.length === 0) return parts;
2153
- const rows = await this.database.all(`SELECT b.hash, b.bytes, b.chunks, CASE WHEN b.chunks >= 0 AND b.bytes <= ? THEN c.data END AS data
2154
- FROM ${this.tables.blobs} b LEFT JOIN ${this.tables.blobChunks} c
2155
- ON c.session_id = b.session_id AND c.hash = b.hash AND c.idx = 0
2156
- WHERE b.session_id = ? AND b.hash IN (${hashes.map(() => "?").join(", ")})`, maxBytes, sessionId, ...hashes);
2157
- for (const row of rows) parts.set(String(row.hash), {
2158
- bytes: Number(row.bytes),
2159
- chunks: Number(row.chunks),
2160
- ...row.data == null ? {} : { data: row.data }
2161
- });
2162
- return parts;
3512
+ async sharedForkDonor(tx, child, source, reads) {
3513
+ const settle = (read) => read.then((value) => ({ value }), (error) => ({ error }));
3514
+ const existing = settle(tx.get(reads.exists.sql, ...reads.exists.params));
3515
+ const locked = settle(tx.all(reads.lock.sql, ...reads.lock.params));
3516
+ const tombstones = settle(tx.all(reads.tombstones.sql, ...reads.tombstones.params));
3517
+ const segmentRows = settle(tx.all(reads.segments.sql, ...reads.segments.params));
3518
+ for (const read of [
3519
+ existing,
3520
+ locked,
3521
+ tombstones,
3522
+ segmentRows
3523
+ ]) {
3524
+ const answer = await read;
3525
+ if ("error" in answer) throw answer.error;
3526
+ }
3527
+ const answer = (read) => read.value;
3528
+ if (answer(await existing)) throw new SessionExistsError$1(child);
3529
+ const row = answer(await locked).find((candidate) => String(candidate.id) === source.sessionId);
3530
+ if (row === void 0) throw new SessionNotFoundError$1(source.sessionId);
3531
+ const segments = answer(await segmentRows).map((segment) => ({
3532
+ sourceId: String(segment.source_id),
3533
+ fromSeq: Number(segment.from_seq),
3534
+ toSeq: Number(segment.to_seq),
3535
+ baseSeq: Number(segment.base_seq)
3536
+ }));
3537
+ const sources = [...new Set(segments.map((segment) => segment.sourceId))].sort();
3538
+ this.noteForkSources(source.sessionId, sources);
3539
+ const lockedIds = /* @__PURE__ */ new Set([
3540
+ ...reads.ids,
3541
+ ...answer(await locked).map((candidate) => String(candidate.id)),
3542
+ ...answer(await tombstones).map((candidate) => String(candidate.session_id))
3543
+ ]);
3544
+ if (sources.some((id) => !lockedIds.has(id))) throw new ForkSourcesMoved();
3545
+ const lastSeq = Number(row.last_seq);
3546
+ const epoch = String(row.epoch);
3547
+ if (source.epoch !== void 0 && epoch !== source.epoch) throw new SessionConflictError$1(source.sessionId, 0, lastSeq);
3548
+ return {
3549
+ lastSeq,
3550
+ epoch,
3551
+ segments,
3552
+ ...typeof row.summary_state === "string" ? { state: JSON.parse(row.summary_state) } : {}
3553
+ };
2163
3554
  }
2164
3555
  /**
2165
- * The bytes of a blob from `offset`, a multiple of {@link SESSION_BLOB_CHUNK_BYTES}, so a staged clone never holds
2166
- * the whole of a large one (#5594): the stored chunk row there, or for a blob in the legacy one-row layout (`chunks`
2167
- * -1), at most `legacyBytes` cut from its data column by the database, which loads that one value itself for each
2168
- * cut; with `legacyBytes` 0, only its header. Nothing is converted or written.
3556
+ * A fork with shared history of the donor's whole view as it stands (#6560): its segments, its lineage and its
3557
+ * session row, whose summary is the donor's in a generation of its own, and no row of any entry. Undefined, for
3558
+ * the fork to read the donor's rows, when the donor's resume index does not cover its watermark.
2169
3559
  */
2170
- async readBlobPart(sessionId, hash, offset, legacyBytes) {
2171
- this.assertOpen();
2172
- const cut = this.legacyBlobData && legacyBytes > 0;
2173
- const legacy = cut ? "CASE WHEN b.chunks = -1 THEN substr(b.data, ?, ?) ELSE c.data END" : "c.data";
2174
- const row = await this.database.get(`SELECT b.bytes, b.chunks, ${legacy} AS data FROM ${this.tables.blobs} b LEFT JOIN ${this.tables.blobChunks} c
2175
- ON c.session_id = b.session_id AND c.hash = b.hash AND c.idx = ? WHERE b.session_id = ? AND b.hash = ?`, ...cut ? [offset + 1, legacyBytes] : [], Math.floor(offset / SESSION_BLOB_CHUNK_BYTES), sessionId, hash);
2176
- if (row === void 0) return void 0;
3560
+ async writeSharedPrefixFork(tx, header, donorId, donor) {
3561
+ const index = donor.state === void 0 ? void 0 : windowIndex(donor.state, donor.lastSeq);
3562
+ if (donor.state === void 0 || index === void 0) return void 0;
3563
+ const epoch = newRevision();
3564
+ const segments = prefixForkSegments(donorId, donor.segments, donor.lastSeq, donor.lastSeq);
3565
+ const { resume: _resume, windowResume: _window, epoch: _epoch, ...listed } = donor.state;
3566
+ const summary = this.summaryWrite(header.id, {
3567
+ header,
3568
+ entries: [],
3569
+ lastSeq: donor.lastSeq
3570
+ }, {
3571
+ ...listed,
3572
+ epoch
3573
+ }, {
3574
+ ...index,
3575
+ epoch
3576
+ });
3577
+ const lineage = this.lineageTables();
3578
+ assertForkSegments(header.id, segments, donor.lastSeq);
3579
+ const statements = [
3580
+ ...forkSegmentInserts(lineage, header.id, 0, segments),
3581
+ forkLineageWrite(lineage, header.id, {
3582
+ parentId: donorId,
3583
+ cutSeq: donor.lastSeq
3584
+ }),
3585
+ summary.statement
3586
+ ];
3587
+ if (transactionFinisher(tx)?.(statements) !== true) for (const { sql, params } of statements) await tx.run(sql, ...params);
2177
3588
  return {
2178
- bytes: Number(row.bytes),
2179
- chunks: Number(row.chunks),
2180
- ...row.data == null ? {} : { data: row.data }
3589
+ lastSeq: donor.lastSeq,
3590
+ epoch: summary.epoch,
3591
+ remainingBlobs: []
2181
3592
  };
2182
3593
  }
2183
- async createStreamedFork(header, stream, source) {
2184
- this.assertOpen();
2185
- validateSessionHeader(header);
2186
- const { encodedForkRow } = await import("../core/storage/session/fork-row-bytes.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
2187
- const { foldForkRow } = await import("../core/storage/session/fork-row-index.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
2188
- return this.transaction(async (tx) => {
2189
- const head = await this.forkDonor(tx, header.id, source);
2190
- const reader = new SqlSessionStore({
2191
- descriptor: this.database.descriptor,
2192
- dialect: this.dialect,
2193
- readOnly: true,
2194
- exec: tx.exec.bind(tx),
2195
- get: tx.get.bind(tx),
2196
- run: tx.run.bind(tx),
2197
- all: tx.all.bind(tx),
2198
- transaction: async (cb) => cb(tx),
2199
- close: async () => {}
2200
- }, this.tables, this.prefix, this.cwdMatcher, this.blobTable, this.legacyBlobData, void 0, this.entryByteLength);
2201
- const { index: donorIndex } = await reader.prepareResume(source.sessionId);
2202
- reader.readBranchSpan = async (id, cut) => transcriptBranchSpan(id, donorIndex, cut);
2203
- reader.readEntryChunk = this.forkChunkReader(tx, reader, source.sessionId, head.epoch);
2204
- const copies = new ForkRowRuns(this.tables, header.id, source.sessionId);
2205
- const lookup = async (id) => copies.heldSeq(id) ?? this.seqOfEntry(tx, header.id, id);
2206
- let summary = applySessionSummaryEntries(void 0, []).state;
2207
- let index = foldSessionResume(void 0, []);
2208
- let seq = 0;
2209
- const hashes = /* @__PURE__ */ new Set();
2210
- const inlineSnapshot = async (ref) => {
2211
- const text = (key) => this.dialect.jsonText("entry_json", key);
2212
- const ty = (key) => this.dialect.jsonType("entry_json", key);
2213
- const s = await tx.get(`SELECT entry_id AS id,${text("parentId")} AS parent,${text("timestamp")} AS stamp,${text("root")} AS root,${text("snapshotId")} AS snapshot,${text("captureMs")} AS capture,${ty("snapshot")} AS record,${ty("restore")} AS restore,${ty("unrestored")} AS unrestored,${text("degradedFrom")} AS degraded FROM ${this.tables.entries} WHERE session_id=? AND seq=? AND chunks=0 AND ${text("type")}='worktree_snapshot'`, ref.sessionId, ref.seq);
2214
- if (!s) return void 0;
2215
- return {
2216
- type: "worktree_snapshot",
2217
- id: s.id,
2218
- parentId: s.parent,
2219
- timestamp: s.stamp,
2220
- root: s.root,
2221
- snapshotId: s.snapshot,
2222
- ...s.capture !== null ? { captureMs: Number(s.capture) } : {},
2223
- ...s.record === "object" ? { snapshot: {} } : {},
2224
- ...s.restore === "object" ? { restore: {} } : {},
2225
- ...s.unrestored === "object" ? { unrestored: {} } : {},
2226
- ...s.degraded ? { degradedFrom: s.degraded } : {}
2227
- };
2228
- };
2229
- const writes = new SentWrites(tx);
2230
- const blobs = {};
2231
- const remainingBlobs = await writes.around(async () => {
2232
- for await (const row of stream.read(reader, async (id) => await lookup(id) !== void 0, inlineSnapshot)) {
2233
- index = await foldForkRow(index, row, lookup);
2234
- const entry = row.entry;
2235
- const listed = applySessionSummaryEntries(summary, [entry]);
2236
- summary = listed.state;
2237
- if (entry.type === "custom" && entry.customType === "atomic.tool-output") {
2238
- const hash = entry.data?.hash;
2239
- if (typeof hash === "string") hashes.add(hash);
2240
- }
2241
- if (row.stored?.sessionId === source.sessionId && row.edits === void 0) {
2242
- copies.add(row.stored.seq, seq + 1, entry.id);
2243
- await writes.send(this.entryWrites(header.id, [], seq, listed.texts, false));
2244
- if (copies.full) await writes.send(copies.drain());
2245
- seq++;
2246
- continue;
2247
- }
2248
- await writes.send(copies.drain());
2249
- if (!row.reference) await writes.send(this.entryWrites(header.id, [entry], seq, listed.texts, false));
2250
- else if (row.inlineSnapshot) await this.writeInlineForkSnapshot(tx, reader, row.reference, header.id, seq, listed.texts, row.edits);
2251
- else {
2252
- const encoded = await encodedForkRow(reader, row);
2253
- const chunks = Math.ceil(encoded.size / SESSION_ENTRY_CHUNK_BYTES);
2254
- await tx.run(`INSERT INTO ${this.tables.entries} (session_id,seq,entry_id,entry_json,chunks) VALUES (?,?,?,?,?)`, header.id, seq + 1, entry.id, JSON.stringify({
2255
- type: entry.type,
2256
- id: entry.id,
2257
- parentId: entry.parentId ?? null
2258
- }), chunks);
2259
- let n = 0;
2260
- let used = 0;
2261
- let buffer = new Uint8Array(SESSION_ENTRY_CHUNK_BYTES);
2262
- const write = async () => {
2263
- await tx.run(`INSERT INTO ${this.tables.entryChunks} (session_id,seq,idx,data) VALUES (?,?,?,?)`, header.id, seq + 1, n++, buffer.subarray(0, used));
2264
- used = 0;
2265
- };
2266
- for await (const part of encoded.chunks()) for (let start = 0; start < part.length;) {
2267
- const count = Math.min(part.length - start, buffer.length - used);
2268
- buffer.set(part.subarray(start, start + count), used);
2269
- start += count;
2270
- used += count;
2271
- if (used === buffer.length) await write();
2272
- }
2273
- if (used) await write();
2274
- if (n !== chunks) throw new StorageError("Incomplete historical entry in fork");
2275
- await writes.send(this.entryWrites(header.id, [], seq, listed.texts, false));
2276
- }
2277
- seq++;
2278
- }
2279
- await writes.send(copies.drain());
2280
- blobs.copy = this.forkBlobCopy(source.sessionId, header.id, hashes);
2281
- const statement = this.summaryWrite(header.id, {
2282
- header,
2283
- entries: [],
2284
- lastSeq: seq
2285
- }, summary, index);
2286
- await writes.send([statement.statement]);
2287
- return {
2288
- remaining: await this.finishForkCopy(tx, writes, header.id, blobs.copy, hashes),
2289
- epoch: statement.epoch
2290
- };
2291
- });
2292
- await this.finishFork(tx, header.id);
2293
- return {
2294
- lastSeq: seq,
2295
- epoch: remainingBlobs.epoch,
2296
- remainingBlobs: remainingBlobs.remaining
2297
- };
2298
- }, this.sessionWrite(header.id));
2299
- }
2300
3594
  /**
2301
3595
  * `readEntryChunk` for a fork's reader bound to transaction `tx`, reading session `source` in generation `epoch`: a
2302
3596
  * read of an entry fetches a whole stored chunk row, or a part as large of an entry stored whole, and answers the next
2303
3597
  * reads of it from that, so an entry costs a round trip a chunk, not one every 64 KiB (#6560). The fork holds the
2304
3598
  * source's row, so its generation cannot change meanwhile. Other reads go to `reader` as before.
2305
3599
  */
2306
- forkChunkReader(tx, reader, source, epoch) {
3600
+ forkChunkReader(tx, tables, reader, source, epoch) {
2307
3601
  const json = this.dialect.name === "sqlite" ? "CAST(e.entry_json AS BLOB)" : "convert_to(e.entry_json, 'UTF8')";
2308
3602
  let held;
2309
3603
  return async (reference, offset, bytes = SESSION_HISTORY_CHUNK_BYTES) => {
@@ -2311,10 +3605,11 @@ var SqlSessionStore = class SqlSessionStore {
2311
3605
  const part = Math.floor(offset / SESSION_ENTRY_CHUNK_BYTES);
2312
3606
  const start = part * SESSION_ENTRY_CHUNK_BYTES;
2313
3607
  if (held?.seq !== reference.seq || held.start !== start) {
2314
- const row = await tx.get(`SELECT CASE WHEN e.chunks > 0
2315
- THEN (SELECT c.data FROM ${this.tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx = ?)
3608
+ const view = this.entriesView(tables, source, reference.seq - 1, reference.seq);
3609
+ const row = await tx.get(withForkViews([view], `SELECT CASE WHEN e.chunks > 0
3610
+ THEN (SELECT c.data FROM ${this.tables.entryChunks} c WHERE c.session_id = e.src_id AND c.seq = e.src_seq AND c.idx = ?)
2316
3611
  ELSE substr(${json}, CAST(? AS INTEGER), CAST(? AS INTEGER)) END AS data
2317
- FROM ${this.tables.entries} e WHERE e.session_id = ? AND e.seq = ?`, part, start + 1, SESSION_ENTRY_CHUNK_BYTES, source, reference.seq);
3612
+ FROM ${view.name} e`), ...view.params, part, start + 1, SESSION_ENTRY_CHUNK_BYTES);
2318
3613
  if (row?.data == null || row.data.byteLength <= offset - start) return SqlSessionStore.prototype.readEntryChunk.call(reader, reference, offset, bytes);
2319
3614
  held = {
2320
3615
  seq: reference.seq,
@@ -2339,8 +3634,13 @@ var SqlSessionStore = class SqlSessionStore {
2339
3634
  async append(sessionId, entries, options) {
2340
3635
  this.assertOpen();
2341
3636
  validateSessionText("sessionId", sessionId);
2342
- return this.transactionCheckedAlongside(async (tx, checked) => {
2343
- const { row: previous, state: summaryState } = await this.forWrite(tx, sessionId, options, true);
3637
+ const fast = await this.appendThroughFunction(sessionId, entries, options);
3638
+ if (fast !== void 0) return fast;
3639
+ let written = [];
3640
+ let writtenRow;
3641
+ const appended = await this.transactionCheckedAlongside(async (tx, checked) => {
3642
+ writtenRow = void 0;
3643
+ const { row: previous, state: summaryState } = await this.forWrite(tx, sessionId, options, true, true);
2344
3644
  validateSessionEntries(entries);
2345
3645
  await this.blobTable.assertStored(tx, entries.flatMap((entry) => entry.type === "worktree_snapshot" && entry.snapshot !== void 0 ? [entry.snapshot] : []));
2346
3646
  const lastSeq = previous.last_seq + entries.length;
@@ -2349,20 +3649,248 @@ var SqlSessionStore = class SqlSessionStore {
2349
3649
  entries,
2350
3650
  lastSeq
2351
3651
  }, summaryState, await this.appendedResume(tx, sessionId, windowIndex(summaryState, previous.last_seq), previous.last_seq, entries));
2352
- const written = this.entryWrites(sessionId, entries, previous.last_seq, summary.texts);
3652
+ written = [];
3653
+ const statements = this.entryWrites(sessionId, entries, previous.last_seq, summary.texts, true, written);
2353
3654
  await checked;
2354
- await this.writeEntries(tx, summary.statement, written);
2355
- return { lastSeq };
2356
- }, this.sessionWrite(sessionId, this.headRead(sessionId, options, true)));
3655
+ const forked = previous.forked !== void 0 ? Number(previous.forked) === 1 : await this.sharedHistoryForks(tx) && await this.hasForkSegments(tx, sessionId);
3656
+ writtenRow = forked ? void 0 : summary.row;
3657
+ const links = forked ? entries.map((_, index) => this.forkLinks().entry(sessionId, previous.last_seq + index + 1)) : [];
3658
+ await this.writeEntries(tx, summary.statement, links.length === 0 ? statements : thenAll(statements, links));
3659
+ return {
3660
+ lastSeq,
3661
+ epoch: summary.epoch
3662
+ };
3663
+ }, this.sessionWrite(sessionId, this.headRead(sessionId, options, true, true)));
3664
+ this.noteWritten(sessionId, appended.epoch, written);
3665
+ this.rememberWritten(sessionId, writtenRow);
3666
+ return { lastSeq: appended.lastSeq };
3667
+ }
3668
+ /**
3669
+ * Remembers `row`, the session's row a committed write of this store left, for the next append to plan from, where
3670
+ * appends go through the append function; forgets the session's row when `row` is undefined. At most
3671
+ * {@link WRITTEN_ROWS} sessions are remembered, the latest written.
3672
+ */
3673
+ rememberWritten(sessionId, row) {
3674
+ this.writtenRows.delete(sessionId);
3675
+ if (row === void 0 || this.appendFunction === void 0) return;
3676
+ this.writtenRows.set(sessionId, row);
3677
+ while (this.writtenRows.size > WRITTEN_ROWS) this.writtenRows.delete(this.writtenRows.keys().next().value);
3678
+ }
3679
+ /**
3680
+ * Appends `entries` in one round trip through the session append function, planned from the row this store's last
3681
+ * write of the session left (#6599). The function takes the session's locks as a session write transaction does,
3682
+ * checks the schema version, the session and its expected seq as `forWrite` does, writes nothing unless the stored
3683
+ * row is still the one planned from, checks the snapshot blobs as `assertStored` does, and writes the row, the
3684
+ * entries and their search texts in the order an append's transaction does. Undefined, having written nothing, when
3685
+ * the append is not one it plans (no function, no remembered row, a row other than the stored one, invalid entries,
3686
+ * a chunked entry or more than one batch of writes, an entry that refers back past the resume window): the caller
3687
+ * then appends in a transaction as before, which reads the row itself and reports what fails.
3688
+ */
3689
+ async appendThroughFunction(sessionId, entries, options) {
3690
+ const fn = this.appendFunction;
3691
+ const autocommit = this.database.autocommit?.bind(this.database);
3692
+ const previous = this.writtenRows.get(sessionId);
3693
+ if (fn === void 0 || autocommit === void 0 || previous === void 0) return void 0;
3694
+ if (previous.last_seq !== options.expectSeq) return void 0;
3695
+ const state = JSON.parse(previous.summary_state);
3696
+ if (options.epoch !== void 0 && state.epoch !== options.epoch) return void 0;
3697
+ try {
3698
+ validateSessionEntries(entries);
3699
+ } catch {
3700
+ return;
3701
+ }
3702
+ const window = windowIndex(state, previous.last_seq);
3703
+ if (isSessionResumeIndex(window, previous.last_seq) && foreignResumeIds(window, entries).length > 0) return void 0;
3704
+ const lastSeq = previous.last_seq + entries.length;
3705
+ const summary = this.summaryWrite(sessionId, {
3706
+ header: JSON.parse(previous.header_json),
3707
+ entries,
3708
+ lastSeq
3709
+ }, state, await this.appendedResume(this.database, sessionId, window, previous.last_seq, entries));
3710
+ const rows = [];
3711
+ const written = [];
3712
+ let bytes = statementBytes(summary.statement);
3713
+ for (const [index, entry] of entries.entries()) {
3714
+ const json = this.encode(entry);
3715
+ const stored = storedEntry(entry, json);
3716
+ bytes += entry.id.length + stored.json.length;
3717
+ if (stored.chunks.length > 0 || bytes > STATEMENT_BATCH_BYTES) return void 0;
3718
+ rows.push([entry.id, stored.json]);
3719
+ written.push({
3720
+ entry,
3721
+ seq: previous.last_seq + index + 1,
3722
+ json
3723
+ });
3724
+ }
3725
+ const texts = summary.texts.map(({ index, text }) => [previous.last_seq + index + 1, this.encode(text)]);
3726
+ const blobs = this.blobTable.storedHashes(entries.flatMap((entry) => entry.type === "worktree_snapshot" && entry.snapshot !== void 0 ? [entry.snapshot] : []));
3727
+ const { concurrency = { kind: "serial" } } = sessionWriteTransaction(this.tables.sessions, sessionId);
3728
+ const [answer] = await autocommit({
3729
+ sql: `SELECT outcome, detail FROM ${fn}(${Array.from({ length: 24 }, () => "?").join(", ")})`,
3730
+ params: [
3731
+ concurrency.kind === "serial" ? concurrency.domain ?? "" : "",
3732
+ SESSION_SCHEMA_VERSION_UNCHUNKED,
3733
+ 3,
3734
+ sessionId,
3735
+ previous.last_seq,
3736
+ previous.revision,
3737
+ await sha256Hex(new TextEncoder().encode(`${previous.header_json}\n${previous.summary_state}`)),
3738
+ blobs.length === 0 ? null : JSON.stringify(blobs),
3739
+ ...summary.statement.params.slice(1),
3740
+ JSON.stringify(rows),
3741
+ JSON.stringify(texts)
3742
+ ]
3743
+ }, concurrency);
3744
+ switch (answer?.outcome) {
3745
+ case "appended":
3746
+ this.noteWritten(sessionId, summary.epoch, written);
3747
+ this.rememberWritten(sessionId, summary.row);
3748
+ return { lastSeq };
3749
+ case "version":
3750
+ assertStorageSchemaVersion("sessions", answer.detail === null ? null : Number(answer.detail), 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
3751
+ break;
3752
+ case "missing": throw new SessionNotFoundError$1(sessionId);
3753
+ case "conflict": throw new SessionConflictError$1(sessionId, options.expectSeq, Number(answer.detail));
3754
+ case "blob": return this.blobTable.refuseCollected(String(answer.detail));
3755
+ }
3756
+ this.writtenRows.delete(sessionId);
3757
+ }
3758
+ /**
3759
+ * The session append function of the store's tables, `<prefix>session_append_v1`: one statement, and so one round
3760
+ * trip, for what an append's transaction does with its two (#6599). Created by `atomic storage migrate` through
3761
+ * {@link prepareAppendFunction}. It runs with the caller's rights, so it lets a role do nothing its table
3762
+ * privileges do not, and in the caller's `search_path`, the schema a transaction of the store sets. It writes no
3763
+ * chunked entry: an append that has one goes through a transaction. Its answer is one row: `appended`, or why it
3764
+ * wrote nothing, with the stored version (`version`), the stored last seq (`conflict`), the first blob that is not
3765
+ * stored (`blob`), no session (`missing`), or a stored row other than the one the caller planned from (`stale`).
3766
+ */
3767
+ appendFunctionSql(fn) {
3768
+ const t = this.tables;
3769
+ return `CREATE OR REPLACE FUNCTION ${fn}(
3770
+ p_domain text, p_oldest bigint, p_newest bigint, p_session_id text, p_expect_seq bigint, p_revision text,
3771
+ p_digest text, p_blobs text, p_cwd text, p_created_at text, p_header_json text, p_internal bigint, p_last_seq bigint,
3772
+ p_modified_at text, p_message_count bigint, p_first_message text, p_name text, p_has_name bigint, p_summary text,
3773
+ p_summarized_through_id text, p_summary_state text, p_new_revision text, p_entries text, p_texts text
3774
+ ) RETURNS TABLE (outcome text, detail text) LANGUAGE plpgsql AS $append$
3775
+ #variable_conflict use_column
3776
+ DECLARE
3777
+ scope text := CASE WHEN current_schema() = 'public' THEN '' ELSE current_schema() || ':' END;
3778
+ stored_version bigint;
3779
+ head record;
3780
+ stored_blobs text[];
3781
+ missing_blob text;
3782
+ BEGIN
3783
+ -- The locks of a session write transaction, waited for as long as one waits: its lock wait is the statement timeout.
3784
+ PERFORM set_config('lock_timeout', current_setting('statement_timeout'), true);
3785
+ PERFORM pg_advisory_xact_lock_shared(hashtextextended(scope || 'atomic', 0)),
3786
+ pg_advisory_xact_lock(hashtextextended(scope || p_domain, 0));
3787
+ SELECT schema_version INTO stored_version FROM ${t.meta};
3788
+ IF stored_version IS NULL OR stored_version < p_oldest OR stored_version > p_newest THEN
3789
+ RETURN QUERY SELECT 'version'::text, stored_version::text;
3790
+ RETURN;
3791
+ END IF;
3792
+ SELECT s.last_seq, s.revision,
3793
+ encode(sha256(convert_to(s.header_json || E'\n' || s.summary_state, 'UTF8')), 'hex') AS digest
3794
+ INTO head FROM ${t.sessions} AS s WHERE s.id = p_session_id;
3795
+ IF NOT FOUND THEN
3796
+ RETURN QUERY SELECT 'missing'::text, NULL::text;
3797
+ RETURN;
3798
+ END IF;
3799
+ IF head.last_seq <> p_expect_seq THEN
3800
+ RETURN QUERY SELECT 'conflict'::text, head.last_seq::text;
3801
+ RETURN;
3802
+ END IF;
3803
+ IF head.revision <> p_revision OR head.digest <> p_digest THEN
3804
+ RETURN QUERY SELECT 'stale'::text, NULL::text;
3805
+ RETURN;
3806
+ END IF;
3807
+ IF p_blobs IS NOT NULL THEN
3808
+ SELECT array_agg(locked.hash) INTO stored_blobs FROM (${this.blobTable.storedBlobsQuery("p_blobs")}) AS locked;
3809
+ SELECT h.value INTO missing_blob FROM json_array_elements_text(p_blobs::json) WITH ORDINALITY AS h(value, ord)
3810
+ WHERE h.value <> ALL (coalesce(stored_blobs, '{}'::text[])) ORDER BY h.ord LIMIT 1;
3811
+ IF missing_blob IS NOT NULL THEN
3812
+ RETURN QUERY SELECT 'blob'::text, missing_blob;
3813
+ RETURN;
3814
+ END IF;
3815
+ END IF;
3816
+ INSERT INTO ${t.sessions}
3817
+ (id, cwd, created_at, header_json, internal, last_seq, modified_at, message_count,
3818
+ first_message, name, has_name, summary, summarized_through_id, summary_state, revision)
3819
+ VALUES (p_session_id, p_cwd, p_created_at, p_header_json, p_internal, p_last_seq, p_modified_at, p_message_count,
3820
+ p_first_message, p_name, p_has_name, p_summary, p_summarized_through_id, p_summary_state, p_new_revision)
3821
+ ON CONFLICT(id) DO UPDATE SET
3822
+ cwd = excluded.cwd, created_at = excluded.created_at, header_json = excluded.header_json,
3823
+ internal = excluded.internal, last_seq = excluded.last_seq, modified_at = excluded.modified_at,
3824
+ message_count = excluded.message_count, first_message = excluded.first_message, name = excluded.name,
3825
+ has_name = excluded.has_name, summary = excluded.summary,
3826
+ summarized_through_id = excluded.summarized_through_id,
3827
+ summary_state = excluded.summary_state, revision = excluded.revision;
3828
+ INSERT INTO ${t.entries} (session_id, seq, entry_id, entry_json, chunks)
3829
+ SELECT p_session_id, p_expect_seq + e.ord, e.value->>0, e.value->>1, 0
3830
+ FROM json_array_elements(p_entries::json) WITH ORDINALITY AS e(value, ord) ORDER BY e.ord;
3831
+ INSERT INTO ${t.searchTexts} (session_id, seq, text_json)
3832
+ SELECT p_session_id, (x.value->>0)::bigint, x.value->>1
3833
+ FROM json_array_elements(p_texts::json) WITH ORDINALITY AS x(value, ord) ORDER BY x.ord;
3834
+ RETURN QUERY SELECT 'appended'::text, NULL::text;
3835
+ END
3836
+ $append$`;
3837
+ }
3838
+ /**
3839
+ * Creates the session append function (#6599), once per revision, as the ledger records it, and lets every role that
3840
+ * may insert into the sessions table execute it: `atomic storage migrate` runs this as the owner role, and a
3841
+ * runtime role appends through the function from its next open on. PostgreSQL only; does nothing elsewhere.
3842
+ */
3843
+ async prepareAppendFunction() {
3844
+ this.assertOpen();
3845
+ if (this.dialect.name !== "postgres") return;
3846
+ const fn = renderStorageIdentifiers("sessions", { append: SESSION_APPEND_FUNCTION }, this.prefix).append;
3847
+ const ledger = storageMigrationTable(this.prefix);
3848
+ const physical = (name) => this.dialect.identifier(name).replaceAll("'", "''");
3849
+ await this.database.transaction(async (tx) => {
3850
+ await ensureStorageSchema(tx, this.dialect, {
3851
+ ledger,
3852
+ domain: SESSION_APPEND_FUNCTION_DOMAIN,
3853
+ revision: SESSION_APPEND_FUNCTION_REVISION
3854
+ }, () => tx.exec(this.appendFunctionSql(fn)));
3855
+ await tx.exec(`DO $grant$
3856
+ DECLARE grantee text;
3857
+ BEGIN
3858
+ FOR grantee IN SELECT DISTINCT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE quote_ident(pg_catalog.pg_get_userbyid(a.grantee)) END
3859
+ FROM pg_catalog.pg_class c, pg_catalog.aclexplode(c.relacl) AS a
3860
+ WHERE c.relnamespace = current_schema()::regnamespace AND c.relname = '${physical(this.tables.sessions)}'
3861
+ AND a.privilege_type = 'INSERT' AND a.grantee <> c.relowner
3862
+ LOOP
3863
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I TO %s', '${physical(fn)}', grantee);
3864
+ END LOOP;
3865
+ END
3866
+ $grant$`);
3867
+ }, {
3868
+ retryTransientFailures: true,
3869
+ concurrency: {
3870
+ kind: "serial",
3871
+ domain: ledger
3872
+ }
3873
+ });
2357
3874
  }
2358
3875
  async replace(sessionId, header, entries, options) {
2359
3876
  this.assertOpen();
2360
3877
  validateSessionText("sessionId", sessionId);
2361
- return this.transaction(async (tx) => {
2362
- await this.forWrite(tx, sessionId, options);
3878
+ this.writtenRows.delete(sessionId);
3879
+ let released = [];
3880
+ let entriesWritten = [];
3881
+ const pinReads = this.sharedHistorySeen ? forkPinReads(this.forkHost(), this.tables.sessions, sessionId) : void 0;
3882
+ const written = await this.transactionCheckedAlongside(async (tx, checked) => {
3883
+ released = [];
3884
+ entriesWritten = [];
3885
+ const [, pins] = await Promise.all([this.forWrite(tx, sessionId, options), this.readForkPinsWithin(tx, sessionId, pinReads)]);
3886
+ await checked;
2363
3887
  validateSessionHeader(header);
2364
3888
  validateSessionEntries(entries);
2365
3889
  if (header.id !== sessionId) throw new SessionIdMismatchError$1(sessionId, header.id);
3890
+ if (pins !== void 0) released = await replaceForkedSessionWithin(this.forkHost(), tx, sessionId, pins).catch((error) => {
3891
+ noteForkCopyRefusal(error, "replace");
3892
+ throw error;
3893
+ });
2366
3894
  await this.searchIndex?.forgetWithin(tx, sessionId);
2367
3895
  await tx.run(`DELETE FROM ${this.tables.searchTexts} WHERE session_id = ?`, sessionId);
2368
3896
  await tx.run(`DELETE FROM ${this.tables.entryChunks} WHERE session_id = ?`, sessionId);
@@ -2372,16 +3900,20 @@ var SqlSessionStore = class SqlSessionStore {
2372
3900
  entries,
2373
3901
  lastSeq: entries.length
2374
3902
  });
2375
- await this.insertEntries(tx, sessionId, entries, 0, texts);
3903
+ await this.insertEntries(tx, sessionId, entries, 0, texts, true, entriesWritten);
2376
3904
  return {
2377
3905
  lastSeq: entries.length,
2378
3906
  epoch
2379
3907
  };
2380
- }, this.sessionWrite(sessionId));
3908
+ }, this.sessionWrite(sessionId, ...pinReads === void 0 ? [] : [this.headRead(sessionId, options, false), ...pinReads]));
3909
+ this.noteWritten(sessionId, written.epoch, entriesWritten);
3910
+ await this.sweepReleasedForkRows(released);
3911
+ return written;
2381
3912
  }
2382
3913
  async updateHeader(header, options) {
2383
3914
  this.assertOpen();
2384
3915
  validateSessionHeader(header);
3916
+ this.writtenRows.delete(header.id);
2385
3917
  return this.transaction(async (tx) => {
2386
3918
  const { row, state } = await this.forWrite(tx, header.id, options, true);
2387
3919
  const epoch = newRevision();
@@ -2421,15 +3953,19 @@ var SqlSessionStore = class SqlSessionStore {
2421
3953
  const skippedSet = query.skipTypes === void 0 ? void 0 : new Set(query.skipTypes);
2422
3954
  const skippedPrefixes = (query.skipTypes ?? []).map((type) => `{"type":${JSON.stringify(type)},`);
2423
3955
  const largeBytes = query.largeEntryBytes ?? 0x7fffffff;
2424
- const read = await this.database.all(`WITH sized AS (
2425
- SELECT seq, chunks, ${this.entryByteLength("entry_json")} AS raw_bytes,
3956
+ const selected = query.seqs === void 0 ? "" : ` AND seq IN (SELECT CAST(value AS ${this.dialect.types.int}) FROM ${this.dialect.jsonValues("?")})`;
3957
+ const fitted = query.seqs === void 0 ? "" : " AND (p.before_chars = 0 OR p.before_chars + p.bytes <= ?)";
3958
+ const maxChars = query.maxChars !== void 0 && query.maxChars <= 0 ? 0 : query.maxChars ?? Number.MAX_SAFE_INTEGER;
3959
+ const read = await this.outsideSessionRead(sessionId, (tables) => {
3960
+ const view = this.entriesView(tables, sessionId, fromSeq - 1, Math.min(query.toSeq, FORK_VIEW_END));
3961
+ return this.database.all(withForkViews([view], `WITH sized AS (
3962
+ SELECT seq, chunks, src_id, src_seq, ${this.entryByteLength("entry_json")} AS raw_bytes,
2426
3963
  ${this.entryByteLength("entry_json")} + chunks * ? AS bytes
2427
- FROM ${this.tables.entries}
2428
- WHERE session_id = ? AND seq >= ? AND seq <= ?
2429
- AND seq <= (SELECT last_seq FROM ${this.tables.sessions} WHERE id = ?)
3964
+ FROM ${view.name}
3965
+ WHERE seq <= (SELECT last_seq FROM ${this.tables.sessions} WHERE id = ?)${selected}
2430
3966
  ),
2431
3967
  paged AS (
2432
- SELECT seq, chunks, raw_bytes, count(*) OVER () AS remaining,
3968
+ SELECT seq, chunks, src_id, src_seq, raw_bytes, bytes, count(*) OVER () AS remaining,
2433
3969
  sum(bytes) OVER (ORDER BY seq) - bytes AS before_chars
2434
3970
  FROM sized
2435
3971
  ),
@@ -2439,13 +3975,19 @@ var SqlSessionStore = class SqlSessionStore {
2439
3975
  CASE WHEN p.chunks = 0 AND p.raw_bytes > ? AND substr(e.entry_json, 1, 8) <> '{"type":'
2440
3976
  THEN ${this.dialect.jsonText("e.entry_json", "type")} END AS entry_type
2441
3977
  FROM paged p
2442
- JOIN ${this.tables.entries} e ON e.session_id = ? AND e.seq = p.seq
2443
- WHERE p.before_chars < ?
3978
+ JOIN ${this.tables.entries} e ON e.session_id = p.src_id AND e.seq = p.src_seq
3979
+ WHERE p.before_chars < ?${fitted}
2444
3980
  )
2445
- SELECT s.last_seq, page.seq, page.entry_json, page.entry_head, page.chunks, page.remaining, page.entry_type
3981
+ SELECT s.last_seq, page.seq, page.entry_json, page.entry_head, page.chunks, page.remaining, page.entry_type${this.outsideForkedColumn("s.id")}
2446
3982
  FROM ${this.tables.sessions} s LEFT JOIN page ON 1 = 1
2447
3983
  WHERE s.id = ?
2448
- ORDER BY page.seq`, SESSION_ENTRY_CHUNK_BYTES, sessionId, fromSeq, Math.min(query.toSeq, Number.MAX_SAFE_INTEGER), sessionId, largeBytes, largeBytes, sessionId, query.maxChars !== void 0 && query.maxChars <= 0 ? 0 : query.maxChars ?? Number.MAX_SAFE_INTEGER, sessionId);
3984
+ ORDER BY page.seq`), ...view.params, SESSION_ENTRY_CHUNK_BYTES, sessionId, ...query.seqs === void 0 ? [] : [JSON.stringify(query.seqs)], largeBytes, largeBytes, maxChars, ...query.seqs === void 0 ? [] : [maxChars], sessionId);
3985
+ }, (found) => {
3986
+ const session = found[0];
3987
+ if (session === void 0 || maxChars <= 0) return true;
3988
+ if (fromSeq > Math.min(query.toSeq, Number(session.last_seq))) return true;
3989
+ return found.some((row) => row.seq !== null && row.seq !== void 0);
3990
+ }, (found) => found[0]?.forked);
2449
3991
  const session = read[0];
2450
3992
  if (!session) throw new SessionNotFoundError$1(sessionId);
2451
3993
  const lastSeq = Number(session.last_seq);
@@ -2468,7 +4010,7 @@ var SqlSessionStore = class SqlSessionStore {
2468
4010
  const seq = Number(row.seq);
2469
4011
  const chunks = Number(row.chunks);
2470
4012
  if (chunks > 0) {
2471
- const rawChunks = await this.readRawEntryChunks(this.database, sessionId, seq, chunks, query.signal);
4013
+ const rawChunks = await this.readRawEntryChunks(this.database, void 0, sessionId, seq, chunks, query.signal);
2472
4014
  if (rawChunks.reduce((total, chunk) => total + chunk.byteLength, 0) > largeBytes) entries.push({
2473
4015
  seq,
2474
4016
  entry: STUB_ENTRY,
@@ -2513,15 +4055,54 @@ var SqlSessionStore = class SqlSessionStore {
2513
4055
  async delete(sessionId) {
2514
4056
  this.assertOpen();
2515
4057
  validateSessionText("sessionId", sessionId);
2516
- await this.transaction(async (tx) => {
4058
+ this.writtenRows.delete(sessionId);
4059
+ let released = [];
4060
+ const pinReads = this.sharedHistorySeen ? forkPinReads(this.forkHost(), this.tables.sessions, sessionId) : void 0;
4061
+ await this.transactionCheckedAlongside(async (tx, checked) => {
4062
+ released = [];
4063
+ const pins = await this.readForkPinsWithin(tx, sessionId, pinReads);
4064
+ await checked;
2517
4065
  await this.searchIndex?.forgetWithin(tx, sessionId);
4066
+ if (pins !== void 0) {
4067
+ const pinned = await deleteForkedSessionWithin(this.forkHost(), tx, sessionId, (/* @__PURE__ */ new Date()).toISOString(), pins);
4068
+ released = pinned.released;
4069
+ if (pinned.keepRows) {
4070
+ await tx.run(`DELETE FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
4071
+ return;
4072
+ }
4073
+ }
2518
4074
  await tx.run(`DELETE FROM ${this.tables.blobChunks} WHERE session_id = ?`, sessionId);
2519
4075
  await tx.run(`DELETE FROM ${this.tables.blobs} WHERE session_id = ?`, sessionId);
2520
4076
  await tx.run(`DELETE FROM ${this.tables.searchTexts} WHERE session_id = ?`, sessionId);
2521
4077
  await tx.run(`DELETE FROM ${this.tables.entryChunks} WHERE session_id = ?`, sessionId);
2522
4078
  await tx.run(`DELETE FROM ${this.tables.entries} WHERE session_id = ?`, sessionId);
2523
4079
  await tx.run(`DELETE FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
2524
- }, SESSION_TRANSACTION);
4080
+ }, pinReads === void 0 ? SESSION_TRANSACTION : {
4081
+ ...SESSION_TRANSACTION,
4082
+ leading: pinReads
4083
+ });
4084
+ await this.sweepReleasedForkRows(released);
4085
+ }
4086
+ /**
4087
+ * The fork history of `sessionId` where the transaction `tx` runs on shared history: through `reads`, the transaction's
4088
+ * leading reads, or, for a store that had not seen shared history when the transaction began, read now.
4089
+ */
4090
+ async readForkPinsWithin(tx, sessionId, reads) {
4091
+ if (reads !== void 0) return readForkPins(tx, reads);
4092
+ if (!await this.sharedHistoryForks(tx)) return void 0;
4093
+ return readForkPins(tx, forkPinReads(this.forkHost(), this.tables.sessions, sessionId));
4094
+ }
4095
+ /**
4096
+ * Removes the rows of deleted sessions no fork reads any more, among `released` and any an earlier sweep left, in
4097
+ * transactions of their own after the write that released them committed. A sweep that fails leaves tombstones the
4098
+ * next one finishes: the write it follows stands either way.
4099
+ */
4100
+ async sweepReleasedForkRows(released) {
4101
+ if (released.length === 0) return;
4102
+ const { sweepForkTombstones } = await import("../core/storage/session/fork-sweep.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
4103
+ try {
4104
+ await sweepForkTombstones(this.forkHost(), released);
4105
+ } catch {}
2525
4106
  }
2526
4107
  /**
2527
4108
  * Stores the blob as rows of at most {@link SESSION_BLOB_CHUNK_BYTES}, then publishes its header. Every statement
@@ -2538,7 +4119,13 @@ var SqlSessionStore = class SqlSessionStore {
2538
4119
  hash: await sha256Hex(stored),
2539
4120
  bytes: stored.byteLength
2540
4121
  };
2541
- const previous = await this.blobHeader(sessionId, blob.hash);
4122
+ const found = await this.database.get(`SELECT (SELECT max(schema_version) FROM ${this.tables.meta}) AS schema_version, b.bytes, b.chunks
4123
+ FROM (SELECT 1 AS one) AS probe LEFT JOIN ${this.tables.blobs} b ON b.session_id = ? AND b.hash = ?`, sessionId, blob.hash);
4124
+ assertStorageSchemaVersion("sessions", found?.schema_version ?? null, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
4125
+ const previous = found?.bytes === null || found?.bytes === void 0 ? void 0 : {
4126
+ bytes: Number(found.bytes),
4127
+ chunks: Number(found.chunks)
4128
+ };
2542
4129
  if (previous) {
2543
4130
  if (previous.chunks === -1) while (await this.database.transaction((tx) => migrateLegacyBlobBatch(tx, this.tables, sessionId, blob.hash, stored), this.sessionWrite(sessionId))) await new Promise((resolve) => setTimeout(resolve, 0));
2544
4131
  return blob;
@@ -2563,36 +4150,68 @@ var SqlSessionStore = class SqlSessionStore {
2563
4150
  async getBlob(sessionId, hash) {
2564
4151
  this.assertOpen();
2565
4152
  validateSessionText("sessionId", sessionId);
2566
- let header = await this.blobHeader(sessionId, hash);
2567
- if (header === void 0) return void 0;
2568
- if (header.chunks === -1) {
2569
- const row = await this.database.get(`SELECT data FROM ${this.tables.blobs} WHERE session_id = ? AND hash = ? AND chunks = -1`, sessionId, hash);
2570
- if (row) {
2571
- if (row.data.byteLength === header.bytes) return row.data;
2572
- throw new SessionBlobError("blob-incomplete", {
2573
- sessionId,
2574
- hash,
2575
- bytes: header.bytes
2576
- });
2577
- }
2578
- header = await this.blobHeader(sessionId, hash);
4153
+ for (let attempt = 0;; attempt++) {
4154
+ const header = await this.blobOwner(sessionId, hash);
2579
4155
  if (header === void 0) return void 0;
4156
+ const { owner } = header;
4157
+ if (header.chunks === -1) {
4158
+ const row = await this.database.get(`SELECT data FROM ${this.tables.blobs} WHERE session_id = ? AND hash = ? AND chunks = -1`, owner, hash);
4159
+ if (row) {
4160
+ if (row.data.byteLength === header.bytes) return row.data;
4161
+ throw new SessionBlobError("blob-incomplete", {
4162
+ sessionId,
4163
+ hash,
4164
+ bytes: header.bytes
4165
+ });
4166
+ }
4167
+ if (attempt < 2) continue;
4168
+ return;
4169
+ }
4170
+ const data = new Uint8Array(header.bytes);
4171
+ let offset = 0;
4172
+ for (let index = 0; index < header.chunks; index++) {
4173
+ const row = await this.database.get(`SELECT data FROM ${this.tables.blobChunks} WHERE idx = ? AND session_id = ? AND hash = ?`, index, owner, hash);
4174
+ if (row?.data == null || offset + row.data.byteLength > data.byteLength) break;
4175
+ data.set(row.data, offset);
4176
+ offset += row.data.byteLength;
4177
+ }
4178
+ if (offset === data.byteLength) return data;
4179
+ const again = await this.blobOwner(sessionId, hash);
4180
+ if (again === void 0) return void 0;
4181
+ if (again.owner !== owner && attempt < 2) continue;
4182
+ throw new SessionBlobError("blob-incomplete", {
4183
+ sessionId,
4184
+ hash,
4185
+ bytes: header.bytes
4186
+ });
2580
4187
  }
2581
- const data = new Uint8Array(header.bytes);
2582
- let offset = 0;
2583
- for (let index = 0; index < header.chunks; index++) {
2584
- const row = await this.database.get(`SELECT data FROM ${this.tables.blobChunks} WHERE idx = ? AND session_id = ? AND hash = ?`, index, sessionId, hash);
2585
- if (row?.data == null || offset + row.data.byteLength > data.byteLength) break;
2586
- data.set(row.data, offset);
2587
- offset += row.data.byteLength;
2588
- }
2589
- if (offset === data.byteLength) return data;
2590
- if (await this.blobHeader(sessionId, hash) === void 0) return void 0;
2591
- throw new SessionBlobError("blob-incomplete", {
2592
- sessionId,
2593
- hash,
2594
- bytes: header.bytes
2595
- });
4188
+ }
4189
+ /**
4190
+ * Where session `sessionId`'s blob `hash` is stored, with its header: its own, or the first of its fork sources' by
4191
+ * id, through the segments of a fork that shares its parent's history (#6560). Read outside a transaction.
4192
+ */
4193
+ async blobOwner(sessionId, hash) {
4194
+ const row = await this.outsideTransaction((tables) => this.database.get(tables.segments === void 0 ? `SELECT session_id AS owner, bytes, chunks FROM ${this.tables.blobs} WHERE session_id = ? AND hash = ?${tables.guard === void 0 ? "" : ` AND ${tables.guard}`}` : `SELECT b.session_id AS owner, b.bytes, b.chunks
4195
+ FROM ${this.blobPlaces(tables)} w JOIN ${this.tables.blobs} b ON b.session_id = w.owner AND b.hash = ?
4196
+ ${tables.guard === void 0 ? "" : `WHERE ${tables.guard}`}
4197
+ ORDER BY w.place, b.session_id LIMIT 1`, ...tables.segments === void 0 ? [sessionId, hash] : [...this.blobPlaceParams(tables, sessionId), hash]), (found) => found !== void 0);
4198
+ return row === void 0 ? void 0 : {
4199
+ owner: String(row.owner),
4200
+ bytes: Number(row.bytes),
4201
+ chunks: Number(row.chunks)
4202
+ };
4203
+ }
4204
+ /**
4205
+ * The sessions whose blobs a session reads (#6560), as a derived table of `owner` and `place`: the session itself,
4206
+ * place 0, and, with shared history, the sources its segments name, place 1. A blob is then looked up by its key in
4207
+ * each, never by a scan of the blobs of every session. Its parameters are {@link blobPlaceParams}.
4208
+ */
4209
+ blobPlaces(tables) {
4210
+ const own = `SELECT CAST(? AS ${this.dialect.types.text}) AS owner, 0 AS place`;
4211
+ return tables.segments === void 0 ? `(${own})` : `(${own} UNION ALL SELECT source_id, 1 FROM ${tables.segments} WHERE session_id = ?)`;
4212
+ }
4213
+ blobPlaceParams(tables, sessionId) {
4214
+ return tables.segments === void 0 ? [sessionId] : [sessionId, sessionId];
2596
4215
  }
2597
4216
  async blobHeader(sessionId, hash) {
2598
4217
  const row = await this.database.get(`SELECT bytes, chunks FROM ${this.tables.blobs} WHERE session_id = ? AND hash = ?`, sessionId, hash);
@@ -2662,6 +4281,7 @@ var SqlSessionStore = class SqlSessionStore {
2662
4281
  this.closed = true;
2663
4282
  this.scopes.clear();
2664
4283
  this.summaries.clear();
4284
+ dropStoredNotes(this);
2665
4285
  const reader = this.reader;
2666
4286
  this.reader = void 0;
2667
4287
  if (reader !== void 0) await (await reader.catch(() => void 0))?.close();
@@ -2846,17 +4466,25 @@ var SqlSessionStore = class SqlSessionStore {
2846
4466
  const order = this.dialect.rowOrder();
2847
4467
  const rows = [];
2848
4468
  for (let after = 0, limit = SESSION_READ_FETCH.first;;) {
4469
+ const seen = this.sharedHistorySeen;
4470
+ const texts = (session) => forkViewOf({
4471
+ segments: seen ? this.forkTables.forkSegments : void 0,
4472
+ dialect: this.dialect
4473
+ }, {
4474
+ table: this.tables.searchTexts,
4475
+ columns: ["text_json"]
4476
+ }, session);
2849
4477
  const page = await this.database.all(`WITH keyed AS MATERIALIZED (
2850
4478
  SELECT ${LISTING_COLUMNS}, ${order} AS ord, ${LISTING_SIZE} AS size
2851
4479
  FROM ${this.tables.sessions} AS s WHERE (${where}) AND ${order} > ? ORDER BY ord LIMIT ?
2852
4480
  ), sized AS MATERIALIZED (
2853
4481
  SELECT ${LISTING_COLUMNS}, ord, size,
2854
- (SELECT COALESCE(sum(length(text_json) + 1) + 1, 2) FROM ${this.tables.searchTexts} WHERE session_id = keyed.id) AS search_size
4482
+ (SELECT COALESCE(sum(length(text_json) + 1) + 1, 2) FROM ${texts("keyed.id")} AS t) AS search_size
2855
4483
  FROM keyed
2856
4484
  ) SELECT ${LISTING_COLUMNS}, ord, fetched, batch_chars, page_chars, CASE WHEN search_size <= ? THEN (
2857
4485
  SELECT COALESCE('[' || ${this.dialect.orderedConcat("text_json", "','", "seq")} || ']', '[]')
2858
- FROM (SELECT text_json, seq FROM ${this.tables.searchTexts} WHERE session_id = page.id ORDER BY seq)
2859
- ) END AS search_texts_json
4486
+ FROM (SELECT text_json, seq FROM ${texts("page.id")} AS t ORDER BY seq) AS ordered
4487
+ ) END AS search_texts_json, (SELECT max(schema_version) FROM ${this.tables.meta}) AS schema_version
2860
4488
  FROM (
2861
4489
  SELECT ${LISTING_COLUMNS}, ord, search_size, count(*) OVER () AS fetched,
2862
4490
  row_number() OVER (ORDER BY ord) AS page_row,
@@ -2864,6 +4492,11 @@ var SqlSessionStore = class SqlSessionStore {
2864
4492
  sum(size + search_size) OVER (ORDER BY ord) AS page_chars
2865
4493
  FROM sized
2866
4494
  ) AS page WHERE (page_chars <= ? OR page_row = 1) AND page_row <= ? ORDER BY ord`, ...params, after, limit + 1, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, limit);
4495
+ for (const row of page) {
4496
+ assertStorageSchemaVersion("sessions", row.schema_version, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
4497
+ this.noteSchemaVersion(row.schema_version);
4498
+ }
4499
+ if (this.sharedHistorySeen !== seen) continue;
2867
4500
  for (const row of page) {
2868
4501
  const summaryRow = row.search_texts_json === null ? {
2869
4502
  ...row,
@@ -2881,12 +4514,31 @@ var SqlSessionStore = class SqlSessionStore {
2881
4514
  limit = next.limit;
2882
4515
  }
2883
4516
  }
2884
- /** A session's search texts as one JSON array, read in pages of at most {@link SESSION_READ_PAGE_CHARS}. */
4517
+ /**
4518
+ * A session's search texts as one JSON array, read in pages of at most {@link SESSION_READ_PAGE_CHARS}, through its
4519
+ * view (#6560). Only a session with some text is read this way, so a read that finds none was held back.
4520
+ */
2885
4521
  async readSearchTexts(sessionId) {
2886
- const sizes = await this.database.all(`SELECT seq, length(text_json) AS size FROM ${this.tables.searchTexts} WHERE session_id = ? ORDER BY seq`, sessionId);
4522
+ const textsView = (tables, after, through) => {
4523
+ return forkView(tables, {
4524
+ name: "texts_view",
4525
+ table: this.tables.searchTexts,
4526
+ columns: ["text_json"],
4527
+ sessionId,
4528
+ after,
4529
+ through
4530
+ });
4531
+ };
4532
+ const sizes = await this.outsideTransaction((tables) => {
4533
+ const view = textsView(tables, 0, FORK_VIEW_END);
4534
+ return this.database.all(withForkViews([view], "SELECT seq, length(text_json) AS size FROM texts_view ORDER BY seq"), ...view.params);
4535
+ }, (found) => found.length > 0);
2887
4536
  const texts = [];
2888
4537
  for (const page of pagesOf(sizes)) {
2889
- const rows = await this.database.all(`SELECT text_json FROM ${this.tables.searchTexts} WHERE session_id = ? AND seq >= ? AND seq <= ? ORDER BY seq`, sessionId, page[0].seq, page.at(-1).seq);
4538
+ const rows = await this.outsideTransaction((tables) => {
4539
+ const view = textsView(tables, Number(page[0].seq) - 1, Number(page.at(-1).seq));
4540
+ return this.database.all(withForkViews([view], "SELECT text_json FROM texts_view ORDER BY seq"), ...view.params);
4541
+ }, (found) => found.length > 0);
2890
4542
  for (const row of rows) texts.push(row.text_json);
2891
4543
  }
2892
4544
  return `[${texts.join(",")}]`;
@@ -2907,8 +4559,18 @@ var SqlSessionStore = class SqlSessionStore {
2907
4559
  query.signal?.throwIfAborted();
2908
4560
  }
2909
4561
  async read(tx, sessionId) {
2910
- const [row, rows] = await Promise.all([tx.get(`SELECT header_json, last_seq,CASE WHEN ${this.dialect.jsonValid("summary_state")} THEN ${this.dialect.jsonText("summary_state", "epoch")} END AS chat_epoch,revision FROM ${this.tables.sessions} WHERE id = ?`, sessionId), this.readRows(tx, sessionId)]);
4562
+ const generation = this.generation(sessionId);
4563
+ const shared = await this.viewTables(tx);
4564
+ const head = tx.get(`SELECT header_json, last_seq,CASE WHEN ${this.dialect.jsonValid("summary_state")} THEN ${this.dialect.jsonText("summary_state", "epoch")} END AS chat_epoch,revision,${generation.sql} AS epoch${this.forkedColumn(shared.segments)} FROM ${this.tables.sessions} WHERE id = ?`, ...generation.params, sessionId);
4565
+ const guess = this.forkedSessions.get(sessionId) === false ? {
4566
+ ...shared,
4567
+ segments: void 0
4568
+ } : shared;
4569
+ const epoch = head.then((found) => found?.epoch);
4570
+ let [row, rows] = await Promise.all([head, this.readRows(tx, sessionId, void 0, void 0, epoch, guess)]);
2911
4571
  if (!row) throw new SessionNotFoundError$1(sessionId);
4572
+ this.noteForked(tx, sessionId, row.forked);
4573
+ if (guess.segments === void 0 && shared.segments !== void 0 && Number(row.forked) === 1) rows = await this.readRows(tx, sessionId, void 0, void 0, epoch, shared);
2912
4574
  const snapshot = {
2913
4575
  header: JSON.parse(row.header_json),
2914
4576
  entries: rows.map(({ entry }) => entry),
@@ -2917,35 +4579,49 @@ var SqlSessionStore = class SqlSessionStore {
2917
4579
  if (typeof row.chat_epoch === "string") bindChatEpoch(snapshot.header, row.chat_epoch);
2918
4580
  return noteSnapshotGeneration(this, snapshot, nativeLoad, row, "revision");
2919
4581
  }
2920
- async readRows(tx, sessionId, filter = "", params = []) {
4582
+ /**
4583
+ * The entries of session `sessionId` from `from` through `through`, in pages, through its view (#6560): only those
4584
+ * whose seq `seqs` lists, when it is given, which then lies in that range. With `epoch`, the session's generation in
4585
+ * the snapshot of `tx`, each entry is noted as stored at its seq in it, for a fork of the session to share its row.
4586
+ */
4587
+ async readRows(tx, sessionId, range = {}, seqs, epoch, viewTables) {
4588
+ const tables = viewTables ?? await this.viewTables(tx, sessionId);
4589
+ const through = range.through ?? FORK_VIEW_END;
4590
+ const filter = seqs === void 0 ? "" : ` AND seq IN (${seqs.map(() => "?").join(", ")})`;
2921
4591
  const entries = [];
2922
- for (let after = 0, limit = SESSION_READ_FETCH.first;;) {
2923
- const rows = await tx.all(`WITH sized AS MATERIALIZED (
2924
- SELECT seq, chunks, length(entry_json) AS size,
4592
+ for (let after = Math.max(0, (range.from ?? 1) - 1), limit = SESSION_READ_FETCH.first;;) {
4593
+ const view = this.entriesView(tables, sessionId, after, tables.segments === void 0 || seqs !== void 0 ? through : Math.min(through, after + limit + 1));
4594
+ const rows = await tx.all(withForkViews([view], `WITH sized AS MATERIALIZED (
4595
+ SELECT seq, chunks, src_id, src_seq, length(entry_json) AS size,
2925
4596
  CASE WHEN ${this.dialect.textByteLength("entry_json")} <= ? THEN entry_json END AS inline_json
2926
- FROM ${this.tables.entries} WHERE session_id = ? AND seq > ?${filter === "" ? "" : ` AND ${filter}`} ORDER BY seq LIMIT ?
4597
+ FROM ${view.name} WHERE seq > ?${filter} ORDER BY seq LIMIT ?
2927
4598
  ), batch AS MATERIALIZED (
2928
4599
  SELECT count(*) AS fetched, COALESCE(sum(size), 0) AS chars FROM sized
2929
4600
  ), page AS (
2930
- SELECT seq, chunks, inline_json, fetched, chars AS batch_chars, 0 AS page_chars
2931
- FROM (SELECT seq, chunks, inline_json FROM sized ORDER BY seq LIMIT ?) AS fitting CROSS JOIN batch
4601
+ SELECT seq, chunks, src_id, src_seq, inline_json, fetched, chars AS batch_chars, 0 AS page_chars
4602
+ FROM (SELECT seq, chunks, src_id, src_seq, inline_json FROM sized ORDER BY seq LIMIT ?) AS fitting CROSS JOIN batch
2932
4603
  WHERE batch.chars <= ?
2933
4604
  UNION ALL
2934
- SELECT seq, chunks, inline_json, fetched, batch_chars, page_chars FROM (
2935
- SELECT seq, chunks, inline_json, batch.fetched, batch.chars AS batch_chars,
4605
+ SELECT seq, chunks, src_id, src_seq, inline_json, fetched, batch_chars, page_chars FROM (
4606
+ SELECT seq, chunks, src_id, src_seq, inline_json, batch.fetched, batch.chars AS batch_chars,
2936
4607
  row_number() OVER (ORDER BY seq) AS page_row,
2937
4608
  sum(size) OVER (ORDER BY seq) AS page_chars
2938
4609
  FROM sized CROSS JOIN batch WHERE batch.chars > ?
2939
4610
  ) AS windowed WHERE (page_chars <= ? OR page_row = 1) AND page_row <= ?
2940
4611
  ) SELECT seq, COALESCE(inline_json, (
2941
- SELECT e.entry_json FROM ${this.tables.entries} AS e WHERE e.session_id = ? AND e.seq = page.seq
2942
- )) AS entry_json, chunks, fetched, batch_chars, page_chars FROM page ORDER BY seq`, SESSION_READ_INLINE_BYTES, sessionId, after, ...params, limit + 1, limit, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, limit, sessionId);
4612
+ SELECT e.entry_json FROM ${this.tables.entries} AS e WHERE e.session_id = page.src_id AND e.seq = page.src_seq
4613
+ )) AS entry_json, chunks, fetched, batch_chars, page_chars FROM page ORDER BY seq`), ...forkViewParams([view]), SESSION_READ_INLINE_BYTES, after, ...seqs ?? [], limit + 1, limit, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, limit);
4614
+ const generation = await epoch;
4615
+ const note = generation === void 0 || !this.sharedHistorySeen ? void 0 : storedEntryNotes(this, sessionId, generation);
2943
4616
  for (const entry of rows) {
2944
4617
  const chunks = Number(entry.chunks);
2945
- const json = chunks === 0 ? entry.entry_json : await this.readEntryChunks(tx, sessionId, entry.seq, chunks);
4618
+ const seq = Number(entry.seq);
4619
+ const json = chunks === 0 ? entry.entry_json : await this.readEntryChunks(tx, tables, sessionId, seq, chunks);
4620
+ const parsed = JSON.parse(json);
4621
+ note?.(parsed, seq, json);
2946
4622
  entries.push({
2947
- seq: Number(entry.seq),
2948
- entry: JSON.parse(json)
4623
+ seq,
4624
+ entry: parsed
2949
4625
  });
2950
4626
  }
2951
4627
  const next = nextFetch(limit, rows);
@@ -2954,11 +4630,15 @@ var SqlSessionStore = class SqlSessionStore {
2954
4630
  limit = next.limit;
2955
4631
  }
2956
4632
  }
2957
- async readSeqs(tx, sessionId, seqs) {
4633
+ async readSeqs(tx, sessionId, seqs, epoch) {
2958
4634
  const entries = [];
2959
4635
  for (let start = 0; start < seqs.length; start += SEQ_BATCH) {
2960
4636
  const batch = seqs.slice(start, start + SEQ_BATCH);
2961
- entries.push(...await this.readRows(tx, sessionId, `seq IN (${batch.map(() => "?").join(", ")})`, batch));
4637
+ const range = {
4638
+ from: Math.min(...batch),
4639
+ through: Math.max(...batch)
4640
+ };
4641
+ entries.push(...await this.readRows(tx, sessionId, range, batch, epoch));
2962
4642
  }
2963
4643
  return entries;
2964
4644
  }
@@ -2968,14 +4648,36 @@ var SqlSessionStore = class SqlSessionStore {
2968
4648
  */
2969
4649
  resumeRow(sessionId) {
2970
4650
  return {
2971
- sql: `SELECT header_json,last_seq,summary_state,revision FROM ${this.tables.sessions} WHERE id = ?`,
4651
+ sql: `SELECT header_json,last_seq,summary_state,revision${this.forkedColumn(this.sharedHistorySeen ? this.forkTables.forkSegments : void 0)} FROM ${this.tables.sessions} WHERE id = ?`,
2972
4652
  params: [sessionId]
2973
4653
  };
2974
4654
  }
4655
+ /**
4656
+ * The view (#6560), as `name`, of session `sessionId`'s entries after seq `after` and through seq `through`, with
4657
+ * `entry_id`, `entry_json` and `chunks`, and where each is stored.
4658
+ */
4659
+ entriesView(tables, sessionId, after = 0, through = FORK_VIEW_END, name = "entries_view") {
4660
+ return {
4661
+ ...forkView(tables, {
4662
+ name,
4663
+ table: this.tables.entries,
4664
+ columns: [
4665
+ "entry_id",
4666
+ "entry_json",
4667
+ "chunks"
4668
+ ],
4669
+ sessionId,
4670
+ after,
4671
+ through
4672
+ }),
4673
+ name
4674
+ };
4675
+ }
2975
4676
  async resumeSource(tx, sessionId) {
2976
4677
  const read = this.resumeRow(sessionId);
2977
4678
  const row = await tx.get(read.sql, ...read.params);
2978
4679
  if (!row) throw new SessionNotFoundError$1(sessionId);
4680
+ this.noteForked(tx, sessionId, row.forked);
2979
4681
  const stored = windowIndex(JSON.parse(row.summary_state), Number(row.last_seq));
2980
4682
  const remembered = this.resumeIndexes.get(sessionId);
2981
4683
  const index = isSessionResumeIndex(stored, Number(row.last_seq)) ? stored : remembered?.revision === row.revision ? remembered.index : void 0;
@@ -3003,14 +4705,15 @@ var SqlSessionStore = class SqlSessionStore {
3003
4705
  }
3004
4706
  async prepareResume(sessionId, leafId, throughSeq) {
3005
4707
  attempts: for (let attempt = 0; attempt < 3; attempt++) {
3006
- const row = await this.database.get(`SELECT header_json,last_seq,summary_state,revision FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
4708
+ const row = await this.database.get(`SELECT header_json,last_seq,summary_state,revision${this.outsideForkedColumn("id")} FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
3007
4709
  if (!row) throw new SessionNotFoundError$1(sessionId);
4710
+ this.noteForked(void 0, sessionId, row.forked);
3008
4711
  const state = JSON.parse(row.summary_state);
3009
4712
  const remembered = this.resumeIndexes.get(sessionId);
3010
4713
  const currentIndex = windowIndex(state, Number(row.last_seq)) ?? (remembered?.revision === row.revision && isSessionResumeIndex(remembered.index, Number(row.last_seq)) ? remembered.index : void 0);
3011
4714
  const limit = throughSeq ?? Number(row.last_seq);
3012
4715
  if (limit > Number(row.last_seq)) throw new SessionConflictError$1(sessionId, limit, Number(row.last_seq));
3013
- const selected = leafId === void 0 ? void 0 : await this.seqOfEntry(this.database, sessionId, leafId) ?? 0;
4716
+ const selected = leafId === void 0 ? void 0 : await this.seqOfEntry(this.database, void 0, sessionId, leafId) ?? 0;
3014
4717
  const requested = selected !== void 0 && selected > limit ? 0 : selected;
3015
4718
  if (currentIndex && limit === currentIndex.seq && (requested === void 0 || requested === currentIndex.leafSeq)) return {
3016
4719
  index: currentIndex,
@@ -3139,12 +4842,18 @@ var SqlSessionStore = class SqlSessionStore {
3139
4842
  const lo = "(SELECT lo FROM bounds)";
3140
4843
  const hi = "(SELECT hi FROM bounds)";
3141
4844
  const pageWhere = sqlite ? `WHERE session_id = ${owner} AND seq > ${lo} AND seq <= ${hi}${sources}` : where;
4845
+ const viewed = this.outsideViewTables();
4846
+ const tables = Number(row.forked) === 0 ? {
4847
+ ...viewed,
4848
+ segments: void 0
4849
+ } : viewed;
4850
+ const shared = tables.segments !== void 0;
3142
4851
  const page = `WITH ${sqlite ? "bounds(id,lo,hi) AS NOT MATERIALIZED (VALUES (?,?,?)), " : ""}page AS (
3143
- SELECT ${sqlite ? "" : "CASE WHEN chunks > 0 THEN session_id END AS session_id,"}seq,entry_id,chunks,entry_json FROM ${this.tables.entries}
4852
+ SELECT ${sqlite && !shared ? "" : "CASE WHEN chunks > 0 THEN src_id END AS src_id,"}seq,src_seq,entry_id,chunks,entry_json FROM entries_view
3144
4853
  ${pageWhere} ORDER BY seq LIMIT ${SESSION_RESUME_REBUILD.pageEntries}
3145
4854
  )`;
3146
- const parts = (source) => `FROM ${this.tables.entryChunks} WHERE session_id = ${sqlite ? owner : `${source}.session_id`}
3147
- AND seq = ${source}.seq AND idx >= 0 AND idx < ${source}.chunks`;
4855
+ const parts = (source) => `FROM ${this.tables.entryChunks} WHERE session_id = ${sqlite && !shared ? owner : `${source}.src_id`}
4856
+ AND seq = ${source}.src_seq AND idx >= 0 AND idx < ${source}.chunks`;
3148
4857
  const projection = sqlite ? `SELECT seq,entry_id,chunks,${select} FROM payloads ORDER BY seq` : `SELECT seq,entry_id,chunks,${select} FROM payloads
3149
4858
  CROSS JOIN LATERAL (SELECT ${postgresJsonb("entry_json")} AS value OFFSET 0) AS parsed ORDER BY seq`;
3150
4859
  const fits = sqlite ? "length(zeroblob(sum(length(data)))) IS NOT NULL" : "sum(octet_length(data)) < 1073741824";
@@ -3159,7 +4868,7 @@ var SqlSessionStore = class SqlSessionStore {
3159
4868
  ) ${projection}`;
3160
4869
  const keysPerEntry = 64;
3161
4870
  const through = `${lo} + ${SESSION_RESUME_REBUILD.pageEntries}`;
3162
- const wide = sqlite && Number(row.last_seq) > 0 && Buffer.byteLength(sessionId) >= 512;
4871
+ const wide = sqlite && !shared && Number(row.last_seq) > 0 && Buffer.byteLength(sessionId) >= 512;
3163
4872
  let inlinePage = wide && this.chunkRowids === void 0 ? `${page}, chunked AS MATERIALIZED (SELECT 1 FROM page WHERE chunks > 0 LIMIT 1),
3164
4873
  payloads AS MATERIALIZED (SELECT seq,entry_id,chunks,entry_json FROM page WHERE NOT EXISTS (SELECT 1 FROM chunked)
3165
4874
  UNION ALL SELECT 0,'',0,'{}' FROM chunked) ${projection}` : void 0;
@@ -3186,14 +4895,16 @@ var SqlSessionStore = class SqlSessionStore {
3186
4895
  let topology = currentIndex && requested !== void 0 ? branchRanges(currentIndex, requested) : void 0;
3187
4896
  for (let pass = topology === void 0 ? 0 : 1; pass < 2; pass++) {
3188
4897
  for (let after = 0; after < limit;) {
4898
+ const view = this.entriesView(tables, sessionId, after, Math.min(limit, after + SESSION_RESUME_REBUILD.pageEntries));
3189
4899
  const args = [
4900
+ ...view.params,
3190
4901
  sessionId,
3191
4902
  after,
3192
4903
  limit
3193
4904
  ];
3194
4905
  let rows;
3195
4906
  try {
3196
- rows = await this.database.all(inlinePage ?? (this.chunkRowids ? rowidPage : directPage), ...args);
4907
+ rows = await this.database.all(withForkViews([view], inlinePage ?? (this.chunkRowids ? rowidPage : directPage)), ...args);
3197
4908
  if (inlinePage && Number(rows[0]?.seq) === 0) {
3198
4909
  inlinePage = void 0;
3199
4910
  try {
@@ -3204,12 +4915,15 @@ var SqlSessionStore = class SqlSessionStore {
3204
4915
  }
3205
4916
  } catch (error) {
3206
4917
  if (!(error instanceof Error && "code" in error && error.code === "payload-too-large")) throw error;
3207
- if (!await this.database.get(`SELECT 1 FROM ${this.tables.entryChunks}
3208
- WHERE session_id = ? AND seq IN (SELECT seq FROM ${this.tables.entries} ${where}
3209
- ORDER BY seq LIMIT ${SESSION_RESUME_REBUILD.pageEntries}) LIMIT 1`, sessionId, ...args).catch(() => void 0)) throw error;
3210
- rows = await this.database.all(stubPage, ...args);
4918
+ if (!await this.database.get(withForkViews([view], `SELECT 1 FROM (SELECT src_id, src_seq FROM ${view.name} ${where}
4919
+ ORDER BY seq LIMIT ${SESSION_RESUME_REBUILD.pageEntries}) AS p
4920
+ JOIN ${this.tables.entryChunks} c ON c.session_id = p.src_id AND c.seq = p.src_seq LIMIT 1`), ...view.params, sessionId, after, limit).catch(() => void 0)) throw error;
4921
+ rows = await this.database.all(withForkViews([view], stubPage), ...args);
4922
+ }
4923
+ if (rows.length === 0) {
4924
+ if (await this.schemaNowShared(viewed.segments !== void 0)) continue attempts;
4925
+ break;
3211
4926
  }
3212
- if (rows.length === 0) break;
3213
4927
  const batch = [];
3214
4928
  let toolCalls = 0;
3215
4929
  for (const entry of rows) {
@@ -3283,7 +4997,7 @@ var SqlSessionStore = class SqlSessionStore {
3283
4997
  const old = index ?? foldSessionResume(void 0, []);
3284
4998
  const seqs = /* @__PURE__ */ new Map();
3285
4999
  for (const id of foreignResumeIds(old, batch)) {
3286
- const seq = await this.seqOfEntry(this.database, sessionId, id);
5000
+ const seq = await this.seqOfEntry(this.database, void 0, sessionId, id);
3287
5001
  if (seq !== void 0) seqs.set(id, seq);
3288
5002
  }
3289
5003
  index = foldSessionResume(index, batch, (id) => seqs.get(id), (seq) => topology === void 0 || topology.some(([a, b]) => seq >= a && seq <= b));
@@ -3341,7 +5055,7 @@ var SqlSessionStore = class SqlSessionStore {
3341
5055
  const source = await this.resumeSource(tx, sessionId);
3342
5056
  const stateSeqs = stateSeqsBefore(source.index, start);
3343
5057
  if (hasHistoryLoadObserver()) announceHistoryLoad(stateSeqs.length + Math.max(0, source.index.seq - start + 1));
3344
- const [state, rows] = await Promise.all([this.readSeqs(tx, sessionId, stateSeqs), this.readRows(tx, sessionId, "seq >= ?", [start])]);
5058
+ const [state, rows] = await Promise.all([this.readSeqs(tx, sessionId, stateSeqs), this.readRows(tx, sessionId, { from: start })]);
3345
5059
  const entries = rows.map(({ entry }) => entry);
3346
5060
  return {
3347
5061
  tail: sessionTailFrom(source.index, source.header, start, state, entries),
@@ -3357,38 +5071,52 @@ var SqlSessionStore = class SqlSessionStore {
3357
5071
  return this.readTransaction(async (tx) => {
3358
5072
  const head = await this.historyHead(tx, sessionId, true);
3359
5073
  if (expectedEpoch !== void 0 && expectedEpoch !== head.epoch) throw new SessionConflictError$1(sessionId, endSeq, head.lastSeq);
3360
- const entries = endSeq < start ? [] : await this.readRows(tx, sessionId, "seq >= ? AND seq <= ?", [start, endSeq]);
5074
+ const entries = endSeq < start ? [] : await this.readRows(tx, sessionId, {
5075
+ from: start,
5076
+ through: endSeq
5077
+ }, void 0, head.epoch);
3361
5078
  return {
3362
5079
  startSeq: start,
3363
5080
  entries: entries.map(({ entry }) => entry),
3364
5081
  seqs: entries.map(({ seq }) => seq),
3365
- ...head
5082
+ lastSeq: head.lastSeq,
5083
+ epoch: head.epoch
3366
5084
  };
3367
5085
  });
3368
5086
  }
5087
+ /**
5088
+ * The session's watermark and generation; with `segments`, the fork segments table of a database with shared
5089
+ * history, also whether the session has segments (#6560), in the same statement: a read that leaves a session without
5090
+ * them to its tables' own keyed lookups costs no read of its own to learn it.
5091
+ */
3369
5092
  async historyHead(tx, sessionId, readOnly = false) {
3370
5093
  const generation = this.generation(sessionId);
3371
- const row = await tx.get(`SELECT last_seq, revision, ${generation.sql} AS epoch FROM ${this.tables.sessions} WHERE id = ?${readOnly ? "" : this.dialect.lockClause("share")}`, ...generation.params, sessionId);
5094
+ const { segments } = await this.viewTables(tx);
5095
+ const row = await tx.get(`SELECT last_seq, revision, ${generation.sql} AS epoch${this.forkedColumn(segments)} FROM ${this.tables.sessions} WHERE id = ?${readOnly ? "" : this.dialect.lockClause("share")}`, ...generation.params, sessionId);
3372
5096
  if (!row) throw new SessionNotFoundError$1(sessionId);
3373
5097
  this.noteGeneration(sessionId, row.revision, Number(row.last_seq), row.epoch);
5098
+ this.noteForked(tx, sessionId, row.forked);
3374
5099
  return {
3375
5100
  lastSeq: Number(row.last_seq),
3376
- epoch: row.epoch
5101
+ epoch: row.epoch,
5102
+ forked: Number(row.forked) === 1
3377
5103
  };
3378
5104
  }
3379
5105
  /** Size at most one page and return only fitting bodies, in the same snapshot as the header. The first
3380
5106
  * oversized row is a chunk reference; its full inline value never crosses the driver boundary. */
3381
5107
  async historyPacket(tx, sessionId, epoch, from, through, backward) {
3382
5108
  const edge = backward ? through : from;
3383
- const rows = await tx.all(`WITH sizes AS MATERIALIZED (
3384
- SELECT e.seq, e.chunks, CASE WHEN e.chunks = 0 THEN ${this.entryByteLength("e.entry_json")} ELSE (e.chunks - 1) * ? +
3385
- (SELECT length(c.data) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx = e.chunks - 1) END AS bytes
3386
- FROM ${this.tables.entries} e WHERE e.session_id = ? AND e.seq BETWEEN ? AND ?
5109
+ const tables = await this.viewTables(tx, sessionId);
5110
+ const view = this.entriesView(tables, sessionId, from - 1, through);
5111
+ const rows = await tx.all(withForkViews([view], `WITH sizes AS MATERIALIZED (
5112
+ SELECT e.seq, e.chunks, e.src_id, e.src_seq, CASE WHEN e.chunks = 0 THEN ${this.entryByteLength("e.entry_json")} ELSE (e.chunks - 1) * ? +
5113
+ (SELECT length(c.data) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.src_id AND c.seq = e.src_seq AND c.idx = e.chunks - 1) END AS bytes
5114
+ FROM ${view.name} e
3387
5115
  ), sized_page AS (
3388
- SELECT seq, chunks, bytes, sum(bytes) OVER (ORDER BY seq ${backward ? "DESC" : "ASC"}) AS cumulative FROM sizes
5116
+ SELECT seq, chunks, src_id, src_seq, bytes, sum(bytes) OVER (ORDER BY seq ${backward ? "DESC" : "ASC"}) AS cumulative FROM sizes
3389
5117
  ) SELECT p.seq, p.chunks, p.bytes, CASE WHEN p.chunks = 0 AND p.bytes <= ? THEN e.entry_json END AS body
3390
- FROM sized_page p JOIN ${this.tables.entries} e ON e.session_id = ? AND e.seq = p.seq
3391
- WHERE p.bytes IS NULL OR p.cumulative <= ? OR p.seq = ? ORDER BY p.seq`, SESSION_ENTRY_CHUNK_BYTES, sessionId, from, through, SESSION_HISTORY_PAGE_BYTES, sessionId, SESSION_HISTORY_PAGE_BYTES, edge);
5118
+ FROM sized_page p JOIN ${this.tables.entries} e ON e.session_id = p.src_id AND e.seq = p.src_seq
5119
+ WHERE p.bytes IS NULL OR p.cumulative <= ? OR p.seq = ? ORDER BY p.seq`), ...view.params, SESSION_ENTRY_CHUNK_BYTES, SESSION_HISTORY_PAGE_BYTES, SESSION_HISTORY_PAGE_BYTES, edge);
3392
5120
  const items = [];
3393
5121
  for (const row of rows) {
3394
5122
  const seq = Number(row.seq);
@@ -3403,7 +5131,7 @@ var SqlSessionStore = class SqlSessionStore {
3403
5131
  });
3404
5132
  else items.push({
3405
5133
  seq,
3406
- entry: JSON.parse(row.body ?? await this.readEntryChunks(tx, sessionId, seq, Number(row.chunks)))
5134
+ entry: JSON.parse(row.body ?? await this.readEntryChunks(tx, tables, sessionId, seq, Number(row.chunks)))
3407
5135
  });
3408
5136
  }
3409
5137
  return items;
@@ -3415,7 +5143,19 @@ var SqlSessionStore = class SqlSessionStore {
3415
5143
  return this.readTransaction(async (tx) => {
3416
5144
  const head = await this.historyHead(tx, sessionId, true);
3417
5145
  if (head.epoch !== index.epoch || head.lastSeq < index.seq) throw new SessionConflictError$1(sessionId, index.seq, head.lastSeq);
3418
- const row = await tx.get(`SELECT seq FROM ${this.tables.entries} WHERE session_id=? AND entry_id=? AND seq<=? ORDER BY seq DESC LIMIT 1`, sessionId, launch.launchLeafId, index.seq);
5146
+ const view = forkView(await this.viewTables(tx, sessionId), {
5147
+ name: "launched",
5148
+ table: this.tables.entries,
5149
+ columns: ["entry_id"],
5150
+ sessionId,
5151
+ after: 0,
5152
+ through: index.seq,
5153
+ match: {
5154
+ column: "entry_id",
5155
+ value: launch.launchLeafId
5156
+ }
5157
+ });
5158
+ const row = await tx.get(withForkViews([view], "SELECT seq FROM launched ORDER BY seq DESC LIMIT 1"), ...view.params);
3419
5159
  return childDisplayCut(index, launch, row === void 0 ? void 0 : Number(row.seq));
3420
5160
  });
3421
5161
  }
@@ -3467,12 +5207,13 @@ var SqlSessionStore = class SqlSessionStore {
3467
5207
  const trim = sqlite ? "trim" : "btrim";
3468
5208
  const hasText = sqlite ? `EXISTS(SELECT 1 FROM json_each(entry_json,'$.message.content') b WHERE CASE WHEN b.type='object' AND json_extract(b.value,'$.type')='text' THEN length(trim(json_extract(b.value,'$.text'),?))>0 END)` : `EXISTS(SELECT 1 FROM jsonb_array_elements((${content})::jsonb) b WHERE b->>'type'='text' AND length(btrim(b->>'text',?))>0)`;
3469
5209
  const callIds = sqlite ? `(SELECT json_group_array(json_extract(b.value,'$.id')) FROM json_each(entry_json,'$.message.content') b WHERE CASE WHEN b.type='object' THEN json_extract(b.value,'$.type')='toolCall' AND json_type(b.value,'$.id')='text' END)` : `(SELECT json_agg(b->>'id')::text FROM jsonb_array_elements((${content})::jsonb) b WHERE b->>'type'='toolCall' AND jsonb_typeof(b->'id')='string')`;
3470
- return (await tx.all(`SELECT CASE WHEN ${role}='assistant' AND ${ctype}='array' THEN ${callIds} END calls,seq,entry_id,chunks,${j("type")} kind,${j("parentId")} parent,${j("timestamp")} stamp,${role} role,
5210
+ const view = this.entriesView(await this.viewTables(tx, sessionId), sessionId, fromSeq - 1, toSeq);
5211
+ return (await tx.all(withForkViews([view], `SELECT CASE WHEN ${role}='assistant' AND ${ctype}='array' THEN ${callIds} END calls,seq,entry_id,chunks,${j("type")} kind,${j("parentId")} parent,${j("timestamp")} stamp,${role} role,
3471
5212
  CASE WHEN ${role}='assistant' AND COALESCE(${j("message", "stopReason")},'') IN ('','toolUse','stop') AND CASE WHEN ${ctype}='array' THEN NOT ${hasText} WHEN ${ctype}='${sqlite ? "text" : "string"}' THEN length(${trim}(${content},?))=0 ELSE TRUE END THEN 1 ELSE 0 END hidden,
3472
5213
  CASE WHEN ${j("type")}='custom' AND ${j("customType")}='atomic.leaf' THEN 1 ELSE 0 END leaf_move,
3473
5214
  CASE WHEN ${j("type")}='custom' AND ${j("customType")}='subagent-child' THEN 1 ELSE 0 END child_record,
3474
5215
  CASE WHEN ${j("type")}='label' THEN ${j("targetId")} END target,CASE WHEN ${j("type")}='label' THEN substr(${j("label")},1,128) END label
3475
- FROM ${this.tables.entries} WHERE session_id=? AND seq BETWEEN ? AND ? ORDER BY seq LIMIT ?`, whites, whites, sessionId, fromSeq, toSeq, 64)).map((row) => Number(row.chunks) > 0 ? {
5216
+ FROM ${view.name} WHERE session_id=? AND seq BETWEEN ? AND ? ORDER BY seq LIMIT ?`), ...view.params, whites, whites, sessionId, fromSeq, toSeq, 64)).map((row) => Number(row.chunks) > 0 ? {
3476
5217
  seq: Number(row.seq),
3477
5218
  streamed: true
3478
5219
  } : {
@@ -3502,8 +5243,9 @@ var SqlSessionStore = class SqlSessionStore {
3502
5243
  return this.readTransaction(async (tx) => {
3503
5244
  const head = await this.historyHead(tx, sessionId, true);
3504
5245
  if (head.epoch !== epoch || head.lastSeq < wanted.at(-1)) throw new SessionConflictError$1(sessionId, wanted.at(-1), head.lastSeq);
3505
- const tail = `(SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id=e.session_id AND c.seq=e.seq AND c.idx=e.chunks-1)`;
3506
- const rows = await tx.all(`SELECT seq,CASE WHEN chunks=0 THEN ${this.entryByteLength("entry_json")} ELSE (chunks-1)*?+${tail} END bytes FROM ${this.tables.entries} e WHERE session_id=? AND seq IN (${wanted.map(() => "?").join(",")}) ORDER BY seq`, SESSION_ENTRY_CHUNK_BYTES, sessionId, ...wanted);
5246
+ const tail = `(SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id=e.src_id AND c.seq=e.src_seq AND c.idx=e.chunks-1)`;
5247
+ const view = this.entriesView(await this.viewTables(tx, sessionId), sessionId, Math.min(...wanted) - 1, Math.max(...wanted));
5248
+ const rows = await tx.all(withForkViews([view], `SELECT seq,CASE WHEN chunks=0 THEN ${this.entryByteLength("entry_json")} ELSE (chunks-1)*?+${tail} END bytes FROM ${view.name} e WHERE session_id=? AND seq IN (${wanted.map(() => "?").join(",")}) ORDER BY seq`), ...view.params, SESSION_ENTRY_CHUNK_BYTES, sessionId, ...wanted);
3507
5249
  const sizes = new Map(rows.map((row) => [Number(row.seq), row.bytes == null ? void 0 : Number(row.bytes)]));
3508
5250
  const plan = selectedPagePlan(sessionId, wanted, head.lastSeq, (seq) => {
3509
5251
  const bytes = sizes.get(seq);
@@ -3539,10 +5281,14 @@ var SqlSessionStore = class SqlSessionStore {
3539
5281
  validateSessionText("sessionId", sessionId);
3540
5282
  return this.readTransaction(async (tx) => {
3541
5283
  const head = await this.historyHead(tx, sessionId, true);
3542
- const lastChunk = `(SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx = e.chunks - 1)`;
3543
- const rows = await tx.all(`SELECT seq, CASE WHEN chunks = 0 THEN ${this.entryByteLength("entry_json")} ELSE (chunks - 1) * ? + ${lastChunk} END AS bytes FROM ${this.tables.entries} e WHERE session_id = ? AND seq BETWEEN ? AND ? ORDER BY seq LIMIT ?`, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, endSeq, entrySizeLimit(limit));
5284
+ const lastChunk = `(SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.src_id AND c.seq = e.src_seq AND c.idx = e.chunks - 1)`;
5285
+ const tables = await this.viewTables(tx, sessionId);
5286
+ const after = Math.max(1, startSeq) - 1;
5287
+ const view = this.entriesView(tables, sessionId, after, tables.segments === void 0 ? endSeq : Math.min(endSeq, after + entrySizeLimit(limit)));
5288
+ const rows = await tx.all(withForkViews([view], `SELECT seq, CASE WHEN chunks = 0 THEN ${this.entryByteLength("entry_json")} ELSE (chunks - 1) * ? + ${lastChunk} END AS bytes FROM ${view.name} e WHERE session_id = ? AND seq BETWEEN ? AND ? ORDER BY seq LIMIT ?`), ...view.params, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, endSeq, entrySizeLimit(limit));
3544
5289
  return {
3545
- ...head,
5290
+ lastSeq: head.lastSeq,
5291
+ epoch: head.epoch,
3546
5292
  sizes: rows.map((row) => {
3547
5293
  if (row.bytes === null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing final chunk of session entry ${row.seq}`));
3548
5294
  return {
@@ -3567,29 +5313,39 @@ var SqlSessionStore = class SqlSessionStore {
3567
5313
  const { select, trailingReference, referencePrefix } = options;
3568
5314
  const generation = this.generation(sessionId);
3569
5315
  const count = entrySizeLimit(limit);
3570
- const bytes = (row) => `CASE WHEN ${row}.chunks = 0 THEN ${this.entryByteLength(`${row}.entry_json`)} ELSE (${row}.chunks - 1) * ? + (SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id = ${row}.session_id AND c.seq = ${row}.seq AND c.idx = ${row}.chunks - 1) END`;
5316
+ const shared = this.sharedHistorySeen;
5317
+ const plain = shared && this.forkedSessions.get(sessionId) === false;
5318
+ const tables = {
5319
+ segments: shared && !plain ? this.forkTables.forkSegments : void 0,
5320
+ dialect: this.dialect
5321
+ };
5322
+ const scanEnd = tables.segments === void 0 ? endSeq : Math.min(endSeq, Math.max(1, startSeq) - 1 + (select === void 0 ? count : SCAN_SELECT_WINDOW));
5323
+ const view = this.entriesView(tables, sessionId, startSeq - 1, scanEnd, "scan_view");
5324
+ const bytes = (row) => `CASE WHEN ${row}.chunks = 0 THEN ${this.entryByteLength(`${row}.entry_json`)} ELSE (${row}.chunks - 1) * ? + (SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id = ${row}.src_id AND c.seq = ${row}.src_seq AND c.idx = ${row}.chunks - 1) END`;
5325
+ const forked = this.outsideForkedColumn("id");
5326
+ const forkedNull = forked === "" ? "" : ", NULL";
3571
5327
  const head = `SELECT 0 AS seq, NULL AS bytes, NULL AS chunks, header_json AS entry_json, last_seq, revision,
3572
- ${generation.sql} AS epoch, (SELECT schema_version FROM ${this.tables.meta} LIMIT 1) AS schema_version`;
5328
+ ${generation.sql} AS epoch, (SELECT schema_version FROM ${this.tables.meta} LIMIT 1) AS schema_version${forked}`;
3573
5329
  const filter = (row) => select ? ` AND ${this.selected(row, select)}` : "";
3574
5330
  const selectParams = select === void 0 ? [] : this.selectedParams(select);
3575
5331
  const json = this.dialect.name === "sqlite" ? "CAST(entry_json AS BLOB)" : "convert_to(entry_json, 'UTF8')";
3576
5332
  const prefixLength = Math.max(1, Math.trunc(referencePrefix ?? 1) || 1);
3577
- const rows = !select && !trailingReference && referencePrefix === void 0 ? await this.database.all(`${head} FROM ${this.tables.sessions} WHERE id = ?
5333
+ const rows = !select && !trailingReference && referencePrefix === void 0 ? await this.database.all(withForkViews([view], `${head} FROM ${this.tables.sessions} WHERE id = ?
3578
5334
  UNION ALL
3579
- SELECT seq, bytes, chunks, CASE WHEN bytes <= ? AND chunks = 0 THEN entry_json END, NULL, NULL, NULL, NULL FROM (
3580
- SELECT e.seq, e.chunks, e.entry_json, ${bytes("e")} AS bytes FROM ${this.tables.entries} e
5335
+ SELECT seq, bytes, chunks, CASE WHEN bytes <= ? AND chunks = 0 THEN entry_json END, NULL, NULL, NULL, NULL${forkedNull} FROM (
5336
+ SELECT e.seq, e.chunks, e.entry_json, ${bytes("e")} AS bytes FROM ${view.name} e
3581
5337
  -- The cut bounds the range itself, so the read stops there, however far the range goes.
3582
5338
  WHERE e.session_id = ? AND e.seq BETWEEN ? AND (
3583
5339
  SELECT COALESCE(max(CASE WHEN total <= ? THEN seq END), min(seq)) FROM (
3584
5340
  SELECT seq, sum(bytes) OVER (ORDER BY seq) AS total FROM (
3585
- SELECT s.seq, ${bytes("s")} AS bytes FROM ${this.tables.entries} s
5341
+ SELECT s.seq, ${bytes("s")} AS bytes FROM ${view.name} s
3586
5342
  WHERE s.session_id = ? AND s.seq BETWEEN ? AND ? ORDER BY s.seq LIMIT ?
3587
5343
  ) AS sized
3588
5344
  ) AS run
3589
5345
  )
3590
5346
  ) AS page
3591
- ORDER BY seq`, ...generation.params, sessionId, SESSION_HISTORY_PAGE_BYTES, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, SESSION_HISTORY_PAGE_BYTES, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, endSeq, count) : await this.database.all(`WITH sized AS MATERIALIZED (
3592
- SELECT s.seq, ${bytes("s")} AS bytes FROM ${this.tables.entries} s
5347
+ ORDER BY seq`), ...view.params, ...generation.params, sessionId, SESSION_HISTORY_PAGE_BYTES, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, SESSION_HISTORY_PAGE_BYTES, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, scanEnd, count) : await this.database.all(withForkViews([view], `WITH sized AS MATERIALIZED (
5348
+ SELECT s.seq, ${bytes("s")} AS bytes FROM ${view.name} s
3593
5349
  WHERE s.session_id = ? AND s.seq BETWEEN ? AND ?${filter("s")} ORDER BY s.seq LIMIT ?
3594
5350
  ), cut AS (
3595
5351
  SELECT COALESCE(
@@ -3604,26 +5360,28 @@ var SqlSessionStore = class SqlSessionStore {
3604
5360
  ${head}, (SELECT count(*) FROM sized) AS sized, (SELECT max(seq) FROM sized) AS sized_last, NULL AS prefix
3605
5361
  FROM ${this.tables.sessions} WHERE id = ?
3606
5362
  UNION ALL
3607
- SELECT seq, bytes, chunks, CASE WHEN bytes <= ? AND chunks = 0 THEN entry_json END, NULL, NULL, NULL, NULL, NULL, NULL,
5363
+ SELECT seq, bytes, chunks, CASE WHEN bytes <= ? AND chunks = 0 THEN entry_json END, NULL, NULL, NULL, NULL${forkedNull}, NULL, NULL,
3608
5364
  ${referencePrefix === void 0 ? "NULL" : `CASE WHEN bytes > ? THEN CASE WHEN chunks > 0
3609
- THEN (SELECT substr(c.data, 1, CAST(? AS INTEGER)) FROM ${this.tables.entryChunks} c WHERE c.session_id = ? AND c.seq = page.seq AND c.idx = 0)
5365
+ THEN (SELECT substr(c.data, 1, CAST(? AS INTEGER)) FROM ${this.tables.entryChunks} c WHERE c.session_id = page.src_id AND c.seq = page.src_seq AND c.idx = 0)
3610
5366
  ELSE substr(${json}, 1, CAST(? AS INTEGER)) END END`}
3611
5367
  FROM (
3612
- SELECT e.seq, e.chunks, e.entry_json, ${bytes("e")} AS bytes FROM ${this.tables.entries} e
5368
+ SELECT e.seq, e.chunks, e.entry_json, e.src_id, e.src_seq, ${bytes("e")} AS bytes FROM ${view.name} e
3613
5369
  WHERE e.session_id = ? AND e.seq BETWEEN ? AND (SELECT seq FROM cut)${filter("e")}
3614
5370
  UNION ALL
3615
- SELECT e.seq, e.chunks, e.entry_json, ${bytes("e")} AS bytes FROM ${this.tables.entries} e
5371
+ SELECT e.seq, e.chunks, e.entry_json, e.src_id, e.src_seq, ${bytes("e")} AS bytes FROM ${view.name} e
3616
5372
  WHERE e.session_id = ? AND e.seq = (SELECT seq FROM tail)
3617
5373
  ) AS page
3618
- ORDER BY seq`, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, endSeq, ...selectParams, count, SESSION_HISTORY_PAGE_BYTES, SESSION_HISTORY_PAGE_BYTES, SESSION_HISTORY_PAGE_BYTES, ...generation.params, sessionId, SESSION_HISTORY_PAGE_BYTES, ...referencePrefix === void 0 ? [] : [
5374
+ ORDER BY seq`), ...view.params, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, scanEnd, ...selectParams, count, SESSION_HISTORY_PAGE_BYTES, SESSION_HISTORY_PAGE_BYTES, SESSION_HISTORY_PAGE_BYTES, ...generation.params, sessionId, SESSION_HISTORY_PAGE_BYTES, ...referencePrefix === void 0 ? [] : [
3619
5375
  SESSION_HISTORY_PAGE_BYTES,
3620
5376
  prefixLength,
3621
- sessionId,
3622
5377
  prefixLength
3623
5378
  ], SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, ...selectParams, SESSION_ENTRY_CHUNK_BYTES, sessionId);
3624
5379
  const first = rows[0];
3625
5380
  if (first === void 0 || Number(first.seq) !== 0) throw new SessionNotFoundError$1(sessionId);
3626
- assertStorageSchemaVersion("sessions", first.schema_version, 2, SESSION_SCHEMA_VERSION_UNCHUNKED);
5381
+ assertStorageSchemaVersion("sessions", first.schema_version, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
5382
+ this.noteSchemaVersion(first.schema_version);
5383
+ this.noteForked(void 0, sessionId, first.forked);
5384
+ if (this.sharedHistorySeen !== shared || plain && Number(first.forked) === 1) return SqlSessionStore.prototype.readScanPage.call(this, sessionId, startSeq, endSeq, epoch, limit, options);
3627
5385
  const lastSeq = Number(first.last_seq);
3628
5386
  this.noteGeneration(sessionId, first.revision, lastSeq, first.epoch);
3629
5387
  if (epoch !== void 0 && first.epoch !== epoch) throw new SessionConflictError$1(sessionId, endSeq, lastSeq);
@@ -3637,10 +5395,10 @@ var SqlSessionStore = class SqlSessionStore {
3637
5395
  const top = page.at(-1);
3638
5396
  if (top === void 0) return {
3639
5397
  ...read,
3640
- throughSeq: endSeq,
5398
+ throughSeq: scanEnd,
3641
5399
  items: []
3642
5400
  };
3643
- const throughSeq = first.sized !== void 0 && Number(first.sized) < count && Number(first.sized_last) <= Number(top.seq) ? endSeq : Number(top.seq);
5401
+ const throughSeq = first.sized !== void 0 && Number(first.sized) < count && Number(first.sized_last) <= Number(top.seq) ? scanEnd : Number(top.seq);
3644
5402
  const prefixes = /* @__PURE__ */ new Map();
3645
5403
  const reference = (row) => {
3646
5404
  if (row.prefix) prefixes.set(Number(row.seq), row.prefix);
@@ -3715,15 +5473,24 @@ var SqlSessionStore = class SqlSessionStore {
3715
5473
  const length = Math.min(Math.max(1, Math.trunc(bytes) || 1), SESSION_HISTORY_PAGE_BYTES);
3716
5474
  const generation = this.generation(sessionId);
3717
5475
  const json = this.dialect.name === "sqlite" ? "CAST(e.entry_json AS BLOB)" : "convert_to(e.entry_json, 'UTF8')";
3718
- const row = await this.database.get(`SELECT s.last_seq, s.revision, ${generation.sql} AS epoch,
5476
+ const shared = this.sharedHistorySeen;
5477
+ const plain = shared && this.forkedSessions.get(sessionId) === false;
5478
+ const view = this.entriesView({
5479
+ segments: shared && !plain ? this.forkTables.forkSegments : void 0,
5480
+ dialect: this.dialect
5481
+ }, sessionId, seq - 1, seq);
5482
+ const row = await this.database.get(withForkViews([view], `SELECT s.last_seq, s.revision, ${generation.sql} AS epoch,
3719
5483
  (SELECT schema_version FROM ${this.tables.meta} LIMIT 1) AS schema_version, e.chunks,
3720
5484
  CASE WHEN e.chunks > 0
3721
- THEN (SELECT substr(c.data, CAST(? AS INTEGER), CAST(? AS INTEGER)) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx = ?)
3722
- ELSE substr(${json}, CAST(? AS INTEGER), CAST(? AS INTEGER)) END AS data
3723
- FROM ${this.tables.sessions} s LEFT JOIN ${this.tables.entries} e ON e.session_id = s.id AND e.seq = ?
3724
- WHERE s.id = ?`, ...generation.params, offset % SESSION_ENTRY_CHUNK_BYTES + 1, length, Math.floor(offset / SESSION_ENTRY_CHUNK_BYTES), offset + 1, length, seq, sessionId);
5485
+ THEN (SELECT substr(c.data, CAST(? AS INTEGER), CAST(? AS INTEGER)) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.src_id AND c.seq = e.src_seq AND c.idx = ?)
5486
+ ELSE substr(${json}, CAST(? AS INTEGER), CAST(? AS INTEGER)) END AS data${this.outsideForkedColumn("s.id")}
5487
+ FROM ${this.tables.sessions} s LEFT JOIN ${view.name} e ON e.session_id = s.id
5488
+ WHERE s.id = ?`), ...view.params, ...generation.params, offset % SESSION_ENTRY_CHUNK_BYTES + 1, length, Math.floor(offset / SESSION_ENTRY_CHUNK_BYTES), offset + 1, length, sessionId);
3725
5489
  if (!row) throw new SessionNotFoundError$1(sessionId);
3726
- assertStorageSchemaVersion("sessions", row.schema_version, 2, SESSION_SCHEMA_VERSION_UNCHUNKED);
5490
+ assertStorageSchemaVersion("sessions", row.schema_version, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
5491
+ this.noteSchemaVersion(row.schema_version);
5492
+ this.noteForked(void 0, sessionId, row.forked);
5493
+ if (this.sharedHistorySeen !== shared || plain && Number(row.forked) === 1) return SqlSessionStore.prototype.readEntryChunk.call(this, reference, offset, bytes);
3727
5494
  this.noteGeneration(sessionId, row.revision, Number(row.last_seq), row.epoch);
3728
5495
  if (row.epoch !== epoch) throw new SessionConflictError$1(sessionId, seq, Number(row.last_seq));
3729
5496
  if (row.chunks === null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing session entry ${seq}`));
@@ -3735,7 +5502,7 @@ var SqlSessionStore = class SqlSessionStore {
3735
5502
  validateSessionText("sessionId", sessionId);
3736
5503
  validateSessionText("entry.id", entryId);
3737
5504
  if (!await this.readHeader(sessionId)) throw new SessionNotFoundError$1(sessionId);
3738
- return this.seqOfEntry(this.database, sessionId, entryId);
5505
+ return this.seqOfEntry(this.database, void 0, sessionId, entryId);
3739
5506
  }
3740
5507
  /**
3741
5508
  * Earlier entries that may save the same task reference as each candidate (#5593), in one statement on the session
@@ -3747,11 +5514,20 @@ var SqlSessionStore = class SqlSessionStore {
3747
5514
  validateSessionText("sessionId", sessionId);
3748
5515
  const { candidates, afterSeq, limit } = taskReferenceDuplicateQuery(query);
3749
5516
  return this.readTransaction(async (tx) => {
5517
+ const tables = await this.viewTables(tx, sessionId);
3750
5518
  const head = await this.historyHead(tx, sessionId, true);
3751
5519
  if (head.epoch !== query.epoch || head.lastSeq < query.throughSeq) throw new SessionConflictError$1(sessionId, query.throughSeq, head.lastSeq);
3752
5520
  if (candidates.length === 0) return { seqs: [] };
3753
5521
  const t = snapshotIndexTables$1(this.prefix);
3754
- const links = t.sessionLinks;
5522
+ const view = !head.forked ? void 0 : forkView(tables, {
5523
+ name: "links_view",
5524
+ table: t.sessionLinks,
5525
+ columns: ["entry_id"],
5526
+ sessionId,
5527
+ after: 0,
5528
+ through: query.throughSeq
5529
+ });
5530
+ const links = view === void 0 ? t.sessionLinks : "links_view";
3755
5531
  /**
3756
5532
  * For each candidate `c`, the links row `s` at its sequence and then, with `earlier`, the rows `e` before it
3757
5533
  * under an ID, each found through an index, never by walking the session. Postgres plans a lateral subquery
@@ -3776,11 +5552,11 @@ var SqlSessionStore = class SqlSessionStore {
3776
5552
  WHEN c.suffix > 0 AND c.suffix <= length(s.entry_id) AND substr(s.entry_id, length(s.entry_id) - c.suffix + 1, 1) = ':'
3777
5553
  THEN substr(s.entry_id, 1, length(s.entry_id) - c.suffix) END`;
3778
5554
  const values = candidates.map(() => `(CAST(? AS ${this.dialect.types.int}), CAST(? AS INTEGER), CAST(? AS INTEGER))`);
3779
- const rows = await tx.all(`WITH c(seq, idx, suffix) AS (VALUES ${values.join(", ")}),
5555
+ const rows = await tx.all(withForkViews(view === void 0 ? [] : [view], `WITH c(seq, idx, suffix) AS (VALUES ${values.join(", ")}),
3780
5556
  hits AS (SELECT e.seq AS seq FROM ${rowsOf("s.entry_id")} UNION SELECT e.seq FROM ${rowsOf(other)})
3781
5557
  SELECT 0 AS kind, (SELECT CASE WHEN backfilled_through >= watermark THEN 1 ELSE 0 END FROM ${t.sources} WHERE source = 'session-entries') AS seq
3782
5558
  UNION ALL SELECT 1, count(*) FROM ${rowsOf()}
3783
- UNION ALL SELECT 2, page.seq FROM (SELECT seq FROM hits ORDER BY seq LIMIT ?) page`, ...candidates.flat(), ...[
5559
+ UNION ALL SELECT 2, page.seq FROM (SELECT seq FROM hits ORDER BY seq LIMIT ?) page`), ...view?.params ?? [], ...candidates.flat(), ...[
3784
5560
  sessionId,
3785
5561
  sessionId,
3786
5562
  afterSeq,
@@ -3811,10 +5587,34 @@ var SqlSessionStore = class SqlSessionStore {
3811
5587
  const { indexedForkWindow, forkMetadata, byteMetadata, locateFork } = await import("../core/storage/session/fork-window.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
3812
5588
  return this.readTransaction(async (tx) => {
3813
5589
  const snapshots = snapshotIndexTables$1(this.prefix);
3814
- const row = await tx.get(`SELECT header_json,last_seq,summary_state,revision,CASE WHEN EXISTS (SELECT 1 FROM ${snapshots.sources} WHERE source='session-entries' AND backfilled_through>=watermark) THEN (SELECT max(seq) FROM ${snapshots.sessionLinks} WHERE session_id=s.id AND entry_id=?) ELSE (SELECT max(seq) FROM ${this.tables.entries} WHERE session_id=s.id AND entry_id=?) END AS leaf_seq FROM ${this.tables.sessions} s WHERE s.id=?`, entryId, entryId, sessionId);
5590
+ const shared = await this.viewTables(tx);
5591
+ const headRead = (leafTables) => {
5592
+ const leafViews = [snapshots.sessionLinks, this.tables.entries].map((table, index) => forkView(leafTables, {
5593
+ name: `leaf_${index}`,
5594
+ table,
5595
+ columns: ["entry_id"],
5596
+ sessionId,
5597
+ after: 0,
5598
+ through: FORK_VIEW_END,
5599
+ match: {
5600
+ column: "entry_id",
5601
+ value: entryId
5602
+ }
5603
+ }));
5604
+ return tx.get(withForkViews(leafViews, `SELECT header_json,last_seq,summary_state,revision,CASE WHEN EXISTS (SELECT 1 FROM ${snapshots.sources} WHERE source='session-entries' AND backfilled_through>=watermark) THEN (SELECT max(seq) FROM leaf_0) ELSE (SELECT max(seq) FROM leaf_1) END AS leaf_seq${this.forkedColumn(shared.segments, "s.id")} FROM ${this.tables.sessions} s WHERE s.id=?`), ...forkViewParams(leafViews), sessionId);
5605
+ };
5606
+ const guessPlain = shared.segments !== void 0 && this.forkedSessions.get(sessionId) === false;
5607
+ let row = await headRead(guessPlain ? {
5608
+ ...shared,
5609
+ segments: void 0
5610
+ } : shared);
5611
+ if (row && guessPlain && Number(row.forked) === 1) row = await headRead(shared);
5612
+ if (row) this.noteForked(tx, sessionId, row.forked);
5613
+ const tables = await this.viewTables(tx, sessionId);
3815
5614
  if (!row) throw new SessionNotFoundError$1(sessionId);
3816
5615
  const header = JSON.parse(row.header_json);
3817
5616
  const state = JSON.parse(row.summary_state);
5617
+ const generation = state.epoch ?? row.revision;
3818
5618
  const count = Number(row.last_seq);
3819
5619
  const cached = this.resumeIndexes.get(sessionId);
3820
5620
  const ready = windowIndex(state, count) ?? (cached?.revision === row.revision ? cached.index : void 0);
@@ -3825,23 +5625,31 @@ var SqlSessionStore = class SqlSessionStore {
3825
5625
  if (!seqs.length) return result;
3826
5626
  const raw = this.dialect.name === "sqlite" ? "CAST(entry_json AS BLOB)" : "convert_to(entry_json,'UTF8')";
3827
5627
  const size = this.dialect.textByteLength("entry_json");
3828
- const rows = await tx.all(`SELECT seq,chunks,${size} AS bytes,CASE WHEN chunks=0 AND ${size}<=512 THEN entry_json END AS body FROM ${this.tables.entries} WHERE session_id=? AND seq IN (${seqs.map(() => "?").join(",")}) ORDER BY seq`, sessionId, ...seqs);
5628
+ const view = this.entriesView(tables, sessionId, Math.min(...seqs) - 1, Math.max(...seqs));
5629
+ const rows = await tx.all(withForkViews([view], `SELECT seq,chunks,${size} AS bytes,CASE WHEN chunks=0 AND ${size}<=512 THEN entry_json END AS body FROM ${view.name} WHERE session_id=? AND seq IN (${seqs.map(() => "?").join(",")}) ORDER BY seq`), ...view.params, sessionId, ...seqs);
3829
5630
  for (const row of rows) {
3830
5631
  const seq = Number(row.seq);
3831
5632
  if (row.body !== null) result.push(forkMetadata(seq, JSON.parse(row.body)));
3832
5633
  else if (Number(row.chunks) > 0) {
3833
5634
  const { projectForkMetadata } = await import("../core/storage/session/chunked-resume-projection.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
3834
- result.push(await projectForkMetadata(seq, this.forkEntryChunks(tx, sessionId, seq, Number(row.chunks))));
5635
+ result.push(await projectForkMetadata(seq, this.forkEntryChunks(tx, tables, sessionId, seq, Number(row.chunks))));
3835
5636
  } else result.push(await byteMetadata(seq, Number(row.bytes), async (offset, n) => {
3836
- const piece = await tx.get(`SELECT substr(${raw},?,?) AS part FROM ${this.tables.entries} WHERE session_id=? AND seq=?`, offset + 1, n, sessionId, seq);
5637
+ const one = this.entriesView(tables, sessionId, seq - 1, seq);
5638
+ const piece = await tx.get(withForkViews([one], `SELECT substr(${raw},?,?) AS part FROM ${one.name}`), ...one.params, offset + 1, n);
3837
5639
  if (!piece) throw new StorageError(`Session ${sessionId} entry ${seq} disappeared during its fork`);
3838
5640
  return piece.part;
3839
5641
  }));
3840
5642
  }
3841
5643
  return result;
3842
5644
  };
3843
- const entries = this.tables.entries;
3844
5645
  const j = (field) => this.dialect.jsonText("entry_json", field);
5646
+ const scanWindow = (from, through) => {
5647
+ const end = tables.segments === void 0 ? through : Math.min(through, from - 1 + SCAN_SELECT_WINDOW);
5648
+ return {
5649
+ end,
5650
+ view: this.entriesView(tables, sessionId, from - 1, end)
5651
+ };
5652
+ };
3845
5653
  const selected = ready ? {
3846
5654
  index: ready,
3847
5655
  leaf,
@@ -3849,7 +5657,7 @@ var SqlSessionStore = class SqlSessionStore {
3849
5657
  } : await locateFork({
3850
5658
  ...foldSessionResume(void 0, []),
3851
5659
  seq: count,
3852
- epoch: state.epoch ?? row.revision,
5660
+ epoch: generation,
3853
5661
  needsBranchRebuild: true
3854
5662
  }, entryId, async (seqs) => {
3855
5663
  const pg = this.dialect.name === "postgres";
@@ -3871,7 +5679,8 @@ var SqlSessionStore = class SqlSessionStore {
3871
5679
  } : { column: "entry_json" }, "data", "completionId")} THEN ${key("data", "completionId")} END`,
3872
5680
  key("message", "role")
3873
5681
  ]);
3874
- const parsed = (await tx.all(`WITH projected AS MATERIALIZED (SELECT seq,chunks,CAST(${projection} AS TEXT) AS link FROM ${entries} ${pg ? `CROSS JOIN LATERAL (SELECT ${postgresJsonb("entry_json")} AS value OFFSET 0) AS parsed` : ""} WHERE session_id=? AND seq BETWEEN ? AND ?) SELECT seq,chunks,CASE WHEN ${this.dialect.textByteLength("link")}<=512 THEN link END AS link FROM projected ORDER BY seq`, sessionId, seqs[0], seqs.at(-1))).map((r) => ({
5682
+ const view = this.entriesView(tables, sessionId, seqs[0] - 1, seqs.at(-1));
5683
+ const parsed = (await tx.all(withForkViews([view], `WITH projected AS MATERIALIZED (SELECT seq,chunks,CAST(${projection} AS TEXT) AS link FROM ${view.name} ${pg ? `CROSS JOIN LATERAL (SELECT ${postgresJsonb("entry_json")} AS value OFFSET 0) AS parsed` : ""} WHERE session_id=? AND seq BETWEEN ? AND ?) SELECT seq,chunks,CASE WHEN ${this.dialect.textByteLength("link")}<=512 THEN link END AS link FROM projected ORDER BY seq`), ...view.params, sessionId, seqs[0], seqs.at(-1))).map((r) => ({
3875
5684
  seq: Number(r.seq),
3876
5685
  chunked: Number(r.chunks) > 0,
3877
5686
  link: r.link === null ? void 0 : JSON.parse(r.link)
@@ -3882,7 +5691,8 @@ var SqlSessionStore = class SqlSessionStore {
3882
5691
  const { messageRoleIn } = await import("../core/storage/session/chunked-resume-projection.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
3883
5692
  for (let i = 0; i < chunkedMessages.length; i += SEQ_BATCH) {
3884
5693
  const batch = chunkedMessages.slice(i, i + SEQ_BATCH);
3885
- const prefixes = await tx.all(`SELECT seq,substr(data,1,${FORK_ROLE_PREFIX_BYTES}) AS prefix FROM ${this.tables.entryChunks} WHERE session_id=? AND idx=0 AND seq IN (${batch.map(() => "?").join(",")})`, sessionId, ...batch);
5694
+ const view = this.entriesView(tables, sessionId, Math.min(...batch) - 1, Math.max(...batch));
5695
+ const prefixes = await tx.all(withForkViews([view], `SELECT v.seq,substr(c.data,1,${FORK_ROLE_PREFIX_BYTES}) AS prefix FROM ${view.name} v JOIN ${this.tables.entryChunks} c ON c.session_id=v.src_id AND c.seq=v.src_seq AND c.idx=0 WHERE v.seq IN (${batch.map(() => "?").join(",")})`), ...view.params, ...batch);
3886
5696
  for (const row of prefixes) roles.set(Number(row.seq), messageRoleIn(row.prefix));
3887
5697
  }
3888
5698
  }
@@ -3910,14 +5720,18 @@ var SqlSessionStore = class SqlSessionStore {
3910
5720
  return page;
3911
5721
  }, true, SESSION_READ_FETCH.max);
3912
5722
  const labelBody = `CASE WHEN chunks=0 AND ${this.dialect.textByteLength("entry_json")}<=512 THEN entry_json END`;
3913
- return indexedForkWindow(header, selected.index, selected.leaf, (lo, hi) => this.readRows(tx, sessionId, "seq BETWEEN ? AND ?", [lo, hi]), (seqs) => this.readSeqs(tx, sessionId, seqs), metadata, async function* (ranges, kinds, types = []) {
5723
+ return indexedForkWindow(header, selected.index, selected.leaf, (lo, hi) => this.readRows(tx, sessionId, {
5724
+ from: lo,
5725
+ through: hi
5726
+ }, void 0, generation), (seqs) => this.readSeqs(tx, sessionId, seqs, generation), metadata, async function* (ranges, kinds, types = []) {
3914
5727
  const filters = [];
3915
5728
  if (types.length) filters.push(`${j("type")} IN (${types.map(() => "?").join(",")})`);
3916
5729
  if (kinds.length) filters.push(`(${j("type")}='custom' AND (chunks>0 OR ${j("customType")} IN (${kinds.map(() => "?").join(",")})))`);
3917
5730
  for (const [lo, hi] of ranges) for (let seq = lo; seq <= hi;) {
3918
5731
  const labels = types.length === 1 && types[0] === "label";
3919
5732
  const limit = labels ? SESSION_READ_FETCH.first : SESSION_READ_FETCH.max;
3920
- const rows = await tx.all(`SELECT seq,${j("type")} AS kind${labels ? `,${labelBody} AS body` : ""} FROM ${entries} WHERE session_id=? AND seq BETWEEN ? AND ? AND (${filters.join(" OR ")}) ORDER BY seq LIMIT ${limit}`, sessionId, seq, hi, ...types, ...kinds);
5733
+ const { end, view } = scanWindow(seq, hi);
5734
+ const rows = await tx.all(withForkViews([view], `SELECT seq,${j("type")} AS kind${labels ? `,${labelBody} AS body` : ""} FROM ${view.name} WHERE session_id=? AND seq BETWEEN ? AND ? AND (${filters.join(" OR ")}) ORDER BY seq LIMIT ${limit}`), ...view.params, sessionId, seq, end, ...types, ...kinds);
3921
5735
  const deferred = rows.filter((r) => r.kind === "custom" || r.kind === "label" && !r.body).map((r) => Number(r.seq));
3922
5736
  const projected = /* @__PURE__ */ new Map();
3923
5737
  for (let i = 0; i < deferred.length; i += SEQ_BATCH) for (const m of await metadata(deferred.slice(i, i + SEQ_BATCH))) projected.set(m.seq, m);
@@ -3925,8 +5739,10 @@ var SqlSessionStore = class SqlSessionStore {
3925
5739
  type: row.kind,
3926
5740
  seq: Number(row.seq)
3927
5741
  });
3928
- if (rows.length < limit) break;
3929
- seq = Number(rows.at(-1).seq) + 1;
5742
+ if (rows.length < limit) {
5743
+ if (end >= hi) break;
5744
+ seq = end + 1;
5745
+ } else seq = Number(rows.at(-1).seq) + 1;
3930
5746
  }
3931
5747
  }, {
3932
5748
  ...selected.extras,
@@ -3934,9 +5750,10 @@ var SqlSessionStore = class SqlSessionStore {
3934
5750
  });
3935
5751
  });
3936
5752
  }
3937
- async *forkEntryChunks(tx, id, seq, count) {
5753
+ async *forkEntryChunks(tx, tables, id, seq, count) {
3938
5754
  for (let i = 0; i < count; i++) {
3939
- const row = await tx.get(`SELECT data FROM ${this.tables.entryChunks} WHERE session_id=? AND seq=? AND idx=?`, id, seq, i);
5755
+ const read = this.entryChunkRead(tables, id, seq, i);
5756
+ const row = await tx.get(read.sql, ...read.params);
3940
5757
  if (!row) throw new StorageError(`Session ${id} entry ${seq} is missing chunk ${i} of ${count}`);
3941
5758
  yield row.data;
3942
5759
  }
@@ -3966,8 +5783,10 @@ var SqlSessionStore = class SqlSessionStore {
3966
5783
  for (let attempt = 0; attempt < 3; attempt++) {
3967
5784
  const { index, revision } = await this.prepareResume(sessionId, leafId, throughSeq);
3968
5785
  const resume = await this.readTransaction(async (tx) => {
3969
- const head = await tx.get(`SELECT header_json,revision FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
5786
+ const { segments } = await this.viewTables(tx);
5787
+ const head = await tx.get(`SELECT header_json,revision${this.forkedColumn(segments)} FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
3970
5788
  if (!head) throw new SessionNotFoundError$1(sessionId);
5789
+ this.noteForked(tx, sessionId, head.forked);
3971
5790
  if (revision !== head.revision) return void 0;
3972
5791
  return this.resumeIn(tx, sessionId, JSON.parse(head.header_json), index, options);
3973
5792
  });
@@ -3981,9 +5800,12 @@ var SqlSessionStore = class SqlSessionStore {
3981
5800
  const plan = sessionResumePlan(index, index.leafSeq, options?.deferChildRecords);
3982
5801
  announceHistoryLoad(plan.state.length + plan.branch.reduce((sum, [a, b]) => sum + b - a + 1, 0));
3983
5802
  const [ranges, state, leaf] = await Promise.all([
3984
- Promise.all(plan.branch.map(([start, end]) => this.readRows(tx, sessionId, "seq >= ? AND seq <= ?", [start, end]))),
3985
- this.readSeqs(tx, sessionId, plan.state),
3986
- leafSeq <= 0 ? void 0 : tx.get(`SELECT entry_id FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, leafSeq)
5803
+ Promise.all(plan.branch.map(([start, end]) => this.readRows(tx, sessionId, {
5804
+ from: start,
5805
+ through: end
5806
+ }, void 0, index.epoch))),
5807
+ this.readSeqs(tx, sessionId, plan.state, index.epoch),
5808
+ leafSeq <= 0 ? void 0 : this.entryIdAt(tx, sessionId, leafSeq)
3987
5809
  ]);
3988
5810
  const branch = ranges.flat();
3989
5811
  const resume = sessionResumeFrom(index, header, branch, state, leaf?.entry_id ?? null, plan.children);
@@ -3997,13 +5819,13 @@ var SqlSessionStore = class SqlSessionStore {
3997
5819
  const { point } = await this.withResumeIndex(sessionId, () => this.readTransaction(async (tx) => {
3998
5820
  const source = await this.resumeSource(tx, sessionId);
3999
5821
  const { index } = source;
4000
- const leafSeq = leafId === void 0 ? index.leafSeq : await this.seqOfEntry(tx, sessionId, leafId) ?? -1;
5822
+ const leafSeq = leafId === void 0 ? index.leafSeq : await this.seqOfEntry(tx, await this.viewTables(tx, sessionId), sessionId, leafId) ?? -1;
4001
5823
  const found = latestCompactionOf(index, leafSeq);
4002
5824
  if (found === void 0) return {
4003
5825
  point: void 0,
4004
5826
  source
4005
5827
  };
4006
- const [[boundary], leaf] = await Promise.all([this.readSeqs(tx, sessionId, [found.seq]), tx.get(`SELECT entry_id FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, leafSeq)]);
5828
+ const [[boundary], leaf] = await Promise.all([this.readSeqs(tx, sessionId, [found.seq]), this.entryIdAt(tx, sessionId, leafSeq)]);
4007
5829
  if (boundary === void 0 || leaf === void 0) return {
4008
5830
  point: void 0,
4009
5831
  source
@@ -4020,15 +5842,44 @@ var SqlSessionStore = class SqlSessionStore {
4020
5842
  }, [this.resumeRow(sessionId)]));
4021
5843
  return point;
4022
5844
  }
5845
+ /** The ID of the entry at view seq `seq` of session `sessionId`, read in transaction `tx` (#6560). */
5846
+ async entryIdAt(tx, sessionId, seq) {
5847
+ const view = this.entriesView(await this.viewTables(tx, sessionId), sessionId, seq - 1, seq);
5848
+ return tx.get(withForkViews([view], `SELECT entry_id FROM ${view.name}`), ...view.params);
5849
+ }
4023
5850
  /** The JSON of a long entry, from its chunks, one statement each. */
4024
- async readEntryChunks(tx, sessionId, seq, count) {
4025
- return Buffer.concat(await this.readRawEntryChunks(tx, sessionId, seq, count)).toString("utf8");
5851
+ async readEntryChunks(tx, tables, sessionId, seq, count) {
5852
+ return Buffer.concat(await this.readRawEntryChunks(tx, tables, sessionId, seq, count)).toString("utf8");
5853
+ }
5854
+ /**
5855
+ * The read of chunk `index` of the entry at view seq `seq` of session `sessionId` (#6560), found through the view in
5856
+ * the statement itself, on the condition `condition` with `params` when given.
5857
+ */
5858
+ entryChunkRead(tables, sessionId, seq, index, condition) {
5859
+ const view = this.entriesView(tables, sessionId, seq - 1, seq);
5860
+ return {
5861
+ sql: withForkViews([view], `SELECT c.data FROM ${view.name} v JOIN ${this.tables.entryChunks} c
5862
+ ON c.session_id = v.src_id AND c.seq = v.src_seq AND c.idx = ?${condition === void 0 ? "" : ` WHERE ${condition.sql}`}`),
5863
+ params: [
5864
+ ...view.params,
5865
+ index,
5866
+ ...condition?.params ?? []
5867
+ ]
5868
+ };
4026
5869
  }
4027
- async readRawEntryChunks(tx, sessionId, seq, count, signal) {
5870
+ /**
5871
+ * The chunks of the entry at view seq `seq`: in transaction `tx` with `tables`, or, with `tables` undefined, each
5872
+ * read outside a transaction through `outsideTransaction`.
5873
+ */
5874
+ async readRawEntryChunks(tx, tables, sessionId, seq, count, signal) {
4028
5875
  const chunks = [];
4029
5876
  for (let index = 0; index < count; index++) {
4030
5877
  signal?.throwIfAborted();
4031
- const chunk = await tx.get(`SELECT data FROM ${this.tables.entryChunks} WHERE session_id = ? AND seq = ? AND idx = ?`, sessionId, seq, index);
5878
+ const read = (viewTables) => {
5879
+ const statement = this.entryChunkRead(viewTables, sessionId, seq, index);
5880
+ return tx.get(statement.sql, ...statement.params);
5881
+ };
5882
+ const chunk = tables === void 0 ? await this.outsideTransaction(read, (row) => row !== void 0) : await read(tables);
4032
5883
  if (chunk === void 0) throw new StorageError(`Session ${sessionId} entry ${seq} is missing chunk ${index} of ${count}`);
4033
5884
  chunks.push(chunk.data);
4034
5885
  if (signal !== void 0 && index + 1 < count) await yieldTurn();
@@ -4037,23 +5888,30 @@ var SqlSessionStore = class SqlSessionStore {
4037
5888
  }
4038
5889
  async *entryChunks(sessionId, seq, count, revision) {
4039
5890
  for (let index = 0; index < count; index++) {
4040
- const chunk = await this.database.get(`SELECT data FROM ${this.tables.entryChunks} WHERE session_id = ? AND seq = ? AND idx = ?
4041
- AND EXISTS (SELECT 1 FROM ${this.tables.sessions} WHERE id = ? AND revision = ?)`, sessionId, seq, index, sessionId, revision);
5891
+ const chunk = await this.outsideTransaction((tables) => {
5892
+ const statement = this.entryChunkRead(tables, sessionId, seq, index, {
5893
+ sql: `EXISTS (SELECT 1 FROM ${this.tables.sessions} WHERE id = ? AND revision = ?)`,
5894
+ params: [sessionId, revision]
5895
+ });
5896
+ return this.database.get(statement.sql, ...statement.params);
5897
+ }, (row) => row !== void 0);
4042
5898
  if (chunk === void 0) throw new StorageError(`Session ${sessionId} entry ${seq} is missing chunk ${index} of ${count}`);
4043
5899
  yield chunk.data;
4044
5900
  if (index + 1 < count) await yieldTurn();
4045
5901
  }
4046
5902
  }
5903
+ /** The JSON bytes of the entry stored whole at view seq `seq`, read outside a transaction. */
4047
5904
  async readInlineEntryBytes(sessionId, seq) {
4048
- if (this.dialect.name === "sqlite") {
4049
- const row = await this.database.get(`SELECT CAST(entry_json AS BLOB) AS data FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, seq);
4050
- return row ? [row.data] : [];
4051
- }
4052
- const row = await this.database.get(`SELECT entry_json FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, seq);
4053
- return row ? [new TextEncoder().encode(row.entry_json)] : [];
4054
- }
4055
- async forWrite(tx, sessionId, options, includeSummaryState = false) {
4056
- const read = this.headRead(sessionId, options, includeSummaryState);
5905
+ const sqlite = this.dialect.name === "sqlite";
5906
+ const row = await this.outsideTransaction((tables) => {
5907
+ const view = this.entriesView(tables, sessionId, seq - 1, seq);
5908
+ return this.database.get(withForkViews([view], `SELECT ${sqlite ? "CAST(entry_json AS BLOB)" : "entry_json"} AS data FROM ${view.name}`), ...view.params);
5909
+ }, (found) => found !== void 0);
5910
+ if (row === void 0) return [];
5911
+ return [typeof row.data === "string" ? new TextEncoder().encode(row.data) : row.data];
5912
+ }
5913
+ async forWrite(tx, sessionId, options, includeSummaryState = false, forked = false) {
5914
+ const read = this.headRead(sessionId, options, includeSummaryState, forked);
4057
5915
  const row = await tx.get(read.sql, ...read.params);
4058
5916
  if (!row) throw new SessionNotFoundError$1(sessionId);
4059
5917
  const state = row.summary_state === void 0 ? void 0 : JSON.parse(String(row.summary_state));
@@ -4063,32 +5921,56 @@ var SqlSessionStore = class SqlSessionStore {
4063
5921
  state
4064
5922
  };
4065
5923
  }
4066
- /** The read of the session's row that `forWrite` checks a write against. */
4067
- headRead(sessionId, options, includeSummaryState) {
5924
+ /**
5925
+ * The read of the session's row that `forWrite` checks a write against; with `forked`, once this store has seen
5926
+ * shared history, it also reads whether the session has fork segments (#6560).
5927
+ */
5928
+ headRead(sessionId, options, includeSummaryState, forked = false) {
4068
5929
  return {
4069
- sql: `SELECT header_json, last_seq${includeSummaryState || options.epoch !== void 0 ? ", summary_state" : ""}
5930
+ sql: `SELECT header_json, last_seq${includeSummaryState || options.epoch !== void 0 ? ", summary_state" : ""}${forked ? this.outsideForkedColumn("id") : ""}
4070
5931
  FROM ${this.tables.sessions} WHERE id = ?`,
4071
5932
  params: [sessionId]
4072
5933
  };
4073
5934
  }
5935
+ /** Whether session `sessionId` has fork segments, read in `tx`, whose database has shared history (#6560). */
5936
+ async hasForkSegments(tx, sessionId) {
5937
+ return await tx.get(`SELECT 1 AS found FROM ${this.forkTables.forkSegments} WHERE session_id = ? LIMIT 1`, sessionId) !== void 0;
5938
+ }
4074
5939
  async appendedResume(tx, sessionId, previous, lastSeq, entries) {
4075
5940
  if (!isSessionResumeIndex(previous, lastSeq)) return void 0;
4076
5941
  const seqs = /* @__PURE__ */ new Map();
4077
5942
  for (const id of foreignResumeIds(previous, entries)) {
4078
- const seq = await this.seqOfEntry(tx, sessionId, id);
5943
+ const seq = await this.seqOfEntry(tx, await this.viewTables(tx), sessionId, id);
4079
5944
  if (seq !== void 0) seqs.set(id, seq);
4080
5945
  }
4081
5946
  return foldSessionResume(previous, entries, (id) => seqs.get(id));
4082
5947
  }
4083
- async seqOfEntry(executor, sessionId, entryId) {
4084
- const tables = snapshotIndexTables$1(this.prefix);
4085
- const source = await executor.get(`SELECT CASE WHEN backfilled_through >= watermark THEN 1 ELSE 0 END AS complete FROM ${tables.sources} WHERE source = 'session-entries'`);
4086
- if (Number(source?.complete) === 1) {
4087
- const linked = await executor.get(`SELECT seq FROM ${tables.sessionLinks} WHERE session_id = ? AND entry_id = ? ORDER BY seq DESC LIMIT 1`, sessionId, entryId);
4088
- return linked === void 0 ? void 0 : Number(linked.seq);
4089
- }
4090
- const row = await executor.get(`SELECT seq FROM ${this.tables.entries} WHERE session_id = ? AND entry_id = ? ORDER BY seq DESC LIMIT 1`, sessionId, entryId);
4091
- return row === void 0 ? void 0 : Number(row.seq);
5948
+ /**
5949
+ * The latest seq of session `sessionId` that holds entry `entryId`, through its view (#6560): in transaction
5950
+ * `executor` with `tables`, or, with `tables` undefined, outside a transaction through `outsideTransaction`. A fork's
5951
+ * inherited entries are linked under the sessions that store them, at their seqs there, which the view renumbers.
5952
+ */
5953
+ async seqOfEntry(executor, tables, sessionId, entryId) {
5954
+ const index = snapshotIndexTables$1(this.prefix);
5955
+ const source = await executor.get(`SELECT CASE WHEN backfilled_through >= watermark THEN 1 ELSE 0 END AS complete FROM ${index.sources} WHERE source = 'session-entries'`);
5956
+ const table = Number(source?.complete) === 1 ? index.sessionLinks : this.tables.entries;
5957
+ const read = (viewTables, forked = "") => {
5958
+ const view = forkView(viewTables, {
5959
+ name: "linked",
5960
+ table,
5961
+ columns: ["entry_id"],
5962
+ sessionId,
5963
+ after: 0,
5964
+ through: FORK_VIEW_END,
5965
+ match: {
5966
+ column: "entry_id",
5967
+ value: entryId
5968
+ }
5969
+ });
5970
+ return executor.get(withForkViews([view], `SELECT (SELECT seq FROM linked ORDER BY seq DESC LIMIT 1) AS seq${forked}`), ...view.params, ...forked === "" ? [] : [sessionId]);
5971
+ };
5972
+ const row = tables === void 0 ? await this.outsideSessionRead(sessionId, (viewTables) => read(viewTables, this.outsideForkedColumn("?")), (found) => found?.seq != null, (found) => found?.forked) : await read(tables);
5973
+ return row?.seq == null ? void 0 : Number(row.seq);
4092
5974
  }
4093
5975
  async saveSummary(tx, sessionId, snapshot, previous, appendedResume) {
4094
5976
  const { statement, texts, epoch } = this.summaryWrite(sessionId, snapshot, previous, appendedResume);
@@ -4110,6 +5992,12 @@ var SqlSessionStore = class SqlSessionStore {
4110
5992
  epoch
4111
5993
  };
4112
5994
  const summary = materializeSessionSummaryMetadata(header, state);
5995
+ const row = {
5996
+ header_json: this.encode(header),
5997
+ summary_state: this.encode(state),
5998
+ revision: newRevision(),
5999
+ last_seq: lastSeq
6000
+ };
4113
6001
  return {
4114
6002
  statement: {
4115
6003
  sql: `INSERT INTO ${this.tables.sessions}
@@ -4127,7 +6015,7 @@ var SqlSessionStore = class SqlSessionStore {
4127
6015
  sessionId,
4128
6016
  header.cwd,
4129
6017
  header.createdAt,
4130
- this.encode(header),
6018
+ row.header_json,
4131
6019
  header.internal ? 1 : 0,
4132
6020
  lastSeq,
4133
6021
  summary.modifiedAt,
@@ -4137,17 +6025,28 @@ var SqlSessionStore = class SqlSessionStore {
4137
6025
  summary.hasName ? 1 : 0,
4138
6026
  summary.summary === void 0 ? null : this.encode(summary.summary),
4139
6027
  summary.summarizedThroughId ?? null,
4140
- this.encode(state),
4141
- newRevision()
6028
+ row.summary_state,
6029
+ row.revision
4142
6030
  ]
4143
6031
  },
4144
6032
  texts,
4145
- epoch
6033
+ epoch,
6034
+ row
4146
6035
  };
4147
6036
  }
4148
- async insertEntries(tx, sessionId, entries, lastSeq, texts, versionStep = true) {
6037
+ async insertEntries(tx, sessionId, entries, lastSeq, texts, versionStep = true, written) {
4149
6038
  const writes = new SentWrites(tx);
4150
- await writes.around(() => writes.send(this.entryWrites(sessionId, entries, lastSeq, texts, versionStep)));
6039
+ await writes.around(() => writes.send(this.entryWrites(sessionId, entries, lastSeq, texts, versionStep, written)));
6040
+ }
6041
+ /**
6042
+ * Notes `written`, the entries a committed write of session `sessionId` stored in generation `epoch`, as stored there
6043
+ * (#6560): a manager keeps the very objects it appended, so a fork of it shares their rows without reading them back.
6044
+ * Only where this store has seen shared history, for which alone the notes count.
6045
+ */
6046
+ noteWritten(sessionId, epoch, written) {
6047
+ if (!this.sharedHistorySeen) return;
6048
+ const note = storedEntryNotes(this, sessionId, epoch);
6049
+ for (const { entry, seq, json } of written) note(entry, seq, json);
4151
6050
  }
4152
6051
  /**
4153
6052
  * A fork's version step, once every entry of the child is in, as the transaction's last write: the same row order as
@@ -4155,7 +6054,12 @@ var SqlSessionStore = class SqlSessionStore {
4155
6054
  * so the two never deadlock (#6560). The body makes no call after it.
4156
6055
  */
4157
6056
  async finishFork(tx, child) {
4158
- const step = {
6057
+ const step = this.forkVersionStep(child);
6058
+ if (transactionFinisher(tx)?.([step]) !== true) await tx.run(step.sql, ...step.params);
6059
+ }
6060
+ /** The statement of {@link finishFork}. */
6061
+ forkVersionStep(child) {
6062
+ return {
4159
6063
  sql: `UPDATE ${this.tables.meta} SET schema_version = ? WHERE schema_version = ? AND EXISTS (SELECT 1 FROM ${this.tables.entries} WHERE session_id = ? AND chunks > 0)`,
4160
6064
  params: [
4161
6065
  2,
@@ -4163,21 +6067,40 @@ var SqlSessionStore = class SqlSessionStore {
4163
6067
  child
4164
6068
  ]
4165
6069
  };
4166
- if (transactionFinisher(tx)?.([step]) !== true) await tx.run(step.sql, ...step.params);
4167
6070
  }
4168
6071
  /**
4169
6072
  * The statements that store `entries` after `lastSeq`, in order, each entry encoded only when its statements are
4170
- * taken: each entry's row and its chunks, the version step a first chunked entry takes unless `versionStep` is
4171
- * false (a fork takes it once its last entry is in), then the entries' search texts.
6073
+ * taken: the entries' rows, several to a statement (see {@link rowInserts}), each chunked entry's own row and its
6074
+ * chunks in their place among them, the version step a first chunked entry takes unless `versionStep` is false (a
6075
+ * fork takes it once its last entry is in), then the entries' search texts. With `written`, each entry is added to it
6076
+ * with its seq and its JSON as it is encoded, for {@link noteWritten} once the write commits.
4172
6077
  */
4173
- *entryWrites(sessionId, entries, lastSeq, texts, versionStep = true) {
6078
+ *entryWrites(sessionId, entries, lastSeq, texts, versionStep = true, written) {
4174
6079
  let chunked = false;
6080
+ const rows = new RowInserts(this.tables.entries, ENTRY_COLUMNS);
4175
6081
  for (const [index, entry] of entries.entries()) {
4176
6082
  const seq = lastSeq + index + 1;
4177
- const stored = storedEntry(entry, this.encode(entry));
4178
- chunked ||= stored.chunks.length > 0;
6083
+ const json = this.encode(entry);
6084
+ written?.push({
6085
+ entry,
6086
+ seq,
6087
+ json
6088
+ });
6089
+ const stored = storedEntry(entry, json);
6090
+ if (stored.chunks.length === 0) {
6091
+ yield* rows.add([
6092
+ sessionId,
6093
+ seq,
6094
+ entry.id,
6095
+ stored.json,
6096
+ 0
6097
+ ]);
6098
+ continue;
6099
+ }
6100
+ chunked = true;
6101
+ yield* rows.drain();
4179
6102
  yield {
4180
- sql: `INSERT INTO ${this.tables.entries} (session_id, seq, entry_id, entry_json, chunks) VALUES (?, ?, ?, ?, ?)`,
6103
+ sql: rows.sql(1),
4181
6104
  params: [
4182
6105
  sessionId,
4183
6106
  seq,
@@ -4186,7 +6109,7 @@ var SqlSessionStore = class SqlSessionStore {
4186
6109
  stored.chunks.length
4187
6110
  ]
4188
6111
  };
4189
- if (stored.chunks.length > 0) yield {
6112
+ yield {
4190
6113
  sql: `DELETE FROM ${this.tables.entryChunks} WHERE session_id = ? AND seq = ?`,
4191
6114
  params: [sessionId, seq]
4192
6115
  };
@@ -4200,40 +6123,53 @@ var SqlSessionStore = class SqlSessionStore {
4200
6123
  ]
4201
6124
  };
4202
6125
  }
6126
+ yield* rows.drain();
4203
6127
  if (chunked && versionStep) yield {
4204
6128
  sql: `UPDATE ${this.tables.meta} SET schema_version = ? WHERE schema_version = ?`,
4205
6129
  params: [2, SESSION_SCHEMA_VERSION_UNCHUNKED]
4206
6130
  };
4207
- for (const { index, text } of texts) yield {
4208
- sql: `INSERT INTO ${this.tables.searchTexts} (session_id, seq, text_json) VALUES (?, ?, ?)`,
4209
- params: [
4210
- sessionId,
4211
- lastSeq + index + 1,
4212
- this.encode(text)
4213
- ]
4214
- };
6131
+ const searchTexts = new RowInserts(this.tables.searchTexts, TEXT_COLUMNS);
6132
+ for (const { index, text } of texts) yield* searchTexts.add([
6133
+ sessionId,
6134
+ lastSeq + index + 1,
6135
+ this.encode(text)
6136
+ ]);
6137
+ yield* searchTexts.drain();
4215
6138
  }
4216
6139
  /**
4217
- * Runs the session row's statement, then `entries`' statements, in order. A write of up to
4218
- * {@link STATEMENT_BATCH_BYTES}, as an ordinary message is, goes to a connection thread as one batch that waits for
4219
- * it once. A larger one runs its statements one at a time as they are made, as before, so it never holds more than
4220
- * about that much of them, or sends it, at once.
6140
+ * Runs the session row's statement, then `entries`' statements, in order, as the transaction's last calls: the body
6141
+ * makes none after them. A write of up to {@link STATEMENT_BATCH_BYTES}, as an ordinary message is, goes with the
6142
+ * commit where the connection is pipelined, or to a connection thread as one batch that waits for it once, or a
6143
+ * request's worth at a time when it has more statements than one takes. A larger one is sent as it is made, without
6144
+ * waiting for each statement's answer, so it never holds more than about that much of them, or sends it, at once.
4221
6145
  */
4222
- /** Writes the session's row and its entries as the transaction's last calls: the body makes none after them. */
4223
6146
  async writeEntries(tx, summary, entries) {
4224
6147
  const batch = [summary];
4225
6148
  let bytes = statementBytes(summary);
4226
6149
  const pending = entries[Symbol.iterator]();
6150
+ let whole = true;
4227
6151
  for (let next = pending.next(); next.done !== true; next = pending.next()) {
4228
6152
  batch.push(next.value);
4229
6153
  bytes += statementBytes(next.value);
4230
- if (bytes <= STATEMENT_BATCH_BYTES) continue;
4231
- for (const { sql, params } of batch) await tx.run(sql, ...params);
4232
- for (let rest = pending.next(); rest.done !== true; rest = pending.next()) await tx.run(rest.value.sql, ...rest.value.params);
6154
+ if (bytes > STATEMENT_BATCH_BYTES) {
6155
+ whole = false;
6156
+ break;
6157
+ }
6158
+ }
6159
+ if (whole) {
6160
+ if (transactionFinisher(tx)?.(batch) === true) return;
6161
+ if (batch.length <= MAX_SEQUENCE_REQUEST_STATEMENTS) {
6162
+ await statementBatch(tx, batch, []);
6163
+ return;
6164
+ }
6165
+ }
6166
+ const runSequence = whole ? sequenceRunner(tx) : void 0;
6167
+ if (runSequence !== void 0) {
6168
+ await runSequence({ statements: batch });
4233
6169
  return;
4234
6170
  }
4235
- if (transactionFinisher(tx)?.(batch) === true) return;
4236
- await statementBatch(tx, batch, []);
6171
+ const writes = new SentWrites(tx);
6172
+ await writes.around(() => writes.send(whole ? batch : withRest(batch, pending)));
4237
6173
  }
4238
6174
  encode(value) {
4239
6175
  try {
@@ -4244,14 +6180,21 @@ var SqlSessionStore = class SqlSessionStore {
4244
6180
  }
4245
6181
  };
4246
6182
  const nativeLoad = registerArchiveLoad(SqlSessionStore.prototype.load);
6183
+ /** The markers among `markers` whose processes `live` judges to be running. */
6184
+ async function liveMarkers(markers, live) {
6185
+ const running = [];
6186
+ for (const marker of markers) if (await live(marker)) running.push(marker);
6187
+ return running;
6188
+ }
4247
6189
  /** The running sessions that have a SQL store's sessions open, in a table every host sharing the store reads (#4971). */
4248
6190
  var SqlSessionOpenMarkers = class {
6191
+ /** A new table already has the columns the later steps add, so on a new database they find them and alter nothing. */
4249
6192
  static async createTable(tx, dialect, table) {
4250
6193
  const { int, text } = dialect.types;
4251
6194
  await tx.exec(`
4252
6195
  CREATE TABLE IF NOT EXISTS ${table} (
4253
6196
  session_id ${text} NOT NULL, token ${text} NOT NULL, pid ${int} NOT NULL, host ${text} NOT NULL,
4254
- heartbeat_at ${int} NOT NULL, PRIMARY KEY(session_id, token)
6197
+ heartbeat_at ${int} NOT NULL, schema_version ${int}, build ${text}, PRIMARY KEY(session_id, token)
4255
6198
  )${dialect.tableOptions};
4256
6199
  `);
4257
6200
  }
@@ -4264,6 +6207,14 @@ var SqlSessionOpenMarkers = class {
4264
6207
  const probe = dialect.columnExists(table, "schema_version");
4265
6208
  if (await tx.get(probe.sql, ...probe.params) === void 0) await tx.exec(`ALTER TABLE ${table} ADD COLUMN schema_version ${dialect.types.int}`);
4266
6209
  }
6210
+ /**
6211
+ * Each marker records the Atomic version of its process, so a command refused while older processes run names the
6212
+ * version each must be upgraded from (#6560). Null for markers of builds before it. Additive.
6213
+ */
6214
+ static async addBuild(tx, dialect, table) {
6215
+ const probe = dialect.columnExists(table, "build");
6216
+ if (await tx.get(probe.sql, ...probe.params) === void 0) await tx.exec(`ALTER TABLE ${table} ADD COLUMN build ${dialect.types.text}`);
6217
+ }
4267
6218
  database;
4268
6219
  table;
4269
6220
  assertOpen;
@@ -4275,9 +6226,26 @@ var SqlSessionOpenMarkers = class {
4275
6226
  async put(sessionId, marker) {
4276
6227
  this.assertOpen();
4277
6228
  const now = dialectOf(this.database).nowMs;
4278
- await this.database.run(`INSERT INTO ${this.table} (session_id, token, pid, host, heartbeat_at, schema_version) VALUES (?, ?, ?, ?, ${now}, ?)
6229
+ await this.database.run(`INSERT INTO ${this.table} (session_id, token, pid, host, heartbeat_at, schema_version, build) VALUES (?, ?, ?, ?, ${now}, ?, ?)
4279
6230
  ON CONFLICT(session_id, token) DO UPDATE SET pid = excluded.pid, host = excluded.host,
4280
- heartbeat_at = excluded.heartbeat_at, schema_version = excluded.schema_version`, sessionId, marker.token, marker.pid, marker.host, 2);
6231
+ heartbeat_at = excluded.heartbeat_at, schema_version = excluded.schema_version, build = excluded.build`, sessionId, marker.token, marker.pid, marker.host, 3, marker.build ?? null);
6232
+ }
6233
+ /**
6234
+ * The markers, through `tx`, of processes that do not read sessions schema `version`: those that record an older
6235
+ * one, and those of builds that record none.
6236
+ */
6237
+ async olderThan(tx, version) {
6238
+ const now = dialectOf(this.database).nowMs;
6239
+ return (await tx.all(`SELECT session_id, token, pid, host, ${now} - heartbeat_at AS age_ms, schema_version, build FROM ${this.table}
6240
+ WHERE schema_version IS NULL OR schema_version < ? ORDER BY host, pid, session_id`, version)).map((row) => ({
6241
+ sessionId: row.session_id,
6242
+ token: row.token,
6243
+ pid: Number(row.pid),
6244
+ host: row.host,
6245
+ ageMs: Number(row.age_ms),
6246
+ schemaVersion: row.schema_version === null ? void 0 : Number(row.schema_version),
6247
+ build: row.build ?? void 0
6248
+ }));
4281
6249
  }
4282
6250
  async remove(sessionId, token) {
4283
6251
  this.assertOpen();
@@ -10801,16 +12769,16 @@ var ThemeSelectorComponent = class extends FramedSelector {
10801
12769
  * update without an ESM missing-export error.
10802
12770
  */
10803
12771
  const COMPACTOR_COMPRESSION_RATIO = .5;
10804
- export { CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL, COMPACTOR_COMPRESSION_RATIO, ClassifierDecisionError, GITHUB_COPILOT_ERROR_DIAGNOSTIC, GitHubCopilotAuthenticationError, GitHubCopilotContentFilterError, GitHubCopilotEmptyResponseError, GitHubCopilotError, GitHubCopilotInvalidRequestError, GitHubCopilotModelUnavailableError, GitHubCopilotPromptTooLargeError, GitHubCopilotQuotaExhaustedError, GitHubCopilotRateLimitError, GitHubCopilotServiceUnavailableError, GitHubCopilotStreamEndedEarlyError, GitHubCopilotUnrecognizedResponseError, IntercomBrokerError, IntercomBrokerProtocolError, IntercomBrokerStopTimeoutError, IntercomBrokerSuccessorTimeoutError, IntercomBrokerUpgradeError, IntercomRoutingChangedError, IntercomRoutingError, IntercomRoutingMismatchError, IntercomRoutingTimeoutError, IntercomRoutingUnavailableError, LISTING_FETCH_BATCH, MAX_SESSION_START_TIMEOUT_MS, McpOAuthAuthorizationRequiredError, McpOAuthCredentialStore, McpSignInCancelledError, MemorySnapshotBlobStore, ModelRegistry, OAuthRefreshRejectedError, OAuthTemporarilyUnavailableError, OutputRepairExhaustedError, ProjectGroupError, ProviderRequestFailure, RUNTIME_INTERCOM_GROUP_ENV, SESSION_BLOB_CHUNK_BYTES, SESSION_DOMAIN, SESSION_ENTRY_CHUNK_BYTES, SESSION_FILLFACTOR_DOMAIN, SESSION_PRESENCE_DOMAIN, SESSION_PRESENCE_TABLES, SESSION_READ_FETCH, SESSION_READ_PAGE_CHARS, SESSION_RESUME_REBUILD, SESSION_SCHEMA_VERSION, SESSION_TABLES, SNAPSHOT_COLLECTION_BATCH, SessionConflictError, SessionExistsError, SessionFormatVersionError, SessionIdMismatchError, SessionInvalidTextError, SessionInvalidTimestampError, SessionNotFoundError, SessionStartConfigError, SessionStartError, SessionStartTimeoutError, ShowImagesSelectorComponent, SqlSessionStore, SqlSnapshotBlobStore, TerminalDecisionError, ThemeSelectorComponent, addMcpServerConfigAsync, announceBlueprintBuildWaits, clampThinkingLevel, classifyGitHubCopilotFailure, configuredSecretRedactor, createGatewayBindingFetch, createMcpAuthProvider, createMcpExtension, createTranscript, decide, decisionFailure, describeGitHubCopilotModel, deserializeGitHubCopilotError, findGitHubCopilotError, findSessionStartError, generateStructuredOutput, getGitHubCopilotError, getMcpToolExposure, getSupportedThinkingLevels, githubChecks, githubReviews, interval, isGitHubCopilotAuthenticationError, isGitHubCopilotContentFilterError, isGitHubCopilotEmptyResponseError, isGitHubCopilotError, isGitHubCopilotInvalidRequestError, isGitHubCopilotModelUnavailableError, isGitHubCopilotPromptTooLargeError, isGitHubCopilotQuotaExhaustedError, isGitHubCopilotRateLimitError, isGitHubCopilotServiceUnavailableError, isGitHubCopilotStreamEndedEarlyError, isGitHubCopilotUnrecognizedResponseError, isIntercomBrokerError, isIntercomBrokerProtocolError, isIntercomBrokerStopTimeoutError, isIntercomBrokerSuccessorTimeoutError, isIntercomBrokerUpgradeError, isIntercomRoutingChangedError, isIntercomRoutingError, isIntercomRoutingMismatchError, isIntercomRoutingTimeoutError, isIntercomRoutingUnavailableError, isOAuthRefreshRejectedError, isProjectGroupError, isRetryableGitHubCopilotError, isRetryableIntercomBrokerError, isRetryableIntercomRoutingError, isRetryableSessionStartError, isSessionStartConfigError, isSessionStartError, isSessionStartTimeoutError, loadMcpConfigAsync, logTail, mcpNamespace, mcpRequestTimeoutMs, parseFlattenedKeyPath, parseSessionStartTimeoutMs, publishExtensionContextEffect, publishPullRequest, readRuntimeIntercomGroup, reconstructFlattenedKeys, registerExtensionContextRetirementEffect, rehydrateIntercomBrokerError, rehydrateSessionStartError, removeMcpServerConfigAsync, resolveAutoModel, resolveDecisionModel, resolveMcpServerUrl, restoreRunWorktree, runDecision, runPrintMode, runRestorePreconditionError, runtimeIntercomGroupEnvKey, serializeGitHubCopilotError, serializeIntercomBrokerError, serializeSessionStartError, sessionScopedExtensionState, sessionStartStepText, setUpRestoredRunWorktrees, setUpResumedRunWorktrees, signInMcpServer, snapshotBlobHashes, snapshotIndexTables, unflattenArgumentsWithSchema, updateMcpServerConfig, updateMcpServerConfigAsync, validateMcpServerConfig, webhook, workspaceChangeSet, writeBlueprintBuildEvent };
12772
+ export { CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL, COMPACTOR_COMPRESSION_RATIO, ClassifierDecisionError, GITHUB_COPILOT_ERROR_DIAGNOSTIC, GitHubCopilotAuthenticationError, GitHubCopilotContentFilterError, GitHubCopilotEmptyResponseError, GitHubCopilotError, GitHubCopilotInvalidRequestError, GitHubCopilotModelUnavailableError, GitHubCopilotPromptTooLargeError, GitHubCopilotQuotaExhaustedError, GitHubCopilotRateLimitError, GitHubCopilotServiceUnavailableError, GitHubCopilotStreamEndedEarlyError, GitHubCopilotUnrecognizedResponseError, IntercomBrokerError, IntercomBrokerProtocolError, IntercomBrokerStopTimeoutError, IntercomBrokerSuccessorTimeoutError, IntercomBrokerUpgradeError, IntercomRoutingChangedError, IntercomRoutingError, IntercomRoutingMismatchError, IntercomRoutingTimeoutError, IntercomRoutingUnavailableError, LISTING_FETCH_BATCH, MAX_SESSION_START_TIMEOUT_MS, McpOAuthAuthorizationRequiredError, McpOAuthCredentialStore, McpSignInCancelledError, MemorySnapshotBlobStore, ModelRegistry, OAuthRefreshRejectedError, OAuthTemporarilyUnavailableError, OutputRepairExhaustedError, ProjectGroupError, ProviderRequestFailure, RUNTIME_INTERCOM_GROUP_ENV, SESSION_APPEND_FUNCTION_DOMAIN, SESSION_BLOB_CHUNK_BYTES, SESSION_DOMAIN, SESSION_ENTRY_CHUNK_BYTES, SESSION_FILLFACTOR_DOMAIN, SESSION_PRESENCE_DOMAIN, SESSION_PRESENCE_TABLES, SESSION_READ_FETCH, SESSION_READ_PAGE_CHARS, SESSION_RESUME_REBUILD, SESSION_SCHEMA_VERSION, SESSION_SCHEMA_VERSION_CHUNKED, SESSION_SCHEMA_VERSION_SHARED_HISTORY, SESSION_TABLES, SNAPSHOT_COLLECTION_BATCH, SessionConflictError, SessionExistsError, SessionFormatVersionError, SessionIdMismatchError, SessionInvalidTextError, SessionInvalidTimestampError, SessionNotFoundError, SessionStartConfigError, SessionStartError, SessionStartTimeoutError, ShowImagesSelectorComponent, SqlSessionStore, SqlSnapshotBlobStore, TerminalDecisionError, ThemeSelectorComponent, addMcpServerConfigAsync, announceBlueprintBuildWaits, clampThinkingLevel, classifyGitHubCopilotFailure, configuredSecretRedactor, createGatewayBindingFetch, createMcpAuthProvider, createMcpExtension, createTranscript, decide, decisionFailure, describeGitHubCopilotModel, deserializeGitHubCopilotError, findGitHubCopilotError, findSessionStartError, generateStructuredOutput, getGitHubCopilotError, getMcpToolExposure, getSupportedThinkingLevels, githubChecks, githubReviews, interval, isGitHubCopilotAuthenticationError, isGitHubCopilotContentFilterError, isGitHubCopilotEmptyResponseError, isGitHubCopilotError, isGitHubCopilotInvalidRequestError, isGitHubCopilotModelUnavailableError, isGitHubCopilotPromptTooLargeError, isGitHubCopilotQuotaExhaustedError, isGitHubCopilotRateLimitError, isGitHubCopilotServiceUnavailableError, isGitHubCopilotStreamEndedEarlyError, isGitHubCopilotUnrecognizedResponseError, isIntercomBrokerError, isIntercomBrokerProtocolError, isIntercomBrokerStopTimeoutError, isIntercomBrokerSuccessorTimeoutError, isIntercomBrokerUpgradeError, isIntercomRoutingChangedError, isIntercomRoutingError, isIntercomRoutingMismatchError, isIntercomRoutingTimeoutError, isIntercomRoutingUnavailableError, isOAuthRefreshRejectedError, isProjectGroupError, isRetryableGitHubCopilotError, isRetryableIntercomBrokerError, isRetryableIntercomRoutingError, isRetryableSessionStartError, isSessionStartConfigError, isSessionStartError, isSessionStartTimeoutError, loadMcpConfigAsync, logTail, mcpNamespace, mcpRequestTimeoutMs, parseFlattenedKeyPath, parseSessionStartTimeoutMs, publishExtensionContextEffect, publishPullRequest, readRuntimeIntercomGroup, reconstructFlattenedKeys, registerExtensionContextRetirementEffect, rehydrateIntercomBrokerError, rehydrateSessionStartError, removeMcpServerConfigAsync, resolveAutoModel, resolveDecisionModel, resolveMcpServerUrl, restoreRunWorktree, runDecision, runPrintMode, runRestorePreconditionError, runtimeIntercomGroupEnvKey, serializeGitHubCopilotError, serializeIntercomBrokerError, serializeSessionStartError, sessionScopedExtensionState, sessionStartStepText, setUpRestoredRunWorktrees, setUpResumedRunWorktrees, signInMcpServer, snapshotBlobHashes, snapshotIndexTables, unflattenArgumentsWithSchema, updateMcpServerConfig, updateMcpServerConfigAsync, validateMcpServerConfig, webhook, workspaceChangeSet, writeBlueprintBuildEvent };
10805
12773
 
10806
- //# sourceMappingURL=sdk-AVFII7NK.js.map
12774
+ //# sourceMappingURL=sdk-IQMULKFU.js.map
10807
12775
  // __atomicOnDemandFailed: written by the build (scripts/in-place-update-gate.mjs). An import of this release's code on
10808
12776
  // demand that fails in a process an in-place update left running says to restart.
10809
12777
  function __atomicOnDemandFailed(error, feature) {
10810
12778
  return (async () => {
10811
12779
  const root = new URL("../", import.meta.url);
10812
12780
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
10813
- const key = `${root.href}#0.10.11-alpha.1`;
12781
+ const key = `${root.href}#0.10.11-alpha.2`;
10814
12782
  let release = releases.get(key);
10815
12783
  if (release === undefined) {
10816
12784
  const current = (async () => {
@@ -10838,7 +12806,7 @@ function __atomicOnDemandFailed(error, feature) {
10838
12806
  } catch {
10839
12807
  // No installation to read, as in a bundle of the package: the release the process runs decides.
10840
12808
  }
10841
- const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.1" ? installed : running !== undefined && running.version !== "0.10.11-alpha.1" ? "0.10.11-alpha.1" : undefined;
12809
+ const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.2" ? installed : running !== undefined && running.version !== "0.10.11-alpha.2" ? "0.10.11-alpha.2" : undefined;
10842
12810
  if (updatedTo === undefined) throw error;
10843
12811
  const application = typeof running?.name === "string" ? running.name : "atomic";
10844
12812
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {