@graphrefly/ts 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/LICENSE +21 -0
  2. package/dist/adapters/index.cjs +9015 -0
  3. package/dist/adapters/index.cjs.map +1 -0
  4. package/dist/adapters/index.d.cts +678 -0
  5. package/dist/adapters/index.d.ts +678 -0
  6. package/dist/adapters/index.js +2894 -0
  7. package/dist/adapters/index.js.map +1 -0
  8. package/dist/adapters/observe-storage.cjs +260 -0
  9. package/dist/adapters/observe-storage.cjs.map +1 -0
  10. package/dist/adapters/observe-storage.d.cts +77 -0
  11. package/dist/adapters/observe-storage.d.ts +77 -0
  12. package/dist/adapters/observe-storage.js +161 -0
  13. package/dist/adapters/observe-storage.js.map +1 -0
  14. package/dist/append-log-DisvEReb.d.cts +189 -0
  15. package/dist/append-log-DzKMmjxx.d.ts +189 -0
  16. package/dist/chunk-2ILL7HQI.js +1189 -0
  17. package/dist/chunk-2ILL7HQI.js.map +1 -0
  18. package/dist/chunk-4VLAQHZI.js +330 -0
  19. package/dist/chunk-4VLAQHZI.js.map +1 -0
  20. package/dist/chunk-6PHB5CJS.js +229 -0
  21. package/dist/chunk-6PHB5CJS.js.map +1 -0
  22. package/dist/chunk-COHO25CZ.js +2449 -0
  23. package/dist/chunk-COHO25CZ.js.map +1 -0
  24. package/dist/chunk-D6BG7U6A.js +161 -0
  25. package/dist/chunk-D6BG7U6A.js.map +1 -0
  26. package/dist/chunk-DJC4CHLQ.js +818 -0
  27. package/dist/chunk-DJC4CHLQ.js.map +1 -0
  28. package/dist/chunk-DK554R7P.js +67 -0
  29. package/dist/chunk-DK554R7P.js.map +1 -0
  30. package/dist/chunk-DKP56CSW.js +322 -0
  31. package/dist/chunk-DKP56CSW.js.map +1 -0
  32. package/dist/chunk-G4M3NHRJ.js +688 -0
  33. package/dist/chunk-G4M3NHRJ.js.map +1 -0
  34. package/dist/chunk-GAJW5I5P.js +1 -0
  35. package/dist/chunk-GAJW5I5P.js.map +1 -0
  36. package/dist/chunk-GDL26N2T.js +282 -0
  37. package/dist/chunk-GDL26N2T.js.map +1 -0
  38. package/dist/chunk-GTPCOEOZ.js +741 -0
  39. package/dist/chunk-GTPCOEOZ.js.map +1 -0
  40. package/dist/chunk-H2HTHFVN.js +1 -0
  41. package/dist/chunk-H2HTHFVN.js.map +1 -0
  42. package/dist/chunk-HDRL4VQQ.js +218 -0
  43. package/dist/chunk-HDRL4VQQ.js.map +1 -0
  44. package/dist/chunk-I3IHOHCJ.js +2267 -0
  45. package/dist/chunk-I3IHOHCJ.js.map +1 -0
  46. package/dist/chunk-JIMUDQN3.js +965 -0
  47. package/dist/chunk-JIMUDQN3.js.map +1 -0
  48. package/dist/chunk-JR4IKCR2.js +462 -0
  49. package/dist/chunk-JR4IKCR2.js.map +1 -0
  50. package/dist/chunk-K3FXTC3I.js +165 -0
  51. package/dist/chunk-K3FXTC3I.js.map +1 -0
  52. package/dist/chunk-OOEN33FB.js +65 -0
  53. package/dist/chunk-OOEN33FB.js.map +1 -0
  54. package/dist/chunk-PKVBHGBM.js +554 -0
  55. package/dist/chunk-PKVBHGBM.js.map +1 -0
  56. package/dist/chunk-RIIOUTGM.js +1857 -0
  57. package/dist/chunk-RIIOUTGM.js.map +1 -0
  58. package/dist/chunk-SCRFRCGR.js +33 -0
  59. package/dist/chunk-SCRFRCGR.js.map +1 -0
  60. package/dist/chunk-SWTLEQL6.js +53 -0
  61. package/dist/chunk-SWTLEQL6.js.map +1 -0
  62. package/dist/chunk-SZAETNNA.js +1 -0
  63. package/dist/chunk-SZAETNNA.js.map +1 -0
  64. package/dist/chunk-TEW47IVR.js +49 -0
  65. package/dist/chunk-TEW47IVR.js.map +1 -0
  66. package/dist/chunk-Y3ZLRGHC.js +1482 -0
  67. package/dist/chunk-Y3ZLRGHC.js.map +1 -0
  68. package/dist/chunk-Z2ANQ6JW.js +149 -0
  69. package/dist/chunk-Z2ANQ6JW.js.map +1 -0
  70. package/dist/codec-BB7p8fJc.d.cts +38 -0
  71. package/dist/codec-BB7p8fJc.d.ts +38 -0
  72. package/dist/composition/index.cjs +2505 -0
  73. package/dist/composition/index.cjs.map +1 -0
  74. package/dist/composition/index.d.cts +95 -0
  75. package/dist/composition/index.d.ts +95 -0
  76. package/dist/composition/index.js +19 -0
  77. package/dist/composition/index.js.map +1 -0
  78. package/dist/core/index.cjs +2475 -0
  79. package/dist/core/index.cjs.map +1 -0
  80. package/dist/core/index.d.cts +25 -0
  81. package/dist/core/index.d.ts +25 -0
  82. package/dist/core/index.js +74 -0
  83. package/dist/core/index.js.map +1 -0
  84. package/dist/cqrs/index.cjs +595 -0
  85. package/dist/cqrs/index.cjs.map +1 -0
  86. package/dist/cqrs/index.d.cts +200 -0
  87. package/dist/cqrs/index.d.ts +200 -0
  88. package/dist/cqrs/index.js +557 -0
  89. package/dist/cqrs/index.js.map +1 -0
  90. package/dist/data-structures/index.cjs +4277 -0
  91. package/dist/data-structures/index.cjs.map +1 -0
  92. package/dist/data-structures/index.d.cts +22 -0
  93. package/dist/data-structures/index.d.ts +22 -0
  94. package/dist/data-structures/index.js +31 -0
  95. package/dist/data-structures/index.js.map +1 -0
  96. package/dist/describe-BZb7AS2y.d.ts +57 -0
  97. package/dist/describe-Ciu8SUnN.d.cts +57 -0
  98. package/dist/graph/index.cjs +7832 -0
  99. package/dist/graph/index.cjs.map +1 -0
  100. package/dist/graph/index.d.cts +251 -0
  101. package/dist/graph/index.d.ts +251 -0
  102. package/dist/graph/index.js +131 -0
  103. package/dist/graph/index.js.map +1 -0
  104. package/dist/graph-DfdF9zy4.d.ts +666 -0
  105. package/dist/graph-s23RbbFO.d.cts +666 -0
  106. package/dist/index-CAEmLCYF.d.cts +166 -0
  107. package/dist/index-SnzZu3x7.d.ts +166 -0
  108. package/dist/index.cjs +15409 -0
  109. package/dist/index.cjs.map +1 -0
  110. package/dist/index.d.cts +23 -0
  111. package/dist/index.d.ts +23 -0
  112. package/dist/index.js +582 -0
  113. package/dist/index.js.map +1 -0
  114. package/dist/messages-BZqrGGm1.d.cts +55 -0
  115. package/dist/messages-BZqrGGm1.d.ts +55 -0
  116. package/dist/messaging/index.cjs +818 -0
  117. package/dist/messaging/index.cjs.map +1 -0
  118. package/dist/messaging/index.d.cts +235 -0
  119. package/dist/messaging/index.d.ts +235 -0
  120. package/dist/messaging/index.js +767 -0
  121. package/dist/messaging/index.js.map +1 -0
  122. package/dist/observe-event-log-0SVsx7JG.d.cts +88 -0
  123. package/dist/observe-event-log-Dnm76owp.d.ts +88 -0
  124. package/dist/operators/index.cjs +3774 -0
  125. package/dist/operators/index.cjs.map +1 -0
  126. package/dist/operators/index.d.cts +308 -0
  127. package/dist/operators/index.d.ts +308 -0
  128. package/dist/operators/index.js +112 -0
  129. package/dist/operators/index.js.map +1 -0
  130. package/dist/orchestration/index.cjs +3541 -0
  131. package/dist/orchestration/index.cjs.map +1 -0
  132. package/dist/orchestration/index.d.cts +302 -0
  133. package/dist/orchestration/index.d.ts +302 -0
  134. package/dist/orchestration/index.js +1004 -0
  135. package/dist/orchestration/index.js.map +1 -0
  136. package/dist/patterns/index.cjs +1045 -0
  137. package/dist/patterns/index.cjs.map +1 -0
  138. package/dist/patterns/index.d.cts +39 -0
  139. package/dist/patterns/index.d.ts +39 -0
  140. package/dist/patterns/index.js +33 -0
  141. package/dist/patterns/index.js.map +1 -0
  142. package/dist/reactive-collection-BxBqtIOE.d.cts +344 -0
  143. package/dist/reactive-collection-Cb1II1Fi.d.ts +344 -0
  144. package/dist/reactive-collection-storage-BNiEc-Gd.d.ts +217 -0
  145. package/dist/reactive-collection-storage-D-KmjE0J.d.cts +217 -0
  146. package/dist/reactive-map-BcB4KsQR.d.ts +256 -0
  147. package/dist/reactive-map-D-g3dv8I.d.cts +256 -0
  148. package/dist/read-through-B1CYPfq_.d.cts +82 -0
  149. package/dist/read-through-DwyJhGs1.d.ts +82 -0
  150. package/dist/render/index.cjs +250 -0
  151. package/dist/render/index.cjs.map +1 -0
  152. package/dist/render/index.d.cts +58 -0
  153. package/dist/render/index.d.ts +58 -0
  154. package/dist/render/index.js +20 -0
  155. package/dist/render/index.js.map +1 -0
  156. package/dist/resilience-Dig3Q7n0.d.cts +45 -0
  157. package/dist/resilience-Dig3Q7n0.d.ts +45 -0
  158. package/dist/semantic-memory-graph-BYoIlP35.d.cts +356 -0
  159. package/dist/semantic-memory-graph-CxyXLms3.d.ts +356 -0
  160. package/dist/solutions/index.cjs +3249 -0
  161. package/dist/solutions/index.cjs.map +1 -0
  162. package/dist/solutions/index.d.cts +520 -0
  163. package/dist/solutions/index.d.ts +520 -0
  164. package/dist/solutions/index.js +31 -0
  165. package/dist/solutions/index.js.map +1 -0
  166. package/dist/sources/browser.cjs +3095 -0
  167. package/dist/sources/browser.cjs.map +1 -0
  168. package/dist/sources/browser.d.cts +39 -0
  169. package/dist/sources/browser.d.ts +39 -0
  170. package/dist/sources/browser.js +137 -0
  171. package/dist/sources/browser.js.map +1 -0
  172. package/dist/sources/index.cjs +3021 -0
  173. package/dist/sources/index.cjs.map +1 -0
  174. package/dist/sources/index.d.cts +7 -0
  175. package/dist/sources/index.d.ts +7 -0
  176. package/dist/sources/index.js +63 -0
  177. package/dist/sources/index.js.map +1 -0
  178. package/dist/sources/node.cjs +675 -0
  179. package/dist/sources/node.cjs.map +1 -0
  180. package/dist/sources/node.d.cts +109 -0
  181. package/dist/sources/node.d.ts +109 -0
  182. package/dist/sources/node.js +639 -0
  183. package/dist/sources/node.js.map +1 -0
  184. package/dist/storage/browser.cjs +777 -0
  185. package/dist/storage/browser.cjs.map +1 -0
  186. package/dist/storage/browser.d.cts +40 -0
  187. package/dist/storage/browser.d.ts +40 -0
  188. package/dist/storage/browser.js +275 -0
  189. package/dist/storage/browser.js.map +1 -0
  190. package/dist/storage/index.cjs +1989 -0
  191. package/dist/storage/index.cjs.map +1 -0
  192. package/dist/storage/index.d.cts +92 -0
  193. package/dist/storage/index.d.ts +92 -0
  194. package/dist/storage/index.js +161 -0
  195. package/dist/storage/index.js.map +1 -0
  196. package/dist/storage/node.cjs +898 -0
  197. package/dist/storage/node.cjs.map +1 -0
  198. package/dist/storage/node.d.cts +66 -0
  199. package/dist/storage/node.d.ts +66 -0
  200. package/dist/storage/node.js +402 -0
  201. package/dist/storage/node.js.map +1 -0
  202. package/dist/testing/index.cjs +95 -0
  203. package/dist/testing/index.cjs.map +1 -0
  204. package/dist/testing/index.d.cts +20 -0
  205. package/dist/testing/index.d.ts +20 -0
  206. package/dist/testing/index.js +8 -0
  207. package/dist/testing/index.js.map +1 -0
  208. package/dist/types-bNMSWKqF.d.cts +732 -0
  209. package/dist/types-h12mNYbq.d.ts +732 -0
  210. package/package.json +250 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/graph/cascading-cache.ts","../src/graph/diagnostics.ts","../src/graph/inspect.ts","../src/graph/restore.ts","../src/graph/worker.ts"],"sourcesContent":["import { type Ctx, depBatch, depLatest } from \"../ctx/types.js\";\nimport type { Node } from \"../node/node.js\";\nimport { errorPayload } from \"../protocol/messages.js\";\nimport { hasKvVersioned, type KvGeneration, type KvStorageTier } from \"../storage/kv.js\";\nimport {\n\ttype ReadThroughLookupFact,\n\ttype ReadThroughLookupTier,\n\ttype TieredReadThroughResult,\n\ttieredReadThrough,\n} from \"../storage/read-through.js\";\nimport type { Graph, SugarOpts } from \"./graph.js\";\n\n/** Dynamic read-through policy for {@link reactiveCascadingCache}. */\nexport interface CascadingCachePolicy {\n\treadonly promoteTo?: readonly number[] | false;\n}\n\nexport type CascadingCacheStatus<K> =\n\t| { readonly kind: \"idle\" }\n\t| { readonly kind: \"loading\"; readonly key: K; readonly requestSeq: number }\n\t| {\n\t\t\treadonly kind: \"hit\";\n\t\t\treadonly key: K;\n\t\t\treadonly requestSeq: number;\n\t\t\treadonly tier?: ReadThroughLookupTier;\n\t }\n\t| { readonly kind: \"miss\"; readonly key: K; readonly requestSeq: number }\n\t| {\n\t\t\treadonly kind: \"error\";\n\t\t\treadonly key: K;\n\t\t\treadonly requestSeq: number;\n\t\t\treadonly error: unknown;\n\t };\n\nexport type CascadingCacheEvent<K, V> =\n\t| { readonly kind: \"request\"; readonly key: K; readonly requestSeq: number }\n\t| { readonly kind: \"invalidate\"; readonly key: K; readonly requestSeq: number }\n\t| {\n\t\t\treadonly kind: \"lookup\";\n\t\t\treadonly key: K;\n\t\t\treadonly requestSeq: number;\n\t\t\treadonly outcome: \"hit\" | \"miss\" | \"error\";\n\t\t\treadonly tier: ReadThroughLookupTier;\n\t\t\treadonly value?: V;\n\t\t\treadonly error?: unknown;\n\t }\n\t| {\n\t\t\treadonly kind: \"promotion\";\n\t\t\treadonly key: K;\n\t\t\treadonly requestSeq: number;\n\t\t\treadonly tier: ReadThroughLookupTier;\n\t\t\treadonly ok: boolean;\n\t\t\treadonly error?: unknown;\n\t }\n\t| {\n\t\t\treadonly kind: \"fill\";\n\t\t\treadonly key: K;\n\t\t\treadonly requestSeq: number;\n\t\t\treadonly status: \"hit\" | \"miss\" | \"error\";\n\t\t\treadonly value?: V;\n\t\t\treadonly tier?: ReadThroughLookupTier;\n\t\t\treadonly error?: unknown;\n\t }\n\t| {\n\t\t\treadonly kind: \"error\";\n\t\t\treadonly key: K;\n\t\t\treadonly requestSeq: number;\n\t\t\treadonly stage: \"lookup\" | \"promotion\";\n\t\t\treadonly tier?: ReadThroughLookupTier;\n\t\t\treadonly error: unknown;\n\t };\n\nexport interface ReactiveCascadingCacheOptions<K extends string, V> {\n\treadonly graph: Graph;\n\treadonly request: Node<K>;\n\treadonly policy?: Node<CascadingCachePolicy>;\n\treadonly invalidate?: Node<K>;\n\treadonly tiers: readonly KvStorageTier<V>[];\n\treadonly load?: (key: K) => Promise<V | undefined> | V | undefined;\n\treadonly tierNames?: readonly string[];\n\t/**\n\t * Storage promotion is explicit for the graph-layer factory. `requestSeq` guards visible graph\n\t * value/status updates; without a generation/CAS storage contract, passive tier writes are\n\t * best-effort and cannot be made stale-proof once an async `set` has started.\n\t *\n\t * @default false\n\t */\n\treadonly promoteTo?: readonly number[] | false;\n\treadonly name?: string;\n\treadonly meta?: Record<string, unknown>;\n}\n\nexport interface ReactiveCascadingCache<K, V> {\n\treadonly value: Node<V | undefined>;\n\treadonly status: Node<CascadingCacheStatus<K>>;\n\treadonly events: Node<CascadingCacheEvent<K, V>>;\n}\n\ninterface DriverState<K> {\n\tseq: number;\n\tactive: boolean;\n\tdropBeforeSeq: number;\n\tlatestKey?: K;\n}\n\ninterface SeqState {\n\tseq: number;\n}\n\n/**\n * Free-standing graph-layer cascading cache factory (D104/D105/D107).\n *\n * Passive tiers stay in `tieredReadThrough`; this factory wraps lookup work at an async pool\n * boundary and exposes every request, invalidation, lookup, promotion, fill, status, and value\n * change through declared graph nodes. `requestSeq` is the stale-fill guard for visible graph\n * nodes: older async fills may still be observable as events, but downstream value/status nodes\n * ignore them. Storage promotion defaults to `false` here because passive tier writes have no\n * generation/CAS contract; callers may opt in with `promoteTo` when best-effort promotion is\n * acceptable.\n */\nexport function reactiveCascadingCache<K extends string, V>(\n\topts: ReactiveCascadingCacheOptions<K, V>,\n): ReactiveCascadingCache<K, V> {\n\tconst {\n\t\tgraph: g,\n\t\trequest,\n\t\tpolicy,\n\t\tinvalidate,\n\t\ttiers,\n\t\ttierNames,\n\t\tpromoteTo,\n\t\tload,\n\t\tname,\n\t\tmeta,\n\t} = opts;\n\tconst eventDeps: Node<unknown>[] = [request];\n\tconst policyIndex = policy === undefined ? -1 : eventDeps.push(policy) - 1;\n\tconst invalidateIndex = invalidate === undefined ? -1 : eventDeps.push(invalidate) - 1;\n\tconst baseName = name ?? \"reactiveCascadingCache\";\n\tconst eventOpts: SugarOpts<CascadingCacheEvent<K, V>> = {\n\t\tname: `${baseName}.events`,\n\t\tmeta,\n\t\tpartial: true,\n\t\tpool: \"async\",\n\t};\n\tconst events = g.node<CascadingCacheEvent<K, V>>(\n\t\teventDeps,\n\t\t(ctx) => {\n\t\t\tconst st = ctx.state.get<DriverState<K>>() ?? {\n\t\t\t\tseq: 0,\n\t\t\t\tactive: true,\n\t\t\t\tdropBeforeSeq: 0,\n\t\t\t};\n\t\t\tst.active = true;\n\t\t\tctx.onDeactivation(() => {\n\t\t\t\tst.active = false;\n\t\t\t\tst.seq += 1;\n\t\t\t\tst.dropBeforeSeq = st.seq;\n\t\t\t});\n\t\t\tconst requestBatch = depBatch(ctx, 0) as readonly K[] | null;\n\t\t\tconst invalidateBatch =\n\t\t\t\tinvalidateIndex === -1 ? null : (depBatch(ctx, invalidateIndex) as readonly K[] | null);\n\t\t\tconst policyBatch =\n\t\t\t\tpolicyIndex === -1\n\t\t\t\t\t? null\n\t\t\t\t\t: (depBatch(ctx, policyIndex) as readonly CascadingCachePolicy[] | null);\n\t\t\tconst currentPolicy =\n\t\t\t\tpolicyIndex === -1\n\t\t\t\t\t? undefined\n\t\t\t\t\t: (depLatest(ctx, policyIndex) as CascadingCachePolicy | undefined);\n\n\t\t\tif (requestBatch !== null) {\n\t\t\t\tfor (const key of requestBatch) {\n\t\t\t\t\tstartLookup(ctx, st, {\n\t\t\t\t\t\tkind: \"request\",\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\ttiers,\n\t\t\t\t\t\ttierNames,\n\t\t\t\t\t\tload,\n\t\t\t\t\t\tpromoteTo: currentPolicy?.promoteTo ?? promoteTo ?? false,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (invalidateBatch !== null) {\n\t\t\t\tfor (const key of invalidateBatch) {\n\t\t\t\t\tstartLookup(ctx, st, {\n\t\t\t\t\t\tkind: \"invalidate\",\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\ttiers,\n\t\t\t\t\t\ttierNames,\n\t\t\t\t\t\tload,\n\t\t\t\t\t\tpromoteTo: currentPolicy?.promoteTo ?? promoteTo ?? false,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (requestBatch === null && invalidateBatch === null && policyBatch !== null) {\n\t\t\t\tconst key = st.latestKey;\n\t\t\t\tif (key !== undefined) {\n\t\t\t\t\tstartLookup(ctx, st, {\n\t\t\t\t\t\tkind: \"request\",\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\ttiers,\n\t\t\t\t\t\ttierNames,\n\t\t\t\t\t\tload,\n\t\t\t\t\t\tpromoteTo: currentPolicy?.promoteTo ?? promoteTo ?? false,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tctx.state.set(st);\n\t\t},\n\t\teventOpts,\n\t);\n\n\tconst status = g.node<CascadingCacheStatus<K>>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tconst st = ctx.state.get<SeqState>() ?? { seq: 0 };\n\t\t\tconst batch = depBatch(ctx, 0) as readonly CascadingCacheEvent<K, V>[] | null;\n\t\t\tif (batch === null) return;\n\t\t\tfor (const event of batch) {\n\t\t\t\tif (event.kind === \"request\" || event.kind === \"invalidate\") {\n\t\t\t\t\tst.seq = event.requestSeq;\n\t\t\t\t\tctx.down([[\"DATA\", { kind: \"loading\", key: event.key, requestSeq: event.requestSeq }]]);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (event.requestSeq !== st.seq) continue;\n\t\t\t\tif (event.kind === \"fill\") {\n\t\t\t\t\tif (event.status === \"hit\") {\n\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tkind: \"hit\",\n\t\t\t\t\t\t\t\t\tkey: event.key,\n\t\t\t\t\t\t\t\t\trequestSeq: event.requestSeq,\n\t\t\t\t\t\t\t\t\ttier: event.tier,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t]);\n\t\t\t\t\t} else if (event.status === \"miss\") {\n\t\t\t\t\t\tctx.down([[\"DATA\", { kind: \"miss\", key: event.key, requestSeq: event.requestSeq }]]);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tkind: \"error\",\n\t\t\t\t\t\t\t\t\tkey: event.key,\n\t\t\t\t\t\t\t\t\trequestSeq: event.requestSeq,\n\t\t\t\t\t\t\t\t\terror: event.error,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t]);\n\t\t\t\t\t}\n\t\t\t\t} else if (event.kind === \"error\") {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"error\",\n\t\t\t\t\t\t\t\tkey: event.key,\n\t\t\t\t\t\t\t\trequestSeq: event.requestSeq,\n\t\t\t\t\t\t\t\terror: event.error,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.state.set(st);\n\t\t},\n\t\t{\n\t\t\tname: `${baseName}.status`,\n\t\t\tinitial: { kind: \"idle\" },\n\t\t\tmeta,\n\t\t\tpartial: true,\n\t\t},\n\t);\n\n\tconst value = g.node<V | undefined>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tconst st = ctx.state.get<SeqState>() ?? { seq: 0 };\n\t\t\tconst batch = depBatch(ctx, 0) as readonly CascadingCacheEvent<K, V>[] | null;\n\t\t\tif (batch === null) return;\n\t\t\tfor (const event of batch) {\n\t\t\t\tif (event.kind === \"request\") {\n\t\t\t\t\tst.seq = event.requestSeq;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (event.kind === \"invalidate\") {\n\t\t\t\t\tst.seq = event.requestSeq;\n\t\t\t\t\tctx.down([[\"INVALIDATE\"]]);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (event.kind !== \"fill\" || event.requestSeq !== st.seq) continue;\n\t\t\t\tif (event.status === \"hit\" && event.value !== undefined) {\n\t\t\t\t\tctx.down([[\"DATA\", event.value]]);\n\t\t\t\t} else {\n\t\t\t\t\tctx.down([[\"INVALIDATE\"]]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.state.set(st);\n\t\t},\n\t\t{\n\t\t\tname: `${baseName}.value`,\n\t\t\tmeta,\n\t\t\tpartial: true,\n\t\t},\n\t);\n\n\treturn { value, status, events };\n}\n\nfunction startLookup<K extends string, V>(\n\tctx: Ctx,\n\tst: DriverState<K>,\n\topts: {\n\t\treadonly kind: \"request\" | \"invalidate\";\n\t\treadonly key: K;\n\t\treadonly tiers: readonly KvStorageTier<V>[];\n\t\treadonly tierNames?: readonly string[];\n\t\treadonly load?: (key: K) => Promise<V | undefined> | V | undefined;\n\t\treadonly promoteTo?: readonly number[] | false;\n\t},\n): void {\n\tconst requestSeq = st.seq + 1;\n\tst.seq = requestSeq;\n\tst.latestKey = opts.key;\n\tctx.down([[\"DATA\", { kind: opts.kind, key: opts.key, requestSeq }]]);\n\ttieredReadThrough<V>({\n\t\tkey: opts.key,\n\t\ttiers: opts.tiers,\n\t\ttierNames: opts.tierNames,\n\t\tload: opts.load === undefined ? undefined : (key) => opts.load?.(key as K),\n\t\tpromoteTo: false,\n\t}).then(\n\t\t(result) => {\n\t\t\tpromoteFresh(ctx, st, requestSeq, {\n\t\t\t\tkey: opts.key,\n\t\t\t\ttiers: opts.tiers,\n\t\t\t\ttierNames: opts.tierNames,\n\t\t\t\tpromoteTo: opts.promoteTo,\n\t\t\t\tresult,\n\t\t\t});\n\t\t},\n\t\t(error) => {\n\t\t\tif (!isLiveRequest(st, requestSeq)) return;\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\t{\n\t\t\t\t\t\tkind: \"error\",\n\t\t\t\t\t\tkey: opts.key,\n\t\t\t\t\t\trequestSeq,\n\t\t\t\t\t\tstage: \"lookup\",\n\t\t\t\t\t\terror: errorPayload(error),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t);\n}\n\nfunction promoteFresh<K, V>(\n\tctx: Ctx,\n\tst: DriverState<K>,\n\trequestSeq: number,\n\topts: {\n\t\treadonly key: K;\n\t\treadonly tiers: readonly KvStorageTier<V>[];\n\t\treadonly tierNames?: readonly string[];\n\t\treadonly promoteTo?: readonly number[] | false;\n\t\treadonly result: TieredReadThroughResult<V>;\n\t},\n\tpromotions: Array<{ tier: ReadThroughLookupTier; ok: boolean; error?: unknown }> = [],\n\toffset = 0,\n): void {\n\tif (!isLiveRequest(st, requestSeq)) return;\n\tconst { result } = opts;\n\tconst sourceIndex = result.hitTier?.index === -1 ? opts.tiers.length : result.hitTier?.index;\n\tconst targets =\n\t\tresult.value === undefined || sourceIndex === undefined\n\t\t\t? []\n\t\t\t: buildPromotionTargets(opts.tiers.length, sourceIndex, opts.promoteTo);\n\tif (st.seq !== requestSeq || offset >= targets.length) {\n\t\tconst messages = eventsFromResult(opts.key, requestSeq, result, promotions);\n\t\tif (messages.length > 0) ctx.down(messages);\n\t\treturn;\n\t}\n\tconst index = targets[offset] as number;\n\tconst tier = { index, name: opts.tierNames?.[index] };\n\ttry {\n\t\tconst target = opts.tiers[index]!;\n\t\tconst generation = generationForTier(result.facts, index);\n\t\tconst write =\n\t\t\thasKvVersioned(target) && generation !== undefined\n\t\t\t\t? target.setIfMatch(opts.key as string, result.value as V, generation)\n\t\t\t\t: target.set(opts.key as string, result.value as V).then(() => true);\n\t\twrite.then(\n\t\t\t(ok) => {\n\t\t\t\tpromotions.push({ tier, ok });\n\t\t\t\tpromoteFresh(ctx, st, requestSeq, opts, promotions, offset + 1);\n\t\t\t},\n\t\t\t(error) => {\n\t\t\t\tpromotions.push({ tier, ok: false, error });\n\t\t\t\tpromoteFresh(ctx, st, requestSeq, opts, promotions, offset + 1);\n\t\t\t},\n\t\t);\n\t} catch (error) {\n\t\tpromotions.push({ tier, ok: false, error });\n\t\tpromoteFresh(ctx, st, requestSeq, opts, promotions, offset + 1);\n\t}\n}\n\nfunction generationForTier<V>(\n\tfacts: readonly ReadThroughLookupFact<V>[],\n\tindex: number,\n): KvGeneration | undefined {\n\treturn facts.find((fact) => fact.tier.index === index)?.generation;\n}\n\nfunction isLiveRequest<K>(st: DriverState<K>, requestSeq: number): boolean {\n\treturn st.active && requestSeq >= st.dropBeforeSeq;\n}\n\nfunction buildPromotionTargets(\n\ttierCount: number,\n\thitIndex: number,\n\tpromoteTo?: readonly number[] | false,\n): number[] {\n\tif (promoteTo === false || tierCount <= 0) return [];\n\tconst maxPromote = Math.max(0, Math.min(hitIndex, tierCount));\n\tif (promoteTo === undefined) return [...Array(maxPromote).keys()];\n\tconst normalized: number[] = [];\n\tconst seen = new Set<number>();\n\tfor (const index of promoteTo) {\n\t\tif (!Number.isSafeInteger(index) || index < 0 || index >= tierCount || index >= maxPromote) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!seen.has(index)) {\n\t\t\tseen.add(index);\n\t\t\tnormalized.push(index);\n\t\t}\n\t}\n\treturn normalized;\n}\n\nfunction eventsFromResult<K, V>(\n\tkey: K,\n\trequestSeq: number,\n\tresult: TieredReadThroughResult<V>,\n\tpromotions = result.promotions,\n): Array<[\"DATA\", CascadingCacheEvent<K, V>]> {\n\tconst out: Array<[\"DATA\", CascadingCacheEvent<K, V>]> = [];\n\tlet firstError: unknown;\n\tfor (const fact of result.facts) {\n\t\tconst lookupEvent: CascadingCacheEvent<K, V> = {\n\t\t\tkind: \"lookup\",\n\t\t\tkey,\n\t\t\trequestSeq,\n\t\t\toutcome: fact.kind,\n\t\t\ttier: fact.tier,\n\t\t\tvalue: fact.value,\n\t\t\terror: fact.error,\n\t\t};\n\t\tout.push([\"DATA\", lookupEvent]);\n\t\tif (fact.kind === \"error\") {\n\t\t\tfirstError ??= fact.error;\n\t\t\tout.push([\n\t\t\t\t\"DATA\",\n\t\t\t\t{\n\t\t\t\t\tkind: \"error\",\n\t\t\t\t\tkey,\n\t\t\t\t\trequestSeq,\n\t\t\t\t\tstage: \"lookup\",\n\t\t\t\t\ttier: fact.tier,\n\t\t\t\t\terror: fact.error,\n\t\t\t\t},\n\t\t\t]);\n\t\t}\n\t}\n\tfor (const promotion of promotions) {\n\t\tout.push([\n\t\t\t\"DATA\",\n\t\t\t{\n\t\t\t\tkind: \"promotion\",\n\t\t\t\tkey,\n\t\t\t\trequestSeq,\n\t\t\t\ttier: promotion.tier,\n\t\t\t\tok: promotion.ok,\n\t\t\t\terror: promotion.error,\n\t\t\t},\n\t\t]);\n\t\tif (!promotion.ok) {\n\t\t\tfirstError ??= promotion.error;\n\t\t\tif (promotion.error !== undefined) {\n\t\t\t\tout.push([\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\t{\n\t\t\t\t\t\tkind: \"error\",\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\trequestSeq,\n\t\t\t\t\t\tstage: \"promotion\",\n\t\t\t\t\t\ttier: promotion.tier,\n\t\t\t\t\t\terror: promotion.error,\n\t\t\t\t\t},\n\t\t\t\t]);\n\t\t\t}\n\t\t}\n\t}\n\tout.push([\n\t\t\"DATA\",\n\t\t{\n\t\t\tkind: \"fill\",\n\t\t\tkey,\n\t\t\trequestSeq,\n\t\t\tstatus: result.status,\n\t\t\tvalue: result.value,\n\t\t\ttier: result.hitTier,\n\t\t\terror: firstError,\n\t\t},\n\t]);\n\treturn out;\n}\n","/**\n * Pure graph diagnostics over {@link DescribeSnapshot} (D39/R-describe).\n *\n * These helpers re-derive the useful frozen pure-ts inspection utilities without restoring\n * graph methods, path facades, actors, soft edges, or storage coupling. They operate only on the\n * public JSON-serializable describe shape; the live topology truth remains R-edges-derived.\n */\n\nimport type { DescribeNode, DescribeSnapshot } from \"./describe.js\";\n\nexport type ReachableDirection = \"upstream\" | \"downstream\";\n\nexport interface ReachableOptions {\n\t/** Maximum hop distance to walk. Omit for unbounded. */\n\tmaxDepth?: number;\n\t/** Walk both upstream and downstream, ignoring `direction`. */\n\tboth?: boolean;\n\t/** Return depths/truncation metadata instead of only sorted paths. */\n\twithDetail?: boolean;\n}\n\nexport interface ReachableResult {\n\t/** Reachable node ids, excluding the start id, sorted deterministically. */\n\tpaths: readonly string[];\n\t/** Hop depth by reachable node id. */\n\tdepths: Readonly<Record<string, number>>;\n\t/** True when `maxDepth` cut off at least one still-expandable frontier node. */\n\ttruncated: boolean;\n}\n\nexport type ExplainPathReason =\n\t| \"ok\"\n\t| \"no-such-from\"\n\t| \"no-such-to\"\n\t| \"no-path\"\n\t| \"max-depth-exceeded\";\n\nexport interface ExplainPathOptions {\n\t/** Maximum hop distance to search. Omit for unbounded. */\n\tmaxDepth?: number;\n\t/** When `from === to`, search for a non-trivial cycle before returning the trivial step. */\n\tfindCycle?: boolean;\n}\n\nexport interface CausalStep {\n\t/** Mount-aware describe node id. */\n\tid: string;\n\t/** Operator/verb factory name from describe. */\n\tfactory: string;\n\t/** Status as of the source snapshot. */\n\tstatus: DescribeNode[\"status\"];\n\t/** Cached value when present; absence still means SENTINEL. */\n\tvalue?: unknown;\n\t/** Hop distance from the `from` node. */\n\thop: number;\n\t/** First dep slot in the next step that points at this step, when the edge is dep-derived. */\n\tdepIndex?: number;\n\t/** All matching dep slots when the next step depends on this step more than once. */\n\tdepIndices?: readonly number[];\n}\n\nexport interface CausalChain {\n\tfrom: string;\n\tto: string;\n\tfound: boolean;\n\treason: ExplainPathReason;\n\tsteps: readonly CausalStep[];\n\ttext: string;\n\ttoJSON(): {\n\t\tfrom: string;\n\t\tto: string;\n\t\tfound: boolean;\n\t\treason: ExplainPathReason;\n\t\tsteps: readonly CausalStep[];\n\t};\n}\n\nexport interface IslandReport {\n\t/** Node id from the flattened snapshot. */\n\tid: string;\n\t/** Factory/kind for quick triage. */\n\tfactory: string;\n}\n\nexport interface ValidateNoIslandsResult {\n\tok: boolean;\n\t/** Nodes with zero deps and zero dependents, sorted by id. */\n\torphans: readonly IslandReport[];\n\tsummary(): string;\n}\n\ninterface SnapshotIndex {\n\tnodes: Map<string, DescribeNode>;\n\toutgoing: Map<string, Set<string>>;\n\tincoming: Map<string, Set<string>>;\n}\n\nfunction compareCodeUnit(a: string, b: string): number {\n\treturn a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction assertMaxDepth(caller: string, maxDepth: number | undefined): void {\n\tif (maxDepth !== undefined && (!Number.isInteger(maxDepth) || maxDepth < 0)) {\n\t\tthrow new Error(`${caller}: maxDepth must be an integer >= 0`);\n\t}\n}\n\nfunction addEdge(map: Map<string, Set<string>>, from: string, to: string): void {\n\tlet set = map.get(from);\n\tif (set === undefined) {\n\t\tset = new Set();\n\t\tmap.set(from, set);\n\t}\n\tset.add(to);\n}\n\nfunction flattenSnapshots(snapshot: DescribeSnapshot): DescribeSnapshot[] {\n\tconst out: DescribeSnapshot[] = [];\n\tconst stack = [snapshot];\n\twhile (stack.length > 0) {\n\t\tconst cur = stack.pop() as DescribeSnapshot;\n\t\tout.push(cur);\n\t\tif (cur.subgraphs) {\n\t\t\tfor (let i = cur.subgraphs.length - 1; i >= 0; i -= 1) stack.push(cur.subgraphs[i]);\n\t\t}\n\t}\n\treturn out;\n}\n\nfunction indexSnapshot(snapshot: DescribeSnapshot): SnapshotIndex {\n\tconst nodes = new Map<string, DescribeNode>();\n\tconst outgoing = new Map<string, Set<string>>();\n\tconst incoming = new Map<string, Set<string>>();\n\tfor (const snap of flattenSnapshots(snapshot)) {\n\t\tfor (const n of snap.nodes) {\n\t\t\tnodes.set(n.id, n);\n\t\t\tif (!outgoing.has(n.id)) outgoing.set(n.id, new Set());\n\t\t\tif (!incoming.has(n.id)) incoming.set(n.id, new Set());\n\t\t}\n\t}\n\tfor (const n of nodes.values()) {\n\t\tfor (const dep of n.deps) {\n\t\t\tif (!dep || !nodes.has(dep)) continue;\n\t\t\taddEdge(outgoing, dep, n.id);\n\t\t\taddEdge(incoming, n.id, dep);\n\t\t}\n\t}\n\tfor (const snap of flattenSnapshots(snapshot)) {\n\t\tfor (const edge of snap.edges) {\n\t\t\tif (!edge.from || !edge.to) continue;\n\t\t\tif (!nodes.has(edge.from) || !nodes.has(edge.to)) continue;\n\t\t\taddEdge(outgoing, edge.from, edge.to);\n\t\t\taddEdge(incoming, edge.to, edge.from);\n\t\t}\n\t}\n\treturn { nodes, outgoing, incoming };\n}\n\nfunction adjacent(\n\tidx: SnapshotIndex,\n\tid: string,\n\tdirection: ReachableDirection,\n\tboth: boolean | undefined,\n): Set<string> {\n\treturn both === true\n\t\t? new Set([...(idx.incoming.get(id) ?? []), ...(idx.outgoing.get(id) ?? [])])\n\t\t: direction === \"upstream\"\n\t\t\t? (idx.incoming.get(id) ?? new Set<string>())\n\t\t\t: (idx.outgoing.get(id) ?? new Set<string>());\n}\n\n/**\n * Return node ids reachable from `from` through describe deps/edges.\n *\n * `upstream` follows dep edges toward causes; `downstream` follows reverse deps toward effects.\n * The helper is intentionally pure over `DescribeSnapshot` (D39/D51): it never reads Nodes.\n */\nexport function reachable(\n\tsnapshot: DescribeSnapshot,\n\tfrom: string,\n\tdirection: ReachableDirection,\n\toptions?: ReachableOptions & { withDetail: true },\n): ReachableResult;\nexport function reachable(\n\tsnapshot: DescribeSnapshot,\n\tfrom: string,\n\tdirection: ReachableDirection,\n\toptions?: ReachableOptions,\n): readonly string[];\nexport function reachable(\n\tsnapshot: DescribeSnapshot,\n\tfrom: string,\n\tdirection: ReachableDirection,\n\toptions: ReachableOptions = {},\n): readonly string[] | ReachableResult {\n\tif (!options.both && direction !== \"upstream\" && direction !== \"downstream\") {\n\t\tthrow new Error(`reachable: direction must be \"upstream\" or \"downstream\"`);\n\t}\n\tassertMaxDepth(\"reachable\", options.maxDepth);\n\tconst empty: ReachableResult = { paths: [], depths: {}, truncated: false };\n\tif (from === \"\") return options.withDetail ? empty : empty.paths;\n\n\tconst idx = indexSnapshot(snapshot);\n\tif (!idx.nodes.has(from)) return options.withDetail ? empty : empty.paths;\n\tif (options.maxDepth === 0) {\n\t\tconst truncated = adjacent(idx, from, direction, options.both).size > 0;\n\t\treturn options.withDetail ? { ...empty, truncated } : empty.paths;\n\t}\n\tconst depths = new Map<string, number>();\n\tconst seen = new Set<string>([from]);\n\tconst queue: Array<{ id: string; depth: number }> = [{ id: from, depth: 0 }];\n\tlet truncated = false;\n\tfor (let head = 0; head < queue.length; head += 1) {\n\t\tconst cur = queue[head] as { id: string; depth: number };\n\t\tconst next = adjacent(idx, cur.id, direction, options.both);\n\t\tif (options.maxDepth !== undefined && cur.depth >= options.maxDepth) {\n\t\t\tif (next.size > 0) truncated = true;\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const id of next) {\n\t\t\tif (seen.has(id)) continue;\n\t\t\tseen.add(id);\n\t\t\tconst depth = cur.depth + 1;\n\t\t\tdepths.set(id, depth);\n\t\t\tqueue.push({ id, depth });\n\t\t}\n\t}\n\tconst paths = [...depths.keys()].sort(compareCodeUnit);\n\tif (!options.withDetail) return paths;\n\treturn {\n\t\tpaths,\n\t\tdepths: Object.fromEntries([...depths.entries()].sort(([a], [b]) => compareCodeUnit(a, b))),\n\t\ttruncated,\n\t};\n}\n\nfunction depIndices(next: DescribeNode | undefined, prevId: string): readonly number[] | undefined {\n\tif (next === undefined) return undefined;\n\tconst indices: number[] = [];\n\tfor (let i = 0; i < next.deps.length; i += 1) {\n\t\tif (next.deps[i] === prevId) indices.push(i);\n\t}\n\treturn indices.length > 0 ? indices : undefined;\n}\n\nfunction stepFor(\n\tnode: DescribeNode,\n\thop: number,\n\tedgeToNext?: { next: DescribeNode; prevId: string },\n): CausalStep {\n\tconst indices = edgeToNext ? depIndices(edgeToNext.next, edgeToNext.prevId) : undefined;\n\tconst out: CausalStep = {\n\t\tid: node.id,\n\t\tfactory: node.factory,\n\t\tstatus: node.status,\n\t\thop,\n\t};\n\tif (\"value\" in node) out.value = node.value;\n\tif (indices !== undefined) {\n\t\tout.depIndex = indices[0];\n\t\tif (indices.length > 1) out.depIndices = indices;\n\t}\n\treturn out;\n}\n\nfunction makeChain(\n\tfrom: string,\n\tto: string,\n\treason: ExplainPathReason,\n\tsteps: readonly CausalStep[],\n): CausalChain {\n\tconst found = reason === \"ok\";\n\tconst text = found\n\t\t? steps.map((s) => s.id).join(\" -> \")\n\t\t: `explainPath: ${reason} from '${from}' to '${to}'`;\n\treturn {\n\t\tfrom,\n\t\tto,\n\t\tfound,\n\t\treason,\n\t\tsteps,\n\t\ttext,\n\t\ttoJSON: () => ({ from, to, found, reason, steps }),\n\t};\n}\n\nfunction shortestPath(\n\tidx: SnapshotIndex,\n\tfrom: string,\n\tto: string,\n\tmaxDepth: number | undefined,\n): { path: string[]; truncated: boolean } | undefined {\n\tconst pred = new Map<string, string>();\n\tconst seen = new Set<string>([from]);\n\tconst queue: Array<{ id: string; depth: number }> = [{ id: from, depth: 0 }];\n\tlet truncated = false;\n\tfor (let head = 0; head < queue.length; head += 1) {\n\t\tconst cur = queue[head] as { id: string; depth: number };\n\t\tconst next = idx.outgoing.get(cur.id) ?? new Set<string>();\n\t\tif (maxDepth !== undefined && cur.depth >= maxDepth) {\n\t\t\tif (next.size > 0) truncated = true;\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const id of next) {\n\t\t\tif (seen.has(id)) continue;\n\t\t\tseen.add(id);\n\t\t\tpred.set(id, cur.id);\n\t\t\tif (id === to) {\n\t\t\t\tconst path = [to];\n\t\t\t\tlet p = to;\n\t\t\t\twhile (p !== from) {\n\t\t\t\t\tp = pred.get(p) as string;\n\t\t\t\t\tpath.push(p);\n\t\t\t\t}\n\t\t\t\tpath.reverse();\n\t\t\t\treturn { path, truncated };\n\t\t\t}\n\t\t\tqueue.push({ id, depth: cur.depth + 1 });\n\t\t}\n\t}\n\treturn truncated ? { path: [], truncated: true } : undefined;\n}\n\nfunction shortestCycle(\n\tidx: SnapshotIndex,\n\tfrom: string,\n\tmaxDepth: number | undefined,\n): { path: string[]; truncated: boolean } | undefined {\n\tconst first = idx.outgoing.get(from) ?? new Set<string>();\n\tif (maxDepth === 0) return first.size > 0 ? { path: [], truncated: true } : undefined;\n\tconst queue: Array<{ id: string; depth: number; path: string[] }> = [];\n\tconst seen = new Set<string>();\n\tfor (const id of first) {\n\t\tif (id === from) return { path: [from, from], truncated: false };\n\t\tseen.add(id);\n\t\tqueue.push({ id, depth: 1, path: [from, id] });\n\t}\n\tlet truncated = false;\n\tfor (let head = 0; head < queue.length; head += 1) {\n\t\tconst cur = queue[head] as { id: string; depth: number; path: string[] };\n\t\tconst next = idx.outgoing.get(cur.id) ?? new Set<string>();\n\t\tif (maxDepth !== undefined && cur.depth >= maxDepth) {\n\t\t\tif (next.size > 0) truncated = true;\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const id of next) {\n\t\t\tif (id === from) return { path: [...cur.path, from], truncated: false };\n\t\t\tif (seen.has(id)) continue;\n\t\t\tseen.add(id);\n\t\t\tqueue.push({ id, depth: cur.depth + 1, path: [...cur.path, id] });\n\t\t}\n\t}\n\treturn truncated ? { path: [], truncated: true } : undefined;\n}\n\nfunction materializePath(idx: SnapshotIndex, path: readonly string[]): readonly CausalStep[] {\n\treturn path.map((id, i) => {\n\t\tconst node = idx.nodes.get(id) as DescribeNode;\n\t\tconst next = path[i + 1] ? idx.nodes.get(path[i + 1]) : undefined;\n\t\treturn stepFor(node, i, next ? { next, prevId: id } : undefined);\n\t});\n}\n\n/**\n * Explain the shortest describe-edge path from `from` to `to`.\n *\n * This is the rich companion to `Graph.describe({ explain })`: it reports found/no-path\n * status and per-hop metadata, but remains a pure helper over the snapshot.\n */\nexport function explainPath(\n\tsnapshot: DescribeSnapshot,\n\tfrom: string,\n\tto: string,\n\toptions: ExplainPathOptions = {},\n): CausalChain {\n\tassertMaxDepth(\"explainPath\", options.maxDepth);\n\tconst idx = indexSnapshot(snapshot);\n\tif (!idx.nodes.has(from)) return makeChain(from, to, \"no-such-from\", []);\n\tif (!idx.nodes.has(to)) return makeChain(from, to, \"no-such-to\", []);\n\tif (options.maxDepth === 0 && from !== to) return makeChain(from, to, \"no-path\", []);\n\n\tif (from === to && options.findCycle !== true) {\n\t\treturn makeChain(from, to, \"ok\", [stepFor(idx.nodes.get(from) as DescribeNode, 0)]);\n\t}\n\tif (from === to && options.findCycle === true) {\n\t\tconst cycle = shortestCycle(idx, from, options.maxDepth);\n\t\tif (cycle !== undefined && cycle.path.length > 0) {\n\t\t\treturn makeChain(from, to, \"ok\", materializePath(idx, cycle.path));\n\t\t}\n\t\tif (cycle?.truncated) return makeChain(from, to, \"max-depth-exceeded\", []);\n\t\treturn makeChain(from, to, \"ok\", [stepFor(idx.nodes.get(from) as DescribeNode, 0)]);\n\t}\n\tconst found = shortestPath(idx, from, to, options.maxDepth);\n\tif (found !== undefined && found.path.length > 0) {\n\t\treturn makeChain(from, to, \"ok\", materializePath(idx, found.path));\n\t}\n\treturn makeChain(from, to, found?.truncated ? \"max-depth-exceeded\" : \"no-path\", []);\n}\n\n/** Detect nodes with zero deps and zero dependents in a describe snapshot. */\nexport function validateNoIslands(snapshot: DescribeSnapshot): ValidateNoIslandsResult {\n\tconst idx = indexSnapshot(snapshot);\n\tconst orphans: IslandReport[] = [];\n\tfor (const node of idx.nodes.values()) {\n\t\tconst hasDeps = node.deps.length > 0 || (idx.incoming.get(node.id)?.size ?? 0) > 0;\n\t\tconst hasDependents = (idx.outgoing.get(node.id)?.size ?? 0) > 0;\n\t\tif (!hasDeps && !hasDependents && !node.id.startsWith(\"__internal__/\")) {\n\t\t\torphans.push({ id: node.id, factory: node.factory });\n\t\t}\n\t}\n\torphans.sort((a, b) => compareCodeUnit(a.id, b.id));\n\treturn {\n\t\tok: orphans.length === 0,\n\t\torphans,\n\t\tsummary(): string {\n\t\t\tif (orphans.length === 0) return \"validateNoIslands: ok (no islands)\";\n\t\t\tconst head = orphans\n\t\t\t\t.slice(0, 3)\n\t\t\t\t.map((o) => `${o.id} (${o.factory})`)\n\t\t\t\t.join(\", \");\n\t\t\treturn `validateNoIslands: ${orphans.length} island node(s) - ${head}${orphans.length > 3 ? \", ...\" : \"\"}`;\n\t\t},\n\t};\n}\n","/**\n * observe / profile inspection shapes (R-observe, R-profile / D39).\n *\n * observe = a read-only enveloped EGRESS (not a graph node). profile = an opt-in\n * accumulated-counter snapshot backed by the dispatcher recorder (counters never live on\n * the thin node, R-node-thin). Per-language (D24, never in parity).\n */\n\nimport type { Status } from \"../node/node.js\";\nimport type { Message } from \"../protocol/messages.js\";\n\n/** One item of an observe() stream. The envelope carries node identity + ordering. */\nexport interface ObserveEvent {\n\t/** Mount-aware `::` path of the emitting node (shared key with describe/profile). */\n\tpath: string;\n\t/** The protocol message observed at that node. */\n\tmsg: Message;\n\t/** messageTier(msg[0]). */\n\ttier: number;\n\t/** Graph-local monotonic sequence (D26) — orders events across nodes. */\n\tseq: number;\n}\n\n/** A read-only egress: subscribe to the live ObserveEvent stream; call the returned fn to stop. */\nexport interface ObserveStream {\n\tsubscribe(sink: (e: ObserveEvent) => void): () => void;\n}\n\nexport type TopologyEventKind =\n\t| \"node-registered\"\n\t| \"deps-changed\"\n\t| \"node-released\"\n\t| \"mount-changed\";\n\nexport interface TopologyEvent {\n\t/** D145 graph inspection/lifecycle event kind. Not a protocol message. */\n\treadonly kind: TopologyEventKind;\n\t/** Mount-aware `::` path of the affected registered node. */\n\treadonly path: string;\n\t/** Current dep ids after the event, matching describe().nodes[].deps. */\n\treadonly deps: readonly string[];\n\t/** Previous dep ids for deps-changed events. */\n\treadonly prevDeps?: readonly string[];\n\t/** Factory name for node-registered and node-released events. */\n\treadonly factory?: string;\n\t/** Graph-local monotonic sequence shared with observe() ordering. */\n\treadonly seq: number;\n}\n\n/** A read-only topology egress stream. It does not activate nodes or emit DATA. */\nexport interface TopologyStream {\n\tsubscribe(sink: (e: TopologyEvent) => void): () => void;\n}\n\n/** Predicate used by filterObserve(). */\nexport type ObservePredicate = (event: ObserveEvent) => boolean;\n\n/** Equality used by coalesceObserve() for adjacent observe-event suppression. */\nexport type ObserveEventEquals = (prev: ObserveEvent, next: ObserveEvent) => boolean;\n\n/**\n * Filter a read-only observe egress stream without turning it into a graph node.\n *\n * The source stream owns ordering and lifecycle; this helper only decides whether to forward each\n * ObserveEvent and returns the source unsubscribe unchanged.\n */\nexport function filterObserve(stream: ObserveStream, predicate: ObservePredicate): ObserveStream {\n\treturn {\n\t\tsubscribe(sink) {\n\t\t\treturn stream.subscribe((event) => {\n\t\t\t\tif (predicate(event)) {\n\t\t\t\t\tsink(event);\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t};\n}\n\nfunction sameObserveEvent(prev: ObserveEvent, next: ObserveEvent): boolean {\n\treturn (\n\t\tprev.path === next.path &&\n\t\tprev.tier === next.tier &&\n\t\tprev.msg[0] === next.msg[0] &&\n\t\tObject.is(messagePayload(prev.msg), messagePayload(next.msg))\n\t);\n}\n\nfunction messagePayload(msg: Message): unknown {\n\treturn msg.length > 1 ? msg[1] : undefined;\n}\n\n/**\n * Suppress adjacent duplicate ObserveEvents while preserving the source stream order.\n *\n * This is egress-side coalescing only: it does not batch, delay, reorder, alter seq values, or add\n * topology to describe(). Pass a custom equality when the caller wants a narrower or wider\n * definition of \"duplicate\".\n */\nexport function coalesceObserve(\n\tstream: ObserveStream,\n\tequals: ObserveEventEquals = sameObserveEvent,\n): ObserveStream {\n\treturn {\n\t\tsubscribe(sink) {\n\t\t\tlet previous: ObserveEvent | undefined;\n\t\t\treturn stream.subscribe((event) => {\n\t\t\t\tif (previous && equals(previous, event)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tprevious = event;\n\t\t\t\tsink(event);\n\t\t\t});\n\t\t},\n\t};\n}\n\n/** Per-node profile counters (D39). invokes/duration are dispatcher-backed (R-profile). */\nexport interface NodeProfile {\n\tinvokes: number;\n\ttotalDurationNs: number;\n\tlastDurationNs: number;\n\tstatus: Status;\n}\n\n/** profile() snapshot. Shares the mount-aware `::` path key with describe/observe. */\nexport interface Profile {\n\ttotalInvokes: number;\n\tnodes: Record<string, NodeProfile>;\n}\n","/**\n * Fresh-graph checkpoint restore (D94/D95).\n *\n * Restore consumes an already-loaded strict-JSON checkpoint. It validates the whole tree,\n * constructs graph-registered topology through explicit descriptors, then performs one\n * internal runtime-state commit. No storage I/O, observe replay, public hook, or protocol\n * wave participates in this path.\n */\n\nimport type { Dispatcher } from \"../dispatcher/index.js\";\nimport { strictCanonicalJsonBytes } from \"../json/codec.js\";\nimport type { Node } from \"../node/node.js\";\nimport { restoreStateOfNode, type Status } from \"../node/node.js\";\nimport {\n\ttype NodeVersioningPolicy,\n\ttype NodeVersionJson,\n\tvalidateNodeVersionJson,\n} from \"../node/versioning.js\";\nimport { SENTINEL } from \"../protocol/messages.js\";\nimport {\n\tGRAPH_CHECKPOINT_VERSION,\n\ttype GraphCheckpoint,\n\ttype GraphCheckpointFactory,\n\ttype GraphCheckpointJson,\n\ttype GraphCheckpointNode,\n\ttype GraphCheckpointTerminal,\n\ttype GraphCheckpointValue,\n\ttoCheckpointJson,\n} from \"./checkpoint.js\";\nimport type { IndexRow, ReactiveIndex } from \"./data-structures/reactive-index.js\";\nimport { restoreReactiveIndexFromBackendState } from \"./data-structures/reactive-index.js\";\nimport { type ReactiveList, reactiveList } from \"./data-structures/reactive-list.js\";\nimport { type ReactiveLog, reactiveLog } from \"./data-structures/reactive-log.js\";\nimport {\n\ttype ReactiveMap,\n\trestoreReactiveMapFromBackendState,\n} from \"./data-structures/reactive-map.js\";\nimport {\n\ttype Graph,\n\tgraph,\n\trestoreNodeInGraph,\n\trestoreStateNodeInGraph,\n\ttype SugarOpts,\n} from \"./graph.js\";\nimport { map, operatorNodeFn, take } from \"./operators.js\";\nimport { timer } from \"./sources.js\";\n\nexport interface GraphRestoreDefinition<S = never, T = unknown> {\n\treadonly kind: \"definition\";\n\treadonly ref: string;\n\treadonly fn: (v: S) => T;\n}\n\nexport type GraphRestoreEntry = GraphRestoreDescriptor | GraphRestoreDefinition;\n\nexport interface GraphRestoreDescriptorContext<\n\tC extends GraphCheckpointJson | undefined = GraphCheckpointJson | undefined,\n> {\n\treadonly graph: Graph;\n\treadonly id: string;\n\treadonly name?: string;\n\treadonly deps: readonly Node<unknown>[];\n\treadonly config: C;\n\treadonly configVersion?: GraphCheckpointJson;\n\treadonly checkpoint: GraphCheckpointNode;\n\tresolveDefinition<S = unknown, T = unknown>(ref: string): GraphRestoreDefinition<S, T>;\n\tregisterState<T = unknown>(opts?: SugarOpts<T>): Node<unknown>;\n\tregisterNode<T = unknown>(\n\t\tfactory: string,\n\t\tdeps: readonly Node<unknown>[],\n\t\tfn: import(\"../ctx/types.js\").NodeFn | null,\n\t\topts?: SugarOpts<T>,\n\t): Node<unknown>;\n}\n\nexport interface GraphRestoreDescriptor<\n\tC extends GraphCheckpointJson | undefined = GraphCheckpointJson | undefined,\n> {\n\treadonly ref: string;\n\tvalidateConfig?(\n\t\tconfig: GraphCheckpointJson | undefined,\n\t\tconfigVersion: GraphCheckpointJson | undefined,\n\t\tcheckpoint: GraphCheckpointNode,\n\t): C;\n\tcreate(ctx: GraphRestoreDescriptorContext<C>): Node<unknown>;\n}\n\nexport type GraphRestoreRegistry =\n\t| ReadonlyMap<string, GraphRestoreEntry>\n\t| Readonly<Record<string, GraphRestoreEntry>>;\n\nexport interface RestoreGraphOptions {\n\tregistry: GraphRestoreRegistry;\n\tdispatcher?: Dispatcher;\n\tversioning?: NodeVersioningPolicy;\n}\n\nexport const stateRestoreDescriptor: GraphRestoreDescriptor<undefined> = {\n\tref: \"state\",\n\tvalidateConfig(config, configVersion) {\n\t\tif (config !== undefined || configVersion !== undefined) {\n\t\t\tthrow new Error(\"restoreGraph: built-in state descriptor does not accept config\");\n\t\t}\n\t\treturn undefined;\n\t},\n\tcreate(ctx) {\n\t\tif (ctx.deps.length !== 0) {\n\t\t\tthrow new Error(`restoreGraph: state node '${ctx.checkpoint.id}' cannot restore deps`);\n\t\t}\n\t\treturn ctx.registerState({\n\t\t\tname: ctx.name,\n\t\t\tmeta: ctx.checkpoint.meta,\n\t\t});\n\t},\n};\n\ntype TakeConfig = { n: number };\ntype TimerConfig = { ms: number };\ntype MapConfig = { fn: string };\ntype LogConfig = { maxSize?: number };\n\nfunction objectConfig(\n\tconfig: GraphCheckpointJson | undefined,\n\tref: string,\n): Record<string, GraphCheckpointJson> {\n\tif (\n\t\tconfig === undefined ||\n\t\tconfig === null ||\n\t\tArray.isArray(config) ||\n\t\ttypeof config !== \"object\"\n\t) {\n\t\tthrow new Error(`restoreGraph: '${ref}' descriptor requires object config`);\n\t}\n\treturn config as Record<string, GraphCheckpointJson>;\n}\n\nfunction finiteNumber(value: GraphCheckpointJson | undefined, ref: string, key: string): number {\n\tif (typeof value !== \"number\" || !Number.isFinite(value)) {\n\t\tthrow new Error(`restoreGraph: '${ref}' config.${key} must be a finite number`);\n\t}\n\treturn value;\n}\n\nexport const takeRestoreDescriptor: GraphRestoreDescriptor<TakeConfig> = {\n\tref: \"take\",\n\tvalidateConfig(config, configVersion) {\n\t\tif (configVersion !== undefined) {\n\t\t\tthrow new Error(\"restoreGraph: built-in take descriptor does not accept configVersion\");\n\t\t}\n\t\treturn { n: finiteNumber(objectConfig(config, \"take\").n, \"take\", \"n\") };\n\t},\n\tcreate(ctx) {\n\t\tif (ctx.deps.length !== 1) {\n\t\t\tthrow new Error(`restoreGraph: take node '${ctx.checkpoint.id}' requires exactly one dep`);\n\t\t}\n\t\tconst op = take(ctx.config.n);\n\t\treturn ctx.registerNode(\"take\", ctx.deps, operatorNodeFn(op), {\n\t\t\tname: ctx.name,\n\t\t\tmeta: ctx.checkpoint.meta,\n\t\t\trestore: op.restore,\n\t\t});\n\t},\n};\n\nexport const mapRestoreDescriptor: GraphRestoreDescriptor<MapConfig> = {\n\tref: \"map\",\n\tvalidateConfig(config, configVersion) {\n\t\tif (configVersion !== undefined) {\n\t\t\tthrow new Error(\"restoreGraph: built-in map descriptor does not accept configVersion\");\n\t\t}\n\t\tconst obj = objectConfig(config, \"map\");\n\t\tif (typeof obj.fn !== \"string\") {\n\t\t\tthrow new Error(\"restoreGraph: 'map' config.fn must be a string definition ref\");\n\t\t}\n\t\treturn { fn: obj.fn };\n\t},\n\tcreate(ctx) {\n\t\tif (ctx.deps.length !== 1) {\n\t\t\tthrow new Error(`restoreGraph: map node '${ctx.checkpoint.id}' requires exactly one dep`);\n\t\t}\n\t\tconst definition = ctx.resolveDefinition(ctx.config.fn);\n\t\tconst op = map(definition);\n\t\treturn ctx.registerNode(\"map\", ctx.deps, operatorNodeFn(op), {\n\t\t\tname: ctx.name,\n\t\t\tmeta: ctx.checkpoint.meta,\n\t\t\trestore: op.restore,\n\t\t});\n\t},\n};\n\nexport const timerRestoreDescriptor: GraphRestoreDescriptor<TimerConfig> = {\n\tref: \"timer\",\n\tvalidateConfig(config, configVersion) {\n\t\tif (configVersion !== undefined) {\n\t\t\tthrow new Error(\"restoreGraph: built-in timer descriptor does not accept configVersion\");\n\t\t}\n\t\treturn { ms: finiteNumber(objectConfig(config, \"timer\").ms, \"timer\", \"ms\") };\n\t},\n\tcreate(ctx) {\n\t\tif (ctx.deps.length !== 0) {\n\t\t\tthrow new Error(`restoreGraph: timer node '${ctx.checkpoint.id}' cannot restore deps`);\n\t\t}\n\t\tconst op = timer(ctx.config.ms);\n\t\treturn ctx.registerNode(\"timer\", ctx.deps, operatorNodeFn(op), {\n\t\t\tname: ctx.name,\n\t\t\tmeta: ctx.checkpoint.meta,\n\t\t\trestore: op.restore,\n\t\t\t...op.opts,\n\t\t});\n\t},\n};\n\ntype RestoredCollection =\n\t| { kind: \"reactiveList\"; collection: ReactiveList<unknown> }\n\t| { kind: \"reactiveIndex\"; collection: ReactiveIndex<unknown, unknown> }\n\t| { kind: \"reactiveLog\"; collection: ReactiveLog<unknown> }\n\t| { kind: \"reactiveMap\"; collection: ReactiveMap<unknown, unknown> };\n\nconst restoredCollections = new WeakMap<Graph, Map<string, RestoredCollection>>();\n\nfunction restoredCollectionMap(graph: Graph): Map<string, RestoredCollection> {\n\tlet map = restoredCollections.get(graph);\n\tif (map === undefined) {\n\t\tmap = new Map();\n\t\trestoredCollections.set(graph, map);\n\t}\n\treturn map;\n}\n\nfunction clearRestoredCollectionMap(graph: Graph): void {\n\trestoredCollections.delete(graph);\n}\n\nfunction collectionBaseId(\n\tid: string,\n\tsuffix: \".intent\" | \".apply\" | \".snapshotPrep\" | \".delta\" | \".snapshot\",\n\tref: string,\n): string {\n\tif (!id.endsWith(suffix)) {\n\t\tthrow new Error(`restoreGraph: '${ref}' node '${id}' must end with '${suffix}'`);\n\t}\n\tconst base = id.slice(0, -suffix.length);\n\tif (base.length === 0) {\n\t\tthrow new Error(`restoreGraph: '${ref}' node '${id}' has no collection name`);\n\t}\n\treturn base;\n}\n\nfunction noCollectionConfig(\n\tconfig: GraphCheckpointJson | undefined,\n\tconfigVersion: GraphCheckpointJson | undefined,\n\tref: string,\n): undefined {\n\tif (config !== undefined || configVersion !== undefined) {\n\t\tthrow new Error(`restoreGraph: '${ref}' descriptor does not accept config`);\n\t}\n\treturn undefined;\n}\n\nfunction backendArray(\n\tcheckpoint: GraphCheckpointNode,\n\tref: string,\n): readonly GraphCheckpointJson[] {\n\tconst state = checkpoint.backendState;\n\tif (!Array.isArray(state)) {\n\t\tthrow new Error(`restoreGraph: '${ref}' node '${checkpoint.id}' requires array backendState`);\n\t}\n\treturn state;\n}\n\nfunction primitiveJsonKey(\n\tvalue: GraphCheckpointJson,\n\tpath: string,\n): string | number | boolean | null {\n\tif (\n\t\tvalue === null ||\n\t\ttypeof value === \"string\" ||\n\t\ttypeof value === \"number\" ||\n\t\ttypeof value === \"boolean\"\n\t) {\n\t\treturn value;\n\t}\n\tthrow new Error(`restoreGraph: ${path} must be a JSON primitive primary key`);\n}\n\nfunction indexRows(\n\tcheckpoint: GraphCheckpointNode,\n\tref: string,\n): readonly IndexRow<unknown, unknown>[] {\n\tconst rows: IndexRow<unknown, unknown>[] = [];\n\tconst seen = new Set<string>();\n\tfor (const [i, row] of backendArray(checkpoint, ref).entries()) {\n\t\tconst path = `${checkpoint.id}.backendState[${i}]`;\n\t\tif (row === null || Array.isArray(row) || typeof row !== \"object\") {\n\t\t\tthrow new Error(`restoreGraph: ${path} must be an index row object`);\n\t\t}\n\t\tif (\n\t\t\t!Object.hasOwn(row, \"primary\") ||\n\t\t\t!Object.hasOwn(row, \"secondary\") ||\n\t\t\t!Object.hasOwn(row, \"value\")\n\t\t) {\n\t\t\tthrow new Error(`restoreGraph: ${path} must contain primary, secondary, and value`);\n\t\t}\n\t\tconst obj = row as Record<string, GraphCheckpointJson>;\n\t\tconst primary = primitiveJsonKey(obj.primary as GraphCheckpointJson, `${path}.primary`);\n\t\tconst stablePrimary = JSON.stringify(primary);\n\t\tif (seen.has(stablePrimary)) {\n\t\t\tthrow new Error(`restoreGraph: ${path}.primary duplicates an earlier index row`);\n\t\t}\n\t\tseen.add(stablePrimary);\n\t\trows.push({\n\t\t\tprimary,\n\t\t\tsecondary: obj.secondary,\n\t\t\tvalue: obj.value,\n\t\t});\n\t}\n\treturn rows;\n}\n\nfunction stableJsonKey(value: GraphCheckpointJson): string {\n\treturn Array.from(strictCanonicalJsonBytes(value)).join(\",\");\n}\n\nfunction mapEntries(\n\tcheckpoint: GraphCheckpointNode,\n\tref: string,\n): readonly (readonly [unknown, unknown])[] {\n\tconst entries: Array<readonly [unknown, unknown]> = [];\n\tconst seen = new Set<string>();\n\tfor (const [i, entry] of backendArray(checkpoint, ref).entries()) {\n\t\tconst path = `${checkpoint.id}.backendState[${i}]`;\n\t\tif (!Array.isArray(entry) || entry.length !== 2) {\n\t\t\tthrow new Error(`restoreGraph: ${path} must be a [key, value] map entry`);\n\t\t}\n\t\tconst key = entry[0] as GraphCheckpointJson;\n\t\tconst stableKey = stableJsonKey(key);\n\t\tif (seen.has(stableKey)) {\n\t\t\tthrow new Error(`restoreGraph: ${path}[0] duplicates an earlier map key`);\n\t\t}\n\t\tseen.add(stableKey);\n\t\tentries.push([key, entry[1]] as const);\n\t}\n\treturn entries;\n}\n\nfunction restoredList(ctx: GraphRestoreDescriptorContext, ref: string): ReactiveList<unknown> {\n\tconst base = collectionBaseId(ctx.id, \".delta\", ref);\n\tif (ctx.deps.length !== 0) {\n\t\tthrow new Error(`restoreGraph: '${ref}' node '${ctx.id}' cannot restore deps`);\n\t}\n\tconst collection = reactiveList(backendArray(ctx.checkpoint, ref), {\n\t\tgraph: ctx.graph,\n\t\tname: base,\n\t});\n\trestoredCollectionMap(ctx.graph).set(base, { kind: \"reactiveList\", collection });\n\treturn collection;\n}\n\nfunction restoredIndex(ctx: GraphRestoreDescriptorContext, ref: string): ReactiveIndex<unknown> {\n\tconst base = collectionBaseId(ctx.id, \".delta\", ref);\n\tif (ctx.deps.length !== 0) {\n\t\tthrow new Error(`restoreGraph: '${ref}' node '${ctx.id}' cannot restore deps`);\n\t}\n\tconst rows = indexRows(ctx.checkpoint, ref);\n\tconst collection = restoreReactiveIndexFromBackendState(rows, {\n\t\tgraph: ctx.graph,\n\t\tname: base,\n\t});\n\trestoredCollectionMap(ctx.graph).set(base, { kind: \"reactiveIndex\", collection });\n\treturn collection;\n}\n\nfunction restoredLog(\n\tctx: GraphRestoreDescriptorContext<LogConfig>,\n\tref: string,\n): ReactiveLog<unknown> {\n\tconst base = collectionBaseId(ctx.id, \".delta\", ref);\n\tif (ctx.deps.length !== 0) {\n\t\tthrow new Error(`restoreGraph: '${ref}' node '${ctx.id}' cannot restore deps`);\n\t}\n\tconst state = backendArray(ctx.checkpoint, ref);\n\tif (ctx.config.maxSize !== undefined && state.length > ctx.config.maxSize) {\n\t\tthrow new Error(`restoreGraph: '${ref}' node '${ctx.id}' backendState exceeds config.maxSize`);\n\t}\n\tconst collection = reactiveLog(state, {\n\t\tgraph: ctx.graph,\n\t\tname: base,\n\t\t...(ctx.config.maxSize !== undefined ? { maxSize: ctx.config.maxSize } : {}),\n\t});\n\trestoredCollectionMap(ctx.graph).set(base, { kind: \"reactiveLog\", collection });\n\treturn collection;\n}\n\nfunction restoredMapNode(ctx: GraphRestoreDescriptorContext, ref: string): Node<unknown> {\n\tconst base = collectionBaseId(ctx.id, \".intent\", ref);\n\tif (ctx.deps.length !== 0) {\n\t\tthrow new Error(`restoreGraph: '${ref}' node '${ctx.id}' cannot restore deps`);\n\t}\n\tconst entries = mapEntries(ctx.checkpoint, ref);\n\tconst collection = restoreReactiveMapFromBackendState(entries, {\n\t\tgraph: ctx.graph,\n\t\tname: base,\n\t});\n\trestoredCollectionMap(ctx.graph).set(base, { kind: \"reactiveMap\", collection });\n\tconst node = ctx.graph.find(ctx.id);\n\tif (node === undefined) {\n\t\tthrow new Error(`restoreGraph: '${ref}' node '${ctx.id}' was not restored`);\n\t}\n\treturn node;\n}\n\nfunction existingMapNode(\n\tctx: GraphRestoreDescriptorContext,\n\tref: string,\n\tsuffix: \".apply\" | \".snapshotPrep\" | \".delta\" | \".snapshot\",\n): Node<unknown> {\n\tconst base = collectionBaseId(ctx.id, suffix, ref);\n\tconst item = restoredCollectionMap(ctx.graph).get(base);\n\tif (item === undefined || item.kind !== \"reactiveMap\") {\n\t\tthrow new Error(`restoreGraph: '${ref}' node '${ctx.id}' is missing restored '${base}.intent'`);\n\t}\n\tconst node = ctx.graph.find(ctx.id);\n\tif (node === undefined) {\n\t\tthrow new Error(`restoreGraph: '${ref}' node '${ctx.id}' was not restored`);\n\t}\n\treturn node;\n}\n\nfunction existingCollection(\n\tctx: GraphRestoreDescriptorContext,\n\tref: string,\n\tkind: RestoredCollection[\"kind\"],\n): RestoredCollection {\n\tconst base = collectionBaseId(ctx.id, \".snapshot\", ref);\n\tif (ctx.deps.length !== 1) {\n\t\tthrow new Error(`restoreGraph: '${ref}' node '${ctx.id}' requires exactly one dep`);\n\t}\n\tconst item = restoredCollectionMap(ctx.graph).get(base);\n\tif (item === undefined || item.kind !== kind) {\n\t\tthrow new Error(`restoreGraph: '${ref}' node '${ctx.id}' is missing restored '${base}.delta'`);\n\t}\n\treturn item;\n}\n\nfunction validateLogConfig(\n\tconfig: GraphCheckpointJson | undefined,\n\tconfigVersion: GraphCheckpointJson | undefined,\n\tref: string,\n): LogConfig {\n\tif (configVersion !== undefined) {\n\t\tthrow new Error(`restoreGraph: '${ref}' descriptor does not accept configVersion`);\n\t}\n\tif (config === undefined) return {};\n\tconst obj = objectConfig(config, ref);\n\tif (obj.maxSize === undefined) return {};\n\tconst maxSize = finiteNumber(obj.maxSize, ref, \"maxSize\");\n\tif (!Number.isInteger(maxSize) || maxSize < 1) {\n\t\tthrow new Error(`restoreGraph: '${ref}' config.maxSize must be a positive integer`);\n\t}\n\treturn { maxSize };\n}\n\nexport const reactiveListDeltaRestoreDescriptor: GraphRestoreDescriptor<undefined> = {\n\tref: \"reactiveList.delta\",\n\tvalidateConfig(config, configVersion) {\n\t\treturn noCollectionConfig(config, configVersion, \"reactiveList.delta\");\n\t},\n\tcreate(ctx) {\n\t\treturn restoredList(ctx, \"reactiveList.delta\").delta as Node<unknown>;\n\t},\n};\n\nexport const reactiveListSnapshotRestoreDescriptor: GraphRestoreDescriptor<undefined> = {\n\tref: \"reactiveList.snapshot\",\n\tvalidateConfig(config, configVersion) {\n\t\treturn noCollectionConfig(config, configVersion, \"reactiveList.snapshot\");\n\t},\n\tcreate(ctx) {\n\t\treturn existingCollection(ctx, \"reactiveList.snapshot\", \"reactiveList\").collection\n\t\t\t.snapshot as Node<unknown>;\n\t},\n};\n\nexport const reactiveIndexDeltaRestoreDescriptor: GraphRestoreDescriptor<undefined> = {\n\tref: \"reactiveIndex.delta\",\n\tvalidateConfig(config, configVersion) {\n\t\treturn noCollectionConfig(config, configVersion, \"reactiveIndex.delta\");\n\t},\n\tcreate(ctx) {\n\t\treturn restoredIndex(ctx, \"reactiveIndex.delta\").delta as Node<unknown>;\n\t},\n};\n\nexport const reactiveIndexSnapshotRestoreDescriptor: GraphRestoreDescriptor<undefined> = {\n\tref: \"reactiveIndex.snapshot\",\n\tvalidateConfig(config, configVersion) {\n\t\treturn noCollectionConfig(config, configVersion, \"reactiveIndex.snapshot\");\n\t},\n\tcreate(ctx) {\n\t\treturn existingCollection(ctx, \"reactiveIndex.snapshot\", \"reactiveIndex\").collection\n\t\t\t.snapshot as Node<unknown>;\n\t},\n};\n\nexport const reactiveLogDeltaRestoreDescriptor: GraphRestoreDescriptor<LogConfig> = {\n\tref: \"reactiveLog.delta\",\n\tvalidateConfig(config, configVersion) {\n\t\treturn validateLogConfig(config, configVersion, \"reactiveLog.delta\");\n\t},\n\tcreate(ctx) {\n\t\treturn restoredLog(ctx, \"reactiveLog.delta\").delta as Node<unknown>;\n\t},\n};\n\nexport const reactiveLogSnapshotRestoreDescriptor: GraphRestoreDescriptor<LogConfig> = {\n\tref: \"reactiveLog.snapshot\",\n\tvalidateConfig(config, configVersion) {\n\t\treturn validateLogConfig(config, configVersion, \"reactiveLog.snapshot\");\n\t},\n\tcreate(ctx) {\n\t\treturn existingCollection(ctx, \"reactiveLog.snapshot\", \"reactiveLog\").collection\n\t\t\t.snapshot as Node<unknown>;\n\t},\n};\n\nexport const reactiveMapIntentRestoreDescriptor: GraphRestoreDescriptor<undefined> = {\n\tref: \"reactiveMap.intent\",\n\tvalidateConfig(config, configVersion) {\n\t\treturn noCollectionConfig(config, configVersion, \"reactiveMap.intent\");\n\t},\n\tcreate(ctx) {\n\t\treturn restoredMapNode(ctx, \"reactiveMap.intent\");\n\t},\n};\n\nexport const reactiveMapApplyRestoreDescriptor: GraphRestoreDescriptor<undefined> = {\n\tref: \"reactiveMap.apply\",\n\tvalidateConfig(config, configVersion) {\n\t\treturn noCollectionConfig(config, configVersion, \"reactiveMap.apply\");\n\t},\n\tcreate(ctx) {\n\t\treturn existingMapNode(ctx, \"reactiveMap.apply\", \".apply\");\n\t},\n};\n\nexport const reactiveMapSnapshotPrepRestoreDescriptor: GraphRestoreDescriptor<undefined> = {\n\tref: \"reactiveMap.snapshotPrep\",\n\tvalidateConfig(config, configVersion) {\n\t\treturn noCollectionConfig(config, configVersion, \"reactiveMap.snapshotPrep\");\n\t},\n\tcreate(ctx) {\n\t\treturn existingMapNode(ctx, \"reactiveMap.snapshotPrep\", \".snapshotPrep\");\n\t},\n};\n\nexport const reactiveMapDeltaRestoreDescriptor: GraphRestoreDescriptor<undefined> = {\n\tref: \"reactiveMap.delta\",\n\tvalidateConfig(config, configVersion) {\n\t\treturn noCollectionConfig(config, configVersion, \"reactiveMap.delta\");\n\t},\n\tcreate(ctx) {\n\t\treturn existingMapNode(ctx, \"reactiveMap.delta\", \".delta\");\n\t},\n};\n\nexport const reactiveMapSnapshotRestoreDescriptor: GraphRestoreDescriptor<undefined> = {\n\tref: \"reactiveMap.snapshot\",\n\tvalidateConfig(config, configVersion) {\n\t\treturn noCollectionConfig(config, configVersion, \"reactiveMap.snapshot\");\n\t},\n\tcreate(ctx) {\n\t\treturn existingMapNode(ctx, \"reactiveMap.snapshot\", \".snapshot\");\n\t},\n};\n\nexport const defaultRestoreRegistry: Readonly<Record<string, GraphRestoreDescriptor>> = {\n\tstate: stateRestoreDescriptor,\n\tmap: mapRestoreDescriptor,\n\ttake: takeRestoreDescriptor,\n\ttimer: timerRestoreDescriptor,\n\t\"reactiveList.delta\": reactiveListDeltaRestoreDescriptor,\n\t\"reactiveList.snapshot\": reactiveListSnapshotRestoreDescriptor,\n\t\"reactiveIndex.delta\": reactiveIndexDeltaRestoreDescriptor,\n\t\"reactiveIndex.snapshot\": reactiveIndexSnapshotRestoreDescriptor,\n\t\"reactiveLog.delta\": reactiveLogDeltaRestoreDescriptor,\n\t\"reactiveLog.snapshot\": reactiveLogSnapshotRestoreDescriptor,\n\t\"reactiveMap.intent\": reactiveMapIntentRestoreDescriptor,\n\t\"reactiveMap.apply\": reactiveMapApplyRestoreDescriptor,\n\t\"reactiveMap.snapshotPrep\": reactiveMapSnapshotPrepRestoreDescriptor,\n\t\"reactiveMap.delta\": reactiveMapDeltaRestoreDescriptor,\n\t\"reactiveMap.snapshot\": reactiveMapSnapshotRestoreDescriptor,\n};\n\ntype PreparedNode = {\n\tcheckpoint: GraphCheckpointNode;\n\tlocalId: string;\n\tdescriptor: GraphRestoreDescriptor;\n\tconfig: GraphCheckpointJson | undefined;\n\tdeps: string[];\n\truntime: PreparedRuntime;\n};\n\ntype PreparedCheckpoint = {\n\tcheckpoint: GraphCheckpoint;\n\tnodes: Map<string, PreparedNode>;\n\tmounts: Array<{ at: string; prepared: PreparedCheckpoint }>;\n};\n\ntype PreparedRuntime = {\n\tcache: unknown;\n\thasData: boolean;\n\tstatus: Status;\n\tterminal: true | unknown | undefined;\n\thasCalledFnOnce: boolean;\n\tctxState: { value: unknown; persist: boolean };\n\tversion: NodeVersionJson | false;\n};\n\nfunction registryGet(registry: GraphRestoreRegistry, ref: string): GraphRestoreEntry | undefined {\n\treturn registry instanceof Map\n\t\t? registry.get(ref)\n\t\t: (registry as Readonly<Record<string, GraphRestoreEntry>>)[ref];\n}\n\nfunction isRestoreDescriptor(\n\tentry: GraphRestoreEntry | undefined,\n): entry is GraphRestoreDescriptor {\n\treturn entry !== undefined && \"create\" in entry;\n}\n\nfunction isRestoreDefinition(\n\tentry: GraphRestoreEntry | undefined,\n): entry is GraphRestoreDefinition {\n\treturn entry !== undefined && \"kind\" in entry && entry.kind === \"definition\";\n}\n\nfunction assertString(value: unknown, label: string): string {\n\tif (typeof value !== \"string\") throw new Error(`restoreGraph: ${label} must be a string`);\n\treturn value;\n}\n\nfunction assertStatus(value: string, id: string): Status {\n\tif (\n\t\tvalue !== \"sentinel\" &&\n\t\tvalue !== \"pending\" &&\n\t\tvalue !== \"dirty\" &&\n\t\tvalue !== \"settled\" &&\n\t\tvalue !== \"resolved\" &&\n\t\tvalue !== \"completed\" &&\n\t\tvalue !== \"errored\"\n\t) {\n\t\tthrow new Error(`restoreGraph: node '${id}' has invalid status '${value}'`);\n\t}\n\tif (value === \"pending\" || value === \"dirty\") {\n\t\tthrow new Error(\n\t\t\t`restoreGraph: node '${id}' has non-quiescent status '${value}' that cannot be checkpoint-restored yet`,\n\t\t);\n\t}\n\treturn value;\n}\n\nfunction checkpointDataValue(\n\tvalue: GraphCheckpointValue,\n\tid: string,\n): {\n\tcache: unknown;\n\thasData: boolean;\n} {\n\tif (value.kind === \"SENTINEL\") return { cache: SENTINEL, hasData: false };\n\tif (value.kind === \"DATA\") return { cache: value.data, hasData: true };\n\tthrow new Error(`restoreGraph: node '${id}' has invalid checkpoint value`);\n}\n\nfunction checkpointTerminal(\n\tvalue: GraphCheckpointTerminal,\n\tid: string,\n): true | unknown | undefined {\n\tif (value.kind === \"none\") return undefined;\n\tif (value.kind === \"COMPLETE\") return true;\n\tif (value.kind === \"ERROR\") return value.error;\n\tthrow new Error(`restoreGraph: node '${id}' has invalid terminal state`);\n}\n\nfunction prepareRuntime(node: GraphCheckpointNode): PreparedRuntime {\n\tconst nonAuthoritativeCollectionHelper = isCollectionHelperNonAuthoritative(node);\n\tconst value = nonAuthoritativeCollectionHelper\n\t\t? { cache: SENTINEL, hasData: false }\n\t\t: checkpointDataValue(node.value, node.id);\n\tconst terminal = checkpointTerminal(node.terminal, node.id);\n\tconst status = assertStatus(node.status, node.id);\n\tif (terminal === true && status !== \"completed\") {\n\t\tthrow new Error(`restoreGraph: node '${node.id}' COMPLETE terminal requires completed status`);\n\t}\n\tif (terminal !== undefined && terminal !== true && status !== \"errored\") {\n\t\tthrow new Error(`restoreGraph: node '${node.id}' ERROR terminal requires errored status`);\n\t}\n\tif (terminal === undefined && (status === \"completed\" || status === \"errored\")) {\n\t\tthrow new Error(`restoreGraph: node '${node.id}' terminal status requires terminal state`);\n\t}\n\tif (typeof node.lifecycle.activated !== \"boolean\") {\n\t\tthrow new Error(`restoreGraph: node '${node.id}' lifecycle.activated must be boolean`);\n\t}\n\tif (typeof node.lifecycle.hasCalledFnOnce !== \"boolean\") {\n\t\tthrow new Error(`restoreGraph: node '${node.id}' lifecycle.hasCalledFnOnce must be boolean`);\n\t}\n\tif (typeof node.ctxState.persist !== \"boolean\") {\n\t\tthrow new Error(`restoreGraph: node '${node.id}' ctxState.persist must be boolean`);\n\t}\n\tconst ctxState = nonAuthoritativeCollectionHelper\n\t\t? { cache: SENTINEL, hasData: false }\n\t\t: checkpointDataValue(node.ctxState.value, `${node.id}.ctxState`);\n\tconst version =\n\t\tnode.version === undefined\n\t\t\t? false\n\t\t\t: validateNodeVersionJson(node.version, `${node.id}.version`);\n\treturn {\n\t\tcache: value.cache,\n\t\thasData: value.hasData,\n\t\tstatus,\n\t\tterminal,\n\t\thasCalledFnOnce: node.lifecycle.hasCalledFnOnce,\n\t\tctxState: { value: ctxState.cache, persist: node.ctxState.persist },\n\t\tversion,\n\t};\n}\n\nfunction isCollectionHelperNonAuthoritative(node: GraphCheckpointNode): boolean {\n\tif (node.factory.kind !== \"registry-ref\") return false;\n\treturn (\n\t\tnode.factory.ref === \"reactiveList.delta\" ||\n\t\tnode.factory.ref === \"reactiveList.snapshot\" ||\n\t\tnode.factory.ref === \"reactiveIndex.delta\" ||\n\t\tnode.factory.ref === \"reactiveIndex.snapshot\" ||\n\t\tnode.factory.ref === \"reactiveLog.delta\" ||\n\t\tnode.factory.ref === \"reactiveLog.snapshot\" ||\n\t\tnode.factory.ref === \"reactiveMap.intent\" ||\n\t\tnode.factory.ref === \"reactiveMap.apply\" ||\n\t\tnode.factory.ref === \"reactiveMap.delta\" ||\n\t\tnode.factory.ref === \"reactiveMap.snapshotPrep\" ||\n\t\tnode.factory.ref === \"reactiveMap.snapshot\"\n\t);\n}\n\nfunction validateFactory(\n\tfactory: GraphCheckpointFactory,\n\tregistry: GraphRestoreRegistry,\n\tid: string,\n): GraphRestoreDescriptor {\n\tif (factory.kind === \"local-only\") {\n\t\tthrow new Error(\n\t\t\t`restoreGraph: node '${id}' uses local-only factory '${factory.name}' (${factory.reason})`,\n\t\t);\n\t}\n\tconst ref = assertString(factory.ref, `factory ref for node '${id}'`);\n\tconst entry = registryGet(registry, ref);\n\tif (!isRestoreDescriptor(entry)) {\n\t\tthrow new Error(`restoreGraph: missing registry descriptor for '${ref}' (node '${id}')`);\n\t}\n\tconst descriptor = entry;\n\tif (descriptor.ref !== ref) {\n\t\tthrow new Error(\n\t\t\t`restoreGraph: registry descriptor for '${ref}' reports ref '${descriptor.ref}'`,\n\t\t);\n\t}\n\tif (factory.config !== undefined) toCheckpointJson(factory.config, `${id}.factory.config`);\n\tif (factory.configVersion !== undefined)\n\t\ttoCheckpointJson(factory.configVersion, `${id}.factory.configVersion`);\n\treturn descriptor;\n}\n\nfunction resolveDefinition<S, T>(\n\tregistry: GraphRestoreRegistry,\n\tref: string,\n\tnodeId: string,\n): GraphRestoreDefinition<S, T> {\n\tconst entry = registryGet(registry, ref);\n\tif (!isRestoreDefinition(entry)) {\n\t\tthrow new Error(`restoreGraph: missing function definition for '${ref}' (node '${nodeId}')`);\n\t}\n\treturn entry as GraphRestoreDefinition<S, T>;\n}\n\nfunction prepareCheckpoint(\n\tcheckpoint: GraphCheckpoint,\n\tregistry: GraphRestoreRegistry,\n\tpath = \"checkpoint\",\n\tmountAt?: string,\n): PreparedCheckpoint {\n\tif (checkpoint.version !== GRAPH_CHECKPOINT_VERSION) {\n\t\tthrow new Error(`restoreGraph: unsupported checkpoint version at ${path}`);\n\t}\n\ttoCheckpointJson(checkpoint, path);\n\tconst nodes = new Map<string, PreparedNode>();\n\tconst localIds = new Set<string>();\n\tfor (const node of checkpoint.nodes) {\n\t\tassertString(node.id, `${path}.nodes[].id`);\n\t\tif (nodes.has(node.id)) throw new Error(`restoreGraph: duplicate node id '${node.id}'`);\n\t\tif (mountAt !== undefined && node.id.startsWith(`${mountAt}::`)) {\n\t\t\tthrow new Error(\n\t\t\t\t`restoreGraph: mounted checkpoint at '${mountAt}' must use child-local node id '${node.id.slice(`${mountAt}::`.length)}', not '${node.id}'`,\n\t\t\t);\n\t\t}\n\t\tconst id = node.id;\n\t\tif (localIds.has(id)) {\n\t\t\tthrow new Error(`restoreGraph: duplicate restored local node id '${id}'`);\n\t\t}\n\t\tlocalIds.add(id);\n\t\tconst factory = node.factory;\n\t\tconst descriptor = validateFactory(factory, registry, node.id);\n\t\tconst rawConfig = factory.kind === \"registry-ref\" ? factory.config : undefined;\n\t\tconst configVersion = factory.kind === \"registry-ref\" ? factory.configVersion : undefined;\n\t\tconst config = descriptor.validateConfig\n\t\t\t? descriptor.validateConfig(rawConfig, configVersion, node)\n\t\t\t: rawConfig;\n\t\tassertStatus(node.status, node.id);\n\t\tnodes.set(node.id, {\n\t\t\tcheckpoint: node,\n\t\t\tlocalId: id,\n\t\t\tdescriptor,\n\t\t\tconfig,\n\t\t\truntime: prepareRuntime(node),\n\t\t\tdeps: node.deps.map((dep, i) => assertString(dep, `${node.id}.deps[${i}]`)),\n\t\t});\n\t}\n\tfor (const prepared of nodes.values()) {\n\t\tfor (const dep of prepared.deps) {\n\t\t\tif (!nodes.has(dep)) {\n\t\t\t\tthrow new Error(`restoreGraph: node '${prepared.checkpoint.id}' has missing dep '${dep}'`);\n\t\t\t}\n\t\t}\n\t}\n\tconst edgeKeys = new Set<string>();\n\tfor (const edge of checkpoint.edges) {\n\t\tconst edgeKey = `${edge.from}\\u0000${edge.to}`;\n\t\tif (edgeKeys.has(edgeKey)) {\n\t\t\tthrow new Error(`restoreGraph: duplicate edge '${edge.from}' -> '${edge.to}'`);\n\t\t}\n\t\tedgeKeys.add(edgeKey);\n\t\tif (!nodes.has(edge.from) || !nodes.has(edge.to)) {\n\t\t\tthrow new Error(\n\t\t\t\t`restoreGraph: edge '${edge.from}' -> '${edge.to}' references a missing node`,\n\t\t\t);\n\t\t}\n\t\tconst target = nodes.get(edge.to) as PreparedNode;\n\t\tif (!target.deps.includes(edge.from)) {\n\t\t\tthrow new Error(\n\t\t\t\t`restoreGraph: edge '${edge.from}' -> '${edge.to}' is not present in target deps`,\n\t\t\t);\n\t\t}\n\t}\n\tfor (const prepared of nodes.values()) {\n\t\tfor (const dep of prepared.deps) {\n\t\t\tif (!edgeKeys.has(`${dep}\\u0000${prepared.checkpoint.id}`)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`restoreGraph: node '${prepared.checkpoint.id}' dep '${dep}' is missing its edge`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\tconst mountPaths = new Set<string>();\n\tconst mounts: PreparedCheckpoint[\"mounts\"] = [];\n\tfor (const mount of checkpoint.mounts ?? []) {\n\t\tconst at = assertString(mount.at, `${path}.mounts[].at`);\n\t\tif (at.length === 0) throw new Error(\"restoreGraph: mount path must not be empty\");\n\t\tif (mountPaths.has(at)) throw new Error(`restoreGraph: duplicate mount path '${at}'`);\n\t\tmountPaths.add(at);\n\t\tmounts.push({\n\t\t\tat,\n\t\t\tprepared: prepareCheckpoint(mount.checkpoint, registry, `${path}.mounts.${at}`, at),\n\t\t});\n\t}\n\treturn { checkpoint, nodes, mounts };\n}\n\nfunction constructPrepared(\n\tprepared: PreparedCheckpoint,\n\tregistry: GraphRestoreRegistry,\n\tdispatcher?: Dispatcher,\n\tversioning?: NodeVersioningPolicy,\n): Graph {\n\tconst out = graph({ name: prepared.checkpoint.name, dispatcher, versioning });\n\ttry {\n\t\tconst built = new Map<string, Node<unknown>>();\n\t\tconst visiting = new Set<string>();\n\n\t\tconst buildNode = (id: string): Node<unknown> => {\n\t\t\tconst existing = built.get(id);\n\t\t\tif (existing) return existing;\n\t\t\tconst item = prepared.nodes.get(id);\n\t\t\tif (item === undefined) throw new Error(`restoreGraph: missing prepared node '${id}'`);\n\t\t\tif (visiting.has(id)) throw new Error(`restoreGraph: dependency cycle at '${id}'`);\n\t\t\tvisiting.add(id);\n\t\t\tconst deps = item.deps.map(buildNode);\n\t\t\tconst node = item.descriptor.create({\n\t\t\t\tgraph: out,\n\t\t\t\tid: item.localId,\n\t\t\t\tname: item.checkpoint.name,\n\t\t\t\tdeps,\n\t\t\t\tconfig: item.config,\n\t\t\t\tconfigVersion:\n\t\t\t\t\titem.checkpoint.factory.kind === \"registry-ref\"\n\t\t\t\t\t\t? item.checkpoint.factory.configVersion\n\t\t\t\t\t\t: undefined,\n\t\t\t\tcheckpoint: item.checkpoint,\n\t\t\t\tresolveDefinition: (ref) => resolveDefinition(registry, ref, item.checkpoint.id),\n\t\t\t\tregisterState: (opts) => restoreStateNodeInGraph(out, item.localId, opts),\n\t\t\t\tregisterNode: (factory, nodeDeps, fn, opts) =>\n\t\t\t\t\trestoreNodeInGraph(out, item.localId, factory, nodeDeps, fn, opts),\n\t\t\t});\n\t\t\tif (out.find(item.localId) !== node) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`restoreGraph: descriptor '${item.descriptor.ref}' did not register node '${item.localId}'`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (node.deps.length !== deps.length || node.deps.some((dep, i) => dep !== deps[i])) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`restoreGraph: descriptor '${item.descriptor.ref}' registered node '${item.localId}' with deps that do not match the checkpoint`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tbuilt.set(id, node);\n\t\t\tvisiting.delete(id);\n\t\t\treturn node;\n\t\t};\n\n\t\tfor (const id of prepared.nodes.keys()) buildNode(id);\n\n\t\tfor (const mount of prepared.mounts) {\n\t\t\tout.mount(constructPrepared(mount.prepared, registry, dispatcher, versioning), {\n\t\t\t\tat: mount.at,\n\t\t\t});\n\t\t}\n\n\t\tfor (const [id, node] of built) {\n\t\t\tconst runtime = (prepared.nodes.get(id) as PreparedNode).runtime;\n\t\t\trestoreStateOfNode(node, {\n\t\t\t\tcache: runtime.cache,\n\t\t\t\thasData: runtime.hasData,\n\t\t\t\tstatus: runtime.status,\n\t\t\t\tterminal: runtime.terminal,\n\t\t\t\thasCalledFnOnce: runtime.hasCalledFnOnce,\n\t\t\t\tctxState: runtime.ctxState,\n\t\t\t\tversion: runtime.version,\n\t\t\t});\n\t\t}\n\t} finally {\n\t\tclearRestoredCollectionMap(out);\n\t}\n\n\treturn out;\n}\n\nexport function restoreGraph(checkpoint: GraphCheckpoint, options: RestoreGraphOptions): Graph {\n\tif (options == null || options.registry === undefined) {\n\t\tthrow new Error(\"restoreGraph: registry is required\");\n\t}\n\tif (\n\t\t!(options.registry instanceof Map) &&\n\t\t(typeof options.registry !== \"object\" || options.registry === null)\n\t) {\n\t\tthrow new Error(\"restoreGraph: registry must be a Map or object\");\n\t}\n\tfor (const key of Object.keys(options)) {\n\t\tif (key !== \"registry\" && key !== \"dispatcher\" && key !== \"versioning\") {\n\t\t\tthrow new Error(`restoreGraph: unknown option '${key}'`);\n\t\t}\n\t}\n\tconst prepared = prepareCheckpoint(checkpoint, options.registry);\n\treturn constructPrepared(prepared, options.registry, options.dispatcher, options.versioning);\n}\n","/**\n * Helper-first worker compute (D138/D148).\n *\n * `prepare` runs on the graph thread and returns an owned input. The required\n * backend receives only that input plus the static compute closure; Ctx/Node/\n * graph state/live topology never cross the boundary.\n */\n\nimport type { Ctx, NodeFn } from \"../ctx/types.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport { errorPayload } from \"../protocol/messages.js\";\n\nexport interface WorkerDerivedJob<TInput, TResult> {\n\treadonly input: TInput;\n\treadonly compute: (input: TInput) => TResult;\n}\n\nexport type WorkerDerivedSettlement<TResult> =\n\t| { readonly ok: true; readonly value: TResult }\n\t| { readonly ok: false; readonly error: unknown };\n\nexport type WorkerDerivedSettle<TResult> = (settlement: WorkerDerivedSettlement<TResult>) => void;\n\nexport type WorkerDerivedCancel = () => void;\n\nexport interface WorkerDerivedBackend<TInput, TResult> {\n\trun(\n\t\tjob: WorkerDerivedJob<TInput, TResult>,\n\t\tsettle: WorkerDerivedSettle<TResult>,\n\t): WorkerDerivedCancel | undefined;\n}\n\nexport interface WorkerDerivedOptions<TInput, TResult> {\n\treadonly name?: string;\n\tprepare(ctx: Ctx): TInput | undefined;\n\tcompute(input: TInput): TResult;\n\tbackend: WorkerDerivedBackend<TInput, TResult>;\n}\n\n/**\n * D148 backend-required graph helper. No public submit API is exposed; the\n * backend starts work only after this helper installs the graph-local fence.\n */\nexport function workerDerived<TInput, TResult>(\n\tgraph: Graph,\n\tdeps: readonly Node<unknown>[],\n\topts: WorkerDerivedOptions<TInput, TResult>,\n): Node<TResult> {\n\tif (typeof opts.prepare !== \"function\") {\n\t\tthrow new TypeError(\"workerDerived: prepare must be a function\");\n\t}\n\tif (typeof opts.compute !== \"function\") {\n\t\tthrow new TypeError(\"workerDerived: compute must be a function\");\n\t}\n\tif (opts.backend === undefined || typeof opts.backend.run !== \"function\") {\n\t\tthrow new TypeError(\"workerDerived: backend is required\");\n\t}\n\tlet latestInvocation = 0;\n\tlet cancelActive: (() => void) | undefined;\n\tconst fn: NodeFn = (ctx) => {\n\t\tcancelActive?.();\n\t\tcancelActive = undefined;\n\t\tlatestInvocation += 1;\n\t\tconst invocation = latestInvocation;\n\t\tlet input: TInput | undefined;\n\t\ttry {\n\t\t\tinput = opts.prepare(ctx);\n\t\t} catch (error) {\n\t\t\tctx.down([[\"ERROR\", errorPayload(error, \"workerDerived prepare failed\")]]);\n\t\t\treturn;\n\t\t}\n\t\tif (input === undefined) {\n\t\t\tctx.down([[\"RESOLVED\"]]);\n\t\t\treturn;\n\t\t}\n\t\tconst ownedInput = cloneWorkerInput(input);\n\t\tif (!ownedInput.ok) {\n\t\t\tctx.down([[\"ERROR\", errorPayload(new Error(ownedInput.message), ownedInput.message)]]);\n\t\t\treturn;\n\t\t}\n\t\tlet live = true;\n\t\tlet cancel: WorkerDerivedCancel | undefined;\n\t\tlet canceled = false;\n\t\tlet submitting = true;\n\t\tlet settled = false;\n\t\tlet synchronousSettlementError: Error | undefined;\n\t\tconst cancelThis = (): void => {\n\t\t\tif (canceled) return;\n\t\t\tcanceled = true;\n\t\t\tlive = false;\n\t\t\tcancel?.();\n\t\t\tcancel = undefined;\n\t\t};\n\t\tcancelActive = cancelThis;\n\t\tctx.onDeactivation(() => {\n\t\t\tcancelThis();\n\t\t\tif (cancelActive === cancelThis) cancelActive = undefined;\n\t\t});\n\t\tconst assertNotSynchronousCompletion = (): void => {\n\t\t\tif (submitting) {\n\t\t\t\tsynchronousSettlementError = new Error(\n\t\t\t\t\t\"workerDerived: backend completions must arrive after backend.run returns\",\n\t\t\t\t);\n\t\t\t\tthrow synchronousSettlementError;\n\t\t\t}\n\t\t};\n\t\tconst clearAcceptedSettlement = (): void => {\n\t\t\tcancelActive = undefined;\n\t\t\tcancel = undefined;\n\t\t\tlive = false;\n\t\t};\n\t\tconst settle: WorkerDerivedSettle<TResult> = (settlement) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tassertNotSynchronousCompletion();\n\t\t\tif (!live || invocation !== latestInvocation) return;\n\t\t\tclearAcceptedSettlement();\n\t\t\tif (settlement.ok) {\n\t\t\t\tctx.down([[\"DATA\", settlement.value]]);\n\t\t\t} else {\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(settlement.error, \"workerDerived compute failed\")]]);\n\t\t\t}\n\t\t};\n\t\tlet thrown = false;\n\t\tlet thrownError: unknown;\n\t\ttry {\n\t\t\tcancel =\n\t\t\t\topts.backend.run(\n\t\t\t\t\t{\n\t\t\t\t\t\tinput: ownedInput.value,\n\t\t\t\t\t\tcompute: opts.compute,\n\t\t\t\t\t},\n\t\t\t\t\tsettle,\n\t\t\t\t) ?? undefined;\n\t\t} catch (error) {\n\t\t\tthrown = true;\n\t\t\tthrownError = error;\n\t\t} finally {\n\t\t\tsubmitting = false;\n\t\t}\n\t\tif (synchronousSettlementError !== undefined) {\n\t\t\tif (live && invocation === latestInvocation) {\n\t\t\t\tctx.down([\n\t\t\t\t\t[\"ERROR\", errorPayload(synchronousSettlementError, \"workerDerived compute failed\")],\n\t\t\t\t]);\n\t\t\t}\n\t\t\tcancelThis();\n\t\t\tif (cancelActive === cancelThis) cancelActive = undefined;\n\t\t\treturn;\n\t\t}\n\t\tif (thrown) {\n\t\t\tif (live && invocation === latestInvocation) {\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(thrownError, \"workerDerived compute failed\")]]);\n\t\t\t}\n\t\t\tcancelThis();\n\t\t\tif (cancelActive === cancelThis) cancelActive = undefined;\n\t\t}\n\t};\n\treturn graph.node<TResult>(deps, fn, {\n\t\tname: opts.name ?? \"workerDerived\",\n\t\tfactory: \"workerDerived\",\n\t\tpool: \"async\",\n\t\tcompleteWhenDepsComplete: false,\n\t\terrorWhenDepsError: false,\n\t});\n}\n\ntype CloneWorkerInputResult<TInput> =\n\t| { readonly ok: true; readonly value: TInput }\n\t| { readonly ok: false; readonly message: string };\n\nfunction cloneWorkerInput<TInput>(input: TInput): CloneWorkerInputResult<TInput> {\n\tif (typeof input === \"function\" || typeof input === \"symbol\") {\n\t\treturn { ok: false, message: \"workerDerived: input must be owned and cloneable\" };\n\t}\n\tif (typeof input !== \"object\" || input === null) return { ok: true, value: input };\n\tif (typeof globalThis.structuredClone !== \"function\") {\n\t\treturn { ok: false, message: \"workerDerived: structuredClone is required for object inputs\" };\n\t}\n\ttry {\n\t\treturn { ok: true, value: globalThis.structuredClone(input) as TInput };\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\treturn {\n\t\t\tok: false,\n\t\t\tmessage: `workerDerived: input must be owned and cloneable (${message})`,\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwHO,SAAS,uBACf,MAC+B;AAC/B,QAAM;AAAA,IACL,OAAO;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD,IAAI;AACJ,QAAM,YAA6B,CAAC,OAAO;AAC3C,QAAM,cAAc,WAAW,SAAY,KAAK,UAAU,KAAK,MAAM,IAAI;AACzE,QAAM,kBAAkB,eAAe,SAAY,KAAK,UAAU,KAAK,UAAU,IAAI;AACrF,QAAM,WAAW,QAAQ;AACzB,QAAM,YAAkD;AAAA,IACvD,MAAM,GAAG,QAAQ;AAAA,IACjB;AAAA,IACA,SAAS;AAAA,IACT,MAAM;AAAA,EACP;AACA,QAAM,SAAS,EAAE;AAAA,IAChB;AAAA,IACA,CAAC,QAAQ;AACR,YAAM,KAAK,IAAI,MAAM,IAAoB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A,EACvE,SAAS,OAAO;AACf,UAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,WAAO;AAAA,MACN,IAAI;AAAA,MACJ,SAAS,qDAAqD,OAAO;AAAA,IACtE;AAAA,EACD;AACD;","names":["map","truncated","graph","map","graph"]}
@@ -0,0 +1,149 @@
1
+ import {
2
+ hasKvVersioned
3
+ } from "./chunk-DKP56CSW.js";
4
+
5
+ // src/storage/read-through.ts
6
+ function defer(fn) {
7
+ return Promise.resolve().then(fn);
8
+ }
9
+ function readThroughKv(opts) {
10
+ return tieredReadThrough(opts);
11
+ }
12
+ function tieredReadThrough(opts) {
13
+ const { key, tiers, tierNames = [], load, promoteTo, onMiss, onError } = opts;
14
+ const lookupFacts = [];
15
+ const promotions = [];
16
+ let hitTier;
17
+ let value;
18
+ const safeOnMiss = (tier) => {
19
+ if (!onMiss) return;
20
+ try {
21
+ onMiss({ key, tier });
22
+ } catch {
23
+ }
24
+ };
25
+ const safeOnError = (context) => {
26
+ if (!onError) return;
27
+ try {
28
+ onError(context);
29
+ } catch {
30
+ }
31
+ };
32
+ const addFact = (fact) => {
33
+ lookupFacts.push(fact);
34
+ };
35
+ const lookupTier = (index) => ({
36
+ index,
37
+ name: tierNames[index]
38
+ });
39
+ const lookupNext = (index) => {
40
+ if (hitTier !== void 0 || index >= tiers.length) return defer(() => void 0);
41
+ const tier = tiers[index];
42
+ const info = lookupTier(index);
43
+ const read = hasKvVersioned(tier) ? defer(() => tier.getVersioned(key)).then((result2) => {
44
+ if (result2.kind === "miss") {
45
+ return { found: void 0, generation: result2.generation };
46
+ }
47
+ return { found: result2.value, generation: result2.generation };
48
+ }) : defer(() => tier.get(key)).then((found) => ({ found, generation: void 0 }));
49
+ return read.then(({ found, generation }) => {
50
+ if (found === void 0) {
51
+ addFact({ kind: "miss", key, tier: info, generation });
52
+ safeOnMiss(info);
53
+ return lookupNext(index + 1);
54
+ }
55
+ addFact({ kind: "hit", key, tier: info, value: found, generation });
56
+ hitTier = info;
57
+ value = found;
58
+ }).catch((error) => {
59
+ addFact({ kind: "error", key, tier: info, error });
60
+ safeOnError({ key, tier: info, stage: "lookup", error });
61
+ return lookupNext(index + 1);
62
+ });
63
+ };
64
+ const runLoader = () => {
65
+ if (hitTier !== void 0 || typeof load !== "function") return defer(() => void 0);
66
+ const loaderTier = { index: -1, name: "load" };
67
+ return defer(() => load(key)).then((loaded) => {
68
+ if (loaded === void 0) {
69
+ addFact({ kind: "miss", key, tier: loaderTier });
70
+ safeOnMiss(loaderTier);
71
+ return;
72
+ }
73
+ addFact({ kind: "hit", key, tier: loaderTier, value: loaded });
74
+ hitTier = loaderTier;
75
+ value = loaded;
76
+ }).catch((error) => {
77
+ addFact({ kind: "error", key, tier: loaderTier, error });
78
+ safeOnError({ key, tier: loaderTier, stage: "lookup", error });
79
+ });
80
+ };
81
+ const promoteNext = (targets, offset) => {
82
+ if (offset >= targets.length || value === void 0) return defer(() => void 0);
83
+ const index = targets[offset];
84
+ const info = { index, name: tierNames[index] };
85
+ const tier = tiers[index];
86
+ const generation = generationForTier(lookupFacts, index);
87
+ const write = hasKvVersioned(tier) ? generation === void 0 ? defer(() => {
88
+ throw new Error(
89
+ "tieredReadThrough: versioned promotion target was not observed with a generation"
90
+ );
91
+ }) : defer(() => tier.setIfMatch(key, value, generation)) : defer(() => tier.set(key, value)).then(() => true);
92
+ return write.then((ok) => {
93
+ promotions.push({ tier: info, ok });
94
+ }).catch((error) => {
95
+ promotions.push({ tier: info, ok: false, error });
96
+ safeOnError({ key, tier: info, stage: "promotion", error });
97
+ }).then(() => promoteNext(targets, offset + 1));
98
+ };
99
+ const promote = () => {
100
+ if (hitTier === void 0 || value === void 0) return defer(() => void 0);
101
+ const sourceIndex = hitTier.index === -1 ? tiers.length : hitTier.index;
102
+ const targets = buildPromotionTargets(tiers.length, sourceIndex, promoteTo);
103
+ return promoteNext(targets, 0);
104
+ };
105
+ const result = () => {
106
+ const status = (() => {
107
+ if (hitTier !== void 0 && hitTier.index >= -1 && value !== void 0) return "hit";
108
+ if (lookupFacts.some((fact) => fact.kind === "error")) return "error";
109
+ return "miss";
110
+ })();
111
+ return {
112
+ status,
113
+ key,
114
+ value,
115
+ hitTier,
116
+ facts: lookupFacts,
117
+ promotions
118
+ };
119
+ };
120
+ return lookupNext(0).then(runLoader).then(promote).then(result);
121
+ }
122
+ function generationForTier(facts, index) {
123
+ return facts.find((fact) => fact.tier.index === index)?.generation;
124
+ }
125
+ function buildPromotionTargets(tierCount, hitIndex, promoteTo) {
126
+ if (promoteTo === false || tierCount <= 0) return [];
127
+ const maxPromote = Math.max(0, Math.min(hitIndex, tierCount));
128
+ if (promoteTo === void 0) {
129
+ return [...Array(maxPromote).keys()];
130
+ }
131
+ const normalized = [];
132
+ const seen = /* @__PURE__ */ new Set();
133
+ for (const index of promoteTo) {
134
+ if (!Number.isSafeInteger(index) || index < 0 || index >= tierCount || index >= maxPromote) {
135
+ continue;
136
+ }
137
+ if (!seen.has(index)) {
138
+ seen.add(index);
139
+ normalized.push(index);
140
+ }
141
+ }
142
+ return normalized;
143
+ }
144
+
145
+ export {
146
+ readThroughKv,
147
+ tieredReadThrough
148
+ };
149
+ //# sourceMappingURL=chunk-Z2ANQ6JW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/storage/read-through.ts"],"sourcesContent":["import { hasKvVersioned, type KvGeneration, type KvStorageTier } from \"./kv.js\";\n\n/** Result tier for read-through output facts. */\nexport interface ReadThroughLookupTier {\n\t/** Tier index in the ordered lookup list. `-1` = optional loader fallback. */\n\treadonly index: number;\n\t/** Optional human-facing tier name. */\n\treadonly name?: string;\n}\n\n/** Ordered lookup result from a single tier or loader attempt. */\ntype ReadThroughOutcome = \"hit\" | \"miss\" | \"error\";\n\n/** Fact for one lookup attempt (one tier or the optional loader fallback). */\nexport interface ReadThroughLookupFact<T> {\n\treadonly kind: ReadThroughOutcome;\n\treadonly key: string;\n\treadonly tier: ReadThroughLookupTier;\n\treadonly value?: T;\n\treadonly generation?: KvGeneration;\n\treadonly error?: unknown;\n}\n\n/** Result of one promotion write attempt to an earlier tier. */\nexport interface ReadThroughPromotionFact {\n\treadonly tier: ReadThroughLookupTier;\n\treadonly ok: boolean;\n\treadonly error?: unknown;\n}\n\n/** Final read-through outcome, with explicit lookup facts and promotion facts. */\nexport interface TieredReadThroughResult<T> {\n\treadonly status: \"hit\" | \"miss\" | \"error\";\n\treadonly key: string;\n\treadonly value?: T;\n\treadonly hitTier?: ReadThroughLookupTier;\n\treadonly facts: readonly ReadThroughLookupFact<T>[];\n\treadonly promotions: readonly ReadThroughPromotionFact[];\n}\n\n/** Optional hook/context for lookup misses. */\nexport interface ReadThroughMissContext {\n\treadonly key: string;\n\treadonly tier: ReadThroughLookupTier;\n}\n\n/** Optional hook/context for get/load/promotion errors. */\nexport interface ReadThroughErrorContext {\n\treadonly key: string;\n\treadonly tier: ReadThroughLookupTier;\n\treadonly stage: \"lookup\" | \"promotion\";\n\treadonly error: unknown;\n}\n\n/** Configuration for `tieredReadThrough`. */\nexport interface TieredReadThroughOptions<T> {\n\t/** Lookup key for all tiers. */\n\treadonly key: string;\n\t/** Ordered lookup tiers, index 0 = hottest/fastest. */\n\treadonly tiers: readonly KvStorageTier<T>[];\n\t/** Optional friendly tier names, matched by index. */\n\treadonly tierNames?: readonly string[];\n\t/**\n\t * Optional loader fallback for cache-miss. If provided and no tier hits, this runs\n\t * after all tiers are checked and may write-through by promotion logic.\n\t */\n\treadonly load?: (key: string) => Promise<T | undefined> | T | undefined;\n\t/**\n\t * Optional promotion policy: set hit values to earlier (lower-index) tiers.\n\t * `false` disables promotion; default promotes to all earlier tiers on any hit.\n\t * Explicit indices can narrow promotion targets.\n\t */\n\treadonly promoteTo?: readonly number[] | false;\n\t/** Optional callbacks for control-plane observability. */\n\treadonly onMiss?: (context: ReadThroughMissContext) => void;\n\t/** Called for lookup/load errors and promotion failures by default. */\n\treadonly onError?: (context: ReadThroughErrorContext) => void;\n}\n\nfunction defer<T>(fn: () => T | PromiseLike<T>): Promise<T> {\n\treturn Promise.resolve().then(fn);\n}\n\n/** Alias for callers that prefer loader-oriented naming. */\nexport function readThroughKv<T>(\n\topts: TieredReadThroughOptions<T>,\n): Promise<TieredReadThroughResult<T>> {\n\treturn tieredReadThrough(opts);\n}\n\n/**\n * Build explicit lookup facts across tiers plus optional loader fallback (D104 layer 1).\n *\n * This is a passive storage/domain helper: it creates no graph nodes, performs no hydration or\n * restore, and treats promotion writes as facts rather than a graph commit barrier.\n */\nexport function tieredReadThrough<T>(\n\topts: TieredReadThroughOptions<T>,\n): Promise<TieredReadThroughResult<T>> {\n\tconst { key, tiers, tierNames = [], load, promoteTo, onMiss, onError } = opts;\n\n\tconst lookupFacts: ReadThroughLookupFact<T>[] = [];\n\tconst promotions: ReadThroughPromotionFact[] = [];\n\tlet hitTier: ReadThroughLookupTier | undefined;\n\tlet value: T | undefined;\n\n\tconst safeOnMiss = (tier: ReadThroughLookupTier): void => {\n\t\tif (!onMiss) return;\n\t\ttry {\n\t\t\tonMiss({ key, tier });\n\t\t} catch {\n\t\t\t/* no-op */\n\t\t}\n\t};\n\n\tconst safeOnError = (context: ReadThroughErrorContext): void => {\n\t\tif (!onError) return;\n\t\ttry {\n\t\t\tonError(context);\n\t\t} catch {\n\t\t\t/* no-op */\n\t\t}\n\t};\n\n\tconst addFact = (fact: ReadThroughLookupFact<T>): void => {\n\t\tlookupFacts.push(fact);\n\t};\n\n\tconst lookupTier = (index: number): ReadThroughLookupTier => ({\n\t\tindex,\n\t\tname: tierNames[index],\n\t});\n\n\tconst lookupNext = (index: number): Promise<void> => {\n\t\tif (hitTier !== undefined || index >= tiers.length) return defer(() => undefined);\n\t\tconst tier = tiers[index]!;\n\t\tconst info = lookupTier(index);\n\t\tconst read = hasKvVersioned(tier)\n\t\t\t? defer(() => tier.getVersioned(key)).then((result) => {\n\t\t\t\t\tif (result.kind === \"miss\") {\n\t\t\t\t\t\treturn { found: undefined, generation: result.generation } as const;\n\t\t\t\t\t}\n\t\t\t\t\treturn { found: result.value, generation: result.generation } as const;\n\t\t\t\t})\n\t\t\t: defer(() => tier.get(key)).then((found) => ({ found, generation: undefined }) as const);\n\t\treturn read\n\t\t\t.then(({ found, generation }) => {\n\t\t\t\tif (found === undefined) {\n\t\t\t\t\taddFact({ kind: \"miss\", key, tier: info, generation });\n\t\t\t\t\tsafeOnMiss(info);\n\t\t\t\t\treturn lookupNext(index + 1);\n\t\t\t\t}\n\t\t\t\taddFact({ kind: \"hit\", key, tier: info, value: found, generation });\n\t\t\t\thitTier = info;\n\t\t\t\tvalue = found;\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\taddFact({ kind: \"error\", key, tier: info, error });\n\t\t\t\tsafeOnError({ key, tier: info, stage: \"lookup\", error });\n\t\t\t\treturn lookupNext(index + 1);\n\t\t\t});\n\t};\n\n\tconst runLoader = (): Promise<void> => {\n\t\tif (hitTier !== undefined || typeof load !== \"function\") return defer(() => undefined);\n\t\tconst loaderTier: ReadThroughLookupTier = { index: -1, name: \"load\" };\n\t\treturn defer(() => load(key))\n\t\t\t.then((loaded) => {\n\t\t\t\tif (loaded === undefined) {\n\t\t\t\t\taddFact({ kind: \"miss\", key, tier: loaderTier });\n\t\t\t\t\tsafeOnMiss(loaderTier);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\taddFact({ kind: \"hit\", key, tier: loaderTier, value: loaded });\n\t\t\t\thitTier = loaderTier;\n\t\t\t\tvalue = loaded;\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\taddFact({ kind: \"error\", key, tier: loaderTier, error });\n\t\t\t\tsafeOnError({ key, tier: loaderTier, stage: \"lookup\", error });\n\t\t\t});\n\t};\n\n\tconst promoteNext = (targets: readonly number[], offset: number): Promise<void> => {\n\t\tif (offset >= targets.length || value === undefined) return defer(() => undefined);\n\t\tconst index = targets[offset]!;\n\t\tconst info = { index, name: tierNames[index] };\n\t\tconst tier = tiers[index]!;\n\t\tconst generation = generationForTier(lookupFacts, index);\n\t\tconst write = hasKvVersioned(tier)\n\t\t\t? generation === undefined\n\t\t\t\t? defer<boolean>(() => {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\"tieredReadThrough: versioned promotion target was not observed with a generation\",\n\t\t\t\t\t\t);\n\t\t\t\t\t})\n\t\t\t\t: defer(() => tier.setIfMatch(key, value as T, generation))\n\t\t\t: defer(() => tier.set(key, value as T)).then(() => true);\n\t\treturn write\n\t\t\t.then((ok) => {\n\t\t\t\tpromotions.push({ tier: info, ok });\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tpromotions.push({ tier: info, ok: false, error });\n\t\t\t\tsafeOnError({ key, tier: info, stage: \"promotion\", error });\n\t\t\t})\n\t\t\t.then(() => promoteNext(targets, offset + 1));\n\t};\n\n\tconst promote = (): Promise<void> => {\n\t\tif (hitTier === undefined || value === undefined) return defer(() => undefined);\n\t\tconst sourceIndex = hitTier.index === -1 ? tiers.length : hitTier.index;\n\t\tconst targets = buildPromotionTargets(tiers.length, sourceIndex, promoteTo);\n\t\treturn promoteNext(targets, 0);\n\t};\n\n\tconst result = (): TieredReadThroughResult<T> => {\n\t\tconst status: TieredReadThroughResult<T>[\"status\"] = (() => {\n\t\t\tif (hitTier !== undefined && hitTier.index >= -1 && value !== undefined) return \"hit\";\n\t\t\tif (lookupFacts.some((fact) => fact.kind === \"error\")) return \"error\";\n\t\t\treturn \"miss\";\n\t\t})();\n\n\t\treturn {\n\t\t\tstatus,\n\t\t\tkey,\n\t\t\tvalue,\n\t\t\thitTier,\n\t\t\tfacts: lookupFacts,\n\t\t\tpromotions,\n\t\t};\n\t};\n\n\treturn lookupNext(0).then(runLoader).then(promote).then(result);\n}\n\nfunction generationForTier<T>(\n\tfacts: readonly ReadThroughLookupFact<T>[],\n\tindex: number,\n): KvGeneration | undefined {\n\treturn facts.find((fact) => fact.tier.index === index)?.generation;\n}\n\nfunction buildPromotionTargets(\n\ttierCount: number,\n\thitIndex: number,\n\tpromoteTo?: readonly number[] | false,\n): number[] {\n\tif (promoteTo === false || tierCount <= 0) return [];\n\tconst maxPromote = Math.max(0, Math.min(hitIndex, tierCount));\n\tif (promoteTo === undefined) {\n\t\treturn [...Array(maxPromote).keys()];\n\t}\n\tconst normalized: number[] = [];\n\tconst seen = new Set<number>();\n\tfor (const index of promoteTo) {\n\t\tif (!Number.isSafeInteger(index) || index < 0 || index >= tierCount || index >= maxPromote) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!seen.has(index)) {\n\t\t\tseen.add(index);\n\t\t\tnormalized.push(index);\n\t\t}\n\t}\n\treturn normalized;\n}\n"],"mappings":";;;;;AA+EA,SAAS,MAAS,IAA0C;AAC3D,SAAO,QAAQ,QAAQ,EAAE,KAAK,EAAE;AACjC;AAGO,SAAS,cACf,MACsC;AACtC,SAAO,kBAAkB,IAAI;AAC9B;AAQO,SAAS,kBACf,MACsC;AACtC,QAAM,EAAE,KAAK,OAAO,YAAY,CAAC,GAAG,MAAM,WAAW,QAAQ,QAAQ,IAAI;AAEzE,QAAM,cAA0C,CAAC;AACjD,QAAM,aAAyC,CAAC;AAChD,MAAI;AACJ,MAAI;AAEJ,QAAM,aAAa,CAAC,SAAsC;AACzD,QAAI,CAAC,OAAQ;AACb,QAAI;AACH,aAAO,EAAE,KAAK,KAAK,CAAC;AAAA,IACrB,QAAQ;AAAA,IAER;AAAA,EACD;AAEA,QAAM,cAAc,CAAC,YAA2C;AAC/D,QAAI,CAAC,QAAS;AACd,QAAI;AACH,cAAQ,OAAO;AAAA,IAChB,QAAQ;AAAA,IAER;AAAA,EACD;AAEA,QAAM,UAAU,CAAC,SAAyC;AACzD,gBAAY,KAAK,IAAI;AAAA,EACtB;AAEA,QAAM,aAAa,CAAC,WAA0C;AAAA,IAC7D;AAAA,IACA,MAAM,UAAU,KAAK;AAAA,EACtB;AAEA,QAAM,aAAa,CAAC,UAAiC;AACpD,QAAI,YAAY,UAAa,SAAS,MAAM,OAAQ,QAAO,MAA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;","names":["result"]}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Neutral JSON/encoding utilities (D96).
3
+ *
4
+ * Shared by graph checkpoints and storage bindings; neither layer owns the strict JSON
5
+ * scanner/canonicalization contract.
6
+ */
7
+ /** Typed byte codec for D82 storage binding helpers and D96 shared JSON surfaces. */
8
+ interface Codec<T> {
9
+ encode(value: T): Uint8Array;
10
+ decode(bytes: Uint8Array): T;
11
+ }
12
+ type StrictJsonScalar = null | boolean | number | string;
13
+ type StrictJsonValue = StrictJsonScalar | readonly StrictJsonValue[] | {
14
+ readonly [key: string]: StrictJsonValue;
15
+ };
16
+ type StrictJsonObject = Readonly<Record<string, StrictJsonValue>>;
17
+ /** Stable JSON string: object keys sort by code-unit order for deterministic storage/checkpoint bytes. */
18
+ declare function stableJsonString(value: unknown): string;
19
+ /** Build a JSON codec using stable object-key ordering. */
20
+ declare function jsonCodecFor<T>(): Codec<T>;
21
+ /** Default stable JSON codec for unknown values. */
22
+ declare const jsonCodec: Codec<unknown>;
23
+ /**
24
+ * Build a strict canonical JSON codec (D84/D87/D96).
25
+ * The strict surface rejects malformed UTF-8, duplicate object keys, non-canonical bytes,
26
+ * unpaired surrogates, and values that cannot round-trip through stable JSON.
27
+ */
28
+ declare function strictJsonCodecFor<T>(): Codec<T>;
29
+ /** Default strict canonical JSON codec for unknown values. */
30
+ declare const strictJsonCodec: Codec<unknown>;
31
+ /** D113 neutral helper for strict canonical JSON UTF-8 bytes. */
32
+ declare function strictCanonicalJsonBytes(value: unknown): Uint8Array;
33
+ /** Validate and normalize a host value into strict canonical JSON data. */
34
+ declare function assertStrictJsonValue(value: unknown, label?: string): StrictJsonValue;
35
+ /** Validate and normalize a host value into a strict canonical JSON object. */
36
+ declare function assertStrictJsonObject(value: unknown, label?: string): StrictJsonObject;
37
+
38
+ export { type Codec as C, type StrictJsonObject as S, type StrictJsonScalar as a, type StrictJsonValue as b, assertStrictJsonObject as c, assertStrictJsonValue as d, jsonCodecFor as e, strictCanonicalJsonBytes as f, strictJsonCodec as g, strictJsonCodecFor as h, jsonCodec as j, stableJsonString as s };
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Neutral JSON/encoding utilities (D96).
3
+ *
4
+ * Shared by graph checkpoints and storage bindings; neither layer owns the strict JSON
5
+ * scanner/canonicalization contract.
6
+ */
7
+ /** Typed byte codec for D82 storage binding helpers and D96 shared JSON surfaces. */
8
+ interface Codec<T> {
9
+ encode(value: T): Uint8Array;
10
+ decode(bytes: Uint8Array): T;
11
+ }
12
+ type StrictJsonScalar = null | boolean | number | string;
13
+ type StrictJsonValue = StrictJsonScalar | readonly StrictJsonValue[] | {
14
+ readonly [key: string]: StrictJsonValue;
15
+ };
16
+ type StrictJsonObject = Readonly<Record<string, StrictJsonValue>>;
17
+ /** Stable JSON string: object keys sort by code-unit order for deterministic storage/checkpoint bytes. */
18
+ declare function stableJsonString(value: unknown): string;
19
+ /** Build a JSON codec using stable object-key ordering. */
20
+ declare function jsonCodecFor<T>(): Codec<T>;
21
+ /** Default stable JSON codec for unknown values. */
22
+ declare const jsonCodec: Codec<unknown>;
23
+ /**
24
+ * Build a strict canonical JSON codec (D84/D87/D96).
25
+ * The strict surface rejects malformed UTF-8, duplicate object keys, non-canonical bytes,
26
+ * unpaired surrogates, and values that cannot round-trip through stable JSON.
27
+ */
28
+ declare function strictJsonCodecFor<T>(): Codec<T>;
29
+ /** Default strict canonical JSON codec for unknown values. */
30
+ declare const strictJsonCodec: Codec<unknown>;
31
+ /** D113 neutral helper for strict canonical JSON UTF-8 bytes. */
32
+ declare function strictCanonicalJsonBytes(value: unknown): Uint8Array;
33
+ /** Validate and normalize a host value into strict canonical JSON data. */
34
+ declare function assertStrictJsonValue(value: unknown, label?: string): StrictJsonValue;
35
+ /** Validate and normalize a host value into a strict canonical JSON object. */
36
+ declare function assertStrictJsonObject(value: unknown, label?: string): StrictJsonObject;
37
+
38
+ export { type Codec as C, type StrictJsonObject as S, type StrictJsonScalar as a, type StrictJsonValue as b, assertStrictJsonObject as c, assertStrictJsonValue as d, jsonCodecFor as e, strictCanonicalJsonBytes as f, strictJsonCodec as g, strictJsonCodecFor as h, jsonCodec as j, stableJsonString as s };