agentic-qe 3.15.17 → 3.15.18
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/.claude/helpers/brain-checkpoint.cjs +107 -10
- package/.claude/skills/agentic-quality-engineering/SKILL.md +67 -44
- package/.claude/skills/brutal-honesty-review/SKILL.md +12 -7
- package/.claude/skills/brutal-honesty-review/evals/brutal-honesty-review.yaml +120 -0
- package/.claude/skills/brutal-honesty-review/schemas/output.json +9 -3
- package/.claude/skills/code-review-quality/SKILL.md +2 -2
- package/.claude/skills/holistic-testing-pact/SKILL.md +11 -11
- package/.claude/skills/sherlock-review/SKILL.md +4 -2
- package/.claude/skills/sherlock-review/evals/sherlock-review.yaml +124 -0
- package/.claude/skills/skills-manifest.json +1 -1
- package/.claude/skills/technical-writing/SKILL.md +12 -6
- package/.claude/skills/technical-writing/evals/technical-writing.yaml +96 -0
- package/.opencode/skills/qe-agentic-quality-engineering.yaml +2 -2
- package/.opencode/skills/qe-holistic-testing-pact.yaml +2 -2
- package/CHANGELOG.md +123 -0
- package/assets/skills/agentic-quality-engineering/SKILL.md +67 -44
- package/assets/skills/brutal-honesty-review/SKILL.md +12 -8
- package/assets/skills/brutal-honesty-review/evals/brutal-honesty-review.yaml +120 -0
- package/assets/skills/brutal-honesty-review/schemas/output.json +9 -3
- package/assets/skills/code-review-quality/SKILL.md +2 -2
- package/assets/skills/holistic-testing-pact/SKILL.md +11 -11
- package/assets/skills/sherlock-review/SKILL.md +4 -3
- package/assets/skills/sherlock-review/evals/sherlock-review.yaml +124 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/assets/skills/technical-writing/SKILL.md +12 -6
- package/assets/skills/technical-writing/evals/technical-writing.yaml +96 -0
- package/dist/cli/brain-commands.d.ts +5 -0
- package/dist/cli/brain-commands.js +4 -0
- package/dist/cli/bundle.js +6 -6
- package/dist/cli/chunks/adapter-WRSDXLOT.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-6BUOFQZA.js → agent-booster-wasm-UFNJNF3M.js} +2 -2
- package/dist/cli/chunks/{agent-handler-HPDK3JI3.js → agent-handler-EAYVRJXN.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-5QKUTWK5.js → agent-memory-branch-M65C6WAQ.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-O6NJBCCM.js +2 -0
- package/dist/cli/chunks/{arena-HZ35LESR.js → arena-2GDICP6R.js} +4 -4
- package/dist/cli/chunks/{arena-7OKPMNHD.js → arena-CG3X67OE.js} +2 -2
- package/dist/cli/chunks/{audit-XI575SVK.js → audit-F4FSPJPL.js} +3 -3
- package/dist/cli/chunks/base-J2FXOE77.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-YO5X7ZJS.js → better-sqlite3-2MCFXW4J.js} +2 -2
- package/dist/cli/chunks/brain-handler-WGTJNYNB.js +95 -0
- package/dist/cli/chunks/{branch-enumerator-N6G44UU2.js → branch-enumerator-KL7C535H.js} +2 -2
- package/dist/cli/chunks/{browser-EVKPTLOI.js → browser-SJEXDVHS.js} +2 -2
- package/dist/cli/chunks/browser-workflow-LXGER6ZD.js +2 -0
- package/dist/cli/chunks/{chunk-VLTDW7XJ.js → chunk-244RKAEP.js} +2 -2
- package/dist/cli/chunks/{chunk-CVPXHDQU.js → chunk-27TUMXPD.js} +1 -1
- package/dist/cli/chunks/{chunk-FBBPRVNF.js → chunk-2MBYDPCP.js} +2 -2
- package/dist/cli/chunks/{chunk-P3D7SEHW.js → chunk-2Q6DTBMT.js} +1 -1
- package/dist/cli/chunks/{chunk-NE3LRUNC.js → chunk-355MI7RV.js} +13 -13
- package/dist/cli/chunks/{chunk-YCVLKU6H.js → chunk-3LX5OKBD.js} +2 -2
- package/dist/cli/chunks/{chunk-74MDUIAZ.js → chunk-3RPDKJGV.js} +1 -1
- package/dist/cli/chunks/{chunk-OWIQR6N2.js → chunk-3YMIT73A.js} +2 -2
- package/dist/cli/chunks/{chunk-VKREKVFI.js → chunk-43KUVBSU.js} +2 -2
- package/dist/cli/chunks/chunk-477FKXSS.js +2 -0
- package/dist/cli/chunks/{chunk-XPTCQKVE.js → chunk-4BIMTRRX.js} +1 -1
- package/dist/cli/chunks/{chunk-HD6W6PHV.js → chunk-4CVNVBX5.js} +2 -2
- package/dist/cli/chunks/{chunk-CQER6IJ5.js → chunk-4HL3SD4A.js} +1 -1
- package/dist/cli/chunks/{chunk-ZNXM6WVL.js → chunk-4PEG4DU2.js} +2 -2
- package/dist/cli/chunks/{chunk-BSIWI4ES.js → chunk-4QSQKFED.js} +2 -2
- package/dist/cli/chunks/chunk-53ZBETYR.js +16 -0
- package/dist/cli/chunks/{chunk-BHQ2DLJU.js → chunk-544KDWL4.js} +1 -1
- package/dist/cli/chunks/chunk-54RCGMLB.js +8 -0
- package/dist/cli/chunks/{chunk-TDZ6N43D.js → chunk-5AGXIZQ5.js} +2 -2
- package/dist/cli/chunks/{chunk-RKCN4B26.js → chunk-5M24X6W7.js} +2 -2
- package/dist/cli/chunks/{chunk-GG7PMTHD.js → chunk-5O5T4LEU.js} +1 -1
- package/dist/cli/chunks/{chunk-OWIZBZLN.js → chunk-5RFXX4IF.js} +2 -2
- package/dist/cli/chunks/{chunk-VQFV2IPV.js → chunk-62MLAQRJ.js} +1 -1
- package/dist/cli/chunks/{chunk-PCL5JRKN.js → chunk-6D6TGL2E.js} +2 -2
- package/dist/cli/chunks/{chunk-WBDWHHKP.js → chunk-6IHZDSDL.js} +2 -2
- package/dist/cli/chunks/{chunk-UOVCTK5L.js → chunk-6P3Y45QL.js} +2 -2
- package/dist/cli/chunks/{chunk-45223KK6.js → chunk-6TEVM3X3.js} +10 -10
- package/dist/cli/chunks/{chunk-K7WAI662.js → chunk-7XTUKKRA.js} +1 -1
- package/dist/cli/chunks/chunk-A3GDX6UF.js +2 -0
- package/dist/cli/chunks/{chunk-GN6OE3JT.js → chunk-A5YTKKNA.js} +1 -1
- package/dist/cli/chunks/{chunk-KR2TAAF6.js → chunk-ADNGZAT2.js} +1 -1
- package/dist/cli/chunks/{chunk-J7Q5TXFZ.js → chunk-AWQAE3SW.js} +2 -2
- package/dist/cli/chunks/{chunk-ZN35XSKF.js → chunk-AXDBQFR4.js} +2 -2
- package/dist/cli/chunks/{chunk-ND72UDVH.js → chunk-AXVD7O3F.js} +2 -2
- package/dist/cli/chunks/{chunk-SAEECT23.js → chunk-B52ULNYO.js} +2 -2
- package/dist/cli/chunks/chunk-B6S4FC7M.js +3 -0
- package/dist/cli/chunks/{chunk-Z7SKUC6P.js → chunk-BDVFSMOQ.js} +1 -1
- package/dist/cli/chunks/{chunk-CXCMATZ6.js → chunk-BGXXMX3Y.js} +2 -2
- package/dist/cli/chunks/{chunk-R3KBOQ3O.js → chunk-BKMQQY5T.js} +2 -2
- package/dist/cli/chunks/{chunk-SAZ4PJBR.js → chunk-BN2FROBQ.js} +2 -2
- package/dist/cli/chunks/{chunk-G2X3OLMN.js → chunk-BO6EQNOC.js} +2 -2
- package/dist/cli/chunks/{chunk-776K4ZLE.js → chunk-BOVAKCDC.js} +2 -2
- package/dist/cli/chunks/{chunk-QSQNXBD2.js → chunk-BSXKZDKO.js} +2 -2
- package/dist/cli/chunks/{chunk-MGZ6XZHU.js → chunk-C5QVJ5XQ.js} +1 -1
- package/dist/cli/chunks/{chunk-LOLSZG5J.js → chunk-CFQLLF3D.js} +2 -2
- package/dist/cli/chunks/{chunk-J6QRNQJF.js → chunk-DUCVLT3F.js} +7 -7
- package/dist/cli/chunks/{chunk-QTQDX4TZ.js → chunk-E4RMJCGA.js} +3 -3
- package/dist/cli/chunks/{chunk-MLMD3I75.js → chunk-EONDCWY4.js} +1 -1
- package/dist/cli/chunks/{chunk-7BSOO3CY.js → chunk-F4AGNKL2.js} +2 -2
- package/dist/cli/chunks/{chunk-IKB3M7OF.js → chunk-F6YD3BOW.js} +1 -1
- package/dist/cli/chunks/{chunk-LIF6UWHV.js → chunk-FQRS7WVA.js} +2 -2
- package/dist/cli/chunks/{chunk-QJSSUBO3.js → chunk-FT24SSDG.js} +2 -2
- package/dist/cli/chunks/chunk-FV4YNSAJ.js +5 -0
- package/dist/cli/chunks/{chunk-VITV7AEC.js → chunk-FVDM3X42.js} +2 -2
- package/dist/cli/chunks/{chunk-LN7NKE3N.js → chunk-FVH7TXWU.js} +2 -2
- package/dist/cli/chunks/{chunk-FBSBXCZS.js → chunk-FWR5QY37.js} +2 -2
- package/dist/cli/chunks/{chunk-X2DWHGCC.js → chunk-FYINK2B7.js} +2 -2
- package/dist/cli/chunks/{chunk-ECKHDHR2.js → chunk-GGISVPOZ.js} +2 -2
- package/dist/cli/chunks/{chunk-SRBCBVSI.js → chunk-GPIJIZJQ.js} +2 -2
- package/dist/cli/chunks/{chunk-YR5QBUHZ.js → chunk-GXEVOT5F.js} +2 -2
- package/dist/cli/chunks/{chunk-ZTP3DQ5M.js → chunk-GZ4VB5RI.js} +1 -1
- package/dist/cli/chunks/{chunk-HWQPMUSN.js → chunk-HBDSCYSK.js} +2 -2
- package/dist/cli/chunks/{chunk-XBTGEYED.js → chunk-HGG4HR7C.js} +2 -2
- package/dist/cli/chunks/{chunk-YD2C6EPN.js → chunk-HSCKWWO2.js} +2 -2
- package/dist/cli/chunks/{chunk-LOMT4UC2.js → chunk-HSQ3GUYJ.js} +2 -2
- package/dist/cli/chunks/{chunk-ZC3KDNJW.js → chunk-HZQBW5EM.js} +3 -3
- package/dist/cli/chunks/{chunk-SUAZ5Z47.js → chunk-IGIYANVT.js} +2 -2
- package/dist/cli/chunks/{chunk-IHQGNDMX.js → chunk-IPWMSXBF.js} +2 -2
- package/dist/cli/chunks/{chunk-6V6BD6PH.js → chunk-IWVNC7VY.js} +1 -1
- package/dist/cli/chunks/{chunk-M2YI5YUR.js → chunk-IZODXKZD.js} +2 -2
- package/dist/cli/chunks/{chunk-LG5PPJT7.js → chunk-J2MT2OJV.js} +1 -1
- package/dist/cli/chunks/{chunk-6LSZCEW2.js → chunk-JKIJVVSP.js} +1 -1
- package/dist/cli/chunks/{chunk-REY52O7J.js → chunk-JMRDT2XK.js} +1 -1
- package/dist/cli/chunks/{chunk-XEYFZLIT.js → chunk-JR2UMTKG.js} +1 -1
- package/dist/cli/chunks/{chunk-DJDVD6RM.js → chunk-K6CH4CFF.js} +2 -2
- package/dist/cli/chunks/{chunk-2PCEMDIX.js → chunk-K7KW5QB5.js} +78 -87
- package/dist/cli/chunks/{chunk-EPVPXHL7.js → chunk-KFCQP434.js} +2 -2
- package/dist/cli/chunks/{chunk-TWBZONKT.js → chunk-KH4T6STG.js} +2 -2
- package/dist/cli/chunks/{chunk-JI33PMPZ.js → chunk-KJBYZO57.js} +1 -1
- package/dist/cli/chunks/{chunk-PK34KJH7.js → chunk-KP4OKOKV.js} +2 -2
- package/dist/cli/chunks/chunk-L2MBKVSE.js +2 -0
- package/dist/cli/chunks/{chunk-JVWZAE2H.js → chunk-L3IPUIT3.js} +2 -2
- package/dist/cli/chunks/{chunk-KT2QCXO6.js → chunk-L7PSU2YN.js} +2 -2
- package/dist/cli/chunks/{chunk-HAQJFUAQ.js → chunk-LA3JPGQA.js} +2 -2
- package/dist/cli/chunks/{chunk-LV7UIK4Q.js → chunk-LC2QRN7V.js} +14 -13
- package/dist/cli/chunks/{chunk-KTORRIX3.js → chunk-LHY7TMTM.js} +2 -2
- package/dist/cli/chunks/{chunk-IJSROBM6.js → chunk-LLQ2UMF6.js} +3 -3
- package/dist/cli/chunks/{chunk-NKUHMA4T.js → chunk-LOJ7OO6W.js} +2 -2
- package/dist/cli/chunks/{chunk-OJIUIEI4.js → chunk-LPUSH3VF.js} +1 -1
- package/dist/cli/chunks/{chunk-WAOEQA3W.js → chunk-LSEC2BU7.js} +2 -2
- package/dist/cli/chunks/{chunk-YMUY3TES.js → chunk-LTGB7OIU.js} +2 -2
- package/dist/cli/chunks/{chunk-CVYPMGUM.js → chunk-LUG7YNVZ.js} +2 -2
- package/dist/cli/chunks/{chunk-YAJOBZE5.js → chunk-LWAFRYKE.js} +2 -2
- package/dist/cli/chunks/{chunk-ZP5AWQRO.js → chunk-M24ZAZ4U.js} +2 -2
- package/dist/cli/chunks/{chunk-HFZD5KLR.js → chunk-MKRKRXTX.js} +1 -1
- package/dist/cli/chunks/{chunk-4YM45Z5B.js → chunk-MNNLONAD.js} +1 -1
- package/dist/cli/chunks/{chunk-CMN7PU2H.js → chunk-MQM37KAR.js} +2 -2
- package/dist/cli/chunks/{chunk-COTQ44YO.js → chunk-MSX2OHYT.js} +2 -2
- package/dist/cli/chunks/{chunk-4UKTIQDT.js → chunk-MVYQRVLP.js} +2 -2
- package/dist/cli/chunks/{chunk-HRUHHHVR.js → chunk-MZC5WM2P.js} +2 -2
- package/dist/cli/chunks/{chunk-YKRLUTK7.js → chunk-MZRBNBB3.js} +2 -2
- package/dist/cli/chunks/{chunk-XEMCHGAJ.js → chunk-N3KQU4UC.js} +2 -2
- package/dist/cli/chunks/{chunk-DS5IFRY6.js → chunk-NKU3FFM4.js} +2 -2
- package/dist/cli/chunks/chunk-O5EWFR76.js +2 -0
- package/dist/cli/chunks/{chunk-J3QFJI2Y.js → chunk-O5RDHD5T.js} +2 -2
- package/dist/cli/chunks/chunk-O6UWIXME.js +3 -0
- package/dist/cli/chunks/{chunk-Q6F3DYZN.js → chunk-OA4EQDC4.js} +2 -2
- package/dist/cli/chunks/{chunk-NQFDJ6BT.js → chunk-OBCXCRXK.js} +1 -1
- package/dist/cli/chunks/{chunk-S3TBOKAZ.js → chunk-OHU5P25N.js} +4 -4
- package/dist/cli/chunks/{chunk-DNVRTJKB.js → chunk-OOSV2RIA.js} +2 -2
- package/dist/cli/chunks/{chunk-NZJVDOUN.js → chunk-OW23N2Y5.js} +2 -2
- package/dist/cli/chunks/{chunk-ZWUF27P4.js → chunk-OXOO3YDL.js} +2 -2
- package/dist/cli/chunks/{chunk-4L6WX5KC.js → chunk-OYGKSSSI.js} +1 -1
- package/dist/cli/chunks/{chunk-DCDSN67A.js → chunk-PGO46IIW.js} +1 -1
- package/dist/cli/chunks/{chunk-C7QLLMYI.js → chunk-PZOYQHWS.js} +1 -1
- package/dist/cli/chunks/{chunk-BKHEQIRZ.js → chunk-Q2BZSG7Z.js} +2 -2
- package/dist/cli/chunks/{chunk-5FSPELOG.js → chunk-Q7V722K5.js} +2 -2
- package/dist/cli/chunks/{chunk-2EQK7B5L.js → chunk-QZU6M5IO.js} +2 -2
- package/dist/cli/chunks/{chunk-HVT7RMGV.js → chunk-R55Y76SJ.js} +1 -1
- package/dist/cli/chunks/{chunk-POPSZDI2.js → chunk-RMEQYJPU.js} +4 -4
- package/dist/cli/chunks/{chunk-H2LHWZRE.js → chunk-RTYXFXTI.js} +2 -2
- package/dist/cli/chunks/{chunk-QN7HP2UW.js → chunk-SJF3O4FX.js} +236 -236
- package/dist/cli/chunks/{chunk-2YWYW7NU.js → chunk-SOUS7Z2H.js} +2 -2
- package/dist/cli/chunks/{chunk-U5SMBJ6F.js → chunk-SRVNR3R3.js} +2 -2
- package/dist/cli/chunks/{chunk-ZAQMRFBB.js → chunk-SU3SXMVG.js} +2 -2
- package/dist/cli/chunks/chunk-SWGPLXWW.js +32 -0
- package/dist/cli/chunks/{chunk-S3DT5TPR.js → chunk-TRB3EVH3.js} +2 -2
- package/dist/cli/chunks/{chunk-IJZFJPHS.js → chunk-TVBDUMKT.js} +2 -2
- package/dist/cli/chunks/{chunk-7SNSI4VY.js → chunk-TWTXPSFU.js} +1 -1
- package/dist/cli/chunks/{chunk-ORQ2YBRR.js → chunk-ULYUVUL2.js} +2 -2
- package/dist/cli/chunks/{chunk-MVVVGQJ6.js → chunk-UNTBVJ5X.js} +2 -2
- package/dist/cli/chunks/{chunk-5WATBVU6.js → chunk-UQAA4PHU.js} +2 -2
- package/dist/cli/chunks/{chunk-5WYZVSL2.js → chunk-UWSJVKTE.js} +1 -1
- package/dist/cli/chunks/{chunk-JHKKIJT2.js → chunk-V2LJ54KP.js} +2 -2
- package/dist/cli/chunks/{chunk-2UUZCQSD.js → chunk-VCCTTKP3.js} +2 -2
- package/dist/cli/chunks/{chunk-P4OB6WDJ.js → chunk-VEGUYUVS.js} +1 -1
- package/dist/cli/chunks/{chunk-WX4PO65Q.js → chunk-VUQPVWNK.js} +2 -2
- package/dist/cli/chunks/{chunk-IQL6XRF5.js → chunk-VVGUE2T2.js} +2 -2
- package/dist/cli/chunks/{chunk-HZ5O7G2P.js → chunk-W5ASDHJQ.js} +1 -1
- package/dist/cli/chunks/{chunk-U4S74IIZ.js → chunk-WGXT5NWQ.js} +1 -1
- package/dist/cli/chunks/chunk-WJN3V7QB.js +7 -0
- package/dist/cli/chunks/chunk-WPCRQIIF.js +29 -0
- package/dist/cli/chunks/{chunk-AGCS5GSO.js → chunk-WQNLXUWA.js} +6 -6
- package/dist/cli/chunks/{chunk-LRY6UIRI.js → chunk-WZVRMKG2.js} +2 -2
- package/dist/cli/chunks/{chunk-KPIPVSIP.js → chunk-X27IUWTD.js} +2 -2
- package/dist/cli/chunks/{chunk-VDEKVIP5.js → chunk-X4B345B6.js} +2 -2
- package/dist/cli/chunks/{chunk-ERYADKMZ.js → chunk-X5I2Y4VO.js} +2 -2
- package/dist/cli/chunks/{chunk-EUWG2JG4.js → chunk-X7IQIFTS.js} +2 -2
- package/dist/cli/chunks/chunk-XJN3RKUD.js +3 -0
- package/dist/cli/chunks/{chunk-JRIJM4LE.js → chunk-XQMGXTHJ.js} +3 -3
- package/dist/cli/chunks/{chunk-VYPVU3JF.js → chunk-XTSAMB2Q.js} +2 -2
- package/dist/cli/chunks/{chunk-4NKZU2JZ.js → chunk-XZLIF4O2.js} +2 -2
- package/dist/cli/chunks/{chunk-XFTX3KLE.js → chunk-Y4LSEOZ3.js} +1 -1
- package/dist/cli/chunks/{chunk-ZVMSSCTH.js → chunk-Y4YN2RXR.js} +2 -2
- package/dist/cli/chunks/{chunk-X5QD76IU.js → chunk-YDI56L35.js} +2 -2
- package/dist/cli/chunks/{chunk-LRKLATSH.js → chunk-YFILS5D5.js} +2 -2
- package/dist/cli/chunks/{chunk-AVHYJ3XP.js → chunk-YISDX6WB.js} +2 -2
- package/dist/cli/chunks/{chunk-GPPTRKEM.js → chunk-YP2GHQSV.js} +2 -2
- package/dist/cli/chunks/{chunk-OO2M2QUV.js → chunk-YSX756AM.js} +4 -4
- package/dist/cli/chunks/{chunk-E7XIMOKW.js → chunk-YWANOASW.js} +2 -2
- package/dist/cli/chunks/{chunk-UHJVZEQA.js → chunk-YYIJLG7S.js} +2 -2
- package/dist/cli/chunks/{chunk-LCWEQRZI.js → chunk-Z7SD7LXM.js} +2 -2
- package/dist/cli/chunks/{chunk-TM75GAXG.js → chunk-ZDWD73UF.js} +2 -2
- package/dist/cli/chunks/{chunk-IRHXGCQR.js → chunk-ZFT3RLA4.js} +2 -2
- package/dist/cli/chunks/{chunk-ZGV7L4MW.js → chunk-ZNTHX5G3.js} +1 -1
- package/dist/cli/chunks/{chunk-D75GLKEL.js → chunk-ZS27R7VL.js} +2 -2
- package/dist/cli/chunks/{chunk-INI3Q4CN.js → chunk-ZXHHHR7K.js} +1 -1
- package/dist/cli/chunks/{ci-3RTTTS2D.js → ci-N5MOMNXH.js} +2 -2
- package/dist/cli/chunks/{ci-config-XRUR3I4K.js → ci-config-6L2ROQCW.js} +2 -2
- package/dist/cli/chunks/{ci-output-E5IAMU2U.js → ci-output-DSRBYEIK.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-SHR2P44P.js → circuit-breaker-VRPTNBL7.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-ZDDILFMF.js → claude-flow-setup-4YFG3FU5.js} +2 -2
- package/dist/cli/chunks/client-I3L6BKRQ.js +2 -0
- package/dist/cli/chunks/{cline-installer-BGYVUM6G.js → cline-installer-7RGYJWGN.js} +2 -2
- package/dist/cli/chunks/{code-PJ4MC3MC.js → code-ISC6NW2K.js} +3 -3
- package/dist/cli/chunks/{code-index-extractor-IW2P22YG.js → code-index-extractor-2FID75YV.js} +2 -2
- package/dist/cli/chunks/{codex-installer-A7WZ6OGL.js → codex-installer-DZ7OG6KM.js} +2 -2
- package/dist/cli/chunks/{completions-KS23WD5J.js → completions-SM3LICWK.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-Q7GLSR2E.js → complexity-analyzer-ZWD2CTAD.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-SK55BFW2.js → continuedev-installer-AGASOA26.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-3N5J3WTM.js → copilot-installer-CLPZYTQC.js} +2 -2
- package/dist/cli/chunks/core-handlers-5EFOJ37H.js +2 -0
- package/dist/cli/chunks/{cost-tracker-NENVSO4A.js → cost-tracker-7PIGQYDV.js} +2 -2
- package/dist/cli/chunks/{coverage-5L7UQWDH.js → coverage-T2GEBTYS.js} +9 -9
- package/dist/cli/chunks/cross-domain-router-65WJAKVD.js +2 -0
- package/dist/cli/chunks/{cursor-installer-XXBO2ZE6.js → cursor-installer-KXBID4MB.js} +2 -2
- package/dist/cli/chunks/daemon-43MXIVH3.js +18 -0
- package/dist/cli/chunks/{daemon-CDCQU3LR.js → daemon-VAMJLQJ5.js} +3 -3
- package/dist/cli/chunks/{dag-attention-scheduler-HOMMF7FA.js → dag-attention-scheduler-UBP4VHTA.js} +2 -2
- package/dist/cli/chunks/{detect-FXCOUG6X.js → detect-QWFIQRKI.js} +2 -2
- package/dist/cli/chunks/{dist-node-GXQ7FMTY.js → dist-node-I2GICS3W.js} +2 -2
- package/dist/cli/chunks/{domain-handler-TI3JBAPC.js → domain-handler-Z66ISB2A.js} +2 -2
- package/dist/cli/chunks/{domain-plugins-R7LTUM32.js → domain-plugins-KHMD3FKT.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-LBIAFHIQ.js → domain-transfer-JWGNNA6K.js} +2 -2
- package/dist/cli/chunks/dream-VQ2PZCVR.js +2 -0
- package/dist/cli/chunks/embed-and-insert-pattern-F5P5B6JX.js +3 -0
- package/dist/cli/chunks/{embedding-space-HHLWTBF5.js → embedding-space-KHG6TITM.js} +2 -2
- package/dist/cli/chunks/{eval-KDOZMAXJ.js → eval-43OHU7EI.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-X45PECQN.js → experience-capture-middleware-KXD47H6P.js} +3 -3
- package/dist/cli/chunks/{fast-paths-462V6UUB.js → fast-paths-6D75D5KD.js} +2 -2
- package/dist/cli/chunks/{feature-flags-NIRQ4YDM.js → feature-flags-IE35Y55N.js} +2 -2
- package/dist/cli/chunks/{feature-flags-G66OT3AS.js → feature-flags-OYYHY7LS.js} +2 -2
- package/dist/cli/chunks/file-discovery-LGBTY3ID.js +2 -0
- package/dist/cli/chunks/{fleet-PXWGB7CU.js → fleet-AGVJMFGD.js} +16 -16
- package/dist/cli/chunks/{gnn-wrapper-7MUW3M5M.js → gnn-wrapper-5L66A7LW.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-5237PB35.js → heartbeat-handler-2BY6YYOT.js} +5 -5
- package/dist/cli/chunks/heartbeat-scheduler-3DU3M5AT.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-N2IMSRPV.js +2 -0
- package/dist/cli/chunks/hnsw-index-DVU7TTJE.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-OSQPW7JP.js → hnsw-legacy-bridge-RYMWFNAH.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-GX6WG2GB.js → hnswlib-node-GG47HP2P.js} +2 -2
- package/dist/cli/chunks/{hooks-GUWHL7VC.js → hooks-FQNACS24.js} +10 -10
- package/dist/cli/chunks/hybrid-backend-AS2PNHOD.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-SRWLLCU3.js → hypergraph-engine-6BYNJQEP.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-AVOPRHHO.js → hypergraph-handler-CYTAXZKJ.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-Y4OONLFP.js +2 -0
- package/dist/cli/chunks/{init-guard-P4N6EVZS.js → init-guard-METTAV5O.js} +2 -2
- package/dist/cli/chunks/{init-handler-LRGWOJMD.js → init-handler-GFT74U5Y.js} +6 -6
- package/dist/cli/chunks/init-wizard-HLNUBJQN.js +2 -0
- package/dist/cli/chunks/kernel-XKFWCL7Y.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-7R2EPOQ6.js → kilocode-installer-GZV2D3FF.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-QNM7DPOB.js → kiro-installer-Q4ZXUFC7.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-CNL77CSZ.js +2 -0
- package/dist/cli/chunks/{learning-7OIZBPXZ.js → learning-WA2QEYL7.js} +35 -34
- package/dist/cli/chunks/{llm-router-SIDXES23.js → llm-router-GRTCHWH7.js} +4 -4
- package/dist/cli/chunks/llm-router-service-UIYTYKP6.js +2 -0
- package/dist/cli/chunks/{load-EI2E2C3S.js → load-WXN3Q7Y5.js} +2 -2
- package/dist/cli/chunks/load-test-PXLW4A5B.js +2 -0
- package/dist/cli/chunks/{mcp-IOE5WOCS.js → mcp-LIQCPSJN.js} +2 -2
- package/dist/cli/chunks/{memory-DLYGJAP7.js → memory-OP6CHRFH.js} +5 -5
- package/dist/cli/chunks/memory-backend-XYOSO73Q.js +2 -0
- package/dist/cli/chunks/memory-handlers-PQFYVNVG.js +2 -0
- package/dist/cli/chunks/{multi-model-executor-WHH4YCHM.js → multi-model-executor-H54DEVRZ.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-63FDZAMS.js → opencode-installer-BSQV6UAT.js} +2 -2
- package/dist/cli/chunks/{orchestrator-3LA776KK.js → orchestrator-TJDPQ4VL.js} +122 -35
- package/dist/cli/chunks/pattern-null-store-BKGTQFNF.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-NW54QUGI.js → pattern-usage-recorder-FOVS4M5L.js} +2 -2
- package/dist/cli/chunks/{pipeline-P3TYX6J6.js → pipeline-4AY2ZIC6.js} +2 -2
- package/dist/cli/chunks/{platform-FNA2WLI6.js → platform-FCSITYMR.js} +2 -2
- package/dist/cli/chunks/{plugin-NJS7BC2S.js → plugin-E56TV5S2.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-NIAVL2OT.js → prime-radiant-advanced-wasm-ACOPC533.js} +2 -2
- package/dist/cli/chunks/project-root-MPX7CN2C.js +2 -0
- package/dist/cli/chunks/protocol-executor-CRQOCC4A.js +2 -0
- package/dist/cli/chunks/{protocol-handler-JU5C4JHY.js → protocol-handler-KRVXF4LS.js} +2 -2
- package/dist/cli/chunks/{prove-35VOSLYP.js → prove-KMFPSKGD.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-UEGQ3O7F.js +2 -0
- package/dist/cli/chunks/{quality-ET74X7HN.js → quality-6DBI3HLB.js} +2 -2
- package/dist/cli/chunks/{quality-gate-FEDQISNB.js → quality-gate-3ROZMEIL.js} +3 -3
- package/dist/cli/chunks/queen-coordinator-32574XSG.js +2 -0
- package/dist/cli/chunks/real-embeddings-MIGZNKK3.js +2 -0
- package/dist/cli/chunks/{ref-validation-DTBPYCEB.js → ref-validation-EYIP7DHW.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-LYQEMR4J.js → roocode-installer-IGGZHR2Y.js} +2 -2
- package/dist/cli/chunks/router-CZJY5WX6.js +2 -0
- package/dist/cli/chunks/routing-feedback-RC3UBNFX.js +2 -0
- package/dist/cli/chunks/{routing-handler-DJOJFPII.js → routing-handler-BWNHBYDC.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-VXYGJDPW.js → ruvector-commands-PXIHF432.js} +2 -2
- package/dist/cli/chunks/rvf-dual-writer-OG7OV2AK.js +2 -0
- package/dist/cli/chunks/rvf-migration-adapter-THYMW7ZO.js +2 -0
- package/dist/cli/chunks/rvf-migration-coordinator-3H6CLFU7.js +2 -0
- package/dist/cli/chunks/rvf-native-adapter-6JQJIKKW.js +2 -0
- package/dist/cli/chunks/{rvf-store-integrity-GA2ZYOEG.js → rvf-store-integrity-CVB3NMSL.js} +2 -2
- package/dist/cli/chunks/safe-db-QFKCVTIJ.js +2 -0
- package/dist/cli/chunks/schedule-6JLVMMYB.js +2 -0
- package/dist/cli/chunks/scheduler-3MPZRMJD.js +2 -0
- package/dist/cli/chunks/{security-MM6YOECX.js → security-DCRGOTWU.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-6AHPA3V5.js → shared-rvf-adapter-GKD74QUB.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-EYAVY2GZ.js → shared-rvf-dual-writer-HVAAVEOH.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-LGTIKAEX.js +2 -0
- package/dist/cli/chunks/{standalone-memory-A3PLB4CZ.js → standalone-memory-O7O2U5N4.js} +2 -2
- package/dist/cli/chunks/{status-handler-OSSFAP4Z.js → status-handler-BQTPJJTL.js} +2 -2
- package/dist/cli/chunks/{structural-health-PGY5XUNO.js → structural-health-4H6J4OHK.js} +2 -2
- package/dist/cli/chunks/sync-DJ4TF6QX.js +2 -0
- package/dist/cli/chunks/{sync-CWEHYGNN.js → sync-WW5TAVYW.js} +2 -2
- package/dist/cli/chunks/{task-handler-LHMQ75W4.js → task-handler-HEM4IEOW.js} +2 -2
- package/dist/cli/chunks/{task-handlers-S2TX5FTR.js → task-handlers-JRA3NXIR.js} +3 -3
- package/dist/cli/chunks/{test-4EGZZ6NJ.js → test-772ZXVG2.js} +4 -4
- package/dist/cli/chunks/test-runner-process-XGF2U3NG.js +2 -0
- package/dist/cli/chunks/{test-scheduling-YJQHH3XE.js → test-scheduling-4TRB7LZ7.js} +3 -3
- package/dist/cli/chunks/token-bootstrap-CICBIJ7T.js +2 -0
- package/dist/cli/chunks/{token-usage-WPNOJR6H.js → token-usage-B7PEKE2G.js} +2 -2
- package/dist/cli/chunks/{transformers-4MRPXCPU.js → transformers-V7X7BDZX.js} +2 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-OXPFKFZS.js +2 -0
- package/dist/cli/chunks/{types-6P5FB4EB.js → types-AHHTUY3I.js} +2 -2
- package/dist/cli/chunks/unified-memory-GUR3IUI6.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-NJP2F2RY.js +2 -0
- package/dist/cli/chunks/unified-persistence-NILBWXDP.js +2 -0
- package/dist/cli/chunks/{upgrade-4ICTN63Y.js → upgrade-DZ4DLUQ5.js} +2 -2
- package/dist/cli/chunks/{validate-HQF5GZ7L.js → validate-4DTLIDJE.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-45JYG7VW.js → validate-swarm-A26UFVIS.js} +2 -2
- package/dist/cli/chunks/visual-security-YECYZ27X.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-UOTWZLNH.js → web-tree-sitter-F2C7QRYT.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-WDWSBXGN.js → windsurf-installer-OOBTDA6W.js} +2 -2
- package/dist/cli/chunks/{witness-chain-DOYMNPC7.js → witness-chain-KGFZJP32.js} +2 -2
- package/dist/cli/chunks/witness-chain-LYBXFLJB.js +2 -0
- package/dist/cli/chunks/witness-chain-repair-CNTXOGPN.js +2 -0
- package/dist/cli/chunks/{witness-chain-verifier-JB42X62J.js → witness-chain-verifier-OB7ZZOI3.js} +2 -2
- package/dist/cli/chunks/{witness-key-manager-LXXO6L2G.js → witness-key-manager-YCKGKGQI.js} +2 -2
- package/dist/cli/chunks/{workflow-6ARK47NF.js → workflow-PRERHWKY.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-UIBGWCU3.js +2 -0
- package/dist/cli/chunks/wrappers-L4UY4V63.js +2 -0
- package/dist/cli/commands/coverage.js +4 -1
- package/dist/cli/commands/learning-prune.js +9 -1
- package/dist/cli/handlers/brain-handler.js +32 -2
- package/dist/cli/handlers/heartbeat-handler.js +3 -1
- package/dist/cli/utils/coverage-data.js +5 -1
- package/dist/cli/utils/coverage-verdict.d.ts +10 -2
- package/dist/cli/utils/coverage-verdict.js +23 -8
- package/dist/cli/utils/fleet-operation.js +9 -3
- package/dist/coordination/handlers/code-intelligence-handlers.js +17 -3
- package/dist/coordination/handlers/coverage-handlers.js +22 -9
- package/dist/coordination/handlers/coverage-target.d.ts +22 -2
- package/dist/coordination/handlers/coverage-target.js +45 -9
- package/dist/coordination/handlers/handler-utils.d.ts +19 -0
- package/dist/coordination/handlers/handler-utils.js +22 -8
- package/dist/coordination/protocols/code-intelligence-index.js +6 -3
- package/dist/coordination/protocols/learning-consolidation-archive.d.ts +6 -3
- package/dist/coordination/protocols/learning-consolidation-archive.js +4 -3
- package/dist/coordination/workflow-builtin.js +1 -0
- package/dist/domains/defect-intelligence/interfaces.d.ts +2 -0
- package/dist/domains/defect-intelligence/prediction-history.d.ts +15 -1
- package/dist/domains/defect-intelligence/prediction-history.js +63 -7
- package/dist/domains/defect-intelligence/services/defect-predictor.d.ts +1 -0
- package/dist/domains/defect-intelligence/services/defect-predictor.js +33 -13
- package/dist/domains/learning-optimization/coordinator.js +17 -10
- package/dist/domains/learning-optimization/domain-ranking.d.ts +26 -0
- package/dist/domains/learning-optimization/domain-ranking.js +28 -0
- package/dist/domains/learning-optimization/interfaces.d.ts +5 -0
- package/dist/domains/learning-optimization/pattern-archive.d.ts +55 -8
- package/dist/domains/learning-optimization/pattern-archive.js +90 -17
- package/dist/domains/learning-optimization/pattern-consolidation.js +18 -2
- package/dist/domains/learning-optimization/pattern-merge.d.ts +26 -0
- package/dist/domains/learning-optimization/pattern-merge.js +127 -0
- package/dist/domains/learning-optimization/services/learning-coordinator.js +21 -35
- package/dist/domains/test-execution/services/test-executor.js +6 -2
- package/dist/init/init-wizard-steps.js +3 -1
- package/dist/init/phases/07-hooks.js +97 -10
- package/dist/integrations/embeddings/cache/EmbeddingCache.js +1 -1
- package/dist/integrations/ruvector/brain-rvf-exporter.d.ts +16 -1
- package/dist/integrations/ruvector/brain-rvf-exporter.js +18 -32
- package/dist/integrations/ruvector/brain-rvf-richness.d.ts +75 -0
- package/dist/integrations/ruvector/brain-rvf-richness.js +127 -0
- package/dist/kernel/unified-memory-migration.js +1 -1
- package/dist/learning/checkpoint-shrink-ack.d.ts +25 -0
- package/dist/learning/checkpoint-shrink-ack.js +57 -0
- package/dist/learning/dream/dream-engine.d.ts +44 -3
- package/dist/learning/dream/dream-engine.js +6 -2
- package/dist/learning/embedder-identity-store.js +3 -1
- package/dist/learning/embedding-space-legacy-adoption.d.ts +53 -0
- package/dist/learning/embedding-space-legacy-adoption.js +115 -0
- package/dist/learning/embedding-space-registry.d.ts +15 -0
- package/dist/learning/embedding-space-registry.js +50 -11
- package/dist/learning/experience-capture.d.ts +3 -1
- package/dist/learning/experience-capture.js +15 -5
- package/dist/learning/experience-space-verification.d.ts +2 -0
- package/dist/learning/experience-space-verification.js +3 -2
- package/dist/learning/learning-retention.js +4 -0
- package/dist/learning/pattern-promotion.d.ts +7 -0
- package/dist/learning/pattern-promotion.js +64 -12
- package/dist/learning/real-embeddings.js +31 -7
- package/dist/learning/rvf-pattern-store.js +6 -1
- package/dist/mcp/bundle.js +570 -558
- package/dist/mcp/handlers/domain-handler-configs.d.ts +3 -0
- package/dist/mcp/handlers/domain-handler-configs.js +1 -0
- package/dist/mcp/handlers/heartbeat-handlers.d.ts +4 -2
- package/dist/mcp/tools/learning-optimization/optimize.d.ts +6 -1
- package/dist/mcp/tools/learning-optimization/optimize.js +20 -11
- package/dist/planning/goap-planner.js +4 -0
- package/dist/planning/plan-executor.js +6 -2
- package/dist/shared/git/git-analyzer.d.ts +30 -11
- package/dist/shared/git/git-analyzer.js +95 -48
- package/dist/shared/io/confined-read.d.ts +32 -7
- package/dist/shared/io/confined-read.js +58 -25
- package/dist/shared/io/file-reader.js +4 -1
- package/dist/shared/safe-db.d.ts +1 -1
- package/dist/shared/safe-db.js +20 -5
- package/dist/shared/sqlite-journal-mode.d.ts +39 -0
- package/dist/shared/sqlite-journal-mode.js +53 -0
- package/dist/sync/claude-flow-bridge.js +1 -1
- package/dist/sync/readers/sqlite-reader.js +3 -4
- package/dist/sync/writers/sqlite-writer.js +1 -1
- package/dist/workers/interfaces.d.ts +2 -2
- package/dist/workers/quality-daemon/git-watcher.d.ts +8 -0
- package/dist/workers/quality-daemon/git-watcher.js +54 -12
- package/dist/workers/quality-daemon/index.js +1 -1
- package/dist/workers/quality-daemon/priority-queue.d.ts +2 -1
- package/dist/workers/workers/defect-predictor.d.ts +9 -4
- package/dist/workers/workers/defect-predictor.js +98 -37
- package/package.json +1 -1
- package/dist/cli/chunks/adapter-OMILP6KH.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-OXH5CCOS.js +0 -2
- package/dist/cli/chunks/base-MAK2BLTG.js +0 -2
- package/dist/cli/chunks/brain-handler-GCQZFZGQ.js +0 -95
- package/dist/cli/chunks/browser-workflow-IR3VF2TL.js +0 -2
- package/dist/cli/chunks/chunk-4EJLHNER.js +0 -12
- package/dist/cli/chunks/chunk-A4BVDYIL.js +0 -2
- package/dist/cli/chunks/chunk-BE7ZHM34.js +0 -3
- package/dist/cli/chunks/chunk-DHKSPOUQ.js +0 -16
- package/dist/cli/chunks/chunk-FAQ24UHB.js +0 -29
- package/dist/cli/chunks/chunk-IOWEBPXJ.js +0 -5
- package/dist/cli/chunks/chunk-KB34MTFZ.js +0 -3
- package/dist/cli/chunks/chunk-MCXW3DKE.js +0 -8
- package/dist/cli/chunks/chunk-O7VJ3VKD.js +0 -2
- package/dist/cli/chunks/chunk-PIWGKGWP.js +0 -3
- package/dist/cli/chunks/chunk-SFITYZLV.js +0 -7
- package/dist/cli/chunks/chunk-TIVKDIF7.js +0 -2
- package/dist/cli/chunks/client-NO5FOWT4.js +0 -2
- package/dist/cli/chunks/core-handlers-JNAZPXE2.js +0 -2
- package/dist/cli/chunks/cross-domain-router-HEBM767Z.js +0 -2
- package/dist/cli/chunks/daemon-JEBJGEUK.js +0 -18
- package/dist/cli/chunks/dream-GQDCEJMS.js +0 -2
- package/dist/cli/chunks/embed-and-insert-pattern-33KLHDD5.js +0 -3
- package/dist/cli/chunks/file-discovery-33USPLB5.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-LIXLC5IH.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-62D5UH27.js +0 -2
- package/dist/cli/chunks/hnsw-index-GSGUMQQC.js +0 -2
- package/dist/cli/chunks/hybrid-backend-FRWP4BOY.js +0 -2
- package/dist/cli/chunks/impact-analyzer-7KF3AQXV.js +0 -2
- package/dist/cli/chunks/init-wizard-XWWAXY25.js +0 -2
- package/dist/cli/chunks/kernel-ZEJPNDBW.js +0 -2
- package/dist/cli/chunks/knowledge-graph-RRZQS7KY.js +0 -2
- package/dist/cli/chunks/llm-router-service-3OSW67LC.js +0 -2
- package/dist/cli/chunks/load-test-7TRIH2WJ.js +0 -2
- package/dist/cli/chunks/memory-backend-G7ZW6Q2B.js +0 -2
- package/dist/cli/chunks/memory-handlers-TPF3KCO5.js +0 -2
- package/dist/cli/chunks/pattern-null-store-OU3ZC3NR.js +0 -2
- package/dist/cli/chunks/project-root-GMOFJEKD.js +0 -2
- package/dist/cli/chunks/protocol-executor-AD345XRO.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-NLTP26RC.js +0 -2
- package/dist/cli/chunks/queen-coordinator-2TB4FWS6.js +0 -2
- package/dist/cli/chunks/real-embeddings-II6CXTCI.js +0 -2
- package/dist/cli/chunks/router-PLM3MWME.js +0 -2
- package/dist/cli/chunks/routing-feedback-I7VOX2HU.js +0 -2
- package/dist/cli/chunks/rvf-dual-writer-GQZHFWO2.js +0 -2
- package/dist/cli/chunks/rvf-migration-adapter-3TVKBCAM.js +0 -2
- package/dist/cli/chunks/rvf-migration-coordinator-XUHKLMT6.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-5GUTYOWS.js +0 -2
- package/dist/cli/chunks/safe-db-RZPQGLGQ.js +0 -2
- package/dist/cli/chunks/schedule-G7JMQDUX.js +0 -2
- package/dist/cli/chunks/scheduler-4SEGPCKD.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-IVE4SQXR.js +0 -2
- package/dist/cli/chunks/sync-PM6D7EQF.js +0 -2
- package/dist/cli/chunks/test-runner-process-72YACW6M.js +0 -2
- package/dist/cli/chunks/token-bootstrap-DJNETMVW.js +0 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-UVWSDXFR.js +0 -2
- package/dist/cli/chunks/unified-memory-2VMGSGQL.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-3KULVD3N.js +0 -2
- package/dist/cli/chunks/unified-persistence-QCSLU2SV.js +0 -2
- package/dist/cli/chunks/visual-security-ZYP2KPH7.js +0 -2
- package/dist/cli/chunks/witness-chain-5QRT7EMX.js +0 -2
- package/dist/cli/chunks/witness-chain-repair-CUF2AFQB.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-RYDDWIXN.js +0 -2
- package/dist/cli/chunks/wrappers-CYQBOMPL.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as we}from"./chunk-MGZ6XZHU.js";import{a as Dt}from"./chunk-P3D7SEHW.js";import{a as kt,b as St}from"./chunk-PCL5JRKN.js";import{a as Ct,b as bt}from"./chunk-776K4ZLE.js";import{j as _}from"./chunk-RKCN4B26.js";import{a as ft}from"./chunk-74MDUIAZ.js";import{a as Tt,b as Ee,c as vt}from"./chunk-MVVVGQJ6.js";import{a as xe}from"./chunk-XFTX3KLE.js";import{b as yt}from"./chunk-IKB3M7OF.js";import{i as C}from"./chunk-XPTCQKVE.js";import{C as Ae,w as R}from"./chunk-NZJVDOUN.js";import{b as I,d as pt}from"./chunk-CMN7PU2H.js";import{a as ht,e as xn}from"./chunk-YKRLUTK7.js";import{c as De,d as An}from"./chunk-LRKLATSH.js";import{a as v,c as y,d as f}from"./chunk-REY52O7J.js";import{a as Dn}from"./chunk-TIVKDIF7.js";import{c as gt}from"./chunk-DS5IFRY6.js";import{R as kn,S as Sn}from"./chunk-JHKKIJT2.js";import{a as h,b as Z,e as k}from"./chunk-J7Q5TXFZ.js";import{b as Y,d as bn,f as mt}from"./chunk-Z7SKUC6P.js";function wt(s){let e=[],t=0;if(s.fileCount!==void 0&&(s.fileCount>20?(t+=25,e.push({name:"very-high-file-count",weight:25,description:`Task involves ${s.fileCount} files (>20)`})):s.fileCount>10?(t+=20,e.push({name:"high-file-count",weight:20,description:`Task involves ${s.fileCount} files (>10)`})):s.fileCount>5&&(t+=10,e.push({name:"moderate-file-count",weight:10,description:`Task involves ${s.fileCount} files (>5)`}))),s.domain&&(Mn.includes(s.domain)?(t+=30,e.push({name:"complex-domain",weight:30,description:`Domain '${s.domain}' requires complex reasoning`})):In.includes(s.domain)&&(t+=15,e.push({name:"moderate-domain",weight:15,description:`Domain '${s.domain}' has moderate complexity`}))),s.crossComponent&&(t+=25,e.push({name:"cross-component",weight:25,description:"Task spans multiple components/modules"})),s.priority==="critical"?(t+=25,e.push({name:"critical-priority",weight:25,description:"Critical priority requires careful attention"})):s.priority==="high"&&(t+=15,e.push({name:"high-priority",weight:15,description:"High priority task"})),s.requiredCapabilities){let r=s.requiredCapabilities.filter(a=>Rn.includes(a)).length;if(r>0){let a=Math.min(20,r*10);t+=a,e.push({name:"complex-capabilities",weight:a,description:`Requires ${r} complex capabilit${r===1?"y":"ies"}`})}}s.requiresExternalApis&&(t+=10,e.push({name:"external-apis",weight:10,description:"Requires external API integration"})),s.involvesDatabaseOps&&(t+=10,e.push({name:"database-ops",weight:10,description:"Involves database operations"})),s.timeSensitive&&(t+=5,e.push({name:"time-sensitive",weight:5,description:"Time-sensitive task"})),s.estimatedLinesAffected!==void 0&&(s.estimatedLinesAffected>500?(t+=15,e.push({name:"large-change",weight:15,description:`Estimated ${s.estimatedLinesAffected} lines affected (>500)`})):s.estimatedLinesAffected>200&&(t+=10,e.push({name:"medium-change",weight:10,description:`Estimated ${s.estimatedLinesAffected} lines affected (>200)`}))),(s.type==="security-scan"||s.type==="vulnerability-assessment")&&(t+=20,e.push({name:"security-task",weight:20,description:"Security-related task requires careful analysis"}));let n=t>=S.critical?"critical":t>=S.complex?"complex":t>=S.moderate?"moderate":"simple",i=_n[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var Mn,In,Rn,S,_n,Mt=Y(()=>{"use strict";Mn=["security-compliance","chaos-resilience","defect-intelligence"],In=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],Rn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},_n={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var P,_e=Y(()=>{"use strict";P=class{weightsInputHidden;weightsHiddenOutput;biasHidden;biasOutput;learningRate;constructor(e=.01){this.learningRate=e,this.weightsInputHidden=this.xavierInit(4,32),this.weightsHiddenOutput=this.xavierInit(32,3),this.biasHidden=new Float32Array(32),this.biasOutput=new Float32Array(3)}xavierInit(e,t){let n=Math.sqrt(2/(e+t)),i=new Float32Array(e*t);for(let r=0;r<i.length;r++){let a=Math.random(),o=Math.random(),l=Math.sqrt(-2*Math.log(Math.max(a,1e-10)))*Math.cos(2*Math.PI*o);i[r]=l*n}return i}forward(e){if(e.length!==4)throw new Error(`Expected 4 features, got ${e.length}`);let t=new Float32Array(32);for(let i=0;i<32;i++){let r=this.biasHidden[i];for(let a=0;a<4;a++)r+=e[a]*this.weightsInputHidden[a*32+i];t[i]=Math.max(0,r)}let n=new Float32Array(3);for(let i=0;i<3;i++){let r=this.biasOutput[i];for(let a=0;a<32;a++)r+=t[a]*this.weightsHiddenOutput[a*3+i];n[i]=r}return this.softmax(n)}softmax(e){let t=Math.max(...e),n=new Float32Array(e.length),i=0;for(let a=0;a<e.length;a++)n[a]=Math.exp(e[a]-t),i+=n[a];let r=[];for(let a=0;a<e.length;a++)r.push(n[a]/i);return r}updateWeights(e,t,n){let i=new Float32Array(32);for(let c=0;c<32;c++){let u=this.biasHidden[c];for(let d=0;d<4;d++)u+=e[d]*this.weightsInputHidden[d*32+c];i[c]=Math.max(0,u)}let r=new Float32Array(3);for(let c=0;c<3;c++){let u=this.biasOutput[c];for(let d=0;d<32;d++)u+=i[d]*this.weightsHiddenOutput[d*3+c];r[c]=u}let a=this.softmax(r),o=new Float32Array(3);for(let c=0;c<3;c++)o[c]=(c===t?1:0)-a[c],o[c]*=n*this.learningRate;for(let c=0;c<32;c++)for(let u=0;u<3;u++)this.weightsHiddenOutput[c*3+u]+=i[c]*o[u];for(let c=0;c<3;c++)this.biasOutput[c]+=o[c];let l=new Float32Array(32);for(let c=0;c<32;c++){if(i[c]<=0)continue;let u=0;for(let d=0;d<3;d++)u+=o[d]*this.weightsHiddenOutput[c*3+d];l[c]=u}for(let c=0;c<4;c++)for(let u=0;u<32;u++)this.weightsInputHidden[c*32+u]+=e[c]*l[u];for(let c=0;c<32;c++)this.biasHidden[c]+=l[c]}serialize(){return{weightsInputHidden:Array.from(this.weightsInputHidden),weightsHiddenOutput:Array.from(this.weightsHiddenOutput),biasHidden:Array.from(this.biasHidden),biasOutput:Array.from(this.biasOutput)}}deserialize(e){e.weightsInputHidden.length===128&&(this.weightsInputHidden=new Float32Array(e.weightsInputHidden)),e.weightsHiddenOutput.length===96&&(this.weightsHiddenOutput=new Float32Array(e.weightsHiddenOutput)),e.biasHidden.length===32&&(this.biasHidden=new Float32Array(e.biasHidden)),e.biasOutput.length===3&&(this.biasOutput=new Float32Array(e.biasOutput))}}});var Rt={};bn(Rt,{NeuralTinyDancerRouter:()=>J,SimpleNeuralRouter:()=>P,createNeuralTinyDancerRouter:()=>$n});import{performance as It}from"perf_hooks";function $n(s){return new J(s)}var Pn,Fn,Hn,On,Nn,Ln,Qn,Bn,J,_t=Y(()=>{"use strict";Pe();_e();_e();Pn=1e3,Fn=.1,Hn=.2,On=50,Nn=.01,Ln=["haiku","sonnet","opus"],Qn={haiku:0,sonnet:1,opus:2},Bn={"test-generation":.1,"test-execution":.15,"coverage-analysis":.2,"quality-assessment":.3,"requirements-validation":.35,"code-intelligence":.4,"contract-testing":.45,"visual-accessibility":.5,"learning-optimization":.55,"defect-intelligence":.7,"chaos-resilience":.8,"security-compliance":.9},J=class{ruleRouter;neuralNet;circuitBreakerThreshold;shadowModeDecisionLimit;shadowModeMaxDisagreement;shadowModeActive;shadowDecisions=[];shadowDisagreements=0;circuitBreakerTripped=!1;recentOutcomes=[];totalNeuralDecisions=0;totalWeightUpdates=0;neuralPrimary=!1;calibrationScores=[];maxCalibrationScores=500;domainSuccessRates=new Map;config;nativeRouterAvailable=!1;constructor(e={}){this.config=e,this.ruleRouter=new L(e),this.neuralNet=new P(e.learningRate??Nn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??Hn,this.shadowModeDecisionLimit=e.shadowModeDecisions??Pn,this.shadowModeMaxDisagreement=e.shadowModeMaxDisagreement??Fn,e.forceShadowMode!==void 0?(this.shadowModeActive=e.forceShadowMode,this.neuralPrimary=!e.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1),this.tryLoadNativeRouter()}tryLoadNativeRouter(){this.nativeRouterAvailable=!1}async route(e){let t=It.now(),n=await this.ruleRouter.route(e);if(this.circuitBreakerTripped)return n;let i=this.extractFeatures(e,n.classification),r;try{r=this.neuralNet.forward(i)}catch{return this.tripCircuitBreaker(),n}let a=this.argmax(r),o=Ln[a],l=r[a];if(this.totalNeuralDecisions++,this.shadowModeActive){let m=n.model===o;return m||this.shadowDisagreements++,this.shadowDecisions.push({taskDescription:e.description.slice(0,100),ruleDecision:n.model,neuralDecision:o,agreed:m,neuralConfidence:l,timestamp:new Date}),this.evaluateShadowModeExit(),n}let c=It.now()-t,u=this.computeEmpiricalConfidenceBounds(r);return l<.3||u.calibrationScore>.8?n:{model:o,confidence:l,uncertainty:1-l,triggerMultiModel:n.triggerMultiModel,triggerHumanReview:n.triggerHumanReview,complexity:n.complexity,classification:n.classification,latencyMs:c,reasoning:this.buildNeuralReasoning(o,l,r,n,u)}}extractFeatures(e,t){let n=Math.min(1,t.score/100),i=e.description.length,r=e.context?.code?.length??0,a=(i+r)/4,o=Math.min(1,a/1e4),l=e.domain??"",c=Bn[l]??.25,u=this.domainSuccessRates.get(l),d=u?u.success/Math.max(1,u.total):.7;return[n,o,c,d]}recordNeuralOutcome(e,t,n,i=n?1:0,r=t.model,a=0){this.ruleRouter.recordOutcome(e,t,n,i,r,a);let o=e.domain??"unknown",l=this.domainSuccessRates.get(o)??{success:0,total:0};l.total++,n&&l.success++,this.domainSuccessRates.set(o,l),this.recentOutcomes.push(n),this.recentOutcomes.length>On&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let c=this.extractFeatures(e,t.classification),u=Qn[r],d=(i-.5)*2;try{this.neuralNet.updateWeights(c,u,d),this.totalWeightUpdates++}catch{}let m=this.neuralNet.forward(c),p=this.argmax(m),T=1-m[u];this.calibrationScores.push(T),this.calibrationScores.length>this.maxCalibrationScores&&this.calibrationScores.shift()}computeEmpiricalConfidenceBounds(e){let n=Math.max(...e),i=1-n;if(this.calibrationScores.length<10)return{lower:0,upper:1,coverageLevel:.9,calibrationScore:i};let r=[...this.calibrationScores].sort((l,c)=>l-c),a=Math.ceil(.9*r.length)-1,o=r[Math.min(a,r.length-1)];return{lower:Math.max(0,n-o),upper:Math.min(1,n+o),coverageLevel:.9,calibrationScore:i}}computeConformalBounds(e){return this.computeEmpiricalConfidenceBounds(e)}evaluateShadowModeExit(){if(!this.shadowModeActive||this.config.forceShadowMode===!0)return;let e=this.shadowDecisions.length;if(e<this.shadowModeDecisionLimit)return;this.shadowDisagreements/e<=this.shadowModeMaxDisagreement&&(this.shadowModeActive=!1,this.neuralPrimary=!0)}checkCircuitBreaker(){if(this.recentOutcomes.length<10)return;let t=this.recentOutcomes.filter(n=>!n).length/this.recentOutcomes.length;t>this.circuitBreakerThreshold?this.tripCircuitBreaker():this.circuitBreakerTripped&&t<this.circuitBreakerThreshold*.5&&(this.circuitBreakerTripped=!1)}tripCircuitBreaker(){this.circuitBreakerTripped=!0,this.neuralPrimary=!1}buildNeuralReasoning(e,t,n,i,r){let a=[];return a.push(`[Neural] Routing to ${e.toUpperCase()}`),a.push(`with ${(t*100).toFixed(0)}% neural confidence.`),a.push(`Tier probabilities: haiku=${(n[0]*100).toFixed(0)}%,`),a.push(`sonnet=${(n[1]*100).toFixed(0)}%,`),a.push(`opus=${(n[2]*100).toFixed(0)}%.`),e!==i.model&&a.push(`Rule-based would choose ${i.model.toUpperCase()}.`),a.push(`Empirical bounds: [${r.lower.toFixed(2)}, ${r.upper.toFixed(2)}]`),a.push(`at ${(r.coverageLevel*100).toFixed(0)}% coverage.`),a.join(" ")}argmax(e){let t=0,n=e[0];for(let i=1;i<e.length;i++)e[i]>n&&(n=e[i],t=i);return t}getNeuralStats(){let e=this.shadowDecisions.length,t=e>0?this.shadowDisagreements/e:0,n=this.recentOutcomes.filter(r=>!r).length,i=this.recentOutcomes.length>0?n/this.recentOutcomes.length:0;return{shadowModeActive:this.shadowModeActive,shadowDecisions:e,disagreementRate:t,circuitBreakerTripped:this.circuitBreakerTripped,recentErrorRate:i,totalNeuralDecisions:this.totalNeuralDecisions,totalWeightUpdates:this.totalWeightUpdates,neuralPrimary:this.neuralPrimary}}getShadowDecisionLogs(){return this.shadowDecisions}getRuleRouter(){return this.ruleRouter}getNeuralNet(){return this.neuralNet}isNativeRouterAvailable(){return this.nativeRouterAvailable}isShadowModeActive(){return this.shadowModeActive}isNeuralPrimary(){return this.neuralPrimary}isCircuitBreakerTripped(){return this.circuitBreakerTripped}resetCircuitBreaker(){this.circuitBreakerTripped=!1,this.recentOutcomes=[]}getStats(){return this.ruleRouter.getStats()}getConfig(){return this.ruleRouter.getConfig()}reset(){this.ruleRouter.reset(),this.shadowDecisions=[],this.shadowDisagreements=0,this.circuitBreakerTripped=!1,this.recentOutcomes=[],this.totalNeuralDecisions=0,this.totalWeightUpdates=0,this.calibrationScores=[],this.domainSuccessRates.clear(),this.config.forceShadowMode!==void 0?(this.shadowModeActive=this.config.forceShadowMode,this.neuralPrimary=!this.config.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1)}}});import{performance as Pt}from"perf_hooks";function Ft(s){try{let{getRuVectorFeatureFlags:e}=(Sn(),mt(kn));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(_t(),mt(Rt));return new n(s)}}catch(e){process.env.DEBUG&&console.debug("[Router] Neural router unavailable, using rule-based:",e instanceof Error?e.message:e)}return new L(s)}var L,Pe=Y(()=>{"use strict";Mt();L=class{confidenceThreshold;uncertaintyThreshold;securityConfidenceThreshold;enableLearning;verbose;executor;totalRouted=0;routesByModel={haiku:0,sonnet:0,opus:0};routesByComplexity={simple:0,moderate:0,complex:0,critical:0};multiModelTriggers=0;humanReviewTriggers=0;advisorConsultations=0;totalConfidence=0;totalLatencyMs=0;outcomes=[];maxOutcomes=1e3;constructor(e={}){this.confidenceThreshold=e.confidenceThreshold??.8,this.uncertaintyThreshold=e.uncertaintyThreshold??.2,this.securityConfidenceThreshold=e.securityConfidenceThreshold??.85,this.enableLearning=e.enableLearning??!0,this.verbose=e.verbose??!1,this.executor=e.executor}hasExecutor(){return this.executor!==void 0}async routeWithAdvisor(e,t){let n=await this.route(e);if(!n.triggerMultiModel||!this.executor||!t)return{route:n};let i=await this.executor.consult(t,{agentName:e.agentId??e.id??"unknown",triggerReason:`tiny_dancer.confidence=${n.confidence.toFixed(2)}<${this.confidenceThreshold}`});return this.advisorConsultations++,{route:n,advisor:i}}async route(e){let t=Pt.now(),n=wt(e),i=this.calculateConfidence(n),r=1-i,a=this.isSecurityTask(e),o=a&&i<this.securityConfidenceThreshold||i<this.confidenceThreshold&&n.complexity!=="simple",l=r>this.uncertaintyThreshold||a&&n.complexity==="critical",c=Pt.now()-t,u=this.buildReasoning(n,i,a,o,l),d={model:n.recommendedModel,confidence:i,uncertainty:r,triggerMultiModel:o,triggerHumanReview:l,complexity:n.complexity,classification:n,latencyMs:c,reasoning:u};return this.updateStats(d),this.verbose&&console.log(`[TinyDancer] Route: ${n.recommendedModel} (complexity=${n.complexity}, confidence=${(i*100).toFixed(1)}%)`),d}calculateConfidence(e){let{score:t,complexity:n}=e;if(n==="simple"&&t<10)return .9;if(n==="critical"&&t>85)return .92;let i=[S.moderate,S.complex,S.critical],r=1/0;for(let d of i){let m=Math.abs(t-d);m<r&&(r=m)}let a=.55,o=.35,l=Math.min(r/25,1),c=a+l*o,u=n!=="simple"?Math.min(.05,e.factors.length*.01):0;return Math.min(.95,c+u)}isSecurityTask(e){let t=e;if(t.type==="security-scan"||t.type==="vulnerability-assessment"||e.domain==="security-compliance")return!0;let n=["sast","dast","vulnerability","owasp","security-scanning"];if(e.requiredCapabilities?.some(a=>n.includes(a)))return!0;let i=["security","vulnerability","cve","owasp","exploit","injection"],r=e.description.toLowerCase();return!!i.some(a=>r.includes(a))}buildReasoning(e,t,n,i,r){let a=[];if(a.push(`Routing to ${e.recommendedModel.toUpperCase()}`),a.push(`(complexity: ${e.complexity}, score: ${e.score})`),a.push(`with ${(t*100).toFixed(0)}% confidence.`),e.factors.length>0){let o=e.factors.slice(0,3).map(l=>l.name).join(", ");a.push(`Key factors: ${o}.`)}return n&&a.push("Security-sensitive task detected."),i&&a.push("Multi-model verification recommended due to uncertainty."),r&&a.push("Human review flagged due to high uncertainty or criticality."),a.join(" ")}updateStats(e){this.totalRouted++,this.routesByModel[e.model]++,this.routesByComplexity[e.complexity]++,this.totalConfidence+=e.confidence,this.totalLatencyMs+=e.latencyMs,e.triggerMultiModel&&this.multiModelTriggers++,e.triggerHumanReview&&this.humanReviewTriggers++}recordOutcome(e,t,n,i=n?1:0,r=t.model,a=0){if(!this.enableLearning)return;let o={task:e,routeResult:t,success:n,qualityScore:i,actualModelUsed:r,durationMs:a,timestamp:new Date};this.outcomes.push(o),this.outcomes.length>this.maxOutcomes&&this.outcomes.shift(),this.verbose&&console.log(`[TinyDancer] Recorded outcome: success=${n}, quality=${(i*100).toFixed(0)}%, model=${r}`)}getStats(){return{totalRouted:this.totalRouted,routesByModel:{...this.routesByModel},routesByComplexity:{...this.routesByComplexity},multiModelTriggers:this.multiModelTriggers,advisorConsultations:this.advisorConsultations,humanReviewTriggers:this.humanReviewTriggers,avgConfidence:this.totalRouted>0?this.totalConfidence/this.totalRouted:0,avgLatencyMs:this.totalRouted>0?this.totalLatencyMs/this.totalRouted:0,outcomesRecorded:this.outcomes.length}}getOutcomes(){return this.outcomes}getSuccessRateByModel(){let e={haiku:{success:0,total:0},sonnet:{success:0,total:0},opus:{success:0,total:0}};for(let t of this.outcomes){let n=t.actualModelUsed;e[n].total++,t.success&&e[n].success++}return{haiku:e.haiku.total>0?e.haiku.success/e.haiku.total:0,sonnet:e.sonnet.total>0?e.sonnet.success/e.sonnet.total:0,opus:e.opus.total>0?e.opus.success/e.opus.total:0}}reset(){this.totalRouted=0,this.routesByModel={haiku:0,sonnet:0,opus:0},this.routesByComplexity={simple:0,moderate:0,complex:0,critical:0},this.multiModelTriggers=0,this.advisorConsultations=0,this.humanReviewTriggers=0,this.totalConfidence=0,this.totalLatencyMs=0,this.outcomes=[]}getConfig(){return{confidenceThreshold:this.confidenceThreshold,uncertaintyThreshold:this.uncertaintyThreshold,securityConfidenceThreshold:this.securityConfidenceThreshold,enableLearning:this.enableLearning,verbose:this.verbose}}}});import{randomUUID as At}from"node:crypto";var En={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},X=class{entries=[];config;generation=At();recordedEntries=0;droppedEntries=0;constructor(e={}){if(this.config={...En,...e},!Number.isSafeInteger(this.config.maxEntries)||this.config.maxEntries<0)throw new RangeError("maxEntries must be a non-negative safe integer")}log(e,t,n){let i={sequence:++this.recordedEntries,timestamp:new Date,operation:e,taskId:t,agentId:n?.agentId,domain:n?.domain,details:n?.details};if(this.entries.push(i),this.entries.length>this.config.maxEntries){let r=this.entries.length-this.config.maxEntries;this.entries.splice(0,r),this.droppedEntries+=r}if(this.config.enableConsoleLog){let r=n?.agentId?` by ${n.agentId}`:"",a=n?.domain?` (${n.domain})`:"";console.log(`${this.config.logPrefix} ${e.toUpperCase()} ${t}${r}${a}`)}}logSubmit(e,t){this.log("submit",e,{details:t})}logAssign(e,t,n){this.log("assign",e,{agentId:t,domain:n})}logReassign(e,t,n,i){this.log("reassign",e,{agentId:n,domain:i,details:{fromAgent:t}})}logComplete(e,t){this.log("complete",e,{agentId:t})}logFail(e,t,n){this.log("fail",e,{agentId:t,details:n?{error:n}:void 0})}logCancel(e){this.log("cancel",e)}logSteal(e,t,n){this.log("steal",e,{domain:n,details:{fromDomain:t}})}logQueue(e,t){this.log("queue",e,{details:{position:t}})}logDequeue(e){this.log("dequeue",e)}getEntries(e){let t=[...this.entries];e&&(e.operation&&(t=t.filter(i=>i.operation===e.operation)),e.taskId&&(t=t.filter(i=>i.taskId===e.taskId)),e.agentId&&(t=t.filter(i=>i.agentId===e.agentId)),e.domain&&(t=t.filter(i=>i.domain===e.domain)),e.fromTimestamp&&(t=t.filter(i=>i.timestamp>=e.fromTimestamp)),e.toTimestamp&&(t=t.filter(i=>i.timestamp<=e.toTimestamp)));let n=e?.limit??t.length;return n===0?[]:t.slice(-n)}getSnapshot(e){return{...this.getWindow(),entries:this.getEntries(e)}}getWindow(){return{generation:this.generation,recordedEntries:this.recordedEntries,retainedEntries:this.entries.length,droppedEntries:this.droppedEntries,firstRetainedSequence:this.entries[0]?.sequence??null,lastRetainedSequence:this.entries[this.entries.length-1]?.sequence??null,disposition:this.droppedEntries>0?"truncated":"complete"}}getStatistics(){let e={submit:0,assign:0,reassign:0,complete:0,fail:0,cancel:0,steal:0,queue:0,dequeue:0},t=new Set,n=new Set;for(let i of this.entries)e[i.operation]++,t.add(i.taskId),i.agentId&&n.add(i.agentId);return{...this.getWindow(),basis:"retained-window",totalEntries:this.entries.length,operationCounts:e,taskCount:t.size,agentCount:n.size}}clear(){this.entries.length=0,this.generation=At(),this.recordedEntries=0,this.droppedEntries=0}};function Me(s){return new X(s)}Ae();pt();var Ie=class{memory;initialized=!1;constructor(e){this.memory=e??R()}async initialize(){this.initialized||(this.memory.isInitialized()||await this.memory.initialize(),this.initialized=!0)}async saveSnapshot(e){this.ensureInitialized();let t=C(),n=this.memory.getDatabase();return await this.memory.writeWhenUnlocked(()=>n.prepare(`
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.18");process.exit(0)}
|
|
2
|
+
import{b as we}from"./chunk-C5QVJ5XQ.js";import{a as Dt}from"./chunk-2Q6DTBMT.js";import{a as kt,b as St}from"./chunk-6D6TGL2E.js";import{a as Ct,b as bt}from"./chunk-BOVAKCDC.js";import{j as _}from"./chunk-5M24X6W7.js";import{a as ft}from"./chunk-3RPDKJGV.js";import{a as Tt,b as Ee,c as vt}from"./chunk-UNTBVJ5X.js";import{a as xe}from"./chunk-Y4LSEOZ3.js";import{b as yt}from"./chunk-F6YD3BOW.js";import{i as C}from"./chunk-4BIMTRRX.js";import{C as Ae,w as R}from"./chunk-OW23N2Y5.js";import{a as ht,e as xn}from"./chunk-MZRBNBB3.js";import{c as De,d as An}from"./chunk-YFILS5D5.js";import{b as I,d as pt}from"./chunk-MQM37KAR.js";import{a as v,c as y,d as f}from"./chunk-JMRDT2XK.js";import{a as Dn}from"./chunk-O5EWFR76.js";import{c as gt}from"./chunk-NKU3FFM4.js";import{R as kn,S as Sn}from"./chunk-V2LJ54KP.js";import{a as h,b as Z,e as k}from"./chunk-AWQAE3SW.js";import{b as Y,d as bn,f as mt}from"./chunk-BDVFSMOQ.js";function wt(s){let e=[],t=0;if(s.fileCount!==void 0&&(s.fileCount>20?(t+=25,e.push({name:"very-high-file-count",weight:25,description:`Task involves ${s.fileCount} files (>20)`})):s.fileCount>10?(t+=20,e.push({name:"high-file-count",weight:20,description:`Task involves ${s.fileCount} files (>10)`})):s.fileCount>5&&(t+=10,e.push({name:"moderate-file-count",weight:10,description:`Task involves ${s.fileCount} files (>5)`}))),s.domain&&(Mn.includes(s.domain)?(t+=30,e.push({name:"complex-domain",weight:30,description:`Domain '${s.domain}' requires complex reasoning`})):In.includes(s.domain)&&(t+=15,e.push({name:"moderate-domain",weight:15,description:`Domain '${s.domain}' has moderate complexity`}))),s.crossComponent&&(t+=25,e.push({name:"cross-component",weight:25,description:"Task spans multiple components/modules"})),s.priority==="critical"?(t+=25,e.push({name:"critical-priority",weight:25,description:"Critical priority requires careful attention"})):s.priority==="high"&&(t+=15,e.push({name:"high-priority",weight:15,description:"High priority task"})),s.requiredCapabilities){let r=s.requiredCapabilities.filter(a=>Rn.includes(a)).length;if(r>0){let a=Math.min(20,r*10);t+=a,e.push({name:"complex-capabilities",weight:a,description:`Requires ${r} complex capabilit${r===1?"y":"ies"}`})}}s.requiresExternalApis&&(t+=10,e.push({name:"external-apis",weight:10,description:"Requires external API integration"})),s.involvesDatabaseOps&&(t+=10,e.push({name:"database-ops",weight:10,description:"Involves database operations"})),s.timeSensitive&&(t+=5,e.push({name:"time-sensitive",weight:5,description:"Time-sensitive task"})),s.estimatedLinesAffected!==void 0&&(s.estimatedLinesAffected>500?(t+=15,e.push({name:"large-change",weight:15,description:`Estimated ${s.estimatedLinesAffected} lines affected (>500)`})):s.estimatedLinesAffected>200&&(t+=10,e.push({name:"medium-change",weight:10,description:`Estimated ${s.estimatedLinesAffected} lines affected (>200)`}))),(s.type==="security-scan"||s.type==="vulnerability-assessment")&&(t+=20,e.push({name:"security-task",weight:20,description:"Security-related task requires careful analysis"}));let n=t>=S.critical?"critical":t>=S.complex?"complex":t>=S.moderate?"moderate":"simple",i=_n[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var Mn,In,Rn,S,_n,Mt=Y(()=>{"use strict";Mn=["security-compliance","chaos-resilience","defect-intelligence"],In=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],Rn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},_n={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var P,_e=Y(()=>{"use strict";P=class{weightsInputHidden;weightsHiddenOutput;biasHidden;biasOutput;learningRate;constructor(e=.01){this.learningRate=e,this.weightsInputHidden=this.xavierInit(4,32),this.weightsHiddenOutput=this.xavierInit(32,3),this.biasHidden=new Float32Array(32),this.biasOutput=new Float32Array(3)}xavierInit(e,t){let n=Math.sqrt(2/(e+t)),i=new Float32Array(e*t);for(let r=0;r<i.length;r++){let a=Math.random(),o=Math.random(),l=Math.sqrt(-2*Math.log(Math.max(a,1e-10)))*Math.cos(2*Math.PI*o);i[r]=l*n}return i}forward(e){if(e.length!==4)throw new Error(`Expected 4 features, got ${e.length}`);let t=new Float32Array(32);for(let i=0;i<32;i++){let r=this.biasHidden[i];for(let a=0;a<4;a++)r+=e[a]*this.weightsInputHidden[a*32+i];t[i]=Math.max(0,r)}let n=new Float32Array(3);for(let i=0;i<3;i++){let r=this.biasOutput[i];for(let a=0;a<32;a++)r+=t[a]*this.weightsHiddenOutput[a*3+i];n[i]=r}return this.softmax(n)}softmax(e){let t=Math.max(...e),n=new Float32Array(e.length),i=0;for(let a=0;a<e.length;a++)n[a]=Math.exp(e[a]-t),i+=n[a];let r=[];for(let a=0;a<e.length;a++)r.push(n[a]/i);return r}updateWeights(e,t,n){let i=new Float32Array(32);for(let c=0;c<32;c++){let u=this.biasHidden[c];for(let d=0;d<4;d++)u+=e[d]*this.weightsInputHidden[d*32+c];i[c]=Math.max(0,u)}let r=new Float32Array(3);for(let c=0;c<3;c++){let u=this.biasOutput[c];for(let d=0;d<32;d++)u+=i[d]*this.weightsHiddenOutput[d*3+c];r[c]=u}let a=this.softmax(r),o=new Float32Array(3);for(let c=0;c<3;c++)o[c]=(c===t?1:0)-a[c],o[c]*=n*this.learningRate;for(let c=0;c<32;c++)for(let u=0;u<3;u++)this.weightsHiddenOutput[c*3+u]+=i[c]*o[u];for(let c=0;c<3;c++)this.biasOutput[c]+=o[c];let l=new Float32Array(32);for(let c=0;c<32;c++){if(i[c]<=0)continue;let u=0;for(let d=0;d<3;d++)u+=o[d]*this.weightsHiddenOutput[c*3+d];l[c]=u}for(let c=0;c<4;c++)for(let u=0;u<32;u++)this.weightsInputHidden[c*32+u]+=e[c]*l[u];for(let c=0;c<32;c++)this.biasHidden[c]+=l[c]}serialize(){return{weightsInputHidden:Array.from(this.weightsInputHidden),weightsHiddenOutput:Array.from(this.weightsHiddenOutput),biasHidden:Array.from(this.biasHidden),biasOutput:Array.from(this.biasOutput)}}deserialize(e){e.weightsInputHidden.length===128&&(this.weightsInputHidden=new Float32Array(e.weightsInputHidden)),e.weightsHiddenOutput.length===96&&(this.weightsHiddenOutput=new Float32Array(e.weightsHiddenOutput)),e.biasHidden.length===32&&(this.biasHidden=new Float32Array(e.biasHidden)),e.biasOutput.length===3&&(this.biasOutput=new Float32Array(e.biasOutput))}}});var Rt={};bn(Rt,{NeuralTinyDancerRouter:()=>J,SimpleNeuralRouter:()=>P,createNeuralTinyDancerRouter:()=>$n});import{performance as It}from"perf_hooks";function $n(s){return new J(s)}var Pn,Fn,Hn,On,Nn,Ln,Qn,Bn,J,_t=Y(()=>{"use strict";Pe();_e();_e();Pn=1e3,Fn=.1,Hn=.2,On=50,Nn=.01,Ln=["haiku","sonnet","opus"],Qn={haiku:0,sonnet:1,opus:2},Bn={"test-generation":.1,"test-execution":.15,"coverage-analysis":.2,"quality-assessment":.3,"requirements-validation":.35,"code-intelligence":.4,"contract-testing":.45,"visual-accessibility":.5,"learning-optimization":.55,"defect-intelligence":.7,"chaos-resilience":.8,"security-compliance":.9},J=class{ruleRouter;neuralNet;circuitBreakerThreshold;shadowModeDecisionLimit;shadowModeMaxDisagreement;shadowModeActive;shadowDecisions=[];shadowDisagreements=0;circuitBreakerTripped=!1;recentOutcomes=[];totalNeuralDecisions=0;totalWeightUpdates=0;neuralPrimary=!1;calibrationScores=[];maxCalibrationScores=500;domainSuccessRates=new Map;config;nativeRouterAvailable=!1;constructor(e={}){this.config=e,this.ruleRouter=new L(e),this.neuralNet=new P(e.learningRate??Nn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??Hn,this.shadowModeDecisionLimit=e.shadowModeDecisions??Pn,this.shadowModeMaxDisagreement=e.shadowModeMaxDisagreement??Fn,e.forceShadowMode!==void 0?(this.shadowModeActive=e.forceShadowMode,this.neuralPrimary=!e.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1),this.tryLoadNativeRouter()}tryLoadNativeRouter(){this.nativeRouterAvailable=!1}async route(e){let t=It.now(),n=await this.ruleRouter.route(e);if(this.circuitBreakerTripped)return n;let i=this.extractFeatures(e,n.classification),r;try{r=this.neuralNet.forward(i)}catch{return this.tripCircuitBreaker(),n}let a=this.argmax(r),o=Ln[a],l=r[a];if(this.totalNeuralDecisions++,this.shadowModeActive){let m=n.model===o;return m||this.shadowDisagreements++,this.shadowDecisions.push({taskDescription:e.description.slice(0,100),ruleDecision:n.model,neuralDecision:o,agreed:m,neuralConfidence:l,timestamp:new Date}),this.evaluateShadowModeExit(),n}let c=It.now()-t,u=this.computeEmpiricalConfidenceBounds(r);return l<.3||u.calibrationScore>.8?n:{model:o,confidence:l,uncertainty:1-l,triggerMultiModel:n.triggerMultiModel,triggerHumanReview:n.triggerHumanReview,complexity:n.complexity,classification:n.classification,latencyMs:c,reasoning:this.buildNeuralReasoning(o,l,r,n,u)}}extractFeatures(e,t){let n=Math.min(1,t.score/100),i=e.description.length,r=e.context?.code?.length??0,a=(i+r)/4,o=Math.min(1,a/1e4),l=e.domain??"",c=Bn[l]??.25,u=this.domainSuccessRates.get(l),d=u?u.success/Math.max(1,u.total):.7;return[n,o,c,d]}recordNeuralOutcome(e,t,n,i=n?1:0,r=t.model,a=0){this.ruleRouter.recordOutcome(e,t,n,i,r,a);let o=e.domain??"unknown",l=this.domainSuccessRates.get(o)??{success:0,total:0};l.total++,n&&l.success++,this.domainSuccessRates.set(o,l),this.recentOutcomes.push(n),this.recentOutcomes.length>On&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let c=this.extractFeatures(e,t.classification),u=Qn[r],d=(i-.5)*2;try{this.neuralNet.updateWeights(c,u,d),this.totalWeightUpdates++}catch{}let m=this.neuralNet.forward(c),p=this.argmax(m),T=1-m[u];this.calibrationScores.push(T),this.calibrationScores.length>this.maxCalibrationScores&&this.calibrationScores.shift()}computeEmpiricalConfidenceBounds(e){let n=Math.max(...e),i=1-n;if(this.calibrationScores.length<10)return{lower:0,upper:1,coverageLevel:.9,calibrationScore:i};let r=[...this.calibrationScores].sort((l,c)=>l-c),a=Math.ceil(.9*r.length)-1,o=r[Math.min(a,r.length-1)];return{lower:Math.max(0,n-o),upper:Math.min(1,n+o),coverageLevel:.9,calibrationScore:i}}computeConformalBounds(e){return this.computeEmpiricalConfidenceBounds(e)}evaluateShadowModeExit(){if(!this.shadowModeActive||this.config.forceShadowMode===!0)return;let e=this.shadowDecisions.length;if(e<this.shadowModeDecisionLimit)return;this.shadowDisagreements/e<=this.shadowModeMaxDisagreement&&(this.shadowModeActive=!1,this.neuralPrimary=!0)}checkCircuitBreaker(){if(this.recentOutcomes.length<10)return;let t=this.recentOutcomes.filter(n=>!n).length/this.recentOutcomes.length;t>this.circuitBreakerThreshold?this.tripCircuitBreaker():this.circuitBreakerTripped&&t<this.circuitBreakerThreshold*.5&&(this.circuitBreakerTripped=!1)}tripCircuitBreaker(){this.circuitBreakerTripped=!0,this.neuralPrimary=!1}buildNeuralReasoning(e,t,n,i,r){let a=[];return a.push(`[Neural] Routing to ${e.toUpperCase()}`),a.push(`with ${(t*100).toFixed(0)}% neural confidence.`),a.push(`Tier probabilities: haiku=${(n[0]*100).toFixed(0)}%,`),a.push(`sonnet=${(n[1]*100).toFixed(0)}%,`),a.push(`opus=${(n[2]*100).toFixed(0)}%.`),e!==i.model&&a.push(`Rule-based would choose ${i.model.toUpperCase()}.`),a.push(`Empirical bounds: [${r.lower.toFixed(2)}, ${r.upper.toFixed(2)}]`),a.push(`at ${(r.coverageLevel*100).toFixed(0)}% coverage.`),a.join(" ")}argmax(e){let t=0,n=e[0];for(let i=1;i<e.length;i++)e[i]>n&&(n=e[i],t=i);return t}getNeuralStats(){let e=this.shadowDecisions.length,t=e>0?this.shadowDisagreements/e:0,n=this.recentOutcomes.filter(r=>!r).length,i=this.recentOutcomes.length>0?n/this.recentOutcomes.length:0;return{shadowModeActive:this.shadowModeActive,shadowDecisions:e,disagreementRate:t,circuitBreakerTripped:this.circuitBreakerTripped,recentErrorRate:i,totalNeuralDecisions:this.totalNeuralDecisions,totalWeightUpdates:this.totalWeightUpdates,neuralPrimary:this.neuralPrimary}}getShadowDecisionLogs(){return this.shadowDecisions}getRuleRouter(){return this.ruleRouter}getNeuralNet(){return this.neuralNet}isNativeRouterAvailable(){return this.nativeRouterAvailable}isShadowModeActive(){return this.shadowModeActive}isNeuralPrimary(){return this.neuralPrimary}isCircuitBreakerTripped(){return this.circuitBreakerTripped}resetCircuitBreaker(){this.circuitBreakerTripped=!1,this.recentOutcomes=[]}getStats(){return this.ruleRouter.getStats()}getConfig(){return this.ruleRouter.getConfig()}reset(){this.ruleRouter.reset(),this.shadowDecisions=[],this.shadowDisagreements=0,this.circuitBreakerTripped=!1,this.recentOutcomes=[],this.totalNeuralDecisions=0,this.totalWeightUpdates=0,this.calibrationScores=[],this.domainSuccessRates.clear(),this.config.forceShadowMode!==void 0?(this.shadowModeActive=this.config.forceShadowMode,this.neuralPrimary=!this.config.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1)}}});import{performance as Pt}from"perf_hooks";function Ft(s){try{let{getRuVectorFeatureFlags:e}=(Sn(),mt(kn));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(_t(),mt(Rt));return new n(s)}}catch(e){process.env.DEBUG&&console.debug("[Router] Neural router unavailable, using rule-based:",e instanceof Error?e.message:e)}return new L(s)}var L,Pe=Y(()=>{"use strict";Mt();L=class{confidenceThreshold;uncertaintyThreshold;securityConfidenceThreshold;enableLearning;verbose;executor;totalRouted=0;routesByModel={haiku:0,sonnet:0,opus:0};routesByComplexity={simple:0,moderate:0,complex:0,critical:0};multiModelTriggers=0;humanReviewTriggers=0;advisorConsultations=0;totalConfidence=0;totalLatencyMs=0;outcomes=[];maxOutcomes=1e3;constructor(e={}){this.confidenceThreshold=e.confidenceThreshold??.8,this.uncertaintyThreshold=e.uncertaintyThreshold??.2,this.securityConfidenceThreshold=e.securityConfidenceThreshold??.85,this.enableLearning=e.enableLearning??!0,this.verbose=e.verbose??!1,this.executor=e.executor}hasExecutor(){return this.executor!==void 0}async routeWithAdvisor(e,t){let n=await this.route(e);if(!n.triggerMultiModel||!this.executor||!t)return{route:n};let i=await this.executor.consult(t,{agentName:e.agentId??e.id??"unknown",triggerReason:`tiny_dancer.confidence=${n.confidence.toFixed(2)}<${this.confidenceThreshold}`});return this.advisorConsultations++,{route:n,advisor:i}}async route(e){let t=Pt.now(),n=wt(e),i=this.calculateConfidence(n),r=1-i,a=this.isSecurityTask(e),o=a&&i<this.securityConfidenceThreshold||i<this.confidenceThreshold&&n.complexity!=="simple",l=r>this.uncertaintyThreshold||a&&n.complexity==="critical",c=Pt.now()-t,u=this.buildReasoning(n,i,a,o,l),d={model:n.recommendedModel,confidence:i,uncertainty:r,triggerMultiModel:o,triggerHumanReview:l,complexity:n.complexity,classification:n,latencyMs:c,reasoning:u};return this.updateStats(d),this.verbose&&console.log(`[TinyDancer] Route: ${n.recommendedModel} (complexity=${n.complexity}, confidence=${(i*100).toFixed(1)}%)`),d}calculateConfidence(e){let{score:t,complexity:n}=e;if(n==="simple"&&t<10)return .9;if(n==="critical"&&t>85)return .92;let i=[S.moderate,S.complex,S.critical],r=1/0;for(let d of i){let m=Math.abs(t-d);m<r&&(r=m)}let a=.55,o=.35,l=Math.min(r/25,1),c=a+l*o,u=n!=="simple"?Math.min(.05,e.factors.length*.01):0;return Math.min(.95,c+u)}isSecurityTask(e){let t=e;if(t.type==="security-scan"||t.type==="vulnerability-assessment"||e.domain==="security-compliance")return!0;let n=["sast","dast","vulnerability","owasp","security-scanning"];if(e.requiredCapabilities?.some(a=>n.includes(a)))return!0;let i=["security","vulnerability","cve","owasp","exploit","injection"],r=e.description.toLowerCase();return!!i.some(a=>r.includes(a))}buildReasoning(e,t,n,i,r){let a=[];if(a.push(`Routing to ${e.recommendedModel.toUpperCase()}`),a.push(`(complexity: ${e.complexity}, score: ${e.score})`),a.push(`with ${(t*100).toFixed(0)}% confidence.`),e.factors.length>0){let o=e.factors.slice(0,3).map(l=>l.name).join(", ");a.push(`Key factors: ${o}.`)}return n&&a.push("Security-sensitive task detected."),i&&a.push("Multi-model verification recommended due to uncertainty."),r&&a.push("Human review flagged due to high uncertainty or criticality."),a.join(" ")}updateStats(e){this.totalRouted++,this.routesByModel[e.model]++,this.routesByComplexity[e.complexity]++,this.totalConfidence+=e.confidence,this.totalLatencyMs+=e.latencyMs,e.triggerMultiModel&&this.multiModelTriggers++,e.triggerHumanReview&&this.humanReviewTriggers++}recordOutcome(e,t,n,i=n?1:0,r=t.model,a=0){if(!this.enableLearning)return;let o={task:e,routeResult:t,success:n,qualityScore:i,actualModelUsed:r,durationMs:a,timestamp:new Date};this.outcomes.push(o),this.outcomes.length>this.maxOutcomes&&this.outcomes.shift(),this.verbose&&console.log(`[TinyDancer] Recorded outcome: success=${n}, quality=${(i*100).toFixed(0)}%, model=${r}`)}getStats(){return{totalRouted:this.totalRouted,routesByModel:{...this.routesByModel},routesByComplexity:{...this.routesByComplexity},multiModelTriggers:this.multiModelTriggers,advisorConsultations:this.advisorConsultations,humanReviewTriggers:this.humanReviewTriggers,avgConfidence:this.totalRouted>0?this.totalConfidence/this.totalRouted:0,avgLatencyMs:this.totalRouted>0?this.totalLatencyMs/this.totalRouted:0,outcomesRecorded:this.outcomes.length}}getOutcomes(){return this.outcomes}getSuccessRateByModel(){let e={haiku:{success:0,total:0},sonnet:{success:0,total:0},opus:{success:0,total:0}};for(let t of this.outcomes){let n=t.actualModelUsed;e[n].total++,t.success&&e[n].success++}return{haiku:e.haiku.total>0?e.haiku.success/e.haiku.total:0,sonnet:e.sonnet.total>0?e.sonnet.success/e.sonnet.total:0,opus:e.opus.total>0?e.opus.success/e.opus.total:0}}reset(){this.totalRouted=0,this.routesByModel={haiku:0,sonnet:0,opus:0},this.routesByComplexity={simple:0,moderate:0,complex:0,critical:0},this.multiModelTriggers=0,this.advisorConsultations=0,this.humanReviewTriggers=0,this.totalConfidence=0,this.totalLatencyMs=0,this.outcomes=[]}getConfig(){return{confidenceThreshold:this.confidenceThreshold,uncertaintyThreshold:this.uncertaintyThreshold,securityConfidenceThreshold:this.securityConfidenceThreshold,enableLearning:this.enableLearning,verbose:this.verbose}}}});import{randomUUID as At}from"node:crypto";var En={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},X=class{entries=[];config;generation=At();recordedEntries=0;droppedEntries=0;constructor(e={}){if(this.config={...En,...e},!Number.isSafeInteger(this.config.maxEntries)||this.config.maxEntries<0)throw new RangeError("maxEntries must be a non-negative safe integer")}log(e,t,n){let i={sequence:++this.recordedEntries,timestamp:new Date,operation:e,taskId:t,agentId:n?.agentId,domain:n?.domain,details:n?.details};if(this.entries.push(i),this.entries.length>this.config.maxEntries){let r=this.entries.length-this.config.maxEntries;this.entries.splice(0,r),this.droppedEntries+=r}if(this.config.enableConsoleLog){let r=n?.agentId?` by ${n.agentId}`:"",a=n?.domain?` (${n.domain})`:"";console.log(`${this.config.logPrefix} ${e.toUpperCase()} ${t}${r}${a}`)}}logSubmit(e,t){this.log("submit",e,{details:t})}logAssign(e,t,n){this.log("assign",e,{agentId:t,domain:n})}logReassign(e,t,n,i){this.log("reassign",e,{agentId:n,domain:i,details:{fromAgent:t}})}logComplete(e,t){this.log("complete",e,{agentId:t})}logFail(e,t,n){this.log("fail",e,{agentId:t,details:n?{error:n}:void 0})}logCancel(e){this.log("cancel",e)}logSteal(e,t,n){this.log("steal",e,{domain:n,details:{fromDomain:t}})}logQueue(e,t){this.log("queue",e,{details:{position:t}})}logDequeue(e){this.log("dequeue",e)}getEntries(e){let t=[...this.entries];e&&(e.operation&&(t=t.filter(i=>i.operation===e.operation)),e.taskId&&(t=t.filter(i=>i.taskId===e.taskId)),e.agentId&&(t=t.filter(i=>i.agentId===e.agentId)),e.domain&&(t=t.filter(i=>i.domain===e.domain)),e.fromTimestamp&&(t=t.filter(i=>i.timestamp>=e.fromTimestamp)),e.toTimestamp&&(t=t.filter(i=>i.timestamp<=e.toTimestamp)));let n=e?.limit??t.length;return n===0?[]:t.slice(-n)}getSnapshot(e){return{...this.getWindow(),entries:this.getEntries(e)}}getWindow(){return{generation:this.generation,recordedEntries:this.recordedEntries,retainedEntries:this.entries.length,droppedEntries:this.droppedEntries,firstRetainedSequence:this.entries[0]?.sequence??null,lastRetainedSequence:this.entries[this.entries.length-1]?.sequence??null,disposition:this.droppedEntries>0?"truncated":"complete"}}getStatistics(){let e={submit:0,assign:0,reassign:0,complete:0,fail:0,cancel:0,steal:0,queue:0,dequeue:0},t=new Set,n=new Set;for(let i of this.entries)e[i.operation]++,t.add(i.taskId),i.agentId&&n.add(i.agentId);return{...this.getWindow(),basis:"retained-window",totalEntries:this.entries.length,operationCounts:e,taskCount:t.size,agentCount:n.size}}clear(){this.entries.length=0,this.generation=At(),this.recordedEntries=0,this.droppedEntries=0}};function Me(s){return new X(s)}Ae();pt();var Ie=class{memory;initialized=!1;constructor(e){this.memory=e??R()}async initialize(){this.initialized||(this.memory.isInitialized()||await this.memory.initialize(),this.initialized=!0)}async saveSnapshot(e){this.ensureInitialized();let t=C(),n=this.memory.getDatabase();return await this.memory.writeWhenUnlocked(()=>n.prepare(`
|
|
3
3
|
INSERT INTO mincut_snapshots (
|
|
4
4
|
id, timestamp, vertex_count, edge_count, total_weight,
|
|
5
5
|
is_connected, component_count, vertices_json, edges_json
|
|
@@ -177,4 +177,4 @@ import{b as we}from"./chunk-MGZ6XZHU.js";import{a as Dt}from"./chunk-P3D7SEHW.js
|
|
|
177
177
|
`;let i=this.getRecommendations(n);if(i.length>0){t+=`**Recommendations:**
|
|
178
178
|
`;for(let r of i)t+=`- ${r}
|
|
179
179
|
`;t+=`
|
|
180
|
-
`}}return t}getRecommendations(e){switch(e.loopType){case"strategic":return[...e.recommendations.forRiskAssessor,...e.recommendations.forQualityCriteria];case"tactical":return e.recommendations.forProductFactorsAssessor;case"operational":return[...e.recommendations.forTestArchitect,...e.recommendations.antiPatterns];case"quality-criteria":return e.recommendations.forRequirementsValidator;default:return[]}}filterManagedHooks(e){if(process.env.AQE_HOOKS_MANAGED_ONLY!=="true")return e;let t=e.filter(([n])=>n.startsWith("managed:"));return t.length<e.length&&console.log(`[CrossPhaseHooks] AQE_HOOKS_MANAGED_ONLY: filtered ${e.length-t.length} non-managed hooks`),t}async isBlockedUrl(e){if(!e.includes("://"))return!1;let t=await we(e);return t.safe?!1:(console.warn(`[CrossPhaseHooks] SSRF blocked: ${t.reason}`),!0)}checkConditions(e,t){return!e||e.length===0?!0:e.every(n=>this.evaluateCondition(n,t))}evaluateCondition(e,t){try{let n=e.split(/\s*(>|<|>=|<=|==|!=)\s*/);if(n.length!==3)return!1;let[i,r,a]=n,o=this.getValueFromPath(t,i),l=isNaN(Number(a))?a:Number(a),c=typeof o=="number"?o:Number(o),u=typeof l=="number"?l:Number(l);switch(r){case">":return c>u;case"<":return c<u;case">=":return c>=u;case"<=":return c<=u;case"==":return o==l;case"!=":return o!=l;default:return!1}}catch{return!1}}getValueFromPath(e,t){return t.split(".").reduce((n,i)=>{if(n&&typeof n=="object"&&Object.hasOwn(n,i))return n[i]},e)}extractFromContext(e,t){let n={};for(let[i,r]of Object.entries(e))n[i]=this.getValueFromPath(t,r);return n}parseMaxAge(e){let t=e.match(/^(\d+)(d|h|m|s)$/);if(!t)return 0;let[,n,i]=t,r=parseInt(n,10);switch(i){case"d":return r*24*60*60*1e3;case"h":return r*60*60*1e3;case"m":return r*60*1e3;case"s":return r*1e3;default:return 0}}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(n=>n(t))}async runCleanup(){if(!this.config?.cleanup.enabled)return;console.log("[CrossPhaseHooks] Running cleanup...");let e=await this.memory.cleanupExpired();console.log(`[CrossPhaseHooks] Cleanup complete: ${e.deleted} signals deleted`)}},rt=null;function rn(s){return rt||(rt=new st(s)),rt}function H(s,e){let t=s.get(e);return t?.status!=="cancelled"?{ignored:!1,settledNow:!1}:t.cancellationResultPending?(s.set(e,{...t,cancellationResultPending:!1}),{ignored:!0,settledNow:!0}):{ignored:!0,settledNow:!1}}function sn(s,e){let t=[];for(let a of e){let o=s.router.subscribeToDoamin(a,async l=>{await Di(s,l)});t.push(o)}let n=s.router.subscribeToEventType("TaskCompleted",async a=>{await Ai(s,a)});t.push(n);let i=s.router.subscribeToEventType("TaskFailed",async a=>{await xi(s,a)});t.push(i);let r=s.router.subscribeToEventType("AgentStatusChanged",async a=>{await Ei(s,a)});return t.push(r),t}async function Di(s,e){s.domainLastActivity.set(e.source,new Date),await s.processQueue()}async function an(s,e){for(let t of e.assignedAgents)await s.agentCoordinator.stop(t)}async function Ai(s,e){let{taskId:t,result:n}=e.payload,i=H(s.tasks,t);if(i.ignored){i.settledNow&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),await s.processQueue());return}let r=s.tasks.get(t);if(r){await an(s,r),(r.status==="running"||r.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1));let a=r.startedAt?Date.now()-r.startedAt.getTime():0;s.tasks.set(t,{...r,status:"completed",completedAt:new Date,result:n}),s.tasksCompleted++,s.taskDurations.push(a),s.auditLogger.logComplete(t,r.assignedAgents[0]);try{let o=rn(),l=r.assignedAgents[0];l&&await o.onAgentComplete(l,{taskId:t,taskType:r.task.type,domain:r.assignedDomain,result:n,duration:a})}catch(o){console.warn("[QueenCoordinator] Cross-phase hook error:",o)}try{await _.afterTaskExecution({taskId:t,taskType:r.task.type,agentId:r.assignedAgents[0]||"unknown",domain:r.assignedDomain||"test-generation",priority:r.task.priority},!0,0,0)}catch(o){console.warn("[QueenCoordinator] Governance tracking error:",o)}if(s.domainBreakerRegistry&&r.assignedDomain&&s.domainBreakerRegistry.getBreaker(r.assignedDomain).recordSuccess(),s.traceCollector){let o=s.taskTraceContexts.get(t);o&&(s.traceCollector.completeSpan(o.spanId),s.taskTraceContexts.delete(t))}if(s.taskCompletedHook)try{let o=typeof n=="object"&&n!==null?n:null;if(o===null)console.error(`[QueenCoordinator] Pattern training skipped for task ${t}: result is not an object (got ${typeof n})`);else{let l=wi(o,t);if(l){let c={taskId:t,agentId:r.assignedAgents[0]||"unknown",domain:r.assignedDomain||"test-generation",type:r.task.type,status:"completed",output:o,metrics:l,duration:a,timestamp:Date.now()};s.taskCompletedHook.onTaskCompleted(c).catch(u=>{console.warn("[QueenCoordinator] Pattern training error:",u)})}}}catch(o){console.warn("[QueenCoordinator] Pattern training setup error:",o)}}await s.processQueue()}async function xi(s,e){let{taskId:t,error:n,callerError:i}=e.payload,r=H(s.tasks,t);if(r.ignored){r.settledNow&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),await s.processQueue());return}let a=s.tasks.get(t);if(a){if(await an(s,a),(a.status==="running"||a.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1)),s.domainBreakerRegistry&&a.assignedDomain&&!i&&s.domainBreakerRegistry.getBreaker(a.assignedDomain).recordFailure(new Error(n||"Task failed")),s.traceCollector){let l=s.taskTraceContexts.get(t);l&&(s.traceCollector.failSpan(l.spanId,n||"Task failed"),s.taskTraceContexts.delete(t))}let o=a.task.executionOwner==="caller";if(!i&&!o&&a.retryCount<s.config.taskRetryLimit){s.auditLogger.logFail(t,a.assignedAgents[0],n);let l={...a,status:"queued",retryCount:a.retryCount+1,error:n};s.tasks.set(t,l),s.enqueueTask(a.task)}else{s.tasks.set(t,{...a,status:"failed",completedAt:new Date,error:n}),s.tasksFailed++,s.auditLogger.logFail(t,a.assignedAgents[0],n);try{await _.afterTaskExecution({taskId:t,taskType:a.task.type,agentId:a.assignedAgents[0]||"unknown",domain:a.assignedDomain||"test-generation",priority:a.task.priority},!1,0,0)}catch(l){console.warn("[QueenCoordinator] Governance tracking error:",l)}if(!i&&s.hypothesisManager&&(a.task.priority==="p0"||a.task.priority==="p1"))try{let l=a.assignedDomain||"test-generation",c=s.hypothesisManager.createInvestigation(t,l,`Root cause analysis for ${a.task.type} failure: ${n}`);s.hypothesisManager.addHypothesis(c.id,`Infrastructure failure in domain '${l}' caused task ${t} to fail`,"log-analysis",`${l}-lead`),s.hypothesisManager.addHypothesis(c.id,`Logic/configuration error in task payload caused ${a.task.type} to fail: ${n}`,"code-analysis",a.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${c.id}`)}catch(l){console.warn("[QueenCoordinator] Hypothesis creation error:",l)}}}await s.processQueue()}async function Ei(s,e){let{agentId:t,status:n,domain:i}=e.payload;s.domainLastActivity.set(i,new Date),(n==="completed"||n==="failed")&&await s.processQueue()}function wi(s,e){if("metrics"in s&&typeof s.metrics=="object"&&s.metrics!==null){let t=s.metrics;return{testsPassed:typeof t.testsPassed=="number"?t.testsPassed:void 0,testsFailed:typeof t.testsFailed=="number"?t.testsFailed:void 0,coverageChange:typeof t.coverageChange=="number"?t.coverageChange:void 0,securityIssues:typeof t.securityIssues=="number"?t.securityIssues:void 0,performanceMs:typeof t.performanceMs=="number"?t.performanceMs:void 0,linesChanged:typeof t.linesChanged=="number"?t.linesChanged:void 0}}return"testsPassed"in s||"testsFailed"in s?{testsPassed:typeof s.testsPassed=="number"?s.testsPassed:void 0,testsFailed:typeof s.testsFailed=="number"?s.testsFailed:void 0,coverageChange:typeof s.coverageChange=="number"?s.coverageChange:void 0,securityIssues:typeof s.securityIssues=="number"?s.securityIssues:void 0,performanceMs:typeof s.performanceMs=="number"?s.performanceMs:void 0,linesChanged:typeof s.linesChanged=="number"?s.linesChanged:void 0}:(console.error(`[QueenCoordinator] Pattern training skipped for task ${e}: result object has no recognizable metrics shape (keys: ${Object.keys(s).join(", ")})`),null)}function on(s,e,t){let n=s.listAgents({domain:e}),i=n.filter(l=>l.status==="running").length,r=n.filter(l=>l.status==="idle").length,a=n.filter(l=>l.status==="failed").length,o;return a>0&&a>=n.length/2?o="unhealthy":a>0?o="degraded":i>0?o="healthy":o="idle",{status:o,agents:{total:n.length,active:i,idle:r,failed:a},lastActivity:t,errors:[]}}function j(s,e,t){let n=[];for(let i of t){let r=s.get(i);if(!r)n.push(`${i} (domain not loaded)`);else if(!r.executeTask||!r.canHandleTask?.(e)){let a=r.getSupportedTaskTypes?.()??[];n.push(a.length>0?`${i} (supported: ${a.join(", ")})`:i)}}return n}function Mi(s,e){let t=[];for(let[n,i]of s)i.executeTask&&i.canHandleTask?.(e)&&t.push(n);return t}function at(s,e,t){if(e.length>0)return e;let n=E(s);return n.length>0||!t?n:Mi(t,s)}function ve(s,e){return`No handler for task type '${s}' in domain ${e.join("; ")}`}k();k();var ln=St();function ot(s,e,t){let n=s.get(t.priority);n&&kt(n,t,ln);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function N(s,e,t){let n=s.get(t.priority);if(n){let i=n.findIndex(r=>r.id===t.id);i!==-1&&n.splice(i,1)}for(let i of t.targetDomains){let r=e.get(i);if(r){let a=r.findIndex(o=>o.id===t.id);a!==-1&&r.splice(a,1)}}}function be(s,e){let t=0;for(let n of["p0","p1","p2","p3"]){let i=s.get(n);if(i){if(n===e.priority){t+=i.findIndex(r=>r.id===e.id);break}t+=i.length}}return t}async function M(s){if(!(s.runningTaskCounter>=s.config.maxConcurrentTasks)){O.set(s.tasks,(O.get(s.tasks)??0)+1);try{do{Ce.delete(s.tasks);for(let e of["p0","p1","p2","p3"]){let t=s.taskQueue.get(e);if(!t||t.length===0)continue;let n=cn(s,t);for(;n;){N(s.taskQueue,s.domainQueues,n),s.runningTaskCounter++;let i;try{i=await Se(s,n)}catch(r){throw s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),r}if(!i.success&&(s.tasks.get(n.id)?.status??"queued")==="queued"&&await ke(s,n,void 0,i.error.message),s.runningTaskCounter>=s.config.maxConcurrentTasks)return;n=cn(s,t)}}}while(Ce.has(s.tasks)&&s.runningTaskCounter<s.config.maxConcurrentTasks)}finally{let e=(O.get(s.tasks)??1)-1;e>0?O.set(s.tasks,e):(O.delete(s.tasks),Ce.delete(s.tasks))}}}var O=new WeakMap,Ce=new WeakSet;async function V(s){if(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),O.has(s.tasks)){Ce.add(s.tasks);return}M(s).catch(e=>{console.warn("[Queen] Queue drain after a released slot failed:",h(e))})}function cn(s,e){let t=e.shift();for(;t;){let n=s.tasks.get(t.id)?.status;if(n===void 0||n==="queued")return t;N(s.taskQueue,s.domainQueues,t),t=e.shift()}}async function ke(s,e,t,n){s.tasks.set(e.id,{taskId:e.id,task:e,status:"failed",assignedDomain:t,assignedAgents:[],retryCount:s.tasks.get(e.id)?.retryCount??0,error:n,completedAt:new Date}),s.tasksFailed++,s.auditLogger.logFail(e.id,void 0,n),await s.publishEvent("TaskFailed",{taskId:e.id,domain:t,error:n}),await V(s)}function un(s,e){let t=Array.from(s.values());return e&&(e.status&&(t=t.filter(n=>n.status===e.status)),e.domain&&(t=t.filter(n=>n.assignedDomain===e.domain)),e.priority&&(t=t.filter(n=>n.task.priority===e.priority)),e.type&&(t=t.filter(n=>n.task.type===e.type)),e.fromDate&&(t=t.filter(n=>n.task.createdAt>=e.fromDate)),e.toDate&&(t=t.filter(n=>n.task.createdAt<=e.toDate))),t}async function Se(s,e){let t=e.targetDomains.length>0?e.targetDomains:E(e.type);if(t.length===0)return f(new Error(`No domains configured for task type: ${e.type}`));let n,i=1/0;for(let r of t){let a=s.getDomainLoad(r);s.getDomainHealth(r)?.status!=="unhealthy"&&a<i&&(i=a,n=r)}return n?dn(s,e,n):f(new Error("No healthy domain available for task"))}async function dn(s,e,t){if(e.executionOwner!=="caller"&&s.domainPlugins){let c=j(s.domainPlugins,e.type,[t]);if(c.length>0)return Ii(s,e,t,ve(e.type,c))}let n;if(s.tinyDancerRouter){let c={p0:"critical",p1:"high",p2:"normal",p3:"low"},u={description:`${e.type}: ${JSON.stringify(e.payload).slice(0,200)}`,type:e.type,domain:t,priority:Object.hasOwn(c,e.priority)?c[e.priority]:"normal"};n=await s.tinyDancerRouter.route(u),s.config.enableMetrics&&console.log(`[Queen] TinyDancer routing: ${e.type} \u2192 tier=${n.tier}, model=${n.model}, cost=$${n.estimatedCost.toFixed(4)}`)}if(s.domainBreakerRegistry&&!s.domainBreakerRegistry.canExecuteInDomain(t))return f(new Error(`Domain '${t}' circuit breaker is open \u2014 too many recent failures`));if(s.domainTeamManager)try{if(!s.domainTeamManager.getDomainTeam(t)){let u=`${t}-lead`;s.domainTeamManager.createDomainTeam(t,u)}}catch(c){console.warn(`[Queen] Domain team setup for '${t}' failed (continuing):`,c)}let i=n?.tier||"task-worker",r=["task-execution",e.type,...n?[`model:${n.model}`]:[],...n?.triggerMultiModel?["advisor:triggerMultiModel"]:[]],a=await s.requestAgentSpawn(t,i,r,e.id);if(s.tasks.get(e.id)?.status==="cancelled")return a.success&&await s.agentCoordinator.stop(a.value),await V(s),y(e.id);let o=[];a.success&&o.push(a.value);let l={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:o,startedAt:new Date,retryCount:0};s.tasks.set(e.id,l),s.domainLastActivity.set(t,new Date);for(let c of o)s.auditLogger.logAssign(e.id,c,t);if(await s.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:o}),e.executionOwner==="caller")return y(e.id);if(s.domainPlugins){let c=s.domainPlugins.get(t);if(c?.executeTask&&c.canHandleTask?.(e.type)){let u={taskId:e.id,taskType:e.type,payload:e.payload,priority:e.priority,timeout:e.timeout,correlationId:e.correlationId},d;try{d=await c.executeTask(u,m=>Ri(s,m))}catch(m){d=f(Z(m))}if(!d.success){let m=H(s.tasks,e.id);return m.ignored?(m.settledNow&&await V(s),y(e.id)):s.tasks.get(e.id)?.status!=="running"?f(d.error):(s.tasks.set(e.id,{...l,status:"failed",error:d.error.message,completedAt:new Date}),s.tasksFailed++,s.auditLogger.logFail(e.id,o[0],d.error.message),await s.publishEvent("TaskFailed",{taskId:e.id,domain:t,error:d.error.message}),await V(s),f(d.error))}return y(e.id)}}return y(e.id)}async function Ii(s,e,t,n){let i=s.taskTraceContexts.get(e.id);return s.traceCollector&&i&&(s.traceCollector.failSpan(i.spanId,n),s.taskTraceContexts.delete(e.id)),await ke(s,e,t,n),y(e.id)}async function mn(s,e,t){let n=s.tasks.get(e.id)?.status;if(n!==void 0&&n!=="queued")return!1;s.runningTaskCounter++;let i;try{i=await dn(s,e,t)}catch(a){throw s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),a}!i.success&&(s.tasks.get(e.id)?.status??"queued")==="queued"&&await ke(s,e,t,i.error.message);let r=s.tasks.get(e.id);return r?.assignedDomain===t&&(r.status==="running"||r.status==="completed")}async function Ri(s,e){let t=s.tasks.get(e.taskId);if(!t){console.warn(`[Queen] Received completion for unknown task: ${e.taskId}`);return}let n=H(s.tasks,e.taskId);if(n.ignored){n.settledNow&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),await M(s));return}let i={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(s.tasks.set(e.taskId,i),e.success?(s.tasksCompleted++,s.taskDurations.push(e.duration),s.auditLogger.logComplete(e.taskId,t.assignedAgents[0])):(s.tasksFailed++,s.auditLogger.logFail(e.taskId,t.assignedAgents[0],e.error||"Unknown error")),s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),s.coExecutionRepo&&t.assignedAgents.length>=2)try{s.coExecutionRepo.recordSwarmCoExecution(t.assignedAgents,t.assignedDomain||"unknown",e.success,t.task.type)}catch{}for(let r of t.assignedAgents)await s.agentCoordinator.stop(r);await s.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await M(s)}function _i(s,e){return E(e.type).includes(s)}function gn(s,e,t){return _i(e,t)?t.executionOwner==="caller"||!s?!0:j(s,t.type,[e]).length===0:!1}k();async function pn(s){let e=0,t=s.getIdleDomains(),n=s.getBusyDomains();if(t.length===0||n.length===0)return 0;n.sort((i,r)=>s.getDomainLoad(r)-s.getDomainLoad(i));for(let i of n){if(t.length===0)break;let r=s.domainQueues.get(i)||[],a=Math.min(r.length,s.config.workStealing.stealBatchSize);for(let o=0;o<a&&t.length>0&&s.availableSlots()>0;o++){let l=r.find(c=>s.canExecuteInDomain(t[0],c));if(l){let c=t.shift();if(s.removeFromQueues(l),!await s.assignTaskToDomain(l,c))continue;s.auditLogger.logSteal(l.id,i,c),e++,s.tasksStolen++,await s.publishEvent("TaskStolen",{taskId:l.id,fromDomain:i,toDomain:c})}}}return e}function ct(s,e){let t=0,n=10,i=setInterval(async()=>{try{await e(),t=0}catch(r){t++;let a=Math.min(1e3*Math.pow(2,t),3e4);if(console.warn(`[QueenCoordinator] Work-stealing failed (attempt ${t}), backing off ${a}ms`,h(r)),t>n){console.error(`[QueenCoordinator] Work-stealing exceeded ${n} consecutive failures, stopping interval`),clearInterval(i);return}await new Promise(o=>setTimeout(o,a))}},s.workStealing.checkInterval);return i}function lt(s){return typeof s.setMinCutBridge=="function"}function hn(s,e){for(let[t,n]of s)lt(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function fn(s,e,t){try{let n=await s.get("queen:state");if(n){for(let[i,r]of n.tasks)if(r.status==="queued"){if(r.task.executionOwner==="caller"){e.set(i,{...r,status:"failed",error:"Caller-owned task was interrupted before completion; submit a new request.",completedAt:new Date});continue}e.set(i,r),t(r.task)}}}catch(n){console.debug("[QueenCoordinator] State loading failed:",n instanceof Error?n.message:n)}}async function yn(s,e){let t=Array.from(e.entries()).filter(([,n])=>n.status==="queued");await s.set("queen:state",{tasks:t},{namespace:"queen-coordinator",persist:!0})}function Tn(s){return setInterval(async()=>{let e=s.getMetrics();if(await s.publishEvent("MetricsCollected",{metrics:e}),await s.memory.set(`queen:metrics:${Date.now()}`,e,{ttl:86400,namespace:"queen-coordinator"}),s.dynamicScaler)try{let t=s.getAverageTaskDuration(),n={queueDepth:s.getQueuedTaskCount(),activeAgents:s.getActiveAgentCount(),idleAgents:s.getIdleAgentCount(),avgTaskDurationMs:t,errorRate:s.getTasksReceived()>0?s.getTasksFailed()/s.getTasksReceived():0,throughput:e.uptime>0?s.getTasksCompleted()/(e.uptime/1e3):0,timestamp:Date.now()};s.dynamicScaler.recordMetrics(n);let i=s.dynamicScaler.evaluate();i&&i.action!=="maintain"&&(console.log(`[QueenCoordinator] Dynamic scaler: ${i.action} to ${i.targetAgents} agents \u2014 ${i.reason}`),s.dynamicScaler.execute(i).catch(r=>{console.warn("[QueenCoordinator] Dynamic scaling execution error:",r)}))}catch(t){console.warn("[QueenCoordinator] Dynamic scaler metrics error:",t)}},s.config.metricsInterval)}function ut(s,e,t=36e5){let n=Date.now(),i=0;for(let[a,o]of s)if(o.status==="completed"||o.status==="failed"||o.status==="cancelled"){let l=o.completedAt?.getTime()||o.startedAt?.getTime()||0;l>0&&n-l>t&&(s.delete(a),e.delete(a),i++)}let r=1e4;if(e.size>r){let a=e.size-r,o=e.keys();for(let l=0;l<a;l++){let c=o.next().value;c!==void 0&&e.delete(c)}console.log(`[QueenCoordinator] Evicted ${a} oldest trace contexts (max: ${r})`)}return i>0&&console.log(`[QueenCoordinator] Cleaned up ${i} old tasks (retention: ${t}ms)`),i}function vn(s,e){return s&&s.size>0?Array.from(s.keys()):[...e]}var g=gt.create("QueenCoordinator");tn(v);var dt=class{constructor(e,t,n,i,r,a,o,l={}){this.eventBus=e;this.agentCoordinator=t;this.memory=n;this.router=i;this.protocolExecutor=r;this.workflowExecutor=a;this.domainPlugins=o;this.config={...en,...l},this.auditLogger=Me({enableConsoleLog:this.config.enableMetrics,maxEntries:1e3,logPrefix:"[QUEEN]"}),["p0","p1","p2","p3"].forEach(c=>{this.taskQueue.set(c,[])}),this.config.enableRouting!==!1&&(this.tinyDancerRouter=new ee(this.config.routing)),v.forEach(c=>{this.domainQueues.set(c,[]),this.domainLastActivity.set(c,new Date)})}eventBus;agentCoordinator;memory;router;protocolExecutor;workflowExecutor;domainPlugins;config;tasks=new Map;taskQueue=new Map;domainQueues=new Map;domainLastActivity=new Map;initialized=!1;workStealingTimer=null;metricsTimer=null;cleanupTimer=null;startTime=new Date;eventSubscriptionIds=[];runningTaskCounter=0;tasksReceived=0;tasksCompleted=0;tasksFailed=0;tasksStolen=0;taskDurations=new ft(1e3);protocolsExecuted=0;workflowsExecuted=0;auditLogger;minCutBridge=null;tinyDancerRouter=null;domainBreakerRegistry=null;domainTeamManager=null;agentTeamsAdapter=null;tierSelector=null;taskCompletedHook=null;traceCollector=null;taskTraceContexts=new Map;hypothesisManager=null;federationMailbox=null;dynamicScaler=null;coExecutionRepo=null;dependencyGraph=null;availableMcpServers=[];async initialize(){if(!this.initialized){this.startTime=new Date,await this.router.initialize(),this.subscribeToEvents(),this.config.workStealing.enabled&&(this.workStealingTimer=ct(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=Tn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{ut(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await fn(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=Et(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:vt()}),await this.minCutBridge.initialize(),this.domainPlugins&&hn(this.domainPlugins,this.minCutBridge);try{await _.initialize(),g.info("Governance adapter initialized")}catch(e){g.warn("Governance initialization failed (continuing)",{error:e})}this.initializeSubsystems();try{let{join:e}=await import("path"),t=e(process.cwd(),".claude","agents","v3");this.dependencyGraph=qt(t),this.availableMcpServers=Dt(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-2VMGSGQL.js"),i=n();await i.initialize(),this.coExecutionRepo=$t(),this.coExecutionRepo.initialize(i.getDatabase()),this.dependencyGraph.warnings.length>0&&g.warn(`Dependency graph: ${this.dependencyGraph.warnings.length} warning(s)`,{warnings:this.dependencyGraph.warnings.slice(0,5)}),g.info("Dependency intelligence initialized",{agents:this.dependencyGraph.nodes.size,mcpServers:this.availableMcpServers.length})}catch(e){g.warn("Dependency intelligence initialization failed (continuing)",{error:e})}await this.publishEvent("QueenInitialized",{timestamp:new Date,config:this.config,domains:v}),this.initialized=!0}}async dispose(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null),this.metricsTimer&&(clearInterval(this.metricsTimer),this.metricsTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.minCutBridge&&(await this.minCutBridge.dispose(),this.minCutBridge=null),this.domainTeamManager&&(this.domainTeamManager.dispose(),this.domainTeamManager=null),this.agentTeamsAdapter&&(this.agentTeamsAdapter.shutdown(),this.agentTeamsAdapter=null),this.domainBreakerRegistry=null,this.tierSelector=null,this.traceCollector&&(this.traceCollector.dispose(),this.traceCollector=null),this.hypothesisManager&&(this.hypothesisManager.dispose(),this.hypothesisManager=null),this.federationMailbox&&(this.federationMailbox.dispose(),this.federationMailbox=null),this.dynamicScaler&&(this.dynamicScaler.dispose(),this.dynamicScaler=null),await yn(this.memory,this.tasks);for(let[e,t]of this.tasks)(t.status==="queued"||t.status==="running")&&await this.cancelTask(e);await this.publishEvent("QueenShutdown",{timestamp:new Date,metrics:this.getMetrics()});for(let e of this.eventSubscriptionIds)this.router.unsubscribe(e);this.eventSubscriptionIds=[],await this.router.dispose(),this.initialized=!1}validateTaskExecutable(e,t=[]){let n=at(e,t,this.domainPlugins);if(n.length===0)return f(new Error(`Unknown task type '${e}': no domain is configured for it and no loaded domain handles it. Pass a target domain.`));if(!this.domainPlugins)return y(void 0);let i=j(this.domainPlugins,e,n);return i.length===0?y(void 0):f(new Error(ve(e,i)))}async submitTask(e){if(!this.initialized)return f(new Error("Queen Coordinator not initialized"));let t=`task_${C()}`,n={...e,targetDomains:E(e.type).length>0?e.targetDomains:[...at(e.type,e.targetDomains,this.domainPlugins)],id:t,createdAt:new Date,timeout:e.timeout||this.config.defaultTaskTimeout},i={taskId:n.id,taskType:n.type,agentId:n.requester||`queen-task:${n.id}`,domain:n.targetDomains[0]||"test-generation",priority:n.priority,payload:n.payload};try{let r=await _.beforeTaskExecution(i);if(!r.allowed)return this.auditLogger.logFail(t,"governance",r.reason||"Governance check failed"),await this.publishEvent("TaskRejected",{taskId:t,reason:r.reason,escalate:r.escalate}),f(new Error(`Task blocked by governance: ${r.reason}`))}catch(r){g.warn("Governance check error (continuing)",{error:r})}this.runningTaskCounter++;try{if(this.runningTaskCounter>this.config.maxConcurrentTasks)return this.runningTaskCounter--,this.queueTask(n);this.auditLogger.logSubmit(t,{type:n.type,priority:n.priority}),this.selectFleetTier(n),this.startTaskTrace(n,t);let r=await Se(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),y(t)):(this.tasks.has(t)||(this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1)),r)}catch(r){throw this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1),r}}async cancelTask(e){let t=this.tasks.get(e);if(!t)return f(new Error(`Task not found: ${e}`));if(t.status==="cancelled")return y(void 0);if(t.status==="completed"||t.status==="failed")return f(new Error(`Task already finished: ${e}`));let n=t.status==="running"||t.status==="assigned";this.tasks.set(e,{...t,status:"cancelled",completedAt:new Date,cancellationResultPending:n}),N(this.taskQueue,this.domainQueues,t.task);for(let i of t.assignedAgents)await this.agentCoordinator.stop(i);return this.auditLogger.logCancel(e),await this.publishEvent("TaskCancelled",{taskId:e}),y(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return un(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return on(this.agentCoordinator,e,this.domainLastActivity.get(e))}getDomainLoad(e){let t=this.domainQueues.get(e)||[],n=Array.from(this.tasks.values()).filter(i=>i.assignedDomain===e&&i.status==="running");return t.length+n.length}getIdleDomains(){let e=Date.now(),t=this.config.workStealing.idleThreshold;return v.filter(n=>{let i=this.domainLastActivity.get(n);return this.getDomainLoad(n)===0&&i&&e-i.getTime()>t})}getBusyDomains(){return v.filter(e=>this.getDomainLoad(e)>this.config.workStealing.loadThreshold)}getSpawnPlan(e){return this.dependencyGraph?zt(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=ct(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return pn(this.createWorkStealingContext())}listAllAgents(){return this.agentCoordinator.listAgents()}getAgentsByDomain(e){return this.agentCoordinator.listAgents({domain:e})}async requestAgentSpawn(e,t,n,i){if(!this.agentCoordinator.canSpawn())return f(new Error("Maximum concurrent agents reached (15)"));if(this.dependencyGraph&&this.availableMcpServers.length>0)try{for(let[,a]of this.dependencyGraph.nodes){let o=a.dependencies.mcpServers;if(!o||o.length===0)continue;let l=o.filter(c=>c.required&&!this.availableMcpServers.includes(c.name));if(l.length>0){g.warn(`Pre-spawn MCP advisory: ${a.agentName} needs ${l.map(c=>c.name).join(", ")}`,{agent:a.agentName,domain:e,missing:l.map(c=>c.name)});break}}}catch{}let r=await this.agentCoordinator.spawn({name:`${e}-${t}-${Date.now()}`,domain:e,type:t,capabilities:n});if(r.success){if(this.domainLastActivity.set(e,new Date),this.domainTeamManager&&typeof this.domainTeamManager.getDomainTeam=="function")try{if(this.domainTeamManager.getDomainTeam(e))this.domainTeamManager.addTeammate(e,r.value)||g.warn(`Agent ${r.value} could not join ${e} team (full)`);else try{this.domainTeamManager.createDomainTeam(e,r.value)}catch{this.domainTeamManager.addTeammate(e,r.value)||g.warn(`Agent ${r.value} could not join ${e} team (full or max teams reached)`)}}catch(a){g.warn(`Auto-team-wiring failed for ${r.value}`,{error:a})}await this.publishEvent("AgentSpawned",{agentId:r.value,domain:e,type:t,capabilities:n,...i?{taskId:i}:{}})}return r}getHealth(){let e=new Map,t=[],n=0,i=0,r=vn(this.domainPlugins,v);for(let u of r){let d=this.getDomainHealth(u);d&&(e.set(u,d),d.status==="unhealthy"?(n++,t.push({domain:u,severity:"high",message:`Domain ${u} is unhealthy`,timestamp:new Date})):d.status==="degraded"&&(i++,t.push({domain:u,severity:"medium",message:`Domain ${u} is degraded`,timestamp:new Date})))}let a=this.agentCoordinator.listAgents(),o=a.filter(u=>u.status==="running").length,l="healthy";n>0?l="unhealthy":i>r.length/2&&(l="degraded");let c={status:l,domainHealth:e,totalAgents:a.length,activeAgents:o,pendingTasks:this.getQueuedTaskCount(),runningTasks:this.getRunningTaskCount(),workStealingActive:this.workStealingTimer!==null,lastHealthCheck:new Date,issues:t};return this.minCutBridge?this.minCutBridge.extendQueenHealth(c):c}getMetrics(){let e=new Map;for(let o of v){let l=this.getDomainLoad(o);e.set(o,l)}let t=this.agentCoordinator.listAgents(),n=t.filter(o=>o.status==="running").length,i=t.length>0?n/t.length:0,r=this.taskDurations.average(),a={tasksReceived:this.tasksReceived,tasksCompleted:this.tasksCompleted,tasksFailed:this.tasksFailed,tasksStolen:this.tasksStolen,averageTaskDuration:r,domainUtilization:e,agentUtilization:i,protocolsExecuted:this.protocolsExecuted,workflowsExecuted:this.workflowsExecuted,uptime:Date.now()-this.startTime.getTime()};return this.minCutBridge?this.minCutBridge.extendQueenMetrics(a):a}getMinCutBridge(){return this.minCutBridge}injectMinCutBridgeIntoDomain(e){if(!this.minCutBridge)return g.warn("Cannot inject MinCut bridge: bridge not initialized"),!1;if(!this.domainPlugins)return g.warn("Cannot inject MinCut bridge: no domain plugins registered"),!1;let t=this.domainPlugins.get(e);return t?lt(t)?(t.setMinCutBridge(this.minCutBridge),g.info(`MinCut bridge injected into ${e} (late binding)`),!0):(g.warn(`Domain ${e} does not support MinCut integration`),!1):(g.warn(`Cannot inject MinCut bridge: domain ${e} not found`),!1)}getTinyDancerRouter(){return this.tinyDancerRouter}getDomainBreakerRegistry(){return this.domainBreakerRegistry}getDomainTeamManager(){return this.domainTeamManager}getAgentTeamsAdapter(){return this.agentTeamsAdapter}getTierSelector(){return this.tierSelector}getTraceCollector(){return this.traceCollector}getHypothesisManager(){return this.hypothesisManager}getFederationMailbox(){return this.federationMailbox}getDynamicScaler(){return this.dynamicScaler}connectReasoningBank(e){let t=new pe(e);this.taskCompletedHook=new ge({},t),g.info("ReasoningBank connected for pattern training")}async executeProtocol(e,t){if(!this.protocolExecutor)return f(new Error("Protocol executor not configured"));let n=await this.protocolExecutor.execute(e,t);return n.success?(this.protocolsExecuted++,await this.publishEvent("ProtocolExecuted",{protocolId:e,executionId:n.value.executionId}),y(n.value.executionId)):n}async executeWorkflow(e,t){if(!this.workflowExecutor)return f(new Error("Workflow executor not configured"));let n=await this.workflowExecutor.execute(e,t);return n.success?(this.workflowsExecuted++,await this.publishEvent("WorkflowExecuted",{workflowId:e,executionId:n.value.executionId}),y(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return ut(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=sn(this.createEventHandlerContext(),v)}enqueueTaskInternal(e){ot(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:C(),type:`Queen${e}`,timestamp:new Date,source:"queen-coordinator",payload:t})}queueTask(e){this.enqueueTaskInternal(e);let t={taskId:e.id,task:e,status:"queued",assignedAgents:[],retryCount:0};return this.tasks.set(e.id,t),this.tasksReceived++,this.auditLogger.logSubmit(e.id,{type:e.type,priority:e.priority}),this.auditLogger.logQueue(e.id,be(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:be(this.taskQueue,e)}),y(e.id)}selectFleetTier(e){if(this.tierSelector)try{let t={trigger:e.payload?.trigger??"manual",changedFiles:e.payload?.changedFiles,affectedDomains:e.targetDomains,severity:e.priority==="p0"?"critical":e.priority==="p1"?"high":void 0,isHotfix:e.payload?.isHotfix},n=this.tierSelector.selectTier(t);return g.info(`Fleet tier: ${n.selectedTier} (${n.reason})`),n.selectedTier}catch(t){g.warn("Tier selection error (continuing)",{error:t});return}}startTaskTrace(e,t){if(this.traceCollector)try{let{context:n}=this.traceCollector.startTrace({operationName:e.type,agentId:e.requester||"queen",domain:e.targetDomains[0]||"test-generation",tags:{taskId:t,priority:e.priority}});if(this.taskTraceContexts.size>=1e4){let r=this.taskTraceContexts.keys().next().value;r!==void 0&&this.taskTraceContexts.delete(r)}this.taskTraceContexts.set(t,n)}catch(n){g.warn("Trace start error (continuing)",{error:n})}}getRunningTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="running"||e.status==="assigned").length}getQueuedTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="queued").length}initializeSubsystems(){if(this.config.enableCircuitBreakers!==!1)try{this.domainBreakerRegistry=Vt(),g.info("Domain circuit breaker registry initialized")}catch(e){g.warn("Circuit breaker initialization failed (continuing)",{error:e})}if(this.config.enableDomainTeams!==!1)try{this.agentTeamsAdapter=Be(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=$e(this.agentTeamsAdapter),g.info("Domain team manager initialized")}catch(e){g.warn("Domain team manager initialization failed (continuing)",{error:e})}if(this.config.enableFleetTiers!==!1)try{this.tierSelector=Ge(),g.info("Fleet tier selector initialized")}catch(e){g.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=Qe(),g.info("Trace collector initialized")}catch(e){g.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=Ve(),this.federationMailbox=Ye(),this.dynamicScaler=Xe(),g.info("Phase 4 modules initialized (hypotheses, federation, scaling)")}catch(e){g.warn("Phase 4 initialization failed (continuing)",{error:e})}}createEventHandlerContext(){let e=this;return{config:e.config,tasks:e.tasks,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,router:e.router,agentCoordinator:e.agentCoordinator,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get domainBreakerRegistry(){return e.domainBreakerRegistry},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get taskCompletedHook(){return e.taskCompletedHook},get hypothesisManager(){return e.hypothesisManager},processQueue:()=>M(e.createTaskContext()),enqueueTask:t=>e.enqueueTaskInternal(t)}}createTaskContext(){let e=this;return{config:e.config,tasks:e.tasks,taskQueue:e.taskQueue,domainQueues:e.domainQueues,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,agentCoordinator:e.agentCoordinator,domainPlugins:e.domainPlugins,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksReceived(){return e.tasksReceived},set tasksReceived(t){e.tasksReceived=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get tinyDancerRouter(){return e.tinyDancerRouter},get domainBreakerRegistry(){return e.domainBreakerRegistry},get domainTeamManager(){return e.domainTeamManager},get tierSelector(){return e.tierSelector},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get coExecutionRepo(){return e.coExecutionRepo},requestAgentSpawn:(t,n,i,r)=>e.requestAgentSpawn(t,n,i,r),publishEvent:(t,n)=>e.publishEvent(t,n),getDomainLoad:t=>e.getDomainLoad(t),getDomainHealth:t=>e.getDomainHealth(t)}}createWorkStealingContext(){let e=this;return{config:e.config,domainQueues:e.domainQueues,auditLogger:e.auditLogger,get tasksStolen(){return e.tasksStolen},set tasksStolen(t){e.tasksStolen=t},getIdleDomains:()=>e.getIdleDomains(),getBusyDomains:()=>e.getBusyDomains(),getDomainLoad:t=>e.getDomainLoad(t),availableSlots:()=>e.config.maxConcurrentTasks-e.runningTaskCounter,canExecuteInDomain:(t,n)=>(e.tasks.get(n.id)?.status??"queued")==="queued"&&gn(e.domainPlugins,t,n),removeFromQueues:t=>N(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>mn(e.createTaskContext(),t,n),publishEvent:(t,n)=>e.publishEvent(t,n)}}createMetricsContext(){let e=this;return{config:e.config,memory:e.memory,get dynamicScaler(){return e.dynamicScaler},getMetrics:()=>e.getMetrics(),publishEvent:(t,n)=>e.publishEvent(t,n),getQueuedTaskCount:()=>e.getQueuedTaskCount(),getActiveAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="running").length,getIdleAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="idle").length,getAverageTaskDuration:()=>e.taskDurations.average(),getTasksReceived:()=>e.tasksReceived,getTasksFailed:()=>e.tasksFailed,getTasksCompleted:()=>e.tasksCompleted}}};function Go(s,e,t,n,i,r){return new dt(s.eventBus,s.coordinator,s.memory,e,t,n,i,r)}export{Ti as a,q as b,dt as c,Go as d};
|
|
180
|
+
`}}return t}getRecommendations(e){switch(e.loopType){case"strategic":return[...e.recommendations.forRiskAssessor,...e.recommendations.forQualityCriteria];case"tactical":return e.recommendations.forProductFactorsAssessor;case"operational":return[...e.recommendations.forTestArchitect,...e.recommendations.antiPatterns];case"quality-criteria":return e.recommendations.forRequirementsValidator;default:return[]}}filterManagedHooks(e){if(process.env.AQE_HOOKS_MANAGED_ONLY!=="true")return e;let t=e.filter(([n])=>n.startsWith("managed:"));return t.length<e.length&&console.log(`[CrossPhaseHooks] AQE_HOOKS_MANAGED_ONLY: filtered ${e.length-t.length} non-managed hooks`),t}async isBlockedUrl(e){if(!e.includes("://"))return!1;let t=await we(e);return t.safe?!1:(console.warn(`[CrossPhaseHooks] SSRF blocked: ${t.reason}`),!0)}checkConditions(e,t){return!e||e.length===0?!0:e.every(n=>this.evaluateCondition(n,t))}evaluateCondition(e,t){try{let n=e.split(/\s*(>|<|>=|<=|==|!=)\s*/);if(n.length!==3)return!1;let[i,r,a]=n,o=this.getValueFromPath(t,i),l=isNaN(Number(a))?a:Number(a),c=typeof o=="number"?o:Number(o),u=typeof l=="number"?l:Number(l);switch(r){case">":return c>u;case"<":return c<u;case">=":return c>=u;case"<=":return c<=u;case"==":return o==l;case"!=":return o!=l;default:return!1}}catch{return!1}}getValueFromPath(e,t){return t.split(".").reduce((n,i)=>{if(n&&typeof n=="object"&&Object.hasOwn(n,i))return n[i]},e)}extractFromContext(e,t){let n={};for(let[i,r]of Object.entries(e))n[i]=this.getValueFromPath(t,r);return n}parseMaxAge(e){let t=e.match(/^(\d+)(d|h|m|s)$/);if(!t)return 0;let[,n,i]=t,r=parseInt(n,10);switch(i){case"d":return r*24*60*60*1e3;case"h":return r*60*60*1e3;case"m":return r*60*1e3;case"s":return r*1e3;default:return 0}}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(n=>n(t))}async runCleanup(){if(!this.config?.cleanup.enabled)return;console.log("[CrossPhaseHooks] Running cleanup...");let e=await this.memory.cleanupExpired();console.log(`[CrossPhaseHooks] Cleanup complete: ${e.deleted} signals deleted`)}},rt=null;function rn(s){return rt||(rt=new st(s)),rt}function H(s,e){let t=s.get(e);return t?.status!=="cancelled"?{ignored:!1,settledNow:!1}:t.cancellationResultPending?(s.set(e,{...t,cancellationResultPending:!1}),{ignored:!0,settledNow:!0}):{ignored:!0,settledNow:!1}}function sn(s,e){let t=[];for(let a of e){let o=s.router.subscribeToDoamin(a,async l=>{await Di(s,l)});t.push(o)}let n=s.router.subscribeToEventType("TaskCompleted",async a=>{await Ai(s,a)});t.push(n);let i=s.router.subscribeToEventType("TaskFailed",async a=>{await xi(s,a)});t.push(i);let r=s.router.subscribeToEventType("AgentStatusChanged",async a=>{await Ei(s,a)});return t.push(r),t}async function Di(s,e){s.domainLastActivity.set(e.source,new Date),await s.processQueue()}async function an(s,e){for(let t of e.assignedAgents)await s.agentCoordinator.stop(t)}async function Ai(s,e){let{taskId:t,result:n}=e.payload,i=H(s.tasks,t);if(i.ignored){i.settledNow&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),await s.processQueue());return}let r=s.tasks.get(t);if(r){await an(s,r),(r.status==="running"||r.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1));let a=r.startedAt?Date.now()-r.startedAt.getTime():0;s.tasks.set(t,{...r,status:"completed",completedAt:new Date,result:n}),s.tasksCompleted++,s.taskDurations.push(a),s.auditLogger.logComplete(t,r.assignedAgents[0]);try{let o=rn(),l=r.assignedAgents[0];l&&await o.onAgentComplete(l,{taskId:t,taskType:r.task.type,domain:r.assignedDomain,result:n,duration:a})}catch(o){console.warn("[QueenCoordinator] Cross-phase hook error:",o)}try{await _.afterTaskExecution({taskId:t,taskType:r.task.type,agentId:r.assignedAgents[0]||"unknown",domain:r.assignedDomain||"test-generation",priority:r.task.priority},!0,0,0)}catch(o){console.warn("[QueenCoordinator] Governance tracking error:",o)}if(s.domainBreakerRegistry&&r.assignedDomain&&s.domainBreakerRegistry.getBreaker(r.assignedDomain).recordSuccess(),s.traceCollector){let o=s.taskTraceContexts.get(t);o&&(s.traceCollector.completeSpan(o.spanId),s.taskTraceContexts.delete(t))}if(s.taskCompletedHook)try{let o=typeof n=="object"&&n!==null?n:null;if(o===null)console.error(`[QueenCoordinator] Pattern training skipped for task ${t}: result is not an object (got ${typeof n})`);else{let l=wi(o,t);if(l){let c={taskId:t,agentId:r.assignedAgents[0]||"unknown",domain:r.assignedDomain||"test-generation",type:r.task.type,status:"completed",output:o,metrics:l,duration:a,timestamp:Date.now()};s.taskCompletedHook.onTaskCompleted(c).catch(u=>{console.warn("[QueenCoordinator] Pattern training error:",u)})}}}catch(o){console.warn("[QueenCoordinator] Pattern training setup error:",o)}}await s.processQueue()}async function xi(s,e){let{taskId:t,error:n,callerError:i}=e.payload,r=H(s.tasks,t);if(r.ignored){r.settledNow&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),await s.processQueue());return}let a=s.tasks.get(t);if(a){if(await an(s,a),(a.status==="running"||a.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1)),s.domainBreakerRegistry&&a.assignedDomain&&!i&&s.domainBreakerRegistry.getBreaker(a.assignedDomain).recordFailure(new Error(n||"Task failed")),s.traceCollector){let l=s.taskTraceContexts.get(t);l&&(s.traceCollector.failSpan(l.spanId,n||"Task failed"),s.taskTraceContexts.delete(t))}let o=a.task.executionOwner==="caller";if(!i&&!o&&a.retryCount<s.config.taskRetryLimit){s.auditLogger.logFail(t,a.assignedAgents[0],n);let l={...a,status:"queued",retryCount:a.retryCount+1,error:n};s.tasks.set(t,l),s.enqueueTask(a.task)}else{s.tasks.set(t,{...a,status:"failed",completedAt:new Date,error:n}),s.tasksFailed++,s.auditLogger.logFail(t,a.assignedAgents[0],n);try{await _.afterTaskExecution({taskId:t,taskType:a.task.type,agentId:a.assignedAgents[0]||"unknown",domain:a.assignedDomain||"test-generation",priority:a.task.priority},!1,0,0)}catch(l){console.warn("[QueenCoordinator] Governance tracking error:",l)}if(!i&&s.hypothesisManager&&(a.task.priority==="p0"||a.task.priority==="p1"))try{let l=a.assignedDomain||"test-generation",c=s.hypothesisManager.createInvestigation(t,l,`Root cause analysis for ${a.task.type} failure: ${n}`);s.hypothesisManager.addHypothesis(c.id,`Infrastructure failure in domain '${l}' caused task ${t} to fail`,"log-analysis",`${l}-lead`),s.hypothesisManager.addHypothesis(c.id,`Logic/configuration error in task payload caused ${a.task.type} to fail: ${n}`,"code-analysis",a.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${c.id}`)}catch(l){console.warn("[QueenCoordinator] Hypothesis creation error:",l)}}}await s.processQueue()}async function Ei(s,e){let{agentId:t,status:n,domain:i}=e.payload;s.domainLastActivity.set(i,new Date),(n==="completed"||n==="failed")&&await s.processQueue()}function wi(s,e){if("metrics"in s&&typeof s.metrics=="object"&&s.metrics!==null){let t=s.metrics;return{testsPassed:typeof t.testsPassed=="number"?t.testsPassed:void 0,testsFailed:typeof t.testsFailed=="number"?t.testsFailed:void 0,coverageChange:typeof t.coverageChange=="number"?t.coverageChange:void 0,securityIssues:typeof t.securityIssues=="number"?t.securityIssues:void 0,performanceMs:typeof t.performanceMs=="number"?t.performanceMs:void 0,linesChanged:typeof t.linesChanged=="number"?t.linesChanged:void 0}}return"testsPassed"in s||"testsFailed"in s?{testsPassed:typeof s.testsPassed=="number"?s.testsPassed:void 0,testsFailed:typeof s.testsFailed=="number"?s.testsFailed:void 0,coverageChange:typeof s.coverageChange=="number"?s.coverageChange:void 0,securityIssues:typeof s.securityIssues=="number"?s.securityIssues:void 0,performanceMs:typeof s.performanceMs=="number"?s.performanceMs:void 0,linesChanged:typeof s.linesChanged=="number"?s.linesChanged:void 0}:(console.error(`[QueenCoordinator] Pattern training skipped for task ${e}: result object has no recognizable metrics shape (keys: ${Object.keys(s).join(", ")})`),null)}function on(s,e,t){let n=s.listAgents({domain:e}),i=n.filter(l=>l.status==="running").length,r=n.filter(l=>l.status==="idle").length,a=n.filter(l=>l.status==="failed").length,o;return a>0&&a>=n.length/2?o="unhealthy":a>0?o="degraded":i>0?o="healthy":o="idle",{status:o,agents:{total:n.length,active:i,idle:r,failed:a},lastActivity:t,errors:[]}}function j(s,e,t){let n=[];for(let i of t){let r=s.get(i);if(!r)n.push(`${i} (domain not loaded)`);else if(!r.executeTask||!r.canHandleTask?.(e)){let a=r.getSupportedTaskTypes?.()??[];n.push(a.length>0?`${i} (supported: ${a.join(", ")})`:i)}}return n}function Mi(s,e){let t=[];for(let[n,i]of s)i.executeTask&&i.canHandleTask?.(e)&&t.push(n);return t}function at(s,e,t){if(e.length>0)return e;let n=E(s);return n.length>0||!t?n:Mi(t,s)}function ve(s,e){return`No handler for task type '${s}' in domain ${e.join("; ")}`}k();k();var ln=St();function ot(s,e,t){let n=s.get(t.priority);n&&kt(n,t,ln);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function N(s,e,t){let n=s.get(t.priority);if(n){let i=n.findIndex(r=>r.id===t.id);i!==-1&&n.splice(i,1)}for(let i of t.targetDomains){let r=e.get(i);if(r){let a=r.findIndex(o=>o.id===t.id);a!==-1&&r.splice(a,1)}}}function be(s,e){let t=0;for(let n of["p0","p1","p2","p3"]){let i=s.get(n);if(i){if(n===e.priority){t+=i.findIndex(r=>r.id===e.id);break}t+=i.length}}return t}async function M(s){if(!(s.runningTaskCounter>=s.config.maxConcurrentTasks)){O.set(s.tasks,(O.get(s.tasks)??0)+1);try{do{Ce.delete(s.tasks);for(let e of["p0","p1","p2","p3"]){let t=s.taskQueue.get(e);if(!t||t.length===0)continue;let n=cn(s,t);for(;n;){N(s.taskQueue,s.domainQueues,n),s.runningTaskCounter++;let i;try{i=await Se(s,n)}catch(r){throw s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),r}if(!i.success&&(s.tasks.get(n.id)?.status??"queued")==="queued"&&await ke(s,n,void 0,i.error.message),s.runningTaskCounter>=s.config.maxConcurrentTasks)return;n=cn(s,t)}}}while(Ce.has(s.tasks)&&s.runningTaskCounter<s.config.maxConcurrentTasks)}finally{let e=(O.get(s.tasks)??1)-1;e>0?O.set(s.tasks,e):(O.delete(s.tasks),Ce.delete(s.tasks))}}}var O=new WeakMap,Ce=new WeakSet;async function V(s){if(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),O.has(s.tasks)){Ce.add(s.tasks);return}M(s).catch(e=>{console.warn("[Queen] Queue drain after a released slot failed:",h(e))})}function cn(s,e){let t=e.shift();for(;t;){let n=s.tasks.get(t.id)?.status;if(n===void 0||n==="queued")return t;N(s.taskQueue,s.domainQueues,t),t=e.shift()}}async function ke(s,e,t,n){s.tasks.set(e.id,{taskId:e.id,task:e,status:"failed",assignedDomain:t,assignedAgents:[],retryCount:s.tasks.get(e.id)?.retryCount??0,error:n,completedAt:new Date}),s.tasksFailed++,s.auditLogger.logFail(e.id,void 0,n),await s.publishEvent("TaskFailed",{taskId:e.id,domain:t,error:n}),await V(s)}function un(s,e){let t=Array.from(s.values());return e&&(e.status&&(t=t.filter(n=>n.status===e.status)),e.domain&&(t=t.filter(n=>n.assignedDomain===e.domain)),e.priority&&(t=t.filter(n=>n.task.priority===e.priority)),e.type&&(t=t.filter(n=>n.task.type===e.type)),e.fromDate&&(t=t.filter(n=>n.task.createdAt>=e.fromDate)),e.toDate&&(t=t.filter(n=>n.task.createdAt<=e.toDate))),t}async function Se(s,e){let t=e.targetDomains.length>0?e.targetDomains:E(e.type);if(t.length===0)return f(new Error(`No domains configured for task type: ${e.type}`));let n,i=1/0;for(let r of t){let a=s.getDomainLoad(r);s.getDomainHealth(r)?.status!=="unhealthy"&&a<i&&(i=a,n=r)}return n?dn(s,e,n):f(new Error("No healthy domain available for task"))}async function dn(s,e,t){if(e.executionOwner!=="caller"&&s.domainPlugins){let c=j(s.domainPlugins,e.type,[t]);if(c.length>0)return Ii(s,e,t,ve(e.type,c))}let n;if(s.tinyDancerRouter){let c={p0:"critical",p1:"high",p2:"normal",p3:"low"},u={description:`${e.type}: ${JSON.stringify(e.payload).slice(0,200)}`,type:e.type,domain:t,priority:Object.hasOwn(c,e.priority)?c[e.priority]:"normal"};n=await s.tinyDancerRouter.route(u),s.config.enableMetrics&&console.log(`[Queen] TinyDancer routing: ${e.type} \u2192 tier=${n.tier}, model=${n.model}, cost=$${n.estimatedCost.toFixed(4)}`)}if(s.domainBreakerRegistry&&!s.domainBreakerRegistry.canExecuteInDomain(t))return f(new Error(`Domain '${t}' circuit breaker is open \u2014 too many recent failures`));if(s.domainTeamManager)try{if(!s.domainTeamManager.getDomainTeam(t)){let u=`${t}-lead`;s.domainTeamManager.createDomainTeam(t,u)}}catch(c){console.warn(`[Queen] Domain team setup for '${t}' failed (continuing):`,c)}let i=n?.tier||"task-worker",r=["task-execution",e.type,...n?[`model:${n.model}`]:[],...n?.triggerMultiModel?["advisor:triggerMultiModel"]:[]],a=await s.requestAgentSpawn(t,i,r,e.id);if(s.tasks.get(e.id)?.status==="cancelled")return a.success&&await s.agentCoordinator.stop(a.value),await V(s),y(e.id);let o=[];a.success&&o.push(a.value);let l={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:o,startedAt:new Date,retryCount:0};s.tasks.set(e.id,l),s.domainLastActivity.set(t,new Date);for(let c of o)s.auditLogger.logAssign(e.id,c,t);if(await s.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:o}),e.executionOwner==="caller")return y(e.id);if(s.domainPlugins){let c=s.domainPlugins.get(t);if(c?.executeTask&&c.canHandleTask?.(e.type)){let u={taskId:e.id,taskType:e.type,payload:e.payload,priority:e.priority,timeout:e.timeout,correlationId:e.correlationId},d;try{d=await c.executeTask(u,m=>Ri(s,m))}catch(m){d=f(Z(m))}if(!d.success){let m=H(s.tasks,e.id);return m.ignored?(m.settledNow&&await V(s),y(e.id)):s.tasks.get(e.id)?.status!=="running"?f(d.error):(s.tasks.set(e.id,{...l,status:"failed",error:d.error.message,completedAt:new Date}),s.tasksFailed++,s.auditLogger.logFail(e.id,o[0],d.error.message),await s.publishEvent("TaskFailed",{taskId:e.id,domain:t,error:d.error.message}),await V(s),f(d.error))}return y(e.id)}}return y(e.id)}async function Ii(s,e,t,n){let i=s.taskTraceContexts.get(e.id);return s.traceCollector&&i&&(s.traceCollector.failSpan(i.spanId,n),s.taskTraceContexts.delete(e.id)),await ke(s,e,t,n),y(e.id)}async function mn(s,e,t){let n=s.tasks.get(e.id)?.status;if(n!==void 0&&n!=="queued")return!1;s.runningTaskCounter++;let i;try{i=await dn(s,e,t)}catch(a){throw s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),a}!i.success&&(s.tasks.get(e.id)?.status??"queued")==="queued"&&await ke(s,e,t,i.error.message);let r=s.tasks.get(e.id);return r?.assignedDomain===t&&(r.status==="running"||r.status==="completed")}async function Ri(s,e){let t=s.tasks.get(e.taskId);if(!t){console.warn(`[Queen] Received completion for unknown task: ${e.taskId}`);return}let n=H(s.tasks,e.taskId);if(n.ignored){n.settledNow&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),await M(s));return}let i={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(s.tasks.set(e.taskId,i),e.success?(s.tasksCompleted++,s.taskDurations.push(e.duration),s.auditLogger.logComplete(e.taskId,t.assignedAgents[0])):(s.tasksFailed++,s.auditLogger.logFail(e.taskId,t.assignedAgents[0],e.error||"Unknown error")),s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),s.coExecutionRepo&&t.assignedAgents.length>=2)try{s.coExecutionRepo.recordSwarmCoExecution(t.assignedAgents,t.assignedDomain||"unknown",e.success,t.task.type)}catch{}for(let r of t.assignedAgents)await s.agentCoordinator.stop(r);await s.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await M(s)}function _i(s,e){return E(e.type).includes(s)}function gn(s,e,t){return _i(e,t)?t.executionOwner==="caller"||!s?!0:j(s,t.type,[e]).length===0:!1}k();async function pn(s){let e=0,t=s.getIdleDomains(),n=s.getBusyDomains();if(t.length===0||n.length===0)return 0;n.sort((i,r)=>s.getDomainLoad(r)-s.getDomainLoad(i));for(let i of n){if(t.length===0)break;let r=s.domainQueues.get(i)||[],a=Math.min(r.length,s.config.workStealing.stealBatchSize);for(let o=0;o<a&&t.length>0&&s.availableSlots()>0;o++){let l=r.find(c=>s.canExecuteInDomain(t[0],c));if(l){let c=t.shift();if(s.removeFromQueues(l),!await s.assignTaskToDomain(l,c))continue;s.auditLogger.logSteal(l.id,i,c),e++,s.tasksStolen++,await s.publishEvent("TaskStolen",{taskId:l.id,fromDomain:i,toDomain:c})}}}return e}function ct(s,e){let t=0,n=10,i=setInterval(async()=>{try{await e(),t=0}catch(r){t++;let a=Math.min(1e3*Math.pow(2,t),3e4);if(console.warn(`[QueenCoordinator] Work-stealing failed (attempt ${t}), backing off ${a}ms`,h(r)),t>n){console.error(`[QueenCoordinator] Work-stealing exceeded ${n} consecutive failures, stopping interval`),clearInterval(i);return}await new Promise(o=>setTimeout(o,a))}},s.workStealing.checkInterval);return i}function lt(s){return typeof s.setMinCutBridge=="function"}function hn(s,e){for(let[t,n]of s)lt(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function fn(s,e,t){try{let n=await s.get("queen:state");if(n){for(let[i,r]of n.tasks)if(r.status==="queued"){if(r.task.executionOwner==="caller"){e.set(i,{...r,status:"failed",error:"Caller-owned task was interrupted before completion; submit a new request.",completedAt:new Date});continue}e.set(i,r),t(r.task)}}}catch(n){console.debug("[QueenCoordinator] State loading failed:",n instanceof Error?n.message:n)}}async function yn(s,e){let t=Array.from(e.entries()).filter(([,n])=>n.status==="queued");await s.set("queen:state",{tasks:t},{namespace:"queen-coordinator",persist:!0})}function Tn(s){return setInterval(async()=>{let e=s.getMetrics();if(await s.publishEvent("MetricsCollected",{metrics:e}),await s.memory.set(`queen:metrics:${Date.now()}`,e,{ttl:86400,namespace:"queen-coordinator"}),s.dynamicScaler)try{let t=s.getAverageTaskDuration(),n={queueDepth:s.getQueuedTaskCount(),activeAgents:s.getActiveAgentCount(),idleAgents:s.getIdleAgentCount(),avgTaskDurationMs:t,errorRate:s.getTasksReceived()>0?s.getTasksFailed()/s.getTasksReceived():0,throughput:e.uptime>0?s.getTasksCompleted()/(e.uptime/1e3):0,timestamp:Date.now()};s.dynamicScaler.recordMetrics(n);let i=s.dynamicScaler.evaluate();i&&i.action!=="maintain"&&(console.log(`[QueenCoordinator] Dynamic scaler: ${i.action} to ${i.targetAgents} agents \u2014 ${i.reason}`),s.dynamicScaler.execute(i).catch(r=>{console.warn("[QueenCoordinator] Dynamic scaling execution error:",r)}))}catch(t){console.warn("[QueenCoordinator] Dynamic scaler metrics error:",t)}},s.config.metricsInterval)}function ut(s,e,t=36e5){let n=Date.now(),i=0;for(let[a,o]of s)if(o.status==="completed"||o.status==="failed"||o.status==="cancelled"){let l=o.completedAt?.getTime()||o.startedAt?.getTime()||0;l>0&&n-l>t&&(s.delete(a),e.delete(a),i++)}let r=1e4;if(e.size>r){let a=e.size-r,o=e.keys();for(let l=0;l<a;l++){let c=o.next().value;c!==void 0&&e.delete(c)}console.log(`[QueenCoordinator] Evicted ${a} oldest trace contexts (max: ${r})`)}return i>0&&console.log(`[QueenCoordinator] Cleaned up ${i} old tasks (retention: ${t}ms)`),i}function vn(s,e){return s&&s.size>0?Array.from(s.keys()):[...e]}var g=gt.create("QueenCoordinator");tn(v);var dt=class{constructor(e,t,n,i,r,a,o,l={}){this.eventBus=e;this.agentCoordinator=t;this.memory=n;this.router=i;this.protocolExecutor=r;this.workflowExecutor=a;this.domainPlugins=o;this.config={...en,...l},this.auditLogger=Me({enableConsoleLog:this.config.enableMetrics,maxEntries:1e3,logPrefix:"[QUEEN]"}),["p0","p1","p2","p3"].forEach(c=>{this.taskQueue.set(c,[])}),this.config.enableRouting!==!1&&(this.tinyDancerRouter=new ee(this.config.routing)),v.forEach(c=>{this.domainQueues.set(c,[]),this.domainLastActivity.set(c,new Date)})}eventBus;agentCoordinator;memory;router;protocolExecutor;workflowExecutor;domainPlugins;config;tasks=new Map;taskQueue=new Map;domainQueues=new Map;domainLastActivity=new Map;initialized=!1;workStealingTimer=null;metricsTimer=null;cleanupTimer=null;startTime=new Date;eventSubscriptionIds=[];runningTaskCounter=0;tasksReceived=0;tasksCompleted=0;tasksFailed=0;tasksStolen=0;taskDurations=new ft(1e3);protocolsExecuted=0;workflowsExecuted=0;auditLogger;minCutBridge=null;tinyDancerRouter=null;domainBreakerRegistry=null;domainTeamManager=null;agentTeamsAdapter=null;tierSelector=null;taskCompletedHook=null;traceCollector=null;taskTraceContexts=new Map;hypothesisManager=null;federationMailbox=null;dynamicScaler=null;coExecutionRepo=null;dependencyGraph=null;availableMcpServers=[];async initialize(){if(!this.initialized){this.startTime=new Date,await this.router.initialize(),this.subscribeToEvents(),this.config.workStealing.enabled&&(this.workStealingTimer=ct(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=Tn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{ut(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await fn(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=Et(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:vt()}),await this.minCutBridge.initialize(),this.domainPlugins&&hn(this.domainPlugins,this.minCutBridge);try{await _.initialize(),g.info("Governance adapter initialized")}catch(e){g.warn("Governance initialization failed (continuing)",{error:e})}this.initializeSubsystems();try{let{join:e}=await import("path"),t=e(process.cwd(),".claude","agents","v3");this.dependencyGraph=qt(t),this.availableMcpServers=Dt(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-GUR3IUI6.js"),i=n();await i.initialize(),this.coExecutionRepo=$t(),this.coExecutionRepo.initialize(i.getDatabase()),this.dependencyGraph.warnings.length>0&&g.warn(`Dependency graph: ${this.dependencyGraph.warnings.length} warning(s)`,{warnings:this.dependencyGraph.warnings.slice(0,5)}),g.info("Dependency intelligence initialized",{agents:this.dependencyGraph.nodes.size,mcpServers:this.availableMcpServers.length})}catch(e){g.warn("Dependency intelligence initialization failed (continuing)",{error:e})}await this.publishEvent("QueenInitialized",{timestamp:new Date,config:this.config,domains:v}),this.initialized=!0}}async dispose(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null),this.metricsTimer&&(clearInterval(this.metricsTimer),this.metricsTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.minCutBridge&&(await this.minCutBridge.dispose(),this.minCutBridge=null),this.domainTeamManager&&(this.domainTeamManager.dispose(),this.domainTeamManager=null),this.agentTeamsAdapter&&(this.agentTeamsAdapter.shutdown(),this.agentTeamsAdapter=null),this.domainBreakerRegistry=null,this.tierSelector=null,this.traceCollector&&(this.traceCollector.dispose(),this.traceCollector=null),this.hypothesisManager&&(this.hypothesisManager.dispose(),this.hypothesisManager=null),this.federationMailbox&&(this.federationMailbox.dispose(),this.federationMailbox=null),this.dynamicScaler&&(this.dynamicScaler.dispose(),this.dynamicScaler=null),await yn(this.memory,this.tasks);for(let[e,t]of this.tasks)(t.status==="queued"||t.status==="running")&&await this.cancelTask(e);await this.publishEvent("QueenShutdown",{timestamp:new Date,metrics:this.getMetrics()});for(let e of this.eventSubscriptionIds)this.router.unsubscribe(e);this.eventSubscriptionIds=[],await this.router.dispose(),this.initialized=!1}validateTaskExecutable(e,t=[]){let n=at(e,t,this.domainPlugins);if(n.length===0)return f(new Error(`Unknown task type '${e}': no domain is configured for it and no loaded domain handles it. Pass a target domain.`));if(!this.domainPlugins)return y(void 0);let i=j(this.domainPlugins,e,n);return i.length===0?y(void 0):f(new Error(ve(e,i)))}async submitTask(e){if(!this.initialized)return f(new Error("Queen Coordinator not initialized"));let t=`task_${C()}`,n={...e,targetDomains:E(e.type).length>0?e.targetDomains:[...at(e.type,e.targetDomains,this.domainPlugins)],id:t,createdAt:new Date,timeout:e.timeout||this.config.defaultTaskTimeout},i={taskId:n.id,taskType:n.type,agentId:n.requester||`queen-task:${n.id}`,domain:n.targetDomains[0]||"test-generation",priority:n.priority,payload:n.payload};try{let r=await _.beforeTaskExecution(i);if(!r.allowed)return this.auditLogger.logFail(t,"governance",r.reason||"Governance check failed"),await this.publishEvent("TaskRejected",{taskId:t,reason:r.reason,escalate:r.escalate}),f(new Error(`Task blocked by governance: ${r.reason}`))}catch(r){g.warn("Governance check error (continuing)",{error:r})}this.runningTaskCounter++;try{if(this.runningTaskCounter>this.config.maxConcurrentTasks)return this.runningTaskCounter--,this.queueTask(n);this.auditLogger.logSubmit(t,{type:n.type,priority:n.priority}),this.selectFleetTier(n),this.startTaskTrace(n,t);let r=await Se(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),y(t)):(this.tasks.has(t)||(this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1)),r)}catch(r){throw this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1),r}}async cancelTask(e){let t=this.tasks.get(e);if(!t)return f(new Error(`Task not found: ${e}`));if(t.status==="cancelled")return y(void 0);if(t.status==="completed"||t.status==="failed")return f(new Error(`Task already finished: ${e}`));let n=t.status==="running"||t.status==="assigned";this.tasks.set(e,{...t,status:"cancelled",completedAt:new Date,cancellationResultPending:n}),N(this.taskQueue,this.domainQueues,t.task);for(let i of t.assignedAgents)await this.agentCoordinator.stop(i);return this.auditLogger.logCancel(e),await this.publishEvent("TaskCancelled",{taskId:e}),y(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return un(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return on(this.agentCoordinator,e,this.domainLastActivity.get(e))}getDomainLoad(e){let t=this.domainQueues.get(e)||[],n=Array.from(this.tasks.values()).filter(i=>i.assignedDomain===e&&i.status==="running");return t.length+n.length}getIdleDomains(){let e=Date.now(),t=this.config.workStealing.idleThreshold;return v.filter(n=>{let i=this.domainLastActivity.get(n);return this.getDomainLoad(n)===0&&i&&e-i.getTime()>t})}getBusyDomains(){return v.filter(e=>this.getDomainLoad(e)>this.config.workStealing.loadThreshold)}getSpawnPlan(e){return this.dependencyGraph?zt(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=ct(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return pn(this.createWorkStealingContext())}listAllAgents(){return this.agentCoordinator.listAgents()}getAgentsByDomain(e){return this.agentCoordinator.listAgents({domain:e})}async requestAgentSpawn(e,t,n,i){if(!this.agentCoordinator.canSpawn())return f(new Error("Maximum concurrent agents reached (15)"));if(this.dependencyGraph&&this.availableMcpServers.length>0)try{for(let[,a]of this.dependencyGraph.nodes){let o=a.dependencies.mcpServers;if(!o||o.length===0)continue;let l=o.filter(c=>c.required&&!this.availableMcpServers.includes(c.name));if(l.length>0){g.warn(`Pre-spawn MCP advisory: ${a.agentName} needs ${l.map(c=>c.name).join(", ")}`,{agent:a.agentName,domain:e,missing:l.map(c=>c.name)});break}}}catch{}let r=await this.agentCoordinator.spawn({name:`${e}-${t}-${Date.now()}`,domain:e,type:t,capabilities:n});if(r.success){if(this.domainLastActivity.set(e,new Date),this.domainTeamManager&&typeof this.domainTeamManager.getDomainTeam=="function")try{if(this.domainTeamManager.getDomainTeam(e))this.domainTeamManager.addTeammate(e,r.value)||g.warn(`Agent ${r.value} could not join ${e} team (full)`);else try{this.domainTeamManager.createDomainTeam(e,r.value)}catch{this.domainTeamManager.addTeammate(e,r.value)||g.warn(`Agent ${r.value} could not join ${e} team (full or max teams reached)`)}}catch(a){g.warn(`Auto-team-wiring failed for ${r.value}`,{error:a})}await this.publishEvent("AgentSpawned",{agentId:r.value,domain:e,type:t,capabilities:n,...i?{taskId:i}:{}})}return r}getHealth(){let e=new Map,t=[],n=0,i=0,r=vn(this.domainPlugins,v);for(let u of r){let d=this.getDomainHealth(u);d&&(e.set(u,d),d.status==="unhealthy"?(n++,t.push({domain:u,severity:"high",message:`Domain ${u} is unhealthy`,timestamp:new Date})):d.status==="degraded"&&(i++,t.push({domain:u,severity:"medium",message:`Domain ${u} is degraded`,timestamp:new Date})))}let a=this.agentCoordinator.listAgents(),o=a.filter(u=>u.status==="running").length,l="healthy";n>0?l="unhealthy":i>r.length/2&&(l="degraded");let c={status:l,domainHealth:e,totalAgents:a.length,activeAgents:o,pendingTasks:this.getQueuedTaskCount(),runningTasks:this.getRunningTaskCount(),workStealingActive:this.workStealingTimer!==null,lastHealthCheck:new Date,issues:t};return this.minCutBridge?this.minCutBridge.extendQueenHealth(c):c}getMetrics(){let e=new Map;for(let o of v){let l=this.getDomainLoad(o);e.set(o,l)}let t=this.agentCoordinator.listAgents(),n=t.filter(o=>o.status==="running").length,i=t.length>0?n/t.length:0,r=this.taskDurations.average(),a={tasksReceived:this.tasksReceived,tasksCompleted:this.tasksCompleted,tasksFailed:this.tasksFailed,tasksStolen:this.tasksStolen,averageTaskDuration:r,domainUtilization:e,agentUtilization:i,protocolsExecuted:this.protocolsExecuted,workflowsExecuted:this.workflowsExecuted,uptime:Date.now()-this.startTime.getTime()};return this.minCutBridge?this.minCutBridge.extendQueenMetrics(a):a}getMinCutBridge(){return this.minCutBridge}injectMinCutBridgeIntoDomain(e){if(!this.minCutBridge)return g.warn("Cannot inject MinCut bridge: bridge not initialized"),!1;if(!this.domainPlugins)return g.warn("Cannot inject MinCut bridge: no domain plugins registered"),!1;let t=this.domainPlugins.get(e);return t?lt(t)?(t.setMinCutBridge(this.minCutBridge),g.info(`MinCut bridge injected into ${e} (late binding)`),!0):(g.warn(`Domain ${e} does not support MinCut integration`),!1):(g.warn(`Cannot inject MinCut bridge: domain ${e} not found`),!1)}getTinyDancerRouter(){return this.tinyDancerRouter}getDomainBreakerRegistry(){return this.domainBreakerRegistry}getDomainTeamManager(){return this.domainTeamManager}getAgentTeamsAdapter(){return this.agentTeamsAdapter}getTierSelector(){return this.tierSelector}getTraceCollector(){return this.traceCollector}getHypothesisManager(){return this.hypothesisManager}getFederationMailbox(){return this.federationMailbox}getDynamicScaler(){return this.dynamicScaler}connectReasoningBank(e){let t=new pe(e);this.taskCompletedHook=new ge({},t),g.info("ReasoningBank connected for pattern training")}async executeProtocol(e,t){if(!this.protocolExecutor)return f(new Error("Protocol executor not configured"));let n=await this.protocolExecutor.execute(e,t);return n.success?(this.protocolsExecuted++,await this.publishEvent("ProtocolExecuted",{protocolId:e,executionId:n.value.executionId}),y(n.value.executionId)):n}async executeWorkflow(e,t){if(!this.workflowExecutor)return f(new Error("Workflow executor not configured"));let n=await this.workflowExecutor.execute(e,t);return n.success?(this.workflowsExecuted++,await this.publishEvent("WorkflowExecuted",{workflowId:e,executionId:n.value.executionId}),y(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return ut(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=sn(this.createEventHandlerContext(),v)}enqueueTaskInternal(e){ot(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:C(),type:`Queen${e}`,timestamp:new Date,source:"queen-coordinator",payload:t})}queueTask(e){this.enqueueTaskInternal(e);let t={taskId:e.id,task:e,status:"queued",assignedAgents:[],retryCount:0};return this.tasks.set(e.id,t),this.tasksReceived++,this.auditLogger.logSubmit(e.id,{type:e.type,priority:e.priority}),this.auditLogger.logQueue(e.id,be(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:be(this.taskQueue,e)}),y(e.id)}selectFleetTier(e){if(this.tierSelector)try{let t={trigger:e.payload?.trigger??"manual",changedFiles:e.payload?.changedFiles,affectedDomains:e.targetDomains,severity:e.priority==="p0"?"critical":e.priority==="p1"?"high":void 0,isHotfix:e.payload?.isHotfix},n=this.tierSelector.selectTier(t);return g.info(`Fleet tier: ${n.selectedTier} (${n.reason})`),n.selectedTier}catch(t){g.warn("Tier selection error (continuing)",{error:t});return}}startTaskTrace(e,t){if(this.traceCollector)try{let{context:n}=this.traceCollector.startTrace({operationName:e.type,agentId:e.requester||"queen",domain:e.targetDomains[0]||"test-generation",tags:{taskId:t,priority:e.priority}});if(this.taskTraceContexts.size>=1e4){let r=this.taskTraceContexts.keys().next().value;r!==void 0&&this.taskTraceContexts.delete(r)}this.taskTraceContexts.set(t,n)}catch(n){g.warn("Trace start error (continuing)",{error:n})}}getRunningTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="running"||e.status==="assigned").length}getQueuedTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="queued").length}initializeSubsystems(){if(this.config.enableCircuitBreakers!==!1)try{this.domainBreakerRegistry=Vt(),g.info("Domain circuit breaker registry initialized")}catch(e){g.warn("Circuit breaker initialization failed (continuing)",{error:e})}if(this.config.enableDomainTeams!==!1)try{this.agentTeamsAdapter=Be(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=$e(this.agentTeamsAdapter),g.info("Domain team manager initialized")}catch(e){g.warn("Domain team manager initialization failed (continuing)",{error:e})}if(this.config.enableFleetTiers!==!1)try{this.tierSelector=Ge(),g.info("Fleet tier selector initialized")}catch(e){g.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=Qe(),g.info("Trace collector initialized")}catch(e){g.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=Ve(),this.federationMailbox=Ye(),this.dynamicScaler=Xe(),g.info("Phase 4 modules initialized (hypotheses, federation, scaling)")}catch(e){g.warn("Phase 4 initialization failed (continuing)",{error:e})}}createEventHandlerContext(){let e=this;return{config:e.config,tasks:e.tasks,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,router:e.router,agentCoordinator:e.agentCoordinator,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get domainBreakerRegistry(){return e.domainBreakerRegistry},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get taskCompletedHook(){return e.taskCompletedHook},get hypothesisManager(){return e.hypothesisManager},processQueue:()=>M(e.createTaskContext()),enqueueTask:t=>e.enqueueTaskInternal(t)}}createTaskContext(){let e=this;return{config:e.config,tasks:e.tasks,taskQueue:e.taskQueue,domainQueues:e.domainQueues,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,agentCoordinator:e.agentCoordinator,domainPlugins:e.domainPlugins,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksReceived(){return e.tasksReceived},set tasksReceived(t){e.tasksReceived=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get tinyDancerRouter(){return e.tinyDancerRouter},get domainBreakerRegistry(){return e.domainBreakerRegistry},get domainTeamManager(){return e.domainTeamManager},get tierSelector(){return e.tierSelector},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get coExecutionRepo(){return e.coExecutionRepo},requestAgentSpawn:(t,n,i,r)=>e.requestAgentSpawn(t,n,i,r),publishEvent:(t,n)=>e.publishEvent(t,n),getDomainLoad:t=>e.getDomainLoad(t),getDomainHealth:t=>e.getDomainHealth(t)}}createWorkStealingContext(){let e=this;return{config:e.config,domainQueues:e.domainQueues,auditLogger:e.auditLogger,get tasksStolen(){return e.tasksStolen},set tasksStolen(t){e.tasksStolen=t},getIdleDomains:()=>e.getIdleDomains(),getBusyDomains:()=>e.getBusyDomains(),getDomainLoad:t=>e.getDomainLoad(t),availableSlots:()=>e.config.maxConcurrentTasks-e.runningTaskCounter,canExecuteInDomain:(t,n)=>(e.tasks.get(n.id)?.status??"queued")==="queued"&&gn(e.domainPlugins,t,n),removeFromQueues:t=>N(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>mn(e.createTaskContext(),t,n),publishEvent:(t,n)=>e.publishEvent(t,n)}}createMetricsContext(){let e=this;return{config:e.config,memory:e.memory,get dynamicScaler(){return e.dynamicScaler},getMetrics:()=>e.getMetrics(),publishEvent:(t,n)=>e.publishEvent(t,n),getQueuedTaskCount:()=>e.getQueuedTaskCount(),getActiveAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="running").length,getIdleAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="idle").length,getAverageTaskDuration:()=>e.taskDurations.average(),getTasksReceived:()=>e.tasksReceived,getTasksFailed:()=>e.tasksFailed,getTasksCompleted:()=>e.tasksCompleted}}};function Go(s,e,t,n,i,r){return new dt(s.eventBus,s.coordinator,s.memory,e,t,n,i,r)}export{Ti as a,q as b,dt as c,Go as d};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.18");process.exit(0)}
|
|
2
2
|
var i=class r{constructor(e){this._value=e;if(!e||e.trim()==="")throw new Error("FilePath cannot be empty")}_value;get value(){return this._value}get extension(){let e=this._value.split(".");return e.length>1?e[e.length-1]:""}get directory(){let e=this._value.lastIndexOf("/");return e>0?this._value.substring(0,e):""}get filename(){let e=this._value.lastIndexOf("/");return e>=0?this._value.substring(e+1):this._value}equals(e){return this._value===e._value}static create(e){return new r(e)}};var s=class r{constructor(e){this._value=e;if(e<0||e>1)throw new Error("RiskScore must be between 0 and 1")}_value;get value(){return this._value}get percentage(){return this._value*100}get level(){return this._value>=.8?"critical":this._value>=.6?"high":this._value>=.3?"medium":"low"}isHigherThan(e){return this._value>e._value}equals(e){return this._value===e._value}static create(e){return new r(e)}static fromPercentage(e){return new r(e/100)}},u=class r{constructor(e,t){this._start=e;this._end=t;if(e>t)throw new Error("Start date cannot be after end date")}_start;_end;get start(){return this._start}get end(){return this._end}get durationMs(){return this._end.getTime()-this._start.getTime()}get durationSeconds(){return this.durationMs/1e3}contains(e){return e>=this._start&&e<=this._end}overlaps(e){return this._start<=e._end&&e._start<=this._end}equals(e){return this._start.getTime()===e._start.getTime()&&this._end.getTime()===e._end.getTime()}static create(e,t){return new r(e,t)}static lastNDays(e){let t=new Date,n=new Date(t.getTime()-e*24*60*60*1e3);return new r(n,t)}},o=class r{constructor(e,t,n,a){this._major=e;this._minor=t;this._patch=n;this._prerelease=a}_major;_minor;_patch;_prerelease;get major(){return this._major}get minor(){return this._minor}get patch(){return this._patch}get prerelease(){return this._prerelease}toString(){let e=`${this._major}.${this._minor}.${this._patch}`;return this._prerelease?`${e}-${this._prerelease}`:e}isNewerThan(e){return this._major!==e._major?this._major>e._major:this._minor!==e._minor?this._minor>e._minor:this._patch>e._patch}equals(e){return this._major===e._major&&this._minor===e._minor&&this._patch===e._patch&&this._prerelease===e._prerelease}static create(e,t,n,a){return new r(e,t,n,a)}static parse(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(!t)throw new Error(`Invalid version format: ${e}`);return new r(parseInt(t[1]),parseInt(t[2]),parseInt(t[3]),t[4])}};export{i as a,s as b,u as c,o as d};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as u}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.18");process.exit(0)}
|
|
2
|
+
import{b as u}from"./chunk-BDVFSMOQ.js";function t(){return{...e}}function o(r){e={...e,...r}}function i(){e={...s}}function a(){return e.useBrowserMode}function E(){return e.useScreenshotCapture}function l(){return e.useVisualRegression}function c(){return e.useE2EExecution}function f(){return e.defaultHeadless}function d(){return e.useAutoRetry}function _(){return e.logPerformanceMetrics}function I(){return e.useAxeCore}function p(){let r={};process.env.VIBIUM_USE_BROWSER_MODE!==void 0&&(r.useBrowserMode=process.env.VIBIUM_USE_BROWSER_MODE==="true"),process.env.VIBIUM_USE_SCREENSHOT_CAPTURE!==void 0&&(r.useScreenshotCapture=process.env.VIBIUM_USE_SCREENSHOT_CAPTURE==="true"),process.env.VIBIUM_USE_VISUAL_REGRESSION!==void 0&&(r.useVisualRegression=process.env.VIBIUM_USE_VISUAL_REGRESSION==="true"),process.env.VIBIUM_USE_E2E_EXECUTION!==void 0&&(r.useE2EExecution=process.env.VIBIUM_USE_E2E_EXECUTION==="true"),process.env.VIBIUM_DEFAULT_HEADLESS!==void 0&&(r.defaultHeadless=process.env.VIBIUM_DEFAULT_HEADLESS==="true"),process.env.VIBIUM_USE_AUTO_RETRY!==void 0&&(r.useAutoRetry=process.env.VIBIUM_USE_AUTO_RETRY==="true"),process.env.VIBIUM_LOG_PERFORMANCE_METRICS!==void 0&&(r.logPerformanceMetrics=process.env.VIBIUM_LOG_PERFORMANCE_METRICS==="true"),process.env.VIBIUM_USE_AXE_CORE!==void 0&&(r.useAxeCore=process.env.VIBIUM_USE_AXE_CORE==="true"),o(r)}function U(){o({defaultHeadless:!0,useAutoRetry:!0,logPerformanceMetrics:!0})}function R(){o({defaultHeadless:!1,logPerformanceMetrics:!0})}function S(){o({useBrowserMode:!1,useScreenshotCapture:!1,useVisualRegression:!1,useE2EExecution:!1,useAxeCore:!1})}var s,e,n=u(()=>{s={useBrowserMode:!0,useScreenshotCapture:!0,useVisualRegression:!0,useE2EExecution:!0,defaultHeadless:!1,useAutoRetry:!0,logPerformanceMetrics:!0,useAxeCore:!0},e={...s}});export{s as a,t as b,o as c,i as d,a as e,E as f,l as g,c as h,f as i,d as j,_ as k,I as l,p as m,U as n,R as o,S as p,n as q};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.18");process.exit(0)}
|
|
2
2
|
var l=class m{vertices=new Map;edges=new Map;adjacencyList=new Map;totalWeight=0;addVertex(e){if(this.vertices.has(e.id)){this.vertices.set(e.id,e);return}this.vertices.set(e.id,e),this.adjacencyList.set(e.id,[])}removeVertex(e){if(!this.vertices.has(e))return!1;let t=this.adjacencyList.get(e)||[];for(let r of t)this.removeEdge(e,r.neighborId);for(let[,r]of this.adjacencyList){let n=r.findIndex(i=>i.neighborId===e);n!==-1&&(this.totalWeight-=r[n].weight,r.splice(n,1))}return this.vertices.delete(e),this.adjacencyList.delete(e),!0}getVertex(e){return this.vertices.get(e)}hasVertex(e){return this.vertices.has(e)}getVertices(){return Array.from(this.vertices.values())}getVertexIds(){return Array.from(this.vertices.keys())}getVerticesByDomain(e){return this.getVertices().filter(t=>t.domain===e)}getVerticesByType(e){return this.getVertices().filter(t=>t.type===e)}addEdge(e){if(!this.vertices.has(e.source))throw new Error(`Source vertex ${e.source} does not exist`);if(!this.vertices.has(e.target))throw new Error(`Target vertex ${e.target} does not exist`);let t=this.edgeKey(e.source,e.target);if(this.edges.has(t)){let r=this.edges.get(t);this.totalWeight-=r.weight,this.removeFromAdjacency(e.source,e.target),r.bidirectional&&this.removeFromAdjacency(e.target,e.source)}this.edges.set(t,e),this.totalWeight+=e.weight,this.addToAdjacency(e.source,e.target,e.weight,e),e.bidirectional&&this.addToAdjacency(e.target,e.source,e.weight,e)}removeEdge(e,t){let r=this.edgeKey(e,t),n=this.edges.get(r);return n?(this.totalWeight-=n.weight,this.edges.delete(r),this.removeFromAdjacency(e,t),n.bidirectional&&this.removeFromAdjacency(t,e),!0):!1}getEdge(e,t){return this.edges.get(this.edgeKey(e,t))}hasEdge(e,t){return this.edges.has(this.edgeKey(e,t))}getEdges(){return Array.from(this.edges.values())}getEdgesForVertex(e){return(this.adjacencyList.get(e)||[]).map(r=>r.edge)}degree(e){return this.adjacencyList.get(e)?.length||0}weightedDegree(e){let t=this.adjacencyList.get(e);return t?t.reduce((r,n)=>r+n.weight,0):0}neighbors(e){return(this.adjacencyList.get(e)||[]).map(r=>({vertex:this.vertices.get(r.neighborId),weight:r.weight})).filter(r=>r.vertex!==void 0)}neighborIds(e){return(this.adjacencyList.get(e)||[]).map(r=>r.neighborId)}getStats(){let e=this.vertices.size,t=this.edges.size,r=0;for(let[,s]of this.adjacencyList)r+=s.length;let n=e>0?r/e:0,i=e>1?e*(e-1)/2:0,a=i>0?t/i:0,o=this.countConnectedComponents(),c=o===1&&e>0;return{vertexCount:e,edgeCount:t,totalWeight:this.totalWeight,averageDegree:n,density:a,isConnected:c,componentCount:o}}countConnectedComponents(){let e=new Set,t=0;for(let r of this.vertices.keys())e.has(r)||(this.dfs(r,e),t++);return t}dfs(e,t){t.add(e);let r=this.adjacencyList.get(e)||[];for(let n of r)t.has(n.neighborId)||this.dfs(n.neighborId,t)}isConnected(){if(this.vertices.size===0||this.vertices.size===1)return!0;let e=new Set,t=this.vertices.keys().next().value;return t===void 0?!0:(this.dfs(t,e),e.size===this.vertices.size)}getConnectedComponent(e){if(!this.vertices.has(e))return[];let t=new Set;return this.dfs(e,t),Array.from(t)}snapshot(){return{timestamp:new Date,vertices:this.getVertices(),edges:this.getEdges(),stats:this.getStats()}}clone(){let e=new m;for(let t of this.vertices.values())e.addVertex({...t});for(let t of this.edges.values())e.addEdge({...t});return e}static fromSnapshot(e){let t=new m;for(let r of e.vertices)t.addVertex(r);for(let r of e.edges)t.addEdge(r);return t}clear(){this.vertices.clear(),this.edges.clear(),this.adjacencyList.clear(),this.totalWeight=0}get vertexCount(){return this.vertices.size}get edgeCount(){return this.edges.size}isEmpty(){return this.vertices.size===0}edgeKey(e,t){return e<t?`${e}:${t}`:`${t}:${e}`}addToAdjacency(e,t,r,n){let i=this.adjacencyList.get(e);i&&(i.find(o=>o.neighborId===t)||i.push({neighborId:t,weight:r,edge:n}))}removeFromAdjacency(e,t){let r=this.adjacencyList.get(e);if(r){let n=r.findIndex(i=>i.neighborId===t);n!==-1&&r.splice(n,1)}}};function p(){return new l}var f=class{approxMinCut(e){let t=Date.now();if(e.isEmpty())return this.emptyResult(t,"weighted-degree");let r=e.getVertexIds(),n=1/0,i=null;for(let o of r){let c=e.weightedDegree(o);c<n&&(n=c,i=o)}if(i===null||r.length===1)return this.emptyResult(t,"weighted-degree");let a=e.getEdgesForVertex(i);return{value:n,sourceSide:[i],targetSide:r.filter(o=>o!==i),cutEdges:a,calculatedAt:new Date,algorithm:"weighted-degree",durationMs:Date.now()-t}}findWeakVertices(e,t){if(e.isEmpty())return[];let r=e.getVertices(),n=[],i=new Map,a=0;for(let g of r){let h=e.weightedDegree(g.id);i.set(g.id,h),a+=h}let o=a/r.length,c=0;for(let g of i.values())c+=(g-o)**2;let s=Math.sqrt(c/r.length),d=1/0;for(let g of i.values())g<d&&(d=g);let u=t??o-s;for(let g of r){let h=i.get(g.id);if(h<=u){let w=this.calculateRiskScore(h,o,s,d),y=this.determineWeakReason(g,h,o,e),v=this.generateStrengtheningActions(g,e,h);n.push({vertexId:g.id,vertex:g,weightedDegree:h,riskScore:w,reason:y,suggestions:v})}}return n.sort((g,h)=>h.riskScore-g.riskScore),n}getMinCutValue(e){if(e.isEmpty())return 0;let t=1/0;for(let r of e.getVertexIds()){let n=e.weightedDegree(r);n<t&&(t=n)}return t===1/0?0:t}isConnectivityCritical(e,t){return this.getMinCutValue(e)<t}getMinDegreeVertex(e){if(e.isEmpty())return null;let t=1/0,r=null;for(let n of e.getVertexIds()){let i=e.weightedDegree(n);i<t&&(t=i,r=n)}return r?{vertexId:r,degree:t}:null}getLocalMinCut(e,t){return e.hasVertex(t)?e.weightedDegree(t):0}findPartitioningPoints(e){if(e.isEmpty()||e.vertexCount<2)return[];let t=this.findArticulationPoints(e),r=[];for(let n of e.getVertices()){let i=this.getLocalMinCut(e,n.id);r.push({vertexId:n.id,localMinCut:i,wouldDisconnect:t.has(n.id)&&e.vertexCount>2})}return r.sort((n,i)=>n.localMinCut-i.localMinCut),r}findArticulationPoints(e){let t=new Map,r=new Map,n=new Map,i=new Set,a=0,o=e.getVertexIds();for(let s of o)t.set(s,-1),r.set(s,-1),n.set(s,null);let c=s=>{let d=0;t.set(s,a),r.set(s,a),a++;for(let u of e.neighborIds(s))t.get(u)===-1?(d++,n.set(u,s),c(u),r.set(s,Math.min(r.get(s),r.get(u))),n.get(s)===null&&d>1&&i.add(s),n.get(s)!==null&&r.get(u)>=t.get(s)&&i.add(s)):u!==n.get(s)&&r.set(s,Math.min(r.get(s),t.get(u)))};for(let s of o)t.get(s)===-1&&c(s);return i}suggestEdgeAdditions(e,t){let r=this.findWeakVertices(e),n=[],i=0,a=e.getVertices().map(o=>({vertex:o,degree:e.weightedDegree(o.id)})).sort((o,c)=>c.degree-o.degree);for(let o of r){if(i>=t)break;let c=new Set(e.neighborIds(o.vertexId));for(let{vertex:s}of a){if(s.id===o.vertexId||c.has(s.id))continue;let d={source:o.vertexId,target:s.id,weight:1,type:"coordination",bidirectional:!0};n.push(d),i+=1;break}}return n}emptyResult(e,t){return{value:0,sourceSide:[],targetSide:[],cutEdges:[],calculatedAt:new Date,algorithm:t,durationMs:Date.now()-e}}calculateRiskScore(e,t,r,n){if(r===0)return .5;let i=(t-e)/r,a=1/(1+Math.exp(-i)),o=n>0?n/e:1;return Math.min(1,a*o)}determineWeakReason(e,t,r,n){return t===0?"Isolated vertex with no connections":n.degree(e.id)===1?"Single connection point (leaf node)":t<r*.5?`Low connectivity (${(t/r*100).toFixed(0)}% of average)`:"Below average connectivity threshold"}generateStrengtheningActions(e,t,r){let n=[],i=new Set(t.neighborIds(e.id)),a=t.getStats().averageDegree,o=Math.max(a,3),c=Math.ceil(o-r),s=t.getVertices().filter(d=>d.id!==e.id&&!i.has(d.id)).sort((d,u)=>t.weightedDegree(u.id)-t.weightedDegree(d.id)).slice(0,c);for(let d of s)n.push({type:"add_edge",targetVertex:d.id,priority:"high",estimatedImprovement:1});return e.type==="agent"&&e.domain&&r<1&&n.push({type:"spawn_agent",domain:e.domain,priority:"critical",estimatedImprovement:2}),i.size>0&&i.size<3&&n.push({type:"increase_weight",weightDelta:.5,priority:"medium",estimatedImprovement:.5*i.size}),n}};function x(){return new f}export{l as a,p as b,f as c,x as d};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.18");process.exit(0)}
|
|
2
|
+
import{a as D,b as Q}from"./chunk-LWAFRYKE.js";import{b as E,d as S}from"./chunk-MQM37KAR.js";import{S as M,l as A}from"./chunk-V2LJ54KP.js";import{f as C}from"./chunk-BDVFSMOQ.js";S();M();var v=(1+Math.sqrt(5))/2,R=1/v;function k(t,e=0){if(t<0||!Number.isFinite(t))throw new Error(`Invalid dither sequence length: ${t}`);if(!Number.isFinite(e))throw new Error(`Invalid dither seed: ${e}`);let n=new Float32Array(t),r=(e*R%1+1)%1;for(let i=0;i<t;i++)n[i]=((r+(i+1)*v)%1+1)%1;return n}function I(t,e,n=0){if(!(t instanceof Float32Array))throw new Error("Input vector must be a Float32Array");if(t.length===0)return{quantized:new Int32Array(0),dequantized:new Float32Array(0),bitDepth:e,seed:n,stepSize:0,minValue:0,maxValue:0};if(e<1||e>32||!Number.isInteger(e))throw new Error(`Invalid bit depth: ${e}. Must be an integer in [1, 32].`);let r=t[0],i=t[0];for(let d=1;d<t.length;d++)t[d]<r&&(r=t[d]),t[d]>i&&(i=t[d]);let s=(1<<e)-1,a=i-r,o=a===0?1:a/s,m=k(t.length,n),l=new Int32Array(t.length),u=new Float32Array(t.length);for(let d=0;d<t.length;d++){if(a===0)l[d]=Math.round(s/2);else{let L=(t[d]-r)/o+(m[d]-.5);l[d]=Math.max(0,Math.min(s,Math.round(L)))}u[d]=l[d]*o+r}return{quantized:l,dequantized:u,bitDepth:e,seed:n,stepSize:o,minValue:r,maxValue:i}}var h=null,b=null,p=null,g=null,f=null,w=null,x=!1;try{let t=(Q(),C(D));h=t.RuvectorLayer,b=t.TensorCompress,p=t.differentiableSearch,g=t.hierarchicalForward,f=t.getCompressionLevel,w=t.init,x=!0}catch{}function H(){return x}function c(){if(!x)throw new Error("@ruvector/gnn native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var F=!1;function V(){if(!F){c();let t=w();return F=!0,t}return"@ruvector/gnn already initialized"}var y=class{indexes;config;nextId;gnnLayers;compressor;constructor(e={}){this.config={M:e.M||16,efConstruction:e.efConstruction||200,efSearch:e.efSearch||50,dimension:e.dimension||384,metric:e.metric||"cosine",quantization:e.quantization||"none"},this.indexes=new Map,this.nextId=new Map,this.gnnLayers=new Map,c(),this.compressor=new b,V()}initializeIndex(e){this.indexes.has(e)||(this.indexes.set(e,new Map),this.nextId.set(e,0))}addEmbedding(e,n){let r=e.namespace;this.indexes.has(r)||this.initializeIndex(r);let i=this.indexes.get(r),s=n??this.nextId.get(r);return n===void 0&&this.nextId.set(r,s+1),i.set(s,e),s}addEmbeddingsBatch(e){let n=[];for(let r of e){let i=this.addEmbedding(r.embedding,r.id);n.push(i)}return n}search(e,n={}){let r=n.namespace||e.namespace;if(!this.indexes.has(r))return[];let i=this.indexes.get(r),s=n.limit||10,a=[];for(let[u,d]of i.entries())a.push({id:u,vector:Array.from(d.vector)});if(a.length===0)return[];let o=new Float32Array(e.vector),m=a.map(u=>new Float32Array(u.vector)),l=p(o,m,Math.min(s,a.length),1);return l.indices.map((u,d)=>({id:a[u]?.id??u,distance:1-l.weights[d]}))}differentiableSearchWithWeights(e,n,r,i=1){let s=new Float32Array(e.vector),a=n.map(m=>new Float32Array(m.embedding.vector)),o=p(s,a,Math.min(r,n.length),i);return{indices:o.indices.map(m=>n[m]?.id??m),weights:o.weights}}hierarchicalForward(e,n,r){let i=r.map(l=>`${l.inputDim}-${l.hiddenDim}`).join(",");if(!this.gnnLayers.has(i)){let l=[];for(let u of r){let d=new h(u.inputDim,u.hiddenDim,u.heads,u.dropout);l.push(d)}this.gnnLayers.set(i,l[0])}let a=this.gnnLayers.get(i).toJson(),o=new Float32Array(e),m=n.map(l=>l.map(u=>new Float32Array(u)));return Array.from(g(o,m,[a]))}compressEmbedding(e,n){let r=f(n),s={none:"none",half:"half",pq8:"pq8",pq4:"pq4",binary:"binary"}[r]??"none",a=new Float32Array(e.vector),o=this.compressor.compress(a,n);return{dimension:Array.from(e.vector).length,level:s,data:o,accessFreq:n}}decompressEmbedding(e){let n=this.compressor.decompress(e.data),r={none:"none",half:"fp16",pq8:"int8",pq4:"int8",binary:"binary"};return{vector:n,dimension:e.dimension,namespace:"code",text:"",timestamp:Date.now(),quantization:r[e.level]??"none"}}getCompressionLevelForFrequency(e){return c(),f(e)}getIndexStats(e){return this.indexes.has(e)?{size:this.indexes.get(e).size,maxElements:1e4,dimension:this.config.dimension,metric:this.config.metric}:null}clearIndex(e){this.indexes.delete(e),this.nextId.delete(e)}clearAll(){this.indexes.clear(),this.nextId.clear()}resizeIndex(e){}setEfSearch(e){this.config.efSearch=e}getConfig(){return{...this.config}}isInitialized(e){return this.indexes.has(e)}getInitializedNamespaces(){return Array.from(this.indexes.keys())}getSize(e){return this.indexes.get(e)?.size??0}async saveIndex(e,n){let r=this.indexes.get(e);if(!r)throw new Error(`Namespace ${e} not initialized`);let i=Array.from(r.entries()).map(([a,o])=>({id:a,vector:Array.from(o.vector),metadata:o.metadata}));await(await import("fs/promises")).writeFile(n,JSON.stringify(i,null,2))}async loadIndex(e,n){let i=await(await import("fs/promises")).readFile(n,"utf-8"),s=E(i);this.initializeIndex(e);for(let a of s){let o={vector:a.vector,dimension:a.vector.length,namespace:e,text:"",timestamp:Date.now(),quantization:"none",metadata:a.metadata};this.addEmbedding(o,a.id)}}},q=class{static instances=new Map;static getInstance(e,n){return this.instances.has(e)||this.instances.set(e,new y(n)),this.instances.get(e)}static closeInstance(e){let n=this.instances.get(e);n&&(n.clearAll(),this.instances.delete(e))}static closeAll(){for(let e of this.instances.values())e.clearAll();this.instances.clear()}},z=class{static layers=new Map;static getLayer(e){let n=`${e.inputDim}-${e.hiddenDim}-${e.heads}-${e.dropout}`;if(!this.layers.has(n)){c();let r=new h(e.inputDim,e.hiddenDim,e.heads,e.dropout);this.layers.set(n,r)}return this.layers.get(n)}static layerFromJson(e){return c(),h.fromJson(e)}static clearCache(){this.layers.clear()}},N=class{static _compressor=null;static get compressor(){return this._compressor||(c(),this._compressor=new b),this._compressor}static compressWithLevel(e,n){let r={levelType:n,scale:1,subvectors:n==="pq8"?8:n==="pq4"?16:void 0,centroids:n==="pq8"?256:void 0,outlierThreshold:n==="pq4"?3:void 0,threshold:n==="binary"?0:void 0},i=e instanceof Float32Array?e:new Float32Array(e);return this.compressor.compressWithLevel(i,r)}static decompress(e){return this.compressor.decompress(e)}static getLevel(e){return c(),f(e)}static compressWithDither(e,n,r){let i=e instanceof Float32Array?e:new Float32Array(e),s;if(A()){let o={none:32,half:16,pq8:8,pq4:4,binary:1},m=r?.bitDepth??o[n]??8,l=r?.seed??0;s=I(i,m,l)}return{compressed:this.compressWithLevel(s?s.dequantized:e,n),ditherResult:s}}};function G(){return c(),h}function J(){return c(),b}function O(){return c(),p}function j(){return c(),g}function B(){return c(),f}function K(){return c(),w}function U(t){return t instanceof Float32Array?t:"vector"in t?t.vector instanceof Float32Array?t.vector:new Float32Array(t.vector):new Float32Array(t)}function X(t){return"vector"in t?Array.from(t.vector):Array.from(t)}function Y(t,e="code"){return{vector:t,dimension:t.length,namespace:e,text:"",timestamp:Date.now(),quantization:"none"}}function Z(t,e,n,r=1){let i=[],s=e.map(a=>a instanceof Float32Array?a:new Float32Array(a));for(let a of t){let o=a instanceof Float32Array?a:new Float32Array(a),m=p(o,s,n,r);i.push({indices:m.indices,weights:m.weights})}return i}export{H as a,V as b,y as c,q as d,z as e,N as f,G as g,J as h,O as i,j,B as k,K as l,U as m,X as n,Y as o,Z as p};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{a as b}from"./chunk-TIVKDIF7.js";import{c as g}from"./chunk-DS5IFRY6.js";import{C as B,S as v,b as p}from"./chunk-JHKKIJT2.js";import{a as I}from"./chunk-Z7SKUC6P.js";b();v();b();v();import{createHash as ue,randomUUID as me}from"crypto";b();function Z(o){let e=2166136261;for(let t=0;t<o.length;t++)e^=o.charCodeAt(t),e=Math.imul(e,16777619);return(e>>>0)%64}function W(o){let e=new Array(64).fill(0),t=o.toLowerCase().split(/[\s,;:.!?()[\]{}"']+/).filter(n=>n.length>0);for(let n of t){let s=Z(n);e[s]++}let r=0;for(let n=0;n<64;n++)r+=e[n]*e[n];if(r=Math.sqrt(r),r>1e-10)for(let n=0;n<64;n++)e[n]/=r;return e}function _(o,e){let t=0,r=0,n=0,s=Math.min(o.length,e.length);for(let a=0;a<s;a++)t+=o[a]*e[a],r+=o[a]*o[a],n+=e[a]*e[a];let i=Math.sqrt(r)*Math.sqrt(n);return i>1e-10?t/i:0}b();import{createRequire as ee}from"module";var S=ee(import.meta.url),V=g.create("coherence-gate-cohomology"),C=null,k=!1;function H(){if(k)return C;k=!0;try{let o=S("prime-radiant-advanced-wasm"),e=S("fs"),t=S("path"),r=t.join(t.dirname(I.resolve("prime-radiant-advanced-wasm")),"prime_radiant_advanced_wasm_bg.wasm");o.initSync({module:e.readFileSync(r)}),C=new o.CohomologyEngine,V.info("CohomologyEngine loaded from prime-radiant-advanced-wasm")}catch(o){V.debug("CohomologyEngine unavailable, using word-frequency fallback",{error:String(o)}),C=null}return C}var te={threshold:5,slack:.5,resetOnAlarm:!0,warmupSamples:20},d=class{config;states=new Map;constructor(e={}){this.config={...te,...e}}update(e,t){let r=this.getOrCreateState(e);if(r.samplesSinceReset++,r.mu===null)return r.warmupSum+=t,r.warmupCount++,r.warmupCount>=this.config.warmupSamples&&(r.mu=r.warmupSum/r.warmupCount),{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:r.samplesSinceReset};r.sPlus=Math.max(0,r.sPlus+(t-r.mu-this.config.slack)),r.sMinus=Math.max(0,r.sMinus+(-t+r.mu-this.config.slack));let n=Math.max(r.sPlus,r.sMinus),s=!1,i="none";r.sPlus>this.config.threshold?(s=!0,i="positive"):r.sMinus>this.config.threshold&&(s=!0,i="negative");let a={driftDetected:s,cumulativeSum:n,direction:i,samplesSinceReset:r.samplesSinceReset};return s&&this.config.resetOnAlarm&&(r.sPlus=0,r.sMinus=0,r.samplesSinceReset=0),a}reset(e){e?this.states.delete(e):this.states.clear()}getState(e){let t=this.states.get(e);if(!t)return{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:0};let r=Math.max(t.sPlus,t.sMinus),n="none";return t.sPlus>this.config.threshold?n="positive":t.sMinus>this.config.threshold&&(n="negative"),{driftDetected:t.sPlus>this.config.threshold||t.sMinus>this.config.threshold,cumulativeSum:r,direction:n,samplesSinceReset:t.samplesSinceReset}}getOrCreateState(e){let t=this.states.get(e);return t||(t={sPlus:0,sMinus:0,samplesSinceReset:0,warmupSum:0,warmupCount:0,mu:null},this.states.set(e,t)),t}};v();var x=g.create("coherence-gate-energy"),D=null,re=[],P=[],ne=100;function oe(){return D||(B()?(D=new d,x.debug("CUSUM drift detector auto-created via feature flag"),D):null)}function O(o,e){let t=oe();if(!t)return;let r=t.update(o,e);if(r.driftDetected){let n={gateType:o,energy:e,cusumResult:r,timestamp:Date.now()};x.warn("CUSUM drift detected",{gateType:o,energy:e,direction:r.direction,cumulativeSum:r.cumulativeSum}),P.push(n),P.length>ne&&P.shift();for(let s of re)try{s(n)}catch(i){x.debug("Drift listener error",{error:String(i)})}}}var f={assertionCoverage:.4,codeCoverage:.3,confidencePenalty:.3,contradictionWeight:.2,laplacianWeight:.15},N=1;function U(o){if(o.assertions.length===0)return 0;let e=o.observedBehavior.length/o.assertions.length;return Math.max(0,Math.min(1-e,1))}function $(o){return Math.max(0,Math.min(1-o.coverage,1))}function j(o){return Math.max(0,Math.min(1-o.confidence,1))}function se(o){if(o.assertions.length===0||o.observedBehavior.length===0)return 0;let e=0,t=["not","never","false","undefined","null","error","fail"];for(let r of o.assertions){let n=r.toLowerCase();for(let s of o.observedBehavior){let i=s.toLowerCase();for(let a of t){let c=n.includes(a),u=i.includes(a);if(c!==u){let m=new Set(n.split(/\s+/)),l=new Set(i.split(/\s+/)),h=0;for(let L of m)l.has(L)&&L.length>3&&h++;if(h>0){e++;break}}}}}return Math.min(e/o.assertions.length,1)}function ie(o,e,t){let r=t[0]?.length??64,n=t.map((c,u)=>({id:u,label:e.assertions[u]?.slice(0,50)??`assertion-${u}`,section:c,weight:e.confidence})),s=[];for(let c=0;c<t.length;c++)for(let u=c+1;u<t.length;u++){let m=[];for(let l=0;l<r;l++)for(let h=0;h<r;h++)m.push(l===h?1:0);s.push({source:c,target:u,weight:1,restriction_map:m,source_dim:r,target_dim:r})}let i=o.consistencyEnergy({nodes:n,edges:s}),a=i/(i+1);return Math.max(0,Math.min(a,1))}function ae(o){let e=0,t=0;for(let n=0;n<o.length;n++)for(let s=n+1;s<o.length;s++)e+=_(o[n],o[s]),t++;if(t===0)return 0;let r=e/t;return Math.max(0,Math.min(1-r,1))}function ce(o){if(o.assertions.length<2)return 0;let e=o.assertions.map(r=>W(r)),t=H();if(t)try{return ie(t,o,e)}catch(r){x.debug("CohomologyEngine.consistencyEnergy failed, using fallback",{error:String(r)})}return ae(e)}function K(o,e="act"){let t=U(o),r=$(o),n=j(o),s=Math.min(t*f.assertionCoverage+r*f.codeCoverage+n*f.confidencePenalty,1);return O(e,s),{energy:s,components:{assertionCoverage:t,codeCoverage:r,confidencePenalty:n,contradictionScore:0,laplacianDeviation:0}}}function q(o,e="retrieve"){let t=U(o),r=$(o),n=j(o),s=se(o),i=ce(o),a=t*f.assertionCoverage+r*f.codeCoverage+n*f.confidencePenalty,c=s*f.contradictionWeight+i*f.laplacianWeight,u=f.assertionCoverage+f.codeCoverage+f.confidencePenalty+f.contradictionWeight+f.laplacianWeight,m=Math.min((a+c)/u,1);return O(e,m),{energy:m,components:{assertionCoverage:t,codeCoverage:r,confidencePenalty:n,contradictionScore:s,laplacianDeviation:i}}}var z=g.create("coherence-gate"),le=.4,T=class{threshold;decisionLog=[];witnessChain=[];lastWitnessHash="0".repeat(64);nativeAvailable=null;governanceChain=null;constructor(e=le){this.threshold=e}setGovernanceChain(e){this.governanceChain=e}computeEnergy(e,t=!1,r="retrieve"){let n=performance.now();if(!t){let a=K(e,r),c=performance.now()-n;if(c<=N)return{energy:a.energy,tier:"reflex",components:a.components,latencyMs:c}}let s=q(e,r),i=performance.now()-n;return{energy:s.energy,tier:"retrieval",components:s.components,latencyMs:i}}validate(e,t,r="retrieve"){let n=t??this.threshold,s=this.computeEnergy(e,!1,r),i=s.energy<=n,a;i||(a=this.buildFailureReason(s,n));let c=this.createWitnessRecord(e,s.energy,n,i);return this.logDecision({id:c.id,timestamp:c.timestamp,domain:e.domain,energy:s.energy,tier:s.tier,passed:i,threshold:n}),{passed:i,energy:s.energy,threshold:n,reason:a,witness:c}}getDecisionLog(){return[...this.decisionLog]}getWitnessChain(){return[...this.witnessChain]}getThreshold(){return this.threshold}clearDecisionLog(){this.decisionLog=[]}validateTransfer(e,t){if(!p().useCoherenceGate)return{approved:!0};let n={assertions:this.extractAssertions(e),observedBehavior:this.extractObservedBehavior(e),coverage:typeof e.coverage=="number"?e.coverage:.5,domain:t,confidence:e.confidence??.5},s=this.validate(n,void 0,"write");return{approved:s.passed,energy:s.energy,rejectionReason:s.reason}}buildFailureReason(e,t){let r=[];r.push(`Coherence energy ${e.energy.toFixed(3)} exceeds threshold ${t.toFixed(3)}.`);let n=e.components;return n.assertionCoverage>.5&&r.push("High assertion-observation mismatch (possible hallucination)."),n.codeCoverage>.5&&r.push("Low code coverage."),n.confidencePenalty>.5&&r.push("Low generator confidence."),n.contradictionScore>.3&&r.push("Contradictions detected between assertions and observed behavior."),n.laplacianDeviation>.5&&r.push("Inconsistent assertion structure (high Laplacian deviation)."),r.join(" ")}createWitnessRecord(e,t,r,n){let s=me(),i=Date.now(),a=this.hashContent(JSON.stringify(e)),c={id:s,timestamp:i,artifactHash:a,energy:t,threshold:r,passed:n,previousHash:this.lastWitnessHash,recordHash:""},u=`${s}|${i}|${a}|${t}|${r}|${n}|${this.lastWitnessHash}`;if(c.recordHash=this.hashContent(u),p().useWitnessChain&&(this.witnessChain.push(c),this.lastWitnessHash=c.recordHash,this.governanceChain))try{let l={type:"coherence-gate",decision:n?"PASS":"FAIL",context:{energy:t,threshold:r,artifactHash:c.artifactHash}};this.governanceChain.appendWitness(l)}catch(l){z.debug("Failed to persist to governance chain",{error:String(l)})}return c}hashContent(e){return ue("sha256").update(e).digest("hex")}logDecision(e){this.decisionLog.push(e);let t=1e3;this.decisionLog.length>t&&(this.decisionLog=this.decisionLog.slice(-t)),z.debug("Coherence decision",{domain:e.domain,energy:e.energy,tier:e.tier,passed:e.passed})}extractAssertions(e){return Array.isArray(e.assertions)?e.assertions.map(String):typeof e.description=="string"?[e.description]:["transfer-pattern"]}extractObservedBehavior(e){return Array.isArray(e.observedBehavior)?e.observedBehavior.map(String):typeof e.evidence=="string"?[e.evidence]:["observed"]}};var R=class{validateTransfer(e,t){return{approved:!0}}};function X(){return p().useCoherenceGate?new T:new R}b();var Y=g.create("transfer-verification"),fe={maxSourceRegression:.05,minTargetImprovement:0,maxSourceConfidenceRegression:.1},w=class{config;constructor(e={}){this.config={...fe,...e}}verifyTransfer(e){let t=e.sourcePerformanceAfter.successRate-e.sourcePerformanceBefore.successRate,r=e.targetPerformanceAfter.successRate-e.targetPerformanceBefore.successRate,n=e.sourcePerformanceAfter.avgConfidence-e.sourcePerformanceBefore.avgConfidence,s=e.targetPerformanceAfter.avgConfidence-e.targetPerformanceBefore.avgConfidence,i=t>=-this.config.maxSourceRegression&&n>=-this.config.maxSourceConfidenceRegression,a=r>=this.config.minTargetImprovement,c=i&&a,u;if(!c){let m=[];i||m.push(`source domain regressed: successRate delta=${t.toFixed(4)}, confidence delta=${n.toFixed(4)}`),a||m.push(`target domain did not improve: successRate delta=${r.toFixed(4)}`),u=m.join("; ")}return c?Y.debug("Transfer verification passed",{transferId:e.transferId,sourceDelta:t,targetDelta:r}):Y.warn("Transfer verification failed",{transferId:e.transferId,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourceDelta:t,targetDelta:r,failureReason:u}),{passed:c,sourceStable:i,targetImproved:a,sourceDelta:t,targetDelta:r,sourceConfidenceDelta:n,targetConfidenceDelta:s,failureReason:u}}getConfig(){return{...this.config}}};function J(o){return new w(o)}v();var y=class{alphas=new Map;betas=new Map;sample(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return this.sampleBeta(t,r)}update(e,t){t?this.alphas.set(e,(this.alphas.get(e)??1)+1):this.betas.set(e,(this.betas.get(e)??1)+1)}getMean(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t/(t+r)}getObservationCount(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t-1+(r-1)}getAlpha(e){return this.alphas.get(e)??1}getBeta(e){return this.betas.get(e)??1}sampleBeta(e,t){let r=this.sampleGamma(e),n=this.sampleGamma(t);return r+n===0?.5:r/(r+n)}sampleGamma(e){if(e<1){let n=Math.random();return this.sampleGamma(e+1)*Math.pow(n,1/e)}let t=e-1/3,r=1/Math.sqrt(9*t);for(;;){let n,s;do n=this.standardNormal(),s=1+r*n;while(s<=0);s=s*s*s;let i=Math.random();if(i<1-.0331*n*n*n*n||Math.log(i)<.5*n*n+t*(1-s+Math.log(s)))return t*s}}standardNormal(){let e=Math.random(),t=Math.random();return Math.sqrt(-2*Math.log(e||1e-10))*Math.cos(2*Math.PI*t)}};var Q=g.create("domain-transfer"),ge={minTransferProbability:.3,explorationWarmup:5,verification:{},maxHistorySize:1e3,useMetaLearningEnhancements:!0},M=class{constructor(e=100){this.decayThreshold=e}decayThreshold;getDecayMultiplier(e){return e<=0?1:Math.pow(.5,e/this.decayThreshold)}applyDecay(e,t,r){return t+(e-t)*this.getDecayMultiplier(r)}},E=class{cusum;outcomes=[];windowSize;constructor(e=20){this.windowSize=e,this.cusum=new d({threshold:3,slack:.1,resetOnAlarm:!1,warmupSamples:Math.min(10,Math.floor(e/2))})}record(e){this.outcomes.push(e),this.outcomes.length>this.windowSize*2&&this.outcomes.splice(0,this.outcomes.length-this.windowSize*2);let t=this.getCurrentRate();this.cusum.update("learn",t)}isPlateaued(){return this.outcomes.length<this.windowSize?!1:!this.cusum.getState("learn").driftDetected}getCurrentRate(){if(this.outcomes.length===0)return 0;let e=this.outcomes.slice(-this.windowSize);return e.filter(Boolean).length/e.length}getOutcomeCount(){return this.outcomes.length}getCusumState(){return this.cusum.getState("learn")}},A=class{front=[];dominates(e,t){let r=e.successRate>=t.successRate&&e.speed>=t.speed&&e.confidence>=t.confidence,n=e.successRate>t.successRate||e.speed>t.speed||e.confidence>t.confidence;return r&&n}add(e){for(let t=this.front.length-1;t>=0;t--)this.dominates(e,this.front[t])&&this.front.splice(t,1);this.front.some(t=>this.dominates(t,e))||this.front.push(e)}getFront(){return[...this.front]}isNonDominated(e){return!this.front.some(t=>this.dominates(t,e))}},F=class{constructor(e=.2){this.bonusScale=e}bonusScale;triedPairs=new Set;markTried(e){this.triedPairs.add(e)}isTried(e){return this.triedPairs.has(e)}getBonus(e){return this.triedPairs.has(e)?0:this.bonusScale}apply(e,t){return Math.min(1,e+this.getBonus(t))}getTriedCount(){return this.triedPairs.size}},G=class{config;sampler;verifier;coherenceGate;transferHistory=[];affinityScores=new Map;performanceProvider=null;transferExecutor=null;nativeModule=null;decayingBeta;plateauDetector;paretoFront;curiosityBonus;constructor(e={}){this.config={...ge,...e},this.sampler=new y,this.verifier=J(this.config.verification),this.coherenceGate=X(),this.decayingBeta=new M,this.plateauDetector=new E,this.paretoFront=new A,this.curiosityBonus=new F,this.tryLoadNativeModule()}evaluateTransfer(e,t){if(!this.isEnabled())return this.createRejectedCandidate(e,t);let r=this.makePairKey(e,t),n=this.sampler.sample(r),i=this.sampler.getObservationCount(r)<this.config.explorationWarmup,a=this.getAffinityScore(e,t);if(this.isMetaLearningEnabled()){let c=this.sampler.getMean(r),u=this.sampler.getAlpha(r)-1;n=this.decayingBeta.applyDecay(n,c,u),n=this.curiosityBonus.apply(n,r)}return{sourceDomain:e,targetDomain:t,sampledProbability:n,affinityScore:a,isExploration:i,pairKey:r}}executeTransfer(e){let t=`transfer-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r=this.coherenceGate.validateTransfer({domain:e.sourceDomain},e.targetDomain);if(!r.approved)return Q.info("Transfer blocked by coherence gate",{transferId:t,source:e.sourceDomain,target:e.targetDomain,reason:r.rejectionReason}),this.createBlockedResult(t,e,r);let n=this.getPerformanceSnapshot(e.sourceDomain),s=this.getPerformanceSnapshot(e.targetDomain),i=this.computeSqrtDampening(e),a=this.doTransfer(e.sourceDomain,e.targetDomain,i),c=this.getPerformanceSnapshot(e.sourceDomain),u=this.getPerformanceSnapshot(e.targetDomain),m=this.verifier.verifyTransfer({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourcePerformanceBefore:n,sourcePerformanceAfter:c,targetPerformanceBefore:s,targetPerformanceAfter:u}),l=a&&m.passed;if(this.sampler.update(e.pairKey,l),this.updateAffinityScore(e.pairKey,l),this.isMetaLearningEnabled()){this.plateauDetector.record(l),this.curiosityBonus.markTried(e.pairKey);let h=this.sampler.getMean(e.pairKey);this.paretoFront.add({pairKey:e.pairKey,successRate:h,speed:1/(1+i),confidence:this.getAffinityScore(e.sourceDomain,e.targetDomain)})}return this.addToHistory({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,success:l,sampledProbability:e.sampledProbability,dampeningFactor:i,sourceDelta:m.sourceDelta,targetDelta:m.targetDelta,timestamp:Date.now()}),Q.info("Transfer completed",{transferId:t,source:e.sourceDomain,target:e.targetDomain,success:l,dampeningFactor:i.toFixed(4),sourceDelta:m.sourceDelta.toFixed(4),targetDelta:m.targetDelta.toFixed(4)}),{transferId:t,candidate:e,success:l,dampeningFactor:i,verification:m,coherenceResult:r,sourcePerformanceBefore:n,sourcePerformanceAfter:c,targetPerformanceBefore:s,targetPerformanceAfter:u,timestamp:Date.now()}}getAffinityScore(e,t){return this.affinityScores.get(this.makePairKey(e,t))??.5}getTransferHistory(){return[...this.transferHistory]}getExpectedSuccessRate(e,t){return this.sampler.getMean(this.makePairKey(e,t))}getObservationCount(e,t){return this.sampler.getObservationCount(this.makePairKey(e,t))}setPerformanceProvider(e){this.performanceProvider=e}setTransferExecutor(e){this.transferExecutor=e}getSampler(){return this.sampler}getCoherenceGate(){return this.coherenceGate}getDecayingBeta(){return this.decayingBeta}getPlateauDetector(){return this.plateauDetector}getParetoFront(){return this.paretoFront}getCuriosityBonus(){return this.curiosityBonus}isLearningPlateaued(){return this.plateauDetector.isPlateaued()}isEnabled(){return p().useCrossDomainTransfer===!0}isMetaLearningEnabled(){return this.config.useMetaLearningEnhancements===!0&&p().useMetaLearningEnhancements!==!1}makePairKey(e,t){return`${e}->${t}`}computeSqrtDampening(e){let t=this.sampler.getObservationCount(e.pairKey);return Math.sqrt(t/(t+this.config.explorationWarmup))}doTransfer(e,t,r){return this.transferExecutor?this.transferExecutor(e,t,r):!0}getPerformanceSnapshot(e){return this.performanceProvider?this.performanceProvider(e):{domain:e,successRate:.5,avgConfidence:.5,patternCount:0,timestamp:Date.now()}}updateAffinityScore(e,t){let r=this.affinityScores.get(e)??.5;this.affinityScores.set(e,.2*(t?1:0)+.8*r)}addToHistory(e){for(this.transferHistory.push(e);this.transferHistory.length>this.config.maxHistorySize;)this.transferHistory.shift()}createBlockedResult(e,t,r){let n={domain:"",successRate:0,avgConfidence:0,patternCount:0,timestamp:Date.now()};return{transferId:e,candidate:t,success:!1,dampeningFactor:0,verification:{passed:!1,sourceStable:!1,targetImproved:!1,sourceDelta:0,targetDelta:0,sourceConfidenceDelta:0,targetConfidenceDelta:0,failureReason:`Coherence gate rejected: ${r.rejectionReason??"unknown"}`},coherenceResult:r,sourcePerformanceBefore:{...n,domain:t.sourceDomain},sourcePerformanceAfter:{...n,domain:t.sourceDomain},targetPerformanceBefore:{...n,domain:t.targetDomain},targetPerformanceAfter:{...n,domain:t.targetDomain},timestamp:Date.now()}}createRejectedCandidate(e,t){return{sourceDomain:e,targetDomain:t,sampledProbability:0,affinityScore:0,isExploration:!1,pairKey:this.makePairKey(e,t)}}tryLoadNativeModule(){this.nativeModule=null}};function $e(o){return new G(o)}export{d as a,y as b,ge as c,M as d,E as e,A as f,F as g,G as h,$e as i};
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.18");process.exit(0)}
|
|
2
|
+
import{a as b}from"./chunk-O5EWFR76.js";import{c as g}from"./chunk-NKU3FFM4.js";import{C as B,S as v,b as p}from"./chunk-V2LJ54KP.js";import{a as I}from"./chunk-BDVFSMOQ.js";b();v();b();v();import{createHash as ue,randomUUID as me}from"crypto";b();function Z(o){let e=2166136261;for(let t=0;t<o.length;t++)e^=o.charCodeAt(t),e=Math.imul(e,16777619);return(e>>>0)%64}function W(o){let e=new Array(64).fill(0),t=o.toLowerCase().split(/[\s,;:.!?()[\]{}"']+/).filter(n=>n.length>0);for(let n of t){let s=Z(n);e[s]++}let r=0;for(let n=0;n<64;n++)r+=e[n]*e[n];if(r=Math.sqrt(r),r>1e-10)for(let n=0;n<64;n++)e[n]/=r;return e}function _(o,e){let t=0,r=0,n=0,s=Math.min(o.length,e.length);for(let a=0;a<s;a++)t+=o[a]*e[a],r+=o[a]*o[a],n+=e[a]*e[a];let i=Math.sqrt(r)*Math.sqrt(n);return i>1e-10?t/i:0}b();import{createRequire as ee}from"module";var S=ee(import.meta.url),V=g.create("coherence-gate-cohomology"),C=null,k=!1;function H(){if(k)return C;k=!0;try{let o=S("prime-radiant-advanced-wasm"),e=S("fs"),t=S("path"),r=t.join(t.dirname(I.resolve("prime-radiant-advanced-wasm")),"prime_radiant_advanced_wasm_bg.wasm");o.initSync({module:e.readFileSync(r)}),C=new o.CohomologyEngine,V.info("CohomologyEngine loaded from prime-radiant-advanced-wasm")}catch(o){V.debug("CohomologyEngine unavailable, using word-frequency fallback",{error:String(o)}),C=null}return C}var te={threshold:5,slack:.5,resetOnAlarm:!0,warmupSamples:20},d=class{config;states=new Map;constructor(e={}){this.config={...te,...e}}update(e,t){let r=this.getOrCreateState(e);if(r.samplesSinceReset++,r.mu===null)return r.warmupSum+=t,r.warmupCount++,r.warmupCount>=this.config.warmupSamples&&(r.mu=r.warmupSum/r.warmupCount),{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:r.samplesSinceReset};r.sPlus=Math.max(0,r.sPlus+(t-r.mu-this.config.slack)),r.sMinus=Math.max(0,r.sMinus+(-t+r.mu-this.config.slack));let n=Math.max(r.sPlus,r.sMinus),s=!1,i="none";r.sPlus>this.config.threshold?(s=!0,i="positive"):r.sMinus>this.config.threshold&&(s=!0,i="negative");let a={driftDetected:s,cumulativeSum:n,direction:i,samplesSinceReset:r.samplesSinceReset};return s&&this.config.resetOnAlarm&&(r.sPlus=0,r.sMinus=0,r.samplesSinceReset=0),a}reset(e){e?this.states.delete(e):this.states.clear()}getState(e){let t=this.states.get(e);if(!t)return{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:0};let r=Math.max(t.sPlus,t.sMinus),n="none";return t.sPlus>this.config.threshold?n="positive":t.sMinus>this.config.threshold&&(n="negative"),{driftDetected:t.sPlus>this.config.threshold||t.sMinus>this.config.threshold,cumulativeSum:r,direction:n,samplesSinceReset:t.samplesSinceReset}}getOrCreateState(e){let t=this.states.get(e);return t||(t={sPlus:0,sMinus:0,samplesSinceReset:0,warmupSum:0,warmupCount:0,mu:null},this.states.set(e,t)),t}};v();var x=g.create("coherence-gate-energy"),D=null,re=[],P=[],ne=100;function oe(){return D||(B()?(D=new d,x.debug("CUSUM drift detector auto-created via feature flag"),D):null)}function O(o,e){let t=oe();if(!t)return;let r=t.update(o,e);if(r.driftDetected){let n={gateType:o,energy:e,cusumResult:r,timestamp:Date.now()};x.warn("CUSUM drift detected",{gateType:o,energy:e,direction:r.direction,cumulativeSum:r.cumulativeSum}),P.push(n),P.length>ne&&P.shift();for(let s of re)try{s(n)}catch(i){x.debug("Drift listener error",{error:String(i)})}}}var f={assertionCoverage:.4,codeCoverage:.3,confidencePenalty:.3,contradictionWeight:.2,laplacianWeight:.15},N=1;function U(o){if(o.assertions.length===0)return 0;let e=o.observedBehavior.length/o.assertions.length;return Math.max(0,Math.min(1-e,1))}function $(o){return Math.max(0,Math.min(1-o.coverage,1))}function j(o){return Math.max(0,Math.min(1-o.confidence,1))}function se(o){if(o.assertions.length===0||o.observedBehavior.length===0)return 0;let e=0,t=["not","never","false","undefined","null","error","fail"];for(let r of o.assertions){let n=r.toLowerCase();for(let s of o.observedBehavior){let i=s.toLowerCase();for(let a of t){let c=n.includes(a),u=i.includes(a);if(c!==u){let m=new Set(n.split(/\s+/)),l=new Set(i.split(/\s+/)),h=0;for(let L of m)l.has(L)&&L.length>3&&h++;if(h>0){e++;break}}}}}return Math.min(e/o.assertions.length,1)}function ie(o,e,t){let r=t[0]?.length??64,n=t.map((c,u)=>({id:u,label:e.assertions[u]?.slice(0,50)??`assertion-${u}`,section:c,weight:e.confidence})),s=[];for(let c=0;c<t.length;c++)for(let u=c+1;u<t.length;u++){let m=[];for(let l=0;l<r;l++)for(let h=0;h<r;h++)m.push(l===h?1:0);s.push({source:c,target:u,weight:1,restriction_map:m,source_dim:r,target_dim:r})}let i=o.consistencyEnergy({nodes:n,edges:s}),a=i/(i+1);return Math.max(0,Math.min(a,1))}function ae(o){let e=0,t=0;for(let n=0;n<o.length;n++)for(let s=n+1;s<o.length;s++)e+=_(o[n],o[s]),t++;if(t===0)return 0;let r=e/t;return Math.max(0,Math.min(1-r,1))}function ce(o){if(o.assertions.length<2)return 0;let e=o.assertions.map(r=>W(r)),t=H();if(t)try{return ie(t,o,e)}catch(r){x.debug("CohomologyEngine.consistencyEnergy failed, using fallback",{error:String(r)})}return ae(e)}function K(o,e="act"){let t=U(o),r=$(o),n=j(o),s=Math.min(t*f.assertionCoverage+r*f.codeCoverage+n*f.confidencePenalty,1);return O(e,s),{energy:s,components:{assertionCoverage:t,codeCoverage:r,confidencePenalty:n,contradictionScore:0,laplacianDeviation:0}}}function q(o,e="retrieve"){let t=U(o),r=$(o),n=j(o),s=se(o),i=ce(o),a=t*f.assertionCoverage+r*f.codeCoverage+n*f.confidencePenalty,c=s*f.contradictionWeight+i*f.laplacianWeight,u=f.assertionCoverage+f.codeCoverage+f.confidencePenalty+f.contradictionWeight+f.laplacianWeight,m=Math.min((a+c)/u,1);return O(e,m),{energy:m,components:{assertionCoverage:t,codeCoverage:r,confidencePenalty:n,contradictionScore:s,laplacianDeviation:i}}}var z=g.create("coherence-gate"),le=.4,T=class{threshold;decisionLog=[];witnessChain=[];lastWitnessHash="0".repeat(64);nativeAvailable=null;governanceChain=null;constructor(e=le){this.threshold=e}setGovernanceChain(e){this.governanceChain=e}computeEnergy(e,t=!1,r="retrieve"){let n=performance.now();if(!t){let a=K(e,r),c=performance.now()-n;if(c<=N)return{energy:a.energy,tier:"reflex",components:a.components,latencyMs:c}}let s=q(e,r),i=performance.now()-n;return{energy:s.energy,tier:"retrieval",components:s.components,latencyMs:i}}validate(e,t,r="retrieve"){let n=t??this.threshold,s=this.computeEnergy(e,!1,r),i=s.energy<=n,a;i||(a=this.buildFailureReason(s,n));let c=this.createWitnessRecord(e,s.energy,n,i);return this.logDecision({id:c.id,timestamp:c.timestamp,domain:e.domain,energy:s.energy,tier:s.tier,passed:i,threshold:n}),{passed:i,energy:s.energy,threshold:n,reason:a,witness:c}}getDecisionLog(){return[...this.decisionLog]}getWitnessChain(){return[...this.witnessChain]}getThreshold(){return this.threshold}clearDecisionLog(){this.decisionLog=[]}validateTransfer(e,t){if(!p().useCoherenceGate)return{approved:!0};let n={assertions:this.extractAssertions(e),observedBehavior:this.extractObservedBehavior(e),coverage:typeof e.coverage=="number"?e.coverage:.5,domain:t,confidence:e.confidence??.5},s=this.validate(n,void 0,"write");return{approved:s.passed,energy:s.energy,rejectionReason:s.reason}}buildFailureReason(e,t){let r=[];r.push(`Coherence energy ${e.energy.toFixed(3)} exceeds threshold ${t.toFixed(3)}.`);let n=e.components;return n.assertionCoverage>.5&&r.push("High assertion-observation mismatch (possible hallucination)."),n.codeCoverage>.5&&r.push("Low code coverage."),n.confidencePenalty>.5&&r.push("Low generator confidence."),n.contradictionScore>.3&&r.push("Contradictions detected between assertions and observed behavior."),n.laplacianDeviation>.5&&r.push("Inconsistent assertion structure (high Laplacian deviation)."),r.join(" ")}createWitnessRecord(e,t,r,n){let s=me(),i=Date.now(),a=this.hashContent(JSON.stringify(e)),c={id:s,timestamp:i,artifactHash:a,energy:t,threshold:r,passed:n,previousHash:this.lastWitnessHash,recordHash:""},u=`${s}|${i}|${a}|${t}|${r}|${n}|${this.lastWitnessHash}`;if(c.recordHash=this.hashContent(u),p().useWitnessChain&&(this.witnessChain.push(c),this.lastWitnessHash=c.recordHash,this.governanceChain))try{let l={type:"coherence-gate",decision:n?"PASS":"FAIL",context:{energy:t,threshold:r,artifactHash:c.artifactHash}};this.governanceChain.appendWitness(l)}catch(l){z.debug("Failed to persist to governance chain",{error:String(l)})}return c}hashContent(e){return ue("sha256").update(e).digest("hex")}logDecision(e){this.decisionLog.push(e);let t=1e3;this.decisionLog.length>t&&(this.decisionLog=this.decisionLog.slice(-t)),z.debug("Coherence decision",{domain:e.domain,energy:e.energy,tier:e.tier,passed:e.passed})}extractAssertions(e){return Array.isArray(e.assertions)?e.assertions.map(String):typeof e.description=="string"?[e.description]:["transfer-pattern"]}extractObservedBehavior(e){return Array.isArray(e.observedBehavior)?e.observedBehavior.map(String):typeof e.evidence=="string"?[e.evidence]:["observed"]}};var R=class{validateTransfer(e,t){return{approved:!0}}};function X(){return p().useCoherenceGate?new T:new R}b();var Y=g.create("transfer-verification"),fe={maxSourceRegression:.05,minTargetImprovement:0,maxSourceConfidenceRegression:.1},w=class{config;constructor(e={}){this.config={...fe,...e}}verifyTransfer(e){let t=e.sourcePerformanceAfter.successRate-e.sourcePerformanceBefore.successRate,r=e.targetPerformanceAfter.successRate-e.targetPerformanceBefore.successRate,n=e.sourcePerformanceAfter.avgConfidence-e.sourcePerformanceBefore.avgConfidence,s=e.targetPerformanceAfter.avgConfidence-e.targetPerformanceBefore.avgConfidence,i=t>=-this.config.maxSourceRegression&&n>=-this.config.maxSourceConfidenceRegression,a=r>=this.config.minTargetImprovement,c=i&&a,u;if(!c){let m=[];i||m.push(`source domain regressed: successRate delta=${t.toFixed(4)}, confidence delta=${n.toFixed(4)}`),a||m.push(`target domain did not improve: successRate delta=${r.toFixed(4)}`),u=m.join("; ")}return c?Y.debug("Transfer verification passed",{transferId:e.transferId,sourceDelta:t,targetDelta:r}):Y.warn("Transfer verification failed",{transferId:e.transferId,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourceDelta:t,targetDelta:r,failureReason:u}),{passed:c,sourceStable:i,targetImproved:a,sourceDelta:t,targetDelta:r,sourceConfidenceDelta:n,targetConfidenceDelta:s,failureReason:u}}getConfig(){return{...this.config}}};function J(o){return new w(o)}v();var y=class{alphas=new Map;betas=new Map;sample(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return this.sampleBeta(t,r)}update(e,t){t?this.alphas.set(e,(this.alphas.get(e)??1)+1):this.betas.set(e,(this.betas.get(e)??1)+1)}getMean(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t/(t+r)}getObservationCount(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t-1+(r-1)}getAlpha(e){return this.alphas.get(e)??1}getBeta(e){return this.betas.get(e)??1}sampleBeta(e,t){let r=this.sampleGamma(e),n=this.sampleGamma(t);return r+n===0?.5:r/(r+n)}sampleGamma(e){if(e<1){let n=Math.random();return this.sampleGamma(e+1)*Math.pow(n,1/e)}let t=e-1/3,r=1/Math.sqrt(9*t);for(;;){let n,s;do n=this.standardNormal(),s=1+r*n;while(s<=0);s=s*s*s;let i=Math.random();if(i<1-.0331*n*n*n*n||Math.log(i)<.5*n*n+t*(1-s+Math.log(s)))return t*s}}standardNormal(){let e=Math.random(),t=Math.random();return Math.sqrt(-2*Math.log(e||1e-10))*Math.cos(2*Math.PI*t)}};var Q=g.create("domain-transfer"),ge={minTransferProbability:.3,explorationWarmup:5,verification:{},maxHistorySize:1e3,useMetaLearningEnhancements:!0},M=class{constructor(e=100){this.decayThreshold=e}decayThreshold;getDecayMultiplier(e){return e<=0?1:Math.pow(.5,e/this.decayThreshold)}applyDecay(e,t,r){return t+(e-t)*this.getDecayMultiplier(r)}},E=class{cusum;outcomes=[];windowSize;constructor(e=20){this.windowSize=e,this.cusum=new d({threshold:3,slack:.1,resetOnAlarm:!1,warmupSamples:Math.min(10,Math.floor(e/2))})}record(e){this.outcomes.push(e),this.outcomes.length>this.windowSize*2&&this.outcomes.splice(0,this.outcomes.length-this.windowSize*2);let t=this.getCurrentRate();this.cusum.update("learn",t)}isPlateaued(){return this.outcomes.length<this.windowSize?!1:!this.cusum.getState("learn").driftDetected}getCurrentRate(){if(this.outcomes.length===0)return 0;let e=this.outcomes.slice(-this.windowSize);return e.filter(Boolean).length/e.length}getOutcomeCount(){return this.outcomes.length}getCusumState(){return this.cusum.getState("learn")}},A=class{front=[];dominates(e,t){let r=e.successRate>=t.successRate&&e.speed>=t.speed&&e.confidence>=t.confidence,n=e.successRate>t.successRate||e.speed>t.speed||e.confidence>t.confidence;return r&&n}add(e){for(let t=this.front.length-1;t>=0;t--)this.dominates(e,this.front[t])&&this.front.splice(t,1);this.front.some(t=>this.dominates(t,e))||this.front.push(e)}getFront(){return[...this.front]}isNonDominated(e){return!this.front.some(t=>this.dominates(t,e))}},F=class{constructor(e=.2){this.bonusScale=e}bonusScale;triedPairs=new Set;markTried(e){this.triedPairs.add(e)}isTried(e){return this.triedPairs.has(e)}getBonus(e){return this.triedPairs.has(e)?0:this.bonusScale}apply(e,t){return Math.min(1,e+this.getBonus(t))}getTriedCount(){return this.triedPairs.size}},G=class{config;sampler;verifier;coherenceGate;transferHistory=[];affinityScores=new Map;performanceProvider=null;transferExecutor=null;nativeModule=null;decayingBeta;plateauDetector;paretoFront;curiosityBonus;constructor(e={}){this.config={...ge,...e},this.sampler=new y,this.verifier=J(this.config.verification),this.coherenceGate=X(),this.decayingBeta=new M,this.plateauDetector=new E,this.paretoFront=new A,this.curiosityBonus=new F,this.tryLoadNativeModule()}evaluateTransfer(e,t){if(!this.isEnabled())return this.createRejectedCandidate(e,t);let r=this.makePairKey(e,t),n=this.sampler.sample(r),i=this.sampler.getObservationCount(r)<this.config.explorationWarmup,a=this.getAffinityScore(e,t);if(this.isMetaLearningEnabled()){let c=this.sampler.getMean(r),u=this.sampler.getAlpha(r)-1;n=this.decayingBeta.applyDecay(n,c,u),n=this.curiosityBonus.apply(n,r)}return{sourceDomain:e,targetDomain:t,sampledProbability:n,affinityScore:a,isExploration:i,pairKey:r}}executeTransfer(e){let t=`transfer-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r=this.coherenceGate.validateTransfer({domain:e.sourceDomain},e.targetDomain);if(!r.approved)return Q.info("Transfer blocked by coherence gate",{transferId:t,source:e.sourceDomain,target:e.targetDomain,reason:r.rejectionReason}),this.createBlockedResult(t,e,r);let n=this.getPerformanceSnapshot(e.sourceDomain),s=this.getPerformanceSnapshot(e.targetDomain),i=this.computeSqrtDampening(e),a=this.doTransfer(e.sourceDomain,e.targetDomain,i),c=this.getPerformanceSnapshot(e.sourceDomain),u=this.getPerformanceSnapshot(e.targetDomain),m=this.verifier.verifyTransfer({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourcePerformanceBefore:n,sourcePerformanceAfter:c,targetPerformanceBefore:s,targetPerformanceAfter:u}),l=a&&m.passed;if(this.sampler.update(e.pairKey,l),this.updateAffinityScore(e.pairKey,l),this.isMetaLearningEnabled()){this.plateauDetector.record(l),this.curiosityBonus.markTried(e.pairKey);let h=this.sampler.getMean(e.pairKey);this.paretoFront.add({pairKey:e.pairKey,successRate:h,speed:1/(1+i),confidence:this.getAffinityScore(e.sourceDomain,e.targetDomain)})}return this.addToHistory({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,success:l,sampledProbability:e.sampledProbability,dampeningFactor:i,sourceDelta:m.sourceDelta,targetDelta:m.targetDelta,timestamp:Date.now()}),Q.info("Transfer completed",{transferId:t,source:e.sourceDomain,target:e.targetDomain,success:l,dampeningFactor:i.toFixed(4),sourceDelta:m.sourceDelta.toFixed(4),targetDelta:m.targetDelta.toFixed(4)}),{transferId:t,candidate:e,success:l,dampeningFactor:i,verification:m,coherenceResult:r,sourcePerformanceBefore:n,sourcePerformanceAfter:c,targetPerformanceBefore:s,targetPerformanceAfter:u,timestamp:Date.now()}}getAffinityScore(e,t){return this.affinityScores.get(this.makePairKey(e,t))??.5}getTransferHistory(){return[...this.transferHistory]}getExpectedSuccessRate(e,t){return this.sampler.getMean(this.makePairKey(e,t))}getObservationCount(e,t){return this.sampler.getObservationCount(this.makePairKey(e,t))}setPerformanceProvider(e){this.performanceProvider=e}setTransferExecutor(e){this.transferExecutor=e}getSampler(){return this.sampler}getCoherenceGate(){return this.coherenceGate}getDecayingBeta(){return this.decayingBeta}getPlateauDetector(){return this.plateauDetector}getParetoFront(){return this.paretoFront}getCuriosityBonus(){return this.curiosityBonus}isLearningPlateaued(){return this.plateauDetector.isPlateaued()}isEnabled(){return p().useCrossDomainTransfer===!0}isMetaLearningEnabled(){return this.config.useMetaLearningEnhancements===!0&&p().useMetaLearningEnhancements!==!1}makePairKey(e,t){return`${e}->${t}`}computeSqrtDampening(e){let t=this.sampler.getObservationCount(e.pairKey);return Math.sqrt(t/(t+this.config.explorationWarmup))}doTransfer(e,t,r){return this.transferExecutor?this.transferExecutor(e,t,r):!0}getPerformanceSnapshot(e){return this.performanceProvider?this.performanceProvider(e):{domain:e,successRate:.5,avgConfidence:.5,patternCount:0,timestamp:Date.now()}}updateAffinityScore(e,t){let r=this.affinityScores.get(e)??.5;this.affinityScores.set(e,.2*(t?1:0)+.8*r)}addToHistory(e){for(this.transferHistory.push(e);this.transferHistory.length>this.config.maxHistorySize;)this.transferHistory.shift()}createBlockedResult(e,t,r){let n={domain:"",successRate:0,avgConfidence:0,patternCount:0,timestamp:Date.now()};return{transferId:e,candidate:t,success:!1,dampeningFactor:0,verification:{passed:!1,sourceStable:!1,targetImproved:!1,sourceDelta:0,targetDelta:0,sourceConfidenceDelta:0,targetConfidenceDelta:0,failureReason:`Coherence gate rejected: ${r.rejectionReason??"unknown"}`},coherenceResult:r,sourcePerformanceBefore:{...n,domain:t.sourceDomain},sourcePerformanceAfter:{...n,domain:t.sourceDomain},targetPerformanceBefore:{...n,domain:t.targetDomain},targetPerformanceAfter:{...n,domain:t.targetDomain},timestamp:Date.now()}}createRejectedCandidate(e,t){return{sourceDomain:e,targetDomain:t,sampledProbability:0,affinityScore:0,isExploration:!1,pairKey:this.makePairKey(e,t)}}tryLoadNativeModule(){this.nativeModule=null}};function $e(o){return new G(o)}export{d as a,y as b,ge as c,M as d,E as e,A as f,F as g,G as h,$e as i};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.18");process.exit(0)}
|
|
2
|
+
import{a as G,c as R,d as C}from"./chunk-MVYQRVLP.js";import{a as I}from"./chunk-PZOYQHWS.js";import{a as E,b as P,c as x,e as K}from"./chunk-MZRBNBB3.js";import{b as F,d as J}from"./chunk-YP2GHQSV.js";var $=new Set(["false","0","off","no"]),V=new Set([...$,"disabled","disable","none","never"]),Y=30,Q=36500;function ge(l=process.env){let e=l.AQE_WORKERS_ENABLED;return e===void 0?!0:!$.has(e.trim().toLowerCase())}function fe(l=process.env){let e=l.AQE_DISABLED_WORKERS;if(!e)return[];let t=e.split(",").map(i=>i.trim().toLowerCase()).filter(i=>i.length>0);return Array.from(new Set(t))}function ye(l=process.env){let e=l.AQE_DREAM_INSIGHTS_RETENTION_DAYS;if(e===void 0||e.trim()==="")return{retentionDays:Y};let t=e.trim().toLowerCase();if(V.has(t))return{retentionDays:null};if(/^\d+$/.test(t)){let i=Number(t);if(i>=1&&i<=Q)return{retentionDays:i}}return{retentionDays:null,warning:`Invalid AQE_DREAM_INSIGHTS_RETENTION_DAYS=${JSON.stringify(e)}; expected a whole number of days (1-${Q}), 0 or "off". The dream_insights retention sweep is off until this is fixed; nothing is deleted.`}}var M="quality-daemon",A=class{constructor(e){this.backend=e}backend;async get(e,t){return this.backend.kvGet(e,t?.namespace??M)}async set(e,t){await this.backend.kvSet(e,t,M)}async search(e,t,i){return this.backend.kvSearch(e,i?.namespace??M,t)}};import{cpus as de,freemem as he,totalmem as me,loadavg as pe}from"os";var p=class{queues={now:[],next:[],later:[]};_maxSize;constructor(e=1e3){this._maxSize=e}enqueue(e){return this.size>=this._maxSize&&(this.pruneExpired(),this.size>=this._maxSize)?!1:(this.queues[e.priority].push(e),!0)}dequeue(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(;i.length>0;){let r=i.shift();if(!(r.ttlMs&&e-r.createdAt>r.ttlMs))return r}}}peek(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(let r of i)if(!r.ttlMs||e-r.createdAt<=r.ttlMs)return r}}drainPriority(e){let t=this.queues[e].splice(0),i=Date.now();return t.filter(r=>!r.ttlMs||i-r.createdAt<=r.ttlMs)}pruneExpired(){let e=0,t=Date.now();for(let i of["now","next","later"]){let r=this.queues[i].length;this.queues[i]=this.queues[i].filter(o=>!o.ttlMs||t-o.createdAt<=o.ttlMs),e+=r-this.queues[i].length}return e}get size(){return this.queues.now.length+this.queues.next.length+this.queues.later.length}get depths(){return{now:this.queues.now.length,next:this.queues.next.length,later:this.queues.later.length}}get isEmpty(){return this.size===0}clear(){this.queues.now=[],this.queues.next=[],this.queues.later=[]}};import{watch as X}from"fs";import{resolve as H,join as Z}from"path";import{existsSync as ee,readFileSync as te}from"fs";var N=1e4,ie={repoRoot:process.cwd(),debounceMs:500,maxChangedFiles:200,pollIntervalMs:5e3},g=class{constructor(e,t){this.queue=e;this.options={...ie,...t}}queue;watcher;pollTimer;options;lastKnownHeads=new Map;debounceTimer;_running=!1;_polling=!1;retryTimers=new Set;get running(){return this._running}async start(){if(this._running)return;let e=H(this.options.repoRoot,".git","refs","heads");if(!ee(e))throw new Error(`Git refs directory not found: ${e}`);await this.snapshotHeads(),process.platform==="darwin"||process.platform==="win32"?this.watcher=X(e,{recursive:!0},(i,r)=>{r&&this.handleRefChange(r)}):(this.pollTimer=setInterval(()=>{this.poll().catch(i=>{console.debug("[GitWatcher] Poll error:",i)})},this.options.pollIntervalMs),this.pollTimer.unref?.()),this._running=!0}stop(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0),this.watcher&&(this.watcher.close(),this.watcher=void 0);for(let e of this.retryTimers)clearTimeout(e);this.retryTimers.clear(),this._running=!1}async poll(){if(this._polling)return[];this._polling=!0;let e=[];try{let t=await C(["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot,timeout:N});for(let i of t.trim().split(`
|
|
3
|
+
`)){if(!i)continue;let[r,o]=i.split(" "),n=this.lastKnownHeads.get(r);if(n&&n!==o){if(!await this.enqueueCommitAnalysis(r,o,n))continue;e.push(r)}this.lastKnownHeads.set(r,o)}}catch{}finally{this._polling=!1}return e}handleRefChange(e){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.processRefChange(e).catch(t=>{console.debug("[GitWatcher] Error processing ref change:",t)})},this.options.debounceMs)}async processRefChange(e){let t=e.replace(/\\/g,"/"),i=H(this.options.repoRoot,".git","refs","heads"),r=Z(i,e),o;try{o=te(r,"utf-8").trim()}catch{return}let n=this.lastKnownHeads.get(t);if(n!==o){if(!await this.enqueueCommitAnalysis(t,o,n)){let s=setTimeout(()=>{this.retryTimers.delete(s),this.processRefChange(e).catch(a=>{console.debug("[GitWatcher] Error processing ref change:",a)})},this.options.pollIntervalMs);s.unref?.(),this.retryTimers.add(s);return}this.lastKnownHeads.set(t,o)}}async enqueueCommitAnalysis(e,t,i){if(I(t,"commit hash"))return!0;let r=i&&!I(i,"commit hash")?i:void 0,o=async u=>(await C(["diff-tree","--no-commit-id","--name-only","-r",...u],{cwd:this.options.repoRoot,timeout:N})).trim().split(`
|
|
4
|
+
`).filter(Boolean).slice(0,this.options.maxChangedFiles),n;try{n=await o(r?[r,t]:["--root",t])}catch(u){if(u instanceof R)return!1;if(r)try{n=await o(["--root",t])}catch(c){if(c instanceof R)return!1}}let s={type:"git_commit",branch:e,commitHash:t,...n?{changedFiles:n}:{}},a={id:`git-${t}-${Date.now()}`,priority:"next",payload:s,createdAt:Date.now(),source:"git-watcher",ttlMs:300*1e3};return this.queue.enqueue(a),!0}async snapshotHeads(){try{let e=await C(["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot,timeout:N});for(let t of e.trim().split(`
|
|
5
|
+
`)){if(!t)continue;let[i,r]=t.split(" ");this.lastKnownHeads.set(i,r)}}catch{}}};function W(l,e){return l===null||e===null?0:l-e}var re={regressionThreshold:2,gapThreshold:60,memoryPrefix:"quality-daemon:coverage"},f=class{constructor(e,t){this.queue=e;this.options={...re,...t}}queue;options;async analyze(e,t,i){let r=await t.get(`${this.options.memoryPrefix}:snapshot`);if(await t.set(`${this.options.memoryPrefix}:snapshot`,e),!r)return{regressionDetected:!1,overallDelta:{line:0,branch:0,function:0,statement:0},affectedFiles:[],newGaps:[]};let o=r,n={line:e.overall.line-o.overall.line,branch:W(e.overall.branch,o.overall.branch??null),function:W(e.overall.function,o.overall.function??null),statement:W(e.overall.statement,o.overall.statement??null)},s=n.line<-this.options.regressionThreshold||(n.branch??0)<-this.options.regressionThreshold,a=i??Object.keys(e.files),u=[],c=[];for(let h of a){let d=e.files[h],m=o.files[h];if(!d)continue;let q=m?d.line-m.line:0,O=m?d.branch-m.branch:0,D=m?d.uncoveredLines.filter(_=>!m.uncoveredLines.includes(_)):d.uncoveredLines;if((q!==0||O!==0||D.length>0)&&u.push({file:h,lineDelta:q,branchDelta:O,newUncoveredLines:D}),d.line<this.options.gapThreshold){let _=this.computeRiskScore(d,D.length);c.push({file:h,uncoveredLines:d.uncoveredLines,currentCoverage:d.line,riskScore:_})}}return(s||c.length>0)&&this.enqueueTestSuggestion(e,o,c),await t.set(`${this.options.memoryPrefix}:delta`,{timestamp:Date.now(),overallDelta:n,regressionDetected:s,affectedFileCount:u.length,gapCount:c.length}),{regressionDetected:s,overallDelta:n,affectedFiles:u,newGaps:c}}async buildSnapshot(e){let t=await e.get("coverage:latest"),i=G(t);if(i)return{timestamp:Date.now(),overall:{line:i.line,branch:i.branch,function:i.function,statement:i.statement},files:t&&typeof t.files=="object"?t.files:{}}}computeRiskScore(e,t){let r=1-Math.min(100,Math.max(0,e.line))/100,o=Math.min(t/50,1);return Math.min(1,r*.6+o*.4)}enqueueTestSuggestion(e,t,i){let r={type:"coverage_delta",previousSnapshot:`snapshot-${t.timestamp}`,currentSnapshot:`snapshot-${e.timestamp}`},o={id:`coverage-delta-${Date.now()}`,priority:i.some(n=>n.riskScore>.8)?"now":"next",payload:r,createdAt:Date.now(),source:"coverage-delta",ttlMs:600*1e3};this.queue.enqueue(o)}};K();import{execFile as oe}from"child_process";import{promisify as ne}from"util";var se=ne(oe),ae={runsPerWorkflow:10,flakyThreshold:3,repo:""},y=class{constructor(e,t){this.queue=e;this.options={...ae,...t}}queue;options;async check(){let e=await this.fetchRecentRuns(),t=this.groupByWorkflow(e),i=[],r=[],o=0;for(let[s,a]of Object.entries(t)){let u=a.filter(m=>m.conclusion==="failure").length,c=a.length>0?(a.length-u)/a.length*100:100,h=this.countConsecutiveFailures(a),d=a[0]?.conclusion??"unknown";d==="failure"&&o++,h>=this.options.flakyThreshold&&(r.push(s),this.enqueueFailureAlert(s,a[0])),i.push({name:s,recentRuns:a.length,failedRuns:u,successRate:Math.round(c*10)/10,lastConclusion:d,consecutiveFailures:h})}let n=this.calculateHealthScore(i);return{timestamp:Date.now(),workflows:i,failingWorkflows:o,flakyWorkflows:r,healthScore:n}}async fetchRecentRuns(){try{let e=["run","list","--limit",String(this.options.runsPerWorkflow*5),"--json","name,status,conclusion,headBranch,number,databaseId,createdAt"];this.options.repo&&e.push("--repo",this.options.repo);let{stdout:t}=await se("gh",e,{timeout:15e3});return JSON.parse(t).map(r=>({name:r.name,status:r.status,conclusion:r.conclusion??"pending",headBranch:r.headBranch,runNumber:r.number,databaseId:r.databaseId,createdAt:r.createdAt}))}catch{return[]}}groupByWorkflow(e){let t=E();for(let i of e){let r=P(t,i.name);r||(r=[],x(t,i.name,r)),r.push(i)}for(let i of Object.keys(t))x(t,i,P(t,i).slice(0,this.options.runsPerWorkflow));return t}countConsecutiveFailures(e){let t=0;for(let i of e)if(i.conclusion==="failure")t++;else break;return t}calculateHealthScore(e){if(e.length===0)return 100;let t=e.reduce((i,r)=>i+r.successRate,0)/e.length;return Math.round(t)}enqueueFailureAlert(e,t){let i={type:"ci_failure",workflowName:e,runId:t.databaseId,conclusion:t.conclusion},r={id:`ci-failure-${e}-${Date.now()}`,priority:"now",payload:i,createdAt:Date.now(),source:"ci-monitor",ttlMs:1800*1e3};this.queue.enqueue(r)}};var le={memoryPrefix:"quality-daemon:suggestions",maxSuggestions:100,minRiskScore:.3},v=class{options;constructor(e){this.options={...le,...e}}async suggest(e,t,i){let r=[],o=e.filter(s=>s.riskScore>=this.options.minRiskScore);for(let s of o){let a=t.includes(s.file),u=this.determinePriority(s,a),c=this.determineTestType(s.file),h=this.estimateEffort(s);r.push({id:`suggestion-${Date.now()}-${r.length}`,file:s.file,uncoveredLines:s.uncoveredLines.slice(0,50),suggestedTestType:c,description:this.generateDescription(s,c),priority:u,estimatedEffort:h,createdAt:Date.now(),status:"pending"})}r.sort((s,a)=>{let u={high:0,medium:1,low:2};return u[s.priority]-u[a.priority]});let n=r.slice(0,this.options.maxSuggestions);return await this.storeSuggestions(n,i),n}async getPending(e){return(await e.get(`${this.options.memoryPrefix}:list`)??[]).filter(i=>i.status==="pending")}async updateStatus(e,t,i){let r=await i.get(`${this.options.memoryPrefix}:list`);if(!r)return!1;let o=r.findIndex(s=>s.id===e);if(o===-1)return!1;let n=r.map((s,a)=>a===o?{...s,status:t}:s);return await i.set(`${this.options.memoryPrefix}:list`,n),!0}determinePriority(e,t){return e.riskScore>.8?"high":t||e.riskScore>.5?"medium":"low"}determineTestType(e){return e.includes("/api/")||e.includes("/routes/")||e.includes("/handlers/")?"integration":e.includes("/e2e/")||e.includes("/pages/")||e.includes("/views/")?"e2e":"unit"}estimateEffort(e){return e.uncoveredLines.length<=10?"small":e.uncoveredLines.length<=50?"medium":"large"}generateDescription(e,t){let i=e.uncoveredLines.length,r=Math.round(e.currentCoverage);return`Add ${t} tests for ${e.file} (${i} uncovered lines, ${r}% coverage, risk ${(e.riskScore*100).toFixed(0)}%)`}async storeSuggestions(e,t){let o=[...(await t.get(`${this.options.memoryPrefix}:list`)??[]).filter(n=>n.status!=="pending"),...e].slice(-this.options.maxSuggestions);await t.set(`${this.options.memoryPrefix}:list`,o),await t.set(`${this.options.memoryPrefix}:count`,{pending:e.length,total:o.length,lastUpdated:Date.now()})}};var ue={memoryPrefix:"quality-daemon:nightly",maxEntryAge:6048e5,nightlyHour:2},w=class{constructor(e,t){this.queue=e;this.options={...ue,...t}}queue;options;lastRunDate;shouldRun(){let e=new Date,t=e.toISOString().split("T")[0];return this.lastRunDate===t?!1:e.getHours()>=this.options.nightlyHour}scheduleIfDue(){if(!this.shouldRun())return!1;let e={type:"nightly",tasks:["consolidate_patterns","prune_expired","generate_report"]},t={id:`nightly-${Date.now()}`,priority:"later",payload:e,createdAt:Date.now(),source:"nightly-consolidation",ttlMs:720*60*1e3};return this.queue.enqueue(t)}async execute(e,t){let i=Date.now(),r=new Date().toISOString().split("T")[0],o=await this.consolidatePatterns(e),n=await this.pruneExpired(e),s=this.generateReport(r,t);await e.set(`${this.options.memoryPrefix}:report:${r}`,s),this.lastRunDate=r;let a={timestamp:Date.now(),patternsConsolidated:o,entriesPruned:n,reportGenerated:!0,durationMs:Date.now()-i};return await e.set(`${this.options.memoryPrefix}:last-result`,a),a}async getLastResult(e){return e.get(`${this.options.memoryPrefix}:last-result`)}async consolidatePatterns(e){let t=await e.search("quality-daemon:*"),i=0;return await e.get("quality-daemon:suggestions:count")&&i++,await e.get("quality-daemon:coverage:delta")&&i++,i}async pruneExpired(e){let t=await e.search("quality-daemon:*"),i=0,r=Date.now();for(let o of t){if(o.endsWith(":snapshot")||o.endsWith(":list"))continue;let n=await e.get(o);n&&typeof n.timestamp=="number"&&r-n.timestamp>this.options.maxEntryAge&&(await e.set(o,{pruned:!0,prunedAt:r}),i++)}return i}generateReport(e,t){return{date:e,coverageHealth:t.coverageHealth??0,ciHealth:t.ciHealth??0,commitsAnalyzed:t.commitsAnalyzed??0,suggestionsGenerated:t.suggestionsGenerated??0,notificationsSent:t.notificationsSent??0,queueDepthAvg:t.queueDepthAvg??0,daemonUptime:t.uptimeSeconds??0}}};J();import{writeFileSync as L,mkdirSync as U,readdirSync as T,readFileSync as z,unlinkSync as j}from"fs";import{join as b}from"path";var ce={maxNotifications:200},k=class{notificationsDir;maxNotifications;webhookUrl;urlValidator;_sentCount=0;constructor(e){this.notificationsDir=e?.notificationsDir??F("notifications"),this.maxNotifications=e?.maxNotifications??ce.maxNotifications,this.webhookUrl=e?.webhookUrl,this.urlValidator=e?.urlValidator}get sentCount(){return this._sentCount}initialize(){U(this.notificationsDir,{recursive:!0})}async send(e){let t={...e,id:`notif-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now(),read:!1};return this.writeToFile(t),this.webhookUrl&&await this.sendWebhook(t),this._sentCount++,this.pruneOldNotifications(),t}list(e){let t=e?.limit??50;try{let i=T(this.notificationsDir).filter(o=>o.endsWith(".json")).sort().reverse(),r=[];for(let o of i){if(r.length>=t)break;try{let n=z(b(this.notificationsDir,o),"utf-8"),s=JSON.parse(n);if(e?.unreadOnly&&s.read||e?.type&&s.type!==e.type)continue;r.push(s)}catch{}}return r}catch{return[]}}markRead(e){try{let t=T(this.notificationsDir).filter(n=>n.endsWith(`-${e}.json`));if(t.length===0)return!1;let i=b(this.notificationsDir,t[0]),o={...JSON.parse(z(i,"utf-8")),read:!0};return L(i,JSON.stringify(o,null,2)),!0}catch{return!1}}clear(){try{let e=T(this.notificationsDir).filter(t=>t.endsWith(".json"));for(let t of e)j(b(this.notificationsDir,t));return e.length}catch{return 0}}writeToFile(e){try{U(this.notificationsDir,{recursive:!0});let t=`${e.timestamp}-${e.id}.json`,i=b(this.notificationsDir,t);L(i,JSON.stringify(e,null,2))}catch(t){console.debug("[NotificationService] Failed to write notification:",t)}}async sendWebhook(e){if(this.webhookUrl){if(this.urlValidator&&!this.urlValidator(this.webhookUrl)){console.warn("[NotificationService] Webhook URL blocked by SSRF guard:",this.webhookUrl);return}try{let t=await fetch(this.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(5e3)});t.ok||console.debug(`[NotificationService] Webhook returned ${t.status}`)}catch(t){console.debug("[NotificationService] Webhook delivery failed:",t)}}}pruneOldNotifications(){try{let e=T(this.notificationsDir).filter(i=>i.endsWith(".json")).sort();if(e.length<=this.maxNotifications)return;let t=e.slice(0,e.length-this.maxNotifications);for(let i of t)j(b(this.notificationsDir,i))}catch{}}};var S={tickIntervalMs:3e4,ciPollIntervalMs:5*6e4,coverageCheckIntervalMs:2*6e4,cpuThreshold:.7,memoryThreshold:.8},B=class{queue;gitWatcher;coverageDelta;ciMonitor;testSuggester;nightlyConsolidation;notificationService;tickTimer;_running=!1;_startedAt=0;_tickCount=0;_lastTickAt;_throttled=!1;_commitsAnalyzed=0;_suggestionsGenerated=0;_ciHealth=100;_coverageHealth=100;_lastCICheck;_lastCoverageCheck;_memory;config;constructor(e){this.config={tickIntervalMs:e?.tickIntervalMs??S.tickIntervalMs,ciPollIntervalMs:e?.ciPollIntervalMs??S.ciPollIntervalMs,coverageCheckIntervalMs:e?.coverageCheckIntervalMs??S.coverageCheckIntervalMs,cpuThreshold:e?.cpuThreshold??S.cpuThreshold,memoryThreshold:e?.memoryThreshold??S.memoryThreshold},this.queue=new p,this.gitWatcher=new g(this.queue,e?.git),this.coverageDelta=new f(this.queue,e?.coverage),this.ciMonitor=new y(this.queue,e?.ci),this.testSuggester=new v(e?.suggestions),this.nightlyConsolidation=new w(this.queue,e?.nightly),this.notificationService=new k(e?.notifications)}get running(){return this._running}async start(e){this._running||(this._memory=e,this._running=!0,this._startedAt=Date.now(),this.notificationService.initialize(),await this.gitWatcher.start().catch(t=>{console.debug("[QualityDaemon] Git watcher failed to start:",t)}),this.scheduleTick())}async stop(){this._running&&(this._running=!1,this.tickTimer&&(clearTimeout(this.tickTimer),this.tickTimer=void 0),this.gitWatcher.stop(),this._memory&&await this._memory.set("quality-daemon:state",{stoppedAt:Date.now(),tickCount:this._tickCount,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated}))}getStatus(){return{running:this._running,uptimeSeconds:this._running?Math.floor((Date.now()-this._startedAt)/1e3):0,tickCount:this._tickCount,queueDepth:this.queue.depths,lastTickAt:this._lastTickAt,throttled:this._throttled,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated,notificationsSent:this.notificationService.sentCount,ciHealth:this._ciHealth,coverageHealth:this._coverageHealth,lastCICheck:this._lastCICheck,lastCoverageCheck:this._lastCoverageCheck}}scheduleTick(){this._running&&(this.tickTimer=setTimeout(()=>this.tick(),this.config.tickIntervalMs),this.tickTimer.unref?.())}async tick(){if(!(!this._running||!this._memory)){if(this._tickCount++,this._lastTickAt=Date.now(),this._throttled=this.isResourceConstrained(),this._throttled){await this.processNowItems(this._memory),this.scheduleTick();return}await this.processQueue(this._memory),await this.runPeriodicChecks(this._memory),this.nightlyConsolidation.scheduleIfDue(),this.queue.pruneExpired(),this.scheduleTick()}}async processQueue(e){let t=0,i=10;for(;t<i&&!this.queue.isEmpty;){let r=this.queue.dequeue();if(!r)break;await this.handleQueueItem(r,e),t++}}async processNowItems(e){let t=this.queue.drainPriority("now");for(let i of t)await this.handleQueueItem(i,e)}async handleQueueItem(e,t){let i=e.payload;switch(i.type){case"git_commit":{this._commitsAnalyzed++;let r=await this.coverageDelta.buildSnapshot(t);if(r){let o=await this.coverageDelta.analyze(r,t,i.changedFiles);if(o.regressionDetected&&await this.notificationService.send({type:"coverage_drop",title:"Coverage Regression Detected",message:`Line coverage delta: ${o.overallDelta.line.toFixed(1)}% (${o.affectedFiles.length} files affected)`,severity:"high",metadata:{delta:o.overallDelta,commit:i.commitHash}}),o.newGaps.length>0){let n=await this.testSuggester.suggest(o.newGaps,i.changedFiles??[],t);this._suggestionsGenerated+=n.length,n.length>0&&await this.notificationService.send({type:"suggestion_available",title:"New Test Suggestions Available",message:`${n.length} test suggestions generated for uncovered code`,severity:"info",metadata:{count:n.length}})}}break}case"coverage_delta":{let r=await this.testSuggester.getPending(t);r.length>0&&await this.notificationService.send({type:"suggestion_available",title:"Test Suggestions Pending",message:`${r.length} test suggestions awaiting review`,severity:"info",metadata:{count:r.length}});break}case"gate_failure":await this.notificationService.send({type:"gate_failure",title:`Quality Gate Failed: ${i.gateName}`,message:`Score ${i.score} below threshold ${i.threshold}`,severity:"critical",metadata:{gate:i.gateName,score:i.score,threshold:i.threshold}});break;case"ci_failure":await this.notificationService.send({type:"ci_failure",title:`CI Failure: ${i.workflowName}`,message:`Workflow ${i.workflowName} run #${i.runId} concluded: ${i.conclusion}`,severity:"high",metadata:{workflow:i.workflowName,runId:i.runId}});break;case"nightly":{let r={coverageHealth:this._coverageHealth,ciHealth:this._ciHealth,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated,notificationsSent:this.notificationService.sentCount,queueDepthAvg:this.queue.size,uptimeSeconds:Math.floor((Date.now()-this._startedAt)/1e3)};await this.nightlyConsolidation.execute(t,r);break}default:console.warn("[QualityDaemon] Unhandled payload type:",i.type)}}async runPeriodicChecks(e){let t=Date.now();if(!this._lastCICheck||t-this._lastCICheck>=this.config.ciPollIntervalMs)try{let i=await this.ciMonitor.check();this._ciHealth=i.healthScore,this._lastCICheck=t,i.flakyWorkflows.length>0&&await this.notificationService.send({type:"flaky_detected",title:"Flaky Workflows Detected",message:`${i.flakyWorkflows.length} workflows showing repeated failures: ${i.flakyWorkflows.join(", ")}`,severity:"medium",metadata:{workflows:i.flakyWorkflows}})}catch{}if(!this._lastCoverageCheck||t-this._lastCoverageCheck>=this.config.coverageCheckIntervalMs)try{let i=await this.coverageDelta.buildSnapshot(e);if(i){let r=[i.overall.line,i.overall.branch,i.overall.function,i.overall.statement].filter(o=>typeof o=="number");this._coverageHealth=Math.round(r.reduce((o,n)=>o+n,0)/r.length),this._lastCoverageCheck=t}}catch{}}isResourceConstrained(){if(1-he()/me()>this.config.memoryThreshold)return!0;let t=de().length;return(t>0?pe()[0]/t:0)>this.config.cpuThreshold}};export{ge as a,fe as b,ye as c,A as d,B as e};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
var e=null,f=null,t=null,u=!1;async function W(){return u&&!t?e:t||(t=(async()=>{try{if(process.env.AQE_RVF_MODE==="sqlite-only"||process.env.AQE_MEMORY_BACKEND==="memory")return null;let{isRvfNativeAvailable:d}=await import("./rvf-native-adapter-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.18");process.exit(0)}
|
|
2
|
+
var e=null,f=null,t=null,u=!1;async function W(){return u&&!t?e:t||(t=(async()=>{try{if(process.env.AQE_RVF_MODE==="sqlite-only"||process.env.AQE_MEMORY_BACKEND==="memory")return null;let{isRvfNativeAvailable:d}=await import("./rvf-native-adapter-6JQJIKKW.js");if(!d())return null;let{getUnifiedMemory:v,findProjectRoot:p}=await import("./unified-memory-GUR3IUI6.js"),o=v().getDatabase();if(!o)return null;let{join:m}=await import("node:path"),g=m(process.env.AQE_PROJECT_ROOT??p(),".agentic-qe","brain.rvf"),{RvfDualWriter:R}=await import("./rvf-dual-writer-OG7OV2AK.js"),l=new R(o,{rvfPath:g,mode:"dual-write",dimensions:384});await l.initialize(),e=l;try{let{getRvfMigrationStage:y}=await import("./feature-flags-OYYHY7LS.js"),a=y();if(a>=2){let{RvfMigrationAdapter:A}=await import("./rvf-migration-adapter-THYMW7ZO.js"),s=new A({stage:a});s.setSqliteDb(o);let{getSharedRvfAdapter:D}=await import("./shared-rvf-adapter-GKD74QUB.js"),i=D();if(i){let h={ingest:n=>i.ingest(n),search:(n,M)=>i.search(n,M).map(c=>({id:c.id,score:c.score})),delete:n=>i.delete(n),status:()=>i.status(),close:()=>{}};s.setRvfStore(h)}f=s,console.log(`[RVF] Migration adapter active at stage ${a} (${["sqlite-only","hybrid","dual-sqlite","dual-rvf","rvf-primary"][a]})`)}}catch{}return l}catch(r){return(process.env.DEBUG||process.env.AQE_VERBOSE)&&console.debug("[RVF] Dual-writer init failed, degrading to sqlite-only:",r instanceof Error?r.message:r),null}finally{u=!0,t=null,import("./base-J2FXOE77.js").then(({registerRvfResetFn:r})=>r(w)).catch(()=>{})}})(),t)}function S(){return e}function b(){return f}function w(){if(e){try{e.close()}catch{}e=null}f=null,t=null,u=!1}export{W as a,S as b,b as c,w as d};
|