@bastani/atomic 0.9.89 → 0.9.90-alpha.1

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 (868) hide show
  1. package/CHANGELOG.md +113 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +13 -0
  3. package/dist/builtin/intercom/README.md +3 -1
  4. package/dist/builtin/intercom/broker/broker.ts +35 -10
  5. package/dist/builtin/intercom/broker/client.ts +42 -1
  6. package/dist/builtin/intercom/index.bundle.mjs +400 -67
  7. package/dist/builtin/intercom/package.json +1 -1
  8. package/dist/builtin/intercom/skills/intercom/SKILL.md +24 -5
  9. package/dist/builtin/intercom/types.ts +5 -0
  10. package/dist/builtin/mcp/package.json +1 -1
  11. package/dist/builtin/subagents/CHANGELOG.md +27 -0
  12. package/dist/builtin/subagents/README.md +18 -20
  13. package/dist/builtin/subagents/agents/worker.md +1 -1
  14. package/dist/builtin/subagents/package.json +1 -1
  15. package/dist/builtin/subagents/skills/feedback/SKILL.md +2 -2
  16. package/dist/builtin/subagents/skills/qlty/SKILL.md +2 -2
  17. package/dist/builtin/subagents/skills/qlty/references/commands.md +45 -12
  18. package/dist/builtin/subagents/skills/qlty/references/quickstart.md +102 -21
  19. package/dist/builtin/subagents/skills/subagent/SKILL.md +18 -17
  20. package/dist/builtin/subagents/skills/tdd/LICENSE.txt +50 -0
  21. package/dist/builtin/subagents/skills/tdd/SKILL.md +10 -0
  22. package/dist/builtin/subagents/skills/tdd/tests.md +16 -0
  23. package/dist/builtin/subagents/skills/tmux/LICENSE.txt +24 -0
  24. package/dist/builtin/subagents/skills/tmux/SKILL.md +20 -1
  25. package/dist/builtin/subagents/skills/tmux/scripts/find-sessions.sh +19 -10
  26. package/dist/builtin/subagents/skills/tmux/scripts/wait-for-text.sh +231 -19
  27. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1911 -845
  28. package/dist/builtin/web-access/CHANGELOG.md +6 -0
  29. package/dist/builtin/web-access/index.bundle.mjs +158 -34
  30. package/dist/builtin/web-access/package.json +1 -1
  31. package/dist/builtin/workflows/CHANGELOG.md +36 -0
  32. package/dist/builtin/workflows/builtin/{chunk-tjk7jp9a.js → chunk-akmcsx14.js} +1 -1
  33. package/dist/builtin/workflows/builtin/{chunk-913nwrzq.js → chunk-erpybg3c.js} +109 -30
  34. package/dist/builtin/workflows/builtin/{chunk-e07n7en6.js → chunk-wpgpr31s.js} +1 -1
  35. package/dist/builtin/workflows/builtin/goal.js +2 -2
  36. package/dist/builtin/workflows/builtin/index.js +3 -3
  37. package/dist/builtin/workflows/builtin/ralph.js +2 -2
  38. package/dist/builtin/workflows/package.json +1 -1
  39. package/dist/builtin/workflows/skills/bro/SKILL.md +1 -1
  40. package/dist/builtin/workflows/skills/prompt-engineer/references/claude_fable_5_2.md +19 -19
  41. package/dist/builtin/workflows/skills/prompt-engineer/references/claude_haiku_5_5.md +2 -2
  42. package/dist/builtin/workflows/skills/prompt-engineer/references/claude_opus_5_5.md +3 -3
  43. package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_6.md +2 -2
  44. package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_6_1_sol.md +2 -2
  45. package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_6_1_terra.md +3 -3
  46. package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_6_2.md +3 -2
  47. package/dist/builtin/workflows/skills/show-me/SKILL.md +2 -2
  48. package/dist/builtin/workflows/skills/skill-creator/scripts/run_eval.py +29 -24
  49. package/dist/builtin/workflows/skills/teach/SKILL.md +8 -8
  50. package/dist/builtin/workflows/skills/unslop/SKILL.md +29 -51
  51. package/dist/builtin/workflows/src/durable/journal/internal.d.ts +10 -5
  52. package/dist/builtin/workflows/src/durable/journal/sharded-run-journal.d.ts +6 -3
  53. package/dist/builtin/workflows/src/durable/journal/sql-run-journal.d.ts +25 -3
  54. package/dist/builtin/workflows/src/extension/index.bundle.mjs +4444 -1356
  55. package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +2544 -568
  56. package/dist/builtin/workflows/src/index.js +2467 -549
  57. package/dist/builtin/workflows/src/local-worker-entry.mjs +2544 -568
  58. package/dist/cli/storage-command.d.ts +6 -0
  59. package/dist/cli/storage-command.d.ts.map +1 -1
  60. package/dist/cli/storage-command.js +11 -0
  61. package/dist/cli/storage-command.js.map +1 -1
  62. package/dist/cli/storage-search-database.d.ts +18 -0
  63. package/dist/cli/storage-search-database.d.ts.map +1 -0
  64. package/dist/cli/storage-search-database.js +90 -0
  65. package/dist/cli/storage-search-database.js.map +1 -0
  66. package/dist/cli/storage-search-session.d.ts +5 -0
  67. package/dist/cli/storage-search-session.d.ts.map +1 -0
  68. package/dist/cli/storage-search-session.js +133 -0
  69. package/dist/cli/storage-search-session.js.map +1 -0
  70. package/dist/core/agent-session-accessors.d.ts.map +1 -1
  71. package/dist/core/agent-session-accessors.js +107 -1
  72. package/dist/core/agent-session-accessors.js.map +1 -1
  73. package/dist/core/agent-session-bash.d.ts.map +1 -1
  74. package/dist/core/agent-session-bash.js +2 -0
  75. package/dist/core/agent-session-bash.js.map +1 -1
  76. package/dist/core/agent-session-boundaries.d.ts +2 -0
  77. package/dist/core/agent-session-boundaries.d.ts.map +1 -1
  78. package/dist/core/agent-session-boundaries.js +9 -4
  79. package/dist/core/agent-session-boundaries.js.map +1 -1
  80. package/dist/core/agent-session-custom-message-commit.d.ts.map +1 -1
  81. package/dist/core/agent-session-custom-message-commit.js +2 -1
  82. package/dist/core/agent-session-custom-message-commit.js.map +1 -1
  83. package/dist/core/agent-session-detached-tools.d.ts +3 -2
  84. package/dist/core/agent-session-detached-tools.d.ts.map +1 -1
  85. package/dist/core/agent-session-detached-tools.js +156 -41
  86. package/dist/core/agent-session-detached-tools.js.map +1 -1
  87. package/dist/core/agent-session-events.d.ts +2 -1
  88. package/dist/core/agent-session-events.d.ts.map +1 -1
  89. package/dist/core/agent-session-events.js +59 -23
  90. package/dist/core/agent-session-events.js.map +1 -1
  91. package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
  92. package/dist/core/agent-session-extension-bindings.js +53 -4
  93. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  94. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  95. package/dist/core/agent-session-message-queue.js +2 -1
  96. package/dist/core/agent-session-message-queue.js.map +1 -1
  97. package/dist/core/agent-session-methods.d.ts +23 -3
  98. package/dist/core/agent-session-methods.d.ts.map +1 -1
  99. package/dist/core/agent-session-methods.js.map +1 -1
  100. package/dist/core/agent-session-models.d.ts.map +1 -1
  101. package/dist/core/agent-session-models.js +2 -0
  102. package/dist/core/agent-session-models.js.map +1 -1
  103. package/dist/core/agent-session-prompt.d.ts +1 -1
  104. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  105. package/dist/core/agent-session-prompt.js +14 -3
  106. package/dist/core/agent-session-prompt.js.map +1 -1
  107. package/dist/core/agent-session-queue-pause.d.ts +2 -1
  108. package/dist/core/agent-session-queue-pause.d.ts.map +1 -1
  109. package/dist/core/agent-session-queue-pause.js +8 -4
  110. package/dist/core/agent-session-queue-pause.js.map +1 -1
  111. package/dist/core/agent-session-retry.d.ts +7 -3
  112. package/dist/core/agent-session-retry.d.ts.map +1 -1
  113. package/dist/core/agent-session-retry.js +113 -112
  114. package/dist/core/agent-session-retry.js.map +1 -1
  115. package/dist/core/agent-session-runtime.d.ts +15 -0
  116. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  117. package/dist/core/agent-session-runtime.js +26 -0
  118. package/dist/core/agent-session-runtime.js.map +1 -1
  119. package/dist/core/agent-session-services.d.ts +5 -2
  120. package/dist/core/agent-session-services.d.ts.map +1 -1
  121. package/dist/core/agent-session-services.js +6 -6
  122. package/dist/core/agent-session-services.js.map +1 -1
  123. package/dist/core/agent-session-tasks.js.map +1 -1
  124. package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
  125. package/dist/core/agent-session-tool-registry.js +4 -2
  126. package/dist/core/agent-session-tool-registry.js.map +1 -1
  127. package/dist/core/agent-session-types.d.ts +19 -1
  128. package/dist/core/agent-session-types.d.ts.map +1 -1
  129. package/dist/core/agent-session-types.js.map +1 -1
  130. package/dist/core/agent-session.d.ts +11 -0
  131. package/dist/core/agent-session.d.ts.map +1 -1
  132. package/dist/core/agent-session.js +8 -0
  133. package/dist/core/agent-session.js.map +1 -1
  134. package/dist/core/anthropic-thinking-guard.d.ts +16 -1
  135. package/dist/core/anthropic-thinking-guard.d.ts.map +1 -1
  136. package/dist/core/anthropic-thinking-guard.js +124 -7
  137. package/dist/core/anthropic-thinking-guard.js.map +1 -1
  138. package/dist/core/auth-storage.d.ts +3 -0
  139. package/dist/core/auth-storage.d.ts.map +1 -1
  140. package/dist/core/auth-storage.js +10 -0
  141. package/dist/core/auth-storage.js.map +1 -1
  142. package/dist/core/detached-tool-output.d.ts +4 -0
  143. package/dist/core/detached-tool-output.d.ts.map +1 -0
  144. package/dist/core/detached-tool-output.js +48 -0
  145. package/dist/core/detached-tool-output.js.map +1 -0
  146. package/dist/core/event-loop-monitor.d.ts +4 -1
  147. package/dist/core/event-loop-monitor.d.ts.map +1 -1
  148. package/dist/core/event-loop-monitor.js +84 -159
  149. package/dist/core/event-loop-monitor.js.map +1 -1
  150. package/dist/core/export-html/index.d.ts.map +1 -1
  151. package/dist/core/export-html/index.js +26 -4
  152. package/dist/core/export-html/index.js.map +1 -1
  153. package/dist/core/export-html/saved-agent-cards.d.ts +15 -0
  154. package/dist/core/export-html/saved-agent-cards.d.ts.map +1 -0
  155. package/dist/core/export-html/saved-agent-cards.js +255 -0
  156. package/dist/core/export-html/saved-agent-cards.js.map +1 -0
  157. package/dist/core/export-html/saved-agent-viewer.js +101 -0
  158. package/dist/core/extensions/builtin-subagent-record-writer.d.ts +11 -0
  159. package/dist/core/extensions/builtin-subagent-record-writer.d.ts.map +1 -0
  160. package/dist/core/extensions/builtin-subagent-record-writer.js +33 -0
  161. package/dist/core/extensions/builtin-subagent-record-writer.js.map +1 -0
  162. package/dist/core/extensions/loader-api.d.ts +1 -1
  163. package/dist/core/extensions/loader-api.d.ts.map +1 -1
  164. package/dist/core/extensions/loader-api.js +9 -2
  165. package/dist/core/extensions/loader-api.js.map +1 -1
  166. package/dist/core/extensions/loader-bindings.d.ts +7 -0
  167. package/dist/core/extensions/loader-bindings.d.ts.map +1 -1
  168. package/dist/core/extensions/loader-bindings.js +42 -1
  169. package/dist/core/extensions/loader-bindings.js.map +1 -1
  170. package/dist/core/extensions/loader-core.d.ts.map +1 -1
  171. package/dist/core/extensions/loader-core.js +33 -12
  172. package/dist/core/extensions/loader-core.js.map +1 -1
  173. package/dist/core/extensions/runner-events.d.ts +2 -0
  174. package/dist/core/extensions/runner-events.d.ts.map +1 -1
  175. package/dist/core/extensions/runner-events.js +17 -7
  176. package/dist/core/extensions/runner-events.js.map +1 -1
  177. package/dist/core/extensions/runner.d.ts +6 -2
  178. package/dist/core/extensions/runner.d.ts.map +1 -1
  179. package/dist/core/extensions/runner.js +5 -2
  180. package/dist/core/extensions/runner.js.map +1 -1
  181. package/dist/core/extensions/ui-types.d.ts +4 -0
  182. package/dist/core/extensions/ui-types.d.ts.map +1 -1
  183. package/dist/core/extensions/ui-types.js.map +1 -1
  184. package/dist/core/extensions/workflow-run-control-hub.d.ts +2 -2
  185. package/dist/core/extensions/workflow-run-control-hub.d.ts.map +1 -1
  186. package/dist/core/extensions/workflow-run-control-hub.js +2 -2
  187. package/dist/core/extensions/workflow-run-control-hub.js.map +1 -1
  188. package/dist/core/extensions/workflow-run-control.d.ts +10 -3
  189. package/dist/core/extensions/workflow-run-control.d.ts.map +1 -1
  190. package/dist/core/extensions/workflow-run-control.js.map +1 -1
  191. package/dist/core/first-prompt-model.d.ts +22 -0
  192. package/dist/core/first-prompt-model.d.ts.map +1 -0
  193. package/dist/core/first-prompt-model.js +84 -0
  194. package/dist/core/first-prompt-model.js.map +1 -0
  195. package/dist/core/footer-data-provider.d.ts.map +1 -1
  196. package/dist/core/footer-data-provider.js +11 -7
  197. package/dist/core/footer-data-provider.js.map +1 -1
  198. package/dist/core/fork-replay-pair.d.ts +22 -0
  199. package/dist/core/fork-replay-pair.d.ts.map +1 -0
  200. package/dist/core/fork-replay-pair.js +174 -0
  201. package/dist/core/fork-replay-pair.js.map +1 -0
  202. package/dist/core/fork-replay-wire.d.ts +11 -0
  203. package/dist/core/fork-replay-wire.d.ts.map +1 -0
  204. package/dist/core/fork-replay-wire.js +116 -0
  205. package/dist/core/fork-replay-wire.js.map +1 -0
  206. package/dist/core/messages.d.ts +2 -0
  207. package/dist/core/messages.d.ts.map +1 -1
  208. package/dist/core/messages.js +8 -4
  209. package/dist/core/messages.js.map +1 -1
  210. package/dist/core/model-runtime.d.ts +10 -1
  211. package/dist/core/model-runtime.d.ts.map +1 -1
  212. package/dist/core/model-runtime.js +76 -11
  213. package/dist/core/model-runtime.js.map +1 -1
  214. package/dist/core/package-manager-auto-resources.d.ts.map +1 -1
  215. package/dist/core/package-manager-auto-resources.js +3 -2
  216. package/dist/core/package-manager-auto-resources.js.map +1 -1
  217. package/dist/core/package-manager-resource-files.js +7 -8
  218. package/dist/core/package-manager-resource-files.js.map +1 -1
  219. package/dist/core/project-trust-state.d.ts +90 -0
  220. package/dist/core/project-trust-state.d.ts.map +1 -0
  221. package/dist/core/project-trust-state.js +65 -0
  222. package/dist/core/project-trust-state.js.map +1 -0
  223. package/dist/core/provider-rate-limits.d.ts +6 -0
  224. package/dist/core/provider-rate-limits.d.ts.map +1 -1
  225. package/dist/core/provider-rate-limits.js +43 -0
  226. package/dist/core/provider-rate-limits.js.map +1 -1
  227. package/dist/core/provider-request-admission.d.ts.map +1 -1
  228. package/dist/core/provider-request-admission.js +10 -1
  229. package/dist/core/provider-request-admission.js.map +1 -1
  230. package/dist/core/remote-catalog-provider.d.ts +6 -1
  231. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  232. package/dist/core/remote-catalog-provider.js +22 -1
  233. package/dist/core/remote-catalog-provider.js.map +1 -1
  234. package/dist/core/resolve-config-value.d.ts.map +1 -1
  235. package/dist/core/resolve-config-value.js +5 -2
  236. package/dist/core/resolve-config-value.js.map +1 -1
  237. package/dist/core/resource-loader-core.d.ts.map +1 -1
  238. package/dist/core/resource-loader-core.js +3 -0
  239. package/dist/core/resource-loader-core.js.map +1 -1
  240. package/dist/core/resource-loader-extensions.d.ts +2 -2
  241. package/dist/core/resource-loader-extensions.d.ts.map +1 -1
  242. package/dist/core/resource-loader-extensions.js +6 -4
  243. package/dist/core/resource-loader-extensions.js.map +1 -1
  244. package/dist/core/resource-loader-package-resources.d.ts +1 -0
  245. package/dist/core/resource-loader-package-resources.d.ts.map +1 -1
  246. package/dist/core/resource-loader-package-resources.js +2 -1
  247. package/dist/core/resource-loader-package-resources.js.map +1 -1
  248. package/dist/core/resource-loader-reload.d.ts +1 -1
  249. package/dist/core/resource-loader-reload.d.ts.map +1 -1
  250. package/dist/core/resource-loader-reload.js +3 -2
  251. package/dist/core/resource-loader-reload.js.map +1 -1
  252. package/dist/core/resource-loader-types.d.ts +2 -0
  253. package/dist/core/resource-loader-types.d.ts.map +1 -1
  254. package/dist/core/resource-loader-types.js.map +1 -1
  255. package/dist/core/resume/blueprint/actions.d.ts.map +1 -1
  256. package/dist/core/resume/blueprint/actions.js +15 -15
  257. package/dist/core/resume/blueprint/actions.js.map +1 -1
  258. package/dist/core/resume/blueprint/process.d.ts +6 -1
  259. package/dist/core/resume/blueprint/process.d.ts.map +1 -1
  260. package/dist/core/resume/blueprint/process.js +132 -21
  261. package/dist/core/resume/blueprint/process.js.map +1 -1
  262. package/dist/core/runtime-credentials.d.ts +5 -0
  263. package/dist/core/runtime-credentials.d.ts.map +1 -1
  264. package/dist/core/runtime-credentials.js +34 -0
  265. package/dist/core/runtime-credentials.js.map +1 -1
  266. package/dist/core/sdk-types.d.ts +2 -0
  267. package/dist/core/sdk-types.d.ts.map +1 -1
  268. package/dist/core/sdk-types.js.map +1 -1
  269. package/dist/core/sdk.d.ts +1 -1
  270. package/dist/core/sdk.d.ts.map +1 -1
  271. package/dist/core/sdk.js +187 -32
  272. package/dist/core/sdk.js.map +1 -1
  273. package/dist/core/session-account-model.d.ts +15 -0
  274. package/dist/core/session-account-model.d.ts.map +1 -0
  275. package/dist/core/session-account-model.js +105 -0
  276. package/dist/core/session-account-model.js.map +1 -0
  277. package/dist/core/session-lifecycle-scope.d.ts +5 -0
  278. package/dist/core/session-lifecycle-scope.d.ts.map +1 -1
  279. package/dist/core/session-lifecycle-scope.js.map +1 -1
  280. package/dist/core/session-manager-core.d.ts +21 -2
  281. package/dist/core/session-manager-core.d.ts.map +1 -1
  282. package/dist/core/session-manager-core.js +64 -8
  283. package/dist/core/session-manager-core.js.map +1 -1
  284. package/dist/core/session-manager-history.d.ts +3 -1
  285. package/dist/core/session-manager-history.d.ts.map +1 -1
  286. package/dist/core/session-manager-history.js +19 -5
  287. package/dist/core/session-manager-history.js.map +1 -1
  288. package/dist/core/session-manager-types.d.ts +2 -0
  289. package/dist/core/session-manager-types.d.ts.map +1 -1
  290. package/dist/core/session-manager-types.js.map +1 -1
  291. package/dist/core/session-retry-status.d.ts +22 -0
  292. package/dist/core/session-retry-status.d.ts.map +1 -0
  293. package/dist/core/session-retry-status.js +25 -0
  294. package/dist/core/session-retry-status.js.map +1 -0
  295. package/dist/core/session-worktree-snapshots.d.ts +4 -2
  296. package/dist/core/session-worktree-snapshots.d.ts.map +1 -1
  297. package/dist/core/session-worktree-snapshots.js +8 -4
  298. package/dist/core/session-worktree-snapshots.js.map +1 -1
  299. package/dist/core/settings-manager-core.d.ts +4 -0
  300. package/dist/core/settings-manager-core.d.ts.map +1 -1
  301. package/dist/core/settings-manager-core.js +73 -1
  302. package/dist/core/settings-manager-core.js.map +1 -1
  303. package/dist/core/settings-schema.js +1 -1
  304. package/dist/core/settings-schema.js.map +1 -1
  305. package/dist/core/slash-commands.d.ts +2 -2
  306. package/dist/core/slash-commands.d.ts.map +1 -1
  307. package/dist/core/slash-commands.js +15 -4
  308. package/dist/core/slash-commands.js.map +1 -1
  309. package/dist/core/storage/database.d.ts +14 -2
  310. package/dist/core/storage/database.d.ts.map +1 -1
  311. package/dist/core/storage/database.js.map +1 -1
  312. package/dist/core/storage/dialect.d.ts +13 -0
  313. package/dist/core/storage/dialect.d.ts.map +1 -1
  314. package/dist/core/storage/dialect.js +9 -1
  315. package/dist/core/storage/dialect.js.map +1 -1
  316. package/dist/core/storage/errors.d.ts +23 -1
  317. package/dist/core/storage/errors.d.ts.map +1 -1
  318. package/dist/core/storage/errors.js +28 -5
  319. package/dist/core/storage/errors.js.map +1 -1
  320. package/dist/core/storage/journal-transfer.d.ts.map +1 -1
  321. package/dist/core/storage/journal-transfer.js +90 -5
  322. package/dist/core/storage/journal-transfer.js.map +1 -1
  323. package/dist/core/storage/node-sqlite.d.ts.map +1 -1
  324. package/dist/core/storage/node-sqlite.js +61 -1
  325. package/dist/core/storage/node-sqlite.js.map +1 -1
  326. package/dist/core/storage/session/chunked-resume-projection.d.ts +4 -0
  327. package/dist/core/storage/session/chunked-resume-projection.d.ts.map +1 -0
  328. package/dist/core/storage/session/chunked-resume-projection.js +369 -0
  329. package/dist/core/storage/session/chunked-resume-projection.js.map +1 -0
  330. package/dist/core/storage/session/legacy-session-store.d.ts +5 -0
  331. package/dist/core/storage/session/legacy-session-store.d.ts.map +1 -1
  332. package/dist/core/storage/session/legacy-session-store.js +10 -2
  333. package/dist/core/storage/session/legacy-session-store.js.map +1 -1
  334. package/dist/core/storage/session/memory-session-store.d.ts.map +1 -1
  335. package/dist/core/storage/session/memory-session-store.js +6 -1
  336. package/dist/core/storage/session/memory-session-store.js.map +1 -1
  337. package/dist/core/storage/session/snapshot-generation.d.ts +8 -0
  338. package/dist/core/storage/session/snapshot-generation.d.ts.map +1 -0
  339. package/dist/core/storage/session/snapshot-generation.js +17 -0
  340. package/dist/core/storage/session/snapshot-generation.js.map +1 -0
  341. package/dist/core/storage/session/sql-session-store.d.ts +12 -0
  342. package/dist/core/storage/session/sql-session-store.d.ts.map +1 -1
  343. package/dist/core/storage/session/sql-session-store.js +243 -46
  344. package/dist/core/storage/session/sql-session-store.js.map +1 -1
  345. package/dist/core/storage/sqlite-facade.d.ts +17 -2
  346. package/dist/core/storage/sqlite-facade.d.ts.map +1 -1
  347. package/dist/core/storage/sqlite-facade.js +17 -1
  348. package/dist/core/storage/sqlite-facade.js.map +1 -1
  349. package/dist/core/tasks/agent-adapter.d.ts +13 -2
  350. package/dist/core/tasks/agent-adapter.d.ts.map +1 -1
  351. package/dist/core/tasks/agent-adapter.js +25 -8
  352. package/dist/core/tasks/agent-adapter.js.map +1 -1
  353. package/dist/core/tasks/agent-panel-rules.d.ts +77 -0
  354. package/dist/core/tasks/agent-panel-rules.d.ts.map +1 -0
  355. package/dist/core/tasks/agent-panel-rules.js +88 -0
  356. package/dist/core/tasks/agent-panel-rules.js.map +1 -0
  357. package/dist/core/tasks/agent-panel-source.d.ts +19 -0
  358. package/dist/core/tasks/agent-panel-source.d.ts.map +1 -1
  359. package/dist/core/tasks/agent-panel-source.js +50 -9
  360. package/dist/core/tasks/agent-panel-source.js.map +1 -1
  361. package/dist/core/tasks/command-output.d.ts +17 -2
  362. package/dist/core/tasks/command-output.d.ts.map +1 -1
  363. package/dist/core/tasks/command-output.js +59 -3
  364. package/dist/core/tasks/command-output.js.map +1 -1
  365. package/dist/core/tasks/completion-message.d.ts +8 -3
  366. package/dist/core/tasks/completion-message.d.ts.map +1 -1
  367. package/dist/core/tasks/completion-message.js +14 -10
  368. package/dist/core/tasks/completion-message.js.map +1 -1
  369. package/dist/core/tasks/completion.d.ts +14 -4
  370. package/dist/core/tasks/completion.d.ts.map +1 -1
  371. package/dist/core/tasks/completion.js +58 -17
  372. package/dist/core/tasks/completion.js.map +1 -1
  373. package/dist/core/tasks/contracts.d.ts +10 -1
  374. package/dist/core/tasks/contracts.d.ts.map +1 -1
  375. package/dist/core/tasks/contracts.js +3 -1
  376. package/dist/core/tasks/contracts.js.map +1 -1
  377. package/dist/core/tasks/heartbeat.js +2 -1
  378. package/dist/core/tasks/heartbeat.js.map +1 -1
  379. package/dist/core/tasks/live-elapsed.d.ts +16 -1
  380. package/dist/core/tasks/live-elapsed.d.ts.map +1 -1
  381. package/dist/core/tasks/live-elapsed.js +43 -4
  382. package/dist/core/tasks/live-elapsed.js.map +1 -1
  383. package/dist/core/tasks/owner-store.d.ts +8 -0
  384. package/dist/core/tasks/owner-store.d.ts.map +1 -1
  385. package/dist/core/tasks/owner-store.js +34 -4
  386. package/dist/core/tasks/owner-store.js.map +1 -1
  387. package/dist/core/tasks/session-scope.d.ts +7 -0
  388. package/dist/core/tasks/session-scope.d.ts.map +1 -1
  389. package/dist/core/tasks/session-scope.js +15 -9
  390. package/dist/core/tasks/session-scope.js.map +1 -1
  391. package/dist/core/tasks/supervisor.d.ts +7 -3
  392. package/dist/core/tasks/supervisor.d.ts.map +1 -1
  393. package/dist/core/tasks/supervisor.js +92 -17
  394. package/dist/core/tasks/supervisor.js.map +1 -1
  395. package/dist/core/tasks/task-archive-snapshot.d.ts +7 -0
  396. package/dist/core/tasks/task-archive-snapshot.d.ts.map +1 -0
  397. package/dist/core/tasks/task-archive-snapshot.js +33 -0
  398. package/dist/core/tasks/task-archive-snapshot.js.map +1 -0
  399. package/dist/core/tasks/task-resumer.d.ts +5 -3
  400. package/dist/core/tasks/task-resumer.d.ts.map +1 -1
  401. package/dist/core/tasks/task-resumer.js +37 -13
  402. package/dist/core/tasks/task-resumer.js.map +1 -1
  403. package/dist/core/tasks/task-view-source.d.ts +25 -3
  404. package/dist/core/tasks/task-view-source.d.ts.map +1 -1
  405. package/dist/core/tasks/task-view-source.js +144 -44
  406. package/dist/core/tasks/task-view-source.js.map +1 -1
  407. package/dist/core/tasks/transcript.d.ts +3 -1
  408. package/dist/core/tasks/transcript.d.ts.map +1 -1
  409. package/dist/core/tasks/transcript.js +27 -0
  410. package/dist/core/tasks/transcript.js.map +1 -1
  411. package/dist/core/tools/ask-user-question/view/dialog-builder.d.ts.map +1 -1
  412. package/dist/core/tools/ask-user-question/view/dialog-builder.js +2 -1
  413. package/dist/core/tools/ask-user-question/view/dialog-builder.js.map +1 -1
  414. package/dist/core/tools/bash.d.ts.map +1 -1
  415. package/dist/core/tools/bash.js +2 -1
  416. package/dist/core/tools/bash.js.map +1 -1
  417. package/dist/core/tools/history-protocol.d.ts.map +1 -1
  418. package/dist/core/tools/history-protocol.js +130 -29
  419. package/dist/core/tools/history-protocol.js.map +1 -1
  420. package/dist/core/tools/history-search-position.d.ts +30 -0
  421. package/dist/core/tools/history-search-position.d.ts.map +1 -0
  422. package/dist/core/tools/history-search-position.js +161 -0
  423. package/dist/core/tools/history-search-position.js.map +1 -0
  424. package/dist/core/tools/history-search-wire.d.ts +25 -0
  425. package/dist/core/tools/history-search-wire.d.ts.map +1 -0
  426. package/dist/core/tools/history-search-wire.js +210 -0
  427. package/dist/core/tools/history-search-wire.js.map +1 -0
  428. package/dist/core/tools/resource-selectors.d.ts +7 -1
  429. package/dist/core/tools/resource-selectors.d.ts.map +1 -1
  430. package/dist/core/tools/resource-selectors.js +18 -11
  431. package/dist/core/tools/resource-selectors.js.map +1 -1
  432. package/dist/core/tools/search.d.ts.map +1 -1
  433. package/dist/core/tools/search.js +24 -3
  434. package/dist/core/tools/search.js.map +1 -1
  435. package/dist/core/tools/sqlite-selector-connection.d.ts +3 -0
  436. package/dist/core/tools/sqlite-selector-connection.d.ts.map +1 -1
  437. package/dist/core/tools/sqlite-selector-connection.js +4 -0
  438. package/dist/core/tools/sqlite-selector-connection.js.map +1 -1
  439. package/dist/core/tools/tool-abort-grace.d.ts +13 -0
  440. package/dist/core/tools/tool-abort-grace.d.ts.map +1 -0
  441. package/dist/core/tools/tool-abort-grace.js +72 -0
  442. package/dist/core/tools/tool-abort-grace.js.map +1 -0
  443. package/dist/core/tools/tool-concurrency.d.ts +5 -1
  444. package/dist/core/tools/tool-concurrency.d.ts.map +1 -1
  445. package/dist/core/tools/tool-concurrency.js +36 -6
  446. package/dist/core/tools/tool-concurrency.js.map +1 -1
  447. package/dist/core/workflow-resume.d.ts +1 -1
  448. package/dist/core/workflow-resume.d.ts.map +1 -1
  449. package/dist/core/workflow-resume.js +13 -3
  450. package/dist/core/workflow-resume.js.map +1 -1
  451. package/dist/core/workflow-summary-lifecycle.d.ts.map +1 -1
  452. package/dist/core/workflow-summary-lifecycle.js +8 -2
  453. package/dist/core/workflow-summary-lifecycle.js.map +1 -1
  454. package/dist/core/workspace/errors.d.ts +5 -2
  455. package/dist/core/workspace/errors.d.ts.map +1 -1
  456. package/dist/core/workspace/errors.js +59 -5
  457. package/dist/core/workspace/errors.js.map +1 -1
  458. package/dist/core/worktree-snapshot/blob-store.d.ts +138 -17
  459. package/dist/core/worktree-snapshot/blob-store.d.ts.map +1 -1
  460. package/dist/core/worktree-snapshot/blob-store.js +788 -82
  461. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  462. package/dist/core/worktree-snapshot/garbage.d.ts +17 -2
  463. package/dist/core/worktree-snapshot/garbage.d.ts.map +1 -1
  464. package/dist/core/worktree-snapshot/garbage.js +20 -4
  465. package/dist/core/worktree-snapshot/garbage.js.map +1 -1
  466. package/dist/core/worktree-snapshot/index.d.ts +1 -1
  467. package/dist/core/worktree-snapshot/index.d.ts.map +1 -1
  468. package/dist/core/worktree-snapshot/index.js +1 -1
  469. package/dist/core/worktree-snapshot/index.js.map +1 -1
  470. package/dist/core/worktree-snapshot/pool.d.ts.map +1 -1
  471. package/dist/core/worktree-snapshot/pool.js +38 -6
  472. package/dist/core/worktree-snapshot/pool.js.map +1 -1
  473. package/dist/core/worktree-snapshot/shared-clock.d.ts +3 -1
  474. package/dist/core/worktree-snapshot/shared-clock.d.ts.map +1 -1
  475. package/dist/core/worktree-snapshot/shared-clock.js +116 -26
  476. package/dist/core/worktree-snapshot/shared-clock.js.map +1 -1
  477. package/dist/core/worktree-snapshot/types.d.ts +4 -1
  478. package/dist/core/worktree-snapshot/types.d.ts.map +1 -1
  479. package/dist/core/worktree-snapshot/types.js.map +1 -1
  480. package/dist/extensions/llama/huggingface-ui.d.ts.map +1 -1
  481. package/dist/extensions/llama/huggingface-ui.js +2 -2
  482. package/dist/extensions/llama/huggingface-ui.js.map +1 -1
  483. package/dist/extensions/llama/index.d.ts +2 -0
  484. package/dist/extensions/llama/index.d.ts.map +1 -1
  485. package/dist/extensions/llama/index.js +19 -2
  486. package/dist/extensions/llama/index.js.map +1 -1
  487. package/dist/index.d.ts +9 -6
  488. package/dist/index.d.ts.map +1 -1
  489. package/dist/index.js +8 -4
  490. package/dist/index.js.map +1 -1
  491. package/dist/main.d.ts.map +1 -1
  492. package/dist/main.js +74 -15
  493. package/dist/main.js.map +1 -1
  494. package/dist/modes/interactive/components/agent-panel.d.ts +22 -6
  495. package/dist/modes/interactive/components/agent-panel.d.ts.map +1 -1
  496. package/dist/modes/interactive/components/agent-panel.js +80 -23
  497. package/dist/modes/interactive/components/agent-panel.js.map +1 -1
  498. package/dist/modes/interactive/components/assistant-message.d.ts +2 -0
  499. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  500. package/dist/modes/interactive/components/assistant-message.js +11 -0
  501. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  502. package/dist/modes/interactive/components/atomic-working-status.d.ts.map +1 -1
  503. package/dist/modes/interactive/components/atomic-working-status.js +10 -3
  504. package/dist/modes/interactive/components/atomic-working-status.js.map +1 -1
  505. package/dist/modes/interactive/components/bash-execution.d.ts +3 -2
  506. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  507. package/dist/modes/interactive/components/bash-execution.js +7 -7
  508. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  509. package/dist/modes/interactive/components/branch-summary-message.d.ts +6 -0
  510. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  511. package/dist/modes/interactive/components/branch-summary-message.js +12 -7
  512. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  513. package/dist/modes/interactive/components/chat-message-renderer.d.ts +2 -0
  514. package/dist/modes/interactive/components/chat-message-renderer.d.ts.map +1 -1
  515. package/dist/modes/interactive/components/chat-message-renderer.js +24 -3
  516. package/dist/modes/interactive/components/chat-message-renderer.js.map +1 -1
  517. package/dist/modes/interactive/components/chat-session-host-actions.d.ts +1 -1
  518. package/dist/modes/interactive/components/chat-session-host-actions.d.ts.map +1 -1
  519. package/dist/modes/interactive/components/chat-session-host-actions.js +16 -10
  520. package/dist/modes/interactive/components/chat-session-host-actions.js.map +1 -1
  521. package/dist/modes/interactive/components/chat-session-host-events.d.ts +10 -0
  522. package/dist/modes/interactive/components/chat-session-host-events.d.ts.map +1 -1
  523. package/dist/modes/interactive/components/chat-session-host-events.js +76 -31
  524. package/dist/modes/interactive/components/chat-session-host-events.js.map +1 -1
  525. package/dist/modes/interactive/components/chat-session-host-rendering.d.ts +17 -5
  526. package/dist/modes/interactive/components/chat-session-host-rendering.d.ts.map +1 -1
  527. package/dist/modes/interactive/components/chat-session-host-rendering.js +79 -24
  528. package/dist/modes/interactive/components/chat-session-host-rendering.js.map +1 -1
  529. package/dist/modes/interactive/components/chat-session-host-runtime.d.ts.map +1 -1
  530. package/dist/modes/interactive/components/chat-session-host-runtime.js +5 -4
  531. package/dist/modes/interactive/components/chat-session-host-runtime.js.map +1 -1
  532. package/dist/modes/interactive/components/chat-session-host-state.d.ts +16 -1
  533. package/dist/modes/interactive/components/chat-session-host-state.d.ts.map +1 -1
  534. package/dist/modes/interactive/components/chat-session-host-state.js +22 -0
  535. package/dist/modes/interactive/components/chat-session-host-state.js.map +1 -1
  536. package/dist/modes/interactive/components/chat-session-host-types.d.ts +8 -2
  537. package/dist/modes/interactive/components/chat-session-host-types.d.ts.map +1 -1
  538. package/dist/modes/interactive/components/chat-session-host-types.js.map +1 -1
  539. package/dist/modes/interactive/components/chat-session-host-utils.d.ts +1 -0
  540. package/dist/modes/interactive/components/chat-session-host-utils.d.ts.map +1 -1
  541. package/dist/modes/interactive/components/chat-session-host-utils.js +2 -1
  542. package/dist/modes/interactive/components/chat-session-host-utils.js.map +1 -1
  543. package/dist/modes/interactive/components/chat-session-host.d.ts +35 -9
  544. package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
  545. package/dist/modes/interactive/components/chat-session-host.js +129 -35
  546. package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
  547. package/dist/modes/interactive/components/chat-transcript.d.ts +13 -2
  548. package/dist/modes/interactive/components/chat-transcript.d.ts.map +1 -1
  549. package/dist/modes/interactive/components/chat-transcript.js +24 -4
  550. package/dist/modes/interactive/components/chat-transcript.js.map +1 -1
  551. package/dist/modes/interactive/components/compaction-boundary-message.d.ts +6 -0
  552. package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
  553. package/dist/modes/interactive/components/compaction-boundary-message.js +12 -7
  554. package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
  555. package/dist/modes/interactive/components/composer-rule.d.ts +0 -2
  556. package/dist/modes/interactive/components/composer-rule.d.ts.map +1 -1
  557. package/dist/modes/interactive/components/composer-rule.js +4 -6
  558. package/dist/modes/interactive/components/composer-rule.js.map +1 -1
  559. package/dist/modes/interactive/components/countdown-timer.d.ts +5 -9
  560. package/dist/modes/interactive/components/countdown-timer.d.ts.map +1 -1
  561. package/dist/modes/interactive/components/countdown-timer.js +32 -23
  562. package/dist/modes/interactive/components/countdown-timer.js.map +1 -1
  563. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  564. package/dist/modes/interactive/components/custom-editor.js +4 -3
  565. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  566. package/dist/modes/interactive/components/custom-entry.d.ts +6 -0
  567. package/dist/modes/interactive/components/custom-entry.d.ts.map +1 -1
  568. package/dist/modes/interactive/components/custom-entry.js +15 -0
  569. package/dist/modes/interactive/components/custom-entry.js.map +1 -1
  570. package/dist/modes/interactive/components/custom-message.d.ts +7 -3
  571. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  572. package/dist/modes/interactive/components/custom-message.js +17 -15
  573. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  574. package/dist/modes/interactive/components/footer.d.ts +10 -3
  575. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  576. package/dist/modes/interactive/components/footer.js +37 -45
  577. package/dist/modes/interactive/components/footer.js.map +1 -1
  578. package/dist/modes/interactive/components/heartbeat-block.d.ts.map +1 -1
  579. package/dist/modes/interactive/components/heartbeat-block.js +3 -1
  580. package/dist/modes/interactive/components/heartbeat-block.js.map +1 -1
  581. package/dist/modes/interactive/components/host-input-form.d.ts.map +1 -1
  582. package/dist/modes/interactive/components/host-input-form.js +3 -3
  583. package/dist/modes/interactive/components/host-input-form.js.map +1 -1
  584. package/dist/modes/interactive/components/index.d.ts +1 -1
  585. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  586. package/dist/modes/interactive/components/index.js.map +1 -1
  587. package/dist/modes/interactive/components/input-label.d.ts.map +1 -1
  588. package/dist/modes/interactive/components/input-label.js +4 -5
  589. package/dist/modes/interactive/components/input-label.js.map +1 -1
  590. package/dist/modes/interactive/components/keybinding-hints.d.ts +7 -0
  591. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
  592. package/dist/modes/interactive/components/keybinding-hints.js +27 -6
  593. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
  594. package/dist/modes/interactive/components/main-composer-keys.d.ts +17 -2
  595. package/dist/modes/interactive/components/main-composer-keys.d.ts.map +1 -1
  596. package/dist/modes/interactive/components/main-composer-keys.js +44 -27
  597. package/dist/modes/interactive/components/main-composer-keys.js.map +1 -1
  598. package/dist/modes/interactive/components/model-selector.d.ts +6 -1
  599. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  600. package/dist/modes/interactive/components/model-selector.js +13 -7
  601. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  602. package/dist/modes/interactive/components/nav-keys.d.ts +7 -2
  603. package/dist/modes/interactive/components/nav-keys.d.ts.map +1 -1
  604. package/dist/modes/interactive/components/nav-keys.js +51 -17
  605. package/dist/modes/interactive/components/nav-keys.js.map +1 -1
  606. package/dist/modes/interactive/components/notice-line.d.ts +8 -0
  607. package/dist/modes/interactive/components/notice-line.d.ts.map +1 -1
  608. package/dist/modes/interactive/components/notice-line.js +6 -1
  609. package/dist/modes/interactive/components/notice-line.js.map +1 -1
  610. package/dist/modes/interactive/components/selector.d.ts +3 -0
  611. package/dist/modes/interactive/components/selector.d.ts.map +1 -1
  612. package/dist/modes/interactive/components/selector.js +30 -7
  613. package/dist/modes/interactive/components/selector.js.map +1 -1
  614. package/dist/modes/interactive/components/session-selector-list.d.ts.map +1 -1
  615. package/dist/modes/interactive/components/session-selector-list.js +11 -11
  616. package/dist/modes/interactive/components/session-selector-list.js.map +1 -1
  617. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  618. package/dist/modes/interactive/components/session-selector.js +2 -2
  619. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  620. package/dist/modes/interactive/components/settings-picker.d.ts +5 -0
  621. package/dist/modes/interactive/components/settings-picker.d.ts.map +1 -1
  622. package/dist/modes/interactive/components/settings-picker.js +36 -2
  623. package/dist/modes/interactive/components/settings-picker.js.map +1 -1
  624. package/dist/modes/interactive/components/settings-selector-submenus.d.ts +10 -0
  625. package/dist/modes/interactive/components/settings-selector-submenus.d.ts.map +1 -1
  626. package/dist/modes/interactive/components/settings-selector-submenus.js +89 -19
  627. package/dist/modes/interactive/components/settings-selector-submenus.js.map +1 -1
  628. package/dist/modes/interactive/components/settings-selector-types.d.ts +6 -0
  629. package/dist/modes/interactive/components/settings-selector-types.d.ts.map +1 -1
  630. package/dist/modes/interactive/components/settings-selector-types.js.map +1 -1
  631. package/dist/modes/interactive/components/settings-selector.d.ts +7 -0
  632. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  633. package/dist/modes/interactive/components/settings-selector.js +12 -0
  634. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  635. package/dist/modes/interactive/components/skill-invocation-message.d.ts +6 -0
  636. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  637. package/dist/modes/interactive/components/skill-invocation-message.js +12 -7
  638. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  639. package/dist/modes/interactive/components/task-board.d.ts.map +1 -1
  640. package/dist/modes/interactive/components/task-board.js +9 -2
  641. package/dist/modes/interactive/components/task-board.js.map +1 -1
  642. package/dist/modes/interactive/components/task-completion-message.d.ts +10 -3
  643. package/dist/modes/interactive/components/task-completion-message.d.ts.map +1 -1
  644. package/dist/modes/interactive/components/task-completion-message.js +173 -19
  645. package/dist/modes/interactive/components/task-completion-message.js.map +1 -1
  646. package/dist/modes/interactive/components/task-inspector.d.ts +1 -1
  647. package/dist/modes/interactive/components/task-inspector.d.ts.map +1 -1
  648. package/dist/modes/interactive/components/task-inspector.js +28 -19
  649. package/dist/modes/interactive/components/task-inspector.js.map +1 -1
  650. package/dist/modes/interactive/components/task-list.d.ts +7 -3
  651. package/dist/modes/interactive/components/task-list.d.ts.map +1 -1
  652. package/dist/modes/interactive/components/task-list.js +60 -33
  653. package/dist/modes/interactive/components/task-list.js.map +1 -1
  654. package/dist/modes/interactive/components/task-row.d.ts +7 -0
  655. package/dist/modes/interactive/components/task-row.d.ts.map +1 -1
  656. package/dist/modes/interactive/components/task-row.js +25 -11
  657. package/dist/modes/interactive/components/task-row.js.map +1 -1
  658. package/dist/modes/interactive/components/task-transcript-notices.d.ts +16 -0
  659. package/dist/modes/interactive/components/task-transcript-notices.d.ts.map +1 -0
  660. package/dist/modes/interactive/components/task-transcript-notices.js +74 -0
  661. package/dist/modes/interactive/components/task-transcript-notices.js.map +1 -0
  662. package/dist/modes/interactive/components/task-transcript-page.d.ts +11 -6
  663. package/dist/modes/interactive/components/task-transcript-page.d.ts.map +1 -1
  664. package/dist/modes/interactive/components/task-transcript-page.js +48 -21
  665. package/dist/modes/interactive/components/task-transcript-page.js.map +1 -1
  666. package/dist/modes/interactive/components/tool-block-families.d.ts.map +1 -1
  667. package/dist/modes/interactive/components/tool-block-families.js +2 -1
  668. package/dist/modes/interactive/components/tool-block-families.js.map +1 -1
  669. package/dist/modes/interactive/components/tool-execution.d.ts +3 -2
  670. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  671. package/dist/modes/interactive/components/tool-execution.js +23 -9
  672. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  673. package/dist/modes/interactive/components/transcript-block-clicks.d.ts +54 -14
  674. package/dist/modes/interactive/components/transcript-block-clicks.d.ts.map +1 -1
  675. package/dist/modes/interactive/components/transcript-block-clicks.js +151 -16
  676. package/dist/modes/interactive/components/transcript-block-clicks.js.map +1 -1
  677. package/dist/modes/interactive/components/tree-selector-help.d.ts.map +1 -1
  678. package/dist/modes/interactive/components/tree-selector-help.js +25 -30
  679. package/dist/modes/interactive/components/tree-selector-help.js.map +1 -1
  680. package/dist/modes/interactive/components/tree-selector-list.d.ts +4 -0
  681. package/dist/modes/interactive/components/tree-selector-list.d.ts.map +1 -1
  682. package/dist/modes/interactive/components/tree-selector-list.js +21 -21
  683. package/dist/modes/interactive/components/tree-selector-list.js.map +1 -1
  684. package/dist/modes/interactive/components/working-run-meter.d.ts +31 -2
  685. package/dist/modes/interactive/components/working-run-meter.d.ts.map +1 -1
  686. package/dist/modes/interactive/components/working-run-meter.js +81 -10
  687. package/dist/modes/interactive/components/working-run-meter.js.map +1 -1
  688. package/dist/modes/interactive/interactive-agent-events.js +67 -14
  689. package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
  690. package/dist/modes/interactive/interactive-autocomplete.js +2 -2
  691. package/dist/modes/interactive/interactive-autocomplete.js.map +1 -1
  692. package/dist/modes/interactive/interactive-deferred-startup.d.ts.map +1 -1
  693. package/dist/modes/interactive/interactive-deferred-startup.js +10 -4
  694. package/dist/modes/interactive/interactive-deferred-startup.js.map +1 -1
  695. package/dist/modes/interactive/interactive-editor-actions.js +4 -1
  696. package/dist/modes/interactive/interactive-editor-actions.js.map +1 -1
  697. package/dist/modes/interactive/interactive-extension-custom-ui.js +13 -3
  698. package/dist/modes/interactive/interactive-extension-custom-ui.js.map +1 -1
  699. package/dist/modes/interactive/interactive-extension-runtime.js +4 -2
  700. package/dist/modes/interactive/interactive-extension-runtime.js.map +1 -1
  701. package/dist/modes/interactive/interactive-extension-widgets.js +6 -8
  702. package/dist/modes/interactive/interactive-extension-widgets.js.map +1 -1
  703. package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
  704. package/dist/modes/interactive/interactive-input-handling.js +43 -3
  705. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  706. package/dist/modes/interactive/interactive-mode-base.d.ts +7 -0
  707. package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
  708. package/dist/modes/interactive/interactive-mode-base.js +9 -2
  709. package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
  710. package/dist/modes/interactive/interactive-mode-deps.d.ts +1 -1
  711. package/dist/modes/interactive/interactive-mode-deps.d.ts.map +1 -1
  712. package/dist/modes/interactive/interactive-mode-deps.js +1 -1
  713. package/dist/modes/interactive/interactive-mode-deps.js.map +1 -1
  714. package/dist/modes/interactive/interactive-mode-helpers.d.ts +5 -0
  715. package/dist/modes/interactive/interactive-mode-helpers.d.ts.map +1 -1
  716. package/dist/modes/interactive/interactive-mode-helpers.js +9 -0
  717. package/dist/modes/interactive/interactive-mode-helpers.js.map +1 -1
  718. package/dist/modes/interactive/interactive-mode-surface.d.ts +10 -2
  719. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  720. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  721. package/dist/modes/interactive/interactive-model-routing.d.ts.map +1 -1
  722. package/dist/modes/interactive/interactive-model-routing.js +63 -21
  723. package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
  724. package/dist/modes/interactive/interactive-prompt-turn.js +1 -1
  725. package/dist/modes/interactive/interactive-prompt-turn.js.map +1 -1
  726. package/dist/modes/interactive/interactive-render-chat.d.ts.map +1 -1
  727. package/dist/modes/interactive/interactive-render-chat.js +71 -10
  728. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  729. package/dist/modes/interactive/interactive-resource-rendering.js +9 -18
  730. package/dist/modes/interactive/interactive-resource-rendering.js.map +1 -1
  731. package/dist/modes/interactive/interactive-selectors.js +106 -57
  732. package/dist/modes/interactive/interactive-selectors.js.map +1 -1
  733. package/dist/modes/interactive/interactive-session-routing.js +10 -5
  734. package/dist/modes/interactive/interactive-session-routing.js.map +1 -1
  735. package/dist/modes/interactive/interactive-session-runtime.d.ts +3 -0
  736. package/dist/modes/interactive/interactive-session-runtime.d.ts.map +1 -1
  737. package/dist/modes/interactive/interactive-session-runtime.js +11 -0
  738. package/dist/modes/interactive/interactive-session-runtime.js.map +1 -1
  739. package/dist/modes/interactive/interactive-slash-commands.js +3 -0
  740. package/dist/modes/interactive/interactive-slash-commands.js.map +1 -1
  741. package/dist/modes/interactive/interactive-startup-chat-container.d.ts +5 -1
  742. package/dist/modes/interactive/interactive-startup-chat-container.d.ts.map +1 -1
  743. package/dist/modes/interactive/interactive-startup-chat-container.js +8 -3
  744. package/dist/modes/interactive/interactive-startup-chat-container.js.map +1 -1
  745. package/dist/modes/interactive/interactive-startup-trust.d.ts +2 -0
  746. package/dist/modes/interactive/interactive-startup-trust.d.ts.map +1 -1
  747. package/dist/modes/interactive/interactive-startup-trust.js +21 -0
  748. package/dist/modes/interactive/interactive-startup-trust.js.map +1 -1
  749. package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
  750. package/dist/modes/interactive/interactive-startup.js +39 -17
  751. package/dist/modes/interactive/interactive-startup.js.map +1 -1
  752. package/dist/modes/interactive/interactive-task-projection.d.ts.map +1 -1
  753. package/dist/modes/interactive/interactive-task-projection.js +11 -1
  754. package/dist/modes/interactive/interactive-task-projection.js.map +1 -1
  755. package/dist/modes/interactive/resume-catalog.d.ts.map +1 -1
  756. package/dist/modes/interactive/resume-catalog.js +1 -0
  757. package/dist/modes/interactive/resume-catalog.js.map +1 -1
  758. package/dist/modes/interactive/theme/theme-controller.d.ts +6 -1
  759. package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -1
  760. package/dist/modes/interactive/theme/theme-controller.js +19 -1
  761. package/dist/modes/interactive/theme/theme-controller.js.map +1 -1
  762. package/dist/modes/interactive-engine/engine-child-liveness.d.ts +2 -0
  763. package/dist/modes/interactive-engine/engine-child-liveness.d.ts.map +1 -1
  764. package/dist/modes/interactive-engine/engine-child-liveness.js +2 -0
  765. package/dist/modes/interactive-engine/engine-child-liveness.js.map +1 -1
  766. package/dist/modes/interactive-engine/engine-custom-ui.d.ts.map +1 -1
  767. package/dist/modes/interactive-engine/engine-custom-ui.js +54 -4
  768. package/dist/modes/interactive-engine/engine-custom-ui.js.map +1 -1
  769. package/dist/modes/interactive-engine/engine-render-service.d.ts.map +1 -1
  770. package/dist/modes/interactive-engine/engine-render-service.js +21 -2
  771. package/dist/modes/interactive-engine/engine-render-service.js.map +1 -1
  772. package/dist/modes/interactive-engine/extension-ui-bridge.d.ts +4 -2
  773. package/dist/modes/interactive-engine/extension-ui-bridge.d.ts.map +1 -1
  774. package/dist/modes/interactive-engine/extension-ui-bridge.js +4 -0
  775. package/dist/modes/interactive-engine/extension-ui-bridge.js.map +1 -1
  776. package/dist/modes/interactive-engine/isolated-runtime.d.ts +39 -3
  777. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  778. package/dist/modes/interactive-engine/isolated-runtime.js +219 -29
  779. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  780. package/dist/modes/interactive-engine/protocol.d.ts +33 -1
  781. package/dist/modes/interactive-engine/protocol.d.ts.map +1 -1
  782. package/dist/modes/interactive-engine/protocol.js +40 -2
  783. package/dist/modes/interactive-engine/protocol.js.map +1 -1
  784. package/dist/modes/interactive-engine/remote-command-catalog.d.ts +2 -2
  785. package/dist/modes/interactive-engine/remote-command-catalog.d.ts.map +1 -1
  786. package/dist/modes/interactive-engine/remote-command-catalog.js +7 -3
  787. package/dist/modes/interactive-engine/remote-command-catalog.js.map +1 -1
  788. package/dist/modes/interactive-engine/remote-component.d.ts.map +1 -1
  789. package/dist/modes/interactive-engine/remote-component.js +31 -5
  790. package/dist/modes/interactive-engine/remote-component.js.map +1 -1
  791. package/dist/modes/interactive-engine/remote-renderer.d.ts +20 -12
  792. package/dist/modes/interactive-engine/remote-renderer.d.ts.map +1 -1
  793. package/dist/modes/interactive-engine/remote-renderer.js +100 -34
  794. package/dist/modes/interactive-engine/remote-renderer.js.map +1 -1
  795. package/dist/modes/print-mode.d.ts.map +1 -1
  796. package/dist/modes/print-mode.js +4 -1
  797. package/dist/modes/print-mode.js.map +1 -1
  798. package/dist/modes/rpc/agent-panel-bridge.d.ts +7 -0
  799. package/dist/modes/rpc/agent-panel-bridge.d.ts.map +1 -1
  800. package/dist/modes/rpc/agent-panel-bridge.js +119 -114
  801. package/dist/modes/rpc/agent-panel-bridge.js.map +1 -1
  802. package/dist/modes/rpc/rpc-client-process.d.ts +2 -1
  803. package/dist/modes/rpc/rpc-client-process.d.ts.map +1 -1
  804. package/dist/modes/rpc/rpc-client-process.js +2 -1
  805. package/dist/modes/rpc/rpc-client-process.js.map +1 -1
  806. package/dist/modes/rpc/rpc-client.d.ts +8 -0
  807. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  808. package/dist/modes/rpc/rpc-client.js +5 -1
  809. package/dist/modes/rpc/rpc-client.js.map +1 -1
  810. package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
  811. package/dist/modes/rpc/rpc-command-handler.js +19 -2
  812. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  813. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  814. package/dist/modes/rpc/rpc-mode.js +4 -2
  815. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  816. package/dist/modes/rpc/rpc-session-binding.d.ts.map +1 -1
  817. package/dist/modes/rpc/rpc-session-binding.js +7 -0
  818. package/dist/modes/rpc/rpc-session-binding.js.map +1 -1
  819. package/dist/modes/rpc/rpc-types.d.ts +13 -1
  820. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  821. package/dist/modes/rpc/rpc-types.js.map +1 -1
  822. package/dist/utils/interactive-engine-bootstrap.d.ts +3 -0
  823. package/dist/utils/interactive-engine-bootstrap.d.ts.map +1 -1
  824. package/dist/utils/interactive-engine-bootstrap.js +25 -0
  825. package/dist/utils/interactive-engine-bootstrap.js.map +1 -1
  826. package/dist/utils/interactive-engine-env.d.ts +3 -0
  827. package/dist/utils/interactive-engine-env.d.ts.map +1 -1
  828. package/dist/utils/interactive-engine-env.js +1 -0
  829. package/dist/utils/interactive-engine-env.js.map +1 -1
  830. package/dist/utils/shell.d.ts +2 -0
  831. package/dist/utils/shell.d.ts.map +1 -1
  832. package/dist/utils/shell.js +3 -3
  833. package/dist/utils/shell.js.map +1 -1
  834. package/docs/background-tasks.md +32 -37
  835. package/docs/compaction.md +2 -2
  836. package/docs/computer-use.md +2 -0
  837. package/docs/development.md +11 -1
  838. package/docs/environment-variables.md +2 -0
  839. package/docs/extensions/api-reference.md +7 -3
  840. package/docs/extensions/authoring.md +3 -1
  841. package/docs/extensions/events.md +3 -1
  842. package/docs/extensions/ui.md +2 -0
  843. package/docs/guides/resume-on-any-machine.md +3 -1
  844. package/docs/intercom/reference.md +1 -1
  845. package/docs/intercom.md +3 -3
  846. package/docs/keybindings.md +6 -2
  847. package/docs/libraries/tui.md +4 -0
  848. package/docs/providers.md +1 -1
  849. package/docs/rpc/protocol.md +6 -4
  850. package/docs/sdk/reference.md +10 -4
  851. package/docs/sdk.md +5 -2
  852. package/docs/security.md +5 -1
  853. package/docs/session-format.md +1 -1
  854. package/docs/sessions.md +16 -0
  855. package/docs/settings.md +2 -2
  856. package/docs/skills.md +3 -3
  857. package/docs/storage.md +25 -4
  858. package/docs/subagents.md +42 -45
  859. package/docs/tui.md +1 -1
  860. package/docs/usage.md +3 -1
  861. package/docs/workflows/api-reference.md +3 -1
  862. package/docs/workflows/authoring.md +1 -1
  863. package/docs/workflows/operations.md +21 -14
  864. package/docs/workflows.md +1 -1
  865. package/docs/worktree-snapshots.md +10 -8
  866. package/npm-shrinkwrap.json +71 -49
  867. package/package.json +9 -8
  868. package/schemas/settings.schema.json +1 -1
@@ -3,6 +3,36 @@ import { StorageWriteLockTimeoutError } from "../storage/errors.js";
3
3
  import { applyStorageMigrations, withShortSchemaLockWaits } from "../storage/migrations.js";
4
4
  import { renderStorageIdentifiers, storageMigrationTable, validateStoragePrefix } from "../storage/prefix.js";
5
5
  import { RUN_JOURNAL_SCHEMA_VERSION, RUN_JOURNAL_SCHEMA_VERSION_UNCHUNKED } from "../storage/run-journal.js";
6
+ /**
7
+ * The key under which a failed rename's error carries the trigger or view that stopped it, once confirmed in the
8
+ * database (#5622); `WorkspaceCollectionError` names it in its hint. A `Symbol.for` key, shared without an import.
9
+ */
10
+ const RENAME_BLOCKER = Symbol.for("atomic-snapshots/rename-blocker@1");
11
+ /** What SQLite writes after an object's name when the object stops a schema change only once the change is made. */
12
+ const RENAME_BLOCKER_WHEN = [" after rename", " after drop column"];
13
+ /**
14
+ * Every trigger or view that `error`, a failed rename, or an error it wraps can name. SQLite names a trigger or view
15
+ * that no longer compiles, such as one that refers to a dropped table, as `error in <type> <name>[ <when>]: <reason>`,
16
+ * and drivers add their own prefix. The name is not quoted, so `error in view sales after rename: …` can name a view
17
+ * `sales after rename` or a view `sales`, and a name can hold `: `. Only the database can tell which object it is.
18
+ */
19
+ function renameBlockerCandidates(error) {
20
+ const candidates = [];
21
+ let current = error;
22
+ for (let depth = 0; depth < 8 && current instanceof Error; depth++, current = current.cause)
23
+ for (const match of current.message.matchAll(/\berror in (trigger|view) /gu)) {
24
+ const type = match[1];
25
+ const rest = current.message.slice(match.index + match[0].length);
26
+ for (let end = rest.indexOf(": "); end !== -1; end = rest.indexOf(": ", end + 1)) {
27
+ const name = rest.slice(0, end);
28
+ candidates.push({ type, name });
29
+ for (const when of RENAME_BLOCKER_WHEN)
30
+ if (name.endsWith(when))
31
+ candidates.push({ type, name: name.slice(0, -when.length) });
32
+ }
33
+ }
34
+ return candidates;
35
+ }
6
36
  /** Every blob hash a snapshot needs to be restored: its chain's patches and its bundle. */
7
37
  export function snapshotBlobHashes(snapshot) {
8
38
  const hashes = snapshot.chain.flatMap((link) => (link.patch === null ? [] : [link.patch]));
@@ -148,8 +178,25 @@ const yieldToEventLoop = () => new Promise((resolve) => setImmediate(resolve));
148
178
  */
149
179
  export const DEGRADED_RESTORE_RETENTION_DAYS = 30;
150
180
  const DEGRADED_PIN_SECONDS = DEGRADED_RESTORE_RETENTION_DAYS * 24 * 60 * 60;
151
- /** Blobs one collection batch examines and deletes in one write transaction. */
181
+ /** Aged blobs one page of a collection examines, read from the age index in one statement. */
152
182
  export const SNAPSHOT_COLLECTION_BATCH = 256;
183
+ /**
184
+ * The most blobs one delete batch of a collection deletes, in one write transaction (#5530). Deleting a blob also
185
+ * deletes its chunks. On a chunk table an earlier release created `WITHOUT ROWID`, until collection moves it (#5541),
186
+ * finding them reads whole chunks of the rows each seek compares: about 3.5 ms per blob on a large store with its
187
+ * pages cached, so a batch of this many takes about 30 ms.
188
+ * The transaction also checks again, in one statement, the sessions that reference the batch's blobs: at most
189
+ * {@link SNAPSHOT_COLLECTION_SESSION_REFS} snapshot entries of them.
190
+ */
191
+ export const SNAPSHOT_COLLECTION_DELETE_BATCH = 8;
192
+ /**
193
+ * The most snapshot entries of sessions one collection statement walks to find the snapshots those sessions retain
194
+ * (#5530). Each session's retained snapshots are found by walking the snapshot entries on its open branches, about
195
+ * 2 µs per entry with its pages cached, so a statement over this many takes a few milliseconds, and the event loop
196
+ * gets a turn between statements. A session with more entries than this is walked in a statement of its own, and so
197
+ * is a blob whose sessions hold more together when its delete batch checks them again.
198
+ */
199
+ export const SNAPSHOT_COLLECTION_SESSION_REFS = 2_048;
153
200
  /**
154
201
  * The most bytes of legacy blobs one write transaction of a collection stamps or moves. A blob stored before blob ages
155
202
  * has an unknown age, which collection stamps; changing one column rewrites the whole row on SQLite and libSQL, its
@@ -159,6 +206,37 @@ export const SNAPSHOT_COLLECTION_BATCH = 256;
159
206
  * proportional to that value's size.
160
207
  */
161
208
  export const SNAPSHOT_LEGACY_STAMP_BYTES = 16 * SNAPSHOT_BLOB_CHUNK_BYTES;
209
+ /**
210
+ * The most chunk rows one write transaction copies or frees while collection moves a chunk table an earlier release
211
+ * created `WITHOUT ROWID` to the row layout (#5541). Each costs a read of its 1 MiB, cold on a first move, under the
212
+ * write lock.
213
+ */
214
+ export const SNAPSHOT_CHUNK_MOVE_ROWS = 4;
215
+ /**
216
+ * The free space a chunk table's move to the row layout leaves on the file system of a SQLite or libSQL database file
217
+ * beyond its copy, at least (#5694): the move starts only when the disk has room for the copy, its write-ahead log and
218
+ * this much more, so other writes keep room on the disk.
219
+ */
220
+ export const SNAPSHOT_CHUNK_MOVE_HEADROOM_BYTES = 64 * 1024 * 1024;
221
+ /**
222
+ * Whether `error`, or a failure it wraps, says the database's disk is full or failed to read or write: SQLite's
223
+ * `SQLITE_FULL` or `SQLITE_IOERR` and its extended codes (node:sqlite's `errcode`, libSQL's code or `rawCode`), as a
224
+ * libSQL server answers when its disk fills, or PostgreSQL's `disk_full` (53100) or `io_error` (58030).
225
+ */
226
+ function isStorageSpaceFailure(error) {
227
+ const seen = new Set();
228
+ for (let cause = error; typeof cause === "object" && cause !== null && !seen.has(cause);) {
229
+ seen.add(cause);
230
+ const { code, errcode, rawCode } = cause;
231
+ if (typeof code === "string" && /^(?:SQLITE_FULL|SQLITE_IOERR(?:_\w+)?|53100|58030)$/.test(code))
232
+ return true;
233
+ const number = errcode ?? rawCode;
234
+ if (typeof number === "number" && ((number & 0xff) === 13 || (number & 0xff) === 10))
235
+ return true;
236
+ cause = cause.cause;
237
+ }
238
+ return false;
239
+ }
162
240
  /** Rows of one referencing table that one backfill transaction indexes. */
163
241
  export const SNAPSHOT_INDEX_BACKFILL_BATCH = 500;
164
242
  /**
@@ -182,6 +260,138 @@ export const SNAPSHOT_COLLECTION_LOCK_RETRY_MAX_MS = 1_000;
182
260
  function collectableAge(graceSeconds) {
183
261
  return graceSeconds === 0 ? 0 : graceSeconds + 1;
184
262
  }
263
+ /**
264
+ * How long the light statements of a sweep, such as reading what walking a session costs, may hold the event loop
265
+ * together before the sweep gives it a turn, in milliseconds. Counting a session's snapshot entries reads them: a few
266
+ * milliseconds for a large session whose pages are not cached, so each session is counted in a statement of its own.
267
+ */
268
+ const SWEEP_TURN_MS = 8;
269
+ /**
270
+ * How long a sweep goes without a write before it renews its claim in a transaction of its own: a quarter of the claim
271
+ * lease, so pages with nothing to delete, which write nothing else, never let the lease run out.
272
+ */
273
+ const SWEEP_CLAIM_RENEWAL_MS = (SNAPSHOT_COLLECTION_LEASE_SECONDS * 1_000) / 4;
274
+ /**
275
+ * Groups `costs`' sessions, in order, into groups whose costs add up to at most {@link SNAPSHOT_COLLECTION_SESSION_REFS};
276
+ * a session that costs more is a group of its own.
277
+ */
278
+ function sessionGroups(costs) {
279
+ const groups = [];
280
+ let group = [];
281
+ let total = 0;
282
+ for (const [session, cost] of costs) {
283
+ if (group.length > 0 && total + cost > SNAPSHOT_COLLECTION_SESSION_REFS) {
284
+ groups.push(group);
285
+ group = [];
286
+ total = 0;
287
+ }
288
+ group.push(session);
289
+ total += cost;
290
+ }
291
+ if (group.length > 0)
292
+ groups.push(group);
293
+ return groups;
294
+ }
295
+ /**
296
+ * The turns of the event loop between the steps of a sweep that hold it, such as a statement that walks sessions, a
297
+ * delete batch or a page: {@link next} gives the loop a turn when a step has held it since the last turn, then checks
298
+ * the sweep's abort signal.
299
+ */
300
+ class SweepTurns {
301
+ signal;
302
+ yieldTurn;
303
+ holding = false;
304
+ turnedAt = performance.now();
305
+ constructor(options, yieldTurn) {
306
+ this.signal = options.signal;
307
+ this.yieldTurn = yieldTurn;
308
+ }
309
+ async next() {
310
+ if (this.holding) {
311
+ this.holding = false;
312
+ await this.yieldTurn();
313
+ this.turnedAt = performance.now();
314
+ }
315
+ this.signal?.throwIfAborted();
316
+ }
317
+ /** Records that a step held the event loop since the last turn. */
318
+ held() {
319
+ this.holding = true;
320
+ }
321
+ /** Gives the event loop a turn once the light steps since the last one have held it for {@link SWEEP_TURN_MS}. */
322
+ async light() {
323
+ if (performance.now() - this.turnedAt >= SWEEP_TURN_MS)
324
+ this.holding = true;
325
+ await this.next();
326
+ }
327
+ }
328
+ /**
329
+ * What one sweep has read about the sessions that reference its candidates (#5530): how many snapshot entries walking
330
+ * each costs, and the blobs the snapshots of those it walked retain. Only nominates candidates: each delete batch reads
331
+ * its sessions again in its transaction.
332
+ */
333
+ class SweepSessions {
334
+ costs = new Map();
335
+ walked = new Set();
336
+ retained = new Set();
337
+ /** Which of `sessions` this sweep has not walked yet. */
338
+ unwalked(sessions) {
339
+ return [...new Set(sessions)].filter((session) => !this.walked.has(session));
340
+ }
341
+ cost(costs) {
342
+ for (const [session, cost] of costs)
343
+ this.costs.set(session, cost);
344
+ }
345
+ /** Records that `sessions` were walked and that their retained snapshots reference `hashes`. */
346
+ retain(sessions, hashes) {
347
+ for (const session of sessions)
348
+ this.walked.add(session);
349
+ for (const hash of hashes)
350
+ this.retained.add(hash);
351
+ }
352
+ retains(hash) {
353
+ return this.retained.has(hash);
354
+ }
355
+ /**
356
+ * `candidates` in delete batches, in order, of at most {@link SNAPSHOT_COLLECTION_DELETE_BATCH} blobs whose sessions
357
+ * cost at most {@link SNAPSHOT_COLLECTION_SESSION_REFS} to walk together; a candidate whose own sessions cost more
358
+ * is a batch of its own.
359
+ */
360
+ batches(candidates) {
361
+ const batches = [];
362
+ let batch = [];
363
+ let sessions = new Set();
364
+ let total = 0;
365
+ const added = (candidate) => candidate.sessions.reduce((sum, session) => (sessions.has(session) ? sum : sum + (this.costs.get(session) ?? 1)), 0);
366
+ for (const candidate of candidates) {
367
+ if (batch.length === SNAPSHOT_COLLECTION_DELETE_BATCH ||
368
+ (batch.length > 0 && total + added(candidate) > SNAPSHOT_COLLECTION_SESSION_REFS)) {
369
+ batches.push({ hashes: batch, sessions: [...sessions] });
370
+ batch = [];
371
+ sessions = new Set();
372
+ total = 0;
373
+ }
374
+ total += added(candidate);
375
+ batch.push(candidate.hash);
376
+ for (const session of candidate.sessions)
377
+ sessions.add(session);
378
+ }
379
+ if (batch.length > 0)
380
+ batches.push({ hashes: batch, sessions: [...sessions] });
381
+ return batches;
382
+ }
383
+ }
384
+ /**
385
+ * The watermark and progress of a source's {@link IndexSource.version} row as this build writes it: on SQLite once its
386
+ * own backfill of the source is done, on Postgres when it installs the source's triggers (#5558). Builds 0.9.88 and
387
+ * 0.9.89 write the row as `(0, 0)`.
388
+ */
389
+ const PUBLISHED_VERSION = 1;
390
+ /**
391
+ * A row that a development build marked a source with while it removed the source's index in batches. An index an
392
+ * older build installed while it was there is never trusted as that build's finished index (#5558).
393
+ */
394
+ const rebuildRow = (source) => `${source.name}@rebuild`;
185
395
  const CHECKPOINT_EVENT = "CheckpointRecorded";
186
396
  const STATUS_EVENTS = "'RunStarted', 'StatusChanged'";
187
397
  const RELEASED_STATUSES = "'completed', 'cancelled'";
@@ -269,6 +479,13 @@ function carriedSource(d, t, carried) {
269
479
  reset: [`DELETE FROM ${t.carriedRefs} WHERE owner LIKE '${carried.owner}:%'`],
270
480
  };
271
481
  }
482
+ /** The progress row of this build's own backfill of the session entries (#5558). */
483
+ const ENTRIES_OWN_PROGRESS = "session-entries@own-progress";
484
+ /** `trigger`, its SQL holding `marker` in a comment that changes nothing it does (#5558). */
485
+ function withMarker(trigger, marker) {
486
+ const [first, ...rest] = trigger.statements;
487
+ return { ...trigger, statements: [`/* ${marker} */ ${first}`, ...rest] };
488
+ }
272
489
  function indexSources(prefix, t, d) {
273
490
  const { events, runs } = renderStorageIdentifiers("journal", { events: "events", runs: "runs" }, prefix);
274
491
  const { entries } = renderStorageIdentifiers("sessions", { entries: "entries" }, prefix);
@@ -370,6 +587,9 @@ function indexSources(prefix, t, d) {
370
587
  createTrigger(`${entries}_snapshot_pending`, "INSERT", entries, [
371
588
  `UPDATE ${t.sources} SET watermark = ${newRowOrder} WHERE source = 'session-entries' AND watermark < ${newRowOrder}`,
372
589
  `UPDATE ${t.sources} SET backfilled_through = ${newRowOrder} - 1 WHERE source = 'session-entries' AND backfilled_through >= ${newRowOrder}`,
590
+ // This build's own progress follows, so an older build's backfill of these rows is never trusted (#5558).
591
+ `UPDATE ${t.sources} SET watermark = ${newRowOrder} WHERE source = '${ENTRIES_OWN_PROGRESS}' AND watermark < ${newRowOrder}`,
592
+ `UPDATE ${t.sources} SET backfilled_through = ${newRowOrder} - 1 WHERE source = '${ENTRIES_OWN_PROGRESS}' AND backfilled_through >= ${newRowOrder}`,
373
593
  ], `NOT COALESCE(${indexComplete}, ${d.literals.true})`),
374
594
  createTrigger(`${entries}_snapshot_refs_delete`, "DELETE", entries, [
375
595
  `UPDATE ${t.sessionLinks} SET children = children - 1 WHERE session_id = OLD.session_id AND children > 0 AND entry_id = (SELECT parent_id FROM ${t.sessionLinks} WHERE session_id = OLD.session_id AND seq = OLD.seq)`,
@@ -377,11 +597,14 @@ function indexSources(prefix, t, d) {
377
597
  `DELETE FROM ${t.sessionRefs} WHERE session_id = OLD.session_id AND seq = OLD.seq`,
378
598
  `DELETE FROM ${t.sessionRecords} WHERE session_id = OLD.session_id AND seq = OLD.seq`,
379
599
  ]),
380
- ],
600
+ ].map((trigger) => withMarker(trigger, ENTRIES_OWN_PROGRESS)),
381
601
  backfill: [],
382
602
  rowwise: [...sessionLink(storedEntry), ...sessionRecord(storedEntry)],
383
603
  // The triggers that index degraded pins (#4922). Older builds install theirs under the same names (#5065).
384
604
  version: "session-entries@degraded-pins",
605
+ own: ENTRIES_OWN_PROGRESS,
606
+ marker: ENTRIES_OWN_PROGRESS,
607
+ signature: { trigger: `${entries}_snapshot_refs`, text: "degraded_from" },
385
608
  reset: [`DELETE FROM ${t.sessionLinks}`, `DELETE FROM ${t.sessionRefs}`, `DELETE FROM ${t.sessionRecords}`],
386
609
  };
387
610
  // What a shared-placement root carries to its children (#4503): the snapshot each queued pool work row carries, and
@@ -405,24 +628,41 @@ function indexSources(prefix, t, d) {
405
628
  });
406
629
  return [eventsSource, runsSource, entriesSource, workSource, rootSource];
407
630
  }
631
+ /**
632
+ * Creates a chunk table named `table` unless it exists. An ordinary table, whose primary key is an index of its own:
633
+ * a lookup reads that small index, then only the row it finds. A `WITHOUT ROWID` table, as earlier releases created,
634
+ * keeps each row in its key's b-tree, so a seek reads the whole record of every 1 MiB row it compares on its way, and
635
+ * every lookup, a delete's of a blob without chunks included, read several chunks (#5541). On Postgres both are the
636
+ * same heap table.
637
+ */
638
+ function chunkTableDefinition(table, dialect) {
639
+ const { int, text, blob } = dialect.types;
640
+ return `CREATE TABLE IF NOT EXISTS ${table} (hash ${text} NOT NULL, idx ${int} NOT NULL, data ${blob} NOT NULL, PRIMARY KEY (hash, idx))${dialect.tableOptions}`;
641
+ }
642
+ /** The trigger that deletes a blob's chunks with it, in the statement that deletes it, whoever deletes it. */
643
+ const chunksDeleteTrigger = (t) => createTrigger(`${t.blobs}_chunks_delete_all`, "DELETE", t.blobs, [
644
+ `DELETE FROM ${t.blobChunks} WHERE hash = OLD.hash`,
645
+ ]);
646
+ /**
647
+ * The tables of a chunk table's move to the row layout (#5541): `next`, the new table it fills, which then takes the
648
+ * chunk table's name, and `retired`, the old table under its new name until it is emptied and dropped.
649
+ */
650
+ const chunkMoveTables = (t) => ({ next: `${t.blobChunks}_next`, retired: `${t.blobChunks}_retired` });
408
651
  /**
409
652
  * Chunked blobs (#4954): the chunk table, the blob table's `chunks` column, 0 for a blob whose bytes are in its own row,
410
653
  * as every blob written before it was, and the trigger that deletes a blob's chunks with it. Idempotent.
411
654
  */
412
655
  async function addBlobChunks(transaction, t, dialect) {
413
- const { int, text, blob } = dialect.types;
414
- await transaction.exec(`CREATE TABLE IF NOT EXISTS ${t.blobChunks} (hash ${text} NOT NULL, idx ${int} NOT NULL, data ${blob} NOT NULL, PRIMARY KEY (hash, idx))${dialect.withoutRowidTableOptions}`);
656
+ await transaction.exec(chunkTableDefinition(t.blobChunks, dialect));
415
657
  const column = dialect.columnExists(t.blobs, "chunks");
416
658
  if (!(await transaction.get(column.sql, ...column.params))) {
417
- await transaction.exec(`ALTER TABLE ${t.blobs} ADD COLUMN chunks ${int} NOT NULL DEFAULT 0`);
659
+ await transaction.exec(`ALTER TABLE ${t.blobs} ADD COLUMN chunks ${dialect.types.int} NOT NULL DEFAULT 0`);
418
660
  }
419
661
  const trigger = dialect.schemaObjects([`${t.blobs}_chunks_delete_all`]);
420
662
  if (await transaction.get(trigger.sql, ...trigger.params))
421
663
  return;
422
664
  await transaction.exec(dialect.dropTrigger(`${t.blobs}_chunks_delete`, t.blobs, true));
423
- await transaction.exec(dialect.renderTrigger(createTrigger(`${t.blobs}_chunks_delete_all`, "DELETE", t.blobs, [
424
- `DELETE FROM ${t.blobChunks} WHERE hash = OLD.hash`,
425
- ])));
665
+ await transaction.exec(dialect.renderTrigger(chunksDeleteTrigger(t)));
426
666
  }
427
667
  /** Creates the blob table and the tables of its reference index that are missing. */
428
668
  async function createSnapshotIndexTables(transaction, t, prefix, dialect) {
@@ -505,8 +745,32 @@ async function installSource(transaction, dialect, t, source) {
505
745
  await transaction.exec(dialect.dropTrigger(trigger.name, trigger.table));
506
746
  await transaction.exec(source.triggers.map((trigger) => dialect.renderTrigger(trigger)).join("\n"));
507
747
  await transaction.run(`INSERT INTO ${t.sources} (source, watermark, backfilled_through) SELECT ?, COALESCE(MAX(${dialect.rowOrder()}), 0), 0 FROM ${source.table} WHERE true ${REPLACE_PROGRESS}`, source.name);
508
- if (source.version !== undefined)
509
- await transaction.run(`INSERT INTO ${t.sources} (source, watermark, backfilled_through) VALUES (?, 0, 0) ${REPLACE_PROGRESS}`, source.version);
748
+ if (source.own !== undefined)
749
+ await transaction.run(`INSERT INTO ${t.sources} (source, watermark, backfilled_through) SELECT ?, watermark, 0 FROM ${t.sources} WHERE source = ? ${REPLACE_PROGRESS}`, source.own, source.name);
750
+ await transaction.run(`DELETE FROM ${t.sources} WHERE source = ?`, rebuildRow(source));
751
+ if (source.version === undefined)
752
+ return;
753
+ if (!withholdsVersion(dialect, source)) {
754
+ await publishVersion(transaction, t, source);
755
+ return;
756
+ }
757
+ // A table with no row yet is backfilled as it is installed; any other is published once its backfill is done.
758
+ const installed = await transaction.get(`SELECT watermark FROM ${t.sources} WHERE source = ?`, source.name);
759
+ if (Number(installed?.watermark) === 0)
760
+ await publishVersion(transaction, t, source);
761
+ else
762
+ await transaction.run(`DELETE FROM ${t.sources} WHERE source = ?`, source.version);
763
+ }
764
+ /**
765
+ * Whether this build writes `source`'s {@link IndexSource.version} row only once its own backfill of the source is done:
766
+ * on SQLite and libSQL, which builds before 0.9.88 also open (#5558).
767
+ */
768
+ function withholdsVersion(dialect, source) {
769
+ return dialect.name === "sqlite" && source.version !== undefined && source.own !== undefined;
770
+ }
771
+ /** Writes `source`'s version row as this build's, its own backfill of the source being done (#5558). */
772
+ async function publishVersion(transaction, t, source) {
773
+ await transaction.run(`INSERT INTO ${t.sources} (source, watermark, backfilled_through) VALUES (?, ?, ?) ${REPLACE_PROGRESS}`, source.version, PUBLISHED_VERSION, PUBLISHED_VERSION);
510
774
  }
511
775
  /**
512
776
  * Installs the index triggers of every referencing table that exists and lacks them, except a source whose rebuild is
@@ -521,26 +785,82 @@ async function installMissingSources(transaction, t, prefix, dialect) {
521
785
  /** Which referencing tables exist, whether each has all its triggers and a source row, and whether its backfill is done. */
522
786
  async function readSourceStates(executor, dialect, t, sources) {
523
787
  const names = sources.flatMap((source) => [source.table, ...source.triggers.map((trigger) => trigger.name)]);
524
- const objects = dialect.schemaObjects(names);
525
- const present = new Set((await executor.all(objects.sql, ...objects.params)).map((row) => row.name));
788
+ // Builds before 0.9.88 open SQLite and libSQL databases only, so only there can a trigger of this build's name be
789
+ // one that indexes less.
790
+ const sqlite = dialect.name === "sqlite";
791
+ const signatures = sqlite ? sources.flatMap((source) => source.signature ?? []) : [];
792
+ const markers = sqlite
793
+ ? sources.flatMap((source) => source.marker === undefined
794
+ ? []
795
+ : source.triggers.map((trigger) => ({ trigger: trigger.name, text: source.marker })))
796
+ : [];
797
+ const holds = (checks) => checks.length === 0 ? "NULL" : `CASE ${checks.map(() => "WHEN name = ? THEN instr(sql, ?) > 0").join(" ")} END`;
798
+ const objects = signatures.length + markers.length === 0
799
+ ? dialect.schemaObjects(names)
800
+ : {
801
+ sql: `SELECT name, ${holds(signatures)} AS signed, ${holds(markers)} AS marked FROM sqlite_schema WHERE name IN (${names.map(() => "?").join(", ")})`,
802
+ params: [...signatures, ...markers].flatMap((check) => [check.trigger, check.text]).concat(names),
803
+ };
804
+ const objectRows = await executor.all(objects.sql, ...objects.params);
805
+ const present = new Set(objectRows.map((row) => row.name));
806
+ // Whether each checked trigger's SQL holds this build's text; every other object reads null.
807
+ const checked = (column) => new Map(objectRows
808
+ .filter((row) => row[column] !== null && row[column] !== undefined)
809
+ .map((row) => [row.name, Number(row[column]) === 1]));
810
+ const signed = checked("signed");
811
+ const marked = checked("marked");
526
812
  const progress = new Map((await executor.all(`SELECT source, watermark, backfilled_through FROM ${t.sources}`)).map((row) => [row.source, row]));
527
813
  return sources
528
814
  .filter((source) => present.has(source.table))
529
815
  .map((source) => {
530
816
  const row = progress.get(source.name);
531
- // A source whose triggers an older build installed is indexed again by collection, as after an upgrade.
532
- const foreign = source.version !== undefined && !progress.has(source.version);
817
+ const version = source.version === undefined ? undefined : progress.get(source.version);
818
+ const own = source.own === undefined ? undefined : progress.get(source.own);
819
+ const ownDone = own !== undefined && row !== undefined && Number(own.backfilled_through) >= Number(row.watermark);
820
+ // An index an older build installed while a rebuild row was there, which 0.9.87 may have indexed since (#5558).
821
+ const reinstalled = row !== undefined && progress.has(rebuildRow(source));
822
+ // On SQLite, a reference trigger without this build's text is a build's before 0.9.88, installed after this
823
+ // build's went missing (#5558).
824
+ const unsigned = source.signature !== undefined && signed.get(source.signature.trigger) === false;
825
+ // Every trigger the source has is this build's. One a build before 0.9.88 installed again after it went
826
+ // missing is not, even when its SQL is the same in every build otherwise (#5558).
827
+ const mine = source.marker !== undefined &&
828
+ source.triggers.every((trigger) => !present.has(trigger.name) || marked.get(trigger.name) === true);
829
+ let foreign;
830
+ // Whether the backfill is done for this build, besides the source's own progress row.
831
+ let trusted;
832
+ if (withholdsVersion(dialect, source)) {
833
+ // This build's install whose backfill is not done yet, which holds back the version row (#5558).
834
+ const pending = version === undefined && own !== undefined && mine;
835
+ // A row of 0 is a build of 0.9.88 or 0.9.89's, whose finished backfill indexed what this build's does, unless
836
+ // it installed the index while a rebuild row was there: this build takes it over then. This build publishes
837
+ // its own once its own progress reaches the watermark, which it must still hold.
838
+ const published = version !== undefined && Number(version.watermark) === PUBLISHED_VERSION;
839
+ foreign = unsigned || (version === undefined && !pending) || (published && !mine);
840
+ trusted = published ? ownDone : version !== undefined && !reinstalled;
841
+ }
842
+ else {
843
+ // A source whose triggers an older build installed is indexed again by collection, as after an upgrade.
844
+ foreign = unsigned || (source.version !== undefined && version === undefined) || reinstalled;
845
+ // Rows an older build indexed with its statements past this build's own progress are not backfilled.
846
+ trusted = own === undefined || ownDone;
847
+ }
848
+ const installed = row !== undefined &&
849
+ !foreign &&
850
+ Number(row.watermark) >= 0 &&
851
+ source.triggers.every((trigger) => present.has(trigger.name));
852
+ const backfilled = row !== undefined &&
853
+ !foreign &&
854
+ trusted &&
855
+ Number(row.watermark) >= 0 &&
856
+ Number(row.backfilled_through) >= Number(row.watermark);
533
857
  return {
534
858
  source,
535
- installed: row !== undefined &&
536
- !foreign &&
537
- Number(row.watermark) >= 0 &&
538
- source.triggers.every((trigger) => present.has(trigger.name)),
539
- backfilled: row !== undefined &&
540
- !foreign &&
541
- Number(row.watermark) >= 0 &&
542
- Number(row.backfilled_through) >= Number(row.watermark),
859
+ installed,
860
+ backfilled,
543
861
  deferred: row !== undefined && (foreign || Number(row.watermark) === -1),
862
+ foreign,
863
+ takeover: withholdsVersion(dialect, source) && installed && version !== undefined && !backfilled,
544
864
  };
545
865
  });
546
866
  }
@@ -622,6 +942,11 @@ export class SqlSnapshotBlobStore {
622
942
  await store.installIndex();
623
943
  return store;
624
944
  }
945
+ /** A transcript-only handle has no snapshot sources to index. Binding it must not even inspect their tables. */
946
+ static forTranscriptReader(database) {
947
+ const journalMeta = renderStorageIdentifiers("journal", { meta: "meta" }).meta;
948
+ return new SqlSnapshotBlobStore(database, dialectOf(database), snapshotIndexTables(), [], journalMeta, "");
949
+ }
625
950
  /**
626
951
  * Creates the blob table and its reference index inside the caller's transaction, and indexes the referencing tables
627
952
  * that exist, so a store that creates its own tables, such as a new run journal, takes the write lock once for all
@@ -801,17 +1126,17 @@ export class SqlSnapshotBlobStore {
801
1126
  * Indexes the rows that referencing tables held before their triggers were installed, in transactions of
802
1127
  * {@link SNAPSHOT_INDEX_BACKFILL_BATCH} rows, so that the index covers every reference. A one-time cost in the number
803
1128
  * of existing rows, paid in the background by the first collection; resumes where it stopped. Does nothing once the
804
- * index is complete. Yields to the event loop between batches, and checks `signal` before each batch and rejects
805
- * with its reason.
1129
+ * index is complete. Yields to the event loop after every batch, so the next batch, of the same table or another,
1130
+ * or what follows the index, such as a sweep's first batch, starts on a turn of its own (#5530). Checks `signal`
1131
+ * before each batch and rejects with its reason.
806
1132
  */
807
1133
  async completeIndex(options = {}) {
808
1134
  for (const { source, backfilled } of await this.installIndex(options.pace, true)) {
809
1135
  if (backfilled)
810
1136
  continue;
811
- for (;;) {
1137
+ for (let done = false; !done;) {
812
1138
  options.signal?.throwIfAborted();
813
- if (await this.backfillBatch(source, options))
814
- break;
1139
+ done = await this.backfillBatch(source, options);
815
1140
  await this.betweenBatches(options.pace);
816
1141
  }
817
1142
  }
@@ -820,16 +1145,64 @@ export class SqlSnapshotBlobStore {
820
1145
  backfillBatch(source, { holder, pace, signal }) {
821
1146
  const t = this.tables;
822
1147
  const row = this.dialect.rowOrder();
1148
+ const withholds = withholdsVersion(this.dialect, source);
823
1149
  return this.write(pace, async (transaction) => {
1150
+ const [state] = await readSourceStates(transaction, this.dialect, t, [source]);
1151
+ if (state === undefined || state.backfilled)
1152
+ return true;
1153
+ if (state.foreign) {
1154
+ // A build before 0.9.88 installed its own triggers since the loop read the states: the source is installed again
1155
+ // in this transaction, its old rows removed, as at the start of a collection. Left as it is, that build could
1156
+ // index it its way, and builds 0.9.88 and 0.9.89 trust their version row (#5558).
1157
+ await withShortSchemaLockWaits(transaction, this.dialect, () => installSource(transaction, this.dialect, t, source));
1158
+ if (holder !== undefined)
1159
+ await this.renewClaim(transaction, holder);
1160
+ return false;
1161
+ }
1162
+ // A source that lost triggers meanwhile is indexed on, as its rows still need this build's statements; the sweep
1163
+ // installs its triggers again before it deletes anything.
824
1164
  const progress = await transaction.get(`SELECT watermark, backfilled_through FROM ${t.sources} WHERE source = ?`, source.name);
825
- if (progress === undefined || progress.backfilled_through >= progress.watermark)
1165
+ if (progress === undefined || progress.watermark < 0)
1166
+ return true;
1167
+ if (state.takeover) {
1168
+ // Installed by a build of 0.9.88 or 0.9.89 whose backfill is not done, which a build before 0.9.88 may have
1169
+ // indexed some of its way: this build indexes it again from its first row, with its own triggers, whose
1170
+ // pending trigger moves its own progress back, and holds the version row back until it is done, so that
1171
+ // builds 0.9.88 and 0.9.89 do not trust it meanwhile (#5558).
1172
+ await transaction.run(`INSERT INTO ${t.sources} (source, watermark, backfilled_through) VALUES (?, ?, 0) ${REPLACE_PROGRESS}`, source.own, progress.watermark);
1173
+ for (const name of [source.version, rebuildRow(source)])
1174
+ await transaction.run(`DELETE FROM ${t.sources} WHERE source = ?`, name);
1175
+ for (const trigger of source.triggers)
1176
+ await transaction.exec(this.dialect.dropTrigger(trigger.name, trigger.table));
1177
+ await transaction.exec(source.triggers.map((trigger) => this.dialect.renderTrigger(trigger)).join("\n"));
1178
+ }
1179
+ // This build's own progress (#5558): rows an older build indexed past it are indexed again. On Postgres, which
1180
+ // no build before 0.9.88 opens, a source a build of 0.9.88 or 0.9.89 installed has none: its backfill, which
1181
+ // indexes what this one does, is trusted as far as it got.
1182
+ let own = source.own === undefined
1183
+ ? undefined
1184
+ : await transaction.get(`SELECT backfilled_through FROM ${t.sources} WHERE source = ?`, source.own);
1185
+ if (source.own !== undefined && own === undefined && progress.backfilled_through < progress.watermark) {
1186
+ await transaction.run(`INSERT INTO ${t.sources} (source, watermark, backfilled_through) VALUES (?, ?, ?) ${REPLACE_PROGRESS}`, source.own, progress.watermark, progress.backfilled_through);
1187
+ own = { backfilled_through: progress.backfilled_through };
1188
+ }
1189
+ const from = own !== undefined && own.backfilled_through < progress.backfilled_through
1190
+ ? own.backfilled_through
1191
+ : progress.backfilled_through;
1192
+ // The version row says the index is this build's and complete: never while a trigger is missing, which a build
1193
+ // before 0.9.88 would install again its way under it (#5558).
1194
+ const publish = withholds && state.installed;
1195
+ if (from >= progress.watermark) {
1196
+ if (publish)
1197
+ await publishVersion(transaction, t, source);
826
1198
  return true;
827
- const { upper: lastRow } = (await transaction.get(`SELECT MAX(${row}) AS upper FROM (SELECT ${row} FROM ${source.table} WHERE ${row} > ? AND ${row} <= ? ORDER BY ${row} LIMIT ?)`, progress.backfilled_through, progress.watermark, SNAPSHOT_INDEX_BACKFILL_BATCH));
1199
+ }
1200
+ const { upper: lastRow } = (await transaction.get(`SELECT MAX(${row}) AS upper FROM (SELECT ${row} FROM ${source.table} WHERE ${row} > ? AND ${row} <= ? ORDER BY ${row} LIMIT ?)`, from, progress.watermark, SNAPSHOT_INDEX_BACKFILL_BATCH));
828
1201
  const upper = lastRow ?? progress.watermark;
829
1202
  for (const sql of source.backfill)
830
- await transaction.run(sql, progress.backfilled_through, upper);
1203
+ await transaction.run(sql, from, upper);
831
1204
  if (source.rowwise !== undefined) {
832
- const rows = await transaction.all(`SELECT ${row} AS id FROM ${source.table} WHERE ${row} > ? AND ${row} <= ? ORDER BY ${row}`, progress.backfilled_through, upper);
1205
+ const rows = await transaction.all(`SELECT ${row} AS id FROM ${source.table} WHERE ${row} > ? AND ${row} <= ? ORDER BY ${row}`, from, upper);
833
1206
  for (const { id } of rows) {
834
1207
  // Stopping between rows rolls the whole batch back, progress included, so the pass stays resumable.
835
1208
  signal?.throwIfAborted();
@@ -837,28 +1210,41 @@ export class SqlSnapshotBlobStore {
837
1210
  await transaction.run(sql, id);
838
1211
  }
839
1212
  }
840
- await transaction.run(`UPDATE ${t.sources} SET backfilled_through = ? WHERE source = ?`, upper, source.name);
1213
+ // Indexing rows again behind the source's progress, for this build's own, never moves the progress back.
1214
+ await transaction.run(`UPDATE ${t.sources} SET backfilled_through = ? WHERE source = ? AND backfilled_through < ?`, upper, source.name, upper);
1215
+ if (own !== undefined)
1216
+ await transaction.run(`UPDATE ${t.sources} SET watermark = ?, backfilled_through = ? WHERE source = ?`, progress.watermark, upper, source.own);
841
1217
  if (holder !== undefined)
842
1218
  await this.renewClaim(transaction, holder);
843
- return upper >= progress.watermark;
1219
+ const done = upper >= progress.watermark;
1220
+ // Both progress rows reach the watermark: builds 0.9.88 and 0.9.89 may trust the index now (#5558).
1221
+ if (done && publish)
1222
+ await publishVersion(transaction, t, source);
1223
+ return done;
844
1224
  });
845
1225
  }
846
1226
  /**
847
1227
  * Deletes every blob stored or re-stored at least `graceSeconds` ago on the database clock that no retained snapshot
848
- * and no snapshot dispatched work carries references, in batches of {@link SNAPSHOT_COLLECTION_BATCH}, and resolves
849
- * with the hashes deleted. Each batch is one write transaction whose delete re-checks age and references in the same
850
- * statement, so a reference published before the batch commits keeps its blob and a process killed mid-collection
851
- * leaves only garbage. Each batch's page holds only blobs it can delete, so a sweep started again after a process
852
- * exited makes progress even when the oldest blobs are all retained. Reads the reference index and the blob table's
853
- * age index, never a journal or a session. Ages are counted in whole seconds, so a blob can stay up to a second past
854
- * `graceSeconds`, never less.
1228
+ * and no snapshot dispatched work carries references, and resolves with the hashes deleted. Reads the reference index
1229
+ * and the blob table's age index, never a journal or a session. Ages are counted in whole seconds, so a blob can stay
1230
+ * up to a second past `graceSeconds`, never less.
855
1231
  *
856
- * Every batch first checks, in its own transaction, that every referencing table has its triggers and a finished
1232
+ * Pages through the aged blobs, oldest first, {@link SNAPSHOT_COLLECTION_BATCH} at a time, and keeps as candidates
1233
+ * those no retaining run, no carried work and no session retains. A session's retained snapshots are found by walking
1234
+ * its snapshot entries, at most {@link SNAPSHOT_COLLECTION_SESSION_REFS} of them per statement, once per sweep
1235
+ * (#5530). The candidates are deleted in batches, each one write transaction that finds the retained snapshots of the
1236
+ * sessions it walked for its blobs again, in one statement, and deletes only the blobs none of them retains, no other
1237
+ * session records, and that are still old and unreferenced by runs and carried work. So a reference published before
1238
+ * the batch commits keeps its blob, and a process killed mid-collection leaves only garbage. The event loop never
1239
+ * gets a turn inside a write transaction: another connection of this process that wrote then would wait for the
1240
+ * write lock while holding the event loop, and the transaction could not end until it gave up.
1241
+ *
1242
+ * Every batch first checks, in its transaction, that every referencing table has its triggers and a finished
857
1243
  * backfill, as {@link completeIndex} leaves them. When one does not, because a table appeared or lost its triggers
858
1244
  * since, nothing is deleted until the index has been completed again. A sweep repairs the index once; when it is
859
1245
  * incomplete again after that, because the schema keeps changing under it, the sweep stops without deleting
860
- * anything more and the next collection tries again. Yields to the event loop between batches, and checks `signal`
861
- * before each batch and rejects with its reason.
1246
+ * anything more and the next collection tries again. Gives the event loop a turn between statements that walk
1247
+ * sessions, between batches and between pages, and checks `signal` before each and rejects with its reason.
862
1248
  */
863
1249
  async sweep(options) {
864
1250
  const t = this.tables;
@@ -880,62 +1266,184 @@ export class SqlSnapshotBlobStore {
880
1266
  });
881
1267
  await this.betweenBatches(options.pace);
882
1268
  }
883
- const unreferenced = `NOT EXISTS (
884
- SELECT 1 FROM ${t.runRefs} AS ref WHERE ref.hash = ${t.blobs}.hash
885
- AND NOT EXISTS (SELECT 1 FROM ${t.runState} AS state WHERE state.run_id = ref.run_id AND state.retained = 0)
886
- ) AND NOT EXISTS (
887
- SELECT 1 FROM ${t.sessionRecords} AS record
888
- WHERE record.hash = ${t.blobs}.hash AND (
889
- (record.session_id, record.snapshot_id) IN (${this.sessionHeads()})
890
- OR EXISTS (SELECT 1 FROM ${t.sessionLinks} AS broken WHERE broken.session_id = record.session_id AND broken.broken = 1)
891
- )
892
- ) AND NOT EXISTS (SELECT 1 FROM ${t.carriedRefs} AS carried WHERE carried.hash = ${t.blobs}.hash)`;
893
1269
  const minimumAge = collectableAge(options.graceSeconds);
894
1270
  const deleted = [];
1271
+ const turns = new SweepTurns(options, () => this.betweenBatches(options.pace));
1272
+ let sessions = new SweepSessions();
895
1273
  let cursor;
896
1274
  let repaired = false;
1275
+ let renewedAt = Number.NEGATIVE_INFINITY;
897
1276
  for (;;) {
898
- options.signal?.throwIfAborted();
899
- const after = cursor;
900
- const batch = await this.write(options.pace, async (transaction) => {
901
- const states = await readSourceStates(transaction, this.dialect, this.tables, this.sources);
902
- if (!states.every((state) => state.installed && state.backfilled))
903
- return undefined;
904
- if (options.holder !== undefined)
905
- await this.renewClaim(transaction, options.holder);
906
- const page = await this.page(transaction, minimumAge, unreferenced, after);
907
- if (page.length === 0)
908
- return { page, deleted: [] };
909
- const rows = await transaction.all(`DELETE FROM ${t.blobs} WHERE hash IN (SELECT value FROM ${this.dialect.jsonValues("?")}) AND created_at > 0 AND created_at <= ${this.dialect.nowSeconds} - ? AND ${unreferenced} RETURNING hash`, JSON.stringify(page.map((row) => row.hash)), minimumAge);
910
- return { page, deleted: rows.map((row) => row.hash) };
911
- });
912
- if (batch === undefined) {
1277
+ await turns.next();
1278
+ if (options.holder !== undefined && performance.now() - renewedAt >= SWEEP_CLAIM_RENEWAL_MS) {
1279
+ // Pages that hold nothing to delete write nothing else; the claim is renewed when the sweep starts and then
1280
+ // at least once per quarter lease.
1281
+ const holder = options.holder;
1282
+ await this.write(options.pace, (transaction) => this.renewClaim(transaction, holder));
1283
+ renewedAt = performance.now();
1284
+ }
1285
+ const page = await this.page(minimumAge, cursor);
1286
+ const candidates = await this.unretainedOf(page.map((row) => row.hash), sessions, turns);
1287
+ let incomplete = false;
1288
+ for (const batch of sessions.batches(candidates)) {
1289
+ // Every delete batch starts on a turn of its own and ends with one: never a turn while it holds the write lock.
1290
+ await turns.next();
1291
+ const removed = await this.deleteUnretained(batch, minimumAge, options);
1292
+ turns.held();
1293
+ if (removed === undefined) {
1294
+ incomplete = true;
1295
+ break;
1296
+ }
1297
+ renewedAt = performance.now();
1298
+ deleted.push(...removed);
1299
+ options.onBatch?.(removed);
1300
+ }
1301
+ if (incomplete) {
913
1302
  if (repaired)
914
1303
  return deleted;
915
1304
  repaired = true;
916
1305
  await this.completeIndex(options);
1306
+ sessions = new SweepSessions();
917
1307
  continue;
918
1308
  }
919
- deleted.push(...batch.deleted);
920
- options.onBatch?.(batch.deleted);
921
- if (batch.page.length < SNAPSHOT_COLLECTION_BATCH) {
1309
+ if (page.length < SNAPSHOT_COLLECTION_BATCH) {
922
1310
  await this.stampLegacyAges(options);
1311
+ await this.moveChunksToRowTable(options);
923
1312
  return deleted;
924
1313
  }
925
- cursor = batch.page.at(-1);
926
- await this.betweenBatches(options.pace);
1314
+ cursor = page.at(-1);
1315
+ // Every page holds the event loop, also one whose blobs runs, carried work or sessions this sweep walked
1316
+ // already retain, which walks no session and deletes nothing: the next page starts after a turn (#5530).
1317
+ turns.held();
1318
+ }
1319
+ }
1320
+ /**
1321
+ * Which of `hashes` no retaining run, no carried work and no session retains, as far as these reads see: the sweep's
1322
+ * candidates, which a delete batch checks again in its transaction. Finds the retained blobs of each session that
1323
+ * references one of them and that `sessions` has not walked yet, in statements of at most
1324
+ * {@link SNAPSHOT_COLLECTION_SESSION_REFS} snapshot entries, with a turn between them.
1325
+ */
1326
+ async unretainedOf(hashes, sessions, turns) {
1327
+ if (hashes.length === 0)
1328
+ return [];
1329
+ const t = this.tables;
1330
+ const free = await this.database.all(`SELECT value AS hash FROM ${this.dialect.jsonValues("?")} WHERE ${this.unreferencedByRuns("value")}`, JSON.stringify(hashes));
1331
+ if (free.length === 0)
1332
+ return [];
1333
+ const referencing = new Map(free.map((row) => [row.hash, []]));
1334
+ for (const { hash, session_id } of await this.database.all(`SELECT DISTINCT hash, session_id FROM ${t.sessionRecords} WHERE hash IN (SELECT value FROM ${this.dialect.jsonValues("?")})`, JSON.stringify([...referencing.keys()])))
1335
+ referencing.get(hash)?.push(session_id);
1336
+ const unwalked = sessions.unwalked([...referencing.values()].flat());
1337
+ if (unwalked.length > 0) {
1338
+ const costs = await this.sessionCosts(unwalked, () => turns.light());
1339
+ sessions.cost(costs);
1340
+ for (const group of sessionGroups(costs)) {
1341
+ await turns.next();
1342
+ sessions.retain(group, await this.retainedBySessions(group));
1343
+ turns.held();
1344
+ }
1345
+ }
1346
+ return [...referencing]
1347
+ .filter(([hash]) => !sessions.retains(hash))
1348
+ .map(([hash, referencedBy]) => ({ hash, sessions: referencedBy }));
1349
+ }
1350
+ /**
1351
+ * Deletes the blobs of `batch` that are still old and that no retaining run, no carried work and no session retains,
1352
+ * in one write transaction, and resolves with the hashes deleted; undefined, deleting nothing, when the reference
1353
+ * index is incomplete. The transaction checks the batch's blobs again in one statement, so what it sees is what
1354
+ * holds when the batch commits: the snapshots the batch's sessions, those the sweep walked for its blobs, retain now,
1355
+ * and the sessions that record its blobs now. A blob a session the sweep did not walk records, such as one created
1356
+ * since, is kept; the next collection walks that session. Nothing in the transaction waits for a turn of the event
1357
+ * loop (#5530).
1358
+ */
1359
+ deleteUnretained(batch, minimumAge, options) {
1360
+ const t = this.tables;
1361
+ return this.write(options.pace, async (transaction) => {
1362
+ const states = await readSourceStates(transaction, this.dialect, this.tables, this.sources);
1363
+ if (!states.every((state) => state.installed && state.backfilled))
1364
+ return undefined;
1365
+ if (options.holder !== undefined)
1366
+ await this.renewClaim(transaction, options.holder);
1367
+ const kept = new Set(await this.keptBySessions(transaction, batch));
1368
+ const unretained = batch.hashes.filter((hash) => !kept.has(hash));
1369
+ if (unretained.length === 0)
1370
+ return [];
1371
+ const rows = await transaction.all(`DELETE FROM ${t.blobs} WHERE hash IN (SELECT value FROM ${this.dialect.jsonValues("?")}) AND created_at > 0 AND created_at <= ${this.dialect.nowSeconds} - ? AND ${this.unreferencedByRuns(`${t.blobs}.hash`)} RETURNING hash`, JSON.stringify(unretained), minimumAge);
1372
+ return rows.map((row) => row.hash);
1373
+ });
1374
+ }
1375
+ /** A condition that no retaining run and no carried work references the blob `hash` names. */
1376
+ unreferencedByRuns(hash) {
1377
+ const t = this.tables;
1378
+ return `NOT EXISTS (
1379
+ SELECT 1 FROM ${t.runRefs} AS ref WHERE ref.hash = ${hash}
1380
+ AND NOT EXISTS (SELECT 1 FROM ${t.runState} AS state WHERE state.run_id = ref.run_id AND state.retained = 0)
1381
+ ) AND NOT EXISTS (SELECT 1 FROM ${t.carriedRefs} AS carried WHERE carried.hash = ${hash})`;
1382
+ }
1383
+ /**
1384
+ * How many snapshot entries finding the retained snapshots of each of `sessions` walks: the entries of the session,
1385
+ * once for each distinct latest snapshot entry of its open leaves, which bounds the entries on those leaves'
1386
+ * branches. Reads one session per statement, waiting for `turn` between statements.
1387
+ */
1388
+ async sessionCosts(sessions, turn) {
1389
+ const t = this.tables;
1390
+ const costs = new Map();
1391
+ for (const [index, session] of sessions.entries()) {
1392
+ if (index > 0)
1393
+ await turn();
1394
+ const row = await this.database.get(`SELECT count(*) AS refs,
1395
+ (SELECT count(DISTINCT anchor_seq) FROM ${t.sessionLinks} WHERE session_id = ? AND children = 0 AND anchor_seq IS NOT NULL) AS anchors
1396
+ FROM ${t.sessionRefs} WHERE session_id = ?`, session, session);
1397
+ costs.set(session, Math.max(1, Number(row?.refs ?? 0) * Number(row?.anchors ?? 0)));
927
1398
  }
1399
+ return costs;
1400
+ }
1401
+ /**
1402
+ * The blobs that the snapshots `sessions` retain reference, in one statement. A session whose tree the index could
1403
+ * not follow retains every snapshot it records.
1404
+ */
1405
+ async retainedBySessions(sessions) {
1406
+ const t = this.tables;
1407
+ const ids = JSON.stringify(sessions);
1408
+ const rows = await this.database.all(`SELECT DISTINCT record.hash FROM ${t.sessionRecords} AS record
1409
+ WHERE record.session_id IN (SELECT value FROM ${this.dialect.jsonValues("?")})
1410
+ AND (
1411
+ (record.session_id, record.snapshot_id) IN (${this.sessionHeads(`session_id IN (SELECT value FROM ${this.dialect.jsonValues("?")})`)})
1412
+ OR EXISTS (SELECT 1 FROM ${t.sessionLinks} AS broken WHERE broken.session_id = record.session_id AND broken.broken = 1)
1413
+ )`, ids, ids);
1414
+ return rows.map((row) => row.hash);
1415
+ }
1416
+ /**
1417
+ * The blobs of `batch` that a session records and that the delete must keep, in one statement: those the snapshots
1418
+ * of `batch.sessions` retain, and those a session not among them records, whose snapshots the sweep did not walk.
1419
+ * Walks only `batch.sessions`, whose snapshot entries the sweep bounded when it made the batch (#5530).
1420
+ */
1421
+ async keptBySessions(executor, batch) {
1422
+ const t = this.tables;
1423
+ const ids = JSON.stringify(batch.sessions);
1424
+ const walked = `(SELECT value FROM ${this.dialect.jsonValues("?")})`;
1425
+ const rows = await executor.all(`SELECT DISTINCT record.hash FROM ${t.sessionRecords} AS record
1426
+ WHERE record.hash IN (SELECT value FROM ${this.dialect.jsonValues("?")})
1427
+ AND (
1428
+ record.session_id NOT IN ${walked}
1429
+ OR (record.session_id, record.snapshot_id) IN (${this.sessionHeads(`session_id IN ${walked}`)})
1430
+ OR EXISTS (SELECT 1 FROM ${t.sessionLinks} AS broken WHERE broken.session_id = record.session_id AND broken.broken = 1)
1431
+ )`, JSON.stringify(batch.hashes), ids, ids);
1432
+ return rows.map((row) => row.hash);
928
1433
  }
929
1434
  /**
930
1435
  * Stamps every blob of unknown age with the database clock, in hash order, in write transactions of at most
931
1436
  * {@link SNAPSHOT_LEGACY_STAMP_BYTES} of blobs. Moves every in-row blob larger than
932
1437
  * {@link SNAPSHOT_BLOB_CHUNK_BYTES} to chunks regardless of age. Chunk writes have the same byte bound;
933
- * publishing also frees the old in-row value, whose cost grows with its size.
1438
+ * publishing also frees the old in-row value, whose cost grows with its size. Starts with a turn of the event loop
1439
+ * when there is anything to do, so its first write does not share the turn of the sweep's last batch, and every
1440
+ * stamp and every statement of a move ends with a turn, whatever it found, so every page does too (#5530).
934
1441
  */
935
1442
  async stampLegacyAges(options) {
936
1443
  const oversized = `chunks = 0 AND length(data) > ${SNAPSHOT_BLOB_CHUNK_BYTES}`;
937
1444
  if (!(await this.database.get(`SELECT 1 FROM ${this.table} WHERE created_at = 0 UNION ALL SELECT 1 FROM ${this.table} WHERE ${oversized} LIMIT 1`)))
938
1445
  return;
1446
+ await this.betweenBatches(options.pace);
939
1447
  let after = "";
940
1448
  for (;;) {
941
1449
  options.signal?.throwIfAborted();
@@ -979,11 +1487,14 @@ export class SqlSnapshotBlobStore {
979
1487
  * {@link SNAPSHOT_LEGACY_STAMP_BYTES} per transaction while readers retain the in-row value. Publishing stamps
980
1488
  * only an unknown age and frees the old value under the writer, with time proportional to the freed size. It marks the
981
1489
  * journal as requiring chunk support, as {@link putBlobs} does. A stopped move leaves chunks the next move reuses.
1490
+ * Gives the event loop a turn after reading the blob's bytes and after every transaction, also when another host
1491
+ * moved or deleted the blob first (#5530).
982
1492
  */
983
1493
  async moveLegacyBlobToChunks(hash, options) {
984
1494
  const t = this.tables;
985
1495
  const unmoved = `hash = ? AND chunks = 0 AND length(data) > ${SNAPSHOT_BLOB_CHUNK_BYTES}`;
986
1496
  const legacy = await this.database.get(`SELECT data FROM ${t.blobs} WHERE ${unmoved}`, hash);
1497
+ await this.betweenBatches(options.pace);
987
1498
  if (legacy === undefined)
988
1499
  return;
989
1500
  const { data } = legacy;
@@ -1003,9 +1514,9 @@ export class SqlSnapshotBlobStore {
1003
1514
  }
1004
1515
  return true;
1005
1516
  });
1517
+ await this.betweenBatches(options.pace);
1006
1518
  if (!pending)
1007
1519
  return;
1008
- await this.betweenBatches(options.pace);
1009
1520
  }
1010
1521
  options.signal?.throwIfAborted();
1011
1522
  const journal = await import("../storage/journal-adoption.js");
@@ -1028,13 +1539,206 @@ export class SqlSnapshotBlobStore {
1028
1539
  const t = this.tables;
1029
1540
  await transaction.run(`DELETE FROM ${t.blobChunks} WHERE hash IN (SELECT value FROM ${this.dialect.jsonValues("?")}) AND NOT EXISTS (SELECT 1 FROM ${t.blobs} AS stored WHERE stored.hash = ${t.blobChunks}.hash AND stored.chunks > 0)`, JSON.stringify(hashes));
1030
1541
  }
1542
+ /**
1543
+ * Moves a chunk table that an earlier release created `WITHOUT ROWID` to the row layout of
1544
+ * {@link chunkTableDefinition} (#5541), in write transactions that each copy or free at most
1545
+ * {@link SNAPSHOT_CHUNK_MOVE_ROWS} chunks in all. It copies the rows, in key order, to a new table in that layout;
1546
+ * later transactions copy the rows written since and drop the copies of rows deleted since, and the one that leaves
1547
+ * the new table holding exactly the chunk table's rows gives it the chunk table's name, under which the old one is
1548
+ * kept until later transactions empty and drop it. The chunk table keeps its name, columns and key throughout, so
1549
+ * a process of an earlier release reads and writes it unchanged, and a chunk is copied with its bytes: its key, a
1550
+ * blob's hash and an index, names them. A stopped move resumes from what the tables hold. Does nothing on a chunk
1551
+ * table in the row layout, which every Postgres table is.
1552
+ */
1553
+ async moveChunksToRowTable(options) {
1554
+ const t = this.tables;
1555
+ const { next, retired } = chunkMoveTables(t);
1556
+ // The old table is `WITHOUT ROWID` under either name, so one statement tells a store with nothing to move, as
1557
+ // every store is once its move is over.
1558
+ const probe = this.dialect.withoutRowidTables([t.blobChunks, retired]);
1559
+ const clustered = async (executor) => (await executor.all(probe.sql, ...probe.params)).map((row) => row.name);
1560
+ const rows = SNAPSHOT_CHUNK_MOVE_ROWS;
1561
+ const pending = await clustered(this.database);
1562
+ if (pending.includes(retired))
1563
+ await this.dropChunkTable(retired, options);
1564
+ if (!pending.includes(t.blobChunks))
1565
+ return;
1566
+ // A copy the disk has no room for would fill it (#5694): the table stays as it is, read and written as before, and a
1567
+ // partial copy an earlier collection left is dropped, its pages back on the database's free list.
1568
+ if (!(await this.roomForChunkCopy(next)))
1569
+ return this.dropChunkTable(next, options);
1570
+ // Copies the rows after the last one copied: no other statement writes the new table before it is renamed.
1571
+ const copyNext = async (transaction) => {
1572
+ const last = await transaction.get(`SELECT hash, idx FROM ${next} ORDER BY hash DESC, idx DESC LIMIT 1`);
1573
+ const { changes } = await transaction.run(`INSERT INTO ${next} (hash, idx, data) SELECT hash, idx, data FROM ${t.blobChunks} WHERE (hash, idx) > (?, ?) ORDER BY hash, idx LIMIT ? ON CONFLICT DO NOTHING`, last?.hash ?? "", last?.idx ?? -1, rows);
1574
+ return changes;
1575
+ };
1576
+ // Copies the first rows the new table lacks, wherever they are: rows written behind the copy.
1577
+ const copyMissing = async (transaction) => {
1578
+ const { changes } = await transaction.run(`INSERT INTO ${next} (hash, idx, data) SELECT old.hash, old.idx, old.data FROM ${t.blobChunks} AS old WHERE NOT EXISTS (SELECT 1 FROM ${next} AS copy WHERE copy.hash = old.hash AND copy.idx = old.idx) ORDER BY old.hash, old.idx LIMIT ?`, rows);
1579
+ return changes;
1580
+ };
1581
+ // The rows the new table holds and the chunk table no longer does: copies of rows deleted since they were copied.
1582
+ const stale = `SELECT hash, idx FROM ${next} EXCEPT SELECT hash, idx FROM ${t.blobChunks}`;
1583
+ for (let copying = true;;) {
1584
+ options.signal?.throwIfAborted();
1585
+ let moved;
1586
+ try {
1587
+ moved = await this.write(options.pace, async (transaction) => {
1588
+ if (options.holder !== undefined)
1589
+ await this.renewClaim(transaction, options.holder);
1590
+ if (!(await clustered(transaction)).includes(t.blobChunks))
1591
+ return true;
1592
+ await transaction.exec(chunkTableDefinition(next, this.dialect));
1593
+ if (copying) {
1594
+ copying = (await copyNext(transaction)) === rows;
1595
+ return false;
1596
+ }
1597
+ // Rows copied and stale copies dropped share the transaction's rows. The tables are renamed only by a transaction
1598
+ // that leaves the new table holding exactly the chunk table's rows; otherwise the next transaction continues.
1599
+ const copied = await copyMissing(transaction);
1600
+ if (copied === rows)
1601
+ return false;
1602
+ const room = rows - copied;
1603
+ const { changes: dropped } = await transaction.run(`DELETE FROM ${next} WHERE (hash, idx) IN (${stale} LIMIT ?)`, room);
1604
+ if (dropped === room && (await transaction.get(`${stale} LIMIT 1`)) !== undefined)
1605
+ return false;
1606
+ // Renaming the table would point a trigger that names it at the old table: both of the delete triggers releases
1607
+ // installed are dropped, and the current one is installed again on the new table.
1608
+ await transaction.exec(this.dialect.dropTrigger(`${t.blobs}_chunks_delete`, t.blobs));
1609
+ await transaction.exec(this.dialect.dropTrigger(`${t.blobs}_chunks_delete_all`, t.blobs));
1610
+ try {
1611
+ await transaction.exec(`ALTER TABLE ${t.blobChunks} RENAME TO ${retired}`);
1612
+ await transaction.exec(`ALTER TABLE ${next} RENAME TO ${t.blobChunks}`);
1613
+ }
1614
+ catch (error) {
1615
+ await this.confirmRenameBlocker(transaction, error);
1616
+ throw error;
1617
+ }
1618
+ await transaction.exec(this.dialect.renderTrigger(chunksDeleteTrigger(t)));
1619
+ return true;
1620
+ });
1621
+ }
1622
+ catch (error) {
1623
+ // A disk that fills up ends the move, not the collection (#5694): the partial copy is dropped, its pages back on
1624
+ // the database's free list, and a later collection tries again.
1625
+ if (!isStorageSpaceFailure(error))
1626
+ throw error;
1627
+ await this.betweenBatches(options.pace);
1628
+ return this.dropChunkTable(next, options);
1629
+ }
1630
+ await this.betweenBatches(options.pace);
1631
+ if (moved)
1632
+ break;
1633
+ }
1634
+ await this.dropChunkTable(retired, options);
1635
+ }
1636
+ /**
1637
+ * Records on `error`, a rename that failed in `transaction`, the trigger or view SQLite named in it, when the schema
1638
+ * holds exactly one trigger or view that the error's words can name (#5622). The failed statement left the
1639
+ * transaction open on the schema SQLite checked, so that object is the one SQLite named. Otherwise, or when the schema
1640
+ * cannot be read, nothing is recorded and the collection warning names no object.
1641
+ */
1642
+ async confirmRenameBlocker(transaction, error) {
1643
+ const candidates = renameBlockerCandidates(error);
1644
+ if (candidates.length === 0)
1645
+ return;
1646
+ const names = JSON.stringify([...new Set(candidates.map((candidate) => candidate.name))]);
1647
+ const objects = (schema) => `SELECT type, name FROM ${schema} WHERE type IN ('trigger', 'view') AND name IN (SELECT value FROM ${this.dialect.jsonValues("?")})`;
1648
+ const rows = await transaction
1649
+ .all(`${objects("sqlite_master")} UNION ALL ${objects("sqlite_temp_master")}`, names, names)
1650
+ .catch(() => undefined);
1651
+ if (rows === undefined)
1652
+ return;
1653
+ const named = rows.filter((row) => candidates.some((candidate) => candidate.type === row.type && candidate.name === row.name));
1654
+ const [only] = named;
1655
+ if (named.length === 1 && only !== undefined && typeof error === "object" && error !== null)
1656
+ Reflect.defineProperty(error, RENAME_BLOCKER, { value: { type: only.type, name: only.name } });
1657
+ }
1658
+ /**
1659
+ * Whether the file system of a SQLite or libSQL database file has room to copy what is left of the chunk table to the
1660
+ * row layout (#5694): the copy grows the file by the bytes its free pages do not hold, and the write-ahead log can
1661
+ * hold every page the copy writes until a checkpoint moves them into the file, with
1662
+ * {@link SNAPSHOT_CHUNK_MOVE_HEADROOM_BYTES} left over; the database's own `freeBytes` says how much the file system
1663
+ * holds. A database whose disk this process cannot see, such as a libSQL server, moves only what is left of a table
1664
+ * no larger than that headroom: the move must never be what fills a disk, and the old layout works as before.
1665
+ */
1666
+ async roomForChunkCopy(next) {
1667
+ const rowsOf = async (table) => Number((await this.database.get(`SELECT count(*) AS rows FROM ${table}`))?.rows ?? 0);
1668
+ const copy = this.dialect.tableExists(next);
1669
+ const copyExists = async () => (await this.database.get(copy.sql, ...copy.params)) !== undefined;
1670
+ // The chunks the copy lacks, counted in one statement against what it holds: a copy may also hold copies of chunks
1671
+ // deleted since, which take no more room, and chunks stored since that it lacks.
1672
+ const lacking = async () => Number((await this.database.get(`SELECT count(*) AS rows FROM ${this.tables.blobChunks} AS old WHERE NOT EXISTS (SELECT 1 FROM ${next} AS copy WHERE copy.hash = old.hash AND copy.idx = old.idx)`))?.rows ?? 0);
1673
+ const rows = !(await copyExists())
1674
+ ? await rowsOf(this.tables.blobChunks)
1675
+ : await lacking().catch(async (error) => {
1676
+ // Another collector finished the move, which took the copy's name, or dropped the copy, since it was found:
1677
+ // none of it is left to count on. The move's own transactions see which.
1678
+ if (!(await copyExists()))
1679
+ return rowsOf(this.tables.blobChunks);
1680
+ throw error;
1681
+ });
1682
+ const left = rows * SNAPSHOT_BLOB_CHUNK_BYTES;
1683
+ let free;
1684
+ try {
1685
+ free = await this.database.freeBytes?.();
1686
+ }
1687
+ catch {
1688
+ // A reading that fails is no reading: the collection goes on as for a disk this process cannot see.
1689
+ free = undefined;
1690
+ }
1691
+ if (free === undefined)
1692
+ return left <= SNAPSHOT_CHUNK_MOVE_HEADROOM_BYTES;
1693
+ const freePages = await this.database.get("SELECT (SELECT freelist_count FROM pragma_freelist_count()) * (SELECT page_size FROM pragma_page_size()) AS bytes");
1694
+ const reused = Math.min(left, Number(freePages?.bytes ?? 0));
1695
+ return free >= left - reused + left + SNAPSHOT_CHUNK_MOVE_HEADROOM_BYTES;
1696
+ }
1697
+ /**
1698
+ * Empties `table`, the chunk table a move to the row layout retired or a partial copy of the move (#5694), in write
1699
+ * transactions of at most {@link SNAPSHOT_CHUNK_MOVE_ROWS} rows, from its first key on, then drops it; its pages go
1700
+ * to the database's free list. A full disk stops it without a failure: a later collection goes on.
1701
+ */
1702
+ async dropChunkTable(table, options) {
1703
+ const probe = this.dialect.tableExists(table);
1704
+ if ((await this.database.get(probe.sql, ...probe.params)) === undefined)
1705
+ return;
1706
+ for (;;) {
1707
+ options.signal?.throwIfAborted();
1708
+ let dropped;
1709
+ try {
1710
+ dropped = await this.write(options.pace, async (transaction) => {
1711
+ if (options.holder !== undefined)
1712
+ await this.renewClaim(transaction, options.holder);
1713
+ if ((await transaction.get(probe.sql, ...probe.params)) === undefined)
1714
+ return true;
1715
+ const last = await transaction.get(`SELECT hash, idx FROM ${table} ORDER BY hash, idx LIMIT 1 OFFSET ?`, SNAPSHOT_CHUNK_MOVE_ROWS - 1);
1716
+ if (last === undefined) {
1717
+ await transaction.exec(`DROP TABLE IF EXISTS ${table}`);
1718
+ return true;
1719
+ }
1720
+ await transaction.run(`DELETE FROM ${table} WHERE (hash, idx) <= (?, ?)`, last.hash, last.idx);
1721
+ return false;
1722
+ });
1723
+ }
1724
+ catch (error) {
1725
+ if (isStorageSpaceFailure(error))
1726
+ return;
1727
+ throw error;
1728
+ }
1729
+ await this.betweenBatches(options.pace);
1730
+ if (dropped)
1731
+ return;
1732
+ }
1733
+ }
1031
1734
  /** {@link completeIndex}, then {@link sweep}: what a manual collection does. */
1032
1735
  async collectGarbage(options) {
1033
1736
  await this.completeIndex(options);
1034
1737
  return this.sweep(options);
1035
1738
  }
1036
1739
  /**
1037
- * The snapshots sessions keep, as a subquery of `(session_id, snapshot_id)`: for every leaf of every session tree,
1740
+ * The snapshots the sessions that `sessions` selects keep, a condition on `session_id` (#5530), as a subquery of
1741
+ * `(session_id, snapshot_id)`: for every leaf of their session trees,
1038
1742
  * the latest snapshot entry of each checkout on the leaf's branch, followed through each entry's link to the
1039
1743
  * nearest snapshot entry before it. A leaf costs the snapshot entries on its branch and never a message, and leaves
1040
1744
  * that share their latest snapshot are followed once. Roots are grouped into checkouts the way resume does: a root
@@ -1043,10 +1747,10 @@ export class SqlSnapshotBlobStore {
1043
1747
  * snapshot more than resume needs and never fewer. A head that records a partly restored worktree also keeps the
1044
1748
  * snapshot it lacks, named in `degraded_from`, for {@link DEGRADED_RESTORE_RETENTION_DAYS} (#4922).
1045
1749
  */
1046
- sessionHeads() {
1750
+ sessionHeads(sessions) {
1047
1751
  const t = this.tables;
1048
1752
  return `WITH RECURSIVE
1049
- open_anchors(session_id, seq) AS (SELECT DISTINCT session_id, anchor_seq FROM ${t.sessionLinks} WHERE children = 0 AND anchor_seq IS NOT NULL),
1753
+ open_anchors(session_id, seq) AS (SELECT DISTINCT session_id, anchor_seq FROM ${t.sessionLinks} WHERE ${sessions} AND children = 0 AND anchor_seq IS NOT NULL),
1050
1754
  branch(session_id, start_seq, root, snapshot_id, restore_from, restore_to, degraded_from, degraded_since, prev_seq, depth) AS (
1051
1755
  SELECT ref.session_id, ref.seq, ref.root, ref.snapshot_id, ref.restore_from, ref.restore_to, ref.degraded_from, ref.degraded_since, ref.prev_seq, 0 FROM open_anchors AS anchor JOIN ${t.sessionRefs} AS ref ON ref.session_id = anchor.session_id AND ref.seq = anchor.seq
1052
1756
  UNION ALL
@@ -1073,13 +1777,15 @@ export class SqlSnapshotBlobStore {
1073
1777
  }
1074
1778
  /**
1075
1779
  * The next {@link SNAPSHOT_COLLECTION_BATCH} blobs whose `created_at` is at least `minimumAge` whole seconds behind
1076
- * the database clock and that are `unreferenced`, oldest first, after `after`.
1780
+ * the database clock, oldest first, after `after`: a range of the age index, whatever references them. A page after
1781
+ * `after` searches the index from `after`, which already excludes an unknown age (0): with `created_at > 0` as a
1782
+ * second lower bound, SQLite searched from the oldest blob instead, so each page cost more than the one before (#5530).
1077
1783
  */
1078
- page(transaction, minimumAge, unreferenced, after) {
1784
+ page(minimumAge, after) {
1079
1785
  const t = this.tables;
1080
1786
  return after === undefined
1081
- ? transaction.all(`SELECT created_at, hash FROM ${t.blobs} WHERE created_at > 0 AND created_at <= ${this.dialect.nowSeconds} - ? AND ${unreferenced} ORDER BY created_at, hash LIMIT ?`, minimumAge, SNAPSHOT_COLLECTION_BATCH)
1082
- : transaction.all(`SELECT created_at, hash FROM ${t.blobs} WHERE created_at > 0 AND created_at <= ${this.dialect.nowSeconds} - ? AND (created_at, hash) > (?, ?) AND ${unreferenced} ORDER BY created_at, hash LIMIT ?`, minimumAge, after.created_at, after.hash, SNAPSHOT_COLLECTION_BATCH);
1787
+ ? this.database.all(`SELECT created_at, hash FROM ${t.blobs} WHERE created_at > 0 AND created_at <= ${this.dialect.nowSeconds} - ? ORDER BY created_at, hash LIMIT ?`, minimumAge, SNAPSHOT_COLLECTION_BATCH)
1788
+ : this.database.all(`SELECT created_at, hash FROM ${t.blobs} WHERE created_at <= ${this.dialect.nowSeconds} - ? AND (created_at, hash) > (?, ?) ORDER BY created_at, hash LIMIT ?`, minimumAge, after.created_at, after.hash, SNAPSHOT_COLLECTION_BATCH);
1083
1789
  }
1084
1790
  /**
1085
1791
  * Claims this table's next collection for `holder` when it is due on the database clock: none was ever claimed, or