@graphrefly/graphrefly 0.41.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (296) hide show
  1. package/dist/{cascading-Cxs1eztH.d.cts → cascading-CH-_VwG9.d.cts} +2 -2
  2. package/dist/{cascading-BNfxffgc.d.ts → cascading-OgKQZjsa.d.ts} +2 -2
  3. package/dist/chunk-3XDYJRYU.js +1 -0
  4. package/dist/{chunk-AI7QC7J6.js → chunk-4YAN45KM.js} +1 -1
  5. package/dist/chunk-626TESAC.js +3 -0
  6. package/dist/chunk-6HOSXQKF.js +1 -0
  7. package/dist/{chunk-G3M3IMEV.js → chunk-CUNIRONA.js} +1 -1
  8. package/dist/chunk-EBW4V6JN.js +1 -0
  9. package/dist/chunk-FDQGFWLF.js +1 -0
  10. package/dist/{chunk-33N4TU3X.js → chunk-FG4TKHMC.js} +1 -1
  11. package/dist/{chunk-YQRN4CIV.js → chunk-I7IGYPSL.js} +1 -1
  12. package/dist/chunk-INQD2KRQ.js +1 -0
  13. package/dist/{chunk-7PQLZMOG.js → chunk-JNWRYDJN.js} +1 -1
  14. package/dist/{chunk-TT4C7DXW.js → chunk-JQFH2DV6.js} +1 -1
  15. package/dist/{chunk-M3FQSXEW.js → chunk-K2Q24F5T.js} +1 -1
  16. package/dist/chunk-KVV66NN2.js +1 -0
  17. package/dist/chunk-NON4NLIC.js +45 -0
  18. package/dist/{chunk-CYOSWFT2.js → chunk-O2BLLH7M.js} +3 -3
  19. package/dist/{chunk-OV5AA6HJ.js → chunk-OCKEEPRJ.js} +1 -1
  20. package/dist/{chunk-X7QKTXXC.js → chunk-OFZG3TB3.js} +3 -3
  21. package/dist/chunk-OYJKFY7V.js +1 -0
  22. package/dist/{chunk-SC27WTSG.js → chunk-P6C4WHZO.js} +1 -1
  23. package/dist/{chunk-VV62MIG4.js → chunk-PT7W5FCD.js} +1 -1
  24. package/dist/{chunk-UISPDFJ3.js → chunk-Q4U3A3L5.js} +1 -1
  25. package/dist/chunk-QE4IGY7I.js +61 -0
  26. package/dist/{chunk-5VEZLQFN.js → chunk-QYVXF7GW.js} +1 -1
  27. package/dist/{chunk-ZAJ7J7TO.js → chunk-S3EEIPO7.js} +1 -1
  28. package/dist/{chunk-GI4Q7PNY.js → chunk-SUWT3ZON.js} +1 -1
  29. package/dist/{chunk-CGNOWGV6.js → chunk-TPKQW72B.js} +1 -1
  30. package/dist/{chunk-L77I47VU.js → chunk-V5A7M7RJ.js} +1 -1
  31. package/dist/chunk-VNC3TMVY.js +1 -0
  32. package/dist/{chunk-AK5RHMC5.js → chunk-VOPGGIL7.js} +1 -1
  33. package/dist/chunk-VQ4A6T2A.js +1 -0
  34. package/dist/{chunk-KNVCCBIU.js → chunk-XG62INFA.js} +1 -1
  35. package/dist/{chunk-F7VUYPP6.js → chunk-Y4NI3X7O.js} +1 -1
  36. package/dist/compat/index.cjs +5 -5
  37. package/dist/compat/index.d.cts +16 -16
  38. package/dist/compat/index.d.ts +16 -16
  39. package/dist/compat/index.js +1 -1
  40. package/dist/compat/jotai/index.d.cts +2 -2
  41. package/dist/compat/jotai/index.d.ts +2 -2
  42. package/dist/compat/nanostores/index.d.cts +2 -2
  43. package/dist/compat/nanostores/index.d.ts +2 -2
  44. package/dist/compat/nestjs/index.cjs +5 -5
  45. package/dist/compat/nestjs/index.d.cts +8 -8
  46. package/dist/compat/nestjs/index.d.ts +8 -8
  47. package/dist/compat/nestjs/index.js +1 -1
  48. package/dist/compat/react/index.d.cts +2 -2
  49. package/dist/compat/react/index.d.ts +2 -2
  50. package/dist/compat/solid/index.d.cts +2 -2
  51. package/dist/compat/solid/index.d.ts +2 -2
  52. package/dist/compat/svelte/index.d.cts +2 -2
  53. package/dist/compat/svelte/index.d.ts +2 -2
  54. package/dist/compat/vue/index.d.cts +2 -2
  55. package/dist/compat/vue/index.d.ts +2 -2
  56. package/dist/compat/zustand/index.cjs +3 -3
  57. package/dist/compat/zustand/index.d.cts +4 -4
  58. package/dist/compat/zustand/index.d.ts +4 -4
  59. package/dist/compat/zustand/index.js +1 -1
  60. package/dist/core/index.d.cts +4 -4
  61. package/dist/core/index.d.ts +4 -4
  62. package/dist/{decay-C25AyNAj.d.cts → decay-2ZukgQ4o.d.cts} +2 -2
  63. package/dist/{decay-BnrlbxSv.d.ts → decay-CdEBmDIs.d.ts} +2 -2
  64. package/dist/extra/browser.d.cts +1 -1
  65. package/dist/extra/browser.d.ts +1 -1
  66. package/dist/extra/index.cjs +14 -14
  67. package/dist/extra/index.d.cts +10 -11
  68. package/dist/extra/index.d.ts +10 -11
  69. package/dist/extra/index.js +1 -1
  70. package/dist/extra/node.cjs +2 -2
  71. package/dist/extra/node.d.cts +1 -1
  72. package/dist/extra/node.d.ts +1 -1
  73. package/dist/extra/node.js +1 -1
  74. package/dist/extra/operators.cjs +1 -1
  75. package/dist/extra/operators.d.cts +1 -1
  76. package/dist/extra/operators.d.ts +1 -1
  77. package/dist/extra/operators.js +1 -1
  78. package/dist/extra/reactive.d.cts +3 -3
  79. package/dist/extra/reactive.d.ts +3 -3
  80. package/dist/extra/reactive.js +1 -1
  81. package/dist/extra/render/index.d.cts +3 -3
  82. package/dist/extra/render/index.d.ts +3 -3
  83. package/dist/extra/sources.cjs +3 -1
  84. package/dist/extra/sources.d.cts +1 -1
  85. package/dist/extra/sources.d.ts +1 -1
  86. package/dist/extra/sources.js +1 -1
  87. package/dist/extra/storage-browser.d.cts +1 -1
  88. package/dist/extra/storage-browser.d.ts +1 -1
  89. package/dist/{fallback-CMZl39L5.d.ts → fallback-CqYVLL6X.d.ts} +1 -1
  90. package/dist/{fallback-8JYU8tlT.d.cts → fallback-Ctlj2tMY.d.cts} +1 -1
  91. package/dist/graph/index.cjs +7 -7
  92. package/dist/graph/index.d.cts +5 -5
  93. package/dist/graph/index.d.ts +5 -5
  94. package/dist/graph/index.js +1 -1
  95. package/dist/{graph-BkIkog4h.d.ts → graph-7VguS7a4.d.ts} +3 -3
  96. package/dist/{graph-E6likq7w.d.cts → graph-C4SHb3Ly.d.cts} +3 -3
  97. package/dist/{index-DgJc8Zgc.d.cts → index-0rKFCVFp.d.cts} +90 -5
  98. package/dist/{index-BAQrjuZF.d.ts → index-B-i4_g3k.d.ts} +2 -2
  99. package/dist/{index-DpiGqtrs.d.cts → index-B5iz82A3.d.cts} +441 -381
  100. package/dist/{index-Bd91Nmf4.d.cts → index-BAOD98JD.d.cts} +4 -4
  101. package/dist/{index-2n8Eai6M.d.ts → index-BG0BN3PB.d.ts} +1 -1
  102. package/dist/{index-z8WFPVI8.d.cts → index-BJX94aud.d.cts} +1 -1
  103. package/dist/{index-DhLyOHYZ.d.ts → index-BP8a88zx.d.ts} +11 -4
  104. package/dist/{index-Cnr1WrlX.d.cts → index-BTQtTb_H.d.cts} +14 -3
  105. package/dist/{index-DOBLxOti.d.cts → index-BVpm6noz.d.cts} +1 -1
  106. package/dist/{index-Cczxgd2D.d.ts → index-Bc41FuHp.d.cts} +3 -3
  107. package/dist/{index-BiHUBEKq.d.cts → index-BdGtBX-X.d.cts} +3 -3
  108. package/dist/{index-da2V5vPy.d.ts → index-Bf7eqeSF.d.ts} +2 -2
  109. package/dist/{index-DuRsN9ae.d.cts → index-BiX1Nkgx.d.cts} +383 -18
  110. package/dist/{index-DGTo1yka.d.cts → index-BoLv_OfD.d.cts} +2 -2
  111. package/dist/{index-DVAlsmEU.d.cts → index-BojK2fwH.d.cts} +3 -3
  112. package/dist/{index-B72TQQHd.d.cts → index-BsT7F2et.d.ts} +3 -3
  113. package/dist/{index-DGD4_fj6.d.cts → index-BwLvVVsy.d.cts} +8 -5
  114. package/dist/{index-CQtWm7jS.d.ts → index-C59mYFKp.d.ts} +9 -9
  115. package/dist/{index-C6ZUaos7.d.ts → index-C7O6r5fV.d.ts} +1 -1
  116. package/dist/{index-CL7oilfm.d.cts → index-C9kSENB4.d.cts} +1 -1
  117. package/dist/{index-DVDapw2k.d.cts → index-C9pjcz3l.d.cts} +35 -36
  118. package/dist/{index-CG33HeBW.d.ts → index-CAC_rNzm.d.ts} +8 -5
  119. package/dist/{index-yLt-aPMp.d.ts → index-CCq87F7t.d.ts} +1 -1
  120. package/dist/{index-D4uimgee.d.cts → index-CDXc9zKM.d.cts} +1 -1
  121. package/dist/{index-B2RUoIUz.d.ts → index-CJK1JkYy.d.ts} +1 -1
  122. package/dist/{index-DktLSZOc.d.cts → index-CLon-IWF.d.cts} +4 -4
  123. package/dist/{index-DQQCOIt8.d.cts → index-COD1kVoS.d.cts} +10 -5
  124. package/dist/{index-bXXLSvor.d.ts → index-CPT7C_f1.d.ts} +4 -4
  125. package/dist/{index-CD2dBMet.d.ts → index-CQG3D1cp.d.ts} +10 -5
  126. package/dist/{index-BQ1fR4li.d.ts → index-CZQXo5tH.d.ts} +35 -36
  127. package/dist/{index-A3U3CSve.d.cts → index-CZjOhcBy.d.cts} +2 -2
  128. package/dist/{index-DYTBbF8T.d.cts → index-ChOyVLKm.d.cts} +1 -1
  129. package/dist/{index-BJSZxSFX.d.ts → index-CvrqGfNS.d.ts} +1 -1
  130. package/dist/{index-DhnsQfa3.d.ts → index-D-AEQVLo.d.ts} +441 -381
  131. package/dist/{index-CAP3UGsq.d.ts → index-D4Y1cMG0.d.ts} +1 -1
  132. package/dist/{index-40ZT4MHj.d.ts → index-DBHK8O6H.d.ts} +14 -3
  133. package/dist/{index-3k4Gg6-n.d.ts → index-DBevwHj_.d.ts} +3 -3
  134. package/dist/{index-Ctb7_2sG.d.ts → index-DIOoAZUX.d.ts} +1 -1
  135. package/dist/{index-WSlcjhQF.d.ts → index-DSZ3ZCHF.d.ts} +124 -13
  136. package/dist/{index-DH4fm2Ck.d.ts → index-Dgs8zcj7.d.ts} +2 -2
  137. package/dist/{index-BaA-xpSw.d.ts → index-Dh_HJ82K.d.ts} +3 -3
  138. package/dist/{index-CtFNGe-m.d.cts → index-Dhc7a7Xo.d.cts} +2 -2
  139. package/dist/{index-CoM4rzyB.d.ts → index-Dmqp7KjD.d.ts} +1 -1
  140. package/dist/{index-B6iTqKtJ.d.ts → index-Dn-wI9g4.d.ts} +2 -2
  141. package/dist/{index-C-dkXOpB.d.cts → index-Du7u1lSf.d.cts} +11 -4
  142. package/dist/{index-DfOK_oL5.d.ts → index-DwigL4lY.d.ts} +383 -18
  143. package/dist/index-DyR7eU5S.d.cts +779 -0
  144. package/dist/index-JZUPJIJy.d.ts +779 -0
  145. package/dist/{index-I1cCY3ZI.d.ts → index-K0_0eR8g.d.ts} +90 -5
  146. package/dist/{index-BilOa6AE.d.cts → index-O16yXPK4.d.cts} +124 -13
  147. package/dist/{index-CRm0YIzC.d.cts → index-O7fucFrU.d.cts} +9 -9
  148. package/dist/{index-MxYuWOrf.d.cts → index-RV_yDjOX.d.cts} +3 -3
  149. package/dist/{index-C5cQ7Gfx.d.ts → index-cm1GNcWE.d.ts} +4 -4
  150. package/dist/{index-CgnCFhr2.d.cts → index-f5IivDUX.d.cts} +1 -1
  151. package/dist/{index-PgwvGWa1.d.cts → index-hHcaFlJX.d.cts} +1 -1
  152. package/dist/{index-tV3AA9hI.d.cts → index-tJoTcnHh.d.cts} +2 -2
  153. package/dist/{index-eaQuGJnv.d.ts → index-wAzD9yVj.d.ts} +3 -3
  154. package/dist/{index-D3ayz3hy.d.cts → index-z96luz5O.d.cts} +1 -1
  155. package/dist/index.cjs +48 -48
  156. package/dist/index.d.cts +45 -50
  157. package/dist/index.d.ts +45 -50
  158. package/dist/index.js +1 -1
  159. package/dist/{meta-D8OyedKp.d.ts → meta-BgVAsg9j.d.ts} +1 -1
  160. package/dist/{meta-Ct9nqQS5.d.cts → meta-vE8bxW1E.d.cts} +1 -1
  161. package/dist/{node-BYInONRr.d.cts → node-ClS5yC-B.d.cts} +1 -1
  162. package/dist/{node-BYInONRr.d.ts → node-ClS5yC-B.d.ts} +1 -1
  163. package/dist/{observable-DO8DDEzv.d.ts → observable-BsBzUrcI.d.ts} +1 -1
  164. package/dist/{observable-DMIlYJV1.d.cts → observable-DLGPPtb8.d.cts} +1 -1
  165. package/dist/patterns/ai/browser.d.cts +4 -4
  166. package/dist/patterns/ai/browser.d.ts +4 -4
  167. package/dist/patterns/ai/browser.js +1 -1
  168. package/dist/patterns/ai/index.cjs +17 -17
  169. package/dist/patterns/ai/index.d.cts +17 -17
  170. package/dist/patterns/ai/index.d.ts +17 -17
  171. package/dist/patterns/ai/index.js +1 -1
  172. package/dist/patterns/ai/node.d.cts +4 -4
  173. package/dist/patterns/ai/node.d.ts +4 -4
  174. package/dist/patterns/ai/node.js +1 -1
  175. package/dist/patterns/cqrs/index.cjs +3 -3
  176. package/dist/patterns/cqrs/index.d.cts +6 -6
  177. package/dist/patterns/cqrs/index.d.ts +6 -6
  178. package/dist/patterns/cqrs/index.js +1 -1
  179. package/dist/patterns/demo-shell/index.cjs +5 -5
  180. package/dist/patterns/demo-shell/index.d.cts +5 -5
  181. package/dist/patterns/demo-shell/index.d.ts +5 -5
  182. package/dist/patterns/demo-shell/index.js +1 -1
  183. package/dist/patterns/domain-templates/index.cjs +3 -3
  184. package/dist/patterns/domain-templates/index.d.cts +4 -4
  185. package/dist/patterns/domain-templates/index.d.ts +4 -4
  186. package/dist/patterns/domain-templates/index.js +1 -1
  187. package/dist/patterns/graphspec/index.cjs +12 -12
  188. package/dist/patterns/graphspec/index.d.cts +5 -5
  189. package/dist/patterns/graphspec/index.d.ts +5 -5
  190. package/dist/patterns/graphspec/index.js +1 -1
  191. package/dist/patterns/harness/index.cjs +10 -8
  192. package/dist/patterns/harness/index.d.cts +11 -12
  193. package/dist/patterns/harness/index.d.ts +11 -12
  194. package/dist/patterns/harness/index.js +1 -1
  195. package/dist/patterns/inspect/index.cjs +3 -0
  196. package/dist/patterns/inspect/index.d.cts +9 -0
  197. package/dist/patterns/inspect/index.d.ts +9 -0
  198. package/dist/patterns/inspect/index.js +1 -0
  199. package/dist/patterns/job-queue/index.cjs +3 -3
  200. package/dist/patterns/job-queue/index.d.cts +6 -6
  201. package/dist/patterns/job-queue/index.d.ts +6 -6
  202. package/dist/patterns/job-queue/index.js +1 -1
  203. package/dist/patterns/memory/index.cjs +3 -3
  204. package/dist/patterns/memory/index.d.cts +6 -6
  205. package/dist/patterns/memory/index.d.ts +6 -6
  206. package/dist/patterns/memory/index.js +1 -1
  207. package/dist/patterns/messaging/index.cjs +3 -3
  208. package/dist/patterns/messaging/index.d.cts +5 -5
  209. package/dist/patterns/messaging/index.d.ts +5 -5
  210. package/dist/patterns/messaging/index.js +1 -1
  211. package/dist/patterns/orchestration/index.cjs +3 -3
  212. package/dist/patterns/orchestration/index.d.cts +7 -7
  213. package/dist/patterns/orchestration/index.d.ts +7 -7
  214. package/dist/patterns/orchestration/index.js +1 -1
  215. package/dist/patterns/process/index.cjs +1 -1
  216. package/dist/patterns/process/index.d.cts +7 -7
  217. package/dist/patterns/process/index.d.ts +7 -7
  218. package/dist/patterns/process/index.js +1 -1
  219. package/dist/patterns/reactive-layout/index.cjs +4 -4
  220. package/dist/patterns/reactive-layout/index.d.cts +5 -5
  221. package/dist/patterns/reactive-layout/index.d.ts +5 -5
  222. package/dist/patterns/reactive-layout/index.js +1 -1
  223. package/dist/patterns/reduction/index.cjs +3 -3
  224. package/dist/patterns/reduction/index.d.cts +4 -4
  225. package/dist/patterns/reduction/index.d.ts +4 -4
  226. package/dist/patterns/reduction/index.js +1 -1
  227. package/dist/patterns/surface/index.cjs +8 -8
  228. package/dist/patterns/surface/index.d.cts +6 -6
  229. package/dist/patterns/surface/index.d.ts +6 -6
  230. package/dist/patterns/surface/index.js +1 -1
  231. package/dist/{pipeline-graph-MWrQZXCq.d.cts → pipeline-graph-DPqKDk59.d.cts} +5 -5
  232. package/dist/{pipeline-graph-CB4La-UW.d.ts → pipeline-graph-loP57TBA.d.ts} +5 -5
  233. package/dist/{reactive-layout-BtZfUKuL.d.cts → reactive-layout-Dsvob4zD.d.cts} +2 -2
  234. package/dist/{reactive-layout-KJj4E2dT.d.ts → reactive-layout-v7KPvxoc.d.ts} +2 -2
  235. package/dist/{reactive-log-_zeEnB9H.d.cts → reactive-log-B00laMSQ.d.cts} +1 -1
  236. package/dist/{reactive-log-BlAsPLl2.d.ts → reactive-log-BezYsbA_.d.ts} +1 -1
  237. package/dist/{reactive-map-6P_k3AQM.d.cts → reactive-map-48mnZ-nu.d.cts} +1 -1
  238. package/dist/{reactive-map-CjXByDV-.d.ts → reactive-map-BVVPdvmi.d.ts} +1 -1
  239. package/dist/resilience-YIWPK4YC.js +1 -0
  240. package/dist/{sugar-DzePN5-g.d.cts → sugar-DLwvMr3F.d.ts} +24 -4
  241. package/dist/{sugar-BhfjgetH.d.ts → sugar-DyVGtczU.d.cts} +24 -4
  242. package/dist/{topology-tree-mF7Emqzm.d.ts → topology-tree-BNGvuG82.d.ts} +1 -1
  243. package/dist/{topology-tree-3LBKFsUo.d.cts → topology-tree-BSdfSwMi.d.cts} +1 -1
  244. package/dist/{types-1Dhoi7HM.d.cts → types-B1jDWVsM.d.cts} +1 -1
  245. package/dist/{types-39jk0kaV.d.ts → types-DkzUUs0H.d.ts} +1 -1
  246. package/package.json +11 -51
  247. package/dist/budget-gate-CmmVtasH.d.ts +0 -115
  248. package/dist/budget-gate-DiP_nK0n.d.cts +0 -115
  249. package/dist/chunk-2W553JJC.js +0 -1
  250. package/dist/chunk-4MKL6Q3K.js +0 -1
  251. package/dist/chunk-5B3JDG5F.js +0 -1
  252. package/dist/chunk-5QSXEMXG.js +0 -1
  253. package/dist/chunk-5TEFC2ZX.js +0 -1
  254. package/dist/chunk-5TOPVRN6.js +0 -1
  255. package/dist/chunk-EC2WNSZ7.js +0 -1
  256. package/dist/chunk-ELAASRBT.js +0 -3
  257. package/dist/chunk-H5SCWHWP.js +0 -1
  258. package/dist/chunk-OLIKJUKI.js +0 -1
  259. package/dist/chunk-POXANAJ6.js +0 -3
  260. package/dist/chunk-RSMEXK53.js +0 -43
  261. package/dist/chunk-SGS4OJGS.js +0 -1
  262. package/dist/chunk-URJ2VFNC.js +0 -1
  263. package/dist/chunk-VXPLLA4P.js +0 -1
  264. package/dist/chunk-WZYB3JQS.js +0 -1
  265. package/dist/chunk-Z6X7B6A4.js +0 -61
  266. package/dist/index-8s-Qm-gz.d.ts +0 -218
  267. package/dist/index-BgjS2b8N.d.ts +0 -366
  268. package/dist/index-BmSQLAZo.d.cts +0 -244
  269. package/dist/index-CGhMJNHb.d.cts +0 -128
  270. package/dist/index-CUIkE1l9.d.cts +0 -230
  271. package/dist/index-Ck35nA-T.d.ts +0 -244
  272. package/dist/index-CuPUehFa.d.cts +0 -218
  273. package/dist/index-D1Gc7wV5.d.ts +0 -230
  274. package/dist/index-N2MAxt7_.d.ts +0 -128
  275. package/dist/index-t6L2qpHh.d.cts +0 -366
  276. package/dist/patterns/audit/index.cjs +0 -3
  277. package/dist/patterns/audit/index.d.cts +0 -8
  278. package/dist/patterns/audit/index.d.ts +0 -8
  279. package/dist/patterns/audit/index.js +0 -1
  280. package/dist/patterns/guarded-execution/index.cjs +0 -3
  281. package/dist/patterns/guarded-execution/index.d.cts +0 -9
  282. package/dist/patterns/guarded-execution/index.d.ts +0 -9
  283. package/dist/patterns/guarded-execution/index.js +0 -1
  284. package/dist/patterns/lens/index.cjs +0 -3
  285. package/dist/patterns/lens/index.d.cts +0 -7
  286. package/dist/patterns/lens/index.d.ts +0 -7
  287. package/dist/patterns/lens/index.js +0 -1
  288. package/dist/patterns/refine-loop/index.cjs +0 -5
  289. package/dist/patterns/refine-loop/index.d.cts +0 -9
  290. package/dist/patterns/refine-loop/index.d.ts +0 -9
  291. package/dist/patterns/refine-loop/index.js +0 -1
  292. package/dist/patterns/resilient-pipeline/index.cjs +0 -3
  293. package/dist/patterns/resilient-pipeline/index.d.cts +0 -8
  294. package/dist/patterns/resilient-pipeline/index.d.ts +0 -8
  295. package/dist/patterns/resilient-pipeline/index.js +0 -1
  296. package/dist/resilience-JISHQD2F.js +0 -1
@@ -1,4 +1,6 @@
1
- "use strict";var Zt=Object.defineProperty;var qr=Object.getOwnPropertyDescriptor;var Ur=Object.getOwnPropertyNames;var Kr=Object.prototype.hasOwnProperty;var _e=(r,e)=>()=>(r&&(e=r(r=0)),e);var Wr=(r,e)=>{for(var t in e)Zt(r,t,{get:e[t],enumerable:!0})},Jr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ur(e))!Kr.call(r,s)&&s!==t&&Zt(r,s,{get:()=>e[s],enumerable:!(n=qr(e,s))||n.enumerable});return r};var Yr=r=>Jr(Zt({},"__esModule",{value:!0}),r);var $e,D,Q,W,Re,De,Ve,pe,$,I,Be,Et,jn,kt,zn,Hn,Rt,en,tn,nn,Ot,be=_e(()=>{"use strict";$e=Symbol.for("graphrefly/START"),D=Symbol.for("graphrefly/DATA"),Q=Symbol.for("graphrefly/DIRTY"),W=Symbol.for("graphrefly/RESOLVED"),Re=Symbol.for("graphrefly/INVALIDATE"),De=Symbol.for("graphrefly/PAUSE"),Ve=Symbol.for("graphrefly/RESUME"),pe=Symbol.for("graphrefly/TEARDOWN"),$=Symbol.for("graphrefly/COMPLETE"),I=Symbol.for("graphrefly/ERROR"),Be=Object.freeze([Q]),Et=Object.freeze([W]),jn=Object.freeze([Re]),kt=Object.freeze([$e]),zn=Object.freeze([$]),Hn=Object.freeze([pe]),Rt=Object.freeze([Be]),en=Object.freeze([Et]),tn=Object.freeze([jn]),nn=Object.freeze([zn]),Ot=Object.freeze([Hn])});function qn(r,e){let t=new TextEncoder().encode(r.name);if(t.length===0||t.length>255)throw new Error(`encodeEnvelope: codec name "${r.name}" encodes to ${t.length} bytes (must be 1\u2013255)`);let n=r.version;if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`encodeEnvelope: codec.version ${n} out of u16 range (expected integer 0\u201365535)`);let s=2+t.length+2+e.length;if(s>4294967295)throw new Error(`encodeEnvelope: total envelope size ${s} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let o=new Uint8Array(s),i=0;return o[i++]=rn,o[i++]=t.length,o.set(t,i),i+=t.length,o[i++]=n>>>8&255,o[i++]=n&255,o.set(e,i),o}function Un(r,e){if(r.length<Bn)throw new Error(`decodeEnvelope: bytes too short (${r.length} < ${Bn})`);let t=0,n=r[t++];if(n!==rn)throw new Error(`decodeEnvelope: unsupported envelope version ${n} (expected ${rn})`);let s=r[t++];if(s===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(t+s+2>r.length)throw new Error(`decodeEnvelope: envelope truncated (need ${t+s+2} bytes, have ${r.length})`);let o=new TextDecoder().decode(r.subarray(t,t+s));t+=s;let i=(r[t]<<8|r[t+1])>>>0;t+=2;let a=r.subarray(t),d=e.lookupCodec(o);if(d==null)throw new Error(`decodeEnvelope: codec "${o}" not registered (envelope codec_v=${i})`);return{codec:d,codecVersion:i,payload:a}}function Kn(r){r.registerCodec(Qr)}var Qr,rn,Bn,on=_e(()=>{"use strict";Qr={name:"json",version:1,contentType:"application/json",encode(r){let e=JSON.stringify(r);return new TextEncoder().encode(e)},decode(r,e){let t=new TextDecoder().decode(r);return JSON.parse(t)}},rn=1,Bn=4});function St(r){if(r==null)return Qe;let{type:e,id:t,...n}=r;return{type:e??"system",id:t??"",...n}}var Qe,At=_e(()=>{"use strict";Qe={type:"system",id:""}});function ht(){return Xe>0||ft}function Wn(){return Xe>0}function et(r){Xe>0?pt.push(r):r()}function U(r){Xe+=1;let e=!1;try{r()}catch(t){throw e=!0,t}finally{if(Xe-=1,Xe===0)if(e){if(!ft){let t=pt.splice(0);for(let n of t)try{n()}catch{}qe.length=0,Ue.length=0,Ze.length=0}}else Xr()}}function Xr(){let r=!ft;r&&(ft=!0);let e=[],t=0;try{for(;qe.length>0||Ue.length>0||Ze.length>0||r&&pt.length>0;){if(r&&pt.length>0){let o=pt.splice(0);for(let i of o)try{i()}catch(a){e.push(a)}continue}if(t+=1,t>1e3)throw qe.length=0,Ue.length=0,Ze.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let s=(qe.length>0?qe:Ue.length>0?Ue:Ze).splice(0);for(let o of s)try{o()}catch(i){e.push(i)}}}finally{r&&(ft=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function mt(r,e,t){if(e.length===0)return;if(e.length===1){let u=t(e[0][0]);if(u<3||!ht()){r(e);return}(u>=5?Ze:u===4?Ue:qe).push(()=>r(e));return}let n=e.length,s=n,o=n,i=n,a=0;for(;a<n&&t(e[a][0])<3;)a++;for(s=a;a<n&&t(e[a][0])===3;)a++;for(o=a;a<n&&t(e[a][0])===4;)a++;i=a;let d=ht();if(s>0){let u=e.slice(0,s);r(u)}if(o>s){let u=e.slice(s,o);d?qe.push(()=>r(u)):r(u)}if(i>o){let u=e.slice(o,i);d?Ue.push(()=>r(u)):r(u)}if(n>i){let u=e.slice(i,n);d?Ze.push(()=>r(u)):r(u)}}var Xe,ft,qe,Ue,Ze,pt,Me=_e(()=>{"use strict";Xe=0,ft=!1,qe=[],Ue=[],Ze=[],pt=[]});function K(){return Math.trunc(performance.now()*1e6)}function xe(){return Date.now()*1e6}var Oe=_e(()=>{"use strict"});function Jn(r){r.registerMessageType($e,{tier:0,wireCrossing:!1}),r.registerMessageType(Q,{tier:1,wireCrossing:!1}),r.registerMessageType(Re,{tier:1,wireCrossing:!1,metaPassthrough:!1}),r.registerMessageType(De,{tier:2,wireCrossing:!1}),r.registerMessageType(Ve,{tier:2,wireCrossing:!1}),r.registerMessageType(D,{tier:3,wireCrossing:!0}),r.registerMessageType(W,{tier:3,wireCrossing:!0}),r.registerMessageType($,{tier:4,wireCrossing:!0,metaPassthrough:!1}),r.registerMessageType(I,{tier:4,wireCrossing:!0,metaPassthrough:!1}),r.registerMessageType(pe,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var Ct,Yn=_e(()=>{"use strict";be();Ct=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_rigorRecorder;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=t=>{let n=this._messageTypes.get(t);return n!=null?n.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}get rigorRecorder(){return this._rigorRecorder}set rigorRecorder(e){this._rigorRecorder=e}registerMessageType(e,t){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:t.tier,wireCrossing:t.wireCrossing??t.tier>=3,metaPassthrough:t.metaPassthrough??!0}),this}messageTier(e){let t=this._messageTypes.get(e);return t!=null?t.tier:1}isWireCrossing(e){let t=this._messageTypes.get(e);return t!=null?t.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let t=this._messageTypes.get(e);return t!=null?t.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function Qn(r){return Array.isArray(r)?[...r]:[r]}function Zr(r,e){return r.has(e)||r.has("*")}function Xn(r){let e=[];return r((s,o)=>{e.push({kind:"allow",actions:new Set(Qn(s)),where:o?.where??(()=>!0)})},(s,o)=>{e.push({kind:"deny",actions:new Set(Qn(s)),where:o?.where??(()=>!0)})}),(s,o)=>{let i=!1,a=!1;for(let d of e)Zr(d.actions,o)&&d.where(s)&&(d.kind==="deny"?i=!0:a=!0);return i?!1:a}}function sn(r){let e=eo.filter(t=>r({type:t,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(t=>t==="human"||t==="llm"||t==="system")?"both":e.length===1?e[0]:e.join("+")}var Se,eo,tt=_e(()=>{"use strict";Se=class extends Error{actor;action;nodeName;constructor(e,t){super(t??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}};eo=["human","llm","wallet","system"]});function an(r){if(r===void 0)return null;if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError(`Cannot hash non-finite number: ${r}`);if(Number.isInteger(r)&&!Number.isSafeInteger(r))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${r}. Cross-language cid parity is not guaranteed for unsafe integers.`);return r}if(typeof r=="string"||typeof r=="boolean"||r===null)return r;if(Array.isArray(r))return r.map(an);if(typeof r=="object"&&r!==null){let e={};for(let t of Object.keys(r).sort())e[t]=an(r[t]);return e}return null}function ro(r){let e=no.encode(r),t=e.length,n=t*8,s=t+9+63&-64,o=new Uint8Array(s);o.set(e),o[t]=128;let i=new DataView(o.buffer);i.setUint32(s-4,n>>>0,!1),i.setUint32(s-8,Math.floor(n/4294967296)>>>0,!1);let a=1779033703,d=3144134277,u=1013904242,c=2773480762,p=1359893119,l=2600822924,h=528734635,f=1541459225,b=new Uint32Array(64),m=(v,g)=>v>>>g|v<<32-g;for(let v=0;v<s;v+=64){for(let N=0;N<16;N++)b[N]=i.getUint32(v+N*4,!1);for(let N=16;N<64;N++){let P=b[N-15],H=b[N-2],F=m(P,7)^m(P,18)^P>>>3,ye=m(H,17)^m(H,19)^H>>>10;b[N]=b[N-16]+F+b[N-7]+ye>>>0}let g=a,_=d,w=u,E=c,y=p,x=l,k=h,S=f;for(let N=0;N<64;N++){let P=m(y,6)^m(y,11)^m(y,25),H=y&x^~y&k,F=S+P+H+to[N]+b[N]>>>0,ye=m(g,2)^m(g,13)^m(g,22),ve=g&_^g&w^_&w,ke=ye+ve>>>0;S=k,k=x,x=y,y=E+F>>>0,E=w,w=_,_=g,g=F+ke>>>0}a=a+g>>>0,d=d+_>>>0,u=u+w>>>0,c=c+E>>>0,p=p+y>>>0,l=l+x>>>0,h=h+k>>>0,f=f+S>>>0}let T=v=>v.toString(16).padStart(8,"0");return T(a)+T(d)+T(u)+T(c)+T(p)+T(l)+T(h)+T(f)}function un(r){let e=an(r??null),t=JSON.stringify(e);return ro(t).slice(0,16)}function oo(){let r=globalThis.crypto;if(r?.randomUUID)return r.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),t=e()+e()+e()+e();return`${t.slice(0,8)}-${t.slice(8,12)}-4${t.slice(13,16)}-${(parseInt(t.slice(16,17),16)&3|8).toString(16)}${t.slice(17,20)}-${t.slice(20,32)}`}function dn(r,e,t){let n=t?.id??oo();if(r===0)return{id:n,version:0};let o=(t?.hash??un)(e);return{id:n,version:0,cid:o,prev:null}}function Zn(r,e,t){r.version+=1,"cid"in r&&(r.prev=r.cid,r.cid=t(e))}var to,no,er=_e(()=>{"use strict";to=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),no=new TextEncoder});function rr(r){return{node:r,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function cn(r){r.prevData=void 0,r.dirty=!1,r.involvedThisWave=!1,r.dataBatch.length=0,r.terminal=void 0}function Dt(r){return r.length===0?r:typeof r[0]=="symbol"?[r]:r}function ee(r,e,t){let n=or(r)?r:[],s=typeof r=="function"?r:typeof e=="function"?e:void 0,o={};return or(r)?o=(ln(e)?e:t)??{}:ln(r)?o=r:o=(ln(e)?e:t)??{},new oe(n,s,o)}var tr,nr,so,io,nt,oe,or,ln,Ie=_e(()=>{"use strict";on();At();Me();Oe();Yn();tt();be();er();tr=()=>{},nr=100;so=(r,e,t,n)=>{t.direction==="down-in"&&r._onDepMessage(t.depIndex,e)},io=(r,e,t,n)=>{let s=r;if(s._status==="completed"||s._status==="errored")return;let o=s._cached,i=o===void 0?[kt]:[kt,[D,o]];s._status==="dirty"&&i.push(Be),mt(e,i,s._config.tierOf)},nt=new Ct({onMessage:so,onSubscribe:io});Jn(nt);Kn(nt);oe=class r{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,t,n){this._config=n.config??nt,this._config.onMessage,this._optsName=n.name,this._describeKind=n.describeKind,this._equals=n.equals??Object.is,this._resubscribable=n.resubscribable??!1,this._resetOnTeardown=n.resetOnTeardown??!1,this._autoComplete=n.completeWhenDepsComplete??!0,this._autoError=n.errorWhenDepsError??!0,this._pausable=n.pausable??!0,this._guard=n.guard,this._fn=t,this._partial=n.partial??!1,this._cached=n.initial!==void 0?n.initial:void 0,this._status=e.length===0&&t==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=n.versioningHash??this._config.defaultHashFn??un;let s=n.versioning??this._config.defaultVersioning;this._versioningLevel=s,this._versioning=s!=null?dn(s,this._cached===void 0?void 0:this._cached,{id:n.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(rr);let o={};for(let[a,d]of Object.entries(n.meta??{})){let u={initial:d,name:`${n.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};n.guard!=null&&(u.guard=n.guard),o[a]=new r([],void 0,u)}Object.freeze(o),this.meta=o,this._hasMeta=Object.keys(o).length>0;let i=this;this._actions={emit(a){i._emit([[D,a]])},down(a){i._emit(Dt(a))},up(a){i._emitUp(Dt(a))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,t){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let n=this._versioningLevel;if(n!=null&&e<=n)return;let s=t?.hash??this._hashFn;s!==this._hashFn&&(this._hashFn=s);let o=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??t?.id,d=i?.version??0,u=dn(e,o,{id:a,hash:s});u.version=d,this._versioning=u,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let t=St(e);if(this._guard!=null&&!this._guard(t,"observe"))return!1;if(this._extraGuards!=null){for(let n of this._extraGuards)if(!n(t,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let t=this._guard!=null||this._extraGuards!=null,n=e?.actor!=null;if(!t&&!n)return;let s=St(e?.actor),o=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(s,o))throw new Se({actor:s,action:o,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(s,o))throw new Se({actor:s,action:o,nodeName:this.name})}this._lastMutation={actor:s,timestamp_ns:xe()}}down(e,t){let n=Dt(e);n.length!==0&&(this._checkGuard(t),this._emit(n))}emit(e,t){this._checkGuard(t),this._emit([[D,e]])}up(e,t){if(this._deps.length===0)return;let n=Dt(e);if(n.length===0)return;this._checkGuard(t);let s=t??{internal:!0};this._validateUpTiers(n);for(let o of this._deps)o.node.up?.(n,s)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let t of this._deps)t.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let t=this._config.tierOf;for(let n of e){let s=t(n[0]);if(s===3||s===4)throw new Error(`Node "${this.name}": tier-${s} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,t){if(t!=null&&this._guard!=null){let d=St(t);if(!this._guard(d,"observe"))throw new Se({actor:d,action:"observe",nodeName:this.name})}let s=this._isTerminal&&this._resubscribable;if(s){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let d of this._deps)cn(d);if(this._partial===!1){for(let d of this._deps)if(d.prevData!==void 0||d.dataBatch.length!==0||d.terminal!==void 0||d.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let o;try{o=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:s},this._actions)}catch(d){throw this._sinkCount-=1,d}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(d){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof o=="function")try{o()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!0,this._sinkCount-=1,this._removeSink(e),typeof o=="function"&&o(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[t]=this._sinks;this._sinks=t}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,t=0;try{for(let n=0;n<e;n++){let s=n,o=this._deps[n];o.unsub=tr,o.unsub=o.node.subscribe(i=>{if(o.unsub===null)return;let a=this._config.tierOf,d=!1;for(let u of i)a(u[0])>=3&&(d=!0),this._config.onMessage(this,u,{direction:"down-in",depIndex:s},this._actions);d&&this._maybeRunFnOnSettlement()}),t++}}catch(n){this._deps[t].unsub=null;for(let s=0;s<t;s++){let o=this._deps[s];if(o.unsub!=null){let i=o.unsub;o.unsub=null;try{i()}catch{}cn(o)}}throw this._dirtyDepCount=0,n}}_addDep(e){for(let s=0;s<this._deps.length;s++)if(this._deps[s].node===e)return s;let t=this._deps.length,n=rr(e);if(this._deps.push(n),this._sinks==null)return t;n.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Rt),n.unsub=tr;try{n.unsub=e.subscribe(s=>{if(n.unsub===null)return;let o=this._config.tierOf,i=!1;for(let a of s)o(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:t},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(s){throw n.unsub=null,this._deps.pop(),this._dirtyDepCount--,s}return t}_deactivate(e=!1){let t=this._cleanup;if(this._cleanup=void 0,typeof t=="function")try{t()}catch(n){this._emit([[I,this._wrapFnError("cleanup threw",n)]])}else if(t!=null&&typeof t=="object"){let n=t.deactivate;if(typeof n=="function")try{n()}catch(s){this._emit([[I,this._wrapFnError("cleanup.deactivate threw",s)]])}}for(let n of this._deps){if(n.unsub!=null){let s=n.unsub;n.unsub=null;try{s()}catch{}}cn(n)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,t){let n=this._deps[e],s=t[0];if(this._inspectorHooks!=null){let o={kind:"dep_message",depIndex:e,message:t};for(let i of this._inspectorHooks)i(o)}if(s!==$e){if(s===Q){this._depDirtied(n);return}if(s===Re){if(this._depInvalidated(n),this._cached===void 0)return;this._emit(tn);return}if(s===De||s===Ve){this._emit([t]);return}if(s===pe){this._emit(Ot);return}if(s===D)this._depSettledAsData(n,t[1]);else if(s===W)this._depSettledAsResolved(n);else if(s===$)this._depSettledAsTerminal(n,!0);else if(s===I)this._depSettledAsTerminal(n,t[1]);else{this._emit([t]);return}if(!this._fn){(s===D||s===W)&&this._emit([t]),(s===$||s===I)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Rt))}_depSettledAsData(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(t),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=t,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let t=this._deps[e];if(t.dataBatch.length===0&&t.prevData===void 0&&t.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(en),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(t=>t.terminal!==void 0&&t.terminal!==!0);if(e!=null){this._autoError&&this._emit([[I,e.terminal]]);return}this._autoComplete&&this._deps.every(t=>t.terminal!==void 0)&&this._emit(nn)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(i){this._emit([[I,this._wrapFnError("cleanup threw",i)]]);return}}else if(e!=null&&typeof e=="object"){let i=e.beforeRun;if(typeof i=="function"){e.beforeRun=void 0;try{i()}catch(a){this._emit([[I,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let t=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),n=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=t[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let s=this._deps.map(i=>i.terminal),o={prevData:n,terminalDeps:s,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:t,prevData:n};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(t,this._actions,o);if(typeof i=="function")this._cleanup=i;else if(i!=null&&typeof i=="object"){let a=i;(typeof a.beforeRun=="function"||typeof a.deactivate=="function"||typeof a.invalidate=="function")&&(this._cleanup=i)}}catch(i){this._emit([[I,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>nr?(this._rerunDepth=0,this._emit([[I,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${nr} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,t){let n=t instanceof Error?t.message:String(t);return new Error(`Node "${this.name}": ${e}: ${n}`,{cause:t})}_frameBatch(e){let t=this._config.tierOf;if(e.length===1)return t(e[0][0])===3&&this._status!=="dirty"?[Be,e[0]]:e;let n=!0,s=!1,o=!1,i=-1;for(let d of e){let u=t(d[0]);u<i&&(n=!1),u===3&&(s=!0),d[0]===Q&&(o=!0),i=u}let a=e;if(!n){let d=e.map((u,c)=>({m:u,i:c,tier:t(u[0])}));d.sort((u,c)=>u.tier-c.tier||u.i-c.i),a=d.map(u=>u.m)}if(s&&!o&&this._status!=="dirty"){let d=0;for(;d<a.length&&t(a[d][0])===0;)d++;return d===0?[Be,...a]:[...a.slice(0,d),Be,...a.slice(d)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let d=e[a];if(d[0]===I&&d[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let t=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(d=>d[0]===pe||d[0]===Re);if(a.length===0)return;t=a}t=this._frameBatch(t);let s=null;for(let a=0;a<t.length;a++){let d=t[a],u=d[0];if(u!==De&&u!==Ve){s?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===De?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let p=d[1];if(u===De)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(p),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(p))c=!1;else if(this._pauseLocks.delete(p),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let l=this._pauseBuffer;this._pauseBuffer=[],this._emit(l)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?s?.push(d):s==null&&(s=t.slice(0,a))}if(s!=null){if(s.length===0)return;t=s}if(this._hasMeta&&t.some(a=>a[0]===pe))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Ot)}catch{}let{finalMessages:o,equalsError:i}=this._updateState(t);if(o.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:o})}catch{}}if(o.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,d=[];for(let u of o)a(u[0])===3?this._pauseBuffer.push(u):d.push(u);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(o);i!=null&&this._emit([[I,i]])}_updateState(e){let t=this._config.tierOf,n,s,o=-1,i=0;for(let c of e)t(c[0])===3&&i++;let a=i<=1,d=-1;if(this._versioning!=null&&i>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===D){d=c;break}}for(let c=0;c<e.length;c++){let p=e[c],l=p[0];if(l===D){if(p.length>=2){let h=!1;if(a&&this._cached!==void 0)try{h=this._equals(this._cached,p[1])}catch(f){s=this._wrapFnError("equals threw",f),o=c;break}if(h){n==null&&(n=e.slice(0,c)),n.push(Et),this._status="resolved";continue}this._cached=p[1],this._versioning!=null&&(d<0||c===d)&&Zn(this._versioning,p[1],this._hashFn)}this._status="settled",n?.push(p)}else if(n?.push(p),l===Q)this._status="dirty";else if(l===W)this._status="resolved";else if(l===$){this._status="completed";{let h=this._config.rigorRecorder;if(h!=null)try{h.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(l===I){this._status="errored";{let h=this._config.rigorRecorder;if(h!=null)try{h.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(l===Re){if(this._cached!==void 0){let f=this._config.rigorRecorder;if(f!=null)try{f.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let h=this._cleanup;if(typeof h=="function"){this._cleanup=void 0;try{h()}catch{}}else if(h!=null&&typeof h=="object"){let f=h.invalidate;if(typeof f=="function")try{f()}catch{}}}else l===pe&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=o>=0?n??e.slice(0,o):n??e;return s!=null?{finalMessages:u,equalsError:s}:{finalMessages:u}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let t=[...this._sinks];for(let n of t)n(e)};_dispatchOrAccumulate(e){if(Wn()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],et(()=>this._flushBatchPending()));for(let t of e)this._batchPendingMessages.push(t);return}mt(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let t=this._frameBatch(e);mt(this._deliverToSinks,t,this._config.tierOf)}},or=r=>Array.isArray(r),ln=r=>typeof r=="object"&&r!=null&&!Array.isArray(r)});function V(r,e){return ee([],{...e,initial:r})}function ue(r,e){return ee((n,s,o)=>r(s,o)??void 0,{describeKind:"producer",...e})}function G(r,e,t){return ee(r,(s,o,i)=>{let a=s.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);o.emit(e(a,i))},{describeKind:"derived",...t})}function he(r,e,t){return ee(r,(s,o,i)=>{let a=s.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);return e(a,o,i)??void 0},{describeKind:"effect",...t})}var te=_e(()=>{"use strict";Ie()});function fn(r){return{describeKind:"producer",...r}}function sr(r,e){return ue(t=>{let n=!1;try{for(let s of r){if(n)return;t.emit(s)}n||t.down([[$]])}catch(s){n||t.down([[I,s]])}return()=>{n=!0}},fn(e))}function ao(r){return r!=null&&typeof r.then=="function"}function uo(r,e){let{signal:t,...n}=e??{};return ue(s=>{let o=!1,i=()=>{o||(o=!0,s.down([[I,t.reason]]))};if(t?.aborted){i();return}return t?.addEventListener("abort",i,{once:!0}),Promise.resolve(r).then(a=>{o||(o=!0,t?.removeEventListener("abort",i),s.emit(a),s.down([[$]]))},a=>{o||(o=!0,t?.removeEventListener("abort",i),s.down([[I,a]]))}),()=>{o=!0,t?.removeEventListener("abort",i)}},fn(n))}function co(r,e){let{signal:t,...n}=e??{};return ue(s=>{let o=new AbortController,i=()=>o.abort(t?.reason);t?.aborted?o.abort(t.reason):t?.addEventListener("abort",i,{once:!0});let a=t??o.signal,d=!1,u=r[Symbol.asyncIterator](),c=()=>{d||a.aborted||Promise.resolve(u.next()).then(p=>{if(!(d||a.aborted)){if(p.done){s.down([[$]]);return}s.emit(p.value),c()}},p=>{!d&&!a.aborted&&s.down([[I,p]])})};return c(),()=>{d=!0,t?.removeEventListener("abort",i),o.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},fn(n))}function lo(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"}function Ae(r,e){if(lo(r))return r;if(ao(r))return uo(r,e);if(r!=null){let t=r;if(typeof t[Symbol.asyncIterator]=="function")return co(r,e);if(typeof t[Symbol.iterator]=="function")return sr(r,e)}return fo(r)}function fo(...r){return sr(r,void 0)}function ir(r,e){let t=new AbortController,n=e?.reason??new Error("cancelled via nodeSignal"),s,o=!1,i=()=>{s?(s(),s=void 0):o=!0};return s=r.subscribe(a=>{if(!t.signal.aborted)for(let d of a){if(d[0]===D&&d[1]===!0){t.abort(n),i();return}if(d[0]===I){t.abort(d[1]),i();return}if(d[0]===$){i();return}}}),o&&(s?.(),s=void 0),{signal:t.signal,dispose:()=>{s&&(s(),s=void 0)}}}function de(r){return r.subscribe(()=>{})}var ar=_e(()=>{"use strict";be();te()});var Pe=_e(()=>{"use strict";ar()});function Mt(r,e){if(e!=null&&e.length>0)return new Set(e);switch(r){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;case"spec":return new Set(["type","deps","meta","value"]);default:return new Set(["type","deps"])}}function vo(r){return r._describeKind!=null?r._describeKind:r._deps.length>0?"derived":r._fn!=null?"producer":"state"}function Ke(r){let e=new WeakSet,t={};for(let[n,s]of dr(r))t[n]=pn(s,e);return t}function pn(r,e){if(r==null)return r;let t=typeof r;if(t==="boolean"||t==="number"||t==="string")return r;if(t==="function")return"<function>";if(Array.isArray(r))return e.has(r)?"<cycle>":(e.add(r),r.map(n=>pn(n,e)));if(t==="object"){let n=r;if(e.has(n))return"<cycle>";e.add(n);try{if(typeof n.subscribe=="function"&&"cache"in n)return"<Node>"}catch{return"<unserializable>"}let s={};for(let[o,i]of dr(n))s[o]=pn(i,e);return s}return"<unserializable>"}function dr(r){let e=[],t;try{t=Object.keys(r)}catch{return e}for(let n of t)try{e.push([n,r[n]])}catch{e.push([n,"<unserializable>"])}return e}function We(r,e){let t={factory:r};return e!==void 0&&(t.factoryArgs=e),t}function To(r){let e={};for(let[t,n]of Object.entries(r.meta))try{e[t]=n.cache}catch{}return e}function hn(r,e,t){let n=e==null,s=!n&&e!=null?[...e].filter(c=>c.startsWith("meta.")).map(c=>c.slice(5)):null,o=n||e.has("meta")||s!=null&&s.length>0,i="state",a=[];r instanceof oe&&(i=vo(r),a=r._deps.map(c=>c.node.name??""));let d={type:i,deps:a};(n||e.has("status"))&&(d.status=r.status);let u=r instanceof oe?r._guard:void 0;if(o){let c={...To(r)};if(u!=null&&c.access===void 0&&(c.access=sn(u)),s!=null&&s.length>0&&!e.has("meta")){let p={};for(let l of s)l in c&&(p[l]=c[l]);d.meta=p}else d.meta=c}if(r.name!=null&&(d.name=r.name),(n||e.has("value"))&&(!t||i==="state")){r.status==="sentinel"&&(d.sentinel=!0);try{d.value=r.cache}catch{}}if((n||e.has("v"))&&r.v!=null){let c={id:r.v.id,version:r.v.version};"cid"in r.v&&(c.cid=r.v.cid,c.prev=r.v.prev),d.v=c}return(n||e.has("guard"))&&u!=null&&(d.guard=sn(u)),(n||e.has("lastMutation"))&&r.lastMutation!=null&&(d.lastMutation=r.lastMutation),d}var rt=_e(()=>{"use strict";tt();Ie()});var Ft,fr=_e(()=>{"use strict";Ft=class{_timer;_gen=0;start(e,t){this.cancel(),this._gen+=1;let n=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,n===this._gen&&t()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var bt,pr=_e(()=>{"use strict";bt=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<=0)throw new Error(`RingBuffer capacity must be a positive integer (got ${e})`);this.buf=new Array(e)}buf;head=0;_size=0;get size(){return this._size}get maxSize(){return this.capacity}push(e){let t=(this.head+this._size)%this.capacity;this.buf[t]=e,this._size<this.capacity?this._size++:this.head=(this.head+1)%this.capacity}shift(){if(this._size===0)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this._size--,e}at(e){if(this._size===0)return;let t=e<0?this._size+e:e;if(!(t<0||t>=this._size))return this.buf[(this.head+t)%this.capacity]}toArray(){let e=new Array(this._size);for(let t=0;t<this._size;t++)e[t]=this.buf[(this.head+t)%this.capacity];return e}clear(){for(let e=0;e<this._size;e++)this.buf[(this.head+e)%this.capacity]=void 0;this.head=0,this._size=0}}});function ze(r,e,t){return{[r]:!0,[`${r}_type`]:e,...t??{}}}var yt=_e(()=>{"use strict"});var _s={};Wr(_s,{DEFAULT_DECAY_RATE:()=>it,DEFAULT_EXECUTE_PROMPT:()=>bn,DEFAULT_QUEUE_CONFIGS:()=>Pt,DEFAULT_SEVERITY_WEIGHTS:()=>st,DEFAULT_TRIAGE_PROMPT:()=>gn,DEFAULT_VERIFY_PROMPT:()=>yn,HarnessGraph:()=>Jt,QUEUE_NAMES:()=>Ne,actuatorExecutor:()=>ur,affectedTaskFilter:()=>Ro,autoSolidify:()=>yo,beforeAfterCompare:()=>ko,codeChangeBridge:()=>Oo,createIntakeBridge:()=>xo,defaultErrorClassifier:()=>Lt,defaultLlmExecutor:()=>jr,defaultLlmVerifier:()=>zr,dispatchActuator:()=>bo,effectivenessTracker:()=>Co,evalIntakeBridge:()=>No,evalSource:()=>Eo,evalVerifier:()=>Or,harnessEvalPair:()=>as,harnessLoop:()=>ms,harnessProfile:()=>bs,harnessTrace:()=>vs,notifyEffect:()=>So,priorityScore:()=>ps,refineExecutor:()=>Cn,resolvePromptFn:()=>gt,strategyKey:()=>at,strategyModel:()=>Vn});module.exports=Yr(_s);be();te();Pe();function po(r,e){return{outcome:"success",detail:`actuator applied ${e.intervention} for ${go(e.summary)}`,artifact:r}}function ho(r,e){let t=r instanceof Error?r.message:String(r);return{outcome:"failure",detail:`actuator threw on ${e.intervention}: ${t}`}}function mo(r){return`actuator skipped ${r.intervention} (shouldApply returned false)`}function go(r,e=80){return r.length<=e?r:`${r.slice(0,e-1)}\u2026`}function ur(r){let e=r.name??"actuator-executor",t=r.toOutput??po,n=r.onError??ho,s=r.skipDetail??mo;return o=>{let i=o.payload.item;return r.shouldApply&&!r.shouldApply(i)?{...o.payload,execution:{item:i,outcome:"failure",detail:s(i)}}:ue(a=>{let d=new AbortController,u=!1,c=null,p=h=>{u||(u=!0,a.down([[D,{...o.payload,execution:{item:i,...h}}],[$]]),c?.(),c=null)},l;try{let h=r.apply(i,{signal:d.signal});l=Ae(h,{signal:d.signal})}catch(h){return p(n(h,i)),()=>{d.abort()}}return c=l.subscribe(h=>{for(let f of h){if(u)return;if(f[0]===D){p(t(f[1],i));return}if(f[0]===I){p(n(f[1],i));return}if(f[0]===$){p(n(new Error("actuator inner completed without emitting DATA"),i));return}}}),u&&c&&(c(),c=null),()=>{d.abort(),c?.(),c=null}},{name:`${e}/inner`})}}function bo(r){let e=r.name??"dispatch-actuator",t=r.default??null,n=t!=null;return ur({apply:(s,o)=>{let i=Object.hasOwn(r.routes,s.intervention)?r.routes[s.intervention]:t;if(!i)throw new Error(`dispatchActuator: no route for intervention '${s.intervention}'`);return i(s,o)},shouldApply:s=>Object.hasOwn(r.routes,s.intervention)||n,skipDetail:s=>`no route for intervention '${s.intervention}'`,name:e})}be();te();function yo(r){let e=r.name??"auto-solidify",t=r.extract??(s=>s.execution.artifact??null),n=r.predicate??(()=>!0);return ue(s=>{let o=null,i=!1,a=()=>{i||(i=!0,o?.(),o=null)},d=u=>{i||(s.down([[I,u]]),a())};return o=r.verifyResults.subscribe(u=>{if(!i)for(let c of u){if(i)return;if(c[0]!==D){if(c[0]===$){s.down([[$]]),a();return}continue}let p=c[1];if(p==null||!p.verified)continue;let l;try{l=n(p)}catch(f){d(f);return}if(!l)continue;let h;try{h=t(p)}catch(f){d(f);return}if(h!=null){try{r.write(h,p)}catch(f){d(f);return}s.down([[D,h]])}}}),i&&o&&(o(),o=null),()=>{a()}},{name:e})}te();be();rt();Ie();te();Pe();function It(r){return{describeKind:"derived",...r}}function _o(r){return{describeKind:"derived",partial:!0,...r}}function Gt(r,e,t){return ee([r],(n,s)=>{let o=n[0];if(o==null||o.length===0){s.down([[W]]);return}let i=!1;for(let a of o)e(a)&&(s.emit(a),i=!0);i||s.down([[W]])},{...It(t),meta:{...We("filter"),...t?.meta??{}}})}function mn(r,e,t){return ee([r,e],(n,s,o)=>{let i=n[0],a=n[1],d=a!=null&&a.length>0?a.at(-1):o.prevData[1];if(i!=null&&i.length>0){if(!(a!=null&&a.length>0)&&o.prevData[1]===void 0){s.down([[W]]);return}for(let u of i)s.emit([u,d])}else s.down([[W]])},{..._o(t),meta:{...We("withLatestFrom"),...t?.meta??{}}})}function cr(...r){return r.length===0?ue(e=>{e.down([[$]])},{...It(),meta:{...We("merge")}}):ue(e=>{let t=r.length,n=0,s=[];for(let o of r){let i=o.subscribe(a=>{for(let d of a)d[0]===D?e.emit(d[1]):d[0]===$?(n+=1,n>=t&&e.down([[$]])):d[0]===I&&e.down([d])});s.push(i)}return()=>{for(let o of s)o()}},{...It(),meta:{...We("merge")}})}function wo(r,e,t){let n,s=!1,o=()=>{s||(s=!0,t())};return n=r.subscribe(i=>{let a=!1,d=!1;for(let u of i)u[0]!==$e&&(u[0]===D?e.emit(u[1]):u[0]===$?a=!0:u[0]===I?(d=!0,e.down([u])):(u[0]===Q||u[0]===W)&&e.down([u]));d?(n?.(),n=void 0,o()):a&&o()}),()=>{n?.(),n=void 0}}function ot(r,e,t){let n,s=!1;function o(){n?.(),n=void 0}return ee([r],(i,a,d)=>{if(d.terminalDeps[0]!=null&&d.terminalDeps[0]!==!0){o();return}if(d.terminalDeps[0]===!0){s=!0,n||a.down([[$]]);return}let u=i[0];if(!(u==null||u.length===0))return o(),n=wo(Ae(e(u[u.length-1])),a,()=>{o(),s&&a.down([[$]])}),{deactivate:()=>{o(),s=!1}}},{...It(t),completeWhenDepsComplete:!1,meta:{...We("switchMap"),...t?.meta??{}}})}Pe();function xo(r,e,t,n){return he([r],([s])=>{if(s==null)return;let o=t(s);for(let i of o)e.publish(i)},{name:n?.name??"intake-bridge"})}function No(r,e,t){let n=t?.defaultSeverity??"medium";return he([r],([s])=>{if(s==null)return;let o=Array.isArray(s)?s:[s];for(let i of o)for(let a of i.tasks)if(!(a.valid&&a.judge_scores?.every(d=>d.pass))){if(!a.valid&&(!a.judge_scores||a.judge_scores.length===0)){e.publish({source:"eval",summary:`Task ${a.task_id} invalid (model: ${i.model})`,evidence:`Run ${i.run_id}: task produced invalid output`,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:n});continue}if(a.judge_scores)for(let d of a.judge_scores)d.pass||e.publish({source:"eval",summary:`${a.task_id}: ${d.claim} (model: ${i.model})`,evidence:d.reasoning,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:n})}},{name:t?.name??"eval-intake-bridge"})}function Eo(r,e){return ot(r,()=>Ae(e()))}function ko(r,e){return G([r,e],([t,n])=>{let s=t,o=n,i=new Map(s.tasks.map(l=>[l.task_id,l])),a=new Map(o.tasks.map(l=>[l.task_id,l])),d=new Set([...i.keys(),...a.keys()]),u=[],c=[],p=[];for(let l of d){let h=i.get(l),f=a.get(l),b=h?.valid??!1,m=f?.valid??!1,T=h?.judge_scores?h.judge_scores.filter(_=>_.pass).length:void 0,v=f?.judge_scores?f.judge_scores.filter(_=>_.pass).length:void 0,g=T!==void 0&&v!==void 0?v-T:void 0;u.push({taskId:l,before:b,after:m,scoreDiff:g}),b&&!m&&c.push(l),!b&&m&&p.push(l)}return{newFailures:c,resolved:p,taskDeltas:u,overallImproved:p.length>c.length}},{name:"eval-delta"})}function Ro(r,e){let t=e==null?null:Array.isArray(e)?V(e):e,n=[r];return t&&n.push(t),G(n,s=>{let o=s[0],i=t?new Set(s[1]):null,a=new Set;for(let d of o)for(let u of d.affectsEvalTasks??[])(i==null||i.has(u))&&a.add(u);return[...a].sort()},{name:"affected-task-filter"})}function Oo(r,e,t,n){let s=n?.defaultSeverity??"high";function o(a){let d=[];for(let u of a.lintErrors??[])d.push({source:"code-change",summary:`Lint: ${u.rule} in ${u.file}:${u.line}`,evidence:u.message,affectsAreas:[u.file],severity:s});for(let u of a.testFailures??[])d.push({source:"test",summary:`Test failure: ${u.testId}`,evidence:u.message,affectsAreas:[u.file],affectsEvalTasks:[u.testId],severity:s});return d}let i=t??o;return he([r],([a])=>{if(a!=null)for(let d of i(a))e.publish(d)},{name:n?.name??"code-change-bridge"})}function So(r,e,t){return he([r.latest],([n])=>{n!=null&&e(n)},{name:t?.name??"notify-effect"})}var Ne=["auto-fix","needs-decision","investigation","backlog"],Pt={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},st={critical:100,high:70,medium:40,low:10},it=Math.LN2/(168*3600);function at(r,e){return`${r}\u2192${e}`}var Ao=/\b(parse|json|config|validation|syntax)\b/i,Lt=r=>Ao.test(r.detail)?"self-correctable":"structural",gn=`You are a triage classifier for a reactive collaboration harness.
1
+ "use strict";var on=Object.defineProperty;var oo=Object.getOwnPropertyDescriptor;var so=Object.getOwnPropertyNames;var io=Object.prototype.hasOwnProperty;var W=(r,e)=>()=>(r&&(e=r(r=0)),e);var ao=(r,e)=>{for(var t in e)on(r,t,{get:e[t],enumerable:!0})},uo=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of so(e))!io.call(r,s)&&s!==t&&on(r,s,{get:()=>e[s],enumerable:!(n=oo(e,s))||n.enumerable});return r};var co=r=>uo(on({},"__esModule",{value:!0}),r);var Ve,D,X,J,ke,Ce,je,he,$,I,qe,Ot,Qn,At,Xn,Zn,St,sn,an,un,Ct,ye=W(()=>{"use strict";Ve=Symbol.for("graphrefly/START"),D=Symbol.for("graphrefly/DATA"),X=Symbol.for("graphrefly/DIRTY"),J=Symbol.for("graphrefly/RESOLVED"),ke=Symbol.for("graphrefly/INVALIDATE"),Ce=Symbol.for("graphrefly/PAUSE"),je=Symbol.for("graphrefly/RESUME"),he=Symbol.for("graphrefly/TEARDOWN"),$=Symbol.for("graphrefly/COMPLETE"),I=Symbol.for("graphrefly/ERROR"),qe=Object.freeze([X]),Ot=Object.freeze([J]),Qn=Object.freeze([ke]),At=Object.freeze([Ve]),Xn=Object.freeze([$]),Zn=Object.freeze([he]),St=Object.freeze([qe]),sn=Object.freeze([Ot]),an=Object.freeze([Qn]),un=Object.freeze([Xn]),Ct=Object.freeze([Zn])});function tr(r,e){let t=new TextEncoder().encode(r.name);if(t.length===0||t.length>255)throw new Error(`encodeEnvelope: codec name "${r.name}" encodes to ${t.length} bytes (must be 1\u2013255)`);let n=r.version;if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`encodeEnvelope: codec.version ${n} out of u16 range (expected integer 0\u201365535)`);let s=2+t.length+2+e.length;if(s>4294967295)throw new Error(`encodeEnvelope: total envelope size ${s} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let o=new Uint8Array(s),i=0;return o[i++]=dn,o[i++]=t.length,o.set(t,i),i+=t.length,o[i++]=n>>>8&255,o[i++]=n&255,o.set(e,i),o}function nr(r,e){if(r.length<er)throw new Error(`decodeEnvelope: bytes too short (${r.length} < ${er})`);let t=0,n=r[t++];if(n!==dn)throw new Error(`decodeEnvelope: unsupported envelope version ${n} (expected ${dn})`);let s=r[t++];if(s===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(t+s+2>r.length)throw new Error(`decodeEnvelope: envelope truncated (need ${t+s+2} bytes, have ${r.length})`);let o=new TextDecoder().decode(r.subarray(t,t+s));t+=s;let i=(r[t]<<8|r[t+1])>>>0;t+=2;let a=r.subarray(t),d=e.lookupCodec(o);if(d==null)throw new Error(`decodeEnvelope: codec "${o}" not registered (envelope codec_v=${i})`);return{codec:d,codecVersion:i,payload:a}}function rr(r){r.registerCodec(lo)}var lo,dn,er,cn=W(()=>{"use strict";lo={name:"json",version:1,contentType:"application/json",encode(r){let e=JSON.stringify(r);return new TextEncoder().encode(e)},decode(r,e){let t=new TextDecoder().decode(r);return JSON.parse(t)}},dn=1,er=4});function Dt(r){if(r==null)return Ze;let{type:e,id:t,...n}=r;return{type:e??"system",id:t??"",...n}}var Ze,Mt=W(()=>{"use strict";Ze={type:"system",id:""}});function gt(){return et>0||ht}function or(){return et>0}function nt(r){et>0?mt.push(r):r()}function U(r){et+=1;let e=!1;try{r()}catch(t){throw e=!0,t}finally{if(et-=1,et===0)if(e){if(!ht){let t=mt.splice(0);for(let n of t)try{n()}catch{}Ue.length=0,Ke.length=0,tt.length=0}}else fo()}}function fo(){let r=!ht;r&&(ht=!0);let e=[],t=0;try{for(;Ue.length>0||Ke.length>0||tt.length>0||r&&mt.length>0;){if(r&&mt.length>0){let o=mt.splice(0);for(let i of o)try{i()}catch(a){e.push(a)}continue}if(t+=1,t>1e3)throw Ue.length=0,Ke.length=0,tt.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let s=(Ue.length>0?Ue:Ke.length>0?Ke:tt).splice(0);for(let o of s)try{o()}catch(i){e.push(i)}}}finally{r&&(ht=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function bt(r,e,t){if(e.length===0)return;if(e.length===1){let u=t(e[0][0]);if(u<3||!gt()){r(e);return}(u>=5?tt:u===4?Ke:Ue).push(()=>r(e));return}let n=e.length,s=n,o=n,i=n,a=0;for(;a<n&&t(e[a][0])<3;)a++;for(s=a;a<n&&t(e[a][0])===3;)a++;for(o=a;a<n&&t(e[a][0])===4;)a++;i=a;let d=gt();if(s>0){let u=e.slice(0,s);r(u)}if(o>s){let u=e.slice(s,o);d?Ue.push(()=>r(u)):r(u)}if(i>o){let u=e.slice(o,i);d?Ke.push(()=>r(u)):r(u)}if(n>i){let u=e.slice(i,n);d?tt.push(()=>r(u)):r(u)}}var et,ht,Ue,Ke,tt,mt,De=W(()=>{"use strict";et=0,ht=!1,Ue=[],Ke=[],tt=[],mt=[]});function K(){return Math.trunc(performance.now()*1e6)}function Me(){return Date.now()*1e6}var Re=W(()=>{"use strict"});function sr(r){r.registerMessageType(Ve,{tier:0,wireCrossing:!1}),r.registerMessageType(X,{tier:1,wireCrossing:!1}),r.registerMessageType(ke,{tier:1,wireCrossing:!1,metaPassthrough:!1}),r.registerMessageType(Ce,{tier:2,wireCrossing:!1}),r.registerMessageType(je,{tier:2,wireCrossing:!1}),r.registerMessageType(D,{tier:3,wireCrossing:!0}),r.registerMessageType(J,{tier:3,wireCrossing:!0}),r.registerMessageType($,{tier:4,wireCrossing:!0,metaPassthrough:!1}),r.registerMessageType(I,{tier:4,wireCrossing:!0,metaPassthrough:!1}),r.registerMessageType(he,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var It,ir=W(()=>{"use strict";ye();It=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_rigorRecorder;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=t=>{let n=this._messageTypes.get(t);return n!=null?n.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}get rigorRecorder(){return this._rigorRecorder}set rigorRecorder(e){this._rigorRecorder=e}registerMessageType(e,t){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:t.tier,wireCrossing:t.wireCrossing??t.tier>=3,metaPassthrough:t.metaPassthrough??!0}),this}messageTier(e){let t=this._messageTypes.get(e);return t!=null?t.tier:1}isWireCrossing(e){let t=this._messageTypes.get(e);return t!=null?t.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let t=this._messageTypes.get(e);return t!=null?t.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function ar(r){return Array.isArray(r)?[...r]:[r]}function po(r,e){return r.has(e)||r.has("*")}function ur(r){let e=[];return r((s,o)=>{e.push({kind:"allow",actions:new Set(ar(s)),where:o?.where??(()=>!0)})},(s,o)=>{e.push({kind:"deny",actions:new Set(ar(s)),where:o?.where??(()=>!0)})}),(s,o)=>{let i=!1,a=!1;for(let d of e)po(d.actions,o)&&d.where(s)&&(d.kind==="deny"?i=!0:a=!0);return i?!1:a}}function ln(r){let e=ho.filter(t=>r({type:t,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(t=>t==="human"||t==="llm"||t==="system")?"both":e.length===1?e[0]:e.join("+")}var Oe,ho,rt=W(()=>{"use strict";Oe=class extends Error{actor;action;nodeName;constructor(e,t){super(t??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}};ho=["human","llm","wallet","system"]});function fn(r){if(r===void 0)return null;if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError(`Cannot hash non-finite number: ${r}`);if(Number.isInteger(r)&&!Number.isSafeInteger(r))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${r}. Cross-language cid parity is not guaranteed for unsafe integers.`);return r}if(typeof r=="string"||typeof r=="boolean"||r===null)return r;if(Array.isArray(r))return r.map(fn);if(typeof r=="object"&&r!==null){let e={};for(let t of Object.keys(r).sort())e[t]=fn(r[t]);return e}return null}function bo(r){let e=go.encode(r),t=e.length,n=t*8,s=t+9+63&-64,o=new Uint8Array(s);o.set(e),o[t]=128;let i=new DataView(o.buffer);i.setUint32(s-4,n>>>0,!1),i.setUint32(s-8,Math.floor(n/4294967296)>>>0,!1);let a=1779033703,d=3144134277,u=1013904242,c=2773480762,p=1359893119,l=2600822924,h=528734635,f=1541459225,b=new Uint32Array(64),m=(v,g)=>v>>>g|v<<32-g;for(let v=0;v<s;v+=64){for(let E=0;E<16;E++)b[E]=i.getUint32(v+E*4,!1);for(let E=16;E<64;E++){let P=b[E-15],H=b[E-2],F=m(P,7)^m(P,18)^P>>>3,ve=m(H,17)^m(H,19)^H>>>10;b[E]=b[E-16]+F+b[E-7]+ve>>>0}let g=a,_=d,w=u,N=c,y=p,x=l,k=h,A=f;for(let E=0;E<64;E++){let P=m(y,6)^m(y,11)^m(y,25),H=y&x^~y&k,F=A+P+H+mo[E]+b[E]>>>0,ve=m(g,2)^m(g,13)^m(g,22),Te=g&_^g&w^_&w,Ee=ve+Te>>>0;A=k,k=x,x=y,y=N+F>>>0,N=w,w=_,_=g,g=F+Ee>>>0}a=a+g>>>0,d=d+_>>>0,u=u+w>>>0,c=c+N>>>0,p=p+y>>>0,l=l+x>>>0,h=h+k>>>0,f=f+A>>>0}let T=v=>v.toString(16).padStart(8,"0");return T(a)+T(d)+T(u)+T(c)+T(p)+T(l)+T(h)+T(f)}function pn(r){let e=fn(r??null),t=JSON.stringify(e);return bo(t).slice(0,16)}function yo(){let r=globalThis.crypto;if(r?.randomUUID)return r.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),t=e()+e()+e()+e();return`${t.slice(0,8)}-${t.slice(8,12)}-4${t.slice(13,16)}-${(parseInt(t.slice(16,17),16)&3|8).toString(16)}${t.slice(17,20)}-${t.slice(20,32)}`}function hn(r,e,t){let n=t?.id??yo();if(r===0)return{id:n,version:0};let o=(t?.hash??pn)(e);return{id:n,version:0,cid:o,prev:null}}function dr(r,e,t){r.version+=1,"cid"in r&&(r.prev=r.cid,r.cid=t(e))}var mo,go,cr=W(()=>{"use strict";mo=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),go=new TextEncoder});function pr(r){return{node:r,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function mn(r){r.prevData=void 0,r.dirty=!1,r.involvedThisWave=!1,r.dataBatch.length=0,r.terminal=void 0}function Gt(r){return r.length===0?r:typeof r[0]=="symbol"?[r]:r}function te(r,e,t){let n=hr(r)?r:[],s=typeof r=="function"?r:typeof e=="function"?e:void 0,o={};return hr(r)?o=(gn(e)?e:t)??{}:gn(r)?o=r:o=(gn(e)?e:t)??{},new ie(n,s,o)}var lr,fr,vo,To,ot,ie,hr,gn,Ie=W(()=>{"use strict";cn();Mt();De();Re();ir();rt();ye();cr();lr=()=>{},fr=100;vo=(r,e,t,n)=>{t.direction==="down-in"&&r._onDepMessage(t.depIndex,e)},To=(r,e,t,n)=>{let s=r;if(s._status==="completed"||s._status==="errored")return;let o=s._cached,i=o===void 0?[At]:[At,[D,o]];s._status==="dirty"&&i.push(qe),bt(e,i,s._config.tierOf)},ot=new It({onMessage:vo,onSubscribe:To});sr(ot);rr(ot);ie=class r{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,t,n){this._config=n.config??ot,this._config.onMessage,this._optsName=n.name,this._describeKind=n.describeKind,this._equals=n.equals??Object.is,this._resubscribable=n.resubscribable??!1,this._resetOnTeardown=n.resetOnTeardown??!1,this._autoComplete=n.completeWhenDepsComplete??!0,this._autoError=n.errorWhenDepsError??!0,this._pausable=n.pausable??!0,this._guard=n.guard,this._fn=t,this._partial=n.partial??!1,this._cached=n.initial!==void 0?n.initial:void 0,this._status=e.length===0&&t==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=n.versioningHash??this._config.defaultHashFn??pn;let s=n.versioning??this._config.defaultVersioning;this._versioningLevel=s,this._versioning=s!=null?hn(s,this._cached===void 0?void 0:this._cached,{id:n.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(pr);let o={};for(let[a,d]of Object.entries(n.meta??{})){let u={initial:d,name:`${n.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};n.guard!=null&&(u.guard=n.guard),o[a]=new r([],void 0,u)}Object.freeze(o),this.meta=o,this._hasMeta=Object.keys(o).length>0;let i=this;this._actions={emit(a){i._emit([[D,a]])},down(a){i._emit(Gt(a))},up(a){i._emitUp(Gt(a))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,t){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let n=this._versioningLevel;if(n!=null&&e<=n)return;let s=t?.hash??this._hashFn;s!==this._hashFn&&(this._hashFn=s);let o=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??t?.id,d=i?.version??0,u=hn(e,o,{id:a,hash:s});u.version=d,this._versioning=u,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let t=Dt(e);if(this._guard!=null&&!this._guard(t,"observe"))return!1;if(this._extraGuards!=null){for(let n of this._extraGuards)if(!n(t,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let t=this._guard!=null||this._extraGuards!=null,n=e?.actor!=null;if(!t&&!n)return;let s=Dt(e?.actor),o=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(s,o))throw new Oe({actor:s,action:o,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(s,o))throw new Oe({actor:s,action:o,nodeName:this.name})}this._lastMutation={actor:s,timestamp_ns:Me()}}down(e,t){let n=Gt(e);n.length!==0&&(this._checkGuard(t),this._emit(n))}emit(e,t){this._checkGuard(t),this._emit([[D,e]])}up(e,t){if(this._deps.length===0)return;let n=Gt(e);if(n.length===0)return;this._checkGuard(t);let s=t??{internal:!0};this._validateUpTiers(n);for(let o of this._deps)o.node.up?.(n,s)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let t of this._deps)t.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let t=this._config.tierOf;for(let n of e){let s=t(n[0]);if(s===3||s===4)throw new Error(`Node "${this.name}": tier-${s} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,t){if(t!=null&&this._guard!=null){let d=Dt(t);if(!this._guard(d,"observe"))throw new Oe({actor:d,action:"observe",nodeName:this.name})}let s=this._isTerminal&&this._resubscribable;if(s){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let d of this._deps)mn(d);if(this._partial===!1){for(let d of this._deps)if(d.prevData!==void 0||d.dataBatch.length!==0||d.terminal!==void 0||d.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let o;try{o=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:s},this._actions)}catch(d){throw this._sinkCount-=1,d}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(d){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof o=="function")try{o()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!0,this._sinkCount-=1,this._removeSink(e),typeof o=="function"&&o(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[t]=this._sinks;this._sinks=t}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,t=0;try{for(let n=0;n<e;n++){let s=n,o=this._deps[n];o.unsub=lr,o.unsub=o.node.subscribe(i=>{if(o.unsub===null)return;let a=this._config.tierOf,d=!1;for(let u of i)a(u[0])>=3&&(d=!0),this._config.onMessage(this,u,{direction:"down-in",depIndex:s},this._actions);d&&this._maybeRunFnOnSettlement()}),t++}}catch(n){this._deps[t].unsub=null;for(let s=0;s<t;s++){let o=this._deps[s];if(o.unsub!=null){let i=o.unsub;o.unsub=null;try{i()}catch{}mn(o)}}throw this._dirtyDepCount=0,n}}_addDep(e){for(let s=0;s<this._deps.length;s++)if(this._deps[s].node===e)return s;let t=this._deps.length,n=pr(e);if(this._deps.push(n),this._sinks==null)return t;n.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(St),n.unsub=lr;try{n.unsub=e.subscribe(s=>{if(n.unsub===null)return;let o=this._config.tierOf,i=!1;for(let a of s)o(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:t},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(s){throw n.unsub=null,this._deps.pop(),this._dirtyDepCount--,s}return t}_deactivate(e=!1){let t=this._cleanup;if(this._cleanup=void 0,typeof t=="function")try{t()}catch(n){this._emit([[I,this._wrapFnError("cleanup threw",n)]])}else if(t!=null&&typeof t=="object"){let n=t.deactivate;if(typeof n=="function")try{n()}catch(s){this._emit([[I,this._wrapFnError("cleanup.deactivate threw",s)]])}}for(let n of this._deps){if(n.unsub!=null){let s=n.unsub;n.unsub=null;try{s()}catch{}}mn(n)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,t){let n=this._deps[e],s=t[0];if(this._inspectorHooks!=null){let o={kind:"dep_message",depIndex:e,message:t};for(let i of this._inspectorHooks)i(o)}if(s!==Ve){if(s===X){this._depDirtied(n);return}if(s===ke){if(this._depInvalidated(n),this._cached===void 0)return;this._emit(an);return}if(s===Ce||s===je){this._emit([t]);return}if(s===he){this._emit(Ct);return}if(s===D)this._depSettledAsData(n,t[1]);else if(s===J)this._depSettledAsResolved(n);else if(s===$)this._depSettledAsTerminal(n,!0);else if(s===I)this._depSettledAsTerminal(n,t[1]);else{this._emit([t]);return}if(!this._fn){(s===D||s===J)&&this._emit([t]),(s===$||s===I)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(St))}_depSettledAsData(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(t),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=t,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let t=this._deps[e];if(t.dataBatch.length===0&&t.prevData===void 0&&t.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(sn),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(t=>t.terminal!==void 0&&t.terminal!==!0);if(e!=null){this._autoError&&this._emit([[I,e.terminal]]);return}this._autoComplete&&this._deps.every(t=>t.terminal!==void 0)&&this._emit(un)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(i){this._emit([[I,this._wrapFnError("cleanup threw",i)]]);return}}else if(e!=null&&typeof e=="object"){let i=e.beforeRun;if(typeof i=="function"){e.beforeRun=void 0;try{i()}catch(a){this._emit([[I,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let t=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),n=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=t[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let s=this._deps.map(i=>i.terminal),o={prevData:n,terminalDeps:s,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:t,prevData:n};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(t,this._actions,o);if(typeof i=="function")this._cleanup=i;else if(i!=null&&typeof i=="object"){let a=i;(typeof a.beforeRun=="function"||typeof a.deactivate=="function"||typeof a.invalidate=="function")&&(this._cleanup=i)}}catch(i){this._emit([[I,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>fr?(this._rerunDepth=0,this._emit([[I,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${fr} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,t){let n=t instanceof Error?t.message:String(t);return new Error(`Node "${this.name}": ${e}: ${n}`,{cause:t})}_frameBatch(e){let t=this._config.tierOf;if(e.length===1)return t(e[0][0])===3&&this._status!=="dirty"?[qe,e[0]]:e;let n=!0,s=!1,o=!1,i=-1;for(let d of e){let u=t(d[0]);u<i&&(n=!1),u===3&&(s=!0),d[0]===X&&(o=!0),i=u}let a=e;if(!n){let d=e.map((u,c)=>({m:u,i:c,tier:t(u[0])}));d.sort((u,c)=>u.tier-c.tier||u.i-c.i),a=d.map(u=>u.m)}if(s&&!o&&this._status!=="dirty"){let d=0;for(;d<a.length&&t(a[d][0])===0;)d++;return d===0?[qe,...a]:[...a.slice(0,d),qe,...a.slice(d)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let d=e[a];if(d[0]===I&&d[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let t=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(d=>d[0]===he||d[0]===ke);if(a.length===0)return;t=a}t=this._frameBatch(t);let s=null;for(let a=0;a<t.length;a++){let d=t[a],u=d[0];if(u!==Ce&&u!==je){s?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===Ce?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let p=d[1];if(u===Ce)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(p),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(p))c=!1;else if(this._pauseLocks.delete(p),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let l=this._pauseBuffer;this._pauseBuffer=[],this._emit(l)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?s?.push(d):s==null&&(s=t.slice(0,a))}if(s!=null){if(s.length===0)return;t=s}if(this._hasMeta&&t.some(a=>a[0]===he))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Ct)}catch{}let{finalMessages:o,equalsError:i}=this._updateState(t);if(o.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:o})}catch{}}if(o.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,d=[];for(let u of o)a(u[0])===3?this._pauseBuffer.push(u):d.push(u);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(o);i!=null&&this._emit([[I,i]])}_updateState(e){let t=this._config.tierOf,n,s,o=-1,i=0;for(let c of e)t(c[0])===3&&i++;let a=i<=1,d=-1;if(this._versioning!=null&&i>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===D){d=c;break}}for(let c=0;c<e.length;c++){let p=e[c],l=p[0];if(l===D){if(p.length>=2){let h=!1;if(a&&this._cached!==void 0)try{h=this._equals(this._cached,p[1])}catch(f){s=this._wrapFnError("equals threw",f),o=c;break}if(h){n==null&&(n=e.slice(0,c)),n.push(Ot),this._status="resolved";continue}this._cached=p[1],this._versioning!=null&&(d<0||c===d)&&dr(this._versioning,p[1],this._hashFn)}this._status="settled",n?.push(p)}else if(n?.push(p),l===X)this._status="dirty";else if(l===J)this._status="resolved";else if(l===$){this._status="completed";{let h=this._config.rigorRecorder;if(h!=null)try{h.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(l===I){this._status="errored";{let h=this._config.rigorRecorder;if(h!=null)try{h.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(l===ke){if(this._cached!==void 0){let f=this._config.rigorRecorder;if(f!=null)try{f.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let h=this._cleanup;if(typeof h=="function"){this._cleanup=void 0;try{h()}catch{}}else if(h!=null&&typeof h=="object"){let f=h.invalidate;if(typeof f=="function")try{f()}catch{}}}else l===he&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=o>=0?n??e.slice(0,o):n??e;return s!=null?{finalMessages:u,equalsError:s}:{finalMessages:u}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let t=[...this._sinks];for(let n of t)n(e)};_dispatchOrAccumulate(e){if(or()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],nt(()=>this._flushBatchPending()));for(let t of e)this._batchPendingMessages.push(t);return}bt(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let t=this._frameBatch(e);bt(this._deliverToSinks,t,this._config.tierOf)}},hr=r=>Array.isArray(r),gn=r=>typeof r=="object"&&r!=null&&!Array.isArray(r)});function V(r,e){return te([],{...e,initial:r})}function de(r,e){return te((n,s,o)=>r(s,o)??void 0,{describeKind:"producer",...e})}function G(r,e,t){return te(r,(s,o,i)=>{let a=s.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);o.emit(e(a,i))},{describeKind:"derived",...t})}function me(r,e,t){return te(r,(s,o,i)=>{let a=s.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);return e(a,o,i)??void 0},{describeKind:"effect",...t})}var ne=W(()=>{"use strict";Ie()});function bn(r){return{describeKind:"producer",...r}}function mr(r,e){return de(t=>{let n=!1;try{for(let s of r){if(n)return;t.emit(s)}n||t.down([[$]])}catch(s){n||t.down([[I,s]])}return()=>{n=!0}},bn(e))}function _o(r){return r!=null&&typeof r.then=="function"}function wo(r,e){let{signal:t,...n}=e??{};return de(s=>{let o=!1,i=()=>{o||(o=!0,s.down([[I,t.reason]]))};if(t?.aborted){i();return}return t?.addEventListener("abort",i,{once:!0}),Promise.resolve(r).then(a=>{o||(o=!0,t?.removeEventListener("abort",i),s.emit(a),s.down([[$]]))},a=>{o||(o=!0,t?.removeEventListener("abort",i),s.down([[I,a]]))}),()=>{o=!0,t?.removeEventListener("abort",i)}},bn(n))}function xo(r,e){let{signal:t,...n}=e??{};return de(s=>{let o=new AbortController,i=()=>o.abort(t?.reason);t?.aborted?o.abort(t.reason):t?.addEventListener("abort",i,{once:!0});let a=t??o.signal,d=!1,u=r[Symbol.asyncIterator](),c=()=>{d||a.aborted||Promise.resolve(u.next()).then(p=>{if(!(d||a.aborted)){if(p.done){s.down([[$]]);return}s.emit(p.value),c()}},p=>{!d&&!a.aborted&&s.down([[I,p]])})};return c(),()=>{d=!0,t?.removeEventListener("abort",i),o.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},bn(n))}function No(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"}function Ae(r,e){if(No(r))return r;if(_o(r))return wo(r,e);if(r!=null){let t=r;if(typeof t[Symbol.asyncIterator]=="function")return xo(r,e);if(typeof t[Symbol.iterator]=="function")return mr(r,e)}return Eo(r)}function Eo(...r){return mr(r,void 0)}function gr(r,e){let t=new AbortController,n=e?.reason??new Error("cancelled via nodeSignal"),s,o=!1,i=()=>{s?(s(),s=void 0):o=!0};return s=r.subscribe(a=>{if(!t.signal.aborted)for(let d of a){if(d[0]===D&&d[1]===!0){t.abort(n),i();return}if(d[0]===I){t.abort(d[1]),i();return}if(d[0]===$){i();return}}}),o&&(s?.(),s=void 0),{signal:t.signal,dispose:()=>{s&&(s(),s=void 0)}}}function ce(r){return r.subscribe(()=>{})}var br=W(()=>{"use strict";ye();ne()});var Pe=W(()=>{"use strict";br()});function Pt(r,e){if(e!=null&&e.length>0)return new Set(e);switch(r){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;case"spec":return new Set(["type","deps","meta","value"]);default:return new Set(["type","deps"])}}function Do(r){return r._describeKind!=null?r._describeKind:r._deps.length>0?"derived":r._fn!=null?"producer":"state"}function We(r){let e=new WeakSet,t={};for(let[n,s]of vr(r))t[n]=yn(s,e);return t}function yn(r,e){if(r==null)return r;let t=typeof r;if(t==="boolean"||t==="number"||t==="string")return r;if(t==="function")return"<function>";if(Array.isArray(r))return e.has(r)?"<cycle>":(e.add(r),r.map(n=>yn(n,e)));if(t==="object"){let n=r;if(e.has(n))return"<cycle>";e.add(n);try{if(typeof n.subscribe=="function"&&"cache"in n)return"<Node>"}catch{return"<unserializable>"}let s={};for(let[o,i]of vr(n))s[o]=yn(i,e);return s}return"<unserializable>"}function vr(r){let e=[],t;try{t=Object.keys(r)}catch{return e}for(let n of t)try{e.push([n,r[n]])}catch{e.push([n,"<unserializable>"])}return e}function Je(r,e){let t={factory:r};return e!==void 0&&(t.factoryArgs=e),t}function Mo(r){let e={};for(let[t,n]of Object.entries(r.meta))try{e[t]=n.cache}catch{}return e}function vn(r,e,t){let n=e==null,s=!n&&e!=null?[...e].filter(c=>c.startsWith("meta.")).map(c=>c.slice(5)):null,o=n||e.has("meta")||s!=null&&s.length>0,i="state",a=[];r instanceof ie&&(i=Do(r),a=r._deps.map(c=>c.node.name??""));let d={type:i,deps:a};(n||e.has("status"))&&(d.status=r.status);let u=r instanceof ie?r._guard:void 0;if(o){let c={...Mo(r)};if(u!=null&&c.access===void 0&&(c.access=ln(u)),s!=null&&s.length>0&&!e.has("meta")){let p={};for(let l of s)l in c&&(p[l]=c[l]);d.meta=p}else d.meta=c}if(r.name!=null&&(d.name=r.name),(n||e.has("value"))&&(!t||i==="state")){r.status==="sentinel"&&(d.sentinel=!0);try{d.value=r.cache}catch{}}if((n||e.has("v"))&&r.v!=null){let c={id:r.v.id,version:r.v.version};"cid"in r.v&&(c.cid=r.v.cid,c.prev=r.v.prev),d.v=c}return(n||e.has("guard"))&&u!=null&&(d.guard=ln(u)),(n||e.has("lastMutation"))&&r.lastMutation!=null&&(d.lastMutation=r.lastMutation),d}var st=W(()=>{"use strict";rt();Ie()});function Lt(r){return{describeKind:"derived",...r}}function Io(r){return{describeKind:"derived",partial:!0,...r}}function Ft(r,e,t){return te([r],(n,s)=>{let o=n[0];if(o==null||o.length===0){s.down([[J]]);return}let i=!1;for(let a of o)e(a)&&(s.emit(a),i=!0);i||s.down([[J]])},{...Lt(t),meta:{...Je("filter"),...t?.meta??{}}})}function Tn(r,e,t){return te([r,e],(n,s,o)=>{let i=n[0],a=n[1],d=a!=null&&a.length>0?a.at(-1):o.prevData[1];if(i!=null&&i.length>0){if(!(a!=null&&a.length>0)&&o.prevData[1]===void 0){s.down([[J]]);return}for(let u of i)s.emit([u,d])}else s.down([[J]])},{...Io(t),meta:{...Je("withLatestFrom"),...t?.meta??{}}})}function Tr(...r){return r.length===0?de(e=>{e.down([[$]])},{...Lt(),meta:{...Je("merge")}}):de(e=>{let t=r.length,n=0,s=[];for(let o of r){let i=o.subscribe(a=>{for(let d of a)d[0]===D?e.emit(d[1]):d[0]===$?(n+=1,n>=t&&e.down([[$]])):d[0]===I&&e.down([d])});s.push(i)}return()=>{for(let o of s)o()}},{...Lt(),meta:{...Je("merge")}})}function Go(r,e,t){let n,s=!1,o=()=>{s||(s=!0,t())};return n=r.subscribe(i=>{let a=!1,d=!1;for(let u of i)u[0]!==Ve&&(u[0]===D?e.emit(u[1]):u[0]===$?a=!0:u[0]===I?(d=!0,e.down([u])):(u[0]===X||u[0]===J)&&e.down([u]));d?(n?.(),n=void 0,o()):a&&o()}),()=>{n?.(),n=void 0}}function it(r,e,t){let n,s=!1;function o(){n?.(),n=void 0}return te([r],(i,a,d)=>{if(d.terminalDeps[0]!=null&&d.terminalDeps[0]!==!0){o();return}if(d.terminalDeps[0]===!0){s=!0,n||a.down([[$]]);return}let u=i[0];if(!(u==null||u.length===0))return o(),n=Go(Ae(e(u[u.length-1])),a,()=>{o(),s&&a.down([[$]])}),{deactivate:()=>{o(),s=!1}}},{...Lt(t),completeWhenDepsComplete:!1,meta:{...Je("switchMap"),...t?.meta??{}}})}var _r=W(()=>{"use strict";ye();st();Ie();ne();Pe()});var Ye=W(()=>{"use strict";_r()});function En(r,e){if(Object.is(r,e))return!0;if(r==null||e==null||typeof r!="object"||typeof e!="object")return!1;if(Array.isArray(r)){if(!Array.isArray(e)||r.length!==e.length)return!1;for(let o=0;o<r.length;o++)if(!En(r[o],e[o]))return!1;return!0}if(Array.isArray(e))return!1;let t=Object.keys(r),n=Object.keys(e);if(t.length!==n.length)return!1;let s=new Set(n);for(let o of t)if(!s.has(o)||!En(r[o],e[o]))return!1;return!0}function wr(r,e){return`${r}\0${e}`}function kn(r,e){let t=[],n=new Set(r.subgraphs),s=new Set(e.subgraphs),o=[];for(let m of s)n.has(m)||o.push(m);o.sort();for(let m of o)t.push({type:"subgraph-mounted",path:m});let i=new Set(Object.keys(r.nodes)),a=new Set(Object.keys(e.nodes)),d=[];for(let m of a)i.has(m)||d.push(m);d.sort();for(let m of d)t.push({type:"node-added",path:m,node:{...e.nodes[m]}});let u=[];for(let m of a){if(!i.has(m))continue;let T=r.nodes[m]?.meta,v=e.nodes[m]?.meta;T==null&&v==null||En(T??{},v??{})||u.push(m)}u.sort();for(let m of u)t.push({type:"node-meta-changed",path:m,prevMeta:r.nodes[m]?.meta??{},nextMeta:e.nodes[m]?.meta??{}});let c=new Map;for(let m of r.edges)c.set(wr(m.from,m.to),m);let p=new Map;for(let m of e.edges)p.set(wr(m.from,m.to),m);let l=[];for(let[m,T]of p)c.has(m)||l.push(T);l.sort((m,T)=>m.from<T.from?-1:m.from>T.from?1:m.to<T.to?-1:m.to>T.to?1:0);for(let m of l)t.push({type:"edge-added",from:m.from,to:m.to});let h=[];for(let[m,T]of c)p.has(m)||h.push(T);h.sort((m,T)=>m.from<T.from?-1:m.from>T.from?1:m.to<T.to?-1:m.to>T.to?1:0);for(let m of h)t.push({type:"edge-removed",from:m.from,to:m.to});let f=[];for(let m of i)a.has(m)||f.push(m);f.sort();for(let m of f)t.push({type:"node-removed",path:m});let b=[];for(let m of n)s.has(m)||b.push(m);b.sort();for(let m of b)t.push({type:"subgraph-unmounted",path:m});return{events:t,flushedAt_ns:K()}}var xr=W(()=>{"use strict";Re()});var jt,Nr=W(()=>{"use strict";jt=class{_timer;_gen=0;start(e,t){this.cancel(),this._gen+=1;let n=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,n===this._gen&&t()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var vt,Er=W(()=>{"use strict";vt=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<=0)throw new Error(`RingBuffer capacity must be a positive integer (got ${e})`);this.buf=new Array(e)}buf;head=0;_size=0;get size(){return this._size}get maxSize(){return this.capacity}push(e){let t=(this.head+this._size)%this.capacity;this.buf[t]=e,this._size<this.capacity?this._size++:this.head=(this.head+1)%this.capacity}shift(){if(this._size===0)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this._size--,e}at(e){if(this._size===0)return;let t=e<0?this._size+e:e;if(!(t<0||t>=this._size))return this.buf[(this.head+t)%this.capacity]}toArray(){let e=new Array(this._size);for(let t=0;t<this._size;t++)e[t]=this.buf[(this.head+t)%this.capacity];return e}clear(){for(let e=0;e<this._size;e++)this.buf[(this.head+e)%this.capacity]=void 0;this.head=0,this._size=0}}});function kr(r,e,t,n={}){let s=e in r.nodes,o=t in r.nodes;if(!s)return zt(e,t,"no-such-from");if(!o)return zt(e,t,"no-such-to");let i=n.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===t){if(n.findCycle===!0){let u=qo(r,e,n);if(u!=null)return u}let d=Ht(e,r.nodes[e],0,n);return Bt(e,t,[d])}if(i===0)return zt(e,t,"no-path");let a=Rr(r,e,t,i);return a.found?Bt(e,t,Or(r,a.pathOrder,n)):zt(e,t,a.truncated?"max-depth-exceeded":"no-path")}function Rr(r,e,t,n){let s=new Map,o=[{path:t,depth:0}],i=new Set([t]),a=0,d=!1;for(;a<o.length;){let p=o[a++];if(p.path===e)break;if(n!=null&&p.depth>=n){let b=r.nodes[p.path];b?.deps&&b.deps.length>0&&(d=!0);continue}let l=r.nodes[p.path];if(l==null)continue;let h=l.deps??[],f=new Map;for(let b=0;b<h.length;b++){let m=h[b];if(!m)continue;let T=f.get(m);T==null&&(T=[],f.set(m,T)),T.push(b)}for(let[b,m]of f)i.has(b)||(i.add(b),s.set(b,{from:p.path,depIndices:m}),o.push({path:b,depth:p.depth+1}))}if(!s.has(e))return{found:!1,pathOrder:[],truncated:d};let u=[{path:e}],c=e;for(;c!==t;){let p=s.get(c);if(p==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=p.depIndices,u.push({path:p.from}),c=p.from}return{found:!0,pathOrder:u,truncated:!1}}function qo(r,e,t){let n=r.nodes[e];if(n==null)return null;let s=n.deps??[],o=[];for(let a=0;a<s.length;a++)s[a]===e&&o.push(a);if(o.length>0){let a=Ht(e,n,0,t);a.dep_index=o[0];let d=Ht(e,n,1,t);return Bt(e,e,[a,d])}let i=null;for(let a=0;a<s.length;a++){let d=s[a];if(!d||d===e)continue;let u=Rr(r,d,e,t.maxDepth);u.found&&(i==null||u.pathOrder.length<i.pathOrder.length)&&(i=u,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...u.pathOrder],truncated:!1})}return i==null?null:Bt(e,e,Or(r,i.pathOrder,t))}function Or(r,e,t){return e.map((n,s)=>{let o=r.nodes[n.path],i=Ht(n.path,o,s,t);return n.depIndices!=null&&n.depIndices.length>0&&(i.dep_index=n.depIndices[0],n.depIndices.length>1&&(i.dep_indices=[...n.depIndices])),i})}function Ht(r,e,t,n){let s={path:r,type:e.type,hop:t};e.status!==void 0&&(s.status=e.status),"value"in e&&(s.value=e.value),e.v!=null&&(s.v=e.v);let o=n.annotations?.get(r)??e.annotation;o!=null&&(s.annotation=o);let i=n.lastMutations?.get(r)??e.lastMutation;return i!=null&&(s.lastMutation=i),s}function Bt(r,e,t){return Ar(r,e,!0,"ok",t)}function zt(r,e,t){return Ar(r,e,!1,t,[])}function Ar(r,e,t,n,s){let o=Uo(r,e,t,n,s);return{from:r,to:e,found:t,reason:n,steps:s,text:o,toJSON(){return{from:r,to:e,found:t,reason:n,steps:s}}}}function Uo(r,e,t,n,s){if(!t)switch(n){case"no-such-from":return`explainPath: no node named "${r}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${r}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${r}" to "${e}"`}let o=[`Causal path: ${r} \u2192 ${e} (${s.length} step(s))`];for(let i of s){let d=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(o.push(d),"value"in i&&o.push(` value: ${Ko(i.value)}`),i.annotation!=null&&o.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let u=i.lastMutation.actor;o.push(` actor: ${u.type}${u.id?`:${u.id}`:""}`)}}return o.join(`
2
+ `)}function Ko(r){if(r===void 0)return"<sentinel>";if(r===null)return"null";if(typeof r=="string")return JSON.stringify(r);if(typeof r=="number"||typeof r=="boolean"||typeof r=="bigint")return String(r);try{let e=JSON.stringify(r);return e.length>80?`${e.slice(0,77)}...`:e}catch{return String(r)}}var Sr=W(()=>{"use strict"});function Cr(r){let e=new WeakSet,t=new WeakSet,n=[r],s=0;for(;n.length>0;){let o=n.pop();s+=Jo(o,e,t,n)}return s}function Jo(r,e,t,n){if(r==null)return 0;switch(typeof r){case"number":return ae.number;case"boolean":return ae.boolean;case"string":return ae.string+r.length*2;case"bigint":return ae.bigint+Yo(r);case"symbol":return ae.symbol;case"function":return e.has(r)?0:(e.add(r),ae.function);case"undefined":return 0}let o=r;if(e.has(o))return 0;e.add(o);let i=o[Wo];if(typeof i=="function")try{let u=i.call(o);if(typeof u=="number"&&Number.isFinite(u))return u}catch{}if(o instanceof Date)return ae.date;if(o instanceof RegExp)return ae.regexp+o.source.length*2;if(o instanceof Error){let u=o.message?o.message.length*2:0,c=o.stack?o.stack.length*2:0;return ae.error+u+c}if(typeof URL<"u"&&o instanceof URL)return ae.url+o.href.length*2;if(typeof Promise<"u"&&o instanceof Promise)return ae.promise;if(o instanceof WeakMap)return ae.weakmap;if(o instanceof WeakSet)return ae.weakset;if(o instanceof Map){let u=ae.map;for(let[c,p]of o)u+=ae.mapEntry,n.push(c),n.push(p);return u}if(o instanceof Set){let u=ae.set;for(let c of o)u+=ae.setEntry,n.push(c);return u}if(Array.isArray(o)){let u=ae.array+o.length*8;for(let c of o)n.push(c);return u}if(o instanceof ArrayBuffer)return t.has(o)?0:(t.add(o),o.byteLength);if(ArrayBuffer.isView(o)){let u=o;return t.has(u.buffer)?48:(t.add(u.buffer),u.buffer.byteLength+48)}let a=ae.object,d=Object.keys(o);for(let u of d){a+=ae.string+u.length*2;try{n.push(o[u])}catch{}}return a}function Yo(r){let e=r<0n?-r:r;if(e===0n)return 0;let t=e.toString(2).length;return Math.ceil(t/32)*8}var ae,Wo,Dr=W(()=>{"use strict";ae={object:56,array:64,string:40,number:8,boolean:4,null:0,undefined:0,symbol:40,bigint:16,function:120,map:72,set:72,mapEntry:40,setEntry:24,date:24,regexp:48,error:64,url:80,promise:48,weakmap:40,weakset:40},Wo=Symbol.for("sizeof")});function qt(r,e){let t=e?.topN??10,n=r.describe({detail:"standard"}),s=[],o=r._collectObserveTargets;typeof o=="function"&&o.call(r,"",s);let i=new Map;for(let[l,h]of s)i.set(l,h);let a=[];for(let[l,h]of Object.entries(n.nodes)){let f=i.get(l),b=f instanceof ie?f:null,m=b?Cr(b.cache):0,T=b?b._sinkCount:0,v=h.deps?.length??0,g=h.type==="effect"&&T===0,_=T===0?h.type==="effect"?"orphan-effect":h.type==="derived"?"idle-derived":h.type==="producer"?"idle-producer":null:null;a.push({path:l,type:h.type,status:h.status??"unknown",valueSizeBytes:m,subscriberCount:T,depCount:v,isOrphanEffect:g,orphanKind:_})}let d=a.reduce((l,h)=>l+h.valueSizeBytes,0),u=(l,h)=>[...a].sort(h??((f,b)=>b[l]-f[l])).slice(0,t),c=a.filter(l=>l.orphanKind!=null),p=a.filter(l=>l.isOrphanEffect);return{nodeCount:a.length,edgeCount:n.edges.length,subgraphCount:n.subgraphs.length,nodes:a,totalValueSizeBytes:d,hotspots:{byValueSize:u("valueSizeBytes"),bySubscriberCount:u("subscriberCount"),byDepCount:u("depCount")},orphans:c,orphanEffects:p}}var Rn=W(()=>{"use strict";Ie();Dr()});function Mr(r,e){let t=Math.max(16,r.size*4),n=0;for(;r.size>0;){if(n++>=t){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${t}); ${r.size} disposer(s) discarded`),r.clear();return}let s=r.values().next();if(s.done)return;let o=s.value;r.delete(o);try{o()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function Fr(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"&&typeof r.down=="function"}function Qo(r){if(r!=null)return Fr(r)?r.cache:r}function Xe(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"&&typeof r.down=="function"}function ze(r){return Xe(r)?r.cache??"":r}function Ir(r){return Xe(r)?r.cache??0:r}function Gr(r){return Xe(r)?r.cache??!1:r}function Xo(r){let e=[];for(let t of Object.keys(r).sort()){let n=r[t].v;n!=null&&e.push(`${t} ${n.id} ${n.version}`)}return e.join(`
3
+ `)}function Pr(r){if(r.version!==Qe)throw new Error(`unsupported snapshot version ${String(r.version)} (expected ${Qe})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in r))throw new Error(`snapshot missing required key "${e}"`);if(typeof r.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof r.nodes!="object"||r.nodes===null||Array.isArray(r.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(r.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(r.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function Zo(r,e){let t=new WeakMap,n=(s,o)=>{if(Object.is(s,o))return!0;if(s==null||o==null||typeof s!="object"||typeof o!="object")return!1;let i=t.get(s);if(i==null&&(i=new WeakSet,t.set(s,i)),i.has(o))return!0;i.add(o);let a=s.constructor,d=o.constructor;if(a!==d)return!1;if(s instanceof Date)return s.getTime()===o.getTime();if(s instanceof RegExp)return s.source===o.source&&s.flags===o.flags;if(Array.isArray(s)){let l=o;if(s.length!==l.length)return!1;for(let h=0;h<s.length;h++)if(!n(s[h],l[h]))return!1;return!0}if(s instanceof Map){let l=o;if(s.size!==l.size)return!1;for(let[h,f]of s)if(!l.has(h)||!n(f,l.get(h)))return!1;return!0}if(s instanceof Set){let l=o;if(s.size!==l.size)return!1;for(let h of s){let f=!1;for(let b of l)if(n(h,b)){f=!0;break}if(!f)return!1}return!0}if(ArrayBuffer.isView(s)){let l=s,h=o;if(l.length!==h.length)return!1;for(let f=0;f<l.length;f++)if(l[f]!==h[f])return!1;return!0}let u=Object.keys(s),c=Object.keys(o);if(u.length!==c.length)return!1;let p=new Set(c);for(let l of u)if(!p.has(l)||!n(s[l],o[l]))return!1;return!0};return n(r,e)}function es(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ut(r){let e="^";for(let t=0;t<r.length;t+=1){let n=r[t];if(n==="*"){e+=".*";continue}if(n==="?"){e+=".";continue}if(n==="["){let s=r.indexOf("]",t+1);if(s<=t+1){e+="\\[";continue}let o=r.slice(t+1,s);o.startsWith("!")&&(o=`^${o.slice(1)}`),o=o.replace(/\\/g,"\\\\"),e+=`[${o}]`,t=s;continue}e+=es(n)}return e+="$",new RegExp(e)}function On(r){if(typeof r=="string")return JSON.stringify(r);if(typeof r=="number"||typeof r=="boolean"||r==null)return String(r);try{return JSON.stringify(r)}catch{return"[unserializable]"}}function rs(r){return r==="none"?ns:r==="ansi"||r==null?ts:{data:r.data??"",dirty:r.dirty??"",resolved:r.resolved??"",invalidate:r.invalidate??"",pause:r.pause??"",resume:r.resume??"",complete:r.complete??"",error:r.error??"",teardown:r.teardown??"",derived:r.derived??"",path:r.path??"",reset:r.reset??""}}function Lr(r){if(r==null)return{};let e=r.detail;return e==="full"?{...r,structured:r.structured??!0,timeline:r.timeline??!0,causal:r.causal??!0,derived:r.derived??!0}:e==="minimal"?{...r,structured:r.structured??!0}:r.format==="stage-log"?{...r,structured:r.structured??!0,timeline:r.timeline??!0}:r}function os(r,e,t){for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);if(s<32||s===127)throw new Error(`Graph "${e}": ${t} "${r}" must not contain control character (U+${s.toString(16).padStart(4,"0").toUpperCase()} at index ${n})`)}}function An(r,e,t){if(r==="")throw new Error(`Graph "${e}": ${t} name must be non-empty`);if(r.includes(Y))throw new Error(`Graph "${e}": ${t} "${r}" must not contain '${Y}' (path separator)`);if(r===Se)throw new Error(`Graph "${e}": ${t} name "${Se}" is reserved for meta companion paths`);os(r,e,t)}function ss(r,e){if(r==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let t=r.split(Y);for(let n of t)if(n==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return t}function is(r,e){let t=!1;for(let s of r)if(!e.isMetaPassthrough(s[0])){t=!0;break}return t?r.filter(s=>e.isMetaPassthrough(s[0])):r}function $r(r){for(let e of r._mounts.values())$r(e);for(let e of r._nodes.values())try{e.down([[he]],{internal:!0})}catch{}}function Vr(r,e){let t=le.diff(r,e),n={};for(let s of t.nodesAdded){let o=e.nodes[s];o!=null&&(n[s]=o)}return{...t,nodesAddedFull:n}}function Sn(r,e,t,n={}){let s={paths:[],depths:new Map,truncated:!1};if(!e)return n.withDetail?s:[];if(!n.both&&t!=="upstream"&&t!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let o=n.maxDepth;if(o!=null&&(!Number.isInteger(o)||o<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(o===0)return n.withDetail?s:[];let i=new Map,a=new Map,d=new Map,u=new Map,c=new Set;for(let[g,_]of Object.entries(r.nodes)){if(!g)continue;c.add(g);let w=_.deps??[];i.set(g,w);for(let N of w)N&&(c.add(N),a.has(N)||a.set(N,new Set),a.get(N).add(g))}for(let g of r.edges){if(g==null||typeof g!="object")continue;let _=typeof g.from=="string"?g.from:"",w=typeof g.to=="string"?g.to:"";!_||!w||(c.add(_),c.add(w),u.has(_)||u.set(_,new Set),u.get(_).add(w),d.has(w)||d.set(w,new Set),d.get(w).add(_))}if(!c.has(e))return n.withDetail?s:[];let p=n.both===!0,l=g=>{if(p){let y=i.get(g)??[],x=d.get(g),k=a.get(g),A=u.get(g),E=[...y];return x&&E.push(...x),k&&E.push(...k),A&&E.push(...A),E}if(t==="upstream"){let y=i.get(g)??[],x=d.get(g);return x?[...y,...x]:y}let _=a.get(g),w=u.get(g),N=_?[..._]:[];return w&&N.push(...w),N},h=new Set([e]),f=new Map,b=[{path:e,depth:0}],m=0,T=!1;for(;m<b.length;){let g=b[m++];if(o!=null&&g.depth>=o){l(g.path).length>0&&(T=!0);continue}for(let _ of l(g.path))!_||h.has(_)||(h.add(_),f.set(_,g.depth+1),b.push({path:_,depth:g.depth+1}))}let v=[...f.keys()].sort((g,_)=>g<_?-1:g>_?1:0);return n.withDetail?{paths:v,depths:f,truncated:T}:v}function as(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],s=e[t];if(n.path!==s.path||n.type!==s.type||n.status!==s.status||n.hop!==s.hop||n.dep_index!==s.dep_index||n.annotation!==s.annotation||n.value!==s.value||n.lastMutation!==s.lastMutation)return!1;let o=n.v,i=s.v;if(o!==i&&(o==null||i==null||o.id!==i.id||o.version!==i.version))return!1}return!0}var Y,Se,Qe,ts,ns,le,Tt=W(()=>{"use strict";Mt();De();Re();rt();ye();st();Ie();ne();xr();Pe();Nr();Er();cn();Sr();Rn();Y="::",Se="__meta__",Qe=1;ts={data:"\x1B[32m",dirty:"\x1B[33m",resolved:"\x1B[36m",invalidate:"\x1B[93m",pause:"\x1B[90m",resume:"\x1B[96m",complete:"\x1B[34m",error:"\x1B[31m",teardown:"\x1B[91m",derived:"\x1B[35m",path:"\x1B[90m",reset:"\x1B[0m"},ns={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};le=class r{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_destroyed=!1;_topology;_topologyEmitters=new Set;_factory;_factoryArgs;constructor(e,t){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(Y))throw new Error(`Graph name must not contain '${Y}' (got "${e}")`);if(e===Se)throw new Error(`Graph name "${Se}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...t??{}}),this.config=t?.config??ot,this._traceRing=new vt(t?.traceCapacity??1e3),t?.versioning!=null&&this.setVersioning(t.versioning),typeof t?.factory=="string"&&(this._factory=t.factory,t.factoryArgs!==void 0&&(this._factoryArgs=t.factoryArgs))}tagFactory(e,t){return this._factory=e,this._factoryArgs=t,this}ancestors(e=!0){let t=[],n=e?this:this._parent;for(;n!=null;)t.push(n),n=n._parent;return t}get topology(){return this._topology==null&&(this._topology=de(e=>{let t=n=>{e.emit(n)};return this._topologyEmitters.add(t),()=>{this._topologyEmitters.delete(t)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let t of this._topologyEmitters)t(e)}nameOf(e){return this._nodeToName.get(e)}add(e,t){let n=e.name,s=t?.name??n;if(s==null||s==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let o=s,i=t?.annotation;if(An(o,this.name,"add"),this._mounts.has(o))throw new Error(`Graph "${this.name}": name "${o}" is already a mount point`);if(this._nodes.has(o))throw new Error(`Graph "${this.name}": node "${o}" already exists`);let a=this._nodeToName.get(e);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(o,e),this._nodeToName.set(e,o),this._emitTopology({kind:"added",name:o,nodeKind:"node"}),i!=null&&(this._annotations.set(o,i),this.config.inspectorEnabled&&this._traceRing.push({path:o,annotation:i,timestamp_ns:K()})),e}setVersioning(e){if(e!=null)for(let t of this._nodes.values())t instanceof ie&&t._applyVersioning(e)}remove(e){An(e,this.name,"remove");let t=this._mounts.get(e);if(t){let o={kind:"mount",nodes:[],mounts:[]},i=[];t._collectObserveTargets("",i);for(let[a,d]of i)a.includes(`${Y}${Se}${Y}`)||o.nodes.push(a);return o.nodes.sort(),o.mounts.push(e),o.mounts.push(...t._collectSubgraphs(`${e}${Y}`)),this._mounts.delete(e),t._parent=void 0,$r(t),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:o}),o}let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(n),n.down([[he]],{internal:!0});let s={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:s}),s}removeAll(e){let t=typeof e=="function"?e:(()=>{let o=Ut(e);return i=>o.test(i)})(),n={kind:"mount",nodes:[],mounts:[]},s=[...this._nodes.keys(),...this._mounts.keys()].filter(o=>t(o));for(let o of s){let i=this.remove(o);n.nodes.push(...i.nodes),n.mounts.push(...i.mounts)}return n.nodes.sort(),n.mounts.sort(),n}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),t=this._nodes,n=0;return{[Symbol.iterator](){return this},next(){if(n>=e.length)return{value:void 0,done:!0};let s=e[n++];return{value:[s,t.get(s)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(Y))return this.resolve(e);let t=this._nodes.get(e);if(!t)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return t}get(e){return this.node(e).cache}set(e,t,n){let s=n?.internal===!0;this.node(e).down([[D,t]],{actor:n?.actor,internal:s,delivery:"write"})}setAll(e,t){let n=Symbol.iterator in e?e:Object.entries(e);U(()=>{for(let[s,o]of n)this.set(s,o,t)})}invalidate(e,t){let n=t?.internal===!0;this.node(e).down([[ke]],{actor:t?.actor,internal:n,delivery:"write"})}error(e,t,n){let s=n?.internal===!0;this.node(e).down([[I,t]],{actor:n?.actor,internal:s,delivery:"write"})}complete(e,t){let n=t?.internal===!0;this.node(e).down([[$]],{actor:t?.actor,internal:n,delivery:"write"})}edges(e){let t=e?.recursive===!0,n=new Map;if(!t){for(let[d,u]of this._nodes)n.set(u,d);let a=[];for(let[d,u]of this._nodes)if(u instanceof ie)for(let c of u._deps){let p=n.get(c.node);p!=null&&a.push([p,d])}return a.sort((d,u)=>d[0]<u[0]?-1:d[0]>u[0]?1:d[1]<u[1]?-1:d[1]>u[1]?1:0),a}let s=[];this._collectObserveTargets("",s);let o=new Map;for(let[a,d]of s)o.set(d,a);let i=[];for(let[a,d]of s)if(d instanceof ie)for(let u of d._deps){let c=o.get(u.node);c!=null&&i.push([c,a])}return i.sort((a,d)=>a[0]<d[0]?-1:a[0]>d[0]?1:a[1]<d[1]?-1:a[1]>d[1]?1:0),i}mount(e,t){if(t===void 0){let s=new r(e);return this.mount(e,s)}if(typeof t=="function"){let s=new r(e);return t(s),this.mount(e,s)}let n=t;if(An(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(n===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(n._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${n._parent.name}"`);for(let s=this;s!=null;s=s._parent)if(s===n)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,n),n._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),n}resolve(e){let t=ss(e,this.name);return this._resolveFromSegments(t)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let t=e;if(t[0]===this.name&&(t=t.slice(1),t.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let n=t[0],s=t.slice(1);if(s.length===0){let a=this._nodes.get(n);if(a)return a;throw this._mounts.has(n)?new Error(`Graph "${this.name}": path ends at subgraph "${n}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${n}"`)}let o=this._nodes.get(n);if(o&&s.length>0&&s[0]===Se)return this._resolveMetaChainFromNode(o,s,t.join(Y));let i=this._mounts.get(n);if(!i)throw this._nodes.has(n)?new Error(`Graph "${this.name}": "${n}" is a node; trailing path "${s.join(Y)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${n}"`);return i.resolve(s.join(Y))}_resolveMetaChainFromNode(e,t,n){let s=e,o=0,i=[...t];for(;o<i.length;){if(i[o]!==Se)throw new Error(`Graph "${this.name}": expected ${Se} segment in meta path "${n}"`);if(o+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${Se} in "${n}"`);let a=i[o+1],d=s.meta[a];if(!d)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${n}"`);s=d,o+=2}return s}signal(e,t){if(t?.internal!==!0){for(let s of e)if(this.config.messageTier(s[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let n=[];if(this._signalDeliver(e,t??{},new Set,n),n.length>0)throw n[0]}_signalDeliver(e,t,n,s){for(let d of this._mounts.values())d._signalDeliver(e,t,n,s);let i=t.internal===!0?{internal:!0}:{actor:t.actor,delivery:"signal"},a=is(e,this.config);for(let d of[...this._nodes.keys()].sort()){let u=this._nodes.get(d);if(!n.has(u)){n.add(u);try{u.down(e,i)}catch(c){if(c instanceof Oe)throw c;s.push(c)}a.length!==0&&this._signalMetaSubtree(u,a,n,i,s)}}}_signalMetaSubtree(e,t,n,s,o){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!n.has(a)){n.add(a);try{a.down(t,s)}catch(d){if(d instanceof Oe)throw d;o.push(d)}this._signalMetaSubtree(a,t,n,s,o)}}}describe(e){if(e?.reactive==="diff")return this._describeReactiveDiff(e);if(e?.reactive===!0)return this._describeReactive(e);let t=Qo(e?.actor),n=e?.filter;if(e?.detail!=null&&e?.fields!=null)throw new TypeError("Graph.describe(): pass either `detail` or `fields`, not both. `detail: 'spec'` is the canonical spec projection; use `fields` only when you need a custom subset.");let s=Pt(e?.detail,e?.fields),o=e?.detail==="spec",i=s,a=[];this._collectObserveTargets("",a);let d=new Map;for(let[_,w]of a)d.set(w,_);let u=[];{let _=a.map(([,y])=>y),w=new Set(d.values()),N=0;for(;_.length>0;){let y=_.shift();if(y instanceof ie)for(let x of y._deps){let k=x.node;if(d.has(k))continue;let A=k.name??"",E=A;if(!E||w.has(E))if(A){let P=2;for(;w.has(`${A}#${P}`);)P++;E=`${A}#${P}`}else for(E=`__internal__/${N++}`;w.has(E);)E=`__internal__/${N++}`;d.set(k,E),w.add(E),u.push([E,k]),_.push(k)}}}let c=[...a,...u],p={};for(let[_,w]of c){if(t!=null&&!w.allowsObserve(t))continue;let N=vn(w,i,o),y=w instanceof ie?w._deps.map(E=>d.get(E.node)??E.node.name??""):[],{name:x,...k}=N,A={...k,deps:y};if(!o){let E=this._annotations.get(_);E!=null&&(A.annotation=E)}if(n!=null)if(typeof n=="function"){let E=n;if(!(E.length>=2?E(_,A):E(A)))continue}else{let E=!0;for(let[P,H]of Object.entries(n)){let F=P==="deps_includes"?"depsIncludes":P==="meta_has"?"metaHas":P;if(F==="depsIncludes"){if(!A.deps.includes(String(H))){E=!1;break}continue}if(F==="metaHas"){if(!Object.hasOwn(A.meta??{},String(H))){E=!1;break}continue}if(A[F]!==H){E=!1;break}}if(!E)continue}p[_]=A}let l=new Set(Object.keys(p)),h=[];for(let[_,w]of c)if(w instanceof ie)for(let N of w._deps){let y=d.get(N.node);y!=null&&h.push([y,_])}h.sort((_,w)=>_[0]<w[0]?-1:_[0]>w[0]?1:_[1]<w[1]?-1:_[1]>w[1]?1:0);let f=h.map(([_,w])=>({from:_,to:w}));(t!=null||n!=null)&&(f=f.filter(_=>l.has(_.from)&&l.has(_.to)));let b=this._collectSubgraphs(""),m=t!=null||n!=null?b.filter(_=>{let w=`${_}${Y}`;return[...l].some(N=>N===_||N.startsWith(w))}):b,T=this,v=e;return{name:this.name,nodes:p,edges:f,subgraphs:m,...this._factory!==void 0?{factory:this._factory}:{},...this._factoryArgs!==void 0?{factoryArgs:this._factoryArgs}:{},expand(_){let w={...v};return Array.isArray(_)?(w.fields=_,w.detail=void 0):(w.detail=_,w.fields=void 0),T.describe(w)}}}_collectSubgraphs(e){let t=[];for(let n of[...this._mounts.keys()].sort()){let s=e===""?n:`${e}${n}`;t.push(s),t.push(...this._mounts.get(n)._collectSubgraphs(`${s}${Y}`))}return t}resourceProfile(e){return qt(this,e)}reachable(e,t,n={}){return n.withDetail===!0?Sn(this.describe(),e,t,{...n,withDetail:!0}):Sn(this.describe(),e,t,n)}explain(e,t,n){return n?.reactive===!0?this._explainReactive(e,t,n):this._explainStatic(ze(e),ze(t),{...n?.maxDepth!==void 0?{maxDepth:Ir(n.maxDepth)}:{},...n?.findCycle!==void 0?{findCycle:Gr(n.findCycle)}:{}})}_explainStatic(e,t,n){let s=this.describe({detail:"full"}),o=new Map(this._annotations),i=new Map;for(let[a,d]of Object.entries(s.nodes))d.lastMutation!=null&&i.set(a,d.lastMutation);return kr(s,e,t,{...n?.maxDepth!=null?{maxDepth:n.maxDepth}:{},...n?.findCycle===!0?{findCycle:!0}:{},annotations:o,lastMutations:i})}_describeReactive(e){let t={...e,reactive:!1},n=e.reactiveName??"describe",s=0,o=V(s,{name:`${n}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,nt(()=>{a=!1,!d&&(s+=1,o.emit(s))}))},c=i.onEvent(v=>{let g=v.type;g!=="data"&&g!=="error"&&g!=="complete"&&g!=="teardown"||u()}),p=[],l=new WeakSet,h=v=>{if(l.has(v)||d)return;l.add(v);let g=v.topology.subscribe(_=>{for(let w of _){if(w[0]!==D)continue;let N=w[1];if(u(),N.kind==="added"&&N.nodeKind==="mount"){let y=v._mounts.get(N.name);y!=null&&h(y)}}});p.push(g);for(let _ of v._mounts.keys()){let w=v._mounts.get(_);w!=null&&h(w)}};h(this);let f,b=e.actor;Fr(b)&&(f=b.subscribe(v=>{let g=!1,_=!1;for(let w of v){let N=w[0];N===D?g=!0:(N===$||N===I||N===he)&&(_=!0)}g&&u(),_&&(f?.(),f=void 0,u())}));let m;try{m=G([o],()=>this.describe(t),{name:n,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(v,g)=>v===g})}catch(v){c(),f?.();for(let g of p)g();throw i.dispose(),v}let T=ce(m);return{node:m,dispose(){d=!0,c(),f?.();for(let v of p)v();p.length=0,i.dispose(),T()}}}_describeReactiveDiff(e){let t={...e,reactive:!1},n=e.reactiveName??"describe-diff",s={name:this.name,nodes:{},edges:[],subgraphs:[]},o=this.describe(t),i=kn(s,o),a=V(i,{name:n,meta:{domain:"audit",kind:"describe-diff"},equals:(l,h)=>l===h}),d=this._describeReactive({...e,reactiveName:void 0}),u=!1,c=d.node.subscribe(l=>{if(!u)for(let h of l){if(h[0]!==D)continue;let f=h[1],b=kn(o,f);o=f,b.events.length!==0&&a.emit(b)}}),p=ce(a);return{node:a,dispose(){u=!0,c(),d.dispose(),a.down([[he,"describe-diff disposed"]]),p()}}}_explainReactive(e,t,n){let s=0,o=V(s,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,nt(()=>{a=!1,!d&&(s+=1,o.emit(s))}))},c=i.onEvent(v=>{let g=v.type;g!=="data"&&g!=="error"&&g!=="complete"&&g!=="teardown"||u()}),p=[];e!=null&&Xe(e)&&p.push(e),t!=null&&Xe(t)&&p.push(t),n?.maxDepth!=null&&Xe(n.maxDepth)&&p.push(n.maxDepth),n?.findCycle!=null&&Xe(n.findCycle)&&p.push(n.findCycle);let l=()=>{for(let v of p)if(v.cache===void 0)return!1;return!0},h=()=>{let v=ze(e),g=ze(t);return{from:v,to:g,found:!1,reason:"pending",steps:[],text:"(awaiting reactive args)",toJSON:()=>({from:v,to:g,found:!1,reason:"pending",steps:[]})}},f;try{f=G([o],()=>{if(!l())return h();let v=ze(e),g=ze(t),_={...n?.maxDepth!==void 0?{maxDepth:Ir(n.maxDepth)}:{},...n?.findCycle!==void 0?{findCycle:Gr(n.findCycle)}:{}};return this._explainStatic(v,g,_)},{name:n?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:ze(e),to:ze(t)},equals:(v,g)=>v.found===g.found&&v.reason===g.reason&&v.steps.length===g.steps.length&&as(v.steps,g.steps)})}catch(v){throw c(),i.dispose(),v}let b=ce(f),m=[],T=v=>{let g;return g=v.subscribe(_=>{let w=!1,N=!1;for(let y of _){let x=y[0];x===D?w=!0:(x===$||x===I||x===he)&&(N=!0)}(w||N)&&u(),N&&g&&(g(),g=void 0)}),()=>{g&&(g(),g=void 0)}};for(let v of p)m.push(T(v));return{node:f,dispose(){d=!0,c();for(let v of m)v?.();m.length=0,i.dispose(),b()}}}_pathsMatching(e){let t=Ut(e),n=[];return this._collectObserveTargets("",n),n.map(([s])=>s).filter(s=>t.test(s))}_collectObserveTargets(e,t){for(let n of[...this._mounts.keys()].sort()){let s=e===""?n:`${e}${Y}${n}`;this._mounts.get(n)._collectObserveTargets(s,t)}for(let n of[...this._nodes.keys()].sort()){let s=this._nodes.get(n),o=e===""?n:`${e}${Y}${n}`;t.push([o,s]),this._appendMetaObserveTargets(o,s,t)}}_appendMetaObserveTargets(e,t,n){for(let s of Object.keys(t.meta).sort()){let o=t.meta[s],i=`${e}${Y}${Se}${Y}${s}`;n.push([i,o]),this._appendMetaObserveTargets(i,o,n)}}observe(e,t){let n=typeof e=="string",o=Lr(n?t:e);if(o.reactive===!0)return this._observeReactive(n?e:void 0,o);let i=o.structured===!0||o.timeline===!0||o.causal===!0||o.derived===!0||o.detail==="minimal"||o.detail==="full"||o.format!=null,a=o.actor;if(n){let c=e,p=this.resolve(c);if(a!=null&&!p.allowsObserve(a))throw new Oe({actor:a,action:"observe",nodeName:c});return i?this._buildStructuredObserver([[c,p]],o,"one"):{subscribe(l){return p.subscribe(l)},up(l){try{p.up?.(l)}catch(h){if(h instanceof Oe)return;throw h}}}}let d=[];this._collectObserveTargets("",d),d.sort((c,p)=>c[0]<p[0]?-1:c[0]>p[0]?1:0);let u=a==null?d:d.filter(([,c])=>c.allowsObserve(a));return i?this._buildStructuredObserver(u,o,"all"):{subscribe:c=>{let p=u.map(([l,h])=>h.subscribe(f=>{c(l,f)}));return()=>{for(let l of p)l()}},up:(c,p)=>{try{this.resolve(c).up?.(p)}catch(l){if(l instanceof Oe)return;throw l}}}}_observeReactive(e,t){let n=t.tiers,s=n!=null?new Set(n):null,o=t.reactiveName??"observe";return de(i=>{let a=[],d=!1,u=!1,c=()=>{if(a.length===0||u)return;let b={events:a.slice(),flushedAt_ns:K()};a.length=0,i.emit(b)},p={...t,reactive:!1,structured:!0,timeline:!0},l=e!=null?this.observe(e,p):this.observe(p),h=b=>{u||(a.push(b),!d&&(d=!0,nt(()=>{d=!1,c()})))};for(let b of l.events)h(b);let f=l.onEvent(h);return()=>{u=!0,f(),l.dispose()}},{name:o,meta:{domain:"audit",kind:"observe-reactive"}})}_buildStructuredObserver(e,t,n){let s=n==="one"?e[0]?.[0]:void 0,o=i=>{if(n==="one"&&s!=null){let c=this.resolve(s);return this._buildStructuredObserver([[s,c]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((c,p)=>c[0]<p[0]?-1:c[0]>p[0]?1:0);let d=i.actor,u=d==null?a:a.filter(([,c])=>c.allowsObserve(d));return this._buildStructuredObserver(u,i,"all")};return this._createObserveResult(e,t,o)}_createObserveResult(e,t,n){let s=t.timeline===!0,o=t.causal===!0,i=t.derived===!0,a=t.detail==="minimal",d=this.config.inspectorEnabled,u=(o||i)&&d,c=t.maxEvents,p=c!=null&&c>0?new vt(c):null,l=[],h=new Set,f=t.tiers!=null?new Set(t.tiers):null,b={},m=new Set,T=0,v=0,g=0,_=0,w=0,N=0,y=!1,x=!1,k=0,A=new Map,E=new Map,P=new Map,H=C=>{if(!(f!=null&&!f.has(C.type))){p?p.push(C):l.push(C);for(let q of h)q(C)}},F=C=>f==null||f.has(C),ve=()=>s?{timestamp_ns:K(),in_batch:gt(),batch_id:k}:{},Te=(C,q)=>{if(!(!u||!(C instanceof ie)))return C._setInspectorHook(be=>{if(be.kind==="dep_message")A.set(C,be.depIndex);else if(be.kind==="run"){let Ge=be.batchData.map((R,M)=>R!=null&&R.length>0?R.at(-1):be.prevData[M]);E.set(C,Ge);let we=be.batchData.map(R=>R!=null?[...R]:void 0);P.set(C,we),i&&H({type:"derived",path:q,dep_values:Ge,dep_batches:we,...ve()})}})},Ee=C=>{let q=A.get(C),be=E.get(C);if(!o||be==null)return{};let we=(q!=null&&q>=0&&C instanceof ie?C._deps[q]:void 0)?.node,R=we?.v,M=P.get(C);return{trigger_dep_index:q,trigger_dep_name:we?.name,...R!=null?{trigger_version:{id:R.id,version:R.version}}:{},dep_values:[...be],...M!=null?{dep_batches:M}:{}}},Ne=[],j=[];for(let[C,q]of e){let be=Te(q,C);be&&Ne.push(be),j.push(q.subscribe(Ge=>{k++;for(let we of Ge){let R=we[0],M=ve();if(R===D){b[C]=we[1];let ee=q instanceof ie?q.lastMutation?.actor??Ze:Ze;H({type:"data",path:C,data:we[1],actor:ee,...M,...Ee(q)})}else if(a)R===X?F("dirty")&&T++:R===J?F("resolved")&&v++:R===ke?F("invalidate")&&g++:R===Ce?F("pause")&&_++:R===je?F("resume")&&w++:R===he?F("teardown")&&N++:R===$&&!m.has(C)?F("complete")&&(y=!0):R===I&&F("error")&&(x=!0,m.add(C));else if(R===X)F("dirty")&&T++,H({type:"dirty",path:C,...M});else if(R===J)F("resolved")&&v++,H({type:"resolved",path:C,...M,...Ee(q)});else if(R===ke)F("invalidate")&&g++,H({type:"invalidate",path:C,...M});else if(R===Ce)F("pause")&&_++,H({type:"pause",path:C,lockId:we[1],...M});else if(R===je)F("resume")&&w++,H({type:"resume",path:C,lockId:we[1],...M});else if(R===$)F("complete")&&!m.has(C)&&(y=!0),H({type:"complete",path:C,...M});else if(R===I){F("error")&&(x=!0,m.add(C));let ee=q instanceof ie?q.lastMutation?.actor??Ze:Ze;H({type:"error",path:C,data:we[1],actor:ee,...M})}else R===he&&(F("teardown")&&N++,H({type:"teardown",path:C,...M}))}}))}let z=!1,L=()=>{if(!z){z=!0;for(let C of j)C();for(let C of Ne)C();for(let C of Z)C({value:void 0,done:!0});Z.length=0}},ue=[],Z=[];h.add(C=>{let q=Z.shift();q?q({value:C,done:!1}):ue.push(C)});let ge={get values(){return b},get dirtyCount(){return T},get resolvedCount(){return v},get invalidateCount(){return g},get pauseCount(){return _},get resumeCount(){return w},get teardownCount(){return N},get events(){return p?p.toArray():[...l]},get anyCompletedCleanly(){return y},get anyErrored(){return x},get completedWithoutErrors(){return y&&!x},onEvent(C){return h.add(C),()=>h.delete(C)},dispose:L,expand(C){L();let q={...t};return typeof C=="string"?q.detail=C:Object.assign(q,C),n(Lr(q))},[Symbol.asyncIterator](){return{next(){return ue.length>0?Promise.resolve({value:ue.shift(),done:!1}):z?Promise.resolve({value:void 0,done:!0}):new Promise(C=>Z.push(C))},return(){return L(),Promise.resolve({value:void 0,done:!0})}}}};return t.format!=null&&this._attachFormatLogger(ge,t),ge}_attachFormatLogger(e,t){let n=t.format;if(n==null)return;let s=t.logger??(f=>console.log(f)),o=t.includeTypes?new Set(t.includeTypes):null,i=t.excludeTypes?new Set(t.excludeTypes):null,a=o==null&&i==null?()=>!0:f=>(o==null||o.has(f))&&(i==null||!i.has(f)),d=rs(t.theme),u=n==="stage-log"?K():0,c=f=>f==null?"":t.stageLabels?.[f]??f,p=(f,b)=>f.length>b?`${f.slice(0,b-1)}\u2026`:f,l=f=>f.type==="data"||f.type==="error"?p(On(f.data),120):"",h=f=>{if(n==="stage-log"){let y=(K()-u)/1e9,x=c(f.path).padEnd(9);if(f.type==="data"){let k=l(f);return`[${y.toFixed(3)}s] ${x} \u2190${k?` ${k}`:""}`}if(f.type==="error"){let k=l(f);return`[${y.toFixed(3)}s] ${x} \u2717${k?` ${k}`:""}`}return f.type==="complete"?`[${y.toFixed(3)}s] ${x} \u25A0 complete`:`[${y.toFixed(3)}s] ${x} ${f.type}`}if(n==="json")try{return JSON.stringify(f)}catch{return JSON.stringify({type:f.type,path:f.path,data:"[unserializable]"})}let b=d[f.type]??"",m=f.path?`${d.path}${f.path}${d.reset} `:"",T=f.type==="data"||f.type==="error",v=f.type==="pause"||f.type==="resume",g=T?` ${On(f.data)}`:v?` ${On(f.lockId)}`:"",_=f.type==="data"||f.type==="resolved"||f.type==="derived"?f:void 0,w=_?.trigger_dep_name!=null?` <- ${_.trigger_dep_name}`:_?.trigger_dep_index!=null?` <- #${_.trigger_dep_index}`:"",N=f.in_batch?" [batch]":"";return`${m}${b}${f.type.toUpperCase()}${d.reset}${g}${w}${N}`};e.onEvent(f=>{a(f.type)&&s(h(f),f)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){Mr(this._disposers,this.name),this.signal([[he]],{internal:!0}),Mr(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}get destroyed(){return this._destroyed}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}snapshot(e){let{expand:t,...n}=this.describe({detail:"full"}),s={};for(let a of Object.keys(n.nodes).sort()){let{lastMutation:d,guard:u,...c}=n.nodes[a];s[a]=c}let o=[...n.subgraphs].sort(),i={...n,version:1,nodes:s,subgraphs:o};if(e?.format==null)return i;if(e.format==="json-string")return JSON.stringify(i);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(e.codec);if(a==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return tr(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,t){let n=t?.config??ot,{codec:s,codecVersion:o,payload:i}=nr(e,n);return s.decode(i,o)}restore(e,t){if(Pr(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let n=t?.only==null?null:(Array.isArray(t.only)?t.only:[t.only]).map(o=>Ut(o)),s=t?.includeProducers===!0;for(let o of Object.keys(e.nodes).sort()){if(n!==null&&!n.some(a=>a.test(o)))continue;let i=e.nodes[o];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&t?.onError?.(o,new Error(`restore: slice.value is undefined for "${o}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!s)){if(i.v!=null){let d=this.tryResolve(o)?.v;if(d!=null&&d.id===i.v.id&&d.version===i.v.version)continue}try{this.set(o,i.value)}catch(a){t?.onError?.(o,a)}}}}}static fromSnapshot(e,t){Pr(e);let n=typeof t=="function"?t:t?.build,s=typeof t=="function"?void 0:t?.factories,o=new r(e.name);if(n)return n(o),o.restore(e),o;for(let h of[...e.subgraphs].sort((f,b)=>{let m=f.split(Y).length,T=b.split(Y).length;return m!==T?m-T:f<b?-1:f>b?1:0})){let f=h.split(Y),b=o;for(let m of f)b._mounts.has(m)||b.mount(m,new r(m)),b=b._mounts.get(m)}let i=s?Object.entries(s).map(([h,f])=>({re:Ut(h),factory:f})):[],a=h=>{for(let f of i)if(f.re.test(h))return f.factory},d=h=>{let f=h.split(Y),b=f.pop();if(b==null||b.length===0)throw new Error(`invalid snapshot path "${h}"`);let m=o;for(let T of f){let v=m._mounts.get(T);if(!v)throw new Error(`unknown mount "${T}" in path "${h}"`);m=v}return[m,b]},u=Object.entries(e.nodes).filter(([h])=>!h.includes(`${Y}${Se}${Y}`)).sort((h,f)=>h[0]<f[0]?-1:h[0]>f[0]?1:0),c=new Map(u),p=new Map,l=!0;for(;c.size>0&&l;){l=!1;for(let[h,f]of[...c.entries()]){let b=f?.deps??[];if(!b.every(w=>p.has(w)))continue;let[m,T]=d(h),v={...f?.meta??{}},g=a(h),_;if(f?.type==="state")_=V(f.value,{meta:v});else{if(g==null)continue;_=g(T,{path:h,type:f.type,value:f.value,meta:v,deps:b,resolvedDeps:b.map(w=>p.get(w))})}m.add(_,{name:T}),p.set(h,_),c.delete(h),l=!0}}if(c.size>0){let h=[...c.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${h}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return o.restore(e),o}toJSON(){return this.snapshot()}attachSnapshotStorage(e,t={}){let n=e.map(u=>({tier:u,debounceMs:Math.max(0,u.debounceMs??0),compactEvery:Math.max(1,u.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));t.autoRestore===!0&&this._cascadeRestore(e,t.onError);let s=(u,c)=>{if(u.disposed)return;let p=Xo(c.nodes);if(u.lastSnapshot!=null&&p!==""&&p===u.lastFingerprint)return;let l=u.seq+1,h=Me(),m=u.lastSnapshot==null||l%u.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:l,timestamp_ns:h,format_version:Qe}:{name:this.name,mode:"diff",diff:Vr(u.lastSnapshot,c),seq:l,timestamp_ns:h,format_version:Qe};if(u.tier.filter&&!u.tier.filter(m))return;let T;try{T=u.tier.save(m)}catch(v){t.onError?.(v,u.tier);return}if(T&&typeof T.then=="function"){let _=(u.savePending??Promise.resolve()).then(()=>T,()=>T).then(()=>{u.disposed||(u.seq=l,u.lastSnapshot=c,u.lastFingerprint=p)},w=>{t.onError?.(w,u.tier)});u.savePending=_.finally(()=>{u.savePending===_&&(u.savePending=void 0)})}else u.seq=l,u.lastSnapshot=c,u.lastFingerprint=p},o=(u,c)=>{try{s(u,c)}catch(p){t.onError?.(p,u.tier)}},i=(u,c)=>{if(!c.some(f=>{let b=this.config.messageTier(f[0]);return b>=3&&b<5}))return;if(t.filter){let f=this.tryResolve(u);if(f==null)return;let b=vn(f,Pt("standard"));if(!t.filter(u,b))return}let l,h=()=>(l==null&&(l=this.snapshot()),l);for(let f of n)f.disposed||(f.debounceMs===0?o(f,h()):(f.timer==null&&(f.timer=new jt),f.timer.start(f.debounceMs,()=>{f.disposed||o(f,this.snapshot())})))},a;if(t.paths!=null){let c=(typeof t.paths=="string"?this._pathsMatching(t.paths):t.paths).map(p=>{let l=this.tryResolve(p);return l==null?()=>{}:l.subscribe(h=>i(p,h))});a=()=>{for(let p of c)p()}}else a=this.observe().subscribe((u,c)=>i(u,c));let d=()=>{a();for(let u of n)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(d)};return this._storageDisposers.add(d),{dispose:d}}async _cascadeRestore(e,t){for(let n of e){let s;try{s=await n.load?.()}catch(i){t?.(i,n);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let o=s;try{if(o.mode==="full"&&o.snapshot!=null)return this.restore(o.snapshot),!0;if(o.version===Qe&&o.nodes!=null)return this.restore(o),!0}catch(i){t?.(i,n)}}return!1}static async fromStorage(e,t,n){for(let s of t){let o;try{o=await s.load?.()}catch(d){n?.onError?.(d,s);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let i=o,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===Qe&&i.nodes!=null?i:void 0;if(a!=null)try{return r.fromSnapshot(a,n)}catch(d){n?.onError?.(d,s)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${t.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,t,n){if(e!=null&&t!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,t),this.config.inspectorEnabled){let s={path:e,annotation:t,timestamp_ns:K(),...n?.actor!=null?{actor:n.actor}:{}};this._traceRing.push(s)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let t=this._traceRing.toArray().filter(s=>!e(s)),n=this._traceRing.size-t.length;this._traceRing.clear();for(let s of t)this._traceRing.push(s);return n}static diff(e,t){let n=new Set(Object.keys(e.nodes)),s=new Set(Object.keys(t.nodes)),o=[...s].filter(v=>!n.has(v)).sort(),i=[...n].filter(v=>!s.has(v)).sort(),a=[],d=[];for(let v of n){if(!s.has(v))continue;let g=e.nodes[v],_=t.nodes[v],w=g.v,N=_.v;w!=null&&N!=null&&w.id===N.id&&w.version!==N.version&&d.push({path:v,id:w.id,from:w.version,to:N.version});let y=w!=null&&N!=null&&w.id===N.id&&w.version===N.version;for(let x of["type","status","sentinel"]){let k=g[x],A=_[x];k!==A&&a.push({path:v,field:x,from:k,to:A})}if(!y)for(let x of["value","meta"]){let k=g[x],A=_[x];Zo(k,A)||a.push({path:v,field:x,from:k,to:A})}}let u=v=>`${v.from} ${v.to}`,c=new Set(e.edges.map(u)),p=new Set(t.edges.map(u)),l=t.edges.filter(v=>!c.has(u(v))),h=e.edges.filter(v=>!p.has(u(v))),f=new Set(e.subgraphs),b=new Set(t.subgraphs),m=[...b].filter(v=>!f.has(v)).sort(),T=[...f].filter(v=>!b.has(v)).sort();return{nodesAdded:o,nodesRemoved:i,nodesChanged:a,versionChanges:d,edgesAdded:l,edgesRemoved:h,subgraphsAdded:m,subgraphsRemoved:T}}}});function He(r,e,t){return{[r]:!0,[`${r}_type`]:e,...t??{}}}var _t=W(()=>{"use strict"});var In=W(()=>{"use strict";Tt()});var Gs={};ao(Gs,{DEFAULT_DECAY_RATE:()=>ut,DEFAULT_EXECUTE_PROMPT:()=>wn,DEFAULT_QUEUE_CONFIGS:()=>$t,DEFAULT_SEVERITY_WEIGHTS:()=>at,DEFAULT_TRIAGE_PROMPT:()=>_n,DEFAULT_VERIFY_PROMPT:()=>xn,HarnessGraph:()=>en,QUEUE_NAMES:()=>xe,actuatorExecutor:()=>yr,affectedTaskFilter:()=>Vo,autoSolidify:()=>Co,beforeAfterCompare:()=>$o,blindVariation:()=>ms,codeChangeBridge:()=>jo,createIntakeBridge:()=>Po,defaultErrorClassifier:()=>Vt,defaultLlmExecutor:()=>eo,defaultLlmVerifier:()=>to,dispatchActuator:()=>So,effectivenessTracker:()=>Bo,errorCritique:()=>ys,evalIntakeBridge:()=>Lo,evalSource:()=>Fo,evalVerifier:()=>Br,harnessEvalPair:()=>xs,harnessLoop:()=>As,harnessProfile:()=>Cs,harnessTrace:()=>Ms,notifyEffect:()=>zo,priorityScore:()=>Rs,refineExecutor:()=>zn,refineLoop:()=>jn,resolvePromptFn:()=>yt,strategyKey:()=>dt,strategyModel:()=>Yn});module.exports=co(Gs);ye();ne();Pe();function ko(r,e){return{outcome:"success",detail:`actuator applied ${e.intervention} for ${Ao(e.summary)}`,artifact:r}}function Ro(r,e){let t=r instanceof Error?r.message:String(r);return{outcome:"failure",detail:`actuator threw on ${e.intervention}: ${t}`}}function Oo(r){return`actuator skipped ${r.intervention} (shouldApply returned false)`}function Ao(r,e=80){return r.length<=e?r:`${r.slice(0,e-1)}\u2026`}function yr(r){let e=r.name??"actuator-executor",t=r.toOutput??ko,n=r.onError??Ro,s=r.skipDetail??Oo;return o=>{let i=o.payload.item;return r.shouldApply&&!r.shouldApply(i)?{...o.payload,execution:{item:i,outcome:"failure",detail:s(i)}}:de(a=>{let d=new AbortController,u=!1,c=null,p=h=>{u||(u=!0,a.down([[D,{...o.payload,execution:{item:i,...h}}],[$]]),c?.(),c=null)},l;try{let h=r.apply(i,{signal:d.signal});l=Ae(h,{signal:d.signal})}catch(h){return p(n(h,i)),()=>{d.abort()}}return c=l.subscribe(h=>{for(let f of h){if(u)return;if(f[0]===D){p(t(f[1],i));return}if(f[0]===I){p(n(f[1],i));return}if(f[0]===$){p(n(new Error("actuator inner completed without emitting DATA"),i));return}}}),u&&c&&(c(),c=null),()=>{d.abort(),c?.(),c=null}},{name:`${e}/inner`})}}function So(r){let e=r.name??"dispatch-actuator",t=r.default??null,n=t!=null;return yr({apply:(s,o)=>{let i=Object.hasOwn(r.routes,s.intervention)?r.routes[s.intervention]:t;if(!i)throw new Error(`dispatchActuator: no route for intervention '${s.intervention}'`);return i(s,o)},shouldApply:s=>Object.hasOwn(r.routes,s.intervention)||n,skipDetail:s=>`no route for intervention '${s.intervention}'`,name:e})}ye();ne();function Co(r){let e=r.name??"auto-solidify",t=r.extract??(s=>s.execution.artifact??null),n=r.predicate??(()=>!0);return de(s=>{let o=null,i=!1,a=()=>{i||(i=!0,o?.(),o=null)},d=u=>{i||(s.down([[I,u]]),a())};return o=r.verifyResults.subscribe(u=>{if(!i)for(let c of u){if(i)return;if(c[0]!==D){if(c[0]===$){s.down([[$]]),a();return}continue}let p=c[1];if(p==null||!p.verified)continue;let l;try{l=n(p)}catch(f){d(f);return}if(!l)continue;let h;try{h=t(p)}catch(f){d(f);return}if(h!=null){try{r.write(h,p)}catch(f){d(f);return}s.down([[D,h]])}}}),i&&o&&(o(),o=null),()=>{a()}},{name:e})}ne();Ye();Pe();function Po(r,e,t,n){return me([r],([s])=>{if(s==null)return;let o=t(s);for(let i of o)e.publish(i)},{name:n?.name??"intake-bridge"})}function Lo(r,e,t){let n=t?.defaultSeverity??"medium";return me([r],([s])=>{if(s==null)return;let o=Array.isArray(s)?s:[s];for(let i of o)for(let a of i.tasks)if(!(a.valid&&a.judge_scores?.every(d=>d.pass))){if(!a.valid&&(!a.judge_scores||a.judge_scores.length===0)){e.publish({source:"eval",summary:`Task ${a.task_id} invalid (model: ${i.model})`,evidence:`Run ${i.run_id}: task produced invalid output`,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:n});continue}if(a.judge_scores)for(let d of a.judge_scores)d.pass||e.publish({source:"eval",summary:`${a.task_id}: ${d.claim} (model: ${i.model})`,evidence:d.reasoning,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:n})}},{name:t?.name??"eval-intake-bridge"})}function Fo(r,e){return it(r,()=>Ae(e()))}function $o(r,e){return G([r,e],([t,n])=>{let s=t,o=n,i=new Map(s.tasks.map(l=>[l.task_id,l])),a=new Map(o.tasks.map(l=>[l.task_id,l])),d=new Set([...i.keys(),...a.keys()]),u=[],c=[],p=[];for(let l of d){let h=i.get(l),f=a.get(l),b=h?.valid??!1,m=f?.valid??!1,T=h?.judge_scores?h.judge_scores.filter(_=>_.pass).length:void 0,v=f?.judge_scores?f.judge_scores.filter(_=>_.pass).length:void 0,g=T!==void 0&&v!==void 0?v-T:void 0;u.push({taskId:l,before:b,after:m,scoreDiff:g}),b&&!m&&c.push(l),!b&&m&&p.push(l)}return{newFailures:c,resolved:p,taskDeltas:u,overallImproved:p.length>c.length}},{name:"eval-delta"})}function Vo(r,e){let t=e==null?null:Array.isArray(e)?V(e):e,n=[r];return t&&n.push(t),G(n,s=>{let o=s[0],i=t?new Set(s[1]):null,a=new Set;for(let d of o)for(let u of d.affectsEvalTasks??[])(i==null||i.has(u))&&a.add(u);return[...a].sort()},{name:"affected-task-filter"})}function jo(r,e,t,n){let s=n?.defaultSeverity??"high";function o(a){let d=[];for(let u of a.lintErrors??[])d.push({source:"code-change",summary:`Lint: ${u.rule} in ${u.file}:${u.line}`,evidence:u.message,affectsAreas:[u.file],severity:s});for(let u of a.testFailures??[])d.push({source:"test",summary:`Test failure: ${u.testId}`,evidence:u.message,affectsAreas:[u.file],affectsEvalTasks:[u.testId],severity:s});return d}let i=t??o;return me([r],([a])=>{if(a!=null)for(let d of i(a))e.publish(d)},{name:n?.name??"code-change-bridge"})}function zo(r,e,t){return me([r.latest],([n])=>{n!=null&&e(n)},{name:t?.name??"notify-effect"})}var xe=["auto-fix","needs-decision","investigation","backlog"],$t={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},at={critical:100,high:70,medium:40,low:10},ut=Math.LN2/(168*3600);function dt(r,e){return`${r}\u2192${e}`}var Ho=/\b(parse|json|config|validation|syntax)\b/i,Vt=r=>Ho.test(r.detail)?"self-correctable":"structural",_n=`You are a triage classifier for a reactive collaboration harness.
2
4
 
3
5
  Given an intake item, classify it and output JSON:
4
6
  {
@@ -13,7 +15,7 @@ Strategy model (past effectiveness):
13
15
  {{strategy}}
14
16
 
15
17
  Intake item:
16
- {{item}}`,bn=`You are an implementation agent.
18
+ {{item}}`,wn=`You are an implementation agent.
17
19
 
18
20
  Given a triaged issue with root cause and intervention type, produce a fix.
19
21
 
@@ -24,7 +26,7 @@ Output JSON:
24
26
  {
25
27
  "outcome": "success" | "failure" | "partial",
26
28
  "detail": "<description of what was done or what failed>"
27
- }`,yn=`You are a QA reviewer.
29
+ }`,xn=`You are a QA reviewer.
28
30
 
29
31
  Given an execution result, verify whether the fix is correct.
30
32
 
@@ -39,8 +41,8 @@ Output JSON:
39
41
  "verified": true/false,
40
42
  "findings": ["<finding1>", ...],
41
43
  "errorClass": "self-correctable" | "structural" // only if verified=false
42
- }`;function gt(r,e,t){if(typeof r=="function")return r;let n=r??e;return s=>t(n,s)}te();Me();Oe();be();te();var vn=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(e={}){let{maxSize:t,defaultTtl:n}=e;if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1");if(n!==void 0&&n<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=t,this._defaultTtl=n}get version(){return this._version}get size(){return this._store.size}has(e){let t=this._store.get(e);return t===void 0?!1:this._isExpired(t)?(this._store.delete(e),this._version+=1,!1):(this._touchLru(e,t),!0)}get(e){let t=this._store.get(e);if(t!==void 0){if(this._isExpired(t)){this._store.delete(e),this._version+=1;return}return this._touchLru(e,t),t.value}}set(e,t,n){let s=this._resolveExpiresAt(n);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:t,expiresAt:s}),this._evictLruWhileOver(),this._version+=1}setMany(e,t){let n=this._resolveExpiresAt(t),s=0;try{for(let[o,i]of e)this._store.has(o)&&this._store.delete(o),this._store.set(o,{value:i,expiresAt:n}),s+=1}finally{s>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(e){let t=this._store.delete(e);return t&&(this._version+=1),t}deleteMany(e){let t=0;try{for(let n of e)this._store.delete(n)&&(t+=1)}finally{t>0&&(this._version+=1)}return t}clear(){let e=this._store.size;return e===0?0:(this._store.clear(),this._version+=1,e)}pruneExpired(){let e=K(),t=0;for(let[n,s]of this._store)this._isExpired(s,e)&&(this._store.delete(n),t+=1);return t>0&&(this._version+=1),t}toMap(){let e=K(),t=new Map;for(let[n,s]of this._store)this._isExpired(s,e)||t.set(n,s.value);return t}_resolveExpiresAt(e){let t=e??this._defaultTtl;if(t!==void 0){if(!Number.isFinite(t)||t<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${t})`);return K()+t*1e9}}_isExpired(e,t){return e.expiresAt===void 0?!1:(t??K())>=e.expiresAt}_touchLru(e,t){this._store.delete(e),this._store.set(e,t)}_evictLruWhileOver(){if(this._maxSize!==void 0)for(;this._store.size>this._maxSize;){let e=this._store.keys().next().value;if(e===void 0)break;this._store.delete(e)}}};function ut(r={}){let{name:e,maxSize:t,defaultTtl:n,versioning:s,backend:o,retention:i}=r;if(i&&t!==void 0)throw new RangeError("reactiveMap: `maxSize` (LRU) and `retention` (score-based) are mutually exclusive. Pick one eviction policy.");if(i&&i.archiveThreshold===void 0&&i.maxSize===void 0)throw new RangeError("reactiveMap: `retention` requires at least one of `archiveThreshold` or `maxSize` to trigger archival.");let a=o??new vn({maxSize:t,defaultTtl:n}),d=V(a.toMap(),{name:e,describeKind:"state",equals:(l,h)=>l===h,...s!=null?{versioning:s}:{}});function u(){let l=a.toMap();U(()=>{d.down([[Q]]),d.down([[D,l]])})}function c(){if(!i)return;let l=a.toMap(),h=i.archiveThreshold,f=i.maxSize,b=[];for(let[T,v]of l)b.push({key:T,value:v,score:i.score(T,v)});b.sort((T,v)=>T.score-v.score);let m=new Set;if(h!==void 0)for(let T of b)if(T.score<h)m.add(T.key);else break;if(f!==void 0&&b.length-m.size>f)for(let T of b){if(b.length-m.size<=f)break;m.has(T.key)||m.add(T.key)}if(m.size!==0)for(let T of b)m.has(T.key)&&(i.onArchive?.(T.key,T.value,T.score),a.delete(T.key))}function p(l,h="mutation"){let f=a.version;try{return l()}finally{a.version!==f&&(h==="mutation"&&c(),u())}}return{entries:d,has(l){return p(()=>a.has(l),"read")},get(l){return p(()=>a.get(l),"read")},set(l,h,f){p(()=>a.set(l,h,f?.ttl))},setMany(l,h){p(()=>a.setMany(l,h?.ttl))},delete(l){p(()=>a.delete(l))},deleteMany(l){p(()=>a.deleteMany(l))},clear(){p(()=>a.clear())},pruneExpired(){p(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}Pe();function Co(r){let e=ut({name:r?.name??"effectiveness-entries"}),t=G([e.entries],([i])=>new Map(i),{name:`${r?.name??"effectiveness"}-snapshot`,equals:(i,a)=>{let d=i,u=a;if(d.size!==u.size)return!1;for(let[c,p]of d){let l=u.get(c);if(!l||p.attempts!==l.attempts||p.successes!==l.successes)return!1}return!0}});function n(i,a){let d=e.get(i),u=(d?.attempts??0)+1,c=(d?.successes??0)+(a?1:0);e.set(i,{key:i,attempts:u,successes:c,successRate:c/u})}function s(i){return e.get(i)}let o=de(t);return{node:t,record:n,lookup:s,dispose:()=>{o(),e.dispose()}}}Me();te();te();Me();Oe();be();Ie();te();At();Me();Oe();tt();be();rt();Ie();te();Oe();function Tn(r,e){if(Object.is(r,e))return!0;if(r==null||e==null||typeof r!="object"||typeof e!="object")return!1;if(Array.isArray(r)){if(!Array.isArray(e)||r.length!==e.length)return!1;for(let o=0;o<r.length;o++)if(!Tn(r[o],e[o]))return!1;return!0}if(Array.isArray(e))return!1;let t=Object.keys(r),n=Object.keys(e);if(t.length!==n.length)return!1;let s=new Set(n);for(let o of t)if(!s.has(o)||!Tn(r[o],e[o]))return!1;return!0}function lr(r,e){return`${r}\0${e}`}function _n(r,e){let t=[],n=new Set(r.subgraphs),s=new Set(e.subgraphs),o=[];for(let m of s)n.has(m)||o.push(m);o.sort();for(let m of o)t.push({type:"subgraph-mounted",path:m});let i=new Set(Object.keys(r.nodes)),a=new Set(Object.keys(e.nodes)),d=[];for(let m of a)i.has(m)||d.push(m);d.sort();for(let m of d)t.push({type:"node-added",path:m,node:{...e.nodes[m]}});let u=[];for(let m of a){if(!i.has(m))continue;let T=r.nodes[m]?.meta,v=e.nodes[m]?.meta;T==null&&v==null||Tn(T??{},v??{})||u.push(m)}u.sort();for(let m of u)t.push({type:"node-meta-changed",path:m,prevMeta:r.nodes[m]?.meta??{},nextMeta:e.nodes[m]?.meta??{}});let c=new Map;for(let m of r.edges)c.set(lr(m.from,m.to),m);let p=new Map;for(let m of e.edges)p.set(lr(m.from,m.to),m);let l=[];for(let[m,T]of p)c.has(m)||l.push(T);l.sort((m,T)=>m.from<T.from?-1:m.from>T.from?1:m.to<T.to?-1:m.to>T.to?1:0);for(let m of l)t.push({type:"edge-added",from:m.from,to:m.to});let h=[];for(let[m,T]of c)p.has(m)||h.push(T);h.sort((m,T)=>m.from<T.from?-1:m.from>T.from?1:m.to<T.to?-1:m.to>T.to?1:0);for(let m of h)t.push({type:"edge-removed",from:m.from,to:m.to});let f=[];for(let m of i)a.has(m)||f.push(m);f.sort();for(let m of f)t.push({type:"node-removed",path:m});let b=[];for(let m of n)s.has(m)||b.push(m);b.sort();for(let m of b)t.push({type:"subgraph-unmounted",path:m});return{events:t,flushedAt_ns:K()}}Pe();fr();pr();on();function hr(r,e,t,n={}){let s=e in r.nodes,o=t in r.nodes;if(!s)return $t(e,t,"no-such-from");if(!o)return $t(e,t,"no-such-to");let i=n.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===t){if(n.findCycle===!0){let u=Do(r,e,n);if(u!=null)return u}let d=Vt(e,r.nodes[e],0,n);return jt(e,t,[d])}if(i===0)return $t(e,t,"no-path");let a=mr(r,e,t,i);return a.found?jt(e,t,gr(r,a.pathOrder,n)):$t(e,t,a.truncated?"max-depth-exceeded":"no-path")}function mr(r,e,t,n){let s=new Map,o=[{path:t,depth:0}],i=new Set([t]),a=0,d=!1;for(;a<o.length;){let p=o[a++];if(p.path===e)break;if(n!=null&&p.depth>=n){let b=r.nodes[p.path];b?.deps&&b.deps.length>0&&(d=!0);continue}let l=r.nodes[p.path];if(l==null)continue;let h=l.deps??[],f=new Map;for(let b=0;b<h.length;b++){let m=h[b];if(!m)continue;let T=f.get(m);T==null&&(T=[],f.set(m,T)),T.push(b)}for(let[b,m]of f)i.has(b)||(i.add(b),s.set(b,{from:p.path,depIndices:m}),o.push({path:b,depth:p.depth+1}))}if(!s.has(e))return{found:!1,pathOrder:[],truncated:d};let u=[{path:e}],c=e;for(;c!==t;){let p=s.get(c);if(p==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=p.depIndices,u.push({path:p.from}),c=p.from}return{found:!0,pathOrder:u,truncated:!1}}function Do(r,e,t){let n=r.nodes[e];if(n==null)return null;let s=n.deps??[],o=[];for(let a=0;a<s.length;a++)s[a]===e&&o.push(a);if(o.length>0){let a=Vt(e,n,0,t);a.dep_index=o[0];let d=Vt(e,n,1,t);return jt(e,e,[a,d])}let i=null;for(let a=0;a<s.length;a++){let d=s[a];if(!d||d===e)continue;let u=mr(r,d,e,t.maxDepth);u.found&&(i==null||u.pathOrder.length<i.pathOrder.length)&&(i=u,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...u.pathOrder],truncated:!1})}return i==null?null:jt(e,e,gr(r,i.pathOrder,t))}function gr(r,e,t){return e.map((n,s)=>{let o=r.nodes[n.path],i=Vt(n.path,o,s,t);return n.depIndices!=null&&n.depIndices.length>0&&(i.dep_index=n.depIndices[0],n.depIndices.length>1&&(i.dep_indices=[...n.depIndices])),i})}function Vt(r,e,t,n){let s={path:r,type:e.type,hop:t};e.status!==void 0&&(s.status=e.status),"value"in e&&(s.value=e.value),e.v!=null&&(s.v=e.v);let o=n.annotations?.get(r)??e.annotation;o!=null&&(s.annotation=o);let i=n.lastMutations?.get(r)??e.lastMutation;return i!=null&&(s.lastMutation=i),s}function jt(r,e,t){return br(r,e,!0,"ok",t)}function $t(r,e,t){return br(r,e,!1,t,[])}function br(r,e,t,n,s){let o=Mo(r,e,t,n,s);return{from:r,to:e,found:t,reason:n,steps:s,text:o,toJSON(){return{from:r,to:e,found:t,reason:n,steps:s}}}}function Mo(r,e,t,n,s){if(!t)switch(n){case"no-such-from":return`explainPath: no node named "${r}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${r}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${r}" to "${e}"`}let o=[`Causal path: ${r} \u2192 ${e} (${s.length} step(s))`];for(let i of s){let d=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(o.push(d),"value"in i&&o.push(` value: ${Io(i.value)}`),i.annotation!=null&&o.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let u=i.lastMutation.actor;o.push(` actor: ${u.type}${u.id?`:${u.id}`:""}`)}}return o.join(`
43
- `)}function Io(r){if(r===void 0)return"<sentinel>";if(r===null)return"null";if(typeof r=="string")return JSON.stringify(r);if(typeof r=="number"||typeof r=="boolean"||typeof r=="bigint")return String(r);try{let e=JSON.stringify(r);return e.length>80?`${e.slice(0,77)}...`:e}catch{return String(r)}}Ie();var se={object:56,array:64,string:40,number:8,boolean:4,null:0,undefined:0,symbol:40,bigint:16,function:120,map:72,set:72,mapEntry:40,setEntry:24,date:24,regexp:48,error:64,url:80,promise:48,weakmap:40,weakset:40},Go=Symbol.for("sizeof");function yr(r){let e=new WeakSet,t=new WeakSet,n=[r],s=0;for(;n.length>0;){let o=n.pop();s+=Po(o,e,t,n)}return s}function Po(r,e,t,n){if(r==null)return 0;switch(typeof r){case"number":return se.number;case"boolean":return se.boolean;case"string":return se.string+r.length*2;case"bigint":return se.bigint+Lo(r);case"symbol":return se.symbol;case"function":return e.has(r)?0:(e.add(r),se.function);case"undefined":return 0}let o=r;if(e.has(o))return 0;e.add(o);let i=o[Go];if(typeof i=="function")try{let u=i.call(o);if(typeof u=="number"&&Number.isFinite(u))return u}catch{}if(o instanceof Date)return se.date;if(o instanceof RegExp)return se.regexp+o.source.length*2;if(o instanceof Error){let u=o.message?o.message.length*2:0,c=o.stack?o.stack.length*2:0;return se.error+u+c}if(typeof URL<"u"&&o instanceof URL)return se.url+o.href.length*2;if(typeof Promise<"u"&&o instanceof Promise)return se.promise;if(o instanceof WeakMap)return se.weakmap;if(o instanceof WeakSet)return se.weakset;if(o instanceof Map){let u=se.map;for(let[c,p]of o)u+=se.mapEntry,n.push(c),n.push(p);return u}if(o instanceof Set){let u=se.set;for(let c of o)u+=se.setEntry,n.push(c);return u}if(Array.isArray(o)){let u=se.array+o.length*8;for(let c of o)n.push(c);return u}if(o instanceof ArrayBuffer)return t.has(o)?0:(t.add(o),o.byteLength);if(ArrayBuffer.isView(o)){let u=o;return t.has(u.buffer)?48:(t.add(u.buffer),u.buffer.byteLength+48)}let a=se.object,d=Object.keys(o);for(let u of d){a+=se.string+u.length*2;try{n.push(o[u])}catch{}}return a}function Lo(r){let e=r<0n?-r:r;if(e===0n)return 0;let t=e.toString(2).length;return Math.ceil(t/32)*8}function zt(r,e){let t=e?.topN??10,n=r.describe({detail:"standard"}),s=[],o=r._collectObserveTargets;typeof o=="function"&&o.call(r,"",s);let i=new Map;for(let[l,h]of s)i.set(l,h);let a=[];for(let[l,h]of Object.entries(n.nodes)){let f=i.get(l),b=f instanceof oe?f:null,m=b?yr(b.cache):0,T=b?b._sinkCount:0,v=h.deps?.length??0,g=h.type==="effect"&&T===0,_=T===0?h.type==="effect"?"orphan-effect":h.type==="derived"?"idle-derived":h.type==="producer"?"idle-producer":null:null;a.push({path:l,type:h.type,status:h.status??"unknown",valueSizeBytes:m,subscriberCount:T,depCount:v,isOrphanEffect:g,orphanKind:_})}let d=a.reduce((l,h)=>l+h.valueSizeBytes,0),u=(l,h)=>[...a].sort(h??((f,b)=>b[l]-f[l])).slice(0,t),c=a.filter(l=>l.orphanKind!=null),p=a.filter(l=>l.isOrphanEffect);return{nodeCount:a.length,edgeCount:n.edges.length,subgraphCount:n.subgraphs.length,nodes:a,totalValueSizeBytes:d,hotspots:{byValueSize:u("valueSizeBytes"),bySubscriberCount:u("subscriberCount"),byDepCount:u("depCount")},orphans:c,orphanEffects:p}}var J="::",Ce="__meta__",Je=1;function vr(r,e){let t=Math.max(16,r.size*4),n=0;for(;r.size>0;){if(n++>=t){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${t}); ${r.size} disposer(s) discarded`),r.clear();return}let s=r.values().next();if(s.done)return;let o=s.value;r.delete(o);try{o()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function Nr(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"&&typeof r.down=="function"}function Fo(r){if(r!=null)return Nr(r)?r.cache:r}function Ye(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"&&typeof r.down=="function"}function je(r){return Ye(r)?r.cache??"":r}function Tr(r){return Ye(r)?r.cache??0:r}function _r(r){return Ye(r)?r.cache??!1:r}function $o(r){let e=[];for(let t of Object.keys(r).sort()){let n=r[t].v;n!=null&&e.push(`${t} ${n.id} ${n.version}`)}return e.join(`
44
- `)}function wr(r){if(r.version!==Je)throw new Error(`unsupported snapshot version ${String(r.version)} (expected ${Je})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in r))throw new Error(`snapshot missing required key "${e}"`);if(typeof r.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof r.nodes!="object"||r.nodes===null||Array.isArray(r.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(r.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(r.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function Vo(r,e){let t=new WeakMap,n=(s,o)=>{if(Object.is(s,o))return!0;if(s==null||o==null||typeof s!="object"||typeof o!="object")return!1;let i=t.get(s);if(i==null&&(i=new WeakSet,t.set(s,i)),i.has(o))return!0;i.add(o);let a=s.constructor,d=o.constructor;if(a!==d)return!1;if(s instanceof Date)return s.getTime()===o.getTime();if(s instanceof RegExp)return s.source===o.source&&s.flags===o.flags;if(Array.isArray(s)){let l=o;if(s.length!==l.length)return!1;for(let h=0;h<s.length;h++)if(!n(s[h],l[h]))return!1;return!0}if(s instanceof Map){let l=o;if(s.size!==l.size)return!1;for(let[h,f]of s)if(!l.has(h)||!n(f,l.get(h)))return!1;return!0}if(s instanceof Set){let l=o;if(s.size!==l.size)return!1;for(let h of s){let f=!1;for(let b of l)if(n(h,b)){f=!0;break}if(!f)return!1}return!0}if(ArrayBuffer.isView(s)){let l=s,h=o;if(l.length!==h.length)return!1;for(let f=0;f<l.length;f++)if(l[f]!==h[f])return!1;return!0}let u=Object.keys(s),c=Object.keys(o);if(u.length!==c.length)return!1;let p=new Set(c);for(let l of u)if(!p.has(l)||!n(s[l],o[l]))return!1;return!0};return n(r,e)}function jo(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ht(r){let e="^";for(let t=0;t<r.length;t+=1){let n=r[t];if(n==="*"){e+=".*";continue}if(n==="?"){e+=".";continue}if(n==="["){let s=r.indexOf("]",t+1);if(s<=t+1){e+="\\[";continue}let o=r.slice(t+1,s);o.startsWith("!")&&(o=`^${o.slice(1)}`),o=o.replace(/\\/g,"\\\\"),e+=`[${o}]`,t=s;continue}e+=jo(n)}return e+="$",new RegExp(e)}var zo={data:"\x1B[32m",dirty:"\x1B[33m",resolved:"\x1B[36m",invalidate:"\x1B[93m",pause:"\x1B[90m",resume:"\x1B[96m",complete:"\x1B[34m",error:"\x1B[31m",teardown:"\x1B[91m",derived:"\x1B[35m",path:"\x1B[90m",reset:"\x1B[0m"},Ho={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function wn(r){if(typeof r=="string")return JSON.stringify(r);if(typeof r=="number"||typeof r=="boolean"||r==null)return String(r);try{return JSON.stringify(r)}catch{return"[unserializable]"}}function Bo(r){return r==="none"?Ho:r==="ansi"||r==null?zo:{data:r.data??"",dirty:r.dirty??"",resolved:r.resolved??"",invalidate:r.invalidate??"",pause:r.pause??"",resume:r.resume??"",complete:r.complete??"",error:r.error??"",teardown:r.teardown??"",derived:r.derived??"",path:r.path??"",reset:r.reset??""}}function xr(r){if(r==null)return{};let e=r.detail;return e==="full"?{...r,structured:r.structured??!0,timeline:r.timeline??!0,causal:r.causal??!0,derived:r.derived??!0}:e==="minimal"?{...r,structured:r.structured??!0}:r.format==="stage-log"?{...r,structured:r.structured??!0,timeline:r.timeline??!0}:r}function qo(r,e,t){for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);if(s<32||s===127)throw new Error(`Graph "${e}": ${t} "${r}" must not contain control character (U+${s.toString(16).padStart(4,"0").toUpperCase()} at index ${n})`)}}function xn(r,e,t){if(r==="")throw new Error(`Graph "${e}": ${t} name must be non-empty`);if(r.includes(J))throw new Error(`Graph "${e}": ${t} "${r}" must not contain '${J}' (path separator)`);if(r===Ce)throw new Error(`Graph "${e}": ${t} name "${Ce}" is reserved for meta companion paths`);qo(r,e,t)}function Uo(r,e){if(r==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let t=r.split(J);for(let n of t)if(n==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return t}function Ko(r,e){let t=!1;for(let s of r)if(!e.isMetaPassthrough(s[0])){t=!0;break}return t?r.filter(s=>e.isMetaPassthrough(s[0])):r}function Er(r){for(let e of r._mounts.values())Er(e);for(let e of r._nodes.values())try{e.down([[pe]],{internal:!0})}catch{}}var ce=class r{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_destroyed=!1;_topology;_topologyEmitters=new Set;_factory;_factoryArgs;constructor(e,t){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(J))throw new Error(`Graph name must not contain '${J}' (got "${e}")`);if(e===Ce)throw new Error(`Graph name "${Ce}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...t??{}}),this.config=t?.config??nt,this._traceRing=new bt(t?.traceCapacity??1e3),t?.versioning!=null&&this.setVersioning(t.versioning),typeof t?.factory=="string"&&(this._factory=t.factory,t.factoryArgs!==void 0&&(this._factoryArgs=t.factoryArgs))}tagFactory(e,t){return this._factory=e,this._factoryArgs=t,this}ancestors(e=!0){let t=[],n=e?this:this._parent;for(;n!=null;)t.push(n),n=n._parent;return t}get topology(){return this._topology==null&&(this._topology=ue(e=>{let t=n=>{e.emit(n)};return this._topologyEmitters.add(t),()=>{this._topologyEmitters.delete(t)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let t of this._topologyEmitters)t(e)}nameOf(e){return this._nodeToName.get(e)}add(e,t){let n=e.name,s=t?.name??n;if(s==null||s==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let o=s,i=t?.annotation;if(xn(o,this.name,"add"),this._mounts.has(o))throw new Error(`Graph "${this.name}": name "${o}" is already a mount point`);if(this._nodes.has(o))throw new Error(`Graph "${this.name}": node "${o}" already exists`);let a=this._nodeToName.get(e);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(o,e),this._nodeToName.set(e,o),this._emitTopology({kind:"added",name:o,nodeKind:"node"}),i!=null&&(this._annotations.set(o,i),this.config.inspectorEnabled&&this._traceRing.push({path:o,annotation:i,timestamp_ns:K()})),e}setVersioning(e){if(e!=null)for(let t of this._nodes.values())t instanceof oe&&t._applyVersioning(e)}remove(e){xn(e,this.name,"remove");let t=this._mounts.get(e);if(t){let o={kind:"mount",nodes:[],mounts:[]},i=[];t._collectObserveTargets("",i);for(let[a,d]of i)a.includes(`${J}${Ce}${J}`)||o.nodes.push(a);return o.nodes.sort(),o.mounts.push(e),o.mounts.push(...t._collectSubgraphs(`${e}${J}`)),this._mounts.delete(e),t._parent=void 0,Er(t),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:o}),o}let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(n),n.down([[pe]],{internal:!0});let s={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:s}),s}removeAll(e){let t=typeof e=="function"?e:(()=>{let o=Ht(e);return i=>o.test(i)})(),n={kind:"mount",nodes:[],mounts:[]},s=[...this._nodes.keys(),...this._mounts.keys()].filter(o=>t(o));for(let o of s){let i=this.remove(o);n.nodes.push(...i.nodes),n.mounts.push(...i.mounts)}return n.nodes.sort(),n.mounts.sort(),n}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),t=this._nodes,n=0;return{[Symbol.iterator](){return this},next(){if(n>=e.length)return{value:void 0,done:!0};let s=e[n++];return{value:[s,t.get(s)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(J))return this.resolve(e);let t=this._nodes.get(e);if(!t)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return t}get(e){return this.node(e).cache}set(e,t,n){let s=n?.internal===!0;this.node(e).down([[D,t]],{actor:n?.actor,internal:s,delivery:"write"})}setAll(e,t){let n=Symbol.iterator in e?e:Object.entries(e);U(()=>{for(let[s,o]of n)this.set(s,o,t)})}invalidate(e,t){let n=t?.internal===!0;this.node(e).down([[Re]],{actor:t?.actor,internal:n,delivery:"write"})}error(e,t,n){let s=n?.internal===!0;this.node(e).down([[I,t]],{actor:n?.actor,internal:s,delivery:"write"})}complete(e,t){let n=t?.internal===!0;this.node(e).down([[$]],{actor:t?.actor,internal:n,delivery:"write"})}edges(e){let t=e?.recursive===!0,n=new Map;if(!t){for(let[d,u]of this._nodes)n.set(u,d);let a=[];for(let[d,u]of this._nodes)if(u instanceof oe)for(let c of u._deps){let p=n.get(c.node);p!=null&&a.push([p,d])}return a.sort((d,u)=>d[0]<u[0]?-1:d[0]>u[0]?1:d[1]<u[1]?-1:d[1]>u[1]?1:0),a}let s=[];this._collectObserveTargets("",s);let o=new Map;for(let[a,d]of s)o.set(d,a);let i=[];for(let[a,d]of s)if(d instanceof oe)for(let u of d._deps){let c=o.get(u.node);c!=null&&i.push([c,a])}return i.sort((a,d)=>a[0]<d[0]?-1:a[0]>d[0]?1:a[1]<d[1]?-1:a[1]>d[1]?1:0),i}mount(e,t){if(t===void 0){let s=new r(e);return this.mount(e,s)}if(typeof t=="function"){let s=new r(e);return t(s),this.mount(e,s)}let n=t;if(xn(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(n===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(n._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${n._parent.name}"`);for(let s=this;s!=null;s=s._parent)if(s===n)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,n),n._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),n}resolve(e){let t=Uo(e,this.name);return this._resolveFromSegments(t)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let t=e;if(t[0]===this.name&&(t=t.slice(1),t.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let n=t[0],s=t.slice(1);if(s.length===0){let a=this._nodes.get(n);if(a)return a;throw this._mounts.has(n)?new Error(`Graph "${this.name}": path ends at subgraph "${n}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${n}"`)}let o=this._nodes.get(n);if(o&&s.length>0&&s[0]===Ce)return this._resolveMetaChainFromNode(o,s,t.join(J));let i=this._mounts.get(n);if(!i)throw this._nodes.has(n)?new Error(`Graph "${this.name}": "${n}" is a node; trailing path "${s.join(J)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${n}"`);return i.resolve(s.join(J))}_resolveMetaChainFromNode(e,t,n){let s=e,o=0,i=[...t];for(;o<i.length;){if(i[o]!==Ce)throw new Error(`Graph "${this.name}": expected ${Ce} segment in meta path "${n}"`);if(o+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${Ce} in "${n}"`);let a=i[o+1],d=s.meta[a];if(!d)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${n}"`);s=d,o+=2}return s}signal(e,t){if(t?.internal!==!0){for(let s of e)if(this.config.messageTier(s[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let n=[];if(this._signalDeliver(e,t??{},new Set,n),n.length>0)throw n[0]}_signalDeliver(e,t,n,s){for(let d of this._mounts.values())d._signalDeliver(e,t,n,s);let i=t.internal===!0?{internal:!0}:{actor:t.actor,delivery:"signal"},a=Ko(e,this.config);for(let d of[...this._nodes.keys()].sort()){let u=this._nodes.get(d);if(!n.has(u)){n.add(u);try{u.down(e,i)}catch(c){if(c instanceof Se)throw c;s.push(c)}a.length!==0&&this._signalMetaSubtree(u,a,n,i,s)}}}_signalMetaSubtree(e,t,n,s,o){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!n.has(a)){n.add(a);try{a.down(t,s)}catch(d){if(d instanceof Se)throw d;o.push(d)}this._signalMetaSubtree(a,t,n,s,o)}}}describe(e){if(e?.reactive==="diff")return this._describeReactiveDiff(e);if(e?.reactive===!0)return this._describeReactive(e);let t=Fo(e?.actor),n=e?.filter;if(e?.detail!=null&&e?.fields!=null)throw new TypeError("Graph.describe(): pass either `detail` or `fields`, not both. `detail: 'spec'` is the canonical spec projection; use `fields` only when you need a custom subset.");let s=Mt(e?.detail,e?.fields),o=e?.detail==="spec",i=s,a=[];this._collectObserveTargets("",a);let d=new Map;for(let[_,w]of a)d.set(w,_);let u=[];{let _=a.map(([,y])=>y),w=new Set(d.values()),E=0;for(;_.length>0;){let y=_.shift();if(y instanceof oe)for(let x of y._deps){let k=x.node;if(d.has(k))continue;let S=k.name??"",N=S;if(!N||w.has(N))if(S){let P=2;for(;w.has(`${S}#${P}`);)P++;N=`${S}#${P}`}else for(N=`__internal__/${E++}`;w.has(N);)N=`__internal__/${E++}`;d.set(k,N),w.add(N),u.push([N,k]),_.push(k)}}}let c=[...a,...u],p={};for(let[_,w]of c){if(t!=null&&!w.allowsObserve(t))continue;let E=hn(w,i,o),y=w instanceof oe?w._deps.map(N=>d.get(N.node)??N.node.name??""):[],{name:x,...k}=E,S={...k,deps:y};if(!o){let N=this._annotations.get(_);N!=null&&(S.annotation=N)}if(n!=null)if(typeof n=="function"){let N=n;if(!(N.length>=2?N(_,S):N(S)))continue}else{let N=!0;for(let[P,H]of Object.entries(n)){let F=P==="deps_includes"?"depsIncludes":P==="meta_has"?"metaHas":P;if(F==="depsIncludes"){if(!S.deps.includes(String(H))){N=!1;break}continue}if(F==="metaHas"){if(!Object.hasOwn(S.meta??{},String(H))){N=!1;break}continue}if(S[F]!==H){N=!1;break}}if(!N)continue}p[_]=S}let l=new Set(Object.keys(p)),h=[];for(let[_,w]of c)if(w instanceof oe)for(let E of w._deps){let y=d.get(E.node);y!=null&&h.push([y,_])}h.sort((_,w)=>_[0]<w[0]?-1:_[0]>w[0]?1:_[1]<w[1]?-1:_[1]>w[1]?1:0);let f=h.map(([_,w])=>({from:_,to:w}));(t!=null||n!=null)&&(f=f.filter(_=>l.has(_.from)&&l.has(_.to)));let b=this._collectSubgraphs(""),m=t!=null||n!=null?b.filter(_=>{let w=`${_}${J}`;return[...l].some(E=>E===_||E.startsWith(w))}):b,T=this,v=e;return{name:this.name,nodes:p,edges:f,subgraphs:m,...this._factory!==void 0?{factory:this._factory}:{},...this._factoryArgs!==void 0?{factoryArgs:this._factoryArgs}:{},expand(_){let w={...v};return Array.isArray(_)?(w.fields=_,w.detail=void 0):(w.detail=_,w.fields=void 0),T.describe(w)}}}_collectSubgraphs(e){let t=[];for(let n of[...this._mounts.keys()].sort()){let s=e===""?n:`${e}${n}`;t.push(s),t.push(...this._mounts.get(n)._collectSubgraphs(`${s}${J}`))}return t}resourceProfile(e){return zt(this,e)}reachable(e,t,n={}){return n.withDetail===!0?Nn(this.describe(),e,t,{...n,withDetail:!0}):Nn(this.describe(),e,t,n)}explain(e,t,n){return n?.reactive===!0?this._explainReactive(e,t,n):this._explainStatic(je(e),je(t),{...n?.maxDepth!==void 0?{maxDepth:Tr(n.maxDepth)}:{},...n?.findCycle!==void 0?{findCycle:_r(n.findCycle)}:{}})}_explainStatic(e,t,n){let s=this.describe({detail:"full"}),o=new Map(this._annotations),i=new Map;for(let[a,d]of Object.entries(s.nodes))d.lastMutation!=null&&i.set(a,d.lastMutation);return hr(s,e,t,{...n?.maxDepth!=null?{maxDepth:n.maxDepth}:{},...n?.findCycle===!0?{findCycle:!0}:{},annotations:o,lastMutations:i})}_describeReactive(e){let t={...e,reactive:!1},n=e.reactiveName??"describe",s=0,o=V(s,{name:`${n}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,et(()=>{a=!1,!d&&(s+=1,o.emit(s))}))},c=i.onEvent(v=>{let g=v.type;g!=="data"&&g!=="error"&&g!=="complete"&&g!=="teardown"||u()}),p=[],l=new WeakSet,h=v=>{if(l.has(v)||d)return;l.add(v);let g=v.topology.subscribe(_=>{for(let w of _){if(w[0]!==D)continue;let E=w[1];if(u(),E.kind==="added"&&E.nodeKind==="mount"){let y=v._mounts.get(E.name);y!=null&&h(y)}}});p.push(g);for(let _ of v._mounts.keys()){let w=v._mounts.get(_);w!=null&&h(w)}};h(this);let f,b=e.actor;Nr(b)&&(f=b.subscribe(v=>{let g=!1,_=!1;for(let w of v){let E=w[0];E===D?g=!0:(E===$||E===I||E===pe)&&(_=!0)}g&&u(),_&&(f?.(),f=void 0,u())}));let m;try{m=G([o],()=>this.describe(t),{name:n,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(v,g)=>v===g})}catch(v){c(),f?.();for(let g of p)g();throw i.dispose(),v}let T=de(m);return{node:m,dispose(){d=!0,c(),f?.();for(let v of p)v();p.length=0,i.dispose(),T()}}}_describeReactiveDiff(e){let t={...e,reactive:!1},n=e.reactiveName??"describe-diff",s={name:this.name,nodes:{},edges:[],subgraphs:[]},o=this.describe(t),i=_n(s,o),a=V(i,{name:n,meta:{domain:"audit",kind:"describe-diff"},equals:(l,h)=>l===h}),d=this._describeReactive({...e,reactiveName:void 0}),u=!1,c=d.node.subscribe(l=>{if(!u)for(let h of l){if(h[0]!==D)continue;let f=h[1],b=_n(o,f);o=f,b.events.length!==0&&a.emit(b)}}),p=de(a);return{node:a,dispose(){u=!0,c(),d.dispose(),a.down([[pe,"describe-diff disposed"]]),p()}}}_explainReactive(e,t,n){let s=0,o=V(s,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,et(()=>{a=!1,!d&&(s+=1,o.emit(s))}))},c=i.onEvent(v=>{let g=v.type;g!=="data"&&g!=="error"&&g!=="complete"&&g!=="teardown"||u()}),p=[];e!=null&&Ye(e)&&p.push(e),t!=null&&Ye(t)&&p.push(t),n?.maxDepth!=null&&Ye(n.maxDepth)&&p.push(n.maxDepth),n?.findCycle!=null&&Ye(n.findCycle)&&p.push(n.findCycle);let l=()=>{for(let v of p)if(v.cache===void 0)return!1;return!0},h=()=>{let v=je(e),g=je(t);return{from:v,to:g,found:!1,reason:"pending",steps:[],text:"(awaiting reactive args)",toJSON:()=>({from:v,to:g,found:!1,reason:"pending",steps:[]})}},f;try{f=G([o],()=>{if(!l())return h();let v=je(e),g=je(t),_={...n?.maxDepth!==void 0?{maxDepth:Tr(n.maxDepth)}:{},...n?.findCycle!==void 0?{findCycle:_r(n.findCycle)}:{}};return this._explainStatic(v,g,_)},{name:n?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:je(e),to:je(t)},equals:(v,g)=>v.found===g.found&&v.reason===g.reason&&v.steps.length===g.steps.length&&Wo(v.steps,g.steps)})}catch(v){throw c(),i.dispose(),v}let b=de(f),m=[],T=v=>{let g;return g=v.subscribe(_=>{let w=!1,E=!1;for(let y of _){let x=y[0];x===D?w=!0:(x===$||x===I||x===pe)&&(E=!0)}(w||E)&&u(),E&&g&&(g(),g=void 0)}),()=>{g&&(g(),g=void 0)}};for(let v of p)m.push(T(v));return{node:f,dispose(){d=!0,c();for(let v of m)v?.();m.length=0,i.dispose(),b()}}}_pathsMatching(e){let t=Ht(e),n=[];return this._collectObserveTargets("",n),n.map(([s])=>s).filter(s=>t.test(s))}_collectObserveTargets(e,t){for(let n of[...this._mounts.keys()].sort()){let s=e===""?n:`${e}${J}${n}`;this._mounts.get(n)._collectObserveTargets(s,t)}for(let n of[...this._nodes.keys()].sort()){let s=this._nodes.get(n),o=e===""?n:`${e}${J}${n}`;t.push([o,s]),this._appendMetaObserveTargets(o,s,t)}}_appendMetaObserveTargets(e,t,n){for(let s of Object.keys(t.meta).sort()){let o=t.meta[s],i=`${e}${J}${Ce}${J}${s}`;n.push([i,o]),this._appendMetaObserveTargets(i,o,n)}}observe(e,t){let n=typeof e=="string",o=xr(n?t:e);if(o.reactive===!0)return this._observeReactive(n?e:void 0,o);let i=o.structured===!0||o.timeline===!0||o.causal===!0||o.derived===!0||o.detail==="minimal"||o.detail==="full"||o.format!=null,a=o.actor;if(n){let c=e,p=this.resolve(c);if(a!=null&&!p.allowsObserve(a))throw new Se({actor:a,action:"observe",nodeName:c});return i?this._buildStructuredObserver([[c,p]],o,"one"):{subscribe(l){return p.subscribe(l)},up(l){try{p.up?.(l)}catch(h){if(h instanceof Se)return;throw h}}}}let d=[];this._collectObserveTargets("",d),d.sort((c,p)=>c[0]<p[0]?-1:c[0]>p[0]?1:0);let u=a==null?d:d.filter(([,c])=>c.allowsObserve(a));return i?this._buildStructuredObserver(u,o,"all"):{subscribe:c=>{let p=u.map(([l,h])=>h.subscribe(f=>{c(l,f)}));return()=>{for(let l of p)l()}},up:(c,p)=>{try{this.resolve(c).up?.(p)}catch(l){if(l instanceof Se)return;throw l}}}}_observeReactive(e,t){let n=t.tiers,s=n!=null?new Set(n):null,o=t.reactiveName??"observe";return ue(i=>{let a=[],d=!1,u=!1,c=()=>{if(a.length===0||u)return;let b={events:a.slice(),flushedAt_ns:K()};a.length=0,i.emit(b)},p={...t,reactive:!1,structured:!0,timeline:!0},l=e!=null?this.observe(e,p):this.observe(p),h=b=>{u||(a.push(b),!d&&(d=!0,et(()=>{d=!1,c()})))};for(let b of l.events)h(b);let f=l.onEvent(h);return()=>{u=!0,f(),l.dispose()}},{name:o,meta:{domain:"audit",kind:"observe-reactive"}})}_buildStructuredObserver(e,t,n){let s=n==="one"?e[0]?.[0]:void 0,o=i=>{if(n==="one"&&s!=null){let c=this.resolve(s);return this._buildStructuredObserver([[s,c]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((c,p)=>c[0]<p[0]?-1:c[0]>p[0]?1:0);let d=i.actor,u=d==null?a:a.filter(([,c])=>c.allowsObserve(d));return this._buildStructuredObserver(u,i,"all")};return this._createObserveResult(e,t,o)}_createObserveResult(e,t,n){let s=t.timeline===!0,o=t.causal===!0,i=t.derived===!0,a=t.detail==="minimal",d=this.config.inspectorEnabled,u=(o||i)&&d,c=t.maxEvents,p=c!=null&&c>0?new bt(c):null,l=[],h=new Set,f=t.tiers!=null?new Set(t.tiers):null,b={},m=new Set,T=0,v=0,g=0,_=0,w=0,E=0,y=!1,x=!1,k=0,S=new Map,N=new Map,P=new Map,H=C=>{if(!(f!=null&&!f.has(C.type))){p?p.push(C):l.push(C);for(let q of h)q(C)}},F=C=>f==null||f.has(C),ye=()=>s?{timestamp_ns:K(),in_batch:ht(),batch_id:k}:{},ve=(C,q)=>{if(!(!u||!(C instanceof oe)))return C._setInspectorHook(ge=>{if(ge.kind==="dep_message")S.set(C,ge.depIndex);else if(ge.kind==="run"){let Ge=ge.batchData.map((R,M)=>R!=null&&R.length>0?R.at(-1):ge.prevData[M]);N.set(C,Ge);let we=ge.batchData.map(R=>R!=null?[...R]:void 0);P.set(C,we),i&&H({type:"derived",path:q,dep_values:Ge,dep_batches:we,...ye()})}})},ke=C=>{let q=S.get(C),ge=N.get(C);if(!o||ge==null)return{};let we=(q!=null&&q>=0&&C instanceof oe?C._deps[q]:void 0)?.node,R=we?.v,M=P.get(C);return{trigger_dep_index:q,trigger_dep_name:we?.name,...R!=null?{trigger_version:{id:R.id,version:R.version}}:{},dep_values:[...ge],...M!=null?{dep_batches:M}:{}}},Ee=[],j=[];for(let[C,q]of e){let ge=ve(q,C);ge&&Ee.push(ge),j.push(q.subscribe(Ge=>{k++;for(let we of Ge){let R=we[0],M=ye();if(R===D){b[C]=we[1];let Z=q instanceof oe?q.lastMutation?.actor??Qe:Qe;H({type:"data",path:C,data:we[1],actor:Z,...M,...ke(q)})}else if(a)R===Q?F("dirty")&&T++:R===W?F("resolved")&&v++:R===Re?F("invalidate")&&g++:R===De?F("pause")&&_++:R===Ve?F("resume")&&w++:R===pe?F("teardown")&&E++:R===$&&!m.has(C)?F("complete")&&(y=!0):R===I&&F("error")&&(x=!0,m.add(C));else if(R===Q)F("dirty")&&T++,H({type:"dirty",path:C,...M});else if(R===W)F("resolved")&&v++,H({type:"resolved",path:C,...M,...ke(q)});else if(R===Re)F("invalidate")&&g++,H({type:"invalidate",path:C,...M});else if(R===De)F("pause")&&_++,H({type:"pause",path:C,lockId:we[1],...M});else if(R===Ve)F("resume")&&w++,H({type:"resume",path:C,lockId:we[1],...M});else if(R===$)F("complete")&&!m.has(C)&&(y=!0),H({type:"complete",path:C,...M});else if(R===I){F("error")&&(x=!0,m.add(C));let Z=q instanceof oe?q.lastMutation?.actor??Qe:Qe;H({type:"error",path:C,data:we[1],actor:Z,...M})}else R===pe&&(F("teardown")&&E++,H({type:"teardown",path:C,...M}))}}))}let z=!1,L=()=>{if(!z){z=!0;for(let C of j)C();for(let C of Ee)C();for(let C of X)C({value:void 0,done:!0});X.length=0}},ie=[],X=[];h.add(C=>{let q=X.shift();q?q({value:C,done:!1}):ie.push(C)});let me={get values(){return b},get dirtyCount(){return T},get resolvedCount(){return v},get invalidateCount(){return g},get pauseCount(){return _},get resumeCount(){return w},get teardownCount(){return E},get events(){return p?p.toArray():[...l]},get anyCompletedCleanly(){return y},get anyErrored(){return x},get completedWithoutErrors(){return y&&!x},onEvent(C){return h.add(C),()=>h.delete(C)},dispose:L,expand(C){L();let q={...t};return typeof C=="string"?q.detail=C:Object.assign(q,C),n(xr(q))},[Symbol.asyncIterator](){return{next(){return ie.length>0?Promise.resolve({value:ie.shift(),done:!1}):z?Promise.resolve({value:void 0,done:!0}):new Promise(C=>X.push(C))},return(){return L(),Promise.resolve({value:void 0,done:!0})}}}};return t.format!=null&&this._attachFormatLogger(me,t),me}_attachFormatLogger(e,t){let n=t.format;if(n==null)return;let s=t.logger??(f=>console.log(f)),o=t.includeTypes?new Set(t.includeTypes):null,i=t.excludeTypes?new Set(t.excludeTypes):null,a=o==null&&i==null?()=>!0:f=>(o==null||o.has(f))&&(i==null||!i.has(f)),d=Bo(t.theme),u=n==="stage-log"?K():0,c=f=>f==null?"":t.stageLabels?.[f]??f,p=(f,b)=>f.length>b?`${f.slice(0,b-1)}\u2026`:f,l=f=>f.type==="data"||f.type==="error"?p(wn(f.data),120):"",h=f=>{if(n==="stage-log"){let y=(K()-u)/1e9,x=c(f.path).padEnd(9);if(f.type==="data"){let k=l(f);return`[${y.toFixed(3)}s] ${x} \u2190${k?` ${k}`:""}`}if(f.type==="error"){let k=l(f);return`[${y.toFixed(3)}s] ${x} \u2717${k?` ${k}`:""}`}return f.type==="complete"?`[${y.toFixed(3)}s] ${x} \u25A0 complete`:`[${y.toFixed(3)}s] ${x} ${f.type}`}if(n==="json")try{return JSON.stringify(f)}catch{return JSON.stringify({type:f.type,path:f.path,data:"[unserializable]"})}let b=d[f.type]??"",m=f.path?`${d.path}${f.path}${d.reset} `:"",T=f.type==="data"||f.type==="error",v=f.type==="pause"||f.type==="resume",g=T?` ${wn(f.data)}`:v?` ${wn(f.lockId)}`:"",_=f.type==="data"||f.type==="resolved"||f.type==="derived"?f:void 0,w=_?.trigger_dep_name!=null?` <- ${_.trigger_dep_name}`:_?.trigger_dep_index!=null?` <- #${_.trigger_dep_index}`:"",E=f.in_batch?" [batch]":"";return`${m}${b}${f.type.toUpperCase()}${d.reset}${g}${w}${E}`};e.onEvent(f=>{a(f.type)&&s(h(f),f)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){vr(this._disposers,this.name),this.signal([[pe]],{internal:!0}),vr(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}get destroyed(){return this._destroyed}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}snapshot(e){let{expand:t,...n}=this.describe({detail:"full"}),s={};for(let a of Object.keys(n.nodes).sort()){let{lastMutation:d,guard:u,...c}=n.nodes[a];s[a]=c}let o=[...n.subgraphs].sort(),i={...n,version:1,nodes:s,subgraphs:o};if(e?.format==null)return i;if(e.format==="json-string")return JSON.stringify(i);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(e.codec);if(a==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return qn(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,t){let n=t?.config??nt,{codec:s,codecVersion:o,payload:i}=Un(e,n);return s.decode(i,o)}restore(e,t){if(wr(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let n=t?.only==null?null:(Array.isArray(t.only)?t.only:[t.only]).map(o=>Ht(o)),s=t?.includeProducers===!0;for(let o of Object.keys(e.nodes).sort()){if(n!==null&&!n.some(a=>a.test(o)))continue;let i=e.nodes[o];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&t?.onError?.(o,new Error(`restore: slice.value is undefined for "${o}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!s)){if(i.v!=null){let d=this.tryResolve(o)?.v;if(d!=null&&d.id===i.v.id&&d.version===i.v.version)continue}try{this.set(o,i.value)}catch(a){t?.onError?.(o,a)}}}}}static fromSnapshot(e,t){wr(e);let n=typeof t=="function"?t:t?.build,s=typeof t=="function"?void 0:t?.factories,o=new r(e.name);if(n)return n(o),o.restore(e),o;for(let h of[...e.subgraphs].sort((f,b)=>{let m=f.split(J).length,T=b.split(J).length;return m!==T?m-T:f<b?-1:f>b?1:0})){let f=h.split(J),b=o;for(let m of f)b._mounts.has(m)||b.mount(m,new r(m)),b=b._mounts.get(m)}let i=s?Object.entries(s).map(([h,f])=>({re:Ht(h),factory:f})):[],a=h=>{for(let f of i)if(f.re.test(h))return f.factory},d=h=>{let f=h.split(J),b=f.pop();if(b==null||b.length===0)throw new Error(`invalid snapshot path "${h}"`);let m=o;for(let T of f){let v=m._mounts.get(T);if(!v)throw new Error(`unknown mount "${T}" in path "${h}"`);m=v}return[m,b]},u=Object.entries(e.nodes).filter(([h])=>!h.includes(`${J}${Ce}${J}`)).sort((h,f)=>h[0]<f[0]?-1:h[0]>f[0]?1:0),c=new Map(u),p=new Map,l=!0;for(;c.size>0&&l;){l=!1;for(let[h,f]of[...c.entries()]){let b=f?.deps??[];if(!b.every(w=>p.has(w)))continue;let[m,T]=d(h),v={...f?.meta??{}},g=a(h),_;if(f?.type==="state")_=V(f.value,{meta:v});else{if(g==null)continue;_=g(T,{path:h,type:f.type,value:f.value,meta:v,deps:b,resolvedDeps:b.map(w=>p.get(w))})}m.add(_,{name:T}),p.set(h,_),c.delete(h),l=!0}}if(c.size>0){let h=[...c.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${h}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return o.restore(e),o}toJSON(){return this.snapshot()}attachSnapshotStorage(e,t={}){let n=e.map(u=>({tier:u,debounceMs:Math.max(0,u.debounceMs??0),compactEvery:Math.max(1,u.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));t.autoRestore===!0&&this._cascadeRestore(e,t.onError);let s=(u,c)=>{if(u.disposed)return;let p=$o(c.nodes);if(u.lastSnapshot!=null&&p!==""&&p===u.lastFingerprint)return;let l=u.seq+1,h=xe(),m=u.lastSnapshot==null||l%u.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:l,timestamp_ns:h,format_version:Je}:{name:this.name,mode:"diff",diff:kr(u.lastSnapshot,c),seq:l,timestamp_ns:h,format_version:Je};if(u.tier.filter&&!u.tier.filter(m))return;let T;try{T=u.tier.save(m)}catch(v){t.onError?.(v,u.tier);return}if(T&&typeof T.then=="function"){let _=(u.savePending??Promise.resolve()).then(()=>T,()=>T).then(()=>{u.disposed||(u.seq=l,u.lastSnapshot=c,u.lastFingerprint=p)},w=>{t.onError?.(w,u.tier)});u.savePending=_.finally(()=>{u.savePending===_&&(u.savePending=void 0)})}else u.seq=l,u.lastSnapshot=c,u.lastFingerprint=p},o=(u,c)=>{try{s(u,c)}catch(p){t.onError?.(p,u.tier)}},i=(u,c)=>{if(!c.some(f=>{let b=this.config.messageTier(f[0]);return b>=3&&b<5}))return;if(t.filter){let f=this.tryResolve(u);if(f==null)return;let b=hn(f,Mt("standard"));if(!t.filter(u,b))return}let l,h=()=>(l==null&&(l=this.snapshot()),l);for(let f of n)f.disposed||(f.debounceMs===0?o(f,h()):(f.timer==null&&(f.timer=new Ft),f.timer.start(f.debounceMs,()=>{f.disposed||o(f,this.snapshot())})))},a;if(t.paths!=null){let c=(typeof t.paths=="string"?this._pathsMatching(t.paths):t.paths).map(p=>{let l=this.tryResolve(p);return l==null?()=>{}:l.subscribe(h=>i(p,h))});a=()=>{for(let p of c)p()}}else a=this.observe().subscribe((u,c)=>i(u,c));let d=()=>{a();for(let u of n)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(d)};return this._storageDisposers.add(d),{dispose:d}}async _cascadeRestore(e,t){for(let n of e){let s;try{s=await n.load?.()}catch(i){t?.(i,n);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let o=s;try{if(o.mode==="full"&&o.snapshot!=null)return this.restore(o.snapshot),!0;if(o.version===Je&&o.nodes!=null)return this.restore(o),!0}catch(i){t?.(i,n)}}return!1}static async fromStorage(e,t,n){for(let s of t){let o;try{o=await s.load?.()}catch(d){n?.onError?.(d,s);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let i=o,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===Je&&i.nodes!=null?i:void 0;if(a!=null)try{return r.fromSnapshot(a,n)}catch(d){n?.onError?.(d,s)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${t.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,t,n){if(e!=null&&t!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,t),this.config.inspectorEnabled){let s={path:e,annotation:t,timestamp_ns:K(),...n?.actor!=null?{actor:n.actor}:{}};this._traceRing.push(s)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let t=this._traceRing.toArray().filter(s=>!e(s)),n=this._traceRing.size-t.length;this._traceRing.clear();for(let s of t)this._traceRing.push(s);return n}static diff(e,t){let n=new Set(Object.keys(e.nodes)),s=new Set(Object.keys(t.nodes)),o=[...s].filter(v=>!n.has(v)).sort(),i=[...n].filter(v=>!s.has(v)).sort(),a=[],d=[];for(let v of n){if(!s.has(v))continue;let g=e.nodes[v],_=t.nodes[v],w=g.v,E=_.v;w!=null&&E!=null&&w.id===E.id&&w.version!==E.version&&d.push({path:v,id:w.id,from:w.version,to:E.version});let y=w!=null&&E!=null&&w.id===E.id&&w.version===E.version;for(let x of["type","status","sentinel"]){let k=g[x],S=_[x];k!==S&&a.push({path:v,field:x,from:k,to:S})}if(!y)for(let x of["value","meta"]){let k=g[x],S=_[x];Vo(k,S)||a.push({path:v,field:x,from:k,to:S})}}let u=v=>`${v.from} ${v.to}`,c=new Set(e.edges.map(u)),p=new Set(t.edges.map(u)),l=t.edges.filter(v=>!c.has(u(v))),h=e.edges.filter(v=>!p.has(u(v))),f=new Set(e.subgraphs),b=new Set(t.subgraphs),m=[...b].filter(v=>!f.has(v)).sort(),T=[...f].filter(v=>!b.has(v)).sort();return{nodesAdded:o,nodesRemoved:i,nodesChanged:a,versionChanges:d,edgesAdded:l,edgesRemoved:h,subgraphsAdded:m,subgraphsRemoved:T}}};function kr(r,e){let t=ce.diff(r,e),n={};for(let s of t.nodesAdded){let o=e.nodes[s];o!=null&&(n[s]=o)}return{...t,nodesAddedFull:n}}function Nn(r,e,t,n={}){let s={paths:[],depths:new Map,truncated:!1};if(!e)return n.withDetail?s:[];if(!n.both&&t!=="upstream"&&t!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let o=n.maxDepth;if(o!=null&&(!Number.isInteger(o)||o<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(o===0)return n.withDetail?s:[];let i=new Map,a=new Map,d=new Map,u=new Map,c=new Set;for(let[g,_]of Object.entries(r.nodes)){if(!g)continue;c.add(g);let w=_.deps??[];i.set(g,w);for(let E of w)E&&(c.add(E),a.has(E)||a.set(E,new Set),a.get(E).add(g))}for(let g of r.edges){if(g==null||typeof g!="object")continue;let _=typeof g.from=="string"?g.from:"",w=typeof g.to=="string"?g.to:"";!_||!w||(c.add(_),c.add(w),u.has(_)||u.set(_,new Set),u.get(_).add(w),d.has(w)||d.set(w,new Set),d.get(w).add(_))}if(!c.has(e))return n.withDetail?s:[];let p=n.both===!0,l=g=>{if(p){let y=i.get(g)??[],x=d.get(g),k=a.get(g),S=u.get(g),N=[...y];return x&&N.push(...x),k&&N.push(...k),S&&N.push(...S),N}if(t==="upstream"){let y=i.get(g)??[],x=d.get(g);return x?[...y,...x]:y}let _=a.get(g),w=u.get(g),E=_?[..._]:[];return w&&E.push(...w),E},h=new Set([e]),f=new Map,b=[{path:e,depth:0}],m=0,T=!1;for(;m<b.length;){let g=b[m++];if(o!=null&&g.depth>=o){l(g.path).length>0&&(T=!0);continue}for(let _ of l(g.path))!_||h.has(_)||(h.add(_),f.set(_,g.depth+1),b.push({path:_,depth:g.depth+1}))}let v=[...f.keys()].sort((g,_)=>g<_?-1:g>_?1:0);return n.withDetail?{paths:v,depths:f,truncated:T}:v}function Wo(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],s=e[t];if(n.path!==s.path||n.type!==s.type||n.status!==s.status||n.hop!==s.hop||n.dep_index!==s.dep_index||n.annotation!==s.annotation||n.value!==s.value||n.lastMutation!==s.lastMutation)return!1;let o=n.v,i=s.v;if(o!==i&&(o==null||i==null||o.id!==i.id||o.version!==i.version))return!1}return!0}At();Me();tt();be();rt();te();Ie();yt();Me();be();Ie();te();var En=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=t,t!==void 0){if(this._buf=new Array(t),e&&e.length>0){let n=Math.min(e.length,t),s=e.length-n;for(let o=0;o<n;o++)this._buf[o]=e[s+o];this._size=n}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let t=e>=0?e:this._size+e;if(!(t<0||t>=this._size))return this._maxSize!==void 0?this._buf[(this._head+t)%this._maxSize]:this._buf[t]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let t=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let n=t;n<e.length;n++)this._rawAppend(e[n]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let t=0;t<e;t++)this._buf[(this._head+t)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let t=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,t);else{for(let n=0;n<t;n++)this._buf[(this._head+n)%this._maxSize]=void 0;this._head=(this._head+t)%this._maxSize}return this._size-=t,this._version+=1,t}slice(e,t){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${t})`);let n=t===void 0?this._size:Math.min(Math.max(t,0),this._size),s=Math.min(e,this._size);if(s>=n)return[];let o=n-s;if(this._maxSize===void 0)return this._buf.slice(s,n);let i=new Array(o);for(let a=0;a<o;a++)i[a]=this._buf[(this._head+s+a)%this._maxSize];return i}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let t=Math.min(e,this._size);return this.slice(this._size-t,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let t=0;t<this._size;t++)e[t]=this._buf[(this._head+t)%this._maxSize];return e}snapshot(){return this.toArray()}restore(e){if(this._maxSize===void 0){this._buf.length=0;for(let t=0;t<e.length;t++)this._buf.push(e[t]);this._size=this._buf.length}else{let t=this._maxSize;for(let o=0;o<t;o++)this._buf[o]=void 0;this._head=0;let n=Math.min(e.length,t),s=e.length-n;for(let o=0;o<n;o++)this._buf[o]=e[s+o];this._size=n}this._version+=1}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function vt(r){return r.subscribe(()=>{})}var Jo=64;function dt(r,e={}){let{name:t,maxSize:n,versioning:s,guard:o,backend:i}=e,a=i??new En(r,n),d=V(a.toArray(),{name:t,describeKind:"state",equals:(y,x)=>y===x,...s!=null?{versioning:s}:{},...o!=null?{guard:o}:{}});function u(){let y=a.toArray();U(()=>{d.down([[Q]],{internal:!0}),d.down([[D,y]],{internal:!0})})}let c=new Map,p=new Map,l=new Map;function h(y,x){return`${y}:${x===void 0?"END":x}`}function f(y){if(y.size<Jo)return;let x=y.keys().next();if(x.done)return;let k=y.get(x.value);k!==void 0&&k.dispose(),y.delete(x.value)}function b(y){let x=a.version;try{return y()}finally{a.version!==x&&u()}}function m(y){if(!Number.isInteger(y)||y<0)throw new RangeError(`tail: n must be a non-negative integer (got ${y})`);let x=c.get(y);if(x!==void 0)return c.delete(y),c.set(y,x),x.node;f(c);let k=G([d],([N])=>{let P=N;return y===0||P.length===0?[]:P.slice(Math.max(0,P.length-y))},{initial:a.tail(y),describeKind:"derived"}),S=vt(k);return c.set(y,{node:k,dispose:S}),k}function T(y,x){if(!Number.isInteger(y)||y<0)throw new RangeError(`slice: start must be a non-negative integer (got ${y})`);if(x!==void 0&&(!Number.isInteger(x)||x<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${x})`);let k=h(y,x),S=p.get(k);if(S!==void 0)return p.delete(k),p.set(k,S),S.node;f(p);let N=G([d],([H])=>{let F=H;return x===void 0?F.slice(y):F.slice(y,x)},{initial:a.slice(y,x),describeKind:"derived"}),P=vt(N);return p.set(k,{node:N,dispose:P}),N}function v(y){let x=l.get(y);if(x!==void 0)return x.node;let k=G([d,y],([N,P])=>{let H=N,F=Math.max(0,Math.trunc(P??0));return H.slice(F)},{initial:[],describeKind:"derived"}),S=vt(k);return l.set(y,{node:k,dispose:S}),k}let g,_;function w(){g===void 0&&(g=ee([d],(y,x,k)=>{let S=y[0],P=S!=null&&S.length>0?S.at(-1):k.prevData[0];if(P==null||P.length===0){x.down([[W]]);return}x.emit(P[P.length-1])},{name:t!=null?`${t}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),_=G([d],([y])=>y.length>0,{name:t!=null?`${t}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),vt(g),vt(_))}let E={entries:d,get size(){return a.size},at(y){return a.at(y)},append(y){b(()=>a.append(y))},appendMany(y){y.length!==0&&b(()=>a.appendMany(y))},clear(){b(()=>a.clear())},trimHead(y){b(()=>a.trimHead(y))},withLatest(){return w(),d},get lastValue(){return w(),g},get hasLatest(){return w(),_},view(y){switch(y.kind){case"tail":return m(y.n);case"slice":return T(y.start,y.stop);case"fromCursor":return v(y.cursor)}},attach(y){let x=y.subscribe(k=>{for(let S of k)S[0]===D&&E.append(S[1])});return()=>x()},attachStorage(y){if(y.length===0)return()=>{};let x=new Map;for(let S of y)x.set(S,a.size);(async()=>{for(let S of y)if(typeof S.loadEntries=="function")try{let N=await Promise.resolve(S.loadEntries());N.entries.length>0&&a.size===0&&(a.restore(N.entries),x.set(S,N.entries.length),u());break}catch{}})();let k=d.subscribe(S=>{for(let N of S){if(N[0]!==D)continue;let P=N[1];for(let H of y){let F=x.get(H)??0;if(P.length<F){try{let ve=H.appendEntries(P);ve instanceof Promise&&ve.catch(()=>{})}catch{}x.set(H,P.length);continue}if(P.length===F)continue;let ye=P.slice(F);x.set(H,P.length);try{let ve=H.appendEntries(ye);ve instanceof Promise&&ve.catch(()=>{})}catch{}}}});return()=>k()},disposeAllViews(){for(let y of c.values())y.dispose();c.clear();for(let y of p.values())y.dispose();p.clear();for(let y of l.values())y.dispose();l.clear()},dispose(){for(let y of c.values())y.dispose();c.clear();for(let y of p.values())y.dispose();p.clear();for(let y of l.values())y.dispose();l.clear()}};return E}Pe();var Yo=256;function ct(r,e){if(!Number.isFinite(r)||!Number.isInteger(r)||r<0)throw new Error(`${e} must be a non-negative integer`);return r}function He(r,e){return ze("messaging",r,e)}var Qo=1024,kn=class extends ce{_log;events;latest;hasLatest;constructor(e,t={}){super(e,t.graph),this._log=dt([],{name:"events",maxSize:t.retainedLimit??Qo}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=G([this.events],([n])=>{let s=n;return s.length===0?null:s[s.length-1]},{name:"latest",describeKind:"derived",meta:He("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(de(this.latest)),this.hasLatest=G([this.events],([n])=>n.length>0,{name:"hasLatest",describeKind:"derived",meta:He("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(de(this.hasLatest)),this.addDisposer(()=>{this.events.down([[$]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){if(e===void 0)throw new TypeError(`TopicGraph "${this.name}": publish(undefined) is not allowed (spec \xA75.12 SENTINEL).`);this._log.append(e)}attachEventStorage(e){return this._log.attachStorage(e)}retained(){return this.events.cache}get _logBundle(){return this._log}},Bt=class extends ce{cursor;available;topic;_disposed=!1;constructor(e,t,n={}){super(e,n.graph),this.topic=t;let s;if(n.from!==void 0?n.from==="retained"?s=0:n.from==="now"?s=t.events.cache.length:s=ct(n.from,"subscription from"):s=ct(n.cursor??0,"subscription cursor"),this.cursor=V(s,{name:"cursor",describeKind:"state",meta:He("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=t._logBundle.view({kind:"fromCursor",cursor:this.cursor}),this.add(this.available,{name:"available"}),this.addDisposer(de(this.available)),n.advanceOn!==void 0){let o=n.advanceOn,i=!1,a=ee([o],()=>{if(!i){i=!0;return}if(this._disposed)return;let d=this.available.cache;if(d.length===0)return;let u=this.cursor.cache+d.length;this.cursor.emit(u)},{name:"advancePump",describeKind:"effect",meta:He("subscription_advance_pump")});this.add(a,{name:"advancePump"}),this.addDisposer(de(a))}}ack(e){if(this._disposed)return this.cursor.cache;let t=this.available.cache,n=e===void 0?t.length:ct(e,"subscription ack count"),s=Math.min(n,t.length);if(s<=0)return this.cursor.cache;let o=this.cursor.cache+s;return this.cursor.emit(o),o}pull(e){if(this._disposed)return[];let t=this.available.cache,n=e===void 0?t.length:ct(e,"subscription pull limit");return t.slice(0,n)}pullAndAck(e){if(this._disposed)return{items:[],cursor:this.cursor.cache};let t=this.available.cache,n=e===void 0?t.length:ct(e,"subscription pullAndAck limit"),s=t.slice(0,n);if(s.length===0)return{items:s,cursor:this.cursor.cache};let o=this.cursor.cache+s.length;return this.cursor.emit(o),{items:s,cursor:o}}dispose(){this._disposed||(this._disposed=!0,this.cursor.down([[$]]),this.destroy())}},Rn=class extends ce{_sourceSub;bridgedCount;output;constructor(e,t,n,s={}){super(e,s.graph),this._sourceSub=Zo(`${e}-subscription`,t,{cursor:s.cursor}),this.mount("subscription",this._sourceSub);let o=Math.max(1,ct(s.maxPerPump??Yo,"topic bridge maxPerPump")),i=s.map??(l=>l);this.output=G([this._sourceSub.available],([l])=>{let h=l,f=[],b=Math.min(h.length,o);for(let m=0;m<b;m++){let T=i(h[m]);T!==void 0&&f.push(T)}return f},{name:"output",describeKind:"derived",meta:He("topic_bridge_output",{targetRef:n.name}),initial:[]}),this.add(this.output,{name:"output"}),this.addDisposer(de(this.output)),this.bridgedCount=V(0,{name:"bridgedCount",describeKind:"state",meta:He("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"}),this.addDisposer(de(this.bridgedCount));let a=this.output,d=this._sourceSub,u=this.bridgedCount,c=ee([a],()=>{let l=a.cache;if(l.length===0)return;let h=d.available.cache.length,f=Math.min(h,o);if(f>0){d.ack(f);let b=u.cache??0;u.emit(b+l.length)}},{name:"ackPump",describeKind:"effect",meta:He("topic_bridge_ack_pump")});this.add(c,{name:"ackPump"}),this.addDisposer(de(c));let p=Xo(this.output,n);this.addDisposer(p)}};function Xo(r,e){return r.subscribe(t=>{for(let n of t){if(n[0]!==D)continue;let s=n[1];s.length!==0&&U(()=>{for(let o of s)e.publish(o)})}})}var On=class{_map=new Map;version;constructor(e){this.version=e}get size(){return this._map.size}has(e){return this._map.has(e)}get(e){return this._map.get(e)}set(e,t){this._map.set(e,t)}delete(e){return this._map.delete(e)}keys(){return this._map.keys()}},Sn=class extends ce{_registry;version;_defaultTopicOptions;constructor(e,t={}){super(e,t.graph);let n=V(0,{name:"version",describeKind:"state",meta:He("hub_version")});this.add(n,{name:"version"}),this.version=n,this._registry=new On(n),this._defaultTopicOptions={...t.defaultTopicOptions??{}}}get size(){return this._registry.size}has(e){return this._registry.has(e)}topicNames(){return this._registry.keys()}topic(e,t){let n=this._registry.get(e);if(n===void 0){let s={...this._defaultTopicOptions,...t??{}};n=new kn(e,s),this._registry.set(e,n),this.mount(e,n);let o=this.version.cache??0;this.version.emit(o+1)}return n}publish(e,t){this.topic(e).publish(t)}publishMany(e){U(()=>{for(let[t,n]of e)this.topic(t).publish(n)})}subscribe(e,t,n){let s=this.topic(t);return new Bt(e,s,n)}removeTopic(e){if(!this._registry.has(e))return!1;try{this.remove(e)}finally{this._registry.delete(e);let t=this.version.cache??0;this.version.emit(t+1)}return!0}};function qt(r,e){return new Sn(r,e)}function Zo(r,e,t){return new Bt(r,e,t)}function An(r,e,t,n){return new Rn(r,e,t,n)}function es(r){if(typeof r!="object"||r===null)return!1;let e=r;return typeof e.subscribe=="function"&&typeof e.down=="function"&&typeof e.emit=="function"}function ts(r,e){if(r.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(r.length===1){let o=ns(e);return{best:r[0],bestScore:o}}if(e.some(o=>typeof o.candidateIndex=="number")){let o=new Array(r.length);for(let d=0;d<r.length;d++)o[d]={sum:0,count:0};for(let d of e){let u=d.candidateIndex;typeof u=="number"&&u>=0&&u<r.length&&(o[u].sum+=d.score,o[u].count+=1)}let i=r[0],a=o[0].count>0?o[0].sum/o[0].count:Number.NEGATIVE_INFINITY;for(let d=1;d<r.length;d++){let u=o[d].count>0?o[d].sum/o[d].count:Number.NEGATIVE_INFINITY;u>a&&(a=u,i=r[d])}return{best:i,bestScore:a}}let n=r[0],s=e[0]?.score??Number.NEGATIVE_INFINITY;for(let o=1;o<r.length;o++){let i=e[o]?.score??Number.NEGATIVE_INFINITY;i>s&&(s=i,n=r[o])}return{best:n,bestScore:s}}function ns(r){if(r.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let t of r)e+=t.score;return e/r.length}function Rr(r,e,t,n){let s=n.name??"refine-loop",o=new ce(s,n.graph),i=es(n.dataset)?n.dataset:V(n.dataset,{name:"dataset"});o.add(i,{name:"dataset"});let a=V(0,{name:"iteration"});o.add(a,{name:"iteration"});let d=V(t,{name:"strategy",equals:()=>!1});o.add(d,{name:"strategy"});let u=V(null,{name:"lastFeedback"});o.add(u,{name:"lastFeedback"});let c=V([],{name:"prevCandidates"});o.add(c,{name:"prevCandidates"});let p=V(!1,{name:"paused"});o.add(p,{name:"paused"});let l=V("running",{name:"status"});o.add(l,{name:"status"});let h=V([],{name:"history",equals:()=>!1});o.add(h,{name:"history"});let f=V(null,{name:"best"});o.add(f,{name:"best"});let b=V(Number.NEGATIVE_INFINITY,{name:"score"});o.add(b,{name:"score"});let m=V(0,{name:"budget-used"});o.add(m,{name:"budget-used"});let T=qt("stages");o.mount("stages",T);let v=T.topic("generate"),g=T.topic("evaluate"),_=T.topic("analyze"),w=T.topic("decide"),E=t,y=null,x=[];o.addDisposer(d.subscribe(R=>{for(let M of R)M[0]===D&&(E=M[1])})),o.addDisposer(u.subscribe(R=>{for(let M of R)M[0]===D&&(y=M[1])})),o.addDisposer(c.subscribe(R=>{for(let M of R)M[0]===D&&(x=M[1])}));let k=ot(a,R=>{let M=E,Z=R===0||y==null;return ee([],(ae,le)=>{let B=!1;try{let O=Z?M.seed(r):M.generate(y,x);if(O instanceof Promise)return O.then(A=>{B||le.emit(A)},A=>{B||le.down([[I,A]])}),()=>{B=!0};le.emit(O)}catch(O){B=!0,le.down([[I,O]])}},{describeKind:"producer"})},{name:"candidates"});o.add(k,{name:"candidates"});let S=he([k],(R,M,Z)=>{let ae=Z.terminalDeps[0];ae!==void 0&&ae!==!0&&l.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});o.add(S,{name:"error-watcher"}),o.addDisposer(S.subscribe(()=>{}));let N=G([k,a],([R,M])=>({iteration:M,candidates:R,timestamp_ns:K()}),{name:"generate-event"});o.add(N,{name:"generate-event"}),o.addDisposer(N.subscribe(()=>{}));let P=he([N],([R])=>{v.publish(R)},{name:"generate-publish"});o.add(P,{name:"generate-publish"}),o.addDisposer(P.subscribe(()=>{}));let H=he([k],([R])=>{c.emit(R)},{name:"generate-mirror"});o.add(H,{name:"generate-mirror"}),o.addDisposer(H.subscribe(()=>{}));let F=e(k,i);o.add(F,{name:"scores"});let ye=G([F,k,a],([R,M,Z])=>({iteration:Z,candidates:M,scores:R,timestamp_ns:K()}),{name:"evaluate-event"});o.add(ye,{name:"evaluate-event"}),o.addDisposer(ye.subscribe(()=>{}));let ve=he([ye],([R])=>{g.publish(R)},{name:"evaluate-publish"});o.add(ve,{name:"evaluate-publish"}),o.addDisposer(ve.subscribe(()=>{}));let ke=G([F,k],([R,M])=>E.analyze(R,M),{name:"feedback"});o.add(ke,{name:"feedback"});let Ee=G([ke,k,a],([R,M,Z])=>({iteration:Z,candidates:M,feedback:R,timestamp_ns:K()}),{name:"analyze-event"});o.add(Ee,{name:"analyze-event"}),o.addDisposer(Ee.subscribe(()=>{}));let j=he([Ee],([R])=>{_.publish(R)},{name:"analyze-publish"});o.add(j,{name:"analyze-publish"}),o.addDisposer(j.subscribe(()=>{}));let z=G([h],([R])=>{let M=R;if(n.patience==null||M.length<=n.patience)return!1;let Z=M.slice(-(n.patience+1)),ae=Z[0].bestScore;return Z.slice(1).every(le=>le.bestScore<=ae)},{name:"patience-check"});o.add(z,{name:"patience-check"});let L=G([b],([R])=>n.minScore!=null&&R>=n.minScore,{name:"min-score-check"});o.add(L,{name:"min-score-check"});let ie=G([h],([R])=>{let M=R;if(n.minDelta==null||M.length<2)return!1;let Z=M[M.length-2].bestScore,ae=M[M.length-1].bestScore;return Math.abs(ae-Z)<n.minDelta},{name:"min-delta-check"});o.add(ie,{name:"min-delta-check"});let X=G([m],([R])=>n.maxEvaluations!=null&&R>=n.maxEvaluations,{name:"max-evaluations-check"});o.add(X,{name:"max-evaluations-check"});let me=G([a],([R])=>n.maxIterations!=null&&R>=n.maxIterations,{name:"max-iterations-check"});o.add(me,{name:"max-iterations-check"});let C=G([m],([R])=>n.budget!=null&&R>=n.budget,{name:"budget-exhausted-check"});o.add(C,{name:"budget-exhausted-check"}),o.addDisposer(z.subscribe(()=>{})),o.addDisposer(L.subscribe(()=>{})),o.addDisposer(ie.subscribe(()=>{})),o.addDisposer(X.subscribe(()=>{})),o.addDisposer(me.subscribe(()=>{})),o.addDisposer(C.subscribe(()=>{}));let q=G([z,L,ie,X,me],([R,M,Z,ae,le])=>R?{converged:!0,reason:"patience"}:M?{converged:!0,reason:"min-score"}:Z?{converged:!0,reason:"min-delta"}:ae?{converged:!0,reason:"max-evaluations"}:le?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});o.add(q,{name:"converged"}),o.addDisposer(q.subscribe(()=>{}));let ge=-1,Ge=he([ke,F,k],([R,M,Z])=>{let ae=a.cache,le=R,B=Z,O=M;if(ae<=ge)return;ge=ae;let{best:A,bestScore:Y}=ts(B,O),ne=h.cache,Le={n:ae,candidates:B,scores:O,feedback:le,best:A,bestScore:Y,timestamp_ns:K()},fe=[...ne,Le],Fe=m.cache+B.length,re="continue",Te,Yt=n.budget!=null&&Fe>=n.budget,Qt=p.cache;if(Yt)re="budget",Te="budget";else if(n.minScore!=null&&le.score>=n.minScore)re="converged",Te="min-score";else if(n.maxIterations!=null&&ae>=n.maxIterations)re="converged",Te="max-iterations";else if(n.maxEvaluations!=null&&Fe>=n.maxEvaluations)re="converged",Te="max-evaluations";else if(n.minDelta!=null&&fe.length>=2){let Nt=fe[fe.length-2].bestScore,Xt=fe[fe.length-1].bestScore;Math.abs(Xt-Nt)<n.minDelta&&(re="converged",Te="min-delta")}else if(n.patience!=null&&fe.length>n.patience){let Nt=fe.slice(-(n.patience+1)),Xt=Nt[0].bestScore;Nt.slice(1).every(Br=>Br.bestScore<=Xt)&&(re="converged",Te="patience")}re==="continue"&&Qt&&(re="paused"),U(()=>{f.emit(A),b.emit(le.score),h.emit(fe),m.emit(Fe),u.emit(le),w.publish({iteration:ae,decision:re,reason:Te,timestamp_ns:K()}),re==="continue"?a.emit(ae+1):l.emit(re==="converged"?"converged":re==="budget"?"budget":"paused")})},{name:"decide-bridge"});return o.add(Ge,{name:"decide-bridge"}),o.addDisposer(Ge.subscribe(()=>{})),Object.assign(o,{best:f,score:b,status:l,history:h,strategy:d,iteration:a,generate:v,evaluate:g,analyze:_,decide:w,setStrategy(R){d.emit(R)},pause(){p.emit(!0)},resume(){l.cache==="paused"&&U(()=>{p.emit(!1),l.emit("running"),a.emit(a.cache+1)})}})}function rs(r){let{best:e,score:t,status:n}=r,s=Number.isFinite(t)?t.toFixed(3):String(t),o=e??void 0;return n==="converged"?{outcome:"success",detail:`refineLoop converged at score ${s}`,artifact:o}:n==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${s}`,artifact:o}:{outcome:"failure",detail:`refineLoop errored (status=${n})`,artifact:o}}function Cn(r){let e=r.name??"refine-executor",t=r.toOutput??rs;return n=>{let s=n.payload.item,o=Rr(r.seedFrom(s),r.evaluator,r.strategy,{...r.refine,dataset:r.datasetFor(s),name:`${e}/inner`}),i=G([o.status,o.best,o.score],([a,d,u])=>{let c=a;if(c!=="converged"&&c!=="budget"&&c!=="errored")return null;let p=t({best:d,score:u,status:c});return{...n.payload,execution:{item:s,...p}}},{name:`${e}/output`});return Gt(i,a=>a!=null,{name:`${e}/gate-out`})}}function os(r){if(r.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let t of r)e+=t.score;return e/r.length}function ss(r){let{passCount:e,total:t,meanScore:n,threshold:s,missingArtifact:o}=r,i=Number.isFinite(n)?n.toFixed(3):String(n),a=!o&&t>0&&n>=s,d=o?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:a?[`${e}/${t} eval tasks passed; mean score ${i} \u2265 ${s}`]:t===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${e}/${t} eval tasks passed; mean score ${i} < threshold ${s}`];return a?{verified:!0,findings:d}:{verified:!1,findings:d,errorClass:"structural"}}function is(r){return r.artifact??null}function Or(r){let e=r.name??"eval-verifier",t=r.threshold??.5,n=r.toOutput??ss,s=r.extractArtifact??is;return o=>{let{item:i,execution:a}=o.payload;if(a==null)return{...o.payload,verify:{verified:!1,findings:["evalVerifier: prior execute stage produced no execution"],errorClass:"structural"}};let d=s(a,i);if(d==null)return{...o.payload,verify:n({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:t,missingArtifact:!0})};let u=V([d],{name:`${e}/candidates`}),c=V(r.datasetFor(i),{name:`${e}/dataset`}),p;U(()=>{p=r.evaluator(u,c)});let l=G([p],([h])=>{let f=h;if(f==null)return null;let b=os(f),m=f.filter(T=>T.score>=t).length;return{...o.payload,verify:n({scores:f,meanScore:b,passCount:m,total:f.length,threshold:t})}},{name:`${e}/output`});return Gt(l,h=>h!=null,{name:`${e}/gate-out`})}}function as(r){let e=r.name??"harness-pair",t=Cn({name:`${e}-exec`,seedFrom:r.seedFrom,evaluator:r.evaluator,strategy:r.strategy,datasetFor:r.datasetFor,refine:r.refine}),n=Or({name:`${e}-verify`,evaluator:r.evaluator,datasetFor:r.datasetFor,threshold:r.threshold});return{executor:t,verifier:n}}Oe();rt();te();Me();Oe();tt();be();te();function Dn(r,e){let t=r.cache??0;return t>=e?!1:(r.down([[Q],[D,t+1]]),!0)}var us=Xn((r,e)=>{r("observe"),r("signal"),e("write")});function Ut(r){let e=dt([],{name:r.name,maxSize:r.retainedLimit??1024,guard:r.guard??us,...r.versioning!=null?{versioning:r.versioning}:{}});return e.withLatest(),r.graph&&r.graph.add(e.entries,{name:r.name}),e}function Ar(r){if(r===null||typeof r!="object"||Object.isFrozen(r))return r;for(let e of Object.keys(r))Ar(r[e]);return Object.freeze(r)}function ds(r){let e=r.cache,n=(typeof e=="number"&&Number.isFinite(e)?e:0)+1;return r.down([[Q],[D,n]]),n}function Sr(r,e,t,n,s,o){let i=e(t,n,s);if(i===void 0)return;let a=o!=null?{...i,handlerVersion:o}:i;r.append(a)}function lt(r,e){let t=e.freeze??!0;return function(...s){let o=t?s.map(Ar):s,i=xe(),a,d,u=!1,c;try{U(()=>{e.seq&&(c=ds(e.seq));try{a=r(...o),e.onSuccess&&Sr(e.audit,e.onSuccess,o,a,{t_ns:i,seq:c},e.handlerVersion)}catch(p){throw d=p,u=!0,p}})}catch(p){if(u&&e.onFailure){let l=d instanceof Error?d.name:typeof d;Sr(e.audit,e.onFailure,o,d,{t_ns:i,seq:c,errorType:l},e.handlerVersion)}throw u?d:p}return a}}function Cr(r,e,t=0){let n=V(t,{name:e,describeKind:"state"});return r.add(n,{name:e}),n}function Tt(r){return r.relatedTo?.[0]??r.summary}be();te();yt();Pe();function _t(r,e){return ze("ai",r,e)}function wt(r){let e=r.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:r}function Mn(r,e,t){return ue(n=>{let s=new AbortController,o=!1,i=null,a=c=>{o||(o=!0,n.down([[D,c],[$]]),i?.(),i=null)},d;try{d=r.invoke(e,{...t.invokeOpts,signal:s.signal})}catch(c){return a(t.onFailure("throw",c)),()=>s.abort()}return i=Ae(d,{signal:s.signal}).subscribe(c=>{for(let p of c){if(o)return;if(p[0]===D){try{a(t.onSuccess(p[1]))}catch(l){a(t.onFailure("onSuccess-threw",l))}return}if(p[0]===I){a(t.onFailure("error",p[1]));return}if(p[0]===$){a(t.onFailure("complete",void 0));return}}}),o&&i&&(i(),i=null),()=>{s.abort(),i?.(),i=null}})}be();te();Pe();function Dr(r){return r!=null&&typeof r=="object"&&"content"in r?String(r.content):typeof r=="string"?r:String(r)}function cs(r,e=200){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function Mr(r,e,t,n){let s=n?.format??"text",o=n?.name??"prompt_node";n?.tools!==void 0&&s!=="raw"&&console.warn("promptNode: `tools` is set but `format !== 'raw'`. Tool calls in the response will be silently dropped \u2014 set `format: 'raw'` to receive the full LLMResponse with `toolCalls`.");let i=G(e,d=>{if(d.some(c=>c==null))return[];let u=typeof t=="string"?t:t(...d);return u?[{role:"user",content:u}]:[]},{name:`${o}::messages`,meta:_t("prompt_node")});return ot(i,d=>!d||d.length===0?V(null):ue(u=>{let c=!1,p=!1,l,h={model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,systemPrompt:n?.systemPrompt,...n?.tools!==void 0?{tools:n.tools}:{}};if(n?.abort){let T=ir(n.abort);h.signal=T.signal,l=T.dispose}let f;try{f=r.invoke(d,h)}catch(T){return c=!0,u.down([[I,T]]),()=>{l?.()}}let m=Ae(f).subscribe(T=>{if(!(p||c))for(let v of T){if(c)return;if(v[0]===D){let g=v[1];if(s==="raw")u.emit(g);else try{let _=Dr(g),w=s==="json"?JSON.parse(wt(_)):_;u.emit(w)}catch(_){let w=Dr(g),E=new Error(`promptNode: failed to parse LLM response as JSON: ${_.message}
45
- Raw content (first 200 chars): ${cs(w)}`);c=!0,u.down([[I,E]]);return}}else if(v[0]===I){c=!0,u.down([[I,v[1]]]);return}else if(v[0]===$){c=!0,u.down([[$]]);return}else u.down([v])}});return()=>{p=!0,m(),l?.()}},{name:`${o}::call`,meta:_t("prompt_node::call")}),{name:`${o}::output`,meta:n?.meta?{..._t("prompt_node::output"),...n.meta}:_t("prompt_node::output")})}Me();Oe();be();rt();Ie();te();yt();function xt(r,e){return ze("orchestration",r,e)}var Kt=class extends ce{constructor(e,t){super(e,t)}task(e,t,n={}){let s=(n.deps??[]).map(i=>this._resolveStep(i)),o=G(s,t,{name:e,describeKind:"derived",meta:xt("task",n.meta)});return this.add(o,{name:e}),o}classify(e,t,n,s={}){let o=this._resolveStep(t),i=G([o],([a])=>{try{return{tag:n(a),value:a}}catch(d){return{tag:"error",value:a,error:d}}},{name:e,describeKind:"derived",meta:xt("classify",s.meta)});return this.add(i,{name:e}),i}combine(e,t,n={}){let s=Object.keys(t),o=s.map(a=>this._resolveStep(t[a])),i=G(o,a=>{let d={};for(let u=0;u<s.length;u++)d[s[u]]=a[u];return d},{name:e,describeKind:"derived",meta:xt("combine",n.meta)});return this.add(i,{name:e}),i}approvalGate(e,t,n={}){let s=n.maxPending??1e3;if(s<1&&s!==Number.POSITIVE_INFINITY)throw new RangeError("approvalGate: maxPending must be >= 1");let o=n.startOpen??!1;typeof t!="string"&&this.nameOf(t)===void 0&&this.add(t,{name:`${e}/source`});let i=this._resolveStep(t),a=new ce(`${e}_state`),d=V([],{name:"pending",equals:()=>!1}),u=V(o,{name:"isOpen"}),c=G([d],([j])=>j.length,{name:"count"}),p=V(0,{name:"droppedCount"}),l=Ut({name:"decisions",retainedLimit:1024,graph:a});a.add(d,{name:"pending"}),a.add(u,{name:"isOpen"}),a.add(c,{name:"count"}),a.add(p,{name:"droppedCount"}),this.mount(`${e}_state`,a);let h=[],f=!1,b=!1,m=o,T=u.subscribe(j=>{for(let z of j)z[0]===D&&(m=z[1])});this.addDisposer(T);function v(){d.emit([...h])}function g(j,z,L){l.append({action:j,t_ns:xe(),...z!==void 0?{items:z,count:z.length}:{},...L!==void 0?{unflushed:L}:{},...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}function _(j){if(h.push(j),h.length>s){let z=h.shift();p.emit(p.cache+1),g("drop",[z])}v()}function w(j){let z=h.splice(0,j);return v(),z}let E=ee([i],(j,z,L)=>{let ie=L.terminalDeps[0];if(ie!==void 0){f=!0;let me=h.length;h=[],v(),g("teardown",void 0,me),z.down(ie===!0?[[$]]:[[I,ie]]);return}let X=j[0];if(X==null||X.length===0){z.down([[W]]);return}for(let me of X)m?z.emit(me):(_(me),z.down([[W]]))},{name:e,describeKind:"derived",meta:xt("approval_gate",n.meta)});if(this.add(E,{name:e}),n.approver!=null){n.approver.cache&&(u.emit(!0),m=!0,n.onceOnly&&(b=!0));let z=n.approver.subscribe(L=>{for(let ie of L){if(ie[0]!==D)continue;let X=!!ie[1];if(X&&!m){if(n.onceOnly){if(b)continue;b=!0}U(()=>{u.emit(!0);let me=w(h.length);g("open",me);for(let C of me){if(f)break;E.emit(C)}})}else if(!X&&m){if(n.onceOnly&&b)continue;U(()=>{u.emit(!1),g("close")})}}});this.addDisposer(z)}let y=j=>{if(f)throw new Error(`approvalGate: ${j}() called after the gate was torn down`)},x=(j=1)=>{y("approve");let z=w(j);for(let L of z){if(f)break;E.emit(L)}},k=(j=1)=>{y("reject"),w(j)},S=(j,z=1)=>{y("modify");let L=[...h],ie=w(z);for(let X=0;X<ie.length&&!f;X++)E.emit(j(ie[X],X,L))},N=()=>{y("open"),u.emit(!0);let j=w(h.length);for(let z of j){if(f)break;E.emit(z)}},P=()=>{y("close"),!(n.onceOnly&&b)&&u.emit(!1)},H=lt(x,{audit:l,freeze:!1,onSuccess:(j,z,L)=>({action:"approve",count:j[0]??1,t_ns:L.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:(j,z,L)=>({action:"drop",t_ns:L.t_ns,errorType:L.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}),F=lt(k,{audit:l,freeze:!1,onSuccess:(j,z,L)=>({action:"reject",count:j[0]??1,t_ns:L.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:(j,z,L)=>({action:"drop",t_ns:L.t_ns,errorType:L.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}),ye=lt(S,{audit:l,freeze:!1,onSuccess:(j,z,L)=>({action:"modify",count:j[1]??1,t_ns:L.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:(j,z,L)=>({action:"drop",t_ns:L.t_ns,errorType:L.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}),ve=lt(N,{audit:l,freeze:!1,onSuccess:(j,z,L)=>({action:"open",t_ns:L.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:(j,z,L)=>({action:"drop",t_ns:L.t_ns,errorType:L.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}),ke=lt(P,{audit:l,freeze:!1,onSuccess:(j,z,L)=>({action:"close",t_ns:L.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:(j,z,L)=>({action:"drop",t_ns:L.t_ns,errorType:L.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})});return this.addDisposer(c.subscribe(()=>{})),{node:E,pending:d,count:c,isOpen:u,droppedCount:p,decisions:l,audit:l,approve:H,reject:F,modify:ye,open:ve,close:ke}}approval(e,t,n,s={}){return this.approvalGate(e,t,{...s,approver:n,maxPending:1})}catch(e,t,n,s={}){let o=this._resolveStep(t),i=s.on??"errored",a=ee([o],(d,u,c)=>{let p=c.terminalDeps[0];if(p!==void 0){let h=p===!0?{kind:"completed"}:{kind:"errored",error:p};if(i==="terminal"||i===h.kind){u.emit(n(h,u));return}u.down(h.kind==="completed"?[[$]]:[[I,h.error]]);return}let l=d[0];if(l==null||l.length===0){u.down([[W]]);return}for(let h of l)u.emit(h)},{name:e,describeKind:"derived",completeWhenDepsComplete:s.completeWhenDepsComplete??!(i==="completed"||i==="terminal"),errorWhenDepsError:!(i==="errored"||i==="terminal"),meta:xt("catch",s.meta)});return this.add(a,{name:e}),a}_resolveStep(e){if(typeof e=="string")return this.resolve(e);if(this.nameOf(e)===void 0)throw new Error(`PipelineGraph "${this.name}": Node dep is not registered. Pass a string path or call graph.add(node) first.`);return e}};function In(r,e){let t=new Kt(r,e),{factory:n,factoryArgs:s,...o}=e??{};return t.tagFactory("pipelineGraph",Ke(o)),t}var gu=Math.LN2/604800;function Ir(r,e,t,n=0){if(!Number.isFinite(r))return n;if(!Number.isFinite(e)||e<=0||!Number.isFinite(t)||t<=0)return Math.max(n,r);let s=r*Math.exp(-t*e);return Math.max(n,s)}Oe();Ie();yt();Me();be();te();var Gn=class{_version=0;_buf;constructor(e){this._buf=e?[...e]:[]}get version(){return this._version}get size(){return this._buf.length}at(e){if(!Number.isInteger(e))return;let t=e>=0?e:this._buf.length+e;if(!(t<0||t>=this._buf.length))return this._buf[t]}append(e){this._buf.push(e),this._version+=1}appendMany(e){if(e.length===0)return;let t=this._buf.length;this._buf.length=t+e.length;for(let n=0;n<e.length;n++)this._buf[t+n]=e[n];this._version+=1}insert(e,t){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insert: index ${e} out of range [0, ${this._buf.length}]`);this._buf.splice(e,0,t),this._version+=1}insertMany(e,t){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insertMany: index ${e} out of range [0, ${this._buf.length}]`);t.length!==0&&(this._buf.splice(e,0,...t),this._version+=1)}pop(e){if(this._buf.length===0)throw new RangeError("pop from empty list");if(!Number.isInteger(e))throw new RangeError(`pop: index ${e} must be an integer`);let t=e>=0?e:this._buf.length+e;if(t<0||t>=this._buf.length)throw new RangeError(`pop: index ${e} out of range`);let[n]=this._buf.splice(t,1);return this._version+=1,n}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._version+=1,e)}toArray(){return[...this._buf]}};function Gr(r,e={}){let{name:t,versioning:n,backend:s}=e,o=s??new Gn(r),i=V(o.toArray(),{name:t,describeKind:"state",equals:(u,c)=>u===c,...n!=null?{versioning:n}:{}});function a(){let u=o.toArray();U(()=>{i.down([[Q]]),i.down([[D,u]])})}function d(u){let c=o.version;try{return u()}finally{o.version!==c&&a()}}return{items:i,get size(){return o.size},at(u){return o.at(u)},append(u){d(()=>o.append(u))},appendMany(u){d(()=>o.appendMany(u))},insert(u,c){d(()=>o.insert(u,c))},insertMany(u,c){d(()=>o.insertMany(u,c))},pop(u=-1){return d(()=>o.pop(u))},clear(){d(()=>o.clear())},dispose(){}}}Pe();var ls=256,fs=1024;function Pn(r,e){if(!Number.isFinite(r)||!Number.isInteger(r)||r<0)throw new Error(`${e} must be a non-negative integer`);return r}function Wt(r,e){return ze("job_queue",r,e)}var Ln=class extends ce{_pending;_jobs;_seqCursor;pending;jobs;depth;events;audit;constructor(e,t={}){super(e,t.graph),this._pending=Gr([],{name:"pending"}),this._jobs=ut({name:"jobs"}),this.pending=this._pending.items,this.jobs=this._jobs.entries,this.add(this.pending,{name:"pending"}),this.add(this.jobs,{name:"jobs"}),this.depth=G([this.pending],([n])=>n.length,{name:"depth",describeKind:"derived",meta:Wt("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(de(this.depth)),this.events=Ut({name:"events",retainedLimit:1024,graph:this}),this.audit=this.events,this._seqCursor=Cr(this,"seq",0)}_bumpSeq(){let t=(this._seqCursor.cache??0)+1;return this._seqCursor.emit(t),t}attachEventStorage(e){return this.events.attachStorage(e)}enqueue(e,t={}){let n=this._bumpSeq(),s=t.id??`${this.name}-${n}`;if(this._jobs.get(s)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${s}"`);let o={id:s,payload:e,attempts:0,metadata:Object.freeze({...t.metadata??{}}),state:"queued"};return this._jobs.set(s,o),this._pending.append(s),this.events.append({action:"enqueue",id:s,payload:e,t_ns:xe(),seq:n}),s}claim(e=1){let t=Pn(e,"job queue claim limit");if(t===0)return[];let n=[];for(;n.length<t&&this.pending.cache.length!==0;){let o=this._pending.pop(0),i=this._jobs.get(o);if(!i||i.state!=="queued")continue;let a={...i,state:"inflight",attempts:i.attempts+1};this._jobs.set(o,a),n.push(a),this.events.append({action:"claim",id:o,attempts:a.attempts,t_ns:xe(),seq:this._bumpSeq()})}return n}ack(e){let t=this._jobs.get(e);return!t||t.state!=="inflight"?!1:(this._jobs.delete(e),this.events.append({action:"ack",id:e,attempts:t.attempts,t_ns:xe(),seq:this._bumpSeq()}),!0)}nack(e,t={}){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:t.requeue??!0?(this._jobs.set(e,{...n,state:"queued"}),this._pending.append(e),this.events.append({action:"nack",id:e,attempts:n.attempts,t_ns:xe(),seq:this._bumpSeq()}),!0):(this._jobs.delete(e),this.events.append({action:"nack",id:e,attempts:n.attempts,t_ns:xe(),seq:this._bumpSeq()}),!0)}removeById(e){let t=this._jobs.get(e);if(!t)return!1;if(t.state==="queued"){let s=this.pending.cache.indexOf(e);s>=0&&this._pending.pop(s)}return this._jobs.delete(e),this.events.append({action:"remove",id:e,attempts:t.attempts,t_ns:xe(),seq:this._bumpSeq()}),!0}consumeFrom(e,t){return e.subscribe(n=>{for(let s of n){if(s[0]!==D)continue;let o=s[1];this.enqueue(o,t?{metadata:t.metadata}:void 0)}})}},Fn=class extends ce{_stageNames;_stageWorkFns;_queues=new Map;_completed;completed;completedCount;constructor(e,t={}){super(e,t.graph);let n=t.stages??["incoming","processing","done"],s=[],o=new Map,i=new Map;for(let u of n){let c=typeof u=="string"?u.trim():u.name.trim();typeof u!="string"&&u.work&&o.set(c,u.work),typeof u!="string"&&u.maxPerPump!=null&&i.set(c,Math.max(1,Pn(u.maxPerPump,`job flow stage "${c}" maxPerPump`))),s.push(c)}if(s.length<2)throw new Error(`jobFlow("${e}"): requires at least 2 stages`);if(new Set(s).size!==s.length)throw new Error(`jobFlow("${e}"): stage names must be unique`);this._stageNames=Object.freeze([...s]),this._stageWorkFns=o;for(let u of this._stageNames){let c=$n(`${e}-${u}`);this._queues.set(u,c),this.mount(u,c)}this._completed=dt([],{name:"completed",maxSize:fs}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=G([this.completed],([u])=>u.length,{name:"completedCount",describeKind:"derived",meta:Wt("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(de(this.completedCount));let d=Math.max(1,Pn(t.maxPerPump??ls,"job flow maxPerPump"));for(let u=0;u<this._stageNames.length;u+=1){let c=this._stageNames[u],p=this.queue(c),l=u+1<this._stageNames.length?this.queue(this._stageNames[u+1]):null,h=this._stageWorkFns.get(c),f=i.get(c)??d,b=l===null;if(h){let m=ee([p.pending],()=>{let T=0;for(;T<f;){let v=p.claim(1);if(v.length===0)break;let g=v[0];if(!g)break;let w=[...g.metadata.job_flow_path??[],c],E;try{E=h(g)}catch{p.nack(g.id,{requeue:!1}),T+=1;continue}let y=Ae(E),x=!1,k;k=y.subscribe(S=>{if(!x){for(let N of S)if(N[0]===D){x=!0,k?k():Promise.resolve().then(()=>k?.());let P=N[1],H={...g.metadata,job_flow_path:w};if(b){let F={...g,payload:P,metadata:Object.freeze(H)};U(()=>{p.ack(g.id),this._completed.append(F)})}else U(()=>{p.ack(g.id),l.enqueue(P,{metadata:H})});return}else if(N[0]===I){x=!0,k?k():Promise.resolve().then(()=>k?.()),p.nack(g.id,{requeue:!1});return}}}),T+=1}},{name:`pump_${c}`,describeKind:"effect",meta:Wt("job_flow_pump",{stage:c,has_work:!0})});this.add(m,{name:`pump_${c}`}),this.addDisposer(de(m))}else{let m=ee([p.pending],()=>{let T=0;for(;T<f;){let v=p.claim(1);if(v.length===0)break;let g=v[0];if(!g)break;let w=[...g.metadata.job_flow_path??[],c],E={...g.metadata,job_flow_path:w};if(b){let y={...g,metadata:Object.freeze(E)};U(()=>{p.ack(g.id),this._completed.append(y)})}else U(()=>{p.ack(g.id),l.enqueue(g.payload,{metadata:E})});T+=1}},{name:`pump_${c}`,describeKind:"effect",meta:Wt("job_flow_pump",{stage:c,has_work:!1})});this.add(m,{name:`pump_${c}`}),this.addDisposer(de(m))}}}stages(){return this._stageNames}queue(e){let t=this._queues.get(e);if(!t)throw new Error(`jobFlow("${this.name}"): unknown stage "${e}"`);return t}enqueue(e,t={}){return this.queue(this._stageNames[0]).enqueue(e,t)}retainedCompleted(){return this.completed.cache}};function $n(r,e){return new Ln(r,e)}function Pr(r,e){let t=new Fn(r,e),{factory:n,factoryArgs:s,...o}=e??{};return t.tagFactory("jobFlow",Ke(o)),t}Oe();te();function Vn(){let r=ut({name:"strategy-entries"}),e=G([r.entries],([i])=>{let a=i;return new Map(a)},{name:"strategy-model",equals:(i,a)=>{let d=i,u=a;if(d.size!==u.size)return!1;for(let[c,p]of d){let l=u.get(c);if(!l||p.attempts!==l.attempts||p.successes!==l.successes)return!1}return!0}});function t(i,a,d){let u=at(i,a),c=r.get(u),p=(c?.attempts??0)+1,l=(c?.successes??0)+(d?1:0);r.set(u,{rootCause:i,intervention:a,attempts:p,successes:l,successRate:l/p})}function n(i,a){return r.get(at(i,a))}let s=e.subscribe(()=>{});function o(){s()}return{node:e,record:t,lookup:n,dispose:o}}function ps(r,e,t,n,s){let o={...st,...s?.severityWeights},i=s?.decayRate??it,a=s?.effectivenessThreshold??.7,d=s?.effectivenessBoost??15,u=[r,e,t];return n&&u.push(n),G(u,c=>{let p=c[0],l=c[1],h=c[2],f=n?c[3]:0,b=o[p.severity??"medium"],m=(K()-h)/1e9,T=Ir(b,m,i,0),v=at(p.rootCause,p.intervention),g=l.get(v);return g&&g.successRate>=a&&(T+=d),T+=f*20,T},{name:"priority-score"})}var Lr="intake",hs="triage-output",Fr="retry",$r="verify-results",Vr="__unrouted";function jr(r,e){let t=gt(e,bn,(n,s)=>n.replace("{{item}}",JSON.stringify(s)));return n=>{let s=n.payload.item,o=[{role:"user",content:t(s)}],i=d=>({...n.payload,execution:{item:s,outcome:"failure",detail:d}}),a=d=>d instanceof Error?d.message:String(d);return Mn(r,o,{onSuccess:d=>{let u;try{u=JSON.parse(wt(String(d.content)))}catch(p){return i(`execute parse error: ${a(p)}`)}if(u==null||typeof u!="object"||Array.isArray(u))return i(`execute parse error: non-object response: ${JSON.stringify(u)}`);let c=u;return{...n.payload,execution:{item:s,outcome:c.outcome??"failure",detail:c.detail??"unknown",artifact:c.artifact}}},onFailure:(d,u)=>i(d==="complete"?"adapter completed without emitting DATA":`executor failed: ${a(u)}`)})}}function zr(r,e){let t=gt(e,yn,(n,s)=>{let[o,i]=s;return n.replace("{{execution}}",JSON.stringify(o)).replace("{{item}}",JSON.stringify(i))});return n=>{let{item:s,execution:o}=n.payload;if(o==null)return{...n.payload,verify:{verified:!1,findings:["verifier: prior execute stage produced no execution"],errorClass:"structural"}};let i=[{role:"user",content:t([o,s])}],a=u=>({...n.payload,verify:{verified:!1,findings:[u],errorClass:"self-correctable"}}),d=u=>u instanceof Error?u.message:String(u);return Mn(r,i,{onSuccess:u=>{let c;try{c=JSON.parse(wt(String(u.content)))}catch(l){return a(`verify parse error: ${d(l)}`)}if(c==null||typeof c!="object"||Array.isArray(c))return a(`verify parse error: non-object response: ${JSON.stringify(c)}`);let p=c;return{...n.payload,verify:{verified:p.verified===!0,findings:p.findings??[],errorClass:p.errorClass}}},onFailure:(u,c)=>a(u==="complete"?"verifier completed without emitting DATA":`verifier failed: ${d(c)}`)})}}var Jt=class extends ce{queues;executeFlow;jobs;gates;queueTopics;strategy;totalRetries;totalReingestions;priorityScores;constructor(e,t,n,s,o,i,a,d,u,c){super(e),this.queues=t,this.executeFlow=n,this.queueTopics=s,this.jobs=o,this.gates=i,this.strategy=a,this.totalRetries=d,this.totalReingestions=u,this.priorityScores=c}get intake(){return this.queues.topic(Lr)}get verifyResults(){return this.queues.topic($r)}get retry(){return this.queues.topic(Fr)}get unrouted(){return this.queues.topic(Vr)}stageNodes(){let e=this.queues,t=i=>e.has(i)?`queues::${i}::latest`:null,n=i=>i==null?[]:[i],s=Ne.flatMap(i=>n(t(i))),o=[];for(let[i]of this.gates)o.push(`gates::${i}/gate`);return[{label:"INTAKE",paths:n(t("intake"))},{label:"TRIAGE",paths:["triage"]},{label:"QUEUE",paths:s},{label:"GATE",paths:o},{label:"EXECUTE",paths:["executeFlow::execute::events"]},{label:"VERIFY",paths:["executeFlow::verify::events"]},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function ms(r,e){let t=e.adapter,n=e.maxRetries??2,s=e.retainedLimit??1e3,o=e.errorClassifier??Lt,i=new Map;for(let O of Ne)i.set(O,{...Pt[O],...e.queues?.[O]});let a=qt(`${r}/queues`,{defaultTopicOptions:{retainedLimit:s}}),d=a.topic(Lr),u=a.topic(hs),c=a.topic(Fr),p=a.topic($r),l=new Map;for(let O of Ne)l.set(O,a.topic(O));let h=a.topic(Vr),f=Vn(),b=mn(d.latest,f.node),m=gt(e.triagePrompt,gn,(O,A)=>{let[Y,ne]=A;return O.replace("{{strategy}}",JSON.stringify(Array.from(ne.entries()))).replace("{{item}}",JSON.stringify(Y))}),T=Mr(t,[b],O=>{let A=O;return!A||!A[0]?"":m(A)},{name:"triage",format:"json"}),v=mn(T,b),_=he([v],([O])=>{if(O==null)return;let[A,Y]=O;if(!A?.route)return;let ne=Y?.[0],Le={...A,...ne};u.publish(Le)}).subscribe(()=>{}),w=new Set(Ne);for(let O of Ne)An(`bridge/${O}`,u,l.get(O),{map:A=>A.route===O?A:void 0});An("bridge/__unrouted",u,h,{map:O=>w.has(O.route)?void 0:O});let E=new Map,y=new Map;for(let O of Ne)E.set(O,$n(`jobs/${O}`));let x=[];for(let O of Ne){let A=l.get(O),Y=E.get(O),ne=new WeakSet,Le=he([A.events],([fe])=>{let Fe=fe??[];for(let re of Fe){if(ne.has(re))continue;ne.add(re);let Te=Y.enqueue(re);y.set(Tt(re),{route:O,id:Te})}},{name:`jobs/${O}-mirror`});x.push(Le.subscribe(()=>{}))}function k(O){let A=Tt(O),Y=y.get(A);Y&&(E.get(Y.route)?.removeById(Y.id),y.delete(A))}let S=In("gates"),N=new Map;for(let O of Ne){let A=i.get(O);if(!A.gated)continue;let Y=l.get(O),ne=S.approvalGate(`${O}/gate`,Y.latest,{maxPending:A.maxPending,startOpen:A.startOpen});N.set(O,ne)}let P=[];for(let O of Ne)i.get(O).gated&&N.has(O)?P.push(N.get(O).node):P.push(l.get(O).latest);P.push(c.latest);let H=cr(...P),F=e.executor??jr(t,e.executePrompt),ye=e.verifier??zr(t,e.verifyPrompt),ve=e.executeMaxPerPump??Number.MAX_SAFE_INTEGER,ke=e.verifyMaxPerPump??Number.MAX_SAFE_INTEGER,Ee=Pr(`${r}/executeFlow`,{stages:[{name:"execute",work:O=>F(O),maxPerPump:ve},{name:"verify",work:O=>ye(O),maxPerPump:ke}]}),j=he([H],([O])=>{O!=null&&Ee.enqueue({item:O})},{name:"execute-enqueue"}),z=j.subscribe(()=>{}),L=e.maxReingestions??1,ie=Math.min(e.maxTotalRetries??n*10,100),X=Math.min(e.maxTotalReingestions??L*10,100),me=V(0),C=V(0);function q(O,A,Y){return{item:Y,execution:O,verified:A.verified,findings:A.findings??[],errorClass:A.errorClass}}function ge(O,A){f.record(A.rootCause,A.intervention,!0),p.publish(O),k(A)}function Ge(O,A){let Y=Tt(A),ne=A.$retries??0,Le={...A,$retries:ne+1,summary:`[RETRY ${ne+1}/${n}] ${Y} \u2014 Previous attempt failed: ${O.findings.join("; ")}`,relatedTo:[Y]};c.publish(Le)}function we(O,A){f.record(A.rootCause,A.intervention,!1),p.publish(O),k(A);let Y=Tt(A),ne=A.$reingestions??0;ne<L&&Dn(C,X)&&d.publish({source:A.source,summary:`Verification failed for: ${Y}`,evidence:O.findings.join(`
46
- `),affectsAreas:A.affectsAreas,affectsEvalTasks:A.affectsEvalTasks,severity:A.severity??"high",relatedTo:[Y],$reingestions:ne+1})}let R=0,M=he([Ee.completed],([O])=>{let A=O??[];R>A.length&&(R=A.length);let Y=R;R=A.length;for(let ne=Y;ne<A.length;ne++){let Le=A[ne],{item:fe,execution:Fe,verify:re}=Le.payload;if(Fe==null||re==null){k(fe);continue}let Te=q(Fe,re,fe);if(Te.verified){ge(Te,fe);continue}let Yt=Te.errorClass??o({item:fe,outcome:Fe.outcome,detail:Te.findings.join("; ")}),Qt=fe.$retries??0;Yt==="self-correctable"&&Qt<n&&Dn(me,ie)?Ge(Te,fe):we(Te,fe)}},{name:"verify-dispatch"}),Z=M.subscribe(()=>{}),ae=G([Ee.completed],()=>null,{name:"reflect",equals:()=>!1}),le;e.priority&&(le=gs(l,f,e));let B=new Jt(r,a,Ee,l,E,N,f,me,C,le);B.addDisposer(_),B.addDisposer(z),B.addDisposer(Z),B.addDisposer(f.dispose);for(let O of x)B.addDisposer(O);if(B.add(b,{name:"triage-input"}),B.add(T,{name:"triage"}),B.add(v,{name:"router-input"}),B.add(H,{name:"execute-input"}),B.add(j,{name:"execute-enqueue"}),B.add(M,{name:"verify-dispatch"}),B.add(ae,{name:"reflect"}),B.add(f.node,{name:"strategy"}),B.addDisposer(ae.subscribe(()=>{})),le)for(let[O,A]of le)B.add(A,{name:`priority/${O}`}),B.addDisposer(A.subscribe(()=>{}));B.mount("queues",a),B.mount("gates",S),B.mount("executeFlow",Ee);for(let[O,A]of E)B.mount(`jobs/${O}`,A);return B.tagFactory("harnessLoop",Ke(e)),B}function gs(r,e,t){if(!t.lastInteractionNs)throw new Error("harnessLoop: `opts.priority` requires `opts.lastInteractionNs` \u2014 pass a Node<number> (e.g. `fromTimer(60_000)` or a `state(monotonicNs())` you bump on human interaction). Priority scores only decay when this node settles; an internal default would freeze age at construction time.");let n=t.lastInteractionNs,s=t.priority??{},o={...st,...s.severityWeights},i=s.decayRate??it,a=s.effectivenessThreshold??.7,d=s.effectivenessBoost??15,u=new Map;for(let[c,p]of r){let l=G([p.latest,e.node,n],h=>{let f=h[0];if(f==null)return 0;let b=o[f.severity??"medium"]??40,m=(K()-h[2])/1e9,T=b*Math.exp(-i*Math.max(0,m)),v=`${f.rootCause}\u2192${f.intervention}`,_=h[1]?.get(v);return _&&_.successRate>=a&&(T+=d),T},{name:`priority/${c}`});u.set(c,l)}return u}function bs(r,e){let t=zt(r,e),n={};for(let s of Ne){let o=r.queues.has(s)?r.queues.topic(s):null;n[s]=o?.retained().length??0}return{...t,queueDepths:n,strategyEntries:r.strategy.node.cache?.size??0,totalRetries:r.totalRetries.cache??0,totalReingestions:r.totalReingestions.cache??0}}Oe();function ys(r){let e={};for(let{label:t,paths:n}of r.stageNodes())for(let s of n)e[s]=t;return e}function vs(r,e){let t=e?.logger===null?null:e?.logger??console.log,n=e?.detail??"summary",s=K(),o=[],i=[],a=ys(r);function d(){return(K()-s)/1e9}function u(c,p,l){let h={elapsed:d(),stage:c,type:p};n!=="summary"&&(h.summary=Ts(l)),n==="full"&&(h.data=l),i.push(h)}for(let[c,p]of Object.entries(a))try{let l=r.observe(c,{format:"stage-log",stageLabels:a,logger:t?h=>t(h):()=>{},includeTypes:["data","error","complete"]});l.onEvent(h=>{h.type==="data"?u(p,"data",h.data):h.type==="error"?u(p,"error",h.data):h.type==="complete"&&u(p,"complete",void 0)}),o.push(l)}catch(l){let h=l instanceof Error?l.message:String(l);u(p,"error",`observe-unavailable: ${c} \u2014 ${h}`),t&&t(`[${d().toFixed(3)}s] ${p.padEnd(9)} \u2717 observe-unavailable: ${h}`)}return{get events(){return i},dispose(){for(let c of o)c.dispose();o.length=0}}}function Ts(r){if(r==null)return"null";if(typeof r=="string")return Hr(r,80);if(typeof r=="number"||typeof r=="boolean"||typeof r=="bigint")return String(r);try{let e=JSON.stringify(r);return Hr(e,120)}catch{return String(r)}}function Hr(r,e){return r.length>e?`${r.slice(0,e-1)}\u2026`:r}0&&(module.exports={DEFAULT_DECAY_RATE,DEFAULT_EXECUTE_PROMPT,DEFAULT_QUEUE_CONFIGS,DEFAULT_SEVERITY_WEIGHTS,DEFAULT_TRIAGE_PROMPT,DEFAULT_VERIFY_PROMPT,HarnessGraph,QUEUE_NAMES,actuatorExecutor,affectedTaskFilter,autoSolidify,beforeAfterCompare,codeChangeBridge,createIntakeBridge,defaultErrorClassifier,defaultLlmExecutor,defaultLlmVerifier,dispatchActuator,effectivenessTracker,evalIntakeBridge,evalSource,evalVerifier,harnessEvalPair,harnessLoop,harnessProfile,harnessTrace,notifyEffect,priorityScore,refineExecutor,resolvePromptFn,strategyKey,strategyModel});
44
+ }`;function yt(r,e,t){if(typeof r=="function")return r;let n=r??e;return s=>t(n,s)}ne();De();Re();ye();ne();var Nn=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(e={}){let{maxSize:t,defaultTtl:n}=e;if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1");if(n!==void 0&&n<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=t,this._defaultTtl=n}get version(){return this._version}get size(){return this._store.size}has(e){let t=this._store.get(e);return t===void 0?!1:this._isExpired(t)?(this._store.delete(e),this._version+=1,!1):(this._touchLru(e,t),!0)}get(e){let t=this._store.get(e);if(t!==void 0){if(this._isExpired(t)){this._store.delete(e),this._version+=1;return}return this._touchLru(e,t),t.value}}set(e,t,n){let s=this._resolveExpiresAt(n);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:t,expiresAt:s}),this._evictLruWhileOver(),this._version+=1}setMany(e,t){let n=this._resolveExpiresAt(t),s=0;try{for(let[o,i]of e)this._store.has(o)&&this._store.delete(o),this._store.set(o,{value:i,expiresAt:n}),s+=1}finally{s>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(e){let t=this._store.delete(e);return t&&(this._version+=1),t}deleteMany(e){let t=0;try{for(let n of e)this._store.delete(n)&&(t+=1)}finally{t>0&&(this._version+=1)}return t}clear(){let e=this._store.size;return e===0?0:(this._store.clear(),this._version+=1,e)}pruneExpired(){let e=K(),t=0;for(let[n,s]of this._store)this._isExpired(s,e)&&(this._store.delete(n),t+=1);return t>0&&(this._version+=1),t}toMap(){let e=K(),t=new Map;for(let[n,s]of this._store)this._isExpired(s,e)||t.set(n,s.value);return t}_resolveExpiresAt(e){let t=e??this._defaultTtl;if(t!==void 0){if(!Number.isFinite(t)||t<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${t})`);return K()+t*1e9}}_isExpired(e,t){return e.expiresAt===void 0?!1:(t??K())>=e.expiresAt}_touchLru(e,t){this._store.delete(e),this._store.set(e,t)}_evictLruWhileOver(){if(this._maxSize!==void 0)for(;this._store.size>this._maxSize;){let e=this._store.keys().next().value;if(e===void 0)break;this._store.delete(e)}}};function ct(r={}){let{name:e,maxSize:t,defaultTtl:n,versioning:s,backend:o,retention:i}=r;if(i&&t!==void 0)throw new RangeError("reactiveMap: `maxSize` (LRU) and `retention` (score-based) are mutually exclusive. Pick one eviction policy.");if(i&&i.archiveThreshold===void 0&&i.maxSize===void 0)throw new RangeError("reactiveMap: `retention` requires at least one of `archiveThreshold` or `maxSize` to trigger archival.");let a=o??new Nn({maxSize:t,defaultTtl:n}),d=V(a.toMap(),{name:e,describeKind:"state",equals:(l,h)=>l===h,...s!=null?{versioning:s}:{}});function u(){let l=a.toMap();U(()=>{d.down([[X]]),d.down([[D,l]])})}function c(){if(!i)return;let l=a.toMap(),h=i.archiveThreshold,f=i.maxSize,b=[];for(let[T,v]of l)b.push({key:T,value:v,score:i.score(T,v)});b.sort((T,v)=>T.score-v.score);let m=new Set;if(h!==void 0)for(let T of b)if(T.score<h)m.add(T.key);else break;if(f!==void 0&&b.length-m.size>f)for(let T of b){if(b.length-m.size<=f)break;m.has(T.key)||m.add(T.key)}if(m.size!==0)for(let T of b)m.has(T.key)&&(i.onArchive?.(T.key,T.value,T.score),a.delete(T.key))}function p(l,h="mutation"){let f=a.version;try{return l()}finally{a.version!==f&&(h==="mutation"&&c(),u())}}return{entries:d,has(l){return p(()=>a.has(l),"read")},get(l){return p(()=>a.get(l),"read")},set(l,h,f){p(()=>a.set(l,h,f?.ttl))},setMany(l,h){p(()=>a.setMany(l,h?.ttl))},delete(l){p(()=>a.delete(l))},deleteMany(l){p(()=>a.deleteMany(l))},clear(){p(()=>a.clear())},pruneExpired(){p(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}Pe();function Bo(r){let e=ct({name:r?.name??"effectiveness-entries"}),t=G([e.entries],([i])=>new Map(i),{name:`${r?.name??"effectiveness"}-snapshot`,equals:(i,a)=>{let d=i,u=a;if(d.size!==u.size)return!1;for(let[c,p]of d){let l=u.get(c);if(!l||p.attempts!==l.attempts||p.successes!==l.successes)return!1}return!0}});function n(i,a){let d=e.get(i),u=(d?.attempts??0)+1,c=(d?.successes??0)+(a?1:0);e.set(i,{key:i,attempts:u,successes:c,successRate:c/u})}function s(i){return e.get(i)}let o=ce(t);return{node:t,record:n,lookup:s,dispose:()=>{o(),e.dispose()}}}De();ne();Ye();ne();Ye();De();Re();ye();Ie();ne();Ye();Tt();Mt();De();rt();ye();st();ne();Ie();_t();De();Re();rt();ye();ne();De();ye();Ie();ne();var Cn=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=t,t!==void 0){if(this._buf=new Array(t),e&&e.length>0){let n=Math.min(e.length,t),s=e.length-n;for(let o=0;o<n;o++)this._buf[o]=e[s+o];this._size=n}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let t=e>=0?e:this._size+e;if(!(t<0||t>=this._size))return this._maxSize!==void 0?this._buf[(this._head+t)%this._maxSize]:this._buf[t]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let t=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let n=t;n<e.length;n++)this._rawAppend(e[n]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let t=0;t<e;t++)this._buf[(this._head+t)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let t=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,t);else{for(let n=0;n<t;n++)this._buf[(this._head+n)%this._maxSize]=void 0;this._head=(this._head+t)%this._maxSize}return this._size-=t,this._version+=1,t}slice(e,t){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${t})`);let n=t===void 0?this._size:Math.min(Math.max(t,0),this._size),s=Math.min(e,this._size);if(s>=n)return[];let o=n-s;if(this._maxSize===void 0)return this._buf.slice(s,n);let i=new Array(o);for(let a=0;a<o;a++)i[a]=this._buf[(this._head+s+a)%this._maxSize];return i}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let t=Math.min(e,this._size);return this.slice(this._size-t,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let t=0;t<this._size;t++)e[t]=this._buf[(this._head+t)%this._maxSize];return e}snapshot(){return this.toArray()}restore(e){if(this._maxSize===void 0){this._buf.length=0;for(let t=0;t<e.length;t++)this._buf.push(e[t]);this._size=this._buf.length}else{let t=this._maxSize;for(let o=0;o<t;o++)this._buf[o]=void 0;this._head=0;let n=Math.min(e.length,t),s=e.length-n;for(let o=0;o<n;o++)this._buf[o]=e[s+o];this._size=n}this._version+=1}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function wt(r){return r.subscribe(()=>{})}var us=64;function lt(r,e={}){let{name:t,maxSize:n,versioning:s,guard:o,backend:i}=e,a=i??new Cn(r,n),d=V(a.toArray(),{name:t,describeKind:"state",equals:(y,x)=>y===x,...s!=null?{versioning:s}:{},...o!=null?{guard:o}:{}});function u(){let y=a.toArray();U(()=>{d.down([[X]],{internal:!0}),d.down([[D,y]],{internal:!0})})}let c=new Map,p=new Map,l=new Map;function h(y,x){return`${y}:${x===void 0?"END":x}`}function f(y){if(y.size<us)return;let x=y.keys().next();if(x.done)return;let k=y.get(x.value);k!==void 0&&k.dispose(),y.delete(x.value)}function b(y){let x=a.version;try{return y()}finally{a.version!==x&&u()}}function m(y){if(!Number.isInteger(y)||y<0)throw new RangeError(`tail: n must be a non-negative integer (got ${y})`);let x=c.get(y);if(x!==void 0)return c.delete(y),c.set(y,x),x.node;f(c);let k=G([d],([E])=>{let P=E;return y===0||P.length===0?[]:P.slice(Math.max(0,P.length-y))},{initial:a.tail(y),describeKind:"derived"}),A=wt(k);return c.set(y,{node:k,dispose:A}),k}function T(y,x){if(!Number.isInteger(y)||y<0)throw new RangeError(`slice: start must be a non-negative integer (got ${y})`);if(x!==void 0&&(!Number.isInteger(x)||x<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${x})`);let k=h(y,x),A=p.get(k);if(A!==void 0)return p.delete(k),p.set(k,A),A.node;f(p);let E=G([d],([H])=>{let F=H;return x===void 0?F.slice(y):F.slice(y,x)},{initial:a.slice(y,x),describeKind:"derived"}),P=wt(E);return p.set(k,{node:E,dispose:P}),E}function v(y){let x=l.get(y);if(x!==void 0)return x.node;let k=G([d,y],([E,P])=>{let H=E,F=Math.max(0,Math.trunc(P??0));return H.slice(F)},{initial:[],describeKind:"derived"}),A=wt(k);return l.set(y,{node:k,dispose:A}),k}let g,_;function w(){g===void 0&&(g=te([d],(y,x,k)=>{let A=y[0],P=A!=null&&A.length>0?A.at(-1):k.prevData[0];if(P==null||P.length===0){x.down([[J]]);return}x.emit(P[P.length-1])},{name:t!=null?`${t}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),_=G([d],([y])=>y.length>0,{name:t!=null?`${t}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),wt(g),wt(_))}let N={entries:d,get size(){return a.size},at(y){return a.at(y)},append(y){b(()=>a.append(y))},appendMany(y){y.length!==0&&b(()=>a.appendMany(y))},clear(){b(()=>a.clear())},trimHead(y){b(()=>a.trimHead(y))},withLatest(){return w(),d},get lastValue(){return w(),g},get hasLatest(){return w(),_},view(y){switch(y.kind){case"tail":return m(y.n);case"slice":return T(y.start,y.stop);case"fromCursor":return v(y.cursor)}},attach(y){let x=y.subscribe(k=>{for(let A of k)A[0]===D&&N.append(A[1])});return()=>x()},attachStorage(y){if(y.length===0)return()=>{};let x=new Map;for(let A of y)x.set(A,a.size);(async()=>{for(let A of y)if(typeof A.loadEntries=="function")try{let E=await Promise.resolve(A.loadEntries());E.entries.length>0&&a.size===0&&(a.restore(E.entries),x.set(A,E.entries.length),u());break}catch{}})();let k=d.subscribe(A=>{for(let E of A){if(E[0]!==D)continue;let P=E[1];for(let H of y){let F=x.get(H)??0;if(P.length<F){try{let Te=H.appendEntries(P);Te instanceof Promise&&Te.catch(()=>{})}catch{}x.set(H,P.length);continue}if(P.length===F)continue;let ve=P.slice(F);x.set(H,P.length);try{let Te=H.appendEntries(ve);Te instanceof Promise&&Te.catch(()=>{})}catch{}}}});return()=>k()},disposeAllViews(){for(let y of c.values())y.dispose();c.clear();for(let y of p.values())y.dispose();p.clear();for(let y of l.values())y.dispose();l.clear()},dispose(){for(let y of c.values())y.dispose();c.clear();for(let y of p.values())y.dispose();p.clear();for(let y of l.values())y.dispose();l.clear()}};return N}function Dn(r,e){let t=r.cache??0;return t>=e?!1:(r.down([[X],[D,t+1]]),!0)}var ds=ur((r,e)=>{r("observe"),r("signal"),e("write")});function Wt(r){let e=lt([],{name:r.name,maxSize:r.retainedLimit??1024,guard:r.guard??ds,...r.versioning!=null?{versioning:r.versioning}:{}});return e.withLatest(),r.graph&&r.graph.add(e.entries,{name:r.name}),e}function Mn(r){if(r===null||typeof r!="object"||Object.isFrozen(r))return r;for(let e of Object.keys(r))Mn(r[e]);return Object.freeze(r)}var jr=new WeakSet;function Jt(r){let e=r.cache,t=typeof e=="number"&&Number.isFinite(e);!t&&e!==void 0&&!jr.has(r)&&(jr.add(r),console.warn(`bumpCursor: cursor cache held a non-numeric value (${String(e)}); resetting to 0. Causes include: a snapshot codec round-tripping the cursor as a string / null / NaN, OR a malformed initial seed (e.g. state<number>(NaN)). Audit consumers may see colliding seq values after this point.`));let s=(t?e:0)+1;return r.down([[X],[D,s]]),s}function Kt(r,e,t,n,s,o){let i=e(t,n,s);if(i===void 0)return;let a=o!=null?{...i,handlerVersion:o}:i;r.append(a)}function Le(r,e){let t=e.freeze??!0;return function(...s){let o=t?s.map(Mn):s,i=Me(),a=e.seq?Jt(e.seq):void 0;try{let d=r(...o);return e.audit&&e.onSuccess&&Kt(e.audit,e.onSuccess,o,d,{t_ns:i,seq:a},e.handlerVersion),d}catch(d){if(e.audit&&e.onFailure){let u=d instanceof Error?d.name:typeof d;Kt(e.audit,e.onFailure,o,d,{t_ns:i,seq:a,errorType:u},e.handlerVersion)}throw d}}}function ft(r,e){let t=e.freeze??!0;return function(...s){let o=t?s.map(Mn):s,i=Me(),a,d,u=!1,c;try{U(()=>{e.seq&&(c=Jt(e.seq));try{a=r(...o),e.audit&&e.onSuccess&&Kt(e.audit,e.onSuccess,o,a,{t_ns:i,seq:c},e.handlerVersion)}catch(p){throw d=p,u=!0,p}})}catch(p){if(u&&e.audit&&e.onFailure){let l=d instanceof Error?d.name:typeof d;Kt(e.audit,e.onFailure,o,d,{t_ns:i,seq:c,errorType:l},e.handlerVersion)}throw u?d:p}return a}}function zr(r,e,t=0){let n=V(t,{name:e,describeKind:"state"});return r.add(n,{name:e}),n}Pe();In();var cs=256;function pt(r,e){if(!Number.isFinite(r)||!Number.isInteger(r)||r<0)throw new Error(`${e} must be a non-negative integer`);return r}function Be(r,e){return He("messaging",r,e)}var ls=1024,Gn=class extends le{_log;_publishImpl;events;latest;hasLatest;constructor(e,t={}){super(e,t.graph),this._log=lt([],{name:"events",maxSize:t.retainedLimit??ls}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=G([this.events],([n])=>{let s=n;return s.length===0?null:s[s.length-1]},{name:"latest",describeKind:"derived",meta:Be("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(ce(this.latest)),this.hasLatest=G([this.events],([n])=>n.length>0,{name:"hasLatest",describeKind:"derived",meta:Be("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(ce(this.hasLatest)),this.addDisposer(()=>{this.events.down([[$]])}),this.addDisposer(()=>this._log.disposeAllViews()),this._publishImpl=Le(n=>{this._log.append(n)},{freeze:!1})}publish(e){if(e===void 0)throw new TypeError(`TopicGraph "${this.name}": publish(undefined) is not allowed (spec \xA75.12 SENTINEL).`);this._publishImpl(e)}attachEventStorage(e){return this._log.attachStorage(e)}retained(){return this.events.cache}get _logBundle(){return this._log}},Yt=class extends le{cursor;available;topic;_disposed=!1;_ackImpl;_pullAndAckImpl;constructor(e,t,n={}){super(e,n.graph),this.topic=t;let s;if(n.from!==void 0?n.from==="retained"?s=0:n.from==="now"?s=t.events.cache.length:s=pt(n.from,"subscription from"):s=pt(n.cursor??0,"subscription cursor"),this.cursor=V(s,{name:"cursor",describeKind:"state",meta:Be("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=t._logBundle.view({kind:"fromCursor",cursor:this.cursor}),this.add(this.available,{name:"available"}),this.addDisposer(ce(this.available)),n.advanceOn!==void 0){let o=n.advanceOn,i=!1,a=te([o],()=>{if(!i){i=!0;return}if(this._disposed)return;let d=this.available.cache;if(d.length===0)return;let u=this.cursor.cache+d.length;this.cursor.emit(u)},{name:"advancePump",describeKind:"effect",meta:Be("subscription_advance_pump")});this.add(a,{name:"advancePump"}),this.addDisposer(ce(a))}this._ackImpl=Le(o=>{let i=this.available.cache,a=o===void 0?i.length:pt(o,"subscription ack count"),d=Math.min(a,i.length);if(d<=0)return this.cursor.cache;let u=this.cursor.cache+d;return this.cursor.emit(u),u},{freeze:!1}),this._pullAndAckImpl=Le(o=>{let i=this.available.cache,a=o===void 0?i.length:pt(o,"subscription pullAndAck limit"),d=i.slice(0,a);if(d.length===0)return{items:d,cursor:this.cursor.cache};let u=this.cursor.cache+d.length;return this.cursor.emit(u),{items:d,cursor:u}},{freeze:!1})}ack(e){return this._disposed?this.cursor.cache:this._ackImpl(e)}pull(e){if(this._disposed)return[];let t=this.available.cache,n=e===void 0?t.length:pt(e,"subscription pull limit");return t.slice(0,n)}pullAndAck(e){return this._disposed?{items:[],cursor:this.cursor.cache}:this._pullAndAckImpl(e)}dispose(){this._disposed||(this._disposed=!0,this.cursor.down([[$]]),this.destroy())}},Pn=class extends le{_sourceSub;bridgedCount;output;constructor(e,t,n,s={}){super(e,s.graph),this._sourceSub=ps(`${e}-subscription`,t,{cursor:s.cursor}),this.mount("subscription",this._sourceSub);let o=Math.max(1,pt(s.maxPerPump??cs,"topic bridge maxPerPump")),i=s.map??(l=>l);this.output=G([this._sourceSub.available],([l])=>{let h=l,f=[],b=Math.min(h.length,o);for(let m=0;m<b;m++){let T=i(h[m]);T!==void 0&&f.push(T)}return f},{name:"output",describeKind:"derived",meta:Be("topic_bridge_output",{targetRef:n.name}),initial:[]}),this.add(this.output,{name:"output"}),this.addDisposer(ce(this.output)),this.bridgedCount=V(0,{name:"bridgedCount",describeKind:"state",meta:Be("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"}),this.addDisposer(ce(this.bridgedCount));let a=this.output,d=this._sourceSub,u=this.bridgedCount,c=te([a],()=>{let l=a.cache;if(l.length===0)return;let h=d.available.cache.length,f=Math.min(h,o);if(f>0){d.ack(f);let b=u.cache??0;u.emit(b+l.length)}},{name:"ackPump",describeKind:"effect",meta:Be("topic_bridge_ack_pump")});this.add(c,{name:"ackPump"}),this.addDisposer(ce(c));let p=fs(this.output,n);this.addDisposer(p)}};function fs(r,e){return r.subscribe(t=>{for(let n of t){if(n[0]!==D)continue;let s=n[1];s.length!==0&&U(()=>{for(let o of s)e.publish(o)})}})}var Ln=class{_map=new Map;version;constructor(e){this.version=e}get size(){return this._map.size}has(e){return this._map.has(e)}get(e){return this._map.get(e)}set(e,t){this._map.set(e,t)}delete(e){return this._map.delete(e)}keys(){return this._map.keys()}},Fn=class extends le{_registry;version;_defaultTopicOptions;_removeTopicImpl;constructor(e,t={}){super(e,t.graph);let n=V(0,{name:"version",describeKind:"state",meta:Be("hub_version")});this.add(n,{name:"version"}),this.version=n,this._registry=new Ln(n),this._defaultTopicOptions={...t.defaultTopicOptions??{}},this._removeTopicImpl=Le(s=>{try{this.remove(s)}finally{this._registry.delete(s);let o=this.version.cache??0;this.version.emit(o+1)}},{freeze:!1})}get size(){return this._registry.size}has(e){return this._registry.has(e)}topicNames(){return this._registry.keys()}topic(e,t){let n=this._registry.get(e);if(n===void 0){let s={...this._defaultTopicOptions,...t??{}};n=new Gn(e,s),this._registry.set(e,n),this.mount(e,n);let o=this.version.cache??0;this.version.emit(o+1)}return n}publish(e,t){this.topic(e).publish(t)}publishMany(e){U(()=>{for(let[t,n]of e)this.topic(t).publish(n)})}subscribe(e,t,n){let s=this.topic(t);return new Yt(e,s,n)}removeTopic(e){return this._registry.has(e)?(this._removeTopicImpl(e),!0):!1}};function Qt(r,e){return new Fn(r,e)}function ps(r,e,t){return new Yt(r,e,t)}function $n(r,e,t,n){return new Pn(r,e,t,n)}function hs(r){if(typeof r!="object"||r===null)return!1;let e=r;return typeof e.subscribe=="function"&&typeof e.down=="function"&&typeof e.emit=="function"}function Hr(r,e){if(r.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(r.length===1){let o=Vn(e);return{best:r[0],bestScore:o}}if(e.some(o=>typeof o.candidateIndex=="number")){let o=new Array(r.length);for(let d=0;d<r.length;d++)o[d]={sum:0,count:0};for(let d of e){let u=d.candidateIndex;typeof u=="number"&&u>=0&&u<r.length&&(o[u].sum+=d.score,o[u].count+=1)}let i=r[0],a=o[0].count>0?o[0].sum/o[0].count:Number.NEGATIVE_INFINITY;for(let d=1;d<r.length;d++){let u=o[d].count>0?o[d].sum/o[d].count:Number.NEGATIVE_INFINITY;u>a&&(a=u,i=r[d])}return{best:i,bestScore:a}}let n=r[0],s=e[0]?.score??Number.NEGATIVE_INFINITY;for(let o=1;o<r.length;o++){let i=e[o]?.score??Number.NEGATIVE_INFINITY;i>s&&(s=i,n=r[o])}return{best:n,bestScore:s}}function Vn(r){if(r.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let t of r)e+=t.score;return e/r.length}function jn(r,e,t,n){let s=n.name??"refine-loop",o=new le(s,n.graph),i=hs(n.dataset)?n.dataset:V(n.dataset,{name:"dataset"});o.add(i,{name:"dataset"});let a=V(0,{name:"iteration"});o.add(a,{name:"iteration"});let d=V(t,{name:"strategy",equals:()=>!1});o.add(d,{name:"strategy"});let u=V(null,{name:"lastFeedback"});o.add(u,{name:"lastFeedback"});let c=V([],{name:"prevCandidates"});o.add(c,{name:"prevCandidates"});let p=V(!1,{name:"paused"});o.add(p,{name:"paused"});let l=V("running",{name:"status"});o.add(l,{name:"status"});let h=V([],{name:"history",equals:()=>!1});o.add(h,{name:"history"});let f=V(null,{name:"best"});o.add(f,{name:"best"});let b=V(Number.NEGATIVE_INFINITY,{name:"score"});o.add(b,{name:"score"});let m=V(0,{name:"budget-used"});o.add(m,{name:"budget-used"});let T=Qt("stages");o.mount("stages",T);let v=T.topic("generate"),g=T.topic("evaluate"),_=T.topic("analyze"),w=T.topic("decide"),N=t,y=null,x=[];o.addDisposer(d.subscribe(R=>{for(let M of R)M[0]===D&&(N=M[1])})),o.addDisposer(u.subscribe(R=>{for(let M of R)M[0]===D&&(y=M[1])})),o.addDisposer(c.subscribe(R=>{for(let M of R)M[0]===D&&(x=M[1])}));let k=it(a,R=>{let M=N,ee=R===0||y==null;return te([],(re,fe)=>{let B=!1;try{let O=ee?M.seed(r):M.generate(y,x);if(O instanceof Promise)return O.then(S=>{B||fe.emit(S)},S=>{B||fe.down([[I,S]])}),()=>{B=!0};fe.emit(O)}catch(O){B=!0,fe.down([[I,O]])}},{describeKind:"producer"})},{name:"candidates"});o.add(k,{name:"candidates"});let A=me([k],(R,M,ee)=>{let re=ee.terminalDeps[0];re!==void 0&&re!==!0&&l.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});o.add(A,{name:"error-watcher"}),o.addDisposer(A.subscribe(()=>{}));let E=G([k,a],([R,M])=>({iteration:M,candidates:R,timestamp_ns:K()}),{name:"generate-event"});o.add(E,{name:"generate-event"}),o.addDisposer(E.subscribe(()=>{}));let P=me([E],([R])=>{v.publish(R)},{name:"generate-publish"});o.add(P,{name:"generate-publish"}),o.addDisposer(P.subscribe(()=>{}));let H=me([k],([R])=>{c.emit(R)},{name:"generate-mirror"});o.add(H,{name:"generate-mirror"}),o.addDisposer(H.subscribe(()=>{}));let F=e(k,i);o.add(F,{name:"scores"});let ve=G([F,k,a],([R,M,ee])=>({iteration:ee,candidates:M,scores:R,timestamp_ns:K()}),{name:"evaluate-event"});o.add(ve,{name:"evaluate-event"}),o.addDisposer(ve.subscribe(()=>{}));let Te=me([ve],([R])=>{g.publish(R)},{name:"evaluate-publish"});o.add(Te,{name:"evaluate-publish"}),o.addDisposer(Te.subscribe(()=>{}));let Ee=G([F,k],([R,M])=>N.analyze(R,M),{name:"feedback"});o.add(Ee,{name:"feedback"});let Ne=G([Ee,k,a],([R,M,ee])=>({iteration:ee,candidates:M,feedback:R,timestamp_ns:K()}),{name:"analyze-event"});o.add(Ne,{name:"analyze-event"}),o.addDisposer(Ne.subscribe(()=>{}));let j=me([Ne],([R])=>{_.publish(R)},{name:"analyze-publish"});o.add(j,{name:"analyze-publish"}),o.addDisposer(j.subscribe(()=>{}));let z=G([h],([R])=>{let M=R;if(n.patience==null||M.length<=n.patience)return!1;let ee=M.slice(-(n.patience+1)),re=ee[0].bestScore;return ee.slice(1).every(fe=>fe.bestScore<=re)},{name:"patience-check"});o.add(z,{name:"patience-check"});let L=G([b],([R])=>n.minScore!=null&&R>=n.minScore,{name:"min-score-check"});o.add(L,{name:"min-score-check"});let ue=G([h],([R])=>{let M=R;if(n.minDelta==null||M.length<2)return!1;let ee=M[M.length-2].bestScore,re=M[M.length-1].bestScore;return Math.abs(re-ee)<n.minDelta},{name:"min-delta-check"});o.add(ue,{name:"min-delta-check"});let Z=G([m],([R])=>n.maxEvaluations!=null&&R>=n.maxEvaluations,{name:"max-evaluations-check"});o.add(Z,{name:"max-evaluations-check"});let ge=G([a],([R])=>n.maxIterations!=null&&R>=n.maxIterations,{name:"max-iterations-check"});o.add(ge,{name:"max-iterations-check"});let C=G([m],([R])=>n.budget!=null&&R>=n.budget,{name:"budget-exhausted-check"});o.add(C,{name:"budget-exhausted-check"}),o.addDisposer(z.subscribe(()=>{})),o.addDisposer(L.subscribe(()=>{})),o.addDisposer(ue.subscribe(()=>{})),o.addDisposer(Z.subscribe(()=>{})),o.addDisposer(ge.subscribe(()=>{})),o.addDisposer(C.subscribe(()=>{}));let q=G([z,L,ue,Z,ge],([R,M,ee,re,fe])=>R?{converged:!0,reason:"patience"}:M?{converged:!0,reason:"min-score"}:ee?{converged:!0,reason:"min-delta"}:re?{converged:!0,reason:"max-evaluations"}:fe?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});o.add(q,{name:"converged"}),o.addDisposer(q.subscribe(()=>{}));let be=-1,Ge=me([Ee,F,k],([R,M,ee])=>{let re=a.cache,fe=R,B=ee,O=M;if(re<=be)return;be=re;let{best:S,bestScore:Q}=Hr(B,O),oe=h.cache,Fe={n:re,candidates:B,scores:O,feedback:fe,best:S,bestScore:Q,timestamp_ns:K()},pe=[...oe,Fe],$e=m.cache+B.length,se="continue",_e,tn=n.budget!=null&&$e>=n.budget,nn=p.cache;if(tn)se="budget",_e="budget";else if(n.minScore!=null&&fe.score>=n.minScore)se="converged",_e="min-score";else if(n.maxIterations!=null&&re>=n.maxIterations)se="converged",_e="max-iterations";else if(n.maxEvaluations!=null&&$e>=n.maxEvaluations)se="converged",_e="max-evaluations";else if(n.minDelta!=null&&pe.length>=2){let Rt=pe[pe.length-2].bestScore,rn=pe[pe.length-1].bestScore;Math.abs(rn-Rt)<n.minDelta&&(se="converged",_e="min-delta")}else if(n.patience!=null&&pe.length>n.patience){let Rt=pe.slice(-(n.patience+1)),rn=Rt[0].bestScore;Rt.slice(1).every(ro=>ro.bestScore<=rn)&&(se="converged",_e="patience")}se==="continue"&&nn&&(se="paused"),U(()=>{f.emit(S),b.emit(fe.score),h.emit(pe),m.emit($e),u.emit(fe),w.publish({iteration:re,decision:se,reason:_e,timestamp_ns:K()}),se==="continue"?a.emit(re+1):l.emit(se==="converged"?"converged":se==="budget"?"budget":"paused")})},{name:"decide-bridge"});return o.add(Ge,{name:"decide-bridge"}),o.addDisposer(Ge.subscribe(()=>{})),Object.assign(o,{best:f,score:b,status:l,history:h,strategy:d,iteration:a,generate:v,evaluate:g,analyze:_,decide:w,setStrategy(R){d.emit(R)},pause(){p.emit(!0)},resume(){l.cache==="paused"&&U(()=>{p.emit(!1),l.emit("running"),a.emit(a.cache+1)})}})}function ms(r){let e=r.width??4;return{name:r.name??"blindVariation",seed(n){return[n]},analyze(n,s){let o=Vn(n),i=null;for(let a of n)(!i||a.score<i.score)&&(i=a);return{summary:`blindVariation iteration: mean=${o.toFixed(3)}, n=${n.length}`,score:o,weakTasks:i?[i.taskId]:[]}},async generate(n,s){if(s.length===0)throw new Error("blindVariation.generate: empty candidate batch \u2014 cannot derive prior for teacher");let o=s[s.length-1],i=0,d={prior:o,reportCost:u=>{i+=u}};try{if(r.parallel!==!1)return await Promise.all(Array.from({length:e},()=>r.teacher(d)));let u=[];for(let c=0;c<e;c++)u.push(await r.teacher(d));return u}finally{if(r.tokens!=null&&i>0){let u=r.tokens.cache??0;r.tokens.emit(u+i)}}}}}function gs(r){return typeof r=="object"&&r!==null&&r.kind==="errorCritique"}function bs(r,e){return r.length===0?`No task scored below the batch mean (${e.score.toFixed(3)}). Reinforce the current direction.`:`Failures below threshold:
45
+ ${r.map(n=>{let s=n.error!=null?` | error: ${n.error}`:"";return`- ${n.taskId} (score=${n.score.toFixed(3)})${s}`}).join(`
46
+ `)}`}function ys(r){let e=r.width??4,t=r.name??"errorCritique",n=r.maxFailureSamples??5,s=r.formatCritique??bs;return{name:t,seed(o){return[o]},analyze(o,i){let a=Vn(o),d=typeof r.failureThreshold=="function"?r.failureThreshold(o):r.failureThreshold,u=d===void 0&&!Number.isFinite(a),c=d??a,p=u?[...o].sort((g,_)=>g.score-_.score):o.filter(g=>g.score<c).slice().sort((g,_)=>g.score-_.score),l=p.slice(0,n),{best:h,bestScore:f}=Hr(i,o),b={summary:"",score:a,weakTasks:l.map(g=>g.taskId)},m=s(l,b),T={kind:"errorCritique",best:h,failures:l,critiqueText:m},v=p.length>l.length?` (top ${l.length} retained)`:"";return{summary:`errorCritique iteration: mean=${a.toFixed(3)}, failures=${p.length}${v}/${o.length}, bestScore=${f.toFixed(3)}`,critique:T,weakTasks:l.map(g=>g.taskId),score:a}},async generate(o,i){if(i.length===0)throw new Error("errorCritique.generate: empty candidate batch \u2014 cannot derive prior for teacher");let a=gs(o.critique)?o.critique:void 0,d=a!==void 0?a.best:i[i.length-1],u=a?.critiqueText??o.summary,c=a?.failures??[],p=0,h={prior:d,critique:u,failures:c,reportCost:f=>{p+=f}};try{if(r.parallel!==!1)return await Promise.all(Array.from({length:e},()=>r.teacher(h)));let f=[];for(let b=0;b<e;b++)f.push(await r.teacher(h));return f}finally{if(r.tokens!=null&&p>0){let f=r.tokens.cache??0;r.tokens.emit(f+p)}}}}}function vs(r){let{best:e,score:t,status:n}=r,s=Number.isFinite(t)?t.toFixed(3):String(t),o=e??void 0;return n==="converged"?{outcome:"success",detail:`refineLoop converged at score ${s}`,artifact:o}:n==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${s}`,artifact:o}:{outcome:"failure",detail:`refineLoop errored (status=${n})`,artifact:o}}function zn(r){let e=r.name??"refine-executor",t=r.toOutput??vs;return n=>{let s=n.payload.item,o=jn(r.seedFrom(s),r.evaluator,r.strategy,{...r.refine,dataset:r.datasetFor(s),name:`${e}/inner`}),i=G([o.status,o.best,o.score],([a,d,u])=>{let c=a;if(c!=="converged"&&c!=="budget"&&c!=="errored")return null;let p=t({best:d,score:u,status:c});return{...n.payload,execution:{item:s,...p}}},{name:`${e}/output`});return Ft(i,a=>a!=null,{name:`${e}/gate-out`})}}function Ts(r){if(r.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let t of r)e+=t.score;return e/r.length}function _s(r){let{passCount:e,total:t,meanScore:n,threshold:s,missingArtifact:o}=r,i=Number.isFinite(n)?n.toFixed(3):String(n),a=!o&&t>0&&n>=s,d=o?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:a?[`${e}/${t} eval tasks passed; mean score ${i} \u2265 ${s}`]:t===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${e}/${t} eval tasks passed; mean score ${i} < threshold ${s}`];return a?{verified:!0,findings:d}:{verified:!1,findings:d,errorClass:"structural"}}function ws(r){return r.artifact??null}function Br(r){let e=r.name??"eval-verifier",t=r.threshold??.5,n=r.toOutput??_s,s=r.extractArtifact??ws;return o=>{let{item:i,execution:a}=o.payload;if(a==null)return{...o.payload,verify:{verified:!1,findings:["evalVerifier: prior execute stage produced no execution"],errorClass:"structural"}};let d=s(a,i);if(d==null)return{...o.payload,verify:n({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:t,missingArtifact:!0})};let u=V([d],{name:`${e}/candidates`}),c=V(r.datasetFor(i),{name:`${e}/dataset`}),p;U(()=>{p=r.evaluator(u,c)});let l=G([p],([h])=>{let f=h;if(f==null)return null;let b=Ts(f),m=f.filter(T=>T.score>=t).length;return{...o.payload,verify:n({scores:f,meanScore:b,passCount:m,total:f.length,threshold:t})}},{name:`${e}/output`});return Ft(l,h=>h!=null,{name:`${e}/gate-out`})}}function xs(r){let e=r.name??"harness-pair",t=zn({name:`${e}-exec`,seedFrom:r.seedFrom,evaluator:r.evaluator,strategy:r.strategy,datasetFor:r.datasetFor,refine:r.refine}),n=Br({name:`${e}-verify`,evaluator:r.evaluator,datasetFor:r.datasetFor,threshold:r.threshold});return{executor:t,verifier:n}}Re();st();ne();Ye();Tt();function xt(r){return r.relatedTo?.[0]??r.summary}ye();ne();_t();Pe();function Nt(r,e){return He("ai",r,e)}function Et(r){let e=r.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:r}function Hn(r,e,t){return de(n=>{let s=new AbortController,o=!1,i=null,a=c=>{o||(o=!0,n.down([[D,c],[$]]),i?.(),i=null)},d;try{d=r.invoke(e,{...t.invokeOpts,signal:s.signal})}catch(c){return a(t.onFailure("throw",c)),()=>s.abort()}return i=Ae(d,{signal:s.signal}).subscribe(c=>{for(let p of c){if(o)return;if(p[0]===D){try{a(t.onSuccess(p[1]))}catch(l){a(t.onFailure("onSuccess-threw",l))}return}if(p[0]===I){a(t.onFailure("error",p[1]));return}if(p[0]===$){a(t.onFailure("complete",void 0));return}}}),o&&i&&(i(),i=null),()=>{s.abort(),i?.(),i=null}})}ye();ne();Ye();Pe();function qr(r){return r!=null&&typeof r=="object"&&"content"in r?String(r.content):typeof r=="string"?r:String(r)}function Ns(r,e=200){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function Ur(r,e,t,n){let s=n?.format??"text",o=n?.name??"prompt_node";n?.tools!==void 0&&s!=="raw"&&console.warn("promptNode: `tools` is set but `format !== 'raw'`. Tool calls in the response will be silently dropped \u2014 set `format: 'raw'` to receive the full LLMResponse with `toolCalls`.");let i=e.length,a=n?.tools!==void 0?[...e,n.tools]:e,d=G(a,c=>{let p=c.slice(0,i),l=n?.tools!==void 0?c[i]:void 0;if(p.some(f=>f==null))return{messages:[],tools:l};let h=typeof t=="string"?t:t(...p);return h?{messages:[{role:"user",content:h}],tools:l}:{messages:[],tools:l}},{name:`${o}::messages`,meta:Nt("prompt_node")});return it(d,c=>{let{messages:p,tools:l}=c;return!p||p.length===0?V(null):de(h=>{let f=!1,b=!1,m,T={model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,systemPrompt:n?.systemPrompt,...l!==void 0?{tools:l}:{}};if(n?.abort){let w=gr(n.abort);T.signal=w.signal,m=w.dispose}let v;try{v=r.invoke(p,T)}catch(w){return f=!0,h.down([[I,w]]),()=>{m?.()}}let _=Ae(v).subscribe(w=>{if(!(b||f))for(let N of w){if(f)return;if(N[0]===D){let y=N[1];if(s==="raw")h.emit(y);else try{let x=qr(y),k=s==="json"?JSON.parse(Et(x)):x;h.emit(k)}catch(x){let k=qr(y),A=new Error(`promptNode: failed to parse LLM response as JSON: ${x.message}
47
+ Raw content (first 200 chars): ${Ns(k)}`);f=!0,h.down([[I,A]]);return}}else if(N[0]===I){f=!0,h.down([[I,N[1]]]);return}else if(N[0]===$){f=!0,h.down([[$]]);return}else h.down([N])}});return()=>{b=!0,_(),m?.()}},{name:`${o}::call`,meta:Nt("prompt_node::call")})},{name:`${o}::output`,meta:n?.meta?{...Nt("prompt_node::output"),...n.meta}:Nt("prompt_node::output")})}De();Re();ye();st();Ie();ne();_t();Tt();function kt(r,e){return He("orchestration",r,e)}var Xt=class extends le{constructor(e,t){super(e,t)}task(e,t,n={}){let s=(n.deps??[]).map(i=>this._resolveStep(i)),o=G(s,t,{name:e,describeKind:"derived",meta:kt("task",n.meta)});return this.add(o,{name:e}),o}classify(e,t,n,s={}){let o=this._resolveStep(t),i=G([o],([a])=>{try{return{tag:n(a),value:a}}catch(d){return{tag:"error",value:a,error:d}}},{name:e,describeKind:"derived",meta:kt("classify",s.meta)});return this.add(i,{name:e}),i}combine(e,t,n={}){let s=Object.keys(t),o=s.map(a=>this._resolveStep(t[a])),i=G(o,a=>{let d={};for(let u=0;u<s.length;u++)d[s[u]]=a[u];return d},{name:e,describeKind:"derived",meta:kt("combine",n.meta)});return this.add(i,{name:e}),i}approvalGate(e,t,n={}){let s=n.maxPending??1e3;if(s<1&&s!==Number.POSITIVE_INFINITY)throw new RangeError("approvalGate: maxPending must be >= 1");let o=n.startOpen??!1;typeof t!="string"&&this.nameOf(t)===void 0&&this.add(t,{name:`${e}/source`});let i=this._resolveStep(t),a=new le(`${e}_state`),d=V([],{name:"pending",equals:()=>!1}),u=V(o,{name:"isOpen"}),c=G([d],([j])=>j.length,{name:"count"}),p=V(0,{name:"droppedCount"}),l=Wt({name:"decisions",retainedLimit:1024,graph:a});a.add(d,{name:"pending"}),a.add(u,{name:"isOpen"}),a.add(c,{name:"count"}),a.add(p,{name:"droppedCount"}),this.mount(`${e}_state`,a);let h=[],f=!1,b=!1,m=o,T=u.subscribe(j=>{for(let z of j)z[0]===D&&(m=z[1])});this.addDisposer(T);function v(){d.emit([...h])}function g(j,z,L){l.append({action:j,t_ns:Me(),...z!==void 0?{items:z,count:z.length}:{},...L!==void 0?{unflushed:L}:{},...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}function _(j){if(h.push(j),h.length>s){let z=h.shift();p.emit(p.cache+1),g("drop",[z])}v()}function w(j){let z=h.splice(0,j);return v(),z}let N=te([i],(j,z,L)=>{let ue=L.terminalDeps[0];if(ue!==void 0){f=!0;let ge=h.length;h=[],v(),g("teardown",void 0,ge),z.down(ue===!0?[[$]]:[[I,ue]]);return}let Z=j[0];if(Z==null||Z.length===0){z.down([[J]]);return}for(let ge of Z)m?z.emit(ge):(_(ge),z.down([[J]]))},{name:e,describeKind:"derived",meta:kt("approval_gate",n.meta)});if(this.add(N,{name:e}),n.approver!=null){n.approver.cache&&(u.emit(!0),m=!0,n.onceOnly&&(b=!0));let z=n.approver.subscribe(L=>{for(let ue of L){if(ue[0]!==D)continue;let Z=!!ue[1];if(Z&&!m){if(n.onceOnly){if(b)continue;b=!0}U(()=>{u.emit(!0);let ge=w(h.length);g("open",ge);for(let C of ge){if(f)break;N.emit(C)}})}else if(!Z&&m){if(n.onceOnly&&b)continue;U(()=>{u.emit(!1),g("close")})}}});this.addDisposer(z)}let y=j=>{if(f)throw new Error(`approvalGate: ${j}() called after the gate was torn down`)},x=(j=1)=>{y("approve");let z=w(j);for(let L of z){if(f)break;N.emit(L)}},k=(j=1)=>{y("reject"),w(j)},A=(j,z=1)=>{y("modify");let L=[...h],ue=w(z);for(let Z=0;Z<ue.length&&!f;Z++)N.emit(j(ue[Z],Z,L))},E=()=>{y("open"),u.emit(!0);let j=w(h.length);for(let z of j){if(f)break;N.emit(z)}},P=()=>{y("close"),!(n.onceOnly&&b)&&u.emit(!1)},H=ft(x,{audit:l,freeze:!1,onSuccess:(j,z,L)=>({action:"approve",count:j[0]??1,t_ns:L.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:(j,z,L)=>({action:"drop",t_ns:L.t_ns,errorType:L.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}),F=ft(k,{audit:l,freeze:!1,onSuccess:(j,z,L)=>({action:"reject",count:j[0]??1,t_ns:L.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:(j,z,L)=>({action:"drop",t_ns:L.t_ns,errorType:L.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}),ve=ft(A,{audit:l,freeze:!1,onSuccess:(j,z,L)=>({action:"modify",count:j[1]??1,t_ns:L.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:(j,z,L)=>({action:"drop",t_ns:L.t_ns,errorType:L.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}),Te=ft(E,{audit:l,freeze:!1,onSuccess:(j,z,L)=>({action:"open",t_ns:L.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:(j,z,L)=>({action:"drop",t_ns:L.t_ns,errorType:L.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}),Ee=ft(P,{audit:l,freeze:!1,onSuccess:(j,z,L)=>({action:"close",t_ns:L.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:(j,z,L)=>({action:"drop",t_ns:L.t_ns,errorType:L.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})});return this.addDisposer(c.subscribe(()=>{})),{node:N,pending:d,count:c,isOpen:u,droppedCount:p,decisions:l,audit:l,approve:H,reject:F,modify:ve,open:Te,close:Ee}}approval(e,t,n,s={}){return this.approvalGate(e,t,{...s,approver:n,maxPending:1})}catch(e,t,n,s={}){let o=this._resolveStep(t),i=s.on??"errored",a=te([o],(d,u,c)=>{let p=c.terminalDeps[0];if(p!==void 0){let h=p===!0?{kind:"completed"}:{kind:"errored",error:p};if(i==="terminal"||i===h.kind){u.emit(n(h,u));return}u.down(h.kind==="completed"?[[$]]:[[I,h.error]]);return}let l=d[0];if(l==null||l.length===0){u.down([[J]]);return}for(let h of l)u.emit(h)},{name:e,describeKind:"derived",completeWhenDepsComplete:s.completeWhenDepsComplete??!(i==="completed"||i==="terminal"),errorWhenDepsError:!(i==="errored"||i==="terminal"),meta:kt("catch",s.meta)});return this.add(a,{name:e}),a}_resolveStep(e){if(typeof e=="string")return this.resolve(e);if(this.nameOf(e)===void 0)throw new Error(`PipelineGraph "${this.name}": Node dep is not registered. Pass a string path or call graph.add(node) first.`);return e}};function Bn(r,e){let t=new Xt(r,e),{factory:n,factoryArgs:s,...o}=e??{};return t.tagFactory("pipelineGraph",We(o)),t}var Mu=Math.LN2/604800;function Kr(r,e,t,n=0){if(!Number.isFinite(r))return n;if(!Number.isFinite(e)||e<=0||!Number.isFinite(t)||t<=0)return Math.max(n,r);let s=r*Math.exp(-t*e);return Math.max(n,s)}Re();Ie();_t();De();ye();ne();var qn=class{_version=0;_buf;constructor(e){this._buf=e?[...e]:[]}get version(){return this._version}get size(){return this._buf.length}at(e){if(!Number.isInteger(e))return;let t=e>=0?e:this._buf.length+e;if(!(t<0||t>=this._buf.length))return this._buf[t]}append(e){this._buf.push(e),this._version+=1}appendMany(e){if(e.length===0)return;let t=this._buf.length;this._buf.length=t+e.length;for(let n=0;n<e.length;n++)this._buf[t+n]=e[n];this._version+=1}insert(e,t){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insert: index ${e} out of range [0, ${this._buf.length}]`);this._buf.splice(e,0,t),this._version+=1}insertMany(e,t){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insertMany: index ${e} out of range [0, ${this._buf.length}]`);t.length!==0&&(this._buf.splice(e,0,...t),this._version+=1)}pop(e){if(this._buf.length===0)throw new RangeError("pop from empty list");if(!Number.isInteger(e))throw new RangeError(`pop: index ${e} must be an integer`);let t=e>=0?e:this._buf.length+e;if(t<0||t>=this._buf.length)throw new RangeError(`pop: index ${e} out of range`);let[n]=this._buf.splice(t,1);return this._version+=1,n}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._version+=1,e)}toArray(){return[...this._buf]}};function Wr(r,e={}){let{name:t,versioning:n,backend:s}=e,o=s??new qn(r),i=V(o.toArray(),{name:t,describeKind:"state",equals:(u,c)=>u===c,...n!=null?{versioning:n}:{}});function a(){let u=o.toArray();U(()=>{i.down([[X]]),i.down([[D,u]])})}function d(u){let c=o.version;try{return u()}finally{o.version!==c&&a()}}return{items:i,get size(){return o.size},at(u){return o.at(u)},append(u){d(()=>o.append(u))},appendMany(u){d(()=>o.appendMany(u))},insert(u,c){d(()=>o.insert(u,c))},insertMany(u,c){d(()=>o.insertMany(u,c))},pop(u=-1){return d(()=>o.pop(u))},clear(){d(()=>o.clear())},dispose(){}}}Pe();In();var Es=256,ks=1024;function Un(r,e){if(!Number.isFinite(r)||!Number.isInteger(r)||r<0)throw new Error(`${e} must be a non-negative integer`);return r}function Zt(r,e){return He("job_queue",r,e)}var Kn=class extends le{_pending;_jobs;_seqCursor;pending;jobs;depth;events;audit;_enqueueImpl;_ackImpl;_nackImpl;_removeByIdImpl;constructor(e,t={}){super(e,t.graph),this._pending=Wr([],{name:"pending"}),this._jobs=ct({name:"jobs"}),this.pending=this._pending.items,this.jobs=this._jobs.entries,this.add(this.pending,{name:"pending"}),this.add(this.jobs,{name:"jobs"}),this.depth=G([this.pending],([n])=>n.length,{name:"depth",describeKind:"derived",meta:Zt("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(ce(this.depth)),this.events=Wt({name:"events",retainedLimit:1024,graph:this}),this.audit=this.events,this._seqCursor=zr(this,"seq",0),this._enqueueImpl=Le((n,s)=>{let o=this._seqCursor.cache,i=s.id??`${this.name}-${o}`;if(this._jobs.get(i)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${i}"`);let a={id:i,payload:n,attempts:0,metadata:Object.freeze({...s.metadata??{}}),state:"queued"};return this._jobs.set(i,a),this._pending.append(i),i},{audit:this.events,seq:this._seqCursor,freeze:!1,onSuccess:([n],s,{t_ns:o,seq:i})=>({action:"enqueue",id:s,payload:n,t_ns:o,seq:i??0})}),this._ackImpl=Le((n,s)=>{this._jobs.delete(n)},{audit:this.events,seq:this._seqCursor,freeze:!1,onSuccess:([n,s],o,{t_ns:i,seq:a})=>({action:"ack",id:n,attempts:s.attempts,t_ns:i,seq:a??0})}),this._nackImpl=Le((n,s,o)=>{o?(this._jobs.set(n,{...s,state:"queued"}),this._pending.append(n)):this._jobs.delete(n)},{audit:this.events,seq:this._seqCursor,freeze:!1,onSuccess:([n,s],o,{t_ns:i,seq:a})=>({action:"nack",id:n,attempts:s.attempts,t_ns:i,seq:a??0})}),this._removeByIdImpl=Le((n,s)=>{if(s.state==="queued"){let i=this.pending.cache.indexOf(n);i>=0&&this._pending.pop(i)}this._jobs.delete(n)},{audit:this.events,seq:this._seqCursor,freeze:!1,onSuccess:([n,s],o,{t_ns:i,seq:a})=>({action:"remove",id:n,attempts:s.attempts,t_ns:i,seq:a??0})})}attachEventStorage(e){return this.events.attachStorage(e)}enqueue(e,t={}){return this._enqueueImpl(e,t)}claim(e=1){let t=Un(e,"job queue claim limit");if(t===0)return[];let n=[];for(;n.length<t&&this.pending.cache.length!==0;){let o=this._pending.pop(0),i=this._jobs.get(o);if(!i||i.state!=="queued")continue;let a={...i,state:"inflight",attempts:i.attempts+1};this._jobs.set(o,a),n.push(a),this.events.append({action:"claim",id:o,attempts:a.attempts,t_ns:Me(),seq:Jt(this._seqCursor)})}return n}ack(e){let t=this._jobs.get(e);return!t||t.state!=="inflight"?!1:(this._ackImpl(e,t),!0)}nack(e,t={}){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:(this._nackImpl(e,n,t.requeue??!0),!0)}removeById(e){let t=this._jobs.get(e);return t?(this._removeByIdImpl(e,t),!0):!1}consumeFrom(e,t){return e.subscribe(n=>{for(let s of n){if(s[0]!==D)continue;let o=s[1];this.enqueue(o,t?{metadata:t.metadata}:void 0)}})}},Wn=class extends le{_stageNames;_stageWorkFns;_queues=new Map;_completed;completed;completedCount;constructor(e,t={}){super(e,t.graph);let n=t.stages??["incoming","processing","done"],s=[],o=new Map,i=new Map;for(let u of n){let c=typeof u=="string"?u.trim():u.name.trim();typeof u!="string"&&u.work&&o.set(c,u.work),typeof u!="string"&&u.maxPerPump!=null&&i.set(c,Math.max(1,Un(u.maxPerPump,`job flow stage "${c}" maxPerPump`))),s.push(c)}if(s.length<2)throw new Error(`jobFlow("${e}"): requires at least 2 stages`);if(new Set(s).size!==s.length)throw new Error(`jobFlow("${e}"): stage names must be unique`);this._stageNames=Object.freeze([...s]),this._stageWorkFns=o;for(let u of this._stageNames){let c=Jn(`${e}-${u}`);this._queues.set(u,c),this.mount(u,c)}this._completed=lt([],{name:"completed",maxSize:ks}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=G([this.completed],([u])=>u.length,{name:"completedCount",describeKind:"derived",meta:Zt("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(ce(this.completedCount));let d=Math.max(1,Un(t.maxPerPump??Es,"job flow maxPerPump"));for(let u=0;u<this._stageNames.length;u+=1){let c=this._stageNames[u],p=this.queue(c),l=u+1<this._stageNames.length?this.queue(this._stageNames[u+1]):null,h=this._stageWorkFns.get(c),f=i.get(c)??d,b=l===null;if(h){let m=te([p.pending],()=>{let T=0;for(;T<f;){let v=p.claim(1);if(v.length===0)break;let g=v[0];if(!g)break;let w=[...g.metadata.job_flow_path??[],c],N;try{N=h(g)}catch{p.nack(g.id,{requeue:!1}),T+=1;continue}let y=Ae(N),x=!1,k;k=y.subscribe(A=>{if(!x){for(let E of A)if(E[0]===D){x=!0,k?k():Promise.resolve().then(()=>k?.());let P=E[1],H={...g.metadata,job_flow_path:w};if(b){let F={...g,payload:P,metadata:Object.freeze(H)};U(()=>{p.ack(g.id),this._completed.append(F)})}else U(()=>{p.ack(g.id),l.enqueue(P,{metadata:H})});return}else if(E[0]===I){x=!0,k?k():Promise.resolve().then(()=>k?.()),p.nack(g.id,{requeue:!1});return}}}),T+=1}},{name:`pump_${c}`,describeKind:"effect",meta:Zt("job_flow_pump",{stage:c,has_work:!0})});this.add(m,{name:`pump_${c}`}),this.addDisposer(ce(m))}else{let m=te([p.pending],()=>{let T=0;for(;T<f;){let v=p.claim(1);if(v.length===0)break;let g=v[0];if(!g)break;let w=[...g.metadata.job_flow_path??[],c],N={...g.metadata,job_flow_path:w};if(b){let y={...g,metadata:Object.freeze(N)};U(()=>{p.ack(g.id),this._completed.append(y)})}else U(()=>{p.ack(g.id),l.enqueue(g.payload,{metadata:N})});T+=1}},{name:`pump_${c}`,describeKind:"effect",meta:Zt("job_flow_pump",{stage:c,has_work:!1})});this.add(m,{name:`pump_${c}`}),this.addDisposer(ce(m))}}}stages(){return this._stageNames}queue(e){let t=this._queues.get(e);if(!t)throw new Error(`jobFlow("${this.name}"): unknown stage "${e}"`);return t}enqueue(e,t={}){return this.queue(this._stageNames[0]).enqueue(e,t)}retainedCompleted(){return this.completed.cache}};function Jn(r,e){return new Kn(r,e)}function Jr(r,e){let t=new Wn(r,e),{factory:n,factoryArgs:s,...o}=e??{};return t.tagFactory("jobFlow",We(o)),t}Re();ne();function Yn(){let r=ct({name:"strategy-entries"}),e=G([r.entries],([i])=>{let a=i;return new Map(a)},{name:"strategy-model",equals:(i,a)=>{let d=i,u=a;if(d.size!==u.size)return!1;for(let[c,p]of d){let l=u.get(c);if(!l||p.attempts!==l.attempts||p.successes!==l.successes)return!1}return!0}});function t(i,a,d){let u=dt(i,a),c=r.get(u),p=(c?.attempts??0)+1,l=(c?.successes??0)+(d?1:0);r.set(u,{rootCause:i,intervention:a,attempts:p,successes:l,successRate:l/p})}function n(i,a){return r.get(dt(i,a))}let s=e.subscribe(()=>{});function o(){s()}return{node:e,record:t,lookup:n,dispose:o}}function Rs(r,e,t,n,s){let o={...at,...s?.severityWeights},i=s?.decayRate??ut,a=s?.effectivenessThreshold??.7,d=s?.effectivenessBoost??15,u=[r,e,t];return n&&u.push(n),G(u,c=>{let p=c[0],l=c[1],h=c[2],f=n?c[3]:0,b=o[p.severity??"medium"],m=(K()-h)/1e9,T=Kr(b,m,i,0),v=dt(p.rootCause,p.intervention),g=l.get(v);return g&&g.successRate>=a&&(T+=d),T+=f*20,T},{name:"priority-score"})}var Yr="intake",Os="triage-output",Qr="retry",Xr="verify-results",Zr="__unrouted";function eo(r,e){let t=yt(e,wn,(n,s)=>n.replace("{{item}}",JSON.stringify(s)));return n=>{let s=n.payload.item,o=[{role:"user",content:t(s)}],i=d=>({...n.payload,execution:{item:s,outcome:"failure",detail:d}}),a=d=>d instanceof Error?d.message:String(d);return Hn(r,o,{onSuccess:d=>{let u;try{u=JSON.parse(Et(String(d.content)))}catch(p){return i(`execute parse error: ${a(p)}`)}if(u==null||typeof u!="object"||Array.isArray(u))return i(`execute parse error: non-object response: ${JSON.stringify(u)}`);let c=u;return{...n.payload,execution:{item:s,outcome:c.outcome??"failure",detail:c.detail??"unknown",artifact:c.artifact}}},onFailure:(d,u)=>i(d==="complete"?"adapter completed without emitting DATA":`executor failed: ${a(u)}`)})}}function to(r,e){let t=yt(e,xn,(n,s)=>{let[o,i]=s;return n.replace("{{execution}}",JSON.stringify(o)).replace("{{item}}",JSON.stringify(i))});return n=>{let{item:s,execution:o}=n.payload;if(o==null)return{...n.payload,verify:{verified:!1,findings:["verifier: prior execute stage produced no execution"],errorClass:"structural"}};let i=[{role:"user",content:t([o,s])}],a=u=>({...n.payload,verify:{verified:!1,findings:[u],errorClass:"self-correctable"}}),d=u=>u instanceof Error?u.message:String(u);return Hn(r,i,{onSuccess:u=>{let c;try{c=JSON.parse(Et(String(u.content)))}catch(l){return a(`verify parse error: ${d(l)}`)}if(c==null||typeof c!="object"||Array.isArray(c))return a(`verify parse error: non-object response: ${JSON.stringify(c)}`);let p=c;return{...n.payload,verify:{verified:p.verified===!0,findings:p.findings??[],errorClass:p.errorClass}}},onFailure:(u,c)=>a(u==="complete"?"verifier completed without emitting DATA":`verifier failed: ${d(c)}`)})}}var en=class extends le{queues;executeFlow;jobs;gates;queueTopics;strategy;totalRetries;totalReingestions;priorityScores;reflect;constructor(e,t,n,s,o,i,a,d,u,c,p){super(e),this.queues=t,this.executeFlow=n,this.queueTopics=s,this.jobs=o,this.gates=i,this.strategy=a,this.totalRetries=d,this.totalReingestions=u,this.reflect=c,this.priorityScores=p}get intake(){return this.queues.topic(Yr)}get verifyResults(){return this.queues.topic(Xr)}get retry(){return this.queues.topic(Qr)}get unrouted(){return this.queues.topic(Zr)}stageNodes(){let e=this.queues,t=i=>e.has(i)?`queues::${i}::latest`:null,n=i=>i==null?[]:[i],s=xe.flatMap(i=>n(t(i))),o=[];for(let[i]of this.gates)o.push(`gates::${i}/gate`);return[{label:"INTAKE",paths:n(t("intake"))},{label:"TRIAGE",paths:["triage"]},{label:"QUEUE",paths:s},{label:"GATE",paths:o},{label:"EXECUTE",paths:["executeFlow::execute::events"]},{label:"VERIFY",paths:["executeFlow::verify::events"]},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function As(r,e){let t=e.adapter,n=e.maxRetries??2,s=e.retainedLimit??1e3,o=e.errorClassifier??Vt,i=new Map;for(let O of xe)i.set(O,{...$t[O],...e.queues?.[O]});let a=Qt(`${r}/queues`,{defaultTopicOptions:{retainedLimit:s}}),d=a.topic(Yr),u=a.topic(Os),c=a.topic(Qr),p=a.topic(Xr),l=new Map;for(let O of xe)l.set(O,a.topic(O));let h=a.topic(Zr),f=Yn(),b=Tn(d.latest,f.node),m=yt(e.triagePrompt,_n,(O,S)=>{let[Q,oe]=S;return O.replace("{{strategy}}",JSON.stringify(Array.from(oe.entries()))).replace("{{item}}",JSON.stringify(Q))}),T=Ur(t,[b],O=>{let S=O;return!S||!S[0]?"":m(S)},{name:"triage",format:"json"}),v=Tn(T,b),_=me([v],([O])=>{if(O==null)return;let[S,Q]=O;if(!S?.route)return;let oe=Q?.[0],Fe={...S,...oe};u.publish(Fe)}).subscribe(()=>{}),w=new Set(xe);for(let O of xe)$n(`bridge/${O}`,u,l.get(O),{map:S=>S.route===O?S:void 0});$n("bridge/__unrouted",u,h,{map:O=>w.has(O.route)?void 0:O});let N=new Map,y=new Map;for(let O of xe)N.set(O,Jn(`jobs/${O}`));let x=[];for(let O of xe){let S=l.get(O),Q=N.get(O),oe=new WeakSet,Fe=me([S.events],([pe])=>{let $e=pe??[];for(let se of $e){if(oe.has(se))continue;oe.add(se);let _e=Q.enqueue(se);y.set(xt(se),{route:O,id:_e})}},{name:`jobs/${O}-mirror`});x.push(Fe.subscribe(()=>{}))}function k(O){let S=xt(O),Q=y.get(S);Q&&(N.get(Q.route)?.removeById(Q.id),y.delete(S))}let A=Bn("gates"),E=new Map;for(let O of xe){let S=i.get(O);if(!S.gated)continue;let Q=l.get(O),oe=A.approvalGate(`${O}/gate`,Q.latest,{maxPending:S.maxPending,startOpen:S.startOpen});E.set(O,oe)}let P=[];for(let O of xe)i.get(O).gated&&E.has(O)?P.push(E.get(O).node):P.push(l.get(O).latest);P.push(c.latest);let H=Tr(...P),F=e.executor??eo(t,e.executePrompt),ve=e.verifier??to(t,e.verifyPrompt),Te=e.executeMaxPerPump??Number.MAX_SAFE_INTEGER,Ee=e.verifyMaxPerPump??Number.MAX_SAFE_INTEGER,Ne=Jr(`${r}/executeFlow`,{stages:[{name:"execute",work:O=>F(O),maxPerPump:Te},{name:"verify",work:O=>ve(O),maxPerPump:Ee}]}),j=me([H],([O])=>{O!=null&&Ne.enqueue({item:O})},{name:"execute-enqueue"}),z=j.subscribe(()=>{}),L=e.maxReingestions??1,ue=Math.min(e.maxTotalRetries??n*10,100),Z=Math.min(e.maxTotalReingestions??L*10,100),ge=V(0),C=V(0);function q(O,S,Q){return{item:Q,execution:O,verified:S.verified,findings:S.findings??[],errorClass:S.errorClass}}function be(O,S){f.record(S.rootCause,S.intervention,!0),p.publish(O),k(S)}function Ge(O,S){let Q=xt(S),oe=S.$retries??0,Fe={...S,$retries:oe+1,summary:`[RETRY ${oe+1}/${n}] ${Q} \u2014 Previous attempt failed: ${O.findings.join("; ")}`,relatedTo:[Q]};c.publish(Fe)}function we(O,S){f.record(S.rootCause,S.intervention,!1),p.publish(O),k(S);let Q=xt(S),oe=S.$reingestions??0;oe<L&&Dn(C,Z)&&d.publish({source:S.source,summary:`Verification failed for: ${Q}`,evidence:O.findings.join(`
48
+ `),affectsAreas:S.affectsAreas,affectsEvalTasks:S.affectsEvalTasks,severity:S.severity??"high",relatedTo:[Q],$reingestions:oe+1})}let R=0,M=me([Ne.completed],([O])=>{let S=O??[];R>S.length&&(R=S.length);let Q=R;R=S.length;for(let oe=Q;oe<S.length;oe++){let Fe=S[oe],{item:pe,execution:$e,verify:se}=Fe.payload;if($e==null||se==null){k(pe);continue}let _e=q($e,se,pe);if(_e.verified){be(_e,pe);continue}let tn=_e.errorClass??o({item:pe,outcome:$e.outcome,detail:_e.findings.join("; ")}),nn=pe.$retries??0;tn==="self-correctable"&&nn<n&&Dn(ge,ue)?Ge(_e,pe):we(_e,pe)}},{name:"verify-dispatch"}),ee=M.subscribe(()=>{}),re=G([Ne.completed],()=>null,{name:"reflect",equals:()=>!1}),fe;e.priority&&(fe=Ss(l,f,e));let B=new en(r,a,Ne,l,N,E,f,ge,C,re,fe);B.addDisposer(_),B.addDisposer(z),B.addDisposer(ee),B.addDisposer(f.dispose);for(let O of x)B.addDisposer(O);if(B.add(b,{name:"triage-input"}),B.add(T,{name:"triage"}),B.add(v,{name:"router-input"}),B.add(H,{name:"execute-input"}),B.add(j,{name:"execute-enqueue"}),B.add(M,{name:"verify-dispatch"}),B.add(re,{name:"reflect"}),B.add(f.node,{name:"strategy"}),B.addDisposer(re.subscribe(()=>{})),fe)for(let[O,S]of fe)B.add(S,{name:`priority/${O}`}),B.addDisposer(S.subscribe(()=>{}));B.mount("queues",a),B.mount("gates",A),B.mount("executeFlow",Ne);for(let[O,S]of N)B.mount(`jobs/${O}`,S);return B.tagFactory("harnessLoop",We(e)),B}function Ss(r,e,t){if(!t.lastInteractionNs)throw new Error("harnessLoop: `opts.priority` requires `opts.lastInteractionNs` \u2014 pass a Node<number> (e.g. `fromTimer(60_000)` or a `state(monotonicNs())` you bump on human interaction). Priority scores only decay when this node settles; an internal default would freeze age at construction time.");let n=t.lastInteractionNs,s=t.priority??{},o={...at,...s.severityWeights},i=s.decayRate??ut,a=s.effectivenessThreshold??.7,d=s.effectivenessBoost??15,u=new Map;for(let[c,p]of r){let l=G([p.latest,e.node,n],h=>{let f=h[0];if(f==null)return 0;let b=o[f.severity??"medium"]??40,m=(K()-h[2])/1e9,T=b*Math.exp(-i*Math.max(0,m)),v=`${f.rootCause}\u2192${f.intervention}`,_=h[1]?.get(v);return _&&_.successRate>=a&&(T+=d),T},{name:`priority/${c}`});u.set(c,l)}return u}Rn();function Cs(r,e){let t=qt(r,e),n={};for(let s of xe){let o=r.queues.has(s)?r.queues.topic(s):null;n[s]=o?.retained().length??0}return{...t,queueDepths:n,strategyEntries:r.strategy.node.cache?.size??0,totalRetries:r.totalRetries.cache??0,totalReingestions:r.totalReingestions.cache??0}}Re();function Ds(r){let e={};for(let{label:t,paths:n}of r.stageNodes())for(let s of n)e[s]=t;return e}function Ms(r,e){let t=e?.logger===null?null:e?.logger??console.log,n=e?.detail??"summary",s=K(),o=[],i=[],a=Ds(r);function d(){return(K()-s)/1e9}function u(c,p,l){let h={elapsed:d(),stage:c,type:p};n!=="summary"&&(h.summary=Is(l)),n==="full"&&(h.data=l),i.push(h)}for(let[c,p]of Object.entries(a))try{let l=r.observe(c,{format:"stage-log",stageLabels:a,logger:t?h=>t(h):()=>{},includeTypes:["data","error","complete"]});l.onEvent(h=>{h.type==="data"?u(p,"data",h.data):h.type==="error"?u(p,"error",h.data):h.type==="complete"&&u(p,"complete",void 0)}),o.push(l)}catch(l){let h=l instanceof Error?l.message:String(l);u(p,"error",`observe-unavailable: ${c} \u2014 ${h}`),t&&t(`[${d().toFixed(3)}s] ${p.padEnd(9)} \u2717 observe-unavailable: ${h}`)}return{get events(){return i},dispose(){for(let c of o)c.dispose();o.length=0}}}function Is(r){if(r==null)return"null";if(typeof r=="string")return no(r,80);if(typeof r=="number"||typeof r=="boolean"||typeof r=="bigint")return String(r);try{let e=JSON.stringify(r);return no(e,120)}catch{return String(r)}}function no(r,e){return r.length>e?`${r.slice(0,e-1)}\u2026`:r}0&&(module.exports={DEFAULT_DECAY_RATE,DEFAULT_EXECUTE_PROMPT,DEFAULT_QUEUE_CONFIGS,DEFAULT_SEVERITY_WEIGHTS,DEFAULT_TRIAGE_PROMPT,DEFAULT_VERIFY_PROMPT,HarnessGraph,QUEUE_NAMES,actuatorExecutor,affectedTaskFilter,autoSolidify,beforeAfterCompare,blindVariation,codeChangeBridge,createIntakeBridge,defaultErrorClassifier,defaultLlmExecutor,defaultLlmVerifier,dispatchActuator,effectivenessTracker,errorCritique,evalIntakeBridge,evalSource,evalVerifier,harnessEvalPair,harnessLoop,harnessProfile,harnessTrace,notifyEffect,priorityScore,refineExecutor,refineLoop,resolvePromptFn,strategyKey,strategyModel});