agentic-qe 3.13.3 → 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/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/skills-manifest.json +1 -1
- package/.codex/hooks/aqe-codex-hook.cjs +34 -9
- package/.codex/hooks.json +9 -9
- package/CHANGELOG.md +42 -0
- 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-YIGGREZN.js → agent-booster-wasm-PR3RQWXF.js} +2 -2
- package/dist/cli/chunks/{agent-handler-64O7R55A.js → agent-handler-J5EPFBSZ.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-2ZZBYUP3.js → agent-memory-branch-CCHI6QAA.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-TVTNP76S.js +2 -0
- package/dist/cli/chunks/{arena-PF5WL2WM.js → arena-KMKBGSMY.js} +2 -2
- package/dist/cli/chunks/{arena-6YRNQNCX.js → arena-SI7IPVZ3.js} +4 -4
- package/dist/cli/chunks/{audit-R53FOYCK.js → audit-ZDKR3HT6.js} +3 -3
- package/dist/cli/chunks/base-WBCYKM45.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-QOULNHXS.js → better-sqlite3-FXJFG2WH.js} +2 -2
- package/dist/cli/chunks/{brain-handler-J4ICUOUX.js → brain-handler-MSYMTM5B.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-YVPD43TG.js → branch-enumerator-FRAHCBTO.js} +2 -2
- package/dist/cli/chunks/{browser-TKVHX53S.js → browser-4KHKVNYC.js} +2 -2
- package/dist/cli/chunks/browser-workflow-4JM3IWCS.js +2 -0
- package/dist/cli/chunks/{chunk-GSG5FASF.js → chunk-26SNR2EK.js} +3 -3
- package/dist/cli/chunks/{chunk-JG267MVB.js → chunk-27FWRWOB.js} +2 -2
- package/dist/cli/chunks/{chunk-NIA6VTIH.js → chunk-27REOPQK.js} +2 -2
- package/dist/cli/chunks/{chunk-4RYU4WMW.js → chunk-2Q73TQUQ.js} +1 -1
- package/dist/cli/chunks/{chunk-A22RTEJ3.js → chunk-344CLTV7.js} +2 -2
- package/dist/cli/chunks/{chunk-MGKJFO57.js → chunk-3RSF7POD.js} +2 -2
- package/dist/cli/chunks/{chunk-CVFUANMU.js → chunk-44SYMJ4T.js} +2 -2
- package/dist/cli/chunks/{chunk-22WFXSXB.js → chunk-4FP4PJ45.js} +2 -2
- package/dist/cli/chunks/{chunk-DTOKJKSE.js → chunk-4HVVVVUF.js} +2 -2
- package/dist/cli/chunks/{chunk-QGJYKXUO.js → chunk-55E62F4T.js} +1 -1
- package/dist/cli/chunks/{chunk-RWPWD5GG.js → chunk-56QR72EB.js} +2 -2
- package/dist/cli/chunks/{chunk-NUPAGPN6.js → chunk-5DESO7E4.js} +2 -2
- package/dist/cli/chunks/{chunk-PHNNAIFA.js → chunk-5IVXM3TE.js} +1 -1
- package/dist/cli/chunks/{chunk-TW5QWNT4.js → chunk-5R26MAMK.js} +2 -2
- package/dist/cli/chunks/{chunk-IZIYFVAZ.js → chunk-5RVWL2U3.js} +3 -3
- package/dist/cli/chunks/{chunk-OX6WPOGR.js → chunk-6BHRSGR7.js} +3 -3
- package/dist/cli/chunks/{chunk-4Z2AKQP4.js → chunk-6CZUQA4G.js} +1 -1
- package/dist/cli/chunks/{chunk-FGIZVGIE.js → chunk-6GNVVQW3.js} +2 -2
- package/dist/cli/chunks/{chunk-7AHQ7ROU.js → chunk-6VNUASTQ.js} +2 -2
- package/dist/cli/chunks/{chunk-B7XZJBMT.js → chunk-6XCULO27.js} +2 -2
- package/dist/cli/chunks/{chunk-LOZRBK2Z.js → chunk-6XVP6BGM.js} +2 -2
- package/dist/cli/chunks/{chunk-APXJJRU4.js → chunk-75CFWCQV.js} +2 -2
- package/dist/cli/chunks/{chunk-37GCWGXT.js → chunk-7EL5QEMJ.js} +2 -2
- package/dist/cli/chunks/{chunk-3NML6POU.js → chunk-7YAHECC5.js} +2 -2
- package/dist/cli/chunks/{chunk-N3KQRDTM.js → chunk-A2G26WU4.js} +1 -1
- package/dist/cli/chunks/{chunk-X737I4SO.js → chunk-AROPZPNG.js} +1 -1
- package/dist/cli/chunks/{chunk-IKPBQZQP.js → chunk-BQRCNRTJ.js} +2 -2
- package/dist/cli/chunks/{chunk-JLFU5SCI.js → chunk-C3AF5Z55.js} +2 -2
- package/dist/cli/chunks/{chunk-FF53QW6C.js → chunk-C75V5PTW.js} +1 -1
- package/dist/cli/chunks/{chunk-HJNFXYX4.js → chunk-CQP6BDSF.js} +1 -1
- package/dist/cli/chunks/{chunk-ADBTOUOX.js → chunk-CTNDSP2M.js} +1 -1
- package/dist/cli/chunks/{chunk-VRTNRI4H.js → chunk-CW7LDLJ2.js} +2 -2
- package/dist/cli/chunks/{chunk-PHBGMXTR.js → chunk-DQ247474.js} +2 -2
- package/dist/cli/chunks/{chunk-66KIIH6V.js → chunk-E7FCVH32.js} +2 -2
- package/dist/cli/chunks/{chunk-64C4SS66.js → chunk-EEHEMDNV.js} +2 -2
- package/dist/cli/chunks/{chunk-2MLPO3RZ.js → chunk-EPSF2ERW.js} +2 -2
- package/dist/cli/chunks/{chunk-AXXFY7PX.js → chunk-ERKYIV25.js} +2 -2
- package/dist/cli/chunks/{chunk-VFZNVJP2.js → chunk-ESMSH7HG.js} +2 -2
- package/dist/cli/chunks/{chunk-PS32DXYF.js → chunk-EUIUWZF4.js} +3 -3
- package/dist/cli/chunks/{chunk-764G7VK6.js → chunk-FBXWU37F.js} +1 -1
- package/dist/cli/chunks/{chunk-NF2N2FIY.js → chunk-FJSL7TWU.js} +1 -1
- package/dist/cli/chunks/{chunk-6I2L22WS.js → chunk-FZ4MUDHZ.js} +1 -1
- package/dist/cli/chunks/{chunk-62F5M5OO.js → chunk-GGZB2ZBB.js} +1 -1
- package/dist/cli/chunks/{chunk-HOIH542Y.js → chunk-GIU26D5G.js} +1 -1
- package/dist/cli/chunks/{chunk-7TG7LJAB.js → chunk-GNFKG2LX.js} +2 -2
- package/dist/cli/chunks/{chunk-J5AIMM2J.js → chunk-GOFP47XU.js} +1 -1
- package/dist/cli/chunks/{chunk-AJ45QR3K.js → chunk-GOHWEQEP.js} +2 -2
- package/dist/cli/chunks/{chunk-MNEQESQJ.js → chunk-GRMKN44A.js} +3 -3
- package/dist/cli/chunks/{chunk-H4XZOIV6.js → chunk-HGBVGEUE.js} +2 -2
- package/dist/cli/chunks/{chunk-JQTDNUHA.js → chunk-HGY62IYZ.js} +2 -2
- package/dist/cli/chunks/{chunk-2G2XD6EM.js → chunk-HN2DD2DQ.js} +2 -2
- package/dist/cli/chunks/{chunk-N4OBRS6S.js → chunk-II2RP3MY.js} +2 -2
- package/dist/cli/chunks/{chunk-CXPMA7LY.js → chunk-IN5KRJSE.js} +1 -1
- package/dist/cli/chunks/{chunk-TNM7X2GD.js → chunk-ISGKDLZ7.js} +2 -2
- package/dist/cli/chunks/{chunk-TGVDKSSS.js → chunk-ITQCSIYG.js} +1 -1
- package/dist/cli/chunks/{chunk-PY55ZD2G.js → chunk-IU5SILCS.js} +2 -2
- package/dist/cli/chunks/{chunk-JOHWWTJF.js → chunk-IUFNB6I6.js} +2 -2
- package/dist/cli/chunks/{chunk-UAXFRKR3.js → chunk-IVZA5XTW.js} +2 -2
- package/dist/cli/chunks/{chunk-A6J5MAVO.js → chunk-JBHGMLN7.js} +10 -10
- package/dist/cli/chunks/{chunk-UF7JKDWB.js → chunk-JDADACZZ.js} +1 -1
- package/dist/cli/chunks/{chunk-5IH22DLD.js → chunk-JJ5YIKTJ.js} +3 -3
- package/dist/cli/chunks/{chunk-TRPRFW27.js → chunk-KB4S7MGB.js} +2 -2
- package/dist/cli/chunks/{chunk-XRF5MX4Q.js → chunk-KDICUKYX.js} +2 -2
- package/dist/cli/chunks/{chunk-EEG4G5JG.js → chunk-KE656E6T.js} +3 -3
- package/dist/cli/chunks/{chunk-F6V5POSK.js → chunk-KO3UQYGY.js} +10 -10
- package/dist/cli/chunks/{chunk-WRC66JTK.js → chunk-KQLJILCZ.js} +1 -1
- package/dist/cli/chunks/{chunk-C7AXBCMS.js → chunk-KZAVYHH7.js} +4 -4
- package/dist/cli/chunks/{chunk-7MBPKAQ3.js → chunk-L3UTZEVW.js} +2 -2
- package/dist/cli/chunks/{chunk-RRHIEG4Y.js → chunk-LASZCR5G.js} +2 -2
- package/dist/cli/chunks/{chunk-PHGOMAIS.js → chunk-LEIG3KIG.js} +2 -2
- package/dist/cli/chunks/{chunk-ZIYCZZYD.js → chunk-LIMFWEUI.js} +2 -2
- package/dist/cli/chunks/{chunk-VGWHFFK6.js → chunk-LJSHQU2P.js} +5 -5
- package/dist/cli/chunks/{chunk-3J2QITXC.js → chunk-LUAYTM77.js} +1 -1
- package/dist/cli/chunks/{chunk-GNCGRDQ2.js → chunk-MANWLRAW.js} +1 -1
- package/dist/cli/chunks/{chunk-JBWXBDJX.js → chunk-MP3RCZ75.js} +1 -1
- package/dist/cli/chunks/{chunk-WVWWTRKT.js → chunk-MPVOZKUP.js} +1 -1
- package/dist/cli/chunks/{chunk-A547LEUW.js → chunk-MWWTYPFL.js} +2 -2
- package/dist/cli/chunks/{chunk-IRX2THND.js → chunk-N57M7UPQ.js} +2 -2
- package/dist/cli/chunks/{chunk-TK6CHESH.js → chunk-N7LIYK7Z.js} +1 -1
- package/dist/cli/chunks/{chunk-ORXDKBZC.js → chunk-NAAPL2HK.js} +1 -1
- package/dist/cli/chunks/{chunk-IH47VGC7.js → chunk-NAZFAGJ5.js} +2 -2
- package/dist/cli/chunks/{chunk-M7XDTQHX.js → chunk-NQJLUY2K.js} +2 -2
- package/dist/cli/chunks/{chunk-6C3PDY72.js → chunk-NQVF4M7L.js} +1 -1
- package/dist/cli/chunks/{chunk-SJWTNKPY.js → chunk-NW4YPUPN.js} +3 -3
- package/dist/cli/chunks/{chunk-46U73TST.js → chunk-O45CEMVF.js} +1 -1
- package/dist/cli/chunks/{chunk-37I4AMCT.js → chunk-O74V7MB4.js} +2 -2
- package/dist/cli/chunks/{chunk-ZI7BWJJW.js → chunk-OF7674H5.js} +2 -2
- package/dist/cli/chunks/{chunk-P5CQMDFQ.js → chunk-OR2RC7ZH.js} +2 -2
- package/dist/cli/chunks/{chunk-ZLTAAROU.js → chunk-OU2YHXJY.js} +2 -2
- package/dist/cli/chunks/{chunk-JHOJG5VO.js → chunk-OU3SYEYJ.js} +1 -1
- package/dist/cli/chunks/{chunk-N7IRBQ4D.js → chunk-PD2ZSCEH.js} +1 -1
- package/dist/cli/chunks/{chunk-DSUEJK33.js → chunk-PFQLB4XP.js} +2 -2
- package/dist/cli/chunks/{chunk-V6W4IHS5.js → chunk-PI55PHUL.js} +2 -2
- package/dist/cli/chunks/{chunk-EMH54CO7.js → chunk-PIYDPOW6.js} +2 -2
- package/dist/cli/chunks/{chunk-DSGKRXHF.js → chunk-PJFQGNRW.js} +1 -1
- package/dist/cli/chunks/{chunk-L4O2645U.js → chunk-PRHLV6FS.js} +1 -1
- package/dist/cli/chunks/chunk-Q4VZXT6X.js +2 -0
- package/dist/cli/chunks/{chunk-H2BR5MCX.js → chunk-QENUKXPP.js} +2 -2
- package/dist/cli/chunks/chunk-QGH54HTH.js +2 -0
- package/dist/cli/chunks/{chunk-2BYRQ5MV.js → chunk-QXF6EQFP.js} +2 -2
- package/dist/cli/chunks/{chunk-ZU3XUBDQ.js → chunk-RCRKCMN5.js} +1 -1
- package/dist/cli/chunks/{chunk-5A5EC5RD.js → chunk-RKNKFLCQ.js} +2 -2
- package/dist/cli/chunks/{chunk-5IVOY76M.js → chunk-RLZZTFEN.js} +2 -2
- package/dist/cli/chunks/{chunk-CBLKYGKT.js → chunk-RO4BYINM.js} +2 -2
- package/dist/cli/chunks/{chunk-K2D3YW2N.js → chunk-SFRYDGLF.js} +1 -1
- package/dist/cli/chunks/{chunk-UX434RY5.js → chunk-SJ26ZR75.js} +2 -2
- package/dist/cli/chunks/{chunk-LLQG3F4H.js → chunk-SPTCNM45.js} +2 -2
- package/dist/cli/chunks/{chunk-KQFMCVBH.js → chunk-SQCACQUM.js} +2 -2
- package/dist/cli/chunks/{chunk-3CFWNT3F.js → chunk-TCYSMSBO.js} +2 -2
- package/dist/cli/chunks/{chunk-W6OIDL4J.js → chunk-TFFEB7XD.js} +2 -2
- package/dist/cli/chunks/{chunk-RU23JXCG.js → chunk-TM6LLT4G.js} +3 -3
- package/dist/cli/chunks/{chunk-WHUQDBV7.js → chunk-TO7FTPRV.js} +2 -2
- package/dist/cli/chunks/{chunk-QZ3EIONO.js → chunk-U52IQFMP.js} +1 -1
- package/dist/cli/chunks/{chunk-33SPAMQZ.js → chunk-UAEP2ZUQ.js} +2 -2
- package/dist/cli/chunks/{chunk-OD5R7HRI.js → chunk-UNMWI4QU.js} +1 -1
- package/dist/cli/chunks/{chunk-U7DGRHSB.js → chunk-UOO7P2AK.js} +2 -2
- package/dist/cli/chunks/{chunk-QFANYWC5.js → chunk-UQFMQOZB.js} +1 -1
- package/dist/cli/chunks/{chunk-2QKSIHXO.js → chunk-VDPQ7NVG.js} +1 -1
- package/dist/cli/chunks/{chunk-QP4UKSUJ.js → chunk-VLELNETG.js} +2 -2
- package/dist/cli/chunks/{chunk-KQ5GLUOB.js → chunk-VOAXVNO5.js} +4 -4
- package/dist/cli/chunks/{chunk-QZS3XCU5.js → chunk-VZO4V4R4.js} +2 -2
- package/dist/cli/chunks/{chunk-BDOD534O.js → chunk-W37WY3OL.js} +2 -2
- package/dist/cli/chunks/{chunk-UWBHR4EZ.js → chunk-WCUXA3NV.js} +1 -1
- package/dist/cli/chunks/{chunk-RMQRSZB4.js → chunk-WSQE3VZB.js} +1 -1
- package/dist/cli/chunks/{chunk-MYR6CBXC.js → chunk-WUXCL65V.js} +2 -2
- package/dist/cli/chunks/{chunk-OU5CZFBG.js → chunk-X5JMTHXC.js} +3 -3
- package/dist/cli/chunks/{chunk-XRQGWUDX.js → chunk-X67O2KUE.js} +2 -2
- package/dist/cli/chunks/{chunk-HEF6XKA5.js → chunk-XBSBVPSM.js} +2 -2
- package/dist/cli/chunks/{chunk-KBQRYAHZ.js → chunk-XEI5LLHX.js} +2 -2
- package/dist/cli/chunks/{chunk-LWPCGOQM.js → chunk-XF4F5ZXO.js} +2 -2
- package/dist/cli/chunks/{chunk-SAMAYDVS.js → chunk-XLP44YGX.js} +2 -2
- package/dist/cli/chunks/{chunk-CW7BWFFF.js → chunk-XTHRSBMJ.js} +2 -2
- package/dist/cli/chunks/{chunk-VKUH57JE.js → chunk-Y7VWCP35.js} +1 -1
- package/dist/cli/chunks/{chunk-6R6QGQ7D.js → chunk-YQI6SOUO.js} +1 -1
- package/dist/cli/chunks/{chunk-GTURQ454.js → chunk-YZGA4ELM.js} +2 -2
- package/dist/cli/chunks/{chunk-SSXCHSVM.js → chunk-Z6FK7T7J.js} +2 -2
- package/dist/cli/chunks/{chunk-UOJ26GXD.js → chunk-Z7FVGJYC.js} +2 -2
- package/dist/cli/chunks/{chunk-DPJLA7JW.js → chunk-ZAT65V6I.js} +2 -2
- package/dist/cli/chunks/{chunk-J65XQ6WE.js → chunk-ZYCPTARG.js} +2 -2
- package/dist/cli/chunks/{ci-G2NEYLVO.js → ci-DK4FGREO.js} +2 -2
- package/dist/cli/chunks/{ci-output-SZFEXGBU.js → ci-output-HQBBQQES.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-ZD7PJY6N.js → circuit-breaker-MJCS46DN.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-DAVANGUJ.js → claude-flow-setup-IIQT52H4.js} +2 -2
- package/dist/cli/chunks/client-FNDZB4TY.js +2 -0
- package/dist/cli/chunks/{cline-installer-WCPKWLY7.js → cline-installer-7SPKUNNZ.js} +2 -2
- package/dist/cli/chunks/{code-324ZJR3V.js → code-V2B4FP3X.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-EWVSXJHR.js → code-index-extractor-IRGAI76Y.js} +2 -2
- package/dist/cli/chunks/codex-installer-PDFCYRU6.js +15 -0
- package/dist/cli/chunks/{completions-ZAWBZWYK.js → completions-TAJ6N7YZ.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-S3H2IRON.js → complexity-analyzer-JHQKQKBG.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-4DDFAJ26.js → continuedev-installer-DESZXCLC.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-KBBAL3G5.js → copilot-installer-OQPXBLWS.js} +2 -2
- package/dist/cli/chunks/core-handlers-S37RHLKP.js +2 -0
- package/dist/cli/chunks/{cost-tracker-2YM7SGBW.js → cost-tracker-KHDFSCAJ.js} +2 -2
- package/dist/cli/chunks/{coverage-6CCBAORJ.js → coverage-T7EENIDE.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-7ZHDB2V3.js +2 -0
- package/dist/cli/chunks/{cursor-installer-24DKXNU5.js → cursor-installer-X6BFU5QU.js} +2 -2
- package/dist/cli/chunks/{daemon-M2PSDIZF.js → daemon-22NOG5XI.js} +3 -3
- package/dist/cli/chunks/{daemon-JLF6CRBS.js → daemon-UTPP4JCG.js} +4 -4
- package/dist/cli/chunks/{dag-attention-scheduler-Y5HSZDRV.js → dag-attention-scheduler-XI6DG3FW.js} +2 -2
- package/dist/cli/chunks/{detect-6Y227IJ6.js → detect-7IMQGJ5I.js} +2 -2
- package/dist/cli/chunks/{dist-node-EGOJXGTA.js → dist-node-YMLM4K7J.js} +2 -2
- package/dist/cli/chunks/{domain-handler-G3JEWRE5.js → domain-handler-LRTJGTEH.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-XOHI3EMJ.js → domain-transfer-HZJ3WUCT.js} +2 -2
- package/dist/cli/chunks/dream-BEVYNIOO.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-CSSA55L4.js → embed-and-insert-pattern-QSRN7Z5Q.js} +2 -2
- package/dist/cli/chunks/{eval-NHBXOXDV.js → eval-JVVVQVV6.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-B7ZDV5UY.js → experience-capture-middleware-ORZN3ROJ.js} +3 -3
- package/dist/cli/chunks/{fast-paths-XGKSBALA.js → fast-paths-LUFARZR5.js} +2 -2
- package/dist/cli/chunks/{feature-flags-NBUDJSWJ.js → feature-flags-2XC4ECLW.js} +2 -2
- package/dist/cli/chunks/{feature-flags-ZVD73ZYK.js → feature-flags-ZHQESXIP.js} +2 -2
- package/dist/cli/chunks/{file-discovery-C42TEUKT.js → file-discovery-UHXZQ7GS.js} +2 -2
- package/dist/cli/chunks/{fleet-LF77P3BW.js → fleet-FUQ6G4SB.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-UXNT7BEN.js → gnn-wrapper-A4E6OKGD.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-C4LMU5LA.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-EHHBIWS3.js → hnsw-legacy-bridge-AHKFKM2J.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-OW5HIPEN.js → hnswlib-node-BP5CZGMD.js} +2 -2
- package/dist/cli/chunks/{hooks-AGE3HCFI.js → hooks-JNW5ZB2E.js} +10 -10
- package/dist/cli/chunks/hybrid-router-4SXBHTOY.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-E5QX5MEB.js → hypergraph-engine-3DTAMNSJ.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-ZZHBANYB.js → hypergraph-handler-ZV4AZRGF.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-55GE7EQD.js +2 -0
- package/dist/cli/chunks/{init-handler-PNVRBZZT.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-TR53QKPU.js → kilocode-installer-D35TR6LG.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-MJW6LCAX.js → kiro-installer-OHHTQENO.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-OITIVT5J.js +2 -0
- package/dist/cli/chunks/{learning-6LLGHP2Q.js → learning-24PCHLWU.js} +3 -3
- package/dist/cli/chunks/{llm-router-DBLV3VGG.js → llm-router-XLTE52H5.js} +4 -4
- package/dist/cli/chunks/llm-router-service-RUPU52AR.js +2 -0
- package/dist/cli/chunks/{load-LAZ3E5PE.js → load-BHMK4FIL.js} +2 -2
- package/dist/cli/chunks/load-test-ZV3C55ZE.js +2 -0
- package/dist/cli/chunks/{mcp-L5QXHSEY.js → mcp-V4MAYT7C.js} +2 -2
- package/dist/cli/chunks/{memory-YR5PCMWA.js → memory-PDA7MQ7E.js} +5 -5
- package/dist/cli/chunks/memory-backend-S3KCPHCF.js +2 -0
- package/dist/cli/chunks/{memory-handlers-BSRTZQYR.js → memory-handlers-X5BLXOSH.js} +2 -2
- package/dist/cli/chunks/{multi-model-executor-RECZ3ACW.js → multi-model-executor-KECHOXKD.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-4TDUB7HH.js → opencode-installer-LWSCQOOZ.js} +2 -2
- package/dist/cli/chunks/{orchestrator-PHDKJ5C4.js → orchestrator-ENEBTEUW.js} +6 -6
- package/dist/cli/chunks/pattern-null-store-ILVDKSCX.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-QK2FADRS.js → pattern-usage-recorder-XIHGXYZZ.js} +2 -2
- package/dist/cli/chunks/{pipeline-JQJYSN43.js → pipeline-GQOJM3LU.js} +2 -2
- package/dist/cli/chunks/platform-L56TGXGZ.js +2 -0
- package/dist/cli/chunks/{plugin-766MBGK6.js → plugin-SZ6PZKYX.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-XQERZNSK.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-FAK4MMNA.js → protocol-handler-5MMNVVPX.js} +2 -2
- package/dist/cli/chunks/{prove-HYBVXOGW.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-EGSO2RAX.js → quality-WKC4JCB3.js} +2 -2
- package/dist/cli/chunks/{quality-gate-RK32VMO7.js → quality-gate-CVHVSORK.js} +3 -3
- package/dist/cli/chunks/queen-coordinator-GI7GNVDM.js +2 -0
- package/dist/cli/chunks/{real-embeddings-GI7CRHE2.js → real-embeddings-DN2MEJVM.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-BS3XWJJI.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-XMGRJDHH.js → routing-handler-PSWR2UCT.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-NDL3ONNC.js → ruvector-commands-VTP6Y7PN.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-XAJOYGJ2.js → rvf-dual-writer-EBUMXPRO.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-WXFRZZ26.js → rvf-migration-adapter-5N7GHMD3.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-WFXA2VUQ.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-I7PFJZCK.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-H3WY76GF.js → security-YDWLYXYD.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-GRTJCLW6.js → shared-rvf-adapter-I3HQY7DE.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-46XE5R2B.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-VUIFMY4F.js → status-handler-QRHI3F4V.js} +2 -2
- package/dist/cli/chunks/{structural-health-I7HC477E.js → structural-health-FWKE63CM.js} +2 -2
- package/dist/cli/chunks/{sync-M6LUV5R4.js → sync-2QRCT5MT.js} +2 -2
- package/dist/cli/chunks/{sync-RO2YGMBF.js → sync-E32MBAOF.js} +2 -2
- package/dist/cli/chunks/{task-handler-BJJTZ7AU.js → task-handler-C7BKMOCL.js} +2 -2
- package/dist/cli/chunks/{task-handlers-B6S4NEN3.js → task-handlers-PADWLLDO.js} +3 -3
- package/dist/cli/chunks/{test-BE7EM6Y6.js → test-KX4UKHSX.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-4ISKEFR6.js → test-scheduling-5WKIWH4H.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-BOIYBZHW.js → token-bootstrap-6SKOJM3U.js} +2 -2
- package/dist/cli/chunks/{token-usage-6ZZC7RLT.js → token-usage-V6JW55RV.js} +2 -2
- package/dist/cli/chunks/{transformers-55VI4OGW.js → transformers-3UPFBYSB.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-6GRRGB3K.js → tree-sitter-wasm-parser-UCY4S2DU.js} +2 -2
- package/dist/cli/chunks/{types-SXDF7QQT.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-PMPB7NGB.js → upgrade-MVTMTOPL.js} +2 -2
- package/dist/cli/chunks/{validate-G37QKKXK.js → validate-OJWR2AGZ.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-6X22J3VD.js → validate-swarm-2RGSF2K2.js} +2 -2
- package/dist/cli/chunks/{vibium-SGBJKHQL.js → vibium-O3ZLAEEZ.js} +2 -2
- package/dist/cli/chunks/visual-security-EHVU32UE.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-S46Y5BUJ.js → web-tree-sitter-6VPASTI4.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-PTYCETNM.js → windsurf-installer-CINHOW3N.js} +2 -2
- package/dist/cli/chunks/{witness-chain-5SCRFT2K.js → witness-chain-2NXW7FT7.js} +2 -2
- package/dist/cli/chunks/witness-chain-BIICGRHC.js +2 -0
- package/dist/cli/chunks/{witness-key-manager-XIAMRVUZ.js → witness-key-manager-ODW4DJWT.js} +2 -2
- package/dist/cli/chunks/{workflow-BPQA2NAI.js → workflow-BFGS2GAU.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-PVTYPYY4.js +2 -0
- package/dist/cli/chunks/{wrappers-IWZZZOAU.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 +2 -2
- package/package.json +5 -1
- package/dist/cli/chunks/adapter-NIUFP6QX.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-DC4DNCPB.js +0 -2
- package/dist/cli/chunks/base-EXD3ULZT.js +0 -2
- package/dist/cli/chunks/browser-workflow-KOMASCB7.js +0 -2
- package/dist/cli/chunks/chunk-T5L65R23.js +0 -2
- package/dist/cli/chunks/client-ZJQMJO5N.js +0 -2
- package/dist/cli/chunks/codex-installer-HVSZBHH2.js +0 -10
- package/dist/cli/chunks/core-handlers-U2YJLH6O.js +0 -2
- package/dist/cli/chunks/cross-domain-router-E7EMKZEK.js +0 -2
- package/dist/cli/chunks/dream-ZMNQYBJO.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-2JL4MAJR.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-AZD6O35G.js +0 -2
- package/dist/cli/chunks/hnsw-index-WJLE4S5L.js +0 -2
- package/dist/cli/chunks/hybrid-router-YTKJBAS2.js +0 -2
- package/dist/cli/chunks/impact-analyzer-CX56GZXA.js +0 -2
- package/dist/cli/chunks/init-wizard-WE6HIC66.js +0 -2
- package/dist/cli/chunks/kernel-MT55LNNI.js +0 -2
- package/dist/cli/chunks/knowledge-graph-WN3LQ2W7.js +0 -2
- package/dist/cli/chunks/llm-router-service-NKHEQQMN.js +0 -2
- package/dist/cli/chunks/load-test-3WIQASDF.js +0 -2
- package/dist/cli/chunks/memory-backend-W6YSNT6O.js +0 -2
- package/dist/cli/chunks/pattern-null-store-IV3ZESTR.js +0 -2
- package/dist/cli/chunks/platform-FA5TOPTH.js +0 -2
- package/dist/cli/chunks/protocol-executor-GFAG5G6K.js +0 -2
- package/dist/cli/chunks/provider-manager-TIVIJIYH.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-BYE7YF6Y.js +0 -2
- package/dist/cli/chunks/queen-coordinator-WOHYVV7A.js +0 -2
- package/dist/cli/chunks/router-VUW2UVCN.js +0 -2
- package/dist/cli/chunks/routing-feedback-WSUQMZAK.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-RHZCXVN6.js +0 -2
- package/dist/cli/chunks/safe-db-NTWEW7ZM.js +0 -2
- package/dist/cli/chunks/schedule-WEVC2GW2.js +0 -2
- package/dist/cli/chunks/scheduler-XHI5AJIS.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-QZUPKMHP.js +0 -2
- package/dist/cli/chunks/unified-memory-QKWUSEBV.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-Z2UQZRTK.js +0 -2
- package/dist/cli/chunks/unified-persistence-AVK2NSMI.js +0 -2
- package/dist/cli/chunks/visual-security-64UFH23G.js +0 -2
- package/dist/cli/chunks/witness-chain-ZIVSDX6C.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-TYP4MI2V.js +0 -2
- package/dist/cli/commands/init.d.ts +0 -19
- package/dist/cli/commands/init.js +0 -318
|
@@ -1,6 +1,6 @@
|
|
|
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 x,f as C,j as y,k as R,q as F}from"./chunk-
|
|
3
|
-
Caused by: ${s.stack}`)}code;cause},c=class extends o{constructor(e="Vibium MCP server is unavailable",t){super(e,"VIBIUM_UNAVAILABLE",t),this.name="VibiumUnavailableError"}},f=class extends o{constructor(e="Browser operation timed out",t){super(e,"VIBIUM_TIMEOUT",t),this.name="VibiumTimeoutError"}},g=class extends o{selector;constructor(e,t){super(`Element not found: ${e}`,"ELEMENT_NOT_FOUND",t),this.name="VibiumElementNotFoundError",this.selector=e}},l=class extends o{constructor(e="Failed to connect to browser",t){super(e,"CONNECTION_ERROR",t),this.name="VibiumConnectionError"}},p=class extends o{url;statusCode;constructor(e,t,r){let s=t?`Navigation failed: ${e} (HTTP ${t})`:`Navigation failed: ${e}`;super(s,"NAVIGATION_ERROR",r),this.name="VibiumNavigationError",this.url=e,this.statusCode=t}},m=class extends o{constructor(e="Failed to capture screenshot",t){super(e,"SCREENSHOT_ERROR",t),this.name="VibiumScreenshotError"}},b=class extends o{action;selector;constructor(e,t,r){super(`Failed to ${e} element: ${t}`,"INTERACTION_ERROR",r),this.name="VibiumInteractionError",this.action=e,this.selector=t}}});import{randomUUID as _}from"crypto";async function V(){if(v!==null)return v;try{return v=(await import("./vibium-
|
|
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 x,f as C,j as y,k as R,q as F}from"./chunk-MWWTYPFL.js";import{b as I,c as k}from"./chunk-KDICUKYX.js";import{c as w}from"./chunk-GGZB2ZBB.js";var P,S=w(()=>{"use strict";P={enabled:!0,headless:!0,timeout:3e4,retryAttempts:3,fallbackEnabled:!0,browserType:"chromium",viewport:{width:1280,height:720},userAgent:"",devtools:!1,slowMo:0,screenshotDir:".agentic-qe/screenshots"}});function B(i){return i instanceof o}function a(i,e="Unknown Vibium error"){return B(i)?i:i instanceof Error?new o(i.message||e,"UNKNOWN_ERROR",i):new o(typeof i=="string"?i:e,"UNKNOWN_ERROR")}var o,c,f,g,l,p,m,b,A=w(()=>{"use strict";o=class i extends Error{constructor(t,r,s){super(t);this.code=r;this.cause=s;this.name="VibiumError",Error.captureStackTrace&&Error.captureStackTrace(this,i),s?.stack&&(this.stack+=`
|
|
3
|
+
Caused by: ${s.stack}`)}code;cause},c=class extends o{constructor(e="Vibium MCP server is unavailable",t){super(e,"VIBIUM_UNAVAILABLE",t),this.name="VibiumUnavailableError"}},f=class extends o{constructor(e="Browser operation timed out",t){super(e,"VIBIUM_TIMEOUT",t),this.name="VibiumTimeoutError"}},g=class extends o{selector;constructor(e,t){super(`Element not found: ${e}`,"ELEMENT_NOT_FOUND",t),this.name="VibiumElementNotFoundError",this.selector=e}},l=class extends o{constructor(e="Failed to connect to browser",t){super(e,"CONNECTION_ERROR",t),this.name="VibiumConnectionError"}},p=class extends o{url;statusCode;constructor(e,t,r){let s=t?`Navigation failed: ${e} (HTTP ${t})`:`Navigation failed: ${e}`;super(s,"NAVIGATION_ERROR",r),this.name="VibiumNavigationError",this.url=e,this.statusCode=t}},m=class extends o{constructor(e="Failed to capture screenshot",t){super(e,"SCREENSHOT_ERROR",t),this.name="VibiumScreenshotError"}},b=class extends o{action;selector;constructor(e,t,r){super(`Failed to ${e} element: ${t}`,"INTERACTION_ERROR",r),this.name="VibiumInteractionError",this.action=e,this.selector=t}}});import{randomUUID as _}from"crypto";async function V(){if(v!==null)return v;try{return v=(await import("./vibium-O3ZLAEEZ.js")).browser,O=!0,v}catch(i){return console.warn("[Vibium] Failed to load vibium package:",i),O=!1,null}}async function T(i,e,t){let r;for(let s=1;s<=e;s++)try{return await i()}catch(n){if(r=I(n),s<e){let u=Math.min(100*Math.pow(2,s-1),2e3);await new Promise(d=>setTimeout(d,u))}}throw new o(`${t} failed after ${e} attempts`,"RETRY_EXHAUSTED",r)}async function h(i,e){let t=Date.now();try{let r=await i();return R()&&console.log(`[Vibium] ${e}: ${Date.now()-t}ms`),r}catch(r){throw R()&&console.log(`[Vibium] ${e} failed: ${Date.now()-t}ms`,r),r}}var v,O,E,N,M=w(()=>{S();A();k();F();v=null,O=!1;E=class{config;currentSession=null;lastHealthCheck=null;_initialized=!1;_available=null;vibeInstance=null;constructor(e={}){this.config={...P,...e}}async isAvailable(){if(!this.config.enabled)return!1;if(this._available!==null)return this._available;try{let e=await V();return this._available=e!==null,this._available}catch{return this._available=!1,!1}}async getHealth(){let e=new Date;if(!this.config.enabled)return{status:"unavailable",features:["fallback-only"],lastChecked:e,error:"Vibium is disabled by configuration",sessionActive:!1};try{await this.isAvailable()?this.lastHealthCheck={status:this.vibeInstance?"connected":"disconnected",version:"0.1.2",browserType:this.config.browserType,features:["browser-launch","navigation","element-interaction","screenshots","script-evaluation","accessibility-testing"],latencyMs:10,lastChecked:e,sessionActive:this.vibeInstance!==null}:this.lastHealthCheck={status:"unavailable",features:["fallback-only"],lastChecked:e,error:"Vibium package not available - install with: npm install vibium",sessionActive:!1}}catch(t){this.lastHealthCheck={status:"error",features:["fallback-only"],lastChecked:e,error:t instanceof Error?t.message:"Unknown error",sessionActive:!1}}return this.lastHealthCheck}async getSession(){return this.currentSession}async launch(e){if(!x())return{success:!1,error:new c("Browser mode is disabled by feature flags")};let t=async()=>{let r=await V();if(!r)throw new c("Vibium package not available. Install with: npm install vibium");let s=e?.headless??this.config.headless;this.vibeInstance=await r.launch({headless:s});let n={id:this.generateSessionId(),browserType:this.config.browserType,launchedAt:new Date,status:"connected",viewport:e?.viewport??this.config.viewport,headless:s};return this.currentSession=n,n};try{return{success:!0,value:y()?await T(()=>h(t,"browser_launch"),this.config.retryAttempts,"browser_launch"):await h(t,"browser_launch")}}catch(r){return{success:!1,error:a(r,"Failed to launch browser")}}}async quit(){if(!this.vibeInstance)return{success:!1,error:new l("No active browser session")};let e=async()=>{this.vibeInstance&&(await this.vibeInstance.quit(),this.vibeInstance=null),this.currentSession=null};try{return await h(e,"browser_quit"),{success:!0,value:void 0}}catch(t){return{success:!1,error:a(t,"Failed to quit browser")}}}async navigate(e){this.ensureSession();let t=async()=>{let r=Date.now();await this.vibeInstance.go(e.url);let s="";try{s=await this.vibeInstance.evaluate("document.title")}catch{s="Unknown"}let n={url:e.url,statusCode:200,title:s,durationMs:Date.now()-r,success:!0};return this.currentSession&&(this.currentSession.currentUrl=e.url),n};try{return{success:!0,value:y()?await T(()=>h(t,"page_navigate"),this.config.retryAttempts,"page_navigate"):await h(t,"page_navigate")}}catch(r){return{success:!1,error:new p(e.url,void 0,r instanceof Error?r:void 0)}}}async getPageInfo(){this.ensureSession();try{let e=await this.vibeInstance.evaluate("window.location.href"),t=await this.vibeInstance.evaluate("document.title");return{success:!0,value:{url:e,title:t,viewport:this.config.viewport,loadState:"loaded"}}}catch(e){return{success:!1,error:a(e,"Failed to get page info")}}}async goBack(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.history.back()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to go back")}}}async goForward(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.history.forward()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to go forward")}}}async reload(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.location.reload()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to reload page")}}}async findElement(e){this.ensureSession();try{let t=await this.vibeInstance.find(e.selector,{timeout:e.timeout??this.config.timeout});return{success:!0,value:{selector:e.selector,tagName:t.info.tag,textContent:t.info.text,attributes:{},boundingBox:t.info.box,visible:!0,enabled:!0}}}catch(t){return{success:!1,error:new g(e.selector,t instanceof Error?t:void 0)}}}async findElements(e){this.ensureSession();try{let t=e.selector.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return{success:!0,value:(await this.vibeInstance.evaluate(`
|
|
4
4
|
Array.from(document.querySelectorAll('${t}'))
|
|
5
5
|
.map(el => ({
|
|
6
6
|
tag: el.tagName.toLowerCase(),
|
|
@@ -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
|
function t(r,o,n){let e=new Error(r);return e.name="LLMError",e.code=o,e.provider=n?.provider,e.model=n?.model,e.retryable=n?.retryable??!1,e.retryAfterMs=n?.retryAfterMs,e.cause=n?.cause,e}function i(r){return r instanceof Error&&"code"in r&&typeof r.code=="string"}export{t as a,i as b};
|
|
@@ -1,4 +1,4 @@
|
|
|
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{writeFileSync as p,readFileSync as m}from"node:fs";import{resolve as f,dirname as c,join as d}from"node:path";import{mkdirSync as g}from"node:fs";import{fileURLToPath as h}from"node:url";function $(){try{let e=typeof __dirname<"u"?__dirname:c(h(import.meta.url));for(let t=0;t<5;t++){let n=d(e,"package.json");try{let r=JSON.parse(m(n,"utf-8"));if(r.version)return r.version}catch{}e=c(e)}}catch{}return"unknown"}var T=["-F, --format <format>","Output format (text|json|sarif|junit|markdown)","text"],x=["-o, --output <path>","Write output to file instead of stdout"];function C(e,t,n){if(t){let r=f(t);g(c(r),{recursive:!0}),p(r,e,"utf-8"),n&&console.log(n),console.log(`Output written to: ${r}`)}else console.log(e)}function R(e){return JSON.stringify(e,null,2)}var v="https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json";function w(e){let t=i=>{switch(i.toLowerCase()){case"critical":case"high":return"error";case"medium":return"warning";case"low":case"info":return"note";default:return"warning"}},n=new Map,r=[];for(let i of e.vulnerabilities){let o=i.ruleId||`AQE/${i.type.replace(/\s+/g,"-").toLowerCase()}`;n.has(o)||n.set(o,{id:o,name:i.type,shortDescription:i.type,...i.cweId?{helpUri:`https://cwe.mitre.org/data/definitions/${i.cweId.replace("CWE-","")}.html`}:{}}),r.push({ruleId:o,level:t(i.severity),message:{text:i.message},locations:[{physicalLocation:{artifactLocation:{uri:i.file,uriBaseId:"%SRCROOT%"},region:{startLine:i.line,startColumn:1}}}],...i.cweId?{taxa:[{id:i.cweId,toolComponent:{name:"CWE"}}]}:{}})}let s={$schema:v,version:"2.1.0",runs:[{tool:{driver:{name:"agentic-qe",version:$(),informationUri:"https://github.com/proffesor-for-testing/agentic-qe",rules:Array.from(n.values()).map(i=>({id:i.id,name:i.name,shortDescription:{text:i.shortDescription},...i.helpUri?{helpUri:i.helpUri}:{},defaultConfiguration:{level:"warning"}}))}},results:r,invocations:[{executionSuccessful:!0,commandLine:`aqe security --sast --format sarif -t ${e.target}`}]}]};return JSON.stringify(s,null,2)}function a(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function I(e){let t=e.tests||[],n=e.passed+e.failed+e.skipped,r=(e.duration/1e3).toFixed(3),s=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
3
|
`;if(s+=`<testsuites tests="${n}" failures="${e.failed}" errors="0" time="${r}">
|
|
4
4
|
`,s+=` <testsuite name="aqe-test-run" tests="${n}" failures="${e.failed}" errors="0" skipped="${e.skipped}" time="${r}" id="${a(e.runId)}">
|
|
@@ -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 o=!1;function r(t){if(!o){for(let e of["ALTER TABLE routing_outcomes ADD COLUMN exploration INTEGER NOT NULL DEFAULT 0","ALTER TABLE routing_outcomes ADD COLUMN criticality REAL","ALTER TABLE routing_outcomes ADD COLUMN q_weight REAL"])try{t.prepare(e).run()}catch{}try{t.prepare("CREATE INDEX IF NOT EXISTS idx_routing_outcomes_exploration ON routing_outcomes(exploration)").run()}catch{}o=!0}}export{r 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
|
var h=Object.create;var f=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var k=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty;var m=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')}),n=a=>b=>{var c=a[b];if(c)return c();throw new Error("Module not found in bundle: "+b)};var o=(a,b,c)=>()=>{if(c)throw c[0];try{return a&&(b=a(a=0)),b}catch(d){throw c=[d],d}};var p=(a,b)=>()=>{try{return b||a((b={exports:{}}).exports,b),b.exports}catch(c){throw b=0,c}},q=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0})},g=(a,b,c,d)=>{if(b&&typeof b=="object"||typeof b=="function")for(let e of j(b))!l.call(a,e)&&e!==c&&f(a,e,{get:()=>b[e],enumerable:!(d=i(b,e))||d.enumerable});return a};var r=(a,b,c)=>(c=a!=null?h(k(a)):{},g(b||!a||!a.__esModule?f(c,"default",{value:a,enumerable:!0}):c,a)),s=a=>g(f({},"__esModule",{value:!0}),a);export{m as a,n as b,o as c,p as d,q as e,r as f,s as g};
|
|
@@ -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 i={claude:"metered-api","claude-code":"subscription",codex:"subscription",openai:"metered-api",openrouter:"metered-api",gemini:"metered-api","azure-openai":"metered-api",bedrock:"metered-api",cognitum:"metered-capped",ollama:"local"};function n(e){return e.billingMode??i[e.type]??"metered-api"}function t(e){return i[e]??"metered-api"}function d(e,r){switch(r){case"metered-api":return`\u26A0\uFE0F LLM provider "${e}" bills a pay-per-token API key (not your Claude subscription) and has no server-side spend cap. Set a budget with --max-budget-usd / AQE_MAX_BUDGET_USD, or use AQE_LLM_PROVIDER=claude-code to run on your Claude Code subscription instead.`;case"metered-capped":return`\u2139\uFE0F LLM provider "${e}" bills per-token but enforces a server-side hard spend cap; it will pause at the cap rather than overspend.`;case"subscription":return`\u2139\uFE0F LLM provider "${e}" runs on your ${e==="codex"?"ChatGPT":"Claude Code"} subscription (shared plan usage). Worst case is hitting your plan's rate limit and pausing \u2014 no per-token API charges.`;case"local":return}}export{n as a,t as b,d as c};
|
|
@@ -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{b as m,c as y}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{b as m,c as y}from"./chunk-27REOPQK.js";import{e as S,f as A}from"./chunk-LEIG3KIG.js";import{a as R,b as g,c as v}from"./chunk-O45CEMVF.js";import{a as p,g as b}from"./chunk-GGZB2ZBB.js";y();var s=null,f=!1;function w(t){s=t,f=t!==null}var E=(()=>{let t=process.env.AQE_RVF_SIZE_GUARD_BYTES,r=t?Number(t):NaN;return Number.isFinite(r)&&r>0?r:256*1024*1024})(),C=(()=>{let t=process.env.AQE_RVF_DEAD_RATIO_THRESHOLD,r=t?Number(t):NaN;return Number.isFinite(r)&&r>0&&r<=1?r:.3})();function _(t=".agentic-qe",r=384){if(f)return s;f=!0;try{let{isRvfNativeAvailable:e,createRvfStore:o,openRvfStore:i}=(A(),b(S));if(!e())return console.warn("[RVF] Native bindings unavailable \u2014 agent branching and dream COW disabled. Install @ruvector/rvf-node to enable."),null;let l=p("path"),c=l.isAbsolute(t)?t:l.join(process.env.AQE_PROJECT_ROOT??m(),t),u=l.join(c,"patterns.rvf");return s=$(i,o,u,r),N(s,u),s}catch(e){return console.warn("[RVF] Shared adapter init failed:",e instanceof Error?e.message:e),null}}function $(t,r,e,o){let i=()=>{try{return{adapter:t(e),err:null}}catch(n){return{adapter:null,err:n}}},l=n=>{let a=n instanceof Error?n.message:String(n);return a.includes("LockHeld")||a.includes("0x0300")},{adapter:c,err:u}=i();if(!c&&l(u))try{let n=p("fs"),a=`${e}.lock`;n.existsSync(a)&&g(e)?console.warn(`[RVF] ${e} is locked by a live process (pid ${R(e)}) \u2014 not breaking the lock; degrading to SQLite for this run.`):n.existsSync(a)&&(n.unlinkSync(a),console.warn(`[RVF] Removed stale lock file at ${a} (prior process exited without closing). Retrying open. If you see this repeatedly under live concurrency, file an issue.`),{adapter:c,err:u}=i())}catch(n){process.env.DEBUG&&console.debug("[RVF] stale-lock recovery failed:",n instanceof Error?n.message:n)}if(c){let n=c.dimension();if(n===o)return c;console.warn(`[RVF] patterns.rvf dimension mismatch: file=${n} requested=${o} \u2014 closing and degrading. Delete the .rvf file to recreate at the requested dim.`);try{c.close()}catch{}throw new Error(`RVF dimension mismatch (file=${n}, requested=${o})`)}try{return r(e,o)}catch(n){try{let a=t(e);if(a.dimension()!==o){try{a.close()}catch{}throw new Error(`RVF dimension mismatch after race (file=${a.dimension()}, requested=${o})`)}return a}catch{if(v(e,n instanceof Error?n.message:String(n)))return r(e,o);throw n instanceof Error?n:new Error(String(n))}}}function h(t,r){if(r?.force)return{shouldCompact:!0,trigger:"force"};let e=r?.sizeGuardBytes??E,o=r?.deadRatioThreshold??C;return t.fileSizeBytes>=e?{shouldCompact:!0,trigger:"size-guard"}:(t.deadSpaceRatio??0)>=o?{shouldCompact:!0,trigger:"dead-ratio"}:{shouldCompact:!1,trigger:"none"}}function k(t){if(!s)return null;let r;try{r=s.status()}catch{return null}let e=h(r,t);if(!e.shouldCompact)return null;let o=r.fileSizeBytes,i;try{i=s.compact()}catch{return null}return i?((i.bytesReclaimed>0||i.segmentsCompacted>0)&&console.log(`[RVF] compacted patterns.rvf: reclaimed ${d(i.bytesReclaimed)} (${i.segmentsCompacted} segments, fileSize ${d(o)} \u2192 ${d(Math.max(0,o-i.bytesReclaimed))}, trigger: ${e.trigger})`),i):null}function N(t,r){try{let e=t.status(),o=h(e);if(!o.shouldCompact)return null;let i=t.compact();return i&&(i.bytesReclaimed>0||i.segmentsCompacted>0)&&console.log(`[RVF] boot-time compact (${r}): reclaimed ${d(i.bytesReclaimed)} from ${i.segmentsCompacted} segments (trigger: ${o.trigger})`),i}catch(e){return process.env.DEBUG&&console.debug("[RVF] boot-time compact guard skipped:",e instanceof Error?e.message:e),null}}function d(t){if(!Number.isFinite(t)||t<0)return`${t}B`;let r=["B","KB","MB","GB","TB"],e=0,o=t;for(;o>=1024&&e<r.length-1;)o/=1024,e++;return`${o.toFixed(e===0?0:1)}${r[e]}`}function T(){if(s){try{s.close()}catch{}s=null}f=!1}export{w as a,_ as b,h as c,k as d,N as e,T as f};
|
|
@@ -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 u={0:{tier:0,name:"Agent Booster",description:"Mechanical code transforms via Rust/WASM",useCases:["var-to-const conversion","add-types","remove-console statements","promise-to-async","cjs-to-esm","func-to-arrow"],typicalLatencyMs:1,relativeCost:0,exampleModels:["agent-booster-wasm","agent-booster-typescript"],requiresNetwork:!1,complexityRange:[0,10]},1:{tier:1,name:"Haiku",description:"Fast, cost-effective for simple tasks",useCases:["Simple bug fixes","Code formatting","Documentation updates","Basic refactoring","Test generation (simple)"],typicalLatencyMs:500,relativeCost:1,exampleModels:["claude-haiku-4-5-20251001","gpt-4o-mini","gemini-flash"],requiresNetwork:!0,complexityRange:[10,35]},2:{tier:2,name:"Sonnet",description:"Balanced capability for complex reasoning",useCases:["Feature implementation","Complex refactoring","Security analysis","Performance optimization","Test generation (complex)"],typicalLatencyMs:3e3,relativeCost:2,exampleModels:["claude-sonnet-4-6","gpt-4o","gemini-pro"],requiresNetwork:!0,complexityRange:[35,70]},3:{tier:3,name:"Sonnet Extended",description:"Extended context for multi-step workflows",useCases:["Multi-file refactoring","Workflow orchestration","Cross-domain coordination","Large codebase analysis"],typicalLatencyMs:7e3,relativeCost:3,exampleModels:["claude-sonnet-4-6"],requiresNetwork:!0,complexityRange:[60,85]},4:{tier:4,name:"Opus",description:"Maximum capability for critical decisions",useCases:["Architecture design","Security audits","Complex algorithm design","Critical bug analysis","System-wide refactoring"],typicalLatencyMs:5e3,relativeCost:4,exampleModels:["claude-opus-4-7","gpt-4-turbo"],requiresNetwork:!0,complexityRange:[75,100]}},d={enabled:!0,tierBudgets:{0:{tier:0,maxCostPerRequest:0,maxRequestsPerHour:1e4,maxRequestsPerDay:1e5,maxDailyCostUsd:0,enabled:!0},1:{tier:1,maxCostPerRequest:.01,maxRequestsPerHour:100,maxRequestsPerDay:1e3,maxDailyCostUsd:5,enabled:!0},2:{tier:2,maxCostPerRequest:.1,maxRequestsPerHour:50,maxRequestsPerDay:500,maxDailyCostUsd:20,enabled:!0},3:{tier:3,maxCostPerRequest:.5,maxRequestsPerHour:20,maxRequestsPerDay:100,maxDailyCostUsd:30,enabled:!0},4:{tier:4,maxCostPerRequest:2,maxRequestsPerHour:10,maxRequestsPerDay:50,maxDailyCostUsd:50,enabled:!0}},maxDailyCostUsd:100,warningThreshold:.8,onBudgetExceeded:"downgrade",onBudgetWarning:"warn",allowCriticalOverrides:!0},y={budgetConfig:d,enableAgentBooster:!0,agentBoosterThreshold:.7,enableAutoRouting:!0,complexityThresholds:{0:10,1:35,2:70,3:85,4:100},allowManualOverrides:!0,enableDecisionCache:!0,decisionCacheTtlMs:300*1e3,enableMetrics:!0,maxDecisionTimeMs:10,fallbackTier:2,tierModels:{0:"agent-booster",1:"claude-haiku-4-5-20251001",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"}},r=class extends Error{constructor(e,t,l){super(e);this.code=t;this.cause=l;this.name="ModelRouterError"}code;cause},a=class extends r{constructor(e,t,l){super(e,"BUDGET_EXCEEDED");this.tier=t;this.usage=l;this.name="BudgetExceededError"}tier;usage},i=class extends r{constructor(o,e){super(o,"COMPLEXITY_ANALYSIS_ERROR",e),this.name="ComplexityAnalysisError"}},s=class extends r{constructor(e,t){super(e,"ROUTING_TIMEOUT");this.timeoutMs=t;this.name="RoutingTimeoutError"}timeoutMs};export{u as a,d as b,y as c,r as d,a as e,i as f,s as g};
|
|
@@ -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 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 t}from"./chunk-GGZB2ZBB.js";import{randomInt as o}from"node:crypto";function a(){return Math.random()}function m(n,e){return o(n,e)}function c(n,e){return n+Math.random()*(e-n)}var r=t(()=>{"use strict"});export{a,m as b,c,r as d};
|
|
@@ -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-K2D3YW2N.js";import{a as dt}from"./chunk-3J2QITXC.js";import{a as mt,b as gt}from"./chunk-KBQRYAHZ.js";import{j as I}from"./chunk-HEF6XKA5.js";import{a as lt,b as ut}from"./chunk-DTOKJKSE.js";import{a as nt}from"./chunk-TK6CHESH.js";import{a as at,b as ot,c as ct}from"./chunk-5A5EC5RD.js";import{b as st}from"./chunk-GNCGRDQ2.js";import{a as ge}from"./chunk-UWBHR4EZ.js";import{i as w,m as me}from"./chunk-DPJLA7JW.js";import{a as an}from"./chunk-T5L65R23.js";import{c as it}from"./chunk-66KIIH6V.js";import{b as M,d as rt}from"./chunk-2G2XD6EM.js";import{a as v,b,c as y}from"./chunk-ZU3XUBDQ.js";import{a as h,b as tt,c as k}from"./chunk-XRF5MX4Q.js";import{i as T}from"./chunk-FF53QW6C.js";import{R as on,S as cn}from"./chunk-AXXFY7PX.js";import{c as z,e as sn,g as et}from"./chunk-62F5M5OO.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-K2D3YW2N.js";import{a as dt}from"./chunk-3J2QITXC.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-QKWUSEBV.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-GTURQ454.js";import{S as oe,i as j,p as q}from"./chunk-AXXFY7PX.js";import{c as g,e as D,g as $}from"./chunk-62F5M5OO.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};
|