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,8 +1,8 @@
|
|
|
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{c as N,g as O}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{c as N,g as O,i as L}from"./chunk-3BO7EKGO.js";import{k as R,o as D}from"./chunk-UE3XXKLN.js";import{b as g,d as w}from"./chunk-OKGK7DBT.js";import{a as p,c as q}from"./chunk-KNL3QWVA.js";import{i as h}from"./chunk-MJBXQXSX.js";import{a as S,b as C}from"./chunk-ZCNVFULO.js";C();w();q();D();function y(E,e){let n=E.prepare("SELECT confidence, usage_count, successful_uses FROM qe_patterns WHERE id = ?").get(e.patternId);if(!n)return{updated:!1};let t=e.success?1:0,r=n.usage_count+1,a=n.successful_uses+t,s=a/r,i=Math.min(1,r/100),o=n.confidence*.3+i*.2+s*.5,c=E.prepare(`
|
|
3
3
|
INSERT INTO qe_pattern_usage (pattern_id, success, metrics_json, feedback)
|
|
4
4
|
VALUES (?, ?, ?, ?)
|
|
5
|
-
`),
|
|
5
|
+
`),m=E.prepare(`
|
|
6
6
|
UPDATE qe_patterns SET
|
|
7
7
|
usage_count = ?,
|
|
8
8
|
successful_uses = ?,
|
|
@@ -11,7 +11,7 @@ import{c as N,g as O}from"./chunk-YQRABKOC.js";import{k as R,o as D}from"./chunk
|
|
|
11
11
|
last_used_at = datetime('now'),
|
|
12
12
|
updated_at = datetime('now')
|
|
13
13
|
WHERE id = ?
|
|
14
|
-
`);return E.transaction(()=>{c.run(e.patternId,t,e.metrics?JSON.stringify(e.metrics):null,e.feedback??null),
|
|
14
|
+
`);return E.transaction(()=>{c.run(e.patternId,t,e.metrics?JSON.stringify(e.metrics):null,e.feedback??null),m.run(r,a,s,o,e.patternId)})(),{updated:!0,usageCount:r,successfulUses:a,successRate:s,qualityScore:o}}var P={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:256*1024*1024,cacheSize:-64e3,foreignKeys:!0,useUnified:!0};function U(E,e=384){let n=new Array(e).fill(0),t=E.toLowerCase().trim();for(let a=0;a<3;a++)for(let s=0;s<t.length;s++){let i=t.charCodeAt(s),o=i*(s+1)*(a+1)%e;n[o]+=Math.sin(i*(a+1))/(s+1)}let r=Math.sqrt(n.reduce((a,s)=>a+s*s,0));if(r>0)for(let a=0;a<e;a++)n[a]/=r;return n}var b=class{db=null;config;prepared=new Map;initialized=!1;unifiedMemory=null;constructor(e={}){this.config={...P,...e}}getDatabase(){return this.db}async initialize(){if(!this.initialized)try{if(this.config.useUnified)this.unifiedMemory=R(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),console.log(`[SQLitePatternStore] Using unified storage: ${this.unifiedMemory.getDbPath()}`);else{let e=await import("path"),n=await import("fs"),t=e.dirname(this.config.dbPath);n.existsSync(t)||n.mkdirSync(t,{recursive:!0}),this.db=S(this.config.dbPath),this.db.pragma(`mmap_size = ${this.config.mmapSize}`),this.db.pragma(`cache_size = ${this.config.cacheSize}`),this.config.foreignKeys&&this.db.pragma("foreign_keys = ON"),this.createSchema(),console.log(`[SQLitePatternStore] Initialized (legacy): ${this.config.dbPath}`)}this.deduplicatePatterns(),this.prepareStatements(),this.initialized=!0}catch(e){throw new Error(`Failed to initialize SQLite: ${p(e)}`)}}createSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
|
|
15
15
|
-- QE Patterns table
|
|
16
16
|
CREATE TABLE IF NOT EXISTS qe_patterns (
|
|
17
17
|
id TEXT PRIMARY KEY,
|
|
@@ -150,7 +150,7 @@ import{c as N,g as O}from"./chunk-YQRABKOC.js";import{k as R,o as D}from"./chunk
|
|
|
150
150
|
`),console.log(`[SQLitePatternStore] Deduplicated: removed ${a} duplicates from ${t} patterns (${r} kept)`))}this.db.exec(`
|
|
151
151
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_patterns_unique_name_domain_type
|
|
152
152
|
ON qe_patterns(name, qe_domain, pattern_type)
|
|
153
|
-
`)}catch(e){console.debug("[SQLitePatternStore] Deduplication migration:",
|
|
153
|
+
`)}catch(e){console.debug("[SQLitePatternStore] Deduplication migration:",p(e))}}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("insertPattern",this.db.prepare(`
|
|
154
154
|
INSERT INTO qe_patterns (
|
|
155
155
|
id, pattern_type, qe_domain, domain, name, description,
|
|
156
156
|
confidence, tier, template_json, context_json
|
|
@@ -224,7 +224,7 @@ import{c as N,g as O}from"./chunk-YQRABKOC.js";import{k as R,o as D}from"./chunk
|
|
|
224
224
|
WHERE p.id NOT LIKE 'bench-%'
|
|
225
225
|
AND p.id NOT IN (SELECT pattern_id FROM qe_pattern_embeddings)
|
|
226
226
|
LIMIT 10
|
|
227
|
-
`).all();return{total:e,withoutEmbeddings:n,sampleGhostIds:t.map(r=>r.id)}}getAllEmbeddings(){if(!this.db)throw new Error("Database not initialized");let e=this.prepared.get("getAllEmbeddings");if(!e)throw new Error("Prepared statement not ready");return e.all().map(t=>({patternId:t.pattern_id,embedding:Array.from(new Float32Array(t.embedding.buffer,t.embedding.byteOffset,t.dimension))}))}getRecentEmbeddings(e){if(!this.db)throw new Error("Database not initialized");let n=Number.isFinite(e)&&e>0?Math.floor(e):1e3,t=this.prepared.get("getRecentEmbeddings");if(!t)throw new Error("Prepared statement not ready");return t.all(n).map(a=>({patternId:a.pattern_id,embedding:Array.from(new Float32Array(a.embedding.buffer,a.embedding.byteOffset,a.dimension))}))}recordUsage(e,n,t,r){if(!this.db)throw new Error("Database not initialized");if(!
|
|
227
|
+
`).all();return{total:e,withoutEmbeddings:n,sampleGhostIds:t.map(r=>r.id)}}getAllEmbeddings(){if(!this.db)throw new Error("Database not initialized");let e=this.prepared.get("getAllEmbeddings");if(!e)throw new Error("Prepared statement not ready");return e.all().map(t=>({patternId:t.pattern_id,embedding:Array.from(new Float32Array(t.embedding.buffer,t.embedding.byteOffset,t.dimension))}))}getRecentEmbeddings(e){if(!this.db)throw new Error("Database not initialized");let n=Number.isFinite(e)&&e>0?Math.floor(e):1e3,t=this.prepared.get("getRecentEmbeddings");if(!t)throw new Error("Prepared statement not ready");return t.all(n).map(a=>({patternId:a.pattern_id,embedding:Array.from(new Float32Array(a.embedding.buffer,a.embedding.byteOffset,a.dimension))}))}recordUsage(e,n,t,r){if(!this.db)throw new Error("Database not initialized");if(!y(this.db,{patternId:e,success:n,metrics:t,feedback:r}).updated)throw new Error(`Pattern not found: ${e}`)}deletePattern(e){if(!this.db)throw new Error("Database not initialized");this.db.transaction(()=>{this.db.prepare("DELETE FROM qe_pattern_embeddings WHERE pattern_id = ?").run(e),this.db.prepare("DELETE FROM qe_pattern_usage WHERE pattern_id = ?").run(e),this.db.prepare("DELETE FROM qe_patterns WHERE id = ?").run(e)})()}promotePattern(e){if(!this.db)throw new Error("Database not initialized");let n=this.prepared.get("promotePattern");if(!n)throw new Error("Prepared statement not ready");n.run(e)}getStats(){if(!this.db)throw new Error("Database not initialized");let e=this.prepared.get("countPatterns"),n=this.prepared.get("countByDomain");if(!e||!n)throw new Error("Prepared statements not ready");let t=e.get().count,r=n.all(),a={};for(let o of r)a[o.qe_domain]=o.count;let s=this.db.prepare(`
|
|
228
228
|
SELECT tier, COUNT(*) as count FROM qe_patterns GROUP BY tier
|
|
229
229
|
`).all(),i={};for(let o of s)i[o.tier]=o.count;return{totalPatterns:t,byDomain:a,byTier:i}}getAggregateOutcomeStats(){let e={routingRequests:0,avgRoutingConfidence:0,successfulRoutings:0,learningOutcomes:0,successfulOutcomes:0,avgPatternSuccessRate:0};if(!this.db)return e;let n=s=>{try{return this.db.prepare(s).get()}catch{return}},t=n(`
|
|
230
230
|
SELECT
|
|
@@ -259,7 +259,7 @@ import{c as N,g as O}from"./chunk-YQRABKOC.js";import{k as R,o as D}from"./chunk
|
|
|
259
259
|
INSERT INTO qe_pattern_reuse (
|
|
260
260
|
pattern_id, task_description, similarity_score, was_reused, tokens_saved, routing_context_json
|
|
261
261
|
) VALUES (?, ?, ?, ?, ?, ?)
|
|
262
|
-
`).run(e,n.slice(0,1e3),t,r?1:0,a,s?JSON.stringify(s):null)}catch(i){console.debug("[SQLitePatternStore] Failed to record pattern reuse:",
|
|
262
|
+
`).run(e,n.slice(0,1e3),t,r?1:0,a,s?JSON.stringify(s):null)}catch(i){console.debug("[SQLitePatternStore] Failed to record pattern reuse:",p(i))}}getPatternReuseStats(e,n=7){if(!this.db)throw new Error("Database not initialized");try{if(!this.db.prepare(`
|
|
263
263
|
SELECT name FROM sqlite_master WHERE type='table' AND name='qe_pattern_reuse'
|
|
264
264
|
`).get())return{totalSearches:0,totalReused:0,reuseRate:0,totalTokensSaved:0,avgSimilarity:0,topPatterns:[]};let r=new Date(Date.now()-n*24*60*60*1e3).toISOString(),a=e?"WHERE pattern_id = ? AND created_at >= ?":"WHERE created_at >= ?",s=e?[e,r]:[r],i=this.db.prepare(`
|
|
265
265
|
SELECT
|
|
@@ -279,7 +279,7 @@ import{c as N,g as O}from"./chunk-YQRABKOC.js";import{k as R,o as D}from"./chunk
|
|
|
279
279
|
GROUP BY pattern_id
|
|
280
280
|
ORDER BY reuse_count DESC
|
|
281
281
|
LIMIT 10
|
|
282
|
-
`).all(r);return{totalSearches:i.total_searches||0,totalReused:i.total_reused||0,reuseRate:i.total_searches>0?(i.total_reused||0)/i.total_searches:0,totalTokensSaved:i.total_tokens_saved||0,avgSimilarity:i.avg_similarity||0,topPatterns:o.map(c=>({patternId:c.pattern_id,reuseCount:c.reuse_count,avgSimilarity:c.avg_similarity}))}}catch(t){return console.debug("[SQLitePatternStore] Failed to get reuse stats:",
|
|
282
|
+
`).all(r);return{totalSearches:i.total_searches||0,totalReused:i.total_reused||0,reuseRate:i.total_searches>0?(i.total_reused||0)/i.total_searches:0,totalTokensSaved:i.total_tokens_saved||0,avgSimilarity:i.avg_similarity||0,topPatterns:o.map(c=>({patternId:c.pattern_id,reuseCount:c.reuse_count,avgSimilarity:c.avg_similarity}))}}catch(t){return console.debug("[SQLitePatternStore] Failed to get reuse stats:",p(t)),{totalSearches:0,totalReused:0,reuseRate:0,totalTokensSaved:0,avgSimilarity:0,topPatterns:[]}}}async backfillEmbeddings(e=32){if(!this.db)throw new Error("Database not initialized");let n=O(),t=this.db.prepare(`
|
|
283
283
|
SELECT p.id, p.name, p.description, p.pattern_type, p.qe_domain
|
|
284
284
|
FROM qe_patterns p
|
|
285
285
|
WHERE p.id NOT IN (SELECT pattern_id FROM qe_pattern_embeddings)
|
|
@@ -287,4 +287,4 @@ import{c as N,g as O}from"./chunk-YQRABKOC.js";import{k as R,o as D}from"./chunk
|
|
|
287
287
|
ORDER BY p.quality_score DESC
|
|
288
288
|
`).all(),r=this.db.prepare(`
|
|
289
289
|
SELECT COUNT(*) as c FROM qe_pattern_embeddings
|
|
290
|
-
`).get();if(t.length===0)return console.log(`[SQLitePatternStore] Backfill: all patterns already have embeddings (${r.c} total)`),{processed:0,skipped:0,errors:0,alreadyHad:r.c,method:"transformer"};console.log(`[SQLitePatternStore] Backfill: ${t.length} patterns need embeddings (${r.c} already have)`);let a=this.prepared.get("insertEmbedding");if(!a)throw new Error("Prepared statements not ready");let s=0,i=0,o=0,c="transformer";for(let
|
|
290
|
+
`).get();if(t.length===0)return console.log(`[SQLitePatternStore] Backfill: all patterns already have embeddings (${r.c} total)`),{processed:0,skipped:0,errors:0,alreadyHad:r.c,method:"transformer"};console.log(`[SQLitePatternStore] Backfill: ${t.length} patterns need embeddings (${r.c} already have)`);let a=this.prepared.get("insertEmbedding");if(!a)throw new Error("Prepared statements not ready");let s=0,i=0,o=0,c="transformer";for(let m=0;m<t.length;m+=e){let f=t.slice(m,m+e),_=[];for(let d of f){let u=[d.name,d.description,d.pattern_type,d.qe_domain].filter(Boolean).join(" ");if(!u.trim()){i++;continue}_.push({id:d.id,text:u})}if(_.length===0)continue;let l;try{l=await N(_.map(d=>d.text))}catch(d){if(L())throw new Error(`[SQLitePatternStore] external embedder endpoint failed during backfill; aborting to protect HNSW index. Original error: ${p(d)}`);console.warn(`[SQLitePatternStore] Transformer unavailable, falling back to hash embeddings: ${p(d)}`),c="hash-fallback",l=_.map(u=>U(u.text,n))}let I=c==="transformer"?"transformer-backfill":"hash-backfill";this.db.transaction(()=>{for(let d=0;d<_.length;d++)try{let u=l[d];if(!u||u.length!==n){o++;continue}let A=Buffer.from(new Float32Array(u).buffer);a.run(_[d].id,A,n,I),s++}catch(u){o++,o<=3&&console.warn(`[SQLitePatternStore] Backfill error for ${_[d].id}:`,p(u))}})();let T=Math.min(m+e,t.length);(T%100===0||T>=t.length)&&console.log(`[SQLitePatternStore] Backfill progress: ${T}/${t.length}`)}return console.log(`[SQLitePatternStore] Backfill complete (${c}): ${s} processed, ${i} skipped, ${o} errors`),{processed:s,skipped:i,errors:o,alreadyHad:r.c,method:c}}close(){this.db&&(this.unifiedMemory?console.log("[SQLitePatternStore] Detached from unified storage (not closing shared connection)"):(this.db.close(),console.log("[SQLitePatternStore] Database closed")),this.db=null,this.unifiedMemory=null,this.initialized=!1,this.prepared.clear())}exec(e){if(!this.db)throw new Error("Database not initialized");this.db.exec(e)}getDb(){if(!this.db)throw new Error("Database not initialized");return this.db}};function Q(E={}){return new b(E)}export{y as a,P as b,U as c,b as d,Q as e};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.
|
|
2
|
-
import{a as S}from"./chunk-PHJK33IV.js";import{c as g}from"./chunk-BTPDHALG.js";import{S as T,b as l}from"./chunk-5Q7X5SDB.js";S();T();import{createRequire as B}from"module";var G=B(import.meta.url),d=class{validateTransfer(e,t){return{approved:!0}}};function R(){if(l().useCoherenceGate)try{let{CoherenceGate:o}=G("./coherence-gate.js");return new o}catch{}return new d}S();var x=g.create("transfer-verification"),A={maxSourceRegression:.05,minTargetImprovement:0,maxSourceConfidenceRegression:.1},b=class{config;constructor(e={}){this.config={...A,...e}}verifyTransfer(e){let t=e.sourcePerformanceAfter.successRate-e.sourcePerformanceBefore.successRate,r=e.targetPerformanceAfter.successRate-e.targetPerformanceBefore.successRate,n=e.sourcePerformanceAfter.avgConfidence-e.sourcePerformanceBefore.avgConfidence,a=e.targetPerformanceAfter.avgConfidence-e.targetPerformanceBefore.avgConfidence,s=t>=-this.config.maxSourceRegression&&n>=-this.config.maxSourceConfidenceRegression,c=r>=this.config.minTargetImprovement,u=s&&c,m;if(!u){let i=[];s||i.push(`source domain regressed: successRate delta=${t.toFixed(4)}, confidence delta=${n.toFixed(4)}`),c||i.push(`target domain did not improve: successRate delta=${r.toFixed(4)}`),m=i.join("; ")}return u?x.debug("Transfer verification passed",{transferId:e.transferId,sourceDelta:t,targetDelta:r}):x.warn("Transfer verification failed",{transferId:e.transferId,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourceDelta:t,targetDelta:r,failureReason:m}),{passed:u,sourceStable:s,targetImproved:c,sourceDelta:t,targetDelta:r,sourceConfidenceDelta:n,targetConfidenceDelta:a,failureReason:m}}getConfig(){return{...this.config}}};function M(o){return new b(o)}T();var p=class{alphas=new Map;betas=new Map;sample(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return this.sampleBeta(t,r)}update(e,t){t?this.alphas.set(e,(this.alphas.get(e)??1)+1):this.betas.set(e,(this.betas.get(e)??1)+1)}getMean(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t/(t+r)}getObservationCount(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t-1+(r-1)}getAlpha(e){return this.alphas.get(e)??1}getBeta(e){return this.betas.get(e)??1}sampleBeta(e,t){let r=this.sampleGamma(e),n=this.sampleGamma(t);return r+n===0?.5:r/(r+n)}sampleGamma(e){if(e<1){let n=Math.random();return this.sampleGamma(e+1)*Math.pow(n,1/e)}let t=e-1/3,r=1/Math.sqrt(9*t);for(;;){let n,a;do n=this.standardNormal(),a=1+r*n;while(a<=0);a=a*a*a;let s=Math.random();if(s<1-.0331*n*n*n*n||Math.log(s)<.5*n*n+t*(1-a+Math.log(a)))return t*a}}standardNormal(){let e=Math.random(),t=Math.random();return Math.sqrt(-2*Math.log(e||1e-10))*Math.cos(2*Math.PI*t)}};var I={threshold:5,slack:.5,resetOnAlarm:!0,warmupSamples:20},h=class{config;states=new Map;constructor(e={}){this.config={...I,...e}}update(e,t){let r=this.getOrCreateState(e);if(r.samplesSinceReset++,r.mu===null)return r.warmupSum+=t,r.warmupCount++,r.warmupCount>=this.config.warmupSamples&&(r.mu=r.warmupSum/r.warmupCount),{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:r.samplesSinceReset};r.sPlus=Math.max(0,r.sPlus+(t-r.mu-this.config.slack)),r.sMinus=Math.max(0,r.sMinus+(-t+r.mu-this.config.slack));let n=Math.max(r.sPlus,r.sMinus),a=!1,s="none";r.sPlus>this.config.threshold?(a=!0,s="positive"):r.sMinus>this.config.threshold&&(a=!0,s="negative");let c={driftDetected:a,cumulativeSum:n,direction:s,samplesSinceReset:r.samplesSinceReset};return a&&this.config.resetOnAlarm&&(r.sPlus=0,r.sMinus=0,r.samplesSinceReset=0),c}reset(e){e?this.states.delete(e):this.states.clear()}getState(e){let t=this.states.get(e);if(!t)return{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:0};let r=Math.max(t.sPlus,t.sMinus),n="none";return t.sPlus>this.config.threshold?n="positive":t.sMinus>this.config.threshold&&(n="negative"),{driftDetected:t.sPlus>this.config.threshold||t.sMinus>this.config.threshold,cumulativeSum:r,direction:n,samplesSinceReset:t.samplesSinceReset}}getOrCreateState(e){let t=this.states.get(e);return t||(t={sPlus:0,sMinus:0,samplesSinceReset:0,warmupSum:0,warmupCount:0,mu:null},this.states.set(e,t)),t}};var w=g.create("domain-transfer"),V={minTransferProbability:.3,explorationWarmup:5,verification:{},maxHistorySize:1e3,useMetaLearningEnhancements:!0},y=class{constructor(e=100){this.decayThreshold=e}decayThreshold;getDecayMultiplier(e){return e<=0?1:Math.pow(.5,e/this.decayThreshold)}applyDecay(e,t,r){return t+(e-t)*this.getDecayMultiplier(r)}},v=class{cusum;outcomes=[];windowSize;constructor(e=20){this.windowSize=e,this.cusum=new h({threshold:3,slack:.1,resetOnAlarm:!1,warmupSamples:Math.min(10,Math.floor(e/2))})}record(e){this.outcomes.push(e),this.outcomes.length>this.windowSize*2&&this.outcomes.splice(0,this.outcomes.length-this.windowSize*2);let t=this.getCurrentRate();this.cusum.update("learn",t)}isPlateaued(){return this.outcomes.length<this.windowSize?!1:!this.cusum.getState("learn").driftDetected}getCurrentRate(){if(this.outcomes.length===0)return 0;let e=this.outcomes.slice(-this.windowSize);return e.filter(Boolean).length/e.length}getOutcomeCount(){return this.outcomes.length}getCusumState(){return this.cusum.getState("learn")}},D=class{front=[];dominates(e,t){let r=e.successRate>=t.successRate&&e.speed>=t.speed&&e.confidence>=t.confidence,n=e.successRate>t.successRate||e.speed>t.speed||e.confidence>t.confidence;return r&&n}add(e){for(let t=this.front.length-1;t>=0;t--)this.dominates(e,this.front[t])&&this.front.splice(t,1);this.front.some(t=>this.dominates(t,e))||this.front.push(e)}getFront(){return[...this.front]}isNonDominated(e){return!this.front.some(t=>this.dominates(t,e))}},C=class{constructor(e=.2){this.bonusScale=e}bonusScale;triedPairs=new Set;markTried(e){this.triedPairs.add(e)}isTried(e){return this.triedPairs.has(e)}getBonus(e){return this.triedPairs.has(e)?0:this.bonusScale}apply(e,t){return Math.min(1,e+this.getBonus(t))}getTriedCount(){return this.triedPairs.size}},P=class{config;sampler;verifier;coherenceGate;transferHistory=[];affinityScores=new Map;performanceProvider=null;transferExecutor=null;nativeModule=null;decayingBeta;plateauDetector;paretoFront;curiosityBonus;constructor(e={}){this.config={...V,...e},this.sampler=new p,this.verifier=M(this.config.verification),this.coherenceGate=R(),this.decayingBeta=new y,this.plateauDetector=new v,this.paretoFront=new D,this.curiosityBonus=new C,this.tryLoadNativeModule()}evaluateTransfer(e,t){if(!this.isEnabled())return this.createRejectedCandidate(e,t);let r=this.makePairKey(e,t),n=this.sampler.sample(r),s=this.sampler.getObservationCount(r)<this.config.explorationWarmup,c=this.getAffinityScore(e,t);if(this.isMetaLearningEnabled()){let u=this.sampler.getMean(r),m=this.sampler.getAlpha(r)-1;n=this.decayingBeta.applyDecay(n,u,m),n=this.curiosityBonus.apply(n,r)}return{sourceDomain:e,targetDomain:t,sampledProbability:n,affinityScore:c,isExploration:s,pairKey:r}}executeTransfer(e){let t=`transfer-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r=this.coherenceGate.validateTransfer({domain:e.sourceDomain},e.targetDomain);if(!r.approved)return w.info("Transfer blocked by coherence gate",{transferId:t,source:e.sourceDomain,target:e.targetDomain,reason:r.rejectionReason}),this.createBlockedResult(t,e,r);let n=this.getPerformanceSnapshot(e.sourceDomain),a=this.getPerformanceSnapshot(e.targetDomain),s=this.computeSqrtDampening(e),c=this.doTransfer(e.sourceDomain,e.targetDomain,s),u=this.getPerformanceSnapshot(e.sourceDomain),m=this.getPerformanceSnapshot(e.targetDomain),i=this.verifier.verifyTransfer({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m}),f=c&&i.passed;if(this.sampler.update(e.pairKey,f),this.updateAffinityScore(e.pairKey,f),this.isMetaLearningEnabled()){this.plateauDetector.record(f),this.curiosityBonus.markTried(e.pairKey);let F=this.sampler.getMean(e.pairKey);this.paretoFront.add({pairKey:e.pairKey,successRate:F,speed:1/(1+s),confidence:this.getAffinityScore(e.sourceDomain,e.targetDomain)})}return this.addToHistory({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,success:f,sampledProbability:e.sampledProbability,dampeningFactor:s,sourceDelta:i.sourceDelta,targetDelta:i.targetDelta,timestamp:Date.now()}),w.info("Transfer completed",{transferId:t,source:e.sourceDomain,target:e.targetDomain,success:f,dampeningFactor:s.toFixed(4),sourceDelta:i.sourceDelta.toFixed(4),targetDelta:i.targetDelta.toFixed(4)}),{transferId:t,candidate:e,success:f,dampeningFactor:s,verification:i,coherenceResult:r,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m,timestamp:Date.now()}}getAffinityScore(e,t){return this.affinityScores.get(this.makePairKey(e,t))??.5}getTransferHistory(){return[...this.transferHistory]}getExpectedSuccessRate(e,t){return this.sampler.getMean(this.makePairKey(e,t))}getObservationCount(e,t){return this.sampler.getObservationCount(this.makePairKey(e,t))}setPerformanceProvider(e){this.performanceProvider=e}setTransferExecutor(e){this.transferExecutor=e}getSampler(){return this.sampler}getCoherenceGate(){return this.coherenceGate}getDecayingBeta(){return this.decayingBeta}getPlateauDetector(){return this.plateauDetector}getParetoFront(){return this.paretoFront}getCuriosityBonus(){return this.curiosityBonus}isLearningPlateaued(){return this.plateauDetector.isPlateaued()}isEnabled(){return l().useCrossDomainTransfer===!0}isMetaLearningEnabled(){return this.config.useMetaLearningEnhancements===!0&&l().useMetaLearningEnhancements!==!1}makePairKey(e,t){return`${e}->${t}`}computeSqrtDampening(e){let t=this.sampler.getObservationCount(e.pairKey);return Math.sqrt(t/(t+this.config.explorationWarmup))}doTransfer(e,t,r){return this.transferExecutor?this.transferExecutor(e,t,r):!0}getPerformanceSnapshot(e){return this.performanceProvider?this.performanceProvider(e):{domain:e,successRate:.5,avgConfidence:.5,patternCount:0,timestamp:Date.now()}}updateAffinityScore(e,t){let r=this.affinityScores.get(e)??.5;this.affinityScores.set(e,.2*(t?1:0)+.8*r)}addToHistory(e){for(this.transferHistory.push(e);this.transferHistory.length>this.config.maxHistorySize;)this.transferHistory.shift()}createBlockedResult(e,t,r){let n={domain:"",successRate:0,avgConfidence:0,patternCount:0,timestamp:Date.now()};return{transferId:e,candidate:t,success:!1,dampeningFactor:0,verification:{passed:!1,sourceStable:!1,targetImproved:!1,sourceDelta:0,targetDelta:0,sourceConfidenceDelta:0,targetConfidenceDelta:0,failureReason:`Coherence gate rejected: ${r.rejectionReason??"unknown"}`},coherenceResult:r,sourcePerformanceBefore:{...n,domain:t.sourceDomain},sourcePerformanceAfter:{...n,domain:t.sourceDomain},targetPerformanceBefore:{...n,domain:t.targetDomain},targetPerformanceAfter:{...n,domain:t.targetDomain},timestamp:Date.now()}}createRejectedCandidate(e,t){return{sourceDomain:e,targetDomain:t,sampledProbability:0,affinityScore:0,isExploration:!1,pairKey:this.makePairKey(e,t)}}tryLoadNativeModule(){this.nativeModule=null}};function J(o){return new P(o)}export{p as a,h as b,V as c,y as d,v as e,D as f,C as g,P as h,J as i};
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.0");process.exit(0)}
|
|
2
|
+
import{a as S}from"./chunk-X73CRYF4.js";import{c as g}from"./chunk-BQT4J3BD.js";import{S as T,b as l}from"./chunk-KOSKGZK4.js";S();T();import{createRequire as B}from"module";var G=B(import.meta.url),d=class{validateTransfer(e,t){return{approved:!0}}};function R(){if(l().useCoherenceGate)try{let{CoherenceGate:o}=G("./coherence-gate.js");return new o}catch{}return new d}S();var x=g.create("transfer-verification"),A={maxSourceRegression:.05,minTargetImprovement:0,maxSourceConfidenceRegression:.1},b=class{config;constructor(e={}){this.config={...A,...e}}verifyTransfer(e){let t=e.sourcePerformanceAfter.successRate-e.sourcePerformanceBefore.successRate,r=e.targetPerformanceAfter.successRate-e.targetPerformanceBefore.successRate,n=e.sourcePerformanceAfter.avgConfidence-e.sourcePerformanceBefore.avgConfidence,a=e.targetPerformanceAfter.avgConfidence-e.targetPerformanceBefore.avgConfidence,s=t>=-this.config.maxSourceRegression&&n>=-this.config.maxSourceConfidenceRegression,c=r>=this.config.minTargetImprovement,u=s&&c,m;if(!u){let i=[];s||i.push(`source domain regressed: successRate delta=${t.toFixed(4)}, confidence delta=${n.toFixed(4)}`),c||i.push(`target domain did not improve: successRate delta=${r.toFixed(4)}`),m=i.join("; ")}return u?x.debug("Transfer verification passed",{transferId:e.transferId,sourceDelta:t,targetDelta:r}):x.warn("Transfer verification failed",{transferId:e.transferId,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourceDelta:t,targetDelta:r,failureReason:m}),{passed:u,sourceStable:s,targetImproved:c,sourceDelta:t,targetDelta:r,sourceConfidenceDelta:n,targetConfidenceDelta:a,failureReason:m}}getConfig(){return{...this.config}}};function M(o){return new b(o)}T();var p=class{alphas=new Map;betas=new Map;sample(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return this.sampleBeta(t,r)}update(e,t){t?this.alphas.set(e,(this.alphas.get(e)??1)+1):this.betas.set(e,(this.betas.get(e)??1)+1)}getMean(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t/(t+r)}getObservationCount(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t-1+(r-1)}getAlpha(e){return this.alphas.get(e)??1}getBeta(e){return this.betas.get(e)??1}sampleBeta(e,t){let r=this.sampleGamma(e),n=this.sampleGamma(t);return r+n===0?.5:r/(r+n)}sampleGamma(e){if(e<1){let n=Math.random();return this.sampleGamma(e+1)*Math.pow(n,1/e)}let t=e-1/3,r=1/Math.sqrt(9*t);for(;;){let n,a;do n=this.standardNormal(),a=1+r*n;while(a<=0);a=a*a*a;let s=Math.random();if(s<1-.0331*n*n*n*n||Math.log(s)<.5*n*n+t*(1-a+Math.log(a)))return t*a}}standardNormal(){let e=Math.random(),t=Math.random();return Math.sqrt(-2*Math.log(e||1e-10))*Math.cos(2*Math.PI*t)}};var I={threshold:5,slack:.5,resetOnAlarm:!0,warmupSamples:20},h=class{config;states=new Map;constructor(e={}){this.config={...I,...e}}update(e,t){let r=this.getOrCreateState(e);if(r.samplesSinceReset++,r.mu===null)return r.warmupSum+=t,r.warmupCount++,r.warmupCount>=this.config.warmupSamples&&(r.mu=r.warmupSum/r.warmupCount),{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:r.samplesSinceReset};r.sPlus=Math.max(0,r.sPlus+(t-r.mu-this.config.slack)),r.sMinus=Math.max(0,r.sMinus+(-t+r.mu-this.config.slack));let n=Math.max(r.sPlus,r.sMinus),a=!1,s="none";r.sPlus>this.config.threshold?(a=!0,s="positive"):r.sMinus>this.config.threshold&&(a=!0,s="negative");let c={driftDetected:a,cumulativeSum:n,direction:s,samplesSinceReset:r.samplesSinceReset};return a&&this.config.resetOnAlarm&&(r.sPlus=0,r.sMinus=0,r.samplesSinceReset=0),c}reset(e){e?this.states.delete(e):this.states.clear()}getState(e){let t=this.states.get(e);if(!t)return{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:0};let r=Math.max(t.sPlus,t.sMinus),n="none";return t.sPlus>this.config.threshold?n="positive":t.sMinus>this.config.threshold&&(n="negative"),{driftDetected:t.sPlus>this.config.threshold||t.sMinus>this.config.threshold,cumulativeSum:r,direction:n,samplesSinceReset:t.samplesSinceReset}}getOrCreateState(e){let t=this.states.get(e);return t||(t={sPlus:0,sMinus:0,samplesSinceReset:0,warmupSum:0,warmupCount:0,mu:null},this.states.set(e,t)),t}};var w=g.create("domain-transfer"),V={minTransferProbability:.3,explorationWarmup:5,verification:{},maxHistorySize:1e3,useMetaLearningEnhancements:!0},y=class{constructor(e=100){this.decayThreshold=e}decayThreshold;getDecayMultiplier(e){return e<=0?1:Math.pow(.5,e/this.decayThreshold)}applyDecay(e,t,r){return t+(e-t)*this.getDecayMultiplier(r)}},v=class{cusum;outcomes=[];windowSize;constructor(e=20){this.windowSize=e,this.cusum=new h({threshold:3,slack:.1,resetOnAlarm:!1,warmupSamples:Math.min(10,Math.floor(e/2))})}record(e){this.outcomes.push(e),this.outcomes.length>this.windowSize*2&&this.outcomes.splice(0,this.outcomes.length-this.windowSize*2);let t=this.getCurrentRate();this.cusum.update("learn",t)}isPlateaued(){return this.outcomes.length<this.windowSize?!1:!this.cusum.getState("learn").driftDetected}getCurrentRate(){if(this.outcomes.length===0)return 0;let e=this.outcomes.slice(-this.windowSize);return e.filter(Boolean).length/e.length}getOutcomeCount(){return this.outcomes.length}getCusumState(){return this.cusum.getState("learn")}},D=class{front=[];dominates(e,t){let r=e.successRate>=t.successRate&&e.speed>=t.speed&&e.confidence>=t.confidence,n=e.successRate>t.successRate||e.speed>t.speed||e.confidence>t.confidence;return r&&n}add(e){for(let t=this.front.length-1;t>=0;t--)this.dominates(e,this.front[t])&&this.front.splice(t,1);this.front.some(t=>this.dominates(t,e))||this.front.push(e)}getFront(){return[...this.front]}isNonDominated(e){return!this.front.some(t=>this.dominates(t,e))}},C=class{constructor(e=.2){this.bonusScale=e}bonusScale;triedPairs=new Set;markTried(e){this.triedPairs.add(e)}isTried(e){return this.triedPairs.has(e)}getBonus(e){return this.triedPairs.has(e)?0:this.bonusScale}apply(e,t){return Math.min(1,e+this.getBonus(t))}getTriedCount(){return this.triedPairs.size}},P=class{config;sampler;verifier;coherenceGate;transferHistory=[];affinityScores=new Map;performanceProvider=null;transferExecutor=null;nativeModule=null;decayingBeta;plateauDetector;paretoFront;curiosityBonus;constructor(e={}){this.config={...V,...e},this.sampler=new p,this.verifier=M(this.config.verification),this.coherenceGate=R(),this.decayingBeta=new y,this.plateauDetector=new v,this.paretoFront=new D,this.curiosityBonus=new C,this.tryLoadNativeModule()}evaluateTransfer(e,t){if(!this.isEnabled())return this.createRejectedCandidate(e,t);let r=this.makePairKey(e,t),n=this.sampler.sample(r),s=this.sampler.getObservationCount(r)<this.config.explorationWarmup,c=this.getAffinityScore(e,t);if(this.isMetaLearningEnabled()){let u=this.sampler.getMean(r),m=this.sampler.getAlpha(r)-1;n=this.decayingBeta.applyDecay(n,u,m),n=this.curiosityBonus.apply(n,r)}return{sourceDomain:e,targetDomain:t,sampledProbability:n,affinityScore:c,isExploration:s,pairKey:r}}executeTransfer(e){let t=`transfer-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r=this.coherenceGate.validateTransfer({domain:e.sourceDomain},e.targetDomain);if(!r.approved)return w.info("Transfer blocked by coherence gate",{transferId:t,source:e.sourceDomain,target:e.targetDomain,reason:r.rejectionReason}),this.createBlockedResult(t,e,r);let n=this.getPerformanceSnapshot(e.sourceDomain),a=this.getPerformanceSnapshot(e.targetDomain),s=this.computeSqrtDampening(e),c=this.doTransfer(e.sourceDomain,e.targetDomain,s),u=this.getPerformanceSnapshot(e.sourceDomain),m=this.getPerformanceSnapshot(e.targetDomain),i=this.verifier.verifyTransfer({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m}),f=c&&i.passed;if(this.sampler.update(e.pairKey,f),this.updateAffinityScore(e.pairKey,f),this.isMetaLearningEnabled()){this.plateauDetector.record(f),this.curiosityBonus.markTried(e.pairKey);let F=this.sampler.getMean(e.pairKey);this.paretoFront.add({pairKey:e.pairKey,successRate:F,speed:1/(1+s),confidence:this.getAffinityScore(e.sourceDomain,e.targetDomain)})}return this.addToHistory({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,success:f,sampledProbability:e.sampledProbability,dampeningFactor:s,sourceDelta:i.sourceDelta,targetDelta:i.targetDelta,timestamp:Date.now()}),w.info("Transfer completed",{transferId:t,source:e.sourceDomain,target:e.targetDomain,success:f,dampeningFactor:s.toFixed(4),sourceDelta:i.sourceDelta.toFixed(4),targetDelta:i.targetDelta.toFixed(4)}),{transferId:t,candidate:e,success:f,dampeningFactor:s,verification:i,coherenceResult:r,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m,timestamp:Date.now()}}getAffinityScore(e,t){return this.affinityScores.get(this.makePairKey(e,t))??.5}getTransferHistory(){return[...this.transferHistory]}getExpectedSuccessRate(e,t){return this.sampler.getMean(this.makePairKey(e,t))}getObservationCount(e,t){return this.sampler.getObservationCount(this.makePairKey(e,t))}setPerformanceProvider(e){this.performanceProvider=e}setTransferExecutor(e){this.transferExecutor=e}getSampler(){return this.sampler}getCoherenceGate(){return this.coherenceGate}getDecayingBeta(){return this.decayingBeta}getPlateauDetector(){return this.plateauDetector}getParetoFront(){return this.paretoFront}getCuriosityBonus(){return this.curiosityBonus}isLearningPlateaued(){return this.plateauDetector.isPlateaued()}isEnabled(){return l().useCrossDomainTransfer===!0}isMetaLearningEnabled(){return this.config.useMetaLearningEnhancements===!0&&l().useMetaLearningEnhancements!==!1}makePairKey(e,t){return`${e}->${t}`}computeSqrtDampening(e){let t=this.sampler.getObservationCount(e.pairKey);return Math.sqrt(t/(t+this.config.explorationWarmup))}doTransfer(e,t,r){return this.transferExecutor?this.transferExecutor(e,t,r):!0}getPerformanceSnapshot(e){return this.performanceProvider?this.performanceProvider(e):{domain:e,successRate:.5,avgConfidence:.5,patternCount:0,timestamp:Date.now()}}updateAffinityScore(e,t){let r=this.affinityScores.get(e)??.5;this.affinityScores.set(e,.2*(t?1:0)+.8*r)}addToHistory(e){for(this.transferHistory.push(e);this.transferHistory.length>this.config.maxHistorySize;)this.transferHistory.shift()}createBlockedResult(e,t,r){let n={domain:"",successRate:0,avgConfidence:0,patternCount:0,timestamp:Date.now()};return{transferId:e,candidate:t,success:!1,dampeningFactor:0,verification:{passed:!1,sourceStable:!1,targetImproved:!1,sourceDelta:0,targetDelta:0,sourceConfidenceDelta:0,targetConfidenceDelta:0,failureReason:`Coherence gate rejected: ${r.rejectionReason??"unknown"}`},coherenceResult:r,sourcePerformanceBefore:{...n,domain:t.sourceDomain},sourcePerformanceAfter:{...n,domain:t.sourceDomain},targetPerformanceBefore:{...n,domain:t.targetDomain},targetPerformanceAfter:{...n,domain:t.targetDomain},timestamp:Date.now()}}createRejectedCandidate(e,t){return{sourceDomain:e,targetDomain:t,sampledProbability:0,affinityScore:0,isExploration:!1,pairKey:this.makePairKey(e,t)}}tryLoadNativeModule(){this.nativeModule=null}};function J(o){return new P(o)}export{p as a,h as b,V as c,y as d,v as e,D as f,C as g,P as h,J as i};
|
|
@@ -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{c as r}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{c as r}from"./chunk-55JPAF56.js";function o(n){return n instanceof Error?n.message:String(n)}function e(n){return n instanceof Error?n:new Error(String(n))}var t=r(()=>{"use strict"});export{o as a,e as b,t as c};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.
|
|
2
|
-
import{c as s,e 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{c as s,e as t}from"./chunk-55JPAF56.js";var K={};t(K,{DEFAULT_FEATURE_FLAGS:()=>r,getRuVectorFeatureFlags:()=>i,getRvfMigrationStage:()=>H,initFeatureFlagsFromEnv:()=>z,isAgentMemoryBranchingEnabled:()=>I,isCNNVisualRegressionEnabled:()=>b,isCognitiveRoutingEnabled:()=>Y,isCoherenceActionGateEnabled:()=>A,isCoherenceGateEnabled:()=>f,isColdTierGNNEnabled:()=>m,isCrossDomainTransferEnabled:()=>N,isCusumDriftDetectionEnabled:()=>M,isDAGAttentionEnabled:()=>g,isDeltaEventSourcingEnabled:()=>F,isDeterministicDitherEnabled:()=>C,isEpropOnlineLearningEnabled:()=>Q,isEwcPlusPlusEnabled:()=>L,isFlashAttentionEnabled:()=>E,isGNNIndexEnabled:()=>R,isGrangerCausalityEnabled:()=>B,isGraphMAEEnabled:()=>x,isHDCFingerprintingEnabled:()=>D,isHnswHealthMonitorEnabled:()=>U,isHopfieldMemoryEnabled:()=>h,isHyperbolicHnswEnabled:()=>k,isMetaLearningEnabled:()=>P,isMetadataFilteringEnabled:()=>S,isNativeHNSWEnabled:()=>_,isNeuralRoutingEnabled:()=>T,isRVFPatternStoreEnabled:()=>V,isReasoningQECEnabled:()=>v,isRegretTrackingEnabled:()=>O,isReservoirReplayEnabled:()=>w,isSONAEnabled:()=>a,isSONAThreeLoopEnabled:()=>p,isSpectralSparsificationEnabled:()=>W,isSublinearSolverEnabled:()=>y,isTemporalCompressionEnabled:()=>c,isUnifiedHnswEnabled:()=>G,isWitnessChainEnabled:()=>d,resetRuVectorFeatureFlags:()=>u,setRuVectorFeatureFlags:()=>o,shouldLogMigrationMetrics:()=>l});function i(){return{...e}}function o(n){e={...e,...n}}function u(){e={...r}}function a(){return e.useQESONA}function E(){return e.useQEFlashAttention}function R(){return e.useQEGNNIndex}function l(){return e.logMigrationMetrics}function _(){return e.useNativeHNSW}function c(){return e.useTemporalCompression}function S(){return e.useMetadataFiltering}function C(){return e.useDeterministicDither}function T(){return e.useNeuralRouting}function p(){return e.useSONAThreeLoop}function N(){return e.useCrossDomainTransfer}function U(){return e.useHnswHealthMonitor}function O(){return e.useRegretTracking}function f(){return e.useCoherenceGate}function d(){return e.useWitnessChain}function b(){return e.useCNNVisualRegression}function g(){return e.useDAGAttention}function A(){return e.useCoherenceActionGate}function v(){return e.useReasoningQEC}function V(){return e.useRVFPatternStore}function I(){return e.useAgentMemoryBranching}function G(){return e.useUnifiedHnsw}function H(){return e.rvfMigrationStage}function D(){return e.useHDCFingerprinting}function M(){return e.useCusumDriftDetection}function F(){return e.useDeltaEventSourcing}function L(){return e.useEwcPlusPlusRegularization}function x(){return e.useGraphMAEEmbeddings}function h(){return e.useHopfieldMemory}function m(){return e.useColdTierGNN}function P(){return e.useMetaLearningEnhancements}function y(){return e.useSublinearSolver}function W(){return e.useSpectralSparsification}function w(){return e.useReservoirReplay}function Q(){return e.useEpropOnlineLearning}function B(){return e.useGrangerCausality}function Y(){return e.useCognitiveRouting}function k(){return e.useHyperbolicHnsw}function z(){let n={};process.env.RUVECTOR_USE_SONA!==void 0&&(n.useQESONA=process.env.RUVECTOR_USE_SONA==="true"),process.env.RUVECTOR_USE_FLASH_ATTENTION!==void 0&&(n.useQEFlashAttention=process.env.RUVECTOR_USE_FLASH_ATTENTION==="true"),process.env.RUVECTOR_USE_GNN_INDEX!==void 0&&(n.useQEGNNIndex=process.env.RUVECTOR_USE_GNN_INDEX==="true"),process.env.RUVECTOR_LOG_MIGRATION_METRICS!==void 0&&(n.logMigrationMetrics=process.env.RUVECTOR_LOG_MIGRATION_METRICS==="true"),process.env.RUVECTOR_USE_NATIVE_HNSW!==void 0&&(n.useNativeHNSW=process.env.RUVECTOR_USE_NATIVE_HNSW==="true"),process.env.RUVECTOR_USE_TEMPORAL_COMPRESSION!==void 0&&(n.useTemporalCompression=process.env.RUVECTOR_USE_TEMPORAL_COMPRESSION==="true"),process.env.RUVECTOR_USE_METADATA_FILTERING!==void 0&&(n.useMetadataFiltering=process.env.RUVECTOR_USE_METADATA_FILTERING==="true"),process.env.RUVECTOR_USE_DETERMINISTIC_DITHER!==void 0&&(n.useDeterministicDither=process.env.RUVECTOR_USE_DETERMINISTIC_DITHER==="true"),process.env.RUVECTOR_USE_NEURAL_ROUTING!==void 0&&(n.useNeuralRouting=process.env.RUVECTOR_USE_NEURAL_ROUTING==="true"),process.env.RUVECTOR_USE_SONA_THREE_LOOP!==void 0&&(n.useSONAThreeLoop=process.env.RUVECTOR_USE_SONA_THREE_LOOP==="true"),process.env.RUVECTOR_USE_CROSS_DOMAIN_TRANSFER!==void 0&&(n.useCrossDomainTransfer=process.env.RUVECTOR_USE_CROSS_DOMAIN_TRANSFER==="true"),process.env.RUVECTOR_USE_HNSW_HEALTH_MONITOR!==void 0&&(n.useHnswHealthMonitor=process.env.RUVECTOR_USE_HNSW_HEALTH_MONITOR==="true"),process.env.RUVECTOR_USE_REGRET_TRACKING!==void 0&&(n.useRegretTracking=process.env.RUVECTOR_USE_REGRET_TRACKING==="true"),process.env.RUVECTOR_USE_COHERENCE_GATE!==void 0&&(n.useCoherenceGate=process.env.RUVECTOR_USE_COHERENCE_GATE==="true"),process.env.RUVECTOR_USE_WITNESS_CHAIN!==void 0&&(n.useWitnessChain=process.env.RUVECTOR_USE_WITNESS_CHAIN==="true"),process.env.RUVECTOR_USE_CNN_VISUAL_REGRESSION!==void 0&&(n.useCNNVisualRegression=process.env.RUVECTOR_USE_CNN_VISUAL_REGRESSION==="true"),process.env.RUVECTOR_USE_DAG_ATTENTION!==void 0&&(n.useDAGAttention=process.env.RUVECTOR_USE_DAG_ATTENTION==="true"),process.env.RUVECTOR_USE_COHERENCE_ACTION_GATE!==void 0&&(n.useCoherenceActionGate=process.env.RUVECTOR_USE_COHERENCE_ACTION_GATE==="true"),process.env.RUVECTOR_USE_REASONING_QEC!==void 0&&(n.useReasoningQEC=process.env.RUVECTOR_USE_REASONING_QEC==="true"),process.env.RUVECTOR_USE_HDC_FINGERPRINTING!==void 0&&(n.useHDCFingerprinting=process.env.RUVECTOR_USE_HDC_FINGERPRINTING==="true"),process.env.RUVECTOR_USE_CUSUM_DRIFT_DETECTION!==void 0&&(n.useCusumDriftDetection=process.env.RUVECTOR_USE_CUSUM_DRIFT_DETECTION==="true"),process.env.RUVECTOR_USE_DELTA_EVENT_SOURCING!==void 0&&(n.useDeltaEventSourcing=process.env.RUVECTOR_USE_DELTA_EVENT_SOURCING==="true"),process.env.RUVECTOR_USE_EWC_PLUS_PLUS!==void 0&&(n.useEwcPlusPlusRegularization=process.env.RUVECTOR_USE_EWC_PLUS_PLUS==="true"),process.env.RUVECTOR_USE_META_LEARNING!==void 0&&(n.useMetaLearningEnhancements=process.env.RUVECTOR_USE_META_LEARNING==="true"),process.env.RUVECTOR_USE_SUBLINEAR_SOLVER!==void 0&&(n.useSublinearSolver=process.env.RUVECTOR_USE_SUBLINEAR_SOLVER==="true"),process.env.RUVECTOR_USE_SPECTRAL_SPARSIFICATION!==void 0&&(n.useSpectralSparsification=process.env.RUVECTOR_USE_SPECTRAL_SPARSIFICATION==="true"),process.env.RUVECTOR_USE_RESERVOIR_REPLAY!==void 0&&(n.useReservoirReplay=process.env.RUVECTOR_USE_RESERVOIR_REPLAY==="true"),process.env.RUVECTOR_USE_EPROP_ONLINE_LEARNING!==void 0&&(n.useEpropOnlineLearning=process.env.RUVECTOR_USE_EPROP_ONLINE_LEARNING==="true"),process.env.RUVECTOR_USE_GRANGER_CAUSALITY!==void 0&&(n.useGrangerCausality=process.env.RUVECTOR_USE_GRANGER_CAUSALITY==="true"),process.env.RUVECTOR_USE_COGNITIVE_ROUTING!==void 0&&(n.useCognitiveRouting=process.env.RUVECTOR_USE_COGNITIVE_ROUTING==="true"),process.env.RUVECTOR_USE_HYPERBOLIC_HNSW!==void 0&&(n.useHyperbolicHnsw=process.env.RUVECTOR_USE_HYPERBOLIC_HNSW==="true"),o(n)}var r,e,X=s(()=>{r={useQESONA:!0,useQEFlashAttention:!0,useQEGNNIndex:!0,logMigrationMetrics:!0,useNativeHNSW:!0,useTemporalCompression:!0,useMetadataFiltering:!0,useDeterministicDither:!0,useNeuralRouting:!0,useSONAThreeLoop:!0,useCrossDomainTransfer:!0,useHnswHealthMonitor:!0,useRegretTracking:!0,useCoherenceGate:!0,useWitnessChain:!0,useCNNVisualRegression:!0,useDAGAttention:!0,useCoherenceActionGate:!0,useReasoningQEC:!0,useRVFPatternStore:!0,useAgentMemoryBranching:!0,useUnifiedHnsw:!0,rvfMigrationStage:2,useHDCFingerprinting:!0,useCusumDriftDetection:!0,useDeltaEventSourcing:!0,useEwcPlusPlusRegularization:!0,useGraphMAEEmbeddings:!0,useHopfieldMemory:!0,useColdTierGNN:!0,useMetaLearningEnhancements:!0,useSublinearSolver:!0,useSpectralSparsification:!0,useReservoirReplay:!0,useEpropOnlineLearning:!0,useGrangerCausality:!0,useCognitiveRouting:!1,useHyperbolicHnsw:!1},e={...r}});export{r as a,i as b,o as c,u as d,a as e,E as f,R as g,l as h,_ as i,c as j,S as k,C as l,T as m,p as n,N as o,U as p,O as q,f as r,d as s,b as t,g as u,A as v,v as w,V as x,I as y,G as z,H as A,D as B,M as C,F as D,L as E,x as F,h as G,m as H,P as I,y as J,W as K,w as L,Q as M,B as N,Y as O,k as P,z as Q,K as R,X as S};
|
|
@@ -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 _}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 _}from"./chunk-2POXDKUB.js";import{e as E}from"./chunk-F363JJUI.js";import{b as p,d as b}from"./chunk-OKGK7DBT.js";import{a as T}from"./chunk-X73CRYF4.js";import{c as h}from"./chunk-BQT4J3BD.js";import{S,j as g}from"./chunk-KOSKGZK4.js";b();T();S();var o=h.create("pattern-lifecycle"),A={promotionRewardThreshold:.7,promotionMinOccurrences:E,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3,maxAgeForActivePatterns:90,promotionActivityWindowDays:30,asymmetricLearning:{}},f=class{constructor(e,t={}){this.db=e;this.config={...A,...t},this.asymmetricEngine=new _(this.config.asymmetricLearning),this.ensureSchema()}db;config;asymmetricEngine;_witnessChain=null;set witnessChain(e){this._witnessChain=e}_compressionService=null;set compressionService(e){this._compressionService=e}ensureSchema(){try{this.db.prepare(`
|
|
3
3
|
SELECT deprecated_at FROM qe_patterns LIMIT 1
|
|
4
4
|
`).get()}catch(e){o.debug("Adding missing deprecated_at column",{error:e instanceof Error?e.message:String(e)}),this.db.exec(`
|
|
5
5
|
ALTER TABLE qe_patterns ADD COLUMN deprecated_at TEXT DEFAULT NULL
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.
|
|
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
2
|
import{randomUUID as v}from"crypto";var m={"claude-opus-4-7":{input:5,output:25,provider:"claude"},"claude-sonnet-4-6":{input:3,output:15,provider:"claude"},"claude-haiku-4-5-20251001":{input:1,output:5,provider:"claude"},"claude-opus-4-5-20251101":{input:15,output:75,provider:"claude"},"claude-sonnet-4-20250514":{input:3,output:15,provider:"claude"},"claude-3-5-haiku-20241022":{input:1,output:5,provider:"claude"},"claude-3-opus-20240229":{input:15,output:75,provider:"claude"},"claude-3-sonnet-20240229":{input:3,output:15,provider:"claude"},"claude-3-haiku-20240307":{input:.25,output:1.25,provider:"claude"},"gpt-4o":{input:5,output:15,provider:"openai"},"gpt-4o-mini":{input:.15,output:.6,provider:"openai"},"gpt-4-turbo":{input:10,output:30,provider:"openai"},"gpt-4":{input:30,output:60,provider:"openai"},"gpt-3.5-turbo":{input:.5,output:1.5,provider:"openai"},llama3:{input:0,output:0,provider:"ollama"},"llama3.1":{input:0,output:0,provider:"ollama"},codellama:{input:0,output:0,provider:"ollama"},mistral:{input:0,output:0,provider:"ollama"},mixtral:{input:0,output:0,provider:"ollama"},phi3:{input:0,output:0,provider:"ollama"},qwen2:{input:0,output:0,provider:"ollama"},"anthropic/claude-3.5-sonnet":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3.5-sonnet:beta":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3-opus":{input:15,output:75,provider:"openrouter"},"anthropic/claude-3-sonnet":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3-haiku":{input:.25,output:1.25,provider:"openrouter"},"openai/gpt-4o":{input:5,output:15,provider:"openrouter"},"openai/gpt-4o-mini":{input:.15,output:.6,provider:"openrouter"},"openai/gpt-4-turbo":{input:10,output:30,provider:"openrouter"},"openai/gpt-3.5-turbo":{input:.5,output:1.5,provider:"openrouter"},"google/gemini-pro":{input:.125,output:.375,provider:"openrouter"},"google/gemini-pro-1.5":{input:3.5,output:10.5,provider:"openrouter"},"meta-llama/llama-3.1-70b-instruct":{input:.59,output:.79,provider:"openrouter"},"meta-llama/llama-3.1-8b-instruct":{input:.06,output:.06,provider:"openrouter"},"mistralai/mistral-large":{input:2,output:6,provider:"openrouter"},"mistralai/mixtral-8x7b-instruct":{input:.24,output:.24,provider:"openrouter"},"mistralai/mistral-7b-instruct":{input:.06,output:.06,provider:"openrouter"},"anthropic.claude-opus-4-5-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-opus-4-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-sonnet-4-5-v2:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-sonnet-4-v1:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-3-5-haiku-v1:0":{input:1,output:5,provider:"bedrock"},"anthropic.claude-3-opus-20240229-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-3-sonnet-20240229-v1:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-3-haiku-20240307-v1:0":{input:.25,output:1.25,provider:"bedrock"},"anthropic.claude-3-5-sonnet-20241022-v2:0":{input:3,output:15,provider:"bedrock"},"azure/gpt-4o":{input:5,output:15,provider:"azure-openai"},"azure/gpt-4o-mini":{input:.15,output:.6,provider:"azure-openai"},"azure/gpt-4-turbo":{input:10,output:30,provider:"azure-openai"},"azure/gpt-4":{input:30,output:60,provider:"azure-openai"},"azure/gpt-35-turbo":{input:.5,output:1.5,provider:"azure-openai"},"azure/text-embedding-ada-002":{input:.1,output:0,provider:"azure-openai"},"azure/text-embedding-3-small":{input:.02,output:0,provider:"azure-openai"},"azure/text-embedding-3-large":{input:.13,output:0,provider:"azure-openai"},"gemini-pro":{input:.5,output:1.5,provider:"gemini"},"gemini-1.0-pro":{input:.5,output:1.5,provider:"gemini"},"gemini-1.5-pro":{input:3.5,output:10.5,provider:"gemini"},"gemini-1.5-pro-latest":{input:3.5,output:10.5,provider:"gemini"},"gemini-1.5-flash":{input:.075,output:.3,provider:"gemini"},"gemini-1.5-flash-latest":{input:.075,output:.3,provider:"gemini"},"gemini-2.0-flash-exp":{input:.075,output:.3,provider:"gemini"},"gemini-ultra":{input:7,output:21,provider:"gemini"},"gemini-1.0-ultra":{input:7,output:21,provider:"gemini"},"text-embedding-004":{input:.025,output:0,provider:"gemini"}},d=class c{records=[];alerts=[];maxRecords;alertCheckInterval;constructor(t=1e4){this.maxRecords=t}static calculateCost(t,r){let e=m[t];if(!e)return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"};let i=r.promptTokens/1e6*e.input,o=r.completionTokens/1e6*e.output;return{inputCost:i,outputCost:o,totalCost:i+o,currency:"USD"}}static getCostPerToken(t){let r=m[t];return r?{input:r.input/1e6,output:r.output/1e6}:{input:0,output:0}}recordUsage(t,r,e,i,o){let n=c.calculateCost(r,e),p={timestamp:new Date,provider:t,model:r,usage:e,cost:n,requestId:i,metadata:o};return this.records.push(p),this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords)),this.checkAlerts(),n}getSummary(t){let r=new Date,e=this.getPeriodStart(r,t),i=r,o=this.records.filter(s=>s.timestamp>=e&&s.timestamp<=i),n={claude:0,openai:0,ollama:0,openrouter:0,bedrock:0,"azure-openai":0,gemini:0},p={},u=0,l=0;for(let s of o)u+=s.cost.totalCost,l+=s.usage.totalTokens,n[s.provider]+=s.cost.totalCost,p[s.model]=(p[s.model]||0)+s.cost.totalCost;return{period:t,periodStart:e,periodEnd:i,totalCost:u,byProvider:n,byModel:p,totalTokens:l,totalRequests:o.length}}getCurrentCost(t){return this.getSummary(t).totalCost}getTotalTokens(t){return this.getSummary(t).totalTokens}getUsageByProvider(t,r="all"){let e=this.getPeriodStart(new Date,r),i=this.records.filter(u=>u.provider===t&&u.timestamp>=e),o={},n=0,p=0;for(let u of i)n+=u.cost.totalCost,p+=u.usage.totalTokens,o[u.model]||(o[u.model]={cost:0,tokens:0,requests:0}),o[u.model].cost+=u.cost.totalCost,o[u.model].tokens+=u.usage.totalTokens,o[u.model].requests+=1;return{totalCost:n,totalTokens:p,totalRequests:i.length,models:o}}addAlert(t,r,e){let i=`alert-${Date.now()}-${v().slice(0,12)}`;return this.alerts.push({threshold:t,period:r,onThreshold:e,active:!0}),this.alertCheckInterval||(this.alertCheckInterval=setInterval(()=>this.checkAlerts(),6e4)),i}removeAlert(t){return t>=0&&t<this.alerts.length?(this.alerts.splice(t,1),this.alerts.length===0&&this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0),!0):!1}getRecords(){return[...this.records]}importRecords(t){for(let r of t)r.timestamp=new Date(r.timestamp),this.records.push(r);this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords))}clear(){this.records=[]}getRecentRequests(t=10){return this.records.slice(-t)}estimateCost(t,r,e){return c.calculateCost(t,{promptTokens:r,completionTokens:e,totalTokens:r+e})}wouldExceedLimit(t,r,e,i,o){let n=this.getCurrentCost(o),p=this.estimateCost(t,r,e);return n+p.totalCost>i}dispose(){this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}getPeriodStart(t,r){let e=new Date(t);switch(r){case"minute":e.setSeconds(0,0),e.setMinutes(e.getMinutes()-1);break;case"hour":e.setMinutes(0,0,0),e.setHours(e.getHours()-1);break;case"day":e.setHours(0,0,0,0);break;case"week":e.setHours(0,0,0,0),e.setDate(e.getDate()-7);break;case"month":e.setHours(0,0,0,0),e.setDate(1);break;case"all":return new Date(0)}return e}checkAlerts(){for(let t of this.alerts){if(!t.active)continue;let r=this.getSummary(t.period);if(r.totalCost>=t.threshold){t.active=!1;try{t.onThreshold(r)}catch(e){console.error("Cost alert callback error:",e)}}}}},a;function h(){return a||(a=new d),a}function b(){a&&(a.dispose(),a=void 0)}export{m as a,d as b,h as c,b as d};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.
|
|
2
|
-
import{b as C,d as P}from"./chunk-RZDMSTAQ.js";import{a as T}from"./chunk-PHJK33IV.js";import{c as S}from"./chunk-BTPDHALG.js";import{a as w,c as $}from"./chunk-DEJW6GYF.js";import{a as b,d as M}from"./chunk-3BDZSWCA.js";$();M();import{randomUUID as D}from"crypto";var x={topology:"hierarchical",maxConcurrentSkills:10,maxConcurrentModels:3,timeout:3e5,continueOnFailure:!0,retry:{maxRetries:2,retryDelayMs:1e3}},R=class{config;learner;skillValidator=null;workers=new Map;taskQueue=[];isRunning=!1;constructor(e,t){this.config={...x,...e},this.learner=t}setSkillValidator(e){this.skillValidator=e}async validateSkillsParallel(e,t,i){let s=Date.now(),a=i?.trustTier??3,n=i?.validationLevel??"eval",c=this.determineTopology(e.length,t.length),r=this.createValidationTasks(e,t,a,n),o=await this.executeTasksParallel(r,c),l=new Map;for(let u of o){let p=l.get(u.skill)||[];p.push(u),l.set(u.skill,p)}return await this.recordOutcomesToLearner(o,a,n),l}async validateSkillCrossModel(e,t,i){return(await this.validateSkillsParallel([e],t,i)).get(e)||[]}getSummary(e){let t=[],i=new Map,s=new Map;for(let[c,r]of e){i.set(c,r);for(let o of r){t.push(o);let l=s.get(o.model)||[];l.push(o),s.set(o.model,l)}}let a=t.filter(c=>c.errors.length===0&&c.evalPassRate>=.9).length,n=t.reduce((c,r)=>c+r.durationMs,0);return{totalSkills:i.size,totalModels:s.size,successCount:a,failureCount:t.length-a,overallPassRate:t.length>0?a/t.length:0,totalDurationMs:n,avgDurationMs:t.length>0?n/t.length:0,topology:this.config.topology,bySkill:i,byModel:s,results:t}}determineTopology(e,t){if(this.config.topology){let i=e*t;return i>20&&this.config.topology==="mesh"&&console.warn(`[SwarmSkillValidator] Large workload (${i} tasks) may be more efficient with hierarchical topology`),this.config.topology}return e>5||e>t*2?"hierarchical":t>5&&e<=3?"mesh":"hierarchical"}createValidationTasks(e,t,i,s){let a=[];for(let n of e)for(let c of t)a.push({id:`${n}-${c}-${Date.now()}-${D().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+b()*100,s=.85+b()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=w(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function A(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as L,writeFileSync as E,existsSync as N}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}learner;manifestPath;config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,V)=>v+V,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!N(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(L(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},E(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
|
|
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 C,d as P}from"./chunk-OKGK7DBT.js";import{a as T}from"./chunk-X73CRYF4.js";import{c as S}from"./chunk-BQT4J3BD.js";import{a as w,c as $}from"./chunk-KNL3QWVA.js";import{a as b,d as M}from"./chunk-I4E6CLC4.js";$();M();import{randomUUID as D}from"crypto";var x={topology:"hierarchical",maxConcurrentSkills:10,maxConcurrentModels:3,timeout:3e5,continueOnFailure:!0,retry:{maxRetries:2,retryDelayMs:1e3}},R=class{config;learner;skillValidator=null;workers=new Map;taskQueue=[];isRunning=!1;constructor(e,t){this.config={...x,...e},this.learner=t}setSkillValidator(e){this.skillValidator=e}async validateSkillsParallel(e,t,i){let s=Date.now(),a=i?.trustTier??3,n=i?.validationLevel??"eval",c=this.determineTopology(e.length,t.length),r=this.createValidationTasks(e,t,a,n),o=await this.executeTasksParallel(r,c),l=new Map;for(let u of o){let p=l.get(u.skill)||[];p.push(u),l.set(u.skill,p)}return await this.recordOutcomesToLearner(o,a,n),l}async validateSkillCrossModel(e,t,i){return(await this.validateSkillsParallel([e],t,i)).get(e)||[]}getSummary(e){let t=[],i=new Map,s=new Map;for(let[c,r]of e){i.set(c,r);for(let o of r){t.push(o);let l=s.get(o.model)||[];l.push(o),s.set(o.model,l)}}let a=t.filter(c=>c.errors.length===0&&c.evalPassRate>=.9).length,n=t.reduce((c,r)=>c+r.durationMs,0);return{totalSkills:i.size,totalModels:s.size,successCount:a,failureCount:t.length-a,overallPassRate:t.length>0?a/t.length:0,totalDurationMs:n,avgDurationMs:t.length>0?n/t.length:0,topology:this.config.topology,bySkill:i,byModel:s,results:t}}determineTopology(e,t){if(this.config.topology){let i=e*t;return i>20&&this.config.topology==="mesh"&&console.warn(`[SwarmSkillValidator] Large workload (${i} tasks) may be more efficient with hierarchical topology`),this.config.topology}return e>5||e>t*2?"hierarchical":t>5&&e<=3?"mesh":"hierarchical"}createValidationTasks(e,t,i,s){let a=[];for(let n of e)for(let c of t)a.push({id:`${n}-${c}-${Date.now()}-${D().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+b()*100,s=.85+b()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=w(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function A(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as L,writeFileSync as E,existsSync as N}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}learner;manifestPath;config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,V)=>v+V,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!N(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(L(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},E(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
|
|
3
3
|
|
|
4
4
|
> ${c} Generated: ${e.timestamp.toISOString()}
|
|
5
5
|
> Run ID: ${e.runId}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.
|
|
2
|
-
import{d as l,f 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{d as l,f as i}from"./chunk-6MONUYQ5.js";import{a as r,c as g}from"./chunk-KNL3QWVA.js";g();var c=class extends i{config={name:"qe/tests/schedule",description:"Schedule and execute tests using phase-based pipeline with git-aware selection and flaky tracking. Runs tests in phases (unit, integration, e2e), selects affected tests from git changes, and tracks flaky tests.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{cwd:{type:"string",description:"Working directory for test execution (defaults to project root)"},gitRef:{type:"string",description:'Git ref to compare for affected test selection (e.g., "main", "HEAD~3")'},useGitAware:{type:"boolean",description:"Enable git-aware test selection to only run affected tests",default:!0},trackFlaky:{type:"boolean",description:"Enable flaky test tracking and quarantine",default:!0}}}}async execute(s,o){try{let{runTestPipeline:n}=await import("./test-scheduling-R5EQ2XGV.js"),d=await l(o),t=await n({cwd:s.cwd||process.cwd(),memory:d,baseRef:s.gitRef,flakyHistoryPath:s.trackFlaky!==!1?".agentic-qe/flaky-history.json":void 0,runAllTests:s.useGitAware===!1}),u=t.phaseResults.reduce((e,a)=>e+a.totalTests,0),f=t.phaseResults.reduce((e,a)=>e+a.passed,0),p=t.phaseResults.reduce((e,a)=>e+a.failed,0);return{success:!0,data:{pipelineId:o.requestId,phases:t.phaseResults.map(e=>({phaseId:e.phaseId,phaseName:e.phaseName,totalTests:e.totalTests,passed:e.passed,failed:e.failed,passRate:e.passRate,durationMs:e.durationMs})),gitAware:{enabled:!t.ranAllTests,selectedTests:t.selectedTests.length,gitRef:s.gitRef},flakyTracking:{enabled:s.trackFlaky!==!1},totalDuration:t.totalDurationMs,ranAllTests:t.ranAllTests,summary:`Executed ${t.phaseResults.length} phases, ${u} tests (${f} passed, ${p} failed) in ${t.totalDurationMs}ms`}}}catch(n){return{success:!1,error:r(n)}}}};export{c as a};
|
|
@@ -1,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{o as me}from"./chunk-BKF3E3UJ.js";import{b as w,c as E,d as A,f as j,k as de,o as ue}from"./chunk-IXOGBA7C.js";import{a as Re,b as _,d as ee}from"./chunk-RZDMSTAQ.js";import{a as v}from"./chunk-PHJK33IV.js";import{c as b}from"./chunk-BTPDHALG.js";import{a as d,b as L,c as P}from"./chunk-DEJW6GYF.js";import{i as I}from"./chunk-E7N6CRFV.js";import{a as T,b as z}from"./chunk-NZB2JE2D.js";import{a as le,d as Te}from"./chunk-HMIRBSTI.js";import{f as Ce}from"./chunk-HSR7EHVN.js";var k={cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},environment:process.env.AQE_ENV||"all",batchSize:1e3,sources:[{name:"qe-patterns",cloudTable:"aqe.qe_patterns",localTable:"qe_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","embedding","sync_version"],transforms:{reusable:"boolean-to-int"}},{name:"sona-patterns",cloudTable:"aqe.sona_patterns",localTable:"sona_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],transforms:{is_active:"boolean-to-int",requires_fine_tuning:"boolean-to-int"}},{name:"goap-actions",cloudTable:"aqe.goap_actions",localTable:"goap_actions",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{duration_estimate:"estimated_duration_ms"}},{name:"goap-plans",cloudTable:"aqe.goap_plans",localTable:"goap_plans",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{estimated_duration:"estimated_duration_ms"}},{name:"memory-entries",cloudTable:"aqe.memory_entries",localTable:"kv_store",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}},{name:"learning-experiences",cloudTable:"aqe.learning_experiences",localTable:"captured_experiences",enabled:!0,priority:"high",mode:"append",dropColumns:["id","source_env","sync_version"],columnMap:{agent_id:"agent",task_id:"task",task_type:"domain",state:"result_json",action:"steps_json",reward:"quality",next_state:"routing_json",episode_id:"tags",created_at:"started_at"}},{name:"qlearning-patterns",cloudTable:"aqe.qlearning_patterns",localTable:"rl_q_values",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{state:"state_key",action:"action_key",last_update:"updated_at"}},{name:"routing-outcomes",cloudTable:"aqe.routing_outcomes",localTable:"routing_outcomes",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version"]},{name:"qe-trajectories",cloudTable:"aqe.qe_trajectories",localTable:"qe_trajectories",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version","embedding"]},{name:"dream-insights",cloudTable:"aqe.dream_insights",localTable:"dream_insights",enabled:!0,priority:"low",mode:"append",dropColumns:["source_env","sync_version"]},{name:"claude-flow-memory",cloudTable:"aqe.claude_flow_memory",localTable:"kv_store",enabled:!0,priority:"low",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}}]},Pe={TEXT:"TEXT",INTEGER:"INTEGER",REAL:"REAL",BLOB:"BYTEA",NULL:"NULL"},x={local:{v3MemoryDb:"./.agentic-qe/memory.db",rootMemoryDb:"./.agentic-qe/memory.db",claudeFlowMemory:"./.claude-flow/memory/store.json",claudeFlowDaemon:"./.claude-flow/daemon-state.json",claudeFlowMetrics:"./.claude-flow/metrics/",intelligenceJson:"./.ruvector/intelligence.json",swarmMemoryDb:"./.swarm/memory.db",v2PatternsDb:""},cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},sync:{mode:"incremental",interval:"1h",batchSize:1e3,conflictResolution:"newer-wins",sourcePriority:{qePatterns:1,sonaPatterns:2,goapActions:3,kvStore:4,experiences:5,claudeFlowMemory:6,intelligenceJson:7},sources:[{name:"root-qe-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_patterns",priority:"high",mode:"incremental",query:"SELECT id, pattern_type, qe_domain, domain, name, description, confidence, usage_count, success_rate, quality_score, tier, template_json, context_json, successful_uses, created_at, updated_at, last_used_at, tokens_used, input_tokens, output_tokens, latency_ms, reusable, reuse_count, average_token_savings, total_tokens_saved FROM qe_patterns",enabled:!0},{name:"root-sona-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.sona_patterns",priority:"high",mode:"incremental",query:"SELECT * FROM sona_patterns",enabled:!0},{name:"root-goap-actions",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_actions",priority:"high",mode:"incremental",query:"SELECT * FROM goap_actions",enabled:!0},{name:"root-kv-store",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.memory_entries",priority:"high",mode:"incremental",query:"SELECT key, namespace as partition, CASE WHEN json_valid(value) THEN value ELSE json_quote(value) END as value, created_at, expires_at FROM kv_store WHERE json_valid(value) OR json_valid(json_quote(value))",enabled:!0},{name:"root-captured-experiences",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.learning_experiences",priority:"high",mode:"append",query:"SELECT agent as agent_id, task as task_id, domain as task_type, COALESCE(result_json, '{}') as state, COALESCE(steps_json, '{}') as action, quality as reward, COALESCE(routing_json, '{}') as next_state, tags as episode_id, started_at as created_at FROM captured_experiences",enabled:!0},{name:"root-goap-plans",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_plans",priority:"medium",mode:"incremental",query:"SELECT id, goal_id, action_sequence as sequence, initial_state, goal_state, action_sequence, total_cost, estimated_duration_ms as estimated_duration, status, created_at, completed_at FROM goap_plans",enabled:!0},{name:"root-rl-q-values",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qlearning_patterns",priority:"medium",mode:"incremental",query:"SELECT DISTINCT state_key as state, action_key as action, q_value, visits, updated_at as last_update, created_at FROM rl_q_values GROUP BY state_key, action_key",enabled:!0},{name:"root-routing-outcomes",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.routing_outcomes",priority:"medium",mode:"append",query:"SELECT * FROM routing_outcomes",enabled:!0},{name:"root-qe-trajectories",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_trajectories",priority:"medium",mode:"append",query:"SELECT * FROM qe_trajectories",enabled:!0},{name:"root-dream-insights",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.dream_insights",priority:"low",mode:"append",query:"SELECT * FROM dream_insights",enabled:!0},{name:"claude-flow-memory",type:"json",path:"./.claude-flow/memory/store.json",targetTable:"aqe.claude_flow_memory",priority:"medium",mode:"full",enabled:!0},{name:"intelligence-qlearning",type:"json",path:"./.ruvector/intelligence.json",targetTable:"aqe.qlearning_patterns",priority:"low",mode:"full",jsonPath:"$.qvalues",enabled:!0}]},environment:process.env.AQE_ENV||"devpod"};z();A();ee();P();v();import*as te from"fs";import*as ge from"path";var F=b.create("sqlite-reader"),W=class{name;type="sqlite";db=null;config;dbPath;constructor(e){this.config=e,this.name=e.source.name,this.dbPath=ge.resolve(e.baseDir,e.source.path)}async initialize(){if(!this.db){if(!te.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}`);try{this.db=T(this.dbPath,{readonly:!0}),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),console.log(`[SQLiteReader:${this.name}] Initialized: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${d(e)}`)}}}async readAll(){if(!this.db)throw new Error("Reader not initialized");let e=this.config.source.query||`SELECT * FROM ${w(this.getTableName())}`;try{return this.tableExists(this.getTableName())?this.db.prepare(e).all().map(r=>this.transformRecord(r)):(console.warn(`[SQLiteReader:${this.name}] Table not found, returning empty`),[])}catch(t){throw new Error(`Failed to read from ${this.name}: ${d(t)}`)}}async readChanged(e){if(!this.db)throw new Error("Reader not initialized");let t=this.findTimestampColumn();if(!t)return console.warn(`[SQLiteReader:${this.name}] No timestamp column found, falling back to readAll`),this.readAll();let n=this.getTableName();if(!this.tableExists(n))return[];let r=e.toISOString(),i=`SELECT * FROM ${w(n)} WHERE ${t} > ?`;try{return this.db.prepare(i).all(r).map(a=>this.transformRecord(a))}catch{return console.warn(`[SQLiteReader:${this.name}] Changed query failed, falling back to readAll`),this.readAll()}}async count(){if(!this.db)throw new Error("Reader not initialized");let e=this.getTableName();if(!this.tableExists(e))return 0;try{return this.db.prepare(`SELECT COUNT(*) as count FROM ${w(e)}`).get().count}catch(t){return F.debug("Record count query failed",{table:e,error:d(t)}),0}}async close(){this.db&&(this.db.close(),this.db=null,console.log(`[SQLiteReader:${this.name}] Closed`))}getTableName(){let e=this.config.source.query;if(e){let r=e.match(/FROM\s+(\w+)/i);if(r)return r[1]}let n=this.config.source.targetTable.split(".");return n[n.length-1]}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch(t){return F.debug("Table existence check failed",{table:e,error:t instanceof Error?t.message:String(t)}),!1}}findTimestampColumn(){if(!this.db)return null;let e=this.getTableName(),t=["updated_at","created_at","timestamp","last_used_at","modified_at"];try{let i=this.db.prepare(`PRAGMA table_info(${w(e)})`).all().map(o=>o.name.toLowerCase());for(let o of t)if(i.includes(o))return o}catch(n){return F.debug("Timestamp column detection failed",{table:e,error:n instanceof Error?n.message:String(n)}),null}return null}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t)){if(typeof r=="string"&&this.looksLikeJson(r))try{t[n]=_(r)}catch(i){F.debug("JSON parse failed for record field",{key:n,error:i instanceof Error?i.message:String(i)})}if(n.endsWith("_at")&&typeof r=="number"&&(t[n]=new Date(r).toISOString()),r instanceof Buffer)if(n.includes("embedding")){let i=e.dimension||384;t[n]=Array.from(new Float32Array(r.buffer,r.byteOffset,i))}else t[n]=r.toString("base64")}return t}looksLikeJson(e){if(!e)return!1;let t=e.trim();return t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")}getInfo(){let e=te.existsSync(this.dbPath),t=[];if(e&&this.db)try{t=this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all().map(r=>r.name)}catch(n){console.debug("[SQLiteReader] Table listing error:",n instanceof Error?n.message:n)}return{path:this.dbPath,exists:e,tables:t}}};function re(l){return new W(l)}var he=Ce(Re(),1);P();import{randomUUID as ve}from"crypto";import*as C from"fs";import*as pe from"path";var U=class{name;type="json";config;filePath;data=null;fileModTime=null;constructor(e){this.config=e,this.name=e.source.name,this.filePath=pe.resolve(e.baseDir,e.source.path)}async initialize(){if(!C.existsSync(this.filePath)){console.warn(`[JSONReader:${this.name}] File not found: ${this.filePath}`),this.data=[];return}let e=C.statSync(this.filePath);this.fileModTime=e.mtime,console.log(`[JSONReader:${this.name}] Initialized: ${this.filePath}`)}async readAll(){if(!C.existsSync(this.filePath))return[];try{let e=C.readFileSync(this.filePath,"utf-8"),t=he.default.parse(e);return this.extractRecords(t).map(r=>this.transformRecord(r))}catch(e){return console.error(`[JSONReader:${this.name}] Failed to read: ${d(e)}`),[]}}async readChanged(e){return C.existsSync(this.filePath)?C.statSync(this.filePath).mtime<=e?[]:this.readAll():[]}async count(){return(await this.readAll()).length}async close(){this.data=null,this.fileModTime=null,console.log(`[JSONReader:${this.name}] Closed`)}extractRecords(e){return this.config.source.jsonPath?this.extractByPath(e,this.config.source.jsonPath):this.name.includes("claude-flow-memory")?this.extractClaudeFlowMemory(e):this.name.includes("intelligence")||this.name.includes("qlearning")?this.extractIntelligence(e):this.name.includes("daemon")?this.extractDaemonState(e):Array.isArray(e)?e:typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]}extractByPath(e,t){let n=t.replace(/^\$\./,"").split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return[];return Array.isArray(r)?r:typeof r=="object"&&r!==null?Object.entries(r).map(([i,o])=>({state:i,...typeof o=="object"?o:{value:o}})):[]}extractClaudeFlowMemory(e){if(!e||typeof e!="object")return[];let t=[],n=e;for(let[r,i]of Object.entries(n)){if(r.startsWith("_"))continue;let o="general";r.includes("adr")?o="adr-analysis":r.includes("agent")?o="agent-patterns":r.includes("pattern")?o="patterns":r.includes("metric")&&(o="metrics"),t.push({key:r,value:typeof i=="object"?i:{data:i},category:o})}return t}extractIntelligence(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.qvalues&&typeof n.qvalues=="object"){let r=n.qvalues;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null)for(let[s,a]of Object.entries(o)){let c=typeof a=="object"?a:{value:a};t.push({state:i,action:s,q_value:c.value||c.q_value||0,visits:c.visits||0,last_update:c.lastUpdate||c.last_update})}}if(n.memories&&Array.isArray(n.memories)){for(let r of n.memories)if(typeof r=="object"&&r!==null){let i=r;t.push({id:i.id||`mem_${Date.now()}_${ve().slice(0,12)}`,memory_type:i.type||"file_access",content:i.content||i.path,embedding:i.embedding,metadata:i.metadata,timestamp:i.timestamp})}}return t}extractDaemonState(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.workers&&typeof n.workers=="object"){let r=n.workers;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null){let s=o;t.push({worker_type:i,run_count:s.runCount||s.runs||0,success_count:s.successCount||s.successes||0,failure_count:s.failureCount||s.failures||0,avg_duration_ms:s.avgDuration||s.averageDurationMs,last_run:s.lastRun})}}return t}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t))(n.includes("timestamp")||n.endsWith("_at")||n==="last_update")&&(typeof r=="number"?t[n]=new Date(r).toISOString():typeof r=="string"&&!isNaN(Date.parse(r))&&(t[n]=new Date(r).toISOString())),typeof r=="object"&&r!==null&&!Array.isArray(r)&&["value","metadata","embedding"].includes(n);return t.created_at||(t.created_at=new Date().toISOString()),t}getInfo(){let e=C.existsSync(this.filePath),t=0,n=null;if(e){let r=C.statSync(this.filePath);t=r.size,n=r.mtime}return{path:this.filePath,exists:e,modTime:n,size:t}}};function ne(l){return new U(l)}v();import{spawn as _e}from"child_process";import{createConnection as xe}from"net";var Ae=b.create("tunnel-manager");function fe(l){try{let e=new URL(l);return e.password&&(e.password="***"),e.toString()}catch(e){return Ae.debug("URL parse failed during redaction, using regex fallback",{error:e instanceof Error?e.message:String(e)}),l.replace(/:\/\/([^:]+):([^@]+)@/,"://$1:***@")}}var M=class{process=null;connection=null;config;constructor(e){this.config=e}checkPort(e,t,n=2e3){return new Promise(r=>{let i=xe({host:e,port:t}),o=setTimeout(()=>{i.destroy(),r(!1)},n);i.on("connect",()=>{clearTimeout(o),i.destroy(),r(!0)}),i.on("error",()=>{clearTimeout(o),i.destroy(),r(!1)})})}async start(){return this.process&&this.connection?(console.log("[TunnelManager] Tunnel already running"),this.connection):await this.checkPort("localhost",this.config.tunnelPort)?(console.log(`[TunnelManager] External tunnel detected on port ${this.config.tunnelPort}, reusing`),this.connection={host:"localhost",port:this.config.tunnelPort,startedAt:new Date},this.connection):new Promise((t,n)=>{let r=["compute","start-iap-tunnel",this.config.instance,"5432",`--local-host-port=localhost:${this.config.tunnelPort}`,`--zone=${this.config.zone}`,`--project=${this.config.project}`];console.log(`[TunnelManager] Starting IAP tunnel: gcloud ${r.join(" ")}`),this.process=_e("gcloud",r,{stdio:["ignore","pipe","pipe"]});let i=!1,o="",s=!1;this.process.stderr?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`),["Listening on port","tunnel is running","Testing if tunnel connection works"].some(m=>c.includes(m))&&!i&&!s&&(s=!0,setTimeout(async()=>{for(let g=0;g<10;g++){if(console.log(`[TunnelManager] Checking port connectivity (attempt ${g+1}/10)...`),await this.checkPort("localhost",this.config.tunnelPort)){i=!0,this.connection={host:"localhost",port:this.config.tunnelPort,pid:this.process?.pid,startedAt:new Date},console.log(`[TunnelManager] Tunnel ready on port ${this.config.tunnelPort}`),t(this.connection);return}await new Promise(y=>setTimeout(y,1e3))}s=!1},2e3)),o+=c}),this.process.stdout?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`)}),this.process.on("error",a=>{console.error(`[TunnelManager] Process error: ${a.message}`),i||n(new Error(`Failed to start tunnel: ${a.message}`))}),this.process.on("close",a=>{console.log(`[TunnelManager] Process closed with code ${a}`),this.process=null,this.connection=null,i||n(new Error(`Tunnel process exited with code ${a}: ${o}`))}),setTimeout(()=>{i||(this.stop(),n(new Error("Tunnel connection timeout")))},6e4)})}async stop(){this.process&&(console.log("[TunnelManager] Stopping tunnel"),this.process.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),this.process&&this.process.kill("SIGKILL"),this.process=null,this.connection=null)}isActive(){return this.process!==null&&this.connection!==null}getConnection(){return this.connection}getConnectionString(){if(!this.connection)throw new Error("Tunnel not active");let{database:e,user:t}=this.config,n=process.env.PGPASSWORD||"",r=this.connection.host,i=this.connection.port;return`postgresql://${t}:${n}@${r}:${i}/${e}`}getRedactedConnectionString(){return fe(this.getConnectionString())}};function ke(l){return new M(l)}var B=class{connection=null;connectionString;constructor(e){this.connectionString=e}async start(){let e=new URL(this.connectionString);return this.connection={host:e.hostname,port:parseInt(e.port||"5432",10),startedAt:new Date},this.connection}async stop(){this.connection=null}isActive(){return this.connection!==null}getConnection(){return this.connection}getConnectionString(){return this.connectionString}getRedactedConnectionString(){return fe(this.connectionString)}};function $(l){return l.connectionString?new B(l.connectionString):new M(l)}A();P();v();import{createRequire as Me}from"module";var N=b.create("postgres-writer"),$e=Me(import.meta.url),J=class{client=null;config;inTransaction=!1;connected=!1;constructor(e){this.config=e}async connect(){if(this.connected)return;this.config.tunnelManager.isActive()||await this.config.tunnelManager.start();let e=this.config.tunnelManager.getConnection();if(!e)throw new Error("No tunnel connection available");let t;try{t=$e("pg")}catch(o){N.debug("pg module not installed, using mock mode",{error:o instanceof Error?o.message:String(o)}),console.warn("[PostgresWriter] pg module not installed, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let n=t.default,r=t.Client||n?.Client;if(!r){console.warn("[PostgresWriter] pg.Client not found in module, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let i={host:e.host,port:e.port,database:this.config.cloud.database,user:this.config.cloud.user,password:process.env.PGPASSWORD||"",connectionTimeoutMillis:this.config.connectionTimeout||1e4};this.client=new r(i),await this.client.connect(),this.connected=!0,console.log(`[PostgresWriter] Connected to ${e.host}:${e.port}/${this.config.cloud.database}`)}async beginTransaction(){if(!this.client)throw new Error("Not connected");await this.client.query("BEGIN"),this.inTransaction=!0}async commit(){if(!this.client||!this.inTransaction)throw new Error("No active transaction");await this.client.query("COMMIT"),this.inTransaction=!1}async rollback(){!this.client||!this.inTransaction||(await this.client.query("ROLLBACK"),this.inTransaction=!1)}async upsert(e,t,n){if(!this.client)throw new Error("Not connected");if(t.length===0)return 0;let r=t[0],i=Object.keys(r),o=n?.conflictColumns||this.inferConflictColumns(e,i),s=n?.updateColumns||i.filter(u=>!o.includes(u)),a=0,c=100;for(let u=0;u<t.length;u+=c){let p=t.slice(u,u+c);try{let m=await this.upsertBatch(e,p,i,o,s,n?.skipIfExists);a+=m}catch(m){let g=Math.floor(u/c)+1,h=Math.ceil(t.length/c);N.debug(`Batch ${g}/${h} failed for ${e}, retrying individually`,{error:d(m)});let y=0;for(let f of p)try{let S=await this.upsertBatch(e,[f],i,o,s,n?.skipIfExists);y+=S}catch(S){let R=f.id||f.key||"?";N.debug(`Skipped record ${String(R).slice(0,50)} in ${e}`,{error:d(S)})}a+=y,y<p.length&&console.warn(`[PostgresWriter] Batch ${g}/${h} for ${e}: ${y}/${p.length} recovered (${p.length-y} skipped)`)}}return a}async upsertBatch(e,t,n,r,i,o){if(!this.client)return 0;let s=[],a=[],c=1;for(let f of t){let S=[];for(let R of n){let Ee=f[R];S.push(`$${c++}`),a.push(this.serializeValue(Ee,R))}s.push(`(${S.join(", ")})`)}let u=E(e),p=n.map(E),m=r.map(E),g=i.map(E),h="";if(m.length>0){if(o)h=`ON CONFLICT (${m.join(", ")}) DO NOTHING`;else if(g.length>0){let f=g.map(S=>`${S} = EXCLUDED.${S}`).join(", ");h=`ON CONFLICT (${m.join(", ")}) DO UPDATE SET ${f}`}}let y=`
|
|
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{o as me}from"./chunk-M4HDBRVJ.js";import{b as w,c as E,d as A,f as j,k as de,o as ue}from"./chunk-UE3XXKLN.js";import{a as Re,b as _,d as ee}from"./chunk-OKGK7DBT.js";import{a as v}from"./chunk-X73CRYF4.js";import{c as b}from"./chunk-BQT4J3BD.js";import{a as d,b as L,c as P}from"./chunk-KNL3QWVA.js";import{i as I}from"./chunk-MJBXQXSX.js";import{a as T,b as z}from"./chunk-ZCNVFULO.js";import{a as le,d as Te}from"./chunk-66GIKUI2.js";import{f as Ce}from"./chunk-55JPAF56.js";var k={cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},environment:process.env.AQE_ENV||"all",batchSize:1e3,sources:[{name:"qe-patterns",cloudTable:"aqe.qe_patterns",localTable:"qe_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","embedding","sync_version"],transforms:{reusable:"boolean-to-int"}},{name:"sona-patterns",cloudTable:"aqe.sona_patterns",localTable:"sona_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],transforms:{is_active:"boolean-to-int",requires_fine_tuning:"boolean-to-int"}},{name:"goap-actions",cloudTable:"aqe.goap_actions",localTable:"goap_actions",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{duration_estimate:"estimated_duration_ms"}},{name:"goap-plans",cloudTable:"aqe.goap_plans",localTable:"goap_plans",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{estimated_duration:"estimated_duration_ms"}},{name:"memory-entries",cloudTable:"aqe.memory_entries",localTable:"kv_store",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}},{name:"learning-experiences",cloudTable:"aqe.learning_experiences",localTable:"captured_experiences",enabled:!0,priority:"high",mode:"append",dropColumns:["id","source_env","sync_version"],columnMap:{agent_id:"agent",task_id:"task",task_type:"domain",state:"result_json",action:"steps_json",reward:"quality",next_state:"routing_json",episode_id:"tags",created_at:"started_at"}},{name:"qlearning-patterns",cloudTable:"aqe.qlearning_patterns",localTable:"rl_q_values",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{state:"state_key",action:"action_key",last_update:"updated_at"}},{name:"routing-outcomes",cloudTable:"aqe.routing_outcomes",localTable:"routing_outcomes",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version"]},{name:"qe-trajectories",cloudTable:"aqe.qe_trajectories",localTable:"qe_trajectories",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version","embedding"]},{name:"dream-insights",cloudTable:"aqe.dream_insights",localTable:"dream_insights",enabled:!0,priority:"low",mode:"append",dropColumns:["source_env","sync_version"]},{name:"claude-flow-memory",cloudTable:"aqe.claude_flow_memory",localTable:"kv_store",enabled:!0,priority:"low",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}}]},Pe={TEXT:"TEXT",INTEGER:"INTEGER",REAL:"REAL",BLOB:"BYTEA",NULL:"NULL"},x={local:{v3MemoryDb:"./.agentic-qe/memory.db",rootMemoryDb:"./.agentic-qe/memory.db",claudeFlowMemory:"./.claude-flow/memory/store.json",claudeFlowDaemon:"./.claude-flow/daemon-state.json",claudeFlowMetrics:"./.claude-flow/metrics/",intelligenceJson:"./.ruvector/intelligence.json",swarmMemoryDb:"./.swarm/memory.db",v2PatternsDb:""},cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},sync:{mode:"incremental",interval:"1h",batchSize:1e3,conflictResolution:"newer-wins",sourcePriority:{qePatterns:1,sonaPatterns:2,goapActions:3,kvStore:4,experiences:5,claudeFlowMemory:6,intelligenceJson:7},sources:[{name:"root-qe-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_patterns",priority:"high",mode:"incremental",query:"SELECT id, pattern_type, qe_domain, domain, name, description, confidence, usage_count, success_rate, quality_score, tier, template_json, context_json, successful_uses, created_at, updated_at, last_used_at, tokens_used, input_tokens, output_tokens, latency_ms, reusable, reuse_count, average_token_savings, total_tokens_saved FROM qe_patterns",enabled:!0},{name:"root-sona-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.sona_patterns",priority:"high",mode:"incremental",query:"SELECT * FROM sona_patterns",enabled:!0},{name:"root-goap-actions",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_actions",priority:"high",mode:"incremental",query:"SELECT * FROM goap_actions",enabled:!0},{name:"root-kv-store",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.memory_entries",priority:"high",mode:"incremental",query:"SELECT key, namespace as partition, CASE WHEN json_valid(value) THEN value ELSE json_quote(value) END as value, created_at, expires_at FROM kv_store WHERE json_valid(value) OR json_valid(json_quote(value))",enabled:!0},{name:"root-captured-experiences",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.learning_experiences",priority:"high",mode:"append",query:"SELECT agent as agent_id, task as task_id, domain as task_type, COALESCE(result_json, '{}') as state, COALESCE(steps_json, '{}') as action, quality as reward, COALESCE(routing_json, '{}') as next_state, tags as episode_id, started_at as created_at FROM captured_experiences",enabled:!0},{name:"root-goap-plans",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_plans",priority:"medium",mode:"incremental",query:"SELECT id, goal_id, action_sequence as sequence, initial_state, goal_state, action_sequence, total_cost, estimated_duration_ms as estimated_duration, status, created_at, completed_at FROM goap_plans",enabled:!0},{name:"root-rl-q-values",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qlearning_patterns",priority:"medium",mode:"incremental",query:"SELECT DISTINCT state_key as state, action_key as action, q_value, visits, updated_at as last_update, created_at FROM rl_q_values GROUP BY state_key, action_key",enabled:!0},{name:"root-routing-outcomes",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.routing_outcomes",priority:"medium",mode:"append",query:"SELECT * FROM routing_outcomes",enabled:!0},{name:"root-qe-trajectories",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_trajectories",priority:"medium",mode:"append",query:"SELECT * FROM qe_trajectories",enabled:!0},{name:"root-dream-insights",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.dream_insights",priority:"low",mode:"append",query:"SELECT * FROM dream_insights",enabled:!0},{name:"claude-flow-memory",type:"json",path:"./.claude-flow/memory/store.json",targetTable:"aqe.claude_flow_memory",priority:"medium",mode:"full",enabled:!0},{name:"intelligence-qlearning",type:"json",path:"./.ruvector/intelligence.json",targetTable:"aqe.qlearning_patterns",priority:"low",mode:"full",jsonPath:"$.qvalues",enabled:!0}]},environment:process.env.AQE_ENV||"devpod"};z();A();ee();P();v();import*as te from"fs";import*as ge from"path";var F=b.create("sqlite-reader"),W=class{name;type="sqlite";db=null;config;dbPath;constructor(e){this.config=e,this.name=e.source.name,this.dbPath=ge.resolve(e.baseDir,e.source.path)}async initialize(){if(!this.db){if(!te.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}`);try{this.db=T(this.dbPath,{readonly:!0}),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),console.log(`[SQLiteReader:${this.name}] Initialized: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${d(e)}`)}}}async readAll(){if(!this.db)throw new Error("Reader not initialized");let e=this.config.source.query||`SELECT * FROM ${w(this.getTableName())}`;try{return this.tableExists(this.getTableName())?this.db.prepare(e).all().map(r=>this.transformRecord(r)):(console.warn(`[SQLiteReader:${this.name}] Table not found, returning empty`),[])}catch(t){throw new Error(`Failed to read from ${this.name}: ${d(t)}`)}}async readChanged(e){if(!this.db)throw new Error("Reader not initialized");let t=this.findTimestampColumn();if(!t)return console.warn(`[SQLiteReader:${this.name}] No timestamp column found, falling back to readAll`),this.readAll();let n=this.getTableName();if(!this.tableExists(n))return[];let r=e.toISOString(),i=`SELECT * FROM ${w(n)} WHERE ${t} > ?`;try{return this.db.prepare(i).all(r).map(a=>this.transformRecord(a))}catch{return console.warn(`[SQLiteReader:${this.name}] Changed query failed, falling back to readAll`),this.readAll()}}async count(){if(!this.db)throw new Error("Reader not initialized");let e=this.getTableName();if(!this.tableExists(e))return 0;try{return this.db.prepare(`SELECT COUNT(*) as count FROM ${w(e)}`).get().count}catch(t){return F.debug("Record count query failed",{table:e,error:d(t)}),0}}async close(){this.db&&(this.db.close(),this.db=null,console.log(`[SQLiteReader:${this.name}] Closed`))}getTableName(){let e=this.config.source.query;if(e){let r=e.match(/FROM\s+(\w+)/i);if(r)return r[1]}let n=this.config.source.targetTable.split(".");return n[n.length-1]}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch(t){return F.debug("Table existence check failed",{table:e,error:t instanceof Error?t.message:String(t)}),!1}}findTimestampColumn(){if(!this.db)return null;let e=this.getTableName(),t=["updated_at","created_at","timestamp","last_used_at","modified_at"];try{let i=this.db.prepare(`PRAGMA table_info(${w(e)})`).all().map(o=>o.name.toLowerCase());for(let o of t)if(i.includes(o))return o}catch(n){return F.debug("Timestamp column detection failed",{table:e,error:n instanceof Error?n.message:String(n)}),null}return null}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t)){if(typeof r=="string"&&this.looksLikeJson(r))try{t[n]=_(r)}catch(i){F.debug("JSON parse failed for record field",{key:n,error:i instanceof Error?i.message:String(i)})}if(n.endsWith("_at")&&typeof r=="number"&&(t[n]=new Date(r).toISOString()),r instanceof Buffer)if(n.includes("embedding")){let i=e.dimension||384;t[n]=Array.from(new Float32Array(r.buffer,r.byteOffset,i))}else t[n]=r.toString("base64")}return t}looksLikeJson(e){if(!e)return!1;let t=e.trim();return t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")}getInfo(){let e=te.existsSync(this.dbPath),t=[];if(e&&this.db)try{t=this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all().map(r=>r.name)}catch(n){console.debug("[SQLiteReader] Table listing error:",n instanceof Error?n.message:n)}return{path:this.dbPath,exists:e,tables:t}}};function re(l){return new W(l)}var he=Ce(Re(),1);P();import{randomUUID as ve}from"crypto";import*as C from"fs";import*as pe from"path";var U=class{name;type="json";config;filePath;data=null;fileModTime=null;constructor(e){this.config=e,this.name=e.source.name,this.filePath=pe.resolve(e.baseDir,e.source.path)}async initialize(){if(!C.existsSync(this.filePath)){console.warn(`[JSONReader:${this.name}] File not found: ${this.filePath}`),this.data=[];return}let e=C.statSync(this.filePath);this.fileModTime=e.mtime,console.log(`[JSONReader:${this.name}] Initialized: ${this.filePath}`)}async readAll(){if(!C.existsSync(this.filePath))return[];try{let e=C.readFileSync(this.filePath,"utf-8"),t=he.default.parse(e);return this.extractRecords(t).map(r=>this.transformRecord(r))}catch(e){return console.error(`[JSONReader:${this.name}] Failed to read: ${d(e)}`),[]}}async readChanged(e){return C.existsSync(this.filePath)?C.statSync(this.filePath).mtime<=e?[]:this.readAll():[]}async count(){return(await this.readAll()).length}async close(){this.data=null,this.fileModTime=null,console.log(`[JSONReader:${this.name}] Closed`)}extractRecords(e){return this.config.source.jsonPath?this.extractByPath(e,this.config.source.jsonPath):this.name.includes("claude-flow-memory")?this.extractClaudeFlowMemory(e):this.name.includes("intelligence")||this.name.includes("qlearning")?this.extractIntelligence(e):this.name.includes("daemon")?this.extractDaemonState(e):Array.isArray(e)?e:typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]}extractByPath(e,t){let n=t.replace(/^\$\./,"").split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return[];return Array.isArray(r)?r:typeof r=="object"&&r!==null?Object.entries(r).map(([i,o])=>({state:i,...typeof o=="object"?o:{value:o}})):[]}extractClaudeFlowMemory(e){if(!e||typeof e!="object")return[];let t=[],n=e;for(let[r,i]of Object.entries(n)){if(r.startsWith("_"))continue;let o="general";r.includes("adr")?o="adr-analysis":r.includes("agent")?o="agent-patterns":r.includes("pattern")?o="patterns":r.includes("metric")&&(o="metrics"),t.push({key:r,value:typeof i=="object"?i:{data:i},category:o})}return t}extractIntelligence(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.qvalues&&typeof n.qvalues=="object"){let r=n.qvalues;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null)for(let[s,a]of Object.entries(o)){let c=typeof a=="object"?a:{value:a};t.push({state:i,action:s,q_value:c.value||c.q_value||0,visits:c.visits||0,last_update:c.lastUpdate||c.last_update})}}if(n.memories&&Array.isArray(n.memories)){for(let r of n.memories)if(typeof r=="object"&&r!==null){let i=r;t.push({id:i.id||`mem_${Date.now()}_${ve().slice(0,12)}`,memory_type:i.type||"file_access",content:i.content||i.path,embedding:i.embedding,metadata:i.metadata,timestamp:i.timestamp})}}return t}extractDaemonState(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.workers&&typeof n.workers=="object"){let r=n.workers;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null){let s=o;t.push({worker_type:i,run_count:s.runCount||s.runs||0,success_count:s.successCount||s.successes||0,failure_count:s.failureCount||s.failures||0,avg_duration_ms:s.avgDuration||s.averageDurationMs,last_run:s.lastRun})}}return t}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t))(n.includes("timestamp")||n.endsWith("_at")||n==="last_update")&&(typeof r=="number"?t[n]=new Date(r).toISOString():typeof r=="string"&&!isNaN(Date.parse(r))&&(t[n]=new Date(r).toISOString())),typeof r=="object"&&r!==null&&!Array.isArray(r)&&["value","metadata","embedding"].includes(n);return t.created_at||(t.created_at=new Date().toISOString()),t}getInfo(){let e=C.existsSync(this.filePath),t=0,n=null;if(e){let r=C.statSync(this.filePath);t=r.size,n=r.mtime}return{path:this.filePath,exists:e,modTime:n,size:t}}};function ne(l){return new U(l)}v();import{spawn as _e}from"child_process";import{createConnection as xe}from"net";var Ae=b.create("tunnel-manager");function fe(l){try{let e=new URL(l);return e.password&&(e.password="***"),e.toString()}catch(e){return Ae.debug("URL parse failed during redaction, using regex fallback",{error:e instanceof Error?e.message:String(e)}),l.replace(/:\/\/([^:]+):([^@]+)@/,"://$1:***@")}}var M=class{process=null;connection=null;config;constructor(e){this.config=e}checkPort(e,t,n=2e3){return new Promise(r=>{let i=xe({host:e,port:t}),o=setTimeout(()=>{i.destroy(),r(!1)},n);i.on("connect",()=>{clearTimeout(o),i.destroy(),r(!0)}),i.on("error",()=>{clearTimeout(o),i.destroy(),r(!1)})})}async start(){return this.process&&this.connection?(console.log("[TunnelManager] Tunnel already running"),this.connection):await this.checkPort("localhost",this.config.tunnelPort)?(console.log(`[TunnelManager] External tunnel detected on port ${this.config.tunnelPort}, reusing`),this.connection={host:"localhost",port:this.config.tunnelPort,startedAt:new Date},this.connection):new Promise((t,n)=>{let r=["compute","start-iap-tunnel",this.config.instance,"5432",`--local-host-port=localhost:${this.config.tunnelPort}`,`--zone=${this.config.zone}`,`--project=${this.config.project}`];console.log(`[TunnelManager] Starting IAP tunnel: gcloud ${r.join(" ")}`),this.process=_e("gcloud",r,{stdio:["ignore","pipe","pipe"]});let i=!1,o="",s=!1;this.process.stderr?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`),["Listening on port","tunnel is running","Testing if tunnel connection works"].some(m=>c.includes(m))&&!i&&!s&&(s=!0,setTimeout(async()=>{for(let g=0;g<10;g++){if(console.log(`[TunnelManager] Checking port connectivity (attempt ${g+1}/10)...`),await this.checkPort("localhost",this.config.tunnelPort)){i=!0,this.connection={host:"localhost",port:this.config.tunnelPort,pid:this.process?.pid,startedAt:new Date},console.log(`[TunnelManager] Tunnel ready on port ${this.config.tunnelPort}`),t(this.connection);return}await new Promise(y=>setTimeout(y,1e3))}s=!1},2e3)),o+=c}),this.process.stdout?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`)}),this.process.on("error",a=>{console.error(`[TunnelManager] Process error: ${a.message}`),i||n(new Error(`Failed to start tunnel: ${a.message}`))}),this.process.on("close",a=>{console.log(`[TunnelManager] Process closed with code ${a}`),this.process=null,this.connection=null,i||n(new Error(`Tunnel process exited with code ${a}: ${o}`))}),setTimeout(()=>{i||(this.stop(),n(new Error("Tunnel connection timeout")))},6e4)})}async stop(){this.process&&(console.log("[TunnelManager] Stopping tunnel"),this.process.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),this.process&&this.process.kill("SIGKILL"),this.process=null,this.connection=null)}isActive(){return this.process!==null&&this.connection!==null}getConnection(){return this.connection}getConnectionString(){if(!this.connection)throw new Error("Tunnel not active");let{database:e,user:t}=this.config,n=process.env.PGPASSWORD||"",r=this.connection.host,i=this.connection.port;return`postgresql://${t}:${n}@${r}:${i}/${e}`}getRedactedConnectionString(){return fe(this.getConnectionString())}};function ke(l){return new M(l)}var B=class{connection=null;connectionString;constructor(e){this.connectionString=e}async start(){let e=new URL(this.connectionString);return this.connection={host:e.hostname,port:parseInt(e.port||"5432",10),startedAt:new Date},this.connection}async stop(){this.connection=null}isActive(){return this.connection!==null}getConnection(){return this.connection}getConnectionString(){return this.connectionString}getRedactedConnectionString(){return fe(this.connectionString)}};function $(l){return l.connectionString?new B(l.connectionString):new M(l)}A();P();v();import{createRequire as Me}from"module";var N=b.create("postgres-writer"),$e=Me(import.meta.url),J=class{client=null;config;inTransaction=!1;connected=!1;constructor(e){this.config=e}async connect(){if(this.connected)return;this.config.tunnelManager.isActive()||await this.config.tunnelManager.start();let e=this.config.tunnelManager.getConnection();if(!e)throw new Error("No tunnel connection available");let t;try{t=$e("pg")}catch(o){N.debug("pg module not installed, using mock mode",{error:o instanceof Error?o.message:String(o)}),console.warn("[PostgresWriter] pg module not installed, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let n=t.default,r=t.Client||n?.Client;if(!r){console.warn("[PostgresWriter] pg.Client not found in module, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let i={host:e.host,port:e.port,database:this.config.cloud.database,user:this.config.cloud.user,password:process.env.PGPASSWORD||"",connectionTimeoutMillis:this.config.connectionTimeout||1e4};this.client=new r(i),await this.client.connect(),this.connected=!0,console.log(`[PostgresWriter] Connected to ${e.host}:${e.port}/${this.config.cloud.database}`)}async beginTransaction(){if(!this.client)throw new Error("Not connected");await this.client.query("BEGIN"),this.inTransaction=!0}async commit(){if(!this.client||!this.inTransaction)throw new Error("No active transaction");await this.client.query("COMMIT"),this.inTransaction=!1}async rollback(){!this.client||!this.inTransaction||(await this.client.query("ROLLBACK"),this.inTransaction=!1)}async upsert(e,t,n){if(!this.client)throw new Error("Not connected");if(t.length===0)return 0;let r=t[0],i=Object.keys(r),o=n?.conflictColumns||this.inferConflictColumns(e,i),s=n?.updateColumns||i.filter(u=>!o.includes(u)),a=0,c=100;for(let u=0;u<t.length;u+=c){let p=t.slice(u,u+c);try{let m=await this.upsertBatch(e,p,i,o,s,n?.skipIfExists);a+=m}catch(m){let g=Math.floor(u/c)+1,h=Math.ceil(t.length/c);N.debug(`Batch ${g}/${h} failed for ${e}, retrying individually`,{error:d(m)});let y=0;for(let f of p)try{let S=await this.upsertBatch(e,[f],i,o,s,n?.skipIfExists);y+=S}catch(S){let R=f.id||f.key||"?";N.debug(`Skipped record ${String(R).slice(0,50)} in ${e}`,{error:d(S)})}a+=y,y<p.length&&console.warn(`[PostgresWriter] Batch ${g}/${h} for ${e}: ${y}/${p.length} recovered (${p.length-y} skipped)`)}}return a}async upsertBatch(e,t,n,r,i,o){if(!this.client)return 0;let s=[],a=[],c=1;for(let f of t){let S=[];for(let R of n){let Ee=f[R];S.push(`$${c++}`),a.push(this.serializeValue(Ee,R))}s.push(`(${S.join(", ")})`)}let u=E(e),p=n.map(E),m=r.map(E),g=i.map(E),h="";if(m.length>0){if(o)h=`ON CONFLICT (${m.join(", ")}) DO NOTHING`;else if(g.length>0){let f=g.map(S=>`${S} = EXCLUDED.${S}`).join(", ");h=`ON CONFLICT (${m.join(", ")}) DO UPDATE SET ${f}`}}let y=`
|
|
3
3
|
INSERT INTO ${u} (${p.join(", ")})
|
|
4
4
|
VALUES ${s.join(", ")}
|
|
5
5
|
${h}
|
|
@@ -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{h as s,k as o,o 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{h as s,k as o,o as h}from"./chunk-UE3XXKLN.js";import{a as m}from"./chunk-X73CRYF4.js";import{c as r}from"./chunk-BQT4J3BD.js";import{a,e as u}from"./chunk-NT4PI5HI.js";h();u();m();var l=r.create("hybrid-backend"),c=class{unifiedMemory=null;config;cleanupInterval;cleanupCount=0;initialized=!1;constructor(e){this.config={sqlite:{path:e?.sqlite?.path??".agentic-qe/memory.db",walMode:e?.sqlite?.walMode??!0,poolSize:e?.sqlite?.poolSize??5,busyTimeout:e?.sqlite?.busyTimeout??a.BUSY_TIMEOUT_MS,...e?.sqlite},agentdb:{path:e?.agentdb?.path??".agentic-qe/memory.db",...e?.agentdb},enableFallback:e?.enableFallback??!0,defaultNamespace:e?.defaultNamespace??"default",cleanupInterval:e?.cleanupInterval??a.CLEANUP_INTERVAL_MS}}async initialize(e){if(this.initialized)return;let i=e?.signal;i?.throwIfAborted();let t={dbPath:this.config.sqlite.path??s.dbPath,walMode:this.config.sqlite.walMode??!0,busyTimeout:this.config.sqlite.busyTimeout??a.BUSY_TIMEOUT_MS};this.unifiedMemory=o(t),i?.throwIfAborted(),await this.unifiedMemory.initialize({signal:i}),i?.throwIfAborted(),this.cleanupInterval=setInterval(()=>this.cleanup(),this.config.cleanupInterval),this.cleanupInterval.unref&&this.cleanupInterval.unref(),this.initialized=!0,console.log(`[HybridBackend] Initialized with unified memory: ${this.unifiedMemory.getDbPath()}`)}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.initialized=!1}async set(e,i,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;await this.unifiedMemory.kvSet(e,i,n,t?.ttl)}async get(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvGet(e,t)}async delete(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace,n=await this.unifiedMemory.kvDelete(e,t),d=await this.unifiedMemory.vectorDelete(e);return n||d}async has(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvExists(e,t)}async search(e,i=100,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvSearch(e,n,i)}async vectorSearch(e,i){return this.ensureInitialized(),(await this.unifiedMemory.vectorSearch(e,i)).map(n=>({key:n.id,score:n.score,metadata:n.metadata}))}async storeVector(e,i,t){this.ensureInitialized(),await this.unifiedMemory.vectorStore(e,i,this.config.defaultNamespace,t)}getHealth(){return{sqlite:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",sqlitePersistent:!0,agentdb:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",fallback:"inactive"}}isPersistent(){return this.unifiedMemory?.isInitialized()??!1}getConfig(){return{...this.config}}async setWithBackend(e,i,t,n){await this.set(e,i,n)}async getVectorStats(){if(!this.unifiedMemory?.isInitialized())return null;let e=await this.unifiedMemory.vectorCount(),i=this.unifiedMemory.getStats();return{vectorCount:e,indexSize:i.vectorIndexSize}}getUnifiedMemory(){return this.unifiedMemory}async count(e){return this.ensureInitialized(),this.unifiedMemory.getDatabase().prepare(`
|
|
3
3
|
SELECT COUNT(*) as count FROM kv_store
|
|
4
4
|
WHERE namespace LIKE ?
|
|
5
5
|
AND (expires_at IS NULL OR expires_at > ?)
|
|
@@ -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.
|
|
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
2
|
var h=class{executionHistory=[];learnedDurations=new Map;runCount=0;lastPrunedCount=0;learningRate;maxHistorySize;constructor(t){this.learningRate=t?.learningRate??.3,this.maxHistorySize=t?.maxHistorySize??1e4}buildTestDAG(t){let e=new Map,n=new Map;for(let i of t){let s=this.applyLearnedDuration(i);e.set(s.id,s),n.set(s.id,[])}for(let i of t)for(let s of i.dependencies){if(!e.has(s))throw new Error(`Test '${i.id}' depends on '${s}' which does not exist in the test set`);n.get(s).push(i.id)}let o=this.computeCriticalPath(e,n),a=this.computeParallelGroups(e,n);return{nodes:e,edges:n,criticalPath:o,parallelGroups:a}}findCriticalPath(t){return t.criticalPath.map(e=>t.nodes.get(e)).filter(e=>e!==void 0)}findParallelBranches(t){return t.parallelGroups.map(e=>e.map(n=>t.nodes.get(n)).filter(n=>n!==void 0))}pruneByMinCut(t,e){let n=this.sumDurations(t.nodes);if(n<=e)return this.lastPrunedCount=0,t;let o=this.computeAttentionScores(t),a=Array.from(o.entries()).sort((r,l)=>r[1]-l[1]),i=new Set(t.criticalPath),s=new Set,c=n;for(let[r]of a){if(c<=e)break;if(i.has(r)||(t.edges.get(r)??[]).some(p=>!s.has(p)))continue;let d=t.nodes.get(r);d&&(s.add(r),c-=d.estimatedDuration)}this.lastPrunedCount=s.size;let u=Array.from(t.nodes.values()).filter(r=>!s.has(r.id));return this.buildTestDAG(u)}schedule(t){if(t.length===0)return{phases:[],totalEstimatedTime:0,criticalPathTime:0,parallelism:0};let e=this.buildTestDAG(t),o=this.findParallelBranches(e).map(u=>({tests:u,canRunInParallel:u.length>1})),a=this.computeCriticalPathDuration(e),i=this.sumDurations(e.nodes),s=o.reduce((u,r)=>r.canRunInParallel?u+Math.max(...r.tests.map(l=>l.estimatedDuration)):u+r.tests.reduce((l,d)=>l+d.estimatedDuration,0),0),c=s>0?i/s:1;return this.runCount++,{phases:o,totalEstimatedTime:s,criticalPathTime:a,parallelism:c}}getOptimizationStats(){return{totalTests:0,criticalPathLength:0,parallelGroupCount:0,prunedTests:this.lastPrunedCount,estimatedTimeSaved:0,historicalRuns:this.runCount,usingNativeBackend:!1}}recordExecution(t,e,n){this.executionHistory.push({testId:t,actualDuration:e,result:n,timestamp:Date.now()}),this.executionHistory.length>this.maxHistorySize&&(this.executionHistory=this.executionHistory.slice(-this.maxHistorySize));let o=this.learnedDurations.get(t);o!==void 0?this.learnedDurations.set(t,o*(1-this.learningRate)+e*this.learningRate):this.learnedDurations.set(t,e)}getLearnedDuration(t){return this.learnedDurations.get(t)}isNativeBackendAvailable(){return!1}computeCriticalPath(t,e){let n=this.topologicalSort(t,e);if(n.length===0)return[];let o=new Map,a=new Map;for(let r of n)o.set(r,t.get(r).estimatedDuration),a.set(r,null);for(let r of n){let l=o.get(r);for(let d of e.get(r)??[]){let p=t.get(d);if(!p)continue;let g=l+p.estimatedDuration;g>(o.get(d)??0)&&(o.set(d,g),a.set(d,r))}}let i=0,s=null;for(let[r,l]of o)l>i&&(i=l,s=r);if(!s)return[];let c=[],u=s;for(;u!==null;)c.unshift(u),u=a.get(u)??null;return c}computeCriticalPathDuration(t){return t.criticalPath.reduce((e,n)=>e+(t.nodes.get(n)?.estimatedDuration??0),0)}computeParallelGroups(t,e){let n=this.topologicalSort(t,e);if(n.length===0)return[];let o=new Map;for(let[u,r]of t)o.set(u,new Set(r.dependencies));let a=new Map;for(let u of n){let r=-1;for(let l of o.get(u)??new Set){let d=a.get(l);d!==void 0&&d>r&&(r=d)}a.set(u,r+1)}let i=new Map;for(let u of n){let r=a.get(u)??0;i.has(r)||i.set(r,[]),i.get(r).push(u)}let s=Math.max(...Array.from(i.keys()),-1),c=[];for(let u=0;u<=s;u++){let r=i.get(u);r&&r.length>0&&c.push(r)}return c}computeAttentionScores(t){let e=new Map,n=this.countTransitiveDependents(t);for(let[o,a]of t.nodes){let i=a.lastResult==="fail"?2:1,s=n.get(o)??0;e.set(o,a.priority*i*(1+s))}return e}countTransitiveDependents(t){let e=new Map,n=new Map,o=a=>{if(n.has(a))return n.get(a);let i=new Set;for(let s of t.edges.get(a)??[]){i.add(s);for(let c of o(s))i.add(c)}return n.set(a,i),i};for(let a of t.nodes.keys())e.set(a,o(a).size);return e}topologicalSort(t,e){let n=new Map;for(let i of t.keys())n.set(i,0);for(let i of e.values())for(let s of i)n.has(s)&&n.set(s,(n.get(s)??0)+1);let o=[];for(let[i,s]of n)s===0&&o.push(i);let a=[];for(;o.length>0;){let i=o.shift();a.push(i);for(let s of e.get(i)??[]){let c=(n.get(s)??0)-1;n.set(s,c),c===0&&o.push(s)}}if(a.length!==t.size)throw new Error(`Cycle detected in test DAG: sorted ${a.length} of ${t.size} nodes`);return a}applyLearnedDuration(t){let e=this.learnedDurations.get(t.id);return e!==void 0?{...t,estimatedDuration:Math.round(e)}:t}sumDurations(t){let e=0;for(let n of t.values())e+=n.estimatedDuration;return e}};function m(f){return new h(f)}export{h as a,m as b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.
|
|
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
2
|
function M(u){let e=u|0;return()=>{e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}var A=2,y=10,x=200,p=1e-8,b=class{epsilon;seed;constructor(e){if(this.epsilon=e?.epsilon??.3,this.seed=e?.seed,this.epsilon<=0||this.epsilon>=1)throw new Error("SparsifierConfig.epsilon must be in (0, 1)")}sparsify(e){if(e.nodeCount<=0||e.edges.length===0)return{nodeCount:e.nodeCount,edges:[]};let n=this.seed!==void 0?M(this.seed):Math.random,t=this.approximateEffectiveResistances(e),i=e.nodeCount,r=e.edges.length,o=Math.max(1,Math.log(i)),m=this.epsilon*this.epsilon,l=Math.min(r,Math.max(i-1,A*(i-1)*(1-this.epsilon))),s=new Float64Array(r),c=0;for(let a=0;a<r;a++){let d=e.edges[a][2];s[a]=d*t[a],c+=s[a]}if(c<=0)return{nodeCount:e.nodeCount,edges:[]};let f=[];for(let a=0;a<r;a++){let[d,C,E]=e.edges[a],g=Math.min(1,s[a]/c*l);if(n()<g){let w=E/g;f.push([d,C,w])}}return{nodeCount:e.nodeCount,edges:f}}validateSpectral(e,n){let t=Math.min(y,Math.max(1,e.nodeCount-1)),i=this.computeLaplacian(e),r=this.computeLaplacian(n),o=this.computeTopEigenvalues(i,t),m=this.computeTopEigenvalues(r,t),l=[],s=!0,c=this.epsilon;for(let f=0;f<o.length;f++){if(o[f]<1e-10)continue;let a=m[f]/o[f];l.push(a),(a<1-c||a>1+c)&&(s=!1)}return{isValid:s,eigenvalueRatios:l,originalEdgeCount:e.edges.length,sparsifiedEdgeCount:n.edges.length,compressionRatio:e.edges.length>0?n.edges.length/e.edges.length:0}}computeLaplacian(e){let n=e.nodeCount,t=Array.from({length:n},()=>new Array(n).fill(0));for(let[i,r,o]of e.edges)i<0||i>=n||r<0||r>=n||(t[i][i]+=o,t[r][r]+=o,t[i][r]-=o,t[r][i]-=o);return t}computeTopEigenvalues(e,n){let t=e.length;if(t===0)return[];let i=[],r=[],o=e.map(m=>[...m]);for(let m=0;m<Math.min(n,t);m++){let l=this.powerIteration(o,t,r);if(l===null)break;i.push(l.eigenvalue),r.push(l.eigenvector),V(o,l.eigenvalue,l.eigenvector)}return i}approximateEffectiveResistances(e){let n=e.nodeCount,t=new Float64Array(n);for(let[r,o,m]of e.edges)r>=0&&r<n&&(t[r]+=m),o>=0&&o<n&&(t[o]+=m);let i=new Array(e.edges.length);for(let r=0;r<e.edges.length;r++){let[o,m]=e.edges[r],l=t[o]||1,s=t[m]||1;i[r]=1/l+1/s}return i}powerIteration(e,n,t){let i=0;for(let s=0;s<n;s++)for(let c=0;c<n;c++)i+=e[s][c]*e[s][c];if(i<p*p)return null;let r=t.length,o=new Array(n);for(let s=0;s<n;s++)o[s]=Math.sin((s+1)*(r+1)*1.618033988749895)+.1*(s-n/2);for(let s of t)h(o,s);if(R(o)<p)return null;let l=0;for(let s=0;s<x;s++){let c=L(e,o);for(let d of t)h(c,d);let f=S(c,o),a=v(c);if(a<p)return{eigenvalue:0,eigenvector:o};for(let d=0;d<n;d++)o[d]=c[d]/a;if(Math.abs(f-l)<p){l=f;break}l=f}return{eigenvalue:Math.abs(l),eigenvector:o}}};function L(u,e){let n=u.length,t=new Array(n).fill(0);for(let i=0;i<n;i++){let r=0;for(let o=0;o<n;o++)r+=u[i][o]*e[o];t[i]=r}return t}function v(u){let e=0;for(let n=0;n<u.length;n++)e+=u[n]*u[n];return Math.sqrt(e)}function R(u){let e=v(u);if(e>0)for(let n=0;n<u.length;n++)u[n]/=e;return e}function S(u,e){let n=0;for(let t=0;t<u.length;t++)n+=u[t]*e[t];return n}function h(u,e){let n=S(u,e);for(let t=0;t<u.length;t++)u[t]-=n*e[t]}function V(u,e,n){let t=n.length;for(let i=0;i<t;i++)for(let r=0;r<t;r++)u[i][r]-=e*n[i]*n[r]}export{b as a};
|
|
@@ -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 p,o as N}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.0");process.exit(0)}
|
|
2
|
+
import{k as p,o as N}from"./chunk-UE3XXKLN.js";N();import{createHash as y}from"crypto";var g="0".repeat(64);function m(s){return y("sha256").update(s,"utf-8").digest("hex")}function R(s){try{return y("shake256",{outputLength:32}).update(s,"utf-8").digest("hex")}catch{return m(s)}}function _(s,t){return s==="shake256"?R(t):m(t)}function f(s){return JSON.stringify({id:s.id,prev_hash:s.prev_hash,action_hash:s.action_hash,action_type:s.action_type,action_data:s.action_data,timestamp:s.timestamp,actor:s.actor})}var d=class{constructor(t,i){this.externalDb=t;this.keyManager=i??null}externalDb;db=null;initialized=!1;keyManager=null;async initialize(){if(!this.initialized){if(this.externalDb)this.db=this.externalDb;else{let t=p();await t.initialize(),this.db=t.getDatabase()}this.ensureTable(),this.initialized=!0}}getDatabase(){return this.db}getKeyManager(){return this.keyManager}ensureTable(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS witness_chain (
|
|
4
4
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
5
5
|
prev_hash TEXT NOT NULL, action_hash TEXT NOT NULL, action_type TEXT NOT NULL,
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.
|
|
2
|
-
import{a as v,b as k}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 v,b as k}from"./chunk-KYLJERZ3.js";import{k as g,o as P}from"./chunk-UE3XXKLN.js";import{a as d,b as y,c as R}from"./chunk-KNL3QWVA.js";R();import{randomUUID as M}from"crypto";var p=class{constructor(e){this.config=e}config;_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let r=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let n,t;for(let a=0;a<=this.config.retryCount;a++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");t=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(u){n=y(u),e.logger.warn(`Worker ${this.config.id} attempt ${a+1} failed: ${n.message}`),a<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let o=Date.now()-r;return t?(this._successfulExecutions++,this._lastResult=t):(this._failedExecutions++,t=this.createErrorResult(n,o),this._lastResult=t),this._executionDurations.push(o),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:t.success,durationMs:o}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=t.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:t.success,durationMs:o,findingsCount:t.findings.length,healthScore:t.metrics.healthScore}}),t}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((n,t)=>n+t,0)/this._executionDurations.length:0,r=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(r*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,r,n){return new Promise((t,o)=>{let a=setTimeout(()=>{o(new Error(`Worker execution timed out after ${r}ms`))},r),u=()=>{clearTimeout(a),o(new Error("Worker execution aborted"))};n.addEventListener("abort",u,{once:!0}),e().then(c=>{clearTimeout(a),n.removeEventListener("abort",u),t(c)}).catch(c=>{clearTimeout(a),n.removeEventListener("abort",u),o(c)})})}createErrorResult(e,r){return{workerId:this.config.id,timestamp:new Date,durationMs:r,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,r,n,t){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:r,findings:n,recommendations:t}}delay(e){return new Promise(r=>setTimeout(r,e))}generateId(){return`${Date.now()}-${M().slice(0,9)}`}};P();R();var W={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},b=class extends p{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(W),this.dailyLogger=new k}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=g();await e.initialize();let r=e.getDatabase();return this.lifecycleManager=v(r,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return g().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let r=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let n=[],t=[],o=await this.getLifecycleManager();if(!o)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-r,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let a=0,u=0;try{let s=o.promoteEligiblePatterns();a=s.promoted,u=s.checked,a>0&&n.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${a} of ${u} short-term patterns promoted to long-term`})}catch(s){e.logger.warn("Pattern promotion failed",{error:d(s)})}let c=0,h=0;try{let s=o.deprecateStalePatterns();c=s.deprecated,h=s.checked,c>0&&n.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${c} of ${h} patterns deprecated (stale, failed, or low confidence)`})}catch(s){e.logger.warn("Stale pattern detection failed",{error:d(s)})}let l=0;try{let s=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;l=o.applyConfidenceDecay(Math.min(s,7)).decayed}catch(s){e.logger.warn("Confidence decay failed",{error:d(s)})}let m=this.getPendingExperienceCount(),i={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{i=o.getStats()}catch(s){e.logger.warn("Stats retrieval failed",{error:d(s)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${a} promoted, ${c} deprecated, ${l} decayed, ${m} pending exp, ${i.activePatterns} active patterns (avg conf: ${i.avgConfidence.toFixed(2)})`,details:{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,totalPatterns:i.totalPatterns,activePatterns:i.activePatterns,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}),this.dailyLogger.flush()}catch(s){e.logger.warn("Daily log write failed",{error:d(s)})}this.lastRunTimestamp=Date.now(),i.activePatterns>0&&i.patternsNearDeprecation/i.activePatterns>.5&&t.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${i.patternsNearDeprecation} of ${i.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let f=this.calculateHealthScore(i,a,c),D=this.determineTrend(a,c,i.activePatterns),_=Math.max(u,h),x=a+c+i.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,healthScore:f}),this.createResult(Date.now()-r,{itemsAnalyzed:_,issuesFound:x,healthScore:f,trend:D,domainMetrics:{promoted:a,deprecated:c,decayed:l,stalePatterns:i.patternsNearDeprecation,pendingExperiences:m,avgConfidence:Number(i.avgConfidence.toFixed(3)),avgSuccessRate:Number(i.avgSuccessRate.toFixed(3))}},n,t)}calculateHealthScore(e,r,n){let t=70;if(t+=Math.min(15,r*5),e.avgConfidence>0&&(t+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let o=n/e.activePatterns;t-=Math.round(o*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(t-=10),Math.max(0,Math.min(100,Math.round(t)))}determineTrend(e,r,n){return n===0?"stable":e>r?"improving":r>e&&r/n>.1?"degrading":"stable"}};export{p as a,b};
|