@diffra-ai/durable 0.0.0-stage → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (411) hide show
  1. package/CHANGELOG.md +440 -0
  2. package/README.md +1153 -2
  3. package/dist/codemode/codemode.d.ts +174 -0
  4. package/dist/codemode/codemode.d.ts.map +1 -0
  5. package/dist/codemode/codemode.js +884 -0
  6. package/dist/codemode/codemode.js.map +1 -0
  7. package/dist/codemode/describe.d.ts +38 -0
  8. package/dist/codemode/describe.d.ts.map +1 -0
  9. package/dist/codemode/describe.js +127 -0
  10. package/dist/codemode/describe.js.map +1 -0
  11. package/dist/codemode/index.d.ts +3 -0
  12. package/dist/codemode/index.d.ts.map +1 -0
  13. package/dist/codemode/index.js +3 -0
  14. package/dist/codemode/index.js.map +1 -0
  15. package/dist/codemode/models.d.ts +29 -0
  16. package/dist/codemode/models.d.ts.map +1 -0
  17. package/dist/codemode/models.js +242 -0
  18. package/dist/codemode/models.js.map +1 -0
  19. package/dist/codemode/output.d.ts +43 -0
  20. package/dist/codemode/output.d.ts.map +1 -0
  21. package/dist/codemode/output.js +168 -0
  22. package/dist/codemode/output.js.map +1 -0
  23. package/dist/documents.d.ts +66 -0
  24. package/dist/documents.d.ts.map +1 -0
  25. package/dist/documents.js +98 -0
  26. package/dist/documents.js.map +1 -0
  27. package/dist/entries.d.ts +31 -0
  28. package/dist/entries.d.ts.map +1 -0
  29. package/dist/entries.js +31 -0
  30. package/dist/entries.js.map +1 -0
  31. package/dist/env/decode.d.ts +16 -0
  32. package/dist/env/decode.d.ts.map +1 -0
  33. package/dist/env/decode.js +28 -0
  34. package/dist/env/decode.js.map +1 -0
  35. package/dist/env/index.d.ts +308 -0
  36. package/dist/env/index.d.ts.map +1 -0
  37. package/dist/env/index.js +49 -0
  38. package/dist/env/index.js.map +1 -0
  39. package/dist/env/line-scan.d.ts +13 -0
  40. package/dist/env/line-scan.d.ts.map +1 -0
  41. package/dist/env/line-scan.js +147 -0
  42. package/dist/env/line-scan.js.map +1 -0
  43. package/dist/env/node-watch.d.ts +29 -0
  44. package/dist/env/node-watch.d.ts.map +1 -0
  45. package/dist/env/node-watch.js +487 -0
  46. package/dist/env/node-watch.js.map +1 -0
  47. package/dist/env/node.d.ts +56 -0
  48. package/dist/env/node.d.ts.map +1 -0
  49. package/dist/env/node.js +1185 -0
  50. package/dist/env/node.js.map +1 -0
  51. package/dist/errors.d.ts +48 -0
  52. package/dist/errors.d.ts.map +1 -0
  53. package/dist/errors.js +76 -0
  54. package/dist/errors.js.map +1 -0
  55. package/dist/harness/agent.d.ts +46 -0
  56. package/dist/harness/agent.d.ts.map +1 -0
  57. package/dist/harness/agent.js +334 -0
  58. package/dist/harness/agent.js.map +1 -0
  59. package/dist/harness/compaction.d.ts +68 -0
  60. package/dist/harness/compaction.d.ts.map +1 -0
  61. package/dist/harness/compaction.js +431 -0
  62. package/dist/harness/compaction.js.map +1 -0
  63. package/dist/harness/context.d.ts +84 -0
  64. package/dist/harness/context.d.ts.map +1 -0
  65. package/dist/harness/context.js +301 -0
  66. package/dist/harness/context.js.map +1 -0
  67. package/dist/harness/define.d.ts +25 -0
  68. package/dist/harness/define.d.ts.map +1 -0
  69. package/dist/harness/define.js +32 -0
  70. package/dist/harness/define.js.map +1 -0
  71. package/dist/harness/generation.d.ts +117 -0
  72. package/dist/harness/generation.d.ts.map +1 -0
  73. package/dist/harness/generation.js +1098 -0
  74. package/dist/harness/generation.js.map +1 -0
  75. package/dist/harness/harness.d.ts +22 -0
  76. package/dist/harness/harness.d.ts.map +1 -0
  77. package/dist/harness/harness.js +438 -0
  78. package/dist/harness/harness.js.map +1 -0
  79. package/dist/harness/inbox.d.ts +84 -0
  80. package/dist/harness/inbox.d.ts.map +1 -0
  81. package/dist/harness/inbox.js +135 -0
  82. package/dist/harness/inbox.js.map +1 -0
  83. package/dist/harness/json.d.ts +26 -0
  84. package/dist/harness/json.d.ts.map +1 -0
  85. package/dist/harness/json.js +51 -0
  86. package/dist/harness/json.js.map +1 -0
  87. package/dist/harness/live.d.ts +285 -0
  88. package/dist/harness/live.d.ts.map +1 -0
  89. package/dist/harness/live.js +257 -0
  90. package/dist/harness/live.js.map +1 -0
  91. package/dist/harness/parks.d.ts +23 -0
  92. package/dist/harness/parks.d.ts.map +1 -0
  93. package/dist/harness/parks.js +52 -0
  94. package/dist/harness/parks.js.map +1 -0
  95. package/dist/harness/partial-changes.d.ts +54 -0
  96. package/dist/harness/partial-changes.d.ts.map +1 -0
  97. package/dist/harness/partial-changes.js +163 -0
  98. package/dist/harness/partial-changes.js.map +1 -0
  99. package/dist/harness/prompt.d.ts +27 -0
  100. package/dist/harness/prompt.d.ts.map +1 -0
  101. package/dist/harness/prompt.js +131 -0
  102. package/dist/harness/prompt.js.map +1 -0
  103. package/dist/harness/provider.d.ts +16 -0
  104. package/dist/harness/provider.d.ts.map +1 -0
  105. package/dist/harness/provider.js +33 -0
  106. package/dist/harness/provider.js.map +1 -0
  107. package/dist/harness/registry-reader.d.ts +11 -0
  108. package/dist/harness/registry-reader.d.ts.map +1 -0
  109. package/dist/harness/registry-reader.js +25 -0
  110. package/dist/harness/registry-reader.js.map +1 -0
  111. package/dist/harness/registry.d.ts +6 -0
  112. package/dist/harness/registry.d.ts.map +1 -0
  113. package/dist/harness/registry.js +101 -0
  114. package/dist/harness/registry.js.map +1 -0
  115. package/dist/harness/scheduler.d.ts +195 -0
  116. package/dist/harness/scheduler.d.ts.map +1 -0
  117. package/dist/harness/scheduler.js +3073 -0
  118. package/dist/harness/scheduler.js.map +1 -0
  119. package/dist/harness/submissions.d.ts +44 -0
  120. package/dist/harness/submissions.d.ts.map +1 -0
  121. package/dist/harness/submissions.js +265 -0
  122. package/dist/harness/submissions.js.map +1 -0
  123. package/dist/harness/task-graph.d.ts +75 -0
  124. package/dist/harness/task-graph.d.ts.map +1 -0
  125. package/dist/harness/task-graph.js +224 -0
  126. package/dist/harness/task-graph.js.map +1 -0
  127. package/dist/harness/telemetry.d.ts +307 -0
  128. package/dist/harness/telemetry.d.ts.map +1 -0
  129. package/dist/harness/telemetry.js +140 -0
  130. package/dist/harness/telemetry.js.map +1 -0
  131. package/dist/harness/tool.d.ts +106 -0
  132. package/dist/harness/tool.d.ts.map +1 -0
  133. package/dist/harness/tool.js +1182 -0
  134. package/dist/harness/tool.js.map +1 -0
  135. package/dist/harness/transcript.d.ts +72 -0
  136. package/dist/harness/transcript.d.ts.map +1 -0
  137. package/dist/harness/transcript.js +264 -0
  138. package/dist/harness/transcript.js.map +1 -0
  139. package/dist/harness/types.d.ts +1146 -0
  140. package/dist/harness/types.d.ts.map +1 -0
  141. package/dist/harness/types.js +2 -0
  142. package/dist/harness/types.js.map +1 -0
  143. package/dist/harness/usage.d.ts +19 -0
  144. package/dist/harness/usage.d.ts.map +1 -0
  145. package/dist/harness/usage.js +57 -0
  146. package/dist/harness/usage.js.map +1 -0
  147. package/dist/harness/util.d.ts +25 -0
  148. package/dist/harness/util.d.ts.map +1 -0
  149. package/dist/harness/util.js +76 -0
  150. package/dist/harness/util.js.map +1 -0
  151. package/dist/harness/view.d.ts +69 -0
  152. package/dist/harness/view.d.ts.map +1 -0
  153. package/dist/harness/view.js +265 -0
  154. package/dist/harness/view.js.map +1 -0
  155. package/dist/ids.d.ts +6 -0
  156. package/dist/ids.d.ts.map +1 -0
  157. package/dist/ids.js +9 -0
  158. package/dist/ids.js.map +1 -0
  159. package/dist/images/cloudflare.d.ts +4 -0
  160. package/dist/images/cloudflare.d.ts.map +1 -0
  161. package/dist/images/cloudflare.js +9 -0
  162. package/dist/images/cloudflare.js.map +1 -0
  163. package/dist/images/exif.d.ts +3 -0
  164. package/dist/images/exif.d.ts.map +1 -0
  165. package/dist/images/exif.js +71 -0
  166. package/dist/images/exif.js.map +1 -0
  167. package/dist/images/fit.d.ts +41 -0
  168. package/dist/images/fit.d.ts.map +1 -0
  169. package/dist/images/fit.js +108 -0
  170. package/dist/images/fit.js.map +1 -0
  171. package/dist/images/index.d.ts +18 -0
  172. package/dist/images/index.d.ts.map +1 -0
  173. package/dist/images/index.js +125 -0
  174. package/dist/images/index.js.map +1 -0
  175. package/dist/images/node-worker.d.ts +19 -0
  176. package/dist/images/node-worker.d.ts.map +1 -0
  177. package/dist/images/node-worker.js +17 -0
  178. package/dist/images/node-worker.js.map +1 -0
  179. package/dist/images/node.d.ts +21 -0
  180. package/dist/images/node.d.ts.map +1 -0
  181. package/dist/images/node.js +121 -0
  182. package/dist/images/node.js.map +1 -0
  183. package/dist/index.d.ts +29 -0
  184. package/dist/index.d.ts.map +1 -0
  185. package/dist/index.js +23 -0
  186. package/dist/index.js.map +1 -0
  187. package/dist/search.d.ts +29 -0
  188. package/dist/search.d.ts.map +1 -0
  189. package/dist/search.js +148 -0
  190. package/dist/search.js.map +1 -0
  191. package/dist/session/cached-storage.d.ts +72 -0
  192. package/dist/session/cached-storage.d.ts.map +1 -0
  193. package/dist/session/cached-storage.js +269 -0
  194. package/dist/session/cached-storage.js.map +1 -0
  195. package/dist/session/conversation-tails.d.ts +33 -0
  196. package/dist/session/conversation-tails.d.ts.map +1 -0
  197. package/dist/session/conversation-tails.js +101 -0
  198. package/dist/session/conversation-tails.js.map +1 -0
  199. package/dist/session/forks.d.ts +10 -0
  200. package/dist/session/forks.d.ts.map +1 -0
  201. package/dist/session/forks.js +42 -0
  202. package/dist/session/forks.js.map +1 -0
  203. package/dist/session/keys.d.ts +69 -0
  204. package/dist/session/keys.d.ts.map +1 -0
  205. package/dist/session/keys.js +161 -0
  206. package/dist/session/keys.js.map +1 -0
  207. package/dist/session/session.d.ts +287 -0
  208. package/dist/session/session.d.ts.map +1 -0
  209. package/dist/session/session.js +1701 -0
  210. package/dist/session/session.js.map +1 -0
  211. package/dist/session/transaction.d.ts +205 -0
  212. package/dist/session/transaction.d.ts.map +1 -0
  213. package/dist/session/transaction.js +1059 -0
  214. package/dist/session/transaction.js.map +1 -0
  215. package/dist/session/writer.d.ts +74 -0
  216. package/dist/session/writer.d.ts.map +1 -0
  217. package/dist/session/writer.js +294 -0
  218. package/dist/session/writer.js.map +1 -0
  219. package/dist/signals.d.ts +180 -0
  220. package/dist/signals.d.ts.map +1 -0
  221. package/dist/signals.js +236 -0
  222. package/dist/signals.js.map +1 -0
  223. package/dist/storage/indexeddb.d.ts +69 -0
  224. package/dist/storage/indexeddb.d.ts.map +1 -0
  225. package/dist/storage/indexeddb.js +883 -0
  226. package/dist/storage/indexeddb.js.map +1 -0
  227. package/dist/storage/jsonl/index.d.ts +2 -0
  228. package/dist/storage/jsonl/index.d.ts.map +1 -0
  229. package/dist/storage/jsonl/index.js +2 -0
  230. package/dist/storage/jsonl/index.js.map +1 -0
  231. package/dist/storage/jsonl/node.d.ts +6 -0
  232. package/dist/storage/jsonl/node.d.ts.map +1 -0
  233. package/dist/storage/jsonl/node.js +8 -0
  234. package/dist/storage/jsonl/node.js.map +1 -0
  235. package/dist/storage/jsonl/storage.d.ts +206 -0
  236. package/dist/storage/jsonl/storage.d.ts.map +1 -0
  237. package/dist/storage/jsonl/storage.js +799 -0
  238. package/dist/storage/jsonl/storage.js.map +1 -0
  239. package/dist/storage/memory.d.ts +68 -0
  240. package/dist/storage/memory.d.ts.map +1 -0
  241. package/dist/storage/memory.js +761 -0
  242. package/dist/storage/memory.js.map +1 -0
  243. package/dist/storage/scan.d.ts +18 -0
  244. package/dist/storage/scan.d.ts.map +1 -0
  245. package/dist/storage/scan.js +29 -0
  246. package/dist/storage/scan.js.map +1 -0
  247. package/dist/storage/sqlite/cloudflare.d.ts +9 -0
  248. package/dist/storage/sqlite/cloudflare.d.ts.map +1 -0
  249. package/dist/storage/sqlite/cloudflare.js +11 -0
  250. package/dist/storage/sqlite/cloudflare.js.map +1 -0
  251. package/dist/storage/sqlite/commit.d.ts +52 -0
  252. package/dist/storage/sqlite/commit.d.ts.map +1 -0
  253. package/dist/storage/sqlite/commit.js +371 -0
  254. package/dist/storage/sqlite/commit.js.map +1 -0
  255. package/dist/storage/sqlite/database.d.ts +2 -0
  256. package/dist/storage/sqlite/database.d.ts.map +1 -0
  257. package/dist/storage/sqlite/database.js +2 -0
  258. package/dist/storage/sqlite/database.js.map +1 -0
  259. package/dist/storage/sqlite/index.d.ts +4 -0
  260. package/dist/storage/sqlite/index.d.ts.map +1 -0
  261. package/dist/storage/sqlite/index.js +3 -0
  262. package/dist/storage/sqlite/index.js.map +1 -0
  263. package/dist/storage/sqlite/migrations.d.ts +12 -0
  264. package/dist/storage/sqlite/migrations.d.ts.map +1 -0
  265. package/dist/storage/sqlite/migrations.js +121 -0
  266. package/dist/storage/sqlite/migrations.js.map +1 -0
  267. package/dist/storage/sqlite/node.d.ts +8 -0
  268. package/dist/storage/sqlite/node.d.ts.map +1 -0
  269. package/dist/storage/sqlite/node.js +12 -0
  270. package/dist/storage/sqlite/node.js.map +1 -0
  271. package/dist/storage/sqlite/rows.d.ts +33 -0
  272. package/dist/storage/sqlite/rows.d.ts.map +1 -0
  273. package/dist/storage/sqlite/rows.js +53 -0
  274. package/dist/storage/sqlite/rows.js.map +1 -0
  275. package/dist/storage/sqlite/schema.d.ts +45 -0
  276. package/dist/storage/sqlite/schema.d.ts.map +1 -0
  277. package/dist/storage/sqlite/schema.js +50 -0
  278. package/dist/storage/sqlite/schema.js.map +1 -0
  279. package/dist/storage/sqlite/statements.d.ts +13 -0
  280. package/dist/storage/sqlite/statements.d.ts.map +1 -0
  281. package/dist/storage/sqlite/statements.js +88 -0
  282. package/dist/storage/sqlite/statements.js.map +1 -0
  283. package/dist/storage/sqlite/storage.d.ts +86 -0
  284. package/dist/storage/sqlite/storage.d.ts.map +1 -0
  285. package/dist/storage/sqlite/storage.js +534 -0
  286. package/dist/storage/sqlite/storage.js.map +1 -0
  287. package/dist/storage/store/commit.d.ts +33 -0
  288. package/dist/storage/store/commit.d.ts.map +1 -0
  289. package/dist/storage/store/commit.js +286 -0
  290. package/dist/storage/store/commit.js.map +1 -0
  291. package/dist/storage/store/documents.d.ts +43 -0
  292. package/dist/storage/store/documents.d.ts.map +1 -0
  293. package/dist/storage/store/documents.js +102 -0
  294. package/dist/storage/store/documents.js.map +1 -0
  295. package/dist/storage/store/index.d.ts +2 -0
  296. package/dist/storage/store/index.d.ts.map +1 -0
  297. package/dist/storage/store/index.js +2 -0
  298. package/dist/storage/store/index.js.map +1 -0
  299. package/dist/storage/store/queries.d.ts +49 -0
  300. package/dist/storage/store/queries.d.ts.map +1 -0
  301. package/dist/storage/store/queries.js +93 -0
  302. package/dist/storage/store/queries.js.map +1 -0
  303. package/dist/storage/store/storage.d.ts +60 -0
  304. package/dist/storage/store/storage.d.ts.map +1 -0
  305. package/dist/storage/store/storage.js +438 -0
  306. package/dist/storage/store/storage.js.map +1 -0
  307. package/dist/storage/store/tables.d.ts +54 -0
  308. package/dist/storage/store/tables.d.ts.map +1 -0
  309. package/dist/storage/store/tables.js +108 -0
  310. package/dist/storage/store/tables.js.map +1 -0
  311. package/dist/tasks.d.ts +6 -0
  312. package/dist/tasks.d.ts.map +1 -0
  313. package/dist/tasks.js +5 -0
  314. package/dist/tasks.js.map +1 -0
  315. package/dist/testing/assertions.d.ts +5 -0
  316. package/dist/testing/assertions.d.ts.map +1 -0
  317. package/dist/testing/assertions.js +25 -0
  318. package/dist/testing/assertions.js.map +1 -0
  319. package/dist/testing/commit-writes.d.ts +5 -0
  320. package/dist/testing/commit-writes.d.ts.map +1 -0
  321. package/dist/testing/commit-writes.js +12 -0
  322. package/dist/testing/commit-writes.js.map +1 -0
  323. package/dist/testing/env-conformance.d.ts +7 -0
  324. package/dist/testing/env-conformance.d.ts.map +1 -0
  325. package/dist/testing/env-conformance.js +531 -0
  326. package/dist/testing/env-conformance.js.map +1 -0
  327. package/dist/testing/index.d.ts +8 -0
  328. package/dist/testing/index.d.ts.map +1 -0
  329. package/dist/testing/index.js +7 -0
  330. package/dist/testing/index.js.map +1 -0
  331. package/dist/testing/runner.d.ts +12 -0
  332. package/dist/testing/runner.d.ts.map +1 -0
  333. package/dist/testing/runner.js +23 -0
  334. package/dist/testing/runner.js.map +1 -0
  335. package/dist/testing/storage-benchmark.d.ts +41 -0
  336. package/dist/testing/storage-benchmark.d.ts.map +1 -0
  337. package/dist/testing/storage-benchmark.js +351 -0
  338. package/dist/testing/storage-benchmark.js.map +1 -0
  339. package/dist/testing/storage-conformance.d.ts +4 -0
  340. package/dist/testing/storage-conformance.d.ts.map +1 -0
  341. package/dist/testing/storage-conformance.js +1554 -0
  342. package/dist/testing/storage-conformance.js.map +1 -0
  343. package/dist/testing/types.d.ts +39 -0
  344. package/dist/testing/types.d.ts.map +1 -0
  345. package/dist/testing/types.js +2 -0
  346. package/dist/testing/types.js.map +1 -0
  347. package/dist/timers.d.ts +21 -0
  348. package/dist/timers.d.ts.map +1 -0
  349. package/dist/timers.js +72 -0
  350. package/dist/timers.js.map +1 -0
  351. package/dist/tool-search/index.d.ts +2 -0
  352. package/dist/tool-search/index.d.ts.map +1 -0
  353. package/dist/tool-search/index.js +2 -0
  354. package/dist/tool-search/index.js.map +1 -0
  355. package/dist/tool-search/tool-search.d.ts +17 -0
  356. package/dist/tool-search/tool-search.d.ts.map +1 -0
  357. package/dist/tool-search/tool-search.js +96 -0
  358. package/dist/tool-search/tool-search.js.map +1 -0
  359. package/dist/tools/bash.d.ts +55 -0
  360. package/dist/tools/bash.d.ts.map +1 -0
  361. package/dist/tools/bash.js +139 -0
  362. package/dist/tools/bash.js.map +1 -0
  363. package/dist/tools/edit-diff.d.ts +89 -0
  364. package/dist/tools/edit-diff.d.ts.map +1 -0
  365. package/dist/tools/edit-diff.js +386 -0
  366. package/dist/tools/edit-diff.js.map +1 -0
  367. package/dist/tools/edit.d.ts +18 -0
  368. package/dist/tools/edit.d.ts.map +1 -0
  369. package/dist/tools/edit.js +117 -0
  370. package/dist/tools/edit.js.map +1 -0
  371. package/dist/tools/env.d.ts +5 -0
  372. package/dist/tools/env.d.ts.map +1 -0
  373. package/dist/tools/env.js +7 -0
  374. package/dist/tools/env.js.map +1 -0
  375. package/dist/tools/file-mutation-queue.d.ts +9 -0
  376. package/dist/tools/file-mutation-queue.d.ts.map +1 -0
  377. package/dist/tools/file-mutation-queue.js +52 -0
  378. package/dist/tools/file-mutation-queue.js.map +1 -0
  379. package/dist/tools/image-processor.d.ts +57 -0
  380. package/dist/tools/image-processor.d.ts.map +1 -0
  381. package/dist/tools/image-processor.js +49 -0
  382. package/dist/tools/image-processor.js.map +1 -0
  383. package/dist/tools/image.d.ts +20 -0
  384. package/dist/tools/image.d.ts.map +1 -0
  385. package/dist/tools/image.js +178 -0
  386. package/dist/tools/image.js.map +1 -0
  387. package/dist/tools/index.d.ts +46 -0
  388. package/dist/tools/index.d.ts.map +1 -0
  389. package/dist/tools/index.js +23 -0
  390. package/dist/tools/index.js.map +1 -0
  391. package/dist/tools/path-utils.d.ts +5 -0
  392. package/dist/tools/path-utils.d.ts.map +1 -0
  393. package/dist/tools/path-utils.js +26 -0
  394. package/dist/tools/path-utils.js.map +1 -0
  395. package/dist/tools/read.d.ts +30 -0
  396. package/dist/tools/read.d.ts.map +1 -0
  397. package/dist/tools/read.js +239 -0
  398. package/dist/tools/read.js.map +1 -0
  399. package/dist/tools/write.d.ts +10 -0
  400. package/dist/tools/write.d.ts.map +1 -0
  401. package/dist/tools/write.js +31 -0
  402. package/dist/tools/write.js.map +1 -0
  403. package/dist/truncate.d.ts +65 -0
  404. package/dist/truncate.d.ts.map +1 -0
  405. package/dist/truncate.js +124 -0
  406. package/dist/truncate.js.map +1 -0
  407. package/dist/types.d.ts +1244 -0
  408. package/dist/types.d.ts.map +1 -0
  409. package/dist/types.js +3 -0
  410. package/dist/types.js.map +1 -0
  411. package/package.json +179 -5
@@ -0,0 +1,1554 @@
1
+ import { BACKGROUND_CONTEXT } from "@diffra-ai/chord/context";
2
+ import { idFromNumber } from "../ids.js";
3
+ import { ROOT_CONVERSATION_ID, } from "../types.js";
4
+ import { commitWrites } from "./commit-writes.js";
5
+ const context = BACKGROUND_CONTEXT;
6
+ async function createRoot(storage) {
7
+ await commitWrites(storage, [{ type: "conversation", value: { id: ROOT_CONVERSATION_ID } }], context);
8
+ return ROOT_CONVERSATION_ID;
9
+ }
10
+ function pendingTask(id, conversationId, phase = "ready") {
11
+ return {
12
+ id,
13
+ conversationId,
14
+ kind: "test.task",
15
+ version: 1,
16
+ input: { value: id },
17
+ state: { status: "pending", checkpoint: { phase } },
18
+ background: false,
19
+ abortRequested: false,
20
+ };
21
+ }
22
+ function entry(id, conversationId, kind = "message", extra = {}) {
23
+ return { id, conversationId, kind, ...extra };
24
+ }
25
+ function assertionFacade(assertions) {
26
+ return (actual) => ({
27
+ toBe: (expected) => assertions.strictEqual(actual, expected),
28
+ toBeDefined: () => assertions.ok(actual !== undefined, "Expected value to be defined"),
29
+ toBeGreaterThan: (expected) => assertions.greaterThan(actual, expected),
30
+ toBeUndefined: () => assertions.strictEqual(actual, undefined),
31
+ toEqual: (expected) => assertions.deepEqual(actual, expected),
32
+ toHaveLength: (expected) => assertions.strictEqual(actual.length, expected),
33
+ toMatchObject: (expected) => assertions.partialDeepEqual(actual, expected),
34
+ rejects: {
35
+ toThrow: (messageIncludes) => assertions.rejects(Promise.resolve(actual), messageIncludes),
36
+ },
37
+ resolves: {
38
+ toBe: async (expected) => assertions.strictEqual(await Promise.resolve(actual), expected),
39
+ },
40
+ });
41
+ }
42
+ /**
43
+ * `storage` with every commit checked against the receipt contract: one `receive` per stored batch, in order, with
44
+ * increasing seqs, all before the call settles.
45
+ */
46
+ function checkReceipts(storage, assertions) {
47
+ const commit = async (batches, receive, commitContext) => {
48
+ const seqs = [];
49
+ let settled = false;
50
+ const recording = (index, seq) => {
51
+ assertions.ok(!settled, "Storage.commit() received a batch after it settled");
52
+ assertions.strictEqual(index, seqs.length);
53
+ if (seqs.length > 0)
54
+ assertions.greaterThan(seq, seqs.at(-1));
55
+ seqs.push(seq);
56
+ receive(index, seq);
57
+ };
58
+ try {
59
+ const result = await storage.commit(batches, recording, commitContext);
60
+ assertions.strictEqual(seqs.length, result.stored);
61
+ return result;
62
+ }
63
+ finally {
64
+ settled = true;
65
+ }
66
+ };
67
+ return new Proxy(storage, {
68
+ get(target, property) {
69
+ if (property === "commit")
70
+ return commit;
71
+ const value = Reflect.get(target, property, target);
72
+ return typeof value === "function" ? value.bind(target) : value;
73
+ },
74
+ });
75
+ }
76
+ function createCase(options, name, test) {
77
+ return { name, run: () => options.withStorage((storage) => test(checkReceipts(storage, options.assertions))) };
78
+ }
79
+ /** Creates runner-independent cases. `withStorage` must call and await its callback exactly once per case. */
80
+ export function createStorageConformance(options) {
81
+ const expect = assertionFacade(options.assertions);
82
+ return [
83
+ createCase(options, "reserves ID 1 for the immutable root conversation", async (storage) => {
84
+ expect(await storage.mintId()).toBe(2);
85
+ await expect(createRoot(storage)).resolves.toBe(ROOT_CONVERSATION_ID);
86
+ expect(await storage.conversation(ROOT_CONVERSATION_ID, context)).toEqual({ id: ROOT_CONVERSATION_ID });
87
+ await expect(commitWrites(storage, [{ type: "conversation", value: { id: ROOT_CONVERSATION_ID } }], context)).rejects.toThrow(`ID ${ROOT_CONVERSATION_ID} already belongs to conversation`);
88
+ }),
89
+ createCase(options, "receives a durable commit once before resolving, and never a refused one", async (storage) => {
90
+ const rootId = await createRoot(storage);
91
+ const events = [];
92
+ const entryId = await storage.mintId();
93
+ let read;
94
+ let seq;
95
+ const result = await storage.commit([[{ type: "entry", value: entry(entryId, rootId) }]], (_index, received) => {
96
+ seq = received;
97
+ events.push(`receive ${received}`);
98
+ // The batch is durable when it is received: a read started now observes it.
99
+ read = storage.entry(entryId, context);
100
+ }, context);
101
+ events.push(`resolve ${result.stored}`);
102
+ expect(events).toEqual([`receive ${seq}`, "resolve 1"]);
103
+ expect((await read)?.commitSeq).toBe(seq);
104
+ events.length = 0;
105
+ const refused = await storage.commit([[{ type: "conversation", value: { id: rootId } }]], (_index, received) => events.push(`receive ${received}`), context);
106
+ expect(refused.stored).toBe(0);
107
+ expect(refused.kind === "refused" && String(refused.refused)).toBe(`Error: ID ${rootId} already belongs to conversation`);
108
+ expect(events).toEqual([]);
109
+ const next = await commitWrites(storage, [{ type: "entry", value: entry(await storage.mintId(), rootId) }], context);
110
+ expect(next).toBeGreaterThan(seq);
111
+ }),
112
+ createCase(options, "commits mixed table writes atomically and rolls all of them back on failure", async (storage) => {
113
+ const rootId = await createRoot(storage);
114
+ const entryId = await storage.mintId();
115
+ const taskId = await storage.mintId();
116
+ const submissionId = await storage.mintId();
117
+ const task = pendingTask(taskId, rootId);
118
+ const input = {
119
+ id: submissionId,
120
+ conversationId: rootId,
121
+ requestId: "request-1",
122
+ type: "input",
123
+ status: "placed",
124
+ entry: entryId,
125
+ };
126
+ const initialSeq = await commitWrites(storage, [
127
+ { type: "entry", value: entry(entryId, rootId, "user", { data: { text: "hello" } }) },
128
+ { type: "task", value: task },
129
+ { type: "submission", value: input },
130
+ ], context);
131
+ expect(await storage.entry(entryId, context)).toEqual({
132
+ entry: entry(entryId, rootId, "user", { data: { text: "hello" } }),
133
+ commitSeq: initialSeq,
134
+ });
135
+ expect(await storage.task(taskId, context)).toEqual(task);
136
+ expect(await storage.submission(submissionId, context)).toEqual(input);
137
+ const transientEntryId = await storage.mintId();
138
+ const runningTask = {
139
+ ...task,
140
+ state: { status: "running", checkpoint: { phase: "effect" } },
141
+ };
142
+ const doneInput = { ...input, status: "done", answer: transientEntryId };
143
+ await expect(commitWrites(storage, [
144
+ { type: "task", value: runningTask },
145
+ { type: "submission", value: doneInput },
146
+ { type: "entry", value: entry(transientEntryId, rootId, "assistant") },
147
+ { type: "conversation", value: { id: rootId } },
148
+ ], context)).rejects.toThrow(`ID ${rootId} already belongs to conversation`);
149
+ expect(await storage.task(taskId, context)).toEqual(task);
150
+ expect(await storage.submission(submissionId, context)).toEqual(input);
151
+ expect(await storage.entry(transientEntryId, context)).toBeUndefined();
152
+ const afterRollbackSeq = await commitWrites(storage, [{ type: "entry", value: entry(await storage.mintId(), rootId, "after-rollback") }], context);
153
+ expect(afterRollbackSeq).toBeGreaterThan(initialSeq);
154
+ }),
155
+ createCase(options, "detaches retained writes and every returned record", async (storage) => {
156
+ const rootId = await createRoot(storage);
157
+ const entryId = await storage.mintId();
158
+ const taskId = await storage.mintId();
159
+ const submissionId = await storage.mintId();
160
+ const entryData = { nested: [1, 2] };
161
+ const checkpoint = { phase: "ready", nested: { count: 1 } };
162
+ const detail = { codes: ["initial"] };
163
+ const storedEntry = entry(entryId, rootId, "note", { data: entryData });
164
+ const storedTask = {
165
+ ...pendingTask(taskId, rootId),
166
+ state: { status: "pending", checkpoint },
167
+ };
168
+ const storedInput = {
169
+ id: submissionId,
170
+ conversationId: rootId,
171
+ type: "input",
172
+ status: "unanswered",
173
+ reason: "failed",
174
+ detail,
175
+ };
176
+ await commitWrites(storage, [
177
+ { type: "entry", value: storedEntry },
178
+ { type: "task", value: storedTask },
179
+ { type: "submission", value: storedInput },
180
+ ], context);
181
+ entryData.nested.push(3);
182
+ checkpoint.nested.count = 2;
183
+ detail.codes.push("mutated");
184
+ expect((await storage.entry(entryId, context))?.entry.data).toEqual({ nested: [1, 2] });
185
+ expect((await storage.task(taskId, context))?.state).toEqual({
186
+ status: "pending",
187
+ checkpoint: { phase: "ready", nested: { count: 1 } },
188
+ });
189
+ expect((await storage.submission(submissionId, context))?.detail).toEqual({ codes: ["initial"] });
190
+ const readEntry = (await storage.entry(entryId, context)).entry;
191
+ readEntry.data.nested.push(9);
192
+ const readTask = (await storage.task(taskId, context));
193
+ if (readTask.state.status !== "terminal") {
194
+ readTask.state.checkpoint.nested.count = 9;
195
+ }
196
+ const readInput = (await storage.submission(submissionId, context));
197
+ readInput.detail.codes.push("read mutation");
198
+ expect((await storage.entry(entryId, context))?.entry.data).toEqual({ nested: [1, 2] });
199
+ expect((await storage.task(taskId, context))?.state).toEqual({
200
+ status: "pending",
201
+ checkpoint: { phase: "ready", nested: { count: 1 } },
202
+ });
203
+ expect((await storage.submission(submissionId, context))?.detail).toEqual({ codes: ["initial"] });
204
+ }),
205
+ createCase(options, "detaches prototype-like JSON keys without changing object prototypes", async (storage) => {
206
+ const rootId = await createRoot(storage);
207
+ const entryId = await storage.mintId();
208
+ const data = JSON.parse('{"__proto__":{"polluted":false},"constructor":{"label":"stored"},"toString":"value"}');
209
+ await commitWrites(storage, [{ type: "entry", value: entry(entryId, rootId, "note", { data }) }], context);
210
+ Reflect.get(data, "__proto__").polluted = true;
211
+ Reflect.get(data, "constructor").label = "mutated";
212
+ const firstRead = (await storage.entry(entryId, context)).entry.data;
213
+ expect(Object.getPrototypeOf(firstRead)).toBe(Object.prototype);
214
+ expect(Object.hasOwn(firstRead, "__proto__")).toBe(true);
215
+ expect(Reflect.get(firstRead, "__proto__")).toEqual({ polluted: false });
216
+ expect(Reflect.get(firstRead, "constructor")).toEqual({ label: "stored" });
217
+ expect(Reflect.get(firstRead, "toString")).toBe("value");
218
+ expect({}.polluted).toBeUndefined();
219
+ Reflect.get(firstRead, "__proto__").polluted = true;
220
+ const secondRead = (await storage.entry(entryId, context)).entry.data;
221
+ expect(Reflect.get(secondRead, "__proto__")).toEqual({ polluted: false });
222
+ expect(Reflect.get(secondRead, "constructor")).toEqual({ label: "stored" });
223
+ expect(Reflect.get(secondRead, "toString")).toBe("value");
224
+ }),
225
+ createCase(options, "indexes entries committed out of ID order", async (storage) => {
226
+ const rootId = await createRoot(storage);
227
+ await commitWrites(storage, [
228
+ { type: "entry", value: entry(idFromNumber(30), rootId) },
229
+ { type: "entry", value: entry(idFromNumber(10), rootId) },
230
+ {
231
+ type: "entry",
232
+ value: entry(idFromNumber(20), rootId, "marker", {
233
+ head: idFromNumber(10),
234
+ }),
235
+ },
236
+ ], context);
237
+ expect((await storage.scanEntries({ conversationId: rootId }, 10, undefined, context)).items.map(({ id }) => id)).toEqual([30, 20, 10]);
238
+ expect((await storage.findLatestHeadMarker(rootId, undefined, context))?.id).toBe(20);
239
+ }),
240
+ createCase(options, "continues an entry cursor below its last item after a newer commit", async (storage) => {
241
+ const rootId = await createRoot(storage);
242
+ const oldestId = await storage.mintId();
243
+ const middleId = await storage.mintId();
244
+ const newestId = await storage.mintId();
245
+ await commitWrites(storage, [
246
+ { type: "entry", value: entry(oldestId, rootId) },
247
+ { type: "entry", value: entry(middleId, rootId) },
248
+ { type: "entry", value: entry(newestId, rootId) },
249
+ ], context);
250
+ const first = await storage.scanEntries({ conversationId: rootId }, 2, undefined, context);
251
+ expect(first.items.map(({ id }) => id)).toEqual([newestId, middleId]);
252
+ const appendedId = await storage.mintId();
253
+ await commitWrites(storage, [{ type: "entry", value: entry(appendedId, rootId) }], context);
254
+ const second = await storage.scanEntries({ conversationId: rootId }, 2, first.next, context);
255
+ expect(second.items.map(({ id }) => id)).toEqual([oldestId]);
256
+ expect(second.next).toBeUndefined();
257
+ }),
258
+ createCase(options, "paginates conversations by opaque cursor in ascending ID order", async (storage) => {
259
+ const rootId = await createRoot(storage);
260
+ const secondId = await storage.mintId();
261
+ const thirdId = await storage.mintId();
262
+ await commitWrites(storage, [
263
+ { type: "conversation", value: { id: thirdId } },
264
+ { type: "conversation", value: { id: secondId } },
265
+ ], context);
266
+ const first = await storage.scanConversations({}, 2, undefined, context);
267
+ expect(first.items.map(({ id }) => id)).toEqual([rootId, secondId]);
268
+ expect(first.next).toBeDefined();
269
+ const roundTrippedCursor = JSON.parse(JSON.stringify(first.next));
270
+ const second = await storage.scanConversations({}, 2, roundTrippedCursor, context);
271
+ expect(second.items.map(({ id }) => id)).toEqual([thirdId]);
272
+ expect(second.next).toBeUndefined();
273
+ }),
274
+ createCase(options, "filters and pages conversations by durable owner edges", async (storage) => {
275
+ const rootId = await createRoot(storage);
276
+ const otherOwnerId = await storage.mintId();
277
+ const firstTaskId = await storage.mintId();
278
+ const secondTaskId = await storage.mintId();
279
+ const firstId = await storage.mintId();
280
+ const secondId = await storage.mintId();
281
+ const thirdId = await storage.mintId();
282
+ await commitWrites(storage, [
283
+ { type: "conversation", value: { id: otherOwnerId } },
284
+ {
285
+ type: "conversation",
286
+ value: { id: firstId, owner: { conversationId: rootId, taskId: firstTaskId } },
287
+ },
288
+ {
289
+ type: "conversation",
290
+ value: { id: secondId, owner: { conversationId: rootId, taskId: secondTaskId } },
291
+ },
292
+ {
293
+ type: "conversation",
294
+ value: { id: thirdId, owner: { conversationId: otherOwnerId, taskId: firstTaskId } },
295
+ },
296
+ ], context);
297
+ const first = await storage.scanConversations({ ownerConversationId: rootId }, 1, undefined, context);
298
+ expect(first.items.map(({ id }) => id)).toEqual([firstId]);
299
+ expect(first.next).toBeDefined();
300
+ const second = await storage.scanConversations({ ownerConversationId: rootId }, 1, first.next, context);
301
+ expect(second.items.map(({ id }) => id)).toEqual([secondId]);
302
+ expect(second.next).toBeUndefined();
303
+ expect((await storage.scanConversations({ ownerTaskId: firstTaskId }, 10, undefined, context)).items.map(({ id }) => id)).toEqual([firstId, thirdId]);
304
+ expect((await storage.scanConversations({ ownerConversationId: rootId, ownerTaskId: firstTaskId }, 10, undefined, context)).items.map(({ id }) => id)).toEqual([firstId]);
305
+ }),
306
+ createCase(options, "scans deep fork history newest-first through every ancestor cap", async (storage) => {
307
+ const rootId = await createRoot(storage);
308
+ const rootFirst = await storage.mintId();
309
+ const rootForkPoint = await storage.mintId();
310
+ const rootExcludedSameCommit = await storage.mintId();
311
+ const rootEntriesSeq = await commitWrites(storage, [
312
+ { type: "entry", value: entry(rootFirst, rootId) },
313
+ {
314
+ type: "entry",
315
+ value: entry(rootForkPoint, rootId, "marker", { head: rootFirst }),
316
+ },
317
+ { type: "entry", value: entry(rootExcludedSameCommit, rootId) },
318
+ ], context);
319
+ const childId = await storage.mintId();
320
+ await commitWrites(storage, [
321
+ {
322
+ type: "conversation",
323
+ value: { id: childId, parent: { conversationId: rootId, at: rootForkPoint } },
324
+ },
325
+ ], context);
326
+ const childForkPoint = await storage.mintId();
327
+ const childExcluded = await storage.mintId();
328
+ await commitWrites(storage, [
329
+ { type: "entry", value: entry(childForkPoint, childId, "note") },
330
+ { type: "entry", value: entry(childExcluded, childId) },
331
+ ], context);
332
+ const rootExcludedLater = await storage.mintId();
333
+ await commitWrites(storage, [{ type: "entry", value: entry(rootExcludedLater, rootId) }], context);
334
+ const grandchildId = await storage.mintId();
335
+ await commitWrites(storage, [
336
+ {
337
+ type: "conversation",
338
+ value: { id: grandchildId, parent: { conversationId: childId, at: childForkPoint } },
339
+ },
340
+ ], context);
341
+ const grandchildHead = await storage.mintId();
342
+ const grandchildTail = await storage.mintId();
343
+ const grandchildEntriesSeq = await commitWrites(storage, [
344
+ {
345
+ type: "entry",
346
+ value: entry(grandchildHead, grandchildId, "marker", { head: grandchildHead }),
347
+ },
348
+ { type: "entry", value: entry(grandchildTail, grandchildId) },
349
+ ], context);
350
+ const childExcludedLater = await storage.mintId();
351
+ await commitWrites(storage, [{ type: "entry", value: entry(childExcludedLater, childId) }], context);
352
+ const first = await storage.scanEntries({ conversationId: grandchildId }, 2, undefined, context);
353
+ expect(first.items.map(({ id }) => id)).toEqual([grandchildTail, grandchildHead]);
354
+ const second = await storage.scanEntries({ conversationId: grandchildId }, 2, first.next, context);
355
+ expect(second.items.map(({ id }) => id)).toEqual([childForkPoint, rootForkPoint]);
356
+ const third = await storage.scanEntries({ conversationId: grandchildId }, 2, second.next, context);
357
+ expect(third.items.map(({ id }) => id)).toEqual([rootFirst]);
358
+ expect(third.next).toBeUndefined();
359
+ // Oldest first: the root's segment, then each fork's, each capped at the next fork point.
360
+ const ascending = { conversationId: grandchildId, order: "ascending" };
361
+ const firstUp = await storage.scanEntries(ascending, 2, undefined, context);
362
+ expect(firstUp.items.map(({ id }) => id)).toEqual([rootFirst, rootForkPoint]);
363
+ const secondUp = await storage.scanEntries(ascending, 2, firstUp.next, context);
364
+ expect(secondUp.items.map(({ id }) => id)).toEqual([childForkPoint, grandchildHead]);
365
+ const thirdUp = await storage.scanEntries({ conversationId: grandchildId }, 2, secondUp.next, context);
366
+ expect(thirdUp.items.map(({ id }) => id)).toEqual([grandchildTail]);
367
+ expect(thirdUp.next).toBeUndefined();
368
+ expect((await storage.scanEntries({ ...ascending, minEntryId: rootForkPoint, maxEntryId: childForkPoint }, 10, undefined, context)).items.map(({ id }) => id)).toEqual([rootForkPoint, childForkPoint]);
369
+ await expect(storage.scanEntries({ conversationId: grandchildId, order: "descending" }, 2, firstUp.next, context)).rejects.toThrow("cursor");
370
+ const currentMarker = await storage.findLatestHeadMarker(grandchildId, undefined, context);
371
+ expect(currentMarker?.id).toBe(grandchildHead);
372
+ expect(currentMarker?.head).toBe(grandchildHead);
373
+ const historicalMarker = await storage.findLatestHeadMarker(grandchildId, childForkPoint, context);
374
+ expect(historicalMarker?.id).toBe(rootForkPoint);
375
+ expect(historicalMarker?.head).toBe(rootFirst);
376
+ expect(await storage.findLatestHeadMarker(grandchildId, rootFirst, context)).toBeUndefined();
377
+ const activeFirst = await storage.scanEntries({ conversationId: grandchildId, minEntryId: currentMarker?.head }, 1, undefined, context);
378
+ expect(activeFirst.items.map(({ id }) => id)).toEqual([grandchildTail]);
379
+ expect(activeFirst.next).toBeDefined();
380
+ const activeSecond = await storage.scanEntries({ conversationId: grandchildId, minEntryId: currentMarker?.head }, 1, activeFirst.next, context);
381
+ expect(activeSecond.items.map(({ id }) => id)).toEqual([grandchildHead]);
382
+ expect(activeSecond.next).toBeUndefined();
383
+ expect((await storage.scanEntries({
384
+ conversationId: grandchildId,
385
+ minEntryId: historicalMarker?.head,
386
+ maxEntryId: childForkPoint,
387
+ }, 10, undefined, context)).items.map(({ id }) => id)).toEqual([childForkPoint, rootForkPoint, rootFirst]);
388
+ expect(await storage.entry(rootFirst, context)).toEqual({
389
+ entry: entry(rootFirst, rootId),
390
+ commitSeq: rootEntriesSeq,
391
+ });
392
+ expect((await storage.entry(rootForkPoint, context))?.commitSeq).toBe(rootEntriesSeq);
393
+ expect((await storage.entry(grandchildHead, context))?.commitSeq).toBe(grandchildEntriesSeq);
394
+ expect((await storage.entry(grandchildTail, context))?.commitSeq).toBe(grandchildEntriesSeq);
395
+ expect(await storage.entry(idFromNumber(999_999), context)).toBeUndefined();
396
+ expect(await storage.entry(grandchildId, rootFirst, context)).toEqual({
397
+ entry: entry(rootFirst, rootId),
398
+ commitSeq: rootEntriesSeq,
399
+ });
400
+ expect((await storage.entry(grandchildId, childForkPoint, context))?.entry.conversationId).toBe(childId);
401
+ expect((await storage.entry(grandchildId, grandchildTail, context))?.commitSeq).toBe(grandchildEntriesSeq);
402
+ expect(await storage.entry(grandchildId, rootExcludedSameCommit, context)).toBeUndefined();
403
+ expect(await storage.entry(grandchildId, rootExcludedLater, context)).toBeUndefined();
404
+ expect(await storage.entry(grandchildId, childExcluded, context)).toBeUndefined();
405
+ expect(await storage.entry(grandchildId, childExcludedLater, context)).toBeUndefined();
406
+ expect(await storage.entry(rootId, grandchildHead, context)).toBeUndefined();
407
+ expect(await storage.entry(grandchildId, idFromNumber(999_999), context)).toBeUndefined();
408
+ await expect(storage.entry(idFromNumber(999_999), rootFirst, context)).rejects.toThrow("Unknown conversation");
409
+ await expect(storage.scanEntries({ conversationId: idFromNumber(999_999) }, 10, undefined, context)).rejects.toThrow("Unknown conversation");
410
+ }),
411
+ createCase(options, "scans tables in either ID order and continues a cursor in its order", async (storage) => {
412
+ const rootId = await createRoot(storage);
413
+ const conversationIds = [rootId];
414
+ const taskIds = [];
415
+ const submissionIds = [];
416
+ for (let index = 0; index < 3; index++) {
417
+ const conversationId = await storage.mintId();
418
+ const taskId = await storage.mintId();
419
+ const submissionId = await storage.mintId();
420
+ await commitWrites(storage, [
421
+ { type: "conversation", value: { id: conversationId } },
422
+ { type: "task", value: pendingTask(taskId, rootId) },
423
+ {
424
+ type: "submission",
425
+ value: { id: submissionId, conversationId: rootId, type: "input", status: "queued" },
426
+ },
427
+ ], context);
428
+ conversationIds.push(conversationId);
429
+ taskIds.push(taskId);
430
+ submissionIds.push(submissionId);
431
+ }
432
+ const scans = [
433
+ [(order, cursor) => storage.scanConversations({ order }, 2, cursor, context), conversationIds],
434
+ [(order, cursor) => storage.scanTasks({ order }, 2, cursor, context), taskIds],
435
+ [(order, cursor) => storage.scanSubmissions({ order }, 2, cursor, context), submissionIds],
436
+ ];
437
+ const all = async (scan, order) => {
438
+ const found = [];
439
+ let page = await scan(order, undefined);
440
+ found.push(...page.items.map(({ id }) => id));
441
+ while (page.next !== undefined) {
442
+ // A cursor carries its order; the query may omit it.
443
+ page = await scan(undefined, JSON.parse(JSON.stringify(page.next)));
444
+ found.push(...page.items.map(({ id }) => id));
445
+ }
446
+ return found;
447
+ };
448
+ for (const [scan, ids] of scans) {
449
+ const reversed = [...ids].reverse();
450
+ expect(await all(scan, undefined)).toEqual(ids);
451
+ expect(await all(scan, "ascending")).toEqual(ids);
452
+ expect(await all(scan, "descending")).toEqual(reversed);
453
+ const descending = await scan("descending", undefined);
454
+ expect((await scan("descending", descending.next)).items.map(({ id }) => id)).toEqual(reversed.slice(2, 4));
455
+ await expect(scan("ascending", descending.next)).rejects.toThrow("cursor");
456
+ }
457
+ }),
458
+ createCase(options, "replaces complete task records and pages filtered task scans", async (storage) => {
459
+ const rootId = await createRoot(storage);
460
+ const firstId = await storage.mintId();
461
+ const secondId = await storage.mintId();
462
+ const thirdId = await storage.mintId();
463
+ const first = { ...pendingTask(firstId, rootId), memos: { winner: "first" } };
464
+ const second = { ...pendingTask(secondId, rootId), background: true };
465
+ const third = { ...pendingTask(thirdId, rootId), abortRequested: true };
466
+ await commitWrites(storage, [
467
+ { type: "task", value: first },
468
+ { type: "task", value: second },
469
+ { type: "task", value: third },
470
+ ], context);
471
+ const running = {
472
+ ...first,
473
+ state: { status: "running", checkpoint: { phase: "effect", attempt: 1 } },
474
+ abortRequested: true,
475
+ };
476
+ await commitWrites(storage, [{ type: "task", value: running }], context);
477
+ expect(await storage.task(firstId, context)).toEqual(running);
478
+ const terminal = {
479
+ id: firstId,
480
+ conversationId: rootId,
481
+ kind: first.kind,
482
+ version: first.version,
483
+ input: first.input,
484
+ state: { status: "terminal", outcome: { status: "completed", result: { entryId: 99 } } },
485
+ background: false,
486
+ abortRequested: true,
487
+ };
488
+ await commitWrites(storage, [{ type: "task", value: terminal }], context);
489
+ expect(await storage.task(firstId, context)).toEqual(terminal);
490
+ const pendingPage = await storage.scanTasks({ status: "pending" }, 1, undefined, context);
491
+ expect(pendingPage.items.map(({ id }) => id)).toEqual([secondId]);
492
+ expect(pendingPage.next).toBeDefined();
493
+ expect((await storage.scanTasks({ status: "pending" }, 1, pendingPage.next, context)).items.map(({ id }) => id)).toEqual([thirdId]);
494
+ expect((await storage.scanTasks({ status: "terminal", abortRequested: true }, 10, undefined, context)).items).toEqual([terminal]);
495
+ expect((await storage.scanTasks({ background: true }, 10, undefined, context)).items.map(({ id }) => id)).toEqual([secondId]);
496
+ }),
497
+ createCase(options, "stores owners and scans waiting and completing tasks by status", async (storage) => {
498
+ const rootId = await createRoot(storage);
499
+ const ownerId = await storage.mintId();
500
+ const waitingId = await storage.mintId();
501
+ const completingId = await storage.mintId();
502
+ const owner = pendingTask(ownerId, rootId);
503
+ const waiting = {
504
+ ...pendingTask(waitingId, rootId),
505
+ owner: ownerId,
506
+ state: { status: "waiting", checkpoint: { phase: "next" }, on: [ownerId], policy: "allSettled" },
507
+ memos: { kept: true },
508
+ };
509
+ const { state: _state, ...base } = pendingTask(completingId, rootId);
510
+ const completing = {
511
+ ...base,
512
+ owner: ownerId,
513
+ state: { status: "completing", outcome: { status: "failed", error: { message: "held" } } },
514
+ };
515
+ const writes = [owner, waiting, completing].map((value) => ({ type: "task", value }));
516
+ await commitWrites(storage, writes, context);
517
+ expect(await storage.task(waitingId, context)).toEqual(waiting);
518
+ expect(await storage.task(completingId, context)).toEqual(completing);
519
+ const scan = async (status) => (await storage.scanTasks({ status }, 10, undefined, context)).items;
520
+ expect(await scan("waiting")).toEqual([waiting]);
521
+ expect(await scan("completing")).toEqual([completing]);
522
+ expect((await scan("pending")).map(({ id }) => id)).toEqual([ownerId]);
523
+ const terminal = {
524
+ ...completing,
525
+ state: { status: "terminal", outcome: completing.state.outcome },
526
+ };
527
+ await commitWrites(storage, [{ type: "task", value: terminal }], context);
528
+ expect(await scan("completing")).toEqual([]);
529
+ expect(await scan("terminal")).toEqual([terminal]);
530
+ }),
531
+ createCase(options, "stores and scans sleeping tasks by status", async (storage) => {
532
+ const rootId = await createRoot(storage);
533
+ const sleepingId = await storage.mintId();
534
+ const sleeping = {
535
+ ...pendingTask(sleepingId, rootId),
536
+ state: { status: "sleeping", checkpoint: { phase: "next" }, until: 61_000 },
537
+ memos: { kept: true },
538
+ };
539
+ await commitWrites(storage, [{ type: "task", value: sleeping }], context);
540
+ expect(await storage.task(sleepingId, context)).toEqual(sleeping);
541
+ const scan = async (status) => (await storage.scanTasks({ status }, 10, undefined, context)).items;
542
+ expect(await scan("sleeping")).toEqual([sleeping]);
543
+ const running = { ...sleeping, state: { status: "running", checkpoint: { phase: "next" } } };
544
+ await commitWrites(storage, [{ type: "task", value: running }], context);
545
+ expect(await scan("sleeping")).toEqual([]);
546
+ expect(await scan("running")).toEqual([running]);
547
+ }),
548
+ createCase(options, "round-trips sleeps on signals, any waits, and wakes", async (storage) => {
549
+ const rootId = await createRoot(storage);
550
+ const ids = [];
551
+ for (let index = 0; index < 5; index++)
552
+ ids.push(await storage.mintId());
553
+ const signals = [{ signal: "app.answer", key: "a" }];
554
+ const memos = { "diffra.signal.app.answer/a": { version: 1, value: { text: "yes" } } };
555
+ const tasks = [
556
+ // A sleep without `until`, waiting only for a signal.
557
+ { ...pendingTask(ids[0], rootId), state: { status: "sleeping", checkpoint: { phase: "next" }, signals } },
558
+ {
559
+ ...pendingTask(ids[1], rootId),
560
+ state: { status: "sleeping", checkpoint: { phase: "next" }, until: 61_000, signals },
561
+ memos,
562
+ },
563
+ {
564
+ ...pendingTask(ids[2], rootId),
565
+ state: { status: "waiting", checkpoint: { phase: "next" }, on: [ids[0], ids[1]], policy: "any" },
566
+ },
567
+ {
568
+ ...pendingTask(ids[3], rootId),
569
+ state: { status: "pending", checkpoint: { phase: "next" }, wake: { reason: "tasks", ended: [ids[0]] } },
570
+ },
571
+ {
572
+ ...pendingTask(ids[4], rootId),
573
+ state: {
574
+ status: "running",
575
+ checkpoint: { phase: "next" },
576
+ wake: { reason: "signal", signal: "app.answer", key: "a" },
577
+ },
578
+ },
579
+ ];
580
+ await commitWrites(storage, tasks.map((value) => ({ type: "task", value })), context);
581
+ for (const task of tasks)
582
+ expect(await storage.task(task.id, context)).toEqual(task);
583
+ const scan = async (status) => (await storage.scanTasks({ status }, 10, undefined, context)).items;
584
+ expect(await scan("sleeping")).toEqual([tasks[0], tasks[1]]);
585
+ expect(await scan("waiting")).toEqual([tasks[2]]);
586
+ }),
587
+ createCase(options, "indexes request IDs per conversation and replaces complete submission records", async (storage) => {
588
+ const rootId = await createRoot(storage);
589
+ const secondConversationId = await storage.mintId();
590
+ await commitWrites(storage, [{ type: "conversation", value: { id: secondConversationId } }], context);
591
+ const firstId = await storage.mintId();
592
+ const secondId = await storage.mintId();
593
+ const otherConversationId = await storage.mintId();
594
+ const first = {
595
+ id: firstId,
596
+ conversationId: rootId,
597
+ requestId: "same",
598
+ type: "input",
599
+ status: "queued",
600
+ };
601
+ const second = {
602
+ id: secondId,
603
+ conversationId: rootId,
604
+ requestId: "other",
605
+ type: "input",
606
+ status: "queued",
607
+ };
608
+ const otherConversation = {
609
+ id: otherConversationId,
610
+ conversationId: secondConversationId,
611
+ requestId: "same",
612
+ type: "input",
613
+ status: "queued",
614
+ };
615
+ await commitWrites(storage, [
616
+ { type: "submission", value: first },
617
+ { type: "submission", value: second },
618
+ { type: "submission", value: otherConversation },
619
+ ], context);
620
+ expect(await storage.submissionByRequest(rootId, "same", context)).toEqual(first);
621
+ expect(await storage.submissionByRequest(secondConversationId, "same", context)).toEqual(otherConversation);
622
+ const placedSecond = {
623
+ ...second,
624
+ status: "placed",
625
+ entry: await storage.mintId(),
626
+ };
627
+ await commitWrites(storage, [{ type: "submission", value: placedSecond }], context);
628
+ expect(await storage.submission(secondId, context)).toEqual(placedSecond);
629
+ expect(await storage.submissionByRequest(rootId, "other", context)).toEqual(placedSecond);
630
+ const ids = async (query) => {
631
+ const found = [];
632
+ let cursor;
633
+ do {
634
+ const page = await storage.scanSubmissions(query, 1, cursor, context);
635
+ found.push(...page.items.map(({ id }) => id));
636
+ cursor = page.next;
637
+ } while (cursor !== undefined);
638
+ return found;
639
+ };
640
+ expect(await ids({})).toEqual([firstId, secondId, otherConversationId]);
641
+ expect(await ids({ conversationId: rootId })).toEqual([firstId, secondId]);
642
+ // A status change moves the record between status scans.
643
+ expect(await ids({ status: "queued" })).toEqual([firstId, otherConversationId]);
644
+ expect(await ids({ status: "placed" })).toEqual([secondId]);
645
+ expect(await ids({ conversationId: secondConversationId, status: "queued" })).toEqual([
646
+ otherConversationId,
647
+ ]);
648
+ expect(await ids({ conversationId: secondConversationId, status: "placed" })).toEqual([]);
649
+ expect((await storage.scanSubmissions({ status: "placed" }, 10, undefined, context)).items).toEqual([
650
+ placedSecond,
651
+ ]);
652
+ }),
653
+ createCase(options, "stores passive write submissions without input-only lifecycle states", async (storage) => {
654
+ const rootId = await createRoot(storage);
655
+ const doneId = await storage.mintId();
656
+ const failedId = await storage.mintId();
657
+ const queuedDone = {
658
+ id: doneId,
659
+ conversationId: rootId,
660
+ requestId: "passive-done",
661
+ type: "write",
662
+ status: "queued",
663
+ };
664
+ const queuedFailed = {
665
+ id: failedId,
666
+ conversationId: rootId,
667
+ requestId: "passive-failed",
668
+ type: "write",
669
+ status: "queued",
670
+ };
671
+ await commitWrites(storage, [
672
+ { type: "submission", value: queuedDone },
673
+ { type: "submission", value: queuedFailed },
674
+ ], context);
675
+ const done = {
676
+ ...queuedDone,
677
+ status: "done",
678
+ entry: await storage.mintId(),
679
+ };
680
+ const unanswered = {
681
+ ...queuedFailed,
682
+ status: "unanswered",
683
+ reason: "closed",
684
+ detail: { retryable: false },
685
+ };
686
+ await commitWrites(storage, [
687
+ { type: "submission", value: done },
688
+ { type: "submission", value: unanswered },
689
+ ], context);
690
+ expect(await storage.submission(doneId, context)).toEqual(done);
691
+ expect(await storage.submissionByRequest(rootId, "passive-done", context)).toEqual(done);
692
+ expect(await storage.submission(failedId, context)).toEqual(unanswered);
693
+ expect(await storage.submissionByRequest(rootId, "passive-failed", context)).toEqual(unanswered);
694
+ }),
695
+ createCase(options, "stores continue submissions, which have no entry and are never queued", async (storage) => {
696
+ const rootId = await createRoot(storage);
697
+ const doneId = await storage.mintId();
698
+ const failedId = await storage.mintId();
699
+ const placedDone = {
700
+ id: doneId,
701
+ conversationId: rootId,
702
+ requestId: "continue-done",
703
+ type: "continue",
704
+ status: "placed",
705
+ };
706
+ const placedFailed = {
707
+ id: failedId,
708
+ conversationId: rootId,
709
+ requestId: "continue-failed",
710
+ type: "continue",
711
+ status: "placed",
712
+ };
713
+ await commitWrites(storage, [
714
+ { type: "submission", value: placedDone },
715
+ { type: "submission", value: placedFailed },
716
+ ], context);
717
+ expect(await storage.submission(doneId, context)).toEqual(placedDone);
718
+ expect((await storage.scanSubmissions({ status: "placed" }, 10, undefined, context)).items).toEqual([
719
+ placedDone,
720
+ placedFailed,
721
+ ]);
722
+ const done = { ...placedDone, status: "done", answer: await storage.mintId() };
723
+ const unanswered = { ...placedFailed, status: "unanswered", reason: "nothing_to_answer" };
724
+ await commitWrites(storage, [
725
+ { type: "submission", value: done },
726
+ { type: "submission", value: unanswered },
727
+ ], context);
728
+ expect(await storage.submission(doneId, context)).toEqual(done);
729
+ expect(await storage.submissionByRequest(rootId, "continue-done", context)).toEqual(done);
730
+ expect(await storage.submission(failedId, context)).toEqual(unanswered);
731
+ expect(await storage.submissionByRequest(rootId, "continue-failed", context)).toEqual(unanswered);
732
+ }),
733
+ createCase(options, "reconstructs rewindable documents and preserves half-open incarnations", async (storage) => {
734
+ const rootId = await createRoot(storage);
735
+ const firstId = await storage.mintId();
736
+ const firstRecord = {
737
+ id: firstId,
738
+ kind: "conversation.notes",
739
+ scope: { kind: "conversation", conversationId: rootId },
740
+ history: "rewindable",
741
+ fork: "asOf",
742
+ };
743
+ const initial = { items: ["a"], nested: { count: 1 } };
744
+ const createdAt = await commitWrites(storage, [
745
+ {
746
+ type: "document.create",
747
+ record: firstRecord,
748
+ content: { kind: "base", version: 1, value: initial },
749
+ },
750
+ ], context);
751
+ const appended = ["b"];
752
+ const ops = [
753
+ ["p", ["items"], 1, 0, appended],
754
+ ["s", ["nested", "count"], 2],
755
+ ];
756
+ const changedAt = await commitWrites(storage, [{ type: "document.change", id: firstId, content: { kind: "delta", version: 1, ops } }], context);
757
+ initial.items.push("caller mutation");
758
+ appended.push("caller mutation");
759
+ expect(await storage.document(firstId, createdAt, context)).toMatchObject({
760
+ version: 1,
761
+ value: { items: ["a"], nested: { count: 1 } },
762
+ deltasSinceBase: 0,
763
+ });
764
+ const changed = (await storage.document(firstId, changedAt, context));
765
+ expect(changed.value).toEqual({ items: ["a", "b"], nested: { count: 2 } });
766
+ expect(changed.deltasSinceBase).toBe(1);
767
+ changed.value.items.push("read mutation");
768
+ expect((await storage.document(firstId, "current", context))?.value).toEqual({
769
+ items: ["a", "b"],
770
+ nested: { count: 2 },
771
+ });
772
+ const checkpointAt = await commitWrites(storage, [
773
+ {
774
+ type: "document.change",
775
+ id: firstId,
776
+ content: { kind: "base", version: 2, value: { items: ["checkpoint"], nested: { count: 3 } } },
777
+ },
778
+ ], context);
779
+ const replacedAt = await commitWrites(storage, [
780
+ {
781
+ type: "document.change",
782
+ id: firstId,
783
+ content: {
784
+ kind: "delta",
785
+ version: 2,
786
+ ops: [["r", { items: ["replacement"], nested: { count: 4 } }]],
787
+ },
788
+ },
789
+ ], context);
790
+ expect(await storage.document(firstId, changedAt, context)).toMatchObject({
791
+ version: 1,
792
+ value: { items: ["a", "b"], nested: { count: 2 } },
793
+ });
794
+ expect(await storage.document(firstId, checkpointAt, context)).toMatchObject({
795
+ version: 2,
796
+ value: { items: ["checkpoint"], nested: { count: 3 } },
797
+ deltasSinceBase: 0,
798
+ });
799
+ expect(await storage.document(firstId, replacedAt, context)).toMatchObject({
800
+ value: { items: ["replacement"], nested: { count: 4 } },
801
+ deltasSinceBase: 1,
802
+ });
803
+ expect((await storage.document(firstId, "current", context))?.deltasSinceBase).toBe(1);
804
+ const secondId = await storage.mintId();
805
+ const retiredAt = await commitWrites(storage, [
806
+ {
807
+ type: "document.create",
808
+ record: { ...firstRecord, id: secondId },
809
+ content: { kind: "base", version: 1, value: { items: ["new"] } },
810
+ },
811
+ { type: "document.retire", id: firstId },
812
+ {
813
+ type: "document.change",
814
+ id: firstId,
815
+ content: { kind: "delta", version: 2, ops: [["s", ["retiring"], true]] },
816
+ },
817
+ ], context);
818
+ const address = { kind: firstRecord.kind, scope: firstRecord.scope };
819
+ expect((await storage.findDocument(address, changedAt, context))?.id).toBe(firstId);
820
+ expect(await storage.findDocument(address, retiredAt, context)).toMatchObject({
821
+ id: secondId,
822
+ createdAt: retiredAt,
823
+ });
824
+ expect((await storage.scanDocuments({ scope: firstRecord.scope, at: changedAt }, 10, undefined, context)).items.map(({ id }) => id)).toEqual([firstId]);
825
+ expect((await storage.scanDocuments({ scope: firstRecord.scope, at: retiredAt }, 10, undefined, context)).items.map(({ id }) => id)).toEqual([secondId]);
826
+ expect(await storage.document(firstId, retiredAt, context)).toBeUndefined();
827
+ expect((await storage.document(secondId, "current", context))?.value).toEqual({ items: ["new"] });
828
+ }),
829
+ createCase(options, "streams long document tails across root replacement deltas", async (storage) => {
830
+ const rootId = await createRoot(storage);
831
+ const id = await storage.mintId();
832
+ const record = {
833
+ id,
834
+ kind: "conversation.long-tail",
835
+ scope: { kind: "conversation", conversationId: rootId },
836
+ history: "rewindable",
837
+ fork: "asOf",
838
+ };
839
+ const initial = {
840
+ revision: 0,
841
+ rows: Array.from({ length: 512 }, (_, value) => ({ value, stable: `row-${value}` })),
842
+ };
843
+ const createdAt = await commitWrites(storage, [{ type: "document.create", record, content: { kind: "base", version: 1, value: initial } }], context);
844
+ const beforeReplacement = structuredClone(initial);
845
+ let beforeReplacementAt = createdAt;
846
+ for (let revision = 1; revision <= 24; revision++) {
847
+ const index = (revision * 17) % beforeReplacement.rows.length;
848
+ beforeReplacement.rows[index].value = -revision;
849
+ beforeReplacement.revision = revision;
850
+ beforeReplacementAt = await commitWrites(storage, [
851
+ {
852
+ type: "document.change",
853
+ id,
854
+ content: {
855
+ kind: "delta",
856
+ version: 1,
857
+ ops: [
858
+ ["s", ["rows", index, "value"], -revision],
859
+ ["s", ["revision"], revision],
860
+ ],
861
+ },
862
+ },
863
+ ], context);
864
+ }
865
+ const replacement = {
866
+ revision: 100,
867
+ rows: Array.from({ length: 512 }, (_, value) => ({ value: 10_000 + value, stable: `new-${value}` })),
868
+ };
869
+ const replacementSnapshot = structuredClone(replacement);
870
+ const replacementAt = await commitWrites(storage, [
871
+ {
872
+ type: "document.change",
873
+ id,
874
+ content: { kind: "delta", version: 1, ops: [["r", replacement]] },
875
+ },
876
+ ], context);
877
+ replacement.rows[0].value = -999;
878
+ const current = structuredClone(replacementSnapshot);
879
+ for (let revision = 101; revision <= 124; revision++) {
880
+ const index = (revision * 19) % current.rows.length;
881
+ current.rows[index].value = -revision;
882
+ current.revision = revision;
883
+ await commitWrites(storage, [
884
+ {
885
+ type: "document.change",
886
+ id,
887
+ content: {
888
+ kind: "delta",
889
+ version: 1,
890
+ ops: [
891
+ ["s", ["rows", index, "value"], -revision],
892
+ ["s", ["revision"], revision],
893
+ ],
894
+ },
895
+ },
896
+ ], context);
897
+ }
898
+ expect((await storage.document(id, createdAt, context))?.value).toEqual(initial);
899
+ expect((await storage.document(id, beforeReplacementAt, context))?.value).toEqual(beforeReplacement);
900
+ expect((await storage.document(id, replacementAt, context))?.value).toEqual(replacementSnapshot);
901
+ const read = (await storage.document(id, "current", context));
902
+ expect(read.value).toEqual(current);
903
+ read.value.rows[0].value = -1_000;
904
+ expect((await storage.document(id, "current", context))?.value).toEqual(current);
905
+ }),
906
+ createCase(options, "copies stored document bases independently and rejects ambiguous sources", async (storage) => {
907
+ const rootId = await createRoot(storage);
908
+ const childId = await storage.mintId();
909
+ const secondChildId = await storage.mintId();
910
+ await commitWrites(storage, [
911
+ { type: "conversation", value: { id: childId } },
912
+ { type: "conversation", value: { id: secondChildId } },
913
+ ], context);
914
+ const sourceId = await storage.mintId();
915
+ const sourceRecord = {
916
+ id: sourceId,
917
+ kind: "copy.source",
918
+ scope: { kind: "conversation", conversationId: rootId },
919
+ history: "rewindable",
920
+ fork: "asOf",
921
+ };
922
+ const createdAt = await commitWrites(storage, [
923
+ {
924
+ type: "document.create",
925
+ record: sourceRecord,
926
+ content: { kind: "base", version: 2, value: { count: 1, rows: [{ value: "base" }] } },
927
+ },
928
+ ], context);
929
+ await commitWrites(storage, [
930
+ {
931
+ type: "document.change",
932
+ id: sourceId,
933
+ content: {
934
+ kind: "delta",
935
+ version: 2,
936
+ ops: [
937
+ ["s", ["count"], 2],
938
+ ["p", ["rows"], 1, 0, [{ value: "current" }]],
939
+ ],
940
+ },
941
+ },
942
+ ], context);
943
+ const historicalCopyId = await storage.mintId();
944
+ const currentCopyId = await storage.mintId();
945
+ const retiredCopyId = await storage.mintId();
946
+ const childRecord = (id, conversationId) => ({
947
+ id,
948
+ kind: sourceRecord.kind,
949
+ scope: { kind: "conversation", conversationId },
950
+ history: "rewindable",
951
+ fork: "asOf",
952
+ });
953
+ await commitWrites(storage, [
954
+ {
955
+ type: "document.copy",
956
+ record: childRecord(historicalCopyId, childId),
957
+ source: { id: sourceId, at: createdAt },
958
+ },
959
+ {
960
+ type: "document.copy",
961
+ record: childRecord(currentCopyId, secondChildId),
962
+ source: { id: sourceId, at: "current" },
963
+ },
964
+ {
965
+ type: "document.copy",
966
+ record: childRecord(retiredCopyId, rootId),
967
+ source: { id: sourceId, at: "current" },
968
+ },
969
+ { type: "document.retire", id: retiredCopyId },
970
+ ], context);
971
+ expect(await storage.document(historicalCopyId, "current", context)).toMatchObject({
972
+ version: 2,
973
+ value: { count: 1, rows: [{ value: "base" }] },
974
+ });
975
+ expect(await storage.document(currentCopyId, "current", context)).toMatchObject({
976
+ version: 2,
977
+ value: { count: 2, rows: [{ value: "base" }, { value: "current" }] },
978
+ });
979
+ expect(await storage.document(retiredCopyId, "current", context)).toBeUndefined();
980
+ await commitWrites(storage, [
981
+ {
982
+ type: "document.change",
983
+ id: sourceId,
984
+ content: { kind: "base", version: 2, value: { count: 99, rows: [] } },
985
+ },
986
+ { type: "document.retire", id: sourceId },
987
+ ], context);
988
+ expect((await storage.document(currentCopyId, "current", context))?.value).toEqual({
989
+ count: 2,
990
+ rows: [{ value: "base" }, { value: "current" }],
991
+ });
992
+ const latestSourceId = await storage.mintId();
993
+ const latestCopyId = await storage.mintId();
994
+ const latestSource = {
995
+ id: latestSourceId,
996
+ kind: "copy.latest",
997
+ scope: { kind: "conversation", conversationId: rootId },
998
+ history: "latest",
999
+ fork: "current",
1000
+ };
1001
+ await commitWrites(storage, [
1002
+ {
1003
+ type: "document.create",
1004
+ record: latestSource,
1005
+ content: { kind: "base", version: 4, value: { retained: "copy" } },
1006
+ },
1007
+ ], context);
1008
+ await commitWrites(storage, [
1009
+ {
1010
+ type: "document.copy",
1011
+ record: {
1012
+ ...latestSource,
1013
+ id: latestCopyId,
1014
+ scope: { kind: "conversation", conversationId: childId },
1015
+ },
1016
+ source: { id: latestSourceId, at: "current" },
1017
+ },
1018
+ ], context);
1019
+ await commitWrites(storage, [
1020
+ {
1021
+ type: "document.change",
1022
+ id: latestSourceId,
1023
+ content: { kind: "base", version: 4, value: { retained: "source-only" } },
1024
+ },
1025
+ { type: "document.retire", id: latestSourceId },
1026
+ ], context);
1027
+ expect(await storage.document(latestCopyId, "current", context)).toMatchObject({
1028
+ version: 4,
1029
+ value: { retained: "copy" },
1030
+ });
1031
+ const conflictId = await storage.mintId();
1032
+ let conflictError;
1033
+ try {
1034
+ await commitWrites(storage, [
1035
+ {
1036
+ type: "document.copy",
1037
+ record: childRecord(conflictId, childId),
1038
+ source: { id: currentCopyId, at: "current" },
1039
+ },
1040
+ { type: "document.retire", id: currentCopyId },
1041
+ ], context);
1042
+ }
1043
+ catch (error) {
1044
+ conflictError = error;
1045
+ }
1046
+ // Rejected without effect: the copy and the retirement in the same batch are both absent.
1047
+ expect(conflictError instanceof Error).toBe(true);
1048
+ expect(await storage.document(conflictId, "current", context)).toBeUndefined();
1049
+ expect((await storage.document(currentCopyId, "current", context))?.value).toEqual({
1050
+ count: 2,
1051
+ rows: [{ value: "base" }, { value: "current" }],
1052
+ });
1053
+ const mismatchId = await storage.mintId();
1054
+ let mismatchError;
1055
+ try {
1056
+ await commitWrites(storage, [
1057
+ {
1058
+ type: "document.copy",
1059
+ record: { ...childRecord(mismatchId, childId), kind: "copy.mismatch" },
1060
+ source: { id: currentCopyId, at: "current" },
1061
+ },
1062
+ ], context);
1063
+ }
1064
+ catch (error) {
1065
+ mismatchError = error;
1066
+ }
1067
+ expect(mismatchError instanceof Error).toBe(true);
1068
+ expect(await storage.document(mismatchId, "current", context)).toBeUndefined();
1069
+ }),
1070
+ createCase(options, "uses bases for version transitions and rejects historical reads of current-only documents", async (storage) => {
1071
+ await createRoot(storage);
1072
+ const id = await storage.mintId();
1073
+ const record = {
1074
+ id,
1075
+ kind: "session.settings",
1076
+ scope: { kind: "session" },
1077
+ };
1078
+ await commitWrites(storage, [{ type: "document.create", record, content: { kind: "base", version: 1, value: { count: 1 } } }], context);
1079
+ await commitWrites(storage, [{ type: "document.change", id, content: { kind: "delta", version: 1, ops: [["s", ["count"], 2]] } }], context);
1080
+ const migratedAt = await commitWrites(storage, [{ type: "document.change", id, content: { kind: "base", version: 2, value: { count: 3 } } }], context);
1081
+ expect(await storage.document(id, "current", context)).toMatchObject({ version: 2, value: { count: 3 } });
1082
+ await expect(storage.document(id, migratedAt, context)).rejects.toThrow("does not retain historical content");
1083
+ await expect(commitWrites(storage, [{ type: "document.change", id, content: { kind: "delta", version: 1, ops: [["s", ["count"], 4]] } }], context)).rejects.toThrow("version transition requires a base");
1084
+ expect((await storage.document(id, "current", context))?.value).toEqual({ count: 3 });
1085
+ await commitWrites(storage, [{ type: "document.retire", id }], context);
1086
+ expect(await storage.document(id, "current", context)).toBeUndefined();
1087
+ }),
1088
+ createCase(options, "indexes logical addresses and exact-scope scans independently", async (storage) => {
1089
+ const rootId = await createRoot(storage);
1090
+ const firstId = await storage.mintId();
1091
+ const secondId = await storage.mintId();
1092
+ const conversationId = await storage.mintId();
1093
+ const taskId = await storage.mintId();
1094
+ const taskSingletonId = await storage.mintId();
1095
+ const taskFamilyId = await storage.mintId();
1096
+ const taskOtherKindId = await storage.mintId();
1097
+ const createdAt = await commitWrites(storage, [
1098
+ { type: "task", value: pendingTask(taskId, rootId) },
1099
+ {
1100
+ type: "document.create",
1101
+ record: {
1102
+ id: firstId,
1103
+ kind: "cache",
1104
+ scope: { kind: "session" },
1105
+ key: "__proto__",
1106
+ },
1107
+ content: { kind: "base", version: 1, value: { owner: "first" } },
1108
+ },
1109
+ {
1110
+ type: "document.create",
1111
+ record: {
1112
+ id: secondId,
1113
+ kind: "cache",
1114
+ scope: { kind: "session" },
1115
+ key: "constructor",
1116
+ },
1117
+ content: { kind: "base", version: 1, value: { owner: "second" } },
1118
+ },
1119
+ {
1120
+ type: "document.create",
1121
+ record: {
1122
+ id: conversationId,
1123
+ kind: "cache",
1124
+ scope: { kind: "conversation", conversationId: rootId },
1125
+ history: "latest",
1126
+ fork: "current",
1127
+ key: "__proto__",
1128
+ },
1129
+ content: { kind: "base", version: 1, value: { owner: "conversation" } },
1130
+ },
1131
+ {
1132
+ type: "document.create",
1133
+ record: {
1134
+ id: taskSingletonId,
1135
+ kind: "task.cache",
1136
+ scope: { kind: "task", taskId },
1137
+ },
1138
+ content: { kind: "base", version: 1, value: { owner: "singleton" } },
1139
+ },
1140
+ {
1141
+ type: "document.create",
1142
+ record: {
1143
+ id: taskFamilyId,
1144
+ kind: "task.cache",
1145
+ scope: { kind: "task", taskId },
1146
+ key: "member",
1147
+ },
1148
+ content: { kind: "base", version: 1, value: { owner: "family" } },
1149
+ },
1150
+ {
1151
+ type: "document.create",
1152
+ record: {
1153
+ id: taskOtherKindId,
1154
+ kind: "task.other",
1155
+ scope: { kind: "task", taskId },
1156
+ },
1157
+ content: { kind: "base", version: 1, value: { owner: "other" } },
1158
+ },
1159
+ ], context);
1160
+ expect((await storage.findDocument({ kind: "cache", scope: { kind: "session" }, key: "__proto__" }, "current", context))?.id).toBe(firstId);
1161
+ expect((await storage.scanDocuments({ scope: { kind: "session" }, at: "current" }, 1, undefined, context)).items).toHaveLength(1);
1162
+ const first = await storage.scanDocuments({ scope: { kind: "session" }, at: "current" }, 1, undefined, context);
1163
+ const second = await storage.scanDocuments({ scope: { kind: "session" }, at: "current" }, 1, first.next, context);
1164
+ expect([...first.items, ...second.items].map(({ id }) => id)).toEqual([firstId, secondId]);
1165
+ expect((await storage.scanDocuments({ scope: { kind: "conversation", conversationId: rootId }, at: "current" }, 10, undefined, context)).items.map(({ id }) => id)).toEqual([conversationId]);
1166
+ expect((await storage.findDocument({ kind: "task.cache", scope: { kind: "task", taskId } }, "current", context))
1167
+ ?.id).toBe(taskSingletonId);
1168
+ expect((await storage.findDocument({ kind: "task.cache", scope: { kind: "task", taskId }, key: "member" }, "current", context))?.id).toBe(taskFamilyId);
1169
+ expect((await storage.scanDocuments({ scope: { kind: "task", taskId }, at: "current", kind: "task.cache" }, 10, undefined, context)).items.map(({ id }) => id)).toEqual([taskSingletonId, taskFamilyId]);
1170
+ await expect(storage.document(taskSingletonId, createdAt, context)).rejects.toThrow("does not retain historical content");
1171
+ }),
1172
+ createCase(options, "keeps document lifecycle failures atomic and gives create-plus-retire an empty lifetime", async (storage) => {
1173
+ const rootId = await createRoot(storage);
1174
+ const firstId = await storage.mintId();
1175
+ const secondId = await storage.mintId();
1176
+ const record = {
1177
+ id: firstId,
1178
+ kind: "singleton",
1179
+ scope: { kind: "session" },
1180
+ };
1181
+ await commitWrites(storage, [{ type: "document.create", record, content: { kind: "base", version: 1, value: { value: 1 } } }], context);
1182
+ await expect(commitWrites(storage, [
1183
+ {
1184
+ type: "document.create",
1185
+ record: { ...record, id: secondId },
1186
+ content: { kind: "base", version: 1, value: { value: 2 } },
1187
+ },
1188
+ { type: "document.change", id: firstId, content: { kind: "delta", version: 1, ops: [] } },
1189
+ ], context)).rejects.toThrow("already has a current incarnation");
1190
+ expect((await storage.document(firstId, "current", context))?.value).toEqual({ value: 1 });
1191
+ expect(await storage.document(secondId, "current", context)).toBeUndefined();
1192
+ const emptyId = await storage.mintId();
1193
+ const emptyAt = await commitWrites(storage, [
1194
+ {
1195
+ type: "document.create",
1196
+ record: {
1197
+ id: emptyId,
1198
+ kind: record.kind,
1199
+ key: "empty",
1200
+ scope: { kind: "conversation", conversationId: rootId },
1201
+ history: "rewindable",
1202
+ fork: "initial",
1203
+ },
1204
+ content: { kind: "base", version: 1, value: {} },
1205
+ },
1206
+ { type: "document.retire", id: emptyId },
1207
+ ], context);
1208
+ expect(await storage.document(emptyId, "current", context)).toBeUndefined();
1209
+ expect(await storage.document(emptyId, emptyAt, context)).toBeUndefined();
1210
+ expect(await storage.findDocument({
1211
+ kind: record.kind,
1212
+ scope: { kind: "conversation", conversationId: rootId },
1213
+ key: "empty",
1214
+ }, emptyAt, context)).toBeUndefined();
1215
+ }),
1216
+ createCase(options, "refuses a creation and a change of one document in one commit, in either order", async (storage) => {
1217
+ await createRoot(storage);
1218
+ for (const order of ["create first", "change first"]) {
1219
+ const id = await storage.mintId();
1220
+ const create = {
1221
+ type: "document.create",
1222
+ record: { id, kind: "twice", key: order, scope: { kind: "session" } },
1223
+ content: { kind: "base", version: 1, value: { x: 1 } },
1224
+ };
1225
+ const change = {
1226
+ type: "document.change",
1227
+ id,
1228
+ content: { kind: "delta", version: 1, ops: [["s", ["x"], 2]] },
1229
+ };
1230
+ const writes = order === "create first" ? [create, change] : [change, create];
1231
+ await expect(commitWrites(storage, writes, context)).rejects.toThrow("more than one content command");
1232
+ expect(await storage.document(id, "current", context)).toBeUndefined();
1233
+ }
1234
+ }),
1235
+ createCase(options, "rolls back record tables and secondary indexes when a document command fails", async (storage) => {
1236
+ const rootId = await createRoot(storage);
1237
+ const taskId = await storage.mintId();
1238
+ const submissionId = await storage.mintId();
1239
+ const documentId = await storage.mintId();
1240
+ const task = pendingTask(taskId, rootId);
1241
+ const submission = {
1242
+ id: submissionId,
1243
+ conversationId: rootId,
1244
+ requestId: "atomic",
1245
+ type: "input",
1246
+ status: "queued",
1247
+ };
1248
+ const record = {
1249
+ id: documentId,
1250
+ kind: "atomic",
1251
+ scope: { kind: "session" },
1252
+ };
1253
+ const baselineSeq = await commitWrites(storage, [
1254
+ { type: "task", value: task },
1255
+ { type: "submission", value: submission },
1256
+ { type: "document.create", record, content: { kind: "base", version: 1, value: { count: 1 } } },
1257
+ ], context);
1258
+ const entryId = await storage.mintId();
1259
+ const conflictingDocumentId = await storage.mintId();
1260
+ await expect(commitWrites(storage, [
1261
+ {
1262
+ type: "task",
1263
+ value: { ...task, state: { status: "running", checkpoint: { phase: "effect" } } },
1264
+ },
1265
+ {
1266
+ type: "submission",
1267
+ value: { ...submission, status: "unanswered", reason: "failed" },
1268
+ },
1269
+ { type: "entry", value: entry(entryId, rootId, "transient") },
1270
+ {
1271
+ type: "document.create",
1272
+ record: { ...record, id: conflictingDocumentId },
1273
+ content: { kind: "base", version: 1, value: { count: 2 } },
1274
+ },
1275
+ ], context)).rejects.toThrow("already has a current incarnation");
1276
+ expect(await storage.task(taskId, context)).toEqual(task);
1277
+ expect((await storage.scanTasks({ status: "pending" }, 10, undefined, context)).items).toEqual([task]);
1278
+ expect(await storage.submissionByRequest(rootId, "atomic", context)).toEqual(submission);
1279
+ expect(await storage.entry(entryId, context)).toBeUndefined();
1280
+ expect(await storage.document(conflictingDocumentId, "current", context)).toBeUndefined();
1281
+ expect((await storage.findDocument({ kind: record.kind, scope: record.scope }, "current", context))?.id).toBe(documentId);
1282
+ const afterRollbackSeq = await commitWrites(storage, [
1283
+ {
1284
+ type: "document.change",
1285
+ id: documentId,
1286
+ content: { kind: "delta", version: 1, ops: [["s", ["count"], 3]] },
1287
+ },
1288
+ ], context);
1289
+ expect(afterRollbackSeq).toBeGreaterThan(baselineSeq);
1290
+ }),
1291
+ createCase(options, "keeps indexed string identities lossless", async (storage) => {
1292
+ const rootId = await createRoot(storage);
1293
+ const first = "\ud800";
1294
+ const second = "\ud801";
1295
+ const firstTaskId = await storage.mintId();
1296
+ const secondTaskId = await storage.mintId();
1297
+ const firstSubmissionId = await storage.mintId();
1298
+ const secondSubmissionId = await storage.mintId();
1299
+ const firstKindDocumentId = await storage.mintId();
1300
+ const secondKindDocumentId = await storage.mintId();
1301
+ const firstKeyDocumentId = await storage.mintId();
1302
+ const secondKeyDocumentId = await storage.mintId();
1303
+ await commitWrites(storage, [
1304
+ { type: "task", value: { ...pendingTask(firstTaskId, rootId), kind: first } },
1305
+ { type: "task", value: { ...pendingTask(secondTaskId, rootId), kind: second } },
1306
+ {
1307
+ type: "submission",
1308
+ value: {
1309
+ id: firstSubmissionId,
1310
+ conversationId: rootId,
1311
+ requestId: first,
1312
+ type: "input",
1313
+ status: "queued",
1314
+ },
1315
+ },
1316
+ {
1317
+ type: "submission",
1318
+ value: {
1319
+ id: secondSubmissionId,
1320
+ conversationId: rootId,
1321
+ requestId: second,
1322
+ type: "input",
1323
+ status: "queued",
1324
+ },
1325
+ },
1326
+ {
1327
+ type: "document.create",
1328
+ record: { id: firstKindDocumentId, kind: first, scope: { kind: "session" } },
1329
+ content: { kind: "base", version: 1, value: { identity: "first kind" } },
1330
+ },
1331
+ {
1332
+ type: "document.create",
1333
+ record: { id: secondKindDocumentId, kind: second, scope: { kind: "session" } },
1334
+ content: { kind: "base", version: 1, value: { identity: "second kind" } },
1335
+ },
1336
+ {
1337
+ type: "document.create",
1338
+ record: { id: firstKeyDocumentId, kind: "family", key: first, scope: { kind: "session" } },
1339
+ content: { kind: "base", version: 1, value: { identity: "first key" } },
1340
+ },
1341
+ {
1342
+ type: "document.create",
1343
+ record: { id: secondKeyDocumentId, kind: "family", key: second, scope: { kind: "session" } },
1344
+ content: { kind: "base", version: 1, value: { identity: "second key" } },
1345
+ },
1346
+ ], context);
1347
+ expect((await storage.scanTasks({ kind: first }, 10, undefined, context)).items.map(({ id }) => id)).toEqual([
1348
+ firstTaskId,
1349
+ ]);
1350
+ expect((await storage.scanTasks({ kind: second }, 10, undefined, context)).items.map(({ id }) => id)).toEqual([
1351
+ secondTaskId,
1352
+ ]);
1353
+ expect((await storage.task(firstTaskId, context))?.kind).toBe(first);
1354
+ expect((await storage.task(secondTaskId, context))?.kind).toBe(second);
1355
+ expect((await storage.submissionByRequest(rootId, first, context))?.requestId).toBe(first);
1356
+ expect((await storage.submissionByRequest(rootId, first, context))?.id).toBe(firstSubmissionId);
1357
+ expect((await storage.submissionByRequest(rootId, second, context))?.id).toBe(secondSubmissionId);
1358
+ expect((await storage.findDocument({ kind: first, scope: { kind: "session" } }, "current", context))?.id).toBe(firstKindDocumentId);
1359
+ expect((await storage.findDocument({ kind: second, scope: { kind: "session" } }, "current", context))?.id).toBe(secondKindDocumentId);
1360
+ expect((await storage.findDocument({ kind: "family", key: first, scope: { kind: "session" } }, "current", context))
1361
+ ?.id).toBe(firstKeyDocumentId);
1362
+ expect((await storage.findDocument({ kind: "family", key: second, scope: { kind: "session" } }, "current", context))?.id).toBe(secondKeyDocumentId);
1363
+ expect((await storage.scanDocuments({ scope: { kind: "session" }, at: "current", kind: first }, 10, undefined, context)).items.map(({ id }) => id)).toEqual([firstKindDocumentId]);
1364
+ }),
1365
+ createCase(options, "keeps one global record ID namespace and rejects exhausted ID minting", async (storage) => {
1366
+ const rootId = await createRoot(storage);
1367
+ const explicitEntryId = idFromNumber(100);
1368
+ await commitWrites(storage, [{ type: "entry", value: entry(explicitEntryId, rootId) }], context);
1369
+ expect(await storage.mintId()).toBe(101);
1370
+ await expect(commitWrites(storage, [{ type: "task", value: pendingTask(idFromNumber(explicitEntryId), rootId) }], context)).rejects.toThrow(`ID ${explicitEntryId} already belongs to entry`);
1371
+ await commitWrites(storage, [{ type: "entry", value: entry(idFromNumber(Number.MAX_SAFE_INTEGER), rootId, "last-id") }], context);
1372
+ await expect(storage.mintId()).rejects.toThrow("ID space is exhausted");
1373
+ await expect(storage.mintId()).rejects.toThrow("ID space is exhausted");
1374
+ }),
1375
+ createCase(options, "commits batches in order, each with its seq, checked against the earlier ones", async (storage) => {
1376
+ const rootId = await createRoot(storage);
1377
+ const firstId = await storage.mintId();
1378
+ const lastId = await storage.mintId();
1379
+ const documentId = await storage.mintId();
1380
+ const receipts = [];
1381
+ let read;
1382
+ const result = await storage.commit([
1383
+ [
1384
+ { type: "entry", value: entry(firstId, rootId) },
1385
+ {
1386
+ type: "document.create",
1387
+ record: {
1388
+ id: documentId,
1389
+ kind: "batch.doc",
1390
+ scope: { kind: "conversation", conversationId: rootId },
1391
+ history: "latest",
1392
+ fork: "initial",
1393
+ },
1394
+ content: { kind: "base", version: 1, value: { count: 1 } },
1395
+ },
1396
+ ],
1397
+ // Changes the document the batch before created.
1398
+ [
1399
+ {
1400
+ type: "document.change",
1401
+ id: documentId,
1402
+ content: { kind: "delta", version: 1, ops: [["s", ["count"], 2]] },
1403
+ },
1404
+ ],
1405
+ [{ type: "entry", value: entry(lastId, rootId) }],
1406
+ ], (index, seq) => {
1407
+ receipts.push([index, seq]);
1408
+ // Receipts follow the last durable batch: a read started at the first observes it.
1409
+ read ??= storage.entry(lastId, context);
1410
+ }, context);
1411
+ expect(result).toEqual({ kind: "stored", stored: 3 });
1412
+ expect(receipts.map(([index]) => index)).toEqual([0, 1, 2]);
1413
+ const [[, first], [, second], [, last]] = receipts;
1414
+ expect(second).toBeGreaterThan(first);
1415
+ expect(last).toBeGreaterThan(second);
1416
+ expect((await read)?.commitSeq).toBe(last);
1417
+ expect((await storage.entry(firstId, context))?.commitSeq).toBe(first);
1418
+ expect((await storage.document(documentId, "current", context))?.value).toEqual({ count: 2 });
1419
+ const next = await commitWrites(storage, [{ type: "entry", value: entry(await storage.mintId(), rootId) }], context);
1420
+ expect(next).toBeGreaterThan(last);
1421
+ }),
1422
+ createCase(options, "stores the batches before the first one refused, and none after it", async (storage) => {
1423
+ const rootId = await createRoot(storage);
1424
+ const firstId = await storage.mintId();
1425
+ const afterId = await storage.mintId();
1426
+ const receipts = [];
1427
+ const result = await storage.commit([
1428
+ [{ type: "entry", value: entry(firstId, rootId) }],
1429
+ // Refused against the state the first batch left: the ID is taken now.
1430
+ [
1431
+ { type: "task", value: pendingTask(await storage.mintId(), rootId) },
1432
+ { type: "entry", value: entry(firstId, rootId) },
1433
+ ],
1434
+ [{ type: "entry", value: entry(afterId, rootId) }],
1435
+ ], (index) => receipts.push(index), context);
1436
+ expect(result.stored).toBe(1);
1437
+ expect(result.kind === "refused" && String(result.refused)).toBe(`Error: ID ${firstId} already belongs to entry`);
1438
+ expect(receipts).toEqual([0]);
1439
+ expect(await storage.entry(firstId, context)).toBeDefined();
1440
+ expect(await storage.entry(afterId, context)).toBeUndefined();
1441
+ expect((await storage.scanTasks({}, 10, undefined, context)).items.map((task) => task.id)).toEqual([]);
1442
+ // A refused first batch stores nothing; the storage goes on.
1443
+ const refused = await storage.commit([[{ type: "conversation", value: { id: rootId } }]], (index) => receipts.push(index), context);
1444
+ expect(refused.stored).toBe(0);
1445
+ expect(refused.kind === "refused" && String(refused.refused)).toBe(`Error: ID ${rootId} already belongs to conversation`);
1446
+ expect(receipts).toEqual([0]);
1447
+ await commitWrites(storage, [{ type: "entry", value: entry(afterId, rootId) }], context);
1448
+ expect(await storage.entry(afterId, context)).toBeDefined();
1449
+ }),
1450
+ createCase(options, "refuses a later batch its own malformed actions fail, keeping the batches before it", async (storage) => {
1451
+ const rootId = await createRoot(storage);
1452
+ const documentId = await storage.mintId();
1453
+ await commitWrites(storage, [
1454
+ {
1455
+ type: "document.create",
1456
+ record: { id: documentId, kind: "staged", scope: { kind: "session" } },
1457
+ content: { kind: "base", version: 1, value: { n: 1 } },
1458
+ },
1459
+ ], context);
1460
+ const firstId = await storage.mintId();
1461
+ const secondId = await storage.mintId();
1462
+ const afterId = await storage.mintId();
1463
+ const receipts = [];
1464
+ const result = await storage.commit([
1465
+ [{ type: "entry", value: entry(firstId, rootId) }],
1466
+ // Malformed in itself, whatever is stored: one document retired twice.
1467
+ [
1468
+ { type: "entry", value: entry(secondId, rootId) },
1469
+ { type: "document.retire", id: documentId },
1470
+ { type: "document.retire", id: documentId },
1471
+ ],
1472
+ [{ type: "entry", value: entry(afterId, rootId) }],
1473
+ ], (index) => receipts.push(index), context);
1474
+ expect(result.stored).toBe(1);
1475
+ expect(result.kind).toBe("refused");
1476
+ expect(receipts).toEqual([0]);
1477
+ expect(await storage.entry(firstId, context)).toBeDefined();
1478
+ expect(await storage.entry(secondId, context)).toBeUndefined();
1479
+ expect(await storage.entry(afterId, context)).toBeUndefined();
1480
+ expect((await storage.document(documentId, "current", context))?.value).toEqual({ n: 1 });
1481
+ }),
1482
+ createCase(options, "resolves a batched copy against the state the earlier batches left", async (storage) => {
1483
+ const rootId = await createRoot(storage);
1484
+ const childId = await storage.mintId();
1485
+ const sourceId = await storage.mintId();
1486
+ const copyId = await storage.mintId();
1487
+ const record = (id, conversationId) => ({
1488
+ id,
1489
+ kind: "batch.copy",
1490
+ scope: { kind: "conversation", conversationId },
1491
+ history: "rewindable",
1492
+ fork: "asOf",
1493
+ });
1494
+ const seqs = [];
1495
+ const result = await storage.commit([
1496
+ [
1497
+ {
1498
+ type: "document.create",
1499
+ record: record(sourceId, rootId),
1500
+ content: { kind: "base", version: 1, value: { count: 1 } },
1501
+ },
1502
+ ],
1503
+ [
1504
+ {
1505
+ type: "document.change",
1506
+ id: sourceId,
1507
+ content: { kind: "delta", version: 1, ops: [["s", ["count"], 2]] },
1508
+ },
1509
+ ],
1510
+ [
1511
+ { type: "conversation", value: { id: childId } },
1512
+ {
1513
+ type: "document.copy",
1514
+ record: record(copyId, childId),
1515
+ source: { id: sourceId, at: "current" },
1516
+ },
1517
+ ],
1518
+ ], (_index, seq) => seqs.push(seq), context);
1519
+ expect(result).toEqual({ kind: "stored", stored: 3 });
1520
+ expect((await storage.document(copyId, "current", context))?.value).toEqual({ count: 2 });
1521
+ expect((await storage.document(sourceId, seqs[0], context))?.value).toEqual({ count: 1 });
1522
+ // A copy whose source the same batch changes is refused before the batch writes anything.
1523
+ const laterId = await storage.mintId();
1524
+ const laterCopyId = await storage.mintId();
1525
+ const refused = await storage.commit([
1526
+ [
1527
+ { type: "conversation", value: { id: laterId } },
1528
+ {
1529
+ type: "document.copy",
1530
+ record: record(laterCopyId, laterId),
1531
+ source: { id: sourceId, at: "current" },
1532
+ },
1533
+ {
1534
+ type: "document.change",
1535
+ id: sourceId,
1536
+ content: { kind: "delta", version: 1, ops: [["s", ["count"], 3]] },
1537
+ },
1538
+ ],
1539
+ ], () => { }, context);
1540
+ expect(refused.stored).toBe(0);
1541
+ expect(refused.kind).toBe("refused");
1542
+ expect(await storage.conversation(laterId, context)).toBeUndefined();
1543
+ expect((await storage.document(sourceId, "current", context))?.value).toEqual({ count: 2 });
1544
+ }),
1545
+ createCase(options, "rejects every operation after close", async (storage) => {
1546
+ await createRoot(storage);
1547
+ await storage.close(context);
1548
+ await expect(storage.conversation(ROOT_CONVERSATION_ID, context)).rejects.toThrow("closed");
1549
+ await expect(commitWrites(storage, [{ type: "conversation", value: { id: ROOT_CONVERSATION_ID } }], context)).rejects.toThrow("closed");
1550
+ await expect(storage.mintId()).rejects.toThrow("closed");
1551
+ }),
1552
+ ];
1553
+ }
1554
+ //# sourceMappingURL=storage-conformance.js.map