@graphrefly/graphrefly 0.35.0 → 0.37.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 (193) hide show
  1. package/dist/{chunk-EUE7ELFQ.js → chunk-2C4NESZE.js} +1 -1
  2. package/dist/{chunk-PIIUJIF7.js → chunk-4EATTNAE.js} +1 -1
  3. package/dist/chunk-B4L5X2QO.js +7 -0
  4. package/dist/{chunk-YV2A2VWG.js → chunk-C5CBVOCB.js} +1 -1
  5. package/dist/{chunk-J6TGRQUP.js → chunk-CZIQ6JCE.js} +1 -1
  6. package/dist/chunk-FJ6IEMOS.js +1 -0
  7. package/dist/{chunk-T7GWBGOO.js → chunk-FMI4CWFL.js} +1 -1
  8. package/dist/{chunk-RRFOCAH6.js → chunk-G6Q3DUMJ.js} +1 -1
  9. package/dist/{chunk-CD4CB6S7.js → chunk-GDDPCDLG.js} +1 -1
  10. package/dist/{chunk-3OT7K33Q.js → chunk-GFOT6UBB.js} +1 -1
  11. package/dist/{chunk-53XJ2S6D.js → chunk-K2WYIVHM.js} +1 -1
  12. package/dist/{chunk-5XZRCS2M.js → chunk-K6ZFJ473.js} +1 -1
  13. package/dist/{chunk-E5YSBQSF.js → chunk-KTWBUJO5.js} +1 -1
  14. package/dist/{chunk-RLMYS3XZ.js → chunk-KUVDFOJH.js} +1 -1
  15. package/dist/{chunk-XMDNNSMK.js → chunk-LOQRPP4Y.js} +1 -1
  16. package/dist/{chunk-2Y3DKIZL.js → chunk-MC5LZG3U.js} +1 -1
  17. package/dist/{chunk-M5UC63ZI.js → chunk-NKKUUKPD.js} +1 -1
  18. package/dist/{chunk-GWOKTENT.js → chunk-QKBCTKH7.js} +1 -1
  19. package/dist/{chunk-YOUAVGHJ.js → chunk-QP5TH523.js} +1 -1
  20. package/dist/{chunk-T6RPUERH.js → chunk-QWVQIL3T.js} +1 -1
  21. package/dist/{chunk-6G5YD37E.js → chunk-T4U24DXX.js} +1 -1
  22. package/dist/{chunk-W2ZU226Q.js → chunk-TFK4P4CX.js} +1 -1
  23. package/dist/{chunk-PVUTRA5K.js → chunk-TLS7M7H4.js} +1 -1
  24. package/dist/{chunk-BGEY3PXH.js → chunk-U3COB5WU.js} +1 -1
  25. package/dist/{chunk-UAMWD4GG.js → chunk-UODQF4EY.js} +1 -1
  26. package/dist/{chunk-U347KVM4.js → chunk-WGST56ZH.js} +1 -1
  27. package/dist/{chunk-XINLP35X.js → chunk-WSLN4JFO.js} +1 -1
  28. package/dist/{chunk-ZGVA2SR5.js → chunk-XIJKEXWR.js} +1 -1
  29. package/dist/{chunk-JUJEPZOI.js → chunk-YVYSO5CW.js} +1 -1
  30. package/dist/compat/index.cjs +9 -9
  31. package/dist/compat/index.d.cts +6 -6
  32. package/dist/compat/index.d.ts +6 -6
  33. package/dist/compat/index.js +1 -1
  34. package/dist/compat/nestjs/index.cjs +11 -11
  35. package/dist/compat/nestjs/index.d.cts +4 -4
  36. package/dist/compat/nestjs/index.d.ts +4 -4
  37. package/dist/compat/nestjs/index.js +1 -1
  38. package/dist/compat/zustand/index.cjs +7 -7
  39. package/dist/compat/zustand/index.d.cts +2 -2
  40. package/dist/compat/zustand/index.d.ts +2 -2
  41. package/dist/compat/zustand/index.js +1 -1
  42. package/dist/extra/index.cjs +17 -17
  43. package/dist/extra/index.d.cts +3 -3
  44. package/dist/extra/index.d.ts +3 -3
  45. package/dist/extra/index.js +1 -1
  46. package/dist/extra/reactive.cjs +1 -1
  47. package/dist/extra/reactive.d.cts +1 -1
  48. package/dist/extra/reactive.d.ts +1 -1
  49. package/dist/extra/reactive.js +1 -1
  50. package/dist/graph/index.cjs +7 -7
  51. package/dist/graph/index.d.cts +3 -3
  52. package/dist/graph/index.d.ts +3 -3
  53. package/dist/graph/index.js +1 -1
  54. package/dist/{graph-kTltt95s.d.cts → graph-CaNXUc3c.d.cts} +26 -1
  55. package/dist/{graph-Cv-8x0ZI.d.ts → graph-YQXDndFy.d.ts} +26 -1
  56. package/dist/{index-KNAMYngu.d.ts → index-0qOD-421.d.ts} +2 -2
  57. package/dist/{index-CfOSES72.d.cts → index-4IwO4mH2.d.cts} +5 -5
  58. package/dist/{index-CAIhFfws.d.ts → index-9mbs_PIG.d.ts} +2 -2
  59. package/dist/{index-Bilohojo.d.ts → index-Ae6L8liv.d.ts} +2 -2
  60. package/dist/{index-BhkPzu-Z.d.cts → index-B1IcU--K.d.cts} +2 -2
  61. package/dist/{index-DzgS5uYi.d.ts → index-B46GWgk3.d.ts} +1 -1
  62. package/dist/{index-BpFwRAf9.d.cts → index-B9qJmmv3.d.cts} +1 -1
  63. package/dist/{index-CI_yjtua.d.ts → index-BCq12BqB.d.ts} +1 -1
  64. package/dist/{index-zK_mN1D-.d.cts → index-BECJ8M0T.d.cts} +2 -2
  65. package/dist/{index-DFe2Pk2u.d.ts → index-BOfHwQc1.d.ts} +1 -1
  66. package/dist/{index-hXKhbfh-.d.ts → index-BhLA9feT.d.ts} +12 -7
  67. package/dist/{index-Dp69u0ym.d.ts → index-BmLkcDlj.d.ts} +6 -6
  68. package/dist/{index-XxSeddWP.d.cts → index-BokynmA4.d.cts} +1 -1
  69. package/dist/{index-BEvsFlfH.d.ts → index-Bpzw8hx3.d.ts} +2 -2
  70. package/dist/{index-PluovH45.d.cts → index-BwtIbzSV.d.cts} +2 -2
  71. package/dist/{index-BZ1V5GzX.d.ts → index-C-pFD_FV.d.ts} +2 -2
  72. package/dist/{index-Cot94_82.d.ts → index-C0tga1_x.d.ts} +2 -2
  73. package/dist/{index-BlRVj-7Q.d.cts → index-C4N-dg5U.d.cts} +2 -2
  74. package/dist/{index-B4s70vYf.d.ts → index-CKcnuQ2c.d.ts} +2 -2
  75. package/dist/{index-D7r_vd0b.d.cts → index-CLPQyYY5.d.cts} +3 -3
  76. package/dist/{index-BuMzxRO2.d.ts → index-CRycrNfn.d.ts} +1 -1
  77. package/dist/{index-DeyzuqAi.d.cts → index-CU3z8Cel.d.cts} +2 -2
  78. package/dist/{index-DwNNufVa.d.ts → index-CUTHDZ7Q.d.ts} +3 -3
  79. package/dist/{index-CGKs5ixV.d.cts → index-C_qi0WlF.d.cts} +12 -7
  80. package/dist/{index-BBdwz2BW.d.ts → index-CajEOoAN.d.ts} +2 -2
  81. package/dist/{index-CzC0G0C3.d.cts → index-Ci358GSC.d.cts} +2 -2
  82. package/dist/{index-BkbawFkI.d.cts → index-CkN8CZlT.d.cts} +6 -6
  83. package/dist/{index-ZhKyR8co.d.cts → index-CrpjECS6.d.cts} +2 -2
  84. package/dist/{index-C40wA8zt.d.ts → index-CzIWlnPp.d.ts} +5 -5
  85. package/dist/{index-C9xF16gc.d.ts → index-D0ZxFXYl.d.ts} +2 -2
  86. package/dist/{index-BtY2QVDf.d.cts → index-D11pGlaI.d.cts} +2 -2
  87. package/dist/{index-DlccEIi3.d.ts → index-D1E1tqHT.d.ts} +1 -1
  88. package/dist/{index-Qq-G9B6g.d.cts → index-D6pwWiOc.d.cts} +2 -2
  89. package/dist/{index-BsZlbHM5.d.cts → index-D6tRNEKz.d.cts} +1 -1
  90. package/dist/{index-B3Dfl5sS.d.cts → index-DAKm44My.d.cts} +2 -2
  91. package/dist/{index-BWH17rK_.d.cts → index-DCAuN9u5.d.cts} +1 -1
  92. package/dist/{index-BF-ssbJB.d.ts → index-DPqR3wdW.d.ts} +2 -2
  93. package/dist/{index-GaW6Welt.d.cts → index-DTYIRT_v.d.cts} +2 -2
  94. package/dist/{index-DXSLMoma.d.ts → index-DXz9uwcs.d.ts} +1 -1
  95. package/dist/{index-DmtWMP0X.d.cts → index-D_DThl_J.d.cts} +1 -1
  96. package/dist/{index-BwYGLgmI.d.ts → index-D_d1erkR.d.ts} +2 -2
  97. package/dist/{index-D9qoEOj_.d.cts → index-DbWwMWiB.d.cts} +1 -1
  98. package/dist/{index-D6JRP-1_.d.cts → index-DcWbx58m.d.cts} +2 -2
  99. package/dist/{index-DzYTXMBz.d.ts → index-DfAo9WKr.d.ts} +1 -1
  100. package/dist/{index-DXZsXxtU.d.cts → index-DqtXA3yX.d.cts} +2 -2
  101. package/dist/{index-DBmBtqAN.d.ts → index-DuhOdNyg.d.ts} +2 -2
  102. package/dist/{index-DKp1CIbG.d.cts → index-e1m3ZHgc.d.cts} +1 -1
  103. package/dist/{index-DSD6xnbT.d.ts → index-fHKHdAso.d.ts} +2 -2
  104. package/dist/index.cjs +41 -41
  105. package/dist/index.d.cts +29 -29
  106. package/dist/index.d.ts +29 -29
  107. package/dist/index.js +1 -1
  108. package/dist/patterns/ai/index.cjs +19 -19
  109. package/dist/patterns/ai/index.d.cts +7 -7
  110. package/dist/patterns/ai/index.d.ts +7 -7
  111. package/dist/patterns/ai/index.js +1 -1
  112. package/dist/patterns/audit/index.cjs +7 -7
  113. package/dist/patterns/audit/index.d.cts +4 -4
  114. package/dist/patterns/audit/index.d.ts +4 -4
  115. package/dist/patterns/audit/index.js +1 -1
  116. package/dist/patterns/cqrs/index.cjs +7 -7
  117. package/dist/patterns/cqrs/index.d.cts +3 -3
  118. package/dist/patterns/cqrs/index.d.ts +3 -3
  119. package/dist/patterns/cqrs/index.js +1 -1
  120. package/dist/patterns/demo-shell/index.cjs +8 -8
  121. package/dist/patterns/demo-shell/index.d.cts +3 -3
  122. package/dist/patterns/demo-shell/index.d.ts +3 -3
  123. package/dist/patterns/demo-shell/index.js +1 -1
  124. package/dist/patterns/domain-templates/index.cjs +7 -7
  125. package/dist/patterns/domain-templates/index.d.cts +2 -2
  126. package/dist/patterns/domain-templates/index.d.ts +2 -2
  127. package/dist/patterns/domain-templates/index.js +1 -1
  128. package/dist/patterns/graphspec/index.cjs +17 -17
  129. package/dist/patterns/graphspec/index.d.cts +2 -2
  130. package/dist/patterns/graphspec/index.d.ts +2 -2
  131. package/dist/patterns/graphspec/index.js +1 -1
  132. package/dist/patterns/guarded-execution/index.cjs +7 -7
  133. package/dist/patterns/guarded-execution/index.d.cts +5 -5
  134. package/dist/patterns/guarded-execution/index.d.ts +5 -5
  135. package/dist/patterns/guarded-execution/index.js +1 -1
  136. package/dist/patterns/harness/index.cjs +10 -10
  137. package/dist/patterns/harness/index.d.cts +7 -7
  138. package/dist/patterns/harness/index.d.ts +7 -7
  139. package/dist/patterns/harness/index.js +1 -1
  140. package/dist/patterns/job-queue/index.cjs +7 -7
  141. package/dist/patterns/job-queue/index.d.cts +3 -3
  142. package/dist/patterns/job-queue/index.d.ts +3 -3
  143. package/dist/patterns/job-queue/index.js +1 -1
  144. package/dist/patterns/lens/index.cjs +7 -7
  145. package/dist/patterns/lens/index.d.cts +3 -3
  146. package/dist/patterns/lens/index.d.ts +3 -3
  147. package/dist/patterns/lens/index.js +1 -1
  148. package/dist/patterns/memory/index.cjs +7 -7
  149. package/dist/patterns/memory/index.d.cts +2 -2
  150. package/dist/patterns/memory/index.d.ts +2 -2
  151. package/dist/patterns/memory/index.js +1 -1
  152. package/dist/patterns/messaging/index.cjs +7 -7
  153. package/dist/patterns/messaging/index.d.cts +3 -3
  154. package/dist/patterns/messaging/index.d.ts +3 -3
  155. package/dist/patterns/messaging/index.js +1 -1
  156. package/dist/patterns/orchestration/index.cjs +7 -7
  157. package/dist/patterns/orchestration/index.d.cts +3 -3
  158. package/dist/patterns/orchestration/index.d.ts +3 -3
  159. package/dist/patterns/orchestration/index.js +1 -1
  160. package/dist/patterns/process/index.cjs +1 -1
  161. package/dist/patterns/process/index.d.cts +4 -4
  162. package/dist/patterns/process/index.d.ts +4 -4
  163. package/dist/patterns/process/index.js +1 -1
  164. package/dist/patterns/reactive-layout/index.cjs +8 -8
  165. package/dist/patterns/reactive-layout/index.d.cts +3 -3
  166. package/dist/patterns/reactive-layout/index.d.ts +3 -3
  167. package/dist/patterns/reactive-layout/index.js +1 -1
  168. package/dist/patterns/reduction/index.cjs +7 -7
  169. package/dist/patterns/reduction/index.d.cts +2 -2
  170. package/dist/patterns/reduction/index.d.ts +2 -2
  171. package/dist/patterns/reduction/index.js +1 -1
  172. package/dist/patterns/refine-loop/index.cjs +8 -8
  173. package/dist/patterns/refine-loop/index.d.cts +4 -4
  174. package/dist/patterns/refine-loop/index.d.ts +4 -4
  175. package/dist/patterns/refine-loop/index.js +1 -1
  176. package/dist/patterns/resilient-pipeline/index.d.cts +3 -3
  177. package/dist/patterns/resilient-pipeline/index.d.ts +3 -3
  178. package/dist/patterns/resilient-pipeline/index.js +1 -1
  179. package/dist/patterns/surface/index.cjs +10 -10
  180. package/dist/patterns/surface/index.d.cts +3 -3
  181. package/dist/patterns/surface/index.d.ts +3 -3
  182. package/dist/patterns/surface/index.js +1 -1
  183. package/dist/{pipeline-graph-B85HUrWg.d.cts → pipeline-graph-BrrYGjuZ.d.cts} +2 -2
  184. package/dist/{pipeline-graph-HOTU4UG0.d.ts → pipeline-graph-DX2Twdj-.d.ts} +2 -2
  185. package/dist/{reactive-layout-Btv0-efV.d.ts → reactive-layout-BDdngW56.d.ts} +1 -1
  186. package/dist/{reactive-layout-D9zqqaqK.d.cts → reactive-layout-DrGjuwyC.d.cts} +1 -1
  187. package/dist/{reactive-log-CgbNqksB.d.cts → reactive-log-ScpWyqny.d.cts} +11 -3
  188. package/dist/{reactive-log-ByBb8g6A.d.ts → reactive-log-jirQsxMY.d.ts} +11 -3
  189. package/dist/{topology-tree-CJsT24DP.d.ts → topology-tree-BI665P0L.d.ts} +1 -1
  190. package/dist/{topology-tree-C50l9ARE.d.cts → topology-tree-BkhmMg2a.d.cts} +1 -1
  191. package/package.json +1 -1
  192. package/dist/chunk-5KPIYVCC.js +0 -7
  193. package/dist/chunk-CUQFO6MT.js +0 -1
@@ -1,4 +1,4 @@
1
- "use strict";var Yt=Object.defineProperty;var Br=Object.getOwnPropertyDescriptor;var Hr=Object.getOwnPropertyNames;var Kr=Object.prototype.hasOwnProperty;var _e=(t,e)=>()=>(t&&(e=t(t=0)),e);var qr=(t,e)=>{for(var n in e)Yt(t,n,{get:e[n],enumerable:!0})},Ur=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Hr(e))!Kr.call(t,s)&&s!==n&&Yt(t,s,{get:()=>e[s],enumerable:!(r=Br(e,s))||r.enumerable});return t};var Wr=t=>Ur(Yt({},"__esModule",{value:!0}),t);var Le,M,X,Z,Ee,Se,Pe,ge,j,P,He,vt,Mn,Tt,Dn,Gn,xt,Qt,Xt,Zt,wt,pe=_e(()=>{"use strict";Le=Symbol.for("graphrefly/START"),M=Symbol.for("graphrefly/DATA"),X=Symbol.for("graphrefly/DIRTY"),Z=Symbol.for("graphrefly/RESOLVED"),Ee=Symbol.for("graphrefly/INVALIDATE"),Se=Symbol.for("graphrefly/PAUSE"),Pe=Symbol.for("graphrefly/RESUME"),ge=Symbol.for("graphrefly/TEARDOWN"),j=Symbol.for("graphrefly/COMPLETE"),P=Symbol.for("graphrefly/ERROR"),He=Object.freeze([X]),vt=Object.freeze([Z]),Mn=Object.freeze([Ee]),Tt=Object.freeze([Le]),Dn=Object.freeze([j]),Gn=Object.freeze([ge]),xt=Object.freeze([He]),Qt=Object.freeze([vt]),Xt=Object.freeze([Mn]),Zt=Object.freeze([Dn]),wt=Object.freeze([Gn])});function Pn(t,e){let n=new TextEncoder().encode(t.name);if(n.length===0||n.length>255)throw new Error(`encodeEnvelope: codec name "${t.name}" encodes to ${n.length} bytes (must be 1\u2013255)`);let r=t.version;if(!Number.isInteger(r)||r<0||r>65535)throw new Error(`encodeEnvelope: codec.version ${r} out of u16 range (expected integer 0\u201365535)`);let s=2+n.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++]=en,o[i++]=n.length,o.set(n,i),i+=n.length,o[i++]=r>>>8&255,o[i++]=r&255,o.set(e,i),o}function $n(t,e){if(t.length<Ln)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${Ln})`);let n=0,r=t[n++];if(r!==en)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${en})`);let s=t[n++];if(s===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(n+s+2>t.length)throw new Error(`decodeEnvelope: envelope truncated (need ${n+s+2} bytes, have ${t.length})`);let o=new TextDecoder().decode(t.subarray(n,n+s));n+=s;let i=(t[n]<<8|t[n+1])>>>0;n+=2;let a=t.subarray(n),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 Vn(t){t.registerCodec(Jr)}var Jr,en,Ln,tn=_e(()=>{"use strict";Jr={name:"json",version:1,contentType:"application/json",encode(t){let e=JSON.stringify(t);return new TextEncoder().encode(e)},decode(t,e){let n=new TextDecoder().decode(t);return JSON.parse(n)}},en=1,Ln=4});function _t(t){if(t==null)return Je;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var Je,Et=_e(()=>{"use strict";Je={type:"system",id:""}});function ut(){return Ye>0||it}function Fn(){return Ye>0}function dt(t){Ye>0?at.push(t):t()}function re(t){Ye+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(Ye-=1,Ye===0)if(e){if(!it){let n=at.splice(0);for(let r of n)try{r()}catch{}Ke.length=0,qe.length=0,Qe.length=0}}else Yr()}}function Yr(){let t=!it;t&&(it=!0);let e=[],n=0;try{for(;Ke.length>0||qe.length>0||Qe.length>0||t&&at.length>0;){if(t&&at.length>0){let o=at.splice(0);for(let i of o)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw Ke.length=0,qe.length=0,Qe.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let s=(Ke.length>0?Ke:qe.length>0?qe:Qe).splice(0);for(let o of s)try{o()}catch(i){e.push(i)}}}finally{t&&(it=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function lt(t,e,n){if(e.length===0)return;if(e.length===1){let u=n(e[0][0]);if(u<3||!ut()){t(e);return}(u>=5?Qe:u===4?qe:Ke).push(()=>t(e));return}let r=e.length,s=r,o=r,i=r,a=0;for(;a<r&&n(e[a][0])<3;)a++;for(s=a;a<r&&n(e[a][0])===3;)a++;for(o=a;a<r&&n(e[a][0])===4;)a++;i=a;let d=ut();if(s>0){let u=e.slice(0,s);t(u)}if(o>s){let u=e.slice(s,o);d?Ke.push(()=>t(u)):t(u)}if(i>o){let u=e.slice(o,i);d?qe.push(()=>t(u)):t(u)}if(r>i){let u=e.slice(i,r);d?Qe.push(()=>t(u)):t(u)}}var Ye,it,Ke,qe,Qe,at,De=_e(()=>{"use strict";Ye=0,it=!1,Ke=[],qe=[],Qe=[],at=[]});function ee(){return Math.trunc(performance.now()*1e6)}function be(){return Date.now()*1e6}var Ae=_e(()=>{"use strict"});function jn(t){t.registerMessageType(Le,{tier:0,wireCrossing:!1}),t.registerMessageType(X,{tier:1,wireCrossing:!1}),t.registerMessageType(Ee,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Se,{tier:2,wireCrossing:!1}),t.registerMessageType(Pe,{tier:2,wireCrossing:!1}),t.registerMessageType(M,{tier:3,wireCrossing:!0}),t.registerMessageType(Z,{tier:3,wireCrossing:!0}),t.registerMessageType(j,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(P,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(ge,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var Nt,zn=_e(()=>{"use strict";pe();Nt=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=n=>{let r=this._messageTypes.get(n);return r!=null?r.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,n){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:n.tier,wireCrossing:n.wireCrossing??n.tier>=3,metaPassthrough:n.metaPassthrough??!0}),this}messageTier(e){let n=this._messageTypes.get(e);return n!=null?n.tier:1}isWireCrossing(e){let n=this._messageTypes.get(e);return n!=null?n.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let n=this._messageTypes.get(e);return n!=null?n.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 Bn(t){return Array.isArray(t)?[...t]:[t]}function Qr(t,e){return t.has(e)||t.has("*")}function Hn(t){let e=[];return t((s,o)=>{e.push({kind:"allow",actions:new Set(Bn(s)),where:o?.where??(()=>!0)})},(s,o)=>{e.push({kind:"deny",actions:new Set(Bn(s)),where:o?.where??(()=>!0)})}),(s,o)=>{let i=!1,a=!1;for(let d of e)Qr(d.actions,o)&&d.where(s)&&(d.kind==="deny"?i=!0:a=!0);return i?!1:a}}function nn(t){let e=Xr.filter(n=>t({type:n,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(n=>n==="human"||n==="llm"||n==="system")?"both":e.length===1?e[0]:e.join("+")}var Ne,Xr,Xe=_e(()=>{"use strict";Ne=class extends Error{actor;action;nodeName;constructor(e,n){super(n??`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}};Xr=["human","llm","wallet","system"]});function rn(t){if(t===void 0)return null;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`Cannot hash non-finite number: ${t}`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${t}. Cross-language cid parity is not guaranteed for unsafe integers.`);return t}if(typeof t=="string"||typeof t=="boolean"||t===null)return t;if(Array.isArray(t))return t.map(rn);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=rn(t[n]);return e}return null}function to(t){let e=eo.encode(t),n=e.length,r=n*8,s=n+9+63&-64,o=new Uint8Array(s);o.set(e),o[n]=128;let i=new DataView(o.buffer);i.setUint32(s-4,r>>>0,!1),i.setUint32(s-8,Math.floor(r/4294967296)>>>0,!1);let a=1779033703,d=3144134277,u=1013904242,l=2773480762,h=1359893119,c=2600822924,p=528734635,f=1541459225,g=new Uint32Array(64),b=(x,v)=>x>>>v|x<<32-v;for(let x=0;x<s;x+=64){for(let k=0;k<16;k++)g[k]=i.getUint32(x+k*4,!1);for(let k=16;k<64;k++){let S=g[k-15],C=g[k-2],B=b(S,7)^b(S,18)^S>>>3,Y=b(C,17)^b(C,19)^C>>>10;g[k]=g[k-16]+B+g[k-7]+Y>>>0}let v=a,w=d,R=u,_=l,m=h,T=c,E=p,A=f;for(let k=0;k<64;k++){let S=b(m,6)^b(m,11)^b(m,25),C=m&T^~m&E,B=A+S+C+Zr[k]+g[k]>>>0,Y=b(v,2)^b(v,13)^b(v,22),W=v&w^v&R^w&R,ye=Y+W>>>0;A=E,E=T,T=m,m=_+B>>>0,_=R,R=w,w=v,v=B+ye>>>0}a=a+v>>>0,d=d+w>>>0,u=u+R>>>0,l=l+_>>>0,h=h+m>>>0,c=c+T>>>0,p=p+E>>>0,f=f+A>>>0}let y=x=>x.toString(16).padStart(8,"0");return y(a)+y(d)+y(u)+y(l)+y(h)+y(c)+y(p)+y(f)}function on(t){let e=rn(t??null),n=JSON.stringify(e);return to(n).slice(0,16)}function no(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),n=e()+e()+e()+e();return`${n.slice(0,8)}-${n.slice(8,12)}-4${n.slice(13,16)}-${(parseInt(n.slice(16,17),16)&3|8).toString(16)}${n.slice(17,20)}-${n.slice(20,32)}`}function sn(t,e,n){let r=n?.id??no();if(t===0)return{id:r,version:0};let o=(n?.hash??on)(e);return{id:r,version:0,cid:o,prev:null}}function Kn(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}var Zr,eo,qn=_e(()=>{"use strict";Zr=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]),eo=new TextEncoder});function Jn(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function an(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function Rt(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function oe(t,e,n){let r=Yn(t)?t:[],s=typeof t=="function"?t:typeof e=="function"?e:void 0,o={};return Yn(t)?o=(un(e)?e:n)??{}:un(t)?o=t:o=(un(e)?e:n)??{},new se(r,s,o)}var Un,Wn,ro,oo,Ze,se,Yn,un,Ce=_e(()=>{"use strict";tn();Et();De();Ae();zn();Xe();pe();qn();Un=()=>{},Wn=100;ro=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},oo=(t,e,n,r)=>{let s=t;if(s._status==="completed"||s._status==="errored")return;let o=s._cached,i=o===void 0?[Tt]:[Tt,[M,o]];s._status==="dirty"&&i.push(He),lt(e,i,s._config.tierOf)},Ze=new Nt({onMessage:ro,onSubscribe:oo});jn(Ze);Vn(Ze);se=class t{_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,n,r){this._config=r.config??Ze,this._config.onMessage,this._optsName=r.name,this._describeKind=r.describeKind,this._equals=r.equals??Object.is,this._resubscribable=r.resubscribable??!1,this._resetOnTeardown=r.resetOnTeardown??!1,this._autoComplete=r.completeWhenDepsComplete??!0,this._autoError=r.errorWhenDepsError??!0,this._pausable=r.pausable??!0,this._guard=r.guard,this._fn=n,this._partial=r.partial??!1,this._cached=r.initial!==void 0?r.initial:void 0,this._status=e.length===0&&n==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=r.versioningHash??this._config.defaultHashFn??on;let s=r.versioning??this._config.defaultVersioning;this._versioningLevel=s,this._versioning=s!=null?sn(s,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(Jn);let o={};for(let[a,d]of Object.entries(r.meta??{})){let u={initial:d,name:`${r.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};r.guard!=null&&(u.guard=r.guard),o[a]=new t([],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([[M,a]])},down(a){i._emit(Rt(a))},up(a){i._emitUp(Rt(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,n){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 r=this._versioningLevel;if(r!=null&&e<=r)return;let s=n?.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??n?.id,d=i?.version??0,u=sn(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 n=_t(e);if(this._guard!=null&&!this._guard(n,"observe"))return!1;if(this._extraGuards!=null){for(let r of this._extraGuards)if(!r(n,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let n=this._guard!=null||this._extraGuards!=null,r=e?.actor!=null;if(!n&&!r)return;let s=_t(e?.actor),o=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(s,o))throw new Ne({actor:s,action:o,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(s,o))throw new Ne({actor:s,action:o,nodeName:this.name})}this._lastMutation={actor:s,timestamp_ns:be()}}down(e,n){let r=Rt(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[M,e]])}up(e,n){if(this._deps.length===0)return;let r=Rt(e);if(r.length===0)return;this._checkGuard(n);let s=n??{internal:!0};this._validateUpTiers(r);for(let o of this._deps)o.node.up?.(r,s)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let n of this._deps)n.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let n=this._config.tierOf;for(let r of e){let s=n(r[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,n){if(n!=null&&this._guard!=null){let d=_t(n);if(!this._guard(d,"observe"))throw new Ne({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)an(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[n]=this._sinks;this._sinks=n}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,n=0;try{for(let r=0;r<e;r++){let s=r,o=this._deps[r];o.unsub=Un,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()}),n++}}catch(r){this._deps[n].unsub=null;for(let s=0;s<n;s++){let o=this._deps[s];if(o.unsub!=null){let i=o.unsub;o.unsub=null;try{i()}catch{}an(o)}}throw this._dirtyDepCount=0,r}}_addDep(e){for(let s=0;s<this._deps.length;s++)if(this._deps[s].node===e)return s;let n=this._deps.length,r=Jn(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(xt),r.unsub=Un;try{r.unsub=e.subscribe(s=>{if(r.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:n},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(s){throw r.unsub=null,this._deps.pop(),this._dirtyDepCount--,s}return n}_deactivate(e=!1){let n=this._cleanup;if(this._cleanup=void 0,typeof n=="function")try{n()}catch(r){this._emit([[P,this._wrapFnError("cleanup threw",r)]])}else if(n!=null&&typeof n=="object"){let r=n.deactivate;if(typeof r=="function")try{r()}catch(s){this._emit([[P,this._wrapFnError("cleanup.deactivate threw",s)]])}}for(let r of this._deps){if(r.unsub!=null){let s=r.unsub;r.unsub=null;try{s()}catch{}}an(r)}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,n){let r=this._deps[e],s=n[0];if(this._inspectorHooks!=null){let o={kind:"dep_message",depIndex:e,message:n};for(let i of this._inspectorHooks)i(o)}if(s!==Le){if(s===X){this._depDirtied(r);return}if(s===Ee){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(Xt);return}if(s===Se||s===Pe){this._emit([n]);return}if(s===ge){this._emit(wt);return}if(s===M)this._depSettledAsData(r,n[1]);else if(s===Z)this._depSettledAsResolved(r);else if(s===j)this._depSettledAsTerminal(r,!0);else if(s===P)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(s===M||s===Z)&&this._emit([n]),(s===j||s===P)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(xt))}_depSettledAsData(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(n),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=n,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 n=this._deps[e];if(n.dataBatch.length===0&&n.prevData===void 0&&n.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(Qt),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(n=>n.terminal!==void 0&&n.terminal!==!0);if(e!=null){this._autoError&&this._emit([[P,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(Zt)}_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([[P,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([[P,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let n=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),r=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=n[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let s=this._deps.map(i=>i.terminal),o={prevData:r,terminalDeps:s,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:n,prevData:r};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(n,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([[P,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>Wn?(this._rerunDepth=0,this._emit([[P,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Wn} \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,n){let r=n instanceof Error?n.message:String(n);return new Error(`Node "${this.name}": ${e}: ${r}`,{cause:n})}_frameBatch(e){let n=this._config.tierOf;if(e.length===1)return n(e[0][0])===3&&this._status!=="dirty"?[He,e[0]]:e;let r=!0,s=!1,o=!1,i=-1;for(let d of e){let u=n(d[0]);u<i&&(r=!1),u===3&&(s=!0),d[0]===X&&(o=!0),i=u}let a=e;if(!r){let d=e.map((u,l)=>({m:u,i:l,tier:n(u[0])}));d.sort((u,l)=>u.tier-l.tier||u.i-l.i),a=d.map(u=>u.m)}if(s&&!o&&this._status!=="dirty"){let d=0;for(;d<a.length&&n(a[d][0])===0;)d++;return d===0?[He,...a]:[...a.slice(0,d),He,...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]===P&&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 n=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(d=>d[0]===ge||d[0]===Ee);if(a.length===0)return;n=a}n=this._frameBatch(n);let s=null;for(let a=0;a<n.length;a++){let d=n[a],u=d[0];if(u!==Se&&u!==Pe){s?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===Se?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let l=!0;if(this._pausable!==!1){let h=d[1];if(u===Se)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(h),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(h))l=!1;else if(this._pauseLocks.delete(h),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let c=this._pauseBuffer;this._pauseBuffer=[],this._emit(c)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}l?s?.push(d):s==null&&(s=n.slice(0,a))}if(s!=null){if(s.length===0)return;n=s}if(this._hasMeta&&n.some(a=>a[0]===ge))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(wt)}catch{}let{finalMessages:o,equalsError:i}=this._updateState(n);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([[P,i]])}_updateState(e){let n=this._config.tierOf,r,s,o=-1,i=0;for(let l of e)n(l[0])===3&&i++;let a=i<=1,d=-1;if(this._versioning!=null&&i>1){for(let l=e.length-1;l>=0;l--)if(e[l][0]===M){d=l;break}}for(let l=0;l<e.length;l++){let h=e[l],c=h[0];if(c===M){if(h.length>=2){let p=!1;if(a&&this._cached!==void 0)try{p=this._equals(this._cached,h[1])}catch(f){s=this._wrapFnError("equals threw",f),o=l;break}if(p){r==null&&(r=e.slice(0,l)),r.push(vt),this._status="resolved";continue}this._cached=h[1],this._versioning!=null&&(d<0||l===d)&&Kn(this._versioning,h[1],this._hashFn)}this._status="settled",r?.push(h)}else if(r?.push(h),c===X)this._status="dirty";else if(c===Z)this._status="resolved";else if(c===j){this._status="completed";{let p=this._config.rigorRecorder;if(p!=null)try{p.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(c===P){this._status="errored";{let p=this._config.rigorRecorder;if(p!=null)try{p.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(c===Ee){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 p=this._cleanup;if(typeof p=="function"){this._cleanup=void 0;try{p()}catch{}}else if(p!=null&&typeof p=="object"){let f=p.invalidate;if(typeof f=="function")try{f()}catch{}}}else c===ge&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=o>=0?r??e.slice(0,o):r??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 n=[...this._sinks];for(let r of n)r(e)};_dispatchOrAccumulate(e){if(Fn()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],dt(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}lt(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let n=this._frameBatch(e);lt(this._deliverToSinks,n,this._config.tierOf)}},Yn=t=>Array.isArray(t),un=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function V(t,e){return oe([],{...e,initial:t})}function he(t,e){return oe((r,s,o)=>t(s,o)??void 0,{describeKind:"producer",...e})}function G(t,e,n){return oe(t,(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",...n})}function me(t,e,n){return oe(t,(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",...n})}var de=_e(()=>{"use strict";Ce()});function dn(t){return{describeKind:"producer",...t}}function Qn(t,e){return he(n=>{let r=!1;try{for(let s of t){if(r)return;n.emit(s)}r||n.down([[j]])}catch(s){r||n.down([[P,s]])}return()=>{r=!0}},dn(e))}function so(t){return t!=null&&typeof t.then=="function"}function io(t,e){let{signal:n,...r}=e??{};return he(s=>{let o=!1,i=()=>{o||(o=!0,s.down([[P,n.reason]]))};if(n?.aborted){i();return}return n?.addEventListener("abort",i,{once:!0}),Promise.resolve(t).then(a=>{o||(o=!0,n?.removeEventListener("abort",i),s.emit(a),s.down([[j]]))},a=>{o||(o=!0,n?.removeEventListener("abort",i),s.down([[P,a]]))}),()=>{o=!0,n?.removeEventListener("abort",i)}},dn(r))}function ao(t,e){let{signal:n,...r}=e??{};return he(s=>{let o=new AbortController,i=()=>o.abort(n?.reason);n?.aborted?o.abort(n.reason):n?.addEventListener("abort",i,{once:!0});let a=n??o.signal,d=!1,u=t[Symbol.asyncIterator](),l=()=>{d||a.aborted||Promise.resolve(u.next()).then(h=>{if(!(d||a.aborted)){if(h.done){s.down([[j]]);return}s.emit(h.value),l()}},h=>{!d&&!a.aborted&&s.down([[P,h]])})};return l(),()=>{d=!0,n?.removeEventListener("abort",i),o.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},dn(r))}function uo(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function Ve(t,e){if(uo(t))return t;if(so(t))return io(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return ao(t,e);if(typeof n[Symbol.iterator]=="function")return Qn(t,e)}return lo(t)}function lo(...t){return Qn(t,void 0)}function Xn(t,e){let n=new AbortController,r=e?.reason??new Error("cancelled via nodeSignal"),s,o=!1,i=()=>{s?(s(),s=void 0):o=!0};return s=t.subscribe(a=>{if(!n.signal.aborted)for(let d of a){if(d[0]===M&&d[1]===!0){n.abort(r),i();return}if(d[0]===P){n.abort(d[1]),i();return}if(d[0]===j){i();return}}}),o&&(s?.(),s=void 0),{signal:n.signal,dispose:()=>{s&&(s(),s=void 0)}}}function Te(t){return t.subscribe(()=>{})}var Ue=_e(()=>{"use strict";pe();de()});var Ct,er=_e(()=>{"use strict";Ct=class{_timer;_gen=0;start(e,n){this.cancel(),this._gen+=1;let r=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,r===this._gen&&n()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var Us={};qr(Us,{DEFAULT_DECAY_RATE:()=>tt,DEFAULT_EXECUTE_PROMPT:()=>cn,DEFAULT_QUEUE_CONFIGS:()=>Ot,DEFAULT_SEVERITY_WEIGHTS:()=>et,DEFAULT_TRIAGE_PROMPT:()=>ln,DEFAULT_VERIFY_PROMPT:()=>fn,HarnessGraph:()=>Wt,QUEUE_NAMES:()=>xe,actuatorExecutor:()=>bo,affectedTaskFilter:()=>_o,autoSolidify:()=>yo,beforeAfterCompare:()=>wo,codeChangeBridge:()=>Eo,createIntakeBridge:()=>vo,defaultErrorClassifier:()=>St,defaultLlmExecutor:()=>Vr,defaultLlmVerifier:()=>Fr,evalIntakeBridge:()=>To,evalSource:()=>xo,evalVerifier:()=>kr,harnessEvalPair:()=>Ms,harnessLoop:()=>js,harnessProfile:()=>Bs,harnessTrace:()=>Ks,notifyEffect:()=>No,priorityScore:()=>Vs,refineExecutor:()=>Nn,resolvePromptFn:()=>ft,strategyKey:()=>nt,strategyModel:()=>An});module.exports=Wr(Us);pe();de();pe();Ce();de();Ue();function kt(t){return{describeKind:"derived",...t}}function co(t){return{describeKind:"derived",partial:!0,...t}}function $e(t,e,n){return oe([t],(r,s)=>{let o=r[0];if(o==null||o.length===0){s.down([[Z]]);return}let i=!1;for(let a of o)e(a)&&(s.emit(a),i=!0);i||s.down([[Z]])},kt(n))}function ct(t,e,n){return oe([t,e],(r,s,o)=>{let i=r[0],a=r[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([[Z]]);return}for(let u of i)s.emit([u,d])}else s.down([[Z]])},co(n))}function Zn(...t){return t.length===0?he(e=>{e.down([[j]])},kt()):he(e=>{let n=t.length,r=0,s=[];for(let o of t){let i=o.subscribe(a=>{for(let d of a)d[0]===M?e.emit(d[1]):d[0]===j?(r+=1,r>=n&&e.down([[j]])):d[0]===P&&e.down([d])});s.push(i)}return()=>{for(let o of s)o()}},kt())}function fo(t,e,n){let r,s=!1,o=()=>{s||(s=!0,n())};return r=t.subscribe(i=>{let a=!1,d=!1;for(let u of i)u[0]!==Le&&(u[0]===M?e.emit(u[1]):u[0]===j?a=!0:u[0]===P?(d=!0,e.down([u])):(u[0]===X||u[0]===Z)&&e.down([u]));d?(r?.(),r=void 0,o()):a&&o()}),()=>{r?.(),r=void 0}}function Re(t,e,n){let r,s=!1;function o(){r?.(),r=void 0}return oe([t],(i,a,d)=>{if(d.terminalDeps[0]!=null&&d.terminalDeps[0]!==!0){o();return}if(d.terminalDeps[0]===!0){s=!0,r||a.down([[j]]);return}let u=i[0];if(!(u==null||u.length===0))return o(),r=fo(Ve(e(u[u.length-1])),a,()=>{o(),s&&a.down([[j]])}),{deactivate:()=>{o(),s=!1}}},{...kt(n),completeWhenDepsComplete:!1})}Ue();function po(t,e){return{outcome:"success",detail:`actuator applied ${e.intervention} for ${go(e.summary)}`,artifact:t}}function ho(t,e){let n=t instanceof Error?t.message:String(t);return{outcome:"failure",detail:`actuator threw on ${e.intervention}: ${n}`}}function mo(t){return`actuator skipped ${t.intervention} (shouldApply returned false)`}function go(t,e=80){return t.length<=e?t:`${t.slice(0,e-1)}\u2026`}function bo(t){let e=t.name??"actuator-executor",n=t.toOutput??po,r=t.onError??ho,s=t.skipDetail??mo;return o=>{let i=$e(o,d=>d!=null,{name:`${e}/gate-in`}),a=Re(i,d=>t.shouldApply&&!t.shouldApply(d)?he(u=>(u.down([[M,{outcome:"failure",detail:s(d)}],[j]]),()=>{}),{name:`${e}/skip`}):he(u=>{let l=new AbortController,h=!1,c=null,p=g=>{h||(h=!0,u.down([[M,g],[j]]),c?.(),c=null)},f;try{let g=t.apply(d,{signal:l.signal});f=Ve(g,{signal:l.signal})}catch(g){return p(r(g,d)),()=>{l.abort()}}return c=f.subscribe(g=>{for(let b of g){if(h)return;if(b[0]===M){p(n(b[1],d));return}if(b[0]===P){p(r(b[1],d));return}if(b[0]===j){p(r(new Error("actuator inner completed without emitting DATA"),d));return}}}),h&&c&&(c(),c=null),()=>{l.abort(),c?.(),c=null}},{name:`${e}/inner`}),{name:e});return $e(a,d=>d!=null,{name:`${e}/gate-out`})}}pe();de();function yo(t){let e=t.name??"auto-solidify",n=t.extract??(s=>s.execution.artifact??null),r=t.predicate??(()=>!0);return he(s=>{let o=null,i=!1,a=()=>{i||(i=!0,o?.(),o=null)},d=u=>{i||(s.down([[P,u]]),a())};return o=t.verifyResults.subscribe(u=>{if(!i)for(let l of u){if(i)return;if(l[0]!==M){if(l[0]===j){s.down([[j]]),a();return}continue}let h=l[1];if(h==null||!h.verified)continue;let c;try{c=r(h)}catch(f){d(f);return}if(!c)continue;let p;try{p=n(h)}catch(f){d(f);return}if(p!=null){try{t.write(p,h)}catch(f){d(f);return}s.down([[M,p]])}}}),i&&o&&(o(),o=null),()=>{a()}},{name:e})}de();Ue();function vo(t,e,n,r){return me([t],([s])=>{if(s==null)return;let o=n(s);for(let i of o)e.publish(i)},{name:r?.name??"intake-bridge"})}function To(t,e,n){let r=n?.defaultSeverity??"medium";return me([t],([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:r});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:r})}},{name:n?.name??"eval-intake-bridge"})}function xo(t,e){return Re(t,()=>Ve(e()))}function wo(t,e){return G([t,e],([n,r])=>{let s=n,o=r,i=new Map(s.tasks.map(c=>[c.task_id,c])),a=new Map(o.tasks.map(c=>[c.task_id,c])),d=new Set([...i.keys(),...a.keys()]),u=[],l=[],h=[];for(let c of d){let p=i.get(c),f=a.get(c),g=p?.valid??!1,b=f?.valid??!1,y=p?.judge_scores?p.judge_scores.filter(w=>w.pass).length:void 0,x=f?.judge_scores?f.judge_scores.filter(w=>w.pass).length:void 0,v=y!==void 0&&x!==void 0?x-y:void 0;u.push({taskId:c,before:g,after:b,scoreDiff:v}),g&&!b&&l.push(c),!g&&b&&h.push(c)}return{newFailures:l,resolved:h,taskDeltas:u,overallImproved:h.length>l.length}},{name:"eval-delta"})}function _o(t,e){let n=e==null?null:Array.isArray(e)?V(e):e,r=[t];return n&&r.push(n),G(r,s=>{let o=s[0],i=n?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 Eo(t,e,n,r){let s=r?.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=n??o;return me([t],([a])=>{if(a!=null)for(let d of i(a))e.publish(d)},{name:r?.name??"code-change-bridge"})}function No(t,e,n){return me([t.latest],([r])=>{r!=null&&e(r)},{name:n?.name??"notify-effect"})}var xe=["auto-fix","needs-decision","investigation","backlog"],Ot={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},et={critical:100,high:70,medium:40,low:10},tt=Math.LN2/(168*3600);function nt(t,e){return`${t}\u2192${e}`}var Ro=/\b(parse|json|config|validation|syntax)\b/i,St=t=>Ro.test(t.detail)?"self-correctable":"structural",ln=`You are a triage classifier for a reactive collaboration harness.
1
+ "use strict";var Yt=Object.defineProperty;var Kr=Object.getOwnPropertyDescriptor;var qr=Object.getOwnPropertyNames;var Ur=Object.prototype.hasOwnProperty;var _e=(t,e)=>()=>(t&&(e=t(t=0)),e);var Wr=(t,e)=>{for(var n in e)Yt(t,n,{get:e[n],enumerable:!0})},Jr=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of qr(e))!Ur.call(t,s)&&s!==n&&Yt(t,s,{get:()=>e[s],enumerable:!(r=Kr(e,s))||r.enumerable});return t};var Yr=t=>Jr(Yt({},"__esModule",{value:!0}),t);var Le,I,X,Z,Ee,Se,Pe,me,j,L,He,vt,In,Tt,Dn,Gn,xt,Qt,Xt,Zt,wt,pe=_e(()=>{"use strict";Le=Symbol.for("graphrefly/START"),I=Symbol.for("graphrefly/DATA"),X=Symbol.for("graphrefly/DIRTY"),Z=Symbol.for("graphrefly/RESOLVED"),Ee=Symbol.for("graphrefly/INVALIDATE"),Se=Symbol.for("graphrefly/PAUSE"),Pe=Symbol.for("graphrefly/RESUME"),me=Symbol.for("graphrefly/TEARDOWN"),j=Symbol.for("graphrefly/COMPLETE"),L=Symbol.for("graphrefly/ERROR"),He=Object.freeze([X]),vt=Object.freeze([Z]),In=Object.freeze([Ee]),Tt=Object.freeze([Le]),Dn=Object.freeze([j]),Gn=Object.freeze([me]),xt=Object.freeze([He]),Qt=Object.freeze([vt]),Xt=Object.freeze([In]),Zt=Object.freeze([Dn]),wt=Object.freeze([Gn])});function Pn(t,e){let n=new TextEncoder().encode(t.name);if(n.length===0||n.length>255)throw new Error(`encodeEnvelope: codec name "${t.name}" encodes to ${n.length} bytes (must be 1\u2013255)`);let r=t.version;if(!Number.isInteger(r)||r<0||r>65535)throw new Error(`encodeEnvelope: codec.version ${r} out of u16 range (expected integer 0\u201365535)`);let s=2+n.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++]=en,o[i++]=n.length,o.set(n,i),i+=n.length,o[i++]=r>>>8&255,o[i++]=r&255,o.set(e,i),o}function $n(t,e){if(t.length<Ln)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${Ln})`);let n=0,r=t[n++];if(r!==en)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${en})`);let s=t[n++];if(s===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(n+s+2>t.length)throw new Error(`decodeEnvelope: envelope truncated (need ${n+s+2} bytes, have ${t.length})`);let o=new TextDecoder().decode(t.subarray(n,n+s));n+=s;let i=(t[n]<<8|t[n+1])>>>0;n+=2;let a=t.subarray(n),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 Vn(t){t.registerCodec(Qr)}var Qr,en,Ln,tn=_e(()=>{"use strict";Qr={name:"json",version:1,contentType:"application/json",encode(t){let e=JSON.stringify(t);return new TextEncoder().encode(e)},decode(t,e){let n=new TextDecoder().decode(t);return JSON.parse(n)}},en=1,Ln=4});function _t(t){if(t==null)return Je;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var Je,Et=_e(()=>{"use strict";Je={type:"system",id:""}});function ut(){return Ye>0||it}function Fn(){return Ye>0}function dt(t){Ye>0?at.push(t):t()}function re(t){Ye+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(Ye-=1,Ye===0)if(e){if(!it){let n=at.splice(0);for(let r of n)try{r()}catch{}Ke.length=0,qe.length=0,Qe.length=0}}else Xr()}}function Xr(){let t=!it;t&&(it=!0);let e=[],n=0;try{for(;Ke.length>0||qe.length>0||Qe.length>0||t&&at.length>0;){if(t&&at.length>0){let o=at.splice(0);for(let i of o)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw Ke.length=0,qe.length=0,Qe.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let s=(Ke.length>0?Ke:qe.length>0?qe:Qe).splice(0);for(let o of s)try{o()}catch(i){e.push(i)}}}finally{t&&(it=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function lt(t,e,n){if(e.length===0)return;if(e.length===1){let u=n(e[0][0]);if(u<3||!ut()){t(e);return}(u>=5?Qe:u===4?qe:Ke).push(()=>t(e));return}let r=e.length,s=r,o=r,i=r,a=0;for(;a<r&&n(e[a][0])<3;)a++;for(s=a;a<r&&n(e[a][0])===3;)a++;for(o=a;a<r&&n(e[a][0])===4;)a++;i=a;let d=ut();if(s>0){let u=e.slice(0,s);t(u)}if(o>s){let u=e.slice(s,o);d?Ke.push(()=>t(u)):t(u)}if(i>o){let u=e.slice(o,i);d?qe.push(()=>t(u)):t(u)}if(r>i){let u=e.slice(i,r);d?Qe.push(()=>t(u)):t(u)}}var Ye,it,Ke,qe,Qe,at,De=_e(()=>{"use strict";Ye=0,it=!1,Ke=[],qe=[],Qe=[],at=[]});function ee(){return Math.trunc(performance.now()*1e6)}function be(){return Date.now()*1e6}var Ae=_e(()=>{"use strict"});function jn(t){t.registerMessageType(Le,{tier:0,wireCrossing:!1}),t.registerMessageType(X,{tier:1,wireCrossing:!1}),t.registerMessageType(Ee,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Se,{tier:2,wireCrossing:!1}),t.registerMessageType(Pe,{tier:2,wireCrossing:!1}),t.registerMessageType(I,{tier:3,wireCrossing:!0}),t.registerMessageType(Z,{tier:3,wireCrossing:!0}),t.registerMessageType(j,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(L,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(me,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var Nt,zn=_e(()=>{"use strict";pe();Nt=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=n=>{let r=this._messageTypes.get(n);return r!=null?r.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,n){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:n.tier,wireCrossing:n.wireCrossing??n.tier>=3,metaPassthrough:n.metaPassthrough??!0}),this}messageTier(e){let n=this._messageTypes.get(e);return n!=null?n.tier:1}isWireCrossing(e){let n=this._messageTypes.get(e);return n!=null?n.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let n=this._messageTypes.get(e);return n!=null?n.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 Bn(t){return Array.isArray(t)?[...t]:[t]}function Zr(t,e){return t.has(e)||t.has("*")}function Hn(t){let e=[];return t((s,o)=>{e.push({kind:"allow",actions:new Set(Bn(s)),where:o?.where??(()=>!0)})},(s,o)=>{e.push({kind:"deny",actions:new Set(Bn(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 nn(t){let e=eo.filter(n=>t({type:n,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(n=>n==="human"||n==="llm"||n==="system")?"both":e.length===1?e[0]:e.join("+")}var Ne,eo,Xe=_e(()=>{"use strict";Ne=class extends Error{actor;action;nodeName;constructor(e,n){super(n??`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 rn(t){if(t===void 0)return null;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`Cannot hash non-finite number: ${t}`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${t}. Cross-language cid parity is not guaranteed for unsafe integers.`);return t}if(typeof t=="string"||typeof t=="boolean"||t===null)return t;if(Array.isArray(t))return t.map(rn);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=rn(t[n]);return e}return null}function ro(t){let e=no.encode(t),n=e.length,r=n*8,s=n+9+63&-64,o=new Uint8Array(s);o.set(e),o[n]=128;let i=new DataView(o.buffer);i.setUint32(s-4,r>>>0,!1),i.setUint32(s-8,Math.floor(r/4294967296)>>>0,!1);let a=1779033703,d=3144134277,u=1013904242,l=2773480762,h=1359893119,c=2600822924,p=528734635,f=1541459225,g=new Uint32Array(64),b=(T,y)=>T>>>y|T<<32-y;for(let T=0;T<s;T+=64){for(let k=0;k<16;k++)g[k]=i.getUint32(T+k*4,!1);for(let k=16;k<64;k++){let S=g[k-15],C=g[k-2],B=b(S,7)^b(S,18)^S>>>3,Y=b(C,17)^b(C,19)^C>>>10;g[k]=g[k-16]+B+g[k-7]+Y>>>0}let y=a,w=d,N=u,_=l,m=h,x=c,E=p,A=f;for(let k=0;k<64;k++){let S=b(m,6)^b(m,11)^b(m,25),C=m&x^~m&E,B=A+S+C+to[k]+g[k]>>>0,Y=b(y,2)^b(y,13)^b(y,22),W=y&w^y&N^w&N,ye=Y+W>>>0;A=E,E=x,x=m,m=_+B>>>0,_=N,N=w,w=y,y=B+ye>>>0}a=a+y>>>0,d=d+w>>>0,u=u+N>>>0,l=l+_>>>0,h=h+m>>>0,c=c+x>>>0,p=p+E>>>0,f=f+A>>>0}let v=T=>T.toString(16).padStart(8,"0");return v(a)+v(d)+v(u)+v(l)+v(h)+v(c)+v(p)+v(f)}function on(t){let e=rn(t??null),n=JSON.stringify(e);return ro(n).slice(0,16)}function oo(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),n=e()+e()+e()+e();return`${n.slice(0,8)}-${n.slice(8,12)}-4${n.slice(13,16)}-${(parseInt(n.slice(16,17),16)&3|8).toString(16)}${n.slice(17,20)}-${n.slice(20,32)}`}function sn(t,e,n){let r=n?.id??oo();if(t===0)return{id:r,version:0};let o=(n?.hash??on)(e);return{id:r,version:0,cid:o,prev:null}}function Kn(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}var to,no,qn=_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 Jn(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function an(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function Rt(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function oe(t,e,n){let r=Yn(t)?t:[],s=typeof t=="function"?t:typeof e=="function"?e:void 0,o={};return Yn(t)?o=(un(e)?e:n)??{}:un(t)?o=t:o=(un(e)?e:n)??{},new se(r,s,o)}var Un,Wn,so,io,Ze,se,Yn,un,Ce=_e(()=>{"use strict";tn();Et();De();Ae();zn();Xe();pe();qn();Un=()=>{},Wn=100;so=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},io=(t,e,n,r)=>{let s=t;if(s._status==="completed"||s._status==="errored")return;let o=s._cached,i=o===void 0?[Tt]:[Tt,[I,o]];s._status==="dirty"&&i.push(He),lt(e,i,s._config.tierOf)},Ze=new Nt({onMessage:so,onSubscribe:io});jn(Ze);Vn(Ze);se=class t{_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,n,r){this._config=r.config??Ze,this._config.onMessage,this._optsName=r.name,this._describeKind=r.describeKind,this._equals=r.equals??Object.is,this._resubscribable=r.resubscribable??!1,this._resetOnTeardown=r.resetOnTeardown??!1,this._autoComplete=r.completeWhenDepsComplete??!0,this._autoError=r.errorWhenDepsError??!0,this._pausable=r.pausable??!0,this._guard=r.guard,this._fn=n,this._partial=r.partial??!1,this._cached=r.initial!==void 0?r.initial:void 0,this._status=e.length===0&&n==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=r.versioningHash??this._config.defaultHashFn??on;let s=r.versioning??this._config.defaultVersioning;this._versioningLevel=s,this._versioning=s!=null?sn(s,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(Jn);let o={};for(let[a,d]of Object.entries(r.meta??{})){let u={initial:d,name:`${r.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};r.guard!=null&&(u.guard=r.guard),o[a]=new t([],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([[I,a]])},down(a){i._emit(Rt(a))},up(a){i._emitUp(Rt(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,n){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 r=this._versioningLevel;if(r!=null&&e<=r)return;let s=n?.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??n?.id,d=i?.version??0,u=sn(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 n=_t(e);if(this._guard!=null&&!this._guard(n,"observe"))return!1;if(this._extraGuards!=null){for(let r of this._extraGuards)if(!r(n,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let n=this._guard!=null||this._extraGuards!=null,r=e?.actor!=null;if(!n&&!r)return;let s=_t(e?.actor),o=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(s,o))throw new Ne({actor:s,action:o,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(s,o))throw new Ne({actor:s,action:o,nodeName:this.name})}this._lastMutation={actor:s,timestamp_ns:be()}}down(e,n){let r=Rt(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[I,e]])}up(e,n){if(this._deps.length===0)return;let r=Rt(e);if(r.length===0)return;this._checkGuard(n);let s=n??{internal:!0};this._validateUpTiers(r);for(let o of this._deps)o.node.up?.(r,s)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let n of this._deps)n.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let n=this._config.tierOf;for(let r of e){let s=n(r[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,n){if(n!=null&&this._guard!=null){let d=_t(n);if(!this._guard(d,"observe"))throw new Ne({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)an(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[n]=this._sinks;this._sinks=n}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,n=0;try{for(let r=0;r<e;r++){let s=r,o=this._deps[r];o.unsub=Un,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()}),n++}}catch(r){this._deps[n].unsub=null;for(let s=0;s<n;s++){let o=this._deps[s];if(o.unsub!=null){let i=o.unsub;o.unsub=null;try{i()}catch{}an(o)}}throw this._dirtyDepCount=0,r}}_addDep(e){for(let s=0;s<this._deps.length;s++)if(this._deps[s].node===e)return s;let n=this._deps.length,r=Jn(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(xt),r.unsub=Un;try{r.unsub=e.subscribe(s=>{if(r.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:n},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(s){throw r.unsub=null,this._deps.pop(),this._dirtyDepCount--,s}return n}_deactivate(e=!1){let n=this._cleanup;if(this._cleanup=void 0,typeof n=="function")try{n()}catch(r){this._emit([[L,this._wrapFnError("cleanup threw",r)]])}else if(n!=null&&typeof n=="object"){let r=n.deactivate;if(typeof r=="function")try{r()}catch(s){this._emit([[L,this._wrapFnError("cleanup.deactivate threw",s)]])}}for(let r of this._deps){if(r.unsub!=null){let s=r.unsub;r.unsub=null;try{s()}catch{}}an(r)}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,n){let r=this._deps[e],s=n[0];if(this._inspectorHooks!=null){let o={kind:"dep_message",depIndex:e,message:n};for(let i of this._inspectorHooks)i(o)}if(s!==Le){if(s===X){this._depDirtied(r);return}if(s===Ee){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(Xt);return}if(s===Se||s===Pe){this._emit([n]);return}if(s===me){this._emit(wt);return}if(s===I)this._depSettledAsData(r,n[1]);else if(s===Z)this._depSettledAsResolved(r);else if(s===j)this._depSettledAsTerminal(r,!0);else if(s===L)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(s===I||s===Z)&&this._emit([n]),(s===j||s===L)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(xt))}_depSettledAsData(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(n),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=n,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 n=this._deps[e];if(n.dataBatch.length===0&&n.prevData===void 0&&n.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(Qt),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(n=>n.terminal!==void 0&&n.terminal!==!0);if(e!=null){this._autoError&&this._emit([[L,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(Zt)}_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([[L,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([[L,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let n=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),r=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=n[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let s=this._deps.map(i=>i.terminal),o={prevData:r,terminalDeps:s,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:n,prevData:r};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(n,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([[L,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>Wn?(this._rerunDepth=0,this._emit([[L,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Wn} \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,n){let r=n instanceof Error?n.message:String(n);return new Error(`Node "${this.name}": ${e}: ${r}`,{cause:n})}_frameBatch(e){let n=this._config.tierOf;if(e.length===1)return n(e[0][0])===3&&this._status!=="dirty"?[He,e[0]]:e;let r=!0,s=!1,o=!1,i=-1;for(let d of e){let u=n(d[0]);u<i&&(r=!1),u===3&&(s=!0),d[0]===X&&(o=!0),i=u}let a=e;if(!r){let d=e.map((u,l)=>({m:u,i:l,tier:n(u[0])}));d.sort((u,l)=>u.tier-l.tier||u.i-l.i),a=d.map(u=>u.m)}if(s&&!o&&this._status!=="dirty"){let d=0;for(;d<a.length&&n(a[d][0])===0;)d++;return d===0?[He,...a]:[...a.slice(0,d),He,...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]===L&&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 n=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(d=>d[0]===me||d[0]===Ee);if(a.length===0)return;n=a}n=this._frameBatch(n);let s=null;for(let a=0;a<n.length;a++){let d=n[a],u=d[0];if(u!==Se&&u!==Pe){s?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===Se?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let l=!0;if(this._pausable!==!1){let h=d[1];if(u===Se)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(h),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(h))l=!1;else if(this._pauseLocks.delete(h),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let c=this._pauseBuffer;this._pauseBuffer=[],this._emit(c)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}l?s?.push(d):s==null&&(s=n.slice(0,a))}if(s!=null){if(s.length===0)return;n=s}if(this._hasMeta&&n.some(a=>a[0]===me))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(wt)}catch{}let{finalMessages:o,equalsError:i}=this._updateState(n);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([[L,i]])}_updateState(e){let n=this._config.tierOf,r,s,o=-1,i=0;for(let l of e)n(l[0])===3&&i++;let a=i<=1,d=-1;if(this._versioning!=null&&i>1){for(let l=e.length-1;l>=0;l--)if(e[l][0]===I){d=l;break}}for(let l=0;l<e.length;l++){let h=e[l],c=h[0];if(c===I){if(h.length>=2){let p=!1;if(a&&this._cached!==void 0)try{p=this._equals(this._cached,h[1])}catch(f){s=this._wrapFnError("equals threw",f),o=l;break}if(p){r==null&&(r=e.slice(0,l)),r.push(vt),this._status="resolved";continue}this._cached=h[1],this._versioning!=null&&(d<0||l===d)&&Kn(this._versioning,h[1],this._hashFn)}this._status="settled",r?.push(h)}else if(r?.push(h),c===X)this._status="dirty";else if(c===Z)this._status="resolved";else if(c===j){this._status="completed";{let p=this._config.rigorRecorder;if(p!=null)try{p.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(c===L){this._status="errored";{let p=this._config.rigorRecorder;if(p!=null)try{p.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(c===Ee){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 p=this._cleanup;if(typeof p=="function"){this._cleanup=void 0;try{p()}catch{}}else if(p!=null&&typeof p=="object"){let f=p.invalidate;if(typeof f=="function")try{f()}catch{}}}else c===me&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=o>=0?r??e.slice(0,o):r??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 n=[...this._sinks];for(let r of n)r(e)};_dispatchOrAccumulate(e){if(Fn()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],dt(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}lt(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let n=this._frameBatch(e);lt(this._deliverToSinks,n,this._config.tierOf)}},Yn=t=>Array.isArray(t),un=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function V(t,e){return oe([],{...e,initial:t})}function he(t,e){return oe((r,s,o)=>t(s,o)??void 0,{describeKind:"producer",...e})}function G(t,e,n){return oe(t,(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",...n})}function ge(t,e,n){return oe(t,(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",...n})}var de=_e(()=>{"use strict";Ce()});function dn(t){return{describeKind:"producer",...t}}function Qn(t,e){return he(n=>{let r=!1;try{for(let s of t){if(r)return;n.emit(s)}r||n.down([[j]])}catch(s){r||n.down([[L,s]])}return()=>{r=!0}},dn(e))}function ao(t){return t!=null&&typeof t.then=="function"}function uo(t,e){let{signal:n,...r}=e??{};return he(s=>{let o=!1,i=()=>{o||(o=!0,s.down([[L,n.reason]]))};if(n?.aborted){i();return}return n?.addEventListener("abort",i,{once:!0}),Promise.resolve(t).then(a=>{o||(o=!0,n?.removeEventListener("abort",i),s.emit(a),s.down([[j]]))},a=>{o||(o=!0,n?.removeEventListener("abort",i),s.down([[L,a]]))}),()=>{o=!0,n?.removeEventListener("abort",i)}},dn(r))}function lo(t,e){let{signal:n,...r}=e??{};return he(s=>{let o=new AbortController,i=()=>o.abort(n?.reason);n?.aborted?o.abort(n.reason):n?.addEventListener("abort",i,{once:!0});let a=n??o.signal,d=!1,u=t[Symbol.asyncIterator](),l=()=>{d||a.aborted||Promise.resolve(u.next()).then(h=>{if(!(d||a.aborted)){if(h.done){s.down([[j]]);return}s.emit(h.value),l()}},h=>{!d&&!a.aborted&&s.down([[L,h]])})};return l(),()=>{d=!0,n?.removeEventListener("abort",i),o.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},dn(r))}function co(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function Ve(t,e){if(co(t))return t;if(ao(t))return uo(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return lo(t,e);if(typeof n[Symbol.iterator]=="function")return Qn(t,e)}return fo(t)}function fo(...t){return Qn(t,void 0)}function Xn(t,e){let n=new AbortController,r=e?.reason??new Error("cancelled via nodeSignal"),s,o=!1,i=()=>{s?(s(),s=void 0):o=!0};return s=t.subscribe(a=>{if(!n.signal.aborted)for(let d of a){if(d[0]===I&&d[1]===!0){n.abort(r),i();return}if(d[0]===L){n.abort(d[1]),i();return}if(d[0]===j){i();return}}}),o&&(s?.(),s=void 0),{signal:n.signal,dispose:()=>{s&&(s(),s=void 0)}}}function Te(t){return t.subscribe(()=>{})}var Ue=_e(()=>{"use strict";pe();de()});var Ct,er=_e(()=>{"use strict";Ct=class{_timer;_gen=0;start(e,n){this.cancel(),this._gen+=1;let r=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,r===this._gen&&n()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var Ys={};Wr(Ys,{DEFAULT_DECAY_RATE:()=>tt,DEFAULT_EXECUTE_PROMPT:()=>cn,DEFAULT_QUEUE_CONFIGS:()=>Ot,DEFAULT_SEVERITY_WEIGHTS:()=>et,DEFAULT_TRIAGE_PROMPT:()=>ln,DEFAULT_VERIFY_PROMPT:()=>fn,HarnessGraph:()=>Wt,QUEUE_NAMES:()=>xe,actuatorExecutor:()=>vo,affectedTaskFilter:()=>No,autoSolidify:()=>To,beforeAfterCompare:()=>Eo,codeChangeBridge:()=>Ro,createIntakeBridge:()=>xo,defaultErrorClassifier:()=>St,defaultLlmExecutor:()=>jr,defaultLlmVerifier:()=>zr,evalIntakeBridge:()=>wo,evalSource:()=>_o,evalVerifier:()=>Or,harnessEvalPair:()=>Ls,harnessLoop:()=>Hs,harnessProfile:()=>qs,harnessTrace:()=>Ws,notifyEffect:()=>ko,priorityScore:()=>zs,refineExecutor:()=>Nn,resolvePromptFn:()=>ft,strategyKey:()=>nt,strategyModel:()=>An});module.exports=Yr(Ys);pe();de();pe();Ce();de();Ue();function kt(t){return{describeKind:"derived",...t}}function po(t){return{describeKind:"derived",partial:!0,...t}}function $e(t,e,n){return oe([t],(r,s)=>{let o=r[0];if(o==null||o.length===0){s.down([[Z]]);return}let i=!1;for(let a of o)e(a)&&(s.emit(a),i=!0);i||s.down([[Z]])},kt(n))}function ct(t,e,n){return oe([t,e],(r,s,o)=>{let i=r[0],a=r[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([[Z]]);return}for(let u of i)s.emit([u,d])}else s.down([[Z]])},po(n))}function Zn(...t){return t.length===0?he(e=>{e.down([[j]])},kt()):he(e=>{let n=t.length,r=0,s=[];for(let o of t){let i=o.subscribe(a=>{for(let d of a)d[0]===I?e.emit(d[1]):d[0]===j?(r+=1,r>=n&&e.down([[j]])):d[0]===L&&e.down([d])});s.push(i)}return()=>{for(let o of s)o()}},kt())}function ho(t,e,n){let r,s=!1,o=()=>{s||(s=!0,n())};return r=t.subscribe(i=>{let a=!1,d=!1;for(let u of i)u[0]!==Le&&(u[0]===I?e.emit(u[1]):u[0]===j?a=!0:u[0]===L?(d=!0,e.down([u])):(u[0]===X||u[0]===Z)&&e.down([u]));d?(r?.(),r=void 0,o()):a&&o()}),()=>{r?.(),r=void 0}}function Re(t,e,n){let r,s=!1;function o(){r?.(),r=void 0}return oe([t],(i,a,d)=>{if(d.terminalDeps[0]!=null&&d.terminalDeps[0]!==!0){o();return}if(d.terminalDeps[0]===!0){s=!0,r||a.down([[j]]);return}let u=i[0];if(!(u==null||u.length===0))return o(),r=ho(Ve(e(u[u.length-1])),a,()=>{o(),s&&a.down([[j]])}),{deactivate:()=>{o(),s=!1}}},{...kt(n),completeWhenDepsComplete:!1})}Ue();function mo(t,e){return{outcome:"success",detail:`actuator applied ${e.intervention} for ${yo(e.summary)}`,artifact:t}}function go(t,e){let n=t instanceof Error?t.message:String(t);return{outcome:"failure",detail:`actuator threw on ${e.intervention}: ${n}`}}function bo(t){return`actuator skipped ${t.intervention} (shouldApply returned false)`}function yo(t,e=80){return t.length<=e?t:`${t.slice(0,e-1)}\u2026`}function vo(t){let e=t.name??"actuator-executor",n=t.toOutput??mo,r=t.onError??go,s=t.skipDetail??bo;return o=>{let i=$e(o,d=>d!=null,{name:`${e}/gate-in`}),a=Re(i,d=>t.shouldApply&&!t.shouldApply(d)?he(u=>(u.down([[I,{outcome:"failure",detail:s(d)}],[j]]),()=>{}),{name:`${e}/skip`}):he(u=>{let l=new AbortController,h=!1,c=null,p=g=>{h||(h=!0,u.down([[I,g],[j]]),c?.(),c=null)},f;try{let g=t.apply(d,{signal:l.signal});f=Ve(g,{signal:l.signal})}catch(g){return p(r(g,d)),()=>{l.abort()}}return c=f.subscribe(g=>{for(let b of g){if(h)return;if(b[0]===I){p(n(b[1],d));return}if(b[0]===L){p(r(b[1],d));return}if(b[0]===j){p(r(new Error("actuator inner completed without emitting DATA"),d));return}}}),h&&c&&(c(),c=null),()=>{l.abort(),c?.(),c=null}},{name:`${e}/inner`}),{name:e});return $e(a,d=>d!=null,{name:`${e}/gate-out`})}}pe();de();function To(t){let e=t.name??"auto-solidify",n=t.extract??(s=>s.execution.artifact??null),r=t.predicate??(()=>!0);return he(s=>{let o=null,i=!1,a=()=>{i||(i=!0,o?.(),o=null)},d=u=>{i||(s.down([[L,u]]),a())};return o=t.verifyResults.subscribe(u=>{if(!i)for(let l of u){if(i)return;if(l[0]!==I){if(l[0]===j){s.down([[j]]),a();return}continue}let h=l[1];if(h==null||!h.verified)continue;let c;try{c=r(h)}catch(f){d(f);return}if(!c)continue;let p;try{p=n(h)}catch(f){d(f);return}if(p!=null){try{t.write(p,h)}catch(f){d(f);return}s.down([[I,p]])}}}),i&&o&&(o(),o=null),()=>{a()}},{name:e})}de();Ue();function xo(t,e,n,r){return ge([t],([s])=>{if(s==null)return;let o=n(s);for(let i of o)e.publish(i)},{name:r?.name??"intake-bridge"})}function wo(t,e,n){let r=n?.defaultSeverity??"medium";return ge([t],([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:r});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:r})}},{name:n?.name??"eval-intake-bridge"})}function _o(t,e){return Re(t,()=>Ve(e()))}function Eo(t,e){return G([t,e],([n,r])=>{let s=n,o=r,i=new Map(s.tasks.map(c=>[c.task_id,c])),a=new Map(o.tasks.map(c=>[c.task_id,c])),d=new Set([...i.keys(),...a.keys()]),u=[],l=[],h=[];for(let c of d){let p=i.get(c),f=a.get(c),g=p?.valid??!1,b=f?.valid??!1,v=p?.judge_scores?p.judge_scores.filter(w=>w.pass).length:void 0,T=f?.judge_scores?f.judge_scores.filter(w=>w.pass).length:void 0,y=v!==void 0&&T!==void 0?T-v:void 0;u.push({taskId:c,before:g,after:b,scoreDiff:y}),g&&!b&&l.push(c),!g&&b&&h.push(c)}return{newFailures:l,resolved:h,taskDeltas:u,overallImproved:h.length>l.length}},{name:"eval-delta"})}function No(t,e){let n=e==null?null:Array.isArray(e)?V(e):e,r=[t];return n&&r.push(n),G(r,s=>{let o=s[0],i=n?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 Ro(t,e,n,r){let s=r?.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=n??o;return ge([t],([a])=>{if(a!=null)for(let d of i(a))e.publish(d)},{name:r?.name??"code-change-bridge"})}function ko(t,e,n){return ge([t.latest],([r])=>{r!=null&&e(r)},{name:n?.name??"notify-effect"})}var xe=["auto-fix","needs-decision","investigation","backlog"],Ot={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},et={critical:100,high:70,medium:40,low:10},tt=Math.LN2/(168*3600);function nt(t,e){return`${t}\u2192${e}`}var Oo=/\b(parse|json|config|validation|syntax)\b/i,St=t=>Oo.test(t.detail)?"self-correctable":"structural",ln=`You are a triage classifier for a reactive collaboration harness.
2
2
 
3
3
  Given an intake item, classify it and output JSON:
4
4
  {
@@ -39,12 +39,12 @@ Output JSON:
39
39
  "verified": true/false,
40
40
  "findings": ["<finding1>", ...],
41
41
  "errorClass": "self-correctable" | "structural" // only if verified=false
42
- }`;function ft(t,e,n){if(typeof t=="function")return t;let r=t??e;return s=>n(r,s)}de();de();De();Ae();pe();Ce();de();Et();De();Ae();Xe();pe();Xe();Ce();function At(t,e){if(e!=null&&e.length>0)return new Set(e);switch(t){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;default:return new Set(["type","deps"])}}function ko(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function Oo(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function pn(t,e){let n=e==null,r=!n&&e!=null?[...e].filter(u=>u.startsWith("meta.")).map(u=>u.slice(5)):null,s=n||e.has("meta")||r!=null&&r.length>0,o="state",i=[];t instanceof se&&(o=ko(t),i=t._deps.map(u=>u.node.name??""));let a={type:o,deps:i};(n||e.has("status"))&&(a.status=t.status);let d=t instanceof se?t._guard:void 0;if(s){let u={...Oo(t)};if(d!=null&&u.access===void 0&&(u.access=nn(d)),r!=null&&r.length>0&&!e.has("meta")){let l={};for(let h of r)h in u&&(l[h]=u[h]);a.meta=l}else a.meta=u}if(t.name!=null&&(a.name=t.name),n||e.has("value")){t.status==="sentinel"&&(a.sentinel=!0);try{a.value=t.cache}catch{}}if((n||e.has("v"))&&t.v!=null){let u={id:t.v.id,version:t.v.version};"cid"in t.v&&(u.cid=t.v.cid,u.prev=t.v.prev),a.v=u}return(n||e.has("guard"))&&d!=null&&(a.guard=nn(d)),(n||e.has("lastMutation"))&&t.lastMutation!=null&&(a.lastMutation=t.lastMutation),a}Ce();de();Ue();er();var pt=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 n=(this.head+this._size)%this.capacity;this.buf[n]=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 n=e<0?this._size+e:e;if(!(n<0||n>=this._size))return this.buf[(this.head+n)%this.capacity]}toArray(){let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this.buf[(this.head+n)%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}};tn();function hn(t){return t>=768&&t<=879||t>=1155&&t<=1161||t>=1425&&t<=1469||t>=1552&&t<=1562||t>=1611&&t<=1631||t>=1648&&t===1648||t>=1750&&t<=1756||t>=1759&&t<=1764||t>=1767&&t<=1768||t>=1770&&t<=1773||t>=1840&&t<=1866||t>=1958&&t<=1968||t>=2304&&t<=2307||t>=2362&&t<=2383||t>=2385&&t<=2391||t>=2402&&t<=2403||t>=2433&&t<=2435||t>=2492&&t<=2509||t>=2561&&t<=2563||t>=2620&&t<=2641||t>=2672&&t<=2673||t>=2677&&t===2677||t>=3633&&t===3633||t>=3636&&t<=3642||t>=3655&&t<=3662||t>=3761&&t===3761||t>=3764&&t<=3772||t>=3784&&t<=3790||t>=7616&&t<=7679||t>=8400&&t<=8447||t>=65024&&t<=65039||t>=65056&&t<=65071||t===8205?0:t>=4352&&t<=4447||t>=8986&&t<=8987||t>=9001&&t<=9002||t>=9193&&t<=9203||t>=9208&&t<=9210||t>=9725&&t<=9726||t>=9748&&t<=9749||t>=9800&&t<=9811||t===9855||t===9875||t===9889||t>=9898&&t<=9899||t>=9917&&t<=9918||t>=9924&&t<=9925||t===9934||t===9940||t===9962||t>=9970&&t<=9971||t===9973||t===9978||t===9981||t===9986||t===9989||t>=9992&&t<=9997||t===9999||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t>=10548&&t<=10549||t>=11013&&t<=11015||t>=11035&&t<=11036||t===11088||t===11093||t>=11904&&t<=12350||t>=12352&&t<=12447||t>=12448&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12784&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=19968&&t<=40959||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65131||t>=65281&&t<=65376||t>=65504&&t<=65510||t>=126980&&t===126980||t===127183||t>=127344&&t<=127345||t===127358||t===127359||t===127374||t>=127377&&t<=127386||t>=127456&&t<=127487||t>=127488&&t<=127490||t===127514||t===127535||t>=127538&&t<=127546||t>=127568&&t<=127569||t>=127744&&t<=129535||t>=129536&&t<=129791||t>=129792&&t<=130047||t>=131072&&t<=196605||t>=196608&&t<=262141?2:1}function It(t){let e=0;for(let n of t)e+=hn(n.codePointAt(0));return e}function tr(t,e){if(e<=0)return"";let n=0,r="";for(let s of t){let o=hn(s.codePointAt(0));if(n+o>e){if(e<=1)return"\u2026";for(;n+1>e&&r.length>0;){let i=[...r].pop();r=r.slice(0,-i.length),n-=hn(i.codePointAt(0))}return`${r}\u2026`}r+=s,n+=o}return r}var So={horizontal:"\u2500",vertical:"\u2502",cornerTL:"\u250C",cornerTR:"\u2510",cornerBL:"\u2514",cornerBR:"\u2518",tDown:"\u252C",tUp:"\u2534",tRight:"\u251C",tLeft:"\u2524",cross:"\u253C",arrowRight:"\u25B6",arrowDown:"\u25BC",arrowLeft:"\u25C0",arrowUp:"\u25B2",boxTL:"\u250C",boxTR:"\u2510",boxBL:"\u2514",boxBR:"\u2518",boxH:"\u2500",boxV:"\u2502"},Ao={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function sr(t,e){let n=e.charset==="ascii"?Ao:So,r=t.width,s=t.height,o=Array.from({length:s},()=>Array.from({length:r},()=>" ")),i=Array.from({length:s},()=>Array.from({length:r},()=>"empty"));for(let a of t.edges)Io(o,i,n,a);for(let a of t.boxes)Co(o,i,n,a,e.labelOf(a.id));return o.map(a=>Lo(a.join(""))).join(`
43
- `)}function Co(t,e,n,r,s){let{x:o,y:i,w:a,h:d}=r;if(a<2||d<2){d>0&&nr(t,e,o,i,a,s);return}Fe(t,e,o,i,n.boxTL);for(let l=o+1;l<o+a-1;l+=1)Fe(t,e,l,i,n.boxH);Fe(t,e,o+a-1,i,n.boxTR);for(let l=i+1;l<i+d-1;l+=1){Fe(t,e,o,l,n.boxV);for(let h=o+1;h<o+a-1;h+=1)ir(t,e,h,l," ","empty");Fe(t,e,o+a-1,l,n.boxV)}Fe(t,e,o,i+d-1,n.boxBL);for(let l=o+1;l<o+a-1;l+=1)Fe(t,e,l,i+d-1,n.boxH);Fe(t,e,o+a-1,i+d-1,n.boxBR);let u=i+Math.floor(d/2);nr(t,e,o+1,u,a-2,s)}function Fe(t,e,n,r,s){ir(t,e,n,r,s,s===" "?"empty":s==="\u2500"||s==="-"?"boxH":s==="\u2502"||s==="|"?"boxV":"boxCorner")}function ir(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=t[r];n<0||n>=i.length||(i[n]=s,e[r][n]=o)}function nr(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=n,a=s;for(let d of o){let u=It(d);if(u!==0){if(a<u)break;i>=0&&i<t[r].length&&(t[r][i]=d,e[r][i]="label",u===2&&i+1<t[r].length&&(t[r][i+1]="",e[r][i+1]="label")),i+=u,a-=u}}for(;a>0;)i>=0&&i<t[r].length&&(t[r][i]=" ",e[r][i]="empty"),i+=1,a-=1}function Io(t,e,n,r){let s=r.points;if(s.length<2)return;for(let d=0;d+1<s.length;d+=1)Mo(t,e,n,s[d],s[d+1]);for(let d=1;d+1<s.length;d+=1){let u=s[d-1],l=s[d],h=s[d+1],c=Do(u,l,h,n);c&&or(t,e,l.x,l.y,c,"edgeCorner")}let o=s[s.length-1],i=s[s.length-2],a=Go(i,o,n);a&&or(t,e,o.x,o.y,a,"arrow")}function Mo(t,e,n,r,s){if(!(r.x===s.x&&r.y===s.y)){if(r.y===s.y){let o=r.y,i=Math.min(r.x,s.x),a=Math.max(r.x,s.x);for(let d=i;d<=a;d+=1)rr(t,e,d,o,n,"h")}else if(r.x===s.x){let o=r.x,i=Math.min(r.y,s.y),a=Math.max(r.y,s.y);for(let d=i;d<=a;d+=1)rr(t,e,o,d,n,"v")}}}function rr(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];if(!(a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label")){if(a==="empty"){i[n]=o==="h"?s.horizontal:s.vertical,e[r][n]=o==="h"?"edgeH":"edgeV";return}if(a==="edgeH"&&o==="v"){i[n]=s.cross,e[r][n]="edgeCorner";return}if(a==="edgeV"&&o==="h"){i[n]=s.cross,e[r][n]="edgeCorner";return}}}function or(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label"||(i[n]=s,e[r][n]=o)}function Do(t,e,n,r){let s=t.y===e.y,o=e.y===n.y;if(s===o)return;if(s){let d=t.x<e.x,u=n.y>e.y;return d&&u?r.cornerTR:d&&!u?r.cornerBR:!d&&u?r.cornerTL:r.cornerBL}let i=t.y<e.y,a=n.x>e.x;return i&&a?r.cornerBL:i&&!a?r.cornerBR:!i&&a?r.cornerTL:r.cornerTR}function Go(t,e,n){if(e.x>t.x)return n.arrowRight;if(e.x<t.x)return n.arrowLeft;if(e.y>t.y)return n.arrowDown;if(e.y<t.y)return n.arrowUp}function Lo(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function dr(t){let e=Po(t);$o(e),Vo(e),Fo(e),jo(e,t);let n=Ho(e,t),{width:r,height:s}=qo(e),o=[];for(let i of e.layers)for(let a of i)a.isVirtual||o.push({id:a.id,layer:a.layer,order:a.order,x:a.x,y:a.y,w:a.w,h:a.h});return{boxes:o,edges:n,width:r,height:s}}function Po(t){let e=new Map;for(let s of t.nodes)e.set(s,{id:s,isVirtual:!1,layer:-1,order:0,x:0,y:0,w:t.widthCells(s),h:t.heightCells(s),in:[],out:[]});let n=[],r=0;for(let s of t.edges){if(s.from===s.to)continue;let o=e.get(s.from),i=e.get(s.to);if(!o||!i)continue;let a={chainId:r++,chainFrom:s.from,chainTo:s.to,fromId:s.from,toId:s.to,hopIndex:0,chainLen:1};o.out.push(a),i.in.push(a),n.push(a)}return{nodes:e,layers:[],hops:n}}function $o(t){let e=new Map;for(let o of t.nodes.values())e.set(o.id,o.in.length);let n=[];for(let o of t.nodes.values())(e.get(o.id)??0)===0&&(o.layer=0,n.push(o));let r=new Set,s=0;for(;s<n.length;){let o=n[s++];if(!r.has(o.id)){r.add(o.id);for(let i of o.out){let a=t.nodes.get(i.toId);a.layer=Math.max(a.layer,o.layer+1);let d=(e.get(a.id)??0)-1;e.set(a.id,d),d<=0&&n.push(a)}}}for(let o of t.nodes.values())o.layer<0&&(o.layer=0)}function Vo(t){let e=Math.max(0,...Array.from(t.nodes.values(),o=>o.layer)),n=Array.from({length:e+1},()=>[]);for(let o of t.nodes.values())n[o.layer].push(o);let r=[],s=0;for(let o of t.hops){let i=t.nodes.get(o.fromId),a=t.nodes.get(o.toId),d=a.layer-i.layer;if(d<=0){i.out=i.out.filter(h=>h!==o),a.in=a.in.filter(h=>h!==o);continue}if(d===1){o.hopIndex=0,o.chainLen=1,r.push(o);continue}i.out=i.out.filter(h=>h!==o),a.in=a.in.filter(h=>h!==o);let u=i;for(let h=1;h<d;h+=1){let c=`__virt_${s++}__`,p={id:c,isVirtual:!0,layer:i.layer+h,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(c,p),n[p.layer].push(p);let f={chainId:o.chainId,chainFrom:o.chainFrom,chainTo:o.chainTo,fromId:u.id,toId:c,hopIndex:h-1,chainLen:d};u.out.push(f),p.in.push(f),r.push(f),u=p}let l={chainId:o.chainId,chainFrom:o.chainFrom,chainTo:o.chainTo,fromId:u.id,toId:a.id,hopIndex:d-1,chainLen:d};u.out.push(l),a.in.push(l),r.push(l)}for(let o of n)for(let i=0;i<o.length;i+=1)o[i].order=i;t.layers=n,t.hops=r}function Fo(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)ar(t,t.layers[r],"in"),Mt(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)ar(t,t.layers[r],"out"),Mt(t.layers[r])}for(let n=0;n<2;n+=1){let r=!1;for(let s=1;s<t.layers.length;s+=1){let o=t.layers[s];for(let i=0;i+1<o.length;i+=1){let a=ur(t,o[i],o[i+1],"in");[o[i],o[i+1]]=[o[i+1],o[i]],Mt(o),ur(t,o[i],o[i+1],"in")<a?r=!0:([o[i],o[i+1]]=[o[i+1],o[i]],Mt(o))}}if(!r)break}}function ar(t,e,n){let r=new Map;for(let s of e){let o=n==="in"?s.in:s.out;if(o.length===0){r.set(s.id,s.order);continue}let i=0,a=0;for(let d of o){let u=t.nodes.get(n==="in"?d.fromId:d.toId);u&&(i+=u.order,a+=1)}r.set(s.id,a===0?s.order:i/a)}e.sort((s,o)=>{let i=r.get(s.id),a=r.get(o.id);return i!==a?i-a:s.order-o.order})}function Mt(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function ur(t,e,n,r){let s=r==="in"?e.in:e.out,o=r==="in"?n.in:n.out,i=0;for(let a of s)for(let d of o){let u=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,l=t.nodes.get(r==="in"?d.fromId:d.toId)?.order??0;(e.order<n.order&&u>l||e.order>n.order&&u<l)&&(i+=1)}return i}function jo(t,e){e.direction==="LR"?zo(t,e):Bo(t,e)}function zo(t,e){let n=[],r=0;for(let s=0;s<t.layers.length;s+=1){n.push(r);let o=0;for(let i of t.layers[s])o=Math.max(o,i.w);r+=o+e.layerGap}for(let s=0;s<t.layers.length;s+=1)for(let o of t.layers[s])o.x=n[s];for(let s of t.layers){let o=0;for(let i of s)i.y=o,o+=i.h+e.nodeGap}lr(t,e,"y")}function Bo(t,e){let n=[],r=0;for(let s=0;s<t.layers.length;s+=1){n.push(r);let o=0;for(let i of t.layers[s])o=Math.max(o,i.h);r+=o+e.layerGap}for(let s=0;s<t.layers.length;s+=1)for(let o of t.layers[s])o.y=n[s];for(let s of t.layers){let o=0;for(let i of s)i.x=o,o+=i.w+e.nodeGap}lr(t,e,"x")}function lr(t,e,n){let r=o=>n==="y"?o.h:o.w,s=e.nodeGap;for(let o=0;o<2;o+=1){let i=o===0?t.layers.slice(1):t.layers.slice(0,-1).reverse();for(let a of i){let d=new Map;for(let l of a){let h=o===0?l.in:l.out;if(h.length===0)continue;let c=[];for(let f of h){let g=t.nodes.get(o===0?f.fromId:f.toId);if(!g)continue;let b=n==="y"?g.y:g.x;c.push(b+Math.floor(r(g)/2))}if(c.length===0)continue;c.sort((f,g)=>f-g);let p=c[Math.floor(c.length/2)];d.set(l.id,p-Math.floor(r(l)/2))}let u=0;for(let l of a){let h=d.get(l.id),c=n==="y"?l.y:l.x,f=Math.max(h??c,u);n==="y"?l.y=f:l.x=f,u=f+r(l)+s}}}}function Ho(t,e){let n=new Map;for(let u of t.hops){let l=n.get(u.chainId);l?l.push(u):n.set(u.chainId,[u])}for(let u of n.values())u.sort((l,h)=>l.hopIndex-h.hopIndex);let r=e.direction==="LR",s=u=>r?u.x:u.y,o=u=>r?u.w:u.h,i=u=>r?u.y+Math.floor(u.h/2):u.x+Math.floor(u.w/2),a=new Map;for(let u=0;u+1<t.layers.length;u+=1){let l=t.layers[u],h=t.layers[u+1],c=0;for(let T of l)c=Math.max(c,s(T)+o(T));let p=Number.POSITIVE_INFINITY;for(let T of h)p=Math.min(p,s(T));let f=Number.isFinite(p)?p-1:c,g=Math.max(1,f-c+1),b=[];for(let T of l)for(let E of T.out)b.push(E);b.sort((T,E)=>{let A=i(t.nodes.get(T.fromId)),k=i(t.nodes.get(E.fromId));if(A!==k)return A-k;let S=i(t.nodes.get(T.toId)),C=i(t.nodes.get(E.toId));return S-C});let y=[],x=new Map;for(let T of b){let E=i(t.nodes.get(T.fromId)),A=i(t.nodes.get(T.toId)),k=Math.min(E,A),S=Math.max(E,A),C=-1;for(let B=0;B<y.length;B+=1){let Y=y[B],W=!0;for(let ye of Y)if(ye.lo<=S&&k<=ye.hi){W=!1;break}if(W){Y.push({lo:k,hi:S}),C=B;break}}C<0&&(y.push([{lo:k,hi:S}]),C=y.length-1),x.set(T,C)}let v=y.length,w=g>=Math.max(3,v+2),R=w?c+1:c,_=w?f-1:f,m=Math.max(1,_-R+1);for(let T of b){let E=x.get(T),A;if(v<=1)A=R+Math.floor(m/2);else{let k=(m-1)/(v-1);A=R+Math.floor(E*k)}a.set(T,Math.max(c,Math.min(f,A)))}}let d=[];for(let[,u]of n){let l=[];for(let c=0;c<u.length;c+=1){let p=u[c],f=t.nodes.get(p.fromId),g=t.nodes.get(p.toId),b=a.get(p),y=f.isVirtual?s(f):s(f)+o(f),x=g.isVirtual?s(g):s(g)-1,v=i(f),w=i(g);c===0&&Dt(l,r,y,v),v!==w&&(Dt(l,r,b,v),Dt(l,r,b,w)),Dt(l,r,x,w)}let h=u[0];d.push({from:h.chainFrom,to:h.chainTo,points:Ko(l)})}return d}function Dt(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function Ko(t){let e=[];for(let n of t){let r=e[e.length-1];(!r||r.x!==n.x||r.y!==n.y)&&e.push(n)}return e}function qo(t){let e=0,n=0;for(let r of t.layers)for(let s of r)e=Math.max(e,s.x+s.w),n=Math.max(n,s.y+s.h);return{width:e,height:n}}var Uo=24,Wo=4,Jo=1,Yo=3;function cr(t,e){let n=Qo(e.direction),r=Math.max(3,e.maxLabelWidth??Uo),s=e.asciiCharset??"unicode",o=Object.keys(t.nodes).sort(),i=new Set(o),a=t.edges.filter(p=>i.has(p.from)&&i.has(p.to)),d=new Map,u=new Map;for(let p of o){let f=tr(p,r);d.set(p,f),u.set(p,It(f)+4)}let l=dr({nodes:o,edges:a,widthCells:p=>u.get(p)??3,heightCells:()=>Yo,layerGap:Wo,nodeGap:Jo,direction:n}),h=sr(l,{charset:s,labelOf:p=>d.get(p)??p}),c=e.logger;return c&&c(h),h}function Qo(t){if(t===void 0||t==="LR")return"LR";if(t==="TD")return"TD";throw new Error(`ascii describe supports direction "LR" or "TD" only; got ${String(t)}`)}function fr(t,e,n,r={}){let s=e in t.nodes,o=n in t.nodes;if(!s)return Gt(e,n,"no-such-from");if(!o)return Gt(e,n,"no-such-to");let i=r.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===n){if(r.findCycle===!0){let u=Xo(t,e,r);if(u!=null)return u}let d=Lt(e,t.nodes[e],0,r);return Pt(e,n,[d])}if(i===0)return Gt(e,n,"no-path");let a=pr(t,e,n,i);return a.found?Pt(e,n,hr(t,a.pathOrder,r)):Gt(e,n,a.truncated?"max-depth-exceeded":"no-path")}function pr(t,e,n,r){let s=new Map,o=[{path:n,depth:0}],i=new Set([n]),a=0,d=!1;for(;a<o.length;){let h=o[a++];if(h.path===e)break;if(r!=null&&h.depth>=r){let g=t.nodes[h.path];g?.deps&&g.deps.length>0&&(d=!0);continue}let c=t.nodes[h.path];if(c==null)continue;let p=c.deps??[],f=new Map;for(let g=0;g<p.length;g++){let b=p[g];if(!b)continue;let y=f.get(b);y==null&&(y=[],f.set(b,y)),y.push(g)}for(let[g,b]of f)i.has(g)||(i.add(g),s.set(g,{from:h.path,depIndices:b}),o.push({path:g,depth:h.depth+1}))}if(!s.has(e))return{found:!1,pathOrder:[],truncated:d};let u=[{path:e}],l=e;for(;l!==n;){let h=s.get(l);if(h==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=h.depIndices,u.push({path:h.from}),l=h.from}return{found:!0,pathOrder:u,truncated:!1}}function Xo(t,e,n){let r=t.nodes[e];if(r==null)return null;let s=r.deps??[],o=[];for(let a=0;a<s.length;a++)s[a]===e&&o.push(a);if(o.length>0){let a=Lt(e,r,0,n);a.dep_index=o[0];let d=Lt(e,r,1,n);return Pt(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=pr(t,d,e,n.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:Pt(e,e,hr(t,i.pathOrder,n))}function hr(t,e,n){return e.map((r,s)=>{let o=t.nodes[r.path],i=Lt(r.path,o,s,n);return r.depIndices!=null&&r.depIndices.length>0&&(i.dep_index=r.depIndices[0],r.depIndices.length>1&&(i.dep_indices=[...r.depIndices])),i})}function Lt(t,e,n,r){let s={path:t,type:e.type,hop:n};e.status!==void 0&&(s.status=e.status),"value"in e&&(s.value=e.value),e.v!=null&&(s.v=e.v);let o=r.annotations?.get(t)??e.annotation;o!=null&&(s.annotation=o);let i=r.lastMutations?.get(t)??e.lastMutation;return i!=null&&(s.lastMutation=i),s}function Pt(t,e,n){return mr(t,e,!0,"ok",n)}function Gt(t,e,n){return mr(t,e,!1,n,[])}function mr(t,e,n,r,s){let o=Zo(t,e,n,r,s);return{from:t,to:e,found:n,reason:r,steps:s,text:o,toJSON(){return{from:t,to:e,found:n,reason:r,steps:s}}}}function Zo(t,e,n,r,s){if(!n)switch(r){case"no-such-from":return`explainPath: no node named "${t}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${t}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${t}" to "${e}"`}let o=[`Causal path: ${t} \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: ${es(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(`
44
- `)}function es(t){if(t===void 0)return"<sentinel>";if(t===null)return"null";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return e.length>80?`${e.slice(0,77)}...`:e}catch{return String(t)}}Ce();var ie={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},ts=Symbol.for("sizeof");function gr(t){let e=new WeakSet,n=new WeakSet,r=[t],s=0;for(;r.length>0;){let o=r.pop();s+=ns(o,e,n,r)}return s}function ns(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return ie.number;case"boolean":return ie.boolean;case"string":return ie.string+t.length*2;case"bigint":return ie.bigint+rs(t);case"symbol":return ie.symbol;case"function":return e.has(t)?0:(e.add(t),ie.function);case"undefined":return 0}let o=t;if(e.has(o))return 0;e.add(o);let i=o[ts];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 ie.date;if(o instanceof RegExp)return ie.regexp+o.source.length*2;if(o instanceof Error){let u=o.message?o.message.length*2:0,l=o.stack?o.stack.length*2:0;return ie.error+u+l}if(typeof URL<"u"&&o instanceof URL)return ie.url+o.href.length*2;if(typeof Promise<"u"&&o instanceof Promise)return ie.promise;if(o instanceof WeakMap)return ie.weakmap;if(o instanceof WeakSet)return ie.weakset;if(o instanceof Map){let u=ie.map;for(let[l,h]of o)u+=ie.mapEntry,r.push(l),r.push(h);return u}if(o instanceof Set){let u=ie.set;for(let l of o)u+=ie.setEntry,r.push(l);return u}if(Array.isArray(o)){let u=ie.array+o.length*8;for(let l of o)r.push(l);return u}if(o instanceof ArrayBuffer)return n.has(o)?0:(n.add(o),o.byteLength);if(ArrayBuffer.isView(o)){let u=o;return n.has(u.buffer)?48:(n.add(u.buffer),u.buffer.byteLength+48)}let a=ie.object,d=Object.keys(o);for(let u of d){a+=ie.string+u.length*2;try{r.push(o[u])}catch{}}return a}function rs(t){let e=t<0n?-t:t;if(e===0n)return 0;let n=e.toString(2).length;return Math.ceil(n/32)*8}function $t(t,e){let n=e?.topN??10,r=t.describe({detail:"standard"}),s=[],o=t._collectObserveTargets;typeof o=="function"&&o.call(t,"",s);let i=new Map;for(let[c,p]of s)i.set(c,p);let a=[];for(let[c,p]of Object.entries(r.nodes)){let f=i.get(c),g=f instanceof se?f:null,b=g?gr(g.cache):0,y=g?g._sinkCount:0,x=p.deps?.length??0,v=p.type==="effect"&&y===0,w=y===0?p.type==="effect"?"orphan-effect":p.type==="derived"?"idle-derived":p.type==="producer"?"idle-producer":null:null;a.push({path:c,type:p.type,status:p.status??"unknown",valueSizeBytes:b,subscriberCount:y,depCount:x,isOrphanEffect:v,orphanKind:w})}let d=a.reduce((c,p)=>c+p.valueSizeBytes,0),u=(c,p)=>[...a].sort(p??((f,g)=>g[c]-f[c])).slice(0,n),l=a.filter(c=>c.orphanKind!=null),h=a.filter(c=>c.isOrphanEffect);return{nodeCount:a.length,edgeCount:r.edges.length,subgraphCount:r.subgraphs.length,nodes:a,totalValueSizeBytes:d,hotspots:{byValueSize:u("valueSizeBytes"),bySubscriberCount:u("subscriberCount"),byDepCount:u("depCount")},orphans:l,orphanEffects:h}}var te="::",ke="__meta__",We=1;function br(t,e){let n=Math.max(16,t.size*4),r=0;for(;t.size>0;){if(r++>=n){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${n}); ${t.size} disposer(s) discarded`),t.clear();return}let s=t.values().next();if(s.done)return;let o=s.value;t.delete(o);try{o()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function os(t){let e=[];for(let n of Object.keys(t).sort()){let r=t[n].v;r!=null&&e.push(`${n} ${r.id} ${r.version}`)}return e.join(`
45
- `)}function yr(t){if(t.version!==We)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${We})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in t))throw new Error(`snapshot missing required key "${e}"`);if(typeof t.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof t.nodes!="object"||t.nodes===null||Array.isArray(t.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(t.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(t.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function ss(t,e){let n=new WeakMap,r=(s,o)=>{if(Object.is(s,o))return!0;if(s==null||o==null||typeof s!="object"||typeof o!="object")return!1;let i=n.get(s);if(i==null&&(i=new WeakSet,n.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 c=o;if(s.length!==c.length)return!1;for(let p=0;p<s.length;p++)if(!r(s[p],c[p]))return!1;return!0}if(s instanceof Map){let c=o;if(s.size!==c.size)return!1;for(let[p,f]of s)if(!c.has(p)||!r(f,c.get(p)))return!1;return!0}if(s instanceof Set){let c=o;if(s.size!==c.size)return!1;for(let p of s){let f=!1;for(let g of c)if(r(p,g)){f=!0;break}if(!f)return!1}return!0}if(ArrayBuffer.isView(s)){let c=s,p=o;if(c.length!==p.length)return!1;for(let f=0;f<c.length;f++)if(c[f]!==p[f])return!1;return!0}let u=Object.keys(s),l=Object.keys(o);if(u.length!==l.length)return!1;let h=new Set(l);for(let c of u)if(!h.has(c)||!r(s[c],o[c]))return!1;return!0};return r(t,e)}function gn(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(gn);let e=t,n=Object.keys(e).sort(),r={};for(let s of n)r[s]=gn(e[s]);return r}function is(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function as(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function us(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function Tr(t){let e=new Set,n=[];function r(s,o){let i=`${s}\0${o}`;e.has(i)||(e.add(i),n.push([s,o]))}for(let[s,o]of Object.entries(t.nodes)){let i=o.deps;if(i)for(let a of i)r(a,s)}for(let s of t.edges)r(s.from,s.to);return n}function xr(t){if(t===void 0)return"LR";if(t==="TD"||t==="LR"||t==="BT"||t==="RL")return t;throw new Error(`invalid diagram direction ${String(t)}; expected one of: TD, LR, BT, RL`)}function ds(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,{expand:s,...o}=t,i={...o,edges:n?t.edges:[],subgraphs:r?t.subgraphs:[]},a=JSON.stringify(gn(i),null,e.indent??2);return e.logger?.(a),a}function ls(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,s=[];s.push(`Graph ${t.name}`),s.push("Nodes:");for(let i of Object.keys(t.nodes).sort()){let a=t.nodes[i];s.push(`- ${i} (${a.type}/${a.status}): ${Ft(a.value)}`)}if(n){s.push("Edges:");for(let i of t.edges)s.push(`- ${i.from} -> ${i.to}`)}if(r){s.push("Subgraphs:");for(let i of t.subgraphs)s.push(`- ${i}`)}let o=s.join(`
46
- `);return e.logger?.(o),o}function wr(t,e){let n=xr(e.direction),r=Object.keys(t.nodes).sort(),s=new Map;for(let i=0;i<r.length;i+=1)s.set(r[i],`n${i}`);let o=[`flowchart ${n}`];for(let i of r){let a=s.get(i);o.push(` ${a}["${is(i)}"]`)}for(let[i,a]of Tr(t)){let d=s.get(i),u=s.get(a);!d||!u||o.push(` ${d} --> ${u}`)}return o.join(`
47
- `)}function cs(t,e){let n=wr(t,e);return _r(n)}function _r(t,e){let n=e?.theme??"default",r=e?.autoSync??!0,o=JSON.stringify({code:t,mermaid:{theme:n},autoSync:r}),i=new TextEncoder().encode(o),a="";for(let u=0;u<i.length;u++)a+=String.fromCharCode(i[u]);return`https://mermaid.live/edit#base64:${globalThis.btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function fs(t,e){let n=xr(e.direction),r=Object.keys(t.nodes).sort(),s=new Map;for(let i=0;i<r.length;i+=1)s.set(r[i],`n${i}`);let o=[`direction: ${us(n)}`];for(let i of r){let a=s.get(i);o.push(`${a}: "${as(i)}"`)}for(let[i,a]of Tr(t)){let d=s.get(i),u=s.get(a);!d||!u||o.push(`${d} -> ${u}`)}return o.join(`
48
- `)}function ps(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Vt(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){e+=".*";continue}if(r==="?"){e+=".";continue}if(r==="["){let s=t.indexOf("]",n+1);if(s<=n+1){e+="\\[";continue}let o=t.slice(n+1,s);o.startsWith("!")&&(o=`^${o.slice(1)}`),o=o.replace(/\\/g,"\\\\"),e+=`[${o}]`,n=s;continue}e+=ps(r)}return e+="$",new RegExp(e)}var hs={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"},ms={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function Ft(t){if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||t==null)return String(t);try{return JSON.stringify(t)}catch{return"[unserializable]"}}function gs(t){return t==="none"?ms:t==="ansi"||t==null?hs:{data:t.data??"",dirty:t.dirty??"",resolved:t.resolved??"",invalidate:t.invalidate??"",pause:t.pause??"",resume:t.resume??"",complete:t.complete??"",error:t.error??"",teardown:t.teardown??"",derived:t.derived??"",path:t.path??"",reset:t.reset??""}}function vr(t){if(t==null)return{};let e=t.detail;return e==="full"?{...t,structured:t.structured??!0,timeline:t.timeline??!0,causal:t.causal??!0,derived:t.derived??!0}:e==="minimal"?{...t,structured:t.structured??!0}:t.format==="stage-log"?{...t,structured:t.structured??!0,timeline:t.timeline??!0}:t}function bs(t,e,n){for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);if(s<32||s===127)throw new Error(`Graph "${e}": ${n} "${t}" must not contain control character (U+${s.toString(16).padStart(4,"0").toUpperCase()} at index ${r})`)}}function mn(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(te))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${te}' (path separator)`);if(t===ke)throw new Error(`Graph "${e}": ${n} name "${ke}" is reserved for meta companion paths`);bs(t,e,n)}function ys(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(te);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function vs(t,e){let n=!1;for(let s of t)if(!e.isMetaPassthrough(s[0])){n=!0;break}return n?t.filter(s=>e.isMetaPassthrough(s[0])):t}function Er(t){for(let e of t._mounts.values())Er(e);for(let e of t._nodes.values())try{e.down([[ge]],{internal:!0})}catch{}}var ce=class t{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;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(te))throw new Error(`Graph name must not contain '${te}' (got "${e}")`);if(e===ke)throw new Error(`Graph name "${ke}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??Ze,this._traceRing=new pt(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning)}ancestors(e=!0){let n=[],r=e?this:this._parent;for(;r!=null;)n.push(r),r=r._parent;return n}get topology(){return this._topology==null&&(this._topology=he(e=>{let n=r=>{e.emit(r)};return this._topologyEmitters.add(n),()=>{this._topologyEmitters.delete(n)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let n of this._topologyEmitters)n(e)}nameOf(e){return this._nodeToName.get(e)}add(e,n){let r=e.name,s=n?.name??r;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=n?.annotation;if(mn(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:ee()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof se&&n._applyVersioning(e)}remove(e){mn(e,this.name,"remove");let n=this._mounts.get(e);if(n){let o={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,d]of i)a.includes(`${te}${ke}${te}`)||o.nodes.push(a);return o.nodes.sort(),o.mounts.push(e),o.mounts.push(...n._collectSubgraphs(`${e}${te}`)),this._mounts.delete(e),n._parent=void 0,Er(n),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:o}),o}let r=this._nodes.get(e);if(!r)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(r),r.down([[ge]],{internal:!0});let s={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:s}),s}removeAll(e){let n=typeof e=="function"?e:(()=>{let o=Vt(e);return i=>o.test(i)})(),r={kind:"mount",nodes:[],mounts:[]},s=[...this._nodes.keys(),...this._mounts.keys()].filter(o=>n(o));for(let o of s){let i=this.remove(o);r.nodes.push(...i.nodes),r.mounts.push(...i.mounts)}return r.nodes.sort(),r.mounts.sort(),r}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),n=this._nodes,r=0;return{[Symbol.iterator](){return this},next(){if(r>=e.length)return{value:void 0,done:!0};let s=e[r++];return{value:[s,n.get(s)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(te))return this.resolve(e);let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return n}get(e){return this.node(e).cache}set(e,n,r){let s=r?.internal===!0;this.node(e).down([[M,n]],{actor:r?.actor,internal:s,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);re(()=>{for(let[s,o]of r)this.set(s,o,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[Ee]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let s=r?.internal===!0;this.node(e).down([[P,n]],{actor:r?.actor,internal:s,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[j]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[d,u]of this._nodes)r.set(u,d);let a=[];for(let[d,u]of this._nodes)if(u instanceof se)for(let l of u._deps){let h=r.get(l.node);h!=null&&a.push([h,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 se)for(let u of d._deps){let l=o.get(u.node);l!=null&&i.push([l,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,n){if(n===void 0){let s=new t(e);return this.mount(e,s)}if(typeof n=="function"){let s=new t(e);return n(s),this.mount(e,s)}let r=n;if(mn(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(r===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(r._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${r._parent.name}"`);for(let s=this;s!=null;s=s._parent)if(s===r)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,r),r._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),r}resolve(e){let n=ys(e,this.name);return this._resolveFromSegments(n)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let n=e;if(n[0]===this.name&&(n=n.slice(1),n.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let r=n[0],s=n.slice(1);if(s.length===0){let a=this._nodes.get(r);if(a)return a;throw this._mounts.has(r)?new Error(`Graph "${this.name}": path ends at subgraph "${r}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${r}"`)}let o=this._nodes.get(r);if(o&&s.length>0&&s[0]===ke)return this._resolveMetaChainFromNode(o,s,n.join(te));let i=this._mounts.get(r);if(!i)throw this._nodes.has(r)?new Error(`Graph "${this.name}": "${r}" is a node; trailing path "${s.join(te)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(s.join(te))}_resolveMetaChainFromNode(e,n,r){let s=e,o=0,i=[...n];for(;o<i.length;){if(i[o]!==ke)throw new Error(`Graph "${this.name}": expected ${ke} segment in meta path "${r}"`);if(o+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${ke} in "${r}"`);let a=i[o+1],d=s.meta[a];if(!d)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);s=d,o+=2}return s}signal(e,n){if(n?.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 r=[];if(this._signalDeliver(e,n??{},new Set,r),r.length>0)throw r[0]}_signalDeliver(e,n,r,s){for(let d of this._mounts.values())d._signalDeliver(e,n,r,s);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=vs(e,this.config);for(let d of[...this._nodes.keys()].sort()){let u=this._nodes.get(d);if(!r.has(u)){r.add(u);try{u.down(e,i)}catch(l){if(l instanceof Ne)throw l;s.push(l)}a.length!==0&&this._signalMetaSubtree(u,a,r,i,s)}}}_signalMetaSubtree(e,n,r,s,o){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!r.has(a)){r.add(a);try{a.down(n,s)}catch(d){if(d instanceof Ne)throw d;o.push(d)}this._signalMetaSubtree(a,n,r,s,o)}}}describe(e){if(e?.reactive===!0)return this._describeReactive(e);let n=e?.actor,r=e?.filter,s=At(e?.detail,e?.fields),o=e?.format==="spec",i=o?At("minimal"):s,a=[];this._collectObserveTargets("",a);let d=new Map;for(let[_,m]of a)d.set(m,_);let u=[];{let _=a.map(([,E])=>E),m=new Set(d.values()),T=0;for(;_.length>0;){let E=_.shift();if(E instanceof se)for(let A of E._deps){let k=A.node;if(d.has(k))continue;let S=k.name??"",C=S;if(!C||m.has(C))if(S){let B=2;for(;m.has(`${S}#${B}`);)B++;C=`${S}#${B}`}else for(C=`__internal__/${T++}`;m.has(C);)C=`__internal__/${T++}`;d.set(k,C),m.add(C),u.push([C,k]),_.push(k)}}}let l=[...a,...u],h={};for(let[_,m]of l){if(n!=null&&!m.allowsObserve(n))continue;let T=pn(m,i),E=m instanceof se?m._deps.map(C=>d.get(C.node)??C.node.name??""):[],{name:A,...k}=T,S={...k,deps:E};if(!o){let C=this._annotations.get(_);C!=null&&(S.annotation=C)}if(r!=null)if(typeof r=="function"){let C=r;if(!(C.length>=2?C(_,S):C(S)))continue}else{let C=!0;for(let[B,Y]of Object.entries(r)){let W=B==="deps_includes"?"depsIncludes":B==="meta_has"?"metaHas":B;if(W==="depsIncludes"){if(!S.deps.includes(String(Y))){C=!1;break}continue}if(W==="metaHas"){if(!Object.hasOwn(S.meta??{},String(Y))){C=!1;break}continue}if(S[W]!==Y){C=!1;break}}if(!C)continue}h[_]=S}let c=new Set(Object.keys(h)),p=[];for(let[_,m]of l)if(m instanceof se)for(let T of m._deps){let E=d.get(T.node);E!=null&&p.push([E,_])}p.sort((_,m)=>_[0]<m[0]?-1:_[0]>m[0]?1:_[1]<m[1]?-1:_[1]>m[1]?1:0);let f=p.map(([_,m])=>({from:_,to:m}));(n!=null||r!=null)&&(f=f.filter(_=>c.has(_.from)&&c.has(_.to)));let g=this._collectSubgraphs(""),b=n!=null||r!=null?g.filter(_=>{let m=`${_}${te}`;return[...c].some(T=>T===_||T.startsWith(m))}):g,y=this,x=e,v={name:this.name,nodes:h,edges:f,subgraphs:b,expand(_){let m={...x,format:void 0};return Array.isArray(_)?(m.fields=_,m.detail=void 0):(m.detail=_,m.fields=void 0),y.describe(m)}},w=e??{},R=w.format;return R==="json"?ds(v,w):R==="pretty"?ls(v,w):R==="mermaid"?wr(v,w):R==="mermaid-url"?cs(v,w):R==="d2"?fs(v,w):R==="ascii"?cr(v,w):v}_collectSubgraphs(e){let n=[];for(let r of[...this._mounts.keys()].sort()){let s=e===""?r:`${e}${r}`;n.push(s),n.push(...this._mounts.get(r)._collectSubgraphs(`${s}${te}`))}return n}resourceProfile(e){return $t(this,e)}reachable(e,n,r={}){return r.withDetail===!0?bn(this.describe(),e,n,{...r,withDetail:!0}):bn(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(e,n,r)}_explainStatic(e,n,r){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 fr(s,e,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:o,lastMutations:i})}_describeReactive(e){let n={...e,reactive:!1},r=e.reactiveName??"describe",s=0,o=V(s,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,dt(()=>{a=!1,!d&&(s+=1,o.emit(s))}))},l=i.onEvent(b=>{let y=b.type;y!=="data"&&y!=="error"&&y!=="complete"&&y!=="teardown"||u()}),h=[],c=new WeakSet,p=b=>{if(c.has(b)||d)return;c.add(b);let y=b.topology.subscribe(x=>{for(let v of x){if(v[0]!==M)continue;let w=v[1];if(u(),w.kind==="added"&&w.nodeKind==="mount"){let R=b._mounts.get(w.name);R!=null&&p(R)}}});h.push(y);for(let x of b._mounts.keys()){let v=b._mounts.get(x);v!=null&&p(v)}};p(this);let f;try{f=G([o],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(b,y)=>b===y})}catch(b){l();for(let y of h)y();throw i.dispose(),b}let g=Te(f);return{node:f,dispose(){d=!0,l();for(let b of h)b();h.length=0,i.dispose(),g()}}}_explainReactive(e,n,r){let s=0,o=V(s,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=i.onEvent(p=>{let f=p.type;f!=="data"&&f!=="error"&&f!=="complete"&&f!=="teardown"||a||d||(a=!0,dt(()=>{a=!1,!d&&(s+=1,o.emit(s))}))}),l={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},h;try{h=G([o],()=>this._explainStatic(e,n,l),{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:e,to:n},equals:(p,f)=>p.found===f.found&&p.reason===f.reason&&p.steps.length===f.steps.length&&Ts(p.steps,f.steps)})}catch(p){throw u(),i.dispose(),p}let c=Te(h);return{node:h,dispose(){d=!0,u(),i.dispose(),c()}}}_pathsMatching(e){let n=Vt(e),r=[];return this._collectObserveTargets("",r),r.map(([s])=>s).filter(s=>n.test(s))}_collectObserveTargets(e,n){for(let r of[...this._mounts.keys()].sort()){let s=e===""?r:`${e}${te}${r}`;this._mounts.get(r)._collectObserveTargets(s,n)}for(let r of[...this._nodes.keys()].sort()){let s=this._nodes.get(r),o=e===""?r:`${e}${te}${r}`;n.push([o,s]),this._appendMetaObserveTargets(o,s,n)}}_appendMetaObserveTargets(e,n,r){for(let s of Object.keys(n.meta).sort()){let o=n.meta[s],i=`${e}${te}${ke}${te}${s}`;r.push([i,o]),this._appendMetaObserveTargets(i,o,r)}}observe(e,n){let r=typeof e=="string",o=vr(r?n:e),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(r){let l=e,h=this.resolve(l);if(a!=null&&!h.allowsObserve(a))throw new Ne({actor:a,action:"observe",nodeName:l});return i?this._buildStructuredObserver([[l,h]],o,"one"):{subscribe(c){return h.subscribe(c)},up(c){try{h.up?.(c)}catch(p){if(p instanceof Ne)return;throw p}}}}let d=[];this._collectObserveTargets("",d),d.sort((l,h)=>l[0]<h[0]?-1:l[0]>h[0]?1:0);let u=a==null?d:d.filter(([,l])=>l.allowsObserve(a));return i?this._buildStructuredObserver(u,o,"all"):{subscribe:l=>{let h=u.map(([c,p])=>p.subscribe(f=>{l(c,f)}));return()=>{for(let c of h)c()}},up:(l,h)=>{try{this.resolve(l).up?.(h)}catch(c){if(c instanceof Ne)return;throw c}}}}_buildStructuredObserver(e,n,r){let s=r==="one"?e[0]?.[0]:void 0,o=i=>{if(r==="one"&&s!=null){let l=this.resolve(s);return this._buildStructuredObserver([[s,l]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((l,h)=>l[0]<h[0]?-1:l[0]>h[0]?1:0);let d=i.actor,u=d==null?a:a.filter(([,l])=>l.allowsObserve(d));return this._buildStructuredObserver(u,i,"all")};return this._createObserveResult(e,n,o)}_createObserveResult(e,n,r){let s=n.timeline===!0,o=n.causal===!0,i=n.derived===!0,a=n.detail==="minimal",d=this.config.inspectorEnabled,u=(o||i)&&d,l=n.maxEvents,h=l!=null&&l>0?new pt(l):null,c=[],p=new Set,f={},g=new Set,b=0,y=0,x=0,v=0,w=0,R=0,_=!1,m=!1,T=0,E=new Map,A=new Map,k=new Map,S=O=>{h?h.push(O):c.push(O);for(let z of p)z(O)},C=()=>s?{timestamp_ns:ee(),in_batch:ut(),batch_id:T}:{},B=(O,z)=>{if(!(!u||!(O instanceof se)))return O._setInspectorHook(ae=>{if(ae.kind==="dep_message")E.set(O,ae.depIndex);else if(ae.kind==="run"){let Ie=ae.batchData.map((q,ue)=>q!=null&&q.length>0?q.at(-1):ae.prevData[ue]);A.set(O,Ie);let fe=ae.batchData.map(q=>q!=null?[...q]:void 0);k.set(O,fe),i&&S({type:"derived",path:z,dep_values:Ie,dep_batches:fe,...C()})}})},Y=O=>{let z=E.get(O),ae=A.get(O);if(!o||ae==null)return{};let fe=(z!=null&&z>=0&&O instanceof se?O._deps[z]:void 0)?.node,q=fe?.v,ue=k.get(O);return{trigger_dep_index:z,trigger_dep_name:fe?.name,...q!=null?{trigger_version:{id:q.id,version:q.version}}:{},dep_values:[...ae],...ue!=null?{dep_batches:ue}:{}}},W=[],ye=[];for(let[O,z]of e){let ae=B(z,O);ae&&W.push(ae),ye.push(z.subscribe(Ie=>{T++;for(let fe of Ie){let q=fe[0],ue=C();if(q===M){f[O]=fe[1];let D=z instanceof se?z.lastMutation?.actor??Je:Je;S({type:"data",path:O,data:fe[1],actor:D,...ue,...Y(z)})}else if(a)q===X?b++:q===Z?y++:q===Ee?x++:q===Se?v++:q===Pe?w++:q===ge?R++:q===j&&!g.has(O)?_=!0:q===P&&(m=!0,g.add(O));else if(q===X)b++,S({type:"dirty",path:O,...ue});else if(q===Z)y++,S({type:"resolved",path:O,...ue,...Y(z)});else if(q===Ee)x++,S({type:"invalidate",path:O,...ue});else if(q===Se)v++,S({type:"pause",path:O,lockId:fe[1],...ue});else if(q===Pe)w++,S({type:"resume",path:O,lockId:fe[1],...ue});else if(q===j)g.has(O)||(_=!0),S({type:"complete",path:O,...ue});else if(q===P){m=!0,g.add(O);let D=z instanceof se?z.lastMutation?.actor??Je:Je;S({type:"error",path:O,data:fe[1],actor:D,...ue})}else q===ge&&(R++,S({type:"teardown",path:O,...ue}))}}))}let Oe=!1,$=()=>{if(!Oe){Oe=!0;for(let O of ye)O();for(let O of W)O();for(let O of L)O({value:void 0,done:!0});L.length=0}},F=[],L=[];p.add(O=>{let z=L.shift();z?z({value:O,done:!1}):F.push(O)});let le={get values(){return f},get dirtyCount(){return b},get resolvedCount(){return y},get invalidateCount(){return x},get pauseCount(){return v},get resumeCount(){return w},get teardownCount(){return R},get events(){return h?h.toArray():[...c]},get anyCompletedCleanly(){return _},get anyErrored(){return m},get completedWithoutErrors(){return _&&!m},onEvent(O){return p.add(O),()=>p.delete(O)},dispose:$,expand(O){$();let z={...n};return typeof O=="string"?z.detail=O:Object.assign(z,O),r(vr(z))},[Symbol.asyncIterator](){return{next(){return F.length>0?Promise.resolve({value:F.shift(),done:!1}):Oe?Promise.resolve({value:void 0,done:!0}):new Promise(O=>L.push(O))},return(){return $(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(le,n),le}_attachFormatLogger(e,n){let r=n.format;if(r==null)return;let s=n.logger??(f=>console.log(f)),o=n.includeTypes?new Set(n.includeTypes):null,i=n.excludeTypes?new Set(n.excludeTypes):null,a=o==null&&i==null?()=>!0:f=>(o==null||o.has(f))&&(i==null||!i.has(f)),d=gs(n.theme),u=r==="stage-log"?ee():0,l=f=>f==null?"":n.stageLabels?.[f]??f,h=(f,g)=>f.length>g?`${f.slice(0,g-1)}\u2026`:f,c=f=>f.type==="data"||f.type==="error"?h(Ft(f.data),120):"",p=f=>{if(r==="stage-log"){let m=(ee()-u)/1e9,T=l(f.path).padEnd(9);if(f.type==="data"){let E=c(f);return`[${m.toFixed(3)}s] ${T} \u2190${E?` ${E}`:""}`}if(f.type==="error"){let E=c(f);return`[${m.toFixed(3)}s] ${T} \u2717${E?` ${E}`:""}`}return f.type==="complete"?`[${m.toFixed(3)}s] ${T} \u25A0 complete`:`[${m.toFixed(3)}s] ${T} ${f.type}`}if(r==="json")try{return JSON.stringify(f)}catch{return JSON.stringify({type:f.type,path:f.path,data:"[unserializable]"})}let g=d[f.type]??"",b=f.path?`${d.path}${f.path}${d.reset} `:"",y=f.type==="data"||f.type==="error",x=f.type==="pause"||f.type==="resume",v=y?` ${Ft(f.data)}`:x?` ${Ft(f.lockId)}`:"",w=f.type==="data"||f.type==="resolved"||f.type==="derived"?f:void 0,R=w?.trigger_dep_name!=null?` <- ${w.trigger_dep_name}`:w?.trigger_dep_index!=null?` <- #${w.trigger_dep_index}`:"",_=f.in_batch?" [batch]":"";return`${b}${g}${f.type.toUpperCase()}${d.reset}${v}${R}${_}`};e.onEvent(f=>{a(f.type)&&s(p(f),f)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){br(this._disposers,this.name),this.signal([[ge]],{internal:!0}),br(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:n,...r}=this.describe({detail:"full"}),s={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:d,guard:u,...l}=r.nodes[a];s[a]=l}let o=[...r.subgraphs].sort(),i={...r,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 Pn(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??Ze,{codec:s,codecVersion:o,payload:i}=$n(e,r);return s.decode(i,o)}restore(e,n){if(yr(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let r=n?.only==null?null:(Array.isArray(n.only)?n.only:[n.only]).map(o=>Vt(o)),s=n?.includeProducers===!0;for(let o of Object.keys(e.nodes).sort()){if(r!==null&&!r.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&&n?.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){n?.onError?.(o,a)}}}}}static fromSnapshot(e,n){yr(e);let r=typeof n=="function"?n:n?.build,s=typeof n=="function"?void 0:n?.factories,o=new t(e.name);if(r)return r(o),o.restore(e),o;for(let p of[...e.subgraphs].sort((f,g)=>{let b=f.split(te).length,y=g.split(te).length;return b!==y?b-y:f<g?-1:f>g?1:0})){let f=p.split(te),g=o;for(let b of f)g._mounts.has(b)||g.mount(b,new t(b)),g=g._mounts.get(b)}let i=s?Object.entries(s).map(([p,f])=>({re:Vt(p),factory:f})):[],a=p=>{for(let f of i)if(f.re.test(p))return f.factory},d=p=>{let f=p.split(te),g=f.pop();if(g==null||g.length===0)throw new Error(`invalid snapshot path "${p}"`);let b=o;for(let y of f){let x=b._mounts.get(y);if(!x)throw new Error(`unknown mount "${y}" in path "${p}"`);b=x}return[b,g]},u=Object.entries(e.nodes).filter(([p])=>!p.includes(`${te}${ke}${te}`)).sort((p,f)=>p[0]<f[0]?-1:p[0]>f[0]?1:0),l=new Map(u),h=new Map,c=!0;for(;l.size>0&&c;){c=!1;for(let[p,f]of[...l.entries()]){let g=f?.deps??[];if(!g.every(R=>h.has(R)))continue;let[b,y]=d(p),x={...f?.meta??{}},v=a(p),w;if(f?.type==="state")w=V(f.value,{meta:x});else{if(v==null)continue;w=v(y,{path:p,type:f.type,value:f.value,meta:x,deps:g,resolvedDeps:g.map(R=>h.get(R))})}b.add(w,{name:y}),h.set(p,w),l.delete(p),c=!0}}if(l.size>0){let p=[...l.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${p}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return o.restore(e),o}toJSON(){return this.snapshot()}attachSnapshotStorage(e,n={}){let r=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}));n.autoRestore===!0&&this._cascadeRestore(e,n.onError);let s=(u,l)=>{if(u.disposed)return;let h=os(l.nodes);if(u.lastSnapshot!=null&&h!==""&&h===u.lastFingerprint)return;let c=u.seq+1,p=be(),b=u.lastSnapshot==null||c%u.compactEvery===0?{name:this.name,mode:"full",snapshot:l,seq:c,timestamp_ns:p,format_version:We}:{name:this.name,mode:"diff",diff:Nr(u.lastSnapshot,l),seq:c,timestamp_ns:p,format_version:We};if(u.tier.filter&&!u.tier.filter(b))return;let y;try{y=u.tier.save(b)}catch(x){n.onError?.(x,u.tier);return}if(y&&typeof y.then=="function"){let w=(u.savePending??Promise.resolve()).then(()=>y,()=>y).then(()=>{u.disposed||(u.seq=c,u.lastSnapshot=l,u.lastFingerprint=h)},R=>{n.onError?.(R,u.tier)});u.savePending=w.finally(()=>{u.savePending===w&&(u.savePending=void 0)})}else u.seq=c,u.lastSnapshot=l,u.lastFingerprint=h},o=(u,l)=>{try{s(u,l)}catch(h){n.onError?.(h,u.tier)}},i=(u,l)=>{if(!l.some(f=>{let g=this.config.messageTier(f[0]);return g>=3&&g<5}))return;if(n.filter){let f=this.tryResolve(u);if(f==null)return;let g=pn(f,At("standard"));if(!n.filter(u,g))return}let c,p=()=>(c==null&&(c=this.snapshot()),c);for(let f of r)f.disposed||(f.debounceMs===0?o(f,p()):(f.timer==null&&(f.timer=new Ct),f.timer.start(f.debounceMs,()=>{f.disposed||o(f,this.snapshot())})))},a;if(n.paths!=null){let l=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(h=>{let c=this.tryResolve(h);return c==null?()=>{}:c.subscribe(p=>i(h,p))});a=()=>{for(let h of l)h()}}else a=this.observe().subscribe((u,l)=>i(u,l));let d=()=>{a();for(let u of r)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(d)};return this._storageDisposers.add(d),{dispose:d}}async _cascadeRestore(e,n){for(let r of e){let s;try{s=await r.load?.()}catch(i){n?.(i,r);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===We&&o.nodes!=null)return this.restore(o),!0}catch(i){n?.(i,r)}}return!1}static async fromStorage(e,n,r){for(let s of n){let o;try{o=await s.load?.()}catch(d){r?.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===We&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(d){r?.onError?.(d,s)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${n.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,n,r){if(e!=null&&n!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,n),this.config.inspectorEnabled){let s={path:e,annotation:n,timestamp_ns:ee(),...r?.actor!=null?{actor:r.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 n=this._traceRing.toArray().filter(s=>!e(s)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let s of n)this._traceRing.push(s);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),s=new Set(Object.keys(n.nodes)),o=[...s].filter(x=>!r.has(x)).sort(),i=[...r].filter(x=>!s.has(x)).sort(),a=[],d=[];for(let x of r){if(!s.has(x))continue;let v=e.nodes[x],w=n.nodes[x],R=v.v,_=w.v;R!=null&&_!=null&&R.id===_.id&&R.version!==_.version&&d.push({path:x,id:R.id,from:R.version,to:_.version});let m=R!=null&&_!=null&&R.id===_.id&&R.version===_.version;for(let T of["type","status","sentinel"]){let E=v[T],A=w[T];E!==A&&a.push({path:x,field:T,from:E,to:A})}if(!m)for(let T of["value","meta"]){let E=v[T],A=w[T];ss(E,A)||a.push({path:x,field:T,from:E,to:A})}}let u=x=>`${x.from} ${x.to}`,l=new Set(e.edges.map(u)),h=new Set(n.edges.map(u)),c=n.edges.filter(x=>!l.has(u(x))),p=e.edges.filter(x=>!h.has(u(x))),f=new Set(e.subgraphs),g=new Set(n.subgraphs),b=[...g].filter(x=>!f.has(x)).sort(),y=[...f].filter(x=>!g.has(x)).sort();return{nodesAdded:o,nodesRemoved:i,nodesChanged:a,versionChanges:d,edgesAdded:c,edgesRemoved:p,subgraphsAdded:b,subgraphsRemoved:y}}};function Nr(t,e){let n=ce.diff(t,e),r={};for(let s of n.nodesAdded){let o=e.nodes[s];o!=null&&(r[s]=o)}return{...n,nodesAddedFull:r}}function bn(t,e,n,r={}){let s={paths:[],depths:new Map,truncated:!1};if(!e)return r.withDetail?s:[];if(!r.both&&n!=="upstream"&&n!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let o=r.maxDepth;if(o!=null&&(!Number.isInteger(o)||o<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(o===0)return r.withDetail?s:[];let i=new Map,a=new Map,d=new Map,u=new Map,l=new Set;for(let[v,w]of Object.entries(t.nodes)){if(!v)continue;l.add(v);let R=w.deps??[];i.set(v,R);for(let _ of R)_&&(l.add(_),a.has(_)||a.set(_,new Set),a.get(_).add(v))}for(let v of t.edges){if(v==null||typeof v!="object")continue;let w=typeof v.from=="string"?v.from:"",R=typeof v.to=="string"?v.to:"";!w||!R||(l.add(w),l.add(R),u.has(w)||u.set(w,new Set),u.get(w).add(R),d.has(R)||d.set(R,new Set),d.get(R).add(w))}if(!l.has(e))return r.withDetail?s:[];let h=r.both===!0,c=v=>{if(h){let m=i.get(v)??[],T=d.get(v),E=a.get(v),A=u.get(v),k=[...m];return T&&k.push(...T),E&&k.push(...E),A&&k.push(...A),k}if(n==="upstream"){let m=i.get(v)??[],T=d.get(v);return T?[...m,...T]:m}let w=a.get(v),R=u.get(v),_=w?[...w]:[];return R&&_.push(...R),_},p=new Set([e]),f=new Map,g=[{path:e,depth:0}],b=0,y=!1;for(;b<g.length;){let v=g[b++];if(o!=null&&v.depth>=o){c(v.path).length>0&&(y=!0);continue}for(let w of c(v.path))!w||p.has(w)||(p.add(w),f.set(w,v.depth+1),g.push({path:w,depth:v.depth+1}))}let x=[...f.keys()].sort((v,w)=>v<w?-1:v>w?1:0);return r.withDetail?{paths:x,depths:f,truncated:y}:x}function Ts(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],s=e[n];if(r.path!==s.path||r.type!==s.type||r.status!==s.status||r.hop!==s.hop||r.dep_index!==s.dep_index||r.annotation!==s.annotation||r.value!==s.value||r.lastMutation!==s.lastMutation)return!1;let o=r.v,i=s.v;if(o!==i&&(o==null||i==null||o.id!==i.id||o.version!==i.version))return!1}return!0}Et();De();Xe();pe();de();Ce();De();pe();Ce();de();var yn=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,n){if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=n,n!==void 0){if(this._buf=new Array(n),e&&e.length>0){let r=Math.min(e.length,n),s=e.length-r;for(let o=0;o<r;o++)this._buf[o]=e[s+o];this._size=r}}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 n=e>=0?e:this._size+e;if(!(n<0||n>=this._size))return this._maxSize!==void 0?this._buf[(this._head+n)%this._maxSize]:this._buf[n]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let r=n;r<e.length;r++)this._rawAppend(e[r]);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 n=0;n<e;n++)this._buf[(this._head+n)%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 n=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,n);else{for(let r=0;r<n;r++)this._buf[(this._head+r)%this._maxSize]=void 0;this._head=(this._head+n)%this._maxSize}return this._size-=n,this._version+=1,n}slice(e,n){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${n})`);let r=n===void 0?this._size:Math.min(Math.max(n,0),this._size),s=Math.min(e,this._size);if(s>=r)return[];let o=r-s;if(this._maxSize===void 0)return this._buf.slice(s,r);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 n=Math.min(e,this._size);return this.slice(this._size-n,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this._buf[(this._head+n)%this._maxSize];return e}snapshot(){return this.toArray()}restore(e){if(this._maxSize===void 0){this._buf.length=0;for(let n=0;n<e.length;n++)this._buf.push(e[n]);this._size=this._buf.length}else{let n=this._maxSize;for(let o=0;o<n;o++)this._buf[o]=void 0;this._head=0;let r=Math.min(e.length,n),s=e.length-r;for(let o=0;o<r;o++)this._buf[o]=e[s+o];this._size=r}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 ht(t){return t.subscribe(()=>{})}var xs=64;function jt(t,e={}){let{name:n,maxSize:r,versioning:s,guard:o,backend:i}=e,a=i??new yn(t,r),d=V(a.toArray(),{name:n,describeKind:"state",equals:(m,T)=>m===T,...s!=null?{versioning:s}:{},...o!=null?{guard:o}:{}});function u(){let m=a.toArray();re(()=>{d.down([[X]],{internal:!0}),d.down([[M,m]],{internal:!0})})}let l=new Map,h=new Map,c=new Map;function p(m,T){return`${m}:${T===void 0?"END":T}`}function f(m){if(m.size<xs)return;let T=m.keys().next();if(T.done)return;let E=m.get(T.value);E!==void 0&&E.dispose(),m.delete(T.value)}function g(m){let T=a.version;try{return m()}finally{a.version!==T&&u()}}function b(m){if(!Number.isInteger(m)||m<0)throw new RangeError(`tail: n must be a non-negative integer (got ${m})`);let T=l.get(m);if(T!==void 0)return l.delete(m),l.set(m,T),T.node;f(l);let E=G([d],([k])=>{let S=k;return m===0||S.length===0?[]:S.slice(Math.max(0,S.length-m))},{initial:a.tail(m),describeKind:"derived"}),A=ht(E);return l.set(m,{node:E,dispose:A}),E}function y(m,T){if(!Number.isInteger(m)||m<0)throw new RangeError(`slice: start must be a non-negative integer (got ${m})`);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 E=p(m,T),A=h.get(E);if(A!==void 0)return h.delete(E),h.set(E,A),A.node;f(h);let k=G([d],([C])=>{let B=C;return T===void 0?B.slice(m):B.slice(m,T)},{initial:a.slice(m,T),describeKind:"derived"}),S=ht(k);return h.set(E,{node:k,dispose:S}),k}function x(m){let T=c.get(m);if(T!==void 0)return T.node;let E=G([d,m],([k,S])=>{let C=k,B=Math.max(0,Math.trunc(S??0));return C.slice(B)},{initial:[],describeKind:"derived"}),A=ht(E);return c.set(m,{node:E,dispose:A}),E}let v,w;function R(){v===void 0&&(v=oe([d],(m,T,E)=>{let A=m[0],S=A!=null&&A.length>0?A.at(-1):E.prevData[0];if(S==null||S.length===0){T.down([[Z]]);return}T.emit(S[S.length-1])},{name:n!=null?`${n}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),w=G([d],([m])=>m.length>0,{name:n!=null?`${n}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),ht(v),ht(w))}let _={entries:d,get size(){return a.size},at(m){return a.at(m)},append(m){g(()=>a.append(m))},appendMany(m){m.length!==0&&g(()=>a.appendMany(m))},clear(){g(()=>a.clear())},trimHead(m){g(()=>a.trimHead(m))},withLatest(){return R(),d},get lastValue(){return R(),v},get hasLatest(){return R(),w},view(m){switch(m.kind){case"tail":return b(m.n);case"slice":return y(m.start,m.stop);case"fromCursor":return x(m.cursor)}},attach(m){let T=m.subscribe(E=>{for(let A of E)A[0]===M&&_.append(A[1])});return()=>T()},attachStorage(m){if(m.length===0)return()=>{};let T=new Map;for(let A of m)T.set(A,a.size);(async()=>{for(let A of m)if(typeof A.loadEntries=="function")try{let k=await Promise.resolve(A.loadEntries());k.entries.length>0&&a.size===0&&(a.restore(k.entries),T.set(A,k.entries.length),u());break}catch{}})();let E=d.subscribe(A=>{for(let k of A){if(k[0]!==M)continue;let S=k[1];for(let C of m){let B=T.get(C)??0;if(S.length<B){try{let W=C.appendEntries(S);W instanceof Promise&&W.catch(()=>{})}catch{}T.set(C,S.length);continue}if(S.length===B)continue;let Y=S.slice(B);T.set(C,S.length);try{let W=C.appendEntries(Y);W instanceof Promise&&W.catch(()=>{})}catch{}}}});return()=>E()},disposeAllViews(){for(let m of l.values())m.dispose();l.clear();for(let m of h.values())m.dispose();h.clear();for(let m of c.values())m.dispose();c.clear()},dispose(){for(let m of l.values())m.dispose();l.clear();for(let m of h.values())m.dispose();h.clear();for(let m of c.values())m.dispose();c.clear()}};return _}pe();Ue();function vn(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[X],[M,n+1]]),!0)}function je(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function mt(t){return t.relatedTo?.[0]??t.summary}var ws=256;function rt(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function ze(t,e){return je("messaging",t,e)}var _s=1024,Tn=class extends ce{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=jt([],{name:"events",maxSize:n.retainedLimit??_s}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=G([this.events],([r])=>{let s=r;return s.length===0?null:s[s.length-1]},{name:"latest",describeKind:"derived",meta:ze("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(Te(this.latest)),this.hasLatest=G([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:ze("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(Te(this.hasLatest)),this.addDisposer(()=>{this.events.down([[j]])}),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}},zt=class extends ce{cursor;available;topic;_disposed=!1;constructor(e,n,r={}){super(e,r.graph),this.topic=n;let s;if(r.from!==void 0?r.from==="retained"?s=0:r.from==="now"?s=n.events.cache.length:s=rt(r.from,"subscription from"):s=rt(r.cursor??0,"subscription cursor"),this.cursor=V(s,{name:"cursor",describeKind:"state",meta:ze("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=n._logBundle.view({kind:"fromCursor",cursor:this.cursor}),this.add(this.available,{name:"available"}),this.addDisposer(Te(this.available)),r.advanceOn!==void 0){let o=r.advanceOn,i=!1,a=oe([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:ze("subscription_advance_pump")});this.add(a,{name:"advancePump"}),this.addDisposer(Te(a))}}ack(e){if(this._disposed)return this.cursor.cache;let n=this.available.cache,r=e===void 0?n.length:rt(e,"subscription ack count"),s=Math.min(r,n.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 n=this.available.cache,r=e===void 0?n.length:rt(e,"subscription pull limit");return n.slice(0,r)}pullAndAck(e){if(this._disposed)return{items:[],cursor:this.cursor.cache};let n=this.available.cache,r=e===void 0?n.length:rt(e,"subscription pullAndAck limit"),s=n.slice(0,r);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([[j]]),this.destroy())}},xn=class extends ce{_sourceSub;bridgedCount;output;constructor(e,n,r,s={}){super(e,s.graph),this._sourceSub=Ns(`${e}-subscription`,n,{cursor:s.cursor}),this.mount("subscription",this._sourceSub);let o=Math.max(1,rt(s.maxPerPump??ws,"topic bridge maxPerPump")),i=s.map??(c=>c);this.output=G([this._sourceSub.available],([c])=>{let p=c,f=[],g=Math.min(p.length,o);for(let b=0;b<g;b++){let y=i(p[b]);y!==void 0&&f.push(y)}return f},{name:"output",describeKind:"derived",meta:ze("topic_bridge_output",{targetRef:r.name}),initial:[]}),this.add(this.output,{name:"output"}),this.addDisposer(Te(this.output)),this.bridgedCount=V(0,{name:"bridgedCount",describeKind:"state",meta:ze("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"}),this.addDisposer(Te(this.bridgedCount));let a=this.output,d=this._sourceSub,u=this.bridgedCount,l=oe([a],()=>{let c=a.cache;if(c.length===0)return;let p=d.available.cache.length,f=Math.min(p,o);if(f>0){d.ack(f);let g=u.cache??0;u.emit(g+c.length)}},{name:"ackPump",describeKind:"effect",meta:ze("topic_bridge_ack_pump")});this.add(l,{name:"ackPump"}),this.addDisposer(Te(l));let h=Es(this.output,r);this.addDisposer(h)}};function Es(t,e){return t.subscribe(n=>{for(let r of n){if(r[0]!==M)continue;let s=r[1];s.length!==0&&re(()=>{for(let o of s)e.publish(o)})}})}var wn=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,n){this._map.set(e,n)}delete(e){return this._map.delete(e)}keys(){return this._map.keys()}},_n=class extends ce{_registry;version;_defaultTopicOptions;constructor(e,n={}){super(e,n.graph);let r=V(0,{name:"version",describeKind:"state",meta:ze("hub_version")});this.add(r,{name:"version"}),this.version=r,this._registry=new wn(r),this._defaultTopicOptions={...n.defaultTopicOptions??{}}}get size(){return this._registry.size}has(e){return this._registry.has(e)}topicNames(){return this._registry.keys()}topic(e,n){let r=this._registry.get(e);if(r===void 0){let s={...this._defaultTopicOptions,...n??{}};r=new Tn(e,s),this._registry.set(e,r),this.mount(e,r);let o=this.version.cache??0;this.version.emit(o+1)}return r}publish(e,n){this.topic(e).publish(n)}publishMany(e){re(()=>{for(let[n,r]of e)this.topic(n).publish(r)})}subscribe(e,n,r){let s=this.topic(n);return new zt(e,s,r)}removeTopic(e){if(!this._registry.has(e))return!1;try{this.remove(e)}finally{this._registry.delete(e);let n=this.version.cache??0;this.version.emit(n+1)}return!0}};function Bt(t,e){return new _n(t,e)}function Ns(t,e,n){return new zt(t,e,n)}function En(t,e,n,r){return new xn(t,e,n,r)}function Rs(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.subscribe=="function"&&typeof e.down=="function"&&typeof e.emit=="function"}function ks(t,e){if(t.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(t.length===1){let o=Os(e);return{best:t[0],bestScore:o}}if(e.some(o=>typeof o.candidateIndex=="number")){let o=new Array(t.length);for(let d=0;d<t.length;d++)o[d]={sum:0,count:0};for(let d of e){let u=d.candidateIndex;typeof u=="number"&&u>=0&&u<t.length&&(o[u].sum+=d.score,o[u].count+=1)}let i=t[0],a=o[0].count>0?o[0].sum/o[0].count:Number.NEGATIVE_INFINITY;for(let d=1;d<t.length;d++){let u=o[d].count>0?o[d].sum/o[d].count:Number.NEGATIVE_INFINITY;u>a&&(a=u,i=t[d])}return{best:i,bestScore:a}}let r=t[0],s=e[0]?.score??Number.NEGATIVE_INFINITY;for(let o=1;o<t.length;o++){let i=e[o]?.score??Number.NEGATIVE_INFINITY;i>s&&(s=i,r=t[o])}return{best:r,bestScore:s}}function Os(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function Rr(t,e,n,r){let s=r.name??"refine-loop",o=new ce(s,r.graph),i=Rs(r.dataset)?r.dataset:V(r.dataset,{name:"dataset"});o.add(i,{name:"dataset"});let a=V(0,{name:"iteration"});o.add(a,{name:"iteration"});let d=V(n,{name:"strategy",equals:()=>!1});o.add(d,{name:"strategy"});let u=V(null,{name:"lastFeedback"});o.add(u,{name:"lastFeedback"});let l=V([],{name:"prevCandidates"});o.add(l,{name:"prevCandidates"});let h=V(!1,{name:"paused"});o.add(h,{name:"paused"});let c=V("running",{name:"status"});o.add(c,{name:"status"});let p=V([],{name:"history",equals:()=>!1});o.add(p,{name:"history"});let f=V(null,{name:"best"});o.add(f,{name:"best"});let g=V(Number.NEGATIVE_INFINITY,{name:"score"});o.add(g,{name:"score"});let b=V(0,{name:"budget-used"});o.add(b,{name:"budget-used"});let y=Bt("stages");o.mount("stages",y);let x=y.topic("generate"),v=y.topic("evaluate"),w=y.topic("analyze"),R=y.topic("decide"),_=n,m=null,T=[];o.addDisposer(d.subscribe(D=>{for(let K of D)K[0]===M&&(_=K[1])})),o.addDisposer(u.subscribe(D=>{for(let K of D)K[0]===M&&(m=K[1])})),o.addDisposer(l.subscribe(D=>{for(let K of D)K[0]===M&&(T=K[1])}));let E=Re(a,D=>{let K=_,ne=D===0||m==null;return oe([],(H,N)=>{let I=!1;try{let U=ne?K.seed(t):K.generate(m,T);if(U instanceof Promise)return U.then(J=>{I||N.emit(J)},J=>{I||N.down([[P,J]])}),()=>{I=!0};N.emit(U)}catch(U){I=!0,N.down([[P,U]])}},{describeKind:"producer"})},{name:"candidates"});o.add(E,{name:"candidates"});let A=me([E],(D,K,ne)=>{let H=ne.terminalDeps[0];H!==void 0&&H!==!0&&c.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});o.add(A,{name:"error-watcher"}),o.addDisposer(A.subscribe(()=>{}));let k=G([E,a],([D,K])=>({iteration:K,candidates:D,timestamp_ns:ee()}),{name:"generate-event"});o.add(k,{name:"generate-event"}),o.addDisposer(k.subscribe(()=>{}));let S=me([k],([D])=>{x.publish(D)},{name:"generate-publish"});o.add(S,{name:"generate-publish"}),o.addDisposer(S.subscribe(()=>{}));let C=me([E],([D])=>{l.emit(D)},{name:"generate-mirror"});o.add(C,{name:"generate-mirror"}),o.addDisposer(C.subscribe(()=>{}));let B=e(E,i);o.add(B,{name:"scores"});let Y=G([B,E,a],([D,K,ne])=>({iteration:ne,candidates:K,scores:D,timestamp_ns:ee()}),{name:"evaluate-event"});o.add(Y,{name:"evaluate-event"}),o.addDisposer(Y.subscribe(()=>{}));let W=me([Y],([D])=>{v.publish(D)},{name:"evaluate-publish"});o.add(W,{name:"evaluate-publish"}),o.addDisposer(W.subscribe(()=>{}));let ye=G([B,E],([D,K])=>_.analyze(D,K),{name:"feedback"});o.add(ye,{name:"feedback"});let Oe=G([ye,E,a],([D,K,ne])=>({iteration:ne,candidates:K,feedback:D,timestamp_ns:ee()}),{name:"analyze-event"});o.add(Oe,{name:"analyze-event"}),o.addDisposer(Oe.subscribe(()=>{}));let $=me([Oe],([D])=>{w.publish(D)},{name:"analyze-publish"});o.add($,{name:"analyze-publish"}),o.addDisposer($.subscribe(()=>{}));let F=G([p],([D])=>{let K=D;if(r.patience==null||K.length<=r.patience)return!1;let ne=K.slice(-(r.patience+1)),H=ne[0].bestScore;return ne.slice(1).every(N=>N.bestScore<=H)},{name:"patience-check"});o.add(F,{name:"patience-check"});let L=G([g],([D])=>r.minScore!=null&&D>=r.minScore,{name:"min-score-check"});o.add(L,{name:"min-score-check"});let le=G([p],([D])=>{let K=D;if(r.minDelta==null||K.length<2)return!1;let ne=K[K.length-2].bestScore,H=K[K.length-1].bestScore;return Math.abs(H-ne)<r.minDelta},{name:"min-delta-check"});o.add(le,{name:"min-delta-check"});let O=G([b],([D])=>r.maxEvaluations!=null&&D>=r.maxEvaluations,{name:"max-evaluations-check"});o.add(O,{name:"max-evaluations-check"});let z=G([a],([D])=>r.maxIterations!=null&&D>=r.maxIterations,{name:"max-iterations-check"});o.add(z,{name:"max-iterations-check"});let ae=G([b],([D])=>r.budget!=null&&D>=r.budget,{name:"budget-exhausted-check"});o.add(ae,{name:"budget-exhausted-check"}),o.addDisposer(F.subscribe(()=>{})),o.addDisposer(L.subscribe(()=>{})),o.addDisposer(le.subscribe(()=>{})),o.addDisposer(O.subscribe(()=>{})),o.addDisposer(z.subscribe(()=>{})),o.addDisposer(ae.subscribe(()=>{}));let Ie=G([F,L,le,O,z],([D,K,ne,H,N])=>D?{converged:!0,reason:"patience"}:K?{converged:!0,reason:"min-score"}:ne?{converged:!0,reason:"min-delta"}:H?{converged:!0,reason:"max-evaluations"}:N?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});o.add(Ie,{name:"converged"}),o.addDisposer(Ie.subscribe(()=>{}));let fe=-1,q=me([ye,B,E],([D,K,ne])=>{let H=a.cache,N=D,I=ne,U=K;if(H<=fe)return;fe=H;let{best:J,bestScore:Me}=ks(I,U),st=p.cache,Be={n:H,candidates:I,scores:U,feedback:N,best:J,bestScore:Me,timestamp_ns:ee()},Q=[...st,Be],we=b.cache+I.length,ve="continue",Ge,Cn=r.budget!=null&&we>=r.budget,In=h.cache;if(Cn)ve="budget",Ge="budget";else if(r.minScore!=null&&N.score>=r.minScore)ve="converged",Ge="min-score";else if(r.maxIterations!=null&&H>=r.maxIterations)ve="converged",Ge="max-iterations";else if(r.maxEvaluations!=null&&we>=r.maxEvaluations)ve="converged",Ge="max-evaluations";else if(r.minDelta!=null&&Q.length>=2){let yt=Q[Q.length-2].bestScore,Jt=Q[Q.length-1].bestScore;Math.abs(Jt-yt)<r.minDelta&&(ve="converged",Ge="min-delta")}else if(r.patience!=null&&Q.length>r.patience){let yt=Q.slice(-(r.patience+1)),Jt=yt[0].bestScore;yt.slice(1).every(zr=>zr.bestScore<=Jt)&&(ve="converged",Ge="patience")}ve==="continue"&&In&&(ve="paused"),re(()=>{f.emit(J),g.emit(N.score),p.emit(Q),b.emit(we),u.emit(N),R.publish({iteration:H,decision:ve,reason:Ge,timestamp_ns:ee()}),ve==="continue"?a.emit(H+1):c.emit(ve==="converged"?"converged":ve==="budget"?"budget":"paused")})},{name:"decide-bridge"});return o.add(q,{name:"decide-bridge"}),o.addDisposer(q.subscribe(()=>{})),Object.assign(o,{best:f,score:g,status:c,history:p,strategy:d,iteration:a,generate:x,evaluate:v,analyze:w,decide:R,setStrategy(D){d.emit(D)},pause(){h.emit(!0)},resume(){c.cache==="paused"&&re(()=>{h.emit(!1),c.emit("running"),a.emit(a.cache+1)})}})}function Ss(t){let{best:e,score:n,status:r}=t,s=Number.isFinite(n)?n.toFixed(3):String(n),o=e??void 0;return r==="converged"?{outcome:"success",detail:`refineLoop converged at score ${s}`,artifact:o}:r==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${s}`,artifact:o}:{outcome:"failure",detail:`refineLoop errored (status=${r})`,artifact:o}}function Nn(t){let e=t.name??"refine-executor",n=t.toOutput??Ss;return r=>{let s=$e(r,i=>i!=null,{name:`${e}/gate-in`}),o=Re(s,i=>{let a=Rr(t.seedFrom(i),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(i),name:`${e}/inner`});return G([a.status,a.best,a.score],([d,u,l])=>{let h=d;return h!=="converged"&&h!=="budget"&&h!=="errored"?null:n({best:u,score:l,status:h})},{name:`${e}/output`})},{name:e});return $e(o,i=>i!=null,{name:`${e}/gate-out`})}}function As(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function Cs(t){let{passCount:e,total:n,meanScore:r,threshold:s,missingArtifact:o}=t,i=Number.isFinite(r)?r.toFixed(3):String(r),a=!o&&n>0&&r>=s,d=o?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:a?[`${e}/${n} eval tasks passed; mean score ${i} \u2265 ${s}`]:n===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${e}/${n} eval tasks passed; mean score ${i} < threshold ${s}`];return a?{verified:!0,findings:d}:{verified:!1,findings:d,errorClass:"structural"}}function Is(t){return t.artifact??null}function kr(t){let e=t.name??"eval-verifier",n=t.threshold??.5,r=t.toOutput??Cs,s=t.extractArtifact??Is;return o=>{let i=$e(o,d=>d!=null&&d[0]!=null&&d[1]!=null,{name:`${e}/gate-in`}),a=Re(i,d=>{let[u,l]=d,h=s(u,l);if(h==null)return V(r({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:n,missingArtifact:!0}));let c=V([h],{name:`${e}/candidates`}),p=V(t.datasetFor(l),{name:`${e}/dataset`}),f=t.evaluator(c,p);return G([f],([g])=>{let b=g;if(b==null)return null;let y=As(b),x=b.filter(v=>v.score>=n).length;return r({scores:b,meanScore:y,passCount:x,total:b.length,threshold:n})},{name:`${e}/output`})},{name:e});return $e(a,d=>d!=null,{name:`${e}/gate-out`})}}function Ms(t){let e=t.name??"harness-pair",n=Nn({name:`${e}-exec`,seedFrom:t.seedFrom,evaluator:t.evaluator,strategy:t.strategy,datasetFor:t.datasetFor,refine:t.refine}),r=kr({name:`${e}-verify`,evaluator:t.evaluator,datasetFor:t.datasetFor,threshold:t.threshold});return{executor:n,verifier:r}}Ae();Ce();de();De();Ae();pe();de();var Rn=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(e={}){let{maxSize:n,defaultTtl:r}=e;if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(r!==void 0&&r<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=n,this._defaultTtl=r}get version(){return this._version}get size(){return this._store.size}has(e){let n=this._store.get(e);return n===void 0?!1:this._isExpired(n)?(this._store.delete(e),this._version+=1,!1):(this._touchLru(e,n),!0)}get(e){let n=this._store.get(e);if(n!==void 0){if(this._isExpired(n)){this._store.delete(e),this._version+=1;return}return this._touchLru(e,n),n.value}}set(e,n,r){let s=this._resolveExpiresAt(r);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:n,expiresAt:s}),this._evictLruWhileOver(),this._version+=1}setMany(e,n){let r=this._resolveExpiresAt(n),s=0;try{for(let[o,i]of e)this._store.has(o)&&this._store.delete(o),this._store.set(o,{value:i,expiresAt:r}),s+=1}finally{s>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(e){let n=this._store.delete(e);return n&&(this._version+=1),n}deleteMany(e){let n=0;try{for(let r of e)this._store.delete(r)&&(n+=1)}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._store.size;return e===0?0:(this._store.clear(),this._version+=1,e)}pruneExpired(){let e=ee(),n=0;for(let[r,s]of this._store)this._isExpired(s,e)&&(this._store.delete(r),n+=1);return n>0&&(this._version+=1),n}toMap(){let e=ee(),n=new Map;for(let[r,s]of this._store)this._isExpired(s,e)||n.set(r,s.value);return n}_resolveExpiresAt(e){let n=e??this._defaultTtl;if(n!==void 0){if(!Number.isFinite(n)||n<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${n})`);return ee()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??ee())>=e.expiresAt}_touchLru(e,n){this._store.delete(e),this._store.set(e,n)}_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 Ht(t={}){let{name:e,maxSize:n,defaultTtl:r,versioning:s,backend:o,retention:i}=t;if(i&&n!==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 Rn({maxSize:n,defaultTtl:r}),d=V(a.toMap(),{name:e,describeKind:"state",equals:(c,p)=>c===p,...s!=null?{versioning:s}:{}});function u(){let c=a.toMap();re(()=>{d.down([[X]]),d.down([[M,c]])})}function l(){if(!i)return;let c=a.toMap(),p=i.archiveThreshold,f=i.maxSize,g=[];for(let[y,x]of c)g.push({key:y,value:x,score:i.score(y,x)});g.sort((y,x)=>y.score-x.score);let b=new Set;if(p!==void 0)for(let y of g)if(y.score<p)b.add(y.key);else break;if(f!==void 0&&g.length-b.size>f)for(let y of g){if(g.length-b.size<=f)break;b.has(y.key)||b.add(y.key)}if(b.size!==0)for(let y of g)b.has(y.key)&&(i.onArchive?.(y.key,y.value,y.score),a.delete(y.key))}function h(c,p="mutation"){let f=a.version;try{return c()}finally{a.version!==f&&(p==="mutation"&&l(),u())}}return{entries:d,has(c){return h(()=>a.has(c),"read")},get(c){return h(()=>a.get(c),"read")},set(c,p,f){h(()=>a.set(c,p,f?.ttl))},setMany(c,p){h(()=>a.setMany(c,p?.ttl))},delete(c){h(()=>a.delete(c))},deleteMany(c){h(()=>a.deleteMany(c))},clear(){h(()=>a.clear())},pruneExpired(){h(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}function gt(t,e){return je("ai",t,e)}function Or(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}pe();de();Ue();function Sr(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function Ds(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Kt(t,e,n,r){let s=r?.format??"text",o=r?.name??"prompt_node",i=G(e,d=>{if(d.some(l=>l==null))return[];let u=typeof n=="string"?n:n(...d);return u?[{role:"user",content:u}]:[]},{name:`${o}::messages`,meta:gt("prompt_node")});return Re(i,d=>!d||d.length===0?V(null):he(u=>{let l=!1,h=!1,c,p={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt};if(r?.abort){let y=Xn(r.abort);p.signal=y.signal,c=y.dispose}let f;try{f=t.invoke(d,p)}catch(y){return l=!0,u.down([[P,y]]),()=>{c?.()}}let b=Ve(f).subscribe(y=>{if(!(h||l))for(let x of y){if(l)return;if(x[0]===M){let v=x[1];try{let w=Sr(v),R=s==="json"?JSON.parse(Or(w)):w;u.emit(R)}catch(w){let R=Sr(v),_=new Error(`promptNode: failed to parse LLM response as JSON: ${w.message}
49
- Raw content (first 200 chars): ${Ds(R)}`);l=!0,u.down([[P,_]]);return}}else if(x[0]===P){l=!0,u.down([[P,x[1]]]);return}else if(x[0]===j){l=!0,u.down([[j]]);return}else u.down([x])}});return()=>{h=!0,b(),c?.()}},{name:`${o}::call`,meta:gt("prompt_node::call")}),{name:`${o}::output`,meta:r?.meta?{...gt("prompt_node::output"),...r.meta}:gt("prompt_node::output")})}De();Ae();pe();Ce();de();De();Ae();Xe();pe();de();var Gs=Hn((t,e)=>{t("observe"),t("signal"),e("write")});function qt(t){let e=jt([],{name:t.name,maxSize:t.retainedLimit??1024,guard:t.guard??Gs,...t.versioning!=null?{versioning:t.versioning}:{}});return e.withLatest(),t.graph&&t.graph.add(e.entries,{name:t.name}),e}function Ar(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))Ar(t[e]);return Object.freeze(t)}function Ls(t){let n=(t.cache??0)+1;return t.down([[X],[M,n]]),n}function ot(t,e){let n=e.freeze??!0;return function(...s){let o=n?s.map(Ar):s,i=be(),a,d,u=!1,l;try{re(()=>{e.seq&&(l=Ls(e.seq));try{if(a=t(...o),e.onSuccess){let h=e.onSuccess(o,a,{t_ns:i,seq:l});if(h!==void 0){let c=e.handlerVersion!=null?{...h,handlerVersion:e.handlerVersion}:h;e.audit.append(c)}}}catch(h){throw d=h,u=!0,h}})}catch(h){if(u&&e.onFailure){let c=d instanceof Error?d.name:typeof d,p=e.onFailure(o,d,{t_ns:i,seq:l,errorType:c});if(p!==void 0){let f=e.handlerVersion!=null?{...p,handlerVersion:e.handlerVersion}:p;e.audit.append(f)}}throw u?d:h}return a}}function Cr(t,e,n=0){let r=V(n,{name:e,describeKind:"state"});return t.add(r,{name:e}),r}function bt(t,e){return je("orchestration",t,e)}var Ut=class extends ce{constructor(e,n){super(e,n)}task(e,n,r={}){let s=(r.deps??[]).map(i=>this._resolveStep(i)),o=G(s,n,{name:e,describeKind:"derived",meta:bt("task",r.meta)});return this.add(o,{name:e}),o}classify(e,n,r,s={}){let o=this._resolveStep(n),i=G([o],([a])=>{try{return{tag:r(a),value:a}}catch(d){return{tag:"error",value:a,error:d}}},{name:e,describeKind:"derived",meta:bt("classify",s.meta)});return this.add(i,{name:e}),i}combine(e,n,r={}){let s=Object.keys(n),o=s.map(a=>this._resolveStep(n[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:bt("combine",r.meta)});return this.add(i,{name:e}),i}gate(e,n,r={}){let s=r.maxPending??1e3;if(s<1&&s!==Number.POSITIVE_INFINITY)throw new RangeError("gate: maxPending must be >= 1");let o=r.startOpen??!1;typeof n!="string"&&this.nameOf(n)===void 0&&this.add(n,{name:`${e}/source`});let i=this._resolveStep(n),a=new ce(`${e}_state`),d=V([],{name:"pending",equals:()=>!1}),u=V(o,{name:"isOpen"}),l=G([d],([$])=>$.length,{name:"count"}),h=V(0,{name:"droppedCount"}),c=qt({name:"decisions",retainedLimit:1024,graph:a});a.add(d,{name:"pending"}),a.add(u,{name:"isOpen"}),a.add(l,{name:"count"}),a.add(h,{name:"droppedCount"}),this.mount(`${e}_state`,a);let p=[],f=!1,g=!1,b=o,y=u.subscribe($=>{for(let F of $)F[0]===M&&(b=F[1])});this.addDisposer(y);function x(){d.emit([...p])}function v($,F,L){c.append({action:$,t_ns:be(),...F!==void 0?{items:F,count:F.length}:{},...L!==void 0?{unflushed:L}:{},...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}function w($){if(p.push($),p.length>s){let F=p.shift();h.emit(h.cache+1),v("drop",[F])}x()}function R($){let F=p.splice(0,$);return x(),F}let _=oe([i],($,F,L)=>{let le=L.terminalDeps[0];if(le!==void 0){f=!0;let z=p.length;p=[],x(),v("teardown",void 0,z),F.down(le===!0?[[j]]:[[P,le]]);return}let O=$[0];if(O==null||O.length===0){F.down([[Z]]);return}for(let z of O)b?F.emit(z):(w(z),F.down([[Z]]))},{name:e,describeKind:"derived",meta:bt("gate",r.meta)});if(this.add(_,{name:e}),r.approver!=null){r.approver.cache&&(u.emit(!0),b=!0,r.onceOnly&&(g=!0));let F=r.approver.subscribe(L=>{for(let le of L){if(le[0]!==M)continue;let O=!!le[1];if(O&&!b){if(r.onceOnly){if(g)continue;g=!0}re(()=>{u.emit(!0);let z=R(p.length);v("open",z);for(let ae of z){if(f)break;_.emit(ae)}})}else if(!O&&b){if(r.onceOnly&&g)continue;re(()=>{u.emit(!1),v("close")})}}});this.addDisposer(F)}let m=$=>{if(f)throw new Error(`gate: ${$}() called after gate was torn down`)},T=($=1)=>{m("approve");let F=R($);for(let L of F){if(f)break;_.emit(L)}},E=($=1)=>{m("reject"),R($)},A=($,F=1)=>{m("modify");let L=[...p],le=R(F);for(let O=0;O<le.length&&!f;O++)_.emit($(le[O],O,L))},k=()=>{m("open"),u.emit(!0);let $=R(p.length);for(let F of $){if(f)break;_.emit(F)}},S=()=>{m("close"),!(r.onceOnly&&g)&&u.emit(!1)},C=ot(T,{audit:c,freeze:!1,onSuccess:($,F,L)=>({action:"approve",count:$[0]??1,t_ns:L.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:($,F,L)=>({action:"drop",t_ns:L.t_ns,errorType:L.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),B=ot(E,{audit:c,freeze:!1,onSuccess:($,F,L)=>({action:"reject",count:$[0]??1,t_ns:L.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:($,F,L)=>({action:"drop",t_ns:L.t_ns,errorType:L.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),Y=ot(A,{audit:c,freeze:!1,onSuccess:($,F,L)=>({action:"modify",count:$[1]??1,t_ns:L.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:($,F,L)=>({action:"drop",t_ns:L.t_ns,errorType:L.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),W=ot(k,{audit:c,freeze:!1,onSuccess:($,F,L)=>({action:"open",t_ns:L.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:($,F,L)=>({action:"drop",t_ns:L.t_ns,errorType:L.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),ye=ot(S,{audit:c,freeze:!1,onSuccess:($,F,L)=>({action:"close",t_ns:L.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:($,F,L)=>({action:"drop",t_ns:L.t_ns,errorType:L.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})});return this.addDisposer(l.subscribe(()=>{})),{node:_,pending:d,count:l,isOpen:u,droppedCount:h,decisions:c,audit:c,approve:C,reject:B,modify:Y,open:W,close:ye}}approval(e,n,r,s={}){return this.gate(e,n,{...s,approver:r,maxPending:1})}catch(e,n,r,s={}){let o=this._resolveStep(n),i=s.on??"error",a=oe([o],(d,u,l)=>{let h=l.terminalDeps[0];if(h!==void 0){let p=h===!0?{kind:"complete"}:{kind:"error",error:h};if(i==="terminal"||i===p.kind){u.emit(r(p,u));return}u.down(p.kind==="complete"?[[j]]:[[P,p.error]]);return}let c=d[0];if(c==null||c.length===0){u.down([[Z]]);return}for(let p of c)u.emit(p)},{name:e,describeKind:"derived",completeWhenDepsComplete:s.completeWhenDepsComplete??!(i==="complete"||i==="terminal"),errorWhenDepsError:!(i==="error"||i==="terminal"),meta:bt("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 kn(t,e){return new Ut(t,e)}function Ir(t,e,n,r=0){if(!Number.isFinite(t))return r;if(!Number.isFinite(e)||e<=0||!Number.isFinite(n)||n<=0)return Math.max(r,t);let s=t*Math.exp(-n*e);return Math.max(r,s)}Ae();De();pe();de();var On=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 n=e>=0?e:this._buf.length+e;if(!(n<0||n>=this._buf.length))return this._buf[n]}append(e){this._buf.push(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._buf.length;this._buf.length=n+e.length;for(let r=0;r<e.length;r++)this._buf[n+r]=e[r];this._version+=1}insert(e,n){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,n),this._version+=1}insertMany(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insertMany: index ${e} out of range [0, ${this._buf.length}]`);n.length!==0&&(this._buf.splice(e,0,...n),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 n=e>=0?e:this._buf.length+e;if(n<0||n>=this._buf.length)throw new RangeError(`pop: index ${e} out of range`);let[r]=this._buf.splice(n,1);return this._version+=1,r}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._version+=1,e)}toArray(){return[...this._buf]}};function Mr(t,e={}){let{name:n,versioning:r,backend:s}=e,o=s??new On(t),i=V(o.toArray(),{name:n,describeKind:"state",equals:(u,l)=>u===l,...r!=null?{versioning:r}:{}});function a(){let u=o.toArray();re(()=>{i.down([[X]]),i.down([[M,u]])})}function d(u){let l=o.version;try{return u()}finally{o.version!==l&&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,l){d(()=>o.insert(u,l))},insertMany(u,l){d(()=>o.insertMany(u,l))},pop(u=-1){return d(()=>o.pop(u))},clear(){d(()=>o.clear())},dispose(){}}}function Ps(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function $s(t,e){return je("job_queue",t,e)}var Sn=class extends ce{_pending;_jobs;_seqCursor;pending;jobs;depth;events;audit;constructor(e,n={}){super(e,n.graph),this._pending=Mr([],{name:"pending"}),this._jobs=Ht({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],([r])=>r.length,{name:"depth",describeKind:"derived",meta:$s("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(Te(this.depth)),this.events=qt({name:"events",retainedLimit:1024,graph:this}),this.audit=this.events,this._seqCursor=Cr(this,"seq",0)}_bumpSeq(){let n=(this._seqCursor.cache??0)+1;return this._seqCursor.emit(n),n}attachEventStorage(e){return this.events.attachStorage(e)}enqueue(e,n={}){let r=this._bumpSeq(),s=n.id??`${this.name}-${r}`;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({...n.metadata??{}}),state:"queued"};return this._jobs.set(s,o),this._pending.append(s),this.events.append({action:"enqueue",id:s,payload:e,t_ns:be(),seq:r}),s}claim(e=1){let n=Ps(e,"job queue claim limit");if(n===0)return[];let r=[];for(;r.length<n&&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),r.push(a),this.events.append({action:"claim",id:o,attempts:a.attempts,t_ns:be(),seq:this._bumpSeq()})}return r}ack(e){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:(this._jobs.delete(e),this.events.append({action:"ack",id:e,attempts:n.attempts,t_ns:be(),seq:this._bumpSeq()}),!0)}nack(e,n={}){let r=this._jobs.get(e);return!r||r.state!=="inflight"?!1:n.requeue??!0?(this._jobs.set(e,{...r,state:"queued"}),this._pending.append(e),this.events.append({action:"nack",id:e,attempts:r.attempts,t_ns:be(),seq:this._bumpSeq()}),!0):(this._jobs.delete(e),this.events.append({action:"nack",id:e,attempts:r.attempts,t_ns:be(),seq:this._bumpSeq()}),!0)}removeById(e){let n=this._jobs.get(e);if(!n)return!1;if(n.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:n.attempts,t_ns:be(),seq:this._bumpSeq()}),!0}consumeFrom(e,n){return e.subscribe(r=>{for(let s of r){if(s[0]!==M)continue;let o=s[1];this.enqueue(o,n?{metadata:n.metadata}:void 0)}})}};function Dr(t,e){return new Sn(t,e)}Ae();de();function An(){let t=Ht({name:"strategy-entries"}),e=G([t.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[l,h]of d){let c=u.get(l);if(!c||h.attempts!==c.attempts||h.successes!==c.successes)return!1}return!0}});function n(i,a,d){let u=nt(i,a),l=t.get(u),h=(l?.attempts??0)+1,c=(l?.successes??0)+(d?1:0);t.set(u,{rootCause:i,intervention:a,attempts:h,successes:c,successRate:c/h})}function r(i,a){return t.get(nt(i,a))}let s=e.subscribe(()=>{});function o(){s()}return{node:e,record:n,lookup:r,dispose:o}}function Vs(t,e,n,r,s){let o={...et,...s?.severityWeights},i=s?.decayRate??tt,a=s?.effectivenessThreshold??.7,d=s?.effectivenessBoost??15,u=[t,e,n];return r&&u.push(r),G(u,l=>{let h=l[0],c=l[1],p=l[2],f=r?l[3]:0,g=o[h.severity??"medium"],b=(ee()-p)/1e9,y=Ir(g,b,i,0),x=nt(h.rootCause,h.intervention),v=c.get(x);return v&&v.successRate>=a&&(y+=d),y+=f*20,y},{name:"priority-score"})}var Gr="intake",Fs="triage-output",Lr="retry",Pr="verify-results",$r="__unrouted";function Vr(t,e){let n=ft(e,cn,(r,s)=>r.replace("{{item}}",JSON.stringify(s)));return r=>Kt(t,[r],n,{name:"execute",format:"json"})}function Fr(t,e){let n=ft(e,fn,(r,s)=>{let[o,i]=s;return r.replace("{{execution}}",JSON.stringify(o)).replace("{{item}}",JSON.stringify(i))});return r=>Kt(t,[r],s=>s==null?"":n(s),{name:"verify",format:"json"})}var Wt=class extends ce{queues;jobs;gates;queueTopics;strategy;totalRetries;totalReingestions;priorityScores;constructor(e,n,r,s,o,i,a,d,u){super(e),this.queues=n,this.queueTopics=r,this.jobs=s,this.gates=o,this.strategy=i,this.totalRetries=a,this.totalReingestions=d,this.priorityScores=u}get intake(){return this.queues.topic(Gr)}get verifyResults(){return this.queues.topic(Pr)}get retry(){return this.queues.topic(Lr)}get unrouted(){return this.queues.topic($r)}stageNodes(){let e=this.queues,n=i=>e.has(i)?`queues::${i}::latest`:null,r=i=>i==null?[]:[i],s=xe.flatMap(i=>r(n(i))),o=[];for(let[i]of this.gates)o.push(`gates::${i}/gate`);return[{label:"INTAKE",paths:r(n("intake"))},{label:"TRIAGE",paths:["triage"]},{label:"QUEUE",paths:s},{label:"GATE",paths:o},{label:"EXECUTE",paths:["execute"]},{label:"VERIFY",paths:r(n("verify-results"))},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function js(t,e){let n=e.adapter,r=e.maxRetries??2,s=e.retainedLimit??1e3,o=e.errorClassifier??St,i=new Map;for(let N of xe)i.set(N,{...Ot[N],...e.queues?.[N]});let a=Bt(`${t}/queues`,{defaultTopicOptions:{retainedLimit:s}}),d=a.topic(Gr),u=a.topic(Fs),l=a.topic(Lr),h=a.topic(Pr),c=new Map;for(let N of xe)c.set(N,a.topic(N));let p=a.topic($r),f=An(),g=ct(d.latest,f.node),b=ft(e.triagePrompt,ln,(N,I)=>{let[U,J]=I;return N.replace("{{strategy}}",JSON.stringify(Array.from(J.entries()))).replace("{{item}}",JSON.stringify(U))}),y=Kt(n,[g],N=>{let I=N;return!I||!I[0]?"":b(I)},{name:"triage",format:"json"}),x=ct(y,g),w=me([x],([N])=>{if(N==null)return;let[I,U]=N;if(!I?.route)return;let J=U?.[0],Me={...I,...J};u.publish(Me)}).subscribe(()=>{}),R=new Set(xe);for(let N of xe)En(`bridge/${N}`,u,c.get(N),{map:I=>I.route===N?I:void 0});En("bridge/__unrouted",u,p,{map:N=>R.has(N.route)?void 0:N});let _=new Map,m=new Map;for(let N of xe)_.set(N,Dr(`jobs/${N}`));let T=[];for(let N of xe){let I=c.get(N),U=_.get(N),J=new WeakSet,Me=me([I.events],([st])=>{let Be=st??[];for(let Q of Be){if(J.has(Q))continue;J.add(Q);let we=U.enqueue(Q);m.set(mt(Q),{route:N,id:we})}},{name:`jobs/${N}-mirror`});T.push(Me.subscribe(()=>{}))}function E(N){let I=mt(N),U=m.get(I);U&&(_.get(U.route)?.removeById(U.id),m.delete(I))}let A=kn("gates"),k=new Map;for(let N of xe){let I=i.get(N);if(!I.gated)continue;let U=c.get(N),J=A.gate(`${N}/gate`,U.latest,{maxPending:I.maxPending,startOpen:I.startOpen});k.set(N,J)}let S=[];for(let N of xe)i.get(N).gated&&k.has(N)?S.push(k.get(N).node):S.push(c.get(N).latest);S.push(l.latest);let C=Zn(...S),Y=(e.executor??Vr(n,e.executePrompt))(C),W=ct(Y,C),Oe=(e.verifier??Fr(n,e.verifyPrompt))(W),$=ct(Oe,W),F=e.maxReingestions??1,L=Math.min(e.maxTotalRetries??r*10,100),le=Math.min(e.maxTotalReingestions??F*10,100),O=V(0),z=V(0);function ae(N,I,U){let J={item:U,outcome:I?.outcome??"failure",detail:I?.detail??"unknown",artifact:I?.artifact};return{item:U,execution:J,verified:N.verified,findings:N.findings??[],errorClass:N.errorClass}}function Ie(N,I){f.record(I.rootCause,I.intervention,!0),h.publish(N),E(I)}function fe(N,I){let U=mt(I),J=I.$retries??0,Me={...I,$retries:J+1,summary:`[RETRY ${J+1}/${r}] ${U} \u2014 Previous attempt failed: ${N.findings.join("; ")}`,relatedTo:[U]};l.publish(Me)}function q(N,I){f.record(I.rootCause,I.intervention,!1),h.publish(N),E(I);let U=mt(I),J=I.$reingestions??0;J<F&&vn(z,le)&&d.publish({source:I.source,summary:`Verification failed for: ${U}`,evidence:N.findings.join(`
50
- `),affectsAreas:I.affectsAreas,affectsEvalTasks:I.affectsEvalTasks,severity:I.severity??"high",relatedTo:[U],$reingestions:J+1})}let ue=oe([$],(N,I)=>{let U=N[0];if(U==null||U.length===0)return;let J=U[U.length-1];if(J==null)return;let[Me,st]=J,[Be,Q]=st??[null,null];if(!Me||!Q)return;if(Be==null){q({item:Q,execution:{item:Q,outcome:"failure",detail:"executor returned null"},verified:!1,findings:["executor returned null"],errorClass:"structural"},Q);return}let we=ae(Me,Be,Q);if(we.verified){Ie(we,Q);return}let ve=we.errorClass??o({item:Q,outcome:Be.outcome,detail:we.findings.join("; ")}),Ge=Q.$retries??0;ve==="self-correctable"&&Ge<r&&vn(O,L)?fe(we,Q):q(we,Q)}),D=ue.subscribe(()=>{}),K=G([ue],()=>null,{name:"reflect",equals:()=>!1}),ne;e.priority&&(ne=zs(c,f,e));let H=new Wt(t,a,c,_,k,f,O,z,ne);H.addDisposer(w),H.addDisposer(D),H.addDisposer(f.dispose);for(let N of T)H.addDisposer(N);if(H.add(y,{name:"triage"}),H.add(C,{name:"execute-input"}),H.add(Y,{name:"execute"}),H.add(W,{name:"execute-context"}),H.add(Oe,{name:"verify"}),H.add($,{name:"verify-context"}),H.add(ue,{name:"verify-dispatch"}),H.add(K,{name:"reflect"}),H.add(f.node,{name:"strategy"}),H.addDisposer(K.subscribe(()=>{})),ne)for(let[N,I]of ne)H.add(I,{name:`priority/${N}`}),H.addDisposer(I.subscribe(()=>{}));H.mount("queues",a),H.mount("gates",A);for(let[N,I]of _)H.mount(`jobs/${N}`,I);return H}function zs(t,e,n){if(!n.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 r=n.lastInteractionNs,s=n.priority??{},o={...et,...s.severityWeights},i=s.decayRate??tt,a=s.effectivenessThreshold??.7,d=s.effectivenessBoost??15,u=new Map;for(let[l,h]of t){let c=G([h.latest,e.node,r],p=>{let f=p[0];if(f==null)return 0;let g=o[f.severity??"medium"]??40,b=(ee()-p[2])/1e9,y=g*Math.exp(-i*Math.max(0,b)),x=`${f.rootCause}\u2192${f.intervention}`,w=p[1]?.get(x);return w&&w.successRate>=a&&(y+=d),y},{name:`priority/${l}`});u.set(l,c)}return u}function Bs(t,e){let n=$t(t,e),r={};for(let s of xe){let o=t.queues.has(s)?t.queues.topic(s):null;r[s]=o?.retained().length??0}return{...n,queueDepths:r,strategyEntries:t.strategy.node.cache?.size??0,totalRetries:t.totalRetries.cache??0,totalReingestions:t.totalReingestions.cache??0}}Ae();function Hs(t){let e={};for(let{label:n,paths:r}of t.stageNodes())for(let s of r)e[s]=n;return e}function Ks(t,e){let n=e?.logger===null?null:e?.logger??console.log,r=e?.detail??"summary",s=ee(),o=[],i=[],a=Hs(t);function d(){return(ee()-s)/1e9}function u(l,h,c){let p={elapsed:d(),stage:l,type:h};r!=="summary"&&(p.summary=qs(c)),r==="full"&&(p.data=c),i.push(p)}for(let[l,h]of Object.entries(a))try{let c=t.observe(l,{format:"stage-log",stageLabels:a,logger:n?p=>n(p):()=>{},includeTypes:["data","error","complete"]});c.onEvent(p=>{p.type==="data"?u(h,"data",p.data):p.type==="error"?u(h,"error",p.data):p.type==="complete"&&u(h,"complete",void 0)}),o.push(c)}catch(c){let p=c instanceof Error?c.message:String(c);u(h,"error",`observe-unavailable: ${l} \u2014 ${p}`),n&&n(`[${d().toFixed(3)}s] ${h.padEnd(9)} \u2717 observe-unavailable: ${p}`)}return{get events(){return i},dispose(){for(let l of o)l.dispose();o.length=0}}}function qs(t){if(t==null)return"null";if(typeof t=="string")return jr(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return jr(e,120)}catch{return String(t)}}function jr(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}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,evalIntakeBridge,evalSource,evalVerifier,harnessEvalPair,harnessLoop,harnessProfile,harnessTrace,notifyEffect,priorityScore,refineExecutor,resolvePromptFn,strategyKey,strategyModel});
42
+ }`;function ft(t,e,n){if(typeof t=="function")return t;let r=t??e;return s=>n(r,s)}de();de();De();Ae();pe();Ce();de();Et();De();Ae();Xe();pe();Xe();Ce();function At(t,e){if(e!=null&&e.length>0)return new Set(e);switch(t){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;default:return new Set(["type","deps"])}}function So(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function Ao(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function pn(t,e){let n=e==null,r=!n&&e!=null?[...e].filter(u=>u.startsWith("meta.")).map(u=>u.slice(5)):null,s=n||e.has("meta")||r!=null&&r.length>0,o="state",i=[];t instanceof se&&(o=So(t),i=t._deps.map(u=>u.node.name??""));let a={type:o,deps:i};(n||e.has("status"))&&(a.status=t.status);let d=t instanceof se?t._guard:void 0;if(s){let u={...Ao(t)};if(d!=null&&u.access===void 0&&(u.access=nn(d)),r!=null&&r.length>0&&!e.has("meta")){let l={};for(let h of r)h in u&&(l[h]=u[h]);a.meta=l}else a.meta=u}if(t.name!=null&&(a.name=t.name),n||e.has("value")){t.status==="sentinel"&&(a.sentinel=!0);try{a.value=t.cache}catch{}}if((n||e.has("v"))&&t.v!=null){let u={id:t.v.id,version:t.v.version};"cid"in t.v&&(u.cid=t.v.cid,u.prev=t.v.prev),a.v=u}return(n||e.has("guard"))&&d!=null&&(a.guard=nn(d)),(n||e.has("lastMutation"))&&t.lastMutation!=null&&(a.lastMutation=t.lastMutation),a}Ce();de();Ue();er();var pt=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 n=(this.head+this._size)%this.capacity;this.buf[n]=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 n=e<0?this._size+e:e;if(!(n<0||n>=this._size))return this.buf[(this.head+n)%this.capacity]}toArray(){let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this.buf[(this.head+n)%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}};tn();function hn(t){return t>=768&&t<=879||t>=1155&&t<=1161||t>=1425&&t<=1469||t>=1552&&t<=1562||t>=1611&&t<=1631||t>=1648&&t===1648||t>=1750&&t<=1756||t>=1759&&t<=1764||t>=1767&&t<=1768||t>=1770&&t<=1773||t>=1840&&t<=1866||t>=1958&&t<=1968||t>=2304&&t<=2307||t>=2362&&t<=2383||t>=2385&&t<=2391||t>=2402&&t<=2403||t>=2433&&t<=2435||t>=2492&&t<=2509||t>=2561&&t<=2563||t>=2620&&t<=2641||t>=2672&&t<=2673||t>=2677&&t===2677||t>=3633&&t===3633||t>=3636&&t<=3642||t>=3655&&t<=3662||t>=3761&&t===3761||t>=3764&&t<=3772||t>=3784&&t<=3790||t>=7616&&t<=7679||t>=8400&&t<=8447||t>=65024&&t<=65039||t>=65056&&t<=65071||t===8205?0:t>=4352&&t<=4447||t>=8986&&t<=8987||t>=9001&&t<=9002||t>=9193&&t<=9203||t>=9208&&t<=9210||t>=9725&&t<=9726||t>=9748&&t<=9749||t>=9800&&t<=9811||t===9855||t===9875||t===9889||t>=9898&&t<=9899||t>=9917&&t<=9918||t>=9924&&t<=9925||t===9934||t===9940||t===9962||t>=9970&&t<=9971||t===9973||t===9978||t===9981||t===9986||t===9989||t>=9992&&t<=9997||t===9999||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t>=10548&&t<=10549||t>=11013&&t<=11015||t>=11035&&t<=11036||t===11088||t===11093||t>=11904&&t<=12350||t>=12352&&t<=12447||t>=12448&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12784&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=19968&&t<=40959||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65131||t>=65281&&t<=65376||t>=65504&&t<=65510||t>=126980&&t===126980||t===127183||t>=127344&&t<=127345||t===127358||t===127359||t===127374||t>=127377&&t<=127386||t>=127456&&t<=127487||t>=127488&&t<=127490||t===127514||t===127535||t>=127538&&t<=127546||t>=127568&&t<=127569||t>=127744&&t<=129535||t>=129536&&t<=129791||t>=129792&&t<=130047||t>=131072&&t<=196605||t>=196608&&t<=262141?2:1}function Mt(t){let e=0;for(let n of t)e+=hn(n.codePointAt(0));return e}function tr(t,e){if(e<=0)return"";let n=0,r="";for(let s of t){let o=hn(s.codePointAt(0));if(n+o>e){if(e<=1)return"\u2026";for(;n+1>e&&r.length>0;){let i=[...r].pop();r=r.slice(0,-i.length),n-=hn(i.codePointAt(0))}return`${r}\u2026`}r+=s,n+=o}return r}var Co={horizontal:"\u2500",vertical:"\u2502",cornerTL:"\u250C",cornerTR:"\u2510",cornerBL:"\u2514",cornerBR:"\u2518",tDown:"\u252C",tUp:"\u2534",tRight:"\u251C",tLeft:"\u2524",cross:"\u253C",arrowRight:"\u25B6",arrowDown:"\u25BC",arrowLeft:"\u25C0",arrowUp:"\u25B2",boxTL:"\u250C",boxTR:"\u2510",boxBL:"\u2514",boxBR:"\u2518",boxH:"\u2500",boxV:"\u2502"},Mo={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function sr(t,e){let n=e.charset==="ascii"?Mo:Co,r=t.width,s=t.height,o=Array.from({length:s},()=>Array.from({length:r},()=>" ")),i=Array.from({length:s},()=>Array.from({length:r},()=>"empty"));for(let a of t.edges)Do(o,i,n,a);for(let a of t.boxes)Io(o,i,n,a,e.labelOf(a.id));return o.map(a=>$o(a.join(""))).join(`
43
+ `)}function Io(t,e,n,r,s){let{x:o,y:i,w:a,h:d}=r;if(a<2||d<2){d>0&&nr(t,e,o,i,a,s);return}Fe(t,e,o,i,n.boxTL);for(let l=o+1;l<o+a-1;l+=1)Fe(t,e,l,i,n.boxH);Fe(t,e,o+a-1,i,n.boxTR);for(let l=i+1;l<i+d-1;l+=1){Fe(t,e,o,l,n.boxV);for(let h=o+1;h<o+a-1;h+=1)ir(t,e,h,l," ","empty");Fe(t,e,o+a-1,l,n.boxV)}Fe(t,e,o,i+d-1,n.boxBL);for(let l=o+1;l<o+a-1;l+=1)Fe(t,e,l,i+d-1,n.boxH);Fe(t,e,o+a-1,i+d-1,n.boxBR);let u=i+Math.floor(d/2);nr(t,e,o+1,u,a-2,s)}function Fe(t,e,n,r,s){ir(t,e,n,r,s,s===" "?"empty":s==="\u2500"||s==="-"?"boxH":s==="\u2502"||s==="|"?"boxV":"boxCorner")}function ir(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=t[r];n<0||n>=i.length||(i[n]=s,e[r][n]=o)}function nr(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=n,a=s;for(let d of o){let u=Mt(d);if(u!==0){if(a<u)break;i>=0&&i<t[r].length&&(t[r][i]=d,e[r][i]="label",u===2&&i+1<t[r].length&&(t[r][i+1]="",e[r][i+1]="label")),i+=u,a-=u}}for(;a>0;)i>=0&&i<t[r].length&&(t[r][i]=" ",e[r][i]="empty"),i+=1,a-=1}function Do(t,e,n,r){let s=r.points;if(s.length<2)return;for(let d=0;d+1<s.length;d+=1)Go(t,e,n,s[d],s[d+1]);for(let d=1;d+1<s.length;d+=1){let u=s[d-1],l=s[d],h=s[d+1],c=Lo(u,l,h,n);c&&or(t,e,l.x,l.y,c,"edgeCorner")}let o=s[s.length-1],i=s[s.length-2],a=Po(i,o,n);a&&or(t,e,o.x,o.y,a,"arrow")}function Go(t,e,n,r,s){if(!(r.x===s.x&&r.y===s.y)){if(r.y===s.y){let o=r.y,i=Math.min(r.x,s.x),a=Math.max(r.x,s.x);for(let d=i;d<=a;d+=1)rr(t,e,d,o,n,"h")}else if(r.x===s.x){let o=r.x,i=Math.min(r.y,s.y),a=Math.max(r.y,s.y);for(let d=i;d<=a;d+=1)rr(t,e,o,d,n,"v")}}}function rr(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];if(!(a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label")){if(a==="empty"){i[n]=o==="h"?s.horizontal:s.vertical,e[r][n]=o==="h"?"edgeH":"edgeV";return}if(a==="edgeH"&&o==="v"){i[n]=s.cross,e[r][n]="edgeCorner";return}if(a==="edgeV"&&o==="h"){i[n]=s.cross,e[r][n]="edgeCorner";return}}}function or(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label"||(i[n]=s,e[r][n]=o)}function Lo(t,e,n,r){let s=t.y===e.y,o=e.y===n.y;if(s===o)return;if(s){let d=t.x<e.x,u=n.y>e.y;return d&&u?r.cornerTR:d&&!u?r.cornerBR:!d&&u?r.cornerTL:r.cornerBL}let i=t.y<e.y,a=n.x>e.x;return i&&a?r.cornerBL:i&&!a?r.cornerBR:!i&&a?r.cornerTL:r.cornerTR}function Po(t,e,n){if(e.x>t.x)return n.arrowRight;if(e.x<t.x)return n.arrowLeft;if(e.y>t.y)return n.arrowDown;if(e.y<t.y)return n.arrowUp}function $o(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function dr(t){let e=Vo(t);Fo(e),jo(e),zo(e),Bo(e,t);let n=qo(e,t),{width:r,height:s}=Wo(e),o=[];for(let i of e.layers)for(let a of i)a.isVirtual||o.push({id:a.id,layer:a.layer,order:a.order,x:a.x,y:a.y,w:a.w,h:a.h});return{boxes:o,edges:n,width:r,height:s}}function Vo(t){let e=new Map;for(let s of t.nodes)e.set(s,{id:s,isVirtual:!1,layer:-1,order:0,x:0,y:0,w:t.widthCells(s),h:t.heightCells(s),in:[],out:[]});let n=[],r=0;for(let s of t.edges){if(s.from===s.to)continue;let o=e.get(s.from),i=e.get(s.to);if(!o||!i)continue;let a={chainId:r++,chainFrom:s.from,chainTo:s.to,fromId:s.from,toId:s.to,hopIndex:0,chainLen:1};o.out.push(a),i.in.push(a),n.push(a)}return{nodes:e,layers:[],hops:n}}function Fo(t){let e=new Map;for(let o of t.nodes.values())e.set(o.id,o.in.length);let n=[];for(let o of t.nodes.values())(e.get(o.id)??0)===0&&(o.layer=0,n.push(o));let r=new Set,s=0;for(;s<n.length;){let o=n[s++];if(!r.has(o.id)){r.add(o.id);for(let i of o.out){let a=t.nodes.get(i.toId);a.layer=Math.max(a.layer,o.layer+1);let d=(e.get(a.id)??0)-1;e.set(a.id,d),d<=0&&n.push(a)}}}for(let o of t.nodes.values())o.layer<0&&(o.layer=0)}function jo(t){let e=Math.max(0,...Array.from(t.nodes.values(),o=>o.layer)),n=Array.from({length:e+1},()=>[]);for(let o of t.nodes.values())n[o.layer].push(o);let r=[],s=0;for(let o of t.hops){let i=t.nodes.get(o.fromId),a=t.nodes.get(o.toId),d=a.layer-i.layer;if(d<=0){i.out=i.out.filter(h=>h!==o),a.in=a.in.filter(h=>h!==o);continue}if(d===1){o.hopIndex=0,o.chainLen=1,r.push(o);continue}i.out=i.out.filter(h=>h!==o),a.in=a.in.filter(h=>h!==o);let u=i;for(let h=1;h<d;h+=1){let c=`__virt_${s++}__`,p={id:c,isVirtual:!0,layer:i.layer+h,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(c,p),n[p.layer].push(p);let f={chainId:o.chainId,chainFrom:o.chainFrom,chainTo:o.chainTo,fromId:u.id,toId:c,hopIndex:h-1,chainLen:d};u.out.push(f),p.in.push(f),r.push(f),u=p}let l={chainId:o.chainId,chainFrom:o.chainFrom,chainTo:o.chainTo,fromId:u.id,toId:a.id,hopIndex:d-1,chainLen:d};u.out.push(l),a.in.push(l),r.push(l)}for(let o of n)for(let i=0;i<o.length;i+=1)o[i].order=i;t.layers=n,t.hops=r}function zo(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)ar(t,t.layers[r],"in"),It(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)ar(t,t.layers[r],"out"),It(t.layers[r])}for(let n=0;n<2;n+=1){let r=!1;for(let s=1;s<t.layers.length;s+=1){let o=t.layers[s];for(let i=0;i+1<o.length;i+=1){let a=ur(t,o[i],o[i+1],"in");[o[i],o[i+1]]=[o[i+1],o[i]],It(o),ur(t,o[i],o[i+1],"in")<a?r=!0:([o[i],o[i+1]]=[o[i+1],o[i]],It(o))}}if(!r)break}}function ar(t,e,n){let r=new Map;for(let s of e){let o=n==="in"?s.in:s.out;if(o.length===0){r.set(s.id,s.order);continue}let i=0,a=0;for(let d of o){let u=t.nodes.get(n==="in"?d.fromId:d.toId);u&&(i+=u.order,a+=1)}r.set(s.id,a===0?s.order:i/a)}e.sort((s,o)=>{let i=r.get(s.id),a=r.get(o.id);return i!==a?i-a:s.order-o.order})}function It(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function ur(t,e,n,r){let s=r==="in"?e.in:e.out,o=r==="in"?n.in:n.out,i=0;for(let a of s)for(let d of o){let u=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,l=t.nodes.get(r==="in"?d.fromId:d.toId)?.order??0;(e.order<n.order&&u>l||e.order>n.order&&u<l)&&(i+=1)}return i}function Bo(t,e){e.direction==="LR"?Ho(t,e):Ko(t,e)}function Ho(t,e){let n=[],r=0;for(let s=0;s<t.layers.length;s+=1){n.push(r);let o=0;for(let i of t.layers[s])o=Math.max(o,i.w);r+=o+e.layerGap}for(let s=0;s<t.layers.length;s+=1)for(let o of t.layers[s])o.x=n[s];for(let s of t.layers){let o=0;for(let i of s)i.y=o,o+=i.h+e.nodeGap}lr(t,e,"y")}function Ko(t,e){let n=[],r=0;for(let s=0;s<t.layers.length;s+=1){n.push(r);let o=0;for(let i of t.layers[s])o=Math.max(o,i.h);r+=o+e.layerGap}for(let s=0;s<t.layers.length;s+=1)for(let o of t.layers[s])o.y=n[s];for(let s of t.layers){let o=0;for(let i of s)i.x=o,o+=i.w+e.nodeGap}lr(t,e,"x")}function lr(t,e,n){let r=o=>n==="y"?o.h:o.w,s=e.nodeGap;for(let o=0;o<2;o+=1){let i=o===0?t.layers.slice(1):t.layers.slice(0,-1).reverse();for(let a of i){let d=new Map;for(let l of a){let h=o===0?l.in:l.out;if(h.length===0)continue;let c=[];for(let f of h){let g=t.nodes.get(o===0?f.fromId:f.toId);if(!g)continue;let b=n==="y"?g.y:g.x;c.push(b+Math.floor(r(g)/2))}if(c.length===0)continue;c.sort((f,g)=>f-g);let p=c[Math.floor(c.length/2)];d.set(l.id,p-Math.floor(r(l)/2))}let u=0;for(let l of a){let h=d.get(l.id),c=n==="y"?l.y:l.x,f=Math.max(h??c,u);n==="y"?l.y=f:l.x=f,u=f+r(l)+s}}}}function qo(t,e){let n=new Map;for(let u of t.hops){let l=n.get(u.chainId);l?l.push(u):n.set(u.chainId,[u])}for(let u of n.values())u.sort((l,h)=>l.hopIndex-h.hopIndex);let r=e.direction==="LR",s=u=>r?u.x:u.y,o=u=>r?u.w:u.h,i=u=>r?u.y+Math.floor(u.h/2):u.x+Math.floor(u.w/2),a=new Map;for(let u=0;u+1<t.layers.length;u+=1){let l=t.layers[u],h=t.layers[u+1],c=0;for(let x of l)c=Math.max(c,s(x)+o(x));let p=Number.POSITIVE_INFINITY;for(let x of h)p=Math.min(p,s(x));let f=Number.isFinite(p)?p-1:c,g=Math.max(1,f-c+1),b=[];for(let x of l)for(let E of x.out)b.push(E);b.sort((x,E)=>{let A=i(t.nodes.get(x.fromId)),k=i(t.nodes.get(E.fromId));if(A!==k)return A-k;let S=i(t.nodes.get(x.toId)),C=i(t.nodes.get(E.toId));return S-C});let v=[],T=new Map;for(let x of b){let E=i(t.nodes.get(x.fromId)),A=i(t.nodes.get(x.toId)),k=Math.min(E,A),S=Math.max(E,A),C=-1;for(let B=0;B<v.length;B+=1){let Y=v[B],W=!0;for(let ye of Y)if(ye.lo<=S&&k<=ye.hi){W=!1;break}if(W){Y.push({lo:k,hi:S}),C=B;break}}C<0&&(v.push([{lo:k,hi:S}]),C=v.length-1),T.set(x,C)}let y=v.length,w=g>=Math.max(3,y+2),N=w?c+1:c,_=w?f-1:f,m=Math.max(1,_-N+1);for(let x of b){let E=T.get(x),A;if(y<=1)A=N+Math.floor(m/2);else{let k=(m-1)/(y-1);A=N+Math.floor(E*k)}a.set(x,Math.max(c,Math.min(f,A)))}}let d=[];for(let[,u]of n){let l=[];for(let c=0;c<u.length;c+=1){let p=u[c],f=t.nodes.get(p.fromId),g=t.nodes.get(p.toId),b=a.get(p),v=f.isVirtual?s(f):s(f)+o(f),T=g.isVirtual?s(g):s(g)-1,y=i(f),w=i(g);c===0&&Dt(l,r,v,y),y!==w&&(Dt(l,r,b,y),Dt(l,r,b,w)),Dt(l,r,T,w)}let h=u[0];d.push({from:h.chainFrom,to:h.chainTo,points:Uo(l)})}return d}function Dt(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function Uo(t){let e=[];for(let n of t){let r=e[e.length-1];(!r||r.x!==n.x||r.y!==n.y)&&e.push(n)}return e}function Wo(t){let e=0,n=0;for(let r of t.layers)for(let s of r)e=Math.max(e,s.x+s.w),n=Math.max(n,s.y+s.h);return{width:e,height:n}}var Jo=24,Yo=4,Qo=1,Xo=3;function cr(t,e){let n=Zo(e.direction),r=Math.max(3,e.maxLabelWidth??Jo),s=e.asciiCharset??"unicode",o=Object.keys(t.nodes).sort(),i=new Set(o),a=t.edges.filter(p=>i.has(p.from)&&i.has(p.to)),d=new Map,u=new Map;for(let p of o){let f=tr(p,r);d.set(p,f),u.set(p,Mt(f)+4)}let l=dr({nodes:o,edges:a,widthCells:p=>u.get(p)??3,heightCells:()=>Xo,layerGap:Yo,nodeGap:Qo,direction:n}),h=sr(l,{charset:s,labelOf:p=>d.get(p)??p}),c=e.logger;return c&&c(h),h}function Zo(t){if(t===void 0||t==="LR")return"LR";if(t==="TD")return"TD";throw new Error(`ascii describe supports direction "LR" or "TD" only; got ${String(t)}`)}function fr(t,e,n,r={}){let s=e in t.nodes,o=n in t.nodes;if(!s)return Gt(e,n,"no-such-from");if(!o)return Gt(e,n,"no-such-to");let i=r.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===n){if(r.findCycle===!0){let u=es(t,e,r);if(u!=null)return u}let d=Lt(e,t.nodes[e],0,r);return Pt(e,n,[d])}if(i===0)return Gt(e,n,"no-path");let a=pr(t,e,n,i);return a.found?Pt(e,n,hr(t,a.pathOrder,r)):Gt(e,n,a.truncated?"max-depth-exceeded":"no-path")}function pr(t,e,n,r){let s=new Map,o=[{path:n,depth:0}],i=new Set([n]),a=0,d=!1;for(;a<o.length;){let h=o[a++];if(h.path===e)break;if(r!=null&&h.depth>=r){let g=t.nodes[h.path];g?.deps&&g.deps.length>0&&(d=!0);continue}let c=t.nodes[h.path];if(c==null)continue;let p=c.deps??[],f=new Map;for(let g=0;g<p.length;g++){let b=p[g];if(!b)continue;let v=f.get(b);v==null&&(v=[],f.set(b,v)),v.push(g)}for(let[g,b]of f)i.has(g)||(i.add(g),s.set(g,{from:h.path,depIndices:b}),o.push({path:g,depth:h.depth+1}))}if(!s.has(e))return{found:!1,pathOrder:[],truncated:d};let u=[{path:e}],l=e;for(;l!==n;){let h=s.get(l);if(h==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=h.depIndices,u.push({path:h.from}),l=h.from}return{found:!0,pathOrder:u,truncated:!1}}function es(t,e,n){let r=t.nodes[e];if(r==null)return null;let s=r.deps??[],o=[];for(let a=0;a<s.length;a++)s[a]===e&&o.push(a);if(o.length>0){let a=Lt(e,r,0,n);a.dep_index=o[0];let d=Lt(e,r,1,n);return Pt(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=pr(t,d,e,n.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:Pt(e,e,hr(t,i.pathOrder,n))}function hr(t,e,n){return e.map((r,s)=>{let o=t.nodes[r.path],i=Lt(r.path,o,s,n);return r.depIndices!=null&&r.depIndices.length>0&&(i.dep_index=r.depIndices[0],r.depIndices.length>1&&(i.dep_indices=[...r.depIndices])),i})}function Lt(t,e,n,r){let s={path:t,type:e.type,hop:n};e.status!==void 0&&(s.status=e.status),"value"in e&&(s.value=e.value),e.v!=null&&(s.v=e.v);let o=r.annotations?.get(t)??e.annotation;o!=null&&(s.annotation=o);let i=r.lastMutations?.get(t)??e.lastMutation;return i!=null&&(s.lastMutation=i),s}function Pt(t,e,n){return mr(t,e,!0,"ok",n)}function Gt(t,e,n){return mr(t,e,!1,n,[])}function mr(t,e,n,r,s){let o=ts(t,e,n,r,s);return{from:t,to:e,found:n,reason:r,steps:s,text:o,toJSON(){return{from:t,to:e,found:n,reason:r,steps:s}}}}function ts(t,e,n,r,s){if(!n)switch(r){case"no-such-from":return`explainPath: no node named "${t}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${t}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${t}" to "${e}"`}let o=[`Causal path: ${t} \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: ${ns(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(`
44
+ `)}function ns(t){if(t===void 0)return"<sentinel>";if(t===null)return"null";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return e.length>80?`${e.slice(0,77)}...`:e}catch{return String(t)}}Ce();var ie={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},rs=Symbol.for("sizeof");function gr(t){let e=new WeakSet,n=new WeakSet,r=[t],s=0;for(;r.length>0;){let o=r.pop();s+=os(o,e,n,r)}return s}function os(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return ie.number;case"boolean":return ie.boolean;case"string":return ie.string+t.length*2;case"bigint":return ie.bigint+ss(t);case"symbol":return ie.symbol;case"function":return e.has(t)?0:(e.add(t),ie.function);case"undefined":return 0}let o=t;if(e.has(o))return 0;e.add(o);let i=o[rs];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 ie.date;if(o instanceof RegExp)return ie.regexp+o.source.length*2;if(o instanceof Error){let u=o.message?o.message.length*2:0,l=o.stack?o.stack.length*2:0;return ie.error+u+l}if(typeof URL<"u"&&o instanceof URL)return ie.url+o.href.length*2;if(typeof Promise<"u"&&o instanceof Promise)return ie.promise;if(o instanceof WeakMap)return ie.weakmap;if(o instanceof WeakSet)return ie.weakset;if(o instanceof Map){let u=ie.map;for(let[l,h]of o)u+=ie.mapEntry,r.push(l),r.push(h);return u}if(o instanceof Set){let u=ie.set;for(let l of o)u+=ie.setEntry,r.push(l);return u}if(Array.isArray(o)){let u=ie.array+o.length*8;for(let l of o)r.push(l);return u}if(o instanceof ArrayBuffer)return n.has(o)?0:(n.add(o),o.byteLength);if(ArrayBuffer.isView(o)){let u=o;return n.has(u.buffer)?48:(n.add(u.buffer),u.buffer.byteLength+48)}let a=ie.object,d=Object.keys(o);for(let u of d){a+=ie.string+u.length*2;try{r.push(o[u])}catch{}}return a}function ss(t){let e=t<0n?-t:t;if(e===0n)return 0;let n=e.toString(2).length;return Math.ceil(n/32)*8}function $t(t,e){let n=e?.topN??10,r=t.describe({detail:"standard"}),s=[],o=t._collectObserveTargets;typeof o=="function"&&o.call(t,"",s);let i=new Map;for(let[c,p]of s)i.set(c,p);let a=[];for(let[c,p]of Object.entries(r.nodes)){let f=i.get(c),g=f instanceof se?f:null,b=g?gr(g.cache):0,v=g?g._sinkCount:0,T=p.deps?.length??0,y=p.type==="effect"&&v===0,w=v===0?p.type==="effect"?"orphan-effect":p.type==="derived"?"idle-derived":p.type==="producer"?"idle-producer":null:null;a.push({path:c,type:p.type,status:p.status??"unknown",valueSizeBytes:b,subscriberCount:v,depCount:T,isOrphanEffect:y,orphanKind:w})}let d=a.reduce((c,p)=>c+p.valueSizeBytes,0),u=(c,p)=>[...a].sort(p??((f,g)=>g[c]-f[c])).slice(0,n),l=a.filter(c=>c.orphanKind!=null),h=a.filter(c=>c.isOrphanEffect);return{nodeCount:a.length,edgeCount:r.edges.length,subgraphCount:r.subgraphs.length,nodes:a,totalValueSizeBytes:d,hotspots:{byValueSize:u("valueSizeBytes"),bySubscriberCount:u("subscriberCount"),byDepCount:u("depCount")},orphans:l,orphanEffects:h}}var te="::",ke="__meta__",We=1;function br(t,e){let n=Math.max(16,t.size*4),r=0;for(;t.size>0;){if(r++>=n){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${n}); ${t.size} disposer(s) discarded`),t.clear();return}let s=t.values().next();if(s.done)return;let o=s.value;t.delete(o);try{o()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function Tr(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"&&typeof t.down=="function"}function is(t){if(t!=null)return Tr(t)?t.cache:t}function as(t){let e=[];for(let n of Object.keys(t).sort()){let r=t[n].v;r!=null&&e.push(`${n} ${r.id} ${r.version}`)}return e.join(`
45
+ `)}function yr(t){if(t.version!==We)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${We})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in t))throw new Error(`snapshot missing required key "${e}"`);if(typeof t.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof t.nodes!="object"||t.nodes===null||Array.isArray(t.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(t.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(t.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function us(t,e){let n=new WeakMap,r=(s,o)=>{if(Object.is(s,o))return!0;if(s==null||o==null||typeof s!="object"||typeof o!="object")return!1;let i=n.get(s);if(i==null&&(i=new WeakSet,n.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 c=o;if(s.length!==c.length)return!1;for(let p=0;p<s.length;p++)if(!r(s[p],c[p]))return!1;return!0}if(s instanceof Map){let c=o;if(s.size!==c.size)return!1;for(let[p,f]of s)if(!c.has(p)||!r(f,c.get(p)))return!1;return!0}if(s instanceof Set){let c=o;if(s.size!==c.size)return!1;for(let p of s){let f=!1;for(let g of c)if(r(p,g)){f=!0;break}if(!f)return!1}return!0}if(ArrayBuffer.isView(s)){let c=s,p=o;if(c.length!==p.length)return!1;for(let f=0;f<c.length;f++)if(c[f]!==p[f])return!1;return!0}let u=Object.keys(s),l=Object.keys(o);if(u.length!==l.length)return!1;let h=new Set(l);for(let c of u)if(!h.has(c)||!r(s[c],o[c]))return!1;return!0};return r(t,e)}function gn(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(gn);let e=t,n=Object.keys(e).sort(),r={};for(let s of n)r[s]=gn(e[s]);return r}function ds(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function ls(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function cs(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function xr(t){let e=new Set,n=[];function r(s,o){let i=`${s}\0${o}`;e.has(i)||(e.add(i),n.push([s,o]))}for(let[s,o]of Object.entries(t.nodes)){let i=o.deps;if(i)for(let a of i)r(a,s)}for(let s of t.edges)r(s.from,s.to);return n}function wr(t){if(t===void 0)return"LR";if(t==="TD"||t==="LR"||t==="BT"||t==="RL")return t;throw new Error(`invalid diagram direction ${String(t)}; expected one of: TD, LR, BT, RL`)}function fs(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,{expand:s,...o}=t,i={...o,edges:n?t.edges:[],subgraphs:r?t.subgraphs:[]},a=JSON.stringify(gn(i),null,e.indent??2);return e.logger?.(a),a}function ps(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,s=[];s.push(`Graph ${t.name}`),s.push("Nodes:");for(let i of Object.keys(t.nodes).sort()){let a=t.nodes[i];s.push(`- ${i} (${a.type}/${a.status}): ${Ft(a.value)}`)}if(n){s.push("Edges:");for(let i of t.edges)s.push(`- ${i.from} -> ${i.to}`)}if(r){s.push("Subgraphs:");for(let i of t.subgraphs)s.push(`- ${i}`)}let o=s.join(`
46
+ `);return e.logger?.(o),o}function _r(t,e){let n=wr(e.direction),r=Object.keys(t.nodes).sort(),s=new Map;for(let i=0;i<r.length;i+=1)s.set(r[i],`n${i}`);let o=[`flowchart ${n}`];for(let i of r){let a=s.get(i);o.push(` ${a}["${ds(i)}"]`)}for(let[i,a]of xr(t)){let d=s.get(i),u=s.get(a);!d||!u||o.push(` ${d} --> ${u}`)}return o.join(`
47
+ `)}function hs(t,e){let n=_r(t,e);return Er(n)}function Er(t,e){let n=e?.theme??"default",r=e?.autoSync??!0,o=JSON.stringify({code:t,mermaid:{theme:n},autoSync:r}),i=new TextEncoder().encode(o),a="";for(let u=0;u<i.length;u++)a+=String.fromCharCode(i[u]);return`https://mermaid.live/edit#base64:${globalThis.btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function ms(t,e){let n=wr(e.direction),r=Object.keys(t.nodes).sort(),s=new Map;for(let i=0;i<r.length;i+=1)s.set(r[i],`n${i}`);let o=[`direction: ${cs(n)}`];for(let i of r){let a=s.get(i);o.push(`${a}: "${ls(i)}"`)}for(let[i,a]of xr(t)){let d=s.get(i),u=s.get(a);!d||!u||o.push(`${d} -> ${u}`)}return o.join(`
48
+ `)}function gs(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Vt(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){e+=".*";continue}if(r==="?"){e+=".";continue}if(r==="["){let s=t.indexOf("]",n+1);if(s<=n+1){e+="\\[";continue}let o=t.slice(n+1,s);o.startsWith("!")&&(o=`^${o.slice(1)}`),o=o.replace(/\\/g,"\\\\"),e+=`[${o}]`,n=s;continue}e+=gs(r)}return e+="$",new RegExp(e)}var bs={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"},ys={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function Ft(t){if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||t==null)return String(t);try{return JSON.stringify(t)}catch{return"[unserializable]"}}function vs(t){return t==="none"?ys:t==="ansi"||t==null?bs:{data:t.data??"",dirty:t.dirty??"",resolved:t.resolved??"",invalidate:t.invalidate??"",pause:t.pause??"",resume:t.resume??"",complete:t.complete??"",error:t.error??"",teardown:t.teardown??"",derived:t.derived??"",path:t.path??"",reset:t.reset??""}}function vr(t){if(t==null)return{};let e=t.detail;return e==="full"?{...t,structured:t.structured??!0,timeline:t.timeline??!0,causal:t.causal??!0,derived:t.derived??!0}:e==="minimal"?{...t,structured:t.structured??!0}:t.format==="stage-log"?{...t,structured:t.structured??!0,timeline:t.timeline??!0}:t}function Ts(t,e,n){for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);if(s<32||s===127)throw new Error(`Graph "${e}": ${n} "${t}" must not contain control character (U+${s.toString(16).padStart(4,"0").toUpperCase()} at index ${r})`)}}function mn(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(te))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${te}' (path separator)`);if(t===ke)throw new Error(`Graph "${e}": ${n} name "${ke}" is reserved for meta companion paths`);Ts(t,e,n)}function xs(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(te);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function ws(t,e){let n=!1;for(let s of t)if(!e.isMetaPassthrough(s[0])){n=!0;break}return n?t.filter(s=>e.isMetaPassthrough(s[0])):t}function Nr(t){for(let e of t._mounts.values())Nr(e);for(let e of t._nodes.values())try{e.down([[me]],{internal:!0})}catch{}}var ce=class t{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;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(te))throw new Error(`Graph name must not contain '${te}' (got "${e}")`);if(e===ke)throw new Error(`Graph name "${ke}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??Ze,this._traceRing=new pt(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning)}ancestors(e=!0){let n=[],r=e?this:this._parent;for(;r!=null;)n.push(r),r=r._parent;return n}get topology(){return this._topology==null&&(this._topology=he(e=>{let n=r=>{e.emit(r)};return this._topologyEmitters.add(n),()=>{this._topologyEmitters.delete(n)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let n of this._topologyEmitters)n(e)}nameOf(e){return this._nodeToName.get(e)}add(e,n){let r=e.name,s=n?.name??r;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=n?.annotation;if(mn(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:ee()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof se&&n._applyVersioning(e)}remove(e){mn(e,this.name,"remove");let n=this._mounts.get(e);if(n){let o={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,d]of i)a.includes(`${te}${ke}${te}`)||o.nodes.push(a);return o.nodes.sort(),o.mounts.push(e),o.mounts.push(...n._collectSubgraphs(`${e}${te}`)),this._mounts.delete(e),n._parent=void 0,Nr(n),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:o}),o}let r=this._nodes.get(e);if(!r)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(r),r.down([[me]],{internal:!0});let s={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:s}),s}removeAll(e){let n=typeof e=="function"?e:(()=>{let o=Vt(e);return i=>o.test(i)})(),r={kind:"mount",nodes:[],mounts:[]},s=[...this._nodes.keys(),...this._mounts.keys()].filter(o=>n(o));for(let o of s){let i=this.remove(o);r.nodes.push(...i.nodes),r.mounts.push(...i.mounts)}return r.nodes.sort(),r.mounts.sort(),r}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),n=this._nodes,r=0;return{[Symbol.iterator](){return this},next(){if(r>=e.length)return{value:void 0,done:!0};let s=e[r++];return{value:[s,n.get(s)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(te))return this.resolve(e);let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return n}get(e){return this.node(e).cache}set(e,n,r){let s=r?.internal===!0;this.node(e).down([[I,n]],{actor:r?.actor,internal:s,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);re(()=>{for(let[s,o]of r)this.set(s,o,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[Ee]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let s=r?.internal===!0;this.node(e).down([[L,n]],{actor:r?.actor,internal:s,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[j]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[d,u]of this._nodes)r.set(u,d);let a=[];for(let[d,u]of this._nodes)if(u instanceof se)for(let l of u._deps){let h=r.get(l.node);h!=null&&a.push([h,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 se)for(let u of d._deps){let l=o.get(u.node);l!=null&&i.push([l,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,n){if(n===void 0){let s=new t(e);return this.mount(e,s)}if(typeof n=="function"){let s=new t(e);return n(s),this.mount(e,s)}let r=n;if(mn(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(r===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(r._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${r._parent.name}"`);for(let s=this;s!=null;s=s._parent)if(s===r)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,r),r._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),r}resolve(e){let n=xs(e,this.name);return this._resolveFromSegments(n)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let n=e;if(n[0]===this.name&&(n=n.slice(1),n.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let r=n[0],s=n.slice(1);if(s.length===0){let a=this._nodes.get(r);if(a)return a;throw this._mounts.has(r)?new Error(`Graph "${this.name}": path ends at subgraph "${r}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${r}"`)}let o=this._nodes.get(r);if(o&&s.length>0&&s[0]===ke)return this._resolveMetaChainFromNode(o,s,n.join(te));let i=this._mounts.get(r);if(!i)throw this._nodes.has(r)?new Error(`Graph "${this.name}": "${r}" is a node; trailing path "${s.join(te)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(s.join(te))}_resolveMetaChainFromNode(e,n,r){let s=e,o=0,i=[...n];for(;o<i.length;){if(i[o]!==ke)throw new Error(`Graph "${this.name}": expected ${ke} segment in meta path "${r}"`);if(o+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${ke} in "${r}"`);let a=i[o+1],d=s.meta[a];if(!d)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);s=d,o+=2}return s}signal(e,n){if(n?.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 r=[];if(this._signalDeliver(e,n??{},new Set,r),r.length>0)throw r[0]}_signalDeliver(e,n,r,s){for(let d of this._mounts.values())d._signalDeliver(e,n,r,s);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=ws(e,this.config);for(let d of[...this._nodes.keys()].sort()){let u=this._nodes.get(d);if(!r.has(u)){r.add(u);try{u.down(e,i)}catch(l){if(l instanceof Ne)throw l;s.push(l)}a.length!==0&&this._signalMetaSubtree(u,a,r,i,s)}}}_signalMetaSubtree(e,n,r,s,o){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!r.has(a)){r.add(a);try{a.down(n,s)}catch(d){if(d instanceof Ne)throw d;o.push(d)}this._signalMetaSubtree(a,n,r,s,o)}}}describe(e){if(e?.reactive===!0)return this._describeReactive(e);let n=is(e?.actor),r=e?.filter,s=At(e?.detail,e?.fields),o=e?.format==="spec",i=o?At("minimal"):s,a=[];this._collectObserveTargets("",a);let d=new Map;for(let[_,m]of a)d.set(m,_);let u=[];{let _=a.map(([,E])=>E),m=new Set(d.values()),x=0;for(;_.length>0;){let E=_.shift();if(E instanceof se)for(let A of E._deps){let k=A.node;if(d.has(k))continue;let S=k.name??"",C=S;if(!C||m.has(C))if(S){let B=2;for(;m.has(`${S}#${B}`);)B++;C=`${S}#${B}`}else for(C=`__internal__/${x++}`;m.has(C);)C=`__internal__/${x++}`;d.set(k,C),m.add(C),u.push([C,k]),_.push(k)}}}let l=[...a,...u],h={};for(let[_,m]of l){if(n!=null&&!m.allowsObserve(n))continue;let x=pn(m,i),E=m instanceof se?m._deps.map(C=>d.get(C.node)??C.node.name??""):[],{name:A,...k}=x,S={...k,deps:E};if(!o){let C=this._annotations.get(_);C!=null&&(S.annotation=C)}if(r!=null)if(typeof r=="function"){let C=r;if(!(C.length>=2?C(_,S):C(S)))continue}else{let C=!0;for(let[B,Y]of Object.entries(r)){let W=B==="deps_includes"?"depsIncludes":B==="meta_has"?"metaHas":B;if(W==="depsIncludes"){if(!S.deps.includes(String(Y))){C=!1;break}continue}if(W==="metaHas"){if(!Object.hasOwn(S.meta??{},String(Y))){C=!1;break}continue}if(S[W]!==Y){C=!1;break}}if(!C)continue}h[_]=S}let c=new Set(Object.keys(h)),p=[];for(let[_,m]of l)if(m instanceof se)for(let x of m._deps){let E=d.get(x.node);E!=null&&p.push([E,_])}p.sort((_,m)=>_[0]<m[0]?-1:_[0]>m[0]?1:_[1]<m[1]?-1:_[1]>m[1]?1:0);let f=p.map(([_,m])=>({from:_,to:m}));(n!=null||r!=null)&&(f=f.filter(_=>c.has(_.from)&&c.has(_.to)));let g=this._collectSubgraphs(""),b=n!=null||r!=null?g.filter(_=>{let m=`${_}${te}`;return[...c].some(x=>x===_||x.startsWith(m))}):g,v=this,T=e,y={name:this.name,nodes:h,edges:f,subgraphs:b,expand(_){let m={...T,format:void 0};return Array.isArray(_)?(m.fields=_,m.detail=void 0):(m.detail=_,m.fields=void 0),v.describe(m)}},w=e??{},N=w.format;return N==="json"?fs(y,w):N==="pretty"?ps(y,w):N==="mermaid"?_r(y,w):N==="mermaid-url"?hs(y,w):N==="d2"?ms(y,w):N==="ascii"?cr(y,w):y}_collectSubgraphs(e){let n=[];for(let r of[...this._mounts.keys()].sort()){let s=e===""?r:`${e}${r}`;n.push(s),n.push(...this._mounts.get(r)._collectSubgraphs(`${s}${te}`))}return n}resourceProfile(e){return $t(this,e)}reachable(e,n,r={}){return r.withDetail===!0?bn(this.describe(),e,n,{...r,withDetail:!0}):bn(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(e,n,r)}_explainStatic(e,n,r){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 fr(s,e,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:o,lastMutations:i})}_describeReactive(e){let n={...e,reactive:!1},r=e.reactiveName??"describe",s=0,o=V(s,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,dt(()=>{a=!1,!d&&(s+=1,o.emit(s))}))},l=i.onEvent(T=>{let y=T.type;y!=="data"&&y!=="error"&&y!=="complete"&&y!=="teardown"||u()}),h=[],c=new WeakSet,p=T=>{if(c.has(T)||d)return;c.add(T);let y=T.topology.subscribe(w=>{for(let N of w){if(N[0]!==I)continue;let _=N[1];if(u(),_.kind==="added"&&_.nodeKind==="mount"){let m=T._mounts.get(_.name);m!=null&&p(m)}}});h.push(y);for(let w of T._mounts.keys()){let N=T._mounts.get(w);N!=null&&p(N)}};p(this);let f,g=e.actor;Tr(g)&&(f=g.subscribe(T=>{let y=!1,w=!1;for(let N of T){let _=N[0];_===I?y=!0:(_===j||_===L||_===me)&&(w=!0)}y&&u(),w&&(f?.(),f=void 0,u())}));let b;try{b=G([o],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(T,y)=>T===y})}catch(T){l(),f?.();for(let y of h)y();throw i.dispose(),T}let v=Te(b);return{node:b,dispose(){d=!0,l(),f?.();for(let T of h)T();h.length=0,i.dispose(),v()}}}_explainReactive(e,n,r){let s=0,o=V(s,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=i.onEvent(p=>{let f=p.type;f!=="data"&&f!=="error"&&f!=="complete"&&f!=="teardown"||a||d||(a=!0,dt(()=>{a=!1,!d&&(s+=1,o.emit(s))}))}),l={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},h;try{h=G([o],()=>this._explainStatic(e,n,l),{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:e,to:n},equals:(p,f)=>p.found===f.found&&p.reason===f.reason&&p.steps.length===f.steps.length&&_s(p.steps,f.steps)})}catch(p){throw u(),i.dispose(),p}let c=Te(h);return{node:h,dispose(){d=!0,u(),i.dispose(),c()}}}_pathsMatching(e){let n=Vt(e),r=[];return this._collectObserveTargets("",r),r.map(([s])=>s).filter(s=>n.test(s))}_collectObserveTargets(e,n){for(let r of[...this._mounts.keys()].sort()){let s=e===""?r:`${e}${te}${r}`;this._mounts.get(r)._collectObserveTargets(s,n)}for(let r of[...this._nodes.keys()].sort()){let s=this._nodes.get(r),o=e===""?r:`${e}${te}${r}`;n.push([o,s]),this._appendMetaObserveTargets(o,s,n)}}_appendMetaObserveTargets(e,n,r){for(let s of Object.keys(n.meta).sort()){let o=n.meta[s],i=`${e}${te}${ke}${te}${s}`;r.push([i,o]),this._appendMetaObserveTargets(i,o,r)}}observe(e,n){let r=typeof e=="string",o=vr(r?n:e),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(r){let l=e,h=this.resolve(l);if(a!=null&&!h.allowsObserve(a))throw new Ne({actor:a,action:"observe",nodeName:l});return i?this._buildStructuredObserver([[l,h]],o,"one"):{subscribe(c){return h.subscribe(c)},up(c){try{h.up?.(c)}catch(p){if(p instanceof Ne)return;throw p}}}}let d=[];this._collectObserveTargets("",d),d.sort((l,h)=>l[0]<h[0]?-1:l[0]>h[0]?1:0);let u=a==null?d:d.filter(([,l])=>l.allowsObserve(a));return i?this._buildStructuredObserver(u,o,"all"):{subscribe:l=>{let h=u.map(([c,p])=>p.subscribe(f=>{l(c,f)}));return()=>{for(let c of h)c()}},up:(l,h)=>{try{this.resolve(l).up?.(h)}catch(c){if(c instanceof Ne)return;throw c}}}}_buildStructuredObserver(e,n,r){let s=r==="one"?e[0]?.[0]:void 0,o=i=>{if(r==="one"&&s!=null){let l=this.resolve(s);return this._buildStructuredObserver([[s,l]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((l,h)=>l[0]<h[0]?-1:l[0]>h[0]?1:0);let d=i.actor,u=d==null?a:a.filter(([,l])=>l.allowsObserve(d));return this._buildStructuredObserver(u,i,"all")};return this._createObserveResult(e,n,o)}_createObserveResult(e,n,r){let s=n.timeline===!0,o=n.causal===!0,i=n.derived===!0,a=n.detail==="minimal",d=this.config.inspectorEnabled,u=(o||i)&&d,l=n.maxEvents,h=l!=null&&l>0?new pt(l):null,c=[],p=new Set,f={},g=new Set,b=0,v=0,T=0,y=0,w=0,N=0,_=!1,m=!1,x=0,E=new Map,A=new Map,k=new Map,S=O=>{h?h.push(O):c.push(O);for(let z of p)z(O)},C=()=>s?{timestamp_ns:ee(),in_batch:ut(),batch_id:x}:{},B=(O,z)=>{if(!(!u||!(O instanceof se)))return O._setInspectorHook(ae=>{if(ae.kind==="dep_message")E.set(O,ae.depIndex);else if(ae.kind==="run"){let Me=ae.batchData.map((q,ue)=>q!=null&&q.length>0?q.at(-1):ae.prevData[ue]);A.set(O,Me);let fe=ae.batchData.map(q=>q!=null?[...q]:void 0);k.set(O,fe),i&&S({type:"derived",path:z,dep_values:Me,dep_batches:fe,...C()})}})},Y=O=>{let z=E.get(O),ae=A.get(O);if(!o||ae==null)return{};let fe=(z!=null&&z>=0&&O instanceof se?O._deps[z]:void 0)?.node,q=fe?.v,ue=k.get(O);return{trigger_dep_index:z,trigger_dep_name:fe?.name,...q!=null?{trigger_version:{id:q.id,version:q.version}}:{},dep_values:[...ae],...ue!=null?{dep_batches:ue}:{}}},W=[],ye=[];for(let[O,z]of e){let ae=B(z,O);ae&&W.push(ae),ye.push(z.subscribe(Me=>{x++;for(let fe of Me){let q=fe[0],ue=C();if(q===I){f[O]=fe[1];let D=z instanceof se?z.lastMutation?.actor??Je:Je;S({type:"data",path:O,data:fe[1],actor:D,...ue,...Y(z)})}else if(a)q===X?b++:q===Z?v++:q===Ee?T++:q===Se?y++:q===Pe?w++:q===me?N++:q===j&&!g.has(O)?_=!0:q===L&&(m=!0,g.add(O));else if(q===X)b++,S({type:"dirty",path:O,...ue});else if(q===Z)v++,S({type:"resolved",path:O,...ue,...Y(z)});else if(q===Ee)T++,S({type:"invalidate",path:O,...ue});else if(q===Se)y++,S({type:"pause",path:O,lockId:fe[1],...ue});else if(q===Pe)w++,S({type:"resume",path:O,lockId:fe[1],...ue});else if(q===j)g.has(O)||(_=!0),S({type:"complete",path:O,...ue});else if(q===L){m=!0,g.add(O);let D=z instanceof se?z.lastMutation?.actor??Je:Je;S({type:"error",path:O,data:fe[1],actor:D,...ue})}else q===me&&(N++,S({type:"teardown",path:O,...ue}))}}))}let Oe=!1,$=()=>{if(!Oe){Oe=!0;for(let O of ye)O();for(let O of W)O();for(let O of P)O({value:void 0,done:!0});P.length=0}},F=[],P=[];p.add(O=>{let z=P.shift();z?z({value:O,done:!1}):F.push(O)});let le={get values(){return f},get dirtyCount(){return b},get resolvedCount(){return v},get invalidateCount(){return T},get pauseCount(){return y},get resumeCount(){return w},get teardownCount(){return N},get events(){return h?h.toArray():[...c]},get anyCompletedCleanly(){return _},get anyErrored(){return m},get completedWithoutErrors(){return _&&!m},onEvent(O){return p.add(O),()=>p.delete(O)},dispose:$,expand(O){$();let z={...n};return typeof O=="string"?z.detail=O:Object.assign(z,O),r(vr(z))},[Symbol.asyncIterator](){return{next(){return F.length>0?Promise.resolve({value:F.shift(),done:!1}):Oe?Promise.resolve({value:void 0,done:!0}):new Promise(O=>P.push(O))},return(){return $(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(le,n),le}_attachFormatLogger(e,n){let r=n.format;if(r==null)return;let s=n.logger??(f=>console.log(f)),o=n.includeTypes?new Set(n.includeTypes):null,i=n.excludeTypes?new Set(n.excludeTypes):null,a=o==null&&i==null?()=>!0:f=>(o==null||o.has(f))&&(i==null||!i.has(f)),d=vs(n.theme),u=r==="stage-log"?ee():0,l=f=>f==null?"":n.stageLabels?.[f]??f,h=(f,g)=>f.length>g?`${f.slice(0,g-1)}\u2026`:f,c=f=>f.type==="data"||f.type==="error"?h(Ft(f.data),120):"",p=f=>{if(r==="stage-log"){let m=(ee()-u)/1e9,x=l(f.path).padEnd(9);if(f.type==="data"){let E=c(f);return`[${m.toFixed(3)}s] ${x} \u2190${E?` ${E}`:""}`}if(f.type==="error"){let E=c(f);return`[${m.toFixed(3)}s] ${x} \u2717${E?` ${E}`:""}`}return f.type==="complete"?`[${m.toFixed(3)}s] ${x} \u25A0 complete`:`[${m.toFixed(3)}s] ${x} ${f.type}`}if(r==="json")try{return JSON.stringify(f)}catch{return JSON.stringify({type:f.type,path:f.path,data:"[unserializable]"})}let g=d[f.type]??"",b=f.path?`${d.path}${f.path}${d.reset} `:"",v=f.type==="data"||f.type==="error",T=f.type==="pause"||f.type==="resume",y=v?` ${Ft(f.data)}`:T?` ${Ft(f.lockId)}`:"",w=f.type==="data"||f.type==="resolved"||f.type==="derived"?f:void 0,N=w?.trigger_dep_name!=null?` <- ${w.trigger_dep_name}`:w?.trigger_dep_index!=null?` <- #${w.trigger_dep_index}`:"",_=f.in_batch?" [batch]":"";return`${b}${g}${f.type.toUpperCase()}${d.reset}${y}${N}${_}`};e.onEvent(f=>{a(f.type)&&s(p(f),f)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){br(this._disposers,this.name),this.signal([[me]],{internal:!0}),br(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:n,...r}=this.describe({detail:"full"}),s={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:d,guard:u,...l}=r.nodes[a];s[a]=l}let o=[...r.subgraphs].sort(),i={...r,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 Pn(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??Ze,{codec:s,codecVersion:o,payload:i}=$n(e,r);return s.decode(i,o)}restore(e,n){if(yr(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let r=n?.only==null?null:(Array.isArray(n.only)?n.only:[n.only]).map(o=>Vt(o)),s=n?.includeProducers===!0;for(let o of Object.keys(e.nodes).sort()){if(r!==null&&!r.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&&n?.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){n?.onError?.(o,a)}}}}}static fromSnapshot(e,n){yr(e);let r=typeof n=="function"?n:n?.build,s=typeof n=="function"?void 0:n?.factories,o=new t(e.name);if(r)return r(o),o.restore(e),o;for(let p of[...e.subgraphs].sort((f,g)=>{let b=f.split(te).length,v=g.split(te).length;return b!==v?b-v:f<g?-1:f>g?1:0})){let f=p.split(te),g=o;for(let b of f)g._mounts.has(b)||g.mount(b,new t(b)),g=g._mounts.get(b)}let i=s?Object.entries(s).map(([p,f])=>({re:Vt(p),factory:f})):[],a=p=>{for(let f of i)if(f.re.test(p))return f.factory},d=p=>{let f=p.split(te),g=f.pop();if(g==null||g.length===0)throw new Error(`invalid snapshot path "${p}"`);let b=o;for(let v of f){let T=b._mounts.get(v);if(!T)throw new Error(`unknown mount "${v}" in path "${p}"`);b=T}return[b,g]},u=Object.entries(e.nodes).filter(([p])=>!p.includes(`${te}${ke}${te}`)).sort((p,f)=>p[0]<f[0]?-1:p[0]>f[0]?1:0),l=new Map(u),h=new Map,c=!0;for(;l.size>0&&c;){c=!1;for(let[p,f]of[...l.entries()]){let g=f?.deps??[];if(!g.every(N=>h.has(N)))continue;let[b,v]=d(p),T={...f?.meta??{}},y=a(p),w;if(f?.type==="state")w=V(f.value,{meta:T});else{if(y==null)continue;w=y(v,{path:p,type:f.type,value:f.value,meta:T,deps:g,resolvedDeps:g.map(N=>h.get(N))})}b.add(w,{name:v}),h.set(p,w),l.delete(p),c=!0}}if(l.size>0){let p=[...l.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${p}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return o.restore(e),o}toJSON(){return this.snapshot()}attachSnapshotStorage(e,n={}){let r=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}));n.autoRestore===!0&&this._cascadeRestore(e,n.onError);let s=(u,l)=>{if(u.disposed)return;let h=as(l.nodes);if(u.lastSnapshot!=null&&h!==""&&h===u.lastFingerprint)return;let c=u.seq+1,p=be(),b=u.lastSnapshot==null||c%u.compactEvery===0?{name:this.name,mode:"full",snapshot:l,seq:c,timestamp_ns:p,format_version:We}:{name:this.name,mode:"diff",diff:Rr(u.lastSnapshot,l),seq:c,timestamp_ns:p,format_version:We};if(u.tier.filter&&!u.tier.filter(b))return;let v;try{v=u.tier.save(b)}catch(T){n.onError?.(T,u.tier);return}if(v&&typeof v.then=="function"){let w=(u.savePending??Promise.resolve()).then(()=>v,()=>v).then(()=>{u.disposed||(u.seq=c,u.lastSnapshot=l,u.lastFingerprint=h)},N=>{n.onError?.(N,u.tier)});u.savePending=w.finally(()=>{u.savePending===w&&(u.savePending=void 0)})}else u.seq=c,u.lastSnapshot=l,u.lastFingerprint=h},o=(u,l)=>{try{s(u,l)}catch(h){n.onError?.(h,u.tier)}},i=(u,l)=>{if(!l.some(f=>{let g=this.config.messageTier(f[0]);return g>=3&&g<5}))return;if(n.filter){let f=this.tryResolve(u);if(f==null)return;let g=pn(f,At("standard"));if(!n.filter(u,g))return}let c,p=()=>(c==null&&(c=this.snapshot()),c);for(let f of r)f.disposed||(f.debounceMs===0?o(f,p()):(f.timer==null&&(f.timer=new Ct),f.timer.start(f.debounceMs,()=>{f.disposed||o(f,this.snapshot())})))},a;if(n.paths!=null){let l=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(h=>{let c=this.tryResolve(h);return c==null?()=>{}:c.subscribe(p=>i(h,p))});a=()=>{for(let h of l)h()}}else a=this.observe().subscribe((u,l)=>i(u,l));let d=()=>{a();for(let u of r)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(d)};return this._storageDisposers.add(d),{dispose:d}}async _cascadeRestore(e,n){for(let r of e){let s;try{s=await r.load?.()}catch(i){n?.(i,r);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===We&&o.nodes!=null)return this.restore(o),!0}catch(i){n?.(i,r)}}return!1}static async fromStorage(e,n,r){for(let s of n){let o;try{o=await s.load?.()}catch(d){r?.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===We&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(d){r?.onError?.(d,s)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${n.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,n,r){if(e!=null&&n!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,n),this.config.inspectorEnabled){let s={path:e,annotation:n,timestamp_ns:ee(),...r?.actor!=null?{actor:r.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 n=this._traceRing.toArray().filter(s=>!e(s)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let s of n)this._traceRing.push(s);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),s=new Set(Object.keys(n.nodes)),o=[...s].filter(T=>!r.has(T)).sort(),i=[...r].filter(T=>!s.has(T)).sort(),a=[],d=[];for(let T of r){if(!s.has(T))continue;let y=e.nodes[T],w=n.nodes[T],N=y.v,_=w.v;N!=null&&_!=null&&N.id===_.id&&N.version!==_.version&&d.push({path:T,id:N.id,from:N.version,to:_.version});let m=N!=null&&_!=null&&N.id===_.id&&N.version===_.version;for(let x of["type","status","sentinel"]){let E=y[x],A=w[x];E!==A&&a.push({path:T,field:x,from:E,to:A})}if(!m)for(let x of["value","meta"]){let E=y[x],A=w[x];us(E,A)||a.push({path:T,field:x,from:E,to:A})}}let u=T=>`${T.from} ${T.to}`,l=new Set(e.edges.map(u)),h=new Set(n.edges.map(u)),c=n.edges.filter(T=>!l.has(u(T))),p=e.edges.filter(T=>!h.has(u(T))),f=new Set(e.subgraphs),g=new Set(n.subgraphs),b=[...g].filter(T=>!f.has(T)).sort(),v=[...f].filter(T=>!g.has(T)).sort();return{nodesAdded:o,nodesRemoved:i,nodesChanged:a,versionChanges:d,edgesAdded:c,edgesRemoved:p,subgraphsAdded:b,subgraphsRemoved:v}}};function Rr(t,e){let n=ce.diff(t,e),r={};for(let s of n.nodesAdded){let o=e.nodes[s];o!=null&&(r[s]=o)}return{...n,nodesAddedFull:r}}function bn(t,e,n,r={}){let s={paths:[],depths:new Map,truncated:!1};if(!e)return r.withDetail?s:[];if(!r.both&&n!=="upstream"&&n!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let o=r.maxDepth;if(o!=null&&(!Number.isInteger(o)||o<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(o===0)return r.withDetail?s:[];let i=new Map,a=new Map,d=new Map,u=new Map,l=new Set;for(let[y,w]of Object.entries(t.nodes)){if(!y)continue;l.add(y);let N=w.deps??[];i.set(y,N);for(let _ of N)_&&(l.add(_),a.has(_)||a.set(_,new Set),a.get(_).add(y))}for(let y of t.edges){if(y==null||typeof y!="object")continue;let w=typeof y.from=="string"?y.from:"",N=typeof y.to=="string"?y.to:"";!w||!N||(l.add(w),l.add(N),u.has(w)||u.set(w,new Set),u.get(w).add(N),d.has(N)||d.set(N,new Set),d.get(N).add(w))}if(!l.has(e))return r.withDetail?s:[];let h=r.both===!0,c=y=>{if(h){let m=i.get(y)??[],x=d.get(y),E=a.get(y),A=u.get(y),k=[...m];return x&&k.push(...x),E&&k.push(...E),A&&k.push(...A),k}if(n==="upstream"){let m=i.get(y)??[],x=d.get(y);return x?[...m,...x]:m}let w=a.get(y),N=u.get(y),_=w?[...w]:[];return N&&_.push(...N),_},p=new Set([e]),f=new Map,g=[{path:e,depth:0}],b=0,v=!1;for(;b<g.length;){let y=g[b++];if(o!=null&&y.depth>=o){c(y.path).length>0&&(v=!0);continue}for(let w of c(y.path))!w||p.has(w)||(p.add(w),f.set(w,y.depth+1),g.push({path:w,depth:y.depth+1}))}let T=[...f.keys()].sort((y,w)=>y<w?-1:y>w?1:0);return r.withDetail?{paths:T,depths:f,truncated:v}:T}function _s(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],s=e[n];if(r.path!==s.path||r.type!==s.type||r.status!==s.status||r.hop!==s.hop||r.dep_index!==s.dep_index||r.annotation!==s.annotation||r.value!==s.value||r.lastMutation!==s.lastMutation)return!1;let o=r.v,i=s.v;if(o!==i&&(o==null||i==null||o.id!==i.id||o.version!==i.version))return!1}return!0}Et();De();Xe();pe();de();Ce();De();pe();Ce();de();var yn=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,n){if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=n,n!==void 0){if(this._buf=new Array(n),e&&e.length>0){let r=Math.min(e.length,n),s=e.length-r;for(let o=0;o<r;o++)this._buf[o]=e[s+o];this._size=r}}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 n=e>=0?e:this._size+e;if(!(n<0||n>=this._size))return this._maxSize!==void 0?this._buf[(this._head+n)%this._maxSize]:this._buf[n]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let r=n;r<e.length;r++)this._rawAppend(e[r]);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 n=0;n<e;n++)this._buf[(this._head+n)%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 n=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,n);else{for(let r=0;r<n;r++)this._buf[(this._head+r)%this._maxSize]=void 0;this._head=(this._head+n)%this._maxSize}return this._size-=n,this._version+=1,n}slice(e,n){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${n})`);let r=n===void 0?this._size:Math.min(Math.max(n,0),this._size),s=Math.min(e,this._size);if(s>=r)return[];let o=r-s;if(this._maxSize===void 0)return this._buf.slice(s,r);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 n=Math.min(e,this._size);return this.slice(this._size-n,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this._buf[(this._head+n)%this._maxSize];return e}snapshot(){return this.toArray()}restore(e){if(this._maxSize===void 0){this._buf.length=0;for(let n=0;n<e.length;n++)this._buf.push(e[n]);this._size=this._buf.length}else{let n=this._maxSize;for(let o=0;o<n;o++)this._buf[o]=void 0;this._head=0;let r=Math.min(e.length,n),s=e.length-r;for(let o=0;o<r;o++)this._buf[o]=e[s+o];this._size=r}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 ht(t){return t.subscribe(()=>{})}var Es=64;function jt(t,e={}){let{name:n,maxSize:r,versioning:s,guard:o,backend:i}=e,a=i??new yn(t,r),d=V(a.toArray(),{name:n,describeKind:"state",equals:(m,x)=>m===x,...s!=null?{versioning:s}:{},...o!=null?{guard:o}:{}});function u(){let m=a.toArray();re(()=>{d.down([[X]],{internal:!0}),d.down([[I,m]],{internal:!0})})}let l=new Map,h=new Map,c=new Map;function p(m,x){return`${m}:${x===void 0?"END":x}`}function f(m){if(m.size<Es)return;let x=m.keys().next();if(x.done)return;let E=m.get(x.value);E!==void 0&&E.dispose(),m.delete(x.value)}function g(m){let x=a.version;try{return m()}finally{a.version!==x&&u()}}function b(m){if(!Number.isInteger(m)||m<0)throw new RangeError(`tail: n must be a non-negative integer (got ${m})`);let x=l.get(m);if(x!==void 0)return l.delete(m),l.set(m,x),x.node;f(l);let E=G([d],([k])=>{let S=k;return m===0||S.length===0?[]:S.slice(Math.max(0,S.length-m))},{initial:a.tail(m),describeKind:"derived"}),A=ht(E);return l.set(m,{node:E,dispose:A}),E}function v(m,x){if(!Number.isInteger(m)||m<0)throw new RangeError(`slice: start must be a non-negative integer (got ${m})`);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 E=p(m,x),A=h.get(E);if(A!==void 0)return h.delete(E),h.set(E,A),A.node;f(h);let k=G([d],([C])=>{let B=C;return x===void 0?B.slice(m):B.slice(m,x)},{initial:a.slice(m,x),describeKind:"derived"}),S=ht(k);return h.set(E,{node:k,dispose:S}),k}function T(m){let x=c.get(m);if(x!==void 0)return x.node;let E=G([d,m],([k,S])=>{let C=k,B=Math.max(0,Math.trunc(S??0));return C.slice(B)},{initial:[],describeKind:"derived"}),A=ht(E);return c.set(m,{node:E,dispose:A}),E}let y,w;function N(){y===void 0&&(y=oe([d],(m,x,E)=>{let A=m[0],S=A!=null&&A.length>0?A.at(-1):E.prevData[0];if(S==null||S.length===0){x.down([[Z]]);return}x.emit(S[S.length-1])},{name:n!=null?`${n}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),w=G([d],([m])=>m.length>0,{name:n!=null?`${n}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),ht(y),ht(w))}let _={entries:d,get size(){return a.size},at(m){return a.at(m)},append(m){g(()=>a.append(m))},appendMany(m){m.length!==0&&g(()=>a.appendMany(m))},clear(){g(()=>a.clear())},trimHead(m){g(()=>a.trimHead(m))},withLatest(){return N(),d},get lastValue(){return N(),y},get hasLatest(){return N(),w},view(m){switch(m.kind){case"tail":return b(m.n);case"slice":return v(m.start,m.stop);case"fromCursor":return T(m.cursor)}},attach(m){let x=m.subscribe(E=>{for(let A of E)A[0]===I&&_.append(A[1])});return()=>x()},attachStorage(m){if(m.length===0)return()=>{};let x=new Map;for(let A of m)x.set(A,a.size);(async()=>{for(let A of m)if(typeof A.loadEntries=="function")try{let k=await Promise.resolve(A.loadEntries());k.entries.length>0&&a.size===0&&(a.restore(k.entries),x.set(A,k.entries.length),u());break}catch{}})();let E=d.subscribe(A=>{for(let k of A){if(k[0]!==I)continue;let S=k[1];for(let C of m){let B=x.get(C)??0;if(S.length<B){try{let W=C.appendEntries(S);W instanceof Promise&&W.catch(()=>{})}catch{}x.set(C,S.length);continue}if(S.length===B)continue;let Y=S.slice(B);x.set(C,S.length);try{let W=C.appendEntries(Y);W instanceof Promise&&W.catch(()=>{})}catch{}}}});return()=>E()},disposeAllViews(){for(let m of l.values())m.dispose();l.clear();for(let m of h.values())m.dispose();h.clear();for(let m of c.values())m.dispose();c.clear()},dispose(){for(let m of l.values())m.dispose();l.clear();for(let m of h.values())m.dispose();h.clear();for(let m of c.values())m.dispose();c.clear()}};return _}pe();Ue();function vn(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[X],[I,n+1]]),!0)}function je(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function mt(t){return t.relatedTo?.[0]??t.summary}var Ns=256;function rt(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function ze(t,e){return je("messaging",t,e)}var Rs=1024,Tn=class extends ce{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=jt([],{name:"events",maxSize:n.retainedLimit??Rs}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=G([this.events],([r])=>{let s=r;return s.length===0?null:s[s.length-1]},{name:"latest",describeKind:"derived",meta:ze("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(Te(this.latest)),this.hasLatest=G([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:ze("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(Te(this.hasLatest)),this.addDisposer(()=>{this.events.down([[j]])}),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}},zt=class extends ce{cursor;available;topic;_disposed=!1;constructor(e,n,r={}){super(e,r.graph),this.topic=n;let s;if(r.from!==void 0?r.from==="retained"?s=0:r.from==="now"?s=n.events.cache.length:s=rt(r.from,"subscription from"):s=rt(r.cursor??0,"subscription cursor"),this.cursor=V(s,{name:"cursor",describeKind:"state",meta:ze("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=n._logBundle.view({kind:"fromCursor",cursor:this.cursor}),this.add(this.available,{name:"available"}),this.addDisposer(Te(this.available)),r.advanceOn!==void 0){let o=r.advanceOn,i=!1,a=oe([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:ze("subscription_advance_pump")});this.add(a,{name:"advancePump"}),this.addDisposer(Te(a))}}ack(e){if(this._disposed)return this.cursor.cache;let n=this.available.cache,r=e===void 0?n.length:rt(e,"subscription ack count"),s=Math.min(r,n.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 n=this.available.cache,r=e===void 0?n.length:rt(e,"subscription pull limit");return n.slice(0,r)}pullAndAck(e){if(this._disposed)return{items:[],cursor:this.cursor.cache};let n=this.available.cache,r=e===void 0?n.length:rt(e,"subscription pullAndAck limit"),s=n.slice(0,r);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([[j]]),this.destroy())}},xn=class extends ce{_sourceSub;bridgedCount;output;constructor(e,n,r,s={}){super(e,s.graph),this._sourceSub=Os(`${e}-subscription`,n,{cursor:s.cursor}),this.mount("subscription",this._sourceSub);let o=Math.max(1,rt(s.maxPerPump??Ns,"topic bridge maxPerPump")),i=s.map??(c=>c);this.output=G([this._sourceSub.available],([c])=>{let p=c,f=[],g=Math.min(p.length,o);for(let b=0;b<g;b++){let v=i(p[b]);v!==void 0&&f.push(v)}return f},{name:"output",describeKind:"derived",meta:ze("topic_bridge_output",{targetRef:r.name}),initial:[]}),this.add(this.output,{name:"output"}),this.addDisposer(Te(this.output)),this.bridgedCount=V(0,{name:"bridgedCount",describeKind:"state",meta:ze("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"}),this.addDisposer(Te(this.bridgedCount));let a=this.output,d=this._sourceSub,u=this.bridgedCount,l=oe([a],()=>{let c=a.cache;if(c.length===0)return;let p=d.available.cache.length,f=Math.min(p,o);if(f>0){d.ack(f);let g=u.cache??0;u.emit(g+c.length)}},{name:"ackPump",describeKind:"effect",meta:ze("topic_bridge_ack_pump")});this.add(l,{name:"ackPump"}),this.addDisposer(Te(l));let h=ks(this.output,r);this.addDisposer(h)}};function ks(t,e){return t.subscribe(n=>{for(let r of n){if(r[0]!==I)continue;let s=r[1];s.length!==0&&re(()=>{for(let o of s)e.publish(o)})}})}var wn=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,n){this._map.set(e,n)}delete(e){return this._map.delete(e)}keys(){return this._map.keys()}},_n=class extends ce{_registry;version;_defaultTopicOptions;constructor(e,n={}){super(e,n.graph);let r=V(0,{name:"version",describeKind:"state",meta:ze("hub_version")});this.add(r,{name:"version"}),this.version=r,this._registry=new wn(r),this._defaultTopicOptions={...n.defaultTopicOptions??{}}}get size(){return this._registry.size}has(e){return this._registry.has(e)}topicNames(){return this._registry.keys()}topic(e,n){let r=this._registry.get(e);if(r===void 0){let s={...this._defaultTopicOptions,...n??{}};r=new Tn(e,s),this._registry.set(e,r),this.mount(e,r);let o=this.version.cache??0;this.version.emit(o+1)}return r}publish(e,n){this.topic(e).publish(n)}publishMany(e){re(()=>{for(let[n,r]of e)this.topic(n).publish(r)})}subscribe(e,n,r){let s=this.topic(n);return new zt(e,s,r)}removeTopic(e){if(!this._registry.has(e))return!1;try{this.remove(e)}finally{this._registry.delete(e);let n=this.version.cache??0;this.version.emit(n+1)}return!0}};function Bt(t,e){return new _n(t,e)}function Os(t,e,n){return new zt(t,e,n)}function En(t,e,n,r){return new xn(t,e,n,r)}function Ss(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.subscribe=="function"&&typeof e.down=="function"&&typeof e.emit=="function"}function As(t,e){if(t.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(t.length===1){let o=Cs(e);return{best:t[0],bestScore:o}}if(e.some(o=>typeof o.candidateIndex=="number")){let o=new Array(t.length);for(let d=0;d<t.length;d++)o[d]={sum:0,count:0};for(let d of e){let u=d.candidateIndex;typeof u=="number"&&u>=0&&u<t.length&&(o[u].sum+=d.score,o[u].count+=1)}let i=t[0],a=o[0].count>0?o[0].sum/o[0].count:Number.NEGATIVE_INFINITY;for(let d=1;d<t.length;d++){let u=o[d].count>0?o[d].sum/o[d].count:Number.NEGATIVE_INFINITY;u>a&&(a=u,i=t[d])}return{best:i,bestScore:a}}let r=t[0],s=e[0]?.score??Number.NEGATIVE_INFINITY;for(let o=1;o<t.length;o++){let i=e[o]?.score??Number.NEGATIVE_INFINITY;i>s&&(s=i,r=t[o])}return{best:r,bestScore:s}}function Cs(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function kr(t,e,n,r){let s=r.name??"refine-loop",o=new ce(s,r.graph),i=Ss(r.dataset)?r.dataset:V(r.dataset,{name:"dataset"});o.add(i,{name:"dataset"});let a=V(0,{name:"iteration"});o.add(a,{name:"iteration"});let d=V(n,{name:"strategy",equals:()=>!1});o.add(d,{name:"strategy"});let u=V(null,{name:"lastFeedback"});o.add(u,{name:"lastFeedback"});let l=V([],{name:"prevCandidates"});o.add(l,{name:"prevCandidates"});let h=V(!1,{name:"paused"});o.add(h,{name:"paused"});let c=V("running",{name:"status"});o.add(c,{name:"status"});let p=V([],{name:"history",equals:()=>!1});o.add(p,{name:"history"});let f=V(null,{name:"best"});o.add(f,{name:"best"});let g=V(Number.NEGATIVE_INFINITY,{name:"score"});o.add(g,{name:"score"});let b=V(0,{name:"budget-used"});o.add(b,{name:"budget-used"});let v=Bt("stages");o.mount("stages",v);let T=v.topic("generate"),y=v.topic("evaluate"),w=v.topic("analyze"),N=v.topic("decide"),_=n,m=null,x=[];o.addDisposer(d.subscribe(D=>{for(let K of D)K[0]===I&&(_=K[1])})),o.addDisposer(u.subscribe(D=>{for(let K of D)K[0]===I&&(m=K[1])})),o.addDisposer(l.subscribe(D=>{for(let K of D)K[0]===I&&(x=K[1])}));let E=Re(a,D=>{let K=_,ne=D===0||m==null;return oe([],(H,R)=>{let M=!1;try{let U=ne?K.seed(t):K.generate(m,x);if(U instanceof Promise)return U.then(J=>{M||R.emit(J)},J=>{M||R.down([[L,J]])}),()=>{M=!0};R.emit(U)}catch(U){M=!0,R.down([[L,U]])}},{describeKind:"producer"})},{name:"candidates"});o.add(E,{name:"candidates"});let A=ge([E],(D,K,ne)=>{let H=ne.terminalDeps[0];H!==void 0&&H!==!0&&c.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});o.add(A,{name:"error-watcher"}),o.addDisposer(A.subscribe(()=>{}));let k=G([E,a],([D,K])=>({iteration:K,candidates:D,timestamp_ns:ee()}),{name:"generate-event"});o.add(k,{name:"generate-event"}),o.addDisposer(k.subscribe(()=>{}));let S=ge([k],([D])=>{T.publish(D)},{name:"generate-publish"});o.add(S,{name:"generate-publish"}),o.addDisposer(S.subscribe(()=>{}));let C=ge([E],([D])=>{l.emit(D)},{name:"generate-mirror"});o.add(C,{name:"generate-mirror"}),o.addDisposer(C.subscribe(()=>{}));let B=e(E,i);o.add(B,{name:"scores"});let Y=G([B,E,a],([D,K,ne])=>({iteration:ne,candidates:K,scores:D,timestamp_ns:ee()}),{name:"evaluate-event"});o.add(Y,{name:"evaluate-event"}),o.addDisposer(Y.subscribe(()=>{}));let W=ge([Y],([D])=>{y.publish(D)},{name:"evaluate-publish"});o.add(W,{name:"evaluate-publish"}),o.addDisposer(W.subscribe(()=>{}));let ye=G([B,E],([D,K])=>_.analyze(D,K),{name:"feedback"});o.add(ye,{name:"feedback"});let Oe=G([ye,E,a],([D,K,ne])=>({iteration:ne,candidates:K,feedback:D,timestamp_ns:ee()}),{name:"analyze-event"});o.add(Oe,{name:"analyze-event"}),o.addDisposer(Oe.subscribe(()=>{}));let $=ge([Oe],([D])=>{w.publish(D)},{name:"analyze-publish"});o.add($,{name:"analyze-publish"}),o.addDisposer($.subscribe(()=>{}));let F=G([p],([D])=>{let K=D;if(r.patience==null||K.length<=r.patience)return!1;let ne=K.slice(-(r.patience+1)),H=ne[0].bestScore;return ne.slice(1).every(R=>R.bestScore<=H)},{name:"patience-check"});o.add(F,{name:"patience-check"});let P=G([g],([D])=>r.minScore!=null&&D>=r.minScore,{name:"min-score-check"});o.add(P,{name:"min-score-check"});let le=G([p],([D])=>{let K=D;if(r.minDelta==null||K.length<2)return!1;let ne=K[K.length-2].bestScore,H=K[K.length-1].bestScore;return Math.abs(H-ne)<r.minDelta},{name:"min-delta-check"});o.add(le,{name:"min-delta-check"});let O=G([b],([D])=>r.maxEvaluations!=null&&D>=r.maxEvaluations,{name:"max-evaluations-check"});o.add(O,{name:"max-evaluations-check"});let z=G([a],([D])=>r.maxIterations!=null&&D>=r.maxIterations,{name:"max-iterations-check"});o.add(z,{name:"max-iterations-check"});let ae=G([b],([D])=>r.budget!=null&&D>=r.budget,{name:"budget-exhausted-check"});o.add(ae,{name:"budget-exhausted-check"}),o.addDisposer(F.subscribe(()=>{})),o.addDisposer(P.subscribe(()=>{})),o.addDisposer(le.subscribe(()=>{})),o.addDisposer(O.subscribe(()=>{})),o.addDisposer(z.subscribe(()=>{})),o.addDisposer(ae.subscribe(()=>{}));let Me=G([F,P,le,O,z],([D,K,ne,H,R])=>D?{converged:!0,reason:"patience"}:K?{converged:!0,reason:"min-score"}:ne?{converged:!0,reason:"min-delta"}:H?{converged:!0,reason:"max-evaluations"}:R?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});o.add(Me,{name:"converged"}),o.addDisposer(Me.subscribe(()=>{}));let fe=-1,q=ge([ye,B,E],([D,K,ne])=>{let H=a.cache,R=D,M=ne,U=K;if(H<=fe)return;fe=H;let{best:J,bestScore:Ie}=As(M,U),st=p.cache,Be={n:H,candidates:M,scores:U,feedback:R,best:J,bestScore:Ie,timestamp_ns:ee()},Q=[...st,Be],we=b.cache+M.length,ve="continue",Ge,Cn=r.budget!=null&&we>=r.budget,Mn=h.cache;if(Cn)ve="budget",Ge="budget";else if(r.minScore!=null&&R.score>=r.minScore)ve="converged",Ge="min-score";else if(r.maxIterations!=null&&H>=r.maxIterations)ve="converged",Ge="max-iterations";else if(r.maxEvaluations!=null&&we>=r.maxEvaluations)ve="converged",Ge="max-evaluations";else if(r.minDelta!=null&&Q.length>=2){let yt=Q[Q.length-2].bestScore,Jt=Q[Q.length-1].bestScore;Math.abs(Jt-yt)<r.minDelta&&(ve="converged",Ge="min-delta")}else if(r.patience!=null&&Q.length>r.patience){let yt=Q.slice(-(r.patience+1)),Jt=yt[0].bestScore;yt.slice(1).every(Hr=>Hr.bestScore<=Jt)&&(ve="converged",Ge="patience")}ve==="continue"&&Mn&&(ve="paused"),re(()=>{f.emit(J),g.emit(R.score),p.emit(Q),b.emit(we),u.emit(R),N.publish({iteration:H,decision:ve,reason:Ge,timestamp_ns:ee()}),ve==="continue"?a.emit(H+1):c.emit(ve==="converged"?"converged":ve==="budget"?"budget":"paused")})},{name:"decide-bridge"});return o.add(q,{name:"decide-bridge"}),o.addDisposer(q.subscribe(()=>{})),Object.assign(o,{best:f,score:g,status:c,history:p,strategy:d,iteration:a,generate:T,evaluate:y,analyze:w,decide:N,setStrategy(D){d.emit(D)},pause(){h.emit(!0)},resume(){c.cache==="paused"&&re(()=>{h.emit(!1),c.emit("running"),a.emit(a.cache+1)})}})}function Ms(t){let{best:e,score:n,status:r}=t,s=Number.isFinite(n)?n.toFixed(3):String(n),o=e??void 0;return r==="converged"?{outcome:"success",detail:`refineLoop converged at score ${s}`,artifact:o}:r==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${s}`,artifact:o}:{outcome:"failure",detail:`refineLoop errored (status=${r})`,artifact:o}}function Nn(t){let e=t.name??"refine-executor",n=t.toOutput??Ms;return r=>{let s=$e(r,i=>i!=null,{name:`${e}/gate-in`}),o=Re(s,i=>{let a=kr(t.seedFrom(i),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(i),name:`${e}/inner`});return G([a.status,a.best,a.score],([d,u,l])=>{let h=d;return h!=="converged"&&h!=="budget"&&h!=="errored"?null:n({best:u,score:l,status:h})},{name:`${e}/output`})},{name:e});return $e(o,i=>i!=null,{name:`${e}/gate-out`})}}function Is(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function Ds(t){let{passCount:e,total:n,meanScore:r,threshold:s,missingArtifact:o}=t,i=Number.isFinite(r)?r.toFixed(3):String(r),a=!o&&n>0&&r>=s,d=o?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:a?[`${e}/${n} eval tasks passed; mean score ${i} \u2265 ${s}`]:n===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${e}/${n} eval tasks passed; mean score ${i} < threshold ${s}`];return a?{verified:!0,findings:d}:{verified:!1,findings:d,errorClass:"structural"}}function Gs(t){return t.artifact??null}function Or(t){let e=t.name??"eval-verifier",n=t.threshold??.5,r=t.toOutput??Ds,s=t.extractArtifact??Gs;return o=>{let i=$e(o,d=>d!=null&&d[0]!=null&&d[1]!=null,{name:`${e}/gate-in`}),a=Re(i,d=>{let[u,l]=d,h=s(u,l);if(h==null)return V(r({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:n,missingArtifact:!0}));let c=V([h],{name:`${e}/candidates`}),p=V(t.datasetFor(l),{name:`${e}/dataset`}),f=t.evaluator(c,p);return G([f],([g])=>{let b=g;if(b==null)return null;let v=Is(b),T=b.filter(y=>y.score>=n).length;return r({scores:b,meanScore:v,passCount:T,total:b.length,threshold:n})},{name:`${e}/output`})},{name:e});return $e(a,d=>d!=null,{name:`${e}/gate-out`})}}function Ls(t){let e=t.name??"harness-pair",n=Nn({name:`${e}-exec`,seedFrom:t.seedFrom,evaluator:t.evaluator,strategy:t.strategy,datasetFor:t.datasetFor,refine:t.refine}),r=Or({name:`${e}-verify`,evaluator:t.evaluator,datasetFor:t.datasetFor,threshold:t.threshold});return{executor:n,verifier:r}}Ae();Ce();de();De();Ae();pe();de();var Rn=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(e={}){let{maxSize:n,defaultTtl:r}=e;if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(r!==void 0&&r<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=n,this._defaultTtl=r}get version(){return this._version}get size(){return this._store.size}has(e){let n=this._store.get(e);return n===void 0?!1:this._isExpired(n)?(this._store.delete(e),this._version+=1,!1):(this._touchLru(e,n),!0)}get(e){let n=this._store.get(e);if(n!==void 0){if(this._isExpired(n)){this._store.delete(e),this._version+=1;return}return this._touchLru(e,n),n.value}}set(e,n,r){let s=this._resolveExpiresAt(r);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:n,expiresAt:s}),this._evictLruWhileOver(),this._version+=1}setMany(e,n){let r=this._resolveExpiresAt(n),s=0;try{for(let[o,i]of e)this._store.has(o)&&this._store.delete(o),this._store.set(o,{value:i,expiresAt:r}),s+=1}finally{s>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(e){let n=this._store.delete(e);return n&&(this._version+=1),n}deleteMany(e){let n=0;try{for(let r of e)this._store.delete(r)&&(n+=1)}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._store.size;return e===0?0:(this._store.clear(),this._version+=1,e)}pruneExpired(){let e=ee(),n=0;for(let[r,s]of this._store)this._isExpired(s,e)&&(this._store.delete(r),n+=1);return n>0&&(this._version+=1),n}toMap(){let e=ee(),n=new Map;for(let[r,s]of this._store)this._isExpired(s,e)||n.set(r,s.value);return n}_resolveExpiresAt(e){let n=e??this._defaultTtl;if(n!==void 0){if(!Number.isFinite(n)||n<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${n})`);return ee()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??ee())>=e.expiresAt}_touchLru(e,n){this._store.delete(e),this._store.set(e,n)}_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 Ht(t={}){let{name:e,maxSize:n,defaultTtl:r,versioning:s,backend:o,retention:i}=t;if(i&&n!==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 Rn({maxSize:n,defaultTtl:r}),d=V(a.toMap(),{name:e,describeKind:"state",equals:(c,p)=>c===p,...s!=null?{versioning:s}:{}});function u(){let c=a.toMap();re(()=>{d.down([[X]]),d.down([[I,c]])})}function l(){if(!i)return;let c=a.toMap(),p=i.archiveThreshold,f=i.maxSize,g=[];for(let[v,T]of c)g.push({key:v,value:T,score:i.score(v,T)});g.sort((v,T)=>v.score-T.score);let b=new Set;if(p!==void 0)for(let v of g)if(v.score<p)b.add(v.key);else break;if(f!==void 0&&g.length-b.size>f)for(let v of g){if(g.length-b.size<=f)break;b.has(v.key)||b.add(v.key)}if(b.size!==0)for(let v of g)b.has(v.key)&&(i.onArchive?.(v.key,v.value,v.score),a.delete(v.key))}function h(c,p="mutation"){let f=a.version;try{return c()}finally{a.version!==f&&(p==="mutation"&&l(),u())}}return{entries:d,has(c){return h(()=>a.has(c),"read")},get(c){return h(()=>a.get(c),"read")},set(c,p,f){h(()=>a.set(c,p,f?.ttl))},setMany(c,p){h(()=>a.setMany(c,p?.ttl))},delete(c){h(()=>a.delete(c))},deleteMany(c){h(()=>a.deleteMany(c))},clear(){h(()=>a.clear())},pruneExpired(){h(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}function gt(t,e){return je("ai",t,e)}function Sr(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}pe();de();Ue();function Ar(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function Ps(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Kt(t,e,n,r){let s=r?.format??"text",o=r?.name??"prompt_node",i=G(e,d=>{if(d.some(l=>l==null))return[];let u=typeof n=="string"?n:n(...d);return u?[{role:"user",content:u}]:[]},{name:`${o}::messages`,meta:gt("prompt_node")});return Re(i,d=>!d||d.length===0?V(null):he(u=>{let l=!1,h=!1,c,p={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt};if(r?.abort){let v=Xn(r.abort);p.signal=v.signal,c=v.dispose}let f;try{f=t.invoke(d,p)}catch(v){return l=!0,u.down([[L,v]]),()=>{c?.()}}let b=Ve(f).subscribe(v=>{if(!(h||l))for(let T of v){if(l)return;if(T[0]===I){let y=T[1];try{let w=Ar(y),N=s==="json"?JSON.parse(Sr(w)):w;u.emit(N)}catch(w){let N=Ar(y),_=new Error(`promptNode: failed to parse LLM response as JSON: ${w.message}
49
+ Raw content (first 200 chars): ${Ps(N)}`);l=!0,u.down([[L,_]]);return}}else if(T[0]===L){l=!0,u.down([[L,T[1]]]);return}else if(T[0]===j){l=!0,u.down([[j]]);return}else u.down([T])}});return()=>{h=!0,b(),c?.()}},{name:`${o}::call`,meta:gt("prompt_node::call")}),{name:`${o}::output`,meta:r?.meta?{...gt("prompt_node::output"),...r.meta}:gt("prompt_node::output")})}De();Ae();pe();Ce();de();De();Ae();Xe();pe();de();var $s=Hn((t,e)=>{t("observe"),t("signal"),e("write")});function qt(t){let e=jt([],{name:t.name,maxSize:t.retainedLimit??1024,guard:t.guard??$s,...t.versioning!=null?{versioning:t.versioning}:{}});return e.withLatest(),t.graph&&t.graph.add(e.entries,{name:t.name}),e}function Mr(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))Mr(t[e]);return Object.freeze(t)}function Vs(t){let e=t.cache,r=(typeof e=="number"&&Number.isFinite(e)?e:0)+1;return t.down([[X],[I,r]]),r}function Cr(t,e,n,r,s,o){let i=e(n,r,s);if(i===void 0)return;let a=o!=null?{...i,handlerVersion:o}:i;t.append(a)}function ot(t,e){let n=e.freeze??!0;return function(...s){let o=n?s.map(Mr):s,i=be(),a,d,u=!1,l;try{re(()=>{e.seq&&(l=Vs(e.seq));try{a=t(...o),e.onSuccess&&Cr(e.audit,e.onSuccess,o,a,{t_ns:i,seq:l},e.handlerVersion)}catch(h){throw d=h,u=!0,h}})}catch(h){if(u&&e.onFailure){let c=d instanceof Error?d.name:typeof d;Cr(e.audit,e.onFailure,o,d,{t_ns:i,seq:l,errorType:c},e.handlerVersion)}throw u?d:h}return a}}function Ir(t,e,n=0){let r=V(n,{name:e,describeKind:"state"});return t.add(r,{name:e}),r}function bt(t,e){return je("orchestration",t,e)}var Ut=class extends ce{constructor(e,n){super(e,n)}task(e,n,r={}){let s=(r.deps??[]).map(i=>this._resolveStep(i)),o=G(s,n,{name:e,describeKind:"derived",meta:bt("task",r.meta)});return this.add(o,{name:e}),o}classify(e,n,r,s={}){let o=this._resolveStep(n),i=G([o],([a])=>{try{return{tag:r(a),value:a}}catch(d){return{tag:"error",value:a,error:d}}},{name:e,describeKind:"derived",meta:bt("classify",s.meta)});return this.add(i,{name:e}),i}combine(e,n,r={}){let s=Object.keys(n),o=s.map(a=>this._resolveStep(n[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:bt("combine",r.meta)});return this.add(i,{name:e}),i}gate(e,n,r={}){let s=r.maxPending??1e3;if(s<1&&s!==Number.POSITIVE_INFINITY)throw new RangeError("gate: maxPending must be >= 1");let o=r.startOpen??!1;typeof n!="string"&&this.nameOf(n)===void 0&&this.add(n,{name:`${e}/source`});let i=this._resolveStep(n),a=new ce(`${e}_state`),d=V([],{name:"pending",equals:()=>!1}),u=V(o,{name:"isOpen"}),l=G([d],([$])=>$.length,{name:"count"}),h=V(0,{name:"droppedCount"}),c=qt({name:"decisions",retainedLimit:1024,graph:a});a.add(d,{name:"pending"}),a.add(u,{name:"isOpen"}),a.add(l,{name:"count"}),a.add(h,{name:"droppedCount"}),this.mount(`${e}_state`,a);let p=[],f=!1,g=!1,b=o,v=u.subscribe($=>{for(let F of $)F[0]===I&&(b=F[1])});this.addDisposer(v);function T(){d.emit([...p])}function y($,F,P){c.append({action:$,t_ns:be(),...F!==void 0?{items:F,count:F.length}:{},...P!==void 0?{unflushed:P}:{},...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}function w($){if(p.push($),p.length>s){let F=p.shift();h.emit(h.cache+1),y("drop",[F])}T()}function N($){let F=p.splice(0,$);return T(),F}let _=oe([i],($,F,P)=>{let le=P.terminalDeps[0];if(le!==void 0){f=!0;let z=p.length;p=[],T(),y("teardown",void 0,z),F.down(le===!0?[[j]]:[[L,le]]);return}let O=$[0];if(O==null||O.length===0){F.down([[Z]]);return}for(let z of O)b?F.emit(z):(w(z),F.down([[Z]]))},{name:e,describeKind:"derived",meta:bt("gate",r.meta)});if(this.add(_,{name:e}),r.approver!=null){r.approver.cache&&(u.emit(!0),b=!0,r.onceOnly&&(g=!0));let F=r.approver.subscribe(P=>{for(let le of P){if(le[0]!==I)continue;let O=!!le[1];if(O&&!b){if(r.onceOnly){if(g)continue;g=!0}re(()=>{u.emit(!0);let z=N(p.length);y("open",z);for(let ae of z){if(f)break;_.emit(ae)}})}else if(!O&&b){if(r.onceOnly&&g)continue;re(()=>{u.emit(!1),y("close")})}}});this.addDisposer(F)}let m=$=>{if(f)throw new Error(`gate: ${$}() called after gate was torn down`)},x=($=1)=>{m("approve");let F=N($);for(let P of F){if(f)break;_.emit(P)}},E=($=1)=>{m("reject"),N($)},A=($,F=1)=>{m("modify");let P=[...p],le=N(F);for(let O=0;O<le.length&&!f;O++)_.emit($(le[O],O,P))},k=()=>{m("open"),u.emit(!0);let $=N(p.length);for(let F of $){if(f)break;_.emit(F)}},S=()=>{m("close"),!(r.onceOnly&&g)&&u.emit(!1)},C=ot(x,{audit:c,freeze:!1,onSuccess:($,F,P)=>({action:"approve",count:$[0]??1,t_ns:P.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:($,F,P)=>({action:"drop",t_ns:P.t_ns,errorType:P.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),B=ot(E,{audit:c,freeze:!1,onSuccess:($,F,P)=>({action:"reject",count:$[0]??1,t_ns:P.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:($,F,P)=>({action:"drop",t_ns:P.t_ns,errorType:P.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),Y=ot(A,{audit:c,freeze:!1,onSuccess:($,F,P)=>({action:"modify",count:$[1]??1,t_ns:P.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:($,F,P)=>({action:"drop",t_ns:P.t_ns,errorType:P.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),W=ot(k,{audit:c,freeze:!1,onSuccess:($,F,P)=>({action:"open",t_ns:P.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:($,F,P)=>({action:"drop",t_ns:P.t_ns,errorType:P.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),ye=ot(S,{audit:c,freeze:!1,onSuccess:($,F,P)=>({action:"close",t_ns:P.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:($,F,P)=>({action:"drop",t_ns:P.t_ns,errorType:P.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})});return this.addDisposer(l.subscribe(()=>{})),{node:_,pending:d,count:l,isOpen:u,droppedCount:h,decisions:c,audit:c,approve:C,reject:B,modify:Y,open:W,close:ye}}approval(e,n,r,s={}){return this.gate(e,n,{...s,approver:r,maxPending:1})}catch(e,n,r,s={}){let o=this._resolveStep(n),i=s.on??"error",a=oe([o],(d,u,l)=>{let h=l.terminalDeps[0];if(h!==void 0){let p=h===!0?{kind:"complete"}:{kind:"error",error:h};if(i==="terminal"||i===p.kind){u.emit(r(p,u));return}u.down(p.kind==="complete"?[[j]]:[[L,p.error]]);return}let c=d[0];if(c==null||c.length===0){u.down([[Z]]);return}for(let p of c)u.emit(p)},{name:e,describeKind:"derived",completeWhenDepsComplete:s.completeWhenDepsComplete??!(i==="complete"||i==="terminal"),errorWhenDepsError:!(i==="error"||i==="terminal"),meta:bt("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 kn(t,e){return new Ut(t,e)}function Dr(t,e,n,r=0){if(!Number.isFinite(t))return r;if(!Number.isFinite(e)||e<=0||!Number.isFinite(n)||n<=0)return Math.max(r,t);let s=t*Math.exp(-n*e);return Math.max(r,s)}Ae();De();pe();de();var On=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 n=e>=0?e:this._buf.length+e;if(!(n<0||n>=this._buf.length))return this._buf[n]}append(e){this._buf.push(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._buf.length;this._buf.length=n+e.length;for(let r=0;r<e.length;r++)this._buf[n+r]=e[r];this._version+=1}insert(e,n){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,n),this._version+=1}insertMany(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insertMany: index ${e} out of range [0, ${this._buf.length}]`);n.length!==0&&(this._buf.splice(e,0,...n),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 n=e>=0?e:this._buf.length+e;if(n<0||n>=this._buf.length)throw new RangeError(`pop: index ${e} out of range`);let[r]=this._buf.splice(n,1);return this._version+=1,r}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._version+=1,e)}toArray(){return[...this._buf]}};function Gr(t,e={}){let{name:n,versioning:r,backend:s}=e,o=s??new On(t),i=V(o.toArray(),{name:n,describeKind:"state",equals:(u,l)=>u===l,...r!=null?{versioning:r}:{}});function a(){let u=o.toArray();re(()=>{i.down([[X]]),i.down([[I,u]])})}function d(u){let l=o.version;try{return u()}finally{o.version!==l&&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,l){d(()=>o.insert(u,l))},insertMany(u,l){d(()=>o.insertMany(u,l))},pop(u=-1){return d(()=>o.pop(u))},clear(){d(()=>o.clear())},dispose(){}}}function Fs(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function js(t,e){return je("job_queue",t,e)}var Sn=class extends ce{_pending;_jobs;_seqCursor;pending;jobs;depth;events;audit;constructor(e,n={}){super(e,n.graph),this._pending=Gr([],{name:"pending"}),this._jobs=Ht({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],([r])=>r.length,{name:"depth",describeKind:"derived",meta:js("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(Te(this.depth)),this.events=qt({name:"events",retainedLimit:1024,graph:this}),this.audit=this.events,this._seqCursor=Ir(this,"seq",0)}_bumpSeq(){let n=(this._seqCursor.cache??0)+1;return this._seqCursor.emit(n),n}attachEventStorage(e){return this.events.attachStorage(e)}enqueue(e,n={}){let r=this._bumpSeq(),s=n.id??`${this.name}-${r}`;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({...n.metadata??{}}),state:"queued"};return this._jobs.set(s,o),this._pending.append(s),this.events.append({action:"enqueue",id:s,payload:e,t_ns:be(),seq:r}),s}claim(e=1){let n=Fs(e,"job queue claim limit");if(n===0)return[];let r=[];for(;r.length<n&&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),r.push(a),this.events.append({action:"claim",id:o,attempts:a.attempts,t_ns:be(),seq:this._bumpSeq()})}return r}ack(e){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:(this._jobs.delete(e),this.events.append({action:"ack",id:e,attempts:n.attempts,t_ns:be(),seq:this._bumpSeq()}),!0)}nack(e,n={}){let r=this._jobs.get(e);return!r||r.state!=="inflight"?!1:n.requeue??!0?(this._jobs.set(e,{...r,state:"queued"}),this._pending.append(e),this.events.append({action:"nack",id:e,attempts:r.attempts,t_ns:be(),seq:this._bumpSeq()}),!0):(this._jobs.delete(e),this.events.append({action:"nack",id:e,attempts:r.attempts,t_ns:be(),seq:this._bumpSeq()}),!0)}removeById(e){let n=this._jobs.get(e);if(!n)return!1;if(n.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:n.attempts,t_ns:be(),seq:this._bumpSeq()}),!0}consumeFrom(e,n){return e.subscribe(r=>{for(let s of r){if(s[0]!==I)continue;let o=s[1];this.enqueue(o,n?{metadata:n.metadata}:void 0)}})}};function Lr(t,e){return new Sn(t,e)}Ae();de();function An(){let t=Ht({name:"strategy-entries"}),e=G([t.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[l,h]of d){let c=u.get(l);if(!c||h.attempts!==c.attempts||h.successes!==c.successes)return!1}return!0}});function n(i,a,d){let u=nt(i,a),l=t.get(u),h=(l?.attempts??0)+1,c=(l?.successes??0)+(d?1:0);t.set(u,{rootCause:i,intervention:a,attempts:h,successes:c,successRate:c/h})}function r(i,a){return t.get(nt(i,a))}let s=e.subscribe(()=>{});function o(){s()}return{node:e,record:n,lookup:r,dispose:o}}function zs(t,e,n,r,s){let o={...et,...s?.severityWeights},i=s?.decayRate??tt,a=s?.effectivenessThreshold??.7,d=s?.effectivenessBoost??15,u=[t,e,n];return r&&u.push(r),G(u,l=>{let h=l[0],c=l[1],p=l[2],f=r?l[3]:0,g=o[h.severity??"medium"],b=(ee()-p)/1e9,v=Dr(g,b,i,0),T=nt(h.rootCause,h.intervention),y=c.get(T);return y&&y.successRate>=a&&(v+=d),v+=f*20,v},{name:"priority-score"})}var Pr="intake",Bs="triage-output",$r="retry",Vr="verify-results",Fr="__unrouted";function jr(t,e){let n=ft(e,cn,(r,s)=>r.replace("{{item}}",JSON.stringify(s)));return r=>Kt(t,[r],n,{name:"execute",format:"json"})}function zr(t,e){let n=ft(e,fn,(r,s)=>{let[o,i]=s;return r.replace("{{execution}}",JSON.stringify(o)).replace("{{item}}",JSON.stringify(i))});return r=>Kt(t,[r],s=>s==null?"":n(s),{name:"verify",format:"json"})}var Wt=class extends ce{queues;jobs;gates;queueTopics;strategy;totalRetries;totalReingestions;priorityScores;constructor(e,n,r,s,o,i,a,d,u){super(e),this.queues=n,this.queueTopics=r,this.jobs=s,this.gates=o,this.strategy=i,this.totalRetries=a,this.totalReingestions=d,this.priorityScores=u}get intake(){return this.queues.topic(Pr)}get verifyResults(){return this.queues.topic(Vr)}get retry(){return this.queues.topic($r)}get unrouted(){return this.queues.topic(Fr)}stageNodes(){let e=this.queues,n=i=>e.has(i)?`queues::${i}::latest`:null,r=i=>i==null?[]:[i],s=xe.flatMap(i=>r(n(i))),o=[];for(let[i]of this.gates)o.push(`gates::${i}/gate`);return[{label:"INTAKE",paths:r(n("intake"))},{label:"TRIAGE",paths:["triage"]},{label:"QUEUE",paths:s},{label:"GATE",paths:o},{label:"EXECUTE",paths:["execute"]},{label:"VERIFY",paths:r(n("verify-results"))},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function Hs(t,e){let n=e.adapter,r=e.maxRetries??2,s=e.retainedLimit??1e3,o=e.errorClassifier??St,i=new Map;for(let R of xe)i.set(R,{...Ot[R],...e.queues?.[R]});let a=Bt(`${t}/queues`,{defaultTopicOptions:{retainedLimit:s}}),d=a.topic(Pr),u=a.topic(Bs),l=a.topic($r),h=a.topic(Vr),c=new Map;for(let R of xe)c.set(R,a.topic(R));let p=a.topic(Fr),f=An(),g=ct(d.latest,f.node),b=ft(e.triagePrompt,ln,(R,M)=>{let[U,J]=M;return R.replace("{{strategy}}",JSON.stringify(Array.from(J.entries()))).replace("{{item}}",JSON.stringify(U))}),v=Kt(n,[g],R=>{let M=R;return!M||!M[0]?"":b(M)},{name:"triage",format:"json"}),T=ct(v,g),w=ge([T],([R])=>{if(R==null)return;let[M,U]=R;if(!M?.route)return;let J=U?.[0],Ie={...M,...J};u.publish(Ie)}).subscribe(()=>{}),N=new Set(xe);for(let R of xe)En(`bridge/${R}`,u,c.get(R),{map:M=>M.route===R?M:void 0});En("bridge/__unrouted",u,p,{map:R=>N.has(R.route)?void 0:R});let _=new Map,m=new Map;for(let R of xe)_.set(R,Lr(`jobs/${R}`));let x=[];for(let R of xe){let M=c.get(R),U=_.get(R),J=new WeakSet,Ie=ge([M.events],([st])=>{let Be=st??[];for(let Q of Be){if(J.has(Q))continue;J.add(Q);let we=U.enqueue(Q);m.set(mt(Q),{route:R,id:we})}},{name:`jobs/${R}-mirror`});x.push(Ie.subscribe(()=>{}))}function E(R){let M=mt(R),U=m.get(M);U&&(_.get(U.route)?.removeById(U.id),m.delete(M))}let A=kn("gates"),k=new Map;for(let R of xe){let M=i.get(R);if(!M.gated)continue;let U=c.get(R),J=A.gate(`${R}/gate`,U.latest,{maxPending:M.maxPending,startOpen:M.startOpen});k.set(R,J)}let S=[];for(let R of xe)i.get(R).gated&&k.has(R)?S.push(k.get(R).node):S.push(c.get(R).latest);S.push(l.latest);let C=Zn(...S),Y=(e.executor??jr(n,e.executePrompt))(C),W=ct(Y,C),Oe=(e.verifier??zr(n,e.verifyPrompt))(W),$=ct(Oe,W),F=e.maxReingestions??1,P=Math.min(e.maxTotalRetries??r*10,100),le=Math.min(e.maxTotalReingestions??F*10,100),O=V(0),z=V(0);function ae(R,M,U){let J={item:U,outcome:M?.outcome??"failure",detail:M?.detail??"unknown",artifact:M?.artifact};return{item:U,execution:J,verified:R.verified,findings:R.findings??[],errorClass:R.errorClass}}function Me(R,M){f.record(M.rootCause,M.intervention,!0),h.publish(R),E(M)}function fe(R,M){let U=mt(M),J=M.$retries??0,Ie={...M,$retries:J+1,summary:`[RETRY ${J+1}/${r}] ${U} \u2014 Previous attempt failed: ${R.findings.join("; ")}`,relatedTo:[U]};l.publish(Ie)}function q(R,M){f.record(M.rootCause,M.intervention,!1),h.publish(R),E(M);let U=mt(M),J=M.$reingestions??0;J<F&&vn(z,le)&&d.publish({source:M.source,summary:`Verification failed for: ${U}`,evidence:R.findings.join(`
50
+ `),affectsAreas:M.affectsAreas,affectsEvalTasks:M.affectsEvalTasks,severity:M.severity??"high",relatedTo:[U],$reingestions:J+1})}let ue=oe([$],(R,M)=>{let U=R[0];if(U==null||U.length===0)return;let J=U[U.length-1];if(J==null)return;let[Ie,st]=J,[Be,Q]=st??[null,null];if(!Ie||!Q)return;if(Be==null){q({item:Q,execution:{item:Q,outcome:"failure",detail:"executor returned null"},verified:!1,findings:["executor returned null"],errorClass:"structural"},Q);return}let we=ae(Ie,Be,Q);if(we.verified){Me(we,Q);return}let ve=we.errorClass??o({item:Q,outcome:Be.outcome,detail:we.findings.join("; ")}),Ge=Q.$retries??0;ve==="self-correctable"&&Ge<r&&vn(O,P)?fe(we,Q):q(we,Q)}),D=ue.subscribe(()=>{}),K=G([ue],()=>null,{name:"reflect",equals:()=>!1}),ne;e.priority&&(ne=Ks(c,f,e));let H=new Wt(t,a,c,_,k,f,O,z,ne);H.addDisposer(w),H.addDisposer(D),H.addDisposer(f.dispose);for(let R of x)H.addDisposer(R);if(H.add(v,{name:"triage"}),H.add(C,{name:"execute-input"}),H.add(Y,{name:"execute"}),H.add(W,{name:"execute-context"}),H.add(Oe,{name:"verify"}),H.add($,{name:"verify-context"}),H.add(ue,{name:"verify-dispatch"}),H.add(K,{name:"reflect"}),H.add(f.node,{name:"strategy"}),H.addDisposer(K.subscribe(()=>{})),ne)for(let[R,M]of ne)H.add(M,{name:`priority/${R}`}),H.addDisposer(M.subscribe(()=>{}));H.mount("queues",a),H.mount("gates",A);for(let[R,M]of _)H.mount(`jobs/${R}`,M);return H}function Ks(t,e,n){if(!n.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 r=n.lastInteractionNs,s=n.priority??{},o={...et,...s.severityWeights},i=s.decayRate??tt,a=s.effectivenessThreshold??.7,d=s.effectivenessBoost??15,u=new Map;for(let[l,h]of t){let c=G([h.latest,e.node,r],p=>{let f=p[0];if(f==null)return 0;let g=o[f.severity??"medium"]??40,b=(ee()-p[2])/1e9,v=g*Math.exp(-i*Math.max(0,b)),T=`${f.rootCause}\u2192${f.intervention}`,w=p[1]?.get(T);return w&&w.successRate>=a&&(v+=d),v},{name:`priority/${l}`});u.set(l,c)}return u}function qs(t,e){let n=$t(t,e),r={};for(let s of xe){let o=t.queues.has(s)?t.queues.topic(s):null;r[s]=o?.retained().length??0}return{...n,queueDepths:r,strategyEntries:t.strategy.node.cache?.size??0,totalRetries:t.totalRetries.cache??0,totalReingestions:t.totalReingestions.cache??0}}Ae();function Us(t){let e={};for(let{label:n,paths:r}of t.stageNodes())for(let s of r)e[s]=n;return e}function Ws(t,e){let n=e?.logger===null?null:e?.logger??console.log,r=e?.detail??"summary",s=ee(),o=[],i=[],a=Us(t);function d(){return(ee()-s)/1e9}function u(l,h,c){let p={elapsed:d(),stage:l,type:h};r!=="summary"&&(p.summary=Js(c)),r==="full"&&(p.data=c),i.push(p)}for(let[l,h]of Object.entries(a))try{let c=t.observe(l,{format:"stage-log",stageLabels:a,logger:n?p=>n(p):()=>{},includeTypes:["data","error","complete"]});c.onEvent(p=>{p.type==="data"?u(h,"data",p.data):p.type==="error"?u(h,"error",p.data):p.type==="complete"&&u(h,"complete",void 0)}),o.push(c)}catch(c){let p=c instanceof Error?c.message:String(c);u(h,"error",`observe-unavailable: ${l} \u2014 ${p}`),n&&n(`[${d().toFixed(3)}s] ${h.padEnd(9)} \u2717 observe-unavailable: ${p}`)}return{get events(){return i},dispose(){for(let l of o)l.dispose();o.length=0}}}function Js(t){if(t==null)return"null";if(typeof t=="string")return Br(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return Br(e,120)}catch{return String(t)}}function Br(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}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,evalIntakeBridge,evalSource,evalVerifier,harnessEvalPair,harnessLoop,harnessProfile,harnessTrace,notifyEffect,priorityScore,refineExecutor,resolvePromptFn,strategyKey,strategyModel});