@graphrefly/graphrefly 0.36.0 → 0.38.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.
- package/dist/{chunk-J6TGRQUP.js → chunk-2YFDSYEF.js} +1 -1
- package/dist/{chunk-JUJEPZOI.js → chunk-4BDQXBXE.js} +1 -1
- package/dist/chunk-5BGFS2XH.js +1 -0
- package/dist/chunk-6773HURD.js +1 -0
- package/dist/{chunk-AQC53OWG.js → chunk-6KZZ6XQE.js} +1 -1
- package/dist/{chunk-5CPPC75H.js → chunk-6VFC334U.js} +1 -1
- package/dist/{chunk-KUVDFOJH.js → chunk-7KZZLWZ6.js} +1 -1
- package/dist/{chunk-Q7EUZ6NN.js → chunk-B5S7KTGP.js} +1 -1
- package/dist/chunk-CMTN3KPT.js +80 -0
- package/dist/chunk-DQJLC6YY.js +1 -0
- package/dist/chunk-DSOVKKTI.js +1 -0
- package/dist/chunk-FAYEMS5M.js +1 -0
- package/dist/chunk-FWGIZP3W.js +1 -0
- package/dist/{chunk-5Z3AFBN7.js → chunk-G7JN6LCB.js} +1 -1
- package/dist/{chunk-PCD2MU7X.js → chunk-IBGE62GZ.js} +1 -1
- package/dist/{chunk-MYFR67PY.js → chunk-K5C67OGE.js} +1 -1
- package/dist/chunk-KJEAIIIY.js +43 -0
- package/dist/chunk-LV3ACS5J.js +1 -0
- package/dist/{chunk-7LYIKMW5.js → chunk-NBGPXQSP.js} +1 -1
- package/dist/chunk-NN3QPJ6U.js +1 -0
- package/dist/{chunk-T6RPUERH.js → chunk-NSAZ6PR6.js} +1 -1
- package/dist/{chunk-KCE6WWJE.js → chunk-NV63VQHI.js} +1 -1
- package/dist/{chunk-PYEIPRSZ.js → chunk-O245YLM5.js} +1 -1
- package/dist/{chunk-K5ZXJPWU.js → chunk-O2BLVQU4.js} +1 -1
- package/dist/chunk-PHXZRR6C.js +1 -0
- package/dist/{chunk-I57VSGRB.js → chunk-POCWFIJ7.js} +1 -1
- package/dist/{chunk-TQSTS3BY.js → chunk-QEVSIVSF.js} +1 -1
- package/dist/chunk-QMC2PLNM.js +7 -0
- package/dist/chunk-QOJFR6GS.js +1 -0
- package/dist/{chunk-MQZWA3DF.js → chunk-RZ5HKPGI.js} +1 -1
- package/dist/{chunk-XINLP35X.js → chunk-SFK7MN7S.js} +1 -1
- package/dist/{chunk-YOUAVGHJ.js → chunk-SP5O2MIX.js} +1 -1
- package/dist/chunk-TB7JKSVS.js +61 -0
- package/dist/{chunk-6G5YD37E.js → chunk-TMVY7OWG.js} +1 -1
- package/dist/{chunk-F36TA3ET.js → chunk-UAXFKMAG.js} +1 -1
- package/dist/{chunk-AACJX2L7.js → chunk-UVLZX2OU.js} +1 -1
- package/dist/chunk-XIMFHEKV.js +1 -0
- package/dist/{chunk-LO3LO2TO.js → chunk-XLMYQB6F.js} +1 -1
- package/dist/{chunk-44QWWUA3.js → chunk-XLYF4LBH.js} +1 -1
- package/dist/compat/index.cjs +9 -9
- package/dist/compat/index.d.cts +7 -7
- package/dist/compat/index.d.ts +7 -7
- package/dist/compat/index.js +1 -1
- package/dist/compat/nestjs/index.cjs +9 -9
- package/dist/compat/nestjs/index.d.cts +5 -5
- package/dist/compat/nestjs/index.d.ts +5 -5
- package/dist/compat/nestjs/index.js +1 -1
- package/dist/compat/zustand/index.cjs +7 -7
- package/dist/compat/zustand/index.d.cts +3 -3
- package/dist/compat/zustand/index.d.ts +3 -3
- package/dist/compat/zustand/index.js +1 -1
- package/dist/{composite-_XckYx2e.d.cts → composite-CgG0MqHm.d.cts} +8 -1
- package/dist/{composite-CT_mApQD.d.ts → composite-DTOlDuch.d.ts} +8 -1
- package/dist/core/index.cjs +1 -1
- package/dist/core/index.d.cts +2 -2
- package/dist/core/index.d.ts +2 -2
- package/dist/core/index.js +1 -1
- package/dist/extra/index.cjs +19 -19
- package/dist/extra/index.d.cts +5 -5
- package/dist/extra/index.d.ts +5 -5
- package/dist/extra/index.js +1 -1
- package/dist/extra/node.cjs +2 -2
- package/dist/extra/node.d.cts +107 -1
- package/dist/extra/node.d.ts +107 -1
- package/dist/extra/node.js +2 -2
- package/dist/extra/operators.cjs +1 -1
- package/dist/extra/operators.js +1 -1
- package/dist/extra/reactive.d.cts +1 -1
- package/dist/extra/reactive.d.ts +1 -1
- package/dist/extra/reactive.js +1 -1
- package/dist/extra/sources.cjs +1 -1
- package/dist/extra/sources.js +1 -1
- package/dist/extra/storage-tiers-browser.d.cts +76 -5
- package/dist/extra/storage-tiers-browser.d.ts +76 -5
- package/dist/extra/storage-tiers-node.d.cts +137 -13
- package/dist/extra/storage-tiers-node.d.ts +137 -13
- package/dist/extra/storage-tiers.d.cts +151 -23
- package/dist/extra/storage-tiers.d.ts +151 -23
- package/dist/graph/index.cjs +7 -7
- package/dist/graph/index.d.cts +4 -4
- package/dist/graph/index.d.ts +4 -4
- package/dist/graph/index.js +1 -1
- package/dist/{graph-Cv-8x0ZI.d.ts → graph-BjW1taJl.d.ts} +243 -11
- package/dist/{graph-kTltt95s.d.cts → graph-CHsVwf9S.d.cts} +243 -11
- package/dist/{index-CZAixNU3.d.ts → index-5dNRlW7J.d.ts} +3 -3
- package/dist/{index-DtSVSKnd.d.ts → index-AUqWe_fX.d.ts} +7 -4
- package/dist/{index-DLyQC5Ww.d.ts → index-B-ORMr3k.d.ts} +2 -2
- package/dist/{index-C4ig7whw.d.cts → index-B2IUcH13.d.cts} +2 -2
- package/dist/{index-KeBhbNg3.d.ts → index-BFaALJxR.d.ts} +2 -2
- package/dist/{index-CsD0fqnO.d.ts → index-BI1wMfyc.d.ts} +2 -2
- package/dist/{index-DxxvGTXp.d.ts → index-BUFCHvOR.d.ts} +2 -2
- package/dist/{index-HCp5ua_i.d.cts → index-BWUMIt7J.d.cts} +3 -3
- package/dist/{index-DHv2M7s8.d.cts → index-BaSy4L6w.d.cts} +37 -17
- package/dist/{index-BhkPzu-Z.d.cts → index-BgzPO43H.d.cts} +2 -2
- package/dist/{index-BsZlbHM5.d.cts → index-BhzwpIJc.d.cts} +1 -1
- package/dist/{index-BC-xjOrd.d.cts → index-BkQqf1EF.d.cts} +80 -7
- package/dist/{index-BBdwz2BW.d.ts → index-BmWuVdER.d.ts} +2 -2
- package/dist/{index-CVhBdCMf.d.ts → index-Bn0uZEL4.d.ts} +2 -2
- package/dist/{index-33mF4XyU.d.cts → index-BpMZzX9P.d.cts} +2 -2
- package/dist/{index-ZhKyR8co.d.cts → index-Bpr0Pwgl.d.cts} +2 -2
- package/dist/{index-2URa-V4S.d.cts → index-BqcgiSQg.d.cts} +2 -2
- package/dist/{index-DzYTXMBz.d.ts → index-BsZk9T8y.d.ts} +1 -1
- package/dist/{index-CvUrRb4m.d.cts → index-BsgxnHN8.d.cts} +2 -2
- package/dist/index-Bub6x_D4.d.cts +427 -0
- package/dist/{index-BZ1V5GzX.d.ts → index-BwOsJfLJ.d.ts} +2 -2
- package/dist/{index-BuMzxRO2.d.ts → index-Byp771zP.d.ts} +1 -1
- package/dist/{index-DKp1CIbG.d.cts → index-C-3UXnHT.d.cts} +1 -1
- package/dist/{index-GaW6Welt.d.cts → index-C56XZiDe.d.cts} +2 -2
- package/dist/{index-k67aNfqC.d.cts → index-CAV-3RpJ.d.cts} +2 -2
- package/dist/{index-DmtWMP0X.d.cts → index-CAbHN_rP.d.cts} +1 -1
- package/dist/{index-BTJxM-wZ.d.ts → index-CEVzBWeB.d.ts} +2 -2
- package/dist/{index-BVNGEX7d.d.cts → index-CM-i58FY.d.cts} +2 -2
- package/dist/{index-EfPb77rT.d.cts → index-CQsqqEVz.d.cts} +1 -1
- package/dist/{index-Cot94_82.d.ts → index-CijfwEWx.d.ts} +2 -2
- package/dist/{index-PluovH45.d.cts → index-Ckil6miL.d.cts} +2 -2
- package/dist/{index-XxSeddWP.d.cts → index-CpdnP-0y.d.cts} +1 -1
- package/dist/{index-Pu1Wa7en.d.ts → index-CrlHFsiT.d.ts} +37 -17
- package/dist/{index-BWH17rK_.d.cts → index-Czk3r0yA.d.cts} +37 -3
- package/dist/{index-BlRVj-7Q.d.cts → index-D-B7U42V.d.cts} +2 -2
- package/dist/{index-B4s70vYf.d.ts → index-D-HZ7sP4.d.ts} +2 -2
- package/dist/{index-Cjrpx2Mg.d.cts → index-D7-RSD93.d.cts} +2 -2
- package/dist/{index-kBUQj-rT.d.ts → index-D9vBTuzo.d.ts} +2 -2
- package/dist/{index-DzCQt2FJ.d.cts → index-DJNAWzcH.d.cts} +2 -2
- package/dist/{index-DSSsxS7B.d.ts → index-DJVQ-t07.d.ts} +2 -2
- package/dist/{index-BwYGLgmI.d.ts → index-DKrIuF-r.d.ts} +2 -2
- package/dist/{index-DXSLMoma.d.ts → index-DOU1Ee_k.d.ts} +1 -1
- package/dist/{index-DlccEIi3.d.ts → index-DTDVDzhA.d.ts} +37 -3
- package/dist/{index-B5UR87KG.d.ts → index-DY2f2b9z.d.ts} +4 -2
- package/dist/{index-D8IyqHvT.d.cts → index-DeSsvHDD.d.cts} +4 -2
- package/dist/index-Di7OdwlO.d.ts +427 -0
- package/dist/{index-isdlyeeO.d.ts → index-DqICM_I7.d.ts} +80 -7
- package/dist/{index-DFe2Pk2u.d.ts → index-ML6vHKXK.d.ts} +1 -1
- package/dist/{index-RJIY7QVW.d.cts → index-UsU9ptzs.d.cts} +7 -4
- package/dist/{index-jA_OwwNg.d.ts → index-Vz7KPfgz.d.ts} +1 -1
- package/dist/index.cjs +50 -50
- package/dist/index.d.cts +32 -32
- package/dist/index.d.ts +32 -32
- package/dist/index.js +1 -1
- package/dist/meta-BYqlATmg.d.ts +98 -0
- package/dist/meta-DreaEM_a.d.cts +98 -0
- package/dist/patterns/ai/browser.cjs +2 -2
- package/dist/patterns/ai/browser.js +1 -1
- package/dist/patterns/ai/index.cjs +21 -21
- package/dist/patterns/ai/index.d.cts +9 -9
- package/dist/patterns/ai/index.d.ts +9 -9
- package/dist/patterns/ai/index.js +1 -1
- package/dist/patterns/ai/node.js +1 -1
- package/dist/patterns/audit/index.cjs +7 -7
- package/dist/patterns/audit/index.d.cts +5 -5
- package/dist/patterns/audit/index.d.ts +5 -5
- package/dist/patterns/audit/index.js +1 -1
- package/dist/patterns/cqrs/index.cjs +7 -7
- package/dist/patterns/cqrs/index.d.cts +4 -4
- package/dist/patterns/cqrs/index.d.ts +4 -4
- package/dist/patterns/cqrs/index.js +1 -1
- package/dist/patterns/demo-shell/index.cjs +8 -8
- package/dist/patterns/demo-shell/index.d.cts +4 -4
- package/dist/patterns/demo-shell/index.d.ts +4 -4
- package/dist/patterns/demo-shell/index.js +1 -1
- package/dist/patterns/domain-templates/index.cjs +7 -7
- package/dist/patterns/domain-templates/index.d.cts +3 -3
- package/dist/patterns/domain-templates/index.d.ts +3 -3
- package/dist/patterns/domain-templates/index.js +1 -1
- package/dist/patterns/graphspec/index.cjs +21 -21
- package/dist/patterns/graphspec/index.d.cts +3 -3
- package/dist/patterns/graphspec/index.d.ts +3 -3
- package/dist/patterns/graphspec/index.js +1 -1
- package/dist/patterns/guarded-execution/index.cjs +7 -7
- package/dist/patterns/guarded-execution/index.d.cts +6 -6
- package/dist/patterns/guarded-execution/index.d.ts +6 -6
- package/dist/patterns/guarded-execution/index.js +1 -1
- package/dist/patterns/harness/index.cjs +12 -12
- package/dist/patterns/harness/index.d.cts +8 -8
- package/dist/patterns/harness/index.d.ts +8 -8
- package/dist/patterns/harness/index.js +1 -1
- package/dist/patterns/job-queue/index.cjs +7 -7
- package/dist/patterns/job-queue/index.d.cts +4 -4
- package/dist/patterns/job-queue/index.d.ts +4 -4
- package/dist/patterns/job-queue/index.js +1 -1
- package/dist/patterns/lens/index.cjs +7 -7
- package/dist/patterns/lens/index.d.cts +4 -4
- package/dist/patterns/lens/index.d.ts +4 -4
- package/dist/patterns/lens/index.js +1 -1
- package/dist/patterns/memory/index.cjs +7 -7
- package/dist/patterns/memory/index.d.cts +6 -4
- package/dist/patterns/memory/index.d.ts +6 -4
- package/dist/patterns/memory/index.js +1 -1
- package/dist/patterns/messaging/index.cjs +7 -7
- package/dist/patterns/messaging/index.d.cts +4 -4
- package/dist/patterns/messaging/index.d.ts +4 -4
- package/dist/patterns/messaging/index.js +1 -1
- package/dist/patterns/orchestration/index.cjs +7 -7
- package/dist/patterns/orchestration/index.d.cts +4 -4
- package/dist/patterns/orchestration/index.d.ts +4 -4
- package/dist/patterns/orchestration/index.js +1 -1
- package/dist/patterns/process/index.cjs +1 -1
- package/dist/patterns/process/index.d.cts +5 -5
- package/dist/patterns/process/index.d.ts +5 -5
- package/dist/patterns/process/index.js +1 -1
- package/dist/patterns/reactive-layout/index.cjs +8 -8
- package/dist/patterns/reactive-layout/index.d.cts +4 -4
- package/dist/patterns/reactive-layout/index.d.ts +4 -4
- package/dist/patterns/reactive-layout/index.js +1 -1
- package/dist/patterns/reduction/index.cjs +7 -7
- package/dist/patterns/reduction/index.d.cts +3 -3
- package/dist/patterns/reduction/index.d.ts +3 -3
- package/dist/patterns/reduction/index.js +1 -1
- package/dist/patterns/refine-loop/index.cjs +8 -8
- package/dist/patterns/refine-loop/index.d.cts +5 -5
- package/dist/patterns/refine-loop/index.d.ts +5 -5
- package/dist/patterns/refine-loop/index.js +1 -1
- package/dist/patterns/resilient-pipeline/index.cjs +1 -1
- package/dist/patterns/resilient-pipeline/index.d.cts +4 -4
- package/dist/patterns/resilient-pipeline/index.d.ts +4 -4
- package/dist/patterns/resilient-pipeline/index.js +1 -1
- package/dist/patterns/surface/index.cjs +14 -14
- package/dist/patterns/surface/index.d.cts +4 -4
- package/dist/patterns/surface/index.d.ts +4 -4
- package/dist/patterns/surface/index.js +1 -1
- package/dist/{pipeline-graph-DdBoRu37.d.ts → pipeline-graph-9JBbmRxA.d.ts} +2 -2
- package/dist/{pipeline-graph-BlLBWSZ2.d.cts → pipeline-graph-DuHpXSOn.d.cts} +2 -2
- package/dist/{reactive-layout-D9zqqaqK.d.cts → reactive-layout-BMLDB4Vd.d.cts} +1 -1
- package/dist/{reactive-layout-Btv0-efV.d.ts → reactive-layout-D-tRiNhg.d.ts} +1 -1
- package/dist/{reactive-log-jirQsxMY.d.ts → reactive-log-BgWSA1fg.d.ts} +28 -1
- package/dist/{reactive-log-ScpWyqny.d.cts → reactive-log-C3IMAGpT.d.cts} +28 -1
- package/dist/resilience-LGBK236C.js +1 -0
- package/dist/{topology-tree-CJsT24DP.d.ts → topology-tree-D47-nI6Z.d.ts} +1 -1
- package/dist/{topology-tree-C50l9ARE.d.cts → topology-tree-jrZue3ao.d.cts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-3U7IIQB2.js +0 -1
- package/dist/chunk-533RQFF6.js +0 -1
- package/dist/chunk-5CZ3KIRJ.js +0 -1
- package/dist/chunk-5KPIYVCC.js +0 -7
- package/dist/chunk-5RTZ6DXG.js +0 -1
- package/dist/chunk-A5HZZYRK.js +0 -1
- package/dist/chunk-CGA5RXO6.js +0 -1
- package/dist/chunk-DBPFMCVH.js +0 -1
- package/dist/chunk-GWOKTENT.js +0 -1
- package/dist/chunk-JJTF75VS.js +0 -1
- package/dist/chunk-KL7CILPL.js +0 -1
- package/dist/chunk-M27MVZCP.js +0 -1
- package/dist/chunk-N2GCKKKH.js +0 -43
- package/dist/chunk-QKUWS7CO.js +0 -80
- package/dist/chunk-YBA5N4XY.js +0 -61
- package/dist/index-CI_yjtua.d.ts +0 -139
- package/dist/index-D9qoEOj_.d.cts +0 -139
- package/dist/meta-BGO6C7K9.d.cts +0 -41
- package/dist/meta-CC6EPdpK.d.ts +0 -41
- package/dist/resilience-OBU472D2.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 Zt=Object.defineProperty;var eo=Object.getOwnPropertyDescriptor;var to=Object.getOwnPropertyNames;var no=Object.prototype.hasOwnProperty;var xe=(t,e)=>()=>(t&&(e=t(t=0)),e);var ro=(t,e)=>{for(var n in e)Zt(t,n,{get:e[n],enumerable:!0})},oo=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of to(e))!no.call(t,s)&&s!==n&&Zt(t,s,{get:()=>e[s],enumerable:!(r=eo(e,s))||r.enumerable});return t};var so=t=>oo(Zt({},"__esModule",{value:!0}),t);var Le,I,Z,ee,Re,Ae,Pe,he,B,V,qe,xt,Fn,_t,$n,jn,Rt,en,tn,nn,Et,me=xe(()=>{"use strict";Le=Symbol.for("graphrefly/START"),I=Symbol.for("graphrefly/DATA"),Z=Symbol.for("graphrefly/DIRTY"),ee=Symbol.for("graphrefly/RESOLVED"),Re=Symbol.for("graphrefly/INVALIDATE"),Ae=Symbol.for("graphrefly/PAUSE"),Pe=Symbol.for("graphrefly/RESUME"),he=Symbol.for("graphrefly/TEARDOWN"),B=Symbol.for("graphrefly/COMPLETE"),V=Symbol.for("graphrefly/ERROR"),qe=Object.freeze([Z]),xt=Object.freeze([ee]),Fn=Object.freeze([Re]),_t=Object.freeze([Le]),$n=Object.freeze([B]),jn=Object.freeze([he]),Rt=Object.freeze([qe]),en=Object.freeze([xt]),tn=Object.freeze([Fn]),nn=Object.freeze([$n]),Et=Object.freeze([jn])});function Bn(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++]=rn,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 qn(t,e){if(t.length<zn)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${zn})`);let n=0,r=t[n++];if(r!==rn)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${rn})`);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 Kn(t){t.registerCodec(io)}var io,rn,zn,on=xe(()=>{"use strict";io={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)}},rn=1,zn=4});function Nt(t){if(t==null)return Je;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var Je,kt=xe(()=>{"use strict";Je={type:"system",id:""}});function ct(){return Ye>0||ut}function Hn(){return Ye>0}function Xe(t){Ye>0?dt.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(!ut){let n=dt.splice(0);for(let r of n)try{r()}catch{}Ke.length=0,He.length=0,Qe.length=0}}else ao()}}function ao(){let t=!ut;t&&(ut=!0);let e=[],n=0;try{for(;Ke.length>0||He.length>0||Qe.length>0||t&&dt.length>0;){if(t&&dt.length>0){let o=dt.splice(0);for(let i of o)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw Ke.length=0,He.length=0,Qe.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let s=(Ke.length>0?Ke:He.length>0?He:Qe).splice(0);for(let o of s)try{o()}catch(i){e.push(i)}}}finally{t&&(ut=!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||!ct()){t(e);return}(u>=5?Qe:u===4?He: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=ct();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?He.push(()=>t(u)):t(u)}if(r>i){let u=e.slice(i,r);d?Qe.push(()=>t(u)):t(u)}}var Ye,ut,Ke,He,Qe,dt,Ie=xe(()=>{"use strict";Ye=0,ut=!1,Ke=[],He=[],Qe=[],dt=[]});function U(){return Math.trunc(performance.now()*1e6)}function ye(){return Date.now()*1e6}var Ee=xe(()=>{"use strict"});function Un(t){t.registerMessageType(Le,{tier:0,wireCrossing:!1}),t.registerMessageType(Z,{tier:1,wireCrossing:!1}),t.registerMessageType(Re,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Ae,{tier:2,wireCrossing:!1}),t.registerMessageType(Pe,{tier:2,wireCrossing:!1}),t.registerMessageType(I,{tier:3,wireCrossing:!0}),t.registerMessageType(ee,{tier:3,wireCrossing:!0}),t.registerMessageType(B,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(V,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(he,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var Ot,Wn=xe(()=>{"use strict";me();Ot=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 Jn(t){return Array.isArray(t)?[...t]:[t]}function uo(t,e){return t.has(e)||t.has("*")}function Yn(t){let e=[];return t((s,o)=>{e.push({kind:"allow",actions:new Set(Jn(s)),where:o?.where??(()=>!0)})},(s,o)=>{e.push({kind:"deny",actions:new Set(Jn(s)),where:o?.where??(()=>!0)})}),(s,o)=>{let i=!1,a=!1;for(let d of e)uo(d.actions,o)&&d.where(s)&&(d.kind==="deny"?i=!0:a=!0);return i?!1:a}}function sn(t){let e=co.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,co,Ze=xe(()=>{"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}};co=["human","llm","wallet","system"]});function an(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(an);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=an(t[n]);return e}return null}function po(t){let e=fo.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,c=2773480762,h=1359893119,l=2600822924,p=528734635,f=1541459225,g=new Uint32Array(64),m=(T,v)=>T>>>v|T<<32-v;for(let T=0;T<s;T+=64){for(let O=0;O<16;O++)g[O]=i.getUint32(T+O*4,!1);for(let O=16;O<64;O++){let D=g[O-15],S=g[O-2],G=m(D,7)^m(D,18)^D>>>3,Q=m(S,17)^m(S,19)^S>>>10;g[O]=g[O-16]+G+g[O-7]+Q>>>0}let v=a,x=d,E=u,_=c,y=h,w=l,R=p,A=f;for(let O=0;O<64;O++){let D=m(y,6)^m(y,11)^m(y,25),S=y&w^~y&R,G=A+D+S+lo[O]+g[O]>>>0,Q=m(v,2)^m(v,13)^m(v,22),J=v&x^v&E^x&E,ve=Q+J>>>0;A=R,R=w,w=y,y=_+G>>>0,_=E,E=x,x=v,v=G+ve>>>0}a=a+v>>>0,d=d+x>>>0,u=u+E>>>0,c=c+_>>>0,h=h+y>>>0,l=l+w>>>0,p=p+R>>>0,f=f+A>>>0}let b=T=>T.toString(16).padStart(8,"0");return b(a)+b(d)+b(u)+b(c)+b(h)+b(l)+b(p)+b(f)}function un(t){let e=an(t??null),n=JSON.stringify(e);return po(n).slice(0,16)}function ho(){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 dn(t,e,n){let r=n?.id??ho();if(t===0)return{id:r,version:0};let o=(n?.hash??un)(e);return{id:r,version:0,cid:o,prev:null}}function Qn(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}var lo,fo,Xn=xe(()=>{"use strict";lo=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]),fo=new TextEncoder});function tr(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function cn(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function St(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function oe(t,e,n){let r=nr(t)?t:[],s=typeof t=="function"?t:typeof e=="function"?e:void 0,o={};return nr(t)?o=(ln(e)?e:n)??{}:ln(t)?o=t:o=(ln(e)?e:n)??{},new se(r,s,o)}var Zn,er,mo,go,et,se,nr,ln,Me=xe(()=>{"use strict";on();kt();Ie();Ee();Wn();Ze();me();Xn();Zn=()=>{},er=100;mo=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},go=(t,e,n,r)=>{let s=t;if(s._status==="completed"||s._status==="errored")return;let o=s._cached,i=o===void 0?[_t]:[_t,[I,o]];s._status==="dirty"&&i.push(qe),lt(e,i,s._config.tierOf)},et=new Ot({onMessage:mo,onSubscribe:go});Un(et);Kn(et);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??et,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??un;let s=r.versioning??this._config.defaultVersioning;this._versioningLevel=s,this._versioning=s!=null?dn(s,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(tr);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(St(a))},up(a){i._emitUp(St(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=dn(e,o,{id:a,hash:s});u.version=d,this._versioning=u,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let n=Nt(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=Nt(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:ye()}}down(e,n){let r=St(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=St(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=Nt(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)cn(d);if(this._partial===!1){for(let d of this._deps)if(d.prevData!==void 0||d.dataBatch.length!==0||d.terminal!==void 0||d.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let o;try{o=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:s},this._actions)}catch(d){throw this._sinkCount-=1,d}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(d){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof o=="function")try{o()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!0,this._sinkCount-=1,this._removeSink(e),typeof o=="function"&&o(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[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=Zn,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{}cn(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=tr(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Rt),r.unsub=Zn;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([[V,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([[V,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{}}cn(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===Z){this._depDirtied(r);return}if(s===Re){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(tn);return}if(s===Ae||s===Pe){this._emit([n]);return}if(s===he){this._emit(Et);return}if(s===I)this._depSettledAsData(r,n[1]);else if(s===ee)this._depSettledAsResolved(r);else if(s===B)this._depSettledAsTerminal(r,!0);else if(s===V)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(s===I||s===ee)&&this._emit([n]),(s===B||s===V)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Rt))}_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(en),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([[V,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(nn)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(i){this._emit([[V,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([[V,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([[V,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>er?(this._rerunDepth=0,this._emit([[V,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${er} \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"?[qe,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]===Z&&(o=!0),i=u}let a=e;if(!r){let d=e.map((u,c)=>({m:u,i:c,tier:n(u[0])}));d.sort((u,c)=>u.tier-c.tier||u.i-c.i),a=d.map(u=>u.m)}if(s&&!o&&this._status!=="dirty"){let d=0;for(;d<a.length&&n(a[d][0])===0;)d++;return d===0?[qe,...a]:[...a.slice(0,d),qe,...a.slice(d)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let d=e[a];if(d[0]===V&&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]===he||d[0]===Re);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!==Ae&&u!==Pe){s?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===Ae?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let h=d[1];if(u===Ae)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))c=!1;else if(this._pauseLocks.delete(h),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let l=this._pauseBuffer;this._pauseBuffer=[],this._emit(l)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?s?.push(d):s==null&&(s=n.slice(0,a))}if(s!=null){if(s.length===0)return;n=s}if(this._hasMeta&&n.some(a=>a[0]===he))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Et)}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([[V,i]])}_updateState(e){let n=this._config.tierOf,r,s,o=-1,i=0;for(let c of e)n(c[0])===3&&i++;let a=i<=1,d=-1;if(this._versioning!=null&&i>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===I){d=c;break}}for(let c=0;c<e.length;c++){let h=e[c],l=h[0];if(l===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=c;break}if(p){r==null&&(r=e.slice(0,c)),r.push(xt),this._status="resolved";continue}this._cached=h[1],this._versioning!=null&&(d<0||c===d)&&Qn(this._versioning,h[1],this._hashFn)}this._status="settled",r?.push(h)}else if(r?.push(h),l===Z)this._status="dirty";else if(l===ee)this._status="resolved";else if(l===B){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(l===V){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(l===Re){if(this._cached!==void 0){let f=this._config.rigorRecorder;if(f!=null)try{f.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let 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 l===he&&(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(Hn()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],Xe(()=>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)}},nr=t=>Array.isArray(t),ln=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function F(t,e){return oe([],{...e,initial:t})}function de(t,e){return oe((r,s,o)=>t(s,o)??void 0,{describeKind:"producer",...e})}function P(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 ue=xe(()=>{"use strict";Me()});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;case"spec":return new Set(["type","deps","meta"]);default:return new Set(["type","deps"])}}function yo(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function ft(t){let e=new WeakSet,n={};for(let[r,s]of rr(t))n[r]=fn(s,e);return n}function fn(t,e){if(t==null)return t;let n=typeof t;if(n==="boolean"||n==="number"||n==="string")return t;if(n==="function")return"<function>";if(Array.isArray(t))return e.has(t)?"<cycle>":(e.add(t),t.map(r=>fn(r,e)));if(n==="object"){let r=t;if(e.has(r))return"<cycle>";e.add(r);try{if(typeof r.subscribe=="function"&&"cache"in r)return"<Node>"}catch{return"<unserializable>"}let s={};for(let[o,i]of rr(r))s[o]=fn(i,e);return s}return"<unserializable>"}function rr(t){let e=[],n;try{n=Object.keys(t)}catch{return e}for(let r of n)try{e.push([r,t[r]])}catch{e.push([r,"<unserializable>"])}return e}function tt(t,e){let n={factory:t};return e!==void 0&&(n.factoryArgs=e),n}function bo(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=yo(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={...bo(t)};if(d!=null&&u.access===void 0&&(u.access=sn(d)),r!=null&&r.length>0&&!e.has("meta")){let c={};for(let h of r)h in u&&(c[h]=u[h]);a.meta=c}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=sn(d)),(n||e.has("lastMutation"))&&t.lastMutation!=null&&(a.lastMutation=t.lastMutation),a}var pt=xe(()=>{"use strict";Ze();Me()});function hn(t){return{describeKind:"producer",...t}}function or(t,e){return de(n=>{let r=!1;try{for(let s of t){if(r)return;n.emit(s)}r||n.down([[B]])}catch(s){r||n.down([[V,s]])}return()=>{r=!0}},hn(e))}function vo(t){return t!=null&&typeof t.then=="function"}function To(t,e){let{signal:n,...r}=e??{};return de(s=>{let o=!1,i=()=>{o||(o=!0,s.down([[V,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([[B]]))},a=>{o||(o=!0,n?.removeEventListener("abort",i),s.down([[V,a]]))}),()=>{o=!0,n?.removeEventListener("abort",i)}},hn(r))}function wo(t,e){let{signal:n,...r}=e??{};return de(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](),c=()=>{d||a.aborted||Promise.resolve(u.next()).then(h=>{if(!(d||a.aborted)){if(h.done){s.down([[B]]);return}s.emit(h.value),c()}},h=>{!d&&!a.aborted&&s.down([[V,h]])})};return c(),()=>{d=!0,n?.removeEventListener("abort",i),o.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},hn(r))}function xo(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function Fe(t,e){if(xo(t))return t;if(vo(t))return To(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return wo(t,e);if(typeof n[Symbol.iterator]=="function")return or(t,e)}return _o(t)}function _o(...t){return or(t,void 0)}function sr(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]===V){n.abort(d[1]),i();return}if(d[0]===B){i();return}}}),o&&(s?.(),s=void 0),{signal:n.signal,dispose:()=>{s&&(s(),s=void 0)}}}function be(t){return t.subscribe(()=>{})}var Ue=xe(()=>{"use strict";me();ue()});var It,dr=xe(()=>{"use strict";It=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 si={};ro(si,{DEFAULT_DECAY_RATE:()=>rt,DEFAULT_EXECUTE_PROMPT:()=>gn,DEFAULT_QUEUE_CONFIGS:()=>Ct,DEFAULT_SEVERITY_WEIGHTS:()=>nt,DEFAULT_TRIAGE_PROMPT:()=>mn,DEFAULT_VERIFY_PROMPT:()=>yn,HarnessGraph:()=>Qt,QUEUE_NAMES:()=>we,actuatorExecutor:()=>ar,affectedTaskFilter:()=>Lo,autoSolidify:()=>Mo,beforeAfterCompare:()=>Go,codeChangeBridge:()=>Po,createIntakeBridge:()=>Co,defaultErrorClassifier:()=>Dt,defaultLlmExecutor:()=>Yr,defaultLlmVerifier:()=>Qr,dispatchActuator:()=>Ao,evalIntakeBridge:()=>Do,evalSource:()=>Io,evalVerifier:()=>Pr,harnessEvalPair:()=>Ks,harnessLoop:()=>Zs,harnessProfile:()=>ti,harnessTrace:()=>ri,notifyEffect:()=>Vo,priorityScore:()=>Qs,refineExecutor:()=>Mn,resolvePromptFn:()=>mt,strategyKey:()=>ot,strategyModel:()=>Ln});module.exports=so(si);me();ue();me();pt();Me();ue();Ue();function Mt(t){return{describeKind:"derived",...t}}function Ro(t){return{describeKind:"derived",partial:!0,...t}}function Ve(t,e,n){return oe([t],(r,s)=>{let o=r[0];if(o==null||o.length===0){s.down([[ee]]);return}let i=!1;for(let a of o)e(a)&&(s.emit(a),i=!0);i||s.down([[ee]])},{...Mt(n),meta:{...tt("filter"),...n?.meta??{}}})}function ht(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([[ee]]);return}for(let u of i)s.emit([u,d])}else s.down([[ee]])},{...Ro(n),meta:{...tt("withLatestFrom"),...n?.meta??{}}})}function ir(...t){return t.length===0?de(e=>{e.down([[B]])},{...Mt(),meta:{...tt("merge")}}):de(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]===B?(r+=1,r>=n&&e.down([[B]])):d[0]===V&&e.down([d])});s.push(i)}return()=>{for(let o of s)o()}},{...Mt(),meta:{...tt("merge")}})}function Eo(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]===B?a=!0:u[0]===V?(d=!0,e.down([u])):(u[0]===Z||u[0]===ee)&&e.down([u]));d?(r?.(),r=void 0,o()):a&&o()}),()=>{r?.(),r=void 0}}function ke(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([[B]]);return}let u=i[0];if(!(u==null||u.length===0))return o(),r=Eo(Fe(e(u[u.length-1])),a,()=>{o(),s&&a.down([[B]])}),{deactivate:()=>{o(),s=!1}}},{...Mt(n),completeWhenDepsComplete:!1,meta:{...tt("switchMap"),...n?.meta??{}}})}Ue();function No(t,e){return{outcome:"success",detail:`actuator applied ${e.intervention} for ${So(e.summary)}`,artifact:t}}function ko(t,e){let n=t instanceof Error?t.message:String(t);return{outcome:"failure",detail:`actuator threw on ${e.intervention}: ${n}`}}function Oo(t){return`actuator skipped ${t.intervention} (shouldApply returned false)`}function So(t,e=80){return t.length<=e?t:`${t.slice(0,e-1)}\u2026`}function ar(t){let e=t.name??"actuator-executor",n=t.toOutput??No,r=t.onError??ko,s=t.skipDetail??Oo;return o=>{let i=Ve(o,d=>d!=null,{name:`${e}/gate-in`}),a=ke(i,d=>t.shouldApply&&!t.shouldApply(d)?de(u=>(u.down([[I,{outcome:"failure",detail:s(d)}],[B]]),()=>{}),{name:`${e}/skip`}):de(u=>{let c=new AbortController,h=!1,l=null,p=g=>{h||(h=!0,u.down([[I,g],[B]]),l?.(),l=null)},f;try{let g=t.apply(d,{signal:c.signal});f=Fe(g,{signal:c.signal})}catch(g){return p(r(g,d)),()=>{c.abort()}}return l=f.subscribe(g=>{for(let m of g){if(h)return;if(m[0]===I){p(n(m[1],d));return}if(m[0]===V){p(r(m[1],d));return}if(m[0]===B){p(r(new Error("actuator inner completed without emitting DATA"),d));return}}}),h&&l&&(l(),l=null),()=>{c.abort(),l?.(),l=null}},{name:`${e}/inner`}),{name:e});return Ve(a,d=>d!=null,{name:`${e}/gate-out`})}}function Ao(t){let e=t.name??"dispatch-actuator",n=t.default??null,r=n!=null;return ar({apply:(s,o)=>{let i=Object.hasOwn(t.routes,s.intervention)?t.routes[s.intervention]:n;if(!i)throw new Error(`dispatchActuator: no route for intervention '${s.intervention}'`);return i(s,o)},shouldApply:s=>Object.hasOwn(t.routes,s.intervention)||r,skipDetail:s=>`no route for intervention '${s.intervention}'`,name:e})}me();ue();function Mo(t){let e=t.name??"auto-solidify",n=t.extract??(s=>s.execution.artifact??null),r=t.predicate??(()=>!0);return de(s=>{let o=null,i=!1,a=()=>{i||(i=!0,o?.(),o=null)},d=u=>{i||(s.down([[V,u]]),a())};return o=t.verifyResults.subscribe(u=>{if(!i)for(let c of u){if(i)return;if(c[0]!==I){if(c[0]===B){s.down([[B]]),a();return}continue}let h=c[1];if(h==null||!h.verified)continue;let l;try{l=r(h)}catch(f){d(f);return}if(!l)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})}ue();Ue();function Co(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 Do(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 Io(t,e){return ke(t,()=>Fe(e()))}function Go(t,e){return P([t,e],([n,r])=>{let s=n,o=r,i=new Map(s.tasks.map(l=>[l.task_id,l])),a=new Map(o.tasks.map(l=>[l.task_id,l])),d=new Set([...i.keys(),...a.keys()]),u=[],c=[],h=[];for(let l of d){let p=i.get(l),f=a.get(l),g=p?.valid??!1,m=f?.valid??!1,b=p?.judge_scores?p.judge_scores.filter(x=>x.pass).length:void 0,T=f?.judge_scores?f.judge_scores.filter(x=>x.pass).length:void 0,v=b!==void 0&&T!==void 0?T-b:void 0;u.push({taskId:l,before:g,after:m,scoreDiff:v}),g&&!m&&c.push(l),!g&&m&&h.push(l)}return{newFailures:c,resolved:h,taskDeltas:u,overallImproved:h.length>c.length}},{name:"eval-delta"})}function Lo(t,e){let n=e==null?null:Array.isArray(e)?F(e):e,r=[t];return n&&r.push(n),P(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 Po(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 Vo(t,e,n){return ge([t.latest],([r])=>{r!=null&&e(r)},{name:n?.name??"notify-effect"})}var we=["auto-fix","needs-decision","investigation","backlog"],Ct={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},nt={critical:100,high:70,medium:40,low:10},rt=Math.LN2/(168*3600);function ot(t,e){return`${t}\u2192${e}`}var Fo=/\b(parse|json|config|validation|syntax)\b/i,Dt=t=>Fo.test(t.detail)?"self-correctable":"structural",mn=`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
|
{
|
|
@@ -13,7 +13,7 @@ Strategy model (past effectiveness):
|
|
|
13
13
|
{{strategy}}
|
|
14
14
|
|
|
15
15
|
Intake item:
|
|
16
|
-
{{item}}`,
|
|
16
|
+
{{item}}`,gn=`You are an implementation agent.
|
|
17
17
|
|
|
18
18
|
Given a triaged issue with root cause and intervention type, produce a fix.
|
|
19
19
|
|
|
@@ -24,7 +24,7 @@ Output JSON:
|
|
|
24
24
|
{
|
|
25
25
|
"outcome": "success" | "failure" | "partial",
|
|
26
26
|
"detail": "<description of what was done or what failed>"
|
|
27
|
-
}`,
|
|
27
|
+
}`,yn=`You are a QA reviewer.
|
|
28
28
|
|
|
29
29
|
Given an execution result, verify whether the fix is correct.
|
|
30
30
|
|
|
@@ -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
|
|
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
|
|
45
|
-
`)}function
|
|
46
|
-
`);return e.logger?.(o),o}function
|
|
47
|
-
`)}function
|
|
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:
|
|
42
|
+
}`;function mt(t,e,n){if(typeof t=="function")return t;let r=t??e;return s=>n(r,s)}ue();ue();Ie();Ee();me();Me();ue();kt();Ie();Ee();Ze();me();pt();Me();ue();Ee();function bn(t,e){if(Object.is(t,e))return!0;if(t==null||e==null||typeof t!="object"||typeof e!="object")return!1;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(let o=0;o<t.length;o++)if(!bn(t[o],e[o]))return!1;return!0}if(Array.isArray(e))return!1;let n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;let s=new Set(r);for(let o of n)if(!s.has(o)||!bn(t[o],e[o]))return!1;return!0}function ur(t,e){return`${t}\0${e}`}function vn(t,e){let n=[],r=new Set(t.subgraphs),s=new Set(e.subgraphs),o=[];for(let m of s)r.has(m)||o.push(m);o.sort();for(let m of o)n.push({type:"subgraph-mounted",path:m});let i=new Set(Object.keys(t.nodes)),a=new Set(Object.keys(e.nodes)),d=[];for(let m of a)i.has(m)||d.push(m);d.sort();for(let m of d)n.push({type:"node-added",path:m,node:{...e.nodes[m]}});let u=[];for(let m of a){if(!i.has(m))continue;let b=t.nodes[m]?.meta,T=e.nodes[m]?.meta;b==null&&T==null||bn(b??{},T??{})||u.push(m)}u.sort();for(let m of u)n.push({type:"node-meta-changed",path:m,prevMeta:t.nodes[m]?.meta??{},nextMeta:e.nodes[m]?.meta??{}});let c=new Map;for(let m of t.edges)c.set(ur(m.from,m.to),m);let h=new Map;for(let m of e.edges)h.set(ur(m.from,m.to),m);let l=[];for(let[m,b]of h)c.has(m)||l.push(b);l.sort((m,b)=>m.from<b.from?-1:m.from>b.from?1:m.to<b.to?-1:m.to>b.to?1:0);for(let m of l)n.push({type:"edge-added",from:m.from,to:m.to});let p=[];for(let[m,b]of c)h.has(m)||p.push(b);p.sort((m,b)=>m.from<b.from?-1:m.from>b.from?1:m.to<b.to?-1:m.to>b.to?1:0);for(let m of p)n.push({type:"edge-removed",from:m.from,to:m.to});let f=[];for(let m of i)a.has(m)||f.push(m);f.sort();for(let m of f)n.push({type:"node-removed",path:m});let g=[];for(let m of r)s.has(m)||g.push(m);g.sort();for(let m of g)n.push({type:"subgraph-unmounted",path:m});return{events:n,flushedAt_ns:U()}}Ue();dr();var gt=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}};on();function Tn(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 Gt(t){let e=0;for(let n of t)e+=Tn(n.codePointAt(0));return e}function cr(t,e){if(e<=0)return"";let n=0,r="";for(let s of t){let o=Tn(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-=Tn(i.codePointAt(0))}return`${r}\u2026`}r+=s,n+=o}return r}var $o={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"},jo={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function hr(t,e){let n=e.charset==="ascii"?jo:$o,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)Bo(o,i,n,a);for(let a of t.boxes)zo(o,i,n,a,e.labelOf(a.id));return o.map(a=>Uo(a.join(""))).join(`
|
|
43
|
+
`)}function zo(t,e,n,r,s){let{x:o,y:i,w:a,h:d}=r;if(a<2||d<2){d>0&&lr(t,e,o,i,a,s);return}$e(t,e,o,i,n.boxTL);for(let c=o+1;c<o+a-1;c+=1)$e(t,e,c,i,n.boxH);$e(t,e,o+a-1,i,n.boxTR);for(let c=i+1;c<i+d-1;c+=1){$e(t,e,o,c,n.boxV);for(let h=o+1;h<o+a-1;h+=1)mr(t,e,h,c," ","empty");$e(t,e,o+a-1,c,n.boxV)}$e(t,e,o,i+d-1,n.boxBL);for(let c=o+1;c<o+a-1;c+=1)$e(t,e,c,i+d-1,n.boxH);$e(t,e,o+a-1,i+d-1,n.boxBR);let u=i+Math.floor(d/2);lr(t,e,o+1,u,a-2,s)}function $e(t,e,n,r,s){mr(t,e,n,r,s,s===" "?"empty":s==="\u2500"||s==="-"?"boxH":s==="\u2502"||s==="|"?"boxV":"boxCorner")}function mr(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 lr(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=Gt(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 Bo(t,e,n,r){let s=r.points;if(s.length<2)return;for(let d=0;d+1<s.length;d+=1)qo(t,e,n,s[d],s[d+1]);for(let d=1;d+1<s.length;d+=1){let u=s[d-1],c=s[d],h=s[d+1],l=Ko(u,c,h,n);l&&pr(t,e,c.x,c.y,l,"edgeCorner")}let o=s[s.length-1],i=s[s.length-2],a=Ho(i,o,n);a&&pr(t,e,o.x,o.y,a,"arrow")}function qo(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)fr(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)fr(t,e,o,d,n,"v")}}}function fr(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 pr(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 Ko(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 Ho(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 Uo(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function br(t){let e=Wo(t);Jo(e),Yo(e),Qo(e),Xo(e,t);let n=ts(e,t),{width:r,height:s}=rs(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 Wo(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 Jo(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 Yo(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 l=`__virt_${s++}__`,p={id:l,isVirtual:!0,layer:i.layer+h,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(l,p),n[p.layer].push(p);let f={chainId:o.chainId,chainFrom:o.chainFrom,chainTo:o.chainTo,fromId:u.id,toId:l,hopIndex:h-1,chainLen:d};u.out.push(f),p.in.push(f),r.push(f),u=p}let c={chainId:o.chainId,chainFrom:o.chainFrom,chainTo:o.chainTo,fromId:u.id,toId:a.id,hopIndex:d-1,chainLen:d};u.out.push(c),a.in.push(c),r.push(c)}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 Qo(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)gr(t,t.layers[r],"in"),Lt(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)gr(t,t.layers[r],"out"),Lt(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=yr(t,o[i],o[i+1],"in");[o[i],o[i+1]]=[o[i+1],o[i]],Lt(o),yr(t,o[i],o[i+1],"in")<a?r=!0:([o[i],o[i+1]]=[o[i+1],o[i]],Lt(o))}}if(!r)break}}function gr(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 Lt(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function yr(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,c=t.nodes.get(r==="in"?d.fromId:d.toId)?.order??0;(e.order<n.order&&u>c||e.order>n.order&&u<c)&&(i+=1)}return i}function Xo(t,e){e.direction==="LR"?Zo(t,e):es(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}vr(t,e,"y")}function es(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}vr(t,e,"x")}function vr(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 c of a){let h=o===0?c.in:c.out;if(h.length===0)continue;let l=[];for(let f of h){let g=t.nodes.get(o===0?f.fromId:f.toId);if(!g)continue;let m=n==="y"?g.y:g.x;l.push(m+Math.floor(r(g)/2))}if(l.length===0)continue;l.sort((f,g)=>f-g);let p=l[Math.floor(l.length/2)];d.set(c.id,p-Math.floor(r(c)/2))}let u=0;for(let c of a){let h=d.get(c.id),l=n==="y"?c.y:c.x,f=Math.max(h??l,u);n==="y"?c.y=f:c.x=f,u=f+r(c)+s}}}}function ts(t,e){let n=new Map;for(let u of t.hops){let c=n.get(u.chainId);c?c.push(u):n.set(u.chainId,[u])}for(let u of n.values())u.sort((c,h)=>c.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 c=t.layers[u],h=t.layers[u+1],l=0;for(let w of c)l=Math.max(l,s(w)+o(w));let p=Number.POSITIVE_INFINITY;for(let w of h)p=Math.min(p,s(w));let f=Number.isFinite(p)?p-1:l,g=Math.max(1,f-l+1),m=[];for(let w of c)for(let R of w.out)m.push(R);m.sort((w,R)=>{let A=i(t.nodes.get(w.fromId)),O=i(t.nodes.get(R.fromId));if(A!==O)return A-O;let D=i(t.nodes.get(w.toId)),S=i(t.nodes.get(R.toId));return D-S});let b=[],T=new Map;for(let w of m){let R=i(t.nodes.get(w.fromId)),A=i(t.nodes.get(w.toId)),O=Math.min(R,A),D=Math.max(R,A),S=-1;for(let G=0;G<b.length;G+=1){let Q=b[G],J=!0;for(let ve of Q)if(ve.lo<=D&&O<=ve.hi){J=!1;break}if(J){Q.push({lo:O,hi:D}),S=G;break}}S<0&&(b.push([{lo:O,hi:D}]),S=b.length-1),T.set(w,S)}let v=b.length,x=g>=Math.max(3,v+2),E=x?l+1:l,_=x?f-1:f,y=Math.max(1,_-E+1);for(let w of m){let R=T.get(w),A;if(v<=1)A=E+Math.floor(y/2);else{let O=(y-1)/(v-1);A=E+Math.floor(R*O)}a.set(w,Math.max(l,Math.min(f,A)))}}let d=[];for(let[,u]of n){let c=[];for(let l=0;l<u.length;l+=1){let p=u[l],f=t.nodes.get(p.fromId),g=t.nodes.get(p.toId),m=a.get(p),b=f.isVirtual?s(f):s(f)+o(f),T=g.isVirtual?s(g):s(g)-1,v=i(f),x=i(g);l===0&&Pt(c,r,b,v),v!==x&&(Pt(c,r,m,v),Pt(c,r,m,x)),Pt(c,r,T,x)}let h=u[0];d.push({from:h.chainFrom,to:h.chainTo,points:ns(c)})}return d}function Pt(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function ns(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 rs(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 os=24,ss=4,is=1,as=3;function Tr(t,e){let n=us(e.direction),r=Math.max(3,e.maxLabelWidth??os),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=cr(p,r);d.set(p,f),u.set(p,Gt(f)+4)}let c=br({nodes:o,edges:a,widthCells:p=>u.get(p)??3,heightCells:()=>as,layerGap:ss,nodeGap:is,direction:n}),h=hr(c,{charset:s,labelOf:p=>d.get(p)??p}),l=e.logger;return l&&l(h),h}function us(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 wr(t,e,n,r={}){let s=e in t.nodes,o=n in t.nodes;if(!s)return Vt(e,n,"no-such-from");if(!o)return Vt(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=ds(t,e,r);if(u!=null)return u}let d=Ft(e,t.nodes[e],0,r);return $t(e,n,[d])}if(i===0)return Vt(e,n,"no-path");let a=xr(t,e,n,i);return a.found?$t(e,n,_r(t,a.pathOrder,r)):Vt(e,n,a.truncated?"max-depth-exceeded":"no-path")}function xr(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 l=t.nodes[h.path];if(l==null)continue;let p=l.deps??[],f=new Map;for(let g=0;g<p.length;g++){let m=p[g];if(!m)continue;let b=f.get(m);b==null&&(b=[],f.set(m,b)),b.push(g)}for(let[g,m]of f)i.has(g)||(i.add(g),s.set(g,{from:h.path,depIndices:m}),o.push({path:g,depth:h.depth+1}))}if(!s.has(e))return{found:!1,pathOrder:[],truncated:d};let u=[{path:e}],c=e;for(;c!==n;){let h=s.get(c);if(h==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=h.depIndices,u.push({path:h.from}),c=h.from}return{found:!0,pathOrder:u,truncated:!1}}function ds(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=Ft(e,r,0,n);a.dep_index=o[0];let d=Ft(e,r,1,n);return $t(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=xr(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:$t(e,e,_r(t,i.pathOrder,n))}function _r(t,e,n){return e.map((r,s)=>{let o=t.nodes[r.path],i=Ft(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 Ft(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 $t(t,e,n){return Rr(t,e,!0,"ok",n)}function Vt(t,e,n){return Rr(t,e,!1,n,[])}function Rr(t,e,n,r,s){let o=cs(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 cs(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: ${ls(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 ls(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)}}Me();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},fs=Symbol.for("sizeof");function Er(t){let e=new WeakSet,n=new WeakSet,r=[t],s=0;for(;r.length>0;){let o=r.pop();s+=ps(o,e,n,r)}return s}function ps(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+hs(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[fs];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,c=o.stack?o.stack.length*2:0;return ie.error+u+c}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[c,h]of o)u+=ie.mapEntry,r.push(c),r.push(h);return u}if(o instanceof Set){let u=ie.set;for(let c of o)u+=ie.setEntry,r.push(c);return u}if(Array.isArray(o)){let u=ie.array+o.length*8;for(let c of o)r.push(c);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 hs(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 jt(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[l,p]of s)i.set(l,p);let a=[];for(let[l,p]of Object.entries(r.nodes)){let f=i.get(l),g=f instanceof se?f:null,m=g?Er(g.cache):0,b=g?g._sinkCount:0,T=p.deps?.length??0,v=p.type==="effect"&&b===0,x=b===0?p.type==="effect"?"orphan-effect":p.type==="derived"?"idle-derived":p.type==="producer"?"idle-producer":null:null;a.push({path:l,type:p.type,status:p.status??"unknown",valueSizeBytes:m,subscriberCount:b,depCount:T,isOrphanEffect:v,orphanKind:x})}let d=a.reduce((l,p)=>l+p.valueSizeBytes,0),u=(l,p)=>[...a].sort(p??((f,g)=>g[l]-f[l])).slice(0,n),c=a.filter(l=>l.orphanKind!=null),h=a.filter(l=>l.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:c,orphanEffects:h}}var te="::",Oe="__meta__",We=1;function Nr(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 Sr(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"&&typeof t.down=="function"}function ms(t){if(t!=null)return Sr(t)?t.cache:t}function gs(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 kr(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 ys(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 l=o;if(s.length!==l.length)return!1;for(let p=0;p<s.length;p++)if(!r(s[p],l[p]))return!1;return!0}if(s instanceof Map){let l=o;if(s.size!==l.size)return!1;for(let[p,f]of s)if(!l.has(p)||!r(f,l.get(p)))return!1;return!0}if(s instanceof Set){let l=o;if(s.size!==l.size)return!1;for(let p of s){let f=!1;for(let g of l)if(r(p,g)){f=!0;break}if(!f)return!1}return!0}if(ArrayBuffer.isView(s)){let l=s,p=o;if(l.length!==p.length)return!1;for(let f=0;f<l.length;f++)if(l[f]!==p[f])return!1;return!0}let u=Object.keys(s),c=Object.keys(o);if(u.length!==c.length)return!1;let h=new Set(c);for(let l of u)if(!h.has(l)||!r(s[l],o[l]))return!1;return!0};return r(t,e)}function xn(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(xn);let e=t,n=Object.keys(e).sort(),r={};for(let s of n)r[s]=xn(e[s]);return r}function bs(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function vs(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Ts(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function Ar(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 Mr(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 ws(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(xn(i),null,e.indent??2);return e.logger?.(a),a}function xs(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}): ${Bt(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 Cr(t,e){let n=Mr(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}["${bs(i)}"]`)}for(let[i,a]of Ar(t)){let d=s.get(i),u=s.get(a);!d||!u||o.push(` ${d} --> ${u}`)}return o.join(`
|
|
47
|
+
`)}function _s(t,e){let n=Cr(t,e);return Dr(n)}function Dr(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 Rs(t,e){let n=Mr(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: ${Ts(n)}`];for(let i of r){let a=s.get(i);o.push(`${a}: "${vs(i)}"`)}for(let[i,a]of Ar(t)){let d=s.get(i),u=s.get(a);!d||!u||o.push(`${d} -> ${u}`)}return o.join(`
|
|
48
|
+
`)}function Es(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function zt(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+=Es(r)}return e+="$",new RegExp(e)}var Ns={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"},ks={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function Bt(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 Os(t){return t==="none"?ks:t==="ansi"||t==null?Ns:{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 Or(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 Ss(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 wn(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===Oe)throw new Error(`Graph "${e}": ${n} name "${Oe}" is reserved for meta companion paths`);Ss(t,e,n)}function As(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 Ms(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 Ir(t){for(let e of t._mounts.values())Ir(e);for(let e of t._nodes.values())try{e.down([[he]],{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;_factory;_factoryArgs;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===Oe)throw new Error(`Graph name "${Oe}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??et,this._traceRing=new gt(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning),typeof n?.factory=="string"&&(this._factory=n.factory,n.factoryArgs!==void 0&&(this._factoryArgs=n.factoryArgs))}tagFactory(e,n){return this._factory=e,this._factoryArgs=n,this}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=de(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(wn(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:U()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof se&&n._applyVersioning(e)}remove(e){wn(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}${Oe}${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,Ir(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([[he]],{internal:!0});let s={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:s}),s}removeAll(e){let n=typeof e=="function"?e:(()=>{let o=zt(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([[Re]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let s=r?.internal===!0;this.node(e).down([[V,n]],{actor:r?.actor,internal:s,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[B]],{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 c of u._deps){let h=r.get(c.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 c=o.get(u.node);c!=null&&i.push([c,a])}return i.sort((a,d)=>a[0]<d[0]?-1:a[0]>d[0]?1:a[1]<d[1]?-1:a[1]>d[1]?1:0),i}mount(e,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(wn(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=As(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]===Oe)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]!==Oe)throw new Error(`Graph "${this.name}": expected ${Oe} segment in meta path "${r}"`);if(o+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${Oe} 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=Ms(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(c){if(c instanceof Ne)throw c;s.push(c)}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==="diff")return this._describeReactiveDiff(e);if(e?.reactive===!0)return this._describeReactive(e);let n=ms(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[_,y]of a)d.set(y,_);let u=[];{let _=a.map(([,R])=>R),y=new Set(d.values()),w=0;for(;_.length>0;){let R=_.shift();if(R instanceof se)for(let A of R._deps){let O=A.node;if(d.has(O))continue;let D=O.name??"",S=D;if(!S||y.has(S))if(D){let G=2;for(;y.has(`${D}#${G}`);)G++;S=`${D}#${G}`}else for(S=`__internal__/${w++}`;y.has(S);)S=`__internal__/${w++}`;d.set(O,S),y.add(S),u.push([S,O]),_.push(O)}}}let c=[...a,...u],h={};for(let[_,y]of c){if(n!=null&&!y.allowsObserve(n))continue;let w=pn(y,i),R=y instanceof se?y._deps.map(S=>d.get(S.node)??S.node.name??""):[],{name:A,...O}=w,D={...O,deps:R};if(!o){let S=this._annotations.get(_);S!=null&&(D.annotation=S)}if(r!=null)if(typeof r=="function"){let S=r;if(!(S.length>=2?S(_,D):S(D)))continue}else{let S=!0;for(let[G,Q]of Object.entries(r)){let J=G==="deps_includes"?"depsIncludes":G==="meta_has"?"metaHas":G;if(J==="depsIncludes"){if(!D.deps.includes(String(Q))){S=!1;break}continue}if(J==="metaHas"){if(!Object.hasOwn(D.meta??{},String(Q))){S=!1;break}continue}if(D[J]!==Q){S=!1;break}}if(!S)continue}h[_]=D}let l=new Set(Object.keys(h)),p=[];for(let[_,y]of c)if(y instanceof se)for(let w of y._deps){let R=d.get(w.node);R!=null&&p.push([R,_])}p.sort((_,y)=>_[0]<y[0]?-1:_[0]>y[0]?1:_[1]<y[1]?-1:_[1]>y[1]?1:0);let f=p.map(([_,y])=>({from:_,to:y}));(n!=null||r!=null)&&(f=f.filter(_=>l.has(_.from)&&l.has(_.to)));let g=this._collectSubgraphs(""),m=n!=null||r!=null?g.filter(_=>{let y=`${_}${te}`;return[...l].some(w=>w===_||w.startsWith(y))}):g,b=this,T=e,v={name:this.name,nodes:h,edges:f,subgraphs:m,...this._factory!==void 0?{factory:this._factory}:{},...this._factoryArgs!==void 0?{factoryArgs:this._factoryArgs}:{},expand(_){let y={...T,format:void 0};return Array.isArray(_)?(y.fields=_,y.detail=void 0):(y.detail=_,y.fields=void 0),b.describe(y)}},x=e??{},E=x.format;return E==="json"?ws(v,x):E==="pretty"?xs(v,x):E==="mermaid"?Cr(v,x):E==="mermaid-url"?_s(v,x):E==="d2"?Rs(v,x):E==="ascii"?Tr(v,x):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 jt(this,e)}reachable(e,n,r={}){return r.withDetail===!0?_n(this.describe(),e,n,{...r,withDetail:!0}):_n(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 wr(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=F(s,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,Xe(()=>{a=!1,!d&&(s+=1,o.emit(s))}))},c=i.onEvent(T=>{let v=T.type;v!=="data"&&v!=="error"&&v!=="complete"&&v!=="teardown"||u()}),h=[],l=new WeakSet,p=T=>{if(l.has(T)||d)return;l.add(T);let v=T.topology.subscribe(x=>{for(let E of x){if(E[0]!==I)continue;let _=E[1];if(u(),_.kind==="added"&&_.nodeKind==="mount"){let y=T._mounts.get(_.name);y!=null&&p(y)}}});h.push(v);for(let x of T._mounts.keys()){let E=T._mounts.get(x);E!=null&&p(E)}};p(this);let f,g=e.actor;Sr(g)&&(f=g.subscribe(T=>{let v=!1,x=!1;for(let E of T){let _=E[0];_===I?v=!0:(_===B||_===V||_===he)&&(x=!0)}v&&u(),x&&(f?.(),f=void 0,u())}));let m;try{m=P([o],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(T,v)=>T===v})}catch(T){c(),f?.();for(let v of h)v();throw i.dispose(),T}let b=be(m);return{node:m,dispose(){d=!0,c(),f?.();for(let T of h)T();h.length=0,i.dispose(),b()}}}_describeReactiveDiff(e){let n={...e,format:void 0,reactive:!1},r=e.reactiveName??"describe-diff",s={name:this.name,nodes:{},edges:[],subgraphs:[]},o=this.describe(n),i=vn(s,o),a=F(i,{name:r,meta:{domain:"audit",kind:"describe-diff"},equals:(l,p)=>l===p}),d=this._describeReactive({...e,format:void 0,reactiveName:void 0}),u=!1,c=d.node.subscribe(l=>{if(!u)for(let p of l){if(p[0]!==I)continue;let f=p[1],g=vn(o,f);o=f,g.events.length!==0&&a.emit(g)}}),h=be(a);return{node:a,dispose(){u=!0,c(),d.dispose(),a.down([[he,"describe-diff disposed"]]),h()}}}_explainReactive(e,n,r){let s=0,o=F(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,Xe(()=>{a=!1,!d&&(s+=1,o.emit(s))}))}),c={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},h;try{h=P([o],()=>this._explainStatic(e,n,c),{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&&Cs(p.steps,f.steps)})}catch(p){throw u(),i.dispose(),p}let l=be(h);return{node:h,dispose(){d=!0,u(),i.dispose(),l()}}}_pathsMatching(e){let n=zt(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}${Oe}${te}${s}`;r.push([i,o]),this._appendMetaObserveTargets(i,o,r)}}observe(e,n){let r=typeof e=="string",o=Or(r?n:e);if(o.reactive===!0)return this._observeReactive(r?e:void 0,o);let i=o.structured===!0||o.timeline===!0||o.causal===!0||o.derived===!0||o.detail==="minimal"||o.detail==="full"||o.format!=null,a=o.actor;if(r){let c=e,h=this.resolve(c);if(a!=null&&!h.allowsObserve(a))throw new Ne({actor:a,action:"observe",nodeName:c});return i?this._buildStructuredObserver([[c,h]],o,"one"):{subscribe(l){return h.subscribe(l)},up(l){try{h.up?.(l)}catch(p){if(p instanceof Ne)return;throw p}}}}let d=[];this._collectObserveTargets("",d),d.sort((c,h)=>c[0]<h[0]?-1:c[0]>h[0]?1:0);let u=a==null?d:d.filter(([,c])=>c.allowsObserve(a));return i?this._buildStructuredObserver(u,o,"all"):{subscribe:c=>{let h=u.map(([l,p])=>p.subscribe(f=>{c(l,f)}));return()=>{for(let l of h)l()}},up:(c,h)=>{try{this.resolve(c).up?.(h)}catch(l){if(l instanceof Ne)return;throw l}}}}_observeReactive(e,n){let r=n.tiers,s=r!=null?new Set(r):null,o=n.reactiveName??"observe";return de(i=>{let a=[],d=!1,u=!1,c=()=>{if(a.length===0||u)return;let g={events:a.slice(),flushedAt_ns:U()};a.length=0,i.emit(g)},h={...n,reactive:!1,structured:!0,timeline:!0},l=e!=null?this.observe(e,h):this.observe(h),p=g=>{u||(a.push(g),!d&&(d=!0,Xe(()=>{d=!1,c()})))};for(let g of l.events)p(g);let f=l.onEvent(p);return()=>{u=!0,f(),l.dispose()}},{name:o,meta:{domain:"audit",kind:"observe-reactive"}})}_buildStructuredObserver(e,n,r){let s=r==="one"?e[0]?.[0]:void 0,o=i=>{if(r==="one"&&s!=null){let c=this.resolve(s);return this._buildStructuredObserver([[s,c]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((c,h)=>c[0]<h[0]?-1:c[0]>h[0]?1:0);let d=i.actor,u=d==null?a:a.filter(([,c])=>c.allowsObserve(d));return this._buildStructuredObserver(u,i,"all")};return this._createObserveResult(e,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,c=n.maxEvents,h=c!=null&&c>0?new gt(c):null,l=[],p=new Set,f=n.tiers!=null?new Set(n.tiers):null,g={},m=new Set,b=0,T=0,v=0,x=0,E=0,_=0,y=!1,w=!1,R=0,A=new Map,O=new Map,D=new Map,S=M=>{if(!(f!=null&&!f.has(M.type))){h?h.push(M):l.push(M);for(let H of p)H(M)}},G=M=>f==null||f.has(M),Q=()=>s?{timestamp_ns:U(),in_batch:ct(),batch_id:R}:{},J=(M,H)=>{if(!(!u||!(M instanceof se)))return M._setInspectorHook(fe=>{if(fe.kind==="dep_message")A.set(M,fe.depIndex);else if(fe.kind==="run"){let Se=fe.batchData.map((N,L)=>N!=null&&N.length>0?N.at(-1):fe.prevData[L]);O.set(M,Se);let pe=fe.batchData.map(N=>N!=null?[...N]:void 0);D.set(M,pe),i&&S({type:"derived",path:H,dep_values:Se,dep_batches:pe,...Q()})}})},ve=M=>{let H=A.get(M),fe=O.get(M);if(!o||fe==null)return{};let pe=(H!=null&&H>=0&&M instanceof se?M._deps[H]:void 0)?.node,N=pe?.v,L=D.get(M);return{trigger_dep_index:H,trigger_dep_name:pe?.name,...N!=null?{trigger_version:{id:N.id,version:N.version}}:{},dep_values:[...fe],...L!=null?{dep_batches:L}:{}}},Ce=[],j=[];for(let[M,H]of e){let fe=J(H,M);fe&&Ce.push(fe),j.push(H.subscribe(Se=>{R++;for(let pe of Se){let N=pe[0],L=Q();if(N===I){g[M]=pe[1];let Y=H instanceof se?H.lastMutation?.actor??Je:Je;S({type:"data",path:M,data:pe[1],actor:Y,...L,...ve(H)})}else if(a)N===Z?G("dirty")&&b++:N===ee?G("resolved")&&T++:N===Re?G("invalidate")&&v++:N===Ae?G("pause")&&x++:N===Pe?G("resume")&&E++:N===he?G("teardown")&&_++:N===B&&!m.has(M)?G("complete")&&(y=!0):N===V&&G("error")&&(w=!0,m.add(M));else if(N===Z)G("dirty")&&b++,S({type:"dirty",path:M,...L});else if(N===ee)G("resolved")&&T++,S({type:"resolved",path:M,...L,...ve(H)});else if(N===Re)G("invalidate")&&v++,S({type:"invalidate",path:M,...L});else if(N===Ae)G("pause")&&x++,S({type:"pause",path:M,lockId:pe[1],...L});else if(N===Pe)G("resume")&&E++,S({type:"resume",path:M,lockId:pe[1],...L});else if(N===B)G("complete")&&!m.has(M)&&(y=!0),S({type:"complete",path:M,...L});else if(N===V){G("error")&&(w=!0,m.add(M));let Y=H instanceof se?H.lastMutation?.actor??Je:Je;S({type:"error",path:M,data:pe[1],actor:Y,...L})}else N===he&&(G("teardown")&&_++,S({type:"teardown",path:M,...L}))}}))}let z=!1,$=()=>{if(!z){z=!0;for(let M of j)M();for(let M of Ce)M();for(let M of ne)M({value:void 0,done:!0});ne.length=0}},ae=[],ne=[];p.add(M=>{let H=ne.shift();H?H({value:M,done:!1}):ae.push(M)});let le={get values(){return g},get dirtyCount(){return b},get resolvedCount(){return T},get invalidateCount(){return v},get pauseCount(){return x},get resumeCount(){return E},get teardownCount(){return _},get events(){return h?h.toArray():[...l]},get anyCompletedCleanly(){return y},get anyErrored(){return w},get completedWithoutErrors(){return y&&!w},onEvent(M){return p.add(M),()=>p.delete(M)},dispose:$,expand(M){$();let H={...n};return typeof M=="string"?H.detail=M:Object.assign(H,M),r(Or(H))},[Symbol.asyncIterator](){return{next(){return ae.length>0?Promise.resolve({value:ae.shift(),done:!1}):z?Promise.resolve({value:void 0,done:!0}):new Promise(M=>ne.push(M))},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=Os(n.theme),u=r==="stage-log"?U():0,c=f=>f==null?"":n.stageLabels?.[f]??f,h=(f,g)=>f.length>g?`${f.slice(0,g-1)}\u2026`:f,l=f=>f.type==="data"||f.type==="error"?h(Bt(f.data),120):"",p=f=>{if(r==="stage-log"){let y=(U()-u)/1e9,w=c(f.path).padEnd(9);if(f.type==="data"){let R=l(f);return`[${y.toFixed(3)}s] ${w} \u2190${R?` ${R}`:""}`}if(f.type==="error"){let R=l(f);return`[${y.toFixed(3)}s] ${w} \u2717${R?` ${R}`:""}`}return f.type==="complete"?`[${y.toFixed(3)}s] ${w} \u25A0 complete`:`[${y.toFixed(3)}s] ${w} ${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]??"",m=f.path?`${d.path}${f.path}${d.reset} `:"",b=f.type==="data"||f.type==="error",T=f.type==="pause"||f.type==="resume",v=b?` ${Bt(f.data)}`:T?` ${Bt(f.lockId)}`:"",x=f.type==="data"||f.type==="resolved"||f.type==="derived"?f:void 0,E=x?.trigger_dep_name!=null?` <- ${x.trigger_dep_name}`:x?.trigger_dep_index!=null?` <- #${x.trigger_dep_index}`:"",_=f.in_batch?" [batch]":"";return`${m}${g}${f.type.toUpperCase()}${d.reset}${v}${E}${_}`};e.onEvent(f=>{a(f.type)&&s(p(f),f)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){Nr(this._disposers,this.name),this.signal([[he]],{internal:!0}),Nr(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,...c}=r.nodes[a];s[a]=c}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 Bn(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??et,{codec:s,codecVersion:o,payload:i}=qn(e,r);return s.decode(i,o)}restore(e,n){if(kr(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=>zt(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){kr(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 m=f.split(te).length,b=g.split(te).length;return m!==b?m-b:f<g?-1:f>g?1:0})){let f=p.split(te),g=o;for(let m of f)g._mounts.has(m)||g.mount(m,new t(m)),g=g._mounts.get(m)}let i=s?Object.entries(s).map(([p,f])=>({re:zt(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 m=o;for(let b of f){let T=m._mounts.get(b);if(!T)throw new Error(`unknown mount "${b}" in path "${p}"`);m=T}return[m,g]},u=Object.entries(e.nodes).filter(([p])=>!p.includes(`${te}${Oe}${te}`)).sort((p,f)=>p[0]<f[0]?-1:p[0]>f[0]?1:0),c=new Map(u),h=new Map,l=!0;for(;c.size>0&&l;){l=!1;for(let[p,f]of[...c.entries()]){let g=f?.deps??[];if(!g.every(E=>h.has(E)))continue;let[m,b]=d(p),T={...f?.meta??{}},v=a(p),x;if(f?.type==="state")x=F(f.value,{meta:T});else{if(v==null)continue;x=v(b,{path:p,type:f.type,value:f.value,meta:T,deps:g,resolvedDeps:g.map(E=>h.get(E))})}m.add(x,{name:b}),h.set(p,x),c.delete(p),l=!0}}if(c.size>0){let p=[...c.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,c)=>{if(u.disposed)return;let h=gs(c.nodes);if(u.lastSnapshot!=null&&h!==""&&h===u.lastFingerprint)return;let l=u.seq+1,p=ye(),m=u.lastSnapshot==null||l%u.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:l,timestamp_ns:p,format_version:We}:{name:this.name,mode:"diff",diff:Gr(u.lastSnapshot,c),seq:l,timestamp_ns:p,format_version:We};if(u.tier.filter&&!u.tier.filter(m))return;let b;try{b=u.tier.save(m)}catch(T){n.onError?.(T,u.tier);return}if(b&&typeof b.then=="function"){let x=(u.savePending??Promise.resolve()).then(()=>b,()=>b).then(()=>{u.disposed||(u.seq=l,u.lastSnapshot=c,u.lastFingerprint=h)},E=>{n.onError?.(E,u.tier)});u.savePending=x.finally(()=>{u.savePending===x&&(u.savePending=void 0)})}else u.seq=l,u.lastSnapshot=c,u.lastFingerprint=h},o=(u,c)=>{try{s(u,c)}catch(h){n.onError?.(h,u.tier)}},i=(u,c)=>{if(!c.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 l,p=()=>(l==null&&(l=this.snapshot()),l);for(let f of r)f.disposed||(f.debounceMs===0?o(f,p()):(f.timer==null&&(f.timer=new It),f.timer.start(f.debounceMs,()=>{f.disposed||o(f,this.snapshot())})))},a;if(n.paths!=null){let c=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(h=>{let l=this.tryResolve(h);return l==null?()=>{}:l.subscribe(p=>i(h,p))});a=()=>{for(let h of c)h()}}else a=this.observe().subscribe((u,c)=>i(u,c));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:U(),...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 v=e.nodes[T],x=n.nodes[T],E=v.v,_=x.v;E!=null&&_!=null&&E.id===_.id&&E.version!==_.version&&d.push({path:T,id:E.id,from:E.version,to:_.version});let y=E!=null&&_!=null&&E.id===_.id&&E.version===_.version;for(let w of["type","status","sentinel"]){let R=v[w],A=x[w];R!==A&&a.push({path:T,field:w,from:R,to:A})}if(!y)for(let w of["value","meta"]){let R=v[w],A=x[w];ys(R,A)||a.push({path:T,field:w,from:R,to:A})}}let u=T=>`${T.from} ${T.to}`,c=new Set(e.edges.map(u)),h=new Set(n.edges.map(u)),l=n.edges.filter(T=>!c.has(u(T))),p=e.edges.filter(T=>!h.has(u(T))),f=new Set(e.subgraphs),g=new Set(n.subgraphs),m=[...g].filter(T=>!f.has(T)).sort(),b=[...f].filter(T=>!g.has(T)).sort();return{nodesAdded:o,nodesRemoved:i,nodesChanged:a,versionChanges:d,edgesAdded:l,edgesRemoved:p,subgraphsAdded:m,subgraphsRemoved:b}}};function Gr(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 _n(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,c=new Set;for(let[v,x]of Object.entries(t.nodes)){if(!v)continue;c.add(v);let E=x.deps??[];i.set(v,E);for(let _ of E)_&&(c.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 x=typeof v.from=="string"?v.from:"",E=typeof v.to=="string"?v.to:"";!x||!E||(c.add(x),c.add(E),u.has(x)||u.set(x,new Set),u.get(x).add(E),d.has(E)||d.set(E,new Set),d.get(E).add(x))}if(!c.has(e))return r.withDetail?s:[];let h=r.both===!0,l=v=>{if(h){let y=i.get(v)??[],w=d.get(v),R=a.get(v),A=u.get(v),O=[...y];return w&&O.push(...w),R&&O.push(...R),A&&O.push(...A),O}if(n==="upstream"){let y=i.get(v)??[],w=d.get(v);return w?[...y,...w]:y}let x=a.get(v),E=u.get(v),_=x?[...x]:[];return E&&_.push(...E),_},p=new Set([e]),f=new Map,g=[{path:e,depth:0}],m=0,b=!1;for(;m<g.length;){let v=g[m++];if(o!=null&&v.depth>=o){l(v.path).length>0&&(b=!0);continue}for(let x of l(v.path))!x||p.has(x)||(p.add(x),f.set(x,v.depth+1),g.push({path:x,depth:v.depth+1}))}let T=[...f.keys()].sort((v,x)=>v<x?-1:v>x?1:0);return r.withDetail?{paths:T,depths:f,truncated:b}:T}function Cs(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}kt();Ie();Ze();me();ue();Me();Ie();me();Me();ue();var Rn=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 yt(t){return t.subscribe(()=>{})}var Ds=64;function qt(t,e={}){let{name:n,maxSize:r,versioning:s,guard:o,backend:i}=e,a=i??new Rn(t,r),d=F(a.toArray(),{name:n,describeKind:"state",equals:(y,w)=>y===w,...s!=null?{versioning:s}:{},...o!=null?{guard:o}:{}});function u(){let y=a.toArray();re(()=>{d.down([[Z]],{internal:!0}),d.down([[I,y]],{internal:!0})})}let c=new Map,h=new Map,l=new Map;function p(y,w){return`${y}:${w===void 0?"END":w}`}function f(y){if(y.size<Ds)return;let w=y.keys().next();if(w.done)return;let R=y.get(w.value);R!==void 0&&R.dispose(),y.delete(w.value)}function g(y){let w=a.version;try{return y()}finally{a.version!==w&&u()}}function m(y){if(!Number.isInteger(y)||y<0)throw new RangeError(`tail: n must be a non-negative integer (got ${y})`);let w=c.get(y);if(w!==void 0)return c.delete(y),c.set(y,w),w.node;f(c);let R=P([d],([O])=>{let D=O;return y===0||D.length===0?[]:D.slice(Math.max(0,D.length-y))},{initial:a.tail(y),describeKind:"derived"}),A=yt(R);return c.set(y,{node:R,dispose:A}),R}function b(y,w){if(!Number.isInteger(y)||y<0)throw new RangeError(`slice: start must be a non-negative integer (got ${y})`);if(w!==void 0&&(!Number.isInteger(w)||w<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${w})`);let R=p(y,w),A=h.get(R);if(A!==void 0)return h.delete(R),h.set(R,A),A.node;f(h);let O=P([d],([S])=>{let G=S;return w===void 0?G.slice(y):G.slice(y,w)},{initial:a.slice(y,w),describeKind:"derived"}),D=yt(O);return h.set(R,{node:O,dispose:D}),O}function T(y){let w=l.get(y);if(w!==void 0)return w.node;let R=P([d,y],([O,D])=>{let S=O,G=Math.max(0,Math.trunc(D??0));return S.slice(G)},{initial:[],describeKind:"derived"}),A=yt(R);return l.set(y,{node:R,dispose:A}),R}let v,x;function E(){v===void 0&&(v=oe([d],(y,w,R)=>{let A=y[0],D=A!=null&&A.length>0?A.at(-1):R.prevData[0];if(D==null||D.length===0){w.down([[ee]]);return}w.emit(D[D.length-1])},{name:n!=null?`${n}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),x=P([d],([y])=>y.length>0,{name:n!=null?`${n}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),yt(v),yt(x))}let _={entries:d,get size(){return a.size},at(y){return a.at(y)},append(y){g(()=>a.append(y))},appendMany(y){y.length!==0&&g(()=>a.appendMany(y))},clear(){g(()=>a.clear())},trimHead(y){g(()=>a.trimHead(y))},withLatest(){return E(),d},get lastValue(){return E(),v},get hasLatest(){return E(),x},view(y){switch(y.kind){case"tail":return m(y.n);case"slice":return b(y.start,y.stop);case"fromCursor":return T(y.cursor)}},attach(y){let w=y.subscribe(R=>{for(let A of R)A[0]===I&&_.append(A[1])});return()=>w()},attachStorage(y){if(y.length===0)return()=>{};let w=new Map;for(let A of y)w.set(A,a.size);(async()=>{for(let A of y)if(typeof A.loadEntries=="function")try{let O=await Promise.resolve(A.loadEntries());O.entries.length>0&&a.size===0&&(a.restore(O.entries),w.set(A,O.entries.length),u());break}catch{}})();let R=d.subscribe(A=>{for(let O of A){if(O[0]!==I)continue;let D=O[1];for(let S of y){let G=w.get(S)??0;if(D.length<G){try{let J=S.appendEntries(D);J instanceof Promise&&J.catch(()=>{})}catch{}w.set(S,D.length);continue}if(D.length===G)continue;let Q=D.slice(G);w.set(S,D.length);try{let J=S.appendEntries(Q);J instanceof Promise&&J.catch(()=>{})}catch{}}}});return()=>R()},disposeAllViews(){for(let y of c.values())y.dispose();c.clear();for(let y of h.values())y.dispose();h.clear();for(let y of l.values())y.dispose();l.clear()},dispose(){for(let y of c.values())y.dispose();c.clear();for(let y of h.values())y.dispose();h.clear();for(let y of l.values())y.dispose();l.clear()}};return _}me();Ue();function En(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[Z],[I,n+1]]),!0)}function je(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function bt(t){return t.relatedTo?.[0]??t.summary}var Is=256;function st(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 Gs=1024,Nn=class extends ce{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=qt([],{name:"events",maxSize:n.retainedLimit??Gs}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=P([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(be(this.latest)),this.hasLatest=P([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:ze("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(be(this.hasLatest)),this.addDisposer(()=>{this.events.down([[B]])}),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}},Kt=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=st(r.from,"subscription from"):s=st(r.cursor??0,"subscription cursor"),this.cursor=F(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(be(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(be(a))}}ack(e){if(this._disposed)return this.cursor.cache;let n=this.available.cache,r=e===void 0?n.length:st(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:st(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:st(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([[B]]),this.destroy())}},kn=class extends ce{_sourceSub;bridgedCount;output;constructor(e,n,r,s={}){super(e,s.graph),this._sourceSub=Ps(`${e}-subscription`,n,{cursor:s.cursor}),this.mount("subscription",this._sourceSub);let o=Math.max(1,st(s.maxPerPump??Is,"topic bridge maxPerPump")),i=s.map??(l=>l);this.output=P([this._sourceSub.available],([l])=>{let p=l,f=[],g=Math.min(p.length,o);for(let m=0;m<g;m++){let b=i(p[m]);b!==void 0&&f.push(b)}return f},{name:"output",describeKind:"derived",meta:ze("topic_bridge_output",{targetRef:r.name}),initial:[]}),this.add(this.output,{name:"output"}),this.addDisposer(be(this.output)),this.bridgedCount=F(0,{name:"bridgedCount",describeKind:"state",meta:ze("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"}),this.addDisposer(be(this.bridgedCount));let a=this.output,d=this._sourceSub,u=this.bridgedCount,c=oe([a],()=>{let l=a.cache;if(l.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+l.length)}},{name:"ackPump",describeKind:"effect",meta:ze("topic_bridge_ack_pump")});this.add(c,{name:"ackPump"}),this.addDisposer(be(c));let h=Ls(this.output,r);this.addDisposer(h)}};function Ls(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 On=class{_map=new Map;version;constructor(e){this.version=e}get size(){return this._map.size}has(e){return this._map.has(e)}get(e){return this._map.get(e)}set(e,n){this._map.set(e,n)}delete(e){return this._map.delete(e)}keys(){return this._map.keys()}},Sn=class extends ce{_registry;version;_defaultTopicOptions;constructor(e,n={}){super(e,n.graph);let r=F(0,{name:"version",describeKind:"state",meta:ze("hub_version")});this.add(r,{name:"version"}),this.version=r,this._registry=new On(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 Nn(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 Kt(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 Ht(t,e){return new Sn(t,e)}function Ps(t,e,n){return new Kt(t,e,n)}function An(t,e,n,r){return new kn(t,e,n,r)}function Vs(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 Fs(t,e){if(t.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(t.length===1){let o=$s(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 $s(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 Lr(t,e,n,r){let s=r.name??"refine-loop",o=new ce(s,r.graph),i=Vs(r.dataset)?r.dataset:F(r.dataset,{name:"dataset"});o.add(i,{name:"dataset"});let a=F(0,{name:"iteration"});o.add(a,{name:"iteration"});let d=F(n,{name:"strategy",equals:()=>!1});o.add(d,{name:"strategy"});let u=F(null,{name:"lastFeedback"});o.add(u,{name:"lastFeedback"});let c=F([],{name:"prevCandidates"});o.add(c,{name:"prevCandidates"});let h=F(!1,{name:"paused"});o.add(h,{name:"paused"});let l=F("running",{name:"status"});o.add(l,{name:"status"});let p=F([],{name:"history",equals:()=>!1});o.add(p,{name:"history"});let f=F(null,{name:"best"});o.add(f,{name:"best"});let g=F(Number.NEGATIVE_INFINITY,{name:"score"});o.add(g,{name:"score"});let m=F(0,{name:"budget-used"});o.add(m,{name:"budget-used"});let b=Ht("stages");o.mount("stages",b);let T=b.topic("generate"),v=b.topic("evaluate"),x=b.topic("analyze"),E=b.topic("decide"),_=n,y=null,w=[];o.addDisposer(d.subscribe(N=>{for(let L of N)L[0]===I&&(_=L[1])})),o.addDisposer(u.subscribe(N=>{for(let L of N)L[0]===I&&(y=L[1])})),o.addDisposer(c.subscribe(N=>{for(let L of N)L[0]===I&&(w=L[1])}));let R=ke(a,N=>{let L=_,Y=N===0||y==null;return oe([],(q,k)=>{let C=!1;try{let K=Y?L.seed(t):L.generate(y,w);if(K instanceof Promise)return K.then(W=>{C||k.emit(W)},W=>{C||k.down([[V,W]])}),()=>{C=!0};k.emit(K)}catch(K){C=!0,k.down([[V,K]])}},{describeKind:"producer"})},{name:"candidates"});o.add(R,{name:"candidates"});let A=ge([R],(N,L,Y)=>{let q=Y.terminalDeps[0];q!==void 0&&q!==!0&&l.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});o.add(A,{name:"error-watcher"}),o.addDisposer(A.subscribe(()=>{}));let O=P([R,a],([N,L])=>({iteration:L,candidates:N,timestamp_ns:U()}),{name:"generate-event"});o.add(O,{name:"generate-event"}),o.addDisposer(O.subscribe(()=>{}));let D=ge([O],([N])=>{T.publish(N)},{name:"generate-publish"});o.add(D,{name:"generate-publish"}),o.addDisposer(D.subscribe(()=>{}));let S=ge([R],([N])=>{c.emit(N)},{name:"generate-mirror"});o.add(S,{name:"generate-mirror"}),o.addDisposer(S.subscribe(()=>{}));let G=e(R,i);o.add(G,{name:"scores"});let Q=P([G,R,a],([N,L,Y])=>({iteration:Y,candidates:L,scores:N,timestamp_ns:U()}),{name:"evaluate-event"});o.add(Q,{name:"evaluate-event"}),o.addDisposer(Q.subscribe(()=>{}));let J=ge([Q],([N])=>{v.publish(N)},{name:"evaluate-publish"});o.add(J,{name:"evaluate-publish"}),o.addDisposer(J.subscribe(()=>{}));let ve=P([G,R],([N,L])=>_.analyze(N,L),{name:"feedback"});o.add(ve,{name:"feedback"});let Ce=P([ve,R,a],([N,L,Y])=>({iteration:Y,candidates:L,feedback:N,timestamp_ns:U()}),{name:"analyze-event"});o.add(Ce,{name:"analyze-event"}),o.addDisposer(Ce.subscribe(()=>{}));let j=ge([Ce],([N])=>{x.publish(N)},{name:"analyze-publish"});o.add(j,{name:"analyze-publish"}),o.addDisposer(j.subscribe(()=>{}));let z=P([p],([N])=>{let L=N;if(r.patience==null||L.length<=r.patience)return!1;let Y=L.slice(-(r.patience+1)),q=Y[0].bestScore;return Y.slice(1).every(k=>k.bestScore<=q)},{name:"patience-check"});o.add(z,{name:"patience-check"});let $=P([g],([N])=>r.minScore!=null&&N>=r.minScore,{name:"min-score-check"});o.add($,{name:"min-score-check"});let ae=P([p],([N])=>{let L=N;if(r.minDelta==null||L.length<2)return!1;let Y=L[L.length-2].bestScore,q=L[L.length-1].bestScore;return Math.abs(q-Y)<r.minDelta},{name:"min-delta-check"});o.add(ae,{name:"min-delta-check"});let ne=P([m],([N])=>r.maxEvaluations!=null&&N>=r.maxEvaluations,{name:"max-evaluations-check"});o.add(ne,{name:"max-evaluations-check"});let le=P([a],([N])=>r.maxIterations!=null&&N>=r.maxIterations,{name:"max-iterations-check"});o.add(le,{name:"max-iterations-check"});let M=P([m],([N])=>r.budget!=null&&N>=r.budget,{name:"budget-exhausted-check"});o.add(M,{name:"budget-exhausted-check"}),o.addDisposer(z.subscribe(()=>{})),o.addDisposer($.subscribe(()=>{})),o.addDisposer(ae.subscribe(()=>{})),o.addDisposer(ne.subscribe(()=>{})),o.addDisposer(le.subscribe(()=>{})),o.addDisposer(M.subscribe(()=>{}));let H=P([z,$,ae,ne,le],([N,L,Y,q,k])=>N?{converged:!0,reason:"patience"}:L?{converged:!0,reason:"min-score"}:Y?{converged:!0,reason:"min-delta"}:q?{converged:!0,reason:"max-evaluations"}:k?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});o.add(H,{name:"converged"}),o.addDisposer(H.subscribe(()=>{}));let fe=-1,Se=ge([ve,G,R],([N,L,Y])=>{let q=a.cache,k=N,C=Y,K=L;if(q<=fe)return;fe=q;let{best:W,bestScore:De}=Fs(C,K),at=p.cache,Be={n:q,candidates:C,scores:K,feedback:k,best:W,bestScore:De,timestamp_ns:U()},X=[...at,Be],_e=m.cache+C.length,Te="continue",Ge,Pn=r.budget!=null&&_e>=r.budget,Vn=h.cache;if(Pn)Te="budget",Ge="budget";else if(r.minScore!=null&&k.score>=r.minScore)Te="converged",Ge="min-score";else if(r.maxIterations!=null&&q>=r.maxIterations)Te="converged",Ge="max-iterations";else if(r.maxEvaluations!=null&&_e>=r.maxEvaluations)Te="converged",Ge="max-evaluations";else if(r.minDelta!=null&&X.length>=2){let wt=X[X.length-2].bestScore,Xt=X[X.length-1].bestScore;Math.abs(Xt-wt)<r.minDelta&&(Te="converged",Ge="min-delta")}else if(r.patience!=null&&X.length>r.patience){let wt=X.slice(-(r.patience+1)),Xt=wt[0].bestScore;wt.slice(1).every(Zr=>Zr.bestScore<=Xt)&&(Te="converged",Ge="patience")}Te==="continue"&&Vn&&(Te="paused"),re(()=>{f.emit(W),g.emit(k.score),p.emit(X),m.emit(_e),u.emit(k),E.publish({iteration:q,decision:Te,reason:Ge,timestamp_ns:U()}),Te==="continue"?a.emit(q+1):l.emit(Te==="converged"?"converged":Te==="budget"?"budget":"paused")})},{name:"decide-bridge"});return o.add(Se,{name:"decide-bridge"}),o.addDisposer(Se.subscribe(()=>{})),Object.assign(o,{best:f,score:g,status:l,history:p,strategy:d,iteration:a,generate:T,evaluate:v,analyze:x,decide:E,setStrategy(N){d.emit(N)},pause(){h.emit(!0)},resume(){l.cache==="paused"&&re(()=>{h.emit(!1),l.emit("running"),a.emit(a.cache+1)})}})}function js(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 Mn(t){let e=t.name??"refine-executor",n=t.toOutput??js;return r=>{let s=Ve(r,i=>i!=null,{name:`${e}/gate-in`}),o=ke(s,i=>{let a=Lr(t.seedFrom(i),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(i),name:`${e}/inner`});return P([a.status,a.best,a.score],([d,u,c])=>{let h=d;return h!=="converged"&&h!=="budget"&&h!=="errored"?null:n({best:u,score:c,status:h})},{name:`${e}/output`})},{name:e});return Ve(o,i=>i!=null,{name:`${e}/gate-out`})}}function zs(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 Bs(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 qs(t){return t.artifact??null}function Pr(t){let e=t.name??"eval-verifier",n=t.threshold??.5,r=t.toOutput??Bs,s=t.extractArtifact??qs;return o=>{let i=Ve(o,d=>d!=null&&d[0]!=null&&d[1]!=null,{name:`${e}/gate-in`}),a=ke(i,d=>{let[u,c]=d,h=s(u,c);if(h==null)return F(r({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:n,missingArtifact:!0}));let l=F([h],{name:`${e}/candidates`}),p=F(t.datasetFor(c),{name:`${e}/dataset`}),f=t.evaluator(l,p);return P([f],([g])=>{let m=g;if(m==null)return null;let b=zs(m),T=m.filter(v=>v.score>=n).length;return r({scores:m,meanScore:b,passCount:T,total:m.length,threshold:n})},{name:`${e}/output`})},{name:e});return Ve(a,d=>d!=null,{name:`${e}/gate-out`})}}function Ks(t){let e=t.name??"harness-pair",n=Mn({name:`${e}-exec`,seedFrom:t.seedFrom,evaluator:t.evaluator,strategy:t.strategy,datasetFor:t.datasetFor,refine:t.refine}),r=Pr({name:`${e}-verify`,evaluator:t.evaluator,datasetFor:t.datasetFor,threshold:t.threshold});return{executor:n,verifier:r}}Ee();pt();Me();ue();Ie();Ee();me();ue();var Cn=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=U(),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=U(),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 U()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??U())>=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 Ut(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 Cn({maxSize:n,defaultTtl:r}),d=F(a.toMap(),{name:e,describeKind:"state",equals:(l,p)=>l===p,...s!=null?{versioning:s}:{}});function u(){let l=a.toMap();re(()=>{d.down([[Z]]),d.down([[I,l]])})}function c(){if(!i)return;let l=a.toMap(),p=i.archiveThreshold,f=i.maxSize,g=[];for(let[b,T]of l)g.push({key:b,value:T,score:i.score(b,T)});g.sort((b,T)=>b.score-T.score);let m=new Set;if(p!==void 0)for(let b of g)if(b.score<p)m.add(b.key);else break;if(f!==void 0&&g.length-m.size>f)for(let b of g){if(g.length-m.size<=f)break;m.has(b.key)||m.add(b.key)}if(m.size!==0)for(let b of g)m.has(b.key)&&(i.onArchive?.(b.key,b.value,b.score),a.delete(b.key))}function h(l,p="mutation"){let f=a.version;try{return l()}finally{a.version!==f&&(p==="mutation"&&c(),u())}}return{entries:d,has(l){return h(()=>a.has(l),"read")},get(l){return h(()=>a.get(l),"read")},set(l,p,f){h(()=>a.set(l,p,f?.ttl))},setMany(l,p){h(()=>a.setMany(l,p?.ttl))},delete(l){h(()=>a.delete(l))},deleteMany(l){h(()=>a.deleteMany(l))},clear(){h(()=>a.clear())},pruneExpired(){h(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}function vt(t,e){return je("ai",t,e)}function Vr(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}me();ue();Ue();function Fr(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function Hs(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Wt(t,e,n,r){let s=r?.format??"text",o=r?.name??"prompt_node",i=P(e,d=>{if(d.some(c=>c==null))return[];let u=typeof n=="string"?n:n(...d);return u?[{role:"user",content:u}]:[]},{name:`${o}::messages`,meta:vt("prompt_node")});return ke(i,d=>!d||d.length===0?F(null):de(u=>{let c=!1,h=!1,l,p={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt};if(r?.abort){let b=sr(r.abort);p.signal=b.signal,l=b.dispose}let f;try{f=t.invoke(d,p)}catch(b){return c=!0,u.down([[V,b]]),()=>{l?.()}}let m=Fe(f).subscribe(b=>{if(!(h||c))for(let T of b){if(c)return;if(T[0]===I){let v=T[1];try{let x=Fr(v),E=s==="json"?JSON.parse(Vr(x)):x;u.emit(E)}catch(x){let E=Fr(v),_=new Error(`promptNode: failed to parse LLM response as JSON: ${x.message}
|
|
49
|
+
Raw content (first 200 chars): ${Hs(E)}`);c=!0,u.down([[V,_]]);return}}else if(T[0]===V){c=!0,u.down([[V,T[1]]]);return}else if(T[0]===B){c=!0,u.down([[B]]);return}else u.down([T])}});return()=>{h=!0,m(),l?.()}},{name:`${o}::call`,meta:vt("prompt_node::call")}),{name:`${o}::output`,meta:r?.meta?{...vt("prompt_node::output"),...r.meta}:vt("prompt_node::output")})}Ie();Ee();me();pt();Me();ue();Ie();Ee();Ze();me();ue();var Us=Yn((t,e)=>{t("observe"),t("signal"),e("write")});function Jt(t){let e=qt([],{name:t.name,maxSize:t.retainedLimit??1024,guard:t.guard??Us,...t.versioning!=null?{versioning:t.versioning}:{}});return e.withLatest(),t.graph&&t.graph.add(e.entries,{name:t.name}),e}function jr(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))jr(t[e]);return Object.freeze(t)}function Ws(t){let e=t.cache,r=(typeof e=="number"&&Number.isFinite(e)?e:0)+1;return t.down([[Z],[I,r]]),r}function $r(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 it(t,e){let n=e.freeze??!0;return function(...s){let o=n?s.map(jr):s,i=ye(),a,d,u=!1,c;try{re(()=>{e.seq&&(c=Ws(e.seq));try{a=t(...o),e.onSuccess&&$r(e.audit,e.onSuccess,o,a,{t_ns:i,seq:c},e.handlerVersion)}catch(h){throw d=h,u=!0,h}})}catch(h){if(u&&e.onFailure){let l=d instanceof Error?d.name:typeof d;$r(e.audit,e.onFailure,o,d,{t_ns:i,seq:c,errorType:l},e.handlerVersion)}throw u?d:h}return a}}function zr(t,e,n=0){let r=F(n,{name:e,describeKind:"state"});return t.add(r,{name:e}),r}function Tt(t,e){return je("orchestration",t,e)}var Yt=class extends ce{constructor(e,n){super(e,n)}task(e,n,r={}){let s=(r.deps??[]).map(i=>this._resolveStep(i)),o=P(s,n,{name:e,describeKind:"derived",meta:Tt("task",r.meta)});return this.add(o,{name:e}),o}classify(e,n,r,s={}){let o=this._resolveStep(n),i=P([o],([a])=>{try{return{tag:r(a),value:a}}catch(d){return{tag:"error",value:a,error:d}}},{name:e,describeKind:"derived",meta:Tt("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=P(o,a=>{let d={};for(let u=0;u<s.length;u++)d[s[u]]=a[u];return d},{name:e,describeKind:"derived",meta:Tt("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=F([],{name:"pending",equals:()=>!1}),u=F(o,{name:"isOpen"}),c=P([d],([j])=>j.length,{name:"count"}),h=F(0,{name:"droppedCount"}),l=Jt({name:"decisions",retainedLimit:1024,graph:a});a.add(d,{name:"pending"}),a.add(u,{name:"isOpen"}),a.add(c,{name:"count"}),a.add(h,{name:"droppedCount"}),this.mount(`${e}_state`,a);let p=[],f=!1,g=!1,m=o,b=u.subscribe(j=>{for(let z of j)z[0]===I&&(m=z[1])});this.addDisposer(b);function T(){d.emit([...p])}function v(j,z,$){l.append({action:j,t_ns:ye(),...z!==void 0?{items:z,count:z.length}:{},...$!==void 0?{unflushed:$}:{},...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}function x(j){if(p.push(j),p.length>s){let z=p.shift();h.emit(h.cache+1),v("drop",[z])}T()}function E(j){let z=p.splice(0,j);return T(),z}let _=oe([i],(j,z,$)=>{let ae=$.terminalDeps[0];if(ae!==void 0){f=!0;let le=p.length;p=[],T(),v("teardown",void 0,le),z.down(ae===!0?[[B]]:[[V,ae]]);return}let ne=j[0];if(ne==null||ne.length===0){z.down([[ee]]);return}for(let le of ne)m?z.emit(le):(x(le),z.down([[ee]]))},{name:e,describeKind:"derived",meta:Tt("gate",r.meta)});if(this.add(_,{name:e}),r.approver!=null){r.approver.cache&&(u.emit(!0),m=!0,r.onceOnly&&(g=!0));let z=r.approver.subscribe($=>{for(let ae of $){if(ae[0]!==I)continue;let ne=!!ae[1];if(ne&&!m){if(r.onceOnly){if(g)continue;g=!0}re(()=>{u.emit(!0);let le=E(p.length);v("open",le);for(let M of le){if(f)break;_.emit(M)}})}else if(!ne&&m){if(r.onceOnly&&g)continue;re(()=>{u.emit(!1),v("close")})}}});this.addDisposer(z)}let y=j=>{if(f)throw new Error(`gate: ${j}() called after gate was torn down`)},w=(j=1)=>{y("approve");let z=E(j);for(let $ of z){if(f)break;_.emit($)}},R=(j=1)=>{y("reject"),E(j)},A=(j,z=1)=>{y("modify");let $=[...p],ae=E(z);for(let ne=0;ne<ae.length&&!f;ne++)_.emit(j(ae[ne],ne,$))},O=()=>{y("open"),u.emit(!0);let j=E(p.length);for(let z of j){if(f)break;_.emit(z)}},D=()=>{y("close"),!(r.onceOnly&&g)&&u.emit(!1)},S=it(w,{audit:l,freeze:!1,onSuccess:(j,z,$)=>({action:"approve",count:j[0]??1,t_ns:$.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(j,z,$)=>({action:"drop",t_ns:$.t_ns,errorType:$.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),G=it(R,{audit:l,freeze:!1,onSuccess:(j,z,$)=>({action:"reject",count:j[0]??1,t_ns:$.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(j,z,$)=>({action:"drop",t_ns:$.t_ns,errorType:$.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),Q=it(A,{audit:l,freeze:!1,onSuccess:(j,z,$)=>({action:"modify",count:j[1]??1,t_ns:$.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(j,z,$)=>({action:"drop",t_ns:$.t_ns,errorType:$.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),J=it(O,{audit:l,freeze:!1,onSuccess:(j,z,$)=>({action:"open",t_ns:$.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(j,z,$)=>({action:"drop",t_ns:$.t_ns,errorType:$.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),ve=it(D,{audit:l,freeze:!1,onSuccess:(j,z,$)=>({action:"close",t_ns:$.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(j,z,$)=>({action:"drop",t_ns:$.t_ns,errorType:$.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})});return this.addDisposer(c.subscribe(()=>{})),{node:_,pending:d,count:c,isOpen:u,droppedCount:h,decisions:l,audit:l,approve:S,reject:G,modify:Q,open:J,close:ve}}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,c)=>{let h=c.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"?[[B]]:[[V,p.error]]);return}let l=d[0];if(l==null||l.length===0){u.down([[ee]]);return}for(let p of l)u.emit(p)},{name:e,describeKind:"derived",completeWhenDepsComplete:s.completeWhenDepsComplete??!(i==="complete"||i==="terminal"),errorWhenDepsError:!(i==="error"||i==="terminal"),meta:Tt("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 Dn(t,e){let n=new Yt(t,e),{factory:r,factoryArgs:s,...o}=e??{};return n.tagFactory("pipelineGraph",ft(o)),n}function Br(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)}Ee();Ie();me();ue();var In=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 qr(t,e={}){let{name:n,versioning:r,backend:s}=e,o=s??new In(t),i=F(o.toArray(),{name:n,describeKind:"state",equals:(u,c)=>u===c,...r!=null?{versioning:r}:{}});function a(){let u=o.toArray();re(()=>{i.down([[Z]]),i.down([[I,u]])})}function d(u){let c=o.version;try{return u()}finally{o.version!==c&&a()}}return{items:i,get size(){return o.size},at(u){return o.at(u)},append(u){d(()=>o.append(u))},appendMany(u){d(()=>o.appendMany(u))},insert(u,c){d(()=>o.insert(u,c))},insertMany(u,c){d(()=>o.insertMany(u,c))},pop(u=-1){return d(()=>o.pop(u))},clear(){d(()=>o.clear())},dispose(){}}}function Js(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Ys(t,e){return je("job_queue",t,e)}var Gn=class extends ce{_pending;_jobs;_seqCursor;pending;jobs;depth;events;audit;constructor(e,n={}){super(e,n.graph),this._pending=qr([],{name:"pending"}),this._jobs=Ut({name:"jobs"}),this.pending=this._pending.items,this.jobs=this._jobs.entries,this.add(this.pending,{name:"pending"}),this.add(this.jobs,{name:"jobs"}),this.depth=P([this.pending],([r])=>r.length,{name:"depth",describeKind:"derived",meta:Ys("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(be(this.depth)),this.events=Jt({name:"events",retainedLimit:1024,graph:this}),this.audit=this.events,this._seqCursor=zr(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:ye(),seq:r}),s}claim(e=1){let n=Js(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:ye(),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:ye(),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:ye(),seq:this._bumpSeq()}),!0):(this._jobs.delete(e),this.events.append({action:"nack",id:e,attempts:r.attempts,t_ns:ye(),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:ye(),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 Kr(t,e){return new Gn(t,e)}Ee();ue();function Ln(){let t=Ut({name:"strategy-entries"}),e=P([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[c,h]of d){let l=u.get(c);if(!l||h.attempts!==l.attempts||h.successes!==l.successes)return!1}return!0}});function n(i,a,d){let u=ot(i,a),c=t.get(u),h=(c?.attempts??0)+1,l=(c?.successes??0)+(d?1:0);t.set(u,{rootCause:i,intervention:a,attempts:h,successes:l,successRate:l/h})}function r(i,a){return t.get(ot(i,a))}let s=e.subscribe(()=>{});function o(){s()}return{node:e,record:n,lookup:r,dispose:o}}function Qs(t,e,n,r,s){let o={...nt,...s?.severityWeights},i=s?.decayRate??rt,a=s?.effectivenessThreshold??.7,d=s?.effectivenessBoost??15,u=[t,e,n];return r&&u.push(r),P(u,c=>{let h=c[0],l=c[1],p=c[2],f=r?c[3]:0,g=o[h.severity??"medium"],m=(U()-p)/1e9,b=Br(g,m,i,0),T=ot(h.rootCause,h.intervention),v=l.get(T);return v&&v.successRate>=a&&(b+=d),b+=f*20,b},{name:"priority-score"})}var Hr="intake",Xs="triage-output",Ur="retry",Wr="verify-results",Jr="__unrouted";function Yr(t,e){let n=mt(e,gn,(r,s)=>r.replace("{{item}}",JSON.stringify(s)));return r=>Wt(t,[r],n,{name:"execute",format:"json"})}function Qr(t,e){let n=mt(e,yn,(r,s)=>{let[o,i]=s;return r.replace("{{execution}}",JSON.stringify(o)).replace("{{item}}",JSON.stringify(i))});return r=>Wt(t,[r],s=>s==null?"":n(s),{name:"verify",format:"json"})}var Qt=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(Hr)}get verifyResults(){return this.queues.topic(Wr)}get retry(){return this.queues.topic(Ur)}get unrouted(){return this.queues.topic(Jr)}stageNodes(){let e=this.queues,n=i=>e.has(i)?`queues::${i}::latest`:null,r=i=>i==null?[]:[i],s=we.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 Zs(t,e){let n=e.adapter,r=e.maxRetries??2,s=e.retainedLimit??1e3,o=e.errorClassifier??Dt,i=new Map;for(let k of we)i.set(k,{...Ct[k],...e.queues?.[k]});let a=Ht(`${t}/queues`,{defaultTopicOptions:{retainedLimit:s}}),d=a.topic(Hr),u=a.topic(Xs),c=a.topic(Ur),h=a.topic(Wr),l=new Map;for(let k of we)l.set(k,a.topic(k));let p=a.topic(Jr),f=Ln(),g=ht(d.latest,f.node),m=mt(e.triagePrompt,mn,(k,C)=>{let[K,W]=C;return k.replace("{{strategy}}",JSON.stringify(Array.from(W.entries()))).replace("{{item}}",JSON.stringify(K))}),b=Wt(n,[g],k=>{let C=k;return!C||!C[0]?"":m(C)},{name:"triage",format:"json"}),T=ht(b,g),x=ge([T],([k])=>{if(k==null)return;let[C,K]=k;if(!C?.route)return;let W=K?.[0],De={...C,...W};u.publish(De)}).subscribe(()=>{}),E=new Set(we);for(let k of we)An(`bridge/${k}`,u,l.get(k),{map:C=>C.route===k?C:void 0});An("bridge/__unrouted",u,p,{map:k=>E.has(k.route)?void 0:k});let _=new Map,y=new Map;for(let k of we)_.set(k,Kr(`jobs/${k}`));let w=[];for(let k of we){let C=l.get(k),K=_.get(k),W=new WeakSet,De=ge([C.events],([at])=>{let Be=at??[];for(let X of Be){if(W.has(X))continue;W.add(X);let _e=K.enqueue(X);y.set(bt(X),{route:k,id:_e})}},{name:`jobs/${k}-mirror`});w.push(De.subscribe(()=>{}))}function R(k){let C=bt(k),K=y.get(C);K&&(_.get(K.route)?.removeById(K.id),y.delete(C))}let A=Dn("gates"),O=new Map;for(let k of we){let C=i.get(k);if(!C.gated)continue;let K=l.get(k),W=A.gate(`${k}/gate`,K.latest,{maxPending:C.maxPending,startOpen:C.startOpen});O.set(k,W)}let D=[];for(let k of we)i.get(k).gated&&O.has(k)?D.push(O.get(k).node):D.push(l.get(k).latest);D.push(c.latest);let S=ir(...D),Q=(e.executor??Yr(n,e.executePrompt))(S),J=ht(Q,S),Ce=(e.verifier??Qr(n,e.verifyPrompt))(J),j=ht(Ce,J),z=e.maxReingestions??1,$=Math.min(e.maxTotalRetries??r*10,100),ae=Math.min(e.maxTotalReingestions??z*10,100),ne=F(0),le=F(0);function M(k,C,K){let W={item:K,outcome:C?.outcome??"failure",detail:C?.detail??"unknown",artifact:C?.artifact};return{item:K,execution:W,verified:k.verified,findings:k.findings??[],errorClass:k.errorClass}}function H(k,C){f.record(C.rootCause,C.intervention,!0),h.publish(k),R(C)}function fe(k,C){let K=bt(C),W=C.$retries??0,De={...C,$retries:W+1,summary:`[RETRY ${W+1}/${r}] ${K} \u2014 Previous attempt failed: ${k.findings.join("; ")}`,relatedTo:[K]};c.publish(De)}function Se(k,C){f.record(C.rootCause,C.intervention,!1),h.publish(k),R(C);let K=bt(C),W=C.$reingestions??0;W<z&&En(le,ae)&&d.publish({source:C.source,summary:`Verification failed for: ${K}`,evidence:k.findings.join(`
|
|
50
|
+
`),affectsAreas:C.affectsAreas,affectsEvalTasks:C.affectsEvalTasks,severity:C.severity??"high",relatedTo:[K],$reingestions:W+1})}let pe=oe([j],(k,C)=>{let K=k[0];if(K==null||K.length===0)return;let W=K[K.length-1];if(W==null)return;let[De,at]=W,[Be,X]=at??[null,null];if(!De||!X)return;if(Be==null){Se({item:X,execution:{item:X,outcome:"failure",detail:"executor returned null"},verified:!1,findings:["executor returned null"],errorClass:"structural"},X);return}let _e=M(De,Be,X);if(_e.verified){H(_e,X);return}let Te=_e.errorClass??o({item:X,outcome:Be.outcome,detail:_e.findings.join("; ")}),Ge=X.$retries??0;Te==="self-correctable"&&Ge<r&&En(ne,$)?fe(_e,X):Se(_e,X)}),N=pe.subscribe(()=>{}),L=P([pe],()=>null,{name:"reflect",equals:()=>!1}),Y;e.priority&&(Y=ei(l,f,e));let q=new Qt(t,a,l,_,O,f,ne,le,Y);q.addDisposer(x),q.addDisposer(N),q.addDisposer(f.dispose);for(let k of w)q.addDisposer(k);if(q.add(b,{name:"triage"}),q.add(S,{name:"execute-input"}),q.add(Q,{name:"execute"}),q.add(J,{name:"execute-context"}),q.add(Ce,{name:"verify"}),q.add(j,{name:"verify-context"}),q.add(pe,{name:"verify-dispatch"}),q.add(L,{name:"reflect"}),q.add(f.node,{name:"strategy"}),q.addDisposer(L.subscribe(()=>{})),Y)for(let[k,C]of Y)q.add(C,{name:`priority/${k}`}),q.addDisposer(C.subscribe(()=>{}));q.mount("queues",a),q.mount("gates",A);for(let[k,C]of _)q.mount(`jobs/${k}`,C);return q.tagFactory("harnessLoop",ft(e)),q}function ei(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={...nt,...s.severityWeights},i=s.decayRate??rt,a=s.effectivenessThreshold??.7,d=s.effectivenessBoost??15,u=new Map;for(let[c,h]of t){let l=P([h.latest,e.node,r],p=>{let f=p[0];if(f==null)return 0;let g=o[f.severity??"medium"]??40,m=(U()-p[2])/1e9,b=g*Math.exp(-i*Math.max(0,m)),T=`${f.rootCause}\u2192${f.intervention}`,x=p[1]?.get(T);return x&&x.successRate>=a&&(b+=d),b},{name:`priority/${c}`});u.set(c,l)}return u}function ti(t,e){let n=jt(t,e),r={};for(let s of we){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}}Ee();function ni(t){let e={};for(let{label:n,paths:r}of t.stageNodes())for(let s of r)e[s]=n;return e}function ri(t,e){let n=e?.logger===null?null:e?.logger??console.log,r=e?.detail??"summary",s=U(),o=[],i=[],a=ni(t);function d(){return(U()-s)/1e9}function u(c,h,l){let p={elapsed:d(),stage:c,type:h};r!=="summary"&&(p.summary=oi(l)),r==="full"&&(p.data=l),i.push(p)}for(let[c,h]of Object.entries(a))try{let l=t.observe(c,{format:"stage-log",stageLabels:a,logger:n?p=>n(p):()=>{},includeTypes:["data","error","complete"]});l.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(l)}catch(l){let p=l instanceof Error?l.message:String(l);u(h,"error",`observe-unavailable: ${c} \u2014 ${p}`),n&&n(`[${d().toFixed(3)}s] ${h.padEnd(9)} \u2717 observe-unavailable: ${p}`)}return{get events(){return i},dispose(){for(let c of o)c.dispose();o.length=0}}}function oi(t){if(t==null)return"null";if(typeof t=="string")return Xr(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return Xr(e,120)}catch{return String(t)}}function Xr(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,dispatchActuator,evalIntakeBridge,evalSource,evalVerifier,harnessEvalPair,harnessLoop,harnessProfile,harnessTrace,notifyEffect,priorityScore,refineExecutor,resolvePromptFn,strategyKey,strategyModel});
|