@diffra-ai/durable 0.0.0-stage → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (411) hide show
  1. package/CHANGELOG.md +442 -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,1059 @@
1
+ import { BACKGROUND_CONTEXT } from "@diffra-ai/chord/context";
2
+ import { track, } from "@diffra-ai/chord/delta";
3
+ import { copyJson } from "@diffra-ai/chord/json";
4
+ import { addressId, checkRecordScope, checkRecordVersion, documentCreate, materializeDocumentValue, resolveAddress, } from "../documents.js";
5
+ import { ReadAfterWrite } from "../errors.js";
6
+ import { deliverSignal, isSettled, SubmissionSettled } from "../signals.js";
7
+ import { ROOT_CONVERSATION_ID } from "../types.js";
8
+ import { prepareForkDocumentCopies } from "./forks.js";
9
+ import { documentKey, incarnationKey, scopeKey, tableKeys } from "./keys.js";
10
+ /**
11
+ * Complete record after applying one change. Placement turns a queued input `placed` and a queued write `done`; a
12
+ * continue is never queued, so never placed. Only a placed input or continue can be answered. A settled record stays.
13
+ */
14
+ function applySubmissionChange(current, change) {
15
+ if (current.status === "done" || current.status === "unanswered")
16
+ return current;
17
+ if (change.status === "placed") {
18
+ if (current.status !== "queued")
19
+ throw new Error(`Submission ${current.id} is not queued`);
20
+ const status = current.type === "input" ? "placed" : "done";
21
+ return { ...current, status, entry: change.entry };
22
+ }
23
+ if (change.status === "done" && current.status !== "placed") {
24
+ throw new Error(`Submission ${current.id} is not a placed input or continue`);
25
+ }
26
+ // Queued and placed records carry no answer, reason, or detail; an unanswered input keeps its entry.
27
+ return { ...current, ...change };
28
+ }
29
+ const INTERNAL_SCAN_PAGE_SIZE = 256;
30
+ const EMPTY_OPERATIONS = [];
31
+ const TABLE_JSON_COPY_OPTIONS = { omitUndefinedProperties: true };
32
+ /**
33
+ * Transaction for one Session commit callback.
34
+ *
35
+ * Every asynchronous operation is tracked so callback settlement can reject and drain unfinished work. Session calls
36
+ * one settlement method, then either discards prepared changes or adopts them once after Storage succeeds.
37
+ */
38
+ export class Transaction {
39
+ #host;
40
+ #context;
41
+ #scope;
42
+ #pendingOperations = new Set();
43
+ #sealed = false;
44
+ #hasTableWrite = false;
45
+ /** Atomic batch; conversation and entry writes stage eagerly, while task and document writes assemble later. */
46
+ #writes = [];
47
+ #createdConversationIds = new Set();
48
+ #forkSourceConversationIds = new Set();
49
+ #forkSourceDocumentIds = new Set();
50
+ /** One entry per task touched by a public read, candidate write, or document-owner lookup. */
51
+ #tasksById = new Map();
52
+ /** Submissions created by this transaction, by ID. */
53
+ #submissions = new Map();
54
+ /** Submission settlements and placements in staging order; resolved against the latest candidate record during assembly. */
55
+ #submissionChanges = [];
56
+ /** Write and publication plans of every staged incarnation, built during assembly. */
57
+ #plans = [];
58
+ /** Every document acquisition or retirement marker in staging order. */
59
+ #documents = [];
60
+ /** Latest transaction-local incarnation or retirement marker at each logical address. */
61
+ #latestDocumentByAddress = new Map();
62
+ constructor(host, context, scope = {}) {
63
+ this.#host = host;
64
+ this.#context = context;
65
+ this.#scope = scope;
66
+ }
67
+ /** Internal: the context of the commit this transaction belongs to. */
68
+ get context() {
69
+ return this.#context;
70
+ }
71
+ /** Internal: whether a table write was staged, after which table reads throw `ReadAfterWrite`. */
72
+ get hasTableWrite() {
73
+ return this.#hasTableWrite;
74
+ }
75
+ /**
76
+ * Internal: whether `tx` is a transaction of a commit of the Session behind `host`. A brand check, so a proxy or
77
+ * another wrapper of a transaction is not one.
78
+ */
79
+ static ownedBy(tx, host) {
80
+ return #host in tx && tx.#host === host;
81
+ }
82
+ // ─── Table reads ────────────────────────────────────────────────────────
83
+ conversation(id) {
84
+ return this.#read("conversation", () => this.#host.storage.conversation(id, this.#context));
85
+ }
86
+ entry(first, second) {
87
+ const kind = typeof first === "number" ? undefined : first.kind;
88
+ const id = typeof first === "number" ? first : second;
89
+ return this.#read("entry", async () => {
90
+ const entry = (await this.#host.storage.entry(id, this.#context))?.entry;
91
+ return kind === undefined || entry?.kind === kind ? entry : undefined;
92
+ });
93
+ }
94
+ task(id) {
95
+ return this.#read("task", () => this.#committedTask(id));
96
+ }
97
+ scanConversations(query, limit, cursor) {
98
+ return this.#read("scanConversations", () => this.#host.storage.scanConversations(query, limit, cursor, this.#context));
99
+ }
100
+ scanEntries(query, limit, cursor) {
101
+ return this.#read("scanEntries", () => this.#host.storage.scanEntries(query, limit, cursor, this.#context));
102
+ }
103
+ latestHeadMarker(conversationId) {
104
+ return this.#read("latestHeadMarker", () => this.#host.latestHeadMarker(conversationId, this.#context));
105
+ }
106
+ latestEntryId(conversationId) {
107
+ return this.#read("latestEntryId", () => this.#host.latestEntryId(conversationId, this.#context));
108
+ }
109
+ scanTasks(query, limit, cursor) {
110
+ return this.#read("scanTasks", () => this.#host.storage.scanTasks(query, limit, cursor, this.#context));
111
+ }
112
+ /** Committed submission record. */
113
+ submission(id) {
114
+ return this.#read("submission", () => this.#host.storage.submission(id, this.#context));
115
+ }
116
+ /** Committed submission with a conversation-scoped request ID. */
117
+ submissionByRequest(conversationId, requestId) {
118
+ return this.#read("submissionByRequest", () => this.#host.storage.submissionByRequest(conversationId, requestId, this.#context));
119
+ }
120
+ // ─── Table writes ───────────────────────────────────────────────────────
121
+ createConversation(options) {
122
+ return this.#write(() => this.#stageConversation(undefined, options.ownership));
123
+ }
124
+ /** Internal final-form bootstrap path for the reserved root identity. */
125
+ createRootConversation() {
126
+ return this.#write(() => this.#stageConversation(undefined, { kind: "ownerless" }, ROOT_CONVERSATION_ID));
127
+ }
128
+ forkConversation(parentConversationId, at, options) {
129
+ return this.#write(() => this.#stageConversation({ conversationId: parentConversationId, at }, options.ownership));
130
+ }
131
+ async #stageConversation(parent, ownership, reservedId) {
132
+ const ownerTaskId = ownership.kind === "task" ? ownership.taskId : undefined;
133
+ const id = reservedId ?? (await this.#host.storage.mintId());
134
+ this.#assertOpen();
135
+ let owner;
136
+ if (ownerTaskId !== undefined) {
137
+ const task = await this.#currentTask(ownerTaskId);
138
+ this.#assertOpen();
139
+ if (task === undefined)
140
+ throw new Error(`Conversation owner task ${ownerTaskId} does not exist`);
141
+ owner = { conversationId: task.conversationId, taskId: ownerTaskId };
142
+ }
143
+ const record = {
144
+ id,
145
+ ...(parent === undefined ? {} : { parent }),
146
+ ...(owner === undefined ? {} : { owner }),
147
+ };
148
+ const copies = parent === undefined
149
+ ? []
150
+ : await prepareForkDocumentCopies(this.#host.storage, parent.conversationId, parent.at, id, this.#context);
151
+ this.#assertOpen();
152
+ for (const copy of copies) {
153
+ this.#forkSourceDocumentIds.add(copy.source.id);
154
+ const entry = {
155
+ addressId: addressId(copy.record),
156
+ address: copy.record,
157
+ target: { kind: "fork-copy", ...copy },
158
+ retireOnCommit: false,
159
+ };
160
+ this.#documents.push(entry);
161
+ this.#latestDocumentByAddress.set(entry.addressId, entry);
162
+ }
163
+ if (parent !== undefined)
164
+ this.#forkSourceConversationIds.add(parent.conversationId);
165
+ this.#createdConversationIds.add(id);
166
+ this.#writes.push({ type: "conversation", value: record });
167
+ await this.#host.conversationCreated(this, record);
168
+ this.#assertOpen();
169
+ return record;
170
+ }
171
+ appendEntry(first, second, third) {
172
+ if (typeof first === "number")
173
+ return this.#appendEntry(first, second);
174
+ return this.#appendEntry(second, { ...third, kind: first.kind });
175
+ }
176
+ #appendEntry(conversationId, value) {
177
+ return this.#write(async () => {
178
+ await this.#requireConversation(conversationId);
179
+ this.#assertOpen();
180
+ const id = await this.#host.storage.mintId();
181
+ this.#assertOpen();
182
+ const { head, ...rest } = value;
183
+ // Undefined `head` and `byTaskId` are omitted by the copy.
184
+ const record = copyJson({
185
+ ...rest,
186
+ id,
187
+ conversationId,
188
+ head: head === "self" ? id : head,
189
+ byTaskId: this.#scope.taskId,
190
+ }, TABLE_JSON_COPY_OPTIONS);
191
+ this.#writes.push({ type: "entry", value: record });
192
+ return record;
193
+ });
194
+ }
195
+ createTask(task, input, options) {
196
+ return this.#write(async () => {
197
+ if (options.submissionIds !== undefined) {
198
+ let trace;
199
+ let links;
200
+ for (let index = 0; index < options.submissionIds.length; index++) {
201
+ const id = options.submissionIds[index];
202
+ const submission = this.#submissions.get(id) ?? (await this.#host.storage.submission(id, this.#context));
203
+ if (index === 0)
204
+ trace = submission?.trace ?? "root";
205
+ else if (submission?.trace !== undefined) {
206
+ links ??= [];
207
+ links.push(submission.trace);
208
+ }
209
+ }
210
+ options = { ...options, trace, links };
211
+ }
212
+ const ownership = options.ownership;
213
+ let owner;
214
+ if (ownership.kind === "task") {
215
+ // Validated again against the owner's final candidate during assembly.
216
+ owner = await this.#currentTask(ownership.taskId);
217
+ this.#assertOpen();
218
+ if (owner === undefined)
219
+ throw new Error(`Task owner ${ownership.taskId} does not exist`);
220
+ if (options.background === true)
221
+ throw new TypeError("A child task cannot be background");
222
+ if (options.conversationId !== undefined && options.conversationId !== owner.conversationId) {
223
+ throw new Error(`A child task lives in its owner's conversation ${owner.conversationId}`);
224
+ }
225
+ }
226
+ const conversationId = owner?.conversationId ?? options.conversationId ?? this.#scope.conversationId;
227
+ if (conversationId === undefined)
228
+ throw new TypeError("Tx.createTask() requires options.conversationId");
229
+ await this.#requireConversation(conversationId);
230
+ this.#assertOpen();
231
+ const definition = task.definition;
232
+ const checkpoint = definition.initial(input);
233
+ const id = await this.#host.storage.mintId();
234
+ this.#assertOpen();
235
+ const record = copyJson({
236
+ id,
237
+ conversationId,
238
+ kind: definition.name,
239
+ version: definition.version,
240
+ input,
241
+ trace: options.trace === "root"
242
+ ? undefined
243
+ : (options.trace ?? this.#context.telemetry.propagation?.inject(this.#context.telemetry)),
244
+ links: options.links,
245
+ ...(owner === undefined ? {} : { owner: owner.id }),
246
+ background: options.background ?? false,
247
+ abortRequested: false,
248
+ ...(options.abandonOnRestart === true ? { abandonOnRestart: true } : {}),
249
+ state: { status: "pending", checkpoint },
250
+ }, TABLE_JSON_COPY_OPTIONS);
251
+ this.#tasksById.set(id, { write: { kind: "create", record } });
252
+ return id;
253
+ });
254
+ }
255
+ /** Create a raw submission record with a fresh ID; no admission rules apply. */
256
+ createSubmission(create) {
257
+ return this.#write(async () => {
258
+ await this.#requireConversation(create.conversationId);
259
+ this.#assertOpen();
260
+ const id = await this.#host.storage.mintId();
261
+ this.#assertOpen();
262
+ const record = copyJson({ ...create, id }, TABLE_JSON_COPY_OPTIONS);
263
+ this.#submissions.set(id, record);
264
+ return record;
265
+ });
266
+ }
267
+ /**
268
+ * Settle a submission. Resolved during assembly against the transaction's latest candidate record, falling back to
269
+ * committed state, so it is not a caller table read and works after the first table write.
270
+ */
271
+ settleSubmission(id, settlement) {
272
+ this.#assertOpen();
273
+ this.#hasTableWrite = true;
274
+ this.#submissionChanges.push({ id, change: copyJson(settlement) });
275
+ }
276
+ /** Place a queued submission at `entry`; resolved during assembly like `settleSubmission()`. */
277
+ placeSubmission(id, entry) {
278
+ this.#assertOpen();
279
+ this.#hasTableWrite = true;
280
+ this.#submissionChanges.push({ id, change: { status: "placed", entry } });
281
+ }
282
+ /** Deliver a signal to a task (spec suspendable §3.2): a read of the task, then a write of it when the key changes. */
283
+ signal(taskId, token, key, value) {
284
+ return this.#read("signal", async () => {
285
+ const committed = await this.#committedTask(taskId);
286
+ // Read after the await: a delivery started alongside, in `Promise.all()`, may have staged the key since.
287
+ const record = this.#tasksById.get(taskId)?.write?.record ?? committed;
288
+ const delivered = deliverSignal(record, token, key, value, this.#host.now());
289
+ if (delivered.record !== undefined)
290
+ this.setTask(delivered.record);
291
+ return delivered.result;
292
+ });
293
+ }
294
+ /**
295
+ * Internal: replace one task record. Tasks change their own state through their runtime. A live replacement keeps the
296
+ * memos an earlier write of this transaction staged, so no write erases another.
297
+ */
298
+ setTask(value) {
299
+ this.#assertOpen();
300
+ this.#hasTableWrite = true;
301
+ this.#stageTask(value);
302
+ }
303
+ /** Stage a task record over the transaction's candidate, also during assembly. */
304
+ #stageTask(value) {
305
+ const task = this.#taskEntry(value.id);
306
+ const candidate = task.write?.record;
307
+ if (candidate?.state.status === "terminal") {
308
+ throw new Error(`Task ${value.id} already has a terminal candidate`);
309
+ }
310
+ if (candidate !== undefined && candidate.conversationId !== value.conversationId) {
311
+ throw new Error(`Task ${value.id} cannot change conversations`);
312
+ }
313
+ // A live replacement keeps the memos an earlier write staged, such as a signal delivered to a task whose own commit
314
+ // then changes its state: no write erases another.
315
+ const status = value.state.status;
316
+ const keeps = candidate?.memos !== undefined && status !== "terminal" && status !== "completing";
317
+ const composed = keeps ? { ...value, memos: { ...candidate.memos, ...value.memos } } : value;
318
+ task.write = {
319
+ kind: task.write?.kind === "create" ? "create" : "replace",
320
+ record: copyJson(this.#stampTimes(composed, candidate), TABLE_JSON_COPY_OPTIONS),
321
+ };
322
+ }
323
+ /** Internal: candidate records of the tasks this transaction created or replaced so far. */
324
+ stagedTasks() {
325
+ const records = [];
326
+ for (const task of this.#tasksById.values())
327
+ if (task.write !== undefined)
328
+ records.push(task.write.record);
329
+ return records;
330
+ }
331
+ /** Internal: IDs of the tasks this transaction creates. */
332
+ createdTaskIds() {
333
+ const ids = [];
334
+ for (const [id, task] of this.#tasksById)
335
+ if (task.write?.kind === "create")
336
+ ids.push(id);
337
+ return ids;
338
+ }
339
+ /** Internal: conversations this transaction created or forked so far. */
340
+ stagedConversations() {
341
+ const records = [];
342
+ for (const write of this.#writes)
343
+ if (write.type === "conversation")
344
+ records.push(write.value);
345
+ return records;
346
+ }
347
+ doc(token, ...args) {
348
+ try {
349
+ this.#assertOpen();
350
+ const definition = token.definition;
351
+ const resolved = resolveAddress(definition, args);
352
+ this.#assertTaskDocumentsOpen(resolved);
353
+ const latest = this.#latestDocumentByAddress.get(resolved.id);
354
+ if (latest !== undefined && !latest.retireOnCommit) {
355
+ if (latest.draftPromise !== undefined)
356
+ return latest.draftPromise;
357
+ if (latest.target?.kind === "fork-copy") {
358
+ latest.draftPromise = this.#track(this.#acquireForkCopy(latest, definition, latest.target));
359
+ return latest.draftPromise;
360
+ }
361
+ }
362
+ const seed = definition.family === true ? copyJson(args[resolved.nextArgument]) : undefined;
363
+ const docEntry = {
364
+ addressId: resolved.id,
365
+ address: resolved.address,
366
+ definition,
367
+ retireOnCommit: false,
368
+ };
369
+ this.#documents.push(docEntry);
370
+ this.#latestDocumentByAddress.set(docEntry.addressId, docEntry);
371
+ // Capture retirement before awaiting so a pending old acquisition and its replacement stay distinct.
372
+ docEntry.draftPromise = this.#track(this.#acquire(docEntry, seed, latest?.retireOnCommit === true));
373
+ return docEntry.draftPromise;
374
+ }
375
+ catch (error) {
376
+ return Promise.reject(error);
377
+ }
378
+ }
379
+ retireDoc(token, ...args) {
380
+ try {
381
+ this.#assertOpen();
382
+ const definition = token.definition;
383
+ const resolved = resolveAddress(definition, args);
384
+ const latest = this.#latestDocumentByAddress.get(resolved.id);
385
+ if (latest?.retireOnCommit)
386
+ return Promise.resolve();
387
+ if (latest?.target?.kind === "fork-copy") {
388
+ checkRecordScope(definition, latest.target.record);
389
+ latest.retireOnCommit = true;
390
+ return Promise.resolve();
391
+ }
392
+ if (latest?.draftPromise !== undefined) {
393
+ // Retirement of an acquired draft persists its final content before retirement.
394
+ latest.retireOnCommit = true;
395
+ return this.#track(latest.draftPromise.then(() => undefined));
396
+ }
397
+ const entry = {
398
+ addressId: resolved.id,
399
+ address: resolved.address,
400
+ definition,
401
+ retireOnCommit: true,
402
+ };
403
+ this.#documents.push(entry);
404
+ this.#latestDocumentByAddress.set(entry.addressId, entry);
405
+ return this.#track(this.#findRetirement(entry));
406
+ }
407
+ catch (error) {
408
+ return Promise.reject(error);
409
+ }
410
+ }
411
+ async #acquire(entry, seed, skipLoad) {
412
+ const definition = entry.definition;
413
+ const loaded = skipLoad
414
+ ? undefined
415
+ : await this.#host.load(definition, entry.addressId, entry.address, this.#context);
416
+ this.#assertOpen();
417
+ if (loaded !== undefined) {
418
+ checkRecordScope(definition, loaded.record);
419
+ checkRecordVersion(definition, loaded.record, loaded.storedVersion);
420
+ entry.target = { kind: "loaded", document: loaded };
421
+ entry.change = loaded.tracker.beginChange();
422
+ return entry.change.state;
423
+ }
424
+ const scope = entry.address.scope;
425
+ if (scope.kind === "conversation")
426
+ await this.#requireConversation(scope.conversationId);
427
+ if (scope.kind === "task") {
428
+ const task = await this.#currentTask(scope.taskId);
429
+ if (task === undefined)
430
+ throw new Error(`Task ${scope.taskId} does not exist`);
431
+ if (task.state.status === "terminal")
432
+ throw new Error(`Task ${scope.taskId} is terminal`);
433
+ }
434
+ this.#assertOpen();
435
+ const value = copyJson(definition.family === true ? definition.initial(seed) : definition.initial());
436
+ const id = await this.#host.storage.mintId();
437
+ this.#assertOpen();
438
+ const tracker = track(value);
439
+ entry.target = {
440
+ kind: "created",
441
+ record: documentCreate(definition, entry.address, id),
442
+ version: definition.version,
443
+ tracker,
444
+ };
445
+ entry.change = tracker.beginChange();
446
+ return entry.change.state;
447
+ }
448
+ async #acquireForkCopy(entry, definition, target) {
449
+ const stored = await this.#host.storage.document(target.source.id, target.source.at, this.#context);
450
+ this.#assertOpen();
451
+ if (stored === undefined) {
452
+ throw new Error(`Fork source document ${target.source.id} cannot be read`);
453
+ }
454
+ if (stored.record.scope.kind !== "conversation" ||
455
+ stored.record.kind !== target.record.kind ||
456
+ stored.record.key !== target.record.key ||
457
+ stored.record.history !== target.record.history ||
458
+ stored.record.fork !== target.record.fork) {
459
+ throw new Error(`Fork source document ${target.source.id} does not match the copied record`);
460
+ }
461
+ const value = materializeDocumentValue(definition, target.record, stored.version, stored.value);
462
+ const tracker = track(value);
463
+ entry.definition = definition;
464
+ entry.target = { kind: "created", record: target.record, version: definition.version, tracker };
465
+ entry.change = tracker.beginChange();
466
+ return entry.change.state;
467
+ }
468
+ async #findRetirement(entry) {
469
+ const gate = this.#host.touch(documentKey(entry.addressId));
470
+ if (gate !== undefined)
471
+ await gate;
472
+ const record = this.#host.cached(entry.addressId)?.record ??
473
+ (await this.#host.storage.findDocument(entry.address, "current", this.#context));
474
+ this.#assertOpen();
475
+ if (record === undefined)
476
+ return;
477
+ checkRecordScope(entry.definition, record);
478
+ entry.target = { kind: "retire-only", record };
479
+ }
480
+ // ─── Settlement ─────────────────────────────────────────────────────────
481
+ /** Seal after callback failure: abort every change and observe every pending operation. */
482
+ async settleFailure() {
483
+ this.#sealed = true;
484
+ this.#abortChanges();
485
+ await Promise.allSettled(this.#pendingOperations);
486
+ this.#context = BACKGROUND_CONTEXT;
487
+ }
488
+ /**
489
+ * Seal after callback success, prepare every open change, and assemble the atomic batch.
490
+ * Any failure aborts every change before Storage admission.
491
+ */
492
+ async settleSuccess() {
493
+ this.#sealed = true;
494
+ if (this.#pendingOperations.size > 0) {
495
+ this.#abortChanges();
496
+ await Promise.allSettled(this.#pendingOperations);
497
+ this.#context = BACKGROUND_CONTEXT;
498
+ throw new Error("Session commit callback settled before its pending Tx operations");
499
+ }
500
+ try {
501
+ // Synchronously prepare every open change; this revokes every draft.
502
+ for (const document of this.#documents) {
503
+ if (document.change !== undefined)
504
+ document.prepared = document.change.prepare();
505
+ }
506
+ return await this.#assemble();
507
+ }
508
+ catch (error) {
509
+ this.#abortChanges();
510
+ throw error;
511
+ }
512
+ finally {
513
+ this.#context = BACKGROUND_CONTEXT;
514
+ }
515
+ }
516
+ /** Abort every prepared change after Storage failure or when no write is required. */
517
+ discard() {
518
+ this.#abortChanges();
519
+ }
520
+ /**
521
+ * Internal: what a deferred commit holds in memory instead of storing (`CommitPersistence`), each changed incarnation
522
+ * with its operations and whether they selected a base; `undefined` when the commit must be stored. It may be held
523
+ * only when every write changes an existing `latest`, `initial`-fork conversation document at its stored version.
524
+ */
525
+ holdable() {
526
+ if (this.#writes.some((write) => write.type !== "document.change"))
527
+ return undefined;
528
+ const held = [];
529
+ for (const plan of this.#plans) {
530
+ const { content, change } = plan;
531
+ if (content === undefined && !plan.retire)
532
+ continue;
533
+ if (plan.retire || change?.loaded === undefined || content?.type !== "document.change")
534
+ return undefined;
535
+ const { loaded, prepared, version } = change;
536
+ const record = loaded.record;
537
+ if (record.scope.kind !== "conversation" || record.history !== "latest" || record.fork !== "initial") {
538
+ return undefined;
539
+ }
540
+ // A migration stores a base at once.
541
+ if (loaded.storedVersion !== version)
542
+ return undefined;
543
+ held.push({ loaded, ops: prepared.ops, base: content.content.kind === "base" });
544
+ }
545
+ return held;
546
+ }
547
+ /**
548
+ * Internal: adopt a held commit (`holdable()`) in memory only. Trackers advance by pointer swap; stored versions and
549
+ * delta counts stay, as nothing was stored. Returns its publication for the Session's own observers.
550
+ */
551
+ adoptHeld() {
552
+ const publications = [];
553
+ for (const plan of this.#plans) {
554
+ // Every plan of a held commit changes or reads a loaded incarnation (`holdable()`).
555
+ const { tracker, prepared, version, loaded } = plan.change;
556
+ if (prepared.ops.length === 0) {
557
+ prepared.abort();
558
+ continue;
559
+ }
560
+ tracker.adopt(prepared);
561
+ const record = loaded.record;
562
+ const conversationId = plan.conversationId;
563
+ publications.push({
564
+ type: "document",
565
+ kind: "change",
566
+ record,
567
+ conversationId,
568
+ version,
569
+ value: prepared.value,
570
+ ops: prepared.ops,
571
+ });
572
+ }
573
+ return publications;
574
+ }
575
+ /**
576
+ * Internal: store the held changes of every incarnation this commit reads or writes in front of its own, so a stored
577
+ * document never misses an operation its later ones build on. Called right before Storage admission, after every
578
+ * fallible step, because it empties the holds: a failure earlier keeps them. Returns the holds it took.
579
+ */
580
+ takeHeld(held) {
581
+ const taken = [];
582
+ for (const plan of this.#plans) {
583
+ // A new incarnation holds nothing yet.
584
+ if (plan.kind === "new")
585
+ continue;
586
+ const hold = held(plan.record.id);
587
+ if (hold === undefined)
588
+ continue;
589
+ taken.push(hold);
590
+ const own = plan.content?.type === "document.change" ? plan.content : undefined;
591
+ const change = plan.change;
592
+ const value = change?.prepared.value ?? hold.loaded.tracker.value;
593
+ const stored = storeHeld(hold, change?.prepared.ops ?? EMPTY_OPERATIONS, value, hold.loaded.valueVersion);
594
+ // A base this commit selected or must write covers what was held.
595
+ const content = own?.content.kind === "base" ? own.content : stored.content;
596
+ const write = { type: "document.change", id: plan.record.id, content };
597
+ if (own !== undefined)
598
+ this.#writes[this.#writes.indexOf(own)] = write;
599
+ else
600
+ this.#insertBeforeRetirement(write);
601
+ if (!plan.retire)
602
+ plan.held = { ops: stored.ops, observed: own !== undefined };
603
+ plan.content = write;
604
+ // Held documents are conversation documents; one this commit only read has no owner resolved yet.
605
+ if (plan.record.scope.kind === "conversation")
606
+ plan.conversationId = plan.record.scope.conversationId;
607
+ }
608
+ return taken;
609
+ }
610
+ /**
611
+ * Internal: the keys this commit writes, once settled (and after `takeHeld()`), for the Session's unpublished write
612
+ * set: its table records, and the address and incarnation of every document it creates, changes, or retires, with
613
+ * the scope of every incarnation it creates or retires.
614
+ */
615
+ writeKeys() {
616
+ const keys = [];
617
+ tableKeys(this.#writes, keys);
618
+ for (const plan of this.#plans) {
619
+ if (plan.content === undefined && !plan.retire)
620
+ continue;
621
+ keys.push(documentKey(plan.addressId), incarnationKey(plan.record.id));
622
+ if (plan.retire || plan.kind === "new")
623
+ keys.push(scopeKey(plan.record.scope));
624
+ }
625
+ return keys;
626
+ }
627
+ /** Stage a content write for an incarnation, before its retirement when it retires. */
628
+ #insertBeforeRetirement(write) {
629
+ const at = this.#writes.findIndex((candidate) => candidate.type === "document.retire" && candidate.id === write.id);
630
+ if (at < 0)
631
+ this.#writes.push(write);
632
+ else
633
+ this.#writes.splice(at, 0, write);
634
+ }
635
+ /** Adopt every prepared change by pointer swap after Storage success and describe the publication. */
636
+ adopt(seq) {
637
+ const publications = [];
638
+ // Only when the commit stored held changes: then what Storage got differs from what memory adopted.
639
+ let stored;
640
+ for (const plan of this.#plans) {
641
+ const committed = plan.kind === "committed";
642
+ let record = plan.kind === "committed" ? plan.record : { ...plan.record, createdAt: seq };
643
+ if (plan.retire)
644
+ record = { ...record, retiredAt: seq };
645
+ const change = plan.change;
646
+ if (change !== undefined) {
647
+ const { tracker, prepared, loaded, version } = change;
648
+ // A new incarnation is adopted unless it retires in the same commit; a loaded one only when it changed.
649
+ if (loaded === undefined ? !plan.retire : prepared.ops.length > 0)
650
+ tracker.adopt(prepared);
651
+ else
652
+ prepared.abort();
653
+ if (loaded !== undefined) {
654
+ if (loaded.storedVersion < version)
655
+ loaded.storedVersion = version;
656
+ if (plan.content?.type === "document.change") {
657
+ if (plan.content.content.kind === "base")
658
+ loaded.deltasSinceBase = 0;
659
+ else
660
+ loaded.deltasSinceBase++;
661
+ }
662
+ }
663
+ else if (!plan.retire) {
664
+ this.#host.install({
665
+ addressId: plan.addressId,
666
+ record,
667
+ storedVersion: version,
668
+ valueVersion: version,
669
+ deltasSinceBase: 0,
670
+ tracker,
671
+ });
672
+ }
673
+ }
674
+ if (plan.retire && committed)
675
+ this.#host.evict(plan.addressId, record.id);
676
+ const publication = describe(plan, record);
677
+ if (publication === undefined)
678
+ continue;
679
+ const held = plan.held;
680
+ if (held === undefined) {
681
+ publications.push(publication);
682
+ stored?.push(publication);
683
+ continue;
684
+ }
685
+ stored ??= [...publications];
686
+ if (held.observed)
687
+ publications.push(publication);
688
+ // Only a document change of a loaded incarnation carries held operations; a retirement is published alone.
689
+ stored.push(publication.type === "document" && publication.kind === "change"
690
+ ? { ...publication, ops: held.ops }
691
+ : publication);
692
+ }
693
+ return { observed: publications, stored: stored ?? publications };
694
+ }
695
+ async #assemble() {
696
+ const storage = this.#host.storage;
697
+ const plans = this.#plans;
698
+ for (const document of this.#documents) {
699
+ const plan = planDocument(document);
700
+ if (plan !== undefined)
701
+ plans.push(plan);
702
+ }
703
+ this.#rejectForkSourceWrites(plans);
704
+ await this.#validateOwners();
705
+ for (const [id, task] of this.#tasksById) {
706
+ if (task.write?.kind !== "replace")
707
+ continue;
708
+ const committed = await this.#committedTask(id);
709
+ if (committed === undefined)
710
+ throw new Error(`Task ${id} does not exist`);
711
+ if (committed.state.status === "terminal")
712
+ throw new Error(`Task ${id} is already terminal`);
713
+ if (committed.conversationId !== task.write.record.conversationId) {
714
+ throw new Error(`Task ${id} cannot change conversations`);
715
+ }
716
+ }
717
+ // Terminal settlement retires every task document, including ones created by this transaction.
718
+ const terminalTaskIds = new Set();
719
+ for (const task of this.#tasksById.values()) {
720
+ if (task.write?.record.state.status === "terminal")
721
+ terminalTaskIds.add(task.write.record.id);
722
+ }
723
+ if (terminalTaskIds.size > 0) {
724
+ const retiring = new Set();
725
+ for (const plan of plans) {
726
+ const scope = plan.record.scope;
727
+ if (scope.kind !== "task" || !terminalTaskIds.has(scope.taskId))
728
+ continue;
729
+ plan.retire = true;
730
+ retiring.add(plan.record.id);
731
+ }
732
+ const retire = (record) => {
733
+ if (retiring.has(record.id))
734
+ return;
735
+ plans.push({ kind: "committed", addressId: addressId(record), record, retire: true });
736
+ retiring.add(record.id);
737
+ };
738
+ for (const taskId of terminalTaskIds) {
739
+ if (this.#tasksById.get(taskId)?.write?.kind === "create")
740
+ continue;
741
+ // The Session knows the documents of the tasks it created; any other task's are scanned.
742
+ const gate = this.#host.touch(scopeKey({ kind: "task", taskId }));
743
+ if (gate !== undefined)
744
+ await gate;
745
+ const known = this.#host.taskDocuments(taskId);
746
+ if (known !== undefined) {
747
+ for (const record of known)
748
+ retire(record);
749
+ continue;
750
+ }
751
+ let cursor;
752
+ do {
753
+ const page = await storage.scanDocuments({ scope: { kind: "task", taskId }, at: "current" }, INTERNAL_SCAN_PAGE_SIZE, cursor, this.#context);
754
+ for (const record of page.items)
755
+ retire(record);
756
+ cursor = page.next;
757
+ } while (cursor !== undefined);
758
+ }
759
+ }
760
+ // Resolve publication ownership before Storage admission so adoption remains synchronous.
761
+ for (const plan of plans) {
762
+ if (!publishes(plan))
763
+ continue;
764
+ const scope = plan.record.scope;
765
+ if (scope.kind === "conversation")
766
+ plan.conversationId = scope.conversationId;
767
+ if (scope.kind !== "task")
768
+ continue;
769
+ const task = this.#taskEntry(scope.taskId);
770
+ if (task.publicationConversationId === undefined) {
771
+ const current = await this.#currentTask(scope.taskId);
772
+ if (current !== undefined)
773
+ task.publicationConversationId = current.conversationId;
774
+ }
775
+ plan.conversationId = task.publicationConversationId;
776
+ }
777
+ // Created settled, or settled by a change: each one with `notify` signals its task (spec suspendable §4.5).
778
+ const settling = [...this.#submissions.values()].filter(isSettled);
779
+ for (const { id, change } of this.#submissionChanges) {
780
+ const current = this.#submissions.get(id) ?? (await storage.submission(id, this.#context));
781
+ if (current === undefined)
782
+ throw new Error(`Submission ${id} does not exist`);
783
+ const next = applySubmissionChange(current, change);
784
+ if (next === current)
785
+ continue;
786
+ this.#submissions.set(id, next);
787
+ if (isSettled(next))
788
+ settling.push(next);
789
+ }
790
+ for (const record of settling)
791
+ if (record.notify !== undefined)
792
+ await this.#notify(record, record.notify);
793
+ const writes = this.#writes;
794
+ for (const value of this.#submissions.values())
795
+ writes.push({ type: "submission", value });
796
+ for (const task of this.#tasksById.values()) {
797
+ if (task.write !== undefined)
798
+ writes.push({ type: "task", value: task.write.record });
799
+ }
800
+ for (const plan of plans) {
801
+ const change = plan.change;
802
+ // Checkpoint predicates run last, after every validation.
803
+ if (plan.content?.type === "document.change" && plan.content.content.kind === "delta" && change?.loaded) {
804
+ const { prepared, version } = change;
805
+ const info = { deltasSinceBase: change.loaded.deltasSinceBase };
806
+ if (change.definition.checkpointWhen(prepared.value, prepared.ops, info)) {
807
+ plan.content = { ...plan.content, content: { version, kind: "base", value: prepared.value } };
808
+ }
809
+ }
810
+ if (plan.content !== undefined)
811
+ writes.push(plan.content);
812
+ if (plan.retire)
813
+ writes.push({ type: "document.retire", id: plan.record.id });
814
+ }
815
+ return writes;
816
+ }
817
+ // ─── Helpers ────────────────────────────────────────────────────────────
818
+ /**
819
+ * Deliver `SubmissionSettled` for a submission this commit settles, against the transaction's latest candidate of the
820
+ * task; a delivery the task refuses changes nothing and fails nothing.
821
+ */
822
+ async #notify(record, notify) {
823
+ const committed = await this.#committedTask(notify.taskId);
824
+ const target = this.#tasksById.get(notify.taskId)?.write?.record ?? committed;
825
+ const delivered = deliverSignal(target, SubmissionSettled, notify.key, record, this.#host.now());
826
+ if (delivered.record !== undefined)
827
+ this.#stageTask(delivered.record);
828
+ }
829
+ /**
830
+ * New owned work needs a live owner, judged on the owner's final candidate: not `completing`, terminal, or
831
+ * abort-marked. A task therefore cannot create owned work in the commit that finishes it (spec §5.5).
832
+ */
833
+ async #validateOwners() {
834
+ const owners = [];
835
+ for (const write of this.#writes) {
836
+ if (write.type !== "conversation" || write.value.owner === undefined)
837
+ continue;
838
+ owners.push({ what: "Conversation owner task", taskId: write.value.owner.taskId });
839
+ }
840
+ for (const task of this.#tasksById.values()) {
841
+ const record = task.write?.kind === "create" ? task.write.record : undefined;
842
+ if (record?.owner !== undefined)
843
+ owners.push({ what: "Task owner", taskId: record.owner });
844
+ }
845
+ for (const { what, taskId } of owners) {
846
+ const task = await this.#currentTask(taskId);
847
+ if (task === undefined)
848
+ throw new Error(`${what} ${taskId} does not exist`);
849
+ if (task.state.status === "terminal" || task.state.status === "completing") {
850
+ throw new Error(`${what} ${taskId} is ${task.state.status}`);
851
+ }
852
+ if (task.abortRequested)
853
+ throw new Error(`${what} ${taskId} is abort-marked`);
854
+ }
855
+ }
856
+ #rejectForkSourceWrites(plans) {
857
+ for (const plan of plans) {
858
+ if (plan.content === undefined && !plan.retire)
859
+ continue;
860
+ const record = plan.record;
861
+ if (this.#forkSourceDocumentIds.has(record.id)) {
862
+ throw new Error(`Cannot change fork source document ${record.id} in the fork transaction`);
863
+ }
864
+ const scope = plan.record.scope;
865
+ if (scope.kind === "conversation" &&
866
+ this.#forkSourceConversationIds.has(scope.conversationId) &&
867
+ record.scope.kind === "conversation" &&
868
+ record.fork === "current") {
869
+ throw new Error(`Cannot fork conversation ${scope.conversationId} while changing its current-policy documents`);
870
+ }
871
+ }
872
+ }
873
+ #abortChanges() {
874
+ for (const document of this.#documents)
875
+ document.change?.abort();
876
+ }
877
+ #assertOpen() {
878
+ if (this.#sealed)
879
+ throw new Error("Transaction has settled");
880
+ }
881
+ #assertTaskDocumentsOpen(resolved) {
882
+ const scope = resolved.address.scope;
883
+ if (scope.kind === "task" && this.#tasksById.get(scope.taskId)?.write?.record.state.status === "terminal") {
884
+ throw new Error(`Task ${scope.taskId} is terminal`);
885
+ }
886
+ }
887
+ /** Register an operation so callback settlement can reject and drain it. */
888
+ #track(operation) {
889
+ this.#pendingOperations.add(operation);
890
+ const settle = () => {
891
+ this.#pendingOperations.delete(operation);
892
+ };
893
+ operation.then(settle, settle);
894
+ return operation;
895
+ }
896
+ #read(method, read) {
897
+ try {
898
+ this.#assertOpen();
899
+ if (this.#hasTableWrite)
900
+ throw new ReadAfterWrite(`Tx.${method}()`);
901
+ return this.#track(read());
902
+ }
903
+ catch (error) {
904
+ return Promise.reject(error);
905
+ }
906
+ }
907
+ #write(write) {
908
+ try {
909
+ this.#assertOpen();
910
+ this.#hasTableWrite = true;
911
+ return this.#track(write());
912
+ }
913
+ catch (error) {
914
+ return Promise.reject(error);
915
+ }
916
+ }
917
+ async #requireConversation(id) {
918
+ if (this.#createdConversationIds.has(id))
919
+ return;
920
+ if ((await this.#host.storage.conversation(id, this.#context)) === undefined) {
921
+ throw new Error(`Conversation ${id} does not exist`);
922
+ }
923
+ }
924
+ /**
925
+ * Lifecycle times: `startedAt` on the first change to `running`, `endedAt` on the change to `terminal`. Once set,
926
+ * they carry over from the replaced record; records written before they existed lack them.
927
+ */
928
+ #stampTimes(value, candidate) {
929
+ const status = value.state.status;
930
+ const now = (stamps) => (stamps ? this.#host.now() : undefined);
931
+ const startedAt = candidate?.startedAt ?? value.startedAt ?? now(status === "running");
932
+ const endedAt = candidate?.endedAt ?? value.endedAt ?? now(status === "terminal");
933
+ if (startedAt === value.startedAt && endedAt === value.endedAt)
934
+ return value;
935
+ return {
936
+ ...value,
937
+ ...(startedAt === undefined ? {} : { startedAt }),
938
+ ...(endedAt === undefined ? {} : { endedAt }),
939
+ };
940
+ }
941
+ #taskEntry(id) {
942
+ let task = this.#tasksById.get(id);
943
+ if (task === undefined) {
944
+ task = {};
945
+ this.#tasksById.set(id, task);
946
+ }
947
+ return task;
948
+ }
949
+ /** Latest candidate task record, falling back to committed state; not a caller table read. */
950
+ async #currentTask(id) {
951
+ return this.#tasksById.get(id)?.write?.record ?? (await this.#committedTask(id));
952
+ }
953
+ #committedTask(id) {
954
+ const task = this.#taskEntry(id);
955
+ task.committedRead ??= this.#host.storage.task(id, this.#context);
956
+ return task.committedRead;
957
+ }
958
+ }
959
+ /** Plan of one staged document: its record, content write, and prepared change. Retirement is decided later. */
960
+ function planDocument(document) {
961
+ const target = document.target;
962
+ if (target === undefined)
963
+ return undefined;
964
+ const plan = { addressId: document.addressId, retire: document.retireOnCommit };
965
+ switch (target.kind) {
966
+ case "created": {
967
+ const prepared = document.prepared;
968
+ const { record, version, tracker } = target;
969
+ const content = { version, kind: "base", value: prepared.value };
970
+ return {
971
+ ...plan,
972
+ kind: "new",
973
+ record,
974
+ content: { type: "document.create", record, content },
975
+ change: { tracker, prepared, version },
976
+ };
977
+ }
978
+ case "fork-copy":
979
+ return {
980
+ ...plan,
981
+ kind: "new",
982
+ record: target.record,
983
+ content: { type: "document.copy", record: target.record, source: target.source },
984
+ };
985
+ case "retire-only":
986
+ return { ...plan, kind: "committed", record: target.record };
987
+ case "loaded": {
988
+ const loaded = target.document;
989
+ const definition = document.definition;
990
+ const prepared = document.prepared;
991
+ const version = definition.version;
992
+ const id = loaded.record.id;
993
+ // A version change stores a base even without operations; otherwise only a change stores a delta.
994
+ const content = loaded.storedVersion < version
995
+ ? { type: "document.change", id, content: { version, kind: "base", value: prepared.value } }
996
+ : prepared.ops.length > 0
997
+ ? { type: "document.change", id, content: { version, kind: "delta", ops: prepared.ops } }
998
+ : undefined;
999
+ const change = {
1000
+ tracker: loaded.tracker,
1001
+ prepared,
1002
+ version,
1003
+ loaded,
1004
+ definition,
1005
+ };
1006
+ return {
1007
+ ...plan,
1008
+ kind: "committed",
1009
+ record: loaded.record,
1010
+ change,
1011
+ ...(content === undefined ? {} : { content }),
1012
+ };
1013
+ }
1014
+ }
1015
+ }
1016
+ /** The publication of one adopted plan, if it publishes (`publishes()`), with `record` as committed. */
1017
+ function describe(plan, record) {
1018
+ const conversationId = plan.conversationId;
1019
+ if (plan.retire)
1020
+ return { type: "document", kind: "retire", record, conversationId };
1021
+ if (plan.content?.type === "document.copy") {
1022
+ return { type: "document.copy", record, conversationId: conversationId, source: plan.content.source };
1023
+ }
1024
+ const change = plan.change;
1025
+ if (change === undefined || !publishes(plan))
1026
+ return undefined;
1027
+ const ops = change.loaded === undefined ? EMPTY_OPERATIONS : change.prepared.ops;
1028
+ return {
1029
+ type: "document",
1030
+ kind: "change",
1031
+ record,
1032
+ conversationId,
1033
+ version: change.version,
1034
+ value: change.prepared.value,
1035
+ ops,
1036
+ };
1037
+ }
1038
+ /**
1039
+ * Take a hold's changes after `ops`, a commit's own on top of them, as one stored content for an incarnation now at
1040
+ * `value`, and the operations a reader of the stored state applies to reach it: the folded ones, or a root replacement
1041
+ * after the queue overflowed, which stores a base, as does a hold whose commits selected one.
1042
+ */
1043
+ export function storeHeld(hold, ops, value, version) {
1044
+ hold.pending.push(ops);
1045
+ const taken = hold.pending.take();
1046
+ if (taken.kind === "replace")
1047
+ return { content: { version, kind: "base", value }, ops: [["r", value]] };
1048
+ if (hold.base)
1049
+ return { content: { version, kind: "base", value }, ops: taken.ops };
1050
+ return { content: { version, kind: "delta", ops: taken.ops }, ops: taken.ops };
1051
+ }
1052
+ /**
1053
+ * Whether adoption publishes the plan: every creation, copy, and retirement, and a loaded incarnation that writes
1054
+ * content, which includes a migration-only base so observers of the older shape receive the new value.
1055
+ */
1056
+ function publishes(plan) {
1057
+ return plan.retire || plan.change?.loaded === undefined || plan.content !== undefined;
1058
+ }
1059
+ //# sourceMappingURL=transaction.js.map