@graphrefly/graphrefly 0.38.0 → 0.40.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/budget-gate-CmmVtasH.d.ts +115 -0
- package/dist/budget-gate-DiP_nK0n.d.cts +115 -0
- package/dist/{cascading-BsJ4GbnS.d.ts → cascading-BNfxffgc.d.ts} +2 -2
- package/dist/{cascading-B25wxpRa.d.cts → cascading-Cxs1eztH.d.cts} +2 -2
- package/dist/chunk-2BX4NB34.js +3 -0
- package/dist/{chunk-6VFC334U.js → chunk-2DMKW2AD.js} +1 -1
- package/dist/{chunk-4BDQXBXE.js → chunk-2QXRYP7Q.js} +1 -1
- package/dist/chunk-32N3JALT.js +1 -0
- package/dist/chunk-35JTVPOX.js +1 -0
- package/dist/chunk-3G5U5QNE.js +5 -0
- package/dist/{chunk-PHXZRR6C.js → chunk-4I45FVQS.js} +1 -1
- package/dist/{chunk-B5S7KTGP.js → chunk-6I726LZU.js} +1 -1
- package/dist/{chunk-NV63VQHI.js → chunk-6VWBPSSY.js} +1 -1
- package/dist/chunk-6XVD5TZV.js +1 -0
- package/dist/chunk-756D5TFD.js +1 -0
- package/dist/{chunk-DSOVKKTI.js → chunk-7Q4ZD3YW.js} +1 -1
- package/dist/{chunk-TMVY7OWG.js → chunk-B7LCDQEV.js} +1 -1
- package/dist/chunk-C72GO4IZ.js +1 -0
- package/dist/{chunk-RZ5HKPGI.js → chunk-CKFQS2CJ.js} +1 -1
- package/dist/chunk-D27JNOLZ.js +1 -0
- package/dist/chunk-ECQRP2UT.js +1 -0
- package/dist/{chunk-6773HURD.js → chunk-FHRBBHJN.js} +1 -1
- package/dist/{chunk-UVLZX2OU.js → chunk-I2DEVPMU.js} +1 -1
- package/dist/chunk-INQFTVZA.js +61 -0
- package/dist/{chunk-6KZZ6XQE.js → chunk-J63M5U46.js} +1 -1
- package/dist/{chunk-POCWFIJ7.js → chunk-JKBOIJ22.js} +1 -1
- package/dist/chunk-K2Z7UENB.js +1 -0
- package/dist/chunk-L6NSJVJZ.js +1 -0
- package/dist/{chunk-K5C67OGE.js → chunk-LCGAVGGV.js} +2 -2
- package/dist/chunk-LYM4PBMV.js +1 -0
- package/dist/{chunk-O2BLVQU4.js → chunk-MNZIKXK4.js} +1 -1
- package/dist/chunk-N43XM7BM.js +1 -0
- package/dist/{chunk-FWGIZP3W.js → chunk-OSZ22J7O.js} +1 -1
- package/dist/{chunk-FAYEMS5M.js → chunk-PPUYQ66A.js} +1 -1
- package/dist/{chunk-SP5O2MIX.js → chunk-QSK3RRII.js} +1 -1
- package/dist/chunk-RZJDIV2G.js +1 -0
- package/dist/chunk-SSCGRYJ2.js +1 -0
- package/dist/chunk-SVFKHUCW.js +1 -0
- package/dist/chunk-TSOYJ743.js +1 -0
- package/dist/{chunk-O245YLM5.js → chunk-UWA6D7UF.js} +1 -1
- package/dist/chunk-VMF23LGB.js +1 -0
- package/dist/chunk-WL6LFPJB.js +1 -0
- package/dist/chunk-WUT362QV.js +1 -0
- package/dist/chunk-XJLYLLIJ.js +1 -0
- package/dist/{chunk-IBGE62GZ.js → chunk-XW4YDF6G.js} +1 -1
- package/dist/chunk-YKD7WUYJ.js +43 -0
- package/dist/{chunk-7KZZLWZ6.js → chunk-YXDRGKXP.js} +1 -1
- package/dist/chunk-Z4F3DOWS.js +84 -0
- package/dist/compat/index.cjs +9 -13
- package/dist/compat/index.d.cts +16 -16
- package/dist/compat/index.d.ts +16 -16
- package/dist/compat/index.js +1 -1
- package/dist/compat/jotai/index.d.cts +2 -2
- package/dist/compat/jotai/index.d.ts +2 -2
- package/dist/compat/nanostores/index.d.cts +2 -2
- package/dist/compat/nanostores/index.d.ts +2 -2
- package/dist/compat/nestjs/index.cjs +7 -11
- package/dist/compat/nestjs/index.d.cts +8 -8
- package/dist/compat/nestjs/index.d.ts +8 -8
- package/dist/compat/nestjs/index.js +1 -1
- package/dist/compat/react/index.d.cts +2 -2
- package/dist/compat/react/index.d.ts +2 -2
- package/dist/compat/solid/index.d.cts +2 -2
- package/dist/compat/solid/index.d.ts +2 -2
- package/dist/compat/svelte/index.d.cts +2 -2
- package/dist/compat/svelte/index.d.ts +2 -2
- package/dist/compat/vue/index.d.cts +2 -2
- package/dist/compat/vue/index.d.ts +2 -2
- package/dist/compat/zustand/index.cjs +3 -7
- package/dist/compat/zustand/index.d.cts +4 -4
- package/dist/compat/zustand/index.d.ts +4 -4
- package/dist/compat/zustand/index.js +1 -1
- package/dist/core/index.cjs +1 -1
- package/dist/core/index.d.cts +4 -4
- package/dist/core/index.d.ts +4 -4
- package/dist/core/index.js +1 -1
- package/dist/{composite-DTOlDuch.d.ts → decay-BnrlbxSv.d.ts} +39 -3
- package/dist/{composite-CgG0MqHm.d.cts → decay-C25AyNAj.d.cts} +39 -3
- package/dist/extra/browser.d.cts +1 -1
- package/dist/extra/browser.d.ts +1 -1
- package/dist/extra/index.cjs +16 -20
- package/dist/extra/index.d.cts +11 -9
- package/dist/extra/index.d.ts +11 -9
- package/dist/extra/index.js +1 -1
- package/dist/extra/node.cjs +2 -2
- package/dist/extra/node.d.cts +1 -1
- package/dist/extra/node.d.ts +1 -1
- package/dist/extra/node.js +1 -1
- package/dist/extra/operators.cjs +1 -1
- package/dist/extra/operators.d.cts +1 -1
- package/dist/extra/operators.d.ts +1 -1
- package/dist/extra/operators.js +1 -1
- package/dist/extra/reactive.cjs +1 -1
- package/dist/extra/reactive.d.cts +3 -3
- package/dist/extra/reactive.d.ts +3 -3
- package/dist/extra/reactive.js +1 -1
- package/dist/extra/render/index.cjs +5 -0
- package/dist/extra/render/index.d.cts +183 -0
- package/dist/extra/render/index.d.ts +183 -0
- package/dist/extra/render/index.js +1 -0
- package/dist/extra/sources.cjs +1 -1
- package/dist/extra/sources.d.cts +1 -1
- package/dist/extra/sources.d.ts +1 -1
- package/dist/extra/sources.js +1 -1
- package/dist/extra/storage-browser.d.cts +1 -1
- package/dist/extra/storage-browser.d.ts +1 -1
- package/dist/{fallback-axI2cXwt.d.cts → fallback-8JYU8tlT.d.cts} +1 -1
- package/dist/{fallback-DuEXfA4F.d.ts → fallback-CMZl39L5.d.ts} +1 -1
- package/dist/graph/index.cjs +7 -7
- package/dist/graph/index.d.cts +5 -5
- package/dist/graph/index.d.ts +5 -5
- package/dist/graph/index.js +1 -1
- package/dist/{graph-BjW1taJl.d.ts → graph-BkIkog4h.d.ts} +76 -100
- package/dist/{graph-CHsVwf9S.d.cts → graph-E6likq7w.d.cts} +76 -100
- package/dist/{index-CIcu6fIR.d.ts → index-2n8Eai6M.d.ts} +1 -1
- package/dist/{index-BwOsJfLJ.d.ts → index-3k4Gg6-n.d.ts} +3 -3
- package/dist/{index-BUFCHvOR.d.ts → index-40ZT4MHj.d.ts} +3 -3
- package/dist/index-8s-Qm-gz.d.ts +218 -0
- package/dist/index-A3U3CSve.d.cts +113 -0
- package/dist/{index-CDvC1m5p.d.ts → index-B2RUoIUz.d.ts} +1 -1
- package/dist/{index-Byp771zP.d.ts → index-B6iTqKtJ.d.ts} +2 -2
- package/dist/{index-D-B7U42V.d.cts → index-B72TQQHd.d.cts} +2 -2
- package/dist/{resilience-Bys63Cpd.d.ts → index-BAQrjuZF.d.ts} +202 -26
- package/dist/{index-BiomL7AW.d.ts → index-BJSZxSFX.d.ts} +1 -1
- package/dist/index-BQ1fR4li.d.ts +210 -0
- package/dist/{index-D7-RSD93.d.cts → index-BTHOTC0Q.d.cts} +4 -4
- package/dist/{index-CEVzBWeB.d.ts → index-BaA-xpSw.d.ts} +26 -19
- package/dist/{index-CAV-3RpJ.d.cts → index-Bd91Nmf4.d.cts} +4 -4
- package/dist/{index-BI1wMfyc.d.ts → index-BgjS2b8N.d.ts} +3 -3
- package/dist/{index-Bpr0Pwgl.d.cts → index-BiHUBEKq.d.cts} +3 -3
- package/dist/{index-UsU9ptzs.d.cts → index-BilOa6AE.d.cts} +55 -9
- package/dist/{index-DJVQ-t07.d.ts → index-BmSQLAZo.d.cts} +41 -48
- package/dist/{index-DTDVDzhA.d.ts → index-C-dkXOpB.d.cts} +56 -54
- package/dist/{index-B-ORMr3k.d.ts → index-C5cQ7Gfx.d.ts} +4 -4
- package/dist/{index-ML6vHKXK.d.ts → index-C6ZUaos7.d.ts} +1 -1
- package/dist/{index-Vz7KPfgz.d.ts → index-CAP3UGsq.d.ts} +1 -1
- package/dist/{index-BFaALJxR.d.ts → index-CD2dBMet.d.ts} +10 -8
- package/dist/index-CGhMJNHb.d.cts +128 -0
- package/dist/{index-B3D_z0Z6.d.cts → index-CL7oilfm.d.cts} +1 -1
- package/dist/{index-Bn0uZEL4.d.ts → index-CQtWm7jS.d.ts} +9 -9
- package/dist/{index-CM-i58FY.d.cts → index-CRm0YIzC.d.cts} +9 -9
- package/dist/index-CUIkE1l9.d.cts +230 -0
- package/dist/{index-CijfwEWx.d.ts → index-Cczxgd2D.d.ts} +2 -2
- package/dist/{index-CAbHN_rP.d.cts → index-CgnCFhr2.d.cts} +1 -1
- package/dist/{index-B2IUcH13.d.cts → index-Ck35nA-T.d.ts} +41 -48
- package/dist/{index-BpMZzX9P.d.cts → index-Cnr1WrlX.d.cts} +3 -3
- package/dist/{index-JYtN9uqM.d.ts → index-CoM4rzyB.d.ts} +1 -1
- package/dist/{index-Ckil6miL.d.cts → index-CtFNGe-m.d.cts} +2 -2
- package/dist/{index-BjWZARLy.d.ts → index-Ctb7_2sG.d.ts} +1 -1
- package/dist/index-CuPUehFa.d.cts +218 -0
- package/dist/index-D1Gc7wV5.d.ts +230 -0
- package/dist/{index-DqICM_I7.d.ts → index-D1IEZUsj.d.ts} +67 -9
- package/dist/{index-BFuVcqL8.d.cts → index-D3ayz3hy.d.cts} +1 -1
- package/dist/{index-CQsqqEVz.d.cts → index-D4uimgee.d.cts} +1 -1
- package/dist/{resilience-BWP2c7Af.d.cts → index-DGTo1yka.d.cts} +202 -26
- package/dist/{index-BmWuVdER.d.ts → index-DH4fm2Ck.d.ts} +2 -2
- package/dist/{index-BkQqf1EF.d.cts → index-DJ_MPOJ5.d.cts} +67 -9
- package/dist/{index-9xhIaM-w.d.cts → index-DOBLxOti.d.cts} +1 -1
- package/dist/{index-BqcgiSQg.d.cts → index-DQQCOIt8.d.cts} +10 -8
- package/dist/{index-DJNAWzcH.d.cts → index-DVAlsmEU.d.cts} +26 -19
- package/dist/index-DVDapw2k.d.cts +210 -0
- package/dist/{index-D_QQ_dTD.d.cts → index-DYTBbF8T.d.cts} +1 -1
- package/dist/{index-BgzPO43H.d.cts → index-DgJc8Zgc.d.cts} +6 -6
- package/dist/{index-Czk3r0yA.d.cts → index-DhLyOHYZ.d.ts} +56 -54
- package/dist/{index-CrlHFsiT.d.ts → index-DhnsQfa3.d.ts} +100 -118
- package/dist/{index-Bub6x_D4.d.cts → index-DktLSZOc.d.cts} +37 -90
- package/dist/{index-BaSy4L6w.d.cts → index-DpiGqtrs.d.cts} +100 -118
- package/dist/{index-D-HZ7sP4.d.ts → index-I1cCY3ZI.d.ts} +6 -6
- package/dist/{index-D9vBTuzo.d.ts → index-IUCY0OFN.d.ts} +4 -4
- package/dist/{index-DeSsvHDD.d.cts → index-MxYuWOrf.d.cts} +3 -3
- package/dist/index-N2MAxt7_.d.ts +128 -0
- package/dist/{index-CpZKtdMw.d.cts → index-PgwvGWa1.d.cts} +1 -1
- package/dist/{index-AUqWe_fX.d.ts → index-WSlcjhQF.d.ts} +55 -9
- package/dist/{index-Di7OdwlO.d.ts → index-bXXLSvor.d.ts} +37 -90
- package/dist/index-da2V5vPy.d.ts +113 -0
- package/dist/{index-DY2f2b9z.d.ts → index-eaQuGJnv.d.ts} +3 -3
- package/dist/{index-BsgxnHN8.d.cts → index-t6L2qpHh.d.cts} +3 -3
- package/dist/{index-C-3UXnHT.d.cts → index-tV3AA9hI.d.cts} +2 -2
- package/dist/{index-8OxXae3g.d.ts → index-yLt-aPMp.d.ts} +1 -1
- package/dist/{index-CqSJ25A9.d.cts → index-z8WFPVI8.d.cts} +1 -1
- package/dist/index.cjs +63 -59
- package/dist/index.d.cts +48 -47
- package/dist/index.d.ts +48 -47
- package/dist/index.js +1 -1
- package/dist/{meta-DreaEM_a.d.cts → meta-Ct9nqQS5.d.cts} +11 -7
- package/dist/{meta-BYqlATmg.d.ts → meta-D8OyedKp.d.ts} +11 -7
- package/dist/{node-fSc-hCv8.d.cts → node-BYInONRr.d.cts} +3 -3
- package/dist/{node-fSc-hCv8.d.ts → node-BYInONRr.d.ts} +3 -3
- package/dist/{observable-Cqty11jG.d.cts → observable-DMIlYJV1.d.cts} +1 -1
- package/dist/{observable-EAV_rNfM.d.ts → observable-DO8DDEzv.d.ts} +1 -1
- package/dist/patterns/ai/browser.cjs +5 -5
- package/dist/patterns/ai/browser.d.cts +4 -4
- package/dist/patterns/ai/browser.d.ts +4 -4
- package/dist/patterns/ai/browser.js +1 -1
- package/dist/patterns/ai/index.cjs +16 -20
- package/dist/patterns/ai/index.d.cts +17 -17
- package/dist/patterns/ai/index.d.ts +17 -17
- package/dist/patterns/ai/index.js +1 -1
- package/dist/patterns/ai/node.cjs +1 -1
- package/dist/patterns/ai/node.d.cts +4 -4
- package/dist/patterns/ai/node.d.ts +4 -4
- package/dist/patterns/ai/node.js +1 -1
- package/dist/patterns/audit/index.cjs +3 -7
- package/dist/patterns/audit/index.d.cts +6 -6
- package/dist/patterns/audit/index.d.ts +6 -6
- package/dist/patterns/audit/index.js +1 -1
- package/dist/patterns/cqrs/index.cjs +3 -7
- package/dist/patterns/cqrs/index.d.cts +6 -6
- package/dist/patterns/cqrs/index.d.ts +6 -6
- package/dist/patterns/cqrs/index.js +1 -1
- package/dist/patterns/demo-shell/index.cjs +5 -8
- package/dist/patterns/demo-shell/index.d.cts +5 -5
- package/dist/patterns/demo-shell/index.d.ts +5 -5
- package/dist/patterns/demo-shell/index.js +1 -1
- package/dist/patterns/domain-templates/index.cjs +3 -7
- package/dist/patterns/domain-templates/index.d.cts +4 -4
- package/dist/patterns/domain-templates/index.d.ts +4 -4
- package/dist/patterns/domain-templates/index.js +1 -1
- package/dist/patterns/graphspec/index.cjs +37 -37
- package/dist/patterns/graphspec/index.d.cts +5 -5
- package/dist/patterns/graphspec/index.d.ts +5 -5
- package/dist/patterns/graphspec/index.js +1 -1
- package/dist/patterns/guarded-execution/index.cjs +3 -7
- package/dist/patterns/guarded-execution/index.d.cts +7 -7
- package/dist/patterns/guarded-execution/index.d.ts +7 -7
- package/dist/patterns/guarded-execution/index.js +1 -1
- package/dist/patterns/harness/index.cjs +8 -12
- package/dist/patterns/harness/index.d.cts +12 -12
- package/dist/patterns/harness/index.d.ts +12 -12
- package/dist/patterns/harness/index.js +1 -1
- package/dist/patterns/job-queue/index.cjs +3 -7
- package/dist/patterns/job-queue/index.d.cts +6 -6
- package/dist/patterns/job-queue/index.d.ts +6 -6
- package/dist/patterns/job-queue/index.js +1 -1
- package/dist/patterns/lens/index.cjs +3 -7
- package/dist/patterns/lens/index.d.cts +5 -6
- package/dist/patterns/lens/index.d.ts +5 -6
- package/dist/patterns/lens/index.js +1 -1
- package/dist/patterns/memory/index.cjs +3 -7
- package/dist/patterns/memory/index.d.cts +6 -6
- package/dist/patterns/memory/index.d.ts +6 -6
- package/dist/patterns/memory/index.js +1 -1
- package/dist/patterns/messaging/index.cjs +3 -7
- package/dist/patterns/messaging/index.d.cts +5 -5
- package/dist/patterns/messaging/index.d.ts +5 -5
- package/dist/patterns/messaging/index.js +1 -1
- package/dist/patterns/orchestration/index.cjs +3 -7
- package/dist/patterns/orchestration/index.d.cts +8 -8
- package/dist/patterns/orchestration/index.d.ts +8 -8
- package/dist/patterns/orchestration/index.js +1 -1
- package/dist/patterns/process/index.cjs +1 -1
- package/dist/patterns/process/index.d.cts +7 -7
- package/dist/patterns/process/index.d.ts +7 -7
- package/dist/patterns/process/index.js +1 -1
- package/dist/patterns/reactive-layout/index.cjs +4 -8
- package/dist/patterns/reactive-layout/index.d.cts +5 -5
- package/dist/patterns/reactive-layout/index.d.ts +5 -5
- package/dist/patterns/reactive-layout/index.js +1 -1
- package/dist/patterns/reduction/index.cjs +3 -7
- package/dist/patterns/reduction/index.d.cts +4 -4
- package/dist/patterns/reduction/index.d.ts +4 -4
- package/dist/patterns/reduction/index.js +1 -1
- package/dist/patterns/refine-loop/index.cjs +5 -9
- package/dist/patterns/refine-loop/index.d.cts +6 -6
- package/dist/patterns/refine-loop/index.d.ts +6 -6
- package/dist/patterns/refine-loop/index.js +1 -1
- package/dist/patterns/resilient-pipeline/index.cjs +3 -1
- package/dist/patterns/resilient-pipeline/index.d.cts +6 -6
- package/dist/patterns/resilient-pipeline/index.d.ts +6 -6
- package/dist/patterns/resilient-pipeline/index.js +1 -1
- package/dist/patterns/surface/index.cjs +12 -16
- package/dist/patterns/surface/index.d.cts +6 -6
- package/dist/patterns/surface/index.d.ts +6 -6
- package/dist/patterns/surface/index.js +1 -1
- package/dist/{pipeline-graph-9JBbmRxA.d.ts → pipeline-graph-CB4La-UW.d.ts} +34 -17
- package/dist/{pipeline-graph-DuHpXSOn.d.cts → pipeline-graph-MWrQZXCq.d.cts} +34 -17
- package/dist/{reactive-layout-BMLDB4Vd.d.cts → reactive-layout-BtZfUKuL.d.cts} +2 -2
- package/dist/{reactive-layout-D-tRiNhg.d.ts → reactive-layout-KJj4E2dT.d.ts} +2 -2
- package/dist/{reactive-log-BgWSA1fg.d.ts → reactive-log-BlAsPLl2.d.ts} +2 -2
- package/dist/{reactive-log-C3IMAGpT.d.cts → reactive-log-_zeEnB9H.d.cts} +2 -2
- package/dist/{reactive-map-DmgeADH8.d.cts → reactive-map-6P_k3AQM.d.cts} +2 -2
- package/dist/{reactive-map-CHyeCf4D.d.ts → reactive-map-CjXByDV-.d.ts} +2 -2
- package/dist/resilience-S33JV6XC.js +1 -0
- package/dist/{sugar-D13E2M_z.d.ts → sugar-BhfjgetH.d.ts} +1 -1
- package/dist/{sugar-DgaGJcI6.d.cts → sugar-DzePN5-g.d.cts} +1 -1
- package/dist/{topology-tree-jrZue3ao.d.cts → topology-tree-3LBKFsUo.d.cts} +1 -1
- package/dist/{topology-tree-D47-nI6Z.d.ts → topology-tree-mF7Emqzm.d.ts} +1 -1
- package/dist/{types-BMSGPlpO.d.cts → types-1Dhoi7HM.d.cts} +1 -1
- package/dist/{types-CidcBDuk.d.ts → types-39jk0kaV.d.ts} +1 -1
- package/package.json +11 -1
- package/dist/chunk-2YFDSYEF.js +0 -1
- package/dist/chunk-5BGFS2XH.js +0 -1
- package/dist/chunk-CMTN3KPT.js +0 -80
- package/dist/chunk-DQJLC6YY.js +0 -1
- package/dist/chunk-G7JN6LCB.js +0 -1
- package/dist/chunk-KJEAIIIY.js +0 -43
- package/dist/chunk-LV3ACS5J.js +0 -1
- package/dist/chunk-NBGPXQSP.js +0 -1
- package/dist/chunk-NN3QPJ6U.js +0 -1
- package/dist/chunk-NSAZ6PR6.js +0 -1
- package/dist/chunk-O32GJOUJ.js +0 -1
- package/dist/chunk-QEVSIVSF.js +0 -1
- package/dist/chunk-QMC2PLNM.js +0 -7
- package/dist/chunk-QOJFR6GS.js +0 -1
- package/dist/chunk-SFK7MN7S.js +0 -1
- package/dist/chunk-TB7JKSVS.js +0 -61
- package/dist/chunk-UAXFKMAG.js +0 -1
- package/dist/chunk-XIMFHEKV.js +0 -1
- package/dist/chunk-XLMYQB6F.js +0 -1
- package/dist/chunk-XLYF4LBH.js +0 -1
- package/dist/imperative-audit-ahAE65a9.d.cts +0 -28
- package/dist/imperative-audit-ahAE65a9.d.ts +0 -28
- package/dist/index-5dNRlW7J.d.ts +0 -135
- package/dist/index-BWUMIt7J.d.cts +0 -135
- package/dist/index-BhzwpIJc.d.cts +0 -105
- package/dist/index-BsZk9T8y.d.ts +0 -105
- package/dist/index-C56XZiDe.d.cts +0 -163
- package/dist/index-CpdnP-0y.d.cts +0 -186
- package/dist/index-DKrIuF-r.d.ts +0 -163
- package/dist/index-DOU1Ee_k.d.ts +0 -186
- package/dist/resilience-LGBK236C.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
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.
|
|
1
|
+
"use strict";var Yt=Object.defineProperty;var Vr=Object.getOwnPropertyDescriptor;var jr=Object.getOwnPropertyNames;var zr=Object.prototype.hasOwnProperty;var me=(r,e)=>()=>(r&&(e=r(r=0)),e);var Br=(r,e)=>{for(var t in e)Yt(r,t,{get:e[t],enumerable:!0})},qr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of jr(e))!zr.call(r,s)&&s!==t&&Yt(r,s,{get:()=>e[s],enumerable:!(n=Vr(e,s))||n.enumerable});return r};var Hr=r=>qr(Yt({},"__esModule",{value:!0}),r);var Pe,C,ee,Q,xe,Ae,Le,ue,j,G,He,Et,Pn,kt,Ln,Fn,Rt,Qt,Xt,Zt,Ot,ge=me(()=>{"use strict";Pe=Symbol.for("graphrefly/START"),C=Symbol.for("graphrefly/DATA"),ee=Symbol.for("graphrefly/DIRTY"),Q=Symbol.for("graphrefly/RESOLVED"),xe=Symbol.for("graphrefly/INVALIDATE"),Ae=Symbol.for("graphrefly/PAUSE"),Le=Symbol.for("graphrefly/RESUME"),ue=Symbol.for("graphrefly/TEARDOWN"),j=Symbol.for("graphrefly/COMPLETE"),G=Symbol.for("graphrefly/ERROR"),He=Object.freeze([ee]),Et=Object.freeze([Q]),Pn=Object.freeze([xe]),kt=Object.freeze([Pe]),Ln=Object.freeze([j]),Fn=Object.freeze([ue]),Rt=Object.freeze([He]),Qt=Object.freeze([Et]),Xt=Object.freeze([Pn]),Zt=Object.freeze([Ln]),Ot=Object.freeze([Fn])});function Vn(r,e){let t=new TextEncoder().encode(r.name);if(t.length===0||t.length>255)throw new Error(`encodeEnvelope: codec name "${r.name}" encodes to ${t.length} bytes (must be 1\u2013255)`);let n=r.version;if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`encodeEnvelope: codec.version ${n} out of u16 range (expected integer 0\u201365535)`);let s=2+t.length+2+e.length;if(s>4294967295)throw new Error(`encodeEnvelope: total envelope size ${s} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let o=new Uint8Array(s),i=0;return o[i++]=en,o[i++]=t.length,o.set(t,i),i+=t.length,o[i++]=n>>>8&255,o[i++]=n&255,o.set(e,i),o}function jn(r,e){if(r.length<$n)throw new Error(`decodeEnvelope: bytes too short (${r.length} < ${$n})`);let t=0,n=r[t++];if(n!==en)throw new Error(`decodeEnvelope: unsupported envelope version ${n} (expected ${en})`);let s=r[t++];if(s===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(t+s+2>r.length)throw new Error(`decodeEnvelope: envelope truncated (need ${t+s+2} bytes, have ${r.length})`);let o=new TextDecoder().decode(r.subarray(t,t+s));t+=s;let i=(r[t]<<8|r[t+1])>>>0;t+=2;let a=r.subarray(t),u=e.lookupCodec(o);if(u==null)throw new Error(`decodeEnvelope: codec "${o}" not registered (envelope codec_v=${i})`);return{codec:u,codecVersion:i,payload:a}}function zn(r){r.registerCodec(Ur)}var Ur,en,$n,tn=me(()=>{"use strict";Ur={name:"json",version:1,contentType:"application/json",encode(r){let e=JSON.stringify(r);return new TextEncoder().encode(e)},decode(r,e){let t=new TextDecoder().decode(r);return JSON.parse(t)}},en=1,$n=4});function St(r){if(r==null)return Ye;let{type:e,id:t,...n}=r;return{type:e??"system",id:t??"",...n}}var Ye,At=me(()=>{"use strict";Ye={type:"system",id:""}});function ft(){return Qe>0||ct}function Bn(){return Qe>0}function Ze(r){Qe>0?lt.push(r):r()}function te(r){Qe+=1;let e=!1;try{r()}catch(t){throw e=!0,t}finally{if(Qe-=1,Qe===0)if(e){if(!ct){let t=lt.splice(0);for(let n of t)try{n()}catch{}Ue.length=0,Ke.length=0,Xe.length=0}}else Kr()}}function Kr(){let r=!ct;r&&(ct=!0);let e=[],t=0;try{for(;Ue.length>0||Ke.length>0||Xe.length>0||r&<.length>0;){if(r&<.length>0){let o=lt.splice(0);for(let i of o)try{i()}catch(a){e.push(a)}continue}if(t+=1,t>1e3)throw Ue.length=0,Ke.length=0,Xe.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let s=(Ue.length>0?Ue:Ke.length>0?Ke:Xe).splice(0);for(let o of s)try{o()}catch(i){e.push(i)}}}finally{r&&(ct=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function pt(r,e,t){if(e.length===0)return;if(e.length===1){let d=t(e[0][0]);if(d<3||!ft()){r(e);return}(d>=5?Xe:d===4?Ke:Ue).push(()=>r(e));return}let n=e.length,s=n,o=n,i=n,a=0;for(;a<n&&t(e[a][0])<3;)a++;for(s=a;a<n&&t(e[a][0])===3;)a++;for(o=a;a<n&&t(e[a][0])===4;)a++;i=a;let u=ft();if(s>0){let d=e.slice(0,s);r(d)}if(o>s){let d=e.slice(s,o);u?Ue.push(()=>r(d)):r(d)}if(i>o){let d=e.slice(o,i);u?Ke.push(()=>r(d)):r(d)}if(n>i){let d=e.slice(i,n);u?Xe.push(()=>r(d)):r(d)}}var Qe,ct,Ue,Ke,Xe,lt,Ie=me(()=>{"use strict";Qe=0,ct=!1,Ue=[],Ke=[],Xe=[],lt=[]});function K(){return Math.trunc(performance.now()*1e6)}function ve(){return Date.now()*1e6}var Ne=me(()=>{"use strict"});function qn(r){r.registerMessageType(Pe,{tier:0,wireCrossing:!1}),r.registerMessageType(ee,{tier:1,wireCrossing:!1}),r.registerMessageType(xe,{tier:1,wireCrossing:!1,metaPassthrough:!1}),r.registerMessageType(Ae,{tier:2,wireCrossing:!1}),r.registerMessageType(Le,{tier:2,wireCrossing:!1}),r.registerMessageType(C,{tier:3,wireCrossing:!0}),r.registerMessageType(Q,{tier:3,wireCrossing:!0}),r.registerMessageType(j,{tier:4,wireCrossing:!0,metaPassthrough:!1}),r.registerMessageType(G,{tier:4,wireCrossing:!0,metaPassthrough:!1}),r.registerMessageType(ue,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var Dt,Hn=me(()=>{"use strict";ge();Dt=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_rigorRecorder;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=t=>{let n=this._messageTypes.get(t);return n!=null?n.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}get rigorRecorder(){return this._rigorRecorder}set rigorRecorder(e){this._rigorRecorder=e}registerMessageType(e,t){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:t.tier,wireCrossing:t.wireCrossing??t.tier>=3,metaPassthrough:t.metaPassthrough??!0}),this}messageTier(e){let t=this._messageTypes.get(e);return t!=null?t.tier:1}isWireCrossing(e){let t=this._messageTypes.get(e);return t!=null?t.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let t=this._messageTypes.get(e);return t!=null?t.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function Un(r){return Array.isArray(r)?[...r]:[r]}function Wr(r,e){return r.has(e)||r.has("*")}function Kn(r){let e=[];return r((s,o)=>{e.push({kind:"allow",actions:new Set(Un(s)),where:o?.where??(()=>!0)})},(s,o)=>{e.push({kind:"deny",actions:new Set(Un(s)),where:o?.where??(()=>!0)})}),(s,o)=>{let i=!1,a=!1;for(let u of e)Wr(u.actions,o)&&u.where(s)&&(u.kind==="deny"?i=!0:a=!0);return i?!1:a}}function nn(r){let e=Jr.filter(t=>r({type:t,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(t=>t==="human"||t==="llm"||t==="system")?"both":e.length===1?e[0]:e.join("+")}var Ee,Jr,et=me(()=>{"use strict";Ee=class extends Error{actor;action;nodeName;constructor(e,t){super(t??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}};Jr=["human","llm","wallet","system"]});function rn(r){if(r===void 0)return null;if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError(`Cannot hash non-finite number: ${r}`);if(Number.isInteger(r)&&!Number.isSafeInteger(r))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${r}. Cross-language cid parity is not guaranteed for unsafe integers.`);return r}if(typeof r=="string"||typeof r=="boolean"||r===null)return r;if(Array.isArray(r))return r.map(rn);if(typeof r=="object"&&r!==null){let e={};for(let t of Object.keys(r).sort())e[t]=rn(r[t]);return e}return null}function Xr(r){let e=Qr.encode(r),t=e.length,n=t*8,s=t+9+63&-64,o=new Uint8Array(s);o.set(e),o[t]=128;let i=new DataView(o.buffer);i.setUint32(s-4,n>>>0,!1),i.setUint32(s-8,Math.floor(n/4294967296)>>>0,!1);let a=1779033703,u=3144134277,d=1013904242,c=2773480762,p=1359893119,l=2600822924,h=528734635,f=1541459225,g=new Uint32Array(64),m=(y,v)=>y>>>v|y<<32-v;for(let y=0;y<s;y+=64){for(let N=0;N<16;N++)g[N]=i.getUint32(y+N*4,!1);for(let N=16;N<64;N++){let P=g[N-15],B=g[N-2],z=m(P,7)^m(P,18)^P>>>3,le=m(B,17)^m(B,19)^B>>>10;g[N]=g[N-16]+z+g[N-7]+le>>>0}let v=a,_=u,w=d,R=c,b=p,x=l,O=h,S=f;for(let N=0;N<64;N++){let P=m(b,6)^m(b,11)^m(b,25),B=b&x^~b&O,z=S+P+B+Yr[N]+g[N]>>>0,le=m(v,2)^m(v,13)^m(v,22),ae=v&_^v&w^_&w,Oe=le+ae>>>0;S=O,O=x,x=b,b=R+z>>>0,R=w,w=_,_=v,v=z+Oe>>>0}a=a+v>>>0,u=u+_>>>0,d=d+w>>>0,c=c+R>>>0,p=p+b>>>0,l=l+x>>>0,h=h+O>>>0,f=f+S>>>0}let T=y=>y.toString(16).padStart(8,"0");return T(a)+T(u)+T(d)+T(c)+T(p)+T(l)+T(h)+T(f)}function on(r){let e=rn(r??null),t=JSON.stringify(e);return Xr(t).slice(0,16)}function Zr(){let r=globalThis.crypto;if(r?.randomUUID)return r.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),t=e()+e()+e()+e();return`${t.slice(0,8)}-${t.slice(8,12)}-4${t.slice(13,16)}-${(parseInt(t.slice(16,17),16)&3|8).toString(16)}${t.slice(17,20)}-${t.slice(20,32)}`}function sn(r,e,t){let n=t?.id??Zr();if(r===0)return{id:n,version:0};let o=(t?.hash??on)(e);return{id:n,version:0,cid:o,prev:null}}function Wn(r,e,t){r.version+=1,"cid"in r&&(r.prev=r.cid,r.cid=t(e))}var Yr,Qr,Jn=me(()=>{"use strict";Yr=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]),Qr=new TextEncoder});function Xn(r){return{node:r,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function an(r){r.prevData=void 0,r.dirty=!1,r.involvedThisWave=!1,r.dataBatch.length=0,r.terminal=void 0}function Ct(r){return r.length===0?r:typeof r[0]=="symbol"?[r]:r}function ne(r,e,t){let n=Zn(r)?r:[],s=typeof r=="function"?r:typeof e=="function"?e:void 0,o={};return Zn(r)?o=(un(e)?e:t)??{}:un(r)?o=r:o=(un(e)?e:t)??{},new re(n,s,o)}var Yn,Qn,eo,to,tt,re,Zn,un,De=me(()=>{"use strict";tn();At();Ie();Ne();Hn();et();ge();Jn();Yn=()=>{},Qn=100;eo=(r,e,t,n)=>{t.direction==="down-in"&&r._onDepMessage(t.depIndex,e)},to=(r,e,t,n)=>{let s=r;if(s._status==="completed"||s._status==="errored")return;let o=s._cached,i=o===void 0?[kt]:[kt,[C,o]];s._status==="dirty"&&i.push(He),pt(e,i,s._config.tierOf)},tt=new Dt({onMessage:eo,onSubscribe:to});qn(tt);zn(tt);re=class r{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,t,n){this._config=n.config??tt,this._config.onMessage,this._optsName=n.name,this._describeKind=n.describeKind,this._equals=n.equals??Object.is,this._resubscribable=n.resubscribable??!1,this._resetOnTeardown=n.resetOnTeardown??!1,this._autoComplete=n.completeWhenDepsComplete??!0,this._autoError=n.errorWhenDepsError??!0,this._pausable=n.pausable??!0,this._guard=n.guard,this._fn=t,this._partial=n.partial??!1,this._cached=n.initial!==void 0?n.initial:void 0,this._status=e.length===0&&t==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=n.versioningHash??this._config.defaultHashFn??on;let s=n.versioning??this._config.defaultVersioning;this._versioningLevel=s,this._versioning=s!=null?sn(s,this._cached===void 0?void 0:this._cached,{id:n.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(Xn);let o={};for(let[a,u]of Object.entries(n.meta??{})){let d={initial:u,name:`${n.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};n.guard!=null&&(d.guard=n.guard),o[a]=new r([],void 0,d)}Object.freeze(o),this.meta=o,this._hasMeta=Object.keys(o).length>0;let i=this;this._actions={emit(a){i._emit([[C,a]])},down(a){i._emit(Ct(a))},up(a){i._emitUp(Ct(a))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,t){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let n=this._versioningLevel;if(n!=null&&e<=n)return;let s=t?.hash??this._hashFn;s!==this._hashFn&&(this._hashFn=s);let o=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??t?.id,u=i?.version??0,d=sn(e,o,{id:a,hash:s});d.version=u,this._versioning=d,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let t=St(e);if(this._guard!=null&&!this._guard(t,"observe"))return!1;if(this._extraGuards!=null){for(let n of this._extraGuards)if(!n(t,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let t=this._guard!=null||this._extraGuards!=null,n=e?.actor!=null;if(!t&&!n)return;let s=St(e?.actor),o=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(s,o))throw new Ee({actor:s,action:o,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(s,o))throw new Ee({actor:s,action:o,nodeName:this.name})}this._lastMutation={actor:s,timestamp_ns:ve()}}down(e,t){let n=Ct(e);n.length!==0&&(this._checkGuard(t),this._emit(n))}emit(e,t){this._checkGuard(t),this._emit([[C,e]])}up(e,t){if(this._deps.length===0)return;let n=Ct(e);if(n.length===0)return;this._checkGuard(t);let s=t??{internal:!0};this._validateUpTiers(n);for(let o of this._deps)o.node.up?.(n,s)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let t of this._deps)t.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let t=this._config.tierOf;for(let n of e){let s=t(n[0]);if(s===3||s===4)throw new Error(`Node "${this.name}": tier-${s} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,t){if(t!=null&&this._guard!=null){let u=St(t);if(!this._guard(u,"observe"))throw new Ee({actor:u,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 u of this._deps)an(u);if(this._partial===!1){for(let u of this._deps)if(u.prevData!==void 0||u.dataBatch.length!==0||u.terminal!==void 0||u.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(u){throw this._sinkCount-=1,u}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(u){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof o=="function")try{o()}catch{}throw u}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!0,this._sinkCount-=1,this._removeSink(e),typeof o=="function"&&o(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[t]=this._sinks;this._sinks=t}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,t=0;try{for(let n=0;n<e;n++){let s=n,o=this._deps[n];o.unsub=Yn,o.unsub=o.node.subscribe(i=>{if(o.unsub===null)return;let a=this._config.tierOf,u=!1;for(let d of i)a(d[0])>=3&&(u=!0),this._config.onMessage(this,d,{direction:"down-in",depIndex:s},this._actions);u&&this._maybeRunFnOnSettlement()}),t++}}catch(n){this._deps[t].unsub=null;for(let s=0;s<t;s++){let o=this._deps[s];if(o.unsub!=null){let i=o.unsub;o.unsub=null;try{i()}catch{}an(o)}}throw this._dirtyDepCount=0,n}}_addDep(e){for(let s=0;s<this._deps.length;s++)if(this._deps[s].node===e)return s;let t=this._deps.length,n=Xn(e);if(this._deps.push(n),this._sinks==null)return t;n.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Rt),n.unsub=Yn;try{n.unsub=e.subscribe(s=>{if(n.unsub===null)return;let o=this._config.tierOf,i=!1;for(let a of s)o(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:t},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(s){throw n.unsub=null,this._deps.pop(),this._dirtyDepCount--,s}return t}_deactivate(e=!1){let t=this._cleanup;if(this._cleanup=void 0,typeof t=="function")try{t()}catch(n){this._emit([[G,this._wrapFnError("cleanup threw",n)]])}else if(t!=null&&typeof t=="object"){let n=t.deactivate;if(typeof n=="function")try{n()}catch(s){this._emit([[G,this._wrapFnError("cleanup.deactivate threw",s)]])}}for(let n of this._deps){if(n.unsub!=null){let s=n.unsub;n.unsub=null;try{s()}catch{}}an(n)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,t){let n=this._deps[e],s=t[0];if(this._inspectorHooks!=null){let o={kind:"dep_message",depIndex:e,message:t};for(let i of this._inspectorHooks)i(o)}if(s!==Pe){if(s===ee){this._depDirtied(n);return}if(s===xe){if(this._depInvalidated(n),this._cached===void 0)return;this._emit(Xt);return}if(s===Ae||s===Le){this._emit([t]);return}if(s===ue){this._emit(Ot);return}if(s===C)this._depSettledAsData(n,t[1]);else if(s===Q)this._depSettledAsResolved(n);else if(s===j)this._depSettledAsTerminal(n,!0);else if(s===G)this._depSettledAsTerminal(n,t[1]);else{this._emit([t]);return}if(!this._fn){(s===C||s===Q)&&this._emit([t]),(s===j||s===G)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Rt))}_depSettledAsData(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(t),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=t,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let t=this._deps[e];if(t.dataBatch.length===0&&t.prevData===void 0&&t.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(Qt),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(t=>t.terminal!==void 0&&t.terminal!==!0);if(e!=null){this._autoError&&this._emit([[G,e.terminal]]);return}this._autoComplete&&this._deps.every(t=>t.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([[G,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([[G,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let t=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),n=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=t[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let s=this._deps.map(i=>i.terminal),o={prevData:n,terminalDeps:s,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:t,prevData:n};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(t,this._actions,o);if(typeof i=="function")this._cleanup=i;else if(i!=null&&typeof i=="object"){let a=i;(typeof a.beforeRun=="function"||typeof a.deactivate=="function"||typeof a.invalidate=="function")&&(this._cleanup=i)}}catch(i){this._emit([[G,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>Qn?(this._rerunDepth=0,this._emit([[G,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Qn} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,t){let n=t instanceof Error?t.message:String(t);return new Error(`Node "${this.name}": ${e}: ${n}`,{cause:t})}_frameBatch(e){let t=this._config.tierOf;if(e.length===1)return t(e[0][0])===3&&this._status!=="dirty"?[He,e[0]]:e;let n=!0,s=!1,o=!1,i=-1;for(let u of e){let d=t(u[0]);d<i&&(n=!1),d===3&&(s=!0),u[0]===ee&&(o=!0),i=d}let a=e;if(!n){let u=e.map((d,c)=>({m:d,i:c,tier:t(d[0])}));u.sort((d,c)=>d.tier-c.tier||d.i-c.i),a=u.map(d=>d.m)}if(s&&!o&&this._status!=="dirty"){let u=0;for(;u<a.length&&t(a[u][0])===0;)u++;return u===0?[He,...a]:[...a.slice(0,u),He,...a.slice(u)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let u=e[a];if(u[0]===G&&u[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let t=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(u=>u[0]===ue||u[0]===xe);if(a.length===0)return;t=a}t=this._frameBatch(t);let s=null;for(let a=0;a<t.length;a++){let u=t[a],d=u[0];if(d!==Ae&&d!==Le){s?.push(u);continue}if(u.length<2)throw new Error(`Node "${this.name}": [[${d===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 p=u[1];if(d===Ae)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(p),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(p))c=!1;else if(this._pauseLocks.delete(p),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let l=this._pauseBuffer;this._pauseBuffer=[],this._emit(l)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?s?.push(u):s==null&&(s=t.slice(0,a))}if(s!=null){if(s.length===0)return;t=s}if(this._hasMeta&&t.some(a=>a[0]===ue))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Ot)}catch{}let{finalMessages:o,equalsError:i}=this._updateState(t);if(o.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:o})}catch{}}if(o.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,u=[];for(let d of o)a(d[0])===3?this._pauseBuffer.push(d):u.push(d);u.length>0&&this._dispatchOrAccumulate(u)}else this._dispatchOrAccumulate(o);i!=null&&this._emit([[G,i]])}_updateState(e){let t=this._config.tierOf,n,s,o=-1,i=0;for(let c of e)t(c[0])===3&&i++;let a=i<=1,u=-1;if(this._versioning!=null&&i>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===C){u=c;break}}for(let c=0;c<e.length;c++){let p=e[c],l=p[0];if(l===C){if(p.length>=2){let h=!1;if(a&&this._cached!==void 0)try{h=this._equals(this._cached,p[1])}catch(f){s=this._wrapFnError("equals threw",f),o=c;break}if(h){n==null&&(n=e.slice(0,c)),n.push(Et),this._status="resolved";continue}this._cached=p[1],this._versioning!=null&&(u<0||c===u)&&Wn(this._versioning,p[1],this._hashFn)}this._status="settled",n?.push(p)}else if(n?.push(p),l===ee)this._status="dirty";else if(l===Q)this._status="resolved";else if(l===j){this._status="completed";{let h=this._config.rigorRecorder;if(h!=null)try{h.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(l===G){this._status="errored";{let h=this._config.rigorRecorder;if(h!=null)try{h.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(l===xe){if(this._cached!==void 0){let f=this._config.rigorRecorder;if(f!=null)try{f.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let h=this._cleanup;if(typeof h=="function"){this._cleanup=void 0;try{h()}catch{}}else if(h!=null&&typeof h=="object"){let f=h.invalidate;if(typeof f=="function")try{f()}catch{}}}else l===ue&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let d=o>=0?n??e.slice(0,o):n??e;return s!=null?{finalMessages:d,equalsError:s}:{finalMessages:d}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let t=[...this._sinks];for(let n of t)n(e)};_dispatchOrAccumulate(e){if(Bn()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],Ze(()=>this._flushBatchPending()));for(let t of e)this._batchPendingMessages.push(t);return}pt(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let t=this._frameBatch(e);pt(this._deliverToSinks,t,this._config.tierOf)}},Zn=r=>Array.isArray(r),un=r=>typeof r=="object"&&r!=null&&!Array.isArray(r)});function L(r,e){return ne([],{...e,initial:r})}function de(r,e){return ne((n,s,o)=>r(s,o)??void 0,{describeKind:"producer",...e})}function I(r,e,t){return ne(r,(s,o,i)=>{let a=s.map((u,d)=>u!=null&&u.length>0?u.at(-1):i.prevData[d]);o.emit(e(a,i))},{describeKind:"derived",...t})}function be(r,e,t){return ne(r,(s,o,i)=>{let a=s.map((u,d)=>u!=null&&u.length>0?u.at(-1):i.prevData[d]);return e(a,o,i)??void 0},{describeKind:"effect",...t})}var oe=me(()=>{"use strict";De()});function cn(r,e){if(e!=null&&e.length>0)return new Set(e);switch(r){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;case"spec":return new Set(["type","deps","meta","value"]);default:return new Set(["type","deps"])}}function no(r){return r._describeKind!=null?r._describeKind:r._deps.length>0?"derived":r._fn!=null?"producer":"state"}function ht(r){let e=new WeakSet,t={};for(let[n,s]of er(r))t[n]=dn(s,e);return t}function dn(r,e){if(r==null)return r;let t=typeof r;if(t==="boolean"||t==="number"||t==="string")return r;if(t==="function")return"<function>";if(Array.isArray(r))return e.has(r)?"<cycle>":(e.add(r),r.map(n=>dn(n,e)));if(t==="object"){let n=r;if(e.has(n))return"<cycle>";e.add(n);try{if(typeof n.subscribe=="function"&&"cache"in n)return"<Node>"}catch{return"<unserializable>"}let s={};for(let[o,i]of er(n))s[o]=dn(i,e);return s}return"<unserializable>"}function er(r){let e=[],t;try{t=Object.keys(r)}catch{return e}for(let n of t)try{e.push([n,r[n]])}catch{e.push([n,"<unserializable>"])}return e}function nt(r,e){let t={factory:r};return e!==void 0&&(t.factoryArgs=e),t}function ro(r){let e={};for(let[t,n]of Object.entries(r.meta))try{e[t]=n.cache}catch{}return e}function ln(r,e,t){let n=e==null,s=!n&&e!=null?[...e].filter(c=>c.startsWith("meta.")).map(c=>c.slice(5)):null,o=n||e.has("meta")||s!=null&&s.length>0,i="state",a=[];r instanceof re&&(i=no(r),a=r._deps.map(c=>c.node.name??""));let u={type:i,deps:a};(n||e.has("status"))&&(u.status=r.status);let d=r instanceof re?r._guard:void 0;if(o){let c={...ro(r)};if(d!=null&&c.access===void 0&&(c.access=nn(d)),s!=null&&s.length>0&&!e.has("meta")){let p={};for(let l of s)l in c&&(p[l]=c[l]);u.meta=p}else u.meta=c}if(r.name!=null&&(u.name=r.name),(n||e.has("value"))&&(!t||i==="state")){r.status==="sentinel"&&(u.sentinel=!0);try{u.value=r.cache}catch{}}if((n||e.has("v"))&&r.v!=null){let c={id:r.v.id,version:r.v.version};"cid"in r.v&&(c.cid=r.v.cid,c.prev=r.v.prev),u.v=c}return(n||e.has("guard"))&&d!=null&&(u.guard=nn(d)),(n||e.has("lastMutation"))&&r.lastMutation!=null&&(u.lastMutation=r.lastMutation),u}var mt=me(()=>{"use strict";et();De()});function fn(r){return{describeKind:"producer",...r}}function tr(r,e){return de(t=>{let n=!1;try{for(let s of r){if(n)return;t.emit(s)}n||t.down([[j]])}catch(s){n||t.down([[G,s]])}return()=>{n=!0}},fn(e))}function oo(r){return r!=null&&typeof r.then=="function"}function so(r,e){let{signal:t,...n}=e??{};return de(s=>{let o=!1,i=()=>{o||(o=!0,s.down([[G,t.reason]]))};if(t?.aborted){i();return}return t?.addEventListener("abort",i,{once:!0}),Promise.resolve(r).then(a=>{o||(o=!0,t?.removeEventListener("abort",i),s.emit(a),s.down([[j]]))},a=>{o||(o=!0,t?.removeEventListener("abort",i),s.down([[G,a]]))}),()=>{o=!0,t?.removeEventListener("abort",i)}},fn(n))}function io(r,e){let{signal:t,...n}=e??{};return de(s=>{let o=new AbortController,i=()=>o.abort(t?.reason);t?.aborted?o.abort(t.reason):t?.addEventListener("abort",i,{once:!0});let a=t??o.signal,u=!1,d=r[Symbol.asyncIterator](),c=()=>{u||a.aborted||Promise.resolve(d.next()).then(p=>{if(!(u||a.aborted)){if(p.done){s.down([[j]]);return}s.emit(p.value),c()}},p=>{!u&&!a.aborted&&s.down([[G,p]])})};return c(),()=>{u=!0,t?.removeEventListener("abort",i),o.abort(),Promise.resolve(d.return?.()).catch(()=>{})}},fn(n))}function ao(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"}function Fe(r,e){if(ao(r))return r;if(oo(r))return so(r,e);if(r!=null){let t=r;if(typeof t[Symbol.asyncIterator]=="function")return io(r,e);if(typeof t[Symbol.iterator]=="function")return tr(r,e)}return uo(r)}function uo(...r){return tr(r,void 0)}function nr(r,e){let t=new AbortController,n=e?.reason??new Error("cancelled via nodeSignal"),s,o=!1,i=()=>{s?(s(),s=void 0):o=!0};return s=r.subscribe(a=>{if(!t.signal.aborted)for(let u of a){if(u[0]===C&&u[1]===!0){t.abort(n),i();return}if(u[0]===G){t.abort(u[1]),i();return}if(u[0]===j){i();return}}}),o&&(s?.(),s=void 0),{signal:t.signal,dispose:()=>{s&&(s(),s=void 0)}}}function ye(r){return r.subscribe(()=>{})}var rr=me(()=>{"use strict";ge();oe()});var $e=me(()=>{"use strict";rr()});var Pt,ar=me(()=>{"use strict";Pt=class{_timer;_gen=0;start(e,t){this.cancel(),this._gen+=1;let n=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,n===this._gen&&t()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var yt,ur=me(()=>{"use strict";yt=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<=0)throw new Error(`RingBuffer capacity must be a positive integer (got ${e})`);this.buf=new Array(e)}buf;head=0;_size=0;get size(){return this._size}get maxSize(){return this.capacity}push(e){let t=(this.head+this._size)%this.capacity;this.buf[t]=e,this._size<this.capacity?this._size++:this.head=(this.head+1)%this.capacity}shift(){if(this._size===0)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this._size--,e}at(e){if(this._size===0)return;let t=e<0?this._size+e:e;if(!(t<0||t>=this._size))return this.buf[(this.head+t)%this.capacity]}toArray(){let e=new Array(this._size);for(let t=0;t<this._size;t++)e[t]=this.buf[(this.head+t)%this.capacity];return e}clear(){for(let e=0;e<this._size;e++)this.buf[(this.head+e)%this.capacity]=void 0;this.head=0,this._size=0}}});function ze(r,e,t){return{[r]:!0,[`${r}_type`]:e,...t??{}}}var vt=me(()=>{"use strict"});var gs={};Br(gs,{DEFAULT_DECAY_RATE:()=>ot,DEFAULT_EXECUTE_PROMPT:()=>hn,DEFAULT_QUEUE_CONFIGS:()=>It,DEFAULT_SEVERITY_WEIGHTS:()=>rt,DEFAULT_TRIAGE_PROMPT:()=>pn,DEFAULT_VERIFY_PROMPT:()=>mn,HarnessGraph:()=>Wt,QUEUE_NAMES:()=>_e,actuatorExecutor:()=>sr,affectedTaskFilter:()=>wo,autoSolidify:()=>bo,beforeAfterCompare:()=>_o,codeChangeBridge:()=>xo,createIntakeBridge:()=>yo,defaultErrorClassifier:()=>Gt,defaultLlmExecutor:()=>Pr,defaultLlmVerifier:()=>Lr,dispatchActuator:()=>go,effectivenessTracker:()=>ko,evalIntakeBridge:()=>vo,evalSource:()=>To,evalVerifier:()=>xr,harnessEvalPair:()=>ns,harnessLoop:()=>cs,harnessProfile:()=>fs,harnessTrace:()=>hs,notifyEffect:()=>No,priorityScore:()=>us,refineExecutor:()=>On,resolvePromptFn:()=>bt,strategyKey:()=>st,strategyModel:()=>Mn});module.exports=Hr(gs);ge();oe();ge();mt();De();oe();$e();function Mt(r){return{describeKind:"derived",...r}}function co(r){return{describeKind:"derived",partial:!0,...r}}function Ve(r,e,t){return ne([r],(n,s)=>{let o=n[0];if(o==null||o.length===0){s.down([[Q]]);return}let i=!1;for(let a of o)e(a)&&(s.emit(a),i=!0);i||s.down([[Q]])},{...Mt(t),meta:{...nt("filter"),...t?.meta??{}}})}function gt(r,e,t){return ne([r,e],(n,s,o)=>{let i=n[0],a=n[1],u=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([[Q]]);return}for(let d of i)s.emit([d,u])}else s.down([[Q]])},{...co(t),meta:{...nt("withLatestFrom"),...t?.meta??{}}})}function or(...r){return r.length===0?de(e=>{e.down([[j]])},{...Mt(),meta:{...nt("merge")}}):de(e=>{let t=r.length,n=0,s=[];for(let o of r){let i=o.subscribe(a=>{for(let u of a)u[0]===C?e.emit(u[1]):u[0]===j?(n+=1,n>=t&&e.down([[j]])):u[0]===G&&e.down([u])});s.push(i)}return()=>{for(let o of s)o()}},{...Mt(),meta:{...nt("merge")}})}function lo(r,e,t){let n,s=!1,o=()=>{s||(s=!0,t())};return n=r.subscribe(i=>{let a=!1,u=!1;for(let d of i)d[0]!==Pe&&(d[0]===C?e.emit(d[1]):d[0]===j?a=!0:d[0]===G?(u=!0,e.down([d])):(d[0]===ee||d[0]===Q)&&e.down([d]));u?(n?.(),n=void 0,o()):a&&o()}),()=>{n?.(),n=void 0}}function ke(r,e,t){let n,s=!1;function o(){n?.(),n=void 0}return ne([r],(i,a,u)=>{if(u.terminalDeps[0]!=null&&u.terminalDeps[0]!==!0){o();return}if(u.terminalDeps[0]===!0){s=!0,n||a.down([[j]]);return}let d=i[0];if(!(d==null||d.length===0))return o(),n=lo(Fe(e(d[d.length-1])),a,()=>{o(),s&&a.down([[j]])}),{deactivate:()=>{o(),s=!1}}},{...Mt(t),completeWhenDepsComplete:!1,meta:{...nt("switchMap"),...t?.meta??{}}})}$e();function fo(r,e){return{outcome:"success",detail:`actuator applied ${e.intervention} for ${mo(e.summary)}`,artifact:r}}function po(r,e){let t=r instanceof Error?r.message:String(r);return{outcome:"failure",detail:`actuator threw on ${e.intervention}: ${t}`}}function ho(r){return`actuator skipped ${r.intervention} (shouldApply returned false)`}function mo(r,e=80){return r.length<=e?r:`${r.slice(0,e-1)}\u2026`}function sr(r){let e=r.name??"actuator-executor",t=r.toOutput??fo,n=r.onError??po,s=r.skipDetail??ho;return o=>{let i=Ve(o,u=>u!=null,{name:`${e}/gate-in`}),a=ke(i,u=>r.shouldApply&&!r.shouldApply(u)?de(d=>(d.down([[C,{outcome:"failure",detail:s(u)}],[j]]),()=>{}),{name:`${e}/skip`}):de(d=>{let c=new AbortController,p=!1,l=null,h=g=>{p||(p=!0,d.down([[C,g],[j]]),l?.(),l=null)},f;try{let g=r.apply(u,{signal:c.signal});f=Fe(g,{signal:c.signal})}catch(g){return h(n(g,u)),()=>{c.abort()}}return l=f.subscribe(g=>{for(let m of g){if(p)return;if(m[0]===C){h(t(m[1],u));return}if(m[0]===G){h(n(m[1],u));return}if(m[0]===j){h(n(new Error("actuator inner completed without emitting DATA"),u));return}}}),p&&l&&(l(),l=null),()=>{c.abort(),l?.(),l=null}},{name:`${e}/inner`}),{name:e});return Ve(a,u=>u!=null,{name:`${e}/gate-out`})}}function go(r){let e=r.name??"dispatch-actuator",t=r.default??null,n=t!=null;return sr({apply:(s,o)=>{let i=Object.hasOwn(r.routes,s.intervention)?r.routes[s.intervention]:t;if(!i)throw new Error(`dispatchActuator: no route for intervention '${s.intervention}'`);return i(s,o)},shouldApply:s=>Object.hasOwn(r.routes,s.intervention)||n,skipDetail:s=>`no route for intervention '${s.intervention}'`,name:e})}ge();oe();function bo(r){let e=r.name??"auto-solidify",t=r.extract??(s=>s.execution.artifact??null),n=r.predicate??(()=>!0);return de(s=>{let o=null,i=!1,a=()=>{i||(i=!0,o?.(),o=null)},u=d=>{i||(s.down([[G,d]]),a())};return o=r.verifyResults.subscribe(d=>{if(!i)for(let c of d){if(i)return;if(c[0]!==C){if(c[0]===j){s.down([[j]]),a();return}continue}let p=c[1];if(p==null||!p.verified)continue;let l;try{l=n(p)}catch(f){u(f);return}if(!l)continue;let h;try{h=t(p)}catch(f){u(f);return}if(h!=null){try{r.write(h,p)}catch(f){u(f);return}s.down([[C,h]])}}}),i&&o&&(o(),o=null),()=>{a()}},{name:e})}oe();$e();function yo(r,e,t,n){return be([r],([s])=>{if(s==null)return;let o=t(s);for(let i of o)e.publish(i)},{name:n?.name??"intake-bridge"})}function vo(r,e,t){let n=t?.defaultSeverity??"medium";return be([r],([s])=>{if(s==null)return;let o=Array.isArray(s)?s:[s];for(let i of o)for(let a of i.tasks)if(!(a.valid&&a.judge_scores?.every(u=>u.pass))){if(!a.valid&&(!a.judge_scores||a.judge_scores.length===0)){e.publish({source:"eval",summary:`Task ${a.task_id} invalid (model: ${i.model})`,evidence:`Run ${i.run_id}: task produced invalid output`,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:n});continue}if(a.judge_scores)for(let u of a.judge_scores)u.pass||e.publish({source:"eval",summary:`${a.task_id}: ${u.claim} (model: ${i.model})`,evidence:u.reasoning,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:n})}},{name:t?.name??"eval-intake-bridge"})}function To(r,e){return ke(r,()=>Fe(e()))}function _o(r,e){return I([r,e],([t,n])=>{let s=t,o=n,i=new Map(s.tasks.map(l=>[l.task_id,l])),a=new Map(o.tasks.map(l=>[l.task_id,l])),u=new Set([...i.keys(),...a.keys()]),d=[],c=[],p=[];for(let l of u){let h=i.get(l),f=a.get(l),g=h?.valid??!1,m=f?.valid??!1,T=h?.judge_scores?h.judge_scores.filter(_=>_.pass).length:void 0,y=f?.judge_scores?f.judge_scores.filter(_=>_.pass).length:void 0,v=T!==void 0&&y!==void 0?y-T:void 0;d.push({taskId:l,before:g,after:m,scoreDiff:v}),g&&!m&&c.push(l),!g&&m&&p.push(l)}return{newFailures:c,resolved:p,taskDeltas:d,overallImproved:p.length>c.length}},{name:"eval-delta"})}function wo(r,e){let t=e==null?null:Array.isArray(e)?L(e):e,n=[r];return t&&n.push(t),I(n,s=>{let o=s[0],i=t?new Set(s[1]):null,a=new Set;for(let u of o)for(let d of u.affectsEvalTasks??[])(i==null||i.has(d))&&a.add(d);return[...a].sort()},{name:"affected-task-filter"})}function xo(r,e,t,n){let s=n?.defaultSeverity??"high";function o(a){let u=[];for(let d of a.lintErrors??[])u.push({source:"code-change",summary:`Lint: ${d.rule} in ${d.file}:${d.line}`,evidence:d.message,affectsAreas:[d.file],severity:s});for(let d of a.testFailures??[])u.push({source:"test",summary:`Test failure: ${d.testId}`,evidence:d.message,affectsAreas:[d.file],affectsEvalTasks:[d.testId],severity:s});return u}let i=t??o;return be([r],([a])=>{if(a!=null)for(let u of i(a))e.publish(u)},{name:n?.name??"code-change-bridge"})}function No(r,e,t){return be([r.latest],([n])=>{n!=null&&e(n)},{name:t?.name??"notify-effect"})}var _e=["auto-fix","needs-decision","investigation","backlog"],It={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},rt={critical:100,high:70,medium:40,low:10},ot=Math.LN2/(168*3600);function st(r,e){return`${r}\u2192${e}`}var Eo=/\b(parse|json|config|validation|syntax)\b/i,Gt=r=>Eo.test(r.detail)?"self-correctable":"structural",pn=`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}}`,hn=`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
|
+
}`,mn=`You are a QA reviewer.
|
|
28
28
|
|
|
29
29
|
Given an execution result, verify whether the fix is correct.
|
|
30
30
|
|
|
@@ -39,12 +39,8 @@ 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 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
|
|
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});
|
|
42
|
+
}`;function bt(r,e,t){if(typeof r=="function")return r;let n=r??e;return s=>t(n,s)}oe();Ie();Ne();ge();oe();var gn=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(e={}){let{maxSize:t,defaultTtl:n}=e;if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1");if(n!==void 0&&n<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=t,this._defaultTtl=n}get version(){return this._version}get size(){return this._store.size}has(e){let t=this._store.get(e);return t===void 0?!1:this._isExpired(t)?(this._store.delete(e),this._version+=1,!1):(this._touchLru(e,t),!0)}get(e){let t=this._store.get(e);if(t!==void 0){if(this._isExpired(t)){this._store.delete(e),this._version+=1;return}return this._touchLru(e,t),t.value}}set(e,t,n){let s=this._resolveExpiresAt(n);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:t,expiresAt:s}),this._evictLruWhileOver(),this._version+=1}setMany(e,t){let n=this._resolveExpiresAt(t),s=0;try{for(let[o,i]of e)this._store.has(o)&&this._store.delete(o),this._store.set(o,{value:i,expiresAt:n}),s+=1}finally{s>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(e){let t=this._store.delete(e);return t&&(this._version+=1),t}deleteMany(e){let t=0;try{for(let n of e)this._store.delete(n)&&(t+=1)}finally{t>0&&(this._version+=1)}return t}clear(){let e=this._store.size;return e===0?0:(this._store.clear(),this._version+=1,e)}pruneExpired(){let e=K(),t=0;for(let[n,s]of this._store)this._isExpired(s,e)&&(this._store.delete(n),t+=1);return t>0&&(this._version+=1),t}toMap(){let e=K(),t=new Map;for(let[n,s]of this._store)this._isExpired(s,e)||t.set(n,s.value);return t}_resolveExpiresAt(e){let t=e??this._defaultTtl;if(t!==void 0){if(!Number.isFinite(t)||t<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${t})`);return K()+t*1e9}}_isExpired(e,t){return e.expiresAt===void 0?!1:(t??K())>=e.expiresAt}_touchLru(e,t){this._store.delete(e),this._store.set(e,t)}_evictLruWhileOver(){if(this._maxSize!==void 0)for(;this._store.size>this._maxSize;){let e=this._store.keys().next().value;if(e===void 0)break;this._store.delete(e)}}};function it(r={}){let{name:e,maxSize:t,defaultTtl:n,versioning:s,backend:o,retention:i}=r;if(i&&t!==void 0)throw new RangeError("reactiveMap: `maxSize` (LRU) and `retention` (score-based) are mutually exclusive. Pick one eviction policy.");if(i&&i.archiveThreshold===void 0&&i.maxSize===void 0)throw new RangeError("reactiveMap: `retention` requires at least one of `archiveThreshold` or `maxSize` to trigger archival.");let a=o??new gn({maxSize:t,defaultTtl:n}),u=L(a.toMap(),{name:e,describeKind:"state",equals:(l,h)=>l===h,...s!=null?{versioning:s}:{}});function d(){let l=a.toMap();te(()=>{u.down([[ee]]),u.down([[C,l]])})}function c(){if(!i)return;let l=a.toMap(),h=i.archiveThreshold,f=i.maxSize,g=[];for(let[T,y]of l)g.push({key:T,value:y,score:i.score(T,y)});g.sort((T,y)=>T.score-y.score);let m=new Set;if(h!==void 0)for(let T of g)if(T.score<h)m.add(T.key);else break;if(f!==void 0&&g.length-m.size>f)for(let T of g){if(g.length-m.size<=f)break;m.has(T.key)||m.add(T.key)}if(m.size!==0)for(let T of g)m.has(T.key)&&(i.onArchive?.(T.key,T.value,T.score),a.delete(T.key))}function p(l,h="mutation"){let f=a.version;try{return l()}finally{a.version!==f&&(h==="mutation"&&c(),d())}}return{entries:u,has(l){return p(()=>a.has(l),"read")},get(l){return p(()=>a.get(l),"read")},set(l,h,f){p(()=>a.set(l,h,f?.ttl))},setMany(l,h){p(()=>a.setMany(l,h?.ttl))},delete(l){p(()=>a.delete(l))},deleteMany(l){p(()=>a.deleteMany(l))},clear(){p(()=>a.clear())},pruneExpired(){p(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}$e();function ko(r){let e=it({name:r?.name??"effectiveness-entries"}),t=I([e.entries],([i])=>new Map(i),{name:`${r?.name??"effectiveness"}-snapshot`,equals:(i,a)=>{let u=i,d=a;if(u.size!==d.size)return!1;for(let[c,p]of u){let l=d.get(c);if(!l||p.attempts!==l.attempts||p.successes!==l.successes)return!1}return!0}});function n(i,a){let u=e.get(i),d=(u?.attempts??0)+1,c=(u?.successes??0)+(a?1:0);e.set(i,{key:i,attempts:d,successes:c,successRate:c/d})}function s(i){return e.get(i)}let o=ye(t);return{node:t,record:n,lookup:s,dispose:()=>{o(),e.dispose()}}}oe();oe();Ie();Ne();ge();De();oe();At();Ie();Ne();et();ge();mt();De();oe();Ne();function bn(r,e){if(Object.is(r,e))return!0;if(r==null||e==null||typeof r!="object"||typeof e!="object")return!1;if(Array.isArray(r)){if(!Array.isArray(e)||r.length!==e.length)return!1;for(let o=0;o<r.length;o++)if(!bn(r[o],e[o]))return!1;return!0}if(Array.isArray(e))return!1;let t=Object.keys(r),n=Object.keys(e);if(t.length!==n.length)return!1;let s=new Set(n);for(let o of t)if(!s.has(o)||!bn(r[o],e[o]))return!1;return!0}function ir(r,e){return`${r}\0${e}`}function yn(r,e){let t=[],n=new Set(r.subgraphs),s=new Set(e.subgraphs),o=[];for(let m of s)n.has(m)||o.push(m);o.sort();for(let m of o)t.push({type:"subgraph-mounted",path:m});let i=new Set(Object.keys(r.nodes)),a=new Set(Object.keys(e.nodes)),u=[];for(let m of a)i.has(m)||u.push(m);u.sort();for(let m of u)t.push({type:"node-added",path:m,node:{...e.nodes[m]}});let d=[];for(let m of a){if(!i.has(m))continue;let T=r.nodes[m]?.meta,y=e.nodes[m]?.meta;T==null&&y==null||bn(T??{},y??{})||d.push(m)}d.sort();for(let m of d)t.push({type:"node-meta-changed",path:m,prevMeta:r.nodes[m]?.meta??{},nextMeta:e.nodes[m]?.meta??{}});let c=new Map;for(let m of r.edges)c.set(ir(m.from,m.to),m);let p=new Map;for(let m of e.edges)p.set(ir(m.from,m.to),m);let l=[];for(let[m,T]of p)c.has(m)||l.push(T);l.sort((m,T)=>m.from<T.from?-1:m.from>T.from?1:m.to<T.to?-1:m.to>T.to?1:0);for(let m of l)t.push({type:"edge-added",from:m.from,to:m.to});let h=[];for(let[m,T]of c)p.has(m)||h.push(T);h.sort((m,T)=>m.from<T.from?-1:m.from>T.from?1:m.to<T.to?-1:m.to>T.to?1:0);for(let m of h)t.push({type:"edge-removed",from:m.from,to:m.to});let f=[];for(let m of i)a.has(m)||f.push(m);f.sort();for(let m of f)t.push({type:"node-removed",path:m});let g=[];for(let m of n)s.has(m)||g.push(m);g.sort();for(let m of g)t.push({type:"subgraph-unmounted",path:m});return{events:t,flushedAt_ns:K()}}$e();ar();ur();tn();function dr(r,e,t,n={}){let s=e in r.nodes,o=t in r.nodes;if(!s)return Lt(e,t,"no-such-from");if(!o)return Lt(e,t,"no-such-to");let i=n.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===t){if(n.findCycle===!0){let d=Ro(r,e,n);if(d!=null)return d}let u=Ft(e,r.nodes[e],0,n);return $t(e,t,[u])}if(i===0)return Lt(e,t,"no-path");let a=cr(r,e,t,i);return a.found?$t(e,t,lr(r,a.pathOrder,n)):Lt(e,t,a.truncated?"max-depth-exceeded":"no-path")}function cr(r,e,t,n){let s=new Map,o=[{path:t,depth:0}],i=new Set([t]),a=0,u=!1;for(;a<o.length;){let p=o[a++];if(p.path===e)break;if(n!=null&&p.depth>=n){let g=r.nodes[p.path];g?.deps&&g.deps.length>0&&(u=!0);continue}let l=r.nodes[p.path];if(l==null)continue;let h=l.deps??[],f=new Map;for(let g=0;g<h.length;g++){let m=h[g];if(!m)continue;let T=f.get(m);T==null&&(T=[],f.set(m,T)),T.push(g)}for(let[g,m]of f)i.has(g)||(i.add(g),s.set(g,{from:p.path,depIndices:m}),o.push({path:g,depth:p.depth+1}))}if(!s.has(e))return{found:!1,pathOrder:[],truncated:u};let d=[{path:e}],c=e;for(;c!==t;){let p=s.get(c);if(p==null)return{found:!1,pathOrder:[],truncated:!1};d[d.length-1].depIndices=p.depIndices,d.push({path:p.from}),c=p.from}return{found:!0,pathOrder:d,truncated:!1}}function Ro(r,e,t){let n=r.nodes[e];if(n==null)return null;let s=n.deps??[],o=[];for(let a=0;a<s.length;a++)s[a]===e&&o.push(a);if(o.length>0){let a=Ft(e,n,0,t);a.dep_index=o[0];let u=Ft(e,n,1,t);return $t(e,e,[a,u])}let i=null;for(let a=0;a<s.length;a++){let u=s[a];if(!u||u===e)continue;let d=cr(r,u,e,t.maxDepth);d.found&&(i==null||d.pathOrder.length<i.pathOrder.length)&&(i=d,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...d.pathOrder],truncated:!1})}return i==null?null:$t(e,e,lr(r,i.pathOrder,t))}function lr(r,e,t){return e.map((n,s)=>{let o=r.nodes[n.path],i=Ft(n.path,o,s,t);return n.depIndices!=null&&n.depIndices.length>0&&(i.dep_index=n.depIndices[0],n.depIndices.length>1&&(i.dep_indices=[...n.depIndices])),i})}function Ft(r,e,t,n){let s={path:r,type:e.type,hop:t};e.status!==void 0&&(s.status=e.status),"value"in e&&(s.value=e.value),e.v!=null&&(s.v=e.v);let o=n.annotations?.get(r)??e.annotation;o!=null&&(s.annotation=o);let i=n.lastMutations?.get(r)??e.lastMutation;return i!=null&&(s.lastMutation=i),s}function $t(r,e,t){return fr(r,e,!0,"ok",t)}function Lt(r,e,t){return fr(r,e,!1,t,[])}function fr(r,e,t,n,s){let o=Oo(r,e,t,n,s);return{from:r,to:e,found:t,reason:n,steps:s,text:o,toJSON(){return{from:r,to:e,found:t,reason:n,steps:s}}}}function Oo(r,e,t,n,s){if(!t)switch(n){case"no-such-from":return`explainPath: no node named "${r}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${r}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${r}" to "${e}"`}let o=[`Causal path: ${r} \u2192 ${e} (${s.length} step(s))`];for(let i of s){let u=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(o.push(u),"value"in i&&o.push(` value: ${So(i.value)}`),i.annotation!=null&&o.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let d=i.lastMutation.actor;o.push(` actor: ${d.type}${d.id?`:${d.id}`:""}`)}}return o.join(`
|
|
43
|
+
`)}function So(r){if(r===void 0)return"<sentinel>";if(r===null)return"null";if(typeof r=="string")return JSON.stringify(r);if(typeof r=="number"||typeof r=="boolean"||typeof r=="bigint")return String(r);try{let e=JSON.stringify(r);return e.length>80?`${e.slice(0,77)}...`:e}catch{return String(r)}}De();var se={object:56,array:64,string:40,number:8,boolean:4,null:0,undefined:0,symbol:40,bigint:16,function:120,map:72,set:72,mapEntry:40,setEntry:24,date:24,regexp:48,error:64,url:80,promise:48,weakmap:40,weakset:40},Ao=Symbol.for("sizeof");function pr(r){let e=new WeakSet,t=new WeakSet,n=[r],s=0;for(;n.length>0;){let o=n.pop();s+=Do(o,e,t,n)}return s}function Do(r,e,t,n){if(r==null)return 0;switch(typeof r){case"number":return se.number;case"boolean":return se.boolean;case"string":return se.string+r.length*2;case"bigint":return se.bigint+Co(r);case"symbol":return se.symbol;case"function":return e.has(r)?0:(e.add(r),se.function);case"undefined":return 0}let o=r;if(e.has(o))return 0;e.add(o);let i=o[Ao];if(typeof i=="function")try{let d=i.call(o);if(typeof d=="number"&&Number.isFinite(d))return d}catch{}if(o instanceof Date)return se.date;if(o instanceof RegExp)return se.regexp+o.source.length*2;if(o instanceof Error){let d=o.message?o.message.length*2:0,c=o.stack?o.stack.length*2:0;return se.error+d+c}if(typeof URL<"u"&&o instanceof URL)return se.url+o.href.length*2;if(typeof Promise<"u"&&o instanceof Promise)return se.promise;if(o instanceof WeakMap)return se.weakmap;if(o instanceof WeakSet)return se.weakset;if(o instanceof Map){let d=se.map;for(let[c,p]of o)d+=se.mapEntry,n.push(c),n.push(p);return d}if(o instanceof Set){let d=se.set;for(let c of o)d+=se.setEntry,n.push(c);return d}if(Array.isArray(o)){let d=se.array+o.length*8;for(let c of o)n.push(c);return d}if(o instanceof ArrayBuffer)return t.has(o)?0:(t.add(o),o.byteLength);if(ArrayBuffer.isView(o)){let d=o;return t.has(d.buffer)?48:(t.add(d.buffer),d.buffer.byteLength+48)}let a=se.object,u=Object.keys(o);for(let d of u){a+=se.string+d.length*2;try{n.push(o[d])}catch{}}return a}function Co(r){let e=r<0n?-r:r;if(e===0n)return 0;let t=e.toString(2).length;return Math.ceil(t/32)*8}function Vt(r,e){let t=e?.topN??10,n=r.describe({detail:"standard"}),s=[],o=r._collectObserveTargets;typeof o=="function"&&o.call(r,"",s);let i=new Map;for(let[l,h]of s)i.set(l,h);let a=[];for(let[l,h]of Object.entries(n.nodes)){let f=i.get(l),g=f instanceof re?f:null,m=g?pr(g.cache):0,T=g?g._sinkCount:0,y=h.deps?.length??0,v=h.type==="effect"&&T===0,_=T===0?h.type==="effect"?"orphan-effect":h.type==="derived"?"idle-derived":h.type==="producer"?"idle-producer":null:null;a.push({path:l,type:h.type,status:h.status??"unknown",valueSizeBytes:m,subscriberCount:T,depCount:y,isOrphanEffect:v,orphanKind:_})}let u=a.reduce((l,h)=>l+h.valueSizeBytes,0),d=(l,h)=>[...a].sort(h??((f,g)=>g[l]-f[l])).slice(0,t),c=a.filter(l=>l.orphanKind!=null),p=a.filter(l=>l.isOrphanEffect);return{nodeCount:a.length,edgeCount:n.edges.length,subgraphCount:n.subgraphs.length,nodes:a,totalValueSizeBytes:u,hotspots:{byValueSize:d("valueSizeBytes"),bySubscriberCount:d("subscriberCount"),byDepCount:d("depCount")},orphans:c,orphanEffects:p}}var X="::",Re="__meta__",We=1;function hr(r,e){let t=Math.max(16,r.size*4),n=0;for(;r.size>0;){if(n++>=t){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${t}); ${r.size} disposer(s) discarded`),r.clear();return}let s=r.values().next();if(s.done)return;let o=s.value;r.delete(o);try{o()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function vr(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"&&typeof r.down=="function"}function Mo(r){if(r!=null)return vr(r)?r.cache:r}function Je(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"&&typeof r.down=="function"}function je(r){return Je(r)?r.cache??"":r}function mr(r){return Je(r)?r.cache??0:r}function gr(r){return Je(r)?r.cache??!1:r}function Io(r){let e=[];for(let t of Object.keys(r).sort()){let n=r[t].v;n!=null&&e.push(`${t} ${n.id} ${n.version}`)}return e.join(`
|
|
44
|
+
`)}function br(r){if(r.version!==We)throw new Error(`unsupported snapshot version ${String(r.version)} (expected ${We})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in r))throw new Error(`snapshot missing required key "${e}"`);if(typeof r.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof r.nodes!="object"||r.nodes===null||Array.isArray(r.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(r.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(r.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function Go(r,e){let t=new WeakMap,n=(s,o)=>{if(Object.is(s,o))return!0;if(s==null||o==null||typeof s!="object"||typeof o!="object")return!1;let i=t.get(s);if(i==null&&(i=new WeakSet,t.set(s,i)),i.has(o))return!0;i.add(o);let a=s.constructor,u=o.constructor;if(a!==u)return!1;if(s instanceof Date)return s.getTime()===o.getTime();if(s instanceof RegExp)return s.source===o.source&&s.flags===o.flags;if(Array.isArray(s)){let l=o;if(s.length!==l.length)return!1;for(let h=0;h<s.length;h++)if(!n(s[h],l[h]))return!1;return!0}if(s instanceof Map){let l=o;if(s.size!==l.size)return!1;for(let[h,f]of s)if(!l.has(h)||!n(f,l.get(h)))return!1;return!0}if(s instanceof Set){let l=o;if(s.size!==l.size)return!1;for(let h of s){let f=!1;for(let g of l)if(n(h,g)){f=!0;break}if(!f)return!1}return!0}if(ArrayBuffer.isView(s)){let l=s,h=o;if(l.length!==h.length)return!1;for(let f=0;f<l.length;f++)if(l[f]!==h[f])return!1;return!0}let d=Object.keys(s),c=Object.keys(o);if(d.length!==c.length)return!1;let p=new Set(c);for(let l of d)if(!p.has(l)||!n(s[l],o[l]))return!1;return!0};return n(r,e)}function Po(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jt(r){let e="^";for(let t=0;t<r.length;t+=1){let n=r[t];if(n==="*"){e+=".*";continue}if(n==="?"){e+=".";continue}if(n==="["){let s=r.indexOf("]",t+1);if(s<=t+1){e+="\\[";continue}let o=r.slice(t+1,s);o.startsWith("!")&&(o=`^${o.slice(1)}`),o=o.replace(/\\/g,"\\\\"),e+=`[${o}]`,t=s;continue}e+=Po(n)}return e+="$",new RegExp(e)}var Lo={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"},Fo={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function vn(r){if(typeof r=="string")return JSON.stringify(r);if(typeof r=="number"||typeof r=="boolean"||r==null)return String(r);try{return JSON.stringify(r)}catch{return"[unserializable]"}}function $o(r){return r==="none"?Fo:r==="ansi"||r==null?Lo:{data:r.data??"",dirty:r.dirty??"",resolved:r.resolved??"",invalidate:r.invalidate??"",pause:r.pause??"",resume:r.resume??"",complete:r.complete??"",error:r.error??"",teardown:r.teardown??"",derived:r.derived??"",path:r.path??"",reset:r.reset??""}}function yr(r){if(r==null)return{};let e=r.detail;return e==="full"?{...r,structured:r.structured??!0,timeline:r.timeline??!0,causal:r.causal??!0,derived:r.derived??!0}:e==="minimal"?{...r,structured:r.structured??!0}:r.format==="stage-log"?{...r,structured:r.structured??!0,timeline:r.timeline??!0}:r}function Vo(r,e,t){for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);if(s<32||s===127)throw new Error(`Graph "${e}": ${t} "${r}" must not contain control character (U+${s.toString(16).padStart(4,"0").toUpperCase()} at index ${n})`)}}function Tn(r,e,t){if(r==="")throw new Error(`Graph "${e}": ${t} name must be non-empty`);if(r.includes(X))throw new Error(`Graph "${e}": ${t} "${r}" must not contain '${X}' (path separator)`);if(r===Re)throw new Error(`Graph "${e}": ${t} name "${Re}" is reserved for meta companion paths`);Vo(r,e,t)}function jo(r,e){if(r==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let t=r.split(X);for(let n of t)if(n==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return t}function zo(r,e){let t=!1;for(let s of r)if(!e.isMetaPassthrough(s[0])){t=!0;break}return t?r.filter(s=>e.isMetaPassthrough(s[0])):r}function Tr(r){for(let e of r._mounts.values())Tr(e);for(let e of r._nodes.values())try{e.down([[ue]],{internal:!0})}catch{}}var ce=class r{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_destroyed=!1;_topology;_topologyEmitters=new Set;_factory;_factoryArgs;constructor(e,t){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(X))throw new Error(`Graph name must not contain '${X}' (got "${e}")`);if(e===Re)throw new Error(`Graph name "${Re}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...t??{}}),this.config=t?.config??tt,this._traceRing=new yt(t?.traceCapacity??1e3),t?.versioning!=null&&this.setVersioning(t.versioning),typeof t?.factory=="string"&&(this._factory=t.factory,t.factoryArgs!==void 0&&(this._factoryArgs=t.factoryArgs))}tagFactory(e,t){return this._factory=e,this._factoryArgs=t,this}ancestors(e=!0){let t=[],n=e?this:this._parent;for(;n!=null;)t.push(n),n=n._parent;return t}get topology(){return this._topology==null&&(this._topology=de(e=>{let t=n=>{e.emit(n)};return this._topologyEmitters.add(t),()=>{this._topologyEmitters.delete(t)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let t of this._topologyEmitters)t(e)}nameOf(e){return this._nodeToName.get(e)}add(e,t){let n=e.name,s=t?.name??n;if(s==null||s==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let o=s,i=t?.annotation;if(Tn(o,this.name,"add"),this._mounts.has(o))throw new Error(`Graph "${this.name}": name "${o}" is already a mount point`);if(this._nodes.has(o))throw new Error(`Graph "${this.name}": node "${o}" already exists`);let a=this._nodeToName.get(e);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(o,e),this._nodeToName.set(e,o),this._emitTopology({kind:"added",name:o,nodeKind:"node"}),i!=null&&(this._annotations.set(o,i),this.config.inspectorEnabled&&this._traceRing.push({path:o,annotation:i,timestamp_ns:K()})),e}setVersioning(e){if(e!=null)for(let t of this._nodes.values())t instanceof re&&t._applyVersioning(e)}remove(e){Tn(e,this.name,"remove");let t=this._mounts.get(e);if(t){let o={kind:"mount",nodes:[],mounts:[]},i=[];t._collectObserveTargets("",i);for(let[a,u]of i)a.includes(`${X}${Re}${X}`)||o.nodes.push(a);return o.nodes.sort(),o.mounts.push(e),o.mounts.push(...t._collectSubgraphs(`${e}${X}`)),this._mounts.delete(e),t._parent=void 0,Tr(t),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:o}),o}let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(n),n.down([[ue]],{internal:!0});let s={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:s}),s}removeAll(e){let t=typeof e=="function"?e:(()=>{let o=jt(e);return i=>o.test(i)})(),n={kind:"mount",nodes:[],mounts:[]},s=[...this._nodes.keys(),...this._mounts.keys()].filter(o=>t(o));for(let o of s){let i=this.remove(o);n.nodes.push(...i.nodes),n.mounts.push(...i.mounts)}return n.nodes.sort(),n.mounts.sort(),n}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),t=this._nodes,n=0;return{[Symbol.iterator](){return this},next(){if(n>=e.length)return{value:void 0,done:!0};let s=e[n++];return{value:[s,t.get(s)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(X))return this.resolve(e);let t=this._nodes.get(e);if(!t)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return t}get(e){return this.node(e).cache}set(e,t,n){let s=n?.internal===!0;this.node(e).down([[C,t]],{actor:n?.actor,internal:s,delivery:"write"})}setAll(e,t){let n=Symbol.iterator in e?e:Object.entries(e);te(()=>{for(let[s,o]of n)this.set(s,o,t)})}invalidate(e,t){let n=t?.internal===!0;this.node(e).down([[xe]],{actor:t?.actor,internal:n,delivery:"write"})}error(e,t,n){let s=n?.internal===!0;this.node(e).down([[G,t]],{actor:n?.actor,internal:s,delivery:"write"})}complete(e,t){let n=t?.internal===!0;this.node(e).down([[j]],{actor:t?.actor,internal:n,delivery:"write"})}edges(e){let t=e?.recursive===!0,n=new Map;if(!t){for(let[u,d]of this._nodes)n.set(d,u);let a=[];for(let[u,d]of this._nodes)if(d instanceof re)for(let c of d._deps){let p=n.get(c.node);p!=null&&a.push([p,u])}return a.sort((u,d)=>u[0]<d[0]?-1:u[0]>d[0]?1:u[1]<d[1]?-1:u[1]>d[1]?1:0),a}let s=[];this._collectObserveTargets("",s);let o=new Map;for(let[a,u]of s)o.set(u,a);let i=[];for(let[a,u]of s)if(u instanceof re)for(let d of u._deps){let c=o.get(d.node);c!=null&&i.push([c,a])}return i.sort((a,u)=>a[0]<u[0]?-1:a[0]>u[0]?1:a[1]<u[1]?-1:a[1]>u[1]?1:0),i}mount(e,t){if(t===void 0){let s=new r(e);return this.mount(e,s)}if(typeof t=="function"){let s=new r(e);return t(s),this.mount(e,s)}let n=t;if(Tn(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(n===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(n._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${n._parent.name}"`);for(let s=this;s!=null;s=s._parent)if(s===n)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,n),n._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),n}resolve(e){let t=jo(e,this.name);return this._resolveFromSegments(t)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let t=e;if(t[0]===this.name&&(t=t.slice(1),t.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let n=t[0],s=t.slice(1);if(s.length===0){let a=this._nodes.get(n);if(a)return a;throw this._mounts.has(n)?new Error(`Graph "${this.name}": path ends at subgraph "${n}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${n}"`)}let o=this._nodes.get(n);if(o&&s.length>0&&s[0]===Re)return this._resolveMetaChainFromNode(o,s,t.join(X));let i=this._mounts.get(n);if(!i)throw this._nodes.has(n)?new Error(`Graph "${this.name}": "${n}" is a node; trailing path "${s.join(X)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${n}"`);return i.resolve(s.join(X))}_resolveMetaChainFromNode(e,t,n){let s=e,o=0,i=[...t];for(;o<i.length;){if(i[o]!==Re)throw new Error(`Graph "${this.name}": expected ${Re} segment in meta path "${n}"`);if(o+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${Re} in "${n}"`);let a=i[o+1],u=s.meta[a];if(!u)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${n}"`);s=u,o+=2}return s}signal(e,t){if(t?.internal!==!0){for(let s of e)if(this.config.messageTier(s[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let n=[];if(this._signalDeliver(e,t??{},new Set,n),n.length>0)throw n[0]}_signalDeliver(e,t,n,s){for(let u of this._mounts.values())u._signalDeliver(e,t,n,s);let i=t.internal===!0?{internal:!0}:{actor:t.actor,delivery:"signal"},a=zo(e,this.config);for(let u of[...this._nodes.keys()].sort()){let d=this._nodes.get(u);if(!n.has(d)){n.add(d);try{d.down(e,i)}catch(c){if(c instanceof Ee)throw c;s.push(c)}a.length!==0&&this._signalMetaSubtree(d,a,n,i,s)}}}_signalMetaSubtree(e,t,n,s,o){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!n.has(a)){n.add(a);try{a.down(t,s)}catch(u){if(u instanceof Ee)throw u;o.push(u)}this._signalMetaSubtree(a,t,n,s,o)}}}describe(e){if(e?.reactive==="diff")return this._describeReactiveDiff(e);if(e?.reactive===!0)return this._describeReactive(e);let t=Mo(e?.actor),n=e?.filter;if(e?.detail!=null&&e?.fields!=null)throw new TypeError("Graph.describe(): pass either `detail` or `fields`, not both. `detail: 'spec'` is the canonical spec projection; use `fields` only when you need a custom subset.");let s=cn(e?.detail,e?.fields),o=e?.detail==="spec",i=s,a=[];this._collectObserveTargets("",a);let u=new Map;for(let[_,w]of a)u.set(w,_);let d=[];{let _=a.map(([,b])=>b),w=new Set(u.values()),R=0;for(;_.length>0;){let b=_.shift();if(b instanceof re)for(let x of b._deps){let O=x.node;if(u.has(O))continue;let S=O.name??"",N=S;if(!N||w.has(N))if(S){let P=2;for(;w.has(`${S}#${P}`);)P++;N=`${S}#${P}`}else for(N=`__internal__/${R++}`;w.has(N);)N=`__internal__/${R++}`;u.set(O,N),w.add(N),d.push([N,O]),_.push(O)}}}let c=[...a,...d],p={};for(let[_,w]of c){if(t!=null&&!w.allowsObserve(t))continue;let R=ln(w,i,o),b=w instanceof re?w._deps.map(N=>u.get(N.node)??N.node.name??""):[],{name:x,...O}=R,S={...O,deps:b};if(!o){let N=this._annotations.get(_);N!=null&&(S.annotation=N)}if(n!=null)if(typeof n=="function"){let N=n;if(!(N.length>=2?N(_,S):N(S)))continue}else{let N=!0;for(let[P,B]of Object.entries(n)){let z=P==="deps_includes"?"depsIncludes":P==="meta_has"?"metaHas":P;if(z==="depsIncludes"){if(!S.deps.includes(String(B))){N=!1;break}continue}if(z==="metaHas"){if(!Object.hasOwn(S.meta??{},String(B))){N=!1;break}continue}if(S[z]!==B){N=!1;break}}if(!N)continue}p[_]=S}let l=new Set(Object.keys(p)),h=[];for(let[_,w]of c)if(w instanceof re)for(let R of w._deps){let b=u.get(R.node);b!=null&&h.push([b,_])}h.sort((_,w)=>_[0]<w[0]?-1:_[0]>w[0]?1:_[1]<w[1]?-1:_[1]>w[1]?1:0);let f=h.map(([_,w])=>({from:_,to:w}));(t!=null||n!=null)&&(f=f.filter(_=>l.has(_.from)&&l.has(_.to)));let g=this._collectSubgraphs(""),m=t!=null||n!=null?g.filter(_=>{let w=`${_}${X}`;return[...l].some(R=>R===_||R.startsWith(w))}):g,T=this,y=e;return{name:this.name,nodes:p,edges:f,subgraphs:m,...this._factory!==void 0?{factory:this._factory}:{},...this._factoryArgs!==void 0?{factoryArgs:this._factoryArgs}:{},expand(_){let w={...y};return Array.isArray(_)?(w.fields=_,w.detail=void 0):(w.detail=_,w.fields=void 0),T.describe(w)}}}_collectSubgraphs(e){let t=[];for(let n of[...this._mounts.keys()].sort()){let s=e===""?n:`${e}${n}`;t.push(s),t.push(...this._mounts.get(n)._collectSubgraphs(`${s}${X}`))}return t}resourceProfile(e){return Vt(this,e)}reachable(e,t,n={}){return n.withDetail===!0?_n(this.describe(),e,t,{...n,withDetail:!0}):_n(this.describe(),e,t,n)}explain(e,t,n){return n?.reactive===!0?this._explainReactive(e,t,n):this._explainStatic(je(e),je(t),{...n?.maxDepth!==void 0?{maxDepth:mr(n.maxDepth)}:{},...n?.findCycle!==void 0?{findCycle:gr(n.findCycle)}:{}})}_explainStatic(e,t,n){let s=this.describe({detail:"full"}),o=new Map(this._annotations),i=new Map;for(let[a,u]of Object.entries(s.nodes))u.lastMutation!=null&&i.set(a,u.lastMutation);return dr(s,e,t,{...n?.maxDepth!=null?{maxDepth:n.maxDepth}:{},...n?.findCycle===!0?{findCycle:!0}:{},annotations:o,lastMutations:i})}_describeReactive(e){let t={...e,reactive:!1},n=e.reactiveName??"describe",s=0,o=L(s,{name:`${n}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,d=()=>{a||u||(a=!0,Ze(()=>{a=!1,!u&&(s+=1,o.emit(s))}))},c=i.onEvent(y=>{let v=y.type;v!=="data"&&v!=="error"&&v!=="complete"&&v!=="teardown"||d()}),p=[],l=new WeakSet,h=y=>{if(l.has(y)||u)return;l.add(y);let v=y.topology.subscribe(_=>{for(let w of _){if(w[0]!==C)continue;let R=w[1];if(d(),R.kind==="added"&&R.nodeKind==="mount"){let b=y._mounts.get(R.name);b!=null&&h(b)}}});p.push(v);for(let _ of y._mounts.keys()){let w=y._mounts.get(_);w!=null&&h(w)}};h(this);let f,g=e.actor;vr(g)&&(f=g.subscribe(y=>{let v=!1,_=!1;for(let w of y){let R=w[0];R===C?v=!0:(R===j||R===G||R===ue)&&(_=!0)}v&&d(),_&&(f?.(),f=void 0,d())}));let m;try{m=I([o],()=>this.describe(t),{name:n,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(y,v)=>y===v})}catch(y){c(),f?.();for(let v of p)v();throw i.dispose(),y}let T=ye(m);return{node:m,dispose(){u=!0,c(),f?.();for(let y of p)y();p.length=0,i.dispose(),T()}}}_describeReactiveDiff(e){let t={...e,reactive:!1},n=e.reactiveName??"describe-diff",s={name:this.name,nodes:{},edges:[],subgraphs:[]},o=this.describe(t),i=yn(s,o),a=L(i,{name:n,meta:{domain:"audit",kind:"describe-diff"},equals:(l,h)=>l===h}),u=this._describeReactive({...e,reactiveName:void 0}),d=!1,c=u.node.subscribe(l=>{if(!d)for(let h of l){if(h[0]!==C)continue;let f=h[1],g=yn(o,f);o=f,g.events.length!==0&&a.emit(g)}}),p=ye(a);return{node:a,dispose(){d=!0,c(),u.dispose(),a.down([[ue,"describe-diff disposed"]]),p()}}}_explainReactive(e,t,n){let s=0,o=L(s,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,d=()=>{a||u||(a=!0,Ze(()=>{a=!1,!u&&(s+=1,o.emit(s))}))},c=i.onEvent(y=>{let v=y.type;v!=="data"&&v!=="error"&&v!=="complete"&&v!=="teardown"||d()}),p=[];e!=null&&Je(e)&&p.push(e),t!=null&&Je(t)&&p.push(t),n?.maxDepth!=null&&Je(n.maxDepth)&&p.push(n.maxDepth),n?.findCycle!=null&&Je(n.findCycle)&&p.push(n.findCycle);let l=()=>{for(let y of p)if(y.cache===void 0)return!1;return!0},h=()=>{let y=je(e),v=je(t);return{from:y,to:v,found:!1,reason:"pending",steps:[],text:"(awaiting reactive args)",toJSON:()=>({from:y,to:v,found:!1,reason:"pending",steps:[]})}},f;try{f=I([o],()=>{if(!l())return h();let y=je(e),v=je(t),_={...n?.maxDepth!==void 0?{maxDepth:mr(n.maxDepth)}:{},...n?.findCycle!==void 0?{findCycle:gr(n.findCycle)}:{}};return this._explainStatic(y,v,_)},{name:n?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:je(e),to:je(t)},equals:(y,v)=>y.found===v.found&&y.reason===v.reason&&y.steps.length===v.steps.length&&Bo(y.steps,v.steps)})}catch(y){throw c(),i.dispose(),y}let g=ye(f),m=[],T=y=>{let v;return v=y.subscribe(_=>{let w=!1,R=!1;for(let b of _){let x=b[0];x===C?w=!0:(x===j||x===G||x===ue)&&(R=!0)}(w||R)&&d(),R&&v&&(v(),v=void 0)}),()=>{v&&(v(),v=void 0)}};for(let y of p)m.push(T(y));return{node:f,dispose(){u=!0,c();for(let y of m)y?.();m.length=0,i.dispose(),g()}}}_pathsMatching(e){let t=jt(e),n=[];return this._collectObserveTargets("",n),n.map(([s])=>s).filter(s=>t.test(s))}_collectObserveTargets(e,t){for(let n of[...this._mounts.keys()].sort()){let s=e===""?n:`${e}${X}${n}`;this._mounts.get(n)._collectObserveTargets(s,t)}for(let n of[...this._nodes.keys()].sort()){let s=this._nodes.get(n),o=e===""?n:`${e}${X}${n}`;t.push([o,s]),this._appendMetaObserveTargets(o,s,t)}}_appendMetaObserveTargets(e,t,n){for(let s of Object.keys(t.meta).sort()){let o=t.meta[s],i=`${e}${X}${Re}${X}${s}`;n.push([i,o]),this._appendMetaObserveTargets(i,o,n)}}observe(e,t){let n=typeof e=="string",o=yr(n?t:e);if(o.reactive===!0)return this._observeReactive(n?e:void 0,o);let i=o.structured===!0||o.timeline===!0||o.causal===!0||o.derived===!0||o.detail==="minimal"||o.detail==="full"||o.format!=null,a=o.actor;if(n){let c=e,p=this.resolve(c);if(a!=null&&!p.allowsObserve(a))throw new Ee({actor:a,action:"observe",nodeName:c});return i?this._buildStructuredObserver([[c,p]],o,"one"):{subscribe(l){return p.subscribe(l)},up(l){try{p.up?.(l)}catch(h){if(h instanceof Ee)return;throw h}}}}let u=[];this._collectObserveTargets("",u),u.sort((c,p)=>c[0]<p[0]?-1:c[0]>p[0]?1:0);let d=a==null?u:u.filter(([,c])=>c.allowsObserve(a));return i?this._buildStructuredObserver(d,o,"all"):{subscribe:c=>{let p=d.map(([l,h])=>h.subscribe(f=>{c(l,f)}));return()=>{for(let l of p)l()}},up:(c,p)=>{try{this.resolve(c).up?.(p)}catch(l){if(l instanceof Ee)return;throw l}}}}_observeReactive(e,t){let n=t.tiers,s=n!=null?new Set(n):null,o=t.reactiveName??"observe";return de(i=>{let a=[],u=!1,d=!1,c=()=>{if(a.length===0||d)return;let g={events:a.slice(),flushedAt_ns:K()};a.length=0,i.emit(g)},p={...t,reactive:!1,structured:!0,timeline:!0},l=e!=null?this.observe(e,p):this.observe(p),h=g=>{d||(a.push(g),!u&&(u=!0,Ze(()=>{u=!1,c()})))};for(let g of l.events)h(g);let f=l.onEvent(h);return()=>{d=!0,f(),l.dispose()}},{name:o,meta:{domain:"audit",kind:"observe-reactive"}})}_buildStructuredObserver(e,t,n){let s=n==="one"?e[0]?.[0]:void 0,o=i=>{if(n==="one"&&s!=null){let c=this.resolve(s);return this._buildStructuredObserver([[s,c]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((c,p)=>c[0]<p[0]?-1:c[0]>p[0]?1:0);let u=i.actor,d=u==null?a:a.filter(([,c])=>c.allowsObserve(u));return this._buildStructuredObserver(d,i,"all")};return this._createObserveResult(e,t,o)}_createObserveResult(e,t,n){let s=t.timeline===!0,o=t.causal===!0,i=t.derived===!0,a=t.detail==="minimal",u=this.config.inspectorEnabled,d=(o||i)&&u,c=t.maxEvents,p=c!=null&&c>0?new yt(c):null,l=[],h=new Set,f=t.tiers!=null?new Set(t.tiers):null,g={},m=new Set,T=0,y=0,v=0,_=0,w=0,R=0,b=!1,x=!1,O=0,S=new Map,N=new Map,P=new Map,B=A=>{if(!(f!=null&&!f.has(A.type))){p?p.push(A):l.push(A);for(let U of h)U(A)}},z=A=>f==null||f.has(A),le=()=>s?{timestamp_ns:K(),in_batch:ft(),batch_id:O}:{},ae=(A,U)=>{if(!(!d||!(A instanceof re)))return A._setInspectorHook(pe=>{if(pe.kind==="dep_message")S.set(A,pe.depIndex);else if(pe.kind==="run"){let Se=pe.batchData.map((E,M)=>E!=null&&E.length>0?E.at(-1):pe.prevData[M]);N.set(A,Se);let he=pe.batchData.map(E=>E!=null?[...E]:void 0);P.set(A,he),i&&B({type:"derived",path:U,dep_values:Se,dep_batches:he,...le()})}})},Oe=A=>{let U=S.get(A),pe=N.get(A);if(!o||pe==null)return{};let he=(U!=null&&U>=0&&A instanceof re?A._deps[U]:void 0)?.node,E=he?.v,M=P.get(A);return{trigger_dep_index:U,trigger_dep_name:he?.name,...E!=null?{trigger_version:{id:E.id,version:E.version}}:{},dep_values:[...pe],...M!=null?{dep_batches:M}:{}}},Ce=[],$=[];for(let[A,U]of e){let pe=ae(U,A);pe&&Ce.push(pe),$.push(U.subscribe(Se=>{O++;for(let he of Se){let E=he[0],M=le();if(E===C){g[A]=he[1];let J=U instanceof re?U.lastMutation?.actor??Ye:Ye;B({type:"data",path:A,data:he[1],actor:J,...M,...Oe(U)})}else if(a)E===ee?z("dirty")&&T++:E===Q?z("resolved")&&y++:E===xe?z("invalidate")&&v++:E===Ae?z("pause")&&_++:E===Le?z("resume")&&w++:E===ue?z("teardown")&&R++:E===j&&!m.has(A)?z("complete")&&(b=!0):E===G&&z("error")&&(x=!0,m.add(A));else if(E===ee)z("dirty")&&T++,B({type:"dirty",path:A,...M});else if(E===Q)z("resolved")&&y++,B({type:"resolved",path:A,...M,...Oe(U)});else if(E===xe)z("invalidate")&&v++,B({type:"invalidate",path:A,...M});else if(E===Ae)z("pause")&&_++,B({type:"pause",path:A,lockId:he[1],...M});else if(E===Le)z("resume")&&w++,B({type:"resume",path:A,lockId:he[1],...M});else if(E===j)z("complete")&&!m.has(A)&&(b=!0),B({type:"complete",path:A,...M});else if(E===G){z("error")&&(x=!0,m.add(A));let J=U instanceof re?U.lastMutation?.actor??Ye:Ye;B({type:"error",path:A,data:he[1],actor:J,...M})}else E===ue&&(z("teardown")&&R++,B({type:"teardown",path:A,...M}))}}))}let V=!1,F=()=>{if(!V){V=!0;for(let A of $)A();for(let A of Ce)A();for(let A of Z)A({value:void 0,done:!0});Z.length=0}},ie=[],Z=[];h.add(A=>{let U=Z.shift();U?U({value:A,done:!1}):ie.push(A)});let fe={get values(){return g},get dirtyCount(){return T},get resolvedCount(){return y},get invalidateCount(){return v},get pauseCount(){return _},get resumeCount(){return w},get teardownCount(){return R},get events(){return p?p.toArray():[...l]},get anyCompletedCleanly(){return b},get anyErrored(){return x},get completedWithoutErrors(){return b&&!x},onEvent(A){return h.add(A),()=>h.delete(A)},dispose:F,expand(A){F();let U={...t};return typeof A=="string"?U.detail=A:Object.assign(U,A),n(yr(U))},[Symbol.asyncIterator](){return{next(){return ie.length>0?Promise.resolve({value:ie.shift(),done:!1}):V?Promise.resolve({value:void 0,done:!0}):new Promise(A=>Z.push(A))},return(){return F(),Promise.resolve({value:void 0,done:!0})}}}};return t.format!=null&&this._attachFormatLogger(fe,t),fe}_attachFormatLogger(e,t){let n=t.format;if(n==null)return;let s=t.logger??(f=>console.log(f)),o=t.includeTypes?new Set(t.includeTypes):null,i=t.excludeTypes?new Set(t.excludeTypes):null,a=o==null&&i==null?()=>!0:f=>(o==null||o.has(f))&&(i==null||!i.has(f)),u=$o(t.theme),d=n==="stage-log"?K():0,c=f=>f==null?"":t.stageLabels?.[f]??f,p=(f,g)=>f.length>g?`${f.slice(0,g-1)}\u2026`:f,l=f=>f.type==="data"||f.type==="error"?p(vn(f.data),120):"",h=f=>{if(n==="stage-log"){let b=(K()-d)/1e9,x=c(f.path).padEnd(9);if(f.type==="data"){let O=l(f);return`[${b.toFixed(3)}s] ${x} \u2190${O?` ${O}`:""}`}if(f.type==="error"){let O=l(f);return`[${b.toFixed(3)}s] ${x} \u2717${O?` ${O}`:""}`}return f.type==="complete"?`[${b.toFixed(3)}s] ${x} \u25A0 complete`:`[${b.toFixed(3)}s] ${x} ${f.type}`}if(n==="json")try{return JSON.stringify(f)}catch{return JSON.stringify({type:f.type,path:f.path,data:"[unserializable]"})}let g=u[f.type]??"",m=f.path?`${u.path}${f.path}${u.reset} `:"",T=f.type==="data"||f.type==="error",y=f.type==="pause"||f.type==="resume",v=T?` ${vn(f.data)}`:y?` ${vn(f.lockId)}`:"",_=f.type==="data"||f.type==="resolved"||f.type==="derived"?f:void 0,w=_?.trigger_dep_name!=null?` <- ${_.trigger_dep_name}`:_?.trigger_dep_index!=null?` <- #${_.trigger_dep_index}`:"",R=f.in_batch?" [batch]":"";return`${m}${g}${f.type.toUpperCase()}${u.reset}${v}${w}${R}`};e.onEvent(f=>{a(f.type)&&s(h(f),f)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){hr(this._disposers,this.name),this.signal([[ue]],{internal:!0}),hr(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}get destroyed(){return this._destroyed}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}snapshot(e){let{expand:t,...n}=this.describe({detail:"full"}),s={};for(let a of Object.keys(n.nodes).sort()){let{lastMutation:u,guard:d,...c}=n.nodes[a];s[a]=c}let o=[...n.subgraphs].sort(),i={...n,version:1,nodes:s,subgraphs:o};if(e?.format==null)return i;if(e.format==="json-string")return JSON.stringify(i);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(e.codec);if(a==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return Vn(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,t){let n=t?.config??tt,{codec:s,codecVersion:o,payload:i}=jn(e,n);return s.decode(i,o)}restore(e,t){if(br(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let n=t?.only==null?null:(Array.isArray(t.only)?t.only:[t.only]).map(o=>jt(o)),s=t?.includeProducers===!0;for(let o of Object.keys(e.nodes).sort()){if(n!==null&&!n.some(a=>a.test(o)))continue;let i=e.nodes[o];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&t?.onError?.(o,new Error(`restore: slice.value is undefined for "${o}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!s)){if(i.v!=null){let u=this.tryResolve(o)?.v;if(u!=null&&u.id===i.v.id&&u.version===i.v.version)continue}try{this.set(o,i.value)}catch(a){t?.onError?.(o,a)}}}}}static fromSnapshot(e,t){br(e);let n=typeof t=="function"?t:t?.build,s=typeof t=="function"?void 0:t?.factories,o=new r(e.name);if(n)return n(o),o.restore(e),o;for(let h of[...e.subgraphs].sort((f,g)=>{let m=f.split(X).length,T=g.split(X).length;return m!==T?m-T:f<g?-1:f>g?1:0})){let f=h.split(X),g=o;for(let m of f)g._mounts.has(m)||g.mount(m,new r(m)),g=g._mounts.get(m)}let i=s?Object.entries(s).map(([h,f])=>({re:jt(h),factory:f})):[],a=h=>{for(let f of i)if(f.re.test(h))return f.factory},u=h=>{let f=h.split(X),g=f.pop();if(g==null||g.length===0)throw new Error(`invalid snapshot path "${h}"`);let m=o;for(let T of f){let y=m._mounts.get(T);if(!y)throw new Error(`unknown mount "${T}" in path "${h}"`);m=y}return[m,g]},d=Object.entries(e.nodes).filter(([h])=>!h.includes(`${X}${Re}${X}`)).sort((h,f)=>h[0]<f[0]?-1:h[0]>f[0]?1:0),c=new Map(d),p=new Map,l=!0;for(;c.size>0&&l;){l=!1;for(let[h,f]of[...c.entries()]){let g=f?.deps??[];if(!g.every(w=>p.has(w)))continue;let[m,T]=u(h),y={...f?.meta??{}},v=a(h),_;if(f?.type==="state")_=L(f.value,{meta:y});else{if(v==null)continue;_=v(T,{path:h,type:f.type,value:f.value,meta:y,deps:g,resolvedDeps:g.map(w=>p.get(w))})}m.add(_,{name:T}),p.set(h,_),c.delete(h),l=!0}}if(c.size>0){let h=[...c.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${h}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return o.restore(e),o}toJSON(){return this.snapshot()}attachSnapshotStorage(e,t={}){let n=e.map(d=>({tier:d,debounceMs:Math.max(0,d.debounceMs??0),compactEvery:Math.max(1,d.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));t.autoRestore===!0&&this._cascadeRestore(e,t.onError);let s=(d,c)=>{if(d.disposed)return;let p=Io(c.nodes);if(d.lastSnapshot!=null&&p!==""&&p===d.lastFingerprint)return;let l=d.seq+1,h=ve(),m=d.lastSnapshot==null||l%d.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:l,timestamp_ns:h,format_version:We}:{name:this.name,mode:"diff",diff:_r(d.lastSnapshot,c),seq:l,timestamp_ns:h,format_version:We};if(d.tier.filter&&!d.tier.filter(m))return;let T;try{T=d.tier.save(m)}catch(y){t.onError?.(y,d.tier);return}if(T&&typeof T.then=="function"){let _=(d.savePending??Promise.resolve()).then(()=>T,()=>T).then(()=>{d.disposed||(d.seq=l,d.lastSnapshot=c,d.lastFingerprint=p)},w=>{t.onError?.(w,d.tier)});d.savePending=_.finally(()=>{d.savePending===_&&(d.savePending=void 0)})}else d.seq=l,d.lastSnapshot=c,d.lastFingerprint=p},o=(d,c)=>{try{s(d,c)}catch(p){t.onError?.(p,d.tier)}},i=(d,c)=>{if(!c.some(f=>{let g=this.config.messageTier(f[0]);return g>=3&&g<5}))return;if(t.filter){let f=this.tryResolve(d);if(f==null)return;let g=ln(f,cn("standard"));if(!t.filter(d,g))return}let l,h=()=>(l==null&&(l=this.snapshot()),l);for(let f of n)f.disposed||(f.debounceMs===0?o(f,h()):(f.timer==null&&(f.timer=new Pt),f.timer.start(f.debounceMs,()=>{f.disposed||o(f,this.snapshot())})))},a;if(t.paths!=null){let c=(typeof t.paths=="string"?this._pathsMatching(t.paths):t.paths).map(p=>{let l=this.tryResolve(p);return l==null?()=>{}:l.subscribe(h=>i(p,h))});a=()=>{for(let p of c)p()}}else a=this.observe().subscribe((d,c)=>i(d,c));let u=()=>{a();for(let d of n)d.disposed=!0,d.timer?.cancel();this._storageDisposers.delete(u)};return this._storageDisposers.add(u),{dispose:u}}async _cascadeRestore(e,t){for(let n of e){let s;try{s=await n.load?.()}catch(i){t?.(i,n);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let o=s;try{if(o.mode==="full"&&o.snapshot!=null)return this.restore(o.snapshot),!0;if(o.version===We&&o.nodes!=null)return this.restore(o),!0}catch(i){t?.(i,n)}}return!1}static async fromStorage(e,t,n){for(let s of t){let o;try{o=await s.load?.()}catch(u){n?.onError?.(u,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 r.fromSnapshot(a,n)}catch(u){n?.onError?.(u,s)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${t.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,t,n){if(e!=null&&t!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,t),this.config.inspectorEnabled){let s={path:e,annotation:t,timestamp_ns:K(),...n?.actor!=null?{actor:n.actor}:{}};this._traceRing.push(s)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let t=this._traceRing.toArray().filter(s=>!e(s)),n=this._traceRing.size-t.length;this._traceRing.clear();for(let s of t)this._traceRing.push(s);return n}static diff(e,t){let n=new Set(Object.keys(e.nodes)),s=new Set(Object.keys(t.nodes)),o=[...s].filter(y=>!n.has(y)).sort(),i=[...n].filter(y=>!s.has(y)).sort(),a=[],u=[];for(let y of n){if(!s.has(y))continue;let v=e.nodes[y],_=t.nodes[y],w=v.v,R=_.v;w!=null&&R!=null&&w.id===R.id&&w.version!==R.version&&u.push({path:y,id:w.id,from:w.version,to:R.version});let b=w!=null&&R!=null&&w.id===R.id&&w.version===R.version;for(let x of["type","status","sentinel"]){let O=v[x],S=_[x];O!==S&&a.push({path:y,field:x,from:O,to:S})}if(!b)for(let x of["value","meta"]){let O=v[x],S=_[x];Go(O,S)||a.push({path:y,field:x,from:O,to:S})}}let d=y=>`${y.from} ${y.to}`,c=new Set(e.edges.map(d)),p=new Set(t.edges.map(d)),l=t.edges.filter(y=>!c.has(d(y))),h=e.edges.filter(y=>!p.has(d(y))),f=new Set(e.subgraphs),g=new Set(t.subgraphs),m=[...g].filter(y=>!f.has(y)).sort(),T=[...f].filter(y=>!g.has(y)).sort();return{nodesAdded:o,nodesRemoved:i,nodesChanged:a,versionChanges:u,edgesAdded:l,edgesRemoved:h,subgraphsAdded:m,subgraphsRemoved:T}}};function _r(r,e){let t=ce.diff(r,e),n={};for(let s of t.nodesAdded){let o=e.nodes[s];o!=null&&(n[s]=o)}return{...t,nodesAddedFull:n}}function _n(r,e,t,n={}){let s={paths:[],depths:new Map,truncated:!1};if(!e)return n.withDetail?s:[];if(!n.both&&t!=="upstream"&&t!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let o=n.maxDepth;if(o!=null&&(!Number.isInteger(o)||o<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(o===0)return n.withDetail?s:[];let i=new Map,a=new Map,u=new Map,d=new Map,c=new Set;for(let[v,_]of Object.entries(r.nodes)){if(!v)continue;c.add(v);let w=_.deps??[];i.set(v,w);for(let R of w)R&&(c.add(R),a.has(R)||a.set(R,new Set),a.get(R).add(v))}for(let v of r.edges){if(v==null||typeof v!="object")continue;let _=typeof v.from=="string"?v.from:"",w=typeof v.to=="string"?v.to:"";!_||!w||(c.add(_),c.add(w),d.has(_)||d.set(_,new Set),d.get(_).add(w),u.has(w)||u.set(w,new Set),u.get(w).add(_))}if(!c.has(e))return n.withDetail?s:[];let p=n.both===!0,l=v=>{if(p){let b=i.get(v)??[],x=u.get(v),O=a.get(v),S=d.get(v),N=[...b];return x&&N.push(...x),O&&N.push(...O),S&&N.push(...S),N}if(t==="upstream"){let b=i.get(v)??[],x=u.get(v);return x?[...b,...x]:b}let _=a.get(v),w=d.get(v),R=_?[..._]:[];return w&&R.push(...w),R},h=new Set([e]),f=new Map,g=[{path:e,depth:0}],m=0,T=!1;for(;m<g.length;){let v=g[m++];if(o!=null&&v.depth>=o){l(v.path).length>0&&(T=!0);continue}for(let _ of l(v.path))!_||h.has(_)||(h.add(_),f.set(_,v.depth+1),g.push({path:_,depth:v.depth+1}))}let y=[...f.keys()].sort((v,_)=>v<_?-1:v>_?1:0);return n.withDetail?{paths:y,depths:f,truncated:T}:y}function Bo(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],s=e[t];if(n.path!==s.path||n.type!==s.type||n.status!==s.status||n.hop!==s.hop||n.dep_index!==s.dep_index||n.annotation!==s.annotation||n.value!==s.value||n.lastMutation!==s.lastMutation)return!1;let o=n.v,i=s.v;if(o!==i&&(o==null||i==null||o.id!==i.id||o.version!==i.version))return!1}return!0}At();Ie();et();ge();oe();De();vt();Ie();ge();De();oe();var wn=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=t,t!==void 0){if(this._buf=new Array(t),e&&e.length>0){let n=Math.min(e.length,t),s=e.length-n;for(let o=0;o<n;o++)this._buf[o]=e[s+o];this._size=n}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let t=e>=0?e:this._size+e;if(!(t<0||t>=this._size))return this._maxSize!==void 0?this._buf[(this._head+t)%this._maxSize]:this._buf[t]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let t=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let n=t;n<e.length;n++)this._rawAppend(e[n]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let t=0;t<e;t++)this._buf[(this._head+t)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let t=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,t);else{for(let n=0;n<t;n++)this._buf[(this._head+n)%this._maxSize]=void 0;this._head=(this._head+t)%this._maxSize}return this._size-=t,this._version+=1,t}slice(e,t){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${t})`);let n=t===void 0?this._size:Math.min(Math.max(t,0),this._size),s=Math.min(e,this._size);if(s>=n)return[];let o=n-s;if(this._maxSize===void 0)return this._buf.slice(s,n);let i=new Array(o);for(let a=0;a<o;a++)i[a]=this._buf[(this._head+s+a)%this._maxSize];return i}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let t=Math.min(e,this._size);return this.slice(this._size-t,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let t=0;t<this._size;t++)e[t]=this._buf[(this._head+t)%this._maxSize];return e}snapshot(){return this.toArray()}restore(e){if(this._maxSize===void 0){this._buf.length=0;for(let t=0;t<e.length;t++)this._buf.push(e[t]);this._size=this._buf.length}else{let t=this._maxSize;for(let o=0;o<t;o++)this._buf[o]=void 0;this._head=0;let n=Math.min(e.length,t),s=e.length-n;for(let o=0;o<n;o++)this._buf[o]=e[s+o];this._size=n}this._version+=1}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function Tt(r){return r.subscribe(()=>{})}var qo=64;function zt(r,e={}){let{name:t,maxSize:n,versioning:s,guard:o,backend:i}=e,a=i??new wn(r,n),u=L(a.toArray(),{name:t,describeKind:"state",equals:(b,x)=>b===x,...s!=null?{versioning:s}:{},...o!=null?{guard:o}:{}});function d(){let b=a.toArray();te(()=>{u.down([[ee]],{internal:!0}),u.down([[C,b]],{internal:!0})})}let c=new Map,p=new Map,l=new Map;function h(b,x){return`${b}:${x===void 0?"END":x}`}function f(b){if(b.size<qo)return;let x=b.keys().next();if(x.done)return;let O=b.get(x.value);O!==void 0&&O.dispose(),b.delete(x.value)}function g(b){let x=a.version;try{return b()}finally{a.version!==x&&d()}}function m(b){if(!Number.isInteger(b)||b<0)throw new RangeError(`tail: n must be a non-negative integer (got ${b})`);let x=c.get(b);if(x!==void 0)return c.delete(b),c.set(b,x),x.node;f(c);let O=I([u],([N])=>{let P=N;return b===0||P.length===0?[]:P.slice(Math.max(0,P.length-b))},{initial:a.tail(b),describeKind:"derived"}),S=Tt(O);return c.set(b,{node:O,dispose:S}),O}function T(b,x){if(!Number.isInteger(b)||b<0)throw new RangeError(`slice: start must be a non-negative integer (got ${b})`);if(x!==void 0&&(!Number.isInteger(x)||x<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${x})`);let O=h(b,x),S=p.get(O);if(S!==void 0)return p.delete(O),p.set(O,S),S.node;f(p);let N=I([u],([B])=>{let z=B;return x===void 0?z.slice(b):z.slice(b,x)},{initial:a.slice(b,x),describeKind:"derived"}),P=Tt(N);return p.set(O,{node:N,dispose:P}),N}function y(b){let x=l.get(b);if(x!==void 0)return x.node;let O=I([u,b],([N,P])=>{let B=N,z=Math.max(0,Math.trunc(P??0));return B.slice(z)},{initial:[],describeKind:"derived"}),S=Tt(O);return l.set(b,{node:O,dispose:S}),O}let v,_;function w(){v===void 0&&(v=ne([u],(b,x,O)=>{let S=b[0],P=S!=null&&S.length>0?S.at(-1):O.prevData[0];if(P==null||P.length===0){x.down([[Q]]);return}x.emit(P[P.length-1])},{name:t!=null?`${t}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),_=I([u],([b])=>b.length>0,{name:t!=null?`${t}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),Tt(v),Tt(_))}let R={entries:u,get size(){return a.size},at(b){return a.at(b)},append(b){g(()=>a.append(b))},appendMany(b){b.length!==0&&g(()=>a.appendMany(b))},clear(){g(()=>a.clear())},trimHead(b){g(()=>a.trimHead(b))},withLatest(){return w(),u},get lastValue(){return w(),v},get hasLatest(){return w(),_},view(b){switch(b.kind){case"tail":return m(b.n);case"slice":return T(b.start,b.stop);case"fromCursor":return y(b.cursor)}},attach(b){let x=b.subscribe(O=>{for(let S of O)S[0]===C&&R.append(S[1])});return()=>x()},attachStorage(b){if(b.length===0)return()=>{};let x=new Map;for(let S of b)x.set(S,a.size);(async()=>{for(let S of b)if(typeof S.loadEntries=="function")try{let N=await Promise.resolve(S.loadEntries());N.entries.length>0&&a.size===0&&(a.restore(N.entries),x.set(S,N.entries.length),d());break}catch{}})();let O=u.subscribe(S=>{for(let N of S){if(N[0]!==C)continue;let P=N[1];for(let B of b){let z=x.get(B)??0;if(P.length<z){try{let ae=B.appendEntries(P);ae instanceof Promise&&ae.catch(()=>{})}catch{}x.set(B,P.length);continue}if(P.length===z)continue;let le=P.slice(z);x.set(B,P.length);try{let ae=B.appendEntries(le);ae instanceof Promise&&ae.catch(()=>{})}catch{}}}});return()=>O()},disposeAllViews(){for(let b of c.values())b.dispose();c.clear();for(let b of p.values())b.dispose();p.clear();for(let b of l.values())b.dispose();l.clear()},dispose(){for(let b of c.values())b.dispose();c.clear();for(let b of p.values())b.dispose();p.clear();for(let b of l.values())b.dispose();l.clear()}};return R}$e();var Ho=256;function at(r,e){if(!Number.isFinite(r)||!Number.isInteger(r)||r<0)throw new Error(`${e} must be a non-negative integer`);return r}function Be(r,e){return ze("messaging",r,e)}var Uo=1024,xn=class extends ce{_log;events;latest;hasLatest;constructor(e,t={}){super(e,t.graph),this._log=zt([],{name:"events",maxSize:t.retainedLimit??Uo}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=I([this.events],([n])=>{let s=n;return s.length===0?null:s[s.length-1]},{name:"latest",describeKind:"derived",meta:Be("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(ye(this.latest)),this.hasLatest=I([this.events],([n])=>n.length>0,{name:"hasLatest",describeKind:"derived",meta:Be("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(ye(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}},Bt=class extends ce{cursor;available;topic;_disposed=!1;constructor(e,t,n={}){super(e,n.graph),this.topic=t;let s;if(n.from!==void 0?n.from==="retained"?s=0:n.from==="now"?s=t.events.cache.length:s=at(n.from,"subscription from"):s=at(n.cursor??0,"subscription cursor"),this.cursor=L(s,{name:"cursor",describeKind:"state",meta:Be("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=t._logBundle.view({kind:"fromCursor",cursor:this.cursor}),this.add(this.available,{name:"available"}),this.addDisposer(ye(this.available)),n.advanceOn!==void 0){let o=n.advanceOn,i=!1,a=ne([o],()=>{if(!i){i=!0;return}if(this._disposed)return;let u=this.available.cache;if(u.length===0)return;let d=this.cursor.cache+u.length;this.cursor.emit(d)},{name:"advancePump",describeKind:"effect",meta:Be("subscription_advance_pump")});this.add(a,{name:"advancePump"}),this.addDisposer(ye(a))}}ack(e){if(this._disposed)return this.cursor.cache;let t=this.available.cache,n=e===void 0?t.length:at(e,"subscription ack count"),s=Math.min(n,t.length);if(s<=0)return this.cursor.cache;let o=this.cursor.cache+s;return this.cursor.emit(o),o}pull(e){if(this._disposed)return[];let t=this.available.cache,n=e===void 0?t.length:at(e,"subscription pull limit");return t.slice(0,n)}pullAndAck(e){if(this._disposed)return{items:[],cursor:this.cursor.cache};let t=this.available.cache,n=e===void 0?t.length:at(e,"subscription pullAndAck limit"),s=t.slice(0,n);if(s.length===0)return{items:s,cursor:this.cursor.cache};let o=this.cursor.cache+s.length;return this.cursor.emit(o),{items:s,cursor:o}}dispose(){this._disposed||(this._disposed=!0,this.cursor.down([[j]]),this.destroy())}},Nn=class extends ce{_sourceSub;bridgedCount;output;constructor(e,t,n,s={}){super(e,s.graph),this._sourceSub=Wo(`${e}-subscription`,t,{cursor:s.cursor}),this.mount("subscription",this._sourceSub);let o=Math.max(1,at(s.maxPerPump??Ho,"topic bridge maxPerPump")),i=s.map??(l=>l);this.output=I([this._sourceSub.available],([l])=>{let h=l,f=[],g=Math.min(h.length,o);for(let m=0;m<g;m++){let T=i(h[m]);T!==void 0&&f.push(T)}return f},{name:"output",describeKind:"derived",meta:Be("topic_bridge_output",{targetRef:n.name}),initial:[]}),this.add(this.output,{name:"output"}),this.addDisposer(ye(this.output)),this.bridgedCount=L(0,{name:"bridgedCount",describeKind:"state",meta:Be("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"}),this.addDisposer(ye(this.bridgedCount));let a=this.output,u=this._sourceSub,d=this.bridgedCount,c=ne([a],()=>{let l=a.cache;if(l.length===0)return;let h=u.available.cache.length,f=Math.min(h,o);if(f>0){u.ack(f);let g=d.cache??0;d.emit(g+l.length)}},{name:"ackPump",describeKind:"effect",meta:Be("topic_bridge_ack_pump")});this.add(c,{name:"ackPump"}),this.addDisposer(ye(c));let p=Ko(this.output,n);this.addDisposer(p)}};function Ko(r,e){return r.subscribe(t=>{for(let n of t){if(n[0]!==C)continue;let s=n[1];s.length!==0&&te(()=>{for(let o of s)e.publish(o)})}})}var En=class{_map=new Map;version;constructor(e){this.version=e}get size(){return this._map.size}has(e){return this._map.has(e)}get(e){return this._map.get(e)}set(e,t){this._map.set(e,t)}delete(e){return this._map.delete(e)}keys(){return this._map.keys()}},kn=class extends ce{_registry;version;_defaultTopicOptions;constructor(e,t={}){super(e,t.graph);let n=L(0,{name:"version",describeKind:"state",meta:Be("hub_version")});this.add(n,{name:"version"}),this.version=n,this._registry=new En(n),this._defaultTopicOptions={...t.defaultTopicOptions??{}}}get size(){return this._registry.size}has(e){return this._registry.has(e)}topicNames(){return this._registry.keys()}topic(e,t){let n=this._registry.get(e);if(n===void 0){let s={...this._defaultTopicOptions,...t??{}};n=new xn(e,s),this._registry.set(e,n),this.mount(e,n);let o=this.version.cache??0;this.version.emit(o+1)}return n}publish(e,t){this.topic(e).publish(t)}publishMany(e){te(()=>{for(let[t,n]of e)this.topic(t).publish(n)})}subscribe(e,t,n){let s=this.topic(t);return new Bt(e,s,n)}removeTopic(e){if(!this._registry.has(e))return!1;try{this.remove(e)}finally{this._registry.delete(e);let t=this.version.cache??0;this.version.emit(t+1)}return!0}};function qt(r,e){return new kn(r,e)}function Wo(r,e,t){return new Bt(r,e,t)}function Rn(r,e,t,n){return new Nn(r,e,t,n)}function Jo(r){if(typeof r!="object"||r===null)return!1;let e=r;return typeof e.subscribe=="function"&&typeof e.down=="function"&&typeof e.emit=="function"}function Yo(r,e){if(r.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(r.length===1){let o=Qo(e);return{best:r[0],bestScore:o}}if(e.some(o=>typeof o.candidateIndex=="number")){let o=new Array(r.length);for(let u=0;u<r.length;u++)o[u]={sum:0,count:0};for(let u of e){let d=u.candidateIndex;typeof d=="number"&&d>=0&&d<r.length&&(o[d].sum+=u.score,o[d].count+=1)}let i=r[0],a=o[0].count>0?o[0].sum/o[0].count:Number.NEGATIVE_INFINITY;for(let u=1;u<r.length;u++){let d=o[u].count>0?o[u].sum/o[u].count:Number.NEGATIVE_INFINITY;d>a&&(a=d,i=r[u])}return{best:i,bestScore:a}}let n=r[0],s=e[0]?.score??Number.NEGATIVE_INFINITY;for(let o=1;o<r.length;o++){let i=e[o]?.score??Number.NEGATIVE_INFINITY;i>s&&(s=i,n=r[o])}return{best:n,bestScore:s}}function Qo(r){if(r.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let t of r)e+=t.score;return e/r.length}function wr(r,e,t,n){let s=n.name??"refine-loop",o=new ce(s,n.graph),i=Jo(n.dataset)?n.dataset:L(n.dataset,{name:"dataset"});o.add(i,{name:"dataset"});let a=L(0,{name:"iteration"});o.add(a,{name:"iteration"});let u=L(t,{name:"strategy",equals:()=>!1});o.add(u,{name:"strategy"});let d=L(null,{name:"lastFeedback"});o.add(d,{name:"lastFeedback"});let c=L([],{name:"prevCandidates"});o.add(c,{name:"prevCandidates"});let p=L(!1,{name:"paused"});o.add(p,{name:"paused"});let l=L("running",{name:"status"});o.add(l,{name:"status"});let h=L([],{name:"history",equals:()=>!1});o.add(h,{name:"history"});let f=L(null,{name:"best"});o.add(f,{name:"best"});let g=L(Number.NEGATIVE_INFINITY,{name:"score"});o.add(g,{name:"score"});let m=L(0,{name:"budget-used"});o.add(m,{name:"budget-used"});let T=qt("stages");o.mount("stages",T);let y=T.topic("generate"),v=T.topic("evaluate"),_=T.topic("analyze"),w=T.topic("decide"),R=t,b=null,x=[];o.addDisposer(u.subscribe(E=>{for(let M of E)M[0]===C&&(R=M[1])})),o.addDisposer(d.subscribe(E=>{for(let M of E)M[0]===C&&(b=M[1])})),o.addDisposer(c.subscribe(E=>{for(let M of E)M[0]===C&&(x=M[1])}));let O=ke(a,E=>{let M=R,J=E===0||b==null;return ne([],(q,k)=>{let D=!1;try{let H=J?M.seed(r):M.generate(b,x);if(H instanceof Promise)return H.then(W=>{D||k.emit(W)},W=>{D||k.down([[G,W]])}),()=>{D=!0};k.emit(H)}catch(H){D=!0,k.down([[G,H]])}},{describeKind:"producer"})},{name:"candidates"});o.add(O,{name:"candidates"});let S=be([O],(E,M,J)=>{let q=J.terminalDeps[0];q!==void 0&&q!==!0&&l.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});o.add(S,{name:"error-watcher"}),o.addDisposer(S.subscribe(()=>{}));let N=I([O,a],([E,M])=>({iteration:M,candidates:E,timestamp_ns:K()}),{name:"generate-event"});o.add(N,{name:"generate-event"}),o.addDisposer(N.subscribe(()=>{}));let P=be([N],([E])=>{y.publish(E)},{name:"generate-publish"});o.add(P,{name:"generate-publish"}),o.addDisposer(P.subscribe(()=>{}));let B=be([O],([E])=>{c.emit(E)},{name:"generate-mirror"});o.add(B,{name:"generate-mirror"}),o.addDisposer(B.subscribe(()=>{}));let z=e(O,i);o.add(z,{name:"scores"});let le=I([z,O,a],([E,M,J])=>({iteration:J,candidates:M,scores:E,timestamp_ns:K()}),{name:"evaluate-event"});o.add(le,{name:"evaluate-event"}),o.addDisposer(le.subscribe(()=>{}));let ae=be([le],([E])=>{v.publish(E)},{name:"evaluate-publish"});o.add(ae,{name:"evaluate-publish"}),o.addDisposer(ae.subscribe(()=>{}));let Oe=I([z,O],([E,M])=>R.analyze(E,M),{name:"feedback"});o.add(Oe,{name:"feedback"});let Ce=I([Oe,O,a],([E,M,J])=>({iteration:J,candidates:M,feedback:E,timestamp_ns:K()}),{name:"analyze-event"});o.add(Ce,{name:"analyze-event"}),o.addDisposer(Ce.subscribe(()=>{}));let $=be([Ce],([E])=>{_.publish(E)},{name:"analyze-publish"});o.add($,{name:"analyze-publish"}),o.addDisposer($.subscribe(()=>{}));let V=I([h],([E])=>{let M=E;if(n.patience==null||M.length<=n.patience)return!1;let J=M.slice(-(n.patience+1)),q=J[0].bestScore;return J.slice(1).every(k=>k.bestScore<=q)},{name:"patience-check"});o.add(V,{name:"patience-check"});let F=I([g],([E])=>n.minScore!=null&&E>=n.minScore,{name:"min-score-check"});o.add(F,{name:"min-score-check"});let ie=I([h],([E])=>{let M=E;if(n.minDelta==null||M.length<2)return!1;let J=M[M.length-2].bestScore,q=M[M.length-1].bestScore;return Math.abs(q-J)<n.minDelta},{name:"min-delta-check"});o.add(ie,{name:"min-delta-check"});let Z=I([m],([E])=>n.maxEvaluations!=null&&E>=n.maxEvaluations,{name:"max-evaluations-check"});o.add(Z,{name:"max-evaluations-check"});let fe=I([a],([E])=>n.maxIterations!=null&&E>=n.maxIterations,{name:"max-iterations-check"});o.add(fe,{name:"max-iterations-check"});let A=I([m],([E])=>n.budget!=null&&E>=n.budget,{name:"budget-exhausted-check"});o.add(A,{name:"budget-exhausted-check"}),o.addDisposer(V.subscribe(()=>{})),o.addDisposer(F.subscribe(()=>{})),o.addDisposer(ie.subscribe(()=>{})),o.addDisposer(Z.subscribe(()=>{})),o.addDisposer(fe.subscribe(()=>{})),o.addDisposer(A.subscribe(()=>{}));let U=I([V,F,ie,Z,fe],([E,M,J,q,k])=>E?{converged:!0,reason:"patience"}:M?{converged:!0,reason:"min-score"}:J?{converged:!0,reason:"min-delta"}:q?{converged:!0,reason:"max-evaluations"}:k?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});o.add(U,{name:"converged"}),o.addDisposer(U.subscribe(()=>{}));let pe=-1,Se=be([Oe,z,O],([E,M,J])=>{let q=a.cache,k=E,D=J,H=M;if(q<=pe)return;pe=q;let{best:W,bestScore:Me}=Yo(D,H),dt=h.cache,qe={n:q,candidates:D,scores:H,feedback:k,best:W,bestScore:Me,timestamp_ns:K()},Y=[...dt,qe],we=m.cache+D.length,Te="continue",Ge,In=n.budget!=null&&we>=n.budget,Gn=p.cache;if(In)Te="budget",Ge="budget";else if(n.minScore!=null&&k.score>=n.minScore)Te="converged",Ge="min-score";else if(n.maxIterations!=null&&q>=n.maxIterations)Te="converged",Ge="max-iterations";else if(n.maxEvaluations!=null&&we>=n.maxEvaluations)Te="converged",Ge="max-evaluations";else if(n.minDelta!=null&&Y.length>=2){let Nt=Y[Y.length-2].bestScore,Jt=Y[Y.length-1].bestScore;Math.abs(Jt-Nt)<n.minDelta&&(Te="converged",Ge="min-delta")}else if(n.patience!=null&&Y.length>n.patience){let Nt=Y.slice(-(n.patience+1)),Jt=Nt[0].bestScore;Nt.slice(1).every($r=>$r.bestScore<=Jt)&&(Te="converged",Ge="patience")}Te==="continue"&&Gn&&(Te="paused"),te(()=>{f.emit(W),g.emit(k.score),h.emit(Y),m.emit(we),d.emit(k),w.publish({iteration:q,decision:Te,reason:Ge,timestamp_ns:K()}),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:h,strategy:u,iteration:a,generate:y,evaluate:v,analyze:_,decide:w,setStrategy(E){u.emit(E)},pause(){p.emit(!0)},resume(){l.cache==="paused"&&te(()=>{p.emit(!1),l.emit("running"),a.emit(a.cache+1)})}})}function Xo(r){let{best:e,score:t,status:n}=r,s=Number.isFinite(t)?t.toFixed(3):String(t),o=e??void 0;return n==="converged"?{outcome:"success",detail:`refineLoop converged at score ${s}`,artifact:o}:n==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${s}`,artifact:o}:{outcome:"failure",detail:`refineLoop errored (status=${n})`,artifact:o}}function On(r){let e=r.name??"refine-executor",t=r.toOutput??Xo;return n=>{let s=Ve(n,i=>i!=null,{name:`${e}/gate-in`}),o=ke(s,i=>{let a=wr(r.seedFrom(i),r.evaluator,r.strategy,{...r.refine,dataset:r.datasetFor(i),name:`${e}/inner`});return I([a.status,a.best,a.score],([u,d,c])=>{let p=u;return p!=="converged"&&p!=="budget"&&p!=="errored"?null:t({best:d,score:c,status:p})},{name:`${e}/output`})},{name:e});return Ve(o,i=>i!=null,{name:`${e}/gate-out`})}}function Zo(r){if(r.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let t of r)e+=t.score;return e/r.length}function es(r){let{passCount:e,total:t,meanScore:n,threshold:s,missingArtifact:o}=r,i=Number.isFinite(n)?n.toFixed(3):String(n),a=!o&&t>0&&n>=s,u=o?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:a?[`${e}/${t} eval tasks passed; mean score ${i} \u2265 ${s}`]:t===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${e}/${t} eval tasks passed; mean score ${i} < threshold ${s}`];return a?{verified:!0,findings:u}:{verified:!1,findings:u,errorClass:"structural"}}function ts(r){return r.artifact??null}function xr(r){let e=r.name??"eval-verifier",t=r.threshold??.5,n=r.toOutput??es,s=r.extractArtifact??ts;return o=>{let i=Ve(o,u=>u!=null&&u[0]!=null&&u[1]!=null,{name:`${e}/gate-in`}),a=ke(i,u=>{let[d,c]=u,p=s(d,c);if(p==null)return L(n({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:t,missingArtifact:!0}));let l=L([p],{name:`${e}/candidates`}),h=L(r.datasetFor(c),{name:`${e}/dataset`}),f=r.evaluator(l,h);return I([f],([g])=>{let m=g;if(m==null)return null;let T=Zo(m),y=m.filter(v=>v.score>=t).length;return n({scores:m,meanScore:T,passCount:y,total:m.length,threshold:t})},{name:`${e}/output`})},{name:e});return Ve(a,u=>u!=null,{name:`${e}/gate-out`})}}function ns(r){let e=r.name??"harness-pair",t=On({name:`${e}-exec`,seedFrom:r.seedFrom,evaluator:r.evaluator,strategy:r.strategy,datasetFor:r.datasetFor,refine:r.refine}),n=xr({name:`${e}-verify`,evaluator:r.evaluator,datasetFor:r.datasetFor,threshold:r.threshold});return{executor:t,verifier:n}}Ne();mt();De();oe();Ie();Ne();et();ge();oe();function Sn(r,e){let t=r.cache??0;return t>=e?!1:(r.down([[ee],[C,t+1]]),!0)}var rs=Kn((r,e)=>{r("observe"),r("signal"),e("write")});function Ht(r){let e=zt([],{name:r.name,maxSize:r.retainedLimit??1024,guard:r.guard??rs,...r.versioning!=null?{versioning:r.versioning}:{}});return e.withLatest(),r.graph&&r.graph.add(e.entries,{name:r.name}),e}function Er(r){if(r===null||typeof r!="object"||Object.isFrozen(r))return r;for(let e of Object.keys(r))Er(r[e]);return Object.freeze(r)}function os(r){let e=r.cache,n=(typeof e=="number"&&Number.isFinite(e)?e:0)+1;return r.down([[ee],[C,n]]),n}function Nr(r,e,t,n,s,o){let i=e(t,n,s);if(i===void 0)return;let a=o!=null?{...i,handlerVersion:o}:i;r.append(a)}function ut(r,e){let t=e.freeze??!0;return function(...s){let o=t?s.map(Er):s,i=ve(),a,u,d=!1,c;try{te(()=>{e.seq&&(c=os(e.seq));try{a=r(...o),e.onSuccess&&Nr(e.audit,e.onSuccess,o,a,{t_ns:i,seq:c},e.handlerVersion)}catch(p){throw u=p,d=!0,p}})}catch(p){if(d&&e.onFailure){let l=u instanceof Error?u.name:typeof u;Nr(e.audit,e.onFailure,o,u,{t_ns:i,seq:c,errorType:l},e.handlerVersion)}throw d?u:p}return a}}function kr(r,e,t=0){let n=L(t,{name:e,describeKind:"state"});return r.add(n,{name:e}),n}function _t(r){return r.relatedTo?.[0]??r.summary}vt();function wt(r,e){return ze("ai",r,e)}function Rr(r){let e=r.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:r}ge();oe();$e();function Or(r){return r!=null&&typeof r=="object"&&"content"in r?String(r.content):typeof r=="string"?r:String(r)}function ss(r,e=200){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function Ut(r,e,t,n){let s=n?.format??"text",o=n?.name??"prompt_node";n?.tools!==void 0&&s!=="raw"&&console.warn("promptNode: `tools` is set but `format !== 'raw'`. Tool calls in the response will be silently dropped \u2014 set `format: 'raw'` to receive the full LLMResponse with `toolCalls`.");let i=I(e,u=>{if(u.some(c=>c==null))return[];let d=typeof t=="string"?t:t(...u);return d?[{role:"user",content:d}]:[]},{name:`${o}::messages`,meta:wt("prompt_node")});return ke(i,u=>!u||u.length===0?L(null):de(d=>{let c=!1,p=!1,l,h={model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,systemPrompt:n?.systemPrompt,...n?.tools!==void 0?{tools:n.tools}:{}};if(n?.abort){let T=nr(n.abort);h.signal=T.signal,l=T.dispose}let f;try{f=r.invoke(u,h)}catch(T){return c=!0,d.down([[G,T]]),()=>{l?.()}}let m=Fe(f).subscribe(T=>{if(!(p||c))for(let y of T){if(c)return;if(y[0]===C){let v=y[1];if(s==="raw")d.emit(v);else try{let _=Or(v),w=s==="json"?JSON.parse(Rr(_)):_;d.emit(w)}catch(_){let w=Or(v),R=new Error(`promptNode: failed to parse LLM response as JSON: ${_.message}
|
|
45
|
+
Raw content (first 200 chars): ${ss(w)}`);c=!0,d.down([[G,R]]);return}}else if(y[0]===G){c=!0,d.down([[G,y[1]]]);return}else if(y[0]===j){c=!0,d.down([[j]]);return}else d.down([y])}});return()=>{p=!0,m(),l?.()}},{name:`${o}::call`,meta:wt("prompt_node::call")}),{name:`${o}::output`,meta:n?.meta?{...wt("prompt_node::output"),...n.meta}:wt("prompt_node::output")})}Ie();Ne();ge();mt();De();oe();vt();function xt(r,e){return ze("orchestration",r,e)}var Kt=class extends ce{constructor(e,t){super(e,t)}task(e,t,n={}){let s=(n.deps??[]).map(i=>this._resolveStep(i)),o=I(s,t,{name:e,describeKind:"derived",meta:xt("task",n.meta)});return this.add(o,{name:e}),o}classify(e,t,n,s={}){let o=this._resolveStep(t),i=I([o],([a])=>{try{return{tag:n(a),value:a}}catch(u){return{tag:"error",value:a,error:u}}},{name:e,describeKind:"derived",meta:xt("classify",s.meta)});return this.add(i,{name:e}),i}combine(e,t,n={}){let s=Object.keys(t),o=s.map(a=>this._resolveStep(t[a])),i=I(o,a=>{let u={};for(let d=0;d<s.length;d++)u[s[d]]=a[d];return u},{name:e,describeKind:"derived",meta:xt("combine",n.meta)});return this.add(i,{name:e}),i}approvalGate(e,t,n={}){let s=n.maxPending??1e3;if(s<1&&s!==Number.POSITIVE_INFINITY)throw new RangeError("approvalGate: maxPending must be >= 1");let o=n.startOpen??!1;typeof t!="string"&&this.nameOf(t)===void 0&&this.add(t,{name:`${e}/source`});let i=this._resolveStep(t),a=new ce(`${e}_state`),u=L([],{name:"pending",equals:()=>!1}),d=L(o,{name:"isOpen"}),c=I([u],([$])=>$.length,{name:"count"}),p=L(0,{name:"droppedCount"}),l=Ht({name:"decisions",retainedLimit:1024,graph:a});a.add(u,{name:"pending"}),a.add(d,{name:"isOpen"}),a.add(c,{name:"count"}),a.add(p,{name:"droppedCount"}),this.mount(`${e}_state`,a);let h=[],f=!1,g=!1,m=o,T=d.subscribe($=>{for(let V of $)V[0]===C&&(m=V[1])});this.addDisposer(T);function y(){u.emit([...h])}function v($,V,F){l.append({action:$,t_ns:ve(),...V!==void 0?{items:V,count:V.length}:{},...F!==void 0?{unflushed:F}:{},...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}function _($){if(h.push($),h.length>s){let V=h.shift();p.emit(p.cache+1),v("drop",[V])}y()}function w($){let V=h.splice(0,$);return y(),V}let R=ne([i],($,V,F)=>{let ie=F.terminalDeps[0];if(ie!==void 0){f=!0;let fe=h.length;h=[],y(),v("teardown",void 0,fe),V.down(ie===!0?[[j]]:[[G,ie]]);return}let Z=$[0];if(Z==null||Z.length===0){V.down([[Q]]);return}for(let fe of Z)m?V.emit(fe):(_(fe),V.down([[Q]]))},{name:e,describeKind:"derived",meta:xt("approval_gate",n.meta)});if(this.add(R,{name:e}),n.approver!=null){n.approver.cache&&(d.emit(!0),m=!0,n.onceOnly&&(g=!0));let V=n.approver.subscribe(F=>{for(let ie of F){if(ie[0]!==C)continue;let Z=!!ie[1];if(Z&&!m){if(n.onceOnly){if(g)continue;g=!0}te(()=>{d.emit(!0);let fe=w(h.length);v("open",fe);for(let A of fe){if(f)break;R.emit(A)}})}else if(!Z&&m){if(n.onceOnly&&g)continue;te(()=>{d.emit(!1),v("close")})}}});this.addDisposer(V)}let b=$=>{if(f)throw new Error(`approvalGate: ${$}() called after the gate was torn down`)},x=($=1)=>{b("approve");let V=w($);for(let F of V){if(f)break;R.emit(F)}},O=($=1)=>{b("reject"),w($)},S=($,V=1)=>{b("modify");let F=[...h],ie=w(V);for(let Z=0;Z<ie.length&&!f;Z++)R.emit($(ie[Z],Z,F))},N=()=>{b("open"),d.emit(!0);let $=w(h.length);for(let V of $){if(f)break;R.emit(V)}},P=()=>{b("close"),!(n.onceOnly&&g)&&d.emit(!1)},B=ut(x,{audit:l,freeze:!1,onSuccess:($,V,F)=>({action:"approve",count:$[0]??1,t_ns:F.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:($,V,F)=>({action:"drop",t_ns:F.t_ns,errorType:F.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}),z=ut(O,{audit:l,freeze:!1,onSuccess:($,V,F)=>({action:"reject",count:$[0]??1,t_ns:F.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:($,V,F)=>({action:"drop",t_ns:F.t_ns,errorType:F.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}),le=ut(S,{audit:l,freeze:!1,onSuccess:($,V,F)=>({action:"modify",count:$[1]??1,t_ns:F.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:($,V,F)=>({action:"drop",t_ns:F.t_ns,errorType:F.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}),ae=ut(N,{audit:l,freeze:!1,onSuccess:($,V,F)=>({action:"open",t_ns:F.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:($,V,F)=>({action:"drop",t_ns:F.t_ns,errorType:F.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}),Oe=ut(P,{audit:l,freeze:!1,onSuccess:($,V,F)=>({action:"close",t_ns:F.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:($,V,F)=>({action:"drop",t_ns:F.t_ns,errorType:F.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})});return this.addDisposer(c.subscribe(()=>{})),{node:R,pending:u,count:c,isOpen:d,droppedCount:p,decisions:l,audit:l,approve:B,reject:z,modify:le,open:ae,close:Oe}}approval(e,t,n,s={}){return this.approvalGate(e,t,{...s,approver:n,maxPending:1})}catch(e,t,n,s={}){let o=this._resolveStep(t),i=s.on??"errored",a=ne([o],(u,d,c)=>{let p=c.terminalDeps[0];if(p!==void 0){let h=p===!0?{kind:"completed"}:{kind:"errored",error:p};if(i==="terminal"||i===h.kind){d.emit(n(h,d));return}d.down(h.kind==="completed"?[[j]]:[[G,h.error]]);return}let l=u[0];if(l==null||l.length===0){d.down([[Q]]);return}for(let h of l)d.emit(h)},{name:e,describeKind:"derived",completeWhenDepsComplete:s.completeWhenDepsComplete??!(i==="completed"||i==="terminal"),errorWhenDepsError:!(i==="errored"||i==="terminal"),meta:xt("catch",s.meta)});return this.add(a,{name:e}),a}_resolveStep(e){if(typeof e=="string")return this.resolve(e);if(this.nameOf(e)===void 0)throw new Error(`PipelineGraph "${this.name}": Node dep is not registered. Pass a string path or call graph.add(node) first.`);return e}};function An(r,e){let t=new Kt(r,e),{factory:n,factoryArgs:s,...o}=e??{};return t.tagFactory("pipelineGraph",ht(o)),t}var au=Math.LN2/604800;function Sr(r,e,t,n=0){if(!Number.isFinite(r))return n;if(!Number.isFinite(e)||e<=0||!Number.isFinite(t)||t<=0)return Math.max(n,r);let s=r*Math.exp(-t*e);return Math.max(n,s)}Ne();vt();Ie();ge();oe();var Dn=class{_version=0;_buf;constructor(e){this._buf=e?[...e]:[]}get version(){return this._version}get size(){return this._buf.length}at(e){if(!Number.isInteger(e))return;let t=e>=0?e:this._buf.length+e;if(!(t<0||t>=this._buf.length))return this._buf[t]}append(e){this._buf.push(e),this._version+=1}appendMany(e){if(e.length===0)return;let t=this._buf.length;this._buf.length=t+e.length;for(let n=0;n<e.length;n++)this._buf[t+n]=e[n];this._version+=1}insert(e,t){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insert: index ${e} out of range [0, ${this._buf.length}]`);this._buf.splice(e,0,t),this._version+=1}insertMany(e,t){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insertMany: index ${e} out of range [0, ${this._buf.length}]`);t.length!==0&&(this._buf.splice(e,0,...t),this._version+=1)}pop(e){if(this._buf.length===0)throw new RangeError("pop from empty list");if(!Number.isInteger(e))throw new RangeError(`pop: index ${e} must be an integer`);let t=e>=0?e:this._buf.length+e;if(t<0||t>=this._buf.length)throw new RangeError(`pop: index ${e} out of range`);let[n]=this._buf.splice(t,1);return this._version+=1,n}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._version+=1,e)}toArray(){return[...this._buf]}};function Ar(r,e={}){let{name:t,versioning:n,backend:s}=e,o=s??new Dn(r),i=L(o.toArray(),{name:t,describeKind:"state",equals:(d,c)=>d===c,...n!=null?{versioning:n}:{}});function a(){let d=o.toArray();te(()=>{i.down([[ee]]),i.down([[C,d]])})}function u(d){let c=o.version;try{return d()}finally{o.version!==c&&a()}}return{items:i,get size(){return o.size},at(d){return o.at(d)},append(d){u(()=>o.append(d))},appendMany(d){u(()=>o.appendMany(d))},insert(d,c){u(()=>o.insert(d,c))},insertMany(d,c){u(()=>o.insertMany(d,c))},pop(d=-1){return u(()=>o.pop(d))},clear(){u(()=>o.clear())},dispose(){}}}$e();function is(r,e){if(!Number.isFinite(r)||!Number.isInteger(r)||r<0)throw new Error(`${e} must be a non-negative integer`);return r}function as(r,e){return ze("job_queue",r,e)}var Cn=class extends ce{_pending;_jobs;_seqCursor;pending;jobs;depth;events;audit;constructor(e,t={}){super(e,t.graph),this._pending=Ar([],{name:"pending"}),this._jobs=it({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=I([this.pending],([n])=>n.length,{name:"depth",describeKind:"derived",meta:as("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(ye(this.depth)),this.events=Ht({name:"events",retainedLimit:1024,graph:this}),this.audit=this.events,this._seqCursor=kr(this,"seq",0)}_bumpSeq(){let t=(this._seqCursor.cache??0)+1;return this._seqCursor.emit(t),t}attachEventStorage(e){return this.events.attachStorage(e)}enqueue(e,t={}){let n=this._bumpSeq(),s=t.id??`${this.name}-${n}`;if(this._jobs.get(s)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${s}"`);let o={id:s,payload:e,attempts:0,metadata:Object.freeze({...t.metadata??{}}),state:"queued"};return this._jobs.set(s,o),this._pending.append(s),this.events.append({action:"enqueue",id:s,payload:e,t_ns:ve(),seq:n}),s}claim(e=1){let t=is(e,"job queue claim limit");if(t===0)return[];let n=[];for(;n.length<t&&this.pending.cache.length!==0;){let o=this._pending.pop(0),i=this._jobs.get(o);if(!i||i.state!=="queued")continue;let a={...i,state:"inflight",attempts:i.attempts+1};this._jobs.set(o,a),n.push(a),this.events.append({action:"claim",id:o,attempts:a.attempts,t_ns:ve(),seq:this._bumpSeq()})}return n}ack(e){let t=this._jobs.get(e);return!t||t.state!=="inflight"?!1:(this._jobs.delete(e),this.events.append({action:"ack",id:e,attempts:t.attempts,t_ns:ve(),seq:this._bumpSeq()}),!0)}nack(e,t={}){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:t.requeue??!0?(this._jobs.set(e,{...n,state:"queued"}),this._pending.append(e),this.events.append({action:"nack",id:e,attempts:n.attempts,t_ns:ve(),seq:this._bumpSeq()}),!0):(this._jobs.delete(e),this.events.append({action:"nack",id:e,attempts:n.attempts,t_ns:ve(),seq:this._bumpSeq()}),!0)}removeById(e){let t=this._jobs.get(e);if(!t)return!1;if(t.state==="queued"){let s=this.pending.cache.indexOf(e);s>=0&&this._pending.pop(s)}return this._jobs.delete(e),this.events.append({action:"remove",id:e,attempts:t.attempts,t_ns:ve(),seq:this._bumpSeq()}),!0}consumeFrom(e,t){return e.subscribe(n=>{for(let s of n){if(s[0]!==C)continue;let o=s[1];this.enqueue(o,t?{metadata:t.metadata}:void 0)}})}};function Dr(r,e){return new Cn(r,e)}Ne();oe();function Mn(){let r=it({name:"strategy-entries"}),e=I([r.entries],([i])=>{let a=i;return new Map(a)},{name:"strategy-model",equals:(i,a)=>{let u=i,d=a;if(u.size!==d.size)return!1;for(let[c,p]of u){let l=d.get(c);if(!l||p.attempts!==l.attempts||p.successes!==l.successes)return!1}return!0}});function t(i,a,u){let d=st(i,a),c=r.get(d),p=(c?.attempts??0)+1,l=(c?.successes??0)+(u?1:0);r.set(d,{rootCause:i,intervention:a,attempts:p,successes:l,successRate:l/p})}function n(i,a){return r.get(st(i,a))}let s=e.subscribe(()=>{});function o(){s()}return{node:e,record:t,lookup:n,dispose:o}}function us(r,e,t,n,s){let o={...rt,...s?.severityWeights},i=s?.decayRate??ot,a=s?.effectivenessThreshold??.7,u=s?.effectivenessBoost??15,d=[r,e,t];return n&&d.push(n),I(d,c=>{let p=c[0],l=c[1],h=c[2],f=n?c[3]:0,g=o[p.severity??"medium"],m=(K()-h)/1e9,T=Sr(g,m,i,0),y=st(p.rootCause,p.intervention),v=l.get(y);return v&&v.successRate>=a&&(T+=u),T+=f*20,T},{name:"priority-score"})}var Cr="intake",ds="triage-output",Mr="retry",Ir="verify-results",Gr="__unrouted";function Pr(r,e){let t=bt(e,hn,(n,s)=>n.replace("{{item}}",JSON.stringify(s)));return n=>Ut(r,[n],t,{name:"execute",format:"json"})}function Lr(r,e){let t=bt(e,mn,(n,s)=>{let[o,i]=s;return n.replace("{{execution}}",JSON.stringify(o)).replace("{{item}}",JSON.stringify(i))});return n=>Ut(r,[n],s=>s==null?"":t(s),{name:"verify",format:"json"})}var Wt=class extends ce{queues;jobs;gates;queueTopics;strategy;totalRetries;totalReingestions;priorityScores;constructor(e,t,n,s,o,i,a,u,d){super(e),this.queues=t,this.queueTopics=n,this.jobs=s,this.gates=o,this.strategy=i,this.totalRetries=a,this.totalReingestions=u,this.priorityScores=d}get intake(){return this.queues.topic(Cr)}get verifyResults(){return this.queues.topic(Ir)}get retry(){return this.queues.topic(Mr)}get unrouted(){return this.queues.topic(Gr)}stageNodes(){let e=this.queues,t=i=>e.has(i)?`queues::${i}::latest`:null,n=i=>i==null?[]:[i],s=_e.flatMap(i=>n(t(i))),o=[];for(let[i]of this.gates)o.push(`gates::${i}/gate`);return[{label:"INTAKE",paths:n(t("intake"))},{label:"TRIAGE",paths:["triage"]},{label:"QUEUE",paths:s},{label:"GATE",paths:o},{label:"EXECUTE",paths:["execute"]},{label:"VERIFY",paths:n(t("verify-results"))},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function cs(r,e){let t=e.adapter,n=e.maxRetries??2,s=e.retainedLimit??1e3,o=e.errorClassifier??Gt,i=new Map;for(let k of _e)i.set(k,{...It[k],...e.queues?.[k]});let a=qt(`${r}/queues`,{defaultTopicOptions:{retainedLimit:s}}),u=a.topic(Cr),d=a.topic(ds),c=a.topic(Mr),p=a.topic(Ir),l=new Map;for(let k of _e)l.set(k,a.topic(k));let h=a.topic(Gr),f=Mn(),g=gt(u.latest,f.node),m=bt(e.triagePrompt,pn,(k,D)=>{let[H,W]=D;return k.replace("{{strategy}}",JSON.stringify(Array.from(W.entries()))).replace("{{item}}",JSON.stringify(H))}),T=Ut(t,[g],k=>{let D=k;return!D||!D[0]?"":m(D)},{name:"triage",format:"json"}),y=gt(T,g),_=be([y],([k])=>{if(k==null)return;let[D,H]=k;if(!D?.route)return;let W=H?.[0],Me={...D,...W};d.publish(Me)}).subscribe(()=>{}),w=new Set(_e);for(let k of _e)Rn(`bridge/${k}`,d,l.get(k),{map:D=>D.route===k?D:void 0});Rn("bridge/__unrouted",d,h,{map:k=>w.has(k.route)?void 0:k});let R=new Map,b=new Map;for(let k of _e)R.set(k,Dr(`jobs/${k}`));let x=[];for(let k of _e){let D=l.get(k),H=R.get(k),W=new WeakSet,Me=be([D.events],([dt])=>{let qe=dt??[];for(let Y of qe){if(W.has(Y))continue;W.add(Y);let we=H.enqueue(Y);b.set(_t(Y),{route:k,id:we})}},{name:`jobs/${k}-mirror`});x.push(Me.subscribe(()=>{}))}function O(k){let D=_t(k),H=b.get(D);H&&(R.get(H.route)?.removeById(H.id),b.delete(D))}let S=An("gates"),N=new Map;for(let k of _e){let D=i.get(k);if(!D.gated)continue;let H=l.get(k),W=S.approvalGate(`${k}/gate`,H.latest,{maxPending:D.maxPending,startOpen:D.startOpen});N.set(k,W)}let P=[];for(let k of _e)i.get(k).gated&&N.has(k)?P.push(N.get(k).node):P.push(l.get(k).latest);P.push(c.latest);let B=or(...P),le=(e.executor??Pr(t,e.executePrompt))(B),ae=gt(le,B),Ce=(e.verifier??Lr(t,e.verifyPrompt))(ae),$=gt(Ce,ae),V=e.maxReingestions??1,F=Math.min(e.maxTotalRetries??n*10,100),ie=Math.min(e.maxTotalReingestions??V*10,100),Z=L(0),fe=L(0);function A(k,D,H){let W={item:H,outcome:D?.outcome??"failure",detail:D?.detail??"unknown",artifact:D?.artifact};return{item:H,execution:W,verified:k.verified,findings:k.findings??[],errorClass:k.errorClass}}function U(k,D){f.record(D.rootCause,D.intervention,!0),p.publish(k),O(D)}function pe(k,D){let H=_t(D),W=D.$retries??0,Me={...D,$retries:W+1,summary:`[RETRY ${W+1}/${n}] ${H} \u2014 Previous attempt failed: ${k.findings.join("; ")}`,relatedTo:[H]};c.publish(Me)}function Se(k,D){f.record(D.rootCause,D.intervention,!1),p.publish(k),O(D);let H=_t(D),W=D.$reingestions??0;W<V&&Sn(fe,ie)&&u.publish({source:D.source,summary:`Verification failed for: ${H}`,evidence:k.findings.join(`
|
|
46
|
+
`),affectsAreas:D.affectsAreas,affectsEvalTasks:D.affectsEvalTasks,severity:D.severity??"high",relatedTo:[H],$reingestions:W+1})}let he=ne([$],(k,D)=>{let H=k[0];if(H==null||H.length===0)return;let W=H[H.length-1];if(W==null)return;let[Me,dt]=W,[qe,Y]=dt??[null,null];if(!Me||!Y)return;if(qe==null){Se({item:Y,execution:{item:Y,outcome:"failure",detail:"executor returned null"},verified:!1,findings:["executor returned null"],errorClass:"structural"},Y);return}let we=A(Me,qe,Y);if(we.verified){U(we,Y);return}let Te=we.errorClass??o({item:Y,outcome:qe.outcome,detail:we.findings.join("; ")}),Ge=Y.$retries??0;Te==="self-correctable"&&Ge<n&&Sn(Z,F)?pe(we,Y):Se(we,Y)}),E=he.subscribe(()=>{}),M=I([he],()=>null,{name:"reflect",equals:()=>!1}),J;e.priority&&(J=ls(l,f,e));let q=new Wt(r,a,l,R,N,f,Z,fe,J);q.addDisposer(_),q.addDisposer(E),q.addDisposer(f.dispose);for(let k of x)q.addDisposer(k);if(q.add(T,{name:"triage"}),q.add(B,{name:"execute-input"}),q.add(le,{name:"execute"}),q.add(ae,{name:"execute-context"}),q.add(Ce,{name:"verify"}),q.add($,{name:"verify-context"}),q.add(he,{name:"verify-dispatch"}),q.add(M,{name:"reflect"}),q.add(f.node,{name:"strategy"}),q.addDisposer(M.subscribe(()=>{})),J)for(let[k,D]of J)q.add(D,{name:`priority/${k}`}),q.addDisposer(D.subscribe(()=>{}));q.mount("queues",a),q.mount("gates",S);for(let[k,D]of R)q.mount(`jobs/${k}`,D);return q.tagFactory("harnessLoop",ht(e)),q}function ls(r,e,t){if(!t.lastInteractionNs)throw new Error("harnessLoop: `opts.priority` requires `opts.lastInteractionNs` \u2014 pass a Node<number> (e.g. `fromTimer(60_000)` or a `state(monotonicNs())` you bump on human interaction). Priority scores only decay when this node settles; an internal default would freeze age at construction time.");let n=t.lastInteractionNs,s=t.priority??{},o={...rt,...s.severityWeights},i=s.decayRate??ot,a=s.effectivenessThreshold??.7,u=s.effectivenessBoost??15,d=new Map;for(let[c,p]of r){let l=I([p.latest,e.node,n],h=>{let f=h[0];if(f==null)return 0;let g=o[f.severity??"medium"]??40,m=(K()-h[2])/1e9,T=g*Math.exp(-i*Math.max(0,m)),y=`${f.rootCause}\u2192${f.intervention}`,_=h[1]?.get(y);return _&&_.successRate>=a&&(T+=u),T},{name:`priority/${c}`});d.set(c,l)}return d}function fs(r,e){let t=Vt(r,e),n={};for(let s of _e){let o=r.queues.has(s)?r.queues.topic(s):null;n[s]=o?.retained().length??0}return{...t,queueDepths:n,strategyEntries:r.strategy.node.cache?.size??0,totalRetries:r.totalRetries.cache??0,totalReingestions:r.totalReingestions.cache??0}}Ne();function ps(r){let e={};for(let{label:t,paths:n}of r.stageNodes())for(let s of n)e[s]=t;return e}function hs(r,e){let t=e?.logger===null?null:e?.logger??console.log,n=e?.detail??"summary",s=K(),o=[],i=[],a=ps(r);function u(){return(K()-s)/1e9}function d(c,p,l){let h={elapsed:u(),stage:c,type:p};n!=="summary"&&(h.summary=ms(l)),n==="full"&&(h.data=l),i.push(h)}for(let[c,p]of Object.entries(a))try{let l=r.observe(c,{format:"stage-log",stageLabels:a,logger:t?h=>t(h):()=>{},includeTypes:["data","error","complete"]});l.onEvent(h=>{h.type==="data"?d(p,"data",h.data):h.type==="error"?d(p,"error",h.data):h.type==="complete"&&d(p,"complete",void 0)}),o.push(l)}catch(l){let h=l instanceof Error?l.message:String(l);d(p,"error",`observe-unavailable: ${c} \u2014 ${h}`),t&&t(`[${u().toFixed(3)}s] ${p.padEnd(9)} \u2717 observe-unavailable: ${h}`)}return{get events(){return i},dispose(){for(let c of o)c.dispose();o.length=0}}}function ms(r){if(r==null)return"null";if(typeof r=="string")return Fr(r,80);if(typeof r=="number"||typeof r=="boolean"||typeof r=="bigint")return String(r);try{let e=JSON.stringify(r);return Fr(e,120)}catch{return String(r)}}function Fr(r,e){return r.length>e?`${r.slice(0,e-1)}\u2026`:r}0&&(module.exports={DEFAULT_DECAY_RATE,DEFAULT_EXECUTE_PROMPT,DEFAULT_QUEUE_CONFIGS,DEFAULT_SEVERITY_WEIGHTS,DEFAULT_TRIAGE_PROMPT,DEFAULT_VERIFY_PROMPT,HarnessGraph,QUEUE_NAMES,actuatorExecutor,affectedTaskFilter,autoSolidify,beforeAfterCompare,codeChangeBridge,createIntakeBridge,defaultErrorClassifier,defaultLlmExecutor,defaultLlmVerifier,dispatchActuator,effectivenessTracker,evalIntakeBridge,evalSource,evalVerifier,harnessEvalPair,harnessLoop,harnessProfile,harnessTrace,notifyEffect,priorityScore,refineExecutor,resolvePromptFn,strategyKey,strategyModel});
|