@bastani/atomic 0.10.11-alpha.1 → 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 (457) hide show
  1. package/CHANGELOG.md +155 -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 +9 -9
  7. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +8 -8
  8. package/dist/_shared/mode-shared-2QJSCUM6.js +9 -9
  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 +5 -5
  16. package/dist/_shared/{sdk-AVFII7NK.js → sdk-B5LEWGGI.js} +2633 -488
  17. package/dist/_shared/sdk-B5LEWGGI.js.map +1 -0
  18. package/dist/_shared/session-data-AHTU7IS6.js +3 -3
  19. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  20. package/dist/_shared/settings-startup-8-DNZ2RIHM.js +1 -1
  21. package/dist/_shared/{settings-startup-4QCVCI53.js → settings-startup-HXQLSUWM.js} +8 -2
  22. package/dist/_shared/settings-startup-HXQLSUWM.js.map +1 -0
  23. package/dist/_shared/{startup-0-0-57KF6LZH.js → startup-0-0-EZUKEP4Q.js} +436 -51
  24. package/dist/_shared/startup-0-0-EZUKEP4Q.js.map +1 -0
  25. package/dist/_shared/{startup-0-1-GIY75K46.js → startup-0-1-RTOHJFDJ.js} +240 -279
  26. package/dist/_shared/startup-0-1-RTOHJFDJ.js.map +1 -0
  27. package/dist/_shared/{startup-0-2-27OWFHV6.js → startup-0-2-5QHPCEON.js} +254 -46
  28. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -0
  29. package/dist/_shared/{startup-0-3-T4DVFYWX.js → startup-0-3-4ZYBYQNM.js} +273 -14
  30. package/dist/_shared/startup-0-3-4ZYBYQNM.js.map +1 -0
  31. package/dist/_shared/startup-0-4-ZMJV547D.js +14 -9
  32. package/dist/_shared/startup-0-4-ZMJV547D.js.map +1 -1
  33. package/dist/_shared/startup-0-5-YDW47QX6.js +10 -10
  34. package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -1
  35. package/dist/_shared/startup-10-0-TDQNBDDL.js +9 -9
  36. package/dist/_shared/startup-12-0-55AAXBJZ.js +3 -3
  37. package/dist/_shared/startup-14-0-MLX36RBG.js +6 -7
  38. package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
  39. package/dist/_shared/startup-15-0-YUKGAC63.js +7 -7
  40. package/dist/_shared/startup-15-1-4S7FLMNG.js +22 -30
  41. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  42. package/dist/_shared/startup-8-0-34CBHPZH.js +455 -102
  43. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  44. package/dist/_shared/{startup-8-1-X32CYSXB.js → startup-8-1-LZFXSD3Z.js} +162 -1184
  45. package/dist/_shared/startup-8-1-LZFXSD3Z.js.map +1 -0
  46. package/dist/_shared/storage-command-7MGXLJGZ.js +189 -36
  47. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  48. package/dist/_shared/storage-status-K7PX2RXA.js +557 -0
  49. package/dist/_shared/storage-status-K7PX2RXA.js.map +1 -0
  50. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  51. package/dist/_shared/team-DOQKICG2.js +376 -0
  52. package/dist/_shared/team-DOQKICG2.js.map +1 -0
  53. package/dist/_shared/tree-outline-MUEPK5B7.js +3 -3
  54. package/dist/builtin/intercom/CHANGELOG.md +34 -0
  55. package/dist/builtin/intercom/README.md +2 -2
  56. package/dist/builtin/intercom/broker/broker.bundle.mjs +1091 -344
  57. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +243 -64
  58. package/dist/builtin/intercom/broker/multinode-router.ts +154 -22
  59. package/dist/builtin/intercom/broker/multinode-state-store.ts +30 -3
  60. package/dist/builtin/intercom/broker/open-broker-state.ts +14 -0
  61. package/dist/builtin/intercom/broker/sql-add-column.ts +29 -5
  62. package/dist/builtin/intercom/broker/sql-ended-child-queue-store.ts +3 -2
  63. package/dist/builtin/intercom/broker/sql-held-send-store.ts +2 -2
  64. package/dist/builtin/intercom/broker/sql-known-session-store.ts +43 -19
  65. package/dist/builtin/intercom/broker/sql-lease-store.ts +208 -101
  66. package/dist/builtin/intercom/broker/sql-outbox-store.ts +516 -102
  67. package/dist/builtin/intercom/broker/sql-pending-ask-store.ts +8 -5
  68. package/dist/builtin/intercom/broker/sql-released-ask-store.ts +12 -5
  69. package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +24 -7
  70. package/dist/builtin/intercom/broker/sql-retention.ts +141 -0
  71. package/dist/builtin/intercom/broker/sql-schema.ts +199 -27
  72. package/dist/builtin/intercom/broker/sql-sent-message-authority.ts +74 -19
  73. package/dist/builtin/intercom/broker/wake-up-bus.ts +6 -0
  74. package/dist/builtin/intercom/index.bundle.mjs +2 -3
  75. package/dist/builtin/intercom/package.json +1 -1
  76. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  77. package/dist/builtin/mcp/package.json +1 -1
  78. package/dist/builtin/subagents/CHANGELOG.md +6 -0
  79. package/dist/builtin/subagents/package.json +1 -1
  80. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  81. package/dist/builtin/web-access/index.bundle.mjs +2 -10
  82. package/dist/builtin/web-access/package.json +1 -1
  83. package/dist/bun/bundled-sqlite.js +41 -0
  84. package/dist/bun/bundled-sqlite.js.map +1 -0
  85. package/dist/cli/args.js +2 -2
  86. package/dist/cli/auth-cli.code.js +6 -6
  87. package/dist/cli/auth-cli.impl.js +3 -3
  88. package/dist/cli/auth-cli.js +3 -3
  89. package/dist/cli/blueprint-command.code.js +4 -4
  90. package/dist/cli/blueprint-command.impl.js +3 -3
  91. package/dist/cli/blueprint-command.js +3 -3
  92. package/dist/cli/intercom-command.code.js +4 -4
  93. package/dist/cli/intercom-command.code.js.map +1 -1
  94. package/dist/cli/intercom-command.impl.js +3 -3
  95. package/dist/cli/intercom-command.js +3 -3
  96. package/dist/cli/list-models.code.js +2 -2
  97. package/dist/cli/list-models.impl.js +3 -3
  98. package/dist/cli/list-models.js +3 -3
  99. package/dist/cli/session-picker.code.js +2 -2
  100. package/dist/cli/session-picker.impl.js +3 -3
  101. package/dist/cli/session-picker.js +3 -3
  102. package/dist/cli/startup-ui.code.js +2 -2
  103. package/dist/cli/startup-ui.impl.js +3 -3
  104. package/dist/cli/startup-ui.js +3 -3
  105. package/dist/cli/storage-command.impl.js +3 -3
  106. package/dist/cli/storage-command.js +3 -3
  107. package/dist/cli/storage-search-session.code.js +3 -3
  108. package/dist/cli/storage-search-session.impl.js +3 -3
  109. package/dist/cli/storage-search-session.js +3 -3
  110. package/dist/cli/team-command.code.js +20 -114
  111. package/dist/cli/team-command.code.js.map +1 -1
  112. package/dist/cli/team-command.impl.js +3 -3
  113. package/dist/cli/team-command.js +3 -3
  114. package/dist/cli.js +5 -18
  115. package/dist/cli.js.map +1 -1
  116. package/dist/core/agent-rehydrate-errors.d.ts +4 -9
  117. package/dist/core/compaction/compactor.d.ts +3 -3
  118. package/dist/core/debug.code.js +1 -1
  119. package/dist/core/debug.impl.js +3 -3
  120. package/dist/core/debug.js +3 -3
  121. package/dist/core/export-html/card-projection.impl.js +3 -3
  122. package/dist/core/export-html/card-projection.js +3 -3
  123. package/dist/core/export-html/index.code.js +2 -2
  124. package/dist/core/export-html/index.impl.js +3 -3
  125. package/dist/core/export-html/index.js +3 -3
  126. package/dist/core/export-html/json-spans.impl.js +3 -3
  127. package/dist/core/export-html/json-spans.js +3 -3
  128. package/dist/core/export-html/oversized-render-inputs.code.js +1 -1
  129. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  130. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  131. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  132. package/dist/core/export-html/tool-renderer.js +3 -3
  133. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  134. package/dist/core/extensions/jiti-loader.js +3 -3
  135. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  136. package/dist/core/extensions/jiti-static-loader.js +3 -3
  137. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  138. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  139. package/dist/core/extensions/loader-host-modules.js +3 -3
  140. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  141. package/dist/core/extensions/runner-context.js +3 -3
  142. package/dist/core/intercom-broker-control-host.code.js +2 -2
  143. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  144. package/dist/core/intercom-broker-control-host.js +3 -3
  145. package/dist/core/intercom-broker-control.code.js +3 -3
  146. package/dist/core/intercom-broker-control.impl.js +3 -3
  147. package/dist/core/intercom-broker-control.js +3 -3
  148. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  149. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  150. package/dist/core/package-manager-storage-adapters.js +3 -3
  151. package/dist/core/process-start-token.d.ts +8 -0
  152. package/dist/core/process-tree-containment.d.ts +16 -0
  153. package/dist/core/sdk-types.d.ts +1 -2
  154. package/dist/core/sdk-types.js.map +1 -1
  155. package/dist/core/sdk.code.js +4 -4
  156. package/dist/core/sdk.impl.js +3 -3
  157. package/dist/core/sdk.js +3 -3
  158. package/dist/core/session-manager-core.js +27 -15
  159. package/dist/core/session-manager-core.js.map +1 -1
  160. package/dist/core/session-manager-list.impl.js +3 -3
  161. package/dist/core/session-manager-list.js +3 -3
  162. package/dist/core/session-manager.code.js +3 -3
  163. package/dist/core/session-manager.impl.js +3 -3
  164. package/dist/core/session-manager.js +3 -3
  165. package/dist/core/session-open-markers.js +3 -0
  166. package/dist/core/session-open-markers.js.map +1 -0
  167. package/dist/core/session-storage.code.js +1 -1
  168. package/dist/core/session-storage.impl.js +3 -3
  169. package/dist/core/session-storage.js +3 -3
  170. package/dist/core/settings-schema.d.ts +0 -3
  171. package/dist/core/storage/added-exports-0-10-11.js +19 -0
  172. package/dist/core/storage/added-exports-0-10-11.js.map +1 -0
  173. package/dist/core/storage/added-exports.js +3 -0
  174. package/dist/core/storage/added-exports.js.map +1 -1
  175. package/dist/core/storage/creation-time.js +105 -0
  176. package/dist/core/storage/creation-time.js.map +1 -0
  177. package/dist/core/storage/database.d.ts +56 -5
  178. package/dist/core/storage/database.js.map +1 -1
  179. package/dist/core/storage/dialect.d.ts +1 -1
  180. package/dist/core/storage/dialect.js +1 -1
  181. package/dist/core/storage/dialect.js.map +1 -1
  182. package/dist/core/storage/errors.d.ts +13 -13
  183. package/dist/core/storage/errors.js +10 -16
  184. package/dist/core/storage/errors.js.map +1 -1
  185. package/dist/core/storage/fenced-paths.d.ts +11 -0
  186. package/dist/core/storage/fenced-paths.js +11 -0
  187. package/dist/core/storage/fenced-paths.js.map +1 -1
  188. package/dist/core/storage/file-identity.d.ts +2 -0
  189. package/dist/core/storage/file-identity.js +24 -8
  190. package/dist/core/storage/file-identity.js.map +1 -1
  191. package/dist/core/storage/index.d.ts +4 -3
  192. package/dist/core/storage/index.js +5 -3
  193. package/dist/core/storage/index.js.map +1 -1
  194. package/dist/core/storage/libsql-removed.d.ts +71 -0
  195. package/dist/core/storage/libsql-removed.js +123 -0
  196. package/dist/core/storage/libsql-removed.js.map +1 -0
  197. package/dist/core/storage/migrations.d.ts +81 -8
  198. package/dist/core/storage/migrations.js +386 -47
  199. package/dist/core/storage/migrations.js.map +1 -1
  200. package/dist/core/storage/node-sqlite-file-gate.js +0 -15
  201. package/dist/core/storage/node-sqlite-file-gate.js.map +1 -1
  202. package/dist/core/storage/node-sqlite-thread.js +36 -12
  203. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  204. package/dist/core/storage/node-sqlite.js +135 -3
  205. package/dist/core/storage/node-sqlite.js.map +1 -1
  206. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  207. package/dist/core/storage/offline-snapshot-file.js +3 -3
  208. package/dist/core/storage/prefix.d.ts +1 -1
  209. package/dist/core/storage/prefix.js +14 -2
  210. package/dist/core/storage/prefix.js.map +1 -1
  211. package/dist/core/storage/process-selection.d.ts +5 -5
  212. package/dist/core/storage/provider.js +2 -2
  213. package/dist/core/storage/schema-catalog.d.ts +82 -5
  214. package/dist/core/storage/schema-catalog.js +244 -34
  215. package/dist/core/storage/schema-catalog.js.map +1 -1
  216. package/dist/core/storage/selection.d.ts +7 -82
  217. package/dist/core/storage/selection.js +20 -235
  218. package/dist/core/storage/selection.js.map +1 -1
  219. package/dist/core/storage/session/branch-fork-source.code.js +9 -8
  220. package/dist/core/storage/session/branch-fork-source.code.js.map +1 -1
  221. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  222. package/dist/core/storage/session/branch-fork-source.js +3 -3
  223. package/dist/core/storage/session/card-view.impl.js +3 -3
  224. package/dist/core/storage/session/card-view.js +3 -3
  225. package/dist/core/storage/session/child-reader.code.js +4 -4
  226. package/dist/core/storage/session/child-reader.impl.js +3 -3
  227. package/dist/core/storage/session/child-reader.js +3 -3
  228. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  229. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  230. package/dist/core/storage/session/errors.js +1 -1
  231. package/dist/core/storage/session/expanded-child-details.code.js +3 -3
  232. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  233. package/dist/core/storage/session/expanded-child-details.js +3 -3
  234. package/dist/core/storage/session/fork-detach.d.ts +118 -0
  235. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  236. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  237. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  238. package/dist/core/storage/session/fork-row-index.js +3 -3
  239. package/dist/core/storage/session/fork-schema.js +53 -0
  240. package/dist/core/storage/session/fork-schema.js.map +1 -0
  241. package/dist/core/storage/session/fork-segments.d.ts +58 -0
  242. package/dist/core/storage/session/fork-staging.code.js +5 -8
  243. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  244. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  245. package/dist/core/storage/session/fork-staging.js +3 -3
  246. package/dist/core/storage/session/fork-sweep.js +61 -0
  247. package/dist/core/storage/session/fork-sweep.js.map +1 -0
  248. package/dist/core/storage/session/fork-window.code.js +4 -4
  249. package/dist/core/storage/session/fork-window.impl.js +3 -3
  250. package/dist/core/storage/session/fork-window.js +3 -3
  251. package/dist/core/storage/session/history-pages.impl.js +3 -3
  252. package/dist/core/storage/session/history-pages.js +3 -3
  253. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  254. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  255. package/dist/core/storage/session/jsonl-session-store.d.ts +42 -2
  256. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  257. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  258. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  259. package/dist/core/storage/session/memory-session-store.js +3 -3
  260. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  261. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  262. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  263. package/dist/core/storage/session/released-history-files.code.js +4 -4
  264. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  265. package/dist/core/storage/session/released-history-files.js +3 -3
  266. package/dist/core/storage/session/resident-fork-rows.code.js +1 -1
  267. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  268. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  269. package/dist/core/storage/session/session-resume.impl.js +3 -3
  270. package/dist/core/storage/session/session-resume.js +3 -3
  271. package/dist/core/storage/session/session-search-index.d.ts +43 -4
  272. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  273. package/dist/core/storage/session/snapshot-cut.js +3 -3
  274. package/dist/core/storage/session/snapshot-history.code.js +4 -4
  275. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  276. package/dist/core/storage/session/snapshot-history.js +3 -3
  277. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  278. package/dist/core/storage/session/sql-session-store.d.ts +394 -20
  279. package/dist/core/storage/session/sql-session-store.impl.js +4 -4
  280. package/dist/core/storage/session/sql-session-store.js +4 -4
  281. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  282. package/dist/core/storage/session/tree-outline.js +3 -3
  283. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  284. package/dist/core/storage/session/tree-presentation.js +3 -3
  285. package/dist/core/storage/session/types.d.ts +22 -0
  286. package/dist/core/storage/sqlite-facade.d.ts +23 -2
  287. package/dist/core/storage/sqlite-facade.js +34 -0
  288. package/dist/core/storage/sqlite-facade.js.map +1 -1
  289. package/dist/core/storage/storage-status.code.js +1 -1
  290. package/dist/core/storage/storage-status.impl.js +3 -3
  291. package/dist/core/storage/storage-status.js +3 -3
  292. package/dist/core/storage/team.code.js +1 -1
  293. package/dist/core/storage/team.d.ts +26 -115
  294. package/dist/core/storage/team.impl.js +3 -3
  295. package/dist/core/storage/team.js +3 -3
  296. package/dist/core/structured-output/index.code.js +1 -1
  297. package/dist/core/structured-output/index.impl.js +3 -3
  298. package/dist/core/structured-output/index.js +3 -3
  299. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  300. package/dist/core/tasks/task-completion-entry.js +3 -3
  301. package/dist/core/tasks/task-file-history.code.js +4 -4
  302. package/dist/core/tasks/task-file-history.impl.js +3 -3
  303. package/dist/core/tasks/task-file-history.js +3 -3
  304. package/dist/core/tasks/task-reference-archive.code.js +5 -5
  305. package/dist/core/tasks/task-reference-archive.js +3 -3
  306. package/dist/core/tasks/task-reference-identity.js +3 -3
  307. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  308. package/dist/core/tasks/task-reference-stream.js +3 -3
  309. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  310. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  311. package/dist/core/tasks/task-view-source.code.js +1 -1
  312. package/dist/core/tasks/task-view-source.impl.js +3 -3
  313. package/dist/core/tasks/task-view-source.js +3 -3
  314. package/dist/core/tools/history-session.d.ts +2 -0
  315. package/dist/core/tools/history-tasks.d.ts +3 -2
  316. package/dist/core/tools/read-url.code.js +4 -4
  317. package/dist/core/tools/read-url.impl.js +3 -3
  318. package/dist/core/tools/read-url.js +3 -3
  319. package/dist/core/worktree-snapshot/blob-store.d.ts +71 -3
  320. package/dist/core/worktree-snapshot/blob-store.js +575 -67
  321. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  322. package/dist/core/worktree-snapshot/errors.code.js +3 -3
  323. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  324. package/dist/core/worktree-snapshot/errors.js +3 -3
  325. package/dist/core/worktree-snapshot/fork-blob-guard.js +81 -0
  326. package/dist/core/worktree-snapshot/fork-blob-guard.js.map +1 -0
  327. package/dist/core/worktree-snapshot/fork-snapshot-index.js +162 -0
  328. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -0
  329. package/dist/core/worktree-snapshot/session-index-reset.code.js +4 -0
  330. package/dist/core/worktree-snapshot/session-index-reset.code.js.map +1 -1
  331. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  332. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  333. package/dist/extensions/codemode/execute.code.js +2 -2
  334. package/dist/extensions/codemode/execute.impl.js +3 -3
  335. package/dist/extensions/codemode/execute.js +3 -3
  336. package/dist/extensions/codemode/renderer.code.js +2 -2
  337. package/dist/extensions/codemode/renderer.impl.js +3 -3
  338. package/dist/extensions/codemode/renderer.js +3 -3
  339. package/dist/extensions/mcp/cli.code.js +3 -3
  340. package/dist/extensions/mcp/cli.impl.js +3 -3
  341. package/dist/extensions/mcp/cli.js +3 -3
  342. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  343. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  344. package/dist/extensions/mcp/cli.lazy.js +3 -3
  345. package/dist/extensions/mcp/runtime.code.js +1 -1
  346. package/dist/extensions/mcp/runtime.impl.js +3 -3
  347. package/dist/extensions/mcp/runtime.js +3 -3
  348. package/dist/index.d.ts +3 -1
  349. package/dist/index.js +8 -8
  350. package/dist/main-first-time-setup.code.js +2 -2
  351. package/dist/main-first-time-setup.impl.js +3 -3
  352. package/dist/main-first-time-setup.js +3 -3
  353. package/dist/main.js +1 -1
  354. package/dist/modes/interactive/components/stored-tree-view.code.js +3 -3
  355. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  356. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  357. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  358. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  359. package/dist/modes/interactive/startup-shell-eligibility.js +1 -1
  360. package/dist/modes/interactive-engine/engine-prewarm.d.ts +1 -1
  361. package/dist/modes/print-mode.js +1 -1
  362. package/dist/package-manager-cli.code.js +7 -7
  363. package/dist/package-manager-cli.impl.js +3 -3
  364. package/dist/package-manager-cli.js +3 -3
  365. package/dist/rpc-entry.js +1 -1
  366. package/dist/startup-files.json +1 -1
  367. package/dist/startup-stages/10.js +1 -1
  368. package/dist/startup-stages/11.js +1 -1
  369. package/dist/startup-stages/12.js +1 -1
  370. package/dist/startup-stages/2.js +2 -3
  371. package/dist/startup-stages/3.js +1 -3
  372. package/dist/startup-stages/4.js +1 -2
  373. package/dist/startup-stages/5.js +1 -1
  374. package/dist/startup-stages/6.js +5 -7
  375. package/dist/startup-stages/7.js +3 -6
  376. package/dist/startup-stages/8.js +7 -2
  377. package/dist/startup-stages/9.js +1 -7
  378. package/dist/startup-stages/stages.json +1 -1
  379. package/dist/utils/compile-cache-deferral.js +8 -13
  380. package/dist/utils/compile-cache-deferral.js.map +1 -1
  381. package/dist/utils/compile-cache-warmup-host.js +3 -4
  382. package/dist/utils/compile-cache-warmup-host.js.map +1 -1
  383. package/dist/utils/compile-cache.js +12 -100
  384. package/dist/utils/compile-cache.js.map +1 -1
  385. package/dist/utils/startup-database-spare.code.js +3 -3
  386. package/dist/utils/startup-database-spare.impl.js +3 -3
  387. package/dist/utils/startup-database-spare.js +3 -3
  388. package/dist/utils/tools-manager.code.js +1 -1
  389. package/dist/utils/tools-manager.impl.js +3 -3
  390. package/dist/utils/tools-manager.js +3 -3
  391. package/dist/utils/worker-threads.js +2 -15
  392. package/dist/utils/worker-threads.js.map +1 -1
  393. package/docs/build.md +3 -3
  394. package/docs/changelog.mdx +1421 -69
  395. package/docs/compaction/reference.md +5 -5
  396. package/docs/compaction.md +7 -9
  397. package/docs/containerization.md +2 -2
  398. package/docs/custom-provider/api-reference.md +1 -1
  399. package/docs/docs.json +37 -10
  400. package/docs/environment-variables.md +0 -2
  401. package/docs/extensions/api-reference.md +4 -4
  402. package/docs/getting-started/installation.md +3 -0
  403. package/docs/guides/configuration.md +1 -1
  404. package/docs/guides/non-interactive.md +1 -1
  405. package/docs/guides/resume-on-any-machine.md +14 -22
  406. package/docs/guides/team-setup.md +56 -83
  407. package/docs/guides.md +2 -4
  408. package/docs/herdr.md +1 -1
  409. package/docs/index.md +1 -1
  410. package/docs/intercom/operations.md +26 -21
  411. package/docs/intercom/reference.md +2 -2
  412. package/docs/intercom.md +1 -1
  413. package/docs/libraries/storage-postgres.md +9 -9
  414. package/docs/libraries.md +2 -3
  415. package/docs/models-configuration.md +2 -2
  416. package/docs/models.md +2 -3
  417. package/docs/packages/authoring.md +7 -7
  418. package/docs/packages.md +1 -1
  419. package/docs/programmatic.md +2 -2
  420. package/docs/quickstart.md +1 -1
  421. package/docs/reference/cli.md +6 -11
  422. package/docs/reference.md +2 -2
  423. package/docs/rpc/extension-ui.md +2 -2
  424. package/docs/sdk/reference.md +5 -4
  425. package/docs/sdk/storage.md +8 -92
  426. package/docs/sdk/structured-decisions.md +1 -1
  427. package/docs/sdk/web-server.md +3 -3
  428. package/docs/sdk.md +14 -4
  429. package/docs/security.md +1 -1
  430. package/docs/session-format.md +5 -5
  431. package/docs/sessions.md +31 -42
  432. package/docs/settings.md +7 -8
  433. package/docs/storage/custom-adapters.md +255 -0
  434. package/docs/storage/jsonl.md +117 -0
  435. package/docs/{guides/postgres-pgbouncer.md → storage/postgres/pgbouncer.md} +73 -68
  436. package/docs/storage/postgres/tuning.md +337 -0
  437. package/docs/storage/postgres.md +556 -0
  438. package/docs/storage/sqlite.md +99 -0
  439. package/docs/storage.md +333 -956
  440. package/docs/subagents/authoring.md +1 -1
  441. package/docs/subagents.md +2 -2
  442. package/docs/tools.md +1 -1
  443. package/docs/worktree-snapshots.md +2 -2
  444. package/package.json +9 -9
  445. package/schemas/models.schema.json +2 -2
  446. package/schemas/settings.schema.json +0 -14
  447. package/dist/_shared/sdk-AVFII7NK.js.map +0 -1
  448. package/dist/_shared/settings-startup-4QCVCI53.js.map +0 -1
  449. package/dist/_shared/startup-0-0-57KF6LZH.js.map +0 -1
  450. package/dist/_shared/startup-0-1-GIY75K46.js.map +0 -1
  451. package/dist/_shared/startup-0-2-27OWFHV6.js.map +0 -1
  452. package/dist/_shared/startup-0-3-T4DVFYWX.js.map +0 -1
  453. package/dist/_shared/startup-8-1-X32CYSXB.js.map +0 -1
  454. package/dist/core/intercom-broker-control.d.ts +0 -129
  455. package/dist/startup-stages/13.js +0 -1
  456. package/docs/guides/postgres-tuning.md +0 -311
  457. package/docs/libraries/storage-libsql.md +0 -97
package/docs/storage.md CHANGED
@@ -1,1142 +1,519 @@
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.
9
+ Read this page when you want to:
47
10
 
48
- ### Locks in the agent directory
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.
49
15
 
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.
16
+ Each kind of store has its own page:
51
17
 
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:
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.
53
22
 
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
- ```
23
+ Apps built on the SDK choose their store in code. See [SDK session storage](/sdk/storage).
92
24
 
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
- `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.
128
-
129
- 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.
130
-
131
- 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.
132
-
133
- 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"`.
134
-
135
- #### Upgrading from tables in `public`
136
-
137
- Older releases created Atomic's tables in `public`. Atomic continues reading tables in `public` when no `atomic` schema exists yet.
138
-
139
- 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.
140
-
141
- `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.
142
-
143
- ### Join a machine
144
-
145
- Install the PostgreSQL adapter once per machine in user scope, then join the database:
146
-
147
- ```bash
148
- atomic install npm:@bastani/atomic-storage-postgres
149
- printf '%s' '<password>' > ~/atomic-db-password && chmod 600 ~/atomic-db-password
150
- atomic storage join 'postgresql://atomic_runtime@db.example.com:5432/atomic' --password-file ~/atomic-db-password
151
- atomic intercom restart
152
- atomic storage status
153
- ```
25
+ Two rules hold for every store:
154
26
 
155
- `atomic storage join` accepts `postgres://` and `postgresql://` URLs with a username and no embedded password. Pass exactly one credential option:
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).
156
29
 
157
- - `--password-file <path>` copies the password into a private mode-`600` `~/.atomic/agent/storage-token.<id>` file. You can delete the input file afterward.
158
- - `--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.
159
- - `--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).
160
-
161
- `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`:
162
-
163
- ```json
164
- {
165
- "storage": {
166
- "adapter": "@bastani/atomic-storage-postgres",
167
- "options": { "url": "postgresql://atomic_runtime@db.example.com:5432/atomic" },
168
- "secrets": { "password": { "file": "agent/storage-token.3f2a" } }
169
- }
170
- }
171
- ```
172
-
173
- 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
174
31
 
175
- | Option | Default | Description |
32
+ | Situation | Store | Why |
176
33
  | --- | --- | --- |
177
- | `url` | Required | `postgres://` or `postgresql://` URL with username and no password |
178
- | `auth` | `"password"` | `"azure-entra"`, `"aws-iam"`, or `"gcp-iam"` for [cloud identities](#cloud-identities) |
179
- | `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) |
180
- | `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 |
181
- | `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 |
182
- | `connectTimeoutMs` | `10000` | How long opening a connection, or waiting for a free one, may take, in milliseconds. A positive integer |
183
- | `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 |
184
- | `keepAliveIdleMs` | `60000` | How long, in milliseconds, a connection sits unused before Atomic starts TCP keepalive probes on it. A positive integer |
185
- | `maxPreparedStatements` | `256`, or `0` when `listenUrl` is set or the URL's port is 6432 or 6543 | 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 |
186
- | `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`) |
187
- | `schema` | `"atomic"` | Schema name starting with a lowercase ASCII letter or `_`, followed by lowercase letters, digits, or `_` (1 to 63 characters) |
188
- | `proxy` | From environment | `http://` or `https://` proxy URL for all connections, or `"none"` to connect directly |
189
-
190
- `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).
191
-
192
- ### TLS
193
-
194
- 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`.
195
-
196
- 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`.
197
-
198
- Provider CA configuration:
199
-
200
- - **Azure Database for PostgreSQL, Azure HorizonDB, and Neon.** Certificates chain to CAs trusted by Node.js, so no extra parameter is required.
201
- - **Supabase.** Download the project CA certificate from Project Settings > Database > SSL Configuration and add `?sslrootcert=/path/to/supabase-ca.pem`.
202
- - **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`.
203
- - **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.
204
-
205
- ### Through an HTTP proxy
206
-
207
- 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.
208
-
209
- - **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.
210
- - **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.
211
- - **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.
212
- - **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.
213
-
214
- Atomic handles informational `1xx` proxy replies (such as `103 Early Hints`) and allows up to 16 KiB for total proxy response headers.
215
-
216
- 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.
217
-
218
- ### Connection budget
219
-
220
- 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:
221
-
222
- - **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`.
223
- - **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`.
224
- - **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`.
225
-
226
- So a process opens at most `maxConnections` + `readerMaxConnections` + 1 connections per database: 11 with the defaults.
227
-
228
- 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.
229
-
230
- 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.
231
-
232
- 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.
233
-
234
- 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:
235
-
236
- - **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.
237
- - **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.
238
- - **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.
239
-
240
- ### 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 |
241
40
 
242
- 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.
243
42
 
244
- 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.
245
-
246
- 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.
247
-
248
- ### Wake-ups
249
-
250
- 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.
251
-
252
- 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.
253
-
254
- `atomic storage status` reports the wake-up state:
255
-
256
- - `wake-ups: LISTEN/NOTIFY` means instant notifications are active.
257
- - `wake-ups: polling only, notifications do not pass the URL's transaction pooler` means you should set `listenUrl` to a direct endpoint.
258
- - `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.
259
-
260
- ### Azure
261
-
262
- **Azure Database for PostgreSQL Flexible Server:**
263
-
264
- - Connect directly to `<server>.postgres.database.azure.com` on port 5432.
265
- - 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.
266
- - 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.
267
- - 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).
268
- - Allow client addresses in firewall rules or use private access.
269
-
270
- **Azure HorizonDB (preview, PostgreSQL 17):**
271
-
272
- - 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.
273
- - Add `pg_trgm` to `azure.extensions` in the compute pool's parameter group, then run `atomic storage migrate`.
274
- - Allow client addresses in firewall rules or connect over a private endpoint.
275
-
276
- 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`.
277
-
278
- ### Cloud identities
279
-
280
- 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:
281
-
282
- | `--auth` | `options.auth` | Install | Credential source |
283
- | --- | --- | --- | --- |
284
- | `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` |
285
- | `aws` or `aws-iam` | `"aws-iam"` | `atomic install npm:@aws-sdk/rds-signer` | Default AWS credentials (`AWS_*` variables, profiles, IRSA, or instance profile) |
286
- | `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`) |
287
-
288
- 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`.
289
-
290
- Map the cloud identity to a PostgreSQL role on your provider:
291
-
292
- - **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.
293
- - **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`.
294
- - **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.
295
-
296
- 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.
297
-
298
- 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.
299
-
300
- ### Troubleshooting PostgreSQL
301
-
302
- - **`credential-in-url`.** Remove the password from the URL and pass `--password-file` or `--token-file`.
303
- - **`unsupported-url` from `atomic team join`.** `atomic team join` supports libSQL only. Use `atomic storage join` for PostgreSQL.
304
- - **`unsupported-option`.** `--password-file` and `--auth` apply to PostgreSQL only. libSQL uses `--token-file`.
305
- - **`unsupported-auth`.** `--auth` accepts `azure` (`azure-entra`), `aws` (`aws-iam`), or `gcp` (`gcp-iam`).
306
- - **`adapter-not-installed`.** Run `atomic install npm:@bastani/atomic-storage-postgres` as the user running Atomic.
307
- - **`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.
308
- - **`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`.
309
- - **"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.
310
- - **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`.
311
- - **`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.
312
- - **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).
313
- - **`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.
314
- - **`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.
315
- - **`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.
316
- - **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.
317
- - **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).
318
- - **`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"`.
319
- - **`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.
320
- - **`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).
321
- - **`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.
322
- - **`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`.
323
- - **`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.
324
- - **`wake-ups: polling only` in `atomic storage status`.** Messages still arrive via polling. See [Wake-ups](#wake-ups) to restore `LISTEN`/`NOTIFY`.
325
- - **Failover or pooler restart disconnects.** Reported as `StorageTransientError` with code `connection-lost`.
326
-
327
- ## Turso and libSQL
328
-
329
- `@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`:
330
-
331
- ```bash
332
- atomic install npm:@bastani/atomic-storage-libsql
333
- ```
334
-
335
- ```json
336
- {
337
- "storage": {
338
- "adapter": "@bastani/atomic-storage-libsql",
339
- "options": { "url": "libsql://<db>.turso.io" },
340
- "secrets": { "authToken": { "file": "turso-token" } }
341
- }
342
- }
343
- ```
344
-
345
- - **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.
346
- - **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.
347
- - **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.
348
- - **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).
349
- - **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`).
350
-
351
- 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).
352
44
 
353
45
  ## Sharing storage across hosts
354
46
 
355
- 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.
356
-
357
- - **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`.
358
- - **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).
359
-
360
- ### Joining a machine to a shared database
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.
361
48
 
362
- > Want shared Intercom while keeping personal sessions local? Use `atomic team join` instead ([Set up teams and CI](/guides/team-setup)).
49
+ Which setting you change decides what is shared:
363
50
 
364
- **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 |
365
56
 
366
- ```bash
367
- atomic install npm:@bastani/atomic-storage-libsql
368
- turso db tokens create <db> > ~/turso-token
369
- atomic storage join libsql://<db>.turso.io --token-file ~/turso-token
370
- atomic intercom restart
371
- atomic storage status
372
- ```
57
+ Project settings can choose where a project's sessions go, but never Intercom's store.
373
58
 
374
- **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).
375
60
 
376
- 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).
377
62
 
378
- ```bash
379
- atomic install npm:@bastani/atomic-storage-postgres
380
- atomic storage join postgresql://atomic_runtime@db.example.com:5432/atomic?sslmode=verify-full --password-file ~/pg-password
381
- atomic intercom restart
382
- atomic storage status
383
- ```
63
+ ### Joining a machine to a shared database
384
64
 
385
- `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.
386
66
 
387
- 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.
388
- 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.
389
- 3. Updates only the top-level `storage` key in `~/.atomic/agent/settings.json` (plus optional `--prefix`), preserving all other settings.
390
- 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:
391
68
 
392
- 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.
393
73
 
394
- - **No embedded secrets.** Userinfo passwords and `authToken=` or `password=` query parameters are refused.
395
- - **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.
396
- - **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.
397
75
 
398
76
  ### Checking the selected storage
399
77
 
400
- 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:
401
79
 
402
- - 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).
403
- - 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.
404
- - 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.
405
84
 
406
- 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.
407
86
 
408
- ### Selecting storage per process
87
+ ## Selecting storage per process
409
88
 
410
- 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`:
411
90
 
412
- | Option | Applies to | Equivalent setting |
91
+ | Option | Applies to | Same as the setting |
413
92
  | --- | --- | --- |
414
- | `--storage '<json>'` | Sessions and Intercom (cannot use `{ "dir": "..." }`) | Shared `storage` |
415
- | `--storage-file <path>` | Sessions and Intercom (reads JSON from a file; cannot use `{ "dir": "..." }`) | Shared `storage` |
416
- | `ATOMIC_STORAGE` | Sessions and Intercom (cannot use `{ "dir": "..." }`) | Shared `storage` |
417
- | `ATOMIC_SESSIONS_STORAGE` | Sessions only (also accepts `{ "dir": "..." }` for JSONL) | `sessions.storage` |
418
- | `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` |
419
97
 
420
98
  ```bash
421
- 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_"}' \
422
100
  atomic --mode rpc
423
101
 
424
102
  atomic --mode rpc --storage-file /etc/atomic/storage.json
425
103
  ```
426
104
 
427
- `--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.
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.
428
108
 
429
- 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.
109
+ ### Which selection wins
430
110
 
431
- Precedence for sessions, highest first:
111
+ For sessions, the first of these that is set wins:
432
112
 
433
- 1. Explicit SDK `sessionManager` (bypasses store selection)
434
- 2. SDK `sessionStore`
435
- 3. SDK `createAgentSession({ storage })`
436
- 4. `--session-store`, `--no-session`, or `--session-dir`
437
- 5. `--storage` or `--storage-file`
438
- 6. `ATOMIC_SESSIONS_STORAGE` or `ATOMIC_CODING_AGENT_SESSION_DIR`
439
- 7. `ATOMIC_STORAGE`
440
- 8. `ATOMIC_PROFILE=ci`
441
- 9. `sessions.storage` setting
442
- 10. Shared `storage` setting
443
- 11. Default local SQLite file (`~/.atomic/workflows/journal.sqlite`)
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`
444
121
 
445
- Override conflicts and path rules:
122
+ Where two selections meet:
446
123
 
447
- - Session flags such as `--session-dir` override `--storage` for sessions only, leaving Intercom on `--storage`.
448
- - `ATOMIC_CODING_AGENT_SESSION_DIR` overrides `ATOMIC_STORAGE` for sessions only.
449
- - 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.
450
- - 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.
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.
451
128
 
452
- 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.
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.
453
130
 
454
- 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.
131
+ ### Keeping credentials safe
455
132
 
456
- 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.
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.
457
138
 
458
- ## Tuning for many concurrent agents
139
+ ## Storage home
459
140
 
460
- 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.
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.
461
142
 
462
- ### Tuning PostgreSQL
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. |
463
147
 
464
- 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).
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.
465
149
 
466
- 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.
150
+ `atomic storage status` never creates a missing agent directory. A read-only agent directory works as long as the storage home is writable.
467
151
 
468
- #### Count the connections Atomic needs
152
+ ## Locks in the agent directory
469
153
 
470
- Each Atomic process opens up to this many connections:
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.
471
155
 
472
- - **An agent process**, including each `atomic --mode rpc` child: `maxConnections` plus `readerMaxConnections`.
473
- - **An Intercom broker**: `maxConnections` plus `readerMaxConnections`, plus 1 for [wake-ups](#wake-ups).
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:
474
157
 
475
- 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.
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.
476
160
 
477
- Find what the server has to share. Run these as an administrator:
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.
478
162
 
479
- ```sql
480
- SHOW max_connections;
481
- SHOW superuser_reserved_connections;
482
- SHOW reserved_connections; -- PostgreSQL 16 and later
483
- SELECT count(*) FROM pg_stat_activity
484
- WHERE backend_type = 'client backend' AND application_name NOT LIKE 'atomic%';
485
- ```
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.
486
164
 
487
- 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`.
165
+ ## Tuning for many concurrent agents
488
166
 
489
- #### Example: 24 processes on a large server
167
+ How many agents can write at once depends on the store:
490
168
 
491
- 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.
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).
492
172
 
493
- - *available* is 500 − 3 − 0 − 20 = 477.
494
- - Each process may use (477 − 4) / 24 = 19.7, rounded down to 19.
495
- - With the default `readerMaxConnections` of 2, set `maxConnections` to 19 − 2 = 17.
173
+ ## Exporting and importing sessions
496
174
 
497
- In `~/.atomic/agent/settings.json` on each machine:
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.
498
176
 
499
- ```json
500
- {
501
- "storage": {
502
- "adapter": "@bastani/atomic-storage-postgres",
503
- "options": {
504
- "url": "postgresql://atomic_runtime@db.example.com:5432/atomic",
505
- "maxConnections": 17,
506
- "readerMaxConnections": 2
507
- },
508
- "secrets": { "password": { "file": "agent/storage-token.3f2a" } }
509
- }
510
- }
177
+ ```bash
178
+ atomic storage export <dir> [--limit <n>] [--since <time>] [--storage <json> | --storage-file <path>]
179
+ atomic storage import <dir> [--storage <json> | --storage-file <path>]
511
180
  ```
512
181
 
513
- The same options in an SDK app:
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.
514
183
 
515
- ```typescript
516
- import { openPostgresDatabase } from "@bastani/atomic-storage-postgres";
184
+ ### Layout
517
185
 
518
- const database = await openPostgresDatabase({
519
- url: "postgresql://atomic_runtime@db.example.com:5432/atomic",
520
- password: process.env.ATOMIC_DB_PASSWORD,
521
- maxConnections: 17,
522
- readerMaxConnections: 2,
523
- });
186
+ ```text
187
+ <dir>/
188
+ sessions/<sessionId>.jsonl one session per file
524
189
  ```
525
190
 
526
- #### Example: 200 machines on a smaller server
527
-
528
- 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.
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.
529
192
 
530
- 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.
531
-
532
- With PgBouncer in transaction mode on port 6432:
193
+ ### Export
533
194
 
534
- - 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.
535
- - 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.
536
- - 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.
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.
537
196
 
538
- ```json
539
- {
540
- "storage": {
541
- "adapter": "@bastani/atomic-storage-postgres",
542
- "options": {
543
- "url": "postgresql://atomic_runtime@pgbouncer.example.com:6432/atomic",
544
- "listenUrl": "postgresql://atomic_runtime@db.example.com:5432/atomic",
545
- "maxConnections": 8
546
- },
547
- "secrets": { "password": { "file": "agent/storage-token.3f2a" } }
548
- }
549
- }
550
- ```
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. |
551
201
 
552
- The same options in an SDK app:
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.
553
203
 
554
- ```typescript
555
- const database = await openPostgresDatabase({
556
- url: "postgresql://atomic_runtime@pgbouncer.example.com:6432/atomic",
557
- listenUrl: "postgresql://atomic_runtime@db.example.com:5432/atomic",
558
- password: process.env.ATOMIC_DB_PASSWORD,
559
- maxConnections: 8,
560
- });
561
- ```
204
+ ### Import
562
205
 
563
- 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.
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.
564
207
 
565
- #### Other settings
208
+ For each session in the files:
566
209
 
567
- Set these in the same `options` object, or pass them to `openPostgresDatabase`. Each takes a positive integer number of milliseconds.
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.
568
213
 
569
- - **Distance.** Saving new entries to a session takes 2 round trips to the server. Put the database in the same region as the agents. A machine 80 ms away from the server spends at least 160 ms on each save.
570
- - **`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.
571
- - **`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.
572
- - **`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.
573
- - **`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.
574
- - **`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. Set it to `0` behind any other pooler that does not keep prepared statements, such as PgBouncer before 1.21 or Supabase's shared pooler. On PgBouncer 1.21 to 1.23, prepared statements work only when PgBouncer's `max_prepared_statements` is above `0`; 1.24 and later set it to 200 by default. Lower the value if the server is short of memory per connection.
214
+ So importing the same directory twice adds nothing, and importing a newer export adds only what changed. Sessions match by ID.
575
215
 
576
- #### Check the effect
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`.
577
217
 
578
- 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`.
218
+ ### Selecting storage for export and import
579
219
 
580
- How many connections Atomic holds, and what they are doing:
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.
581
221
 
582
- ```sql
583
- SELECT application_name, state, count(*)
584
- FROM pg_stat_activity
585
- WHERE datname = 'atomic'
586
- GROUP BY 1, 2
587
- ORDER BY 3 DESC;
588
- ```
222
+ To export from or import into a specific store, including a shared database, name it with `--storage <json>` or `--storage-file <path>`:
589
223
 
590
- What busy connections are waiting for:
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.
591
226
 
592
- ```sql
593
- SELECT wait_event_type, wait_event, count(*)
594
- FROM pg_stat_activity
595
- WHERE datname = 'atomic' AND state <> 'idle'
596
- GROUP BY 1, 2
597
- ORDER BY 3 DESC;
598
- ```
227
+ For example, to copy every session from this machine's local SQLite store into a PostgreSQL database:
599
228
 
600
- How close the server is to its limit:
601
-
602
- ```sql
603
- SELECT count(*) AS used, current_setting('max_connections')::int AS max
604
- FROM pg_stat_activity
605
- WHERE backend_type = 'client backend';
229
+ ```bash
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
234
+ jq .storage ~/.atomic/agent/settings.json > new-storage.json
235
+ atomic storage import ~/moved --storage-file new-storage.json
606
236
  ```
607
237
 
608
- What to change:
609
-
610
- | You see | It means | Change |
611
- | --- | --- | --- |
612
- | `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). |
613
- | `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`. |
614
- | `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. |
615
- | 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. |
616
- | Most `atomic` connections are `idle` and the server is near its limit | Idle processes keep connections open. | Lower `idleTimeoutMs`. |
617
- | `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. |
618
-
619
- 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.
620
-
621
- ### Tuning libSQL and Turso
622
-
623
- 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.
624
-
625
- 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.
238
+ ### Session file format and redaction
626
239
 
627
- 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.
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:
628
241
 
629
242
  ```json
630
- {
631
- "storage": {
632
- "adapter": "@bastani/atomic-storage-libsql",
633
- "options": { "url": "libsql://<db>.turso.io", "concurrency": 50 },
634
- "secrets": { "authToken": { "file": "turso-token" } }
635
- }
636
- }
637
- ```
638
-
639
- The same option in an SDK app:
640
-
641
- ```typescript
642
- import { openLibsqlDatabase } from "@bastani/atomic-storage-libsql";
643
-
644
- const database = await openLibsqlDatabase({
645
- url: "libsql://<db>.turso.io",
646
- authToken: process.env.TURSO_AUTH_TOKEN,
647
- concurrency: 50,
648
- });
243
+ {"type":"session","version":4,"id":"...","createdAt":"2026-11-12T09:30:00.000Z","cwd":"/repo"}
244
+ {"type":"message","id":"a1b2c3d4","parentId":null,"timestamp":"2026-11-12T09:30:05.000Z","message":{"role":"user","content":"..."}}
649
245
  ```
650
246
 
651
- What else helps:
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.
652
248
 
653
- - Keep the database close to the agents, because each request is a round trip.
654
- - 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.
655
- - 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.
656
- - For many agents writing at once from many machines, use [PostgreSQL](#postgresql).
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:
657
250
 
658
- ### Tuning local SQLite
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.
659
254
 
660
- 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).
661
-
662
- ## Exporting and importing sessions
255
+ ### Persisting sessions between CI runs
663
256
 
664
- `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.
257
+ On a CI runner that caches a directory between jobs:
665
258
 
666
259
  ```bash
667
- atomic storage export <dir> [--limit <n>] [--since <time>]
668
- atomic storage import <dir>
669
- ```
260
+ # Start of the job, after the cache restores $STATE_DIR
261
+ mkdir -p "$STATE_DIR" && atomic storage import "$STATE_DIR"
670
262
 
671
- ### Layout
263
+ # ... run Atomic ...
672
264
 
673
- ```text
674
- <dir>/
675
- sessions/<sessionId>.jsonl one session per file
265
+ # End of the job, before the cache saves $STATE_DIR
266
+ atomic storage export "$STATE_DIR"
676
267
  ```
677
268
 
678
- 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.
269
+ Use `--since` or `--limit` to keep the cache small. Continue an imported session with `atomic --session <id>`.
679
270
 
680
- ### Export
271
+ ## Moving off libSQL
681
272
 
682
- Export writes every session by default:
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.
683
274
 
684
- - `--limit <n>` writes only the `n` most recently modified sessions (`n` must be an integer `>= 1` made of ASCII digits).
685
- - `--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.
275
+ Before you start:
686
276
 
687
- 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.
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.
688
281
 
689
- 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.
282
+ 1. **Save the libSQL setting to a file.** It is the top-level `storage` value in `~/.atomic/agent/settings.json`:
690
283
 
691
- ### Import
284
+ ```bash
285
+ jq .storage ~/.atomic/agent/settings.json > old-storage.json
286
+ ```
692
287
 
693
- 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.
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:
694
289
 
695
- - Missing sessions are added.
696
- - Sessions with matching earlier entries receive the file's newer entries.
697
- - Sessions already present in full are skipped.
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
+ ```
698
297
 
699
- 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`.
298
+ 2. **Export the sessions with Atomic 0.10.11-alpha.2:**
700
299
 
701
- 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`.
300
+ ```bash
301
+ npx -y @bastani/atomic@0.10.11-alpha.2 storage export ~/moved --storage-file old-storage.json
302
+ ```
702
303
 
703
- ### Selecting storage for export and import
304
+ It reads only the libSQL database, and prints how many sessions it wrote:
704
305
 
705
- 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.
306
+ ```text
307
+ Exported 4 sessions to /home/me/moved/sessions (4 written, 0 unchanged).
308
+ ```
706
309
 
707
- Pass `--storage <json>` or `--storage-file <path>` to target a specific store explicitly, including a shared database:
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:
708
311
 
709
- - 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.
710
- - JSONL `{ "dir": "..." }` and empty `{}` selections are rejected by `export` and `import --storage`.
312
+ ```bash
313
+ npx -y @bastani/atomic@0.10.11-alpha.2 install npm:@bastani/atomic-storage-libsql@0.10.11-alpha.2
314
+ ```
711
315
 
712
- For example, to migrate sessions from libSQL to PostgreSQL:
316
+ 3. **Import them into their new store.**
713
317
 
714
- ```bash
715
- atomic storage export ~/moved --storage-file old-storage.json
716
- atomic storage join postgres://atomic@db.example.com/atomic --password-file ~/pg-password
717
- jq .storage ~/.atomic/agent/settings.json > new-storage.json
718
- atomic storage import ~/moved --storage-file new-storage.json
719
- ```
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:
720
319
 
721
- ### Session file format and redaction
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
+ ```
722
328
 
723
- 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:
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:
724
330
 
725
- ```json
726
- {"type":"session","version":4,"id":"...","createdAt":"2026-11-12T09:30:00.000Z","cwd":"/repo"}
727
- {"type":"message","id":"a1b2c3d4","parentId":null,"timestamp":"2026-11-12T09:30:05.000Z","message":{"role":"user","content":"..."}}
728
- ```
331
+ ```bash
332
+ atomic storage import ~/moved
333
+ atomic intercom restart
334
+ ```
729
335
 
730
- 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.
336
+ Import prints what it did:
731
337
 
732
- 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:
338
+ ```text
339
+ Imported 4 sessions from /home/me/moved/sessions (4 added, 0 updated, 0 already up to date).
340
+ ```
733
341
 
734
- - Header `type`, `version`, `id`, and `createdAt` (`cwd` determines project assignment).
735
- - Entry `id`, `parentId`, and `type`.
736
- - `base64` values and `blobs` objects, which are hash-verified on import.
342
+ Running it again is safe. It then reports the sessions as `already up to date`.
737
343
 
738
- ### Persisting sessions between CI runs
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.
739
345
 
740
- On a runner that caches a directory across jobs:
346
+ 5. **Remove the libSQL adapter**, which the current release no longer uses:
741
347
 
742
- ```bash
743
- # Start of job, after restoring $STATE_DIR
744
- mkdir -p "$STATE_DIR" && atomic storage import "$STATE_DIR"
348
+ ```bash
349
+ atomic remove npm:@bastani/atomic-storage-libsql
350
+ ```
745
351
 
746
- # ... run Atomic ...
747
-
748
- # End of job, before saving $STATE_DIR
749
- atomic storage export "$STATE_DIR"
750
- ```
352
+ It prints `Removed npm:@bastani/atomic-storage-libsql` when it is done.
751
353
 
752
- Use `--since` or `--limit` to bound cache size. Imported sessions continue with `atomic --session <id>`.
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).`
753
355
 
754
356
  ## Size limits
755
357
 
756
- 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:
757
-
758
- - 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.
759
- - Session search indexes the first 64 KiB (65,536 UTF-16 code units) of each message across all stores.
760
- - Worktree snapshot blobs and session tool-output blobs over 1 MiB split into 1 MiB chunk rows.
761
-
762
- 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`).
763
-
764
- ### Upgrading older SQLite and shared stores
765
-
766
- - **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`.
767
- - **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:
768
-
769
- ```bash
770
- atomic storage move-snapshot-chunks <sqlite-file> [--prefix <prefix>]
771
- ```
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.
772
359
 
773
- 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.
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.
774
361
 
775
- ## Workflow data from earlier releases
362
+ ## Upgrading older stores
776
363
 
777
- 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.
364
+ Some Atomic releases change how a store is laid out, and older releases cannot read the new layout. These changes are one-way:
778
365
 
779
- - `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.
780
- - `atomic storage adopt`, `atomic storage consolidate`, and the `--workflows`, `--run`, and `--unfinished` flags were removed.
781
- - Snapshot garbage collection still respects references held by earlier workflow runs so their blobs are not deleted.
782
- - `ATOMIC_WORKFLOWS_JOURNAL`, `ATOMIC_WORKFLOW_JOURNAL_PATH`, `workflows.journal`, and `createAgentSession({ journal })` no longer select storage.
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).
783
368
 
784
- To run an older workflow definition with this release, see [Migrating workflows](/orchestration/migrating-workflows).
369
+ Upgrade every machine that shares a database at the same time.
785
370
 
786
- ## SDK and local SQLite API
371
+ ### Moving snapshot data in an old SQLite file
787
372
 
788
- 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).
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:
789
374
 
790
- 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:
375
+ 1. Stop every Atomic process that uses the file.
376
+ 2. Run:
791
377
 
792
- ```typescript
793
- import { openNodeSqliteDatabase } from "@bastani/atomic/storage";
378
+ ```bash
379
+ atomic storage move-snapshot-chunks <sqlite-file> [--prefix <prefix>]
380
+ ```
794
381
 
795
- const database = await openNodeSqliteDatabase("./data/example.sqlite");
796
- try {
797
- await database.exec("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, text TEXT)");
798
- await database.transaction(async (transaction) => {
799
- await transaction.run("INSERT INTO notes(text) VALUES (?)", "hello");
800
- });
801
- const notes = await database.all("SELECT id, text FROM notes ORDER BY id");
802
- } finally {
803
- await database.close();
804
- }
805
- ```
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.
806
383
 
807
- ### Query and transaction semantics
384
+ ## Shared-history forks
808
385
 
809
- - `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`.
810
- - 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`.
811
- - 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`).
812
- - `close()` drains accepted work idempotently and rejects subsequent calls with `StoreClosedError`.
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"`.
813
387
 
814
- ### SDK path helpers
388
+ What this means for you:
815
389
 
816
- `@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.
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.
817
393
 
818
- ### Concurrency, options, and diagnostics
394
+ A fork behaves exactly like a copy:
819
395
 
820
- - **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.
821
- - **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.
822
- - **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`.
823
- - **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`.
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.
824
400
 
825
- ## Selecting an adapter
401
+ JSONL directories and in-memory stores always copy.
826
402
 
827
- A storage adapter is a module whose default export satisfies `StorageAdapterModule`:
403
+ ### Older Atomic versions {#older-atomic-versions}
828
404
 
829
- ```typescript
830
- import type { StorageAdapterModule } from "@bastani/atomic/storage";
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:
831
406
 
832
- export default {
833
- atomicStorageAdapter: 1,
834
- async openDatabase(options, context) {
835
- return openMyDatabase({ url: String(options.url), authToken: String(options.authToken) });
836
- },
837
- } satisfies StorageAdapterModule;
407
+ ```text
408
+ Unsupported sessions storage schema version 3: this store needs a newer Atomic. Update Atomic before reopening it.
838
409
  ```
839
410
 
840
- 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.
411
+ When the upgrade happens:
841
412
 
842
- Choose the installation method that matches how you open the adapter:
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.
843
416
 
844
- - **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).
845
- - **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`.
417
+ What to do:
846
418
 
847
- 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`.
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.
848
421
 
849
- `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`).
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.
850
423
 
851
- `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`.
424
+ ## Workflow data from earlier releases
852
425
 
853
- Adapter hooks and lifecycle:
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.
854
427
 
855
- - Implement `openDatabase(options, context): Promise<SqliteDatabase>` for SQL-backed adapters so Atomic manages schemas, prefixes, and Intercom tables.
856
- - Implement `openSessionStore(options, context, { prefix? })` for non-SQL session stores. When both hooks exist, `openSessionStore` takes priority for sessions.
857
- - Missing hooks raise `StorageConfigError` (`reason: "adapter-domain-unsupported"`). Load failures raise `StorageAdapterLoadError`, and driver open failures raise `StorageUnavailableError`.
858
- - `new StorageProvider().openSessionStore(selection, context)` opens stores programmatically (`kind`: `"memory"`, `"jsonl"`, `"sqlite"`, `"database"`, or `"adapter"`). `loadStorageAdapter(module, context, hostModules)` loads an adapter module.
859
- - `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.
860
- - 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.
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.
861
432
 
862
- ### Adapters from Atomic packages
433
+ To run an older workflow definition with this release, see [Migrating workflows](/orchestration/migrating-workflows).
863
434
 
864
- An [Atomic package](/packages) can bundle storage adapters and their driver dependencies by listing adapter paths under `atomic.storageAdapters` in `package.json`:
435
+ ## Storage errors
865
436
 
866
- ```json
867
- {
868
- "name": "@example/atomic-libsql",
869
- "dependencies": { "@libsql/client": "0.18.0" },
870
- "peerDependencies": { "@bastani/atomic": "*" },
871
- "atomic": { "storageAdapters": ["./libsql-adapter.ts"] }
872
- }
873
- ```
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`.
874
438
 
875
- Install the package with `atomic install npm:@example/atomic-libsql` and select it by package name:
439
+ ### Common errors
876
440
 
877
- ```json
878
- {
879
- "storage": {
880
- "adapter": "@example/atomic-libsql",
881
- "options": { "url": "libsql://team.example" },
882
- "secrets": { "authToken": { "file": "turso-token" } }
883
- }
884
- }
885
- ```
441
+ | Error | What it means | What to do |
442
+ | --- | --- | --- |
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. |
886
464
 
887
- 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`).
888
-
889
- 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>"`.
890
-
891
- Atomic resolves adapter package names in this order:
892
-
893
- 1. Extension package directories passed to the process (or inherited from the launching Atomic process).
894
- 2. Packages in effective global settings (including legacy `~/.pi/agent/settings.json` for the default agent directory). Project packages are not searched.
895
- 3. Module resolution from the agent directory.
896
-
897
- 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.
898
-
899
- ## Bring your own driver
900
-
901
- To wrap a SQLite-compatible driver into a `SqliteDatabase`, call `createSqliteDatabase` from `@bastani/atomic/storage` with these driver hooks:
902
-
903
- - `descriptor` provides `{ adapter, location }` for diagnostics (redacted through `redact`).
904
- - `execute(sql, params)` runs one parameterized statement and returns `{ columns, rows, changes }`. Return integers as `bigint` to preserve 64-bit precision.
905
- - `executeMultiple(sql)` runs zero or more unparameterized statements.
906
- - `beginTransaction()` starts a write transaction and returns `{ execute, executeMultiple, commit, rollback, close? }`.
907
- - `close()` releases the driver connection.
908
- - `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.
909
- - `redact(text)` (optional) strips credentials from error text. Use `redactSecrets(secrets)` to build one that removes raw, URI-encoded, and decoded forms.
910
- - `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.
911
- - `freeBytes()` (optional) returns writable free bytes on the filesystem holding a local database file, or `undefined`.
912
- - `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.
913
- - `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.
914
- - `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.
915
- - `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.
916
- - 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.
917
- - A statement whose connection broke after the commit was sent reports `outcome: "unknown"`, because the commit may have applied.
918
- - `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.
919
- - `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.
920
- - 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.
921
-
922
- 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`.
923
-
924
- Transient retry and queue bounds:
925
-
926
- - 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.
927
- - 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.
928
- - 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.
929
- - 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.
930
- - 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).
931
-
932
- You can also implement `SqliteDatabase` directly. In either case, verify your implementation with the [conformance suite](#adapter-conformance).
933
-
934
- ### Custom driver adapter example
935
-
936
- 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:
937
-
938
- ```typescript
939
- import { createClient, type Client, type Transaction } from "@libsql/client";
940
- import {
941
- createSqliteDatabase,
942
- redactSecrets,
943
- type SqliteDatabase,
944
- type SqliteDriverExecutor,
945
- type StorageAdapterModule,
946
- } from "@bastani/atomic/storage";
947
-
948
- export interface CustomDriverOptions {
949
- url: string;
950
- authToken?: string;
951
- }
952
-
953
- function executor(connection: () => Client | Transaction): SqliteDriverExecutor {
954
- return {
955
- async execute(sql, params) {
956
- const result = await connection().execute({ sql, args: [...params] });
957
- return { columns: result.columns, rows: result.rows, changes: result.rowsAffected };
958
- },
959
- executeMultiple: (sql) => connection().executeMultiple(sql),
960
- };
961
- }
962
-
963
- export async function openCustomDatabase({ url, authToken }: CustomDriverOptions): Promise<SqliteDatabase> {
964
- let client: Client | undefined;
965
- const connection = () => (client ??= createClient({ url, authToken, intMode: "bigint" }));
966
- const database = createSqliteDatabase({
967
- descriptor: { adapter: "custom-libsql", location: url },
968
- redact: redactSecrets(authToken ? [authToken] : []),
969
- ...executor(connection),
970
- async beginTransaction() {
971
- const tx = await connection().transaction("write");
972
- return {
973
- ...executor(() => tx),
974
- commit: () => tx.commit(),
975
- rollback: () => tx.rollback(),
976
- close: () => tx.close(),
977
- };
978
- },
979
- async close() {
980
- client?.close();
981
- },
982
- });
983
- await database.exec("PRAGMA foreign_keys = ON");
984
- return database;
985
- }
986
-
987
- export default {
988
- atomicStorageAdapter: 1,
989
- openDatabase: (options) =>
990
- openCustomDatabase({
991
- url: String(options.url),
992
- authToken: typeof options.authToken === "string" ? options.authToken : undefined,
993
- }),
994
- } satisfies StorageAdapterModule;
995
- ```
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.
996
466
 
997
- 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`:
998
-
999
- ```typescript
1000
- import { openCustomDatabase } from "./custom-adapter.js";
1001
-
1002
- const database = await openCustomDatabase({
1003
- url: "libsql://your-database.turso.io",
1004
- authToken: process.env.TURSO_TOKEN,
1005
- });
1006
- try {
1007
- const { session } = await createAgentSession({
1008
- sessionStore: { kind: "database", database, prefix: "project_" },
1009
- });
1010
- await session.prompt("List the failing tests");
1011
- } finally {
1012
- await database.close();
1013
- }
1014
- ```
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.
1015
468
 
1016
- Multiple stores can share one caller-owned `database` without closing it.
469
+ ### Database handle errors
1017
470
 
1018
- ### Custom `SessionStore` contracts
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).
1019
472
 
1020
- Non-SQL backends can implement `openSessionStore` directly (each session has one writer):
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. |
1021
482
 
1022
- - **Required for `history://`.** Implement `readEntryRange(id, query)` honoring `fromSeq`, `toSeq`, `maxChars`, `largeEntryBytes`, `skipTypes`, and `signal`. Return freshly owned UTF-8 JSON buffers and `{ entries: [{ seq, entry }], throughSeq, lastSeq }` without falling back to whole-session `load()`.
1023
- - **Optional fast-path methods.** Implementing these avoids loading entire sessions into memory (stores implementing only `load()` still work with higher memory use):
483
+ ### Handling errors in code
1024
484
 
1025
- | Method | Purpose |
1026
- | --- | --- |
1027
- | `readTail(id, fromSeq)` | Header and entries from `fromSeq`, plus earlier live state and omitted usage totals |
1028
- | `readRange(id, startSeq, endSeq)` | Inclusive 1-based range with `seqs`, `lastSeq`, and `epoch` |
1029
- | `findLatestCompaction(id, leafId?)` | Latest active compaction boundary, sequence, and retained start |
1030
- | `readResume(id, leafId?)` | Atomic resume snapshot (header, active branch from compaction, live state, omitted totals, `deliveryOpIds`, `lastSeq`, `lastEntryId`, `leafId`, `epoch`) |
1031
- | `findEntrySeq(id, entryId)` | 1-based entry sequence, or `undefined` |
1032
- | `readEntrySizes` / `readEntryChunk` / `readScanPage` | Byte-bounded streaming exports and remote page reads |
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`.
1033
489
 
1034
- - **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.
1035
- - **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)).
490
+ ### Errors from `atomic storage join` {#team-setup-errors}
1036
491
 
1037
- ## Storage errors
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.
1038
493
 
1039
- Branch on error classes, `code`, and typed fields rather than message text. Configuration and facade errors are exported from `@bastani/atomic/storage`.
1040
-
1041
- | Error | Fields and response |
1042
- | --- | --- |
1043
- | `StorageConfigError` | `code: "invalid-config"`, `source`, `field`, `reason`, optional `hint`. Fix the selected option; Atomic does not fall back to a lower-precedence store. |
1044
- | `StorageAdapterLoadError` | `module`, `cause`. Check package installation and the module's default export. |
1045
- | `StorageUnavailableError` | `adapter`, `location`, `cause`. Restore access to the selected store before retrying. |
1046
- | `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). |
1047
- | `StorageSchemaVersionError` | `domain`, `found`, `supported`. Upgrade Atomic or use a supported database schema. |
1048
- | `StoreClosedError` / `StorageTransactionClosedError` | The store is closed or the transaction callback has finished. Open a new store or use the active callback handle. |
1049
- | `StorageRollbackError` | `cause`, `rollbackCause`. Do not assume the transaction rolled back. |
1050
- | `StorageOutcomeUnknownError` | `domain`, `id`, `key`. The driver could not confirm the write; inspect the keyed record before retrying. |
1051
- | `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). |
1052
- | `StorageInvalidTextError` | `parameterIndex`, `reason`. Remove U+0000 from scalar text bindings or encode as JSON or binary. |
1053
- | `TeamProfileConfigError` | Subclass of `StorageConfigError` for invalid team inputs (`code` equals `reason`). See [Team setup errors](#team-setup-errors). |
1054
- | `TeamProfileError` | Team setup operation failed after inputs passed validation. See [Team setup errors](#team-setup-errors). |
1055
-
1056
- Coded storage errors carry a stable `code` and actionable `hint`:
1057
-
1058
- | Class | Code | When | Key fields | What to do |
1059
- | --- | --- | --- | --- | --- |
1060
- | `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. |
1061
- | `StorageUnsupportedOperationError` | `unsupported-operation` | `getWriterQueueStats` or `getWriterQueueDegradation` received a non-node-sqlite handle. | `operation`, `adapter`, `location` | Pass a handle from `openNodeSqliteDatabase` or `wrapNodeSqliteDatabase`. |
1062
- | `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. |
1063
- | `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. |
1064
- | `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. |
1065
- | `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. |
1066
- | `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. |
1067
- | `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. |
1068
- | `SessionBlobError` | `blob-corrupt` | Imported tool output failed its SHA-256 check. Nothing was written. | `sessionId`, `hash`, `actualHash` | Export the session again from its source. |
1069
- | `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. |
1070
- | `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. |
1071
- | `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. |
1072
- | `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. |
1073
-
1074
- ### Error guards, serialization, and session persistence errors
1075
-
1076
- - **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`.
1077
- - **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.
1078
- - **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.
1079
- - **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.
1080
- - **Abort signals.** Session listings accept an `AbortSignal` and reject with the original `signal.reason` unwrapped (`AbortError` for bare `controller.abort()`).
1081
-
1082
- ### Team setup errors
1083
-
1084
- `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.
1085
-
1086
- `TeamProfileConfigError` extends `StorageConfigError` (`source`: `"sdk"`, `"cli"`, or `"env"`, `field`, `code`, `reason`, `hint`, optional `path` and `missing`, `retryable: false`). Nothing changes when it is thrown:
1087
-
1088
- | Code | When |
494
+ | `TeamProfileConfigError` code | When |
1089
495
  | --- | --- |
1090
- | `unknown-profile` | `ATOMIC_PROFILE` or SDK `profile` is not `ci` |
1091
- | `incomplete-profile` | A team variable is set without `ATOMIC_PROFILE`, or `ATOMIC_PROFILE=ci` lacks a URL or token (`missing` lists all missing variables) |
1092
- | `missing-url` | No database URL was passed |
1093
- | `unsupported-url` | URL is not `libsql://`, `https://`, `http://`, `wss://`, `ws://`, or `file:` |
1094
- | `relative-file-url` | A `file:` URL is relative |
1095
- | `credential-in-url` | URL contains a username, password, or `authToken` |
1096
- | `missing-token` | Non-`file:` URL has no token, or `tokenEnv` names an unset variable |
1097
- | `conflicting-token` | More than one token source was passed |
1098
- | `unreadable-token-file` | Token file cannot be read (`path` names it) |
1099
- | `relative-token-file` | `ATOMIC_TEAM_TOKEN_FILE` is relative instead of absolute |
1100
- | `empty-token` | Token, token file, or `tokenEnv` name is empty |
1101
- | `invalid-prefix` | Prefix breaks storage prefix rules |
1102
- | `unknown-command`, `unknown-option`, `missing-value`, `unexpected-argument` | Invalid `atomic team` CLI arguments |
1103
-
1104
- `TeamProfileError` (`code`, `subject`, `hint`, optional `detail` and `cause`, `retryable`):
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`.
1105
508
 
1106
509
  | Code | When | What to do |
1107
510
  | --- | --- | --- |
1108
- | `settings-unreadable` | Settings file cannot be read or parsed (`subject` names it). Nothing changed. | Fix the settings file and rerun. |
1109
- | `adapter-not-installed` | libSQL adapter cannot load. Nothing changed. | Run `atomic install npm:@bastani/atomic-storage-libsql`. |
1110
- | `connection-failed` | Database refused or failed `SELECT 1` (`retryable: true`). Nothing changed. | Check URL, token, and network, then retry. |
1111
- | `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. |
1112
- | `token-write-failed` | Private token file could not be written. Nothing changed. | Make the agent directory writable. |
1113
- | `settings-write-failed` | Settings could not be written (previous selection and token are kept). | Make the settings file writable or free disk space. |
1114
- | `settings-locked` | Another process held the settings lock (`retryable: true`). Nothing changed. | Retry in a few seconds; stale locks expire after 10 seconds. |
1115
- | `broker-restart-failed` | Returned in `broker`, not thrown: settings saved, but Intercom broker failed to restart (`retryable: true`). | Run `atomic intercom restart`. |
1116
- | `token-delete-failed` | `leaveTeam` removed settings, but could not delete the token file. | Delete the file manually. |
1117
-
1118
- `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`).
1119
-
1120
- ## Adapter conformance
1121
-
1122
- Validate any `SqliteDatabase` adapter against the conformance suites exported from `@bastani/atomic/storage/testing`:
1123
-
1124
- ```typescript
1125
- import {
1126
- registerSqliteConnectionConformance,
1127
- registerSqliteDatabaseConformance,
1128
- } from "@bastani/atomic/storage/testing";
1129
-
1130
- // Pass your test runner's `describe` and `it` functions.
1131
- registerSqliteDatabaseConformance({ describe, it }, "my adapter", withSubject);
1132
- registerSqliteConnectionConformance({ describe, it }, "my adapter connections", withConnections);
1133
- ```
1134
-
1135
- - `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.
1136
- - `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.
1137
-
1138
- Helper utilities exported from `@bastani/atomic/storage` for custom adapters:
1139
-
1140
- - `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).
1141
- - `renderStorageIdentifiers("sessions", names, prefix)` returns a frozen map of table names with the `session_` prefix applied.
1142
- - `assertStorageSchemaVersion(domain, found, supported)` throws `StorageSchemaVersionError` when stored and supported versions differ.
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>`.