@bastani/atomic 0.10.19 → 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 (377) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/dist/_shared/adapter-open-DXXV6ATH.js +22 -0
  3. package/dist/_shared/adapter-open-DXXV6ATH.js.map +1 -0
  4. package/dist/_shared/dist-KOELCESV.js +2 -2
  5. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  6. package/dist/_shared/lib-4PES5P4V.js +2 -2
  7. package/dist/_shared/mode-interactive-sdk-JXBZ3H27.js +484 -229
  8. package/dist/_shared/mode-interactive-sdk-JXBZ3H27.js.map +1 -1
  9. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +63 -16
  10. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js.map +1 -1
  11. package/dist/_shared/mode-shared-2QJSCUM6.js +61 -16
  12. package/dist/_shared/mode-shared-2QJSCUM6.js.map +1 -1
  13. package/dist/_shared/p0-cli-BB45ZQY6.js +2 -2
  14. package/dist/_shared/p1a-prewarm-XIU57JHF.js +3 -3
  15. package/dist/_shared/p1b-elig-BY2G5BUE.js +6 -3
  16. package/dist/_shared/p1b-elig-BY2G5BUE.js.map +1 -1
  17. package/dist/_shared/runtime-O4KCSG4C.js +5 -5
  18. package/dist/_shared/{sdk-BHX35EPK.js → sdk-5ZFNDXUJ.js} +319 -86
  19. package/dist/_shared/sdk-5ZFNDXUJ.js.map +1 -0
  20. package/dist/_shared/session-data-AHTU7IS6.js +15 -7
  21. package/dist/_shared/session-data-AHTU7IS6.js.map +1 -1
  22. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  23. package/dist/_shared/settings-startup-HXQLSUWM.js +2 -2
  24. package/dist/_shared/settings-startup-HXQLSUWM.js.map +1 -1
  25. package/dist/_shared/{startup-0-0-4EDVBK5P.js → startup-0-0-OWBJIX35.js} +162 -44
  26. package/dist/_shared/startup-0-0-OWBJIX35.js.map +1 -0
  27. package/dist/_shared/{startup-0-1-H5IXVRXQ.js → startup-0-1-DZYE4E5Z.js} +462 -37
  28. package/dist/_shared/startup-0-1-DZYE4E5Z.js.map +1 -0
  29. package/dist/_shared/{startup-0-2-YZZOC22D.js → startup-0-2-WFLTE4SC.js} +147 -6
  30. package/dist/_shared/startup-0-2-WFLTE4SC.js.map +1 -0
  31. package/dist/_shared/startup-0-3-DE2NCS6A.js +59 -50
  32. package/dist/_shared/startup-0-3-DE2NCS6A.js.map +1 -1
  33. package/dist/_shared/{startup-0-4-ZMJV547D.js → startup-0-4-6XXL4JMZ.js} +115 -25
  34. package/dist/_shared/startup-0-4-6XXL4JMZ.js.map +1 -0
  35. package/dist/_shared/{startup-0-5-HZX3ZPTP.js → startup-0-5-DNS6FYS7.js} +229 -156
  36. package/dist/_shared/startup-0-5-DNS6FYS7.js.map +1 -0
  37. package/dist/_shared/{startup-10-0-TDQNBDDL.js → startup-10-0-O6DAT7U4.js} +131 -162
  38. package/dist/_shared/startup-10-0-O6DAT7U4.js.map +1 -0
  39. package/dist/_shared/startup-12-0-55AAXBJZ.js +3 -3
  40. package/dist/_shared/startup-14-0-MLX36RBG.js +9 -6
  41. package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
  42. package/dist/_shared/{startup-15-0-YUKGAC63.js → startup-15-0-E7RYG5YF.js} +9 -9
  43. package/dist/_shared/{startup-15-0-YUKGAC63.js.map → startup-15-0-E7RYG5YF.js.map} +1 -1
  44. package/dist/_shared/startup-15-1-WQZBOTMZ.js +340 -128
  45. package/dist/_shared/startup-15-1-WQZBOTMZ.js.map +1 -1
  46. package/dist/_shared/startup-8-0-34CBHPZH.js +279 -151
  47. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  48. package/dist/_shared/{startup-8-1-QZMXUGHI.js → startup-8-1-VXBL37AI.js} +352 -27
  49. package/dist/_shared/startup-8-1-VXBL37AI.js.map +1 -0
  50. package/dist/_shared/storage-command-7MGXLJGZ.js +15 -273
  51. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  52. package/dist/_shared/{storage-status-K7PX2RXA.js → storage-status-T6FUXRIM.js} +8 -24
  53. package/dist/_shared/{storage-status-K7PX2RXA.js.map → storage-status-T6FUXRIM.js.map} +1 -1
  54. package/dist/_shared/task-reference-stream-JWMUZSJX.js +1 -1
  55. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  56. package/dist/_shared/team-DOQKICG2.js +4 -3
  57. package/dist/_shared/team-DOQKICG2.js.map +1 -1
  58. package/dist/_shared/tree-outline-MUEPK5B7.js +9 -2
  59. package/dist/_shared/tree-outline-MUEPK5B7.js.map +1 -1
  60. package/dist/binary-self-update.js +3 -3
  61. package/dist/builtin/intercom/broker/broker.bundle.mjs +46 -8
  62. package/dist/builtin/intercom/broker/broker.ts +1 -0
  63. package/dist/builtin/intercom/broker/client.ts +5 -1
  64. package/dist/builtin/intercom/broker/departed-children.ts +12 -6
  65. package/dist/builtin/intercom/broker/ended-child-wakes.ts +2 -0
  66. package/dist/builtin/intercom/index.bundle.mjs +130 -264
  67. package/dist/builtin/intercom/message-display.ts +42 -0
  68. package/dist/builtin/intercom/package.json +1 -1
  69. package/dist/builtin/intercom/types.ts +1 -0
  70. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  71. package/dist/builtin/mcp/package.json +1 -1
  72. package/dist/builtin/subagents/package.json +1 -1
  73. package/dist/builtin/subagents/src/extension/index.bundle.mjs +99 -20
  74. package/dist/builtin/web-access/index.bundle.mjs +15 -9
  75. package/dist/builtin/web-access/package.json +1 -1
  76. package/dist/cli/args.js +2 -2
  77. package/dist/cli/auth-cli.code.js +6 -6
  78. package/dist/cli/auth-cli.impl.js +3 -3
  79. package/dist/cli/auth-cli.js +3 -3
  80. package/dist/cli/blueprint-command.code.js +4 -4
  81. package/dist/cli/blueprint-command.impl.js +3 -3
  82. package/dist/cli/blueprint-command.js +3 -3
  83. package/dist/cli/intercom-command.code.js +3 -3
  84. package/dist/cli/intercom-command.impl.js +3 -3
  85. package/dist/cli/intercom-command.js +3 -3
  86. package/dist/cli/list-models.code.js +3 -3
  87. package/dist/cli/list-models.impl.js +3 -3
  88. package/dist/cli/list-models.js +3 -3
  89. package/dist/cli/session-picker.code.js +2 -2
  90. package/dist/cli/session-picker.impl.js +3 -3
  91. package/dist/cli/session-picker.js +3 -3
  92. package/dist/cli/startup-ui.code.js +2 -2
  93. package/dist/cli/startup-ui.impl.js +3 -3
  94. package/dist/cli/startup-ui.js +3 -3
  95. package/dist/cli/storage-command.impl.js +3 -3
  96. package/dist/cli/storage-command.js +3 -3
  97. package/dist/cli/storage-search-session.code.js +3 -3
  98. package/dist/cli/storage-search-session.impl.js +3 -3
  99. package/dist/cli/storage-search-session.js +3 -3
  100. package/dist/cli/team-command.code.js +3 -3
  101. package/dist/cli/team-command.impl.js +3 -3
  102. package/dist/cli/team-command.js +3 -3
  103. package/dist/cli.js +2 -2
  104. package/dist/core/agent-session-runtime.d.ts +16 -4
  105. package/dist/core/agent-session-types.d.ts +5 -1
  106. package/dist/core/debug.impl.js +3 -3
  107. package/dist/core/debug.js +3 -3
  108. package/dist/core/export-html/card-projection.code.js +74 -72
  109. package/dist/core/export-html/card-projection.code.js.map +1 -1
  110. package/dist/core/export-html/card-projection.impl.js +3 -3
  111. package/dist/core/export-html/card-projection.js +3 -3
  112. package/dist/core/export-html/index.code.js +52 -41
  113. package/dist/core/export-html/index.code.js.map +1 -1
  114. package/dist/core/export-html/index.impl.js +3 -3
  115. package/dist/core/export-html/index.js +3 -3
  116. package/dist/core/export-html/json-spans.impl.js +3 -3
  117. package/dist/core/export-html/json-spans.js +3 -3
  118. package/dist/core/export-html/oversized-render-inputs.code.js +1 -1
  119. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  120. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  121. package/dist/core/export-html/template.js +27 -39
  122. package/dist/core/export-html/tool-renderer.code.js +1 -1
  123. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  124. package/dist/core/export-html/tool-renderer.js +3 -3
  125. package/dist/core/extensions/context-types.d.ts +3 -0
  126. package/dist/core/extensions/context-types.js.map +1 -1
  127. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  128. package/dist/core/extensions/jiti-loader.js +3 -3
  129. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  130. package/dist/core/extensions/jiti-static-loader.js +3 -3
  131. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  132. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  133. package/dist/core/extensions/loader-host-modules.js +3 -3
  134. package/dist/core/extensions/loader-virtual-modules.js +2 -2
  135. package/dist/core/extensions/runner-context.d.ts +1 -0
  136. package/dist/core/extensions/runner-context.js +18 -2
  137. package/dist/core/extensions/runner-context.js.map +1 -1
  138. package/dist/core/extensions/runner.d.ts +1 -0
  139. package/dist/core/extensions/runtime-types.d.ts +1 -0
  140. package/dist/core/extensions/runtime-types.js.map +1 -1
  141. package/dist/core/intercom-broker-control-host.code.js +1 -1
  142. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  143. package/dist/core/intercom-broker-control-host.js +3 -3
  144. package/dist/core/intercom-broker-control.code.js +3 -3
  145. package/dist/core/intercom-broker-control.impl.js +3 -3
  146. package/dist/core/intercom-broker-control.js +3 -3
  147. package/dist/core/model-registry.js +2 -2
  148. package/dist/core/model-runtime-streaming.d.ts +3 -1
  149. package/dist/core/model-runtime.d.ts +2 -0
  150. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  151. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  152. package/dist/core/package-manager-storage-adapters.js +3 -3
  153. package/dist/core/resume/failure.d.ts +1 -1
  154. package/dist/core/sdk.code.js +4 -4
  155. package/dist/core/sdk.impl.js +3 -3
  156. package/dist/core/sdk.js +3 -3
  157. package/dist/core/session-claims.d.ts +13 -2
  158. package/dist/core/session-load-events.d.ts +42 -0
  159. package/dist/core/session-manager-core.d.ts +17 -2
  160. package/dist/core/session-manager-core.js +234 -93
  161. package/dist/core/session-manager-core.js.map +1 -1
  162. package/dist/core/session-manager-errors.d.ts +2 -2
  163. package/dist/core/session-manager-history.d.ts +1 -1
  164. package/dist/core/session-manager-list.impl.js +3 -3
  165. package/dist/core/session-manager-list.js +3 -3
  166. package/dist/core/session-manager.code.js +2 -2
  167. package/dist/core/session-manager.impl.js +3 -3
  168. package/dist/core/session-manager.js +3 -3
  169. package/dist/core/session-storage.code.js +1 -1
  170. package/dist/core/session-storage.impl.js +3 -3
  171. package/dist/core/session-storage.js +3 -3
  172. package/dist/core/settings-manager.js +2 -2
  173. package/dist/core/storage/adapter-open.js +3 -0
  174. package/dist/core/storage/adapter-open.js.map +1 -0
  175. package/dist/core/storage/index.js +2 -2
  176. package/dist/core/storage/node-sqlite-thread.js +2 -2
  177. package/dist/core/storage/node-sqlite.js +2 -2
  178. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  179. package/dist/core/storage/offline-snapshot-file.js +3 -3
  180. package/dist/core/storage/prefix.js +1 -0
  181. package/dist/core/storage/prefix.js.map +1 -1
  182. package/dist/core/storage/provider.js +2 -2
  183. package/dist/core/storage/schema-catalog.d.ts +2 -1
  184. package/dist/core/storage/schema-catalog.js +25 -6
  185. package/dist/core/storage/schema-catalog.js.map +1 -1
  186. package/dist/core/storage/selection.js +2 -2
  187. package/dist/core/storage/session/branch-fork-source.code.js +17 -4
  188. package/dist/core/storage/session/branch-fork-source.code.js.map +1 -1
  189. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  190. package/dist/core/storage/session/branch-fork-source.js +3 -3
  191. package/dist/core/storage/session/card-view.impl.js +3 -3
  192. package/dist/core/storage/session/card-view.js +3 -3
  193. package/dist/core/storage/session/child-reader.code.js +7 -7
  194. package/dist/core/storage/session/child-reader.code.js.map +1 -1
  195. package/dist/core/storage/session/child-reader.d.ts +1 -0
  196. package/dist/core/storage/session/child-reader.impl.js +3 -3
  197. package/dist/core/storage/session/child-reader.js +3 -3
  198. package/dist/core/storage/session/chunked-resume-projection.code.js +1 -1
  199. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  200. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  201. package/dist/core/storage/session/expanded-child-details.code.js +3 -3
  202. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  203. package/dist/core/storage/session/expanded-child-details.js +3 -3
  204. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  205. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  206. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  207. package/dist/core/storage/session/fork-row-index.js +3 -3
  208. package/dist/core/storage/session/fork-staging.code.js +9 -5
  209. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  210. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  211. package/dist/core/storage/session/fork-staging.js +3 -3
  212. package/dist/core/storage/session/fork-window.code.js +29 -13
  213. package/dist/core/storage/session/fork-window.code.js.map +1 -1
  214. package/dist/core/storage/session/fork-window.impl.js +3 -3
  215. package/dist/core/storage/session/fork-window.js +3 -3
  216. package/dist/core/storage/session/history-pages.impl.js +3 -3
  217. package/dist/core/storage/session/history-pages.js +3 -3
  218. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  219. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  220. package/dist/core/storage/session/jsonl-session-store.d.ts +8 -4
  221. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  222. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  223. package/dist/core/storage/session/memory-session-store.d.ts +3 -3
  224. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  225. package/dist/core/storage/session/memory-session-store.js +3 -3
  226. package/dist/core/storage/session/parent-links.d.ts +122 -0
  227. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  228. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  229. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  230. package/dist/core/storage/session/released-history-files.code.js +3 -3
  231. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  232. package/dist/core/storage/session/released-history-files.js +3 -3
  233. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  234. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  235. package/dist/core/storage/session/session-resume.impl.js +3 -3
  236. package/dist/core/storage/session/session-resume.js +3 -3
  237. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  238. package/dist/core/storage/session/snapshot-cut.js +3 -3
  239. package/dist/core/storage/session/snapshot-history.code.js +5 -6
  240. package/dist/core/storage/session/snapshot-history.code.js.map +1 -1
  241. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  242. package/dist/core/storage/session/snapshot-history.js +3 -3
  243. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  244. package/dist/core/storage/session/sql-session-store.d.ts +7 -20
  245. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  246. package/dist/core/storage/session/sql-session-store.js +3 -3
  247. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  248. package/dist/core/storage/session/tree-outline.js +3 -3
  249. package/dist/core/storage/session/tree-presentation.code.js +1 -1
  250. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  251. package/dist/core/storage/session/tree-presentation.js +3 -3
  252. package/dist/core/storage/session/types.d.ts +11 -3
  253. package/dist/core/storage/session/usage-observations.d.ts +27 -0
  254. package/dist/core/storage/session/usage-observations.js +3 -0
  255. package/dist/core/storage/session/usage-observations.js.map +1 -0
  256. package/dist/core/storage/storage-status.code.js +1 -1
  257. package/dist/core/storage/storage-status.impl.js +3 -3
  258. package/dist/core/storage/storage-status.js +3 -3
  259. package/dist/core/storage/team.impl.js +3 -3
  260. package/dist/core/storage/team.js +3 -3
  261. package/dist/core/structured-output/index.code.js +1 -1
  262. package/dist/core/structured-output/index.impl.js +3 -3
  263. package/dist/core/structured-output/index.js +3 -3
  264. package/dist/core/subscription-usage-identity.d.ts +9 -0
  265. package/dist/core/subscription-usage-observations.d.ts +15 -0
  266. package/dist/core/subscription-usage-storage.js +3 -0
  267. package/dist/core/subscription-usage-storage.js.map +1 -0
  268. package/dist/core/subscription-usage.d.ts +20 -3
  269. package/dist/core/tasks/task-completion-entry.code.js +1 -1
  270. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  271. package/dist/core/tasks/task-completion-entry.js +3 -3
  272. package/dist/core/tasks/task-file-history.code.js +3 -3
  273. package/dist/core/tasks/task-file-history.impl.js +3 -3
  274. package/dist/core/tasks/task-file-history.js +3 -3
  275. package/dist/core/tasks/task-reference-archive.code.js +5 -5
  276. package/dist/core/tasks/task-reference-archive.js +3 -3
  277. package/dist/core/tasks/task-reference-identity.code.js +1 -1
  278. package/dist/core/tasks/task-reference-identity.js +3 -3
  279. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  280. package/dist/core/tasks/task-reference-stream.js +3 -3
  281. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  282. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  283. package/dist/core/tasks/task-view-source.code.js +1 -1
  284. package/dist/core/tasks/task-view-source.impl.js +3 -3
  285. package/dist/core/tasks/task-view-source.js +3 -3
  286. package/dist/core/tools/read-url.code.js +3 -3
  287. package/dist/core/tools/read-url.impl.js +3 -3
  288. package/dist/core/tools/read-url.js +3 -3
  289. package/dist/core/worktree-snapshot/blob-store.js +2 -2
  290. package/dist/core/worktree-snapshot/errors.code.js +3 -3
  291. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  292. package/dist/core/worktree-snapshot/errors.js +3 -3
  293. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  294. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  295. package/dist/extensions/codemode/execute.code.js +2 -2
  296. package/dist/extensions/codemode/execute.impl.js +3 -3
  297. package/dist/extensions/codemode/execute.js +3 -3
  298. package/dist/extensions/codemode/renderer.code.js +12 -7
  299. package/dist/extensions/codemode/renderer.code.js.map +1 -1
  300. package/dist/extensions/codemode/renderer.impl.js +3 -3
  301. package/dist/extensions/codemode/renderer.js +3 -3
  302. package/dist/extensions/mcp/cli.code.js +3 -3
  303. package/dist/extensions/mcp/cli.impl.js +3 -3
  304. package/dist/extensions/mcp/cli.js +3 -3
  305. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  306. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  307. package/dist/extensions/mcp/cli.lazy.js +3 -3
  308. package/dist/extensions/mcp/runtime.code.js +1 -1
  309. package/dist/extensions/mcp/runtime.impl.js +3 -3
  310. package/dist/extensions/mcp/runtime.js +3 -3
  311. package/dist/index.d.ts +6 -3
  312. package/dist/index.js +10 -10
  313. package/dist/main-first-time-setup.code.js +2 -2
  314. package/dist/main-first-time-setup.impl.js +3 -3
  315. package/dist/main-first-time-setup.js +3 -3
  316. package/dist/main.js +1 -1
  317. package/dist/modes/index.d.ts +1 -1
  318. package/dist/modes/interactive/components/intercom-wake-notice.d.ts +4 -0
  319. package/dist/modes/interactive/components/notice-line.d.ts +1 -1
  320. package/dist/modes/interactive/components/stored-tree-view.code.js +6 -5
  321. package/dist/modes/interactive/components/stored-tree-view.code.js.map +1 -1
  322. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  323. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  324. package/dist/modes/interactive/components/tool-block.d.ts +5 -1
  325. package/dist/modes/interactive/components/user-message-selector-archive.code.js +1 -1
  326. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  327. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  328. package/dist/modes/interactive-engine/isolated-runtime.d.ts +4 -3
  329. package/dist/modes/print-mode.js +1 -1
  330. package/dist/modes/rpc/rpc-client-api.d.ts +5 -0
  331. package/dist/modes/rpc/rpc-client.d.ts +1 -1
  332. package/dist/modes/rpc/rpc-types.d.ts +26 -3
  333. package/dist/package-manager-cli.code.js +7 -7
  334. package/dist/package-manager-cli.impl.js +3 -3
  335. package/dist/package-manager-cli.js +3 -3
  336. package/dist/rpc-entry.js +1 -1
  337. package/dist/startup-files.json +1 -1
  338. package/dist/startup-stages/10.js +1 -1
  339. package/dist/startup-stages/12.js +1 -1
  340. package/dist/startup-stages/13.js +2 -1
  341. package/dist/startup-stages/14.js +1 -0
  342. package/dist/startup-stages/4.js +1 -1
  343. package/dist/startup-stages/6.js +1 -1
  344. package/dist/startup-stages/7.js +1 -1
  345. package/dist/startup-stages/8.js +1 -1
  346. package/dist/startup-stages/stages.json +1 -1
  347. package/dist/utils/startup-database-spare.code.js +3 -3
  348. package/dist/utils/startup-database-spare.impl.js +3 -3
  349. package/dist/utils/startup-database-spare.js +3 -3
  350. package/dist/utils/tools-manager.code.js +1 -1
  351. package/dist/utils/tools-manager.impl.js +3 -3
  352. package/dist/utils/tools-manager.js +3 -3
  353. package/docs/.agents/context/DESIGN.md +30 -0
  354. package/docs/changelog.mdx +46 -0
  355. package/docs/docs.json +1 -1
  356. package/docs/extensions/api-reference.md +6 -0
  357. package/docs/guides/subscription-usage.md +28 -82
  358. package/docs/intercom.md +3 -1
  359. package/docs/json.md +3 -3
  360. package/docs/providers.md +2 -0
  361. package/docs/reference/cli.md +3 -1
  362. package/docs/rpc/protocol.md +31 -3
  363. package/docs/sdk/reference.md +26 -1
  364. package/docs/sdk.md +2 -0
  365. package/docs/sessions.md +38 -1
  366. package/docs/slash-commands.md +1 -1
  367. package/docs/subagents.md +2 -0
  368. package/docs/usage.md +1 -1
  369. package/package.json +8 -8
  370. package/dist/_shared/sdk-BHX35EPK.js.map +0 -1
  371. package/dist/_shared/startup-0-0-4EDVBK5P.js.map +0 -1
  372. package/dist/_shared/startup-0-1-H5IXVRXQ.js.map +0 -1
  373. package/dist/_shared/startup-0-2-YZZOC22D.js.map +0 -1
  374. package/dist/_shared/startup-0-4-ZMJV547D.js.map +0 -1
  375. package/dist/_shared/startup-0-5-HZX3ZPTP.js.map +0 -1
  376. package/dist/_shared/startup-10-0-TDQNBDDL.js.map +0 -1
  377. package/dist/_shared/startup-8-1-QZMXUGHI.js.map +0 -1
@@ -5,16 +5,16 @@ import { isProxy } from "node:util/types";
5
5
  import { getCurrentSystemMessage } from "@bastani/atomic-ai";
6
6
  import { recordsStrictToolLimits } from "@bastani/atomic-ai/api/strict-tool-limits";
7
7
  import { createSessionCwdMatcherAsync, getAgentDir, normalizePath, pathsEqual, resolvePath } from "../_shared/p0-cli-BB45ZQY6.js";
8
- import { SessionAppendRecovery, TOOL_DEACTIVATION_ENTRY_TYPE, chatEpoch, classifiedWorkflowMetadata, findMostRecentResumable, forkScope, forkStoreRelation, getDefaultSessionDirPath, postgresAppendRetryableFailure, storedRows, yieldToEventLoop } from "../_shared/startup-0-0-4EDVBK5P.js";
9
- import { ChildCatalog, SessionKeyDigests, TOOL_OUTPUT_ENTRY_TYPE, WorkspaceConfigError, assertSessionBlobStore, carriedTransformedPrompt, carryCompletionEvidence, convertToLlm, copySessionBlobs, sessionBlobHashes, shareCompletionEvidence, storeInlineToolOutputs, storeSessionBlobs, takeInlineToolOutput, takeInlineToolOutputEntry, writeChunksAtomically } from "../_shared/startup-0-1-H5IXVRXQ.js";
8
+ import { SessionAppendRecovery, TOOL_DEACTIVATION_ENTRY_TYPE, chatEpoch, classifiedWorkflowMetadata, findMostRecentResumable, forkScope, forkStoreRelation, getDefaultSessionDirPath, postgresAppendRetryableFailure, storedRows, yieldToEventLoop } from "../_shared/startup-0-0-OWBJIX35.js";
9
+ import { ChildCatalog, SessionKeyDigests, TOOL_OUTPUT_ENTRY_TYPE, WorkspaceConfigError, assertSessionBlobStore, carriedTransformedPrompt, carryCompletionEvidence, convertToLlm, copySessionBlobs, damagedHistoryWarning, hasDamagedHistoryLinks, isDetachedReceipt, isEarlierSessionEntry, isStorageTransferError, parentIdInEarlierRows, prepareImportedSessionParents, recordedSessionBranch, recordedSessionParents, repairAppendedSessionParents, repairSessionParentWrites, sessionBlobHashes, shareCompletionEvidence, storeInlineToolOutputs, storeSessionBlobs, takeInlineToolOutput, takeInlineToolOutputEntry, warnDamagedHistoryLinks, writeChunksAtomically } from "../_shared/startup-0-1-DZYE4E5Z.js";
10
10
  import { LEAF_MOVE_ENTRY_TYPE, applyContextEdit, assertSessionNotOpenElsewhere, buildContextEntries, buildSessionIndex, buildSessionProjection, buildSessionTree, collectContextEdits, getBranchPath, getLatestCompactionBoundaryEntry, holdSessionOpenMarker, isLeafMoveEntry } from "../_shared/startup-0-3-DE2NCS6A.js";
11
- import { SessionConflictError, SessionFormatVersionError, SessionIdMismatchError, SessionNotFoundError, StorageUnavailableError } from "./storage/session/errors.js";
11
+ import { SessionConflictError, SessionExistsError, SessionFormatVersionError, SessionIdMismatchError, SessionNotFoundError, StorageUnavailableError } from "./storage/session/errors.js";
12
12
  import { EMPTY_SESSION_HISTORY_TOTALS, JsonlSessionStore, MemorySessionStore, addEntryToHistoryTotals, appendFailureWroteNothing, archivedAnswerAt, assertValidSessionId, bindSessionFile, createBranchSummaryEntry, createCompactionEntry, createContextEditEntry, createCustomEntry, createCustomMessageEntry, createLabelEntry, createMessageEntry, createModelChangeEntry, createSessionFilePath, createSessionHeader, createSessionId, createSessionInfoEntry, createSessionSummaryEntry, createThinkingLevelChangeEntry, createWorktreeSnapshotEntry, earlierTranscriptCursor, findInSessionHistory, findWorktreeSnapshotRecords, firstHistoryCursor, generateId, getEntriesWithoutHeader, getLatestSessionName, historyChunks, historyPages, isExtensionCustomState, lastBranchAnswer, markPrivateMemorySessionStore, readSessionRange, recoveryWitnessesOf, savedWindowAnswer, sessionResumeOf, storeSnapshotIndex, updateWorkflowStarts, validateSessionEntryStructure, validateSessionFileEntries, withForkFileWindow, witnessedIn, worktreeSnapshotPages } from "../_shared/startup-8-0-34CBHPZH.js";
13
13
  import { SESSION_HISTORY_SCAN_ENTRIES, SessionDeletedError, SessionEntryError } from "../_shared/settings-startup-HXQLSUWM.js";
14
14
  import { listProjectSessions, resolveParentSessionPaths } from "../_shared/session-manager-list-2BLEEZVG.js";
15
- import { adoptInlineSnapshotBlobs, deleteSessionWithSnapshotRefs } from "../_shared/startup-8-1-QZMXUGHI.js";
15
+ import { adoptInlineSnapshotBlobs, applySessionImport, deleteSessionWithSnapshotRefs, planSessionImport } from "../_shared/startup-8-1-VXBL37AI.js";
16
16
  import { SessionBlobError, StorageRollbackError, isStorageTransientError } from "./storage/errors.js";
17
- import "../_shared/startup-0-2-YZZOC22D.js";
17
+ import "../_shared/startup-0-2-WFLTE4SC.js";
18
18
  // dist/core/fork-context-path.js
19
19
  const forkSettings = /* @__PURE__ */ new Set([
20
20
  "workspace_binding",
@@ -24,7 +24,7 @@ const forkSettings = /* @__PURE__ */ new Set([
24
24
  /** A fork at a specific point can inherit only ancestor receipts. An unqualified current-leaf fork can also
25
25
  * keep a named output that the same session stored on another branch before the boundary. Neither copies
26
26
  * receipts just because they exist, or reads past its captured watermark. */
27
- async function includeNamedForkOutputs(entries, store, sessionId, leaf, epoch, through, scope, archives) {
27
+ async function includeNamedForkOutputs(entries, store, sessionId, leaf, epoch, through, scope, archives, branchLeafSeq) {
28
28
  if (!leaf || scope === "branch" && !getLatestCompactionBoundaryEntry(entries)) return entries;
29
29
  const wanted = /* @__PURE__ */ new Set();
30
30
  const scan = (value) => {
@@ -42,6 +42,8 @@ async function includeNamedForkOutputs(entries, store, sessionId, leaf, epoch, t
42
42
  const ancestors = /* @__PURE__ */ new Set();
43
43
  const positions = new Map(entries.map((entry) => [entry.id, 0]));
44
44
  let next = leaf;
45
+ let span;
46
+ const indexedBranch = branchLeafSeq !== void 0 && store.readBranchSpan !== void 0;
45
47
  search: for await (const { items } of historyPages(store, sessionId, epoch, through, { direction: "backward" })) for (let i = items.length - 1; i >= 0; i--) {
46
48
  const item = items[i];
47
49
  const links = "entry" in item ? {
@@ -50,7 +52,18 @@ async function includeNamedForkOutputs(entries, store, sessionId, leaf, epoch, t
50
52
  hash: hashOf(item.entry)
51
53
  } : await (await import("./storage/session/chunked-resume-projection.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"))).chunkedForkLink(() => historyChunks(store, sessionId, epoch, item, {}));
52
54
  if (links.id !== void 0 && positions.has(links.id)) positions.set(links.id, item.seq);
53
- const ancestor = links.id === next;
55
+ let ancestor;
56
+ if (indexedBranch) {
57
+ if (item.seq <= branchLeafSeq && (span === void 0 || item.seq < span.start)) span = await store.readBranchSpan(sessionId, {
58
+ leaf: branchLeafSeq,
59
+ first: 1,
60
+ last: branchLeafSeq,
61
+ pivot: item.seq,
62
+ backward: true,
63
+ epoch
64
+ });
65
+ ancestor = span !== void 0 && item.seq >= span.start && item.seq <= span.end;
66
+ } else ancestor = links.id === next;
54
67
  if (!ancestor && scope === "branch") continue;
55
68
  if (links.hash && wanted.has(links.hash)) {
56
69
  let candidate;
@@ -96,8 +109,8 @@ async function includeNamedForkOutputs(entries, store, sessionId, leaf, epoch, t
96
109
  wanted.delete(links.hash);
97
110
  }
98
111
  }
99
- if (ancestor) next = links.parentId ?? null;
100
- if (!wanted.size || !next && scope === "branch") break search;
112
+ if (!indexedBranch && ancestor) next = parentIdInEarlierRows(links);
113
+ if (!wanted.size || !indexedBranch && !next && scope === "branch") break search;
101
114
  }
102
115
  if (!found.length) return entries;
103
116
  const archived = new Map(found.reverse().map((entry) => [entry.id, entry]));
@@ -270,6 +283,24 @@ function within(parent, child) {
270
283
  var SessionHistoryIndex = class {
271
284
  view;
272
285
  scan;
286
+ positions;
287
+ repeatedEntries;
288
+ constructor(positions, repeatedEntries) {
289
+ this.positions = positions;
290
+ this.repeatedEntries = repeatedEntries;
291
+ }
292
+ /** A retained window can contain distinct rows with the same legacy ID. Keep the resolved path from storage. */
293
+ restoreBranch(leafId, byId, links, path) {
294
+ this.view = {
295
+ byId,
296
+ links,
297
+ leafId,
298
+ path,
299
+ mappings: void 0,
300
+ continuations: void 0,
301
+ snapshots: void 0
302
+ };
303
+ }
273
304
  /** The branch from the root to `leafId`, which the caller must not change. */
274
305
  branch(leafId, byId, links) {
275
306
  return this.viewOf(leafId, byId, links).path;
@@ -277,7 +308,7 @@ var SessionHistoryIndex = class {
277
308
  /** Extends the cached branch when `entry` was appended at its leaf; anything else drops it. */
278
309
  appended(entry, byId) {
279
310
  const view = this.view;
280
- if (view === void 0 || view.byId !== byId || view.leafId !== entry.parentId) {
311
+ if (view === void 0 || view.byId !== byId || view.leafId !== entry.parentId || entry.parentId !== null && !isEarlierSessionEntry(this.positions().get(entry.parentId), this.positions().get(entry.id))) {
281
312
  this.view = void 0;
282
313
  return;
283
314
  }
@@ -340,15 +371,18 @@ var SessionHistoryIndex = class {
340
371
  return this.scanOf(entries).name;
341
372
  }
342
373
  viewOf(leafId, byId, links) {
343
- if (this.view?.byId !== byId || this.view.leafId !== leafId || this.view.links !== links) this.view = {
344
- byId,
345
- links,
346
- leafId,
347
- path: getBranchPath(leafId, byId, links),
348
- mappings: void 0,
349
- continuations: void 0,
350
- snapshots: void 0
351
- };
374
+ if (this.view?.byId !== byId || this.view.leafId !== leafId || this.view.links !== links) {
375
+ const repeated = leafId === null ? void 0 : this.repeatedEntries();
376
+ this.view = {
377
+ byId,
378
+ links,
379
+ leafId,
380
+ path: repeated === void 0 ? getBranchPath(leafId, byId, links, this.positions()) : recordedSessionBranch(repeated, leafId),
381
+ mappings: void 0,
382
+ continuations: void 0,
383
+ snapshots: void 0
384
+ };
385
+ }
352
386
  return this.view;
353
387
  }
354
388
  scanOf(entries) {
@@ -428,7 +462,7 @@ function createBranchedSessionState(input) {
428
462
  pathWithoutLabels.push(copy);
429
463
  pathParentId = entry.id;
430
464
  }
431
- const newSessionId = createSessionId();
465
+ const newSessionId = input.id ?? createSessionId();
432
466
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
433
467
  const header = createSessionHeader(newSessionId, input.cwd, timestamp, input.parentSessionId, input.internal);
434
468
  const pathEntryIds = new Set(pathWithoutLabels.map((entry) => entry.id));
@@ -613,7 +647,7 @@ async function exportedWindow(source) {
613
647
  const window = await source.file.window();
614
648
  const held = [...window.state.filter(({ onBranch }) => onBranch), ...window.branch].sort((a, b) => a.seq - b.seq);
615
649
  const archived = /* @__PURE__ */ new Map();
616
- const path = await includeNamedForkOutputs(forkContextPath(held.map(({ entry }) => entry), id), history, id, window.leafId, window.epoch, window.lastSeq, "session", archived);
650
+ const path = await includeNamedForkOutputs(forkContextPath(held.map(({ entry }) => entry), id), history, id, window.leafId, window.epoch, window.lastSeq, "session", archived, window.damagedHistoryLinks ? window.branch.at(-1)?.seq : void 0);
617
651
  const entries = [];
618
652
  const outputs = /* @__PURE__ */ new Map();
619
653
  const inWindow = (receipt) => async () => receipt;
@@ -638,7 +672,7 @@ function exportedSessionStream(source, outputs, finish) {
638
672
  const { history, id, file } = source;
639
673
  return {
640
674
  kind: "complete-session",
641
- async *read() {
675
+ async *read(_reader, hasWritten) {
642
676
  const { forkSeedFields } = await import("./storage/session/chunked-resume-projection.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
643
677
  for await (const { items } of historyPages(history, id, file.epoch, file.lastSeq, { pageEntries: SESSION_HISTORY_SCAN_ENTRIES })) for (const item of items) {
644
678
  let row = "entry" in item ? { entry: item.entry } : file.legacy ? { entry: await readExportedEntry(source, item.seq) } : {
@@ -653,6 +687,14 @@ function exportedSessionStream(source, outputs, finish) {
653
687
  row = { entry: taken.entry };
654
688
  }
655
689
  }
690
+ const { parentId } = row.entry;
691
+ if (parentId !== null && parentId !== row.entry.id && isDetachedReceipt(row.entry) && !await hasWritten(parentId)) {
692
+ const parent = await file.findEntrySeq(parentId);
693
+ if (parent !== void 0 && parent > item.seq) row = {
694
+ ...row,
695
+ parentRecordedLater: true
696
+ };
697
+ }
656
698
  yield row;
657
699
  }
658
700
  await finish();
@@ -731,7 +773,10 @@ var SessionManager = class SessionManager {
731
773
  /** Whether a retained row at this leaf differs between the transcript and model projections. */
732
774
  projectedEdits;
733
775
  leafId = null;
734
- historyIndex = new SessionHistoryIndex();
776
+ historyIndex = this.newHistoryIndex();
777
+ warnedHistoryLinksFor;
778
+ importRepairs = [];
779
+ historyRepairListener;
735
780
  historyStartSeq = 1;
736
781
  answerWindowStart = 1;
737
782
  branchSettingsVouchedFrom = {
@@ -799,6 +844,16 @@ var SessionManager = class SessionManager {
799
844
  restore(snapshot, location) {
800
845
  this.restoreHistory(snapshot.header, snapshot.entries, snapshot.lastSeq, location);
801
846
  this.historyEpoch = snapshot.epoch;
847
+ if (hasDamagedHistoryLinks(snapshot.entries)) this.warnHistoryLinks();
848
+ }
849
+ warnHistoryLinks() {
850
+ if (this.warnedHistoryLinksFor === this.sessionId) return;
851
+ this.warnedHistoryLinksFor = this.sessionId;
852
+ warnDamagedHistoryLinks(this.sessionId);
853
+ }
854
+ /** A warning observed while opening the recorded history, available to SDK and RPC clients. */
855
+ getHistoryWarning() {
856
+ return this.warnedHistoryLinksFor === this.sessionId ? damagedHistoryWarning(this.sessionId) : void 0;
802
857
  }
803
858
  restoreOpened(opened, location) {
804
859
  if ("snapshot" in opened) {
@@ -832,12 +887,14 @@ var SessionManager = class SessionManager {
832
887
  const path = [...state.filter((e) => e.onBranch), ...resume.branch].sort((a, b) => a.seq - b.seq);
833
888
  this.branchLinks = new Map(path.slice(1).map((held, i) => [held.entry.id, path[i].entry.id]));
834
889
  this.leafId = resume.leafId;
890
+ if (!this.hasFullHistory() && this.byId.size < held.length) this.historyIndex.restoreBranch(this.leafId, this.byId, this.branchLinks, path.map(({ entry }) => entry));
835
891
  const tailFrom = this.hasFullHistory() ? 1 : resume.branch[0]?.seq ?? resume.lastSeq + 1;
836
892
  this.branchSettingsVouchedFrom = {
837
893
  model: vouchedFromForResumeAxis("model_change", resume.retainedSettings?.model, path, resume.leafId, this.hasFullHistory(), resume.lastSeq, tailFrom),
838
894
  thinkingLevel: vouchedFromForResumeAxis("thinking_level_change", resume.retainedSettings?.thinkingLevel, path, resume.leafId, this.hasFullHistory(), resume.lastSeq, tailFrom)
839
895
  };
840
896
  Object.assign(this.byId, { preferFullIds: !this.hasFullHistory() });
897
+ if (resume.damagedHistoryLinks) this.warnHistoryLinks();
841
898
  }
842
899
  restoreHistory(header, entries, lastSeq, location, partial) {
843
900
  this.childArchive = new ChildCatalog();
@@ -845,6 +902,10 @@ var SessionManager = class SessionManager {
845
902
  type: "session",
846
903
  ...header
847
904
  }, ...entries];
905
+ if (this.sessionId !== header.id) {
906
+ this.warnedHistoryLinksFor = void 0;
907
+ this.importRepairs = [];
908
+ }
848
909
  this.sessionId = header.id;
849
910
  this.lastSeq = lastSeq;
850
911
  this.deletedFromStore = false;
@@ -1265,6 +1326,8 @@ var SessionManager = class SessionManager {
1265
1326
  }
1266
1327
  async initialize() {
1267
1328
  const created = await (this.store instanceof JsonlSessionStore ? this.store.create(this.recordHeader(), this.getEntries(), this.sessionFile) : this.store.create(this.recordHeader(), this.getEntries()));
1329
+ if (created.entries !== void 0) this.restoreHistory(this.recordHeader(), created.entries, created.lastSeq, this.sessionFile);
1330
+ if (created.repaired?.length) this.importRepairs = created.repaired;
1268
1331
  this.lastSeq = created.lastSeq;
1269
1332
  this.historyEpoch = created.epoch;
1270
1333
  this.entrySeqs = new Map(this.getEntries().map((entry, i) => [entry.id, i + 1]));
@@ -1300,8 +1363,11 @@ var SessionManager = class SessionManager {
1300
1363
  return this.sessionFile;
1301
1364
  });
1302
1365
  }
1366
+ newHistoryIndex() {
1367
+ return new SessionHistoryIndex(() => this.entrySeqs, () => this.hasFullHistory() && this.byId.size < this.fileEntries.length - 1 ? this.getEntries() : void 0);
1368
+ }
1303
1369
  _buildIndex() {
1304
- this.historyIndex = new SessionHistoryIndex();
1370
+ this.historyIndex = this.newHistoryIndex();
1305
1371
  validateSessionFileEntries(this.fileEntries, this.sessionFile ?? "in-memory session");
1306
1372
  const index = buildSessionIndex(this.fileEntries);
1307
1373
  this.byId = index.byId;
@@ -1405,7 +1471,8 @@ var SessionManager = class SessionManager {
1405
1471
  return this.runMutation(async () => {
1406
1472
  if (store === this.store) return;
1407
1473
  const header = this.recordHeader();
1408
- const entries = await this.compatibilityCopyEntries();
1474
+ const prepared = repairSessionParentWrites(header.id, await this.compatibilityCopyEntries());
1475
+ const entries = prepared.entries;
1409
1476
  const hashes = sessionBlobHashes(this.store, entries);
1410
1477
  assertSessionBlobStore(store, this.sessionId, hashes.length);
1411
1478
  const result = await store.create(header, entries);
@@ -1417,6 +1484,7 @@ var SessionManager = class SessionManager {
1417
1484
  this.store = store;
1418
1485
  this.sessionDir = store instanceof JsonlSessionStore ? store.descriptor.location : "";
1419
1486
  this.restoreOpened(opened);
1487
+ if (prepared.repaired.length > 0) this.importRepairs = [...this.importRepairs, ...prepared.repaired];
1420
1488
  });
1421
1489
  }
1422
1490
  async openSessionById(sessionId, cwdOverride, sessionDirectory, options) {
@@ -1449,15 +1517,41 @@ var SessionManager = class SessionManager {
1449
1517
  if (location !== void 0) manager.sessionDir = dirname(location);
1450
1518
  return manager;
1451
1519
  }
1452
- async importFromJsonl(inputPath, cwdOverride) {
1520
+ /** History links repaired when this manager imported its session; empty for ordinary opens. */
1521
+ getImportRepairs() {
1522
+ return this.importRepairs;
1523
+ }
1524
+ async importFromJsonl(inputPath, cwdOverride, beforeWrite) {
1453
1525
  const source = await JsonlSessionStore.open(dirname(resolvePath(inputPath)), {
1454
1526
  exactDirectory: true,
1455
1527
  scanExisting: false
1456
1528
  });
1457
1529
  try {
1458
- const loaded = await source.loadFile(inputPath);
1459
- const { entries, blobs } = takeInlineToolOutput(loaded.entries, loaded.header.id);
1530
+ const loaded = await source.loadFile(inputPath, { persistUpgrade: false });
1531
+ await beforeWrite?.(loaded.header.id);
1532
+ const prepared = prepareImportedSessionParents(loaded.header.id, loaded.entries);
1533
+ const { entries, blobs } = takeInlineToolOutput(prepared.entries, loaded.header.id);
1460
1534
  assertSessionBlobStore(this.store, loaded.header.id, blobs.length);
1535
+ if (await this.store.readHeader(loaded.header.id) !== void 0) {
1536
+ const plan = await planSessionImport(this.store, [{
1537
+ file: inputPath,
1538
+ header: loaded.header,
1539
+ original: loaded.entries,
1540
+ entries,
1541
+ blobs,
1542
+ repaired: prepared.repaired
1543
+ }]).catch((error) => {
1544
+ if (isStorageTransferError(error)) throw new SessionExistsError(loaded.header.id);
1545
+ throw error;
1546
+ });
1547
+ if (plan.sessions[0]?.action !== "repair") throw new SessionExistsError(loaded.header.id);
1548
+ const { repaired } = await applySessionImport(plan);
1549
+ const opened = await readStoredSession(this.store, loaded.header.id, void 0);
1550
+ const manager = new SessionManager(this.store, cwdOverride ?? opened.resume.header.cwd, this.sessionDir);
1551
+ manager.restoreOpened(opened);
1552
+ manager.importRepairs = repaired ?? [];
1553
+ return manager;
1554
+ }
1461
1555
  const snapshot = {
1462
1556
  ...loaded,
1463
1557
  entries: await adoptInlineSnapshotBlobs(entries, this.store.snapshotBlobs)
@@ -1468,19 +1562,32 @@ var SessionManager = class SessionManager {
1468
1562
  await storeSessionBlobs(this.store, snapshot.header.id, blobs);
1469
1563
  manager.restoreOpened(await readStoredSession(this.store, snapshot.header.id, void 0), manager.sessionFile);
1470
1564
  manager.startedSessionId = void 0;
1565
+ manager.importRepairs = prepared.repaired;
1471
1566
  return manager;
1472
1567
  } finally {
1473
1568
  await source.close();
1474
1569
  }
1475
1570
  }
1476
- _appendEntry(entry, target) {
1477
- return this._appendEntries([entry], target);
1571
+ /** @internal Reports committed repairs to the owning SDK session. */
1572
+ bindHistoryRepairs(listener) {
1573
+ this.historyRepairListener = listener;
1574
+ }
1575
+ async _appendEntry(entry, target) {
1576
+ return (await this._appendEntries([entry], target))[0];
1478
1577
  }
1479
1578
  async _appendEntries(entries, target) {
1480
1579
  if (this.appendHalt !== void 0) throw this.appendHalt;
1481
1580
  if (this.deletedFromStore) {
1482
1581
  if (target) this.restoreOpened({ resume: target }, this.sessionFile);
1483
- return this.applyAppended(entries);
1582
+ const previous = this.lastEntryId === null ? void 0 : this.entrySeqs.get(this.lastEntryId);
1583
+ const prepared = repairAppendedSessionParents(this.sessionId, entries, {
1584
+ lastSeq: previous ?? this.lastSeq,
1585
+ lastEntryId: this.lastEntryId,
1586
+ seqOf: (id) => this.entrySeqs.get(id)
1587
+ });
1588
+ this.applyAppended(prepared.entries, previous ?? this.lastSeq);
1589
+ if (prepared.repaired.length > 0) this.historyRepairListener?.(prepared.repaired);
1590
+ return prepared.entries;
1484
1591
  }
1485
1592
  const recovery = this.store.descriptor.adapter === "postgres" ? new SessionAppendRecovery(this.liveAppendRecovery) : void 0;
1486
1593
  this.pendingAppendRecovery = recovery;
@@ -1489,8 +1596,9 @@ var SessionManager = class SessionManager {
1489
1596
  try {
1490
1597
  for (;;) {
1491
1598
  const expectSeq = this.lastSeq;
1599
+ let written;
1492
1600
  try {
1493
- const written = await this.store.append(this.sessionId, entries, {
1601
+ written = await this.store.append(this.sessionId, entries, {
1494
1602
  expectSeq,
1495
1603
  ...this.archiveOnlyEpoch || this.historyEpoch === void 0 ? {} : { epoch: this.historyEpoch }
1496
1604
  });
@@ -1511,25 +1619,28 @@ var SessionManager = class SessionManager {
1511
1619
  const unknown = retryable?.outcome === "unknown" || isStorageTransientError(error) && error.outcome === "unknown";
1512
1620
  if (await this.reconcileAppend(entries, error, unknown, expectSeq, target, recovery)) {
1513
1621
  saved = true;
1514
- return;
1622
+ return entries;
1515
1623
  }
1516
1624
  if (recovery && retryable && !await recovery.wait(retryable)) throw error;
1517
1625
  continue;
1518
1626
  }
1519
- this.applyAppended(entries);
1627
+ const actual = written.entries ?? entries;
1628
+ this.applyAppended(actual);
1520
1629
  saved = true;
1521
- return;
1630
+ if (written.repaired?.length) this.historyRepairListener?.(written.repaired);
1631
+ return actual;
1522
1632
  }
1523
1633
  } finally {
1524
1634
  this.pendingAppendRecovery = void 0;
1525
1635
  recovery?.finish(saved);
1526
1636
  }
1527
1637
  }
1528
- applyAppended(entries) {
1638
+ applyAppended(entries, after = this.lastSeq - entries.length) {
1529
1639
  for (const [position, entry] of entries.entries()) {
1530
- this.entrySeqs.set(entry.id, this.lastSeq - entries.length + position + 1);
1531
- updateWorkflowStarts(this.workflowStarts, entry, this.lastSeq - entries.length + position + 1);
1532
- this.childArchive.noteResident(entry, this.lastSeq - entries.length + position + 1);
1640
+ const seq = after + position + 1;
1641
+ this.entrySeqs.set(entry.id, seq);
1642
+ updateWorkflowStarts(this.workflowStarts, entry, seq);
1643
+ this.childArchive.noteResident(entry, seq);
1533
1644
  this.lastEntryId = entry.id;
1534
1645
  this.fileEntries.push(entry);
1535
1646
  this.byId.set(entry.id, entry);
@@ -1719,11 +1830,11 @@ var SessionManager = class SessionManager {
1719
1830
  const companion = this.messageCompanions.get(message);
1720
1831
  this.messageCompanions.delete(message);
1721
1832
  const custom = companion?.();
1722
- await this._appendEntries(custom === void 0 ? [entry] : [entry, createCustomEntry(custom.customType, custom.data, {
1833
+ const [actual] = await this._appendEntries(custom === void 0 ? [entry] : [entry, createCustomEntry(custom.customType, custom.data, {
1723
1834
  has: (id) => id === entry.id || this.byId.has(id),
1724
1835
  preferFullIds: !this.hasFullHistory()
1725
1836
  }, entry.id)]);
1726
- return entry.id;
1837
+ return actual.id;
1727
1838
  });
1728
1839
  }
1729
1840
  /**
@@ -1738,8 +1849,7 @@ var SessionManager = class SessionManager {
1738
1849
  appendThinkingLevelChange(thinkingLevel) {
1739
1850
  return this.runMutation(async () => {
1740
1851
  const entry = createThinkingLevelChangeEntry(thinkingLevel, this.byId, this.leafId);
1741
- await this._appendEntry(entry);
1742
- return entry.id;
1852
+ return (await this._appendEntry(entry)).id;
1743
1853
  });
1744
1854
  }
1745
1855
  /** Record auxiliary model usage without adding it to the LLM context. */
@@ -1756,8 +1866,7 @@ var SessionManager = class SessionManager {
1756
1866
  usage,
1757
1867
  ...note === void 0 ? {} : { note }
1758
1868
  };
1759
- await this._appendEntry(entry);
1760
- return entry;
1869
+ return this._appendEntry(entry);
1761
1870
  });
1762
1871
  }
1763
1872
  /**
@@ -1767,8 +1876,7 @@ var SessionManager = class SessionManager {
1767
1876
  appendModelChange(provider, modelId, fallback) {
1768
1877
  return this.runMutation(async () => {
1769
1878
  const entry = createModelChangeEntry(provider, modelId, this.byId, this.leafId, fallback);
1770
- await this._appendEntry(entry);
1771
- return entry.id;
1879
+ return (await this._appendEntry(entry)).id;
1772
1880
  });
1773
1881
  }
1774
1882
  /**
@@ -1799,8 +1907,7 @@ var SessionManager = class SessionManager {
1799
1907
  };
1800
1908
  const expanded = await this.expandForBoundary([firstKeptEntryId, coveredThroughEntryId]);
1801
1909
  if (expanded) precondition?.();
1802
- await this._appendEntry(entry, expanded);
1803
- return entry.id;
1910
+ return (await this._appendEntry(entry, expanded)).id;
1804
1911
  });
1805
1912
  }
1806
1913
  /** A boundary may name an ancestor before the previous window. Stage that exact branch span before
@@ -1847,7 +1954,7 @@ var SessionManager = class SessionManager {
1847
1954
  const kept = new Set(branch.map(({ entry }) => entry.id));
1848
1955
  const first = branch[0];
1849
1956
  const edits = new Map(branch.flatMap(({ seq, entry }) => entry.type === "context_edit" ? [[entry.targetId, seq]] : []));
1850
- const priorAnswer = first.entry.parentId ? await archivedAnswerAt(this.store, this.sessionId, this.historyEpoch, this.lastSeq, first.seq, first.entry.parentId, edits) : void 0;
1957
+ const priorAnswer = first.entry.parentId ? await archivedAnswerAt(this.store, this.sessionId, this.historyEpoch, this.lastSeq, first.seq, first.entry.parentId, edits, void 0, this.getHistoryWarning() !== void 0) : void 0;
1851
1958
  return {
1852
1959
  header: this.recordHeader(),
1853
1960
  epoch: this.historyEpoch,
@@ -1927,10 +2034,10 @@ var SessionManager = class SessionManager {
1927
2034
  }] } : replacement;
1928
2035
  const entry = createContextEditEntry(targetId, normalizedReplacement, this.byId, this.leafId);
1929
2036
  const first = targetRole === "assistant" && seq < this.answerWindowStart ? branch.find((item) => this.entrySeqs.get(item.id) === this.answerWindowStart) : void 0;
1930
- const before = first ? await archivedAnswerAt(this.store, this.sessionId, this.historyEpoch, this.lastSeq, this.answerWindowStart, first.parentId, new Map(branch.flatMap((item) => item.type === "context_edit" ? [[item.targetId, this.entrySeqs.get(item.id)]] : [])), entry) : void 0;
1931
- await this._appendEntry(entry);
2037
+ const before = first ? await archivedAnswerAt(this.store, this.sessionId, this.historyEpoch, this.lastSeq, this.answerWindowStart, first.parentId, new Map(branch.flatMap((item) => item.type === "context_edit" ? [[item.targetId, this.entrySeqs.get(item.id)]] : [])), entry, this.getHistoryWarning() !== void 0) : void 0;
2038
+ const actual = await this._appendEntry(entry);
1932
2039
  if (first) this.priorAnswer = before;
1933
- return entry.id;
2040
+ return actual.id;
1934
2041
  });
1935
2042
  }
1936
2043
  static {
@@ -1944,8 +2051,7 @@ var SessionManager = class SessionManager {
1944
2051
  }
1945
2052
  async appendCustomEntryAtLeaf(customType, data) {
1946
2053
  const entry = createCustomEntry(customType, data, this.byId, this.leafId);
1947
- await this._appendEntry(entry);
1948
- return entry.id;
2054
+ return (await this._appendEntry(entry)).id;
1949
2055
  }
1950
2056
  /** Append a custom entry (for extensions) as child of current leaf, then advance leaf. Returns entry id. */
1951
2057
  appendCustomEntry(customType, data) {
@@ -1991,8 +2097,7 @@ var SessionManager = class SessionManager {
1991
2097
  if (restore === void 0 && restoreWarnings.length > 0) throw new WorkspaceConfigError("sdk", "restoreWarnings", "warnings recorded together with their restore");
1992
2098
  if (degradedFrom !== void 0 && (degradedFrom === snapshotId || !await this.hasWorktreeSnapshotRecord(degradedFrom))) throw new WorkspaceConfigError("sdk", "degradedFrom", "the id of another snapshot recorded in this session");
1993
2099
  const entry = createWorktreeSnapshotEntry(root, snapshotId, snapshot, restore, restoreWarnings, this.byId, this.leafId, unrestored, captureMs, degradedFrom, capturedAt);
1994
- await this._appendEntry(entry);
1995
- return entry.id;
2100
+ return (await this._appendEntry(entry)).id;
1996
2101
  });
1997
2102
  }
1998
2103
  /** Restores recorded on the active branch, oldest first: work recorded under `from` continues under `to`. */
@@ -2062,8 +2167,7 @@ var SessionManager = class SessionManager {
2062
2167
  appendSessionInfo(name) {
2063
2168
  return this.runMutation(async () => {
2064
2169
  const entry = createSessionInfoEntry(name, this.byId, this.leafId);
2065
- await this._appendEntry(entry);
2066
- return entry.id;
2170
+ return (await this._appendEntry(entry)).id;
2067
2171
  });
2068
2172
  }
2069
2173
  /** Append a generated resume summary anchored to the message it describes. Returns entry id. */
@@ -2071,8 +2175,7 @@ var SessionManager = class SessionManager {
2071
2175
  return this.runMutation(async () => {
2072
2176
  await this.requireEntryExists(summarizedThroughId);
2073
2177
  const entry = createSessionSummaryEntry(summary, summarizedThroughId, usage, this.byId, this.leafId);
2074
- await this._appendEntry(entry);
2075
- return entry.id;
2178
+ return (await this._appendEntry(entry)).id;
2076
2179
  });
2077
2180
  }
2078
2181
  /** Get the current session name from the latest session_info entry, if any. */
@@ -2091,8 +2194,7 @@ var SessionManager = class SessionManager {
2091
2194
  appendCustomMessageEntry(customType, content, display, details, excludeFromContext, protectedReconciliation, stageAdmissionKey) {
2092
2195
  return this.runMutation(async () => {
2093
2196
  const entry = createCustomMessageEntry(customType, content, display, details, excludeFromContext, protectedReconciliation, this.byId, this.leafId, stageAdmissionKey);
2094
- await this._appendEntry(entry);
2095
- return entry.id;
2197
+ return (await this._appendEntry(entry)).id;
2096
2198
  });
2097
2199
  }
2098
2200
  async readEntry(id) {
@@ -2121,6 +2223,27 @@ var SessionManager = class SessionManager {
2121
2223
  if (entry === void 0) throw new SessionEntryError(id, "missing");
2122
2224
  return entry;
2123
2225
  }
2226
+ /** @internal The effective parent for a "before this entry" navigation or fork, even off the held branch. */
2227
+ async readParentId(entry) {
2228
+ const { parentId } = entry;
2229
+ if (parentId == null) return null;
2230
+ if (this.hasFullHistory()) return this.getBranch(entry.id).at(-2)?.id ?? null;
2231
+ const [parent, child] = await Promise.all([this.findEntrySeq(parentId), this.findEntrySeq(entry.id)]);
2232
+ if (child === void 0 || child <= 1) return null;
2233
+ if (parentId !== entry.id && isEarlierSessionEntry(parent, child)) return parentId;
2234
+ const { store, sessionId, historyEpoch: epoch } = this;
2235
+ const cut = {
2236
+ leaf: child,
2237
+ first: 1,
2238
+ last: child - 1,
2239
+ backward: true,
2240
+ pivot: child,
2241
+ epoch
2242
+ };
2243
+ const span = store.readBranchSpan ? await store.readBranchSpan(sessionId, cut) : await (await import("./storage/session/snapshot-history.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"))).snapshotBranchSpan(store, sessionId, cut);
2244
+ if (span === void 0) return null;
2245
+ return (await readSessionRange(store, sessionId, span.end, span.end, epoch)).entries[0]?.id ?? null;
2246
+ }
2124
2247
  getLeafId() {
2125
2248
  return this.leafId;
2126
2249
  }
@@ -2133,7 +2256,15 @@ var SessionManager = class SessionManager {
2133
2256
  /** Get all direct children of an entry. Like `getTree()`, omits recorded leaf moves. */
2134
2257
  getChildren(parentId) {
2135
2258
  const children = [];
2136
- for (const entry of this.byId.values()) if (entry.parentId === parentId && !isLeafMoveEntry(entry)) children.push(entry);
2259
+ const parentSeq = this.entrySeqs.get(parentId);
2260
+ if (parentSeq === void 0) return children;
2261
+ const damaged = this.getHistoryWarning() !== void 0;
2262
+ if (this.hasFullHistory() && damaged) {
2263
+ const entries = this.getEntries();
2264
+ const { parents } = recordedSessionParents(entries);
2265
+ return entries.filter((entry, i) => parents[i] === parentSeq && !isLeafMoveEntry(entry));
2266
+ }
2267
+ for (const entry of this.byId.values()) if ((entry.parentId === parentId || damaged && this.branchLinks?.get(entry.id) === parentId) && isEarlierSessionEntry(parentSeq, this.entrySeqs.get(entry.id)) && !isLeafMoveEntry(entry)) children.push(entry);
2137
2268
  return children;
2138
2269
  }
2139
2270
  /** Get the label for an entry, if any. */
@@ -2147,8 +2278,7 @@ var SessionManager = class SessionManager {
2147
2278
  appendLabelChange(targetId, label) {
2148
2279
  return this.runMutation(async () => {
2149
2280
  await this.requireEntryExists(targetId);
2150
- const entry = createLabelEntry(targetId, label, this.byId, this.leafId);
2151
- await this._appendEntry(entry);
2281
+ const entry = await this._appendEntry(createLabelEntry(targetId, label, this.byId, this.leafId));
2152
2282
  if (label) {
2153
2283
  this.labelsById.set(targetId, label);
2154
2284
  this.labelTimestampsById.set(targetId, entry.timestamp);
@@ -2162,7 +2292,8 @@ var SessionManager = class SessionManager {
2162
2292
  /** Walk from entry to root, returning all entries in path order. */
2163
2293
  getBranch(fromId) {
2164
2294
  const leafId = fromId ?? this.leafId;
2165
- return leafId === this.leafId ? this.historyIndex.branch(leafId, this.byId, this.branchLinks).slice() : getBranchPath(leafId, this.byId, this.branchLinks);
2295
+ if (leafId === this.leafId) return this.historyIndex.branch(leafId, this.byId, this.branchLinks).slice();
2296
+ return leafId !== null && this.hasFullHistory() && this.byId.size < this.fileEntries.length - 1 ? recordedSessionBranch(this.getEntries(), leafId) : getBranchPath(leafId, this.byId, this.branchLinks, this.entrySeqs);
2166
2297
  }
2167
2298
  /** Return the active branch entries after applying the latest compaction boundary. */
2168
2299
  buildContextEntries() {
@@ -2406,8 +2537,7 @@ var SessionManager = class SessionManager {
2406
2537
  const previous = fromId ?? this.leafId ?? "root";
2407
2538
  const target = branchFromId === null ? void 0 : await this.prepareBranchTarget(branchFromId);
2408
2539
  const entry = createBranchSummaryEntry(branchFromId, previous, summary, details, usage, fromHook, this.byId);
2409
- await this._appendEntry(entry, target);
2410
- return entry.id;
2540
+ return (await this._appendEntry(entry, target)).id;
2411
2541
  });
2412
2542
  }
2413
2543
  /**
@@ -2418,20 +2548,23 @@ var SessionManager = class SessionManager {
2418
2548
  */
2419
2549
  createBranchedSession(leafId, options) {
2420
2550
  return this.runMutation(async () => {
2551
+ const id = options?.id ?? createSessionId();
2552
+ assertValidSessionId(id);
2421
2553
  if (options?.history !== void 0 && options.history !== "tail") throw new TypeError("createBranchedSession() accepts only history: \"tail\"; leave the option out to copy the whole branch.");
2422
2554
  if (options?.history === "tail") {
2423
2555
  const receipts = /* @__PURE__ */ new Map();
2424
- return this.installFork(leafId, await this.forkWindow(await this.contextBranch(leafId), leafId, "branch", receipts), receipts);
2556
+ return this.installFork(leafId, await this.forkWindow(await this.contextBranch(leafId), leafId, "branch", receipts), receipts, true, void 0, void 0, id);
2425
2557
  }
2426
2558
  if (!this.store.readEntrySizes || !this.store.readRange || !this.store.readEntryChunk || !this.store.readBranchSpan) {
2427
- const index = buildSessionIndex(await this.legacyForkEntries());
2428
- return this.installFork(leafId, getBranchPath(leafId, index.byId), /* @__PURE__ */ new Map(), false, index);
2559
+ const entries = await this.legacyForkEntries();
2560
+ const index = buildSessionIndex(entries);
2561
+ return this.installFork(leafId, recordedSessionBranch(entries, leafId), /* @__PURE__ */ new Map(), false, index, void 0, id);
2429
2562
  }
2430
2563
  const leaf = await this.findEntrySeq(leafId);
2431
2564
  if (leaf === void 0) throw new SessionEntryError(leafId, "missing");
2432
2565
  const { humanForkStream } = await import("./storage/session/branch-fork-source.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
2433
2566
  const seed = humanForkStream(this.sessionId, this.historyEpoch, this.lastSeq, leaf, leafId, this.labelsById, this.labelTimestampsById);
2434
- const record = this.recordHeader(createSessionHeader(createSessionId(), this.cwd, (/* @__PURE__ */ new Date()).toISOString(), this.sessionId));
2567
+ const record = this.recordHeader(createSessionHeader(id, this.cwd, (/* @__PURE__ */ new Date()).toISOString(), this.sessionId));
2435
2568
  const store = await this.storeForNewSession();
2436
2569
  const location = store instanceof JsonlSessionStore ? this.sessionDir ? createSessionFilePath(this.sessionDir, record.createdAt, record.id) : store.locationFor(record) : void 0;
2437
2570
  await createForkArchive(store, record, seed, {
@@ -2448,11 +2581,12 @@ var SessionManager = class SessionManager {
2448
2581
  return this.sessionFile;
2449
2582
  });
2450
2583
  }
2451
- async installFork(leafId, path, receipts = /* @__PURE__ */ new Map(), preserveReceiptLinks = true, labels, internal) {
2584
+ async installFork(leafId, path, receipts = /* @__PURE__ */ new Map(), preserveReceiptLinks = true, labels, internal, id) {
2452
2585
  const result = createBranchedSessionState({
2453
2586
  leafId,
2454
2587
  cwd: this.cwd,
2455
2588
  parentSessionId: this.sessionId,
2589
+ id,
2456
2590
  path,
2457
2591
  preserveReceiptLinks,
2458
2592
  labelsById: labels?.labelsById ?? this.labelsById,
@@ -2478,12 +2612,14 @@ var SessionManager = class SessionManager {
2478
2612
  const { windowFromSnapshot } = await import("./storage/session/snapshot-history.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
2479
2613
  const snapshot = {
2480
2614
  header: record,
2481
- entries,
2615
+ entries: created.entries ?? entries,
2482
2616
  lastSeq: created.lastSeq,
2483
2617
  epoch: created.epoch
2484
2618
  };
2485
2619
  this.restoreOpened({ resume: windowFromSnapshot(snapshot, void 0, void 0, void 0, isProxy) }, location);
2486
2620
  } else this.restoreOpened(await readStoredSession(store, record.id, void 0), location);
2621
+ this.importRepairs = created.repaired ?? [];
2622
+ if (this.importRepairs.length > 0) this.historyRepairListener?.(this.importRepairs);
2487
2623
  this.markSessionStarted();
2488
2624
  return this.sessionFile;
2489
2625
  }
@@ -2532,13 +2668,14 @@ var SessionManager = class SessionManager {
2532
2668
  source.labelsById = labels.labelsById;
2533
2669
  source.labelTimestampsById = labels.labelTimestampsById;
2534
2670
  const receipts = /* @__PURE__ */ new Map();
2535
- const entries = bounded ? await includeNamedForkOutputs(forkContextPath(window.entries, sessionId, (await import("./storage/session/fork-window.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"))).forkDisplayEvidence(window.entries)), store, sessionId, leafId, window.epoch, watermark ?? window.lastSeq, "branch", receipts) : window.entries;
2671
+ const entries = bounded ? await includeNamedForkOutputs(forkContextPath(window.entries, sessionId, (await import("./storage/session/fork-window.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"))).forkDisplayEvidence(window.entries)), store, sessionId, leafId, window.epoch, watermark ?? window.lastSeq, "branch", receipts, window.damagedHistoryLinks ? await store.findEntrySeq?.(sessionId, leafId) : void 0) : window.entries;
2536
2672
  await source.installFork(leafId, entries, receipts, !!bounded, void 0, internal);
2537
2673
  return source;
2538
2674
  };
2539
2675
  }
2540
- forkWindow(path, leafId, scope = "branch", receipts) {
2541
- return includeNamedForkOutputs(forkContextPath(path, this.sessionId), this.store, this.sessionId, leafId, this.historyEpoch, this.lastSeq, scope, receipts);
2676
+ async forkWindow(path, leafId, scope = "branch", receipts) {
2677
+ const leafSeq = this.getHistoryWarning() !== void 0 && leafId !== null ? await this.findEntrySeq(leafId) : void 0;
2678
+ return includeNamedForkOutputs(forkContextPath(path, this.sessionId), this.store, this.sessionId, leafId, this.historyEpoch, this.lastSeq, scope, receipts, leafSeq);
2542
2679
  }
2543
2680
  /** Resolve the selected stored branch even when an earlier clear has retired its first kept span. */
2544
2681
  async contextBranch(leafId) {
@@ -2586,7 +2723,7 @@ var SessionManager = class SessionManager {
2586
2723
  hashes,
2587
2724
  receipts
2588
2725
  }, manager.sessionFile);
2589
- if (captured && created.epoch !== void 0 && created.lastSeq === captured.length && store.readEntrySizes) {
2726
+ if (captured && !created.repaired?.length && created.epoch !== void 0 && created.lastSeq === captured.length && store.readEntrySizes) {
2590
2727
  const head = await store.readEntrySizes(manager.sessionId, 1, 0);
2591
2728
  if (head.epoch !== created.epoch) throw new SessionConflictError(manager.sessionId, created.lastSeq, head.lastSeq);
2592
2729
  if (head.lastSeq === created.lastSeq) {
@@ -2609,16 +2746,17 @@ var SessionManager = class SessionManager {
2609
2746
  }) : created.epoch;
2610
2747
  if (stamp !== void 0 && opened.resume.epoch !== stamp) throw new SessionConflictError(manager.sessionId, created.lastSeq, opened.resume.lastSeq);
2611
2748
  manager.restoreOpened(opened, manager.sessionFile);
2749
+ manager.importRepairs = created.repaired ?? [];
2612
2750
  manager.markSessionStarted();
2613
2751
  return manager;
2614
2752
  });
2615
2753
  }
2616
- static async importFromJsonl(inputPath, cwd, sessionDir) {
2754
+ static async importFromJsonl(inputPath, cwd, sessionDir, beforeWrite) {
2617
2755
  const store = typeof sessionDir === "string" ? await JsonlSessionStore.open(sessionDir, {
2618
2756
  exactDirectory: true,
2619
2757
  scanExisting: false
2620
2758
  }) : sessionDir ?? await resolveSessionStore(cwd);
2621
- return SessionManager.constructWithStore(store, store !== sessionDir, () => new SessionManager(store, cwd, store instanceof JsonlSessionStore ? store.descriptor.location : "").importFromJsonl(inputPath));
2759
+ return SessionManager.constructWithStore(store, store !== sessionDir, () => new SessionManager(store, cwd, store instanceof JsonlSessionStore ? store.descriptor.location : "").importFromJsonl(inputPath, void 0, beforeWrite));
2622
2760
  }
2623
2761
  static async constructWithStore(store, owned, construct) {
2624
2762
  try {
@@ -2695,13 +2833,12 @@ var SessionManager = class SessionManager {
2695
2833
  async inMemoryBranch(cwd) {
2696
2834
  const header = this.getHeader();
2697
2835
  if (!header) throw new Error("Session header is missing");
2698
- const links = this.branchLinks;
2699
- const path = this.getBranch().map((entry) => {
2700
- const parent = links?.get(entry.id);
2701
- return parent && !this.byId.has(entry.parentId ?? "") ? {
2836
+ const path = this.getBranch().map((entry, index, branch) => {
2837
+ const parentId = branch[index - 1]?.id ?? (entry.parentId != null && isDetachedReceipt(entry) && !this.entrySeqs.has(entry.parentId) ? entry.parentId : null);
2838
+ return parentId === entry.parentId ? entry : {
2702
2839
  ...entry,
2703
- parentId: parent
2704
- } : entry;
2840
+ parentId
2841
+ };
2705
2842
  });
2706
2843
  return SessionManager.inMemory(cwd, void 0, [header, ...path]);
2707
2844
  }
@@ -2731,18 +2868,21 @@ var SessionManager = class SessionManager {
2731
2868
  const start = entries[0]?.type === "session" ? 1 : 0;
2732
2869
  const header = start ? validateSessionFileEntries([entries[0]], "in-memory session") : this.getHeader();
2733
2870
  const record = this.recordHeader(header);
2871
+ const input = entries.slice(start);
2872
+ validateSessionEntryStructure(input, "in-memory session");
2873
+ const prepared = repairSessionParentWrites(record.id, input);
2734
2874
  const created = await this.store.create(record, []);
2735
2875
  let seq = 0;
2736
- for (let i = start; i < entries.length; i += 64) {
2737
- if (i > start) await yieldToEventLoop();
2738
- const page = entries.slice(i, i + 64);
2739
- validateSessionEntryStructure(page, "in-memory session");
2876
+ for (let i = 0; i < prepared.entries.length; i += 64) {
2877
+ if (i > 0) await yieldToEventLoop();
2878
+ const page = prepared.entries.slice(i, i + 64);
2740
2879
  seq = (await this.store.append(record.id, page, {
2741
2880
  expectSeq: seq,
2742
2881
  epoch: created.epoch
2743
2882
  })).lastSeq;
2744
2883
  }
2745
2884
  this.restoreOpened(await readStoredSession(this.store, record.id, void 0));
2885
+ this.importRepairs = prepared.repaired;
2746
2886
  return this;
2747
2887
  }
2748
2888
  /**
@@ -2796,6 +2936,7 @@ var SessionManager = class SessionManager {
2796
2936
  const opened = await readStoredSession(store, manager.sessionId, void 0);
2797
2937
  if (created.epoch !== void 0 && opened.resume.epoch !== created.epoch) throw new SessionConflictError(manager.sessionId, created.lastSeq, opened.resume.lastSeq);
2798
2938
  manager.restoreOpened(opened, manager.sessionFile);
2939
+ manager.importRepairs = created.repaired ?? [];
2799
2940
  manager.markSessionStarted();
2800
2941
  return manager;
2801
2942
  };
@@ -2878,7 +3019,7 @@ function __atomicOnDemandFailed(error, feature) {
2878
3019
  return (async () => {
2879
3020
  const root = new URL("../", import.meta.url);
2880
3021
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
2881
- const key = `${root.href}#0.10.19`;
3022
+ const key = `${root.href}#0.10.20-alpha.2`;
2882
3023
  let release = releases.get(key);
2883
3024
  if (release === undefined) {
2884
3025
  const current = (async () => {
@@ -2906,7 +3047,7 @@ function __atomicOnDemandFailed(error, feature) {
2906
3047
  } catch {
2907
3048
  // No installation to read, as in a bundle of the package: the release the process runs decides.
2908
3049
  }
2909
- const updatedTo = typeof installed === "string" && installed !== "0.10.19" ? installed : running !== undefined && running.version !== "0.10.19" ? "0.10.19" : undefined;
3050
+ 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;
2910
3051
  if (updatedTo === undefined) throw error;
2911
3052
  const application = typeof running?.name === "string" ? running.name : "atomic";
2912
3053
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {