@earendil-works/pi-agent-core 0.85.1 → 0.86.1

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 (198) hide show
  1. package/README.md +16 -6
  2. package/dist/agent-loop.d.ts.map +1 -1
  3. package/dist/agent-loop.js +64 -22
  4. package/dist/agent-loop.js.map +1 -1
  5. package/dist/agent.d.ts +5 -3
  6. package/dist/agent.d.ts.map +1 -1
  7. package/dist/agent.js +15 -6
  8. package/dist/agent.js.map +1 -1
  9. package/dist/harness/config.d.ts +1 -1
  10. package/dist/harness/config.d.ts.map +1 -1
  11. package/dist/harness/config.js +10 -2
  12. package/dist/harness/config.js.map +1 -1
  13. package/dist/harness/env/nodejs.d.ts +2 -1
  14. package/dist/harness/env/nodejs.d.ts.map +1 -1
  15. package/dist/harness/env/nodejs.js +98 -27
  16. package/dist/harness/env/nodejs.js.map +1 -1
  17. package/dist/harness/execution/tools.d.ts +1 -1
  18. package/dist/harness/execution/tools.d.ts.map +1 -1
  19. package/dist/harness/execution/tools.js +0 -2
  20. package/dist/harness/execution/tools.js.map +1 -1
  21. package/dist/harness/messages.d.ts.map +1 -1
  22. package/dist/harness/messages.js +1 -0
  23. package/dist/harness/messages.js.map +1 -1
  24. package/dist/harness/pico3/bash.d.ts +10 -0
  25. package/dist/harness/pico3/bash.d.ts.map +1 -0
  26. package/dist/harness/pico3/bash.js +25 -0
  27. package/dist/harness/pico3/bash.js.map +1 -0
  28. package/dist/harness/pico3/bounded.d.ts +21 -0
  29. package/dist/harness/pico3/bounded.d.ts.map +1 -0
  30. package/dist/harness/pico3/bounded.js +98 -0
  31. package/dist/harness/pico3/bounded.js.map +1 -0
  32. package/dist/harness/pico3/chord.d.ts +41 -0
  33. package/dist/harness/pico3/chord.d.ts.map +1 -0
  34. package/dist/harness/pico3/chord.js +130 -0
  35. package/dist/harness/pico3/chord.js.map +1 -0
  36. package/dist/harness/pico3/context.d.ts +16 -0
  37. package/dist/harness/pico3/context.d.ts.map +1 -0
  38. package/dist/harness/pico3/context.js +88 -0
  39. package/dist/harness/pico3/context.js.map +1 -0
  40. package/dist/harness/pico3/harness.d.ts +197 -0
  41. package/dist/harness/pico3/harness.d.ts.map +1 -0
  42. package/dist/harness/pico3/harness.js +654 -0
  43. package/dist/harness/pico3/harness.js.map +1 -0
  44. package/dist/harness/pico3/hooks.d.ts +10 -0
  45. package/dist/harness/pico3/hooks.d.ts.map +1 -0
  46. package/dist/harness/pico3/hooks.js +33 -0
  47. package/dist/harness/pico3/hooks.js.map +1 -0
  48. package/dist/harness/pico3/index.d.ts +19 -0
  49. package/dist/harness/pico3/index.d.ts.map +1 -0
  50. package/dist/harness/pico3/index.js +15 -0
  51. package/dist/harness/pico3/index.js.map +1 -0
  52. package/dist/harness/pico3/jsonl.d.ts +58 -0
  53. package/dist/harness/pico3/jsonl.d.ts.map +1 -0
  54. package/dist/harness/pico3/jsonl.js +325 -0
  55. package/dist/harness/pico3/jsonl.js.map +1 -0
  56. package/dist/harness/pico3/kinds/collapse.d.ts +49 -0
  57. package/dist/harness/pico3/kinds/collapse.d.ts.map +1 -0
  58. package/dist/harness/pico3/kinds/collapse.js +191 -0
  59. package/dist/harness/pico3/kinds/collapse.js.map +1 -0
  60. package/dist/harness/pico3/kinds/entries.d.ts +78 -0
  61. package/dist/harness/pico3/kinds/entries.d.ts.map +1 -0
  62. package/dist/harness/pico3/kinds/entries.js +13 -0
  63. package/dist/harness/pico3/kinds/entries.js.map +1 -0
  64. package/dist/harness/pico3/kinds/frames.d.ts +9 -0
  65. package/dist/harness/pico3/kinds/frames.d.ts.map +1 -0
  66. package/dist/harness/pico3/kinds/frames.js +75 -0
  67. package/dist/harness/pico3/kinds/frames.js.map +1 -0
  68. package/dist/harness/pico3/kinds/generation.d.ts +94 -0
  69. package/dist/harness/pico3/kinds/generation.d.ts.map +1 -0
  70. package/dist/harness/pico3/kinds/generation.js +504 -0
  71. package/dist/harness/pico3/kinds/generation.js.map +1 -0
  72. package/dist/harness/pico3/kinds/job.d.ts +44 -0
  73. package/dist/harness/pico3/kinds/job.d.ts.map +1 -0
  74. package/dist/harness/pico3/kinds/job.js +143 -0
  75. package/dist/harness/pico3/kinds/job.js.map +1 -0
  76. package/dist/harness/pico3/kinds/plugin.d.ts +15 -0
  77. package/dist/harness/pico3/kinds/plugin.d.ts.map +1 -0
  78. package/dist/harness/pico3/kinds/plugin.js +35 -0
  79. package/dist/harness/pico3/kinds/plugin.js.map +1 -0
  80. package/dist/harness/pico3/kinds/post-tools.d.ts +22 -0
  81. package/dist/harness/pico3/kinds/post-tools.d.ts.map +1 -0
  82. package/dist/harness/pico3/kinds/post-tools.js +145 -0
  83. package/dist/harness/pico3/kinds/post-tools.js.map +1 -0
  84. package/dist/harness/pico3/kinds/task-api.d.ts +3 -0
  85. package/dist/harness/pico3/kinds/task-api.d.ts.map +1 -0
  86. package/dist/harness/pico3/kinds/task-api.js +45 -0
  87. package/dist/harness/pico3/kinds/task-api.js.map +1 -0
  88. package/dist/harness/pico3/kinds/tool.d.ts +43 -0
  89. package/dist/harness/pico3/kinds/tool.d.ts.map +1 -0
  90. package/dist/harness/pico3/kinds/tool.js +373 -0
  91. package/dist/harness/pico3/kinds/tool.js.map +1 -0
  92. package/dist/harness/pico3/membrane.d.ts +23 -0
  93. package/dist/harness/pico3/membrane.d.ts.map +1 -0
  94. package/dist/harness/pico3/membrane.js +141 -0
  95. package/dist/harness/pico3/membrane.js.map +1 -0
  96. package/dist/harness/pico3/memory.d.ts +53 -0
  97. package/dist/harness/pico3/memory.d.ts.map +1 -0
  98. package/dist/harness/pico3/memory.js +264 -0
  99. package/dist/harness/pico3/memory.js.map +1 -0
  100. package/dist/harness/pico3/scheduler.d.ts +46 -0
  101. package/dist/harness/pico3/scheduler.d.ts.map +1 -0
  102. package/dist/harness/pico3/scheduler.js +438 -0
  103. package/dist/harness/pico3/scheduler.js.map +1 -0
  104. package/dist/harness/pico3/session.d.ts +263 -0
  105. package/dist/harness/pico3/session.d.ts.map +1 -0
  106. package/dist/harness/pico3/session.js +1347 -0
  107. package/dist/harness/pico3/session.js.map +1 -0
  108. package/dist/harness/pico3/system.d.ts +126 -0
  109. package/dist/harness/pico3/system.d.ts.map +1 -0
  110. package/dist/harness/pico3/system.js +244 -0
  111. package/dist/harness/pico3/system.js.map +1 -0
  112. package/dist/harness/pico3/types.d.ts +973 -0
  113. package/dist/harness/pico3/types.d.ts.map +1 -0
  114. package/dist/harness/pico3/types.js +96 -0
  115. package/dist/harness/pico3/types.js.map +1 -0
  116. package/dist/harness/pico3/view.d.ts +34 -0
  117. package/dist/harness/pico3/view.d.ts.map +1 -0
  118. package/dist/harness/pico3/view.js +417 -0
  119. package/dist/harness/pico3/view.js.map +1 -0
  120. package/dist/harness/runtime/drive/boundary.d.ts.map +1 -1
  121. package/dist/harness/runtime/drive/boundary.js +6 -3
  122. package/dist/harness/runtime/drive/boundary.js.map +1 -1
  123. package/dist/harness/runtime/drive/response.d.ts.map +1 -1
  124. package/dist/harness/runtime/drive/response.js +4 -4
  125. package/dist/harness/runtime/drive/response.js.map +1 -1
  126. package/dist/harness/runtime/drive/retry.d.ts +2 -2
  127. package/dist/harness/runtime/drive/retry.d.ts.map +1 -1
  128. package/dist/harness/runtime/drive/retry.js +3 -6
  129. package/dist/harness/runtime/drive/retry.js.map +1 -1
  130. package/dist/harness/runtime/drive/structural.d.ts.map +1 -1
  131. package/dist/harness/runtime/drive/structural.js +5 -5
  132. package/dist/harness/runtime/drive/structural.js.map +1 -1
  133. package/dist/harness/runtime/drive/tool-placement.d.ts.map +1 -1
  134. package/dist/harness/runtime/drive/tool-placement.js +2 -27
  135. package/dist/harness/runtime/drive/tool-placement.js.map +1 -1
  136. package/dist/harness/runtime/drive/tools.d.ts.map +1 -1
  137. package/dist/harness/runtime/drive/tools.js.map +1 -1
  138. package/dist/harness/session/fork-policy.d.ts +20 -12
  139. package/dist/harness/session/fork-policy.d.ts.map +1 -1
  140. package/dist/harness/session/fork-policy.js +45 -12
  141. package/dist/harness/session/fork-policy.js.map +1 -1
  142. package/dist/harness/session/fork.d.ts +0 -2
  143. package/dist/harness/session/fork.d.ts.map +1 -1
  144. package/dist/harness/session/fork.js +20 -68
  145. package/dist/harness/session/fork.js.map +1 -1
  146. package/dist/harness/session/in-memory-storage-state.d.ts +5 -5
  147. package/dist/harness/session/in-memory-storage-state.d.ts.map +1 -1
  148. package/dist/harness/session/in-memory-storage-state.js +99 -39
  149. package/dist/harness/session/in-memory-storage-state.js.map +1 -1
  150. package/dist/harness/session/index.d.ts +1 -1
  151. package/dist/harness/session/index.d.ts.map +1 -1
  152. package/dist/harness/session/index.js +1 -1
  153. package/dist/harness/session/index.js.map +1 -1
  154. package/dist/harness/session/jsonl/fork.d.ts +38 -0
  155. package/dist/harness/session/jsonl/fork.d.ts.map +1 -0
  156. package/dist/harness/session/jsonl/fork.js +264 -0
  157. package/dist/harness/session/jsonl/fork.js.map +1 -0
  158. package/dist/harness/session/jsonl/io.d.ts +14 -0
  159. package/dist/harness/session/jsonl/io.d.ts.map +1 -0
  160. package/dist/harness/session/jsonl/io.js +86 -0
  161. package/dist/harness/session/jsonl/io.js.map +1 -0
  162. package/dist/harness/session/jsonl/legacy-v3.d.ts +33 -8
  163. package/dist/harness/session/jsonl/legacy-v3.d.ts.map +1 -1
  164. package/dist/harness/session/jsonl/legacy-v3.js +285 -206
  165. package/dist/harness/session/jsonl/legacy-v3.js.map +1 -1
  166. package/dist/harness/session/jsonl/repo.d.ts +2 -1
  167. package/dist/harness/session/jsonl/repo.d.ts.map +1 -1
  168. package/dist/harness/session/jsonl/repo.js +36 -20
  169. package/dist/harness/session/jsonl/repo.js.map +1 -1
  170. package/dist/harness/session/jsonl/storage.d.ts +4 -5
  171. package/dist/harness/session/jsonl/storage.d.ts.map +1 -1
  172. package/dist/harness/session/jsonl/storage.js +39 -113
  173. package/dist/harness/session/jsonl/storage.js.map +1 -1
  174. package/dist/harness/session/memory.d.ts +3 -5
  175. package/dist/harness/session/memory.d.ts.map +1 -1
  176. package/dist/harness/session/memory.js +9 -14
  177. package/dist/harness/session/memory.js.map +1 -1
  178. package/dist/harness/session/testing/conformance/session-repo.d.ts +2 -0
  179. package/dist/harness/session/testing/conformance/session-repo.d.ts.map +1 -1
  180. package/dist/harness/session/testing/conformance/session-repo.js +220 -1
  181. package/dist/harness/session/testing/conformance/session-repo.js.map +1 -1
  182. package/dist/harness/session/testing/index.d.ts +1 -1
  183. package/dist/harness/session/testing/index.d.ts.map +1 -1
  184. package/dist/harness/session/testing/index.js +1 -1
  185. package/dist/harness/session/testing/index.js.map +1 -1
  186. package/dist/harness/session/types.d.ts +1 -0
  187. package/dist/harness/session/types.d.ts.map +1 -1
  188. package/dist/harness/session/types.js.map +1 -1
  189. package/dist/harness/types.d.ts +14 -0
  190. package/dist/harness/types.d.ts.map +1 -1
  191. package/dist/harness/types.js.map +1 -1
  192. package/dist/proxy.d.ts +2 -2
  193. package/dist/proxy.d.ts.map +1 -1
  194. package/dist/proxy.js.map +1 -1
  195. package/dist/types.d.ts +30 -14
  196. package/dist/types.d.ts.map +1 -1
  197. package/dist/types.js.map +1 -1
  198. package/package.json +10 -6
@@ -1 +1 @@
1
- {"version":3,"file":"fork-policy.js","sourceRoot":"","sources":["../../../src/harness/session/fork-policy.ts"],"names":[],"mappings":"AAQA,2EAA2E;AAC3E,MAAM,UAAU,mBAAmB,CAClC,OAA6D,EAC7D,KAAwB,EACxB,aAA2C,EACzB;IAClB,QAAQ,OAAO,CAAC,SAAS,EAAE,CAAC;QAC3B,KAAK,iBAAiB;YACrB,OAAO,MAAM,CAAC;QACf,KAAK,gBAAgB;YACpB,OAAO,aAAa,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;QACxD,KAAK,eAAe,CAAC;QACrB,KAAK,gBAAgB,CAAC;QACtB,KAAK,eAAe;YACnB,OAAO,aAAa,CAAC;QACtB,KAAK,WAAW;YACf,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,IAAI,OAAO,CAAC,SAAS,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,OAAO,CAAC,SAAS,CAAC,UAAU,CAAC,aAAa,CAAC;QAAE,OAAO,SAAS,CAAC;IAC5G,IAAI,OAAO,CAAC,SAAS,KAAK,IAAI,IAAI,OAAO,CAAC,SAAS,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;QACvE,MAAM,IAAI,KAAK,CAAC,oCAAoC,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;IAC1E,CAAC;IACD,OAAO,KAAK,KAAK,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;AAAA,CAC7C","sourcesContent":["/**\n * Final action for current state at one address:\n * - copy: emit the current value in the destination;\n * - exclude: omit it from the destination;\n * - reconstruct: do not copy the row because lane handling emits a coherent replacement.\n */\nexport type ForkDisposition = \"copy\" | \"exclude\" | \"reconstruct\";\n\n/** Decide the final fork action for one current scalar or list address. */\nexport function classifyForkAddress(\n\taddress: { readonly namespace: string; readonly key: string },\n\tscope: \"branch\" | \"tree\",\n\tisEntryCopied: (entryId: string) => boolean,\n): ForkDisposition {\n\tswitch (address.namespace) {\n\t\tcase \"pi.session.name\":\n\t\t\treturn \"copy\";\n\t\tcase \"pi.entry.label\":\n\t\t\treturn isEntryCopied(address.key) ? \"copy\" : \"exclude\";\n\t\tcase \"pi.branch.tip\":\n\t\tcase \"pi.lane.config\":\n\t\tcase \"pi.lane.state\":\n\t\t\treturn \"reconstruct\";\n\t\tcase \"pi.result\":\n\t\t\treturn \"exclude\";\n\t}\n\tif (address.namespace.startsWith(\"pi.op.\") || address.namespace.startsWith(\"pi.pending.\")) return \"exclude\";\n\tif (address.namespace === \"pi\" || address.namespace.startsWith(\"pi.\")) {\n\t\tthrow new Error(`Unknown reserved fork namespace: ${address.namespace}`);\n\t}\n\treturn scope === \"tree\" ? \"copy\" : \"exclude\";\n}\n"]}
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AI,KAAK,CAAC,SAAS,CAAC,UAAU,CAAC,aAAa,CAAC;QAAE,OAAO,SAAS,CAAC;IACxG,IAAI,KAAK,CAAC,SAAS,KAAK,IAAI,IAAI,KAAK,CAAC,SAAS,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;QACnE,MAAM,IAAI,KAAK,CAAC,oCAAoC,KAAK,CAAC,SAAS,EAAE,CAAC,CAAC;IACxE,CAAC;IACD,OAAO,IAAI,CAAC,KAAK,KAAK,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAAA,CACjD","sourcesContent":["import type { CommittedListAppendWrite, CommittedValueSetWrite } from \"./commit.ts\";\nimport type { ForkOptions } from \"./types.ts\";\n\nexport type ForkCurrentStatePlan =\n\t| { scope: \"branch\"; branch: string; destinationTip: string | null }\n\t| { scope: \"tree\" };\n\nexport function selectBranchFork(\n\toptions: Extract<ForkOptions, { scope: \"branch\" }>,\n\tsource: {\n\t\ttip: string | null | undefined;\n\t\tgetParent: (entryId: string) => string | null | undefined;\n\t\tselectEntry: (entryId: string) => void;\n\t},\n): Extract<ForkCurrentStatePlan, { scope: \"branch\" }> {\n\tif (source.tip === undefined) throw new Error(`Unknown source branch: ${options.branch}`);\n\tconst requested = options.entryId ?? source.tip;\n\tlet found = requested === null;\n\tlet destinationTip: string | null = null;\n\tlet entryId = source.tip;\n\twhile (entryId !== null) {\n\t\tconst parentId = source.getParent(entryId);\n\t\tif (parentId === undefined) throw new Error(`Corrupt source branch: missing parent ${entryId}`);\n\t\tif (entryId === requested) {\n\t\t\tfound = true;\n\t\t\tdestinationTip = options.position === \"before\" ? parentId : entryId;\n\t\t\tif (options.position !== \"before\") source.selectEntry(entryId);\n\t\t} else if (found) {\n\t\t\tsource.selectEntry(entryId);\n\t\t}\n\t\tentryId = parentId;\n\t}\n\tif (!found) {\n\t\tthrow new Error(`Fork entry ${requested} is not on source branch ${JSON.stringify(options.branch)}`);\n\t}\n\treturn { scope: \"branch\", branch: options.branch, destinationTip };\n}\n\n/** Project one current scalar row or surviving list element into destination state. */\nexport function projectForkCurrentStateWrite(\n\twrite: CommittedValueSetWrite | CommittedListAppendWrite,\n\tplan: ForkCurrentStatePlan,\n\tisEntryCopied: (entryId: string) => boolean,\n): CommittedValueSetWrite | CommittedListAppendWrite | undefined {\n\tswitch (write.namespace) {\n\t\tcase \"pi.session.name\":\n\t\t\treturn write;\n\t\tcase \"pi.entry.label\":\n\t\t\treturn isEntryCopied(write.key) ? write : undefined;\n\t\tcase \"pi.branch.tip\":\n\t\t\tif (plan.scope === \"tree\") return write;\n\t\t\treturn write.key === plan.branch ? { ...write, value: plan.destinationTip } : undefined;\n\t\tcase \"pi.lane.config\":\n\t\t\treturn plan.scope === \"tree\" || write.key === plan.branch ? write : undefined;\n\t\tcase \"pi.lane.state\":\n\t\t\treturn plan.scope === \"tree\" || write.key === plan.branch\n\t\t\t\t? { ...write, value: { currentOperationId: null, lastOperationId: null, inbox: [] } }\n\t\t\t\t: undefined;\n\t\tcase \"pi.result\":\n\t\t\treturn undefined;\n\t}\n\tif (write.namespace.startsWith(\"pi.op.\") || write.namespace.startsWith(\"pi.pending.\")) return undefined;\n\tif (write.namespace === \"pi\" || write.namespace.startsWith(\"pi.\")) {\n\t\tthrow new Error(`Unknown reserved fork namespace: ${write.namespace}`);\n\t}\n\treturn plan.scope === \"tree\" ? write : undefined;\n}\n"]}
@@ -1,4 +1,3 @@
1
- import type { CommittedWrite } from "./commit.ts";
2
1
  import type { Entry, ForkOptions } from "./types.ts";
3
2
  import { type StoredValue } from "./values.ts";
4
3
  export interface ForkSourceSnapshot {
@@ -14,5 +13,4 @@ export interface ForkDestinationSnapshot {
14
13
  }
15
14
  /** Build the complete logical state for a forked destination session. */
16
15
  export declare function createForkSnapshot(source: ForkSourceSnapshot, options: ForkOptions): ForkDestinationSnapshot;
17
- export declare function forkSnapshotWrites(snapshot: ForkDestinationSnapshot): CommittedWrite[];
18
16
  //# sourceMappingURL=fork.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"fork.d.ts","sourceRoot":"","sources":["../../../src/harness/session/fork.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAElD,OAAO,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,EAAoC,KAAK,WAAW,EAAqB,MAAM,aAAa,CAAC;AAEpG,MAAM,WAAW,kBAAkB;IAClC,OAAO,EAAE,KAAK,EAAE,CAAC;IACjB,YAAY,EAAE,WAAW,CAAC,OAAO,CAAC,EAAE,CAAC;IACrC,yFAAyF;IACzF,eAAe,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,uBAAuB;IACvC,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAC5B,YAAY,EAAE,WAAW,CAAC,OAAO,CAAC,EAAE,CAAC;IACrC,OAAO,EAAE,MAAM,CAAC;CAChB;AAYD,yEAAyE;AACzE,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,kBAAkB,EAAE,OAAO,EAAE,WAAW,GAAG,uBAAuB,CAsC5G;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,uBAAuB,GAAG,cAAc,EAAE,CActF","sourcesContent":["import type { CommittedWrite } from \"./commit.ts\";\nimport { classifyForkAddress } from \"./fork-policy.ts\";\nimport type { Entry, ForkOptions } from \"./types.ts\";\nimport { branchTip, laneConfig, laneState, type StoredValue, type Value, value } from \"./values.ts\";\n\nexport interface ForkSourceSnapshot {\n\tentries: Entry[];\n\tscalarValues: StoredValue<unknown>[];\n\t/** False when a backend supplied only the requested branch rather than the full tree. */\n\tentriesComplete?: boolean;\n}\n\nexport interface ForkDestinationSnapshot {\n\tentries: Map<string, Entry>;\n\tscalarValues: StoredValue<unknown>[];\n\tnextSeq: number;\n}\n\nfunction storedValuesInNamespace<T>(values: readonly StoredValue<unknown>[], address: Value<T>): StoredValue<T>[] {\n\treturn values.filter((stored) => stored.address.namespace === address.namespace) as StoredValue<T>[];\n}\n\nfunction findStoredValue<T>(values: readonly StoredValue<unknown>[], address: Value<T>): StoredValue<T> | undefined {\n\treturn values.find(\n\t\t(stored) => stored.address.namespace === address.namespace && stored.address.key === address.key,\n\t) as StoredValue<T> | undefined;\n}\n\n/** Build the complete logical state for a forked destination session. */\nexport function createForkSnapshot(source: ForkSourceSnapshot, options: ForkOptions): ForkDestinationSnapshot {\n\tconst sourceEntries = new Map(source.entries.map((entry) => [entry.id, entry]));\n\tconst sourceTips = storedValuesInNamespace(source.scalarValues, branchTip(\"\"));\n\tvalidateForkSourceSnapshot(source, sourceEntries, sourceTips, options);\n\n\tconst { entryIds, destinationTips } = selectForkContents(sourceEntries, sourceTips, options);\n\tconst entries = new Map<string, Entry>();\n\tfor (const id of entryIds) entries.set(id, sourceEntries.get(id)!);\n\n\tconst scalarValues: StoredValue<unknown>[] = [];\n\tlet nextSeq = Math.max(0, ...[...entries.values()].map((entry) => entry.seq)) + 1;\n\tconst store = <T>(address: Value<T>, storedValue: T): void => {\n\t\tscalarValues.push({\n\t\t\taddress: value<unknown>(address.namespace, address.key),\n\t\t\tvalue: storedValue,\n\t\t\tseq: nextSeq++,\n\t\t});\n\t};\n\tfor (const [branch, tipId] of destinationTips) {\n\t\tconst configuration = findStoredValue(source.scalarValues, laneConfig(branch));\n\t\tstore(branchTip(branch), tipId);\n\t\tif (configuration !== undefined) {\n\t\t\tstore(laneConfig(branch), configuration.value);\n\t\t\tstore(laneState(branch), { currentOperationId: null, lastOperationId: null, inbox: [] });\n\t\t}\n\t}\n\tfor (const stored of source.scalarValues) {\n\t\tswitch (classifyForkAddress(stored.address, options.scope, (entryId) => entryIds.has(entryId))) {\n\t\t\tcase \"copy\":\n\t\t\t\tstore(stored.address, stored.value);\n\t\t\t\tbreak;\n\t\t\tcase \"exclude\":\n\t\t\tcase \"reconstruct\":\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn { entries, scalarValues, nextSeq };\n}\n\nexport function forkSnapshotWrites(snapshot: ForkDestinationSnapshot): CommittedWrite[] {\n\tconst writes: CommittedWrite[] = [];\n\tfor (const entry of snapshot.entries.values()) writes.push({ kind: \"entry\", ...entry });\n\tfor (const stored of snapshot.scalarValues) {\n\t\twrites.push({\n\t\t\tkind: \"value\",\n\t\t\top: \"set\",\n\t\t\tseq: stored.seq,\n\t\t\tnamespace: stored.address.namespace,\n\t\t\tkey: stored.address.key,\n\t\t\tvalue: stored.value,\n\t\t});\n\t}\n\treturn writes.sort((left, right) => left.seq - right.seq);\n}\n\nfunction selectForkContents(\n\tsourceEntries: Map<string, Entry>,\n\tsourceTips: StoredValue<string | null>[],\n\toptions: ForkOptions,\n): {\n\tentryIds: Set<string>;\n\tdestinationTips: Map<string, string | null>;\n} {\n\tconst entryIds = new Set<string>();\n\tconst destinationTips = new Map<string, string | null>();\n\tif (options.scope === \"tree\") {\n\t\tfor (const id of sourceEntries.keys()) entryIds.add(id);\n\t\tfor (const stored of sourceTips) destinationTips.set(stored.address.key, stored.value);\n\t} else {\n\t\tconst sourceTip = sourceTips.find((stored) => stored.address.key === options.branch);\n\t\tif (sourceTip === undefined) throw new Error(`Unknown source branch: ${options.branch}`);\n\n\t\tconst requested = options.entryId ?? sourceTip.value;\n\t\tlet found = requested === null;\n\t\tlet tipId: string | null = null;\n\t\tlet entryId = sourceTip.value;\n\t\twhile (entryId !== null) {\n\t\t\tconst entry = sourceEntries.get(entryId);\n\t\t\tif (entry === undefined) throw new Error(`Corrupt source branch: missing parent ${entryId}`);\n\t\t\tif (entry.id === requested) {\n\t\t\t\tfound = true;\n\t\t\t\ttipId = options.position === \"before\" ? entry.parentId : entry.id;\n\t\t\t\tif (options.position !== \"before\") entryIds.add(entry.id);\n\t\t\t} else if (found) {\n\t\t\t\tentryIds.add(entry.id);\n\t\t\t}\n\t\t\tentryId = entry.parentId;\n\t\t}\n\t\tif (!found) {\n\t\t\tthrow new Error(`Fork entry ${requested} is not on source branch ${JSON.stringify(options.branch)}`);\n\t\t}\n\t\tdestinationTips.set(options.branch, tipId);\n\t}\n\treturn { entryIds, destinationTips };\n}\n\nfunction validateForkSourceSnapshot(\n\tsource: ForkSourceSnapshot,\n\tsourceEntries: Map<string, Entry>,\n\tsourceTips: StoredValue<string | null>[],\n\toptions: ForkOptions,\n): void {\n\tconst sourceTipKeys = new Set(sourceTips.map((stored) => stored.address.key));\n\n\tfor (const stored of source.scalarValues) {\n\t\tif (\n\t\t\t(stored.address.namespace === laneConfig(\"\").namespace ||\n\t\t\t\tstored.address.namespace === laneState(\"\").namespace) &&\n\t\t\t!sourceTipKeys.has(stored.address.key)\n\t\t) {\n\t\t\tthrow new Error(`Source session branch ${JSON.stringify(stored.address.key)} is missing branch.tip`);\n\t\t}\n\t}\n\tfor (const tip of sourceTips) {\n\t\tconst configuration = findStoredValue(source.scalarValues, laneConfig(tip.address.key));\n\t\tconst state = findStoredValue(source.scalarValues, laneState(tip.address.key));\n\t\tif ((configuration === undefined) !== (state === undefined)) {\n\t\t\tthrow new Error(`Source session branch ${JSON.stringify(tip.address.key)} has incomplete lane state`);\n\t\t}\n\t\tif (options.scope === \"branch\" && tip.address.key === options.branch && configuration === undefined) {\n\t\t\tthrow new Error(`Source branch ${JSON.stringify(options.branch)} is not a configured AgentLane`);\n\t\t}\n\t\tif (\n\t\t\t(source.entriesComplete !== false || options.scope === \"tree\") &&\n\t\t\ttip.value !== null &&\n\t\t\t!sourceEntries.has(tip.value)\n\t\t) {\n\t\t\tthrow new Error(`Source session branch ${JSON.stringify(tip.address.key)} has an unknown tip`);\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"fork.d.ts","sourceRoot":"","sources":["../../../src/harness/session/fork.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,EAAoC,KAAK,WAAW,EAAqB,MAAM,aAAa,CAAC;AAEpG,MAAM,WAAW,kBAAkB;IAClC,OAAO,EAAE,KAAK,EAAE,CAAC;IACjB,YAAY,EAAE,WAAW,CAAC,OAAO,CAAC,EAAE,CAAC;IACrC,yFAAyF;IACzF,eAAe,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,uBAAuB;IACvC,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAC5B,YAAY,EAAE,WAAW,CAAC,OAAO,CAAC,EAAE,CAAC;IACrC,OAAO,EAAE,MAAM,CAAC;CAChB;AAYD,yEAAyE;AACzE,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,kBAAkB,EAAE,OAAO,EAAE,WAAW,GAAG,uBAAuB,CAkC5G","sourcesContent":["import { type ForkCurrentStatePlan, projectForkCurrentStateWrite, selectBranchFork } from \"./fork-policy.ts\";\nimport type { Entry, ForkOptions } from \"./types.ts\";\nimport { branchTip, laneConfig, laneState, type StoredValue, type Value, value } from \"./values.ts\";\n\nexport interface ForkSourceSnapshot {\n\tentries: Entry[];\n\tscalarValues: StoredValue<unknown>[];\n\t/** False when a backend supplied only the requested branch rather than the full tree. */\n\tentriesComplete?: boolean;\n}\n\nexport interface ForkDestinationSnapshot {\n\tentries: Map<string, Entry>;\n\tscalarValues: StoredValue<unknown>[];\n\tnextSeq: number;\n}\n\nfunction storedValuesInNamespace<T>(values: readonly StoredValue<unknown>[], address: Value<T>): StoredValue<T>[] {\n\treturn values.filter((stored) => stored.address.namespace === address.namespace) as StoredValue<T>[];\n}\n\nfunction findStoredValue<T>(values: readonly StoredValue<unknown>[], address: Value<T>): StoredValue<T> | undefined {\n\treturn values.find(\n\t\t(stored) => stored.address.namespace === address.namespace && stored.address.key === address.key,\n\t) as StoredValue<T> | undefined;\n}\n\n/** Build the complete logical state for a forked destination session. */\nexport function createForkSnapshot(source: ForkSourceSnapshot, options: ForkOptions): ForkDestinationSnapshot {\n\tconst sourceEntries = new Map(source.entries.map((entry) => [entry.id, entry]));\n\tconst sourceTips = storedValuesInNamespace(source.scalarValues, branchTip(\"\"));\n\tvalidateForkSourceSnapshot(source, sourceEntries, sourceTips, options);\n\n\tconst { entryIds, plan } = selectForkContents(sourceEntries, sourceTips, options);\n\tconst entries = new Map<string, Entry>();\n\tfor (const id of entryIds) entries.set(id, sourceEntries.get(id)!);\n\n\tconst scalarValues: StoredValue<unknown>[] = [];\n\tlet nextSeq = Math.max(0, ...[...entries.values()].map((entry) => entry.seq)) + 1;\n\tfor (const stored of source.scalarValues) {\n\t\tconst projected = projectForkCurrentStateWrite(\n\t\t\t{\n\t\t\t\tkind: \"value\",\n\t\t\t\top: \"set\",\n\t\t\t\tseq: stored.seq,\n\t\t\t\tnamespace: stored.address.namespace,\n\t\t\t\tkey: stored.address.key,\n\t\t\t\tvalue: stored.value,\n\t\t\t},\n\t\t\tplan,\n\t\t\t(entryId) => entryIds.has(entryId),\n\t\t);\n\t\tif (projected !== undefined) {\n\t\t\tscalarValues.push({\n\t\t\t\taddress: value<unknown>(projected.namespace, projected.key),\n\t\t\t\tvalue: projected.value,\n\t\t\t\tseq: nextSeq++,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn { entries, scalarValues, nextSeq };\n}\n\nfunction selectForkContents(\n\tsourceEntries: Map<string, Entry>,\n\tsourceTips: StoredValue<string | null>[],\n\toptions: ForkOptions,\n): { entryIds: Set<string>; plan: ForkCurrentStatePlan } {\n\tconst entryIds = new Set<string>();\n\tif (options.scope === \"tree\") {\n\t\tfor (const id of sourceEntries.keys()) entryIds.add(id);\n\t\treturn { entryIds, plan: { scope: \"tree\" } };\n\t}\n\n\tconst sourceTip = sourceTips.find((stored) => stored.address.key === options.branch);\n\tconst plan = selectBranchFork(options, {\n\t\ttip: sourceTip?.value,\n\t\tgetParent: (entryId) => sourceEntries.get(entryId)?.parentId,\n\t\tselectEntry: (entryId) => entryIds.add(entryId),\n\t});\n\treturn { entryIds, plan };\n}\n\nfunction validateForkSourceSnapshot(\n\tsource: ForkSourceSnapshot,\n\tsourceEntries: Map<string, Entry>,\n\tsourceTips: StoredValue<string | null>[],\n\toptions: ForkOptions,\n): void {\n\tconst sourceTipKeys = new Set(sourceTips.map((stored) => stored.address.key));\n\n\tfor (const stored of source.scalarValues) {\n\t\tif (\n\t\t\t(stored.address.namespace === laneConfig(\"\").namespace ||\n\t\t\t\tstored.address.namespace === laneState(\"\").namespace) &&\n\t\t\t!sourceTipKeys.has(stored.address.key)\n\t\t) {\n\t\t\tthrow new Error(`Source session branch ${JSON.stringify(stored.address.key)} is missing branch.tip`);\n\t\t}\n\t}\n\tfor (const tip of sourceTips) {\n\t\tconst configuration = findStoredValue(source.scalarValues, laneConfig(tip.address.key));\n\t\tconst state = findStoredValue(source.scalarValues, laneState(tip.address.key));\n\t\tif ((configuration === undefined) !== (state === undefined)) {\n\t\t\tthrow new Error(`Source session branch ${JSON.stringify(tip.address.key)} has incomplete lane state`);\n\t\t}\n\t\tif (options.scope === \"branch\" && tip.address.key === options.branch && configuration === undefined) {\n\t\t\tthrow new Error(`Source branch ${JSON.stringify(options.branch)} is not a configured AgentLane`);\n\t\t}\n\t\tif (\n\t\t\t(source.entriesComplete !== false || options.scope === \"tree\") &&\n\t\t\ttip.value !== null &&\n\t\t\t!sourceEntries.has(tip.value)\n\t\t) {\n\t\t\tthrow new Error(`Source session branch ${JSON.stringify(tip.address.key)} has an unknown tip`);\n\t\t}\n\t}\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { classifyForkAddress } from "./fork-policy.js";
1
+ import { projectForkCurrentStateWrite, selectBranchFork } from "./fork-policy.js";
2
2
  import { branchTip, laneConfig, laneState, value } from "./values.js";
3
3
  function storedValuesInNamespace(values, address) {
4
4
  return values.filter((stored) => stored.address.namespace === address.namespace);
@@ -11,93 +11,45 @@ export function createForkSnapshot(source, options) {
11
11
  const sourceEntries = new Map(source.entries.map((entry) => [entry.id, entry]));
12
12
  const sourceTips = storedValuesInNamespace(source.scalarValues, branchTip(""));
13
13
  validateForkSourceSnapshot(source, sourceEntries, sourceTips, options);
14
- const { entryIds, destinationTips } = selectForkContents(sourceEntries, sourceTips, options);
14
+ const { entryIds, plan } = selectForkContents(sourceEntries, sourceTips, options);
15
15
  const entries = new Map();
16
16
  for (const id of entryIds)
17
17
  entries.set(id, sourceEntries.get(id));
18
18
  const scalarValues = [];
19
19
  let nextSeq = Math.max(0, ...[...entries.values()].map((entry) => entry.seq)) + 1;
20
- const store = (address, storedValue) => {
21
- scalarValues.push({
22
- address: value(address.namespace, address.key),
23
- value: storedValue,
24
- seq: nextSeq++,
25
- });
26
- };
27
- for (const [branch, tipId] of destinationTips) {
28
- const configuration = findStoredValue(source.scalarValues, laneConfig(branch));
29
- store(branchTip(branch), tipId);
30
- if (configuration !== undefined) {
31
- store(laneConfig(branch), configuration.value);
32
- store(laneState(branch), { currentOperationId: null, lastOperationId: null, inbox: [] });
33
- }
34
- }
35
20
  for (const stored of source.scalarValues) {
36
- switch (classifyForkAddress(stored.address, options.scope, (entryId) => entryIds.has(entryId))) {
37
- case "copy":
38
- store(stored.address, stored.value);
39
- break;
40
- case "exclude":
41
- case "reconstruct":
42
- break;
43
- }
44
- }
45
- return { entries, scalarValues, nextSeq };
46
- }
47
- export function forkSnapshotWrites(snapshot) {
48
- const writes = [];
49
- for (const entry of snapshot.entries.values())
50
- writes.push({ kind: "entry", ...entry });
51
- for (const stored of snapshot.scalarValues) {
52
- writes.push({
21
+ const projected = projectForkCurrentStateWrite({
53
22
  kind: "value",
54
23
  op: "set",
55
24
  seq: stored.seq,
56
25
  namespace: stored.address.namespace,
57
26
  key: stored.address.key,
58
27
  value: stored.value,
59
- });
28
+ }, plan, (entryId) => entryIds.has(entryId));
29
+ if (projected !== undefined) {
30
+ scalarValues.push({
31
+ address: value(projected.namespace, projected.key),
32
+ value: projected.value,
33
+ seq: nextSeq++,
34
+ });
35
+ }
60
36
  }
61
- return writes.sort((left, right) => left.seq - right.seq);
37
+ return { entries, scalarValues, nextSeq };
62
38
  }
63
39
  function selectForkContents(sourceEntries, sourceTips, options) {
64
40
  const entryIds = new Set();
65
- const destinationTips = new Map();
66
41
  if (options.scope === "tree") {
67
42
  for (const id of sourceEntries.keys())
68
43
  entryIds.add(id);
69
- for (const stored of sourceTips)
70
- destinationTips.set(stored.address.key, stored.value);
71
- }
72
- else {
73
- const sourceTip = sourceTips.find((stored) => stored.address.key === options.branch);
74
- if (sourceTip === undefined)
75
- throw new Error(`Unknown source branch: ${options.branch}`);
76
- const requested = options.entryId ?? sourceTip.value;
77
- let found = requested === null;
78
- let tipId = null;
79
- let entryId = sourceTip.value;
80
- while (entryId !== null) {
81
- const entry = sourceEntries.get(entryId);
82
- if (entry === undefined)
83
- throw new Error(`Corrupt source branch: missing parent ${entryId}`);
84
- if (entry.id === requested) {
85
- found = true;
86
- tipId = options.position === "before" ? entry.parentId : entry.id;
87
- if (options.position !== "before")
88
- entryIds.add(entry.id);
89
- }
90
- else if (found) {
91
- entryIds.add(entry.id);
92
- }
93
- entryId = entry.parentId;
94
- }
95
- if (!found) {
96
- throw new Error(`Fork entry ${requested} is not on source branch ${JSON.stringify(options.branch)}`);
97
- }
98
- destinationTips.set(options.branch, tipId);
44
+ return { entryIds, plan: { scope: "tree" } };
99
45
  }
100
- return { entryIds, destinationTips };
46
+ const sourceTip = sourceTips.find((stored) => stored.address.key === options.branch);
47
+ const plan = selectBranchFork(options, {
48
+ tip: sourceTip?.value,
49
+ getParent: (entryId) => sourceEntries.get(entryId)?.parentId,
50
+ selectEntry: (entryId) => entryIds.add(entryId),
51
+ });
52
+ return { entryIds, plan };
101
53
  }
102
54
  function validateForkSourceSnapshot(source, sourceEntries, sourceTips, options) {
103
55
  const sourceTipKeys = new Set(sourceTips.map((stored) => stored.address.key));
@@ -1 +1 @@
1
- {"version":3,"file":"fork.js","sourceRoot":"","sources":["../../../src/harness/session/fork.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAEvD,OAAO,EAAE,SAAS,E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AAC,YAAY,EAAE,UAAU,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;QACxF,MAAM,KAAK,GAAG,eAAe,CAAC,MAAM,CAAC,YAAY,EAAE,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;QAC/E,IAAI,CAAC,aAAa,KAAK,SAAS,CAAC,KAAK,CAAC,KAAK,KAAK,SAAS,CAAC,EAAE,CAAC;YAC7D,MAAM,IAAI,KAAK,CAAC,yBAAyB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;QACvG,CAAC;QACD,IAAI,OAAO,CAAC,KAAK,KAAK,QAAQ,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,KAAK,OAAO,CAAC,MAAM,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;YACrG,MAAM,IAAI,KAAK,CAAC,iBAAiB,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,MAAM,CAAC,gCAAgC,CAAC,CAAC;QAClG,CAAC;QACD,IACC,CAAC,MAAM,CAAC,eAAe,KAAK,KAAK,IAAI,OAAO,CAAC,KAAK,KAAK,MAAM,CAAC;YAC9D,GAAG,CAAC,KAAK,KAAK,IAAI;YAClB,CAAC,aAAa,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,EAC5B,CAAC;YACF,MAAM,IAAI,KAAK,CAAC,yBAAyB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC;QAChG,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["import type { CommittedWrite } from \"./commit.ts\";\nimport { classifyForkAddress } from \"./fork-policy.ts\";\nimport type { Entry, ForkOptions } from \"./types.ts\";\nimport { branchTip, laneConfig, laneState, type StoredValue, type Value, value } from \"./values.ts\";\n\nexport interface ForkSourceSnapshot {\n\tentries: Entry[];\n\tscalarValues: StoredValue<unknown>[];\n\t/** False when a backend supplied only the requested branch rather than the full tree. */\n\tentriesComplete?: boolean;\n}\n\nexport interface ForkDestinationSnapshot {\n\tentries: Map<string, Entry>;\n\tscalarValues: StoredValue<unknown>[];\n\tnextSeq: number;\n}\n\nfunction storedValuesInNamespace<T>(values: readonly StoredValue<unknown>[], address: Value<T>): StoredValue<T>[] {\n\treturn values.filter((stored) => stored.address.namespace === address.namespace) as StoredValue<T>[];\n}\n\nfunction findStoredValue<T>(values: readonly StoredValue<unknown>[], address: Value<T>): StoredValue<T> | undefined {\n\treturn values.find(\n\t\t(stored) => stored.address.namespace === address.namespace && stored.address.key === address.key,\n\t) as StoredValue<T> | undefined;\n}\n\n/** Build the complete logical state for a forked destination session. */\nexport function createForkSnapshot(source: ForkSourceSnapshot, options: ForkOptions): ForkDestinationSnapshot {\n\tconst sourceEntries = new Map(source.entries.map((entry) => [entry.id, entry]));\n\tconst sourceTips = storedValuesInNamespace(source.scalarValues, branchTip(\"\"));\n\tvalidateForkSourceSnapshot(source, sourceEntries, sourceTips, options);\n\n\tconst { entryIds, destinationTips } = selectForkContents(sourceEntries, sourceTips, options);\n\tconst entries = new Map<string, Entry>();\n\tfor (const id of entryIds) entries.set(id, sourceEntries.get(id)!);\n\n\tconst scalarValues: StoredValue<unknown>[] = [];\n\tlet nextSeq = Math.max(0, ...[...entries.values()].map((entry) => entry.seq)) + 1;\n\tconst store = <T>(address: Value<T>, storedValue: T): void => {\n\t\tscalarValues.push({\n\t\t\taddress: value<unknown>(address.namespace, address.key),\n\t\t\tvalue: storedValue,\n\t\t\tseq: nextSeq++,\n\t\t});\n\t};\n\tfor (const [branch, tipId] of destinationTips) {\n\t\tconst configuration = findStoredValue(source.scalarValues, laneConfig(branch));\n\t\tstore(branchTip(branch), tipId);\n\t\tif (configuration !== undefined) {\n\t\t\tstore(laneConfig(branch), configuration.value);\n\t\t\tstore(laneState(branch), { currentOperationId: null, lastOperationId: null, inbox: [] });\n\t\t}\n\t}\n\tfor (const stored of source.scalarValues) {\n\t\tswitch (classifyForkAddress(stored.address, options.scope, (entryId) => entryIds.has(entryId))) {\n\t\t\tcase \"copy\":\n\t\t\t\tstore(stored.address, stored.value);\n\t\t\t\tbreak;\n\t\t\tcase \"exclude\":\n\t\t\tcase \"reconstruct\":\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn { entries, scalarValues, nextSeq };\n}\n\nexport function forkSnapshotWrites(snapshot: ForkDestinationSnapshot): CommittedWrite[] {\n\tconst writes: CommittedWrite[] = [];\n\tfor (const entry of snapshot.entries.values()) writes.push({ kind: \"entry\", ...entry });\n\tfor (const stored of snapshot.scalarValues) {\n\t\twrites.push({\n\t\t\tkind: \"value\",\n\t\t\top: \"set\",\n\t\t\tseq: stored.seq,\n\t\t\tnamespace: stored.address.namespace,\n\t\t\tkey: stored.address.key,\n\t\t\tvalue: stored.value,\n\t\t});\n\t}\n\treturn writes.sort((left, right) => left.seq - right.seq);\n}\n\nfunction selectForkContents(\n\tsourceEntries: Map<string, Entry>,\n\tsourceTips: StoredValue<string | null>[],\n\toptions: ForkOptions,\n): {\n\tentryIds: Set<string>;\n\tdestinationTips: Map<string, string | null>;\n} {\n\tconst entryIds = new Set<string>();\n\tconst destinationTips = new Map<string, string | null>();\n\tif (options.scope === \"tree\") {\n\t\tfor (const id of sourceEntries.keys()) entryIds.add(id);\n\t\tfor (const stored of sourceTips) destinationTips.set(stored.address.key, stored.value);\n\t} else {\n\t\tconst sourceTip = sourceTips.find((stored) => stored.address.key === options.branch);\n\t\tif (sourceTip === undefined) throw new Error(`Unknown source branch: ${options.branch}`);\n\n\t\tconst requested = options.entryId ?? sourceTip.value;\n\t\tlet found = requested === null;\n\t\tlet tipId: string | null = null;\n\t\tlet entryId = sourceTip.value;\n\t\twhile (entryId !== null) {\n\t\t\tconst entry = sourceEntries.get(entryId);\n\t\t\tif (entry === undefined) throw new Error(`Corrupt source branch: missing parent ${entryId}`);\n\t\t\tif (entry.id === requested) {\n\t\t\t\tfound = true;\n\t\t\t\ttipId = options.position === \"before\" ? entry.parentId : entry.id;\n\t\t\t\tif (options.position !== \"before\") entryIds.add(entry.id);\n\t\t\t} else if (found) {\n\t\t\t\tentryIds.add(entry.id);\n\t\t\t}\n\t\t\tentryId = entry.parentId;\n\t\t}\n\t\tif (!found) {\n\t\t\tthrow new Error(`Fork entry ${requested} is not on source branch ${JSON.stringify(options.branch)}`);\n\t\t}\n\t\tdestinationTips.set(options.branch, tipId);\n\t}\n\treturn { entryIds, destinationTips };\n}\n\nfunction validateForkSourceSnapshot(\n\tsource: ForkSourceSnapshot,\n\tsourceEntries: Map<string, Entry>,\n\tsourceTips: StoredValue<string | null>[],\n\toptions: ForkOptions,\n): void {\n\tconst sourceTipKeys = new Set(sourceTips.map((stored) => stored.address.key));\n\n\tfor (const stored of source.scalarValues) {\n\t\tif (\n\t\t\t(stored.address.namespace === laneConfig(\"\").namespace ||\n\t\t\t\tstored.address.namespace === laneState(\"\").namespace) &&\n\t\t\t!sourceTipKeys.has(stored.address.key)\n\t\t) {\n\t\t\tthrow new Error(`Source session branch ${JSON.stringify(stored.address.key)} is missing branch.tip`);\n\t\t}\n\t}\n\tfor (const tip of sourceTips) {\n\t\tconst configuration = findStoredValue(source.scalarValues, laneConfig(tip.address.key));\n\t\tconst state = findStoredValue(source.scalarValues, laneState(tip.address.key));\n\t\tif ((configuration === undefined) !== (state === undefined)) {\n\t\t\tthrow new Error(`Source session branch ${JSON.stringify(tip.address.key)} has incomplete lane state`);\n\t\t}\n\t\tif (options.scope === \"branch\" && tip.address.key === options.branch && configuration === undefined) {\n\t\t\tthrow new Error(`Source branch ${JSON.stringify(options.branch)} is not a configured AgentLane`);\n\t\t}\n\t\tif (\n\t\t\t(source.entriesComplete !== false || options.scope === \"tree\") &&\n\t\t\ttip.value !== null &&\n\t\t\t!sourceEntries.has(tip.value)\n\t\t) {\n\t\t\tthrow new Error(`Source session branch ${JSON.stringify(tip.address.key)} has an unknown tip`);\n\t\t}\n\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,CAAC,yBAAyB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC;QAChG,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["import { type ForkCurrentStatePlan, projectForkCurrentStateWrite, selectBranchFork } from \"./fork-policy.ts\";\nimport type { Entry, ForkOptions } from \"./types.ts\";\nimport { branchTip, laneConfig, laneState, type StoredValue, type Value, value } from \"./values.ts\";\n\nexport interface ForkSourceSnapshot {\n\tentries: Entry[];\n\tscalarValues: StoredValue<unknown>[];\n\t/** False when a backend supplied only the requested branch rather than the full tree. */\n\tentriesComplete?: boolean;\n}\n\nexport interface ForkDestinationSnapshot {\n\tentries: Map<string, Entry>;\n\tscalarValues: StoredValue<unknown>[];\n\tnextSeq: number;\n}\n\nfunction storedValuesInNamespace<T>(values: readonly StoredValue<unknown>[], address: Value<T>): StoredValue<T>[] {\n\treturn values.filter((stored) => stored.address.namespace === address.namespace) as StoredValue<T>[];\n}\n\nfunction findStoredValue<T>(values: readonly StoredValue<unknown>[], address: Value<T>): StoredValue<T> | undefined {\n\treturn values.find(\n\t\t(stored) => stored.address.namespace === address.namespace && stored.address.key === address.key,\n\t) as StoredValue<T> | undefined;\n}\n\n/** Build the complete logical state for a forked destination session. */\nexport function createForkSnapshot(source: ForkSourceSnapshot, options: ForkOptions): ForkDestinationSnapshot {\n\tconst sourceEntries = new Map(source.entries.map((entry) => [entry.id, entry]));\n\tconst sourceTips = storedValuesInNamespace(source.scalarValues, branchTip(\"\"));\n\tvalidateForkSourceSnapshot(source, sourceEntries, sourceTips, options);\n\n\tconst { entryIds, plan } = selectForkContents(sourceEntries, sourceTips, options);\n\tconst entries = new Map<string, Entry>();\n\tfor (const id of entryIds) entries.set(id, sourceEntries.get(id)!);\n\n\tconst scalarValues: StoredValue<unknown>[] = [];\n\tlet nextSeq = Math.max(0, ...[...entries.values()].map((entry) => entry.seq)) + 1;\n\tfor (const stored of source.scalarValues) {\n\t\tconst projected = projectForkCurrentStateWrite(\n\t\t\t{\n\t\t\t\tkind: \"value\",\n\t\t\t\top: \"set\",\n\t\t\t\tseq: stored.seq,\n\t\t\t\tnamespace: stored.address.namespace,\n\t\t\t\tkey: stored.address.key,\n\t\t\t\tvalue: stored.value,\n\t\t\t},\n\t\t\tplan,\n\t\t\t(entryId) => entryIds.has(entryId),\n\t\t);\n\t\tif (projected !== undefined) {\n\t\t\tscalarValues.push({\n\t\t\t\taddress: value<unknown>(projected.namespace, projected.key),\n\t\t\t\tvalue: projected.value,\n\t\t\t\tseq: nextSeq++,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn { entries, scalarValues, nextSeq };\n}\n\nfunction selectForkContents(\n\tsourceEntries: Map<string, Entry>,\n\tsourceTips: StoredValue<string | null>[],\n\toptions: ForkOptions,\n): { entryIds: Set<string>; plan: ForkCurrentStatePlan } {\n\tconst entryIds = new Set<string>();\n\tif (options.scope === \"tree\") {\n\t\tfor (const id of sourceEntries.keys()) entryIds.add(id);\n\t\treturn { entryIds, plan: { scope: \"tree\" } };\n\t}\n\n\tconst sourceTip = sourceTips.find((stored) => stored.address.key === options.branch);\n\tconst plan = selectBranchFork(options, {\n\t\ttip: sourceTip?.value,\n\t\tgetParent: (entryId) => sourceEntries.get(entryId)?.parentId,\n\t\tselectEntry: (entryId) => entryIds.add(entryId),\n\t});\n\treturn { entryIds, plan };\n}\n\nfunction validateForkSourceSnapshot(\n\tsource: ForkSourceSnapshot,\n\tsourceEntries: Map<string, Entry>,\n\tsourceTips: StoredValue<string | null>[],\n\toptions: ForkOptions,\n): void {\n\tconst sourceTipKeys = new Set(sourceTips.map((stored) => stored.address.key));\n\n\tfor (const stored of source.scalarValues) {\n\t\tif (\n\t\t\t(stored.address.namespace === laneConfig(\"\").namespace ||\n\t\t\t\tstored.address.namespace === laneState(\"\").namespace) &&\n\t\t\t!sourceTipKeys.has(stored.address.key)\n\t\t) {\n\t\t\tthrow new Error(`Source session branch ${JSON.stringify(stored.address.key)} is missing branch.tip`);\n\t\t}\n\t}\n\tfor (const tip of sourceTips) {\n\t\tconst configuration = findStoredValue(source.scalarValues, laneConfig(tip.address.key));\n\t\tconst state = findStoredValue(source.scalarValues, laneState(tip.address.key));\n\t\tif ((configuration === undefined) !== (state === undefined)) {\n\t\t\tthrow new Error(`Source session branch ${JSON.stringify(tip.address.key)} has incomplete lane state`);\n\t\t}\n\t\tif (options.scope === \"branch\" && tip.address.key === options.branch && configuration === undefined) {\n\t\t\tthrow new Error(`Source branch ${JSON.stringify(options.branch)} is not a configured AgentLane`);\n\t\t}\n\t\tif (\n\t\t\t(source.entriesComplete !== false || options.scope === \"tree\") &&\n\t\t\ttip.value !== null &&\n\t\t\t!sourceEntries.has(tip.value)\n\t\t) {\n\t\t\tthrow new Error(`Source session branch ${JSON.stringify(tip.address.key)} has an unknown tip`);\n\t\t}\n\t}\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { type CommittedWrite, type PreparedCommit } from "./commit.ts";
2
2
  export type { CommittedEntryWrite, CommittedListAppendWrite, CommittedListDeleteWrite, CommittedUsageWrite, CommittedValueDeleteWrite, CommittedValueSetWrite, CommittedWrite, PreparedCommit, } from "./commit.ts";
3
- import type { Entry, EntryScan, EntryStructure, SessionStats, StorageBranchScan, UsageRow, UsageScan, Write } from "./types.ts";
3
+ import type { Entry, EntryScan, EntryStructure, ForkOptions, SessionStats, StorageBranchScan, UsageRow, UsageScan, Write } from "./types.ts";
4
4
  import { type ListElement, type ListReadOptions, type StoredValue, type Value, type ValueList } from "./values.ts";
5
5
  /**
6
6
  * Complete materialized session state for MemoryStorage and JsonlStorage.
@@ -21,6 +21,9 @@ export declare class InMemoryStorageState {
21
21
  validateCommitted(writes: readonly CommittedWrite[]): void;
22
22
  /** Apply writes already accepted by validateCommitted() and return the post-apply totals. */
23
23
  applyValidated(writes: readonly CommittedWrite[]): SessionStats;
24
+ createFork(options: ForkOptions): InMemoryStorageState;
25
+ private selectForkPlan;
26
+ private applyValueSetOrListAppend;
24
27
  advanceNextSeq(nextSeq: number): void;
25
28
  getEntries(ids: readonly string[]): Map<string, Entry>;
26
29
  getValue<T>(address: Value<T>): StoredValue<T> | undefined;
@@ -31,9 +34,6 @@ export declare class InMemoryStorageState {
31
34
  scanEntries(query: EntryScan): Entry[];
32
35
  scanUsage(query: UsageScan): UsageRow[];
33
36
  getStats(): SessionStats;
34
- snapshotEntriesAndValues(): {
35
- entries: Entry[];
36
- scalarValues: StoredValue<unknown>[];
37
- };
37
+ getNextSeq(): number;
38
38
  }
39
39
  //# sourceMappingURL=in-memory-storage-state.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"in-memory-storage-state.d.ts","sourceRoot":"","sources":["../../../src/harness/session/in-memory-storage-state.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,cAAc,EAAE,KAAK,cAAc,EAAiD,MAAM,aAAa,CAAC;AAEtH,YAAY,EACX,mBAAmB,EACnB,wBAAwB,EACxB,wBAAwB,EACxB,mBAAmB,EACnB,yBAAyB,EACzB,sBAAsB,EACtB,cAAc,EACd,cAAc,GACd,MAAM,aAAa,CAAC;AAErB,OAAO,KAAK,EACX,KAAK,EACL,SAAS,EACT,cAAc,EACd,YAAY,EACZ,iBAAiB,EACjB,QAAQ,EACR,SAAS,EACT,KAAK,EACL,MAAM,YAAY,CAAC;AACpB,OAAO,EACN,KAAK,WAAW,EAChB,KAAK,eAAe,EAGpB,KAAK,WAAW,EAChB,KAAK,KAAK,EACV,KAAK,SAAS,EAEd,MAAM,aAAa,CAAC;AAsBrB;;;;;GAKG;AACH,qBAAa,oBAAoB;IAChC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAqB;IAC7C,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAU;IACvC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAoC;IACjE,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAkC;IAC7D,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAwB;IAC9C,OAAO,CAA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sage, emptyUsage } from \"../utils/usage.ts\";\nimport { type CommittedWrite, type PreparedCommit, prepareStorageCommit, validateCommittedWrites } from \"./commit.ts\";\n\nexport type {\n\tCommittedEntryWrite,\n\tCommittedListAppendWrite,\n\tCommittedListDeleteWrite,\n\tCommittedUsageWrite,\n\tCommittedValueDeleteWrite,\n\tCommittedValueSetWrite,\n\tCommittedWrite,\n\tPreparedCommit,\n} from \"./commit.ts\";\n\nimport type {\n\tEntry,\n\tEntryScan,\n\tEntryStructure,\n\tSessionStats,\n\tStorageBranchScan,\n\tUsageRow,\n\tUsageScan,\n\tWrite,\n} from \"./types.ts\";\nimport {\n\ttype ListElement,\n\ttype ListReadOptions,\n\tlist,\n\tresolveListReadOptions,\n\ttype StoredValue,\n\ttype Value,\n\ttype ValueList,\n\tvalue,\n} from \"./values.ts\";\n\ninterface StoredListSnapshot {\n\taddress: ValueList<unknown>;\n\telements: ListElement<unknown>[];\n}\n\nfunction physicalKey(namespace: string, key: string): string {\n\treturn `${namespace}\\u0000${key}`;\n}\n\nfunction compareKeys(left: string, right: string): number {\n\tconst leftCodePoints = Array.from(left, (character) => character.codePointAt(0)!);\n\tconst rightCodePoints = Array.from(right, (character) => character.codePointAt(0)!);\n\tconst length = Math.min(leftCodePoints.length, rightCodePoints.length);\n\tfor (let index = 0; index < length; index++) {\n\t\tconst difference = leftCodePoints[index]! - rightCodePoints[index]!;\n\t\tif (difference !== 0) return difference;\n\t}\n\treturn leftCodePoints.length - rightCodePoints.length;\n}\n\n/**\n * Complete materialized session state for MemoryStorage and JsonlStorage.\n *\n * This is intentionally unsuitable for database backends and long-running sessions that may not fit in memory.\n * Those backends should query indexed durable state and update durable aggregates within each commit transaction.\n */\nexport class InMemoryStorageState {\n\tprivate readonly entries: Map<string, Entry>;\n\tprivate readonly entriesBySeq: Entry[];\n\tprivate readonly scalarValues: Map<string, StoredValue<unknown>>;\n\tprivate readonly listValues: Map<string, StoredListSnapshot>;\n\tprivate readonly usage: Map<string, UsageRow>;\n\tprivate stats: SessionStats;\n\tprivate nextSeq: number;\n\n\tconstructor() {\n\t\tthis.entries = new Map();\n\t\tthis.entriesBySeq = [];\n\t\tthis.scalarValues = new Map();\n\t\tthis.listValues = new Map();\n\t\tthis.usage = new Map();\n\t\tthis.stats = { messageCount: 0, usage: emptyUsage() };\n\t\tthis.nextSeq = 1;\n\t}\n\n\tprepareCommit(writes: Write[], timestamp: number): PreparedCommit {\n\t\tconst prepared = prepareStorageCommit(writes, this.nextSeq, timestamp);\n\t\tthis.validateCommitted(prepared.writes);\n\t\treturn prepared;\n\t}\n\n\tvalidateCommitted(writes: readonly CommittedWrite[]): void {\n\t\tvalidateCommittedWrites(writes, this.nextSeq, {\n\t\t\thasEntryOrUsageId: (id) => this.entries.has(id) || this.usage.has(id),\n\t\t\thasEntryId: (id) => this.entries.has(id),\n\t\t});\n\t}\n\n\t/** Apply writes already accepted by validateCommitted() and return the post-apply totals. */\n\tapplyValidated(writes: readonly CommittedWrite[]): SessionStats {\n\t\tfor (const write of writes) {\n\t\t\tswitch (write.kind) {\n\t\t\t\tcase \"entry\": {\n\t\t\t\t\tconst { kind: _kind, ...entry } = write;\n\t\t\t\t\tthis.entries.set(entry.id, entry);\n\t\t\t\t\tthis.entriesBySeq.push(entry);\n\t\t\t\t\tif (entry.type === \"message\") this.stats = { ...this.stats, messageCount: this.stats.messageCount + 1 };\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"usage\": {\n\t\t\t\t\tconst { kind: _kind, ...row } = write;\n\t\t\t\t\tthis.usage.set(row.id, row);\n\t\t\t\t\tthis.stats = { ...this.stats, usage: addUsage(this.stats.usage, row.usage) };\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"value\": {\n\t\t\t\t\tconst key = physicalKey(write.namespace, write.key);\n\t\t\t\t\tif (write.op === \"delete\") {\n\t\t\t\t\t\tthis.scalarValues.delete(key);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.scalarValues.set(key, {\n\t\t\t\t\t\t\taddress: value<unknown>(write.namespace, write.key),\n\t\t\t\t\t\t\tvalue: write.value,\n\t\t\t\t\t\t\tseq: write.seq,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"list\": {\n\t\t\t\t\tconst key = physicalKey(write.namespace, write.key);\n\t\t\t\t\tif (write.op === \"delete\") {\n\t\t\t\t\t\tthis.listValues.delete(key);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst stored = this.listValues.get(key);\n\t\t\t\t\t\tconst element = { seq: write.seq, value: write.value };\n\t\t\t\t\t\tif (stored === undefined) {\n\t\t\t\t\t\t\tthis.listValues.set(key, {\n\t\t\t\t\t\t\t\taddress: list<unknown>(write.namespace, write.key),\n\t\t\t\t\t\t\t\telements: [element],\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tstored.elements.push(element);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.nextSeq = write.seq + 1;\n\t\t}\n\t\treturn this.stats;\n\t}\n\n\tadvanceNextSeq(nextSeq: number): void {\n\t\tif (!Number.isSafeInteger(nextSeq) || nextSeq < 1) {\n\t\t\tthrow new Error(`Invalid storage sequence high-water mark: ${nextSeq}`);\n\t\t}\n\t\tthis.nextSeq = Math.max(this.nextSeq, nextSeq);\n\t}\n\n\tgetEntries(ids: readonly string[]): Map<string, Entry> {\n\t\tconst found = new Map<string, Entry>();\n\t\tfor (const id of ids) {\n\t\t\tconst entry = this.entries.get(id);\n\t\t\tif (entry !== undefined) found.set(id, entry);\n\t\t}\n\t\treturn found;\n\t}\n\n\tgetValue<T>(address: Value<T>): StoredValue<T> | undefined {\n\t\treturn this.scalarValues.get(physicalKey(address.namespace, address.key)) as StoredValue<T> | undefined;\n\t}\n\n\tscanValues<T>(prefix: Value<T>): StoredValue<T>[] {\n\t\treturn [...this.scalarValues.values()]\n\t\t\t.filter((stored) => stored.address.namespace === prefix.namespace && stored.address.key.startsWith(prefix.key))\n\t\t\t.sort((left, right) => compareKeys(left.address.key, right.address.key)) as StoredValue<T>[];\n\t}\n\n\treadList<T>(address: ValueList<T>, options?: ListReadOptions): ListElement<T>[] {\n\t\tconst resolved = resolveListReadOptions(options);\n\t\tconst elements = this.listValues.get(physicalKey(address.namespace, address.key))?.elements ?? [];\n\t\tconst filtered = elements.filter((element) => {\n\t\t\tif (resolved.cursor === undefined) return true;\n\t\t\treturn resolved.order === \"asc\" ? element.seq > resolved.cursor.seq : element.seq < resolved.cursor.seq;\n\t\t});\n\t\tconst ordered = resolved.order === \"asc\" ? filtered : [...filtered].reverse();\n\t\treturn ordered.slice(0, resolved.limit) as ListElement<T>[];\n\t}\n\n\tscanBranch(query: StorageBranchScan): Entry[] {\n\t\tconst start = this.entries.get(query.start);\n\t\tif (start === undefined) throw new Error(`Unknown branch start: ${query.start}`);\n\n\t\tconst path: Entry[] = [];\n\t\tlet entry: Entry | undefined = start;\n\t\twhile (entry !== undefined) {\n\t\t\tpath.push(entry);\n\t\t\tif (entry.parentId === null) break;\n\t\t\tentry = this.entries.get(entry.parentId);\n\t\t\tif (entry === undefined) throw new Error(\"Corrupt branch: missing parent\");\n\t\t}\n\t\tif (query.order === \"oldestFirst\") path.reverse();\n\n\t\tconst stopped: Entry[] = [];\n\t\tfor (const candidate of path) {\n\t\t\tstopped.push(candidate);\n\t\t\tif (candidate.id === query.stopAtId || candidate.type === query.stopAtType) break;\n\t\t}\n\t\tconst filtered = stopped\n\t\t\t.filter((candidate) => query.type === undefined || candidate.type === query.type)\n\t\t\t.filter((candidate) => query.customType === undefined || candidate.customType === query.customType)\n\t\t\t.filter(\n\t\t\t\t(candidate) =>\n\t\t\t\t\tquery.cursor === undefined ||\n\t\t\t\t\t(query.order === \"oldestFirst\" ? candidate.seq > query.cursor.seq : candidate.seq < query.cursor.seq),\n\t\t\t);\n\t\treturn query.limit === undefined ? filtered : filtered.slice(0, Math.max(0, query.limit));\n\t}\n\n\tscanBranchStructure(query: StorageBranchScan): EntryStructure[] {\n\t\treturn this.scanBranch(query).map((entry) => ({\n\t\t\tid: entry.id,\n\t\t\tparentId: entry.parentId,\n\t\t\tseq: entry.seq,\n\t\t\ttimestamp: entry.timestamp,\n\t\t\ttype: entry.type,\n\t\t\t...(entry.customType === undefined ? {} : { customType: entry.customType }),\n\t\t}));\n\t}\n\n\tscanEntries(query: EntryScan): Entry[] {\n\t\tconst limit = query.limit === undefined ? Number.POSITIVE_INFINITY : Math.max(0, Math.trunc(query.limit));\n\t\tconst entries: Entry[] = [];\n\t\tconst descending = query.order === \"desc\";\n\t\tlet index = descending ? this.entriesBySeq.length - 1 : 0;\n\t\twhile (index >= 0 && index < this.entriesBySeq.length && entries.length < limit) {\n\t\t\tconst entry = this.entriesBySeq[index]!;\n\t\t\tif (\n\t\t\t\t(query.type === undefined || entry.type === query.type) &&\n\t\t\t\t(query.customType === undefined || entry.customType === query.customType) &&\n\t\t\t\t(query.fromSeq === undefined || entry.seq >= query.fromSeq) &&\n\t\t\t\t(query.toSeq === undefined || entry.seq <= query.toSeq)\n\t\t\t) {\n\t\t\t\tentries.push(entry);\n\t\t\t}\n\t\t\tindex += descending ? -1 : 1;\n\t\t}\n\t\treturn entries;\n\t}\n\n\tscanUsage(query: UsageScan): UsageRow[] {\n\t\tconst rows = [...this.usage.values()]\n\t\t\t.filter((row) => query.fromSeq === undefined || row.seq >= query.fromSeq)\n\t\t\t.filter((row) => query.toSeq === undefined || row.seq <= query.toSeq)\n\t\t\t.sort((left, right) => (query.order === \"desc\" ? right.seq - left.seq : left.seq - right.seq));\n\t\treturn query.limit === undefined ? rows : rows.slice(0, Math.max(0, query.limit));\n\t}\n\n\tgetStats(): SessionStats {\n\t\treturn this.stats;\n\t}\n\n\tsnapshotEntriesAndValues(): { entries: Entry[]; scalarValues: StoredValue<unknown>[] } {\n\t\treturn {\n\t\t\tentries: [...this.entries.values()].sort((left, right) => left.seq - right.seq),\n\t\t\tscalarValues: [...this.scalarValues.values()],\n\t\t};\n\t}\n}\n"]}
1
+ {"version":3,"file":"in-memory-storage-state.d.ts","sourceRoot":"","sources":["../../../src/harness/session/in-memory-storage-state.ts"],"names":[],"mappings":"AACA,OAAO,EAGN,KAAK,cAAc,EACnB,KAAK,cAAc,EAGnB,MAAM,aAAa,CAAC;AAGrB,YAAY,EACX,mBAAmB,EACnB,wBAAwB,EACxB,wBAAwB,EACxB,mBAAmB,EACnB,yBAAyB,EACzB,sBAAsB,EACtB,cAAc,EACd,cAAc,GACd,MAAM,aAAa,CAAC;AAErB,OAAO,KAAK,EACX,KAAK,EACL,SAAS,EACT,cAAc,EACd,WAAW,EACX,YAAY,EACZ,iBAAiB,EACjB,QAAQ,EACR,SAAS,EACT,KAAK,EACL,MAAM,YAAY,CAAC;AACpB,OAAO,EAEN,KAAK,WAAW,EAChB,KAAK,eAAe,EAKpB,KAAK,WAAW,EAChB,KAAK,KAAK,EACV,KAAK,SAAS,EAEd,MAAM,aAAa,CAAC;AA0BrB;;;;;GAKG;AACH,qBAAa,oBAAoB;IAChC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAqB;IAC7C,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAU;IACvC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAoC;IACjE,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAkC;IAC7D,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAwB;IAC9C,OAAO,CAAC,KAAK,CAAe;IAC5B,OAAO,CAAC,OAAO,CAAS;IAExB,cAQC;IAED,aAAa,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,SAAS,EAAE,MAAM,GAAG,cAAc,CAIhE;IAED,iBAAiB,CAAC,MAAM,EAAE,SAAS,cAAc,EAAE,GAAG,IAAI,CAKzD;IAED,6FAA6F;IAC7F,cAAc,CAAC,MAAM,EAAE,SAAS,cAAc,EAAE,GAAG,YAAY,CA4B9D;IAED,UAAU,CAAC,OAAO,EAAE,WAAW,GAAG,oBAAoB,CAoDrD;IAED,OAAO,CAAC,cAAc;IAkBtB,OAAO,CAAC,yBAAyB;IAuBjC,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAKpC;IAED,UAAU,CAAC,GAAG,EAAE,SAAS,MAAM,EAAE,GAAG,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,CAOrD;IAED,QAAQ,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,GAAG,SAAS,CAEzD;IAED,UAAU,CAAC,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,EAAE,CAIhD;IAED,QAAQ,CAAC,CAAC,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,WAAW,CAAC,CAAC,CAAC,EAAE,CAS9E;IAED,UAAU,CAAC,KAAK,EAAE,iBAAiB,GAAG,KAAK,EAAE,CA4B5C;IAED,mBAAmB,CAAC,KAAK,EAAE,iBAAiB,GAAG,cAAc,EAAE,CAS9D;IAED,WAAW,CAAC,KAAK,EAAE,SAAS,GAAG,KAAK,EAAE,CAkBrC;IAED,SAAS,CAAC,KAAK,EAAE,SAAS,GAAG,QAAQ,EAAE,CAMtC;IAED,QAAQ,IAAI,YAAY,CAEvB;IAED,UAAU,IAAI,MAAM,CAEnB;CACD","sourcesContent":["import { addUsage, emptyUsage } from \"../utils/usage.ts\";\nimport {\n\ttype CommittedListAppendWrite,\n\ttype CommittedValueSetWrite,\n\ttype CommittedWrite,\n\ttype PreparedCommit,\n\tprepareStorageCommit,\n\tvalidateCommittedWrites,\n} from \"./commit.ts\";\nimport { projectForkCurrentStateWrite, selectBranchFork } from \"./fork-policy.ts\";\n\nexport type {\n\tCommittedEntryWrite,\n\tCommittedListAppendWrite,\n\tCommittedListDeleteWrite,\n\tCommittedUsageWrite,\n\tCommittedValueDeleteWrite,\n\tCommittedValueSetWrite,\n\tCommittedWrite,\n\tPreparedCommit,\n} from \"./commit.ts\";\n\nimport type {\n\tEntry,\n\tEntryScan,\n\tEntryStructure,\n\tForkOptions,\n\tSessionStats,\n\tStorageBranchScan,\n\tUsageRow,\n\tUsageScan,\n\tWrite,\n} from \"./types.ts\";\nimport {\n\tbranchTip,\n\ttype ListElement,\n\ttype ListReadOptions,\n\tlaneConfig,\n\tlaneState,\n\tlist,\n\tresolveListReadOptions,\n\ttype StoredValue,\n\ttype Value,\n\ttype ValueList,\n\tvalue,\n} from \"./values.ts\";\n\ninterface StoredListSnapshot {\n\taddress: ValueList<unknown>;\n\telements: ListElement<unknown>[];\n}\n\ntype MemoryForkPlan =\n\t| { scope: \"tree\" }\n\t| { scope: \"branch\"; branch: string; destinationTip: string | null; entryIds: Set<string> };\n\nfunction physicalKey(namespace: string, key: string): string {\n\treturn `${namespace}\\u0000${key}`;\n}\n\nfunction compareKeys(left: string, right: string): number {\n\tconst leftCodePoints = Array.from(left, (character) => character.codePointAt(0)!);\n\tconst rightCodePoints = Array.from(right, (character) => character.codePointAt(0)!);\n\tconst length = Math.min(leftCodePoints.length, rightCodePoints.length);\n\tfor (let index = 0; index < length; index++) {\n\t\tconst difference = leftCodePoints[index]! - rightCodePoints[index]!;\n\t\tif (difference !== 0) return difference;\n\t}\n\treturn leftCodePoints.length - rightCodePoints.length;\n}\n\n/**\n * Complete materialized session state for MemoryStorage and JsonlStorage.\n *\n * This is intentionally unsuitable for database backends and long-running sessions that may not fit in memory.\n * Those backends should query indexed durable state and update durable aggregates within each commit transaction.\n */\nexport class InMemoryStorageState {\n\tprivate readonly entries: Map<string, Entry>;\n\tprivate readonly entriesBySeq: Entry[];\n\tprivate readonly scalarValues: Map<string, StoredValue<unknown>>;\n\tprivate readonly listValues: Map<string, StoredListSnapshot>;\n\tprivate readonly usage: Map<string, UsageRow>;\n\tprivate stats: SessionStats;\n\tprivate nextSeq: number;\n\n\tconstructor() {\n\t\tthis.entries = new Map();\n\t\tthis.entriesBySeq = [];\n\t\tthis.scalarValues = new Map();\n\t\tthis.listValues = new Map();\n\t\tthis.usage = new Map();\n\t\tthis.stats = { messageCount: 0, usage: emptyUsage() };\n\t\tthis.nextSeq = 1;\n\t}\n\n\tprepareCommit(writes: Write[], timestamp: number): PreparedCommit {\n\t\tconst prepared = prepareStorageCommit(writes, this.nextSeq, timestamp);\n\t\tthis.validateCommitted(prepared.writes);\n\t\treturn prepared;\n\t}\n\n\tvalidateCommitted(writes: readonly CommittedWrite[]): void {\n\t\tvalidateCommittedWrites(writes, this.nextSeq, {\n\t\t\thasEntryOrUsageId: (id) => this.entries.has(id) || this.usage.has(id),\n\t\t\thasEntryId: (id) => this.entries.has(id),\n\t\t});\n\t}\n\n\t/** Apply writes already accepted by validateCommitted() and return the post-apply totals. */\n\tapplyValidated(writes: readonly CommittedWrite[]): SessionStats {\n\t\tfor (const write of writes) {\n\t\t\tswitch (write.kind) {\n\t\t\t\tcase \"entry\": {\n\t\t\t\t\tconst { kind: _kind, ...entry } = write;\n\t\t\t\t\tthis.entries.set(entry.id, entry);\n\t\t\t\t\tthis.entriesBySeq.push(entry);\n\t\t\t\t\tif (entry.type === \"message\") this.stats = { ...this.stats, messageCount: this.stats.messageCount + 1 };\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"usage\": {\n\t\t\t\t\tconst { kind: _kind, ...row } = write;\n\t\t\t\t\tthis.usage.set(row.id, row);\n\t\t\t\t\tthis.stats = { ...this.stats, usage: addUsage(this.stats.usage, row.usage) };\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"value\":\n\t\t\t\t\tif (write.op === \"delete\") this.scalarValues.delete(physicalKey(write.namespace, write.key));\n\t\t\t\t\telse this.applyValueSetOrListAppend(write);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"list\":\n\t\t\t\t\tif (write.op === \"delete\") this.listValues.delete(physicalKey(write.namespace, write.key));\n\t\t\t\t\telse this.applyValueSetOrListAppend(write);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tthis.nextSeq = write.seq + 1;\n\t\t}\n\t\treturn this.stats;\n\t}\n\n\tcreateFork(options: ForkOptions): InMemoryStorageState {\n\t\tconst plan = this.selectForkPlan(options);\n\n\t\tconst isEntryCopied = (entryId: string): boolean => {\n\t\t\tif (plan.scope === \"tree\") return true;\n\t\t\treturn plan.entryIds.has(entryId);\n\t\t};\n\t\tconst destination = new InMemoryStorageState();\n\t\tlet messageCount = 0;\n\t\tfor (const entry of this.entriesBySeq) {\n\t\t\tif (!isEntryCopied(entry.id)) continue;\n\t\t\tdestination.entries.set(entry.id, entry);\n\t\t\tdestination.entriesBySeq.push(entry);\n\t\t\tif (entry.type === \"message\") messageCount++;\n\t\t}\n\t\tdestination.stats = { ...destination.stats, messageCount };\n\n\t\tfor (const stored of this.scalarValues.values()) {\n\t\t\tconst projected = projectForkCurrentStateWrite(\n\t\t\t\t{\n\t\t\t\t\tkind: \"value\",\n\t\t\t\t\top: \"set\",\n\t\t\t\t\tseq: stored.seq,\n\t\t\t\t\tnamespace: stored.address.namespace,\n\t\t\t\t\tkey: stored.address.key,\n\t\t\t\t\tvalue: stored.value,\n\t\t\t\t},\n\t\t\t\tplan,\n\t\t\t\tisEntryCopied,\n\t\t\t);\n\t\t\tif (projected !== undefined) destination.applyValueSetOrListAppend(projected);\n\t\t}\n\n\t\tfor (const stored of this.listValues.values()) {\n\t\t\tfor (const element of stored.elements) {\n\t\t\t\tconst projected = projectForkCurrentStateWrite(\n\t\t\t\t\t{\n\t\t\t\t\t\tkind: \"list\",\n\t\t\t\t\t\top: \"append\",\n\t\t\t\t\t\tseq: element.seq,\n\t\t\t\t\t\tnamespace: stored.address.namespace,\n\t\t\t\t\t\tkey: stored.address.key,\n\t\t\t\t\t\tvalue: element.value,\n\t\t\t\t\t},\n\t\t\t\t\tplan,\n\t\t\t\t\tisEntryCopied,\n\t\t\t\t);\n\t\t\t\tif (projected !== undefined) destination.applyValueSetOrListAppend(projected);\n\t\t\t}\n\t\t}\n\t\tdestination.nextSeq = this.nextSeq;\n\t\treturn destination;\n\t}\n\n\tprivate selectForkPlan(options: ForkOptions): MemoryForkPlan {\n\t\tif (options.scope === \"tree\") return { scope: \"tree\" };\n\n\t\tconst entryIds = new Set<string>();\n\t\tconst plan = selectBranchFork(options, {\n\t\t\ttip: this.getValue(branchTip(options.branch))?.value,\n\t\t\tgetParent: (entryId) => this.entries.get(entryId)?.parentId,\n\t\t\tselectEntry: (entryId) => entryIds.add(entryId),\n\t\t});\n\t\tif (\n\t\t\tthis.getValue(laneConfig(options.branch)) === undefined ||\n\t\t\tthis.getValue(laneState(options.branch)) === undefined\n\t\t) {\n\t\t\tthrow new Error(`Source branch ${JSON.stringify(options.branch)} is not a configured AgentLane`);\n\t\t}\n\t\treturn { ...plan, entryIds };\n\t}\n\n\tprivate applyValueSetOrListAppend(write: CommittedValueSetWrite | CommittedListAppendWrite): void {\n\t\tconst key = physicalKey(write.namespace, write.key);\n\t\tif (write.kind === \"value\") {\n\t\t\tthis.scalarValues.set(key, {\n\t\t\t\taddress: value<unknown>(write.namespace, write.key),\n\t\t\t\tvalue: write.value,\n\t\t\t\tseq: write.seq,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tconst element = { seq: write.seq, value: write.value };\n\t\tconst stored = this.listValues.get(key);\n\t\tif (stored === undefined) {\n\t\t\tthis.listValues.set(key, {\n\t\t\t\taddress: list<unknown>(write.namespace, write.key),\n\t\t\t\telements: [element],\n\t\t\t});\n\t\t} else {\n\t\t\tstored.elements.push(element);\n\t\t}\n\t}\n\n\tadvanceNextSeq(nextSeq: number): void {\n\t\tif (!Number.isSafeInteger(nextSeq) || nextSeq < 1) {\n\t\t\tthrow new Error(`Invalid storage sequence high-water mark: ${nextSeq}`);\n\t\t}\n\t\tthis.nextSeq = Math.max(this.nextSeq, nextSeq);\n\t}\n\n\tgetEntries(ids: readonly string[]): Map<string, Entry> {\n\t\tconst found = new Map<string, Entry>();\n\t\tfor (const id of ids) {\n\t\t\tconst entry = this.entries.get(id);\n\t\t\tif (entry !== undefined) found.set(id, entry);\n\t\t}\n\t\treturn found;\n\t}\n\n\tgetValue<T>(address: Value<T>): StoredValue<T> | undefined {\n\t\treturn this.scalarValues.get(physicalKey(address.namespace, address.key)) as StoredValue<T> | undefined;\n\t}\n\n\tscanValues<T>(prefix: Value<T>): StoredValue<T>[] {\n\t\treturn [...this.scalarValues.values()]\n\t\t\t.filter((stored) => stored.address.namespace === prefix.namespace && stored.address.key.startsWith(prefix.key))\n\t\t\t.sort((left, right) => compareKeys(left.address.key, right.address.key)) as StoredValue<T>[];\n\t}\n\n\treadList<T>(address: ValueList<T>, options?: ListReadOptions): ListElement<T>[] {\n\t\tconst resolved = resolveListReadOptions(options);\n\t\tconst elements = this.listValues.get(physicalKey(address.namespace, address.key))?.elements ?? [];\n\t\tconst filtered = elements.filter((element) => {\n\t\t\tif (resolved.cursor === undefined) return true;\n\t\t\treturn resolved.order === \"asc\" ? element.seq > resolved.cursor.seq : element.seq < resolved.cursor.seq;\n\t\t});\n\t\tconst ordered = resolved.order === \"asc\" ? filtered : [...filtered].reverse();\n\t\treturn ordered.slice(0, resolved.limit) as ListElement<T>[];\n\t}\n\n\tscanBranch(query: StorageBranchScan): Entry[] {\n\t\tconst start = this.entries.get(query.start);\n\t\tif (start === undefined) throw new Error(`Unknown branch start: ${query.start}`);\n\n\t\tconst path: Entry[] = [];\n\t\tlet entry: Entry | undefined = start;\n\t\twhile (entry !== undefined) {\n\t\t\tpath.push(entry);\n\t\t\tif (entry.parentId === null) break;\n\t\t\tentry = this.entries.get(entry.parentId);\n\t\t\tif (entry === undefined) throw new Error(\"Corrupt branch: missing parent\");\n\t\t}\n\t\tif (query.order === \"oldestFirst\") path.reverse();\n\n\t\tconst stopped: Entry[] = [];\n\t\tfor (const candidate of path) {\n\t\t\tstopped.push(candidate);\n\t\t\tif (candidate.id === query.stopAtId || candidate.type === query.stopAtType) break;\n\t\t}\n\t\tconst filtered = stopped\n\t\t\t.filter((candidate) => query.type === undefined || candidate.type === query.type)\n\t\t\t.filter((candidate) => query.customType === undefined || candidate.customType === query.customType)\n\t\t\t.filter(\n\t\t\t\t(candidate) =>\n\t\t\t\t\tquery.cursor === undefined ||\n\t\t\t\t\t(query.order === \"oldestFirst\" ? candidate.seq > query.cursor.seq : candidate.seq < query.cursor.seq),\n\t\t\t);\n\t\treturn query.limit === undefined ? filtered : filtered.slice(0, Math.max(0, query.limit));\n\t}\n\n\tscanBranchStructure(query: StorageBranchScan): EntryStructure[] {\n\t\treturn this.scanBranch(query).map((entry) => ({\n\t\t\tid: entry.id,\n\t\t\tparentId: entry.parentId,\n\t\t\tseq: entry.seq,\n\t\t\ttimestamp: entry.timestamp,\n\t\t\ttype: entry.type,\n\t\t\t...(entry.customType === undefined ? {} : { customType: entry.customType }),\n\t\t}));\n\t}\n\n\tscanEntries(query: EntryScan): Entry[] {\n\t\tconst limit = query.limit === undefined ? Number.POSITIVE_INFINITY : Math.max(0, Math.trunc(query.limit));\n\t\tconst entries: Entry[] = [];\n\t\tconst descending = query.order === \"desc\";\n\t\tlet index = descending ? this.entriesBySeq.length - 1 : 0;\n\t\twhile (index >= 0 && index < this.entriesBySeq.length && entries.length < limit) {\n\t\t\tconst entry = this.entriesBySeq[index]!;\n\t\t\tif (\n\t\t\t\t(query.type === undefined || entry.type === query.type) &&\n\t\t\t\t(query.customType === undefined || entry.customType === query.customType) &&\n\t\t\t\t(query.fromSeq === undefined || entry.seq >= query.fromSeq) &&\n\t\t\t\t(query.toSeq === undefined || entry.seq <= query.toSeq)\n\t\t\t) {\n\t\t\t\tentries.push(entry);\n\t\t\t}\n\t\t\tindex += descending ? -1 : 1;\n\t\t}\n\t\treturn entries;\n\t}\n\n\tscanUsage(query: UsageScan): UsageRow[] {\n\t\tconst rows = [...this.usage.values()]\n\t\t\t.filter((row) => query.fromSeq === undefined || row.seq >= query.fromSeq)\n\t\t\t.filter((row) => query.toSeq === undefined || row.seq <= query.toSeq)\n\t\t\t.sort((left, right) => (query.order === \"desc\" ? right.seq - left.seq : left.seq - right.seq));\n\t\treturn query.limit === undefined ? rows : rows.slice(0, Math.max(0, query.limit));\n\t}\n\n\tgetStats(): SessionStats {\n\t\treturn this.stats;\n\t}\n\n\tgetNextSeq(): number {\n\t\treturn this.nextSeq;\n\t}\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { addUsage, emptyUsage } from "../utils/usage.js";
2
- import { prepareStorageCommit, validateCommittedWrites } from "./commit.js";
3
- import { list, resolveListReadOptions, value, } from "./values.js";
2
+ import { prepareStorageCommit, validateCommittedWrites, } from "./commit.js";
3
+ import { projectForkCurrentStateWrite, selectBranchFork } from "./fork-policy.js";
4
+ import { branchTip, laneConfig, laneState, list, resolveListReadOptions, value, } from "./values.js";
4
5
  function physicalKey(namespace, key) {
5
6
  return `${namespace}\u0000${key}`;
6
7
  }
@@ -67,45 +68,107 @@ export class InMemoryStorageState {
67
68
  this.stats = { ...this.stats, usage: addUsage(this.stats.usage, row.usage) };
68
69
  break;
69
70
  }
70
- case "value": {
71
- const key = physicalKey(write.namespace, write.key);
72
- if (write.op === "delete") {
73
- this.scalarValues.delete(key);
74
- }
75
- else {
76
- this.scalarValues.set(key, {
77
- address: value(write.namespace, write.key),
78
- value: write.value,
79
- seq: write.seq,
80
- });
81
- }
71
+ case "value":
72
+ if (write.op === "delete")
73
+ this.scalarValues.delete(physicalKey(write.namespace, write.key));
74
+ else
75
+ this.applyValueSetOrListAppend(write);
82
76
  break;
83
- }
84
- case "list": {
85
- const key = physicalKey(write.namespace, write.key);
86
- if (write.op === "delete") {
87
- this.listValues.delete(key);
88
- }
89
- else {
90
- const stored = this.listValues.get(key);
91
- const element = { seq: write.seq, value: write.value };
92
- if (stored === undefined) {
93
- this.listValues.set(key, {
94
- address: list(write.namespace, write.key),
95
- elements: [element],
96
- });
97
- }
98
- else {
99
- stored.elements.push(element);
100
- }
101
- }
77
+ case "list":
78
+ if (write.op === "delete")
79
+ this.listValues.delete(physicalKey(write.namespace, write.key));
80
+ else
81
+ this.applyValueSetOrListAppend(write);
102
82
  break;
103
- }
104
83
  }
105
84
  this.nextSeq = write.seq + 1;
106
85
  }
107
86
  return this.stats;
108
87
  }
88
+ createFork(options) {
89
+ const plan = this.selectForkPlan(options);
90
+ const isEntryCopied = (entryId) => {
91
+ if (plan.scope === "tree")
92
+ return true;
93
+ return plan.entryIds.has(entryId);
94
+ };
95
+ const destination = new InMemoryStorageState();
96
+ let messageCount = 0;
97
+ for (const entry of this.entriesBySeq) {
98
+ if (!isEntryCopied(entry.id))
99
+ continue;
100
+ destination.entries.set(entry.id, entry);
101
+ destination.entriesBySeq.push(entry);
102
+ if (entry.type === "message")
103
+ messageCount++;
104
+ }
105
+ destination.stats = { ...destination.stats, messageCount };
106
+ for (const stored of this.scalarValues.values()) {
107
+ const projected = projectForkCurrentStateWrite({
108
+ kind: "value",
109
+ op: "set",
110
+ seq: stored.seq,
111
+ namespace: stored.address.namespace,
112
+ key: stored.address.key,
113
+ value: stored.value,
114
+ }, plan, isEntryCopied);
115
+ if (projected !== undefined)
116
+ destination.applyValueSetOrListAppend(projected);
117
+ }
118
+ for (const stored of this.listValues.values()) {
119
+ for (const element of stored.elements) {
120
+ const projected = projectForkCurrentStateWrite({
121
+ kind: "list",
122
+ op: "append",
123
+ seq: element.seq,
124
+ namespace: stored.address.namespace,
125
+ key: stored.address.key,
126
+ value: element.value,
127
+ }, plan, isEntryCopied);
128
+ if (projected !== undefined)
129
+ destination.applyValueSetOrListAppend(projected);
130
+ }
131
+ }
132
+ destination.nextSeq = this.nextSeq;
133
+ return destination;
134
+ }
135
+ selectForkPlan(options) {
136
+ if (options.scope === "tree")
137
+ return { scope: "tree" };
138
+ const entryIds = new Set();
139
+ const plan = selectBranchFork(options, {
140
+ tip: this.getValue(branchTip(options.branch))?.value,
141
+ getParent: (entryId) => this.entries.get(entryId)?.parentId,
142
+ selectEntry: (entryId) => entryIds.add(entryId),
143
+ });
144
+ if (this.getValue(laneConfig(options.branch)) === undefined ||
145
+ this.getValue(laneState(options.branch)) === undefined) {
146
+ throw new Error(`Source branch ${JSON.stringify(options.branch)} is not a configured AgentLane`);
147
+ }
148
+ return { ...plan, entryIds };
149
+ }
150
+ applyValueSetOrListAppend(write) {
151
+ const key = physicalKey(write.namespace, write.key);
152
+ if (write.kind === "value") {
153
+ this.scalarValues.set(key, {
154
+ address: value(write.namespace, write.key),
155
+ value: write.value,
156
+ seq: write.seq,
157
+ });
158
+ return;
159
+ }
160
+ const element = { seq: write.seq, value: write.value };
161
+ const stored = this.listValues.get(key);
162
+ if (stored === undefined) {
163
+ this.listValues.set(key, {
164
+ address: list(write.namespace, write.key),
165
+ elements: [element],
166
+ });
167
+ }
168
+ else {
169
+ stored.elements.push(element);
170
+ }
171
+ }
109
172
  advanceNextSeq(nextSeq) {
110
173
  if (!Number.isSafeInteger(nextSeq) || nextSeq < 1) {
111
174
  throw new Error(`Invalid storage sequence high-water mark: ${nextSeq}`);
@@ -206,11 +269,8 @@ export class InMemoryStorageState {
206
269
  getStats() {
207
270
  return this.stats;
208
271
  }
209
- snapshotEntriesAndValues() {
210
- return {
211
- entries: [...this.entries.values()].sort((left, right) => left.seq - right.seq),
212
- scalarValues: [...this.scalarValues.values()],
213
- };
272
+ getNextSeq() {
273
+ return this.nextSeq;
214
274
  }
215
275
  }
216
276
  //# sourceMappingURL=in-memory-storage-state.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"in-memory-storage-state.js","sourceRoot":"","sources":["../../../src/harness/session/in-memory-storage-state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAA4C,oBAAoB,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAuBtH,OAAO,EAGN,IAAI,EACJ,sBAAs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AC;IAAA,CAClB;IAED,wBAAwB,GAA+D;QACtF,OAAO;YACN,OAAO,EAAE,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC;YAC/E,YAAY,EAAE,CAAC,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE,CAAC;SAC7C,CAAC;IAAA,CACF;CACD","sourcesContent":["import { addUsage, emptyUsage } from \"../utils/usage.ts\";\nimport { type CommittedWrite, type PreparedCommit, prepareStorageCommit, validateCommittedWrites } from \"./commit.ts\";\n\nexport type {\n\tCommittedEntryWrite,\n\tCommittedListAppendWrite,\n\tCommittedListDeleteWrite,\n\tCommittedUsageWrite,\n\tCommittedValueDeleteWrite,\n\tCommittedValueSetWrite,\n\tCommittedWrite,\n\tPreparedCommit,\n} from \"./commit.ts\";\n\nimport type {\n\tEntry,\n\tEntryScan,\n\tEntryStructure,\n\tSessionStats,\n\tStorageBranchScan,\n\tUsageRow,\n\tUsageScan,\n\tWrite,\n} from \"./types.ts\";\nimport {\n\ttype ListElement,\n\ttype ListReadOptions,\n\tlist,\n\tresolveListReadOptions,\n\ttype StoredValue,\n\ttype Value,\n\ttype ValueList,\n\tvalue,\n} from \"./values.ts\";\n\ninterface StoredListSnapshot {\n\taddress: ValueList<unknown>;\n\telements: ListElement<unknown>[];\n}\n\nfunction physicalKey(namespace: string, key: string): string {\n\treturn `${namespace}\\u0000${key}`;\n}\n\nfunction compareKeys(left: string, right: string): number {\n\tconst leftCodePoints = Array.from(left, (character) => character.codePointAt(0)!);\n\tconst rightCodePoints = Array.from(right, (character) => character.codePointAt(0)!);\n\tconst length = Math.min(leftCodePoints.length, rightCodePoints.length);\n\tfor (let index = 0; index < length; index++) {\n\t\tconst difference = leftCodePoints[index]! - rightCodePoints[index]!;\n\t\tif (difference !== 0) return difference;\n\t}\n\treturn leftCodePoints.length - rightCodePoints.length;\n}\n\n/**\n * Complete materialized session state for MemoryStorage and JsonlStorage.\n *\n * This is intentionally unsuitable for database backends and long-running sessions that may not fit in memory.\n * Those backends should query indexed durable state and update durable aggregates within each commit transaction.\n */\nexport class InMemoryStorageState {\n\tprivate readonly entries: Map<string, Entry>;\n\tprivate readonly entriesBySeq: Entry[];\n\tprivate readonly scalarValues: Map<string, StoredValue<unknown>>;\n\tprivate readonly listValues: Map<string, StoredListSnapshot>;\n\tprivate readonly usage: Map<string, UsageRow>;\n\tprivate stats: SessionStats;\n\tprivate nextSeq: number;\n\n\tconstructor() {\n\t\tthis.entries = new Map();\n\t\tthis.entriesBySeq = [];\n\t\tthis.scalarValues = new Map();\n\t\tthis.listValues = new Map();\n\t\tthis.usage = new Map();\n\t\tthis.stats = { messageCount: 0, usage: emptyUsage() };\n\t\tthis.nextSeq = 1;\n\t}\n\n\tprepareCommit(writes: Write[], timestamp: number): PreparedCommit {\n\t\tconst prepared = prepareStorageCommit(writes, this.nextSeq, timestamp);\n\t\tthis.validateCommitted(prepared.writes);\n\t\treturn prepared;\n\t}\n\n\tvalidateCommitted(writes: readonly CommittedWrite[]): void {\n\t\tvalidateCommittedWrites(writes, this.nextSeq, {\n\t\t\thasEntryOrUsageId: (id) => this.entries.has(id) || this.usage.has(id),\n\t\t\thasEntryId: (id) => this.entries.has(id),\n\t\t});\n\t}\n\n\t/** Apply writes already accepted by validateCommitted() and return the post-apply totals. */\n\tapplyValidated(writes: readonly CommittedWrite[]): SessionStats {\n\t\tfor (const write of writes) {\n\t\t\tswitch (write.kind) {\n\t\t\t\tcase \"entry\": {\n\t\t\t\t\tconst { kind: _kind, ...entry } = write;\n\t\t\t\t\tthis.entries.set(entry.id, entry);\n\t\t\t\t\tthis.entriesBySeq.push(entry);\n\t\t\t\t\tif (entry.type === \"message\") this.stats = { ...this.stats, messageCount: this.stats.messageCount + 1 };\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"usage\": {\n\t\t\t\t\tconst { kind: _kind, ...row } = write;\n\t\t\t\t\tthis.usage.set(row.id, row);\n\t\t\t\t\tthis.stats = { ...this.stats, usage: addUsage(this.stats.usage, row.usage) };\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"value\": {\n\t\t\t\t\tconst key = physicalKey(write.namespace, write.key);\n\t\t\t\t\tif (write.op === \"delete\") {\n\t\t\t\t\t\tthis.scalarValues.delete(key);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.scalarValues.set(key, {\n\t\t\t\t\t\t\taddress: value<unknown>(write.namespace, write.key),\n\t\t\t\t\t\t\tvalue: write.value,\n\t\t\t\t\t\t\tseq: write.seq,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"list\": {\n\t\t\t\t\tconst key = physicalKey(write.namespace, write.key);\n\t\t\t\t\tif (write.op === \"delete\") {\n\t\t\t\t\t\tthis.listValues.delete(key);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst stored = this.listValues.get(key);\n\t\t\t\t\t\tconst element = { seq: write.seq, value: write.value };\n\t\t\t\t\t\tif (stored === undefined) {\n\t\t\t\t\t\t\tthis.listValues.set(key, {\n\t\t\t\t\t\t\t\taddress: list<unknown>(write.namespace, write.key),\n\t\t\t\t\t\t\t\telements: [element],\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tstored.elements.push(element);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.nextSeq = write.seq + 1;\n\t\t}\n\t\treturn this.stats;\n\t}\n\n\tadvanceNextSeq(nextSeq: number): void {\n\t\tif (!Number.isSafeInteger(nextSeq) || nextSeq < 1) {\n\t\t\tthrow new Error(`Invalid storage sequence high-water mark: ${nextSeq}`);\n\t\t}\n\t\tthis.nextSeq = Math.max(this.nextSeq, nextSeq);\n\t}\n\n\tgetEntries(ids: readonly string[]): Map<string, Entry> {\n\t\tconst found = new Map<string, Entry>();\n\t\tfor (const id of ids) {\n\t\t\tconst entry = this.entries.get(id);\n\t\t\tif (entry !== undefined) found.set(id, entry);\n\t\t}\n\t\treturn found;\n\t}\n\n\tgetValue<T>(address: Value<T>): StoredValue<T> | undefined {\n\t\treturn this.scalarValues.get(physicalKey(address.namespace, address.key)) as StoredValue<T> | undefined;\n\t}\n\n\tscanValues<T>(prefix: Value<T>): StoredValue<T>[] {\n\t\treturn [...this.scalarValues.values()]\n\t\t\t.filter((stored) => stored.address.namespace === prefix.namespace && stored.address.key.startsWith(prefix.key))\n\t\t\t.sort((left, right) => compareKeys(left.address.key, right.address.key)) as StoredValue<T>[];\n\t}\n\n\treadList<T>(address: ValueList<T>, options?: ListReadOptions): ListElement<T>[] {\n\t\tconst resolved = resolveListReadOptions(options);\n\t\tconst elements = this.listValues.get(physicalKey(address.namespace, address.key))?.elements ?? [];\n\t\tconst filtered = elements.filter((element) => {\n\t\t\tif (resolved.cursor === undefined) return true;\n\t\t\treturn resolved.order === \"asc\" ? element.seq > resolved.cursor.seq : element.seq < resolved.cursor.seq;\n\t\t});\n\t\tconst ordered = resolved.order === \"asc\" ? filtered : [...filtered].reverse();\n\t\treturn ordered.slice(0, resolved.limit) as ListElement<T>[];\n\t}\n\n\tscanBranch(query: StorageBranchScan): Entry[] {\n\t\tconst start = this.entries.get(query.start);\n\t\tif (start === undefined) throw new Error(`Unknown branch start: ${query.start}`);\n\n\t\tconst path: Entry[] = [];\n\t\tlet entry: Entry | undefined = start;\n\t\twhile (entry !== undefined) {\n\t\t\tpath.push(entry);\n\t\t\tif (entry.parentId === null) break;\n\t\t\tentry = this.entries.get(entry.parentId);\n\t\t\tif (entry === undefined) throw new Error(\"Corrupt branch: missing parent\");\n\t\t}\n\t\tif (query.order === \"oldestFirst\") path.reverse();\n\n\t\tconst stopped: Entry[] = [];\n\t\tfor (const candidate of path) {\n\t\t\tstopped.push(candidate);\n\t\t\tif (candidate.id === query.stopAtId || candidate.type === query.stopAtType) break;\n\t\t}\n\t\tconst filtered = stopped\n\t\t\t.filter((candidate) => query.type === undefined || candidate.type === query.type)\n\t\t\t.filter((candidate) => query.customType === undefined || candidate.customType === query.customType)\n\t\t\t.filter(\n\t\t\t\t(candidate) =>\n\t\t\t\t\tquery.cursor === undefined ||\n\t\t\t\t\t(query.order === \"oldestFirst\" ? candidate.seq > query.cursor.seq : candidate.seq < query.cursor.seq),\n\t\t\t);\n\t\treturn query.limit === undefined ? filtered : filtered.slice(0, Math.max(0, query.limit));\n\t}\n\n\tscanBranchStructure(query: StorageBranchScan): EntryStructure[] {\n\t\treturn this.scanBranch(query).map((entry) => ({\n\t\t\tid: entry.id,\n\t\t\tparentId: entry.parentId,\n\t\t\tseq: entry.seq,\n\t\t\ttimestamp: entry.timestamp,\n\t\t\ttype: entry.type,\n\t\t\t...(entry.customType === undefined ? {} : { customType: entry.customType }),\n\t\t}));\n\t}\n\n\tscanEntries(query: EntryScan): Entry[] {\n\t\tconst limit = query.limit === undefined ? Number.POSITIVE_INFINITY : Math.max(0, Math.trunc(query.limit));\n\t\tconst entries: Entry[] = [];\n\t\tconst descending = query.order === \"desc\";\n\t\tlet index = descending ? this.entriesBySeq.length - 1 : 0;\n\t\twhile (index >= 0 && index < this.entriesBySeq.length && entries.length < limit) {\n\t\t\tconst entry = this.entriesBySeq[index]!;\n\t\t\tif (\n\t\t\t\t(query.type === undefined || entry.type === query.type) &&\n\t\t\t\t(query.customType === undefined || entry.customType === query.customType) &&\n\t\t\t\t(query.fromSeq === undefined || entry.seq >= query.fromSeq) &&\n\t\t\t\t(query.toSeq === undefined || entry.seq <= query.toSeq)\n\t\t\t) {\n\t\t\t\tentries.push(entry);\n\t\t\t}\n\t\t\tindex += descending ? -1 : 1;\n\t\t}\n\t\treturn entries;\n\t}\n\n\tscanUsage(query: UsageScan): UsageRow[] {\n\t\tconst rows = [...this.usage.values()]\n\t\t\t.filter((row) => query.fromSeq === undefined || row.seq >= query.fromSeq)\n\t\t\t.filter((row) => query.toSeq === undefined || row.seq <= query.toSeq)\n\t\t\t.sort((left, right) => (query.order === \"desc\" ? right.seq - left.seq : left.seq - right.seq));\n\t\treturn query.limit === undefined ? rows : rows.slice(0, Math.max(0, query.limit));\n\t}\n\n\tgetStats(): SessionStats {\n\t\treturn this.stats;\n\t}\n\n\tsnapshotEntriesAndValues(): { entries: Entry[]; scalarValues: StoredValue<unknown>[] } {\n\t\treturn {\n\t\t\tentries: [...this.entries.values()].sort((left, right) => left.seq - right.seq),\n\t\t\tscalarValues: [...this.scalarValues.values()],\n\t\t};\n\t}\n}\n"]}
1
+ {"version":3,"file":"in-memory-storage-state.js","sourceRoot":"","sources":["../../../src/harness/session/in-memory-storage-state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAKN,oBAAoB,EACpB,uBAAuB,GACvB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,4BAA4B,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAwBlF,OAAO,EACN,SAAS,EAGT,UAAU,EACV,SAAS,EACT,IAAI,EACJ,sBAAsB,EAItB,KAAK,GACL,MAAM,aAAa,CAAC;AAWrB,SAAS,WAAW,CAAC,SAAiB,EAAE,GAAW,EAAU;IAC5D,OAAO,GAAG,SAAS,SAAS,GAAG,EAAE,CAAC;AAAA,CAClC;AAED,SAAS,WAAW,CAAC,IAAY,EAAE,KAAa,EAAU;IACzD,MAAM,cAAc,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC,CAAE,CAAC,CAAC;IAClF,MAAM,eAAe,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,WAA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OAAO,IAAI,CAAC,KAAK,CAAC;IAAA,CAClB;IAED,UAAU,GAAW;QACpB,OAAO,IAAI,CAAC,OAAO,CAAC;IAAA,CACpB;CACD","sourcesContent":["import { addUsage, emptyUsage } from \"../utils/usage.ts\";\nimport {\n\ttype CommittedListAppendWrite,\n\ttype CommittedValueSetWrite,\n\ttype CommittedWrite,\n\ttype PreparedCommit,\n\tprepareStorageCommit,\n\tvalidateCommittedWrites,\n} from \"./commit.ts\";\nimport { projectForkCurrentStateWrite, selectBranchFork } from \"./fork-policy.ts\";\n\nexport type {\n\tCommittedEntryWrite,\n\tCommittedListAppendWrite,\n\tCommittedListDeleteWrite,\n\tCommittedUsageWrite,\n\tCommittedValueDeleteWrite,\n\tCommittedValueSetWrite,\n\tCommittedWrite,\n\tPreparedCommit,\n} from \"./commit.ts\";\n\nimport type {\n\tEntry,\n\tEntryScan,\n\tEntryStructure,\n\tForkOptions,\n\tSessionStats,\n\tStorageBranchScan,\n\tUsageRow,\n\tUsageScan,\n\tWrite,\n} from \"./types.ts\";\nimport {\n\tbranchTip,\n\ttype ListElement,\n\ttype ListReadOptions,\n\tlaneConfig,\n\tlaneState,\n\tlist,\n\tresolveListReadOptions,\n\ttype StoredValue,\n\ttype Value,\n\ttype ValueList,\n\tvalue,\n} from \"./values.ts\";\n\ninterface StoredListSnapshot {\n\taddress: ValueList<unknown>;\n\telements: ListElement<unknown>[];\n}\n\ntype MemoryForkPlan =\n\t| { scope: \"tree\" }\n\t| { scope: \"branch\"; branch: string; destinationTip: string | null; entryIds: Set<string> };\n\nfunction physicalKey(namespace: string, key: string): string {\n\treturn `${namespace}\\u0000${key}`;\n}\n\nfunction compareKeys(left: string, right: string): number {\n\tconst leftCodePoints = Array.from(left, (character) => character.codePointAt(0)!);\n\tconst rightCodePoints = Array.from(right, (character) => character.codePointAt(0)!);\n\tconst length = Math.min(leftCodePoints.length, rightCodePoints.length);\n\tfor (let index = 0; index < length; index++) {\n\t\tconst difference = leftCodePoints[index]! - rightCodePoints[index]!;\n\t\tif (difference !== 0) return difference;\n\t}\n\treturn leftCodePoints.length - rightCodePoints.length;\n}\n\n/**\n * Complete materialized session state for MemoryStorage and JsonlStorage.\n *\n * This is intentionally unsuitable for database backends and long-running sessions that may not fit in memory.\n * Those backends should query indexed durable state and update durable aggregates within each commit transaction.\n */\nexport class InMemoryStorageState {\n\tprivate readonly entries: Map<string, Entry>;\n\tprivate readonly entriesBySeq: Entry[];\n\tprivate readonly scalarValues: Map<string, StoredValue<unknown>>;\n\tprivate readonly listValues: Map<string, StoredListSnapshot>;\n\tprivate readonly usage: Map<string, UsageRow>;\n\tprivate stats: SessionStats;\n\tprivate nextSeq: number;\n\n\tconstructor() {\n\t\tthis.entries = new Map();\n\t\tthis.entriesBySeq = [];\n\t\tthis.scalarValues = new Map();\n\t\tthis.listValues = new Map();\n\t\tthis.usage = new Map();\n\t\tthis.stats = { messageCount: 0, usage: emptyUsage() };\n\t\tthis.nextSeq = 1;\n\t}\n\n\tprepareCommit(writes: Write[], timestamp: number): PreparedCommit {\n\t\tconst prepared = prepareStorageCommit(writes, this.nextSeq, timestamp);\n\t\tthis.validateCommitted(prepared.writes);\n\t\treturn prepared;\n\t}\n\n\tvalidateCommitted(writes: readonly CommittedWrite[]): void {\n\t\tvalidateCommittedWrites(writes, this.nextSeq, {\n\t\t\thasEntryOrUsageId: (id) => this.entries.has(id) || this.usage.has(id),\n\t\t\thasEntryId: (id) => this.entries.has(id),\n\t\t});\n\t}\n\n\t/** Apply writes already accepted by validateCommitted() and return the post-apply totals. */\n\tapplyValidated(writes: readonly CommittedWrite[]): SessionStats {\n\t\tfor (const write of writes) {\n\t\t\tswitch (write.kind) {\n\t\t\t\tcase \"entry\": {\n\t\t\t\t\tconst { kind: _kind, ...entry } = write;\n\t\t\t\t\tthis.entries.set(entry.id, entry);\n\t\t\t\t\tthis.entriesBySeq.push(entry);\n\t\t\t\t\tif (entry.type === \"message\") this.stats = { ...this.stats, messageCount: this.stats.messageCount + 1 };\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"usage\": {\n\t\t\t\t\tconst { kind: _kind, ...row } = write;\n\t\t\t\t\tthis.usage.set(row.id, row);\n\t\t\t\t\tthis.stats = { ...this.stats, usage: addUsage(this.stats.usage, row.usage) };\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"value\":\n\t\t\t\t\tif (write.op === \"delete\") this.scalarValues.delete(physicalKey(write.namespace, write.key));\n\t\t\t\t\telse this.applyValueSetOrListAppend(write);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"list\":\n\t\t\t\t\tif (write.op === \"delete\") this.listValues.delete(physicalKey(write.namespace, write.key));\n\t\t\t\t\telse this.applyValueSetOrListAppend(write);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tthis.nextSeq = write.seq + 1;\n\t\t}\n\t\treturn this.stats;\n\t}\n\n\tcreateFork(options: ForkOptions): InMemoryStorageState {\n\t\tconst plan = this.selectForkPlan(options);\n\n\t\tconst isEntryCopied = (entryId: string): boolean => {\n\t\t\tif (plan.scope === \"tree\") return true;\n\t\t\treturn plan.entryIds.has(entryId);\n\t\t};\n\t\tconst destination = new InMemoryStorageState();\n\t\tlet messageCount = 0;\n\t\tfor (const entry of this.entriesBySeq) {\n\t\t\tif (!isEntryCopied(entry.id)) continue;\n\t\t\tdestination.entries.set(entry.id, entry);\n\t\t\tdestination.entriesBySeq.push(entry);\n\t\t\tif (entry.type === \"message\") messageCount++;\n\t\t}\n\t\tdestination.stats = { ...destination.stats, messageCount };\n\n\t\tfor (const stored of this.scalarValues.values()) {\n\t\t\tconst projected = projectForkCurrentStateWrite(\n\t\t\t\t{\n\t\t\t\t\tkind: \"value\",\n\t\t\t\t\top: \"set\",\n\t\t\t\t\tseq: stored.seq,\n\t\t\t\t\tnamespace: stored.address.namespace,\n\t\t\t\t\tkey: stored.address.key,\n\t\t\t\t\tvalue: stored.value,\n\t\t\t\t},\n\t\t\t\tplan,\n\t\t\t\tisEntryCopied,\n\t\t\t);\n\t\t\tif (projected !== undefined) destination.applyValueSetOrListAppend(projected);\n\t\t}\n\n\t\tfor (const stored of this.listValues.values()) {\n\t\t\tfor (const element of stored.elements) {\n\t\t\t\tconst projected = projectForkCurrentStateWrite(\n\t\t\t\t\t{\n\t\t\t\t\t\tkind: \"list\",\n\t\t\t\t\t\top: \"append\",\n\t\t\t\t\t\tseq: element.seq,\n\t\t\t\t\t\tnamespace: stored.address.namespace,\n\t\t\t\t\t\tkey: stored.address.key,\n\t\t\t\t\t\tvalue: element.value,\n\t\t\t\t\t},\n\t\t\t\t\tplan,\n\t\t\t\t\tisEntryCopied,\n\t\t\t\t);\n\t\t\t\tif (projected !== undefined) destination.applyValueSetOrListAppend(projected);\n\t\t\t}\n\t\t}\n\t\tdestination.nextSeq = this.nextSeq;\n\t\treturn destination;\n\t}\n\n\tprivate selectForkPlan(options: ForkOptions): MemoryForkPlan {\n\t\tif (options.scope === \"tree\") return { scope: \"tree\" };\n\n\t\tconst entryIds = new Set<string>();\n\t\tconst plan = selectBranchFork(options, {\n\t\t\ttip: this.getValue(branchTip(options.branch))?.value,\n\t\t\tgetParent: (entryId) => this.entries.get(entryId)?.parentId,\n\t\t\tselectEntry: (entryId) => entryIds.add(entryId),\n\t\t});\n\t\tif (\n\t\t\tthis.getValue(laneConfig(options.branch)) === undefined ||\n\t\t\tthis.getValue(laneState(options.branch)) === undefined\n\t\t) {\n\t\t\tthrow new Error(`Source branch ${JSON.stringify(options.branch)} is not a configured AgentLane`);\n\t\t}\n\t\treturn { ...plan, entryIds };\n\t}\n\n\tprivate applyValueSetOrListAppend(write: CommittedValueSetWrite | CommittedListAppendWrite): void {\n\t\tconst key = physicalKey(write.namespace, write.key);\n\t\tif (write.kind === \"value\") {\n\t\t\tthis.scalarValues.set(key, {\n\t\t\t\taddress: value<unknown>(write.namespace, write.key),\n\t\t\t\tvalue: write.value,\n\t\t\t\tseq: write.seq,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tconst element = { seq: write.seq, value: write.value };\n\t\tconst stored = this.listValues.get(key);\n\t\tif (stored === undefined) {\n\t\t\tthis.listValues.set(key, {\n\t\t\t\taddress: list<unknown>(write.namespace, write.key),\n\t\t\t\telements: [element],\n\t\t\t});\n\t\t} else {\n\t\t\tstored.elements.push(element);\n\t\t}\n\t}\n\n\tadvanceNextSeq(nextSeq: number): void {\n\t\tif (!Number.isSafeInteger(nextSeq) || nextSeq < 1) {\n\t\t\tthrow new Error(`Invalid storage sequence high-water mark: ${nextSeq}`);\n\t\t}\n\t\tthis.nextSeq = Math.max(this.nextSeq, nextSeq);\n\t}\n\n\tgetEntries(ids: readonly string[]): Map<string, Entry> {\n\t\tconst found = new Map<string, Entry>();\n\t\tfor (const id of ids) {\n\t\t\tconst entry = this.entries.get(id);\n\t\t\tif (entry !== undefined) found.set(id, entry);\n\t\t}\n\t\treturn found;\n\t}\n\n\tgetValue<T>(address: Value<T>): StoredValue<T> | undefined {\n\t\treturn this.scalarValues.get(physicalKey(address.namespace, address.key)) as StoredValue<T> | undefined;\n\t}\n\n\tscanValues<T>(prefix: Value<T>): StoredValue<T>[] {\n\t\treturn [...this.scalarValues.values()]\n\t\t\t.filter((stored) => stored.address.namespace === prefix.namespace && stored.address.key.startsWith(prefix.key))\n\t\t\t.sort((left, right) => compareKeys(left.address.key, right.address.key)) as StoredValue<T>[];\n\t}\n\n\treadList<T>(address: ValueList<T>, options?: ListReadOptions): ListElement<T>[] {\n\t\tconst resolved = resolveListReadOptions(options);\n\t\tconst elements = this.listValues.get(physicalKey(address.namespace, address.key))?.elements ?? [];\n\t\tconst filtered = elements.filter((element) => {\n\t\t\tif (resolved.cursor === undefined) return true;\n\t\t\treturn resolved.order === \"asc\" ? element.seq > resolved.cursor.seq : element.seq < resolved.cursor.seq;\n\t\t});\n\t\tconst ordered = resolved.order === \"asc\" ? filtered : [...filtered].reverse();\n\t\treturn ordered.slice(0, resolved.limit) as ListElement<T>[];\n\t}\n\n\tscanBranch(query: StorageBranchScan): Entry[] {\n\t\tconst start = this.entries.get(query.start);\n\t\tif (start === undefined) throw new Error(`Unknown branch start: ${query.start}`);\n\n\t\tconst path: Entry[] = [];\n\t\tlet entry: Entry | undefined = start;\n\t\twhile (entry !== undefined) {\n\t\t\tpath.push(entry);\n\t\t\tif (entry.parentId === null) break;\n\t\t\tentry = this.entries.get(entry.parentId);\n\t\t\tif (entry === undefined) throw new Error(\"Corrupt branch: missing parent\");\n\t\t}\n\t\tif (query.order === \"oldestFirst\") path.reverse();\n\n\t\tconst stopped: Entry[] = [];\n\t\tfor (const candidate of path) {\n\t\t\tstopped.push(candidate);\n\t\t\tif (candidate.id === query.stopAtId || candidate.type === query.stopAtType) break;\n\t\t}\n\t\tconst filtered = stopped\n\t\t\t.filter((candidate) => query.type === undefined || candidate.type === query.type)\n\t\t\t.filter((candidate) => query.customType === undefined || candidate.customType === query.customType)\n\t\t\t.filter(\n\t\t\t\t(candidate) =>\n\t\t\t\t\tquery.cursor === undefined ||\n\t\t\t\t\t(query.order === \"oldestFirst\" ? candidate.seq > query.cursor.seq : candidate.seq < query.cursor.seq),\n\t\t\t);\n\t\treturn query.limit === undefined ? filtered : filtered.slice(0, Math.max(0, query.limit));\n\t}\n\n\tscanBranchStructure(query: StorageBranchScan): EntryStructure[] {\n\t\treturn this.scanBranch(query).map((entry) => ({\n\t\t\tid: entry.id,\n\t\t\tparentId: entry.parentId,\n\t\t\tseq: entry.seq,\n\t\t\ttimestamp: entry.timestamp,\n\t\t\ttype: entry.type,\n\t\t\t...(entry.customType === undefined ? {} : { customType: entry.customType }),\n\t\t}));\n\t}\n\n\tscanEntries(query: EntryScan): Entry[] {\n\t\tconst limit = query.limit === undefined ? Number.POSITIVE_INFINITY : Math.max(0, Math.trunc(query.limit));\n\t\tconst entries: Entry[] = [];\n\t\tconst descending = query.order === \"desc\";\n\t\tlet index = descending ? this.entriesBySeq.length - 1 : 0;\n\t\twhile (index >= 0 && index < this.entriesBySeq.length && entries.length < limit) {\n\t\t\tconst entry = this.entriesBySeq[index]!;\n\t\t\tif (\n\t\t\t\t(query.type === undefined || entry.type === query.type) &&\n\t\t\t\t(query.customType === undefined || entry.customType === query.customType) &&\n\t\t\t\t(query.fromSeq === undefined || entry.seq >= query.fromSeq) &&\n\t\t\t\t(query.toSeq === undefined || entry.seq <= query.toSeq)\n\t\t\t) {\n\t\t\t\tentries.push(entry);\n\t\t\t}\n\t\t\tindex += descending ? -1 : 1;\n\t\t}\n\t\treturn entries;\n\t}\n\n\tscanUsage(query: UsageScan): UsageRow[] {\n\t\tconst rows = [...this.usage.values()]\n\t\t\t.filter((row) => query.fromSeq === undefined || row.seq >= query.fromSeq)\n\t\t\t.filter((row) => query.toSeq === undefined || row.seq <= query.toSeq)\n\t\t\t.sort((left, right) => (query.order === \"desc\" ? right.seq - left.seq : left.seq - right.seq));\n\t\treturn query.limit === undefined ? rows : rows.slice(0, Math.max(0, query.limit));\n\t}\n\n\tgetStats(): SessionStats {\n\t\treturn this.stats;\n\t}\n\n\tgetNextSeq(): number {\n\t\treturn this.nextSeq;\n\t}\n}\n"]}