agentic-qe 3.13.0 → 3.13.1

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.
Files changed (378) hide show
  1. package/.agents/skills/aqe-plan-quality/SKILL.md +25 -0
  2. package/.agents/skills/aqe-plan-quality/agents/openai.yaml +4 -0
  3. package/.agents/skills/aqe-plan-quality/references/qe-routing.md +22 -0
  4. package/.agents/skills/aqe-review-quality/SKILL.md +24 -0
  5. package/.agents/skills/aqe-review-quality/agents/openai.yaml +4 -0
  6. package/.agents/skills/aqe-review-quality/references/quality-gates.md +20 -0
  7. package/.agents/skills/aqe-test-change/SKILL.md +26 -0
  8. package/.agents/skills/aqe-test-change/agents/openai.yaml +4 -0
  9. package/.agents/skills/aqe-test-change/references/test-specialties.md +23 -0
  10. package/.claude/helpers/ruflo-hook.cjs +5 -1
  11. package/.claude/skills/skills-manifest.json +1 -1
  12. package/.codex/hooks/aqe-codex-hook.cjs +69 -0
  13. package/.codex/hooks/ruflo-codex-hook.cjs +94 -0
  14. package/.codex/hooks.json +169 -0
  15. package/CHANGELOG.md +94 -0
  16. package/assets/skills/skills-manifest.json +1 -1
  17. package/dist/cli/bundle.js +5 -5
  18. package/dist/cli/chunks/adapter-VRZNL53W.js +2 -0
  19. package/dist/cli/chunks/{agent-booster-wasm-ACX2DK7Y.js → agent-booster-wasm-4VM3DE42.js} +2 -2
  20. package/dist/cli/chunks/{agent-handler-B45WP4ZJ.js → agent-handler-ZDLMZQQX.js} +2 -2
  21. package/dist/cli/chunks/{agent-memory-branch-QQLZDE56.js → agent-memory-branch-P72MDHHV.js} +2 -2
  22. package/dist/cli/chunks/aqe-learning-engine-XCNMNERX.js +2 -0
  23. package/dist/cli/chunks/{arena-G3IKZAG5.js → arena-55FZGKEV.js} +4 -4
  24. package/dist/cli/chunks/{arena-SDB7723R.js → arena-GCRBQ26R.js} +2 -2
  25. package/dist/cli/chunks/{audit-GY46XUZA.js → audit-VYAYVLIV.js} +3 -3
  26. package/dist/cli/chunks/base-VZZNR4UR.js +2 -0
  27. package/dist/cli/chunks/{hnswlib-node-RJPBJU2Q.js → better-sqlite3-JDDFYVCX.js} +2 -2
  28. package/dist/cli/chunks/{brain-handler-347CYMPN.js → brain-handler-IUKMRGWO.js} +3 -3
  29. package/dist/cli/chunks/{branch-enumerator-Z3ULBFSM.js → branch-enumerator-TUI3RWLX.js} +2 -2
  30. package/dist/cli/chunks/{browser-OYEIHD7F.js → browser-NBQTZYX2.js} +2 -2
  31. package/dist/cli/chunks/browser-workflow-5DZNIFUY.js +2 -0
  32. package/dist/cli/chunks/{chunk-2NRZYQSF.js → chunk-23MT7OBY.js} +2 -2
  33. package/dist/cli/chunks/{chunk-7UNY32PU.js → chunk-2CQAWYYE.js} +1 -1
  34. package/dist/cli/chunks/{chunk-ZLXBNNNT.js → chunk-2D2XFUKI.js} +2 -2
  35. package/dist/cli/chunks/{chunk-SHCTEXNH.js → chunk-2G2QWV7B.js} +2 -2
  36. package/dist/cli/chunks/{chunk-TZ73SXQ5.js → chunk-2ISLQU3G.js} +1 -1
  37. package/dist/cli/chunks/{chunk-VLNPJAVH.js → chunk-2OM3TDC4.js} +1 -1
  38. package/dist/cli/chunks/{chunk-JGM6XCCP.js → chunk-2XZ4BHWS.js} +1 -1
  39. package/dist/cli/chunks/{chunk-32ZGV4Q4.js → chunk-3F4XH4ZA.js} +1 -1
  40. package/dist/cli/chunks/{chunk-RDU4WTV2.js → chunk-3K4YC3GC.js} +2 -2
  41. package/dist/cli/chunks/chunk-3KGCBAUH.js +2 -0
  42. package/dist/cli/chunks/{chunk-DYUC7WFA.js → chunk-3Y6CHW67.js} +1 -1
  43. package/dist/cli/chunks/{chunk-3JVUWKCO.js → chunk-4QMWWYNU.js} +2 -2
  44. package/dist/cli/chunks/{chunk-L4LLA5U7.js → chunk-4WGSMODQ.js} +1 -1
  45. package/dist/cli/chunks/{chunk-KUA4HHU6.js → chunk-55WDVSCM.js} +2 -2
  46. package/dist/cli/chunks/{chunk-RVJPWRV6.js → chunk-5BB5DUL4.js} +2 -2
  47. package/dist/cli/chunks/{chunk-ZOXWASCC.js → chunk-6C3MZLYW.js} +2 -2
  48. package/dist/cli/chunks/{chunk-CFVEDUTW.js → chunk-6QKQFHS7.js} +2 -2
  49. package/dist/cli/chunks/{chunk-YFGAHNCG.js → chunk-6XZXMEK4.js} +3 -3
  50. package/dist/cli/chunks/{chunk-Z6QCOZ2H.js → chunk-7D7XFZZI.js} +2 -2
  51. package/dist/cli/chunks/{chunk-AO7AHX6K.js → chunk-7WEHZCSK.js} +2 -2
  52. package/dist/cli/chunks/{chunk-K5N6SLHO.js → chunk-A2MG3YXO.js} +1 -1
  53. package/dist/cli/chunks/{chunk-LXPB7H2P.js → chunk-AHTOWWSE.js} +1 -1
  54. package/dist/cli/chunks/{chunk-U2SW6KK5.js → chunk-AOMXMFDH.js} +2 -2
  55. package/dist/cli/chunks/{chunk-VSNRPMAZ.js → chunk-ARTLSAXO.js} +2 -2
  56. package/dist/cli/chunks/{chunk-FBBZHATF.js → chunk-AY7S7AWN.js} +1 -1
  57. package/dist/cli/chunks/{chunk-CYL2FV23.js → chunk-AYYDO52G.js} +2 -2
  58. package/dist/cli/chunks/chunk-BBLWZT5I.js +2 -0
  59. package/dist/cli/chunks/{chunk-QTU3CVOB.js → chunk-BF5BKSDU.js} +2 -2
  60. package/dist/cli/chunks/{chunk-CWUBOLKY.js → chunk-BOCEOLLJ.js} +2 -2
  61. package/dist/cli/chunks/{chunk-FL3BM54K.js → chunk-CE6LYEHT.js} +1 -1
  62. package/dist/cli/chunks/{chunk-THBTN7XB.js → chunk-CWP4RMOM.js} +2 -2
  63. package/dist/cli/chunks/{chunk-Q7PBGNUD.js → chunk-CWXDL7AH.js} +1 -1
  64. package/dist/cli/chunks/{chunk-RVRBTOWX.js → chunk-DTRFZD7N.js} +2 -2
  65. package/dist/cli/chunks/{chunk-IZRLIWFN.js → chunk-DVPGQG4W.js} +2 -2
  66. package/dist/cli/chunks/{chunk-3NOCK6ED.js → chunk-E4D47QTF.js} +2 -2
  67. package/dist/cli/chunks/{chunk-FQLWQWRU.js → chunk-EAKHU5YX.js} +3 -3
  68. package/dist/cli/chunks/{chunk-56WZFXTQ.js → chunk-EGMGOWCE.js} +2 -2
  69. package/dist/cli/chunks/{chunk-OXXMVQDF.js → chunk-ELMUHNXN.js} +2 -2
  70. package/dist/cli/chunks/{chunk-SNTUKW4Q.js → chunk-EVDYFGVH.js} +2 -2
  71. package/dist/cli/chunks/{chunk-RLCWR7TS.js → chunk-FDUSWM6O.js} +98 -88
  72. package/dist/cli/chunks/{chunk-D3MPV5G7.js → chunk-FM272B4O.js} +2 -2
  73. package/dist/cli/chunks/{chunk-DRIJYTSK.js → chunk-FQUUMC57.js} +2 -2
  74. package/dist/cli/chunks/{chunk-5KAT6WBQ.js → chunk-FQXQJMSF.js} +2 -2
  75. package/dist/cli/chunks/{chunk-BCKTBGDM.js → chunk-FRAGSKXQ.js} +3 -3
  76. package/dist/cli/chunks/{chunk-SRQ3CPJE.js → chunk-GASOBSNB.js} +4 -4
  77. package/dist/cli/chunks/{chunk-GTUFX7AR.js → chunk-GJEEPKAT.js} +2 -2
  78. package/dist/cli/chunks/{chunk-5EIOQCGN.js → chunk-GOV2MHLV.js} +2 -2
  79. package/dist/cli/chunks/{chunk-QI4CGJNK.js → chunk-GTPZVLL6.js} +1 -1
  80. package/dist/cli/chunks/chunk-H7YZ2YF2.js +3 -0
  81. package/dist/cli/chunks/{chunk-ANIDFJCT.js → chunk-HFI5PHG5.js} +3 -3
  82. package/dist/cli/chunks/{chunk-2VQVEQS4.js → chunk-HUMQU4ES.js} +2 -2
  83. package/dist/cli/chunks/{chunk-VHYMSZNF.js → chunk-HYIRFJDB.js} +2 -2
  84. package/dist/cli/chunks/{chunk-A4QLGPYO.js → chunk-IBSBOHUX.js} +2 -2
  85. package/dist/cli/chunks/{chunk-6SXKCIN5.js → chunk-IJA4WS7B.js} +1 -1
  86. package/dist/cli/chunks/{chunk-3GSYD5SL.js → chunk-IJP42OGW.js} +2 -2
  87. package/dist/cli/chunks/{chunk-PERJO2DY.js → chunk-IMQKEFW6.js} +1 -1
  88. package/dist/cli/chunks/{chunk-ZEIG5IQ4.js → chunk-INYS35DV.js} +2 -2
  89. package/dist/cli/chunks/{chunk-J3L52EA4.js → chunk-IV2VCR75.js} +5 -5
  90. package/dist/cli/chunks/{chunk-TVMFH5N2.js → chunk-IZO6TPGX.js} +2 -2
  91. package/dist/cli/chunks/{chunk-ZJG6N2OK.js → chunk-J45DX3IK.js} +1 -1
  92. package/dist/cli/chunks/{chunk-HL2QMM4M.js → chunk-J4T6D2OQ.js} +2 -2
  93. package/dist/cli/chunks/{chunk-5ICQL42E.js → chunk-JAPOMPFD.js} +2 -2
  94. package/dist/cli/chunks/{chunk-L2SFGFE6.js → chunk-JELNVHBF.js} +1 -1
  95. package/dist/cli/chunks/{chunk-RSFIOR2I.js → chunk-JOTNKZ7A.js} +87 -87
  96. package/dist/cli/chunks/{chunk-34PEINFS.js → chunk-KNWDXI3I.js} +2 -2
  97. package/dist/cli/chunks/{chunk-FUU32QY5.js → chunk-KW5NBORV.js} +2 -2
  98. package/dist/cli/chunks/{chunk-N5MMBA35.js → chunk-L7IOTWWY.js} +1 -1
  99. package/dist/cli/chunks/{chunk-RJZRWVL4.js → chunk-LJQ27PUE.js} +1 -1
  100. package/dist/cli/chunks/{chunk-QQB55ZJJ.js → chunk-LSKQUUUN.js} +2 -2
  101. package/dist/cli/chunks/{chunk-NETN3OUG.js → chunk-LSZZQ7H6.js} +1 -1
  102. package/dist/cli/chunks/{chunk-IYDYJ33J.js → chunk-LTKNCYMO.js} +2 -2
  103. package/dist/cli/chunks/{chunk-6DTOGSDV.js → chunk-LTWT4GZD.js} +4 -4
  104. package/dist/cli/chunks/{chunk-NQNKKVNO.js → chunk-LVHMXGDI.js} +3 -3
  105. package/dist/cli/chunks/{chunk-3UHEZ5HZ.js → chunk-M3T6FB54.js} +2 -2
  106. package/dist/cli/chunks/{chunk-ZJIX5FGQ.js → chunk-MAYZTGJ2.js} +2 -2
  107. package/dist/cli/chunks/{chunk-3K4SF57Q.js → chunk-MCIO7BDK.js} +1 -1
  108. package/dist/cli/chunks/{chunk-A7GLWWSE.js → chunk-MPD7RR4P.js} +1 -1
  109. package/dist/cli/chunks/{chunk-FAQLI3P5.js → chunk-MUFYDKVC.js} +2 -2
  110. package/dist/cli/chunks/{chunk-XFCWYQHW.js → chunk-MX5ZDKRR.js} +2 -2
  111. package/dist/cli/chunks/{chunk-MBCGI3M2.js → chunk-MXKHIZVM.js} +5 -5
  112. package/dist/cli/chunks/chunk-MY47CR27.js +2 -0
  113. package/dist/cli/chunks/chunk-N7WAZ2Y6.js +2 -0
  114. package/dist/cli/chunks/{chunk-VC6EXDGY.js → chunk-NHV4PTG6.js} +2 -2
  115. package/dist/cli/chunks/{chunk-LBE2P6UC.js → chunk-NP4CP3LR.js} +2 -2
  116. package/dist/cli/chunks/{chunk-6AOBLBR4.js → chunk-OCKTPTQ7.js} +2 -2
  117. package/dist/cli/chunks/{chunk-ES7WCYOU.js → chunk-OE4B6LDZ.js} +1 -1
  118. package/dist/cli/chunks/{chunk-IPHLXAMX.js → chunk-OPQY2333.js} +2 -2
  119. package/dist/cli/chunks/{chunk-7DMXCCSD.js → chunk-ORDH4VPL.js} +1 -1
  120. package/dist/cli/chunks/{chunk-HTPM3URI.js → chunk-P4Y3G6OB.js} +2 -2
  121. package/dist/cli/chunks/{chunk-TNRIGQ6U.js → chunk-PIOO2M4W.js} +2 -2
  122. package/dist/cli/chunks/{chunk-BGYLNCL6.js → chunk-PKMCZFET.js} +2 -2
  123. package/dist/cli/chunks/{chunk-G7FMYFTN.js → chunk-QES4QHQW.js} +1 -1
  124. package/dist/cli/chunks/{chunk-UIPPJKON.js → chunk-QG6BXSNJ.js} +2 -2
  125. package/dist/cli/chunks/{chunk-7YXT6BXN.js → chunk-QLOOW23R.js} +3 -3
  126. package/dist/cli/chunks/{chunk-CQFT7H3F.js → chunk-RSCGBHLM.js} +2 -2
  127. package/dist/cli/chunks/{chunk-QCEW4ZDW.js → chunk-RZ6CO3RZ.js} +2 -2
  128. package/dist/cli/chunks/{chunk-OETDMOOE.js → chunk-S6F3IJMK.js} +1 -1
  129. package/dist/cli/chunks/{chunk-KVL63BSU.js → chunk-S6VNPKHO.js} +1 -1
  130. package/dist/cli/chunks/{chunk-BUGWPTMF.js → chunk-SHWXADCI.js} +2 -2
  131. package/dist/cli/chunks/{chunk-FQY3UTGA.js → chunk-SPJQJWGK.js} +2 -2
  132. package/dist/cli/chunks/{chunk-BOVH6WSM.js → chunk-SS6K4FBH.js} +2 -2
  133. package/dist/cli/chunks/{chunk-4BESADKE.js → chunk-SXADKQJN.js} +2 -2
  134. package/dist/cli/chunks/{chunk-USMDIIHY.js → chunk-TBQTGQ75.js} +2 -2
  135. package/dist/cli/chunks/{chunk-4BDLD7V2.js → chunk-TDGE52HJ.js} +1 -1
  136. package/dist/cli/chunks/{chunk-JPIBPKBP.js → chunk-THFLRJT6.js} +3 -3
  137. package/dist/cli/chunks/{chunk-ZCFZ4USU.js → chunk-TQ2MA3SR.js} +1 -1
  138. package/dist/cli/chunks/{chunk-G5DFYX3J.js → chunk-UCQ66N6M.js} +2 -2
  139. package/dist/cli/chunks/{chunk-CPH5JP4L.js → chunk-UHGMS2PJ.js} +1 -1
  140. package/dist/cli/chunks/{chunk-ANYYTWOQ.js → chunk-UHKXKWMD.js} +2 -2
  141. package/dist/cli/chunks/{chunk-YRQLVGCI.js → chunk-UJ6TMZC6.js} +2 -2
  142. package/dist/cli/chunks/{chunk-EECM5XKY.js → chunk-UKBDH27A.js} +1 -1
  143. package/dist/cli/chunks/{chunk-VLBV2VL3.js → chunk-UMCEEXQN.js} +1 -1
  144. package/dist/cli/chunks/{chunk-LOXVVMS4.js → chunk-USUFTHHT.js} +3 -3
  145. package/dist/cli/chunks/{chunk-HOKON5EL.js → chunk-V32MDID3.js} +2 -2
  146. package/dist/cli/chunks/{chunk-KZTBNDNE.js → chunk-VAJT6QWX.js} +1 -1
  147. package/dist/cli/chunks/{chunk-UNIBND6A.js → chunk-VLUJWI56.js} +1 -1
  148. package/dist/cli/chunks/{chunk-QWYISZTN.js → chunk-WINA3XUT.js} +2 -2
  149. package/dist/cli/chunks/{chunk-YPTGE5NJ.js → chunk-WWCH5SSF.js} +2 -2
  150. package/dist/cli/chunks/{chunk-W5YEIHIO.js → chunk-WWP2VXYJ.js} +2 -2
  151. package/dist/cli/chunks/{chunk-GFBLWFRV.js → chunk-WZROSTQZ.js} +1 -1
  152. package/dist/cli/chunks/{chunk-UMG5URNV.js → chunk-XFUF654L.js} +1 -1
  153. package/dist/cli/chunks/{chunk-54MFKCLT.js → chunk-XN2CD5S6.js} +2 -2
  154. package/dist/cli/chunks/{chunk-IHQTXJAQ.js → chunk-XOQQGZFY.js} +1 -1
  155. package/dist/cli/chunks/{chunk-WRYT4HTZ.js → chunk-XSCOEY4C.js} +2 -2
  156. package/dist/cli/chunks/{chunk-R3GEXYO4.js → chunk-Y734CWHJ.js} +2 -2
  157. package/dist/cli/chunks/{chunk-NUQBJGGF.js → chunk-YBPCBFEE.js} +2 -2
  158. package/dist/cli/chunks/{chunk-GUEZQOHL.js → chunk-YLAEIS6F.js} +1 -1
  159. package/dist/cli/chunks/{chunk-EFRESRLB.js → chunk-YMMVCOPF.js} +3 -3
  160. package/dist/cli/chunks/{chunk-N7VOOI3U.js → chunk-YQCAXYBF.js} +2 -2
  161. package/dist/cli/chunks/{chunk-5FLTZ3KT.js → chunk-YRVUYM62.js} +2 -2
  162. package/dist/cli/chunks/{chunk-GJMZR7WU.js → chunk-YVKMHXQK.js} +3 -3
  163. package/dist/cli/chunks/{chunk-TZPKTRJB.js → chunk-ZCLFAOVT.js} +2 -2
  164. package/dist/cli/chunks/{chunk-L4S722JD.js → chunk-ZH6ZBDVV.js} +1 -1
  165. package/dist/cli/chunks/{chunk-KSYLRM4Q.js → chunk-ZHEKGB4A.js} +2 -2
  166. package/dist/cli/chunks/{chunk-E3B5XTXJ.js → chunk-ZIBW7CB4.js} +1 -1
  167. package/dist/cli/chunks/{chunk-2DIT5AUU.js → chunk-ZLCATRXI.js} +2 -2
  168. package/dist/cli/chunks/{chunk-LWYLW7RX.js → chunk-ZXX2VFMA.js} +2 -2
  169. package/dist/cli/chunks/{chunk-XKFE3FLI.js → chunk-ZYPESQ4M.js} +2 -2
  170. package/dist/cli/chunks/{ci-74ZUCO5V.js → ci-HHL5WQXQ.js} +2 -2
  171. package/dist/cli/chunks/{ci-output-HD6IZNJA.js → ci-output-HVOJC2KN.js} +2 -2
  172. package/dist/cli/chunks/{circuit-breaker-USZVMA42.js → circuit-breaker-HRXMIY2G.js} +2 -2
  173. package/dist/cli/chunks/{claude-flow-setup-S4XKNCD5.js → claude-flow-setup-3I7WVMZN.js} +2 -2
  174. package/dist/cli/chunks/client-EY2IYQDL.js +2 -0
  175. package/dist/cli/chunks/{cline-installer-6EW4CHAR.js → cline-installer-NBREL4QT.js} +2 -2
  176. package/dist/cli/chunks/{code-TOLWD2XL.js → code-TX4E2RWU.js} +2 -2
  177. package/dist/cli/chunks/{code-index-extractor-UA4QQ7B3.js → code-index-extractor-YELOFLSL.js} +2 -2
  178. package/dist/cli/chunks/codex-installer-HEX3KFRB.js +10 -0
  179. package/dist/cli/chunks/{completions-KVUMQQ4K.js → completions-72GGFRGG.js} +2 -2
  180. package/dist/cli/chunks/{complexity-analyzer-DFH6LMK2.js → complexity-analyzer-WRAKDYUK.js} +2 -2
  181. package/dist/cli/chunks/{continuedev-installer-LYDQSAU7.js → continuedev-installer-UGYKSKTI.js} +2 -2
  182. package/dist/cli/chunks/{copilot-installer-7USXLZHZ.js → copilot-installer-RPCRUKIJ.js} +2 -2
  183. package/dist/cli/chunks/core-handlers-G4GLA4DT.js +2 -0
  184. package/dist/cli/chunks/{cost-tracker-JBDIUMKZ.js → cost-tracker-CNHJ7G4M.js} +2 -2
  185. package/dist/cli/chunks/{coverage-RGO3K357.js → coverage-RHIQ4XEX.js} +3 -3
  186. package/dist/cli/chunks/cross-domain-router-P3K4IH5H.js +2 -0
  187. package/dist/cli/chunks/{cursor-installer-YEZGD37F.js → cursor-installer-KSRVA4V2.js} +2 -2
  188. package/dist/cli/chunks/{daemon-FVETQ3LL.js → daemon-IT4AAFBW.js} +3 -3
  189. package/dist/cli/chunks/{daemon-LPEXHNYG.js → daemon-QBXSJABV.js} +4 -4
  190. package/dist/cli/chunks/{dag-attention-scheduler-UKYE2FII.js → dag-attention-scheduler-F7WCQTLY.js} +2 -2
  191. package/dist/cli/chunks/{detect-WBG5P7ER.js → detect-2IYU332U.js} +2 -2
  192. package/dist/cli/chunks/{dist-node-YW6YRBCU.js → dist-node-CIYNYCYN.js} +2 -2
  193. package/dist/cli/chunks/{domain-handler-HH7J4A32.js → domain-handler-QRYQO2QK.js} +2 -2
  194. package/dist/cli/chunks/{domain-transfer-V34GXD5I.js → domain-transfer-2OQDOD3G.js} +2 -2
  195. package/dist/cli/chunks/dream-IT4ZQGEO.js +2 -0
  196. package/dist/cli/chunks/{embed-and-insert-pattern-WYLRS3CL.js → embed-and-insert-pattern-P2IFC7JL.js} +2 -2
  197. package/dist/cli/chunks/{eval-EIMVXY5J.js → eval-SBPK37IB.js} +2 -2
  198. package/dist/cli/chunks/{experience-capture-middleware-QMZHRUKM.js → experience-capture-middleware-3GMFND3F.js} +3 -3
  199. package/dist/cli/chunks/{fast-paths-NHLW6XS6.js → fast-paths-4OYYII2F.js} +2 -2
  200. package/dist/cli/chunks/{feature-flags-NE3MBL3P.js → feature-flags-BM6QTMMC.js} +2 -2
  201. package/dist/cli/chunks/{feature-flags-N3UHMSZ3.js → feature-flags-NFCAYUWO.js} +2 -2
  202. package/dist/cli/chunks/{file-discovery-SI44X4YS.js → file-discovery-2M3ZUAGC.js} +2 -2
  203. package/dist/cli/chunks/{fleet-MMYUXRRM.js → fleet-QMGGVIDV.js} +3 -3
  204. package/dist/cli/chunks/{gnn-wrapper-RLYXYU2Q.js → gnn-wrapper-WGMAGZMO.js} +2 -2
  205. package/dist/cli/chunks/{heartbeat-handler-6EDRUYLV.js → heartbeat-handler-5RSMEZGG.js} +4 -4
  206. package/dist/cli/chunks/heartbeat-scheduler-UUWSPHF2.js +2 -0
  207. package/dist/cli/chunks/hnsw-adapter-YUJVSFPD.js +2 -0
  208. package/dist/cli/chunks/hnsw-index-FQZ47RSJ.js +2 -0
  209. package/dist/cli/chunks/{hnsw-legacy-bridge-RVM7EAIH.js → hnsw-legacy-bridge-TYPQ2T6P.js} +2 -2
  210. package/dist/cli/chunks/{better-sqlite3-DUZ6FFAH.js → hnswlib-node-GMRPPMDM.js} +2 -2
  211. package/dist/cli/chunks/{hooks-ZF4VKHEO.js → hooks-NUC5P3OJ.js} +10 -10
  212. package/dist/cli/chunks/hybrid-router-T5MF73NF.js +2 -0
  213. package/dist/cli/chunks/{hypergraph-engine-YWS66PGO.js → hypergraph-engine-OIB7WK54.js} +2 -2
  214. package/dist/cli/chunks/{hypergraph-handler-OQHVRPWB.js → hypergraph-handler-XX2N75QC.js} +3 -3
  215. package/dist/cli/chunks/impact-analyzer-AEGELYMD.js +2 -0
  216. package/dist/cli/chunks/{init-handler-YW74YF2V.js → init-handler-AKSTJMZY.js} +6 -6
  217. package/dist/cli/chunks/init-wizard-WKX3OGWM.js +2 -0
  218. package/dist/cli/chunks/kernel-5CVWFIGR.js +2 -0
  219. package/dist/cli/chunks/{kilocode-installer-APWB2GMA.js → kilocode-installer-375V5ZZB.js} +2 -2
  220. package/dist/cli/chunks/{kiro-installer-DICKFVNC.js → kiro-installer-GKY5GB5Q.js} +2 -2
  221. package/dist/cli/chunks/knowledge-graph-EGPMNDMT.js +2 -0
  222. package/dist/cli/chunks/{learning-MXHNYW5D.js → learning-2CQE3QP6.js} +3 -3
  223. package/dist/cli/chunks/{llm-router-LTFIX7NY.js → llm-router-FTQNRF45.js} +4 -4
  224. package/dist/cli/chunks/llm-router-service-H4LXOARB.js +2 -0
  225. package/dist/cli/chunks/{load-JUMIQ4LZ.js → load-3DBAO5ZG.js} +2 -2
  226. package/dist/cli/chunks/load-test-OOOGITSN.js +2 -0
  227. package/dist/cli/chunks/{mcp-WHIARJGO.js → mcp-AWR6TDXM.js} +2 -2
  228. package/dist/cli/chunks/{memory-KAHS6Z5A.js → memory-GI4LCNXY.js} +5 -5
  229. package/dist/cli/chunks/memory-backend-O2YOT4LW.js +2 -0
  230. package/dist/cli/chunks/{memory-handlers-DG3RRXB6.js → memory-handlers-MALKG7GP.js} +2 -2
  231. package/dist/cli/chunks/{multi-model-executor-E3Y2RHMX.js → multi-model-executor-SWFT5U72.js} +2 -2
  232. package/dist/cli/chunks/{opencode-installer-3RKGNGGE.js → opencode-installer-EYXGYJX5.js} +2 -2
  233. package/dist/cli/chunks/{orchestrator-TXITUKWD.js → orchestrator-MP3EAZVC.js} +5 -5
  234. package/dist/cli/chunks/pattern-null-store-WBOHE2XL.js +2 -0
  235. package/dist/cli/chunks/{pattern-usage-recorder-EE2BUFZT.js → pattern-usage-recorder-25P3R3W7.js} +2 -2
  236. package/dist/cli/chunks/{pipeline-AXTT6KZB.js → pipeline-LSAFL25D.js} +2 -2
  237. package/dist/cli/chunks/{platform-TICPVKE2.js → platform-IJ6DJ2PG.js} +2 -2
  238. package/dist/cli/chunks/{plugin-VQKNV3EM.js → plugin-OXOZRZW2.js} +2 -2
  239. package/dist/cli/chunks/{prime-radiant-advanced-wasm-6GY5YY7D.js → prime-radiant-advanced-wasm-HJNJQQ3R.js} +2 -2
  240. package/dist/cli/chunks/protocol-executor-JCNTPW5J.js +2 -0
  241. package/dist/cli/chunks/{protocol-handler-YFWDR7UZ.js → protocol-handler-TCMUH2HL.js} +2 -2
  242. package/dist/cli/chunks/{prove-FUMRCXAA.js → prove-ADXQ2GOX.js} +2 -2
  243. package/dist/cli/chunks/provider-manager-LPGQ5GOO.js +2 -0
  244. package/dist/cli/chunks/qe-reasoning-bank-FWVYVSPP.js +2 -0
  245. package/dist/cli/chunks/{quality-2APISBW5.js → quality-EWP36ORX.js} +2 -2
  246. package/dist/cli/chunks/{quality-gate-MCC3E5TM.js → quality-gate-3BIG7PVU.js} +3 -3
  247. package/dist/cli/chunks/queen-coordinator-UXNALRVD.js +2 -0
  248. package/dist/cli/chunks/{real-embeddings-CC5TNOTI.js → real-embeddings-D4NBT7W5.js} +2 -2
  249. package/dist/cli/chunks/{roocode-installer-YAHTEVPI.js → roocode-installer-DOPWH6YV.js} +2 -2
  250. package/dist/cli/chunks/router-C6LUIQYY.js +2 -0
  251. package/dist/cli/chunks/routing-feedback-KMSGGDVD.js +2 -0
  252. package/dist/cli/chunks/{routing-handler-6NQBW4TQ.js → routing-handler-5ADEFOHS.js} +2 -2
  253. package/dist/cli/chunks/{ruvector-commands-ZHXLHUPG.js → ruvector-commands-PLMEIHSN.js} +2 -2
  254. package/dist/cli/chunks/{rvf-dual-writer-5KF2DGCW.js → rvf-dual-writer-EQWKVNQB.js} +2 -2
  255. package/dist/cli/chunks/{rvf-migration-adapter-BBU57BGF.js → rvf-migration-adapter-2OWFUUCG.js} +2 -2
  256. package/dist/cli/chunks/{rvf-migration-coordinator-VN4VRZA4.js → rvf-migration-coordinator-URAETAPU.js} +2 -2
  257. package/dist/cli/chunks/rvf-native-adapter-K54BELUE.js +2 -0
  258. package/dist/cli/chunks/{rvf-store-integrity-XCY2XQZA.js → rvf-store-integrity-4AWPW4TF.js} +2 -2
  259. package/dist/cli/chunks/safe-db-NGOZWF2D.js +2 -0
  260. package/dist/cli/chunks/schedule-B3Y5P64E.js +2 -0
  261. package/dist/cli/chunks/scheduler-Z6QVRMTB.js +2 -0
  262. package/dist/cli/chunks/{security-PYP4H3KN.js → security-HDLZVM62.js} +3 -3
  263. package/dist/cli/chunks/{shared-rvf-adapter-3CJHRNX6.js → shared-rvf-adapter-YQT7PF7X.js} +2 -2
  264. package/dist/cli/chunks/{shared-rvf-dual-writer-MKSLKWDI.js → shared-rvf-dual-writer-N5D3NSJ7.js} +2 -2
  265. package/dist/cli/chunks/sqlite-persistence-PLOUGATS.js +2 -0
  266. package/dist/cli/chunks/{status-handler-VYIZ3VJF.js → status-handler-KLYRJ2MR.js} +2 -2
  267. package/dist/cli/chunks/{structural-health-MVV4OWXP.js → structural-health-6LKVRP6Y.js} +2 -2
  268. package/dist/cli/chunks/{sync-VNX6L3TI.js → sync-7VMFPBVB.js} +2 -2
  269. package/dist/cli/chunks/{sync-G47OYIQ3.js → sync-YYOW6L6W.js} +2 -2
  270. package/dist/cli/chunks/{task-handler-GOWF2GEH.js → task-handler-RKQDGFN2.js} +2 -2
  271. package/dist/cli/chunks/{task-handlers-J2WC6J37.js → task-handlers-6YJ4QTEP.js} +3 -3
  272. package/dist/cli/chunks/{test-DMCJ3BXS.js → test-ASPUIUJH.js} +4 -4
  273. package/dist/cli/chunks/{test-scheduling-TRFHHKFM.js → test-scheduling-I7ABQBBU.js} +3 -3
  274. package/dist/cli/chunks/{token-bootstrap-KEQ7AHFF.js → token-bootstrap-2XZBTODN.js} +2 -2
  275. package/dist/cli/chunks/{token-usage-B54FOFOF.js → token-usage-TMUE6PTF.js} +2 -2
  276. package/dist/cli/chunks/{transformers-IACZG7IV.js → transformers-FDHHH4SL.js} +2 -2
  277. package/dist/cli/chunks/{tree-sitter-wasm-parser-N7H4X37E.js → tree-sitter-wasm-parser-G7PGZA5C.js} +2 -2
  278. package/dist/cli/chunks/{types-B3SHT4OD.js → types-JGT57UFP.js} +2 -2
  279. package/dist/cli/chunks/unified-memory-P5YVLMFI.js +2 -0
  280. package/dist/cli/chunks/unified-memory-hnsw-7HI43A2O.js +2 -0
  281. package/dist/cli/chunks/unified-persistence-U26YP3N3.js +2 -0
  282. package/dist/cli/chunks/{upgrade-A2PQ5EWK.js → upgrade-V6UQODJF.js} +2 -2
  283. package/dist/cli/chunks/{validate-UXV7UQUT.js → validate-UBZAE5RW.js} +2 -2
  284. package/dist/cli/chunks/{validate-swarm-MMBU4FPP.js → validate-swarm-TSO2MI5X.js} +2 -2
  285. package/dist/cli/chunks/{vibium-R4GUVADA.js → vibium-7G3VYSQA.js} +2 -2
  286. package/dist/cli/chunks/visual-security-6FCDY5FF.js +2 -0
  287. package/dist/cli/chunks/{web-tree-sitter-MP6E6CJB.js → web-tree-sitter-MIYJSF2L.js} +2 -2
  288. package/dist/cli/chunks/{windsurf-installer-Z6BWMUUO.js → windsurf-installer-5TLZSQIJ.js} +2 -2
  289. package/dist/cli/chunks/witness-chain-I3K3WQID.js +2 -0
  290. package/dist/cli/chunks/{witness-chain-EFLTABBA.js → witness-chain-LTV7H2HM.js} +2 -2
  291. package/dist/cli/chunks/{witness-key-manager-PN36TV43.js → witness-key-manager-PAJ2J4AL.js} +2 -2
  292. package/dist/cli/chunks/{workflow-A2AX3RJU.js → workflow-DL3ESR2H.js} +4 -4
  293. package/dist/cli/chunks/workflow-orchestrator-MAALP4WA.js +2 -0
  294. package/dist/cli/chunks/{wrappers-NA6FHA63.js → wrappers-5HSU665E.js} +2 -2
  295. package/dist/cli/handlers/init-handler.js +1 -1
  296. package/dist/coordination/handlers/coverage-collection.d.ts +161 -0
  297. package/dist/coordination/handlers/coverage-collection.js +639 -0
  298. package/dist/coordination/handlers/coverage-handlers.js +199 -146
  299. package/dist/coordination/handlers/handler-types.d.ts +6 -1
  300. package/dist/coordination/handlers/handler-utils.js +10 -3
  301. package/dist/coordination/handlers/security-handlers.js +17 -2
  302. package/dist/coordination/handlers/test-execution-handlers.js +16 -1
  303. package/dist/coordination/result-saver.js +119 -97
  304. package/dist/coordination/task-executor.d.ts +26 -1
  305. package/dist/coordination/task-executor.js +52 -4
  306. package/dist/domains/code-intelligence/services/knowledge-graph.js +8 -0
  307. package/dist/domains/coverage-analysis/services/coverage-analyzer.js +4 -0
  308. package/dist/domains/coverage-analysis/services/gap-detector.js +4 -0
  309. package/dist/domains/defect-intelligence/services/defect-predictor.js +4 -0
  310. package/dist/domains/defect-intelligence/services/root-cause-analyzer.js +4 -0
  311. package/dist/domains/quality-assessment/services/deployment-advisor.js +4 -0
  312. package/dist/domains/quality-assessment/services/quality-analyzer.js +4 -0
  313. package/dist/domains/security-compliance/services/scanners/sast-scanner.js +4 -0
  314. package/dist/domains/test-generation/index.js +17 -2
  315. package/dist/domains/test-generation/services/test-generator.js +31 -9
  316. package/dist/init/codex-installer.d.ts +13 -0
  317. package/dist/init/codex-installer.js +122 -1
  318. package/dist/init/phases/09-assets.js +4 -0
  319. package/dist/init/phases/phase-interface.d.ts +1 -1
  320. package/dist/learning/real-embeddings.js +15 -1
  321. package/dist/mcp/bundle.js +429 -419
  322. package/dist/mcp/handlers/domain-handler-configs.js +79 -14
  323. package/dist/mcp/types.d.ts +42 -4
  324. package/dist/optimization/session-cache.d.ts +13 -1
  325. package/dist/optimization/session-cache.js +27 -2
  326. package/dist/shared/llm/llm-router-service.js +59 -4
  327. package/dist/shared/llm/router/agent-router-config.d.ts +46 -2
  328. package/dist/shared/llm/router/agent-router-config.js +124 -2
  329. package/dist/shared/llm/router/config-store.d.ts +17 -1
  330. package/dist/shared/llm/router/config-store.js +103 -0
  331. package/dist/shared/llm/router/index.d.ts +2 -2
  332. package/dist/shared/llm/router/index.js +2 -0
  333. package/dist/shared/llm/router/types.d.ts +44 -0
  334. package/dist/shared/llm/router/types.js +1 -0
  335. package/package.json +9 -6
  336. package/dist/cli/chunks/adapter-CWIMFWAI.js +0 -2
  337. package/dist/cli/chunks/aqe-learning-engine-OTXT2DLN.js +0 -2
  338. package/dist/cli/chunks/base-O3SPSWBA.js +0 -2
  339. package/dist/cli/chunks/browser-workflow-MXS3ZKY2.js +0 -2
  340. package/dist/cli/chunks/chunk-G4GTE3RJ.js +0 -2
  341. package/dist/cli/chunks/chunk-HVB2L52I.js +0 -2
  342. package/dist/cli/chunks/chunk-MVI2QMRW.js +0 -2
  343. package/dist/cli/chunks/chunk-OZR25R7W.js +0 -2
  344. package/dist/cli/chunks/chunk-PP2RYSHT.js +0 -3
  345. package/dist/cli/chunks/client-33PGO5FA.js +0 -2
  346. package/dist/cli/chunks/codex-installer-C2CUP4FW.js +0 -8
  347. package/dist/cli/chunks/core-handlers-CSNZIM3A.js +0 -2
  348. package/dist/cli/chunks/cross-domain-router-DRIBR5L3.js +0 -2
  349. package/dist/cli/chunks/dream-WUNO723O.js +0 -2
  350. package/dist/cli/chunks/heartbeat-scheduler-VAFQDJLL.js +0 -2
  351. package/dist/cli/chunks/hnsw-adapter-TIRPA7XE.js +0 -2
  352. package/dist/cli/chunks/hnsw-index-SSQBRQCQ.js +0 -2
  353. package/dist/cli/chunks/hybrid-router-AKBWZOQ3.js +0 -2
  354. package/dist/cli/chunks/impact-analyzer-46FQIZ6Y.js +0 -2
  355. package/dist/cli/chunks/init-wizard-U3NHGYSS.js +0 -2
  356. package/dist/cli/chunks/kernel-ZDXHT6QF.js +0 -2
  357. package/dist/cli/chunks/knowledge-graph-6XTW6WO6.js +0 -2
  358. package/dist/cli/chunks/llm-router-service-3F4E64SY.js +0 -2
  359. package/dist/cli/chunks/load-test-SWZNGEIY.js +0 -2
  360. package/dist/cli/chunks/memory-backend-PR74ZPBA.js +0 -2
  361. package/dist/cli/chunks/pattern-null-store-EPE36BVT.js +0 -2
  362. package/dist/cli/chunks/protocol-executor-IELENNST.js +0 -2
  363. package/dist/cli/chunks/provider-manager-3R3KOBHG.js +0 -2
  364. package/dist/cli/chunks/qe-reasoning-bank-S2R2PCBS.js +0 -2
  365. package/dist/cli/chunks/queen-coordinator-2E23NEV4.js +0 -2
  366. package/dist/cli/chunks/router-3FVLWO6S.js +0 -2
  367. package/dist/cli/chunks/routing-feedback-ZQLRNNR7.js +0 -2
  368. package/dist/cli/chunks/rvf-native-adapter-YFGLQNEB.js +0 -2
  369. package/dist/cli/chunks/safe-db-4SBLBTW7.js +0 -2
  370. package/dist/cli/chunks/schedule-5Y3BGVAA.js +0 -2
  371. package/dist/cli/chunks/scheduler-DOID3QF3.js +0 -2
  372. package/dist/cli/chunks/sqlite-persistence-M4JEQO57.js +0 -2
  373. package/dist/cli/chunks/unified-memory-WNYWTGVX.js +0 -2
  374. package/dist/cli/chunks/unified-memory-hnsw-YPAV7U4E.js +0 -2
  375. package/dist/cli/chunks/unified-persistence-TJ252S7L.js +0 -2
  376. package/dist/cli/chunks/visual-security-VKYXEGJB.js +0 -2
  377. package/dist/cli/chunks/witness-chain-WVXRXKQP.js +0 -2
  378. package/dist/cli/chunks/workflow-orchestrator-GOWSPR3G.js +0 -2
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.0");process.exit(0)}
2
- import{a as l}from"./chunk-UNIBND6A.js";import{a as m}from"./chunk-QI4CGJNK.js";import{i as a}from"./chunk-E3B5XTXJ.js";var u=class{constructor(t,e){this.eventBus=t;this.maxHistorySize=e?.maxHistorySize??1e4,this.eventHistory=new l(this.maxHistorySize),this.correlationTimeout=e?.correlationTimeout??6e4,this.maxEventsPerCorrelation=e?.maxEventsPerCorrelation??100}eventBus;subscriptions=new Map;correlations=new Map;eventHistory;routes=[];domainSubscriptions=new Map;maxHistorySize;correlationTimeout;maxEventsPerCorrelation;initialized=!1;async initialize(){if(!this.initialized){for(let t of m){let e=this.eventBus.subscribeToChannel(t,async i=>{await this.handleIncomingEvent(i)});this.domainSubscriptions.set(t,e)}this.eventBus.subscribe("*",async t=>{m.includes(t.source)||await this.handleIncomingEvent(t)}),this.initialized=!0}}subscribeToDoamin(t,e){let i=`sub_domain_${a()}`;return this.subscriptions.set(i,{id:i,type:"domain",filter:t,handler:e,active:!0}),i}subscribeToEventType(t,e){let i=`sub_type_${a()}`;return this.subscriptions.set(i,{id:i,type:"eventType",filter:t,handler:e,active:!0}),i}unsubscribe(t){let e=this.subscriptions.get(t);return e?(e.active=!1,this.subscriptions.delete(t),!0):!1}async route(t){this.addToHistory(t),t.correlationId&&this.trackCorrelation(t);let i=this.findMatchingSubscriptions(t).map(async o=>{try{await o.handler(t)}catch(n){console.error(`Error in subscription handler ${o.id}:`,n instanceof Error?n.message:n)}}),r=await this.applyRoutes(t);await Promise.allSettled([...i,...r])}getCorrelation(t){let e=this.correlations.get(t);if(e)return{correlationId:e.correlationId,events:[...e.events],domains:new Set(e.domains),startedAt:e.startedAt,lastEventAt:e.lastEventAt,complete:e.complete}}trackCorrelation(t){if(!t.correlationId)return;let e=this.correlations.get(t.correlationId);e||(e={correlationId:t.correlationId,events:[],domains:new Set,startedAt:t.timestamp,lastEventAt:t.timestamp,complete:!1,timeout:null},this.correlations.set(t.correlationId,e)),e.events.length<this.maxEventsPerCorrelation&&(e.events.push(t),e.domains.add(t.source),e.lastEventAt=t.timestamp),e.timeout&&clearTimeout(e.timeout),e.timeout=setTimeout(()=>{e.complete=!0,e.timeout=null},this.correlationTimeout)}aggregate(t,e){let i=this.eventHistory.toArray().filter(s=>s.timestamp>=t&&s.timestamp<=e),r=new Map,o=new Map;for(let s of i)r.set(s.type,(r.get(s.type)??0)+1),o.set(s.source,(o.get(s.source)??0)+1);let n={totalEvents:i.length,uniqueEventTypes:r.size,uniqueDomains:o.size,eventsPerSecond:i.length>0?i.length/((e.getTime()-t.getTime())/1e3):0};return{id:a(),windowStart:t,windowEnd:e,events:i,countByType:r,countByDomain:o,metrics:n}}getHistory(t){let e=this.eventHistory.toArray();return t&&(t.eventTypes?.length&&(e=e.filter(i=>t.eventTypes.includes(i.type))),t.domains?.length&&(e=e.filter(i=>t.domains.includes(i.source))),t.fromTimestamp&&(e=e.filter(i=>i.timestamp>=t.fromTimestamp)),t.toTimestamp&&(e=e.filter(i=>i.timestamp<=t.toTimestamp)),t.limit&&(e=e.slice(-t.limit))),e}addRoute(t){let e=t.priority??0,i=this.routes.findIndex(r=>(r.priority??0)<e);i===-1?this.routes.push(t):this.routes.splice(i,0,t)}removeRoute(t,e){let i=this.routes.findIndex(r=>r.eventPattern===t&&(e===void 0||r.source===e));return i!==-1?(this.routes.splice(i,1),!0):!1}async dispose(){this.subscriptions.clear();for(let t of this.domainSubscriptions.values())t.unsubscribe();this.domainSubscriptions.clear();for(let t of this.correlations.values())t.timeout&&clearTimeout(t.timeout);this.correlations.clear(),this.eventHistory.clear(),this.initialized=!1}async handleIncomingEvent(t){await this.route(t)}findMatchingSubscriptions(t){let e=[];for(let i of this.subscriptions.values())i.active&&(i.type==="domain"&&i.filter===t.source||i.type==="eventType"&&this.matchEventType(t.type,i.filter))&&e.push(i);return e}matchEventType(t,e){if(e==="*")return!0;let i=e.replace(/\\/g,"\\\\").replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${i}$`).test(t)}async applyRoutes(t){let e=[];for(let i of this.routes){if(!(i.source==="*"||i.source===t.source||Array.isArray(i.source)&&i.source.includes(t.source))||!this.matchEventType(t.type,i.eventPattern)||i.filter&&!i.filter(t))continue;let o=i.transform?i.transform(t):t;for(let n of i.targets)n!==t.source&&e.push(this.eventBus.publish({...o,id:a(),correlationId:t.correlationId??t.id}))}return e}addToHistory(t){this.eventHistory.push(t)}};function y(c,t){return new u(c,t)}export{u as a,y as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
2
+ import{a as l}from"./chunk-VLUJWI56.js";import{a as m}from"./chunk-GTPZVLL6.js";import{i as a}from"./chunk-ZIBW7CB4.js";var u=class{constructor(t,e){this.eventBus=t;this.maxHistorySize=e?.maxHistorySize??1e4,this.eventHistory=new l(this.maxHistorySize),this.correlationTimeout=e?.correlationTimeout??6e4,this.maxEventsPerCorrelation=e?.maxEventsPerCorrelation??100}eventBus;subscriptions=new Map;correlations=new Map;eventHistory;routes=[];domainSubscriptions=new Map;maxHistorySize;correlationTimeout;maxEventsPerCorrelation;initialized=!1;async initialize(){if(!this.initialized){for(let t of m){let e=this.eventBus.subscribeToChannel(t,async i=>{await this.handleIncomingEvent(i)});this.domainSubscriptions.set(t,e)}this.eventBus.subscribe("*",async t=>{m.includes(t.source)||await this.handleIncomingEvent(t)}),this.initialized=!0}}subscribeToDoamin(t,e){let i=`sub_domain_${a()}`;return this.subscriptions.set(i,{id:i,type:"domain",filter:t,handler:e,active:!0}),i}subscribeToEventType(t,e){let i=`sub_type_${a()}`;return this.subscriptions.set(i,{id:i,type:"eventType",filter:t,handler:e,active:!0}),i}unsubscribe(t){let e=this.subscriptions.get(t);return e?(e.active=!1,this.subscriptions.delete(t),!0):!1}async route(t){this.addToHistory(t),t.correlationId&&this.trackCorrelation(t);let i=this.findMatchingSubscriptions(t).map(async o=>{try{await o.handler(t)}catch(n){console.error(`Error in subscription handler ${o.id}:`,n instanceof Error?n.message:n)}}),r=await this.applyRoutes(t);await Promise.allSettled([...i,...r])}getCorrelation(t){let e=this.correlations.get(t);if(e)return{correlationId:e.correlationId,events:[...e.events],domains:new Set(e.domains),startedAt:e.startedAt,lastEventAt:e.lastEventAt,complete:e.complete}}trackCorrelation(t){if(!t.correlationId)return;let e=this.correlations.get(t.correlationId);e||(e={correlationId:t.correlationId,events:[],domains:new Set,startedAt:t.timestamp,lastEventAt:t.timestamp,complete:!1,timeout:null},this.correlations.set(t.correlationId,e)),e.events.length<this.maxEventsPerCorrelation&&(e.events.push(t),e.domains.add(t.source),e.lastEventAt=t.timestamp),e.timeout&&clearTimeout(e.timeout),e.timeout=setTimeout(()=>{e.complete=!0,e.timeout=null},this.correlationTimeout)}aggregate(t,e){let i=this.eventHistory.toArray().filter(s=>s.timestamp>=t&&s.timestamp<=e),r=new Map,o=new Map;for(let s of i)r.set(s.type,(r.get(s.type)??0)+1),o.set(s.source,(o.get(s.source)??0)+1);let n={totalEvents:i.length,uniqueEventTypes:r.size,uniqueDomains:o.size,eventsPerSecond:i.length>0?i.length/((e.getTime()-t.getTime())/1e3):0};return{id:a(),windowStart:t,windowEnd:e,events:i,countByType:r,countByDomain:o,metrics:n}}getHistory(t){let e=this.eventHistory.toArray();return t&&(t.eventTypes?.length&&(e=e.filter(i=>t.eventTypes.includes(i.type))),t.domains?.length&&(e=e.filter(i=>t.domains.includes(i.source))),t.fromTimestamp&&(e=e.filter(i=>i.timestamp>=t.fromTimestamp)),t.toTimestamp&&(e=e.filter(i=>i.timestamp<=t.toTimestamp)),t.limit&&(e=e.slice(-t.limit))),e}addRoute(t){let e=t.priority??0,i=this.routes.findIndex(r=>(r.priority??0)<e);i===-1?this.routes.push(t):this.routes.splice(i,0,t)}removeRoute(t,e){let i=this.routes.findIndex(r=>r.eventPattern===t&&(e===void 0||r.source===e));return i!==-1?(this.routes.splice(i,1),!0):!1}async dispose(){this.subscriptions.clear();for(let t of this.domainSubscriptions.values())t.unsubscribe();this.domainSubscriptions.clear();for(let t of this.correlations.values())t.timeout&&clearTimeout(t.timeout);this.correlations.clear(),this.eventHistory.clear(),this.initialized=!1}async handleIncomingEvent(t){await this.route(t)}findMatchingSubscriptions(t){let e=[];for(let i of this.subscriptions.values())i.active&&(i.type==="domain"&&i.filter===t.source||i.type==="eventType"&&this.matchEventType(t.type,i.filter))&&e.push(i);return e}matchEventType(t,e){if(e==="*")return!0;let i=e.replace(/\\/g,"\\\\").replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${i}$`).test(t)}async applyRoutes(t){let e=[];for(let i of this.routes){if(!(i.source==="*"||i.source===t.source||Array.isArray(i.source)&&i.source.includes(t.source))||!this.matchEventType(t.type,i.eventPattern)||i.filter&&!i.filter(t))continue;let o=i.transform?i.transform(t):t;for(let n of i.targets)n!==t.source&&e.push(this.eventBus.publish({...o,id:a(),correlationId:t.correlationId??t.id}))}return e}addToHistory(t){this.eventHistory.push(t)}};function y(c,t){return new u(c,t)}export{u as a,y as b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.0");process.exit(0)}
2
- import{b as k,c as p}from"./chunk-NUQBJGGF.js";p();import{generateKeyPairSync as g,createPrivateKey as v,createPublicKey as I,sign as m,verify as D,createHash as b}from"crypto";import{existsSync as d,mkdirSync as P,writeFileSync as y,readFileSync as o,readdirSync as w}from"fs";import{join as n}from"path";var f=class{keys=new Map;activeKeyId=null;keyDir;constructor(e={}){this.keyDir=e.keyDir??null,this.keyDir&&this.loadFromDisk(),e.autoGenerate!==!1&&this.keys.size===0&&this.generateKeyPair()}generateKeyPair(){let{publicKey:e,privateKey:i}=g("ed25519"),r=e.export({type:"spki",format:"der"}),t=b("sha256").update(r).digest("hex").slice(0,16),s={keyId:t,publicKey:e,privateKey:i,createdAt:new Date().toISOString(),retired:!1};return this.keys.set(t,s),this.activeKeyId=t,this.keyDir&&(this.saveKeyPairToDisk(s),this.saveActiveKeyId()),{keyId:t,publicKey:r}}sign(e,i){let r=i??this.activeKeyId;if(!r)throw new Error("No active key available for signing");let t=this.keys.get(r);if(!t)throw new Error(`Key not found: ${r}`);return{signature:m(null,e,t.privateKey),keyId:r}}verify(e,i,r){let t=this.keys.get(r);if(!t)return!1;try{return D(null,e,t.publicKey,i)}catch{return!1}}rotateKey(){let e=this.activeKeyId;if(!e)throw new Error("No active key to rotate");let i=this.keys.get(e);i&&(i.retired=!0,this.keyDir&&this.saveKeyPairToDisk(i));let{keyId:r}=this.generateKeyPair();return{oldKeyId:e,newKeyId:r}}getActiveKeyId(){if(!this.activeKeyId)throw new Error("No active key");return this.activeKeyId}hasKey(e){return this.keys.has(e)}getKeyCount(){return this.keys.size}saveKeyPairToDisk(e){if(!this.keyDir)return;d(this.keyDir)||P(this.keyDir,{recursive:!0});let i=n(this.keyDir,e.keyId);y(`${i}.pub.pem`,e.publicKey.export({type:"spki",format:"pem"}),"utf-8"),y(`${i}.key.pem`,e.privateKey.export({type:"pkcs8",format:"pem"}),{encoding:"utf-8",mode:384}),y(`${i}.meta.json`,JSON.stringify({keyId:e.keyId,createdAt:e.createdAt,retired:e.retired}),"utf-8")}saveActiveKeyId(){!this.keyDir||!this.activeKeyId||y(n(this.keyDir,"active-key-id"),this.activeKeyId,"utf-8")}loadFromDisk(){if(!this.keyDir||!d(this.keyDir))return;let i=w(this.keyDir).filter(t=>t.endsWith(".meta.json"));for(let t of i)try{let s=JSON.parse(o(n(this.keyDir,t),"utf-8")),a=n(this.keyDir,s.keyId),l=o(`${a}.pub.pem`,"utf-8"),K=o(`${a}.key.pem`,"utf-8"),h={keyId:s.keyId,publicKey:I(l),privateKey:v(K),createdAt:s.createdAt,retired:s.retired};this.keys.set(s.keyId,h)}catch{}let r=n(this.keyDir,"active-key-id");if(d(r)){let t=o(r,"utf-8").trim();this.keys.has(t)&&(this.activeKeyId=t)}if(!this.activeKeyId){let t=[...this.keys.values()].filter(s=>!s.retired).sort((s,a)=>a.createdAt.localeCompare(s.createdAt));t.length>0&&(this.activeKeyId=t[0].keyId)}}},c=null;function F(){if(!c){let u=n(k(),".agentic-qe","witness-keys");c=new f({keyDir:u})}return c}function O(){c=null}export{f as a,F as b,O as c};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
2
+ import{b as k,c as p}from"./chunk-YBPCBFEE.js";p();import{generateKeyPairSync as g,createPrivateKey as v,createPublicKey as I,sign as m,verify as D,createHash as b}from"crypto";import{existsSync as d,mkdirSync as P,writeFileSync as y,readFileSync as o,readdirSync as w}from"fs";import{join as n}from"path";var f=class{keys=new Map;activeKeyId=null;keyDir;constructor(e={}){this.keyDir=e.keyDir??null,this.keyDir&&this.loadFromDisk(),e.autoGenerate!==!1&&this.keys.size===0&&this.generateKeyPair()}generateKeyPair(){let{publicKey:e,privateKey:i}=g("ed25519"),r=e.export({type:"spki",format:"der"}),t=b("sha256").update(r).digest("hex").slice(0,16),s={keyId:t,publicKey:e,privateKey:i,createdAt:new Date().toISOString(),retired:!1};return this.keys.set(t,s),this.activeKeyId=t,this.keyDir&&(this.saveKeyPairToDisk(s),this.saveActiveKeyId()),{keyId:t,publicKey:r}}sign(e,i){let r=i??this.activeKeyId;if(!r)throw new Error("No active key available for signing");let t=this.keys.get(r);if(!t)throw new Error(`Key not found: ${r}`);return{signature:m(null,e,t.privateKey),keyId:r}}verify(e,i,r){let t=this.keys.get(r);if(!t)return!1;try{return D(null,e,t.publicKey,i)}catch{return!1}}rotateKey(){let e=this.activeKeyId;if(!e)throw new Error("No active key to rotate");let i=this.keys.get(e);i&&(i.retired=!0,this.keyDir&&this.saveKeyPairToDisk(i));let{keyId:r}=this.generateKeyPair();return{oldKeyId:e,newKeyId:r}}getActiveKeyId(){if(!this.activeKeyId)throw new Error("No active key");return this.activeKeyId}hasKey(e){return this.keys.has(e)}getKeyCount(){return this.keys.size}saveKeyPairToDisk(e){if(!this.keyDir)return;d(this.keyDir)||P(this.keyDir,{recursive:!0});let i=n(this.keyDir,e.keyId);y(`${i}.pub.pem`,e.publicKey.export({type:"spki",format:"pem"}),"utf-8"),y(`${i}.key.pem`,e.privateKey.export({type:"pkcs8",format:"pem"}),{encoding:"utf-8",mode:384}),y(`${i}.meta.json`,JSON.stringify({keyId:e.keyId,createdAt:e.createdAt,retired:e.retired}),"utf-8")}saveActiveKeyId(){!this.keyDir||!this.activeKeyId||y(n(this.keyDir,"active-key-id"),this.activeKeyId,"utf-8")}loadFromDisk(){if(!this.keyDir||!d(this.keyDir))return;let i=w(this.keyDir).filter(t=>t.endsWith(".meta.json"));for(let t of i)try{let s=JSON.parse(o(n(this.keyDir,t),"utf-8")),a=n(this.keyDir,s.keyId),l=o(`${a}.pub.pem`,"utf-8"),K=o(`${a}.key.pem`,"utf-8"),h={keyId:s.keyId,publicKey:I(l),privateKey:v(K),createdAt:s.createdAt,retired:s.retired};this.keys.set(s.keyId,h)}catch{}let r=n(this.keyDir,"active-key-id");if(d(r)){let t=o(r,"utf-8").trim();this.keys.has(t)&&(this.activeKeyId=t)}if(!this.activeKeyId){let t=[...this.keys.values()].filter(s=>!s.retired).sort((s,a)=>a.createdAt.localeCompare(s.createdAt));t.length>0&&(this.activeKeyId=t[0].keyId)}}},c=null;function F(){if(!c){let u=n(k(),".agentic-qe","witness-keys");c=new f({keyDir:u})}return c}function O(){c=null}export{f as a,F as b,O as c};
@@ -1 +1 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.0");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.0");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
2
2
  import{readFileSync as O,existsSync as x,readdirSync as A}from"fs";import{join as y,basename as v}from"path";function m(r){let e=[];if(!r||typeof r!="object")return e.push("Overlay must be a non-null object"),e;let t=r;if((!t.agent||typeof t.agent!="string")&&e.push('Overlay must have a string "agent" field'),t.replace!==void 0)if(typeof t.replace!="object"||t.replace===null)e.push('"replace" must be an object');else{let n=t.replace;n.description!==void 0&&typeof n.description!="string"&&e.push('"replace.description" must be a string'),n.domains!==void 0&&!Array.isArray(n.domains)&&e.push('"replace.domains" must be an array'),n.complexity!==void 0&&typeof n.complexity!="string"&&e.push('"replace.complexity" must be a string')}if(t.append!==void 0)if(typeof t.append!="object"||t.append===null)e.push('"append" must be an object');else{let n=t.append;n.instructions!==void 0&&typeof n.instructions!="string"&&e.push('"append.instructions" must be a string'),n.capabilities!==void 0&&!Array.isArray(n.capabilities)&&e.push('"append.capabilities" must be an array'),n.tags!==void 0&&!Array.isArray(n.tags)&&e.push('"append.tags" must be an array')}if(t.config!==void 0)if(typeof t.config!="object"||t.config===null)e.push('"config" must be an object');else{let n=t.config;n.minimumFindings!==void 0&&typeof n.minimumFindings!="number"&&e.push('"config.minimumFindings" must be a number'),n.maxParallelAgents!==void 0&&typeof n.maxParallelAgents!="number"&&e.push('"config.maxParallelAgents" must be a number'),n.preferredFrameworks!==void 0&&!Array.isArray(n.preferredFrameworks)&&e.push('"config.preferredFrameworks" must be an array'),n.needsContext!==void 0&&typeof n.needsContext!="boolean"&&e.push('"config.needsContext" must be a boolean')}return e}var w=".claude/agent-overrides";function $(r){let e={},t=r.split(`
3
3
  `),n=null,i=null,s=null,a=null;for(let o of t){let l=o.replace(/\r$/,"");if(l.trim().startsWith("#")||l.trim()==="")continue;let u=l.length-l.trimStart().length,g=l.trim();if(g.startsWith("- ")){let c=g.slice(2).trim().replace(/^["']|["']$/g,"");s&&s.push(c);continue}if(s&&a){if(i&&n){let c=e[n]||{};c[a]=s,e[n]=c}else if(n){let c=e[n]||{};c[a]=s,e[n]=c}s=null,a=null}let f=g.match(/^(\w[\w.-]*)\s*:\s*(.*)$/);if(!f)continue;let[,p,b]=f,d=b.trim().replace(/^["']|["']$/g,"");if(u===0)d===""||d===void 0?(n=p,i=null,e[p]||(e[p]={})):(e[p]=h(d),n=null,i=null);else if(u<=4&&n)if(d===""||d===void 0)i=p,s=[],a=p;else{let c=e[n]||{};c[p]=h(d),e[n]=c}}if(s&&a&&n){let o=e[n]||{};o[a]=s,e[n]=o}return e}function h(r){if(r==="true")return!0;if(r==="false")return!1;if(r==="null")return null;let e=Number(r);return!isNaN(e)&&r!==""?e:r}function N(r){let e=y(r,w),t={overlays:[],warnings:[],errors:[]};if(!x(e))return t;let n;try{n=A(e).filter(i=>(i.endsWith(".yaml")||i.endsWith(".yml"))&&!i.startsWith("_"))}catch(i){return t.errors.push(`Failed to read overrides directory: ${i.message}`),t}for(let i of n){let s=y(e,i);try{let a=O(s,"utf-8"),o=$(a);if(!o.agent){let u=v(i).replace(/\.(override|customize)\.(yaml|yml)$/,"");o.agent=u}let l=m(o);if(l.length>0){t.warnings.push(`Overlay ${i} has validation issues: ${l.join("; ")}. Loading without overlay.`);continue}t.overlays.push(o)}catch(a){t.warnings.push(`Failed to parse overlay ${i}: ${a.message}. Agent loads without overlay.`)}}return t}function E(r,e){let t=r,n={agentName:e.agent,overlayFile:`${e.agent}.override.yaml`,replacedFields:[],appendedFields:[],configOverrides:[]};if(e.replace){if(e.replace.description){let i=/^(description:\s*).+$/m;i.test(t)&&(t=t.replace(i,`$1${e.replace.description}`),n.replacedFields.push("description"))}if(e.replace.domains){let i=/^(domain:\s*).+$/m;i.test(t)&&(t=t.replace(i,`$1${e.replace.domains.join(", ")}`),n.replacedFields.push("domains"))}if(e.replace.complexity){let i=/^(complexity:\s*).+$/m;i.test(t)&&(t=t.replace(i,`$1${e.replace.complexity}`),n.replacedFields.push("complexity"))}}if(e.append){if(e.append.instructions&&(t+=`
4
4
 
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.0");process.exit(0)}
2
- import{a as g}from"./chunk-IYDYJ33J.js";import{b as p,c}from"./chunk-QI4CGJNK.js";import{a as x,b as f,c as w}from"./chunk-CYL2FV23.js";import{i as v}from"./chunk-E3B5XTXJ.js";w();var l={ProtocolStarted:"coordination.ProtocolStarted",ProtocolCompleted:"coordination.ProtocolCompleted",ProtocolFailed:"coordination.ProtocolFailed",ProtocolCancelled:"coordination.ProtocolCancelled",ActionStarted:"coordination.ActionStarted",ActionCompleted:"coordination.ActionCompleted",ActionFailed:"coordination.ActionFailed"},E=class{constructor(e,t,o){this.eventBus=e;this.memory=t;this.getDomainAPI=o}eventBus;memory;getDomainAPI;protocols=new Map;executions=new Map;scheduledProtocols=new Map;schedulerRunning=!1;registerProtocol(e){this.protocols.set(e.id,e),e.schedule.type==="event"&&e.enabled&&this.setupEventTriggers(e),(e.schedule.type==="cron"||e.schedule.type==="interval")&&e.enabled&&this.scheduleProtocol(e)}unregisterProtocol(e){if(!this.protocols.get(e))return!1;let o=this.scheduledProtocols.get(e);return o?.intervalId&&clearInterval(o.intervalId),this.scheduledProtocols.delete(e),this.protocols.delete(e),!0}getProtocol(e){return this.protocols.get(e)}listProtocols(){return Array.from(this.protocols.values())}async execute(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}async executeOnEvent(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,void 0,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}getExecution(e){let t=this.executions.get(e);if(t)return this.toImmutableExecution(t.execution)}listActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.execution.status==="running"||e.execution.status==="paused").map(e=>this.toImmutableExecution(e.execution))}async cancelExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"&&t.execution.status!=="paused"?c(new Error(`Cannot cancel execution in status: ${t.execution.status}`)):(t.cancelled=!0,t.execution.status="cancelled",t.execution.completedAt=new Date,await this.publishEvent(l.ProtocolCancelled,{executionId:e,protocolId:t.protocol.id}),p(void 0)):c(new Error(`Execution not found: ${e}`))}async pauseExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"?c(new Error(`Cannot pause execution in status: ${t.execution.status}`)):(t.paused=!0,t.execution.status="paused",p(void 0)):c(new Error(`Execution not found: ${e}`))}async resumeExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="paused"?c(new Error(`Cannot resume execution in status: ${t.execution.status}`)):(t.paused=!1,t.execution.status="running",p(void 0)):c(new Error(`Execution not found: ${e}`))}startScheduler(){if(!this.schedulerRunning){this.schedulerRunning=!0;for(let e of this.protocols.values())e.enabled&&(e.schedule.type==="interval"||e.schedule.type==="cron")&&this.scheduleProtocol(e)}}stopScheduler(){this.schedulerRunning=!1;for(let e of this.scheduledProtocols.values())e.intervalId&&(clearInterval(e.intervalId),e.intervalId=void 0)}async dispose(){this.stopScheduler(),this.protocols.clear(),this.executions.clear(),this.scheduledProtocols.clear()}async executeProtocol(e,t,o){let r=v(),a=o?.correlationId??r,n={executionId:r,protocolId:e.id,status:"running",participants:[...e.participants],results:new Map,startedAt:new Date,correlationId:a,triggeredBy:o},u={execution:n,protocol:e,params:t,actionResults:new Map,cancelled:!1,paused:!1};this.executions.set(r,u),await this.publishEvent(l.ProtocolStarted,{executionId:r,protocolId:e.id,participants:e.participants},a);try{await this.executeActions(u);let i=Array.from(u.actionResults.values()).some(s=>s.status==="failed");return u.cancelled?n.status="cancelled":i?(n.status="failed",await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,failedActions:Array.from(u.actionResults.values()).filter(s=>s.status==="failed").map(s=>s.actionId)},a)):(n.status="completed",await this.publishEvent(l.ProtocolCompleted,{executionId:r,protocolId:e.id,duration:Date.now()-n.startedAt.getTime()},a)),n.completedAt=new Date,n.results=u.actionResults,await this.storeExecutionHistory(n),p(this.toImmutableExecution(n))}catch(i){return n.status="failed",n.completedAt=new Date,await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,error:x(i)},a),c(f(i))}}async executeActions(e){let{protocol:t,actionResults:o}=e,r=new Set(t.actions.map(n=>n.id)),a=new Set;for(;r.size>0&&!e.cancelled;){for(;e.paused&&!e.cancelled;)await this.sleep(100);if(e.cancelled)break;let n=t.actions.filter(i=>r.has(i.id)&&this.dependenciesSatisfied(i,a));if(n.length===0&&r.size>0)throw new Error(`Deadlock detected: actions ${Array.from(r).join(", ")} cannot proceed`);let u=await Promise.allSettled(n.map(i=>this.executeAction(i,e)));for(let i=0;i<n.length;i++){let s=n[i],d=u[i],m;d.status==="fulfilled"?m=d.value:m={actionId:s.id,status:"failed",error:d.reason instanceof Error?d.reason.message:String(d.reason)},o.set(s.id,m),r.delete(s.id),m.status==="completed"&&a.add(s.id)}}for(let n of r)o.set(n,{actionId:n,status:e.cancelled?"cancelled":"skipped"})}async executeAction(e,t){let o=new Date;await this.publishEvent(l.ActionStarted,{executionId:t.execution.executionId,actionId:e.id,actionName:e.name,targetDomain:e.targetDomain},t.execution.correlationId);let r=0,a=e.retry?.maxAttempts??1,n;for(;r<a;){r++;try{let i=this.getDomainAPI(e.targetDomain);if(!i)throw new Error(`Domain API not available: ${e.targetDomain}`);let s=i[e.method];if(typeof s!="function")throw new Error(`Method ${e.method} not found on domain ${e.targetDomain}`);let d={...e.params,...t.params},m=await this.executeWithTimeout(s.bind(i)(d),e.timeout??3e4),h=new Date;return await this.publishEvent(l.ActionCompleted,{executionId:t.execution.executionId,actionId:e.id,duration:h.getTime()-o.getTime()},t.execution.correlationId),{actionId:e.id,status:"completed",startedAt:o,completedAt:h,duration:h.getTime()-o.getTime(),result:m,retryAttempts:r>1?r-1:void 0}}catch(i){if(n=f(i),r<a&&e.retry){let s=e.retry.backoffMs*Math.pow(e.retry.backoffMultiplier??2,r-1);await this.sleep(s)}}}let u=new Date;return await this.publishEvent(l.ActionFailed,{executionId:t.execution.executionId,actionId:e.id,error:n?.message??"Unknown error",attempts:r},t.execution.correlationId),{actionId:e.id,status:"failed",startedAt:o,completedAt:u,duration:u.getTime()-o.getTime(),error:n?.message??"Unknown error",retryAttempts:r>1?r-1:void 0}}dependenciesSatisfied(e,t){return!e.dependsOn||e.dependsOn.length===0?!0:e.dependsOn.every(o=>t.has(o))}async executeWithTimeout(e,t){return Promise.race([e,new Promise((o,r)=>setTimeout(()=>r(new Error("Action timeout")),t))])}setupEventTriggers(e){if(e.schedule.type==="event")for(let t of e.schedule.triggerEvents)this.eventBus.subscribe(t,async o=>{await this.executeOnEvent(e.id,o)})}scheduleProtocol(e){if(e.schedule.type==="interval"){let t={protocolId:e.id,schedule:e.schedule};t.intervalId=setInterval(async()=>{this.schedulerRunning&&await this.execute(e.id)},e.schedule.intervalMs),this.scheduledProtocols.set(e.id,t)}}async storeExecutionHistory(e){let t=`protocol-execution:${e.executionId}`;await this.memory.set(t,{...e,results:Object.fromEntries(e.results)},{namespace:"coordination",ttl:86400})}toImmutableExecution(e){return{executionId:e.executionId,protocolId:e.protocolId,status:e.status,participants:[...e.participants],results:new Map(e.results),startedAt:e.startedAt,completedAt:e.completedAt,correlationId:e.correlationId,triggeredBy:e.triggeredBy}}async publishEvent(e,t,o){let r=g(e,"learning-optimization",t,o);await this.eventBus.publish(r)}sleep(e){return new Promise(t=>setTimeout(t,e))}};function S(P,e,t){return new E(P,e,t)}export{E as a,S as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
2
+ import{a as g}from"./chunk-LTKNCYMO.js";import{b as p,c}from"./chunk-GTPZVLL6.js";import{a as x,b as f,c as w}from"./chunk-AYYDO52G.js";import{i as v}from"./chunk-ZIBW7CB4.js";w();var l={ProtocolStarted:"coordination.ProtocolStarted",ProtocolCompleted:"coordination.ProtocolCompleted",ProtocolFailed:"coordination.ProtocolFailed",ProtocolCancelled:"coordination.ProtocolCancelled",ActionStarted:"coordination.ActionStarted",ActionCompleted:"coordination.ActionCompleted",ActionFailed:"coordination.ActionFailed"},E=class{constructor(e,t,o){this.eventBus=e;this.memory=t;this.getDomainAPI=o}eventBus;memory;getDomainAPI;protocols=new Map;executions=new Map;scheduledProtocols=new Map;schedulerRunning=!1;registerProtocol(e){this.protocols.set(e.id,e),e.schedule.type==="event"&&e.enabled&&this.setupEventTriggers(e),(e.schedule.type==="cron"||e.schedule.type==="interval")&&e.enabled&&this.scheduleProtocol(e)}unregisterProtocol(e){if(!this.protocols.get(e))return!1;let o=this.scheduledProtocols.get(e);return o?.intervalId&&clearInterval(o.intervalId),this.scheduledProtocols.delete(e),this.protocols.delete(e),!0}getProtocol(e){return this.protocols.get(e)}listProtocols(){return Array.from(this.protocols.values())}async execute(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}async executeOnEvent(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,void 0,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}getExecution(e){let t=this.executions.get(e);if(t)return this.toImmutableExecution(t.execution)}listActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.execution.status==="running"||e.execution.status==="paused").map(e=>this.toImmutableExecution(e.execution))}async cancelExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"&&t.execution.status!=="paused"?c(new Error(`Cannot cancel execution in status: ${t.execution.status}`)):(t.cancelled=!0,t.execution.status="cancelled",t.execution.completedAt=new Date,await this.publishEvent(l.ProtocolCancelled,{executionId:e,protocolId:t.protocol.id}),p(void 0)):c(new Error(`Execution not found: ${e}`))}async pauseExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"?c(new Error(`Cannot pause execution in status: ${t.execution.status}`)):(t.paused=!0,t.execution.status="paused",p(void 0)):c(new Error(`Execution not found: ${e}`))}async resumeExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="paused"?c(new Error(`Cannot resume execution in status: ${t.execution.status}`)):(t.paused=!1,t.execution.status="running",p(void 0)):c(new Error(`Execution not found: ${e}`))}startScheduler(){if(!this.schedulerRunning){this.schedulerRunning=!0;for(let e of this.protocols.values())e.enabled&&(e.schedule.type==="interval"||e.schedule.type==="cron")&&this.scheduleProtocol(e)}}stopScheduler(){this.schedulerRunning=!1;for(let e of this.scheduledProtocols.values())e.intervalId&&(clearInterval(e.intervalId),e.intervalId=void 0)}async dispose(){this.stopScheduler(),this.protocols.clear(),this.executions.clear(),this.scheduledProtocols.clear()}async executeProtocol(e,t,o){let r=v(),a=o?.correlationId??r,n={executionId:r,protocolId:e.id,status:"running",participants:[...e.participants],results:new Map,startedAt:new Date,correlationId:a,triggeredBy:o},u={execution:n,protocol:e,params:t,actionResults:new Map,cancelled:!1,paused:!1};this.executions.set(r,u),await this.publishEvent(l.ProtocolStarted,{executionId:r,protocolId:e.id,participants:e.participants},a);try{await this.executeActions(u);let i=Array.from(u.actionResults.values()).some(s=>s.status==="failed");return u.cancelled?n.status="cancelled":i?(n.status="failed",await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,failedActions:Array.from(u.actionResults.values()).filter(s=>s.status==="failed").map(s=>s.actionId)},a)):(n.status="completed",await this.publishEvent(l.ProtocolCompleted,{executionId:r,protocolId:e.id,duration:Date.now()-n.startedAt.getTime()},a)),n.completedAt=new Date,n.results=u.actionResults,await this.storeExecutionHistory(n),p(this.toImmutableExecution(n))}catch(i){return n.status="failed",n.completedAt=new Date,await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,error:x(i)},a),c(f(i))}}async executeActions(e){let{protocol:t,actionResults:o}=e,r=new Set(t.actions.map(n=>n.id)),a=new Set;for(;r.size>0&&!e.cancelled;){for(;e.paused&&!e.cancelled;)await this.sleep(100);if(e.cancelled)break;let n=t.actions.filter(i=>r.has(i.id)&&this.dependenciesSatisfied(i,a));if(n.length===0&&r.size>0)throw new Error(`Deadlock detected: actions ${Array.from(r).join(", ")} cannot proceed`);let u=await Promise.allSettled(n.map(i=>this.executeAction(i,e)));for(let i=0;i<n.length;i++){let s=n[i],d=u[i],m;d.status==="fulfilled"?m=d.value:m={actionId:s.id,status:"failed",error:d.reason instanceof Error?d.reason.message:String(d.reason)},o.set(s.id,m),r.delete(s.id),m.status==="completed"&&a.add(s.id)}}for(let n of r)o.set(n,{actionId:n,status:e.cancelled?"cancelled":"skipped"})}async executeAction(e,t){let o=new Date;await this.publishEvent(l.ActionStarted,{executionId:t.execution.executionId,actionId:e.id,actionName:e.name,targetDomain:e.targetDomain},t.execution.correlationId);let r=0,a=e.retry?.maxAttempts??1,n;for(;r<a;){r++;try{let i=this.getDomainAPI(e.targetDomain);if(!i)throw new Error(`Domain API not available: ${e.targetDomain}`);let s=i[e.method];if(typeof s!="function")throw new Error(`Method ${e.method} not found on domain ${e.targetDomain}`);let d={...e.params,...t.params},m=await this.executeWithTimeout(s.bind(i)(d),e.timeout??3e4),h=new Date;return await this.publishEvent(l.ActionCompleted,{executionId:t.execution.executionId,actionId:e.id,duration:h.getTime()-o.getTime()},t.execution.correlationId),{actionId:e.id,status:"completed",startedAt:o,completedAt:h,duration:h.getTime()-o.getTime(),result:m,retryAttempts:r>1?r-1:void 0}}catch(i){if(n=f(i),r<a&&e.retry){let s=e.retry.backoffMs*Math.pow(e.retry.backoffMultiplier??2,r-1);await this.sleep(s)}}}let u=new Date;return await this.publishEvent(l.ActionFailed,{executionId:t.execution.executionId,actionId:e.id,error:n?.message??"Unknown error",attempts:r},t.execution.correlationId),{actionId:e.id,status:"failed",startedAt:o,completedAt:u,duration:u.getTime()-o.getTime(),error:n?.message??"Unknown error",retryAttempts:r>1?r-1:void 0}}dependenciesSatisfied(e,t){return!e.dependsOn||e.dependsOn.length===0?!0:e.dependsOn.every(o=>t.has(o))}async executeWithTimeout(e,t){return Promise.race([e,new Promise((o,r)=>setTimeout(()=>r(new Error("Action timeout")),t))])}setupEventTriggers(e){if(e.schedule.type==="event")for(let t of e.schedule.triggerEvents)this.eventBus.subscribe(t,async o=>{await this.executeOnEvent(e.id,o)})}scheduleProtocol(e){if(e.schedule.type==="interval"){let t={protocolId:e.id,schedule:e.schedule};t.intervalId=setInterval(async()=>{this.schedulerRunning&&await this.execute(e.id)},e.schedule.intervalMs),this.scheduledProtocols.set(e.id,t)}}async storeExecutionHistory(e){let t=`protocol-execution:${e.executionId}`;await this.memory.set(t,{...e,results:Object.fromEntries(e.results)},{namespace:"coordination",ttl:86400})}toImmutableExecution(e){return{executionId:e.executionId,protocolId:e.protocolId,status:e.status,participants:[...e.participants],results:new Map(e.results),startedAt:e.startedAt,completedAt:e.completedAt,correlationId:e.correlationId,triggeredBy:e.triggeredBy}}async publishEvent(e,t,o){let r=g(e,"learning-optimization",t,o);await this.eventBus.publish(r)}sleep(e){return new Promise(t=>setTimeout(t,e))}};function S(P,e,t){return new E(P,e,t)}export{E as a,S as b};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.0");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
2
2
  var i={copilot:{id:"copilot",name:"GitHub Copilot",configPath:".vscode/mcp.json",configFormat:"json",configKey:"servers",rulesPath:".github/copilot-instructions.md",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},cursor:{id:"cursor",name:"Cursor",configPath:".cursor/mcp.json",configFormat:"json",configKey:"mcpServers",rulesPath:".cursorrules",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},cline:{id:"cline",name:"Cline",configPath:".vscode/cline_mcp_settings.json",configFormat:"json",configKey:"mcpServers",rulesPath:".vscode/cline_custom_modes.json",rulesFormat:"json",supportsAutoApprove:!0,supportsCustomModes:!0,globalConfig:!1},kilocode:{id:"kilocode",name:"Kilo Code",configPath:".kilocode/mcp.json",configFormat:"json",configKey:"mcpServers",rulesPath:".kilocode/modes.json",rulesFormat:"json",supportsAutoApprove:!0,supportsCustomModes:!0,globalConfig:!1},roocode:{id:"roocode",name:"Roo Code",configPath:".roo/mcp.json",configFormat:"json",configKey:"mcpServers",rulesPath:".roo/modes.json",rulesFormat:"json",supportsAutoApprove:!0,supportsCustomModes:!0,globalConfig:!1},codex:{id:"codex",name:"OpenAI Codex CLI",configPath:".codex/config.toml",configFormat:"toml",configKey:"mcp_servers",rulesPath:"AGENTS.md",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},windsurf:{id:"windsurf",name:"Windsurf",configPath:".windsurf/mcp_config.json",configFormat:"json",configKey:"mcpServers",rulesPath:".windsurfrules",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},continuedev:{id:"continuedev",name:"Continue.dev",configPath:".continue/config.yaml",configFormat:"yaml",configKey:"mcpServers",rulesPath:".continue/rules/aqe-qe-standards.yaml",rulesFormat:"yaml",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1}},l=["fleet_init","fleet_status","fleet_health","agent_list","agent_metrics","agent_status","team_list","team_health","task_list","task_status","test_generate_enhanced","coverage_analyze_sublinear","quality_assess","defect_predict","code_index","memory_store","memory_retrieve","memory_query","memory_usage","model_route","routing_metrics","aqe_health"];function u(t){return t?{AQE_MEMORY_BACKEND:"memory",AQE_V3_MODE:"true"}:{AQE_MEMORY_PATH:".agentic-qe/memory.db",AQE_V3_MODE:"true"}}function m(t,o){let e={command:"npx",args:["-y","agentic-qe@latest","mcp"],env:u(o)};return t&&(e.disabled=!1,e.alwaysAllow=l),e}function g(t,o){let e=m(t.supportsAutoApprove,o);if(t.id==="copilot"){let r={[t.configKey]:{"agentic-qe":{type:"stdio",...e}}};return JSON.stringify(r,null,2)+`
3
3
  `}let n={[t.configKey]:{"agentic-qe":e}};return JSON.stringify(n,null,2)+`
4
4
  `}function f(t){return`# Agentic QE MCP Server
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.0");process.exit(0)}
2
- import{i as e}from"./chunk-E3B5XTXJ.js";function g(t,n,r,a){return{id:e(),type:t,timestamp:new Date,source:n,correlationId:a,payload:r}}var i={TestGenerated:"test-generation.TestGenerated",TestSuiteCreated:"test-generation.TestSuiteCreated",PatternLearned:"test-generation.PatternLearned",GenerationFailed:"test-generation.GenerationFailed"},s={TestRunStarted:"test-execution.TestRunStarted",TestRunCompleted:"test-execution.TestRunCompleted",FlakyTestDetected:"test-execution.FlakyTestDetected",RetryTriggered:"test-execution.RetryTriggered"},o={CoverageReportCreated:"coverage-analysis.CoverageReportCreated",CoverageGapDetected:"coverage-analysis.CoverageGapDetected",RiskZoneIdentified:"coverage-analysis.RiskZoneIdentified"},d={QualityGateEvaluated:"quality-assessment.QualityGateEvaluated",DeploymentApproved:"quality-assessment.DeploymentApproved",DeploymentBlocked:"quality-assessment.DeploymentBlocked"},l={DefectPredicted:"defect-intelligence.DefectPredicted",RootCauseIdentified:"defect-intelligence.RootCauseIdentified",RegressionRiskAnalyzed:"defect-intelligence.RegressionRiskAnalyzed"},c={KnowledgeGraphUpdated:"code-intelligence.KnowledgeGraphUpdated",ImpactAnalysisCompleted:"code-intelligence.ImpactAnalysisCompleted",SemanticSearchCompleted:"code-intelligence.SemanticSearchCompleted",C4DiagramsGenerated:"code-intelligence.C4DiagramsGenerated"},m={VulnerabilityDetected:"security-compliance.VulnerabilityDetected",ComplianceValidated:"security-compliance.ComplianceValidated",SecurityAuditCompleted:"security-compliance.SecurityAuditCompleted"},p={PatternConsolidated:"learning-optimization.PatternConsolidated",TransferCompleted:"learning-optimization.TransferCompleted",OptimizationApplied:"learning-optimization.OptimizationApplied",DreamCycleCompleted:"learning-optimization.dream.completed"},y={...i,...s,...o,...d,...l,...c,...m,...p};export{g as a,i as b,s as c,o as d,d as e,l as f,c as g,m as h,p as i};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
2
+ import{i as e}from"./chunk-ZIBW7CB4.js";function g(t,n,r,a){return{id:e(),type:t,timestamp:new Date,source:n,correlationId:a,payload:r}}var i={TestGenerated:"test-generation.TestGenerated",TestSuiteCreated:"test-generation.TestSuiteCreated",PatternLearned:"test-generation.PatternLearned",GenerationFailed:"test-generation.GenerationFailed"},s={TestRunStarted:"test-execution.TestRunStarted",TestRunCompleted:"test-execution.TestRunCompleted",FlakyTestDetected:"test-execution.FlakyTestDetected",RetryTriggered:"test-execution.RetryTriggered"},o={CoverageReportCreated:"coverage-analysis.CoverageReportCreated",CoverageGapDetected:"coverage-analysis.CoverageGapDetected",RiskZoneIdentified:"coverage-analysis.RiskZoneIdentified"},d={QualityGateEvaluated:"quality-assessment.QualityGateEvaluated",DeploymentApproved:"quality-assessment.DeploymentApproved",DeploymentBlocked:"quality-assessment.DeploymentBlocked"},l={DefectPredicted:"defect-intelligence.DefectPredicted",RootCauseIdentified:"defect-intelligence.RootCauseIdentified",RegressionRiskAnalyzed:"defect-intelligence.RegressionRiskAnalyzed"},c={KnowledgeGraphUpdated:"code-intelligence.KnowledgeGraphUpdated",ImpactAnalysisCompleted:"code-intelligence.ImpactAnalysisCompleted",SemanticSearchCompleted:"code-intelligence.SemanticSearchCompleted",C4DiagramsGenerated:"code-intelligence.C4DiagramsGenerated"},m={VulnerabilityDetected:"security-compliance.VulnerabilityDetected",ComplianceValidated:"security-compliance.ComplianceValidated",SecurityAuditCompleted:"security-compliance.SecurityAuditCompleted"},p={PatternConsolidated:"learning-optimization.PatternConsolidated",TransferCompleted:"learning-optimization.TransferCompleted",OptimizationApplied:"learning-optimization.OptimizationApplied",DreamCycleCompleted:"learning-optimization.dream.completed"},y={...i,...s,...o,...d,...l,...c,...m,...p};export{g as a,i as b,s as c,o as d,d as e,l as f,c as g,m as h,p as i};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.0");process.exit(0)}
2
- import{b as P,c as q,d as R,e as D,g as O,h as j,i as x,j as $,k as L,l as N,m as Q,n as M}from"./chunk-ZJIX5FGQ.js";import{b as v,d as T}from"./chunk-2DIT5AUU.js";import{a as y,c as A}from"./chunk-CYL2FV23.js";import{a as _,b as re}from"./chunk-SNTUKW4Q.js";T();import{existsSync as f,mkdirSync as U,writeFileSync as b,readFileSync as C,copyFileSync as se}from"fs";import{join as p,dirname as ae}from"path";async function z(t,e){if(!e.hooks.claudeCode)return!1;let n=p(t,".claude");f(n)||U(n,{recursive:!0});let r=p(n,"settings.json"),s={};if(f(r))try{let m=C(r,"utf-8");s=v(m)}catch{s={}}let i={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:3e3,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:5e3,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:3e3,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:5e3,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:5e3,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:5e3,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:5e3,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" route --json',timeout:5e3,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-start --session-id "$SESSION_ID" --json',timeout:1e4,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-end --save-state --json',timeout:5e3,continueOnError:!0}]},{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-route --success true --json',timeout:5e3,continueOnError:!0}]}]},u=s.hooks||{};s.hooks=O(u,i);let l=s.env;s.env=j(l,x(e));let d=L(e,t);$(s,d);let a=s.enabledMcpjsonServers||[];return a=a.filter(m=>m!=="aqe"),a.includes("agentic-qe")||a.push("agentic-qe"),s.enabledMcpjsonServers=a,D(r),b(r,JSON.stringify(s,null,2),"utf-8"),await oe(t),!0}async function oe(t){let e=p(t,".claude","hooks");f(e)||U(e,{recursive:!0});let n=p(e,"cross-phase-memory.yaml");if(f(n))return;let r=[p(ae(import.meta.url.replace("file://","")),"..","..","assets","hooks","cross-phase-memory.yaml"),p(process.cwd(),"assets","hooks","cross-phase-memory.yaml"),p(process.cwd(),"v3","assets","hooks","cross-phase-memory.yaml")];for(let i of r)try{if(f(i)){se(i,n),console.log(" \u2713 Cross-phase memory hooks installed");return}}catch{}b(n,`# Cross-Phase Memory Hooks Configuration
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
2
+ import{b as P,c as q,d as R,e as D,g as O,h as j,i as x,j as $,k as L,l as N,m as Q,n as M}from"./chunk-MAYZTGJ2.js";import{b as v,d as T}from"./chunk-ZLCATRXI.js";import{a as y,c as A}from"./chunk-AYYDO52G.js";import{a as _,b as re}from"./chunk-EVDYFGVH.js";T();import{existsSync as f,mkdirSync as U,writeFileSync as b,readFileSync as C,copyFileSync as se}from"fs";import{join as p,dirname as ae}from"path";async function z(t,e){if(!e.hooks.claudeCode)return!1;let n=p(t,".claude");f(n)||U(n,{recursive:!0});let r=p(n,"settings.json"),s={};if(f(r))try{let m=C(r,"utf-8");s=v(m)}catch{s={}}let i={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:3e3,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:5e3,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:3e3,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:5e3,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:5e3,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:5e3,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:5e3,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" route --json',timeout:5e3,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-start --session-id "$SESSION_ID" --json',timeout:1e4,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-end --save-state --json',timeout:5e3,continueOnError:!0}]},{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-route --success true --json',timeout:5e3,continueOnError:!0}]}]},u=s.hooks||{};s.hooks=O(u,i);let l=s.env;s.env=j(l,x(e));let d=L(e,t);$(s,d);let a=s.enabledMcpjsonServers||[];return a=a.filter(m=>m!=="aqe"),a.includes("agentic-qe")||a.push("agentic-qe"),s.enabledMcpjsonServers=a,D(r),b(r,JSON.stringify(s,null,2),"utf-8"),await oe(t),!0}async function oe(t){let e=p(t,".claude","hooks");f(e)||U(e,{recursive:!0});let n=p(e,"cross-phase-memory.yaml");if(f(n))return;let r=[p(ae(import.meta.url.replace("file://","")),"..","..","assets","hooks","cross-phase-memory.yaml"),p(process.cwd(),"assets","hooks","cross-phase-memory.yaml"),p(process.cwd(),"v3","assets","hooks","cross-phase-memory.yaml")];for(let i of r)try{if(f(i)){se(i,n),console.log(" \u2713 Cross-phase memory hooks installed");return}}catch{}b(n,`# Cross-Phase Memory Hooks Configuration
3
3
  # Generated by aqe init
4
4
  # See: https://github.com/anthropics/agentic-qe/docs/cross-phase-memory.md
5
5
 
@@ -276,7 +276,7 @@ aqe init --auto
276
276
  `).run("aqe_version",JSON.stringify(e),i),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()),i),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(i){return s.close(),console.warn(` \u26A0 Could not write version: ${y(i)}`),!1}}catch(r){return console.warn(` \u26A0 Could not open memory.db: ${y(r)}`),!1}}async function V(t){let e=null;try{e=(await import("./better-sqlite3-DUZ6FFAH.js")).default}catch{throw new Error(`SQLite persistence REQUIRED but better-sqlite3 is not installed.
279
+ `).run("init_timestamp",JSON.stringify(new Date().toISOString()),i),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(i){return s.close(),console.warn(` \u26A0 Could not write version: ${y(i)}`),!1}}catch(r){return console.warn(` \u26A0 Could not open memory.db: ${y(r)}`),!1}}async function V(t){let e=null;try{e=(await import("./better-sqlite3-JDDFYVCX.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
@@ -302,7 +302,7 @@ Database path: ${r}
302
302
  Ensure the directory is writable and has sufficient disk space.`)}}async function J(t){let e=o(t,".agentic-qe","memory.db");if(!h(e))return!1;try{let n=_(e),r=n.prepare(`
303
303
  SELECT COUNT(*) as count FROM kv_store
304
304
  WHERE namespace = 'code-intelligence:kg'
305
- `).get();return n.close(),r.count>0}catch{return!1}}async function B(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-6XTW6WO6.js"),{InMemoryBackend:n}=await import("./memory-backend-PR74ZPBA.js"),r=new n;await r.initialize();let s=new e(r,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0}),u=await(await import("fast-glob")).default(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:t,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"]}),l=await s.index({paths:u.map(d=>o(t,d)),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:",y(e)),{status:"skipped",entries:0}}}async function H(t){let e=o(t,".agentic-qe","memory.db");try{let n=_(e),r=n.prepare(`
305
+ `).get();return n.close(),r.count>0}catch{return!1}}async function B(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-EGPMNDMT.js"),{InMemoryBackend:n}=await import("./memory-backend-O2YOT4LW.js"),r=new n;await r.initialize();let s=new e(r,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0}),u=await(await import("fast-glob")).default(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:t,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"]}),l=await s.index({paths:u.map(d=>o(t,d)),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:",y(e)),{status:"skipped",entries:0}}}async function H(t){let e=o(t,".agentic-qe","memory.db");try{let n=_(e),r=n.prepare(`
306
306
  SELECT COUNT(*) as count FROM kv_store
307
307
  WHERE namespace LIKE 'code-intelligence:kg%'
308
308
  `).get();return n.close(),r.count}catch{return 0}}async function X(t,e,n){if(!e.learning.enabled)return 0;let r=o(t,".agentic-qe","data");h(r)||k(r,{recursive:!0});let s=o(r,"hnsw");h(s)||k(s,{recursive:!0});let i=o(r,"learning-config.json"),u={embeddingModel:e.learning.embeddingModel,hnswConfig:e.learning.hnswConfig,qualityThreshold:e.learning.qualityThreshold,promotionThreshold:e.learning.promotionThreshold,databasePath:o(r,"memory.db"),hnswIndexPath:o(s,"index.bin"),initialized:new Date().toISOString()};E(i,JSON.stringify(u,null,2),"utf-8");let l=0;if(e.learning.pretrainedPatterns&&n){let d=n,a=new Map;for(let g of d.patterns){let c=g.domain||"general";a.has(c)||a.set(c,[]),a.get(c).push(g)}let m=o(r,"pretrained-index.json"),S={version:d.version,totalPatterns:d.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=o(r,"patterns",g);h(w)||k(w,{recursive:!0});let ne=o(w,"patterns.json");E(ne,JSON.stringify(c,null,2),"utf-8"),l+=c.length}return l}return 0}async function K(t,e){if(!e.workers.daemonAutoStart||e.workers.enabled.length===0)return 0;let n=o(t,".agentic-qe","workers");h(n)||k(n,{recursive:!0});let r={},s={"pattern-consolidator":6e4,"coverage-gap-scanner":3e5,"flaky-test-detector":6e5,"routing-accuracy-monitor":12e4};for(let a of e.workers.enabled)r[a]={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,lastRun:null,status:"pending"};let i=o(n,"registry.json"),u={version:e.version,maxConcurrent:e.workers.maxConcurrent,workers:r,createdAt:new Date().toISOString(),daemonPid:null};E(i,JSON.stringify(u,null,2),"utf-8");for(let a of e.workers.enabled){let m=o(n,`${a}.json`),S={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,projectRoot:t,dataDir:o(t,".agentic-qe","data"),createdAt:new Date().toISOString()};E(m,JSON.stringify(S,null,2),"utf-8")}let l=o(n,"start-daemon.cjs");return E(l,`#!/usr/bin/env node
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.0");process.exit(0)}
2
- import{b as w,c as E,d as k,i as de,m as ue}from"./chunk-G5DFYX3J.js";import{a as v}from"./chunk-HVB2L52I.js";import{c as b}from"./chunk-OXXMVQDF.js";import{b as j}from"./chunk-NUQBJGGF.js";import{a as Te,b as _,d as ee}from"./chunk-2DIT5AUU.js";import{a as d,b as L,c as P}from"./chunk-CYL2FV23.js";import{i as I}from"./chunk-E3B5XTXJ.js";import{a as T,b as z}from"./chunk-SNTUKW4Q.js";import{a as le,d as Ce}from"./chunk-IZRLIWFN.js";import{f as Ee}from"./chunk-ES7WCYOU.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"}}]},Re={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 me 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=me.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 pe=Ee(Te(),1);P();import{randomUUID as Pe}from"crypto";import*as C from"fs";import*as ge 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=ge.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=pe.default.parse(e);return this.extractRecords(t).map(r=>this.transformRecord(r))}catch(e){return console.error(`[JSONReader:${this.name}] Failed to read: ${d(e)}`),[]}}async readChanged(e){return C.existsSync(this.filePath)?C.statSync(this.filePath).mtime<=e?[]:this.readAll():[]}async count(){return(await this.readAll()).length}async close(){this.data=null,this.fileModTime=null,console.log(`[JSONReader:${this.name}] Closed`)}extractRecords(e){return this.config.source.jsonPath?this.extractByPath(e,this.config.source.jsonPath):this.name.includes("claude-flow-memory")?this.extractClaudeFlowMemory(e):this.name.includes("intelligence")||this.name.includes("qlearning")?this.extractIntelligence(e):this.name.includes("daemon")?this.extractDaemonState(e):Array.isArray(e)?e:typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]}extractByPath(e,t){let n=t.replace(/^\$\./,"").split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return[];return Array.isArray(r)?r:typeof r=="object"&&r!==null?Object.entries(r).map(([i,o])=>({state:i,...typeof o=="object"?o:{value:o}})):[]}extractClaudeFlowMemory(e){if(!e||typeof e!="object")return[];let t=[],n=e;for(let[r,i]of Object.entries(n)){if(r.startsWith("_"))continue;let o="general";r.includes("adr")?o="adr-analysis":r.includes("agent")?o="agent-patterns":r.includes("pattern")?o="patterns":r.includes("metric")&&(o="metrics"),t.push({key:r,value:typeof i=="object"?i:{data:i},category:o})}return t}extractIntelligence(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.qvalues&&typeof n.qvalues=="object"){let r=n.qvalues;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null)for(let[s,a]of Object.entries(o)){let c=typeof a=="object"?a:{value:a};t.push({state:i,action:s,q_value:c.value||c.q_value||0,visits:c.visits||0,last_update:c.lastUpdate||c.last_update})}}if(n.memories&&Array.isArray(n.memories)){for(let r of n.memories)if(typeof r=="object"&&r!==null){let i=r;t.push({id:i.id||`mem_${Date.now()}_${Pe().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 ve}from"child_process";import{createConnection as _e}from"net";var xe=b.create("tunnel-manager");function he(l){try{let e=new URL(l);return e.password&&(e.password="***"),e.toString()}catch(e){return xe.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=_e({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=ve("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 he(this.getConnectionString())}};function ke(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 he(this.connectionString)}};function M(l){return l.connectionString?new B(l.connectionString):new $(l)}k();P();v();import{createRequire as Ae}from"module";var N=b.create("postgres-writer"),$e=Ae(import.meta.url),J=class{client=null;config;inTransaction=!1;connected=!1;constructor(e){this.config=e}async connect(){if(this.connected)return;this.config.tunnelManager.isActive()||await this.config.tunnelManager.start();let e=this.config.tunnelManager.getConnection();if(!e)throw new Error("No tunnel connection available");let t;try{t=$e("pg")}catch(o){N.debug("pg module not installed, using mock mode",{error:o instanceof Error?o.message:String(o)}),console.warn("[PostgresWriter] pg module not installed, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let n=t.default,r=t.Client||n?.Client;if(!r){console.warn("[PostgresWriter] pg.Client not found in module, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let i={host:e.host,port:e.port,database:this.config.cloud.database,user:this.config.cloud.user,password:process.env.PGPASSWORD||"",connectionTimeoutMillis:this.config.connectionTimeout||1e4};this.client=new r(i),await this.client.connect(),this.connected=!0,console.log(`[PostgresWriter] Connected to ${e.host}:${e.port}/${this.config.cloud.database}`)}async beginTransaction(){if(!this.client)throw new Error("Not connected");await this.client.query("BEGIN"),this.inTransaction=!0}async commit(){if(!this.client||!this.inTransaction)throw new Error("No active transaction");await this.client.query("COMMIT"),this.inTransaction=!1}async rollback(){!this.client||!this.inTransaction||(await this.client.query("ROLLBACK"),this.inTransaction=!1)}async upsert(e,t,n){if(!this.client)throw new Error("Not connected");if(t.length===0)return 0;let r=t[0],i=Object.keys(r),o=n?.conflictColumns||this.inferConflictColumns(e,i),s=n?.updateColumns||i.filter(u=>!o.includes(u)),a=0,c=100;for(let u=0;u<t.length;u+=c){let p=t.slice(u,u+c);try{let m=await this.upsertBatch(e,p,i,o,s,n?.skipIfExists);a+=m}catch(m){let g=Math.floor(u/c)+1,h=Math.ceil(t.length/c);N.debug(`Batch ${g}/${h} failed for ${e}, retrying individually`,{error:d(m)});let y=0;for(let f of p)try{let S=await this.upsertBatch(e,[f],i,o,s,n?.skipIfExists);y+=S}catch(S){let R=f.id||f.key||"?";N.debug(`Skipped record ${String(R).slice(0,50)} in ${e}`,{error:d(S)})}a+=y,y<p.length&&console.warn(`[PostgresWriter] Batch ${g}/${h} for ${e}: ${y}/${p.length} recovered (${p.length-y} skipped)`)}}return a}async upsertBatch(e,t,n,r,i,o){if(!this.client)return 0;let s=[],a=[],c=1;for(let f of t){let S=[];for(let R of n){let we=f[R];S.push(`$${c++}`),a.push(this.serializeValue(we,R))}s.push(`(${S.join(", ")})`)}let u=E(e),p=n.map(E),m=r.map(E),g=i.map(E),h="";if(m.length>0){if(o)h=`ON CONFLICT (${m.join(", ")}) DO NOTHING`;else if(g.length>0){let f=g.map(S=>`${S} = EXCLUDED.${S}`).join(", ");h=`ON CONFLICT (${m.join(", ")}) DO UPDATE SET ${f}`}}let y=`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
2
+ import{b as w,c as E,d as k,i as de,m as ue}from"./chunk-UCQ66N6M.js";import{a as v}from"./chunk-BBLWZT5I.js";import{c as b}from"./chunk-ELMUHNXN.js";import{b as j}from"./chunk-YBPCBFEE.js";import{a as Te,b as _,d as ee}from"./chunk-ZLCATRXI.js";import{a as d,b as L,c as P}from"./chunk-AYYDO52G.js";import{i as I}from"./chunk-ZIBW7CB4.js";import{a as T,b as z}from"./chunk-EVDYFGVH.js";import{a as le,d as Ce}from"./chunk-DVPGQG4W.js";import{f as Ee}from"./chunk-OE4B6LDZ.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"}}]},Re={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 me 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=me.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 pe=Ee(Te(),1);P();import{randomUUID as Pe}from"crypto";import*as C from"fs";import*as ge 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=ge.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=pe.default.parse(e);return this.extractRecords(t).map(r=>this.transformRecord(r))}catch(e){return console.error(`[JSONReader:${this.name}] Failed to read: ${d(e)}`),[]}}async readChanged(e){return C.existsSync(this.filePath)?C.statSync(this.filePath).mtime<=e?[]:this.readAll():[]}async count(){return(await this.readAll()).length}async close(){this.data=null,this.fileModTime=null,console.log(`[JSONReader:${this.name}] Closed`)}extractRecords(e){return this.config.source.jsonPath?this.extractByPath(e,this.config.source.jsonPath):this.name.includes("claude-flow-memory")?this.extractClaudeFlowMemory(e):this.name.includes("intelligence")||this.name.includes("qlearning")?this.extractIntelligence(e):this.name.includes("daemon")?this.extractDaemonState(e):Array.isArray(e)?e:typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]}extractByPath(e,t){let n=t.replace(/^\$\./,"").split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return[];return Array.isArray(r)?r:typeof r=="object"&&r!==null?Object.entries(r).map(([i,o])=>({state:i,...typeof o=="object"?o:{value:o}})):[]}extractClaudeFlowMemory(e){if(!e||typeof e!="object")return[];let t=[],n=e;for(let[r,i]of Object.entries(n)){if(r.startsWith("_"))continue;let o="general";r.includes("adr")?o="adr-analysis":r.includes("agent")?o="agent-patterns":r.includes("pattern")?o="patterns":r.includes("metric")&&(o="metrics"),t.push({key:r,value:typeof i=="object"?i:{data:i},category:o})}return t}extractIntelligence(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.qvalues&&typeof n.qvalues=="object"){let r=n.qvalues;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null)for(let[s,a]of Object.entries(o)){let c=typeof a=="object"?a:{value:a};t.push({state:i,action:s,q_value:c.value||c.q_value||0,visits:c.visits||0,last_update:c.lastUpdate||c.last_update})}}if(n.memories&&Array.isArray(n.memories)){for(let r of n.memories)if(typeof r=="object"&&r!==null){let i=r;t.push({id:i.id||`mem_${Date.now()}_${Pe().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 ve}from"child_process";import{createConnection as _e}from"net";var xe=b.create("tunnel-manager");function he(l){try{let e=new URL(l);return e.password&&(e.password="***"),e.toString()}catch(e){return xe.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=_e({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=ve("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 he(this.getConnectionString())}};function ke(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 he(this.connectionString)}};function M(l){return l.connectionString?new B(l.connectionString):new $(l)}k();P();v();import{createRequire as Ae}from"module";var N=b.create("postgres-writer"),$e=Ae(import.meta.url),J=class{client=null;config;inTransaction=!1;connected=!1;constructor(e){this.config=e}async connect(){if(this.connected)return;this.config.tunnelManager.isActive()||await this.config.tunnelManager.start();let e=this.config.tunnelManager.getConnection();if(!e)throw new Error("No tunnel connection available");let t;try{t=$e("pg")}catch(o){N.debug("pg module not installed, using mock mode",{error:o instanceof Error?o.message:String(o)}),console.warn("[PostgresWriter] pg module not installed, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let n=t.default,r=t.Client||n?.Client;if(!r){console.warn("[PostgresWriter] pg.Client not found in module, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let i={host:e.host,port:e.port,database:this.config.cloud.database,user:this.config.cloud.user,password:process.env.PGPASSWORD||"",connectionTimeoutMillis:this.config.connectionTimeout||1e4};this.client=new r(i),await this.client.connect(),this.connected=!0,console.log(`[PostgresWriter] Connected to ${e.host}:${e.port}/${this.config.cloud.database}`)}async beginTransaction(){if(!this.client)throw new Error("Not connected");await this.client.query("BEGIN"),this.inTransaction=!0}async commit(){if(!this.client||!this.inTransaction)throw new Error("No active transaction");await this.client.query("COMMIT"),this.inTransaction=!1}async rollback(){!this.client||!this.inTransaction||(await this.client.query("ROLLBACK"),this.inTransaction=!1)}async upsert(e,t,n){if(!this.client)throw new Error("Not connected");if(t.length===0)return 0;let r=t[0],i=Object.keys(r),o=n?.conflictColumns||this.inferConflictColumns(e,i),s=n?.updateColumns||i.filter(u=>!o.includes(u)),a=0,c=100;for(let u=0;u<t.length;u+=c){let p=t.slice(u,u+c);try{let m=await this.upsertBatch(e,p,i,o,s,n?.skipIfExists);a+=m}catch(m){let g=Math.floor(u/c)+1,h=Math.ceil(t.length/c);N.debug(`Batch ${g}/${h} failed for ${e}, retrying individually`,{error:d(m)});let y=0;for(let f of p)try{let S=await this.upsertBatch(e,[f],i,o,s,n?.skipIfExists);y+=S}catch(S){let R=f.id||f.key||"?";N.debug(`Skipped record ${String(R).slice(0,50)} in ${e}`,{error:d(S)})}a+=y,y<p.length&&console.warn(`[PostgresWriter] Batch ${g}/${h} for ${e}: ${y}/${p.length} recovered (${p.length-y} skipped)`)}}return a}async upsertBatch(e,t,n,r,i,o){if(!this.client)return 0;let s=[],a=[],c=1;for(let f of t){let S=[];for(let R of n){let we=f[R];S.push(`$${c++}`),a.push(this.serializeValue(we,R))}s.push(`(${S.join(", ")})`)}let u=E(e),p=n.map(E),m=r.map(E),g=i.map(E),h="";if(m.length>0){if(o)h=`ON CONFLICT (${m.join(", ")}) DO NOTHING`;else if(g.length>0){let f=g.map(S=>`${S} = EXCLUDED.${S}`).join(", ");h=`ON CONFLICT (${m.join(", ")}) DO UPDATE SET ${f}`}}let y=`
3
3
  INSERT INTO ${u} (${p.join(", ")})
4
4
  VALUES ${s.join(", ")}
5
5
  ${h}
@@ -26,4 +26,4 @@ import{b as w,c as E,d as k,i as de,m as ue}from"./chunk-G5DFYX3J.js";import{a a
26
26
  INSERT OR REPLACE INTO embeddings
27
27
  (key, namespace, vector, dimension, text, timestamp, quantization, metadata, last_access)
28
28
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
29
- `).run(e,n,r,t.dimension,t.text,t.timestamp,t.quantization,i,Date.now())}catch(r){console.warn("Failed to persist embedding:",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}};Ce();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-IACZG7IV.js"))}catch(i){throw new Error(`Local (in-process) embeddings require the optional dependency "@huggingface/transformers", which is not installed. Either run \`npm install @huggingface/transformers\`, or configure an embedding endpoint (e.g. Cognitum /v1/embeddings) so the local backend is not needed. 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:le(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 ze,dirname as je}from"path";import{fileURLToPath as Fe}from"url";var be=b.create("sync-embedding-generator"),We=Fe(import.meta.url),Ue=je(We),q=class{generator;dbPath;initialized=!1;constructor(e){this.dbPath=e||ze(Ue,"../../../../.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){be.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){be.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 Se(l){return new q(l)}export{A as a,Re as b,x as c,W as d,re as e,U as f,ne as g,$ as h,ke 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,Ne as t,Oe as u,X as v,ce as w,De as x,qe as y,q as z,Se as A};
29
+ `).run(e,n,r,t.dimension,t.text,t.timestamp,t.quantization,i,Date.now())}catch(r){console.warn("Failed to persist embedding:",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}};Ce();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-FDHHH4SL.js"))}catch(i){throw new Error(`Local (in-process) embeddings require the optional dependency "@huggingface/transformers", which is not installed. Either run \`npm install @huggingface/transformers\`, or configure an embedding endpoint (e.g. Cognitum /v1/embeddings) so the local backend is not needed. 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:le(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 ze,dirname as je}from"path";import{fileURLToPath as Fe}from"url";var be=b.create("sync-embedding-generator"),We=Fe(import.meta.url),Ue=je(We),q=class{generator;dbPath;initialized=!1;constructor(e){this.dbPath=e||ze(Ue,"../../../../.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){be.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){be.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 Se(l){return new q(l)}export{A as a,Re as b,x as c,W as d,re as e,U as f,ne as g,$ as h,ke 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,Ne as t,Oe as u,X as v,ce as w,De as x,qe as y,q as z,Se 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.13.0");process.exit(0)}
2
- import{b as f,d as v}from"./chunk-2DIT5AUU.js";import q,{MultiBar as F,Presets as k}from"cli-progress";import O from"ora";import o from"chalk";v();import{existsSync as w,readFileSync as y,writeFileSync as j,mkdirSync as W,unlinkSync as V}from"fs";import{join as p}from"path";import{homedir as C}from"os";var u={wizards:{enabled:!0,themes:["default","minimal","detailed"],defaultTheme:"default"},progress:{style:"multi-bar",updateIntervalMs:100,showETA:!0,colors:!0},completion:{maxSuggestions:10,historyWeight:.3,contextWeight:.7,fuzzyMatch:!0},streaming:{enabled:!0,bufferSize:100,updateIntervalMs:50}};function x(){return p(C(),".aqe")}function E(){return p(x(),"cli-config.json")}var g=null,d=0,T=5e3;function S(){return g?Date.now()-d<T:!1}function A(s){let e=[],t=s;if(typeof t.enabled!="boolean"&&t.enabled!==void 0&&e.push({path:"wizards.enabled",message:"must be a boolean"}),t.themes!==void 0)if(!Array.isArray(t.themes))e.push({path:"wizards.themes",message:"must be an array"});else{let r=["default","minimal","detailed"];for(let n of t.themes)r.includes(n)||e.push({path:"wizards.themes",message:`invalid theme: ${n}`})}return t.defaultTheme!==void 0&&(["default","minimal","detailed"].includes(t.defaultTheme)||e.push({path:"wizards.defaultTheme",message:`invalid theme: ${t.defaultTheme}`})),e}function P(s){let e=[],t=s;return t.style!==void 0&&(["multi-bar","single-bar","spinner"].includes(t.style)||e.push({path:"progress.style",message:`invalid style: ${t.style}`})),t.updateIntervalMs!==void 0&&(typeof t.updateIntervalMs!="number"||t.updateIntervalMs<10)&&e.push({path:"progress.updateIntervalMs",message:"must be a number >= 10"}),typeof t.showETA!="boolean"&&t.showETA!==void 0&&e.push({path:"progress.showETA",message:"must be a boolean"}),typeof t.colors!="boolean"&&t.colors!==void 0&&e.push({path:"progress.colors",message:"must be a boolean"}),e}function $(s){let e=[],t=s;return t.maxSuggestions!==void 0&&(typeof t.maxSuggestions!="number"||t.maxSuggestions<1)&&e.push({path:"completion.maxSuggestions",message:"must be a number >= 1"}),t.historyWeight!==void 0&&(typeof t.historyWeight!="number"||t.historyWeight<0||t.historyWeight>1)&&e.push({path:"completion.historyWeight",message:"must be a number between 0 and 1"}),t.contextWeight!==void 0&&(typeof t.contextWeight!="number"||t.contextWeight<0||t.contextWeight>1)&&e.push({path:"completion.contextWeight",message:"must be a number between 0 and 1"}),typeof t.fuzzyMatch!="boolean"&&t.fuzzyMatch!==void 0&&e.push({path:"completion.fuzzyMatch",message:"must be a boolean"}),e}function I(s){let e=[],t=s;return typeof t.enabled!="boolean"&&t.enabled!==void 0&&e.push({path:"streaming.enabled",message:"must be a boolean"}),t.bufferSize!==void 0&&(typeof t.bufferSize!="number"||t.bufferSize<1)&&e.push({path:"streaming.bufferSize",message:"must be a number >= 1"}),t.updateIntervalMs!==void 0&&(typeof t.updateIntervalMs!="number"||t.updateIntervalMs<10)&&e.push({path:"streaming.updateIntervalMs",message:"must be a number >= 10"}),e}function M(s){let e=[];if(typeof s!="object"||s===null)return{valid:!1,errors:[{path:"",message:"config must be an object"}]};let t=s;return t.wizards!==void 0&&(typeof t.wizards!="object"||t.wizards===null?e.push({path:"wizards",message:"must be an object"}):e.push(...A(t.wizards))),t.progress!==void 0&&(typeof t.progress!="object"||t.progress===null?e.push({path:"progress",message:"must be an object"}):e.push(...P(t.progress))),t.completion!==void 0&&(typeof t.completion!="object"||t.completion===null?e.push({path:"completion",message:"must be an object"}):e.push(...$(t.completion))),t.streaming!==void 0&&(typeof t.streaming!="object"||t.streaming===null?e.push({path:"streaming",message:"must be an object"}):e.push(...I(t.streaming))),{valid:e.length===0,errors:e}}var z=["__proto__","constructor","prototype"];function m(s,e){let t={...s};for(let r of Object.keys(e)){if(z.includes(r)){console.warn(`Security: Skipping forbidden key '${String(r)}' in configuration merge`);continue}let n=e[r],i=s[r];n!==void 0&&typeof n=="object"&&!Array.isArray(n)&&typeof i=="object"&&!Array.isArray(i)?t[r]=m(i,n):n!==void 0&&(t[r]=n)}return t}function D(){let s=E();if(!w(s))return{...u};try{let e=y(s,"utf-8"),t=f(e),r=M(t);return r.valid?m(u,t):(console.warn(`CLI config validation errors: ${r.errors.map(n=>`${n.path}: ${n.message}`).join(", ")}`),console.warn("Using default configuration"),{...u})}catch(e){return console.warn(`Failed to load CLI config: ${e instanceof Error?e.message:"Unknown error"}`),{...u}}}function c(){return S()||(g=D(),d=Date.now()),g}function B(){return process.stdout.isTTY===!0}function h(){let s=c();return process.env.NO_COLOR!==void 0?!1:process.env.FORCE_COLOR!==void 0?!0:s.progress.colors&&B()}var b=class{multiBar;agentBars=new Map;agentStates=new Map;fleetBar=null;startTime=Date.now();options;isActive=!1;constructor(e={}){let t=c(),r=h();this.options={title:"Fleet Progress",showEta:t.progress.showETA,showPercentage:!0,...e};let n=r?o.cyan("{bar}"):"{bar}",i=this.options.format||`{name} ${n} {percentage}% | {status} {eta}`;this.multiBar=new F({clearOnComplete:!1,hideCursor:!0,format:i,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",forceRedraw:!0,fps:Math.round(1e3/t.progress.updateIntervalMs)},k.shades_classic)}start(e){this.isActive=!0,this.startTime=Date.now(),console.log(o.blue(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
2
+ import{b as f,d as v}from"./chunk-ZLCATRXI.js";import q,{MultiBar as F,Presets as k}from"cli-progress";import O from"ora";import o from"chalk";v();import{existsSync as w,readFileSync as y,writeFileSync as j,mkdirSync as W,unlinkSync as V}from"fs";import{join as p}from"path";import{homedir as C}from"os";var u={wizards:{enabled:!0,themes:["default","minimal","detailed"],defaultTheme:"default"},progress:{style:"multi-bar",updateIntervalMs:100,showETA:!0,colors:!0},completion:{maxSuggestions:10,historyWeight:.3,contextWeight:.7,fuzzyMatch:!0},streaming:{enabled:!0,bufferSize:100,updateIntervalMs:50}};function x(){return p(C(),".aqe")}function E(){return p(x(),"cli-config.json")}var g=null,d=0,T=5e3;function S(){return g?Date.now()-d<T:!1}function A(s){let e=[],t=s;if(typeof t.enabled!="boolean"&&t.enabled!==void 0&&e.push({path:"wizards.enabled",message:"must be a boolean"}),t.themes!==void 0)if(!Array.isArray(t.themes))e.push({path:"wizards.themes",message:"must be an array"});else{let r=["default","minimal","detailed"];for(let n of t.themes)r.includes(n)||e.push({path:"wizards.themes",message:`invalid theme: ${n}`})}return t.defaultTheme!==void 0&&(["default","minimal","detailed"].includes(t.defaultTheme)||e.push({path:"wizards.defaultTheme",message:`invalid theme: ${t.defaultTheme}`})),e}function P(s){let e=[],t=s;return t.style!==void 0&&(["multi-bar","single-bar","spinner"].includes(t.style)||e.push({path:"progress.style",message:`invalid style: ${t.style}`})),t.updateIntervalMs!==void 0&&(typeof t.updateIntervalMs!="number"||t.updateIntervalMs<10)&&e.push({path:"progress.updateIntervalMs",message:"must be a number >= 10"}),typeof t.showETA!="boolean"&&t.showETA!==void 0&&e.push({path:"progress.showETA",message:"must be a boolean"}),typeof t.colors!="boolean"&&t.colors!==void 0&&e.push({path:"progress.colors",message:"must be a boolean"}),e}function $(s){let e=[],t=s;return t.maxSuggestions!==void 0&&(typeof t.maxSuggestions!="number"||t.maxSuggestions<1)&&e.push({path:"completion.maxSuggestions",message:"must be a number >= 1"}),t.historyWeight!==void 0&&(typeof t.historyWeight!="number"||t.historyWeight<0||t.historyWeight>1)&&e.push({path:"completion.historyWeight",message:"must be a number between 0 and 1"}),t.contextWeight!==void 0&&(typeof t.contextWeight!="number"||t.contextWeight<0||t.contextWeight>1)&&e.push({path:"completion.contextWeight",message:"must be a number between 0 and 1"}),typeof t.fuzzyMatch!="boolean"&&t.fuzzyMatch!==void 0&&e.push({path:"completion.fuzzyMatch",message:"must be a boolean"}),e}function I(s){let e=[],t=s;return typeof t.enabled!="boolean"&&t.enabled!==void 0&&e.push({path:"streaming.enabled",message:"must be a boolean"}),t.bufferSize!==void 0&&(typeof t.bufferSize!="number"||t.bufferSize<1)&&e.push({path:"streaming.bufferSize",message:"must be a number >= 1"}),t.updateIntervalMs!==void 0&&(typeof t.updateIntervalMs!="number"||t.updateIntervalMs<10)&&e.push({path:"streaming.updateIntervalMs",message:"must be a number >= 10"}),e}function M(s){let e=[];if(typeof s!="object"||s===null)return{valid:!1,errors:[{path:"",message:"config must be an object"}]};let t=s;return t.wizards!==void 0&&(typeof t.wizards!="object"||t.wizards===null?e.push({path:"wizards",message:"must be an object"}):e.push(...A(t.wizards))),t.progress!==void 0&&(typeof t.progress!="object"||t.progress===null?e.push({path:"progress",message:"must be an object"}):e.push(...P(t.progress))),t.completion!==void 0&&(typeof t.completion!="object"||t.completion===null?e.push({path:"completion",message:"must be an object"}):e.push(...$(t.completion))),t.streaming!==void 0&&(typeof t.streaming!="object"||t.streaming===null?e.push({path:"streaming",message:"must be an object"}):e.push(...I(t.streaming))),{valid:e.length===0,errors:e}}var z=["__proto__","constructor","prototype"];function m(s,e){let t={...s};for(let r of Object.keys(e)){if(z.includes(r)){console.warn(`Security: Skipping forbidden key '${String(r)}' in configuration merge`);continue}let n=e[r],i=s[r];n!==void 0&&typeof n=="object"&&!Array.isArray(n)&&typeof i=="object"&&!Array.isArray(i)?t[r]=m(i,n):n!==void 0&&(t[r]=n)}return t}function D(){let s=E();if(!w(s))return{...u};try{let e=y(s,"utf-8"),t=f(e),r=M(t);return r.valid?m(u,t):(console.warn(`CLI config validation errors: ${r.errors.map(n=>`${n.path}: ${n.message}`).join(", ")}`),console.warn("Using default configuration"),{...u})}catch(e){return console.warn(`Failed to load CLI config: ${e instanceof Error?e.message:"Unknown error"}`),{...u}}}function c(){return S()||(g=D(),d=Date.now()),g}function B(){return process.stdout.isTTY===!0}function h(){let s=c();return process.env.NO_COLOR!==void 0?!1:process.env.FORCE_COLOR!==void 0?!0:s.progress.colors&&B()}var b=class{multiBar;agentBars=new Map;agentStates=new Map;fleetBar=null;startTime=Date.now();options;isActive=!1;constructor(e={}){let t=c(),r=h();this.options={title:"Fleet Progress",showEta:t.progress.showETA,showPercentage:!0,...e};let n=r?o.cyan("{bar}"):"{bar}",i=this.options.format||`{name} ${n} {percentage}% | {status} {eta}`;this.multiBar=new F({clearOnComplete:!1,hideCursor:!0,format:i,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",forceRedraw:!0,fps:Math.round(1e3/t.progress.updateIntervalMs)},k.shades_classic)}start(e){this.isActive=!0,this.startTime=Date.now(),console.log(o.blue(`
3
3
  ${this.options.title}
4
4
  `)),this.fleetBar=this.multiBar.create(100,0,{name:o.white("Fleet Progress".padEnd(30)),status:"",eta:""})}addAgent(e){if(!this.isActive)return;this.agentStates.set(e.id,e);let t=this.multiBar.create(100,e.progress,{name:o.gray(this.truncateName(e.name,30).padEnd(30)),status:this.getStatusIcon(e.status),eta:e.eta?this.formatEta(e.eta):""});this.agentBars.set(e.id,t),this.updateFleetProgress()}updateAgent(e,t,r){if(!this.isActive)return;let n=this.agentStates.get(e),i=this.agentBars.get(e);!n||!i||(n.progress=Math.min(100,Math.max(0,t)),r?.status&&(n.status=r.status),r?.message&&(n.message=r.message),r?.eta!==void 0&&(n.eta=r.eta),i.update(n.progress,{name:this.getAgentNameDisplay(n),status:this.getStatusIcon(n.status),eta:n.eta?this.formatEta(n.eta):""}),this.updateFleetProgress())}completeAgent(e,t=!0){if(!this.isActive)return;let r=this.agentStates.get(e),n=this.agentBars.get(e);!r||!n||(r.status=t?"completed":"failed",r.progress=t?100:r.progress,n.update(r.progress,{name:this.getAgentNameDisplay(r),status:this.getStatusIcon(r.status),eta:""}),this.updateFleetProgress())}stop(){if(!this.isActive)return;this.isActive=!1,this.multiBar.stop();let e=Array.from(this.agentStates.values()).filter(i=>i.status==="completed").length,t=Array.from(this.agentStates.values()).filter(i=>i.status==="failed").length,r=this.agentStates.size,n=Date.now()-this.startTime;console.log(""),console.log(t===0?o.green(`All ${e}/${r} agents completed successfully (${this.formatDuration(n)})`):o.yellow(`${e}/${r} agents completed, ${t} failed (${this.formatDuration(n)})`)),console.log("")}updateFleetProgress(){if(!this.fleetBar)return;let e=Array.from(this.agentStates.values()),t=e.reduce((a,l)=>a+l.progress,0),r=e.length>0?Math.round(t/e.length):0,n=e.filter(a=>a.status==="completed").length,i=e.filter(a=>a.status==="running").length;this.fleetBar.update(r,{status:o.gray(`${n}/${e.length} complete, ${i} running`),eta:this.options.showEta?this.estimateFleetEta(e):""})}getAgentNameDisplay(e){let t=this.truncateName(e.name,26);switch(e.status){case"completed":return o.green(t.padEnd(30));case"failed":return o.red(t.padEnd(30));case"running":return o.yellow(t.padEnd(30));default:return o.gray(t.padEnd(30))}}getStatusIcon(e){switch(e){case"completed":return o.green("\u2713");case"failed":return o.red("\u2717");case"running":return o.yellow("\u25B6");default:return o.gray("\u25CB")}}truncateName(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}formatEta(e){return e<=0?"":e<1e3?`${e}ms`:e<6e4?`${Math.round(e/1e3)}s`:e<36e5?`${Math.round(e/6e4)}m`:`${Math.round(e/36e5)}h`}formatDuration(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:e<36e5?`${(e/6e4).toFixed(1)}m`:`${(e/36e5).toFixed(1)}h`}estimateFleetEta(e){let t=e.filter(a=>a.status==="running"||a.status==="pending");if(t.length===0)return"";let r=t.map(a=>a.eta||0).filter(a=>a>0);if(r.length>0){let a=Math.max(...r);return o.gray(`ETA: ${this.formatEta(a)}`)}let n=Date.now()-this.startTime,i=t.reduce((a,l)=>a+l.progress,0)/t.length;if(i>0){let a=n/(i/100),l=Math.max(0,a-n);return o.gray(`ETA: ${this.formatEta(l)}`)}return""}};function X(s){let e=Date.now(),t=O({text:s,color:"cyan"}).start(),r=setInterval(()=>{let i=((Date.now()-e)/1e3).toFixed(1);t.text=`${s} (${i}s)`},100);r.unref?.();let n=()=>{clearInterval(r)};return{spinner:t,stop:()=>{n(),t.stop()},succeed:i=>{n();let a=((Date.now()-e)/1e3).toFixed(1);t.succeed(i||`${s} (${a}s)`)},fail:i=>{n();let a=((Date.now()-e)/1e3).toFixed(1);t.fail(i||`${s} failed (${a}s)`)}}}export{b as a,X as b};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.0");process.exit(0)}
2
- import{a as b}from"./chunk-PERJO2DY.js";import{a as te,b as ne}from"./chunk-RJZRWVL4.js";import{b as ee}from"./chunk-4BDLD7V2.js";import{b as E,d as ve}from"./chunk-2DIT5AUU.js";import{a as k,c as T}from"./chunk-CYL2FV23.js";var ke={M:16,efConstruction:200,efSearch:100},P={enabled:!0,pretrainedPatterns:!0,hnswConfig:ke,promotionThreshold:3,qualityThreshold:.7,embeddingModel:"auto"},_={mode:"hybrid",confidenceThreshold:.7,feedbackEnabled:!0,cacheEnabled:!0,cacheTTLMs:300*1e3},F={enabled:["pattern-consolidator","coverage-gap-scanner","flaky-test-detector","routing-accuracy-monitor"],intervals:{"pattern-consolidator":1800*1e3,"coverage-gap-scanner":3600*1e3,"flaky-test-detector":7200*1e3,"routing-accuracy-monitor":900*1e3},maxConcurrent:4,daemonAutoStart:!0},$={claudeCode:!0,preCommit:!1,ciIntegration:!1},N={install:!0,installV2:!0,installV3:!0,overwrite:!1},O={enabled:!0,parameters:["hnsw.efSearch","routing.confidenceThreshold","pattern.promotionThreshold","testGen.complexityLimit"],tuningIntervalMs:10080*60*1e3,evaluationPeriodMs:5e3};var L=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization","enterprise-integration"];function M(){return"3.13.0"}function Ve(r,e){return{version:M(),project:{name:r,root:e,type:"single"},learning:P,routing:_,workers:F,hooks:$,skills:N,autoTuning:O,domains:{enabled:L,disabled:[]},agents:{maxConcurrent:15,defaultTimeout:6e4}}}ve();import{readFileSync as C,existsSync as p,statSync as be,readdirSync as xe}from"fs";import{join as g,basename as re,extname as ie,relative as V}from"path";var Se=[{name:"jest",detect:r=>{let e=["jest.config.js","jest.config.ts","jest.config.mjs","jest.config.cjs"];for(let n of e)if(p(g(r,n)))return{name:"jest",version:A(r,"jest"),configFile:n,confidence:1};let t=S(r);return t?.jest?{name:"jest",version:A(r,"jest"),configFile:"package.json",confidence:.9}:t?.devDependencies?.jest||t?.dependencies?.jest?{name:"jest",version:t.devDependencies?.jest||t.dependencies?.jest,confidence:.7}:null}},{name:"vitest",detect:r=>{let e=["vitest.config.ts","vitest.config.js","vitest.config.mts","vite.config.ts"];for(let n of e)if(p(g(r,n)))return{name:"vitest",version:A(r,"vitest"),configFile:n,confidence:1};let t=S(r);return t?.devDependencies?.vitest||t?.dependencies?.vitest?{name:"vitest",version:t.devDependencies?.vitest,confidence:.8}:null}},{name:"mocha",detect:r=>{let e=[".mocharc.js",".mocharc.json",".mocharc.yaml",".mocharc.yml"];for(let n of e)if(p(g(r,n)))return{name:"mocha",version:A(r,"mocha"),configFile:n,confidence:1};let t=S(r);return t?.devDependencies?.mocha?{name:"mocha",version:t.devDependencies?.mocha,confidence:.8}:null}},{name:"pytest",detect:r=>{let e=["pytest.ini","pyproject.toml","setup.cfg"];for(let n of e){let i=g(r,n);if(p(i))try{let s=C(i,"utf-8");if(s.includes("[pytest]")||s.includes("[tool.pytest]"))return{name:"pytest",configFile:n,confidence:1}}catch(s){console.debug("[ProjectAnalyzer] Config read failed:",s instanceof Error?s.message:s)}}let t=g(r,"requirements.txt");if(p(t))try{if(C(t,"utf-8").includes("pytest"))return{name:"pytest",configFile:"requirements.txt",confidence:.8}}catch(n){console.debug("[ProjectAnalyzer] requirements.txt read failed:",n instanceof Error?n.message:n)}return null}},{name:"playwright",detect:r=>{let e=["playwright.config.ts","playwright.config.js"];for(let n of e)if(p(g(r,n)))return{name:"playwright",version:A(r,"@playwright/test"),configFile:n,confidence:1};let t=S(r);return t?.devDependencies?.["@playwright/test"]?{name:"playwright",version:t.devDependencies["@playwright/test"],confidence:.8}:null}},{name:"cypress",detect:r=>{let e=["cypress.config.ts","cypress.config.js","cypress.json"];for(let t of e)if(p(g(r,t)))return{name:"cypress",version:A(r,"cypress"),configFile:t,confidence:1};return p(g(r,"cypress"))?{name:"cypress",configFile:"cypress/",confidence:.9}:null}}],Ae=[{name:"typescript",extensions:[".ts",".tsx",".mts",".cts"]},{name:"javascript",extensions:[".js",".jsx",".mjs",".cjs"]},{name:"python",extensions:[".py",".pyw"]},{name:"java",extensions:[".java"]},{name:"go",extensions:[".go"]},{name:"rust",extensions:[".rs"]},{name:"csharp",extensions:[".cs"]},{name:"ruby",extensions:[".rb"]},{name:"php",extensions:[".php"]},{name:"kotlin",extensions:[".kt",".kts"]},{name:"swift",extensions:[".swift"]}];function S(r){let e=g(r,"package.json");if(!p(e))return null;try{return E(C(e,"utf-8"))}catch{return null}}function A(r,e){let t=S(r);if(t)return t.devDependencies?.[e]||t.dependencies?.[e]}function Q(r,e,t={}){let{maxDepth:n=10,exclude:i=["node_modules",".git","dist","build","coverage",".next","__pycache__"]}=t;function s(o,a){if(a>n)return;let l;try{l=xe(o)}catch{return}for(let u of l){if(i.includes(u))continue;let c=g(o,u),x;try{x=be(c)}catch{continue}x.isDirectory()?s(c,a+1):x.isFile()&&e(c)}}s(r,0)}var W=class{projectRoot;constructor(e){this.projectRoot=e}async analyze(){let e=Date.now(),[t,n,i,s,o]=await Promise.all([this.detectFrameworks(),this.detectLanguages(),this.detectExistingTests(),this.analyzeComplexity(),this.measureCoverage()]);return{projectName:S(this.projectRoot)?.name||re(this.projectRoot),projectRoot:this.projectRoot,projectType:this.detectProjectType(),frameworks:t,languages:n,existingTests:i,codeComplexity:s,coverage:o,packageManager:this.detectPackageManager(),hasTypeScript:p(g(this.projectRoot,"tsconfig.json")),hasCIConfig:this.detectCIConfig(),ciProvider:this.detectCIProvider(),analysisTimestamp:new Date,analysisDurationMs:Date.now()-e}}async detectFrameworks(){let e=[];for(let t of Se){let n=t.detect(this.projectRoot);n&&e.push(n)}return e.sort((t,n)=>n.confidence-t.confidence)}async detectLanguages(){let e=new Map,t=0;Q(this.projectRoot,i=>{let s=ie(i).toLowerCase();if(s){for(let o of Ae)if(o.extensions.includes(s)){let a=e.get(o.name)||{count:0,extensions:new Set};a.count++,a.extensions.add(s),e.set(o.name,a),t++;break}}});let n=[];for(let[i,s]of e)n.push({name:i,percentage:t>0?Math.round(s.count/t*100):0,fileCount:s.count,extensions:Array.from(s.extensions)});return n.sort((i,s)=>s.fileCount-i.fileCount)}async detectExistingTests(){let e={totalCount:0,byFramework:{},byType:{unit:0,integration:0,e2e:0,unknown:0},directories:[]},t=new Set,n=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/_test\.[jt]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/,/.*Test\.java$/];return Q(this.projectRoot,i=>{let s=re(i);if(n.some(a=>a.test(s))){e.totalCount++;let a=V(this.projectRoot,i).toLowerCase();a.includes("e2e")||a.includes("cypress")||a.includes("playwright")?e.byType.e2e++:a.includes("integration")||a.includes("int-test")?e.byType.integration++:a.includes("unit")||a.includes("__tests__")||a.includes("test/")?e.byType.unit++:e.byType.unknown++;let l=V(this.projectRoot,g(i,".."));t.add(l)}}),e.directories=Array.from(t).slice(0,10),e}async analyzeComplexity(){let e=[],t=[],n=0,i=0;Q(this.projectRoot,a=>{let l=ie(a);if([".ts",".tsx",".js",".jsx",".py",".java",".go"].includes(l))try{let u=C(a,"utf-8"),c=this.calculateFileComplexity(u,l);t.push(...c.functionComplexities),c.maxComplexity>n&&(n=c.maxComplexity),i++,c.maxComplexity>10&&e.push(V(this.projectRoot,a))}catch(u){console.debug("[ProjectAnalyzer] Complexity analysis read failed:",u instanceof Error?u.message:u)}});let s=t.reduce((a,l)=>a+l,0),o=t.length>0?s/t.length:0;return{averageCyclomatic:Math.round(o*10)/10,maxCyclomatic:n,totalFiles:i,complexFiles:e.slice(0,20),recommendation:o<5?"simple":o<15?"medium":"complex"}}calculateFileComplexity(e,t){let n=this.stripCommentsAndStrings(e,t),i=this.calculateComplexity(n);return{functionComplexities:[i],maxComplexity:i}}removeDelimitedBlocks(e,t,n){let i="",s=0;for(;s<e.length;){let o=e.indexOf(t,s);if(o===-1){i+=e.slice(s);break}i+=e.slice(s,o);let a=e.indexOf(n,o+t.length);if(a===-1)break;s=a+n.length}return i}stripCommentsAndStrings(e,t){let n=e;return[".ts",".tsx",".js",".jsx",".java",".go"].includes(t)?(n=n.split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
2
+ import{a as b}from"./chunk-IMQKEFW6.js";import{a as te,b as ne}from"./chunk-LJQ27PUE.js";import{b as ee}from"./chunk-TDGE52HJ.js";import{b as E,d as ve}from"./chunk-ZLCATRXI.js";import{a as k,c as T}from"./chunk-AYYDO52G.js";var ke={M:16,efConstruction:200,efSearch:100},P={enabled:!0,pretrainedPatterns:!0,hnswConfig:ke,promotionThreshold:3,qualityThreshold:.7,embeddingModel:"auto"},_={mode:"hybrid",confidenceThreshold:.7,feedbackEnabled:!0,cacheEnabled:!0,cacheTTLMs:300*1e3},F={enabled:["pattern-consolidator","coverage-gap-scanner","flaky-test-detector","routing-accuracy-monitor"],intervals:{"pattern-consolidator":1800*1e3,"coverage-gap-scanner":3600*1e3,"flaky-test-detector":7200*1e3,"routing-accuracy-monitor":900*1e3},maxConcurrent:4,daemonAutoStart:!0},$={claudeCode:!0,preCommit:!1,ciIntegration:!1},N={install:!0,installV2:!0,installV3:!0,overwrite:!1},O={enabled:!0,parameters:["hnsw.efSearch","routing.confidenceThreshold","pattern.promotionThreshold","testGen.complexityLimit"],tuningIntervalMs:10080*60*1e3,evaluationPeriodMs:5e3};var L=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization","enterprise-integration"];function M(){return"3.13.1"}function Ve(r,e){return{version:M(),project:{name:r,root:e,type:"single"},learning:P,routing:_,workers:F,hooks:$,skills:N,autoTuning:O,domains:{enabled:L,disabled:[]},agents:{maxConcurrent:15,defaultTimeout:6e4}}}ve();import{readFileSync as C,existsSync as p,statSync as be,readdirSync as xe}from"fs";import{join as g,basename as re,extname as ie,relative as V}from"path";var Se=[{name:"jest",detect:r=>{let e=["jest.config.js","jest.config.ts","jest.config.mjs","jest.config.cjs"];for(let n of e)if(p(g(r,n)))return{name:"jest",version:A(r,"jest"),configFile:n,confidence:1};let t=S(r);return t?.jest?{name:"jest",version:A(r,"jest"),configFile:"package.json",confidence:.9}:t?.devDependencies?.jest||t?.dependencies?.jest?{name:"jest",version:t.devDependencies?.jest||t.dependencies?.jest,confidence:.7}:null}},{name:"vitest",detect:r=>{let e=["vitest.config.ts","vitest.config.js","vitest.config.mts","vite.config.ts"];for(let n of e)if(p(g(r,n)))return{name:"vitest",version:A(r,"vitest"),configFile:n,confidence:1};let t=S(r);return t?.devDependencies?.vitest||t?.dependencies?.vitest?{name:"vitest",version:t.devDependencies?.vitest,confidence:.8}:null}},{name:"mocha",detect:r=>{let e=[".mocharc.js",".mocharc.json",".mocharc.yaml",".mocharc.yml"];for(let n of e)if(p(g(r,n)))return{name:"mocha",version:A(r,"mocha"),configFile:n,confidence:1};let t=S(r);return t?.devDependencies?.mocha?{name:"mocha",version:t.devDependencies?.mocha,confidence:.8}:null}},{name:"pytest",detect:r=>{let e=["pytest.ini","pyproject.toml","setup.cfg"];for(let n of e){let i=g(r,n);if(p(i))try{let s=C(i,"utf-8");if(s.includes("[pytest]")||s.includes("[tool.pytest]"))return{name:"pytest",configFile:n,confidence:1}}catch(s){console.debug("[ProjectAnalyzer] Config read failed:",s instanceof Error?s.message:s)}}let t=g(r,"requirements.txt");if(p(t))try{if(C(t,"utf-8").includes("pytest"))return{name:"pytest",configFile:"requirements.txt",confidence:.8}}catch(n){console.debug("[ProjectAnalyzer] requirements.txt read failed:",n instanceof Error?n.message:n)}return null}},{name:"playwright",detect:r=>{let e=["playwright.config.ts","playwright.config.js"];for(let n of e)if(p(g(r,n)))return{name:"playwright",version:A(r,"@playwright/test"),configFile:n,confidence:1};let t=S(r);return t?.devDependencies?.["@playwright/test"]?{name:"playwright",version:t.devDependencies["@playwright/test"],confidence:.8}:null}},{name:"cypress",detect:r=>{let e=["cypress.config.ts","cypress.config.js","cypress.json"];for(let t of e)if(p(g(r,t)))return{name:"cypress",version:A(r,"cypress"),configFile:t,confidence:1};return p(g(r,"cypress"))?{name:"cypress",configFile:"cypress/",confidence:.9}:null}}],Ae=[{name:"typescript",extensions:[".ts",".tsx",".mts",".cts"]},{name:"javascript",extensions:[".js",".jsx",".mjs",".cjs"]},{name:"python",extensions:[".py",".pyw"]},{name:"java",extensions:[".java"]},{name:"go",extensions:[".go"]},{name:"rust",extensions:[".rs"]},{name:"csharp",extensions:[".cs"]},{name:"ruby",extensions:[".rb"]},{name:"php",extensions:[".php"]},{name:"kotlin",extensions:[".kt",".kts"]},{name:"swift",extensions:[".swift"]}];function S(r){let e=g(r,"package.json");if(!p(e))return null;try{return E(C(e,"utf-8"))}catch{return null}}function A(r,e){let t=S(r);if(t)return t.devDependencies?.[e]||t.dependencies?.[e]}function Q(r,e,t={}){let{maxDepth:n=10,exclude:i=["node_modules",".git","dist","build","coverage",".next","__pycache__"]}=t;function s(o,a){if(a>n)return;let l;try{l=xe(o)}catch{return}for(let u of l){if(i.includes(u))continue;let c=g(o,u),x;try{x=be(c)}catch{continue}x.isDirectory()?s(c,a+1):x.isFile()&&e(c)}}s(r,0)}var W=class{projectRoot;constructor(e){this.projectRoot=e}async analyze(){let e=Date.now(),[t,n,i,s,o]=await Promise.all([this.detectFrameworks(),this.detectLanguages(),this.detectExistingTests(),this.analyzeComplexity(),this.measureCoverage()]);return{projectName:S(this.projectRoot)?.name||re(this.projectRoot),projectRoot:this.projectRoot,projectType:this.detectProjectType(),frameworks:t,languages:n,existingTests:i,codeComplexity:s,coverage:o,packageManager:this.detectPackageManager(),hasTypeScript:p(g(this.projectRoot,"tsconfig.json")),hasCIConfig:this.detectCIConfig(),ciProvider:this.detectCIProvider(),analysisTimestamp:new Date,analysisDurationMs:Date.now()-e}}async detectFrameworks(){let e=[];for(let t of Se){let n=t.detect(this.projectRoot);n&&e.push(n)}return e.sort((t,n)=>n.confidence-t.confidence)}async detectLanguages(){let e=new Map,t=0;Q(this.projectRoot,i=>{let s=ie(i).toLowerCase();if(s){for(let o of Ae)if(o.extensions.includes(s)){let a=e.get(o.name)||{count:0,extensions:new Set};a.count++,a.extensions.add(s),e.set(o.name,a),t++;break}}});let n=[];for(let[i,s]of e)n.push({name:i,percentage:t>0?Math.round(s.count/t*100):0,fileCount:s.count,extensions:Array.from(s.extensions)});return n.sort((i,s)=>s.fileCount-i.fileCount)}async detectExistingTests(){let e={totalCount:0,byFramework:{},byType:{unit:0,integration:0,e2e:0,unknown:0},directories:[]},t=new Set,n=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/_test\.[jt]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/,/.*Test\.java$/];return Q(this.projectRoot,i=>{let s=re(i);if(n.some(a=>a.test(s))){e.totalCount++;let a=V(this.projectRoot,i).toLowerCase();a.includes("e2e")||a.includes("cypress")||a.includes("playwright")?e.byType.e2e++:a.includes("integration")||a.includes("int-test")?e.byType.integration++:a.includes("unit")||a.includes("__tests__")||a.includes("test/")?e.byType.unit++:e.byType.unknown++;let l=V(this.projectRoot,g(i,".."));t.add(l)}}),e.directories=Array.from(t).slice(0,10),e}async analyzeComplexity(){let e=[],t=[],n=0,i=0;Q(this.projectRoot,a=>{let l=ie(a);if([".ts",".tsx",".js",".jsx",".py",".java",".go"].includes(l))try{let u=C(a,"utf-8"),c=this.calculateFileComplexity(u,l);t.push(...c.functionComplexities),c.maxComplexity>n&&(n=c.maxComplexity),i++,c.maxComplexity>10&&e.push(V(this.projectRoot,a))}catch(u){console.debug("[ProjectAnalyzer] Complexity analysis read failed:",u instanceof Error?u.message:u)}});let s=t.reduce((a,l)=>a+l,0),o=t.length>0?s/t.length:0;return{averageCyclomatic:Math.round(o*10)/10,maxCyclomatic:n,totalFiles:i,complexFiles:e.slice(0,20),recommendation:o<5?"simple":o<15?"medium":"complex"}}calculateFileComplexity(e,t){let n=this.stripCommentsAndStrings(e,t),i=this.calculateComplexity(n);return{functionComplexities:[i],maxComplexity:i}}removeDelimitedBlocks(e,t,n){let i="",s=0;for(;s<e.length;){let o=e.indexOf(t,s);if(o===-1){i+=e.slice(s);break}i+=e.slice(s,o);let a=e.indexOf(n,o+t.length);if(a===-1)break;s=a+n.length}return i}stripCommentsAndStrings(e,t){let n=e;return[".ts",".tsx",".js",".jsx",".java",".go"].includes(t)?(n=n.split(`
3
3
  `).map(i=>{let s=i.indexOf("//");return s>=0?i.slice(0,s):i}).join(`
4
4
  `),n=this.removeDelimitedBlocks(n,"/*","*/"),n=this.removeDelimitedBlocks(n,"`","`"),n=this.removeDelimitedBlocks(n,'"','"'),n=this.removeDelimitedBlocks(n,"'","'")):t===".py"&&(n=n.split(`
5
5
  `).map(i=>{let s=i.indexOf("#");return s>=0?i.slice(0,s):i}).join(`
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.0");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
2
2
  import{existsSync as _,readdirSync as d,statSync as w}from"fs";import{join as i,extname as E}from"path";var T=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".pyw",".go",".rs",".java",".kt",".kts",".rb",".cs",".php",".swift",".c",".h",".cpp",".hpp",".cc",".scala"]),v=[".test.",".spec.","_test.","_spec."],b=new Set(["node_modules","dist","build","coverage",".git","__pycache__",".venv","venv",".tox",".mypy_cache","target",".gradle","vendor",".bundle",".next",".nuxt",".output"]);function O(s,p={}){let{maxDepth:f=6,includeTests:m=!1,testsOnly:x=!1,extraExtensions:S=[]}=p;if(!_(s))return[];let o=w(s);if(o.isFile())return[s];if(!o.isDirectory())return[];let y=new Set(S.map(t=>t.startsWith(".")?t:`.${t}`)),n=[];function r(t,c){if(c>f)return;let a;try{a=d(t,{withFileTypes:!0})}catch{return}for(let e of a)if(e.isDirectory()){if(b.has(e.name))continue;r(i(t,e.name),c+1)}else if(e.isFile()){let u=E(e.name).toLowerCase();if(!(T.has(u)||y.has(u))||e.name.endsWith(".d.ts"))continue;let l=v.some(h=>e.name.includes(h))||e.name.startsWith("test_");x?l&&n.push(i(t,e.name)):(m||!l)&&n.push(i(t,e.name))}}return r(s,0),n}export{T as a,O as b};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.0");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
2
2
  var h={0:"sqlite-only",1:"hybrid",2:"dual-write-sqlite-primary",3:"dual-write-rvf-primary",4:"rvf-primary"},g=class{config;db=null;rvfStore=null;totalWrites=0;totalReads=0;rvfWriteFailures=0;rvfReadFailures=0;fallbacksUsed=0;sqliteLatencies=[];rvfLatencies=[];sqliteWriteLatencies=[];rvfWriteLatencies=[];constructor(e){this.config={rvfPath:".agentic-qe/patterns.rvf",dimensions:384,enableFallback:!0,...e}}setSqliteDb(e){this.db=e}setRvfStore(e){this.rvfStore=e}get stage(){return this.config.stage}setStage(e){this.config={...this.config,stage:e}}write(e,t){this.totalWrites++;let s={sqliteSuccess:!1,rvfSuccess:!1,stage:this.config.stage,fallbackUsed:!1},n=this.config.stage<4,o=this.config.stage>=2;if(n&&this.db){let i=performance.now();try{let r=Buffer.from(t instanceof Float32Array?t.buffer:new Float32Array(t).buffer);this.db.prepare(`
3
3
  INSERT INTO qe_pattern_embeddings (pattern_id, embedding, dimension, model, created_at)
4
4
  VALUES (?, ?, ?, 'all-MiniLM-L6-v2', datetime('now'))
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.0");process.exit(0)}
2
- import{b as m,c as y}from"./chunk-NUQBJGGF.js";import{e as S,f as A}from"./chunk-KUA4HHU6.js";import{a as R,b as g,c as v}from"./chunk-G7FMYFTN.js";import{a as p,g as b}from"./chunk-ES7WCYOU.js";y();var s=null,f=!1;function w(t){s=t,f=t!==null}var E=(()=>{let t=process.env.AQE_RVF_SIZE_GUARD_BYTES,r=t?Number(t):NaN;return Number.isFinite(r)&&r>0?r:256*1024*1024})(),C=(()=>{let t=process.env.AQE_RVF_DEAD_RATIO_THRESHOLD,r=t?Number(t):NaN;return Number.isFinite(r)&&r>0&&r<=1?r:.3})();function _(t=".agentic-qe",r=384){if(f)return s;f=!0;try{let{isRvfNativeAvailable:e,createRvfStore:o,openRvfStore:i}=(A(),b(S));if(!e())return console.warn("[RVF] Native bindings unavailable \u2014 agent branching and dream COW disabled. Install @ruvector/rvf-node to enable."),null;let l=p("path"),c=l.isAbsolute(t)?t:l.join(process.env.AQE_PROJECT_ROOT??m(),t),u=l.join(c,"patterns.rvf");return s=$(i,o,u,r),N(s,u),s}catch(e){return console.warn("[RVF] Shared adapter init failed:",e instanceof Error?e.message:e),null}}function $(t,r,e,o){let i=()=>{try{return{adapter:t(e),err:null}}catch(n){return{adapter:null,err:n}}},l=n=>{let a=n instanceof Error?n.message:String(n);return a.includes("LockHeld")||a.includes("0x0300")},{adapter:c,err:u}=i();if(!c&&l(u))try{let n=p("fs"),a=`${e}.lock`;n.existsSync(a)&&g(e)?console.warn(`[RVF] ${e} is locked by a live process (pid ${R(e)}) \u2014 not breaking the lock; degrading to SQLite for this run.`):n.existsSync(a)&&(n.unlinkSync(a),console.warn(`[RVF] Removed stale lock file at ${a} (prior process exited without closing). Retrying open. If you see this repeatedly under live concurrency, file an issue.`),{adapter:c,err:u}=i())}catch(n){process.env.DEBUG&&console.debug("[RVF] stale-lock recovery failed:",n instanceof Error?n.message:n)}if(c){let n=c.dimension();if(n===o)return c;console.warn(`[RVF] patterns.rvf dimension mismatch: file=${n} requested=${o} \u2014 closing and degrading. Delete the .rvf file to recreate at the requested dim.`);try{c.close()}catch{}throw new Error(`RVF dimension mismatch (file=${n}, requested=${o})`)}try{return r(e,o)}catch(n){try{let a=t(e);if(a.dimension()!==o){try{a.close()}catch{}throw new Error(`RVF dimension mismatch after race (file=${a.dimension()}, requested=${o})`)}return a}catch{if(v(e,n instanceof Error?n.message:String(n)))return r(e,o);throw n instanceof Error?n:new Error(String(n))}}}function h(t,r){if(r?.force)return{shouldCompact:!0,trigger:"force"};let e=r?.sizeGuardBytes??E,o=r?.deadRatioThreshold??C;return t.fileSizeBytes>=e?{shouldCompact:!0,trigger:"size-guard"}:(t.deadSpaceRatio??0)>=o?{shouldCompact:!0,trigger:"dead-ratio"}:{shouldCompact:!1,trigger:"none"}}function k(t){if(!s)return null;let r;try{r=s.status()}catch{return null}let e=h(r,t);if(!e.shouldCompact)return null;let o=r.fileSizeBytes,i;try{i=s.compact()}catch{return null}return i?((i.bytesReclaimed>0||i.segmentsCompacted>0)&&console.log(`[RVF] compacted patterns.rvf: reclaimed ${d(i.bytesReclaimed)} (${i.segmentsCompacted} segments, fileSize ${d(o)} \u2192 ${d(Math.max(0,o-i.bytesReclaimed))}, trigger: ${e.trigger})`),i):null}function N(t,r){try{let e=t.status(),o=h(e);if(!o.shouldCompact)return null;let i=t.compact();return i&&(i.bytesReclaimed>0||i.segmentsCompacted>0)&&console.log(`[RVF] boot-time compact (${r}): reclaimed ${d(i.bytesReclaimed)} from ${i.segmentsCompacted} segments (trigger: ${o.trigger})`),i}catch(e){return process.env.DEBUG&&console.debug("[RVF] boot-time compact guard skipped:",e instanceof Error?e.message:e),null}}function d(t){if(!Number.isFinite(t)||t<0)return`${t}B`;let r=["B","KB","MB","GB","TB"],e=0,o=t;for(;o>=1024&&e<r.length-1;)o/=1024,e++;return`${o.toFixed(e===0?0:1)}${r[e]}`}function T(){if(s){try{s.close()}catch{}s=null}f=!1}export{w as a,_ as b,h as c,k as d,N as e,T as f};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
2
+ import{b as m,c as y}from"./chunk-YBPCBFEE.js";import{e as S,f as A}from"./chunk-55WDVSCM.js";import{a as R,b as g,c as v}from"./chunk-QES4QHQW.js";import{a as p,g as b}from"./chunk-OE4B6LDZ.js";y();var s=null,f=!1;function w(t){s=t,f=t!==null}var E=(()=>{let t=process.env.AQE_RVF_SIZE_GUARD_BYTES,r=t?Number(t):NaN;return Number.isFinite(r)&&r>0?r:256*1024*1024})(),C=(()=>{let t=process.env.AQE_RVF_DEAD_RATIO_THRESHOLD,r=t?Number(t):NaN;return Number.isFinite(r)&&r>0&&r<=1?r:.3})();function _(t=".agentic-qe",r=384){if(f)return s;f=!0;try{let{isRvfNativeAvailable:e,createRvfStore:o,openRvfStore:i}=(A(),b(S));if(!e())return console.warn("[RVF] Native bindings unavailable \u2014 agent branching and dream COW disabled. Install @ruvector/rvf-node to enable."),null;let l=p("path"),c=l.isAbsolute(t)?t:l.join(process.env.AQE_PROJECT_ROOT??m(),t),u=l.join(c,"patterns.rvf");return s=$(i,o,u,r),N(s,u),s}catch(e){return console.warn("[RVF] Shared adapter init failed:",e instanceof Error?e.message:e),null}}function $(t,r,e,o){let i=()=>{try{return{adapter:t(e),err:null}}catch(n){return{adapter:null,err:n}}},l=n=>{let a=n instanceof Error?n.message:String(n);return a.includes("LockHeld")||a.includes("0x0300")},{adapter:c,err:u}=i();if(!c&&l(u))try{let n=p("fs"),a=`${e}.lock`;n.existsSync(a)&&g(e)?console.warn(`[RVF] ${e} is locked by a live process (pid ${R(e)}) \u2014 not breaking the lock; degrading to SQLite for this run.`):n.existsSync(a)&&(n.unlinkSync(a),console.warn(`[RVF] Removed stale lock file at ${a} (prior process exited without closing). Retrying open. If you see this repeatedly under live concurrency, file an issue.`),{adapter:c,err:u}=i())}catch(n){process.env.DEBUG&&console.debug("[RVF] stale-lock recovery failed:",n instanceof Error?n.message:n)}if(c){let n=c.dimension();if(n===o)return c;console.warn(`[RVF] patterns.rvf dimension mismatch: file=${n} requested=${o} \u2014 closing and degrading. Delete the .rvf file to recreate at the requested dim.`);try{c.close()}catch{}throw new Error(`RVF dimension mismatch (file=${n}, requested=${o})`)}try{return r(e,o)}catch(n){try{let a=t(e);if(a.dimension()!==o){try{a.close()}catch{}throw new Error(`RVF dimension mismatch after race (file=${a.dimension()}, requested=${o})`)}return a}catch{if(v(e,n instanceof Error?n.message:String(n)))return r(e,o);throw n instanceof Error?n:new Error(String(n))}}}function h(t,r){if(r?.force)return{shouldCompact:!0,trigger:"force"};let e=r?.sizeGuardBytes??E,o=r?.deadRatioThreshold??C;return t.fileSizeBytes>=e?{shouldCompact:!0,trigger:"size-guard"}:(t.deadSpaceRatio??0)>=o?{shouldCompact:!0,trigger:"dead-ratio"}:{shouldCompact:!1,trigger:"none"}}function k(t){if(!s)return null;let r;try{r=s.status()}catch{return null}let e=h(r,t);if(!e.shouldCompact)return null;let o=r.fileSizeBytes,i;try{i=s.compact()}catch{return null}return i?((i.bytesReclaimed>0||i.segmentsCompacted>0)&&console.log(`[RVF] compacted patterns.rvf: reclaimed ${d(i.bytesReclaimed)} (${i.segmentsCompacted} segments, fileSize ${d(o)} \u2192 ${d(Math.max(0,o-i.bytesReclaimed))}, trigger: ${e.trigger})`),i):null}function N(t,r){try{let e=t.status(),o=h(e);if(!o.shouldCompact)return null;let i=t.compact();return i&&(i.bytesReclaimed>0||i.segmentsCompacted>0)&&console.log(`[RVF] boot-time compact (${r}): reclaimed ${d(i.bytesReclaimed)} from ${i.segmentsCompacted} segments (trigger: ${o.trigger})`),i}catch(e){return process.env.DEBUG&&console.debug("[RVF] boot-time compact guard skipped:",e instanceof Error?e.message:e),null}}function d(t){if(!Number.isFinite(t)||t<0)return`${t}B`;let r=["B","KB","MB","GB","TB"],e=0,o=t;for(;o>=1024&&e<r.length-1;)o/=1024,e++;return`${o.toFixed(e===0?0:1)}${r[e]}`}function T(){if(s){try{s.close()}catch{}s=null}f=!1}export{w as a,_ as b,h as c,k as d,N as e,T as f};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.0");process.exit(0)}
2
- import{a as j,c as V}from"./chunk-PP2RYSHT.js";import{a as U,b as W,d as G}from"./chunk-JPIBPKBP.js";import{b as F}from"./chunk-OETDMOOE.js";import{a as T,c as N}from"./chunk-CYL2FV23.js";import{b as D,c as $,d as Y}from"./chunk-RDU4WTV2.js";N();Y();import*as C from"fs";import*as b from"path";import*as H from"yaml";var z=5,X=4,Z=3e4,ee=".claude/skills",te=5e3,se=500,K=100,re=1e3,q=500,ne=.8,ae=.2,ie=.1,w=.1,oe=.1,le=.1,ce=.1,ue=200,de=500,pe=300,me=1,ge=.9,Q={maxWorkers:z,batchSize:X,retryFailedTests:!0,timeout:Z,skillsDir:ee,progressIntervalMs:te},S=class{async execute(e,r,s){let t=$(K,se+K);return await new Promise(i=>setTimeout(i,t)),{output:this.generateMockResponse(e),tokensUsed:D(q,re+q),durationMs:t}}generateMockResponse(e){let r=[];return e.includes("alt")&&r.push("alt","1.1.1","perceivable"),e.includes("contrast")&&r.push("contrast","1.4.3","4.5:1"),e.includes("keyboard")&&r.push("keyboard","2.1.1","operable","button"),e.includes("label")&&r.push("label","3.3.2","understandable"),e.includes("ARIA")&&r.push("ARIA","4.1.2","robust"),e.includes("focus")&&r.push("focus","2.4.7","outline"),e.includes("lang")&&r.push("lang","3.1.1","language"),e.includes("caption")&&r.push("caption","1.2.2","track"),e.includes("accessible")&&r.push("accessible","compliant"),r.length===0&&r.push("accessibility","WCAG","finding"),`Analysis complete. Found issues related to: ${r.join(", ")}.
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
2
+ import{a as j,c as V}from"./chunk-H7YZ2YF2.js";import{a as U,b as W,d as G}from"./chunk-THFLRJT6.js";import{b as F}from"./chunk-S6F3IJMK.js";import{a as T,c as N}from"./chunk-AYYDO52G.js";import{b as D,c as $,d as Y}from"./chunk-3K4YC3GC.js";N();Y();import*as C from"fs";import*as b from"path";import*as H from"yaml";var z=5,X=4,Z=3e4,ee=".claude/skills",te=5e3,se=500,K=100,re=1e3,q=500,ne=.8,ae=.2,ie=.1,w=.1,oe=.1,le=.1,ce=.1,ue=200,de=500,pe=300,me=1,ge=.9,Q={maxWorkers:z,batchSize:X,retryFailedTests:!0,timeout:Z,skillsDir:ee,progressIntervalMs:te},S=class{async execute(e,r,s){let t=$(K,se+K);return await new Promise(i=>setTimeout(i,t)),{output:this.generateMockResponse(e),tokensUsed:D(q,re+q),durationMs:t}}generateMockResponse(e){let r=[];return e.includes("alt")&&r.push("alt","1.1.1","perceivable"),e.includes("contrast")&&r.push("contrast","1.4.3","4.5:1"),e.includes("keyboard")&&r.push("keyboard","2.1.1","operable","button"),e.includes("label")&&r.push("label","3.3.2","understandable"),e.includes("ARIA")&&r.push("ARIA","4.1.2","robust"),e.includes("focus")&&r.push("focus","2.4.7","outline"),e.includes("lang")&&r.push("lang","3.1.1","language"),e.includes("caption")&&r.push("caption","1.2.2","track"),e.includes("accessible")&&r.push("accessible","compliant"),r.length===0&&r.push("accessibility","WCAG","finding"),`Analysis complete. Found issues related to: ${r.join(", ")}.
3
3
  Recommendations: Implement proper ${r[0]} attributes for better accessibility.
4
4
  Severity: ${e.includes("critical")?"critical":"serious"}`}},P=class{constructor(e,r,s){this.executor=r;this.config=s;this.id=e}executor;config;id;status="idle";tasksCompleted=0;tasksFailed=0;lastHeartbeat=Date.now();async executeBatch(e){this.status="running";let r=[];for(let s of e){this.lastHeartbeat=Date.now();try{let t=await this.executeTestCase(s);if(r.push(t),t.passed)this.tasksCompleted++;else if(this.tasksFailed++,this.config.retryFailedTests&&!t.passed){let a=await this.executeTestCase(s,!0);a.passed&&(r[r.length-1]=a,this.tasksCompleted++,this.tasksFailed--)}}catch(t){this.tasksFailed++,r.push({testId:s.testCaseId,passed:!1,expectedPatterns:s.testCase.expected_output.must_contain||[],actualPatterns:[],reasoningQuality:0,category:s.testCase.category,priority:s.testCase.priority,error:T(t)})}}return this.status="idle",r}async executeTestCase(e,r=!1){let s=Date.now(),t=this.buildPrompt(e),a=await this.executor.execute(t,e.model,{timeout:this.config.timeout}),i=this.validateResponse(a.output,e.testCase.expected_output,e.testCase.validation);return{testId:e.testCaseId,passed:i.passed,expectedPatterns:e.testCase.expected_output.must_contain||[],actualPatterns:i.foundPatterns,reasoningQuality:i.reasoningQuality,executionTimeMs:Date.now()-s,category:e.testCase.category,priority:e.testCase.priority,error:i.error}}buildPrompt(e){let{testCase:r}=e,s=r.input.context;return`Analyze the following ${s.language||"HTML"} code for accessibility issues.
5
5
  Context: ${s.description||r.description}