@earendil-works/pi-durable 1.4.0 → 1.5.0

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 (221) hide show
  1. package/CHANGELOG.md +186 -0
  2. package/README.md +181 -84
  3. package/dist/codemode/codemode.d.ts +4 -4
  4. package/dist/codemode/codemode.d.ts.map +1 -1
  5. package/dist/codemode/codemode.js +9 -12
  6. package/dist/codemode/codemode.js.map +1 -1
  7. package/dist/codemode/models.js +4 -4
  8. package/dist/codemode/models.js.map +1 -1
  9. package/dist/env/index.d.ts +12 -10
  10. package/dist/env/index.d.ts.map +1 -1
  11. package/dist/env/index.js.map +1 -1
  12. package/dist/env/node-watch.d.ts +3 -3
  13. package/dist/env/node-watch.d.ts.map +1 -1
  14. package/dist/env/node-watch.js +18 -16
  15. package/dist/env/node-watch.js.map +1 -1
  16. package/dist/env/node.d.ts +2 -2
  17. package/dist/env/node.d.ts.map +1 -1
  18. package/dist/env/node.js +1 -1
  19. package/dist/env/node.js.map +1 -1
  20. package/dist/errors.d.ts +18 -2
  21. package/dist/errors.d.ts.map +1 -1
  22. package/dist/errors.js +26 -3
  23. package/dist/errors.js.map +1 -1
  24. package/dist/harness/agent.d.ts.map +1 -1
  25. package/dist/harness/agent.js +10 -2
  26. package/dist/harness/agent.js.map +1 -1
  27. package/dist/harness/compaction.d.ts.map +1 -1
  28. package/dist/harness/compaction.js +19 -2
  29. package/dist/harness/compaction.js.map +1 -1
  30. package/dist/harness/context.d.ts +23 -7
  31. package/dist/harness/context.d.ts.map +1 -1
  32. package/dist/harness/context.js +71 -25
  33. package/dist/harness/context.js.map +1 -1
  34. package/dist/harness/define.d.ts +7 -3
  35. package/dist/harness/define.d.ts.map +1 -1
  36. package/dist/harness/define.js +4 -0
  37. package/dist/harness/define.js.map +1 -1
  38. package/dist/harness/generation.d.ts +38 -5
  39. package/dist/harness/generation.d.ts.map +1 -1
  40. package/dist/harness/generation.js +445 -96
  41. package/dist/harness/generation.js.map +1 -1
  42. package/dist/harness/harness.d.ts +2 -0
  43. package/dist/harness/harness.d.ts.map +1 -1
  44. package/dist/harness/harness.js +87 -62
  45. package/dist/harness/harness.js.map +1 -1
  46. package/dist/harness/inbox.d.ts +5 -1
  47. package/dist/harness/inbox.d.ts.map +1 -1
  48. package/dist/harness/inbox.js +4 -1
  49. package/dist/harness/inbox.js.map +1 -1
  50. package/dist/harness/json.d.ts +20 -4
  51. package/dist/harness/json.d.ts.map +1 -1
  52. package/dist/harness/json.js +23 -5
  53. package/dist/harness/json.js.map +1 -1
  54. package/dist/harness/live.d.ts +122 -16
  55. package/dist/harness/live.d.ts.map +1 -1
  56. package/dist/harness/live.js +93 -12
  57. package/dist/harness/live.js.map +1 -1
  58. package/dist/harness/partial-changes.d.ts +54 -0
  59. package/dist/harness/partial-changes.d.ts.map +1 -0
  60. package/dist/harness/partial-changes.js +162 -0
  61. package/dist/harness/partial-changes.js.map +1 -0
  62. package/dist/harness/registry-reader.d.ts +11 -0
  63. package/dist/harness/registry-reader.d.ts.map +1 -0
  64. package/dist/harness/registry-reader.js +25 -0
  65. package/dist/harness/registry-reader.js.map +1 -0
  66. package/dist/harness/scheduler.d.ts +46 -19
  67. package/dist/harness/scheduler.d.ts.map +1 -1
  68. package/dist/harness/scheduler.js +973 -376
  69. package/dist/harness/scheduler.js.map +1 -1
  70. package/dist/harness/submissions.d.ts +17 -10
  71. package/dist/harness/submissions.d.ts.map +1 -1
  72. package/dist/harness/submissions.js +62 -25
  73. package/dist/harness/submissions.js.map +1 -1
  74. package/dist/harness/task-graph.d.ts +12 -9
  75. package/dist/harness/task-graph.d.ts.map +1 -1
  76. package/dist/harness/task-graph.js +38 -28
  77. package/dist/harness/task-graph.js.map +1 -1
  78. package/dist/harness/telemetry.d.ts +11 -11
  79. package/dist/harness/telemetry.d.ts.map +1 -1
  80. package/dist/harness/telemetry.js +7 -7
  81. package/dist/harness/telemetry.js.map +1 -1
  82. package/dist/harness/tool.d.ts +2 -0
  83. package/dist/harness/tool.d.ts.map +1 -1
  84. package/dist/harness/tool.js +171 -55
  85. package/dist/harness/tool.js.map +1 -1
  86. package/dist/harness/transcript.d.ts +72 -0
  87. package/dist/harness/transcript.d.ts.map +1 -0
  88. package/dist/harness/transcript.js +264 -0
  89. package/dist/harness/transcript.js.map +1 -0
  90. package/dist/harness/types.d.ts +218 -59
  91. package/dist/harness/types.d.ts.map +1 -1
  92. package/dist/harness/types.js.map +1 -1
  93. package/dist/harness/util.d.ts +3 -1
  94. package/dist/harness/util.d.ts.map +1 -1
  95. package/dist/harness/util.js +9 -0
  96. package/dist/harness/util.js.map +1 -1
  97. package/dist/harness/view.d.ts +43 -22
  98. package/dist/harness/view.d.ts.map +1 -1
  99. package/dist/harness/view.js +130 -71
  100. package/dist/harness/view.js.map +1 -1
  101. package/dist/index.d.ts +9 -7
  102. package/dist/index.d.ts.map +1 -1
  103. package/dist/index.js +4 -3
  104. package/dist/index.js.map +1 -1
  105. package/dist/search.d.ts +19 -3
  106. package/dist/search.d.ts.map +1 -1
  107. package/dist/search.js +107 -44
  108. package/dist/search.js.map +1 -1
  109. package/dist/session/cached-storage.d.ts +71 -0
  110. package/dist/session/cached-storage.d.ts.map +1 -0
  111. package/dist/session/cached-storage.js +269 -0
  112. package/dist/session/cached-storage.js.map +1 -0
  113. package/dist/session/conversation-tails.d.ts +33 -0
  114. package/dist/session/conversation-tails.d.ts.map +1 -0
  115. package/dist/session/conversation-tails.js +101 -0
  116. package/dist/session/conversation-tails.js.map +1 -0
  117. package/dist/session/keys.d.ts +68 -0
  118. package/dist/session/keys.d.ts.map +1 -0
  119. package/dist/session/keys.js +161 -0
  120. package/dist/session/keys.js.map +1 -0
  121. package/dist/session/session.d.ts +167 -26
  122. package/dist/session/session.d.ts.map +1 -1
  123. package/dist/session/session.js +1029 -171
  124. package/dist/session/session.js.map +1 -1
  125. package/dist/session/transaction.d.ts +81 -3
  126. package/dist/session/transaction.d.ts.map +1 -1
  127. package/dist/session/transaction.js +224 -37
  128. package/dist/session/transaction.js.map +1 -1
  129. package/dist/session/writer.d.ts +74 -0
  130. package/dist/session/writer.d.ts.map +1 -0
  131. package/dist/session/writer.js +294 -0
  132. package/dist/session/writer.js.map +1 -0
  133. package/dist/storage/indexeddb.d.ts +10 -2
  134. package/dist/storage/indexeddb.d.ts.map +1 -1
  135. package/dist/storage/indexeddb.js +91 -41
  136. package/dist/storage/indexeddb.js.map +1 -1
  137. package/dist/storage/jsonl/storage.d.ts +14 -2
  138. package/dist/storage/jsonl/storage.d.ts.map +1 -1
  139. package/dist/storage/jsonl/storage.js +88 -24
  140. package/dist/storage/jsonl/storage.js.map +1 -1
  141. package/dist/storage/memory.d.ts +7 -2
  142. package/dist/storage/memory.d.ts.map +1 -1
  143. package/dist/storage/memory.js +28 -2
  144. package/dist/storage/memory.js.map +1 -1
  145. package/dist/storage/sqlite/storage.d.ts +14 -2
  146. package/dist/storage/sqlite/storage.d.ts.map +1 -1
  147. package/dist/storage/sqlite/storage.js +110 -36
  148. package/dist/storage/sqlite/storage.js.map +1 -1
  149. package/dist/storage/store/commit.d.ts +33 -0
  150. package/dist/storage/store/commit.d.ts.map +1 -0
  151. package/dist/storage/store/commit.js +286 -0
  152. package/dist/storage/store/commit.js.map +1 -0
  153. package/dist/storage/store/documents.d.ts +43 -0
  154. package/dist/storage/store/documents.d.ts.map +1 -0
  155. package/dist/storage/store/documents.js +102 -0
  156. package/dist/storage/store/documents.js.map +1 -0
  157. package/dist/storage/store/index.d.ts +2 -0
  158. package/dist/storage/store/index.d.ts.map +1 -0
  159. package/dist/storage/store/index.js +2 -0
  160. package/dist/storage/store/index.js.map +1 -0
  161. package/dist/storage/store/queries.d.ts +49 -0
  162. package/dist/storage/store/queries.d.ts.map +1 -0
  163. package/dist/storage/store/queries.js +93 -0
  164. package/dist/storage/store/queries.js.map +1 -0
  165. package/dist/storage/store/storage.d.ts +59 -0
  166. package/dist/storage/store/storage.d.ts.map +1 -0
  167. package/dist/storage/store/storage.js +438 -0
  168. package/dist/storage/store/storage.js.map +1 -0
  169. package/dist/storage/store/tables.d.ts +54 -0
  170. package/dist/storage/store/tables.d.ts.map +1 -0
  171. package/dist/storage/store/tables.js +108 -0
  172. package/dist/storage/store/tables.js.map +1 -0
  173. package/dist/testing/commit-writes.d.ts +5 -0
  174. package/dist/testing/commit-writes.d.ts.map +1 -0
  175. package/dist/testing/commit-writes.js +12 -0
  176. package/dist/testing/commit-writes.js.map +1 -0
  177. package/dist/testing/env-conformance.js +7 -7
  178. package/dist/testing/env-conformance.js.map +1 -1
  179. package/dist/testing/index.d.ts +1 -0
  180. package/dist/testing/index.d.ts.map +1 -1
  181. package/dist/testing/index.js +1 -0
  182. package/dist/testing/index.js.map +1 -1
  183. package/dist/testing/storage-benchmark.d.ts.map +1 -1
  184. package/dist/testing/storage-benchmark.js +18 -17
  185. package/dist/testing/storage-benchmark.js.map +1 -1
  186. package/dist/testing/storage-conformance.d.ts.map +1 -1
  187. package/dist/testing/storage-conformance.js +354 -69
  188. package/dist/testing/storage-conformance.js.map +1 -1
  189. package/dist/tool-search/tool-search.d.ts +6 -12
  190. package/dist/tool-search/tool-search.d.ts.map +1 -1
  191. package/dist/tool-search/tool-search.js +7 -7
  192. package/dist/tool-search/tool-search.js.map +1 -1
  193. package/dist/tools/bash.d.ts +12 -12
  194. package/dist/tools/bash.d.ts.map +1 -1
  195. package/dist/tools/bash.js +16 -15
  196. package/dist/tools/bash.js.map +1 -1
  197. package/dist/tools/edit.d.ts +7 -7
  198. package/dist/tools/edit.d.ts.map +1 -1
  199. package/dist/tools/edit.js +9 -9
  200. package/dist/tools/edit.js.map +1 -1
  201. package/dist/tools/index.d.ts +32 -32
  202. package/dist/tools/read.d.ts +6 -6
  203. package/dist/tools/read.d.ts.map +1 -1
  204. package/dist/tools/read.js +19 -8
  205. package/dist/tools/read.js.map +1 -1
  206. package/dist/tools/write.d.ts +4 -4
  207. package/dist/tools/write.d.ts.map +1 -1
  208. package/dist/tools/write.js +5 -5
  209. package/dist/tools/write.js.map +1 -1
  210. package/dist/types.d.ts +223 -77
  211. package/dist/types.d.ts.map +1 -1
  212. package/dist/types.js.map +1 -1
  213. package/package.json +19 -12
  214. package/dist/harness/events.d.ts +0 -186
  215. package/dist/harness/events.d.ts.map +0 -1
  216. package/dist/harness/events.js +0 -373
  217. package/dist/harness/events.js.map +0 -1
  218. package/dist/session/observation.d.ts +0 -42
  219. package/dist/session/observation.d.ts.map +0 -1
  220. package/dist/session/observation.js +0 -281
  221. package/dist/session/observation.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"memory.js","sourceRoot":"","sources":["../../src/storage/memory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAW,MAAM,6BAA6B,CAAC;AAC7E,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AA+BxD,OAAO,EAAE,UAAU,EAAkB,SAAS,EAAE,MAAM,WAAW,CAAC;AAiBlE,QAAQ,CAAC,CAAC,oBAAoB,CAC7B,EAAc,EACd,OAAe,EACf,SAAsC,EACtC,KAAa;IAEb,KAAK,IAAI,KAAK,GAAG,KAAK,EAAE,KAAK,GAAG,SAAS,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC;QAC3D,MAAM,QAAQ,GAAG,SAAS,CAAC,KAAK,CAAE,CAAC;QACnC,IAAI,QAAQ,CAAC,IAAI,KAAK,OAAO,IAAI,QAAQ,CAAC,OAAO,KAAK,OAAO,EAAE,CAAC;YAC/D,MAAM,IAAI,KAAK,CAAC,YAAY,EAAE,mDAAmD,CAAC,CAAC;QACpF,CAAC;QACD,MAAM,QAAQ,CAAC,GAAG,CAAC;IACpB,CAAC;AACF,CAAC;AA6BD,MAAM,KAAK,GAAG,CAAI,KAAQ,EAAK,EAAE;IAChC,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,O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a,CAAC,MAAO,CAAC,MAAM,CAAC;gBAAE,MAAO,CAAC,SAAS,GAAG,EAAE,CAAC;YAC3E,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;gBAClD,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC,GAAG,CAAC,gBAAgB,CAAC,MAAO,CAAC,MAAM,CAAC,CAAE,CAAC;gBACpF,IAAI,MAAM,CAAC,MAAM,IAAI,OAAO,CAAC,SAAS,KAAK,EAAE;oBAAE,OAAO,OAAO,CAAC,SAAS,CAAC;gBACxE,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS,IAAI,CAAC,MAAM,CAAC,MAAM;oBAAE,OAAO,CAAC,SAAS,GAAG,EAAE,CAAC;YAC3E,CAAC;QACF,CAAC;IACF,CAAC;IAEO,UAAU;QACjB,IAAI,IAAI,CAAC,MAAM;YAAE,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7D,CAAC;CACD","sourcesContent":["import type { Context, JsonValue } from \"@earendil-works/chord\";\nimport { applyImmutableBatches, type Op } from \"@earendil-works/chord/delta\";\nimport { StorageRequestError } from \"../errors.ts\";\nimport { idFromNumber, seqFromNumber } from \"../ids.ts\";\nimport type {\n\tConversationId,\n\tConversationQuery,\n\tConversationRecord,\n\tCursor,\n\tDocumentAddress,\n\tDocumentContent,\n\tDocumentCreate,\n\tDocumentId,\n\tDocumentPoint,\n\tDocumentQuery,\n\tDocumentRecord,\n\tEntryId,\n\tEntryQuery,\n\tEntryRecord,\n\tId,\n\tJsonObject,\n\tPage,\n\tScanOrder,\n\tSeq,\n\tStorage,\n\tStorageWrite,\n\tStoredDocument,\n\tSubmissionId,\n\tSubmissionQuery,\n\tSubmissionRecord,\n\tTaskId,\n\tTaskQuery,\n\tTaskRecord,\n} from \"../types.ts\";\nimport { nextCursor, type ScanStart, scanStart } from \"./scan.ts\";\n\ntype StoredTask = TaskRecord<JsonValue, JsonValue, JsonValue>;\ntype TaskStatus = StoredTask[\"state\"][\"status\"];\ntype SubmissionStatus = SubmissionRecord[\"status\"];\ntype TableName = \"conversation\" | \"entry\" | \"task\" | \"submission\" | \"document\";\ntype DocumentRevision = DocumentContent & { readonly seq: Seq };\ntype StoredDocumentState = {\n\trecord: DocumentRecord;\n\trevisions: DocumentRevision[];\n};\ntype DocumentAction = {\n\tcreate?: DocumentCreate;\n\tcontent?: DocumentContent;\n\tretire: boolean;\n};\n\nfunction* documentDeltaBatches(\n\tid: DocumentId,\n\tversion: number,\n\trevisions: readonly DocumentRevision[],\n\tstart: number,\n): Generator<readonly Op[]> {\n\tfor (let index = start; index < revisions.length; index++) {\n\t\tconst revision = revisions[index]!;\n\t\tif (revision.kind !== \"delta\" || revision.version !== version) {\n\t\t\tthrow new Error(`Document ${id} crosses a stored version boundary without a base`);\n\t\t}\n\t\tyield revision.ops;\n\t}\n}\n\ntype DocumentAddressIndex = {\n\tids: DocumentId[];\n\tcurrentId?: DocumentId;\n};\n\ntype State = {\n\trecordTypes: Map<Id<string>, TableName>;\n\tconversations: Map<ConversationId, ConversationRecord>;\n\tconversationIds: ConversationId[];\n\tconversationIdsByOwnerConversation: Map<ConversationId, ConversationId[]>;\n\tconversationIdsByOwnerTask: Map<TaskId, ConversationId[]>;\n\tentries: Map<EntryId, EntryRecord>;\n\tentryIds: Map<ConversationId, EntryId[]>;\n\theadEntryIds: Map<ConversationId, EntryId[]>;\n\tentryCommitSeqs: Map<EntryId, Seq>;\n\ttasks: Map<TaskId, StoredTask>;\n\ttaskIds: TaskId[];\n\ttaskIdsByStatus: Record<TaskStatus, TaskId[]>;\n\tsubmissions: Map<SubmissionId, SubmissionRecord>;\n\tsubmissionIds: SubmissionId[];\n\tsubmissionIdsByStatus: Record<SubmissionStatus, SubmissionId[]>;\n\tsubmissionIdsByRequest: Map<ConversationId, Map<string, SubmissionId>>;\n\tdocuments: Map<DocumentId, StoredDocumentState>;\n\tdocumentAddresses: Map<string, DocumentAddressIndex>;\n\tdocumentIdsByScope: Map<string, DocumentId[]>;\n};\n\nconst clone = <T>(value: T): T => {\n\tif (value === null || typeof value !== \"object\") return value;\n\tif (Array.isArray(value)) return value.map((item) => clone(item)) as T;\n\tconst source = value as Record<string, unknown>;\n\tconst nullPrototype = Object.getPrototypeOf(value) === null;\n\tconst result = (nullPrototype ? Object.create(null) : {}) as Record<string, unknown>;\n\tfor (const key of Object.keys(source)) {\n\t\tconst copied = clone(source[key]);\n\t\tif (!nullPrototype && key in result) {\n\t\t\tObject.defineProperty(result, key, {\n\t\t\t\tvalue: copied,\n\t\t\t\twritable: true,\n\t\t\t\tenumerable: true,\n\t\t\t\tconfigurable: true,\n\t\t\t});\n\t\t} else {\n\t\t\tresult[key] = copied;\n\t\t}\n\t}\n\treturn result as T;\n};\n\nconst freeze = <T>(value: T): T => {\n\tif (value === null || typeof value !== \"object\" || Object.isFrozen(value)) return value;\n\tfor (const child of Object.values(value)) freeze(child);\n\treturn Object.freeze(value);\n};\n\nconst cursorId = <I extends Id<string>>(cursor: Readonly<Record<string, JsonValue>> | undefined): I | undefined => {\n\tconst after = cursor?.after;\n\tif (after === undefined) return undefined;\n\tif (typeof after !== \"number\" || !Number.isSafeInteger(after))\n\t\tthrow new StorageRequestError(\"Invalid storage cursor\");\n\treturn idFromNumber<I>(after);\n};\n\nconst lowerBound = <I extends Id<string>>(ids: readonly I[], target: number): number => {\n\tlet low = 0;\n\tlet high = ids.length;\n\twhile (low < high) {\n\t\tconst middle = (low + high) >>> 1;\n\t\tif (ids[middle] < target) low = middle + 1;\n\t\telse high = middle;\n\t}\n\treturn low;\n};\n\nconst upperBound = <I extends Id<string>>(ids: readonly I[], target: number): number => {\n\tlet low = 0;\n\tlet high = ids.length;\n\twhile (low < high) {\n\t\tconst middle = (low + high) >>> 1;\n\t\tif (ids[middle] <= target) low = middle + 1;\n\t\telse high = middle;\n\t}\n\treturn low;\n};\n\nconst insertSorted = <I extends Id<string>>(ids: I[], id: I): void => {\n\tif (ids.length === 0 || ids[ids.length - 1] < id) ids.push(id);\n\telse ids.splice(lowerBound(ids, id), 0, id);\n};\n\nconst removeSorted = <I extends Id<string>>(ids: I[], id: I): void => {\n\tconst index = lowerBound(ids, id);\n\tif (ids[index] === id) ids.splice(index, 1);\n};\n\nconst insertMapId = <K, I extends Id<string>>(index: Map<K, I[]>, key: K, id: I): void => {\n\tlet ids = index.get(key);\n\tif (ids === undefined) {\n\t\tids = [];\n\t\tindex.set(key, ids);\n\t}\n\tinsertSorted(ids, id);\n};\n\nconst scopeKey = (scope: DocumentRecord[\"scope\"]): string => {\n\tswitch (scope.kind) {\n\t\tcase \"session\":\n\t\t\treturn JSON.stringify([\"session\"]);\n\t\tcase \"conversation\":\n\t\t\treturn JSON.stringify([\"conversation\", scope.conversationId]);\n\t\tcase \"task\":\n\t\t\treturn JSON.stringify([\"task\", scope.taskId]);\n\t}\n};\n\nconst addressKey = (address: DocumentAddress): string =>\n\tJSON.stringify([\n\t\taddress.kind,\n\t\tscopeKey(address.scope),\n\t\taddress.key === undefined ? [\"singleton\"] : [\"family\", address.key],\n\t]);\n\nconst recordAddressKey = (record: DocumentRecord | DocumentCreate): string =>\n\taddressKey({ kind: record.kind, scope: record.scope, key: record.key });\n\nconst isAliveAt = (record: DocumentRecord, at: DocumentPoint): boolean => {\n\tif (at === \"current\") return record.retiredAt === undefined;\n\treturn record.createdAt <= at && (record.retiredAt === undefined || at < record.retiredAt);\n};\n\nconst isCurrentOnly = (record: DocumentRecord): boolean =>\n\trecord.scope.kind !== \"conversation\" || record.history === \"latest\";\n\nconst tableContaining = (state: State, id: Id<string>): TableName | undefined => state.recordTypes.get(id);\n\nconst page = <T extends { readonly id: Id<string> }>(\n\tvalues: readonly T[],\n\tlimit: number,\n\torder: ScanOrder = \"ascending\",\n): Page<T, Cursor> => {\n\tconst items = values.slice(0, limit);\n\tif (values.length <= limit) return { items: clone(items) };\n\treturn { items: clone(items), next: nextCursor(items.at(-1)!.id, order) };\n};\n\n/** Indexes of sorted `ids` in scan order, after the cursor's ID when there is one. */\nfunction* scanIndexes(ids: readonly Id<string>[], start: ScanStart): Generator<number> {\n\tif (start.order === \"ascending\") {\n\t\tconst first = start.after === undefined ? 0 : upperBound(ids, start.after);\n\t\tfor (let index = first; index < ids.length; index++) yield index;\n\t} else {\n\t\tconst end = start.after === undefined ? ids.length : lowerBound(ids, start.after);\n\t\tfor (let index = end - 1; index >= 0; index--) yield index;\n\t}\n}\n\n/** A fully validated, detached state mutation whose application performs no fallible preparation. */\nexport interface PreparedMemoryCommit {\n\treadonly seq: Seq;\n\t/** Deeply frozen detached writes for persistence. */\n\treadonly writes: readonly StorageWrite[];\n\tapply(): Seq;\n}\n\n/**\n * Detached in-memory reference implementation of `Storage`.\n *\n * Reads and retained writes are cloned intentionally to match the ownership boundary\n * of serialization-backed stores. This is backend conformance, not validation.\n */\nexport class MemoryStorage implements Storage {\n\tprivate readonly state: State = {\n\t\trecordTypes: new Map(),\n\t\tconversations: new Map(),\n\t\tconversationIds: [],\n\t\tconversationIdsByOwnerConversation: new Map(),\n\t\tconversationIdsByOwnerTask: new Map(),\n\t\tentries: new Map(),\n\t\tentryIds: new Map(),\n\t\theadEntryIds: new Map(),\n\t\tentryCommitSeqs: new Map(),\n\t\ttasks: new Map(),\n\t\ttaskIds: [],\n\t\ttaskIdsByStatus: { pending: [], running: [], waiting: [], sleeping: [], completing: [], terminal: [] },\n\t\tsubmissions: new Map(),\n\t\tsubmissionIds: [],\n\t\tsubmissionIdsByStatus: { queued: [], placed: [], done: [], unanswered: [] },\n\t\tsubmissionIdsByRequest: new Map(),\n\t\tdocuments: new Map(),\n\t\tdocumentAddresses: new Map(),\n\t\tdocumentIdsByScope: new Map(),\n\t};\n\tprivate nextId = 2;\n\tprivate nextSeq = 1;\n\tprivate closed = false;\n\n\tasync commit(writes: readonly StorageWrite[], _context: Context): Promise<Seq> {\n\t\treturn this.prepareCommit(writes).apply();\n\t}\n\n\t/** Validate and detach one commit without changing observable state. */\n\tprepareCommit(writes: readonly StorageWrite[], seq: Seq = seqFromNumber(this.nextSeq)): PreparedMemoryCommit {\n\t\tthis.assertOpen();\n\t\tif (!Number.isSafeInteger(seq) || seq < this.nextSeq) {\n\t\t\tthrow new Error(`Commit sequence ${seq} does not strictly increase`);\n\t\t}\n\t\tconst detachedWrites = freeze(this.resolveDocumentCopies(writes.map((write) => clone(write))));\n\t\tthis.checkGlobalIds(detachedWrites);\n\t\tconst documentActions = this.prepareDocumentActions(detachedWrites);\n\t\tthis.checkDocumentActions(documentActions);\n\t\tlet applied = false;\n\t\treturn {\n\t\t\tseq,\n\t\t\twrites: detachedWrites,\n\t\t\tapply: () => {\n\t\t\t\tif (!applied) {\n\t\t\t\t\tapplied = true;\n\t\t\t\t\tthis.applyPreparedCommit(detachedWrites, documentActions, seq);\n\t\t\t\t}\n\t\t\t\treturn seq;\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate resolveDocumentCopies(writes: StorageWrite[]): StorageWrite[] {\n\t\tif (!writes.some((write) => write.type === \"document.copy\")) return writes;\n\t\tconst changedDocumentIds = new Set<DocumentId>();\n\t\tfor (const write of writes) {\n\t\t\tif (write.type === \"document.create\" || write.type === \"document.copy\") {\n\t\t\t\tchangedDocumentIds.add(write.record.id);\n\t\t\t} else if (write.type === \"document.change\" || write.type === \"document.retire\") {\n\t\t\t\tchangedDocumentIds.add(write.id);\n\t\t\t}\n\t\t}\n\t\treturn writes.map((write) => {\n\t\t\tif (write.type !== \"document.copy\") return write;\n\t\t\ttry {\n\t\t\t\tif (changedDocumentIds.has(write.source.id)) {\n\t\t\t\t\tthrow new Error(`Fork source document ${write.source.id} is changed in the copy batch`);\n\t\t\t\t}\n\t\t\t\tconst stored = this.materializeDocument(write.source.id, write.source.at);\n\t\t\t\tif (stored === undefined) throw new Error(`Fork source document ${write.source.id} cannot be read`);\n\t\t\t\tif (\n\t\t\t\t\tstored.record.scope.kind !== \"conversation\" ||\n\t\t\t\t\twrite.record.scope.kind !== \"conversation\" ||\n\t\t\t\t\tstored.record.kind !== write.record.kind ||\n\t\t\t\t\tstored.record.key !== write.record.key ||\n\t\t\t\t\tstored.record.history !== write.record.history ||\n\t\t\t\t\tstored.record.fork !== write.record.fork\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(`Fork source document ${write.source.id} does not match the copied record`);\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"document.create\",\n\t\t\t\t\trecord: write.record,\n\t\t\t\t\tcontent: { kind: \"base\", version: stored.version, value: stored.value },\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tthrow new Error(`Document copy ${write.record.id} was rejected`, { cause: error });\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate applyPreparedCommit(\n\t\tprepared: readonly StorageWrite[],\n\t\tdocumentActions: ReadonlyMap<DocumentId, DocumentAction>,\n\t\tseq: Seq,\n\t): Seq {\n\t\tfor (const write of prepared) {\n\t\t\tswitch (write.type) {\n\t\t\t\tcase \"conversation\": {\n\t\t\t\t\tthis.state.recordTypes.set(write.value.id, \"conversation\");\n\t\t\t\t\tthis.state.conversations.set(write.value.id, write.value);\n\t\t\t\t\tinsertSorted(this.state.conversationIds, write.value.id);\n\t\t\t\t\tconst owner = write.value.owner;\n\t\t\t\t\tif (owner !== undefined) {\n\t\t\t\t\t\tinsertMapId(this.state.conversationIdsByOwnerConversation, owner.conversationId, write.value.id);\n\t\t\t\t\t\tinsertMapId(this.state.conversationIdsByOwnerTask, owner.taskId, write.value.id);\n\t\t\t\t\t}\n\t\t\t\t\tthis.nextId = Math.max(this.nextId, write.value.id + 1);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"entry\": {\n\t\t\t\t\tthis.state.recordTypes.set(write.value.id, \"entry\");\n\t\t\t\t\tthis.state.entries.set(write.value.id, write.value);\n\t\t\t\t\tthis.state.entryCommitSeqs.set(write.value.id, seq);\n\t\t\t\t\tlet ids = this.state.entryIds.get(write.value.conversationId);\n\t\t\t\t\tif (ids === undefined) {\n\t\t\t\t\t\tids = [];\n\t\t\t\t\t\tthis.state.entryIds.set(write.value.conversationId, ids);\n\t\t\t\t\t}\n\t\t\t\t\tinsertSorted(ids, write.value.id);\n\t\t\t\t\tif (write.value.head !== undefined) {\n\t\t\t\t\t\tlet headIds = this.state.headEntryIds.get(write.value.conversationId);\n\t\t\t\t\t\tif (headIds === undefined) {\n\t\t\t\t\t\t\theadIds = [];\n\t\t\t\t\t\t\tthis.state.headEntryIds.set(write.value.conversationId, headIds);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tinsertSorted(headIds, write.value.id);\n\t\t\t\t\t}\n\t\t\t\t\tthis.nextId = Math.max(this.nextId, write.value.id + 1);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"task\": {\n\t\t\t\t\tthis.state.recordTypes.set(write.value.id, \"task\");\n\t\t\t\t\tconst previous = this.state.tasks.get(write.value.id);\n\t\t\t\t\tif (previous === undefined) {\n\t\t\t\t\t\tinsertSorted(this.state.taskIds, write.value.id);\n\t\t\t\t\t\tinsertSorted(this.state.taskIdsByStatus[write.value.state.status], write.value.id);\n\t\t\t\t\t} else if (previous.state.status !== write.value.state.status) {\n\t\t\t\t\t\tremoveSorted(this.state.taskIdsByStatus[previous.state.status], write.value.id);\n\t\t\t\t\t\tinsertSorted(this.state.taskIdsByStatus[write.value.state.status], write.value.id);\n\t\t\t\t\t}\n\t\t\t\t\tthis.state.tasks.set(write.value.id, write.value);\n\t\t\t\t\tthis.nextId = Math.max(this.nextId, write.value.id + 1);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"submission\": {\n\t\t\t\t\tthis.state.recordTypes.set(write.value.id, \"submission\");\n\t\t\t\t\tconst previous = this.state.submissions.get(write.value.id);\n\t\t\t\t\tif (previous === undefined) {\n\t\t\t\t\t\tinsertSorted(this.state.submissionIds, write.value.id);\n\t\t\t\t\t\tinsertSorted(this.state.submissionIdsByStatus[write.value.status], write.value.id);\n\t\t\t\t\t} else if (previous.status !== write.value.status) {\n\t\t\t\t\t\tremoveSorted(this.state.submissionIdsByStatus[previous.status], write.value.id);\n\t\t\t\t\t\tinsertSorted(this.state.submissionIdsByStatus[write.value.status], write.value.id);\n\t\t\t\t\t}\n\t\t\t\t\tif (previous?.requestId !== undefined) {\n\t\t\t\t\t\tconst previousRequests = this.state.submissionIdsByRequest.get(previous.conversationId);\n\t\t\t\t\t\tif (previousRequests?.get(previous.requestId) === write.value.id) {\n\t\t\t\t\t\t\tpreviousRequests.delete(previous.requestId);\n\t\t\t\t\t\t\tif (previousRequests.size === 0) this.state.submissionIdsByRequest.delete(previous.conversationId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tthis.state.submissions.set(write.value.id, write.value);\n\t\t\t\t\tif (write.value.requestId !== undefined) {\n\t\t\t\t\t\tlet requests = this.state.submissionIdsByRequest.get(write.value.conversationId);\n\t\t\t\t\t\tif (requests === undefined) {\n\t\t\t\t\t\t\trequests = new Map();\n\t\t\t\t\t\t\tthis.state.submissionIdsByRequest.set(write.value.conversationId, requests);\n\t\t\t\t\t\t}\n\t\t\t\t\t\trequests.set(write.value.requestId, write.value.id);\n\t\t\t\t\t}\n\t\t\t\t\tthis.nextId = Math.max(this.nextId, write.value.id + 1);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"document.copy\":\n\t\t\t\t\tthrow new Error(\"Prepared document copy was not resolved\");\n\t\t\t\tcase \"document.create\":\n\t\t\t\tcase \"document.change\":\n\t\t\t\tcase \"document.retire\":\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tthis.applyDocumentActions(documentActions, seq);\n\t\tthis.nextSeq = seq + 1;\n\t\treturn seq;\n\t}\n\n\tasync mintId<I extends Id<string>>(): Promise<I> {\n\t\tthis.assertOpen();\n\t\tif (!Number.isSafeInteger(this.nextId)) throw new Error(\"ID space is exhausted\");\n\t\treturn idFromNumber<I>(this.nextId++);\n\t}\n\n\tasync conversation(id: ConversationId, _context: Context): Promise<ConversationRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst value = this.state.conversations.get(id);\n\t\treturn value === undefined ? undefined : clone(value);\n\t}\n\n\tasync scanConversations(\n\t\tquery: ConversationQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<ConversationRecord, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst ids =\n\t\t\tquery.ownerTaskId !== undefined\n\t\t\t\t? (this.state.conversationIdsByOwnerTask.get(query.ownerTaskId) ?? [])\n\t\t\t\t: query.ownerConversationId !== undefined\n\t\t\t\t\t? (this.state.conversationIdsByOwnerConversation.get(query.ownerConversationId) ?? [])\n\t\t\t\t\t: this.state.conversationIds;\n\t\tconst start = scanStart(query.order, cursor, \"ascending\");\n\t\tconst values: ConversationRecord[] = [];\n\t\tfor (const index of scanIndexes(ids, start)) {\n\t\t\tif (values.length > limit) break;\n\t\t\tconst value = this.state.conversations.get(ids[index]!)!;\n\t\t\tif (query.ownerConversationId !== undefined && value.owner?.conversationId !== query.ownerConversationId) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvalues.push(value);\n\t\t}\n\t\treturn page(values, limit, start.order);\n\t}\n\n\tentry(id: EntryId, context: Context): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined>;\n\tentry(\n\t\tconversationId: ConversationId,\n\t\tid: EntryId,\n\t\tcontext: Context,\n\t): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined>;\n\tasync entry(\n\t\tidOrConversationId: EntryId | ConversationId,\n\t\tidOrContext: EntryId | Context,\n\t\tcontext?: Context,\n\t): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined> {\n\t\tthis.assertOpen();\n\t\tif (context === undefined) {\n\t\t\tconst id = idFromNumber<EntryId>(idOrConversationId);\n\t\t\tconst entry = this.state.entries.get(id);\n\t\t\tif (entry === undefined) return undefined;\n\t\t\treturn { entry: clone(entry), commitSeq: this.state.entryCommitSeqs.get(id)! };\n\t\t}\n\t\tif (typeof idOrContext !== \"number\") throw new StorageRequestError(\"Storage.entry() requires an entry ID\");\n\t\tconst conversationId = idFromNumber<ConversationId>(idOrConversationId);\n\t\tconst id = idFromNumber<EntryId>(idOrContext);\n\t\tconst entry = this.visibleEntries(conversationId, id, id).next().value;\n\t\tif (entry === undefined) return undefined;\n\t\treturn { entry: clone(entry), commitSeq: this.state.entryCommitSeqs.get(id)! };\n\t}\n\n\tasync findLatestHeadMarker(\n\t\tconversationId: ConversationId,\n\t\tatOrBeforeEntryId: EntryId | undefined,\n\t\t_context: Context,\n\t): Promise<(EntryRecord & { readonly head: EntryId }) | undefined> {\n\t\tthis.assertOpen();\n\t\tif (!this.state.conversations.has(conversationId)) {\n\t\t\tthrow new StorageRequestError(`Unknown conversation: ${conversationId}`);\n\t\t}\n\t\tlet currentId = conversationId;\n\t\tlet upperEntryId = atOrBeforeEntryId ?? Number.POSITIVE_INFINITY;\n\t\twhile (true) {\n\t\t\tconst ids = this.state.headEntryIds.get(currentId) ?? [];\n\t\t\tconst index = upperBound(ids, upperEntryId) - 1;\n\t\t\tif (index >= 0) {\n\t\t\t\tconst entry = this.state.entries.get(ids[index])!;\n\t\t\t\treturn clone({ ...entry, head: entry.head! });\n\t\t\t}\n\t\t\tconst conversation = this.state.conversations.get(currentId)!;\n\t\t\tif (conversation.parent === undefined) return undefined;\n\t\t\tupperEntryId = Math.min(upperEntryId, conversation.parent.at);\n\t\t\tcurrentId = conversation.parent.conversationId;\n\t\t}\n\t}\n\n\tasync scanEntries(\n\t\tquery: EntryQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<EntryRecord, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst { order, after } = scanStart(query.order, cursor, \"descending\");\n\t\t// The cursor narrows the bound on the side the scan moves away from.\n\t\tlet minEntryId: number | undefined = query.minEntryId;\n\t\tlet maxEntryId: number | undefined = query.maxEntryId;\n\t\tif (after !== undefined && order === \"descending\") maxEntryId = Math.min(maxEntryId ?? after, after - 1);\n\t\tif (after !== undefined && order === \"ascending\") minEntryId = Math.max(minEntryId ?? after, after + 1);\n\t\tconst visible: EntryRecord[] = [];\n\t\tconst entries =\n\t\t\torder === \"descending\"\n\t\t\t\t? this.visibleEntries(query.conversationId, minEntryId, maxEntryId)\n\t\t\t\t: this.visibleEntriesAscending(query.conversationId, minEntryId, maxEntryId);\n\t\tfor (const entry of entries) {\n\t\t\tvisible.push(entry);\n\t\t\tif (visible.length > limit) break;\n\t\t}\n\t\treturn page(visible, limit, order);\n\t}\n\n\tasync task(id: TaskId, _context: Context): Promise<StoredTask | undefined> {\n\t\tthis.assertOpen();\n\t\tconst value = this.state.tasks.get(id);\n\t\treturn value === undefined ? undefined : clone(value);\n\t}\n\n\tasync scanTasks(\n\t\tquery: TaskQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<StoredTask, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst start = scanStart(query.order, cursor, \"ascending\");\n\t\tconst ids = query.status === undefined ? this.state.taskIds : this.state.taskIdsByStatus[query.status];\n\t\tconst values: StoredTask[] = [];\n\t\tfor (const index of scanIndexes(ids, start)) {\n\t\t\tif (values.length > limit) break;\n\t\t\tconst value = this.state.tasks.get(ids[index]!)!;\n\t\t\tif (query.conversationId !== undefined && value.conversationId !== query.conversationId) continue;\n\t\t\tif (query.kind !== undefined && value.kind !== query.kind) continue;\n\t\t\tif (query.abortRequested !== undefined && value.abortRequested !== query.abortRequested) continue;\n\t\t\tif (query.background !== undefined && value.background !== query.background) continue;\n\t\t\tvalues.push(value);\n\t\t}\n\t\treturn page(values, limit, start.order);\n\t}\n\n\tasync submission(id: SubmissionId, _context: Context): Promise<SubmissionRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst value = this.state.submissions.get(id);\n\t\treturn value === undefined ? undefined : clone(value);\n\t}\n\n\tasync scanSubmissions(\n\t\tquery: SubmissionQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<SubmissionRecord, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst start = scanStart(query.order, cursor, \"ascending\");\n\t\tconst ids =\n\t\t\tquery.status === undefined ? this.state.submissionIds : this.state.submissionIdsByStatus[query.status];\n\t\tconst values: SubmissionRecord[] = [];\n\t\tfor (const index of scanIndexes(ids, start)) {\n\t\t\tif (values.length > limit) break;\n\t\t\tconst value = this.state.submissions.get(ids[index]!)!;\n\t\t\tif (query.conversationId !== undefined && value.conversationId !== query.conversationId) continue;\n\t\t\tvalues.push(value);\n\t\t}\n\t\treturn page(values, limit, start.order);\n\t}\n\n\tasync submissionByRequest(\n\t\tconversationId: ConversationId,\n\t\trequestId: string,\n\t\t_context: Context,\n\t): Promise<SubmissionRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst id = this.state.submissionIdsByRequest.get(conversationId)?.get(requestId);\n\t\tif (id === undefined) return undefined;\n\t\treturn clone(this.state.submissions.get(id)!);\n\t}\n\n\tasync findDocument(\n\t\taddress: DocumentAddress,\n\t\tat: DocumentPoint,\n\t\t_context: Context,\n\t): Promise<DocumentRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst index = this.state.documentAddresses.get(addressKey(address));\n\t\tif (at === \"current\") {\n\t\t\treturn index?.currentId === undefined ? undefined : clone(this.state.documents.get(index.currentId)!.record);\n\t\t}\n\t\tfor (const id of index?.ids ?? []) {\n\t\t\tconst record = this.state.documents.get(id)!.record;\n\t\t\tif (isAliveAt(record, at)) return clone(record);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tasync document(id: DocumentId, at: DocumentPoint, _context: Context): Promise<StoredDocument | undefined> {\n\t\tthis.assertOpen();\n\t\tconst stored = this.materializeDocument(id, at);\n\t\treturn stored === undefined\n\t\t\t? undefined\n\t\t\t: {\n\t\t\t\t\trecord: clone(stored.record),\n\t\t\t\t\tversion: stored.version,\n\t\t\t\t\tvalue: clone(stored.value),\n\t\t\t\t\tdeltasSinceBase: stored.deltasSinceBase,\n\t\t\t\t};\n\t}\n\n\tasync scanDocuments(\n\t\tquery: DocumentQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<DocumentRecord, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst ids = this.state.documentIdsByScope.get(scopeKey(query.scope)) ?? [];\n\t\tconst after = cursorId(cursor);\n\t\tconst start = after === undefined ? 0 : upperBound(ids, after);\n\t\tconst values: DocumentRecord[] = [];\n\t\tfor (let index = start; index < ids.length && values.length <= limit; index++) {\n\t\t\tconst record = this.state.documents.get(ids[index]!)!.record;\n\t\t\tif (query.kind !== undefined && record.kind !== query.kind) continue;\n\t\t\tif (isAliveAt(record, query.at)) values.push(record);\n\t\t}\n\t\treturn page(values, limit);\n\t}\n\n\tasync close(_context: Context): Promise<void> {\n\t\tthis.closed = true;\n\t}\n\n\tprivate materializeDocument(id: DocumentId, at: DocumentPoint): StoredDocument | undefined {\n\t\tconst stored = this.state.documents.get(id);\n\t\tif (stored === undefined) return undefined;\n\t\tif (at !== \"current\" && isCurrentOnly(stored.record)) {\n\t\t\tthrow new StorageRequestError(`Document ${id} does not retain historical content`);\n\t\t}\n\t\tif (!isAliveAt(stored.record, at)) return undefined;\n\t\tconst revisions = at === \"current\" ? stored.revisions : stored.revisions.filter((revision) => revision.seq <= at);\n\t\tlet baseIndex = revisions.length - 1;\n\t\twhile (baseIndex >= 0 && revisions[baseIndex]!.kind !== \"base\") baseIndex--;\n\t\tconst base = revisions[baseIndex];\n\t\tif (base?.kind !== \"base\") throw new Error(`Document ${id} is missing a required base`);\n\t\tconst value = applyImmutableBatches(\n\t\t\tbase.value,\n\t\t\tdocumentDeltaBatches(id, base.version, revisions, baseIndex + 1),\n\t\t) as JsonObject;\n\t\treturn { record: stored.record, version: base.version, value, deltasSinceBase: revisions.length - baseIndex - 1 };\n\t}\n\n\tprivate *visibleEntries(\n\t\tconversationId: ConversationId,\n\t\tminEntryId: number = Number.NEGATIVE_INFINITY,\n\t\tmaxEntryId: number = Number.POSITIVE_INFINITY,\n\t): Generator<EntryRecord> {\n\t\tif (!this.state.conversations.has(conversationId)) {\n\t\t\tthrow new StorageRequestError(`Unknown conversation: ${conversationId}`);\n\t\t}\n\t\tlet currentId = conversationId;\n\t\tlet upperEntryId = maxEntryId;\n\t\twhile (true) {\n\t\t\tconst ids = this.state.entryIds.get(currentId) ?? [];\n\t\t\tfor (let index = upperBound(ids, upperEntryId) - 1; index >= 0; index--) {\n\t\t\t\tconst id = ids[index];\n\t\t\t\tif (id < minEntryId) break;\n\t\t\t\tyield this.state.entries.get(id)!;\n\t\t\t}\n\t\t\tconst conversation = this.state.conversations.get(currentId)!;\n\t\t\tif (conversation.parent === undefined) break;\n\t\t\tupperEntryId = Math.min(upperEntryId, conversation.parent.at);\n\t\t\tif (upperEntryId < minEntryId) break;\n\t\t\tcurrentId = conversation.parent.conversationId;\n\t\t}\n\t}\n\n\t/** Visible entries oldest first: the fork chain's segments from the root conversation forward. */\n\tprivate *visibleEntriesAscending(\n\t\tconversationId: ConversationId,\n\t\tminEntryId: number = Number.NEGATIVE_INFINITY,\n\t\tmaxEntryId: number = Number.POSITIVE_INFINITY,\n\t): Generator<EntryRecord> {\n\t\tif (!this.state.conversations.has(conversationId)) {\n\t\t\tthrow new StorageRequestError(`Unknown conversation: ${conversationId}`);\n\t\t}\n\t\tconst segments: { readonly conversationId: ConversationId; readonly upper: number }[] = [];\n\t\tlet currentId = conversationId;\n\t\tlet upperEntryId = maxEntryId;\n\t\twhile (true) {\n\t\t\tsegments.push({ conversationId: currentId, upper: upperEntryId });\n\t\t\tconst conversation = this.state.conversations.get(currentId)!;\n\t\t\tif (conversation.parent === undefined) break;\n\t\t\tupperEntryId = Math.min(upperEntryId, conversation.parent.at);\n\t\t\tif (upperEntryId < minEntryId) break;\n\t\t\tcurrentId = conversation.parent.conversationId;\n\t\t}\n\t\tfor (const segment of segments.reverse()) {\n\t\t\tconst ids = this.state.entryIds.get(segment.conversationId) ?? [];\n\t\t\tfor (let index = lowerBound(ids, minEntryId); index < ids.length; index++) {\n\t\t\t\tconst id = ids[index]!;\n\t\t\t\tif (id > segment.upper) break;\n\t\t\t\tyield this.state.entries.get(id)!;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate checkGlobalIds(writes: readonly StorageWrite[]): void {\n\t\tconst claimed = new Map<Id<string>, TableName>();\n\t\tfor (const write of writes) {\n\t\t\tif (write.type === \"document.change\" || write.type === \"document.retire\") continue;\n\t\t\tconst document = write.type === \"document.create\" || write.type === \"document.copy\";\n\t\t\tconst table: TableName = document ? \"document\" : write.type;\n\t\t\tconst id = document ? write.record.id : write.value.id;\n\t\t\tconst existing = tableContaining(this.state, id);\n\t\t\tconst earlier = claimed.get(id);\n\t\t\tif (table === \"conversation\" || table === \"entry\" || table === \"document\") {\n\t\t\t\tif (existing !== undefined) throw new Error(`ID ${id} already belongs to ${existing}`);\n\t\t\t\tif (earlier !== undefined) throw new Error(`ID ${id} is written more than once`);\n\t\t\t} else {\n\t\t\t\tif (existing !== undefined && existing !== table) {\n\t\t\t\t\tthrow new Error(`ID ${id} already belongs to ${existing}`);\n\t\t\t\t}\n\t\t\t\tif (earlier !== undefined && earlier !== table) throw new Error(`ID ${id} is written as two record types`);\n\t\t\t}\n\t\t\tclaimed.set(id, table);\n\t\t}\n\t}\n\n\tprivate prepareDocumentActions(writes: readonly StorageWrite[]): Map<DocumentId, DocumentAction> {\n\t\tconst actions = new Map<DocumentId, DocumentAction>();\n\t\tfor (const write of writes) {\n\t\t\tif (write.type !== \"document.create\" && write.type !== \"document.change\" && write.type !== \"document.retire\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst id = write.type === \"document.create\" ? write.record.id : write.id;\n\t\t\tlet action = actions.get(id);\n\t\t\tif (action === undefined) {\n\t\t\t\taction = { retire: false };\n\t\t\t\tactions.set(id, action);\n\t\t\t}\n\t\t\tswitch (write.type) {\n\t\t\t\tcase \"document.create\":\n\t\t\t\t\tif (action.create !== undefined || action.content !== undefined) {\n\t\t\t\t\t\tthrow new Error(`Document ${id} has more than one content command`);\n\t\t\t\t\t}\n\t\t\t\t\taction.create = write.record;\n\t\t\t\t\taction.content = write.content;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"document.change\":\n\t\t\t\t\tif (action.content !== undefined) throw new Error(`Document ${id} has more than one content command`);\n\t\t\t\t\taction.content = write.content;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"document.retire\":\n\t\t\t\t\tif (action.retire) throw new Error(`Document ${id} is retired more than once`);\n\t\t\t\t\taction.retire = true;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn actions;\n\t}\n\n\tprivate checkDocumentActions(actions: ReadonlyMap<DocumentId, DocumentAction>): void {\n\t\tconst liveCounts = new Map<string, number>();\n\t\tfor (const [id, action] of actions) {\n\t\t\tconst existing = this.state.documents.get(id);\n\t\t\tif (action.create === undefined && existing === undefined) throw new Error(`Unknown document: ${id}`);\n\t\t\tif (action.create !== undefined && existing !== undefined) throw new Error(`Document ${id} already exists`);\n\t\t\tif (existing?.record.retiredAt !== undefined) throw new Error(`Document ${id} is retired`);\n\t\t\tconst previous = existing?.revisions.at(-1);\n\t\t\tif (action.content?.kind === \"delta\") {\n\t\t\t\tif (previous === undefined) throw new Error(`Document ${id} delta has no base`);\n\t\t\t\tif (previous.version !== action.content.version) {\n\t\t\t\t\tthrow new Error(`Document ${id} version transition requires a base`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst key = action.create === undefined ? recordAddressKey(existing!.record) : recordAddressKey(action.create);\n\t\t\tconst currentId = this.state.documentAddresses.get(key)?.currentId;\n\t\t\tlet live = liveCounts.get(key);\n\t\t\tif (live === undefined) live = currentId === undefined ? 0 : 1;\n\t\t\tif (action.retire && currentId === id) live--;\n\t\t\tif (action.create !== undefined && !action.retire) live++;\n\t\t\tliveCounts.set(key, live);\n\t\t}\n\n\t\tfor (const live of liveCounts.values()) {\n\t\t\tif (live > 1) throw new Error(`Document address already has a current incarnation`);\n\t\t}\n\t}\n\n\tprivate applyDocumentActions(actions: ReadonlyMap<DocumentId, DocumentAction>, seq: Seq): void {\n\t\tfor (const [id, action] of actions) {\n\t\t\tlet stored = this.state.documents.get(id);\n\t\t\tif (action.create !== undefined) {\n\t\t\t\tconst record: DocumentRecord = {\n\t\t\t\t\t...action.create,\n\t\t\t\t\tcreatedAt: seq,\n\t\t\t\t\t...(action.retire ? { retiredAt: seq } : {}),\n\t\t\t\t};\n\t\t\t\tstored = { record, revisions: [{ ...action.content!, seq }] };\n\t\t\t\tthis.state.recordTypes.set(id, \"document\");\n\t\t\t\tthis.state.documents.set(id, stored);\n\n\t\t\t\tconst key = recordAddressKey(record);\n\t\t\t\tlet address = this.state.documentAddresses.get(key);\n\t\t\t\tif (address === undefined) {\n\t\t\t\t\taddress = { ids: [] };\n\t\t\t\t\tthis.state.documentAddresses.set(key, address);\n\t\t\t\t}\n\t\t\t\tinsertSorted(address.ids, id);\n\n\t\t\t\tlet scopeIds = this.state.documentIdsByScope.get(scopeKey(record.scope));\n\t\t\t\tif (scopeIds === undefined) {\n\t\t\t\t\tscopeIds = [];\n\t\t\t\t\tthis.state.documentIdsByScope.set(scopeKey(record.scope), scopeIds);\n\t\t\t\t}\n\t\t\t\tinsertSorted(scopeIds, id);\n\t\t\t\tthis.nextId = Math.max(this.nextId, id + 1);\n\t\t\t} else if (action.content !== undefined) {\n\t\t\t\tconst revision = { ...action.content, seq } as DocumentRevision;\n\t\t\t\tif (revision.kind === \"base\" && isCurrentOnly(stored!.record)) stored!.revisions = [revision];\n\t\t\t\telse stored!.revisions.push(revision);\n\t\t\t}\n\n\t\t\tif (action.retire && action.create === undefined) stored!.record = { ...stored!.record, retiredAt: seq };\n\t\t\tif (action.retire && isCurrentOnly(stored!.record)) stored!.revisions = [];\n\t\t\tif (action.create !== undefined || action.retire) {\n\t\t\t\tconst address = this.state.documentAddresses.get(recordAddressKey(stored!.record))!;\n\t\t\t\tif (action.retire && address.currentId === id) delete address.currentId;\n\t\t\t\tif (action.create !== undefined && !action.retire) address.currentId = id;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate assertOpen(): void {\n\t\tif (this.closed) throw new Error(\"MemoryStorage is closed\");\n\t}\n}\n"]}
1
+ {"version":3,"file":"memory.js","sourceRoot":"","sources":["../../src/storage/memory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAW,MAAM,6BAA6B,CAAC;AAC7E,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAgCxD,OAAO,EAAE,UAAU,EAAkB,SAAS,EAAE,MAAM,WAAW,CAAC;AAiBlE,QAAQ,CAAC,CAAC,oBAAoB,CAC7B,EAAc,EACd,OAAe,EACf,SAAsC,EACtC,KAAa;IAEb,KAAK,IAAI,KAAK,GAAG,KAAK,EAAE,KAAK,GAAG,SAAS,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC;QAC3D,MAAM,QAAQ,GAAG,SAAS,CAAC,KAAK,CAAE,CAAC;QACnC,IAAI,QAAQ,CAAC,IAAI,KAAK,OAAO,IAAI,QAAQ,CAAC,OAAO,KAAK,OAAO,EAAE,CAAC;YAC/D,MAAM,IAAI,KAAK,CAAC,YAAY,EAAE,mDAAmD,CAAC,CAAC;QACpF,CAAC;QACD,MAAM,QAAQ,CAAC,GAAG,CAAC;IACpB,CAAC;AACF,CAAC;AA6BD,MAAM,KAAK,GAAG,CAAI,KAAQ,EAAK,EAAE;IAChC,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC9D,IAAI,KAAK,CAAC,O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,GAAG,EAAE,CAAC;YAC3E,CAAC;QACF,CAAC;IACF,CAAC;IAEO,UAAU;QACjB,IAAI,IAAI,CAAC,MAAM;YAAE,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7D,CAAC;CACD","sourcesContent":["import type { Context, JsonValue } from \"@earendil-works/chord\";\nimport { applyImmutableBatches, type Op } from \"@earendil-works/chord/delta\";\nimport { StorageRequestError } from \"../errors.ts\";\nimport { idFromNumber, seqFromNumber } from \"../ids.ts\";\nimport type {\n\tCommitResult,\n\tConversationId,\n\tConversationQuery,\n\tConversationRecord,\n\tCursor,\n\tDocumentAddress,\n\tDocumentContent,\n\tDocumentCreate,\n\tDocumentId,\n\tDocumentPoint,\n\tDocumentQuery,\n\tDocumentRecord,\n\tEntryId,\n\tEntryQuery,\n\tEntryRecord,\n\tId,\n\tJsonObject,\n\tPage,\n\tScanOrder,\n\tSeq,\n\tStorage,\n\tStorageWrite,\n\tStoredDocument,\n\tSubmissionId,\n\tSubmissionQuery,\n\tSubmissionRecord,\n\tTaskId,\n\tTaskQuery,\n\tTaskRecord,\n} from \"../types.ts\";\nimport { nextCursor, type ScanStart, scanStart } from \"./scan.ts\";\n\ntype StoredTask = TaskRecord<JsonValue, JsonValue, JsonValue>;\ntype TaskStatus = StoredTask[\"state\"][\"status\"];\ntype SubmissionStatus = SubmissionRecord[\"status\"];\ntype TableName = \"conversation\" | \"entry\" | \"task\" | \"submission\" | \"document\";\ntype DocumentRevision = DocumentContent & { readonly seq: Seq };\ntype StoredDocumentState = {\n\trecord: DocumentRecord;\n\trevisions: DocumentRevision[];\n};\ntype DocumentAction = {\n\tcreate?: DocumentCreate;\n\tcontent?: DocumentContent;\n\tretire: boolean;\n};\n\nfunction* documentDeltaBatches(\n\tid: DocumentId,\n\tversion: number,\n\trevisions: readonly DocumentRevision[],\n\tstart: number,\n): Generator<readonly Op[]> {\n\tfor (let index = start; index < revisions.length; index++) {\n\t\tconst revision = revisions[index]!;\n\t\tif (revision.kind !== \"delta\" || revision.version !== version) {\n\t\t\tthrow new Error(`Document ${id} crosses a stored version boundary without a base`);\n\t\t}\n\t\tyield revision.ops;\n\t}\n}\n\ntype DocumentAddressIndex = {\n\tids: DocumentId[];\n\tcurrentId?: DocumentId;\n};\n\ntype State = {\n\trecordTypes: Map<Id<string>, TableName>;\n\tconversations: Map<ConversationId, ConversationRecord>;\n\tconversationIds: ConversationId[];\n\tconversationIdsByOwnerConversation: Map<ConversationId, ConversationId[]>;\n\tconversationIdsByOwnerTask: Map<TaskId, ConversationId[]>;\n\tentries: Map<EntryId, EntryRecord>;\n\tentryIds: Map<ConversationId, EntryId[]>;\n\theadEntryIds: Map<ConversationId, EntryId[]>;\n\tentryCommitSeqs: Map<EntryId, Seq>;\n\ttasks: Map<TaskId, StoredTask>;\n\ttaskIds: TaskId[];\n\ttaskIdsByStatus: Record<TaskStatus, TaskId[]>;\n\tsubmissions: Map<SubmissionId, SubmissionRecord>;\n\tsubmissionIds: SubmissionId[];\n\tsubmissionIdsByStatus: Record<SubmissionStatus, SubmissionId[]>;\n\tsubmissionIdsByRequest: Map<ConversationId, Map<string, SubmissionId>>;\n\tdocuments: Map<DocumentId, StoredDocumentState>;\n\tdocumentAddresses: Map<string, DocumentAddressIndex>;\n\tdocumentIdsByScope: Map<string, DocumentId[]>;\n};\n\nconst clone = <T>(value: T): T => {\n\tif (value === null || typeof value !== \"object\") return value;\n\tif (Array.isArray(value)) return value.map((item) => clone(item)) as T;\n\tconst source = value as Record<string, unknown>;\n\tconst nullPrototype = Object.getPrototypeOf(value) === null;\n\tconst result = (nullPrototype ? Object.create(null) : {}) as Record<string, unknown>;\n\tfor (const key of Object.keys(source)) {\n\t\tconst copied = clone(source[key]);\n\t\tif (!nullPrototype && key in result) {\n\t\t\tObject.defineProperty(result, key, {\n\t\t\t\tvalue: copied,\n\t\t\t\twritable: true,\n\t\t\t\tenumerable: true,\n\t\t\t\tconfigurable: true,\n\t\t\t});\n\t\t} else {\n\t\t\tresult[key] = copied;\n\t\t}\n\t}\n\treturn result as T;\n};\n\nconst freeze = <T>(value: T): T => {\n\tif (value === null || typeof value !== \"object\" || Object.isFrozen(value)) return value;\n\tfor (const child of Object.values(value)) freeze(child);\n\treturn Object.freeze(value);\n};\n\nconst cursorId = <I extends Id<string>>(cursor: Readonly<Record<string, JsonValue>> | undefined): I | undefined => {\n\tconst after = cursor?.after;\n\tif (after === undefined) return undefined;\n\tif (typeof after !== \"number\" || !Number.isSafeInteger(after))\n\t\tthrow new StorageRequestError(\"Invalid storage cursor\");\n\treturn idFromNumber<I>(after);\n};\n\nconst lowerBound = <I extends Id<string>>(ids: readonly I[], target: number): number => {\n\tlet low = 0;\n\tlet high = ids.length;\n\twhile (low < high) {\n\t\tconst middle = (low + high) >>> 1;\n\t\tif (ids[middle] < target) low = middle + 1;\n\t\telse high = middle;\n\t}\n\treturn low;\n};\n\nconst upperBound = <I extends Id<string>>(ids: readonly I[], target: number): number => {\n\tlet low = 0;\n\tlet high = ids.length;\n\twhile (low < high) {\n\t\tconst middle = (low + high) >>> 1;\n\t\tif (ids[middle] <= target) low = middle + 1;\n\t\telse high = middle;\n\t}\n\treturn low;\n};\n\nconst insertSorted = <I extends Id<string>>(ids: I[], id: I): void => {\n\tif (ids.length === 0 || ids[ids.length - 1] < id) ids.push(id);\n\telse ids.splice(lowerBound(ids, id), 0, id);\n};\n\nconst removeSorted = <I extends Id<string>>(ids: I[], id: I): void => {\n\tconst index = lowerBound(ids, id);\n\tif (ids[index] === id) ids.splice(index, 1);\n};\n\nconst insertMapId = <K, I extends Id<string>>(index: Map<K, I[]>, key: K, id: I): void => {\n\tlet ids = index.get(key);\n\tif (ids === undefined) {\n\t\tids = [];\n\t\tindex.set(key, ids);\n\t}\n\tinsertSorted(ids, id);\n};\n\nconst scopeKey = (scope: DocumentRecord[\"scope\"]): string => {\n\tswitch (scope.kind) {\n\t\tcase \"session\":\n\t\t\treturn JSON.stringify([\"session\"]);\n\t\tcase \"conversation\":\n\t\t\treturn JSON.stringify([\"conversation\", scope.conversationId]);\n\t\tcase \"task\":\n\t\t\treturn JSON.stringify([\"task\", scope.taskId]);\n\t}\n};\n\nconst addressKey = (address: DocumentAddress): string =>\n\tJSON.stringify([\n\t\taddress.kind,\n\t\tscopeKey(address.scope),\n\t\taddress.key === undefined ? [\"singleton\"] : [\"family\", address.key],\n\t]);\n\nconst recordAddressKey = (record: DocumentRecord | DocumentCreate): string =>\n\taddressKey({ kind: record.kind, scope: record.scope, key: record.key });\n\nconst isAliveAt = (record: DocumentRecord, at: DocumentPoint): boolean => {\n\tif (at === \"current\") return record.retiredAt === undefined;\n\treturn record.createdAt <= at && (record.retiredAt === undefined || at < record.retiredAt);\n};\n\nconst isCurrentOnly = (record: DocumentRecord): boolean =>\n\trecord.scope.kind !== \"conversation\" || record.history === \"latest\";\n\nconst tableContaining = (state: State, id: Id<string>): TableName | undefined => state.recordTypes.get(id);\n\nconst page = <T extends { readonly id: Id<string> }>(\n\tvalues: readonly T[],\n\tlimit: number,\n\torder: ScanOrder = \"ascending\",\n): Page<T, Cursor> => {\n\tconst items = values.slice(0, limit);\n\tif (values.length <= limit) return { items: clone(items) };\n\treturn { items: clone(items), next: nextCursor(items.at(-1)!.id, order) };\n};\n\n/** Indexes of sorted `ids` in scan order, after the cursor's ID when there is one. */\nfunction* scanIndexes(ids: readonly Id<string>[], start: ScanStart): Generator<number> {\n\tif (start.order === \"ascending\") {\n\t\tconst first = start.after === undefined ? 0 : upperBound(ids, start.after);\n\t\tfor (let index = first; index < ids.length; index++) yield index;\n\t} else {\n\t\tconst end = start.after === undefined ? ids.length : lowerBound(ids, start.after);\n\t\tfor (let index = end - 1; index >= 0; index--) yield index;\n\t}\n}\n\n/** A fully validated, detached state mutation whose application performs no fallible preparation. */\nexport interface PreparedMemoryCommit {\n\treadonly seq: Seq;\n\t/** Deeply frozen detached writes for persistence. */\n\treadonly writes: readonly StorageWrite[];\n\tapply(): Seq;\n}\n\n/**\n * Detached in-memory reference implementation of `Storage`.\n *\n * Reads and retained writes are cloned intentionally to match the ownership boundary\n * of serialization-backed stores. This is backend conformance, not validation.\n */\nexport class MemoryStorage implements Storage {\n\tprivate readonly state: State = {\n\t\trecordTypes: new Map(),\n\t\tconversations: new Map(),\n\t\tconversationIds: [],\n\t\tconversationIdsByOwnerConversation: new Map(),\n\t\tconversationIdsByOwnerTask: new Map(),\n\t\tentries: new Map(),\n\t\tentryIds: new Map(),\n\t\theadEntryIds: new Map(),\n\t\tentryCommitSeqs: new Map(),\n\t\ttasks: new Map(),\n\t\ttaskIds: [],\n\t\ttaskIdsByStatus: { pending: [], running: [], waiting: [], sleeping: [], completing: [], terminal: [] },\n\t\tsubmissions: new Map(),\n\t\tsubmissionIds: [],\n\t\tsubmissionIdsByStatus: { queued: [], placed: [], done: [], unanswered: [] },\n\t\tsubmissionIdsByRequest: new Map(),\n\t\tdocuments: new Map(),\n\t\tdocumentAddresses: new Map(),\n\t\tdocumentIdsByScope: new Map(),\n\t};\n\tprivate nextId = 2;\n\tprivate nextSeq = 1;\n\tprivate closed = false;\n\n\t/**\n\t * Apply `batches` one by one, each checked against the state the earlier ones left (`prepareCommit()`, which only\n\t * checks and detaches, so a batch it refuses changed nothing); stops at the first one refused. Memory is durable at\n\t * once; the receipts follow the last batch.\n\t */\n\tasync commit(\n\t\tbatches: readonly (readonly StorageWrite[])[],\n\t\treceive: (index: number, seq: Seq) => void,\n\t\t_context: Context,\n\t): Promise<CommitResult> {\n\t\tthis.assertOpen();\n\t\tconst seqs: Seq[] = [];\n\t\tlet refused: { readonly error: unknown } | undefined;\n\t\ttry {\n\t\t\tfor (const writes of batches) {\n\t\t\t\tlet prepared: PreparedMemoryCommit;\n\t\t\t\ttry {\n\t\t\t\t\tprepared = this.prepareCommit(writes);\n\t\t\t\t} catch (error) {\n\t\t\t\t\trefused = { error };\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tseqs.push(prepared.apply());\n\t\t\t}\n\t\t} finally {\n\t\t\t// Also when a batch's apply throws: the batches applied before it are stored, and their receipts stand.\n\t\t\tfor (const [index, seq] of seqs.entries()) receive(index, seq);\n\t\t}\n\t\treturn refused === undefined ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error };\n\t}\n\n\t/** Validate and detach one commit without changing observable state. */\n\tprepareCommit(writes: readonly StorageWrite[], seq: Seq = seqFromNumber(this.nextSeq)): PreparedMemoryCommit {\n\t\tthis.assertOpen();\n\t\tif (!Number.isSafeInteger(seq) || seq < this.nextSeq) {\n\t\t\tthrow new Error(`Commit sequence ${seq} does not strictly increase`);\n\t\t}\n\t\tconst detachedWrites = freeze(this.resolveDocumentCopies(writes.map((write) => clone(write))));\n\t\tthis.checkGlobalIds(detachedWrites);\n\t\tconst documentActions = this.prepareDocumentActions(detachedWrites);\n\t\tthis.checkDocumentActions(documentActions);\n\t\tlet applied = false;\n\t\treturn {\n\t\t\tseq,\n\t\t\twrites: detachedWrites,\n\t\t\tapply: () => {\n\t\t\t\tif (!applied) {\n\t\t\t\t\tapplied = true;\n\t\t\t\t\tthis.applyPreparedCommit(detachedWrites, documentActions, seq);\n\t\t\t\t}\n\t\t\t\treturn seq;\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate resolveDocumentCopies(writes: StorageWrite[]): StorageWrite[] {\n\t\tif (!writes.some((write) => write.type === \"document.copy\")) return writes;\n\t\tconst changedDocumentIds = new Set<DocumentId>();\n\t\tfor (const write of writes) {\n\t\t\tif (write.type === \"document.create\" || write.type === \"document.copy\") {\n\t\t\t\tchangedDocumentIds.add(write.record.id);\n\t\t\t} else if (write.type === \"document.change\" || write.type === \"document.retire\") {\n\t\t\t\tchangedDocumentIds.add(write.id);\n\t\t\t}\n\t\t}\n\t\treturn writes.map((write) => {\n\t\t\tif (write.type !== \"document.copy\") return write;\n\t\t\ttry {\n\t\t\t\tif (changedDocumentIds.has(write.source.id)) {\n\t\t\t\t\tthrow new Error(`Fork source document ${write.source.id} is changed in the copy batch`);\n\t\t\t\t}\n\t\t\t\tconst stored = this.materializeDocument(write.source.id, write.source.at);\n\t\t\t\tif (stored === undefined) throw new Error(`Fork source document ${write.source.id} cannot be read`);\n\t\t\t\tif (\n\t\t\t\t\tstored.record.scope.kind !== \"conversation\" ||\n\t\t\t\t\twrite.record.scope.kind !== \"conversation\" ||\n\t\t\t\t\tstored.record.kind !== write.record.kind ||\n\t\t\t\t\tstored.record.key !== write.record.key ||\n\t\t\t\t\tstored.record.history !== write.record.history ||\n\t\t\t\t\tstored.record.fork !== write.record.fork\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(`Fork source document ${write.source.id} does not match the copied record`);\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"document.create\",\n\t\t\t\t\trecord: write.record,\n\t\t\t\t\tcontent: { kind: \"base\", version: stored.version, value: stored.value },\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tthrow new Error(`Document copy ${write.record.id} was rejected`, { cause: error });\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate applyPreparedCommit(\n\t\tprepared: readonly StorageWrite[],\n\t\tdocumentActions: ReadonlyMap<DocumentId, DocumentAction>,\n\t\tseq: Seq,\n\t): Seq {\n\t\tfor (const write of prepared) {\n\t\t\tswitch (write.type) {\n\t\t\t\tcase \"conversation\": {\n\t\t\t\t\tthis.state.recordTypes.set(write.value.id, \"conversation\");\n\t\t\t\t\tthis.state.conversations.set(write.value.id, write.value);\n\t\t\t\t\tinsertSorted(this.state.conversationIds, write.value.id);\n\t\t\t\t\tconst owner = write.value.owner;\n\t\t\t\t\tif (owner !== undefined) {\n\t\t\t\t\t\tinsertMapId(this.state.conversationIdsByOwnerConversation, owner.conversationId, write.value.id);\n\t\t\t\t\t\tinsertMapId(this.state.conversationIdsByOwnerTask, owner.taskId, write.value.id);\n\t\t\t\t\t}\n\t\t\t\t\tthis.nextId = Math.max(this.nextId, write.value.id + 1);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"entry\": {\n\t\t\t\t\tthis.state.recordTypes.set(write.value.id, \"entry\");\n\t\t\t\t\tthis.state.entries.set(write.value.id, write.value);\n\t\t\t\t\tthis.state.entryCommitSeqs.set(write.value.id, seq);\n\t\t\t\t\tlet ids = this.state.entryIds.get(write.value.conversationId);\n\t\t\t\t\tif (ids === undefined) {\n\t\t\t\t\t\tids = [];\n\t\t\t\t\t\tthis.state.entryIds.set(write.value.conversationId, ids);\n\t\t\t\t\t}\n\t\t\t\t\tinsertSorted(ids, write.value.id);\n\t\t\t\t\tif (write.value.head !== undefined) {\n\t\t\t\t\t\tlet headIds = this.state.headEntryIds.get(write.value.conversationId);\n\t\t\t\t\t\tif (headIds === undefined) {\n\t\t\t\t\t\t\theadIds = [];\n\t\t\t\t\t\t\tthis.state.headEntryIds.set(write.value.conversationId, headIds);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tinsertSorted(headIds, write.value.id);\n\t\t\t\t\t}\n\t\t\t\t\tthis.nextId = Math.max(this.nextId, write.value.id + 1);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"task\": {\n\t\t\t\t\tthis.state.recordTypes.set(write.value.id, \"task\");\n\t\t\t\t\tconst previous = this.state.tasks.get(write.value.id);\n\t\t\t\t\tif (previous === undefined) {\n\t\t\t\t\t\tinsertSorted(this.state.taskIds, write.value.id);\n\t\t\t\t\t\tinsertSorted(this.state.taskIdsByStatus[write.value.state.status], write.value.id);\n\t\t\t\t\t} else if (previous.state.status !== write.value.state.status) {\n\t\t\t\t\t\tremoveSorted(this.state.taskIdsByStatus[previous.state.status], write.value.id);\n\t\t\t\t\t\tinsertSorted(this.state.taskIdsByStatus[write.value.state.status], write.value.id);\n\t\t\t\t\t}\n\t\t\t\t\tthis.state.tasks.set(write.value.id, write.value);\n\t\t\t\t\tthis.nextId = Math.max(this.nextId, write.value.id + 1);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"submission\": {\n\t\t\t\t\tthis.state.recordTypes.set(write.value.id, \"submission\");\n\t\t\t\t\tconst previous = this.state.submissions.get(write.value.id);\n\t\t\t\t\tif (previous === undefined) {\n\t\t\t\t\t\tinsertSorted(this.state.submissionIds, write.value.id);\n\t\t\t\t\t\tinsertSorted(this.state.submissionIdsByStatus[write.value.status], write.value.id);\n\t\t\t\t\t} else if (previous.status !== write.value.status) {\n\t\t\t\t\t\tremoveSorted(this.state.submissionIdsByStatus[previous.status], write.value.id);\n\t\t\t\t\t\tinsertSorted(this.state.submissionIdsByStatus[write.value.status], write.value.id);\n\t\t\t\t\t}\n\t\t\t\t\tif (previous?.requestId !== undefined) {\n\t\t\t\t\t\tconst previousRequests = this.state.submissionIdsByRequest.get(previous.conversationId);\n\t\t\t\t\t\tif (previousRequests?.get(previous.requestId) === write.value.id) {\n\t\t\t\t\t\t\tpreviousRequests.delete(previous.requestId);\n\t\t\t\t\t\t\tif (previousRequests.size === 0) this.state.submissionIdsByRequest.delete(previous.conversationId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tthis.state.submissions.set(write.value.id, write.value);\n\t\t\t\t\tif (write.value.requestId !== undefined) {\n\t\t\t\t\t\tlet requests = this.state.submissionIdsByRequest.get(write.value.conversationId);\n\t\t\t\t\t\tif (requests === undefined) {\n\t\t\t\t\t\t\trequests = new Map();\n\t\t\t\t\t\t\tthis.state.submissionIdsByRequest.set(write.value.conversationId, requests);\n\t\t\t\t\t\t}\n\t\t\t\t\t\trequests.set(write.value.requestId, write.value.id);\n\t\t\t\t\t}\n\t\t\t\t\tthis.nextId = Math.max(this.nextId, write.value.id + 1);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"document.copy\":\n\t\t\t\t\tthrow new Error(\"Prepared document copy was not resolved\");\n\t\t\t\tcase \"document.create\":\n\t\t\t\tcase \"document.change\":\n\t\t\t\tcase \"document.retire\":\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tthis.applyDocumentActions(documentActions, seq);\n\t\tthis.nextSeq = seq + 1;\n\t\treturn seq;\n\t}\n\n\tasync mintId<I extends Id<string>>(): Promise<I> {\n\t\tthis.assertOpen();\n\t\tif (!Number.isSafeInteger(this.nextId)) throw new Error(\"ID space is exhausted\");\n\t\treturn idFromNumber<I>(this.nextId++);\n\t}\n\n\tasync conversation(id: ConversationId, _context: Context): Promise<ConversationRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst value = this.state.conversations.get(id);\n\t\treturn value === undefined ? undefined : clone(value);\n\t}\n\n\tasync scanConversations(\n\t\tquery: ConversationQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<ConversationRecord, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst ids =\n\t\t\tquery.ownerTaskId !== undefined\n\t\t\t\t? (this.state.conversationIdsByOwnerTask.get(query.ownerTaskId) ?? [])\n\t\t\t\t: query.ownerConversationId !== undefined\n\t\t\t\t\t? (this.state.conversationIdsByOwnerConversation.get(query.ownerConversationId) ?? [])\n\t\t\t\t\t: this.state.conversationIds;\n\t\tconst start = scanStart(query.order, cursor, \"ascending\");\n\t\tconst values: ConversationRecord[] = [];\n\t\tfor (const index of scanIndexes(ids, start)) {\n\t\t\tif (values.length > limit) break;\n\t\t\tconst value = this.state.conversations.get(ids[index]!)!;\n\t\t\tif (query.ownerConversationId !== undefined && value.owner?.conversationId !== query.ownerConversationId) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvalues.push(value);\n\t\t}\n\t\treturn page(values, limit, start.order);\n\t}\n\n\tentry(id: EntryId, context: Context): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined>;\n\tentry(\n\t\tconversationId: ConversationId,\n\t\tid: EntryId,\n\t\tcontext: Context,\n\t): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined>;\n\tasync entry(\n\t\tidOrConversationId: EntryId | ConversationId,\n\t\tidOrContext: EntryId | Context,\n\t\tcontext?: Context,\n\t): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined> {\n\t\tthis.assertOpen();\n\t\tif (context === undefined) {\n\t\t\tconst id = idFromNumber<EntryId>(idOrConversationId);\n\t\t\tconst entry = this.state.entries.get(id);\n\t\t\tif (entry === undefined) return undefined;\n\t\t\treturn { entry: clone(entry), commitSeq: this.state.entryCommitSeqs.get(id)! };\n\t\t}\n\t\tif (typeof idOrContext !== \"number\") throw new StorageRequestError(\"Storage.entry() requires an entry ID\");\n\t\tconst conversationId = idFromNumber<ConversationId>(idOrConversationId);\n\t\tconst id = idFromNumber<EntryId>(idOrContext);\n\t\tconst entry = this.visibleEntries(conversationId, id, id).next().value;\n\t\tif (entry === undefined) return undefined;\n\t\treturn { entry: clone(entry), commitSeq: this.state.entryCommitSeqs.get(id)! };\n\t}\n\n\tasync findLatestHeadMarker(\n\t\tconversationId: ConversationId,\n\t\tatOrBeforeEntryId: EntryId | undefined,\n\t\t_context: Context,\n\t): Promise<(EntryRecord & { readonly head: EntryId }) | undefined> {\n\t\tthis.assertOpen();\n\t\tif (!this.state.conversations.has(conversationId)) {\n\t\t\tthrow new StorageRequestError(`Unknown conversation: ${conversationId}`);\n\t\t}\n\t\tlet currentId = conversationId;\n\t\tlet upperEntryId = atOrBeforeEntryId ?? Number.POSITIVE_INFINITY;\n\t\twhile (true) {\n\t\t\tconst ids = this.state.headEntryIds.get(currentId) ?? [];\n\t\t\tconst index = upperBound(ids, upperEntryId) - 1;\n\t\t\tif (index >= 0) {\n\t\t\t\tconst entry = this.state.entries.get(ids[index])!;\n\t\t\t\treturn clone({ ...entry, head: entry.head! });\n\t\t\t}\n\t\t\tconst conversation = this.state.conversations.get(currentId)!;\n\t\t\tif (conversation.parent === undefined) return undefined;\n\t\t\tupperEntryId = Math.min(upperEntryId, conversation.parent.at);\n\t\t\tcurrentId = conversation.parent.conversationId;\n\t\t}\n\t}\n\n\tasync scanEntries(\n\t\tquery: EntryQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<EntryRecord, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst { order, after } = scanStart(query.order, cursor, \"descending\");\n\t\t// The cursor narrows the bound on the side the scan moves away from.\n\t\tlet minEntryId: number | undefined = query.minEntryId;\n\t\tlet maxEntryId: number | undefined = query.maxEntryId;\n\t\tif (after !== undefined && order === \"descending\") maxEntryId = Math.min(maxEntryId ?? after, after - 1);\n\t\tif (after !== undefined && order === \"ascending\") minEntryId = Math.max(minEntryId ?? after, after + 1);\n\t\tconst visible: EntryRecord[] = [];\n\t\tconst entries =\n\t\t\torder === \"descending\"\n\t\t\t\t? this.visibleEntries(query.conversationId, minEntryId, maxEntryId)\n\t\t\t\t: this.visibleEntriesAscending(query.conversationId, minEntryId, maxEntryId);\n\t\tfor (const entry of entries) {\n\t\t\tvisible.push(entry);\n\t\t\tif (visible.length > limit) break;\n\t\t}\n\t\treturn page(visible, limit, order);\n\t}\n\n\tasync task(id: TaskId, _context: Context): Promise<StoredTask | undefined> {\n\t\tthis.assertOpen();\n\t\tconst value = this.state.tasks.get(id);\n\t\treturn value === undefined ? undefined : clone(value);\n\t}\n\n\tasync scanTasks(\n\t\tquery: TaskQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<StoredTask, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst start = scanStart(query.order, cursor, \"ascending\");\n\t\tconst ids = query.status === undefined ? this.state.taskIds : this.state.taskIdsByStatus[query.status];\n\t\tconst values: StoredTask[] = [];\n\t\tfor (const index of scanIndexes(ids, start)) {\n\t\t\tif (values.length > limit) break;\n\t\t\tconst value = this.state.tasks.get(ids[index]!)!;\n\t\t\tif (query.conversationId !== undefined && value.conversationId !== query.conversationId) continue;\n\t\t\tif (query.kind !== undefined && value.kind !== query.kind) continue;\n\t\t\tif (query.abortRequested !== undefined && value.abortRequested !== query.abortRequested) continue;\n\t\t\tif (query.background !== undefined && value.background !== query.background) continue;\n\t\t\tvalues.push(value);\n\t\t}\n\t\treturn page(values, limit, start.order);\n\t}\n\n\tasync submission(id: SubmissionId, _context: Context): Promise<SubmissionRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst value = this.state.submissions.get(id);\n\t\treturn value === undefined ? undefined : clone(value);\n\t}\n\n\tasync scanSubmissions(\n\t\tquery: SubmissionQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<SubmissionRecord, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst start = scanStart(query.order, cursor, \"ascending\");\n\t\tconst ids =\n\t\t\tquery.status === undefined ? this.state.submissionIds : this.state.submissionIdsByStatus[query.status];\n\t\tconst values: SubmissionRecord[] = [];\n\t\tfor (const index of scanIndexes(ids, start)) {\n\t\t\tif (values.length > limit) break;\n\t\t\tconst value = this.state.submissions.get(ids[index]!)!;\n\t\t\tif (query.conversationId !== undefined && value.conversationId !== query.conversationId) continue;\n\t\t\tvalues.push(value);\n\t\t}\n\t\treturn page(values, limit, start.order);\n\t}\n\n\tasync submissionByRequest(\n\t\tconversationId: ConversationId,\n\t\trequestId: string,\n\t\t_context: Context,\n\t): Promise<SubmissionRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst id = this.state.submissionIdsByRequest.get(conversationId)?.get(requestId);\n\t\tif (id === undefined) return undefined;\n\t\treturn clone(this.state.submissions.get(id)!);\n\t}\n\n\tasync findDocument(\n\t\taddress: DocumentAddress,\n\t\tat: DocumentPoint,\n\t\t_context: Context,\n\t): Promise<DocumentRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst index = this.state.documentAddresses.get(addressKey(address));\n\t\tif (at === \"current\") {\n\t\t\treturn index?.currentId === undefined ? undefined : clone(this.state.documents.get(index.currentId)!.record);\n\t\t}\n\t\tfor (const id of index?.ids ?? []) {\n\t\t\tconst record = this.state.documents.get(id)!.record;\n\t\t\tif (isAliveAt(record, at)) return clone(record);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tasync document(id: DocumentId, at: DocumentPoint, _context: Context): Promise<StoredDocument | undefined> {\n\t\tthis.assertOpen();\n\t\tconst stored = this.materializeDocument(id, at);\n\t\treturn stored === undefined\n\t\t\t? undefined\n\t\t\t: {\n\t\t\t\t\trecord: clone(stored.record),\n\t\t\t\t\tversion: stored.version,\n\t\t\t\t\tvalue: clone(stored.value),\n\t\t\t\t\tdeltasSinceBase: stored.deltasSinceBase,\n\t\t\t\t};\n\t}\n\n\tasync scanDocuments(\n\t\tquery: DocumentQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<DocumentRecord, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst ids = this.state.documentIdsByScope.get(scopeKey(query.scope)) ?? [];\n\t\tconst after = cursorId(cursor);\n\t\tconst start = after === undefined ? 0 : upperBound(ids, after);\n\t\tconst values: DocumentRecord[] = [];\n\t\tfor (let index = start; index < ids.length && values.length <= limit; index++) {\n\t\t\tconst record = this.state.documents.get(ids[index]!)!.record;\n\t\t\tif (query.kind !== undefined && record.kind !== query.kind) continue;\n\t\t\tif (isAliveAt(record, query.at)) values.push(record);\n\t\t}\n\t\treturn page(values, limit);\n\t}\n\n\tasync close(_context: Context): Promise<void> {\n\t\tthis.closed = true;\n\t}\n\n\tprivate materializeDocument(id: DocumentId, at: DocumentPoint): StoredDocument | undefined {\n\t\tconst stored = this.state.documents.get(id);\n\t\tif (stored === undefined) return undefined;\n\t\tif (at !== \"current\" && isCurrentOnly(stored.record)) {\n\t\t\tthrow new StorageRequestError(`Document ${id} does not retain historical content`);\n\t\t}\n\t\tif (!isAliveAt(stored.record, at)) return undefined;\n\t\tconst revisions = at === \"current\" ? stored.revisions : stored.revisions.filter((revision) => revision.seq <= at);\n\t\tlet baseIndex = revisions.length - 1;\n\t\twhile (baseIndex >= 0 && revisions[baseIndex]!.kind !== \"base\") baseIndex--;\n\t\tconst base = revisions[baseIndex];\n\t\tif (base?.kind !== \"base\") throw new Error(`Document ${id} is missing a required base`);\n\t\tconst value = applyImmutableBatches(\n\t\t\tbase.value,\n\t\t\tdocumentDeltaBatches(id, base.version, revisions, baseIndex + 1),\n\t\t) as JsonObject;\n\t\treturn { record: stored.record, version: base.version, value, deltasSinceBase: revisions.length - baseIndex - 1 };\n\t}\n\n\tprivate *visibleEntries(\n\t\tconversationId: ConversationId,\n\t\tminEntryId: number = Number.NEGATIVE_INFINITY,\n\t\tmaxEntryId: number = Number.POSITIVE_INFINITY,\n\t): Generator<EntryRecord> {\n\t\tif (!this.state.conversations.has(conversationId)) {\n\t\t\tthrow new StorageRequestError(`Unknown conversation: ${conversationId}`);\n\t\t}\n\t\tlet currentId = conversationId;\n\t\tlet upperEntryId = maxEntryId;\n\t\twhile (true) {\n\t\t\tconst ids = this.state.entryIds.get(currentId) ?? [];\n\t\t\tfor (let index = upperBound(ids, upperEntryId) - 1; index >= 0; index--) {\n\t\t\t\tconst id = ids[index];\n\t\t\t\tif (id < minEntryId) break;\n\t\t\t\tyield this.state.entries.get(id)!;\n\t\t\t}\n\t\t\tconst conversation = this.state.conversations.get(currentId)!;\n\t\t\tif (conversation.parent === undefined) break;\n\t\t\tupperEntryId = Math.min(upperEntryId, conversation.parent.at);\n\t\t\tif (upperEntryId < minEntryId) break;\n\t\t\tcurrentId = conversation.parent.conversationId;\n\t\t}\n\t}\n\n\t/** Visible entries oldest first: the fork chain's segments from the root conversation forward. */\n\tprivate *visibleEntriesAscending(\n\t\tconversationId: ConversationId,\n\t\tminEntryId: number = Number.NEGATIVE_INFINITY,\n\t\tmaxEntryId: number = Number.POSITIVE_INFINITY,\n\t): Generator<EntryRecord> {\n\t\tif (!this.state.conversations.has(conversationId)) {\n\t\t\tthrow new StorageRequestError(`Unknown conversation: ${conversationId}`);\n\t\t}\n\t\tconst segments: { readonly conversationId: ConversationId; readonly upper: number }[] = [];\n\t\tlet currentId = conversationId;\n\t\tlet upperEntryId = maxEntryId;\n\t\twhile (true) {\n\t\t\tsegments.push({ conversationId: currentId, upper: upperEntryId });\n\t\t\tconst conversation = this.state.conversations.get(currentId)!;\n\t\t\tif (conversation.parent === undefined) break;\n\t\t\tupperEntryId = Math.min(upperEntryId, conversation.parent.at);\n\t\t\tif (upperEntryId < minEntryId) break;\n\t\t\tcurrentId = conversation.parent.conversationId;\n\t\t}\n\t\tfor (const segment of segments.reverse()) {\n\t\t\tconst ids = this.state.entryIds.get(segment.conversationId) ?? [];\n\t\t\tfor (let index = lowerBound(ids, minEntryId); index < ids.length; index++) {\n\t\t\t\tconst id = ids[index]!;\n\t\t\t\tif (id > segment.upper) break;\n\t\t\t\tyield this.state.entries.get(id)!;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate checkGlobalIds(writes: readonly StorageWrite[]): void {\n\t\tconst claimed = new Map<Id<string>, TableName>();\n\t\tfor (const write of writes) {\n\t\t\tif (write.type === \"document.change\" || write.type === \"document.retire\") continue;\n\t\t\tconst document = write.type === \"document.create\" || write.type === \"document.copy\";\n\t\t\tconst table: TableName = document ? \"document\" : write.type;\n\t\t\tconst id = document ? write.record.id : write.value.id;\n\t\t\tconst existing = tableContaining(this.state, id);\n\t\t\tconst earlier = claimed.get(id);\n\t\t\tif (table === \"conversation\" || table === \"entry\" || table === \"document\") {\n\t\t\t\tif (existing !== undefined) throw new Error(`ID ${id} already belongs to ${existing}`);\n\t\t\t\tif (earlier !== undefined) throw new Error(`ID ${id} is written more than once`);\n\t\t\t} else {\n\t\t\t\tif (existing !== undefined && existing !== table) {\n\t\t\t\t\tthrow new Error(`ID ${id} already belongs to ${existing}`);\n\t\t\t\t}\n\t\t\t\tif (earlier !== undefined && earlier !== table) throw new Error(`ID ${id} is written as two record types`);\n\t\t\t}\n\t\t\tclaimed.set(id, table);\n\t\t}\n\t}\n\n\tprivate prepareDocumentActions(writes: readonly StorageWrite[]): Map<DocumentId, DocumentAction> {\n\t\tconst actions = new Map<DocumentId, DocumentAction>();\n\t\tfor (const write of writes) {\n\t\t\tif (write.type !== \"document.create\" && write.type !== \"document.change\" && write.type !== \"document.retire\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst id = write.type === \"document.create\" ? write.record.id : write.id;\n\t\t\tlet action = actions.get(id);\n\t\t\tif (action === undefined) {\n\t\t\t\taction = { retire: false };\n\t\t\t\tactions.set(id, action);\n\t\t\t}\n\t\t\tswitch (write.type) {\n\t\t\t\tcase \"document.create\":\n\t\t\t\t\tif (action.create !== undefined || action.content !== undefined) {\n\t\t\t\t\t\tthrow new Error(`Document ${id} has more than one content command`);\n\t\t\t\t\t}\n\t\t\t\t\taction.create = write.record;\n\t\t\t\t\taction.content = write.content;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"document.change\":\n\t\t\t\t\tif (action.content !== undefined) throw new Error(`Document ${id} has more than one content command`);\n\t\t\t\t\taction.content = write.content;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"document.retire\":\n\t\t\t\t\tif (action.retire) throw new Error(`Document ${id} is retired more than once`);\n\t\t\t\t\taction.retire = true;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn actions;\n\t}\n\n\tprivate checkDocumentActions(actions: ReadonlyMap<DocumentId, DocumentAction>): void {\n\t\tconst liveCounts = new Map<string, number>();\n\t\tfor (const [id, action] of actions) {\n\t\t\tconst existing = this.state.documents.get(id);\n\t\t\tif (action.create === undefined && existing === undefined) throw new Error(`Unknown document: ${id}`);\n\t\t\tif (action.create !== undefined && existing !== undefined) throw new Error(`Document ${id} already exists`);\n\t\t\tif (existing?.record.retiredAt !== undefined) throw new Error(`Document ${id} is retired`);\n\t\t\tconst previous = existing?.revisions.at(-1);\n\t\t\tif (action.content?.kind === \"delta\") {\n\t\t\t\tif (previous === undefined) throw new Error(`Document ${id} delta has no base`);\n\t\t\t\tif (previous.version !== action.content.version) {\n\t\t\t\t\tthrow new Error(`Document ${id} version transition requires a base`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst key = action.create === undefined ? recordAddressKey(existing!.record) : recordAddressKey(action.create);\n\t\t\tconst currentId = this.state.documentAddresses.get(key)?.currentId;\n\t\t\tlet live = liveCounts.get(key);\n\t\t\tif (live === undefined) live = currentId === undefined ? 0 : 1;\n\t\t\tif (action.retire && currentId === id) live--;\n\t\t\tif (action.create !== undefined && !action.retire) live++;\n\t\t\tliveCounts.set(key, live);\n\t\t}\n\n\t\tfor (const live of liveCounts.values()) {\n\t\t\tif (live > 1) throw new Error(`Document address already has a current incarnation`);\n\t\t}\n\t}\n\n\tprivate applyDocumentActions(actions: ReadonlyMap<DocumentId, DocumentAction>, seq: Seq): void {\n\t\tfor (const [id, action] of actions) {\n\t\t\tlet stored = this.state.documents.get(id);\n\t\t\tif (action.create !== undefined) {\n\t\t\t\tconst record: DocumentRecord = {\n\t\t\t\t\t...action.create,\n\t\t\t\t\tcreatedAt: seq,\n\t\t\t\t\t...(action.retire ? { retiredAt: seq } : {}),\n\t\t\t\t};\n\t\t\t\tstored = { record, revisions: [{ ...action.content!, seq }] };\n\t\t\t\tthis.state.recordTypes.set(id, \"document\");\n\t\t\t\tthis.state.documents.set(id, stored);\n\n\t\t\t\tconst key = recordAddressKey(record);\n\t\t\t\tlet address = this.state.documentAddresses.get(key);\n\t\t\t\tif (address === undefined) {\n\t\t\t\t\taddress = { ids: [] };\n\t\t\t\t\tthis.state.documentAddresses.set(key, address);\n\t\t\t\t}\n\t\t\t\tinsertSorted(address.ids, id);\n\n\t\t\t\tlet scopeIds = this.state.documentIdsByScope.get(scopeKey(record.scope));\n\t\t\t\tif (scopeIds === undefined) {\n\t\t\t\t\tscopeIds = [];\n\t\t\t\t\tthis.state.documentIdsByScope.set(scopeKey(record.scope), scopeIds);\n\t\t\t\t}\n\t\t\t\tinsertSorted(scopeIds, id);\n\t\t\t\tthis.nextId = Math.max(this.nextId, id + 1);\n\t\t\t} else if (action.content !== undefined) {\n\t\t\t\tconst revision = { ...action.content, seq } as DocumentRevision;\n\t\t\t\tif (revision.kind === \"base\" && isCurrentOnly(stored!.record)) stored!.revisions = [revision];\n\t\t\t\telse stored!.revisions.push(revision);\n\t\t\t}\n\n\t\t\tif (action.retire && action.create === undefined) stored!.record = { ...stored!.record, retiredAt: seq };\n\t\t\tif (action.retire && isCurrentOnly(stored!.record)) stored!.revisions = [];\n\t\t\tif (action.create !== undefined || action.retire) {\n\t\t\t\tconst address = this.state.documentAddresses.get(recordAddressKey(stored!.record))!;\n\t\t\t\tif (action.retire && address.currentId === id) delete address.currentId;\n\t\t\t\tif (action.create !== undefined && !action.retire) address.currentId = id;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate assertOpen(): void {\n\t\tif (this.closed) throw new Error(\"MemoryStorage is closed\");\n\t}\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import type { Context, JsonValue } from "@earendil-works/chord";
2
2
  import type { SqliteDatabase } from "@earendil-works/chord/sqlite";
3
- import type { ConversationId, ConversationQuery, ConversationRecord, Cursor, DocumentAddress, DocumentId, DocumentPoint, DocumentQuery, DocumentRecord, EntryId, EntryQuery, EntryRecord, Id, Page, Seq, Storage, StorageWrite, StoredDocument, SubmissionId, SubmissionQuery, SubmissionRecord, TaskId, TaskQuery, TaskRecord } from "../../types.ts";
3
+ import type { CommitResult, ConversationId, ConversationQuery, ConversationRecord, Cursor, DocumentAddress, DocumentId, DocumentPoint, DocumentQuery, DocumentRecord, EntryId, EntryQuery, EntryRecord, Id, Page, Seq, Storage, StorageWrite, StoredDocument, SubmissionId, SubmissionQuery, SubmissionRecord, TaskId, TaskQuery, TaskRecord } from "../../types.ts";
4
4
  type StoredTask = TaskRecord<JsonValue, JsonValue, JsonValue>;
5
5
  export type SqliteStorageOptions = {
6
6
  /**
@@ -21,7 +21,17 @@ export declare class SqliteStorage implements Storage {
21
21
  private constructor();
22
22
  /** Initialize storage over an owned SQLite database facade. */
23
23
  static open(db: SqliteDatabase, options?: SqliteStorageOptions): Promise<SqliteStorage>;
24
- commit(writes: readonly StorageWrite[], _context: Context): Promise<Seq>;
24
+ /**
25
+ * Commit `batches` in one SQL transaction, each with its own seq. Each batch is checked before it writes anything,
26
+ * against the state the earlier ones left, and the first one refused ends the batch: the transaction commits the ones
27
+ * before it. No savepoints, which Durable Objects do not allow: the checks run before the writes instead.
28
+ */
29
+ commit(batches: readonly (readonly StorageWrite[])[], receive: (index: number, seq: Seq) => void, _context: Context): Promise<CommitResult>;
30
+ private readMetadata;
31
+ private writeMetadata;
32
+ /** Durable's own checks of one batch, copy resolution included, before it writes anything. */
33
+ private checkBatch;
34
+ private applyBatch;
25
35
  mintId<I extends Id<string>>(): Promise<I>;
26
36
  conversation(id: ConversationId, _context: Context): Promise<ConversationRecord | undefined>;
27
37
  scanConversations(query: ConversationQuery, limit: number, cursor: Cursor | undefined, _context: Context): Promise<Page<ConversationRecord, Cursor>>;
@@ -66,6 +76,8 @@ export declare class SqliteStorage implements Storage {
66
76
  private currentDocumentId;
67
77
  private applyTableWrite;
68
78
  private claimId;
79
+ /** Resolve each copy to a base of its source's state before this batch, which may not change the source. */
80
+ private resolveCopies;
69
81
  private applyDocumentActions;
70
82
  private assertOpen;
71
83
  }
@@ -1 +1 @@
1
- {"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../../../src/storage/sqlite/storage.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAEhE,OAAO,KAAK,EAAE,cAAc,EAA+B,MAAM,8BAA8B,CAAC;AAGhG,OAAO,KAAK,EACX,cAAc,EACd,iBAAiB,EACjB,kBAAkB,EAClB,MAAM,EACN,eAAe,EAGf,UAAU,EACV,aAAa,EACb,aAAa,EACb,cAAc,EACd,OAAO,EACP,UAAU,EACV,WAAW,EACX,EAAE,EAEF,IAAI,EAEJ,GAAG,EACH,OAAO,EACP,YAAY,EACZ,cAAc,EACd,YAAY,EACZ,eAAe,EACf,gBAAgB,EAChB,MAAM,EACN,SAAS,EACT,UAAU,E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AM,EACb,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,QAAQ,EAAE,OAAO,GACf,OAAO,CAAC,IAAI,CAAC,cAAc,EAAE,MAAM,CAAC,CAAC,CAwBvC;IAED,KAAK,CAAC,QAAQ,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAMtC;YAEa,aAAa;IAS3B;;;OAGG;YACW,SAAS;YAUT,gBAAgB;YAKhB,mBAAmB;IAqCjC,OAAO,CAAC,eAAe;YAST,cAAc;IAuB5B,OAAO,CAAC,sBAAsB;YA+ChB,oBAAoB;YAqCpB,iBAAiB;YAoBjB,eAAe;YA6Df,OAAO;IAQrB,4GAA4G;YAC9F,aAAa;YAwBb,oBAAoB;IAuElC,OAAO,CAAC,UAAU;CAGlB"}
@@ -70,6 +70,28 @@ const writeId = (write) => {
70
70
  return undefined;
71
71
  }
72
72
  };
73
+ /**
74
+ * `executor`, setting `calls.failed` when one of its calls throws, synchronously (a synchronous driver) or by
75
+ * rejecting, with any value: then a failing check is the database's, not one of Durable's own.
76
+ */
77
+ function watchCalls(executor, calls) {
78
+ const watched = async (call) => {
79
+ try {
80
+ return await call();
81
+ }
82
+ catch (error) {
83
+ calls.failed = true;
84
+ throw error;
85
+ }
86
+ };
87
+ return {
88
+ exec: (sql) => watched(() => executor.exec(sql)),
89
+ run: (sql, ...params) => watched(() => executor.run(sql, ...params)),
90
+ runCounted: (sql, ...params) => watched(() => executor.runCounted(sql, ...params)),
91
+ get: (sql, ...params) => watched(() => executor.get(sql, ...params)),
92
+ all: (sql, ...params) => watched(() => executor.all(sql, ...params)),
93
+ };
94
+ }
73
95
  /** Portable SQLite implementation of the Pico storage contract. */
74
96
  export class SqliteStorage {
75
97
  db;
@@ -104,25 +126,71 @@ export class SqliteStorage {
104
126
  throw error;
105
127
  }
106
128
  }
107
- async commit(writes, _context) {
129
+ /**
130
+ * Commit `batches` in one SQL transaction, each with its own seq. Each batch is checked before it writes anything,
131
+ * against the state the earlier ones left, and the first one refused ends the batch: the transaction commits the ones
132
+ * before it. No savepoints, which Durable Objects do not allow: the checks run before the writes instead.
133
+ */
134
+ async commit(batches, receive, _context) {
108
135
  this.assertOpen();
109
- const documentActions = this.prepareDocumentActions(writes);
110
- const candidateNextId = this.candidateNextId(writes);
111
- const seq = await this.db.transaction(async (transaction) => {
112
- const metadata = await transaction.get(`SELECT next_id, next_seq FROM ${this.schema.tables.durableMetadata} WHERE singleton = 1`);
113
- if (metadata === undefined)
114
- throw new Error("Durable SQLite metadata is missing");
115
- const committedSeq = seqFromNumber(metadata.next_seq);
116
- await this.checkGlobalIds(transaction, writes);
117
- await this.checkDocumentActions(transaction, documentActions);
118
- for (const write of writes)
119
- await this.applyTableWrite(transaction, write, committedSeq);
120
- await this.applyDocumentActions(transaction, documentActions, committedSeq);
121
- await transaction.run(`UPDATE ${this.schema.tables.durableMetadata} SET next_id = ?, next_seq = ? WHERE singleton = 1`, String(Math.max(Number(metadata.next_id), candidateNextId)), committedSeq + 1);
122
- return committedSeq;
136
+ const seqs = [];
137
+ let refused;
138
+ let candidateNextId = this.nextId;
139
+ await this.db.transaction(async (transaction) => {
140
+ const metadata = await this.readMetadata(transaction);
141
+ let next = metadata.next_seq;
142
+ // Whether a database call of a batch's checks failed: then the failure is an unknown outcome, not a refusal.
143
+ const calls = { failed: false };
144
+ const checked = watchCalls(transaction, calls);
145
+ for (const writes of batches) {
146
+ let documentActions;
147
+ // Only Durable's own checks refuse a batch, before it wrote anything: the ones before it stand. A failure of
148
+ // the database rejects the call, and rolls back the batches before it with the transaction.
149
+ calls.failed = false;
150
+ try {
151
+ documentActions = this.prepareDocumentActions(writes);
152
+ await this.checkBatch(checked, writes, documentActions);
153
+ }
154
+ catch (error) {
155
+ if (calls.failed)
156
+ throw error;
157
+ refused = { error };
158
+ break;
159
+ }
160
+ const seq = seqFromNumber(next++);
161
+ await this.applyBatch(transaction, writes, documentActions, seq);
162
+ seqs.push(seq);
163
+ candidateNextId = Math.max(candidateNextId, this.candidateNextId(writes));
164
+ }
165
+ if (seqs.length > 0) {
166
+ await this.writeMetadata(transaction, Math.max(Number(metadata.next_id), candidateNextId), next);
167
+ }
123
168
  });
124
169
  this.nextId = Math.max(this.nextId, candidateNextId);
125
- return seq;
170
+ // `COMMIT` returned: the stored batches are durable.
171
+ for (const [index, seq] of seqs.entries())
172
+ receive(index, seq);
173
+ return refused === undefined ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error };
174
+ }
175
+ async readMetadata(executor) {
176
+ const metadata = await executor.get(`SELECT next_id, next_seq FROM ${this.schema.tables.durableMetadata} WHERE singleton = 1`);
177
+ if (metadata === undefined)
178
+ throw new Error("Durable SQLite metadata is missing");
179
+ return metadata;
180
+ }
181
+ async writeMetadata(executor, nextId, nextSeq) {
182
+ await executor.run(`UPDATE ${this.schema.tables.durableMetadata} SET next_id = ?, next_seq = ? WHERE singleton = 1`, String(nextId), nextSeq);
183
+ }
184
+ /** Durable's own checks of one batch, copy resolution included, before it writes anything. */
185
+ async checkBatch(executor, writes, documentActions) {
186
+ await this.checkGlobalIds(executor, writes);
187
+ await this.checkDocumentActions(executor, documentActions);
188
+ await this.resolveCopies(executor, documentActions);
189
+ }
190
+ async applyBatch(executor, writes, documentActions, seq) {
191
+ for (const write of writes)
192
+ await this.applyTableWrite(executor, write, seq);
193
+ await this.applyDocumentActions(executor, documentActions, seq);
126
194
  }
127
195
  async mintId() {
128
196
  this.assertOpen();
@@ -607,29 +675,35 @@ export class SqliteStorage {
607
675
  async claimId(executor, id, table) {
608
676
  await executor.run(`INSERT OR IGNORE INTO ${this.schema.tables.recordIds} (id, record_type) VALUES (?, ?)`, id, table);
609
677
  }
610
- async applyDocumentActions(executor, actions, seq) {
678
+ /** Resolve each copy to a base of its source's state before this batch, which may not change the source. */
679
+ async resolveCopies(executor, actions) {
611
680
  for (const [id, action] of actions) {
612
- let content = action.content;
613
- if (action.copy !== undefined) {
614
- try {
615
- const stored = await this.materializeDocument(executor, action.copy.id, action.copy.at);
616
- if (stored === undefined)
617
- throw new Error(`Fork source document ${action.copy.id} cannot be read`);
618
- const create = action.create;
619
- if (stored.record.scope.kind !== "conversation" ||
620
- create.scope.kind !== "conversation" ||
621
- stored.record.kind !== create.kind ||
622
- stored.record.key !== create.key ||
623
- stored.record.history !== create.history ||
624
- stored.record.fork !== create.fork) {
625
- throw new Error(`Fork source document ${action.copy.id} does not match the copied record`);
626
- }
627
- content = { kind: "base", version: stored.version, value: stored.value };
628
- }
629
- catch (error) {
630
- throw new Error(`Document copy ${id} was rejected`, { cause: error });
681
+ if (action.copy === undefined)
682
+ continue;
683
+ try {
684
+ const stored = await this.materializeDocument(executor, action.copy.id, action.copy.at);
685
+ if (stored === undefined)
686
+ throw new Error(`Fork source document ${action.copy.id} cannot be read`);
687
+ const create = action.create;
688
+ if (stored.record.scope.kind !== "conversation" ||
689
+ create.scope.kind !== "conversation" ||
690
+ stored.record.kind !== create.kind ||
691
+ stored.record.key !== create.key ||
692
+ stored.record.history !== create.history ||
693
+ stored.record.fork !== create.fork) {
694
+ throw new Error(`Fork source document ${action.copy.id} does not match the copied record`);
631
695
  }
696
+ action.content = { kind: "base", version: stored.version, value: stored.value };
697
+ }
698
+ catch (error) {
699
+ throw new Error(`Document copy ${id} was rejected`, { cause: error });
632
700
  }
701
+ }
702
+ }
703
+ async applyDocumentActions(executor, actions, seq) {
704
+ for (const [id, action] of actions) {
705
+ // Copies are resolved to their content by `resolveCopies()`.
706
+ const content = action.content;
633
707
  let record;
634
708
  if (action.create !== undefined) {
635
709
  record = {