@bastani/atomic 0.10.11-alpha.3 → 0.10.11-alpha.4

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 (288) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/dist/_shared/dist-KOELCESV.js +2 -2
  3. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  4. package/dist/_shared/lib-4PES5P4V.js +2 -2
  5. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +4 -4
  6. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +4 -4
  7. package/dist/_shared/mode-shared-2QJSCUM6.js +4 -4
  8. package/dist/_shared/p1a-prewarm-XIU57JHF.js +3 -3
  9. package/dist/_shared/p1b-elig-TVB5CBLL.js +22 -6
  10. package/dist/_shared/p1b-elig-TVB5CBLL.js.map +1 -1
  11. package/dist/_shared/p2-shell-main-B2WIALFD.js +6 -3
  12. package/dist/_shared/p2-shell-main-B2WIALFD.js.map +1 -1
  13. package/dist/_shared/runtime-O4KCSG4C.js +2 -2
  14. package/dist/_shared/sdk-B5LEWGGI.js +899 -515
  15. package/dist/_shared/sdk-B5LEWGGI.js.map +1 -1
  16. package/dist/_shared/session-data-AHTU7IS6.js +2 -2
  17. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  18. package/dist/_shared/{startup-0-0-EZUKEP4Q.js → startup-0-0-XJJDOIEC.js} +6 -12
  19. package/dist/_shared/{startup-0-0-EZUKEP4Q.js.map → startup-0-0-XJJDOIEC.js.map} +1 -1
  20. package/dist/_shared/{startup-0-1-RTOHJFDJ.js → startup-0-1-M6OWAYHH.js} +354 -103
  21. package/dist/_shared/startup-0-1-M6OWAYHH.js.map +1 -0
  22. package/dist/_shared/startup-0-2-5QHPCEON.js +18 -9
  23. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -1
  24. package/dist/_shared/startup-0-3-4ZYBYQNM.js +4 -4
  25. package/dist/_shared/startup-0-4-ZMJV547D.js +4 -4
  26. package/dist/_shared/startup-0-5-YDW47QX6.js +4 -4
  27. package/dist/_shared/startup-10-0-TDQNBDDL.js +4 -4
  28. package/dist/_shared/startup-12-0-55AAXBJZ.js +1 -1
  29. package/dist/_shared/startup-14-0-MLX36RBG.js +2 -2
  30. package/dist/_shared/startup-15-0-YUKGAC63.js +2 -2
  31. package/dist/_shared/startup-15-1-4S7FLMNG.js +4 -4
  32. package/dist/_shared/startup-8-0-34CBHPZH.js +2114 -235
  33. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  34. package/dist/_shared/startup-8-1-LZFXSD3Z.js +12 -12
  35. package/dist/_shared/storage-command-7MGXLJGZ.js +6 -6
  36. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  37. package/dist/_shared/storage-status-K7PX2RXA.js +2 -2
  38. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  39. package/dist/_shared/team-DOQKICG2.js +1 -1
  40. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  41. package/dist/builtin/intercom/CHANGELOG.md +19 -0
  42. package/dist/builtin/intercom/broker/broker.bundle.mjs +1020 -108
  43. package/dist/builtin/intercom/broker/client.ts +8 -0
  44. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +91 -14
  45. package/dist/builtin/intercom/broker/multinode-router.ts +102 -17
  46. package/dist/builtin/intercom/broker/multinode-state-store.ts +41 -2
  47. package/dist/builtin/intercom/broker/send-order-gate.ts +5 -2
  48. package/dist/builtin/intercom/broker/sql-add-column.ts +22 -1
  49. package/dist/builtin/intercom/broker/sql-lease-store.ts +304 -48
  50. package/dist/builtin/intercom/broker/sql-outbox-store.ts +541 -50
  51. package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +239 -8
  52. package/dist/builtin/intercom/broker/sql-retention.ts +11 -2
  53. package/dist/builtin/intercom/broker/sql-schema.ts +42 -8
  54. package/dist/builtin/intercom/index.bundle.mjs +13 -2
  55. package/dist/builtin/intercom/package.json +1 -1
  56. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  57. package/dist/builtin/mcp/package.json +1 -1
  58. package/dist/builtin/subagents/CHANGELOG.md +6 -0
  59. package/dist/builtin/subagents/package.json +1 -1
  60. package/dist/builtin/subagents/skills/skill-creator/eval-viewer/generate_review.py +8 -1
  61. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  62. package/dist/builtin/web-access/index.bundle.mjs +1 -1
  63. package/dist/builtin/web-access/package.json +1 -1
  64. package/dist/cli/args.js +2 -2
  65. package/dist/cli/auth-cli.code.js +2 -2
  66. package/dist/cli/auth-cli.impl.js +3 -3
  67. package/dist/cli/auth-cli.js +3 -3
  68. package/dist/cli/blueprint-command.code.js +1 -1
  69. package/dist/cli/blueprint-command.impl.js +3 -3
  70. package/dist/cli/blueprint-command.js +3 -3
  71. package/dist/cli/intercom-command.code.js +2 -2
  72. package/dist/cli/intercom-command.impl.js +3 -3
  73. package/dist/cli/intercom-command.js +3 -3
  74. package/dist/cli/list-models.code.js +2 -2
  75. package/dist/cli/list-models.impl.js +3 -3
  76. package/dist/cli/list-models.js +3 -3
  77. package/dist/cli/session-picker.code.js +1 -1
  78. package/dist/cli/session-picker.impl.js +3 -3
  79. package/dist/cli/session-picker.js +3 -3
  80. package/dist/cli/startup-ui.code.js +1 -1
  81. package/dist/cli/startup-ui.impl.js +3 -3
  82. package/dist/cli/startup-ui.js +3 -3
  83. package/dist/cli/storage-command.impl.js +3 -3
  84. package/dist/cli/storage-command.js +3 -3
  85. package/dist/cli/storage-search-session.code.js +1 -1
  86. package/dist/cli/storage-search-session.impl.js +3 -3
  87. package/dist/cli/storage-search-session.js +3 -3
  88. package/dist/cli/team-command.code.js +1 -1
  89. package/dist/cli/team-command.impl.js +3 -3
  90. package/dist/cli/team-command.js +3 -3
  91. package/dist/cli.js +2 -2
  92. package/dist/core/debug.impl.js +3 -3
  93. package/dist/core/debug.js +3 -3
  94. package/dist/core/export-html/card-projection.impl.js +3 -3
  95. package/dist/core/export-html/card-projection.js +3 -3
  96. package/dist/core/export-html/index.code.js +4 -4
  97. package/dist/core/export-html/index.code.js.map +1 -1
  98. package/dist/core/export-html/index.impl.js +3 -3
  99. package/dist/core/export-html/index.js +3 -3
  100. package/dist/core/export-html/json-spans.impl.js +3 -3
  101. package/dist/core/export-html/json-spans.js +3 -3
  102. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  103. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  104. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  105. package/dist/core/export-html/tool-renderer.js +3 -3
  106. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  107. package/dist/core/extensions/jiti-loader.js +3 -3
  108. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  109. package/dist/core/extensions/jiti-static-loader.js +3 -3
  110. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  111. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  112. package/dist/core/extensions/loader-host-modules.js +3 -3
  113. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  114. package/dist/core/extensions/runner-context.js +1 -1
  115. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  116. package/dist/core/intercom-broker-control-host.js +3 -3
  117. package/dist/core/intercom-broker-control.code.js +3 -3
  118. package/dist/core/intercom-broker-control.impl.js +3 -3
  119. package/dist/core/intercom-broker-control.js +3 -3
  120. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  121. package/dist/core/package-manager-storage-adapters.js +3 -3
  122. package/dist/core/process-start-token.d.ts +5 -4
  123. package/dist/core/sdk.code.js +2 -2
  124. package/dist/core/sdk.impl.js +3 -3
  125. package/dist/core/sdk.js +3 -3
  126. package/dist/core/session-manager-core.js +4 -4
  127. package/dist/core/session-manager-list.impl.js +3 -3
  128. package/dist/core/session-manager-list.js +3 -3
  129. package/dist/core/session-manager.code.js +1 -1
  130. package/dist/core/session-manager.impl.js +3 -3
  131. package/dist/core/session-manager.js +3 -3
  132. package/dist/core/session-storage.impl.js +3 -3
  133. package/dist/core/session-storage.js +3 -3
  134. package/dist/core/storage/database.d.ts +6 -0
  135. package/dist/core/storage/database.js.map +1 -1
  136. package/dist/core/storage/fenced-paths.d.ts +7 -6
  137. package/dist/core/storage/fenced-paths.js +7 -6
  138. package/dist/core/storage/fenced-paths.js.map +1 -1
  139. package/dist/core/storage/index.js +2 -2
  140. package/dist/core/storage/node-sqlite-thread.js +209 -19
  141. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  142. package/dist/core/storage/node-sqlite.js +435 -71
  143. package/dist/core/storage/node-sqlite.js.map +1 -1
  144. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  145. package/dist/core/storage/offline-snapshot-file.js +3 -3
  146. package/dist/core/storage/provider.js +2 -2
  147. package/dist/core/storage/schema-catalog.d.ts +69 -7
  148. package/dist/core/storage/schema-catalog.js +352 -61
  149. package/dist/core/storage/schema-catalog.js.map +1 -1
  150. package/dist/core/storage/selection.js +2 -2
  151. package/dist/core/storage/session/branch-fork-source.code.js +2 -2
  152. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  153. package/dist/core/storage/session/branch-fork-source.js +3 -3
  154. package/dist/core/storage/session/card-view.impl.js +3 -3
  155. package/dist/core/storage/session/card-view.js +3 -3
  156. package/dist/core/storage/session/child-reader.code.js +3 -3
  157. package/dist/core/storage/session/child-reader.impl.js +3 -3
  158. package/dist/core/storage/session/child-reader.js +3 -3
  159. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  160. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  161. package/dist/core/storage/session/expanded-child-details.code.js +2 -2
  162. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  163. package/dist/core/storage/session/expanded-child-details.js +3 -3
  164. package/dist/core/storage/session/fork-detach.d.ts +11 -1
  165. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  166. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  167. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  168. package/dist/core/storage/session/fork-row-index.js +3 -3
  169. package/dist/core/storage/session/fork-staging.code.js +1 -1
  170. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  171. package/dist/core/storage/session/fork-staging.js +3 -3
  172. package/dist/core/storage/session/fork-sweep.js +31 -7
  173. package/dist/core/storage/session/fork-sweep.js.map +1 -1
  174. package/dist/core/storage/session/fork-window.code.js +3 -3
  175. package/dist/core/storage/session/fork-window.impl.js +3 -3
  176. package/dist/core/storage/session/fork-window.js +3 -3
  177. package/dist/core/storage/session/history-pages.impl.js +3 -3
  178. package/dist/core/storage/session/history-pages.js +3 -3
  179. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  180. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  181. package/dist/core/storage/session/jsonl-session-lock.d.ts +100 -0
  182. package/dist/core/storage/session/jsonl-session-store.d.ts +41 -23
  183. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  184. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  185. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  186. package/dist/core/storage/session/memory-session-store.js +3 -3
  187. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  188. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  189. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  190. package/dist/core/storage/session/released-history-files.code.js +8 -8
  191. package/dist/core/storage/session/released-history-files.code.js.map +1 -1
  192. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  193. package/dist/core/storage/session/released-history-files.js +3 -3
  194. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  195. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  196. package/dist/core/storage/session/session-resume.impl.js +3 -3
  197. package/dist/core/storage/session/session-resume.js +3 -3
  198. package/dist/core/storage/session/session-search-index.d.ts +9 -1
  199. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  200. package/dist/core/storage/session/snapshot-cut.js +3 -3
  201. package/dist/core/storage/session/snapshot-history.code.js +3 -3
  202. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  203. package/dist/core/storage/session/snapshot-history.js +3 -3
  204. package/dist/core/storage/session/sql-session-store.d.ts +51 -7
  205. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  206. package/dist/core/storage/session/sql-session-store.js +3 -3
  207. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  208. package/dist/core/storage/session/tree-outline.js +3 -3
  209. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  210. package/dist/core/storage/session/tree-presentation.js +3 -3
  211. package/dist/core/storage/sqlite-facade.d.ts +6 -0
  212. package/dist/core/storage/sqlite-facade.js +309 -33
  213. package/dist/core/storage/sqlite-facade.js.map +1 -1
  214. package/dist/core/storage/sqlite-open-batch.js +10 -0
  215. package/dist/core/storage/sqlite-open-batch.js.map +1 -0
  216. package/dist/core/storage/storage-status.impl.js +3 -3
  217. package/dist/core/storage/storage-status.js +3 -3
  218. package/dist/core/storage/team.impl.js +3 -3
  219. package/dist/core/storage/team.js +3 -3
  220. package/dist/core/structured-output/index.impl.js +3 -3
  221. package/dist/core/structured-output/index.js +3 -3
  222. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  223. package/dist/core/tasks/task-completion-entry.js +3 -3
  224. package/dist/core/tasks/task-file-history.code.js +3 -3
  225. package/dist/core/tasks/task-file-history.impl.js +3 -3
  226. package/dist/core/tasks/task-file-history.js +3 -3
  227. package/dist/core/tasks/task-reference-archive.code.js +3 -3
  228. package/dist/core/tasks/task-reference-archive.js +3 -3
  229. package/dist/core/tasks/task-reference-identity.js +3 -3
  230. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  231. package/dist/core/tasks/task-reference-stream.js +3 -3
  232. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  233. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  234. package/dist/core/tasks/task-view-source.impl.js +3 -3
  235. package/dist/core/tasks/task-view-source.js +3 -3
  236. package/dist/core/tools/read-url.code.js +2 -2
  237. package/dist/core/tools/read-url.impl.js +3 -3
  238. package/dist/core/tools/read-url.js +3 -3
  239. package/dist/core/worktree-snapshot/blob-store.d.ts +5 -3
  240. package/dist/core/worktree-snapshot/blob-store.js +151 -21
  241. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  242. package/dist/core/worktree-snapshot/errors.code.js +2 -2
  243. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  244. package/dist/core/worktree-snapshot/errors.js +3 -3
  245. package/dist/core/worktree-snapshot/fork-snapshot-index.js +158 -41
  246. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -1
  247. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  248. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  249. package/dist/extensions/codemode/execute.code.js +1 -1
  250. package/dist/extensions/codemode/execute.impl.js +3 -3
  251. package/dist/extensions/codemode/execute.js +3 -3
  252. package/dist/extensions/codemode/renderer.code.js +1 -1
  253. package/dist/extensions/codemode/renderer.impl.js +3 -3
  254. package/dist/extensions/codemode/renderer.js +3 -3
  255. package/dist/extensions/mcp/cli.code.js +1 -1
  256. package/dist/extensions/mcp/cli.impl.js +3 -3
  257. package/dist/extensions/mcp/cli.js +3 -3
  258. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  259. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  260. package/dist/extensions/mcp/cli.lazy.js +3 -3
  261. package/dist/extensions/mcp/runtime.impl.js +3 -3
  262. package/dist/extensions/mcp/runtime.js +3 -3
  263. package/dist/index.js +2 -2
  264. package/dist/main-first-time-setup.code.js +1 -1
  265. package/dist/main-first-time-setup.impl.js +3 -3
  266. package/dist/main-first-time-setup.js +3 -3
  267. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  268. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  269. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  270. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  271. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  272. package/dist/package-manager-cli.code.js +4 -4
  273. package/dist/package-manager-cli.impl.js +3 -3
  274. package/dist/package-manager-cli.js +3 -3
  275. package/dist/rpc-entry.js +1 -1
  276. package/dist/startup-files.json +1 -1
  277. package/dist/startup-stages/3.js +1 -1
  278. package/dist/startup-stages/5.js +1 -1
  279. package/dist/utils/startup-database-spare.code.js +2 -2
  280. package/dist/utils/startup-database-spare.impl.js +3 -3
  281. package/dist/utils/startup-database-spare.js +3 -3
  282. package/dist/utils/tools-manager.code.js +1 -1
  283. package/dist/utils/tools-manager.impl.js +3 -3
  284. package/dist/utils/tools-manager.js +3 -3
  285. package/docs/changelog.mdx +49 -0
  286. package/docs/storage/jsonl.md +3 -3
  287. package/package.json +8 -8
  288. package/dist/_shared/startup-0-1-RTOHJFDJ.js.map +0 -1
@@ -1,25 +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, epochHasCreationTime, fileEpochOf, firstChatOrders, getErrnoCode, historySnapshotFor, inheritForkScope, isClassifiedWorkflowSession, legacyFileEpochOf, materializeSessionSummaryMetadata, noteSnapshotGeneration, observeReferenceCut, readLines, referenceMetadataRead, registerArchiveLoad, registerForkScope, require_sha256, sha256Hex, summarizeSession, yieldTurn } from "./startup-0-0-EZUKEP4Q.js";
4
- import { AgentRehydrateError, AgentReleaseConfigError, SessionKeyDigests, appendFileChatRecord, deleteFileChatRecords, hasFileChatRecords, latestLegacyMessageTime, legacyCompletionTarget, readFileChatOrders, readFileChatRecords, rememberEarlierCompletion, summarizeLegacySession } from "./startup-0-1-RTOHJFDJ.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 { learnCreationTime } from "../core/storage/creation-time.js";
22
+ import { fileGenerationOf, learnCreationTime } from "../core/storage/creation-time.js";
23
23
  import { openNodeSqliteDatabase } from "../core/storage/node-sqlite.js";
24
24
  import { StringDecoder } from "string_decoder";
25
25
  // dist/core/storage/session/validation.js
@@ -2372,6 +2372,46 @@ async function* historyChunks(store, sessionId, epoch, reference, options) {
2372
2372
  if (offset < reference.bytes) await yieldSessionTurn();
2373
2373
  }
2374
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
+ }
2375
2415
  // dist/core/storage/session/jsonl-entry-projection.js
2376
2416
  /**
2377
2417
  * One byte-level pass over an oversized saved entry. It checks the JSON text as `JSON.parse` would and keeps only the
@@ -2962,6 +3002,637 @@ async function* branchStatePages(lastSeq, source, prefixToolCalls) {
2962
3002
  if (seq <= lastSeq) await yieldSessionTurn();
2963
3003
  }
2964
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
+ }
2965
3636
  // dist/core/storage/session/legacy-format.js
2966
3637
  function isEarlyFormat4Header(stored) {
2967
3638
  return stored.version === 4 && typeof stored.createdAt !== "string" && typeof stored.timestamp === "string";
@@ -3083,6 +3754,8 @@ const KEEP_APPEND_FILES = process.platform !== "win32";
3083
3754
  const KEPT_FILE_IDLE_MS = 3e4;
3084
3755
  /** The most handles one store keeps open; the least recently used is closed first. */
3085
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;
3086
3759
  function isForkCatalogType(type) {
3087
3760
  return type === "session_info" || type === "session_summary" || type === "branch_summary";
3088
3761
  }
@@ -3127,6 +3800,20 @@ const SIDECAR_REFRESH_BYTES = 1048576;
3127
3800
  const INDEX_BATCH_ENTRIES = 512;
3128
3801
  const READ_GAP_BYTES = 65536;
3129
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
+ }
3130
3817
  /** The last 64 bytes, which locate the boundary a later append starts from. */
3131
3818
  function witnessOf(bytes) {
3132
3819
  return Buffer.from(bytes.subarray(-64));
@@ -3182,6 +3869,7 @@ async function rangeIndexHolds(file, index, marks, signal) {
3182
3869
  }
3183
3870
  function isBlankLine(line) {
3184
3871
  for (const byte of line) {
3872
+ if (byte === 0) return false;
3185
3873
  if (byte > 32 && byte < 128) return false;
3186
3874
  if (byte >= 128) return line.toString("utf8").trim() === "";
3187
3875
  }
@@ -3219,6 +3907,7 @@ async function scanSessionLines(file, size, atEnd, from, index, signal, visitor)
3219
3907
  let parts = [];
3220
3908
  let partsBytes = 0;
3221
3909
  let completeLineRetained = true;
3910
+ let lineHasNul = false;
3222
3911
  let reader;
3223
3912
  let mode = header ? "header" : "blank";
3224
3913
  const startLine = (offset) => {
@@ -3228,6 +3917,7 @@ async function scanSessionLines(file, size, atEnd, from, index, signal, visitor)
3228
3917
  parts = [];
3229
3918
  partsBytes = 0;
3230
3919
  completeLineRetained = true;
3920
+ lineHasNul = false;
3231
3921
  reader = void 0;
3232
3922
  mode = header ? "header" : "blank";
3233
3923
  };
@@ -3272,6 +3962,7 @@ async function scanSessionLines(file, size, atEnd, from, index, signal, visitor)
3272
3962
  const take = (segment) => {
3273
3963
  lineBytes += segment.length;
3274
3964
  if (linePrefixBytes < linePrefix.length) linePrefixBytes += segment.copy(linePrefix, linePrefixBytes);
3965
+ if (mode !== "header" && !lineHasNul && hasNulByte(segment)) lineHasNul = true;
3275
3966
  if (mode === "header" || mode === "pass") return true;
3276
3967
  keep(segment);
3277
3968
  if (mode === "typing" && reader !== void 0) {
@@ -3299,6 +3990,7 @@ async function scanSessionLines(file, size, atEnd, from, index, signal, visitor)
3299
3990
  header = false;
3300
3991
  return "next";
3301
3992
  }
3993
+ if (lineHasNul) return "stop-nul";
3302
3994
  if (mode === "blank") {
3303
3995
  if (isBlankParts(parts)) return "next";
3304
3996
  if (!classify()) return "stop-before";
@@ -3364,6 +4056,11 @@ async function scanSessionLines(file, size, atEnd, from, index, signal, visitor)
3364
4056
  if (index.completeEnd !== completeEnd) advancedAt = start;
3365
4057
  if (outcome !== "next") {
3366
4058
  keepWitness(bytes, advancedAt);
4059
+ if (outcome === "stop-nul") return {
4060
+ offset: size,
4061
+ seq: mode === "blank" ? seq : seq - 1,
4062
+ header: false
4063
+ };
3367
4064
  return outcome === "stop-before" ? {
3368
4065
  offset: lineOffset,
3369
4066
  seq,
@@ -3394,6 +4091,11 @@ async function scanSessionLines(file, size, atEnd, from, index, signal, visitor)
3394
4091
  header
3395
4092
  };
3396
4093
  const counted = mode !== "blank";
4094
+ if (lineHasNul) return {
4095
+ offset: size,
4096
+ seq: counted ? seq - 1 : seq,
4097
+ header: false
4098
+ };
3397
4099
  if (!atEnd) return {
3398
4100
  offset: lineOffset,
3399
4101
  seq: counted ? seq - 1 : seq,
@@ -3463,6 +4165,7 @@ async function lineStartFromEnd(file, end, count, signal) {
3463
4165
  position -= length;
3464
4166
  for (let at = length - 1; at >= 0; at--) {
3465
4167
  const byte = bytes[at];
4168
+ if (byte === 0) return void 0;
3466
4169
  if (byte === 10) {
3467
4170
  if (position + at === end - 1) continue;
3468
4171
  if (visible) {
@@ -3491,7 +4194,7 @@ function reportTornLine(path) {
3491
4194
  * the scan, which then resolves undefined. A line longer than one scan window is projected as it is read, never held
3492
4195
  * or decoded whole unless it is malformed, so that the parser's own diagnostic is reported.
3493
4196
  */
3494
- async function scanEntries(path, file, from, end, header, take, legacy) {
4197
+ async function scanEntries(path, file, from, end, header, take, legacy, reportTorn = true) {
3495
4198
  let invalidStructure;
3496
4199
  let invalidText;
3497
4200
  let stopped = false;
@@ -3533,9 +4236,13 @@ async function scanEntries(path, file, from, end, header, take, legacy) {
3533
4236
  let parts = [];
3534
4237
  let lineStart = from;
3535
4238
  let position = from;
4239
+ let lineHasNul = false;
4240
+ let nulTailAt;
3536
4241
  let projector;
3537
4242
  const add = (part, stop) => {
3538
4243
  if (header) return;
4244
+ if (!lineHasNul && hasNulByte(part)) lineHasNul = true;
4245
+ if (lineHasNul) return;
3539
4246
  if (projector) projector.feed(part);
3540
4247
  else if (stop - lineStart > SCAN_WINDOW_BYTES$1) {
3541
4248
  projector = entryProjector();
@@ -3577,7 +4284,10 @@ async function scanEntries(path, file, from, end, header, take, legacy) {
3577
4284
  const stop = position + newline;
3578
4285
  add(chunk.subarray(at, newline), stop);
3579
4286
  if (header) header = false;
3580
- 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);
3581
4291
  else {
3582
4292
  const short = shortLine(stop, true);
3583
4293
  if (short !== true) await short;
@@ -3585,20 +4295,35 @@ async function scanEntries(path, file, from, end, header, take, legacy) {
3585
4295
  if (stopped) return void 0;
3586
4296
  at = newline + 1;
3587
4297
  lineStart = position + at;
4298
+ lineHasNul = false;
3588
4299
  parts = [];
3589
4300
  projector = void 0;
3590
4301
  }
4302
+ if (nulTailAt !== void 0) break;
3591
4303
  if (at < chunk.length) add(chunk.subarray(at), position + chunk.length);
3592
4304
  position += chunk.length;
3593
4305
  }
3594
4306
  } finally {
3595
4307
  await next?.catch(() => void 0);
3596
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}`);
3597
4322
  const terminated = lineStart === position;
3598
- 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)));
3599
4324
  await settle();
3600
4325
  if (stopped) return void 0;
3601
- if (torn) reportTornLine(path);
4326
+ if (torn && reportTorn) reportTornLine(path);
3602
4327
  if (invalidStructure) throw invalidStructure.error;
3603
4328
  if (invalidText) throw invalidText.error;
3604
4329
  return {
@@ -3651,23 +4376,6 @@ var JsonlStoragePoisonedError = class extends Error {
3651
4376
  this.rollbackCause = rollbackCause;
3652
4377
  }
3653
4378
  };
3654
- /** Removing a lock directory fails with these on Windows while another handle, such as a scanner or indexer, holds it. */
3655
- const TRANSIENT_RELEASE_CODES = /* @__PURE__ */ new Set([
3656
- "EPERM",
3657
- "EBUSY",
3658
- "EACCES",
3659
- "ENOTEMPTY"
3660
- ]);
3661
- /** 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. */
3662
- const LOCK_BACKOFF_MS = [
3663
- 10,
3664
- 20,
3665
- 50,
3666
- 100,
3667
- 200,
3668
- 400,
3669
- 700
3670
- ];
3671
4379
  /** The name a session's file is created with: its creation time, then its id or the key of its id. */
3672
4380
  const SESSION_FILE_NAME = /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(?:-\d+)?Z_(.+)\.jsonl$/;
3673
4381
  /** Internal exact-file input for a fork, not a way to open a live or writable session by ID. */
@@ -3686,7 +4394,10 @@ var JsonlSessionStore = class JsonlSessionStore {
3686
4394
  /** Operations queued so far, counted so an append joins only a group that is still the last thing queued. */
3687
4395
  queued = 0;
3688
4396
  appendGroup;
4397
+ chatAppendGroup;
3689
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();
3690
4401
  closed = false;
3691
4402
  poisoned;
3692
4403
  directory;
@@ -3696,25 +4407,95 @@ var JsonlSessionStore = class JsonlSessionStore {
3696
4407
  has: hasFileChatRecords,
3697
4408
  read: readFileChatRecords,
3698
4409
  readOrders: readFileChatOrders,
3699
- append: (owner, anchor, record) => {
3700
- record = boundedChatRecord(record);
3701
- return this.run(async () => {
3702
- const held = await this.locate(owner.id);
3703
- if (held && held.stats.birthtimeNs > 0n && held.path === owner.file && fileEpochOf(held.stats, JSON.stringify(held.header)) === owner.epoch) await appendFileChatRecord(owner, anchor, record);
3704
- });
3705
- }
4410
+ append: (owner, anchor, record) => this.appendChatRecord(owner, anchor, boundedChatRecord(record))
3706
4411
  };
3707
4412
  return this.chatStore;
3708
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
+ }
3709
4488
  fileStates = /* @__PURE__ */ new Map();
3710
4489
  rangeIndexes = /* @__PURE__ */ new Map();
3711
4490
  indexes = /* @__PURE__ */ new Map();
3712
4491
  exactDirectory;
3713
4492
  lockFs;
4493
+ /** Stripes currently held by this store's active locked operation in `heldLockDirectory`, if narrowed. */
4494
+ heldStripes;
4495
+ heldLockDirectory;
3714
4496
  /**
3715
- * Lock directories this store acquired and could not remove, by path, with the modification time they had
3716
- * then. Nothing refreshes them any more, so another process may take them only once they are stale; until
3717
- * 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.
3718
4499
  */
3719
4500
  unreleased = /* @__PURE__ */ new Map();
3720
4501
  constructor(directory, exactDirectory, lockFs) {
@@ -3783,6 +4564,9 @@ var JsonlSessionStore = class JsonlSessionStore {
3783
4564
  store.fileStates.delete(path);
3784
4565
  store.fileStates.set(path, state);
3785
4566
  }
4567
+ }, paths === void 0 ? true : {
4568
+ kind: "files",
4569
+ paths: [...unread]
3786
4570
  });
3787
4571
  return store;
3788
4572
  }
@@ -3804,10 +4588,10 @@ var JsonlSessionStore = class JsonlSessionStore {
3804
4588
  if (await this.claimed(header.id)) throw new SessionExistsError(header.id);
3805
4589
  const payload = Buffer.from(this.encode(header, entries));
3806
4590
  const path = location === void 0 ? this.locationFor(header) : resolve$1(location);
3807
- await mkdir(resolve$1(path, ".."), { recursive: true });
4591
+ await makeDirectory(dirname$1(path));
3808
4592
  const temporary = `${path}.${randomUUID()}.tmp`;
3809
4593
  try {
3810
- await writeFile(temporary, payload, { flag: "wx" });
4594
+ await writeSynced(temporary, payload);
3811
4595
  try {
3812
4596
  await link(temporary, path);
3813
4597
  } catch (cause) {
@@ -3819,6 +4603,7 @@ var JsonlSessionStore = class JsonlSessionStore {
3819
4603
  if (cause.code !== "ENOENT") throw cause;
3820
4604
  });
3821
4605
  }
4606
+ await syncDirectory(dirname$1(path));
3822
4607
  const state = this.contentState(header, entries, payload);
3823
4608
  const stats = await this.remember(path, state);
3824
4609
  if (this.selectedFile?.id === header.id) this.selectedFile = {
@@ -3829,14 +4614,23 @@ var JsonlSessionStore = class JsonlSessionStore {
3829
4614
  lastSeq: entries.length,
3830
4615
  epoch: fileEpochOf(stats, state.headerStamp)
3831
4616
  };
3832
- }, 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
+ });
3833
4627
  }
3834
4628
  async createFork(header, entries, source, location) {
3835
4629
  if (this.create !== JsonlSessionStore.prototype.create) return void 0;
3836
4630
  validateSessionHeader(header);
3837
4631
  if (!("read" in entries)) validateSessionEntries(entries);
3838
4632
  const path = location === void 0 ? this.locationFor(header) : resolve$1(location);
3839
- await mkdir(dirname$1(path), { recursive: true });
4633
+ await makeDirectory(dirname$1(path));
3840
4634
  const temporary = `${path}.${randomUUID()}.tmp`;
3841
4635
  const handle = await open(temporary, "wx+");
3842
4636
  try {
@@ -3874,7 +4668,7 @@ var JsonlSessionStore = class JsonlSessionStore {
3874
4668
  }));
3875
4669
  const line = this.encode(header, []);
3876
4670
  let size = Buffer.byteLength(line);
3877
- let witness;
4671
+ let integrity;
3878
4672
  try {
3879
4673
  await write(Buffer.from(line));
3880
4674
  for await (const row of rows) {
@@ -3895,7 +4689,8 @@ var JsonlSessionStore = class JsonlSessionStore {
3895
4689
  size++;
3896
4690
  }
3897
4691
  await flush();
3898
- witness = await witnessAt(handle, size);
4692
+ await syncFile(handle);
4693
+ integrity = await captureIntegrity(handle, size, spans);
3899
4694
  } finally {
3900
4695
  await handle.close();
3901
4696
  }
@@ -3907,6 +4702,10 @@ var JsonlSessionStore = class JsonlSessionStore {
3907
4702
  if (cause.code === "EEXIST") throw new SessionExistsError(header.id);
3908
4703
  throw cause;
3909
4704
  }
4705
+ await unlink(temporary).catch((cause) => {
4706
+ if (cause.code !== "ENOENT") throw cause;
4707
+ });
4708
+ await syncDirectory(dirname$1(path));
3910
4709
  const headerStamp = JSON.stringify(header);
3911
4710
  const stats = await this.remember(path, {
3912
4711
  headerStamp,
@@ -3915,7 +4714,7 @@ var JsonlSessionStore = class JsonlSessionStore {
3915
4714
  lastEntryId: lastId,
3916
4715
  terminated: true,
3917
4716
  torn: false,
3918
- witness,
4717
+ witness: integrity.witness,
3919
4718
  summaryState: summary
3920
4719
  });
3921
4720
  const epoch = fileEpochOf(stats, headerStamp);
@@ -3926,7 +4725,8 @@ var JsonlSessionStore = class JsonlSessionStore {
3926
4725
  fileSize: size,
3927
4726
  mtimeNs: String(stats.mtimeNs),
3928
4727
  size,
3929
- witness,
4728
+ ...integrity,
4729
+ synced: true,
3930
4730
  terminated: true,
3931
4731
  torn: false,
3932
4732
  spans,
@@ -3936,12 +4736,15 @@ var JsonlSessionStore = class JsonlSessionStore {
3936
4736
  epoch
3937
4737
  },
3938
4738
  sidecarSize: 0
3939
- });
4739
+ }, { synced: true });
3940
4740
  return {
3941
4741
  lastSeq: ids.length,
3942
4742
  epoch
3943
4743
  };
3944
- }, true);
4744
+ }, {
4745
+ kind: "create",
4746
+ path
4747
+ });
3945
4748
  } finally {
3946
4749
  await unlink(temporary).catch((cause) => {
3947
4750
  if (cause.code !== "ENOENT") throw cause;
@@ -3951,8 +4754,10 @@ var JsonlSessionStore = class JsonlSessionStore {
3951
4754
  /**
3952
4755
  * Appends made while an earlier one waits its turn join it and commit together, as a LevelDB log writer's queue does:
3953
4756
  * under one lock, each is checked against the session as the appends before it leave it, and each file gets one write
3954
- * of all their lines. Every append is answered once its lines are written and the lock is released, as it was alone,
3955
- * 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.
3956
4761
  */
3957
4762
  append(sessionId, entries, options) {
3958
4763
  if (this.closed) return Promise.reject(new StoreClosedError$1(this.descriptor));
@@ -3975,26 +4780,59 @@ var JsonlSessionStore = class JsonlSessionStore {
3975
4780
  started: false
3976
4781
  };
3977
4782
  this.appendGroup = group;
3978
- this.run(() => this.commitAppends(group)).then(() => {
4783
+ const settle = (fallback) => {
3979
4784
  for (const { answer, resolve, reject } of group.requests) if (answer !== void 0 && "lastSeq" in answer) resolve(answer);
3980
- else reject(answer?.error);
3981
- }, (cause) => {
3982
- for (const pending of group.requests) pending.reject(cause);
3983
- });
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));
3984
4794
  group.queued = this.queued;
3985
4795
  });
3986
4796
  }
3987
4797
  async commitAppends(group) {
3988
4798
  group.started = true;
3989
4799
  if (this.appendGroup === group) this.appendGroup = void 0;
4800
+ for (const request of group.requests) request.answer = void 0;
3990
4801
  const staged = /* @__PURE__ */ new Map();
3991
- for (const request of group.requests) try {
3992
- await this.stageAppend(staged, request);
3993
- } catch (cause) {
3994
- if (this.poisoned) throw this.poisoned;
3995
- 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();
3996
4835
  }
3997
- for (const file of staged.values()) await this.writeStaged(file);
3998
4836
  }
3999
4837
  /** Checks one append against its session as the appends staged before it leave it, and stages its lines. */
4000
4838
  async stageAppend(staged, request) {
@@ -4022,6 +4860,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4022
4860
  if (entries.some((entry) => entry.type === "compaction")) {
4023
4861
  if (!await this.writeStaged(file)) {
4024
4862
  staged.delete(sessionId);
4863
+ if (this.poisoned) throw this.poisoned;
4025
4864
  throw new SessionConflictError(sessionId, options.expectSeq, file.before.lastSeq);
4026
4865
  }
4027
4866
  await copyFile(file.path, `${file.path}.${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.${randomUUID()}.compact.bak`);
@@ -4037,30 +4876,38 @@ var JsonlSessionStore = class JsonlSessionStore {
4037
4876
  }
4038
4877
  /**
4039
4878
  * Writes the lines staged for `file` through its kept handle, then decides the appends they came from: false when the
4040
- * 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.
4041
4881
  */
4042
4882
  async writeStaged(file) {
4043
4883
  const { path, before, entries, lines, requests } = file;
4044
4884
  file.entries = [];
4045
4885
  file.lines = [];
4046
4886
  file.requests = [];
4887
+ if (this.poisoned) {
4888
+ for (const { request } of requests) request.answer = { error: this.poisoned };
4889
+ return false;
4890
+ }
4047
4891
  if (entries.length === 0) {
4048
4892
  for (const { request, lastSeq } of requests) request.answer = { lastSeq };
4049
4893
  return true;
4050
4894
  }
4051
4895
  const offset = before.size;
4052
4896
  const payload = Buffer.from(`${before.terminated ? "" : "\n"}${lines.join("\n")}\n`);
4897
+ this.pinnedKeptFiles.add(path);
4053
4898
  try {
4054
4899
  const kept = await this.keptFile(path, file.identity);
4055
4900
  if (before.torn) await truncate(path, before.size);
4056
4901
  try {
4057
4902
  await writeAll(kept.handle, payload);
4903
+ await syncFile(kept.handle);
4058
4904
  } catch (cause) {
4059
4905
  try {
4060
4906
  await truncate(path, offset);
4061
4907
  } catch (rollbackCause) {
4062
- this.poisoned = new JsonlStoragePoisonedError(path, cause, rollbackCause);
4063
- throw this.poisoned;
4908
+ const poisoned = new JsonlStoragePoisonedError(path, cause, rollbackCause);
4909
+ this.poisoned ??= poisoned;
4910
+ throw poisoned;
4064
4911
  }
4065
4912
  throw cause;
4066
4913
  }
@@ -4080,15 +4927,16 @@ var JsonlSessionStore = class JsonlSessionStore {
4080
4927
  rangeIndex.seenStamp = this.stamp(stats);
4081
4928
  rangeIndex.seenSize = Number(stats.size);
4082
4929
  }
4083
- 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);
4084
4931
  if (KEEP_APPEND_FILES) this.armIdle(path, kept);
4085
4932
  else await this.closeKept(path);
4086
4933
  } catch (cause) {
4087
4934
  await this.closeKept(path);
4088
- const failure = cause === this.poisoned ? cause : this.failure(cause);
4935
+ const failure = cause instanceof JsonlStoragePoisonedError ? cause : this.failure(cause);
4089
4936
  for (const { request } of requests) request.answer = { error: failure };
4090
- if (cause === this.poisoned) throw cause;
4091
4937
  return false;
4938
+ } finally {
4939
+ this.pinnedKeptFiles.delete(path);
4092
4940
  }
4093
4941
  for (const { request, lastSeq } of requests) request.answer = { lastSeq };
4094
4942
  return true;
@@ -4103,6 +4951,9 @@ var JsonlSessionStore = class JsonlSessionStore {
4103
4951
  lastSeq: entries.length,
4104
4952
  epoch: await this.commit(path, header, entries)
4105
4953
  };
4954
+ }, {
4955
+ kind: "sessions",
4956
+ sessionIds: () => [sessionId]
4106
4957
  });
4107
4958
  }
4108
4959
  updateHeader(header, options) {
@@ -4127,12 +4978,14 @@ var JsonlSessionStore = class JsonlSessionStore {
4127
4978
  }
4128
4979
  witness = await witnessAt(output, (await output.stat()).size);
4129
4980
  await output.chmod((await stat(path)).mode & 4095);
4981
+ await syncFile(output);
4130
4982
  } finally {
4131
4983
  await output.close();
4132
4984
  }
4133
4985
  await this.forgetIndex(path);
4134
4986
  await this.closeKept(path);
4135
- await rename(temporary, path);
4987
+ await renameOver(temporary, path);
4988
+ await syncDirectory(dirname$1(path));
4136
4989
  const headerStamp = JSON.stringify(header);
4137
4990
  const stats = await this.remember(path, {
4138
4991
  ...state,
@@ -4150,6 +5003,9 @@ var JsonlSessionStore = class JsonlSessionStore {
4150
5003
  if (cause.code !== "ENOENT") throw cause;
4151
5004
  });
4152
5005
  }
5006
+ }, {
5007
+ kind: "sessions",
5008
+ sessionIds: () => [header.id]
4153
5009
  });
4154
5010
  }
4155
5011
  async commit(path, header, entries) {
@@ -4158,8 +5014,9 @@ var JsonlSessionStore = class JsonlSessionStore {
4158
5014
  const payload = Buffer.from(this.encode(header, entries));
4159
5015
  const temporary = `${path}.${randomUUID()}.tmp`;
4160
5016
  try {
4161
- await writeFile(temporary, payload, { flag: "wx" });
4162
- await rename(temporary, path);
5017
+ await writeSynced(temporary, payload);
5018
+ await renameOver(temporary, path);
5019
+ await syncDirectory(dirname$1(path));
4163
5020
  } finally {
4164
5021
  await unlink(temporary).catch((cause) => {
4165
5022
  if (cause.code !== "ENOENT") throw cause;
@@ -4169,11 +5026,37 @@ var JsonlSessionStore = class JsonlSessionStore {
4169
5026
  return fileEpochOf(await this.remember(path, state), state.headerStamp);
4170
5027
  }
4171
5028
  load(sessionId) {
4172
- 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 () => {
4173
5056
  const located = await this.locate(sessionId);
4174
5057
  if (!located) throw new SessionNotFoundError(sessionId);
4175
5058
  return this.readPersisted(located.path, located.stored);
4176
- });
5059
+ }), false);
4177
5060
  }
4178
5061
  readEntryRange(sessionId, query) {
4179
5062
  return this.run(async () => {
@@ -4393,20 +5276,137 @@ var JsonlSessionStore = class JsonlSessionStore {
4393
5276
  };
4394
5277
  }
4395
5278
  loadFile(path) {
4396
- 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);
4397
5350
  }
4398
5351
  readHeaderFile(path) {
4399
- 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);
4400
5387
  }
4401
5388
  readTail(sessionId, fromSeq) {
4402
- 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 () => {
4403
5403
  const { path, header, jsonl } = await this.indexed(sessionId);
4404
5404
  const start = Math.max(1, fromSeq);
4405
5405
  const read = await this.entriesAt(path, jsonl, [...stateSeqsBefore(jsonl.index, start), ...seqRange$1(start, jsonl.index.seq)]);
4406
5406
  const state = read.filter((held) => held.seq < start);
4407
5407
  const tail = read.filter((held) => held.seq >= start).map((held) => held.entry);
4408
5408
  return sessionTailFrom(jsonl.index, header, start, state, tail);
4409
- });
5409
+ }), false);
4410
5410
  }
4411
5411
  readChildDisplayCut(sessionId, launch) {
4412
5412
  return this.run(async () => {
@@ -4414,6 +5414,9 @@ var JsonlSessionStore = class JsonlSessionStore {
4414
5414
  const { path, jsonl } = await this.indexed(sessionId);
4415
5415
  const found = typeof launch.launchLeafId === "string" ? await this.seqInFile(path, jsonl, launch.launchLeafId) : void 0;
4416
5416
  return childDisplayCut(jsonl.index, launch, found);
5417
+ }, {
5418
+ kind: "sessions",
5419
+ sessionIds: () => [sessionId]
4417
5420
  });
4418
5421
  }
4419
5422
  /** Bind a short-lived archive reader to this exact file, including for duplicate exported IDs. */
@@ -4432,7 +5435,10 @@ var JsonlSessionStore = class JsonlSessionStore {
4432
5435
  }
4433
5436
  }
4434
5437
  readBranchSpan(sessionId, cut) {
4435
- 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
+ });
4436
5442
  }
4437
5443
  readEntrySizes(sessionId, startSeq, endSeq, limit) {
4438
5444
  return this.run(async () => {
@@ -4447,6 +5453,9 @@ var JsonlSessionStore = class JsonlSessionStore {
4447
5453
  bytes: spanEnd(jsonl, seq) - spanStart(jsonl, seq)
4448
5454
  }))
4449
5455
  };
5456
+ }, {
5457
+ kind: "sessions",
5458
+ sessionIds: () => [sessionId]
4450
5459
  });
4451
5460
  }
4452
5461
  readEntryChunk(reference, offset) {
@@ -4455,10 +5464,32 @@ var JsonlSessionStore = class JsonlSessionStore {
4455
5464
  if (jsonl.index.epoch !== reference.epoch) throw new SessionConflictError(reference.sessionId, reference.seq, jsonl.index.seq);
4456
5465
  const start = spanStart(jsonl, reference.seq) + offset;
4457
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]
4458
5470
  });
4459
5471
  }
4460
5472
  readRange(sessionId, startSeq, endSeq, expectedEpoch) {
4461
- 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 () => {
4462
5493
  const { path, jsonl } = await this.indexed(sessionId);
4463
5494
  if (expectedEpoch !== void 0 && expectedEpoch !== jsonl.index.epoch) throw new SessionConflictError(sessionId, endSeq, jsonl.index.seq);
4464
5495
  const start = Math.max(1, startSeq);
@@ -4471,7 +5502,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4471
5502
  seqs,
4472
5503
  lastEntryId: jsonl.index.lastId
4473
5504
  };
4474
- });
5505
+ }), false);
4475
5506
  }
4476
5507
  findLatestCompaction(sessionId, leafId) {
4477
5508
  return this.run(async () => {
@@ -4490,6 +5521,9 @@ var JsonlSessionStore = class JsonlSessionStore {
4490
5521
  leafId: leaf.id,
4491
5522
  lastSeq: jsonl.index.seq
4492
5523
  };
5524
+ }, {
5525
+ kind: "sessions",
5526
+ sessionIds: () => [sessionId]
4493
5527
  });
4494
5528
  }
4495
5529
  /** Read this exact export file, not another file in the directory with the same session ID. An export is an
@@ -4613,6 +5647,9 @@ var JsonlSessionStore = class JsonlSessionStore {
4613
5647
  await this.keepIndex(path, {
4614
5648
  ...jsonl,
4615
5649
  fork
5650
+ }, {
5651
+ synced: jsonl.synced,
5652
+ handle: file
4616
5653
  });
4617
5654
  return fork;
4618
5655
  };
@@ -4630,10 +5667,16 @@ var JsonlSessionStore = class JsonlSessionStore {
4630
5667
  await file.close();
4631
5668
  }
4632
5669
  }
5670
+ }, {
5671
+ kind: "sessions",
5672
+ sessionIds: () => [sessionId]
4633
5673
  });
4634
5674
  }
4635
5675
  readChildCatalogCut(sessionId) {
4636
- 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
+ });
4637
5680
  }
4638
5681
  /** The snapshot entries the session's index locates; no line of the file is read (#5554). */
4639
5682
  readSnapshotCut(sessionId, options = {}) {
@@ -4641,6 +5684,9 @@ var JsonlSessionStore = class JsonlSessionStore {
4641
5684
  const { index } = (await this.indexed(sessionId)).jsonl;
4642
5685
  if (options.leafSeq !== void 0 && options.leafSeq > index.seq) return void 0;
4643
5686
  return snapshotCutOf(index, options.leafSeq);
5687
+ }, {
5688
+ kind: "sessions",
5689
+ sessionIds: () => [sessionId]
4644
5690
  });
4645
5691
  }
4646
5692
  /** The lines at `seqs`, each read from where the index places it, without reading the lines between them. */
@@ -4659,25 +5705,45 @@ var JsonlSessionStore = class JsonlSessionStore {
4659
5705
  ...plan.oversized
4660
5706
  }] };
4661
5707
  return { items: await this.entriesAt(path, jsonl, plan.seqs) };
5708
+ }, {
5709
+ kind: "sessions",
5710
+ sessionIds: () => [sessionId]
4662
5711
  });
4663
5712
  }
4664
5713
  readResume(sessionId, leafId, options) {
4665
5714
  return this.run(async () => {
4666
5715
  if (leafId !== void 0) validateSessionText("entry.id", leafId);
4667
- const { path, header, jsonl } = await this.indexed(sessionId);
4668
- const leafSeq = leafId === void 0 ? jsonl.index.leafSeq : await this.seqInFile(path, jsonl, leafId) ?? 0;
4669
- const index = leafSeq === jsonl.index.leafSeq ? jsonl.index : await selectResumeLeaf(jsonl.index, leafSeq, branchStatePages(jsonl.index.seq, {
4670
- bytes: (seq) => spanEnd(jsonl, seq) - spanStart(jsonl, seq),
4671
- read: (seqs) => this.entriesAt(path, jsonl, seqs),
4672
- chunk: (seq, offset, length) => readBytes(path, spanStart(jsonl, seq) + offset, length)
4673
- }));
4674
- const result = await this.windowFromIndex(path, header, jsonl, index, void 0, options?.deferChildRecords);
4675
- if (leafSeq !== jsonl.index.leafSeq) {
4676
- const stats = await stat(path, { bigint: true });
4677
- 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);
4678
- }
4679
- return result;
4680
- });
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);
4681
5747
  }
4682
5748
  async windowFromIndex(path, header, jsonl, index = jsonl.index, input, deferChildRecords = false) {
4683
5749
  const plan = sessionResumePlan(index, index.leafSeq, deferChildRecords);
@@ -4694,6 +5760,9 @@ var JsonlSessionStore = class JsonlSessionStore {
4694
5760
  validateSessionText("entry.id", entryId);
4695
5761
  const { path, jsonl } = await this.indexed(sessionId);
4696
5762
  return this.seqInFile(path, jsonl, entryId);
5763
+ }, {
5764
+ kind: "sessions",
5765
+ sessionIds: () => [sessionId]
4697
5766
  });
4698
5767
  }
4699
5768
  async indexed(sessionId) {
@@ -4706,7 +5775,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4706
5775
  if (!isCurrentSessionHeader(located.stored)) throw new SessionFormatVersionError$1(located.path, located.stored.version);
4707
5776
  }
4708
5777
  const { path, header, stats } = located;
4709
- const jsonl = await this.indexFor(path, header, stats);
5778
+ const { jsonl } = await this.indexFor(path, header, stats);
4710
5779
  const prior = this.fileStates.get(path);
4711
5780
  await this.remember(path, {
4712
5781
  headerStamp: jsonl.headerStamp,
@@ -4724,11 +5793,47 @@ var JsonlSessionStore = class JsonlSessionStore {
4724
5793
  jsonl
4725
5794
  };
4726
5795
  }
4727
- 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;
4728
5831
  const identity = `${stats.dev}:${stats.ino}`;
4729
5832
  const headerStamp = JSON.stringify(header);
4730
5833
  const epoch = fileEpochOf(stats, headerStamp);
4731
- let cached = this.indexes.get(path) ?? await readSidecar(path);
5834
+ const inMemory = this.indexes.get(path);
5835
+ let cached = inMemory ?? await readSidecar(path);
5836
+ const fromDisk = inMemory === void 0 && cached !== void 0;
4732
5837
  const older = cached !== void 0 && cached.index.epoch !== epoch && cached.index.epoch === legacyFileEpochOf(stats, headerStamp);
4733
5838
  if (cached !== void 0 && older) cached = {
4734
5839
  ...cached,
@@ -4737,26 +5842,108 @@ var JsonlSessionStore = class JsonlSessionStore {
4737
5842
  epoch
4738
5843
  }
4739
5844
  };
4740
- if (cached !== void 0 && cached.identity === identity && cached.birthtimeNs === String(stats.birthtimeNs) && cached.headerStamp === headerStamp && cached.index.epoch === epoch) {
5845
+ if (cached !== void 0 && (!fromDisk || cached.synced) && cached.identity === identity && cached.birthtimeNs === String(stats.birthtimeNs) && cached.headerStamp === headerStamp && cached.index.epoch === epoch) {
4741
5846
  const fileSize = Number(stats.size);
4742
- const kept = this.keptFor(path, identity);
4743
- if (cached.fileSize === fileSize && cached.mtimeNs === String(stats.mtimeNs) && await witnessHolds(path, cached, kept)) {
4744
- if (older) return this.keepIndex(path, cached);
4745
- this.indexes.set(path, cached);
4746
- 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
+ };
4747
5870
  }
4748
- if (fileSize > cached.size && await witnessHolds(path, cached, kept)) {
4749
- const grown = await this.catchUp(path, cached, stats, kept);
4750
- 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
+ }
4751
5886
  }
4752
5887
  }
4753
- 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
+ }
4754
5913
  }
4755
- async keepIndex(path, jsonl) {
4756
- 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 : {
4757
5927
  ...jsonl,
4758
- sidecarSize: jsonl.size
4759
- } : 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;
4760
5947
  this.indexes.set(path, kept);
4761
5948
  return kept;
4762
5949
  }
@@ -4768,23 +5955,25 @@ var JsonlSessionStore = class JsonlSessionStore {
4768
5955
  }
4769
5956
  /** `folded` reuses a topology pass already made; `branch: false` keeps it and skips folding the active branch
4770
5957
  * again, for a reader of positions that never selects a window. */
4771
- async buildIndex(path, headerStamp, stats, input, folded) {
5958
+ async buildIndex(path, headerStamp, stats, input, folded, reportTorn = true) {
4772
5959
  const identity = `${stats.dev}:${stats.ino}`;
4773
5960
  if (input === void 0) {
4774
5961
  const kept = this.keptFor(path, identity);
4775
- 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);
4776
5963
  const handle = await open(path, "r");
4777
5964
  try {
4778
- return await this.buildIndex(path, headerStamp, stats, { handle }, folded);
5965
+ return await this.buildIndex(path, headerStamp, stats, { handle }, folded, reportTorn);
4779
5966
  } finally {
4780
5967
  await handle.close();
4781
5968
  }
4782
5969
  }
4783
5970
  const birthtimeNs = String(stats.birthtimeNs);
4784
5971
  const epoch = fileEpochOf(stats, headerStamp);
4785
- const topology = folded?.topology ?? await this.foldFile(path, epoch, () => true, input);
5972
+ const end = reportTorn ? void 0 : Number(stats.size);
5973
+ const topology = folded?.topology ?? await this.foldFile(path, epoch, () => true, input, end, reportTorn);
4786
5974
  const ranges = folded?.branch === false || topology.index.jumps.length === 0 ? void 0 : branchRanges(topology.index, topology.index.leafSeq);
4787
- 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);
4788
5977
  return {
4789
5978
  identity,
4790
5979
  birthtimeNs,
@@ -4792,7 +5981,8 @@ var JsonlSessionStore = class JsonlSessionStore {
4792
5981
  fileSize: Number(stats.size),
4793
5982
  mtimeNs: String(stats.mtimeNs),
4794
5983
  size: active.size,
4795
- witness: await readFrom(input.handle, Math.max(0, active.size - WITNESS_BYTES), Math.min(active.size, WITNESS_BYTES)),
5984
+ ...integrity,
5985
+ synced: false,
4796
5986
  terminated: active.terminated,
4797
5987
  torn: active.torn,
4798
5988
  spans: active.spans,
@@ -4802,7 +5992,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4802
5992
  sidecarSize: 0
4803
5993
  };
4804
5994
  }
4805
- async foldFile(path, epoch, activeSeq, pinned) {
5995
+ async foldFile(path, epoch, activeSeq, pinned, end, reportTorn = true) {
4806
5996
  let index = {
4807
5997
  ...foldSessionResume(void 0, [], void 0, activeSeq),
4808
5998
  epoch
@@ -4834,10 +6024,10 @@ var JsonlSessionStore = class JsonlSessionStore {
4834
6024
  batchBytes = 0;
4835
6025
  extraToolCalls = 0;
4836
6026
  };
4837
- const take = (entry, start, end, toolCalls) => {
4838
- const bytes = end - start;
6027
+ const take = (entry, start, stop, toolCalls) => {
6028
+ const bytes = stop - start;
4839
6029
  if (batch.length && batchBytes + bytes > SCAN_WINDOW_BYTES$1) flush();
4840
- spans.push(start, end);
6030
+ spans.push(start, stop);
4841
6031
  hashes.push(idHash(entry.id));
4842
6032
  ids.set(entry.id, spans.length / 2);
4843
6033
  batch.push(entry);
@@ -4848,7 +6038,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4848
6038
  };
4849
6039
  const file = pinned?.handle ?? await open(path, "r");
4850
6040
  try {
4851
- 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);
4852
6042
  flush();
4853
6043
  return {
4854
6044
  index,
@@ -4861,9 +6051,9 @@ var JsonlSessionStore = class JsonlSessionStore {
4861
6051
  if (!pinned) await file.close();
4862
6052
  }
4863
6053
  }
4864
- async catchUp(path, cached, stats, kept) {
6054
+ async catchUp(path, cached, stats, kept, reportTorn = true) {
4865
6055
  const from = cached.size - cached.witness.length;
4866
- 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);
4867
6057
  const bytes = await readBytes(path, from, Number(stats.size) - from, kept);
4868
6058
  let offset = cached.size;
4869
6059
  let appended = bytes.subarray(cached.witness.length);
@@ -4875,40 +6065,80 @@ var JsonlSessionStore = class JsonlSessionStore {
4875
6065
  const spans = [...cached.spans];
4876
6066
  const entries = [];
4877
6067
  let start = 0;
6068
+ let stoppedAtNul = false;
4878
6069
  for (let newline = appended.indexOf(10); newline !== -1; newline = appended.indexOf(10, start)) {
4879
- 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");
4880
6077
  if (text.trim()) {
4881
6078
  entries.push(JSON.parse(text));
4882
6079
  spans.push(offset + start, offset + newline);
4883
6080
  }
4884
6081
  start = newline + 1;
4885
6082
  }
4886
- const last = appended.subarray(start);
4887
6083
  let size = offset + start;
4888
6084
  let terminated = true;
4889
- let torn = false;
4890
- if (last.length > 0) {
4891
- const unterminated = parseUnterminated(last.toString("utf8"));
4892
- if (unterminated) {
4893
- entries.push(unterminated);
4894
- spans.push(offset + start, offset + appended.length);
4895
- size = offset + appended.length;
4896
- terminated = false;
4897
- } else {
4898
- torn = true;
4899
- 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
+ }
4900
6099
  }
4901
6100
  }
4902
6101
  validateSessionEntryStructure(entries, path);
4903
6102
  validateSessionEntries(entries);
4904
6103
  if (resumeIndexNeedsRefold(cached.index, entries)) return void 0;
4905
- 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
+ }
4906
6131
  return {
4907
6132
  ...cached,
4908
6133
  fileSize: Number(stats.size),
4909
6134
  mtimeNs: String(stats.mtimeNs),
4910
6135
  size,
4911
- witness: witnessAfter(cached.witness, appended.subarray(0, size - offset)),
6136
+ witness,
6137
+ synced: false,
6138
+ prefixHash,
6139
+ headWitness,
6140
+ checkpointStride,
6141
+ checkpoints,
4912
6142
  terminated: appended.length === 0 ? cached.terminated : terminated,
4913
6143
  torn,
4914
6144
  spans,
@@ -4922,8 +6152,8 @@ var JsonlSessionStore = class JsonlSessionStore {
4922
6152
  * indexed prefix, rather than read the whole file again or hold the suffix. Undefined when the cache cannot be
4923
6153
  * extended: the suffix does not continue the cached last line, or it branches, which needs a full fold.
4924
6154
  */
4925
- async streamCatchUp(path, cached, stats) {
4926
- const file = await open(path, "r");
6155
+ async streamCatchUp(path, cached, stats, kept, reportTorn = true) {
6156
+ const file = kept ?? await open(path, "r");
4927
6157
  try {
4928
6158
  let start = cached.size;
4929
6159
  if (!cached.terminated) {
@@ -4943,7 +6173,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4943
6173
  if (!batch.length) return;
4944
6174
  const seqs = /* @__PURE__ */ new Map();
4945
6175
  for (const id of foreignResumeIds(index, batch)) {
4946
- const seq = appended.get(id) ?? await this.seqInFile(path, cached, id);
6176
+ const seq = appended.get(id) ?? await this.seqInFile(path, cached, id, file);
4947
6177
  if (seq !== void 0) seqs.set(id, seq);
4948
6178
  }
4949
6179
  fork = appendedForkIndex({
@@ -4968,33 +6198,40 @@ var JsonlSessionStore = class JsonlSessionStore {
4968
6198
  extraToolCalls += toolCalls;
4969
6199
  return batch.length >= INDEX_BATCH_ENTRIES || batchBytes >= SCAN_WINDOW_BYTES$1 ? flush().then(() => true) : true;
4970
6200
  };
4971
- 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);
4972
6202
  if (!scanned) return void 0;
4973
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);
4974
6206
  return {
4975
6207
  ...cached,
4976
6208
  fileSize: Number(stats.size),
4977
6209
  mtimeNs: String(stats.mtimeNs),
4978
6210
  ...scanned,
4979
6211
  witness: await witnessAt(file, scanned.size),
6212
+ synced: false,
6213
+ prefixHash: void 0,
6214
+ headWitness,
6215
+ checkpointStride: extended.stride,
6216
+ checkpoints: extended.checkpoints,
4980
6217
  spans,
4981
6218
  ids: hashes,
4982
6219
  fork,
4983
6220
  index
4984
6221
  };
4985
6222
  } finally {
4986
- await file.close();
6223
+ if (kept === void 0) await file.close();
4987
6224
  }
4988
6225
  }
4989
- async foldAppended(path, cached, entries) {
6226
+ async foldAppended(path, cached, entries, pinned) {
4990
6227
  const seqs = /* @__PURE__ */ new Map();
4991
6228
  for (const id of foreignResumeIds(cached.index, entries)) {
4992
- const seq = await this.seqInFile(path, cached, id);
6229
+ const seq = await this.seqInFile(path, cached, id, pinned);
4993
6230
  if (seq !== void 0) seqs.set(id, seq);
4994
6231
  }
4995
6232
  return foldSessionResume(cached.index, entries, (id) => seqs.get(id));
4996
6233
  }
4997
- async indexAppended(path, before, entries, lines, firstLine, stats) {
6234
+ async indexAppended(path, before, entries, lines, firstLine, stats, handle) {
4998
6235
  const cached = this.indexes.get(path);
4999
6236
  if (cached === void 0 || cached.identity !== before.identity || cached.size !== before.size || cached.index.seq !== before.lastSeq || resumeIndexNeedsRefold(cached.index, entries)) {
5000
6237
  this.indexes.delete(path);
@@ -5014,6 +6251,8 @@ var JsonlSessionStore = class JsonlSessionStore {
5014
6251
  mtimeNs: String(stats.mtimeNs),
5015
6252
  size: state.size,
5016
6253
  witness: state.witness,
6254
+ synced: true,
6255
+ prefixHash: void 0,
5017
6256
  terminated: true,
5018
6257
  torn: false,
5019
6258
  spans,
@@ -5021,8 +6260,14 @@ var JsonlSessionStore = class JsonlSessionStore {
5021
6260
  fork: appendedForkIndex(cached, entries),
5022
6261
  index: await this.foldAppended(path, cached, entries)
5023
6262
  };
5024
- if (next.size - next.sidecarSize >= SIDECAR_REFRESH_BYTES) await this.keepIndex(path, next);
5025
- 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);
5026
6271
  }
5027
6272
  async entriesAt(path, jsonl, seqs, input, exactRevision = false) {
5028
6273
  const wanted = [...new Set(seqs.filter((seq) => seq >= 1 && seq <= jsonl.index.seq))].sort((a, b) => a - b);
@@ -5089,15 +6334,22 @@ var JsonlSessionStore = class JsonlSessionStore {
5089
6334
  stored ??= await this.readFirstLine(path);
5090
6335
  const directory = dirname$1(path);
5091
6336
  if (isCurrentSessionHeader(stored) || directory === this.directory) return this.readSnapshot(path, stored, true);
5092
- 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
+ });
5093
6341
  }
5094
6342
  findFile(sessionId) {
5095
- 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);
5096
6347
  }
5097
6348
  readHeader(sessionId) {
5098
- return this.run(async () => {
5099
- return (await this.locate(sessionId))?.header;
5100
- });
6349
+ return this.run(() => this.readUnlocked(sessionId, async ({ header }) => ({
6350
+ value: header,
6351
+ commit: async () => {}
6352
+ }), async () => (await this.locate(sessionId))?.header), false);
5101
6353
  }
5102
6354
  delete(sessionId) {
5103
6355
  return this.run(async () => {
@@ -5117,12 +6369,16 @@ var JsonlSessionStore = class JsonlSessionStore {
5117
6369
  this.fileStates.delete(located.path);
5118
6370
  await this.forgetIndex(located.path);
5119
6371
  await deleteFileChatRecords(owner).catch(() => {});
6372
+ }, {
6373
+ kind: "sessions",
6374
+ sessionIds: () => [sessionId],
6375
+ create: true
5120
6376
  });
5121
6377
  }
5122
6378
  async *list(query) {
5123
6379
  this.checkAbort(query.signal);
5124
6380
  const matchesCwd = query.cwd === void 0 ? void 0 : createSessionCwdMatcherAsync(query.cwd);
5125
- const paths = await this.run(() => this.paths(), true, query.signal);
6381
+ const paths = await this.run(() => this.paths(), { kind: "list" }, query.signal);
5126
6382
  for (const path of paths) {
5127
6383
  const cached = query.withoutSearchText ? this.fileStates.get(path) : void 0;
5128
6384
  const summary = await this.run(async () => {
@@ -5165,18 +6421,24 @@ var JsonlSessionStore = class JsonlSessionStore {
5165
6421
  location: path
5166
6422
  };
5167
6423
  };
5168
- 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());
5169
6428
  } catch (cause) {
5170
6429
  const error = cause;
5171
6430
  if (error.path === path && (error.code === "ENOENT" || error.code === "ENOTDIR")) return void 0;
5172
6431
  if (cause instanceof SessionFormatVersionError$1 || cause instanceof SessionInvalidTextError || cause instanceof SessionInvalidTimestampError || cause instanceof SyntaxError) return void 0;
5173
6432
  throw cause;
5174
6433
  }
5175
- }, cached?.summaryState === void 0, query.signal);
6434
+ }, cached?.summaryState === void 0 ? {
6435
+ kind: "files",
6436
+ paths: [path]
6437
+ } : false, query.signal);
5176
6438
  this.checkAbort(query.signal);
5177
6439
  if (summary) yield summary;
5178
6440
  }
5179
- await this.run(async () => this.checkAbort(query.signal), true, query.signal);
6441
+ await this.run(async () => this.checkAbort(query.signal), { kind: "list" }, query.signal);
5180
6442
  }
5181
6443
  async *scanFiles() {
5182
6444
  for (const location of await this.run(() => this.paths({ skipUnreadableDirectories: true }), false)) {
@@ -5231,9 +6493,18 @@ var JsonlSessionStore = class JsonlSessionStore {
5231
6493
  armed: 0
5232
6494
  };
5233
6495
  this.keptFiles.set(path, opened);
5234
- while (this.keptFiles.size > KEPT_FILES) await this.closeKept(this.keptFiles.keys().next().value);
6496
+ await this.trimKeptFiles();
5235
6497
  return opened;
5236
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
+ }
5237
6508
  /** The kept handle of the file at `path`, while it is the file `identity` names, to read through. */
5238
6509
  keptFor(path, identity) {
5239
6510
  const kept = this.keptFiles.get(path);
@@ -5265,7 +6536,7 @@ var JsonlSessionStore = class JsonlSessionStore {
5265
6536
  const result = this.queue.then(async () => {
5266
6537
  if (this.poisoned) throw this.poisoned;
5267
6538
  try {
5268
- return await (locked ? this.exclusive(operation, signal) : operation());
6539
+ return await (locked === false ? operation() : this.exclusive(operation, signal, this.directory, locked));
5269
6540
  } catch (cause) {
5270
6541
  if (signal?.aborted && cause === signal.reason) throw cause;
5271
6542
  throw this.failure(cause);
@@ -5279,7 +6550,93 @@ var JsonlSessionStore = class JsonlSessionStore {
5279
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;
5280
6551
  return new StorageUnavailableError$1(this.descriptor, cause);
5281
6552
  }
5282
- 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) {
5283
6640
  const lockfilePath = join$1(directory, ".session.lock");
5284
6641
  let release;
5285
6642
  let refusals = 0;
@@ -5320,9 +6677,7 @@ var JsonlSessionStore = class JsonlSessionStore {
5320
6677
  return result;
5321
6678
  }
5322
6679
  /**
5323
- * Releases the lock. The directory removal is retried when Windows refuses it for a moment. If it never
5324
- * succeeds the work is still done, so the failure is not reported over it: the lock is remembered so this
5325
- * 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.
5326
6681
  */
5327
6682
  async release(release, lockfilePath) {
5328
6683
  const fs = this.lockFs ?? {
@@ -5347,7 +6702,7 @@ var JsonlSessionStore = class JsonlSessionStore {
5347
6702
  const modified = await statMtimeMs(fs, lockfilePath);
5348
6703
  if (modified !== void 0) this.unreleased.set(lockfilePath, modified);
5349
6704
  }
5350
- /** 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. */
5351
6706
  async clearUnreleased(lockfilePath) {
5352
6707
  const expected = this.unreleased.get(lockfilePath);
5353
6708
  if (expected === void 0) return false;
@@ -5379,6 +6734,7 @@ var JsonlSessionStore = class JsonlSessionStore {
5379
6734
  async paths(options = {}) {
5380
6735
  const paths = [];
5381
6736
  for (const entry of await readdir(this.directory, { withFileTypes: true })) {
6737
+ if (entry.name.startsWith(".session.lock")) continue;
5382
6738
  const path = join$1(this.directory, entry.name);
5383
6739
  if ((entry.isDirectory() || entry.isSymbolicLink()) && !this.exactDirectory) {
5384
6740
  const children = await readdir(path, { withFileTypes: true }).catch((cause) => {
@@ -5393,14 +6749,20 @@ var JsonlSessionStore = class JsonlSessionStore {
5393
6749
  }
5394
6750
  async locate(sessionId) {
5395
6751
  validateSessionText("sessionId", sessionId);
5396
- if (this.selectedFile?.id === sessionId) return this.scan(sessionId, [this.selectedFile.path]);
5397
- const known = await this.locateKnown(sessionId);
5398
- if (known) return known;
5399
- const suffix = `_${this.key(sessionId)}.jsonl`;
5400
- const paths = await this.paths();
5401
- const named = paths.filter((path) => basename$1(path).endsWith(suffix));
5402
- const others = paths.filter((path) => !named.includes(path));
5403
- 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;
5404
6766
  }
5405
6767
  /**
5406
6768
  * Whether a file of this directory already holds `sessionId`, as {@link locate} finds it, without reading the files
@@ -5548,58 +6910,326 @@ var JsonlSessionStore = class JsonlSessionStore {
5548
6910
  }
5549
6911
  /**
5550
6912
  * The entries after the header line. A last line without a newline is read when it is a complete record and
5551
- * left out when it is torn; `size` and `witness` then end at the last complete line. A malformed line before
5552
- * 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.
5553
6916
  */
5554
6917
  async readEntries(path) {
5555
6918
  const input = createReadStream(path);
6919
+ const entries = [];
5556
6920
  let size = 0;
5557
- let complete = 0;
6921
+ let lineStart = 0;
5558
6922
  let witness = Buffer.alloc(0);
5559
- let completeWitness = Buffer.alloc(0);
5560
- input.on("data", (chunk) => {
5561
- const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
5562
- const newline = bytes.lastIndexOf(10);
5563
- if (newline !== -1) {
5564
- complete = size + newline + 1;
5565
- completeWitness = witnessAfter(witness, bytes.subarray(0, newline + 1));
5566
- }
5567
- witness = witnessAfter(witness, bytes);
5568
- size += bytes.length;
5569
- });
5570
- const entries = [];
6923
+ let parts = [];
5571
6924
  let first = true;
5572
- let last;
5573
6925
  try {
5574
- for await (const line of readLines(input)) {
5575
- if (first) {
5576
- first = false;
5577
- 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;
5578
6952
  }
5579
- if (last?.trim()) entries.push(JSON.parse(last));
5580
- last = line;
6953
+ if (start < bytes.length) parts.push(bytes.subarray(start));
6954
+ size += bytes.length;
5581
6955
  }
5582
6956
  } finally {
5583
6957
  input.destroy();
5584
6958
  }
5585
- const terminated = complete === size;
5586
- if (last !== void 0 && terminated) {
5587
- if (last.trim()) entries.push(JSON.parse(last));
5588
- } else if (last !== void 0) {
5589
- const entry = parseUnterminated(last);
5590
- if (!entry) return {
5591
- entries,
5592
- witness: completeWitness,
5593
- terminated: true,
5594
- torn: true,
5595
- 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
+ }
5596
7090
  };
5597
- entries.push(entry);
7091
+ } finally {
7092
+ if (release) await handle.close();
5598
7093
  }
5599
- 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 {
5600
7199
  entries,
5601
7200
  witness,
5602
- 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,
5603
7233
  torn: false,
5604
7234
  size
5605
7235
  };
@@ -5625,10 +7255,13 @@ var JsonlSessionStore = class JsonlSessionStore {
5625
7255
  */
5626
7256
  async remember(path, state, size, stats) {
5627
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);
5628
7261
  this.keepFileState(path, {
5629
7262
  ...state,
5630
7263
  stamp: this.stamp(stats),
5631
- identity: `${stats.dev}:${stats.ino}`,
7264
+ identity,
5632
7265
  size: size ?? Number(stats.size)
5633
7266
  });
5634
7267
  return stats;
@@ -5655,7 +7288,8 @@ var JsonlSessionStore = class JsonlSessionStore {
5655
7288
  const stale = async () => new SessionConflictError(sessionId, options.expectSeq, (await this.readEntries(path)).entries.length);
5656
7289
  if (state.identity !== `${stats.dev}:${stats.ino}` || state.headerStamp !== JSON.stringify(header) || Number(stats.size) < state.size) throw await stale();
5657
7290
  if (state.stamp !== this.stamp(stats)) {
5658
- const file = await open(path, "r");
7291
+ const kept = this.keptFor(path, state.identity);
7292
+ const file = kept ?? await open(path, "r");
5659
7293
  const offset = state.size - state.witness.length;
5660
7294
  const bytes = Buffer.alloc(Number(stats.size) - offset);
5661
7295
  try {
@@ -5666,24 +7300,45 @@ var JsonlSessionStore = class JsonlSessionStore {
5666
7300
  read += bytesRead;
5667
7301
  }
5668
7302
  } finally {
5669
- await file.close();
7303
+ if (kept === void 0) await file.close();
5670
7304
  }
5671
7305
  if (!bytes.subarray(0, state.witness.length).equals(state.witness)) throw await stale();
5672
- let appended = bytes.subarray(state.witness.length).toString("utf8");
5673
- if (appended && !state.terminated) {
5674
- if (!appended.startsWith("\n")) throw await stale();
5675
- 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;
5676
7339
  }
5677
- const lines = appended.split("\n");
5678
- const last = lines.pop() ?? "";
5679
- const entries = lines.map((line) => JSON.parse(line));
5680
- const unterminated = last === "" ? void 0 : parseUnterminated(last);
5681
- if (unterminated) entries.push(unterminated);
5682
- const torn = last !== "" && !unterminated;
5683
- if (torn) reportTornLine(path);
5684
7340
  validateSessionEntryStructure(entries, path);
5685
7341
  validateSessionEntries(entries);
5686
- const end = torn ? bytes.lastIndexOf(10) + 1 : bytes.length;
5687
7342
  state = {
5688
7343
  ...state,
5689
7344
  stamp: this.stamp(stats),
@@ -5713,14 +7368,6 @@ var JsonlSessionStore = class JsonlSessionStore {
5713
7368
  }), ...entries.map((entry) => JSON.stringify(entry))].join("\n")}\n`;
5714
7369
  }
5715
7370
  };
5716
- function removeDirectory(fs, path) {
5717
- return new Promise((resolve, reject) => {
5718
- fs.rmdir(path, (error) => {
5719
- if (error && error.code !== "ENOENT") reject(error);
5720
- else resolve();
5721
- });
5722
- });
5723
- }
5724
7371
  function statMtimeMs(fs, path) {
5725
7372
  return new Promise((resolve) => {
5726
7373
  fs.stat(path, (error, stats) => resolve(error ? void 0 : stats.mtimeMs));
@@ -5774,6 +7421,77 @@ async function writeAll(file, bytes) {
5774
7421
  at += bytesWritten;
5775
7422
  }
5776
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
+ }
5777
7495
  async function readFirstLineFrom(file, firstReadBytes, start = null) {
5778
7496
  const chunks = [];
5779
7497
  let position = start;
@@ -5809,6 +7527,135 @@ async function witnessHolds(path, jsonl, kept) {
5809
7527
  return false;
5810
7528
  }
5811
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
+ }
5812
7659
  function encodeDeltas(values) {
5813
7660
  let previous = 0;
5814
7661
  return values.map((value) => {
@@ -5835,6 +7682,11 @@ async function writeSidecar(path, jsonl) {
5835
7682
  mtimeNs: jsonl.mtimeNs,
5836
7683
  size: jsonl.size,
5837
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")]),
5838
7690
  terminated: jsonl.terminated,
5839
7691
  torn: jsonl.torn,
5840
7692
  spans: encodeDeltas(jsonl.spans),
@@ -5853,6 +7705,22 @@ async function writeSidecar(path, jsonl) {
5853
7705
  return false;
5854
7706
  }
5855
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
+ }
5856
7724
  function validForkIndex(value, last) {
5857
7725
  if (value === null || typeof value !== "object" || !("labels" in value) || !("catalog" in value)) return void 0;
5858
7726
  const seq = (n) => typeof n === "number" && Number.isSafeInteger(n) && n > 0 && n <= last;
@@ -5880,6 +7748,12 @@ async function readSidecar(path) {
5880
7748
  const spans = decodeDeltas(stored.spans);
5881
7749
  const ids = decodeIdHashes(stored.ids);
5882
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;
5883
7757
  return {
5884
7758
  identity: stored.identity,
5885
7759
  birthtimeNs: stored.birthtimeNs,
@@ -5888,6 +7762,11 @@ async function readSidecar(path) {
5888
7762
  mtimeNs: stored.mtimeNs,
5889
7763
  size: stored.size,
5890
7764
  witness: Buffer.from(stored.witness, "base64"),
7765
+ synced,
7766
+ prefixHash,
7767
+ headWitness,
7768
+ checkpointStride,
7769
+ checkpoints: checkpoints ?? [],
5891
7770
  terminated: stored.terminated,
5892
7771
  torn: stored.torn,
5893
7772
  spans,
@@ -7851,7 +9730,7 @@ function readSessionHeader(filePath) {
7851
9730
  }
7852
9731
  async function readSessionHeaderAsync(filePath) {
7853
9732
  try {
7854
- const file = await open$1(filePath, "r");
9733
+ const file = await open$2(filePath, "r");
7855
9734
  try {
7856
9735
  const line = new SessionHeaderLine();
7857
9736
  const buffer = Buffer.allocUnsafe(HEADER_READ_BUFFER_SIZE);
@@ -8376,7 +10255,7 @@ function __atomicOnDemandFailed(error, feature) {
8376
10255
  return (async () => {
8377
10256
  const root = new URL("../", import.meta.url);
8378
10257
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
8379
- const key = `${root.href}#0.10.11-alpha.3`;
10258
+ const key = `${root.href}#0.10.11-alpha.4`;
8380
10259
  let release = releases.get(key);
8381
10260
  if (release === undefined) {
8382
10261
  const current = (async () => {
@@ -8404,7 +10283,7 @@ function __atomicOnDemandFailed(error, feature) {
8404
10283
  } catch {
8405
10284
  // No installation to read, as in a bundle of the package: the release the process runs decides.
8406
10285
  }
8407
- const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.3" ? installed : running !== undefined && running.version !== "0.10.11-alpha.3" ? "0.10.11-alpha.3" : undefined;
10286
+ const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.4" ? installed : running !== undefined && running.version !== "0.10.11-alpha.4" ? "0.10.11-alpha.4" : undefined;
8408
10287
  if (updatedTo === undefined) throw error;
8409
10288
  const application = typeof running?.name === "string" ? running.name : "atomic";
8410
10289
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {