@bastani/atomic 0.10.11-alpha.2 → 0.10.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (447) hide show
  1. package/CHANGELOG.md +307 -0
  2. package/README.md +5 -8
  3. package/dist/_shared/dist-KOELCESV.js +2 -2
  4. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  5. package/dist/_shared/lib-4PES5P4V.js +2 -2
  6. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +6 -6
  7. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +5 -5
  8. package/dist/_shared/mode-shared-2QJSCUM6.js +6 -6
  9. package/dist/_shared/p0-cli-BB45ZQY6.js +46 -67
  10. package/dist/_shared/p0-cli-BB45ZQY6.js.map +1 -1
  11. package/dist/_shared/p1a-prewarm-XIU57JHF.js +7 -8
  12. package/dist/_shared/p1a-prewarm-XIU57JHF.js.map +1 -1
  13. package/dist/_shared/{p1b-elig-ENCUPKKJ.js → p1b-elig-TVB5CBLL.js} +36 -8
  14. package/dist/_shared/p1b-elig-TVB5CBLL.js.map +1 -0
  15. package/dist/_shared/p2-shell-main-B2WIALFD.js +6 -3
  16. package/dist/_shared/p2-shell-main-B2WIALFD.js.map +1 -1
  17. package/dist/_shared/runtime-O4KCSG4C.js +3 -3
  18. package/dist/_shared/{sdk-IQMULKFU.js → sdk-B5LEWGGI.js} +1218 -657
  19. package/dist/_shared/sdk-B5LEWGGI.js.map +1 -0
  20. package/dist/_shared/session-data-AHTU7IS6.js +2 -2
  21. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  22. package/dist/_shared/{startup-0-0-3IXNMFM2.js → startup-0-0-XJJDOIEC.js} +50 -48
  23. package/dist/_shared/startup-0-0-XJJDOIEC.js.map +1 -0
  24. package/dist/_shared/{startup-0-1-7T2IAE7J.js → startup-0-1-M6OWAYHH.js} +540 -136
  25. package/dist/_shared/startup-0-1-M6OWAYHH.js.map +1 -0
  26. package/dist/_shared/startup-0-2-5QHPCEON.js +47 -48
  27. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -1
  28. package/dist/_shared/startup-0-3-4ZYBYQNM.js +5 -5
  29. package/dist/_shared/startup-0-4-ZMJV547D.js +12 -7
  30. package/dist/_shared/startup-0-4-ZMJV547D.js.map +1 -1
  31. package/dist/_shared/startup-0-5-YDW47QX6.js +7 -7
  32. package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -1
  33. package/dist/_shared/startup-10-0-TDQNBDDL.js +6 -6
  34. package/dist/_shared/startup-12-0-55AAXBJZ.js +2 -2
  35. package/dist/_shared/startup-14-0-MLX36RBG.js +4 -5
  36. package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
  37. package/dist/_shared/startup-15-0-YUKGAC63.js +4 -4
  38. package/dist/_shared/startup-15-1-4S7FLMNG.js +19 -27
  39. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  40. package/dist/_shared/startup-8-0-34CBHPZH.js +2144 -249
  41. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  42. package/dist/_shared/{startup-8-1-X32CYSXB.js → startup-8-1-LZFXSD3Z.js} +98 -1184
  43. package/dist/_shared/startup-8-1-LZFXSD3Z.js.map +1 -0
  44. package/dist/_shared/storage-command-7MGXLJGZ.js +188 -37
  45. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  46. package/dist/_shared/storage-status-K7PX2RXA.js +557 -0
  47. package/dist/_shared/storage-status-K7PX2RXA.js.map +1 -0
  48. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  49. package/dist/_shared/team-DOQKICG2.js +376 -0
  50. package/dist/_shared/team-DOQKICG2.js.map +1 -0
  51. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  52. package/dist/builtin/intercom/CHANGELOG.md +88 -0
  53. package/dist/builtin/intercom/README.md +2 -2
  54. package/dist/builtin/intercom/broker/broker.bundle.mjs +1917 -381
  55. package/dist/builtin/intercom/broker/client.ts +8 -0
  56. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +324 -68
  57. package/dist/builtin/intercom/broker/multinode-router.ts +256 -39
  58. package/dist/builtin/intercom/broker/multinode-state-store.ts +71 -5
  59. package/dist/builtin/intercom/broker/open-broker-state.ts +14 -0
  60. package/dist/builtin/intercom/broker/send-order-gate.ts +5 -2
  61. package/dist/builtin/intercom/broker/sql-add-column.ts +50 -5
  62. package/dist/builtin/intercom/broker/sql-ended-child-queue-store.ts +3 -2
  63. package/dist/builtin/intercom/broker/sql-held-send-store.ts +2 -2
  64. package/dist/builtin/intercom/broker/sql-known-session-store.ts +43 -19
  65. package/dist/builtin/intercom/broker/sql-lease-store.ts +473 -121
  66. package/dist/builtin/intercom/broker/sql-outbox-store.ts +821 -79
  67. package/dist/builtin/intercom/broker/sql-pending-ask-store.ts +8 -5
  68. package/dist/builtin/intercom/broker/sql-released-ask-store.ts +12 -5
  69. package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +256 -8
  70. package/dist/builtin/intercom/broker/sql-retention.ts +150 -0
  71. package/dist/builtin/intercom/broker/sql-schema.ts +175 -24
  72. package/dist/builtin/intercom/broker/sql-sent-message-authority.ts +74 -19
  73. package/dist/builtin/intercom/broker/wake-up-bus.ts +6 -0
  74. package/dist/builtin/intercom/index.bundle.mjs +14 -4
  75. package/dist/builtin/intercom/package.json +1 -1
  76. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  77. package/dist/builtin/mcp/package.json +1 -1
  78. package/dist/builtin/subagents/CHANGELOG.md +20 -0
  79. package/dist/builtin/subagents/package.json +1 -1
  80. package/dist/builtin/subagents/skills/skill-creator/eval-viewer/generate_review.py +8 -1
  81. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  82. package/dist/builtin/web-access/index.bundle.mjs +2 -10
  83. package/dist/builtin/web-access/package.json +1 -1
  84. package/dist/bun/bundled-sqlite.js +41 -0
  85. package/dist/bun/bundled-sqlite.js.map +1 -0
  86. package/dist/cli/args.js +2 -2
  87. package/dist/cli/auth-cli.code.js +4 -4
  88. package/dist/cli/auth-cli.impl.js +3 -3
  89. package/dist/cli/auth-cli.js +3 -3
  90. package/dist/cli/blueprint-command.code.js +3 -3
  91. package/dist/cli/blueprint-command.impl.js +3 -3
  92. package/dist/cli/blueprint-command.js +3 -3
  93. package/dist/cli/intercom-command.code.js +3 -3
  94. package/dist/cli/intercom-command.code.js.map +1 -1
  95. package/dist/cli/intercom-command.impl.js +3 -3
  96. package/dist/cli/intercom-command.js +3 -3
  97. package/dist/cli/list-models.code.js +2 -2
  98. package/dist/cli/list-models.impl.js +3 -3
  99. package/dist/cli/list-models.js +3 -3
  100. package/dist/cli/session-picker.code.js +1 -1
  101. package/dist/cli/session-picker.impl.js +3 -3
  102. package/dist/cli/session-picker.js +3 -3
  103. package/dist/cli/startup-ui.code.js +1 -1
  104. package/dist/cli/startup-ui.impl.js +3 -3
  105. package/dist/cli/startup-ui.js +3 -3
  106. package/dist/cli/storage-command.impl.js +3 -3
  107. package/dist/cli/storage-command.js +3 -3
  108. package/dist/cli/storage-search-session.code.js +3 -3
  109. package/dist/cli/storage-search-session.impl.js +3 -3
  110. package/dist/cli/storage-search-session.js +3 -3
  111. package/dist/cli/team-command.code.js +19 -113
  112. package/dist/cli/team-command.code.js.map +1 -1
  113. package/dist/cli/team-command.impl.js +3 -3
  114. package/dist/cli/team-command.js +3 -3
  115. package/dist/cli.js +5 -18
  116. package/dist/cli.js.map +1 -1
  117. package/dist/core/agent-rehydrate-errors.d.ts +4 -9
  118. package/dist/core/compaction/compactor.d.ts +3 -3
  119. package/dist/core/debug.code.js +1 -1
  120. package/dist/core/debug.impl.js +3 -3
  121. package/dist/core/debug.js +3 -3
  122. package/dist/core/export-html/card-projection.impl.js +3 -3
  123. package/dist/core/export-html/card-projection.js +3 -3
  124. package/dist/core/export-html/index.code.js +4 -4
  125. package/dist/core/export-html/index.code.js.map +1 -1
  126. package/dist/core/export-html/index.impl.js +3 -3
  127. package/dist/core/export-html/index.js +3 -3
  128. package/dist/core/export-html/json-spans.impl.js +3 -3
  129. package/dist/core/export-html/json-spans.js +3 -3
  130. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  131. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  132. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  133. package/dist/core/export-html/tool-renderer.js +3 -3
  134. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  135. package/dist/core/extensions/jiti-loader.js +3 -3
  136. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  137. package/dist/core/extensions/jiti-static-loader.js +3 -3
  138. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  139. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  140. package/dist/core/extensions/loader-host-modules.js +3 -3
  141. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  142. package/dist/core/extensions/runner-context.js +2 -2
  143. package/dist/core/intercom-broker-control-host.code.js +2 -2
  144. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  145. package/dist/core/intercom-broker-control-host.js +3 -3
  146. package/dist/core/intercom-broker-control.code.js +3 -3
  147. package/dist/core/intercom-broker-control.impl.js +3 -3
  148. package/dist/core/intercom-broker-control.js +3 -3
  149. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  150. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  151. package/dist/core/package-manager-storage-adapters.js +3 -3
  152. package/dist/core/process-start-token.d.ts +12 -3
  153. package/dist/core/process-tree-containment.d.ts +16 -0
  154. package/dist/core/sdk-types.d.ts +1 -2
  155. package/dist/core/sdk-types.js.map +1 -1
  156. package/dist/core/sdk.code.js +3 -3
  157. package/dist/core/sdk.impl.js +3 -3
  158. package/dist/core/sdk.js +3 -3
  159. package/dist/core/session-manager-core.js +5 -5
  160. package/dist/core/session-manager-list.impl.js +3 -3
  161. package/dist/core/session-manager-list.js +3 -3
  162. package/dist/core/session-manager.code.js +1 -1
  163. package/dist/core/session-manager.impl.js +3 -3
  164. package/dist/core/session-manager.js +3 -3
  165. package/dist/core/session-storage.code.js +1 -1
  166. package/dist/core/session-storage.impl.js +3 -3
  167. package/dist/core/session-storage.js +3 -3
  168. package/dist/core/settings-schema.d.ts +0 -3
  169. package/dist/core/storage/added-exports-0-10-11.js +19 -0
  170. package/dist/core/storage/added-exports-0-10-11.js.map +1 -0
  171. package/dist/core/storage/creation-time.js +105 -0
  172. package/dist/core/storage/creation-time.js.map +1 -0
  173. package/dist/core/storage/database.d.ts +25 -5
  174. package/dist/core/storage/database.js.map +1 -1
  175. package/dist/core/storage/dialect.d.ts +1 -1
  176. package/dist/core/storage/dialect.js +1 -1
  177. package/dist/core/storage/dialect.js.map +1 -1
  178. package/dist/core/storage/errors.d.ts +13 -13
  179. package/dist/core/storage/errors.js +10 -16
  180. package/dist/core/storage/errors.js.map +1 -1
  181. package/dist/core/storage/fenced-paths.d.ts +18 -6
  182. package/dist/core/storage/fenced-paths.js +18 -6
  183. package/dist/core/storage/fenced-paths.js.map +1 -1
  184. package/dist/core/storage/file-identity.d.ts +2 -0
  185. package/dist/core/storage/file-identity.js +24 -8
  186. package/dist/core/storage/file-identity.js.map +1 -1
  187. package/dist/core/storage/index.d.ts +3 -2
  188. package/dist/core/storage/index.js +5 -3
  189. package/dist/core/storage/index.js.map +1 -1
  190. package/dist/core/storage/libsql-removed.d.ts +71 -0
  191. package/dist/core/storage/libsql-removed.js +123 -0
  192. package/dist/core/storage/libsql-removed.js.map +1 -0
  193. package/dist/core/storage/migrations.d.ts +78 -14
  194. package/dist/core/storage/migrations.js +375 -49
  195. package/dist/core/storage/migrations.js.map +1 -1
  196. package/dist/core/storage/node-sqlite-file-gate.js +0 -15
  197. package/dist/core/storage/node-sqlite-file-gate.js.map +1 -1
  198. package/dist/core/storage/node-sqlite-thread.js +215 -30
  199. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  200. package/dist/core/storage/node-sqlite.js +484 -72
  201. package/dist/core/storage/node-sqlite.js.map +1 -1
  202. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  203. package/dist/core/storage/offline-snapshot-file.js +3 -3
  204. package/dist/core/storage/prefix.d.ts +1 -1
  205. package/dist/core/storage/prefix.js +9 -2
  206. package/dist/core/storage/prefix.js.map +1 -1
  207. package/dist/core/storage/process-selection.d.ts +5 -5
  208. package/dist/core/storage/provider.js +2 -2
  209. package/dist/core/storage/schema-catalog.d.ts +76 -15
  210. package/dist/core/storage/schema-catalog.js +359 -68
  211. package/dist/core/storage/schema-catalog.js.map +1 -1
  212. package/dist/core/storage/selection.d.ts +7 -82
  213. package/dist/core/storage/selection.js +20 -235
  214. package/dist/core/storage/selection.js.map +1 -1
  215. package/dist/core/storage/session/branch-fork-source.code.js +2 -2
  216. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  217. package/dist/core/storage/session/branch-fork-source.js +3 -3
  218. package/dist/core/storage/session/card-view.impl.js +3 -3
  219. package/dist/core/storage/session/card-view.js +3 -3
  220. package/dist/core/storage/session/child-reader.code.js +3 -3
  221. package/dist/core/storage/session/child-reader.impl.js +3 -3
  222. package/dist/core/storage/session/child-reader.js +3 -3
  223. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  224. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  225. package/dist/core/storage/session/expanded-child-details.code.js +2 -2
  226. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  227. package/dist/core/storage/session/expanded-child-details.js +3 -3
  228. package/dist/core/storage/session/fork-detach.d.ts +11 -1
  229. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  230. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  231. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  232. package/dist/core/storage/session/fork-row-index.js +3 -3
  233. package/dist/core/storage/session/fork-staging.code.js +4 -7
  234. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  235. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  236. package/dist/core/storage/session/fork-staging.js +3 -3
  237. package/dist/core/storage/session/fork-sweep.js +31 -7
  238. package/dist/core/storage/session/fork-sweep.js.map +1 -1
  239. package/dist/core/storage/session/fork-window.code.js +3 -3
  240. package/dist/core/storage/session/fork-window.impl.js +3 -3
  241. package/dist/core/storage/session/fork-window.js +3 -3
  242. package/dist/core/storage/session/history-pages.impl.js +3 -3
  243. package/dist/core/storage/session/history-pages.js +3 -3
  244. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  245. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  246. package/dist/core/storage/session/jsonl-session-lock.d.ts +100 -0
  247. package/dist/core/storage/session/jsonl-session-store.d.ts +46 -24
  248. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  249. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  250. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  251. package/dist/core/storage/session/memory-session-store.js +3 -3
  252. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  253. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  254. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  255. package/dist/core/storage/session/released-history-files.code.js +9 -9
  256. package/dist/core/storage/session/released-history-files.code.js.map +1 -1
  257. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  258. package/dist/core/storage/session/released-history-files.js +3 -3
  259. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  260. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  261. package/dist/core/storage/session/session-resume.impl.js +3 -3
  262. package/dist/core/storage/session/session-resume.js +3 -3
  263. package/dist/core/storage/session/session-search-index.d.ts +52 -5
  264. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  265. package/dist/core/storage/session/snapshot-cut.js +3 -3
  266. package/dist/core/storage/session/snapshot-history.code.js +3 -3
  267. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  268. package/dist/core/storage/session/snapshot-history.js +3 -3
  269. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  270. package/dist/core/storage/session/sql-session-store.d.ts +99 -18
  271. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  272. package/dist/core/storage/session/sql-session-store.js +3 -3
  273. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  274. package/dist/core/storage/session/tree-outline.js +3 -3
  275. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  276. package/dist/core/storage/session/tree-presentation.js +3 -3
  277. package/dist/core/storage/sqlite-facade.d.ts +12 -1
  278. package/dist/core/storage/sqlite-facade.js +310 -33
  279. package/dist/core/storage/sqlite-facade.js.map +1 -1
  280. package/dist/core/storage/sqlite-open-batch.js +10 -0
  281. package/dist/core/storage/sqlite-open-batch.js.map +1 -0
  282. package/dist/core/storage/storage-status.code.js +1 -1
  283. package/dist/core/storage/storage-status.impl.js +3 -3
  284. package/dist/core/storage/storage-status.js +3 -3
  285. package/dist/core/storage/team.code.js +1 -1
  286. package/dist/core/storage/team.d.ts +26 -115
  287. package/dist/core/storage/team.impl.js +3 -3
  288. package/dist/core/storage/team.js +3 -3
  289. package/dist/core/structured-output/index.code.js +1 -1
  290. package/dist/core/structured-output/index.impl.js +3 -3
  291. package/dist/core/structured-output/index.js +3 -3
  292. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  293. package/dist/core/tasks/task-completion-entry.js +3 -3
  294. package/dist/core/tasks/task-file-history.code.js +3 -3
  295. package/dist/core/tasks/task-file-history.impl.js +3 -3
  296. package/dist/core/tasks/task-file-history.js +3 -3
  297. package/dist/core/tasks/task-reference-archive.code.js +4 -4
  298. package/dist/core/tasks/task-reference-archive.js +3 -3
  299. package/dist/core/tasks/task-reference-identity.js +3 -3
  300. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  301. package/dist/core/tasks/task-reference-stream.js +3 -3
  302. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  303. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  304. package/dist/core/tasks/task-view-source.code.js +1 -1
  305. package/dist/core/tasks/task-view-source.impl.js +3 -3
  306. package/dist/core/tasks/task-view-source.js +3 -3
  307. package/dist/core/tools/history-tasks.d.ts +3 -2
  308. package/dist/core/tools/read-url.code.js +4 -4
  309. package/dist/core/tools/read-url.impl.js +3 -3
  310. package/dist/core/tools/read-url.js +3 -3
  311. package/dist/core/worktree-snapshot/blob-store.d.ts +44 -5
  312. package/dist/core/worktree-snapshot/blob-store.js +553 -30
  313. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  314. package/dist/core/worktree-snapshot/errors.code.js +2 -2
  315. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  316. package/dist/core/worktree-snapshot/errors.js +3 -3
  317. package/dist/core/worktree-snapshot/fork-blob-guard.js +81 -0
  318. package/dist/core/worktree-snapshot/fork-blob-guard.js.map +1 -0
  319. package/dist/core/worktree-snapshot/fork-snapshot-index.js +208 -50
  320. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -1
  321. package/dist/core/worktree-snapshot/session-index-reset.code.js +4 -0
  322. package/dist/core/worktree-snapshot/session-index-reset.code.js.map +1 -1
  323. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  324. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  325. package/dist/extensions/codemode/execute.code.js +1 -1
  326. package/dist/extensions/codemode/execute.impl.js +3 -3
  327. package/dist/extensions/codemode/execute.js +3 -3
  328. package/dist/extensions/codemode/renderer.code.js +2 -2
  329. package/dist/extensions/codemode/renderer.impl.js +3 -3
  330. package/dist/extensions/codemode/renderer.js +3 -3
  331. package/dist/extensions/mcp/cli.code.js +3 -3
  332. package/dist/extensions/mcp/cli.impl.js +3 -3
  333. package/dist/extensions/mcp/cli.js +3 -3
  334. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  335. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  336. package/dist/extensions/mcp/cli.lazy.js +3 -3
  337. package/dist/extensions/mcp/runtime.code.js +1 -1
  338. package/dist/extensions/mcp/runtime.impl.js +3 -3
  339. package/dist/extensions/mcp/runtime.js +3 -3
  340. package/dist/index.d.ts +3 -1
  341. package/dist/index.js +5 -5
  342. package/dist/main-first-time-setup.code.js +1 -1
  343. package/dist/main-first-time-setup.impl.js +3 -3
  344. package/dist/main-first-time-setup.js +3 -3
  345. package/dist/main.js +1 -1
  346. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  347. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  348. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  349. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  350. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  351. package/dist/modes/interactive/startup-shell-eligibility.js +1 -1
  352. package/dist/modes/interactive-engine/engine-prewarm.d.ts +1 -1
  353. package/dist/modes/print-mode.js +1 -1
  354. package/dist/package-manager-cli.code.js +6 -6
  355. package/dist/package-manager-cli.impl.js +3 -3
  356. package/dist/package-manager-cli.js +3 -3
  357. package/dist/rpc-entry.js +1 -1
  358. package/dist/startup-files.json +1 -1
  359. package/dist/startup-stages/10.js +1 -1
  360. package/dist/startup-stages/11.js +1 -1
  361. package/dist/startup-stages/12.js +1 -1
  362. package/dist/startup-stages/2.js +2 -4
  363. package/dist/startup-stages/3.js +1 -3
  364. package/dist/startup-stages/4.js +1 -2
  365. package/dist/startup-stages/5.js +1 -1
  366. package/dist/startup-stages/6.js +5 -7
  367. package/dist/startup-stages/7.js +3 -10
  368. package/dist/startup-stages/8.js +7 -2
  369. package/dist/startup-stages/9.js +1 -7
  370. package/dist/startup-stages/stages.json +1 -1
  371. package/dist/utils/compile-cache-deferral.js +8 -13
  372. package/dist/utils/compile-cache-deferral.js.map +1 -1
  373. package/dist/utils/compile-cache-warmup-host.js +3 -4
  374. package/dist/utils/compile-cache-warmup-host.js.map +1 -1
  375. package/dist/utils/compile-cache.js +12 -100
  376. package/dist/utils/compile-cache.js.map +1 -1
  377. package/dist/utils/startup-database-spare.code.js +2 -2
  378. package/dist/utils/startup-database-spare.impl.js +3 -3
  379. package/dist/utils/startup-database-spare.js +3 -3
  380. package/dist/utils/tools-manager.code.js +1 -1
  381. package/dist/utils/tools-manager.impl.js +3 -3
  382. package/dist/utils/tools-manager.js +3 -3
  383. package/dist/utils/worker-threads.js +2 -15
  384. package/dist/utils/worker-threads.js.map +1 -1
  385. package/docs/build.md +3 -3
  386. package/docs/changelog.mdx +1498 -69
  387. package/docs/compaction/reference.md +5 -5
  388. package/docs/compaction.md +7 -9
  389. package/docs/containerization.md +2 -2
  390. package/docs/custom-provider/api-reference.md +1 -1
  391. package/docs/docs.json +37 -10
  392. package/docs/environment-variables.md +0 -2
  393. package/docs/extensions/api-reference.md +4 -4
  394. package/docs/getting-started/installation.md +3 -0
  395. package/docs/guides/configuration.md +1 -1
  396. package/docs/guides/non-interactive.md +1 -1
  397. package/docs/guides/resume-on-any-machine.md +14 -22
  398. package/docs/guides/team-setup.md +56 -83
  399. package/docs/guides.md +2 -4
  400. package/docs/herdr.md +1 -1
  401. package/docs/index.md +1 -1
  402. package/docs/intercom/operations.md +26 -21
  403. package/docs/intercom/reference.md +2 -2
  404. package/docs/intercom.md +1 -1
  405. package/docs/libraries/storage-postgres.md +9 -9
  406. package/docs/libraries.md +2 -3
  407. package/docs/models-configuration.md +2 -2
  408. package/docs/models.md +2 -3
  409. package/docs/packages/authoring.md +7 -7
  410. package/docs/packages.md +1 -1
  411. package/docs/programmatic.md +2 -2
  412. package/docs/quickstart.md +1 -1
  413. package/docs/reference/cli.md +6 -11
  414. package/docs/reference.md +2 -2
  415. package/docs/rpc/extension-ui.md +2 -2
  416. package/docs/sdk/reference.md +5 -4
  417. package/docs/sdk/storage.md +8 -92
  418. package/docs/sdk/structured-decisions.md +1 -1
  419. package/docs/sdk/web-server.md +3 -3
  420. package/docs/sdk.md +14 -4
  421. package/docs/security.md +1 -1
  422. package/docs/session-format.md +5 -5
  423. package/docs/sessions.md +29 -49
  424. package/docs/settings.md +7 -8
  425. package/docs/storage/custom-adapters.md +255 -0
  426. package/docs/storage/jsonl.md +117 -0
  427. package/docs/{guides/postgres-pgbouncer.md → storage/postgres/pgbouncer.md} +66 -68
  428. package/docs/storage/postgres/tuning.md +337 -0
  429. package/docs/storage/postgres.md +556 -0
  430. package/docs/storage/sqlite.md +99 -0
  431. package/docs/storage.md +326 -990
  432. package/docs/subagents/authoring.md +1 -1
  433. package/docs/subagents.md +2 -2
  434. package/docs/tools.md +1 -1
  435. package/docs/worktree-snapshots.md +2 -2
  436. package/package.json +9 -9
  437. package/schemas/models.schema.json +2 -2
  438. package/schemas/settings.schema.json +0 -14
  439. package/dist/_shared/p1b-elig-ENCUPKKJ.js.map +0 -1
  440. package/dist/_shared/sdk-IQMULKFU.js.map +0 -1
  441. package/dist/_shared/startup-0-0-3IXNMFM2.js.map +0 -1
  442. package/dist/_shared/startup-0-1-7T2IAE7J.js.map +0 -1
  443. package/dist/_shared/startup-8-1-X32CYSXB.js.map +0 -1
  444. package/dist/core/intercom-broker-control.d.ts +0 -129
  445. package/dist/startup-stages/13.js +0 -1
  446. package/docs/guides/postgres-tuning.md +0 -311
  447. package/docs/libraries/storage-libsql.md +0 -97
@@ -1,24 +1,25 @@
1
1
  import { __name } from "./rolldown-runtime-BGM3D5V3.js";
2
- import { createSessionCwdMatcher, normalizePath, resolvePath } from "./p0-cli-BB45ZQY6.js";
3
- import { CURRENT_SESSION_VERSION, EntryTypeReader, JsonTextChecker, applySessionSummaryEntries, bindChatEpoch, boundedChatRecord, decodeChatRecord, firstChatOrders, getErrnoCode, historySnapshotFor, inheritForkScope, isClassifiedWorkflowSession, materializeSessionSummaryMetadata, noteSnapshotGeneration, observeReferenceCut, readLines, referenceMetadataRead, registerArchiveLoad, registerForkScope, require_sha256, sha256Hex, summarizeSession, yieldTurn } from "./startup-0-0-3IXNMFM2.js";
4
- import { AgentRehydrateError, AgentReleaseConfigError, SessionKeyDigests, appendFileChatRecord, deleteFileChatRecords, hasFileChatRecords, latestLegacyMessageTime, legacyCompletionTarget, readFileChatOrders, readFileChatRecords, rememberEarlierCompletion, summarizeLegacySession } from "./startup-0-1-7T2IAE7J.js";
2
+ import { createModuleRequire, createSessionCwdMatcher, normalizePath, resolvePath } from "./p0-cli-BB45ZQY6.js";
3
+ import { CURRENT_SESSION_VERSION, EntryTypeReader, JsonTextChecker, applySessionSummaryEntries, bindChatEpoch, boundedChatRecord, decodeChatRecord, epochHasCreationTime, fileEpochOf, firstChatOrders, getErrnoCode, historySnapshotFor, inheritForkScope, isClassifiedWorkflowSession, legacyFileEpochOf, materializeSessionSummaryMetadata, noteSnapshotGeneration, observeReferenceCut, referenceMetadataRead, registerArchiveLoad, registerForkScope, require_sha256, sha256Hex, summarizeSession, yieldTurn } from "./startup-0-0-XJJDOIEC.js";
4
+ import { AgentRehydrateError, AgentReleaseConfigError, SessionKeyDigests, appendFileChatRecords, deleteFileChatRecords, hasFileChatRecords, latestLegacyMessageTime, legacyCompletionTarget, readFileChatOrders, readFileChatRecords, rememberEarlierCompletion, summarizeLegacySession } from "./startup-0-1-M6OWAYHH.js";
5
5
  import { agentWakeDispatcher } from "./startup-0-2-5QHPCEON.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";
9
9
  import { join } from "path";
10
- import { basename as basename$1, dirname as dirname$1, join as join$1, resolve as resolve$1 } from "node:path";
10
+ import { basename as basename$1, dirname as dirname$1, join as join$1, resolve as resolve$1, win32 as win32$1 } from "node:path";
11
11
  import { createSessionCwdMatcherAsync } from "../utils/canonical-path.js";
12
- import { constants as constants$1, createReadStream, rmdir as rmdir$1, stat as stat$1 } from "node:fs";
12
+ import { close, constants as constants$1, createReadStream, mkdir as mkdir$1, open as open$1, rmdir as rmdir$1, stat as stat$1, utimes as utimes$1, write } from "node:fs";
13
13
  import { uuidv7 } from "@bastani/atomic-ai";
14
14
  import { SessionSpillError, StoragePayloadTooLargeError, describeStorageError, isStorageTransientError, isStorageWriteLockTimeoutError, isStorageWriterQueueUnusableError } from "../core/storage/errors.js";
15
- import { open as open$1 } from "fs/promises";
15
+ import { open as open$2 } from "fs/promises";
16
16
  import { createHash, randomUUID } from "node:crypto";
17
17
  import lockfile from "proper-lockfile";
18
18
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
19
19
  import { randomUUID as randomUUID$1 } from "crypto";
20
20
  import { SessionConflictError, SessionExistsError, SessionFormatVersionError, SessionFormatVersionError as SessionFormatVersionError$1, SessionIdMismatchError, SessionInvalidTextError, SessionInvalidTimestampError, SessionNotFoundError, StorageUnavailableError as StorageUnavailableError$1, StoreClosedError as StoreClosedError$1 } from "../core/storage/session/errors.js";
21
21
  import { isProxy } from "node:util/types";
22
+ import { fileGenerationOf, learnCreationTime } from "../core/storage/creation-time.js";
22
23
  import { openNodeSqliteDatabase } from "../core/storage/node-sqlite.js";
23
24
  import { StringDecoder } from "string_decoder";
24
25
  // dist/core/storage/session/validation.js
@@ -2371,6 +2372,46 @@ async function* historyChunks(store, sessionId, epoch, reference, options) {
2371
2372
  if (offset < reference.bytes) await yieldSessionTurn();
2372
2373
  }
2373
2374
  }
2375
+ // dist/core/storage/file-sync.js
2376
+ const __atomicDistModuleUrl$1 = new URL("../core/storage/file-sync.js", import.meta.url).href;
2377
+ let plainSync;
2378
+ function nativePlainSync() {
2379
+ if (process.platform !== "darwin") return null;
2380
+ if (plainSync === void 0) try {
2381
+ plainSync = createModuleRequire(__atomicDistModuleUrl$1)("@bastani/atomic-natives").fsyncDescriptor ?? null;
2382
+ } catch {
2383
+ plainSync = null;
2384
+ }
2385
+ return plainSync;
2386
+ }
2387
+ async function syncFile(handle) {
2388
+ const sync = nativePlainSync();
2389
+ if (sync === null) await handle.datasync();
2390
+ else await sync(handle.fd);
2391
+ }
2392
+ async function syncPath(path, handle, handleWritable = false) {
2393
+ if (handle !== void 0 && (process.platform !== "win32" || handleWritable)) {
2394
+ await syncFile(handle);
2395
+ return;
2396
+ }
2397
+ const opened = await open(path, process.platform === "win32" ? "r+" : "r");
2398
+ try {
2399
+ await syncFile(opened);
2400
+ } finally {
2401
+ await opened.close();
2402
+ }
2403
+ }
2404
+ async function syncDirectory(path) {
2405
+ if (process.platform === "win32") return;
2406
+ const handle = await open(path, "r");
2407
+ try {
2408
+ const sync = nativePlainSync();
2409
+ if (sync === null) await handle.sync();
2410
+ else await sync(handle.fd);
2411
+ } finally {
2412
+ await handle.close();
2413
+ }
2414
+ }
2374
2415
  // dist/core/storage/session/jsonl-entry-projection.js
2375
2416
  /**
2376
2417
  * One byte-level pass over an oversized saved entry. It checks the JSON text as `JSON.parse` would and keeps only the
@@ -2961,6 +3002,637 @@ async function* branchStatePages(lastSeq, source, prefixToolCalls) {
2961
3002
  if (seq <= lastSeq) await yieldSessionTurn();
2962
3003
  }
2963
3004
  }
3005
+ // dist/core/storage/session/jsonl-session-lock.js
3006
+ const __atomicDistModuleUrl = new URL("../core/storage/session/jsonl-session-lock.js", import.meta.url).href;
3007
+ const WINDOWS_PLAIN_LOCK_PATH_LIMIT = 240;
3008
+ function nativeLockPath(path, platform = process.platform) {
3009
+ if (platform !== "win32") return path;
3010
+ return win32$1.resolve(path).length > WINDOWS_PLAIN_LOCK_PATH_LIMIT ? win32$1.toNamespacedPath(path) : path;
3011
+ }
3012
+ const LEGACY_LOCK_STALE_MS = 1e4;
3013
+ const GROUP_LOCK_BACKDATE_MS = 2e3;
3014
+ const GROUP_LOCK_HEARTBEAT_MS = 3e3;
3015
+ const GROUP_LOCK_FRESH_MS = 8e3;
3016
+ const GROUP_LOCK_REFRESH_ON_JOIN_MS = 5e3;
3017
+ const GROUP_LOCK_PLACE_MAX_AGE_MS = 5e3;
3018
+ const ADVISORY_WAIT_CHUNK_MS = 25;
3019
+ const LEGACY_POLL_MS = 5;
3020
+ const TRANSIENT_RELEASE_CODES = /* @__PURE__ */ new Set([
3021
+ "EPERM",
3022
+ "EBUSY",
3023
+ "EACCES",
3024
+ "ENOTEMPTY"
3025
+ ]);
3026
+ const LOCK_BACKOFF_MS = [
3027
+ 10,
3028
+ 20,
3029
+ 50,
3030
+ 100,
3031
+ 200,
3032
+ 400,
3033
+ 700
3034
+ ];
3035
+ const ALL_STRIPE_INDICES = Array.from({ length: 32 }, (_, index) => index);
3036
+ const lastSeenGroupRecords = /* @__PURE__ */ new Map();
3037
+ const MAX_CACHED_GROUP_RECORDS = 256;
3038
+ function rememberGroupRecord(lockPath, record) {
3039
+ lastSeenGroupRecords.delete(lockPath);
3040
+ lastSeenGroupRecords.set(lockPath, record);
3041
+ if (lastSeenGroupRecords.size > MAX_CACHED_GROUP_RECORDS) lastSeenGroupRecords.delete(lastSeenGroupRecords.keys().next().value);
3042
+ }
3043
+ let nativeSessionLocks;
3044
+ function loadNativeSessionLocks() {
3045
+ if (nativeSessionLocks === void 0) try {
3046
+ const binding = createModuleRequire(__atomicDistModuleUrl)("@bastani/atomic-natives");
3047
+ nativeSessionLocks = typeof binding.tryAdvisoryLockAsync === "function" && typeof binding.trySharedAdvisoryLockAsync === "function" && typeof binding.renameNoReplaceAsync === "function" ? {
3048
+ tryAdvisoryLockAsync: (path, waitMs) => binding.tryAdvisoryLockAsync(path, waitMs),
3049
+ trySharedAdvisoryLockAsync: (path, waitMs) => binding.trySharedAdvisoryLockAsync(path, waitMs),
3050
+ renameNoReplaceAsync: (from, to) => binding.renameNoReplaceAsync(from, to)
3051
+ } : null;
3052
+ } catch {
3053
+ nativeSessionLocks = null;
3054
+ }
3055
+ return nativeSessionLocks;
3056
+ }
3057
+ function sessionLockStripe(name) {
3058
+ let hash = 0x811c9dc5;
3059
+ for (let index = 0; index < name.length; index++) hash = Math.imul(hash ^ name.charCodeAt(index), 16777619);
3060
+ return (hash >>> 0) % 32;
3061
+ }
3062
+ function sortedStripesForPaths(paths) {
3063
+ const set = /* @__PURE__ */ new Set();
3064
+ for (const path of paths) set.add(sessionLockStripe(basename$1(path)));
3065
+ return [...set].sort((a, b) => a - b);
3066
+ }
3067
+ var RelockRequiredError = class extends Error {
3068
+ path;
3069
+ constructor(path) {
3070
+ super(`Session file ${path} requires a different lock stripe`);
3071
+ this.name = "RelockRequiredError";
3072
+ this.path = path;
3073
+ }
3074
+ };
3075
+ function defaultDirectoryFs(lockFs) {
3076
+ return lockFs ?? {
3077
+ mkdir: mkdir$1,
3078
+ rmdir: rmdir$1,
3079
+ stat: stat$1,
3080
+ utimes: utimes$1
3081
+ };
3082
+ }
3083
+ function gateLockPath(lockPath) {
3084
+ return `${lockPath}.gate`;
3085
+ }
3086
+ function membersLockPath(lockPath) {
3087
+ return `${lockPath}.members`;
3088
+ }
3089
+ function groupRecordPath(lockPath) {
3090
+ return `${lockPath}.group`;
3091
+ }
3092
+ function groupRecordTmpPath(lockPath) {
3093
+ return `${lockPath}.group.tmp`;
3094
+ }
3095
+ function stagingDirPath(lockPath) {
3096
+ return `${lockPath}.staging`;
3097
+ }
3098
+ function deadDirPath(lockPath) {
3099
+ return `${lockPath}.dead`;
3100
+ }
3101
+ function createLockPath(lockPath) {
3102
+ return `${lockPath}.create`;
3103
+ }
3104
+ function stripeLockPath(lockPath, stripe) {
3105
+ return `${lockPath}.stripe.${stripe}`;
3106
+ }
3107
+ function backdatedLockMtimeMs(nowMs = Date.now()) {
3108
+ return Math.floor((nowMs - GROUP_LOCK_BACKDATE_MS) / 2e3) * 2e3;
3109
+ }
3110
+ function ageMsOf(stats, nowMs = Date.now()) {
3111
+ return nowMs - Number(stats.mtimeNs / 1000000n);
3112
+ }
3113
+ function matchesGroupRecord(stats, record) {
3114
+ if (fileGenerationOf(stats) !== record.generation) return false;
3115
+ const mtimeNs = String(stats.mtimeNs);
3116
+ return mtimeNs === record.mtimeNs || record.nextMtimeNs !== void 0 && mtimeNs === record.nextMtimeNs;
3117
+ }
3118
+ function isWindowsTransientPermissionError(error) {
3119
+ if (process.platform !== "win32") return false;
3120
+ if (error?.code === "EPERM") return true;
3121
+ const message = error instanceof Error ? error.message : String(error);
3122
+ return /\(os error (?:5|32)\)/i.test(message);
3123
+ }
3124
+ function isTransientDirectoryError(error) {
3125
+ const code = error?.code ?? "";
3126
+ if (TRANSIENT_RELEASE_CODES.has(code)) return true;
3127
+ return isWindowsTransientPermissionError(error);
3128
+ }
3129
+ function statBigInt(fs, path) {
3130
+ return new Promise((resolve, reject) => {
3131
+ fs.stat(path, { bigint: true }, (error, stats) => {
3132
+ if (!error) {
3133
+ resolve(stats);
3134
+ return;
3135
+ }
3136
+ const code = error.code;
3137
+ if (code === "ENOENT" || code === "ENOTDIR") {
3138
+ resolve(void 0);
3139
+ return;
3140
+ }
3141
+ reject(error);
3142
+ });
3143
+ });
3144
+ }
3145
+ function mkdirDirectory(fs, path) {
3146
+ return new Promise((resolve, reject) => {
3147
+ fs.mkdir(path, (error) => {
3148
+ if (error) reject(error);
3149
+ else resolve();
3150
+ });
3151
+ });
3152
+ }
3153
+ function removeDirectory(fs, path) {
3154
+ return new Promise((resolve, reject) => {
3155
+ fs.rmdir(path, (error) => {
3156
+ if (error && error.code !== "ENOENT") reject(error);
3157
+ else resolve();
3158
+ });
3159
+ });
3160
+ }
3161
+ function utimesDirectory(fs, path, timeMs) {
3162
+ const time = new Date(timeMs);
3163
+ return new Promise((resolve, reject) => {
3164
+ fs.utimes(path, time, time, (error) => {
3165
+ if (error) reject(error);
3166
+ else resolve();
3167
+ });
3168
+ });
3169
+ }
3170
+ async function readGroupRecord(path) {
3171
+ let text;
3172
+ try {
3173
+ text = await readFile(path, "utf8");
3174
+ } catch {
3175
+ return;
3176
+ }
3177
+ if (!text) return void 0;
3178
+ try {
3179
+ const parsed = JSON.parse(text);
3180
+ if (typeof parsed.generation !== "string" || typeof parsed.mtimeNs !== "string") return void 0;
3181
+ if (parsed.nextMtimeNs !== void 0 && typeof parsed.nextMtimeNs !== "string") return void 0;
3182
+ return {
3183
+ generation: parsed.generation,
3184
+ mtimeNs: parsed.mtimeNs,
3185
+ ...parsed.nextMtimeNs !== void 0 ? { nextMtimeNs: parsed.nextMtimeNs } : {}
3186
+ };
3187
+ } catch {
3188
+ return;
3189
+ }
3190
+ }
3191
+ function openFd(path, flags, mode) {
3192
+ return new Promise((resolve, reject) => {
3193
+ const cb = (error, fd) => {
3194
+ if (error) reject(error);
3195
+ else resolve(fd);
3196
+ };
3197
+ if (mode === void 0) open$1(path, flags, cb);
3198
+ else open$1(path, flags, mode, cb);
3199
+ });
3200
+ }
3201
+ function writeFd(fd, payload, offset, length) {
3202
+ return new Promise((resolve, reject) => {
3203
+ write(fd, payload, offset, length, (error, bytesWritten) => {
3204
+ if (error) reject(error);
3205
+ else resolve(bytesWritten);
3206
+ });
3207
+ });
3208
+ }
3209
+ function closeFd(fd) {
3210
+ return new Promise((resolve, reject) => {
3211
+ close(fd, (error) => {
3212
+ if (error) reject(error);
3213
+ else resolve();
3214
+ });
3215
+ });
3216
+ }
3217
+ async function writeGroupRecord(path, record) {
3218
+ const payload = Buffer.from(JSON.stringify(record));
3219
+ const fd = await openFd(path, "w", 384);
3220
+ try {
3221
+ for (let offset = 0; offset < payload.length;) offset += await writeFd(fd, payload, offset, payload.length - offset);
3222
+ } finally {
3223
+ await closeFd(fd);
3224
+ }
3225
+ }
3226
+ async function writeGroupRecordAtomic(path, tmpPath, record) {
3227
+ try {
3228
+ await writeGroupRecord(tmpPath, record);
3229
+ await rename(tmpPath, path);
3230
+ } catch (error) {
3231
+ await unlink(tmpPath).catch(() => void 0);
3232
+ throw error;
3233
+ }
3234
+ }
3235
+ async function clearGroupRecord(path) {
3236
+ let fd;
3237
+ try {
3238
+ fd = await openFd(path, "w", 384);
3239
+ } catch (error) {
3240
+ if (error.code === "ENOENT") return;
3241
+ throw error;
3242
+ }
3243
+ await closeFd(fd);
3244
+ }
3245
+ async function callAdvisoryWithWindowsBackoff(attempt, signal) {
3246
+ let refusals = 0;
3247
+ for (;;) {
3248
+ signal?.throwIfAborted();
3249
+ try {
3250
+ return await attempt();
3251
+ } catch (error) {
3252
+ if (isWindowsTransientPermissionError(error) && refusals < LOCK_BACKOFF_MS.length) {
3253
+ signal?.throwIfAborted();
3254
+ await setTimeout$1(LOCK_BACKOFF_MS[refusals++]);
3255
+ continue;
3256
+ }
3257
+ throw error;
3258
+ }
3259
+ }
3260
+ }
3261
+ async function tryAdvisoryExclusiveZero(native, path, signal) {
3262
+ const target = nativeLockPath(path);
3263
+ return callAdvisoryWithWindowsBackoff(() => native.tryAdvisoryLockAsync(target, 0), signal);
3264
+ }
3265
+ async function acquireAdvisoryExclusive(native, path, signal) {
3266
+ const target = nativeLockPath(path);
3267
+ for (let attempt = 0;; attempt++) {
3268
+ signal?.throwIfAborted();
3269
+ const waitMs = attempt < 3 ? 0 : ADVISORY_WAIT_CHUNK_MS;
3270
+ const lock = await callAdvisoryWithWindowsBackoff(() => native.tryAdvisoryLockAsync(target, waitMs), signal);
3271
+ if (lock !== null) return lock;
3272
+ if (attempt < 2) {
3273
+ signal?.throwIfAborted();
3274
+ await setTimeout$1(1);
3275
+ }
3276
+ }
3277
+ }
3278
+ async function acquireAdvisoryShared(native, path, signal) {
3279
+ const target = nativeLockPath(path);
3280
+ for (let attempt = 0;; attempt++) {
3281
+ signal?.throwIfAborted();
3282
+ const waitMs = attempt < 3 ? 0 : ADVISORY_WAIT_CHUNK_MS;
3283
+ const lock = await callAdvisoryWithWindowsBackoff(() => native.trySharedAdvisoryLockAsync(target, waitMs), signal);
3284
+ if (lock !== null) return lock;
3285
+ if (attempt < 2) {
3286
+ signal?.throwIfAborted();
3287
+ await setTimeout$1(1);
3288
+ }
3289
+ }
3290
+ }
3291
+ async function renameNoReplaceWithBackoff(native, from, to, signal) {
3292
+ const source = nativeLockPath(from);
3293
+ const destination = nativeLockPath(to);
3294
+ return callAdvisoryWithWindowsBackoff(() => native.renameNoReplaceAsync(source, destination), signal);
3295
+ }
3296
+ async function mkdirWithWindowsBackoff(fs, path, signal) {
3297
+ let refusals = 0;
3298
+ for (;;) {
3299
+ signal?.throwIfAborted();
3300
+ try {
3301
+ await mkdirDirectory(fs, path);
3302
+ return;
3303
+ } catch (error) {
3304
+ if (error.code === "EPERM" && process.platform === "win32" && refusals < LOCK_BACKOFF_MS.length) {
3305
+ signal?.throwIfAborted();
3306
+ await setTimeout$1(LOCK_BACKOFF_MS[refusals++]);
3307
+ continue;
3308
+ }
3309
+ throw error;
3310
+ }
3311
+ }
3312
+ }
3313
+ async function removeDirectoryWithBackoff(fs, path) {
3314
+ try {
3315
+ await removeDirectory(fs, path);
3316
+ return true;
3317
+ } catch (error) {
3318
+ if (!TRANSIENT_RELEASE_CODES.has(error.code ?? "")) throw error;
3319
+ }
3320
+ for (const wait of LOCK_BACKOFF_MS) {
3321
+ await setTimeout$1(wait);
3322
+ try {
3323
+ await removeDirectory(fs, path);
3324
+ return true;
3325
+ } catch (error) {
3326
+ if (!TRANSIENT_RELEASE_CODES.has(error.code ?? "")) throw error;
3327
+ }
3328
+ }
3329
+ return false;
3330
+ }
3331
+ async function refreshGroupDirLock(fs, lockPath, groupPath, tmpPath, dirStats, groupRec) {
3332
+ if (!matchesGroupRecord(dirStats, groupRec)) return false;
3333
+ const targetMs = backdatedLockMtimeMs();
3334
+ const targetNs = BigInt(targetMs) * 1000000n;
3335
+ if (targetNs <= dirStats.mtimeNs) return true;
3336
+ await writeGroupRecordAtomic(groupPath, tmpPath, {
3337
+ generation: groupRec.generation,
3338
+ mtimeNs: String(dirStats.mtimeNs),
3339
+ nextMtimeNs: String(targetNs)
3340
+ });
3341
+ try {
3342
+ await utimesDirectory(fs, lockPath, targetMs);
3343
+ } catch (error) {
3344
+ if (error.code === "ENOENT") return false;
3345
+ throw error;
3346
+ }
3347
+ const updated = await statBigInt(fs, lockPath);
3348
+ if (updated === void 0 || fileGenerationOf(updated) !== groupRec.generation) return false;
3349
+ await writeGroupRecordAtomic(groupPath, tmpPath, {
3350
+ generation: groupRec.generation,
3351
+ mtimeNs: String(updated.mtimeNs)
3352
+ });
3353
+ return true;
3354
+ }
3355
+ async function clearUnreleasedGroupLock(native, fs, lockPath, dirStats, signal) {
3356
+ const groupPath = groupRecordPath(lockPath);
3357
+ const deadPath = deadDirPath(lockPath);
3358
+ const groupRec = await readGroupRecord(groupPath);
3359
+ const isOurs = groupRec !== void 0 && matchesGroupRecord(dirStats, groupRec);
3360
+ const ageMs = ageMsOf(dirStats);
3361
+ if (isOurs && ageMs < GROUP_LOCK_FRESH_MS) {
3362
+ try {
3363
+ await removeDirectory(fs, lockPath);
3364
+ } catch (error) {
3365
+ if (isTransientDirectoryError(error)) return false;
3366
+ throw error;
3367
+ }
3368
+ await clearGroupRecord(groupPath);
3369
+ return true;
3370
+ }
3371
+ if (!isOurs && ageMs <= LEGACY_LOCK_STALE_MS) return false;
3372
+ const judgedGeneration = fileGenerationOf(dirStats);
3373
+ const judgedMtimeNs = dirStats.mtimeNs;
3374
+ try {
3375
+ await rename(lockPath, deadPath);
3376
+ } catch (error) {
3377
+ if (error.code === "ENOENT") return true;
3378
+ if (isTransientDirectoryError(error)) return false;
3379
+ throw error;
3380
+ }
3381
+ const movedStats = await statBigInt(fs, deadPath);
3382
+ if (movedStats === void 0) return true;
3383
+ if (fileGenerationOf(movedStats) === judgedGeneration && movedStats.mtimeNs === judgedMtimeNs) {
3384
+ await removeDirectoryWithBackoff(fs, deadPath);
3385
+ if (isOurs) await clearGroupRecord(groupPath);
3386
+ return true;
3387
+ }
3388
+ await renameNoReplaceWithBackoff(native, deadPath, lockPath, signal).catch(() => false);
3389
+ return false;
3390
+ }
3391
+ async function acquireSessionGroupLock(native, directory, options) {
3392
+ const lockPath = join$1(directory, ".session.lock");
3393
+ const gatePath = gateLockPath(lockPath);
3394
+ const membersPath = membersLockPath(lockPath);
3395
+ const groupPath = groupRecordPath(lockPath);
3396
+ const groupTmpPath = groupRecordTmpPath(lockPath);
3397
+ const stagingPath = stagingDirPath(lockPath);
3398
+ const deadPath = deadDirPath(lockPath);
3399
+ const fs = defaultDirectoryFs(options.lockFs);
3400
+ const { signal, onCompromised } = options;
3401
+ let membersSh;
3402
+ let knownRecord;
3403
+ for (;;) {
3404
+ signal?.throwIfAborted();
3405
+ let gate = await acquireAdvisoryExclusive(native, gatePath, signal);
3406
+ let membersEx = null;
3407
+ let retryAfterDelay = false;
3408
+ try {
3409
+ membersEx = await tryAdvisoryExclusiveZero(native, membersPath, signal);
3410
+ if (membersEx === null) {
3411
+ const dirStats = await statBigInt(fs, lockPath);
3412
+ if (dirStats !== void 0) {
3413
+ const cached = lastSeenGroupRecords.get(lockPath);
3414
+ let groupRec = cached !== void 0 && matchesGroupRecord(dirStats, cached) ? cached : void 0;
3415
+ if (groupRec === void 0) {
3416
+ groupRec = await readGroupRecord(groupPath);
3417
+ if (groupRec !== void 0) rememberGroupRecord(lockPath, groupRec);
3418
+ }
3419
+ if (groupRec !== void 0 && matchesGroupRecord(dirStats, groupRec)) {
3420
+ const ageMs = ageMsOf(dirStats);
3421
+ if (ageMs < GROUP_LOCK_FRESH_MS) {
3422
+ let fresh = true;
3423
+ if (ageMs >= GROUP_LOCK_REFRESH_ON_JOIN_MS) {
3424
+ fresh = await refreshGroupDirLock(fs, lockPath, groupPath, groupTmpPath, dirStats, groupRec);
3425
+ knownRecord = void 0;
3426
+ lastSeenGroupRecords.delete(lockPath);
3427
+ } else knownRecord = groupRec;
3428
+ if (fresh) {
3429
+ membersSh = await acquireAdvisoryShared(native, membersPath, signal);
3430
+ gate.release();
3431
+ gate = null;
3432
+ break;
3433
+ }
3434
+ }
3435
+ }
3436
+ }
3437
+ retryAfterDelay = true;
3438
+ } else {
3439
+ let [deadStats, dirStats] = await Promise.all([statBigInt(fs, deadPath), statBigInt(fs, lockPath)]);
3440
+ if (deadStats !== void 0) {
3441
+ const groupRec = await readGroupRecord(groupPath);
3442
+ const deadMatchesGroup = groupRec !== void 0 && matchesGroupRecord(deadStats, groupRec);
3443
+ if (deadMatchesGroup || ageMsOf(deadStats) > LEGACY_LOCK_STALE_MS) {
3444
+ await removeDirectoryWithBackoff(fs, deadPath);
3445
+ if (deadMatchesGroup) await clearGroupRecord(groupPath);
3446
+ } else await renameNoReplaceWithBackoff(native, deadPath, lockPath, signal).catch(() => false);
3447
+ dirStats = await statBigInt(fs, lockPath);
3448
+ }
3449
+ if (dirStats !== void 0) {
3450
+ if (await statBigInt(fs, stagingPath) !== void 0) {
3451
+ await clearGroupRecord(groupPath);
3452
+ await removeDirectoryWithBackoff(fs, stagingPath);
3453
+ dirStats = await statBigInt(fs, lockPath);
3454
+ }
3455
+ }
3456
+ if (dirStats !== void 0) {
3457
+ if (!await clearUnreleasedGroupLock(native, fs, lockPath, dirStats, signal)) retryAfterDelay = true;
3458
+ }
3459
+ if (!retryAfterDelay) {
3460
+ for (;;) try {
3461
+ await mkdirWithWindowsBackoff(fs, stagingPath, signal);
3462
+ break;
3463
+ } catch (error) {
3464
+ if (error.code === "EEXIST") {
3465
+ await clearGroupRecord(groupPath);
3466
+ await removeDirectoryWithBackoff(fs, stagingPath);
3467
+ continue;
3468
+ }
3469
+ throw error;
3470
+ }
3471
+ let placed = false;
3472
+ try {
3473
+ for (;;) {
3474
+ await utimesDirectory(fs, stagingPath, backdatedLockMtimeMs());
3475
+ const stagedStats = await statBigInt(fs, stagingPath);
3476
+ if (stagedStats === void 0) throw Object.assign(/* @__PURE__ */ new Error(`Missing staged lock directory ${stagingPath}`), { code: "ENOENT" });
3477
+ const record = {
3478
+ generation: fileGenerationOf(stagedStats),
3479
+ mtimeNs: String(stagedStats.mtimeNs)
3480
+ };
3481
+ await writeGroupRecord(groupPath, record);
3482
+ knownRecord = record;
3483
+ rememberGroupRecord(lockPath, record);
3484
+ if (ageMsOf(stagedStats) >= GROUP_LOCK_PLACE_MAX_AGE_MS) continue;
3485
+ break;
3486
+ }
3487
+ placed = await renameNoReplaceWithBackoff(native, stagingPath, lockPath, signal);
3488
+ } catch (error) {
3489
+ await clearGroupRecord(groupPath).catch(() => void 0);
3490
+ await removeDirectoryWithBackoff(fs, stagingPath).catch(() => void 0);
3491
+ throw error;
3492
+ }
3493
+ if (!placed) {
3494
+ await clearGroupRecord(groupPath);
3495
+ await removeDirectoryWithBackoff(fs, stagingPath);
3496
+ retryAfterDelay = true;
3497
+ } else {
3498
+ membersEx.release();
3499
+ membersEx = null;
3500
+ membersSh = await acquireAdvisoryShared(native, membersPath, signal);
3501
+ gate.release();
3502
+ gate = null;
3503
+ break;
3504
+ }
3505
+ }
3506
+ }
3507
+ } finally {
3508
+ membersEx?.release();
3509
+ gate?.release();
3510
+ }
3511
+ if (retryAfterDelay) {
3512
+ signal?.throwIfAborted();
3513
+ await setTimeout$1(LEGACY_POLL_MS);
3514
+ }
3515
+ }
3516
+ const heldShared = membersSh;
3517
+ let heartbeatStopped = false;
3518
+ let heartbeatInFlight;
3519
+ let heartbeatTimer;
3520
+ const scheduleHeartbeat = () => {
3521
+ if (heartbeatStopped) return;
3522
+ heartbeatTimer = setTimeout(() => {
3523
+ heartbeatTimer = void 0;
3524
+ if (heartbeatStopped) return;
3525
+ heartbeatInFlight = runHeartbeat().catch(() => void 0).finally(() => {
3526
+ heartbeatInFlight = void 0;
3527
+ scheduleHeartbeat();
3528
+ });
3529
+ }, GROUP_LOCK_HEARTBEAT_MS);
3530
+ heartbeatTimer.unref();
3531
+ };
3532
+ const runHeartbeat = async () => {
3533
+ const gate = await tryAdvisoryExclusiveZero(native, gatePath).catch(() => null);
3534
+ if (gate === null) return;
3535
+ try {
3536
+ if (heartbeatStopped) return;
3537
+ const [dirStats, groupRec] = await Promise.all([statBigInt(fs, lockPath), readGroupRecord(groupPath)]);
3538
+ if (dirStats === void 0 || groupRec === void 0 || !matchesGroupRecord(dirStats, groupRec)) {
3539
+ onCompromised(Object.assign(/* @__PURE__ */ new Error("Session lock directory was removed or replaced while held"), { code: "ECOMPROMISED" }));
3540
+ heartbeatStopped = true;
3541
+ return;
3542
+ }
3543
+ if (!await refreshGroupDirLock(fs, lockPath, groupPath, groupTmpPath, dirStats, groupRec)) {
3544
+ onCompromised(Object.assign(/* @__PURE__ */ new Error("Session lock directory could not be refreshed"), { code: "ECOMPROMISED" }));
3545
+ heartbeatStopped = true;
3546
+ }
3547
+ } finally {
3548
+ gate.release();
3549
+ }
3550
+ };
3551
+ scheduleHeartbeat();
3552
+ let released = false;
3553
+ return {
3554
+ lockPath,
3555
+ release: async () => {
3556
+ if (released) return;
3557
+ released = true;
3558
+ heartbeatStopped = true;
3559
+ if (heartbeatTimer !== void 0) {
3560
+ clearTimeout(heartbeatTimer);
3561
+ heartbeatTimer = void 0;
3562
+ }
3563
+ await heartbeatInFlight;
3564
+ heldShared.release();
3565
+ const gate = await acquireAdvisoryExclusive(native, gatePath);
3566
+ try {
3567
+ const membersEx = await tryAdvisoryExclusiveZero(native, membersPath);
3568
+ if (membersEx === null) return;
3569
+ try {
3570
+ const dirStats = await statBigInt(fs, lockPath);
3571
+ if (dirStats !== void 0) {
3572
+ let isOurs = knownRecord !== void 0 && matchesGroupRecord(dirStats, knownRecord);
3573
+ if (!isOurs) {
3574
+ const groupRec = await readGroupRecord(groupPath);
3575
+ isOurs = groupRec !== void 0 && matchesGroupRecord(dirStats, groupRec);
3576
+ }
3577
+ if (isOurs) {
3578
+ if (await removeDirectoryWithBackoff(fs, lockPath)) {
3579
+ lastSeenGroupRecords.delete(lockPath);
3580
+ await clearGroupRecord(groupPath);
3581
+ }
3582
+ }
3583
+ }
3584
+ } finally {
3585
+ membersEx.release();
3586
+ }
3587
+ } finally {
3588
+ gate.release();
3589
+ }
3590
+ }
3591
+ };
3592
+ }
3593
+ async function acquireFineSessionLocks(native, lockPath, scope, signal) {
3594
+ let needCreate = false;
3595
+ let stripeIndices;
3596
+ switch (scope.kind) {
3597
+ case "full":
3598
+ needCreate = true;
3599
+ stripeIndices = ALL_STRIPE_INDICES;
3600
+ break;
3601
+ case "list":
3602
+ needCreate = true;
3603
+ stripeIndices = [];
3604
+ break;
3605
+ case "create":
3606
+ needCreate = true;
3607
+ stripeIndices = [sessionLockStripe(basename$1(scope.path))];
3608
+ break;
3609
+ case "files":
3610
+ needCreate = false;
3611
+ stripeIndices = sortedStripesForPaths(scope.paths);
3612
+ break;
3613
+ case "stripes":
3614
+ needCreate = scope.create;
3615
+ stripeIndices = [...new Set(scope.stripes)].sort((a, b) => a - b);
3616
+ }
3617
+ const held = [];
3618
+ try {
3619
+ if (needCreate) held.push(await acquireAdvisoryExclusive(native, createLockPath(lockPath), signal));
3620
+ for (const stripe of stripeIndices) held.push(await acquireAdvisoryExclusive(native, stripeLockPath(lockPath, stripe), signal));
3621
+ } catch (error) {
3622
+ for (let index = held.length - 1; index >= 0; index--) held[index].release();
3623
+ throw error;
3624
+ }
3625
+ const stripes = new Set(stripeIndices);
3626
+ let released = false;
3627
+ return {
3628
+ stripes,
3629
+ release: () => {
3630
+ if (released) return;
3631
+ released = true;
3632
+ for (let index = held.length - 1; index >= 0; index--) held[index].release();
3633
+ }
3634
+ };
3635
+ }
2964
3636
  // dist/core/storage/session/legacy-format.js
2965
3637
  function isEarlyFormat4Header(stored) {
2966
3638
  return stored.version === 4 && typeof stored.createdAt !== "string" && typeof stored.timestamp === "string";
@@ -3082,6 +3754,8 @@ const KEEP_APPEND_FILES = process.platform !== "win32";
3082
3754
  const KEPT_FILE_IDLE_MS = 3e4;
3083
3755
  /** The most handles one store keeps open; the least recently used is closed first. */
3084
3756
  const KEPT_FILES = 16;
3757
+ /** The most session files a multi-session append group syncs in parallel, keeping open handles well below OS limits. */
3758
+ const MAX_PARALLEL_SYNCS = 32;
3085
3759
  function isForkCatalogType(type) {
3086
3760
  return type === "session_info" || type === "session_summary" || type === "branch_summary";
3087
3761
  }
@@ -3114,12 +3788,32 @@ function appendedForkIndex(cached, entries) {
3114
3788
  catalog: catalog ?? previous.catalog
3115
3789
  } : previous;
3116
3790
  }
3117
- const JSONL_INDEX_VERSION = 2;
3791
+ /** The sidecar version an older build reads, whose epochs all hold the file's creation time. */
3792
+ const BIRTHTIME_INDEX_VERSION = 2;
3793
+ /**
3794
+ * The newest sidecar version. A sidecar whose epoch leaves out the creation time is written as version 3, so an older
3795
+ * build, which compares it with an epoch that has one, indexes the file again rather than read it. Both are read.
3796
+ */
3797
+ const JSONL_INDEX_VERSION = 3;
3118
3798
  const SIDECAR_SUFFIX = ".idx";
3119
3799
  const SIDECAR_REFRESH_BYTES = 1048576;
3120
3800
  const INDEX_BATCH_ENTRIES = 512;
3121
3801
  const READ_GAP_BYTES = 65536;
3122
3802
  const SCAN_WINDOW_BYTES$1 = 1048576;
3803
+ /** Files up to this size carry a full prefix SHA-256 in `.idx`, checked in one read on cold sidecar load. */
3804
+ const PREFIX_HASH_MAX_BYTES = 262144;
3805
+ /** Each 32-byte straddling checkpoint at `k * 8192` checks the end of page `2k-1` and start of page `2k`. */
3806
+ const CHECKPOINT_INITIAL_STRIDE = 8192;
3807
+ const MAX_CHECKPOINTS = 64;
3808
+ const CHECKPOINT_HALF_BYTES = 16;
3809
+ const HEAD_WITNESS_BYTES = 32;
3810
+ /**
3811
+ * Valid JSONL lines never contain raw NUL bytes (`JSON.stringify` escapes U+0000 and session text forbids it), so one
3812
+ * marks an unwritten zero-filled page left by out-of-order page writeback and power loss.
3813
+ */
3814
+ function hasNulByte(bytes) {
3815
+ return bytes.includes(0);
3816
+ }
3123
3817
  /** The last 64 bytes, which locate the boundary a later append starts from. */
3124
3818
  function witnessOf(bytes) {
3125
3819
  return Buffer.from(bytes.subarray(-64));
@@ -3175,6 +3869,7 @@ async function rangeIndexHolds(file, index, marks, signal) {
3175
3869
  }
3176
3870
  function isBlankLine(line) {
3177
3871
  for (const byte of line) {
3872
+ if (byte === 0) return false;
3178
3873
  if (byte > 32 && byte < 128) return false;
3179
3874
  if (byte >= 128) return line.toString("utf8").trim() === "";
3180
3875
  }
@@ -3212,6 +3907,7 @@ async function scanSessionLines(file, size, atEnd, from, index, signal, visitor)
3212
3907
  let parts = [];
3213
3908
  let partsBytes = 0;
3214
3909
  let completeLineRetained = true;
3910
+ let lineHasNul = false;
3215
3911
  let reader;
3216
3912
  let mode = header ? "header" : "blank";
3217
3913
  const startLine = (offset) => {
@@ -3221,6 +3917,7 @@ async function scanSessionLines(file, size, atEnd, from, index, signal, visitor)
3221
3917
  parts = [];
3222
3918
  partsBytes = 0;
3223
3919
  completeLineRetained = true;
3920
+ lineHasNul = false;
3224
3921
  reader = void 0;
3225
3922
  mode = header ? "header" : "blank";
3226
3923
  };
@@ -3265,6 +3962,7 @@ async function scanSessionLines(file, size, atEnd, from, index, signal, visitor)
3265
3962
  const take = (segment) => {
3266
3963
  lineBytes += segment.length;
3267
3964
  if (linePrefixBytes < linePrefix.length) linePrefixBytes += segment.copy(linePrefix, linePrefixBytes);
3965
+ if (mode !== "header" && !lineHasNul && hasNulByte(segment)) lineHasNul = true;
3268
3966
  if (mode === "header" || mode === "pass") return true;
3269
3967
  keep(segment);
3270
3968
  if (mode === "typing" && reader !== void 0) {
@@ -3292,6 +3990,7 @@ async function scanSessionLines(file, size, atEnd, from, index, signal, visitor)
3292
3990
  header = false;
3293
3991
  return "next";
3294
3992
  }
3993
+ if (lineHasNul) return "stop-nul";
3295
3994
  if (mode === "blank") {
3296
3995
  if (isBlankParts(parts)) return "next";
3297
3996
  if (!classify()) return "stop-before";
@@ -3357,6 +4056,11 @@ async function scanSessionLines(file, size, atEnd, from, index, signal, visitor)
3357
4056
  if (index.completeEnd !== completeEnd) advancedAt = start;
3358
4057
  if (outcome !== "next") {
3359
4058
  keepWitness(bytes, advancedAt);
4059
+ if (outcome === "stop-nul") return {
4060
+ offset: size,
4061
+ seq: mode === "blank" ? seq : seq - 1,
4062
+ header: false
4063
+ };
3360
4064
  return outcome === "stop-before" ? {
3361
4065
  offset: lineOffset,
3362
4066
  seq,
@@ -3387,6 +4091,11 @@ async function scanSessionLines(file, size, atEnd, from, index, signal, visitor)
3387
4091
  header
3388
4092
  };
3389
4093
  const counted = mode !== "blank";
4094
+ if (lineHasNul) return {
4095
+ offset: size,
4096
+ seq: counted ? seq - 1 : seq,
4097
+ header: false
4098
+ };
3390
4099
  if (!atEnd) return {
3391
4100
  offset: lineOffset,
3392
4101
  seq: counted ? seq - 1 : seq,
@@ -3456,6 +4165,7 @@ async function lineStartFromEnd(file, end, count, signal) {
3456
4165
  position -= length;
3457
4166
  for (let at = length - 1; at >= 0; at--) {
3458
4167
  const byte = bytes[at];
4168
+ if (byte === 0) return void 0;
3459
4169
  if (byte === 10) {
3460
4170
  if (position + at === end - 1) continue;
3461
4171
  if (visible) {
@@ -3484,7 +4194,7 @@ function reportTornLine(path) {
3484
4194
  * the scan, which then resolves undefined. A line longer than one scan window is projected as it is read, never held
3485
4195
  * or decoded whole unless it is malformed, so that the parser's own diagnostic is reported.
3486
4196
  */
3487
- async function scanEntries(path, file, from, end, header, take, legacy) {
4197
+ async function scanEntries(path, file, from, end, header, take, legacy, reportTorn = true) {
3488
4198
  let invalidStructure;
3489
4199
  let invalidText;
3490
4200
  let stopped = false;
@@ -3526,9 +4236,13 @@ async function scanEntries(path, file, from, end, header, take, legacy) {
3526
4236
  let parts = [];
3527
4237
  let lineStart = from;
3528
4238
  let position = from;
4239
+ let lineHasNul = false;
4240
+ let nulTailAt;
3529
4241
  let projector;
3530
4242
  const add = (part, stop) => {
3531
4243
  if (header) return;
4244
+ if (!lineHasNul && hasNulByte(part)) lineHasNul = true;
4245
+ if (lineHasNul) return;
3532
4246
  if (projector) projector.feed(part);
3533
4247
  else if (stop - lineStart > SCAN_WINDOW_BYTES$1) {
3534
4248
  projector = entryProjector();
@@ -3570,7 +4284,10 @@ async function scanEntries(path, file, from, end, header, take, legacy) {
3570
4284
  const stop = position + newline;
3571
4285
  add(chunk.subarray(at, newline), stop);
3572
4286
  if (header) header = false;
3573
- else if (projector) await longLine(projector.finish(), stop, true);
4287
+ else if (lineHasNul) {
4288
+ nulTailAt = lineStart;
4289
+ break;
4290
+ } else if (projector) await longLine(projector.finish(), stop, true);
3574
4291
  else {
3575
4292
  const short = shortLine(stop, true);
3576
4293
  if (short !== true) await short;
@@ -3578,20 +4295,35 @@ async function scanEntries(path, file, from, end, header, take, legacy) {
3578
4295
  if (stopped) return void 0;
3579
4296
  at = newline + 1;
3580
4297
  lineStart = position + at;
4298
+ lineHasNul = false;
3581
4299
  parts = [];
3582
4300
  projector = void 0;
3583
4301
  }
4302
+ if (nulTailAt !== void 0) break;
3584
4303
  if (at < chunk.length) add(chunk.subarray(at), position + chunk.length);
3585
4304
  position += chunk.length;
3586
4305
  }
3587
4306
  } finally {
3588
4307
  await next?.catch(() => void 0);
3589
4308
  }
4309
+ if (nulTailAt !== void 0) {
4310
+ await settle();
4311
+ if (stopped) return void 0;
4312
+ if (reportTorn) reportTornLine(path);
4313
+ if (invalidStructure) throw invalidStructure.error;
4314
+ if (invalidText) throw invalidText.error;
4315
+ return {
4316
+ size: nulTailAt,
4317
+ terminated: true,
4318
+ torn: true
4319
+ };
4320
+ }
4321
+ if (end !== void 0 && position < end) throw new Error(`Session file ended before byte ${end}`);
3590
4322
  const terminated = lineStart === position;
3591
- const torn = !terminated && !header && !(projector ? await longLine(projector.finish(), position, false) : await shortLine(position, false));
4323
+ const torn = !terminated && !header && (lineHasNul || !(projector ? await longLine(projector.finish(), position, false) : await shortLine(position, false)));
3592
4324
  await settle();
3593
4325
  if (stopped) return void 0;
3594
- if (torn) reportTornLine(path);
4326
+ if (torn && reportTorn) reportTornLine(path);
3595
4327
  if (invalidStructure) throw invalidStructure.error;
3596
4328
  if (invalidText) throw invalidText.error;
3597
4329
  return {
@@ -3644,23 +4376,6 @@ var JsonlStoragePoisonedError = class extends Error {
3644
4376
  this.rollbackCause = rollbackCause;
3645
4377
  }
3646
4378
  };
3647
- /** Removing a lock directory fails with these on Windows while another handle, such as a scanner or indexer, holds it. */
3648
- const TRANSIENT_RELEASE_CODES = /* @__PURE__ */ new Set([
3649
- "EPERM",
3650
- "EBUSY",
3651
- "EACCES",
3652
- "ENOTEMPTY"
3653
- ]);
3654
- /** Waits between attempts to take or remove the lock directory, about 1.5 s in all, far inside the lock's 10 s stale window. */
3655
- const LOCK_BACKOFF_MS = [
3656
- 10,
3657
- 20,
3658
- 50,
3659
- 100,
3660
- 200,
3661
- 400,
3662
- 700
3663
- ];
3664
4379
  /** The name a session's file is created with: its creation time, then its id or the key of its id. */
3665
4380
  const SESSION_FILE_NAME = /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(?:-\d+)?Z_(.+)\.jsonl$/;
3666
4381
  /** Internal exact-file input for a fork, not a way to open a live or writable session by ID. */
@@ -3679,7 +4394,10 @@ var JsonlSessionStore = class JsonlSessionStore {
3679
4394
  /** Operations queued so far, counted so an append joins only a group that is still the last thing queued. */
3680
4395
  queued = 0;
3681
4396
  appendGroup;
4397
+ chatAppendGroup;
3682
4398
  keptFiles = /* @__PURE__ */ new Map();
4399
+ /** Paths whose kept handles are currently in use by an in-flight write or sync, so LRU eviction skips them. */
4400
+ pinnedKeptFiles = /* @__PURE__ */ new Set();
3683
4401
  closed = false;
3684
4402
  poisoned;
3685
4403
  directory;
@@ -3689,25 +4407,95 @@ var JsonlSessionStore = class JsonlSessionStore {
3689
4407
  has: hasFileChatRecords,
3690
4408
  read: readFileChatRecords,
3691
4409
  readOrders: readFileChatOrders,
3692
- append: (owner, anchor, record) => {
3693
- record = boundedChatRecord(record);
3694
- return this.run(async () => {
3695
- const held = await this.locate(owner.id);
3696
- if (held && held.stats.birthtimeNs > 0n && held.path === owner.file && epochOf(held.stats, JSON.stringify(held.header)) === owner.epoch) await appendFileChatRecord(owner, anchor, record);
3697
- });
3698
- }
4410
+ append: (owner, anchor, record) => this.appendChatRecord(owner, anchor, boundedChatRecord(record))
3699
4411
  };
3700
4412
  return this.chatStore;
3701
4413
  }
4414
+ appendChatRecord(owner, anchor, record) {
4415
+ if (this.closed) return Promise.reject(new StoreClosedError$1(this.descriptor));
4416
+ return new Promise((resolve, reject) => {
4417
+ const request = {
4418
+ owner,
4419
+ anchor,
4420
+ record,
4421
+ resolve,
4422
+ reject
4423
+ };
4424
+ const waiting = this.chatAppendGroup;
4425
+ if (waiting !== void 0 && !waiting.started && waiting.queued === this.queued) {
4426
+ waiting.requests.push(request);
4427
+ return;
4428
+ }
4429
+ const group = {
4430
+ requests: [request],
4431
+ queued: 0,
4432
+ started: false
4433
+ };
4434
+ this.chatAppendGroup = group;
4435
+ const settle = (fallback) => {
4436
+ for (const pending of group.requests) if (pending.answer !== void 0 && "ok" in pending.answer) pending.resolve();
4437
+ else pending.reject(pending.answer !== void 0 ? pending.answer.error : fallback);
4438
+ };
4439
+ this.run(() => this.commitChatAppends(group), {
4440
+ kind: "sessions",
4441
+ sessionIds: () => group.requests.map((pending) => pending.owner.id)
4442
+ }).then(() => settle(), (cause) => settle(cause));
4443
+ group.queued = this.queued;
4444
+ });
4445
+ }
4446
+ async commitChatAppends(group) {
4447
+ group.started = true;
4448
+ if (this.chatAppendGroup === group) this.chatAppendGroup = void 0;
4449
+ for (const request of group.requests) request.answer = void 0;
4450
+ const byOwner = /* @__PURE__ */ new Map();
4451
+ for (const request of group.requests) {
4452
+ const key = `${request.owner.id}\0${request.owner.file ?? ""}\0${request.owner.epoch}`;
4453
+ let bucket = byOwner.get(key);
4454
+ if (!bucket) {
4455
+ bucket = {
4456
+ owner: request.owner,
4457
+ requests: []
4458
+ };
4459
+ byOwner.set(key, bucket);
4460
+ }
4461
+ bucket.requests.push(request);
4462
+ }
4463
+ const located = [];
4464
+ for (const { owner, requests } of byOwner.values()) try {
4465
+ const held = await this.locate(owner.id);
4466
+ const writable = held !== void 0 && held.stats.birthtimeNs > 0n && held.path === owner.file && fileEpochOf(held.stats, JSON.stringify(held.header)) === owner.epoch;
4467
+ located.push({
4468
+ owner,
4469
+ requests,
4470
+ writable
4471
+ });
4472
+ } catch (cause) {
4473
+ if (cause instanceof RelockRequiredError) throw cause;
4474
+ const failure = this.failure(cause);
4475
+ for (const request of requests) request.answer = { error: failure };
4476
+ }
4477
+ for (const { owner, requests, writable } of located) try {
4478
+ if (writable) await appendFileChatRecords(owner, requests.map(({ anchor, record }) => ({
4479
+ anchor,
4480
+ record
4481
+ })));
4482
+ for (const request of requests) request.answer = { ok: true };
4483
+ } catch (cause) {
4484
+ const failure = this.failure(cause);
4485
+ for (const request of requests) request.answer = { error: failure };
4486
+ }
4487
+ }
3702
4488
  fileStates = /* @__PURE__ */ new Map();
3703
4489
  rangeIndexes = /* @__PURE__ */ new Map();
3704
4490
  indexes = /* @__PURE__ */ new Map();
3705
4491
  exactDirectory;
3706
4492
  lockFs;
4493
+ /** Stripes currently held by this store's active locked operation in `heldLockDirectory`, if narrowed. */
4494
+ heldStripes;
4495
+ heldLockDirectory;
3707
4496
  /**
3708
- * Lock directories this store acquired and could not remove, by path, with the modification time they had
3709
- * then. Nothing refreshes them any more, so another process may take them only once they are stale; until
3710
- * then the store removes its own, recognised by that time, rather than waiting out the stale window.
4497
+ * Lock directories this store acquired and could not remove (fallback path when native advisory locks are
4498
+ * unavailable), by path, with the modification time they had then.
3711
4499
  */
3712
4500
  unreleased = /* @__PURE__ */ new Map();
3713
4501
  constructor(directory, exactDirectory, lockFs) {
@@ -3729,6 +4517,7 @@ var JsonlSessionStore = class JsonlSessionStore {
3729
4517
  const create = options?.createDirectory !== false;
3730
4518
  if (options?.scanExisting === false) {
3731
4519
  if (create) await store.run(() => mkdir(store.directory, { recursive: true }).then(() => {}), false);
4520
+ await learnCreationTime(store.directory);
3732
4521
  return store;
3733
4522
  }
3734
4523
  const paths = await store.run(async () => {
@@ -3740,6 +4529,7 @@ var JsonlSessionStore = class JsonlSessionStore {
3740
4529
  return [];
3741
4530
  }
3742
4531
  }, false);
4532
+ await learnCreationTime(store.directory);
3743
4533
  const unread = await store.run(async () => {
3744
4534
  const changed = /* @__PURE__ */ new Set();
3745
4535
  const all = paths ?? [];
@@ -3774,6 +4564,9 @@ var JsonlSessionStore = class JsonlSessionStore {
3774
4564
  store.fileStates.delete(path);
3775
4565
  store.fileStates.set(path, state);
3776
4566
  }
4567
+ }, paths === void 0 ? true : {
4568
+ kind: "files",
4569
+ paths: [...unread]
3777
4570
  });
3778
4571
  return store;
3779
4572
  }
@@ -3795,10 +4588,10 @@ var JsonlSessionStore = class JsonlSessionStore {
3795
4588
  if (await this.claimed(header.id)) throw new SessionExistsError(header.id);
3796
4589
  const payload = Buffer.from(this.encode(header, entries));
3797
4590
  const path = location === void 0 ? this.locationFor(header) : resolve$1(location);
3798
- await mkdir(resolve$1(path, ".."), { recursive: true });
4591
+ await makeDirectory(dirname$1(path));
3799
4592
  const temporary = `${path}.${randomUUID()}.tmp`;
3800
4593
  try {
3801
- await writeFile(temporary, payload, { flag: "wx" });
4594
+ await writeSynced(temporary, payload);
3802
4595
  try {
3803
4596
  await link(temporary, path);
3804
4597
  } catch (cause) {
@@ -3810,6 +4603,7 @@ var JsonlSessionStore = class JsonlSessionStore {
3810
4603
  if (cause.code !== "ENOENT") throw cause;
3811
4604
  });
3812
4605
  }
4606
+ await syncDirectory(dirname$1(path));
3813
4607
  const state = this.contentState(header, entries, payload);
3814
4608
  const stats = await this.remember(path, state);
3815
4609
  if (this.selectedFile?.id === header.id) this.selectedFile = {
@@ -3818,16 +4612,25 @@ var JsonlSessionStore = class JsonlSessionStore {
3818
4612
  };
3819
4613
  return {
3820
4614
  lastSeq: entries.length,
3821
- epoch: epochOf(stats, state.headerStamp)
4615
+ epoch: fileEpochOf(stats, state.headerStamp)
3822
4616
  };
3823
- }, true);
4617
+ }, () => {
4618
+ try {
4619
+ return {
4620
+ kind: "create",
4621
+ path: location === void 0 ? this.locationFor(header) : resolve$1(location)
4622
+ };
4623
+ } catch {
4624
+ return { kind: "list" };
4625
+ }
4626
+ });
3824
4627
  }
3825
4628
  async createFork(header, entries, source, location) {
3826
4629
  if (this.create !== JsonlSessionStore.prototype.create) return void 0;
3827
4630
  validateSessionHeader(header);
3828
4631
  if (!("read" in entries)) validateSessionEntries(entries);
3829
4632
  const path = location === void 0 ? this.locationFor(header) : resolve$1(location);
3830
- await mkdir(dirname$1(path), { recursive: true });
4633
+ await makeDirectory(dirname$1(path));
3831
4634
  const temporary = `${path}.${randomUUID()}.tmp`;
3832
4635
  const handle = await open(temporary, "wx+");
3833
4636
  try {
@@ -3865,7 +4668,7 @@ var JsonlSessionStore = class JsonlSessionStore {
3865
4668
  }));
3866
4669
  const line = this.encode(header, []);
3867
4670
  let size = Buffer.byteLength(line);
3868
- let witness;
4671
+ let integrity;
3869
4672
  try {
3870
4673
  await write(Buffer.from(line));
3871
4674
  for await (const row of rows) {
@@ -3886,7 +4689,8 @@ var JsonlSessionStore = class JsonlSessionStore {
3886
4689
  size++;
3887
4690
  }
3888
4691
  await flush();
3889
- witness = await witnessAt(handle, size);
4692
+ await syncFile(handle);
4693
+ integrity = await captureIntegrity(handle, size, spans);
3890
4694
  } finally {
3891
4695
  await handle.close();
3892
4696
  }
@@ -3898,6 +4702,10 @@ var JsonlSessionStore = class JsonlSessionStore {
3898
4702
  if (cause.code === "EEXIST") throw new SessionExistsError(header.id);
3899
4703
  throw cause;
3900
4704
  }
4705
+ await unlink(temporary).catch((cause) => {
4706
+ if (cause.code !== "ENOENT") throw cause;
4707
+ });
4708
+ await syncDirectory(dirname$1(path));
3901
4709
  const headerStamp = JSON.stringify(header);
3902
4710
  const stats = await this.remember(path, {
3903
4711
  headerStamp,
@@ -3906,10 +4714,10 @@ var JsonlSessionStore = class JsonlSessionStore {
3906
4714
  lastEntryId: lastId,
3907
4715
  terminated: true,
3908
4716
  torn: false,
3909
- witness,
4717
+ witness: integrity.witness,
3910
4718
  summaryState: summary
3911
4719
  });
3912
- const epoch = epochOf(stats, headerStamp);
4720
+ const epoch = fileEpochOf(stats, headerStamp);
3913
4721
  await this.keepIndex(path, {
3914
4722
  identity: `${stats.dev}:${stats.ino}`,
3915
4723
  birthtimeNs: String(stats.birthtimeNs),
@@ -3917,7 +4725,8 @@ var JsonlSessionStore = class JsonlSessionStore {
3917
4725
  fileSize: size,
3918
4726
  mtimeNs: String(stats.mtimeNs),
3919
4727
  size,
3920
- witness,
4728
+ ...integrity,
4729
+ synced: true,
3921
4730
  terminated: true,
3922
4731
  torn: false,
3923
4732
  spans,
@@ -3927,12 +4736,15 @@ var JsonlSessionStore = class JsonlSessionStore {
3927
4736
  epoch
3928
4737
  },
3929
4738
  sidecarSize: 0
3930
- });
4739
+ }, { synced: true });
3931
4740
  return {
3932
4741
  lastSeq: ids.length,
3933
4742
  epoch
3934
4743
  };
3935
- }, true);
4744
+ }, {
4745
+ kind: "create",
4746
+ path
4747
+ });
3936
4748
  } finally {
3937
4749
  await unlink(temporary).catch((cause) => {
3938
4750
  if (cause.code !== "ENOENT") throw cause;
@@ -3942,8 +4754,10 @@ var JsonlSessionStore = class JsonlSessionStore {
3942
4754
  /**
3943
4755
  * Appends made while an earlier one waits its turn join it and commit together, as a LevelDB log writer's queue does:
3944
4756
  * under one lock, each is checked against the session as the appends before it leave it, and each file gets one write
3945
- * of all their lines. Every append is answered once its lines are written and the lock is released, as it was alone,
3946
- * and one that conflicts or fails validation rejects alone. Nothing is synced, as before.
4757
+ * of all their lines and one sync of them, as PostgreSQL's WAL flush covers every commit queued behind it (#6686).
4758
+ * Every append is answered once the sync covering its lines has finished and the lock is released, as it was alone,
4759
+ * and one that conflicts or fails validation rejects alone. The sync is made under the lock, so a failed one is cut
4760
+ * back before any other writer can append after lines a crash may have lost.
3947
4761
  */
3948
4762
  append(sessionId, entries, options) {
3949
4763
  if (this.closed) return Promise.reject(new StoreClosedError$1(this.descriptor));
@@ -3966,26 +4780,59 @@ var JsonlSessionStore = class JsonlSessionStore {
3966
4780
  started: false
3967
4781
  };
3968
4782
  this.appendGroup = group;
3969
- this.run(() => this.commitAppends(group)).then(() => {
4783
+ const settle = (fallback) => {
3970
4784
  for (const { answer, resolve, reject } of group.requests) if (answer !== void 0 && "lastSeq" in answer) resolve(answer);
3971
- else reject(answer?.error);
3972
- }, (cause) => {
3973
- for (const pending of group.requests) pending.reject(cause);
3974
- });
4785
+ else reject(answer !== void 0 ? answer.error : fallback);
4786
+ };
4787
+ this.run(() => this.commitAppends(group), {
4788
+ kind: "sessions",
4789
+ sessionIds: () => group.requests.map((pending) => pending.sessionId),
4790
+ forceFull: () => {
4791
+ return new Set(group.requests.map((pending) => pending.sessionId)).size > 1 && group.requests.some((pending) => pending.entries.some((entry) => entry.type === "compaction"));
4792
+ }
4793
+ }).then(() => settle(), (cause) => settle(cause));
3975
4794
  group.queued = this.queued;
3976
4795
  });
3977
4796
  }
3978
4797
  async commitAppends(group) {
3979
4798
  group.started = true;
3980
4799
  if (this.appendGroup === group) this.appendGroup = void 0;
4800
+ for (const request of group.requests) request.answer = void 0;
3981
4801
  const staged = /* @__PURE__ */ new Map();
3982
- for (const request of group.requests) try {
3983
- await this.stageAppend(staged, request);
3984
- } catch (cause) {
3985
- if (this.poisoned) throw this.poisoned;
3986
- request.answer = { error: this.failure(cause) };
4802
+ for (const request of group.requests) {
4803
+ if (this.poisoned) {
4804
+ request.answer = { error: this.poisoned };
4805
+ continue;
4806
+ }
4807
+ try {
4808
+ await this.stageAppend(staged, request);
4809
+ } catch (cause) {
4810
+ if (cause instanceof RelockRequiredError) throw cause;
4811
+ if (this.poisoned) {
4812
+ request.answer = { error: this.poisoned };
4813
+ break;
4814
+ }
4815
+ request.answer = { error: this.failure(cause) };
4816
+ }
4817
+ }
4818
+ if (this.poisoned) {
4819
+ for (const file of staged.values()) for (const { request } of file.requests) request.answer = { error: this.poisoned };
4820
+ for (const request of group.requests) request.answer ??= { error: this.poisoned };
4821
+ return;
4822
+ }
4823
+ const files = [...staged.values()];
4824
+ if (files.length === 1) await this.writeStaged(files[0]);
4825
+ else if (files.length > 1) {
4826
+ let cursor = 0;
4827
+ const workers = Array.from({ length: Math.min(files.length, MAX_PARALLEL_SYNCS) }, async () => {
4828
+ while (cursor < files.length) {
4829
+ const file = files[cursor++];
4830
+ await this.writeStaged(file);
4831
+ }
4832
+ });
4833
+ await Promise.all(workers);
4834
+ await this.trimKeptFiles();
3987
4835
  }
3988
- for (const file of staged.values()) await this.writeStaged(file);
3989
4836
  }
3990
4837
  /** Checks one append against its session as the appends staged before it leave it, and stages its lines. */
3991
4838
  async stageAppend(staged, request) {
@@ -3997,7 +4844,7 @@ var JsonlSessionStore = class JsonlSessionStore {
3997
4844
  sessionId,
3998
4845
  path,
3999
4846
  identity: state.identity,
4000
- epoch: epochOf(stats, JSON.stringify(header)),
4847
+ epoch: fileEpochOf(stats, JSON.stringify(header)),
4001
4848
  before: state,
4002
4849
  entries: [],
4003
4850
  lines: [],
@@ -4013,6 +4860,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4013
4860
  if (entries.some((entry) => entry.type === "compaction")) {
4014
4861
  if (!await this.writeStaged(file)) {
4015
4862
  staged.delete(sessionId);
4863
+ if (this.poisoned) throw this.poisoned;
4016
4864
  throw new SessionConflictError(sessionId, options.expectSeq, file.before.lastSeq);
4017
4865
  }
4018
4866
  await copyFile(file.path, `${file.path}.${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.${randomUUID()}.compact.bak`);
@@ -4028,30 +4876,38 @@ var JsonlSessionStore = class JsonlSessionStore {
4028
4876
  }
4029
4877
  /**
4030
4878
  * Writes the lines staged for `file` through its kept handle, then decides the appends they came from: false when the
4031
- * write failed and they fail. A failed write is cut off again; when that fails too the store is poisoned.
4879
+ * write failed and they fail. A failed write or sync is cut off again; when that fails too the store is poisoned,
4880
+ * without failing sibling files in the same group that already synced.
4032
4881
  */
4033
4882
  async writeStaged(file) {
4034
4883
  const { path, before, entries, lines, requests } = file;
4035
4884
  file.entries = [];
4036
4885
  file.lines = [];
4037
4886
  file.requests = [];
4887
+ if (this.poisoned) {
4888
+ for (const { request } of requests) request.answer = { error: this.poisoned };
4889
+ return false;
4890
+ }
4038
4891
  if (entries.length === 0) {
4039
4892
  for (const { request, lastSeq } of requests) request.answer = { lastSeq };
4040
4893
  return true;
4041
4894
  }
4042
4895
  const offset = before.size;
4043
4896
  const payload = Buffer.from(`${before.terminated ? "" : "\n"}${lines.join("\n")}\n`);
4897
+ this.pinnedKeptFiles.add(path);
4044
4898
  try {
4045
4899
  const kept = await this.keptFile(path, file.identity);
4046
4900
  if (before.torn) await truncate(path, before.size);
4047
4901
  try {
4048
4902
  await writeAll(kept.handle, payload);
4903
+ await syncFile(kept.handle);
4049
4904
  } catch (cause) {
4050
4905
  try {
4051
4906
  await truncate(path, offset);
4052
4907
  } catch (rollbackCause) {
4053
- this.poisoned = new JsonlStoragePoisonedError(path, cause, rollbackCause);
4054
- throw this.poisoned;
4908
+ const poisoned = new JsonlStoragePoisonedError(path, cause, rollbackCause);
4909
+ this.poisoned ??= poisoned;
4910
+ throw poisoned;
4055
4911
  }
4056
4912
  throw cause;
4057
4913
  }
@@ -4071,15 +4927,16 @@ var JsonlSessionStore = class JsonlSessionStore {
4071
4927
  rangeIndex.seenStamp = this.stamp(stats);
4072
4928
  rangeIndex.seenSize = Number(stats.size);
4073
4929
  }
4074
- await this.indexAppended(path, before, entries, lines, offset + (before.terminated ? 0 : 1), stats);
4930
+ await this.indexAppended(path, before, entries, lines, offset + (before.terminated ? 0 : 1), stats, kept.handle);
4075
4931
  if (KEEP_APPEND_FILES) this.armIdle(path, kept);
4076
4932
  else await this.closeKept(path);
4077
4933
  } catch (cause) {
4078
4934
  await this.closeKept(path);
4079
- const failure = cause === this.poisoned ? cause : this.failure(cause);
4935
+ const failure = cause instanceof JsonlStoragePoisonedError ? cause : this.failure(cause);
4080
4936
  for (const { request } of requests) request.answer = { error: failure };
4081
- if (cause === this.poisoned) throw cause;
4082
4937
  return false;
4938
+ } finally {
4939
+ this.pinnedKeptFiles.delete(path);
4083
4940
  }
4084
4941
  for (const { request, lastSeq } of requests) request.answer = { lastSeq };
4085
4942
  return true;
@@ -4094,6 +4951,9 @@ var JsonlSessionStore = class JsonlSessionStore {
4094
4951
  lastSeq: entries.length,
4095
4952
  epoch: await this.commit(path, header, entries)
4096
4953
  };
4954
+ }, {
4955
+ kind: "sessions",
4956
+ sessionIds: () => [sessionId]
4097
4957
  });
4098
4958
  }
4099
4959
  updateHeader(header, options) {
@@ -4118,12 +4978,14 @@ var JsonlSessionStore = class JsonlSessionStore {
4118
4978
  }
4119
4979
  witness = await witnessAt(output, (await output.stat()).size);
4120
4980
  await output.chmod((await stat(path)).mode & 4095);
4981
+ await syncFile(output);
4121
4982
  } finally {
4122
4983
  await output.close();
4123
4984
  }
4124
4985
  await this.forgetIndex(path);
4125
4986
  await this.closeKept(path);
4126
- await rename(temporary, path);
4987
+ await renameOver(temporary, path);
4988
+ await syncDirectory(dirname$1(path));
4127
4989
  const headerStamp = JSON.stringify(header);
4128
4990
  const stats = await this.remember(path, {
4129
4991
  ...state,
@@ -4134,13 +4996,16 @@ var JsonlSessionStore = class JsonlSessionStore {
4134
4996
  });
4135
4997
  return {
4136
4998
  lastSeq: state.lastSeq,
4137
- epoch: epochOf(stats, headerStamp)
4999
+ epoch: fileEpochOf(stats, headerStamp)
4138
5000
  };
4139
5001
  } finally {
4140
5002
  await unlink(temporary).catch((cause) => {
4141
5003
  if (cause.code !== "ENOENT") throw cause;
4142
5004
  });
4143
5005
  }
5006
+ }, {
5007
+ kind: "sessions",
5008
+ sessionIds: () => [header.id]
4144
5009
  });
4145
5010
  }
4146
5011
  async commit(path, header, entries) {
@@ -4149,22 +5014,49 @@ var JsonlSessionStore = class JsonlSessionStore {
4149
5014
  const payload = Buffer.from(this.encode(header, entries));
4150
5015
  const temporary = `${path}.${randomUUID()}.tmp`;
4151
5016
  try {
4152
- await writeFile(temporary, payload, { flag: "wx" });
4153
- await rename(temporary, path);
5017
+ await writeSynced(temporary, payload);
5018
+ await renameOver(temporary, path);
5019
+ await syncDirectory(dirname$1(path));
4154
5020
  } finally {
4155
5021
  await unlink(temporary).catch((cause) => {
4156
5022
  if (cause.code !== "ENOENT") throw cause;
4157
5023
  });
4158
5024
  }
4159
5025
  const state = this.contentState(header, entries, payload);
4160
- return epochOf(await this.remember(path, state), state.headerStamp);
5026
+ return fileEpochOf(await this.remember(path, state), state.headerStamp);
4161
5027
  }
4162
5028
  load(sessionId) {
4163
- return this.run(async () => {
5029
+ return this.run(() => this.readUnlocked(sessionId, async ({ path, handle, stats, header, firstLine }) => {
5030
+ const { entries, witness, terminated, torn, size } = await this.readEntriesFrom(handle, Number(stats.size), firstLine);
5031
+ validateSessionEntryStructure(entries, path);
5032
+ validateSessionEntries(entries);
5033
+ const headerStamp = JSON.stringify(header);
5034
+ bindChatEpoch(header, fileEpochOf(stats, headerStamp));
5035
+ return {
5036
+ value: {
5037
+ header,
5038
+ entries,
5039
+ lastSeq: entries.length
5040
+ },
5041
+ commit: async () => {
5042
+ if (torn) reportTornLine(path);
5043
+ await this.remember(path, {
5044
+ headerStamp,
5045
+ headerId: header.id,
5046
+ lastSeq: entries.length,
5047
+ lastEntryId: entries.at(-1)?.id,
5048
+ witness,
5049
+ terminated,
5050
+ torn,
5051
+ summaryState: applySessionSummaryEntries(void 0, entries).state
5052
+ }, torn ? size : void 0, stats);
5053
+ }
5054
+ };
5055
+ }, async () => {
4164
5056
  const located = await this.locate(sessionId);
4165
5057
  if (!located) throw new SessionNotFoundError(sessionId);
4166
5058
  return this.readPersisted(located.path, located.stored);
4167
- });
5059
+ }), false);
4168
5060
  }
4169
5061
  readEntryRange(sessionId, query) {
4170
5062
  return this.run(async () => {
@@ -4384,20 +5276,137 @@ var JsonlSessionStore = class JsonlSessionStore {
4384
5276
  };
4385
5277
  }
4386
5278
  loadFile(path) {
4387
- return this.run(() => this.readPersisted(resolve$1(path)));
5279
+ const target = resolve$1(path);
5280
+ return this.run(async () => {
5281
+ const fallback = () => this.exclusive(() => this.readPersisted(target), void 0, this.directory, {
5282
+ kind: "files",
5283
+ paths: [target]
5284
+ });
5285
+ let handle;
5286
+ try {
5287
+ handle = await open(target, "r");
5288
+ } catch {
5289
+ return fallback();
5290
+ }
5291
+ let snapshot;
5292
+ let commit;
5293
+ let caught;
5294
+ let valid = false;
5295
+ let isLegacy = false;
5296
+ try {
5297
+ const stats = await handle.stat({ bigint: true });
5298
+ let firstLine;
5299
+ try {
5300
+ firstLine = await readFirstLineWithTailFrom(handle, HEADER_READ_CHUNK_BYTES, Number(stats.size));
5301
+ } catch (error) {
5302
+ caught = { error };
5303
+ }
5304
+ if (firstLine !== void 0) {
5305
+ if (!isCurrentSessionHeader(firstLine.stored)) isLegacy = true;
5306
+ else try {
5307
+ const header = await this.readHeaderAt(target, firstLine.stored);
5308
+ const { entries, witness, terminated, torn, size } = await this.readEntriesFrom(handle, Number(stats.size), firstLine);
5309
+ validateSessionEntryStructure(entries, target);
5310
+ validateSessionEntries(entries);
5311
+ const headerStamp = JSON.stringify(header);
5312
+ bindChatEpoch(header, fileEpochOf(stats, headerStamp));
5313
+ snapshot = {
5314
+ header,
5315
+ entries,
5316
+ lastSeq: entries.length
5317
+ };
5318
+ commit = async () => {
5319
+ if (torn) reportTornLine(target);
5320
+ await this.remember(target, {
5321
+ headerStamp,
5322
+ headerId: header.id,
5323
+ lastSeq: entries.length,
5324
+ lastEntryId: entries.at(-1)?.id,
5325
+ witness,
5326
+ terminated,
5327
+ torn,
5328
+ summaryState: applySessionSummaryEntries(void 0, entries).state
5329
+ }, torn ? size : void 0, stats);
5330
+ };
5331
+ } catch (error) {
5332
+ caught = { error };
5333
+ }
5334
+ }
5335
+ if (!isLegacy) {
5336
+ const dir = dirname$1(target);
5337
+ if (!await this.isDirectoryLockPresent(dir) && (dir === this.directory || !await this.isDirectoryLockPresent(this.directory))) {
5338
+ const after = await stat(target, { bigint: true }).catch(() => void 0);
5339
+ valid = after !== void 0 && this.stamp(after) === this.stamp(stats);
5340
+ }
5341
+ }
5342
+ } finally {
5343
+ await handle.close();
5344
+ }
5345
+ if (isLegacy || !valid) return fallback();
5346
+ if (caught !== void 0) throw caught.error;
5347
+ await commit();
5348
+ return snapshot;
5349
+ }, false);
4388
5350
  }
4389
5351
  readHeaderFile(path) {
4390
- return this.run(() => this.readHeaderAt(resolve$1(path)));
5352
+ const target = resolve$1(path);
5353
+ return this.run(async () => {
5354
+ const fallback = () => this.exclusive(() => this.readHeaderAt(target), void 0, this.directory, {
5355
+ kind: "files",
5356
+ paths: [target]
5357
+ });
5358
+ let handle;
5359
+ try {
5360
+ handle = await open(target, "r");
5361
+ } catch {
5362
+ return fallback();
5363
+ }
5364
+ let header;
5365
+ let caught;
5366
+ let valid = false;
5367
+ try {
5368
+ const stats = await handle.stat({ bigint: true });
5369
+ try {
5370
+ const stored = await readFirstLineFrom(handle, HEADER_READ_CHUNK_BYTES, 0);
5371
+ header = await this.readHeaderAt(target, stored);
5372
+ } catch (error) {
5373
+ caught = { error };
5374
+ }
5375
+ const dir = dirname$1(target);
5376
+ if (!await this.isDirectoryLockPresent(dir) && (dir === this.directory || !await this.isDirectoryLockPresent(this.directory))) {
5377
+ const after = await stat(target, { bigint: true }).catch(() => void 0);
5378
+ valid = after !== void 0 && this.stamp(after) === this.stamp(stats);
5379
+ }
5380
+ } finally {
5381
+ await handle.close();
5382
+ }
5383
+ if (!valid) return fallback();
5384
+ if (caught !== void 0) throw caught.error;
5385
+ return header;
5386
+ }, false);
4391
5387
  }
4392
5388
  readTail(sessionId, fromSeq) {
4393
- return this.run(async () => {
5389
+ return this.run(() => this.readUnlocked(sessionId, async ({ path, handle, stats, header }) => {
5390
+ const { jsonl, needsPersist } = await this.indexFor(path, header, stats, {
5391
+ handle,
5392
+ persist: false
5393
+ });
5394
+ const start = Math.max(1, fromSeq);
5395
+ const read = await this.entriesAt(path, jsonl, [...stateSeqsBefore(jsonl.index, start), ...seqRange$1(start, jsonl.index.seq)], { handle });
5396
+ const state = read.filter((held) => held.seq < start);
5397
+ const tail = read.filter((held) => held.seq >= start).map((held) => held.entry);
5398
+ return {
5399
+ value: sessionTailFrom(jsonl.index, header, start, state, tail),
5400
+ commit: () => this.commitIndexed(path, header, stats, jsonl, needsPersist)
5401
+ };
5402
+ }, async () => {
4394
5403
  const { path, header, jsonl } = await this.indexed(sessionId);
4395
5404
  const start = Math.max(1, fromSeq);
4396
5405
  const read = await this.entriesAt(path, jsonl, [...stateSeqsBefore(jsonl.index, start), ...seqRange$1(start, jsonl.index.seq)]);
4397
5406
  const state = read.filter((held) => held.seq < start);
4398
5407
  const tail = read.filter((held) => held.seq >= start).map((held) => held.entry);
4399
5408
  return sessionTailFrom(jsonl.index, header, start, state, tail);
4400
- });
5409
+ }), false);
4401
5410
  }
4402
5411
  readChildDisplayCut(sessionId, launch) {
4403
5412
  return this.run(async () => {
@@ -4405,6 +5414,9 @@ var JsonlSessionStore = class JsonlSessionStore {
4405
5414
  const { path, jsonl } = await this.indexed(sessionId);
4406
5415
  const found = typeof launch.launchLeafId === "string" ? await this.seqInFile(path, jsonl, launch.launchLeafId) : void 0;
4407
5416
  return childDisplayCut(jsonl.index, launch, found);
5417
+ }, {
5418
+ kind: "sessions",
5419
+ sessionIds: () => [sessionId]
4408
5420
  });
4409
5421
  }
4410
5422
  /** Bind a short-lived archive reader to this exact file, including for duplicate exported IDs. */
@@ -4423,7 +5435,10 @@ var JsonlSessionStore = class JsonlSessionStore {
4423
5435
  }
4424
5436
  }
4425
5437
  readBranchSpan(sessionId, cut) {
4426
- return this.run(async () => transcriptBranchSpan(sessionId, (await this.indexed(sessionId)).jsonl.index, cut));
5438
+ return this.run(async () => transcriptBranchSpan(sessionId, (await this.indexed(sessionId)).jsonl.index, cut), {
5439
+ kind: "sessions",
5440
+ sessionIds: () => [sessionId]
5441
+ });
4427
5442
  }
4428
5443
  readEntrySizes(sessionId, startSeq, endSeq, limit) {
4429
5444
  return this.run(async () => {
@@ -4438,6 +5453,9 @@ var JsonlSessionStore = class JsonlSessionStore {
4438
5453
  bytes: spanEnd(jsonl, seq) - spanStart(jsonl, seq)
4439
5454
  }))
4440
5455
  };
5456
+ }, {
5457
+ kind: "sessions",
5458
+ sessionIds: () => [sessionId]
4441
5459
  });
4442
5460
  }
4443
5461
  readEntryChunk(reference, offset) {
@@ -4446,10 +5464,32 @@ var JsonlSessionStore = class JsonlSessionStore {
4446
5464
  if (jsonl.index.epoch !== reference.epoch) throw new SessionConflictError(reference.sessionId, reference.seq, jsonl.index.seq);
4447
5465
  const start = spanStart(jsonl, reference.seq) + offset;
4448
5466
  return readBytes(path, start, Math.min(SESSION_HISTORY_CHUNK_BYTES, spanEnd(jsonl, reference.seq) - start), this.keptFor(path, jsonl.identity));
5467
+ }, {
5468
+ kind: "sessions",
5469
+ sessionIds: () => [reference.sessionId]
4449
5470
  });
4450
5471
  }
4451
5472
  readRange(sessionId, startSeq, endSeq, expectedEpoch) {
4452
- return this.run(async () => {
5473
+ return this.run(() => this.readUnlocked(sessionId, async ({ path, handle, stats, header }) => {
5474
+ const { jsonl, needsPersist } = await this.indexFor(path, header, stats, {
5475
+ handle,
5476
+ persist: false
5477
+ });
5478
+ if (expectedEpoch !== void 0 && expectedEpoch !== jsonl.index.epoch) throw new SessionConflictError(sessionId, endSeq, jsonl.index.seq);
5479
+ const start = Math.max(1, startSeq);
5480
+ const seqs = seqRange$1(start, Math.min(endSeq, jsonl.index.seq));
5481
+ return {
5482
+ value: {
5483
+ startSeq: start,
5484
+ entries: (await this.entriesAt(path, jsonl, seqs, { handle })).map((held) => held.entry),
5485
+ lastSeq: jsonl.index.seq,
5486
+ epoch: jsonl.index.epoch,
5487
+ seqs,
5488
+ lastEntryId: jsonl.index.lastId
5489
+ },
5490
+ commit: () => this.commitIndexed(path, header, stats, jsonl, needsPersist)
5491
+ };
5492
+ }, async () => {
4453
5493
  const { path, jsonl } = await this.indexed(sessionId);
4454
5494
  if (expectedEpoch !== void 0 && expectedEpoch !== jsonl.index.epoch) throw new SessionConflictError(sessionId, endSeq, jsonl.index.seq);
4455
5495
  const start = Math.max(1, startSeq);
@@ -4462,7 +5502,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4462
5502
  seqs,
4463
5503
  lastEntryId: jsonl.index.lastId
4464
5504
  };
4465
- });
5505
+ }), false);
4466
5506
  }
4467
5507
  findLatestCompaction(sessionId, leafId) {
4468
5508
  return this.run(async () => {
@@ -4481,6 +5521,9 @@ var JsonlSessionStore = class JsonlSessionStore {
4481
5521
  leafId: leaf.id,
4482
5522
  lastSeq: jsonl.index.seq
4483
5523
  };
5524
+ }, {
5525
+ kind: "sessions",
5526
+ sessionIds: () => [sessionId]
4484
5527
  });
4485
5528
  }
4486
5529
  /** Read this exact export file, not another file in the directory with the same session ID. An export is an
@@ -4508,7 +5551,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4508
5551
  legacy: isCurrentSessionHeader(stored) ? void 0 : stored
4509
5552
  };
4510
5553
  const headerStamp = JSON.stringify(header);
4511
- const topology = await this.foldFile(path, epochOf(stats, headerStamp), () => true, input);
5554
+ const topology = await this.foldFile(path, fileEpochOf(stats, headerStamp), () => true, input);
4512
5555
  const jsonl = await this.buildIndex(path, headerStamp, stats, input, {
4513
5556
  topology,
4514
5557
  branch: false
@@ -4604,6 +5647,9 @@ var JsonlSessionStore = class JsonlSessionStore {
4604
5647
  await this.keepIndex(path, {
4605
5648
  ...jsonl,
4606
5649
  fork
5650
+ }, {
5651
+ synced: jsonl.synced,
5652
+ handle: file
4607
5653
  });
4608
5654
  return fork;
4609
5655
  };
@@ -4621,10 +5667,16 @@ var JsonlSessionStore = class JsonlSessionStore {
4621
5667
  await file.close();
4622
5668
  }
4623
5669
  }
5670
+ }, {
5671
+ kind: "sessions",
5672
+ sessionIds: () => [sessionId]
4624
5673
  });
4625
5674
  }
4626
5675
  readChildCatalogCut(sessionId) {
4627
- return this.run(async () => childCatalogCut((await this.indexed(sessionId)).jsonl.index));
5676
+ return this.run(async () => childCatalogCut((await this.indexed(sessionId)).jsonl.index), {
5677
+ kind: "sessions",
5678
+ sessionIds: () => [sessionId]
5679
+ });
4628
5680
  }
4629
5681
  /** The snapshot entries the session's index locates; no line of the file is read (#5554). */
4630
5682
  readSnapshotCut(sessionId, options = {}) {
@@ -4632,6 +5684,9 @@ var JsonlSessionStore = class JsonlSessionStore {
4632
5684
  const { index } = (await this.indexed(sessionId)).jsonl;
4633
5685
  if (options.leafSeq !== void 0 && options.leafSeq > index.seq) return void 0;
4634
5686
  return snapshotCutOf(index, options.leafSeq);
5687
+ }, {
5688
+ kind: "sessions",
5689
+ sessionIds: () => [sessionId]
4635
5690
  });
4636
5691
  }
4637
5692
  /** The lines at `seqs`, each read from where the index places it, without reading the lines between them. */
@@ -4650,25 +5705,45 @@ var JsonlSessionStore = class JsonlSessionStore {
4650
5705
  ...plan.oversized
4651
5706
  }] };
4652
5707
  return { items: await this.entriesAt(path, jsonl, plan.seqs) };
5708
+ }, {
5709
+ kind: "sessions",
5710
+ sessionIds: () => [sessionId]
4653
5711
  });
4654
5712
  }
4655
5713
  readResume(sessionId, leafId, options) {
4656
5714
  return this.run(async () => {
4657
5715
  if (leafId !== void 0) validateSessionText("entry.id", leafId);
4658
- const { path, header, jsonl } = await this.indexed(sessionId);
4659
- const leafSeq = leafId === void 0 ? jsonl.index.leafSeq : await this.seqInFile(path, jsonl, leafId) ?? 0;
4660
- const index = leafSeq === jsonl.index.leafSeq ? jsonl.index : await selectResumeLeaf(jsonl.index, leafSeq, branchStatePages(jsonl.index.seq, {
4661
- bytes: (seq) => spanEnd(jsonl, seq) - spanStart(jsonl, seq),
4662
- read: (seqs) => this.entriesAt(path, jsonl, seqs),
4663
- chunk: (seq, offset, length) => readBytes(path, spanStart(jsonl, seq) + offset, length)
4664
- }));
4665
- const result = await this.windowFromIndex(path, header, jsonl, index, void 0, options?.deferChildRecords);
4666
- if (leafSeq !== jsonl.index.leafSeq) {
4667
- const stats = await stat(path, { bigint: true });
4668
- if (`${stats.dev}:${stats.ino}` !== jsonl.identity || String(stats.mtimeNs) !== jsonl.mtimeNs || Number(stats.size) !== jsonl.fileSize) throw new SessionConflictError(sessionId, index.seq, index.seq);
4669
- }
4670
- return result;
4671
- });
5716
+ return this.readUnlocked(sessionId, async ({ path, handle, stats, header }) => {
5717
+ const { jsonl, needsPersist } = await this.indexFor(path, header, stats, {
5718
+ handle,
5719
+ persist: false
5720
+ });
5721
+ const leafSeq = leafId === void 0 ? jsonl.index.leafSeq : await this.seqInFile(path, jsonl, leafId, handle) ?? 0;
5722
+ const index = leafSeq === jsonl.index.leafSeq ? jsonl.index : await selectResumeLeaf(jsonl.index, leafSeq, branchStatePages(jsonl.index.seq, {
5723
+ bytes: (seq) => spanEnd(jsonl, seq) - spanStart(jsonl, seq),
5724
+ read: (seqs) => this.entriesAt(path, jsonl, seqs, { handle }),
5725
+ chunk: (seq, offset, length) => readFrom(handle, spanStart(jsonl, seq) + offset, length)
5726
+ }));
5727
+ return {
5728
+ value: await this.windowFromIndex(path, header, jsonl, index, { handle }, options?.deferChildRecords),
5729
+ commit: () => this.commitIndexed(path, header, stats, jsonl, needsPersist)
5730
+ };
5731
+ }, async () => {
5732
+ const { path, header, jsonl } = await this.indexed(sessionId);
5733
+ const leafSeq = leafId === void 0 ? jsonl.index.leafSeq : await this.seqInFile(path, jsonl, leafId) ?? 0;
5734
+ const index = leafSeq === jsonl.index.leafSeq ? jsonl.index : await selectResumeLeaf(jsonl.index, leafSeq, branchStatePages(jsonl.index.seq, {
5735
+ bytes: (seq) => spanEnd(jsonl, seq) - spanStart(jsonl, seq),
5736
+ read: (seqs) => this.entriesAt(path, jsonl, seqs),
5737
+ chunk: (seq, offset, length) => readBytes(path, spanStart(jsonl, seq) + offset, length)
5738
+ }));
5739
+ const result = await this.windowFromIndex(path, header, jsonl, index, void 0, options?.deferChildRecords);
5740
+ if (leafSeq !== jsonl.index.leafSeq) {
5741
+ const stats = await stat(path, { bigint: true });
5742
+ if (`${stats.dev}:${stats.ino}` !== jsonl.identity || String(stats.mtimeNs) !== jsonl.mtimeNs || Number(stats.size) !== jsonl.fileSize) throw new SessionConflictError(sessionId, index.seq, index.seq);
5743
+ }
5744
+ return result;
5745
+ });
5746
+ }, false);
4672
5747
  }
4673
5748
  async windowFromIndex(path, header, jsonl, index = jsonl.index, input, deferChildRecords = false) {
4674
5749
  const plan = sessionResumePlan(index, index.leafSeq, deferChildRecords);
@@ -4685,6 +5760,9 @@ var JsonlSessionStore = class JsonlSessionStore {
4685
5760
  validateSessionText("entry.id", entryId);
4686
5761
  const { path, jsonl } = await this.indexed(sessionId);
4687
5762
  return this.seqInFile(path, jsonl, entryId);
5763
+ }, {
5764
+ kind: "sessions",
5765
+ sessionIds: () => [sessionId]
4688
5766
  });
4689
5767
  }
4690
5768
  async indexed(sessionId) {
@@ -4697,7 +5775,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4697
5775
  if (!isCurrentSessionHeader(located.stored)) throw new SessionFormatVersionError$1(located.path, located.stored.version);
4698
5776
  }
4699
5777
  const { path, header, stats } = located;
4700
- const jsonl = await this.indexFor(path, header, stats);
5778
+ const { jsonl } = await this.indexFor(path, header, stats);
4701
5779
  const prior = this.fileStates.get(path);
4702
5780
  await this.remember(path, {
4703
5781
  headerStamp: jsonl.headerStamp,
@@ -4715,29 +5793,157 @@ var JsonlSessionStore = class JsonlSessionStore {
4715
5793
  jsonl
4716
5794
  };
4717
5795
  }
4718
- async indexFor(path, header, stats) {
5796
+ async commitIndexed(path, header, stats, jsonl, needsPersist) {
5797
+ if (jsonl.torn) reportTornLine(path);
5798
+ this.indexes.set(path, jsonl);
5799
+ const prior = this.fileStates.get(path);
5800
+ await this.remember(path, {
5801
+ headerStamp: jsonl.headerStamp,
5802
+ headerId: header.id,
5803
+ lastSeq: jsonl.index.seq,
5804
+ lastEntryId: jsonl.index.lastId ?? void 0,
5805
+ witness: jsonl.witness,
5806
+ terminated: jsonl.terminated,
5807
+ torn: jsonl.torn,
5808
+ ...prior?.summaryState !== void 0 && prior.stamp === this.stamp(stats) ? { summaryState: prior.summaryState } : {}
5809
+ }, jsonl.torn ? jsonl.size : void 0, stats);
5810
+ if (needsPersist) await this.persistSidecarUnderLock(path, jsonl, stats);
5811
+ }
5812
+ async persistSidecarUnderLock(path, jsonl, stats) {
5813
+ const expected = this.stamp(stats);
5814
+ await this.exclusive(async () => {
5815
+ const current = await stat(path, { bigint: true }).catch(() => void 0);
5816
+ if (current !== void 0 && this.stamp(current) === expected) {
5817
+ const kept = this.keptFor(path, jsonl.identity);
5818
+ await this.keepIndex(path, jsonl, {
5819
+ synced: jsonl.synced,
5820
+ handle: kept,
5821
+ writable: kept !== void 0
5822
+ });
5823
+ }
5824
+ }, void 0, this.directory, {
5825
+ kind: "files",
5826
+ paths: [path]
5827
+ });
5828
+ }
5829
+ async indexFor(path, header, stats, options) {
5830
+ const persist = options?.persist !== false;
4719
5831
  const identity = `${stats.dev}:${stats.ino}`;
4720
5832
  const headerStamp = JSON.stringify(header);
4721
- const cached = this.indexes.get(path) ?? await readSidecar(path);
4722
- if (cached !== void 0 && cached.identity === identity && cached.birthtimeNs === String(stats.birthtimeNs) && cached.headerStamp === headerStamp) {
5833
+ const epoch = fileEpochOf(stats, headerStamp);
5834
+ const inMemory = this.indexes.get(path);
5835
+ let cached = inMemory ?? await readSidecar(path);
5836
+ const fromDisk = inMemory === void 0 && cached !== void 0;
5837
+ const older = cached !== void 0 && cached.index.epoch !== epoch && cached.index.epoch === legacyFileEpochOf(stats, headerStamp);
5838
+ if (cached !== void 0 && older) cached = {
5839
+ ...cached,
5840
+ index: {
5841
+ ...cached.index,
5842
+ epoch
5843
+ }
5844
+ };
5845
+ if (cached !== void 0 && (!fromDisk || cached.synced) && cached.identity === identity && cached.birthtimeNs === String(stats.birthtimeNs) && cached.headerStamp === headerStamp && cached.index.epoch === epoch) {
4723
5846
  const fileSize = Number(stats.size);
4724
- const kept = this.keptFor(path, identity);
4725
- if (cached.fileSize === fileSize && cached.mtimeNs === String(stats.mtimeNs) && await witnessHolds(path, cached, kept)) {
4726
- this.indexes.set(path, cached);
4727
- return cached;
5847
+ const handle = options?.handle ?? this.keptFor(path, identity);
5848
+ const writable = options?.handle === void 0 && handle !== void 0;
5849
+ const checkCached = () => fromDisk ? integrityHolds(path, cached, handle) : witnessHolds(path, cached, handle);
5850
+ if (cached.fileSize === fileSize && cached.mtimeNs === String(stats.mtimeNs) && await checkCached()) {
5851
+ if (older) {
5852
+ if (!persist) return {
5853
+ jsonl: cached,
5854
+ needsPersist: true
5855
+ };
5856
+ return {
5857
+ jsonl: await this.keepIndex(path, cached, {
5858
+ synced: cached.synced,
5859
+ handle,
5860
+ writable
5861
+ }),
5862
+ needsPersist: false
5863
+ };
5864
+ }
5865
+ if (persist) this.indexes.set(path, cached);
5866
+ return {
5867
+ jsonl: cached,
5868
+ needsPersist: false
5869
+ };
4728
5870
  }
4729
- if (fileSize > cached.size && await witnessHolds(path, cached, kept)) {
4730
- const grown = await this.catchUp(path, cached, stats, kept);
4731
- if (grown !== void 0) return this.keepIndex(path, grown);
5871
+ if (fileSize > cached.size && await checkCached()) {
5872
+ const grown = await this.catchUp(path, cached, stats, handle, persist);
5873
+ if (grown !== void 0) {
5874
+ if (!persist) return {
5875
+ jsonl: grown,
5876
+ needsPersist: true
5877
+ };
5878
+ return {
5879
+ jsonl: await this.keepIndex(path, grown, {
5880
+ handle,
5881
+ writable
5882
+ }),
5883
+ needsPersist: false
5884
+ };
5885
+ }
4732
5886
  }
4733
5887
  }
4734
- return this.keepIndex(path, await this.buildIndex(path, headerStamp, stats));
5888
+ if (!persist) return {
5889
+ jsonl: await this.buildIndex(path, headerStamp, stats, options?.handle ? { handle: options.handle } : void 0, void 0, false),
5890
+ needsPersist: true
5891
+ };
5892
+ const kept = this.keptFor(path, identity);
5893
+ if (kept !== void 0) {
5894
+ const built = await this.buildIndex(path, headerStamp, stats, { handle: kept });
5895
+ return {
5896
+ jsonl: await this.keepIndex(path, built, {
5897
+ handle: kept,
5898
+ writable: true
5899
+ }),
5900
+ needsPersist: false
5901
+ };
5902
+ }
5903
+ const handle = await open(path, "r");
5904
+ try {
5905
+ const built = await this.buildIndex(path, headerStamp, stats, { handle });
5906
+ return {
5907
+ jsonl: await this.keepIndex(path, built, { handle }),
5908
+ needsPersist: false
5909
+ };
5910
+ } finally {
5911
+ await handle.close();
5912
+ }
4735
5913
  }
4736
- async keepIndex(path, jsonl) {
4737
- const kept = await writeSidecar(path, jsonl) ? {
5914
+ async keepIndex(path, jsonl, options) {
5915
+ if (jsonl.torn) {
5916
+ this.indexes.set(path, jsonl);
5917
+ await unlink(`${path}${SIDECAR_SUFFIX}`).catch(() => void 0);
5918
+ return jsonl;
5919
+ }
5920
+ if (!options?.synced) try {
5921
+ await syncPath(path, options?.handle, options?.writable === true);
5922
+ } catch {
5923
+ this.indexes.set(path, jsonl);
5924
+ return jsonl;
5925
+ }
5926
+ let durable = jsonl.synced ? jsonl : {
4738
5927
  ...jsonl,
4739
- sidecarSize: jsonl.size
4740
- } : jsonl;
5928
+ synced: true
5929
+ };
5930
+ if (durable.size <= PREFIX_HASH_MAX_BYTES && durable.prefixHash === void 0) {
5931
+ const handle = options?.handle ?? this.keptFor(path, durable.identity);
5932
+ const file = handle ?? await open(path, "r");
5933
+ try {
5934
+ const integrity = await captureIntegrity(file, durable.size, durable.spans);
5935
+ durable = {
5936
+ ...durable,
5937
+ ...integrity
5938
+ };
5939
+ } finally {
5940
+ if (handle === void 0) await file.close();
5941
+ }
5942
+ }
5943
+ const kept = await writeSidecar(path, durable) ? {
5944
+ ...durable,
5945
+ sidecarSize: durable.size
5946
+ } : durable;
4741
5947
  this.indexes.set(path, kept);
4742
5948
  return kept;
4743
5949
  }
@@ -4749,23 +5955,25 @@ var JsonlSessionStore = class JsonlSessionStore {
4749
5955
  }
4750
5956
  /** `folded` reuses a topology pass already made; `branch: false` keeps it and skips folding the active branch
4751
5957
  * again, for a reader of positions that never selects a window. */
4752
- async buildIndex(path, headerStamp, stats, input, folded) {
5958
+ async buildIndex(path, headerStamp, stats, input, folded, reportTorn = true) {
4753
5959
  const identity = `${stats.dev}:${stats.ino}`;
4754
5960
  if (input === void 0) {
4755
5961
  const kept = this.keptFor(path, identity);
4756
- if (kept !== void 0) return this.buildIndex(path, headerStamp, stats, { handle: kept }, folded);
5962
+ if (kept !== void 0) return this.buildIndex(path, headerStamp, stats, { handle: kept }, folded, reportTorn);
4757
5963
  const handle = await open(path, "r");
4758
5964
  try {
4759
- return await this.buildIndex(path, headerStamp, stats, { handle }, folded);
5965
+ return await this.buildIndex(path, headerStamp, stats, { handle }, folded, reportTorn);
4760
5966
  } finally {
4761
5967
  await handle.close();
4762
5968
  }
4763
5969
  }
4764
5970
  const birthtimeNs = String(stats.birthtimeNs);
4765
- const epoch = epochOf(stats, headerStamp);
4766
- const topology = folded?.topology ?? await this.foldFile(path, epoch, () => true, input);
5971
+ const epoch = fileEpochOf(stats, headerStamp);
5972
+ const end = reportTorn ? void 0 : Number(stats.size);
5973
+ const topology = folded?.topology ?? await this.foldFile(path, epoch, () => true, input, end, reportTorn);
4767
5974
  const ranges = folded?.branch === false || topology.index.jumps.length === 0 ? void 0 : branchRanges(topology.index, topology.index.leafSeq);
4768
- const active = ranges === void 0 ? topology : await this.foldFile(path, epoch, (seq) => ranges.some(([low, high]) => seq >= low && seq <= high), input);
5975
+ const active = ranges === void 0 ? topology : await this.foldFile(path, epoch, (seq) => ranges.some(([low, high]) => seq >= low && seq <= high), input, end, reportTorn);
5976
+ const integrity = await captureIntegrity(input.handle, active.size, active.spans);
4769
5977
  return {
4770
5978
  identity,
4771
5979
  birthtimeNs,
@@ -4773,7 +5981,8 @@ var JsonlSessionStore = class JsonlSessionStore {
4773
5981
  fileSize: Number(stats.size),
4774
5982
  mtimeNs: String(stats.mtimeNs),
4775
5983
  size: active.size,
4776
- witness: await readFrom(input.handle, Math.max(0, active.size - WITNESS_BYTES), Math.min(active.size, WITNESS_BYTES)),
5984
+ ...integrity,
5985
+ synced: false,
4777
5986
  terminated: active.terminated,
4778
5987
  torn: active.torn,
4779
5988
  spans: active.spans,
@@ -4783,7 +5992,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4783
5992
  sidecarSize: 0
4784
5993
  };
4785
5994
  }
4786
- async foldFile(path, epoch, activeSeq, pinned) {
5995
+ async foldFile(path, epoch, activeSeq, pinned, end, reportTorn = true) {
4787
5996
  let index = {
4788
5997
  ...foldSessionResume(void 0, [], void 0, activeSeq),
4789
5998
  epoch
@@ -4815,10 +6024,10 @@ var JsonlSessionStore = class JsonlSessionStore {
4815
6024
  batchBytes = 0;
4816
6025
  extraToolCalls = 0;
4817
6026
  };
4818
- const take = (entry, start, end, toolCalls) => {
4819
- const bytes = end - start;
6027
+ const take = (entry, start, stop, toolCalls) => {
6028
+ const bytes = stop - start;
4820
6029
  if (batch.length && batchBytes + bytes > SCAN_WINDOW_BYTES$1) flush();
4821
- spans.push(start, end);
6030
+ spans.push(start, stop);
4822
6031
  hashes.push(idHash(entry.id));
4823
6032
  ids.set(entry.id, spans.length / 2);
4824
6033
  batch.push(entry);
@@ -4829,7 +6038,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4829
6038
  };
4830
6039
  const file = pinned?.handle ?? await open(path, "r");
4831
6040
  try {
4832
- const scanned = await scanEntries(path, file, 0, void 0, true, take, pinned?.legacy);
6041
+ const scanned = await scanEntries(path, file, 0, end, true, take, pinned?.legacy, reportTorn);
4833
6042
  flush();
4834
6043
  return {
4835
6044
  index,
@@ -4842,9 +6051,9 @@ var JsonlSessionStore = class JsonlSessionStore {
4842
6051
  if (!pinned) await file.close();
4843
6052
  }
4844
6053
  }
4845
- async catchUp(path, cached, stats, kept) {
6054
+ async catchUp(path, cached, stats, kept, reportTorn = true) {
4846
6055
  const from = cached.size - cached.witness.length;
4847
- if (Number(stats.size) - from > SCAN_WINDOW_BYTES$1) return this.streamCatchUp(path, cached, stats);
6056
+ if (Number(stats.size) - from > SCAN_WINDOW_BYTES$1) return this.streamCatchUp(path, cached, stats, kept, reportTorn);
4848
6057
  const bytes = await readBytes(path, from, Number(stats.size) - from, kept);
4849
6058
  let offset = cached.size;
4850
6059
  let appended = bytes.subarray(cached.witness.length);
@@ -4856,40 +6065,80 @@ var JsonlSessionStore = class JsonlSessionStore {
4856
6065
  const spans = [...cached.spans];
4857
6066
  const entries = [];
4858
6067
  let start = 0;
6068
+ let stoppedAtNul = false;
4859
6069
  for (let newline = appended.indexOf(10); newline !== -1; newline = appended.indexOf(10, start)) {
4860
- const text = appended.subarray(start, newline).toString("utf8");
6070
+ const rawLine = appended.subarray(start, newline);
6071
+ if (hasNulByte(rawLine)) {
6072
+ stoppedAtNul = true;
6073
+ if (reportTorn) reportTornLine(path);
6074
+ break;
6075
+ }
6076
+ const text = rawLine.toString("utf8");
4861
6077
  if (text.trim()) {
4862
6078
  entries.push(JSON.parse(text));
4863
6079
  spans.push(offset + start, offset + newline);
4864
6080
  }
4865
6081
  start = newline + 1;
4866
6082
  }
4867
- const last = appended.subarray(start);
4868
6083
  let size = offset + start;
4869
6084
  let terminated = true;
4870
- let torn = false;
4871
- if (last.length > 0) {
4872
- const unterminated = parseUnterminated(last.toString("utf8"));
4873
- if (unterminated) {
4874
- entries.push(unterminated);
4875
- spans.push(offset + start, offset + appended.length);
4876
- size = offset + appended.length;
4877
- terminated = false;
4878
- } else {
4879
- torn = true;
4880
- reportTornLine(path);
6085
+ let torn = stoppedAtNul;
6086
+ if (!stoppedAtNul) {
6087
+ const last = appended.subarray(start);
6088
+ if (last.length > 0) {
6089
+ const unterminated = hasNulByte(last) ? void 0 : parseUnterminated(last.toString("utf8"));
6090
+ if (unterminated) {
6091
+ entries.push(unterminated);
6092
+ spans.push(offset + start, offset + appended.length);
6093
+ size = offset + appended.length;
6094
+ terminated = false;
6095
+ } else {
6096
+ torn = true;
6097
+ if (reportTorn) reportTornLine(path);
6098
+ }
4881
6099
  }
4882
6100
  }
4883
6101
  validateSessionEntryStructure(entries, path);
4884
6102
  validateSessionEntries(entries);
4885
6103
  if (resumeIndexNeedsRefold(cached.index, entries)) return void 0;
4886
- const index = await this.foldAppended(path, cached, entries);
6104
+ const index = await this.foldAppended(path, cached, entries, kept);
6105
+ const witness = witnessOf(bytes.subarray(0, size - from));
6106
+ let prefixHash;
6107
+ let headWitness = cached.headWitness;
6108
+ let checkpointStride = cached.checkpointStride;
6109
+ let checkpoints = cached.checkpoints;
6110
+ if (size <= PREFIX_HASH_MAX_BYTES) {
6111
+ const file = kept ?? await open(path, "r");
6112
+ try {
6113
+ const captured = await captureIntegrity(file, size, spans);
6114
+ prefixHash = captured.prefixHash;
6115
+ headWitness = captured.headWitness;
6116
+ checkpointStride = captured.checkpointStride;
6117
+ checkpoints = captured.checkpoints;
6118
+ } finally {
6119
+ if (kept === void 0) await file.close();
6120
+ }
6121
+ } else {
6122
+ if (headWitness === void 0 && spans.length >= 2) {
6123
+ const headStart = spans[0];
6124
+ const headLen = Math.min(HEAD_WITNESS_BYTES, size - headStart);
6125
+ headWitness = headStart >= from ? Buffer.from(bytes.subarray(headStart - from, headStart - from + headLen)) : await readBytes(path, headStart, headLen, kept);
6126
+ }
6127
+ const extended = extendCheckpointsFromBuffer(checkpointStride, checkpoints, cached.size, size, from, bytes);
6128
+ checkpointStride = extended.stride;
6129
+ checkpoints = extended.checkpoints;
6130
+ }
4887
6131
  return {
4888
6132
  ...cached,
4889
6133
  fileSize: Number(stats.size),
4890
6134
  mtimeNs: String(stats.mtimeNs),
4891
6135
  size,
4892
- witness: witnessAfter(cached.witness, appended.subarray(0, size - offset)),
6136
+ witness,
6137
+ synced: false,
6138
+ prefixHash,
6139
+ headWitness,
6140
+ checkpointStride,
6141
+ checkpoints,
4893
6142
  terminated: appended.length === 0 ? cached.terminated : terminated,
4894
6143
  torn,
4895
6144
  spans,
@@ -4903,8 +6152,8 @@ var JsonlSessionStore = class JsonlSessionStore {
4903
6152
  * indexed prefix, rather than read the whole file again or hold the suffix. Undefined when the cache cannot be
4904
6153
  * extended: the suffix does not continue the cached last line, or it branches, which needs a full fold.
4905
6154
  */
4906
- async streamCatchUp(path, cached, stats) {
4907
- const file = await open(path, "r");
6155
+ async streamCatchUp(path, cached, stats, kept, reportTorn = true) {
6156
+ const file = kept ?? await open(path, "r");
4908
6157
  try {
4909
6158
  let start = cached.size;
4910
6159
  if (!cached.terminated) {
@@ -4924,7 +6173,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4924
6173
  if (!batch.length) return;
4925
6174
  const seqs = /* @__PURE__ */ new Map();
4926
6175
  for (const id of foreignResumeIds(index, batch)) {
4927
- const seq = appended.get(id) ?? await this.seqInFile(path, cached, id);
6176
+ const seq = appended.get(id) ?? await this.seqInFile(path, cached, id, file);
4928
6177
  if (seq !== void 0) seqs.set(id, seq);
4929
6178
  }
4930
6179
  fork = appendedForkIndex({
@@ -4949,33 +6198,40 @@ var JsonlSessionStore = class JsonlSessionStore {
4949
6198
  extraToolCalls += toolCalls;
4950
6199
  return batch.length >= INDEX_BATCH_ENTRIES || batchBytes >= SCAN_WINDOW_BYTES$1 ? flush().then(() => true) : true;
4951
6200
  };
4952
- const scanned = await scanEntries(path, file, start, Number(stats.size), false, take);
6201
+ const scanned = await scanEntries(path, file, start, Number(stats.size), false, take, void 0, reportTorn);
4953
6202
  if (!scanned) return void 0;
4954
6203
  await flush();
6204
+ const headWitness = cached.headWitness ?? (spans.length >= 2 ? await readFrom(file, spans[0], Math.min(HEAD_WITNESS_BYTES, scanned.size - spans[0])) : void 0);
6205
+ const extended = await extendCheckpointsFromHandle(file, cached.checkpointStride, cached.checkpoints, cached.size, scanned.size);
4955
6206
  return {
4956
6207
  ...cached,
4957
6208
  fileSize: Number(stats.size),
4958
6209
  mtimeNs: String(stats.mtimeNs),
4959
6210
  ...scanned,
4960
6211
  witness: await witnessAt(file, scanned.size),
6212
+ synced: false,
6213
+ prefixHash: void 0,
6214
+ headWitness,
6215
+ checkpointStride: extended.stride,
6216
+ checkpoints: extended.checkpoints,
4961
6217
  spans,
4962
6218
  ids: hashes,
4963
6219
  fork,
4964
6220
  index
4965
6221
  };
4966
6222
  } finally {
4967
- await file.close();
6223
+ if (kept === void 0) await file.close();
4968
6224
  }
4969
6225
  }
4970
- async foldAppended(path, cached, entries) {
6226
+ async foldAppended(path, cached, entries, pinned) {
4971
6227
  const seqs = /* @__PURE__ */ new Map();
4972
6228
  for (const id of foreignResumeIds(cached.index, entries)) {
4973
- const seq = await this.seqInFile(path, cached, id);
6229
+ const seq = await this.seqInFile(path, cached, id, pinned);
4974
6230
  if (seq !== void 0) seqs.set(id, seq);
4975
6231
  }
4976
6232
  return foldSessionResume(cached.index, entries, (id) => seqs.get(id));
4977
6233
  }
4978
- async indexAppended(path, before, entries, lines, firstLine, stats) {
6234
+ async indexAppended(path, before, entries, lines, firstLine, stats, handle) {
4979
6235
  const cached = this.indexes.get(path);
4980
6236
  if (cached === void 0 || cached.identity !== before.identity || cached.size !== before.size || cached.index.seq !== before.lastSeq || resumeIndexNeedsRefold(cached.index, entries)) {
4981
6237
  this.indexes.delete(path);
@@ -4995,6 +6251,8 @@ var JsonlSessionStore = class JsonlSessionStore {
4995
6251
  mtimeNs: String(stats.mtimeNs),
4996
6252
  size: state.size,
4997
6253
  witness: state.witness,
6254
+ synced: true,
6255
+ prefixHash: void 0,
4998
6256
  terminated: true,
4999
6257
  torn: false,
5000
6258
  spans,
@@ -5002,8 +6260,14 @@ var JsonlSessionStore = class JsonlSessionStore {
5002
6260
  fork: appendedForkIndex(cached, entries),
5003
6261
  index: await this.foldAppended(path, cached, entries)
5004
6262
  };
5005
- if (next.size - next.sidecarSize >= SIDECAR_REFRESH_BYTES) await this.keepIndex(path, next);
5006
- else this.indexes.set(path, next);
6263
+ if (next.size - next.sidecarSize >= SIDECAR_REFRESH_BYTES) {
6264
+ const integrity = await captureIntegrity(handle, next.size, spans);
6265
+ await this.keepIndex(path, {
6266
+ ...next,
6267
+ ...integrity,
6268
+ synced: true
6269
+ }, { synced: true });
6270
+ } else this.indexes.set(path, next);
5007
6271
  }
5008
6272
  async entriesAt(path, jsonl, seqs, input, exactRevision = false) {
5009
6273
  const wanted = [...new Set(seqs.filter((seq) => seq >= 1 && seq <= jsonl.index.seq))].sort((a, b) => a - b);
@@ -5070,15 +6334,22 @@ var JsonlSessionStore = class JsonlSessionStore {
5070
6334
  stored ??= await this.readFirstLine(path);
5071
6335
  const directory = dirname$1(path);
5072
6336
  if (isCurrentSessionHeader(stored) || directory === this.directory) return this.readSnapshot(path, stored, true);
5073
- return this.exclusive(() => this.readSnapshot(path, void 0, true), void 0, directory);
6337
+ return this.exclusive(() => this.readSnapshot(path, void 0, true), void 0, directory, {
6338
+ kind: "files",
6339
+ paths: [path]
6340
+ });
5074
6341
  }
5075
6342
  findFile(sessionId) {
5076
- return this.run(async () => (await this.locate(sessionId))?.path);
6343
+ return this.run(() => this.readUnlocked(sessionId, async ({ path }) => ({
6344
+ value: path,
6345
+ commit: async () => {}
6346
+ }), async () => (await this.locate(sessionId))?.path), false);
5077
6347
  }
5078
6348
  readHeader(sessionId) {
5079
- return this.run(async () => {
5080
- return (await this.locate(sessionId))?.header;
5081
- });
6349
+ return this.run(() => this.readUnlocked(sessionId, async ({ header }) => ({
6350
+ value: header,
6351
+ commit: async () => {}
6352
+ }), async () => (await this.locate(sessionId))?.header), false);
5082
6353
  }
5083
6354
  delete(sessionId) {
5084
6355
  return this.run(async () => {
@@ -5091,19 +6362,23 @@ var JsonlSessionStore = class JsonlSessionStore {
5091
6362
  const owner = {
5092
6363
  file: located.path,
5093
6364
  id: sessionId,
5094
- epoch: epochOf(located.stats, JSON.stringify(located.header))
6365
+ epoch: fileEpochOf(located.stats, JSON.stringify(located.header))
5095
6366
  };
5096
6367
  await this.closeKept(located.path);
5097
6368
  await unlink(located.path);
5098
6369
  this.fileStates.delete(located.path);
5099
6370
  await this.forgetIndex(located.path);
5100
6371
  await deleteFileChatRecords(owner).catch(() => {});
6372
+ }, {
6373
+ kind: "sessions",
6374
+ sessionIds: () => [sessionId],
6375
+ create: true
5101
6376
  });
5102
6377
  }
5103
6378
  async *list(query) {
5104
6379
  this.checkAbort(query.signal);
5105
6380
  const matchesCwd = query.cwd === void 0 ? void 0 : createSessionCwdMatcherAsync(query.cwd);
5106
- const paths = await this.run(() => this.paths(), true, query.signal);
6381
+ const paths = await this.run(() => this.paths(), { kind: "list" }, query.signal);
5107
6382
  for (const path of paths) {
5108
6383
  const cached = query.withoutSearchText ? this.fileStates.get(path) : void 0;
5109
6384
  const summary = await this.run(async () => {
@@ -5146,18 +6421,24 @@ var JsonlSessionStore = class JsonlSessionStore {
5146
6421
  location: path
5147
6422
  };
5148
6423
  };
5149
- return await (cached?.summaryState !== void 0 ? this.exclusive(readOne, query.signal) : readOne());
6424
+ return await (cached?.summaryState !== void 0 ? this.exclusive(readOne, query.signal, this.directory, {
6425
+ kind: "files",
6426
+ paths: [path]
6427
+ }) : readOne());
5150
6428
  } catch (cause) {
5151
6429
  const error = cause;
5152
6430
  if (error.path === path && (error.code === "ENOENT" || error.code === "ENOTDIR")) return void 0;
5153
6431
  if (cause instanceof SessionFormatVersionError$1 || cause instanceof SessionInvalidTextError || cause instanceof SessionInvalidTimestampError || cause instanceof SyntaxError) return void 0;
5154
6432
  throw cause;
5155
6433
  }
5156
- }, cached?.summaryState === void 0, query.signal);
6434
+ }, cached?.summaryState === void 0 ? {
6435
+ kind: "files",
6436
+ paths: [path]
6437
+ } : false, query.signal);
5157
6438
  this.checkAbort(query.signal);
5158
6439
  if (summary) yield summary;
5159
6440
  }
5160
- await this.run(async () => this.checkAbort(query.signal), true, query.signal);
6441
+ await this.run(async () => this.checkAbort(query.signal), { kind: "list" }, query.signal);
5161
6442
  }
5162
6443
  async *scanFiles() {
5163
6444
  for (const location of await this.run(() => this.paths({ skipUnreadableDirectories: true }), false)) {
@@ -5212,9 +6493,18 @@ var JsonlSessionStore = class JsonlSessionStore {
5212
6493
  armed: 0
5213
6494
  };
5214
6495
  this.keptFiles.set(path, opened);
5215
- while (this.keptFiles.size > KEPT_FILES) await this.closeKept(this.keptFiles.keys().next().value);
6496
+ await this.trimKeptFiles();
5216
6497
  return opened;
5217
6498
  }
6499
+ /** Closes the least recently used unpinned handles until the cache is back within {@link KEPT_FILES}. */
6500
+ async trimKeptFiles() {
6501
+ if (this.keptFiles.size <= KEPT_FILES) return;
6502
+ for (const candidate of [...this.keptFiles.keys()]) {
6503
+ if (this.keptFiles.size <= KEPT_FILES) return;
6504
+ if (this.pinnedKeptFiles.has(candidate)) continue;
6505
+ await this.closeKept(candidate);
6506
+ }
6507
+ }
5218
6508
  /** The kept handle of the file at `path`, while it is the file `identity` names, to read through. */
5219
6509
  keptFor(path, identity) {
5220
6510
  const kept = this.keptFiles.get(path);
@@ -5246,7 +6536,7 @@ var JsonlSessionStore = class JsonlSessionStore {
5246
6536
  const result = this.queue.then(async () => {
5247
6537
  if (this.poisoned) throw this.poisoned;
5248
6538
  try {
5249
- return await (locked ? this.exclusive(operation, signal) : operation());
6539
+ return await (locked === false ? operation() : this.exclusive(operation, signal, this.directory, locked));
5250
6540
  } catch (cause) {
5251
6541
  if (signal?.aborted && cause === signal.reason) throw cause;
5252
6542
  throw this.failure(cause);
@@ -5260,7 +6550,93 @@ var JsonlSessionStore = class JsonlSessionStore {
5260
6550
  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;
5261
6551
  return new StorageUnavailableError$1(this.descriptor, cause);
5262
6552
  }
5263
- async exclusive(operation, signal, directory = this.directory) {
6553
+ async resolveLockScope(lockRequest) {
6554
+ if (lockRequest === true) return { kind: "full" };
6555
+ if (typeof lockRequest === "function") return lockRequest();
6556
+ if (lockRequest.kind !== "sessions") return lockRequest;
6557
+ if (lockRequest.forceFull?.()) return { kind: "full" };
6558
+ const ids = [...new Set(lockRequest.sessionIds())];
6559
+ const targetPaths = [];
6560
+ const missing = [];
6561
+ for (const id of ids) {
6562
+ if (this.selectedFile?.id === id) {
6563
+ targetPaths.push(this.selectedFile.path);
6564
+ continue;
6565
+ }
6566
+ let found;
6567
+ for (const [path, cached] of this.fileStates) if (cached.headerId === id) {
6568
+ found = path;
6569
+ break;
6570
+ }
6571
+ if (found !== void 0) targetPaths.push(found);
6572
+ else missing.push(id);
6573
+ }
6574
+ if (missing.length > 0) {
6575
+ const allPaths = await this.paths();
6576
+ for (const id of missing) {
6577
+ const suffix = `_${this.key(id)}.jsonl`;
6578
+ let matched = false;
6579
+ for (const path of allPaths) {
6580
+ const name = basename$1(path);
6581
+ if (name.endsWith(suffix) || SESSION_FILE_NAME.exec(name)?.[1] === id) {
6582
+ targetPaths.push(path);
6583
+ matched = true;
6584
+ }
6585
+ }
6586
+ if (!matched) return { kind: "full" };
6587
+ }
6588
+ }
6589
+ return {
6590
+ kind: "stripes",
6591
+ stripes: sortedStripesForPaths(targetPaths),
6592
+ create: lockRequest.create === true
6593
+ };
6594
+ }
6595
+ assertStripeHeld(path) {
6596
+ if (this.heldStripes === void 0 || this.heldLockDirectory !== this.directory) return;
6597
+ if (!this.heldStripes.has(sessionLockStripe(basename$1(path)))) throw new RelockRequiredError(path);
6598
+ }
6599
+ async exclusive(operation, signal, directory = this.directory, lockRequest = true) {
6600
+ const native = loadNativeSessionLocks();
6601
+ if (native === null) return this.exclusiveLegacy(operation, signal, directory);
6602
+ const groupLock = await acquireSessionGroupLock(native, directory, {
6603
+ lockFs: this.lockFs,
6604
+ signal,
6605
+ onCompromised: (cause) => {
6606
+ this.poisoned = new StorageUnavailableError$1(this.descriptor, cause);
6607
+ }
6608
+ });
6609
+ try {
6610
+ let scope = await this.resolveLockScope(lockRequest);
6611
+ for (let attempt = 0;; attempt++) {
6612
+ const fine = await acquireFineSessionLocks(native, groupLock.lockPath, scope, signal);
6613
+ const prevStripes = this.heldStripes;
6614
+ const prevDir = this.heldLockDirectory;
6615
+ this.heldStripes = fine.stripes;
6616
+ this.heldLockDirectory = directory;
6617
+ try {
6618
+ this.checkAbort(signal);
6619
+ if (this.poisoned) throw this.poisoned;
6620
+ const result = await operation();
6621
+ if (this.poisoned) throw this.poisoned;
6622
+ return result;
6623
+ } catch (cause) {
6624
+ if (cause instanceof RelockRequiredError && attempt === 0) {
6625
+ scope = { kind: "full" };
6626
+ continue;
6627
+ }
6628
+ throw cause;
6629
+ } finally {
6630
+ this.heldStripes = prevStripes;
6631
+ this.heldLockDirectory = prevDir;
6632
+ fine.release();
6633
+ }
6634
+ }
6635
+ } finally {
6636
+ await groupLock.release();
6637
+ }
6638
+ }
6639
+ async exclusiveLegacy(operation, signal, directory = this.directory) {
5264
6640
  const lockfilePath = join$1(directory, ".session.lock");
5265
6641
  let release;
5266
6642
  let refusals = 0;
@@ -5301,9 +6677,7 @@ var JsonlSessionStore = class JsonlSessionStore {
5301
6677
  return result;
5302
6678
  }
5303
6679
  /**
5304
- * Releases the lock. The directory removal is retried when Windows refuses it for a moment. If it never
5305
- * succeeds the work is still done, so the failure is not reported over it: the lock is remembered so this
5306
- * store's next acquire removes it at once, instead of waiting for it to go stale.
6680
+ * Releases a fallback proper-lockfile directory lock when native advisory locks are unavailable.
5307
6681
  */
5308
6682
  async release(release, lockfilePath) {
5309
6683
  const fs = this.lockFs ?? {
@@ -5328,7 +6702,7 @@ var JsonlSessionStore = class JsonlSessionStore {
5328
6702
  const modified = await statMtimeMs(fs, lockfilePath);
5329
6703
  if (modified !== void 0) this.unreleased.set(lockfilePath, modified);
5330
6704
  }
5331
- /** Removes a lock directory this store failed to release, if it still has the time it had then. */
6705
+ /** Removes a fallback lock directory this store failed to release, if it still has the time it had then. */
5332
6706
  async clearUnreleased(lockfilePath) {
5333
6707
  const expected = this.unreleased.get(lockfilePath);
5334
6708
  if (expected === void 0) return false;
@@ -5360,6 +6734,7 @@ var JsonlSessionStore = class JsonlSessionStore {
5360
6734
  async paths(options = {}) {
5361
6735
  const paths = [];
5362
6736
  for (const entry of await readdir(this.directory, { withFileTypes: true })) {
6737
+ if (entry.name.startsWith(".session.lock")) continue;
5363
6738
  const path = join$1(this.directory, entry.name);
5364
6739
  if ((entry.isDirectory() || entry.isSymbolicLink()) && !this.exactDirectory) {
5365
6740
  const children = await readdir(path, { withFileTypes: true }).catch((cause) => {
@@ -5374,14 +6749,20 @@ var JsonlSessionStore = class JsonlSessionStore {
5374
6749
  }
5375
6750
  async locate(sessionId) {
5376
6751
  validateSessionText("sessionId", sessionId);
5377
- if (this.selectedFile?.id === sessionId) return this.scan(sessionId, [this.selectedFile.path]);
5378
- const known = await this.locateKnown(sessionId);
5379
- if (known) return known;
5380
- const suffix = `_${this.key(sessionId)}.jsonl`;
5381
- const paths = await this.paths();
5382
- const named = paths.filter((path) => basename$1(path).endsWith(suffix));
5383
- const others = paths.filter((path) => !named.includes(path));
5384
- return await this.scan(sessionId, named) ?? await this.scan(sessionId, others);
6752
+ let found;
6753
+ if (this.selectedFile?.id === sessionId) found = await this.scan(sessionId, [this.selectedFile.path]);
6754
+ else {
6755
+ found = await this.locateKnown(sessionId);
6756
+ if (!found) {
6757
+ const suffix = `_${this.key(sessionId)}.jsonl`;
6758
+ const paths = await this.paths();
6759
+ const named = paths.filter((path) => basename$1(path).endsWith(suffix));
6760
+ const others = paths.filter((path) => !named.includes(path));
6761
+ found = await this.scan(sessionId, named) ?? await this.scan(sessionId, others);
6762
+ }
6763
+ }
6764
+ if (found !== void 0) this.assertStripeHeld(found.path);
6765
+ return found;
5385
6766
  }
5386
6767
  /**
5387
6768
  * Whether a file of this directory already holds `sessionId`, as {@link locate} finds it, without reading the files
@@ -5520,7 +6901,7 @@ var JsonlSessionStore = class JsonlSessionStore {
5520
6901
  torn,
5521
6902
  summaryState: applySessionSummaryEntries(void 0, entries).state
5522
6903
  }, torn ? size : void 0);
5523
- bindChatEpoch(header, epochOf(stats, JSON.stringify(header)));
6904
+ bindChatEpoch(header, fileEpochOf(stats, JSON.stringify(header)));
5524
6905
  return {
5525
6906
  header,
5526
6907
  entries,
@@ -5529,58 +6910,326 @@ var JsonlSessionStore = class JsonlSessionStore {
5529
6910
  }
5530
6911
  /**
5531
6912
  * The entries after the header line. A last line without a newline is read when it is a complete record and
5532
- * left out when it is torn; `size` and `witness` then end at the last complete line. A malformed line before
5533
- * the last one is still a parse failure.
6913
+ * left out when it is torn; a line containing raw NUL bytes (an unwritten zero-filled page from out-of-order
6914
+ * writeback and power loss) ends the readable prefix right before it as a torn tail. `size` and `witness` then
6915
+ * end at the last complete line before that tail. Any other malformed complete line is still a parse failure.
5534
6916
  */
5535
6917
  async readEntries(path) {
5536
6918
  const input = createReadStream(path);
6919
+ const entries = [];
5537
6920
  let size = 0;
5538
- let complete = 0;
6921
+ let lineStart = 0;
5539
6922
  let witness = Buffer.alloc(0);
5540
- let completeWitness = Buffer.alloc(0);
5541
- input.on("data", (chunk) => {
5542
- const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
5543
- const newline = bytes.lastIndexOf(10);
5544
- if (newline !== -1) {
5545
- complete = size + newline + 1;
5546
- completeWitness = witnessAfter(witness, bytes.subarray(0, newline + 1));
5547
- }
5548
- witness = witnessAfter(witness, bytes);
5549
- size += bytes.length;
5550
- });
5551
- const entries = [];
6923
+ let parts = [];
5552
6924
  let first = true;
5553
- let last;
5554
6925
  try {
5555
- for await (const line of readLines(input)) {
5556
- if (first) {
5557
- first = false;
5558
- continue;
6926
+ for await (const chunk of input) {
6927
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
6928
+ let start = 0;
6929
+ for (let newline = bytes.indexOf(10); newline !== -1; newline = bytes.indexOf(10, start)) {
6930
+ parts.push(bytes.subarray(start, newline));
6931
+ const lineBytes = parts.length === 1 ? parts[0] : Buffer.concat(parts);
6932
+ parts = [];
6933
+ const lineEnd = size + newline + 1;
6934
+ if (first) {
6935
+ first = false;
6936
+ witness = witnessAfter(witnessAfter(witness, lineBytes), NEWLINE);
6937
+ lineStart = lineEnd;
6938
+ } else if (hasNulByte(lineBytes)) return {
6939
+ entries,
6940
+ witness,
6941
+ terminated: true,
6942
+ torn: true,
6943
+ size: lineStart
6944
+ };
6945
+ else {
6946
+ const text = lineBytes.toString("utf8", 0, lineBytes.at(-1) === 13 ? lineBytes.length - 1 : lineBytes.length);
6947
+ if (text.trim()) entries.push(JSON.parse(text));
6948
+ witness = witnessAfter(witnessAfter(witness, lineBytes), NEWLINE);
6949
+ lineStart = lineEnd;
6950
+ }
6951
+ start = newline + 1;
5559
6952
  }
5560
- if (last?.trim()) entries.push(JSON.parse(last));
5561
- last = line;
6953
+ if (start < bytes.length) parts.push(bytes.subarray(start));
6954
+ size += bytes.length;
5562
6955
  }
5563
6956
  } finally {
5564
6957
  input.destroy();
5565
6958
  }
5566
- const terminated = complete === size;
5567
- if (last !== void 0 && terminated) {
5568
- if (last.trim()) entries.push(JSON.parse(last));
5569
- } else if (last !== void 0) {
5570
- const entry = parseUnterminated(last);
5571
- if (!entry) return {
5572
- entries,
5573
- witness: completeWitness,
5574
- terminated: true,
5575
- torn: true,
5576
- size: complete
6959
+ if (parts.length === 0) return {
6960
+ entries,
6961
+ witness,
6962
+ terminated: true,
6963
+ torn: false,
6964
+ size
6965
+ };
6966
+ const lastBytes = parts.length === 1 ? parts[0] : Buffer.concat(parts);
6967
+ if (first) return {
6968
+ entries,
6969
+ witness: witnessAfter(witness, lastBytes),
6970
+ terminated: false,
6971
+ torn: false,
6972
+ size
6973
+ };
6974
+ if (hasNulByte(lastBytes)) return {
6975
+ entries,
6976
+ witness,
6977
+ terminated: true,
6978
+ torn: true,
6979
+ size: lineStart
6980
+ };
6981
+ const entry = parseUnterminated(lastBytes.toString("utf8", 0, lastBytes.at(-1) === 13 ? lastBytes.length - 1 : lastBytes.length));
6982
+ if (!entry) return {
6983
+ entries,
6984
+ witness,
6985
+ terminated: true,
6986
+ torn: true,
6987
+ size: lineStart
6988
+ };
6989
+ entries.push(entry);
6990
+ return {
6991
+ entries,
6992
+ witness: witnessAfter(witness, lastBytes),
6993
+ terminated: false,
6994
+ torn: false,
6995
+ size
6996
+ };
6997
+ }
6998
+ async isDirectoryLockPresent(directory = this.directory) {
6999
+ const lockfilePath = join$1(directory, ".session.lock");
7000
+ if (this.lockFs) return new Promise((resolve) => {
7001
+ this.lockFs.stat(lockfilePath, (error) => {
7002
+ resolve(error?.code !== "ENOENT");
7003
+ });
7004
+ });
7005
+ try {
7006
+ await stat(lockfilePath);
7007
+ return true;
7008
+ } catch (cause) {
7009
+ return cause.code !== "ENOENT";
7010
+ }
7011
+ }
7012
+ /**
7013
+ * Checks that no writer held the lock and the file at `path` still matches `before`.
7014
+ * The lock check must run strictly before `stat(path)`: checking `stat(path)` first could match an
7015
+ * unsynced write right before a failed sync rolls it back and releases the lock.
7016
+ */
7017
+ async unlockedReadValid(path, before) {
7018
+ if (await this.isDirectoryLockPresent()) return false;
7019
+ const after = await stat(path, { bigint: true }).catch(() => void 0);
7020
+ return after !== void 0 && this.stamp(after) === this.stamp(before);
7021
+ }
7022
+ async readUnlocked(sessionId, readOpen, locked) {
7023
+ const found = await this.locateOpen(sessionId);
7024
+ const lockScope = {
7025
+ kind: "sessions",
7026
+ sessionIds: () => [sessionId]
7027
+ };
7028
+ if (found.kind !== "found") return this.exclusive(locked, void 0, this.directory, lockScope);
7029
+ const { located } = found;
7030
+ let outcome;
7031
+ let caught;
7032
+ let valid = false;
7033
+ try {
7034
+ try {
7035
+ outcome = await readOpen(located);
7036
+ } catch (error) {
7037
+ caught = { error };
7038
+ }
7039
+ valid = await this.unlockedReadValid(located.path, located.stats);
7040
+ } finally {
7041
+ if (located.owned) await located.handle.close();
7042
+ }
7043
+ if (!valid) return this.exclusive(locked, void 0, this.directory, lockScope);
7044
+ if (caught !== void 0) throw caught.error;
7045
+ await outcome.commit();
7046
+ return outcome.value;
7047
+ }
7048
+ async openCandidate(sessionId, path, firstReadBytes, mode) {
7049
+ let handle;
7050
+ try {
7051
+ handle = await open(path, "r");
7052
+ } catch {
7053
+ return mode === "scan" ? { kind: "skip" } : { kind: "retry" };
7054
+ }
7055
+ let release = true;
7056
+ try {
7057
+ const stats = await handle.stat({ bigint: true });
7058
+ let firstLine;
7059
+ try {
7060
+ firstLine = await readFirstLineWithTailFrom(handle, firstReadBytes, Number(stats.size));
7061
+ } catch (cause) {
7062
+ if (mode === "known") return { kind: "retry" };
7063
+ if (!(mode === "selected" || basename$1(path).match(/_([0-9a-f]{64})\.jsonl$/)?.[1] === this.key(sessionId))) return { kind: "skip" };
7064
+ if (await this.unlockedReadValid(path, stats)) throw cause;
7065
+ return { kind: "retry" };
7066
+ }
7067
+ const { stored } = firstLine;
7068
+ if (stored.id !== sessionId) return mode === "scan" ? { kind: "skip" } : { kind: "retry" };
7069
+ if (!isCurrentSessionHeader(stored)) return { kind: "legacy" };
7070
+ let header;
7071
+ try {
7072
+ header = await this.readHeaderAt(path, stored);
7073
+ } catch (cause) {
7074
+ if (mode === "known") return { kind: "retry" };
7075
+ if (await this.unlockedReadValid(path, stats)) throw cause;
7076
+ return { kind: "retry" };
7077
+ }
7078
+ release = false;
7079
+ return {
7080
+ kind: "found",
7081
+ located: {
7082
+ path,
7083
+ handle,
7084
+ owned: true,
7085
+ stats,
7086
+ header,
7087
+ firstLine,
7088
+ state: this.fileStates.get(path)
7089
+ }
5577
7090
  };
5578
- entries.push(entry);
7091
+ } finally {
7092
+ if (release) await handle.close();
5579
7093
  }
5580
- return {
7094
+ }
7095
+ async locateOpen(sessionId) {
7096
+ validateSessionText("sessionId", sessionId);
7097
+ if (this.selectedFile?.id === sessionId) {
7098
+ const hit = await this.openCandidate(sessionId, this.selectedFile.path, HEADER_READ_CHUNK_BYTES, "selected");
7099
+ return hit.kind === "found" ? hit : { kind: "retry" };
7100
+ }
7101
+ for (const [path, cached] of this.fileStates) {
7102
+ if (cached.headerId !== sessionId) continue;
7103
+ const parent = dirname$1(path);
7104
+ if (parent !== this.directory && (this.exactDirectory || dirname$1(parent) !== this.directory)) return { kind: "retry" };
7105
+ const kept = this.keptFiles.get(path);
7106
+ if (kept !== void 0) {
7107
+ let stats;
7108
+ try {
7109
+ stats = await kept.handle.stat({ bigint: true });
7110
+ } catch {
7111
+ return { kind: "retry" };
7112
+ }
7113
+ let firstLine;
7114
+ try {
7115
+ firstLine = await readFirstLineWithTailFrom(kept.handle, headerLineBytes(cached.headerStamp), Number(stats.size));
7116
+ } catch {
7117
+ return { kind: "retry" };
7118
+ }
7119
+ const { stored } = firstLine;
7120
+ if (stored.id !== sessionId || !isCurrentSessionHeader(stored)) return { kind: "retry" };
7121
+ let header;
7122
+ try {
7123
+ header = await this.readHeaderAt(path, stored);
7124
+ } catch {
7125
+ return { kind: "retry" };
7126
+ }
7127
+ this.armIdle(path, kept);
7128
+ return {
7129
+ kind: "found",
7130
+ located: {
7131
+ path,
7132
+ handle: kept.handle,
7133
+ owned: false,
7134
+ stats,
7135
+ header,
7136
+ firstLine,
7137
+ state: cached
7138
+ }
7139
+ };
7140
+ }
7141
+ const hit = await this.openCandidate(sessionId, path, headerLineBytes(cached.headerStamp), "known");
7142
+ return hit.kind === "found" ? hit : { kind: "retry" };
7143
+ }
7144
+ let paths;
7145
+ try {
7146
+ paths = await this.paths();
7147
+ } catch {
7148
+ return { kind: "retry" };
7149
+ }
7150
+ const suffix = `_${this.key(sessionId)}.jsonl`;
7151
+ const named = paths.filter((path) => basename$1(path).endsWith(suffix));
7152
+ const others = paths.filter((path) => !named.includes(path));
7153
+ for (const path of [...named, ...others]) {
7154
+ const hit = await this.openCandidate(sessionId, path, HEADER_READ_CHUNK_BYTES, "scan");
7155
+ if (hit.kind === "found") return hit;
7156
+ if (hit.kind === "legacy" || hit.kind === "retry") return { kind: "retry" };
7157
+ }
7158
+ return { kind: "retry" };
7159
+ }
7160
+ async readEntriesFrom(file, fileSize, header) {
7161
+ let size = header.headerEnd;
7162
+ let lineStart = header.headerEnd;
7163
+ let witness = header.headerWitness;
7164
+ const entries = [];
7165
+ let parts = [];
7166
+ let stoppedAtNul = false;
7167
+ const consume = (bytes) => {
7168
+ if (bytes.length === 0 || stoppedAtNul) return;
7169
+ let start = 0;
7170
+ for (let newline = bytes.indexOf(10); newline !== -1; newline = bytes.indexOf(10, start)) {
7171
+ parts.push(bytes.subarray(start, newline));
7172
+ const lineBytes = parts.length === 1 ? parts[0] : Buffer.concat(parts);
7173
+ parts = [];
7174
+ const lineEnd = size + newline + 1;
7175
+ if (hasNulByte(lineBytes)) {
7176
+ stoppedAtNul = true;
7177
+ return;
7178
+ }
7179
+ const text = lineBytes.toString("utf8", 0, lineBytes.at(-1) === 13 ? lineBytes.length - 1 : lineBytes.length);
7180
+ if (text.trim()) entries.push(JSON.parse(text));
7181
+ witness = witnessAfter(witnessAfter(witness, lineBytes), NEWLINE);
7182
+ lineStart = lineEnd;
7183
+ start = newline + 1;
7184
+ }
7185
+ if (start < bytes.length) parts.push(Buffer.from(bytes.subarray(start)));
7186
+ size += bytes.length;
7187
+ };
7188
+ consume(header.remainder);
7189
+ let position = header.nextOffset;
7190
+ while (position < fileSize && !stoppedAtNul) {
7191
+ const length = Math.min(SCAN_WINDOW_BYTES$1, fileSize - position);
7192
+ const buffer = Buffer.allocUnsafe(length);
7193
+ const { bytesRead } = await file.read(buffer, 0, length, position);
7194
+ if (bytesRead === 0) throw new Error(`Session file ended before byte ${fileSize}`);
7195
+ consume(buffer.subarray(0, bytesRead));
7196
+ position += bytesRead;
7197
+ }
7198
+ if (stoppedAtNul) return {
5581
7199
  entries,
5582
7200
  witness,
5583
- terminated,
7201
+ terminated: true,
7202
+ torn: true,
7203
+ size: lineStart
7204
+ };
7205
+ if (parts.length === 0) return {
7206
+ entries,
7207
+ witness,
7208
+ terminated: header.headerTerminated || size > header.headerEnd,
7209
+ torn: false,
7210
+ size
7211
+ };
7212
+ const lastBytes = parts.length === 1 ? parts[0] : Buffer.concat(parts);
7213
+ if (hasNulByte(lastBytes)) return {
7214
+ entries,
7215
+ witness,
7216
+ terminated: true,
7217
+ torn: true,
7218
+ size: lineStart
7219
+ };
7220
+ const entry = parseUnterminated(lastBytes.toString("utf8", 0, lastBytes.at(-1) === 13 ? lastBytes.length - 1 : lastBytes.length));
7221
+ if (!entry) return {
7222
+ entries,
7223
+ witness,
7224
+ terminated: true,
7225
+ torn: true,
7226
+ size: lineStart
7227
+ };
7228
+ entries.push(entry);
7229
+ return {
7230
+ entries,
7231
+ witness: witnessAfter(witness, lastBytes),
7232
+ terminated: false,
5584
7233
  torn: false,
5585
7234
  size
5586
7235
  };
@@ -5606,10 +7255,13 @@ var JsonlSessionStore = class JsonlSessionStore {
5606
7255
  */
5607
7256
  async remember(path, state, size, stats) {
5608
7257
  stats ??= await stat(path, { bigint: true });
7258
+ const identity = `${stats.dev}:${stats.ino}`;
7259
+ const kept = this.keptFiles.get(path);
7260
+ if (kept !== void 0 && kept.identity !== identity) await this.closeKept(path);
5609
7261
  this.keepFileState(path, {
5610
7262
  ...state,
5611
7263
  stamp: this.stamp(stats),
5612
- identity: `${stats.dev}:${stats.ino}`,
7264
+ identity,
5613
7265
  size: size ?? Number(stats.size)
5614
7266
  });
5615
7267
  return stats;
@@ -5636,7 +7288,8 @@ var JsonlSessionStore = class JsonlSessionStore {
5636
7288
  const stale = async () => new SessionConflictError(sessionId, options.expectSeq, (await this.readEntries(path)).entries.length);
5637
7289
  if (state.identity !== `${stats.dev}:${stats.ino}` || state.headerStamp !== JSON.stringify(header) || Number(stats.size) < state.size) throw await stale();
5638
7290
  if (state.stamp !== this.stamp(stats)) {
5639
- const file = await open(path, "r");
7291
+ const kept = this.keptFor(path, state.identity);
7292
+ const file = kept ?? await open(path, "r");
5640
7293
  const offset = state.size - state.witness.length;
5641
7294
  const bytes = Buffer.alloc(Number(stats.size) - offset);
5642
7295
  try {
@@ -5647,24 +7300,45 @@ var JsonlSessionStore = class JsonlSessionStore {
5647
7300
  read += bytesRead;
5648
7301
  }
5649
7302
  } finally {
5650
- await file.close();
7303
+ if (kept === void 0) await file.close();
5651
7304
  }
5652
7305
  if (!bytes.subarray(0, state.witness.length).equals(state.witness)) throw await stale();
5653
- let appended = bytes.subarray(state.witness.length).toString("utf8");
5654
- if (appended && !state.terminated) {
5655
- if (!appended.startsWith("\n")) throw await stale();
5656
- appended = appended.slice(1);
7306
+ let pos = state.witness.length;
7307
+ if (pos < bytes.length && !state.terminated) {
7308
+ if (bytes[pos] !== 10) throw await stale();
7309
+ pos += 1;
7310
+ }
7311
+ const entries = [];
7312
+ let torn = false;
7313
+ let stoppedAtNul = false;
7314
+ for (let newline = bytes.indexOf(10, pos); newline !== -1; newline = bytes.indexOf(10, pos)) {
7315
+ const rawLine = bytes.subarray(pos, newline);
7316
+ if (hasNulByte(rawLine)) {
7317
+ torn = true;
7318
+ stoppedAtNul = true;
7319
+ reportTornLine(path);
7320
+ break;
7321
+ }
7322
+ const text = rawLine.toString("utf8");
7323
+ if (text.trim()) entries.push(JSON.parse(text));
7324
+ pos = newline + 1;
7325
+ }
7326
+ let end = pos;
7327
+ if (!stoppedAtNul) {
7328
+ if (pos < bytes.length) {
7329
+ const tail = bytes.subarray(pos);
7330
+ const unterminated = hasNulByte(tail) ? void 0 : parseUnterminated(tail.toString("utf8"));
7331
+ if (unterminated) {
7332
+ entries.push(unterminated);
7333
+ end = bytes.length;
7334
+ } else {
7335
+ torn = true;
7336
+ reportTornLine(path);
7337
+ }
7338
+ } else end = bytes.length;
5657
7339
  }
5658
- const lines = appended.split("\n");
5659
- const last = lines.pop() ?? "";
5660
- const entries = lines.map((line) => JSON.parse(line));
5661
- const unterminated = last === "" ? void 0 : parseUnterminated(last);
5662
- if (unterminated) entries.push(unterminated);
5663
- const torn = last !== "" && !unterminated;
5664
- if (torn) reportTornLine(path);
5665
7340
  validateSessionEntryStructure(entries, path);
5666
7341
  validateSessionEntries(entries);
5667
- const end = torn ? bytes.lastIndexOf(10) + 1 : bytes.length;
5668
7342
  state = {
5669
7343
  ...state,
5670
7344
  stamp: this.stamp(stats),
@@ -5679,7 +7353,7 @@ var JsonlSessionStore = class JsonlSessionStore {
5679
7353
  this.keepFileState(path, state);
5680
7354
  }
5681
7355
  }
5682
- if (state.lastSeq !== options.expectSeq || options.epoch !== void 0 && epochOf(stats, JSON.stringify(header)) !== options.epoch) throw new SessionConflictError(sessionId, options.expectSeq, state.lastSeq);
7356
+ if (state.lastSeq !== options.expectSeq || options.epoch !== void 0 && fileEpochOf(stats, JSON.stringify(header)) !== options.epoch) throw new SessionConflictError(sessionId, options.expectSeq, state.lastSeq);
5683
7357
  return {
5684
7358
  path,
5685
7359
  state,
@@ -5694,14 +7368,6 @@ var JsonlSessionStore = class JsonlSessionStore {
5694
7368
  }), ...entries.map((entry) => JSON.stringify(entry))].join("\n")}\n`;
5695
7369
  }
5696
7370
  };
5697
- function removeDirectory(fs, path) {
5698
- return new Promise((resolve, reject) => {
5699
- fs.rmdir(path, (error) => {
5700
- if (error && error.code !== "ENOENT") reject(error);
5701
- else resolve();
5702
- });
5703
- });
5704
- }
5705
7371
  function statMtimeMs(fs, path) {
5706
7372
  return new Promise((resolve) => {
5707
7373
  fs.stat(path, (error, stats) => resolve(error ? void 0 : stats.mtimeMs));
@@ -5737,9 +7403,6 @@ function decodeIdHashes(text) {
5737
7403
  for (let offset = 0; offset < bytes.length; offset += 4) hashes.push(bytes.readUInt32LE(offset));
5738
7404
  return hashes;
5739
7405
  }
5740
- function epochOf(stats, headerStamp) {
5741
- return `${stats.dev}:${stats.ino}:${stats.birthtimeNs}:${createHash("sha256").update(headerStamp).digest("hex").slice(0, 16)}`;
5742
- }
5743
7406
  async function readFrom(file, position, length) {
5744
7407
  const bytes = Buffer.alloc(Math.max(0, length));
5745
7408
  for (let read = 0; read < bytes.length;) {
@@ -5758,6 +7421,77 @@ async function writeAll(file, bytes) {
5758
7421
  at += bytesWritten;
5759
7422
  }
5760
7423
  }
7424
+ /**
7425
+ * Renames `from` over `to`. On Windows, an unlocked reader that holds `to` open for a moment causes `rename` to fail
7426
+ * with `EPERM`, `EBUSY` or `EACCES`, so retry with short backoff until the reader closes its handle.
7427
+ */
7428
+ async function renameOver(from, to) {
7429
+ for (let attempt = 0;; attempt++) try {
7430
+ await rename(from, to);
7431
+ return;
7432
+ } catch (cause) {
7433
+ const code = cause.code ?? "";
7434
+ if (process.platform !== "win32" || !TRANSIENT_RELEASE_CODES.has(code) || attempt >= LOCK_BACKOFF_MS.length) throw cause;
7435
+ await setTimeout$1(LOCK_BACKOFF_MS[attempt]);
7436
+ }
7437
+ }
7438
+ /** Writes `payload` to a new file at `path` and syncs it, before the caller links or renames it into place. */
7439
+ async function writeSynced(path, payload) {
7440
+ const handle = await open(path, "wx");
7441
+ try {
7442
+ await handle.writeFile(payload);
7443
+ await syncFile(handle);
7444
+ } finally {
7445
+ await handle.close();
7446
+ }
7447
+ }
7448
+ /** Makes the directory at `path` and those above it that are missing, and syncs the directory naming each it made. */
7449
+ async function makeDirectory(path) {
7450
+ const made = await mkdir(path, { recursive: true });
7451
+ if (made === void 0) return;
7452
+ for (let directory = path;; directory = dirname$1(directory)) {
7453
+ await syncDirectory(dirname$1(directory));
7454
+ if (directory === made || dirname$1(directory) === directory) return;
7455
+ }
7456
+ }
7457
+ async function readFirstLineWithTailFrom(file, firstReadBytes, maxBytes) {
7458
+ const chunks = [];
7459
+ let position = 0;
7460
+ let headerWitness = Buffer.alloc(0);
7461
+ let headerEnd = 0;
7462
+ let headerTerminated = false;
7463
+ let remainder = Buffer.alloc(0);
7464
+ for (let length = firstReadBytes; position < maxBytes; length = HEADER_READ_CHUNK_BYTES) {
7465
+ const toRead = Math.min(length, maxBytes - position);
7466
+ const buffer = Buffer.allocUnsafe(toRead);
7467
+ const { bytesRead } = await file.read(buffer, 0, toRead, position);
7468
+ if (!bytesRead) throw new Error(`Session file ended before byte ${maxBytes}`);
7469
+ const slice = buffer.subarray(0, bytesRead);
7470
+ const newline = slice.indexOf(10);
7471
+ if (newline !== -1) {
7472
+ chunks.push(slice.subarray(0, newline));
7473
+ headerWitness = witnessAfter(headerWitness, slice.subarray(0, newline + 1));
7474
+ headerEnd = position + newline + 1;
7475
+ headerTerminated = true;
7476
+ remainder = slice.subarray(newline + 1);
7477
+ position += bytesRead;
7478
+ break;
7479
+ }
7480
+ chunks.push(slice);
7481
+ headerWitness = witnessAfter(headerWitness, slice);
7482
+ position += bytesRead;
7483
+ headerEnd = position;
7484
+ }
7485
+ const value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
7486
+ return {
7487
+ stored: value !== null && typeof value === "object" && !Array.isArray(value) ? value : {},
7488
+ headerEnd,
7489
+ headerWitness,
7490
+ headerTerminated,
7491
+ remainder,
7492
+ nextOffset: position
7493
+ };
7494
+ }
5761
7495
  async function readFirstLineFrom(file, firstReadBytes, start = null) {
5762
7496
  const chunks = [];
5763
7497
  let position = start;
@@ -5793,6 +7527,135 @@ async function witnessHolds(path, jsonl, kept) {
5793
7527
  return false;
5794
7528
  }
5795
7529
  }
7530
+ function chooseCheckpointStride(size, initial = CHECKPOINT_INITIAL_STRIDE) {
7531
+ let stride = initial;
7532
+ while (size > stride && Math.floor((size - 1) / stride) > MAX_CHECKPOINTS) stride *= 2;
7533
+ return stride;
7534
+ }
7535
+ function thinCheckpoints(stride, checkpoints) {
7536
+ while (checkpoints.length > MAX_CHECKPOINTS) {
7537
+ stride *= 2;
7538
+ checkpoints = checkpoints.filter((cp) => cp.offset % stride === 0);
7539
+ }
7540
+ return {
7541
+ stride,
7542
+ checkpoints
7543
+ };
7544
+ }
7545
+ function checkpointsFromBuffer(size, bytes) {
7546
+ const stride = chooseCheckpointStride(size);
7547
+ const checkpoints = [];
7548
+ for (let offset = stride; offset < size; offset += stride) {
7549
+ const start = Math.max(0, offset - CHECKPOINT_HALF_BYTES);
7550
+ const end = Math.min(size, offset + CHECKPOINT_HALF_BYTES);
7551
+ checkpoints.push({
7552
+ offset,
7553
+ bytes: Buffer.from(bytes.subarray(start, end))
7554
+ });
7555
+ }
7556
+ return {
7557
+ stride,
7558
+ checkpoints
7559
+ };
7560
+ }
7561
+ function extendCheckpointsFromBuffer(initialStride, existing, previousSize, size, bufferOffset, buffer) {
7562
+ const stride = Math.max(CHECKPOINT_INITIAL_STRIDE, initialStride);
7563
+ const checkpoints = [...existing];
7564
+ const firstOffset = Math.max(stride, Math.ceil(previousSize / stride) * stride);
7565
+ for (let offset = firstOffset; offset < size; offset += stride) {
7566
+ if (checkpoints.at(-1)?.offset === offset) continue;
7567
+ const start = Math.max(0, offset - CHECKPOINT_HALF_BYTES);
7568
+ const end = Math.min(size, offset + CHECKPOINT_HALF_BYTES);
7569
+ if (start < bufferOffset || end > bufferOffset + buffer.length) continue;
7570
+ checkpoints.push({
7571
+ offset,
7572
+ bytes: Buffer.from(buffer.subarray(start - bufferOffset, end - bufferOffset))
7573
+ });
7574
+ }
7575
+ return thinCheckpoints(stride, checkpoints);
7576
+ }
7577
+ async function extendCheckpointsFromHandle(file, initialStride, existing, previousSize, size) {
7578
+ const stride = chooseCheckpointStride(size, Math.max(CHECKPOINT_INITIAL_STRIDE, initialStride));
7579
+ const checkpoints = existing.filter((cp) => cp.offset % stride === 0);
7580
+ const offsets = [];
7581
+ const firstOffset = Math.max(stride, Math.ceil(previousSize / stride) * stride);
7582
+ for (let offset = firstOffset; offset < size; offset += stride) {
7583
+ if (checkpoints.at(-1)?.offset === offset) continue;
7584
+ offsets.push(offset);
7585
+ }
7586
+ const read = await Promise.all(offsets.map(async (offset) => {
7587
+ const start = Math.max(0, offset - CHECKPOINT_HALF_BYTES);
7588
+ return {
7589
+ offset,
7590
+ bytes: await readFrom(file, start, Math.min(size, offset + CHECKPOINT_HALF_BYTES) - start)
7591
+ };
7592
+ }));
7593
+ checkpoints.push(...read);
7594
+ return thinCheckpoints(stride, checkpoints);
7595
+ }
7596
+ /** Captures the tail witness and mid-file integrity checks (`prefixHash` for <= 256 KiB, straddling checkpoints above). */
7597
+ async function captureIntegrity(file, size, spans) {
7598
+ if (size <= PREFIX_HASH_MAX_BYTES) {
7599
+ const all = size === 0 ? Buffer.alloc(0) : await readFrom(file, 0, size);
7600
+ const { stride, checkpoints } = checkpointsFromBuffer(size, all);
7601
+ const headWitness = spans.length >= 2 ? Buffer.from(all.subarray(spans[0], Math.min(size, spans[0] + HEAD_WITNESS_BYTES))) : void 0;
7602
+ return {
7603
+ witness: witnessOf(all),
7604
+ prefixHash: createHash("sha256").update(all).digest("hex"),
7605
+ headWitness,
7606
+ checkpointStride: stride,
7607
+ checkpoints
7608
+ };
7609
+ }
7610
+ const stride = chooseCheckpointStride(size);
7611
+ const offsets = [];
7612
+ for (let offset = stride; offset < size; offset += stride) offsets.push(offset);
7613
+ const [witness, headWitness, ...checkpointBytes] = await Promise.all([
7614
+ witnessAt(file, size),
7615
+ spans.length >= 2 ? readFrom(file, spans[0], Math.min(HEAD_WITNESS_BYTES, size - spans[0])) : Promise.resolve(void 0),
7616
+ ...offsets.map((offset) => {
7617
+ const start = Math.max(0, offset - CHECKPOINT_HALF_BYTES);
7618
+ return readFrom(file, start, Math.min(size, offset + CHECKPOINT_HALF_BYTES) - start);
7619
+ })
7620
+ ]);
7621
+ return {
7622
+ witness,
7623
+ headWitness,
7624
+ checkpointStride: stride,
7625
+ checkpoints: offsets.map((offset, i) => ({
7626
+ offset,
7627
+ bytes: checkpointBytes[i]
7628
+ }))
7629
+ };
7630
+ }
7631
+ /**
7632
+ * Verifies a cold `.idx` sidecar loaded from disk against the session file's bytes, catching both tail mismatches and
7633
+ * lost earlier pages whose tail witness survived a crash (#6717).
7634
+ */
7635
+ async function integrityHolds(path, jsonl, kept) {
7636
+ const file = kept ?? await open(path, "r").catch(() => void 0);
7637
+ if (!file) return false;
7638
+ try {
7639
+ if (jsonl.prefixHash !== void 0) {
7640
+ const all = jsonl.size === 0 ? Buffer.alloc(0) : await readFrom(file, 0, jsonl.size);
7641
+ return witnessOf(all).equals(jsonl.witness) && createHash("sha256").update(all).digest("hex") === jsonl.prefixHash;
7642
+ }
7643
+ const checks = [witnessAt(file, jsonl.size).then((actual) => actual.equals(jsonl.witness))];
7644
+ if (jsonl.headWitness !== void 0 && jsonl.spans.length >= 2) {
7645
+ const headStart = jsonl.spans[0];
7646
+ checks.push(readFrom(file, headStart, jsonl.headWitness.length).then((actual) => actual.equals(jsonl.headWitness)));
7647
+ }
7648
+ for (const cp of jsonl.checkpoints) {
7649
+ const start = Math.max(0, cp.offset - CHECKPOINT_HALF_BYTES);
7650
+ checks.push(readFrom(file, start, cp.bytes.length).then((actual) => actual.equals(cp.bytes)));
7651
+ }
7652
+ return (await Promise.all(checks)).every(Boolean);
7653
+ } catch {
7654
+ return false;
7655
+ } finally {
7656
+ if (kept === void 0) await file.close().catch(() => void 0);
7657
+ }
7658
+ }
5796
7659
  function encodeDeltas(values) {
5797
7660
  let previous = 0;
5798
7661
  return values.map((value) => {
@@ -5811,7 +7674,7 @@ function decodeDeltas(text) {
5811
7674
  }
5812
7675
  async function writeSidecar(path, jsonl) {
5813
7676
  const body = JSON.stringify({
5814
- version: 2,
7677
+ version: epochHasCreationTime(jsonl.index.epoch) ? BIRTHTIME_INDEX_VERSION : 3,
5815
7678
  identity: jsonl.identity,
5816
7679
  birthtimeNs: jsonl.birthtimeNs,
5817
7680
  headerStamp: jsonl.headerStamp,
@@ -5819,6 +7682,11 @@ async function writeSidecar(path, jsonl) {
5819
7682
  mtimeNs: jsonl.mtimeNs,
5820
7683
  size: jsonl.size,
5821
7684
  witness: jsonl.witness.toString("base64"),
7685
+ synced: jsonl.synced,
7686
+ ...jsonl.prefixHash !== void 0 ? { prefixHash: jsonl.prefixHash } : {},
7687
+ ...jsonl.headWitness !== void 0 ? { headWitness: jsonl.headWitness.toString("base64") } : {},
7688
+ checkpointStride: jsonl.checkpointStride,
7689
+ checkpoints: jsonl.checkpoints.map((cp) => [cp.offset, cp.bytes.toString("base64")]),
5822
7690
  terminated: jsonl.terminated,
5823
7691
  torn: jsonl.torn,
5824
7692
  spans: encodeDeltas(jsonl.spans),
@@ -5837,6 +7705,22 @@ async function writeSidecar(path, jsonl) {
5837
7705
  return false;
5838
7706
  }
5839
7707
  }
7708
+ function validCheckpoints(value, size) {
7709
+ if (!Array.isArray(value)) return void 0;
7710
+ const checkpoints = [];
7711
+ for (const item of value) {
7712
+ if (!Array.isArray(item) || item.length !== 2) return void 0;
7713
+ const [offset, encoded] = item;
7714
+ if (typeof offset !== "number" || !Number.isSafeInteger(offset) || offset <= 0 || offset >= size || typeof encoded !== "string") return void 0;
7715
+ const bytes = Buffer.from(encoded, "base64");
7716
+ if (bytes.length === 0 || bytes.length > 32) return void 0;
7717
+ checkpoints.push({
7718
+ offset,
7719
+ bytes
7720
+ });
7721
+ }
7722
+ return checkpoints;
7723
+ }
5840
7724
  function validForkIndex(value, last) {
5841
7725
  if (value === null || typeof value !== "object" || !("labels" in value) || !("catalog" in value)) return void 0;
5842
7726
  const seq = (n) => typeof n === "number" && Number.isSafeInteger(n) && n > 0 && n <= last;
@@ -5860,10 +7744,16 @@ async function readSidecar(path) {
5860
7744
  } catch {
5861
7745
  return;
5862
7746
  }
5863
- if (stored.version !== 2 || typeof stored.identity !== "string" || typeof stored.birthtimeNs !== "string" || typeof stored.headerStamp !== "string" || typeof stored.fileSize !== "number" || typeof stored.mtimeNs !== "string" || typeof stored.size !== "number" || typeof stored.witness !== "string" || typeof stored.terminated !== "boolean" || typeof stored.torn !== "boolean" || typeof stored.spans !== "string" || typeof stored.ids !== "string") return void 0;
7747
+ if (stored.version !== 3 && stored.version !== BIRTHTIME_INDEX_VERSION || typeof stored.identity !== "string" || typeof stored.birthtimeNs !== "string" || typeof stored.headerStamp !== "string" || typeof stored.fileSize !== "number" || typeof stored.mtimeNs !== "string" || typeof stored.size !== "number" || typeof stored.witness !== "string" || typeof stored.terminated !== "boolean" || typeof stored.torn !== "boolean" || typeof stored.spans !== "string" || typeof stored.ids !== "string") return void 0;
5864
7748
  const spans = decodeDeltas(stored.spans);
5865
7749
  const ids = decodeIdHashes(stored.ids);
5866
7750
  if (spans.length % 2 !== 0 || ids?.length !== spans.length / 2 || !isSessionResumeIndex(stored.index, spans.length / 2)) return void 0;
7751
+ const synced = stored.synced === true;
7752
+ const prefixHash = typeof stored.prefixHash === "string" && /^[0-9a-f]{64}$/.test(stored.prefixHash) ? stored.prefixHash : void 0;
7753
+ const headWitness = typeof stored.headWitness === "string" ? Buffer.from(stored.headWitness, "base64") : void 0;
7754
+ const checkpointStride = typeof stored.checkpointStride === "number" && Number.isSafeInteger(stored.checkpointStride) && stored.checkpointStride >= CHECKPOINT_INITIAL_STRIDE ? stored.checkpointStride : CHECKPOINT_INITIAL_STRIDE;
7755
+ const checkpoints = validCheckpoints(stored.checkpoints, stored.size);
7756
+ if (synced && (checkpoints === void 0 || stored.size <= PREFIX_HASH_MAX_BYTES && prefixHash === void 0 || stored.size > PREFIX_HASH_MAX_BYTES && stored.size > checkpointStride && checkpoints.length === 0)) return void 0;
5867
7757
  return {
5868
7758
  identity: stored.identity,
5869
7759
  birthtimeNs: stored.birthtimeNs,
@@ -5872,6 +7762,11 @@ async function readSidecar(path) {
5872
7762
  mtimeNs: stored.mtimeNs,
5873
7763
  size: stored.size,
5874
7764
  witness: Buffer.from(stored.witness, "base64"),
7765
+ synced,
7766
+ prefixHash,
7767
+ headWitness,
7768
+ checkpointStride,
7769
+ checkpoints: checkpoints ?? [],
5875
7770
  terminated: stored.terminated,
5876
7771
  torn: stored.torn,
5877
7772
  spans,
@@ -7835,7 +9730,7 @@ function readSessionHeader(filePath) {
7835
9730
  }
7836
9731
  async function readSessionHeaderAsync(filePath) {
7837
9732
  try {
7838
- const file = await open$1(filePath, "r");
9733
+ const file = await open$2(filePath, "r");
7839
9734
  try {
7840
9735
  const line = new SessionHeaderLine();
7841
9736
  const buffer = Buffer.allocUnsafe(HEADER_READ_BUFFER_SIZE);
@@ -8360,7 +10255,7 @@ function __atomicOnDemandFailed(error, feature) {
8360
10255
  return (async () => {
8361
10256
  const root = new URL("../", import.meta.url);
8362
10257
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
8363
- const key = `${root.href}#0.10.11-alpha.2`;
10258
+ const key = `${root.href}#0.10.11`;
8364
10259
  let release = releases.get(key);
8365
10260
  if (release === undefined) {
8366
10261
  const current = (async () => {
@@ -8388,7 +10283,7 @@ function __atomicOnDemandFailed(error, feature) {
8388
10283
  } catch {
8389
10284
  // No installation to read, as in a bundle of the package: the release the process runs decides.
8390
10285
  }
8391
- const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.2" ? installed : running !== undefined && running.version !== "0.10.11-alpha.2" ? "0.10.11-alpha.2" : undefined;
10286
+ const updatedTo = typeof installed === "string" && installed !== "0.10.11" ? installed : running !== undefined && running.version !== "0.10.11" ? "0.10.11" : undefined;
8392
10287
  if (updatedTo === undefined) throw error;
8393
10288
  const application = typeof running?.name === "string" ? running.name : "atomic";
8394
10289
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {