@graphrefly/ts 0.0.0 → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (307) hide show
  1. package/README.md +135 -0
  2. package/dist/adapters/index.cjs +105 -66
  3. package/dist/adapters/index.cjs.map +1 -1
  4. package/dist/adapters/index.d.cts +11 -136
  5. package/dist/adapters/index.d.ts +11 -136
  6. package/dist/adapters/index.js +27 -225
  7. package/dist/adapters/index.js.map +1 -1
  8. package/dist/adapters/observe-storage.d.cts +4 -4
  9. package/dist/adapters/observe-storage.d.ts +4 -4
  10. package/dist/adapters/observe-storage.js +1 -0
  11. package/dist/adapters/observe-storage.js.map +1 -1
  12. package/dist/adapters/react.cjs +166 -0
  13. package/dist/adapters/react.cjs.map +1 -0
  14. package/dist/adapters/react.d.cts +31 -0
  15. package/dist/adapters/react.d.ts +31 -0
  16. package/dist/adapters/react.js +51 -0
  17. package/dist/adapters/react.js.map +1 -0
  18. package/dist/adapters/solid.cjs +157 -0
  19. package/dist/adapters/solid.cjs.map +1 -0
  20. package/dist/adapters/solid.d.cts +26 -0
  21. package/dist/adapters/solid.d.ts +26 -0
  22. package/dist/adapters/solid.js +48 -0
  23. package/dist/adapters/solid.js.map +1 -0
  24. package/dist/adapters/svelte.cjs +148 -0
  25. package/dist/adapters/svelte.cjs.map +1 -0
  26. package/dist/adapters/svelte.d.cts +31 -0
  27. package/dist/adapters/svelte.d.ts +31 -0
  28. package/dist/adapters/svelte.js +46 -0
  29. package/dist/adapters/svelte.js.map +1 -0
  30. package/dist/adapters/vue.cjs +155 -0
  31. package/dist/adapters/vue.cjs.map +1 -0
  32. package/dist/adapters/vue.d.cts +26 -0
  33. package/dist/adapters/vue.d.ts +26 -0
  34. package/dist/adapters/vue.js +46 -0
  35. package/dist/adapters/vue.js.map +1 -0
  36. package/dist/agent-runtime-BesGDZcB.d.ts +555 -0
  37. package/dist/agent-runtime-DZTJ3C-p.d.cts +555 -0
  38. package/dist/agentic-memory-BmRCvh0d.d.ts +517 -0
  39. package/dist/agentic-memory-DfuVZ-lY.d.cts +517 -0
  40. package/dist/capability-admission-B0BzqAm5.d.cts +102 -0
  41. package/dist/capability-admission-g0mn9hpq.d.ts +102 -0
  42. package/dist/{chunk-JR4IKCR2.js → chunk-2747WN4Y.js} +5 -5
  43. package/dist/{chunk-2ILL7HQI.js → chunk-3JR3EDB2.js} +17 -17
  44. package/dist/{chunk-2ILL7HQI.js.map → chunk-3JR3EDB2.js.map} +1 -1
  45. package/dist/{chunk-GDL26N2T.js → chunk-3KN7NJDR.js} +2 -2
  46. package/dist/{chunk-DJC4CHLQ.js → chunk-43BKLFZU.js} +9 -9
  47. package/dist/chunk-6XAIOL3X.js +2407 -0
  48. package/dist/chunk-6XAIOL3X.js.map +1 -0
  49. package/dist/{chunk-SCRFRCGR.js → chunk-BSQGE5PS.js} +1 -1
  50. package/dist/{chunk-Y3ZLRGHC.js → chunk-CZNV3VXM.js} +16 -16
  51. package/dist/chunk-DGUM43GV.js +11 -0
  52. package/dist/chunk-DGUM43GV.js.map +1 -0
  53. package/dist/{chunk-JIMUDQN3.js → chunk-FBUU43PM.js} +2 -2
  54. package/dist/chunk-H75VXTGT.js +219 -0
  55. package/dist/chunk-H75VXTGT.js.map +1 -0
  56. package/dist/{chunk-RIIOUTGM.js → chunk-HKK2JD7Z.js} +12 -9
  57. package/dist/chunk-HKK2JD7Z.js.map +1 -0
  58. package/dist/{chunk-D6BG7U6A.js → chunk-IXZBUWSP.js} +3 -3
  59. package/dist/chunk-PC3BTTBE.js +3217 -0
  60. package/dist/chunk-PC3BTTBE.js.map +1 -0
  61. package/dist/chunk-QFY4AFY4.js +879 -0
  62. package/dist/chunk-QFY4AFY4.js.map +1 -0
  63. package/dist/{chunk-DK554R7P.js → chunk-S6HXABGL.js} +2 -1
  64. package/dist/chunk-S6HXABGL.js.map +1 -0
  65. package/dist/{chunk-PKVBHGBM.js → chunk-SS2A464I.js} +7 -7
  66. package/dist/chunk-UT3MHJCW.js +49 -0
  67. package/dist/chunk-UT3MHJCW.js.map +1 -0
  68. package/dist/{chunk-G4M3NHRJ.js → chunk-V7CIJE4B.js} +3 -3
  69. package/dist/{chunk-TEW47IVR.js → chunk-VPEFSDME.js} +2 -2
  70. package/dist/chunk-VTHLCFN4.js +368 -0
  71. package/dist/chunk-VTHLCFN4.js.map +1 -0
  72. package/dist/{chunk-SWTLEQL6.js → chunk-WQIA3GFB.js} +2 -2
  73. package/dist/chunk-WQIA3GFB.js.map +1 -0
  74. package/dist/{chunk-I3IHOHCJ.js → chunk-XKXWK2KP.js} +108 -64
  75. package/dist/chunk-XKXWK2KP.js.map +1 -0
  76. package/dist/{chunk-COHO25CZ.js → chunk-YDSIVHRR.js} +553 -7
  77. package/dist/chunk-YDSIVHRR.js.map +1 -0
  78. package/dist/chunk-YXMZ2N6J.js +1884 -0
  79. package/dist/chunk-YXMZ2N6J.js.map +1 -0
  80. package/dist/composition/index.cjs +102 -57
  81. package/dist/composition/index.cjs.map +1 -1
  82. package/dist/composition/index.d.cts +4 -4
  83. package/dist/composition/index.d.ts +4 -4
  84. package/dist/composition/index.js +6 -5
  85. package/dist/core/index.cjs +102 -57
  86. package/dist/core/index.cjs.map +1 -1
  87. package/dist/core/index.d.cts +2 -2
  88. package/dist/core/index.d.ts +2 -2
  89. package/dist/core/index.js +5 -4
  90. package/dist/cqrs/index.cjs.map +1 -1
  91. package/dist/cqrs/index.d.cts +4 -4
  92. package/dist/cqrs/index.d.ts +4 -4
  93. package/dist/cqrs/index.js +3 -2
  94. package/dist/cqrs/index.js.map +1 -1
  95. package/dist/cqrs/messaging.cjs +312 -0
  96. package/dist/cqrs/messaging.cjs.map +1 -0
  97. package/dist/cqrs/messaging.d.cts +57 -0
  98. package/dist/cqrs/messaging.d.ts +57 -0
  99. package/dist/cqrs/messaging.js +274 -0
  100. package/dist/cqrs/messaging.js.map +1 -0
  101. package/dist/cqrs/work-queue.cjs +329 -0
  102. package/dist/cqrs/work-queue.cjs.map +1 -0
  103. package/dist/cqrs/work-queue.d.cts +90 -0
  104. package/dist/cqrs/work-queue.d.ts +90 -0
  105. package/dist/cqrs/work-queue.js +292 -0
  106. package/dist/cqrs/work-queue.js.map +1 -0
  107. package/dist/data/index.cjs +19 -0
  108. package/dist/data/index.cjs.map +1 -0
  109. package/dist/data/index.d.cts +36 -0
  110. package/dist/data/index.d.ts +36 -0
  111. package/dist/data/index.js +1 -0
  112. package/dist/data/index.js.map +1 -0
  113. package/dist/data-structures/index.cjs +105 -57
  114. package/dist/data-structures/index.cjs.map +1 -1
  115. package/dist/data-structures/index.d.cts +8 -8
  116. package/dist/data-structures/index.d.ts +8 -8
  117. package/dist/data-structures/index.js +7 -6
  118. package/dist/{describe-BZb7AS2y.d.ts → describe-BpyJuWkw.d.ts} +1 -1
  119. package/dist/{describe-Ciu8SUnN.d.cts → describe-DYMw_l1C.d.cts} +1 -1
  120. package/dist/executors/work-queue.cjs +342 -0
  121. package/dist/executors/work-queue.cjs.map +1 -0
  122. package/dist/executors/work-queue.d.cts +90 -0
  123. package/dist/executors/work-queue.d.ts +90 -0
  124. package/dist/executors/work-queue.js +306 -0
  125. package/dist/executors/work-queue.js.map +1 -0
  126. package/dist/graph/index.cjs +112 -58
  127. package/dist/graph/index.cjs.map +1 -1
  128. package/dist/graph/index.d.cts +9 -9
  129. package/dist/graph/index.d.ts +9 -9
  130. package/dist/graph/index.js +18 -17
  131. package/dist/{graph-DfdF9zy4.d.ts → graph-D-1-SQeC.d.ts} +3 -3
  132. package/dist/{graph-s23RbbFO.d.cts → graph-DCEWh4T2.d.cts} +3 -3
  133. package/dist/{index-CAEmLCYF.d.cts → index-72VZC0-E.d.cts} +2 -2
  134. package/dist/{index-SnzZu3x7.d.ts → index-Bmxeu0nK.d.ts} +2 -2
  135. package/dist/index.cjs +112 -58
  136. package/dist/index.cjs.map +1 -1
  137. package/dist/index.d.cts +11 -10
  138. package/dist/index.d.ts +11 -10
  139. package/dist/index.js +118 -113
  140. package/dist/inspection/boundary.cjs +98 -0
  141. package/dist/inspection/boundary.cjs.map +1 -0
  142. package/dist/inspection/boundary.d.cts +61 -0
  143. package/dist/inspection/boundary.d.ts +61 -0
  144. package/dist/inspection/boundary.js +75 -0
  145. package/dist/inspection/boundary.js.map +1 -0
  146. package/dist/{messages-BZqrGGm1.d.ts → messages-CAzUPPJM.d.cts} +10 -5
  147. package/dist/{messages-BZqrGGm1.d.cts → messages-CAzUPPJM.d.ts} +10 -5
  148. package/dist/messaging/index.cjs +744 -613
  149. package/dist/messaging/index.cjs.map +1 -1
  150. package/dist/messaging/index.d.cts +216 -160
  151. package/dist/messaging/index.d.ts +216 -160
  152. package/dist/messaging/index.js +19 -749
  153. package/dist/messaging/index.js.map +1 -1
  154. package/dist/operators/index.cjs +102 -57
  155. package/dist/operators/index.cjs.map +1 -1
  156. package/dist/operators/index.d.cts +6 -6
  157. package/dist/operators/index.d.ts +6 -6
  158. package/dist/operators/index.js +8 -7
  159. package/dist/orchestration/index.cjs +3333 -59
  160. package/dist/orchestration/index.cjs.map +1 -1
  161. package/dist/orchestration/index.d.cts +7 -4
  162. package/dist/orchestration/index.d.ts +7 -4
  163. package/dist/orchestration/index.js +49 -8
  164. package/dist/orchestration/index.js.map +1 -1
  165. package/dist/orchestration/messaging.cjs +314 -0
  166. package/dist/orchestration/messaging.cjs.map +1 -0
  167. package/dist/orchestration/messaging.d.cts +59 -0
  168. package/dist/orchestration/messaging.d.ts +59 -0
  169. package/dist/orchestration/messaging.js +276 -0
  170. package/dist/orchestration/messaging.js.map +1 -0
  171. package/dist/orchestration/work-queue.cjs +262 -0
  172. package/dist/orchestration/work-queue.cjs.map +1 -0
  173. package/dist/orchestration/work-queue.d.cts +85 -0
  174. package/dist/orchestration/work-queue.d.ts +85 -0
  175. package/dist/orchestration/work-queue.js +226 -0
  176. package/dist/orchestration/work-queue.js.map +1 -0
  177. package/dist/patterns/event-flow.cjs +447 -0
  178. package/dist/patterns/event-flow.cjs.map +1 -0
  179. package/dist/patterns/event-flow.d.cts +115 -0
  180. package/dist/patterns/event-flow.d.ts +115 -0
  181. package/dist/patterns/event-flow.js +14 -0
  182. package/dist/patterns/event-flow.js.map +1 -0
  183. package/dist/patterns/index.cjs +423 -18
  184. package/dist/patterns/index.cjs.map +1 -1
  185. package/dist/patterns/index.d.cts +8 -5
  186. package/dist/patterns/index.d.ts +8 -5
  187. package/dist/patterns/index.js +13 -4
  188. package/dist/{reactive-collection-Cb1II1Fi.d.ts → reactive-collection-BAmfrGjd.d.ts} +9 -9
  189. package/dist/{reactive-collection-BxBqtIOE.d.cts → reactive-collection-DNV0-gFi.d.cts} +9 -9
  190. package/dist/{reactive-collection-storage-D-KmjE0J.d.cts → reactive-collection-storage-BNEldDyi.d.cts} +5 -5
  191. package/dist/{reactive-collection-storage-BNiEc-Gd.d.ts → reactive-collection-storage-YZsAQsWK.d.ts} +5 -5
  192. package/dist/{reactive-map-D-g3dv8I.d.cts → reactive-map-DRD1LJ2H.d.cts} +6 -6
  193. package/dist/{reactive-map-BcB4KsQR.d.ts → reactive-map-EsDiCmJk.d.ts} +6 -6
  194. package/dist/render/index.d.cts +3 -3
  195. package/dist/render/index.d.ts +3 -3
  196. package/dist/render/index.js +1 -0
  197. package/dist/{semantic-memory-graph-BYoIlP35.d.cts → semantic-memory-graph-DKuNzuWw.d.cts} +2 -2
  198. package/dist/{semantic-memory-graph-CxyXLms3.d.ts → semantic-memory-graph-uwbwJdhe.d.ts} +2 -2
  199. package/dist/solutions/index.cjs +4478 -2
  200. package/dist/solutions/index.cjs.map +1 -1
  201. package/dist/solutions/index.d.cts +13 -519
  202. package/dist/solutions/index.d.ts +13 -519
  203. package/dist/solutions/index.js +90 -6
  204. package/dist/solutions/reactive-layout/browser/index.cjs +449 -0
  205. package/dist/solutions/reactive-layout/browser/index.cjs.map +1 -0
  206. package/dist/solutions/reactive-layout/browser/index.d.cts +44 -0
  207. package/dist/solutions/reactive-layout/browser/index.d.ts +44 -0
  208. package/dist/solutions/reactive-layout/browser/index.js +69 -0
  209. package/dist/solutions/reactive-layout/browser/index.js.map +1 -0
  210. package/dist/solutions/reactive-layout/index.cjs +4266 -0
  211. package/dist/solutions/reactive-layout/index.cjs.map +1 -0
  212. package/dist/solutions/reactive-layout/index.d.cts +581 -0
  213. package/dist/solutions/reactive-layout/index.d.ts +581 -0
  214. package/dist/solutions/reactive-layout/index.js +86 -0
  215. package/dist/solutions/reactive-layout/index.js.map +1 -0
  216. package/dist/solutions/reactive-layout/node-canvas/index.cjs +545 -0
  217. package/dist/solutions/reactive-layout/node-canvas/index.cjs.map +1 -0
  218. package/dist/solutions/reactive-layout/node-canvas/index.d.cts +54 -0
  219. package/dist/solutions/reactive-layout/node-canvas/index.d.ts +54 -0
  220. package/dist/solutions/reactive-layout/node-canvas/index.js +131 -0
  221. package/dist/solutions/reactive-layout/node-canvas/index.js.map +1 -0
  222. package/dist/solutions/reactive-layout/react-native/index.cjs +494 -0
  223. package/dist/solutions/reactive-layout/react-native/index.cjs.map +1 -0
  224. package/dist/solutions/reactive-layout/react-native/index.d.cts +51 -0
  225. package/dist/solutions/reactive-layout/react-native/index.d.ts +51 -0
  226. package/dist/solutions/reactive-layout/react-native/index.js +77 -0
  227. package/dist/solutions/reactive-layout/react-native/index.js.map +1 -0
  228. package/dist/solutions/reactive-layout/skia/index.cjs +547 -0
  229. package/dist/solutions/reactive-layout/skia/index.cjs.map +1 -0
  230. package/dist/solutions/reactive-layout/skia/index.d.cts +64 -0
  231. package/dist/solutions/reactive-layout/skia/index.d.ts +64 -0
  232. package/dist/solutions/reactive-layout/skia/index.js +70 -0
  233. package/dist/solutions/reactive-layout/skia/index.js.map +1 -0
  234. package/dist/solutions/work-item/actions.cjs +2164 -0
  235. package/dist/solutions/work-item/actions.cjs.map +1 -0
  236. package/dist/solutions/work-item/actions.d.cts +201 -0
  237. package/dist/solutions/work-item/actions.d.ts +201 -0
  238. package/dist/solutions/work-item/actions.js +1454 -0
  239. package/dist/solutions/work-item/actions.js.map +1 -0
  240. package/dist/solutions/work-item/scheduling.cjs +2454 -0
  241. package/dist/solutions/work-item/scheduling.cjs.map +1 -0
  242. package/dist/solutions/work-item/scheduling.d.cts +433 -0
  243. package/dist/solutions/work-item/scheduling.d.ts +433 -0
  244. package/dist/solutions/work-item/scheduling.js +32 -0
  245. package/dist/solutions/work-item/scheduling.js.map +1 -0
  246. package/dist/solutions/work-item/work-queue.cjs +306 -0
  247. package/dist/solutions/work-item/work-queue.cjs.map +1 -0
  248. package/dist/solutions/work-item/work-queue.d.cts +71 -0
  249. package/dist/solutions/work-item/work-queue.d.ts +71 -0
  250. package/dist/solutions/work-item/work-queue.js +270 -0
  251. package/dist/solutions/work-item/work-queue.js.map +1 -0
  252. package/dist/sources/browser.cjs +169 -57
  253. package/dist/sources/browser.cjs.map +1 -1
  254. package/dist/sources/browser.d.cts +33 -6
  255. package/dist/sources/browser.d.ts +33 -6
  256. package/dist/sources/browser.js +73 -6
  257. package/dist/sources/browser.js.map +1 -1
  258. package/dist/sources/index.cjs +102 -57
  259. package/dist/sources/index.cjs.map +1 -1
  260. package/dist/sources/index.d.cts +5 -5
  261. package/dist/sources/index.d.ts +5 -5
  262. package/dist/sources/index.js +6 -5
  263. package/dist/sources/node.cjs.map +1 -1
  264. package/dist/sources/node.d.cts +4 -4
  265. package/dist/sources/node.d.ts +4 -4
  266. package/dist/sources/node.js +2 -1
  267. package/dist/sources/node.js.map +1 -1
  268. package/dist/storage/browser.js +1 -0
  269. package/dist/storage/browser.js.map +1 -1
  270. package/dist/storage/index.d.cts +5 -5
  271. package/dist/storage/index.d.ts +5 -5
  272. package/dist/storage/index.js +5 -4
  273. package/dist/storage/node.js +1 -0
  274. package/dist/storage/node.js.map +1 -1
  275. package/dist/store-C-joM4gh.d.ts +123 -0
  276. package/dist/store-CNJwmT-h.d.cts +123 -0
  277. package/dist/testing/index.cjs +1 -0
  278. package/dist/testing/index.cjs.map +1 -1
  279. package/dist/testing/index.d.cts +1 -1
  280. package/dist/testing/index.d.ts +1 -1
  281. package/dist/testing/index.js +3 -2
  282. package/dist/{types-h12mNYbq.d.ts → types-BsJvElYZ.d.ts} +31 -31
  283. package/dist/{types-bNMSWKqF.d.cts → types-CcPIn7sy.d.cts} +31 -31
  284. package/dist/work-item-runtime-C3M79vE9.d.ts +228 -0
  285. package/dist/work-item-runtime-qaVgsL0T.d.cts +228 -0
  286. package/dist/work-queue/index.cjs +1132 -0
  287. package/dist/work-queue/index.cjs.map +1 -0
  288. package/dist/work-queue/index.d.cts +369 -0
  289. package/dist/work-queue/index.d.ts +369 -0
  290. package/dist/work-queue/index.js +1078 -0
  291. package/dist/work-queue/index.js.map +1 -0
  292. package/package.json +266 -2
  293. package/dist/chunk-COHO25CZ.js.map +0 -1
  294. package/dist/chunk-DK554R7P.js.map +0 -1
  295. package/dist/chunk-I3IHOHCJ.js.map +0 -1
  296. package/dist/chunk-RIIOUTGM.js.map +0 -1
  297. package/dist/chunk-SWTLEQL6.js.map +0 -1
  298. /package/dist/{chunk-JR4IKCR2.js.map → chunk-2747WN4Y.js.map} +0 -0
  299. /package/dist/{chunk-GDL26N2T.js.map → chunk-3KN7NJDR.js.map} +0 -0
  300. /package/dist/{chunk-DJC4CHLQ.js.map → chunk-43BKLFZU.js.map} +0 -0
  301. /package/dist/{chunk-SCRFRCGR.js.map → chunk-BSQGE5PS.js.map} +0 -0
  302. /package/dist/{chunk-Y3ZLRGHC.js.map → chunk-CZNV3VXM.js.map} +0 -0
  303. /package/dist/{chunk-JIMUDQN3.js.map → chunk-FBUU43PM.js.map} +0 -0
  304. /package/dist/{chunk-D6BG7U6A.js.map → chunk-IXZBUWSP.js.map} +0 -0
  305. /package/dist/{chunk-PKVBHGBM.js.map → chunk-SS2A464I.js.map} +0 -0
  306. /package/dist/{chunk-G4M3NHRJ.js.map → chunk-V7CIJE4B.js.map} +0 -0
  307. /package/dist/{chunk-TEW47IVR.js.map → chunk-VPEFSDME.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/messaging/index.ts","../../src/protocol/messages.ts","../../src/ctx/types.ts","../../src/graph/graph.ts"],"sourcesContent":["/**\n * Reusable application-infrastructure messaging namespace.\n *\n * Retained root messaging utilities land here only after B63 re-derives them\n * onto the D125 package DAG.\n */\n\nimport { depBatch, type NodeFn } from \"../ctx/types.js\";\nimport { type Graph, releaseGraphNodes } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\n\nexport interface MessageEnvelope<T = unknown> {\n\treadonly topic: string;\n\treadonly seq: number;\n\treadonly payload: T;\n\treadonly key?: string;\n\treadonly timestampMs: number;\n}\n\n/**\n * Minimal JSON Schema vocabulary for cross-graph/topic payload descriptions.\n *\n * D125/D132 keep this as passive messaging vocabulary: GraphReFly does not ship\n * a validator here and does not make schemas protocol messages.\n */\nexport interface JsonSchema {\n\treadonly type?:\n\t\t| \"string\"\n\t\t| \"number\"\n\t\t| \"integer\"\n\t\t| \"boolean\"\n\t\t| \"object\"\n\t\t| \"array\"\n\t\t| \"null\"\n\t\t| readonly (\"string\" | \"number\" | \"integer\" | \"boolean\" | \"object\" | \"array\" | \"null\")[];\n\treadonly properties?: Readonly<Record<string, JsonSchema>>;\n\treadonly required?: readonly string[];\n\treadonly additionalProperties?: boolean | JsonSchema;\n\treadonly items?: JsonSchema | readonly JsonSchema[];\n\treadonly enum?: readonly unknown[];\n\treadonly const?: unknown;\n\treadonly $ref?: string;\n\treadonly definitions?: Readonly<Record<string, JsonSchema>>;\n\treadonly description?: string;\n\treadonly title?: string;\n}\n\n/**\n * Recommended passive envelope for payloads that cross topic, agent, or graph\n * boundaries. It is an application fact shape, not a required protocol type.\n */\nexport interface TopicMessage<T = unknown> {\n\treadonly id: string;\n\treadonly schema?: JsonSchema;\n\treadonly expiresAt?: string;\n\treadonly correlationId?: string;\n\treadonly payload: T;\n}\n\nexport const PROMPTS_TOPIC = \"prompts\";\nexport const RESPONSES_TOPIC = \"responses\";\nexport const INJECTIONS_TOPIC = \"injections\";\nexport const DEFERRED_TOPIC = \"deferred\";\nexport const SPAWNS_TOPIC = \"spawns\";\nexport const CONTEXT_TOPIC = \"context\";\nexport const TODOS_TOPIC = \"todos\";\n\nexport const STANDARD_TOPICS = Object.freeze([\n\tPROMPTS_TOPIC,\n\tRESPONSES_TOPIC,\n\tINJECTIONS_TOPIC,\n\tDEFERRED_TOPIC,\n\tSPAWNS_TOPIC,\n\tCONTEXT_TOPIC,\n\tTODOS_TOPIC,\n] as const);\n\nexport type StandardTopic = (typeof STANDARD_TOPICS)[number];\n\nexport interface MessageBusEvent<T = unknown> {\n\treadonly kind: \"publish\" | \"complete\" | \"error\";\n\treadonly topic: string;\n\treadonly seq?: number;\n\treadonly payload?: T;\n\treadonly error?: unknown;\n}\n\nexport interface MessageBusOptions<TTopic extends string = string> {\n\treadonly topics: readonly TTopic[];\n\treadonly name?: string;\n\treadonly now?: () => number;\n}\n\nexport interface MessageBus<TTopic extends string = string> {\n\treadonly topics: readonly TTopic[];\n\ttopic<T = unknown>(name: TTopic): Node<MessageEnvelope<T>>;\n\tpublish<T = unknown>(name: TTopic, payload: T, opts?: { key?: string }): MessageEnvelope<T>;\n\thas(name: string): name is TTopic;\n}\n\ninterface MessageBusState<TTopic extends string> {\n\treadonly graph: Graph;\n\treadonly name: string;\n\treadonly now: () => number;\n\treadonly topics: readonly TTopic[];\n\treadonly records: Map<TTopic, TopicRecord>;\n\tseq: number;\n}\n\ntype ProducedTopicMessage<T = unknown> =\n\t| { readonly kind: \"publish\"; readonly envelope: MessageEnvelope<T> }\n\t| { readonly kind: \"error\"; readonly topic: string; readonly error: unknown };\n\ninterface TopicRecord {\n\treadonly node: Node<MessageEnvelope<unknown>>;\n\treadonly producers: Node<ProducedTopicMessage<unknown>>[];\n\treadonly body: NodeFn;\n}\n\nconst busStates = new WeakMap<MessageBus<string>, MessageBusState<string>>();\n\nexport interface ToTopicOptions {\n\treadonly name?: string;\n\treadonly keyOf?: (value: unknown) => string | undefined;\n}\n\nexport interface ToTopicBundle<T> {\n\treadonly events: Node<MessageBusEvent<T>>;\n}\n\nexport type DynamicHubUnknownTopicPolicy = \"drop\" | \"error\" | \"dead-letter\" | \"create-as-fact\";\n\nexport interface DynamicHubOptions {\n\treadonly name?: string;\n\treadonly topics?: readonly string[];\n\treadonly unknownTopic?: DynamicHubUnknownTopicPolicy;\n\treadonly deadLetter?: boolean;\n\treadonly maxTopics?: number;\n\treadonly maxTopicLength?: number;\n\treadonly now?: () => number;\n}\n\nexport interface DynamicHubMetadata {\n\treadonly seq: number;\n\treadonly cursor: number;\n\treadonly timestampMs: number;\n}\n\nexport type DynamicHubEventKind =\n\t| \"create\"\n\t| \"delete\"\n\t| \"message\"\n\t| \"subscribe\"\n\t| \"close\"\n\t| \"error\"\n\t| \"dead-letter\";\n\nexport type DynamicHubCommand<T = unknown> =\n\t| {\n\t\t\treadonly kind: \"create\";\n\t\t\treadonly topic: string;\n\t\t\treadonly key?: string;\n\t\t\treadonly payload?: T;\n\t }\n\t| {\n\t\t\treadonly kind: \"delete\";\n\t\t\treadonly topic: string;\n\t\t\treadonly key?: string;\n\t\t\treadonly payload?: T;\n\t }\n\t| {\n\t\t\treadonly kind: \"publish\";\n\t\t\treadonly topic: string;\n\t\t\treadonly payload: T;\n\t\t\treadonly key?: string;\n\t }\n\t| {\n\t\t\treadonly kind: \"subscribe\";\n\t\t\treadonly topic: string;\n\t\t\treadonly key?: string;\n\t\t\treadonly payload?: T;\n\t }\n\t| {\n\t\t\treadonly kind: \"close\";\n\t\t\treadonly key?: string;\n\t\t\treadonly payload?: T;\n\t };\n\nexport interface DynamicHubStatus {\n\treadonly open: boolean;\n\treadonly topics: readonly string[];\n\treadonly seq: number;\n\treadonly cursor: number;\n\treadonly lastEventKind?: DynamicHubEventKind;\n}\n\ninterface DynamicHubEventFrame {\n\treadonly meta: DynamicHubMetadata;\n\treadonly status: DynamicHubStatus;\n}\n\nexport type DynamicHubEvent<T = unknown> = DynamicHubEventFrame &\n\t(\n\t\t| {\n\t\t\t\treadonly kind: \"create\";\n\t\t\t\treadonly topic: string;\n\t\t\t\treadonly key?: string;\n\t\t\t\treadonly payload?: T;\n\t\t }\n\t\t| {\n\t\t\t\treadonly kind: \"delete\";\n\t\t\t\treadonly topic: string;\n\t\t\t\treadonly key?: string;\n\t\t\t\treadonly payload?: T;\n\t\t }\n\t\t| {\n\t\t\t\treadonly kind: \"message\";\n\t\t\t\treadonly topic: string;\n\t\t\t\treadonly payload: T;\n\t\t\t\treadonly key?: string;\n\t\t }\n\t\t| {\n\t\t\t\treadonly kind: \"subscribe\";\n\t\t\t\treadonly topic: string;\n\t\t\t\treadonly key?: string;\n\t\t\t\treadonly payload?: T;\n\t\t }\n\t\t| {\n\t\t\t\treadonly kind: \"close\";\n\t\t\t\treadonly key?: string;\n\t\t\t\treadonly payload?: T;\n\t\t }\n\t\t| {\n\t\t\t\treadonly kind: \"error\";\n\t\t\t\treadonly topic?: string;\n\t\t\t\treadonly error: string;\n\t\t\t\treadonly command: unknown;\n\t\t }\n\t\t| {\n\t\t\t\treadonly kind: \"dead-letter\";\n\t\t\t\treadonly topic?: string;\n\t\t\t\treadonly reason: string;\n\t\t\t\treadonly command: unknown;\n\t\t }\n\t);\n\nexport interface DynamicHubError {\n\treadonly topic?: string;\n\treadonly error: string;\n\treadonly command: unknown;\n\treadonly meta: DynamicHubMetadata;\n}\n\nexport interface DynamicHubDeadLetter {\n\treadonly topic?: string;\n\treadonly reason: string;\n\treadonly command: unknown;\n\treadonly meta: DynamicHubMetadata;\n}\n\nexport interface DynamicHub<T = unknown> {\n\treadonly command: Node<DynamicHubCommand<T>>;\n\treadonly events: Node<DynamicHubEvent<T>>;\n\treadonly status: Node<DynamicHubStatus>;\n\treadonly errors: Node<DynamicHubError>;\n\treadonly deadLetter?: Node<DynamicHubDeadLetter>;\n\tcreate(topic: string, opts?: { key?: string; payload?: T }): DynamicHubCommand<T>;\n\tdelete(topic: string, opts?: { key?: string; payload?: T }): DynamicHubCommand<T>;\n\tpublish(topic: string, payload: T, opts?: { key?: string }): DynamicHubCommand<T>;\n\tsubscribeTopic(topic: string, opts?: { key?: string; payload?: T }): DynamicHubCommand<T>;\n\tclose(opts?: { key?: string; payload?: T }): DynamicHubCommand<T>;\n}\n\nexport interface ToHubTopicOptions<T> {\n\treadonly name?: string;\n\treadonly keyOf?: (value: T) => string | undefined;\n}\n\nexport interface ToHubTopicBundle<T> {\n\treadonly commands: Node<DynamicHubCommand<T>>;\n}\n\ninterface DynamicHubState<T> {\n\treadonly graph: Graph;\n\treadonly name: string;\n\treadonly maxTopicLength: number;\n\treadonly commandSources: Node<DynamicHubCommand<T>>[];\n\treadonly commandBody: NodeFn;\n\treadonly releaseEventsRetain: () => void;\n}\n\ninterface DynamicHubRuntime {\n\ttopics: string[];\n\topen: boolean;\n\tseq: number;\n\tcursor: number;\n}\n\nconst dynamicHubStates = new WeakMap<DynamicHub<unknown>, DynamicHubState<unknown>>();\nconst DEFAULT_DYNAMIC_HUB_MAX_TOPICS = 1024;\nconst DEFAULT_DYNAMIC_HUB_MAX_TOPIC_LENGTH = 256;\n\nexport function messageBus<TTopic extends string>(\n\tgraph: Graph,\n\topts: MessageBusOptions<TTopic>,\n): MessageBus<TTopic> {\n\tconst unique = [...new Set(opts.topics)];\n\tif (unique.length !== opts.topics.length) throw new Error(\"messageBus: duplicate topic\");\n\tif (unique.length === 0) throw new Error(\"messageBus: at least one topic is required\");\n\tconst name = opts.name ?? \"messageBus\";\n\tconst state: MessageBusState<TTopic> = {\n\t\tgraph,\n\t\tname,\n\t\tnow: opts.now ?? Date.now,\n\t\ttopics: Object.freeze([...unique]),\n\t\trecords: new Map(),\n\t\tseq: 0,\n\t};\n\tfor (const topic of unique) {\n\t\tconst producers: Node<ProducedTopicMessage<unknown>>[] = [];\n\t\tconst body: NodeFn = (ctx) => {\n\t\t\tfor (let i = 0; i < producers.length; i++) {\n\t\t\t\tfor (const produced of depBatch(ctx, i) ?? []) {\n\t\t\t\t\tif ((produced as ProducedTopicMessage).kind === \"publish\") {\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\tproduced as ProducedTopicMessage<unknown> & {\n\t\t\t\t\t\t\t\t\t\tkind: \"publish\";\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t).envelope,\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};\n\t\tconst node = graph.node<MessageEnvelope<unknown>>([], body, {\n\t\t\tname: `${name}/${topic}`,\n\t\t\tfactory: \"messageTopic\",\n\t\t\tmeta: { topic },\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t});\n\t\tstate.records.set(topic, { node, producers, body });\n\t}\n\tconst bus: MessageBus<TTopic> = {\n\t\ttopics: state.topics,\n\t\ttopic<T = unknown>(topic: TTopic): Node<MessageEnvelope<T>> {\n\t\t\treturn requireTopic(state, topic) as Node<MessageEnvelope<T>>;\n\t\t},\n\t\tpublish<T = unknown>(\n\t\t\ttopic: TTopic,\n\t\t\tpayload: T,\n\t\t\tpublishOpts: { key?: string } = {},\n\t\t): MessageEnvelope<T> {\n\t\t\tconst node = requireTopic(state, topic);\n\t\t\tconst envelope: MessageEnvelope<T> = {\n\t\t\t\ttopic,\n\t\t\t\tseq: ++state.seq,\n\t\t\t\tpayload,\n\t\t\t\ttimestampMs: state.now(),\n\t\t\t\t...(publishOpts.key === undefined ? {} : { key: publishOpts.key }),\n\t\t\t};\n\t\t\tnode.down([[\"DATA\", envelope as MessageEnvelope<unknown>]]);\n\t\t\treturn envelope;\n\t\t},\n\t\thas(topic: string): topic is TTopic {\n\t\t\treturn state.records.has(topic as TTopic);\n\t\t},\n\t};\n\tbusStates.set(bus as MessageBus<string>, state as unknown as MessageBusState<string>);\n\treturn bus;\n}\n\n/**\n * D135 dynamic messaging hub: topic lifecycle is DATA facts over fixed graph-visible\n * command/event/status/error nodes. Topic keys never create or delete graph nodes.\n */\nexport function dynamicHub<T = unknown>(graph: Graph, opts: DynamicHubOptions = {}): DynamicHub<T> {\n\tconst name = opts.name ?? \"dynamicHub\";\n\tconst unknownTopic = normalizeUnknownTopicPolicy(opts.unknownTopic);\n\tconst maxTopics = normalizeHubLimit(\n\t\topts.maxTopics,\n\t\tDEFAULT_DYNAMIC_HUB_MAX_TOPICS,\n\t\t\"dynamicHub: maxTopics\",\n\t);\n\tconst maxTopicLength = normalizeHubLimit(\n\t\topts.maxTopicLength,\n\t\tDEFAULT_DYNAMIC_HUB_MAX_TOPIC_LENGTH,\n\t\t\"dynamicHub: maxTopicLength\",\n\t);\n\tconst now = opts.now ?? Date.now;\n\tconst initialTopics = uniqueTopics(opts.topics ?? [], maxTopicLength);\n\tif (initialTopics.length > maxTopics) {\n\t\tthrow new Error(\"dynamicHub: topics exceed maxTopics\");\n\t}\n\tconst commandSources: Node<DynamicHubCommand<T>>[] = [];\n\tconst commandBody: NodeFn = (ctx) => {\n\t\tfor (let i = 0; i < commandSources.length; i++) {\n\t\t\tfor (const command of depBatch(ctx, i) ?? []) ctx.down([[\"DATA\", command]]);\n\t\t}\n\t};\n\tconst command = graph.node<DynamicHubCommand<T>>([], commandBody, {\n\t\tname: `${name}/command`,\n\t\tfactory: \"dynamicHubCommand\",\n\t\tcompleteWhenDepsComplete: false,\n\t\terrorWhenDepsError: false,\n\t});\n\tconst events = graph.node<DynamicHubEvent<T>>(\n\t\t[command],\n\t\t(ctx) => {\n\t\t\tconst runtime =\n\t\t\t\tctx.state.get<DynamicHubRuntime>() ??\n\t\t\t\t({\n\t\t\t\t\ttopics: [...initialTopics],\n\t\t\t\t\topen: true,\n\t\t\t\t\tseq: 0,\n\t\t\t\t\tcursor: 0,\n\t\t\t\t} satisfies DynamicHubRuntime);\n\t\t\tctx.state.persist(true);\n\t\t\tfor (const commandFact of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst parsed = parseDynamicHubCommand(commandFact);\n\t\t\t\tif (typeof parsed === \"string\") {\n\t\t\t\t\tctx.down([[\"DATA\", hubError(runtime, commandFact, parsed, timestampOrFallback(now))]]);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst reduced = reduceDynamicHubCommand(\n\t\t\t\t\truntime,\n\t\t\t\t\tparsed as DynamicHubCommand<T>,\n\t\t\t\t\tunknownTopic,\n\t\t\t\t\tmaxTopics,\n\t\t\t\t\tmaxTopicLength,\n\t\t\t\t\tnow,\n\t\t\t\t);\n\t\t\t\tfor (const event of reduced) ctx.down([[\"DATA\", event]]);\n\t\t\t}\n\t\t\tctx.state.set(runtime);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/events`,\n\t\t\tfactory: \"dynamicHubEvents\",\n\t\t\tmeta: { unknownTopic },\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst status = graph.node<DynamicHubStatus>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const event of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = event as DynamicHubEvent<T>;\n\t\t\t\tctx.down([[\"DATA\", typed.status]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/status`,\n\t\t\tfactory: \"dynamicHubStatus\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst errors = graph.node<DynamicHubError>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const event of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = event as DynamicHubEvent<T>;\n\t\t\t\tif (typed.kind !== \"error\") continue;\n\t\t\t\tctx.down([\n\t\t\t\t\t[\n\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...(typed.topic === undefined ? {} : { topic: typed.topic }),\n\t\t\t\t\t\t\terror: typed.error,\n\t\t\t\t\t\t\tcommand: typed.command,\n\t\t\t\t\t\t\tmeta: typed.meta,\n\t\t\t\t\t\t} satisfies DynamicHubError,\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/errors`,\n\t\t\tfactory: \"dynamicHubErrors\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst deadLetter =\n\t\topts.deadLetter === true || unknownTopic === \"dead-letter\"\n\t\t\t? graph.node<DynamicHubDeadLetter>(\n\t\t\t\t\t[events],\n\t\t\t\t\t(ctx) => {\n\t\t\t\t\t\tfor (const event of depBatch(ctx, 0) ?? []) {\n\t\t\t\t\t\t\tconst typed = event as DynamicHubEvent<T>;\n\t\t\t\t\t\t\tif (typed.kind !== \"dead-letter\") continue;\n\t\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t...(typed.topic === undefined ? {} : { topic: typed.topic }),\n\t\t\t\t\t\t\t\t\t\treason: typed.reason,\n\t\t\t\t\t\t\t\t\t\tcommand: typed.command,\n\t\t\t\t\t\t\t\t\t\tmeta: typed.meta,\n\t\t\t\t\t\t\t\t\t} satisfies DynamicHubDeadLetter,\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\t{\n\t\t\t\t\t\tname: `${name}/deadLetter`,\n\t\t\t\t\t\tfactory: \"dynamicHubDeadLetter\",\n\t\t\t\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t\t\t\terrorWhenDepsError: false,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t: undefined;\n\tconst releaseEventsRetain = graph.retain(events, { reason: `${name}.dynamicHub.events` });\n\tconst hub: DynamicHub<T> = {\n\t\tcommand,\n\t\tevents,\n\t\tstatus,\n\t\terrors,\n\t\t...(deadLetter === undefined ? {} : { deadLetter }),\n\t\tcreate(topic, commandOpts = {}) {\n\t\t\treturn publishHubCommand(command, {\n\t\t\t\tkind: \"create\",\n\t\t\t\ttopic,\n\t\t\t\t...(commandOpts.key === undefined ? {} : { key: commandOpts.key }),\n\t\t\t\t...(commandOpts.payload === undefined ? {} : { payload: commandOpts.payload }),\n\t\t\t} as DynamicHubCommand<T>);\n\t\t},\n\t\tdelete(topic, commandOpts = {}) {\n\t\t\treturn publishHubCommand(command, {\n\t\t\t\tkind: \"delete\",\n\t\t\t\ttopic,\n\t\t\t\t...(commandOpts.key === undefined ? {} : { key: commandOpts.key }),\n\t\t\t\t...(commandOpts.payload === undefined ? {} : { payload: commandOpts.payload }),\n\t\t\t} as DynamicHubCommand<T>);\n\t\t},\n\t\tpublish(topic, payload, commandOpts = {}) {\n\t\t\treturn publishHubCommand(command, {\n\t\t\t\tkind: \"publish\",\n\t\t\t\ttopic,\n\t\t\t\tpayload,\n\t\t\t\t...(commandOpts.key === undefined ? {} : { key: commandOpts.key }),\n\t\t\t});\n\t\t},\n\t\tsubscribeTopic(topic, commandOpts = {}) {\n\t\t\treturn publishHubCommand(command, {\n\t\t\t\tkind: \"subscribe\",\n\t\t\t\ttopic,\n\t\t\t\t...(commandOpts.key === undefined ? {} : { key: commandOpts.key }),\n\t\t\t\t...(commandOpts.payload === undefined ? {} : { payload: commandOpts.payload }),\n\t\t\t} as DynamicHubCommand<T>);\n\t\t},\n\t\tclose(commandOpts = {}) {\n\t\t\treturn publishHubCommand(command, {\n\t\t\t\tkind: \"close\",\n\t\t\t\t...(commandOpts.key === undefined ? {} : { key: commandOpts.key }),\n\t\t\t\t...(commandOpts.payload === undefined ? {} : { payload: commandOpts.payload }),\n\t\t\t} as DynamicHubCommand<T>);\n\t\t},\n\t};\n\tdynamicHubStates.set(hub as DynamicHub<unknown>, {\n\t\tgraph,\n\t\tname,\n\t\tmaxTopicLength,\n\t\tcommandSources: commandSources as Node<DynamicHubCommand<unknown>>[],\n\t\tcommandBody,\n\t\treleaseEventsRetain,\n\t});\n\treturn hub;\n}\n\n/** Static D135 projection over hub event facts for one topic key; no topic node is created. */\nexport function fromHubTopic<T = unknown>(\n\thub: DynamicHub<unknown>,\n\ttopic: string,\n\topts: { name?: string } = {},\n): Node<MessageEnvelope<T>> {\n\tconst state = requireDynamicHubState(hub);\n\tassertTopicKey(topic, \"fromHubTopic\", state.maxTopicLength);\n\treturn state.graph.node<MessageEnvelope<T>>(\n\t\t[hub.events],\n\t\t(ctx) => {\n\t\t\tfor (const event of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = event as DynamicHubEvent<T>;\n\t\t\t\tif (typed.kind !== \"message\" || typed.topic !== topic) continue;\n\t\t\t\tctx.down([\n\t\t\t\t\t[\n\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttopic,\n\t\t\t\t\t\t\tseq: typed.meta.seq,\n\t\t\t\t\t\t\tpayload: typed.payload,\n\t\t\t\t\t\t\ttimestampMs: typed.meta.timestampMs,\n\t\t\t\t\t\t\t...(typed.key === undefined ? {} : { key: typed.key }),\n\t\t\t\t\t\t} satisfies MessageEnvelope<T>,\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: opts.name ?? `${state.name}/${topic}/fromHubTopic`,\n\t\t\tfactory: \"fromHubTopic\",\n\t\t\tmeta: { topic },\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\n/** Static D135 command helper: source DATA becomes publish command facts for one topic key. */\nexport function toHubTopic<T>(\n\tgraph: Graph,\n\tsource: Node<T>,\n\thub: DynamicHub<unknown>,\n\ttopic: string,\n\topts: ToHubTopicOptions<T> = {},\n): ToHubTopicBundle<T> {\n\tconst state = requireDynamicHubState(hub);\n\tassertTopicKey(topic, \"toHubTopic\", state.maxTopicLength);\n\tif (state.graph !== graph) throw new Error(\"toHubTopic: hub and source graph must match\");\n\tif (isReachableUpstream(source as Node<unknown>, hub.command as Node<unknown>)) {\n\t\tthrow new Error(\"toHubTopic: source already depends on hub command path\");\n\t}\n\tconst commands = graph.node<DynamicHubCommand<T>>(\n\t\t[source],\n\t\t(ctx) => {\n\t\t\tfor (const value of depBatch(ctx, 0) ?? []) {\n\t\t\t\ttry {\n\t\t\t\t\tconst key = opts.keyOf?.(value as T);\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: \"publish\",\n\t\t\t\t\t\t\t\ttopic,\n\t\t\t\t\t\t\t\tpayload: value as T,\n\t\t\t\t\t\t\t\t...(key === undefined ? {} : { key }),\n\t\t\t\t\t\t\t} satisfies DynamicHubCommand<T>,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t} catch (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: \"invalid\",\n\t\t\t\t\t\t\t\ttopic,\n\t\t\t\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t\t\t} as unknown as DynamicHubCommand<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},\n\t\t{\n\t\t\tname: opts.name ?? `${state.name}/${topic}/toHubTopic`,\n\t\t\tfactory: \"toHubTopic\",\n\t\t\tmeta: { topic },\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst commandSource = commands as Node<DynamicHubCommand<unknown>>;\n\tstate.commandSources.push(commandSource);\n\ttry {\n\t\thub.command.replaceDeps([...state.commandSources], state.commandBody);\n\t} catch (error) {\n\t\tstate.commandSources.splice(state.commandSources.indexOf(commandSource), 1);\n\t\treleaseGraphNodes(graph, [commands as Node<unknown>], {\n\t\t\treason: \"toHubTopic failed command wiring\",\n\t\t});\n\t\tthrow error;\n\t}\n\treturn { commands };\n}\n\nexport function fromTopic<T = unknown, TTopic extends string = string>(\n\tbus: MessageBus<TTopic>,\n\ttopic: TTopic,\n): Node<MessageEnvelope<T>> {\n\treturn bus.topic<T>(topic);\n}\n\nexport function toTopic<T, TTopic extends string>(\n\tgraph: Graph,\n\tsource: Node<T>,\n\tbus: MessageBus<TTopic>,\n\ttopic: TTopic,\n\topts: ToTopicOptions = {},\n): ToTopicBundle<T> {\n\tconst state = busStates.get(bus as MessageBus<string>) as MessageBusState<TTopic> | undefined;\n\tif (state === undefined) throw new Error(\"toTopic: unknown message bus implementation\");\n\tif (state.graph !== graph) throw new Error(\"toTopic: bus and source graph must match\");\n\tconst record = requireTopicRecord(state, topic);\n\tconst name = opts.name ?? `toTopic/${topic}`;\n\tconst producer = graph.node<ProducedTopicMessage<T>>(\n\t\t[source],\n\t\t(ctx) => {\n\t\t\tfor (const value of depBatch(ctx, 0) ?? []) {\n\t\t\t\ttry {\n\t\t\t\t\tconst key = opts.keyOf?.(value);\n\t\t\t\t\tconst envelope: MessageEnvelope<T> = {\n\t\t\t\t\t\ttopic,\n\t\t\t\t\t\tseq: ++state.seq,\n\t\t\t\t\t\tpayload: value as T,\n\t\t\t\t\t\ttimestampMs: state.now(),\n\t\t\t\t\t\t...(key === undefined ? {} : { key }),\n\t\t\t\t\t};\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: \"publish\",\n\t\t\t\t\t\t\t\tenvelope,\n\t\t\t\t\t\t\t} satisfies ProducedTopicMessage<T>,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tctx.down([[\"DATA\", { kind: \"error\", topic, error } satisfies ProducedTopicMessage<T>]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory: \"toTopic\",\n\t\t\tmeta: { topic },\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\trecord.producers.push(producer as Node<ProducedTopicMessage<unknown>>);\n\trecord.node.replaceDeps([...record.producers], record.body);\n\tconst events = graph.node<MessageBusEvent<T>>(\n\t\t[producer, source],\n\t\t(ctx) => {\n\t\t\tfor (const produced of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = produced as ProducedTopicMessage<T>;\n\t\t\t\tif (typed.kind === \"publish\") {\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: \"publish\",\n\t\t\t\t\t\t\t\ttopic,\n\t\t\t\t\t\t\t\tseq: typed.envelope.seq,\n\t\t\t\t\t\t\t\tpayload: typed.envelope.payload,\n\t\t\t\t\t\t\t} satisfies MessageBusEvent<T>,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t} else {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\"DATA\", { kind: \"error\", topic, error: typed.error } satisfies MessageBusEvent<T>],\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst terminal = ctx.terminal[0];\n\t\t\tif (terminal !== false && terminal !== undefined && terminal !== true) {\n\t\t\t\tctx.down([\n\t\t\t\t\t[\"DATA\", { kind: \"error\", topic, error: terminal } satisfies MessageBusEvent<T>],\n\t\t\t\t]);\n\t\t\t}\n\t\t\tconst sourceTerminal = ctx.terminal[1];\n\t\t\tif (sourceTerminal === true) {\n\t\t\t\tctx.down([[\"DATA\", { kind: \"complete\", topic } satisfies MessageBusEvent<T>]]);\n\t\t\t} else if (sourceTerminal !== false && sourceTerminal !== undefined) {\n\t\t\t\tctx.down([\n\t\t\t\t\t[\"DATA\", { kind: \"error\", topic, error: sourceTerminal } satisfies MessageBusEvent<T>],\n\t\t\t\t]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/events`,\n\t\t\tfactory: \"toTopicEvents\",\n\t\t\tmeta: { topic },\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t\tterminalAsRealInput: true,\n\t\t},\n\t);\n\treturn { events };\n}\n\nfunction requireTopic<TTopic extends string>(\n\tstate: MessageBusState<TTopic>,\n\ttopic: TTopic,\n): Node<MessageEnvelope<unknown>> {\n\treturn requireTopicRecord(state, topic).node;\n}\n\nfunction requireTopicRecord<TTopic extends string>(\n\tstate: MessageBusState<TTopic>,\n\ttopic: TTopic,\n): TopicRecord {\n\tconst record = state.records.get(topic);\n\tif (record === undefined) throw new Error(`messageBus: unknown topic '${topic}'`);\n\treturn record;\n}\n\nfunction uniqueTopics(topics: readonly string[], maxTopicLength: number): readonly string[] {\n\tconst unique = [...new Set(topics)];\n\tif (unique.length !== topics.length) throw new Error(\"dynamicHub: duplicate topic\");\n\tfor (const topic of unique) assertTopicKey(topic, \"dynamicHub\", maxTopicLength);\n\treturn Object.freeze(unique.sort());\n}\n\nfunction normalizeUnknownTopicPolicy(\n\tpolicy: DynamicHubOptions[\"unknownTopic\"],\n): DynamicHubUnknownTopicPolicy {\n\tif (policy === undefined) return \"error\";\n\tif (\n\t\tpolicy === \"drop\" ||\n\t\tpolicy === \"error\" ||\n\t\tpolicy === \"dead-letter\" ||\n\t\tpolicy === \"create-as-fact\"\n\t) {\n\t\treturn policy;\n\t}\n\tthrow new Error(\"dynamicHub: unknownTopic policy is not recognized\");\n}\n\nfunction normalizeHubLimit(value: number | undefined, fallback: number, owner: string): number {\n\tif (value === undefined) return fallback;\n\tif (!Number.isInteger(value) || value < 1) {\n\t\tthrow new Error(`${owner} must be a positive integer`);\n\t}\n\treturn value;\n}\n\nfunction publishHubCommand<T>(\n\tcommandNode: Node<DynamicHubCommand<T>>,\n\tcommand: DynamicHubCommand<T>,\n): DynamicHubCommand<T> {\n\tcommandNode.down([[\"DATA\", command]]);\n\treturn command;\n}\n\nfunction parseDynamicHubCommand(value: unknown): DynamicHubCommand<unknown> | string {\n\tif (!isObjectRecord(value)) return \"dynamicHub: command fact must be an object\";\n\tconst kind = value.kind;\n\tif (\n\t\tkind !== \"create\" &&\n\t\tkind !== \"delete\" &&\n\t\tkind !== \"publish\" &&\n\t\tkind !== \"subscribe\" &&\n\t\tkind !== \"close\"\n\t) {\n\t\treturn \"dynamicHub: command kind is not recognized\";\n\t}\n\tif (kind === \"close\") {\n\t\treturn {\n\t\t\tkind,\n\t\t\t...(typeof value.key === \"string\" ? { key: value.key } : {}),\n\t\t\t...(value.payload === undefined ? {} : { payload: value.payload }),\n\t\t};\n\t}\n\tconst topic = value.topic;\n\tif (typeof topic !== \"string\" || topic.length === 0) {\n\t\treturn \"dynamicHub: command topic must be a non-empty string\";\n\t}\n\tif (kind === \"publish\") {\n\t\tif (value.payload === undefined) return \"dynamicHub: publish command payload is required\";\n\t\treturn {\n\t\t\tkind,\n\t\t\ttopic,\n\t\t\tpayload: value.payload,\n\t\t\t...(typeof value.key === \"string\" ? { key: value.key } : {}),\n\t\t};\n\t}\n\treturn {\n\t\tkind,\n\t\ttopic,\n\t\t...(typeof value.key === \"string\" ? { key: value.key } : {}),\n\t\t...(value.payload === undefined ? {} : { payload: value.payload }),\n\t};\n}\n\nfunction isObjectRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction readHubTimestamp(now: () => number): number | string {\n\ttry {\n\t\tconst timestampMs = now();\n\t\treturn Number.isFinite(timestampMs)\n\t\t\t? timestampMs\n\t\t\t: \"dynamicHub: now() must return a finite number\";\n\t} catch (error) {\n\t\treturn `dynamicHub: now() threw: ${error instanceof Error ? error.message : String(error)}`;\n\t}\n}\n\nfunction timestampOrFallback(now: () => number): number {\n\tconst timestampMs = readHubTimestamp(now);\n\treturn typeof timestampMs === \"number\" ? timestampMs : Date.now();\n}\n\nfunction reduceDynamicHubCommand<T>(\n\truntime: DynamicHubRuntime,\n\tcommand: DynamicHubCommand<T>,\n\tunknownTopic: DynamicHubUnknownTopicPolicy,\n\tmaxTopics: number,\n\tmaxTopicLength: number,\n\tnow: () => number,\n): DynamicHubEvent<T>[] {\n\tconst topic = \"topic\" in command ? command.topic : undefined;\n\tif (topic !== undefined) {\n\t\tconst topicError = validateTopicKey(topic, \"dynamicHub\", maxTopicLength);\n\t\tif (topicError !== undefined) {\n\t\t\treturn [hubError(runtime, command, topicError, timestampOrFallback(now))];\n\t\t}\n\t}\n\tif (!runtime.open && command.kind !== \"close\") {\n\t\treturn [hubError(runtime, command, \"dynamicHub: hub is closed\", timestampOrFallback(now))];\n\t}\n\tswitch (command.kind) {\n\t\tcase \"create\": {\n\t\t\tconst capacityError = canAddHubTopic(runtime, command.topic, maxTopics);\n\t\t\tif (capacityError !== undefined) {\n\t\t\t\treturn [hubError(runtime, command, capacityError, timestampOrFallback(now))];\n\t\t\t}\n\t\t\tconst timestampMs = readHubTimestamp(now);\n\t\t\tif (typeof timestampMs === \"string\")\n\t\t\t\treturn [hubError(runtime, command, timestampMs, Date.now())];\n\t\t\taddHubTopic(runtime, command.topic);\n\t\t\treturn [hubEvent(runtime, timestampMs, command)];\n\t\t}\n\t\tcase \"delete\": {\n\t\t\tif (!hasHubTopic(runtime, command.topic)) {\n\t\t\t\treturn unknownHubTopic(runtime, command, unknownTopic, now);\n\t\t\t}\n\t\t\tconst timestampMs = readHubTimestamp(now);\n\t\t\tif (typeof timestampMs === \"string\")\n\t\t\t\treturn [hubError(runtime, command, timestampMs, Date.now())];\n\t\t\tdeleteHubTopic(runtime, command.topic);\n\t\t\treturn [hubEvent(runtime, timestampMs, command)];\n\t\t}\n\t\tcase \"publish\": {\n\t\t\tif (!hasHubTopic(runtime, command.topic)) {\n\t\t\t\tif (unknownTopic === \"create-as-fact\") {\n\t\t\t\t\tconst capacityError = canAddHubTopic(runtime, command.topic, maxTopics);\n\t\t\t\t\tif (capacityError !== undefined) {\n\t\t\t\t\t\treturn [hubError(runtime, command, capacityError, timestampOrFallback(now))];\n\t\t\t\t\t}\n\t\t\t\t\tconst createTimestampMs = readHubTimestamp(now);\n\t\t\t\t\tif (typeof createTimestampMs === \"string\") {\n\t\t\t\t\t\treturn [hubError(runtime, command, createTimestampMs, Date.now())];\n\t\t\t\t\t}\n\t\t\t\t\tconst messageTimestampMs = readHubTimestamp(now);\n\t\t\t\t\tif (typeof messageTimestampMs === \"string\") {\n\t\t\t\t\t\treturn [hubError(runtime, command, messageTimestampMs, Date.now())];\n\t\t\t\t\t}\n\t\t\t\t\taddHubTopic(runtime, command.topic);\n\t\t\t\t\treturn [\n\t\t\t\t\t\thubEvent(runtime, createTimestampMs, { kind: \"create\", topic: command.topic }),\n\t\t\t\t\t\thubEvent(runtime, messageTimestampMs, {\n\t\t\t\t\t\t\tkind: \"message\",\n\t\t\t\t\t\t\ttopic: command.topic,\n\t\t\t\t\t\t\tpayload: command.payload,\n\t\t\t\t\t\t\t...(command.key === undefined ? {} : { key: command.key }),\n\t\t\t\t\t\t}),\n\t\t\t\t\t];\n\t\t\t\t}\n\t\t\t\treturn unknownHubTopic(runtime, command, unknownTopic, now);\n\t\t\t}\n\t\t\tconst timestampMs = readHubTimestamp(now);\n\t\t\tif (typeof timestampMs === \"string\")\n\t\t\t\treturn [hubError(runtime, command, timestampMs, Date.now())];\n\t\t\treturn [\n\t\t\t\thubEvent(runtime, timestampMs, {\n\t\t\t\t\tkind: \"message\",\n\t\t\t\t\ttopic: command.topic,\n\t\t\t\t\tpayload: command.payload,\n\t\t\t\t\t...(command.key === undefined ? {} : { key: command.key }),\n\t\t\t\t}),\n\t\t\t];\n\t\t}\n\t\tcase \"subscribe\": {\n\t\t\tif (!hasHubTopic(runtime, command.topic)) {\n\t\t\t\tif (unknownTopic === \"create-as-fact\") {\n\t\t\t\t\tconst capacityError = canAddHubTopic(runtime, command.topic, maxTopics);\n\t\t\t\t\tif (capacityError !== undefined) {\n\t\t\t\t\t\treturn [hubError(runtime, command, capacityError, timestampOrFallback(now))];\n\t\t\t\t\t}\n\t\t\t\t\tconst createTimestampMs = readHubTimestamp(now);\n\t\t\t\t\tif (typeof createTimestampMs === \"string\") {\n\t\t\t\t\t\treturn [hubError(runtime, command, createTimestampMs, Date.now())];\n\t\t\t\t\t}\n\t\t\t\t\tconst subscribeTimestampMs = readHubTimestamp(now);\n\t\t\t\t\tif (typeof subscribeTimestampMs === \"string\") {\n\t\t\t\t\t\treturn [hubError(runtime, command, subscribeTimestampMs, Date.now())];\n\t\t\t\t\t}\n\t\t\t\t\taddHubTopic(runtime, command.topic);\n\t\t\t\t\treturn [\n\t\t\t\t\t\thubEvent(runtime, createTimestampMs, { kind: \"create\", topic: command.topic }),\n\t\t\t\t\t\thubEvent(runtime, subscribeTimestampMs, command),\n\t\t\t\t\t];\n\t\t\t\t}\n\t\t\t\treturn unknownHubTopic(runtime, command, unknownTopic, now);\n\t\t\t}\n\t\t\tconst timestampMs = readHubTimestamp(now);\n\t\t\tif (typeof timestampMs === \"string\")\n\t\t\t\treturn [hubError(runtime, command, timestampMs, Date.now())];\n\t\t\treturn [hubEvent(runtime, timestampMs, command)];\n\t\t}\n\t\tcase \"close\": {\n\t\t\tconst timestampMs = readHubTimestamp(now);\n\t\t\tif (typeof timestampMs === \"string\")\n\t\t\t\treturn [hubError(runtime, command, timestampMs, Date.now())];\n\t\t\truntime.open = false;\n\t\t\treturn [hubEvent(runtime, timestampMs, command)];\n\t\t}\n\t}\n}\n\nfunction hubEvent<T>(\n\truntime: DynamicHubRuntime,\n\ttimestampMs: number,\n\tevent: Record<string, unknown> & { readonly kind: DynamicHubEventKind },\n): DynamicHubEvent<T> {\n\tconst meta = nextHubMetadata(runtime, timestampMs);\n\treturn {\n\t\t...event,\n\t\tmeta,\n\t\tstatus: snapshotHubStatus(runtime, meta, event.kind),\n\t} as DynamicHubEvent<T>;\n}\n\nfunction hubError<T>(\n\truntime: DynamicHubRuntime,\n\tcommand: unknown,\n\terror: string,\n\ttimestampMs: number,\n): DynamicHubEvent<T> {\n\treturn hubEvent(runtime, timestampMs, {\n\t\tkind: \"error\",\n\t\t...(isObjectRecord(command) && typeof command.topic === \"string\"\n\t\t\t? { topic: command.topic }\n\t\t\t: {}),\n\t\terror,\n\t\tcommand,\n\t});\n}\n\nfunction unknownHubTopic<T>(\n\truntime: DynamicHubRuntime,\n\tcommand: DynamicHubCommand<T>,\n\tpolicy: DynamicHubUnknownTopicPolicy,\n\tnow: () => number,\n): DynamicHubEvent<T>[] {\n\tconst topic = \"topic\" in command ? command.topic : undefined;\n\tconst reason = `dynamicHub: unknown topic '${topic ?? \"\"}'`;\n\tif (policy === \"drop\") return [];\n\tif (policy === \"dead-letter\") {\n\t\treturn [\n\t\t\thubEvent(runtime, timestampOrFallback(now), {\n\t\t\t\tkind: \"dead-letter\",\n\t\t\t\t...(topic === undefined ? {} : { topic }),\n\t\t\t\treason,\n\t\t\t\tcommand,\n\t\t\t}),\n\t\t];\n\t}\n\treturn [hubError(runtime, command, reason, timestampOrFallback(now))];\n}\n\nfunction nextHubMetadata(runtime: DynamicHubRuntime, timestampMs: number): DynamicHubMetadata {\n\truntime.seq += 1;\n\truntime.cursor = runtime.seq;\n\treturn { seq: runtime.seq, cursor: runtime.cursor, timestampMs };\n}\n\nfunction snapshotHubStatus(\n\truntime: DynamicHubRuntime,\n\tmeta: DynamicHubMetadata,\n\tkind: DynamicHubEventKind,\n): DynamicHubStatus {\n\treturn {\n\t\topen: runtime.open,\n\t\ttopics: Object.freeze([...runtime.topics].sort()),\n\t\tseq: meta.seq,\n\t\tcursor: meta.cursor,\n\t\tlastEventKind: kind,\n\t};\n}\n\nfunction assertTopicKey(topic: string, owner: string, maxTopicLength: number): void {\n\tconst error = validateTopicKey(topic, owner, maxTopicLength);\n\tif (error !== undefined) throw new Error(error);\n}\n\nfunction validateTopicKey(\n\ttopic: string,\n\towner: string,\n\tmaxTopicLength: number,\n): string | undefined {\n\tif (typeof topic !== \"string\" || topic.length === 0) {\n\t\treturn `${owner}: topic must be a non-empty string`;\n\t}\n\tif (topic.length > maxTopicLength) {\n\t\treturn `${owner}: topic exceeds maxTopicLength`;\n\t}\n\treturn undefined;\n}\n\nfunction hasHubTopic(runtime: DynamicHubRuntime, topic: string): boolean {\n\treturn runtime.topics.includes(topic);\n}\n\nfunction addHubTopic(runtime: DynamicHubRuntime, topic: string): void {\n\tif (!hasHubTopic(runtime, topic)) runtime.topics = [...runtime.topics, topic];\n}\n\nfunction deleteHubTopic(runtime: DynamicHubRuntime, topic: string): void {\n\truntime.topics = runtime.topics.filter((existing) => existing !== topic);\n}\n\nfunction canAddHubTopic(\n\truntime: DynamicHubRuntime,\n\ttopic: string,\n\tmaxTopics: number,\n): string | undefined {\n\tif (hasHubTopic(runtime, topic)) return undefined;\n\treturn runtime.topics.length >= maxTopics\n\t\t? \"dynamicHub: topic count exceeds maxTopics\"\n\t\t: undefined;\n}\n\nfunction isReachableUpstream(from: Node<unknown>, target: Node<unknown>): boolean {\n\tconst seen = new Set<Node<unknown>>();\n\tconst stack: Node<unknown>[] = [from];\n\twhile (stack.length > 0) {\n\t\tconst node = stack.pop();\n\t\tif (node === undefined) continue;\n\t\tif (node === target) return true;\n\t\tif (seen.has(node)) continue;\n\t\tseen.add(node);\n\t\tfor (const dep of node.deps) stack.push(dep);\n\t}\n\treturn false;\n}\n\nfunction requireDynamicHubState(hub: DynamicHub<unknown>): DynamicHubState<unknown> {\n\tconst state = dynamicHubStates.get(hub);\n\tif (state === undefined) throw new Error(\"dynamicHub: unknown hub implementation\");\n\treturn state;\n}\n","/**\n * Wave-protocol message types and the tier const table.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-msg-format, R-msg-closed-set, R-tier (D34), R-data-payload, R-sentinel.\n */\n\n/** Opaque pause-lock identifier (R-pause-lockset). */\nexport type LockId = string | symbol;\n\n/**\n * The CLOSED set of 10 message types (R-msg-closed-set / D9 + START handshake).\n * No open set, no user-defined custom types. Adding a type is a spec change.\n */\nexport type Message =\n\t| readonly [\"START\"]\n\t| readonly [\"DIRTY\"]\n\t| readonly [\"DATA\", unknown]\n\t| readonly [\"RESOLVED\"]\n\t| readonly [\"INVALIDATE\"]\n\t| readonly [\"COMPLETE\"]\n\t| readonly [\"ERROR\", unknown]\n\t| readonly [\"TEARDOWN\"]\n\t| readonly [\"PAUSE\", LockId]\n\t| readonly [\"RESUME\", LockId];\n\n/** One array of messages delivered in one call = one Wave (R-wave-boundary). */\nexport type Wave = readonly Message[];\n\n/** The message-type tag (the first tuple element). */\nexport type MessageType = Message[0];\n\n/**\n * SENTINEL = absence-of-DATA (R-sentinel / D16). TS representation is `undefined`.\n * Never a valid DATA payload; `null` IS a valid DATA value (domain-level absence).\n */\nexport const SENTINEL = undefined;\n\n/** R-data-payload: ERROR payloads must not collide with terminal metadata shorthand. */\nexport function isInvalidErrorPayload(v: unknown): boolean {\n\treturn v === SENTINEL || typeof v === \"boolean\";\n}\n\n/** R-data-payload / D78: host-language failures that collide with ctx.terminal shorthand become diagnostics. */\nexport function errorPayload(reason: unknown, fallback = \"error without a valid payload\"): unknown {\n\treturn isInvalidErrorPayload(reason) ? new Error(fallback) : reason;\n}\n\nexport const TIER_START = 0;\nexport const TIER_CONTROL = 1;\nexport const TIER_NOTIFICATION = 2;\nexport const TIER_VALUE = 3;\nexport const TIER_SETTLE = 4;\nexport const TIER_TERMINAL = 5;\nexport const TIER_TEARDOWN = 6;\n\n/**\n * Tier const table (R-tier / D34). Tiers below value dispatch immediately; value\n * and above are batch-deferred. This is a compile-time const table (D18), not runtime config.\n */\nconst TIER: Record<MessageType, number> = {\n\tSTART: TIER_START,\n\tPAUSE: TIER_CONTROL,\n\tRESUME: TIER_CONTROL,\n\tDIRTY: TIER_NOTIFICATION,\n\tDATA: TIER_VALUE,\n\tRESOLVED: TIER_VALUE,\n\tINVALIDATE: TIER_SETTLE,\n\tCOMPLETE: TIER_TERMINAL,\n\tERROR: TIER_TERMINAL,\n\tTEARDOWN: TIER_TEARDOWN,\n};\n\nexport function messageTier(t: MessageType): number {\n\treturn TIER[t];\n}\n\n/** Value and above are deferred inside a batch (DATA/RESOLVED/INVALIDATE/terminal/teardown). */\nexport function isDeferredTier(t: MessageType): boolean {\n\treturn TIER[t] >= TIER_VALUE;\n}\n\n/** Value-tier messages (DATA/RESOLVED) occupy the tier-3 slot. */\nexport function isValueTier(t: MessageType): boolean {\n\treturn TIER[t] === TIER_VALUE;\n}\n\n/** The pause buffer holds the settle slice only: value-tier DATA/RESOLVED plus INVALIDATE. */\nexport function isPauseBufferedTier(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier === TIER_VALUE || tier === TIER_SETTLE;\n}\n\n/**\n * A TERMINAL message = tier 5 (COMPLETE | ERROR), R-tier / D34. Detected via the CENTRAL tier\n * table, NOT a per-variant `=== \"COMPLETE\" || === \"ERROR\"` check — so terminal routing stays\n * driven by the one const table (feedback_use_tier_for_signal_routing); discriminate COMPLETE vs\n * ERROR within the tier by the message type only where the handling actually differs.\n */\nexport function isTerminal(t: MessageType): boolean {\n\treturn TIER[t] === TIER_TERMINAL;\n}\n\n/**\n * ctx.up carries control tiers only (R-ctx-up / DR-5): DIRTY, PAUSE, RESUME,\n * INVALIDATE, TEARDOWN. DATA/RESOLVED (tier 3) and COMPLETE/ERROR (tier 5) are\n * down-only.\n */\nexport function isUpAllowed(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier !== TIER_VALUE && tier !== TIER_TERMINAL;\n}\n","/**\n * The fn-invocation context and per-dep input shapes.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-fn-contract (D8/D27), R-ctx-state (D23/D29), R-cleanup-hooks (D28), R-ctx-up.\n */\n\nimport type { Dispatcher } from \"../dispatcher/index.js\";\nimport type { EnvironmentDrivers } from \"../graph/environment.js\";\nimport type { Node } from \"../node/node.js\";\nimport { type Message, SENTINEL, type Wave } from \"../protocol/messages.js\";\n\n/** A downstream sink callback (the only way to connect to a node's output). */\nexport type Sink = (msg: Message, delivery?: DeliveryMeta) => void;\n\n/** Internal delivery metadata used to preserve the upstream `ctx.down(msgs)` wave boundary. */\nexport interface DeliveryMeta {\n\treadonly wave: object;\n\treadonly last: boolean;\n}\n\n/**\n * Internal current-value reader. It is deliberately a symbol-backed implementation detail:\n * raw ctx exposes `waveData` + `terminal`; helpers below derive from that plus this dep cache.\n */\nexport const CTX_DEP_CACHE: unique symbol = Symbol(\"graphrefly.ctx.depCache\");\n\nexport interface CtxDepCache {\n\treadonly latest: readonly unknown[];\n}\n\n/** Internal node-construction binding for graph-local helper-created deps. */\nexport const CTX_NODE_BINDING: unique symbol = Symbol(\"graphrefly.ctx.nodeBinding\");\n\nexport interface CtxNodeBinding {\n\treadonly dispatcher: Dispatcher;\n\tcreate<T>(factory: () => Node<T>): Node<T>;\n}\n\n/** Per-dep wave projections: dep -> waves -> values/SENTINEL markers. */\nexport type WaveData = readonly (readonly (readonly unknown[])[])[];\n\n/** Terminal metadata parallel to `waveData`: false = none, true = COMPLETE, otherwise ERROR payload. */\nexport type TerminalData = readonly unknown[];\n\nexport function isTerminalNone(t: unknown): boolean {\n\treturn t === false || t === undefined;\n}\n\nexport function isTerminalComplete(t: unknown): t is true {\n\treturn t === true;\n}\n\nexport function isTerminalError(t: unknown): boolean {\n\treturn !isTerminalNone(t) && !isTerminalComplete(t);\n}\n\nexport function terminalErrorValue(t: unknown): unknown {\n\treturn isTerminalError(t) ? t : undefined;\n}\n\n/**\n * Per-node private cross-wave state (R-ctx-state / D23,D29). Default fresh-lifecycle\n * wipe; `persist(true)` keeps it across lifecycle transitions.\n */\nexport interface CtxState {\n\tget<S = unknown>(): S | undefined;\n\tset<S = unknown>(v: S): void;\n\tpersist(on?: boolean): void;\n}\n\n/**\n * Deferred SELF-rewire (R-rewire-deferred / D47). A node fn may, DURING its run, request a\n * mutation of its OWN dep set; the request is QUEUED and applied at the committed wave boundary\n * (after the current wave settles / batch commit / final-lock RESUME) as a fresh wave, reusing\n * R-rewire surgical/Option-C semantics (D42). This is the ONLY legal self-triggered rewire — an\n * IMMEDIATE in-fn `node.subscribeDep/unsubscribeDep/replaceDeps` is the D37 mid-fn feedback-cycle ERROR. An\n * added cached dep pushes `[DIRTY,DATA]` on the boundary wave (R-push-subscribe); a removed dep\n * is drained and, if it loses its last subscriber, `_deactivate`s + fires `onDeactivation`\n * (input-side teardown — the basis for higher-order operator cancellation / abortInFlight).\n */\nexport interface RewireNext {\n\t/** Defer subscribing to a dep (paired with the re-supplied fn — positional fn-deps lock, SD-1). */\n\tsubscribeDep(dep: Node<unknown>, fn: NodeFn): void;\n\t/** Defer unsubscribing from a dep (its source is torn down if it loses its last subscriber). */\n\tunsubscribeDep(dep: Node<unknown>, fn: NodeFn): void;\n\t/** Defer replacing the whole dep set (surgical: kept deps untouched, removed drained, added fresh-subscribe). */\n\treplaceDeps(deps: Node<unknown>[], fn: NodeFn): void;\n}\n\n/**\n * The single argument to a node fn: `(ctx) => void` (R-fn-contract / D8). All emission\n * is explicit via `ctx.down`; there is no return-value framing.\n */\nexport interface Ctx {\n\t/**\n\t * Emit upstream toward deps — control tiers only (R-ctx-up). IMMEDIATE. `towardDep` (a dep index)\n\t * routes the wave up ONE declared edge (R-up-routing directed-up); omitted = broadcast up all deps.\n\t * A pull DEMAND is `up([[RESUME, pullId]])` — but for a SELF-demand (demanding a dep this fn also\n\t * reads) use {@link Ctx.upNext} instead, since an immediate demand whose delivery loops back\n\t * re-enters this fn mid-wave (D37 / R-reentrancy).\n\t */\n\tup(msgs: Wave, towardDep?: number): void;\n\t/** Emit downstream toward sinks. */\n\tdown(msgs: Wave): void;\n\t/**\n\t * The single raw dep-value input surface (R-ctx-wave-data / D77): dep -> upstream waves ->\n\t * per-wave DATA payloads and INVALIDATE/SENTINEL markers. `waveData[i] = []` means dep i\n\t * delivered no wave to this invocation; `waveData[i] = [[]]` means RESOLVED-only.\n\t */\n\twaveData: WaveData;\n\t/** Terminal metadata for the same invocation; terminal values never enter `waveData`. */\n\tterminal: TerminalData;\n\tstate: CtxState;\n\t/** Release external resources on deactivation (R-cleanup-hooks). */\n\tonDeactivation(fn: () => void): void;\n\t/** Flush on INVALIDATE (R-cleanup-hooks). */\n\tonInvalidate(fn: () => void): void;\n\t/** Graph-owned environment drivers for source/adapter boundaries (D130/D131). */\n\tenvironment(): EnvironmentDrivers;\n\t/**\n\t * Deferred SELF-rewire (R-rewire-deferred / D47) — the substrate affordance higher-order\n\t * operators (switchMap/mergeMap/concatMap/exhaustMap/flatMap) use to grow/shrink their own\n\t * inner-source dep set in response to their own data. Always present; see {@link RewireNext}.\n\t */\n\trewireNext: RewireNext;\n\t/**\n\t * Deferred up — the boundary-deferred form of {@link Ctx.up} (R-up-routing / R-pull / D59). Routes\n\t * `msgs` up from this node at the COMMITTED wave boundary (broadcast, or up the single `towardDep`\n\t * edge), riding the same R-rewire-deferred (D47) drain as {@link RewireNext}. This is the\n\t * SELF-DEMAND path: a consumer issues `ctx.upNext([[RESUME, pullId]])` to demand a pull dep it\n\t * ALSO reads — the cone-routed RESUME reaches the pullId-holder, whose delivery loops back as a\n\t * FRESH wave (not a mid-fn re-entry → no D37). The consumer accepts one-wave latency (the\n\t * HTTP-request model). No node reference needed: the author writes the pullId verbatim.\n\t */\n\tupNext(msgs: Wave, towardDep?: number): void;\n\t/**\n\t * Read a dep's latest value by index (dynamicNode only, R-dynamic-node / D35).\n\t * Present only on dynamicNode fns; all declared deps still participate in wave\n\t * tracking. Under D49/R-resolved-undirty an unread dep's change still fires the fn,\n\t * which re-emits its (unchanged) output as a DATA occurrence — there is NO equals-\n\t * absorption; pair with distinctUntilChanged to suppress unchanged re-emits (opt-in).\n\t */\n\ttrack?(depIndex: number): unknown;\n\t[CTX_DEP_CACHE]?: CtxDepCache;\n\t[CTX_NODE_BINDING]?: CtxNodeBinding;\n}\n\n/** A node fn (R-fn-contract). Registered in a dispatcher pool, indexed by Handle. */\nexport type NodeFn = (ctx: Ctx) => void;\n\n/** Number of declared dep slots visible in this invocation. */\nexport function depCount(ctx: Ctx): number {\n\treturn ctx.waveData.length;\n}\n\n/** DATA/SENTINEL projection batches delivered by one dep in this invocation. */\nexport function depWaves(ctx: Ctx, depIndex: number): readonly (readonly unknown[])[] {\n\treturn ctx.waveData[depIndex] ?? [];\n}\n\n/** Flattened DATA projection for old event-counting operator bodies; null = no wave. */\nexport function depBatch(ctx: Ctx, depIndex: number): readonly unknown[] | null {\n\tconst waves = depWaves(ctx, depIndex);\n\tif (waves.length === 0) return null;\n\tconst flattened = waves.flat().filter((v) => v !== SENTINEL);\n\treturn flattened.length === 0 ? [] : flattened;\n}\n\n/** Latest cached DATA for a dep, derived from implementation-owned dep cache. */\nexport function depLatest(ctx: Ctx, depIndex: number): unknown {\n\treturn ctx[CTX_DEP_CACHE]?.latest[depIndex];\n}\n\n/** Terminal metadata for one dep: false = none, true = COMPLETE, otherwise ERROR payload. */\nexport function depTerminal(ctx: Ctx, depIndex: number): unknown {\n\tconst t = ctx.terminal[depIndex];\n\treturn t === undefined ? false : t;\n}\n","/**\n * The Graph layer (CSP-2): convenience + inspection entry (D5 / R-graph-role).\n *\n * g.* sugar desugars to dispatcher.register + Node and auto-registers into the graph\n * inspection index (D27: sugar→ctx-fn conversion lives strictly here; the substrate node\n * only ever sees `(ctx)=>void`). The Graph owns naming, describe, mount, and the D30\n * value-level throw→ERROR boundary. The bare node()/dispatcher stay inspection-free\n * (R-node-thin).\n *\n * Canonical authority: ~/src/graphrefly — D3/D5/D27/D30/D36/D37/D39, R-graph-role,\n * R-describe, R-fn-contract, R-edges-derived, R-meta-presentation.\n */\n\nimport { type BatchCtx, batch as batchRun } from \"../batch/batch.js\";\nimport { type Ctx, depCount, depLatest, type NodeFn } from \"../ctx/types.js\";\nimport { type Dispatcher, defaultDispatcher } from \"../dispatcher/index.js\";\nimport { NodeCore } from \"../node/core.js\";\nimport {\n\tcheckpointStateOfNode,\n\tgetNodeOwner,\n\tisNodeActiveForRelease,\n\tisNodeRuntimeQuiescentForRelease,\n\tisNodeRuntimeReleased,\n\tNode,\n\ttype NodeOptions,\n\treleaseRuntimeOfNode,\n\tsetNodeOwner,\n\tsetNodeTopologyDepsChangedObserver,\n\tsubscriberCountOfNode,\n\twithEnvironmentDrivers,\n\twithNodeCore,\n} from \"../node/node.js\";\nimport type { NodeVersioningPolicy } from \"../node/versioning.js\";\nimport { errorPayload, messageTier, SENTINEL } from \"../protocol/messages.js\";\nimport {\n\tGRAPH_BLUEPRINT_VERSION,\n\ttype GraphBlueprint,\n\ttype GraphBlueprintOptions,\n\tgraphBlueprintDiagnostics,\n\tnormalizeTopology,\n\tnormalizeTopologyMeta,\n} from \"./blueprint.js\";\nimport {\n\tcheckpointBackendStateOfNode,\n\tcheckpointTerminal,\n\tcheckpointValue,\n\tGRAPH_CHECKPOINT_VERSION,\n\ttype GraphCheckpoint,\n\ttype GraphCheckpointFactory,\n\ttype GraphCheckpointJson,\n\ttype GraphCheckpointNode,\n\ttoCheckpointJson,\n} from \"./checkpoint.js\";\nimport {\n\ttype DescribeEdge,\n\ttype DescribeNode,\n\ttype DescribeOpts,\n\ttype DescribeSnapshot,\n\ttype GraphTopologySnapshot,\n\ttopologyFromDescribe,\n} from \"./describe.js\";\nimport { EnvironmentDrivers } from \"./environment.js\";\nimport type {\n\tNodeProfile,\n\tObserveStream,\n\tProfile,\n\tTopologyEvent,\n\tTopologyStream,\n} from \"./inspect.js\";\nimport { initNodeWithCore, type Operator } from \"./operators.js\";\n\n/** Map a tuple of Nodes to the tuple of their value types (typed value-level fn args). */\ntype DepValues<D extends readonly Node<unknown>[]> = {\n\t[K in keyof D]: D[K] extends Node<infer V> ? V : never;\n};\n\n/** Value-level derived fn: receives dep values, returns the next value (undefined = no emit). */\nexport type DerivedFn<D extends readonly Node<unknown>[], T> = (\n\t...values: DepValues<D>\n) => T | undefined;\n\n/** Value-level effect fn: receives dep values, optionally returns a deactivation cleanup. */\nexport type EffectFn<D extends readonly Node<unknown>[]> = (\n\t...values: DepValues<D>\n\t// biome-ignore lint/suspicious/noConfusingVoidType: effect returns void OR a cleanup fn — the void arm keeps `(v) => { sideEffect(v) }` ergonomic (React EffectCallback idiom); dropping it would force an explicit `return undefined`.\n) => void | (() => void);\n\n/** Sugar options — node options minus graph-owned dispatcher plus naming/meta. */\nexport interface SugarOpts<T = unknown> extends Omit<NodeOptions<T>, \"dispatcher\"> {\n\tname?: string;\n\tmeta?: Record<string, unknown>;\n\t/**\n\t * D95: explicit restorable factory metadata. Static JSON-compatible config may live here;\n\t * reactive options must remain graph deps. Without this, function-backed nodes are local-only.\n\t */\n\trestore?: { ref: string; config?: unknown; configVersion?: unknown };\n}\n\nexport interface GraphOptions {\n\tname?: string;\n\t/** Bind to a dispatcher (default = process-global, D26). */\n\tdispatcher?: Dispatcher;\n\t/** D109 default node runtime versioning policy for graph-owned nodes. Default is nodev0. */\n\tversioning?: NodeVersioningPolicy;\n\t/** Graph-owned environment drivers for source/adapter boundaries (D130/D131). */\n\tenvironment?: EnvironmentDrivers;\n\t/**\n\t * Turn on the dispatcher profile recorder (D39 / F-PERF default off). NOTE: this\n\t * switches recording on for the WHOLE bound dispatcher (the default is process-global,\n\t * D26) — every graph sharing it then pays the recorder cost. For isolated profiling\n\t * use a dedicated dispatcher: `graph({ dispatcher: new Dispatcher(), profile: true })`.\n\t */\n\tprofile?: boolean;\n}\n\ninterface Entry {\n\tnode: Node<unknown>;\n\tid: string;\n\tname?: string;\n\tfactory: string;\n\tdeps: readonly Node<unknown>[];\n\tmeta?: Record<string, unknown>;\n\trestore?: { ref: string; config?: unknown; configVersion?: unknown };\n}\n\ninterface TopologyObserver {\n\tpath?: string;\n\tsink(event: TopologyEvent): void;\n}\n\ninterface MountedGraph {\n\tat: string;\n\tgraph: Graph;\n\ttopologyUnsub?: () => void;\n}\n\ninterface GraphRestoreRegistrar {\n\tstateNode<T>(id: string, opts?: SugarOpts<T>): StateNode<T>;\n\tnode<T>(\n\t\tid: string,\n\t\tfactory: string,\n\t\tdeps: readonly Node<unknown>[],\n\t\tfn: NodeFn | null,\n\t\topts?: SugarOpts<T>,\n\t): Node<T>;\n}\n\nconst restoreRegistrars = new WeakMap<Graph, GraphRestoreRegistrar>();\n\ninterface GraphLifecycleRegistrar {\n\tassertRegisteredNode(node: Node<unknown>, label: string): void;\n\treleaseNodes(nodes: readonly Node<unknown>[], opts?: { reason?: string }): void;\n}\n\nconst lifecycleRegistrars = new WeakMap<Graph, GraphLifecycleRegistrar>();\n\nfunction nodeOwner(n: Node<unknown>): Graph | undefined {\n\treturn getNodeOwner(n) as Graph | undefined;\n}\n\nexport function assertGraphLocalNode(owner: Graph, n: Node<unknown>, label: string): void {\n\tif (isNodeRuntimeReleased(n)) {\n\t\tthrow new Error(`${label} has been released from its graph lifecycle (D122)`);\n\t}\n\tconst existing = nodeOwner(n);\n\tif (existing !== undefined && existing !== owner) {\n\t\tthrow new Error(\n\t\t\t`${label} belongs to a different graph; cross-graph deps require a wire bridge`,\n\t\t);\n\t}\n}\n\n/**\n * A state node (L4-Q1): a manual source whose `.set(v)` is `node.down([[DATA, v]])` sugar.\n * Extends the substrate Node so it is usable as a dep AND carries the graph-layer `.set`.\n */\nexport class StateNode<T> extends Node<T> {\n\tset(v: T): void {\n\t\tthis.down([[\"DATA\", v]]);\n\t}\n}\n\nexport interface TopologyGroupOptions {\n\t/** Optional inspection/release reason label for this graph-owned topology group. */\n\tname?: string;\n}\n\nexport interface TopologyGroupReleaseOptions {\n\t/** Optional diagnostic reason. No protocol/control messages are synthesized. */\n\treason?: string;\n}\n\n/**\n * Graph-owned D152 release group: a label over ordinary graph-registered nodes.\n * The graph registry remains the source of truth; helper-local membership is only\n * a memo for atomic quiescent release.\n */\nexport interface TopologyGroup {\n\treadonly name?: string;\n\treadonly released: boolean;\n\tadd<T extends Node<unknown>>(node: T): T;\n\tnode<T = unknown>(\n\t\tdeps?: readonly Node<unknown>[],\n\t\tfn?: NodeFn | null,\n\t\topts?: SugarOpts<T>,\n\t): Node<T>;\n\tstate<T>(initial: T, opts?: SugarOpts<T>): StateNode<T>;\n\tproducer<T = unknown>(fn: NodeFn, opts?: SugarOpts<T>): Node<T>;\n\tderived<const D extends readonly Node<unknown>[], T>(\n\t\tdeps: D,\n\t\tfn: DerivedFn<D, T>,\n\t\topts?: SugarOpts<T>,\n\t): Node<T>;\n\teffect<const D extends readonly Node<unknown>[]>(\n\t\tdeps: D,\n\t\tfn: EffectFn<D>,\n\t\topts?: SugarOpts<void>,\n\t): Node<void>;\n\tinitNode<TIn, TOut>(\n\t\top: Operator<TIn, TOut>,\n\t\tdeps: readonly Node<TIn>[],\n\t\topts?: SugarOpts<TOut>,\n\t): Node<TOut>;\n\trelease(opts?: TopologyGroupReleaseOptions): void;\n}\n\nclass GraphTopologyGroup implements TopologyGroup {\n\treadonly name?: string;\n\tprivate readonly _graph: Graph;\n\tprivate readonly _members: Node<unknown>[] = [];\n\tprivate _released = false;\n\n\tconstructor(graph: Graph, opts: TopologyGroupOptions = {}) {\n\t\tthis._graph = graph;\n\t\tthis.name = opts.name;\n\t}\n\n\tget released(): boolean {\n\t\treturn this._released;\n\t}\n\n\tadd<T extends Node<unknown>>(node: T): T {\n\t\tthis._assertLive();\n\t\tconst lifecycle = lifecycleRegistrars.get(this._graph);\n\t\tif (lifecycle === undefined) throw new Error(\"topologyGroup: graph lifecycle unavailable\");\n\t\tlifecycle.assertRegisteredNode(node, `topology group '${this.name ?? \"group\"}' member`);\n\t\tif (!this._members.includes(node)) this._members.push(node);\n\t\treturn node;\n\t}\n\n\tnode<T = unknown>(\n\t\tdeps: readonly Node<unknown>[] = [],\n\t\tfn: NodeFn | null = null,\n\t\topts: SugarOpts<T> = {},\n\t): Node<T> {\n\t\tthis._assertLive();\n\t\treturn this.add(this._graph.node(deps, fn, opts));\n\t}\n\n\tstate<T>(initial: T, opts: SugarOpts<T> = {}): StateNode<T> {\n\t\tthis._assertLive();\n\t\treturn this.add(this._graph.state(initial, opts));\n\t}\n\n\tproducer<T = unknown>(fn: NodeFn, opts: SugarOpts<T> = {}): Node<T> {\n\t\tthis._assertLive();\n\t\treturn this.add(this._graph.producer(fn, opts));\n\t}\n\n\tderived<const D extends readonly Node<unknown>[], T>(\n\t\tdeps: D,\n\t\tfn: DerivedFn<D, T>,\n\t\topts: SugarOpts<T> = {},\n\t): Node<T> {\n\t\tthis._assertLive();\n\t\treturn this.add(this._graph.derived(deps, fn, opts));\n\t}\n\n\teffect<const D extends readonly Node<unknown>[]>(\n\t\tdeps: D,\n\t\tfn: EffectFn<D>,\n\t\topts: SugarOpts<void> = {},\n\t): Node<void> {\n\t\tthis._assertLive();\n\t\treturn this.add(this._graph.effect(deps, fn, opts));\n\t}\n\n\tinitNode<TIn, TOut>(\n\t\top: Operator<TIn, TOut>,\n\t\tdeps: readonly Node<TIn>[],\n\t\topts: SugarOpts<TOut> = {},\n\t): Node<TOut> {\n\t\tthis._assertLive();\n\t\treturn this.add(this._graph.initNode(op, deps, opts));\n\t}\n\n\trelease(opts: TopologyGroupReleaseOptions = {}): void {\n\t\tif (this._released) return;\n\t\tconst lifecycle = lifecycleRegistrars.get(this._graph);\n\t\tif (lifecycle === undefined) throw new Error(\"topologyGroup: graph lifecycle unavailable\");\n\t\tlifecycle.releaseNodes([...this._members], {\n\t\t\treason: opts.reason ?? this.name,\n\t\t});\n\t\tthis._members.length = 0;\n\t\tthis._released = true;\n\t}\n\n\tprivate _assertLive(): void {\n\t\tif (this._released) {\n\t\t\tthrow new Error(`topology group '${this.name ?? \"group\"}' has been released (D152)`);\n\t\t}\n\t}\n}\n\nexport class Graph {\n\treadonly name?: string;\n\tprivate readonly _dispatcher: Dispatcher;\n\tprivate readonly _versioning: NodeVersioningPolicy | undefined;\n\tprivate readonly _environment: EnvironmentDrivers;\n\tprivate readonly _core = new NodeCore();\n\tprivate readonly _entries = new Map<Node<unknown>, Entry>();\n\tprivate readonly _byId = new Map<string, Node<unknown>>();\n\tprivate readonly _retiredIds = new Set<string>();\n\tprivate readonly _mounts: MountedGraph[] = [];\n\tprivate _seq = 0;\n\tprivate _clock = 0; // graph-local monotonic clock for observe seq (D26)\n\tprivate _topologyObserverSeq = 0;\n\tprivate readonly _topologyObservers = new Map<number, TopologyObserver>();\n\tprivate _topologyDelivering = false;\n\tprivate readonly _topologyQueue: TopologyEvent[] = [];\n\t// D51: stable synthetic ids for unregistered live deps (runtime *Map inners) auto-discovered by\n\t// describe(). WeakMap-cached so successive describes agree + the inner's id is freed when it is.\n\t// A dedicated counter (NOT _seq) so a describe() call never perturbs registered-node id numbering.\n\tprivate _synthSeq = 0;\n\tprivate readonly _synthIds = new WeakMap<Node<unknown>, string>();\n\n\tconstructor(opts: GraphOptions = {}) {\n\t\tthis.name = opts.name;\n\t\tthis._dispatcher = opts.dispatcher ?? defaultDispatcher;\n\t\tthis._versioning = opts.versioning;\n\t\tthis._environment = opts.environment ?? EnvironmentDrivers.empty();\n\t\tif (opts.profile) this._dispatcher.setRecording(true);\n\t\trestoreRegistrars.set(this, {\n\t\t\tstateNode: <T = unknown>(id: string, stateOpts: SugarOpts<T> = {}) => {\n\t\t\t\tconst n = this._construct(() => new StateNode<T>([], null, this._nodeOpts(stateOpts)));\n\t\t\t\tthis._addWithId(n, \"state\", [], stateOpts, id);\n\t\t\t\treturn n;\n\t\t\t},\n\t\t\tnode: <T = unknown>(\n\t\t\t\tid: string,\n\t\t\t\tfactory: string,\n\t\t\t\tdeps: readonly Node<unknown>[],\n\t\t\t\tfn: NodeFn | null,\n\t\t\t\tnodeOpts: SugarOpts<T> = {},\n\t\t\t) => {\n\t\t\t\tthis._assertDepsLocal(deps, `dep of restored '${id}'`);\n\t\t\t\tconst n = this._construct(() => new Node<T>([...deps], fn, this._nodeOpts(nodeOpts)));\n\t\t\t\tthis._addWithId(n, factory, deps, nodeOpts, id);\n\t\t\t\treturn n;\n\t\t\t},\n\t\t});\n\t\tlifecycleRegistrars.set(this, {\n\t\t\tassertRegisteredNode: (node, label) => this._assertRegisteredNode(node, label),\n\t\t\treleaseNodes: (nodes, releaseOpts) => this._releaseNodes(nodes, releaseOpts),\n\t\t});\n\t}\n\n\t// ── registration / inspection index ──\n\n\tprivate _add<T>(\n\t\tn: Node<T>,\n\t\tfactory: string,\n\t\tdeps: readonly Node<unknown>[],\n\t\topts: SugarOpts<T>,\n\t): Node<T> {\n\t\tconst id = opts.name ?? `${factory}#${this._seq++}`;\n\t\treturn this._addWithId(n, factory, deps, opts, id);\n\t}\n\n\tprivate _addWithId<T>(\n\t\tn: Node<T>,\n\t\tfactory: string,\n\t\tdeps: readonly Node<unknown>[],\n\t\topts: SugarOpts<T>,\n\t\tid: string,\n\t): Node<T> {\n\t\tassertGraphLocalNode(this, n as Node<unknown>, `graph node '${opts.name ?? factory}'`);\n\t\tfor (const dep of deps) assertGraphLocalNode(this, dep, `dep of '${opts.name ?? factory}'`);\n\t\tif (this._byId.has(id)) {\n\t\t\tthrow new Error(`graph: duplicate node id '${id}' (checkpoint/describe ids must be unique)`);\n\t\t}\n\t\tif (this._retiredIds.has(id)) {\n\t\t\tthrow new Error(`graph: node id '${id}' was released and cannot be reused (D152/D153)`);\n\t\t}\n\t\tconst meta =\n\t\t\topts.meta === undefined\n\t\t\t\t? undefined\n\t\t\t\t: (normalizeTopologyMeta(opts.meta, `graph node '${id}' meta`) as Record<string, unknown>);\n\t\tthis._entries.set(n as Node<unknown>, {\n\t\t\tnode: n as Node<unknown>,\n\t\t\tid,\n\t\t\tname: opts.name,\n\t\t\tfactory,\n\t\t\tdeps,\n\t\t\tmeta,\n\t\t\trestore: opts.restore,\n\t\t});\n\t\tsetNodeOwner(n as Node<unknown>, this);\n\t\tthis._byId.set(id, n as Node<unknown>);\n\t\tsetNodeTopologyDepsChangedObserver(n as Node<unknown>, (_node, prevDeps, nextDeps) => {\n\t\t\tthis._emitTopologyDepsChanged(n as Node<unknown>, prevDeps, nextDeps);\n\t\t});\n\t\tconst seqMatch = /#(\\d+)$/.exec(id);\n\t\tif (seqMatch) this._seq = Math.max(this._seq, Number(seqMatch[1]) + 1);\n\t\tthis._emitTopologyNodeRegistered(n as Node<unknown>);\n\t\treturn n;\n\t}\n\n\tprivate _assertDepsLocal(deps: readonly Node<unknown>[], label: string): void {\n\t\tfor (const dep of deps) assertGraphLocalNode(this, dep, label);\n\t}\n\n\tprivate _assertRegisteredNode(node: Node<unknown>, label: string): void {\n\t\tassertGraphLocalNode(this, node, label);\n\t\tif (!this._entries.has(node)) {\n\t\t\tthrow new Error(`${label} is not a registered graph node (D152)`);\n\t\t}\n\t}\n\n\tprivate _nodeOpts<T>(opts: SugarOpts<T>): NodeOptions<T> {\n\t\tif (opts.meta !== undefined) {\n\t\t\tnormalizeTopologyMeta(opts.meta, `graph node '${opts.name ?? opts.factory ?? \"node\"}' meta`);\n\t\t}\n\t\t// strip graph-only fields; inject the bound dispatcher\n\t\tconst { name: _n, meta: _m, restore: _r, ...rest } = opts;\n\t\treturn {\n\t\t\t...rest,\n\t\t\tversioning: rest.versioning ?? this._versioning,\n\t\t\tdispatcher: this._dispatcher,\n\t\t};\n\t}\n\n\tprivate _construct<TNode extends Node<unknown>>(create: () => TNode): TNode {\n\t\treturn withEnvironmentDrivers(this._environment, () => withNodeCore(this._core, create));\n\t}\n\n\t/** Look up a registered node by its id. */\n\tfind(id: string): Node<unknown> | undefined {\n\t\treturn this._byId.get(id);\n\t}\n\n\tprivate _releaseNodes(nodes: readonly Node<unknown>[], _opts: { reason?: string } = {}): void {\n\t\tconst seen = new Set<Node<unknown>>();\n\t\tconst entries: Array<{ node: Node<unknown>; entry: Entry }> = [];\n\t\tfor (const node of nodes) {\n\t\t\tif (seen.has(node)) continue;\n\t\t\tseen.add(node);\n\t\t\tconst entry = this._entries.get(node);\n\t\t\tif (entry === undefined) continue;\n\t\t\tentries.push({ node, entry });\n\t\t}\n\t\tconst releaseSet = new Set(entries.map(({ node }) => node));\n\t\tconst releaseIds = new Map(entries.map(({ node, entry }) => [node, entry.id] as const));\n\t\tfor (const entry of this._entries.values()) {\n\t\t\tif (releaseSet.has(entry.node)) continue;\n\t\t\tfor (const dep of entry.node.deps) {\n\t\t\t\tif (!releaseSet.has(dep)) continue;\n\t\t\t\tconst depId = releaseIds.get(dep) ?? dep.name ?? dep.factory ?? \"released node\";\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`graph: cannot release node group; '${entry.id}' still depends on '${depId}' (D122)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tfor (const { node, entry } of entries) {\n\t\t\tif (!isNodeRuntimeQuiescentForRelease(node)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`graph: cannot release node group; '${entry.id}' is not runtime-quiescent (D124)`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlet internalSubscribers = 0;\n\t\t\tfor (const { node: dependent } of entries) {\n\t\t\t\tif (dependent === node || !isNodeActiveForRelease(dependent)) continue;\n\t\t\t\tfor (const dep of dependent.deps) {\n\t\t\t\t\tif (dep === node) internalSubscribers += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (subscriberCountOfNode(node) > internalSubscribers) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`graph: cannot release node group; '${entry.id}' still has live subscribers (D124)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tconst releasedEvents =\n\t\t\tthis._topologyObservers.size === 0\n\t\t\t\t? []\n\t\t\t\t: entries.map(({ node, entry }) => ({\n\t\t\t\t\t\tpath: entry.id,\n\t\t\t\t\t\tfactory: entry.factory,\n\t\t\t\t\t\tdeps: this._topologyDeps(node.deps),\n\t\t\t\t\t}));\n\t\tfor (const { node, entry } of entries) {\n\t\t\tthis._entries.delete(node);\n\t\t\tthis._byId.delete(entry.id);\n\t\t\tthis._retiredIds.add(entry.id);\n\t\t}\n\t\tlet releaseError: unknown;\n\t\tfor (const { node } of entries) {\n\t\t\ttry {\n\t\t\t\treleaseRuntimeOfNode(node);\n\t\t\t} catch (error) {\n\t\t\t\tif (releaseError === undefined) releaseError = error;\n\t\t\t}\n\t\t}\n\t\tfor (const event of releasedEvents) this._emitTopologyNodeReleased(event);\n\t\tif (releaseError !== undefined) throw releaseError;\n\t}\n\n\t// ── 8 verbs (core: node/state/batch + sugar: producer/derived/effect/mount) ──\n\n\t/** ctx-level power surface: a raw `(ctx)=>void` fn (or a passthrough/state when null). */\n\tnode<T = unknown>(\n\t\tdeps: readonly Node<unknown>[] = [],\n\t\tfn: NodeFn | null = null,\n\t\topts: SugarOpts<T> = {},\n\t): Node<T> {\n\t\tthis._assertDepsLocal(deps, `dep of '${opts.name ?? \"node\"}'`);\n\t\tconst n = this._construct(() => new Node<T>(deps as Node<unknown>[], fn, this._nodeOpts(opts)));\n\t\treturn this._add(n, opts.factory ?? \"node\", deps, opts);\n\t}\n\n\t/** A manual source with `.set(v)` (L4-Q1). */\n\tstate<T>(initial: T, opts: SugarOpts<T> = {}): StateNode<T> {\n\t\tconst n = this._construct(\n\t\t\t() => new StateNode<T>([], null, { ...this._nodeOpts(opts), initial }),\n\t\t);\n\t\tthis._add(n, \"state\", [], opts);\n\t\treturn n;\n\t}\n\n\t/** ctx-level depless source; its fn runs on activation (R-rom-ram). */\n\tproducer<T = unknown>(fn: NodeFn, opts: SugarOpts<T> = {}): Node<T> {\n\t\tconst n = this._construct(() => new Node<T>([], fn, this._nodeOpts(opts)));\n\t\treturn this._add(n, \"producer\", [], opts);\n\t}\n\n\t/** value-level pure transform: deps → value (D27 wrapped; D30 throw→ERROR). */\n\tderived<const D extends readonly Node<unknown>[], T>(\n\t\tdeps: D,\n\t\tfn: DerivedFn<D, T>,\n\t\topts: SugarOpts<T> = {},\n\t): Node<T> {\n\t\tthis._assertDepsLocal(deps, `dep of '${opts.name ?? \"derived\"}'`);\n\t\tconst ctxFn: NodeFn = (ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst args = Array.from({ length: depCount(ctx) }, (_, i) =>\n\t\t\t\t\tdepLatest(ctx, i),\n\t\t\t\t) as DepValues<D>;\n\t\t\t\tconst result = fn(...args);\n\t\t\t\tif (result !== undefined) ctx.down([[\"DATA\", result]]);\n\t\t\t} catch (e) {\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"derived threw without a valid error payload\")]]); // D30: value-level throw → graph-layer ERROR\n\t\t\t}\n\t\t};\n\t\tconst n = this._construct(() => new Node<T>([...deps], ctxFn, this._nodeOpts(opts)));\n\t\treturn this._add(n, \"derived\", deps, opts);\n\t}\n\n\t/** value-level sink: deps → effect; return value (a fn) becomes onDeactivation (D28). */\n\teffect<const D extends readonly Node<unknown>[]>(\n\t\tdeps: D,\n\t\tfn: EffectFn<D>,\n\t\topts: SugarOpts<void> = {},\n\t): Node<void> {\n\t\tthis._assertDepsLocal(deps, `dep of '${opts.name ?? \"effect\"}'`);\n\t\t// effect cleanup = deactivation-only (D28 / Flag 3): the LATEST returned cleanup\n\t\t// fires ONCE when the effect deactivates (not between re-runs — onRerun was cut).\n\t\t// R-cleanup-hooks per-run lifecycle (D28 clarification / C-14): the substrate clears\n\t\t// the hook list before EACH fn run, so the effect re-registers its returned cleanup\n\t\t// every run — only the latest run's registration is live (or none, if the latest run\n\t\t// returned void). No st.registered/ctx.state bookkeeping; re-registering every run is\n\t\t// safe (the per-run clear prevents accumulation).\n\t\tconst ctxFn: NodeFn = (ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst args = Array.from({ length: depCount(ctx) }, (_, i) =>\n\t\t\t\t\tdepLatest(ctx, i),\n\t\t\t\t) as DepValues<D>;\n\t\t\t\tconst cleanup = fn(...args);\n\t\t\t\tif (typeof cleanup === \"function\") ctx.onDeactivation(cleanup);\n\t\t\t} catch (e) {\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"effect threw without a valid error payload\")]]);\n\t\t\t}\n\t\t};\n\t\tconst n = this._construct(() => new Node<void>([...deps], ctxFn, this._nodeOpts(opts)));\n\t\treturn this._add(n, \"effect\", deps, opts);\n\t}\n\n\t/** Declarative batch (D12): one wave, success→commit / throw→rollback. */\n\tbatch<T>(fn: (bctx: BatchCtx) => T): T {\n\t\treturn batchRun(fn);\n\t}\n\n\t/** Embed a child graph addressable under `at` (R-mount; mount has no deps). */\n\tmount(child: Graph, opts: { at: string }): void {\n\t\tconst mount = { at: opts.at, graph: child };\n\t\tthis._mounts.push(mount);\n\t\tif (this._topologyObservers.size > 0) this._ensureMountedTopologyForwarders();\n\t\tthis._emitTopologyMountChanged(opts.at);\n\t}\n\n\t// ── operator funnel (D43): instantiate any free-standing Operator (node sugar, D6/L1.5) ──\n\t// g.initNode is the single graph-bound entry for the whole operator/source catalog (D40):\n\t// it delegates to the FREE initNode (graph/operators.ts — the D30 throw→ERROR boundary +\n\t// dispatcher binding live there) and records the operator's REAL factory name in the\n\t// inspection index (_add) so describe shows it (D6/R-describe) while the node stays thin\n\t// (R-node-thin). Operators are free-standing factory definitions (graph/operators.ts,\n\t// graph/sources.ts) usable bare via the free initNode(); this funnel is the inspectable\n\t// path. Replaces the per-operator methods.\n\n\t/**\n\t * Instantiate an operator (or source) factory as a registered graph node. `deps` are\n\t * type-checked against the operator's input element type; the output type flows from the\n\t * operator. A source is a depless operator — pass `[]`. Caller `opts` (name/meta/behavioral\n\t * overrides) win over the operator's baked-in `opts`.\n\t */\n\tinitNode<TIn, TOut>(\n\t\top: Operator<TIn, TOut>,\n\t\tdeps: readonly Node<TIn>[],\n\t\topts: SugarOpts<TOut> = {},\n\t): Node<TOut> {\n\t\tconst entryOpts =\n\t\t\top.restore !== undefined && !(\"restore\" in opts) ? { ...opts, restore: op.restore } : opts;\n\t\tfor (const dep of deps as readonly Node<unknown>[])\n\t\t\tassertGraphLocalNode(this, dep, `dep of '${entryOpts.name ?? op.factory}'`);\n\t\t// Node<T> is invariant (T appears in NodeOptions.initial); widen the typed deps to the\n\t\t// erased Node surface the free initNode / _add accept (same cast the old methods used).\n\t\tconst erased = deps as readonly Node<unknown>[];\n\t\tconst n = withEnvironmentDrivers(this._environment, () =>\n\t\t\tinitNodeWithCore(this._core, op, erased, this._nodeOpts(entryOpts)),\n\t\t);\n\t\treturn this._add(n, op.factory, erased, entryOpts);\n\t}\n\n\t/**\n\t * Graph-owned activation root for internal helper nodes. This is the sanctioned keepalive shape:\n\t * a graph, not a helper closure, owns the subscription and returns the release handle.\n\t */\n\tretain<T>(node: Node<T>, opts: { reason?: string } = {}): () => void {\n\t\tassertGraphLocalNode(this, node as Node<unknown>, opts.reason ?? \"retained node\");\n\t\treturn node.subscribe(() => {});\n\t}\n\n\t/**\n\t * D152 graph-owned topology/release group. Members are ordinary registered graph nodes;\n\t * release is quiescent-only and removes ids atomically without synthesizing protocol messages.\n\t */\n\ttopologyGroup(opts: TopologyGroupOptions = {}): TopologyGroup {\n\t\treturn new GraphTopologyGroup(this, opts);\n\t}\n\n\t// ── inspection: describe / observe / profile (D39) ──\n\n\t/** Live point-in-time structure snapshot (R-describe / D39 / D51). `_prefix` carries the mount path. */\n\tdescribe(opts: DescribeOpts = {}, _prefix = \"\"): DescribeSnapshot {\n\t\t// D51: edges derive from each node's CURRENT/LIVE deps (entry.node.deps, NOT the\n\t\t// construction-time entry.deps), so a rewire (C-8 immediate / C-11 *Map deferred) is\n\t\t// reflected and every edge is a real current subscription (D3). A live dep absent from this\n\t\t// graph's index (a runtime *Map inner / bare fromAny node) is AUTO-DISCOVERED as a snapshot\n\t\t// node with a synthesized stable id (B2). B38 extends this to transitive live-reachability:\n\t\t// discovered unregistered nodes are recursively expanded through their own live deps.\n\t\tconst discovered = new Map<Node<unknown>, string>(); // unregistered live dep → synth local id\n\t\tconst localId = (n: Node<unknown>): string => {\n\t\t\tconst e = this._entries.get(n);\n\t\t\tif (e) return `${_prefix}${e.id}`;\n\t\t\t// unregistered: a stable synthetic id, cached so successive describes + both call sites\n\t\t\t// agree; the `~` prefix can't collide with a registered name or `factory#seq`.\n\t\t\tlet sid = this._synthIds.get(n);\n\t\t\tif (sid === undefined) {\n\t\t\t\t// the `~` prefix avoids the registered `name`/`factory#seq` space; guard the\n\t\t\t\t// pathological case of a user node literally named `~factory#n` (bump until free).\n\t\t\t\tdo {\n\t\t\t\t\tsid = `~${n.factory ?? \"?\"}#${this._synthSeq++}`;\n\t\t\t\t} while (this._byId.has(sid));\n\t\t\t\tthis._synthIds.set(n, sid);\n\t\t\t}\n\t\t\tdiscovered.set(n, sid);\n\t\t\treturn `${_prefix}${sid}`;\n\t\t};\n\t\tconst nodes: DescribeNode[] = [];\n\t\tconst edges: DescribeEdge[] = [];\n\t\t// pass 1: registered nodes, reading LIVE deps (localId records any unregistered inner).\n\t\tfor (const entry of this._entries.values()) {\n\t\t\tconst id = `${_prefix}${entry.id}`;\n\t\t\tconst liveIds = entry.node.deps.map(localId);\n\t\t\tconst dnode: DescribeNode = {\n\t\t\t\tid,\n\t\t\t\tfactory: entry.factory,\n\t\t\t\tstatus: entry.node.status,\n\t\t\t\tdeps: liveIds,\n\t\t\t};\n\t\t\tif (entry.name !== undefined) dnode.name = entry.name;\n\t\t\tif (entry.node.cache !== undefined) dnode.value = entry.node.cache; // absent = SENTINEL\n\t\t\tif (entry.node.version !== undefined) dnode.version = entry.node.version;\n\t\t\tif (entry.meta !== undefined) dnode.meta = entry.meta;\n\t\t\tnodes.push(dnode);\n\t\t\tfor (const from of liveIds) edges.push({ from, to: id });\n\t\t}\n\t\t// pass 2: recursively emit auto-discovered unregistered nodes (D51+B38). localId() may add\n\t\t// further unregistered deps to `discovered` while this loop runs; a visited set keeps each\n\t\t// discovered node emitted once (stable ids via _synthIds).\n\t\tconst visited = new Set<Node<unknown>>();\n\t\tconst queue: Node<unknown>[] = [...discovered.keys()];\n\t\tfor (let i = 0; i < queue.length; i += 1) {\n\t\t\tconst inner = queue[i];\n\t\t\tif (visited.has(inner)) continue;\n\t\t\tvisited.add(inner);\n\t\t\tconst sid = discovered.get(inner);\n\t\t\tif (sid === undefined) continue;\n\t\t\tconst liveIds = inner.deps.map(localId);\n\t\t\tfor (const dep of inner.deps) {\n\t\t\t\tif (!this._entries.has(dep) && !visited.has(dep)) queue.push(dep);\n\t\t\t}\n\t\t\tconst dnode: DescribeNode = {\n\t\t\t\tid: `${_prefix}${sid}`,\n\t\t\t\tfactory: inner.factory ?? \"?\",\n\t\t\t\tstatus: inner.status,\n\t\t\t\tdeps: liveIds,\n\t\t\t};\n\t\t\tif (inner.cache !== undefined) dnode.value = inner.cache;\n\t\t\tif (inner.version !== undefined) dnode.version = inner.version;\n\t\t\tnodes.push(dnode);\n\t\t\tfor (const from of liveIds) edges.push({ from, to: dnode.id });\n\t\t}\n\t\tconst snap: DescribeSnapshot = { nodes, edges };\n\t\tif (this.name !== undefined) snap.name = this.name;\n\t\tif (this._mounts.length > 0) {\n\t\t\tsnap.subgraphs = this._mounts.map((m) => m.graph.describe({}, `${_prefix}${m.at}::`));\n\t\t}\n\t\treturn opts.explain ? explainSubset(snap, opts.explain) : snap;\n\t}\n\n\t/**\n\t * D173 pure-structure topology snapshot over the same live truth source as describe().\n\t * Runtime status/value/version remain on describe(); blueprint metadata is a later envelope.\n\t */\n\ttopology(): GraphTopologySnapshot {\n\t\treturn topologyFromDescribe(this.describe());\n\t}\n\n\t/**\n\t * D177 synchronous audit/collaboration envelope over the pure topology snapshot.\n\t * Hashing and environment provenance enrichment stay in pure helpers outside Graph core.\n\t */\n\tblueprint(opts: GraphBlueprintOptions = {}): GraphBlueprint {\n\t\tconst topology = normalizeTopology(this.topology());\n\t\tconst out: GraphBlueprint = {\n\t\t\tversion: GRAPH_BLUEPRINT_VERSION,\n\t\t\ttopology,\n\t\t};\n\t\tif (opts.diagnostics) {\n\t\t\t(out as { diagnostics?: ReturnType<typeof graphBlueprintDiagnostics> }).diagnostics =\n\t\t\t\tgraphBlueprintDiagnostics(topology);\n\t\t}\n\t\tif (opts.provenance !== undefined) {\n\t\t\t(out as { provenance?: GraphBlueprint[\"provenance\"] }).provenance = normalizeTopologyMeta(\n\t\t\t\topts.provenance,\n\t\t\t\t\"graph blueprint provenance\",\n\t\t\t\t\"provenance\",\n\t\t\t);\n\t\t}\n\t\treturn out;\n\t}\n\n\tprivate _observeTargets(path?: string): Array<[string, Node<unknown>]> {\n\t\tconst all: Array<[string, Node<unknown>]> = [...this._entries.values()].map((e) => [\n\t\t\te.id,\n\t\t\te.node,\n\t\t]);\n\t\tif (path === undefined) return all; // whole graph\n\t\tconst exact = this._byId.get(path);\n\t\tif (exact) return [[path, exact]]; // single node\n\t\treturn all.filter(([id]) => id.startsWith(`${path}::`)); // subtree (mount-aware :: boundary, QA A-1)\n\t}\n\n\t/**\n\t * observe(path?) = read-only enveloped EGRESS (R-observe / D39). NOT a graph node — it\n\t * taps the target node(s) via subscribe and forwards each Message as an ObserveEvent.\n\t * No path = whole graph; an exact id = a single node; otherwise a `::`-prefix subtree.\n\t */\n\t// NOTE (R-observe/D19): observe is a real, lazily-ACTIVATING subscriber — observing a\n\t// cold node runs its fn (and activates upstream); whole-graph observe() activates the\n\t// graph. \"Read-only\" means it never emits/mutates node state, NOT that it avoids\n\t// activation. Use it knowing inspection of a cold graph wakes it.\n\tobserve(path?: string): ObserveStream {\n\t\tconst targets = this._observeTargets(path);\n\t\treturn {\n\t\t\tsubscribe: (sink) => {\n\t\t\t\tconst unsubs = targets.map(([id, n]) =>\n\t\t\t\t\tn.subscribe((msg) => {\n\t\t\t\t\t\tsink({ path: id, msg, tier: messageTier(msg[0]), seq: this._clock++ });\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\treturn () => {\n\t\t\t\t\tfor (const u of unsubs) u();\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * D145 observeTopology(path?) = read-only graph lifecycle egress over the existing\n\t * graph registry. It is not a graph node, does not subscribe to nodes, and emits no DATA.\n\t */\n\tobserveTopology(path?: string): TopologyStream {\n\t\treturn {\n\t\t\tsubscribe: (sink) => {\n\t\t\t\tconst id = this._topologyObserverSeq++;\n\t\t\t\tthis._topologyObservers.set(id, { path, sink });\n\t\t\t\tthis._ensureMountedTopologyForwarders();\n\t\t\t\treturn () => {\n\t\t\t\t\tthis._topologyObservers.delete(id);\n\t\t\t\t\tif (this._topologyObservers.size === 0) this._releaseMountedTopologyForwarders();\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate _idForTopologyNode(n: Node<unknown>): string {\n\t\tconst e = this._entries.get(n);\n\t\tif (e) return e.id;\n\t\tlet sid = this._synthIds.get(n);\n\t\tif (sid === undefined) {\n\t\t\tdo {\n\t\t\t\tsid = `~${n.factory ?? \"?\"}#${this._synthSeq++}`;\n\t\t\t} while (this._byId.has(sid));\n\t\t\tthis._synthIds.set(n, sid);\n\t\t}\n\t\treturn sid;\n\t}\n\n\tprivate _topologyDeps(deps: readonly Node<unknown>[]): string[] {\n\t\treturn deps.map((dep) => this._idForTopologyNode(dep));\n\t}\n\n\tprivate _emitTopologyNodeRegistered(node: Node<unknown>): void {\n\t\tif (this._topologyObservers.size === 0) return;\n\t\tconst entry = this._entries.get(node);\n\t\tif (entry === undefined) return;\n\t\tthis._emitTopologyEvent({\n\t\t\tkind: \"node-registered\",\n\t\t\tpath: entry.id,\n\t\t\tfactory: entry.factory,\n\t\t\tdeps: this._topologyDeps(node.deps),\n\t\t\tseq: this._clock++,\n\t\t});\n\t}\n\n\tprivate _emitTopologyDepsChanged(\n\t\tnode: Node<unknown>,\n\t\tprevDeps: readonly Node<unknown>[],\n\t\tnextDeps: readonly Node<unknown>[],\n\t): void {\n\t\tif (this._topologyObservers.size === 0) return;\n\t\tconst entry = this._entries.get(node);\n\t\tif (entry === undefined) return;\n\t\tthis._emitTopologyEvent({\n\t\t\tkind: \"deps-changed\",\n\t\t\tpath: entry.id,\n\t\t\tprevDeps: this._topologyDeps(prevDeps),\n\t\t\tdeps: this._topologyDeps(nextDeps),\n\t\t\tseq: this._clock++,\n\t\t});\n\t}\n\n\tprivate _emitTopologyNodeReleased(event: {\n\t\tpath: string;\n\t\tfactory: string;\n\t\tdeps: readonly string[];\n\t}): void {\n\t\tif (this._topologyObservers.size === 0) return;\n\t\tthis._emitTopologyEvent({\n\t\t\tkind: \"node-released\",\n\t\t\tpath: event.path,\n\t\t\tfactory: event.factory,\n\t\t\tdeps: [...event.deps],\n\t\t\tseq: this._clock++,\n\t\t});\n\t}\n\n\tprivate _emitTopologyMountChanged(path: string): void {\n\t\tif (this._topologyObservers.size === 0) return;\n\t\tthis._emitTopologyEvent({\n\t\t\tkind: \"mount-changed\",\n\t\t\tpath,\n\t\t\tfactory: \"mount\",\n\t\t\tdeps: [],\n\t\t\tseq: this._clock++,\n\t\t});\n\t}\n\n\tprivate _ensureMountedTopologyForwarders(): void {\n\t\tif (this._topologyObservers.size === 0) return;\n\t\tfor (const mount of this._mounts) {\n\t\t\tif (mount.topologyUnsub !== undefined) continue;\n\t\t\tconst mountPath = mount.at;\n\t\t\tmount.topologyUnsub = mount.graph.observeTopology().subscribe((event) => {\n\t\t\t\tthis._emitMountedTopologyEvent(mountPath, event);\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate _releaseMountedTopologyForwarders(): void {\n\t\tfor (const mount of this._mounts) {\n\t\t\tmount.topologyUnsub?.();\n\t\t\tmount.topologyUnsub = undefined;\n\t\t}\n\t}\n\n\tprivate _emitMountedTopologyEvent(mountPath: string, event: TopologyEvent): void {\n\t\tif (this._topologyObservers.size === 0) return;\n\t\tthis._emitTopologyEvent({\n\t\t\tkind: event.kind,\n\t\t\tpath: prefixTopologyPath(mountPath, event.path),\n\t\t\tdeps: event.deps.map((dep) => prefixTopologyPath(mountPath, dep)),\n\t\t\t...(event.prevDeps !== undefined\n\t\t\t\t? { prevDeps: event.prevDeps.map((dep) => prefixTopologyPath(mountPath, dep)) }\n\t\t\t\t: {}),\n\t\t\t...(event.factory !== undefined ? { factory: event.factory } : {}),\n\t\t\tseq: this._clock++,\n\t\t});\n\t}\n\n\tprivate _emitTopologyEvent(event: TopologyEvent): void {\n\t\tif (this._topologyDelivering) {\n\t\t\tthis._topologyQueue.push(event);\n\t\t\treturn;\n\t\t}\n\t\tthis._topologyDelivering = true;\n\t\ttry {\n\t\t\tlet current: TopologyEvent | undefined = event;\n\t\t\twhile (current !== undefined) {\n\t\t\t\tconst observers = [...this._topologyObservers.entries()];\n\t\t\t\tfor (const [id, observer] of observers) {\n\t\t\t\t\tif (this._topologyObservers.get(id) !== observer) continue;\n\t\t\t\t\tif (observer.path !== undefined && !topologyPathMatches(current.path, observer.path))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tobserver.sink(cloneTopologyEvent(current));\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// D145 egress is read-only inspection; observer failure must not veto a\n\t\t\t\t\t\t// graph registry/rewire mutation that already committed.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrent = this._topologyQueue.shift();\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._topologyDelivering = false;\n\t\t}\n\t}\n\n\t/**\n\t * profile() = accumulated-counter snapshot (R-profile / D39). invokes + duration are\n\t * dispatcher-backed (the invoke funnel, F-DISPATCH-ALL) — counters never live on the\n\t * thin node (R-node-thin). Requires `graph({ profile: true })` (opt-in, F-PERF).\n\t */\n\tprofile(): Profile {\n\t\tconst nodes: Record<string, NodeProfile> = {};\n\t\tlet totalInvokes = 0;\n\t\tfor (const e of this._entries.values()) {\n\t\t\tconst h = e.node.handle;\n\t\t\tconst stat = h ? this._dispatcher.statFor(h) : undefined;\n\t\t\tconst invokes = stat?.invokes ?? 0;\n\t\t\tnodes[e.id] = {\n\t\t\t\tinvokes,\n\t\t\t\ttotalDurationNs: stat?.totalDurationNs ?? 0,\n\t\t\t\tlastDurationNs: stat?.lastDurationNs ?? 0,\n\t\t\t\tstatus: e.node.status,\n\t\t\t};\n\t\t\t// graph-scoped (QA D-2): sum THIS graph's nodes, NOT the dispatcher-global\n\t\t\t// counter (which would leak invokes from other graphs sharing the dispatcher).\n\t\t\ttotalInvokes += invokes;\n\t\t}\n\t\treturn { totalInvokes, nodes };\n\t}\n\n\t/** Versioned graph lifecycle checkpoint (R-snapshot / D83 / D90). Pure capture, no storage I/O. */\n\tcheckpoint(): GraphCheckpoint {\n\t\treturn this._checkpoint(\"\", new WeakSet());\n\t}\n\n\tprivate _checkpoint(_prefix: string, stack: WeakSet<Graph>): GraphCheckpoint {\n\t\tif (stack.has(this)) {\n\t\t\tthrow new Error(\"checkpoint: cyclic graph mount detected\");\n\t\t}\n\t\tstack.add(this);\n\t\tconst discovered = new Map<Node<unknown>, string>();\n\t\tconst localId = (n: Node<unknown>): string => {\n\t\t\tconst e = this._entries.get(n);\n\t\t\tif (e) return `${_prefix}${e.id}`;\n\t\t\tlet sid = this._synthIds.get(n);\n\t\t\tif (sid === undefined) {\n\t\t\t\tdo {\n\t\t\t\t\tsid = `~${n.factory ?? \"?\"}#${this._synthSeq++}`;\n\t\t\t\t} while (this._byId.has(sid));\n\t\t\t\tthis._synthIds.set(n, sid);\n\t\t\t}\n\t\t\tdiscovered.set(n, sid);\n\t\t\treturn `${_prefix}${sid}`;\n\t\t};\n\t\tconst nodes: GraphCheckpointNode[] = [];\n\t\tconst edges: DescribeEdge[] = [];\n\t\tfor (const entry of this._entries.values()) {\n\t\t\tconst id = `${_prefix}${entry.id}`;\n\t\t\tconst liveIds = entry.node.deps.map(localId);\n\t\t\tnodes.push(\n\t\t\t\tthis._checkpointNode(entry.node, id, {\n\t\t\t\t\tname: entry.name,\n\t\t\t\t\tfactory: checkpointFactory(entry.factory, entry.node, false, entry.restore, entry.meta),\n\t\t\t\t\tdeps: liveIds,\n\t\t\t\t\tmeta: entry.meta,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tfor (const from of liveIds) edges.push({ from, to: id });\n\t\t}\n\t\tconst visited = new Set<Node<unknown>>();\n\t\tconst queue: Node<unknown>[] = [...discovered.keys()];\n\t\tfor (let i = 0; i < queue.length; i += 1) {\n\t\t\tconst inner = queue[i];\n\t\t\tif (visited.has(inner)) continue;\n\t\t\tvisited.add(inner);\n\t\t\tconst sid = discovered.get(inner);\n\t\t\tif (sid === undefined) continue;\n\t\t\tconst liveIds = inner.deps.map(localId);\n\t\t\tfor (const dep of inner.deps) {\n\t\t\t\tif (!this._entries.has(dep) && !visited.has(dep)) queue.push(dep);\n\t\t\t}\n\t\t\tconst id = `${_prefix}${sid}`;\n\t\t\tnodes.push(\n\t\t\t\tthis._checkpointNode(inner, id, {\n\t\t\t\t\tfactory: checkpointFactory(inner.factory ?? \"?\", inner, true),\n\t\t\t\t\tdeps: liveIds,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tfor (const from of liveIds) edges.push({ from, to: id });\n\t\t}\n\t\tconst checkpoint: GraphCheckpoint = {\n\t\t\tversion: GRAPH_CHECKPOINT_VERSION,\n\t\t\tnodes,\n\t\t\tedges,\n\t\t};\n\t\tif (this.name !== undefined) checkpoint.name = this.name;\n\t\tif (this._mounts.length > 0) {\n\t\t\tcheckpoint.mounts = this._mounts.map((m) => ({\n\t\t\t\tat: m.at,\n\t\t\t\tcheckpoint: m.graph._checkpoint(\"\", stack),\n\t\t\t}));\n\t\t}\n\t\tstack.delete(this);\n\t\treturn toCheckpointJson(checkpoint, \"checkpoint\") as unknown as GraphCheckpoint;\n\t}\n\n\tprivate _checkpointNode(\n\t\tnode: Node<unknown>,\n\t\tid: string,\n\t\topts: {\n\t\t\tname?: string;\n\t\t\tfactory: GraphCheckpointFactory;\n\t\t\tdeps: string[];\n\t\t\tmeta?: Record<string, unknown>;\n\t\t},\n\t): GraphCheckpointNode {\n\t\tconst state = checkpointStateOfNode(node);\n\t\tassertCheckpointQuiescentStatus(node.status, id, \"checkpoint\");\n\t\tconst nonAuthoritativeCollectionHelper = isNonAuthoritativeCollectionHelperMeta(opts.meta);\n\t\tconst out: GraphCheckpointNode = {\n\t\t\tid,\n\t\t\tfactory: opts.factory,\n\t\t\tstatus: node.status,\n\t\t\tdeps: opts.deps,\n\t\t\tvalue: nonAuthoritativeCollectionHelper\n\t\t\t\t? { kind: \"SENTINEL\" }\n\t\t\t\t: checkpointValue(state.cache, state.hasData, `${id}.value`),\n\t\t\tterminal: checkpointTerminal(state.terminal, `${id}.terminal`),\n\t\t\tlifecycle: { activated: state.activated, hasCalledFnOnce: state.hasCalledFnOnce },\n\t\t\tctxState: {\n\t\t\t\tpersist: state.ctxState.persist,\n\t\t\t\tvalue: nonAuthoritativeCollectionHelper\n\t\t\t\t\t? { kind: \"SENTINEL\" }\n\t\t\t\t\t: checkpointValue(\n\t\t\t\t\t\t\tstate.ctxState.value,\n\t\t\t\t\t\t\tstate.ctxState.value !== SENTINEL,\n\t\t\t\t\t\t\t`${id}.ctxState`,\n\t\t\t\t\t\t),\n\t\t\t},\n\t\t};\n\t\tif (opts.name !== undefined) out.name = opts.name;\n\t\tconst backendState = checkpointBackendStateOfNode(node, `${id}.backendState`);\n\t\tif (backendState !== undefined) out.backendState = backendState;\n\t\tif (state.version !== undefined) out.version = state.version;\n\t\tif (opts.meta !== undefined)\n\t\t\tout.meta = toCheckpointJson(opts.meta, `${id}.meta`) as {\n\t\t\t\t[key: string]: GraphCheckpointJson;\n\t\t\t};\n\t\treturn out;\n\t}\n}\n\nfunction isNonAuthoritativeCollectionHelperMeta(\n\tmeta: Record<string, unknown> | undefined,\n): boolean {\n\treturn (\n\t\tmeta?.kind === \"collection_delta\" ||\n\t\tmeta?.kind === \"collection_intent\" ||\n\t\tmeta?.kind === \"collection_policy_apply\" ||\n\t\tmeta?.kind === \"collection_snapshot\" ||\n\t\tmeta?.kind === \"collection_snapshot_prep\"\n\t);\n}\n\nfunction assertCheckpointQuiescentStatus(status: string, id: string, op: string): void {\n\tif (status === \"pending\" || status === \"dirty\") {\n\t\tthrow new Error(\n\t\t\t`${op}: node '${id}' has non-quiescent status '${status}' that cannot be checkpoint-restored yet`,\n\t\t);\n\t}\n}\n\nfunction topologyPathMatches(eventPath: string, path: string): boolean {\n\treturn eventPath === path || eventPath.startsWith(`${path}::`);\n}\n\nfunction prefixTopologyPath(prefix: string, path: string): string {\n\treturn `${prefix}::${path}`;\n}\n\nfunction cloneTopologyEvent(event: TopologyEvent): TopologyEvent {\n\tconst deps = Object.freeze([...event.deps]);\n\tconst prevDeps = event.prevDeps === undefined ? undefined : Object.freeze([...event.prevDeps]);\n\treturn Object.freeze({\n\t\tkind: event.kind,\n\t\tpath: event.path,\n\t\tdeps,\n\t\t...(prevDeps !== undefined ? { prevDeps } : {}),\n\t\t...(event.factory !== undefined ? { factory: event.factory } : {}),\n\t\tseq: event.seq,\n\t});\n}\n\nfunction checkpointFactory(\n\tname: string,\n\tnode: Node<unknown>,\n\tunregistered: boolean,\n\trestore?: { ref: string; config?: unknown; configVersion?: unknown },\n\tmeta?: Record<string, unknown>,\n): GraphCheckpointFactory {\n\tconst state = checkpointStateOfNode(node);\n\tif (unregistered) {\n\t\treturn {\n\t\t\tkind: \"local-only\",\n\t\t\tname,\n\t\t\treason: \"node is an unregistered live dependency auto-discovered from topology\",\n\t\t};\n\t}\n\tif (\n\t\trestore === undefined &&\n\t\ttypeof meta?.kind === \"string\" &&\n\t\tmeta.kind.startsWith(\"collection_\")\n\t) {\n\t\treturn {\n\t\t\tkind: \"local-only\",\n\t\t\tname,\n\t\t\treason: \"collection helper node has no backend checkpoint restore metadata\",\n\t\t};\n\t}\n\tif (restore !== undefined) {\n\t\tconst out: GraphCheckpointFactory = {\n\t\t\tkind: \"registry-ref\",\n\t\t\tref: toCheckpointJson(restore.ref, `${name}.factory.ref`) as string,\n\t\t};\n\t\tif (restore.config !== undefined)\n\t\t\tout.config = toCheckpointJson(restore.config, `${name}.factory.config`);\n\t\tif (restore.configVersion !== undefined)\n\t\t\tout.configVersion = toCheckpointJson(restore.configVersion, `${name}.factory.configVersion`);\n\t\treturn out;\n\t}\n\tif (state.handle !== null) {\n\t\treturn {\n\t\t\tkind: \"local-only\",\n\t\t\tname,\n\t\t\treason: \"node uses a function body; first-cut checkpoints do not serialize local functions\",\n\t\t};\n\t}\n\treturn { kind: \"registry-ref\", ref: name };\n}\n\n/** Filter a snapshot to the causal chain from→to (forward-reachable(from) ∩ back-reachable(to)). */\nfunction explainSubset(\n\tsnap: DescribeSnapshot,\n\tchain: { from: string; to: string },\n): DescribeSnapshot {\n\tconst fwd = new Map<string, string[]>();\n\tconst rev = new Map<string, string[]>();\n\tconst push = (map: Map<string, string[]>, k: string, v: string): void => {\n\t\tconst a = map.get(k);\n\t\tif (a) a.push(v);\n\t\telse map.set(k, [v]);\n\t};\n\tfor (const e of snap.edges) {\n\t\tpush(fwd, e.from, e.to);\n\t\tpush(rev, e.to, e.from);\n\t}\n\tconst reach = (start: string, adj: Map<string, string[]>): Set<string> => {\n\t\tconst seen = new Set<string>([start]);\n\t\tconst stack = [start];\n\t\twhile (stack.length > 0) {\n\t\t\tconst cur = stack.pop() as string;\n\t\t\tfor (const nxt of adj.get(cur) ?? []) {\n\t\t\t\tif (!seen.has(nxt)) {\n\t\t\t\t\tseen.add(nxt);\n\t\t\t\t\tstack.push(nxt);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn seen;\n\t};\n\tconst onPath = new Set([...reach(chain.from, fwd)].filter((id) => reach(chain.to, rev).has(id)));\n\treturn {\n\t\t...(snap.name !== undefined ? { name: snap.name } : {}),\n\t\tnodes: snap.nodes.filter((n) => onPath.has(n.id)),\n\t\tedges: snap.edges.filter((e) => onPath.has(e.from) && onPath.has(e.to)),\n\t};\n}\n\n/** Construct a Graph (default global dispatcher; L4-Q4). */\nexport function graph(opts: GraphOptions = {}): Graph {\n\treturn new Graph(opts);\n}\n\n/** @internal D122 graph-owned ephemeral node-group release. */\nexport function releaseGraphNodes(\n\tgraph: Graph,\n\tnodes: readonly Node<unknown>[],\n\topts: { reason?: string } = {},\n): void {\n\tconst registrar = lifecycleRegistrars.get(graph);\n\tif (registrar === undefined) throw new Error(\"graph: unknown lifecycle registrar\");\n\tregistrar.releaseNodes(nodes, opts);\n}\n\n/** @internal D94 descriptor path: register a restored state node without widening Graph. */\nexport function restoreStateNodeInGraph<T = unknown>(\n\tgraph: Graph,\n\tid: string,\n\topts: SugarOpts<T> = {},\n): StateNode<T> {\n\tconst registrar = restoreRegistrars.get(graph);\n\tif (registrar === undefined) throw new Error(\"restoreGraph: unknown graph restore registrar\");\n\treturn registrar.stateNode(id, opts);\n}\n\n/** @internal D94 descriptor path: register a restored ctx-level node without widening Graph. */\nexport function restoreNodeInGraph<T = unknown>(\n\tgraph: Graph,\n\tid: string,\n\tfactory: string,\n\tdeps: readonly Node<unknown>[],\n\tfn: NodeFn | null,\n\topts: SugarOpts<T> = {},\n): Node<T> {\n\tconst registrar = restoreRegistrars.get(graph);\n\tif (registrar === undefined) throw new Error(\"restoreGraph: unknown graph restore registrar\");\n\treturn registrar.node(id, factory, deps, fn, opts);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoCO,IAAM,WAAW;;;ACyHjB,SAAS,SAAS,KAAU,UAAmD;AACrF,SAAO,IAAI,SAAS,QAAQ,KAAK,CAAC;AACnC;AAGO,SAAS,SAAS,KAAU,UAA6C;AAC/E,QAAM,QAAQ,SAAS,KAAK,QAAQ;AACpC,MAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,QAAM,YAAY,MAAM,KAAK,EAAE,OAAO,CAAC,MAAM,MAAM,QAAQ;AAC3D,SAAO,UAAU,WAAW,IAAI,CAAC,IAAI;AACtC;;;ACbA,IAAM,sBAAsB,oBAAI,QAAwC;AA4jCjE,SAAS,kBACf,OACA,OACA,OAA4B,CAAC,GACtB;AACP,QAAM,YAAY,oBAAoB,IAAI,KAAK;AAC/C,MAAI,cAAc,OAAW,OAAM,IAAI,MAAM,oCAAoC;AACjF,YAAU,aAAa,OAAO,IAAI;AACnC;;;AHnqCO,IAAM,gBAAgB;AACtB,IAAM,kBAAkB;AACxB,IAAM,mBAAmB;AACzB,IAAM,iBAAiB;AACvB,IAA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EA,SAAS,uBAAuB,KAAoD;AACnF,QAAM,QAAQ,iBAAiB,IAAI,GAAG;AACtC,MAAI,UAAU,OAAW,OAAM,IAAI,MAAM,wCAAwC;AACjF,SAAO;AACR;","names":["command"]}
1
+ {"version":3,"sources":["../../src/messaging/index.ts","../../src/protocol/messages.ts","../../src/ctx/types.ts","../../src/messaging/internal.ts"],"sourcesContent":["/**\n * Reusable application-infrastructure messaging namespace.\n *\n * D279/D282/D284/D285/D276: messageBus is a retained topic-log plus independent\n * subscription-cursor substrate. DynamicHub is intentionally retired; do not add aliases.\n */\n\nimport { depBatch, type NodeFn } from \"../ctx/types.js\";\nimport type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport type { LockId, PullDemand } from \"../protocol/messages.js\";\nimport {\n\tattachMessageBusCommandSource,\n\tgetMessageBusState,\n\tregisterMessageBusState,\n} from \"./internal.js\";\n\nexport interface MessageEnvelope<T = unknown> {\n\treadonly topic: string;\n\treadonly seq: number;\n\treadonly payload: T;\n\treadonly key?: string;\n\treadonly idempotencyKey?: string;\n\treadonly timestampMs: number;\n\treadonly commandId?: string;\n}\n\n/** Minimal JSON Schema vocabulary for passive topic payload descriptions (D125/D132). */\nexport interface JsonSchema {\n\treadonly type?:\n\t\t| \"string\"\n\t\t| \"number\"\n\t\t| \"integer\"\n\t\t| \"boolean\"\n\t\t| \"object\"\n\t\t| \"array\"\n\t\t| \"null\"\n\t\t| readonly (\"string\" | \"number\" | \"integer\" | \"boolean\" | \"object\" | \"array\" | \"null\")[];\n\treadonly properties?: Readonly<Record<string, JsonSchema>>;\n\treadonly required?: readonly string[];\n\treadonly additionalProperties?: boolean | JsonSchema;\n\treadonly items?: JsonSchema | readonly JsonSchema[];\n\treadonly enum?: readonly unknown[];\n\treadonly const?: unknown;\n\treadonly $ref?: string;\n\treadonly definitions?: Readonly<Record<string, JsonSchema>>;\n\treadonly description?: string;\n\treadonly title?: string;\n}\n\n/** Passive envelope for payloads that cross topic, agent, or graph boundaries. */\nexport interface TopicMessage<T = unknown> {\n\treadonly id: string;\n\treadonly schema?: JsonSchema;\n\treadonly expiresAt?: string;\n\treadonly correlationId?: string;\n\treadonly payload: T;\n}\n\n/** Passive domain event vocabulary for messageBus/eventFlow composition (D329). */\nexport interface EventMessage<T = unknown> {\n\treadonly id: string;\n\treadonly type: string;\n\treadonly payload: T;\n\treadonly key?: string;\n\treadonly subjectId?: string;\n\treadonly correlationId?: string;\n\treadonly causationId?: string;\n\treadonly occurredAtMs?: number;\n\treadonly actor?: string;\n\treadonly evidenceRefs?: readonly string[];\n\treadonly schema?: JsonSchema;\n\treadonly metadata?: Readonly<Record<string, unknown>>;\n}\n\nexport interface EventMessageOptions {\n\treadonly id: string;\n\treadonly key?: string;\n\treadonly subjectId?: string;\n\treadonly correlationId?: string;\n\treadonly causationId?: string;\n\treadonly occurredAtMs?: number;\n\treadonly actor?: string;\n\treadonly evidenceRefs?: readonly string[];\n\treadonly schema?: JsonSchema;\n\treadonly metadata?: Readonly<Record<string, unknown>>;\n}\n\nexport function eventMessage<T>(\n\ttype: string,\n\tpayload: T,\n\topts: EventMessageOptions,\n): EventMessage<T> {\n\tassertNonEmpty(type, \"eventMessage.type\");\n\tassertNonEmpty(opts.id, \"eventMessage.id\");\n\treturn {\n\t\tid: opts.id,\n\t\ttype,\n\t\tpayload,\n\t\t...(opts.key === undefined ? {} : { key: opts.key }),\n\t\t...(opts.subjectId === undefined ? {} : { subjectId: opts.subjectId }),\n\t\t...(opts.correlationId === undefined ? {} : { correlationId: opts.correlationId }),\n\t\t...(opts.causationId === undefined ? {} : { causationId: opts.causationId }),\n\t\t...(opts.occurredAtMs === undefined ? {} : { occurredAtMs: opts.occurredAtMs }),\n\t\t...(opts.actor === undefined ? {} : { actor: opts.actor }),\n\t\t...(opts.evidenceRefs === undefined ? {} : { evidenceRefs: opts.evidenceRefs }),\n\t\t...(opts.schema === undefined ? {} : { schema: opts.schema }),\n\t\t...(opts.metadata === undefined ? {} : { metadata: opts.metadata }),\n\t};\n}\n\nexport function isEventMessage(value: unknown): value is EventMessage {\n\treturn eventMessageIssue(value) === undefined;\n}\n\nexport function eventMessageIssue(value: unknown): DataIssue | undefined {\n\tif (!isObjectRecord(value)) {\n\t\treturn eventIssue(\"event message must be an object\");\n\t}\n\tif (typeof value.id !== \"string\" || value.id.length === 0) {\n\t\treturn eventIssue(\"event message id must be a non-empty string\");\n\t}\n\tif (typeof value.type !== \"string\" || value.type.length === 0) {\n\t\treturn eventIssue(\"event message type must be a non-empty string\");\n\t}\n\tif (!(\"payload\" in value)) {\n\t\treturn eventIssue(\"event message payload field is required\");\n\t}\n\treturn undefined;\n}\n\nfunction eventIssue(message: string): DataIssue {\n\treturn {\n\t\tkind: \"issue\",\n\t\tcode: \"malformed-event-message\",\n\t\tmessage,\n\t\tseverity: \"error\",\n\t\tsource: \"messageBus.eventMessage\",\n\t};\n}\n\nexport const PROMPTS_TOPIC = \"prompts\";\nexport const RESPONSES_TOPIC = \"responses\";\nexport const INJECTIONS_TOPIC = \"injections\";\nexport const DEFERRED_TOPIC = \"deferred\";\nexport const SPAWNS_TOPIC = \"spawns\";\nexport const CONTEXT_TOPIC = \"context\";\nexport const TODOS_TOPIC = \"todos\";\n\nexport const STANDARD_TOPICS = Object.freeze([\n\tPROMPTS_TOPIC,\n\tRESPONSES_TOPIC,\n\tINJECTIONS_TOPIC,\n\tDEFERRED_TOPIC,\n\tSPAWNS_TOPIC,\n\tCONTEXT_TOPIC,\n\tTODOS_TOPIC,\n] as const);\n\nexport type StandardTopic = (typeof STANDARD_TOPICS)[number];\n\nexport type MessageBusTopicPolicy = \"strict\" | \"create-as-fact\";\n\nexport interface MessageBusRetentionPolicy {\n\t/** Count retention. Trimming advances headSeq and never rewrites seq (D284). */\n\treadonly maxMessages?: number;\n}\n\nexport interface MessageBusDedupePolicy {\n\t/** Duplicate commandId emits status and never publishes a second retained message (D284). */\n\treadonly commandId?: \"status\" | \"issue\";\n}\n\nexport interface MessageBusOptions<TTopic extends string = string> {\n\treadonly topics?: readonly TTopic[];\n\treadonly name?: string;\n\treadonly now?: () => number;\n\treadonly topicPolicy?: MessageBusTopicPolicy;\n\treadonly retention?: MessageBusRetentionPolicy;\n\treadonly dedupe?: MessageBusDedupePolicy;\n}\n\nexport type MessageBusCommand<T = unknown> =\n\t| {\n\t\t\treadonly kind: \"ensure-topic\";\n\t\t\treadonly topic: string;\n\t\t\treadonly commandId?: string;\n\t }\n\t| {\n\t\t\treadonly kind: \"close-topic\";\n\t\t\treadonly topic: string;\n\t\t\treadonly commandId?: string;\n\t }\n\t| {\n\t\t\treadonly kind: \"publish\";\n\t\t\treadonly topic: string;\n\t\t\treadonly payload: T;\n\t\t\treadonly key?: string;\n\t\t\treadonly commandId?: string;\n\t\t\treadonly idempotencyKey?: string;\n\t }\n\t| {\n\t\t\treadonly kind: \"topic-policy\";\n\t\t\treadonly topicPolicy: MessageBusTopicPolicy;\n\t\t\treadonly commandId?: string;\n\t }\n\t| {\n\t\t\treadonly kind: \"ack\";\n\t\t\treadonly topic: string;\n\t\t\treadonly subscriptionId: string;\n\t\t\treadonly seq: number;\n\t\t\treadonly commandId?: string;\n\t }\n\t| {\n\t\t\treadonly kind: \"seek\";\n\t\t\treadonly topic: string;\n\t\t\treadonly subscriptionId: string;\n\t\t\treadonly nextSeq: number;\n\t\t\treadonly commandId?: string;\n\t }\n\t| {\n\t\t\treadonly kind: \"close-subscription\";\n\t\t\treadonly topic: string;\n\t\t\treadonly subscriptionId: string;\n\t\t\treadonly commandId?: string;\n\t };\n\nexport type MessageBusMessage<T = unknown> = MessageEnvelope<T>;\n\nexport interface MessageBusStatus {\n\treadonly kind:\n\t\t| \"topic-created\"\n\t\t| \"topic-closed\"\n\t\t| \"message-published\"\n\t\t| \"retention-trimmed\"\n\t\t| \"duplicate-command\"\n\t\t| \"subscription-acked\"\n\t\t| \"subscription-sought\"\n\t\t| \"subscription-closed\"\n\t\t| \"command-rejected\"\n\t\t| \"projection-ready\"\n\t\t| \"projection-partial\";\n\treadonly topic?: string;\n\treadonly seq?: number;\n\treadonly headSeq?: number;\n\treadonly subscriptionId?: string;\n\treadonly nextSeq?: number;\n\treadonly commandId?: string;\n\treadonly issueCode?: string;\n\treadonly timestampMs: number;\n\treadonly details?: unknown;\n}\n\nexport interface MessageBusCatalogEntry {\n\treadonly topic: string;\n\treadonly closed: boolean;\n\treadonly headSeq: number;\n\treadonly nextSeq: number;\n\treadonly messageCount: number;\n}\n\nexport interface MessageBusCatalogPage {\n\treadonly topics: readonly MessageBusCatalogEntry[];\n\treadonly nextAfterTopic?: string;\n\treadonly hasMore: boolean;\n}\n\nexport interface MessageBusDeadLetterEntry<T = unknown> {\n\treadonly entrySeq: number;\n\treadonly topic?: string;\n\treadonly command?: MessageBusCommand<T>;\n\treadonly message?: MessageBusMessage<T>;\n\treadonly issue: DataIssue;\n\treadonly timestampMs: number;\n}\n\nexport interface MessageBusDeadLetterPage<T = unknown> {\n\treadonly entries: readonly MessageBusDeadLetterEntry<T>[];\n\treadonly nextAfterEntrySeq?: number;\n\treadonly hasMore: boolean;\n}\n\nexport interface MessageBusTopicPage<T = unknown> {\n\treadonly topic: string;\n\treadonly messages: readonly MessageBusMessage<T>[];\n\treadonly fromSeq: number;\n\treadonly throughSeq?: number;\n\treadonly nextAfterSeq?: number;\n\treadonly hasMore: boolean;\n}\n\nexport interface MessageBusCursor {\n\treadonly topic: string;\n\treadonly subscriptionId: string;\n\treadonly nextSeq: number;\n\treadonly closed: boolean;\n\treadonly retentionGap: boolean;\n\treadonly headSeq: number;\n}\n\nexport interface MessageBusAvailablePage<T = unknown> {\n\treadonly topic: string;\n\treadonly subscriptionId: string;\n\treadonly cursor: MessageBusCursor;\n\treadonly messages: readonly MessageBusMessage<T>[];\n\treadonly fromSeq: number;\n\treadonly throughSeq?: number;\n\treadonly nextAfterSeq?: number;\n\treadonly hasMore: boolean;\n}\n\nexport interface MessageBusPageParams {\n\treadonly limit?: number;\n}\n\nexport interface MessageBusCatalogParams extends MessageBusPageParams {\n\treadonly afterTopic?: string;\n\treadonly includeClosed?: boolean;\n}\n\nexport interface MessageBusDeadLetterParams extends MessageBusPageParams {\n\treadonly afterEntrySeq?: number;\n\treadonly topic?: string;\n\treadonly code?: string;\n}\n\nexport interface MessageBusTopicParams extends MessageBusPageParams {\n\treadonly afterSeq?: number;\n}\n\nexport interface MessageBusAvailableParams extends MessageBusPageParams {\n\treadonly afterSeq?: number;\n}\n\nexport interface MessageBusPullProjection<TPage> {\n\treadonly snapshot: Node<TPage>;\n\treadonly snapshotPullId: LockId;\n\treadonly status: Node<MessageBusStatus>;\n\treadonly issues: Node<DataIssue>;\n}\n\nexport interface MessageBusTopicProjection<T = unknown>\n\textends MessageBusPullProjection<MessageBusTopicPage<T>> {}\n\nexport interface MessageBusSubscription<T = unknown> {\n\treadonly available: Node<MessageBusAvailablePage<T>>;\n\treadonly availablePullId: LockId;\n\treadonly cursor: Node<MessageBusCursor>;\n\treadonly status: Node<MessageBusStatus>;\n\treadonly issues: Node<DataIssue>;\n\tack(seq: number, opts?: { commandId?: string }): MessageBusCommand;\n\tseek(nextSeq: number, opts?: { commandId?: string }): MessageBusCommand;\n\tclose(opts?: { commandId?: string }): MessageBusCommand;\n}\n\nexport interface MessageBus<TTopic extends string = string> {\n\treadonly commands: Node<MessageBusCommand>;\n\treadonly messages: Node<MessageBusMessage>;\n\treadonly status: Node<MessageBusStatus>;\n\treadonly issues: Node<DataIssue>;\n\tensureTopic(topic: TTopic | string, opts?: { commandId?: string }): MessageBusCommand;\n\tcloseTopic(topic: TTopic | string, opts?: { commandId?: string }): MessageBusCommand;\n\tpublish<T = unknown>(\n\t\ttopic: TTopic | string,\n\t\tpayload: T,\n\t\topts?: { key?: string; commandId?: string; idempotencyKey?: string },\n\t): MessageBusCommand<T>;\n\ttopic<T = unknown>(\n\t\ttopic: TTopic | string,\n\t\topts?: { name?: string },\n\t): MessageBusTopicProjection<T>;\n\tcatalog(opts?: { name?: string }): MessageBusPullProjection<MessageBusCatalogPage>;\n\tdeadLetter<T = unknown>(opts?: {\n\t\tname?: string;\n\t}): MessageBusPullProjection<MessageBusDeadLetterPage<T>>;\n\tsubscription<T = unknown>(opts: {\n\t\ttopic: TTopic | string;\n\t\tsubscriptionId: string;\n\t\tfrom?: \"earliest\" | \"latest\" | number;\n\t\tname?: string;\n\t}): MessageBusSubscription<T>;\n}\n\nexport interface ToTopicOptions {\n\treadonly name?: string;\n\treadonly keyOf?: (value: unknown) => string | undefined;\n\treadonly commandIdOf?: (value: unknown) => string | undefined;\n}\n\nexport interface ToTopicBundle<T> {\n\treadonly commands: Node<MessageBusCommand<T>>;\n\trelease(): void;\n}\n\ninterface TopicState {\n\tclosed: boolean;\n\theadSeq: number;\n\tnextSeq: number;\n\tmessages: MessageBusMessage[];\n}\n\ninterface SubscriptionState {\n\ttopic: string;\n\tsubscriptionId: string;\n\tnextSeq: number;\n\tclosed: boolean;\n\tretentionGap: boolean;\n}\n\ntype RuntimeEvent<T = unknown> =\n\t| { readonly kind: \"message\"; readonly message: MessageBusMessage<T> }\n\t| { readonly kind: \"status\"; readonly status: MessageBusStatus }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"dead-letter\"; readonly entry: MessageBusDeadLetterEntry<T> };\n\ninterface MessageBusState {\n\treadonly graph: Graph;\n\treadonly name: string;\n\treadonly now: () => number;\n\ttopicPolicy: MessageBusTopicPolicy;\n\treadonly retention: MessageBusRetentionPolicy;\n\treadonly dedupe: MessageBusDedupePolicy;\n\treadonly topics: Map<string, TopicState>;\n\treadonly subscriptions: Map<string, SubscriptionState>;\n\treadonly seenCommandIds: Set<string>;\n\treadonly seenIdempotencyKeys: Set<string>;\n\treadonly deadLetters: MessageBusDeadLetterEntry[];\n\tdeadLetterSeq: number;\n\treadonly commandSources: Node<MessageBusCommand>[];\n\treadonly commandBody: NodeFn;\n}\n\nexport function messageBus<TTopic extends string>(\n\tgraph: Graph,\n\topts: MessageBusOptions<TTopic> = {},\n): MessageBus<TTopic> {\n\tconst name = opts.name ?? \"messageBus\";\n\tconst initialTopics = uniqueTopics(opts.topics ?? []);\n\tconst commandSources: Node<MessageBusCommand>[] = [];\n\tconst commandBody: NodeFn = (ctx) => {\n\t\tfor (let i = 0; i < commandSources.length; i++) {\n\t\t\tfor (const command of depBatch(ctx, i) ?? []) ctx.down([[\"DATA\", command]]);\n\t\t}\n\t};\n\tconst commands = graph.node<MessageBusCommand>([], commandBody, {\n\t\tname: `${name}/commands`,\n\t\tfactory: \"messageBusCommands\",\n\t\tcompleteWhenDepsComplete: false,\n\t\terrorWhenDepsError: false,\n\t});\n\tconst state: MessageBusState = {\n\t\tgraph,\n\t\tname,\n\t\tnow: opts.now ?? Date.now,\n\t\ttopicPolicy: opts.topicPolicy ?? \"strict\",\n\t\tretention: opts.retention ?? {},\n\t\tdedupe: opts.dedupe ?? { commandId: \"status\" },\n\t\ttopics: new Map(initialTopics.map((topic) => [topic, makeTopicState()])),\n\t\tsubscriptions: new Map(),\n\t\tseenCommandIds: new Set(),\n\t\tseenIdempotencyKeys: new Set(),\n\t\tdeadLetters: [],\n\t\tdeadLetterSeq: 0,\n\t\tcommandSources,\n\t\tcommandBody,\n\t};\n\tconst runtime = graph.node<RuntimeEvent>(\n\t\t[commands],\n\t\t(ctx) => {\n\t\t\tfor (const command of depBatch(ctx, 0) ?? []) {\n\t\t\t\tfor (const event of reduceMessageBusCommand(state, command as MessageBusCommand)) {\n\t\t\t\t\tctx.down([[\"DATA\", event]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/runtime`,\n\t\t\tfactory: \"messageBusRuntime\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tgraph.retain(runtime, { reason: `${name}.messageBus.runtime` });\n\tconst messages = graph.node<MessageBusMessage>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const event of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = event as RuntimeEvent;\n\t\t\t\tif (typed.kind === \"message\") ctx.down([[\"DATA\", typed.message]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/messages`,\n\t\t\tfactory: \"messageBusMessages\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst status = graph.node<MessageBusStatus>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const event of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = event as RuntimeEvent;\n\t\t\t\tif (typed.kind === \"status\") ctx.down([[\"DATA\", typed.status]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/status`,\n\t\t\tfactory: \"messageBusStatus\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst issues = graph.node<DataIssue>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const event of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = event as RuntimeEvent;\n\t\t\t\tif (typed.kind === \"issue\") ctx.down([[\"DATA\", typed.issue]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/issues`,\n\t\t\tfactory: \"messageBusIssues\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\n\tconst bus: MessageBus<TTopic> = {\n\t\tcommands,\n\t\tmessages,\n\t\tstatus,\n\t\tissues,\n\t\tensureTopic(topic, commandOpts = {}) {\n\t\t\treturn publishCommand(commands, {\n\t\t\t\tkind: \"ensure-topic\",\n\t\t\t\ttopic,\n\t\t\t\t...(commandOpts.commandId === undefined ? {} : { commandId: commandOpts.commandId }),\n\t\t\t});\n\t\t},\n\t\tcloseTopic(topic, commandOpts = {}) {\n\t\t\treturn publishCommand(commands, {\n\t\t\t\tkind: \"close-topic\",\n\t\t\t\ttopic,\n\t\t\t\t...(commandOpts.commandId === undefined ? {} : { commandId: commandOpts.commandId }),\n\t\t\t});\n\t\t},\n\t\tpublish<T = unknown>(\n\t\t\ttopic: TTopic | string,\n\t\t\tpayload: T,\n\t\t\tpublishOpts: { key?: string; commandId?: string; idempotencyKey?: string } = {},\n\t\t) {\n\t\t\treturn publishCommand(commands, {\n\t\t\t\tkind: \"publish\",\n\t\t\t\ttopic,\n\t\t\t\tpayload,\n\t\t\t\t...(publishOpts.key === undefined ? {} : { key: publishOpts.key }),\n\t\t\t\t...(publishOpts.commandId === undefined ? {} : { commandId: publishOpts.commandId }),\n\t\t\t\t...(publishOpts.idempotencyKey === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { idempotencyKey: publishOpts.idempotencyKey }),\n\t\t\t});\n\t\t},\n\t\ttopic<T = unknown>(topic: TTopic | string, projectionOpts: { name?: string } = {}) {\n\t\t\tassertTopicKey(topic, \"messageBus.topic\");\n\t\t\tconst snapshotPullId = Symbol(`${name}/${topic}/topicSnapshot`);\n\t\t\tconst snapshot = graph.node<MessageBusTopicPage<T>>(\n\t\t\t\t[messages],\n\t\t\t\t(ctx) => {\n\t\t\t\t\tconst params = pullParams<MessageBusTopicParams>(ctx.pull);\n\t\t\t\t\tctx.down([[\"DATA\", topicPage<T>(state, topic, params)]]);\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: projectionOpts.name ?? `${name}/${topic}/topic`,\n\t\t\t\t\tfactory: \"messageBusTopicProjection\",\n\t\t\t\t\tmeta: { topic },\n\t\t\t\t\tpullId: snapshotPullId,\n\t\t\t\t\tpartial: true,\n\t\t\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t\t\terrorWhenDepsError: false,\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { snapshot, snapshotPullId, status, issues };\n\t\t},\n\t\tcatalog(projectionOpts: { name?: string } = {}) {\n\t\t\tconst snapshotPullId = Symbol(`${name}/catalogSnapshot`);\n\t\t\tconst snapshot = graph.node<MessageBusCatalogPage>(\n\t\t\t\t[runtime],\n\t\t\t\t(ctx) => {\n\t\t\t\t\tconst params = pullParams<MessageBusCatalogParams>(ctx.pull);\n\t\t\t\t\tctx.down([[\"DATA\", catalogPage(state, params)]]);\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: projectionOpts.name ?? `${name}/catalog`,\n\t\t\t\t\tfactory: \"messageBusCatalog\",\n\t\t\t\t\tpullId: snapshotPullId,\n\t\t\t\t\tpartial: true,\n\t\t\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t\t\terrorWhenDepsError: false,\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { snapshot, snapshotPullId, status, issues };\n\t\t},\n\t\tdeadLetter<T = unknown>(projectionOpts: { name?: string } = {}) {\n\t\t\tconst snapshotPullId = Symbol(`${name}/deadLetterSnapshot`);\n\t\t\tconst snapshot = graph.node<MessageBusDeadLetterPage<T>>(\n\t\t\t\t[runtime],\n\t\t\t\t(ctx) => {\n\t\t\t\t\tconst params = pullParams<MessageBusDeadLetterParams>(ctx.pull);\n\t\t\t\t\tctx.down([[\"DATA\", deadLetterPage<T>(state, params)]]);\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: projectionOpts.name ?? `${name}/deadLetter`,\n\t\t\t\t\tfactory: \"messageBusDeadLetter\",\n\t\t\t\t\tpullId: snapshotPullId,\n\t\t\t\t\tpartial: true,\n\t\t\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t\t\terrorWhenDepsError: false,\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { snapshot, snapshotPullId, status, issues };\n\t\t},\n\t\tsubscription<T = unknown>(subscriptionOpts: {\n\t\t\ttopic: TTopic | string;\n\t\t\tsubscriptionId: string;\n\t\t\tfrom?: \"earliest\" | \"latest\" | number;\n\t\t\tname?: string;\n\t\t}) {\n\t\t\tassertTopicKey(subscriptionOpts.topic, \"messageBus.subscription\");\n\t\t\tassertNonEmpty(subscriptionOpts.subscriptionId, \"messageBus.subscriptionId\");\n\t\t\tconst sub = ensureSubscription(state, {\n\t\t\t\ttopic: subscriptionOpts.topic,\n\t\t\t\tsubscriptionId: subscriptionOpts.subscriptionId,\n\t\t\t\tfrom: subscriptionOpts.from ?? \"earliest\",\n\t\t\t});\n\t\t\tconst availablePullId = Symbol(\n\t\t\t\t`${name}/${subscriptionOpts.topic}/${subscriptionOpts.subscriptionId}/available`,\n\t\t\t);\n\t\t\tconst projectionName =\n\t\t\t\tsubscriptionOpts.name ??\n\t\t\t\t`${name}/${subscriptionOpts.topic}/${subscriptionOpts.subscriptionId}`;\n\t\t\tconst available = graph.node<MessageBusAvailablePage<T>>(\n\t\t\t\t[messages, status],\n\t\t\t\t(ctx) => {\n\t\t\t\t\tconst params = pullParams<MessageBusAvailableParams>(ctx.pull);\n\t\t\t\t\tctx.down([[\"DATA\", availablePage<T>(state, sub, params)]]);\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: `${projectionName}/available`,\n\t\t\t\t\tfactory: \"messageBusSubscriptionAvailable\",\n\t\t\t\t\tmeta: { topic: subscriptionOpts.topic, subscriptionId: subscriptionOpts.subscriptionId },\n\t\t\t\t\tpullId: availablePullId,\n\t\t\t\t\tpartial: true,\n\t\t\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t\t\terrorWhenDepsError: false,\n\t\t\t\t},\n\t\t\t);\n\t\t\tconst cursor = graph.node<MessageBusCursor>(\n\t\t\t\t[status],\n\t\t\t\t(ctx) => {\n\t\t\t\t\tfor (const fact of depBatch(ctx, 0) ?? []) {\n\t\t\t\t\t\tconst typed = fact as MessageBusStatus;\n\t\t\t\t\t\tconst subscriptionMoved =\n\t\t\t\t\t\t\ttyped.topic === sub.topic &&\n\t\t\t\t\t\t\ttyped.subscriptionId === sub.subscriptionId &&\n\t\t\t\t\t\t\t(typed.kind === \"subscription-acked\" ||\n\t\t\t\t\t\t\t\ttyped.kind === \"subscription-sought\" ||\n\t\t\t\t\t\t\t\ttyped.kind === \"subscription-closed\");\n\t\t\t\t\t\tconst retentionMoved = typed.topic === sub.topic && typed.kind === \"retention-trimmed\";\n\t\t\t\t\t\tif (subscriptionMoved || retentionMoved) {\n\t\t\t\t\t\t\tctx.down([[\"DATA\", cursorSnapshot(state, sub)]]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: `${projectionName}/cursor`,\n\t\t\t\t\tfactory: \"messageBusSubscriptionCursor\",\n\t\t\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t\t\terrorWhenDepsError: false,\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn {\n\t\t\t\tavailable,\n\t\t\t\tavailablePullId,\n\t\t\t\tcursor,\n\t\t\t\tstatus,\n\t\t\t\tissues,\n\t\t\t\tack(seq, commandOpts = {}) {\n\t\t\t\t\treturn publishCommand(commands, {\n\t\t\t\t\t\tkind: \"ack\",\n\t\t\t\t\t\ttopic: sub.topic,\n\t\t\t\t\t\tsubscriptionId: sub.subscriptionId,\n\t\t\t\t\t\tseq,\n\t\t\t\t\t\t...(commandOpts.commandId === undefined ? {} : { commandId: commandOpts.commandId }),\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tseek(nextSeq, commandOpts = {}) {\n\t\t\t\t\treturn publishCommand(commands, {\n\t\t\t\t\t\tkind: \"seek\",\n\t\t\t\t\t\ttopic: sub.topic,\n\t\t\t\t\t\tsubscriptionId: sub.subscriptionId,\n\t\t\t\t\t\tnextSeq,\n\t\t\t\t\t\t...(commandOpts.commandId === undefined ? {} : { commandId: commandOpts.commandId }),\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tclose(commandOpts = {}) {\n\t\t\t\t\treturn publishCommand(commands, {\n\t\t\t\t\t\tkind: \"close-subscription\",\n\t\t\t\t\t\ttopic: sub.topic,\n\t\t\t\t\t\tsubscriptionId: sub.subscriptionId,\n\t\t\t\t\t\t...(commandOpts.commandId === undefined ? {} : { commandId: commandOpts.commandId }),\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t};\n\tregisterMessageBusState(bus, state);\n\treturn bus;\n}\n\nexport function fromTopic<T = unknown, TTopic extends string = string>(\n\tbus: MessageBus<TTopic>,\n\ttopic: TTopic | string,\n): Node<MessageBusTopicPage<T>> {\n\treturn bus.topic<T>(topic).snapshot;\n}\n\nexport function toTopic<T, TTopic extends string>(\n\tgraph: Graph,\n\tsource: Node<T>,\n\tbus: MessageBus<TTopic>,\n\ttopic: TTopic | string,\n\topts: ToTopicOptions = {},\n): ToTopicBundle<T> {\n\tconst state = getMessageBusState(bus);\n\tif (state === undefined) throw new Error(\"toTopic: unknown message bus implementation\");\n\tif (state.graph !== graph) throw new Error(\"toTopic: bus and source graph must match\");\n\tassertTopicKey(topic, \"toTopic\");\n\tconst commands = graph.node<MessageBusCommand<T>>(\n\t\t[source],\n\t\t(ctx) => {\n\t\t\tfor (const value of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst key = opts.keyOf?.(value);\n\t\t\t\tconst commandId = opts.commandIdOf?.(value);\n\t\t\t\tctx.down([\n\t\t\t\t\t[\n\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tkind: \"publish\",\n\t\t\t\t\t\t\ttopic,\n\t\t\t\t\t\t\tpayload: value as T,\n\t\t\t\t\t\t\t...(key === undefined ? {} : { key }),\n\t\t\t\t\t\t\t...(commandId === undefined ? {} : { commandId }),\n\t\t\t\t\t\t} satisfies MessageBusCommand<T>,\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: opts.name ?? `${state.name}/${topic}/toTopic`,\n\t\t\tfactory: \"toTopic\",\n\t\t\tmeta: { topic },\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst releaseSource = attachMessageBusCommandSource(\n\t\tgraph,\n\t\tbus,\n\t\tcommands as Node<MessageBusCommand>,\n\t);\n\tlet released = false;\n\treturn {\n\t\tcommands,\n\t\trelease() {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\treleaseSource();\n\t\t},\n\t};\n}\n\nfunction reduceMessageBusCommand(\n\tstate: MessageBusState,\n\tcommand: MessageBusCommand,\n): RuntimeEvent[] {\n\tconst malformed = validateCommand(command);\n\tif (malformed !== undefined) return rejectCommand(state, command, malformed);\n\tif (command.commandId !== undefined) {\n\t\tif (state.seenCommandIds.has(command.commandId)) {\n\t\t\treturn duplicateCommandEvents(state, command, \"duplicate commandId\");\n\t\t}\n\t\tstate.seenCommandIds.add(command.commandId);\n\t}\n\tif (\n\t\tcommand.kind === \"publish\" &&\n\t\tcommand.idempotencyKey !== undefined &&\n\t\tstate.seenIdempotencyKeys.has(idempotencyKey(command.topic, command.idempotencyKey))\n\t) {\n\t\treturn duplicateCommandEvents(state, command, \"duplicate idempotencyKey\");\n\t}\n\tswitch (command.kind) {\n\t\tcase \"ensure-topic\":\n\t\t\treturn ensureTopic(state, command.topic, command.commandId);\n\t\tcase \"close-topic\": {\n\t\t\tconst topic = state.topics.get(command.topic);\n\t\t\tif (topic === undefined) {\n\t\t\t\treturn issueEvents(state, command, \"unknown-topic\", `unknown topic '${command.topic}'`);\n\t\t\t}\n\t\t\ttopic.closed = true;\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tkind: \"status\",\n\t\t\t\t\tstatus: statusFact(state, \"topic-closed\", {\n\t\t\t\t\t\ttopic: command.topic,\n\t\t\t\t\t\tcommandId: command.commandId,\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t];\n\t\t}\n\t\tcase \"topic-policy\":\n\t\t\tstate.topicPolicy = command.topicPolicy;\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tkind: \"status\",\n\t\t\t\t\tstatus: statusFact(state, \"projection-ready\", {\n\t\t\t\t\t\tcommandId: command.commandId,\n\t\t\t\t\t\tdetails: { topicPolicy: command.topicPolicy },\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t];\n\t\tcase \"publish\":\n\t\t\treturn publishMessage(state, command);\n\t\tcase \"ack\":\n\t\t\treturn ackSubscription(state, command);\n\t\tcase \"seek\":\n\t\t\treturn seekSubscription(state, command);\n\t\tcase \"close-subscription\":\n\t\t\treturn closeSubscription(state, command);\n\t}\n}\n\nfunction publishMessage(\n\tstate: MessageBusState,\n\tcommand: Extract<MessageBusCommand, { kind: \"publish\" }>,\n): RuntimeEvent[] {\n\tlet topic = state.topics.get(command.topic);\n\tconst events: RuntimeEvent[] = [];\n\tif (topic === undefined) {\n\t\tif (state.topicPolicy !== \"create-as-fact\") {\n\t\t\treturn issueEvents(state, command, \"unknown-topic\", `unknown topic '${command.topic}'`);\n\t\t}\n\t\tevents.push(...ensureTopic(state, command.topic, command.commandId));\n\t\ttopic = state.topics.get(command.topic);\n\t}\n\tif (topic === undefined)\n\t\treturn issueEvents(state, command, \"unknown-topic\", `unknown topic '${command.topic}'`);\n\tif (topic.closed)\n\t\treturn issueEvents(state, command, \"closed-topic\", `closed topic '${command.topic}'`);\n\tconst message: MessageBusMessage = {\n\t\ttopic: command.topic,\n\t\tseq: topic.nextSeq++,\n\t\tpayload: command.payload,\n\t\ttimestampMs: state.now(),\n\t\t...(command.key === undefined ? {} : { key: command.key }),\n\t\t...(command.idempotencyKey === undefined ? {} : { idempotencyKey: command.idempotencyKey }),\n\t\t...(command.commandId === undefined ? {} : { commandId: command.commandId }),\n\t};\n\tif (command.idempotencyKey !== undefined) {\n\t\tstate.seenIdempotencyKeys.add(idempotencyKey(command.topic, command.idempotencyKey));\n\t}\n\ttopic.messages.push(message);\n\tevents.push({ kind: \"message\", message });\n\tevents.push({\n\t\tkind: \"status\",\n\t\tstatus: statusFact(state, \"message-published\", {\n\t\t\ttopic: command.topic,\n\t\t\tseq: message.seq,\n\t\t\tcommandId: command.commandId,\n\t\t}),\n\t});\n\tevents.push(...trimRetention(state, command.topic, topic));\n\treturn events;\n}\n\nfunction ensureTopic(state: MessageBusState, topic: string, commandId?: string): RuntimeEvent[] {\n\tassertTopicKey(topic, \"messageBus\");\n\tif (!state.topics.has(topic)) state.topics.set(topic, makeTopicState());\n\treturn [\n\t\t{\n\t\t\tkind: \"status\",\n\t\t\tstatus: statusFact(state, \"topic-created\", { topic, commandId }),\n\t\t},\n\t];\n}\n\nfunction trimRetention(\n\tstate: MessageBusState,\n\ttopicName: string,\n\ttopic: TopicState,\n): RuntimeEvent[] {\n\tconst max = state.retention.maxMessages;\n\tif (max === undefined || topic.messages.length <= max) return [];\n\tif (!Number.isInteger(max) || max < 1) {\n\t\treturn issueEvents(\n\t\t\tstate,\n\t\t\t{ kind: \"publish\", topic: topicName, payload: undefined },\n\t\t\t\"policy-rejected\",\n\t\t\t\"retention.maxMessages must be a positive integer\",\n\t\t);\n\t}\n\tconst trimCount = topic.messages.length - max;\n\ttopic.messages.splice(0, trimCount);\n\ttopic.headSeq = topic.messages[0]?.seq ?? topic.nextSeq;\n\tconst events: RuntimeEvent[] = [\n\t\t{\n\t\t\tkind: \"status\",\n\t\t\tstatus: statusFact(state, \"retention-trimmed\", {\n\t\t\t\ttopic: topicName,\n\t\t\t\theadSeq: topic.headSeq,\n\t\t\t\tdetails: { trimCount },\n\t\t\t}),\n\t\t},\n\t];\n\tfor (const sub of state.subscriptions.values()) {\n\t\tif (sub.closed || sub.topic !== topicName || sub.nextSeq >= topic.headSeq) continue;\n\t\tsub.retentionGap = true;\n\t\tevents.push(\n\t\t\t...issueEvents(\n\t\t\t\tstate,\n\t\t\t\t{\n\t\t\t\t\tkind: \"seek\",\n\t\t\t\t\ttopic: topicName,\n\t\t\t\t\tsubscriptionId: sub.subscriptionId,\n\t\t\t\t\tnextSeq: sub.nextSeq,\n\t\t\t\t},\n\t\t\t\t\"retention-gap\",\n\t\t\t\t`subscription '${sub.subscriptionId}' is before retained headSeq`,\n\t\t\t),\n\t\t);\n\t}\n\treturn events;\n}\n\nfunction ackSubscription(\n\tstate: MessageBusState,\n\tcommand: Extract<MessageBusCommand, { kind: \"ack\" }>,\n): RuntimeEvent[] {\n\tconst topic = state.topics.get(command.topic);\n\tif (topic === undefined)\n\t\treturn issueEvents(state, command, \"unknown-topic\", `unknown topic '${command.topic}'`);\n\tconst sub = getSubscription(state, command.topic, command.subscriptionId);\n\tif (sub === undefined)\n\t\treturn issueEvents(\n\t\t\tstate,\n\t\t\tcommand,\n\t\t\t\"unknown-subscription\",\n\t\t\t`unknown subscription '${command.subscriptionId}'`,\n\t\t);\n\tif (sub.closed)\n\t\treturn issueEvents(state, command, \"subscription-closed\", \"subscription is closed\");\n\tif (sub.retentionGap)\n\t\treturn issueEvents(state, command, \"retention-gap\", \"subscription must seek before ack\");\n\tif (command.seq < sub.nextSeq)\n\t\treturn issueEvents(state, command, \"source-cursor-stale\", \"ack is behind subscription cursor\");\n\tif (command.seq >= topic.nextSeq)\n\t\treturn issueEvents(state, command, \"cursor-out-of-range\", \"ack is beyond topic tail\");\n\tsub.nextSeq = Math.max(sub.nextSeq, command.seq + 1);\n\treturn [\n\t\t{\n\t\t\tkind: \"status\",\n\t\t\tstatus: statusFact(state, \"subscription-acked\", {\n\t\t\t\ttopic: command.topic,\n\t\t\t\tsubscriptionId: command.subscriptionId,\n\t\t\t\tnextSeq: sub.nextSeq,\n\t\t\t\tcommandId: command.commandId,\n\t\t\t}),\n\t\t},\n\t];\n}\n\nfunction seekSubscription(\n\tstate: MessageBusState,\n\tcommand: Extract<MessageBusCommand, { kind: \"seek\" }>,\n): RuntimeEvent[] {\n\tconst topic = state.topics.get(command.topic);\n\tif (topic === undefined)\n\t\treturn issueEvents(state, command, \"unknown-topic\", `unknown topic '${command.topic}'`);\n\tconst sub = getSubscription(state, command.topic, command.subscriptionId);\n\tif (sub === undefined)\n\t\treturn issueEvents(\n\t\t\tstate,\n\t\t\tcommand,\n\t\t\t\"unknown-subscription\",\n\t\t\t`unknown subscription '${command.subscriptionId}'`,\n\t\t);\n\tif (sub.closed)\n\t\treturn issueEvents(state, command, \"subscription-closed\", \"subscription is closed\");\n\tif (command.nextSeq < topic.headSeq)\n\t\treturn issueEvents(state, command, \"retention-gap\", \"seek is before retained headSeq\");\n\tif (command.nextSeq > topic.nextSeq)\n\t\treturn issueEvents(state, command, \"cursor-out-of-range\", \"seek is beyond topic tail\");\n\tsub.nextSeq = command.nextSeq;\n\tsub.retentionGap = false;\n\treturn [\n\t\t{\n\t\t\tkind: \"status\",\n\t\t\tstatus: statusFact(state, \"subscription-sought\", {\n\t\t\t\ttopic: command.topic,\n\t\t\t\tsubscriptionId: command.subscriptionId,\n\t\t\t\tnextSeq: sub.nextSeq,\n\t\t\t\tcommandId: command.commandId,\n\t\t\t}),\n\t\t},\n\t];\n}\n\nfunction closeSubscription(\n\tstate: MessageBusState,\n\tcommand: Extract<MessageBusCommand, { kind: \"close-subscription\" }>,\n): RuntimeEvent[] {\n\tif (!state.topics.has(command.topic))\n\t\treturn issueEvents(state, command, \"unknown-topic\", `unknown topic '${command.topic}'`);\n\tconst sub = getSubscription(state, command.topic, command.subscriptionId);\n\tif (sub === undefined)\n\t\treturn issueEvents(\n\t\t\tstate,\n\t\t\tcommand,\n\t\t\t\"unknown-subscription\",\n\t\t\t`unknown subscription '${command.subscriptionId}'`,\n\t\t);\n\tsub.closed = true;\n\treturn [\n\t\t{\n\t\t\tkind: \"status\",\n\t\t\tstatus: statusFact(state, \"subscription-closed\", {\n\t\t\t\ttopic: command.topic,\n\t\t\t\tsubscriptionId: command.subscriptionId,\n\t\t\t\tnextSeq: sub.nextSeq,\n\t\t\t\tcommandId: command.commandId,\n\t\t\t}),\n\t\t},\n\t];\n}\n\nfunction issueEvents(\n\tstate: MessageBusState,\n\tcommand: unknown,\n\tcode: string,\n\tmessage: string,\n): RuntimeEvent[] {\n\tconst topic = commandTopic(command);\n\tconst commandId = commandIdOf(command);\n\tconst issue: DataIssue = {\n\t\tkind: \"issue\",\n\t\tcode,\n\t\tmessage,\n\t\tseverity: \"error\",\n\t\tsource: \"messageBus\",\n\t\tdetails: command,\n\t\tmetadata: topic === undefined ? undefined : { topic },\n\t};\n\tconst entry: MessageBusDeadLetterEntry = {\n\t\tentrySeq: ++state.deadLetterSeq,\n\t\t...(topic === undefined ? {} : { topic }),\n\t\t...(isObjectRecord(command) ? { command: command as MessageBusCommand } : {}),\n\t\tissue,\n\t\ttimestampMs: state.now(),\n\t};\n\tstate.deadLetters.push(entry);\n\treturn [\n\t\t{ kind: \"issue\", issue },\n\t\t{ kind: \"dead-letter\", entry },\n\t\t{\n\t\t\tkind: \"status\",\n\t\t\tstatus: statusFact(state, \"command-rejected\", {\n\t\t\t\ttopic,\n\t\t\t\tcommandId,\n\t\t\t\tissueCode: code,\n\t\t\t}),\n\t\t},\n\t];\n}\n\nfunction rejectCommand(state: MessageBusState, command: unknown, reason: string): RuntimeEvent[] {\n\treturn issueEvents(state, command, \"malformed-command\", reason);\n}\n\nfunction duplicateCommandEvents(\n\tstate: MessageBusState,\n\tcommand: MessageBusCommand,\n\tmessage: string,\n): RuntimeEvent[] {\n\tconst status = statusFact(state, \"duplicate-command\", {\n\t\ttopic: \"topic\" in command ? command.topic : undefined,\n\t\tcommandId: command.commandId,\n\t});\n\tif (state.dedupe.commandId === \"issue\") {\n\t\treturn [\n\t\t\t{ kind: \"status\", status },\n\t\t\t...issueEvents(state, command, \"duplicate-command\", message),\n\t\t];\n\t}\n\treturn [{ kind: \"status\", status }];\n}\n\nfunction statusFact(\n\tstate: MessageBusState,\n\tkind: MessageBusStatus[\"kind\"],\n\tfields: Partial<MessageBusStatus>,\n): MessageBusStatus {\n\treturn {\n\t\tkind,\n\t\ttimestampMs: state.now(),\n\t\t...(fields.topic === undefined ? {} : { topic: fields.topic }),\n\t\t...(fields.seq === undefined ? {} : { seq: fields.seq }),\n\t\t...(fields.headSeq === undefined ? {} : { headSeq: fields.headSeq }),\n\t\t...(fields.subscriptionId === undefined ? {} : { subscriptionId: fields.subscriptionId }),\n\t\t...(fields.nextSeq === undefined ? {} : { nextSeq: fields.nextSeq }),\n\t\t...(fields.commandId === undefined ? {} : { commandId: fields.commandId }),\n\t\t...(fields.issueCode === undefined ? {} : { issueCode: fields.issueCode }),\n\t\t...(fields.details === undefined ? {} : { details: fields.details }),\n\t};\n}\n\nfunction validateCommand(command: unknown): string | undefined {\n\tif (!isObjectRecord(command)) return \"command must be an object\";\n\tif (typeof command.kind !== \"string\") return \"command kind is required\";\n\tif (!isMessageBusCommandKind(command.kind)) return `unknown command kind '${command.kind}'`;\n\tif (\"topic\" in command) {\n\t\tif (typeof command.topic !== \"string\") return \"messageBus: topic must be a non-empty string\";\n\t\tconst topicError = validateTopicKey(command.topic, \"messageBus\");\n\t\tif (topicError !== undefined) return topicError;\n\t}\n\tif (\"subscriptionId\" in command && typeof command.subscriptionId !== \"string\") {\n\t\treturn \"subscriptionId must be a string\";\n\t}\n\tif (command.kind === \"publish\" && command.payload === undefined)\n\t\treturn \"publish payload is required\";\n\tif (command.kind === \"ack\" && !isPositiveSeq(command.seq))\n\t\treturn \"ack seq must be a positive integer\";\n\tif (command.kind === \"seek\" && !isPositiveSeq(command.nextSeq)) {\n\t\treturn \"seek nextSeq must be a positive integer\";\n\t}\n\tif (\n\t\tcommand.kind === \"topic-policy\" &&\n\t\tcommand.topicPolicy !== \"strict\" &&\n\t\tcommand.topicPolicy !== \"create-as-fact\"\n\t) {\n\t\treturn \"topicPolicy is not recognized\";\n\t}\n\treturn undefined;\n}\n\nfunction isMessageBusCommandKind(kind: string): kind is MessageBusCommand[\"kind\"] {\n\treturn (\n\t\tkind === \"ensure-topic\" ||\n\t\tkind === \"close-topic\" ||\n\t\tkind === \"publish\" ||\n\t\tkind === \"topic-policy\" ||\n\t\tkind === \"ack\" ||\n\t\tkind === \"seek\" ||\n\t\tkind === \"close-subscription\"\n\t);\n}\n\nfunction catalogPage(\n\tstate: MessageBusState,\n\tparams: MessageBusCatalogParams,\n): MessageBusCatalogPage {\n\tconst limit = positiveLimit(params.limit);\n\tconst topics = [...state.topics.entries()]\n\t\t.filter(\n\t\t\t([topic, value]) =>\n\t\t\t\t(params.includeClosed ? true : !value.closed) &&\n\t\t\t\t(params.afterTopic === undefined || topic > params.afterTopic),\n\t\t)\n\t\t.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n\tconst page = topics.slice(0, limit);\n\tconst hasMore = topics.length > limit;\n\treturn {\n\t\ttopics: page.map(([topic, value]) => ({\n\t\t\ttopic,\n\t\t\tclosed: value.closed,\n\t\t\theadSeq: value.headSeq,\n\t\t\tnextSeq: value.nextSeq,\n\t\t\tmessageCount: value.messages.length,\n\t\t})),\n\t\t...(hasMore && page.length > 0 ? { nextAfterTopic: page[page.length - 1]?.[0] } : {}),\n\t\thasMore,\n\t};\n}\n\nfunction topicPage<T>(\n\tstate: MessageBusState,\n\ttopicName: string,\n\tparams: MessageBusTopicParams,\n): MessageBusTopicPage<T> {\n\tconst topic = state.topics.get(topicName);\n\tconst start = params.afterSeq === undefined ? (topic?.headSeq ?? 1) : params.afterSeq + 1;\n\tconst all = (topic?.messages ?? []).filter((message) => message.seq >= start);\n\tconst limit = positiveLimit(params.limit);\n\tconst messages = all.slice(0, limit) as MessageBusMessage<T>[];\n\tconst hasMore = all.length > limit;\n\treturn {\n\t\ttopic: topicName,\n\t\tmessages,\n\t\tfromSeq: start,\n\t\t...(messages.length > 0 ? { throughSeq: messages[messages.length - 1]?.seq } : {}),\n\t\t...(hasMore && messages.length > 0 ? { nextAfterSeq: messages[messages.length - 1]?.seq } : {}),\n\t\thasMore,\n\t};\n}\n\nfunction availablePage<T>(\n\tstate: MessageBusState,\n\tsub: SubscriptionState,\n\tparams: MessageBusAvailableParams,\n): MessageBusAvailablePage<T> {\n\tconst cursor = cursorSnapshot(state, sub);\n\tconst start = params.afterSeq === undefined ? sub.nextSeq : params.afterSeq + 1;\n\tconst topic = state.topics.get(sub.topic);\n\tconst all = sub.retentionGap\n\t\t? []\n\t\t: (topic?.messages ?? []).filter((message) => message.seq >= start);\n\tconst limit = positiveLimit(params.limit);\n\tconst messages = all.slice(0, limit) as MessageBusMessage<T>[];\n\tconst hasMore = all.length > limit;\n\treturn {\n\t\ttopic: sub.topic,\n\t\tsubscriptionId: sub.subscriptionId,\n\t\tcursor,\n\t\tmessages,\n\t\tfromSeq: start,\n\t\t...(messages.length > 0 ? { throughSeq: messages[messages.length - 1]?.seq } : {}),\n\t\t...(hasMore && messages.length > 0 ? { nextAfterSeq: messages[messages.length - 1]?.seq } : {}),\n\t\thasMore,\n\t};\n}\n\nfunction deadLetterPage<T>(\n\tstate: MessageBusState,\n\tparams: MessageBusDeadLetterParams,\n): MessageBusDeadLetterPage<T> {\n\tconst limit = positiveLimit(params.limit);\n\tconst entries = state.deadLetters.filter((entry) => {\n\t\tif (params.afterEntrySeq !== undefined && entry.entrySeq <= params.afterEntrySeq) return false;\n\t\tif (params.topic !== undefined && entry.topic !== params.topic) return false;\n\t\tif (params.code !== undefined && entry.issue.code !== params.code) return false;\n\t\treturn true;\n\t});\n\tconst page = entries.slice(0, limit) as MessageBusDeadLetterEntry<T>[];\n\tconst hasMore = entries.length > limit;\n\treturn {\n\t\tentries: page,\n\t\t...(hasMore && page.length > 0 ? { nextAfterEntrySeq: page[page.length - 1]?.entrySeq } : {}),\n\t\thasMore,\n\t};\n}\n\nfunction cursorSnapshot(state: MessageBusState, sub: SubscriptionState): MessageBusCursor {\n\tconst topic = state.topics.get(sub.topic);\n\treturn {\n\t\ttopic: sub.topic,\n\t\tsubscriptionId: sub.subscriptionId,\n\t\tnextSeq: sub.nextSeq,\n\t\tclosed: sub.closed,\n\t\tretentionGap: sub.retentionGap,\n\t\theadSeq: topic?.headSeq ?? 1,\n\t};\n}\n\nfunction ensureSubscription(\n\tstate: MessageBusState,\n\topts: { topic: string; subscriptionId: string; from: \"earliest\" | \"latest\" | number },\n): SubscriptionState {\n\tconst key = `${opts.topic}\\u0000${opts.subscriptionId}`;\n\tconst existing = state.subscriptions.get(key);\n\tif (existing !== undefined) return existing;\n\tconst topic = state.topics.get(opts.topic);\n\tconst nextSeq =\n\t\topts.from === \"earliest\"\n\t\t\t? (topic?.headSeq ?? 1)\n\t\t\t: opts.from === \"latest\"\n\t\t\t\t? (topic?.nextSeq ?? 1)\n\t\t\t\t: opts.from;\n\tconst sub: SubscriptionState = {\n\t\ttopic: opts.topic,\n\t\tsubscriptionId: opts.subscriptionId,\n\t\tnextSeq,\n\t\tclosed: false,\n\t\tretentionGap: topic !== undefined && nextSeq < topic.headSeq,\n\t};\n\tstate.subscriptions.set(key, sub);\n\treturn sub;\n}\n\nfunction getSubscription(\n\tstate: MessageBusState,\n\ttopic: string,\n\tsubscriptionId: string,\n): SubscriptionState | undefined {\n\treturn state.subscriptions.get(`${topic}\\u0000${subscriptionId}`);\n}\n\nfunction pullParams<T>(pull: PullDemand | undefined): T {\n\treturn (isObjectRecord(pull?.params) ? pull.params : {}) as T;\n}\n\nfunction publishCommand<T extends MessageBusCommand>(\n\tcommandNode: Node<MessageBusCommand>,\n\tcommand: T,\n): T {\n\tcommandNode.down([[\"DATA\", command]]);\n\treturn command;\n}\n\nfunction makeTopicState(): TopicState {\n\treturn { closed: false, headSeq: 1, nextSeq: 1, messages: [] };\n}\n\nfunction uniqueTopics(topics: readonly string[]): readonly string[] {\n\tconst unique = [...new Set(topics)];\n\tif (unique.length !== topics.length) throw new Error(\"messageBus: duplicate topic\");\n\tfor (const topic of unique) assertTopicKey(topic, \"messageBus\");\n\treturn Object.freeze(unique.sort());\n}\n\nfunction assertTopicKey(topic: string, owner: string): void {\n\tconst error = validateTopicKey(topic, owner);\n\tif (error !== undefined) throw new Error(error);\n}\n\nfunction validateTopicKey(topic: string, owner: string): string | undefined {\n\tif (typeof topic !== \"string\" || topic.length === 0)\n\t\treturn `${owner}: topic must be a non-empty string`;\n\treturn undefined;\n}\n\nfunction assertNonEmpty(value: string, owner: string): void {\n\tif (typeof value !== \"string\" || value.length === 0)\n\t\tthrow new Error(`${owner}: must be a non-empty string`);\n}\n\nfunction positiveLimit(limit: number | undefined): number {\n\tif (limit === undefined) return 100;\n\tif (!Number.isInteger(limit) || limit < 1)\n\t\tthrow new Error(\"messageBus: limit must be a positive integer\");\n\treturn limit;\n}\n\nfunction isPositiveSeq(value: unknown): value is number {\n\treturn Number.isInteger(value) && (value as number) >= 1;\n}\n\nfunction isObjectRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction commandTopic(command: unknown): string | undefined {\n\treturn isObjectRecord(command) && typeof command.topic === \"string\" ? command.topic : undefined;\n}\n\nfunction commandIdOf(command: unknown): string | undefined {\n\treturn isObjectRecord(command) && typeof command.commandId === \"string\"\n\t\t? command.commandId\n\t\t: undefined;\n}\n\nfunction idempotencyKey(topic: string, key: string): string {\n\treturn `${topic}\\u0000${key}`;\n}\n","/**\n * Wave-protocol message types and the tier const table.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-msg-format, R-msg-closed-set, R-tier (D34), R-data-payload, R-sentinel.\n */\n\n/** Opaque pause-lock / pull identifier (R-pause-lockset, R-pull). */\nexport type LockId = string | symbol;\n\n/** Explicit pull demand payload (D269/D272). Params are holder-visible context, never DATA-up. */\nexport interface PullDemand {\n\treadonly pullId: LockId;\n\treadonly params?: unknown;\n}\n\n/**\n * The CLOSED set of 11 message types (R-msg-closed-set / D9 + D269 + START handshake).\n * No open set, no user-defined custom types. Adding a type is a spec change.\n */\nexport type Message =\n\t| readonly [\"START\"]\n\t| readonly [\"DIRTY\"]\n\t| readonly [\"DATA\", unknown]\n\t| readonly [\"RESOLVED\"]\n\t| readonly [\"INVALIDATE\"]\n\t| readonly [\"COMPLETE\"]\n\t| readonly [\"ERROR\", unknown]\n\t| readonly [\"TEARDOWN\"]\n\t| readonly [\"PAUSE\", LockId]\n\t| readonly [\"RESUME\", LockId]\n\t| readonly [\"PULL\", PullDemand];\n\n/** One array of messages delivered in one call = one Wave (R-wave-boundary). */\nexport type Wave = readonly Message[];\n\n/** The message-type tag (the first tuple element). */\nexport type MessageType = Message[0];\n\n/**\n * SENTINEL = absence-of-DATA (R-sentinel / D16). TS representation is `undefined`.\n * Never a valid DATA payload; `null` IS a valid DATA value (domain-level absence).\n */\nexport const SENTINEL = undefined;\n\n/** R-data-payload: ERROR payloads must not collide with terminal metadata shorthand. */\nexport function isInvalidErrorPayload(v: unknown): boolean {\n\treturn v === SENTINEL || typeof v === \"boolean\";\n}\n\n/** R-data-payload / D78: host-language failures that collide with ctx.terminal shorthand become diagnostics. */\nexport function errorPayload(reason: unknown, fallback = \"error without a valid payload\"): unknown {\n\treturn isInvalidErrorPayload(reason) ? new Error(fallback) : reason;\n}\n\nexport const TIER_START = 0;\nexport const TIER_CONTROL = 1;\nexport const TIER_NOTIFICATION = 2;\nexport const TIER_VALUE = 3;\nexport const TIER_SETTLE = 4;\nexport const TIER_TERMINAL = 5;\nexport const TIER_TEARDOWN = 6;\n\n/**\n * Tier const table (R-tier / D34). Tiers below value dispatch immediately; value\n * and above are batch-deferred. This is a compile-time const table (D18), not runtime config.\n */\nconst TIER: Record<MessageType, number> = {\n\tSTART: TIER_START,\n\tPAUSE: TIER_CONTROL,\n\tRESUME: TIER_CONTROL,\n\tPULL: TIER_CONTROL,\n\tDIRTY: TIER_NOTIFICATION,\n\tDATA: TIER_VALUE,\n\tRESOLVED: TIER_VALUE,\n\tINVALIDATE: TIER_SETTLE,\n\tCOMPLETE: TIER_TERMINAL,\n\tERROR: TIER_TERMINAL,\n\tTEARDOWN: TIER_TEARDOWN,\n};\n\nexport function messageTier(t: MessageType): number {\n\treturn TIER[t];\n}\n\n/** Value and above are deferred inside a batch (DATA/RESOLVED/INVALIDATE/terminal/teardown). */\nexport function isDeferredTier(t: MessageType): boolean {\n\treturn TIER[t] >= TIER_VALUE;\n}\n\n/** Value-tier messages (DATA/RESOLVED) occupy the tier-3 slot. */\nexport function isValueTier(t: MessageType): boolean {\n\treturn TIER[t] === TIER_VALUE;\n}\n\n/** The pause buffer holds the settle slice only: value-tier DATA/RESOLVED plus INVALIDATE. */\nexport function isPauseBufferedTier(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier === TIER_VALUE || tier === TIER_SETTLE;\n}\n\n/**\n * A TERMINAL message = tier 5 (COMPLETE | ERROR), R-tier / D34. Detected via the CENTRAL tier\n * table, NOT a per-variant `=== \"COMPLETE\" || === \"ERROR\"` check — so terminal routing stays\n * driven by the one const table (feedback_use_tier_for_signal_routing); discriminate COMPLETE vs\n * ERROR within the tier by the message type only where the handling actually differs.\n */\nexport function isTerminal(t: MessageType): boolean {\n\treturn TIER[t] === TIER_TERMINAL;\n}\n\n/**\n * ctx.up carries control/demand tiers only (R-ctx-up / D269): DIRTY, PAUSE, RESUME, PULL,\n * INVALIDATE, TEARDOWN. DATA/RESOLVED (tier 3) and COMPLETE/ERROR (tier 5) are\n * down-only.\n */\nexport function isUpAllowed(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier !== TIER_VALUE && tier !== TIER_TERMINAL;\n}\n","/**\n * The fn-invocation context and per-dep input shapes.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-fn-contract (D8/D27), R-ctx-state (D23/D29), R-cleanup-hooks (D28), R-ctx-up.\n */\n\nimport type { Dispatcher } from \"../dispatcher/index.js\";\nimport type { EnvironmentDrivers } from \"../graph/environment.js\";\nimport type { Node } from \"../node/node.js\";\nimport { type Message, type PullDemand, SENTINEL, type Wave } from \"../protocol/messages.js\";\n\n/** A downstream sink callback (the only way to connect to a node's output). */\nexport type Sink = (msg: Message, delivery?: DeliveryMeta) => void;\n\n/** Internal delivery metadata used to preserve the upstream `ctx.down(msgs)` wave boundary. */\nexport interface DeliveryMeta {\n\treadonly wave: object;\n\treadonly last: boolean;\n}\n\n/**\n * Internal current-value reader. It is deliberately a symbol-backed implementation detail:\n * raw ctx exposes `waveData` + `terminal`; helpers below derive from that plus this dep cache.\n */\nexport const CTX_DEP_CACHE: unique symbol = Symbol(\"graphrefly.ctx.depCache\");\n\nexport interface CtxDepCache {\n\treadonly latest: readonly unknown[];\n}\n\n/** Internal node-construction binding for graph-local helper-created deps. */\nexport const CTX_NODE_BINDING: unique symbol = Symbol(\"graphrefly.ctx.nodeBinding\");\n\nexport interface CtxNodeBinding {\n\treadonly dispatcher: Dispatcher;\n\tcreate<T>(factory: () => Node<T>): Node<T>;\n}\n\n/** Per-dep wave projections: dep -> waves -> values/SENTINEL markers. */\nexport type WaveData = readonly (readonly (readonly unknown[])[])[];\n\n/** Terminal metadata parallel to `waveData`: false = none, true = COMPLETE, otherwise ERROR payload. */\nexport type TerminalData = readonly unknown[];\n\nexport function isTerminalNone(t: unknown): boolean {\n\treturn t === false || t === undefined;\n}\n\nexport function isTerminalComplete(t: unknown): t is true {\n\treturn t === true;\n}\n\nexport function isTerminalError(t: unknown): boolean {\n\treturn !isTerminalNone(t) && !isTerminalComplete(t);\n}\n\nexport function terminalErrorValue(t: unknown): unknown {\n\treturn isTerminalError(t) ? t : undefined;\n}\n\n/**\n * Per-node private cross-wave state (R-ctx-state / D23,D29). Default fresh-lifecycle\n * wipe; `persist(true)` keeps it across lifecycle transitions.\n */\nexport interface CtxState {\n\tget<S = unknown>(): S | undefined;\n\tset<S = unknown>(v: S): void;\n\tpersist(on?: boolean): void;\n}\n\n/**\n * Deferred SELF-rewire (R-rewire-deferred / D47). A node fn may, DURING its run, request a\n * mutation of its OWN dep set; the request is QUEUED and applied at the committed wave boundary\n * (after the current wave settles / batch commit / final-lock RESUME) as a fresh wave, reusing\n * R-rewire surgical/Option-C semantics (D42). This is the ONLY legal self-triggered rewire — an\n * IMMEDIATE in-fn `node.subscribeDep/unsubscribeDep/replaceDeps` is the D37 mid-fn feedback-cycle ERROR. An\n * added cached dep pushes `[DIRTY,DATA]` on the boundary wave (R-push-subscribe); a removed dep\n * is drained and, if it loses its last subscriber, `_deactivate`s + fires `onDeactivation`\n * (input-side teardown — the basis for higher-order operator cancellation / abortInFlight).\n */\nexport interface RewireNext {\n\t/** Defer subscribing to a dep (paired with the re-supplied fn — positional fn-deps lock, SD-1). */\n\tsubscribeDep(dep: Node<unknown>, fn: NodeFn): void;\n\t/** Defer unsubscribing from a dep (its source is torn down if it loses its last subscriber). */\n\tunsubscribeDep(dep: Node<unknown>, fn: NodeFn): void;\n\t/** Defer replacing the whole dep set (surgical: kept deps untouched, removed drained, added fresh-subscribe). */\n\treplaceDeps(deps: Node<unknown>[], fn: NodeFn): void;\n}\n\n/**\n * The single argument to a node fn: `(ctx) => void` (R-fn-contract / D8). All emission\n * is explicit via `ctx.down`; there is no return-value framing.\n */\nexport interface Ctx {\n\t/**\n\t * Emit upstream toward deps — control tiers only (R-ctx-up). IMMEDIATE. `towardDep` (a dep index)\n\t * routes the wave up ONE declared edge (R-up-routing directed-up); omitted = broadcast up all deps.\n\t * A pull DEMAND is `up([[PULL, { pullId, params }]])` — but for a SELF-demand (demanding a dep\n\t * this fn also reads) use {@link Ctx.upNext} instead, since an immediate demand whose delivery loops back\n\t * re-enters this fn mid-wave (D37 / R-reentrancy).\n\t */\n\tup(msgs: Wave, towardDep?: number): void;\n\t/** Emit downstream toward sinks. */\n\tdown(msgs: Wave): void;\n\t/**\n\t * The single raw dep-value input surface (R-ctx-wave-data / D77): dep -> upstream waves ->\n\t * per-wave DATA payloads and INVALIDATE/SENTINEL markers. `waveData[i] = []` means dep i\n\t * delivered no wave to this invocation; `waveData[i] = [[]]` means RESOLVED-only.\n\t */\n\twaveData: WaveData;\n\t/** Terminal metadata for the same invocation; terminal values never enter `waveData`. */\n\tterminal: TerminalData;\n\tstate: CtxState;\n\t/** Release external resources on deactivation (R-cleanup-hooks). */\n\tonDeactivation(fn: () => void): void;\n\t/** Flush on INVALIDATE (R-cleanup-hooks). */\n\tonInvalidate(fn: () => void): void;\n\t/** Graph-owned environment drivers for source/adapter boundaries (D130/D131). */\n\tenvironment(): EnvironmentDrivers;\n\t/** Holder-visible context for a PULL-caused invocation (D272); absent for ordinary waves. */\n\treadonly pull?: PullDemand;\n\t/**\n\t * Deferred SELF-rewire (R-rewire-deferred / D47) — the substrate affordance higher-order\n\t * operators (switchMap/mergeMap/concatMap/exhaustMap/flatMap) use to grow/shrink their own\n\t * inner-source dep set in response to their own data. Always present; see {@link RewireNext}.\n\t */\n\trewireNext: RewireNext;\n\t/**\n\t * Deferred up — the boundary-deferred form of {@link Ctx.up} (R-up-routing / R-pull / D59). Routes\n\t * `msgs` up from this node at the COMMITTED wave boundary (broadcast, or up the single `towardDep`\n\t * edge), riding the same R-rewire-deferred (D47) drain as {@link RewireNext}. This is the\n\t * SELF-DEMAND path: a consumer issues `ctx.upNext([[PULL, { pullId, params }]])` to demand a pull\n\t * dep it ALSO reads — the cone-routed PULL reaches the pullId-holder, whose delivery loops back as a\n\t * FRESH wave (not a mid-fn re-entry → no D37). The consumer accepts one-wave latency (the\n\t * HTTP-request model). No node reference needed: the author writes the pullId verbatim.\n\t */\n\tupNext(msgs: Wave, towardDep?: number): void;\n\t/**\n\t * Read a dep's latest value by index (dynamicNode only, R-dynamic-node / D35).\n\t * Present only on dynamicNode fns; all declared deps still participate in wave\n\t * tracking. Under D49/R-resolved-undirty an unread dep's change still fires the fn,\n\t * which re-emits its (unchanged) output as a DATA occurrence — there is NO equals-\n\t * absorption; pair with distinctUntilChanged to suppress unchanged re-emits (opt-in).\n\t */\n\ttrack?(depIndex: number): unknown;\n\t[CTX_DEP_CACHE]?: CtxDepCache;\n\t[CTX_NODE_BINDING]?: CtxNodeBinding;\n}\n\n/** A node fn (R-fn-contract). Registered in a dispatcher pool, indexed by Handle. */\nexport type NodeFn = (ctx: Ctx) => void;\n\n/** Number of declared dep slots visible in this invocation. */\nexport function depCount(ctx: Ctx): number {\n\treturn ctx.waveData.length;\n}\n\n/** DATA/SENTINEL projection batches delivered by one dep in this invocation. */\nexport function depWaves(ctx: Ctx, depIndex: number): readonly (readonly unknown[])[] {\n\treturn ctx.waveData[depIndex] ?? [];\n}\n\n/** Flattened DATA projection for old event-counting operator bodies; null = no wave. */\nexport function depBatch(ctx: Ctx, depIndex: number): readonly unknown[] | null {\n\tconst waves = depWaves(ctx, depIndex);\n\tif (waves.length === 0) return null;\n\tconst flattened = waves.flat().filter((v) => v !== SENTINEL);\n\treturn flattened.length === 0 ? [] : flattened;\n}\n\n/** Latest cached DATA for a dep, derived from implementation-owned dep cache. */\nexport function depLatest(ctx: Ctx, depIndex: number): unknown {\n\treturn ctx[CTX_DEP_CACHE]?.latest[depIndex];\n}\n\n/** Terminal metadata for one dep: false = none, true = COMPLETE, otherwise ERROR payload. */\nexport function depTerminal(ctx: Ctx, depIndex: number): unknown {\n\tconst t = ctx.terminal[depIndex];\n\treturn t === undefined ? false : t;\n}\n","import type { NodeFn } from \"../ctx/types.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport type { MessageBusCommand } from \"./index.js\";\n\nexport interface MessageBusInternalState {\n\treadonly graph: Graph;\n\treadonly name: string;\n\treadonly commandSources: Node<MessageBusCommand>[];\n\treadonly commandBody: NodeFn;\n}\n\nconst busStates = new WeakMap<object, MessageBusInternalState>();\n\nexport function registerMessageBusState(bus: object, state: MessageBusInternalState): void {\n\tbusStates.set(bus, state);\n}\n\nexport function getMessageBusState(bus: object): MessageBusInternalState | undefined {\n\treturn busStates.get(bus);\n}\n\nexport function attachMessageBusCommandSource(\n\tgraph: Graph,\n\tbus: object,\n\tcommands: Node<MessageBusCommand>,\n): () => void {\n\tconst state = getMessageBusState(bus);\n\tif (state === undefined) throw new Error(\"messageBus: unknown implementation\");\n\tif (state.graph !== graph) throw new Error(\"messageBus: command source graph must match\");\n\tstate.commandSources.push(commands);\n\tconst busCommands = (bus as { readonly commands?: Node<MessageBusCommand> }).commands;\n\tif (busCommands === undefined) throw new Error(\"messageBus: missing commands node\");\n\tbusCommands.replaceDeps([...state.commandSources], state.commandBody);\n\tlet released = false;\n\treturn () => {\n\t\tif (released) return;\n\t\treleased = true;\n\t\tconst index = state.commandSources.indexOf(commands);\n\t\tif (index >= 0) state.commandSources.splice(index, 1);\n\t\tbusCommands.replaceDeps([...state.commandSources], state.commandBody);\n\t};\n}\n\nexport function attachMessageBusDeferredCommandSink(\n\tgraph: Graph,\n\tbus: object,\n\tcommands: Node<MessageBusCommand>,\n): () => void {\n\tconst state = getMessageBusState(bus);\n\tif (state === undefined) throw new Error(\"messageBus: unknown implementation\");\n\tif (state.graph !== graph) throw new Error(\"messageBus: command sink graph must match\");\n\tconst busCommands = (bus as { readonly commands?: Node<MessageBusCommand> }).commands;\n\tif (busCommands === undefined) throw new Error(\"messageBus: missing commands node\");\n\tconst boundary = commands as Node<MessageBusCommand> & {\n\t\t__deferBoundary?: (fn: () => void) => void;\n\t};\n\tconst unsubscribe = commands.subscribe((msg) => {\n\t\tif (msg[0] !== \"DATA\") return;\n\t\tconst command = msg[1] as MessageBusCommand;\n\t\tconst send = () => busCommands.down([[\"DATA\", command]]);\n\t\tif (boundary.__deferBoundary === undefined) send();\n\t\telse boundary.__deferBoundary(send);\n\t});\n\treturn unsubscribe;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC2CO,IAAM,WAAW;;;ACoHjB,SAAS,SAAS,KAAU,UAAmD;AACrF,SAAO,IAAI,SAAS,QAAQ,KAAK,CAAC;AACnC;AAGO,SAAS,SAAS,KAAU,UAA6C;AAC/E,QAAM,QAAQ,SAAS,KAAK,QAAQ;AACpC,MAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,QAAM,YAAY,MAAM,KAAK,EAAE,OAAO,CAAC,MAAM,MAAM,QAAQ;AAC3D,SAAO,UAAU,WAAW,IAAI,CAAC,IAAI;AACtC;;;AC7JA,IAAM,YAAY,oBAAI,QAAyC;AAExD,SAAS,wBAAwB,KAAa,OAAsC;AAC1F,YAAU,IAAI,KAA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