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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (335) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/_shared/dist-KOELCESV.js +2 -2
  3. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  4. package/dist/_shared/lib-4PES5P4V.js +2 -2
  5. package/dist/_shared/mode-interactive-sdk-JXBZ3H27.js +72 -39
  6. package/dist/_shared/mode-interactive-sdk-JXBZ3H27.js.map +1 -1
  7. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +57 -18
  8. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js.map +1 -1
  9. package/dist/_shared/mode-shared-2QJSCUM6.js +59 -14
  10. package/dist/_shared/mode-shared-2QJSCUM6.js.map +1 -1
  11. package/dist/_shared/p0-cli-BB45ZQY6.js +2 -2
  12. package/dist/_shared/p1a-prewarm-XIU57JHF.js +3 -3
  13. package/dist/_shared/p1b-elig-BY2G5BUE.js +6 -3
  14. package/dist/_shared/p1b-elig-BY2G5BUE.js.map +1 -1
  15. package/dist/_shared/runtime-O4KCSG4C.js +4 -4
  16. package/dist/_shared/sdk-5ZFNDXUJ.js +208 -54
  17. package/dist/_shared/sdk-5ZFNDXUJ.js.map +1 -1
  18. package/dist/_shared/session-data-AHTU7IS6.js +14 -7
  19. package/dist/_shared/session-data-AHTU7IS6.js.map +1 -1
  20. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  21. package/dist/_shared/settings-startup-HXQLSUWM.js +2 -2
  22. package/dist/_shared/settings-startup-HXQLSUWM.js.map +1 -1
  23. package/dist/_shared/{startup-0-0-FPPQF42L.js → startup-0-0-OWBJIX35.js} +161 -86
  24. package/dist/_shared/startup-0-0-OWBJIX35.js.map +1 -0
  25. package/dist/_shared/{startup-0-1-Q7GBLBEL.js → startup-0-1-DZYE4E5Z.js} +321 -17
  26. package/dist/_shared/startup-0-1-DZYE4E5Z.js.map +1 -0
  27. package/dist/_shared/{startup-0-2-JNYN24UI.js → startup-0-2-WFLTE4SC.js} +113 -6
  28. package/dist/_shared/startup-0-2-WFLTE4SC.js.map +1 -0
  29. package/dist/_shared/startup-0-3-DE2NCS6A.js +47 -23
  30. package/dist/_shared/startup-0-3-DE2NCS6A.js.map +1 -1
  31. package/dist/_shared/{startup-0-4-ZZXFKE55.js → startup-0-4-6XXL4JMZ.js} +37 -13
  32. package/dist/_shared/startup-0-4-6XXL4JMZ.js.map +1 -0
  33. package/dist/_shared/{startup-0-5-WN2IYA25.js → startup-0-5-DNS6FYS7.js} +126 -150
  34. package/dist/_shared/startup-0-5-DNS6FYS7.js.map +1 -0
  35. package/dist/_shared/startup-10-0-O6DAT7U4.js +93 -72
  36. package/dist/_shared/startup-10-0-O6DAT7U4.js.map +1 -1
  37. package/dist/_shared/startup-12-0-55AAXBJZ.js +3 -3
  38. package/dist/_shared/startup-14-0-MLX36RBG.js +5 -5
  39. package/dist/_shared/startup-15-0-E7RYG5YF.js +6 -6
  40. package/dist/_shared/startup-15-1-WQZBOTMZ.js +289 -122
  41. package/dist/_shared/startup-15-1-WQZBOTMZ.js.map +1 -1
  42. package/dist/_shared/startup-8-0-34CBHPZH.js +263 -145
  43. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  44. package/dist/_shared/{startup-8-1-QZMXUGHI.js → startup-8-1-VXBL37AI.js} +325 -10
  45. package/dist/_shared/startup-8-1-VXBL37AI.js.map +1 -0
  46. package/dist/_shared/storage-command-7MGXLJGZ.js +11 -273
  47. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  48. package/dist/_shared/storage-status-T6FUXRIM.js +4 -4
  49. package/dist/_shared/task-reference-stream-JWMUZSJX.js +1 -1
  50. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  51. package/dist/_shared/team-DOQKICG2.js +2 -2
  52. package/dist/_shared/tree-outline-MUEPK5B7.js +9 -2
  53. package/dist/_shared/tree-outline-MUEPK5B7.js.map +1 -1
  54. package/dist/binary-self-update.js +3 -3
  55. package/dist/builtin/intercom/broker/broker.bundle.mjs +46 -8
  56. package/dist/builtin/intercom/broker/broker.ts +1 -0
  57. package/dist/builtin/intercom/broker/client.ts +5 -1
  58. package/dist/builtin/intercom/broker/departed-children.ts +12 -6
  59. package/dist/builtin/intercom/broker/ended-child-wakes.ts +2 -0
  60. package/dist/builtin/intercom/index.bundle.mjs +130 -264
  61. package/dist/builtin/intercom/message-display.ts +42 -0
  62. package/dist/builtin/intercom/package.json +1 -1
  63. package/dist/builtin/intercom/types.ts +1 -0
  64. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  65. package/dist/builtin/mcp/package.json +1 -1
  66. package/dist/builtin/subagents/package.json +1 -1
  67. package/dist/builtin/subagents/src/extension/index.bundle.mjs +99 -20
  68. package/dist/builtin/web-access/index.bundle.mjs +15 -9
  69. package/dist/builtin/web-access/package.json +1 -1
  70. package/dist/cli/args.js +2 -2
  71. package/dist/cli/auth-cli.code.js +6 -6
  72. package/dist/cli/auth-cli.impl.js +3 -3
  73. package/dist/cli/auth-cli.js +3 -3
  74. package/dist/cli/blueprint-command.code.js +4 -4
  75. package/dist/cli/blueprint-command.impl.js +3 -3
  76. package/dist/cli/blueprint-command.js +3 -3
  77. package/dist/cli/intercom-command.code.js +3 -3
  78. package/dist/cli/intercom-command.impl.js +3 -3
  79. package/dist/cli/intercom-command.js +3 -3
  80. package/dist/cli/list-models.code.js +3 -3
  81. package/dist/cli/list-models.impl.js +3 -3
  82. package/dist/cli/list-models.js +3 -3
  83. package/dist/cli/session-picker.code.js +2 -2
  84. package/dist/cli/session-picker.impl.js +3 -3
  85. package/dist/cli/session-picker.js +3 -3
  86. package/dist/cli/startup-ui.code.js +2 -2
  87. package/dist/cli/startup-ui.impl.js +3 -3
  88. package/dist/cli/startup-ui.js +3 -3
  89. package/dist/cli/storage-command.impl.js +3 -3
  90. package/dist/cli/storage-command.js +3 -3
  91. package/dist/cli/storage-search-session.code.js +2 -2
  92. package/dist/cli/storage-search-session.impl.js +3 -3
  93. package/dist/cli/storage-search-session.js +3 -3
  94. package/dist/cli/team-command.code.js +2 -2
  95. package/dist/cli/team-command.impl.js +3 -3
  96. package/dist/cli/team-command.js +3 -3
  97. package/dist/cli.js +2 -2
  98. package/dist/core/agent-session-runtime.d.ts +14 -3
  99. package/dist/core/agent-session-types.d.ts +5 -1
  100. package/dist/core/debug.impl.js +3 -3
  101. package/dist/core/debug.js +3 -3
  102. package/dist/core/export-html/card-projection.code.js +74 -72
  103. package/dist/core/export-html/card-projection.code.js.map +1 -1
  104. package/dist/core/export-html/card-projection.impl.js +3 -3
  105. package/dist/core/export-html/card-projection.js +3 -3
  106. package/dist/core/export-html/index.code.js +12 -4
  107. package/dist/core/export-html/index.code.js.map +1 -1
  108. package/dist/core/export-html/index.impl.js +3 -3
  109. package/dist/core/export-html/index.js +3 -3
  110. package/dist/core/export-html/json-spans.impl.js +3 -3
  111. package/dist/core/export-html/json-spans.js +3 -3
  112. package/dist/core/export-html/oversized-render-inputs.code.js +1 -1
  113. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  114. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  115. package/dist/core/export-html/template.js +24 -23
  116. package/dist/core/export-html/tool-renderer.code.js +1 -1
  117. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  118. package/dist/core/export-html/tool-renderer.js +3 -3
  119. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  120. package/dist/core/extensions/jiti-loader.js +3 -3
  121. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  122. package/dist/core/extensions/jiti-static-loader.js +3 -3
  123. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  124. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  125. package/dist/core/extensions/loader-host-modules.js +3 -3
  126. package/dist/core/extensions/loader-virtual-modules.js +2 -2
  127. package/dist/core/extensions/runner-context.js +2 -2
  128. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  129. package/dist/core/intercom-broker-control-host.js +3 -3
  130. package/dist/core/intercom-broker-control.code.js +3 -3
  131. package/dist/core/intercom-broker-control.impl.js +3 -3
  132. package/dist/core/intercom-broker-control.js +3 -3
  133. package/dist/core/model-registry.js +2 -2
  134. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  135. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  136. package/dist/core/package-manager-storage-adapters.js +3 -3
  137. package/dist/core/resume/failure.d.ts +1 -1
  138. package/dist/core/sdk.code.js +4 -4
  139. package/dist/core/sdk.impl.js +3 -3
  140. package/dist/core/sdk.js +3 -3
  141. package/dist/core/session-claims.d.ts +13 -2
  142. package/dist/core/session-load-events.d.ts +42 -0
  143. package/dist/core/session-manager-core.d.ts +13 -2
  144. package/dist/core/session-manager-core.js +211 -98
  145. package/dist/core/session-manager-core.js.map +1 -1
  146. package/dist/core/session-manager-errors.d.ts +2 -2
  147. package/dist/core/session-manager-list.impl.js +3 -3
  148. package/dist/core/session-manager-list.js +3 -3
  149. package/dist/core/session-manager.code.js +1 -1
  150. package/dist/core/session-manager.impl.js +3 -3
  151. package/dist/core/session-manager.js +3 -3
  152. package/dist/core/session-storage.code.js +1 -1
  153. package/dist/core/session-storage.impl.js +3 -3
  154. package/dist/core/session-storage.js +3 -3
  155. package/dist/core/settings-manager.js +2 -2
  156. package/dist/core/storage/index.js +2 -2
  157. package/dist/core/storage/node-sqlite-thread.js +2 -2
  158. package/dist/core/storage/node-sqlite.js +2 -2
  159. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  160. package/dist/core/storage/offline-snapshot-file.js +3 -3
  161. package/dist/core/storage/provider.js +2 -2
  162. package/dist/core/storage/schema-catalog.d.ts +2 -1
  163. package/dist/core/storage/schema-catalog.js +25 -6
  164. package/dist/core/storage/schema-catalog.js.map +1 -1
  165. package/dist/core/storage/selection.js +2 -2
  166. package/dist/core/storage/session/branch-fork-source.code.js +17 -4
  167. package/dist/core/storage/session/branch-fork-source.code.js.map +1 -1
  168. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  169. package/dist/core/storage/session/branch-fork-source.js +3 -3
  170. package/dist/core/storage/session/card-view.impl.js +3 -3
  171. package/dist/core/storage/session/card-view.js +3 -3
  172. package/dist/core/storage/session/child-reader.code.js +3 -3
  173. package/dist/core/storage/session/child-reader.impl.js +3 -3
  174. package/dist/core/storage/session/child-reader.js +3 -3
  175. package/dist/core/storage/session/chunked-resume-projection.code.js +1 -1
  176. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  177. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  178. package/dist/core/storage/session/expanded-child-details.code.js +3 -3
  179. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  180. package/dist/core/storage/session/expanded-child-details.js +3 -3
  181. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  182. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  183. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  184. package/dist/core/storage/session/fork-row-index.js +3 -3
  185. package/dist/core/storage/session/fork-staging.code.js +8 -4
  186. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  187. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  188. package/dist/core/storage/session/fork-staging.js +3 -3
  189. package/dist/core/storage/session/fork-window.code.js +29 -14
  190. package/dist/core/storage/session/fork-window.code.js.map +1 -1
  191. package/dist/core/storage/session/fork-window.impl.js +3 -3
  192. package/dist/core/storage/session/fork-window.js +3 -3
  193. package/dist/core/storage/session/history-pages.impl.js +3 -3
  194. package/dist/core/storage/session/history-pages.js +3 -3
  195. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  196. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  197. package/dist/core/storage/session/jsonl-session-store.d.ts +8 -4
  198. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  199. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  200. package/dist/core/storage/session/memory-session-store.d.ts +3 -3
  201. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  202. package/dist/core/storage/session/memory-session-store.js +3 -3
  203. package/dist/core/storage/session/parent-links.d.ts +122 -0
  204. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  205. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  206. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  207. package/dist/core/storage/session/released-history-files.code.js +3 -3
  208. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  209. package/dist/core/storage/session/released-history-files.js +3 -3
  210. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  211. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  212. package/dist/core/storage/session/session-resume.impl.js +3 -3
  213. package/dist/core/storage/session/session-resume.js +3 -3
  214. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  215. package/dist/core/storage/session/snapshot-cut.js +3 -3
  216. package/dist/core/storage/session/snapshot-history.code.js +5 -6
  217. package/dist/core/storage/session/snapshot-history.code.js.map +1 -1
  218. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  219. package/dist/core/storage/session/snapshot-history.js +3 -3
  220. package/dist/core/storage/session/sql-session-store.d.ts +4 -3
  221. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  222. package/dist/core/storage/session/sql-session-store.js +3 -3
  223. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  224. package/dist/core/storage/session/tree-outline.js +3 -3
  225. package/dist/core/storage/session/tree-presentation.code.js +1 -1
  226. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  227. package/dist/core/storage/session/tree-presentation.js +3 -3
  228. package/dist/core/storage/session/types.d.ts +9 -3
  229. package/dist/core/storage/session/usage-observations.js +1 -1
  230. package/dist/core/storage/storage-status.impl.js +3 -3
  231. package/dist/core/storage/storage-status.js +3 -3
  232. package/dist/core/storage/team.impl.js +3 -3
  233. package/dist/core/storage/team.js +3 -3
  234. package/dist/core/structured-output/index.impl.js +3 -3
  235. package/dist/core/structured-output/index.js +3 -3
  236. package/dist/core/tasks/task-completion-entry.code.js +1 -1
  237. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  238. package/dist/core/tasks/task-completion-entry.js +3 -3
  239. package/dist/core/tasks/task-file-history.code.js +3 -3
  240. package/dist/core/tasks/task-file-history.impl.js +3 -3
  241. package/dist/core/tasks/task-file-history.js +3 -3
  242. package/dist/core/tasks/task-reference-archive.code.js +5 -5
  243. package/dist/core/tasks/task-reference-archive.js +3 -3
  244. package/dist/core/tasks/task-reference-identity.code.js +1 -1
  245. package/dist/core/tasks/task-reference-identity.js +3 -3
  246. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  247. package/dist/core/tasks/task-reference-stream.js +3 -3
  248. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  249. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  250. package/dist/core/tasks/task-view-source.code.js +1 -1
  251. package/dist/core/tasks/task-view-source.impl.js +3 -3
  252. package/dist/core/tasks/task-view-source.js +3 -3
  253. package/dist/core/tools/read-url.code.js +3 -3
  254. package/dist/core/tools/read-url.impl.js +3 -3
  255. package/dist/core/tools/read-url.js +3 -3
  256. package/dist/core/worktree-snapshot/blob-store.js +2 -2
  257. package/dist/core/worktree-snapshot/errors.code.js +3 -3
  258. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  259. package/dist/core/worktree-snapshot/errors.js +3 -3
  260. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  261. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  262. package/dist/extensions/codemode/execute.code.js +2 -2
  263. package/dist/extensions/codemode/execute.impl.js +3 -3
  264. package/dist/extensions/codemode/execute.js +3 -3
  265. package/dist/extensions/codemode/renderer.code.js +12 -7
  266. package/dist/extensions/codemode/renderer.code.js.map +1 -1
  267. package/dist/extensions/codemode/renderer.impl.js +3 -3
  268. package/dist/extensions/codemode/renderer.js +3 -3
  269. package/dist/extensions/mcp/cli.code.js +2 -2
  270. package/dist/extensions/mcp/cli.impl.js +3 -3
  271. package/dist/extensions/mcp/cli.js +3 -3
  272. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  273. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  274. package/dist/extensions/mcp/cli.lazy.js +3 -3
  275. package/dist/extensions/mcp/runtime.impl.js +3 -3
  276. package/dist/extensions/mcp/runtime.js +3 -3
  277. package/dist/index.d.ts +5 -2
  278. package/dist/index.js +7 -7
  279. package/dist/main-first-time-setup.code.js +2 -2
  280. package/dist/main-first-time-setup.impl.js +3 -3
  281. package/dist/main-first-time-setup.js +3 -3
  282. package/dist/main.js +1 -1
  283. package/dist/modes/index.d.ts +1 -1
  284. package/dist/modes/interactive/components/intercom-wake-notice.d.ts +4 -0
  285. package/dist/modes/interactive/components/notice-line.d.ts +1 -1
  286. package/dist/modes/interactive/components/stored-tree-view.code.js +6 -5
  287. package/dist/modes/interactive/components/stored-tree-view.code.js.map +1 -1
  288. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  289. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  290. package/dist/modes/interactive/components/tool-block.d.ts +5 -1
  291. package/dist/modes/interactive/components/user-message-selector-archive.code.js +1 -1
  292. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  293. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  294. package/dist/modes/interactive-engine/isolated-runtime.d.ts +3 -3
  295. package/dist/modes/interactive-engine/protocol.d.ts +0 -4
  296. package/dist/modes/rpc/rpc-client-api.d.ts +5 -0
  297. package/dist/modes/rpc/rpc-types.d.ts +23 -5
  298. package/dist/package-manager-cli.code.js +7 -7
  299. package/dist/package-manager-cli.impl.js +3 -3
  300. package/dist/package-manager-cli.js +3 -3
  301. package/dist/rpc-entry.js +1 -1
  302. package/dist/startup-files.json +1 -1
  303. package/dist/startup-stages/10.js +1 -1
  304. package/dist/startup-stages/12.js +1 -1
  305. package/dist/startup-stages/13.js +2 -1
  306. package/dist/startup-stages/14.js +1 -0
  307. package/dist/startup-stages/4.js +1 -1
  308. package/dist/startup-stages/6.js +1 -1
  309. package/dist/startup-stages/7.js +1 -1
  310. package/dist/startup-stages/8.js +1 -1
  311. package/dist/startup-stages/stages.json +1 -1
  312. package/dist/utils/startup-database-spare.code.js +3 -3
  313. package/dist/utils/startup-database-spare.impl.js +3 -3
  314. package/dist/utils/startup-database-spare.js +3 -3
  315. package/dist/utils/tools-manager.code.js +1 -1
  316. package/dist/utils/tools-manager.impl.js +3 -3
  317. package/dist/utils/tools-manager.js +3 -3
  318. package/docs/.agents/context/DESIGN.md +30 -0
  319. package/docs/changelog.mdx +23 -0
  320. package/docs/docs.json +1 -1
  321. package/docs/guides/subscription-usage.md +3 -3
  322. package/docs/intercom.md +3 -1
  323. package/docs/json.md +3 -3
  324. package/docs/providers.md +2 -0
  325. package/docs/rpc/protocol.md +1 -1
  326. package/docs/sdk.md +2 -0
  327. package/docs/sessions.md +36 -1
  328. package/docs/subagents.md +2 -0
  329. package/package.json +8 -8
  330. package/dist/_shared/startup-0-0-FPPQF42L.js.map +0 -1
  331. package/dist/_shared/startup-0-1-Q7GBLBEL.js.map +0 -1
  332. package/dist/_shared/startup-0-2-JNYN24UI.js.map +0 -1
  333. package/dist/_shared/startup-0-4-ZZXFKE55.js.map +0 -1
  334. package/dist/_shared/startup-0-5-WN2IYA25.js.map +0 -1
  335. package/dist/_shared/startup-8-1-QZMXUGHI.js.map +0 -1
@@ -1,8 +1,8 @@
1
1
  import { __name } from "./rolldown-runtime-BGM3D5V3.js";
2
2
  import { createModuleRequire, createSessionCwdMatcher, normalizePath, resolvePath } from "./p0-cli-BB45ZQY6.js";
3
- import { CURRENT_SESSION_VERSION, EntryTypeReader, JsonTextChecker, LaterSessionParents, applySessionSummaryEntries, bindChatEpoch, boundedChatRecord, decodeChatRecord, epochHasCreationTime, fileEpochOf, firstChatOrders, getErrnoCode, historySnapshotFor, inheritForkScope, isBetterMostRecentCandidate, isClassifiedWorkflowSession, isEarlierSessionEntry, legacyFileEpochOf, markPreferResumableSupported, materializeSessionSummaryMetadata, noteSnapshotGeneration, observeReferenceCut, parentIdInEarlierRows, referenceMetadataRead, registerArchiveLoad, registerForkScope, require_sha256, sha256Hex, summarizeSession, supportsPreferResumable, walkSessionParents, yieldTurn } from "./startup-0-0-FPPQF42L.js";
4
- import { AgentRehydrateError, AgentReleaseConfigError, SessionKeyDigests, appendFileChatRecords, deleteFileChatRecords, hasFileChatRecords, latestLegacyMessageTime, legacyCompletionTarget, readFileChatOrders, readFileChatRecords, rememberEarlierCompletion, setUsageObservationStore, summarizeLegacySession, usageObservationStore } from "./startup-0-1-Q7GBLBEL.js";
5
- import { agentWakeDispatcher } from "./startup-0-2-JNYN24UI.js";
3
+ import { CURRENT_SESSION_VERSION, EntryTypeReader, JsonTextChecker, applySessionSummaryEntries, bindChatEpoch, boundedChatRecord, decodeChatRecord, epochHasCreationTime, fileEpochOf, firstChatOrders, getErrnoCode, historySnapshotFor, inheritForkScope, isBetterMostRecentCandidate, isClassifiedWorkflowSession, legacyFileEpochOf, markPreferResumableSupported, materializeSessionSummaryMetadata, noteSnapshotGeneration, observeReferenceCut, referenceMetadataRead, registerArchiveLoad, registerForkScope, require_sha256, sha256Hex, summarizeSession, supportsPreferResumable, yieldTurn } from "./startup-0-0-OWBJIX35.js";
4
+ import { AgentRehydrateError, AgentReleaseConfigError, LaterSessionParents, SessionDuplicateEntryError, SessionInvalidParentError, SessionKeyDigests, SessionParentIndex, SessionParentRepairer, appendFileChatRecords, deleteFileChatRecords, hasFileChatRecords, isEarlierSessionEntry, latestLegacyMessageTime, legacyCompletionTarget, newSessionEntryPositions, pairedForkEntry, parentIdInEarlierRows, parentLinkDisposition, readFileChatOrders, readFileChatRecords, recordedSessionParents, rememberEarlierCompletion, repairAppendedSessionParents, repairSessionParentWrites, repairedWriteResult, setUsageObservationStore, summarizeLegacySession, usageObservationStore, validateSessionParentWrites } from "./startup-0-1-DZYE4E5Z.js";
5
+ import { agentWakeDispatcher } from "./startup-0-2-WFLTE4SC.js";
6
6
  import { SESSION_HISTORY_CHUNK_BYTES, SESSION_HISTORY_PAGE_BYTES, SESSION_HISTORY_SCAN_ENTRIES, SessionIdError, entrySizeLimit, matchesSessionIdPrefix, onlySeqs, yieldSessionTurn } from "./settings-startup-HXQLSUWM.js";
7
7
  import { access, copyFile, link, mkdir, open, readFile, readdir, rename, stat, truncate, unlink, writeFile } from "node:fs/promises";
8
8
  import { closeSync, existsSync, openSync, readSync, readdirSync, statSync } from "fs";
@@ -228,7 +228,7 @@ function text(value) {
228
228
  return typeof value === "string" ? value : void 0;
229
229
  }
230
230
  function foreignResumeIds(previous, entries) {
231
- const own = new Set(entries.map((entry) => entry.id));
231
+ const own = /* @__PURE__ */ new Set();
232
232
  const foreign = /* @__PURE__ */ new Set();
233
233
  const note = (id) => {
234
234
  if (typeof id === "string" && !own.has(id) && id !== previous.lastId) foreign.add(id);
@@ -239,6 +239,7 @@ function foreignResumeIds(previous, entries) {
239
239
  note(entry.firstKeptEntryId);
240
240
  note(entry.coveredThroughEntryId);
241
241
  }
242
+ own.add(entry.id);
242
243
  }
243
244
  return [...foreign];
244
245
  }
@@ -551,16 +552,11 @@ function addStatePosition(positions, entry, seq) {
551
552
  }
552
553
  function foldSessionResume(previous, entries, seqOf = () => void 0, activeSeq, unresolvedParents = new LaterSessionParents()) {
553
554
  if (previous === void 0 && activeSeq === void 0 && entries.length > 0) {
554
- const ids = new Map(entries.map((entry, i) => [entry.id, {
555
- entry,
556
- seq: i + 1
557
- }]));
555
+ const { parents } = recordedSessionParents(entries);
558
556
  const last = entries.at(-1);
559
- const entryOf = (id) => ids.get(id)?.entry;
560
- const positionOf = (id) => ids.get(id)?.seq;
561
- const leaf = last.type === "custom" && last.customType === LEAF_MOVE_TYPE ? last.parentId === null || last.parentId === last.id ? void 0 : entryOf(last.parentId) : last;
557
+ const leaf = last.type === "custom" && last.customType === LEAF_MOVE_TYPE ? parents.at(-1) : entries.length;
562
558
  const active = /* @__PURE__ */ new Set();
563
- for (const entry of walkSessionParents(leaf, entryOf, positionOf)) active.add(positionOf(entry.id));
559
+ for (let seq = leaf; seq > 0; seq = parents[seq - 1]) active.add(seq);
564
560
  activeSeq = (seq) => active.has(seq);
565
561
  }
566
562
  const protocols = new ResumeProtocols(previous);
@@ -583,13 +579,23 @@ function foldSessionResume(previous, entries, seqOf = () => void 0, activeSeq, u
583
579
  const resolve = (id) => typeof id === "string" ? own.get(id) ?? seqOf(id) ?? -1 : -1;
584
580
  for (const entry of entries) {
585
581
  seq++;
582
+ const formerlyDetached = unresolvedParents.found(entry.id);
583
+ if (formerlyDetached !== void 0) {
584
+ damagedHistoryLinks = true;
585
+ for (const child of formerlyDetached) {
586
+ const jump = jumps.findIndex(([from, , parent]) => from === child && parent < 0);
587
+ if (jump !== -1) jumps.splice(jump, 1);
588
+ }
589
+ }
586
590
  const resolvedParent = resolve(entry.parentId);
587
- const parentSeq = entry.parentId === null ? 0 : isEarlierSessionEntry(resolvedParent, seq) ? resolvedParent : -1;
588
- if (!damagedHistoryLinks && (resolvedParent >= seq || unresolvedParents.note(entry, parentSeq > 0))) damagedHistoryLinks = true;
591
+ const link = parentLinkDisposition(entry, isEarlierSessionEntry(resolvedParent, seq), resolvedParent >= 0);
592
+ const parentSeq = link === "earlier" ? resolvedParent : link === "broken" ? seq - 1 : link === "detached" ? -1 : 0;
593
+ if (link === "detached") unresolvedParents.note(entry.parentId, seq);
594
+ if (link === "broken" || isEarlierSessionEntry(resolve(entry.id), seq)) damagedHistoryLinks = true;
589
595
  if (parentSeq !== seq - 1) {
590
596
  if (previous !== void 0 && activeSeq === void 0) needsBranchRebuild = true;
591
597
  const last = jumps.at(-1);
592
- if (last !== void 0 && last[1] === seq - 1 && last[2] === parentSeq) jumps[jumps.length - 1] = [
598
+ if (parentSeq >= 0 && last !== void 0 && last[1] === seq - 1 && last[2] === parentSeq) jumps[jumps.length - 1] = [
593
599
  last[0],
594
600
  seq,
595
601
  parentSeq
@@ -631,6 +637,7 @@ function foldSessionResume(previous, entries, seqOf = () => void 0, activeSeq, u
631
637
  return {
632
638
  version: RESUME_INDEX_VERSION,
633
639
  damagedHistoryLinks,
640
+ ...damagedHistoryLinks || jumps.some(([, , parent]) => parent < 0) ? { reattachedParents: true } : {},
634
641
  ...needsBranchRebuild ? { needsBranchRebuild: true } : {},
635
642
  epoch: previous?.epoch ?? crypto.randomUUID(),
636
643
  ...protocols.serialize(),
@@ -656,7 +663,7 @@ const isObject = (value) => value !== null && typeof value === "object" && !Arra
656
663
  function isUpgradableSessionResumeIndex(value, lastSeq) {
657
664
  if (!isObject(value) || false) return false;
658
665
  const index = value;
659
- return index.version === UPGRADABLE_RESUME_INDEX_VERSION && !index.needsBranchRebuild && typeof index.epoch === "string" && index.seq === lastSeq && typeof index.leafSeq === "number" && Array.isArray(index.jumps) && index.jumps.every((jump) => jump?.[2] >= 0) && Array.isArray(index.compactions) && Array.isArray(index.intents) && Array.isArray(index.acks) && typeof index.state === "string" && typeof index.lastStateSeq === "number" && isObject(index.totals) && isObject(index.latest) && Array.isArray(index.admissions) && index.admissions.every((key) => typeof key === "string") && Array.isArray(index.delivered) && Array.isArray(index.deliveryOps) && Array.isArray(index.settled) && isObject(index.pending) && isObject(index.parks) && Array.isArray(index.models) && Array.isArray(index.assistants);
666
+ return index.version === UPGRADABLE_RESUME_INDEX_VERSION && !index.needsBranchRebuild && typeof index.epoch === "string" && index.seq === lastSeq && typeof index.leafSeq === "number" && Array.isArray(index.jumps) && index.jumps.every((jump) => jump?.[2] >= 0 && jump[2] < jump[0]) && Array.isArray(index.compactions) && Array.isArray(index.intents) && Array.isArray(index.acks) && typeof index.state === "string" && typeof index.lastStateSeq === "number" && isObject(index.totals) && isObject(index.latest) && Array.isArray(index.admissions) && index.admissions.every((key) => typeof key === "string") && Array.isArray(index.delivered) && Array.isArray(index.deliveryOps) && Array.isArray(index.settled) && isObject(index.pending) && isObject(index.parks) && Array.isArray(index.models) && Array.isArray(index.assistants);
660
667
  }
661
668
  /** Custom entries outside the branch state whose positions or records the upgrade derives again. */
662
669
  const UPGRADED_CUSTOM_TYPES = /* @__PURE__ */ new Set([
@@ -743,7 +750,7 @@ function resumeHasDamagedHistoryLinks(index) {
743
750
  function isSessionResumeIndex(value, lastSeq) {
744
751
  if (value === null || typeof value !== "object") return false;
745
752
  const index = value;
746
- return index.version === RESUME_INDEX_VERSION && index.childAliases != null && typeof index.childAliases === "object" && !index.needsBranchRebuild && typeof index.admissions === "string" && Array.isArray(index.deliveryOps) && typeof index.epoch === "string" && index.seq === lastSeq && typeof index.leafSeq === "number" && Array.isArray(index.jumps) && (typeof index.damagedHistoryLinks === "boolean" || index.jumps.every((jump) => jump?.[2] >= 0)) && Array.isArray(index.compactions) && Array.isArray(index.intents) && Array.isArray(index.acks) && typeof index.state === "string" && typeof index.lastStateSeq === "number" && typeof index.settingsHistory === "string" && typeof index.lastSettingSeq === "number" && typeof index.snapshotRefs === "string" && typeof index.lastSnapshotRef === "number" && typeof index.snapshotHeads === "object" && index.snapshotHeads !== null && Array.isArray(index.snapshotPins) && typeof index.snapshotRecords === "object" && index.snapshotRecords !== null && typeof index.totals === "object" && index.totals !== null && Array.isArray(index.extensionState) && index.extensionState.every((seq) => Number.isSafeInteger(seq) && seq > 0 && seq <= lastSeq);
753
+ return index.version === RESUME_INDEX_VERSION && index.childAliases != null && typeof index.childAliases === "object" && !index.needsBranchRebuild && typeof index.admissions === "string" && Array.isArray(index.deliveryOps) && typeof index.epoch === "string" && index.seq === lastSeq && typeof index.leafSeq === "number" && Array.isArray(index.jumps) && (index.reattachedParents === true || index.damagedHistoryLinks !== true && index.jumps.every((jump) => jump?.[2] >= 0)) && Array.isArray(index.compactions) && Array.isArray(index.intents) && Array.isArray(index.acks) && typeof index.state === "string" && typeof index.lastStateSeq === "number" && typeof index.settingsHistory === "string" && typeof index.lastSettingSeq === "number" && typeof index.snapshotRefs === "string" && typeof index.lastSnapshotRef === "number" && typeof index.snapshotHeads === "object" && index.snapshotHeads !== null && Array.isArray(index.snapshotPins) && typeof index.snapshotRecords === "object" && index.snapshotRecords !== null && typeof index.totals === "object" && index.totals !== null && Array.isArray(index.extensionState) && index.extensionState.every((seq) => Number.isSafeInteger(seq) && seq > 0 && seq <= lastSeq);
747
754
  }
748
755
  function branchJump(jumps, high) {
749
756
  let lowest = 0;
@@ -1662,7 +1669,7 @@ const agentSessionPersistenceFailureMethods = {
1662
1669
  };
1663
1670
  // dist/core/session-manager-append-errors.js
1664
1671
  function appendFailureWroteNothing(error) {
1665
- return isStorageTransientError(error) && error.outcome === "not-applied" || isStorageWriteLockTimeoutError(error) || isStorageWriterQueueUnusableError(error) || error instanceof SessionInvalidTextError || error instanceof SessionInvalidTimestampError || error instanceof StoragePayloadTooLargeError || error instanceof Error && error.name === "StoreClosedError";
1672
+ return isStorageTransientError(error) && error.outcome === "not-applied" || isStorageWriteLockTimeoutError(error) || isStorageWriterQueueUnusableError(error) || error instanceof SessionInvalidTextError || error instanceof SessionInvalidTimestampError || error instanceof SessionInvalidParentError || error instanceof SessionDuplicateEntryError || error instanceof StoragePayloadTooLargeError || error instanceof Error && error.name === "StoreClosedError";
1666
1673
  }
1667
1674
  // dist/core/storage/session/entry-structure.js
1668
1675
  /** Validate the tree envelope and required payload fields before consuming persisted entries. */
@@ -2501,6 +2508,7 @@ const ENTRY = object({
2501
2508
  fromId: leaf,
2502
2509
  data: object({
2503
2510
  completionId: exact,
2511
+ hash: leaf,
2504
2512
  ownerId: exact,
2505
2513
  taskId: exact,
2506
2514
  sessionId: exact,
@@ -4594,8 +4602,9 @@ var JsonlSessionStore = class JsonlSessionStore {
4594
4602
  return this.run(async () => {
4595
4603
  validateSessionHeader(header);
4596
4604
  validateSessionEntries(entries);
4605
+ const prepared = repairSessionParentWrites(header.id, entries);
4597
4606
  if (await this.claimed(header.id)) throw new SessionExistsError(header.id);
4598
- const payload = Buffer.from(this.encode(header, entries));
4607
+ const payload = Buffer.from(this.encode(header, prepared.entries));
4599
4608
  const path = location === void 0 ? this.locationFor(header) : resolve$1(location);
4600
4609
  await makeDirectory(dirname$1(path));
4601
4610
  const temporary = `${path}.${randomUUID()}.tmp`;
@@ -4613,7 +4622,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4613
4622
  });
4614
4623
  }
4615
4624
  await syncDirectory(dirname$1(path));
4616
- const state = this.contentState(header, entries, payload);
4625
+ const state = this.contentState(header, prepared.entries, payload);
4617
4626
  const stats = await this.remember(path, state);
4618
4627
  if (this.selectedFile?.id === header.id) this.selectedFile = {
4619
4628
  id: header.id,
@@ -4621,7 +4630,8 @@ var JsonlSessionStore = class JsonlSessionStore {
4621
4630
  };
4622
4631
  return {
4623
4632
  lastSeq: entries.length,
4624
- epoch: fileEpochOf(stats, state.headerStamp)
4633
+ epoch: fileEpochOf(stats, state.headerStamp),
4634
+ ...repairedWriteResult(prepared)
4625
4635
  };
4626
4636
  }, () => {
4627
4637
  try {
@@ -4638,6 +4648,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4638
4648
  if (this.create !== JsonlSessionStore.prototype.create) return void 0;
4639
4649
  validateSessionHeader(header);
4640
4650
  if (!("read" in entries)) validateSessionEntries(entries);
4651
+ const prepared = "read" in entries ? void 0 : repairSessionParentWrites(header.id, entries);
4641
4652
  const path = location === void 0 ? this.locationFor(header) : resolve$1(location);
4642
4653
  await makeDirectory(dirname$1(path));
4643
4654
  const temporary = `${path}.${randomUUID()}.tmp`;
@@ -4668,19 +4679,23 @@ var JsonlSessionStore = class JsonlSessionStore {
4668
4679
  for (let i = spans[2 * seq - 2]; i < end; i += SESSION_HISTORY_CHUNK_BYTES) yield await readFrom(handle, i, Math.min(end - i, SESSION_HISTORY_CHUNK_BYTES));
4669
4680
  });
4670
4681
  const stream = "read" in entries;
4671
- let summary = applySessionSummaryEntries(void 0, stream ? [] : entries).state;
4672
- let index = foldSessionResume(void 0, stream ? [] : entries);
4682
+ let summary = applySessionSummaryEntries(void 0, prepared?.entries ?? []).state;
4683
+ let index = foldSessionResume(void 0, prepared?.entries ?? []);
4673
4684
  let lastId;
4674
- const rows = stream ? entries.read(source.store, async (id) => await lookup(id) !== void 0) : entries.map((entry) => ({
4685
+ const parents = new SessionParentIndex();
4686
+ const repairer = new SessionParentRepairer(header.id);
4687
+ const rows = stream ? entries.read(source.store, async (id) => await lookup(id) !== void 0) : entries.map((entry, index) => pairedForkEntry({
4675
4688
  entry,
4676
4689
  reference: source.receipts.get(entry.id)
4677
- }));
4690
+ }, prepared.entries[index]));
4678
4691
  const line = this.encode(header, []);
4679
4692
  let size = Buffer.byteLength(line);
4680
4693
  let integrity;
4681
4694
  try {
4682
4695
  await write(Buffer.from(line));
4683
- for await (const row of rows) {
4696
+ for await (const original of rows) {
4697
+ const row = stream ? pairedForkEntry(original, repairer.repair(original.entry, ids.length + 1, original.parentRecordedLater)) : original;
4698
+ parents.note(row.entry, ids.length + 1);
4684
4699
  const start = size;
4685
4700
  const encoded = await encodedForkRow(source.store, row);
4686
4701
  for await (const part of encoded.chunks()) {
@@ -4724,7 +4739,8 @@ var JsonlSessionStore = class JsonlSessionStore {
4724
4739
  terminated: true,
4725
4740
  torn: false,
4726
4741
  witness: integrity.witness,
4727
- summaryState: summary
4742
+ summaryState: summary,
4743
+ parentIndex: parents
4728
4744
  });
4729
4745
  const epoch = fileEpochOf(stats, headerStamp);
4730
4746
  await this.keepIndex(path, {
@@ -4748,7 +4764,8 @@ var JsonlSessionStore = class JsonlSessionStore {
4748
4764
  }, { synced: true });
4749
4765
  return {
4750
4766
  lastSeq: ids.length,
4751
- epoch
4767
+ epoch,
4768
+ ...prepared ? repairedWriteResult(prepared) : repairer.repaired.length > 0 ? { repaired: repairer.repaired } : {}
4752
4769
  };
4753
4770
  }, {
4754
4771
  kind: "create",
@@ -4855,6 +4872,8 @@ var JsonlSessionStore = class JsonlSessionStore {
4855
4872
  identity: state.identity,
4856
4873
  epoch: fileEpochOf(stats, JSON.stringify(header)),
4857
4874
  before: state,
4875
+ parents: state.parentIndex,
4876
+ stagedParents: new SessionParentIndex(),
4858
4877
  entries: [],
4859
4878
  lines: [],
4860
4879
  requests: []
@@ -4865,8 +4884,15 @@ var JsonlSessionStore = class JsonlSessionStore {
4865
4884
  if (options.expectSeq !== lastSeq || options.epoch !== void 0 && options.epoch !== file.epoch) throw new SessionConflictError(sessionId, options.expectSeq, lastSeq);
4866
4885
  }
4867
4886
  validateSessionEntries(entries);
4868
- const lines = entries.map((entry) => JSON.stringify(entry));
4869
- if (entries.some((entry) => entry.type === "compaction")) {
4887
+ if (file.parents === void 0 && !this.parentFactsInSidecar(file, entries)) file.parents = await this.scanParentIndex(file.path, file.before);
4888
+ const prepared = repairAppendedSessionParents(sessionId, entries, {
4889
+ lastSeq: file.before.lastSeq + file.entries.length,
4890
+ lastEntryId: file.entries.at(-1)?.id ?? file.before.lastEntryId ?? null,
4891
+ seqOf: (id) => file.stagedParents.positions.get(id) ?? file.parents?.positions.get(id) ?? (id === file.before.lastEntryId ? file.before.lastSeq : void 0),
4892
+ detachedParents: { get: (id) => file.stagedParents.detached.get(id) ?? file.parents?.detached.get(id) }
4893
+ });
4894
+ const lines = prepared.entries.map((entry) => JSON.stringify(entry));
4895
+ if (prepared.entries.some((entry) => entry.type === "compaction")) {
4870
4896
  if (!await this.writeStaged(file)) {
4871
4897
  staged.delete(sessionId);
4872
4898
  if (this.poisoned) throw this.poisoned;
@@ -4874,15 +4900,32 @@ var JsonlSessionStore = class JsonlSessionStore {
4874
4900
  }
4875
4901
  await copyFile(file.path, `${file.path}.${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.${randomUUID()}.compact.bak`);
4876
4902
  }
4877
- for (const [index, entry] of entries.entries()) {
4903
+ for (const [index, entry] of prepared.entries.entries()) {
4878
4904
  file.entries.push(entry);
4879
4905
  file.lines.push(lines[index]);
4906
+ file.stagedParents.note(entry, file.before.lastSeq + file.entries.length, file.parents?.positions);
4880
4907
  }
4881
4908
  file.requests.push({
4882
4909
  request,
4883
- lastSeq: file.before.lastSeq + file.entries.length
4910
+ result: {
4911
+ lastSeq: file.before.lastSeq + file.entries.length,
4912
+ ...repairedWriteResult(prepared)
4913
+ }
4884
4914
  });
4885
4915
  }
4916
+ /** On an indexed linear append, the sidecar can rule out ID collisions without decoding any earlier row. */
4917
+ parentFactsInSidecar(file, entries) {
4918
+ if (entries.length === 0 || file.before.lastSeq === 0) return true;
4919
+ const index = this.indexes.get(file.path);
4920
+ if (index?.identity !== file.identity || index.size !== file.before.size || index.index.seq !== file.before.lastSeq || !file.before.stamp.startsWith(`${index.identity}:${index.fileSize}:${index.mtimeNs}:`) || index.index.epoch !== file.epoch || !index.witness.equals(file.before.witness) || index.index.jumps.some((jump) => jump[2] < 0)) return false;
4921
+ const earlier = /* @__PURE__ */ new Set();
4922
+ for (const { id, parentId } of entries) {
4923
+ if (index.ids.includes(idHash(id)) || earlier.has(id) || file.stagedParents.positions.has(id) || file.stagedParents.detached.has(id)) return false;
4924
+ if (parentId !== null && parentId !== file.before.lastEntryId && !earlier.has(parentId) && !file.stagedParents.positions.has(parentId)) return false;
4925
+ earlier.add(id);
4926
+ }
4927
+ return true;
4928
+ }
4886
4929
  /**
4887
4930
  * Writes the lines staged for `file` through its kept handle, then decides the appends they came from: false when the
4888
4931
  * write failed and they fail. A failed write or sync is cut off again; when that fails too the store is poisoned,
@@ -4893,12 +4936,13 @@ var JsonlSessionStore = class JsonlSessionStore {
4893
4936
  file.entries = [];
4894
4937
  file.lines = [];
4895
4938
  file.requests = [];
4939
+ file.stagedParents = new SessionParentIndex();
4896
4940
  if (this.poisoned) {
4897
4941
  for (const { request } of requests) request.answer = { error: this.poisoned };
4898
4942
  return false;
4899
4943
  }
4900
4944
  if (entries.length === 0) {
4901
- for (const { request, lastSeq } of requests) request.answer = { lastSeq };
4945
+ for (const { request, result } of requests) request.answer = result;
4902
4946
  return true;
4903
4947
  }
4904
4948
  const offset = before.size;
@@ -4921,8 +4965,10 @@ var JsonlSessionStore = class JsonlSessionStore {
4921
4965
  throw cause;
4922
4966
  }
4923
4967
  const stats = await kept.handle.stat({ bigint: true });
4968
+ if (file.parents !== void 0) for (const [index, entry] of entries.entries()) file.parents.note(entry, before.lastSeq + index + 1);
4924
4969
  await this.remember(path, {
4925
4970
  ...before,
4971
+ ...file.parents === void 0 ? {} : { parentIndex: file.parents },
4926
4972
  lastSeq: before.lastSeq + entries.length,
4927
4973
  lastEntryId: entries.at(-1)?.id,
4928
4974
  terminated: true,
@@ -4947,7 +4993,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4947
4993
  } finally {
4948
4994
  this.pinnedKeptFiles.delete(path);
4949
4995
  }
4950
- for (const { request, lastSeq } of requests) request.answer = { lastSeq };
4996
+ for (const { request, result } of requests) request.answer = result;
4951
4997
  return true;
4952
4998
  }
4953
4999
  replace(sessionId, header, entries, options) {
@@ -4955,10 +5001,12 @@ var JsonlSessionStore = class JsonlSessionStore {
4955
5001
  const { path } = await this.forWrite(sessionId, options);
4956
5002
  validateSessionHeader(header);
4957
5003
  validateSessionEntries(entries);
5004
+ const prepared = repairSessionParentWrites(sessionId, entries);
4958
5005
  if (header.id !== sessionId) throw new SessionIdMismatchError(sessionId, header.id);
4959
5006
  return {
4960
5007
  lastSeq: entries.length,
4961
- epoch: await this.commit(path, header, entries)
5008
+ epoch: await this.commit(path, header, prepared.entries),
5009
+ ...repairedWriteResult(prepared)
4962
5010
  };
4963
5011
  }, {
4964
5012
  kind: "sessions",
@@ -5050,6 +5098,7 @@ var JsonlSessionStore = class JsonlSessionStore {
5050
5098
  commit: async () => {
5051
5099
  if (torn) reportTornLine(path);
5052
5100
  await this.remember(path, {
5101
+ parentIndex: new SessionParentIndex(entries),
5053
5102
  headerStamp,
5054
5103
  headerId: header.id,
5055
5104
  lastSeq: entries.length,
@@ -5284,10 +5333,10 @@ var JsonlSessionStore = class JsonlSessionStore {
5284
5333
  changed
5285
5334
  };
5286
5335
  }
5287
- loadFile(path) {
5336
+ loadFile(path, options) {
5288
5337
  const target = resolve$1(path);
5289
5338
  return this.run(async () => {
5290
- const fallback = () => this.exclusive(() => this.readPersisted(target), void 0, this.directory, {
5339
+ const fallback = () => this.exclusive(() => options?.persistUpgrade === false ? this.readSnapshot(target) : this.readPersisted(target), void 0, this.directory, {
5291
5340
  kind: "files",
5292
5341
  paths: [target]
5293
5342
  });
@@ -5581,6 +5630,7 @@ var JsonlSessionStore = class JsonlSessionStore {
5581
5630
  epoch,
5582
5631
  lastSeq,
5583
5632
  legacy: input.legacy !== void 0,
5633
+ findEntrySeq: reading((id) => this.seqInFile(path, jsonl, id, handle)),
5584
5634
  window: reading(() => {
5585
5635
  window ??= this.buildIndex(path, headerStamp, stats, input, {
5586
5636
  topology,
@@ -5591,6 +5641,7 @@ var JsonlSessionStore = class JsonlSessionStore {
5591
5641
  unchanged
5592
5642
  }, {
5593
5643
  descriptor: this.descriptor,
5644
+ readBranchSpan: reading(async (id, cut) => transcriptBranchSpan(id, jsonl.index, cut)),
5594
5645
  readEntrySizes: reading(async (_id, from, to, limit) => {
5595
5646
  const end = Math.min(lastSeq, to, from + entrySizeLimit(limit) - 1);
5596
5647
  return {
@@ -5745,6 +5796,16 @@ var JsonlSessionStore = class JsonlSessionStore {
5745
5796
  commit: () => this.commitIndexed(path, header, stats, jsonl, needsPersist)
5746
5797
  };
5747
5798
  }, async () => {
5799
+ const located = await this.locate(sessionId);
5800
+ if (located !== void 0 && !isCurrentSessionHeader(located.stored)) {
5801
+ const snapshot = await this.readPersisted(located.path, located.stored);
5802
+ try {
5803
+ validateSessionParentWrites(snapshot.entries);
5804
+ } catch (error) {
5805
+ if (!(error instanceof SessionInvalidParentError || error instanceof SessionDuplicateEntryError)) throw error;
5806
+ return sessionResumeOf(snapshot.header, snapshot.entries, leafId);
5807
+ }
5808
+ }
5748
5809
  const { path, header, jsonl } = await this.indexed(sessionId);
5749
5810
  const leafSeq = leafId === void 0 ? jsonl.index.leafSeq : await this.seqInFile(path, jsonl, leafId) ?? 0;
5750
5811
  const index = leafSeq === jsonl.index.leafSeq ? jsonl.index : await selectResumeLeaf(jsonl.index, leafSeq, branchStatePages(jsonl.index.seq, {
@@ -6036,6 +6097,8 @@ var JsonlSessionStore = class JsonlSessionStore {
6036
6097
  } else if (isForkCatalogType(entry.type)) catalog.push([seq, entry.type]);
6037
6098
  }
6038
6099
  index = foldSessionResume(index, batch, (id) => ids.get(id), activeSeq, unresolvedParents);
6100
+ let seq = index.seq - batch.length;
6101
+ for (const { id } of batch) ids.set(id, ++seq);
6039
6102
  if (extraToolCalls) index = withToolCalls(index, extraToolCalls);
6040
6103
  batch = [];
6041
6104
  batchBytes = 0;
@@ -6046,7 +6109,6 @@ var JsonlSessionStore = class JsonlSessionStore {
6046
6109
  if (batch.length && batchBytes + bytes > SCAN_WINDOW_BYTES$1) flush();
6047
6110
  spans.push(start, stop);
6048
6111
  hashes.push(idHash(entry.id));
6049
- ids.set(entry.id, spans.length / 2);
6050
6112
  batch.push(entry);
6051
6113
  batchBytes += bytes;
6052
6114
  extraToolCalls += toolCalls;
@@ -6069,7 +6131,7 @@ var JsonlSessionStore = class JsonlSessionStore {
6069
6131
  }
6070
6132
  }
6071
6133
  async catchUp(path, cached, stats, kept, reportTorn = true) {
6072
- if (!cached.index.damagedHistoryLinks && cached.index.jumps.some((jump) => jump[2] < 0)) return void 0;
6134
+ if (cached.index.jumps.some((jump) => jump[2] < 0)) return void 0;
6073
6135
  const from = cached.size - cached.witness.length;
6074
6136
  if (Number(stats.size) - from > SCAN_WINDOW_BYTES$1) return this.streamCatchUp(path, cached, stats, kept, reportTorn);
6075
6137
  const bytes = await readBytes(path, from, Number(stats.size) - from, kept);
@@ -6569,7 +6631,7 @@ var JsonlSessionStore = class JsonlSessionStore {
6569
6631
  }
6570
6632
  /** What an operation rejects with for `cause`: the session errors as they are, any other as the store unavailable. */
6571
6633
  failure(cause) {
6572
- if (cause instanceof SessionConflictError || cause instanceof SessionExistsError || cause instanceof SessionNotFoundError || cause instanceof SessionIdMismatchError || cause instanceof SessionInvalidTextError || cause instanceof SessionInvalidTimestampError || cause instanceof SessionFormatVersionError$1 || cause instanceof JsonlStoragePoisonedError || cause instanceof DOMException) return cause;
6634
+ if (cause instanceof SessionConflictError || cause instanceof SessionExistsError || cause instanceof SessionNotFoundError || cause instanceof SessionIdMismatchError || cause instanceof SessionInvalidTextError || cause instanceof SessionInvalidTimestampError || cause instanceof SessionInvalidParentError || cause instanceof SessionDuplicateEntryError || cause instanceof SessionFormatVersionError$1 || cause instanceof JsonlStoragePoisonedError || cause instanceof DOMException) return cause;
6573
6635
  return new StorageUnavailableError$1(this.descriptor, cause);
6574
6636
  }
6575
6637
  async resolveLockScope(lockRequest) {
@@ -6904,7 +6966,12 @@ var JsonlSessionStore = class JsonlSessionStore {
6904
6966
  const upgraded = upgradeLegacySessionEntries(stored, entries, path).entries;
6905
6967
  validateSessionEntryStructure(upgraded, path);
6906
6968
  validateSessionEntries(upgraded);
6907
- if (persistUpgrade) await this.commit(path, header, upgraded);
6969
+ if (persistUpgrade) try {
6970
+ validateSessionParentWrites(upgraded);
6971
+ await this.commit(path, header, upgraded);
6972
+ } catch (error) {
6973
+ if (!(error instanceof SessionInvalidParentError || error instanceof SessionDuplicateEntryError)) throw error;
6974
+ }
6908
6975
  return {
6909
6976
  header,
6910
6977
  entries: upgraded,
@@ -6921,7 +6988,8 @@ var JsonlSessionStore = class JsonlSessionStore {
6921
6988
  witness,
6922
6989
  terminated,
6923
6990
  torn,
6924
- summaryState: applySessionSummaryEntries(void 0, entries).state
6991
+ summaryState: applySessionSummaryEntries(void 0, entries).state,
6992
+ parentIndex: new SessionParentIndex(entries)
6925
6993
  }, torn ? size : void 0);
6926
6994
  bindChatEpoch(header, fileEpochOf(stats, JSON.stringify(header)));
6927
6995
  return {
@@ -7261,6 +7329,7 @@ var JsonlSessionStore = class JsonlSessionStore {
7261
7329
  }
7262
7330
  contentState(header, entries, content) {
7263
7331
  return {
7332
+ parentIndex: new SessionParentIndex(entries),
7264
7333
  headerStamp: JSON.stringify(header),
7265
7334
  lastSeq: entries.length,
7266
7335
  headerId: header.id,
@@ -7280,14 +7349,34 @@ var JsonlSessionStore = class JsonlSessionStore {
7280
7349
  const identity = `${stats.dev}:${stats.ino}`;
7281
7350
  const kept = this.keptFiles.get(path);
7282
7351
  if (kept !== void 0 && kept.identity !== identity) await this.closeKept(path);
7352
+ const stamp = this.stamp(stats);
7353
+ const previous = this.fileStates.get(path);
7354
+ const parentIndex = state.parentIndex ?? (previous?.stamp === stamp ? previous.parentIndex : void 0);
7283
7355
  this.keepFileState(path, {
7284
7356
  ...state,
7285
- stamp: this.stamp(stats),
7357
+ ...parentIndex === void 0 ? {} : { parentIndex },
7358
+ stamp,
7286
7359
  identity,
7287
7360
  size: size ?? Number(stats.size)
7288
7361
  });
7289
7362
  return stats;
7290
7363
  }
7364
+ async scanParentIndex(path, state) {
7365
+ const index = new SessionParentIndex();
7366
+ if (state.lastSeq === 0) return index;
7367
+ const kept = this.keptFor(path, state.identity);
7368
+ const handle = kept ?? await open(path, "r");
7369
+ try {
7370
+ let seq = 0;
7371
+ await scanEntries(path, handle, 0, state.size, true, (entry) => {
7372
+ index.note(entry, ++seq);
7373
+ return true;
7374
+ });
7375
+ return index;
7376
+ } finally {
7377
+ if (kept === void 0) await handle.close();
7378
+ }
7379
+ }
7291
7380
  keepFileState(path, state) {
7292
7381
  this.fileStates.set(path, state);
7293
7382
  recordFileState(path, state);
@@ -7361,6 +7450,7 @@ var JsonlSessionStore = class JsonlSessionStore {
7361
7450
  }
7362
7451
  validateSessionEntryStructure(entries, path);
7363
7452
  validateSessionEntries(entries);
7453
+ if (state.parentIndex) for (const [index, entry] of entries.entries()) state.parentIndex.note(entry, state.lastSeq + index + 1);
7364
7454
  state = {
7365
7455
  ...state,
7366
7456
  stamp: this.stamp(stats),
@@ -8082,11 +8172,13 @@ var MemorySessionStore = class MemorySessionStore {
8082
8172
  validateSessionHeader(header);
8083
8173
  validateSessionEntries(entries);
8084
8174
  if (this.records.has(header.id)) throw new SessionExistsError(header.id);
8085
- const record = this.encodeSession(header, entries);
8175
+ const prepared = repairSessionParentWrites(header.id, entries);
8176
+ const record = this.encodeSession(header, prepared.entries);
8086
8177
  this.records.set(header.id, record);
8087
8178
  return {
8088
8179
  lastSeq: entries.length,
8089
- epoch: record.index.epoch
8180
+ epoch: record.index.epoch,
8181
+ ...repairedWriteResult(prepared)
8090
8182
  };
8091
8183
  }
8092
8184
  async createFork(header, entries, source) {
@@ -8105,7 +8197,11 @@ var MemorySessionStore = class MemorySessionStore {
8105
8197
  });
8106
8198
  const blobs = /* @__PURE__ */ new Map();
8107
8199
  const remainingBlobs = /* @__PURE__ */ new Set();
8108
- for await (const row of entries.read(source.store, async (id) => await lookup(id) !== void 0)) {
8200
+ const repairer = new SessionParentRepairer(header.id);
8201
+ for await (const original of entries.read(source.store, async (id) => await lookup(id) !== void 0)) {
8202
+ const row = pairedForkEntry(original, repairer.repair(original.entry, record.lastSeq + 1, original.parentRecordedLater));
8203
+ const parents = this.validateParents(record, [row.entry]);
8204
+ this.noteParents(record, [row.entry], parents);
8109
8205
  const encoded = await encodedForkRow(source.store, row);
8110
8206
  const bytes = new Uint8Array(encoded.size);
8111
8207
  let at = 0;
@@ -8136,13 +8232,27 @@ var MemorySessionStore = class MemorySessionStore {
8136
8232
  return {
8137
8233
  lastSeq: record.lastSeq,
8138
8234
  epoch: record.index.epoch,
8139
- remainingBlobs: [...remainingBlobs]
8235
+ remainingBlobs: [...remainingBlobs],
8236
+ ...repairer.repaired.length ? { repaired: repairer.repaired } : {}
8140
8237
  };
8141
8238
  }
8142
8239
  this.assertOpen();
8143
8240
  validateSessionHeader(header);
8144
8241
  validateSessionEntries(entries);
8145
8242
  if (this.records.has(header.id)) throw new SessionExistsError(header.id);
8243
+ const prepared = repairSessionParentWrites(header.id, entries);
8244
+ if (prepared.repaired.length > 0) {
8245
+ const copied = await this.createFork(header, { async *read() {
8246
+ for (const [index, entry] of entries.entries()) yield pairedForkEntry({
8247
+ entry,
8248
+ reference: source.receipts.get(entry.id)
8249
+ }, prepared.entries[index]);
8250
+ } }, source);
8251
+ return copied && {
8252
+ ...copied,
8253
+ ...repairedWriteResult(prepared)
8254
+ };
8255
+ }
8146
8256
  const record = this.encodeSession(header, entries);
8147
8257
  const projected = record.entries[0];
8148
8258
  const chunks = [];
@@ -8192,12 +8302,31 @@ var MemorySessionStore = class MemorySessionStore {
8192
8302
  const record = this.forWrite(sessionId, options);
8193
8303
  validateSessionEntries(entries);
8194
8304
  if (entries.length === 0) return { lastSeq: record.lastSeq };
8195
- const index = this.appendedIndex(record, entries);
8196
- const encoded = this.encodeEntries(entries);
8305
+ const prepared = repairAppendedSessionParents(sessionId, entries, {
8306
+ lastSeq: record.lastSeq,
8307
+ lastEntryId: record.index.lastId,
8308
+ seqOf: (id) => record.entryPositions.get(id),
8309
+ detachedParents: record.detachedParents
8310
+ });
8311
+ const actual = prepared.entries;
8312
+ const parents = this.validateParents(record, actual);
8313
+ const index = this.appendedIndex(record, actual);
8314
+ const encoded = this.encodeEntries(actual);
8197
8315
  this.appendEncoded(record, encoded);
8316
+ this.noteParents(record, actual, parents, record.lastSeq - actual.length);
8198
8317
  record.index = index;
8199
- record.summaryState = applySessionSummaryEntries(record.summaryState, entries).state;
8200
- return { lastSeq: record.lastSeq };
8318
+ record.summaryState = applySessionSummaryEntries(record.summaryState, actual).state;
8319
+ return {
8320
+ lastSeq: record.lastSeq,
8321
+ ...repairedWriteResult(prepared)
8322
+ };
8323
+ }
8324
+ validateParents(record, entries) {
8325
+ return validateSessionParentWrites(entries, record.lastSeq, (id) => record.entryPositions.get(id), record.detachedParents);
8326
+ }
8327
+ noteParents(record, entries, parents, after = record.lastSeq) {
8328
+ for (const [index, { id }] of entries.entries()) record.entryPositions.set(id, after + index + 1);
8329
+ if (parents) for (const [id, child] of parents) record.detachedParents.set(id, child);
8201
8330
  }
8202
8331
  appendEncoded(record, encoded) {
8203
8332
  if (record.starts.length !== record.lastSeq) record.starts = record.starts.slice(0, record.lastSeq);
@@ -8221,6 +8350,8 @@ var MemorySessionStore = class MemorySessionStore {
8221
8350
  ...record.index,
8222
8351
  epoch: crypto.randomUUID()
8223
8352
  } : record.index,
8353
+ entryPositions: new Map(record.entryPositions),
8354
+ detachedParents: new Map(record.detachedParents),
8224
8355
  entries: [...record.entries]
8225
8356
  });
8226
8357
  return copy;
@@ -8360,7 +8491,9 @@ var MemorySessionStore = class MemorySessionStore {
8360
8491
  if (p.seq !== r.lastSeq + 1 || !p.lengths.length || p.lengths.length > 4096 || bytes.length > SCAN_WINDOW_BYTES || p.lengths.some((n) => !Number.isSafeInteger(n) || n < 1) || p.lengths.reduce((a, b) => a + b, p.lengths.length - 1) !== bytes.length) throw new Error("Incomplete unsaved engine history");
8361
8492
  const page = parseEntries(bytes);
8362
8493
  if (page.length !== p.lengths.length) throw new Error("Incomplete unsaved engine history");
8494
+ const parents = this.validateParents(r, page);
8363
8495
  const index = this.appendedIndex(r, page);
8496
+ this.noteParents(r, page, parents);
8364
8497
  if (r.starts.length !== r.lastSeq) r.starts = r.starts.slice(0, r.lastSeq);
8365
8498
  r.entries.push(bytes);
8366
8499
  let pos = r.lastSeq ? r.totalBytes + 1 : 0;
@@ -8391,11 +8524,13 @@ var MemorySessionStore = class MemorySessionStore {
8391
8524
  const result = project.finish();
8392
8525
  if (at !== size || !result) throw new Error("Incomplete private mirror entry");
8393
8526
  const entry = result.entry;
8527
+ const parents = this.validateParents(record, [entry]);
8394
8528
  const index = this.appendedIndex(record, [entry]);
8395
8529
  this.appendEncoded(record, {
8396
8530
  bytes,
8397
8531
  lengths: [size]
8398
8532
  });
8533
+ this.noteParents(record, [entry], parents, seq - 1);
8399
8534
  record.index = result.toolCalls ? {
8400
8535
  ...index,
8401
8536
  totals: {
@@ -8415,20 +8550,7 @@ var MemorySessionStore = class MemorySessionStore {
8415
8550
  this.privateMirrorRecord(id).summaryState = summary;
8416
8551
  }
8417
8552
  appendedIndex(record, entries) {
8418
- const previous = record.index;
8419
- if (resumeIndexNeedsRefold(previous, entries)) return foldSessionResume(previous, entries);
8420
- const seqs = /* @__PURE__ */ new Map();
8421
- let unresolved = false;
8422
- for (const id of foreignResumeIds(previous, entries)) {
8423
- const seq = record.spilling === void 0 ? heldSeqOf(record, id) : void 0;
8424
- if (seq !== void 0) seqs.set(id, seq);
8425
- else if (record.spilling !== void 0 || record.directory !== void 0) unresolved = true;
8426
- }
8427
- const index = foldSessionResume(previous, entries, (id) => seqs.get(id));
8428
- return unresolved ? {
8429
- ...index,
8430
- needsBranchRebuild: true
8431
- } : index;
8553
+ return foldSessionResume(record.index, entries, (id) => record.entryPositions.get(id));
8432
8554
  }
8433
8555
  async resumeIndex(sessionId, record) {
8434
8556
  const previous = record.index;
@@ -8475,12 +8597,14 @@ var MemorySessionStore = class MemorySessionStore {
8475
8597
  validateSessionHeader(header);
8476
8598
  validateSessionEntries(entries);
8477
8599
  if (header.id !== sessionId) throw new SessionIdMismatchError(sessionId, header.id);
8478
- const record = this.encodeSession(header, entries);
8600
+ const prepared = repairSessionParentWrites(sessionId, entries);
8601
+ const record = this.encodeSession(header, prepared.entries);
8479
8602
  this.records.set(sessionId, record);
8480
8603
  await this.removeSpillFile(sessionId, previous);
8481
8604
  return {
8482
8605
  lastSeq: entries.length,
8483
- epoch: record.index.epoch
8606
+ epoch: record.index.epoch,
8607
+ ...repairedWriteResult(prepared)
8484
8608
  };
8485
8609
  }
8486
8610
  async updateHeader(header, options) {
@@ -8620,7 +8744,10 @@ var MemorySessionStore = class MemorySessionStore {
8620
8744
  };
8621
8745
  const metadata = rangedForkMetadata((seq) => this.spanOf(held, seq, seq), (start, n) => this.bytesOf(sessionId, held, start, start + n));
8622
8746
  try {
8623
- const { index, leaf } = await locateFork(captured, entryId, metadata);
8747
+ const { index, leaf } = await locateFork(captured, entryId, metadata, (id, through) => {
8748
+ const seq = record.entryPositions.get(id);
8749
+ return seq !== void 0 && seq <= through ? seq : void 0;
8750
+ });
8624
8751
  const window = await indexedForkWindow(decodeHeader(record), index, leaf, (lo, hi) => many(seqRange(lo, hi)), many, metadata, scanForkRecords(metadata), options);
8625
8752
  if (!invalid && this.records.get(sessionId) === record) return window;
8626
8753
  } catch (error) {
@@ -9229,6 +9356,7 @@ var MemorySessionStore = class MemorySessionStore {
9229
9356
  }, cause));
9230
9357
  }
9231
9358
  encodeSession(header, entries) {
9359
+ const detachedParents = validateSessionParentWrites(entries) ?? /* @__PURE__ */ new Map();
9232
9360
  const headerBytes = this.encode(() => JSON.stringify(header));
9233
9361
  const encoded = entries.length === 0 ? void 0 : this.encodeEntries(entries);
9234
9362
  const starts = [];
@@ -9242,6 +9370,8 @@ var MemorySessionStore = class MemorySessionStore {
9242
9370
  entries: encoded === void 0 ? [] : [encoded.bytes],
9243
9371
  summaryState: applySessionSummaryEntries(void 0, entries).state,
9244
9372
  lastSeq: entries.length,
9373
+ entryPositions: newSessionEntryPositions(entries),
9374
+ detachedParents,
9245
9375
  directory: void 0,
9246
9376
  file: 0,
9247
9377
  spilledBytes: 0,
@@ -9469,19 +9599,6 @@ function verifyBlock(held, sessionId, bytes, block, from) {
9469
9599
  });
9470
9600
  }
9471
9601
  const nativeLoad = registerArchiveLoad(MemorySessionStore.prototype.load);
9472
- function heldSeqOf(record, entryId) {
9473
- if (record.index.lastId === entryId) return record.index.seq;
9474
- const heldStart = record.directory === void 0 ? 0 : record.spilledBytes + 1;
9475
- const needle = Buffer.from(`"id":${JSON.stringify(entryId)}`);
9476
- for (let seq = record.lastSeq; seq >= 1; seq--) {
9477
- const start = record.starts[seq - 1];
9478
- if (start < heldStart) return void 0;
9479
- const end = seq < record.lastSeq ? record.starts[seq] - 1 : record.totalBytes;
9480
- const bytes = Buffer.from(heldSlice(record.entries, start - heldStart, end - heldStart));
9481
- if (bytes.indexOf(needle) === -1) continue;
9482
- if (parseEntries(bytes)[0]?.id === entryId) return seq;
9483
- }
9484
- }
9485
9602
  // dist/core/agent-session-release.js
9486
9603
  /** The namespace of the wake keys idle sessions are released under. */
9487
9604
  const IDLE_RELEASE_NAMESPACE = "session-idle";
@@ -9844,9 +9961,9 @@ async function savedWindowAnswer(store, resume) {
9844
9961
  if (!resume.omitted.assistantMessages && !resume.state.some(({ entry, onBranch }) => onBranch && entry.type === "message" && entry.message.role === "assistant")) return;
9845
9962
  const edits = /* @__PURE__ */ new Map();
9846
9963
  for (const { entry, seq } of resume.branch) if (entry.type === "context_edit") edits.set(entry.targetId, seq);
9847
- return archivedAnswerAt(store, resume.header.id, resume.epoch, resume.lastSeq, first.seq, first.entry.parentId, edits);
9964
+ return archivedAnswerAt(store, resume.header.id, resume.epoch, resume.lastSeq, first.seq, first.entry.parentId, edits, void 0, resume.damagedHistoryLinks);
9848
9965
  }
9849
- async function archivedAnswerAt(store, id, epoch, through, firstSeq, parent, edits, overlay) {
9966
+ async function archivedAnswerAt(store, id, epoch, through, firstSeq, parent, edits, overlay, damagedHistoryLinks = false) {
9850
9967
  const pages = (fromSeq, toSeq) => historyPages(store, id, epoch, through, {
9851
9968
  fromSeq,
9852
9969
  toSeq,
@@ -9861,7 +9978,12 @@ async function archivedAnswerAt(store, id, epoch, through, firstSeq, parent, edi
9861
9978
  if (item.entry.type === "context_edit") return item.entry.replacement === null ? null : contentText(item.entry.replacement.content);
9862
9979
  }
9863
9980
  };
9864
- for await (const { items } of pages(1, firstSeq - 1)) for (let i = items.length - 1; i >= 0; i--) {
9981
+ const ancestors = damagedHistoryLinks ? historyPages(store, id, epoch, through, {
9982
+ toSeq: firstSeq - 1,
9983
+ direction: "backward",
9984
+ branchLeafSeq: firstSeq
9985
+ }) : pages(1, firstSeq - 1);
9986
+ for await (const { items } of ancestors) for (let i = items.length - 1; i >= 0; i--) {
9865
9987
  const item = items[i];
9866
9988
  let entry;
9867
9989
  if ("entry" in item) {
@@ -9875,15 +9997,17 @@ async function archivedAnswerAt(store, id, epoch, through, firstSeq, parent, edi
9875
9997
  stop: raw.type === "message" && raw.message.role === "assistant" && raw.message.stopReason === "stop"
9876
9998
  };
9877
9999
  } else entry = await (await import("../core/storage/session/chunked-resume-projection.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"))).chunkedAnswerHeader(chunks(item));
9878
- if (entry.id !== parent) continue;
9879
- parent = parentIdInEarlierRows(entry);
10000
+ if (!damagedHistoryLinks) {
10001
+ if (entry.id !== parent) continue;
10002
+ parent = parentIdInEarlierRows(entry);
10003
+ }
9880
10004
  if (entry.targetId !== void 0 && !latest.has(entry.targetId)) latest.set(entry.targetId, item.seq);
9881
10005
  if (entry.type === "message" && entry.role === "assistant") {
9882
10006
  const edited = latest.get(entry.id);
9883
10007
  const text = overlay?.targetId === entry.id ? overlay.replacement === null ? null : contentText(overlay.replacement.content) : edited !== void 0 ? await replacement(edited) : "entry" in item ? contentText(item.entry.type === "message" && item.entry.message.role === "assistant" && item.entry.message.content) : await (await import("../core/storage/session/chunked-resume-projection.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"))).chunkedAnswerContent(chunks(item), false);
9884
10008
  if (text !== null && (text || entry.stop)) return text ? { text } : {};
9885
10009
  }
9886
- if (parent === null) return;
10010
+ if (!damagedHistoryLinks && parent === null) return;
9887
10011
  }
9888
10012
  }
9889
10013
  // dist/core/storage/session/legacy-session-store.js
@@ -9928,8 +10052,7 @@ var LegacySessionStore = class LegacySessionStore {
9928
10052
  if (supportsPreferResumable(inner)) markPreferResumableSupported(this);
9929
10053
  const { putBlob, getBlob, readForkWindow } = inner;
9930
10054
  if (readForkWindow) this.readForkWindow = async (id, entryId, options) => {
9931
- await this.convert(id);
9932
- return readForkWindow.call(inner, id, entryId, options);
10055
+ return (await this.readStore(id)).readForkWindow(id, entryId, options);
9933
10056
  };
9934
10057
  if (putBlob !== void 0 && getBlob !== void 0) {
9935
10058
  this.putBlob = async (sessionId, data) => {
@@ -9938,35 +10061,20 @@ var LegacySessionStore = class LegacySessionStore {
9938
10061
  };
9939
10062
  this.getBlob = (sessionId, hash) => getBlob.call(inner, sessionId, hash);
9940
10063
  }
9941
- if (inner.readChildDisplayCut) this.readChildDisplayCut = async (id, launch) => {
9942
- await this.convert(id);
9943
- return inner.readChildDisplayCut(id, launch);
9944
- };
9945
- if (inner.readChildCatalogCut) this.readChildCatalogCut = async (id) => {
9946
- await this.convert(id);
9947
- return inner.readChildCatalogCut(id);
9948
- };
9949
- if (inner.readSelectedPage) this.readSelectedPage = async (id, seqs, epoch, options) => {
9950
- await this.convert(id);
9951
- return inner.readSelectedPage(id, seqs, epoch, options);
9952
- };
10064
+ if (inner.readChildDisplayCut) this.readChildDisplayCut = async (id, launch) => (await this.readStore(id)).readChildDisplayCut(id, launch);
10065
+ if (inner.readChildCatalogCut) this.readChildCatalogCut = async (id) => (await this.readStore(id)).readChildCatalogCut(id);
10066
+ if (inner.readSelectedPage) this.readSelectedPage = async (id, seqs, epoch, options) => (await this.readStore(id)).readSelectedPage(id, seqs, epoch, options);
9953
10067
  if (inner.readScanPage) this.readScanPage = async (id, startSeq, endSeq, epoch, limit, options) => {
9954
- await this.convert(id);
9955
- return options === void 0 ? inner.readScanPage(id, startSeq, endSeq, epoch, limit) : inner.readScanPage(id, startSeq, endSeq, epoch, limit, options);
9956
- };
9957
- if (inner.readSnapshotCut) this.readSnapshotCut = async (id, options) => {
9958
- await this.convert(id);
9959
- return inner.readSnapshotCut(id, options);
10068
+ const store = await this.readStore(id);
10069
+ return options === void 0 ? store.readScanPage(id, startSeq, endSeq, epoch, limit) : store.readScanPage(id, startSeq, endSeq, epoch, limit, options);
9960
10070
  };
10071
+ if (inner.readSnapshotCut) this.readSnapshotCut = async (id, options) => (await this.readStore(id)).readSnapshotCut(id, options);
9961
10072
  if (inner.readBranchSnapshotMetadata) this.readBranchSnapshotMetadata = async (ids) => {
9962
10073
  const candidates = new Map(await inner.readBranchSnapshotMetadata(ids));
9963
10074
  for (const [id, candidate] of candidates) if (candidate === null) candidates.delete(id);
9964
10075
  return candidates;
9965
10076
  };
9966
- if (inner.readTreeOutline) this.readTreeOutline = async (id, from, to, epoch) => {
9967
- await this.convert(id);
9968
- return inner.readTreeOutline(id, from, to, epoch);
9969
- };
10077
+ if (inner.readTreeOutline) this.readTreeOutline = async (id, from, to, epoch) => (await this.readStore(id)).readTreeOutline(id, from, to, epoch);
9970
10078
  const { readEntryRange, searchIndex } = inner;
9971
10079
  if (readEntryRange !== void 0) this.readEntryRange = async (sessionId, query) => {
9972
10080
  query.signal?.throwIfAborted();
@@ -10011,29 +10119,27 @@ var LegacySessionStore = class LegacySessionStore {
10011
10119
  } catch (error) {
10012
10120
  if (!(error instanceof SessionNotFoundError)) throw error;
10013
10121
  }
10014
- await this.convert(sessionId);
10015
- return this.inner.append(sessionId, entries, options);
10122
+ const legacy = await this.readLegacy(sessionId);
10123
+ if (legacy === void 0) throw new SessionNotFoundError(sessionId);
10124
+ if (options.expectSeq !== legacy.lastSeq) throw new SessionConflictError(sessionId, options.expectSeq, legacy.lastSeq);
10125
+ return (await this.readStore(sessionId, legacy)).append(sessionId, entries, options);
10016
10126
  }
10017
10127
  async replace(sessionId, header, entries, options) {
10018
- await this.convert(sessionId);
10019
- return this.inner.replace(sessionId, header, entries, options);
10128
+ return (await this.readStore(sessionId)).replace(sessionId, header, entries, options);
10020
10129
  }
10021
10130
  async updateHeader(header, options) {
10022
- await this.convert(header.id);
10023
- return (await import("../core/storage/session/snapshot-history.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"))).updateStoredHeader(this.inner, header, options);
10131
+ return (await import("../core/storage/session/snapshot-history.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"))).updateStoredHeader(await this.readStore(header.id), header, options);
10024
10132
  }
10025
10133
  async load(sessionId) {
10026
- await this.convert(sessionId);
10027
- return this.inner.load(sessionId);
10134
+ return (await this.readStore(sessionId)).load(sessionId);
10028
10135
  }
10029
10136
  async readTail(sessionId, fromSeq) {
10030
- await this.convert(sessionId);
10031
- return readSessionTail(this.inner, sessionId, fromSeq);
10137
+ return readSessionTail(await this.readStore(sessionId), sessionId, fromSeq);
10032
10138
  }
10033
10139
  async readRange(sessionId, startSeq, endSeq, expectedEpoch) {
10034
- await this.convert(sessionId);
10035
- if (this.inner.readRange) return this.inner.readRange(sessionId, startSeq, endSeq, expectedEpoch);
10036
- const snapshot = await this.inner.load(sessionId);
10140
+ const store = await this.readStore(sessionId);
10141
+ if (store.readRange) return store.readRange(sessionId, startSeq, endSeq, expectedEpoch);
10142
+ const snapshot = await store.load(sessionId);
10037
10143
  const { assertSnapshotCut, snapshotStamp } = await import("../core/storage/session/snapshot-history.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
10038
10144
  assertSnapshotCut(snapshot, expectedEpoch, Math.min(endSeq, snapshot.lastSeq));
10039
10145
  return {
@@ -10042,14 +10148,14 @@ var LegacySessionStore = class LegacySessionStore {
10042
10148
  };
10043
10149
  }
10044
10150
  async readBranchSpan(sessionId, cut) {
10045
- await this.convert(sessionId);
10046
- if (this.inner.readBranchSpan) return this.inner.readBranchSpan(sessionId, cut);
10047
- return (await import("../core/storage/session/snapshot-history.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"))).snapshotBranchSpan(this.inner, sessionId, cut);
10151
+ const store = await this.readStore(sessionId);
10152
+ if (store.readBranchSpan) return store.readBranchSpan(sessionId, cut);
10153
+ return (await import("../core/storage/session/snapshot-history.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"))).snapshotBranchSpan(store, sessionId, cut);
10048
10154
  }
10049
10155
  async readEntrySizes(sessionId, startSeq, endSeq, limit) {
10050
- await this.convert(sessionId);
10051
- if (this.inner.readEntrySizes) return limit === void 0 ? this.inner.readEntrySizes(sessionId, startSeq, endSeq) : this.inner.readEntrySizes(sessionId, startSeq, endSeq, limit);
10052
- const snapshot = await this.inner.load(sessionId);
10156
+ const store = await this.readStore(sessionId);
10157
+ if (store.readEntrySizes) return limit === void 0 ? store.readEntrySizes(sessionId, startSeq, endSeq) : store.readEntrySizes(sessionId, startSeq, endSeq, limit);
10158
+ const snapshot = await store.load(sessionId);
10053
10159
  const { snapshotStamp } = await import("../core/storage/session/snapshot-history.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
10054
10160
  const start = Math.max(startSeq, 1);
10055
10161
  return {
@@ -10062,23 +10168,22 @@ var LegacySessionStore = class LegacySessionStore {
10062
10168
  };
10063
10169
  }
10064
10170
  async readEntryChunk(reference, offset, bytes) {
10065
- await this.convert(reference.sessionId);
10066
- if (this.inner.readEntryChunk) return bytes === void 0 ? this.inner.readEntryChunk(reference, offset) : this.inner.readEntryChunk(reference, offset, bytes);
10067
- return (await import("../core/storage/session/snapshot-history.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"))).snapshotChunk(this.inner, reference, offset);
10171
+ const store = await this.readStore(reference.sessionId);
10172
+ if (store.readEntryChunk) return bytes === void 0 ? store.readEntryChunk(reference, offset) : store.readEntryChunk(reference, offset, bytes);
10173
+ return (await import("../core/storage/session/snapshot-history.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"))).snapshotChunk(store, reference, offset);
10068
10174
  }
10069
10175
  async findLatestCompaction(sessionId, leafId) {
10070
- await this.convert(sessionId);
10071
- return findSessionCompaction(this.inner, sessionId, leafId);
10176
+ return findSessionCompaction(await this.readStore(sessionId), sessionId, leafId);
10072
10177
  }
10073
10178
  async readResume(sessionId, leafId, options) {
10074
- await this.convert(sessionId);
10075
- if (this.inner.readResume) return options ? this.inner.readResume(sessionId, leafId, options) : this.inner.readResume(sessionId, leafId);
10076
- return (await import("../core/storage/session/snapshot-history.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"))).snapshotWindow(this.inner, sessionId, leafId, void 0, void 0, isProxy);
10179
+ const store = await this.readStore(sessionId);
10180
+ if (store.readResume) return options ? store.readResume(sessionId, leafId, options) : store.readResume(sessionId, leafId);
10181
+ return (await import("../core/storage/session/snapshot-history.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"))).snapshotWindow(store, sessionId, leafId, void 0, void 0, isProxy);
10077
10182
  }
10078
10183
  async findEntrySeq(sessionId, entryId) {
10079
- await this.convert(sessionId);
10080
- if (this.inner.findEntrySeq) return this.inner.findEntrySeq(sessionId, entryId);
10081
- const index = (await this.inner.load(sessionId)).entries.findLastIndex((entry) => entry.id === entryId);
10184
+ const store = await this.readStore(sessionId);
10185
+ if (store.findEntrySeq) return store.findEntrySeq(sessionId, entryId);
10186
+ const index = (await store.load(sessionId)).entries.findLastIndex((entry) => entry.id === entryId);
10082
10187
  return index < 0 ? void 0 : index + 1;
10083
10188
  }
10084
10189
  /**
@@ -10145,11 +10250,24 @@ var LegacySessionStore = class LegacySessionStore {
10145
10250
  await Promise.all([legacy?.then((store) => store?.close()).catch(() => {}), deletions?.then((database) => database.close()).catch(() => {})]);
10146
10251
  await this.inner.close();
10147
10252
  }
10253
+ /** A damaged legacy session stays in its original file; opening it must not publish that damage in SQLite. */
10254
+ async readStore(sessionId, legacySnapshot) {
10255
+ try {
10256
+ await this.convert(sessionId, legacySnapshot);
10257
+ return this.inner;
10258
+ } catch (error) {
10259
+ if (!(error instanceof SessionInvalidParentError || error instanceof SessionDuplicateEntryError)) throw error;
10260
+ const legacy = await this.legacyStore();
10261
+ if (legacy === void 0) throw error;
10262
+ return legacy;
10263
+ }
10264
+ }
10148
10265
  /** Convert one legacy session into the database the first time it is needed. */
10149
- async convert(sessionId) {
10266
+ async convert(sessionId, legacySnapshot) {
10150
10267
  if (await this.inner.readHeader(sessionId) !== void 0) return;
10151
- const snapshot = await this.readLegacy(sessionId);
10268
+ const snapshot = legacySnapshot ?? await this.readLegacy(sessionId);
10152
10269
  if (snapshot === void 0) return;
10270
+ validateSessionParentWrites(snapshot.entries);
10153
10271
  try {
10154
10272
  await this.inner.create(snapshot.header, snapshot.entries);
10155
10273
  } catch (error) {
@@ -10302,7 +10420,7 @@ function __atomicOnDemandFailed(error, feature) {
10302
10420
  return (async () => {
10303
10421
  const root = new URL("../", import.meta.url);
10304
10422
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
10305
- const key = `${root.href}#0.10.20-alpha.1`;
10423
+ const key = `${root.href}#0.10.20-alpha.2`;
10306
10424
  let release = releases.get(key);
10307
10425
  if (release === undefined) {
10308
10426
  const current = (async () => {
@@ -10330,7 +10448,7 @@ function __atomicOnDemandFailed(error, feature) {
10330
10448
  } catch {
10331
10449
  // No installation to read, as in a bundle of the package: the release the process runs decides.
10332
10450
  }
10333
- const updatedTo = typeof installed === "string" && installed !== "0.10.20-alpha.1" ? installed : running !== undefined && running.version !== "0.10.20-alpha.1" ? "0.10.20-alpha.1" : undefined;
10451
+ const updatedTo = typeof installed === "string" && installed !== "0.10.20-alpha.2" ? installed : running !== undefined && running.version !== "0.10.20-alpha.2" ? "0.10.20-alpha.2" : undefined;
10334
10452
  if (updatedTo === undefined) throw error;
10335
10453
  const application = typeof running?.name === "string" ? running.name : "atomic";
10336
10454
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {