agentic-qe 3.15.14 → 3.15.16
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/agents/v3/templates/qx-report-template.html +1 -1
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +136 -0
- package/assets/agents/v3/templates/qx-report-template.html +1 -1
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/audit/witness-chain.d.ts +7 -0
- package/dist/audit/witness-chain.js +10 -0
- package/dist/cli/bundle.js +6 -6
- package/dist/cli/chunks/adapter-6CQ2PIP5.js +2 -0
- package/dist/cli/chunks/agent-booster-wasm-45NWEKVS.js +2 -0
- package/dist/cli/chunks/{agent-handler-P3IY7XEE.js → agent-handler-LVHMYFEF.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-WWKC2H3G.js → agent-memory-branch-YDWOJFEQ.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-73RR52VS.js +2 -0
- package/dist/cli/chunks/{arena-EIV5OALF.js → arena-CZKHXDDS.js} +2 -2
- package/dist/cli/chunks/{arena-4BMFF6BS.js → arena-ELDZH3CZ.js} +4 -4
- package/dist/cli/chunks/{audit-DNTI453H.js → audit-5MT4T47Z.js} +3 -3
- package/dist/cli/chunks/base-SMCMMVGP.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-TQBQGNC6.js → better-sqlite3-6TGYPC2B.js} +2 -2
- package/dist/cli/chunks/{brain-handler-HY57CNAO.js → brain-handler-HQWZFO52.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-THPMZPHQ.js → branch-enumerator-WVILM4SO.js} +2 -2
- package/dist/cli/chunks/{browser-O6JJOZCK.js → browser-RX5ALU3H.js} +2 -2
- package/dist/cli/chunks/browser-workflow-A2MEZ66K.js +2 -0
- package/dist/cli/chunks/{chunk-CIINJHOX.js → chunk-24OX5TQJ.js} +1 -1
- package/dist/cli/chunks/{chunk-6P4Q4RTC.js → chunk-24QHCVX6.js} +1 -1
- package/dist/cli/chunks/{chunk-U6IOQKCT.js → chunk-2H4XH6FT.js} +2 -2
- package/dist/cli/chunks/{chunk-OGEIHS76.js → chunk-2YZ4G6NW.js} +1 -1
- package/dist/cli/chunks/chunk-32BPDLRZ.js +27 -0
- package/dist/cli/chunks/{chunk-5PLBQZ5J.js → chunk-32GN3JKR.js} +1 -1
- package/dist/cli/chunks/{chunk-AJVLVF7V.js → chunk-3HD7E6HN.js} +2 -2
- package/dist/cli/chunks/{chunk-X7CUI7KH.js → chunk-4D4DENG6.js} +2 -2
- package/dist/cli/chunks/{chunk-E2JLAW3U.js → chunk-4LQFBY5L.js} +6 -6
- package/dist/cli/chunks/{chunk-E3QIQMMN.js → chunk-4NFQLP6R.js} +1 -1
- package/dist/cli/chunks/{chunk-7Y3LXH57.js → chunk-525CFDUE.js} +2 -2
- package/dist/cli/chunks/chunk-5B5QPCNU.js +65 -0
- package/dist/cli/chunks/{chunk-X6Q2N5S5.js → chunk-5JZRZI4S.js} +2 -2
- package/dist/cli/chunks/{chunk-MB4UKUBV.js → chunk-5LAVKGLH.js} +2 -2
- package/dist/cli/chunks/chunk-5NNNEWLS.js +755 -0
- package/dist/cli/chunks/{chunk-NKOLILT7.js → chunk-5PBLPQ5T.js} +2 -2
- package/dist/cli/chunks/chunk-5QO3R3TU.js +6 -0
- package/dist/cli/chunks/{chunk-7T6L3LFN.js → chunk-5SPCGMBB.js} +2 -2
- package/dist/cli/chunks/{chunk-2QLE6NDW.js → chunk-5V3TI2LG.js} +1 -1
- package/dist/cli/chunks/{chunk-A2T56XVL.js → chunk-5VZL4UVN.js} +2 -2
- package/dist/cli/chunks/{chunk-TWOV3I3A.js → chunk-63GMRQ25.js} +1 -1
- package/dist/cli/chunks/{chunk-YGOSSVY5.js → chunk-63ZKI4PX.js} +6 -6
- package/dist/cli/chunks/{chunk-FHPNWHY7.js → chunk-67Z5R7RJ.js} +2 -2
- package/dist/cli/chunks/{chunk-PCQZIAXB.js → chunk-6DPYNAOK.js} +2 -2
- package/dist/cli/chunks/{chunk-WCM6WE7G.js → chunk-6ICX3FEG.js} +3 -3
- package/dist/cli/chunks/{chunk-JB7R77SH.js → chunk-6XXZDV2C.js} +2 -2
- package/dist/cli/chunks/{chunk-FJOIBZUB.js → chunk-6ZBXSOX6.js} +2 -2
- package/dist/cli/chunks/{chunk-WZQADC5R.js → chunk-72XSEQMW.js} +2 -2
- package/dist/cli/chunks/{chunk-AYLEH2UF.js → chunk-7TE5ONQQ.js} +1 -1
- package/dist/cli/chunks/{chunk-7QUSNBAA.js → chunk-A5GBXCP5.js} +2 -2
- package/dist/cli/chunks/{chunk-7724KXM2.js → chunk-AAMLQ2LF.js} +3 -3
- package/dist/cli/chunks/chunk-AG2EWGXS.js +21 -0
- package/dist/cli/chunks/{chunk-2UZBLC5H.js → chunk-AGRV5B3T.js} +2 -2
- package/dist/cli/chunks/{chunk-V6SE2ZU2.js → chunk-AJMJNQMP.js} +1 -1
- package/dist/cli/chunks/{chunk-2HPNGK7A.js → chunk-AR67RJPY.js} +2 -2
- package/dist/cli/chunks/{chunk-G7HGUQAE.js → chunk-ASEOFRIG.js} +2 -2
- package/dist/cli/chunks/{chunk-7TH4PJSU.js → chunk-BEKDKVQT.js} +2 -2
- package/dist/cli/chunks/{chunk-M5JEA6ZY.js → chunk-BY5OF7OH.js} +2 -2
- package/dist/cli/chunks/{chunk-OLUOVNUF.js → chunk-C5FP5GW3.js} +2 -2
- package/dist/cli/chunks/{chunk-R5RRWLRI.js → chunk-C6D5AHBO.js} +2 -2
- package/dist/cli/chunks/{chunk-K7GFYFBO.js → chunk-CAKMOVZ6.js} +2 -2
- package/dist/cli/chunks/{chunk-6NIGSY5L.js → chunk-CEYSYSK5.js} +2 -2
- package/dist/cli/chunks/{chunk-U4TML2VD.js → chunk-CGGUM2YJ.js} +2 -2
- package/dist/cli/chunks/{chunk-YE54T2NQ.js → chunk-CJSHWQXP.js} +2 -2
- package/dist/cli/chunks/{chunk-7SQTLUEN.js → chunk-CRPIYUTJ.js} +2 -2
- package/dist/cli/chunks/{chunk-65EE2EST.js → chunk-D6COXLYE.js} +2 -2
- package/dist/cli/chunks/{chunk-4WLIOPHX.js → chunk-DTMAS2GB.js} +2 -2
- package/dist/cli/chunks/{chunk-E7QTWGPI.js → chunk-DVYHMDFR.js} +470 -411
- package/dist/cli/chunks/chunk-DXD6K2ZP.js +3 -0
- package/dist/cli/chunks/{chunk-HSDWPQQY.js → chunk-E3D4GPLP.js} +3 -3
- package/dist/cli/chunks/{chunk-JJHLGGPP.js → chunk-EA4YQVKS.js} +1 -1
- package/dist/cli/chunks/{chunk-EIEEST4T.js → chunk-EGYE5UPQ.js} +2 -2
- package/dist/cli/chunks/{chunk-O756AOUX.js → chunk-EK7OLYOZ.js} +2 -2
- package/dist/cli/chunks/{chunk-57DRT6UA.js → chunk-F742SZAX.js} +2 -2
- package/dist/cli/chunks/{chunk-6OI5SK7M.js → chunk-FBDVGRSC.js} +1 -1
- package/dist/cli/chunks/{chunk-H3C5FJRH.js → chunk-FDDC72IA.js} +2 -2
- package/dist/cli/chunks/{chunk-IQRPR4KB.js → chunk-FL64OUBA.js} +2 -2
- package/dist/cli/chunks/{chunk-BNG4J3CE.js → chunk-FLNAW7C4.js} +2 -2
- package/dist/cli/chunks/{chunk-C3OIBFAA.js → chunk-G5RHFBAY.js} +2 -2
- package/dist/cli/chunks/{chunk-NPCXGX7N.js → chunk-GAHNO6JJ.js} +2 -2
- package/dist/cli/chunks/{chunk-PNRPVQGI.js → chunk-GFWHUQSF.js} +2 -2
- package/dist/cli/chunks/{chunk-OCN53CCK.js → chunk-GJYHWYXR.js} +2 -2
- package/dist/cli/chunks/{chunk-5Z4MO2F3.js → chunk-GQ6TUIKY.js} +1 -1
- package/dist/cli/chunks/{chunk-N736GLWZ.js → chunk-GSKMOPL7.js} +2 -2
- package/dist/cli/chunks/{chunk-43XHGWYH.js → chunk-HCH4Y6XX.js} +2 -2
- package/dist/cli/chunks/{chunk-QP6GL3O5.js → chunk-HGWXF45W.js} +1 -1
- package/dist/cli/chunks/{chunk-PGN4TARY.js → chunk-HJ6ZGVTB.js} +2 -2
- package/dist/cli/chunks/{chunk-M2TG7VDK.js → chunk-HLUXXCHF.js} +1 -1
- package/dist/cli/chunks/{chunk-UMHFTQTR.js → chunk-HVRRLYX6.js} +4 -4
- package/dist/cli/chunks/{chunk-L7PC675Y.js → chunk-I7MQIM2U.js} +1 -1
- package/dist/cli/chunks/{chunk-JSSU4RIK.js → chunk-IESR7TNB.js} +2 -2
- package/dist/cli/chunks/{chunk-H4LYXLAT.js → chunk-IHRXZZQM.js} +1 -1
- package/dist/cli/chunks/{chunk-HV43NX4A.js → chunk-IOKYCMTJ.js} +6 -6
- package/dist/cli/chunks/{chunk-NZQYJCO6.js → chunk-IOQ6ZQ5W.js} +1 -1
- package/dist/cli/chunks/{chunk-JO26SG47.js → chunk-IOYG4VFL.js} +2 -2
- package/dist/cli/chunks/{chunk-6O63ZTVX.js → chunk-IUBJVHNB.js} +2 -2
- package/dist/cli/chunks/{chunk-XSPMLJCQ.js → chunk-J442IZLE.js} +1 -1
- package/dist/cli/chunks/{chunk-LTGQJYYO.js → chunk-J4ELZNLY.js} +2 -2
- package/dist/cli/chunks/chunk-J7I6PABJ.js +153 -0
- package/dist/cli/chunks/chunk-JDIYMZCQ.js +2 -0
- package/dist/cli/chunks/{chunk-TOJF3ZG4.js → chunk-JHQCRRJI.js} +2 -2
- package/dist/cli/chunks/{chunk-QUZ745UQ.js → chunk-JQ3DYUMS.js} +2 -2
- package/dist/cli/chunks/{chunk-P2TPH3TC.js → chunk-KITOPKRG.js} +2 -2
- package/dist/cli/chunks/{chunk-QNQE3EOH.js → chunk-KKU2QGSJ.js} +2 -2
- package/dist/cli/chunks/chunk-KL7OKSU2.js +4 -0
- package/dist/cli/chunks/{chunk-L5VSLPMW.js → chunk-KNSRL6NO.js} +2 -2
- package/dist/cli/chunks/{chunk-INGXD5IX.js → chunk-KPRCB5LT.js} +2 -2
- package/dist/cli/chunks/{chunk-GY4P7KAI.js → chunk-KQYJ4VQ5.js} +1 -1
- package/dist/cli/chunks/{chunk-Z2S7DNFP.js → chunk-KU2AUFGX.js} +2 -2
- package/dist/cli/chunks/{chunk-O5CEL447.js → chunk-KVF4NXGQ.js} +2 -2
- package/dist/cli/chunks/{chunk-2IJO3657.js → chunk-KXCLACFG.js} +2 -2
- package/dist/cli/chunks/{chunk-ZJGFQK27.js → chunk-L2DWPVNJ.js} +1 -1
- package/dist/cli/chunks/{chunk-E7OR6V3V.js → chunk-L6QSTQME.js} +2 -2
- package/dist/cli/chunks/{chunk-RE6JTSDM.js → chunk-LE4QJREF.js} +1 -1
- package/dist/cli/chunks/{chunk-DSQESXL4.js → chunk-LKTTUHLF.js} +2 -2
- package/dist/cli/chunks/{chunk-YGC5QKQ4.js → chunk-LQLPB2T6.js} +2 -2
- package/dist/cli/chunks/{chunk-VGZOPQQY.js → chunk-LRSX2FJM.js} +1 -1
- package/dist/cli/chunks/chunk-M4FRQ4TE.js +12 -0
- package/dist/cli/chunks/chunk-M7WJCTG3.js +2 -0
- package/dist/cli/chunks/{chunk-56NSE3LJ.js → chunk-MAFQV4U4.js} +2 -2
- package/dist/cli/chunks/{chunk-MKYOE7NE.js → chunk-MD43XRX5.js} +1 -1
- package/dist/cli/chunks/{chunk-3TF27MG5.js → chunk-MI5MFHRA.js} +2 -2
- package/dist/cli/chunks/{chunk-JK6PMLQQ.js → chunk-MO55CVMT.js} +32 -32
- package/dist/cli/chunks/{chunk-X6NJOT3V.js → chunk-N7HL5PHH.js} +1 -1
- package/dist/cli/chunks/chunk-NAEWCFQT.js +14 -0
- package/dist/cli/chunks/{chunk-WUGXXNK4.js → chunk-NDJ7P2EP.js} +1 -1
- package/dist/cli/chunks/{chunk-D5GB5PUU.js → chunk-NO3IV5Q5.js} +1 -1
- package/dist/cli/chunks/{chunk-3XACRXBY.js → chunk-NQXXI77K.js} +2 -2
- package/dist/cli/chunks/{chunk-EC65UZ77.js → chunk-NVEWF4JV.js} +1 -1
- package/dist/cli/chunks/{chunk-JI67T6Q2.js → chunk-NZU4ACBZ.js} +2 -2
- package/dist/cli/chunks/chunk-O5W3FIO6.js +63 -0
- package/dist/cli/chunks/{chunk-YEFTK4HD.js → chunk-OAEE6JWQ.js} +2 -2
- package/dist/cli/chunks/{chunk-JAOCHPYX.js → chunk-OCV2XEWQ.js} +2 -2
- package/dist/cli/chunks/{chunk-IDBA5GK2.js → chunk-P3EYRILV.js} +2 -2
- package/dist/cli/chunks/{chunk-4RPBODN5.js → chunk-PEQDY4BO.js} +2 -2
- package/dist/cli/chunks/{chunk-CPPYZYXC.js → chunk-PF7RBAYL.js} +2 -2
- package/dist/cli/chunks/{chunk-WCPSR4MJ.js → chunk-PHT5N7SC.js} +2 -2
- package/dist/cli/chunks/{chunk-O2AAYJUV.js → chunk-PINSJCM3.js} +1 -1
- package/dist/cli/chunks/{chunk-HEDGFKC5.js → chunk-PPUZWYUG.js} +2 -2
- package/dist/cli/chunks/{chunk-XMCSKYDE.js → chunk-QPEOLAAS.js} +1 -1
- package/dist/cli/chunks/{chunk-7MUO4DEH.js → chunk-QQWBWEJS.js} +18 -18
- package/dist/cli/chunks/{chunk-UFP7SN5V.js → chunk-QVDCVD5D.js} +2 -2
- package/dist/cli/chunks/{chunk-NHEG2DLN.js → chunk-RJIEG3NA.js} +2 -2
- package/dist/cli/chunks/{chunk-KJ5A54ZH.js → chunk-RV74I3YO.js} +2 -2
- package/dist/cli/chunks/{chunk-UDSB3XCG.js → chunk-S75SOOZL.js} +2 -2
- package/dist/cli/chunks/{chunk-BPDAQB3F.js → chunk-SASBO5Y5.js} +2 -2
- package/dist/cli/chunks/{chunk-VJBJRFUO.js → chunk-SDLWKRVL.js} +9 -9
- package/dist/cli/chunks/{chunk-J6ASX536.js → chunk-SHKOCGNK.js} +2 -2
- package/dist/cli/chunks/{chunk-J35JWDJE.js → chunk-SI6DPU5D.js} +1 -1
- package/dist/cli/chunks/{chunk-V3MGY76S.js → chunk-SJ6Y4725.js} +2 -2
- package/dist/cli/chunks/{chunk-FTYRPEJS.js → chunk-SR52XP5F.js} +1 -1
- package/dist/cli/chunks/{chunk-ZUE524JL.js → chunk-SSUAAX3F.js} +2 -2
- package/dist/cli/chunks/{chunk-VG32EEUG.js → chunk-SSYAQZXA.js} +2 -2
- package/dist/cli/chunks/{chunk-HTVGHHX2.js → chunk-SUDMM5SO.js} +2 -2
- package/dist/cli/chunks/{chunk-K2SMP4OD.js → chunk-TIUKLYAI.js} +1 -1
- package/dist/cli/chunks/{chunk-VCVRZD4Y.js → chunk-TVGI32MB.js} +33 -33
- package/dist/cli/chunks/{chunk-CAZM63TP.js → chunk-U2A7NHZA.js} +2 -2
- package/dist/cli/chunks/{chunk-WBC6WB32.js → chunk-UE5ZOZR2.js} +2 -2
- package/dist/cli/chunks/{chunk-BQJ7CV53.js → chunk-UHEOGZLX.js} +12 -12
- package/dist/cli/chunks/chunk-UNGBRZDK.js +12 -0
- package/dist/cli/chunks/{chunk-XN3KCKAM.js → chunk-V5NHZV7S.js} +2 -2
- package/dist/cli/chunks/{chunk-UNYTHZDZ.js → chunk-VJCIEHEF.js} +1 -1
- package/dist/cli/chunks/{chunk-5Y7UFHJD.js → chunk-VMDFFTCK.js} +1 -1
- package/dist/cli/chunks/chunk-VSIKHWZ4.js +29 -0
- package/dist/cli/chunks/{chunk-UPWLMIDY.js → chunk-VWPM27GU.js} +2 -2
- package/dist/cli/chunks/{chunk-USAKCGHC.js → chunk-VXFLJNCA.js} +2 -2
- package/dist/cli/chunks/{chunk-WKI46WWN.js → chunk-W5HQUIML.js} +2 -2
- package/dist/cli/chunks/{chunk-Z54G2YOL.js → chunk-WP4RETKG.js} +2 -2
- package/dist/cli/chunks/{chunk-IRPNEXOU.js → chunk-XIIQ5QTT.js} +2 -2
- package/dist/cli/chunks/{chunk-O32BFQV4.js → chunk-XIQW7EFL.js} +2 -2
- package/dist/cli/chunks/{chunk-TW6Z6W4X.js → chunk-XWUWX7BV.js} +13 -13
- package/dist/cli/chunks/{chunk-57FX3GP6.js → chunk-Y4PFUMOU.js} +1 -1
- package/dist/cli/chunks/chunk-YAPLJR7K.js +2 -0
- package/dist/cli/chunks/{chunk-4T7XV5KQ.js → chunk-YLMNVLDK.js} +1 -1
- package/dist/cli/chunks/{chunk-TSP6SU5V.js → chunk-YNMJEDN5.js} +2 -2
- package/dist/cli/chunks/{chunk-PWQWKYBG.js → chunk-YPBSUGMI.js} +1 -1
- package/dist/cli/chunks/{chunk-QP2HLKTS.js → chunk-YRAX7SFJ.js} +2 -2
- package/dist/cli/chunks/{chunk-O3ERGUXH.js → chunk-YTHTQPWR.js} +1 -1
- package/dist/cli/chunks/{chunk-MR2OPUSA.js → chunk-YU2BDRSD.js} +1 -1
- package/dist/cli/chunks/chunk-ZB3LEFYG.js +2 -0
- package/dist/cli/chunks/{chunk-2W5MQDHM.js → chunk-ZFL436FN.js} +2 -2
- package/dist/cli/chunks/{chunk-7MISCSL5.js → chunk-ZJH5MU2I.js} +2 -2
- package/dist/cli/chunks/{chunk-52KOPIMI.js → chunk-ZQ2XW3IP.js} +2 -2
- package/dist/cli/chunks/chunk-ZR2TKVXQ.js +14 -0
- package/dist/cli/chunks/{ci-UMA2SMNW.js → ci-MFUR4CWV.js} +2 -2
- package/dist/cli/chunks/{ci-config-UQSILJFQ.js → ci-config-PNDLQ6XV.js} +2 -2
- package/dist/cli/chunks/{ci-output-U6YZLLKH.js → ci-output-PFZ4M7NC.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-ATYQP6X2.js → circuit-breaker-5HH6NLZN.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-6YHFD7AN.js → claude-flow-setup-QCKYLGLC.js} +2 -2
- package/dist/cli/chunks/client-MHQRTZM4.js +2 -0
- package/dist/cli/chunks/{cline-installer-EPE7IOZE.js → cline-installer-EASVPFXR.js} +2 -2
- package/dist/cli/chunks/{code-NUEJ4XYO.js → code-UJXDVYRK.js} +4 -3
- package/dist/cli/chunks/{code-index-extractor-D4DBT6OL.js → code-index-extractor-BZJ3UDP4.js} +2 -2
- package/dist/cli/chunks/{codex-installer-633SM4LR.js → codex-installer-XSQZUVOZ.js} +4 -4
- package/dist/cli/chunks/{completions-WUKVIW3L.js → completions-OWOOJFI2.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-F73ACR5H.js → complexity-analyzer-KP5TOHDT.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-QH42TKMS.js → continuedev-installer-IFKQXLHM.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-Y3XC7BTT.js → copilot-installer-IGJ6KGQY.js} +2 -2
- package/dist/cli/chunks/core-handlers-UAK3LLJE.js +2 -0
- package/dist/cli/chunks/{cost-tracker-57QPV7E3.js → cost-tracker-MMDDNKZB.js} +2 -2
- package/dist/cli/chunks/{coverage-IBCHMBCR.js → coverage-LUH2B7NT.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-WTRZQPNQ.js +2 -0
- package/dist/cli/chunks/{cursor-installer-F4UYQHIN.js → cursor-installer-4YLM5GWM.js} +2 -2
- package/dist/cli/chunks/daemon-CAVZ7OFV.js +18 -0
- package/dist/cli/chunks/{daemon-XR4Q6YZF.js → daemon-MZKVM4CJ.js} +3 -3
- package/dist/cli/chunks/{dag-attention-scheduler-ZR5ZD3TW.js → dag-attention-scheduler-X4CYW665.js} +2 -2
- package/dist/cli/chunks/{detect-GEGYURLL.js → detect-7BM2XINO.js} +2 -2
- package/dist/cli/chunks/{dist-node-JU3KT2JO.js → dist-node-Y5APLEYB.js} +2 -2
- package/dist/cli/chunks/{domain-handler-7QI3FJGE.js → domain-handler-X3ZRJNAH.js} +2 -2
- package/dist/cli/chunks/{domain-plugins-O2YRM2PD.js → domain-plugins-2UW5KQJB.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-7J3S2OS6.js → domain-transfer-35W4CIBV.js} +2 -2
- package/dist/cli/chunks/dream-EJY24JN6.js +2 -0
- package/dist/cli/chunks/embed-and-insert-pattern-COG4C7ZI.js +3 -0
- package/dist/cli/chunks/embedding-space-SBM2MZD2.js +2 -0
- package/dist/cli/chunks/{eval-RVMCIUOR.js → eval-4QA2SROK.js} +2 -2
- package/dist/cli/chunks/experience-capture-middleware-Z6BF6KYM.js +40 -0
- package/dist/cli/chunks/{fast-paths-QUKPKWKZ.js → fast-paths-FIORX6GN.js} +2 -2
- package/dist/cli/chunks/{feature-flags-K7JXNKJI.js → feature-flags-6LYI2T4G.js} +2 -2
- package/dist/cli/chunks/{feature-flags-5JCSKL2P.js → feature-flags-ZOO7LMIC.js} +2 -2
- package/dist/cli/chunks/file-discovery-UZSFSS4V.js +2 -0
- package/dist/cli/chunks/{fleet-II4Q6HXK.js → fleet-7WF53H4F.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-M7VO2EMS.js → gnn-wrapper-KJ6B7BRM.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-ND5CY26N.js → heartbeat-handler-DEKKMOVW.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-NVR356I7.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-LFMPLUJU.js +2 -0
- package/dist/cli/chunks/hnsw-index-POCPMVJH.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-N3AUUUU7.js → hnsw-legacy-bridge-L27WS27N.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-NZY3E5EN.js → hnswlib-node-4YOQC6L4.js} +2 -2
- package/dist/cli/chunks/{hooks-QVJDTII5.js → hooks-TAOKV4EJ.js} +23 -22
- package/dist/cli/chunks/hybrid-backend-4STAO7CV.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-ZRY6MTDV.js → hypergraph-engine-BODRJLHL.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-56DO4XZQ.js → hypergraph-handler-RKMYJNTU.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-3VIIISBQ.js +2 -0
- package/dist/cli/chunks/{init-guard-DTF4EVUY.js → init-guard-MXHSLSB2.js} +2 -2
- package/dist/cli/chunks/{init-handler-M6CNQHMX.js → init-handler-HUE57IFW.js} +6 -6
- package/dist/cli/chunks/init-wizard-PL6QN6RQ.js +2 -0
- package/dist/cli/chunks/kernel-CCDWT7KS.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-IJN7XKBH.js → kilocode-installer-S333IKYQ.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-UKKPGPDC.js → kiro-installer-WM5DLQWC.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-KFOMEN3H.js +2 -0
- package/dist/cli/chunks/{learning-W2HETWQ4.js → learning-LNHMQLH5.js} +3 -3
- package/dist/cli/chunks/{llm-router-Y546K4VX.js → llm-router-EWFXYZZR.js} +4 -4
- package/dist/cli/chunks/llm-router-service-7NBE2EX6.js +2 -0
- package/dist/cli/chunks/{load-MKAB2AXE.js → load-FGYGWVDK.js} +2 -2
- package/dist/cli/chunks/load-test-UNZUWY3F.js +2 -0
- package/dist/cli/chunks/{mcp-AZKUS6K3.js → mcp-2FHNAAOM.js} +2 -2
- package/dist/cli/chunks/{memory-ZDOQN2KU.js → memory-DZMQ73AB.js} +5 -5
- package/dist/cli/chunks/memory-backend-DFGKWA2Q.js +2 -0
- package/dist/cli/chunks/memory-handlers-MP426XRJ.js +2 -0
- package/dist/cli/chunks/{multi-model-executor-WWVXDHG4.js → multi-model-executor-6F2UAEUW.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-YUJNXXWS.js → opencode-installer-XY3BGOTZ.js} +2 -2
- package/dist/cli/chunks/{orchestrator-Z6PWPLRE.js → orchestrator-B4CNKUOS.js} +17 -17
- package/dist/cli/chunks/pattern-null-store-SSVF5TE5.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-TPWPX32U.js → pattern-usage-recorder-R4GUFNMD.js} +2 -2
- package/dist/cli/chunks/{pipeline-4BBGTE4M.js → pipeline-FG5RKVRO.js} +2 -2
- package/dist/cli/chunks/{platform-5GSHXCV5.js → platform-3BT4KEVJ.js} +2 -2
- package/dist/cli/chunks/{plugin-OFDVF5HS.js → plugin-WI4RIN7O.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-NC6MUYGJ.js → prime-radiant-advanced-wasm-7ECDNQFS.js} +2 -2
- package/dist/cli/chunks/project-root-BEANNYWU.js +2 -0
- package/dist/cli/chunks/protocol-executor-FQVIHXZ7.js +2 -0
- package/dist/cli/chunks/{protocol-handler-MPOAAEPA.js → protocol-handler-WNODKPGW.js} +2 -2
- package/dist/cli/chunks/{prove-CDKMAIVM.js → prove-5RHAEPYZ.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-5TFYSE24.js +2 -0
- package/dist/cli/chunks/{quality-ZH4F7R7R.js → quality-WPHR7BGQ.js} +2 -2
- package/dist/cli/chunks/{quality-gate-IDRMW6OE.js → quality-gate-4RKTEZMX.js} +3 -3
- package/dist/cli/chunks/queen-coordinator-Y2OUL7IN.js +2 -0
- package/dist/cli/chunks/real-embeddings-OXLYU7JW.js +2 -0
- package/dist/cli/chunks/{ref-validation-Z5GCGVXK.js → ref-validation-TPAWHOHH.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-IZ2S7PH2.js → roocode-installer-7AVHFNDI.js} +2 -2
- package/dist/cli/chunks/router-EP34O3KB.js +2 -0
- package/dist/cli/chunks/routing-feedback-FJCRKXNG.js +2 -0
- package/dist/cli/chunks/{routing-handler-NAX35VUW.js → routing-handler-YKEDVJSH.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-5YW2SOFF.js → ruvector-commands-JUAMM354.js} +2 -2
- package/dist/cli/chunks/rvf-dual-writer-ILITJSFG.js +2 -0
- package/dist/cli/chunks/rvf-migration-adapter-XF6W4C2N.js +2 -0
- package/dist/cli/chunks/rvf-migration-coordinator-CMKG56AR.js +2 -0
- package/dist/cli/chunks/rvf-native-adapter-7YFW6S4Y.js +2 -0
- package/dist/cli/chunks/{rvf-store-integrity-IPGCAT6C.js → rvf-store-integrity-VJDUIRTX.js} +2 -2
- package/dist/cli/chunks/safe-db-TCAU4FUT.js +2 -0
- package/dist/cli/chunks/schedule-NB5KV435.js +2 -0
- package/dist/cli/chunks/scheduler-JKXGKVK6.js +2 -0
- package/dist/cli/chunks/{security-3IH4BO5Z.js → security-ORDN3RD2.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-ABY7PAY2.js → shared-rvf-adapter-CF4BCIO7.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-6KENLN2W.js → shared-rvf-dual-writer-C32UBR6D.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-IXCNZRTW.js +2 -0
- package/dist/cli/chunks/{standalone-memory-RLFAUGOW.js → standalone-memory-OXRJYZXN.js} +2 -2
- package/dist/cli/chunks/{status-handler-FCOZBPE5.js → status-handler-BCX5D4HY.js} +2 -2
- package/dist/cli/chunks/{structural-health-4RDA5UUM.js → structural-health-LFG7RUU6.js} +2 -2
- package/dist/cli/chunks/sync-OSF7C2NL.js +2 -0
- package/dist/cli/chunks/{sync-KGEEXXCC.js → sync-YJEE2K2L.js} +2 -2
- package/dist/cli/chunks/task-handler-6LXKPTXJ.js +64 -0
- package/dist/cli/chunks/{task-handlers-6H7L2UT4.js → task-handlers-CILP36I7.js} +4 -4
- package/dist/cli/chunks/{test-S7IG6EIX.js → test-SD457QJ6.js} +4 -4
- package/dist/cli/chunks/test-runner-process-VKD65QQU.js +2 -0
- package/dist/cli/chunks/{test-scheduling-7XYXI4L2.js → test-scheduling-ISI2O4Q5.js} +3 -3
- package/dist/cli/chunks/token-bootstrap-VUELSBOS.js +2 -0
- package/dist/cli/chunks/{token-usage-Y2YTPOFE.js → token-usage-XOC5KG7S.js} +2 -2
- package/dist/cli/chunks/{transformers-UCJ3HHHC.js → transformers-LSLQAARK.js} +2 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-YAIPHRIL.js +2 -0
- package/dist/cli/chunks/{types-6CMFPETH.js → types-5BLCGLCR.js} +2 -2
- package/dist/cli/chunks/unified-memory-GI76TXFV.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-GXJ5BTZO.js +2 -0
- package/dist/cli/chunks/unified-persistence-OP7FDQPD.js +2 -0
- package/dist/cli/chunks/{upgrade-K25DN6WU.js → upgrade-RQJYLK3J.js} +2 -2
- package/dist/cli/chunks/{validate-T4V3TBY3.js → validate-QBHWXXCK.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-XSRC576T.js → validate-swarm-IKXBKFB5.js} +2 -2
- package/dist/cli/chunks/visual-security-GZ2MOKWB.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-YOZXHRTN.js → web-tree-sitter-ZF6FIE5R.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-ITPU2IYL.js → windsurf-installer-HQGDZT5D.js} +2 -2
- package/dist/cli/chunks/witness-chain-DCHCAMSQ.js +2 -0
- package/dist/cli/chunks/witness-chain-P3XXXA62.js +2 -0
- package/dist/cli/chunks/witness-chain-repair-PUX2NFDL.js +2 -0
- package/dist/cli/chunks/{witness-chain-verifier-DTDSVKOG.js → witness-chain-verifier-PX2OQ6XT.js} +2 -2
- package/dist/cli/chunks/{witness-key-manager-EWACWGAW.js → witness-key-manager-RXYQNFJB.js} +2 -2
- package/dist/cli/chunks/{workflow-ZIQ4FV42.js → workflow-FBKCA4H6.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-P2APAJAA.js +2 -0
- package/dist/cli/chunks/wrappers-TWSKBTWD.js +2 -0
- package/dist/cli/commands/code.js +4 -0
- package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +10 -2
- package/dist/cli/handlers/task-handler.d.ts +5 -0
- package/dist/cli/handlers/task-handler.js +21 -1
- package/dist/cli/utils/task-result.d.ts +11 -0
- package/dist/cli/utils/task-result.js +39 -0
- package/dist/coordination/handlers/test-execution-handlers.js +92 -58
- package/dist/coordination/mincut/mincut-persistence.js +29 -25
- package/dist/domains/code-intelligence/coordinator.d.ts +4 -0
- package/dist/domains/code-intelligence/coordinator.js +46 -13
- package/dist/domains/code-intelligence/interfaces.d.ts +10 -1
- package/dist/domains/code-intelligence/services/semantic-analyzer.d.ts +32 -7
- package/dist/domains/code-intelligence/services/semantic-analyzer.js +112 -53
- package/dist/domains/learning-optimization/services/learning-coordinator.js +1 -1
- package/dist/domains/quality-assessment/coordinator.js +2 -1
- package/dist/domains/test-execution/coordinator.js +10 -5
- package/dist/domains/test-execution/interfaces.d.ts +12 -0
- package/dist/domains/test-execution/plugin.js +6 -2
- package/dist/domains/test-execution/services/retry-handler.d.ts +2 -0
- package/dist/domains/test-execution/services/retry-handler.js +14 -9
- package/dist/domains/test-execution/services/test-executor.d.ts +1 -0
- package/dist/domains/test-execution/services/test-executor.js +28 -9
- package/dist/domains/visual-accessibility/coordinator.d.ts +15 -7
- package/dist/domains/visual-accessibility/coordinator.js +15 -7
- package/dist/domains/visual-accessibility/interfaces.d.ts +27 -3
- package/dist/domains/visual-accessibility/services/accessibility-contrast.d.ts +39 -0
- package/dist/domains/visual-accessibility/services/accessibility-contrast.js +93 -0
- package/dist/domains/visual-accessibility/services/accessibility-tester-browser.d.ts +18 -3
- package/dist/domains/visual-accessibility/services/accessibility-tester-browser.js +50 -40
- package/dist/domains/visual-accessibility/services/accessibility-tester-checks.d.ts +27 -0
- package/dist/domains/visual-accessibility/services/accessibility-tester-checks.js +137 -0
- package/dist/domains/visual-accessibility/services/accessibility-tester.d.ts +5 -0
- package/dist/domains/visual-accessibility/services/accessibility-tester.js +43 -24
- package/dist/domains/visual-accessibility/services/browser-swarm-coordinator.d.ts +2 -3
- package/dist/domains/visual-accessibility/services/browser-swarm-coordinator.js +8 -14
- package/dist/feedback/coverage-learner.js +13 -9
- package/dist/feedback/test-outcome-tracker.js +13 -9
- package/dist/governance/witness-chain.d.ts +5 -0
- package/dist/governance/witness-chain.js +22 -6
- package/dist/init/init-wizard-hooks.d.ts +1 -1
- package/dist/init/init-wizard-hooks.js +7 -8
- package/dist/init/phases/08-mcp.js +9 -0
- package/dist/init/settings-merge.d.ts +13 -0
- package/dist/init/settings-merge.js +49 -2
- package/dist/integrations/agent-booster-wasm/agent_booster_wasm.js +849 -0
- package/dist/integrations/agent-booster-wasm/agent_booster_wasm_bg.wasm +0 -0
- package/dist/integrations/agent-booster-wasm/index.d.ts +8 -0
- package/dist/integrations/agent-booster-wasm/index.js +25 -2
- package/dist/integrations/agent-booster-wasm/package.json +16 -0
- package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.d.ts +22 -0
- package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.js +115 -45
- package/dist/integrations/agentic-flow/reasoning-bank/pattern-evolution.d.ts +6 -0
- package/dist/integrations/agentic-flow/reasoning-bank/pattern-evolution.js +51 -33
- package/dist/integrations/agentic-flow/reasoning-bank/trajectory-tracker.js +17 -9
- package/dist/integrations/embeddings/cache/EmbeddingCache.d.ts +8 -0
- package/dist/integrations/embeddings/cache/EmbeddingCache.js +24 -10
- package/dist/integrations/ruvector/delta-tracker.d.ts +11 -0
- package/dist/integrations/ruvector/delta-tracker.js +16 -0
- package/dist/integrations/ruvector/sona-persistence.d.ts +10 -0
- package/dist/integrations/ruvector/sona-persistence.js +49 -24
- package/dist/kernel/unified-memory.d.ts +24 -0
- package/dist/kernel/unified-memory.js +63 -8
- package/dist/learning/aqe-learning-engine.js +1 -1
- package/dist/learning/dream/dream-engine.d.ts +3 -2
- package/dist/learning/dream/dream-engine.js +42 -24
- package/dist/learning/dream/dream-lock-retry.d.ts +38 -0
- package/dist/learning/dream/dream-lock-retry.js +66 -0
- package/dist/learning/dream/speculative-dreamer.js +1 -1
- package/dist/learning/embed-and-insert-pattern.js +4 -2
- package/dist/learning/embedder-endpoint-client.d.ts +31 -0
- package/dist/learning/embedder-endpoint-client.js +103 -10
- package/dist/learning/embedding-space.d.ts +12 -0
- package/dist/learning/embedding-space.js +17 -0
- package/dist/learning/experience-capture-middleware.js +25 -13
- package/dist/learning/experience-capture.js +1 -1
- package/dist/learning/experience-consolidation.d.ts +18 -0
- package/dist/learning/experience-consolidation.js +55 -8
- package/dist/learning/experience-space-verification.d.ts +71 -0
- package/dist/learning/experience-space-verification.js +147 -0
- package/dist/learning/pattern-lifecycle.d.ts +40 -4
- package/dist/learning/pattern-lifecycle.js +153 -76
- package/dist/learning/pattern-null-store.d.ts +5 -0
- package/dist/learning/pattern-null-store.js +8 -0
- package/dist/learning/pattern-promotion.js +6 -3
- package/dist/learning/pattern-store.d.ts +6 -0
- package/dist/learning/pattern-store.js +19 -6
- package/dist/learning/qe-reasoning-bank.js +2 -2
- package/dist/learning/real-embeddings.js +3 -1
- package/dist/learning/real-qe-reasoning-bank.d.ts +5 -0
- package/dist/learning/real-qe-reasoning-bank.js +77 -47
- package/dist/learning/rvf-pattern-store.js +6 -2
- package/dist/learning/sqlite-persistence.d.ts +6 -0
- package/dist/learning/sqlite-persistence.js +10 -0
- package/dist/mcp/bundle.js +642 -571
- package/dist/mcp/entry.js +4 -0
- package/dist/mcp/handlers/domain-handler-configs.js +2 -0
- package/dist/mcp/handlers/trajectory-judge.js +1 -1
- package/dist/mcp/protocol-server.js +1 -0
- package/dist/mcp/tools/visual-accessibility/index.js +8 -2
- package/dist/mcp/types.d.ts +6 -0
- package/dist/optimization/session-cache.d.ts +17 -1
- package/dist/optimization/session-cache.js +40 -36
- package/dist/planning/goap-planner.d.ts +6 -0
- package/dist/planning/goap-planner.js +35 -19
- package/dist/planning/plan-executor.js +24 -15
- package/dist/routing/co-execution-repository.js +12 -9
- package/dist/routing/routing-feedback.d.ts +8 -0
- package/dist/routing/routing-feedback.js +46 -24
- package/dist/routing/routing-outcomes-migration.js +7 -2
- package/dist/shared/llm/spend-ledger.d.ts +9 -0
- package/dist/shared/llm/spend-ledger.js +64 -39
- package/dist/shared/sqlite-lock-wait.d.ts +27 -0
- package/dist/shared/sqlite-lock-wait.js +37 -0
- package/dist/shared/sqlite-write-queue.d.ts +28 -0
- package/dist/shared/sqlite-write-queue.js +38 -0
- package/dist/shared/test-runner-project.d.ts +69 -0
- package/dist/shared/test-runner-project.js +186 -0
- package/dist/skills/security-visual-testing/index.d.ts +3 -1
- package/dist/skills/security-visual-testing/index.js +49 -35
- package/dist/skills/security-visual-testing/types.d.ts +19 -3
- package/dist/workers/workers/heartbeat-scheduler.js +5 -5
- package/dist/workers/workers/learning-consolidation.js +8 -7
- package/package.json +4 -2
- package/dist/cli/chunks/adapter-23KA2YW7.js +0 -2
- package/dist/cli/chunks/agent-booster-wasm-2DLAEZK6.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-MUICAXW5.js +0 -2
- package/dist/cli/chunks/base-XPWGYDKD.js +0 -2
- package/dist/cli/chunks/browser-workflow-UMQVBVGK.js +0 -2
- package/dist/cli/chunks/chunk-3FITMWWJ.js +0 -21
- package/dist/cli/chunks/chunk-ARRBXCII.js +0 -4
- package/dist/cli/chunks/chunk-BBYJBZHG.js +0 -14
- package/dist/cli/chunks/chunk-BM3EJLMV.js +0 -153
- package/dist/cli/chunks/chunk-D3ZZ2NLL.js +0 -62
- package/dist/cli/chunks/chunk-DLTB5KCR.js +0 -2
- package/dist/cli/chunks/chunk-DRLSJJIC.js +0 -6
- package/dist/cli/chunks/chunk-HAYKLXCT.js +0 -744
- package/dist/cli/chunks/chunk-HHBF2BZC.js +0 -65
- package/dist/cli/chunks/chunk-K7RT6ITZ.js +0 -2
- package/dist/cli/chunks/chunk-L752CNG3.js +0 -13
- package/dist/cli/chunks/chunk-MQXWG55U.js +0 -12
- package/dist/cli/chunks/chunk-WM2QRIRD.js +0 -14
- package/dist/cli/chunks/chunk-WRC3HLUY.js +0 -29
- package/dist/cli/chunks/chunk-XTZGAG6P.js +0 -27
- package/dist/cli/chunks/chunk-YKQWIXUY.js +0 -2
- package/dist/cli/chunks/client-E43GWLQH.js +0 -2
- package/dist/cli/chunks/core-handlers-R5A3SQDY.js +0 -2
- package/dist/cli/chunks/cross-domain-router-LLYVPZF6.js +0 -2
- package/dist/cli/chunks/daemon-BYYPIJ7G.js +0 -18
- package/dist/cli/chunks/dream-6C4NURSE.js +0 -2
- package/dist/cli/chunks/embed-and-insert-pattern-URES5Q6J.js +0 -3
- package/dist/cli/chunks/experience-capture-middleware-SYJQSBKE.js +0 -40
- package/dist/cli/chunks/file-discovery-J5IE5KP7.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-FC5PBTMN.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-47UIVOBG.js +0 -2
- package/dist/cli/chunks/hnsw-index-3AKVLOZQ.js +0 -2
- package/dist/cli/chunks/hybrid-backend-YAOSNX47.js +0 -2
- package/dist/cli/chunks/impact-analyzer-4FMJXM4M.js +0 -2
- package/dist/cli/chunks/init-wizard-RTLCRWDT.js +0 -2
- package/dist/cli/chunks/kernel-2OWIGGGT.js +0 -2
- package/dist/cli/chunks/knowledge-graph-25XXKDJN.js +0 -2
- package/dist/cli/chunks/llm-router-service-G3EIN4UB.js +0 -2
- package/dist/cli/chunks/load-test-D6QYNIVT.js +0 -2
- package/dist/cli/chunks/memory-backend-LDFFZMEQ.js +0 -2
- package/dist/cli/chunks/memory-handlers-3SQVY7FE.js +0 -2
- package/dist/cli/chunks/pattern-null-store-KDVRM7PW.js +0 -2
- package/dist/cli/chunks/project-root-DDGBWDP6.js +0 -2
- package/dist/cli/chunks/protocol-executor-KBOLLCWA.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-GRXBT7FC.js +0 -2
- package/dist/cli/chunks/queen-coordinator-L2QWMJ5Q.js +0 -2
- package/dist/cli/chunks/real-embeddings-I2UVNNB3.js +0 -2
- package/dist/cli/chunks/router-FT5WJPUH.js +0 -2
- package/dist/cli/chunks/routing-feedback-EO2MKOUX.js +0 -2
- package/dist/cli/chunks/rvf-dual-writer-WHBFQJVU.js +0 -2
- package/dist/cli/chunks/rvf-migration-adapter-YT3APF2I.js +0 -2
- package/dist/cli/chunks/rvf-migration-coordinator-VUIZHTVG.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-37PUFKQD.js +0 -2
- package/dist/cli/chunks/safe-db-TDZKUOZJ.js +0 -2
- package/dist/cli/chunks/schedule-CRKTRY2A.js +0 -2
- package/dist/cli/chunks/scheduler-6ZBDVQWN.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-FFJQAIKW.js +0 -2
- package/dist/cli/chunks/sync-54LUAUTK.js +0 -2
- package/dist/cli/chunks/task-handler-K3OXHYKU.js +0 -62
- package/dist/cli/chunks/test-runner-process-OTQDAJLN.js +0 -2
- package/dist/cli/chunks/token-bootstrap-3QMABE45.js +0 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-D6JTTHTP.js +0 -2
- package/dist/cli/chunks/unified-memory-QARWQKJ2.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-LHY3DXCP.js +0 -2
- package/dist/cli/chunks/unified-persistence-WEYYGLHM.js +0 -2
- package/dist/cli/chunks/visual-security-O4ALMCXQ.js +0 -2
- package/dist/cli/chunks/witness-chain-B3YW5NMS.js +0 -2
- package/dist/cli/chunks/witness-chain-PIYR72HJ.js +0 -2
- package/dist/cli/chunks/witness-chain-repair-YUG7E3UX.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-3ZN2BCGY.js +0 -2
- package/dist/cli/chunks/wrappers-PW2O27LL.js +0 -2
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
|
|
2
|
+
import{i as j}from"./chunk-HGWXF45W.js";import{B as me,g as w,h as E,i as k,w as ue}from"./chunk-MO55CVMT.js";import{c as le,d as Re}from"./chunk-JDIYMZCQ.js";import{a as Te,b as _,d as ee}from"./chunk-V5NHZV7S.js";import{a as de,d as Pe}from"./chunk-FLNAW7C4.js";import{a as v}from"./chunk-YAPLJR7K.js";import{c as b}from"./chunk-G5RHFBAY.js";import{c as I}from"./chunk-AGRV5B3T.js";import{d as T,e as z}from"./chunk-KPRCB5LT.js";import{a as d,b as L,e as P}from"./chunk-KNSRL6NO.js";import{e as Ce}from"./chunk-AJMJNQMP.js";var A={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"}}]},ve={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();k();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(Te(),1);P();import{randomUUID as _e}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"&&Object.hasOwn(r,i))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()}_${_e().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 xe}from"child_process";import{createConnection as ke}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 $=class{process=null;connection=null;config;constructor(e){this.config=e}checkPort(e,t,n=2e3){return new Promise(r=>{let i=ke({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=xe("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 $e(l){return new $(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 M(l){return l.connectionString?new B(l.connectionString):new $(l)}k();P();v();import{createRequire as Me}from"module";var N=b.create("postgres-writer"),Ne=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=Ne("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
|
+
INSERT INTO ${u} (${p.join(", ")})
|
|
4
|
+
VALUES ${s.join(", ")}
|
|
5
|
+
${h}
|
|
6
|
+
`;try{return(await this.client.query(y,a)).rowCount||0}catch(f){throw N.debug(`Upsert failed for ${e}`,{error:d(f)}),f}}async execute(e,t){if(!this.client)throw new Error("Not connected");await this.client.query(e,t)}async query(e,t){if(!this.client)throw new Error("Not connected");return(await this.client.query(e,t)).rows}async close(){this.inTransaction&&await this.rollback(),this.client&&(await this.client.end(),this.client=null,this.connected=!1,console.log("[PostgresWriter] Connection closed"))}serializeValue(e,t){if(e==null)return null;if(Buffer.isBuffer(e)){try{let n=new Float32Array(e.buffer,e.byteOffset,e.length/4);if(n.length>0&&n.length<=1024)return`[${Array.from(n).join(",")}]`}catch(n){N.debug("Buffer to float array conversion failed",{error:n instanceof Error?n.message:String(n)})}return null}if(typeof e=="number")return e>9466848e5&&e<41024448e5?new Date(e).toISOString():e>946684800&&e<4102444800?new Date(e*1e3).toISOString():e;if(Array.isArray(e))return e.length>0&&typeof e[0]=="number"?`[${e.join(",")}]`:JSON.stringify(e);if(typeof e=="object"){let n=JSON.stringify(e);if(t&&this.isJsonbColumn(t)){n=n.replace(/\u0000/g,"");try{JSON.parse(n)}catch{return JSON.stringify(String(e))}}return n}if(typeof e=="string"){if(e===""&&t&&["created_at","updated_at","last_used_at","started_at","ended_at","completed_at","expires_at","last_update"].includes(t))return null;if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(e))return e;let n=parseInt(e,10);if(!isNaN(n)&&n>9466848e5&&n<41024448e5)return new Date(n).toISOString();if(t&&this.isJsonbColumn(t)){let r=e.replace(/\u0000/g,"");try{return JSON.parse(r),r}catch{return JSON.stringify(r)}}}return e}isJsonbColumn(e){return["action_value","state","action","next_state","preconditions","effects","metadata","value","payload","context_json","template_json","execution_trace","action_sequence","initial_state","goal_state","sequence","task_json","decision_json","steps_json","metadata_json"].includes(e)}inferConflictColumns(e,t){let n=e.includes(".")?e.split(".")[1]:e,r=["qe_patterns","sona_patterns","goap_actions","goap_plans","patterns","events","routing_outcomes","qe_trajectories","dream_insights","intelligence_memories"];return t.includes("id")&&r.includes(n)?["id"]:n==="memory_entries"&&t.includes("key")&&t.includes("source_env")?t.includes("partition")?["key","partition","source_env"]:["key","source_env"]:n==="claude_flow_memory"&&t.includes("key")&&t.includes("source_env")?["key","source_env"]:n==="qlearning_patterns"&&t.includes("state")&&t.includes("action")&&t.includes("source_env")?["state","action","source_env"]:n==="claude_flow_workers"&&t.includes("worker_type")&&t.includes("source_env")?["worker_type","source_env"]:[]}createMockClient(){let e=[];return{async connect(){console.log("[MockPgClient] Connected (mock mode)")},async query(t,n){return console.log(`[MockPgClient] Query: ${t.slice(0,100)}... (${n?.length||0} params)`),{rows:e,rowCount:0}},async end(){console.log("[MockPgClient] Disconnected (mock mode)")}}}};function O(l){return new J(l)}k();P();v();var G=b.create("postgres-reader"),Q=class{writer;environment;constructor(e){this.writer=e.writer,this.environment=e.environment}sanitizeCloudTable(e){let t=e.indexOf(".");if(t===-1||t===0||t===e.length-1)throw new Error(`Invalid cloud table format '${e}': expected 'schema.table' (e.g., 'aqe.qe_patterns')`);let n=e.substring(0,t),r=e.substring(t+1);return`${E(n)}.${E(r)}`}async readAll(e){let t=this.sanitizeCloudTable(e.cloudTable),n,r;this.environment!=="all"?(n=`SELECT * FROM ${t} WHERE source_env = $1`,r=[this.environment]):(n=`SELECT * FROM ${t}`,r=[]);try{let i=await this.writer.query(n,r);return G.debug(`Read ${i.length} records from ${e.cloudTable}`,{env:this.environment}),i.map(o=>this.transformRecord(o,e))}catch(i){throw new Error(`Failed to read from ${e.cloudTable}: ${d(i)}`)}}async readChanged(e,t){let n=this.sanitizeCloudTable(e.cloudTable),r=await this.findTimestampColumn(n);if(!r)return G.debug(`No timestamp column found for ${e.cloudTable}, falling back to readAll`),this.readAll(e);let i,o;this.environment!=="all"?(i=`SELECT * FROM ${n} WHERE ${E(r)} > $1 AND source_env = $2`,o=[t.toISOString(),this.environment]):(i=`SELECT * FROM ${n} WHERE ${E(r)} > $1`,o=[t.toISOString()]);try{return(await this.writer.query(i,o)).map(a=>this.transformRecord(a,e))}catch(s){return G.debug(`Changed query failed for ${e.cloudTable}, falling back to readAll`,{error:d(s)}),this.readAll(e)}}async count(e){let t=this.sanitizeCloudTable(e.cloudTable),n,r;this.environment!=="all"?(n=`SELECT COUNT(*) as count FROM ${t} WHERE source_env = $1`,r=[this.environment]):(n=`SELECT COUNT(*) as count FROM ${t}`,r=[]);try{await this.writer.beginTransaction(),await this.writer.execute("SET LOCAL enable_indexonlyscan = off");let i=await this.writer.query(n,r);return await this.writer.commit(),typeof i[0]?.count=="string"?parseInt(i[0].count,10):i[0]?.count||0}catch(i){try{await this.writer.rollback()}catch{}return G.debug(`Count query failed for ${e.cloudTable}`,{error:d(i)}),-1}}transformRecord(e,t){let n={};for(let[r,i]of Object.entries(e)){if(t.dropColumns?.includes(r))continue;let o=t.columnMap?.[r]||r;n[o]=this.transformValue(i,r,t.transforms)}return n}transformValue(e,t,n){if(e==null)return null;let r=n?.[t];return r==="boolean-to-int"?typeof e=="boolean"?e?1:0:e==="true"||e==="t"?1:e==="false"||e==="f"?0:e:r==="jsonb-to-text"?typeof e=="object"?JSON.stringify(e):e:r==="timestamptz-to-text"?e instanceof Date?e.toISOString():e:typeof e=="object"&&!Buffer.isBuffer(e)?JSON.stringify(e):e instanceof Date?e.toISOString():typeof e=="boolean"?e?1:0:e}async findTimestampColumn(e){let t=["updated_at","created_at","last_update","last_used_at"];try{let n=e.split(".")[0],r=e.split(".")[1],o=(await this.writer.query(`SELECT column_name FROM information_schema.columns
|
|
7
|
+
WHERE table_schema = $1 AND table_name = $2
|
|
8
|
+
AND data_type IN ('timestamp with time zone', 'timestamp without time zone')`,[n,r])).map(s=>s.column_name);for(let s of t)if(o.includes(s))return s;return o[0]||null}catch{return null}}};function ie(l){return new Q(l)}z();k();P();v();import*as ye from"fs";var D=b.create("sqlite-writer"),V=class{db=null;dbPath;batchSize;constructor(e){this.dbPath=e.dbPath,this.batchSize=e.batchSize||500}async connect(){if(!this.db){if(!ye.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}. Run 'aqe init' to create it.`);try{this.db=T(this.dbPath),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),D.debug(`Opened SQLite database: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${d(e)}`)}}}async upsert(e,t){if(!this.db)throw new Error("Not connected");if(t.length===0)return 0;let n=w(e);if(!this.tableExists(e))return console.warn(`[SQLiteWriter] Table '${e}' does not exist in local database \u2014 ${t.length} records skipped. Run 'aqe init' to create schema.`),0;let r=this.getTableColumns(e);if(r.length===0)return D.debug(`No columns found for table ${e}`),0;let i=new Set(r),o=0;for(let s=0;s<t.length;s+=this.batchSize){let a=t.slice(s,s+this.batchSize);try{let c=this.upsertBatch(n,a,i);o+=c}catch(c){let u=Math.floor(s/this.batchSize)+1;D.debug(`Batch ${u} failed for ${e}, retrying individually`,{error:d(c)});let p=0;for(let m of a)try{p+=this.upsertBatch(n,[m],i)}catch(g){let h=m.id||m.key||"?";D.debug(`Skipped record ${String(h).slice(0,50)} in ${e}`,{error:d(g)})}o+=p}}return o}async count(e){if(!this.db)throw new Error("Not connected");if(!this.tableExists(e))return 0;try{let t=w(e);return this.db.prepare(`SELECT COUNT(*) as count FROM ${t}`).get().count}catch{return 0}}async close(){this.db&&(this.db.close(),this.db=null,D.debug("SQLite writer closed"))}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{return!1}}getTableColumns(e){if(!this.db)return[];try{let t=w(e);return this.db.prepare(`PRAGMA table_info(${t})`).all().map(r=>r.name)}catch{return[]}}getPrimaryKeyColumns(e){if(!this.db)return[];try{let t=w(e);return this.db.prepare(`PRAGMA table_info(${t})`).all().filter(i=>i.pk>0).sort((i,o)=>i.pk-o.pk).map(i=>i.name)}catch{return[]}}upsertBatch(e,t,n){if(!this.db||t.length===0)return 0;let r=t[0],i=Object.keys(r).filter(g=>n.has(g));if(i.length===0)return 0;let o=i.map(E),s=i.map(()=>"?").join(", "),a=e.replace(/"/g,""),c=this.getPrimaryKeyColumns(a),u;if(c.length>0){let g=c.map(E),h=i.filter(y=>!c.includes(y));if(h.length>0){let y=h.map(f=>`${E(f)} = excluded.${E(f)}`).join(", ");u=`INSERT INTO ${e} (${o.join(", ")}) VALUES (${s}) ON CONFLICT(${g.join(", ")}) DO UPDATE SET ${y}`}else u=`INSERT OR IGNORE INTO ${e} (${o.join(", ")}) VALUES (${s})`}else u=`INSERT OR IGNORE INTO ${e} (${o.join(", ")}) VALUES (${s})`;let p=this.db.prepare(u);return this.db.transaction(g=>{let h=0;for(let y of g){let f=i.map(S=>this.serializeValue(y[S]));p.run(...f),h++}return h})(t)}serializeValue(e){return e==null?null:typeof e=="object"&&!Buffer.isBuffer(e)&&!(e instanceof Date)?JSON.stringify(e):e instanceof Date?e.toISOString():typeof e=="boolean"?e?1:0:(Buffer.isBuffer(e),e)}};function oe(l){return new V(l)}v();P();var Oe=b.create("sync-agent"),H=class{config;readers=new Map;writer=null;report=null;constructor(e={}){this.config={...x,...e,local:{...x.local,...e.local},cloud:{...x.cloud,...e.cloud},sync:{...x.sync,...e.sync}}}async initialize(){this.log("Initializing sync agent...");let e=this.config.sync.sources.filter(t=>t.enabled!==!1);for(let t of e){let n=this.createReader(t);if(n)try{await n.initialize(),this.readers.set(t.name,n),this.log(`Initialized reader: ${t.name}`)}catch(r){this.log(`Warning: Failed to initialize reader ${t.name}: ${r}`,"warn")}}this.log(`Initialized ${this.readers.size} readers`)}async syncAll(){this.report=this.createReport("full");try{await this.connectToCloud();let e=this.config.sync.sources.filter(r=>r.enabled!==!1&&this.readers.has(r.name)).sort((r,i)=>{let o={high:0,medium:1,low:2};return o[r.priority]-o[i.priority]}),t=0,n=e.length;for(let r of e){this.progress(`Syncing ${r.name}...`,t/n);let i=await this.syncSource(r);this.report.results.push(i),t++}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(e){this.report.status="failed",this.report.errors.push(d(e))}finally{await this.disconnect(),this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((e,t)=>e+t.recordsSynced,0),this.report.totalConflictsResolved=this.report.results.reduce((e,t)=>e+t.conflictsResolved,0)}return this.report}async syncIncremental(e){this.report=this.createReport("incremental");let t=e||new Date(Date.now()-1440*60*1e3);try{await this.connectToCloud();let n=this.config.sync.sources.filter(r=>r.enabled!==!1&&this.readers.has(r.name)&&r.mode!=="full").sort((r,i)=>{let o={high:0,medium:1,low:2};return o[r.priority]-o[i.priority]});for(let r of n){this.progress(`Incremental sync ${r.name}...`,0);let i=await this.syncSourceIncremental(r,t);this.report.results.push(i)}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(n){this.report.status="failed",this.report.errors.push(d(n))}finally{await this.disconnect(),this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((n,r)=>n+r.recordsSynced,0)}return this.report}async syncSource(e){let t=Date.now(),n={success:!1,table:e.targetTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0,warnings:[]};try{let r=this.readers.get(e.name);if(!r)throw new Error(`Reader not found: ${e.name}`);let i=await r.readAll();if(this.log(`Read ${i.length} records from ${e.name}`),i.length===0)return n.success=!0,n.durationMs=Date.now()-t,n;if(this.writer&&!this.config.sync.dryRun){let o=await this.writer.upsert(e.targetTable,i,{skipIfExists:e.mode==="append"});n.recordsSynced=o}else n.recordsSynced=i.length,this.log(`[DRY RUN] Would sync ${i.length} records to ${e.targetTable}`);n.success=!0}catch(r){n.error=d(r),this.config.onError?.(L(r),e.name)}return n.durationMs=Date.now()-t,n}async syncSourceIncremental(e,t){let n=Date.now(),r={success:!1,table:e.targetTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0};try{let i=this.readers.get(e.name);if(!i)throw new Error(`Reader not found: ${e.name}`);let o=await i.readChanged(t);if(this.log(`Read ${o.length} changed records from ${e.name} (since ${t.toISOString()})`),o.length===0)return r.success=!0,r.durationMs=Date.now()-n,r;if(this.writer&&!this.config.sync.dryRun){let s=await this.writer.upsert(e.targetTable,o);r.recordsSynced=s}else r.recordsSynced=o.length;r.success=!0}catch(i){r.error=d(i)}return r.durationMs=Date.now()-n,r}async getStatus(){let e=[];for(let t of this.config.sync.sources){let n=this.readers.get(t.name);if(n){let r=await n.count();e.push({name:t.name,type:t.type,targetTable:t.targetTable,recordCount:r,enabled:t.enabled!==!1,priority:t.priority})}else e.push({name:t.name,type:t.type,targetTable:t.targetTable,recordCount:0,enabled:t.enabled!==!1,priority:t.priority,error:"Reader not initialized"})}return{sources:e}}async verify(){let e=[];for(let t of this.config.sync.sources.filter(n=>n.enabled!==!1)){let n=this.readers.get(t.name);if(!n)continue;let r=await n.count(),i=0;if(this.writer)try{await this.writer.beginTransaction(),await this.writer.execute("SET LOCAL enable_indexonlyscan = off");let o=await this.writer.query(`SELECT COUNT(*) as count FROM ${t.targetTable} WHERE source_env = $1`,[this.config.environment]);await this.writer.commit(),i=o[0]?.count||0}catch(o){try{await this.writer.rollback()}catch{}Oe.debug("Cloud count query failed",{source:t.name,error:o instanceof Error?o.message:String(o)}),i=-1}e.push({source:t.name,table:t.targetTable,localCount:r,cloudCount:i,match:r===i,diff:r-i})}return{verified:e.every(t=>t.match||t.cloudCount===-1),results:e}}async close(){await this.disconnect();for(let e of Array.from(this.readers.entries())){let[t,n]=e;try{await n.close()}catch(r){this.log(`Warning: Failed to close reader ${t}: ${r}`,"warn")}}this.readers.clear(),this.log("Sync agent closed")}createReader(e){let t=process.cwd(),n=this.config.environment;return e.type==="sqlite"?re({source:e,baseDir:t,environment:n}):e.type==="json"?ne({source:e,baseDir:t,environment:n}):null}async connectToCloud(){if(this.writer)return;let e=M(this.config.cloud);this.writer=O({cloud:this.config.cloud,tunnelManager:e}),await this.writer.connect(),this.log("Connected to cloud database")}async disconnect(){this.writer&&(await this.writer.close(),this.writer=null)}createReport(e){return{syncId:j(),startedAt:new Date,status:"running",environment:this.config.environment,mode:e,results:[],totalRecordsSynced:0,totalConflictsResolved:0,totalDurationMs:0,errors:[]}}log(e,t="info"){if(!this.config.verbose&&t==="info")return;let n=`[CloudSync:${this.config.environment}]`;switch(t){case"warn":console.warn(`${n} ${e}`);break;case"error":console.error(`${n} ${e}`);break;default:console.log(`${n} ${e}`)}}progress(e,t){this.config.onProgress?.(e,t),this.log(e)}};function se(l){return new H(l)}async function De(l){let e=se({...l,verbose:!0});await e.initialize();try{return await e.syncAll()}finally{await e.close()}}async function qe(l,e){let t=se({...e,verbose:!0});await t.initialize();try{return await t.syncIncremental(l)}finally{await t.close()}}import*as Y from"fs";import*as ae from"path";me();P();v();var It=b.create("pull-agent"),X=class{config;reader=null;writer=null;cloudWriter=null;report=null;constructor(e={}){this.config={...A,...e,cloud:{...A.cloud,...e.cloud},sources:e.sources||A.sources}}async initialize(){this.log("Initializing pull sync agent...");let e=M(this.config.cloud);this.cloudWriter=O({cloud:this.config.cloud,tunnelManager:e}),await this.cloudWriter.connect(),this.log("Connected to cloud database"),this.reader=ie({writer:this.cloudWriter,environment:this.config.environment});let t=this.resolveTargetDb();this.writer=oe({dbPath:t}),await this.writer.connect(),this.log(`Connected to local database: ${t}`)}async pullAll(){this.report=this.createReport("full");try{this.ensureInitialized(),this.backupLocalDb();let e=this.getEnabledSources(),t=0;for(let n of e){this.progress(`Pulling ${n.name}...`,t/e.length);let r=await this.pullTable(n);this.report.results.push(r),t++}this.report.status=this.report.results.every(n=>n.success)?"completed":"partial"}catch(e){this.report.status="failed",this.report.errors.push(d(e))}finally{this.finalizeReport()}return this.report}async pullIncremental(e){this.report=this.createReport("incremental");let t=e||new Date(Date.now()-1440*60*1e3);try{this.ensureInitialized(),this.backupLocalDb();let n=this.getEnabledSources().filter(r=>r.mode!=="full");for(let r of n){this.progress(`Incremental pull ${r.name}...`,0);let i=await this.pullTableIncremental(r,t);this.report.results.push(i)}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(n){this.report.status="failed",this.report.errors.push(d(n))}finally{this.finalizeReport()}return this.report}async pullTable(e){let t=Date.now(),n={success:!1,table:e.localTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0,warnings:[]};try{this.ensureInitialized();let r=await this.reader.readAll(e);if(this.log(`Read ${r.length} records from cloud ${e.cloudTable}`),r.length===0)return n.success=!0,n.durationMs=Date.now()-t,n;if(this.config.dryRun)n.recordsSynced=r.length,this.log(`[DRY RUN] Would write ${r.length} records to local ${e.localTable}`);else{let i=await this.writer.upsert(e.localTable,r);n.recordsSynced=i,n.recordsSkipped=r.length-i}n.success=!0}catch(r){n.error=d(r),this.config.onError?.(L(r),e.name)}return n.durationMs=Date.now()-t,n}async pullTableIncremental(e,t){let n=Date.now(),r={success:!1,table:e.localTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0};try{this.ensureInitialized();let i=await this.reader.readChanged(e,t);if(this.log(`Read ${i.length} changed records from cloud ${e.cloudTable} (since ${t.toISOString()})`),i.length===0)return r.success=!0,r.durationMs=Date.now()-n,r;if(this.config.dryRun)r.recordsSynced=i.length;else{let o=await this.writer.upsert(e.localTable,i);r.recordsSynced=o}r.success=!0}catch(i){r.error=d(i)}return r.durationMs=Date.now()-n,r}async verify(){this.ensureInitialized();let e=[];for(let t of this.getEnabledSources()){let n=await this.reader.count(t),r=await this.writer.count(t.localTable);e.push({source:t.name,cloudTable:t.cloudTable,localTable:t.localTable,cloudCount:n,localCount:r,match:n===r||n===-1,diff:r-n})}return{verified:e.every(t=>t.match),results:e}}async close(){this.writer&&(await this.writer.close(),this.writer=null),this.cloudWriter&&(await this.cloudWriter.close(),this.cloudWriter=null),this.reader=null,this.log("Pull sync agent closed")}ensureInitialized(){if(!this.reader||!this.writer)throw new Error("PullSyncAgent not initialized. Call initialize() first.")}getEnabledSources(){let e=this.config.sources.filter(n=>n.enabled);if(this.config.tables&&this.config.tables.length>0){let n=new Set(this.config.tables);e=e.filter(r=>n.has(r.localTable)||n.has(r.name))}let t={high:0,medium:1,low:2};return e.sort((n,r)=>t[n.priority]-t[r.priority])}resolveTargetDb(){return this.config.targetDb?ae.resolve(this.config.targetDb):ae.resolve(I(),".agentic-qe/memory.db")}backupLocalDb(){if(this.config.dryRun)return;let e=this.resolveTargetDb();if(!Y.existsSync(e))return;let t=Math.floor(Date.now()/1e3),n=`${e}.bak-${t}`;try{Y.copyFileSync(e,n),this.log(`Backed up local DB to ${n}`)}catch(r){this.log(`Warning: Failed to backup local DB: ${d(r)}`,"warn")}}createReport(e){return{syncId:j(),startedAt:new Date,status:"running",environment:this.config.environment,mode:e,results:[],totalRecordsSynced:0,totalConflictsResolved:0,totalDurationMs:0,errors:[]}}finalizeReport(){this.report&&(this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((e,t)=>e+t.recordsSynced,0),this.report.totalConflictsResolved=this.report.results.reduce((e,t)=>e+t.conflictsResolved,0))}log(e,t="info"){if(!this.config.verbose&&t==="info")return;let n=`[PullSync:${this.config.environment}]`;switch(t){case"warn":console.warn(`${n} ${e}`);break;case"error":console.error(`${n} ${e}`);break;default:console.log(`${n} ${e}`)}}progress(e,t){this.config.onProgress?.(e,t),this.log(e)}};function ce(l){return new X(l)}async function Le(l){let e=ce({...l,verbose:!0});await e.initialize();try{return await e.pullAll()}finally{await e.close()}}async function Ie(l,e){let t=ce({...e,verbose:!0});await t.initialize();try{return await t.pullIncremental(l)}finally{await t.close()}}z();me();ee();Re();import{join as be}from"path";import{existsSync as ze,mkdirSync as je}from"fs";var K=class{memoryCache;maxSize;ttl;persistent;compression;db=null;storagePath;useUnified;unifiedMemory=null;pendingWrites=[];dbInitializing=!1;constructor(e={}){this.maxSize=e.maxSize||1e4,this.ttl=e.ttl||0,this.persistent=e.persistent??!0,this.compression=e.compression??!0,this.useUnified=e.useUnified??!0,this.storagePath=e.storagePath||be(I(),".agentic-qe","embeddings-cache.db"),this.memoryCache=new Map;let t=["text","code","test","coverage","defect"];for(let n of t)this.memoryCache.set(n,new Map);this.persistent&&this.initializePersistentStorage()}initializePersistentStorage(){try{if(this.useUnified)this.unifiedMemory=ue(),this.dbInitializing=!0,this.unifiedMemory.initialize().then(()=>{this.db=this.unifiedMemory.getDatabase(),this.dbInitializing=!1,console.log(`[EmbeddingCache] Using unified storage: ${this.unifiedMemory.getDbPath()}`),this.loadFromDisk(),this.flushPendingWrites()}).catch(e=>{console.warn("[EmbeddingCache] Failed to initialize unified storage:",e),this.db=null,this.dbInitializing=!1,this.unifiedMemory=null,this.pendingWrites=[]});else{let e=be(this.storagePath,"..");ze(e)||je(e,{recursive:!0}),this.db=T(this.storagePath),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.exec(`
|
|
9
|
+
CREATE TABLE IF NOT EXISTS embeddings (
|
|
10
|
+
key TEXT NOT NULL,
|
|
11
|
+
namespace TEXT NOT NULL,
|
|
12
|
+
vector BLOB NOT NULL,
|
|
13
|
+
dimension INTEGER NOT NULL,
|
|
14
|
+
text TEXT NOT NULL,
|
|
15
|
+
timestamp INTEGER NOT NULL,
|
|
16
|
+
quantization TEXT NOT NULL,
|
|
17
|
+
metadata TEXT,
|
|
18
|
+
access_count INTEGER DEFAULT 1,
|
|
19
|
+
last_access INTEGER NOT NULL,
|
|
20
|
+
PRIMARY KEY (key, namespace)
|
|
21
|
+
);
|
|
22
|
+
|
|
23
|
+
CREATE INDEX IF NOT EXISTS idx_namespace ON embeddings(namespace);
|
|
24
|
+
CREATE INDEX IF NOT EXISTS idx_timestamp ON embeddings(timestamp);
|
|
25
|
+
`),console.log(`[EmbeddingCache] Initialized (legacy): ${this.storagePath}`),this.loadFromDisk()}}catch(e){console.warn("Failed to initialize persistent storage:",e),this.db=null}}get(e,t="text"){let n=this.memoryCache.get(t);if(!n)return null;let r=n.get(e);return r?this.ttl>0&&Date.now()-r.lastAccess>this.ttl*1e3?(n.delete(e),null):(r.accessCount++,r.lastAccess=Date.now(),r.embedding):null}set(e,t,n="text"){let r=this.memoryCache.get(n);if(!r)return;r.size>=this.maxSize&&!r.has(e)&&this.evictLRU(n);let i={key:e,embedding:t,accessCount:1,lastAccess:Date.now()};r.set(e,i),this.persistent&&(this.db?this.persistToDisk(e,t,n):this.dbInitializing&&this.pendingWrites.push({key:e,embedding:t,namespace:n}))}has(e,t="text"){return this.memoryCache.get(t)?.has(e)||!1}delete(e,t="text"){let r=this.memoryCache.get(t)?.delete(e)||!1;return r&&this.persistent&&this.db&&this.persist("delete",i=>i.prepare("DELETE FROM embeddings WHERE key = ? AND namespace = ?").run(e,t)),r}clear(e){if(e)this.memoryCache.get(e)?.clear(),this.persistent&&this.db&&this.persist("clear",n=>n.prepare("DELETE FROM embeddings WHERE namespace = ?").run(e));else{for(let t of this.memoryCache.values())t.clear();this.persistent&&this.db&&this.persist("clear",t=>t.exec("DELETE FROM embeddings"))}}getAll(e){let t=[];if(e)this.memoryCache.get(e)?.forEach(r=>t.push(r.embedding));else for(let n of this.memoryCache.values())n.forEach(r=>t.push(r.embedding));return t}evictLRU(e){let t=this.memoryCache.get(e);if(!t||t.size===0)return;let n=null,r=1/0;for(let[i,o]of t.entries())o.lastAccess<r&&(r=o.lastAccess,n=i);if(n&&(t.delete(n),this.persistent&&this.db)){let i=n;this.persist("evict",o=>o.prepare("DELETE FROM embeddings WHERE key = ? AND namespace = ?").run(i,e))}}persistToDisk(e,t,n){if(this.db)try{let r=this.serializeVector(t.vector),i=t.metadata?JSON.stringify(t.metadata):null,o=Date.now();this.persist("persist",s=>s.prepare(`
|
|
26
|
+
INSERT OR REPLACE INTO embeddings
|
|
27
|
+
(key, namespace, vector, dimension, text, timestamp, quantization, metadata, last_access)
|
|
28
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
29
|
+
`).run(e,n,r,t.dimension,t.text,t.timestamp,t.quantization,i,o))}catch(r){console.warn("Failed to persist embedding:",r)}}persist(e,t){let n=this.db;n&&le(n,()=>t(n)).catch(r=>{console.warn(`Failed to ${e} embedding cache entry:`,r)})}flushPendingWrites(){if(this.pendingWrites.length===0||!this.db)return;let e=this.pendingWrites;this.pendingWrites=[];for(let{key:t,embedding:n,namespace:r}of e)this.persistToDisk(t,n,r);e.length>0&&console.log(`[EmbeddingCache] Flushed ${e.length} pending writes after DB init`)}loadFromDisk(){if(this.db)try{let t=this.db.prepare("SELECT * FROM embeddings").all();for(let n of t){let r={vector:this.deserializeVector(n.vector),dimension:n.dimension,namespace:n.namespace,text:n.text,timestamp:n.timestamp,quantization:n.quantization,metadata:n.metadata?_(n.metadata):void 0},i=this.memoryCache.get(n.namespace);i&&i.set(n.key,{key:n.key,embedding:r,accessCount:n.access_count||1,lastAccess:n.last_access})}}catch(e){console.warn("Failed to load embeddings from disk:",e)}}serializeVector(e){if(e instanceof Float32Array)return Buffer.from(e.buffer);if(e instanceof Int8Array)return Buffer.from(e.buffer);if(e instanceof Uint8Array)return Buffer.from(e.buffer);{let t=new Float32Array(e);return Buffer.from(t.buffer)}}deserializeVector(e){let t=new Float32Array(e.buffer,e.byteOffset,e.byteLength/Float32Array.BYTES_PER_ELEMENT);return Array.from(t)}getStats(){let e=0,t={text:0,code:0,test:0,coverage:0,defect:0,experiences:0};for(let[r,i]of this.memoryCache.entries()){let o=i.size;t[r]=o,e+=o}let n=e*384*4;return{totalEntries:e,entriesByNamespace:t,memoryUsage:n,hitRate:0}}resetStats(){}close(){this.db&&(this.unifiedMemory?console.log("[EmbeddingCache] Detached from unified storage (not closing shared connection)"):(this.db.close(),console.log("[EmbeddingCache] Database closed")),this.db=null,this.unifiedMemory=null,this.pendingWrites=[],this.dbInitializing=!1)}getMostAccessed(e="text",t=10){let n=this.memoryCache.get(e);return n?Array.from(n.entries()).map(([r,i])=>({key:r,accessCount:i.accessCount})).sort((r,i)=>i.accessCount-r.accessCount).slice(0,t):[]}optimize(e=2,t){let n=0,r=i=>{let o=this.memoryCache.get(i);if(!o)return;let s=[];for(let[a,c]of o.entries())c.accessCount<e&&s.push(a);for(let a of s)o.delete(a),n++};if(t)r(t);else for(let i of this.memoryCache.keys())r(i);return n}};Pe();var Z=class{model=null;config;cache;stats;constructor(e={}){this.config={type:e.type||"transformers",model:e.model||"Xenova/all-MiniLM-L6-v2",dimension:e.dimension||384,quantization:e.quantization||"none",cacheEnabled:e.cacheEnabled??!0,onnxEnabled:e.onnxEnabled??!0,maxSequenceLength:e.maxSequenceLength||512},this.cache=new K({maxSize:1e4,ttl:0,persistent:!0,compression:!0}),this.stats=this.initializeStats()}async initialize(){if(this.model)return;let e=performance.now();if(this.config.onnxEnabled){let n=this.config.quantization==="none"?"fp32":this.config.quantization==="fp16"?"fp16":this.config.quantization==="int8"?"int8":"q8",r;try{({pipeline:r}=await import("./transformers-LSLQAARK.js"))}catch(i){throw new Error(`Local (in-process) embeddings require the optional dependency "@huggingface/transformers", which is not installed. Configure an embedding endpoint (e.g. Cognitum /v1/embeddings) so the local backend is not needed. Installing @huggingface/transformers@4.2.0 is an explicit security opt-in: its compatible dependency chain currently has unresolved HIGH advisories GHSA-xcpc-8h2w-3j85 and GHSA-f88m-g3jw-g9cj. Underlying import error: ${i instanceof Error?i.message:String(i)}`)}this.model=await r("feature-extraction",this.config.model,{dtype:n,progress_callback:i=>{i.status==="progress"&&typeof i.progress=="number"&&console.log(`Downloading model: ${(i.progress*100).toFixed(0)}%`)}})}let t=performance.now()-e;console.log(`Model loaded in ${t.toFixed(2)}ms`)}async embed(e,t={}){let n=performance.now(),r=t.namespace||"text";if(t.cache!==!1&&this.config.cacheEnabled){let c=this.cache.get(e,r);if(c)return this.stats.cacheHits++,c;this.stats.cacheMisses++}await this.initialize();let i;if(this.model){let c=await this.model(e,{pooling:"mean",normalize:!0});i=Array.from(c.data)}else throw new Error("Model not initialized");let o=i;if(t.quantization||this.config.quantization){let c=t.quantization||this.config.quantization;o=this.quantize(i,c)}let s={vector:o,dimension:this.config.dimension,namespace:r,text:e,timestamp:Date.now(),quantization:t.quantization||this.config.quantization,metadata:t?.metadata};t.cache!==!1&&this.config.cacheEnabled&&this.cache.set(e,s,r);let a=performance.now()-n;return this.stats.avgEmbeddingTime=(this.stats.avgEmbeddingTime*this.stats.totalEmbeddings+a)/(this.stats.totalEmbeddings+1),this.stats.totalEmbeddings++,this.stats.byNamespace[r]++,s}async embedBatch(e,t={}){let n=performance.now(),r=0,i=0,o=[];for(let a of e){let c=await this.embed(a,t);this.cache.get(a,t.namespace||"text")?r++:i++,o.push(c),t.onProgress&&t.onProgress(o.length/e.length)}let s=performance.now()-n;return{embeddings:o,totalTime:s,avgTime:s/e.length,cacheHits:r,cacheMisses:i}}async findSimilar(e,t={}){let n=t.limit||10,r=t.threshold||.7,i=typeof e=="string"?await this.embed(e,{namespace:t.namespace}):e,s=this.cache.getAll(t.namespace).map(a=>({target:a.text,score:de(i.vector,a.vector),rank:0})).filter(a=>a.score>=r).sort((a,c)=>c.score-a.score).slice(0,n);return s.forEach((a,c)=>{a.rank=c+1}),s}quantize(e,t){switch(t){case"fp16":return new Float32Array(e.map(n=>Math.fround(n)));case"int8":{let n=Math.max(...e.map(Math.abs));return new Int8Array(e.map(r=>Math.round(r/n*127)))}case"binary":{let n=new Uint8Array(Math.ceil(e.length/8));for(let r=0;r<e.length;r++)e[r]>=0&&(n[Math.floor(r/8)]|=1<<r%8);return n}default:return e}}getStats(){let e=this.cache.getStats();return{...this.stats,cacheHitRate:this.stats.cacheHits+this.stats.cacheMisses>0?this.stats.cacheHits/(this.stats.cacheHits+this.stats.cacheMisses):0,memoryUsage:e.memoryUsage,memoryReduction:this.calculateMemoryReduction()}}calculateMemoryReduction(){switch(this.config.quantization){case"fp16":return 50;case"int8":return 75;case"binary":return 97;default:return 0}}initializeStats(){return{totalEmbeddings:0,byNamespace:{text:0,code:0,test:0,coverage:0,defect:0,experiences:0},cacheHits:0,cacheMisses:0,cacheHitRate:0,avgEmbeddingTime:0,memoryUsage:0,memoryReduction:0,indexSize:0,indexBuildTime:0}}resetStats(){this.stats=this.initializeStats(),this.cache.resetStats()}async clear(){this.cache.clear(),this.model=null}};z();k();P();ee();v();import{resolve as Fe,dirname as We}from"path";import{fileURLToPath as Ue}from"url";var Se=b.create("sync-embedding-generator"),Be=Ue(import.meta.url),Je=We(Be),q=class{generator;dbPath;initialized=!1;constructor(e){this.dbPath=e||Fe(Je,"../../../../.agentic-qe/memory.db"),this.generator=new Z({model:"Xenova/all-MiniLM-L6-v2",dimension:384,cacheEnabled:!0,onnxEnabled:!0})}async initialize(){this.initialized||(await this.generator.initialize(),this.initialized=!0,console.log("[SyncEmbedding] Model initialized"))}async generateForPattern(e){await this.initialize();let t=this.extractText(e),n=await this.generator.embed(t,{namespace:"text"});return{id:e.id,embedding:Array.isArray(n.vector)?n.vector:Array.from(n.vector),text:t,dimension:n.dimension,generatedAt:new Date}}async generateForAllPatterns(e="patterns",t={}){let n=Date.now(),r={totalPatterns:0,patternsWithEmbeddings:0,patternsGenerated:0,patternsSkipped:0,errors:[],durationMs:0};await this.initialize();let i=T(this.dbPath);try{i.prepare(`PRAGMA table_info(${w(e)})`).all().some(h=>h.name==="embedding")||(i.prepare(`ALTER TABLE ${w(e)} ADD COLUMN embedding TEXT`).run(),console.log(`[SyncEmbedding] Added embedding column to ${e}`));let a=w(e),c=t.force?`SELECT * FROM ${a}`:`SELECT * FROM ${a} WHERE embedding IS NULL OR embedding = ''`,u=i.prepare(c).all();r.totalPatterns=u.length,t.verbose&&console.log(`[SyncEmbedding] Processing ${u.length} patterns from ${e}`);let p=i.prepare(`SELECT COUNT(*) as count FROM ${a} WHERE embedding IS NOT NULL AND embedding != ''`).get();r.patternsWithEmbeddings=p.count;let m=i.prepare(`UPDATE ${a} SET embedding = ? WHERE id = ?`),g=t.batchSize||50;for(let h=0;h<u.length;h+=g){let y=u.slice(h,Math.min(h+g,u.length));for(let f of y)try{let S=await this.generateForPattern(f),R=JSON.stringify(S.embedding);m.run(R,f.id),r.patternsGenerated++,t.verbose&&r.patternsGenerated%10===0&&console.log(`[SyncEmbedding] Generated ${r.patternsGenerated}/${u.length}`)}catch(S){let R=d(S);r.errors.push(`Pattern ${f.id}: ${R}`),r.patternsSkipped++}}return r.durationMs=Date.now()-n,t.verbose&&(console.log(`[SyncEmbedding] Completed: ${r.patternsGenerated} generated, ${r.patternsSkipped} skipped`),console.log(`[SyncEmbedding] Duration: ${r.durationMs}ms`)),r}finally{i.close()}}async findSimilarPatterns(e,t={}){await this.initialize();let n=t.limit||10,r=t.threshold||.5,i=t.tableName||"patterns",o=await this.generator.embed(e,{namespace:"text"}),s=Array.isArray(o.vector)?o.vector:Array.from(o.vector),a=T(this.dbPath,{readonly:!0});try{let c=a.prepare(`SELECT * FROM ${w(i)} WHERE embedding IS NOT NULL AND embedding != ''`).all(),u=[];for(let p of c)try{let m=typeof p.embedding=="string"?_(p.embedding):p.embedding;if(Array.isArray(m)&&m.length===s.length){let g=this.cosineSimilarity(s,m);g>=r&&u.push({pattern:p,similarity:g})}}catch(m){Se.debug("Invalid embedding in search pattern",{error:m instanceof Error?m.message:String(m)})}return u.sort((p,m)=>m.similarity-p.similarity).slice(0,n)}finally{a.close()}}extractText(e){let t=[];if(e.pattern&&t.push(e.pattern),e.content)try{let r=typeof e.content=="string"?_(e.content):e.content;typeof r=="object"?(r.description&&t.push(r.description),r.name&&t.push(r.name),r.summary&&t.push(r.summary),r.text&&t.push(r.text)):typeof r=="string"&&t.push(r)}catch(r){Se.debug("Pattern content is not JSON, using as string",{error:r instanceof Error?r.message:String(r)}),t.push(String(e.content))}return e.type&&t.push(`type:${e.type}`),e.domain&&t.push(`domain:${e.domain}`),t.join(" ").trim().substring(0,512)}cosineSimilarity(e,t){let n=0,r=0,i=0;for(let s=0;s<e.length;s++)n+=e[s]*t[s],r+=e[s]*e[s],i+=t[s]*t[s];let o=Math.sqrt(r)*Math.sqrt(i);return o===0?0:n/o}getStats(){return this.generator.getStats()}async clear(){await this.generator.clear(),this.initialized=!1}};function we(l){return new q(l)}export{A as a,ve as b,x as c,W as d,re as e,U as f,ne as g,$ as h,$e as i,B as j,M as k,J as l,O as m,Q as n,ie as o,V as p,oe as q,H as r,se as s,De as t,qe as u,X as v,ce as w,Le as x,Ie as y,q as z,we as A};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as d,d as c}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
|
|
2
|
+
import{b as d,d as c}from"./chunk-V5NHZV7S.js";import{a as l,e as g}from"./chunk-KNSRL6NO.js";g();c();import{existsSync as y,readFileSync as p}from"node:fs";import{join as o,dirname as u}from"node:path";import{fileURLToPath as m}from"node:url";var i=class extends Error{constructor(t,n,r){super(t);this.code=n;this.cause=r;this.name="PatternLoaderError"}code;cause},s=class a{static instance=null;config;patterns;isLoading=!1;constructor(e={}){this.config={basePath:e.basePath??this.getDefaultBasePath(),throwOnMissing:e.throwOnMissing??!1,validatePatterns:e.validatePatterns??!0},this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]}}static getInstance(e){return a.instance||(a.instance=new a(e)),a.instance}static resetInstance(){a.instance=null}getDefaultBasePath(){try{let e=import.meta.url,t=m(e),n=u(t),r=o(n,"..","..","..");return o(r,"assets","patterns")}catch{return o(process.cwd(),"assets","patterns")}}async loadPatterns(){if(!this.isLoading){this.isLoading=!0,this.patterns.errors=[];try{this.patterns.index=this.loadJsonFile("index.json");let[e,t,n,r]=await Promise.all([Promise.resolve(this.loadJsonFile("adr-051-booster-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-router-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-embedding-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-reasoning-patterns.json"))]);this.patterns.booster=e,this.patterns.router=t,this.patterns.embedding=n,this.patterns.reasoning=r,this.patterns.loadedAt=new Date,this.config.validatePatterns&&this.validateLoadedPatterns()}finally{this.isLoading=!1}}}loadJsonFile(e){let t=o(this.config.basePath,e);try{if(!y(t)){let r=`Pattern file not found: ${t}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"FILE_NOT_FOUND");return null}let n=p(t,"utf-8");return d(n)}catch(n){if(n instanceof i)throw n;let r=`Failed to load pattern file ${e}: ${l(n)}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"PARSE_ERROR",n instanceof Error?n:void 0);return null}}validateLoadedPatterns(){this.patterns.booster&&(Array.isArray(this.patterns.booster.patterns)||this.patterns.errors.push("Booster patterns file missing patterns array")),this.patterns.router&&(Array.isArray(this.patterns.router.patterns)||this.patterns.errors.push("Router patterns file missing patterns array")),this.patterns.embedding&&(Array.isArray(this.patterns.embedding.patterns)||this.patterns.errors.push("Embedding patterns file missing patterns array")),this.patterns.reasoning&&(Array.isArray(this.patterns.reasoning.patterns)||this.patterns.errors.push("Reasoning patterns file missing patterns array"))}async ensureLoaded(){this.patterns.loadedAt||await this.loadPatterns()}async getIndex(){return await this.ensureLoaded(),this.patterns.index}async getBoosterPatterns(){return await this.ensureLoaded(),this.patterns.booster}async getRouterPatterns(){return await this.ensureLoaded(),this.patterns.router}async getEmbeddingPatterns(){return await this.ensureLoaded(),this.patterns.embedding}async getReasoningPatterns(){return await this.ensureLoaded(),this.patterns.reasoning}async getBoosterPatternByKey(e){let t=await this.getBoosterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getRouterPatternByKey(e){let t=await this.getRouterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEmbeddingPatternByKey(e){let t=await this.getEmbeddingPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getReasoningPatternByKey(e){let t=await this.getReasoningPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEligibleBoosterTransforms(){let e=await this.getBoosterPatternByKey("booster-transform-eligibility");return e?e.eligibility_criteria.simple_transforms:[]}async getTierHierarchy(){let e=await this.getRouterPatternByKey("router-5tier-complexity");return e?e.tier_hierarchy:null}async getQualityGateThresholds(){let e=await this.getReasoningPatternByKey("reasoning-pattern-quality-gates");return e?e.gate_thresholds:null}isLoaded(){return this.patterns.loadedAt!==null}getLoadedAt(){return this.patterns.loadedAt}getErrors(){return[...this.patterns.errors]}async getStatistics(){let e=await this.getIndex();return e?e.pattern_statistics:null}async reload(){this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]},await this.loadPatterns()}async getAllPatterns(){return await this.ensureLoaded(),{...this.patterns}}};function x(){return s.getInstance()}export{x as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
|
|
2
|
+
import{B as h,t as c,w as d,y as f}from"./chunk-MO55CVMT.js";import{a as r,e as u}from"./chunk-CRPIYUTJ.js";import{a as s,c as o,d as g}from"./chunk-J4ELZNLY.js";import{a,e as m}from"./chunk-KNSRL6NO.js";m();h();u();g();var P={dbPath:c.dbPath,walMode:!0,mmapSize:r.MMAP_SIZE_BYTES,cacheSize:r.CACHE_SIZE_KB,busyTimeout:r.BUSY_TIMEOUT_MS},t=class e{static instance=null;static instancePromise=null;unifiedMemory=null;config;initialized=!1;initPromise=null;constructor(i){this.config={...P,...i}}static getInstance(i){return e.instance||(e.instance=new e(i)),e.instance}static async getInstanceAsync(i){return e.instance?.initialized?e.instance:(e.instancePromise||(e.instancePromise=(async()=>{let n=e.getInstance(i);return await n.initialize(),n})()),e.instancePromise)}static resetInstance(){e.instance&&(e.instance.close(),e.instance=null),e.instancePromise=null,f()}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{let i={dbPath:this.config.dbPath,walMode:this.config.walMode,busyTimeout:this.config.busyTimeout,mmapSize:this.config.mmapSize,cacheSize:this.config.cacheSize};this.unifiedMemory=d(i),await this.unifiedMemory.initialize(),this.initialized=!0,console.log(`[UnifiedPersistence] Initialized via UnifiedMemoryManager: ${this.config.dbPath}`)}catch(i){throw this.initPromise=null,new Error(`Failed to initialize UnifiedPersistenceManager: ${a(i)}`)}}getDatabase(){if(!this.unifiedMemory||!this.initialized)throw new Error("UnifiedPersistenceManager not initialized");return this.unifiedMemory.getDatabase()}isInitialized(){return this.initialized}getDbPath(){return this.config.dbPath}prepare(i,n){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.prepare(i,n)}transaction(i){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.transaction(i)}getStats(){if(!this.unifiedMemory)throw new Error("Database not initialized");let i=this.unifiedMemory.getStats();return{tables:i.tables,fileSize:i.fileSize,walSize:i.walSize}}vacuum(){this.getDatabase().exec("VACUUM")}checkpoint(){this.getDatabase().pragma("wal_checkpoint(TRUNCATE)")}close(){this.initialized=!1,console.log("[UnifiedPersistence] Facade closed")}};function p(e){return t.getInstance(e)}async function E(e){let i=p(e);return await i.initialize(),i}function I(){t.resetInstance()}var l=!1;function M(){if(l)return;l=!0;let e=()=>{try{let n=t.instance;n&&n.close()}catch(n){console.debug("[UnifiedPersistence] Cleanup error:",n instanceof Error?n.message:n)}};process.on("beforeExit",e),s(e);let i=n=>{o(n)||(e(),process.exit(0))};process.on("SIGINT",i),process.on("SIGTERM",i)}M();export{P as a,t as b,p as c,E as d,I as e};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as p}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
|
|
2
|
+
import{b as p}from"./chunk-AJMJNQMP.js";import{existsSync as l}from"node:fs";import{dirname as e,join as m}from"node:path";function f(n,r=process.platform,o=process.execPath,t=l){if(r!=="win32")return[n,[]];let i=m(e(o),"node_modules","npm","bin",`${n}-cli.js`);return t(i)?[o,[i]]:null}var s=p(()=>{"use strict"});export{f as a,s as b};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as e}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
|
|
2
|
+
import{b as e}from"./chunk-AJMJNQMP.js";function r(t){t.exec(n)}var n,a=e(()=>{"use strict";n=`
|
|
3
3
|
-- Negative pattern records (ADR-110 kept nulls)
|
|
4
4
|
CREATE TABLE IF NOT EXISTS qe_pattern_nulls (
|
|
5
5
|
id TEXT PRIMARY KEY,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as m,d 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.15.16");process.exit(0)}
|
|
2
|
+
import{b as m,d as $}from"./chunk-A5GBXCP5.js";import{b as A}from"./chunk-AJMJNQMP.js";function T(n){let i=Buffer.from(n,"base64").toString("latin1");return i.includes(":")&&/^[\x20-\x7e]+$/.test(i)}function _(n){return/^[A-Z]?[a-z]+\.?$/.test(n)&&n.replace(/\.$/,"").length<=16}function x(n){let i=new RegExp(b.source,b.flags),t="",r=0;for(let e=i.exec(n);e!==null;e=i.exec(n)){let[s,o="",a,u,S,f]=e,l=a??u,d=e.index+s.length-f.length;if(!D(l)){i.lastIndex=d+1;continue}let E=f==="{"||f==="["?C(n,d,o.length===2):f.length===2&&f[0]==="\\"?k(n,d+2,f):e.index+s.length;t+=`${n.slice(r,e.index)}${o}${l}${o}${S}${o}<REDACTED:sensitive-key>${o}`,r=E,i.lastIndex=E}return r===0?n:t+n.slice(r)}function k(n,i,t){let r=!1;for(let e=i;e<n.length;e++){let s=n[e]==="\\";s&&e++;let o=n[e];if(o===`
|
|
3
3
|
`||o===void 0)return e;if(r)r=!1;else if(s&&o==="\\")r=!0;else if(s&&o===t[1])return e+1}return n.length}function C(n,i,t){let r=0;for(let e=i;e<n.length;e++){let s=n[e];if(t&&s==="\\"&&(n[e+1]==='"'||n[e+1]==="'"))e=k(n,e+2,n.slice(e,e+2))-1;else if(!t&&(s==='"'||s==="'"))for(e++;e<n.length&&n[e]!==s&&n[e]!==`
|
|
4
4
|
`;e++)n[e]==="\\"&&e++;else if(s==="{"||s==="[")r++;else if((s==="}"||s==="]")&&--r===0)return e+1}return n.length}function D(n){let i=n.toLowerCase().replace(/[^a-z0-9]/g,"");return w.has(i)||z.some(t=>i.endsWith(t))}function c(n,i=y.maxStringLength){if(typeof n!="string")return I(n);if(n.length>L)return`[REDACTED:size-limit ${n.length} chars]`;let t=n;for(let[r,e]of O)t=t.replace(r,e);return t=x(t),t=m(t,"balanced").text,t.length>i?`${t.slice(0,i)}\u2026[truncated ${t.length-i} chars]`:t}function p(n,i={}){return g(n,{...y,...i},0,[])}function I(n){try{if(n instanceof Error){let i=h(n),t=n.cause;for(let r=0;t!==void 0&&r<3;r++)i+=`
|
|
5
5
|
Caused by: ${t instanceof Error?h(t):JSON.stringify(p(t,{maxDepth:3}))}`,t=t instanceof Error?t.cause:void 0;return i}return typeof n=="string"?c(n):JSON.stringify(p(n,{maxDepth:3}))??String(n)}catch{return"[REDACTED:sanitization-failed]"}}function R(n){let i={};for(let t of N){let r=Object.getOwnPropertyDescriptor(n,t)??(t==="name"?{value:n.name}:void 0),e=r&&"value"in r?r.value:void 0;typeof e=="string"?i[t]=c(e,j):typeof e=="number"&&Number.isFinite(e)&&(i[t]=e)}return i}function h(n){let i=c(n.stack||`${n.name}: ${n.message}`),t=R(n),r=Object.keys(t);return r.length===0||r.length===1&&i.startsWith(`${t.name}`)?i:`${i} ${JSON.stringify(t)}`}function g(n,i,t,r){try{if(n==null||typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return c(n,i.maxStringLength);if(typeof n=="bigint"||typeof n=="symbol")return n.toString();if(typeof n=="function")return"[function]";let e=n;if(r.includes(e))return"[circular]";if(t>=i.maxDepth)return"[object]";if(ArrayBuffer.isView(e))return`[binary ${e.byteLength} bytes]`;if(e instanceof ArrayBuffer)return`[binary ${e.byteLength} bytes]`;if(e instanceof Date)return Number.isNaN(e.getTime())?"[invalid date]":e.toISOString();if(e instanceof Map||e instanceof Set)return`[${e.constructor.name}(${e.size})]`;let s=[...r,e];if(Array.isArray(e)){let o=e.slice(0,i.maxEntries).map(a=>g(a,i,t+1,s));return e.length>i.maxEntries&&o.push(`[+${e.length-i.maxEntries} more]`),o}return e instanceof Error?F(e,i,t,s):Z(e,Object.keys(e),i,t,s)}catch{return"[REDACTED:sanitization-failed]"}}function F(n,i,t,r){let e={name:c(String(n.name),i.maxStringLength),message:c(String(n.message),i.maxStringLength)};typeof n.stack=="string"&&(e.stack=c(n.stack,i.maxStringLength));let{code:s,status:o}=R(n);s!==void 0&&(e.code=s),o!==void 0&&(e.status=o);let a=n.cause;return a!==void 0&&(e.cause=g(a,i,t+1,r)),e}function Z(n,i,t,r,e){let s={};for(let o of i.slice(0,t.maxEntries)){let a=Object.getOwnPropertyDescriptor(n,o);if(!a)continue;if(!("value"in a)){s[o]="[getter]";continue}let u=a.value;if(D(o)&&u!==null&&u!==void 0&&typeof u!="boolean"){s[o]="[REDACTED:sensitive-key]";continue}s[o]=g(u,t,r+1,e)}return i.length>t.maxEntries&&(s["[truncated]"]=`${i.length-t.maxEntries} more keys`),s}var y,L,w,z,O,b,N,j,B=A(()=>{"use strict";$();y={maxDepth:6,maxEntries:100,maxStringLength:8192},L=1e6,w=new Set(["auth","dsn","pwd","proxyauthorization","setcookie","sessionid"]),z=["token","secret","password","passwd","passphrase","apikey","privatekey","accesskey","secretkey","credential","credentials","cookie","authorization","sessionid","connectionstring"];O=[[/(:\/\/)[^\s/@:"']*:[^\s/@"']+@/g,"$1<REDACTED:credentials>@"],[/\b(authorization:\s*Basic)\s+[^\s"']+/gi,"$1 <REDACTED:credential>"],[/\b(Basic)\s+([A-Za-z0-9+/]{8,}={0,2})(?![A-Za-z0-9._~+/=-])/gi,(n,i,t)=>T(t)?`${i} <REDACTED:credential>`:n],[/\b(authorization:\s*Bearer)\s+[^\s"']+/gi,"$1 <REDACTED:credential>"],[/\b(Bearer)\s+([A-Za-z0-9._~+/=-]{8,})/gi,(n,i,t)=>_(t)?n:`${i} <REDACTED:credential>`],[/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{16,}/g,"<REDACTED:api_key>"],[/\b(set-cookie|cookie):\s*[^\n]+/gi,"$1: <REDACTED:cookie>"],[/\b([A-Za-z0-9_-]{0,64}?[_-](?:token|secret|password|passwd))=([^\s&"'#]+)/gi,"$1=<REDACTED:credential>"]],b=/(?:(\\?["'])([A-Za-z0-9_.-]{1,64})\1|(?<![A-Za-z0-9_.$-])([A-Za-z_$][A-Za-z0-9_.$-]{0,63}))(\s*:\s*)("(?:[^"\\\n]|\\.)*"?|'(?:[^'\\\n]|\\.)*'?|\\["']|-?\d[\d.eE+-]*|[{[])/g;N=["name","code","status"],j=200});export{c as a,p as b,I as c,B as d};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{r as f,v as P}from"./chunk-JK6PMLQQ.js";import{b as h,d as U}from"./chunk-XN3KCKAM.js";import{d as p,e as y}from"./chunk-C3OIBFAA.js";import{a as T,e as C}from"./chunk-L5VSLPMW.js";P();C();U();y();import{randomUUID as v}from"crypto";var M=p("TokenTracker"),S={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},I={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},m=class u{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=I;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=S}initialize(t){this.initialized||(this.initialized=!0,t&&(this.costConfig={...S,...t}),this.initializeDb().catch(e=>{M.warn("DB initialization failed",{error:e instanceof Error?e.message:String(e)})}),this.startAutoSave())}setCostConfig(t){this.costConfig={...this.costConfig,...t}}recordTokenUsage(t,e,n,a,s,r){this.ensureInitialized();let c,d,i,o,l,k;typeof e=="object"?(c="default",d="unknown",i="unknown",o=e,l=!1,k=0):(c=e,d=n??"unknown",i=a??"unknown",o=s,l=r?.patternReused??!1,k=r?.tokensSaved??0),o.estimatedCostUsd===void 0&&(o.estimatedCostUsd=this.calculateCost(o));let g={taskId:t,agentId:c,domain:d,operation:i,timestamp:Date.now(),usage:o,patternReused:l,tokensSaved:k};this.taskMetrics.push(g),this.updateAgentMetrics(c,o,l,k),this.updateDomainMetrics(d,o),l&&this.totalPatternsReused++,k>0&&(this.totalTokensSaved+=k),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(t,e){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=e;let n={taskId:t,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:e};this.taskMetrics.push(n),this.isDirty=!0}recordCacheHit(t){this.cacheHits++,this.totalTokensSaved+=t,this.isDirty=!0}recordEarlyExit(t){this.earlyExits++,this.totalTokensSaved+=t,this.isDirty=!0}getSessionSummary(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),n=this.aggregateTokenUsage(e),a=new Map;for(let i of e){let o=a.get(i.agentId);o?(o.totalInputTokens+=i.usage.inputTokens,o.totalOutputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.totalCost+=i.usage.estimatedCostUsd||0,o.tasksExecuted++,i.patternReused&&o.patternsReused++,o.estimatedTokensSaved+=i.tokensSaved||0):a.set(i.agentId,{agentId:i.agentId,totalInputTokens:i.usage.inputTokens,totalOutputTokens:i.usage.outputTokens,totalTokens:i.usage.totalTokens,totalCost:i.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i.patternReused?1:0,estimatedTokensSaved:i.tokensSaved||0})}let s=new Map;for(let i of e){let o=s.get(i.domain);o?(o.inputTokens+=i.usage.inputTokens,o.outputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(i.usage.estimatedCostUsd||0)):s.set(i.domain,{...i.usage})}let r=n.totalTokens,c=this.totalTokensSaved,d=r+c>0?c/(r+c)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:a,byDomain:s,totalUsage:n,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(d*100)/100}}}getAgentMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.agentId===t);return this.aggregateAgentMetrics(t,s)}let a=new Map;for(let s of n){let r=a.get(s.agentId)||[];r.push(s),a.set(s.agentId,r)}return Array.from(a.entries()).map(([s,r])=>this.aggregateAgentMetrics(s,r))}getDomainMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.domain===t);return this.aggregateTokenUsage(s)}let a=new Map;for(let s of n){let r=a.get(s.domain);r?(r.inputTokens+=s.usage.inputTokens,r.outputTokens+=s.usage.outputTokens,r.totalTokens+=s.usage.totalTokens,r.estimatedCostUsd=(r.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):a.set(s.domain,{...s.usage})}return a}getTaskMetrics(t){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,t)}getEfficiencyReport(t){return this.getTokenEfficiency(t)}getTokenEfficiency(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),a=this.aggregateTokenUsage(e).totalTokens,s=this.totalTokensSaved,r=a+s>0?s/(a+s)*100:0,c=e.length,d=c>0?e.filter(l=>l.patternReused).length/c:0,i=c>0?a/c:0,o=this.generateRecommendations(e);return{totalTokensUsed:a,totalTokensSaved:s,savingsPercentage:Math.round(r*100)/100,patternReuseRate:Math.round(d*100)/100,averageTokensPerTask:Math.round(i),recommendations:o}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(t){this.persistenceConfig={...this.persistenceConfig,...t},t.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),t.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(t=>{console.warn("[TokenMetricsCollector] Auto-save failed:",t)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let t=await import("fs"),e=await import("path"),n={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},a=e.resolve(this.persistenceConfig.filePath),s=e.dirname(a);t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.writeFileSync(a,JSON.stringify(n,null,2)),this.isDirty=!1}async load(){let t=await import("fs"),n=(await import("path")).resolve(this.persistenceConfig.filePath);if(!t.existsSync(n))return!1;try{let a=t.readFileSync(n,"utf-8"),s=h(a);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let r=s.taskMetrics||[];this.taskMetrics=[...r,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let c of r)this.updateAgentMetrics(c.agentId,c.usage,c.patternReused,c.tokensSaved||0),this.updateDomainMetrics(c.domain,c.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(a){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",a),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=f(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",T(t)),this.db=null}}async persistToKv(){if(!this.db)return;let t={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(u.KV_KEY,t,u.KV_NAMESPACE,u.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let t=await this.db.kvGet(u.KV_KEY,u.KV_NAMESPACE);if(!t)return!1;if(!t.version||!t.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let e=t.taskMetrics||[];this.taskMetrics=[...e,...this.taskMetrics],this.cacheHits+=t.optimizationStats?.cacheHits||0,this.earlyExits+=t.optimizationStats?.earlyExits||0,this.totalTokensSaved+=t.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=t.optimizationStats?.totalPatternsReused||0;for(let n of e)this.updateAgentMetrics(n.agentId,n.usage,n.patternReused,n.tokensSaved||0),this.updateDomainMetrics(n.domain,n.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=u.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(t=>{M.warn("KV persist failed",{error:t instanceof Error?t.message:String(t)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(t){let e=t.inputTokens*this.costConfig.costPerInputToken,n=t.outputTokens*this.costConfig.costPerOutputToken;return Math.round((e+n)*1e5)/1e5}filterByTimeframe(t,e){if(!e)return t;let n=Date.now(),a;switch(e){case"1h":a=n-3600*1e3;break;case"24h":a=n-1440*60*1e3;break;case"7d":a=n-10080*60*1e3;break;case"30d":a=n-720*60*60*1e3;break;default:return t}return t.filter(s=>s.timestamp>=a)}aggregateTokenUsage(t){let e=0,n=0,a=0,s=0;for(let r of t)e+=r.usage.inputTokens,n+=r.usage.outputTokens,a+=r.usage.totalTokens,s+=r.usage.estimatedCostUsd||0;return{inputTokens:e,outputTokens:n,totalTokens:a,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(t,e){let n=0,a=0,s=0,r=0,c=0,d=0;for(let i of e)n+=i.usage.inputTokens,a+=i.usage.outputTokens,s+=i.usage.totalTokens,r+=i.usage.estimatedCostUsd||0,i.patternReused&&c++,d+=i.tokensSaved||0;return{agentId:t,totalInputTokens:n,totalOutputTokens:a,totalTokens:s,totalCost:Math.round(r*1e5)/1e5,tasksExecuted:e.length,patternsReused:c,estimatedTokensSaved:d}}updateAgentMetrics(t,e,n,a){let s=this.agentMetrics.get(t);s?(s.totalInputTokens+=e.inputTokens,s.totalOutputTokens+=e.outputTokens,s.totalTokens+=e.totalTokens,s.totalCost+=e.estimatedCostUsd||0,s.tasksExecuted++,n&&s.patternsReused++,s.estimatedTokensSaved+=a):this.agentMetrics.set(t,{agentId:t,totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalTokens:e.totalTokens,totalCost:e.estimatedCostUsd||0,tasksExecuted:1,patternsReused:n?1:0,estimatedTokensSaved:a})}updateDomainMetrics(t,e){let n=this.domainMetrics.get(t);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.estimatedCostUsd=(n.estimatedCostUsd||0)+(e.estimatedCostUsd||0)):this.domainMetrics.set(t,{...e})}generateRecommendations(t){let e=[];if(t.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let n=t.filter(i=>i.patternReused).length/t.length;n<.2?e.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):n>.5&&e.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let a=new Map;for(let i of t){let o=a.get(i.domain)||0;a.set(i.domain,o+i.usage.totalTokens)}let s=Array.from(a.entries()).sort((i,o)=>o[1]-i[1]);if(s.length>0){let i=s[0];e.push(`Highest token consumer: ${i[0]} (${i[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let r=t.reduce((i,o)=>i+o.usage.inputTokens,0);return t.reduce((i,o)=>i+o.usage.outputTokens,0)/(r||1)>2&&e.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&t.length>10&&e.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&t.length>20&&e.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),e}};function b(u){return u.toLocaleString("en-US")}function z(u){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!u){let d=E.getSessionSummary(),i=d.totalUsage.totalTokens,o=d.totalUsage.estimatedCostUsd??0,l=d.optimizationStats.tokensSaved,k=i>0?o/i:0,g=l*k;u={totalTokens:i,totalCostUsd:o,savedTokens:l,savedCostUsd:g}}let t=u.totalTokens??0,e=u.totalCostUsd??0,n=u.savedTokens??0,a=u.savedCostUsd??0,s=u.budgetLimitUsd;if(t===0&&n===0)return"Token Dashboard: No data available";let r=`Token Usage: ${b(t)} tokens ($${e.toFixed(2)})`;n>0&&(r+=` | Saved: ${b(n)} tokens ($${a.toFixed(2)}) via pattern reuse`);let c=[];if(s!==void 0&&s>0){let d=Math.round(e/s*100);c.push(`Budget: $${e.toFixed(2)} / $${s.toFixed(2)} (${d}%)`)}if(u.tierSplit&&Object.keys(u.tierSplit).length>0){let d=Object.entries(u.tierSplit).sort((i,o)=>o[1]-i[1]).map(([i,o])=>`${i} ${o}%`);c.push(`Tier split: ${d.join(" | ")}`)}return c.length===0?r:`${r}
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
|
|
2
|
+
import{B as P,w as f}from"./chunk-MO55CVMT.js";import{b as h,d as U}from"./chunk-V5NHZV7S.js";import{d as p,e as y}from"./chunk-G5RHFBAY.js";import{a as T,e as C}from"./chunk-KNSRL6NO.js";P();C();U();y();import{randomUUID as v}from"crypto";var M=p("TokenTracker"),S={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},I={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},m=class u{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=I;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=S}initialize(t){this.initialized||(this.initialized=!0,t&&(this.costConfig={...S,...t}),this.initializeDb().catch(e=>{M.warn("DB initialization failed",{error:e instanceof Error?e.message:String(e)})}),this.startAutoSave())}setCostConfig(t){this.costConfig={...this.costConfig,...t}}recordTokenUsage(t,e,n,a,s,r){this.ensureInitialized();let c,d,i,o,l,k;typeof e=="object"?(c="default",d="unknown",i="unknown",o=e,l=!1,k=0):(c=e,d=n??"unknown",i=a??"unknown",o=s,l=r?.patternReused??!1,k=r?.tokensSaved??0),o.estimatedCostUsd===void 0&&(o.estimatedCostUsd=this.calculateCost(o));let g={taskId:t,agentId:c,domain:d,operation:i,timestamp:Date.now(),usage:o,patternReused:l,tokensSaved:k};this.taskMetrics.push(g),this.updateAgentMetrics(c,o,l,k),this.updateDomainMetrics(d,o),l&&this.totalPatternsReused++,k>0&&(this.totalTokensSaved+=k),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(t,e){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=e;let n={taskId:t,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:e};this.taskMetrics.push(n),this.isDirty=!0}recordCacheHit(t){this.cacheHits++,this.totalTokensSaved+=t,this.isDirty=!0}recordEarlyExit(t){this.earlyExits++,this.totalTokensSaved+=t,this.isDirty=!0}getSessionSummary(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),n=this.aggregateTokenUsage(e),a=new Map;for(let i of e){let o=a.get(i.agentId);o?(o.totalInputTokens+=i.usage.inputTokens,o.totalOutputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.totalCost+=i.usage.estimatedCostUsd||0,o.tasksExecuted++,i.patternReused&&o.patternsReused++,o.estimatedTokensSaved+=i.tokensSaved||0):a.set(i.agentId,{agentId:i.agentId,totalInputTokens:i.usage.inputTokens,totalOutputTokens:i.usage.outputTokens,totalTokens:i.usage.totalTokens,totalCost:i.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i.patternReused?1:0,estimatedTokensSaved:i.tokensSaved||0})}let s=new Map;for(let i of e){let o=s.get(i.domain);o?(o.inputTokens+=i.usage.inputTokens,o.outputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(i.usage.estimatedCostUsd||0)):s.set(i.domain,{...i.usage})}let r=n.totalTokens,c=this.totalTokensSaved,d=r+c>0?c/(r+c)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:a,byDomain:s,totalUsage:n,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(d*100)/100}}}getAgentMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.agentId===t);return this.aggregateAgentMetrics(t,s)}let a=new Map;for(let s of n){let r=a.get(s.agentId)||[];r.push(s),a.set(s.agentId,r)}return Array.from(a.entries()).map(([s,r])=>this.aggregateAgentMetrics(s,r))}getDomainMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.domain===t);return this.aggregateTokenUsage(s)}let a=new Map;for(let s of n){let r=a.get(s.domain);r?(r.inputTokens+=s.usage.inputTokens,r.outputTokens+=s.usage.outputTokens,r.totalTokens+=s.usage.totalTokens,r.estimatedCostUsd=(r.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):a.set(s.domain,{...s.usage})}return a}getTaskMetrics(t){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,t)}getEfficiencyReport(t){return this.getTokenEfficiency(t)}getTokenEfficiency(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),a=this.aggregateTokenUsage(e).totalTokens,s=this.totalTokensSaved,r=a+s>0?s/(a+s)*100:0,c=e.length,d=c>0?e.filter(l=>l.patternReused).length/c:0,i=c>0?a/c:0,o=this.generateRecommendations(e);return{totalTokensUsed:a,totalTokensSaved:s,savingsPercentage:Math.round(r*100)/100,patternReuseRate:Math.round(d*100)/100,averageTokensPerTask:Math.round(i),recommendations:o}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(t){this.persistenceConfig={...this.persistenceConfig,...t},t.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),t.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(t=>{console.warn("[TokenMetricsCollector] Auto-save failed:",t)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let t=await import("fs"),e=await import("path"),n={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},a=e.resolve(this.persistenceConfig.filePath),s=e.dirname(a);t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.writeFileSync(a,JSON.stringify(n,null,2)),this.isDirty=!1}async load(){let t=await import("fs"),n=(await import("path")).resolve(this.persistenceConfig.filePath);if(!t.existsSync(n))return!1;try{let a=t.readFileSync(n,"utf-8"),s=h(a);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let r=s.taskMetrics||[];this.taskMetrics=[...r,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let c of r)this.updateAgentMetrics(c.agentId,c.usage,c.patternReused,c.tokensSaved||0),this.updateDomainMetrics(c.domain,c.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(a){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",a),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=f(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",T(t)),this.db=null}}async persistToKv(){if(!this.db)return;let t={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(u.KV_KEY,t,u.KV_NAMESPACE,u.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let t=await this.db.kvGet(u.KV_KEY,u.KV_NAMESPACE);if(!t)return!1;if(!t.version||!t.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let e=t.taskMetrics||[];this.taskMetrics=[...e,...this.taskMetrics],this.cacheHits+=t.optimizationStats?.cacheHits||0,this.earlyExits+=t.optimizationStats?.earlyExits||0,this.totalTokensSaved+=t.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=t.optimizationStats?.totalPatternsReused||0;for(let n of e)this.updateAgentMetrics(n.agentId,n.usage,n.patternReused,n.tokensSaved||0),this.updateDomainMetrics(n.domain,n.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=u.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(t=>{M.warn("KV persist failed",{error:t instanceof Error?t.message:String(t)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(t){let e=t.inputTokens*this.costConfig.costPerInputToken,n=t.outputTokens*this.costConfig.costPerOutputToken;return Math.round((e+n)*1e5)/1e5}filterByTimeframe(t,e){if(!e)return t;let n=Date.now(),a;switch(e){case"1h":a=n-3600*1e3;break;case"24h":a=n-1440*60*1e3;break;case"7d":a=n-10080*60*1e3;break;case"30d":a=n-720*60*60*1e3;break;default:return t}return t.filter(s=>s.timestamp>=a)}aggregateTokenUsage(t){let e=0,n=0,a=0,s=0;for(let r of t)e+=r.usage.inputTokens,n+=r.usage.outputTokens,a+=r.usage.totalTokens,s+=r.usage.estimatedCostUsd||0;return{inputTokens:e,outputTokens:n,totalTokens:a,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(t,e){let n=0,a=0,s=0,r=0,c=0,d=0;for(let i of e)n+=i.usage.inputTokens,a+=i.usage.outputTokens,s+=i.usage.totalTokens,r+=i.usage.estimatedCostUsd||0,i.patternReused&&c++,d+=i.tokensSaved||0;return{agentId:t,totalInputTokens:n,totalOutputTokens:a,totalTokens:s,totalCost:Math.round(r*1e5)/1e5,tasksExecuted:e.length,patternsReused:c,estimatedTokensSaved:d}}updateAgentMetrics(t,e,n,a){let s=this.agentMetrics.get(t);s?(s.totalInputTokens+=e.inputTokens,s.totalOutputTokens+=e.outputTokens,s.totalTokens+=e.totalTokens,s.totalCost+=e.estimatedCostUsd||0,s.tasksExecuted++,n&&s.patternsReused++,s.estimatedTokensSaved+=a):this.agentMetrics.set(t,{agentId:t,totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalTokens:e.totalTokens,totalCost:e.estimatedCostUsd||0,tasksExecuted:1,patternsReused:n?1:0,estimatedTokensSaved:a})}updateDomainMetrics(t,e){let n=this.domainMetrics.get(t);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.estimatedCostUsd=(n.estimatedCostUsd||0)+(e.estimatedCostUsd||0)):this.domainMetrics.set(t,{...e})}generateRecommendations(t){let e=[];if(t.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let n=t.filter(i=>i.patternReused).length/t.length;n<.2?e.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):n>.5&&e.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let a=new Map;for(let i of t){let o=a.get(i.domain)||0;a.set(i.domain,o+i.usage.totalTokens)}let s=Array.from(a.entries()).sort((i,o)=>o[1]-i[1]);if(s.length>0){let i=s[0];e.push(`Highest token consumer: ${i[0]} (${i[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let r=t.reduce((i,o)=>i+o.usage.inputTokens,0);return t.reduce((i,o)=>i+o.usage.outputTokens,0)/(r||1)>2&&e.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&t.length>10&&e.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&t.length>20&&e.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),e}};function b(u){return u.toLocaleString("en-US")}function z(u){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!u){let d=E.getSessionSummary(),i=d.totalUsage.totalTokens,o=d.totalUsage.estimatedCostUsd??0,l=d.optimizationStats.tokensSaved,k=i>0?o/i:0,g=l*k;u={totalTokens:i,totalCostUsd:o,savedTokens:l,savedCostUsd:g}}let t=u.totalTokens??0,e=u.totalCostUsd??0,n=u.savedTokens??0,a=u.savedCostUsd??0,s=u.budgetLimitUsd;if(t===0&&n===0)return"Token Dashboard: No data available";let r=`Token Usage: ${b(t)} tokens ($${e.toFixed(2)})`;n>0&&(r+=` | Saved: ${b(n)} tokens ($${a.toFixed(2)}) via pattern reuse`);let c=[];if(s!==void 0&&s>0){let d=Math.round(e/s*100);c.push(`Budget: $${e.toFixed(2)} / $${s.toFixed(2)} (${d}%)`)}if(u.tierSplit&&Object.keys(u.tierSplit).length>0){let d=Object.entries(u.tierSplit).sort((i,o)=>o[1]-i[1]).map(([i,o])=>`${i} ${o}%`);c.push(`Tier split: ${d.join(" | ")}`)}return c.length===0?r:`${r}
|
|
3
3
|
${c.join(" | ")}`}var E=new m;function $(u){return`$${u.toFixed(2)}`}export{z as a,E as b,$ as c};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as R,c as D,d as O,e as x,g as j,h as L,i as $,j as
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
|
|
2
|
+
import{b as R,c as D,d as O,e as x,g as j,h as L,i as $,j as M,k as N,l as Q,m as U,n as z,o as F,p as W,q as G,r as V}from"./chunk-SDLWKRVL.js";import{b as _,d as P}from"./chunk-V5NHZV7S.js";import{a as T,b as q,c as ce,d as v,e as ue}from"./chunk-KPRCB5LT.js";import{a as h,e as A}from"./chunk-KNSRL6NO.js";P();import{existsSync as y,mkdirSync as J,writeFileSync as b,readFileSync as C,copyFileSync as de}from"fs";import{join as u,dirname as pe}from"path";async function H(t,e){if(!e.hooks.claudeCode)return!1;let r=u(t,".claude");y(r)||J(r,{recursive:!0});let n=u(r,"settings.json"),s={};if(y(n))try{let m=C(n,"utf-8");s=_(m)}catch{s={}}let o={PreToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" guard --file "$TOOL_INPUT_file_path" --json',timeout:3,continueOnError:!0}]},{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-edit --file "$TOOL_INPUT_file_path" --json',timeout:5,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-command --command "$TOOL_INPUT_command" --json',timeout:3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-task --description "$TOOL_INPUT_prompt" --json',timeout:5,continueOnError:!0}]}],PostToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-edit --file "$TOOL_INPUT_file_path" --success --json',timeout:5,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-command --command "$TOOL_INPUT_command" --success true --json',timeout:5,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-task --task-id "$TOOL_RESULT_agent_id" --agent "$TOOL_INPUT_subagent_type" --success true --description "$TOOL_INPUT_prompt" --json',timeout:5,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" route --json',timeout:5,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-start --session-id "$SESSION_ID" --json',timeout:10,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-end --save-state --json',timeout:5,continueOnError:!0}]},{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-route --success true --json',timeout:5,continueOnError:!0}]}]},d=s.hooks||{};s.hooks=j(d,o);let l=s.env;s.env=L(l,$(e));let p=U(e,t);Q(s,p);let a=s.enabledMcpjsonServers||[];return a=a.filter(m=>m!=="aqe"),a.includes("agentic-qe")||a.push("agentic-qe"),s.enabledMcpjsonServers=a,x(n),b(n,JSON.stringify(s,null,2),"utf-8"),await me(t),!0}async function me(t){let e=u(t,".claude","hooks");y(e)||J(e,{recursive:!0});let r=u(e,"cross-phase-memory.yaml");if(y(r))return;let n=[u(pe(import.meta.url.replace("file://","")),"..","..","assets","hooks","cross-phase-memory.yaml"),u(process.cwd(),"assets","hooks","cross-phase-memory.yaml"),u(process.cwd(),"v3","assets","hooks","cross-phase-memory.yaml")];for(let o of n)try{if(y(o)){de(o,r),console.log(" \u2713 Cross-phase memory hooks installed");return}}catch{}b(r,`# Cross-Phase Memory Hooks Configuration
|
|
3
3
|
# Generated by aqe init
|
|
4
|
-
# See: https://github.com/
|
|
4
|
+
# See: https://github.com/proffesor-for-testing/agentic-qe/blob/main/docs/architecture/CROSS-PHASE-MEMORY-IMPLEMENTATION.md
|
|
5
5
|
|
|
6
6
|
version: "1.0"
|
|
7
7
|
enabled: true
|
|
@@ -23,9 +23,9 @@ routing:
|
|
|
23
23
|
quality-criteria:
|
|
24
24
|
- "qe-requirements-validator"
|
|
25
25
|
- "qe-bdd-generator"
|
|
26
|
-
`,"utf-8"),console.log(" \u2713 Cross-phase memory hooks created (minimal config)")}async function
|
|
26
|
+
`,"utf-8"),console.log(" \u2713 Cross-phase memory hooks created (minimal config)")}async function B(t,e={}){if(!e.force&&z(t).enabled)return console.log(F(t)),N(u(t,".mcp.json")),!1;let r=u(t,".mcp.json"),n={};if(y(r))try{let o=C(r,"utf-8");n=_(o)}catch{n={}}n.mcpServers||(n.mcpServers={});let s=n.mcpServers;return M(s),s["agentic-qe"]={command:"aqe-mcp",args:[],env:{AQE_LEARNING_ENABLED:"true",AQE_VERBOSE:"false"},autoStart:!1},b(r,JSON.stringify(n,null,2),"utf-8"),!0}async function X(t,e){let r=u(t,"CLAUDE.md"),n=ge(e);if(y(r)){let s=C(r,"utf-8");if(s.includes("## Agentic QE v3"))return!0;let o=u(t,"CLAUDE.md.backup");b(o,s,"utf-8"),b(r,s+`
|
|
27
27
|
|
|
28
|
-
`+n,"utf-8")}else b(r,n,"utf-8");return!0}function
|
|
28
|
+
`+n,"utf-8")}else b(r,n,"utf-8");return!0}function ge(t){let e=t.domains.enabled.slice(0,6).join(", "),r=Math.max(0,t.domains.enabled.length-6);return`## Agentic QE v3
|
|
29
29
|
|
|
30
30
|
This project uses **Agentic QE v3** - a Domain-Driven Quality Engineering platform with 12 bounded contexts, ReasoningBank learning, and HNSW vector search.
|
|
31
31
|
|
|
@@ -261,7 +261,7 @@ aqe init --auto
|
|
|
261
261
|
|
|
262
262
|
---
|
|
263
263
|
*Generated by AQE v3 init - ${new Date().toISOString()}*
|
|
264
|
-
`}A();import{existsSync as f,mkdirSync as k,writeFileSync as E}from"fs";import{join as i,dirname as
|
|
264
|
+
`}A();import{existsSync as f,mkdirSync as k,writeFileSync as E}from"fs";import{join as i,dirname as he}from"path";A();ce();ue();P();async function K(t,e){let r=i(t,".agentic-qe","memory.db");try{let n=he(r);f(n)||k(n,{recursive:!0});let s=v(r);try{s.exec(`
|
|
265
265
|
CREATE TABLE IF NOT EXISTS kv_store (
|
|
266
266
|
key TEXT NOT NULL,
|
|
267
267
|
namespace TEXT NOT NULL,
|
|
@@ -276,7 +276,7 @@ aqe init --auto
|
|
|
276
276
|
`).run("aqe_version",JSON.stringify(e),o),s.prepare(`
|
|
277
277
|
INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
|
|
278
278
|
VALUES (?, '_system', ?, ?)
|
|
279
|
-
`).run("init_timestamp",JSON.stringify(new Date().toISOString()),o),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(o){return s.close(),console.warn(` \u26A0 Could not write version: ${h(o)}`),!1}}catch(n){return console.warn(` \u26A0 Could not open memory.db: ${h(n)}`),!1}}async function
|
|
279
|
+
`).run("init_timestamp",JSON.stringify(new Date().toISOString()),o),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(o){return s.close(),console.warn(` \u26A0 Could not write version: ${h(o)}`),!1}}catch(n){return console.warn(` \u26A0 Could not open memory.db: ${h(n)}`),!1}}async function Y(t){let e=null;try{e=(await import("./better-sqlite3-6TGYPC2B.js")).default}catch{throw new Error(`SQLite persistence REQUIRED but better-sqlite3 is not installed.
|
|
280
280
|
Install it with: npm install better-sqlite3
|
|
281
281
|
If you see native compilation errors, ensure build tools are installed:
|
|
282
282
|
- macOS: xcode-select --install
|
|
@@ -299,18 +299,18 @@ If you see native compilation errors, ensure build tools are installed:
|
|
|
299
299
|
VALUES (?, ?, ?)
|
|
300
300
|
`).run("_init_test","_system",JSON.stringify({initialized:new Date().toISOString()})),s.close(),console.log(`\u2713 SQLite persistence initialized: ${n}`),!0}catch(s){throw q(s)?new Error(`SQLite persistence initialization FAILED: ${h(T(s))}`,{cause:s}):new Error(`SQLite persistence initialization FAILED: ${s}
|
|
301
301
|
Database path: ${n}
|
|
302
|
-
Ensure the directory is writable and has sufficient disk space.`)}}async function
|
|
302
|
+
Ensure the directory is writable and has sufficient disk space.`)}}async function Z(t){let e=i(t,".agentic-qe","memory.db");if(!f(e))return!1;try{let r=v(e),n=r.prepare(`
|
|
303
303
|
SELECT COUNT(*) as count FROM kv_store
|
|
304
304
|
WHERE namespace = 'code-intelligence:kg'
|
|
305
|
-
`).get();return r.close(),n.count>0}catch{return!1}}async function
|
|
305
|
+
`).get();return r.close(),n.count>0}catch{return!1}}async function ee(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-KFOMEN3H.js"),{InMemoryBackend:r}=await import("./memory-backend-DFGKWA2Q.js"),n=new r;await n.initialize();let s=new e(n,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0,projectRoot:t}),{glob:o}=await import("tinyglobby"),d=await o(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:t,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"],expandDirectories:!1}),l=await s.index({paths:d.map(p=>i(t,p)),incremental:!1,includeTests:!0});return s.destroy(),l.success?{status:"indexed",entries:l.value.nodesCreated+l.value.edgesCreated}:{status:"error",entries:0}}catch(e){return console.warn("Code intelligence scan warning:",h(e)),{status:"skipped",entries:0}}}async function te(t){let e=i(t,".agentic-qe","memory.db");try{let r=v(e),n=r.prepare(`
|
|
306
306
|
SELECT COUNT(*) as count FROM kv_store
|
|
307
307
|
WHERE namespace LIKE 'code-intelligence:kg%'
|
|
308
|
-
`).get();return r.close(),n.count}catch{return 0}}async function
|
|
308
|
+
`).get();return r.close(),n.count}catch{return 0}}async function ne(t,e,r){if(!e.learning.enabled)return 0;let n=i(t,".agentic-qe","data");f(n)||k(n,{recursive:!0});let s=i(n,"hnsw");f(s)||k(s,{recursive:!0});let o=i(n,"learning-config.json"),d={embeddingModel:e.learning.embeddingModel,hnswConfig:e.learning.hnswConfig,qualityThreshold:e.learning.qualityThreshold,promotionThreshold:e.learning.promotionThreshold,databasePath:i(n,"memory.db"),hnswIndexPath:i(s,"index.bin"),initialized:new Date().toISOString()};E(o,JSON.stringify(d,null,2),"utf-8");let l=0;if(e.learning.pretrainedPatterns&&r){let p=r,a=new Map;for(let g of p.patterns){let c=g.domain||"general";a.has(c)||a.set(c,[]),a.get(c).push(g)}let m=i(n,"pretrained-index.json"),S={version:p.version,totalPatterns:p.statistics.totalPatterns,domains:Array.from(a.entries()).map(([g,c])=>({name:g,patternCount:c.length})),loadedAt:new Date().toISOString()};E(m,JSON.stringify(S,null,2),"utf-8");for(let[g,c]of a){let w=i(n,"patterns",g);f(w)||k(w,{recursive:!0});let le=i(w,"patterns.json");E(le,JSON.stringify(c,null,2),"utf-8"),l+=c.length}return l}return 0}async function re(t,e){if(!e.workers.daemonAutoStart||e.workers.enabled.length===0)return 0;let r=i(t,".agentic-qe","workers");f(r)||k(r,{recursive:!0});let n={},s={"pattern-consolidator":6e4,"coverage-gap-scanner":3e5,"flaky-test-detector":6e5,"routing-accuracy-monitor":12e4};for(let a of e.workers.enabled)n[a]={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,lastRun:null,status:"pending"};let o=i(r,"registry.json"),d={version:e.version,maxConcurrent:e.workers.maxConcurrent,workers:n,createdAt:new Date().toISOString(),daemonPid:null};E(o,JSON.stringify(d,null,2),"utf-8");for(let a of e.workers.enabled){let m=i(r,`${a}.json`),S={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,projectRoot:t,dataDir:i(t,".agentic-qe","data"),createdAt:new Date().toISOString()};E(m,JSON.stringify(S,null,2),"utf-8")}let l=i(r,"start-daemon.cjs");return E(l,`#!/usr/bin/env node
|
|
309
309
|
// AQE v3 Worker Daemon Startup Script (cross-platform)
|
|
310
310
|
// Generated by aqe init
|
|
311
311
|
|
|
312
312
|
console.log("AQE v3 hooks work via CLI commands (no daemon required)");
|
|
313
313
|
console.log("Use: npx aqe hooks session-start");
|
|
314
|
-
`),e.workers.enabled.length}async function
|
|
315
|
-
`)}var
|
|
316
|
-
`)}export{I as a,
|
|
314
|
+
`),e.workers.enabled.length}async function se(t,e){if(!e.skills.install)return 0;let n=await W({projectRoot:t,installV2Skills:e.skills.installV2,installV3Skills:e.skills.installV3,overwrite:e.skills.overwrite}).install();return n.errors.length>0&&console.warn("Skills installation warnings:",n.errors),n.installed.length}async function ae(t){let r=await G({projectRoot:t,installQEAgents:!0,installSubagents:!0,overwrite:!1}).install();return r.errors.length>0&&console.warn("Agents installation warnings:",r.errors),r.installed.length}async function oe(t,e,r){let s=await V({projectRoot:t,installAgents:!0,installSkills:!0,overwrite:!1,n8nApiConfig:r}).install();return s.errors.length>0&&console.warn("N8n installation warnings:",s.errors),e.platforms||(e.platforms={}),e.platforms.n8n={enabled:!0,installAgents:!0,installSkills:!0,installTypeScriptAgents:!1,n8nApiConfig:r},{agents:s.agentsInstalled.length,skills:s.skillsInstalled.length}}async function ie(t,e){if(!e)throw new Error("No configuration to save");let r=i(t,".agentic-qe");f(r)||k(r,{recursive:!0});let n=fe(e),s=i(r,"config.yaml");E(s,n,"utf-8")}function fe(t){let e=["# Agentic QE v3 Configuration","# Generated by aqe init",`# ${new Date().toISOString()}`,""];e.push(`version: "${t.version}"`),e.push(""),e.push("project:"),e.push(` name: "${t.project.name}"`),e.push(` root: "${t.project.root}"`),e.push(` type: "${t.project.type}"`),e.push(""),e.push("learning:"),e.push(` enabled: ${t.learning.enabled}`),e.push(` embeddingModel: "${t.learning.embeddingModel}"`),e.push(" hnswConfig:"),e.push(` M: ${t.learning.hnswConfig.M}`),e.push(` efConstruction: ${t.learning.hnswConfig.efConstruction}`),e.push(` efSearch: ${t.learning.hnswConfig.efSearch}`),e.push(` qualityThreshold: ${t.learning.qualityThreshold}`),e.push(` promotionThreshold: ${t.learning.promotionThreshold}`),e.push(` pretrainedPatterns: ${t.learning.pretrainedPatterns}`),e.push(""),e.push("routing:"),e.push(` mode: "${t.routing.mode}"`),e.push(` confidenceThreshold: ${t.routing.confidenceThreshold}`),e.push(` feedbackEnabled: ${t.routing.feedbackEnabled}`),e.push(""),e.push("# ADR-092: Advisor Strategy \u2014 agents consult a stronger model for strategic guidance"),e.push("# Set provider/model to override auto-detection from environment API keys"),e.push("advisor:"),e.push(' # provider: "openrouter" # openrouter | claude | ollama (auto-detected if not set)'),e.push(' # model: "anthropic/claude-opus-5.5" # provider-specific model ID'),e.push(' # maxUses: "3" # per-task advisor call cap'),e.push(' redact: "strict" # strict | balanced | off'),e.push(""),e.push("workers:"),e.push(" enabled:");for(let r of t.workers.enabled)e.push(` - "${r}"`);e.push(" intervals:");for(let[r,n]of Object.entries(t.workers.intervals))e.push(` ${r}: ${n}`);e.push(` maxConcurrent: ${t.workers.maxConcurrent}`),e.push(` daemonAutoStart: ${t.workers.daemonAutoStart}`),e.push(""),e.push("hooks:"),e.push(` claudeCode: ${t.hooks.claudeCode}`),e.push(` preCommit: ${t.hooks.preCommit}`),e.push(` ciIntegration: ${t.hooks.ciIntegration}`),e.push(""),e.push("skills:"),e.push(` install: ${t.skills.install}`),e.push(` installV2: ${t.skills.installV2}`),e.push(` installV3: ${t.skills.installV3}`),e.push(` overwrite: ${t.skills.overwrite}`),e.push(""),e.push("autoTuning:"),e.push(` enabled: ${t.autoTuning.enabled}`),e.push(" parameters:");for(let r of t.autoTuning.parameters)e.push(` - "${r}"`);e.push(` evaluationPeriodMs: ${t.autoTuning.evaluationPeriodMs}`),e.push(""),e.push("domains:"),e.push(" enabled:");for(let r of t.domains.enabled)e.push(` - "${r}"`);e.push(" disabled:");for(let r of t.domains.disabled)e.push(` - "${r}"`);return e.push(""),e.push("agents:"),e.push(` maxConcurrent: ${t.agents.maxConcurrent}`),e.push(` defaultTimeout: ${t.agents.defaultTimeout}`),e.push(""),e.join(`
|
|
315
|
+
`)}var ye=[{id:"welcome",title:"Welcome to AQE v3",description:"This wizard will configure Agentic QE for your project.",type:"info"},{id:"project-type",title:"Project Type",description:"What type of project is this?",type:"choice",options:[{value:"auto",label:"Auto-detect",description:"Let AQE analyze your project",recommended:!0},{value:"single",label:"Single Package",description:"Standard single-package project"},{value:"monorepo",label:"Monorepo",description:"Multi-package workspace"},{value:"library",label:"Library",description:"Publishable package/library"}],default:"auto"},{id:"learning-mode",title:"Learning System",description:"How should AQE learn from your project?",type:"choice",options:[{value:"full",label:"Full Learning",description:"Transformer embeddings + SQLite persistence",recommended:!0},{value:"basic",label:"Basic Learning",description:"Hash-based embeddings, in-memory"},{value:"disabled",label:"Disabled",description:"No pattern learning"}],default:"full"},{id:"load-patterns",title:"Pre-trained Patterns",description:"Load pre-trained QE patterns for faster results?",type:"confirm",default:!0},{id:"hooks",title:"Claude Code Integration",description:"Enable Claude Code hooks for seamless integration?",type:"confirm",default:!0},{id:"workers",title:"Background Workers",description:"Start background workers for continuous monitoring?",type:"confirm",default:!0},{id:"skills",title:"Install Skills",description:"Install AQE skills (v2 methodology + v3 domain skills)?",type:"confirm",default:!0},{id:"agents",title:"Install Agents",description:"Install V3 QE agents for Claude Code Task tool?",type:"confirm",default:!0}],I=class{projectRoot;options;analyzer;configurator;steps=[];constructor(e){this.options=e,this.projectRoot=e.projectRoot,this.analyzer=D(e.projectRoot),this.configurator=O({minimal:e.minimal})}async initialize(){let e=Date.now();try{let r=await this.runStep("Project Analysis",async()=>await this.analyzer.analyze()),n=await this.runStep("Configuration Generation",async()=>this.options.autoMode?this.configurator.recommend(r):this.applyWizardAnswers(r));await this.runStep("Persistence Database Setup",async()=>await Y(this.projectRoot));let s=await this.runStep("Code Intelligence Pre-Scan",async()=>{if(!await Z(this.projectRoot))return console.log(" Building knowledge graph for code intelligence..."),await ee(r.projectRoot);let w=await te(this.projectRoot);return console.log(` Using existing code intelligence index (${w} entries)`),{status:"existing",entries:w}}),o=await this.runStep("Learning System Setup",async()=>n.learning.enabled&&!this.options.skipPatterns?await ne(this.projectRoot,n,this.options.pretrainedLibrary):0),d=await this.runStep("Hooks Configuration",async()=>n.hooks.claudeCode?await H(this.projectRoot,n):!1),l=await this.runStep("MCP Configuration",async()=>this.options.noMcp?!1:await B(this.projectRoot,{force:this.options.withMcp})),p=await this.runStep("CLAUDE.md Generation",async()=>await X(this.projectRoot,n)),a=await this.runStep("Background Workers",async()=>n.workers.daemonAutoStart?await re(this.projectRoot,n):0),m=await this.runStep("Skills Installation",async()=>n.skills.install?await se(this.projectRoot,n):0),S=await this.runStep("Agents Installation",async()=>await ae(this.projectRoot)),g;if(this.options.withN8n){let c=await this.runStep("N8n Platform Installation",async()=>await oe(this.projectRoot,n,this.options.n8nApiConfig));c&&(g=c)}return await this.runStep("Save Configuration",async()=>await ie(this.projectRoot,n)),await this.runStep("Version Marker",async()=>await K(this.projectRoot,n.version)),{success:!0,config:n,steps:this.steps,summary:{projectAnalyzed:!0,configGenerated:!0,codeIntelligenceIndexed:s?.entries??0,patternsLoaded:o,skillsInstalled:m,agentsInstalled:S,hooksConfigured:d,mcpConfigured:l,claudeMdGenerated:p,workersStarted:a,n8nInstalled:g},totalDurationMs:Date.now()-e,timestamp:new Date}}catch(r){return this.steps.push({step:"Initialization Failed",status:"error",message:h(r),durationMs:0}),{success:!1,config:R("unknown",this.projectRoot),steps:this.steps,summary:{projectAnalyzed:!1,configGenerated:!1,codeIntelligenceIndexed:0,patternsLoaded:0,skillsInstalled:0,agentsInstalled:0,hooksConfigured:!1,mcpConfigured:!1,claudeMdGenerated:!1,workersStarted:0},totalDurationMs:Date.now()-e,timestamp:new Date}}}getWizardSteps(){return ye}async runStep(e,r){let n=Date.now();try{let s=await r();return this.steps.push({step:e,status:"success",message:`${e} completed successfully`,durationMs:Date.now()-n}),s}catch(s){throw this.steps.push({step:e,status:"error",message:h(s),durationMs:Date.now()-n}),s}}applyWizardAnswers(e){let r=this.options.wizardAnswers||{},n=this.configurator.recommend(e);switch(r["project-type"]&&r["project-type"]!=="auto"&&(n.project.type=r["project-type"]),r["learning-mode"]){case"full":n.learning.enabled=!0,n.learning.embeddingModel="transformer";break;case"basic":n.learning.enabled=!0,n.learning.embeddingModel="hash";break;case"disabled":n.learning.enabled=!1;break}return r["load-patterns"]===!1&&(n.learning.pretrainedPatterns=!1),r.hooks===!1&&(n.hooks.claudeCode=!1),r.workers===!1&&(n.workers.daemonAutoStart=!1),r.skills===!1&&(n.skills.install=!1),n}};function ke(t){return new I(t)}async function We(t){return await ke({projectRoot:t,autoMode:!0}).initialize()}function Ge(t){let e=[];e.push(""),e.push("+-------------------------------------------------------------+"),e.push("| AQE v3 Initialization |"),e.push("+-------------------------------------------------------------+");for(let n of t.steps){let s=n.status==="success"?"[OK]":n.status==="error"?"[!!]":"[ ]";e.push(`| ${s} ${n.step.padEnd(50)} ${String(n.durationMs).padStart(4)}ms |`)}e.push("+-------------------------------------------------------------+"),e.push(`| Project: ${t.config.project.name.padEnd(47)} |`),e.push(`| Type: ${t.config.project.type.padEnd(50)} |`),e.push(`| Code Intel Indexed: ${String(t.summary.codeIntelligenceIndexed).padEnd(36)} |`),e.push(`| Patterns Loaded: ${String(t.summary.patternsLoaded).padEnd(39)} |`),e.push(`| Skills Installed: ${String(t.summary.skillsInstalled).padEnd(38)} |`),e.push(`| Agents Installed: ${String(t.summary.agentsInstalled).padEnd(38)} |`),e.push(`| Workers Started: ${String(t.summary.workersStarted).padEnd(39)} |`),e.push(`| Hooks Configured: ${t.summary.hooksConfigured?"Yes":"No".padEnd(38)} |`),e.push(`| MCP Server: ${t.summary.mcpConfigured?"Yes":"No".padEnd(44)} |`),e.push(`| CLAUDE.md: ${t.summary.claudeMdGenerated?"Yes":"No".padEnd(45)} |`),e.push("+-------------------------------------------------------------+");let r=t.success?"[OK] AQE v3 initialized as self-learning platform":"[!!] Initialization failed";return e.push(`| ${r.padEnd(57)} |`),e.push("+-------------------------------------------------------------+"),e.push(""),e.join(`
|
|
316
|
+
`)}export{I as a,ke as b,We as c,Ge as d};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
|
|
2
2
|
var p={"||":1,"&&":2,"===":3,"!==":3,"==":3,"!=":3,"<":4,">":4,"<=":4,">=":4,"+":5,"-":5,"*":6,"/":6,"%":6},l=new Set(Object.keys(p)),w=new Set(["!","-","+"]);function h(r){let n=[],e=0;for(;e<r.length;){let t=r[e];if(/\s/.test(t)){e++;continue}if(/\d/.test(t)||t==="."&&/\d/.test(r[e+1])){let s="";for(;e<r.length&&/[\d.]/.test(r[e]);)s+=r[e++];n.push({type:"NUMBER",value:parseFloat(s),raw:s});continue}if(t==='"'||t==="'"){let s=t,u="";for(e++;e<r.length&&r[e]!==s;){if(r[e]==="\\"&&e+1<r.length){e++;let c=r[e];switch(c){case"n":u+=`
|
|
3
3
|
`;break;case"t":u+=" ";break;case"r":u+="\r";break;default:u+=c}}else u+=r[e];e++}e++,n.push({type:"STRING",value:u,raw:`${s}${u}${s}`});continue}if(/[a-zA-Z_$]/.test(t)){let s="";for(;e<r.length&&/[a-zA-Z0-9_$]/.test(r[e]);)s+=r[e++];s==="true"?n.push({type:"BOOLEAN",value:!0,raw:s}):s==="false"?n.push({type:"BOOLEAN",value:!1,raw:s}):s==="null"?n.push({type:"NULL",value:null,raw:s}):s==="undefined"?n.push({type:"UNDEFINED",value:void 0,raw:s}):n.push({type:"IDENTIFIER",value:s,raw:s});continue}let a=r.slice(e,e+2),o=r.slice(e,e+3);if(o==="==="||o==="!=="){n.push({type:"OPERATOR",value:o,raw:o}),e+=3;continue}if(a==="=="||a==="!="||a==="<="||a===">="||a==="&&"||a==="||"){n.push({type:"OPERATOR",value:a,raw:a}),e+=2;continue}if(t==="("){n.push({type:"LPAREN",value:"(",raw:"("}),e++;continue}if(t===")"){n.push({type:"RPAREN",value:")",raw:")"}),e++;continue}if(t==="."){n.push({type:"DOT",value:".",raw:"."}),e++;continue}if("+-*/%<>!".includes(t)){n.push({type:"OPERATOR",value:t,raw:t}),e++;continue}throw new Error(`Unexpected character at position ${e}: ${t}`)}return n.push({type:"EOF",value:"",raw:""}),n}var i=class{tokens;pos=0;context;constructor(n,e){this.tokens=n,this.context=e}current(){return this.tokens[this.pos]}advance(){return this.tokens[this.pos++]}expect(n){let e=this.current();if(e.type!==n)throw new Error(`Expected ${n}, got ${e.type}`);return this.advance()}parse(){let n=this.parseExpression(0);if(this.current().type!=="EOF")throw new Error(`Unexpected token: ${this.current().raw}`);return n}parseExpression(n){let e=this.parseUnary();for(;;){let t=this.current();if(t.type!=="OPERATOR"||!l.has(t.value))break;let a=p[t.value];if(a<n)break;let o=this.advance().value,s=this.parseExpression(a+1);e=this.applyBinaryOperator(o,e,s)}return e}parseUnary(){let n=this.current();if(n.type==="OPERATOR"&&w.has(n.value)){let e=this.advance().value,t=this.parseUnary();return this.applyUnaryOperator(e,t)}return this.parsePrimary()}parsePrimary(){let n=this.current();switch(n.type){case"NUMBER":case"STRING":case"BOOLEAN":case"NULL":case"UNDEFINED":return this.advance(),n.value;case"IDENTIFIER":return this.parseIdentifier();case"LPAREN":{this.advance();let e=this.parseExpression(0);return this.expect("RPAREN"),e}default:throw new Error(`Unexpected token: ${n.raw}`)}}parseIdentifier(){let n=this.context,e=this.advance().value;for(typeof n=="object"&&n!==null&&Object.hasOwn(n,e)?n=n[e]:n=void 0;this.current().type==="DOT";){this.advance();let t=this.expect("IDENTIFIER").value;n!=null&&typeof n=="object"&&Object.hasOwn(n,t)?n=n[t]:n=void 0}return n}applyBinaryOperator(n,e,t){switch(n){case"===":return e===t;case"!==":return e!==t;case"==":return e==t;case"!=":return e!=t;case"<":return e<t;case">":return e>t;case"<=":return e<=t;case">=":return e>=t;case"&&":return e&&t;case"||":return e||t;case"+":return e+t;case"-":return e-t;case"*":return e*t;case"/":return e/t;case"%":return e%t;default:throw new Error(`Unknown operator: ${n}`)}}applyUnaryOperator(n,e){switch(n){case"!":return!e;case"-":return-e;case"+":return+e;default:throw new Error(`Unknown unary operator: ${n}`)}}};function b(r,n={}){if(!r||typeof r!="string")throw new Error("Expression must be a non-empty string");let e=[/\beval\b/i,/\bFunction\b/,/\bconstructor\b/,/\b__proto__\b/,/\bprototype\b/,/\bimport\b/,/\brequire\b/,/\bprocess\b/,/\bglobal\b/,/\bwindow\b/,/\bdocument\b/,/\[\s*['"`]/,/\[.*\]/];for(let o of e)if(o.test(r))throw new Error(`Expression contains potentially dangerous pattern: ${r}`);let t=h(r.trim());return new i(t,n).parse()}function E(r,n={},e=!1){try{return!!b(r,n)}catch(t){return console.warn(`[SafeEvaluator] Failed to evaluate expression: ${r}`,t),e}}export{E as a};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
|
|
2
|
+
import{a as e,b as g,e as t}from"./chunk-G5RHFBAY.js";import{d as r}from"./chunk-XIIQ5QTT.js";import{b as o}from"./chunk-AJMJNQMP.js";var L=o(()=>{"use strict";e();g();t();r()});export{L as a};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
|
|
2
2
|
import{writeFileSync as p,readFileSync as m}from"node:fs";import{resolve as f,dirname as u,join as g}from"node:path";import{mkdirSync as h}from"node:fs";import{fileURLToPath as y}from"node:url";function v(){try{let e=typeof __dirname<"u"?__dirname:u(y(import.meta.url));for(let n=0;n<5;n++){let t=g(e,"package.json");try{let r=JSON.parse(m(t,"utf-8"));if(r.version)return r.version}catch{}e=u(e)}}catch{}return"unknown"}function d(e){return e.status??e.evidence?.completeness??"unverified"}var T=["-F, --format <format>","Output format (text|json|sarif|junit|markdown)","text"],w=["-o, --output <path>","Write output to file instead of stdout"];function C(e,n,t){if(n){let r=f(n);h(u(r),{recursive:!0}),p(r,e,"utf-8"),t&&console.log(t),console.log(`Output written to: ${r}`)}else console.log(e)}function S(e){return JSON.stringify(e,null,2)}var $="https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json";function E(e){let n=d(e),t=s=>{switch(s.toLowerCase()){case"critical":case"high":return"error";case"medium":return"warning";case"low":case"info":return"note";default:return"warning"}},r=new Map,o=[];for(let s of e.vulnerabilities){let a=s.ruleId||`AQE/${s.type.replace(/\s+/g,"-").toLowerCase()}`;r.has(a)||r.set(a,{id:a,name:s.type,shortDescription:s.type,...s.cweId?{helpUri:`https://cwe.mitre.org/data/definitions/${s.cweId.replace("CWE-","")}.html`}:{}}),o.push({ruleId:a,level:t(s.severity),message:{text:s.message},locations:[{physicalLocation:{artifactLocation:{uri:s.file,uriBaseId:"%SRCROOT%"},region:{startLine:s.line,startColumn:1}}}],...s.cweId?{taxa:[{id:s.cweId,toolComponent:{name:"CWE"}}]}:{}})}let i={$schema:$,version:"2.1.0",runs:[{tool:{driver:{name:"agentic-qe",version:v(),informationUri:"https://github.com/proffesor-for-testing/agentic-qe",rules:Array.from(r.values()).map(s=>({id:s.id,name:s.name,shortDescription:{text:s.shortDescription},...s.helpUri?{helpUri:s.helpUri}:{},defaultConfiguration:{level:"warning"}}))}},results:o,properties:{securityScan:{status:n,target:e.target,scanType:e.scanType,coverage:e.evidence?e.coverage:void 0,evidence:e.evidence,discovery:e.discovery,checks:e.checks}},invocations:[{executionSuccessful:n==="complete",...n==="complete"?{}:{toolExecutionNotifications:[{level:"warning",message:{text:`Security analysis ${n}; findings do not establish complete coverage.`}}]}}]}]};return JSON.stringify(i,null,2)}function c(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function F(e){let n=e.tests||[],t=e.passed+e.failed+e.skipped,r=(e.duration/1e3).toFixed(3),o=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
3
|
`;if(o+=`<testsuites tests="${t}" failures="${e.failed}" errors="0" time="${r}">
|
|
4
4
|
`,o+=` <testsuite name="aqe-test-run" tests="${t}" failures="${e.failed}" errors="0" skipped="${e.skipped}" time="${r}" id="${c(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.15.
|
|
2
|
-
import{a as n}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
|
|
2
|
+
import{a as n}from"./chunk-SUDMM5SO.js";import{a as i}from"./chunk-JQ3DYUMS.js";import{a as o,e as d}from"./chunk-CRPIYUTJ.js";import{existsSync as m,statSync as s}from"node:fs";import{extname as l,join as c}from"node:path";d();var _=o.CLEANUP_INTERVAL_MS,y=".agentic-qe/memory.db";async function p(t,r=!0){let e;switch(t.type){case"memory":e=new i;break;case"sqlite":e=new n({sqlite:t.sqlite,enableFallback:!0});break;case"agentdb":e=new n({sqlite:{path:t.agentdb?.path??y},enableFallback:!0});break;case"hybrid":e=new n(t.hybrid);break;default:throw new Error(`Unknown memory backend type: ${t.type}`)}return r&&await e.initialize(),{backend:e,type:t.type,initialized:r}}async function P(t=!0){let r=process.env.AQE_MEMORY_BACKEND??"memory",e=process.env.AQE_MEMORY_PATH,a=e?e===":memory:"?e:m(e)?s(e).isDirectory()?c(e,"memory.db"):e:/\.(db|sqlite|sqlite3)$/i.test(l(e))?e:c(e,"memory.db"):y;return p({type:r,sqlite:{path:a,walMode:!0},agentdb:{path:a},hybrid:{enableFallback:!0,sqlite:{path:a}}},t)}export{p as a,P 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.15.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
|
|
2
2
|
var l=["ECONNREFUSED","ETIMEOUT","ENOMEM","ENOSPC"];var s={successRate:.1,failureRate:1,viabilityThreshold:.3,rehabilitationThreshold:10,maxQuarantineDurationMs:6048e5,domainOverrides:{"security-compliance":{successRate:.05,failureRate:1,viabilityThreshold:.5},"test-generation":{successRate:.15,failureRate:1,viabilityThreshold:.2},"quality-assessment":{successRate:.1,failureRate:1,viabilityThreshold:.4}}},a=class{config;_witnessChain=null;set witnessChain(e){this._witnessChain=e}constructor(e={}){this.config={...s,...e,domainOverrides:{...s.domainOverrides,...e.domainOverrides}}}computeConfidenceUpdate(e,r,i){let{successRate:u,failureRate:o}=this.getConfigForDomain(i),n=r==="success"?u:-o;if(r==="failure")try{this._witnessChain?.append("HEBBIAN_PENALTY",{previousConfidence:e,delta:n,domain:i},"asymmetric-learning")}catch{}return c(e+n,0,1)}shouldQuarantine(e,r){let{viabilityThreshold:i}=this.getConfigForDomain(r);return{shouldQuarantine:e<i,confidence:e,viabilityThreshold:i,domain:r}}classifyFailure(e){if(e.infrastructureHealthy===!1||e.durationMs!==void 0&&e.durationMs>3e4)return"infrastructure";if(e.errorMessage){let r=e.errorMessage.toUpperCase();for(let i of l)if(r.includes(i))return"infrastructure"}return e.failureCategory==="infrastructure"?"infrastructure":(e.failureCategory==="pattern","pattern")}checkRehabilitation(e,r){let i=this.config.rehabilitationThreshold;return{canRehabilitate:e>=i,consecutiveSuccesses:e,requiredSuccesses:i,domain:r}}getConfigForDomain(e){return e&&this.config.domainOverrides?.[e]?this.config.domainOverrides[e]:{successRate:this.config.successRate,failureRate:this.config.failureRate,viabilityThreshold:this.config.viabilityThreshold}}getAsymmetryRatio(e){let{successRate:r,failureRate:i}=this.getConfigForDomain(e);return r===0?1/0:i/r}};function c(t,e,r){return t<e?e:t>r?r:t}export{a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{d as a,e as m}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
|
|
2
|
+
import{d as a,e as m}from"./chunk-HCH4Y6XX.js";var o=n=>typeof n=="number"&&Number.isFinite(n)&&n>=0&&n<=100,l=n=>n===null||o(n);function f(n){if(!n||typeof n!="object")return null;let e=n;if(e.measured!==!0||!o(e.line)||!l(e.statement)||!l(e.branch)||!l(e.function))return null;let r=typeof e.files=="number"&&Number.isInteger(e.files)&&e.files>=0?e.files:null;return r===null?null:{line:e.line,branch:e.branch,function:e.function,statement:e.statement,files:r,measured:!0,...e.runStatus==="passed"||e.runStatus==="failed"?{runStatus:e.runStatus}:{}}}function b(n){if(!n||typeof n!="object")return null;let e=n;if(e.measured!==!0||!o(e.line))return null;let r=t=>o(t)?t:null,u=c(e.lines,e.line);return{line:e.line,branch:r(e.branch),function:r(e.function),statement:r(e.statement),measured:!0,...u?{lines:u}:{}}}function c(n,e){if(!n||typeof n!="object")return;let{covered:r,total:u}=n;if(!Number.isSafeInteger(r)||!Number.isSafeInteger(u))return;let t=r,i=u;if(!(i<=0||t<0||t>i||Math.abs(t/i*100-e)>.01))return{covered:t,total:i}}m();var s=class extends Error{constructor(e,r){super(`git ${e.join(" ")} timed out after ${Math.max(0,r)}ms`),this.name="GitTimeoutError"}};async function g(n,e){if(e.timeout<=0)throw new s(n,e.timeout);try{return await a("git",n,{cwd:e.cwd,timeout:e.timeout,maxBuffer:e.maxBuffer,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}catch(r){throw r.code==="ETIMEDOUT"?new s(n,e.timeout):r}}export{f as a,b,s as c,g as d};
|