agentic-qe 3.13.2 → 3.13.4
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/.agents/skills/aqe-plan-work/SKILL.md +31 -0
- package/.agents/skills/aqe-plan-work/agents/openai.yaml +4 -0
- package/.agents/skills/aqe-plan-work/references/planning-framework.md +39 -0
- package/.agents/skills/aqe-research/SKILL.md +31 -0
- package/.agents/skills/aqe-research/agents/openai.yaml +4 -0
- package/.agents/skills/aqe-research/references/evidence-rules.md +21 -0
- package/.agents/skills/aqe-ruflo/SKILL.md +29 -0
- package/.claude/commands/pair/README.md +261 -0
- package/.claude/commands/pair/commands.md +546 -0
- package/.claude/commands/pair/config.md +510 -0
- package/.claude/commands/pair/examples.md +512 -0
- package/.claude/commands/pair/modes.md +348 -0
- package/.claude/commands/pair/session.md +407 -0
- package/.claude/commands/pair/start.md +209 -0
- package/.claude/commands/stream-chain/pipeline.md +121 -0
- package/.claude/commands/stream-chain/run.md +70 -0
- package/.claude/commands/training/README.md +9 -0
- package/.claude/commands/training/model-update.md +25 -0
- package/.claude/commands/training/neural-patterns.md +108 -0
- package/.claude/commands/training/neural-train.md +75 -0
- package/.claude/commands/training/pattern-learn.md +25 -0
- package/.claude/commands/training/specialization.md +63 -0
- package/.claude/commands/truth/start.md +143 -0
- package/.claude/commands/verify/check.md +50 -0
- package/.claude/commands/verify/start.md +128 -0
- package/.claude/helpers/v3/advisor-call.cjs +283 -0
- package/.claude/hooks/aqe-hook.cjs +24 -3
- package/.claude/skills/README.md +54 -64
- package/.claude/skills/dual-mode/README.md +71 -0
- package/.claude/skills/dual-mode/dual-collect.md +103 -0
- package/.claude/skills/dual-mode/dual-coordinate.md +85 -0
- package/.claude/skills/dual-mode/dual-spawn.md +81 -0
- package/.claude/skills/qe-court/SKILL.md +25 -3
- package/.claude/skills/qe-court/config.json +1 -1
- package/.claude/skills/skills-manifest.json +1 -1
- package/.codex/hooks/aqe-codex-hook.cjs +34 -9
- package/.codex/hooks.json +9 -9
- package/CHANGELOG.md +85 -0
- package/assets/skills/qe-court/SKILL.md +25 -3
- package/assets/skills/qe-court/config.json +1 -1
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-JISQ35YY.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-PZYYTKSS.js → agent-booster-wasm-PR3RQWXF.js} +2 -2
- package/dist/cli/chunks/{agent-handler-DNN7GXUN.js → agent-handler-J5EPFBSZ.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-LVCBBCQY.js → agent-memory-branch-CCHI6QAA.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-TVTNP76S.js +2 -0
- package/dist/cli/chunks/{arena-422HSTPE.js → arena-KMKBGSMY.js} +2 -2
- package/dist/cli/chunks/{arena-OCEOLMCH.js → arena-SI7IPVZ3.js} +4 -4
- package/dist/cli/chunks/{audit-5O45K34M.js → audit-ZDKR3HT6.js} +3 -3
- package/dist/cli/chunks/base-WBCYKM45.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-OVLAHTPU.js → better-sqlite3-FXJFG2WH.js} +2 -2
- package/dist/cli/chunks/{brain-handler-7VHXYN3P.js → brain-handler-MSYMTM5B.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-PZKOD6S6.js → branch-enumerator-FRAHCBTO.js} +2 -2
- package/dist/cli/chunks/{browser-M74UO4WJ.js → browser-4KHKVNYC.js} +2 -2
- package/dist/cli/chunks/browser-workflow-4JM3IWCS.js +2 -0
- package/dist/cli/chunks/{chunk-62D27BDO.js → chunk-26SNR2EK.js} +3 -3
- package/dist/cli/chunks/{chunk-NTKIDOIW.js → chunk-27FWRWOB.js} +2 -2
- package/dist/cli/chunks/{chunk-REBNPQI7.js → chunk-27REOPQK.js} +2 -2
- package/dist/cli/chunks/{chunk-73HALJY5.js → chunk-2Q73TQUQ.js} +1 -1
- package/dist/cli/chunks/{chunk-LG6UUM55.js → chunk-344CLTV7.js} +2 -2
- package/dist/cli/chunks/{chunk-LXYVWAFN.js → chunk-3RSF7POD.js} +2 -2
- package/dist/cli/chunks/{chunk-BO2RBAPF.js → chunk-44SYMJ4T.js} +2 -2
- package/dist/cli/chunks/{chunk-4SFOQSXU.js → chunk-4FP4PJ45.js} +2 -2
- package/dist/cli/chunks/{chunk-T726SRYP.js → chunk-4HVVVVUF.js} +2 -2
- package/dist/cli/chunks/{chunk-NIE3SGZM.js → chunk-55E62F4T.js} +1 -1
- package/dist/cli/chunks/{chunk-5AAG7JTB.js → chunk-56QR72EB.js} +2 -2
- package/dist/cli/chunks/{chunk-IV77BQ2R.js → chunk-5DESO7E4.js} +2 -2
- package/dist/cli/chunks/{chunk-RWHHOQIC.js → chunk-5IVXM3TE.js} +1 -1
- package/dist/cli/chunks/{chunk-ELVUERQW.js → chunk-5R26MAMK.js} +2 -2
- package/dist/cli/chunks/{chunk-RJYAUJDC.js → chunk-5RVWL2U3.js} +3 -3
- package/dist/cli/chunks/{chunk-7TCVVVFA.js → chunk-6BHRSGR7.js} +3 -3
- package/dist/cli/chunks/{chunk-PNQWEOE2.js → chunk-6CZUQA4G.js} +1 -1
- package/dist/cli/chunks/{chunk-JPPHM3I6.js → chunk-6GNVVQW3.js} +2 -2
- package/dist/cli/chunks/{chunk-HANBJ37Z.js → chunk-6VNUASTQ.js} +2 -2
- package/dist/cli/chunks/{chunk-PRQPUOSH.js → chunk-6XCULO27.js} +2 -2
- package/dist/cli/chunks/{chunk-24S5IUSI.js → chunk-6XVP6BGM.js} +2 -2
- package/dist/cli/chunks/{chunk-LZNJ7HXB.js → chunk-75CFWCQV.js} +2 -2
- package/dist/cli/chunks/{chunk-HANJESCY.js → chunk-7EL5QEMJ.js} +2 -2
- package/dist/cli/chunks/{chunk-COOMXCCP.js → chunk-7YAHECC5.js} +2 -2
- package/dist/cli/chunks/{chunk-Q45FBGVV.js → chunk-A2G26WU4.js} +1 -1
- package/dist/cli/chunks/{chunk-A2OD5Z4B.js → chunk-AROPZPNG.js} +1 -1
- package/dist/cli/chunks/{chunk-4PM5VORA.js → chunk-BQRCNRTJ.js} +2 -2
- package/dist/cli/chunks/{chunk-XZOTFJHU.js → chunk-C3AF5Z55.js} +2 -2
- package/dist/cli/chunks/{chunk-SOOI2HJB.js → chunk-C75V5PTW.js} +1 -1
- package/dist/cli/chunks/{chunk-EU7NUUL6.js → chunk-CQP6BDSF.js} +1 -1
- package/dist/cli/chunks/{chunk-MBTVAIFF.js → chunk-CTNDSP2M.js} +1 -1
- package/dist/cli/chunks/{chunk-AP2BBV2D.js → chunk-CW7LDLJ2.js} +2 -2
- package/dist/cli/chunks/{chunk-ZY5FB3JV.js → chunk-DQ247474.js} +2 -2
- package/dist/cli/chunks/{chunk-BSQ32ZS5.js → chunk-E7FCVH32.js} +2 -2
- package/dist/cli/chunks/{chunk-4FYTWD4Q.js → chunk-EEHEMDNV.js} +2 -2
- package/dist/cli/chunks/{chunk-54BCLRRJ.js → chunk-EPSF2ERW.js} +2 -2
- package/dist/cli/chunks/{chunk-GZ775E5O.js → chunk-ERKYIV25.js} +2 -2
- package/dist/cli/chunks/{chunk-4DKL4H5L.js → chunk-ESMSH7HG.js} +2 -2
- package/dist/cli/chunks/{chunk-NNIKJZA4.js → chunk-EUIUWZF4.js} +3 -3
- package/dist/cli/chunks/{chunk-M4JZOCV3.js → chunk-FBXWU37F.js} +1 -1
- package/dist/cli/chunks/{chunk-K47EWX3M.js → chunk-FJSL7TWU.js} +1 -1
- package/dist/cli/chunks/{chunk-MVJ5UQI3.js → chunk-FZ4MUDHZ.js} +1 -1
- package/dist/cli/chunks/{chunk-AJ7A52GF.js → chunk-GGZB2ZBB.js} +1 -1
- package/dist/cli/chunks/{chunk-FFMUTX26.js → chunk-GIU26D5G.js} +1 -1
- package/dist/cli/chunks/{chunk-RF2DMPX2.js → chunk-GNFKG2LX.js} +2 -2
- package/dist/cli/chunks/{chunk-FXXXLDB3.js → chunk-GOFP47XU.js} +1 -1
- package/dist/cli/chunks/{chunk-TLG56A27.js → chunk-GOHWEQEP.js} +2 -2
- package/dist/cli/chunks/{chunk-DL2HDULJ.js → chunk-GRMKN44A.js} +3 -3
- package/dist/cli/chunks/{chunk-VOYUCJLK.js → chunk-HGBVGEUE.js} +2 -2
- package/dist/cli/chunks/{chunk-RI2V2U2N.js → chunk-HGY62IYZ.js} +2 -2
- package/dist/cli/chunks/{chunk-FMYNKZ2S.js → chunk-HN2DD2DQ.js} +2 -2
- package/dist/cli/chunks/{chunk-QS6TI7NR.js → chunk-II2RP3MY.js} +2 -2
- package/dist/cli/chunks/{chunk-N4O2RWSL.js → chunk-IN5KRJSE.js} +1 -1
- package/dist/cli/chunks/{chunk-ZIT5VF43.js → chunk-ISGKDLZ7.js} +2 -2
- package/dist/cli/chunks/{chunk-VKU5BUUC.js → chunk-ITQCSIYG.js} +1 -1
- package/dist/cli/chunks/{chunk-T55XIENI.js → chunk-IU5SILCS.js} +2 -2
- package/dist/cli/chunks/{chunk-4HFNY3Z2.js → chunk-IUFNB6I6.js} +2 -2
- package/dist/cli/chunks/{chunk-F6UMLI5Y.js → chunk-IVZA5XTW.js} +2 -2
- package/dist/cli/chunks/{chunk-4STE6VLR.js → chunk-JBHGMLN7.js} +10 -10
- package/dist/cli/chunks/{chunk-5GGGZYFA.js → chunk-JDADACZZ.js} +1 -1
- package/dist/cli/chunks/{chunk-WMK2ZNLM.js → chunk-JJ5YIKTJ.js} +3 -3
- package/dist/cli/chunks/{chunk-JDRYENTD.js → chunk-KB4S7MGB.js} +2 -2
- package/dist/cli/chunks/{chunk-IIZ3HBPV.js → chunk-KDICUKYX.js} +2 -2
- package/dist/cli/chunks/{chunk-HD6PZHLC.js → chunk-KE656E6T.js} +3 -3
- package/dist/cli/chunks/{chunk-KKPWS3XJ.js → chunk-KO3UQYGY.js} +10 -10
- package/dist/cli/chunks/{chunk-NBRKZOPM.js → chunk-KQLJILCZ.js} +1 -1
- package/dist/cli/chunks/{chunk-UPGJZA3D.js → chunk-KZAVYHH7.js} +4 -4
- package/dist/cli/chunks/{chunk-YTHUTBBH.js → chunk-L3UTZEVW.js} +2 -2
- package/dist/cli/chunks/{chunk-6XHDH3IJ.js → chunk-LASZCR5G.js} +2 -2
- package/dist/cli/chunks/{chunk-E6PYV3DB.js → chunk-LEIG3KIG.js} +2 -2
- package/dist/cli/chunks/{chunk-HHUKHEW5.js → chunk-LIMFWEUI.js} +2 -2
- package/dist/cli/chunks/{chunk-GHJRLC3C.js → chunk-LJSHQU2P.js} +5 -5
- package/dist/cli/chunks/{chunk-QVD3LU27.js → chunk-LUAYTM77.js} +1 -1
- package/dist/cli/chunks/{chunk-6R7TX5L4.js → chunk-MANWLRAW.js} +1 -1
- package/dist/cli/chunks/{chunk-MNDPSIEI.js → chunk-MP3RCZ75.js} +1 -1
- package/dist/cli/chunks/{chunk-TVWX7NYD.js → chunk-MPVOZKUP.js} +1 -1
- package/dist/cli/chunks/{chunk-WTSVP6OK.js → chunk-MWWTYPFL.js} +2 -2
- package/dist/cli/chunks/{chunk-PILZKQX7.js → chunk-N57M7UPQ.js} +2 -2
- package/dist/cli/chunks/{chunk-KHVW6DQS.js → chunk-N7LIYK7Z.js} +1 -1
- package/dist/cli/chunks/{chunk-GMKJWOXZ.js → chunk-NAAPL2HK.js} +1 -1
- package/dist/cli/chunks/{chunk-H6C2YTPX.js → chunk-NAZFAGJ5.js} +2 -2
- package/dist/cli/chunks/{chunk-JMRUHQEL.js → chunk-NQJLUY2K.js} +2 -2
- package/dist/cli/chunks/{chunk-XXQLFPIK.js → chunk-NQVF4M7L.js} +1 -1
- package/dist/cli/chunks/{chunk-AS2HVJ42.js → chunk-NW4YPUPN.js} +3 -3
- package/dist/cli/chunks/{chunk-LEOSNZR2.js → chunk-O45CEMVF.js} +1 -1
- package/dist/cli/chunks/{chunk-FZEWEG6Q.js → chunk-O74V7MB4.js} +2 -2
- package/dist/cli/chunks/{chunk-EFHMS7TJ.js → chunk-OF7674H5.js} +2 -2
- package/dist/cli/chunks/{chunk-5EFNZEOB.js → chunk-OR2RC7ZH.js} +2 -2
- package/dist/cli/chunks/{chunk-2DG44UZ5.js → chunk-OU2YHXJY.js} +2 -2
- package/dist/cli/chunks/{chunk-DAHNHVND.js → chunk-OU3SYEYJ.js} +1 -1
- package/dist/cli/chunks/{chunk-ASIGTVFQ.js → chunk-PD2ZSCEH.js} +1 -1
- package/dist/cli/chunks/{chunk-QZACODX6.js → chunk-PFQLB4XP.js} +2 -2
- package/dist/cli/chunks/{chunk-J722Z7VO.js → chunk-PI55PHUL.js} +2 -2
- package/dist/cli/chunks/{chunk-CLBBFKXV.js → chunk-PIYDPOW6.js} +2 -2
- package/dist/cli/chunks/{chunk-MUSLUG6Y.js → chunk-PJFQGNRW.js} +1 -1
- package/dist/cli/chunks/{chunk-OYWZYG6Q.js → chunk-PRHLV6FS.js} +1 -1
- package/dist/cli/chunks/chunk-Q4VZXT6X.js +2 -0
- package/dist/cli/chunks/{chunk-5KMBZTDI.js → chunk-QENUKXPP.js} +2 -2
- package/dist/cli/chunks/chunk-QGH54HTH.js +2 -0
- package/dist/cli/chunks/chunk-QXF6EQFP.js +4 -0
- package/dist/cli/chunks/{chunk-E6JJ4ZRQ.js → chunk-RCRKCMN5.js} +1 -1
- package/dist/cli/chunks/{chunk-GKKD22CC.js → chunk-RKNKFLCQ.js} +2 -2
- package/dist/cli/chunks/{chunk-DCQQJLUY.js → chunk-RLZZTFEN.js} +2 -2
- package/dist/cli/chunks/{chunk-N2AGOQCL.js → chunk-RO4BYINM.js} +2 -2
- package/dist/cli/chunks/{chunk-YXTDCP6H.js → chunk-SFRYDGLF.js} +1 -1
- package/dist/cli/chunks/{chunk-DIPOFCBX.js → chunk-SJ26ZR75.js} +2 -2
- package/dist/cli/chunks/{chunk-FECBWGCA.js → chunk-SPTCNM45.js} +2 -2
- package/dist/cli/chunks/{chunk-GMKQJEKX.js → chunk-SQCACQUM.js} +2 -2
- package/dist/cli/chunks/{chunk-BFKXHXWW.js → chunk-TCYSMSBO.js} +2 -2
- package/dist/cli/chunks/{chunk-UIQVVS7K.js → chunk-TFFEB7XD.js} +2 -2
- package/dist/cli/chunks/{chunk-JKVUSXT4.js → chunk-TM6LLT4G.js} +3 -3
- package/dist/cli/chunks/{chunk-YWJ2GPD4.js → chunk-TO7FTPRV.js} +2 -2
- package/dist/cli/chunks/{chunk-ODE7Z667.js → chunk-U52IQFMP.js} +1 -1
- package/dist/cli/chunks/{chunk-G4LZ5SBC.js → chunk-UAEP2ZUQ.js} +2 -2
- package/dist/cli/chunks/{chunk-EABGQVTV.js → chunk-UNMWI4QU.js} +1 -1
- package/dist/cli/chunks/{chunk-P33EORZZ.js → chunk-UOO7P2AK.js} +2 -2
- package/dist/cli/chunks/{chunk-JPO4AC5Q.js → chunk-UQFMQOZB.js} +1 -1
- package/dist/cli/chunks/{chunk-YZUMCXH6.js → chunk-VDPQ7NVG.js} +1 -1
- package/dist/cli/chunks/{chunk-KRRGOJ6K.js → chunk-VLELNETG.js} +2 -2
- package/dist/cli/chunks/{chunk-Q625ISQI.js → chunk-VOAXVNO5.js} +4 -4
- package/dist/cli/chunks/{chunk-LJWIBYTR.js → chunk-VZO4V4R4.js} +2 -2
- package/dist/cli/chunks/{chunk-K3MNTU4O.js → chunk-W37WY3OL.js} +2 -2
- package/dist/cli/chunks/{chunk-FJ2L6P7O.js → chunk-WCUXA3NV.js} +1 -1
- package/dist/cli/chunks/{chunk-B7KZMPF2.js → chunk-WSQE3VZB.js} +1 -1
- package/dist/cli/chunks/{chunk-PT6NTWGT.js → chunk-WUXCL65V.js} +2 -2
- package/dist/cli/chunks/{chunk-XS2S3ECA.js → chunk-X5JMTHXC.js} +3 -3
- package/dist/cli/chunks/{chunk-PJOH5Z5I.js → chunk-X67O2KUE.js} +2 -2
- package/dist/cli/chunks/{chunk-5XYVRTI6.js → chunk-XBSBVPSM.js} +2 -2
- package/dist/cli/chunks/{chunk-RWUK5VMZ.js → chunk-XEI5LLHX.js} +2 -2
- package/dist/cli/chunks/{chunk-LQDQTLWV.js → chunk-XF4F5ZXO.js} +2 -2
- package/dist/cli/chunks/{chunk-TTWWCWAR.js → chunk-XLP44YGX.js} +2 -2
- package/dist/cli/chunks/{chunk-HQCJYUKC.js → chunk-XTHRSBMJ.js} +2 -2
- package/dist/cli/chunks/{chunk-KAHMXURL.js → chunk-Y7VWCP35.js} +1 -1
- package/dist/cli/chunks/{chunk-UVLWT6QM.js → chunk-YQI6SOUO.js} +1 -1
- package/dist/cli/chunks/{chunk-DQXSDWRP.js → chunk-YZGA4ELM.js} +2 -2
- package/dist/cli/chunks/{chunk-CKTFKA7Q.js → chunk-Z6FK7T7J.js} +2 -2
- package/dist/cli/chunks/{chunk-T2XXTEZV.js → chunk-Z7FVGJYC.js} +2 -2
- package/dist/cli/chunks/{chunk-U2FCUBBW.js → chunk-ZAT65V6I.js} +2 -2
- package/dist/cli/chunks/{chunk-2QJPAQE5.js → chunk-ZYCPTARG.js} +2 -2
- package/dist/cli/chunks/{ci-EOFZKCSH.js → ci-DK4FGREO.js} +2 -2
- package/dist/cli/chunks/{ci-output-TAJFQWDP.js → ci-output-HQBBQQES.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-QA7YJ3IF.js → circuit-breaker-MJCS46DN.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-4RNAIALK.js → claude-flow-setup-IIQT52H4.js} +2 -2
- package/dist/cli/chunks/client-FNDZB4TY.js +2 -0
- package/dist/cli/chunks/{cline-installer-K25NUUA4.js → cline-installer-7SPKUNNZ.js} +2 -2
- package/dist/cli/chunks/{code-JM4D3I2W.js → code-V2B4FP3X.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-6B6TJ2B5.js → code-index-extractor-IRGAI76Y.js} +2 -2
- package/dist/cli/chunks/codex-installer-PDFCYRU6.js +15 -0
- package/dist/cli/chunks/{completions-LADTXGCC.js → completions-TAJ6N7YZ.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-IQITOJH5.js → complexity-analyzer-JHQKQKBG.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-H6NAXFZK.js → continuedev-installer-DESZXCLC.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-W7HCQKOS.js → copilot-installer-OQPXBLWS.js} +2 -2
- package/dist/cli/chunks/core-handlers-S37RHLKP.js +2 -0
- package/dist/cli/chunks/{cost-tracker-MC7KEENQ.js → cost-tracker-KHDFSCAJ.js} +2 -2
- package/dist/cli/chunks/{coverage-NOOKPFYQ.js → coverage-T7EENIDE.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-7ZHDB2V3.js +2 -0
- package/dist/cli/chunks/{cursor-installer-GOZ64GZJ.js → cursor-installer-X6BFU5QU.js} +2 -2
- package/dist/cli/chunks/{daemon-G4ABQMFJ.js → daemon-22NOG5XI.js} +3 -3
- package/dist/cli/chunks/{daemon-V23WTCJJ.js → daemon-UTPP4JCG.js} +4 -4
- package/dist/cli/chunks/{dag-attention-scheduler-YKOO6ZWL.js → dag-attention-scheduler-XI6DG3FW.js} +2 -2
- package/dist/cli/chunks/{detect-SNEMKQGJ.js → detect-7IMQGJ5I.js} +2 -2
- package/dist/cli/chunks/{dist-node-VBNEM6K6.js → dist-node-YMLM4K7J.js} +2 -2
- package/dist/cli/chunks/{domain-handler-2G5XEERC.js → domain-handler-LRTJGTEH.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-HSEUUM7E.js → domain-transfer-HZJ3WUCT.js} +2 -2
- package/dist/cli/chunks/dream-BEVYNIOO.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-H6MU5HK4.js → embed-and-insert-pattern-QSRN7Z5Q.js} +2 -2
- package/dist/cli/chunks/{eval-XYVDJXJF.js → eval-JVVVQVV6.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-BZQJVXTE.js → experience-capture-middleware-ORZN3ROJ.js} +3 -3
- package/dist/cli/chunks/{fast-paths-76WWBJ4H.js → fast-paths-LUFARZR5.js} +2 -2
- package/dist/cli/chunks/{feature-flags-7E5YZ4P5.js → feature-flags-2XC4ECLW.js} +2 -2
- package/dist/cli/chunks/{feature-flags-SCQ35J6M.js → feature-flags-ZHQESXIP.js} +2 -2
- package/dist/cli/chunks/{file-discovery-LU5MAXWA.js → file-discovery-UHXZQ7GS.js} +2 -2
- package/dist/cli/chunks/{fleet-M3TH65SV.js → fleet-FUQ6G4SB.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-OYUJEJD2.js → gnn-wrapper-A4E6OKGD.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-II4NSOXK.js → heartbeat-handler-3JKQORXA.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-K4YLB3X4.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-PPR3LTMA.js +2 -0
- package/dist/cli/chunks/hnsw-index-ZSKFT4LZ.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-322R2UAB.js → hnsw-legacy-bridge-AHKFKM2J.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-Y36THYK2.js → hnswlib-node-BP5CZGMD.js} +2 -2
- package/dist/cli/chunks/{hooks-2A27XCUJ.js → hooks-JNW5ZB2E.js} +10 -10
- package/dist/cli/chunks/hybrid-router-4SXBHTOY.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-ERA527UR.js → hypergraph-engine-3DTAMNSJ.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-7XL4OL6W.js → hypergraph-handler-ZV4AZRGF.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-55GE7EQD.js +2 -0
- package/dist/cli/chunks/{init-handler-WN6KQ5WY.js → init-handler-NPOUX47N.js} +10 -6
- package/dist/cli/chunks/init-wizard-EUQLSGI6.js +2 -0
- package/dist/cli/chunks/kernel-BSGSVYPM.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-5UCCFZ7V.js → kilocode-installer-D35TR6LG.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-77DPEP3K.js → kiro-installer-OHHTQENO.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-OITIVT5J.js +2 -0
- package/dist/cli/chunks/{learning-A5GKUD73.js → learning-24PCHLWU.js} +3 -3
- package/dist/cli/chunks/{llm-router-SINJNEGP.js → llm-router-XLTE52H5.js} +4 -4
- package/dist/cli/chunks/llm-router-service-RUPU52AR.js +2 -0
- package/dist/cli/chunks/{load-Q56GLXHJ.js → load-BHMK4FIL.js} +2 -2
- package/dist/cli/chunks/load-test-ZV3C55ZE.js +2 -0
- package/dist/cli/chunks/{mcp-VBDU2WLY.js → mcp-V4MAYT7C.js} +2 -2
- package/dist/cli/chunks/{memory-IGWBRDIT.js → memory-PDA7MQ7E.js} +5 -5
- package/dist/cli/chunks/memory-backend-S3KCPHCF.js +2 -0
- package/dist/cli/chunks/{memory-handlers-IITHQ7KV.js → memory-handlers-X5BLXOSH.js} +2 -2
- package/dist/cli/chunks/{multi-model-executor-2QUEY4CC.js → multi-model-executor-KECHOXKD.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-FZJ5N2B3.js → opencode-installer-LWSCQOOZ.js} +2 -2
- package/dist/cli/chunks/{orchestrator-BGLDS47V.js → orchestrator-ENEBTEUW.js} +6 -6
- package/dist/cli/chunks/pattern-null-store-ILVDKSCX.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-4MFN4WKV.js → pattern-usage-recorder-XIHGXYZZ.js} +2 -2
- package/dist/cli/chunks/{pipeline-GZHAORGP.js → pipeline-GQOJM3LU.js} +2 -2
- package/dist/cli/chunks/platform-L56TGXGZ.js +2 -0
- package/dist/cli/chunks/{plugin-VEYUFCNY.js → plugin-SZ6PZKYX.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-OA5DLXJJ.js → prime-radiant-advanced-wasm-SID5FQFW.js} +2 -2
- package/dist/cli/chunks/protocol-executor-GDRHCW3Q.js +2 -0
- package/dist/cli/chunks/{protocol-handler-MVJ5N4X5.js → protocol-handler-5MMNVVPX.js} +2 -2
- package/dist/cli/chunks/{prove-VKF7YCUA.js → prove-DJ6BQ2AK.js} +2 -2
- package/dist/cli/chunks/provider-manager-BS4MVCSH.js +2 -0
- package/dist/cli/chunks/qe-reasoning-bank-P3ARGHDN.js +2 -0
- package/dist/cli/chunks/{quality-NLB5LVGM.js → quality-WKC4JCB3.js} +2 -2
- package/dist/cli/chunks/{quality-gate-OM6A7FQM.js → quality-gate-CVHVSORK.js} +3 -3
- package/dist/cli/chunks/queen-coordinator-GI7GNVDM.js +2 -0
- package/dist/cli/chunks/{real-embeddings-NONEKGAV.js → real-embeddings-DN2MEJVM.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-ORXQQO3F.js → roocode-installer-LTAQJWIH.js} +2 -2
- package/dist/cli/chunks/router-YU6MLJBV.js +2 -0
- package/dist/cli/chunks/routing-feedback-D6B2SK5V.js +2 -0
- package/dist/cli/chunks/{routing-handler-LGMIBVDS.js → routing-handler-PSWR2UCT.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-4GZMU4BZ.js → ruvector-commands-VTP6Y7PN.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-45HKI22F.js → rvf-dual-writer-EBUMXPRO.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-RHYIXI3I.js → rvf-migration-adapter-5N7GHMD3.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-ANTAYKNN.js → rvf-migration-coordinator-GQKDBNRR.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-M7ZVRN5Z.js +2 -0
- package/dist/cli/chunks/{rvf-store-integrity-CPQUTFST.js → rvf-store-integrity-LR3SYGQK.js} +2 -2
- package/dist/cli/chunks/safe-db-3OHTLXG7.js +2 -0
- package/dist/cli/chunks/schedule-H43ADREQ.js +2 -0
- package/dist/cli/chunks/scheduler-CGSXNEPJ.js +2 -0
- package/dist/cli/chunks/{security-BM6LMCBI.js → security-YDWLYXYD.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-3HGARKJX.js → shared-rvf-adapter-I3HQY7DE.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-UQ4O46ZI.js → shared-rvf-dual-writer-2UADEA5N.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-V6U5FKVK.js +2 -0
- package/dist/cli/chunks/{status-handler-TGRAM5PC.js → status-handler-QRHI3F4V.js} +2 -2
- package/dist/cli/chunks/{structural-health-RXETMBB3.js → structural-health-FWKE63CM.js} +2 -2
- package/dist/cli/chunks/{sync-JTBZIACA.js → sync-2QRCT5MT.js} +2 -2
- package/dist/cli/chunks/{sync-B4KEYFCP.js → sync-E32MBAOF.js} +2 -2
- package/dist/cli/chunks/{task-handler-D7VXHWPG.js → task-handler-C7BKMOCL.js} +2 -2
- package/dist/cli/chunks/{task-handlers-XF6VVPTR.js → task-handlers-PADWLLDO.js} +3 -3
- package/dist/cli/chunks/{test-BKEIMBSX.js → test-KX4UKHSX.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-A4OHR7KW.js → test-scheduling-5WKIWH4H.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-LIDDAOAK.js → token-bootstrap-6SKOJM3U.js} +2 -2
- package/dist/cli/chunks/{token-usage-BJUFIU4V.js → token-usage-V6JW55RV.js} +2 -2
- package/dist/cli/chunks/{transformers-YYUQCGMV.js → transformers-3UPFBYSB.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-DFXYTJ23.js → tree-sitter-wasm-parser-UCY4S2DU.js} +2 -2
- package/dist/cli/chunks/{types-Z75HK5HH.js → types-XNMNQGET.js} +2 -2
- package/dist/cli/chunks/unified-memory-H2J5BHPY.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-LFGIWMTS.js +2 -0
- package/dist/cli/chunks/unified-persistence-F6W7EXU5.js +2 -0
- package/dist/cli/chunks/{upgrade-NETNZZH3.js → upgrade-MVTMTOPL.js} +2 -2
- package/dist/cli/chunks/{validate-U2WQ7P6T.js → validate-OJWR2AGZ.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-DKD7H2E3.js → validate-swarm-2RGSF2K2.js} +2 -2
- package/dist/cli/chunks/{vibium-FOQ73JBW.js → vibium-O3ZLAEEZ.js} +2 -2
- package/dist/cli/chunks/visual-security-EHVU32UE.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-PQXWMQO6.js → web-tree-sitter-6VPASTI4.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-CTFSFOBX.js → windsurf-installer-CINHOW3N.js} +2 -2
- package/dist/cli/chunks/{witness-chain-NCRHNFQM.js → witness-chain-2NXW7FT7.js} +2 -2
- package/dist/cli/chunks/witness-chain-BIICGRHC.js +2 -0
- package/dist/cli/chunks/{witness-key-manager-WGCSSB23.js → witness-key-manager-ODW4DJWT.js} +2 -2
- package/dist/cli/chunks/{workflow-FE5QGP2U.js → workflow-BFGS2GAU.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-PVTYPYY4.js +2 -0
- package/dist/cli/chunks/{wrappers-AHL5K2LO.js → wrappers-VEVVSVMS.js} +2 -2
- package/dist/cli/commands/platform.d.ts +17 -0
- package/dist/cli/commands/platform.js +91 -41
- package/dist/cli/handlers/init-handler.d.ts +1 -0
- package/dist/cli/handlers/init-handler.js +9 -3
- package/dist/init/codex-installer.d.ts +22 -3
- package/dist/init/codex-installer.js +132 -54
- package/dist/init/codex-skill-manifest.d.ts +43 -0
- package/dist/init/codex-skill-manifest.js +21 -0
- package/dist/init/orchestrator.js +1 -0
- package/dist/init/phases/09-assets.js +10 -1
- package/dist/init/phases/phase-interface.d.ts +2 -0
- package/dist/mcp/bundle.js +204 -202
- package/dist/shared/safe-db.js +60 -1
- package/dist/skills/qe-court/referee.d.ts +44 -0
- package/dist/skills/qe-court/referee.js +31 -2
- package/package.json +5 -1
- package/dist/cli/chunks/adapter-I4SNWMCM.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-WI47XKXI.js +0 -2
- package/dist/cli/chunks/base-VJ6VDLD7.js +0 -2
- package/dist/cli/chunks/browser-workflow-WRYHQQDU.js +0 -2
- package/dist/cli/chunks/chunk-6DMB6WK5.js +0 -2
- package/dist/cli/chunks/chunk-6UGYFYS4.js +0 -2
- package/dist/cli/chunks/client-N2WAM5IK.js +0 -2
- package/dist/cli/chunks/codex-installer-GRUENCIO.js +0 -10
- package/dist/cli/chunks/core-handlers-VSX474R3.js +0 -2
- package/dist/cli/chunks/cross-domain-router-VNE7QKX4.js +0 -2
- package/dist/cli/chunks/dream-A5LVJU7T.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-CFZ6DNQY.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-I4Y2T4HO.js +0 -2
- package/dist/cli/chunks/hnsw-index-SBR5VYGN.js +0 -2
- package/dist/cli/chunks/hybrid-router-E6YM74NQ.js +0 -2
- package/dist/cli/chunks/impact-analyzer-GHYFSSMJ.js +0 -2
- package/dist/cli/chunks/init-wizard-KAN5KOGD.js +0 -2
- package/dist/cli/chunks/kernel-LET4HEEF.js +0 -2
- package/dist/cli/chunks/knowledge-graph-P3UJWNQS.js +0 -2
- package/dist/cli/chunks/llm-router-service-BOBENURJ.js +0 -2
- package/dist/cli/chunks/load-test-4VDCVB7S.js +0 -2
- package/dist/cli/chunks/memory-backend-RRFAYQYS.js +0 -2
- package/dist/cli/chunks/pattern-null-store-V7DEZEF2.js +0 -2
- package/dist/cli/chunks/platform-TZEX4YZQ.js +0 -2
- package/dist/cli/chunks/protocol-executor-I3C2ZETP.js +0 -2
- package/dist/cli/chunks/provider-manager-HB4YVQDI.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-RDLBAXJY.js +0 -2
- package/dist/cli/chunks/queen-coordinator-QRWRNUDR.js +0 -2
- package/dist/cli/chunks/router-WDF7KV4M.js +0 -2
- package/dist/cli/chunks/routing-feedback-DHYB4ZNL.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-7W53TYTH.js +0 -2
- package/dist/cli/chunks/safe-db-4HBFO7OQ.js +0 -2
- package/dist/cli/chunks/schedule-M2OSBJZM.js +0 -2
- package/dist/cli/chunks/scheduler-JWV5MSGE.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-QA4JRQZ2.js +0 -2
- package/dist/cli/chunks/unified-memory-BEUZQTTC.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-FHLSAEX4.js +0 -2
- package/dist/cli/chunks/unified-persistence-TVEQGCSB.js +0 -2
- package/dist/cli/chunks/visual-security-AYV46OUO.js +0 -2
- package/dist/cli/chunks/witness-chain-RU356H6R.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-N2DQTC3X.js +0 -2
- package/dist/cli/commands/init.d.ts +0 -19
- package/dist/cli/commands/init.js +0 -318
|
@@ -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.13.
|
|
2
|
-
import{b as pe}from"./chunk-YXTDCP6H.js";import{a as dt}from"./chunk-QVD3LU27.js";import{a as mt,b as gt}from"./chunk-RWUK5VMZ.js";import{j as I}from"./chunk-5XYVRTI6.js";import{a as lt,b as ut}from"./chunk-T726SRYP.js";import{a as nt}from"./chunk-KHVW6DQS.js";import{a as at,b as ot,c as ct}from"./chunk-GKKD22CC.js";import{b as st}from"./chunk-6R7TX5L4.js";import{a as ge}from"./chunk-FJ2L6P7O.js";import{i as w,m as me}from"./chunk-U2FCUBBW.js";import{a as an}from"./chunk-6UGYFYS4.js";import{c as it}from"./chunk-BSQ32ZS5.js";import{b as M,d as rt}from"./chunk-FMYNKZ2S.js";import{a as v,b,c as y}from"./chunk-E6JJ4ZRQ.js";import{a as h,b as tt,c as k}from"./chunk-IIZ3HBPV.js";import{i as T}from"./chunk-SOOI2HJB.js";import{R as on,S as cn}from"./chunk-GZ775E5O.js";import{c as z,e as sn,g as et}from"./chunk-AJ7A52GF.js";function ft(a){let e=[],t=0;if(a.fileCount!==void 0&&(a.fileCount>20?(t+=25,e.push({name:"very-high-file-count",weight:25,description:`Task involves ${a.fileCount} files (>20)`})):a.fileCount>10?(t+=20,e.push({name:"high-file-count",weight:20,description:`Task involves ${a.fileCount} files (>10)`})):a.fileCount>5&&(t+=10,e.push({name:"moderate-file-count",weight:10,description:`Task involves ${a.fileCount} files (>5)`}))),a.domain&&(dn.includes(a.domain)?(t+=30,e.push({name:"complex-domain",weight:30,description:`Domain '${a.domain}' requires complex reasoning`})):mn.includes(a.domain)&&(t+=15,e.push({name:"moderate-domain",weight:15,description:`Domain '${a.domain}' has moderate complexity`}))),a.crossComponent&&(t+=25,e.push({name:"cross-component",weight:25,description:"Task spans multiple components/modules"})),a.priority==="critical"?(t+=25,e.push({name:"critical-priority",weight:25,description:"Critical priority requires careful attention"})):a.priority==="high"&&(t+=15,e.push({name:"high-priority",weight:15,description:"High priority task"})),a.requiredCapabilities){let r=a.requiredCapabilities.filter(s=>gn.includes(s)).length;if(r>0){let s=Math.min(20,r*10);t+=s,e.push({name:"complex-capabilities",weight:s,description:`Requires ${r} complex capabilit${r===1?"y":"ies"}`})}}a.requiresExternalApis&&(t+=10,e.push({name:"external-apis",weight:10,description:"Requires external API integration"})),a.involvesDatabaseOps&&(t+=10,e.push({name:"database-ops",weight:10,description:"Involves database operations"})),a.timeSensitive&&(t+=5,e.push({name:"time-sensitive",weight:5,description:"Time-sensitive task"})),a.estimatedLinesAffected!==void 0&&(a.estimatedLinesAffected>500?(t+=15,e.push({name:"large-change",weight:15,description:`Estimated ${a.estimatedLinesAffected} lines affected (>500)`})):a.estimatedLinesAffected>200&&(t+=10,e.push({name:"medium-change",weight:10,description:`Estimated ${a.estimatedLinesAffected} lines affected (>200)`}))),(a.type==="security-scan"||a.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=pn[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var dn,mn,gn,S,pn,yt=z(()=>{"use strict";dn=["security-compliance","chaos-resilience","defect-intelligence"],mn=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],gn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},pn={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var R,Te=z(()=>{"use strict";R=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 s=Math.random(),o=Math.random(),l=Math.sqrt(-2*Math.log(Math.max(s,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 s=0;s<4;s++)r+=e[s]*this.weightsInputHidden[s*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 s=0;s<32;s++)r+=t[s]*this.weightsHiddenOutput[s*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 s=0;s<e.length;s++)n[s]=Math.exp(e[s]-t),i+=n[s];let r=[];for(let s=0;s<e.length;s++)r.push(n[s]/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 s=this.softmax(r),o=new Float32Array(3);for(let c=0;c<3;c++)o[c]=(c===t?1:0)-s[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 vt={};sn(vt,{NeuralTinyDancerRouter:()=>G,SimpleNeuralRouter:()=>R,createNeuralTinyDancerRouter:()=>Sn});import{performance as Tt}from"perf_hooks";function Sn(a){return new G(a)}var hn,fn,yn,Tn,vn,Cn,bn,kn,G,Ct=z(()=>{"use strict";ve();Te();Te();hn=1e3,fn=.1,yn=.2,Tn=50,vn=.01,Cn=["haiku","sonnet","opus"],bn={haiku:0,sonnet:1,opus:2},kn={"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},G=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 F(e),this.neuralNet=new R(e.learningRate??vn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??yn,this.shadowModeDecisionLimit=e.shadowModeDecisions??hn,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=Tt.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 s=this.argmax(r),o=Cn[s],l=r[s];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=Tt.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,s=(i+r)/4,o=Math.min(1,s/1e4),l=e.domain??"",c=kn[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,s=0){this.ruleRouter.recordOutcome(e,t,n,i,r,s);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>Tn&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let c=this.extractFeatures(e,t.classification),u=bn[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),f=1-m[u];this.calibrationScores.push(f),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),s=Math.ceil(.9*r.length)-1,o=r[Math.min(s,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 s=[];return s.push(`[Neural] Routing to ${e.toUpperCase()}`),s.push(`with ${(t*100).toFixed(0)}% neural confidence.`),s.push(`Tier probabilities: haiku=${(n[0]*100).toFixed(0)}%,`),s.push(`sonnet=${(n[1]*100).toFixed(0)}%,`),s.push(`opus=${(n[2]*100).toFixed(0)}%.`),e!==i.model&&s.push(`Rule-based would choose ${i.model.toUpperCase()}.`),s.push(`Empirical bounds: [${r.lower.toFixed(2)}, ${r.upper.toFixed(2)}]`),s.push(`at ${(r.coverageLevel*100).toFixed(0)}% coverage.`),s.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 bt}from"perf_hooks";function kt(a){try{let{getRuVectorFeatureFlags:e}=(cn(),et(on));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(Ct(),et(vt));return new n(a)}}catch(e){process.env.DEBUG&&console.debug("[Router] Neural router unavailable, using rule-based:",e instanceof Error?e.message:e)}return new F(a)}var F,ve=z(()=>{"use strict";yt();F=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=bt.now(),n=ft(e),i=this.calculateConfidence(n),r=1-i,s=this.isSecurityTask(e),o=s&&i<this.securityConfidenceThreshold||i<this.confidenceThreshold&&n.complexity!=="simple",l=r>this.uncertaintyThreshold||s&&n.complexity==="critical",c=bt.now()-t,u=this.buildReasoning(n,i,s,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 s=.55,o=.35,l=Math.min(r/25,1),c=s+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(s=>n.includes(s)))return!0;let i=["security","vulnerability","cve","owasp","exploit","injection"],r=e.description.toLowerCase();return!!i.some(s=>r.includes(s))}buildReasoning(e,t,n,i,r){let s=[];if(s.push(`Routing to ${e.recommendedModel.toUpperCase()}`),s.push(`(complexity: ${e.complexity}, score: ${e.score})`),s.push(`with ${(t*100).toFixed(0)}% confidence.`),e.factors.length>0){let o=e.factors.slice(0,3).map(l=>l.name).join(", ");s.push(`Key factors: ${o}.`)}return n&&s.push("Security-sensitive task detected."),i&&s.push("Multi-model verification recommended due to uncertainty."),r&&s.push("Human review flagged due to high uncertainty or criticality."),s.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,s=0){if(!this.enableLearning)return;let o={task:e,routeResult:t,success:n,qualityScore:i,actualModelUsed:r,durationMs:s,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}}}});var ln={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},q=class{entries=[];config;constructor(e={}){this.config={...ln,...e}}log(e,t,n){let i={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&&this.entries.splice(0,this.entries.length-this.config.maxEntries),this.config.enableConsoleLog){let r=n?.agentId?` by ${n.agentId}`:"",s=n?.domain?` (${n.domain})`:"";console.log(`${this.config.logPrefix} ${e.toUpperCase()} ${t}${r}${s}`)}}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 t.slice(-n)}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{totalEntries:this.entries.length,operationCounts:e,taskCount:t.size,agentCount:n.size}}clear(){this.entries.length=0}};function he(a){return new q(a)}me();rt();var fe=class{memory;initialized=!1;constructor(e){this.memory=e??w()}async initialize(){this.initialized||(this.memory.isInitialized()||await this.memory.initialize(),this.initialized=!0)}async saveSnapshot(e){this.ensureInitialized();let t=T();return this.memory.getDatabase().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.13.4");process.exit(0)}
|
|
2
|
+
import{b as pe}from"./chunk-SFRYDGLF.js";import{a as dt}from"./chunk-LUAYTM77.js";import{a as mt,b as gt}from"./chunk-XEI5LLHX.js";import{j as I}from"./chunk-XBSBVPSM.js";import{a as lt,b as ut}from"./chunk-4HVVVVUF.js";import{a as nt}from"./chunk-N7LIYK7Z.js";import{a as at,b as ot,c as ct}from"./chunk-RKNKFLCQ.js";import{b as st}from"./chunk-MANWLRAW.js";import{a as ge}from"./chunk-WCUXA3NV.js";import{i as w,m as me}from"./chunk-ZAT65V6I.js";import{a as an}from"./chunk-QGH54HTH.js";import{c as it}from"./chunk-E7FCVH32.js";import{b as M,d as rt}from"./chunk-HN2DD2DQ.js";import{a as v,b,c as y}from"./chunk-RCRKCMN5.js";import{a as h,b as tt,c as k}from"./chunk-KDICUKYX.js";import{i as T}from"./chunk-C75V5PTW.js";import{R as on,S as cn}from"./chunk-ERKYIV25.js";import{c as z,e as sn,g as et}from"./chunk-GGZB2ZBB.js";function ft(a){let e=[],t=0;if(a.fileCount!==void 0&&(a.fileCount>20?(t+=25,e.push({name:"very-high-file-count",weight:25,description:`Task involves ${a.fileCount} files (>20)`})):a.fileCount>10?(t+=20,e.push({name:"high-file-count",weight:20,description:`Task involves ${a.fileCount} files (>10)`})):a.fileCount>5&&(t+=10,e.push({name:"moderate-file-count",weight:10,description:`Task involves ${a.fileCount} files (>5)`}))),a.domain&&(dn.includes(a.domain)?(t+=30,e.push({name:"complex-domain",weight:30,description:`Domain '${a.domain}' requires complex reasoning`})):mn.includes(a.domain)&&(t+=15,e.push({name:"moderate-domain",weight:15,description:`Domain '${a.domain}' has moderate complexity`}))),a.crossComponent&&(t+=25,e.push({name:"cross-component",weight:25,description:"Task spans multiple components/modules"})),a.priority==="critical"?(t+=25,e.push({name:"critical-priority",weight:25,description:"Critical priority requires careful attention"})):a.priority==="high"&&(t+=15,e.push({name:"high-priority",weight:15,description:"High priority task"})),a.requiredCapabilities){let r=a.requiredCapabilities.filter(s=>gn.includes(s)).length;if(r>0){let s=Math.min(20,r*10);t+=s,e.push({name:"complex-capabilities",weight:s,description:`Requires ${r} complex capabilit${r===1?"y":"ies"}`})}}a.requiresExternalApis&&(t+=10,e.push({name:"external-apis",weight:10,description:"Requires external API integration"})),a.involvesDatabaseOps&&(t+=10,e.push({name:"database-ops",weight:10,description:"Involves database operations"})),a.timeSensitive&&(t+=5,e.push({name:"time-sensitive",weight:5,description:"Time-sensitive task"})),a.estimatedLinesAffected!==void 0&&(a.estimatedLinesAffected>500?(t+=15,e.push({name:"large-change",weight:15,description:`Estimated ${a.estimatedLinesAffected} lines affected (>500)`})):a.estimatedLinesAffected>200&&(t+=10,e.push({name:"medium-change",weight:10,description:`Estimated ${a.estimatedLinesAffected} lines affected (>200)`}))),(a.type==="security-scan"||a.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=pn[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var dn,mn,gn,S,pn,yt=z(()=>{"use strict";dn=["security-compliance","chaos-resilience","defect-intelligence"],mn=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],gn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},pn={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var R,Te=z(()=>{"use strict";R=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 s=Math.random(),o=Math.random(),l=Math.sqrt(-2*Math.log(Math.max(s,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 s=0;s<4;s++)r+=e[s]*this.weightsInputHidden[s*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 s=0;s<32;s++)r+=t[s]*this.weightsHiddenOutput[s*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 s=0;s<e.length;s++)n[s]=Math.exp(e[s]-t),i+=n[s];let r=[];for(let s=0;s<e.length;s++)r.push(n[s]/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 s=this.softmax(r),o=new Float32Array(3);for(let c=0;c<3;c++)o[c]=(c===t?1:0)-s[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 vt={};sn(vt,{NeuralTinyDancerRouter:()=>G,SimpleNeuralRouter:()=>R,createNeuralTinyDancerRouter:()=>Sn});import{performance as Tt}from"perf_hooks";function Sn(a){return new G(a)}var hn,fn,yn,Tn,vn,Cn,bn,kn,G,Ct=z(()=>{"use strict";ve();Te();Te();hn=1e3,fn=.1,yn=.2,Tn=50,vn=.01,Cn=["haiku","sonnet","opus"],bn={haiku:0,sonnet:1,opus:2},kn={"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},G=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 F(e),this.neuralNet=new R(e.learningRate??vn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??yn,this.shadowModeDecisionLimit=e.shadowModeDecisions??hn,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=Tt.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 s=this.argmax(r),o=Cn[s],l=r[s];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=Tt.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,s=(i+r)/4,o=Math.min(1,s/1e4),l=e.domain??"",c=kn[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,s=0){this.ruleRouter.recordOutcome(e,t,n,i,r,s);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>Tn&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let c=this.extractFeatures(e,t.classification),u=bn[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),f=1-m[u];this.calibrationScores.push(f),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),s=Math.ceil(.9*r.length)-1,o=r[Math.min(s,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 s=[];return s.push(`[Neural] Routing to ${e.toUpperCase()}`),s.push(`with ${(t*100).toFixed(0)}% neural confidence.`),s.push(`Tier probabilities: haiku=${(n[0]*100).toFixed(0)}%,`),s.push(`sonnet=${(n[1]*100).toFixed(0)}%,`),s.push(`opus=${(n[2]*100).toFixed(0)}%.`),e!==i.model&&s.push(`Rule-based would choose ${i.model.toUpperCase()}.`),s.push(`Empirical bounds: [${r.lower.toFixed(2)}, ${r.upper.toFixed(2)}]`),s.push(`at ${(r.coverageLevel*100).toFixed(0)}% coverage.`),s.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 bt}from"perf_hooks";function kt(a){try{let{getRuVectorFeatureFlags:e}=(cn(),et(on));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(Ct(),et(vt));return new n(a)}}catch(e){process.env.DEBUG&&console.debug("[Router] Neural router unavailable, using rule-based:",e instanceof Error?e.message:e)}return new F(a)}var F,ve=z(()=>{"use strict";yt();F=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=bt.now(),n=ft(e),i=this.calculateConfidence(n),r=1-i,s=this.isSecurityTask(e),o=s&&i<this.securityConfidenceThreshold||i<this.confidenceThreshold&&n.complexity!=="simple",l=r>this.uncertaintyThreshold||s&&n.complexity==="critical",c=bt.now()-t,u=this.buildReasoning(n,i,s,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 s=.55,o=.35,l=Math.min(r/25,1),c=s+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(s=>n.includes(s)))return!0;let i=["security","vulnerability","cve","owasp","exploit","injection"],r=e.description.toLowerCase();return!!i.some(s=>r.includes(s))}buildReasoning(e,t,n,i,r){let s=[];if(s.push(`Routing to ${e.recommendedModel.toUpperCase()}`),s.push(`(complexity: ${e.complexity}, score: ${e.score})`),s.push(`with ${(t*100).toFixed(0)}% confidence.`),e.factors.length>0){let o=e.factors.slice(0,3).map(l=>l.name).join(", ");s.push(`Key factors: ${o}.`)}return n&&s.push("Security-sensitive task detected."),i&&s.push("Multi-model verification recommended due to uncertainty."),r&&s.push("Human review flagged due to high uncertainty or criticality."),s.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,s=0){if(!this.enableLearning)return;let o={task:e,routeResult:t,success:n,qualityScore:i,actualModelUsed:r,durationMs:s,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}}}});var ln={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},q=class{entries=[];config;constructor(e={}){this.config={...ln,...e}}log(e,t,n){let i={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&&this.entries.splice(0,this.entries.length-this.config.maxEntries),this.config.enableConsoleLog){let r=n?.agentId?` by ${n.agentId}`:"",s=n?.domain?` (${n.domain})`:"";console.log(`${this.config.logPrefix} ${e.toUpperCase()} ${t}${r}${s}`)}}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 t.slice(-n)}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{totalEntries:this.entries.length,operationCounts:e,taskCount:t.size,agentCount:n.size}}clear(){this.entries.length=0}};function he(a){return new q(a)}me();rt();var fe=class{memory;initialized=!1;constructor(e){this.memory=e??w()}async initialize(){this.initialized||(this.memory.isInitialized()||await this.memory.initialize(),this.initialized=!0)}async saveSnapshot(e){this.ensureInitialized();let t=T();return this.memory.getDatabase().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 pe}from"./chunk-YXTDCP6H.js";import{a as dt}from"./chunk-QVD3LU27.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 pe(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,s]=n,o=this.getValueFromPath(t,i),l=isNaN(Number(s))?s:Number(s),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"&&i in n)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`)}},qe=null;function Gt(a){return qe||(qe=new Ge(a)),qe}function jt(a,e){let t=[];for(let s of e){let o=a.router.subscribeToDoamin(s,async l=>{await ai(a,l)});t.push(o)}let n=a.router.subscribeToEventType("TaskCompleted",async s=>{await oi(a,s)});t.push(n);let i=a.router.subscribeToEventType("TaskFailed",async s=>{await ci(a,s)});t.push(i);let r=a.router.subscribeToEventType("AgentStatusChanged",async s=>{await li(a,s)});return t.push(r),t}async function ai(a,e){a.domainLastActivity.set(e.source,new Date),await a.processQueue()}async function oi(a,e){let{taskId:t,result:n}=e.payload,i=a.tasks.get(t);if(i){(i.status==="running"||i.status==="assigned")&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1));let r=i.startedAt?Date.now()-i.startedAt.getTime():0;a.tasks.set(t,{...i,status:"completed",completedAt:new Date,result:n}),a.tasksCompleted++,a.taskDurations.push(r),a.auditLogger.logComplete(t,i.assignedAgents[0]);try{let s=Gt(),o=i.assignedAgents[0];o&&await s.onAgentComplete(o,{taskId:t,taskType:i.task.type,domain:i.assignedDomain,result:n,duration:r})}catch(s){console.warn("[QueenCoordinator] Cross-phase hook error:",s)}try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!0,0,0)}catch(s){console.warn("[QueenCoordinator] Governance tracking error:",s)}if(a.domainBreakerRegistry&&i.assignedDomain&&a.domainBreakerRegistry.getBreaker(i.assignedDomain).recordSuccess(),a.traceCollector){let s=a.taskTraceContexts.get(t);s&&(a.traceCollector.completeSpan(s.spanId),a.taskTraceContexts.delete(t))}if(a.taskCompletedHook)try{let s=typeof n=="object"&&n!==null?n:null;if(s===null)console.error(`[QueenCoordinator] Pattern training skipped for task ${t}: result is not an object (got ${typeof n})`);else{let o=ui(s,t);if(o){let l={taskId:t,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",type:i.task.type,status:"completed",output:s,metrics:o,duration:r,timestamp:Date.now()};a.taskCompletedHook.onTaskCompleted(l).catch(c=>{console.warn("[QueenCoordinator] Pattern training error:",c)})}}}catch(s){console.warn("[QueenCoordinator] Pattern training setup error:",s)}}await a.processQueue()}async function ci(a,e){let{taskId:t,error:n}=e.payload,i=a.tasks.get(t);if(i){if((i.status==="running"||i.status==="assigned")&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1)),a.domainBreakerRegistry&&i.assignedDomain&&a.domainBreakerRegistry.getBreaker(i.assignedDomain).recordFailure(new Error(n||"Task failed")),a.traceCollector){let r=a.taskTraceContexts.get(t);r&&(a.traceCollector.failSpan(r.spanId,n||"Task failed"),a.taskTraceContexts.delete(t))}if(i.retryCount<a.config.taskRetryLimit){a.auditLogger.logFail(t,i.assignedAgents[0],n);let r={...i,status:"queued",retryCount:i.retryCount+1,error:n};a.tasks.set(t,r),a.enqueueTask(i.task)}else{a.tasks.set(t,{...i,status:"failed",completedAt:new Date,error:n}),a.tasksFailed++,a.auditLogger.logFail(t,i.assignedAgents[0],n);try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!1,0,0)}catch(r){console.warn("[QueenCoordinator] Governance tracking error:",r)}if(a.hypothesisManager&&(i.task.priority==="p0"||i.task.priority==="p1"))try{let r=i.assignedDomain||"test-generation",s=a.hypothesisManager.createInvestigation(t,r,`Root cause analysis for ${i.task.type} failure: ${n}`);a.hypothesisManager.addHypothesis(s.id,`Infrastructure failure in domain '${r}' caused task ${t} to fail`,"log-analysis",`${r}-lead`),a.hypothesisManager.addHypothesis(s.id,`Logic/configuration error in task payload caused ${i.task.type} to fail: ${n}`,"code-analysis",i.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${s.id}`)}catch(r){console.warn("[QueenCoordinator] Hypothesis creation error:",r)}}}await a.processQueue()}async function li(a,e){let{agentId:t,status:n,domain:i}=e.payload;a.domainLastActivity.set(i,new Date),(n==="completed"||n==="failed")&&await a.processQueue()}function ui(a,e){if("metrics"in a&&typeof a.metrics=="object"&&a.metrics!==null){let t=a.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 a||"testsFailed"in a?{testsPassed:typeof a.testsPassed=="number"?a.testsPassed:void 0,testsFailed:typeof a.testsFailed=="number"?a.testsFailed:void 0,coverageChange:typeof a.coverageChange=="number"?a.coverageChange:void 0,securityIssues:typeof a.securityIssues=="number"?a.securityIssues:void 0,performanceMs:typeof a.performanceMs=="number"?a.performanceMs:void 0,linesChanged:typeof a.linesChanged=="number"?a.linesChanged:void 0}:(console.error(`[QueenCoordinator] Pattern training skipped for task ${e}: result object has no recognizable metrics shape (keys: ${Object.keys(a).join(", ")})`),null)}function Wt(a,e,t){let n=a.listAgents({domain:e}),i=n.filter(l=>l.status==="running").length,r=n.filter(l=>l.status==="idle").length,s=n.filter(l=>l.status==="failed").length,o;return s>0&&s>=n.length/2?o="unhealthy":s>0?o="degraded":i>0?o="healthy":o="idle",{status:o,agents:{total:n.length,active:i,idle:r,failed:s},lastActivity:t,errors:[]}}var di=ut();function Vt(a,e,t){let n=a.get(t.priority);n&<(n,t,di);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function de(a,e,t){let n=a.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 s=r.findIndex(o=>o.id===t.id);s!==-1&&r.splice(s,1)}}}function je(a,e){let t=0;for(let n of["p0","p1","p2","p3"]){let i=a.get(n);if(i){if(n===e.priority){t+=i.findIndex(r=>r.id===e.id);break}t+=i.length}}return t}async function We(a){if(!(a.runningTaskCounter>=a.config.maxConcurrentTasks))for(let e of["p0","p1","p2","p3"]){let t=a.taskQueue.get(e);if(!t||t.length===0)continue;let n=t.shift();if(n){de(a.taskQueue,a.domainQueues,n),a.runningTaskCounter++;try{await Ve(a,n)}catch(i){throw a.runningTaskCounter--,i}if(a.runningTaskCounter>=a.config.maxConcurrentTasks)return}}}function Kt(a,e){let t=Array.from(a.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 Ve(a,e){let t=e.targetDomains.length>0?e.targetDomains:P[e.type]||[];if(t.length===0)return y(new Error(`No domains configured for task type: ${e.type}`));let n,i=1/0;for(let r of t){let s=a.getDomainLoad(r);a.getDomainHealth(r)?.status!=="unhealthy"&&s<i&&(i=s,n=r)}return n?Ke(a,e,n):y(new Error("No healthy domain available for task"))}async function Ke(a,e,t){let n;if(a.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:c[e.priority]};n=await a.tinyDancerRouter.route(u),a.config.enableMetrics&&console.log(`[Queen] TinyDancer routing: ${e.type} \u2192 tier=${n.tier}, model=${n.model}, cost=$${n.estimatedCost.toFixed(4)}`)}if(a.domainBreakerRegistry&&!a.domainBreakerRegistry.canExecuteInDomain(t))return y(new Error(`Domain '${t}' circuit breaker is open \u2014 too many recent failures`));if(a.domainTeamManager)try{if(!a.domainTeamManager.getDomainTeam(t)){let u=`${t}-lead`;a.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"]:[]],s=await a.requestAgentSpawn(t,i,r),o=[];s.success&&o.push(s.value);let l={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:o,startedAt:new Date,retryCount:0};a.tasks.set(e.id,l),a.domainLastActivity.set(t,new Date);for(let c of o)a.auditLogger.logAssign(e.id,c,t);if(await a.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:o}),a.domainPlugins){let c=a.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=await c.executeTask(u,m=>mi(a,m));return d.success?b(e.id):(a.tasks.set(e.id,{...l,status:"failed",error:d.error.message,completedAt:new Date}),a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),a.tasksFailed++,a.auditLogger.logFail(e.id,o[0],d.error.message),y(d.error))}if(c)try{await c.handleEvent({id:T(),type:"TaskAssigned",timestamp:new Date,source:"queen-coordinator",correlationId:e.correlationId,payload:{task:e}}),console.warn(`[Queen] Domain ${t} has no executeTask handler, using event fallback`)}catch(u){console.warn(`[Queen] Failed to invoke domain ${t} event handler:`,u)}}return b(e.id)}async function mi(a,e){let t=a.tasks.get(e.taskId);if(!t){console.warn(`[Queen] Received completion for unknown task: ${e.taskId}`);return}let n={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(a.tasks.set(e.taskId,n),e.success?(a.tasksCompleted++,a.taskDurations.push(e.duration),a.auditLogger.logComplete(e.taskId,t.assignedAgents[0])):(a.tasksFailed++,a.auditLogger.logFail(e.taskId,t.assignedAgents[0],e.error||"Unknown error")),a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),a.coExecutionRepo&&t.assignedAgents.length>=2)try{a.coExecutionRepo.recordSwarmCoExecution(t.assignedAgents,t.assignedDomain||"unknown",e.success,t.task.type)}catch{}for(let i of t.assignedAgents)await a.agentCoordinator.stop(i);await a.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await We(a)}function Yt(a,e){return(P[e.type]||[]).includes(a)}k();async function Zt(a){let e=0,t=a.getIdleDomains(),n=a.getBusyDomains();if(t.length===0||n.length===0)return 0;n.sort((i,r)=>a.getDomainLoad(r)-a.getDomainLoad(i));for(let i of n){if(t.length===0)break;let r=a.domainQueues.get(i)||[],s=Math.min(r.length,a.config.workStealing.stealBatchSize);for(let o=0;o<s&&t.length>0;o++){let l=r.find(c=>Yt(t[0],c));if(l){let c=t.shift();a.removeFromQueues(l),a.auditLogger.logSteal(l.id,i,c),await a.assignTaskToDomain(l,c),e++,a.tasksStolen++,await a.publishEvent("TaskStolen",{taskId:l.id,fromDomain:i,toDomain:c})}}}return e}function Ye(a,e){let t=0,n=10,i=setInterval(async()=>{try{await e(),t=0}catch(r){t++;let s=Math.min(1e3*Math.pow(2,t),3e4);if(console.warn(`[QueenCoordinator] Work-stealing failed (attempt ${t}), backing off ${s}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,s))}},a.workStealing.checkInterval);return i}function Ze(a){return typeof a.setMinCutBridge=="function"}function Xt(a,e){for(let[t,n]of a)Ze(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function Jt(a,e,t){try{let n=await a.get("queen:state");if(n)for(let[i,r]of n.tasks)r.status==="queued"&&(e.set(i,r),t(r.task))}catch(n){console.debug("[QueenCoordinator] State loading failed:",n instanceof Error?n.message:n)}}async function en(a,e){let t=Array.from(e.entries()).filter(([,n])=>n.status==="queued");await a.set("queen:state",{tasks:t},{namespace:"queen-coordinator",persist:!0})}function tn(a){return setInterval(async()=>{let e=a.getMetrics();if(await a.publishEvent("MetricsCollected",{metrics:e}),await a.memory.set(`queen:metrics:${Date.now()}`,e,{ttl:86400,namespace:"queen-coordinator"}),a.dynamicScaler)try{let t=a.getAverageTaskDuration(),n={queueDepth:a.getQueuedTaskCount(),activeAgents:a.getActiveAgentCount(),idleAgents:a.getIdleAgentCount(),avgTaskDurationMs:t,errorRate:a.getTasksReceived()>0?a.getTasksFailed()/a.getTasksReceived():0,throughput:e.uptime>0?a.getTasksCompleted()/(e.uptime/1e3):0,timestamp:Date.now()};a.dynamicScaler.recordMetrics(n);let i=a.dynamicScaler.evaluate();i&&i.action!=="maintain"&&(console.log(`[QueenCoordinator] Dynamic scaler: ${i.action} to ${i.targetAgents} agents \u2014 ${i.reason}`),a.dynamicScaler.execute(i).catch(r=>{console.warn("[QueenCoordinator] Dynamic scaling execution error:",r)}))}catch(t){console.warn("[QueenCoordinator] Dynamic scaler metrics error:",t)}},a.config.metricsInterval)}function Xe(a,e,t=36e5){let n=Date.now(),i=0;for(let[s,o]of a)if(o.status==="completed"||o.status==="failed"||o.status==="cancelled"){let l=o.completedAt?.getTime()||o.startedAt?.getTime()||0;l>0&&n-l>t&&(a.delete(s),e.delete(s),i++)}let r=1e4;if(e.size>r){let s=e.size-r,o=e.keys();for(let l=0;l<s;l++){let c=o.next().value;c!==void 0&&e.delete(c)}console.log(`[QueenCoordinator] Evicted ${s} oldest trace contexts (max: ${r})`)}return i>0&&console.log(`[QueenCoordinator] Cleaned up ${i} old tasks (retention: ${t}ms)`),i}function nn(a,e){return a&&a.size>0?Array.from(a.keys()):[...e]}var g=it.create("QueenCoordinator");zt(v);var Je=class{constructor(e,t,n,i,r,s,o,l={}){this.eventBus=e;this.agentCoordinator=t;this.memory=n;this.router=i;this.protocolExecutor=r;this.workflowExecutor=s;this.domainPlugins=o;this.config={...Ut,...l},this.auditLogger=he({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 j(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 nt(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=Ye(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=tn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{Xe(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await Jt(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=ht(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:ct()}),await this.minCutBridge.initialize(),this.domainPlugins&&Xt(this.domainPlugins,this.minCutBridge);try{await I.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=Rt(t),this.availableMcpServers=dt(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-BEUZQTTC.js"),i=n();await i.initialize(),this.coExecutionRepo=wt(),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 en(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}async submitTask(e){if(!this.initialized)return y(new Error("Queen Coordinator not initialized"));let t=`task_${T()}`,n={...e,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 I.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}),y(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 Ve(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),b(t)):(this.runningTaskCounter--,r)}catch(r){throw this.runningTaskCounter--,r}}async cancelTask(e){let t=this.tasks.get(e);if(!t)return y(new Error(`Task not found: ${e}`));if(t.status==="completed"||t.status==="failed")return y(new Error(`Task already finished: ${e}`));(t.status==="running"||t.status==="assigned")&&(this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1)),this.tasks.set(e,{...t,status:"cancelled",completedAt:new Date}),de(this.taskQueue,this.domainQueues,t.task);for(let n of t.assignedAgents)await this.agentCoordinator.stop(n);return this.auditLogger.logCancel(e),await this.publishEvent("TaskCancelled",{taskId:e}),b(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return Kt(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return Wt(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?_t(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=Ye(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return Zt(this.createWorkStealingContext())}listAllAgents(){return this.agentCoordinator.listAgents()}getAgentsByDomain(e){return this.agentCoordinator.listAgents({domain:e})}async requestAgentSpawn(e,t,n){if(!this.agentCoordinator.canSpawn())return y(new Error("Maximum concurrent agents reached (15)"));if(this.dependencyGraph&&this.availableMcpServers.length>0)try{for(let[,r]of this.dependencyGraph.nodes){let s=r.dependencies.mcpServers;if(!s||s.length===0)continue;let o=s.filter(l=>l.required&&!this.availableMcpServers.includes(l.name));if(o.length>0){g.warn(`Pre-spawn MCP advisory: ${r.agentName} needs ${o.map(l=>l.name).join(", ")}`,{agent:r.agentName,domain:e,missing:o.map(l=>l.name)});break}}}catch{}let i=await this.agentCoordinator.spawn({name:`${e}-${t}-${Date.now()}`,domain:e,type:t,capabilities:n});if(i.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,i.value)||g.warn(`Agent ${i.value} could not join ${e} team (full)`);else try{this.domainTeamManager.createDomainTeam(e,i.value)}catch{this.domainTeamManager.addTeammate(e,i.value)||g.warn(`Agent ${i.value} could not join ${e} team (full or max teams reached)`)}}catch(r){g.warn(`Auto-team-wiring failed for ${i.value}`,{error:r})}await this.publishEvent("AgentSpawned",{agentId:i.value,domain:e,type:t,capabilities:n})}return i}getHealth(){let e=new Map,t=[],n=0,i=0,r=nn(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 s=this.agentCoordinator.listAgents(),o=s.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:s.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(),s={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(s):s}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?Ze(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 ae(e);this.taskCompletedHook=new se({},t),g.info("ReasoningBank connected for pattern training")}async executeProtocol(e,t){if(!this.protocolExecutor)return y(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}),b(n.value.executionId)):n}async executeWorkflow(e,t){if(!this.workflowExecutor)return y(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}),b(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return Xe(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=jt(this.createEventHandlerContext(),v)}enqueueTaskInternal(e){Vt(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:T(),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,je(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:je(this.taskQueue,e)}),b(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=Ot(),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=Ae(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=Ee(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=Re(),g.info("Fleet tier selector initialized")}catch(e){g.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=xe(),g.info("Trace collector initialized")}catch(e){g.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=Fe(),this.federationMailbox=Oe(),this.dynamicScaler=Le(),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:()=>We(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)=>e.requestAgentSpawn(t,n,i),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),removeFromQueues:t=>de(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>Ke(e.createTaskContext(),t,n).then(()=>{}),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 uo(a,e,t,n,i,r){return new Je(a.eventBus,a.coordinator,a.memory,e,t,n,i,r)}export{ei as a,P as b,Je as c,uo 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 pe(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,s]=n,o=this.getValueFromPath(t,i),l=isNaN(Number(s))?s:Number(s),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"&&i in n)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`)}},qe=null;function Gt(a){return qe||(qe=new Ge(a)),qe}function jt(a,e){let t=[];for(let s of e){let o=a.router.subscribeToDoamin(s,async l=>{await ai(a,l)});t.push(o)}let n=a.router.subscribeToEventType("TaskCompleted",async s=>{await oi(a,s)});t.push(n);let i=a.router.subscribeToEventType("TaskFailed",async s=>{await ci(a,s)});t.push(i);let r=a.router.subscribeToEventType("AgentStatusChanged",async s=>{await li(a,s)});return t.push(r),t}async function ai(a,e){a.domainLastActivity.set(e.source,new Date),await a.processQueue()}async function oi(a,e){let{taskId:t,result:n}=e.payload,i=a.tasks.get(t);if(i){(i.status==="running"||i.status==="assigned")&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1));let r=i.startedAt?Date.now()-i.startedAt.getTime():0;a.tasks.set(t,{...i,status:"completed",completedAt:new Date,result:n}),a.tasksCompleted++,a.taskDurations.push(r),a.auditLogger.logComplete(t,i.assignedAgents[0]);try{let s=Gt(),o=i.assignedAgents[0];o&&await s.onAgentComplete(o,{taskId:t,taskType:i.task.type,domain:i.assignedDomain,result:n,duration:r})}catch(s){console.warn("[QueenCoordinator] Cross-phase hook error:",s)}try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!0,0,0)}catch(s){console.warn("[QueenCoordinator] Governance tracking error:",s)}if(a.domainBreakerRegistry&&i.assignedDomain&&a.domainBreakerRegistry.getBreaker(i.assignedDomain).recordSuccess(),a.traceCollector){let s=a.taskTraceContexts.get(t);s&&(a.traceCollector.completeSpan(s.spanId),a.taskTraceContexts.delete(t))}if(a.taskCompletedHook)try{let s=typeof n=="object"&&n!==null?n:null;if(s===null)console.error(`[QueenCoordinator] Pattern training skipped for task ${t}: result is not an object (got ${typeof n})`);else{let o=ui(s,t);if(o){let l={taskId:t,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",type:i.task.type,status:"completed",output:s,metrics:o,duration:r,timestamp:Date.now()};a.taskCompletedHook.onTaskCompleted(l).catch(c=>{console.warn("[QueenCoordinator] Pattern training error:",c)})}}}catch(s){console.warn("[QueenCoordinator] Pattern training setup error:",s)}}await a.processQueue()}async function ci(a,e){let{taskId:t,error:n}=e.payload,i=a.tasks.get(t);if(i){if((i.status==="running"||i.status==="assigned")&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1)),a.domainBreakerRegistry&&i.assignedDomain&&a.domainBreakerRegistry.getBreaker(i.assignedDomain).recordFailure(new Error(n||"Task failed")),a.traceCollector){let r=a.taskTraceContexts.get(t);r&&(a.traceCollector.failSpan(r.spanId,n||"Task failed"),a.taskTraceContexts.delete(t))}if(i.retryCount<a.config.taskRetryLimit){a.auditLogger.logFail(t,i.assignedAgents[0],n);let r={...i,status:"queued",retryCount:i.retryCount+1,error:n};a.tasks.set(t,r),a.enqueueTask(i.task)}else{a.tasks.set(t,{...i,status:"failed",completedAt:new Date,error:n}),a.tasksFailed++,a.auditLogger.logFail(t,i.assignedAgents[0],n);try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!1,0,0)}catch(r){console.warn("[QueenCoordinator] Governance tracking error:",r)}if(a.hypothesisManager&&(i.task.priority==="p0"||i.task.priority==="p1"))try{let r=i.assignedDomain||"test-generation",s=a.hypothesisManager.createInvestigation(t,r,`Root cause analysis for ${i.task.type} failure: ${n}`);a.hypothesisManager.addHypothesis(s.id,`Infrastructure failure in domain '${r}' caused task ${t} to fail`,"log-analysis",`${r}-lead`),a.hypothesisManager.addHypothesis(s.id,`Logic/configuration error in task payload caused ${i.task.type} to fail: ${n}`,"code-analysis",i.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${s.id}`)}catch(r){console.warn("[QueenCoordinator] Hypothesis creation error:",r)}}}await a.processQueue()}async function li(a,e){let{agentId:t,status:n,domain:i}=e.payload;a.domainLastActivity.set(i,new Date),(n==="completed"||n==="failed")&&await a.processQueue()}function ui(a,e){if("metrics"in a&&typeof a.metrics=="object"&&a.metrics!==null){let t=a.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 a||"testsFailed"in a?{testsPassed:typeof a.testsPassed=="number"?a.testsPassed:void 0,testsFailed:typeof a.testsFailed=="number"?a.testsFailed:void 0,coverageChange:typeof a.coverageChange=="number"?a.coverageChange:void 0,securityIssues:typeof a.securityIssues=="number"?a.securityIssues:void 0,performanceMs:typeof a.performanceMs=="number"?a.performanceMs:void 0,linesChanged:typeof a.linesChanged=="number"?a.linesChanged:void 0}:(console.error(`[QueenCoordinator] Pattern training skipped for task ${e}: result object has no recognizable metrics shape (keys: ${Object.keys(a).join(", ")})`),null)}function Wt(a,e,t){let n=a.listAgents({domain:e}),i=n.filter(l=>l.status==="running").length,r=n.filter(l=>l.status==="idle").length,s=n.filter(l=>l.status==="failed").length,o;return s>0&&s>=n.length/2?o="unhealthy":s>0?o="degraded":i>0?o="healthy":o="idle",{status:o,agents:{total:n.length,active:i,idle:r,failed:s},lastActivity:t,errors:[]}}var di=ut();function Vt(a,e,t){let n=a.get(t.priority);n&<(n,t,di);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function de(a,e,t){let n=a.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 s=r.findIndex(o=>o.id===t.id);s!==-1&&r.splice(s,1)}}}function je(a,e){let t=0;for(let n of["p0","p1","p2","p3"]){let i=a.get(n);if(i){if(n===e.priority){t+=i.findIndex(r=>r.id===e.id);break}t+=i.length}}return t}async function We(a){if(!(a.runningTaskCounter>=a.config.maxConcurrentTasks))for(let e of["p0","p1","p2","p3"]){let t=a.taskQueue.get(e);if(!t||t.length===0)continue;let n=t.shift();if(n){de(a.taskQueue,a.domainQueues,n),a.runningTaskCounter++;try{await Ve(a,n)}catch(i){throw a.runningTaskCounter--,i}if(a.runningTaskCounter>=a.config.maxConcurrentTasks)return}}}function Kt(a,e){let t=Array.from(a.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 Ve(a,e){let t=e.targetDomains.length>0?e.targetDomains:P[e.type]||[];if(t.length===0)return y(new Error(`No domains configured for task type: ${e.type}`));let n,i=1/0;for(let r of t){let s=a.getDomainLoad(r);a.getDomainHealth(r)?.status!=="unhealthy"&&s<i&&(i=s,n=r)}return n?Ke(a,e,n):y(new Error("No healthy domain available for task"))}async function Ke(a,e,t){let n;if(a.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:c[e.priority]};n=await a.tinyDancerRouter.route(u),a.config.enableMetrics&&console.log(`[Queen] TinyDancer routing: ${e.type} \u2192 tier=${n.tier}, model=${n.model}, cost=$${n.estimatedCost.toFixed(4)}`)}if(a.domainBreakerRegistry&&!a.domainBreakerRegistry.canExecuteInDomain(t))return y(new Error(`Domain '${t}' circuit breaker is open \u2014 too many recent failures`));if(a.domainTeamManager)try{if(!a.domainTeamManager.getDomainTeam(t)){let u=`${t}-lead`;a.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"]:[]],s=await a.requestAgentSpawn(t,i,r),o=[];s.success&&o.push(s.value);let l={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:o,startedAt:new Date,retryCount:0};a.tasks.set(e.id,l),a.domainLastActivity.set(t,new Date);for(let c of o)a.auditLogger.logAssign(e.id,c,t);if(await a.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:o}),a.domainPlugins){let c=a.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=await c.executeTask(u,m=>mi(a,m));return d.success?b(e.id):(a.tasks.set(e.id,{...l,status:"failed",error:d.error.message,completedAt:new Date}),a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),a.tasksFailed++,a.auditLogger.logFail(e.id,o[0],d.error.message),y(d.error))}if(c)try{await c.handleEvent({id:T(),type:"TaskAssigned",timestamp:new Date,source:"queen-coordinator",correlationId:e.correlationId,payload:{task:e}}),console.warn(`[Queen] Domain ${t} has no executeTask handler, using event fallback`)}catch(u){console.warn(`[Queen] Failed to invoke domain ${t} event handler:`,u)}}return b(e.id)}async function mi(a,e){let t=a.tasks.get(e.taskId);if(!t){console.warn(`[Queen] Received completion for unknown task: ${e.taskId}`);return}let n={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(a.tasks.set(e.taskId,n),e.success?(a.tasksCompleted++,a.taskDurations.push(e.duration),a.auditLogger.logComplete(e.taskId,t.assignedAgents[0])):(a.tasksFailed++,a.auditLogger.logFail(e.taskId,t.assignedAgents[0],e.error||"Unknown error")),a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),a.coExecutionRepo&&t.assignedAgents.length>=2)try{a.coExecutionRepo.recordSwarmCoExecution(t.assignedAgents,t.assignedDomain||"unknown",e.success,t.task.type)}catch{}for(let i of t.assignedAgents)await a.agentCoordinator.stop(i);await a.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await We(a)}function Yt(a,e){return(P[e.type]||[]).includes(a)}k();async function Zt(a){let e=0,t=a.getIdleDomains(),n=a.getBusyDomains();if(t.length===0||n.length===0)return 0;n.sort((i,r)=>a.getDomainLoad(r)-a.getDomainLoad(i));for(let i of n){if(t.length===0)break;let r=a.domainQueues.get(i)||[],s=Math.min(r.length,a.config.workStealing.stealBatchSize);for(let o=0;o<s&&t.length>0;o++){let l=r.find(c=>Yt(t[0],c));if(l){let c=t.shift();a.removeFromQueues(l),a.auditLogger.logSteal(l.id,i,c),await a.assignTaskToDomain(l,c),e++,a.tasksStolen++,await a.publishEvent("TaskStolen",{taskId:l.id,fromDomain:i,toDomain:c})}}}return e}function Ye(a,e){let t=0,n=10,i=setInterval(async()=>{try{await e(),t=0}catch(r){t++;let s=Math.min(1e3*Math.pow(2,t),3e4);if(console.warn(`[QueenCoordinator] Work-stealing failed (attempt ${t}), backing off ${s}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,s))}},a.workStealing.checkInterval);return i}function Ze(a){return typeof a.setMinCutBridge=="function"}function Xt(a,e){for(let[t,n]of a)Ze(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function Jt(a,e,t){try{let n=await a.get("queen:state");if(n)for(let[i,r]of n.tasks)r.status==="queued"&&(e.set(i,r),t(r.task))}catch(n){console.debug("[QueenCoordinator] State loading failed:",n instanceof Error?n.message:n)}}async function en(a,e){let t=Array.from(e.entries()).filter(([,n])=>n.status==="queued");await a.set("queen:state",{tasks:t},{namespace:"queen-coordinator",persist:!0})}function tn(a){return setInterval(async()=>{let e=a.getMetrics();if(await a.publishEvent("MetricsCollected",{metrics:e}),await a.memory.set(`queen:metrics:${Date.now()}`,e,{ttl:86400,namespace:"queen-coordinator"}),a.dynamicScaler)try{let t=a.getAverageTaskDuration(),n={queueDepth:a.getQueuedTaskCount(),activeAgents:a.getActiveAgentCount(),idleAgents:a.getIdleAgentCount(),avgTaskDurationMs:t,errorRate:a.getTasksReceived()>0?a.getTasksFailed()/a.getTasksReceived():0,throughput:e.uptime>0?a.getTasksCompleted()/(e.uptime/1e3):0,timestamp:Date.now()};a.dynamicScaler.recordMetrics(n);let i=a.dynamicScaler.evaluate();i&&i.action!=="maintain"&&(console.log(`[QueenCoordinator] Dynamic scaler: ${i.action} to ${i.targetAgents} agents \u2014 ${i.reason}`),a.dynamicScaler.execute(i).catch(r=>{console.warn("[QueenCoordinator] Dynamic scaling execution error:",r)}))}catch(t){console.warn("[QueenCoordinator] Dynamic scaler metrics error:",t)}},a.config.metricsInterval)}function Xe(a,e,t=36e5){let n=Date.now(),i=0;for(let[s,o]of a)if(o.status==="completed"||o.status==="failed"||o.status==="cancelled"){let l=o.completedAt?.getTime()||o.startedAt?.getTime()||0;l>0&&n-l>t&&(a.delete(s),e.delete(s),i++)}let r=1e4;if(e.size>r){let s=e.size-r,o=e.keys();for(let l=0;l<s;l++){let c=o.next().value;c!==void 0&&e.delete(c)}console.log(`[QueenCoordinator] Evicted ${s} oldest trace contexts (max: ${r})`)}return i>0&&console.log(`[QueenCoordinator] Cleaned up ${i} old tasks (retention: ${t}ms)`),i}function nn(a,e){return a&&a.size>0?Array.from(a.keys()):[...e]}var g=it.create("QueenCoordinator");zt(v);var Je=class{constructor(e,t,n,i,r,s,o,l={}){this.eventBus=e;this.agentCoordinator=t;this.memory=n;this.router=i;this.protocolExecutor=r;this.workflowExecutor=s;this.domainPlugins=o;this.config={...Ut,...l},this.auditLogger=he({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 j(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 nt(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=Ye(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=tn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{Xe(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await Jt(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=ht(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:ct()}),await this.minCutBridge.initialize(),this.domainPlugins&&Xt(this.domainPlugins,this.minCutBridge);try{await I.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=Rt(t),this.availableMcpServers=dt(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-H2J5BHPY.js"),i=n();await i.initialize(),this.coExecutionRepo=wt(),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 en(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}async submitTask(e){if(!this.initialized)return y(new Error("Queen Coordinator not initialized"));let t=`task_${T()}`,n={...e,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 I.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}),y(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 Ve(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),b(t)):(this.runningTaskCounter--,r)}catch(r){throw this.runningTaskCounter--,r}}async cancelTask(e){let t=this.tasks.get(e);if(!t)return y(new Error(`Task not found: ${e}`));if(t.status==="completed"||t.status==="failed")return y(new Error(`Task already finished: ${e}`));(t.status==="running"||t.status==="assigned")&&(this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1)),this.tasks.set(e,{...t,status:"cancelled",completedAt:new Date}),de(this.taskQueue,this.domainQueues,t.task);for(let n of t.assignedAgents)await this.agentCoordinator.stop(n);return this.auditLogger.logCancel(e),await this.publishEvent("TaskCancelled",{taskId:e}),b(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return Kt(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return Wt(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?_t(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=Ye(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return Zt(this.createWorkStealingContext())}listAllAgents(){return this.agentCoordinator.listAgents()}getAgentsByDomain(e){return this.agentCoordinator.listAgents({domain:e})}async requestAgentSpawn(e,t,n){if(!this.agentCoordinator.canSpawn())return y(new Error("Maximum concurrent agents reached (15)"));if(this.dependencyGraph&&this.availableMcpServers.length>0)try{for(let[,r]of this.dependencyGraph.nodes){let s=r.dependencies.mcpServers;if(!s||s.length===0)continue;let o=s.filter(l=>l.required&&!this.availableMcpServers.includes(l.name));if(o.length>0){g.warn(`Pre-spawn MCP advisory: ${r.agentName} needs ${o.map(l=>l.name).join(", ")}`,{agent:r.agentName,domain:e,missing:o.map(l=>l.name)});break}}}catch{}let i=await this.agentCoordinator.spawn({name:`${e}-${t}-${Date.now()}`,domain:e,type:t,capabilities:n});if(i.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,i.value)||g.warn(`Agent ${i.value} could not join ${e} team (full)`);else try{this.domainTeamManager.createDomainTeam(e,i.value)}catch{this.domainTeamManager.addTeammate(e,i.value)||g.warn(`Agent ${i.value} could not join ${e} team (full or max teams reached)`)}}catch(r){g.warn(`Auto-team-wiring failed for ${i.value}`,{error:r})}await this.publishEvent("AgentSpawned",{agentId:i.value,domain:e,type:t,capabilities:n})}return i}getHealth(){let e=new Map,t=[],n=0,i=0,r=nn(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 s=this.agentCoordinator.listAgents(),o=s.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:s.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(),s={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(s):s}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?Ze(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 ae(e);this.taskCompletedHook=new se({},t),g.info("ReasoningBank connected for pattern training")}async executeProtocol(e,t){if(!this.protocolExecutor)return y(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}),b(n.value.executionId)):n}async executeWorkflow(e,t){if(!this.workflowExecutor)return y(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}),b(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return Xe(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=jt(this.createEventHandlerContext(),v)}enqueueTaskInternal(e){Vt(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:T(),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,je(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:je(this.taskQueue,e)}),b(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=Ot(),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=Ae(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=Ee(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=Re(),g.info("Fleet tier selector initialized")}catch(e){g.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=xe(),g.info("Trace collector initialized")}catch(e){g.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=Fe(),this.federationMailbox=Oe(),this.dynamicScaler=Le(),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:()=>We(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)=>e.requestAgentSpawn(t,n,i),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),removeFromQueues:t=>de(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>Ke(e.createTaskContext(),t,n).then(()=>{}),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 uo(a,e,t,n,i,r){return new Je(a.eventBus,a.coordinator,a.memory,e,t,n,i,r)}export{ei as a,P as b,Je as c,uo 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.13.
|
|
2
|
-
import{a as ie,b as ae}from"./chunk-DQXSDWRP.js";import{S as oe,i as j,p as q}from"./chunk-GZ775E5O.js";import{c as g,e as D,g as $}from"./chunk-AJ7A52GF.js";var I,E=g(()=>{"use strict";I={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}});function se(){if(z)return A!==null;try{let i=(ae(),$(ie));if(A=i.differentiableSearch,P=i.init,P)try{P()}catch{}return z=!0,!0}catch{return z=!0,!1}}function B(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function ce(i,e,r,t){let n=r*t;if(n===0)return 0;let a=0,o=Math.min(i.length,e.length);for(let c=0;c<o;c++)a+=i[c]*e[c];return a/n}function U(i,e){let r=0,t=Math.min(i.length,e.length);for(let n=0;n<t;n++){let a=i[n]-e[n];r+=a*a}return Math.sqrt(r)}function le(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}var A,P,z,S,O=g(()=>{"use strict";E();A=null,P=null,z=!1;S=class{config;entries=[];idToIndex=new Map;hasRuvector=!1;loaded=!1;constructor(e){this.config={...I,...e}}ensureLoaded(){this.loaded||(this.hasRuvector=se(),this.loaded=!0)}normalizeVector(e){return e.length===this.config.dimensions?e:le(e,this.config.dimensions)}add(e,r,t){this.ensureLoaded();let n=this.normalizeVector(r),a=B(n);if(this.idToIndex.has(e)){let c=this.idToIndex.get(e);this.entries[c]={id:e,vector:n,norm:a,metadata:t};return}let o=this.entries.length;this.entries.push({id:e,vector:n,norm:a,metadata:t}),this.idToIndex.set(e,o)}search(e,r){if(this.ensureLoaded(),this.entries.length===0)return[];let t=this.normalizeVector(e),n=B(t),a=Math.min(r,this.entries.length),o=this.entries.length>0?this.entries[0].vector.length:0,c=t.length===o;if(this.config.metric==="cosine")return this.bruteForcSearch(t,n,a);if(this.hasRuvector&&c&&A)try{let s=this.entries.map(u=>u.vector),l=A(t,s,a,1).indices.map(u=>{let h=this.entries[u],m=-U(t,h.vector);return{id:h.id,score:m,metadata:h.metadata}});return l.sort((u,h)=>h.score-u.score),l}catch{}return this.bruteForcSearch(t,n,a)}bruteForcSearch(e,r,t){let n=[];for(let a of this.entries){let o;this.config.metric==="cosine"?o=ce(e,a.vector,r,a.norm):o=-U(e,a.vector),n.push({id:a.id,score:o,metadata:a.metadata})}return n.sort((a,o)=>o.score-a.score),n.slice(0,t)}remove(e){let r=this.idToIndex.get(e);if(r===void 0)return!1;let t=this.entries.length-1;if(r!==t){let n=this.entries[t];this.entries[r]=n,this.idToIndex.set(n.id,r)}return this.entries.pop(),this.idToIndex.delete(e),!0}size(){return this.entries.length}dimensions(){return this.config.dimensions}recall(){return this.hasRuvector,1}isRuvectorAvailable(){return this.ensureLoaded(),this.hasRuvector}getConfig(){return{...this.config}}clear(){this.entries=[],this.idToIndex.clear()}dispose(){this.clear()}}});import{createRequire as he}from"module";function de(){if(K){if(k)return k;throw new b(J??"Unknown load error")}K=!0;try{let i=ue("hnswlib-node");if(!i.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return k=i,k}catch(i){let e=i instanceof Error?i.message:String(i);throw J=e,new b(e)}}function me(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}function Q(i){let e=new Array(i.length);for(let r=0;r<i.length;r++)e[r]=i[r];return e}var ue,b,k,K,J,X,w,Y=g(()=>{"use strict";E();ue=he(import.meta.url),b=class extends Error{constructor(e){super(`Native HNSW backend unavailable: ${e}`),this.name="NativeHnswUnavailableError"}},k=null,K=!1,J=null;X=1e4,w=class{config;nativeIndex=null;currentMaxElements=X;liveIds=new Set;metadataStore=new Map;_metrics={totalSearches:0,totalAdds:0,totalRemoves:0,avgSearchLatencyMs:0,maxSearchLatencyMs:0,lastSearchLatencyMs:0,fallbackSearchCount:0,bruteForceSearchCount:0,nativeSearchCount:0,fallbackRate:0,allSearchesBruteForce:!1};constructor(e){this.config={...I,...e},this.nativeIndex=this.createFreshIndex()}createFreshIndex(){let e=de(),r=this.config.metric==="euclidean"?"l2":"cosine";try{let t=new e.HierarchicalNSW(r,this.config.dimensions);return t.initIndex(this.currentMaxElements,this.config.M,this.config.efConstruction,100,!0),t.setEf(this.config.efSearch),t}catch(t){let n=t instanceof Error?t.message:String(t);throw new b(`HierarchicalNSW init failed: ${n}`)}}add(e,r,t){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");let n=this.normalizeVector(r);if(!this.liveIds.has(e)&&this.liveIds.size>=this.currentMaxElements){let a=this.currentMaxElements*2;this.nativeIndex.resizeIndex(a),this.currentMaxElements=a}this.nativeIndex.addPoint(Q(n),e,!0),this.liveIds.add(e),t?this.metadataStore.set(e,t):this.metadataStore.delete(e),this._metrics.totalAdds++}search(e,r){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");if(this.liveIds.size===0||r<=0)return[];let t=performance.now(),n=this.normalizeVector(e),a=Math.min(r,this.liveIds.size),o=Math.min(a*2,this.liveIds.size),c=this.nativeIndex.searchKnn(Q(n),o),s=this.config.metric==="cosine",d=new Map;for(let h=0;h<c.neighbors.length;h++){let m=c.neighbors[h];if(!this.liveIds.has(m))continue;let x=c.distances[h],f=s?1-x:-x,W=d.get(m);(W===void 0||f>W.score)&&d.set(m,{id:m,score:f,metadata:this.metadataStore.get(m)})}let l=Array.from(d.values());l.sort((h,m)=>m.score-h.score),l.length>a&&(l.length=a);let u=performance.now()-t;return this.updateSearchMetrics(u),this._metrics.nativeSearchCount=this._metrics.totalSearches,u>50&&console.warn(`[NativeHNSW] search took ${u.toFixed(1)}ms (k=${r}, results=${l.length})`),l}remove(e){if(!this.nativeIndex||!this.liveIds.has(e))return!1;try{this.nativeIndex.markDelete(e)}catch{return!1}return this.liveIds.delete(e),this.metadataStore.delete(e),this._metrics.totalRemoves++,!0}size(){return this.liveIds.size}dimensions(){return this.config.dimensions}recall(){return .99}getMetrics(){return{...this._metrics}}get lastSearchLatencyMs(){return this._metrics.lastSearchLatencyMs}getConfig(){return{...this.config}}clear(){this.nativeIndex&&(this.liveIds.clear(),this.metadataStore.clear(),this.currentMaxElements=X,this.nativeIndex=this.createFreshIndex())}dispose(){this.liveIds.clear(),this.metadataStore.clear(),this.nativeIndex=null}isNativeAvailable(){return this.nativeIndex!==null}normalizeVector(e){return e.length===this.config.dimensions?e:me(e,this.config.dimensions)}updateSearchMetrics(e){this._metrics.totalSearches++,this._metrics.lastSearchLatencyMs=e,e>this._metrics.maxSearchLatencyMs&&(this._metrics.maxSearchLatencyMs=e);let r=this._metrics.totalSearches;this._metrics.avgSearchLatencyMs=this._metrics.avgSearchLatencyMs*((r-1)/r)+e/r}}});function Z(i,e){let r=Array.from({length:e},()=>new Float64Array(e));for(let t=0;t<e;t++){let n=i[t].length;r[t][t]=n;for(let a of i[t])r[t][a]=-1}return r}function N(i,e){let r=e.length,t=new Float64Array(r);for(let n=0;n<r;n++){let a=i[n].length;t[n]=a*e[n];for(let o of i[n])t[n]-=e[o]}return t}function H(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function R(i){let e=H(i);if(e>0)for(let r=0;r<i.length;r++)i[r]/=e}function v(i,e){let r=0;for(let t=0;t<i.length;t++)r+=i[t]*e[t];for(let t=0;t<i.length;t++)i[t]-=r*e[t]}function y(i,e,r=100,t=1e-6){if(e<=1)return 0;if(e===2)return i[0].includes(1)?2:0;let n=new Float64Array(e).fill(1/Math.sqrt(e)),a=new Float64Array(e);for(let l=0;l<e;l++)a[l]=Math.random()-.5;v(a,n),R(a);let o=0;for(let l=0;l<30;l++){let u=N(i,a);if(v(u,n),o=H(u),o>0)for(let h=0;h<e;h++)a[h]=u[h]/o}if(o<t)return 0;let c=new Float64Array(e);for(let l=0;l<e;l++)c[l]=Math.random()-.5;v(c,n),R(c);let s=0;for(let l=0;l<r;l++){let u=N(i,c),h=new Float64Array(e);for(let f=0;f<e;f++)h[f]=o*c[f]-u[f];v(h,n);let m=H(h);if(m<t)break;let x=m;for(let f=0;f<e;f++)c[f]=h[f]/m;if(Math.abs(x-s)<t)break;s=x}let d=o-s;return Math.max(0,d)}function F(i,e,r=100,t=1e-6){return y(i,e,r,t)}function C(i,e,r=50,t){if(e<=1)return 0;let n=t??y(i,e);if(n<1e-10)return 1/0;let o=2*Math.max(...i.map(d=>d.length),1),s=2*(Math.log(o/n)/(o-n));return Math.max(0,s)}function M(i,e,r){let t=1-Math.exp(-i/.05),n=1-Math.exp(-e/.5),a=r===1/0?0:1/(1+r/5),o=.4*t+.3*n+.3*a;return Math.max(0,Math.min(1,o))}var _=g(()=>{"use strict"});var re={};D(re,{ALERT_THRESHOLDS:()=>fe,DEFAULT_HNSW_HEALTH_CONFIG:()=>ee,HnswHealthMonitor:()=>L,_resetNativeLoader:()=>be,approximateFiedlerValue:()=>y,approximateSpectralGap:()=>F,buildAdjacencyFromIndex:()=>te,buildLaplacian:()=>Z,computeCoherenceScore:()=>M,createHnswHealthMonitor:()=>ge,deflateVector:()=>v,estimateEffectiveResistance:()=>C,laplacianMultiply:()=>N,normalizeInPlace:()=>R,vectorNorm:()=>H});function pe(){return V?T:(V=!0,T=null,null)}function be(){T=null,V=!1}function te(i,e=16,r){let t=i.size();if(t===0)return{adjacency:[],nodeCount:0,adjacencySource:"approximate"};let n=Array.from({length:t},()=>[]),a=Math.min(e,t-1);if(a===0)return{adjacency:n,nodeCount:t,adjacencySource:"approximate"};if(r&&r.size>0){let o=Array.from(r.keys()).slice(0,t),c=new Map;for(let s=0;s<o.length;s++)c.set(o[s],s);for(let s=0;s<o.length;s++){let d=r.get(o[s]);if(!d)continue;let l=i.search(d,a+1);for(let u of l){if(u.id===o[s])continue;let h=c.get(u.id);h!==void 0&&(n[s].includes(h)||n[s].push(h),n[h].includes(s)||n[h].push(s))}}return{adjacency:n,nodeCount:t,adjacencySource:"actual-search"}}console.warn("[HnswHealthMonitor] No stored vectors provided \u2014 using approximate circular adjacency. Pass stored vectors for accurate health metrics.");for(let o=0;o<t;o++)for(let c=0;c<a;c++){let s=(o+c+1)%t;n[o].includes(s)||n[o].push(s),n[s].includes(o)||n[s].push(o)}return{adjacency:n,nodeCount:t,adjacencySource:"approximate"}}function ge(i){return new L(i)}var ee,fe,T,V,L,ne=g(()=>{"use strict";_();_();ee={fiedlerThreshold:.01,spectralGapThreshold:.1,resistanceThreshold:10,coherenceThreshold:.3,maxPowerIterations:100,convergenceTolerance:1e-6,resistanceSampleSize:50,maxHistoryEntries:200,minIndexSize:3},fe={FragileIndex:.01,PoorExpansion:.1,HighResistance:10,LowCoherence:.3},T=null,V=!1;L=class{config;alerts=[];history=[];lastReport=null;useNative=!1;nativeChecked=!1;constructor(e){this.config={...ee,...e}}checkHealth(e){let r=performance.now(),t=e.size();if(t<this.config.minIndexSize)return this.createSmallIndexReport(t,performance.now()-r);this.nativeChecked||(this.nativeChecked=!0,this.useNative=pe()!==null);let{adjacency:n,nodeCount:a,adjacencySource:o}=te(e),c=this.useNative?this.computeNativeMetrics(n):this.computeApproximateMetrics(n,a),s=this.generateAlerts(c);this.alerts.length=0,this.alerts.push(...s);let d=performance.now()-r,l={healthy:s.length===0,metrics:c,alerts:s,indexSize:t,usedNativeBackend:this.useNative,adjacencySource:o,checkDurationMs:d,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:c.coherenceScore,fiedlerValue:c.fiedlerValue,indexSize:t,healthy:l.healthy,timestamp:l.checkedAt}),this.lastReport=l,l}getAlerts(){return[...this.alerts]}getMetricsHistory(e){let r=[...this.history];return e!==void 0&&e<r.length?r.slice(-e):r}isHealthy(){return this.lastReport===null?!0:this.lastReport.healthy}getLastReport(){return this.lastReport}clearHistory(){this.history.length=0,this.alerts.length=0,this.lastReport=null}computeNativeMetrics(e){let r=T,t=r.computeFiedlerValue(e),n=r.computeSpectralGap(e),a=r.computeEffectiveResistance(e),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}computeApproximateMetrics(e,r){let t=y(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),n=F(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),a=C(e,r,this.config.resistanceSampleSize,t),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}generateAlerts(e){let r=[],t=new Date;return e.fiedlerValue<this.config.fiedlerThreshold&&r.push({type:"FragileIndex",message:`Fiedler value ${e.fiedlerValue.toFixed(6)} is below threshold ${this.config.fiedlerThreshold}. The index graph has weak algebraic connectivity.`,value:e.fiedlerValue,threshold:this.config.fiedlerThreshold,timestamp:t}),e.spectralGap<this.config.spectralGapThreshold&&r.push({type:"PoorExpansion",message:`Spectral gap ${e.spectralGap.toFixed(6)} is below threshold ${this.config.spectralGapThreshold}. The index graph has poor expansion properties.`,value:e.spectralGap,threshold:this.config.spectralGapThreshold,timestamp:t}),e.effectiveResistance>this.config.resistanceThreshold&&r.push({type:"HighResistance",message:`Average effective resistance ${e.effectiveResistance.toFixed(4)} exceeds threshold ${this.config.resistanceThreshold}. Nodes are poorly connected.`,value:e.effectiveResistance,threshold:this.config.resistanceThreshold,timestamp:t}),e.coherenceScore<this.config.coherenceThreshold&&r.push({type:"LowCoherence",message:`Coherence score ${e.coherenceScore.toFixed(4)} is below threshold ${this.config.coherenceThreshold}. Overall index health is degraded.`,value:e.coherenceScore,threshold:this.config.coherenceThreshold,timestamp:t}),r}createSmallIndexReport(e,r){let t={fiedlerValue:e>0?1:0,spectralGap:e>0?1:0,effectiveResistance:e>0?.5:0,coherenceScore:e>0?1:0},n={healthy:!0,metrics:t,alerts:[],indexSize:e,usedNativeBackend:!1,adjacencySource:"approximate",checkDurationMs:r,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:t.coherenceScore,fiedlerValue:t.fiedlerValue,indexSize:e,healthy:!0,timestamp:n.checkedAt}),this.lastReport=n,n}addHistoryPoint(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}}});var ye={};D(ye,{HnswAdapter:()=>G});var ve,p,G,xe=g(()=>{O();Y();oe();ve={patterns:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},"qe-memory":{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},learning:{dimensions:384,M:16,efConstruction:200,efSearch:50,metric:"cosine"},coverage:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}},p=new Map,G=class i{backend;_isNativeBackend;indexName;stringToNumericId=new Map;numericToStringId=new Map;nextAutoId=0;healthMonitor=null;healthMonitorLoaded=!1;operationsSinceLastCheck=0;healthCheckFrequency=100;lastHealthReport=null;constructor(e,r){this.indexName=e;let n={...ve[e]??{},...r},{backend:a,isNative:o}=i.createBackend(n);this.backend=a,this._isNativeBackend=o}add(e,r,t){this.backend.add(e,r,t),this.maybeRunHealthCheck()}search(e,r){let t=performance.now(),n=this.backend.search(e,r),a=performance.now()-t;return a>50&&console.warn(`[HNSW] search took ${a.toFixed(1)}ms (k=${r}, results=${n.length})`),this._lastSearchLatencyMs=a,n}_lastSearchLatencyMs=0;get lastSearchLatencyMs(){return this._lastSearchLatencyMs}remove(e){return this.backend.remove(e)}size(){return this.backend.size()}dimensions(){return this.backend.dimensions()}recall(){return this.backend.recall()}addByStringId(e,r){let t=this.stringToNumericId.get(e);t!==void 0?this.backend.remove(t):(t=this.nextAutoId++,this.stringToNumericId.set(e,t),this.numericToStringId.set(t,e)),this.backend.add(t,new Float32Array(r))}searchByArray(e,r){return this.backend.search(new Float32Array(e),r).map(n=>({id:this.numericToStringId.get(n.id)??String(n.id),score:n.score}))}removeByStringId(e){let r=this.stringToNumericId.get(e);if(r===void 0)return!1;let t=this.backend.remove(r);return t&&(this.stringToNumericId.delete(e),this.numericToStringId.delete(r)),t}clear(){this.backend.clear?.(),this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}dispose(){try{this.backend.dispose?.()}catch{}this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}isRuvectorAvailable(){return this.backend instanceof S?this.backend.isRuvectorAvailable():this.backend instanceof w?this.backend.isNativeAvailable():!1}isNativeBackend(){return this._isNativeBackend}getName(){return this.indexName}setHealthCheckFrequency(e){this.healthCheckFrequency=Math.max(1,e)}getHealthCheckFrequency(){return this.healthCheckFrequency}getLastHealthReport(){return this.lastHealthReport}getHealthMonitor(){return this.healthMonitor}maybeRunHealthCheck(){if(q()&&(this.operationsSinceLastCheck++,!(this.operationsSinceLastCheck<this.healthCheckFrequency)&&(this.operationsSinceLastCheck=0,this.ensureHealthMonitor(),this.healthMonitor)))try{this.lastHealthReport=this.healthMonitor.checkHealth(this.backend),this.lastHealthReport.healthy||console.warn(`[HNSW-Health] Index "${this.indexName}" health check failed: ${this.lastHealthReport.alerts.length} alert(s). Coherence: ${this.lastHealthReport.metrics.coherenceScore.toFixed(3)}`)}catch(e){console.warn(`[HNSW-Health] Health check error for "${this.indexName}":`,e)}}ensureHealthMonitor(){if(!this.healthMonitorLoaded){this.healthMonitorLoaded=!0;try{let e=(ne(),$(re));this.healthMonitor=e.createHnswHealthMonitor()}catch(e){process.env.DEBUG&&console.debug("[HNSW-Health] Monitor module unavailable:",e instanceof Error?e.message:e),this.healthMonitor=null}}}static createBackend(e){if(j())try{return{backend:new w(e),isNative:!0}}catch(r){r instanceof b?console.info(`[HNSW] Native backend unavailable, falling back to JS: ${r.message}`):console.warn("[HNSW] Unexpected error creating native backend, falling back to JS:",r)}return{backend:new S(e),isNative:!1}}static create(e,r){let t=p.get(e);if(t instanceof i)return t;let n=new i(e,r);return p.set(e,n),n}static get(e){let r=p.get(e);return r instanceof i?r:void 0}static close(e){let r=p.get(e);r instanceof i&&r.dispose(),p.delete(e)}static closeAll(){for(let[e]of p)i.close(e);p.clear()}static listIndexes(){return Array.from(p.keys())}}});export{G as a,ye as b,xe as c};
|
|
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.13.4");process.exit(0)}
|
|
2
|
+
import{a as ie,b as ae}from"./chunk-YZGA4ELM.js";import{S as oe,i as j,p as q}from"./chunk-ERKYIV25.js";import{c as g,e as D,g as $}from"./chunk-GGZB2ZBB.js";var I,E=g(()=>{"use strict";I={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}});function se(){if(z)return A!==null;try{let i=(ae(),$(ie));if(A=i.differentiableSearch,P=i.init,P)try{P()}catch{}return z=!0,!0}catch{return z=!0,!1}}function B(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function ce(i,e,r,t){let n=r*t;if(n===0)return 0;let a=0,o=Math.min(i.length,e.length);for(let c=0;c<o;c++)a+=i[c]*e[c];return a/n}function U(i,e){let r=0,t=Math.min(i.length,e.length);for(let n=0;n<t;n++){let a=i[n]-e[n];r+=a*a}return Math.sqrt(r)}function le(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}var A,P,z,S,O=g(()=>{"use strict";E();A=null,P=null,z=!1;S=class{config;entries=[];idToIndex=new Map;hasRuvector=!1;loaded=!1;constructor(e){this.config={...I,...e}}ensureLoaded(){this.loaded||(this.hasRuvector=se(),this.loaded=!0)}normalizeVector(e){return e.length===this.config.dimensions?e:le(e,this.config.dimensions)}add(e,r,t){this.ensureLoaded();let n=this.normalizeVector(r),a=B(n);if(this.idToIndex.has(e)){let c=this.idToIndex.get(e);this.entries[c]={id:e,vector:n,norm:a,metadata:t};return}let o=this.entries.length;this.entries.push({id:e,vector:n,norm:a,metadata:t}),this.idToIndex.set(e,o)}search(e,r){if(this.ensureLoaded(),this.entries.length===0)return[];let t=this.normalizeVector(e),n=B(t),a=Math.min(r,this.entries.length),o=this.entries.length>0?this.entries[0].vector.length:0,c=t.length===o;if(this.config.metric==="cosine")return this.bruteForcSearch(t,n,a);if(this.hasRuvector&&c&&A)try{let s=this.entries.map(u=>u.vector),l=A(t,s,a,1).indices.map(u=>{let h=this.entries[u],m=-U(t,h.vector);return{id:h.id,score:m,metadata:h.metadata}});return l.sort((u,h)=>h.score-u.score),l}catch{}return this.bruteForcSearch(t,n,a)}bruteForcSearch(e,r,t){let n=[];for(let a of this.entries){let o;this.config.metric==="cosine"?o=ce(e,a.vector,r,a.norm):o=-U(e,a.vector),n.push({id:a.id,score:o,metadata:a.metadata})}return n.sort((a,o)=>o.score-a.score),n.slice(0,t)}remove(e){let r=this.idToIndex.get(e);if(r===void 0)return!1;let t=this.entries.length-1;if(r!==t){let n=this.entries[t];this.entries[r]=n,this.idToIndex.set(n.id,r)}return this.entries.pop(),this.idToIndex.delete(e),!0}size(){return this.entries.length}dimensions(){return this.config.dimensions}recall(){return this.hasRuvector,1}isRuvectorAvailable(){return this.ensureLoaded(),this.hasRuvector}getConfig(){return{...this.config}}clear(){this.entries=[],this.idToIndex.clear()}dispose(){this.clear()}}});import{createRequire as he}from"module";function de(){if(K){if(k)return k;throw new b(J??"Unknown load error")}K=!0;try{let i=ue("hnswlib-node");if(!i.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return k=i,k}catch(i){let e=i instanceof Error?i.message:String(i);throw J=e,new b(e)}}function me(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}function Q(i){let e=new Array(i.length);for(let r=0;r<i.length;r++)e[r]=i[r];return e}var ue,b,k,K,J,X,w,Y=g(()=>{"use strict";E();ue=he(import.meta.url),b=class extends Error{constructor(e){super(`Native HNSW backend unavailable: ${e}`),this.name="NativeHnswUnavailableError"}},k=null,K=!1,J=null;X=1e4,w=class{config;nativeIndex=null;currentMaxElements=X;liveIds=new Set;metadataStore=new Map;_metrics={totalSearches:0,totalAdds:0,totalRemoves:0,avgSearchLatencyMs:0,maxSearchLatencyMs:0,lastSearchLatencyMs:0,fallbackSearchCount:0,bruteForceSearchCount:0,nativeSearchCount:0,fallbackRate:0,allSearchesBruteForce:!1};constructor(e){this.config={...I,...e},this.nativeIndex=this.createFreshIndex()}createFreshIndex(){let e=de(),r=this.config.metric==="euclidean"?"l2":"cosine";try{let t=new e.HierarchicalNSW(r,this.config.dimensions);return t.initIndex(this.currentMaxElements,this.config.M,this.config.efConstruction,100,!0),t.setEf(this.config.efSearch),t}catch(t){let n=t instanceof Error?t.message:String(t);throw new b(`HierarchicalNSW init failed: ${n}`)}}add(e,r,t){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");let n=this.normalizeVector(r);if(!this.liveIds.has(e)&&this.liveIds.size>=this.currentMaxElements){let a=this.currentMaxElements*2;this.nativeIndex.resizeIndex(a),this.currentMaxElements=a}this.nativeIndex.addPoint(Q(n),e,!0),this.liveIds.add(e),t?this.metadataStore.set(e,t):this.metadataStore.delete(e),this._metrics.totalAdds++}search(e,r){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");if(this.liveIds.size===0||r<=0)return[];let t=performance.now(),n=this.normalizeVector(e),a=Math.min(r,this.liveIds.size),o=Math.min(a*2,this.liveIds.size),c=this.nativeIndex.searchKnn(Q(n),o),s=this.config.metric==="cosine",d=new Map;for(let h=0;h<c.neighbors.length;h++){let m=c.neighbors[h];if(!this.liveIds.has(m))continue;let x=c.distances[h],f=s?1-x:-x,W=d.get(m);(W===void 0||f>W.score)&&d.set(m,{id:m,score:f,metadata:this.metadataStore.get(m)})}let l=Array.from(d.values());l.sort((h,m)=>m.score-h.score),l.length>a&&(l.length=a);let u=performance.now()-t;return this.updateSearchMetrics(u),this._metrics.nativeSearchCount=this._metrics.totalSearches,u>50&&console.warn(`[NativeHNSW] search took ${u.toFixed(1)}ms (k=${r}, results=${l.length})`),l}remove(e){if(!this.nativeIndex||!this.liveIds.has(e))return!1;try{this.nativeIndex.markDelete(e)}catch{return!1}return this.liveIds.delete(e),this.metadataStore.delete(e),this._metrics.totalRemoves++,!0}size(){return this.liveIds.size}dimensions(){return this.config.dimensions}recall(){return .99}getMetrics(){return{...this._metrics}}get lastSearchLatencyMs(){return this._metrics.lastSearchLatencyMs}getConfig(){return{...this.config}}clear(){this.nativeIndex&&(this.liveIds.clear(),this.metadataStore.clear(),this.currentMaxElements=X,this.nativeIndex=this.createFreshIndex())}dispose(){this.liveIds.clear(),this.metadataStore.clear(),this.nativeIndex=null}isNativeAvailable(){return this.nativeIndex!==null}normalizeVector(e){return e.length===this.config.dimensions?e:me(e,this.config.dimensions)}updateSearchMetrics(e){this._metrics.totalSearches++,this._metrics.lastSearchLatencyMs=e,e>this._metrics.maxSearchLatencyMs&&(this._metrics.maxSearchLatencyMs=e);let r=this._metrics.totalSearches;this._metrics.avgSearchLatencyMs=this._metrics.avgSearchLatencyMs*((r-1)/r)+e/r}}});function Z(i,e){let r=Array.from({length:e},()=>new Float64Array(e));for(let t=0;t<e;t++){let n=i[t].length;r[t][t]=n;for(let a of i[t])r[t][a]=-1}return r}function N(i,e){let r=e.length,t=new Float64Array(r);for(let n=0;n<r;n++){let a=i[n].length;t[n]=a*e[n];for(let o of i[n])t[n]-=e[o]}return t}function H(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function R(i){let e=H(i);if(e>0)for(let r=0;r<i.length;r++)i[r]/=e}function v(i,e){let r=0;for(let t=0;t<i.length;t++)r+=i[t]*e[t];for(let t=0;t<i.length;t++)i[t]-=r*e[t]}function y(i,e,r=100,t=1e-6){if(e<=1)return 0;if(e===2)return i[0].includes(1)?2:0;let n=new Float64Array(e).fill(1/Math.sqrt(e)),a=new Float64Array(e);for(let l=0;l<e;l++)a[l]=Math.random()-.5;v(a,n),R(a);let o=0;for(let l=0;l<30;l++){let u=N(i,a);if(v(u,n),o=H(u),o>0)for(let h=0;h<e;h++)a[h]=u[h]/o}if(o<t)return 0;let c=new Float64Array(e);for(let l=0;l<e;l++)c[l]=Math.random()-.5;v(c,n),R(c);let s=0;for(let l=0;l<r;l++){let u=N(i,c),h=new Float64Array(e);for(let f=0;f<e;f++)h[f]=o*c[f]-u[f];v(h,n);let m=H(h);if(m<t)break;let x=m;for(let f=0;f<e;f++)c[f]=h[f]/m;if(Math.abs(x-s)<t)break;s=x}let d=o-s;return Math.max(0,d)}function F(i,e,r=100,t=1e-6){return y(i,e,r,t)}function C(i,e,r=50,t){if(e<=1)return 0;let n=t??y(i,e);if(n<1e-10)return 1/0;let o=2*Math.max(...i.map(d=>d.length),1),s=2*(Math.log(o/n)/(o-n));return Math.max(0,s)}function M(i,e,r){let t=1-Math.exp(-i/.05),n=1-Math.exp(-e/.5),a=r===1/0?0:1/(1+r/5),o=.4*t+.3*n+.3*a;return Math.max(0,Math.min(1,o))}var _=g(()=>{"use strict"});var re={};D(re,{ALERT_THRESHOLDS:()=>fe,DEFAULT_HNSW_HEALTH_CONFIG:()=>ee,HnswHealthMonitor:()=>L,_resetNativeLoader:()=>be,approximateFiedlerValue:()=>y,approximateSpectralGap:()=>F,buildAdjacencyFromIndex:()=>te,buildLaplacian:()=>Z,computeCoherenceScore:()=>M,createHnswHealthMonitor:()=>ge,deflateVector:()=>v,estimateEffectiveResistance:()=>C,laplacianMultiply:()=>N,normalizeInPlace:()=>R,vectorNorm:()=>H});function pe(){return V?T:(V=!0,T=null,null)}function be(){T=null,V=!1}function te(i,e=16,r){let t=i.size();if(t===0)return{adjacency:[],nodeCount:0,adjacencySource:"approximate"};let n=Array.from({length:t},()=>[]),a=Math.min(e,t-1);if(a===0)return{adjacency:n,nodeCount:t,adjacencySource:"approximate"};if(r&&r.size>0){let o=Array.from(r.keys()).slice(0,t),c=new Map;for(let s=0;s<o.length;s++)c.set(o[s],s);for(let s=0;s<o.length;s++){let d=r.get(o[s]);if(!d)continue;let l=i.search(d,a+1);for(let u of l){if(u.id===o[s])continue;let h=c.get(u.id);h!==void 0&&(n[s].includes(h)||n[s].push(h),n[h].includes(s)||n[h].push(s))}}return{adjacency:n,nodeCount:t,adjacencySource:"actual-search"}}console.warn("[HnswHealthMonitor] No stored vectors provided \u2014 using approximate circular adjacency. Pass stored vectors for accurate health metrics.");for(let o=0;o<t;o++)for(let c=0;c<a;c++){let s=(o+c+1)%t;n[o].includes(s)||n[o].push(s),n[s].includes(o)||n[s].push(o)}return{adjacency:n,nodeCount:t,adjacencySource:"approximate"}}function ge(i){return new L(i)}var ee,fe,T,V,L,ne=g(()=>{"use strict";_();_();ee={fiedlerThreshold:.01,spectralGapThreshold:.1,resistanceThreshold:10,coherenceThreshold:.3,maxPowerIterations:100,convergenceTolerance:1e-6,resistanceSampleSize:50,maxHistoryEntries:200,minIndexSize:3},fe={FragileIndex:.01,PoorExpansion:.1,HighResistance:10,LowCoherence:.3},T=null,V=!1;L=class{config;alerts=[];history=[];lastReport=null;useNative=!1;nativeChecked=!1;constructor(e){this.config={...ee,...e}}checkHealth(e){let r=performance.now(),t=e.size();if(t<this.config.minIndexSize)return this.createSmallIndexReport(t,performance.now()-r);this.nativeChecked||(this.nativeChecked=!0,this.useNative=pe()!==null);let{adjacency:n,nodeCount:a,adjacencySource:o}=te(e),c=this.useNative?this.computeNativeMetrics(n):this.computeApproximateMetrics(n,a),s=this.generateAlerts(c);this.alerts.length=0,this.alerts.push(...s);let d=performance.now()-r,l={healthy:s.length===0,metrics:c,alerts:s,indexSize:t,usedNativeBackend:this.useNative,adjacencySource:o,checkDurationMs:d,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:c.coherenceScore,fiedlerValue:c.fiedlerValue,indexSize:t,healthy:l.healthy,timestamp:l.checkedAt}),this.lastReport=l,l}getAlerts(){return[...this.alerts]}getMetricsHistory(e){let r=[...this.history];return e!==void 0&&e<r.length?r.slice(-e):r}isHealthy(){return this.lastReport===null?!0:this.lastReport.healthy}getLastReport(){return this.lastReport}clearHistory(){this.history.length=0,this.alerts.length=0,this.lastReport=null}computeNativeMetrics(e){let r=T,t=r.computeFiedlerValue(e),n=r.computeSpectralGap(e),a=r.computeEffectiveResistance(e),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}computeApproximateMetrics(e,r){let t=y(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),n=F(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),a=C(e,r,this.config.resistanceSampleSize,t),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}generateAlerts(e){let r=[],t=new Date;return e.fiedlerValue<this.config.fiedlerThreshold&&r.push({type:"FragileIndex",message:`Fiedler value ${e.fiedlerValue.toFixed(6)} is below threshold ${this.config.fiedlerThreshold}. The index graph has weak algebraic connectivity.`,value:e.fiedlerValue,threshold:this.config.fiedlerThreshold,timestamp:t}),e.spectralGap<this.config.spectralGapThreshold&&r.push({type:"PoorExpansion",message:`Spectral gap ${e.spectralGap.toFixed(6)} is below threshold ${this.config.spectralGapThreshold}. The index graph has poor expansion properties.`,value:e.spectralGap,threshold:this.config.spectralGapThreshold,timestamp:t}),e.effectiveResistance>this.config.resistanceThreshold&&r.push({type:"HighResistance",message:`Average effective resistance ${e.effectiveResistance.toFixed(4)} exceeds threshold ${this.config.resistanceThreshold}. Nodes are poorly connected.`,value:e.effectiveResistance,threshold:this.config.resistanceThreshold,timestamp:t}),e.coherenceScore<this.config.coherenceThreshold&&r.push({type:"LowCoherence",message:`Coherence score ${e.coherenceScore.toFixed(4)} is below threshold ${this.config.coherenceThreshold}. Overall index health is degraded.`,value:e.coherenceScore,threshold:this.config.coherenceThreshold,timestamp:t}),r}createSmallIndexReport(e,r){let t={fiedlerValue:e>0?1:0,spectralGap:e>0?1:0,effectiveResistance:e>0?.5:0,coherenceScore:e>0?1:0},n={healthy:!0,metrics:t,alerts:[],indexSize:e,usedNativeBackend:!1,adjacencySource:"approximate",checkDurationMs:r,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:t.coherenceScore,fiedlerValue:t.fiedlerValue,indexSize:e,healthy:!0,timestamp:n.checkedAt}),this.lastReport=n,n}addHistoryPoint(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}}});var ye={};D(ye,{HnswAdapter:()=>G});var ve,p,G,xe=g(()=>{O();Y();oe();ve={patterns:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},"qe-memory":{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},learning:{dimensions:384,M:16,efConstruction:200,efSearch:50,metric:"cosine"},coverage:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}},p=new Map,G=class i{backend;_isNativeBackend;indexName;stringToNumericId=new Map;numericToStringId=new Map;nextAutoId=0;healthMonitor=null;healthMonitorLoaded=!1;operationsSinceLastCheck=0;healthCheckFrequency=100;lastHealthReport=null;constructor(e,r){this.indexName=e;let n={...ve[e]??{},...r},{backend:a,isNative:o}=i.createBackend(n);this.backend=a,this._isNativeBackend=o}add(e,r,t){this.backend.add(e,r,t),this.maybeRunHealthCheck()}search(e,r){let t=performance.now(),n=this.backend.search(e,r),a=performance.now()-t;return a>50&&console.warn(`[HNSW] search took ${a.toFixed(1)}ms (k=${r}, results=${n.length})`),this._lastSearchLatencyMs=a,n}_lastSearchLatencyMs=0;get lastSearchLatencyMs(){return this._lastSearchLatencyMs}remove(e){return this.backend.remove(e)}size(){return this.backend.size()}dimensions(){return this.backend.dimensions()}recall(){return this.backend.recall()}addByStringId(e,r){let t=this.stringToNumericId.get(e);t!==void 0?this.backend.remove(t):(t=this.nextAutoId++,this.stringToNumericId.set(e,t),this.numericToStringId.set(t,e)),this.backend.add(t,new Float32Array(r))}searchByArray(e,r){return this.backend.search(new Float32Array(e),r).map(n=>({id:this.numericToStringId.get(n.id)??String(n.id),score:n.score}))}removeByStringId(e){let r=this.stringToNumericId.get(e);if(r===void 0)return!1;let t=this.backend.remove(r);return t&&(this.stringToNumericId.delete(e),this.numericToStringId.delete(r)),t}clear(){this.backend.clear?.(),this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}dispose(){try{this.backend.dispose?.()}catch{}this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}isRuvectorAvailable(){return this.backend instanceof S?this.backend.isRuvectorAvailable():this.backend instanceof w?this.backend.isNativeAvailable():!1}isNativeBackend(){return this._isNativeBackend}getName(){return this.indexName}setHealthCheckFrequency(e){this.healthCheckFrequency=Math.max(1,e)}getHealthCheckFrequency(){return this.healthCheckFrequency}getLastHealthReport(){return this.lastHealthReport}getHealthMonitor(){return this.healthMonitor}maybeRunHealthCheck(){if(q()&&(this.operationsSinceLastCheck++,!(this.operationsSinceLastCheck<this.healthCheckFrequency)&&(this.operationsSinceLastCheck=0,this.ensureHealthMonitor(),this.healthMonitor)))try{this.lastHealthReport=this.healthMonitor.checkHealth(this.backend),this.lastHealthReport.healthy||console.warn(`[HNSW-Health] Index "${this.indexName}" health check failed: ${this.lastHealthReport.alerts.length} alert(s). Coherence: ${this.lastHealthReport.metrics.coherenceScore.toFixed(3)}`)}catch(e){console.warn(`[HNSW-Health] Health check error for "${this.indexName}":`,e)}}ensureHealthMonitor(){if(!this.healthMonitorLoaded){this.healthMonitorLoaded=!0;try{let e=(ne(),$(re));this.healthMonitor=e.createHnswHealthMonitor()}catch(e){process.env.DEBUG&&console.debug("[HNSW-Health] Monitor module unavailable:",e instanceof Error?e.message:e),this.healthMonitor=null}}}static createBackend(e){if(j())try{return{backend:new w(e),isNative:!0}}catch(r){r instanceof b?console.info(`[HNSW] Native backend unavailable, falling back to JS: ${r.message}`):console.warn("[HNSW] Unexpected error creating native backend, falling back to JS:",r)}return{backend:new S(e),isNative:!1}}static create(e,r){let t=p.get(e);if(t instanceof i)return t;let n=new i(e,r);return p.set(e,n),n}static get(e){let r=p.get(e);return r instanceof i?r:void 0}static close(e){let r=p.get(e);r instanceof i&&r.dispose(),p.delete(e)}static closeAll(){for(let[e]of p)i.close(e);p.clear()}static listIndexes(){return Array.from(p.keys())}}});export{G as a,ye as b,xe as c};
|
|
@@ -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.13.
|
|
2
|
-
import{a as P}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.13.4");process.exit(0)}
|
|
2
|
+
import{a as P}from"./chunk-CTNDSP2M.js";import{b as w}from"./chunk-IN5KRJSE.js";import{e as S}from"./chunk-WCUXA3NV.js";import{a as H}from"./chunk-QGH54HTH.js";import{c as A}from"./chunk-E7FCVH32.js";import{b as E,d as q}from"./chunk-HN2DD2DQ.js";import{S as $,j as T}from"./chunk-ERKYIV25.js";q();var W=["oracle:test-exec","judge:llm","proxy:structural"],d="proxy:structural";function j(n){return n&&W.includes(n)?n:d}function m(n,e={}){switch(j(n)){case"oracle:test-exec":return!0;case"judge:llm":return e.allowJudgeTier===!0;default:return!1}}import{createHash as O}from"node:crypto";function D(n,e){let t=n.length;if(t===0)return-1/0;let r=e?.iters??2e3,a=e?.alpha??.05,s=(e?.seed??2654435761)>>>0,o=()=>(s=Math.imul(s,1664525)+1013904223>>>0,s/4294967296),c=new Array(r);for(let u=0;u<r;u++){let l=0;for(let h=0;h<t;h++)l+=n[Math.floor(o()*t)];c[u]=l/t}c.sort((u,l)=>u-l);let i=Math.min(Math.floor(a*r),r-1);return c[i]}function L(n,e){let t=Math.min(n.length,e.length),r=new Array(t);for(let a=0;a<t;a++)r[a]=n[a]-e[a];return r}var U=n=>m(n.provenanceTier,{allowJudgeTier:n.allowJudgeTier})?n.candidateHeldOut>n.baselineHeldOut?w(n.candidateAnchorMean,n.baselineAnchorMean,n.anchorTol)?{promote:!0,reason:"held-out gain, no anchor regression, oracle-tier evidence"}:{promote:!1,reason:`anchor regression: ${n.candidateAnchorMean} < ${n.baselineAnchorMean} - ${n.anchorTol}`}:{promote:!1,reason:`held-out ${n.candidateHeldOut} did not beat baseline ${n.baselineHeldOut}`}:{promote:!1,reason:`provenance tier '${n.provenanceTier}' not allowed to promote`},C=8,x=1e-6,N=n=>n.reduce((e,t)=>e+t,0)/n.length,V=n=>{let e=U(n);if(!e.promote)return e;let t=n.candidateHeldOutSamples,r=n.baselineHeldOutSamples;if(!t||!r||t.length===0||t.length!==r.length)return{promote:!1,reason:"significance gate: missing/mismatched paired held-out samples (need equal-length candidate & baseline per-task vectors)"};if(t.length<C)return{promote:!1,reason:`significance gate: only ${t.length} paired samples (< ${C}) \u2014 a bootstrap CI is not meaningful; fail closed rather than certify noise`};if(Math.abs(N(t)-n.candidateHeldOut)>x||Math.abs(N(r)-n.baselineHeldOut)>x)return{promote:!1,reason:"significance gate: sealed sample means do not match the sealed held-out scalars \u2014 inconsistent/forged evaluation"};let a=D(L(t,r));return a>0?{promote:!0,reason:`${e.reason}; paired gain significant (CI low ${a.toFixed(4)} > 0)`}:{promote:!1,reason:`significance gate: paired held-out gain not significant (95% CI lower bound ${a.toFixed(4)} \u2264 0)`}},se=Object.freeze({"accept/v1":U,"accept/v1+sig":V});function _(n){if(n===null||typeof n!="object")return JSON.stringify(n)??"null";if(Array.isArray(n))return`[${n.map(_).join(",")}]`;let e=n;return`{${Object.keys(e).filter(r=>e[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${_(e[r])}`).join(",")}}`}var Q="aqe:promotion-path-rule:v1+sig",J=n=>m(n.provenanceTier,{allowJudgeTier:n.allowJudgeTier})?n.reward===void 0||n.rewardThreshold===void 0||!(n.reward>=n.rewardThreshold)?{promote:!1,reason:`reward ${n.reward} below threshold ${n.rewardThreshold}`}:n.occurrences===void 0||n.occurrenceThreshold===void 0||!(n.occurrences>=n.occurrenceThreshold)?{promote:!1,reason:`occurrences ${n.occurrences} below threshold ${n.occurrenceThreshold}`}:n.successRate===void 0||n.successRateThreshold===void 0||!(n.successRate>=n.successRateThreshold)?{promote:!1,reason:`success rate ${n.successRate} below threshold ${n.successRateThreshold}`}:n.withinActivityWindow!==!0?{promote:!1,reason:"pattern outside promotion activity window (stale)"}:{promote:!0,reason:"tier allowed; reward/occurrence/success-rate thresholds met; within activity window"}:{promote:!1,reason:`provenance tier '${n.provenanceTier}' not allowed to promote`},G=n=>m(n.provenanceTier,{allowJudgeTier:n.allowJudgeTier})?n.insightConfidence===void 0||n.insightConfidenceThreshold===void 0||!(n.insightConfidence>=n.insightConfidenceThreshold)?{promote:!1,reason:`insight confidence ${n.insightConfidence} below threshold ${n.insightConfidenceThreshold}`}:n.insightActionable!==!0?{promote:!1,reason:"insight produced no actionable reorganization"}:{promote:!0,reason:"tier allowed; insight confidence meets threshold; actionable"}:{promote:!1,reason:`provenance tier '${n.provenanceTier}' not allowed to apply`},M=Object.freeze({"pattern-promote/v1":J,"dream-apply/v1":G});function b(n){return O("sha256").update(_(n)).digest("hex")}function y(n){if(!(n in M))throw new Error(`Unknown promotion-path rule version '${n}' \u2014 cannot fingerprint an unregistered rule.`);return O("sha256").update(Q).update("\0").update(n).digest("hex")}function R(n,e){let t=M[n];if(!t)throw new Error(`Unknown promotion-path rule version '${n}' \u2014 refusing to re-execute an unregistered rule.`);return t(e)}function I(n,e={}){let t=[],r=b(n.sealed)===n.sealedHash;r||t.push("sealIntact");let a=!1;try{let c=y(n.ruleVersion);a=n.ruleFingerprint===c&&(e.pinnedRuleFingerprint===void 0||n.ruleFingerprint===e.pinnedRuleFingerprint)}catch{a=!1}a||t.push("gateUnchanged");let s=!1;r&&a&&(s=(R(n.ruleVersion,n.sealed).promote?"promote":"reject")===n.recordedVerdict),s||t.push("gateReExecutes");let o=t.length===0;return{valid:o,checks:{sealIntact:r,gateUnchanged:a,gateReExecutes:s},failures:t,reason:o?"promotion verified: sealed inputs intact, rule unchanged, frozen rule re-execution reproduces the recorded verdict":`promotion INVALID (failed: ${t.join(", ")}) \u2014 the recorded verdict is not reproducible under the frozen rule`}}H();$();var p=A.create("pattern-lifecycle"),z={promotionRewardThreshold:.7,promotionMinOccurrences:S,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3,maxAgeForActivePatterns:90,promotionActivityWindowDays:30,asymmetricLearning:{},allowJudgeTierPromotion:!1},k=5,B=.9,X=2;function Y(n,e){return e<k||!Number.isFinite(n)?0:Math.min(Math.max(n,0),1)}var v=class{constructor(e,t={}){this.db=e;this.config={...z,...t},this.asymmetricEngine=new P(this.config.asymmetricLearning),this.ensureSchema()}db;config;asymmetricEngine;_witnessChain=null;set witnessChain(e){this._witnessChain=e}_compressionService=null;set compressionService(e){this._compressionService=e}ensureSchema(){try{this.db.prepare(`
|
|
3
3
|
SELECT deprecated_at FROM qe_patterns LIMIT 1
|
|
4
4
|
`).get()}catch(e){p.debug("Adding missing deprecated_at column",{error:e instanceof Error?e.message:String(e)}),this.db.exec(`
|
|
5
5
|
ALTER TABLE qe_patterns ADD COLUMN deprecated_at TEXT DEFAULT NULL
|
|
@@ -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.13.
|
|
2
|
-
import{c as w,d as E,f as T}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.13.4");process.exit(0)}
|
|
2
|
+
import{c as w,d as E,f as T}from"./chunk-GGZB2ZBB.js";var d=E((b,u)=>{"use strict";var _=typeof Buffer<"u",a=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,l=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function p(r,t,e){e==null&&t!==null&&typeof t=="object"&&(e=t,t=void 0),_&&Buffer.isBuffer(r)&&(r=r.toString()),r&&r.charCodeAt(0)===65279&&(r=r.slice(1));let o=JSON.parse(r,t);if(o===null||typeof o!="object")return o;let n=e&&e.protoAction||"error",c=e&&e.constructorAction||"error";if(n==="ignore"&&c==="ignore")return o;if(n!=="ignore"&&c!=="ignore"){if(a.test(r)===!1&&l.test(r)===!1)return o}else if(n!=="ignore"&&c==="ignore"){if(a.test(r)===!1)return o}else if(l.test(r)===!1)return o;return y(o,{protoAction:n,constructorAction:c,safe:e&&e.safe})}function y(r,{protoAction:t="error",constructorAction:e="error",safe:o}={}){let n=[r];for(;n.length;){let c=n;n=[];for(let s of c){if(t!=="ignore"&&Object.prototype.hasOwnProperty.call(s,"__proto__")){if(o===!0)return null;if(t==="error")throw new SyntaxError("Object contains forbidden prototype property");delete s.__proto__}if(e!=="ignore"&&Object.prototype.hasOwnProperty.call(s,"constructor")&&s.constructor!==null&&typeof s.constructor=="object"&&Object.prototype.hasOwnProperty.call(s.constructor,"prototype")){if(o===!0)return null;if(e==="error")throw new SyntaxError("Object contains forbidden prototype property");delete s.constructor}for(let h in s){let f=s[h];f&&typeof f=="object"&&n.push(f)}}}return r}function i(r,t,e){let{stackTraceLimit:o}=Error;Error.stackTraceLimit=0;try{return p(r,t,e)}finally{Error.stackTraceLimit=o}}function m(r,t){let{stackTraceLimit:e}=Error;Error.stackTraceLimit=0;try{return p(r,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=e}}u.exports=i;u.exports.default=i;u.exports.parse=i;u.exports.safeParse=m;u.exports.scan=y});function F(r){return g.default.parse(r,void 0,{protoAction:"remove",constructorAction:"remove"})}function j(r,t){try{return F(r)}catch(e){throw new Error(`Invalid JSON in --${t}: ${e instanceof Error?e.message:"Parse error"}`)}}var g,O=w(()=>{"use strict";g=T(d(),1)});export{d as a,F as b,j 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.13.
|
|
2
|
-
import{e as l,l as i}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.13.4");process.exit(0)}
|
|
2
|
+
import{e as l,l as i}from"./chunk-NQJLUY2K.js";import{a as r,c as g}from"./chunk-KDICUKYX.js";g();var c=class extends i{config={name:"qe/tests/schedule",description:"Schedule and execute tests using phase-based pipeline with git-aware selection and flaky tracking. Runs tests in phases (unit, integration, e2e), selects affected tests from git changes, and tracks flaky tests.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{cwd:{type:"string",description:"Working directory for test execution (defaults to project root)"},gitRef:{type:"string",description:'Git ref to compare for affected test selection (e.g., "main", "HEAD~3")'},useGitAware:{type:"boolean",description:"Enable git-aware test selection to only run affected tests",default:!0},trackFlaky:{type:"boolean",description:"Enable flaky test tracking and quarantine",default:!0}}}}async execute(s,o){try{let{runTestPipeline:n}=await import("./test-scheduling-5WKIWH4H.js"),d=await l(o),t=await n({cwd:s.cwd||process.cwd(),memory:d,baseRef:s.gitRef,flakyHistoryPath:s.trackFlaky!==!1?".agentic-qe/flaky-history.json":void 0,runAllTests:s.useGitAware===!1}),u=t.phaseResults.reduce((e,a)=>e+a.totalTests,0),f=t.phaseResults.reduce((e,a)=>e+a.passed,0),p=t.phaseResults.reduce((e,a)=>e+a.failed,0);return{success:!0,data:{pipelineId:o.requestId,phases:t.phaseResults.map(e=>({phaseId:e.phaseId,phaseName:e.phaseName,totalTests:e.totalTests,passed:e.passed,failed:e.failed,passRate:e.passRate,durationMs:e.durationMs})),gitAware:{enabled:!t.ranAllTests,selectedTests:t.selectedTests.length,gitRef:s.gitRef},flakyTracking:{enabled:s.trackFlaky!==!1},totalDuration:t.totalDurationMs,ranAllTests:t.ranAllTests,summary:`Executed ${t.phaseResults.length} phases, ${u} tests (${f} passed, ${p} failed) in ${t.totalDurationMs}ms`}}}catch(n){return{success:!1,error:r(n)}}}};export{c as a};
|
|
@@ -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.13.
|
|
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.13.4");process.exit(0)}
|
|
2
2
|
import{createHash as o}from"node:crypto";import a from"node:fs";function c(r){let n=[...r].sort((e,t)=>e.id.localeCompare(t.id)).map(e=>({id:e.id,inputUnderTest:e.inputUnderTest,moduleName:e.moduleName,referenceImpl:e.referenceImpl,requirements:e.requirements,expectedMutants:e.expectedMutants}));return JSON.stringify(n)}function s(r){return o("sha256").update(c(r)).digest("hex")}function u(r){let n=JSON.parse(a.readFileSync(r,"utf8")),e=s(n.items);if(e!==n.contentHash)throw new Error(`Anchor set hash drift at ${r}: recorded ${n.contentHash}, recomputed ${e}. Refusing to load a mutated frozen anchor (ADR-117). A legitimate change must be a versioned re-freeze (qe-anchor-v2), never an in-place edit.`);if(n.items.length===0)throw new Error(`Anchor set at ${r} has no items \u2014 a frozen anchor must be non-empty.`);return n}function h(r,n,e){return r>=n-e}export{u as a,h as b};
|
|
@@ -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.13.
|
|
2
|
-
import{a as _}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.13.4");process.exit(0)}
|
|
2
|
+
import{a as _}from"./chunk-FZ4MUDHZ.js";import{a as w}from"./chunk-W37WY3OL.js";import{c as k}from"./chunk-A2G26WU4.js";import{i as M,m as U}from"./chunk-ZAT65V6I.js";import{b as f,d as P}from"./chunk-HN2DD2DQ.js";import{a as g,c as F}from"./chunk-KDICUKYX.js";import{a as R}from"./chunk-GGZB2ZBB.js";import{randomUUID as N}from"crypto";U();P();F();var x={alpha:.1,minOutcomes:10,weightFloor:.2,weightCeiling:2},p=class{records=new Map;config;constructor(e){this.config={...x,...e}}recordOutcome(e,t,o){let{alpha:i,minOutcomes:r,weightFloor:s,weightCeiling:n}=this.config,c=this.records.get(e),d=t?1:0,a=Math.max(0,Math.min(1,o)),l,u;c?(l=i*d+(1-i)*c.emaAccuracy,u=i*a+(1-i)*c.emaQuality):(l=d,u=a);let h=(c?.totalOutcomes??0)+1,C;h>=r?C=Math.max(s,Math.min(n,l*2)):C=1;let S={agentId:e,emaAccuracy:l,emaQuality:u,calibratedWeight:C,totalOutcomes:h,lastUpdated:new Date};return this.records.set(e,S),S}getCalibration(e){return this.records.get(e)??null}getCalibratedWeight(e){let t=this.records.get(e);return!t||t.totalOutcomes<this.config.minOutcomes?1:t.calibratedWeight}getAllCalibrations(){return Array.from(this.records.values())}reset(e){e!==void 0?this.records.delete(e):this.records.clear()}serialize(){let e={};for(let[t,o]of this.records)e[t]={...o};return e}deserialize(e){this.records.clear();for(let[t,o]of Object.entries(e))this.records.set(t,{...o,lastUpdated:new Date(o.lastUpdated)})}};var D={escalateAfterFailures:2,deEscalateAfterSuccesses:5,maxTier:"opus",minTier:"haiku"},q=["booster","haiku","sonnet","opus"],b=class{config;tierOrder;states=new Map;constructor(e){this.config={...D,...e},this.tierOrder=this.config.tierOrder??q}tierIndex(e){return this.tierOrder.indexOf(e)}recordOutcome(e,t,o){let i=this.states.get(e);i||(i={agentId:e,currentTier:o,baseTier:o,consecutiveFailures:0,consecutiveSuccesses:0,escalationCount:0,deEscalationCount:0,lastAction:"none",lastActionTimestamp:new Date},this.states.set(e,i));let r=i.currentTier;if(t){if(i.consecutiveSuccesses++,i.consecutiveFailures=0,i.consecutiveSuccesses>=this.config.deEscalateAfterSuccesses){let s=this.tierIndex(i.currentTier),n=this.tierIndex(this.config.minTier);if(s>n)return i.currentTier=this.tierOrder[s-1],i.deEscalationCount++,i.consecutiveSuccesses=0,i.lastAction="de-escalate",i.lastActionTimestamp=new Date,{action:"de-escalate",previousTier:r,newTier:i.currentTier}}}else if(i.consecutiveFailures++,i.consecutiveSuccesses=0,i.consecutiveFailures>=this.config.escalateAfterFailures){let s=this.tierIndex(i.currentTier),n=this.tierIndex(this.config.maxTier);if(s>=0&&s<n)return i.currentTier=this.tierOrder[s+1],i.escalationCount++,i.consecutiveFailures=0,i.lastAction="escalate",i.lastActionTimestamp=new Date,{action:"escalate",previousTier:r,newTier:i.currentTier}}return{action:"none",previousTier:r,newTier:i.currentTier}}getCurrentTier(e){return this.states.get(e)?.currentTier??null}getState(e){return this.states.get(e)??null}getAllStates(){return Array.from(this.states.values())}reset(e){e?this.states.delete(e):this.states.clear()}};var T={booster:{avgInputTokens:0,avgOutputTokens:0,costPerTask:0},haiku:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.0035},sonnet:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.021},opus:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.105}},v=["booster","haiku","sonnet","opus"],y=T.opus.costPerTask,I={qualityWeight:.6,costWeight:.4,budgetPerHourUsd:0,budgetPerDayUsd:0,minQualityThreshold:.5,enabled:!0},L=.15,E=class{config;costTracker;tierQualityEstimates=new Map;tierOutcomeCounts=new Map;constructor(e,t){let o={...I,...t};o.qualityWeight=Math.max(0,Math.min(1,o.qualityWeight)),o.costWeight=Math.max(0,Math.min(1,o.costWeight)),o.minQualityThreshold=Math.max(0,Math.min(1,o.minQualityThreshold)),o.budgetPerHourUsd=Math.max(0,o.budgetPerHourUsd),o.budgetPerDayUsd=Math.max(0,o.budgetPerDayUsd);let i=o.qualityWeight+o.costWeight;i>0&&i!==1&&(o.qualityWeight/=i,o.costWeight/=i),this.config=o,this.costTracker=e,this.tierQualityEstimates.set("booster",.3),this.tierQualityEstimates.set("haiku",.55),this.tierQualityEstimates.set("sonnet",.75),this.tierQualityEstimates.set("opus",.9)}scoreTiers(e){let t=v.map(o=>{let i=this.getQualityEstimate(o,e),r=T[o].costPerTask,s=r>0?i/r:i>0?1/0:0,n=y>0?1-r/y:1,c=this.config.qualityWeight*i+this.config.costWeight*n;return{tier:o,qualityScore:i,estimatedCostUsd:r,qualityPerDollar:s,economicScore:c}});return t.sort((o,i)=>i.economicScore-o.economicScore),t}selectTier(e){let t=this.scoreTiers(e);for(let r of t)if(!(r.qualityScore<this.config.minQualityThreshold)&&!this.wouldExceedBudget(r.tier))return{tier:r.tier,reason:`Best economic score (${r.economicScore.toFixed(3)}): quality=${r.qualityScore.toFixed(2)}, cost=$${r.estimatedCostUsd.toFixed(4)}`,scores:t};let o=t.filter(r=>r.qualityScore>=this.config.minQualityThreshold);if(o.length>0){let r=[...o].sort((s,n)=>s.estimatedCostUsd-n.estimatedCostUsd)[0];return{tier:r.tier,reason:`Budget constrained fallback to ${r.tier}`,scores:t}}let i=[...t].sort((r,s)=>s.qualityScore-r.qualityScore)[0];return{tier:i.tier,reason:`No tier meets quality threshold ${this.config.minQualityThreshold}; using best quality: ${i.tier}`,scores:t}}wouldExceedBudget(e){let t=T[e].costPerTask;if(t===0)return!1;let o=this.costTracker.getCurrentCost("hour"),i=this.costTracker.getCurrentCost("day");return this.config.budgetPerHourUsd>0&&o+t>this.config.budgetPerHourUsd||this.config.budgetPerDayUsd>0&&i+t>this.config.budgetPerDayUsd}updateFromOutcome(e,t){let o=e.outcome.qualityScore,i=this.tierQualityEstimates.get(t)??.5,r=this.tierOutcomeCounts.get(t)??0,s=r<5?.4:L,n=i*(1-s)+o*s;this.tierQualityEstimates.set(t,n),this.tierOutcomeCounts.set(t,r+1)}getEconomicReport(){let e=this.scoreTiers(.5),t=this.costTracker.getCurrentCost("hour"),o=this.costTracker.getCurrentCost("day"),i={hourly:this.config.budgetPerHourUsd>0?Math.max(0,this.config.budgetPerHourUsd-t):null,daily:this.config.budgetPerDayUsd>0?Math.max(0,this.config.budgetPerDayUsd-o):null},r=null,s=[...e].sort((a,l)=>l.qualityPerDollar-a.qualityPerDollar),n=s.find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar)),c=[...s].reverse().find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar));if(n&&c&&n.tier!==c.tier){let a=c.estimatedCostUsd-n.estimatedCostUsd;a>0&&(r={usd:a,description:`Switch from ${c.tier} ($${c.estimatedCostUsd.toFixed(4)}/task) to ${n.tier} ($${n.estimatedCostUsd.toFixed(4)}/task) for comparable tasks to save ~$${a.toFixed(4)}/task`})}let d=this.generateRecommendation(e,i);return{tierEfficiency:e,currentHourlyCostUsd:t,currentDailyCostUsd:o,budgetRemaining:i,recommendation:d,savingsOpportunity:r}}computeCostAdjustedReward(e,t,o){let i=T[t].costPerTask;if(y===0)return e;let r=i/y,s=Math.max(0,o-this.config.minQualityThreshold),n=r*(1-s),c=e-n*this.config.costWeight;return Math.max(-1,Math.min(1,c))}serializeEstimates(){let e={};for(let t of v)e[t]={quality:this.tierQualityEstimates.get(t)??.5,count:this.tierOutcomeCounts.get(t)??0};return e}deserializeEstimates(e){for(let t of v)e[t]&&(this.tierQualityEstimates.set(t,e[t].quality),this.tierOutcomeCounts.set(t,e[t].count))}getConfig(){return{...this.config}}getQualityEstimate(e,t){let o=this.tierQualityEstimates.get(e)??.5,i=e==="booster"?t*.4:e==="haiku"?t*.2:0;return Math.max(0,Math.min(1,o-i))}generateRecommendation(e,t){if(t.hourly!==null&&t.hourly<.01)return"Hourly budget nearly exhausted. Consider increasing budget or routing to cheaper tiers.";if(t.daily!==null&&t.daily<.1)return"Daily budget nearly exhausted. Only critical tasks should use expensive tiers.";let o=e[0];return o?`Most cost-efficient tier: ${o.tier} (score=${o.economicScore.toFixed(3)}, quality=${o.qualityScore.toFixed(2)})`:"No economic data available yet."}};var A=class{outcomes=[];maxOutcomes;constructor(e=1e4){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getByAgent(e,t=100){return this.outcomes.filter(o=>o.usedAgent===e).slice(-t)}getAll(e=1e3){return this.outcomes.slice(-e)}getRecentOverrides(e=50){return this.outcomes.filter(t=>!t.followedRecommendation).slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},O=class m{static schemaMigrated=!1;outcomeStore;router=null;db=null;calibrator=null;escalationTracker=null;economicModel=null;economicPersistCounter=0;static ECONOMIC_PERSIST_INTERVAL=10;persistCount=0;maxOutcomes;static RETENTION_CLEANUP_INTERVAL=100;constructor(e=1e4,t){this.maxOutcomes=e,this.outcomeStore=new A(e),t?.enableEMACalibration&&this.enableCalibration(),t?.enableAutoEscalation&&this.enableAutoEscalation()}async initialize(){try{this.db=M(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb(),this.loadCalibratorState()}catch(e){console.warn("[RoutingFeedbackCollector] DB init failed, using memory-only:",g(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
|
|
3
3
|
SELECT * FROM routing_outcomes ORDER BY created_at DESC LIMIT ?
|
|
4
4
|
`).all(this.maxOutcomes);for(let o of t.reverse()){let i={id:o.id,task:f(o.task_json),decision:f(o.decision_json),usedAgent:o.used_agent,followedRecommendation:!!o.followed_recommendation,outcome:{success:!!o.success,qualityScore:o.quality_score,durationMs:o.duration_ms,error:o.error||void 0},timestamp:new Date(o.created_at),advisorConsultation:o.advisor_consultation_json?f(o.advisor_consultation_json):void 0};this.outcomeStore.add(i)}t.length>0&&console.log(`[RoutingFeedbackCollector] Loaded ${t.length} outcomes from DB`)}persistOutcome(e){if(this.db)try{let t=this.db.getDatabase();if(!m.schemaMigrated){for(let r of["ALTER TABLE routing_outcomes ADD COLUMN model_tier TEXT","ALTER TABLE routing_outcomes ADD COLUMN advisor_consultation_json TEXT"])try{t.prepare(r).run()}catch{}_(t),m.schemaMigrated=!0}let o=this.inferTier(e.usedAgent),i=e.advisorConsultation?JSON.stringify(e.advisorConsultation):null;t.prepare(`
|
|
5
5
|
INSERT OR REPLACE INTO routing_outcomes (
|
|
@@ -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.13.
|
|
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.13.4");process.exit(0)}
|
|
2
2
|
var h=class{executionHistory=[];learnedDurations=new Map;runCount=0;lastPrunedCount=0;learningRate;maxHistorySize;constructor(t){this.learningRate=t?.learningRate??.3,this.maxHistorySize=t?.maxHistorySize??1e4}buildTestDAG(t){let e=new Map,n=new Map;for(let i of t){let s=this.applyLearnedDuration(i);e.set(s.id,s),n.set(s.id,[])}for(let i of t)for(let s of i.dependencies){if(!e.has(s))throw new Error(`Test '${i.id}' depends on '${s}' which does not exist in the test set`);n.get(s).push(i.id)}let o=this.computeCriticalPath(e,n),a=this.computeParallelGroups(e,n);return{nodes:e,edges:n,criticalPath:o,parallelGroups:a}}findCriticalPath(t){return t.criticalPath.map(e=>t.nodes.get(e)).filter(e=>e!==void 0)}findParallelBranches(t){return t.parallelGroups.map(e=>e.map(n=>t.nodes.get(n)).filter(n=>n!==void 0))}pruneByMinCut(t,e){let n=this.sumDurations(t.nodes);if(n<=e)return this.lastPrunedCount=0,t;let o=this.computeAttentionScores(t),a=Array.from(o.entries()).sort((r,l)=>r[1]-l[1]),i=new Set(t.criticalPath),s=new Set,c=n;for(let[r]of a){if(c<=e)break;if(i.has(r)||(t.edges.get(r)??[]).some(p=>!s.has(p)))continue;let d=t.nodes.get(r);d&&(s.add(r),c-=d.estimatedDuration)}this.lastPrunedCount=s.size;let u=Array.from(t.nodes.values()).filter(r=>!s.has(r.id));return this.buildTestDAG(u)}schedule(t){if(t.length===0)return{phases:[],totalEstimatedTime:0,criticalPathTime:0,parallelism:0};let e=this.buildTestDAG(t),o=this.findParallelBranches(e).map(u=>({tests:u,canRunInParallel:u.length>1})),a=this.computeCriticalPathDuration(e),i=this.sumDurations(e.nodes),s=o.reduce((u,r)=>r.canRunInParallel?u+Math.max(...r.tests.map(l=>l.estimatedDuration)):u+r.tests.reduce((l,d)=>l+d.estimatedDuration,0),0),c=s>0?i/s:1;return this.runCount++,{phases:o,totalEstimatedTime:s,criticalPathTime:a,parallelism:c}}getOptimizationStats(){return{totalTests:0,criticalPathLength:0,parallelGroupCount:0,prunedTests:this.lastPrunedCount,estimatedTimeSaved:0,historicalRuns:this.runCount,usingNativeBackend:!1}}recordExecution(t,e,n){this.executionHistory.push({testId:t,actualDuration:e,result:n,timestamp:Date.now()}),this.executionHistory.length>this.maxHistorySize&&(this.executionHistory=this.executionHistory.slice(-this.maxHistorySize));let o=this.learnedDurations.get(t);o!==void 0?this.learnedDurations.set(t,o*(1-this.learningRate)+e*this.learningRate):this.learnedDurations.set(t,e)}getLearnedDuration(t){return this.learnedDurations.get(t)}isNativeBackendAvailable(){return!1}computeCriticalPath(t,e){let n=this.topologicalSort(t,e);if(n.length===0)return[];let o=new Map,a=new Map;for(let r of n)o.set(r,t.get(r).estimatedDuration),a.set(r,null);for(let r of n){let l=o.get(r);for(let d of e.get(r)??[]){let p=t.get(d);if(!p)continue;let g=l+p.estimatedDuration;g>(o.get(d)??0)&&(o.set(d,g),a.set(d,r))}}let i=0,s=null;for(let[r,l]of o)l>i&&(i=l,s=r);if(!s)return[];let c=[],u=s;for(;u!==null;)c.unshift(u),u=a.get(u)??null;return c}computeCriticalPathDuration(t){return t.criticalPath.reduce((e,n)=>e+(t.nodes.get(n)?.estimatedDuration??0),0)}computeParallelGroups(t,e){let n=this.topologicalSort(t,e);if(n.length===0)return[];let o=new Map;for(let[u,r]of t)o.set(u,new Set(r.dependencies));let a=new Map;for(let u of n){let r=-1;for(let l of o.get(u)??new Set){let d=a.get(l);d!==void 0&&d>r&&(r=d)}a.set(u,r+1)}let i=new Map;for(let u of n){let r=a.get(u)??0;i.has(r)||i.set(r,[]),i.get(r).push(u)}let s=Math.max(...Array.from(i.keys()),-1),c=[];for(let u=0;u<=s;u++){let r=i.get(u);r&&r.length>0&&c.push(r)}return c}computeAttentionScores(t){let e=new Map,n=this.countTransitiveDependents(t);for(let[o,a]of t.nodes){let i=a.lastResult==="fail"?2:1,s=n.get(o)??0;e.set(o,a.priority*i*(1+s))}return e}countTransitiveDependents(t){let e=new Map,n=new Map,o=a=>{if(n.has(a))return n.get(a);let i=new Set;for(let s of t.edges.get(a)??[]){i.add(s);for(let c of o(s))i.add(c)}return n.set(a,i),i};for(let a of t.nodes.keys())e.set(a,o(a).size);return e}topologicalSort(t,e){let n=new Map;for(let i of t.keys())n.set(i,0);for(let i of e.values())for(let s of i)n.has(s)&&n.set(s,(n.get(s)??0)+1);let o=[];for(let[i,s]of n)s===0&&o.push(i);let a=[];for(;o.length>0;){let i=o.shift();a.push(i);for(let s of e.get(i)??[]){let c=(n.get(s)??0)-1;n.set(s,c),c===0&&o.push(s)}}if(a.length!==t.size)throw new Error(`Cycle detected in test DAG: sorted ${a.length} of ${t.size} nodes`);return a}applyLearnedDuration(t){let e=this.learnedDurations.get(t.id);return e!==void 0?{...t,estimatedDuration:Math.round(e)}:t}sumDurations(t){let e=0;for(let n of t.values())e+=n.estimatedDuration;return e}};function m(f){return new h(f)}export{h as a,m as b};
|
|
@@ -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.13.
|
|
2
|
-
import{a as n}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.13.4");process.exit(0)}
|
|
2
|
+
import{a as n}from"./chunk-6VNUASTQ.js";import{a as o}from"./chunk-TCYSMSBO.js";import{a,e as c}from"./chunk-SJ26ZR75.js";c();var M=a.CLEANUP_INTERVAL_MS,y=".agentic-qe/memory.db";async function d(r,t=!0){let e;switch(r.type){case"memory":e=new o;break;case"sqlite":e=new n({sqlite:r.sqlite,enableFallback:!0});break;case"agentdb":e=new n({sqlite:{path:r.agentdb?.path??y},enableFallback:!0});break;case"hybrid":e=new n(r.hybrid);break;default:throw new Error(`Unknown memory backend type: ${r.type}`)}return t&&await e.initialize(),{backend:e,type:r.type,initialized:t}}async function u(r=!0){let t=process.env.AQE_MEMORY_BACKEND??"memory",e=process.env.AQE_MEMORY_PATH??".agentic-qe",i={type:t,sqlite:{path:`${e}/memory.db`,walMode:!0},agentdb:{path:`${e}/memory.db`},hybrid:{enableFallback:!0,sqlite:{path:`${e}/memory.db`}}};return d(i,r)}export{d as a,u as b};
|
|
@@ -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.13.
|
|
2
|
-
import{a as w,b as E}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.13.4");process.exit(0)}
|
|
2
|
+
import{a as w,b as E}from"./chunk-KB4S7MGB.js";import{a as T}from"./chunk-VOAXVNO5.js";import{a as C}from"./chunk-WCUXA3NV.js";import{l as D,m as F}from"./chunk-ZAT65V6I.js";import{a as R,c as A}from"./chunk-KDICUKYX.js";import{g as O}from"./chunk-GGZB2ZBB.js";import{createHash as M}from"crypto";function I(){let s="3.13.4",e=(process.env.AQE_SESSION_CACHE_SALT??"").trim();return e?`${s}+${e}`:s}var $={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function x(s){if(s==null||typeof s!="object")return JSON.stringify(s);if(Array.isArray(s))return"["+s.map(i=>x(i)).join(",")+"]";let e=s;return"{"+Object.keys(e).sort().map(i=>JSON.stringify(i)+":"+x(e[i])).join(",")+"}"}var b=class{cache=new Map;config;hits=0;misses=0;constructor(e){this.config={...$,...e}}computeFingerprint(e,t,r){let i=x({action:t,build:I(),domain:e,input:r});return M("sha256").update(i).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,r,i,n){if(!this.config.enabled)return;this.cache.size>=this.config.maxEntries&&this.evictOldest();let o={fingerprint:e,domain:t,action:r,result:i,tokensSaved:n,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,o),this.config.persistToDb&&this.persistEntry(o)}loadFromDb(){try{let e=S();if(!e)return;let t=Date.now()-this.config.ttlMs,r=e.prepare(`SELECT key, value FROM kv_store
|
|
3
3
|
WHERE namespace = 'session_cache'
|
|
4
4
|
AND created_at > ?
|
|
5
5
|
ORDER BY created_at DESC LIMIT ?`).all(t,this.config.maxEntries);for(let i of r)try{let n=JSON.parse(i.value);Date.now()-n.cachedAt<=this.config.ttlMs&&this.cache.set(n.fingerprint,n)}catch{}}catch{}}getStats(){let e=this.hits+this.misses,t=0;for(let r of this.cache.values())t+=r.tokensSaved*r.hitCount;return{size:this.cache.size,hits:this.hits,misses:this.misses,hitRate:e>0?this.hits/e:0,estimatedTokensSaved:t}}clear(){this.cache.clear(),this.hits=0,this.misses=0}invalidateDomain(e){let t=0;for(let[r,i]of this.cache)i.domain===e&&(this.cache.delete(r),this.deletePersisted(i.fingerprint),t++);return t}evictOldest(){let e=null,t=1/0;for(let[r,i]of this.cache)i.cachedAt<t&&(t=i.cachedAt,e=r);e&&this.cache.delete(e)}persistEntry(e){try{let t=S();if(!t)return;t.prepare(`INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
|