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

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 (432) hide show
  1. package/CHANGELOG.md +99 -0
  2. package/README.md +5 -8
  3. package/dist/_shared/dist-KOELCESV.js +2 -2
  4. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  5. package/dist/_shared/lib-4PES5P4V.js +2 -2
  6. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +6 -6
  7. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +5 -5
  8. package/dist/_shared/mode-shared-2QJSCUM6.js +6 -6
  9. package/dist/_shared/p0-cli-BB45ZQY6.js +46 -67
  10. package/dist/_shared/p0-cli-BB45ZQY6.js.map +1 -1
  11. package/dist/_shared/p1a-prewarm-XIU57JHF.js +7 -8
  12. package/dist/_shared/p1a-prewarm-XIU57JHF.js.map +1 -1
  13. package/dist/_shared/{p1b-elig-ENCUPKKJ.js → p1b-elig-TVB5CBLL.js} +14 -2
  14. package/dist/_shared/{p1b-elig-ENCUPKKJ.js.map → p1b-elig-TVB5CBLL.js.map} +1 -1
  15. package/dist/_shared/runtime-O4KCSG4C.js +3 -3
  16. package/dist/_shared/{sdk-IQMULKFU.js → sdk-B5LEWGGI.js} +340 -163
  17. package/dist/_shared/sdk-B5LEWGGI.js.map +1 -0
  18. package/dist/_shared/session-data-AHTU7IS6.js +2 -2
  19. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  20. package/dist/_shared/{startup-0-0-3IXNMFM2.js → startup-0-0-EZUKEP4Q.js} +48 -40
  21. package/dist/_shared/startup-0-0-EZUKEP4Q.js.map +1 -0
  22. package/dist/_shared/{startup-0-1-7T2IAE7J.js → startup-0-1-RTOHJFDJ.js} +195 -42
  23. package/dist/_shared/startup-0-1-RTOHJFDJ.js.map +1 -0
  24. package/dist/_shared/startup-0-2-5QHPCEON.js +33 -43
  25. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -1
  26. package/dist/_shared/startup-0-3-4ZYBYQNM.js +5 -5
  27. package/dist/_shared/startup-0-4-ZMJV547D.js +12 -7
  28. package/dist/_shared/startup-0-4-ZMJV547D.js.map +1 -1
  29. package/dist/_shared/startup-0-5-YDW47QX6.js +7 -7
  30. package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -1
  31. package/dist/_shared/startup-10-0-TDQNBDDL.js +6 -6
  32. package/dist/_shared/startup-12-0-55AAXBJZ.js +2 -2
  33. package/dist/_shared/startup-14-0-MLX36RBG.js +4 -5
  34. package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
  35. package/dist/_shared/startup-15-0-YUKGAC63.js +4 -4
  36. package/dist/_shared/startup-15-1-4S7FLMNG.js +19 -27
  37. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  38. package/dist/_shared/startup-8-0-34CBHPZH.js +39 -23
  39. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  40. package/dist/_shared/{startup-8-1-X32CYSXB.js → startup-8-1-LZFXSD3Z.js} +90 -1176
  41. package/dist/_shared/startup-8-1-LZFXSD3Z.js.map +1 -0
  42. package/dist/_shared/storage-command-7MGXLJGZ.js +186 -35
  43. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  44. package/dist/_shared/storage-status-K7PX2RXA.js +557 -0
  45. package/dist/_shared/storage-status-K7PX2RXA.js.map +1 -0
  46. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  47. package/dist/_shared/team-DOQKICG2.js +376 -0
  48. package/dist/_shared/team-DOQKICG2.js.map +1 -0
  49. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  50. package/dist/builtin/intercom/CHANGELOG.md +23 -0
  51. package/dist/builtin/intercom/README.md +2 -2
  52. package/dist/builtin/intercom/broker/broker.bundle.mjs +913 -289
  53. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +243 -64
  54. package/dist/builtin/intercom/broker/multinode-router.ts +154 -22
  55. package/dist/builtin/intercom/broker/multinode-state-store.ts +30 -3
  56. package/dist/builtin/intercom/broker/open-broker-state.ts +14 -0
  57. package/dist/builtin/intercom/broker/sql-add-column.ts +29 -5
  58. package/dist/builtin/intercom/broker/sql-ended-child-queue-store.ts +3 -2
  59. package/dist/builtin/intercom/broker/sql-held-send-store.ts +2 -2
  60. package/dist/builtin/intercom/broker/sql-known-session-store.ts +43 -19
  61. package/dist/builtin/intercom/broker/sql-lease-store.ts +170 -74
  62. package/dist/builtin/intercom/broker/sql-outbox-store.ts +298 -47
  63. package/dist/builtin/intercom/broker/sql-pending-ask-store.ts +8 -5
  64. package/dist/builtin/intercom/broker/sql-released-ask-store.ts +12 -5
  65. package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +24 -7
  66. package/dist/builtin/intercom/broker/sql-retention.ts +141 -0
  67. package/dist/builtin/intercom/broker/sql-schema.ts +136 -19
  68. package/dist/builtin/intercom/broker/sql-sent-message-authority.ts +74 -19
  69. package/dist/builtin/intercom/broker/wake-up-bus.ts +6 -0
  70. package/dist/builtin/intercom/index.bundle.mjs +2 -3
  71. package/dist/builtin/intercom/package.json +1 -1
  72. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  73. package/dist/builtin/mcp/package.json +1 -1
  74. package/dist/builtin/subagents/package.json +1 -1
  75. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  76. package/dist/builtin/web-access/index.bundle.mjs +2 -10
  77. package/dist/builtin/web-access/package.json +1 -1
  78. package/dist/bun/bundled-sqlite.js +41 -0
  79. package/dist/bun/bundled-sqlite.js.map +1 -0
  80. package/dist/cli/args.js +2 -2
  81. package/dist/cli/auth-cli.code.js +4 -4
  82. package/dist/cli/auth-cli.impl.js +3 -3
  83. package/dist/cli/auth-cli.js +3 -3
  84. package/dist/cli/blueprint-command.code.js +3 -3
  85. package/dist/cli/blueprint-command.impl.js +3 -3
  86. package/dist/cli/blueprint-command.js +3 -3
  87. package/dist/cli/intercom-command.code.js +3 -3
  88. package/dist/cli/intercom-command.code.js.map +1 -1
  89. package/dist/cli/intercom-command.impl.js +3 -3
  90. package/dist/cli/intercom-command.js +3 -3
  91. package/dist/cli/list-models.code.js +2 -2
  92. package/dist/cli/list-models.impl.js +3 -3
  93. package/dist/cli/list-models.js +3 -3
  94. package/dist/cli/session-picker.code.js +1 -1
  95. package/dist/cli/session-picker.impl.js +3 -3
  96. package/dist/cli/session-picker.js +3 -3
  97. package/dist/cli/startup-ui.code.js +1 -1
  98. package/dist/cli/startup-ui.impl.js +3 -3
  99. package/dist/cli/startup-ui.js +3 -3
  100. package/dist/cli/storage-command.impl.js +3 -3
  101. package/dist/cli/storage-command.js +3 -3
  102. package/dist/cli/storage-search-session.code.js +3 -3
  103. package/dist/cli/storage-search-session.impl.js +3 -3
  104. package/dist/cli/storage-search-session.js +3 -3
  105. package/dist/cli/team-command.code.js +19 -113
  106. package/dist/cli/team-command.code.js.map +1 -1
  107. package/dist/cli/team-command.impl.js +3 -3
  108. package/dist/cli/team-command.js +3 -3
  109. package/dist/cli.js +5 -18
  110. package/dist/cli.js.map +1 -1
  111. package/dist/core/agent-rehydrate-errors.d.ts +4 -9
  112. package/dist/core/compaction/compactor.d.ts +3 -3
  113. package/dist/core/debug.code.js +1 -1
  114. package/dist/core/debug.impl.js +3 -3
  115. package/dist/core/debug.js +3 -3
  116. package/dist/core/export-html/card-projection.impl.js +3 -3
  117. package/dist/core/export-html/card-projection.js +3 -3
  118. package/dist/core/export-html/index.code.js +2 -2
  119. package/dist/core/export-html/index.impl.js +3 -3
  120. package/dist/core/export-html/index.js +3 -3
  121. package/dist/core/export-html/json-spans.impl.js +3 -3
  122. package/dist/core/export-html/json-spans.js +3 -3
  123. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  124. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  125. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  126. package/dist/core/export-html/tool-renderer.js +3 -3
  127. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  128. package/dist/core/extensions/jiti-loader.js +3 -3
  129. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  130. package/dist/core/extensions/jiti-static-loader.js +3 -3
  131. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  132. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  133. package/dist/core/extensions/loader-host-modules.js +3 -3
  134. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  135. package/dist/core/extensions/runner-context.js +2 -2
  136. package/dist/core/intercom-broker-control-host.code.js +2 -2
  137. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  138. package/dist/core/intercom-broker-control-host.js +3 -3
  139. package/dist/core/intercom-broker-control.code.js +3 -3
  140. package/dist/core/intercom-broker-control.impl.js +3 -3
  141. package/dist/core/intercom-broker-control.js +3 -3
  142. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  143. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  144. package/dist/core/package-manager-storage-adapters.js +3 -3
  145. package/dist/core/process-start-token.d.ts +8 -0
  146. package/dist/core/process-tree-containment.d.ts +16 -0
  147. package/dist/core/sdk-types.d.ts +1 -2
  148. package/dist/core/sdk-types.js.map +1 -1
  149. package/dist/core/sdk.code.js +3 -3
  150. package/dist/core/sdk.impl.js +3 -3
  151. package/dist/core/sdk.js +3 -3
  152. package/dist/core/session-manager-core.js +5 -5
  153. package/dist/core/session-manager-list.impl.js +3 -3
  154. package/dist/core/session-manager-list.js +3 -3
  155. package/dist/core/session-manager.code.js +1 -1
  156. package/dist/core/session-manager.impl.js +3 -3
  157. package/dist/core/session-manager.js +3 -3
  158. package/dist/core/session-storage.code.js +1 -1
  159. package/dist/core/session-storage.impl.js +3 -3
  160. package/dist/core/session-storage.js +3 -3
  161. package/dist/core/settings-schema.d.ts +0 -3
  162. package/dist/core/storage/added-exports-0-10-11.js +19 -0
  163. package/dist/core/storage/added-exports-0-10-11.js.map +1 -0
  164. package/dist/core/storage/creation-time.js +105 -0
  165. package/dist/core/storage/creation-time.js.map +1 -0
  166. package/dist/core/storage/database.d.ts +19 -5
  167. package/dist/core/storage/database.js.map +1 -1
  168. package/dist/core/storage/dialect.d.ts +1 -1
  169. package/dist/core/storage/dialect.js +1 -1
  170. package/dist/core/storage/dialect.js.map +1 -1
  171. package/dist/core/storage/errors.d.ts +13 -13
  172. package/dist/core/storage/errors.js +10 -16
  173. package/dist/core/storage/errors.js.map +1 -1
  174. package/dist/core/storage/fenced-paths.d.ts +11 -0
  175. package/dist/core/storage/fenced-paths.js +11 -0
  176. package/dist/core/storage/fenced-paths.js.map +1 -1
  177. package/dist/core/storage/file-identity.d.ts +2 -0
  178. package/dist/core/storage/file-identity.js +24 -8
  179. package/dist/core/storage/file-identity.js.map +1 -1
  180. package/dist/core/storage/index.d.ts +3 -2
  181. package/dist/core/storage/index.js +5 -3
  182. package/dist/core/storage/index.js.map +1 -1
  183. package/dist/core/storage/libsql-removed.d.ts +71 -0
  184. package/dist/core/storage/libsql-removed.js +123 -0
  185. package/dist/core/storage/libsql-removed.js.map +1 -0
  186. package/dist/core/storage/migrations.d.ts +78 -14
  187. package/dist/core/storage/migrations.js +375 -49
  188. package/dist/core/storage/migrations.js.map +1 -1
  189. package/dist/core/storage/node-sqlite-file-gate.js +0 -15
  190. package/dist/core/storage/node-sqlite-file-gate.js.map +1 -1
  191. package/dist/core/storage/node-sqlite-thread.js +8 -13
  192. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  193. package/dist/core/storage/node-sqlite.js +51 -3
  194. package/dist/core/storage/node-sqlite.js.map +1 -1
  195. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  196. package/dist/core/storage/offline-snapshot-file.js +3 -3
  197. package/dist/core/storage/prefix.d.ts +1 -1
  198. package/dist/core/storage/prefix.js +9 -2
  199. package/dist/core/storage/prefix.js.map +1 -1
  200. package/dist/core/storage/process-selection.d.ts +5 -5
  201. package/dist/core/storage/provider.js +2 -2
  202. package/dist/core/storage/schema-catalog.d.ts +7 -8
  203. package/dist/core/storage/schema-catalog.js +8 -8
  204. package/dist/core/storage/schema-catalog.js.map +1 -1
  205. package/dist/core/storage/selection.d.ts +7 -82
  206. package/dist/core/storage/selection.js +20 -235
  207. package/dist/core/storage/selection.js.map +1 -1
  208. package/dist/core/storage/session/branch-fork-source.code.js +2 -2
  209. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  210. package/dist/core/storage/session/branch-fork-source.js +3 -3
  211. package/dist/core/storage/session/card-view.impl.js +3 -3
  212. package/dist/core/storage/session/card-view.js +3 -3
  213. package/dist/core/storage/session/child-reader.code.js +3 -3
  214. package/dist/core/storage/session/child-reader.impl.js +3 -3
  215. package/dist/core/storage/session/child-reader.js +3 -3
  216. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  217. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  218. package/dist/core/storage/session/expanded-child-details.code.js +2 -2
  219. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  220. package/dist/core/storage/session/expanded-child-details.js +3 -3
  221. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  222. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  223. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  224. package/dist/core/storage/session/fork-row-index.js +3 -3
  225. package/dist/core/storage/session/fork-staging.code.js +4 -7
  226. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  227. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  228. package/dist/core/storage/session/fork-staging.js +3 -3
  229. package/dist/core/storage/session/fork-window.code.js +3 -3
  230. package/dist/core/storage/session/fork-window.impl.js +3 -3
  231. package/dist/core/storage/session/fork-window.js +3 -3
  232. package/dist/core/storage/session/history-pages.impl.js +3 -3
  233. package/dist/core/storage/session/history-pages.js +3 -3
  234. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  235. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  236. package/dist/core/storage/session/jsonl-session-store.d.ts +5 -1
  237. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  238. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  239. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  240. package/dist/core/storage/session/memory-session-store.js +3 -3
  241. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  242. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  243. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  244. package/dist/core/storage/session/released-history-files.code.js +3 -3
  245. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  246. package/dist/core/storage/session/released-history-files.js +3 -3
  247. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  248. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  249. package/dist/core/storage/session/session-resume.impl.js +3 -3
  250. package/dist/core/storage/session/session-resume.js +3 -3
  251. package/dist/core/storage/session/session-search-index.d.ts +43 -4
  252. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  253. package/dist/core/storage/session/snapshot-cut.js +3 -3
  254. package/dist/core/storage/session/snapshot-history.code.js +3 -3
  255. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  256. package/dist/core/storage/session/snapshot-history.js +3 -3
  257. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  258. package/dist/core/storage/session/sql-session-store.d.ts +48 -11
  259. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  260. package/dist/core/storage/session/sql-session-store.js +3 -3
  261. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  262. package/dist/core/storage/session/tree-outline.js +3 -3
  263. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  264. package/dist/core/storage/session/tree-presentation.js +3 -3
  265. package/dist/core/storage/sqlite-facade.d.ts +6 -1
  266. package/dist/core/storage/sqlite-facade.js +1 -0
  267. package/dist/core/storage/sqlite-facade.js.map +1 -1
  268. package/dist/core/storage/storage-status.code.js +1 -1
  269. package/dist/core/storage/storage-status.impl.js +3 -3
  270. package/dist/core/storage/storage-status.js +3 -3
  271. package/dist/core/storage/team.code.js +1 -1
  272. package/dist/core/storage/team.d.ts +26 -115
  273. package/dist/core/storage/team.impl.js +3 -3
  274. package/dist/core/storage/team.js +3 -3
  275. package/dist/core/structured-output/index.code.js +1 -1
  276. package/dist/core/structured-output/index.impl.js +3 -3
  277. package/dist/core/structured-output/index.js +3 -3
  278. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  279. package/dist/core/tasks/task-completion-entry.js +3 -3
  280. package/dist/core/tasks/task-file-history.code.js +3 -3
  281. package/dist/core/tasks/task-file-history.impl.js +3 -3
  282. package/dist/core/tasks/task-file-history.js +3 -3
  283. package/dist/core/tasks/task-reference-archive.code.js +4 -4
  284. package/dist/core/tasks/task-reference-archive.js +3 -3
  285. package/dist/core/tasks/task-reference-identity.js +3 -3
  286. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  287. package/dist/core/tasks/task-reference-stream.js +3 -3
  288. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  289. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  290. package/dist/core/tasks/task-view-source.code.js +1 -1
  291. package/dist/core/tasks/task-view-source.impl.js +3 -3
  292. package/dist/core/tasks/task-view-source.js +3 -3
  293. package/dist/core/tools/history-tasks.d.ts +3 -2
  294. package/dist/core/tools/read-url.code.js +4 -4
  295. package/dist/core/tools/read-url.impl.js +3 -3
  296. package/dist/core/tools/read-url.js +3 -3
  297. package/dist/core/worktree-snapshot/blob-store.d.ts +40 -3
  298. package/dist/core/worktree-snapshot/blob-store.js +414 -21
  299. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  300. package/dist/core/worktree-snapshot/errors.code.js +2 -2
  301. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  302. package/dist/core/worktree-snapshot/errors.js +3 -3
  303. package/dist/core/worktree-snapshot/fork-blob-guard.js +81 -0
  304. package/dist/core/worktree-snapshot/fork-blob-guard.js.map +1 -0
  305. package/dist/core/worktree-snapshot/fork-snapshot-index.js +79 -38
  306. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -1
  307. package/dist/core/worktree-snapshot/session-index-reset.code.js +4 -0
  308. package/dist/core/worktree-snapshot/session-index-reset.code.js.map +1 -1
  309. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  310. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  311. package/dist/extensions/codemode/execute.code.js +1 -1
  312. package/dist/extensions/codemode/execute.impl.js +3 -3
  313. package/dist/extensions/codemode/execute.js +3 -3
  314. package/dist/extensions/codemode/renderer.code.js +2 -2
  315. package/dist/extensions/codemode/renderer.impl.js +3 -3
  316. package/dist/extensions/codemode/renderer.js +3 -3
  317. package/dist/extensions/mcp/cli.code.js +3 -3
  318. package/dist/extensions/mcp/cli.impl.js +3 -3
  319. package/dist/extensions/mcp/cli.js +3 -3
  320. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  321. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  322. package/dist/extensions/mcp/cli.lazy.js +3 -3
  323. package/dist/extensions/mcp/runtime.code.js +1 -1
  324. package/dist/extensions/mcp/runtime.impl.js +3 -3
  325. package/dist/extensions/mcp/runtime.js +3 -3
  326. package/dist/index.d.ts +3 -1
  327. package/dist/index.js +5 -5
  328. package/dist/main-first-time-setup.code.js +1 -1
  329. package/dist/main-first-time-setup.impl.js +3 -3
  330. package/dist/main-first-time-setup.js +3 -3
  331. package/dist/main.js +1 -1
  332. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  333. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  334. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  335. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  336. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  337. package/dist/modes/interactive/startup-shell-eligibility.js +1 -1
  338. package/dist/modes/interactive-engine/engine-prewarm.d.ts +1 -1
  339. package/dist/modes/print-mode.js +1 -1
  340. package/dist/package-manager-cli.code.js +6 -6
  341. package/dist/package-manager-cli.impl.js +3 -3
  342. package/dist/package-manager-cli.js +3 -3
  343. package/dist/rpc-entry.js +1 -1
  344. package/dist/startup-files.json +1 -1
  345. package/dist/startup-stages/10.js +1 -1
  346. package/dist/startup-stages/11.js +1 -1
  347. package/dist/startup-stages/12.js +1 -1
  348. package/dist/startup-stages/2.js +2 -4
  349. package/dist/startup-stages/3.js +1 -3
  350. package/dist/startup-stages/4.js +1 -2
  351. package/dist/startup-stages/5.js +1 -1
  352. package/dist/startup-stages/6.js +5 -7
  353. package/dist/startup-stages/7.js +3 -10
  354. package/dist/startup-stages/8.js +7 -2
  355. package/dist/startup-stages/9.js +1 -7
  356. package/dist/startup-stages/stages.json +1 -1
  357. package/dist/utils/compile-cache-deferral.js +8 -13
  358. package/dist/utils/compile-cache-deferral.js.map +1 -1
  359. package/dist/utils/compile-cache-warmup-host.js +3 -4
  360. package/dist/utils/compile-cache-warmup-host.js.map +1 -1
  361. package/dist/utils/compile-cache.js +12 -100
  362. package/dist/utils/compile-cache.js.map +1 -1
  363. package/dist/utils/startup-database-spare.code.js +2 -2
  364. package/dist/utils/startup-database-spare.impl.js +3 -3
  365. package/dist/utils/startup-database-spare.js +3 -3
  366. package/dist/utils/tools-manager.code.js +1 -1
  367. package/dist/utils/tools-manager.impl.js +3 -3
  368. package/dist/utils/tools-manager.js +3 -3
  369. package/dist/utils/worker-threads.js +2 -15
  370. package/dist/utils/worker-threads.js.map +1 -1
  371. package/docs/build.md +3 -3
  372. package/docs/changelog.mdx +1421 -69
  373. package/docs/compaction/reference.md +5 -5
  374. package/docs/compaction.md +7 -9
  375. package/docs/containerization.md +2 -2
  376. package/docs/custom-provider/api-reference.md +1 -1
  377. package/docs/docs.json +37 -10
  378. package/docs/environment-variables.md +0 -2
  379. package/docs/extensions/api-reference.md +4 -4
  380. package/docs/getting-started/installation.md +3 -0
  381. package/docs/guides/configuration.md +1 -1
  382. package/docs/guides/non-interactive.md +1 -1
  383. package/docs/guides/resume-on-any-machine.md +14 -22
  384. package/docs/guides/team-setup.md +56 -83
  385. package/docs/guides.md +2 -4
  386. package/docs/herdr.md +1 -1
  387. package/docs/index.md +1 -1
  388. package/docs/intercom/operations.md +26 -21
  389. package/docs/intercom/reference.md +2 -2
  390. package/docs/intercom.md +1 -1
  391. package/docs/libraries/storage-postgres.md +9 -9
  392. package/docs/libraries.md +2 -3
  393. package/docs/models-configuration.md +2 -2
  394. package/docs/models.md +2 -3
  395. package/docs/packages/authoring.md +7 -7
  396. package/docs/packages.md +1 -1
  397. package/docs/programmatic.md +2 -2
  398. package/docs/quickstart.md +1 -1
  399. package/docs/reference/cli.md +6 -11
  400. package/docs/reference.md +2 -2
  401. package/docs/rpc/extension-ui.md +2 -2
  402. package/docs/sdk/reference.md +5 -4
  403. package/docs/sdk/storage.md +8 -92
  404. package/docs/sdk/structured-decisions.md +1 -1
  405. package/docs/sdk/web-server.md +3 -3
  406. package/docs/sdk.md +14 -4
  407. package/docs/security.md +1 -1
  408. package/docs/session-format.md +5 -5
  409. package/docs/sessions.md +29 -49
  410. package/docs/settings.md +7 -8
  411. package/docs/storage/custom-adapters.md +255 -0
  412. package/docs/storage/jsonl.md +117 -0
  413. package/docs/{guides/postgres-pgbouncer.md → storage/postgres/pgbouncer.md} +66 -68
  414. package/docs/storage/postgres/tuning.md +337 -0
  415. package/docs/storage/postgres.md +556 -0
  416. package/docs/storage/sqlite.md +99 -0
  417. package/docs/storage.md +326 -990
  418. package/docs/subagents/authoring.md +1 -1
  419. package/docs/subagents.md +2 -2
  420. package/docs/tools.md +1 -1
  421. package/docs/worktree-snapshots.md +2 -2
  422. package/package.json +9 -9
  423. package/schemas/models.schema.json +2 -2
  424. package/schemas/settings.schema.json +0 -14
  425. package/dist/_shared/sdk-IQMULKFU.js.map +0 -1
  426. package/dist/_shared/startup-0-0-3IXNMFM2.js.map +0 -1
  427. package/dist/_shared/startup-0-1-7T2IAE7J.js.map +0 -1
  428. package/dist/_shared/startup-8-1-X32CYSXB.js.map +0 -1
  429. package/dist/core/intercom-broker-control.d.ts +0 -129
  430. package/dist/startup-stages/13.js +0 -1
  431. package/docs/guides/postgres-tuning.md +0 -311
  432. package/docs/libraries/storage-libsql.md +0 -97
package/docs/storage.md CHANGED
@@ -1,679 +1,186 @@
1
1
  ---
2
- title: "Storage backends"
3
- sidebarTitle: "Storage"
4
- description: "Configure local SQLite, PostgreSQL, or Turso/libSQL storage, export and import sessions, and build custom storage adapters."
2
+ title: "Storage"
3
+ sidebarTitle: "Overview"
4
+ description: "Choose where Atomic keeps sessions and Intercom messages, share one database across machines, move sessions between stores, and fix storage errors."
5
5
  ---
6
6
 
7
- Atomic saves sessions in a local SQLite database (`~/.atomic/workflows/journal.sqlite`) by default. You can switch to another SQLite file, a JSONL directory, an in-memory store, PostgreSQL, Turso/libSQL, or a custom database adapter through [storage settings](/settings#sessions) or [per-process overrides](#selecting-storage-per-process).
7
+ Atomic saves every session, with its messages, tool output, and [worktree snapshots](/worktree-snapshots), in a **session store**. By default, sessions live in a local SQLite file, `~/.atomic/workflows/journal.sqlite`, and you never need to think about it. Intercom, which carries messages between agents, keeps its own files on each machine until you share a database between machines.
8
8
 
9
- | Track | Start with |
10
- | --- | --- |
11
- | **CLI and operator setup** | [Which store to choose](#which-store-to-choose), [PostgreSQL](#postgresql), [Turso and libSQL](#turso-and-libsql), [Sharing storage across hosts](#sharing-storage-across-hosts) |
12
- | **Node.js and TypeScript SDK** | [SDK session storage](/sdk/storage), [SDK and local SQLite API](#sdk-and-local-sqlite-api), [SessionManager API](/session-format#sessionmanager-api) |
13
- | **Custom adapters and SQL drivers** | [Selecting an adapter](#selecting-an-adapter), [Bring your own driver](#bring-your-own-driver), [Adapter conformance](#adapter-conformance) |
14
-
15
- - A configured persistent store never silently falls back to memory when it fails to open.
16
- - A subagent always keeps its session in its launching parent's store, whatever its working directory, worktree, or the storage settings of the project it runs in. Subagent sessions, fresh or forked, are marked internal and hidden from normal session lists. See [Subagents](/subagents).
17
- - Workflow data written by releases before 0.10.0 stays untouched on disk. See [Workflow data from earlier releases](#workflow-data-from-earlier-releases).
18
-
19
- ## Which store to choose
20
-
21
- | Situation | Choose | Why |
22
- | --- | --- | --- |
23
- | One machine, one person | **Local SQLite** (default) | Requires no setup |
24
- | Sessions and Intercom shared across cloud machines, or a team already running managed PostgreSQL | **[PostgreSQL](#postgresql)** | Supports concurrent writers across many machines, with managed high availability, backups, and cloud identities |
25
- | A few machines, a small team, or CI caches | **[Turso and libSQL](#turso-and-libsql)** | Lightweight setup with one URL and one token. Supports one writer at a time, suited to a small number of concurrent machines |
26
- | Data that must stay on one machine | **Local SQLite** | Nothing leaves the machine |
27
-
28
- To move existing sessions between stores, see [Exporting and importing sessions](#exporting-and-importing-sessions). For CLI selection and resume flags, see [Choosing a store](/sessions#choosing-a-store).
29
-
30
- ## Local SQLite
31
-
32
- Local SQLite works out of the box with no external server. Atomic enables WAL mode, `FULL` synchronous writes, foreign keys, and cross-process writer queuing automatically.
33
-
34
- - Passing an empty object `{}` in top-level `storage` selects `<storageHome>/storage.sqlite`. Passing `{}` in `sessions.storage` selects `<storageHome>/workflows/journal.sqlite` (overriding any shared `storage`).
35
- - JSONL directory stores (`{ "dir": "..." }`) are allowed **only** in `sessions.storage` and `ATOMIC_SESSIONS_STORAGE`. Passing `"dir"` in top-level `storage`, `--storage`, `--storage-file`, or `ATOMIC_STORAGE` fails with `StorageConfigError`.
36
-
37
- ### Storage home
38
-
39
- Relative `path` and `dir` settings, relative `--storage` and `ATOMIC_STORAGE` paths, relative `secrets.file` paths, and shared `repos/` and `worktrees/` directories resolve against the agent directory's **storage home**.
40
-
41
- - **Default agent directory (`~/.atomic/agent`).** Storage home is `~/.atomic` under the current `HOME`. Moving or remounting the home directory keeps relative paths portable.
42
- - **Custom agent directory (`ATOMIC_CODING_AGENT_DIR`, `PI_CODING_AGENT_DIR`, or SDK `agentDir`).** Storage home is `<agentDir>` itself so sibling profiles stay isolated.
43
- - **Upgrading from an older custom agent directory layout.** When a custom agent directory upgrades from an older layout that kept a recognized session database or configured relative path in `<parent>` (other than `~/.atomic`), the first eligible profile keeps using `<parent>` and prints a one-time notice. Profiles that already have their own store stay isolated. Use absolute paths to share a local store intentionally across profiles.
44
- - **Relative secret files.** A relative `secrets.file` reference can still read an existing file in `<parent>`.
45
-
46
- `atomic storage status` never creates missing agent directories. A read-only agent directory works with a writable storage home, though recording a new storage-home decision requires a writable agent directory.
47
-
48
- ### Locks in the agent directory
49
-
50
- Processes that share an agent directory coordinate writes to `settings.json`, `auth.json`, project trust decisions, and session claims using lock files beside those files. If a process exits unexpectedly while holding a lock, the next process takes over automatically.
51
-
52
- These locks protect only processes on the same machine viewing the agent directory through the same local filesystem. Do not share one agent directory:
53
-
54
- - across multiple machines on a network filesystem (NFS, SMB, or cloud-synced folders), where OS file locks may not work across hosts;
55
- - on one machine through both a local path and a container volume, bind mount, or network mount of the same directory.
56
-
57
- Give each machine or container its own agent directory with `ATOMIC_CODING_AGENT_DIR`, and share sessions through a [shared database](#sharing-storage-across-hosts).
58
-
59
- If Atomic warns that a lock takeover file (such as `settings.json.lock.takeover.lock`) or leftover dead lock directory cannot be opened or removed, another user (such as a previous `sudo` run) owns it. Fix ownership or remove the stale lock, for example `sudo chown $USER ~/.atomic/agent/settings.json.lock.takeover.lock`. Until fixed, stale locks expire after 10 seconds before another process takes over.
60
-
61
- ## PostgreSQL
62
-
63
- `@bastani/atomic-storage-postgres` stores Atomic's shared state in PostgreSQL. **Atomic sessions require PostgreSQL 16 or later** (for session JSON query functions). The adapter itself accepts PostgreSQL 14 or later on connect for non-session tables, and rejects servers older than PostgreSQL 14.
64
-
65
- It works with self-hosted PostgreSQL and managed services, including Azure Database for PostgreSQL Flexible Server, Azure HorizonDB, Amazon RDS and Aurora PostgreSQL, Google Cloud SQL, AlloyDB, Neon, and Supabase.
66
-
67
- ### What works on PostgreSQL
68
-
69
- - **Sessions**, including entries containing NUL characters or lone surrogates in tool output.
70
- - **Intercom multi-node routing** across machines pointed at the same database.
71
- - **Session transfer** with `atomic storage export` and `atomic storage import`.
72
- - **Setup and operations** with `atomic storage join`, `atomic storage migrate`, `atomic storage status`, password files, rotated token files, cloud identities, TLS, HTTP proxies, and connection poolers.
73
-
74
- ### Set up the database
75
-
76
- Atomic stores its tables, indexes, trigger functions, and sequences in its own schema, `atomic` (configurable via the `schema` option), rather than `public`. Production deployments use two roles:
77
-
78
- - **Owner role.** Owns the database and the `atomic` schema. Runs `atomic storage migrate` after initial setup and after each Atomic upgrade.
79
- - **Runtime role.** Used by sessions and Intercom brokers. Reads and writes rows without DDL privileges, ownership, or `CREATE`.
80
-
81
- For a single user on one machine, one role that owns the database is enough. Atomic initializes the schema once under an advisory lock when first opened, and subsequent opens on an up-to-date schema run no DDL.
82
-
83
- As the server administrator (a superuser, or the managed service's administrator role), create the roles and database:
84
-
85
- ```sql
86
- CREATE ROLE atomic_owner LOGIN PASSWORD '<owner password>';
87
- CREATE ROLE atomic_runtime LOGIN PASSWORD '<runtime password>';
88
- CREATE DATABASE atomic OWNER atomic_owner;
89
- REVOKE ALL ON DATABASE atomic FROM PUBLIC;
90
- GRANT CONNECT ON DATABASE atomic TO atomic_owner, atomic_runtime;
91
- ```
92
-
93
- Owning the database grants `atomic_owner` `CREATE` on it, which is all it needs to create the `atomic` schema. On managed services where the administrator is not a superuser (Azure, RDS, Cloud SQL), make the administrator a member of the owner role first with `GRANT atomic_owner TO <administrator>;`.
94
-
95
- Next, run `atomic storage migrate` from a machine with the owner role credentials to create the schema and tables:
96
-
97
- ```bash
98
- atomic storage migrate --db 'postgresql://atomic_owner@db.example.com:5432/atomic' --password-file ~/atomic-owner-password
99
- ```
100
-
101
- Passing `--token-file`, `--password-file`, `--auth`, or `--prefix` to `atomic storage migrate` requires passing `--db <url>` too. `atomic storage migrate` has no `--schema` flag; to migrate a custom schema, set `options.schema` in `settings.json`, `--storage`, or `ATOMIC_STORAGE` and run `atomic storage migrate` without `--db`.
102
-
103
- Then connect to the `atomic` database as `atomic_owner` and grant the runtime role its privileges:
104
-
105
- ```sql
106
- GRANT USAGE ON SCHEMA atomic TO atomic_runtime;
107
- GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA atomic TO atomic_runtime;
108
- GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA atomic TO atomic_runtime;
109
- GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA atomic TO atomic_runtime;
110
- ALTER DEFAULT PRIVILEGES FOR ROLE atomic_owner IN SCHEMA atomic GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO atomic_runtime;
111
- ALTER DEFAULT PRIVILEGES FOR ROLE atomic_owner IN SCHEMA atomic GRANT USAGE, SELECT ON SEQUENCES TO atomic_runtime;
112
- ALTER DEFAULT PRIVILEGES FOR ROLE atomic_owner IN SCHEMA atomic GRANT EXECUTE ON FUNCTIONS TO atomic_runtime;
113
- ```
114
-
115
- These statements grant every privilege the runtime role needs. `LISTEN`, `NOTIFY`, `pg_notify`, and advisory locks require no extra grants, and Atomic does not use `TRUNCATE`, `REFERENCES`, or temporary tables. The default privileges cover tables added by later `atomic storage migrate` runs, and `EXECUTE` covers trigger functions on servers where `EXECUTE` is revoked from `PUBLIC`. Join runtime machines using the runtime role as shown in [Join a machine](#join-a-machine).
116
-
117
- Provider notes:
118
-
119
- - **Self-hosted PostgreSQL (16+) and Amazon RDS / Aurora.** Use the statements above. On RDS, run `GRANT atomic_owner TO <master user>;` before `CREATE DATABASE ... OWNER atomic_owner`.
120
- - **Azure Database for PostgreSQL Flexible Server.** Run the statements above as the server administrator (a member of `azure_pg_admin`). If you explicitly select `schema: "public"`, also run `GRANT CREATE ON SCHEMA public TO atomic_owner;` as the administrator.
121
- - **Google Cloud SQL.** Run the statements above as `postgres` or another member of `cloudsqlsuperuser`.
122
-
123
- When the runtime role lacks a required privilege or the schema is behind the current Atomic release, opening the store fails with `StorageConfigError` (`reason: "missing-privilege"`). The error names the exact `GRANT` or `atomic storage migrate` command to run.
124
-
125
- Once the schema is current, opening the session store or an Intercom broker's shared state reads the schema catalog and the migration ledger once, in two statements sent together, and runs no schema transaction and takes no lock. Many processes can therefore start at once against one database without waiting for each other or for other writers. Only an open that finds something missing or behind takes the schema lock and checks again under it.
126
-
127
- On SQLite and libSQL, Atomic records which version of each Intercom store's tables it set up in a table named `<prefix>atomic_schema_stamps`, together with SQLite's count of schema changes (`PRAGMA schema_version`). Atomic writes that record during the second open of a database, in the write transaction that open already takes; from the third open on, opening a broker whose tables are current takes no write lock. Any later change to the schema, by any program or by an older Atomic that doesn't keep the record, makes the next open check those tables again. Older Atomic versions ignore the table.
128
-
129
- `atomic storage migrate` sets `fillfactor = 80` on the sessions table and the Intercom lease table, which every append and lease renewal updates, so those updates usually stay on their page without touching an index. The setting applies to pages written after it. To apply it to existing pages too, run `VACUUM FULL` on those two tables during a quiet period, or use `pg_repack` to do it without a long lock. Both steps are optional. A runtime role that cannot alter these tables leaves the setting to the owner's `atomic storage migrate` and keeps working.
130
-
131
- `atomic storage migrate` also creates a function in the `atomic` schema that saves new entries to a session in 1 round trip instead of 2, and lets every role that may write sessions run it. The function runs with the rights of the role that calls it, so it gives the runtime role no new rights. Each process checks for the function when it opens the database, with no extra query. Until you run `atomic storage migrate`, or if the runtime role may not run the function, saves take 2 round trips as before. Long entries that Atomic stores in chunks, and entries that refer back to earlier parts of a branch, also take the 2-round-trip path. Older Atomic versions ignore the function and keep working.
132
-
133
- If you have not run `atomic storage migrate` after an upgrade and a low-privilege runtime role clones a session across connections, Atomic falls back to copying in memory and prints a one-time warning asking you to run `atomic storage migrate` as the owner role.
134
-
135
- Every Atomic process opens one pool of up to 8 connections (`maxConnections`) per database, however many stores it opens there, plus a smaller pool for reads. See [Connection budget](#connection-budget) for what each process holds, and [Tuning for many concurrent agents](#tuning-for-many-concurrent-agents) for how to size a fleet.
136
-
137
- Give each team or project its own `prefix` or its own database. PostgreSQL prefixes must be lowercase ASCII and at most 24 characters so generated identifiers stay within PostgreSQL's 63-byte limit. Longer prefixes fail with `StoragePrefixError` (`reason: "too-long"`), and uppercase letters fail with `reason: "uppercase"`.
138
-
139
- #### Upgrading from tables in `public`
140
-
141
- Older releases created Atomic's tables in `public`. Atomic continues reading tables in `public` when no `atomic` schema exists yet.
142
-
143
- To move an existing database into the `atomic` schema, upgrade all machines, run `atomic storage migrate` once as the role that owns those tables, and grant the runtime role its privileges on `atomic` as shown above. Restart any Atomic process that opened the database before the migration.
144
-
145
- `atomic storage migrate` moves all existing Atomic tables, indexes, triggers, sequences, and functions from `public` to `atomic` in one transaction and prevents older processes from writing new data into `public`. If an older process created a table in `public` after the migration, a subsequent `atomic storage migrate` reports it and fails so no state is lost silently.
9
+ Read this page when you want to:
146
10
 
147
- ### Join a machine
11
+ - share sessions and Intercom between machines, a team, or CI;
12
+ - move sessions to another machine or another store;
13
+ - choose a store for one process, such as a CI job or an app that launches Atomic;
14
+ - understand a storage error.
148
15
 
149
- Install the PostgreSQL adapter once per machine in user scope, then join the database:
16
+ Each kind of store has its own page:
150
17
 
151
- ```bash
152
- atomic install npm:@bastani/atomic-storage-postgres
153
- printf '%s' '<password>' > ~/atomic-db-password && chmod 600 ~/atomic-db-password
154
- atomic storage join 'postgresql://atomic_runtime@db.example.com:5432/atomic' --password-file ~/atomic-db-password
155
- atomic intercom restart
156
- atomic storage status
157
- ```
18
+ - [Local SQLite](/storage/sqlite): the default, with nothing to set up.
19
+ - [JSONL](/storage/jsonl): sessions as plain text files in a directory on one machine.
20
+ - [PostgreSQL](/storage/postgres): one shared database for many machines and many agents, with guides for [PgBouncer](/storage/postgres/pgbouncer) and [server tuning](/storage/postgres/tuning).
21
+ - [Custom adapters](/storage/custom-adapters): connect Atomic to another database through your own adapter.
158
22
 
159
- `atomic storage join` accepts `postgres://` and `postgresql://` URLs with a username and no embedded password. Pass exactly one credential option:
23
+ Apps built on the SDK choose their store in code. See [SDK session storage](/sdk/storage).
160
24
 
161
- - `--password-file <path>` copies the password into a private mode-`600` `~/.atomic/agent/storage-token.<id>` file. You can delete the input file afterward.
162
- - `--token-file <path>` saves the path as-is and rereads the file on every new connection. Use this with a Vault agent or secrets sidecar that rotates credentials automatically. Atomic strips only one trailing `\n` or `\r\n` when reading PostgreSQL token files, so avoid extra trailing spaces or blank lines.
163
- - `--auth azure`, `--auth aws`, or `--auth gcp` (the long forms `azure-entra`, `aws-iam`, and `gcp-iam` are also accepted) authenticates using the machine's cloud identity. See [Cloud identities](#cloud-identities).
25
+ Two rules hold for every store:
164
26
 
165
- `atomic storage join` tests the connection with `SELECT 1` before writing anything, then updates only the top-level `storage` key in `~/.atomic/agent/settings.json`:
27
+ - If the store you configured fails to open, Atomic stops with an error. It never falls back to keeping sessions in memory.
28
+ - A subagent always keeps its session in the same store as the session that launched it, whatever its working directory or project settings. Subagent sessions are hidden from normal session lists. See [Subagents](/subagents).
166
29
 
167
- ```json
168
- {
169
- "storage": {
170
- "adapter": "@bastani/atomic-storage-postgres",
171
- "options": { "url": "postgresql://atomic_runtime@db.example.com:5432/atomic" },
172
- "secrets": { "password": { "file": "agent/storage-token.3f2a" } }
173
- }
174
- }
175
- ```
176
-
177
- You can also edit this configuration directly. For password authentication in adapter configurations (including `settings.json`, `ATOMIC_STORAGE`, `--storage`, and SDK `{ kind: "adapter" }` selections), set `secrets.password` to `{ "file": "..." }` or `{ "env": "<variable>" }`. Because the adapter declares `liveSecrets: ["password"]`, Atomic rereads `secrets.password` for each new connection and ignores `options.password`, throwing `StorageConfigError` (`reason: "secret-missing"`) when `secrets.password` is omitted.
30
+ ## Which store to choose
178
31
 
179
- | Option | Default | Description |
32
+ | Situation | Store | Why |
180
33
  | --- | --- | --- |
181
- | `url` | Required | `postgres://` or `postgresql://` URL with username and no password |
182
- | `auth` | `"password"` | `"azure-entra"`, `"aws-iam"`, or `"gcp-iam"` for [cloud identities](#cloud-identities) |
183
- | `maxConnections` | `8` | Most connections one Atomic process opens in its main pool for this database. A positive integer. Raise it for more concurrent writes, as far as the server allows. See [Connection budget](#connection-budget) and [Tuning](#tuning-for-many-concurrent-agents) |
184
- | `readerMaxConnections` | `2` | Most connections in the process's pool for reads, capped at `maxConnections`. A non-negative integer. `0` turns the separate pool off, so reads share the main pool |
185
- | `statementTimeoutMs` | `30000` | How long one statement may run, in milliseconds, before the server cancels it. If the server stops answering, Atomic gives up on the connection 5 seconds after this |
186
- | `connectTimeoutMs` | `10000` | How long opening a connection, or waiting for a free one, may take, in milliseconds. A positive integer |
187
- | `idleTimeoutMs` | `300000` | How long, in milliseconds, a pool's last connection stays open after the pool's last call. Connections opened for a burst close after 10 seconds idle, or after `idleTimeoutMs` when it is shorter. A positive integer |
188
- | `keepAliveIdleMs` | `60000` | How long, in milliseconds, a connection sits unused before Atomic starts TCP keepalive probes on it. A positive integer |
189
- | `maxPreparedStatements` | `256`, or `0` when `listenUrl` is set, the URL's port is 6432 or 6543, or Atomic finds a pooler, unless Atomic finds PgBouncer 1.21 or later with `max_prepared_statements` above `0`. If your pooler listens on another port, set `listenUrl` or `0` | Most statements each connection keeps prepared on the server, so the server plans each one once. A non-negative integer. `0` turns prepared statements off. Each prepared statement uses some server memory per connection. See [Prepared statements](/guides/postgres-pgbouncer#how-atomic-works-with-pgbouncer) |
190
- | `listenUrl` | `url` | Direct endpoint for [wake-ups](#wake-ups) when `url` uses a transaction pooler. Enforces the same URL, TLS, proxy, and no-embedded-password rules as `url` (`credential-in-url`) |
191
- | `schema` | `"atomic"` | Schema name starting with a lowercase ASCII letter or `_`, followed by lowercase letters, digits, or `_` (1 to 63 characters) |
192
- | `proxy` | From environment | `http://` or `https://` proxy URL for all connections, or `"none"` to connect directly |
193
-
194
- `atomic team join` supports libSQL URLs only. Use `atomic storage join` for PostgreSQL. For Node.js and TypeScript SDK apps, install `@bastani/atomic-storage-postgres` with `npm install` and import `openPostgresDatabase` directly. See [`@bastani/atomic-storage-postgres`](/libraries/storage-postgres) and [SDK session storage](/sdk/storage).
195
-
196
- ### TLS
197
-
198
- Atomic connects over TLS to every remote host by default and verifies both the server certificate and hostname (`sslmode=verify-full`). If the URL omits the host, Atomic checks `PGHOST`.
199
-
200
- You can override this by adding a lowercase `sslmode` parameter to the URL (`uselibpqcompat` must also be lowercase if used). `verify-ca` verifies the CA without checking the hostname, `prefer` and `allow` encrypt without checking the certificate, and `disable` turns TLS off. `require` with `sslrootcert` behaves like `verify-ca`. Without `sslrootcert`, `require` verifies both certificate and hostname like `verify-full`, which is stricter than libpq. Uppercase TLS parameters or unknown `sslmode` values fail with `StorageConfigError`.
201
-
202
- Provider CA configuration:
203
-
204
- - **Azure Database for PostgreSQL, Azure HorizonDB, and Neon.** Certificates chain to CAs trusted by Node.js, so no extra parameter is required.
205
- - **Supabase.** Download the project CA certificate from Project Settings > Database > SSL Configuration and add `?sslrootcert=/path/to/supabase-ca.pem`.
206
- - **Amazon RDS and Aurora.** Download your region's bundle from `https://truststore.pki.rds.amazonaws.com/<region>/<region>-bundle.pem` and add `?sslrootcert=/path/to/bundle.pem`.
207
- - **Google Cloud SQL.** Save the server CA (`gcloud sql instances describe <instance> --format='value(serverCaCert.cert)'`). When connecting over a private IP address, add `?sslmode=verify-ca&sslrootcert=/path/to/server-ca.pem` because private IPs are not listed in the certificate's hostnames.
208
-
209
- ### Through an HTTP proxy
210
-
211
- In environments that restrict outbound traffic to an HTTP `CONNECT` proxy, Atomic tunnels pooled connections, [wake-up](#wake-ups) connections, and statement-cancel connections through the proxy. Allowlist `<database host>:5432` (or your configured port) on the proxy.
212
-
213
- - **Proxy selection.** Atomic reads `HTTPS_PROXY` (or `https_proxy`), then `ALL_PROXY` when it names an `http://` or `https://` proxy, then `HTTP_PROXY`. Credentials in the proxy URL are sent via `Proxy-Authorization` and redacted from logs and errors.
214
- - **Host exemptions.** `NO_PROXY` (or `no_proxy`) exempts matching hosts (`db.example.com`, `.example.com`, `example.com`, `*.example.com`, `host:port`, or `*`). Local hosts (`localhost`, loopback addresses, and Unix socket directories) connect directly regardless of proxy environment variables.
215
- - **Per-store override.** Set `options.proxy` to a proxy URL to route all connections through it, or to `"none"` to bypass environment proxies. SDK callers can pass `proxy` or a custom `socket` factory to `openPostgresDatabase`, but not both. Socket directories always connect directly.
216
- - **End-to-end TLS.** Atomic negotiates TLS with PostgreSQL inside the tunnel. With default `verify-full` (or `require` without `sslrootcert`), the certificate must match the database hostname so the proxy sees only encrypted traffic. `verify-ca` (and `require` with `sslrootcert`) protects against proxy interception only when `sslrootcert` points to a private CA dedicated to your database servers.
217
-
218
- Atomic handles informational `1xx` proxy replies (such as `103 Early Hints`) and allows up to 16 KiB for total proxy response headers.
219
-
220
- If the proxy refuses the tunnel (`403` or `407`), opening fails immediately with `StorageUnavailableError` without retrying. Connection refusals, dropped connections, and `502` or `503` responses retry like an unreachable server (about 4 seconds for refused connections, or up to about 45 seconds when attempts time out after 8 seconds each), with a warning naming the proxy and failure reason.
221
-
222
- ### Connection budget
223
-
224
- Each Atomic process holds one set of connections per database. The session store, in-process subagents' session stores, chat records, search, the Intercom broker's state, and all their read handles share it, when they use the same URL, role, password, `listenUrl`, `auth`, `schema`, `proxy`, and pool settings. The set closes when the last store using it closes. It holds:
225
-
226
- - **A main pool** of up to `maxConnections` connections, 8 by default, opened as calls need them. In `pg_stat_activity`, their `application_name` is `atomic`.
227
- - **A reader pool** of up to `readerMaxConnections` connections, 2 by default and never more than `maxConnections`. Reads use it, so they do not wait for connections that writes are using. Their `application_name` is `atomic-reader`.
228
- - **One listening connection** for [wake-ups](#wake-ups), opened once something in the process listens, such as an Intercom broker. Its `application_name` is `atomic-listen`.
229
-
230
- So a process opens at most `maxConnections` + `readerMaxConnections` + 1 connections per database: 11 with the defaults.
231
-
232
- Pools grow for bursts and shrink afterwards. A connection opened for a burst closes after 10 seconds without use. A pool's last connection stays open for `idleTimeoutMs`, 5 minutes by default, after the pool's last call, so a call after a pause skips the connection and TLS handshakes. Unused connections do not keep the process from exiting.
233
-
234
- This follows common pool designs. [HikariCP](https://github.com/brettwooldridge/HikariCP#frequently-used) closes idle connections above a minimum and recommends [small pools](https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing). Rails keeps [one pool per process and database](https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/ConnectionPool.html) and closes connections idle for 300 seconds. [pgx](https://github.com/jackc/pgx/blob/master/pgxpool/pool.go) keeps no minimum and closes connections idle for 30 minutes. node-postgres closes idle connections after 10 seconds by default.
235
-
236
- In one measurement, a process with a session store and an Intercom broker made 100 session saves and 100 Intercom sends, 4 at a time each. It peaked at 8 connections instead of 9. Ten seconds after the burst, it held 3 connections, one in each pool and the listening one, instead of 9. With `maxConnections: 2`, the peak dropped from 7 to 5 and the idle count from 7 to 3.
237
-
238
- The Intercom broker runs in its own process on each machine. Count each machine's broker process and each `atomic` process separately. How to size these settings:
239
-
240
- - **A few long-lived processes**, such as one interactive session per machine: the defaults suit them. Each process holds 2 to 3 connections between bursts, and up to the maximum above during one.
241
- - **Many processes, such as a swarm of agent runners:** work out `maxConnections` from the server's limit with [Tuning for many concurrent agents](#tuning-for-many-concurrent-agents). If the processes often sit idle, lower `idleTimeoutMs` to between 10000 and 30000, so idle processes give back their last pooled connection. Each process that listens still holds its listening connection.
242
- - **More processes than the server allows:** connect through [PgBouncer](/guides/postgres-pgbouncer) in transaction mode and set `listenUrl` to the server's direct address. Then only the listening connections count against the server directly.
243
-
244
- ### Connection poolers
34
+ | One person on one machine | [Local SQLite](/storage/sqlite), the default | Needs no setup |
35
+ | Data that must not leave the machine | Local SQLite | Nothing leaves the machine |
36
+ | Sessions and Intercom shared by several machines, a team, or CI | [PostgreSQL](/storage/postgres) | Many machines can write at once, and managed services add backups and high availability. Everyone who can read the database can read every session in it |
37
+ | More than about 8 Atomic processes on one PostgreSQL server with its default limit of 100 connections | PostgreSQL behind [PgBouncer](/storage/postgres/pgbouncer) | Each Atomic process can open up to 10 connections, and each Intercom broker 11. [Count the connections](/storage/postgres#count-the-connections-atomic-needs) first |
38
+ | Sessions as plain text files you can read, back up, or delete by hand, on one machine | [JSONL](/storage/jsonl) | One file per session. Holds sessions only, and forks copy their history |
39
+ | A database Atomic does not support | A [custom adapter](/storage/custom-adapters) | You write the connection code |
245
40
 
246
- Atomic works with transaction-mode poolers, including PgBouncer, Azure's built-in PgBouncer (port 6432), Supabase Supavisor (port 6543), and Neon's `-pooler` endpoint. Use transaction or session mode, never statement mode.
41
+ A JSONL directory holds sessions only. [JSONL setup](/storage/jsonl) shows how to select it.
247
42
 
248
- Atomic keeps schema selection (`SET LOCAL search_path`), statement and lock timeouts, and advisory locks scoped inside transactions so pooled connections return clean. Because transaction poolers cannot relay `LISTEN`/`NOTIFY`, set `listenUrl` to the server's direct endpoint (such as port 5432 on Azure or Neon's unpooled host) to keep [wake-ups](#wake-ups) active while queries stay pooled.
249
-
250
- To run your own PgBouncer, follow the [PgBouncer guide](/guides/postgres-pgbouncer). It has a complete configuration with TLS and SCRAM, how to size the pools, and how to check that it works.
251
-
252
- ### Wake-ups
253
-
254
- On PostgreSQL, Intercom brokers receive instant notifications of new messages through `LISTEN`/`NOTIFY`. Each Atomic process that listens, such as an Intercom broker, holds one listening connection per database in addition to its pools. Everything in the process that listens shares it.
255
-
256
- While notifications are active, each broker also checks for missed messages every 5 seconds. If the listening connection drops or `url` points to a transaction pooler without `listenUrl`, brokers fall back to checking every half second, so no messages are lost. Atomic checks the listening connection every 30 seconds and reconnects if it drops. If it detects a transaction pooler, it stops retrying wake-ups until the process restarts.
257
-
258
- `atomic storage status` reports the wake-up state:
259
-
260
- - `wake-ups: LISTEN/NOTIFY` means instant notifications are active.
261
- - `wake-ups: polling only, notifications do not pass the URL's transaction pooler` means you should set `listenUrl` to a direct endpoint.
262
- - `wake-ups: polling only, the listen connection failed` means the listening endpoint could not be reached or rejected login. Check `listenUrl` and the server connection limit.
263
-
264
- ### Azure
265
-
266
- **Azure Database for PostgreSQL Flexible Server:**
267
-
268
- - Connect directly to `<server>.postgres.database.azure.com` on port 5432.
269
- - Port 6432 uses the built-in PgBouncer transaction pooler on General Purpose and Memory Optimized tiers after enabling `pgbouncer.enabled`. Set `listenUrl` to port 5432 so [wake-ups](#wake-ups) work.
270
- - Add `PG_TRGM` to the `azure.extensions` server parameter before running `atomic storage migrate` so Atomic can index session history search. Without it, searches scan sessions page by page, and `atomic storage migrate` tells you to rerun after enabling it.
271
- - Watch connection limits. A Burstable B1ms server allows 50 connections (15 reserved for administrators), and each Atomic process opens up to `maxConnections` (8), 2 reader connections, and one wake-up connection. Lower `maxConnections`, use PgBouncer, or scale up for multiple processes. See [Connection budget](#connection-budget).
272
- - Allow client addresses in firewall rules or use private access.
273
-
274
- **Azure HorizonDB (preview, PostgreSQL 17):**
275
-
276
- - Connect to the cluster read/write endpoint (`<cluster>.rw.<id>.<region>.horizondb.azure.com` on port 5432). Do not use a read-only endpoint because Atomic writes on every connection. Wake-ups work on the read/write endpoint.
277
- - Add `pg_trgm` to `azure.extensions` in the compute pool's parameter group, then run `atomic storage migrate`.
278
- - Allow client addresses in firewall rules or connect over a private endpoint.
279
-
280
- Both Azure services use certificates trusted by Node.js, work with the role setup in [Set up the database](#set-up-the-database), and support Microsoft Entra authentication with `--auth azure`.
281
-
282
- ### Cloud identities
283
-
284
- With `--auth` (or `options.auth` in settings), Atomic requests a short-lived token from the machine's cloud identity for each new connection and keeps tokens only in memory. Install the cloud provider's SDK alongside the adapter:
285
-
286
- | `--auth` | `options.auth` | Install | Credential source |
287
- | --- | --- | --- | --- |
288
- | `azure` or `azure-entra` | `"azure-entra"` | `atomic install npm:@azure/identity` | `AZURE_*` variables, AKS workload identity, VM/App Service/Container App managed identity (`AZURE_CLIENT_ID` selects user-assigned), or `az login` |
289
- | `aws` or `aws-iam` | `"aws-iam"` | `atomic install npm:@aws-sdk/rds-signer` | Default AWS credentials (`AWS_*` variables, profiles, IRSA, or instance profile) |
290
- | `gcp` or `gcp-iam` | `"gcp-iam"` | `atomic install npm:google-auth-library` | Application Default Credentials (`GOOGLE_APPLICATION_CREDENTIALS`, Compute Engine/GKE/Cloud Run metadata server, or `gcloud auth application-default login`) |
291
-
292
- If the SDK is missing or cannot issue a token, opening fails with `StorageConfigError` (`reason: "auth-unavailable"`). Cloud tokens require TLS, so keep the default `sslmode`.
293
-
294
- Map the cloud identity to a PostgreSQL role on your provider:
295
-
296
- - **Azure (Flexible Server or HorizonDB).** Enable Microsoft Entra authentication and add an Entra administrator. Connected to `postgres` as that administrator, run `SELECT * FROM pgaadauth_create_principal('<identity name>', false, false);` and grant `CONNECT` on the Atomic database. Use that role name in the URL.
297
- - **AWS.** Enable IAM database authentication, run `CREATE USER atomic; GRANT rds_iam TO atomic;`, and grant the IAM identity `rds-db:connect` on `arn:aws:rds-db:<region>:<account>:dbuser:<DbiResourceId>/atomic`.
298
- - **Google Cloud.** Set `cloudsql.iam_authentication=on`, add the service account as an IAM database user, and grant `roles/cloudsql.instanceUser`. Use the service account email without `.gserviceaccount.com` as the URL username. Compute Engine VMs need the `cloud-platform` scope.
299
-
300
- Grant the mapped identity the runtime privileges from [Set up the database](#set-up-the-database), and run `atomic storage migrate` as the owner role. See [`@bastani/atomic-storage-postgres`](/libraries/storage-postgres) for service-specific details and [SDK session storage](/sdk/storage) for SDK integration recipes.
301
-
302
- Running `atomic install npm:@azure/identity` (or the AWS or Google SDK) installs the package under `~/.atomic/agent/npm`. The PostgreSQL adapter searches both its own directory and `~/.atomic/agent/npm`, so adapters installed from local paths find the SDK too.
303
-
304
- ### Troubleshooting PostgreSQL
305
-
306
- - **`credential-in-url`.** Remove the password from the URL and pass `--password-file` or `--token-file`.
307
- - **`unsupported-url` from `atomic team join`.** `atomic team join` supports libSQL only. Use `atomic storage join` for PostgreSQL.
308
- - **`unsupported-option`.** `--password-file` and `--auth` apply to PostgreSQL only. libSQL uses `--token-file`.
309
- - **`unsupported-auth`.** `--auth` accepts `azure` (`azure-entra`), `aws` (`aws-iam`), or `gcp` (`gcp-iam`).
310
- - **`adapter-not-installed`.** Run `atomic install npm:@bastani/atomic-storage-postgres` as the user running Atomic.
311
- - **`auth-unavailable`.** Install the cloud SDK named in the error and confirm the machine has a valid cloud identity. Atomic does not retry this error.
312
- - **`missing-privilege` (`42501` or `3F000`).** Run the `GRANT` named in the error for a runtime role (see [Set up the database](#set-up-the-database)), or run `atomic storage migrate` as the owner role if the error mentions ownership or `CREATE`.
313
- - **"This database was upgraded since this process started".** `atomic storage migrate` moved tables from `public` to `atomic` while this process was running. Restart the process.
314
- - **Refused token (`28P01` or Azure `28000`).** The token expired, targets the wrong user, or has an invalid format. For Azure, request a token for `https://ossrdbms-aad.database.windows.net` (`az account get-access-token --resource-type oss-rdbms`) or use `--auth azure`.
315
- - **`StorageUnavailableError` on open.** The server rejected credentials (`28P01` or `28000`), the database does not exist (`3D000`), or the server is older than PostgreSQL 14. Atomic sessions require PostgreSQL 16 or newer.
316
- - **Certificate untrusted (`self-signed certificate in certificate chain` or `unable to get local issuer certificate`).** Add `sslrootcert` pointing to your server CA. See [TLS](#tls).
317
- - **`INVALID_PURPOSE`.** The certificate in `sslrootcert` lacks `basicConstraints=CA:TRUE` or is restricted to client authentication. Point `sslrootcert` to the signing CA or reissue it with `CA:TRUE`. Not retried.
318
- - **`PATH_LENGTH_EXCEEDED`.** The certificate chain exceeds its root CA path-length limit. Reissue the root without that limit or sign the server certificate directly. Not retried.
319
- - **`UNSPECIFIED` with a reason (such as `key usage does not include certificate signing`).** Node.js reports certain certificate rejections with this code. Follow the reason text, such as reissuing the CA with `keyCertSign`. Not retried.
320
- - **Proxy certificate rejected.** An `https://` proxy's own certificate is checked against Node.js CAs, never `sslrootcert`. Add a private proxy CA to [`NODE_EXTRA_CA_CERTS`](/environment-variables#tls-certificates). Not retried.
321
- - **Proxy refused tunnel or unreachable.** Allowlist the database `host:port` on the proxy, supply proxy credentials for `407`, verify `HTTPS_PROXY`, or bypass the proxy with `NO_PROXY` or `proxy: "none"`. See [Through an HTTP proxy](#through-an-http-proxy).
322
- - **`unsupported-proxy`.** Proxy URLs must use `http://` or `https://` (not `socks5://`). Switch to an HTTP proxy or bypass it with `NO_PROXY` or `proxy: "none"`.
323
- - **`StorageTransientError` with code `read-only-server` (`25006`).** Point `url` at the primary read/write endpoint instead of a replica, or retry once failover or storage-full recovery completes.
324
- - **`sorry, too many clients already`, `remaining connection slots are reserved for roles with the SUPERUSER attribute`, or `too many connections for role "<role>"` (`53300`).** The server, or the role's `CONNECTION LIMIT`, has no connection left. Atomic reports `StorageTransientError` with code `connection-refused`, and the server's message is its cause. Lower `maxConnections` or `readerMaxConnections`, raise the server's `max_connections`, or put [PgBouncer](/guides/postgres-pgbouncer) in front. See [Tuning for many concurrent agents](#tuning-for-many-concurrent-agents).
325
- - **`timeout exceeded when trying to connect`.** Every connection in the process's pool stayed busy, or a new connection took longer than `connectTimeoutMs` to open. Atomic reports `StorageTransientError` with code `connection-refused`, and this message is its cause. Raise `maxConnections` if the server has connections to spare. Raise `connectTimeoutMs` if the server is far away or slow to accept connections.
326
- - **`prepared statement "atomic_…" does not exist` or `already exists` behind a pooler.** The pooler does not keep prepared statements across connections. Atomic then stops preparing statements for the rest of the process and retries the call, so you usually see only a one-time warning. A call Atomic cannot retry fails once with `StorageTransientError` code `connection-lost`, and the pooler's message is its cause. Set `maxPreparedStatements` to `0`, or on PgBouncer 1.21 or later set `max_prepared_statements` above `0`. Atomic turns prepared statements on by itself only behind a PgBouncer it has confirmed keeps them, so you see this only after setting `maxPreparedStatements` yourself, behind a pooler on another port, or after changing PgBouncer's setting while Atomic runs.
327
- - **`StorageTransientError` with code `lock-conflict` or `transaction-timeout`.** The server cancelled a statement or transaction that waited too long or exceeded `statementTimeoutMs`, and wrote nothing. Repeated errors indicate server overload.
328
- - **`wake-ups: polling only` in `atomic storage status`.** Messages still arrive via polling. See [Wake-ups](#wake-ups) to restore `LISTEN`/`NOTIFY`.
329
- - **Failover or pooler restart disconnects.** Reported as `StorageTransientError` with code `connection-lost`.
330
-
331
- ## Turso and libSQL
332
-
333
- `@bastani/atomic-storage-libsql` stores sessions and multi-node Intercom routing in Turso or self-hosted `sqld` with one URL and one token. Install it in user scope and configure `~/.atomic/agent/settings.json`:
334
-
335
- ```bash
336
- atomic install npm:@bastani/atomic-storage-libsql
337
- ```
338
-
339
- ```json
340
- {
341
- "storage": {
342
- "adapter": "@bastani/atomic-storage-libsql",
343
- "options": { "url": "libsql://<db>.turso.io" },
344
- "secrets": { "authToken": { "file": "turso-token" } }
345
- }
346
- }
347
- ```
348
-
349
- - **Self-hosted `sqld`.** Always start `sqld` with `--checkpoint-interval-s 60` (or `SQLD_CHECKPOINT_INTERVAL_S=60`). Without it, `sqld` 0.24.33 and earlier can stall writes during WAL checkpoints. Atomic warns after three consecutive unanswered writes. Interval checkpoints pause writes briefly (up to 5 seconds) while Atomic retries automatically.
350
- - **Namespaces and headers.** For `sqld --enable-namespaces`, set `"namespace": "<name>"` in `options` (sent as `x-namespace` over `libsql:`, `https:`, or `http:` URLs). SDK callers can also pass extra `headers` to `openLibsqlDatabase`, which Atomic redacts from errors.
351
- - **Tokens and local files.** Save a Turso token with `turso db tokens create <db> > turso-token && chmod 600 turso-token` (one trailing line ending is stripped when read from `secrets.authToken.file`, and relative paths resolve against [storage home](#storage-home)), or reference `{ "env": "TURSO_TOKEN" }`. Absolute `file:` URLs need no `secrets`. Add `prefix` to isolate projects or teams.
352
- - **Throughput.** A libSQL database has one writer at a time. The `concurrency` option sets how many reads one connection runs at the same time. See [Tuning libSQL and Turso](#tuning-libsql-and-turso).
353
- - **Retries and WebSockets.** Transient outages, expired streams, and 30-second unanswered requests report `StorageTransientError`. Calls that failed before writing retry up to 5 times over about 4 seconds. Writes with an uncertain outcome fail immediately with `outcome: "unknown"` and are not retried automatically. Over `ws:` or `wss:`, a batch whose `COMMIT` does not run reports `StorageUnavailableError` (`TRANSACTION_CLOSED`).
354
-
355
- For Node.js and TypeScript SDK apps, install `@bastani/atomic-storage-libsql` with `npm install` and import `openLibsqlDatabase` directly as plain ESM with TypeScript declarations. See [`@bastani/atomic-storage-libsql`](/libraries/storage-libsql) and [SDK session storage](/sdk/storage). To wrap another driver, see [Bring your own driver](#bring-your-own-driver).
43
+ To move existing sessions to another store, see [Exporting and importing sessions](#exporting-and-importing-sessions). Atomic no longer supports Turso and libSQL. If you used them, see [Moving off libSQL](#moving-off-libsql).
356
44
 
357
45
  ## Sharing storage across hosts
358
46
 
359
- Share sessions and Intercom across machines or CI fleets by pointing every host at the same [PostgreSQL](#postgresql) or [Turso / libSQL](#turso-and-libsql) database with the same `prefix`. Never put a local SQLite file on a network filesystem.
47
+ To share sessions and Intercom between machines, point every machine at the same [PostgreSQL](/storage/postgres) database, with the same `prefix`. A prefix starts the name of each of Atomic's tables, so several teams can share one database. Never put a local SQLite file on a network drive or a synced folder.
360
48
 
361
- - **Shared `storage` vs. `sessions.storage`.** Configuring top-level `storage` (in global settings, `--storage`, `--storage-file`, or `ATOMIC_STORAGE`) enables multi-node Intercom routing across hosts. Setting only `sessions.storage` shares sessions without enabling multi-node Intercom. On libSQL, single Intercom messages over 5,000,000 bytes fail with `StoragePayloadTooLargeError`.
362
- - **Data stored and access.** The shared database holds sessions, tool-output blobs, [worktree snapshot](/worktree-snapshots) blobs, and transient Intercom messages. Treat database read access as full read access. To share Intercom while keeping personal sessions local, use `atomic team join` as described in [Set up teams and CI](/guides/team-setup). To resume sessions across machines, see [Resume sessions on any machine](/guides/resume-on-any-machine).
49
+ Which setting you change decides what is shared:
363
50
 
364
- ### Joining a machine to a shared database
365
-
366
- > Want shared Intercom while keeping personal sessions local? Use `atomic team join` instead ([Set up teams and CI](/guides/team-setup)).
367
-
368
- **libSQL / Turso:**
51
+ | Setting | Shares sessions | Shares Intercom between machines |
52
+ | --- | --- | --- |
53
+ | Top-level `storage` in global settings, `~/.atomic/agent/settings.json`, or `ATOMIC_STORAGE`, `--storage`, or `--storage-file` | Yes | Yes |
54
+ | `sessions.storage` only, pointing at the shared database | Yes | No |
55
+ | Top-level `storage` in global settings, plus `sessions.storage` set to `{}` | No, sessions stay in the local default file | Yes |
369
56
 
370
- ```bash
371
- atomic install npm:@bastani/atomic-storage-libsql
372
- turso db tokens create <db> > ~/turso-token
373
- atomic storage join libsql://<db>.turso.io --token-file ~/turso-token
374
- atomic intercom restart
375
- atomic storage status
376
- ```
57
+ Project settings can choose where a project's sessions go, but never Intercom's store.
377
58
 
378
- **PostgreSQL (PostgreSQL 16 or newer for sessions):**
59
+ Sharing Intercom between machines is called multi-node routing: an agent on one machine can message an agent on another. Atomic runs one Intercom broker per agent directory, usually one per machine or container. The broker is a background process that passes messages between agents, and with multi-node routing it passes them through the shared database. See [Running Intercom across machines](/intercom/operations#running-intercom-across-machines).
379
60
 
380
- In two-role deployments, run `atomic storage migrate --db 'postgresql://atomic_owner@db.example.com:5432/atomic' --password-file ~/atomic-owner-password` once as the owner role, and after Atomic upgrades, before joining machines with the runtime role. See [Set up the database](#set-up-the-database).
61
+ The shared database holds sessions, tool output, worktree snapshots, and Intercom messages in transit. Anyone who can read the database can read all of them, so grant read access as you would to the sessions themselves. To resume a session on another machine, see [Resume sessions on any machine](/guides/resume-on-any-machine).
381
62
 
382
- ```bash
383
- atomic install npm:@bastani/atomic-storage-postgres
384
- atomic storage join postgresql://atomic_runtime@db.example.com:5432/atomic?sslmode=verify-full --password-file ~/pg-password
385
- atomic intercom restart
386
- atomic storage status
387
- ```
63
+ ### Joining a machine to a shared database
388
64
 
389
- `atomic storage join <url> [options]` runs four steps:
65
+ To create the database, follow [Set up the database](/storage/postgres#set-up-the-database). To join a machine to it, follow [Join a machine](/storage/postgres#join-a-machine): install the PostgreSQL adapter, save the password in a file, run `atomic storage join`, and restart Intercom.
390
66
 
391
- 1. Validates the URL, adapter installation, and credentials, then runs a read-only `SELECT 1` within 15 seconds. If any check fails, nothing is written.
392
- 2. Stores static credentials (`--token-file` for libSQL, trimming surrounding whitespace; `--password-file` for PostgreSQL) in a mode-`600` `~/.atomic/agent/storage-token.<id>` file, reusing an existing identical file and leaving older files intact for running sessions.
393
- 3. Updates only the top-level `storage` key in `~/.atomic/agent/settings.json` (plus optional `--prefix`), preserving all other settings.
394
- 4. Lists any higher-precedence environment variables or project settings and notes if the running Intercom broker still uses the previous store. Run `atomic intercom restart` to switch the broker ([Running Intercom across machines](/intercom/operations#running-intercom-across-machines)).
67
+ `atomic storage join <url>` does four things:
395
68
 
396
- URL and credential rules:
69
+ 1. It checks the URL, the adapter, and the credentials, then runs `SELECT 1` on the database within 15 seconds. If any check fails, it writes nothing.
70
+ 2. It copies a `--password-file` into a private file in the agent directory, `~/.atomic/agent/storage-token.<id>`, readable only by you. A `--token-file` stays where it is, and Atomic reads it again for every new connection.
71
+ 3. It sets the top-level `storage` key in `~/.atomic/agent/settings.json`, and `prefix` if you passed `--prefix`. It replaces any `storage` value that was there and keeps no copy, so save the old value first if you need it. It changes no other setting.
72
+ 4. It lists any environment variable or project setting that overrides the new setting, and says whether the running Intercom broker still uses the old store.
397
73
 
398
- - **No embedded secrets.** Userinfo passwords and `authToken=` or `password=` query parameters are refused.
399
- - **libSQL schemes.** Accepts `libsql://`, `https://`, `http://`, `wss://`, `ws://`, or an absolute `file:` URL (which needs no token). Prefer TLS (`libsql://`, `https://`, or `wss://`) for remote hosts; `http://` and `ws://` are intended for local or private-network `sqld`. Relative `file:` URLs, `--password-file`, and `--auth` are refused.
400
- - **PostgreSQL credentials.** Pass exactly one of `--password-file <path>` (copied to a private file), `--token-file <path>` (external rotated file referenced by path and reread per connection, stripping only one trailing `\n` or `\r\n`), or `--auth azure|aws|gcp` (also accepts `azure-entra`, `aws-iam`, `gcp-iam`). The same flags work with `atomic storage migrate --db`.
74
+ The URL must not contain a password. Pass exactly one of `--password-file <path>`, `--token-file <path>`, or `--auth azure|aws|gcp`. `atomic storage migrate --db <url>` takes the same options.
401
75
 
402
76
  ### Checking the selected storage
403
77
 
404
- Run `atomic storage status` (or `atomic storage status --json`) inside your project directory to inspect effective storage for sessions and Intercom.
78
+ Run `atomic storage status` in your project directory, or `atomic storage status --json` for scripts. For sessions and for Intercom, it shows:
405
79
 
406
- - Reports the active source (environment variable, project settings, global `storage` or `sessions.storage`, or default), overridden selections, untrusted project settings, and project `storage` settings (ignored by Intercom).
407
- - Verifies adapter loading and runs `SELECT 1` with a 15-second timeout per phase. Local SQLite and `file:` URLs probe read-only without creating missing files. PostgreSQL also reports the server version.
408
- - Shows live Intercom broker status, session count, multi-node routing state, and active peer brokers in the shared database.
80
+ - which store is selected, and where the choice comes from: an environment variable, project settings, global settings, or the default;
81
+ - any setting that is overridden or ignored, such as project settings in an untrusted project;
82
+ - whether the adapter loads, and whether the database answers `SELECT 1` within 15 seconds. For PostgreSQL, it also shows the server version;
83
+ - the running Intercom broker, its session count, whether multi-node routing is on, and the other brokers sharing the database.
409
84
 
410
- Exits `1` if settings cannot load, a selection is invalid, an adapter fails to load, or the database does not answer. CLI sessions also warn at startup when shared `storage` names an unloadable adapter.
85
+ It never creates or changes anything. A local SQLite file is opened read-only. It exits `1` if the settings cannot be read, a selection is invalid, an adapter fails to load, or a database does not answer. Interactive sessions also warn at startup when the shared `storage` names an adapter that does not load.
411
86
 
412
- ### Selecting storage per process
87
+ ## Selecting storage per process
413
88
 
414
- A host launching Atomic processes (such as `atomic --mode rpc` children) can override storage for those processes without editing `settings.json`. Each option accepts the same JSON shape as the `storage` setting (`adapter`, `options`, `secrets`, and `prefix`):
89
+ A program that launches Atomic, such as a CI job or an app that runs `atomic --mode rpc`, can choose the store for that process without editing `settings.json`. Each option takes the same JSON object as the `storage` setting, with `adapter`, `options`, `secrets`, and `prefix`:
415
90
 
416
- | Option | Applies to | Equivalent setting |
91
+ | Option | Applies to | Same as the setting |
417
92
  | --- | --- | --- |
418
- | `--storage '<json>'` | Sessions and Intercom (cannot use `{ "dir": "..." }`) | Shared `storage` |
419
- | `--storage-file <path>` | Sessions and Intercom (reads JSON from a file; cannot use `{ "dir": "..." }`) | Shared `storage` |
420
- | `ATOMIC_STORAGE` | Sessions and Intercom (cannot use `{ "dir": "..." }`) | Shared `storage` |
421
- | `ATOMIC_SESSIONS_STORAGE` | Sessions only (also accepts `{ "dir": "..." }` for JSONL) | `sessions.storage` |
422
- | `ATOMIC_PROFILE=ci` with `ATOMIC_TEAM_URL`, `ATOMIC_TEAM_TOKEN` or `ATOMIC_TEAM_TOKEN_FILE`, and optional `ATOMIC_TEAM_PREFIX` | Sessions and Intercom on the team libSQL database | See [CI and swarms](/guides/team-setup#ci-and-swarms) |
93
+ | `--storage '<json>'` | Sessions and Intercom | `storage` |
94
+ | `--storage-file <path>` | Sessions and Intercom. Reads the JSON from a file | `storage` |
95
+ | `ATOMIC_STORAGE` | Sessions and Intercom | `storage` |
96
+ | `ATOMIC_SESSIONS_STORAGE` | Sessions only. Also accepts `{ "dir": "..." }` for a JSONL directory | `sessions.storage` |
423
97
 
424
98
  ```bash
425
- ATOMIC_STORAGE='{"adapter":"@example/atomic-sqlite","options":{"url":"libsql://team.example"},"secrets":{"authToken":{"env":"TEAM_DB_TOKEN"}},"prefix":"svc_"}' \
99
+ ATOMIC_STORAGE='{"adapter":"@bastani/atomic-storage-postgres","options":{"url":"postgresql://atomic_runtime@db.example.com:5432/atomic"},"secrets":{"password":{"env":"ATOMIC_DB_PASSWORD"}},"prefix":"svc_"}' \
426
100
  atomic --mode rpc
427
101
 
428
102
  atomic --mode rpc --storage-file /etc/atomic/storage.json
429
103
  ```
430
104
 
431
- `--storage` and `--storage-file` cannot be combined. Interactive sessions keep `--storage` active for the session, while spawned child processes inherit environment variables (such as `ATOMIC_STORAGE`) rather than CLI flags.
432
-
433
- One Intercom broker serves every session in an agent directory and keeps the storage selection of the process that started it until it exits or `atomic intercom restart` replaces it. Project settings never select the broker's storage.
434
-
435
- Precedence for sessions, highest first:
436
-
437
- 1. Explicit SDK `sessionManager` (bypasses store selection)
438
- 2. SDK `sessionStore`
439
- 3. SDK `createAgentSession({ storage })`
440
- 4. `--session-store`, `--no-session`, or `--session-dir`
441
- 5. `--storage` or `--storage-file`
442
- 6. `ATOMIC_SESSIONS_STORAGE` or `ATOMIC_CODING_AGENT_SESSION_DIR`
443
- 7. `ATOMIC_STORAGE`
444
- 8. `ATOMIC_PROFILE=ci`
445
- 9. `sessions.storage` setting
446
- 10. Shared `storage` setting
447
- 11. Default local SQLite file (`~/.atomic/workflows/journal.sqlite`)
448
-
449
- Override conflicts and path rules:
450
-
451
- - Session flags such as `--session-dir` override `--storage` for sessions only, leaving Intercom on `--storage`.
452
- - `ATOMIC_CODING_AGENT_SESSION_DIR` overrides `ATOMIC_STORAGE` for sessions only.
453
- - Combining `ATOMIC_SESSIONS_STORAGE` or `--storage` / `--storage-file` with a non-empty `ATOMIC_CODING_AGENT_SESSION_DIR` fails startup with `StorageConfigError` (`reason: "conflicting-overrides"`). Unset one variable or pass an explicit session flag.
454
- - Relative `path`, `dir`, and `secrets.file` values resolve against [storage home](#storage-home). Relative adapter specifiers resolve from the agent directory. Relative `--storage-file` paths resolve from the current working directory. Empty variables are ignored.
455
-
456
- Before starting any session (in every mode, including RPC and SDK `createAgentSession()`), Atomic validates `--storage`, `--storage-file`, `ATOMIC_STORAGE`, `ATOMIC_SESSIONS_STORAGE`, and `ATOMIC_PROFILE=ci`, even when outranked by a higher-precedence override. Invalid JSON, schema violations, unreadable files, or incomplete CI variables exit cleanly with `Error: ...` (exit code `1`) on the CLI or throw `StorageConfigError` / `TeamProfileConfigError` in the SDK without falling back to another store. Errors name only the variable or flag, never secret values.
457
-
458
- Process-level storage options bypass [project trust](/security) because they come from the launching host. Because adapter modules execute code with Atomic's privileges, select only trusted modules and pass credentials through `secrets` instead of `options`. Prefer `--storage-file` or environment variables over `--storage` when the selection itself is sensitive, because command-line arguments can be visible to other local users.
459
-
460
- SDK callers can also keep a token strictly in memory with `inMemorySecret(token)` or `teamProfileSelection({ token })` (`{ "value": token }`), which serializes as `[redacted]` and is refused in settings, CLI flags, or environment variables.
461
-
462
- ## Tuning for many concurrent agents
463
-
464
- How many agents can write at once depends on the store. On PostgreSQL it depends on how many connections each process may open. Writes to different sessions run in parallel, each on its own connection. Writes to one session wait for each other. On libSQL and local SQLite, one writer at a time writes a database, and no setting changes that.
465
-
466
- ### Tuning PostgreSQL
467
-
468
- This section covers Atomic's own settings. For the server side, such as memory, monitoring, and the tables that change most, see [Tune PostgreSQL for many agents](/guides/postgres-tuning).
469
-
470
- For high throughput, set `maxConnections` to the maximum the server allows, or a generous value. More connections let more writes from one process run at the same time. The limit is the server's `max_connections`, which every Atomic process on every machine shares.
471
-
472
- #### Count the connections Atomic needs
473
-
474
- Each Atomic process opens up to this many connections:
475
-
476
- - **An agent process**, including each `atomic --mode rpc` child: `maxConnections` plus `readerMaxConnections`.
477
- - **An Intercom broker**: `maxConnections` plus `readerMaxConnections`, plus 1 for [wake-ups](#wake-ups).
478
-
479
- Atomic opens a connection only when it needs one, so a quiet process holds fewer. Plan for the maximum anyway, because busy processes reach it.
480
-
481
- Find what the server has to share. Run these as an administrator:
482
-
483
- ```sql
484
- SHOW max_connections;
485
- SHOW superuser_reserved_connections;
486
- SHOW reserved_connections; -- PostgreSQL 16 and later
487
- SELECT count(*) FROM pg_stat_activity
488
- WHERE backend_type = 'client backend' AND application_name NOT LIKE 'atomic%';
489
- ```
490
-
491
- The connections Atomic may use are `max_connections`, minus both reserved counts, minus what other clients use. Call that number *available*. With *P* Atomic processes, of which *B* are brokers, each process may use `(available - B) / P` connections, rounded down. Set `maxConnections` to that number minus `readerMaxConnections`.
492
-
493
- #### Example: 24 processes on a large server
494
-
495
- Four machines each run five agent processes and one Intercom broker, so *P* is 24 and *B* is 4. The server has `max_connections = 500`, 3 superuser slots, no other reserved slots, and 20 connections used by other clients.
496
-
497
- - *available* is 500 − 3 − 0 − 20 = 477.
498
- - Each process may use (477 − 4) / 24 = 19.7, rounded down to 19.
499
- - With the default `readerMaxConnections` of 2, set `maxConnections` to 19 − 2 = 17.
500
-
501
- In `~/.atomic/agent/settings.json` on each machine:
502
-
503
- ```json
504
- {
505
- "storage": {
506
- "adapter": "@bastani/atomic-storage-postgres",
507
- "options": {
508
- "url": "postgresql://atomic_runtime@db.example.com:5432/atomic",
509
- "maxConnections": 17,
510
- "readerMaxConnections": 2
511
- },
512
- "secrets": { "password": { "file": "agent/storage-token.3f2a" } }
513
- }
514
- }
515
- ```
516
-
517
- The same options in an SDK app:
518
-
519
- ```typescript
520
- import { openPostgresDatabase } from "@bastani/atomic-storage-postgres";
521
-
522
- const database = await openPostgresDatabase({
523
- url: "postgresql://atomic_runtime@db.example.com:5432/atomic",
524
- password: process.env.ATOMIC_DB_PASSWORD,
525
- maxConnections: 17,
526
- readerMaxConnections: 2,
527
- });
528
- ```
529
-
530
- #### Example: 200 machines on a smaller server
531
-
532
- Two hundred CI runners each run one agent process and one Intercom broker, so *P* is 400 and *B* is 200. The server has `max_connections = 300`, 3 superuser slots, and 10 connections used by other clients, so *available* is 287.
533
-
534
- Even at the smallest settings, `maxConnections: 1` and `readerMaxConnections: 0`, the processes need 400 × 1 + 200 = 600 connections. That is more than 287, so connect through a transaction pooler such as PgBouncer instead. Switch to a pooler whenever the arithmetic gives `maxConnections` below 2.
535
-
536
- With PgBouncer in transaction mode on port 6432:
537
-
538
- - Point `url` at PgBouncer. Connections to PgBouncer cost the server nothing, so keep `maxConnections` at its default of 8. Set PgBouncer's `max_client_conn` to at least *P* × (`maxConnections` + `readerMaxConnections`), here 400 × 10 = 4000.
539
- - PgBouncer cannot pass wake-up notifications. Either point `listenUrl` at the server directly, which uses one server connection per broker, or leave it out. With `listenUrl`, brokers are notified of new messages and check for missed ones every 5 seconds. Without it, they check the database every half second, 10 times as often.
540
- - Size PgBouncer's server pool (`default_pool_size`) to what is left. With `listenUrl`, that is 287 − 200 = 87. Without it, PgBouncer can use up to 287.
541
-
542
- ```json
543
- {
544
- "storage": {
545
- "adapter": "@bastani/atomic-storage-postgres",
546
- "options": {
547
- "url": "postgresql://atomic_runtime@pgbouncer.example.com:6432/atomic",
548
- "listenUrl": "postgresql://atomic_runtime@db.example.com:5432/atomic",
549
- "maxConnections": 8
550
- },
551
- "secrets": { "password": { "file": "agent/storage-token.3f2a" } }
552
- }
553
- }
554
- ```
555
-
556
- The same options in an SDK app:
557
-
558
- ```typescript
559
- const database = await openPostgresDatabase({
560
- url: "postgresql://atomic_runtime@pgbouncer.example.com:6432/atomic",
561
- listenUrl: "postgresql://atomic_runtime@db.example.com:5432/atomic",
562
- password: process.env.ATOMIC_DB_PASSWORD,
563
- maxConnections: 8,
564
- });
565
- ```
566
-
567
- The [PgBouncer guide](/guides/postgres-pgbouncer) has a complete, tested PgBouncer configuration, the PostgreSQL and Atomic settings that go with it, and how to check that it works.
568
-
569
- #### Other settings
105
+ - Pass `--storage` or `--storage-file`, not both.
106
+ - An interactive session keeps `--storage` for its whole life. Child processes it starts inherit environment variables such as `ATOMIC_STORAGE`, not command-line flags.
107
+ - Atomic runs one Intercom broker per agent directory, usually one per machine or container, and it serves every session that uses that agent directory. It keeps the store of the process that started it until it exits or `atomic intercom restart` replaces it. Project settings never choose the broker's store.
570
108
 
571
- Set these in the same `options` object, or pass them to `openPostgresDatabase`. Each takes a positive integer number of milliseconds.
109
+ ### Which selection wins
572
110
 
573
- - **Distance.** Saving new entries to a session takes 1 round trip to the server once `atomic storage migrate` has run, and 2 before. Put the database in the same region as the agents. A machine 80 ms away from the server spends at least 80 ms on each save, or 160 ms without the migration.
574
- - **`idleTimeoutMs`** (default `300000`, 5 minutes). Unused connections stay open this long, so the next call skips the connection and TLS handshakes. A process that exits closes its connections at once. Lower it, for example to `30000`, when long-running processes sit idle and the server is near its limit.
575
- - **`statementTimeoutMs`** (default `30000`). The server cancels a statement that runs longer. Raise it only if statements fail with `StorageTransientError` code `transaction-timeout` on a slow server. A lower value does not raise throughput.
576
- - **`connectTimeoutMs`** (default `10000`). Opening a connection, or waiting for a free one in the pool, fails after this long. Raise it for a distant server or one that is slow to accept connections.
577
- - **`keepAliveIdleMs`** (default `60000`). Atomic sends TCP keepalive probes on a connection that has been unused this long. Lower it if calls fail with `StorageTransientError` code `connection-lost` after pauses, which means a firewall, NAT or load balancer dropped idle connections.
578
- - **`maxPreparedStatements`** (default `256`). Each connection keeps up to this many statements prepared on the server, so the server plans each statement once per connection. It does not change round trips. Atomic turns it off by default when `listenUrl` is set or the URL's port is 6432 or 6543, the usual pooler ports, unless it finds PgBouncer 1.21 or later there with `max_prepared_statements` above `0`. 1.24 and later set that to 200 by default. Atomic also keeps it off behind any pooler that hands out its own cancel keys, on any port. If your pooler listens on another port, set `listenUrl` or `maxPreparedStatements: 0`. Lower the value if the server is short of memory per connection.
111
+ For sessions, the first of these that is set wins:
579
112
 
580
- #### Check the effect
113
+ 1. In the SDK: `sessionManager`, then `sessionStore`, then `createAgentSession({ storage })`
114
+ 2. `--session-store <file>`, a local SQLite file for this run, `--no-session`, or `--session-dir <directory>`, a JSONL directory
115
+ 3. `--storage` or `--storage-file`
116
+ 4. `ATOMIC_SESSIONS_STORAGE` or `ATOMIC_CODING_AGENT_SESSION_DIR`
117
+ 5. `ATOMIC_STORAGE`
118
+ 6. The `sessions.storage` setting
119
+ 7. The `storage` setting
120
+ 8. The default local SQLite file, `~/.atomic/workflows/journal.sqlite`
581
121
 
582
- Run these as an administrator. Replace `atomic` with your database name. Atomic's connections report the application name `atomic`, and wake-up connections `atomic-listen`.
122
+ Where two selections meet:
583
123
 
584
- How many connections Atomic holds, and what they are doing:
585
-
586
- ```sql
587
- SELECT application_name, state, count(*)
588
- FROM pg_stat_activity
589
- WHERE datname = 'atomic'
590
- GROUP BY 1, 2
591
- ORDER BY 3 DESC;
592
- ```
593
-
594
- What busy connections are waiting for:
595
-
596
- ```sql
597
- SELECT wait_event_type, wait_event, count(*)
598
- FROM pg_stat_activity
599
- WHERE datname = 'atomic' AND state <> 'idle'
600
- GROUP BY 1, 2
601
- ORDER BY 3 DESC;
602
- ```
124
+ - `--session-dir` and the other session flags replace `--storage` for sessions only. Intercom still uses `--storage`.
125
+ - `ATOMIC_CODING_AGENT_SESSION_DIR` replaces `ATOMIC_STORAGE` for sessions only.
126
+ - Setting `ATOMIC_SESSIONS_STORAGE`, `--storage`, or `--storage-file` together with a non-empty `ATOMIC_CODING_AGENT_SESSION_DIR` stops startup with `StorageConfigError` and reason `conflicting-overrides`. Unset one of them, or pass a session flag.
127
+ - Relative `path`, `dir`, and `secrets.file` values resolve against the [storage home](#storage-home). A relative adapter path resolves from the agent directory. A relative `--storage-file` path resolves from the current directory. An empty variable counts as unset.
603
128
 
604
- How close the server is to its limit:
129
+ Atomic checks `--storage`, `--storage-file`, `ATOMIC_STORAGE`, and `ATOMIC_SESSIONS_STORAGE` before any session starts, in every mode, even when a higher selection wins. Invalid JSON, an unknown field, an unreadable file, a libSQL selection, or a variable of the removed CI team profile, such as `ATOMIC_PROFILE`, stops the CLI with `Error: ...` and exit code `1`, and makes the SDK throw `StorageConfigError`. Atomic never falls back to another store. Error messages name the variable or flag, never a secret.
605
130
 
606
- ```sql
607
- SELECT count(*) AS used, current_setting('max_connections')::int AS max
608
- FROM pg_stat_activity
609
- WHERE backend_type = 'client backend';
610
- ```
131
+ ### Keeping credentials safe
611
132
 
612
- What to change:
133
+ - These options come from the program that launches Atomic, so they apply even in a project you have not [trusted](/security).
134
+ - An adapter is code that runs with Atomic's rights. Select only adapters you trust.
135
+ - Put passwords and tokens in `secrets`, never in `options`.
136
+ - Prefer `--storage-file` or an environment variable to `--storage` for anything sensitive. Other users on the machine can see command-line arguments.
137
+ - In the SDK, `inMemorySecret(value)` keeps a secret only in memory. It shows as `[redacted]` and is refused in settings, flags, and environment variables.
613
138
 
614
- | You see | It means | Change |
615
- | --- | --- | --- |
616
- | `sorry, too many clients already`, `remaining connection slots are reserved for roles with the SUPERUSER attribute`, or `too many connections for role "<role>"` | The processes asked for more connections than the server or role allows. | Lower `maxConnections` or `readerMaxConnections`, raise `max_connections` or the role's `CONNECTION LIMIT`, or [put PgBouncer in front](/guides/postgres-pgbouncer). |
617
- | `timeout exceeded when trying to connect` | Every connection in a process's pool stayed busy for `connectTimeoutMs`. | Raise `maxConnections` if the server has connections to spare. Otherwise raise `connectTimeoutMs`. |
618
- | `the call was queued behind an earlier call that ran 60 seconds without settling, and did not run; nothing was written, retry it` | A call that this one had to wait for ran for a minute, usually because it waited on a lock or on an overloaded server. | Check what busy connections wait for. More connections do not help. |
619
- | Many connections with `wait_event_type` `Lock` | Agents are writing the same sessions or rows at once and wait for each other. | More connections do not help. Spread agents over more sessions. |
620
- | Most `atomic` connections are `idle` and the server is near its limit | Idle processes keep connections open. | Lower `idleTimeoutMs`. |
621
- | `wake-ups: polling only, the listen connection failed` in `atomic storage status` | A broker could not open its wake-up connection, often because the server has none left. | Recount the connections with the formula above. |
139
+ ## Storage home
622
140
 
623
- Atomic reports the first two rows as `StorageTransientError` with code `connection-refused`, with the quoted text as the error's cause. The third row is a `StorageUnavailableError` whose message ends with the quoted text.
141
+ Relative paths in storage settings resolve against the **storage home**. That includes `path`, `dir`, and `secrets.file` values, relative `--storage` and `ATOMIC_STORAGE` paths, and the shared `repos/` and `worktrees/` directories.
624
142
 
625
- ### Tuning libSQL and Turso
143
+ | Agent directory | Storage home |
144
+ | --- | --- |
145
+ | The default, `~/.atomic/agent` | `~/.atomic`, under the current `HOME`. Moving the home directory keeps relative paths working. |
146
+ | A custom one, set with `ATOMIC_CODING_AGENT_DIR`, its older name `PI_CODING_AGENT_DIR`, or the SDK's `agentDir` | The agent directory itself, so separate profiles stay separate. |
626
147
 
627
- A libSQL server lets one writer at a time write a database, and no setting changes that. Each Atomic process has two connections to the server, one for writes and one for reads. A transaction sends its statements together, so saving entries to a session takes 2 requests.
148
+ An older layout kept the session database of a custom agent directory in its parent directory. When such a profile upgrades, the first profile that finds a session database there keeps using the parent directory and prints a one-time notice. Profiles that already have their own store keep it. A relative `secrets.file` can still read an existing file in the parent directory. To share one local store between profiles on purpose, use absolute paths.
628
149
 
629
- Reads can run at the same time. The `concurrency` option sets how many reads each connection runs at once, such as session loads and single `SELECT` statements. It takes a positive integer and defaults to `20`. Writes still run one at a time, in the order they were made, and a read waits for the writes made before it. The option has no effect on `file:` URLs.
150
+ `atomic storage status` never creates a missing agent directory. A read-only agent directory works as long as the storage home is writable.
630
151
 
631
- For high read throughput, set `concurrency` to a generous value, such as 50 to 100, when many agents, subagents or Intercom brokers in one process read at once. It helps most over a slow link. It does not make writes faster.
152
+ ## Locks in the agent directory
632
153
 
633
- ```json
634
- {
635
- "storage": {
636
- "adapter": "@bastani/atomic-storage-libsql",
637
- "options": { "url": "libsql://<db>.turso.io", "concurrency": 50 },
638
- "secrets": { "authToken": { "file": "turso-token" } }
639
- }
640
- }
641
- ```
154
+ Processes that share an agent directory take turns writing `settings.json`, `auth.json`, project trust decisions, and session claims. They coordinate through lock files next to those files. If a process exits while holding a lock, the next process takes the lock over.
642
155
 
643
- The same option in an SDK app:
156
+ These locks work only between processes on one machine that see the agent directory through the same local filesystem. Do not share one agent directory:
644
157
 
645
- ```typescript
646
- import { openLibsqlDatabase } from "@bastani/atomic-storage-libsql";
158
+ - between machines, over NFS, SMB, or a synced folder, where file locks may not work across machines;
159
+ - on one machine through both a local path and a container volume, bind mount, or network mount.
647
160
 
648
- const database = await openLibsqlDatabase({
649
- url: "libsql://<db>.turso.io",
650
- authToken: process.env.TURSO_AUTH_TOKEN,
651
- concurrency: 50,
652
- });
653
- ```
161
+ Give each machine or container its own agent directory with `ATOMIC_CODING_AGENT_DIR`, and share sessions through a [shared database](#sharing-storage-across-hosts) instead.
654
162
 
655
- What else helps:
163
+ If Atomic warns that it cannot open or remove a lock file, such as `settings.json.lock.takeover.lock`, another user owns it, often from an earlier `sudo` run. Fix the owner or remove the file, for example with `sudo chown $USER ~/.atomic/agent/settings.json.lock.takeover.lock`. Until then, Atomic takes over a stale lock after 10 seconds.
656
164
 
657
- - Keep the database close to the agents, because each request is a round trip.
658
- - On a self-hosted `sqld` reached over `http:`, `https:` or `libsql:`, set `keepAliveMs`, for example to `60000`. Unused connections then stay open that long, so a request after a pause skips the connection and TLS handshakes. Without it, Node.js closes an unused connection after about 4 seconds. Leave it unset for Turso, which closes unused connections after 5 seconds. A longer value there makes a write fail with `StorageTransientError` code `connection-lost` when Turso drops the connection just as Atomic reuses it. The option has no effect on `ws:` and `wss:` URLs.
659
- - Give each team its own database. Each database has its own writer. A `prefix` only separates data inside one database, so teams that share a database share its writer.
660
- - For many agents writing at once from many machines, use [PostgreSQL](#postgresql).
165
+ ## Tuning for many concurrent agents
661
166
 
662
- ### Tuning local SQLite
167
+ How many agents can write at once depends on the store:
663
168
 
664
- A local SQLite file has one writer at a time. Atomic queues the writers of every process on the machine in order, and commits the writes queued in one process together. Reads use a separate connection, and Atomic reuses prepared statements. There is nothing to set in `settings.json`. For many agents writing at once from many machines, use [PostgreSQL](#postgresql).
169
+ - **PostgreSQL:** it depends on how many connections each process may open. Writes to different sessions run side by side. Writes to the same session wait for each other. See [Tuning for many concurrent agents](/storage/postgres#tuning-for-many-concurrent-agents), and [Server tuning](/storage/postgres/tuning) for the server itself.
170
+ - **Local SQLite:** one writer at a time, and no setting changes that. See [Tuning local SQLite](/storage/sqlite#tuning-for-many-concurrent-agents).
171
+ - **JSONL:** one writer at a time per directory, and nothing to set. See [Several Atomic processes](/storage/jsonl#several-atomic-processes).
665
172
 
666
173
  ## Exporting and importing sessions
667
174
 
668
- `atomic storage export <dir>` writes sessions to JSONL files, and `atomic storage import <dir>` restores them. Use these commands to move sessions between machines or migrate from one storage backend to another.
669
-
670
- Forks [share history within a store](/sessions#forks-share-history). Export and moving between stores always make full standalone copies. Each exported file holds every entry and tool output of its session, including what the session inherited from the sessions it was forked from. It restores into any backend without them. Import writes every session as a standalone session, so deleting the original parents, in either store, never affects an imported copy. The header's `parentSessionId` is kept only as a record of where the session came from.
175
+ `atomic storage export <dir>` writes sessions to JSONL files, one per session. `atomic storage import <dir>` reads them back. Use them to move sessions to another machine or another store, or to keep sessions between CI runs.
671
176
 
672
177
  ```bash
673
- atomic storage export <dir> [--limit <n>] [--since <time>]
674
- atomic storage import <dir>
178
+ atomic storage export <dir> [--limit <n>] [--since <time>] [--storage <json> | --storage-file <path>]
179
+ atomic storage import <dir> [--storage <json> | --storage-file <path>]
675
180
  ```
676
181
 
182
+ Each exported file is a full copy of one session, with every entry and tool output, including the history a [fork](#shared-history-forks) shares with the session it came from. It does not depend on any other session. Import always writes a standalone session, so deleting the original sessions never affects an imported one.
183
+
677
184
  ### Layout
678
185
 
679
186
  ```text
@@ -681,503 +188,332 @@ atomic storage import <dir>
681
188
  sessions/<sessionId>.jsonl one session per file
682
189
  ```
683
190
 
684
- Import reads only `*.jsonl` files inside `<dir>/sessions` and ignores everything else, including temporary files from interrupted exports. A missing `sessions/` directory imports nothing. The legacy `--sessions` flag is still accepted and has no effect.
191
+ Import reads only the `*.jsonl` files in `<dir>/sessions` and ignores everything else, including temporary files left by an interrupted export. If `<dir>/sessions` does not exist, import adds nothing.
685
192
 
686
193
  ### Export
687
194
 
688
- Export writes every session by default:
195
+ By default, export writes every session, from every project, including the hidden sessions of subagents, so a subagent's history moves with its parent.
689
196
 
690
- - `--limit <n>` writes only the `n` most recently modified sessions (`n` must be an integer `>= 1` made of ASCII digits).
691
- - `--since <time>` writes sessions modified at or after `<time>` (parsed with JavaScript `Date.parse()`). ISO date-only strings such as `2026-11-01` mean UTC midnight, whereas date-time strings without an offset such as `2026-11-01T09:30:00` use your local timezone. Add `Z` or an explicit offset (for example `2026-11-01T09:30:00Z`) to avoid timezone ambiguity.
692
-
693
- Export includes sessions from every project and internal sessions, including fresh subagents' internal sessions (so subagent history transfers with its parent) and workflow-stage internal sessions from earlier releases.
197
+ | Option | Effect |
198
+ | --- | --- |
199
+ | `--limit <n>` | Write only the `n` most recently changed sessions. `n` is a whole number, 1 or more. |
200
+ | `--since <time>` | Write only sessions changed at or after `<time>`. A date such as `2026-11-01` means midnight UTC. A date and time without a time zone, such as `2026-11-01T09:30:00`, uses your local time zone. Add `Z` or an offset, as in `2026-11-01T09:30:00Z`, to avoid surprises. |
694
201
 
695
- Each file is written to a temporary file and renamed atomically so a crash never leaves a partial `.jsonl` file. Identical session state produces identical bytes and skips rewriting unchanged files. Export never deletes files, so prune old exports yourself.
202
+ Export writes each file under a temporary name and renames it when it is complete, so a crash never leaves half a file. A file that would not change is not rewritten. Export never deletes files, so remove old exports yourself.
696
203
 
697
204
  ### Import
698
205
 
699
- Import validates every file before writing anything and compares each session against the copy already in storage. A malformed file, unsupported format version, or diverged session history fails with the file and line number before any write happens.
206
+ Import checks every file before it writes anything. A malformed file, an unsupported format version, or a session whose history differs from the copy already in the store stops the import, with the file name and line number, before any write.
700
207
 
701
- - Missing sessions are added.
702
- - Sessions with matching earlier entries receive the file's newer entries.
703
- - Sessions already present in full are skipped.
208
+ For each session in the files:
704
209
 
705
- Importing the same directory twice adds nothing, and a newer export supersedes an older one. Sessions match by ID, and entries compare by `id`, `parentId`, and `type`.
210
+ - A session the store does not have is added.
211
+ - A session the store has with fewer entries gets the newer entries.
212
+ - A session the store already has in full is skipped.
706
213
 
707
- If an import fails partway through writing multiple sessions, it exits `1` and lists what was imported and what failed. Rerun the same command to import the remaining sessions. Imported sessions immediately work with `--session`, `/resume`, and `history://sessions`.
214
+ So importing the same directory twice adds nothing, and importing a newer export adds only what changed. Sessions match by ID.
215
+
216
+ If an import fails after writing some sessions, it exits `1` and lists what it imported and what it did not. Run the same command again to finish. Imported sessions work at once with `--session`, `/resume`, and `history://sessions`.
708
217
 
709
218
  ### Selecting storage for export and import
710
219
 
711
- Both commands use `ATOMIC_CODING_AGENT_DIR` and the active session storage for the current directory. Exporting from or importing into a shared libSQL, Turso, or PostgreSQL database (or an in-memory store) is refused by default because joined machines already share that database.
220
+ Both commands use the store this directory's settings select. If that store is a shared database or an in-memory store, they refuse by default, because every machine joined to a shared database already sees its sessions.
712
221
 
713
- Pass `--storage <json>` or `--storage-file <path>` to target a specific store explicitly, including a shared database:
222
+ To export from or import into a specific store, including a shared database, name it with `--storage <json>` or `--storage-file <path>`:
714
223
 
715
- - Relative `"path"` values inside `atomic storage export` / `import --storage` (or `--storage-file`) resolve against the **current working directory (`cwd`)**, not storage home. If you copy a `storage` object from `settings.json` whose `"path"` is relative, convert it to an absolute path first.
716
- - JSONL `{ "dir": "..." }` and empty `{}` selections are rejected by `export` and `import --storage`.
224
+ - A relative `path` in these options resolves against the current directory, not the storage home. If you copy a `storage` object from `settings.json` that has a relative `path`, make it absolute first. A relative `secrets.file` still resolves against the storage home, so the password file that `atomic storage join` wrote works as it is.
225
+ - A JSONL `{ "dir": "..." }` or an empty `{}` is refused.
717
226
 
718
- For example, to migrate sessions from libSQL to PostgreSQL:
227
+ For example, to copy every session from this machine's local SQLite store into a PostgreSQL database:
719
228
 
720
229
  ```bash
721
- atomic storage export ~/moved --storage-file old-storage.json
722
- atomic storage join postgres://atomic@db.example.com/atomic --password-file ~/pg-password
230
+ atomic storage export ~/moved
231
+ (umask 077; printf 'Runtime password: '; read -rs password; printf '\n'; printf '%s' "$password" > ~/atomic-db-password)
232
+ atomic storage join 'postgresql://atomic_runtime@db.example.com:5432/atomic' --password-file ~/atomic-db-password
233
+ rm ~/atomic-db-password # atomic storage join keeps its own copy
723
234
  jq .storage ~/.atomic/agent/settings.json > new-storage.json
724
235
  atomic storage import ~/moved --storage-file new-storage.json
725
236
  ```
726
237
 
727
238
  ### Session file format and redaction
728
239
 
729
- Each exported file uses format version 4 (matching JSONL storage and `atomic --import <file>`). Line 1 is the session header, followed by one JSON entry per line in append order:
240
+ Each file uses session format version 4, the same format as JSONL session directories and `atomic --import <file>`. Line 1 is the session header. Each later line is one entry, in the order it was added:
730
241
 
731
242
  ```json
732
243
  {"type":"session","version":4,"id":"...","createdAt":"2026-11-12T09:30:00.000Z","cwd":"/repo"}
733
244
  {"type":"message","id":"a1b2c3d4","parentId":null,"timestamp":"2026-11-12T09:30:05.000Z","message":{"role":"user","content":"..."}}
734
245
  ```
735
246
 
736
- Files contain every branch, with session tool-output blobs and worktree snapshot blobs inlined once as base64 and verified by SHA-256 on import. Files with another header version are rejected.
247
+ Files hold every branch of a session. Tool output and worktree snapshot files are stored once each, encoded as base64, and import checks each one against its SHA-256 hash. A file with another format version is refused.
737
248
 
738
- External tools can redact string values (such as replacing a secret with `***`) without breaking import, provided they keep every line a valid JSON object, preserve line order, and leave these fields unchanged:
249
+ You can redact a file before you share it, for example by replacing a secret with `***`. Import still accepts the file if every line stays a valid JSON object, the lines stay in order, and these fields stay unchanged:
739
250
 
740
- - Header `type`, `version`, `id`, and `createdAt` (`cwd` determines project assignment).
741
- - Entry `id`, `parentId`, and `type`.
742
- - `base64` values and `blobs` objects, which are hash-verified on import.
251
+ - in the header, `type`, `version`, `id`, and `createdAt`. `cwd` decides which project the session belongs to;
252
+ - in every entry, `id`, `parentId`, and `type`;
253
+ - every `base64` value and `blobs` object, because import checks their hashes.
743
254
 
744
255
  ### Persisting sessions between CI runs
745
256
 
746
- On a runner that caches a directory across jobs:
257
+ On a CI runner that caches a directory between jobs:
747
258
 
748
259
  ```bash
749
- # Start of job, after restoring $STATE_DIR
260
+ # Start of the job, after the cache restores $STATE_DIR
750
261
  mkdir -p "$STATE_DIR" && atomic storage import "$STATE_DIR"
751
262
 
752
263
  # ... run Atomic ...
753
264
 
754
- # End of job, before saving $STATE_DIR
265
+ # End of the job, before the cache saves $STATE_DIR
755
266
  atomic storage export "$STATE_DIR"
756
267
  ```
757
268
 
758
- Use `--since` or `--limit` to bound cache size. Imported sessions continue with `atomic --session <id>`.
759
-
760
- ## Size limits
269
+ Use `--since` or `--limit` to keep the cache small. Continue an imported session with `atomic --session <id>`.
761
270
 
762
- Single-value limits vary by backend: `sqld` 0.24 defaults to 5,000,000 bytes (`max_row_size`) and 10 MB responses (`--max-response-size`), local SQLite allows about 1 GB per value, and PostgreSQL allows about 1 GB per field. Atomic chunks large data automatically so large sessions and snapshots work across every backend:
271
+ ## Moving off libSQL
763
272
 
764
- - Session entries over 1 MiB (such as large pasted logs or inline images) split into 1 MiB chunk rows in one transaction, and sessions load in 1 MiB pages.
765
- - Session search indexes the first 64 KiB (65,536 UTF-16 code units) of each message across all stores.
766
- - Worktree snapshot blobs and session tool-output blobs over 1 MiB split into 1 MiB chunk rows.
273
+ Atomic 0.10.11 removed libSQL support: Turso, self-hosted `sqld`, and libSQL `file:` databases. If your sessions are in a libSQL database, move them to PostgreSQL or to a local SQLite file. Forks keep their whole history, and worktree snapshots keep their content. You export them with Atomic 0.10.11-alpha.2, the last release that reads libSQL, and import them with the current release. Use that release even if you last ran an earlier one: it reads every libSQL database, including one it already upgraded for [shared-history forks](#shared-history-forks), which 0.10.10 refuses. Its exports use session format 4, which the current release reads.
767
274
 
768
- Payloads that still exceed a backend's limit fail non-retryably with `StoragePayloadTooLargeError`. Store less in a single value or raise the server's limit (for `sqld`, `max_row_size` and `--max-response-size`).
275
+ Before you start:
769
276
 
770
- ### Upgrading older SQLite and shared stores
277
+ - **Do this before you run `atomic storage join`.** `atomic storage join` replaces the libSQL `storage` setting, and step 1 needs it.
278
+ - **Run it once, from one machine.** If several machines shared the libSQL database, the other machines only upgrade Atomic and [join the new database](/storage/postgres#join-a-machine).
279
+ - **You need Node.js 24.20 or newer with `npx`** to run Atomic 0.10.11-alpha.2 next to the current release. The current release needs the same.
280
+ - **Only sessions move.** Intercom messages that were not yet delivered stay behind. Forks arrive as full copies, so they take more space than they did in the libSQL database.
771
281
 
772
- - **One-way session schema upgrade.** Writing the first chunked session entry permanently upgrades the session schema from version `1` to `2`. Upgrade every host sharing a database together because older releases reject version 2 stores with `StorageSchemaVersionError`. Version `3` comes from the switch to [shared-history forks](#shared-history-forks), which waits until no older release runs a session on the database.
773
- - **Offline local snapshot chunk migration.** On older local SQLite files, background snapshot collection migrates legacy snapshot chunk tables automatically when free disk space allows. To migrate a cleanly closed local SQLite file offline with bounded WAL growth, stop all Atomic processes using that file and run:
282
+ 1. **Save the libSQL setting to a file.** It is the top-level `storage` value in `~/.atomic/agent/settings.json`:
774
283
 
775
- ```bash
776
- atomic storage move-snapshot-chunks <sqlite-file> [--prefix <prefix>]
777
- ```
284
+ ```bash
285
+ jq .storage ~/.atomic/agent/settings.json > old-storage.json
286
+ ```
778
287
 
779
- The file must be a local WAL-mode SQLite database with an empty WAL and without `auto_vacuum=FULL`. Never delete a WAL file manually after a crash; let SQLite recover it first. PostgreSQL requires no chunk migration.
288
+ If `sessions.storage` points at the libSQL database instead, save that value with `jq .sessions.storage` instead. If you already replaced the setting, write `old-storage.json` by hand. It looks like this, with your database's URL and your token file:
780
289
 
781
- ## Shared-history forks
290
+ ```json
291
+ {
292
+ "adapter": "@bastani/atomic-storage-libsql",
293
+ "options": { "url": "libsql://my-db.turso.io" },
294
+ "secrets": { "authToken": { "file": "/home/me/turso-token" } }
295
+ }
296
+ ```
782
297
 
783
- A fork made in the same store as its parent shares the parent's history instead of copying it. The fork stores a note of which part of the parent's history it continues from, and reads those entries from the parent; only the entries added after the fork are its own. This applies to `/fork`, `/clone`, `atomic --fork`, and subagents that start from a copy of their parent's conversation. Forking a long session then takes about as long as forking a short one, and the store does not grow by a second copy of the parent's history.
298
+ 2. **Export the sessions with Atomic 0.10.11-alpha.2:**
784
299
 
785
- There is nothing to turn on or configure. What stays the same:
300
+ ```bash
301
+ npx -y @bastani/atomic@0.10.11-alpha.2 storage export ~/moved --storage-file old-storage.json
302
+ ```
786
303
 
787
- - A fork looks and behaves like a copied fork: the same entries, search results, tree, resume, and export.
788
- - Changing or deleting the parent never changes a fork. Before the parent's entries change or go away, Atomic copies the entries each fork still reads into that fork, or keeps them stored, hidden, until no fork reads them.
789
- - `atomic storage export` writes each fork's full history, and a fork into another store copies, so nothing outside the store depends on it.
790
- - JSONL session directories and in-memory stores always copy.
304
+ It reads only the libSQL database, and prints how many sessions it wrote:
791
305
 
792
- ### How a fork reads its history
306
+ ```text
307
+ Exported 4 sessions to /home/me/moved/sessions (4 written, 0 unchanged).
308
+ ```
793
309
 
794
- A fork that shares its parent's history keeps a short list of ranges, for example "my entries 1 to 400 are the parent's entries 1 to 400". Every entry added after the fork, and any entry the fork changed, is stored in the fork itself.
310
+ If it prints `Error: Could not load storage adapter: @bastani/atomic-storage-libsql: Cannot find module '@bastani/atomic-storage-libsql'`, install the adapter for that release, then export again:
795
311
 
796
- - **One query.** When Atomic reads a fork, it looks the list up in the same database query that reads the entries, so the list and the entries always come from the same moment. No copy of the list is kept in memory between reads, so a read never uses an out-of-date list.
797
- - **Up to the fork point only.** A fork reads its parent's entries only up to the point where it was made. When the parent keeps going, the new entries are the parent's alone.
798
- - **The parent cannot change a fork.** If the parent is later rewritten, Atomic first copies the entries the fork still uses into the fork, in the same step. If the parent is deleted, its entries stay stored, hidden, until no fork uses them.
799
- - **Forking never holds the parent up.** On PostgreSQL, the parent keeps appending while forks are made from it. Making a fork takes the same 2 round trips as creating a session, whatever the parent's length or how many forks deep the chain goes, and the first load of a fork takes the same round trips as a session of the same length.
312
+ ```bash
313
+ npx -y @bastani/atomic@0.10.11-alpha.2 install npm:@bastani/atomic-storage-libsql@0.10.11-alpha.2
314
+ ```
800
315
 
801
- ### Older Atomic versions {#older-atomic-versions}
802
-
803
- A store whose forks share history keeps them in a form that Atomic releases without this feature cannot read correctly: such a release would show a fork's own entries as its whole history, and could delete or rewrite a parent that forks still read. So the first time this release or a later one opens a store, it marks the store as needing this release or later. From then on, an older release refuses to open the store with `StorageSchemaVersionError` ("this store needs a newer Atomic"). The mark is permanent: a store cannot go back to older releases.
316
+ 3. **Import them into their new store.**
804
317
 
805
- The switch never pulls a store out from under an older Atomic that is using it:
318
+ To move them to PostgreSQL, [set up the database](/storage/postgres#set-up-the-database), join it, and import into it by name. `atomic storage join` notes that it replaces the libSQL setting:
806
319
 
807
- - **It waits for older versions to stop.** Every running session records in the store which release runs it. While a session of an older release is running on any machine that uses the store, Atomic leaves the store as it is, and forks keep copying. The next time Atomic opens the store after those sessions have stopped, for example when a session starts or resumes, the switch happens. A session on the same machine counts as running while its process runs. A session on another machine counts while its record is refreshed, about every 15 seconds; one whose record is more than a minute old, for example on a machine that crashed, no longer counts.
808
- - **It happens in one step.** The fork tables and the new mark are written in one transaction that waits for writes already in progress to finish, so upgraded sessions keep working through it, and two machines switching at once is safe.
809
- - **It costs nothing once done.** A store that is already switched opens with the same reads as before.
810
- - **It needs table privileges.** On PostgreSQL, a runtime role without DDL privileges cannot create the fork tables, so forks there keep copying until the owner runs `atomic storage migrate`, which switches the database too. The new tables are `session_fork_segments`, `session_fork_lineage`, `session_fork_tombstones`, and `session_fork_detach`, and the runtime role reaches them through the default privileges granted in [Set up the database](#set-up-the-database).
320
+ ```bash
321
+ (umask 077; printf 'Runtime password: '; read -rs password; printf '\n'; printf '%s' "$password" > ~/atomic-db-password)
322
+ atomic storage join 'postgresql://atomic_runtime@db.example.com:5432/atomic' --password-file ~/atomic-db-password
323
+ rm ~/atomic-db-password # atomic storage join keeps its own copy
324
+ jq .storage ~/.atomic/agent/settings.json > new-storage.json
325
+ atomic storage import ~/moved --storage-file new-storage.json
326
+ atomic intercom restart
327
+ ```
811
328
 
812
- None of this needs any action and none of it is reported as an error. With debug mode on, Atomic notes in the debug log when it leaves the switch for later, and why.
329
+ To keep them on this machine instead, remove the libSQL `storage` setting, and any `sessions.storage` setting that points at libSQL, from `~/.atomic/agent/settings.json`. Then import them into the default local SQLite file:
813
330
 
814
- If you still run an older Atomic against a shared database, for example on a machine you have not upgraded yet, upgrade it too. Once its sessions have stopped and an upgraded session opens the store, the older release cannot open the store again. To move sessions back to an older release after the switch, export them with `atomic storage export`, which writes each fork's full history, then import them with that release into a new store.
331
+ ```bash
332
+ atomic storage import ~/moved
333
+ atomic intercom restart
334
+ ```
815
335
 
816
- ## Workflow data from earlier releases
336
+ Import prints what it did:
817
337
 
818
- Releases before 0.10.0 stored workflow runs under `workflows/journal/`, `workflows/pool/`, `workflows/runs/`, and `wf_*` tables. Atomic no longer runs those workflows and never opens, modifies, or deletes that data, so existing stores continue working and downgrading preserves old runs.
338
+ ```text
339
+ Imported 4 sessions from /home/me/moved/sessions (4 added, 0 updated, 0 already up to date).
340
+ ```
819
341
 
820
- - `atomic storage status`, `migrate`, `export`, and `import` operate on sessions and Intercom only. On PostgreSQL, `atomic storage migrate` still moves existing `wf_*` tables from `public` to `atomic` so a database is not split across schemas.
821
- - `atomic storage adopt`, `atomic storage consolidate`, and the `--workflows`, `--run`, and `--unfinished` flags were removed.
822
- - Snapshot garbage collection still respects references held by earlier workflow runs so their blobs are not deleted.
823
- - `ATOMIC_WORKFLOWS_JOURNAL`, `ATOMIC_WORKFLOW_JOURNAL_PATH`, `workflows.journal`, and `createAgentSession({ journal })` no longer select storage.
342
+ Running it again is safe. It then reports the sessions as `already up to date`.
824
343
 
825
- To run an older workflow definition with this release, see [Migrating workflows](/orchestration/migrating-workflows).
344
+ 4. **Check the result.** `atomic storage status` names the new store for sessions, and `atomic -r` in one of your projects lists that project's old sessions.
826
345
 
827
- ## SDK and local SQLite API
346
+ 5. **Remove the libSQL adapter**, which the current release no longer uses:
828
347
 
829
- For full SDK recipes covering `createAgentSession`, `createAgentSessionRuntime`, `SqlSessionStore`, `JsonlSessionStore`, `MemorySessionStore`, `openPostgresDatabase`, `openLibsqlDatabase`, and store ownership rules, see [SDK session storage](/sdk/storage). For direct session reading, branching, and listing, see [SessionManager API](/session-format#sessionmanager-api).
348
+ ```bash
349
+ atomic remove npm:@bastani/atomic-storage-libsql
350
+ ```
830
351
 
831
- This section covers the low-level local SQLite API and storage path helpers exported from `@bastani/atomic` and `@bastani/atomic/storage`, followed by custom adapter and driver authoring:
352
+ It prints `Removed npm:@bastani/atomic-storage-libsql` when it is done.
832
353
 
833
- ```typescript
834
- import { openNodeSqliteDatabase } from "@bastani/atomic/storage";
354
+ Until you move off it, any setting, variable, or command that still names a libSQL database, or one of the removed `ATOMIC_PROFILE` and `ATOMIC_TEAM_*` variables, stops Atomic with a `libsql-removed` error that links to this section. For the `storage` setting it starts `Error: Invalid storage configuration: storage (libsql-removed).`
835
355
 
836
- const database = await openNodeSqliteDatabase("./data/example.sqlite");
837
- try {
838
- await database.exec("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, text TEXT)");
839
- await database.transaction(async (transaction) => {
840
- await transaction.run("INSERT INTO notes(text) VALUES (?)", "hello");
841
- });
842
- const notes = await database.all("SELECT id, text FROM notes ORDER BY id");
843
- } finally {
844
- await database.close();
845
- }
846
- ```
356
+ ## Size limits
847
357
 
848
- ### Query and transaction semantics
358
+ Long sessions, large pasted logs, inline images, and large worktree snapshots work in every store, because Atomic splits large data into smaller parts. Session search reads only the first 64 KiB of each message.
849
359
 
850
- - `exec`, `run` (returns `{ changes }`), `get` (row or `undefined`), and `all` (array) return promises and bind positional `?` parameters (`null`, `number`, `bigint`, `string`, `Uint8Array`). Binary parameters are copied on call. Safe-range integers return as `number`, and larger integers return as `bigint`.
851
- - String bindings containing U+0000 fail before SQL runs with `StorageInvalidTextError` (`parameterIndex`, `reason: "nul-character"`). Encode zero bytes with `JSON.stringify` or pass a `Uint8Array`.
852
- - Inside `database.transaction(cb)`, use only the callback's `tx` handle (calling `database` deadlocks). Transaction handles expire when the callback settles, rejected callbacks roll back, failed commits reject with `StorageUnavailableError`, and failed rollbacks reject with `StorageRollbackError` (`cause`, `rollbackCause`).
853
- - `close()` drains accepted work idempotently and rejects subsequent calls with `StoreClosedError`.
360
+ A single value that still exceeds the store's limit fails with `StoragePayloadTooLargeError`, and retrying does not help. Local SQLite allows about 1 GB per value, and PostgreSQL about 1 GB per field. Store less in one value, or raise the limit of a custom backend.
854
361
 
855
- ### SDK path helpers
362
+ ## Upgrading older stores
856
363
 
857
- `@bastani/atomic/storage` and `@bastani/atomic` export `storageHomeDir(agentDir?, settings?)`, `workflowsStorageDir(agentDir?, settings?)`, `defaultSessionDatabasePath(agentDir?, settings?)`, `defaultSharedStoragePath(agentDir?, settings?)`, and `storagePathBaseDir(path, agentDir, settings?)`. Pass merged settings before opening a store so legacy parent-directory adoption rules resolve accurately.
364
+ Some Atomic releases change how a store is laid out, and older releases cannot read the new layout. These changes are one-way:
858
365
 
859
- ### Concurrency, options, and diagnostics
366
+ - **Large session entries.** The first session entry over 1 MiB that Atomic 0.9.88 or later saves upgrades the store. Releases before 0.9.88 then refuse it with `StorageSchemaVersionError`.
367
+ - **Shared-history forks.** Atomic 0.10.11 and later upgrade a store for [shared-history forks](#shared-history-forks) once no earlier release has a session open on it. See [Older Atomic versions](#older-atomic-versions).
860
368
 
861
- - **Database options.** `openNodeSqliteDatabase(path, options?)` creates parent directories and enables WAL mode, `FULL` sync, foreign keys, and `busyTimeoutMs: 5000`. Pass `:memory:` for an ephemeral database or `{ readOnly: true }` to inspect a file without creating it or changing its journal mode. File-backed handles run off the main event loop so statements waiting on locks or disk syncs do not block your application. Each connection keeps up to 256 prepared statements for reuse; a handle from `wrapNodeSqliteDatabase` keeps none. A file-backed handle's `openReader()` opens a separate read-only connection to the same file with its own queue. In WAL mode it reads the last commit without waiting for the handle's writes. Closing the handle also closes its readers.
862
- - **Wrapping an existing connection.** `wrapNodeSqliteDatabase(conn)` adapts an existing Node `DatabaseSync` handle on the calling thread and leaves the underlying connection open on `close()`. Avoid mixing raw `DatabaseSync` calls with wrapped calls on the same connection.
863
- - **Writer queuing and timeouts.** Multiple handles in one process and across processes on the same host share FIFO write queues. `groupCommitHoldMs` (default `100` ms, exported as `DEFAULT_GROUP_COMMIT_HOLD_MS`, `0` commits individually) batches queued transactions per lock acquisition. Waiting longer than `lockWaitMs` (default `30000` ms, or per-transaction `{ lockWaitMs }`) with no commits rejects with `StorageWriteLockTimeoutError`.
864
- - **Diagnostics.** `getWriterQueueStats(db)` returns 10-second lock utilization, waiter count, wait latency percentiles (`p50WaitMs`, `p95WaitMs`), and `commitsPerSecond`. `getWriterQueueDegradation(db)` returns recorded `StorageWriterQueueDegradedError` entries (also logged in [debug mode](/development#debugging)). Passing a non-node-sqlite handle throws `StorageUnsupportedOperationError`.
369
+ Upgrade every machine that shares a database at the same time.
865
370
 
866
- ## Selecting an adapter
371
+ ### Moving snapshot data in an old SQLite file
867
372
 
868
- A storage adapter is a module whose default export satisfies `StorageAdapterModule`:
373
+ On older local SQLite files, Atomic moves worktree snapshot data, which it stores in parts called chunks, to a newer layout in the background when there is enough free disk space. To do it yourself, in batches that keep the database's log file small:
869
374
 
870
- ```typescript
871
- import type { StorageAdapterModule } from "@bastani/atomic/storage";
375
+ 1. Stop every Atomic process that uses the file.
376
+ 2. Run:
872
377
 
873
- export default {
874
- atomicStorageAdapter: 1,
875
- async openDatabase(options, context) {
876
- return openMyDatabase({ url: String(options.url), authToken: String(options.authToken) });
877
- },
878
- } satisfies StorageAdapterModule;
879
- ```
378
+ ```bash
379
+ atomic storage move-snapshot-chunks <sqlite-file> [--prefix <prefix>]
380
+ ```
880
381
 
881
- Select an adapter in `sessions.storage` or top-level `storage` in [settings](/settings#sessions), or pass `sessionStore: { kind: "adapter", module, options, secrets, prefix }` in the SDK. Relative module paths resolve from the agent directory (`~/.atomic/agent` by default). Bare package names resolve from user-scope [Atomic packages](#adapters-from-atomic-packages), host extension directories, or the agent directory, never from an embedding application's `node_modules`. Project settings follow the project trust boundary, and adapter code runs with Atomic's privileges.
382
+ The file must be a local SQLite database in WAL mode, closed cleanly so its `-wal` file is empty, and without `auto_vacuum=FULL`. After a crash, never delete the `-wal` file by hand. Open the database with Atomic or SQLite first so SQLite can recover it. PostgreSQL needs no such step.
882
383
 
883
- Choose the installation method that matches how you open the adapter:
384
+ ## Shared-history forks
884
385
 
885
- - **Direct SDK database handles (`{ kind: "database", database }`).** Install the package in your project with `npm install`, call `openPostgresDatabase()` or `openLibsqlDatabase()`, and pass the handle to `sessionStore: { kind: "database", database, prefix? }` or `SqlSessionStore.open(database, { prefix? })`. See [SDK session storage](/sdk/storage).
886
- - **Adapter-resolved selections (`{ kind: "adapter", module }`, `settings.json`, `ATOMIC_STORAGE`, `ATOMIC_PROFILE=ci`).** Install the package in user scope with `atomic install npm:<package>` (without `-l`), or register a local package directory with `DefaultResourceLoader({ additionalExtensionPaths })` or `--extension`.
386
+ When you fork a session, the new session starts with a copy of the conversation so far. In a SQLite or PostgreSQL store, the fork does not actually copy that history. It shares it with the session it came from, its parent, and stores only what is added after the fork. This applies to `/fork`, `/clone`, `atomic --fork`, and subagents started with `context: "fork"`.
887
387
 
888
- Adapter modules can import `@bastani/atomic/storage` and `@bastani/atomic` directly in both npm installs and standalone binaries. This works for the adapter entry file and any ES module or TypeScript file it imports relatively (including `.mjs` files and `.js` files in `"type": "module"` packages). CommonJS files outside the entry file resolve from `node_modules` instead. List `@bastani/atomic` under `peerDependencies`, not `dependencies`.
388
+ What this means for you:
889
389
 
890
- `options` holds SQLite scalar values or booleans. `secrets` maps secret names to `{ env }`, `{ file }`, or (in the SDK only) `inMemorySecret(value)` (`{ value }`), overriding same-named keys in `options`. Atomic strips one trailing `\n` or `\r\n` from `{ file }` secrets and keeps other whitespace intact. `inMemorySecret()` serializes as `[redacted]` and is refused outside the SDK (`in-memory-secret-unsupported`).
390
+ - **Forking is fast.** Forking a long session takes about as long as forking a short one.
391
+ - **Forks take little space.** The store does not keep a second copy of the parent's history.
392
+ - **There is almost nothing to set up.** On SQLite, Atomic does it by itself. On PostgreSQL, the owner runs `atomic storage migrate` once, as [Older Atomic versions](#older-atomic-versions) explains.
891
393
 
892
- `context` provides `agentDir`, `domain: "sessions" | "intercom"`, an optional `signal`, and `secret(name)` to reread `secrets[name]` on demand. An adapter that reads fresh credentials for each new connection (such as a rotated password file) declares `liveSecrets` on its `StorageAdapterModule` (for example `liveSecrets: ["password"]`). Atomic omits names listed in `liveSecrets` from `options` and expects the adapter to call `context.secret(name)`, which throws `StorageConfigError` (`reason: "secret-missing"`) when the secret is missing from `secrets`.
394
+ A fork behaves exactly like a copy:
893
395
 
894
- Adapter hooks and lifecycle:
396
+ - It shows the same entries, search results, tree, and history as a copy would.
397
+ - It shows the parent's history only up to the moment it was forked. What the parent adds later stays in the parent.
398
+ - Changing or deleting the parent never changes the fork. Before the parent's history changes, Atomic gives each fork its own copy of the part it uses. When you delete the parent, it disappears from lists and search at once, and Atomic keeps the part its forks use, out of sight, until no fork needs it.
399
+ - Anything that takes a fork out of its store writes a full copy that does not depend on the parent: `/export`, `/share`, `atomic --export`, `atomic storage export`, and a fork into another store.
895
400
 
896
- - Implement `openDatabase(options, context): Promise<SqliteDatabase>` for SQL-backed adapters so Atomic manages schemas, prefixes, and Intercom tables.
897
- - Implement `openSessionStore(options, context, { prefix? })` for non-SQL session stores. When both hooks exist, `openSessionStore` takes priority for sessions.
898
- - Missing hooks raise `StorageConfigError` (`reason: "adapter-domain-unsupported"`). Load failures raise `StorageAdapterLoadError`, and driver open failures raise `StorageUnavailableError`.
899
- - `new StorageProvider().openSessionStore(selection, context)` opens stores programmatically (`kind`: `"memory"`, `"jsonl"`, `"sqlite"`, `"database"`, or `"adapter"`). `loadStorageAdapter(module, context, hostModules)` loads an adapter module.
900
- - `StorageProvider` instances share one process-wide map of provider-owned databases across matching selections and close each owned database when its last returned store closes. Caller-owned `database` handles passed through `{ kind: "database", database }` are never closed by the provider.
901
- - If opening storage fails and closing its owned database also fails, Atomic throws the original opening error with a `cleanupCause` field holding the cleanup failure.
401
+ JSONL directories and in-memory stores always copy.
902
402
 
903
- ### Adapters from Atomic packages
403
+ ### Older Atomic versions {#older-atomic-versions}
904
404
 
905
- An [Atomic package](/packages) can bundle storage adapters and their driver dependencies by listing adapter paths under `atomic.storageAdapters` in `package.json`:
405
+ Shared-history forks start with Atomic 0.10.11, and its prerelease 0.10.11-alpha.2. Earlier releases cannot read a store that uses them, so Atomic upgrades the store once, and from then on earlier releases refuse to open it:
906
406
 
907
- ```json
908
- {
909
- "name": "@example/atomic-libsql",
910
- "dependencies": { "@libsql/client": "0.18.0" },
911
- "peerDependencies": { "@bastani/atomic": "*" },
912
- "atomic": { "storageAdapters": ["./libsql-adapter.ts"] }
913
- }
407
+ ```text
408
+ Unsupported sessions storage schema version 3: this store needs a newer Atomic. Update Atomic before reopening it.
914
409
  ```
915
410
 
916
- Install the package with `atomic install npm:@example/atomic-libsql` and select it by package name:
411
+ When the upgrade happens:
917
412
 
918
- ```json
919
- {
920
- "storage": {
921
- "adapter": "@example/atomic-libsql",
922
- "options": { "url": "libsql://team.example" },
923
- "secrets": { "authToken": { "file": "turso-token" } }
924
- }
925
- }
926
- ```
413
+ - Atomic upgrades a store when it opens it and no earlier release has a session open on it, on any machine. Until then, forks are full copies, and the earlier release keeps working.
414
+ - A session on another machine counts as open while that machine is running it. If the machine crashed, its sessions stop counting after about a minute.
415
+ - On PostgreSQL, the runtime role cannot create the tables that shared forks need. Forks stay full copies until the owner runs `atomic storage migrate`, which upgrades the database. Atomic shows no error either way.
927
416
 
928
- The bare package name selects the first listed adapter. When a package exports several adapters, select one with `<package>/<name>` using the adapter filename without its extension (such as `@example/atomic-libsql/libsql-adapter`).
929
-
930
- Host applications embedding Atomic can expose their own adapter without installing it separately. Pass the package directory via `--extension <dir>` or `additionalExtensionPaths: [packageRoot]` on `DefaultResourceLoader` before opening storage, then select `"adapter": "@example/app"` or `"@example/app/<name>"`.
931
-
932
- Atomic resolves adapter package names in this order:
933
-
934
- 1. Extension package directories passed to the process (or inherited from the launching Atomic process).
935
- 2. Packages in effective global settings (including legacy `~/.pi/agent/settings.json` for the default agent directory). Project packages are not searched.
936
- 3. Module resolution from the agent directory.
937
-
938
- Child processes that Atomic starts (such as subagents and the Intercom broker) automatically inherit adapters resolved from the host's packages without reloading the host package. `atomic storage status` shows the resolved path when run inside such a process, and resolves from global settings or the agent directory when run directly from a shell.
939
-
940
- ## Bring your own driver
941
-
942
- To wrap a SQLite-compatible driver into a `SqliteDatabase`, call `createSqliteDatabase` from `@bastani/atomic/storage` with these driver hooks:
943
-
944
- - `descriptor` provides `{ adapter, location }` for diagnostics (redacted through `redact`).
945
- - `execute(sql, params)` runs one parameterized statement and returns `{ columns, rows, changes }`. Return integers as `bigint` to preserve 64-bit precision.
946
- - `executeMultiple(sql)` runs zero or more unparameterized statements.
947
- - `beginTransaction()` starts a write transaction and returns `{ execute, executeMultiple, commit, rollback, close? }`.
948
- - `close()` releases the driver connection.
949
- - `batch(statements)` (optional) executes `{ sql, params }` statements in one atomic write transaction sent as a single request. Provide this only when the driver sends the whole batch at once.
950
- - `redact(text)` (optional) strips credentials from error text. Use `redactSecrets(secrets)` to build one that removes raw, URI-encoded, and decoded forms.
951
- - `transientFailure(failure)` (optional) classifies retryable driver errors from structured fields (never message text) and returns `{ code, outcome, hop? }`. Set `outcome` to `"not-applied"` when the database cannot have changed, or `"unknown"` when the write may have committed. Set `hop: { name, failure }` when an intermediate hop such as a proxy failed before reaching the database.
952
- - `freeBytes()` (optional) returns writable free bytes on the filesystem holding a local database file, or `undefined`.
953
- - `openReader()` (optional) returns a driver with connections of its own on the same database, for reads. The facade exposes it as `SqliteDatabase.openReader()`. The reader gets its own call queue and closes when the main database closes.
954
- - `concurrentTransactions` (optional) marks a driver that runs each transaction on its own connection, as the PostgreSQL adapter does. The facade then runs calls that cannot conflict at the same time. See the queue rules below.
955
- - `pipelinedTransactions` (optional) marks a transaction connection that accepts a statement before the previous one is answered. The PostgreSQL adapter and the libSQL adapter's server connections set it. The facade then sends each statement of a transaction without waiting for the answer before it. It can also send a transaction's last writes together with its commit.
956
- - `beginTransaction` receives `leading`, the reads the transaction makes first. The driver may send them with the begin and answer the transaction's first calls from them.
957
- - If a statement sent ahead of an earlier answer, or with the commit, fails, the driver's commit must fail, so nothing commits. The transaction then fails with that statement's error.
958
- - A statement whose connection broke after the commit was sent reports `outcome: "unknown"`, because the commit may have applied.
959
- - `concurrentReads` (optional) is a positive integer for a driver that runs reads on connections or streams of their own, up to that many at once. The facade then runs read-only transactions, and statements outside a transaction that `readsOnly` accepts, beside each other. Every other call still waits for each call before it, and a read waits for the writes queued before it. With `concurrentTransactions` as well, the facade runs at most this many reads at once.
960
- - `readsOnly(sql)` (optional) says whether a statement run outside a transaction only reads. With `concurrentReads` or `concurrentTransactions`, such a statement runs beside other reads. Answer `true` only for a statement that can never write.
961
- - On a driver with `concurrentTransactions`, a read-only transaction returns once its reads are answered. Its commit only ends the snapshot, so it finishes in the background, and `close()` waits for it.
962
-
963
- Driver hooks may return values or promises. The facade runs one operation at a time unless the driver sets `concurrentTransactions`. It copies binary parameters on call, rejects NUL text bindings with `StorageInvalidTextError`, converts safe-range integers to `number`, expires transaction handles after settlement, and drains accepted work on `close()`. Unclassified driver errors reject with `StorageUnavailableError` (with redacted `cause`), and failed rollbacks reject with `StorageRollbackError`.
964
-
965
- Transient retry and queue bounds:
966
-
967
- - Recognized transient failures reject with `StorageTransientError`. Statements and batches that failed before writing retry up to `STORAGE_TRANSIENT_RETRY_ATTEMPTS` (5) times starting at 250 ms with exponential backoff and up to 20% jitter. Writes with `outcome: "unknown"` never retry automatically.
968
- - Transactions retry (re-running their callback) only when called with `{ retryTransientFailures: true }` and only for callbacks that have no external side effects. Non-boolean values throw `StorageConfigError`. The first retried failure on a database emits a one-time process warning.
969
- - On a driver with `concurrentTransactions`, a call waits only for earlier unfinished calls it conflicts with. Statements and batches outside a transaction, and serial transactions without a `domain`, conflict with every call. A serial transaction with a `domain` conflicts with others of the same domain. A read-only transaction waits for writes queued before it, but not for other read-only transactions or later writes. Conflicting calls run in call order, and calls that do not conflict, such as appends to different sessions, run concurrently. `fenced` transactions bypass the queue. Other drivers run one call at a time.
970
- - While a call runs without settling, waiting priority batches (batches sent with `{ priority: true }`) fail after `STORAGE_PRIORITY_CALL_MAX_WAIT_MS` (10 seconds), and other waiting calls fail after `STORAGE_QUEUED_CALL_MAX_WAIT_MS` (60 seconds), both with `StorageUnavailableError`. On a driver with `concurrentTransactions`, only calls waiting behind the stuck call (directly or through other waiting calls) fail. Timers reset for each call that begins running.
971
- - For shared local SQLite files, enable WAL mode with `switchToWriteAheadLog(exec, busyTimeoutMs)` from `@bastani/atomic/storage`. It retries `SQLITE_BUSY` up to `busyTimeoutMs` and retries Windows `SQLITE_IOERR_TRUNCATE` for up to 5 seconds (or `busyTimeoutMs`, whichever is shorter).
972
-
973
- You can also implement `SqliteDatabase` directly. In either case, verify your implementation with the [conformance suite](#adapter-conformance).
974
-
975
- ### Custom driver adapter example
976
-
977
- For production Turso or `sqld` deployments, install `@bastani/atomic-storage-libsql` (which includes abandoned-stream cleanup, namespace headers, and Windows local-file close safeguards). The minimal example below shows the `createSqliteDatabase` and `StorageAdapterModule` structure for wrapping any SQLite-compatible client:
978
-
979
- ```typescript
980
- import { createClient, type Client, type Transaction } from "@libsql/client";
981
- import {
982
- createSqliteDatabase,
983
- redactSecrets,
984
- type SqliteDatabase,
985
- type SqliteDriverExecutor,
986
- type StorageAdapterModule,
987
- } from "@bastani/atomic/storage";
988
-
989
- export interface CustomDriverOptions {
990
- url: string;
991
- authToken?: string;
992
- }
993
-
994
- function executor(connection: () => Client | Transaction): SqliteDriverExecutor {
995
- return {
996
- async execute(sql, params) {
997
- const result = await connection().execute({ sql, args: [...params] });
998
- return { columns: result.columns, rows: result.rows, changes: result.rowsAffected };
999
- },
1000
- executeMultiple: (sql) => connection().executeMultiple(sql),
1001
- };
1002
- }
1003
-
1004
- export async function openCustomDatabase({ url, authToken }: CustomDriverOptions): Promise<SqliteDatabase> {
1005
- let client: Client | undefined;
1006
- const connection = () => (client ??= createClient({ url, authToken, intMode: "bigint" }));
1007
- const database = createSqliteDatabase({
1008
- descriptor: { adapter: "custom-libsql", location: url },
1009
- redact: redactSecrets(authToken ? [authToken] : []),
1010
- ...executor(connection),
1011
- async beginTransaction() {
1012
- const tx = await connection().transaction("write");
1013
- return {
1014
- ...executor(() => tx),
1015
- commit: () => tx.commit(),
1016
- rollback: () => tx.rollback(),
1017
- close: () => tx.close(),
1018
- };
1019
- },
1020
- async close() {
1021
- client?.close();
1022
- },
1023
- });
1024
- await database.exec("PRAGMA foreign_keys = ON");
1025
- return database;
1026
- }
1027
-
1028
- export default {
1029
- atomicStorageAdapter: 1,
1030
- openDatabase: (options) =>
1031
- openCustomDatabase({
1032
- url: String(options.url),
1033
- authToken: typeof options.authToken === "string" ? options.authToken : undefined,
1034
- }),
1035
- } satisfies StorageAdapterModule;
1036
- ```
1037
-
1038
- The default export lets settings select this module as an [adapter](#selecting-an-adapter). From the SDK, call your open helper directly and pass the database to `createAgentSession`:
1039
-
1040
- ```typescript
1041
- import { openCustomDatabase } from "./custom-adapter.js";
1042
-
1043
- const database = await openCustomDatabase({
1044
- url: "libsql://your-database.turso.io",
1045
- authToken: process.env.TURSO_TOKEN,
1046
- });
1047
- try {
1048
- const { session } = await createAgentSession({
1049
- sessionStore: { kind: "database", database, prefix: "project_" },
1050
- });
1051
- await session.prompt("List the failing tests");
1052
- } finally {
1053
- await database.close();
1054
- }
1055
- ```
417
+ What to do:
1056
418
 
1057
- Multiple stores can share one caller-owned `database` without closing it.
419
+ 1. Upgrade every machine that uses a shared database to 0.10.11 or later.
420
+ 2. On PostgreSQL, run `atomic storage migrate` as the owner role.
1058
421
 
1059
- ### Custom `SessionStore` contracts
422
+ To take sessions back to an earlier release after the upgrade, export them with `atomic storage export`, which writes each fork in full, and import them with that release into a new store. With [debug mode](/development#debugging) on, Atomic writes to the debug log when it puts the upgrade off, and why.
1060
423
 
1061
- Non-SQL backends can implement `openSessionStore` directly (each session has one writer):
424
+ ## Workflow data from earlier releases
1062
425
 
1063
- - **Required for `history://`.** Implement `readEntryRange(id, query)` honoring `fromSeq`, `toSeq`, `seqs`, `maxChars`, `largeEntryBytes`, `skipTypes`, and `signal`. When `query.seqs` lists sequence numbers, return only the entries at those numbers. A `history://` search reads the entries it found, and the lines around them, this way, in one call. A store that returns the whole range instead still gives the same results, but reads more. Return freshly owned UTF-8 JSON buffers and `{ entries: [{ seq, entry }], throughSeq, lastSeq }` without falling back to whole-session `load()`.
1064
- - **Optional fast-path methods.** Implementing these avoids loading entire sessions into memory (stores implementing only `load()` still work with higher memory use):
426
+ Releases before 0.10.0 kept workflow runs under `workflows/journal/`, `workflows/pool/`, `workflows/runs/`, and in tables named `wf_*`. Atomic no longer runs those workflows. It never opens, changes, or deletes their data, so you can downgrade without losing old runs.
1065
427
 
1066
- | Method | Purpose |
1067
- | --- | --- |
1068
- | `readTail(id, fromSeq)` | Header and entries from `fromSeq`, plus earlier live state and omitted usage totals |
1069
- | `readRange(id, startSeq, endSeq)` | Inclusive 1-based range with `seqs`, `lastSeq`, and `epoch` |
1070
- | `findLatestCompaction(id, leafId?)` | Latest active compaction boundary, sequence, and retained start |
1071
- | `readResume(id, leafId?)` | Atomic resume snapshot (header, active branch from compaction, live state, omitted totals, `deliveryOpIds`, `lastSeq`, `lastEntryId`, `leafId`, `epoch`) |
1072
- | `findEntrySeq(id, entryId)` | 1-based entry sequence, or `undefined` |
1073
- | `readEntrySizes` / `readEntryChunk` / `readScanPage` | Byte-bounded streaming exports and remote page reads |
428
+ - `atomic storage status`, `migrate`, `export`, and `import` handle sessions and Intercom only. On PostgreSQL, `atomic storage migrate` still moves existing `wf_*` tables from `public` to `atomic`, so one database does not end up split across two schemas.
429
+ - `atomic storage adopt`, `atomic storage consolidate`, and the `--workflows`, `--run`, and `--unfinished` flags were removed.
430
+ - Cleaning up old worktree snapshots still keeps the snapshots that old workflow runs refer to.
431
+ - `ATOMIC_WORKFLOWS_JOURNAL`, `ATOMIC_WORKFLOW_JOURNAL_PATH`, `workflows.journal`, and `createAgentSession({ journal })` no longer choose a store.
1074
432
 
1075
- - **Epochs and indexes.** Keep `epoch` constant on appends, rotate it on `replace` or recreate, and reject mismatched `epoch` writes with `SessionConflictError`. Mark read-only stores `readOnly: true` to skip cleanup writes. Set `estimated: true` on `SessionSummary` when metadata is unindexed.
1076
- - **Forks and cloning.** `/fork`, `/clone`, and `SessionManager.forkFrom` stream entries in pages (same-store forks copy all branches; cross-store forks copy current context and mark the parent in another store; see [`/tree`, `/fork`, and `/clone`](/sessions#tree-fork-and-clone)).
433
+ To run an older workflow definition with this release, see [Migrating workflows](/orchestration/migrating-workflows).
1077
434
 
1078
435
  ## Storage errors
1079
436
 
1080
- Branch on error classes, `code`, and typed fields rather than message text. Configuration and facade errors are exported from `@bastani/atomic/storage`.
437
+ This section lists the errors Atomic's storage can raise, for people reading error output and for SDK apps that handle them. In code, check the error class, its `code`, and its fields, not the message text. The classes are exported from `@bastani/atomic/storage`.
1081
438
 
1082
- | Error | Fields and response |
1083
- | --- | --- |
1084
- | `StorageConfigError` | `code: "invalid-config"`, `source`, `field`, `reason`, optional `hint`. Fix the selected option; Atomic does not fall back to a lower-precedence store. |
1085
- | `StorageAdapterLoadError` | `module`, `cause`. Check package installation and the module's default export. |
1086
- | `StorageUnavailableError` | `adapter`, `location`, `cause`. Restore access to the selected store before retrying. |
1087
- | `StoragePrefixError` | `prefix`, `reason` (`"pattern"`, `"reserved"`, `"too-long"` with `maxLength`, `"identifier-collision"` with `identifier`, or `"uppercase"` on PostgreSQL). Use a valid non-reserved prefix (at most 24 lowercase characters on PostgreSQL). |
1088
- | `StorageSchemaVersionError` | `domain`, `found`, `supported`. Upgrade Atomic or use a supported database schema. |
1089
- | `StoreClosedError` / `StorageTransactionClosedError` | The store is closed or the transaction callback has finished. Open a new store or use the active callback handle. |
1090
- | `StorageRollbackError` | `cause`, `rollbackCause`. Do not assume the transaction rolled back. |
1091
- | `StorageOutcomeUnknownError` | `domain`, `id`, `key`. The driver could not confirm the write; inspect the keyed record before retrying. |
1092
- | `StoragePayloadTooLargeError` | `code: "payload-too-large"`, `kind` (`"value"` or `"response"`), `limitBytes`, `actualBytes`, `adapter`, `location`, `retryable: false`, `hint`, `cause`. Do not retry; reduce payload size or raise backend limits. See [Size limits](#size-limits). |
1093
- | `StorageInvalidTextError` | `parameterIndex`, `reason`. Remove U+0000 from scalar text bindings or encode as JSON or binary. |
1094
- | `TeamProfileConfigError` | Subclass of `StorageConfigError` for invalid team inputs (`code` equals `reason`). See [Team setup errors](#team-setup-errors). |
1095
- | `TeamProfileError` | Team setup operation failed after inputs passed validation. See [Team setup errors](#team-setup-errors). |
1096
-
1097
- Coded storage errors carry a stable `code` and actionable `hint`:
1098
-
1099
- | Class | Code | When | Key fields | What to do |
1100
- | --- | --- | --- | --- | --- |
1101
- | `StorageWriteLockTimeoutError` (subclass of `StorageUnavailableError`) | `write-lock-timeout` | A node-sqlite transaction waited its full `lockWaitMs` with no commits. Nothing ran. | `adapter`, `location`, `timeoutMs`, `elapsedMs`, `phase` (`"queued"` or `"acquiring"`), `holderPid`/`holderHeldMs` or `holderCandidates`, `retryable: true`, `cause` | Check the holding process or raise `lockWaitMs`, then retry. |
1102
- | `StorageUnsupportedOperationError` | `unsupported-operation` | `getWriterQueueStats` or `getWriterQueueDegradation` received a non-node-sqlite handle. | `operation`, `adapter`, `location` | Pass a handle from `openNodeSqliteDatabase` or `wrapNodeSqliteDatabase`. |
1103
- | `StorageWriterQueueDegradedError` | `writer-queue-degraded` | Recorded once per reason (via `getWriterQueueDegradation` and process warning), never thrown. Covers `watch-unavailable`, `wake-failed`, `stale-ticket-kept`, and `holder-record-unavailable`. | `reason`, `adapter`, `location`, `cause`, `hint` | Raise file-watch limits, fix permissions on the writer queue directories beside the database file, or remove abandoned entries. |
1104
- | `StorageWriterQueueUnusableError` (subclass of `StorageUnavailableError`) | `writer-queue-unusable` | A node-sqlite transaction could not use its writer queue directories. Nothing ran. | `adapter`, `location`, `errno`, `cause` | Make the database directory and writer queue directories readable and writable for all writers. |
1105
- | `StorageTransientError` (subclass of `StorageUnavailableError`) | `stream-expired`, `transaction-timeout`, `connection-refused`, `connection-lost`, `lock-conflict`, `read-only-server` | A temporary server or network failure ended a call (after up to 5 attempts if nothing was written, or immediately if `outcome` is `"unknown"`). | `adapter`, `location`, `outcome` (`"not-applied"` or `"unknown"`), `attempts`, `retryable: true`, `cause`, optional `hop` and `hopFailure` | Check connectivity to the server or named `hop`, then retry. For `"unknown"`, read state back before retrying non-idempotent writes. |
1106
- | `SessionBlobError` | `blobs-unsupported` | The session store lacks `putBlob` and `getBlob` needed for an import, fork, branch, or `tool-output://` read. | `sessionId`, `adapter` | Use SQLite, libSQL, or PostgreSQL, or implement `putBlob` and `getBlob` on your custom store. |
1107
- | `SessionBlobError` | `blob-missing` | A `tool-output://<sha256>` blob is missing. Copies, forks, and exports continue without it and emit a warning (or call `onMissingBlob`). | `sessionId`, `hash`, optional `missing` count | Run the tool again to regenerate the output. |
1108
- | `SessionBlobError` | `blob-incomplete` | A blob record exists, but part of its content is missing. | `sessionId`, `hash`, `bytes` | Run the tool again to regenerate the output. |
1109
- | `SessionBlobError` | `blob-corrupt` | Imported tool output failed its SHA-256 check. Nothing was written. | `sessionId`, `hash`, `actualHash` | Export the session again from its source. |
1110
- | `SessionSpillError` | `spill-read-failed` | `MemorySessionStore` failed to read a temporary history file under `released-history`. Retryable for `EMFILE`, `ENFILE`, `EAGAIN`, `EBUSY`, and `EINTR`. | `directory`, `sessionId`, `bytes`, `errno`, `cause` | Check directory permissions and file descriptor limits, then reopen the session. |
1111
- | `SessionSpillError` | `spill-missing` | A temporary history file under `released-history` is missing or truncated. History is lost; listings omit it. | `directory`, `sessionId`, `bytes`, optional `foundBytes`, `errno` | Leave `released-history` untouched while Atomic runs, or use a persistent store. |
1112
- | `SessionSpillError` | `spill-corrupt` | A temporary history file failed length, parse, or checksum checks. History is lost; listings omit it. | `directory`, `sessionId`, `bytes`, optional `foundBytes`, optional `cause` | Leave `released-history` untouched while Atomic runs, or use a persistent store. |
1113
- | `SessionSpillError` | `spill-write-failed`, `spill-dir-refused`, `spill-cleanup-failed` | Recorded once on the store and emitted as a process warning, never thrown. History remains in memory when writes or directory creation fail. | `directory`, optional `sessionId`, optional `bytes`, `errno`, optional `cause` | Free disk space or make the agent directory writable. |
1114
-
1115
- ### Error guards, serialization, and session persistence errors
1116
-
1117
- - **Guards.** Each coded error exports a cross-realm guard: `isStorageConfigError`, `isStorageWriteLockTimeoutError`, `isStorageUnsupportedOperationError`, `isStorageWriterQueueDegradedError`, `isStorageWriterQueueUnusableError`, `isStorageTransientError`, `isSessionBlobError`, and `isSessionSpillError`. Constant arrays `STORAGE_TRANSIENT_ERROR_CODES`, `SESSION_BLOB_ERROR_CODES`, and `SESSION_SPILL_ERROR_CODES` list their codes. `isStorageError(error)` matches any storage error above. `findStorageWriteLockTimeoutError(error)` and `isRetryableStorageError(error)` inspect up to 8 levels of `cause`.
1118
- - **Cross-process serialization.** Use `serializeStorageError(error)` and `rehydrateStorageError(json)` to pass storage errors across process boundaries with their class, fields, `cause` chain, `rollbackCause`, and `cleanupCause`. Unknown future error names rehydrate as `StorageError` keeping `name`, `code`, and fields.
1119
- - **Session store errors.** Session operations can throw `SessionNotFoundError` (`sessionId`), `SessionExistsError` (`sessionId`), `SessionIdMismatchError` (`requested`, `found`), `SessionConflictError` (`sessionId`, `expectedSeq`, `actualSeq`), `SessionFormatVersionError` (`path`, `found`, `supported`), `SessionInvalidTextError` (`field`, `reason`), `SessionInvalidTimestampError` (`field`, `reason`, `value`), and `JsonlStoragePoisonedError` (`location`, `cause`, `rollbackCause`). After a conflict, reopen the session before writing again.
1120
- - **Save failures during a run.** If a running session cannot save a message, Atomic reports `could not persist the <role> message: <cause>` once and halts that run without starting further model requests, tool calls, retries, fallbacks, or compaction. Print and JSON modes print the error on stderr and exit `1` (print mode still prints the received answer). Interactive mode displays the error, stays open, and retries saving on later prompts.
1121
- - **Abort signals.** Session listings accept an `AbortSignal` and reject with the original `signal.reason` unwrapped (`AbortError` for bare `controller.abort()`).
1122
-
1123
- ### Team setup errors
1124
-
1125
- `joinTeam()`, `leaveTeam()`, `getTeamProfile()`, `teamProfileSelection()`, `atomic storage join`, `atomic team`, and `ATOMIC_PROFILE=ci` validation throw these classes from `@bastani/atomic/storage`. Cross-process guards `isTeamProfileError()`, `isTeamProfileTimeoutError()`, and `isTeamProfileConfigError()` match by `name` and `code`, and `isRetryableTeamProfileError()` inspects up to 8 cause levels. Messages and fields name variables, flags, and files, never token values.
1126
-
1127
- `TeamProfileConfigError` extends `StorageConfigError` (`source`: `"sdk"`, `"cli"`, or `"env"`, `field`, `code`, `reason`, `hint`, optional `path` and `missing`, `retryable: false`). Nothing changes when it is thrown:
1128
-
1129
- | Code | When |
1130
- | --- | --- |
1131
- | `unknown-profile` | `ATOMIC_PROFILE` or SDK `profile` is not `ci` |
1132
- | `incomplete-profile` | A team variable is set without `ATOMIC_PROFILE`, or `ATOMIC_PROFILE=ci` lacks a URL or token (`missing` lists all missing variables) |
1133
- | `missing-url` | No database URL was passed |
1134
- | `unsupported-url` | URL is not `libsql://`, `https://`, `http://`, `wss://`, `ws://`, or `file:` |
1135
- | `relative-file-url` | A `file:` URL is relative |
1136
- | `credential-in-url` | URL contains a username, password, or `authToken` |
1137
- | `missing-token` | Non-`file:` URL has no token, or `tokenEnv` names an unset variable |
1138
- | `conflicting-token` | More than one token source was passed |
1139
- | `unreadable-token-file` | Token file cannot be read (`path` names it) |
1140
- | `relative-token-file` | `ATOMIC_TEAM_TOKEN_FILE` is relative instead of absolute |
1141
- | `empty-token` | Token, token file, or `tokenEnv` name is empty |
1142
- | `invalid-prefix` | Prefix breaks storage prefix rules |
1143
- | `unknown-command`, `unknown-option`, `missing-value`, `unexpected-argument` | Invalid `atomic team` CLI arguments |
1144
-
1145
- `TeamProfileError` (`code`, `subject`, `hint`, optional `detail` and `cause`, `retryable`):
439
+ ### Common errors
1146
440
 
1147
- | Code | When | What to do |
441
+ | Error | What it means | What to do |
1148
442
  | --- | --- | --- |
1149
- | `settings-unreadable` | Settings file cannot be read or parsed (`subject` names it). Nothing changed. | Fix the settings file and rerun. |
1150
- | `adapter-not-installed` | libSQL adapter cannot load. Nothing changed. | Run `atomic install npm:@bastani/atomic-storage-libsql`. |
1151
- | `connection-failed` | Database refused or failed `SELECT 1` (`retryable: true`). Nothing changed. | Check URL, token, and network, then retry. |
1152
- | `connection-timeout` | Database did not answer within 15 seconds. Thrown as `TeamProfileTimeoutError` with `timeoutMs`, `elapsedMs`, `phase: "connect"`, `retryable: true`. Nothing changed. | Check database reachability and retry. |
1153
- | `token-write-failed` | Private token file could not be written. Nothing changed. | Make the agent directory writable. |
1154
- | `settings-write-failed` | Settings could not be written (previous selection and token are kept). | Make the settings file writable or free disk space. |
1155
- | `settings-locked` | Another process held the settings lock (`retryable: true`). Nothing changed. | Retry in a few seconds; stale locks expire after 10 seconds. |
1156
- | `broker-restart-failed` | Returned in `broker`, not thrown: settings saved, but Intercom broker failed to restart (`retryable: true`). | Run `atomic intercom restart`. |
1157
- | `token-delete-failed` | `leaveTeam` removed settings, but could not delete the token file. | Delete the file manually. |
1158
-
1159
- `SHARED_STORAGE_JOIN_HINT` exports the canonical hint string `atomic team join <url> --token-file <path>`. Use `serializeTeamError(error)` and `rehydrateTeamError(json)` to preserve team error classes, fields, and up to 8 cause levels across processes without leaking credentials (non-team causes keep only `name` and `code`).
1160
-
1161
- ## Adapter conformance
1162
-
1163
- Validate any `SqliteDatabase` adapter against the conformance suites exported from `@bastani/atomic/storage/testing`:
1164
-
1165
- ```typescript
1166
- import {
1167
- registerSqliteConnectionConformance,
1168
- registerSqliteDatabaseConformance,
1169
- } from "@bastani/atomic/storage/testing";
1170
-
1171
- // Pass your test runner's `describe` and `it` functions.
1172
- registerSqliteDatabaseConformance({ describe, it }, "my adapter", withSubject);
1173
- registerSqliteConnectionConformance({ describe, it }, "my adapter connections", withConnections);
1174
- ```
443
+ | `StorageConfigError` | A storage setting, flag, or variable is invalid. Fields: `code: "invalid-config"`, `source`, `field`, `reason`, and optional `hint`. | Fix the option named in `field`. Atomic does not fall back to another store. |
444
+ | `StorageConfigError` with reason `libsql-removed` | A setting, variable, or command names a libSQL or Turso database. | Move your sessions as in [Moving off libSQL](#moving-off-libsql). |
445
+ | `StorageAdapterLoadError` | An adapter could not be loaded. Fields: `module`, `cause`. | Check that the adapter package is installed and has a default export. |
446
+ | `StorageUnavailableError` | The store could not be reached or opened. Fields: `adapter`, `location`, `cause`. | Restore access to the store, then retry. |
447
+ | `StoragePrefixError` | The `prefix` is not allowed. Fields: `prefix`, `reason`, which is `pattern`, `reserved`, `too-long` with `maxLength`, `identifier-collision` with `identifier`, or `uppercase` on PostgreSQL. | Use another prefix. On PostgreSQL, use at most 24 lowercase characters. |
448
+ | `StorageSchemaVersionError` | The store was upgraded by a newer Atomic. Fields: `domain`, which is `sessions` or `intercom`, `found`, `supported`. | Upgrade Atomic. See [Upgrading older stores](#upgrading-older-stores). |
449
+ | `StoragePayloadTooLargeError` | One value is larger than the store allows. Fields: `code: "payload-too-large"`, `kind` (`value` or `response`), `limitBytes`, `actualBytes`, `adapter`, `location`, `retryable: false`, `hint`, `cause`. | Do not retry. Store less in one value. See [Size limits](#size-limits). |
450
+ | `StorageTransientError` | A temporary server or network failure ended a call. Codes: `stream-expired`, `transaction-timeout`, `connection-refused`, `connection-lost`, `lock-conflict`, `read-only-server`. Fields: `adapter`, `location`, `outcome`, `attempts`, `retryable: true`, `cause`, and optional `hop` and `hopFailure`. Atomic has already retried up to 5 times if nothing was written. | Check the connection to the server, or the `hop` named in the error, then retry. If `outcome` is `unknown`, the write may have happened, so read the data back before you repeat a write. |
451
+ | `StorageOutcomeUnknownError` | The driver could not confirm whether a write happened. Fields: `domain`, `id`, `key`. | Read the record back before you retry. |
452
+
453
+ ### Session errors
454
+
455
+ | Error | Code | What it means | What to do |
456
+ | --- | --- | --- | --- |
457
+ | `SessionBlobError` | `blobs-unsupported` | The session store cannot hold tool output files, which an import, fork, branch, or `tool-output://` read needs. Fields: `sessionId`, `adapter`. | Use SQLite or PostgreSQL, or implement `putBlob` and `getBlob` in your custom store. |
458
+ | `SessionBlobError` | `blob-missing` | A `tool-output://<sha256>` file is missing. Copies, forks, and exports continue without it and warn. Fields: `sessionId`, `hash`, optional `missing` count. | Run the tool again to recreate the output. |
459
+ | `SessionBlobError` | `blob-incomplete` | Part of a tool output file is missing. Fields: `sessionId`, `hash`, `bytes`. | Run the tool again to recreate the output. |
460
+ | `SessionBlobError` | `blob-corrupt` | An imported tool output failed its SHA-256 check. Nothing was written. Fields: `sessionId`, `hash`, `actualHash`. | Export the session again from its source. |
461
+ | `SessionSpillError` | `spill-read-failed` | An in-memory store moves the older history of idle sessions to temporary files in the `released-history` folder of the agent directory. It could not read one of them. Retryable for `EMFILE`, `ENFILE`, `EAGAIN`, `EBUSY`, and `EINTR`. Fields: `directory`, `sessionId`, `bytes`, `errno`, `cause`. | Check the directory's permissions and the open-file limit, then reopen the session. |
462
+ | `SessionSpillError` | `spill-missing`, `spill-corrupt` | That temporary file is missing, cut short, or damaged. The history in it is lost, and session lists leave the session out. | Leave `released-history` alone while Atomic runs, or use a persistent store. |
463
+ | `SessionSpillError` | `spill-write-failed`, `spill-dir-refused`, `spill-cleanup-failed` | Atomic could not write or clean up that temporary file. It warns once and keeps the history in memory. Never thrown. | Free disk space, or make the agent directory writable. |
464
+
465
+ Other session errors: `SessionNotFoundError` (`sessionId`), `SessionExistsError` (`sessionId`), `SessionIdMismatchError` (`requested`, `found`), `SessionConflictError` (`sessionId`, `expectedSeq`, `actualSeq`), `SessionFormatVersionError` (`path`, `found`, `supported`), `SessionInvalidTextError` (`field`, `reason`), `SessionInvalidTimestampError` (`field`, `reason`, `value`), and `JsonlStoragePoisonedError` (`location`, `cause`, `rollbackCause`). After a `SessionConflictError`, another process wrote to the session first. Reopen the session before you write again.
466
+
467
+ **When a running session cannot save.** Atomic prints `could not persist the <role> message: <cause>` once and stops that run. It starts no further model requests, tool calls, retries, or compaction. Print and JSON modes print the error on stderr and exit `1`. Print mode still prints the answer it received. Interactive mode shows the error, stays open, and tries to save again on your next prompt.
468
+
469
+ ### Database handle errors
470
+
471
+ These come from the database handles that SDK apps open directly. The first four come from local SQLite files only. See [Local SQLite](/storage/sqlite#sdk-and-local-sqlite-api).
472
+
473
+ | Error | Code | What it means | What to do |
474
+ | --- | --- | --- | --- |
475
+ | `StorageWriteLockTimeoutError` | `write-lock-timeout` | A write waited `lockWaitMs` for another process to finish writing, and nothing committed in that time. Nothing ran. Fields: `adapter`, `location`, `timeoutMs`, `elapsedMs`, `phase`, the holder's `holderPid` and `holderHeldMs` or `holderCandidates`, `retryable: true`, `cause`. | Check the process that holds the lock, or raise `lockWaitMs`, then retry. |
476
+ | `StorageWriterQueueUnusableError` | `writer-queue-unusable` | A write could not use the queue directories next to the database file, which line writers up between processes. Nothing ran. Fields: `adapter`, `location`, `errno`, `cause`. | Make the database's directory and the queue directories readable and writable for every user that writes. |
477
+ | `StorageWriterQueueDegradedError` | `writer-queue-degraded` | Writes still work, but the queue had a problem: `watch-unavailable`, `wake-failed`, `stale-ticket-kept`, or `holder-record-unavailable`. Atomic warns once per reason. Never thrown. | Raise the file-watch limit, fix the queue directories' permissions, or remove abandoned queue entries. |
478
+ | `StorageUnsupportedOperationError` | `unsupported-operation` | `getWriterQueueStats` or `getWriterQueueDegradation` got a handle that is not a local SQLite handle. Fields: `operation`, `adapter`, `location`. | Pass a handle from `openNodeSqliteDatabase` or `wrapNodeSqliteDatabase`. |
479
+ | `StorageInvalidTextError` | | A text value contains the character U+0000. Fields: `parameterIndex`, `reason`. | Remove U+0000, or store the value as JSON or binary. |
480
+ | `StoreClosedError`, `StorageTransactionClosedError` | | The store is closed, or a transaction's callback has already finished. | Open a new store, or use the handle passed to the active callback. |
481
+ | `StorageRollbackError` | | A rollback failed after an error. Fields: `cause`, `rollbackCause`. | Do not assume the transaction rolled back. |
482
+
483
+ ### Handling errors in code
1175
484
 
1176
- - `withSubject` creates a fresh database per test case and passes `{ database, reopen, withRollbackFailure }` to the callback, cleaning up afterward. `reopen()` closes and reopens the same persistent database, and `withRollbackFailure(error, callback)` injects a rollback failure for the duration of `callback`. The suite verifies parameter binding, exact 64-bit integers, binary snapshots, NUL rejection, transaction ordering and expiration, commit and rollback errors, reopening, and close semantics.
1177
- - `withConnections` (for adapters supporting multiple connections to one database) opens two facades on the same fresh database and closes both afterward. The suite verifies concurrent write queuing and event-loop responsiveness.
485
+ - **Checks that work across processes.** `isStorageConfigError`, `isStorageWriteLockTimeoutError`, `isStorageUnsupportedOperationError`, `isStorageWriterQueueDegradedError`, `isStorageWriterQueueUnusableError`, `isStorageTransientError`, `isSessionBlobError`, and `isSessionSpillError` test for each coded error. `STORAGE_TRANSIENT_ERROR_CODES`, `SESSION_BLOB_ERROR_CODES`, and `SESSION_SPILL_ERROR_CODES` list the codes. `isStorageError(error)` matches any storage error.
486
+ - **Errors wrapped in others.** `findStorageWriteLockTimeoutError(error)` and `isRetryableStorageError(error)` look through up to 8 levels of `cause`.
487
+ - **Passing errors between processes.** `serializeStorageError(error)` and `rehydrateStorageError(json)` keep the class, fields, and `cause`, `rollbackCause`, and `cleanupCause`. An error class this release does not know comes back as `StorageError`, with its `name`, `code`, and fields.
488
+ - **Cancelling.** Session listings accept an `AbortSignal`. When it fires, they reject with the signal's own `reason`, such as an `AbortError`.
1178
489
 
1179
- Helper utilities exported from `@bastani/atomic/storage` for custom adapters:
490
+ ### Errors from `atomic storage join` {#team-setup-errors}
1180
491
 
1181
- - `validateStoragePrefix(prefix, dialect?)` validates optional table prefixes (ASCII letters, digits, and `_`, not starting with `sqlite_`, case-insensitively). Passing `"postgres"` also enforces lowercase and `POSTGRES_MAX_STORAGE_PREFIX_LENGTH` (24).
1182
- - `renderStorageIdentifiers("sessions", names, prefix)` returns a frozen map of table names with the `session_` prefix applied.
1183
- - `assertStorageSchemaVersion(domain, found, supported)` throws `StorageSchemaVersionError` when stored and supported versions differ.
492
+ `atomic storage join` and `atomic storage migrate --db` raise these errors, and so do [`atomic team status`](/guides/team-setup), the SDK's `getTeamProfile()`, and Atomic's refusal of a removed libSQL selection or team variable. `TeamProfileConfigError` means an input was invalid, and nothing changed. Error messages name variables, flags, and files, never a password or token.
493
+
494
+ | `TeamProfileConfigError` code | When |
495
+ | --- | --- |
496
+ | `libsql-removed` | The URL is a libSQL one, the command is `atomic team join` or `atomic team leave`, or a variable of the removed CI team profile is set: `ATOMIC_PROFILE`, `ATOMIC_TEAM_URL`, `ATOMIC_TEAM_TOKEN`, `ATOMIC_TEAM_TOKEN_FILE`, or `ATOMIC_TEAM_PREFIX`. See [Moving off libSQL](#moving-off-libsql). |
497
+ | `unsupported-url` | The URL is not `postgres://` or `postgresql://`. |
498
+ | `credential-in-url` | The URL contains a password. |
499
+ | `missing-token` | None of `--password-file`, `--token-file`, and `--auth` was given. |
500
+ | `conflicting-token` | More than one of `--password-file`, `--token-file`, and `--auth` was given. |
501
+ | `unsupported-auth` | `--auth` names something other than `azure`, `aws`, or `gcp`. |
502
+ | `unreadable-token-file` | The password or token file cannot be read. `path` names it. |
503
+ | `empty-token` | The password or token file is empty. |
504
+ | `invalid-prefix` | The prefix breaks the [prefix rules](/storage/postgres#share-one-database-between-teams). |
505
+ | `unknown-command`, `unknown-option`, `unexpected-argument` | Invalid `atomic team` arguments. |
506
+
507
+ `TeamProfileError` means the operation failed after its inputs passed. Fields: `code`, `subject`, `hint`, `retryable`, and optional `detail` and `cause`.
508
+
509
+ | Code | When | What to do |
510
+ | --- | --- | --- |
511
+ | `settings-unreadable` | The settings file cannot be read or parsed. `subject` names it. Nothing changed. | Fix the settings file and run the command again. |
512
+ | `adapter-not-installed` | The PostgreSQL adapter cannot be loaded. Nothing changed. | Run `atomic install npm:@bastani/atomic-storage-postgres`. |
513
+ | `connection-failed` | The database refused the connection, or `SELECT 1` failed. Nothing changed. Retryable. | Check the URL, the credentials, and the network, then retry. |
514
+ | `connection-timeout` | The database did not answer within 15 seconds. Raised as `TeamProfileTimeoutError`. Nothing changed. Retryable. | Check that the database is reachable, then retry. |
515
+ | `token-write-failed` | The private password file could not be written. Nothing changed. | Make the agent directory writable. |
516
+ | `settings-write-failed` | The settings could not be written. The previous setting and password file are kept. | Make the settings file writable, or free disk space. |
517
+ | `settings-locked` | Another process held the settings lock. Nothing changed. Retryable. | Retry after a few seconds. A stale lock expires after 10 seconds. |
518
+
519
+ In code, `isTeamProfileError()`, `isTeamProfileTimeoutError()`, and `isTeamProfileConfigError()` check these errors across processes, and `isRetryableTeamProfileError()` looks through up to 8 levels of `cause`. `serializeTeamError(error)` and `rehydrateTeamError(json)` pass them between processes without the credentials. `POSTGRES_STORAGE_JOIN_HINT` holds the hint text `atomic storage join <postgres-url> --password-file <path>`.