agentic-qe 3.9.35 → 3.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +131 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-WTE6UVGP.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-4PJZ34PF.js → agent-booster-wasm-5UDM2PWG.js} +2 -2
- package/dist/cli/chunks/{agent-handler-OB5JATVT.js → agent-handler-JSYER5YC.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-ZEHRWZ5R.js → agent-memory-branch-T2SAHI4F.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-LCLEBU7D.js +2 -0
- package/dist/cli/chunks/{audit-PWFRSBBW.js → audit-HIBRVGXG.js} +2 -2
- package/dist/cli/chunks/base-73I73HBF.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-XEOLAMMR.js → better-sqlite3-Y6GX6CGB.js} +2 -2
- package/dist/cli/chunks/{brain-handler-6SMUCFO7.js → brain-handler-N6AWIMXG.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-U6ROQR4O.js → branch-enumerator-VYQGBVEJ.js} +2 -2
- package/dist/cli/chunks/{browser-BMM57TA3.js → browser-2X4WKZPT.js} +2 -2
- package/dist/cli/chunks/browser-workflow-2NSV5O6W.js +2 -0
- package/dist/cli/chunks/{chunk-GWXP36YP.js → chunk-27ACATRH.js} +2 -2
- package/dist/cli/chunks/{chunk-3R6YQEQY.js → chunk-2GL4GH52.js} +4 -4
- package/dist/cli/chunks/{chunk-MSEG7GKM.js → chunk-2POXDKUB.js} +1 -1
- package/dist/cli/chunks/chunk-3BO7EKGO.js +12 -0
- package/dist/cli/chunks/{chunk-X3GKTB6R.js → chunk-3OSCWD7Z.js} +1 -1
- package/dist/cli/chunks/{chunk-WU3RGTLV.js → chunk-3QULDB7K.js} +1 -1
- package/dist/cli/chunks/{chunk-FXITHMQB.js → chunk-3U77XX6J.js} +4 -4
- package/dist/cli/chunks/{chunk-BEJAUYFA.js → chunk-4NQ6KANC.js} +2 -2
- package/dist/cli/chunks/{chunk-56O5V5MP.js → chunk-4UUDFWOP.js} +2 -2
- package/dist/cli/chunks/{chunk-7RNLOYAP.js → chunk-4WYGUTSF.js} +2 -2
- package/dist/cli/chunks/{chunk-HSR7EHVN.js → chunk-55JPAF56.js} +1 -1
- package/dist/cli/chunks/{chunk-T4HZLBM4.js → chunk-5QJDH4Z5.js} +2 -2
- package/dist/cli/chunks/{chunk-UQ6JC3UY.js → chunk-5RQT7EJP.js} +3 -3
- package/dist/cli/chunks/{chunk-CROIRPKG.js → chunk-5UOV7T36.js} +2 -2
- package/dist/cli/chunks/{chunk-HMIRBSTI.js → chunk-66GIKUI2.js} +2 -2
- package/dist/cli/chunks/{chunk-YLYKRAGZ.js → chunk-6F3WJOU2.js} +2 -2
- package/dist/cli/chunks/{chunk-SSJV4AZ7.js → chunk-6H5MRVJS.js} +6 -6
- package/dist/cli/chunks/{chunk-MHUPY3YO.js → chunk-6HCHW5TS.js} +2 -2
- package/dist/cli/chunks/{chunk-FMV22K3J.js → chunk-6MONUYQ5.js} +2 -2
- package/dist/cli/chunks/{chunk-HGJGU625.js → chunk-7Y54QZKF.js} +2 -2
- package/dist/cli/chunks/{chunk-JNK742DP.js → chunk-7ZIRDBXH.js} +1 -1
- package/dist/cli/chunks/{chunk-YPJ2O3TE.js → chunk-AFFYJSW2.js} +2 -2
- package/dist/cli/chunks/{chunk-4NVDPO7L.js → chunk-ALCQRJDY.js} +2 -2
- package/dist/cli/chunks/{chunk-BTPDHALG.js → chunk-BQT4J3BD.js} +2 -2
- package/dist/cli/chunks/{chunk-3UGY4ZQB.js → chunk-BQX5QDU5.js} +1 -1
- package/dist/cli/chunks/{chunk-BSM7YJBY.js → chunk-BTIVIWIG.js} +1 -1
- package/dist/cli/chunks/{chunk-3YIVRMQB.js → chunk-BXCS55GB.js} +1 -1
- package/dist/cli/chunks/{chunk-5CZDHJZX.js → chunk-C5QESAYA.js} +1 -1
- package/dist/cli/chunks/{chunk-CTU4V32J.js → chunk-CU4IUJ2K.js} +2 -2
- package/dist/cli/chunks/{chunk-6TYWIS4R.js → chunk-DQJJS4AX.js} +2 -2
- package/dist/cli/chunks/{chunk-OPD6AENV.js → chunk-DQLEZBWV.js} +2 -2
- package/dist/cli/chunks/{chunk-ACL5JFJR.js → chunk-DXV6NRG3.js} +2 -2
- package/dist/cli/chunks/{chunk-5XXZQCHS.js → chunk-DY7IRNE2.js} +1 -1
- package/dist/cli/chunks/{chunk-NPUMPLL7.js → chunk-F363JJUI.js} +1 -1
- package/dist/cli/chunks/{chunk-HAOGVFKR.js → chunk-FCSJ7GIZ.js} +2 -2
- package/dist/cli/chunks/{chunk-6WZNRHJJ.js → chunk-FEBXP74Y.js} +1 -1
- package/dist/cli/chunks/{chunk-G6BJ5I57.js → chunk-FQ5FT7IE.js} +1 -1
- package/dist/cli/chunks/{chunk-SI6VUQSI.js → chunk-FX4SYT6Y.js} +3 -3
- package/dist/cli/chunks/{chunk-INCNWH3R.js → chunk-G2HA2O3R.js} +2 -2
- package/dist/cli/chunks/{chunk-M4BCSFVN.js → chunk-GPKZ4MMH.js} +1 -1
- package/dist/cli/chunks/{chunk-QOAVXGAU.js → chunk-GXCD7GNH.js} +2 -2
- package/dist/cli/chunks/{chunk-4UZ7G2KT.js → chunk-HD5NQDOL.js} +2 -2
- package/dist/cli/chunks/{chunk-NS4P3VRA.js → chunk-HD6CZBZV.js} +2 -2
- package/dist/cli/chunks/{chunk-RPRFDO23.js → chunk-HIWBW4IQ.js} +1 -1
- package/dist/cli/chunks/{chunk-GHMIADYW.js → chunk-HZPXOAFW.js} +2 -2
- package/dist/cli/chunks/{chunk-3BDZSWCA.js → chunk-I4E6CLC4.js} +2 -2
- package/dist/cli/chunks/{chunk-T2QVCK56.js → chunk-I4T4JPR2.js} +1 -1
- package/dist/cli/chunks/{chunk-OJ5GBEXU.js → chunk-IBXNBLGM.js} +2 -2
- package/dist/cli/chunks/{chunk-J2LOP3GE.js → chunk-IQNR662U.js} +2 -2
- package/dist/cli/chunks/{chunk-FMAUTL26.js → chunk-J5RJYFRM.js} +2 -2
- package/dist/cli/chunks/{chunk-2UY3X3KE.js → chunk-JCKX2LEJ.js} +9 -9
- package/dist/cli/chunks/{chunk-2ICMLI2T.js → chunk-JKVNZASH.js} +2 -2
- package/dist/cli/chunks/{chunk-IQ363U37.js → chunk-JUICZG3T.js} +2 -2
- package/dist/cli/chunks/{chunk-RP5SDWCL.js → chunk-KCHFF4IE.js} +9 -9
- package/dist/cli/chunks/{chunk-NJUNYXMH.js → chunk-KDFW7MVM.js} +2 -2
- package/dist/cli/chunks/{chunk-DEJW6GYF.js → chunk-KNL3QWVA.js} +2 -2
- package/dist/cli/chunks/{chunk-5Q7X5SDB.js → chunk-KOSKGZK4.js} +2 -2
- package/dist/cli/chunks/{chunk-D2ITP3ON.js → chunk-KYLJERZ3.js} +2 -2
- package/dist/cli/chunks/{chunk-S3QU54ZQ.js → chunk-L2AIES7X.js} +1 -1
- package/dist/cli/chunks/{chunk-YYKZVBIG.js → chunk-L3IFZ4IX.js} +2 -2
- package/dist/cli/chunks/{chunk-42QMNST6.js → chunk-L4N6PTIC.js} +2 -2
- package/dist/cli/chunks/{chunk-I7XQT6YM.js → chunk-LDMG4372.js} +2 -2
- package/dist/cli/chunks/{chunk-NAVH552F.js → chunk-LQ3TA22E.js} +2 -2
- package/dist/cli/chunks/{chunk-2FTSVPVG.js → chunk-LRISVDVO.js} +1 -1
- package/dist/cli/chunks/{chunk-M7TDNJMZ.js → chunk-LXHA55EB.js} +1 -1
- package/dist/cli/chunks/{chunk-HKQ23RPJ.js → chunk-LYVFC7C7.js} +2 -2
- package/dist/cli/chunks/{chunk-BTQA2E2Y.js → chunk-M3M7HXDH.js} +2 -2
- package/dist/cli/chunks/{chunk-BKF3E3UJ.js → chunk-M4HDBRVJ.js} +1 -1
- package/dist/cli/chunks/{chunk-XMCMLPXY.js → chunk-M73IL7FA.js} +2 -2
- package/dist/cli/chunks/{chunk-UDKBQAAH.js → chunk-MF3XRML3.js} +2 -2
- package/dist/cli/chunks/{chunk-E7N6CRFV.js → chunk-MJBXQXSX.js} +1 -1
- package/dist/cli/chunks/{chunk-F6R2TGNS.js → chunk-NLCUQMUR.js} +2 -2
- package/dist/cli/chunks/{chunk-UJTI5MRE.js → chunk-NT4PI5HI.js} +2 -2
- package/dist/cli/chunks/{chunk-I5XEXLBF.js → chunk-NWHSEXHA.js} +1 -1
- package/dist/cli/chunks/{chunk-FPPV7TYI.js → chunk-O3NAUNFC.js} +2 -2
- package/dist/cli/chunks/{chunk-TE27EK44.js → chunk-OGT45MZN.js} +2 -2
- package/dist/cli/chunks/{chunk-RZDMSTAQ.js → chunk-OKGK7DBT.js} +2 -2
- package/dist/cli/chunks/{chunk-X27VMOIH.js → chunk-OUJJ34JH.js} +1 -1
- package/dist/cli/chunks/{chunk-A5LZVQQL.js → chunk-OWMGD7FO.js} +3 -3
- package/dist/cli/chunks/{chunk-AAVOYIKA.js → chunk-P6XYFDXN.js} +1 -1
- package/dist/cli/chunks/{chunk-TLBIFZM4.js → chunk-PNDO4W4L.js} +2 -2
- package/dist/cli/chunks/{chunk-WFVBK7N3.js → chunk-QL3U5VSM.js} +2 -2
- package/dist/cli/chunks/{chunk-6SN55CMC.js → chunk-QU54GUEA.js} +2 -2
- package/dist/cli/chunks/{chunk-YBGQT3OS.js → chunk-QWBO76AU.js} +2 -2
- package/dist/cli/chunks/{chunk-Z6NUCGQA.js → chunk-RARSTEUO.js} +1 -1
- package/dist/cli/chunks/{chunk-JW4N25B5.js → chunk-RF6QKV7M.js} +2 -2
- package/dist/cli/chunks/{chunk-T26ENWX5.js → chunk-RGONSQ44.js} +8 -8
- package/dist/cli/chunks/{chunk-PK3NAZQI.js → chunk-RH3PHCJT.js} +2 -2
- package/dist/cli/chunks/{chunk-WGWOCTQW.js → chunk-S33246T4.js} +1 -1
- package/dist/cli/chunks/{chunk-BXBUUSJN.js → chunk-S4CNA6Z5.js} +3 -3
- package/dist/cli/chunks/{chunk-YL56FMCJ.js → chunk-SCYF5CQA.js} +1 -1
- package/dist/cli/chunks/{chunk-SBDRHY3I.js → chunk-SGONA5GS.js} +2 -2
- package/dist/cli/chunks/{chunk-4YKHVRQH.js → chunk-T7DLX3LS.js} +3 -3
- package/dist/cli/chunks/{chunk-NFIOKKA6.js → chunk-TEJPHJMW.js} +2 -2
- package/dist/cli/chunks/{chunk-FMZ7I4XV.js → chunk-TR7BZLB6.js} +1 -1
- package/dist/cli/chunks/{chunk-VMMPOLUV.js → chunk-U56TIYGP.js} +2 -2
- package/dist/cli/chunks/{chunk-H7V3ZQT7.js → chunk-UCIJCRPB.js} +2 -2
- package/dist/cli/chunks/{chunk-GR732YA3.js → chunk-UCXQQCIP.js} +2 -2
- package/dist/cli/chunks/{chunk-IXOGBA7C.js → chunk-UE3XXKLN.js} +2 -2
- package/dist/cli/chunks/{chunk-KAEWFVGD.js → chunk-UGX4EHT5.js} +2 -2
- package/dist/cli/chunks/{chunk-ICYM7H6T.js → chunk-URVDWF2Y.js} +2 -2
- package/dist/cli/chunks/{chunk-BCD2IMXF.js → chunk-V5TRAL57.js} +2 -2
- package/dist/cli/chunks/{chunk-A7QP5E46.js → chunk-VEOQH4W6.js} +2 -2
- package/dist/cli/chunks/{chunk-CMKNLC3Q.js → chunk-VMJXNTJT.js} +4 -4
- package/dist/cli/chunks/{chunk-PY7PJT2Y.js → chunk-VTIXFHZR.js} +2 -2
- package/dist/cli/chunks/{chunk-YTB7DDLE.js → chunk-VTO5O7DA.js} +1 -1
- package/dist/cli/chunks/{chunk-C7QVMFCJ.js → chunk-W6U7SIIK.js} +3 -3
- package/dist/cli/chunks/{chunk-II6DIMY6.js → chunk-WC6KZDPM.js} +2 -2
- package/dist/cli/chunks/{chunk-4HJVTKJD.js → chunk-WG6I7YF3.js} +1 -1
- package/dist/cli/chunks/{chunk-GWROZUWK.js → chunk-WLLE54TA.js} +1 -1
- package/dist/cli/chunks/{chunk-BBHTM2RF.js → chunk-WVCIZIKH.js} +1 -1
- package/dist/cli/chunks/{chunk-ZAGCKWOC.js → chunk-X4U5NYB6.js} +1 -1
- package/dist/cli/chunks/chunk-X73CRYF4.js +2 -0
- package/dist/cli/chunks/{chunk-GQCIW2ZZ.js → chunk-XFMSHTXG.js} +1 -1
- package/dist/cli/chunks/{chunk-NWWXVXXG.js → chunk-XFUU2RCA.js} +2 -2
- package/dist/cli/chunks/{chunk-WSJN6HFR.js → chunk-Y4I5JBOL.js} +2 -2
- package/dist/cli/chunks/{chunk-XUZ73S3Y.js → chunk-YHNEBCYQ.js} +2 -2
- package/dist/cli/chunks/{chunk-O3MTYRBX.js → chunk-YYDHTBHE.js} +1 -1
- package/dist/cli/chunks/{chunk-6CCKOU2U.js → chunk-Z2SCTEZD.js} +2 -2
- package/dist/cli/chunks/{chunk-72HXOVRN.js → chunk-Z6JLPPAY.js} +1 -1
- package/dist/cli/chunks/{chunk-NZB2JE2D.js → chunk-ZCNVFULO.js} +2 -2
- package/dist/cli/chunks/{chunk-VLZ3LC6L.js → chunk-ZFBMBCKN.js} +2 -2
- package/dist/cli/chunks/{chunk-SMPMLODT.js → chunk-ZYZWBNKT.js} +1 -1
- package/dist/cli/chunks/{ci-GXSOJB6I.js → ci-7TR4NQ5I.js} +2 -2
- package/dist/cli/chunks/{ci-output-GNUGZD2F.js → ci-output-SLTICF3O.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-LAW2AAHF.js → circuit-breaker-7GVVTMBY.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-VF5NUUJZ.js → claude-flow-setup-TYCWYEMM.js} +2 -2
- package/dist/cli/chunks/client-7GB4WWUD.js +2 -0
- package/dist/cli/chunks/{cline-installer-H7RPYI3G.js → cline-installer-ESIAJOLK.js} +2 -2
- package/dist/cli/chunks/{code-COHRPYF6.js → code-I42JGOVI.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-353PWY6B.js → code-index-extractor-2CCXPCQW.js} +2 -2
- package/dist/cli/chunks/{codex-installer-DIXHDH63.js → codex-installer-HEZRDNUT.js} +2 -2
- package/dist/cli/chunks/{completions-NGPREB6E.js → completions-44HLIZGI.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-BO3QCTWT.js → complexity-analyzer-SOCSFDVO.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-SG4HUNX6.js → continuedev-installer-Q7O4HLIM.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-RC6ZFHQG.js → copilot-installer-GIWCVLCS.js} +2 -2
- package/dist/cli/chunks/{cost-tracker-Q76KFISR.js → cost-tracker-G7BONKEV.js} +2 -2
- package/dist/cli/chunks/{coverage-PT23ZOGU.js → coverage-5TWVP7KY.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-7HQ74TLE.js +2 -0
- package/dist/cli/chunks/{cursor-installer-ZDS65WC6.js → cursor-installer-43EQZSB5.js} +2 -2
- package/dist/cli/chunks/{daemon-M32BWOES.js → daemon-QQZE4BU2.js} +4 -4
- package/dist/cli/chunks/{daemon-ZRDBUK4Q.js → daemon-ZXHFRDKG.js} +3 -3
- package/dist/cli/chunks/{dag-attention-scheduler-GUPZT7PR.js → dag-attention-scheduler-GOZAVAZQ.js} +2 -2
- package/dist/cli/chunks/{detect-PZNLC2CO.js → detect-X777GVJ4.js} +2 -2
- package/dist/cli/chunks/{dist-node-QO5MMHVF.js → dist-node-EZZK46TB.js} +2 -2
- package/dist/cli/chunks/{domain-handler-OH2YSZCT.js → domain-handler-ZT32DKYY.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-TVTK2YX5.js → domain-transfer-LHQVSLJW.js} +2 -2
- package/dist/cli/chunks/dream-G5SEFHI4.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-2ARE7NCX.js → embed-and-insert-pattern-XFYPPWG7.js} +2 -2
- package/dist/cli/chunks/{eval-64RXRKM4.js → eval-V4NYJZUZ.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-TH7JERGY.js → experience-capture-middleware-HXX2W4GL.js} +3 -3
- package/dist/cli/chunks/{fast-paths-IAWNSJFU.js → fast-paths-RBPWQSFJ.js} +2 -2
- package/dist/cli/chunks/{feature-flags-TAKLIOWM.js → feature-flags-INJJZBMN.js} +2 -2
- package/dist/cli/chunks/{feature-flags-22FDDEFG.js → feature-flags-NX5EXRO3.js} +2 -2
- package/dist/cli/chunks/{file-discovery-QWEHC5VO.js → file-discovery-SNFSG6NK.js} +2 -2
- package/dist/cli/chunks/{fleet-5PQX4H2Q.js → fleet-6SDN4UWE.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-RR5EYGCL.js → gnn-wrapper-2JDRTDDK.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-QOVPD6JV.js → heartbeat-handler-QLK6E7KA.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-NG7BY3FR.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-TDSLUI7K.js +2 -0
- package/dist/cli/chunks/hnsw-index-OWLQSOQH.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-RRTRMCEL.js → hnsw-legacy-bridge-Q2ZEZQKB.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-XEIBI22V.js → hnswlib-node-TA4DZV62.js} +2 -2
- package/dist/cli/chunks/{hooks-DTEIDS42.js → hooks-D4YENHO2.js} +53 -53
- package/dist/cli/chunks/{hybrid-router-E36GZC7Q.js → hybrid-router-URU2XLBD.js} +2 -2
- package/dist/cli/chunks/{hypergraph-engine-7VTF3N6A.js → hypergraph-engine-G72U446M.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-CTUGX3DL.js → hypergraph-handler-TRZ5FDRH.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-NMTN75KA.js +2 -0
- package/dist/cli/chunks/{init-handler-HRSUGKSE.js → init-handler-3ZD4GCT4.js} +6 -6
- package/dist/cli/chunks/init-wizard-SHBFYGBV.js +2 -0
- package/dist/cli/chunks/kernel-7KVY2JGO.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-UGB5UY5B.js → kilocode-installer-AXSIW3XW.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-7SAM5O2F.js → kiro-installer-JQGIFWBK.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-V4G5J5B7.js +2 -0
- package/dist/cli/chunks/{learning-GBRPEBXN.js → learning-SPO7TGWX.js} +3 -3
- package/dist/cli/chunks/{llm-router-YP2RW2QC.js → llm-router-G6N2OKDA.js} +4 -4
- package/dist/cli/chunks/{load-3TRJPJBJ.js → load-XIDDK64U.js} +2 -2
- package/dist/cli/chunks/load-test-N4RNPLG4.js +2 -0
- package/dist/cli/chunks/{mcp-U7ZYZTEU.js → mcp-3JXRGXO4.js} +2 -2
- package/dist/cli/chunks/{memory-CLBPDAAE.js → memory-A66KRS2P.js} +5 -5
- package/dist/cli/chunks/memory-backend-HPGJ5YDQ.js +2 -0
- package/dist/cli/chunks/{memory-handlers-JEOU6AOR.js → memory-handlers-K33YVCVQ.js} +2 -2
- package/dist/cli/chunks/{multi-model-executor-MPPD63KI.js → multi-model-executor-XCDGUVCE.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-DIMXI5PK.js → opencode-installer-GELXWLF2.js} +2 -2
- package/dist/cli/chunks/{orchestrator-YKOSNTFS.js → orchestrator-CCS3K6NH.js} +5 -5
- package/dist/cli/chunks/{pipeline-SDCM3CNA.js → pipeline-Z5C72H5S.js} +2 -2
- package/dist/cli/chunks/{platform-7UH4BXN7.js → platform-4AK7XJ3Y.js} +2 -2
- package/dist/cli/chunks/{plugin-KIVAXJ3P.js → plugin-7RYBIZI7.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-PONLGWM6.js → prime-radiant-advanced-wasm-E5PARKRX.js} +2 -2
- package/dist/cli/chunks/protocol-executor-GNVWUJUP.js +2 -0
- package/dist/cli/chunks/{protocol-handler-6RYLLDOG.js → protocol-handler-R6QJQFNL.js} +2 -2
- package/dist/cli/chunks/{prove-PDFFRQQW.js → prove-7ESQ2YAL.js} +2 -2
- package/dist/cli/chunks/{provider-manager-I6R4EQGK.js → provider-manager-HV55NIIO.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-DDSBHO6D.js +2 -0
- package/dist/cli/chunks/{quality-KQVKAGWL.js → quality-4UE345QA.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-BQJ5O63C.js +2 -0
- package/dist/cli/chunks/real-embeddings-TYIVN3N5.js +2 -0
- package/dist/cli/chunks/{roocode-installer-RYPQ25JO.js → roocode-installer-2KOANC47.js} +2 -2
- package/dist/cli/chunks/router-C2RKWB7J.js +2 -0
- package/dist/cli/chunks/routing-feedback-RHATTSJ6.js +2 -0
- package/dist/cli/chunks/{routing-handler-U4FEWPIN.js → routing-handler-JFEYTN7T.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-YID52EZ6.js → ruvector-commands-KSLSZRJX.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-HABBORJW.js → rvf-dual-writer-EPBL226J.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-JE5NWU3J.js → rvf-migration-adapter-25KSI6SF.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-FBIFWTAD.js → rvf-migration-coordinator-2XBYHPZP.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-QG4CXHLL.js +2 -0
- package/dist/cli/chunks/safe-db-A4KQ2IDB.js +2 -0
- package/dist/cli/chunks/schedule-O7MLASQT.js +2 -0
- package/dist/cli/chunks/scheduler-HT7RNYQ2.js +2 -0
- package/dist/cli/chunks/{security-22ERFMD6.js → security-4XWYKI4O.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-YU7XN6ND.js → shared-rvf-adapter-WRZ3HGDQ.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-G5VIQHSN.js → shared-rvf-dual-writer-DX2N5STR.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-4NNKJ6CQ.js +2 -0
- package/dist/cli/chunks/{status-handler-5B3FP2DN.js → status-handler-V75OSXMQ.js} +2 -2
- package/dist/cli/chunks/{structural-health-6YSKVKQG.js → structural-health-TLX3JHZ6.js} +2 -2
- package/dist/cli/chunks/{sync-OFSJUYBU.js → sync-DXZFMVZQ.js} +2 -2
- package/dist/cli/chunks/{sync-2YCW23XX.js → sync-KGBEXUF7.js} +2 -2
- package/dist/cli/chunks/{task-handler-6OIPFSXX.js → task-handler-T3OJ6R7H.js} +2 -2
- package/dist/cli/chunks/{task-handlers-6QY5Q5IH.js → task-handlers-NJYR54AS.js} +3 -3
- package/dist/cli/chunks/{test-VR6EP23Y.js → test-KMVDNNQA.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-OI7N5QBA.js → test-scheduling-R5EQ2XGV.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-HZES3TAA.js → token-bootstrap-PFKVV3RO.js} +2 -2
- package/dist/cli/chunks/{token-usage-2NSXSNS7.js → token-usage-ZLOGA6LR.js} +2 -2
- package/dist/cli/chunks/{transformers-4U4PX5YQ.js → transformers-TNPSPQI3.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-NQ3JYKHC.js → tree-sitter-wasm-parser-A2EEB5BF.js} +2 -2
- package/dist/cli/chunks/{types-YGTXBQ4T.js → types-DIXPI4NR.js} +2 -2
- package/dist/cli/chunks/unified-memory-CMNJVHOJ.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-JQLU2KI6.js +2 -0
- package/dist/cli/chunks/unified-persistence-I25TEDIU.js +2 -0
- package/dist/cli/chunks/{upgrade-GS4EJOHW.js → upgrade-LX5KP6VO.js} +2 -2
- package/dist/cli/chunks/{validate-4X7OETYQ.js → validate-3L6F7M36.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-RSVPLHZQ.js → validate-swarm-FD42ZKAQ.js} +2 -2
- package/dist/cli/chunks/{vibium-SN2J4QEA.js → vibium-GSBSJR53.js} +2 -2
- package/dist/cli/chunks/visual-security-AJJIEV5V.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-ZO6DPXRC.js → web-tree-sitter-TXHMO4BW.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-RGSOOJSH.js → windsurf-installer-3EUZ6RD3.js} +2 -2
- package/dist/cli/chunks/witness-chain-762QQBTN.js +2 -0
- package/dist/cli/chunks/{witness-chain-7XBKRDAW.js → witness-chain-ONAUEJ4M.js} +2 -2
- package/dist/cli/chunks/{workflow-H7KG5R6L.js → workflow-E7A6BV4C.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-ZGPYISKY.js +2 -0
- package/dist/cli/chunks/{wrappers-3YCDNHDG.js → wrappers-AHHAQJM3.js} +2 -2
- package/dist/cli/commands/hooks-handlers/hooks-dream-learning.d.ts +3 -3
- package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +4 -3
- package/dist/cli/commands/hooks-handlers/routing-hooks.js +50 -12
- package/dist/cli/commands/hooks-handlers/task-hooks.js +30 -6
- package/dist/learning/agent-routing.d.ts +13 -1
- package/dist/learning/agent-routing.js +14 -1
- package/dist/learning/embedder-endpoint-client.d.ts +133 -0
- package/dist/learning/embedder-endpoint-client.js +426 -0
- package/dist/learning/embedder-identity-store.d.ts +30 -0
- package/dist/learning/embedder-identity-store.js +136 -0
- package/dist/learning/qe-reasoning-bank.js +15 -5
- package/dist/learning/real-embeddings.d.ts +28 -0
- package/dist/learning/real-embeddings.js +130 -19
- package/dist/learning/sqlite-persistence.js +16 -3
- package/dist/mcp/bundle.js +399 -389
- package/package.json +1 -1
- package/dist/cli/chunks/adapter-JUISYMI3.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-DEIUPULJ.js +0 -2
- package/dist/cli/chunks/base-7SMQWXHT.js +0 -2
- package/dist/cli/chunks/browser-workflow-4DGHRZLS.js +0 -2
- package/dist/cli/chunks/chunk-PHJK33IV.js +0 -2
- package/dist/cli/chunks/chunk-YQRABKOC.js +0 -2
- package/dist/cli/chunks/client-OSUT6W6W.js +0 -2
- package/dist/cli/chunks/cross-domain-router-X5EEGWMA.js +0 -2
- package/dist/cli/chunks/dream-CP4VOPNU.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-MX7EHYU5.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-B7FZYZGZ.js +0 -2
- package/dist/cli/chunks/hnsw-index-7OVB67MX.js +0 -2
- package/dist/cli/chunks/impact-analyzer-TG34YBHU.js +0 -2
- package/dist/cli/chunks/init-wizard-MS3A2X5C.js +0 -2
- package/dist/cli/chunks/kernel-J4IW4DA6.js +0 -2
- package/dist/cli/chunks/knowledge-graph-4LCYX5AN.js +0 -2
- package/dist/cli/chunks/load-test-TFBVT7V3.js +0 -2
- package/dist/cli/chunks/memory-backend-E7OCG27P.js +0 -2
- package/dist/cli/chunks/protocol-executor-MYFH7ZP4.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-G46PVD2U.js +0 -2
- package/dist/cli/chunks/queen-coordinator-ZQRKBBUH.js +0 -2
- package/dist/cli/chunks/real-embeddings-VQXMPAH6.js +0 -2
- package/dist/cli/chunks/router-UBQULTOO.js +0 -2
- package/dist/cli/chunks/routing-feedback-3VBS3SYD.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-NDKSHCMG.js +0 -2
- package/dist/cli/chunks/safe-db-ZPGX4NYW.js +0 -2
- package/dist/cli/chunks/schedule-JZUKDE6O.js +0 -2
- package/dist/cli/chunks/scheduler-7YIQOOW3.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-4STSI5SJ.js +0 -2
- package/dist/cli/chunks/unified-memory-R72C7IBY.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-A4LOFKDQ.js +0 -2
- package/dist/cli/chunks/unified-persistence-MYD2R4LE.js +0 -2
- package/dist/cli/chunks/visual-security-CUKQ5N37.js +0 -2
- package/dist/cli/chunks/witness-chain-S7ADS6TA.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-3GIDXU43.js +0 -2
|
@@ -1,10 +1,10 @@
|
|
|
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.
|
|
2
|
-
import{b as Z}from"./chunk-72HXOVRN.js";import{b as X}from"./chunk-WFVBK7N3.js";import"./chunk-FMAUTL26.js";import{a as y,b as B}from"./chunk-BTQA2E2Y.js";import{a as Y}from"./chunk-D2ITP3ON.js";import"./chunk-MSEG7GKM.js";import{c as J}from"./chunk-3YIVRMQB.js";import{a as U,r as j}from"./chunk-CMKNLC3Q.js";import"./chunk-UDKBQAAH.js";import"./chunk-A5LZVQQL.js";import"./chunk-T4HZLBM4.js";import"./chunk-SSJV4AZ7.js";import"./chunk-3R6YQEQY.js";import"./chunk-5CZDHJZX.js";import"./chunk-XUZ73S3Y.js";import"./chunk-GWROZUWK.js";import"./chunk-X3GKTB6R.js";import"./chunk-NPUMPLL7.js";import"./chunk-A7QP5E46.js";import"./chunk-HKQ23RPJ.js";import"./chunk-VMMPOLUV.js";import"./chunk-PK3NAZQI.js";import"./chunk-RP5SDWCL.js";import"./chunk-YQRABKOC.js";import{k as R,o as te}from"./chunk-IXOGBA7C.js";import"./chunk-NFIOKKA6.js";import"./chunk-RZDMSTAQ.js";import"./chunk-ACL5JFJR.js";import"./chunk-PHJK33IV.js";import"./chunk-BTPDHALG.js";import{a as w}from"./chunk-6WZNRHJJ.js";import{a as b,c as V}from"./chunk-DEJW6GYF.js";import"./chunk-E7N6CRFV.js";import"./chunk-NZB2JE2D.js";import"./chunk-6SN55CMC.js";import"./chunk-FPPV7TYI.js";import"./chunk-3BDZSWCA.js";import"./chunk-UJTI5MRE.js";import"./chunk-HMIRBSTI.js";import"./chunk-SBDRHY3I.js";import"./chunk-CROIRPKG.js";import"./chunk-5Q7X5SDB.js";import"./chunk-HSR7EHVN.js";var _=class{handlers=[];async publish(e){for(let t of this.handlers)try{t(e)}catch(n){console.debug("[WorkerManager] Event handler error:",n instanceof Error?n.message:n)}}subscribe(e){return this.handlers.push(e),()=>{let t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)}}dispose(){this.handlers=[]}get handlerCount(){return this.handlers.length}},G=class{store=new Map;async get(e){return this.store.get(e)}async set(e,t){this.store.set(e,t)}async search(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(t.replace(/\*/g,".*"));return Array.from(this.store.keys()).filter(s=>n.test(s))}clear(){this.store.clear()}get size(){return this.store.size}},O=class{constructor(e){this.workerId=e}workerId;format(e,t,n){let s=new Date().toISOString(),r=n?` ${JSON.stringify(n)}`:"";return`[${s}] [${e}] [${this.workerId}] ${t}${r}`}debug(e,t){process.env.DEBUG&&console.debug(this.format("DEBUG",e,t))}info(e,t){console.info(this.format("INFO",e,t))}warn(e,t){console.warn(this.format("WARN",e,t))}error(e,t){console.error(this.format("ERROR",e,t))}},L=class{constructor(e){this.kernelGetter=e}kernelGetter;getDomainAPI(e){let t=this.kernelGetter();if(t)return t.getDomainAPI(e)}getDomainHealth(e){let t=this.kernelGetter();if(!t)return{status:"unknown",errors:["Kernel not available"]};let s=t.getHealth().domains[e];return s?{status:s.status,errors:s.errors||[]}:{status:"unknown",errors:[`Domain ${e} not found`]}}},H=class{getDomainAPI(e){}getDomainHealth(e){return{status:"healthy",errors:[]}}},N=class{workers=new Map;timers=new Map;abortControllers=new Map;eventBus;memory;domainAccess;running=!1;kernelRef;constructor(e){this.eventBus=e?.eventBus??new _,this.memory=e?.memory??new G,this.kernelRef=e?.kernel,e?.domainAccess?this.domainAccess=e.domainAccess:e?.kernel?this.domainAccess=new L(()=>this.kernelRef):this.domainAccess=new H}setKernel(e){this.kernelRef=e,this.domainAccess instanceof H&&(this.domainAccess=new L(()=>this.kernelRef))}setMemory(e){this.memory=e}register(e){if(this.workers.has(e.config.id))throw new Error(`Worker ${e.config.id} is already registered`);this.workers.set(e.config.id,e)}unregister(e){this.workers.get(e)&&(this.stopWorker(e),this.workers.delete(e))}get(e){return this.workers.get(e)}list(){return Array.from(this.workers.values())}async startAll(){this.running=!0;for(let e of Array.from(this.workers.values()))e.config.enabled&&await this.startWorker(e)}async stopAll(){this.running=!1;let e=[];for(let t of Array.from(this.workers.keys()))e.push(this.stopWorker(t));await Promise.all(e)}async runNow(e){let t=this.workers.get(e);if(!t)throw new Error(`Worker ${e} not found`);let n=this.timers.get(e);n&&clearTimeout(n);let s=new AbortController;this.abortControllers.set(e,s);let r=this.createContext(e,s.signal),i=await t.execute(r);return this.running&&t.config.enabled&&t.status!=="stopped"&&this.scheduleNextRun(t),i}getHealth(){let e={},t=0,n=0,s=0,r=0;for(let[o,a]of Array.from(this.workers.entries())){let c=a.getHealth();switch(e[o]=c,r+=c.healthScore,a.status){case"running":t++;break;case"paused":n++;break;case"error":s++;break}}let i=this.workers.size>0?Math.round(r/this.workers.size):100;return{totalWorkers:this.workers.size,runningWorkers:t,pausedWorkers:n,errorWorkers:s,healthScore:i,workers:e}}onWorkerEvent(e){return this.eventBus.subscribe(e)}async startWorker(e){await e.initialize();let t=new AbortController;this.abortControllers.set(e.config.id,t);let n=this.createContext(e.config.id,t.signal);try{await e.execute(n)}catch(s){console.error(`Worker ${e.config.id} initial execution failed:`,s)}this.scheduleNextRun(e)}async stopWorker(e){let t=this.timers.get(e);t&&(clearTimeout(t),this.timers.delete(e));let n=this.abortControllers.get(e);n&&(n.abort(),this.abortControllers.delete(e));let s=this.workers.get(e);s&&await s.stop()}scheduleNextRun(e){let t=setTimeout(async()=>{if(!this.running||e.status==="stopped"||e.status==="paused")return;let n=new AbortController;this.abortControllers.set(e.config.id,n);let s=this.createContext(e.config.id,n.signal);try{await e.execute(s)}catch(r){console.error(`Worker ${e.config.id} execution failed:`,r)}this.running&&e.config.enabled&&e.status!=="error"&&this.scheduleNextRun(e)},e.config.intervalMs);this.timers.set(e.config.id,t)}createContext(e,t){return{eventBus:this.eventBus,memory:this.memory,logger:new O(e),domains:this.domainAccess,signal:t}}};V();var re={id:"test-health",name:"Test Health Monitor",description:"Monitors test suite health metrics including pass rates, execution times, and reliability",intervalMs:300*1e3,priority:"high",targetDomains:["test-execution","test-generation"],enabled:!0,timeoutMs:6e4,retryCount:2,retryDelayMs:5e3},M=class extends y{previousMetrics;constructor(){super(re)}async doExecute(e){let t=Date.now();e.logger.info("Starting test health analysis");let n=[],s=[],r=await this.collectMetrics(e);this.analyzePassRate(r,n,s),this.analyzeExecutionTime(r,n,s),this.analyzeReliability(r,n,s),this.analyzeGrowth(r,n,s),this.compareToPrevious(r,n,s),await e.memory.set("test-health:previous-metrics",r),this.previousMetrics=r;let i=this.calculateHealthScore(r),o=this.determineTrend(r);return e.logger.info("Test health analysis complete",{healthScore:i,findingsCount:n.length}),this.createResult(Date.now()-t,{itemsAnalyzed:r.totalTests,issuesFound:n.length,healthScore:i,trend:o,domainMetrics:{passRate:`${(r.passingTests/r.totalTests*100).toFixed(1)}%`,avgExecutionTime:`${r.avgExecutionTimeMs}ms`,reliability:`${r.reliability}%`,totalTests:r.totalTests}},n,s)}async collectMetrics(e){let t=await e.memory.get("test-health:previous-metrics");if(t&&(this.previousMetrics=t),!e.domains.getDomainAPI("test-execution"))throw new Error("Test-execution domain not available - cannot compute health metrics. Ensure the test-execution domain is properly initialized before running this worker.");try{let s=await e.memory.search("test-health:run-result:*");if(s.length===0)throw new Error('No test run data found in memory - cannot compute health metrics. Run some tests first or ensure test results are being stored with keys matching "test-health:run-result:*".');let r=0,i=0,o=0,a=0,c=0,l=0;for(let p of s.slice(0,50)){let g=await e.memory.get(p);g&&(r+=g.total,i+=g.passed,o+=g.failed,a+=g.skipped,c+=g.duration,l++)}let m=l>0?Math.round(c/l):0,d=r>0?Math.round(i/r*100):0,f=await e.memory.get("test-health:growth-metrics");return{totalTests:r||0,passingTests:i||0,failingTests:o||0,skippedTests:a||0,avgExecutionTimeMs:m,reliability:d,growth:{testsAddedLast7Days:f?.testsAddedLast7Days||0,testsRemovedLast7Days:f?.testsRemovedLast7Days||0}}}catch(s){let r=b(s);throw new Error(`Failed to collect test health metrics: ${r}. Check memory service connectivity and test result data availability.`)}}analyzePassRate(e,t,n){let s=e.passingTests/e.totalTests*100;s<95&&(t.push({type:"low-pass-rate",severity:s<90?"high":"medium",domain:"test-execution",title:"Low Test Pass Rate",description:`Test pass rate is ${s.toFixed(1)}%, below the 95% target`,context:{passing:e.passingTests,failing:e.failingTests,total:e.totalTests}}),n.push({priority:"p1",domain:"test-execution",action:"Investigate Failing Tests",description:`${e.failingTests} tests are currently failing. Review and fix to improve pass rate.`,estimatedImpact:"high",effort:"medium",autoFixable:!1}))}analyzeExecutionTime(e,t,n){e.avgExecutionTimeMs>500&&(t.push({type:"slow-tests",severity:e.avgExecutionTimeMs>1e3?"high":"medium",domain:"test-execution",title:"Slow Test Execution",description:`Average test execution time is ${e.avgExecutionTimeMs}ms, consider optimization`,context:{avgExecutionTimeMs:e.avgExecutionTimeMs}}),n.push({priority:"p2",domain:"test-execution",action:"Optimize Test Execution Time",description:"Review and optimize slow-running tests. Consider parallelization or mocking slow dependencies.",estimatedImpact:"medium",effort:"medium",autoFixable:!1}))}analyzeReliability(e,t,n){e.reliability<95&&(t.push({type:"reliability-issue",severity:e.reliability<85?"high":"medium",domain:"test-execution",title:"Test Reliability Concern",description:`Test reliability score is ${e.reliability}%, indicating potential flaky tests`,context:{reliability:e.reliability}}),n.push({priority:"p1",domain:"test-execution",action:"Address Flaky Tests",description:"Identify and fix flaky tests to improve overall test reliability.",estimatedImpact:"high",effort:"medium",autoFixable:!1}))}analyzeGrowth(e,t,n){let s=e.growth.testsAddedLast7Days-e.growth.testsRemovedLast7Days;s<0&&(t.push({type:"test-coverage-decline",severity:"medium",domain:"test-generation",title:"Test Coverage Declining",description:`Net loss of ${Math.abs(s)} tests in the last 7 days`,context:{added:e.growth.testsAddedLast7Days,removed:e.growth.testsRemovedLast7Days}}),n.push({priority:"p2",domain:"test-generation",action:"Review Test Coverage Strategy",description:"More tests are being removed than added. Ensure adequate test coverage is maintained.",estimatedImpact:"medium",effort:"low",autoFixable:!1}))}compareToPrevious(e,t,n){if(!this.previousMetrics)return;let s=e.passingTests/e.totalTests-this.previousMetrics.passingTests/this.previousMetrics.totalTests;s<-.05&&t.push({type:"pass-rate-regression",severity:"high",domain:"test-execution",title:"Pass Rate Regression Detected",description:`Pass rate dropped by ${(Math.abs(s)*100).toFixed(1)}% since last check`,context:{previousPassRate:`${(this.previousMetrics.passingTests/this.previousMetrics.totalTests*100).toFixed(1)}%`,currentPassRate:`${(e.passingTests/e.totalTests*100).toFixed(1)}%`}})}calculateHealthScore(e){let t=e.passingTests/e.totalTests*40,n=e.reliability/100*30,s=Math.max(0,20-e.avgExecutionTimeMs/100),r=Math.min(10,e.growth.testsAddedLast7Days/10*10);return Math.round(t+n+s+r)}determineTrend(e){if(!this.previousMetrics)return"stable";let t=e.passingTests/e.totalTests,n=this.previousMetrics.passingTests/this.previousMetrics.totalTests;return t>n+.02?"improving":t<n-.02?"degrading":"stable"}};var ie={id:"coverage-tracker",name:"Coverage Tracker",description:"Tracks coverage trends over time including gaps, hotspots, and critical paths",intervalMs:600*1e3,priority:"high",targetDomains:["coverage-analysis","test-generation"],enabled:!0,timeoutMs:12e4,retryCount:2,retryDelayMs:1e4},x=class extends y{constructor(){super(ie)}async doExecute(e){let t=Date.now();e.logger.info("Starting coverage tracking analysis");let n=[],s=[],r=await this.collectCoverageTrend(e),i=await this.identifyCoverageGaps(e);this.analyzeCoverageThresholds(r.current,n,s),this.analyzeCoverageGaps(i,n,s),this.analyzeCoverageTrends(r,n,s),await e.memory.set("coverage:current",r.current),await e.memory.set("coverage:gaps",i);let o=this.calculateHealthScore(r.current,i);return e.logger.info("Coverage tracking complete",{healthScore:o,findingsCount:n.length,gapsFound:i.length}),this.createResult(Date.now()-t,{itemsAnalyzed:i.length+4,issuesFound:n.length,healthScore:o,trend:this.determineTrend(r),domainMetrics:{lineCoverage:`${r.current.line}%`,branchCoverage:`${r.current.branch}%`,functionCoverage:`${r.current.function}%`,statementCoverage:`${r.current.statement}%`,gapsCount:i.length}},n,s)}async collectCoverageTrend(e){let t=await e.memory.get("coverage:current"),n=await e.memory.get("coverage:latest");return{current:{line:n?.line??0,branch:n?.branch??0,function:n?.function??0,statement:n?.statement??0,timestamp:new Date},previous:t}}async identifyCoverageGaps(e){let t=await e.memory.search("gap-pattern:*");if(t.length>0){let n=[];for(let s of t){let r=await e.memory.get(s);r&&typeof r.riskScore=="number"&&n.push(r)}if(n.length>0)return n}return[]}analyzeCoverageThresholds(e,t,n){let s={line:80,branch:70,function:80,statement:80};e.line<s.line&&t.push({type:"low-line-coverage",severity:e.line<60?"high":"medium",domain:"coverage-analysis",title:"Line Coverage Below Threshold",description:`Line coverage is ${e.line}%, below ${s.line}% target`,context:{current:e.line,target:s.line}}),e.branch<s.branch&&(t.push({type:"low-branch-coverage",severity:e.branch<50?"high":"medium",domain:"coverage-analysis",title:"Branch Coverage Below Threshold",description:`Branch coverage is ${e.branch}%, below ${s.branch}% target`,context:{current:e.branch,target:s.branch}}),n.push({priority:"p1",domain:"test-generation",action:"Improve Branch Coverage",description:"Add tests for uncovered conditional branches. Focus on complex decision points.",estimatedImpact:"high",effort:"medium",autoFixable:!0})),e.function<s.function&&t.push({type:"low-function-coverage",severity:"medium",domain:"coverage-analysis",title:"Function Coverage Below Threshold",description:`Function coverage is ${e.function}%, below ${s.function}% target`,context:{current:e.function,target:s.function}})}analyzeCoverageGaps(e,t,n){let s=e.filter(i=>i.riskScore>.8);for(let i of s)t.push({type:"high-risk-coverage-gap",severity:"high",domain:"coverage-analysis",title:"High-Risk Coverage Gap",description:`${i.file} has ${i.uncoveredLines} uncovered lines with complexity ${i.complexity}`,resource:i.file,context:{uncoveredLines:i.uncoveredLines,totalLines:i.totalLines,coveragePercent:((i.totalLines-i.uncoveredLines)/i.totalLines*100).toFixed(1),complexity:i.complexity,riskScore:i.riskScore}});s.length>0&&n.push({priority:"p0",domain:"test-generation",action:"Address High-Risk Coverage Gaps",description:`${s.length} files have high-risk coverage gaps. Prioritize testing for complex, uncovered code.`,estimatedImpact:"high",effort:"high",autoFixable:!0});let r=e.filter(i=>(i.totalLines-i.uncoveredLines)/i.totalLines<.5);r.length>0&&t.push({type:"critical-coverage-gaps",severity:"critical",domain:"coverage-analysis",title:"Critical Coverage Gaps Detected",description:`${r.length} files have less than 50% coverage`,context:{files:r.map(i=>i.file)}})}analyzeCoverageTrends(e,t,n){if(!e.previous)return;let s=e.current.line-e.previous.line,r=e.current.branch-e.previous.branch;s<-2&&(t.push({type:"coverage-regression",severity:s<-5?"high":"medium",domain:"coverage-analysis",title:"Coverage Regression Detected",description:`Line coverage dropped by ${Math.abs(s).toFixed(1)}% since last check`,context:{previous:e.previous.line,current:e.current.line,change:s}}),n.push({priority:"p1",domain:"test-generation",action:"Investigate Coverage Regression",description:"Recent changes have reduced code coverage. Review new code and add missing tests.",estimatedImpact:"high",effort:"medium",autoFixable:!1})),r<-3&&t.push({type:"branch-coverage-regression",severity:"medium",domain:"coverage-analysis",title:"Branch Coverage Regression",description:`Branch coverage dropped by ${Math.abs(r).toFixed(1)}%`,context:{previous:e.previous.branch,current:e.current.branch,change:r}})}calculateHealthScore(e,t){let n=e.line/100*25,s=e.branch/100*25,r=e.function/100*20,i=e.statement/100*20,o=t.filter(c=>c.riskScore>.8).length,a=Math.max(0,10-o*2);return Math.round(n+s+r+i+a)}determineTrend(e){if(!e.previous)return"stable";let t=(e.current.line+e.current.branch+e.current.function+e.current.statement)/4,n=(e.previous.line+e.previous.branch+e.previous.function+e.previous.statement)/4;return t>n+1?"improving":t<n-1?"degrading":"stable"}};var ne={id:"flaky-detector",name:"Flaky Test Detector",description:"Detects flaky test patterns through statistical analysis of test execution history",intervalMs:900*1e3,priority:"high",targetDomains:["test-execution"],enabled:!0,timeoutMs:18e4,retryCount:2,retryDelayMs:1e4},P=class extends y{constructor(){super(ne)}async doExecute(e){let t=Date.now();e.logger.info("Starting flaky test detection");let n=[],s=[],r=await this.collectTestHistory(e),i=this.detectFlakyTests(r);this.generateFindings(i,n,s),await e.memory.set("flaky:detected",i),await e.memory.set("flaky:lastAnalysis",new Date().toISOString());let o=this.calculateHealthScore(r.length,i);return e.logger.info("Flaky test detection complete",{healthScore:o,testsAnalyzed:r.length,flakyTestsFound:i.length}),this.createResult(Date.now()-t,{itemsAnalyzed:r.length,issuesFound:i.length,healthScore:o,trend:"stable",domainMetrics:{testsAnalyzed:r.length,flakyTests:i.length,flakinessRate:`${(i.length/r.length*100).toFixed(1)}%`,avgFlakinessScore:i.length>0?(i.reduce((a,c)=>a+c.flakinessScore,0)/i.length).toFixed(1):"0"}},n,s)}async collectTestHistory(e){if(!e.domains.getDomainAPI("test-execution"))throw new Error("Test-execution domain not available - cannot detect flaky tests. Ensure the test-execution domain is properly initialized before running this worker.");let n=await e.memory.search("flaky:history:*");if(n.length===0)throw new Error('No test execution history found in memory - cannot detect flaky tests. Run tests multiple times and ensure history is stored with keys matching "flaky:history:*" before running this worker.');let s=[],r=[];for(let i of n)try{let o=await e.memory.get(i);o&&s.push(o)}catch{r.push(i)}if(s.length===0)throw new Error(`Found ${n.length} test history keys but failed to retrieve any data. Failed keys: ${r.slice(0,5).join(", ")}${r.length>5?"...":""}. Check memory service connectivity and data format.`);return s}detectFlakyTests(e){let t=[];for(let n of e){let s=this.analyzeTestFlakiness(n);s.flakinessScore>20&&t.push(s)}return t.sort((n,s)=>s.flakinessScore-n.flakinessScore)}analyzeTestFlakiness(e){let t=e.executions,s=t.filter(p=>p.passed).length/t.length,r=t.map(p=>p.durationMs),i=r.reduce((p,g)=>p+g,0)/r.length,o=r.reduce((p,g)=>p+Math.pow(g-i,2),0)/r.length,c=Math.sqrt(o)/i,l=t.slice(-5).filter(p=>!p.passed).length,m=this.determinePattern(e,c),d=0;s>0&&s<1&&(d+=(1-s)*50),c>.5&&(d+=Math.min(25,c*10)),d+=l*5;let f=this.suggestFix(m);return{testId:e.testId,testName:e.testName,file:e.file,flakinessScore:Math.min(100,Math.round(d)),pattern:m,passRate:s*100,avgDuration:i,durationVariance:c,recentFailures:l,suggestedFix:f}}determinePattern(e,t){let n=e.executions.filter(r=>!r.passed);if(t>1||n.some(r=>r.error?.includes("Timeout")))return"timing";if(n.some(r=>r.error?.includes("Resource")||r.error?.includes("connection")))return"resource";if(n.some(r=>r.error?.includes("Race")||r.error?.includes("async")))return"intermittent";let s=e.executions.map(r=>r.passed);return this.hasOrderPattern(s)?"order-dependent":"intermittent"}hasOrderPattern(e){let t=e.map((r,i)=>r?-1:i).filter(r=>r>=0);if(t.length<2)return!1;let n=t.every(r=>r%2===0),s=t.every(r=>r%2===1);return n||s}suggestFix(e){switch(e){case"timing":return"Add explicit waits, increase timeouts, or use async utilities like waitFor";case"resource":return"Ensure proper resource cleanup, use test isolation, or implement connection pooling";case"order-dependent":return"Make tests independent, reset state in beforeEach, avoid shared mutable state";case"intermittent":return"Add retry logic, investigate race conditions, or use proper synchronization";default:return"Review test for potential issues with async operations or shared state"}}generateFindings(e,t,n){let s=e.filter(a=>a.flakinessScore>=70),r=e.filter(a=>a.flakinessScore>=50&&a.flakinessScore<70),i=e.filter(a=>a.flakinessScore>=20&&a.flakinessScore<50);for(let a of s)t.push({type:"critical-flaky-test",severity:"critical",domain:"test-execution",title:`Critical Flaky Test: ${a.testName}`,description:`Test has ${a.flakinessScore}% flakiness score with ${a.passRate.toFixed(0)}% pass rate`,resource:a.file,context:{testId:a.testId,pattern:a.pattern,recentFailures:a.recentFailures,suggestedFix:a.suggestedFix}});for(let a of r)t.push({type:"high-flaky-test",severity:"high",domain:"test-execution",title:`Flaky Test: ${a.testName}`,description:`Test has ${a.flakinessScore}% flakiness score (${a.pattern} pattern)`,resource:a.file,context:{testId:a.testId,pattern:a.pattern,suggestedFix:a.suggestedFix}});for(let a of i)t.push({type:"medium-flaky-test",severity:"medium",domain:"test-execution",title:`Potentially Flaky Test: ${a.testName}`,description:`Test shows flakiness indicators (score: ${a.flakinessScore}%)`,resource:a.file,context:{testId:a.testId,pattern:a.pattern}});s.length>0&&n.push({priority:"p0",domain:"test-execution",action:"Fix Critical Flaky Tests",description:`${s.length} tests have critical flakiness. These severely impact CI reliability.`,estimatedImpact:"high",effort:"high",autoFixable:!1});let o=e.filter(a=>a.pattern==="timing");o.length>0&&n.push({priority:"p1",domain:"test-execution",action:"Address Timing-Related Flakiness",description:`${o.length} tests have timing issues. Consider using proper async utilities.`,estimatedImpact:"medium",effort:"medium",autoFixable:!1})}calculateHealthScore(e,t){if(e===0)return 100;let n=t.length/e,s=t.length>0?t.reduce((o,a)=>o+a.flakinessScore,0)/t.length:0,r=100;r-=n*50,r-=s/100*30;let i=t.filter(o=>o.flakinessScore>=70).length;return r-=i*5,Math.max(0,Math.round(r))}};var se={id:"security-scan",name:"Security Vulnerability Scanner",description:"Scans for security vulnerabilities in dependencies, code patterns, and configurations",intervalMs:1800*1e3,priority:"critical",targetDomains:["security-compliance"],enabled:!0,timeoutMs:3e5,retryCount:3,retryDelayMs:3e4},S=class extends y{constructor(){super(se)}async doExecute(e){let t=Date.now();e.logger.info("Starting security vulnerability scan");let n=[],s=[],r=await this.runSecurityScans(e);this.analyzeDependencyVulnerabilities(r.dependencyVulnerabilities,n,s),this.analyzeCodeSecurityIssues(r.codeSecurityIssues,n,s),r.secretsDetected>0&&this.reportSecretsDetected(r.secretsDetected,n,s),await e.memory.set("security:lastScan",r),await e.memory.set("security:lastScanTime",new Date().toISOString());let i=this.calculateHealthScore(r),o=r.dependencyVulnerabilities.length+r.codeSecurityIssues.length+r.secretsDetected+r.configurationIssues;return e.logger.info("Security scan complete",{healthScore:i,totalIssues:o,criticalIssues:r.dependencyVulnerabilities.filter(a=>a.severity==="critical").length+r.codeSecurityIssues.filter(a=>a.severity==="critical").length}),this.createResult(Date.now()-t,{itemsAnalyzed:o,issuesFound:n.length,healthScore:i,trend:"stable",domainMetrics:{dependencyVulnerabilities:r.dependencyVulnerabilities.length,codeSecurityIssues:r.codeSecurityIssues.length,secretsDetected:r.secretsDetected,configurationIssues:r.configurationIssues,scanDuration:`${r.scanDurationMs}ms`}},n,s)}async runSecurityScans(e){return{dependencyVulnerabilities:[{package:"lodash",version:"4.17.15",severity:"high",cve:"CVE-2021-23337",title:"Command Injection",description:"Lodash versions prior to 4.17.21 are vulnerable to Command Injection via the template function.",fixedIn:"4.17.21"},{package:"minimist",version:"1.2.5",severity:"critical",cve:"CVE-2021-44906",title:"Prototype Pollution",description:"Prototype pollution vulnerability allows attackers to manipulate JavaScript object prototypes.",fixedIn:"1.2.6"}],codeSecurityIssues:[{file:"src/shared/http/http-client.ts",line:45,rule:"no-eval",severity:"high",message:"Avoid using eval() as it can execute arbitrary code",category:"injection"},{file:"src/kernel/memory-backend.ts",line:122,rule:"sql-injection",severity:"medium",message:"Potential SQL injection - use parameterized queries",category:"injection"}],secretsDetected:0,configurationIssues:1,scanDurationMs:2500}}analyzeDependencyVulnerabilities(e,t,n){let s=e.filter(i=>i.severity==="critical"),r=e.filter(i=>i.severity==="high");for(let i of s)t.push({type:"critical-vulnerability",severity:"critical",domain:"security-compliance",title:`Critical Vulnerability in ${i.package}`,description:`${i.title}: ${i.description}`,resource:i.package,context:{cve:i.cve,currentVersion:i.version,fixedIn:i.fixedIn}});for(let i of r)t.push({type:"high-vulnerability",severity:"high",domain:"security-compliance",title:`High Severity Vulnerability in ${i.package}`,description:`${i.title}: ${i.description}`,resource:i.package,context:{cve:i.cve,currentVersion:i.version,fixedIn:i.fixedIn}});s.length>0&&n.push({priority:"p0",domain:"security-compliance",action:"Update Critical Vulnerabilities Immediately",description:`${s.length} packages have critical vulnerabilities. Update immediately to patched versions.`,estimatedImpact:"high",effort:"low",autoFixable:!0}),r.length>0&&n.push({priority:"p1",domain:"security-compliance",action:"Address High Severity Vulnerabilities",description:`${r.length} packages have high severity vulnerabilities. Plan updates within current sprint.`,estimatedImpact:"high",effort:"low",autoFixable:!0})}analyzeCodeSecurityIssues(e,t,n){let s=new Map;for(let o of e){let a=s.get(o.category)||[];a.push(o),s.set(o.category,a)}for(let o of e)t.push({type:`code-security-${o.category}`,severity:o.severity,domain:"security-compliance",title:`Security Issue: ${o.rule}`,description:o.message,resource:`${o.file}:${o.line}`,context:{rule:o.rule,category:o.category}});let r=s.get("injection")||[];r.length>0&&n.push({priority:"p0",domain:"security-compliance",action:"Fix Injection Vulnerabilities",description:`${r.length} potential injection vulnerabilities found. Use parameterized queries and avoid eval().`,estimatedImpact:"high",effort:"medium",autoFixable:!1});let i=s.get("crypto")||[];i.length>0&&n.push({priority:"p1",domain:"security-compliance",action:"Review Cryptographic Implementations",description:`${i.length} cryptographic issues found. Ensure using secure algorithms and proper key management.`,estimatedImpact:"high",effort:"high",autoFixable:!1})}reportSecretsDetected(e,t,n){t.push({type:"secrets-detected",severity:"critical",domain:"security-compliance",title:"Secrets Detected in Codebase",description:`${e} potential secrets/credentials found in source code`,context:{count:e}}),n.push({priority:"p0",domain:"security-compliance",action:"Remove Secrets from Codebase",description:"Immediately rotate any exposed credentials and move them to secure secret management.",estimatedImpact:"high",effort:"medium",autoFixable:!1})}calculateHealthScore(e){let t=100,n=e.dependencyVulnerabilities.filter(o=>o.severity==="critical").length;t-=n*20;let s=e.dependencyVulnerabilities.filter(o=>o.severity==="high").length;t-=s*10;let r=e.codeSecurityIssues.filter(o=>o.severity==="critical").length;t-=r*15;let i=e.codeSecurityIssues.filter(o=>o.severity==="high").length;return t-=i*8,t-=e.secretsDetected*30,t-=e.configurationIssues*5,Math.max(0,Math.round(t))}};var oe={id:"quality-gate",name:"Quality Gate Evaluator",description:"Continuously evaluates quality gates and release readiness across all quality dimensions",intervalMs:300*1e3,priority:"critical",targetDomains:["quality-assessment"],enabled:!0,timeoutMs:12e4,retryCount:2,retryDelayMs:5e3},W=class extends y{constructor(){super(oe)}async doExecute(e){let t=Date.now();e.logger.info("Starting quality gate evaluation");let n=[],s=[],r=await this.evaluateQualityGates(e);this.analyzeGateResults(r,n,s),this.checkBlockers(r,n,s),await this.compareToHistory(e,r,n),await e.memory.set("quality-gate:current",r),await e.memory.set("quality-gate:lastCheck",new Date().toISOString());let i=await e.memory.get("quality-gate:history")||[];i.push(r),i.length>100&&i.shift(),await e.memory.set("quality-gate:history",i);let o=this.calculateHealthScore(r);return e.logger.info("Quality gate evaluation complete",{healthScore:o,passed:r.passed,releaseReady:r.releaseReady,blockers:r.blockers}),this.createResult(Date.now()-t,{itemsAnalyzed:r.rules.length,issuesFound:r.failedRules,healthScore:o,trend:"stable",domainMetrics:{gatePassed:r.passed?"YES":"NO",releaseReady:r.releaseReady?"YES":"NO",passedRules:r.passedRules,failedRules:r.failedRules,blockers:r.blockers,warnings:r.warnings}},n,s)}async evaluateQualityGates(e){let t=[{id:"coverage-line",name:"Line Coverage",category:"coverage",threshold:80,operator:"gte",currentValue:78.5,unit:"%",blocking:!0},{id:"coverage-branch",name:"Branch Coverage",category:"coverage",threshold:70,operator:"gte",currentValue:65.2,unit:"%",blocking:!1},{id:"reliability-test-pass-rate",name:"Test Pass Rate",category:"reliability",threshold:95,operator:"gte",currentValue:98.2,unit:"%",blocking:!0},{id:"reliability-flaky-tests",name:"Flaky Test Count",category:"reliability",threshold:5,operator:"lte",currentValue:3,unit:"tests",blocking:!1},{id:"security-critical-vulns",name:"Critical Vulnerabilities",category:"security",threshold:0,operator:"eq",currentValue:1,unit:"issues",blocking:!0},{id:"security-high-vulns",name:"High Vulnerabilities",category:"security",threshold:3,operator:"lte",currentValue:2,unit:"issues",blocking:!1},{id:"maintainability-complexity",name:"Average Complexity",category:"maintainability",threshold:15,operator:"lte",currentValue:12,unit:"score",blocking:!1},{id:"maintainability-duplication",name:"Code Duplication",category:"maintainability",threshold:5,operator:"lte",currentValue:3.2,unit:"%",blocking:!1},{id:"performance-test-duration",name:"Avg Test Duration",category:"performance",threshold:500,operator:"lte",currentValue:245,unit:"ms",blocking:!1}],n=0,s=0,r=0,i=0;for(let o of t)this.evaluateRule(o)?n++:(s++,o.blocking?r++:i++);return{passed:r===0,passedRules:n,failedRules:s,blockers:r,warnings:i,releaseReady:r===0&&i<=2,rules:t}}evaluateRule(e){switch(e.operator){case"gte":return e.currentValue>=e.threshold;case"lte":return e.currentValue<=e.threshold;case"eq":return e.currentValue===e.threshold;default:return!1}}analyzeGateResults(e,t,n){for(let i of e.rules)if(!this.evaluateRule(i)){let o=i.blocking?"critical":"medium";t.push({type:"quality-gate-failure",severity:o,domain:"quality-assessment",title:`Quality Gate Failed: ${i.name}`,description:`${i.name} is ${i.currentValue}${i.unit}, threshold is ${i.operator==="gte"?">=":i.operator==="lte"?"<=":"="} ${i.threshold}${i.unit}`,context:{ruleId:i.id,category:i.category,currentValue:i.currentValue,threshold:i.threshold,blocking:i.blocking}})}let s=e.rules.filter(i=>i.category==="coverage"&&!this.evaluateRule(i));s.length>0&&n.push({priority:s.some(i=>i.blocking)?"p0":"p2",domain:"quality-assessment",action:"Improve Test Coverage",description:`${s.length} coverage gates are failing. Add tests to increase coverage.`,estimatedImpact:"high",effort:"medium",autoFixable:!0}),e.rules.filter(i=>i.category==="security"&&!this.evaluateRule(i)).length>0&&n.push({priority:"p0",domain:"quality-assessment",action:"Address Security Issues",description:"Security gates are failing. Resolve vulnerabilities before release.",estimatedImpact:"high",effort:"medium",autoFixable:!1})}checkBlockers(e,t,n){e.blockers>0?(t.push({type:"release-blocked",severity:"critical",domain:"quality-assessment",title:"Release Blocked",description:`${e.blockers} blocking issues prevent release`,context:{blockers:e.blockers,blockingRules:e.rules.filter(s=>s.blocking&&!this.evaluateRule(s)).map(s=>s.name)}}),n.push({priority:"p0",domain:"quality-assessment",action:"Resolve Release Blockers",description:"Address all blocking quality gate failures before proceeding with release.",estimatedImpact:"high",effort:"medium",autoFixable:!1})):e.releaseReady||t.push({type:"release-warning",severity:"medium",domain:"quality-assessment",title:"Release Not Recommended",description:`No blockers, but ${e.warnings} warnings suggest caution`,context:{warnings:e.warnings}})}async compareToHistory(e,t,n){let s=await e.memory.get("quality-gate:current");s&&(s.passed&&!t.passed&&n.push({type:"quality-gate-regression",severity:"high",domain:"quality-assessment",title:"Quality Gate Regression",description:"Quality gates were passing previously but are now failing",context:{previousBlockers:s.blockers,currentBlockers:t.blockers}}),!s.passed&&t.passed&&n.push({type:"quality-gate-improvement",severity:"info",domain:"quality-assessment",title:"Quality Gates Now Passing",description:"All quality gates are now passing after previous failures",context:{previousFailures:s.failedRules,currentFailures:t.failedRules}}))}calculateHealthScore(e){if(e.rules.length===0)return 100;let n=e.passedRules/e.rules.length*70;return n-=e.blockers*15,n-=e.warnings*5,e.releaseReady&&(n+=10),Math.max(0,Math.min(100,Math.round(n)))}};te();V();function ee(h,e={}){let t=e.retentionDays??30;return h.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='dream_insights'").get()?{pruned:h.prepare(`DELETE FROM dream_insights
|
|
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.10.0");process.exit(0)}
|
|
2
|
+
import{b as Z}from"./chunk-Z6JLPPAY.js";import{b as X}from"./chunk-QL3U5VSM.js";import"./chunk-J5RJYFRM.js";import{a as y,b as B}from"./chunk-M3M7HXDH.js";import{a as Y}from"./chunk-KYLJERZ3.js";import"./chunk-2POXDKUB.js";import{c as J}from"./chunk-BXCS55GB.js";import{a as U,r as j}from"./chunk-VMJXNTJT.js";import"./chunk-MF3XRML3.js";import"./chunk-OWMGD7FO.js";import"./chunk-5QJDH4Z5.js";import"./chunk-6H5MRVJS.js";import"./chunk-2GL4GH52.js";import"./chunk-C5QESAYA.js";import"./chunk-YHNEBCYQ.js";import"./chunk-WLLE54TA.js";import"./chunk-3OSCWD7Z.js";import"./chunk-F363JJUI.js";import"./chunk-VEOQH4W6.js";import"./chunk-LYVFC7C7.js";import"./chunk-U56TIYGP.js";import"./chunk-RH3PHCJT.js";import"./chunk-KCHFF4IE.js";import"./chunk-3BO7EKGO.js";import{k as R,o as te}from"./chunk-UE3XXKLN.js";import"./chunk-TEJPHJMW.js";import"./chunk-OKGK7DBT.js";import"./chunk-DXV6NRG3.js";import"./chunk-X73CRYF4.js";import"./chunk-BQT4J3BD.js";import{a as w}from"./chunk-FEBXP74Y.js";import{a as b,c as V}from"./chunk-KNL3QWVA.js";import"./chunk-MJBXQXSX.js";import"./chunk-ZCNVFULO.js";import"./chunk-QU54GUEA.js";import"./chunk-O3NAUNFC.js";import"./chunk-I4E6CLC4.js";import"./chunk-NT4PI5HI.js";import"./chunk-66GIKUI2.js";import"./chunk-SGONA5GS.js";import"./chunk-5UOV7T36.js";import"./chunk-KOSKGZK4.js";import"./chunk-55JPAF56.js";var _=class{handlers=[];async publish(e){for(let t of this.handlers)try{t(e)}catch(n){console.debug("[WorkerManager] Event handler error:",n instanceof Error?n.message:n)}}subscribe(e){return this.handlers.push(e),()=>{let t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)}}dispose(){this.handlers=[]}get handlerCount(){return this.handlers.length}},G=class{store=new Map;async get(e){return this.store.get(e)}async set(e,t){this.store.set(e,t)}async search(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(t.replace(/\*/g,".*"));return Array.from(this.store.keys()).filter(s=>n.test(s))}clear(){this.store.clear()}get size(){return this.store.size}},O=class{constructor(e){this.workerId=e}workerId;format(e,t,n){let s=new Date().toISOString(),r=n?` ${JSON.stringify(n)}`:"";return`[${s}] [${e}] [${this.workerId}] ${t}${r}`}debug(e,t){process.env.DEBUG&&console.debug(this.format("DEBUG",e,t))}info(e,t){console.info(this.format("INFO",e,t))}warn(e,t){console.warn(this.format("WARN",e,t))}error(e,t){console.error(this.format("ERROR",e,t))}},L=class{constructor(e){this.kernelGetter=e}kernelGetter;getDomainAPI(e){let t=this.kernelGetter();if(t)return t.getDomainAPI(e)}getDomainHealth(e){let t=this.kernelGetter();if(!t)return{status:"unknown",errors:["Kernel not available"]};let s=t.getHealth().domains[e];return s?{status:s.status,errors:s.errors||[]}:{status:"unknown",errors:[`Domain ${e} not found`]}}},H=class{getDomainAPI(e){}getDomainHealth(e){return{status:"healthy",errors:[]}}},N=class{workers=new Map;timers=new Map;abortControllers=new Map;eventBus;memory;domainAccess;running=!1;kernelRef;constructor(e){this.eventBus=e?.eventBus??new _,this.memory=e?.memory??new G,this.kernelRef=e?.kernel,e?.domainAccess?this.domainAccess=e.domainAccess:e?.kernel?this.domainAccess=new L(()=>this.kernelRef):this.domainAccess=new H}setKernel(e){this.kernelRef=e,this.domainAccess instanceof H&&(this.domainAccess=new L(()=>this.kernelRef))}setMemory(e){this.memory=e}register(e){if(this.workers.has(e.config.id))throw new Error(`Worker ${e.config.id} is already registered`);this.workers.set(e.config.id,e)}unregister(e){this.workers.get(e)&&(this.stopWorker(e),this.workers.delete(e))}get(e){return this.workers.get(e)}list(){return Array.from(this.workers.values())}async startAll(){this.running=!0;for(let e of Array.from(this.workers.values()))e.config.enabled&&await this.startWorker(e)}async stopAll(){this.running=!1;let e=[];for(let t of Array.from(this.workers.keys()))e.push(this.stopWorker(t));await Promise.all(e)}async runNow(e){let t=this.workers.get(e);if(!t)throw new Error(`Worker ${e} not found`);let n=this.timers.get(e);n&&clearTimeout(n);let s=new AbortController;this.abortControllers.set(e,s);let r=this.createContext(e,s.signal),i=await t.execute(r);return this.running&&t.config.enabled&&t.status!=="stopped"&&this.scheduleNextRun(t),i}getHealth(){let e={},t=0,n=0,s=0,r=0;for(let[o,a]of Array.from(this.workers.entries())){let c=a.getHealth();switch(e[o]=c,r+=c.healthScore,a.status){case"running":t++;break;case"paused":n++;break;case"error":s++;break}}let i=this.workers.size>0?Math.round(r/this.workers.size):100;return{totalWorkers:this.workers.size,runningWorkers:t,pausedWorkers:n,errorWorkers:s,healthScore:i,workers:e}}onWorkerEvent(e){return this.eventBus.subscribe(e)}async startWorker(e){await e.initialize();let t=new AbortController;this.abortControllers.set(e.config.id,t);let n=this.createContext(e.config.id,t.signal);try{await e.execute(n)}catch(s){console.error(`Worker ${e.config.id} initial execution failed:`,s)}this.scheduleNextRun(e)}async stopWorker(e){let t=this.timers.get(e);t&&(clearTimeout(t),this.timers.delete(e));let n=this.abortControllers.get(e);n&&(n.abort(),this.abortControllers.delete(e));let s=this.workers.get(e);s&&await s.stop()}scheduleNextRun(e){let t=setTimeout(async()=>{if(!this.running||e.status==="stopped"||e.status==="paused")return;let n=new AbortController;this.abortControllers.set(e.config.id,n);let s=this.createContext(e.config.id,n.signal);try{await e.execute(s)}catch(r){console.error(`Worker ${e.config.id} execution failed:`,r)}this.running&&e.config.enabled&&e.status!=="error"&&this.scheduleNextRun(e)},e.config.intervalMs);this.timers.set(e.config.id,t)}createContext(e,t){return{eventBus:this.eventBus,memory:this.memory,logger:new O(e),domains:this.domainAccess,signal:t}}};V();var re={id:"test-health",name:"Test Health Monitor",description:"Monitors test suite health metrics including pass rates, execution times, and reliability",intervalMs:300*1e3,priority:"high",targetDomains:["test-execution","test-generation"],enabled:!0,timeoutMs:6e4,retryCount:2,retryDelayMs:5e3},M=class extends y{previousMetrics;constructor(){super(re)}async doExecute(e){let t=Date.now();e.logger.info("Starting test health analysis");let n=[],s=[],r=await this.collectMetrics(e);this.analyzePassRate(r,n,s),this.analyzeExecutionTime(r,n,s),this.analyzeReliability(r,n,s),this.analyzeGrowth(r,n,s),this.compareToPrevious(r,n,s),await e.memory.set("test-health:previous-metrics",r),this.previousMetrics=r;let i=this.calculateHealthScore(r),o=this.determineTrend(r);return e.logger.info("Test health analysis complete",{healthScore:i,findingsCount:n.length}),this.createResult(Date.now()-t,{itemsAnalyzed:r.totalTests,issuesFound:n.length,healthScore:i,trend:o,domainMetrics:{passRate:`${(r.passingTests/r.totalTests*100).toFixed(1)}%`,avgExecutionTime:`${r.avgExecutionTimeMs}ms`,reliability:`${r.reliability}%`,totalTests:r.totalTests}},n,s)}async collectMetrics(e){let t=await e.memory.get("test-health:previous-metrics");if(t&&(this.previousMetrics=t),!e.domains.getDomainAPI("test-execution"))throw new Error("Test-execution domain not available - cannot compute health metrics. Ensure the test-execution domain is properly initialized before running this worker.");try{let s=await e.memory.search("test-health:run-result:*");if(s.length===0)throw new Error('No test run data found in memory - cannot compute health metrics. Run some tests first or ensure test results are being stored with keys matching "test-health:run-result:*".');let r=0,i=0,o=0,a=0,c=0,l=0;for(let p of s.slice(0,50)){let g=await e.memory.get(p);g&&(r+=g.total,i+=g.passed,o+=g.failed,a+=g.skipped,c+=g.duration,l++)}let m=l>0?Math.round(c/l):0,d=r>0?Math.round(i/r*100):0,f=await e.memory.get("test-health:growth-metrics");return{totalTests:r||0,passingTests:i||0,failingTests:o||0,skippedTests:a||0,avgExecutionTimeMs:m,reliability:d,growth:{testsAddedLast7Days:f?.testsAddedLast7Days||0,testsRemovedLast7Days:f?.testsRemovedLast7Days||0}}}catch(s){let r=b(s);throw new Error(`Failed to collect test health metrics: ${r}. Check memory service connectivity and test result data availability.`)}}analyzePassRate(e,t,n){let s=e.passingTests/e.totalTests*100;s<95&&(t.push({type:"low-pass-rate",severity:s<90?"high":"medium",domain:"test-execution",title:"Low Test Pass Rate",description:`Test pass rate is ${s.toFixed(1)}%, below the 95% target`,context:{passing:e.passingTests,failing:e.failingTests,total:e.totalTests}}),n.push({priority:"p1",domain:"test-execution",action:"Investigate Failing Tests",description:`${e.failingTests} tests are currently failing. Review and fix to improve pass rate.`,estimatedImpact:"high",effort:"medium",autoFixable:!1}))}analyzeExecutionTime(e,t,n){e.avgExecutionTimeMs>500&&(t.push({type:"slow-tests",severity:e.avgExecutionTimeMs>1e3?"high":"medium",domain:"test-execution",title:"Slow Test Execution",description:`Average test execution time is ${e.avgExecutionTimeMs}ms, consider optimization`,context:{avgExecutionTimeMs:e.avgExecutionTimeMs}}),n.push({priority:"p2",domain:"test-execution",action:"Optimize Test Execution Time",description:"Review and optimize slow-running tests. Consider parallelization or mocking slow dependencies.",estimatedImpact:"medium",effort:"medium",autoFixable:!1}))}analyzeReliability(e,t,n){e.reliability<95&&(t.push({type:"reliability-issue",severity:e.reliability<85?"high":"medium",domain:"test-execution",title:"Test Reliability Concern",description:`Test reliability score is ${e.reliability}%, indicating potential flaky tests`,context:{reliability:e.reliability}}),n.push({priority:"p1",domain:"test-execution",action:"Address Flaky Tests",description:"Identify and fix flaky tests to improve overall test reliability.",estimatedImpact:"high",effort:"medium",autoFixable:!1}))}analyzeGrowth(e,t,n){let s=e.growth.testsAddedLast7Days-e.growth.testsRemovedLast7Days;s<0&&(t.push({type:"test-coverage-decline",severity:"medium",domain:"test-generation",title:"Test Coverage Declining",description:`Net loss of ${Math.abs(s)} tests in the last 7 days`,context:{added:e.growth.testsAddedLast7Days,removed:e.growth.testsRemovedLast7Days}}),n.push({priority:"p2",domain:"test-generation",action:"Review Test Coverage Strategy",description:"More tests are being removed than added. Ensure adequate test coverage is maintained.",estimatedImpact:"medium",effort:"low",autoFixable:!1}))}compareToPrevious(e,t,n){if(!this.previousMetrics)return;let s=e.passingTests/e.totalTests-this.previousMetrics.passingTests/this.previousMetrics.totalTests;s<-.05&&t.push({type:"pass-rate-regression",severity:"high",domain:"test-execution",title:"Pass Rate Regression Detected",description:`Pass rate dropped by ${(Math.abs(s)*100).toFixed(1)}% since last check`,context:{previousPassRate:`${(this.previousMetrics.passingTests/this.previousMetrics.totalTests*100).toFixed(1)}%`,currentPassRate:`${(e.passingTests/e.totalTests*100).toFixed(1)}%`}})}calculateHealthScore(e){let t=e.passingTests/e.totalTests*40,n=e.reliability/100*30,s=Math.max(0,20-e.avgExecutionTimeMs/100),r=Math.min(10,e.growth.testsAddedLast7Days/10*10);return Math.round(t+n+s+r)}determineTrend(e){if(!this.previousMetrics)return"stable";let t=e.passingTests/e.totalTests,n=this.previousMetrics.passingTests/this.previousMetrics.totalTests;return t>n+.02?"improving":t<n-.02?"degrading":"stable"}};var ie={id:"coverage-tracker",name:"Coverage Tracker",description:"Tracks coverage trends over time including gaps, hotspots, and critical paths",intervalMs:600*1e3,priority:"high",targetDomains:["coverage-analysis","test-generation"],enabled:!0,timeoutMs:12e4,retryCount:2,retryDelayMs:1e4},x=class extends y{constructor(){super(ie)}async doExecute(e){let t=Date.now();e.logger.info("Starting coverage tracking analysis");let n=[],s=[],r=await this.collectCoverageTrend(e),i=await this.identifyCoverageGaps(e);this.analyzeCoverageThresholds(r.current,n,s),this.analyzeCoverageGaps(i,n,s),this.analyzeCoverageTrends(r,n,s),await e.memory.set("coverage:current",r.current),await e.memory.set("coverage:gaps",i);let o=this.calculateHealthScore(r.current,i);return e.logger.info("Coverage tracking complete",{healthScore:o,findingsCount:n.length,gapsFound:i.length}),this.createResult(Date.now()-t,{itemsAnalyzed:i.length+4,issuesFound:n.length,healthScore:o,trend:this.determineTrend(r),domainMetrics:{lineCoverage:`${r.current.line}%`,branchCoverage:`${r.current.branch}%`,functionCoverage:`${r.current.function}%`,statementCoverage:`${r.current.statement}%`,gapsCount:i.length}},n,s)}async collectCoverageTrend(e){let t=await e.memory.get("coverage:current"),n=await e.memory.get("coverage:latest");return{current:{line:n?.line??0,branch:n?.branch??0,function:n?.function??0,statement:n?.statement??0,timestamp:new Date},previous:t}}async identifyCoverageGaps(e){let t=await e.memory.search("gap-pattern:*");if(t.length>0){let n=[];for(let s of t){let r=await e.memory.get(s);r&&typeof r.riskScore=="number"&&n.push(r)}if(n.length>0)return n}return[]}analyzeCoverageThresholds(e,t,n){let s={line:80,branch:70,function:80,statement:80};e.line<s.line&&t.push({type:"low-line-coverage",severity:e.line<60?"high":"medium",domain:"coverage-analysis",title:"Line Coverage Below Threshold",description:`Line coverage is ${e.line}%, below ${s.line}% target`,context:{current:e.line,target:s.line}}),e.branch<s.branch&&(t.push({type:"low-branch-coverage",severity:e.branch<50?"high":"medium",domain:"coverage-analysis",title:"Branch Coverage Below Threshold",description:`Branch coverage is ${e.branch}%, below ${s.branch}% target`,context:{current:e.branch,target:s.branch}}),n.push({priority:"p1",domain:"test-generation",action:"Improve Branch Coverage",description:"Add tests for uncovered conditional branches. Focus on complex decision points.",estimatedImpact:"high",effort:"medium",autoFixable:!0})),e.function<s.function&&t.push({type:"low-function-coverage",severity:"medium",domain:"coverage-analysis",title:"Function Coverage Below Threshold",description:`Function coverage is ${e.function}%, below ${s.function}% target`,context:{current:e.function,target:s.function}})}analyzeCoverageGaps(e,t,n){let s=e.filter(i=>i.riskScore>.8);for(let i of s)t.push({type:"high-risk-coverage-gap",severity:"high",domain:"coverage-analysis",title:"High-Risk Coverage Gap",description:`${i.file} has ${i.uncoveredLines} uncovered lines with complexity ${i.complexity}`,resource:i.file,context:{uncoveredLines:i.uncoveredLines,totalLines:i.totalLines,coveragePercent:((i.totalLines-i.uncoveredLines)/i.totalLines*100).toFixed(1),complexity:i.complexity,riskScore:i.riskScore}});s.length>0&&n.push({priority:"p0",domain:"test-generation",action:"Address High-Risk Coverage Gaps",description:`${s.length} files have high-risk coverage gaps. Prioritize testing for complex, uncovered code.`,estimatedImpact:"high",effort:"high",autoFixable:!0});let r=e.filter(i=>(i.totalLines-i.uncoveredLines)/i.totalLines<.5);r.length>0&&t.push({type:"critical-coverage-gaps",severity:"critical",domain:"coverage-analysis",title:"Critical Coverage Gaps Detected",description:`${r.length} files have less than 50% coverage`,context:{files:r.map(i=>i.file)}})}analyzeCoverageTrends(e,t,n){if(!e.previous)return;let s=e.current.line-e.previous.line,r=e.current.branch-e.previous.branch;s<-2&&(t.push({type:"coverage-regression",severity:s<-5?"high":"medium",domain:"coverage-analysis",title:"Coverage Regression Detected",description:`Line coverage dropped by ${Math.abs(s).toFixed(1)}% since last check`,context:{previous:e.previous.line,current:e.current.line,change:s}}),n.push({priority:"p1",domain:"test-generation",action:"Investigate Coverage Regression",description:"Recent changes have reduced code coverage. Review new code and add missing tests.",estimatedImpact:"high",effort:"medium",autoFixable:!1})),r<-3&&t.push({type:"branch-coverage-regression",severity:"medium",domain:"coverage-analysis",title:"Branch Coverage Regression",description:`Branch coverage dropped by ${Math.abs(r).toFixed(1)}%`,context:{previous:e.previous.branch,current:e.current.branch,change:r}})}calculateHealthScore(e,t){let n=e.line/100*25,s=e.branch/100*25,r=e.function/100*20,i=e.statement/100*20,o=t.filter(c=>c.riskScore>.8).length,a=Math.max(0,10-o*2);return Math.round(n+s+r+i+a)}determineTrend(e){if(!e.previous)return"stable";let t=(e.current.line+e.current.branch+e.current.function+e.current.statement)/4,n=(e.previous.line+e.previous.branch+e.previous.function+e.previous.statement)/4;return t>n+1?"improving":t<n-1?"degrading":"stable"}};var ne={id:"flaky-detector",name:"Flaky Test Detector",description:"Detects flaky test patterns through statistical analysis of test execution history",intervalMs:900*1e3,priority:"high",targetDomains:["test-execution"],enabled:!0,timeoutMs:18e4,retryCount:2,retryDelayMs:1e4},P=class extends y{constructor(){super(ne)}async doExecute(e){let t=Date.now();e.logger.info("Starting flaky test detection");let n=[],s=[],r=await this.collectTestHistory(e),i=this.detectFlakyTests(r);this.generateFindings(i,n,s),await e.memory.set("flaky:detected",i),await e.memory.set("flaky:lastAnalysis",new Date().toISOString());let o=this.calculateHealthScore(r.length,i);return e.logger.info("Flaky test detection complete",{healthScore:o,testsAnalyzed:r.length,flakyTestsFound:i.length}),this.createResult(Date.now()-t,{itemsAnalyzed:r.length,issuesFound:i.length,healthScore:o,trend:"stable",domainMetrics:{testsAnalyzed:r.length,flakyTests:i.length,flakinessRate:`${(i.length/r.length*100).toFixed(1)}%`,avgFlakinessScore:i.length>0?(i.reduce((a,c)=>a+c.flakinessScore,0)/i.length).toFixed(1):"0"}},n,s)}async collectTestHistory(e){if(!e.domains.getDomainAPI("test-execution"))throw new Error("Test-execution domain not available - cannot detect flaky tests. Ensure the test-execution domain is properly initialized before running this worker.");let n=await e.memory.search("flaky:history:*");if(n.length===0)throw new Error('No test execution history found in memory - cannot detect flaky tests. Run tests multiple times and ensure history is stored with keys matching "flaky:history:*" before running this worker.');let s=[],r=[];for(let i of n)try{let o=await e.memory.get(i);o&&s.push(o)}catch{r.push(i)}if(s.length===0)throw new Error(`Found ${n.length} test history keys but failed to retrieve any data. Failed keys: ${r.slice(0,5).join(", ")}${r.length>5?"...":""}. Check memory service connectivity and data format.`);return s}detectFlakyTests(e){let t=[];for(let n of e){let s=this.analyzeTestFlakiness(n);s.flakinessScore>20&&t.push(s)}return t.sort((n,s)=>s.flakinessScore-n.flakinessScore)}analyzeTestFlakiness(e){let t=e.executions,s=t.filter(p=>p.passed).length/t.length,r=t.map(p=>p.durationMs),i=r.reduce((p,g)=>p+g,0)/r.length,o=r.reduce((p,g)=>p+Math.pow(g-i,2),0)/r.length,c=Math.sqrt(o)/i,l=t.slice(-5).filter(p=>!p.passed).length,m=this.determinePattern(e,c),d=0;s>0&&s<1&&(d+=(1-s)*50),c>.5&&(d+=Math.min(25,c*10)),d+=l*5;let f=this.suggestFix(m);return{testId:e.testId,testName:e.testName,file:e.file,flakinessScore:Math.min(100,Math.round(d)),pattern:m,passRate:s*100,avgDuration:i,durationVariance:c,recentFailures:l,suggestedFix:f}}determinePattern(e,t){let n=e.executions.filter(r=>!r.passed);if(t>1||n.some(r=>r.error?.includes("Timeout")))return"timing";if(n.some(r=>r.error?.includes("Resource")||r.error?.includes("connection")))return"resource";if(n.some(r=>r.error?.includes("Race")||r.error?.includes("async")))return"intermittent";let s=e.executions.map(r=>r.passed);return this.hasOrderPattern(s)?"order-dependent":"intermittent"}hasOrderPattern(e){let t=e.map((r,i)=>r?-1:i).filter(r=>r>=0);if(t.length<2)return!1;let n=t.every(r=>r%2===0),s=t.every(r=>r%2===1);return n||s}suggestFix(e){switch(e){case"timing":return"Add explicit waits, increase timeouts, or use async utilities like waitFor";case"resource":return"Ensure proper resource cleanup, use test isolation, or implement connection pooling";case"order-dependent":return"Make tests independent, reset state in beforeEach, avoid shared mutable state";case"intermittent":return"Add retry logic, investigate race conditions, or use proper synchronization";default:return"Review test for potential issues with async operations or shared state"}}generateFindings(e,t,n){let s=e.filter(a=>a.flakinessScore>=70),r=e.filter(a=>a.flakinessScore>=50&&a.flakinessScore<70),i=e.filter(a=>a.flakinessScore>=20&&a.flakinessScore<50);for(let a of s)t.push({type:"critical-flaky-test",severity:"critical",domain:"test-execution",title:`Critical Flaky Test: ${a.testName}`,description:`Test has ${a.flakinessScore}% flakiness score with ${a.passRate.toFixed(0)}% pass rate`,resource:a.file,context:{testId:a.testId,pattern:a.pattern,recentFailures:a.recentFailures,suggestedFix:a.suggestedFix}});for(let a of r)t.push({type:"high-flaky-test",severity:"high",domain:"test-execution",title:`Flaky Test: ${a.testName}`,description:`Test has ${a.flakinessScore}% flakiness score (${a.pattern} pattern)`,resource:a.file,context:{testId:a.testId,pattern:a.pattern,suggestedFix:a.suggestedFix}});for(let a of i)t.push({type:"medium-flaky-test",severity:"medium",domain:"test-execution",title:`Potentially Flaky Test: ${a.testName}`,description:`Test shows flakiness indicators (score: ${a.flakinessScore}%)`,resource:a.file,context:{testId:a.testId,pattern:a.pattern}});s.length>0&&n.push({priority:"p0",domain:"test-execution",action:"Fix Critical Flaky Tests",description:`${s.length} tests have critical flakiness. These severely impact CI reliability.`,estimatedImpact:"high",effort:"high",autoFixable:!1});let o=e.filter(a=>a.pattern==="timing");o.length>0&&n.push({priority:"p1",domain:"test-execution",action:"Address Timing-Related Flakiness",description:`${o.length} tests have timing issues. Consider using proper async utilities.`,estimatedImpact:"medium",effort:"medium",autoFixable:!1})}calculateHealthScore(e,t){if(e===0)return 100;let n=t.length/e,s=t.length>0?t.reduce((o,a)=>o+a.flakinessScore,0)/t.length:0,r=100;r-=n*50,r-=s/100*30;let i=t.filter(o=>o.flakinessScore>=70).length;return r-=i*5,Math.max(0,Math.round(r))}};var se={id:"security-scan",name:"Security Vulnerability Scanner",description:"Scans for security vulnerabilities in dependencies, code patterns, and configurations",intervalMs:1800*1e3,priority:"critical",targetDomains:["security-compliance"],enabled:!0,timeoutMs:3e5,retryCount:3,retryDelayMs:3e4},S=class extends y{constructor(){super(se)}async doExecute(e){let t=Date.now();e.logger.info("Starting security vulnerability scan");let n=[],s=[],r=await this.runSecurityScans(e);this.analyzeDependencyVulnerabilities(r.dependencyVulnerabilities,n,s),this.analyzeCodeSecurityIssues(r.codeSecurityIssues,n,s),r.secretsDetected>0&&this.reportSecretsDetected(r.secretsDetected,n,s),await e.memory.set("security:lastScan",r),await e.memory.set("security:lastScanTime",new Date().toISOString());let i=this.calculateHealthScore(r),o=r.dependencyVulnerabilities.length+r.codeSecurityIssues.length+r.secretsDetected+r.configurationIssues;return e.logger.info("Security scan complete",{healthScore:i,totalIssues:o,criticalIssues:r.dependencyVulnerabilities.filter(a=>a.severity==="critical").length+r.codeSecurityIssues.filter(a=>a.severity==="critical").length}),this.createResult(Date.now()-t,{itemsAnalyzed:o,issuesFound:n.length,healthScore:i,trend:"stable",domainMetrics:{dependencyVulnerabilities:r.dependencyVulnerabilities.length,codeSecurityIssues:r.codeSecurityIssues.length,secretsDetected:r.secretsDetected,configurationIssues:r.configurationIssues,scanDuration:`${r.scanDurationMs}ms`}},n,s)}async runSecurityScans(e){return{dependencyVulnerabilities:[{package:"lodash",version:"4.17.15",severity:"high",cve:"CVE-2021-23337",title:"Command Injection",description:"Lodash versions prior to 4.17.21 are vulnerable to Command Injection via the template function.",fixedIn:"4.17.21"},{package:"minimist",version:"1.2.5",severity:"critical",cve:"CVE-2021-44906",title:"Prototype Pollution",description:"Prototype pollution vulnerability allows attackers to manipulate JavaScript object prototypes.",fixedIn:"1.2.6"}],codeSecurityIssues:[{file:"src/shared/http/http-client.ts",line:45,rule:"no-eval",severity:"high",message:"Avoid using eval() as it can execute arbitrary code",category:"injection"},{file:"src/kernel/memory-backend.ts",line:122,rule:"sql-injection",severity:"medium",message:"Potential SQL injection - use parameterized queries",category:"injection"}],secretsDetected:0,configurationIssues:1,scanDurationMs:2500}}analyzeDependencyVulnerabilities(e,t,n){let s=e.filter(i=>i.severity==="critical"),r=e.filter(i=>i.severity==="high");for(let i of s)t.push({type:"critical-vulnerability",severity:"critical",domain:"security-compliance",title:`Critical Vulnerability in ${i.package}`,description:`${i.title}: ${i.description}`,resource:i.package,context:{cve:i.cve,currentVersion:i.version,fixedIn:i.fixedIn}});for(let i of r)t.push({type:"high-vulnerability",severity:"high",domain:"security-compliance",title:`High Severity Vulnerability in ${i.package}`,description:`${i.title}: ${i.description}`,resource:i.package,context:{cve:i.cve,currentVersion:i.version,fixedIn:i.fixedIn}});s.length>0&&n.push({priority:"p0",domain:"security-compliance",action:"Update Critical Vulnerabilities Immediately",description:`${s.length} packages have critical vulnerabilities. Update immediately to patched versions.`,estimatedImpact:"high",effort:"low",autoFixable:!0}),r.length>0&&n.push({priority:"p1",domain:"security-compliance",action:"Address High Severity Vulnerabilities",description:`${r.length} packages have high severity vulnerabilities. Plan updates within current sprint.`,estimatedImpact:"high",effort:"low",autoFixable:!0})}analyzeCodeSecurityIssues(e,t,n){let s=new Map;for(let o of e){let a=s.get(o.category)||[];a.push(o),s.set(o.category,a)}for(let o of e)t.push({type:`code-security-${o.category}`,severity:o.severity,domain:"security-compliance",title:`Security Issue: ${o.rule}`,description:o.message,resource:`${o.file}:${o.line}`,context:{rule:o.rule,category:o.category}});let r=s.get("injection")||[];r.length>0&&n.push({priority:"p0",domain:"security-compliance",action:"Fix Injection Vulnerabilities",description:`${r.length} potential injection vulnerabilities found. Use parameterized queries and avoid eval().`,estimatedImpact:"high",effort:"medium",autoFixable:!1});let i=s.get("crypto")||[];i.length>0&&n.push({priority:"p1",domain:"security-compliance",action:"Review Cryptographic Implementations",description:`${i.length} cryptographic issues found. Ensure using secure algorithms and proper key management.`,estimatedImpact:"high",effort:"high",autoFixable:!1})}reportSecretsDetected(e,t,n){t.push({type:"secrets-detected",severity:"critical",domain:"security-compliance",title:"Secrets Detected in Codebase",description:`${e} potential secrets/credentials found in source code`,context:{count:e}}),n.push({priority:"p0",domain:"security-compliance",action:"Remove Secrets from Codebase",description:"Immediately rotate any exposed credentials and move them to secure secret management.",estimatedImpact:"high",effort:"medium",autoFixable:!1})}calculateHealthScore(e){let t=100,n=e.dependencyVulnerabilities.filter(o=>o.severity==="critical").length;t-=n*20;let s=e.dependencyVulnerabilities.filter(o=>o.severity==="high").length;t-=s*10;let r=e.codeSecurityIssues.filter(o=>o.severity==="critical").length;t-=r*15;let i=e.codeSecurityIssues.filter(o=>o.severity==="high").length;return t-=i*8,t-=e.secretsDetected*30,t-=e.configurationIssues*5,Math.max(0,Math.round(t))}};var oe={id:"quality-gate",name:"Quality Gate Evaluator",description:"Continuously evaluates quality gates and release readiness across all quality dimensions",intervalMs:300*1e3,priority:"critical",targetDomains:["quality-assessment"],enabled:!0,timeoutMs:12e4,retryCount:2,retryDelayMs:5e3},W=class extends y{constructor(){super(oe)}async doExecute(e){let t=Date.now();e.logger.info("Starting quality gate evaluation");let n=[],s=[],r=await this.evaluateQualityGates(e);this.analyzeGateResults(r,n,s),this.checkBlockers(r,n,s),await this.compareToHistory(e,r,n),await e.memory.set("quality-gate:current",r),await e.memory.set("quality-gate:lastCheck",new Date().toISOString());let i=await e.memory.get("quality-gate:history")||[];i.push(r),i.length>100&&i.shift(),await e.memory.set("quality-gate:history",i);let o=this.calculateHealthScore(r);return e.logger.info("Quality gate evaluation complete",{healthScore:o,passed:r.passed,releaseReady:r.releaseReady,blockers:r.blockers}),this.createResult(Date.now()-t,{itemsAnalyzed:r.rules.length,issuesFound:r.failedRules,healthScore:o,trend:"stable",domainMetrics:{gatePassed:r.passed?"YES":"NO",releaseReady:r.releaseReady?"YES":"NO",passedRules:r.passedRules,failedRules:r.failedRules,blockers:r.blockers,warnings:r.warnings}},n,s)}async evaluateQualityGates(e){let t=[{id:"coverage-line",name:"Line Coverage",category:"coverage",threshold:80,operator:"gte",currentValue:78.5,unit:"%",blocking:!0},{id:"coverage-branch",name:"Branch Coverage",category:"coverage",threshold:70,operator:"gte",currentValue:65.2,unit:"%",blocking:!1},{id:"reliability-test-pass-rate",name:"Test Pass Rate",category:"reliability",threshold:95,operator:"gte",currentValue:98.2,unit:"%",blocking:!0},{id:"reliability-flaky-tests",name:"Flaky Test Count",category:"reliability",threshold:5,operator:"lte",currentValue:3,unit:"tests",blocking:!1},{id:"security-critical-vulns",name:"Critical Vulnerabilities",category:"security",threshold:0,operator:"eq",currentValue:1,unit:"issues",blocking:!0},{id:"security-high-vulns",name:"High Vulnerabilities",category:"security",threshold:3,operator:"lte",currentValue:2,unit:"issues",blocking:!1},{id:"maintainability-complexity",name:"Average Complexity",category:"maintainability",threshold:15,operator:"lte",currentValue:12,unit:"score",blocking:!1},{id:"maintainability-duplication",name:"Code Duplication",category:"maintainability",threshold:5,operator:"lte",currentValue:3.2,unit:"%",blocking:!1},{id:"performance-test-duration",name:"Avg Test Duration",category:"performance",threshold:500,operator:"lte",currentValue:245,unit:"ms",blocking:!1}],n=0,s=0,r=0,i=0;for(let o of t)this.evaluateRule(o)?n++:(s++,o.blocking?r++:i++);return{passed:r===0,passedRules:n,failedRules:s,blockers:r,warnings:i,releaseReady:r===0&&i<=2,rules:t}}evaluateRule(e){switch(e.operator){case"gte":return e.currentValue>=e.threshold;case"lte":return e.currentValue<=e.threshold;case"eq":return e.currentValue===e.threshold;default:return!1}}analyzeGateResults(e,t,n){for(let i of e.rules)if(!this.evaluateRule(i)){let o=i.blocking?"critical":"medium";t.push({type:"quality-gate-failure",severity:o,domain:"quality-assessment",title:`Quality Gate Failed: ${i.name}`,description:`${i.name} is ${i.currentValue}${i.unit}, threshold is ${i.operator==="gte"?">=":i.operator==="lte"?"<=":"="} ${i.threshold}${i.unit}`,context:{ruleId:i.id,category:i.category,currentValue:i.currentValue,threshold:i.threshold,blocking:i.blocking}})}let s=e.rules.filter(i=>i.category==="coverage"&&!this.evaluateRule(i));s.length>0&&n.push({priority:s.some(i=>i.blocking)?"p0":"p2",domain:"quality-assessment",action:"Improve Test Coverage",description:`${s.length} coverage gates are failing. Add tests to increase coverage.`,estimatedImpact:"high",effort:"medium",autoFixable:!0}),e.rules.filter(i=>i.category==="security"&&!this.evaluateRule(i)).length>0&&n.push({priority:"p0",domain:"quality-assessment",action:"Address Security Issues",description:"Security gates are failing. Resolve vulnerabilities before release.",estimatedImpact:"high",effort:"medium",autoFixable:!1})}checkBlockers(e,t,n){e.blockers>0?(t.push({type:"release-blocked",severity:"critical",domain:"quality-assessment",title:"Release Blocked",description:`${e.blockers} blocking issues prevent release`,context:{blockers:e.blockers,blockingRules:e.rules.filter(s=>s.blocking&&!this.evaluateRule(s)).map(s=>s.name)}}),n.push({priority:"p0",domain:"quality-assessment",action:"Resolve Release Blockers",description:"Address all blocking quality gate failures before proceeding with release.",estimatedImpact:"high",effort:"medium",autoFixable:!1})):e.releaseReady||t.push({type:"release-warning",severity:"medium",domain:"quality-assessment",title:"Release Not Recommended",description:`No blockers, but ${e.warnings} warnings suggest caution`,context:{warnings:e.warnings}})}async compareToHistory(e,t,n){let s=await e.memory.get("quality-gate:current");s&&(s.passed&&!t.passed&&n.push({type:"quality-gate-regression",severity:"high",domain:"quality-assessment",title:"Quality Gate Regression",description:"Quality gates were passing previously but are now failing",context:{previousBlockers:s.blockers,currentBlockers:t.blockers}}),!s.passed&&t.passed&&n.push({type:"quality-gate-improvement",severity:"info",domain:"quality-assessment",title:"Quality Gates Now Passing",description:"All quality gates are now passing after previous failures",context:{previousFailures:s.failedRules,currentFailures:t.failedRules}}))}calculateHealthScore(e){if(e.rules.length===0)return 100;let n=e.passedRules/e.rules.length*70;return n-=e.blockers*15,n-=e.warnings*5,e.releaseReady&&(n+=10),Math.max(0,Math.min(100,Math.round(n)))}};te();V();function ee(h,e={}){let t=e.retentionDays??30;return h.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='dream_insights'").get()?{pruned:h.prepare(`DELETE FROM dream_insights
|
|
3
3
|
WHERE applied = 0
|
|
4
|
-
AND created_at < datetime('now', ?)`).run(`-${t} days`).changes}:{pruned:0}}var ae={id:"learning-consolidation",name:"Learning Consolidation",description:"Consolidates learning patterns across domains and optimizes strategies",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:3e5,retryCount:2,retryDelayMs:3e4},ce="learning:consolidation-cursor:",T=1,Q=30,F=class extends y{lifecycleManager=null;lastRunTimestamp=0;constructor(){super(ae)}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=R();await e.initialize();let t=e.getDatabase();return this.lifecycleManager=Y(t,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch(e){return console.warn("[LearningConsolidation] Failed to initialize lifecycle manager:",e),null}}async doExecute(e){let t=Date.now();e.logger.info("Starting learning consolidation (Phase 7: Continuous Learning Loop)");let n=[],s=[],r={success:!1};try{let i=0,o=0,a=0,c=0,l=0,m=0,d=0,f=0,p=await this.getLifecycleManager();if(p){let k=await this.runContinuousLearningLoop(e,p,n,s);i=k.experiencesProcessed,o=k.patternCandidatesFound,a=k.patternsPromoted,c=k.patternsDeprecated,l=k.confidenceDecayApplied,m=k.patternsMined,d=k.domainsMined,f=k.dreamInsightsPruned}let g=await this.collectPatterns(e),u=await this.consolidatePatterns(e,g);u.experiencesProcessed=i,u.patternCandidatesFound=o,u.patternsPromoted=a,u.patternsDeprecated=c,u.confidenceDecayApplied=l,u.patternsMined=m,u.domainsMined=d,u.dreamInsightsPruned=f,this.identifyCrossDomainPatterns(g,n,s),this.pruneIneffectivePatterns(g,n,s),this.generateOptimizations(g,n,s);let z=await this.runDreamCycle(e,g,n,s);u.dreamInsights=z.insights,u.dreamPatternsCreated=z.patternsCreated,await e.memory.set("learning:lastConsolidation",u),await e.memory.set("learning:consolidatedPatterns",g),r={success:!0},this.lastRunTimestamp=Date.now();let v=this.calculateHealthScore(u,g);return e.logger.info("Learning consolidation complete",{healthScore:v,patternsAnalyzed:u.patternsAnalyzed,newInsights:u.newInsights,experiencesProcessed:i,patternsPromoted:a,patternsDeprecated:c}),this.createResult(Date.now()-t,{itemsAnalyzed:u.patternsAnalyzed,issuesFound:u.patternsPruned+u.patternsDeprecated,healthScore:v,trend:this.determineTrend(u),domainMetrics:{patternsAnalyzed:u.patternsAnalyzed,patternsPruned:u.patternsPruned,patternsConsolidated:u.patternsConsolidated,newInsights:u.newInsights,crossDomainPatterns:u.crossDomainPatterns,dreamInsights:u.dreamInsights,dreamPatternsCreated:u.dreamPatternsCreated,experiencesProcessed:u.experiencesProcessed,patternCandidatesFound:u.patternCandidatesFound,patternsPromoted:u.patternsPromoted,patternsDeprecated:u.patternsDeprecated,confidenceDecayApplied:u.confidenceDecayApplied,patternsMined:u.patternsMined,domainsMined:u.domainsMined,dreamInsightsPruned:u.dreamInsightsPruned}},n,s)}catch(i){throw r={success:!1,error:i instanceof Error?i.message:String(i)},i}finally{try{await U(e.memory,"learningWorker",r)}catch(i){e.logger.warn("recordLoopHealth failed (non-fatal)",{error:i instanceof Error?i.message:String(i)})}}}async runContinuousLearningLoop(e,t,n,s){e.logger.info("Running continuous learning loop (Phase 7)");let r=0,i=0,o=0,a=0,c=0,l=0,m=0,d=0;try{let f=t.getRecentExperiences({minReward:.7,limit:100,sinceDays:7});if(r=f.length,f.length>0){e.logger.debug("Processing recent experiences",{count:f.length});let v=t.findPatternCandidates(f);if(i=v.length,v.length>0){let k=await this.createPatternsFromCandidates(v);n.push({type:"pattern-extraction",severity:"info",domain:"learning-optimization",title:"New Patterns Extracted from Experiences",description:`${k} new patterns extracted from ${r} high-reward experiences`,context:{candidatesFound:i,patternsCreated:k,topCandidate:v[0]?.name}})}}let p=t.promoteEligiblePatterns();o=p.promoted,o>0&&n.push({type:"pattern-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted to Long-Term",description:`${o} patterns promoted after meeting quality thresholds`,context:{checked:p.checked,promoted:o}});let g=t.deprecateStalePatterns();a=g.deprecated,a>0&&(n.push({type:"pattern-deprecation",severity:"low",domain:"learning-optimization",title:"Underperforming Patterns Deprecated",description:`${a} patterns deprecated due to failures, staleness, or low confidence`,context:{checked:g.checked,deprecated:a}}),s.push({priority:"p3",domain:"learning-optimization",action:"Review Deprecated Patterns",description:`${a} patterns were deprecated. Review for potential recovery or permanent removal.`,estimatedImpact:"low",effort:"low",autoFixable:!1}));try{let k=R().getDatabase(),q=new X;await q.initialize(k);let D=await q.consolidateAll();(D.merged>0||D.archived>0)&&n.push({type:"experience-consolidation",severity:"info",domain:"learning-optimization",title:"Experiences Consolidated",description:`${D.merged} merged, ${D.archived} archived across ${D.domainsProcessed.length} domains`,context:{merged:D.merged,archived:D.archived,activeRemaining:D.activeRemaining,domains:D.domainsProcessed}})}catch(v){e.logger.warn("Experience consolidation failed",{error:b(v)})}let u=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/(1e3*60*60*24):1;u>=.5&&(c=t.applyConfidenceDecay(Math.min(u,7)).decayed);let z=t.getStats();this.addLifecycleStatsFinding(z,n,s);try{let v=await this.mineExperiencesPerDomain(e,n);l=v.patternsMined,m=v.domainsMined}catch(v){e.logger.warn("Pattern mining sweep failed",{error:b(v)})}try{let k=R().getDatabase();d=ee(k,{retentionDays:Q}).pruned,d>0&&n.push({type:"dream-insights-pruned",severity:"info",domain:"learning-optimization",title:"Stale Dream Insights Pruned",description:`${d} unapplied dream insights older than ${Q} days deleted`,context:{pruned:d,retentionDays:Q}})}catch(v){e.logger.warn("Dream insights pruning failed",{error:b(v)})}e.logger.info("Continuous learning loop complete",{experiencesProcessed:r,patternCandidatesFound:i,patternsPromoted:o,patternsDeprecated:a,confidenceDecayApplied:c,patternsMined:l,domainsMined:m,dreamInsightsPruned:d})}catch(f){e.logger.warn("Continuous learning loop partially failed",{error:b(f)})}return{experiencesProcessed:r,patternCandidatesFound:i,patternsPromoted:o,patternsDeprecated:a,confidenceDecayApplied:c,patternsMined:l,domainsMined:m,dreamInsightsPruned:d}}async mineExperiencesPerDomain(e,t){let n=e.domains.getDomainAPI("learning-optimization");if(!n||typeof n.getLearningService!="function")return e.logger.debug("mineExperiencesPerDomain: learning-optimization API unavailable"),{patternsMined:0,domainsMined:0};let s=n.getLearningService();if(!s)return e.logger.debug("mineExperiencesPerDomain: learning service not initialized"),{patternsMined:0,domainsMined:0};let r=new Date,i=0,o=0;for(let a of w){let c=`${ce}${a}`,l;try{let m=await e.memory.get(c);if(m){let d=new Date(m);if(!isNaN(d.getTime())&&d<r){let f=new Date(r.getTime()-T*24*60*60*1e3);l=d>f?d:f}else l=new Date(r.getTime()-T*24*60*60*1e3)}else l=new Date(r.getTime()-T*24*60*60*1e3)}catch{l=new Date(r.getTime()-T*24*60*60*1e3)}try{let m=J.create(l,r),d=await s.mineExperiences(a,m);if(!d.success){e.logger.debug(`mineExperiences failed for ${a}`,{error:b(d.error)});continue}let{experienceCount:f,patterns:p}=d.value;f>0&&(i+=p.length,o++,await e.memory.set(c,r.toISOString()))}catch(m){e.logger.debug(`mineExperiences threw for ${a}`,{error:b(m)})}}return i>0&&t.push({type:"pattern-mining",severity:"info",domain:"learning-optimization",title:"Patterns Mined from Experience Replay",description:`${i} patterns mined into learning:pattern:* kv across ${o} domain(s) since their last consolidation tick`,context:{patternsMined:i,domainsMined:o,lookbackDays:T}}),{patternsMined:i,domainsMined:o}}async createPatternsFromCandidates(e){let t=0;try{let s=R().getDatabase();for(let r of e)try{let{v4:i}=await import("./dist-node-
|
|
4
|
+
AND created_at < datetime('now', ?)`).run(`-${t} days`).changes}:{pruned:0}}var ae={id:"learning-consolidation",name:"Learning Consolidation",description:"Consolidates learning patterns across domains and optimizes strategies",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:3e5,retryCount:2,retryDelayMs:3e4},ce="learning:consolidation-cursor:",T=1,Q=30,F=class extends y{lifecycleManager=null;lastRunTimestamp=0;constructor(){super(ae)}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=R();await e.initialize();let t=e.getDatabase();return this.lifecycleManager=Y(t,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch(e){return console.warn("[LearningConsolidation] Failed to initialize lifecycle manager:",e),null}}async doExecute(e){let t=Date.now();e.logger.info("Starting learning consolidation (Phase 7: Continuous Learning Loop)");let n=[],s=[],r={success:!1};try{let i=0,o=0,a=0,c=0,l=0,m=0,d=0,f=0,p=await this.getLifecycleManager();if(p){let k=await this.runContinuousLearningLoop(e,p,n,s);i=k.experiencesProcessed,o=k.patternCandidatesFound,a=k.patternsPromoted,c=k.patternsDeprecated,l=k.confidenceDecayApplied,m=k.patternsMined,d=k.domainsMined,f=k.dreamInsightsPruned}let g=await this.collectPatterns(e),u=await this.consolidatePatterns(e,g);u.experiencesProcessed=i,u.patternCandidatesFound=o,u.patternsPromoted=a,u.patternsDeprecated=c,u.confidenceDecayApplied=l,u.patternsMined=m,u.domainsMined=d,u.dreamInsightsPruned=f,this.identifyCrossDomainPatterns(g,n,s),this.pruneIneffectivePatterns(g,n,s),this.generateOptimizations(g,n,s);let z=await this.runDreamCycle(e,g,n,s);u.dreamInsights=z.insights,u.dreamPatternsCreated=z.patternsCreated,await e.memory.set("learning:lastConsolidation",u),await e.memory.set("learning:consolidatedPatterns",g),r={success:!0},this.lastRunTimestamp=Date.now();let v=this.calculateHealthScore(u,g);return e.logger.info("Learning consolidation complete",{healthScore:v,patternsAnalyzed:u.patternsAnalyzed,newInsights:u.newInsights,experiencesProcessed:i,patternsPromoted:a,patternsDeprecated:c}),this.createResult(Date.now()-t,{itemsAnalyzed:u.patternsAnalyzed,issuesFound:u.patternsPruned+u.patternsDeprecated,healthScore:v,trend:this.determineTrend(u),domainMetrics:{patternsAnalyzed:u.patternsAnalyzed,patternsPruned:u.patternsPruned,patternsConsolidated:u.patternsConsolidated,newInsights:u.newInsights,crossDomainPatterns:u.crossDomainPatterns,dreamInsights:u.dreamInsights,dreamPatternsCreated:u.dreamPatternsCreated,experiencesProcessed:u.experiencesProcessed,patternCandidatesFound:u.patternCandidatesFound,patternsPromoted:u.patternsPromoted,patternsDeprecated:u.patternsDeprecated,confidenceDecayApplied:u.confidenceDecayApplied,patternsMined:u.patternsMined,domainsMined:u.domainsMined,dreamInsightsPruned:u.dreamInsightsPruned}},n,s)}catch(i){throw r={success:!1,error:i instanceof Error?i.message:String(i)},i}finally{try{await U(e.memory,"learningWorker",r)}catch(i){e.logger.warn("recordLoopHealth failed (non-fatal)",{error:i instanceof Error?i.message:String(i)})}}}async runContinuousLearningLoop(e,t,n,s){e.logger.info("Running continuous learning loop (Phase 7)");let r=0,i=0,o=0,a=0,c=0,l=0,m=0,d=0;try{let f=t.getRecentExperiences({minReward:.7,limit:100,sinceDays:7});if(r=f.length,f.length>0){e.logger.debug("Processing recent experiences",{count:f.length});let v=t.findPatternCandidates(f);if(i=v.length,v.length>0){let k=await this.createPatternsFromCandidates(v);n.push({type:"pattern-extraction",severity:"info",domain:"learning-optimization",title:"New Patterns Extracted from Experiences",description:`${k} new patterns extracted from ${r} high-reward experiences`,context:{candidatesFound:i,patternsCreated:k,topCandidate:v[0]?.name}})}}let p=t.promoteEligiblePatterns();o=p.promoted,o>0&&n.push({type:"pattern-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted to Long-Term",description:`${o} patterns promoted after meeting quality thresholds`,context:{checked:p.checked,promoted:o}});let g=t.deprecateStalePatterns();a=g.deprecated,a>0&&(n.push({type:"pattern-deprecation",severity:"low",domain:"learning-optimization",title:"Underperforming Patterns Deprecated",description:`${a} patterns deprecated due to failures, staleness, or low confidence`,context:{checked:g.checked,deprecated:a}}),s.push({priority:"p3",domain:"learning-optimization",action:"Review Deprecated Patterns",description:`${a} patterns were deprecated. Review for potential recovery or permanent removal.`,estimatedImpact:"low",effort:"low",autoFixable:!1}));try{let k=R().getDatabase(),q=new X;await q.initialize(k);let D=await q.consolidateAll();(D.merged>0||D.archived>0)&&n.push({type:"experience-consolidation",severity:"info",domain:"learning-optimization",title:"Experiences Consolidated",description:`${D.merged} merged, ${D.archived} archived across ${D.domainsProcessed.length} domains`,context:{merged:D.merged,archived:D.archived,activeRemaining:D.activeRemaining,domains:D.domainsProcessed}})}catch(v){e.logger.warn("Experience consolidation failed",{error:b(v)})}let u=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/(1e3*60*60*24):1;u>=.5&&(c=t.applyConfidenceDecay(Math.min(u,7)).decayed);let z=t.getStats();this.addLifecycleStatsFinding(z,n,s);try{let v=await this.mineExperiencesPerDomain(e,n);l=v.patternsMined,m=v.domainsMined}catch(v){e.logger.warn("Pattern mining sweep failed",{error:b(v)})}try{let k=R().getDatabase();d=ee(k,{retentionDays:Q}).pruned,d>0&&n.push({type:"dream-insights-pruned",severity:"info",domain:"learning-optimization",title:"Stale Dream Insights Pruned",description:`${d} unapplied dream insights older than ${Q} days deleted`,context:{pruned:d,retentionDays:Q}})}catch(v){e.logger.warn("Dream insights pruning failed",{error:b(v)})}e.logger.info("Continuous learning loop complete",{experiencesProcessed:r,patternCandidatesFound:i,patternsPromoted:o,patternsDeprecated:a,confidenceDecayApplied:c,patternsMined:l,domainsMined:m,dreamInsightsPruned:d})}catch(f){e.logger.warn("Continuous learning loop partially failed",{error:b(f)})}return{experiencesProcessed:r,patternCandidatesFound:i,patternsPromoted:o,patternsDeprecated:a,confidenceDecayApplied:c,patternsMined:l,domainsMined:m,dreamInsightsPruned:d}}async mineExperiencesPerDomain(e,t){let n=e.domains.getDomainAPI("learning-optimization");if(!n||typeof n.getLearningService!="function")return e.logger.debug("mineExperiencesPerDomain: learning-optimization API unavailable"),{patternsMined:0,domainsMined:0};let s=n.getLearningService();if(!s)return e.logger.debug("mineExperiencesPerDomain: learning service not initialized"),{patternsMined:0,domainsMined:0};let r=new Date,i=0,o=0;for(let a of w){let c=`${ce}${a}`,l;try{let m=await e.memory.get(c);if(m){let d=new Date(m);if(!isNaN(d.getTime())&&d<r){let f=new Date(r.getTime()-T*24*60*60*1e3);l=d>f?d:f}else l=new Date(r.getTime()-T*24*60*60*1e3)}else l=new Date(r.getTime()-T*24*60*60*1e3)}catch{l=new Date(r.getTime()-T*24*60*60*1e3)}try{let m=J.create(l,r),d=await s.mineExperiences(a,m);if(!d.success){e.logger.debug(`mineExperiences failed for ${a}`,{error:b(d.error)});continue}let{experienceCount:f,patterns:p}=d.value;f>0&&(i+=p.length,o++,await e.memory.set(c,r.toISOString()))}catch(m){e.logger.debug(`mineExperiences threw for ${a}`,{error:b(m)})}}return i>0&&t.push({type:"pattern-mining",severity:"info",domain:"learning-optimization",title:"Patterns Mined from Experience Replay",description:`${i} patterns mined into learning:pattern:* kv across ${o} domain(s) since their last consolidation tick`,context:{patternsMined:i,domainsMined:o,lookbackDays:T}}),{patternsMined:i,domainsMined:o}}async createPatternsFromCandidates(e){let t=0;try{let s=R().getDatabase();for(let r of e)try{let{v4:i}=await import("./dist-node-EZZK46TB.js"),o=i(),a=`Auto-extracted pattern from ${r.sourceExperiences} experiences. Avg reward: ${r.avgReward.toFixed(3)}`;s.prepare(`
|
|
5
5
|
INSERT INTO qe_patterns (
|
|
6
6
|
id, pattern_type, qe_domain, domain, name, description,
|
|
7
7
|
confidence, usage_count, success_rate, quality_score, tier,
|
|
8
8
|
template_json, context_json, created_at, successful_uses
|
|
9
9
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'), ?)
|
|
10
|
-
`).run(o,r.patternType,r.domain,r.domain,r.name,a,r.confidence,r.sourceExperiences,r.successRate,r.confidence*.3+Math.min(r.sourceExperiences,100)/100*.2+r.successRate*.5,"short-term",JSON.stringify({type:"workflow",content:r.templateContent,variables:[]}),JSON.stringify({tags:r.actions,sourceType:"experience-extraction",extractedAt:new Date().toISOString()}),Math.round(r.sourceExperiences*r.successRate));let{ensurePatternEmbedding:c}=await import("./embed-and-insert-pattern-2ARE7NCX.js");await c(s,o,r.name,a,r.actions),t++}catch(i){console.debug("[LearningConsolidation] Failed to create pattern:",i)}}catch(n){console.warn("[LearningConsolidation] Pattern creation batch failed:",n)}return t}addLifecycleStatsFinding(e,t,n){t.push({type:"lifecycle-stats",severity:"info",domain:"learning-optimization",title:"Pattern Lifecycle Statistics",description:`Active: ${e.activePatterns}, Promoted: ${e.promotedPatterns}, Deprecated: ${e.deprecatedPatterns}`,context:{total:e.totalPatterns,active:e.activePatterns,shortTerm:e.shortTermPatterns,longTerm:e.longTermPatterns,deprecated:e.deprecatedPatterns,avgConfidence:e.avgConfidence.toFixed(3),avgSuccessRate:e.avgSuccessRate.toFixed(3),nearDeprecation:e.patternsNearDeprecation}}),e.patternsNearDeprecation>0&&n.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${e.patternsNearDeprecation} patterns are near deprecation threshold. Consider improving their usage or archiving them.`,estimatedImpact:"medium",effort:"low",autoFixable:!1}),e.avgSuccessRate<.6&&n.push({priority:"p2",domain:"learning-optimization",action:"Improve Pattern Quality",description:`Average success rate (${(e.avgSuccessRate*100).toFixed(1)}%) is below target. Focus on quality over quantity.`,estimatedImpact:"high",effort:"medium",autoFixable:!1})}determineTrend(e){let t=e.patternsPromoted/Math.max(1,e.patternsAnalyzed),n=e.patternsDeprecated/Math.max(1,e.patternsAnalyzed),s=e.patternCandidatesFound/Math.max(1,e.experiencesProcessed);return t>.1&&s>.2?"improving":n>.2||e.patternsPruned>e.newInsights?"degrading":"stable"}async collectPatterns(e){let t=[],n=[];for(let s of w)try{let r=await this.getDomainPatterns(e,s);t.push(...r)}catch(r){let i=b(r);n.push(`${s}: ${i}`),e.logger.warn(`Failed to collect patterns from ${s}`,{error:r})}if(t.length===0&&n.length>0)throw new Error(`Failed to collect any learning patterns. Errors from domains: ${n.join("; ")}. Ensure at least one domain is available and has pattern data.`);if(t.length===0)throw new Error("No learning patterns to consolidate yet. Patterns accumulate as the captured-experience bridge feeds hook activity into the learning-optimization domain \u2014 first runs may be empty until a kernel-owning process (CLI/MCP) has been alive long enough to drain the captured_experiences table.");return t}async getDomainPatterns(e,t){let n=e.domains.getDomainAPI("learning-optimization");if(!n)throw new Error(`Learning-optimization domain not available for ${t} - cannot retrieve patterns. Ensure the learning-optimization domain is properly initialized.`);let s=await n.getPatternStats(t);if(!s.success)throw new Error(`Failed to get pattern stats for ${t}: Unknown error. Check domain service health and data availability.`);return!s.value||!s.value.topPatterns||s.value.topPatterns.length===0?(e.logger.debug(`No patterns found for domain ${t}`),[]):s.value.topPatterns.map(i=>({id:i.id,domain:i.domain,type:i.type,pattern:i.name,confidence:i.confidence,occurrences:i.usageCount,lastSeen:new Date(i.lastUsedAt),effectiveness:i.successRate}))}async consolidatePatterns(e,t){let n=0,s=0,r=0,i=new Map;for(let l of t){let m=`${l.type}:${l.pattern}`,d=i.get(m)||[];d.push(l),i.set(m,d)}for(let[,l]of Array.from(i.entries()))l.length>1&&(s+=l.length-1);n=t.filter(l=>l.confidence<.5).length;let a=t.filter(l=>{let m=(Date.now()-l.lastSeen.getTime())/864e5;return l.effectiveness>.8&&m<7});r=a.length;let c=this.findCrossDomainPatterns(t);return await e.memory.set("learning:insights",{recentHighPerformers:a,crossDomainPatterns:c,timestamp:new Date().toISOString()}),{patternsAnalyzed:t.length,patternsPruned:n,patternsConsolidated:s,newInsights:r,strategyUpdates:0,crossDomainPatterns:c.length,dreamInsights:0,dreamPatternsCreated:0,experiencesProcessed:0,patternCandidatesFound:0,patternsPromoted:0,patternsDeprecated:0,confidenceDecayApplied:0,experiencesMerged:0,experiencesArchived:0,patternsMined:0,domainsMined:0,dreamInsightsPruned:0}}async runDreamCycle(e,t,n,s){if(t.length<10)return e.logger.debug("Skipping dream cycle - insufficient patterns",{patternCount:t.length,required:10}),{insights:0,patternsCreated:0};let r=null;try{r=new j,await r.initialize();let i=t.map(c=>({id:c.id,name:c.pattern,description:`${c.type} pattern from ${c.domain} (effectiveness: ${c.effectiveness})`,domain:c.domain,patternType:c.type,confidence:c.confidence,successRate:c.effectiveness}));await r.loadPatternsAsConcepts(i),e.logger.debug("Starting dream cycle",{patternCount:t.length});let o=await r.dream(),a=o.insights.filter(c=>c.actionable&&c.confidenceScore>.7);return a.length>0&&(n.push({type:"dream-insights",severity:"info",domain:"learning-optimization",title:"Dream Cycle Insights Generated",description:`${a.length} actionable insights discovered through pattern association`,context:{totalInsights:o.insights.length,actionableInsights:a.length,topInsight:a[0]?.description,activationIterations:o.activationStats.totalIterations}}),s.push({priority:"p2",domain:"learning-optimization",action:"Apply Dream Insights",description:`${a.length} insights from dream cycle can improve pattern effectiveness`,estimatedImpact:"medium",effort:"low",autoFixable:!0})),await e.memory.set("learning:dreamInsights",{cycleId:o.cycle.id,insights:a,timestamp:new Date().toISOString()}),e.logger.info("Dream cycle completed",{insights:o.insights.length,actionable:a.length,duration:o.cycle.durationMs}),{insights:o.insights.length,patternsCreated:o.patternsCreated}}catch(i){return e.logger.warn("Dream cycle failed",{error:b(i)}),{insights:0,patternsCreated:0}}finally{r&&await r.close()}}findCrossDomainPatterns(e){let t=new Map;for(let s of e){let r=t.get(s.type)||[];r.push(s),t.set(s.type,r)}let n=[];for(let[s,r]of Array.from(t.entries())){let i=Array.from(new Set(r.map(o=>o.domain)));i.length>=3&&n.push({pattern:s,domains:i,avgEffectiveness:r.reduce((o,a)=>o+a.effectiveness,0)/r.length})}return n}identifyCrossDomainPatterns(e,t,n){let s=this.findCrossDomainPatterns(e);s.length>0&&(t.push({type:"cross-domain-patterns",severity:"info",domain:"learning-optimization",title:"Cross-Domain Patterns Identified",description:`${s.length} patterns are effective across multiple domains`,context:{patterns:s.map(r=>({type:r.pattern,domains:r.domains.length,effectiveness:r.avgEffectiveness.toFixed(2)}))}}),n.push({priority:"p2",domain:"learning-optimization",action:"Leverage Cross-Domain Patterns",description:"Apply successful cross-domain patterns to domains where they are not yet used.",estimatedImpact:"medium",effort:"low",autoFixable:!0}))}pruneIneffectivePatterns(e,t,n){let s=e.filter(i=>i.effectiveness<.3&&i.occurrences>10),r=e.filter(i=>(Date.now()-i.lastSeen.getTime())/864e5>30);s.length>0&&(t.push({type:"ineffective-patterns",severity:"low",domain:"learning-optimization",title:"Ineffective Patterns Detected",description:`${s.length} patterns have low effectiveness despite many occurrences`,context:{count:s.length,domains:Array.from(new Set(s.map(i=>i.domain)))}}),n.push({priority:"p3",domain:"learning-optimization",action:"Review Ineffective Patterns",description:"Consider removing or refining patterns that consistently underperform.",estimatedImpact:"low",effort:"low",autoFixable:!0})),r.length>0&&t.push({type:"stale-patterns",severity:"info",domain:"learning-optimization",title:"Stale Patterns Identified",description:`${r.length} patterns have not been seen in over 30 days`,context:{count:r.length}})}generateOptimizations(e,t,n){let s=new Map;for(let o of e)s.set(o.domain,(s.get(o.domain)||0)+1);let r=w.filter(o=>(s.get(o)||0)<3);r.length>0&&(t.push({type:"learning-gaps",severity:"medium",domain:"learning-optimization",title:"Learning Gaps Identified",description:`${r.length} domains have few learned patterns`,context:{domains:r}}),n.push({priority:"p2",domain:"learning-optimization",action:"Improve Learning Coverage",description:`Focus learning efforts on domains with few patterns: ${r.join(", ")}`,estimatedImpact:"medium",effort:"medium",autoFixable:!1}));let i=e.filter(o=>o.effectiveness>.9&&o.occurrences>20).sort((o,a)=>a.effectiveness-o.effectiveness).slice(0,5);i.length>0&&t.push({type:"top-patterns",severity:"info",domain:"learning-optimization",title:"Top Performing Patterns",description:`${i.length} patterns show exceptional effectiveness`,context:{patterns:i.map(o=>({domain:o.domain,type:o.type,effectiveness:o.effectiveness.toFixed(2)}))}})}calculateHealthScore(e,t){if(t.length===0)return 50;let s=t.reduce((i,o)=>i+o.effectiveness,0)/t.length*50;s+=Math.min(20,e.newInsights*4),s+=Math.min(15,e.crossDomainPatterns*3),s+=Math.min(10,e.dreamInsights*2);let r=e.patternsPruned/e.patternsAnalyzed;return s-=r*15,Math.max(0,Math.min(100,Math.round(s)))}};var le={id:"defect-predictor",name:"Defect Predictor",description:"Uses ML patterns to predict potential defects and identify high-risk code areas",intervalMs:900*1e3,priority:"high",targetDomains:["defect-intelligence"],enabled:!0,timeoutMs:18e4,retryCount:2,retryDelayMs:15e3},I=class extends y{constructor(){super(le)}async doExecute(e){let t=Date.now();e.logger.info("Starting defect prediction analysis");let n=[],s=[],r=await this.analyzeCodeForDefects(e),i=await this.identifyHotspots(e);this.analyzeHighRiskPredictions(r,n,s),this.analyzeHotspots(i,n,s),await e.memory.set("defect:predictions",r),await e.memory.set("defect:hotspots",i),await e.memory.set("defect:lastAnalysis",new Date().toISOString());let o=this.calculateHealthScore(r,i);return e.logger.info("Defect prediction complete",{healthScore:o,predictionsCount:r.length,hotspotsCount:i.length}),this.createResult(Date.now()-t,{itemsAnalyzed:r.length,issuesFound:r.filter(a=>a.probability>.5).length,healthScore:o,trend:"stable",domainMetrics:{filesAnalyzed:r.length,highRiskFiles:r.filter(a=>a.riskLevel==="high"||a.riskLevel==="critical").length,hotspots:i.length,avgDefectProbability:(r.reduce((a,c)=>a+c.probability,0)/r.length).toFixed(2)}},n,s)}async analyzeCodeForDefects(e){return[{file:"src/coordination/workflow-orchestrator.ts",probability:.78,riskLevel:"high",factors:[{name:"complexity",weight:.3,description:"High cyclomatic complexity (28)"},{name:"change-frequency",weight:.25,description:"Changed 15 times in last 30 days"},{name:"size",weight:.2,description:"Large file (1500+ lines)"},{name:"coupling",weight:.15,description:"High coupling with 8 other modules"}],recentChanges:15,historicalDefects:3,complexity:28},{file:"src/domains/security-compliance/services/security-scanner.ts",probability:.65,riskLevel:"high",factors:[{name:"complexity",weight:.35,description:"High cyclomatic complexity (32)"},{name:"size",weight:.25,description:"Very large file (1200+ lines)"},{name:"test-coverage",weight:.2,description:"Low test coverage (45%)"}],recentChanges:8,historicalDefects:2,complexity:32},{file:"src/kernel/memory-backend.ts",probability:.45,riskLevel:"medium",factors:[{name:"change-frequency",weight:.4,description:"Changed 10 times in last 30 days"},{name:"authors",weight:.3,description:"Multiple authors (4)"}],recentChanges:10,historicalDefects:1,complexity:15},{file:"src/shared/http/http-client.ts",probability:.25,riskLevel:"low",factors:[{name:"stability",weight:.5,description:"Stable code, few recent changes"}],recentChanges:2,historicalDefects:0,complexity:8}]}async identifyHotspots(e){return[{file:"src/coordination/workflow-orchestrator.ts",changeFrequency:15,defectDensity:.02,authors:4,lastModified:new Date(Date.now()-2880*60*1e3),score:.85},{file:"src/domains/test-generation/services/test-generator.ts",changeFrequency:12,defectDensity:.015,authors:3,lastModified:new Date(Date.now()-7200*60*1e3),score:.72},{file:"src/mcp/server.ts",changeFrequency:8,defectDensity:.01,authors:2,lastModified:new Date(Date.now()-4320*60*1e3),score:.55}]}analyzeHighRiskPredictions(e,t,n){let s=e.filter(i=>i.riskLevel==="critical"),r=e.filter(i=>i.riskLevel==="high");for(let i of s)t.push({type:"critical-defect-risk",severity:"critical",domain:"defect-intelligence",title:`Critical Defect Risk: ${i.file.split("/").pop()}`,description:`${(i.probability*100).toFixed(0)}% probability of defect based on code analysis`,resource:i.file,context:{probability:i.probability,factors:i.factors,recentChanges:i.recentChanges,historicalDefects:i.historicalDefects}});for(let i of r)t.push({type:"high-defect-risk",severity:"high",domain:"defect-intelligence",title:`High Defect Risk: ${i.file.split("/").pop()}`,description:`${(i.probability*100).toFixed(0)}% probability of defect`,resource:i.file,context:{probability:i.probability,topFactors:i.factors.slice(0,3),complexity:i.complexity}});if(s.length>0||r.length>0){n.push({priority:"p0",domain:"defect-intelligence",action:"Prioritize Code Review for High-Risk Files",description:`${s.length+r.length} files have elevated defect risk. Schedule focused code reviews.`,estimatedImpact:"high",effort:"medium",autoFixable:!1});let i=e.filter(a=>a.factors.some(c=>c.name==="complexity"&&c.weight>.25));i.length>0&&n.push({priority:"p1",domain:"defect-intelligence",action:"Reduce Code Complexity",description:`${i.length} files have high complexity as a defect risk factor. Consider refactoring.`,estimatedImpact:"high",effort:"high",autoFixable:!1});let o=e.filter(a=>a.factors.some(c=>c.name==="test-coverage"));o.length>0&&n.push({priority:"p1",domain:"defect-intelligence",action:"Improve Test Coverage for Risky Files",description:`${o.length} high-risk files have low test coverage. Add targeted tests.`,estimatedImpact:"high",effort:"medium",autoFixable:!0})}}analyzeHotspots(e,t,n){let s=e.filter(i=>i.score>.7);s.length>0&&(t.push({type:"code-hotspots",severity:"medium",domain:"defect-intelligence",title:`${s.length} Code Hotspots Detected`,description:"Files with high change frequency and defect density identified",context:{hotspots:s.map(i=>({file:i.file,changeFrequency:i.changeFrequency,score:i.score.toFixed(2)}))}}),n.push({priority:"p2",domain:"defect-intelligence",action:"Address Code Hotspots",description:"Consider refactoring frequently-changed, defect-prone files to improve stability.",estimatedImpact:"medium",effort:"high",autoFixable:!1}));let r=e.filter(i=>i.authors===1&&i.changeFrequency>5);r.length>0&&(t.push({type:"knowledge-silo",severity:"medium",domain:"defect-intelligence",title:"Knowledge Silos Detected",description:`${r.length} frequently-changed files have only one author`,context:{files:r.map(i=>i.file)}}),n.push({priority:"p2",domain:"defect-intelligence",action:"Address Knowledge Silos",description:"Ensure knowledge sharing for files maintained by single developers.",estimatedImpact:"medium",effort:"low",autoFixable:!1}))}calculateHealthScore(e,t){if(e.length===0)return 100;let s=(1-e.reduce((a,c)=>a+c.probability,0)/e.length)*60,r=e.filter(a=>a.riskLevel==="critical"||a.riskLevel==="high").length;s-=r/e.length*20;let i=t.filter(a=>a.score>.7).length;s-=i*3;let o=e.filter(a=>a.riskLevel==="low").length/e.length;return s+=o*20,Math.max(0,Math.min(100,Math.round(s)))}};var ue={id:"regression-monitor",name:"Regression Monitor",description:"Monitors for regressions in test results, performance, coverage, and quality metrics",intervalMs:600*1e3,priority:"high",targetDomains:["test-execution","coverage-analysis","quality-assessment"],enabled:!0,timeoutMs:12e4,retryCount:2,retryDelayMs:1e4},A=class extends y{constructor(){super(ue)}async doExecute(e){let t=Date.now();e.logger.info("Starting regression monitoring");let n=[],s=[],r=await this.collectCurrentSnapshot(e),i=await e.memory.get("regression:baseline"),o=[];i&&(o=this.detectRegressions(i,r),this.analyzeRegressions(o,n,s)),await e.memory.set("regression:baseline",r);let a=await e.memory.get("regression:history")||[];if(o.length>0){for(a.push(...o);a.length>100;)a.shift();await e.memory.set("regression:history",a)}let c=this.calculateHealthScore(o);return e.logger.info("Regression monitoring complete",{healthScore:c,regressionsDetected:o.length}),this.createResult(Date.now()-t,{itemsAnalyzed:5,issuesFound:o.length,healthScore:c,trend:o.length>0?"degrading":"stable",domainMetrics:{testPassRate:`${r.testPassRate}%`,lineCoverage:`${r.coverage.line}%`,avgTestDuration:`${r.avgTestDuration}ms`,qualityScore:r.qualityScore,regressionsDetected:o.length}},n,s)}async collectCurrentSnapshot(e){return{timestamp:new Date,testPassRate:98.2,coverage:{line:78.5,branch:65.2},avgTestDuration:245,failedTests:["test-execution/retry-handler.test.ts::should retry failed tests","coordination/workflow.test.ts::should handle concurrent workflows"],qualityScore:82}}detectRegressions(e,t){let n=[];if(t.testPassRate<e.testPassRate-1){let i=t.testPassRate-e.testPassRate;n.push({type:"test",metric:"testPassRate",previousValue:e.testPassRate,currentValue:t.testPassRate,changePercent:i,severity:i<-5?"critical":i<-2?"high":"medium",affectedTests:t.failedTests})}if(t.coverage.line<e.coverage.line-2){let i=t.coverage.line-e.coverage.line;n.push({type:"coverage",metric:"lineCoverage",previousValue:e.coverage.line,currentValue:t.coverage.line,changePercent:i,severity:i<-5?"high":"medium"})}if(t.coverage.branch<e.coverage.branch-3){let i=t.coverage.branch-e.coverage.branch;n.push({type:"coverage",metric:"branchCoverage",previousValue:e.coverage.branch,currentValue:t.coverage.branch,changePercent:i,severity:i<-5?"high":"medium"})}let s=(t.avgTestDuration-e.avgTestDuration)/e.avgTestDuration*100;if(s>20&&n.push({type:"performance",metric:"avgTestDuration",previousValue:e.avgTestDuration,currentValue:t.avgTestDuration,changePercent:s,severity:s>50?"high":"medium"}),t.qualityScore<e.qualityScore-5){let i=t.qualityScore-e.qualityScore;n.push({type:"quality",metric:"qualityScore",previousValue:e.qualityScore,currentValue:t.qualityScore,changePercent:i,severity:i<-10?"critical":i<-5?"high":"medium"})}let r=t.failedTests.filter(i=>!e.failedTests.includes(i));return r.length>0&&n.push({type:"test",metric:"newFailures",previousValue:0,currentValue:r.length,changePercent:100,severity:r.length>5?"critical":r.length>2?"high":"medium",affectedTests:r}),n}analyzeRegressions(e,t,n){for(let o of e){let a=this.getDomainForType(o.type);t.push({type:`${o.type}-regression`,severity:o.severity,domain:a,title:`${this.formatMetricName(o.metric)} Regression Detected`,description:this.formatRegressionDescription(o),context:{previousValue:o.previousValue,currentValue:o.currentValue,changePercent:o.changePercent.toFixed(2),affectedTests:o.affectedTests}})}let s=e.filter(o=>o.type==="test");if(s.length>0){let o=s.filter(a=>a.severity==="critical"||a.severity==="high");o.length>0&&n.push({priority:"p0",domain:"test-execution",action:"Investigate Test Regressions Immediately",description:`${o.length} significant test regressions detected. Review recent changes.`,estimatedImpact:"high",effort:"medium",autoFixable:!1})}e.filter(o=>o.type==="coverage").length>0&&n.push({priority:"p1",domain:"coverage-analysis",action:"Address Coverage Regression",description:"Code coverage has decreased. Add tests for new/changed code.",estimatedImpact:"medium",effort:"medium",autoFixable:!0}),e.filter(o=>o.type==="performance").length>0&&n.push({priority:"p2",domain:"test-execution",action:"Investigate Performance Regression",description:"Test execution has slowed. Review for new slow tests or infrastructure issues.",estimatedImpact:"medium",effort:"low",autoFixable:!1})}getDomainForType(e){switch(e){case"test":case"performance":return"test-execution";case"coverage":return"coverage-analysis";case"quality":return"quality-assessment";default:return"quality-assessment"}}formatMetricName(e){return{testPassRate:"Test Pass Rate",lineCoverage:"Line Coverage",branchCoverage:"Branch Coverage",avgTestDuration:"Test Duration",qualityScore:"Quality Score",newFailures:"New Test Failures"}[e]||e}formatRegressionDescription(e){if(e.metric==="newFailures")return`${e.currentValue} new test failures detected since last check`;let t=e.changePercent>0?"increased":"decreased",n=e.type==="performance"?"ms":"%";return`${this.formatMetricName(e.metric)} ${t} from ${e.previousValue}${n} to ${e.currentValue}${n} (${e.changePercent>0?"+":""}${e.changePercent.toFixed(1)}%)`}calculateHealthScore(e){if(e.length===0)return 100;let t=100;for(let n of e)switch(n.severity){case"critical":t-=25;break;case"high":t-=15;break;case"medium":t-=8;break;case"low":t-=3;break}return Math.max(0,Math.round(t))}};var de={id:"performance-baseline",name:"Performance Baseline Tracker",description:"Tracks performance trends and establishes baselines for test execution and builds",intervalMs:3600*1e3,priority:"normal",targetDomains:["test-execution","chaos-resilience"],enabled:!0,timeoutMs:3e5,retryCount:2,retryDelayMs:3e4},E=class extends y{constructor(){super(de)}async doExecute(e){let t=Date.now();e.logger.info("Starting performance baseline tracking");let n=[],s=[],r=await this.collectPerformanceMetrics(e),i=await this.getOrCalculateBaseline(e),o=this.detectAnomalies(r,i);this.analyzeAnomalies(o,n,s),await this.updateBaseline(e,r,i),await this.storeMetricsHistory(e,r);let a=this.calculateHealthScore(o);return e.logger.info("Performance baseline tracking complete",{healthScore:a,anomaliesDetected:o.length}),this.createResult(Date.now()-t,{itemsAnalyzed:10,issuesFound:o.length,healthScore:a,trend:o.length>2?"degrading":"stable",domainMetrics:{avgTestDuration:`${r.testExecution.avgTestDurationMs}ms`,p95TestDuration:`${r.testExecution.p95DurationMs}ms`,compileDuration:`${r.build.compileDurationMs}ms`,bundleSize:`${r.build.bundleSizeKb}KB`,peakMemory:`${r.resources.peakMemoryMb}MB`,anomalies:o.length}},n,s)}async collectPerformanceMetrics(e){return{timestamp:new Date,testExecution:{totalDurationMs:45e3,avgTestDurationMs:245,slowestTestMs:3500,slowestTestName:"workflow-orchestrator.test.ts::complex scenario",p50DurationMs:120,p95DurationMs:800,p99DurationMs:2500},build:{compileDurationMs:12e3,bundleSizeKb:2500,dependencyCount:45},resources:{peakMemoryMb:512,avgCpuPercent:65,diskReadMb:150,diskWriteMb:50}}}async getOrCalculateBaseline(e){let t=await e.memory.get("performance:baseline");return t||{testExecution:{avgDurationMs:200,p95DurationMs:700,threshold:1.3},build:{avgCompileMs:1e4,avgBundleSizeKb:2400,threshold:1.2},resources:{avgMemoryMb:450,avgCpuPercent:60,threshold:1.25}}}detectAnomalies(e,t){let n=[],s=e.testExecution.avgTestDurationMs/t.testExecution.avgDurationMs;s>t.testExecution.threshold&&n.push({metric:"avgTestDuration",category:"test",currentValue:e.testExecution.avgTestDurationMs,baselineValue:t.testExecution.avgDurationMs,deviationPercent:(s-1)*100,severity:s>1.5?"high":"medium"});let r=e.testExecution.p95DurationMs/t.testExecution.p95DurationMs;r>t.testExecution.threshold&&n.push({metric:"p95TestDuration",category:"test",currentValue:e.testExecution.p95DurationMs,baselineValue:t.testExecution.p95DurationMs,deviationPercent:(r-1)*100,severity:r>1.5?"high":"medium"});let i=e.build.compileDurationMs/t.build.avgCompileMs;i>t.build.threshold&&n.push({metric:"compileDuration",category:"build",currentValue:e.build.compileDurationMs,baselineValue:t.build.avgCompileMs,deviationPercent:(i-1)*100,severity:i>1.5?"high":"medium"});let o=e.build.bundleSizeKb/t.build.avgBundleSizeKb;o>t.build.threshold&&n.push({metric:"bundleSize",category:"build",currentValue:e.build.bundleSizeKb,baselineValue:t.build.avgBundleSizeKb,deviationPercent:(o-1)*100,severity:o>1.3?"high":"medium"});let a=e.resources.peakMemoryMb/t.resources.avgMemoryMb;a>t.resources.threshold&&n.push({metric:"peakMemory",category:"resource",currentValue:e.resources.peakMemoryMb,baselineValue:t.resources.avgMemoryMb,deviationPercent:(a-1)*100,severity:a>1.5?"critical":a>1.3?"high":"medium"});let c=e.resources.avgCpuPercent/t.resources.avgCpuPercent;return c>t.resources.threshold&&n.push({metric:"avgCpu",category:"resource",currentValue:e.resources.avgCpuPercent,baselineValue:t.resources.avgCpuPercent,deviationPercent:(c-1)*100,severity:c>1.4?"high":"medium"}),n}analyzeAnomalies(e,t,n){for(let o of e){let a=o.category==="test"?"test-execution":"chaos-resilience";t.push({type:`performance-anomaly-${o.category}`,severity:o.severity,domain:a,title:`Performance Anomaly: ${this.formatMetricName(o.metric)}`,description:`${this.formatMetricName(o.metric)} is ${o.deviationPercent.toFixed(1)}% above baseline`,context:{currentValue:o.currentValue,baselineValue:o.baselineValue,deviationPercent:o.deviationPercent.toFixed(1)}})}let s=e.filter(o=>o.category==="test");s.length>0&&n.push({priority:s.some(o=>o.severity==="high")?"p1":"p2",domain:"test-execution",action:"Investigate Test Performance Degradation",description:"Test execution times have increased. Review for slow tests or infrastructure issues.",estimatedImpact:"medium",effort:"medium",autoFixable:!1});let r=e.filter(o=>o.category==="build");r.length>0&&r.find(a=>a.metric==="bundleSize")&&n.push({priority:"p2",domain:"chaos-resilience",action:"Analyze Bundle Size Increase",description:"Bundle size has grown. Review for unnecessary dependencies or unoptimized imports.",estimatedImpact:"medium",effort:"low",autoFixable:!0});let i=e.filter(o=>o.category==="resource");if(i.length>0){let o=i.find(a=>a.metric==="peakMemory");o&&o.severity==="critical"&&n.push({priority:"p0",domain:"chaos-resilience",action:"Investigate Memory Usage Spike",description:"Memory usage is significantly above baseline. Check for memory leaks.",estimatedImpact:"high",effort:"high",autoFixable:!1})}}formatMetricName(e){return{avgTestDuration:"Average Test Duration",p95TestDuration:"P95 Test Duration",compileDuration:"Compile Duration",bundleSize:"Bundle Size",peakMemory:"Peak Memory Usage",avgCpu:"Average CPU Usage"}[e]||e}async updateBaseline(e,t,n){let r={testExecution:{avgDurationMs:n.testExecution.avgDurationMs*.9+t.testExecution.avgTestDurationMs*.1,p95DurationMs:n.testExecution.p95DurationMs*.9+t.testExecution.p95DurationMs*.1,threshold:n.testExecution.threshold},build:{avgCompileMs:n.build.avgCompileMs*.9+t.build.compileDurationMs*.1,avgBundleSizeKb:n.build.avgBundleSizeKb*.9+t.build.bundleSizeKb*.1,threshold:n.build.threshold},resources:{avgMemoryMb:n.resources.avgMemoryMb*.9+t.resources.peakMemoryMb*.1,avgCpuPercent:n.resources.avgCpuPercent*.9+t.resources.avgCpuPercent*.1,threshold:n.resources.threshold}};await e.memory.set("performance:baseline",r)}async storeMetricsHistory(e,t){let n=await e.memory.get("performance:history")||[];for(n.push(t);n.length>168;)n.shift();await e.memory.set("performance:history",n)}calculateHealthScore(e){if(e.length===0)return 100;let t=100;for(let n of e){let s={critical:25,high:15,medium:8,low:3}[n.severity],r=Math.min(10,n.deviationPercent/10);t-=s+r}return Math.max(0,Math.round(t))}};var me={id:"compliance-checker",name:"ADR/DDD Compliance Checker",description:"Verifies compliance with Architecture Decision Records and DDD patterns",intervalMs:1800*1e3,priority:"normal",targetDomains:["quality-assessment"],enabled:!0,timeoutMs:24e4,retryCount:2,retryDelayMs:3e4},$=class extends y{constructor(){super(me)}async doExecute(e){let t=Date.now();e.logger.info("Starting compliance checking");let n=[],s=[],r=await this.checkADRCompliance(e),i=await this.checkDDDCompliance(e),o=await this.checkStructuralCompliance(e);this.analyzeADRCompliance(r,n,s),this.analyzeDDDCompliance(i,n,s),this.analyzeStructuralCompliance(o,n,s),await e.memory.set("compliance:adr",r),await e.memory.set("compliance:ddd",i),await e.memory.set("compliance:structural",o),await e.memory.set("compliance:lastCheck",new Date().toISOString());let a=this.calculateHealthScore(r,i,o);return e.logger.info("Compliance checking complete",{healthScore:a,adrChecks:r.length,domainChecks:i.length}),this.createResult(Date.now()-t,{itemsAnalyzed:r.length+i.length+o.length,issuesFound:n.length,healthScore:a,trend:"stable",domainMetrics:{adrCompliance:`${this.calculateAvgScore(r)}%`,dddCompliance:`${this.calculateDDDAvgScore(i)}%`,structuralCompliance:`${this.calculateStructuralScore(o)}%`,totalViolations:r.reduce((c,l)=>c+l.violations.length,0)+i.reduce((c,l)=>c+l.violations.length,0)}},n,s)}async checkADRCompliance(e){if(!e.domains.getDomainAPI("quality-assessment"))throw new Error("Quality-assessment domain not available - cannot check ADR compliance. Ensure the quality-assessment domain is properly initialized before running this worker.");let n=await e.memory.search("compliance:adr:*");if(n.length===0)throw new Error('No ADR compliance data found in memory - cannot check ADR compliance. Ensure ADR compliance data is stored with keys matching "compliance:adr:*" before running this worker.');let s=[],r=[];for(let i of n)try{let o=await e.memory.get(i);o&&s.push(o)}catch{r.push(i)}if(s.length===0)throw new Error(`Found ${n.length} ADR compliance keys but failed to retrieve any data. Failed keys: ${r.join(", ")}. Check memory service connectivity.`);return s}async checkDDDCompliance(e){let t=[];for(let n of w)try{let s=await this.checkDomainCompliance(e,n);t.push(s)}catch(s){e.logger.warn(`Failed to check DDD compliance for ${n}`,{error:s})}return t}async checkDomainCompliance(e,t){let n=e.domains.getDomainHealth(t),s=e.domains.getDomainAPI(t),r=n.status!=="unhealthy",i=s!==void 0,o=i,a=i,c=await e.memory.get(`compliance:ddd:${t}`),l=c?.hasEntities??!1,m=c?.hasEvents??!1,d=c?.hasRepositories??!1,f=c?.namingCompliant??i,p=[];l||p.push("Missing domain entities"),m||p.push("Missing domain events"),d||p.push("Missing repositories"),r||p.push("Domain coordinator not available"),i||p.push("Domain plugin not loaded");let g=[r,i,o,a,l,m,d,f],u=Math.round(g.filter(Boolean).length/g.length*100);return{domain:t,hasCoordinator:r,hasPlugin:i,hasInterfaces:o,hasServices:a,hasEntities:l,hasEvents:m,hasRepositories:d,namingCompliant:f,score:u,violations:p}}async checkStructuralCompliance(e){let t=await e.memory.search("compliance:structural:*");if(t.length===0)throw new Error('No structural compliance data found in memory - cannot check structural compliance. Ensure structural compliance data is stored with keys matching "compliance:structural:*" before running this worker.');let n=[],s=[];for(let r of t)try{let i=await e.memory.get(r);i&&n.push(i)}catch(i){s.push(r),e.logger.warn(`Failed to retrieve structural compliance data: ${r}`,{error:i})}if(n.length===0)throw new Error(`Found ${t.length} structural compliance keys but failed to retrieve any data. Failed keys: ${s.join(", ")}. Check memory service connectivity.`);return n}analyzeADRCompliance(e,t,n){let s=e.filter(i=>i.status==="non-compliant"),r=e.filter(i=>i.status==="partial");for(let i of s)t.push({type:"adr-non-compliance",severity:"high",domain:"quality-assessment",title:`ADR Non-Compliance: ${i.adrId}`,description:`${i.title} is not compliant (score: ${i.score}%)`,context:{adrId:i.adrId,violations:i.violations}});for(let i of r)t.push({type:"adr-partial-compliance",severity:"medium",domain:"quality-assessment",title:`ADR Partial Compliance: ${i.adrId}`,description:`${i.title} is partially compliant (score: ${i.score}%)`,context:{adrId:i.adrId,violations:i.violations}});s.length>0&&n.push({priority:"p1",domain:"quality-assessment",action:"Address ADR Non-Compliance",description:`${s.length} ADRs are not being followed. Review and implement required patterns.`,estimatedImpact:"high",effort:"high",autoFixable:!1})}analyzeDDDCompliance(e,t,n){let s=e.filter(o=>o.score<70),r=e.filter(o=>!o.hasEntities),i=e.filter(o=>!o.hasEvents);s.length>0&&t.push({type:"ddd-low-compliance",severity:"medium",domain:"quality-assessment",title:`${s.length} Domains Have Low DDD Compliance`,description:"Some domains are missing required DDD components",context:{domains:s.map(o=>({domain:o.domain,score:o.score}))}}),r.length>0&&(t.push({type:"ddd-missing-entities",severity:"low",domain:"quality-assessment",title:"Domains Missing Entity Definitions",description:`${r.length} domains lack proper entity definitions`,context:{domains:r.map(o=>o.domain)}}),n.push({priority:"p3",domain:"quality-assessment",action:"Add Domain Entities",description:"Define rich domain entities for domains that currently lack them.",estimatedImpact:"medium",effort:"medium",autoFixable:!1})),i.length>0&&n.push({priority:"p3",domain:"quality-assessment",action:"Implement Domain Events",description:`${i.length} domains are missing domain event definitions.`,estimatedImpact:"medium",effort:"medium",autoFixable:!1})}analyzeStructuralCompliance(e,t,n){let s=e.filter(r=>!r.compliant);for(let r of s)t.push({type:"structural-violation",severity:"medium",domain:"quality-assessment",title:`Structural Violation: ${r.category}`,description:`Rule "${r.rule}" is not being followed: ${r.details}`,context:{category:r.category,rule:r.rule}});s.length>0&&n.push({priority:"p2",domain:"quality-assessment",action:"Fix Structural Violations",description:`${s.length} structural rules are being violated. Review architecture guidelines.`,estimatedImpact:"medium",effort:"medium",autoFixable:!1})}calculateAvgScore(e){return e.length===0?100:Math.round(e.reduce((t,n)=>t+n.score,0)/e.length)}calculateDDDAvgScore(e){return e.length===0?100:Math.round(e.reduce((t,n)=>t+n.score,0)/e.length)}calculateStructuralScore(e){if(e.length===0)return 100;let t=e.filter(n=>n.compliant).length;return Math.round(t/e.length*100)}calculateHealthScore(e,t,n){let s=this.calculateAvgScore(e)*.4,r=this.calculateDDDAvgScore(t)*.4,i=this.calculateStructuralScore(n)*.2;return Math.round(s+r+i)}};V();var Ze={id:"cloud-sync",name:"Cloud Sync",description:"Periodically syncs local learning data to cloud PostgreSQL",intervalMs:parseInt(process.env.AQE_SYNC_INTERVAL||"3600000",10),priority:"low",targetDomains:["learning-optimization"],enabled:process.env.AQE_CLOUD_SYNC_ENABLED==="true",timeoutMs:6e5,retryCount:3,retryDelayMs:6e4};var pe={autoStart:!0,enabledWorkers:[],logLevel:"info",healthCheckIntervalMs:6e4},K=class{_running=!1;_startedAt;_healthCheckTimer;workerManager;config;_qualityDaemon;constructor(e){this.config={...pe,...e},this.workerManager=new N,this.registerWorkers()}get running(){return this._running}get uptime(){return this._startedAt?Math.floor((Date.now()-this._startedAt.getTime())/1e3):0}async start(){if(this._running){console.info("[Daemon] Already running");return}console.info("[Daemon] Starting QE Background Workers..."),this._running=!0,this._startedAt=new Date,this._healthCheckTimer=setInterval(()=>{this.performHealthCheck()},this.config.healthCheckIntervalMs),this.config.autoStart&&(await this.workerManager.startAll(),console.info("[Daemon] All workers started"));let e=this.workerManager.list();console.info(`[Daemon] Registered ${e.length} workers:`);for(let t of e)console.info(` - ${t.config.id}: ${t.config.name} (interval: ${t.config.intervalMs}ms)`)}async stop(){if(!this._running){console.info("[Daemon] Not running");return}console.info("[Daemon] Stopping..."),this._healthCheckTimer&&(clearInterval(this._healthCheckTimer),this._healthCheckTimer=void 0),await this.workerManager.stopAll(),this._running=!1,console.info("[Daemon] Stopped")}async restart(){console.info("[Daemon] Restarting..."),await this.stop(),await this.start(),console.info("[Daemon] Restarted")}getStatus(){return{running:this._running,pid:process.pid,uptime:this.uptime,startedAt:this._startedAt,workerManager:this.workerManager.getHealth()}}getWorkerManager(){return this.workerManager}getQualityDaemon(e){return this._qualityDaemon||(this._qualityDaemon=new Z(e)),this._qualityDaemon}async runWorker(e){let t=await this.workerManager.runNow(e);console.info(`[Daemon] Worker ${e} completed:`,{success:t.success,duration:`${t.durationMs}ms`,findings:t.findings.length,healthScore:t.metrics.healthScore})}registerWorkers(){let e=[new M,new x,new P,new S,new W,new F,new I,new A,new E,new $,new B];for(let t of e)(this.config.enabledWorkers.length===0||this.config.enabledWorkers.includes(t.config.id))&&this.workerManager.register(t)}performHealthCheck(){let e=this.workerManager.getHealth();e.errorWorkers>0&&console.warn(`[Daemon] Health check: ${e.errorWorkers} workers in error state`),e.healthScore<70&&console.warn(`[Daemon] Health score degraded: ${e.healthScore}%`),this.config.logLevel==="debug"&&console.debug("[Daemon] Health check:",e)}};function ge(h){return new K(h)}var C;function vt(h){return C||(C=ge(h)),C}function kt(){C?.running&&C.stop().catch(console.error),C=void 0}export{K as QEDaemon,ge as createDaemon,vt as getDaemon,kt as resetDaemon};
|
|
10
|
+
`).run(o,r.patternType,r.domain,r.domain,r.name,a,r.confidence,r.sourceExperiences,r.successRate,r.confidence*.3+Math.min(r.sourceExperiences,100)/100*.2+r.successRate*.5,"short-term",JSON.stringify({type:"workflow",content:r.templateContent,variables:[]}),JSON.stringify({tags:r.actions,sourceType:"experience-extraction",extractedAt:new Date().toISOString()}),Math.round(r.sourceExperiences*r.successRate));let{ensurePatternEmbedding:c}=await import("./embed-and-insert-pattern-XFYPPWG7.js");await c(s,o,r.name,a,r.actions),t++}catch(i){console.debug("[LearningConsolidation] Failed to create pattern:",i)}}catch(n){console.warn("[LearningConsolidation] Pattern creation batch failed:",n)}return t}addLifecycleStatsFinding(e,t,n){t.push({type:"lifecycle-stats",severity:"info",domain:"learning-optimization",title:"Pattern Lifecycle Statistics",description:`Active: ${e.activePatterns}, Promoted: ${e.promotedPatterns}, Deprecated: ${e.deprecatedPatterns}`,context:{total:e.totalPatterns,active:e.activePatterns,shortTerm:e.shortTermPatterns,longTerm:e.longTermPatterns,deprecated:e.deprecatedPatterns,avgConfidence:e.avgConfidence.toFixed(3),avgSuccessRate:e.avgSuccessRate.toFixed(3),nearDeprecation:e.patternsNearDeprecation}}),e.patternsNearDeprecation>0&&n.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${e.patternsNearDeprecation} patterns are near deprecation threshold. Consider improving their usage or archiving them.`,estimatedImpact:"medium",effort:"low",autoFixable:!1}),e.avgSuccessRate<.6&&n.push({priority:"p2",domain:"learning-optimization",action:"Improve Pattern Quality",description:`Average success rate (${(e.avgSuccessRate*100).toFixed(1)}%) is below target. Focus on quality over quantity.`,estimatedImpact:"high",effort:"medium",autoFixable:!1})}determineTrend(e){let t=e.patternsPromoted/Math.max(1,e.patternsAnalyzed),n=e.patternsDeprecated/Math.max(1,e.patternsAnalyzed),s=e.patternCandidatesFound/Math.max(1,e.experiencesProcessed);return t>.1&&s>.2?"improving":n>.2||e.patternsPruned>e.newInsights?"degrading":"stable"}async collectPatterns(e){let t=[],n=[];for(let s of w)try{let r=await this.getDomainPatterns(e,s);t.push(...r)}catch(r){let i=b(r);n.push(`${s}: ${i}`),e.logger.warn(`Failed to collect patterns from ${s}`,{error:r})}if(t.length===0&&n.length>0)throw new Error(`Failed to collect any learning patterns. Errors from domains: ${n.join("; ")}. Ensure at least one domain is available and has pattern data.`);if(t.length===0)throw new Error("No learning patterns to consolidate yet. Patterns accumulate as the captured-experience bridge feeds hook activity into the learning-optimization domain \u2014 first runs may be empty until a kernel-owning process (CLI/MCP) has been alive long enough to drain the captured_experiences table.");return t}async getDomainPatterns(e,t){let n=e.domains.getDomainAPI("learning-optimization");if(!n)throw new Error(`Learning-optimization domain not available for ${t} - cannot retrieve patterns. Ensure the learning-optimization domain is properly initialized.`);let s=await n.getPatternStats(t);if(!s.success)throw new Error(`Failed to get pattern stats for ${t}: Unknown error. Check domain service health and data availability.`);return!s.value||!s.value.topPatterns||s.value.topPatterns.length===0?(e.logger.debug(`No patterns found for domain ${t}`),[]):s.value.topPatterns.map(i=>({id:i.id,domain:i.domain,type:i.type,pattern:i.name,confidence:i.confidence,occurrences:i.usageCount,lastSeen:new Date(i.lastUsedAt),effectiveness:i.successRate}))}async consolidatePatterns(e,t){let n=0,s=0,r=0,i=new Map;for(let l of t){let m=`${l.type}:${l.pattern}`,d=i.get(m)||[];d.push(l),i.set(m,d)}for(let[,l]of Array.from(i.entries()))l.length>1&&(s+=l.length-1);n=t.filter(l=>l.confidence<.5).length;let a=t.filter(l=>{let m=(Date.now()-l.lastSeen.getTime())/864e5;return l.effectiveness>.8&&m<7});r=a.length;let c=this.findCrossDomainPatterns(t);return await e.memory.set("learning:insights",{recentHighPerformers:a,crossDomainPatterns:c,timestamp:new Date().toISOString()}),{patternsAnalyzed:t.length,patternsPruned:n,patternsConsolidated:s,newInsights:r,strategyUpdates:0,crossDomainPatterns:c.length,dreamInsights:0,dreamPatternsCreated:0,experiencesProcessed:0,patternCandidatesFound:0,patternsPromoted:0,patternsDeprecated:0,confidenceDecayApplied:0,experiencesMerged:0,experiencesArchived:0,patternsMined:0,domainsMined:0,dreamInsightsPruned:0}}async runDreamCycle(e,t,n,s){if(t.length<10)return e.logger.debug("Skipping dream cycle - insufficient patterns",{patternCount:t.length,required:10}),{insights:0,patternsCreated:0};let r=null;try{r=new j,await r.initialize();let i=t.map(c=>({id:c.id,name:c.pattern,description:`${c.type} pattern from ${c.domain} (effectiveness: ${c.effectiveness})`,domain:c.domain,patternType:c.type,confidence:c.confidence,successRate:c.effectiveness}));await r.loadPatternsAsConcepts(i),e.logger.debug("Starting dream cycle",{patternCount:t.length});let o=await r.dream(),a=o.insights.filter(c=>c.actionable&&c.confidenceScore>.7);return a.length>0&&(n.push({type:"dream-insights",severity:"info",domain:"learning-optimization",title:"Dream Cycle Insights Generated",description:`${a.length} actionable insights discovered through pattern association`,context:{totalInsights:o.insights.length,actionableInsights:a.length,topInsight:a[0]?.description,activationIterations:o.activationStats.totalIterations}}),s.push({priority:"p2",domain:"learning-optimization",action:"Apply Dream Insights",description:`${a.length} insights from dream cycle can improve pattern effectiveness`,estimatedImpact:"medium",effort:"low",autoFixable:!0})),await e.memory.set("learning:dreamInsights",{cycleId:o.cycle.id,insights:a,timestamp:new Date().toISOString()}),e.logger.info("Dream cycle completed",{insights:o.insights.length,actionable:a.length,duration:o.cycle.durationMs}),{insights:o.insights.length,patternsCreated:o.patternsCreated}}catch(i){return e.logger.warn("Dream cycle failed",{error:b(i)}),{insights:0,patternsCreated:0}}finally{r&&await r.close()}}findCrossDomainPatterns(e){let t=new Map;for(let s of e){let r=t.get(s.type)||[];r.push(s),t.set(s.type,r)}let n=[];for(let[s,r]of Array.from(t.entries())){let i=Array.from(new Set(r.map(o=>o.domain)));i.length>=3&&n.push({pattern:s,domains:i,avgEffectiveness:r.reduce((o,a)=>o+a.effectiveness,0)/r.length})}return n}identifyCrossDomainPatterns(e,t,n){let s=this.findCrossDomainPatterns(e);s.length>0&&(t.push({type:"cross-domain-patterns",severity:"info",domain:"learning-optimization",title:"Cross-Domain Patterns Identified",description:`${s.length} patterns are effective across multiple domains`,context:{patterns:s.map(r=>({type:r.pattern,domains:r.domains.length,effectiveness:r.avgEffectiveness.toFixed(2)}))}}),n.push({priority:"p2",domain:"learning-optimization",action:"Leverage Cross-Domain Patterns",description:"Apply successful cross-domain patterns to domains where they are not yet used.",estimatedImpact:"medium",effort:"low",autoFixable:!0}))}pruneIneffectivePatterns(e,t,n){let s=e.filter(i=>i.effectiveness<.3&&i.occurrences>10),r=e.filter(i=>(Date.now()-i.lastSeen.getTime())/864e5>30);s.length>0&&(t.push({type:"ineffective-patterns",severity:"low",domain:"learning-optimization",title:"Ineffective Patterns Detected",description:`${s.length} patterns have low effectiveness despite many occurrences`,context:{count:s.length,domains:Array.from(new Set(s.map(i=>i.domain)))}}),n.push({priority:"p3",domain:"learning-optimization",action:"Review Ineffective Patterns",description:"Consider removing or refining patterns that consistently underperform.",estimatedImpact:"low",effort:"low",autoFixable:!0})),r.length>0&&t.push({type:"stale-patterns",severity:"info",domain:"learning-optimization",title:"Stale Patterns Identified",description:`${r.length} patterns have not been seen in over 30 days`,context:{count:r.length}})}generateOptimizations(e,t,n){let s=new Map;for(let o of e)s.set(o.domain,(s.get(o.domain)||0)+1);let r=w.filter(o=>(s.get(o)||0)<3);r.length>0&&(t.push({type:"learning-gaps",severity:"medium",domain:"learning-optimization",title:"Learning Gaps Identified",description:`${r.length} domains have few learned patterns`,context:{domains:r}}),n.push({priority:"p2",domain:"learning-optimization",action:"Improve Learning Coverage",description:`Focus learning efforts on domains with few patterns: ${r.join(", ")}`,estimatedImpact:"medium",effort:"medium",autoFixable:!1}));let i=e.filter(o=>o.effectiveness>.9&&o.occurrences>20).sort((o,a)=>a.effectiveness-o.effectiveness).slice(0,5);i.length>0&&t.push({type:"top-patterns",severity:"info",domain:"learning-optimization",title:"Top Performing Patterns",description:`${i.length} patterns show exceptional effectiveness`,context:{patterns:i.map(o=>({domain:o.domain,type:o.type,effectiveness:o.effectiveness.toFixed(2)}))}})}calculateHealthScore(e,t){if(t.length===0)return 50;let s=t.reduce((i,o)=>i+o.effectiveness,0)/t.length*50;s+=Math.min(20,e.newInsights*4),s+=Math.min(15,e.crossDomainPatterns*3),s+=Math.min(10,e.dreamInsights*2);let r=e.patternsPruned/e.patternsAnalyzed;return s-=r*15,Math.max(0,Math.min(100,Math.round(s)))}};var le={id:"defect-predictor",name:"Defect Predictor",description:"Uses ML patterns to predict potential defects and identify high-risk code areas",intervalMs:900*1e3,priority:"high",targetDomains:["defect-intelligence"],enabled:!0,timeoutMs:18e4,retryCount:2,retryDelayMs:15e3},I=class extends y{constructor(){super(le)}async doExecute(e){let t=Date.now();e.logger.info("Starting defect prediction analysis");let n=[],s=[],r=await this.analyzeCodeForDefects(e),i=await this.identifyHotspots(e);this.analyzeHighRiskPredictions(r,n,s),this.analyzeHotspots(i,n,s),await e.memory.set("defect:predictions",r),await e.memory.set("defect:hotspots",i),await e.memory.set("defect:lastAnalysis",new Date().toISOString());let o=this.calculateHealthScore(r,i);return e.logger.info("Defect prediction complete",{healthScore:o,predictionsCount:r.length,hotspotsCount:i.length}),this.createResult(Date.now()-t,{itemsAnalyzed:r.length,issuesFound:r.filter(a=>a.probability>.5).length,healthScore:o,trend:"stable",domainMetrics:{filesAnalyzed:r.length,highRiskFiles:r.filter(a=>a.riskLevel==="high"||a.riskLevel==="critical").length,hotspots:i.length,avgDefectProbability:(r.reduce((a,c)=>a+c.probability,0)/r.length).toFixed(2)}},n,s)}async analyzeCodeForDefects(e){return[{file:"src/coordination/workflow-orchestrator.ts",probability:.78,riskLevel:"high",factors:[{name:"complexity",weight:.3,description:"High cyclomatic complexity (28)"},{name:"change-frequency",weight:.25,description:"Changed 15 times in last 30 days"},{name:"size",weight:.2,description:"Large file (1500+ lines)"},{name:"coupling",weight:.15,description:"High coupling with 8 other modules"}],recentChanges:15,historicalDefects:3,complexity:28},{file:"src/domains/security-compliance/services/security-scanner.ts",probability:.65,riskLevel:"high",factors:[{name:"complexity",weight:.35,description:"High cyclomatic complexity (32)"},{name:"size",weight:.25,description:"Very large file (1200+ lines)"},{name:"test-coverage",weight:.2,description:"Low test coverage (45%)"}],recentChanges:8,historicalDefects:2,complexity:32},{file:"src/kernel/memory-backend.ts",probability:.45,riskLevel:"medium",factors:[{name:"change-frequency",weight:.4,description:"Changed 10 times in last 30 days"},{name:"authors",weight:.3,description:"Multiple authors (4)"}],recentChanges:10,historicalDefects:1,complexity:15},{file:"src/shared/http/http-client.ts",probability:.25,riskLevel:"low",factors:[{name:"stability",weight:.5,description:"Stable code, few recent changes"}],recentChanges:2,historicalDefects:0,complexity:8}]}async identifyHotspots(e){return[{file:"src/coordination/workflow-orchestrator.ts",changeFrequency:15,defectDensity:.02,authors:4,lastModified:new Date(Date.now()-2880*60*1e3),score:.85},{file:"src/domains/test-generation/services/test-generator.ts",changeFrequency:12,defectDensity:.015,authors:3,lastModified:new Date(Date.now()-7200*60*1e3),score:.72},{file:"src/mcp/server.ts",changeFrequency:8,defectDensity:.01,authors:2,lastModified:new Date(Date.now()-4320*60*1e3),score:.55}]}analyzeHighRiskPredictions(e,t,n){let s=e.filter(i=>i.riskLevel==="critical"),r=e.filter(i=>i.riskLevel==="high");for(let i of s)t.push({type:"critical-defect-risk",severity:"critical",domain:"defect-intelligence",title:`Critical Defect Risk: ${i.file.split("/").pop()}`,description:`${(i.probability*100).toFixed(0)}% probability of defect based on code analysis`,resource:i.file,context:{probability:i.probability,factors:i.factors,recentChanges:i.recentChanges,historicalDefects:i.historicalDefects}});for(let i of r)t.push({type:"high-defect-risk",severity:"high",domain:"defect-intelligence",title:`High Defect Risk: ${i.file.split("/").pop()}`,description:`${(i.probability*100).toFixed(0)}% probability of defect`,resource:i.file,context:{probability:i.probability,topFactors:i.factors.slice(0,3),complexity:i.complexity}});if(s.length>0||r.length>0){n.push({priority:"p0",domain:"defect-intelligence",action:"Prioritize Code Review for High-Risk Files",description:`${s.length+r.length} files have elevated defect risk. Schedule focused code reviews.`,estimatedImpact:"high",effort:"medium",autoFixable:!1});let i=e.filter(a=>a.factors.some(c=>c.name==="complexity"&&c.weight>.25));i.length>0&&n.push({priority:"p1",domain:"defect-intelligence",action:"Reduce Code Complexity",description:`${i.length} files have high complexity as a defect risk factor. Consider refactoring.`,estimatedImpact:"high",effort:"high",autoFixable:!1});let o=e.filter(a=>a.factors.some(c=>c.name==="test-coverage"));o.length>0&&n.push({priority:"p1",domain:"defect-intelligence",action:"Improve Test Coverage for Risky Files",description:`${o.length} high-risk files have low test coverage. Add targeted tests.`,estimatedImpact:"high",effort:"medium",autoFixable:!0})}}analyzeHotspots(e,t,n){let s=e.filter(i=>i.score>.7);s.length>0&&(t.push({type:"code-hotspots",severity:"medium",domain:"defect-intelligence",title:`${s.length} Code Hotspots Detected`,description:"Files with high change frequency and defect density identified",context:{hotspots:s.map(i=>({file:i.file,changeFrequency:i.changeFrequency,score:i.score.toFixed(2)}))}}),n.push({priority:"p2",domain:"defect-intelligence",action:"Address Code Hotspots",description:"Consider refactoring frequently-changed, defect-prone files to improve stability.",estimatedImpact:"medium",effort:"high",autoFixable:!1}));let r=e.filter(i=>i.authors===1&&i.changeFrequency>5);r.length>0&&(t.push({type:"knowledge-silo",severity:"medium",domain:"defect-intelligence",title:"Knowledge Silos Detected",description:`${r.length} frequently-changed files have only one author`,context:{files:r.map(i=>i.file)}}),n.push({priority:"p2",domain:"defect-intelligence",action:"Address Knowledge Silos",description:"Ensure knowledge sharing for files maintained by single developers.",estimatedImpact:"medium",effort:"low",autoFixable:!1}))}calculateHealthScore(e,t){if(e.length===0)return 100;let s=(1-e.reduce((a,c)=>a+c.probability,0)/e.length)*60,r=e.filter(a=>a.riskLevel==="critical"||a.riskLevel==="high").length;s-=r/e.length*20;let i=t.filter(a=>a.score>.7).length;s-=i*3;let o=e.filter(a=>a.riskLevel==="low").length/e.length;return s+=o*20,Math.max(0,Math.min(100,Math.round(s)))}};var ue={id:"regression-monitor",name:"Regression Monitor",description:"Monitors for regressions in test results, performance, coverage, and quality metrics",intervalMs:600*1e3,priority:"high",targetDomains:["test-execution","coverage-analysis","quality-assessment"],enabled:!0,timeoutMs:12e4,retryCount:2,retryDelayMs:1e4},A=class extends y{constructor(){super(ue)}async doExecute(e){let t=Date.now();e.logger.info("Starting regression monitoring");let n=[],s=[],r=await this.collectCurrentSnapshot(e),i=await e.memory.get("regression:baseline"),o=[];i&&(o=this.detectRegressions(i,r),this.analyzeRegressions(o,n,s)),await e.memory.set("regression:baseline",r);let a=await e.memory.get("regression:history")||[];if(o.length>0){for(a.push(...o);a.length>100;)a.shift();await e.memory.set("regression:history",a)}let c=this.calculateHealthScore(o);return e.logger.info("Regression monitoring complete",{healthScore:c,regressionsDetected:o.length}),this.createResult(Date.now()-t,{itemsAnalyzed:5,issuesFound:o.length,healthScore:c,trend:o.length>0?"degrading":"stable",domainMetrics:{testPassRate:`${r.testPassRate}%`,lineCoverage:`${r.coverage.line}%`,avgTestDuration:`${r.avgTestDuration}ms`,qualityScore:r.qualityScore,regressionsDetected:o.length}},n,s)}async collectCurrentSnapshot(e){return{timestamp:new Date,testPassRate:98.2,coverage:{line:78.5,branch:65.2},avgTestDuration:245,failedTests:["test-execution/retry-handler.test.ts::should retry failed tests","coordination/workflow.test.ts::should handle concurrent workflows"],qualityScore:82}}detectRegressions(e,t){let n=[];if(t.testPassRate<e.testPassRate-1){let i=t.testPassRate-e.testPassRate;n.push({type:"test",metric:"testPassRate",previousValue:e.testPassRate,currentValue:t.testPassRate,changePercent:i,severity:i<-5?"critical":i<-2?"high":"medium",affectedTests:t.failedTests})}if(t.coverage.line<e.coverage.line-2){let i=t.coverage.line-e.coverage.line;n.push({type:"coverage",metric:"lineCoverage",previousValue:e.coverage.line,currentValue:t.coverage.line,changePercent:i,severity:i<-5?"high":"medium"})}if(t.coverage.branch<e.coverage.branch-3){let i=t.coverage.branch-e.coverage.branch;n.push({type:"coverage",metric:"branchCoverage",previousValue:e.coverage.branch,currentValue:t.coverage.branch,changePercent:i,severity:i<-5?"high":"medium"})}let s=(t.avgTestDuration-e.avgTestDuration)/e.avgTestDuration*100;if(s>20&&n.push({type:"performance",metric:"avgTestDuration",previousValue:e.avgTestDuration,currentValue:t.avgTestDuration,changePercent:s,severity:s>50?"high":"medium"}),t.qualityScore<e.qualityScore-5){let i=t.qualityScore-e.qualityScore;n.push({type:"quality",metric:"qualityScore",previousValue:e.qualityScore,currentValue:t.qualityScore,changePercent:i,severity:i<-10?"critical":i<-5?"high":"medium"})}let r=t.failedTests.filter(i=>!e.failedTests.includes(i));return r.length>0&&n.push({type:"test",metric:"newFailures",previousValue:0,currentValue:r.length,changePercent:100,severity:r.length>5?"critical":r.length>2?"high":"medium",affectedTests:r}),n}analyzeRegressions(e,t,n){for(let o of e){let a=this.getDomainForType(o.type);t.push({type:`${o.type}-regression`,severity:o.severity,domain:a,title:`${this.formatMetricName(o.metric)} Regression Detected`,description:this.formatRegressionDescription(o),context:{previousValue:o.previousValue,currentValue:o.currentValue,changePercent:o.changePercent.toFixed(2),affectedTests:o.affectedTests}})}let s=e.filter(o=>o.type==="test");if(s.length>0){let o=s.filter(a=>a.severity==="critical"||a.severity==="high");o.length>0&&n.push({priority:"p0",domain:"test-execution",action:"Investigate Test Regressions Immediately",description:`${o.length} significant test regressions detected. Review recent changes.`,estimatedImpact:"high",effort:"medium",autoFixable:!1})}e.filter(o=>o.type==="coverage").length>0&&n.push({priority:"p1",domain:"coverage-analysis",action:"Address Coverage Regression",description:"Code coverage has decreased. Add tests for new/changed code.",estimatedImpact:"medium",effort:"medium",autoFixable:!0}),e.filter(o=>o.type==="performance").length>0&&n.push({priority:"p2",domain:"test-execution",action:"Investigate Performance Regression",description:"Test execution has slowed. Review for new slow tests or infrastructure issues.",estimatedImpact:"medium",effort:"low",autoFixable:!1})}getDomainForType(e){switch(e){case"test":case"performance":return"test-execution";case"coverage":return"coverage-analysis";case"quality":return"quality-assessment";default:return"quality-assessment"}}formatMetricName(e){return{testPassRate:"Test Pass Rate",lineCoverage:"Line Coverage",branchCoverage:"Branch Coverage",avgTestDuration:"Test Duration",qualityScore:"Quality Score",newFailures:"New Test Failures"}[e]||e}formatRegressionDescription(e){if(e.metric==="newFailures")return`${e.currentValue} new test failures detected since last check`;let t=e.changePercent>0?"increased":"decreased",n=e.type==="performance"?"ms":"%";return`${this.formatMetricName(e.metric)} ${t} from ${e.previousValue}${n} to ${e.currentValue}${n} (${e.changePercent>0?"+":""}${e.changePercent.toFixed(1)}%)`}calculateHealthScore(e){if(e.length===0)return 100;let t=100;for(let n of e)switch(n.severity){case"critical":t-=25;break;case"high":t-=15;break;case"medium":t-=8;break;case"low":t-=3;break}return Math.max(0,Math.round(t))}};var de={id:"performance-baseline",name:"Performance Baseline Tracker",description:"Tracks performance trends and establishes baselines for test execution and builds",intervalMs:3600*1e3,priority:"normal",targetDomains:["test-execution","chaos-resilience"],enabled:!0,timeoutMs:3e5,retryCount:2,retryDelayMs:3e4},E=class extends y{constructor(){super(de)}async doExecute(e){let t=Date.now();e.logger.info("Starting performance baseline tracking");let n=[],s=[],r=await this.collectPerformanceMetrics(e),i=await this.getOrCalculateBaseline(e),o=this.detectAnomalies(r,i);this.analyzeAnomalies(o,n,s),await this.updateBaseline(e,r,i),await this.storeMetricsHistory(e,r);let a=this.calculateHealthScore(o);return e.logger.info("Performance baseline tracking complete",{healthScore:a,anomaliesDetected:o.length}),this.createResult(Date.now()-t,{itemsAnalyzed:10,issuesFound:o.length,healthScore:a,trend:o.length>2?"degrading":"stable",domainMetrics:{avgTestDuration:`${r.testExecution.avgTestDurationMs}ms`,p95TestDuration:`${r.testExecution.p95DurationMs}ms`,compileDuration:`${r.build.compileDurationMs}ms`,bundleSize:`${r.build.bundleSizeKb}KB`,peakMemory:`${r.resources.peakMemoryMb}MB`,anomalies:o.length}},n,s)}async collectPerformanceMetrics(e){return{timestamp:new Date,testExecution:{totalDurationMs:45e3,avgTestDurationMs:245,slowestTestMs:3500,slowestTestName:"workflow-orchestrator.test.ts::complex scenario",p50DurationMs:120,p95DurationMs:800,p99DurationMs:2500},build:{compileDurationMs:12e3,bundleSizeKb:2500,dependencyCount:45},resources:{peakMemoryMb:512,avgCpuPercent:65,diskReadMb:150,diskWriteMb:50}}}async getOrCalculateBaseline(e){let t=await e.memory.get("performance:baseline");return t||{testExecution:{avgDurationMs:200,p95DurationMs:700,threshold:1.3},build:{avgCompileMs:1e4,avgBundleSizeKb:2400,threshold:1.2},resources:{avgMemoryMb:450,avgCpuPercent:60,threshold:1.25}}}detectAnomalies(e,t){let n=[],s=e.testExecution.avgTestDurationMs/t.testExecution.avgDurationMs;s>t.testExecution.threshold&&n.push({metric:"avgTestDuration",category:"test",currentValue:e.testExecution.avgTestDurationMs,baselineValue:t.testExecution.avgDurationMs,deviationPercent:(s-1)*100,severity:s>1.5?"high":"medium"});let r=e.testExecution.p95DurationMs/t.testExecution.p95DurationMs;r>t.testExecution.threshold&&n.push({metric:"p95TestDuration",category:"test",currentValue:e.testExecution.p95DurationMs,baselineValue:t.testExecution.p95DurationMs,deviationPercent:(r-1)*100,severity:r>1.5?"high":"medium"});let i=e.build.compileDurationMs/t.build.avgCompileMs;i>t.build.threshold&&n.push({metric:"compileDuration",category:"build",currentValue:e.build.compileDurationMs,baselineValue:t.build.avgCompileMs,deviationPercent:(i-1)*100,severity:i>1.5?"high":"medium"});let o=e.build.bundleSizeKb/t.build.avgBundleSizeKb;o>t.build.threshold&&n.push({metric:"bundleSize",category:"build",currentValue:e.build.bundleSizeKb,baselineValue:t.build.avgBundleSizeKb,deviationPercent:(o-1)*100,severity:o>1.3?"high":"medium"});let a=e.resources.peakMemoryMb/t.resources.avgMemoryMb;a>t.resources.threshold&&n.push({metric:"peakMemory",category:"resource",currentValue:e.resources.peakMemoryMb,baselineValue:t.resources.avgMemoryMb,deviationPercent:(a-1)*100,severity:a>1.5?"critical":a>1.3?"high":"medium"});let c=e.resources.avgCpuPercent/t.resources.avgCpuPercent;return c>t.resources.threshold&&n.push({metric:"avgCpu",category:"resource",currentValue:e.resources.avgCpuPercent,baselineValue:t.resources.avgCpuPercent,deviationPercent:(c-1)*100,severity:c>1.4?"high":"medium"}),n}analyzeAnomalies(e,t,n){for(let o of e){let a=o.category==="test"?"test-execution":"chaos-resilience";t.push({type:`performance-anomaly-${o.category}`,severity:o.severity,domain:a,title:`Performance Anomaly: ${this.formatMetricName(o.metric)}`,description:`${this.formatMetricName(o.metric)} is ${o.deviationPercent.toFixed(1)}% above baseline`,context:{currentValue:o.currentValue,baselineValue:o.baselineValue,deviationPercent:o.deviationPercent.toFixed(1)}})}let s=e.filter(o=>o.category==="test");s.length>0&&n.push({priority:s.some(o=>o.severity==="high")?"p1":"p2",domain:"test-execution",action:"Investigate Test Performance Degradation",description:"Test execution times have increased. Review for slow tests or infrastructure issues.",estimatedImpact:"medium",effort:"medium",autoFixable:!1});let r=e.filter(o=>o.category==="build");r.length>0&&r.find(a=>a.metric==="bundleSize")&&n.push({priority:"p2",domain:"chaos-resilience",action:"Analyze Bundle Size Increase",description:"Bundle size has grown. Review for unnecessary dependencies or unoptimized imports.",estimatedImpact:"medium",effort:"low",autoFixable:!0});let i=e.filter(o=>o.category==="resource");if(i.length>0){let o=i.find(a=>a.metric==="peakMemory");o&&o.severity==="critical"&&n.push({priority:"p0",domain:"chaos-resilience",action:"Investigate Memory Usage Spike",description:"Memory usage is significantly above baseline. Check for memory leaks.",estimatedImpact:"high",effort:"high",autoFixable:!1})}}formatMetricName(e){return{avgTestDuration:"Average Test Duration",p95TestDuration:"P95 Test Duration",compileDuration:"Compile Duration",bundleSize:"Bundle Size",peakMemory:"Peak Memory Usage",avgCpu:"Average CPU Usage"}[e]||e}async updateBaseline(e,t,n){let r={testExecution:{avgDurationMs:n.testExecution.avgDurationMs*.9+t.testExecution.avgTestDurationMs*.1,p95DurationMs:n.testExecution.p95DurationMs*.9+t.testExecution.p95DurationMs*.1,threshold:n.testExecution.threshold},build:{avgCompileMs:n.build.avgCompileMs*.9+t.build.compileDurationMs*.1,avgBundleSizeKb:n.build.avgBundleSizeKb*.9+t.build.bundleSizeKb*.1,threshold:n.build.threshold},resources:{avgMemoryMb:n.resources.avgMemoryMb*.9+t.resources.peakMemoryMb*.1,avgCpuPercent:n.resources.avgCpuPercent*.9+t.resources.avgCpuPercent*.1,threshold:n.resources.threshold}};await e.memory.set("performance:baseline",r)}async storeMetricsHistory(e,t){let n=await e.memory.get("performance:history")||[];for(n.push(t);n.length>168;)n.shift();await e.memory.set("performance:history",n)}calculateHealthScore(e){if(e.length===0)return 100;let t=100;for(let n of e){let s={critical:25,high:15,medium:8,low:3}[n.severity],r=Math.min(10,n.deviationPercent/10);t-=s+r}return Math.max(0,Math.round(t))}};var me={id:"compliance-checker",name:"ADR/DDD Compliance Checker",description:"Verifies compliance with Architecture Decision Records and DDD patterns",intervalMs:1800*1e3,priority:"normal",targetDomains:["quality-assessment"],enabled:!0,timeoutMs:24e4,retryCount:2,retryDelayMs:3e4},$=class extends y{constructor(){super(me)}async doExecute(e){let t=Date.now();e.logger.info("Starting compliance checking");let n=[],s=[],r=await this.checkADRCompliance(e),i=await this.checkDDDCompliance(e),o=await this.checkStructuralCompliance(e);this.analyzeADRCompliance(r,n,s),this.analyzeDDDCompliance(i,n,s),this.analyzeStructuralCompliance(o,n,s),await e.memory.set("compliance:adr",r),await e.memory.set("compliance:ddd",i),await e.memory.set("compliance:structural",o),await e.memory.set("compliance:lastCheck",new Date().toISOString());let a=this.calculateHealthScore(r,i,o);return e.logger.info("Compliance checking complete",{healthScore:a,adrChecks:r.length,domainChecks:i.length}),this.createResult(Date.now()-t,{itemsAnalyzed:r.length+i.length+o.length,issuesFound:n.length,healthScore:a,trend:"stable",domainMetrics:{adrCompliance:`${this.calculateAvgScore(r)}%`,dddCompliance:`${this.calculateDDDAvgScore(i)}%`,structuralCompliance:`${this.calculateStructuralScore(o)}%`,totalViolations:r.reduce((c,l)=>c+l.violations.length,0)+i.reduce((c,l)=>c+l.violations.length,0)}},n,s)}async checkADRCompliance(e){if(!e.domains.getDomainAPI("quality-assessment"))throw new Error("Quality-assessment domain not available - cannot check ADR compliance. Ensure the quality-assessment domain is properly initialized before running this worker.");let n=await e.memory.search("compliance:adr:*");if(n.length===0)throw new Error('No ADR compliance data found in memory - cannot check ADR compliance. Ensure ADR compliance data is stored with keys matching "compliance:adr:*" before running this worker.');let s=[],r=[];for(let i of n)try{let o=await e.memory.get(i);o&&s.push(o)}catch{r.push(i)}if(s.length===0)throw new Error(`Found ${n.length} ADR compliance keys but failed to retrieve any data. Failed keys: ${r.join(", ")}. Check memory service connectivity.`);return s}async checkDDDCompliance(e){let t=[];for(let n of w)try{let s=await this.checkDomainCompliance(e,n);t.push(s)}catch(s){e.logger.warn(`Failed to check DDD compliance for ${n}`,{error:s})}return t}async checkDomainCompliance(e,t){let n=e.domains.getDomainHealth(t),s=e.domains.getDomainAPI(t),r=n.status!=="unhealthy",i=s!==void 0,o=i,a=i,c=await e.memory.get(`compliance:ddd:${t}`),l=c?.hasEntities??!1,m=c?.hasEvents??!1,d=c?.hasRepositories??!1,f=c?.namingCompliant??i,p=[];l||p.push("Missing domain entities"),m||p.push("Missing domain events"),d||p.push("Missing repositories"),r||p.push("Domain coordinator not available"),i||p.push("Domain plugin not loaded");let g=[r,i,o,a,l,m,d,f],u=Math.round(g.filter(Boolean).length/g.length*100);return{domain:t,hasCoordinator:r,hasPlugin:i,hasInterfaces:o,hasServices:a,hasEntities:l,hasEvents:m,hasRepositories:d,namingCompliant:f,score:u,violations:p}}async checkStructuralCompliance(e){let t=await e.memory.search("compliance:structural:*");if(t.length===0)throw new Error('No structural compliance data found in memory - cannot check structural compliance. Ensure structural compliance data is stored with keys matching "compliance:structural:*" before running this worker.');let n=[],s=[];for(let r of t)try{let i=await e.memory.get(r);i&&n.push(i)}catch(i){s.push(r),e.logger.warn(`Failed to retrieve structural compliance data: ${r}`,{error:i})}if(n.length===0)throw new Error(`Found ${t.length} structural compliance keys but failed to retrieve any data. Failed keys: ${s.join(", ")}. Check memory service connectivity.`);return n}analyzeADRCompliance(e,t,n){let s=e.filter(i=>i.status==="non-compliant"),r=e.filter(i=>i.status==="partial");for(let i of s)t.push({type:"adr-non-compliance",severity:"high",domain:"quality-assessment",title:`ADR Non-Compliance: ${i.adrId}`,description:`${i.title} is not compliant (score: ${i.score}%)`,context:{adrId:i.adrId,violations:i.violations}});for(let i of r)t.push({type:"adr-partial-compliance",severity:"medium",domain:"quality-assessment",title:`ADR Partial Compliance: ${i.adrId}`,description:`${i.title} is partially compliant (score: ${i.score}%)`,context:{adrId:i.adrId,violations:i.violations}});s.length>0&&n.push({priority:"p1",domain:"quality-assessment",action:"Address ADR Non-Compliance",description:`${s.length} ADRs are not being followed. Review and implement required patterns.`,estimatedImpact:"high",effort:"high",autoFixable:!1})}analyzeDDDCompliance(e,t,n){let s=e.filter(o=>o.score<70),r=e.filter(o=>!o.hasEntities),i=e.filter(o=>!o.hasEvents);s.length>0&&t.push({type:"ddd-low-compliance",severity:"medium",domain:"quality-assessment",title:`${s.length} Domains Have Low DDD Compliance`,description:"Some domains are missing required DDD components",context:{domains:s.map(o=>({domain:o.domain,score:o.score}))}}),r.length>0&&(t.push({type:"ddd-missing-entities",severity:"low",domain:"quality-assessment",title:"Domains Missing Entity Definitions",description:`${r.length} domains lack proper entity definitions`,context:{domains:r.map(o=>o.domain)}}),n.push({priority:"p3",domain:"quality-assessment",action:"Add Domain Entities",description:"Define rich domain entities for domains that currently lack them.",estimatedImpact:"medium",effort:"medium",autoFixable:!1})),i.length>0&&n.push({priority:"p3",domain:"quality-assessment",action:"Implement Domain Events",description:`${i.length} domains are missing domain event definitions.`,estimatedImpact:"medium",effort:"medium",autoFixable:!1})}analyzeStructuralCompliance(e,t,n){let s=e.filter(r=>!r.compliant);for(let r of s)t.push({type:"structural-violation",severity:"medium",domain:"quality-assessment",title:`Structural Violation: ${r.category}`,description:`Rule "${r.rule}" is not being followed: ${r.details}`,context:{category:r.category,rule:r.rule}});s.length>0&&n.push({priority:"p2",domain:"quality-assessment",action:"Fix Structural Violations",description:`${s.length} structural rules are being violated. Review architecture guidelines.`,estimatedImpact:"medium",effort:"medium",autoFixable:!1})}calculateAvgScore(e){return e.length===0?100:Math.round(e.reduce((t,n)=>t+n.score,0)/e.length)}calculateDDDAvgScore(e){return e.length===0?100:Math.round(e.reduce((t,n)=>t+n.score,0)/e.length)}calculateStructuralScore(e){if(e.length===0)return 100;let t=e.filter(n=>n.compliant).length;return Math.round(t/e.length*100)}calculateHealthScore(e,t,n){let s=this.calculateAvgScore(e)*.4,r=this.calculateDDDAvgScore(t)*.4,i=this.calculateStructuralScore(n)*.2;return Math.round(s+r+i)}};V();var Ze={id:"cloud-sync",name:"Cloud Sync",description:"Periodically syncs local learning data to cloud PostgreSQL",intervalMs:parseInt(process.env.AQE_SYNC_INTERVAL||"3600000",10),priority:"low",targetDomains:["learning-optimization"],enabled:process.env.AQE_CLOUD_SYNC_ENABLED==="true",timeoutMs:6e5,retryCount:3,retryDelayMs:6e4};var pe={autoStart:!0,enabledWorkers:[],logLevel:"info",healthCheckIntervalMs:6e4},K=class{_running=!1;_startedAt;_healthCheckTimer;workerManager;config;_qualityDaemon;constructor(e){this.config={...pe,...e},this.workerManager=new N,this.registerWorkers()}get running(){return this._running}get uptime(){return this._startedAt?Math.floor((Date.now()-this._startedAt.getTime())/1e3):0}async start(){if(this._running){console.info("[Daemon] Already running");return}console.info("[Daemon] Starting QE Background Workers..."),this._running=!0,this._startedAt=new Date,this._healthCheckTimer=setInterval(()=>{this.performHealthCheck()},this.config.healthCheckIntervalMs),this.config.autoStart&&(await this.workerManager.startAll(),console.info("[Daemon] All workers started"));let e=this.workerManager.list();console.info(`[Daemon] Registered ${e.length} workers:`);for(let t of e)console.info(` - ${t.config.id}: ${t.config.name} (interval: ${t.config.intervalMs}ms)`)}async stop(){if(!this._running){console.info("[Daemon] Not running");return}console.info("[Daemon] Stopping..."),this._healthCheckTimer&&(clearInterval(this._healthCheckTimer),this._healthCheckTimer=void 0),await this.workerManager.stopAll(),this._running=!1,console.info("[Daemon] Stopped")}async restart(){console.info("[Daemon] Restarting..."),await this.stop(),await this.start(),console.info("[Daemon] Restarted")}getStatus(){return{running:this._running,pid:process.pid,uptime:this.uptime,startedAt:this._startedAt,workerManager:this.workerManager.getHealth()}}getWorkerManager(){return this.workerManager}getQualityDaemon(e){return this._qualityDaemon||(this._qualityDaemon=new Z(e)),this._qualityDaemon}async runWorker(e){let t=await this.workerManager.runNow(e);console.info(`[Daemon] Worker ${e} completed:`,{success:t.success,duration:`${t.durationMs}ms`,findings:t.findings.length,healthScore:t.metrics.healthScore})}registerWorkers(){let e=[new M,new x,new P,new S,new W,new F,new I,new A,new E,new $,new B];for(let t of e)(this.config.enabledWorkers.length===0||this.config.enabledWorkers.includes(t.config.id))&&this.workerManager.register(t)}performHealthCheck(){let e=this.workerManager.getHealth();e.errorWorkers>0&&console.warn(`[Daemon] Health check: ${e.errorWorkers} workers in error state`),e.healthScore<70&&console.warn(`[Daemon] Health score degraded: ${e.healthScore}%`),this.config.logLevel==="debug"&&console.debug("[Daemon] Health check:",e)}};function ge(h){return new K(h)}var C;function vt(h){return C||(C=ge(h)),C}function kt(){C?.running&&C.stop().catch(console.error),C=void 0}export{K as QEDaemon,ge as createDaemon,vt as getDaemon,kt as resetDaemon};
|
|
@@ -1,12 +1,12 @@
|
|
|
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.
|
|
2
|
-
import{a as u,b as d}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.10.0");process.exit(0)}
|
|
2
|
+
import{a as u,b as d}from"./chunk-Z6JLPPAY.js";import{a as m}from"./chunk-WG6I7YF3.js";import"./chunk-55JPAF56.js";import{Command as h}from"commander";import e from"chalk";var t;function Q(){let n=new h("daemon").description("Manage the QE Quality Daemon").addHelpText("after",`
|
|
3
3
|
Examples:
|
|
4
4
|
aqe daemon start Start daemon in foreground
|
|
5
5
|
aqe daemon stop Stop running daemon
|
|
6
6
|
aqe daemon status Show daemon health and queue depth
|
|
7
7
|
aqe daemon notifications List recent notifications
|
|
8
8
|
aqe daemon clear-notifications Clear all notifications
|
|
9
|
-
`);return n.command("start").description("Start the QE Quality Daemon").option("--tick-interval <ms>","Tick interval in milliseconds","30000").option("--ci-interval <ms>","CI poll interval in milliseconds","300000").action(async o=>{if(t?.running){console.log(e.yellow("Daemon is already running"));let i=t.getStatus();console.log(e.gray(` Uptime: ${i.uptimeSeconds}s, Ticks: ${i.tickCount}`));return}let r={tickIntervalMs:parseInt(o.tickInterval,10),ciPollIntervalMs:parseInt(o.ciInterval,10),notifications:{urlValidator:i=>{try{let s=new URL(i).hostname.replace(/^\[|\]$/g,"");return!m(s)}catch{return!1}}}};t=new d(r);let a;try{let{UnifiedMemoryManager:i}=await import("./unified-memory-
|
|
9
|
+
`);return n.command("start").description("Start the QE Quality Daemon").option("--tick-interval <ms>","Tick interval in milliseconds","30000").option("--ci-interval <ms>","CI poll interval in milliseconds","300000").action(async o=>{if(t?.running){console.log(e.yellow("Daemon is already running"));let i=t.getStatus();console.log(e.gray(` Uptime: ${i.uptimeSeconds}s, Ticks: ${i.tickCount}`));return}let r={tickIntervalMs:parseInt(o.tickInterval,10),ciPollIntervalMs:parseInt(o.ciInterval,10),notifications:{urlValidator:i=>{try{let s=new URL(i).hostname.replace(/^\[|\]$/g,"");return!m(s)}catch{return!1}}}};t=new d(r);let a;try{let{UnifiedMemoryManager:i}=await import("./unified-memory-CMNJVHOJ.js"),l=await i.getInstanceAsync();a=new u(l),console.log(e.gray(" Storage: SQLite (persistent)"))}catch{let i=new Map;a={async get(l){return i.get(l)},async set(l,s){i.set(l,s)},async search(l){let s=l.replace(/[.+?^${}()|[\]\\]/g,"\\$&"),y=new RegExp(s.replace(/\*/g,".*"));return Array.from(i.keys()).filter(f=>y.test(f))}},console.log(e.yellow(" Storage: in-memory (no SQLite available, state will not persist)"))}console.log(e.green("Starting QE Quality Daemon...")),await t.start(a),console.log(e.green("QE Quality Daemon started")),console.log(e.gray(` Tick interval: ${r.tickIntervalMs}ms`)),console.log(e.gray(` CI poll interval: ${r.ciPollIntervalMs}ms`)),console.log(e.gray(` PID: ${process.pid}`)),console.log(e.gray(`
|
|
10
10
|
Press Ctrl+C to stop`));let c=setInterval(()=>{t?.running||clearInterval(c)},5e3),g=async()=>{console.log(e.yellow(`
|
|
11
11
|
Stopping QE Quality Daemon...`)),await t?.stop(),clearInterval(c),console.log(e.green("Daemon stopped")),process.exit(0)};process.once("SIGINT",g),process.once("SIGTERM",g)}),n.command("stop").description("Stop the QE Quality Daemon").action(async()=>{if(!t?.running){console.log(e.yellow("No running daemon found"));return}await t.stop(),console.log(e.green("Daemon stopped")),t=void 0}),n.command("status").description("Show daemon health and queue status").action(()=>{if(!t){console.log(e.yellow("No daemon instance (start with: aqe daemon start)"));return}let o=t.getStatus();console.log(e.bold(`
|
|
12
12
|
QE Quality Daemon Status`)),console.log(e.gray("\u2500".repeat(40))),console.log(` Running: ${o.running?e.green("yes"):e.red("no")}`),console.log(` Uptime: ${$(o.uptimeSeconds)}`),console.log(` Ticks: ${o.tickCount}`),console.log(` Throttled: ${o.throttled?e.yellow("yes"):e.green("no")}`),console.log(e.bold(`
|
package/dist/cli/chunks/{dag-attention-scheduler-GUPZT7PR.js → dag-attention-scheduler-GOZAVAZQ.js}
RENAMED
|
@@ -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.
|
|
2
|
-
import{a,b}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.10.0");process.exit(0)}
|
|
2
|
+
import{a,b}from"./chunk-LRISVDVO.js";import"./chunk-55JPAF56.js";export{a as DAGAttentionScheduler,b as createDAGAttentionScheduler};
|
|
@@ -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.
|
|
2
|
-
import{a,b,c,d}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.10.0");process.exit(0)}
|
|
2
|
+
import{a,b,c,d}from"./chunk-U56TIYGP.js";import"./chunk-OKGK7DBT.js";import"./chunk-55JPAF56.js";export{a as clearDetectionCache,b as detectClaudeFlow,d as getClaudeFlowNotFoundMessage,c as resolveCliPackage};
|
|
@@ -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.
|
|
2
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.0");process.exit(0)}
|
|
2
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n}from"./chunk-MJBXQXSX.js";import"./chunk-55JPAF56.js";export{a as MAX,b as NIL,d as parse,e as stringify,f as v1,g as v1ToV6,h as v3,i as v4,j as v5,k as v6,l as v6ToV1,m as v7,c as validate,n as version};
|
|
@@ -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.
|
|
2
|
-
import{a as i}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.0");process.exit(0)}
|
|
2
|
+
import{a as i}from"./chunk-WVCIZIKH.js";import{a as r}from"./chunk-FEBXP74Y.js";import"./chunk-55JPAF56.js";import n from"chalk";var s=class{name="domain";description="Domain operations";cleanupAndExit;ensureInitialized;constructor(o,t){this.cleanupAndExit=o,this.ensureInitialized=t}register(o,t){let e=o.command("domain").description(this.description);e.command("list").description("List all domains").action(async()=>{await this.executeList(t)}),e.command("health <domain>").description("Get domain health").action(async a=>{await this.executeHealth(a,t)})}async executeList(o){if(await this.ensureInitialized())try{console.log(n.blue(`
|
|
3
3
|
Domains
|
|
4
4
|
`));for(let t of r){let e=o.queen.getDomainHealth(t),a=o.queen.getDomainLoad(t);console.log(` ${n.cyan(t)}`),console.log(` Status: ${i(e?.status||"unknown")}`),console.log(` Load: ${a} tasks`),e&&console.log(` Agents: ${e.agents.active}/${e.agents.total}`),console.log("")}}catch(t){console.error(n.red(`
|
|
5
5
|
Failed to list domains:`),t),await this.cleanupAndExit(1)}}async executeHealth(o,t){if(await this.ensureInitialized())try{let e=t.queen.getDomainHealth(o);if(!e){console.log(n.red(`
|
|
@@ -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.
|
|
2
|
-
import{a,c as b,d as c,e as d,f as e,g as f,h as g,i as h}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.10.0");process.exit(0)}
|
|
2
|
+
import{a,c as b,d as c,e as d,f as e,g as f,h as g,i as h}from"./chunk-KDFW7MVM.js";import"./chunk-X73CRYF4.js";import"./chunk-BQT4J3BD.js";import"./chunk-KOSKGZK4.js";import"./chunk-55JPAF56.js";export{f as CuriosityBonus,b as DEFAULT_DOMAIN_TRANSFER_CONFIG,c as DecayingBeta,g as DomainTransferEngine,e as ParetoFront,d as PlateauDetector,a as ThompsonSampler,h as createDomainTransferEngine};
|
|
@@ -0,0 +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.10.0");process.exit(0)}
|
|
2
|
+
import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i,k as j,l as k,m as l,n as m,o as n,p as o,q as p,r as q,s as r,t as s,u as t,v as u}from"./chunk-VMJXNTJT.js";import"./chunk-MF3XRML3.js";import"./chunk-OWMGD7FO.js";import"./chunk-5QJDH4Z5.js";import"./chunk-6H5MRVJS.js";import"./chunk-2GL4GH52.js";import"./chunk-C5QESAYA.js";import"./chunk-YHNEBCYQ.js";import"./chunk-WLLE54TA.js";import"./chunk-3OSCWD7Z.js";import"./chunk-F363JJUI.js";import"./chunk-VEOQH4W6.js";import"./chunk-LYVFC7C7.js";import"./chunk-U56TIYGP.js";import"./chunk-RH3PHCJT.js";import"./chunk-KCHFF4IE.js";import"./chunk-3BO7EKGO.js";import"./chunk-UE3XXKLN.js";import"./chunk-TEJPHJMW.js";import"./chunk-OKGK7DBT.js";import"./chunk-DXV6NRG3.js";import"./chunk-X73CRYF4.js";import"./chunk-BQT4J3BD.js";import"./chunk-FEBXP74Y.js";import"./chunk-KNL3QWVA.js";import"./chunk-MJBXQXSX.js";import"./chunk-ZCNVFULO.js";import"./chunk-QU54GUEA.js";import"./chunk-O3NAUNFC.js";import"./chunk-I4E6CLC4.js";import"./chunk-NT4PI5HI.js";import"./chunk-66GIKUI2.js";import"./chunk-SGONA5GS.js";import"./chunk-5UOV7T36.js";import"./chunk-KOSKGZK4.js";import"./chunk-55JPAF56.js";export{t as BUILT_IN_STRATEGIES,e as ConceptGraph,j as DEFAULT_ACTIVATION_CONFIG,d as DEFAULT_CONCEPT_GRAPH_CONFIG,p as DEFAULT_DREAM_CONFIG,a as DEFAULT_DREAM_SCHEDULER_CONFIG,l as DEFAULT_INSIGHT_CONFIG,n as DEFAULT_VALIDATION_THRESHOLDS,q as DreamEngine,b as DreamScheduler,i as HISTORY_TRIM_TARGET_RATIO,m as InsightGenerator,g as MAX_ACTIVATION_HISTORY_ENTRIES,h as MAX_COACTIVATION_ENTRIES,o as RVCOWBranchManager,u as SpeculativeDreamer,k as SpreadingActivation,f as createConceptGraph,r as createDreamEngine,c as createDreamScheduler,s as default};
|
|
@@ -1,3 +1,3 @@
|
|
|
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.
|
|
2
|
-
import{a as r,b as i}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.0");process.exit(0)}
|
|
2
|
+
import{a as r,b as i}from"./chunk-3BO7EKGO.js";import"./chunk-KNL3QWVA.js";import"./chunk-66GIKUI2.js";import"./chunk-55JPAF56.js";async function u(a,o,d,s,m,t={}){try{let e=`${d??""} ${s??""} ${(m??[]).join(" ")}`.trim();if(!e)return;let n=await i(e,t);if(!n||n.length===0)return;let f=Buffer.from(new Float32Array(n).buffer),g={...r,...t};a.prepare(`INSERT OR REPLACE INTO qe_pattern_embeddings (pattern_id, embedding, dimension, model)
|
|
3
3
|
VALUES (?, ?, ?, ?)`).run(o,f,n.length,g.modelName)}catch(e){console.debug("[ensurePatternEmbedding] non-fatal:",e instanceof Error?e.message:String(e))}}export{u as ensurePatternEmbedding};
|
|
@@ -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.
|
|
2
|
-
import{a 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.10.0");process.exit(0)}
|
|
2
|
+
import{a as T}from"./chunk-XFUU2RCA.js";import{a as R,b as g,c as S,d as b}from"./chunk-Z2SCTEZD.js";import{a as y}from"./chunk-IBXNBLGM.js";import"./chunk-2POXDKUB.js";import"./chunk-JUICZG3T.js";import"./chunk-GPKZ4MMH.js";import"./chunk-CU4IUJ2K.js";import"./chunk-C5QESAYA.js";import"./chunk-F363JJUI.js";import"./chunk-KCHFF4IE.js";import"./chunk-3BO7EKGO.js";import"./chunk-UE3XXKLN.js";import"./chunk-TEJPHJMW.js";import"./chunk-OKGK7DBT.js";import"./chunk-X73CRYF4.js";import"./chunk-BQT4J3BD.js";import"./chunk-FEBXP74Y.js";import"./chunk-KNL3QWVA.js";import"./chunk-MJBXQXSX.js";import"./chunk-ZCNVFULO.js";import"./chunk-QU54GUEA.js";import"./chunk-O3NAUNFC.js";import"./chunk-I4E6CLC4.js";import"./chunk-NT4PI5HI.js";import"./chunk-66GIKUI2.js";import"./chunk-SGONA5GS.js";import"./chunk-5UOV7T36.js";import"./chunk-KOSKGZK4.js";import"./chunk-55JPAF56.js";import{Command as M}from"commander";import s from"chalk";import*as d from"fs";import*as p from"path";import*as x from"yaml";var f=["accessibility-testing","security-testing","performance-testing","chaos-engineering-resilience","contract-testing"],E=["risk-based-testing","test-design-techniques","regression-testing","test-data-management","localization-testing"],C=["quality-metrics","refactoring-patterns","iterative-loop","stream-chain"];function L(e){switch(e){case 3:return f;case 2:return[...f,...E];case 1:return[...f,...E,...C];default:return f}}var h="";function O(e){let t=Math.round(e.completedTasks/e.totalTasks*100),l=k(e.elapsedMs),o=k(e.estimatedRemainingMs),n=A(t,30),i=`${s.cyan("Progress:")} ${n} ${t}% | ${s.green(e.completedTasks)}/${e.totalTasks} tasks | ${s.yellow(e.failedTasks)} failed | ${s.blue(e.activeWorkers)} workers | ${l} elapsed, ~${o} remaining`;h&&process.stdout.write("\r"+" ".repeat(h.length)+"\r"),process.stdout.write(i),h=i}function A(e,t){let l=Math.round(e/100*t),o=t-l;return s.green("=".repeat(l))+s.gray("-".repeat(o))}function k(e){if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;let t=Math.floor(e/6e4),l=Math.round(e%6e4/1e3);return`${t}m ${l}s`}function F(e){let t=[];t.push(""),t.push(s.bold(`Eval Results: ${e.skill}`)+s.dim(` (${e.model})`)),t.push("=".repeat(60));let l=e.passed?s.green("PASSED"):s.red("FAILED");t.push(`Status: ${l}`),t.push(""),t.push(s.bold("Metrics:")),t.push(` Total Tests: ${e.totalTests}`),t.push(` Passed: ${s.green(e.passedTests)}`),t.push(` Failed: ${s.red(e.failedTests)}`),t.push(` Skipped: ${s.yellow(e.skippedTests)}`),t.push(` Pass Rate: ${(e.passRate*100).toFixed(1)}%`),t.push(` Reasoning Avg: ${(e.avgReasoningQuality*100).toFixed(1)}%`),t.push(""),t.push(s.bold("Performance:")),t.push(` Duration: ${k(e.totalDurationMs)}`),t.push(` Workers Used: ${e.workersUsed}`),t.push(` Parallel Speedup: ${s.cyan(e.parallelSpeedup.toFixed(2)+"x")}`),t.push("");let o=e.testResults.filter(n=>!n.passed);if(o.length>0){t.push(s.bold.red("Failed Tests:"));for(let n of o.slice(0,5))t.push(` ${s.red("x")} ${n.testId}`),n.error&&t.push(` ${s.dim(n.error)}`);o.length>5&&t.push(` ... and ${o.length-5} more`),t.push("")}return t.join(`
|
|
3
3
|
`)}function D(e){let t=[];t.push("# Skill Evaluation Report"),t.push(""),t.push(`Generated: ${new Date().toISOString()}`),t.push(""),t.push("## Summary"),t.push(""),t.push("| Skill | Model | Pass Rate | Duration | Speedup | Status |"),t.push("|-------|-------|-----------|----------|---------|--------|");for(let l of e){let o=l.passed?"PASSED":"FAILED";t.push(`| ${l.skill} | ${l.model} | ${(l.passRate*100).toFixed(1)}% | ${k(l.totalDurationMs)} | ${l.parallelSpeedup.toFixed(2)}x | ${o} |`)}t.push(""),t.push("## Detailed Results"),t.push("");for(let l of e){t.push(`### ${l.skill} (${l.model})`),t.push(""),t.push(`- **Total Tests:** ${l.totalTests}`),t.push(`- **Passed:** ${l.passedTests}`),t.push(`- **Failed:** ${l.failedTests}`),t.push(`- **Pass Rate:** ${(l.passRate*100).toFixed(1)}%`),t.push(`- **Avg Reasoning Quality:** ${(l.avgReasoningQuality*100).toFixed(1)}%`),t.push("");let o=l.testResults.filter(n=>!n.passed);if(o.length>0){t.push("**Failed Tests:**"),t.push("");for(let n of o)t.push(`- \`${n.testId}\`: ${n.error||"No error message"}`);t.push("")}}return t.join(`
|
|
4
4
|
`)}var I=".claude/skills";function j(e){let t=p.join(process.cwd(),I,e,"evals",`${e}.yaml`);if(!d.existsSync(t))return null;try{let l=x.parse(d.readFileSync(t,"utf-8"));return S(l)?"command":"llm"}catch{return null}}function B(e,t){return{skill:e.skill,model:t,totalTests:e.totalTests,passedTests:e.passedTests,failedTests:e.failedTests,skippedTests:0,passRate:e.passRate,testResults:e.testResults.map(l=>q(l)),totalDurationMs:e.totalDurationMs,parallelSpeedup:1,avgReasoningQuality:0,passed:e.passed,workersUsed:1,timestamp:e.timestamp}}function q(e){let t=[];return e.setupFailure&&t.push(e.setupFailure),e.failures.length&&t.push(...e.failures),{testId:e.testId,passed:e.passed,expectedPatterns:[],actualPatterns:[],reasoningQuality:0,executionTimeMs:e.durationMs,category:e.category??"uncategorized",priority:e.priority??"medium",error:t.length?t.join("; "):void 0}}async function v(){let e=await T({sqlite:{dbPath:".agentic-qe/eval-runner.db"},hnsw:{M:16,efConstruction:100,efSearch:50}});await e.initialize();let t=y(e);return{runner:g(t),learner:t,reasoningBank:e}}async function V(e){if(console.log(s.bold(`
|
|
5
5
|
AQE Parallel Eval Runner`)),console.log(s.dim(`ADR-056 Phase 5: Worker Pool Pattern
|
|
@@ -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.
|
|
2
|
-
import{k as y,o as S}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.10.0");process.exit(0)}
|
|
2
|
+
import{k as y,o as S}from"./chunk-UE3XXKLN.js";import"./chunk-TEJPHJMW.js";import"./chunk-OKGK7DBT.js";import"./chunk-X73CRYF4.js";import{d as x,e as C}from"./chunk-BQT4J3BD.js";import{a as g,c as N}from"./chunk-KNL3QWVA.js";import{i as f}from"./chunk-MJBXQXSX.js";import"./chunk-ZCNVFULO.js";import"./chunk-QU54GUEA.js";import"./chunk-O3NAUNFC.js";import"./chunk-I4E6CLC4.js";import"./chunk-NT4PI5HI.js";import"./chunk-66GIKUI2.js";import"./chunk-SGONA5GS.js";import"./chunk-5UOV7T36.js";import"./chunk-KOSKGZK4.js";import"./chunk-55JPAF56.js";S();N();C();var D=x("ExperienceCapture"),R=600*1e3,O=120*1e3,M=1024*1024;function m(e,t=M){if(e==null)return null;try{let n=JSON.stringify(e);return n.length>t?(console.warn(`[ExperienceCaptureMiddleware] JSON payload exceeds size limit (${n.length} > ${t} bytes), truncating`),JSON.stringify({_truncated:!0,_originalSize:n.length,_preview:typeof e=="object"?Object.keys(e).slice(0,10):String(e).slice(0,100)})):n}catch(n){return console.warn("[ExperienceCaptureMiddleware] Failed to serialize JSON:",n),null}}var d=new Map,l=null;function U(){let e=Date.now(),t=0;for(let[n,a]of d){let i=e-a.context.startedAt.getTime();i>R&&(console.warn(`[ExperienceCaptureMiddleware] Cleaning up stale experience: ${n} (age=${Math.round(i/1e3)}s, domain=${a.context.domain})`),d.delete(n),t++)}return t>0&&console.log(`[ExperienceCaptureMiddleware] Cleaned ${t} stale experiences`),t}function I(){l||(l=setInterval(()=>{U()},O),l.unref())}function z(){l&&(clearInterval(l),l=null)}var c=null,E=null;async function A(){return E||(E=F(),E)}async function F(){try{c=y(),await c.initialize();let e=c.getDatabase();if(e){let t=!1;if(e.prepare("SELECT COUNT(*) as cnt FROM sqlite_master WHERE type='table' AND name='captured_experiences'").get().cnt>0){let s=e.prepare("PRAGMA table_info(captured_experiences)").all(),r=new Set(s.map(u=>u.name));!r.has("success")||!r.has("task")?(e.exec("ALTER TABLE captured_experiences RENAME TO captured_experiences_v2_backup"),t=!0):(r.has("domain")||e.exec("ALTER TABLE captured_experiences ADD COLUMN domain TEXT NOT NULL DEFAULT ''"),r.has("source")||e.exec("ALTER TABLE captured_experiences ADD COLUMN source TEXT DEFAULT 'middleware'"))}else t=!0;t&&e.exec(`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS captured_experiences (
|
|
4
4
|
id TEXT PRIMARY KEY,
|
|
5
5
|
task TEXT NOT NULL,
|
|
@@ -27,7 +27,7 @@ import{k as y,o as S}from"./chunk-IXOGBA7C.js";import"./chunk-NFIOKKA6.js";impor
|
|
|
27
27
|
(id, task, agent, domain, success, quality, duration_ms, model_tier,
|
|
28
28
|
routing_json, steps_json, result_json, error, started_at, completed_at, source)
|
|
29
29
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'), ?)
|
|
30
|
-
`).run(t.id,e.task,e.agent,e.domain,t.success?1:0,t.quality,t.durationMs,e.modelTier||null,m(e.routing),m(t.steps),m(t.result),t.error||null,e.startedAt.toISOString(),"middleware"),X(n,t.id,e.task,e.domain).catch(i=>{D.warn("Embedding computation failed",{error:i instanceof Error?i.message:String(i),experienceId:t.id,domain:e.domain})})}catch(n){console.error("[ExperienceCaptureMiddleware] Failed to persist experience:",n)}}async function X(e,t,n,a){try{let{computeRealEmbedding:i}=await import("./real-embeddings-
|
|
30
|
+
`).run(t.id,e.task,e.agent,e.domain,t.success?1:0,t.quality,t.durationMs,e.modelTier||null,m(e.routing),m(t.steps),m(t.result),t.error||null,e.startedAt.toISOString(),"middleware"),X(n,t.id,e.task,e.domain).catch(i=>{D.warn("Embedding computation failed",{error:i instanceof Error?i.message:String(i),experienceId:t.id,domain:e.domain})})}catch(n){console.error("[ExperienceCaptureMiddleware] Failed to persist experience:",n)}}async function X(e,t,n,a){try{let{computeRealEmbedding:i}=await import("./real-embeddings-TYIVN3N5.js"),s=`${a}: ${n}`.slice(0,512),r=await i(s);if(!r||r.length===0)return;let u=Buffer.from(new Float32Array(r).buffer);e.prepare(`
|
|
31
31
|
UPDATE captured_experiences
|
|
32
32
|
SET embedding = ?, embedding_dimension = ?
|
|
33
33
|
WHERE id = ? AND embedding IS NULL
|