agentic-qe 3.12.3 → 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 (442) 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/.helpers-version +1 -1
  11. package/.claude/helpers/auto-memory-hook.mjs +430 -430
  12. package/.claude/helpers/helpers.manifest.json +6 -5
  13. package/.claude/helpers/hook-handler.cjs +565 -311
  14. package/.claude/helpers/intelligence.cjs +1058 -1058
  15. package/.claude/helpers/ruflo-hook.cjs +5 -1
  16. package/.claude/helpers/statusline.cjs +995 -682
  17. package/.claude/skills/qe-court/SKILL.md +186 -0
  18. package/.claude/skills/qe-court/config.json +27 -0
  19. package/.claude/skills/qe-court/evals/fixtures/seeded-mutant-delivery/README.md +38 -0
  20. package/.claude/skills/qe-court/evals/fixtures/seeded-mutant-delivery/budget.test.ts +21 -0
  21. package/.claude/skills/qe-court/evals/fixtures/seeded-mutant-delivery/budget.ts +25 -0
  22. package/.claude/skills/qe-court/evals/qe-court.yaml +70 -0
  23. package/.claude/skills/qe-court/schemas/output.json +92 -0
  24. package/.claude/skills/qe-court/scripts/validate-config.json +30 -0
  25. package/.claude/skills/skills-manifest.json +9 -8
  26. package/.codex/hooks/aqe-codex-hook.cjs +69 -0
  27. package/.codex/hooks/ruflo-codex-hook.cjs +94 -0
  28. package/.codex/hooks.json +169 -0
  29. package/CHANGELOG.md +159 -0
  30. package/README.md +3 -3
  31. package/assets/skills/qe-court/SKILL.md +186 -0
  32. package/assets/skills/qe-court/config.json +27 -0
  33. package/assets/skills/qe-court/evals/fixtures/seeded-mutant-delivery/README.md +38 -0
  34. package/assets/skills/qe-court/evals/fixtures/seeded-mutant-delivery/budget.test.ts +21 -0
  35. package/assets/skills/qe-court/evals/fixtures/seeded-mutant-delivery/budget.ts +25 -0
  36. package/assets/skills/qe-court/evals/qe-court.yaml +70 -0
  37. package/assets/skills/qe-court/schemas/output.json +92 -0
  38. package/assets/skills/qe-court/scripts/validate-config.json +30 -0
  39. package/assets/skills/skills-manifest.json +9 -8
  40. package/dist/cli/bundle.js +5 -5
  41. package/dist/cli/chunks/adapter-VRZNL53W.js +2 -0
  42. package/dist/cli/chunks/{agent-booster-wasm-XFAQATTH.js → agent-booster-wasm-4VM3DE42.js} +2 -2
  43. package/dist/cli/chunks/{agent-handler-2ZV4CA3U.js → agent-handler-ZDLMZQQX.js} +2 -2
  44. package/dist/cli/chunks/{agent-memory-branch-6WGP7F5T.js → agent-memory-branch-P72MDHHV.js} +2 -2
  45. package/dist/cli/chunks/aqe-learning-engine-XCNMNERX.js +2 -0
  46. package/dist/cli/chunks/{arena-FWX7XZAE.js → arena-55FZGKEV.js} +4 -4
  47. package/dist/cli/chunks/{arena-KJUNQK4N.js → arena-GCRBQ26R.js} +2 -2
  48. package/dist/cli/chunks/{audit-YFUDEOKN.js → audit-VYAYVLIV.js} +3 -3
  49. package/dist/cli/chunks/base-VZZNR4UR.js +2 -0
  50. package/dist/cli/chunks/{hnswlib-node-SKTT5KIH.js → better-sqlite3-JDDFYVCX.js} +2 -2
  51. package/dist/cli/chunks/{brain-handler-ZCK4WTPK.js → brain-handler-IUKMRGWO.js} +3 -3
  52. package/dist/cli/chunks/{branch-enumerator-HTVINRYG.js → branch-enumerator-TUI3RWLX.js} +2 -2
  53. package/dist/cli/chunks/{browser-WUL2B77M.js → browser-NBQTZYX2.js} +2 -2
  54. package/dist/cli/chunks/browser-workflow-5DZNIFUY.js +2 -0
  55. package/dist/cli/chunks/{chunk-IWQHQLT6.js → chunk-23MT7OBY.js} +2 -2
  56. package/dist/cli/chunks/{chunk-KE3RK35K.js → chunk-2CQAWYYE.js} +1 -1
  57. package/dist/cli/chunks/{chunk-ADQFQBFJ.js → chunk-2D2XFUKI.js} +2 -2
  58. package/dist/cli/chunks/{chunk-2YDZXFO2.js → chunk-2G2QWV7B.js} +2 -2
  59. package/dist/cli/chunks/{chunk-HGJQSTQD.js → chunk-2ISLQU3G.js} +1 -1
  60. package/dist/cli/chunks/{chunk-6E47R27C.js → chunk-2OM3TDC4.js} +1 -1
  61. package/dist/cli/chunks/{chunk-WQASUQ5P.js → chunk-2XZ4BHWS.js} +1 -1
  62. package/dist/cli/chunks/{chunk-E2U3LTGM.js → chunk-3F4XH4ZA.js} +1 -1
  63. package/dist/cli/chunks/{chunk-YUDGQZJN.js → chunk-3K4YC3GC.js} +2 -2
  64. package/dist/cli/chunks/chunk-3KGCBAUH.js +2 -0
  65. package/dist/cli/chunks/{chunk-PXCJDB7J.js → chunk-3Y6CHW67.js} +1 -1
  66. package/dist/cli/chunks/{chunk-MOX25RZQ.js → chunk-4QMWWYNU.js} +2 -2
  67. package/dist/cli/chunks/{chunk-XZGOXLZH.js → chunk-4WGSMODQ.js} +1 -1
  68. package/dist/cli/chunks/{chunk-2CPJCXV6.js → chunk-55WDVSCM.js} +2 -2
  69. package/dist/cli/chunks/{chunk-EHO52NKU.js → chunk-5BB5DUL4.js} +2 -2
  70. package/dist/cli/chunks/{chunk-BEPP57C2.js → chunk-6C3MZLYW.js} +2 -2
  71. package/dist/cli/chunks/{chunk-DTZFZ5M7.js → chunk-6QKQFHS7.js} +2 -2
  72. package/dist/cli/chunks/{chunk-KXKACV3E.js → chunk-6XZXMEK4.js} +3 -3
  73. package/dist/cli/chunks/{chunk-L6GZGEFQ.js → chunk-7D7XFZZI.js} +2 -2
  74. package/dist/cli/chunks/{chunk-NLDLUHOF.js → chunk-7WEHZCSK.js} +2 -2
  75. package/dist/cli/chunks/{chunk-TXLPOXAN.js → chunk-A2MG3YXO.js} +1 -1
  76. package/dist/cli/chunks/{chunk-HJ2LG5IH.js → chunk-AHTOWWSE.js} +1 -1
  77. package/dist/cli/chunks/{chunk-GV2BS5NC.js → chunk-AOMXMFDH.js} +2 -2
  78. package/dist/cli/chunks/{chunk-EH7TSJPS.js → chunk-ARTLSAXO.js} +2 -2
  79. package/dist/cli/chunks/{chunk-CXMOIE7D.js → chunk-AY7S7AWN.js} +2 -2
  80. package/dist/cli/chunks/{chunk-2LNDU7AW.js → chunk-AYYDO52G.js} +2 -2
  81. package/dist/cli/chunks/chunk-BBLWZT5I.js +2 -0
  82. package/dist/cli/chunks/{chunk-KRS4KGX5.js → chunk-BF5BKSDU.js} +2 -2
  83. package/dist/cli/chunks/{chunk-BQ2K4BPD.js → chunk-BOCEOLLJ.js} +2 -2
  84. package/dist/cli/chunks/{chunk-KKOFH26C.js → chunk-CE6LYEHT.js} +1 -1
  85. package/dist/cli/chunks/{chunk-GS6G7AVS.js → chunk-CWP4RMOM.js} +2 -2
  86. package/dist/cli/chunks/{chunk-DCYBV6HV.js → chunk-CWXDL7AH.js} +1 -1
  87. package/dist/cli/chunks/{chunk-KGHSKDC7.js → chunk-DTRFZD7N.js} +2 -2
  88. package/dist/cli/chunks/{chunk-CYSBM52D.js → chunk-DVPGQG4W.js} +2 -2
  89. package/dist/cli/chunks/{chunk-MSDIIRLM.js → chunk-E4D47QTF.js} +2 -2
  90. package/dist/cli/chunks/{chunk-MB7TZQW3.js → chunk-EAKHU5YX.js} +3 -3
  91. package/dist/cli/chunks/{chunk-TP3UAWMB.js → chunk-EGMGOWCE.js} +2 -2
  92. package/dist/cli/chunks/{chunk-4EHW4TNA.js → chunk-ELMUHNXN.js} +2 -2
  93. package/dist/cli/chunks/chunk-EVDYFGVH.js +2 -0
  94. package/dist/cli/chunks/{chunk-D4GMAUTP.js → chunk-FDUSWM6O.js} +98 -88
  95. package/dist/cli/chunks/{chunk-YEC55GO5.js → chunk-FM272B4O.js} +2 -2
  96. package/dist/cli/chunks/{chunk-DMD6WVJ2.js → chunk-FQUUMC57.js} +2 -2
  97. package/dist/cli/chunks/{chunk-Y625LP6K.js → chunk-FQXQJMSF.js} +2 -2
  98. package/dist/cli/chunks/{chunk-Z3SXMYVI.js → chunk-FRAGSKXQ.js} +3 -3
  99. package/dist/cli/chunks/{chunk-MOXKKY5Q.js → chunk-GASOBSNB.js} +4 -4
  100. package/dist/cli/chunks/{chunk-PTPN6HQ7.js → chunk-GJEEPKAT.js} +2 -2
  101. package/dist/cli/chunks/{chunk-WFPGIP4N.js → chunk-GOV2MHLV.js} +2 -2
  102. package/dist/cli/chunks/{chunk-NKTLKMUB.js → chunk-GTPZVLL6.js} +1 -1
  103. package/dist/cli/chunks/chunk-H7YZ2YF2.js +3 -0
  104. package/dist/cli/chunks/{chunk-WKE6WL5C.js → chunk-HFI5PHG5.js} +3 -3
  105. package/dist/cli/chunks/chunk-HUMQU4ES.js +153 -0
  106. package/dist/cli/chunks/{chunk-5FAWIIWF.js → chunk-HYIRFJDB.js} +2 -2
  107. package/dist/cli/chunks/{chunk-DZ775UGW.js → chunk-IBSBOHUX.js} +2 -2
  108. package/dist/cli/chunks/{chunk-NAMJGRGC.js → chunk-IJA4WS7B.js} +2 -2
  109. package/dist/cli/chunks/{chunk-XUUVAAHV.js → chunk-IJP42OGW.js} +2 -2
  110. package/dist/cli/chunks/{chunk-UZ7FXVH5.js → chunk-IMQKEFW6.js} +1 -1
  111. package/dist/cli/chunks/{chunk-MZ7SIO6R.js → chunk-INYS35DV.js} +2 -2
  112. package/dist/cli/chunks/{chunk-MS6VOSPY.js → chunk-IV2VCR75.js} +5 -5
  113. package/dist/cli/chunks/{chunk-UAPUA6OY.js → chunk-IZO6TPGX.js} +2 -2
  114. package/dist/cli/chunks/{chunk-XBOCRCC6.js → chunk-J45DX3IK.js} +1 -1
  115. package/dist/cli/chunks/{chunk-RE42RJYR.js → chunk-J4T6D2OQ.js} +2 -2
  116. package/dist/cli/chunks/{chunk-Y5L37K7X.js → chunk-JAPOMPFD.js} +2 -2
  117. package/dist/cli/chunks/{chunk-M7W6VJ65.js → chunk-JELNVHBF.js} +1 -1
  118. package/dist/cli/chunks/{chunk-YDYKFSD2.js → chunk-JOTNKZ7A.js} +87 -87
  119. package/dist/cli/chunks/{chunk-VUCVSKJC.js → chunk-KNWDXI3I.js} +2 -2
  120. package/dist/cli/chunks/{chunk-SPI4LUJ6.js → chunk-KW5NBORV.js} +2 -2
  121. package/dist/cli/chunks/{chunk-2OX74DOO.js → chunk-L7IOTWWY.js} +1 -1
  122. package/dist/cli/chunks/{chunk-VFYMWDSJ.js → chunk-LJQ27PUE.js} +1 -1
  123. package/dist/cli/chunks/{chunk-NT66CT73.js → chunk-LSKQUUUN.js} +2 -2
  124. package/dist/cli/chunks/{chunk-ROFCS47F.js → chunk-LSZZQ7H6.js} +1 -1
  125. package/dist/cli/chunks/{chunk-Y6XNISHP.js → chunk-LTKNCYMO.js} +2 -2
  126. package/dist/cli/chunks/{chunk-7WF3TW3G.js → chunk-LTWT4GZD.js} +4 -4
  127. package/dist/cli/chunks/chunk-LVHMXGDI.js +29 -0
  128. package/dist/cli/chunks/{chunk-3YC4YUGB.js → chunk-M3T6FB54.js} +2 -2
  129. package/dist/cli/chunks/{chunk-M32DTUZM.js → chunk-MAYZTGJ2.js} +3 -3
  130. package/dist/cli/chunks/{chunk-RLBNAB6Y.js → chunk-MCIO7BDK.js} +1 -1
  131. package/dist/cli/chunks/{chunk-SFS3UHNF.js → chunk-MPD7RR4P.js} +1 -1
  132. package/dist/cli/chunks/{chunk-DDYP6FBC.js → chunk-MUFYDKVC.js} +2 -2
  133. package/dist/cli/chunks/{chunk-ZFLE4D4X.js → chunk-MX5ZDKRR.js} +2 -2
  134. package/dist/cli/chunks/{chunk-WBZNLFTV.js → chunk-MXKHIZVM.js} +5 -5
  135. package/dist/cli/chunks/chunk-MY47CR27.js +2 -0
  136. package/dist/cli/chunks/chunk-N7WAZ2Y6.js +2 -0
  137. package/dist/cli/chunks/{chunk-2HCMRGMO.js → chunk-NHV4PTG6.js} +2 -2
  138. package/dist/cli/chunks/{chunk-HJ4U64BL.js → chunk-NP4CP3LR.js} +2 -2
  139. package/dist/cli/chunks/{chunk-UIHZ34SJ.js → chunk-OCKTPTQ7.js} +2 -2
  140. package/dist/cli/chunks/{chunk-SGMJ277D.js → chunk-OE4B6LDZ.js} +1 -1
  141. package/dist/cli/chunks/{chunk-SV7J5FDW.js → chunk-OPQY2333.js} +2 -2
  142. package/dist/cli/chunks/{chunk-FTM562PF.js → chunk-ORDH4VPL.js} +1 -1
  143. package/dist/cli/chunks/{chunk-YOG5KQZF.js → chunk-P4Y3G6OB.js} +2 -2
  144. package/dist/cli/chunks/{chunk-LHAUFY4Y.js → chunk-PIOO2M4W.js} +2 -2
  145. package/dist/cli/chunks/{chunk-UGW23T6S.js → chunk-PKMCZFET.js} +2 -2
  146. package/dist/cli/chunks/{chunk-OPG2HV2W.js → chunk-QES4QHQW.js} +1 -1
  147. package/dist/cli/chunks/{chunk-BDGKB2PT.js → chunk-QG6BXSNJ.js} +2 -2
  148. package/dist/cli/chunks/{chunk-BSNNTOHY.js → chunk-QLOOW23R.js} +3 -3
  149. package/dist/cli/chunks/{chunk-AIWRYWK2.js → chunk-RSCGBHLM.js} +2 -2
  150. package/dist/cli/chunks/{chunk-LCM7TY76.js → chunk-RZ6CO3RZ.js} +2 -2
  151. package/dist/cli/chunks/chunk-S6F3IJMK.js +2 -0
  152. package/dist/cli/chunks/{chunk-WUE53ZPH.js → chunk-S6VNPKHO.js} +1 -1
  153. package/dist/cli/chunks/{chunk-L2X3BWMN.js → chunk-SHWXADCI.js} +2 -2
  154. package/dist/cli/chunks/{chunk-GMFFMJD6.js → chunk-SPJQJWGK.js} +2 -2
  155. package/dist/cli/chunks/{chunk-KVHCWH4H.js → chunk-SS6K4FBH.js} +2 -2
  156. package/dist/cli/chunks/{chunk-ZGKQCUPB.js → chunk-SXADKQJN.js} +2 -2
  157. package/dist/cli/chunks/{chunk-LGYEOYQJ.js → chunk-TBQTGQ75.js} +2 -2
  158. package/dist/cli/chunks/{chunk-J2RJOJ5Q.js → chunk-TDGE52HJ.js} +1 -1
  159. package/dist/cli/chunks/chunk-THFLRJT6.js +54 -0
  160. package/dist/cli/chunks/{chunk-GGTCD4MA.js → chunk-TQ2MA3SR.js} +1 -1
  161. package/dist/cli/chunks/{chunk-NOSQI2OW.js → chunk-UCQ66N6M.js} +3 -3
  162. package/dist/cli/chunks/{chunk-CL6SNCFF.js → chunk-UHGMS2PJ.js} +1 -1
  163. package/dist/cli/chunks/{chunk-XDHGCBTS.js → chunk-UHKXKWMD.js} +2 -2
  164. package/dist/cli/chunks/{chunk-PEHEANAM.js → chunk-UJ6TMZC6.js} +2 -2
  165. package/dist/cli/chunks/{chunk-PSDH7CIL.js → chunk-UKBDH27A.js} +1 -1
  166. package/dist/cli/chunks/{chunk-ZTKCGEB6.js → chunk-UMCEEXQN.js} +1 -1
  167. package/dist/cli/chunks/{chunk-KA4EAMMQ.js → chunk-USUFTHHT.js} +3 -3
  168. package/dist/cli/chunks/{chunk-QILF6BZH.js → chunk-V32MDID3.js} +2 -2
  169. package/dist/cli/chunks/{chunk-6SUSRXXF.js → chunk-VAJT6QWX.js} +1 -1
  170. package/dist/cli/chunks/{chunk-7Q74K3HZ.js → chunk-VLUJWI56.js} +1 -1
  171. package/dist/cli/chunks/{chunk-DW7OI5IF.js → chunk-WINA3XUT.js} +2 -2
  172. package/dist/cli/chunks/{chunk-S47YGWXK.js → chunk-WWCH5SSF.js} +2 -2
  173. package/dist/cli/chunks/{chunk-FJACKKRL.js → chunk-WWP2VXYJ.js} +2 -2
  174. package/dist/cli/chunks/{chunk-N4ML23ZG.js → chunk-WZROSTQZ.js} +1 -1
  175. package/dist/cli/chunks/{chunk-FXOOOJQD.js → chunk-XFUF654L.js} +1 -1
  176. package/dist/cli/chunks/{chunk-PDX7IYTJ.js → chunk-XN2CD5S6.js} +2 -2
  177. package/dist/cli/chunks/{chunk-DHUZHT5D.js → chunk-XOQQGZFY.js} +1 -1
  178. package/dist/cli/chunks/{chunk-4HP7N6SP.js → chunk-XSCOEY4C.js} +2 -2
  179. package/dist/cli/chunks/{chunk-KNWBRMLL.js → chunk-Y734CWHJ.js} +2 -2
  180. package/dist/cli/chunks/{chunk-NJDLJ3KD.js → chunk-YBPCBFEE.js} +2 -2
  181. package/dist/cli/chunks/{chunk-67BCEHU5.js → chunk-YLAEIS6F.js} +1 -1
  182. package/dist/cli/chunks/{chunk-E53UR2EW.js → chunk-YMMVCOPF.js} +3 -3
  183. package/dist/cli/chunks/{chunk-VSD6JE2H.js → chunk-YQCAXYBF.js} +2 -2
  184. package/dist/cli/chunks/{chunk-32L7DKNQ.js → chunk-YRVUYM62.js} +2 -2
  185. package/dist/cli/chunks/{chunk-LNIHLNW4.js → chunk-YVKMHXQK.js} +3 -3
  186. package/dist/cli/chunks/{chunk-CHFTHSMM.js → chunk-ZCLFAOVT.js} +2 -2
  187. package/dist/cli/chunks/{chunk-AZ24ONMX.js → chunk-ZH6ZBDVV.js} +1 -1
  188. package/dist/cli/chunks/{chunk-R6WMGSEK.js → chunk-ZHEKGB4A.js} +2 -2
  189. package/dist/cli/chunks/{chunk-EOUJ6X5H.js → chunk-ZIBW7CB4.js} +1 -1
  190. package/dist/cli/chunks/{chunk-OBL6W4Z5.js → chunk-ZLCATRXI.js} +2 -2
  191. package/dist/cli/chunks/{chunk-UGXHMQ6P.js → chunk-ZXX2VFMA.js} +2 -2
  192. package/dist/cli/chunks/{chunk-72QQDR3Y.js → chunk-ZYPESQ4M.js} +2 -2
  193. package/dist/cli/chunks/{ci-MMLUV6L6.js → ci-HHL5WQXQ.js} +2 -2
  194. package/dist/cli/chunks/{ci-output-25GS6RXR.js → ci-output-HVOJC2KN.js} +2 -2
  195. package/dist/cli/chunks/{circuit-breaker-4OWAN6R6.js → circuit-breaker-HRXMIY2G.js} +2 -2
  196. package/dist/cli/chunks/{claude-flow-setup-LR3SRBX6.js → claude-flow-setup-3I7WVMZN.js} +2 -2
  197. package/dist/cli/chunks/client-EY2IYQDL.js +2 -0
  198. package/dist/cli/chunks/{cline-installer-YSZWRZUI.js → cline-installer-NBREL4QT.js} +2 -2
  199. package/dist/cli/chunks/{code-UUWUIXI7.js → code-TX4E2RWU.js} +2 -2
  200. package/dist/cli/chunks/{code-index-extractor-2LSPQORU.js → code-index-extractor-YELOFLSL.js} +2 -2
  201. package/dist/cli/chunks/codex-installer-HEX3KFRB.js +10 -0
  202. package/dist/cli/chunks/{completions-YKXBKZSO.js → completions-72GGFRGG.js} +2 -2
  203. package/dist/cli/chunks/{complexity-analyzer-HNT2QRWB.js → complexity-analyzer-WRAKDYUK.js} +2 -2
  204. package/dist/cli/chunks/{continuedev-installer-AW5VCB66.js → continuedev-installer-UGYKSKTI.js} +2 -2
  205. package/dist/cli/chunks/{copilot-installer-B6SVZXQT.js → copilot-installer-RPCRUKIJ.js} +2 -2
  206. package/dist/cli/chunks/core-handlers-G4GLA4DT.js +2 -0
  207. package/dist/cli/chunks/{cost-tracker-POZMBN2V.js → cost-tracker-CNHJ7G4M.js} +2 -2
  208. package/dist/cli/chunks/{coverage-V5BGPN5Q.js → coverage-RHIQ4XEX.js} +3 -3
  209. package/dist/cli/chunks/cross-domain-router-P3K4IH5H.js +2 -0
  210. package/dist/cli/chunks/{cursor-installer-EYBI4QVK.js → cursor-installer-KSRVA4V2.js} +2 -2
  211. package/dist/cli/chunks/{daemon-CF6ENQB2.js → daemon-IT4AAFBW.js} +3 -3
  212. package/dist/cli/chunks/{daemon-HKARXY2W.js → daemon-QBXSJABV.js} +4 -4
  213. package/dist/cli/chunks/{dag-attention-scheduler-XIL5IAP7.js → dag-attention-scheduler-F7WCQTLY.js} +2 -2
  214. package/dist/cli/chunks/{detect-RRX2U2KK.js → detect-2IYU332U.js} +2 -2
  215. package/dist/cli/chunks/{dist-node-DOANNRCS.js → dist-node-CIYNYCYN.js} +2 -2
  216. package/dist/cli/chunks/{domain-handler-QMTJV5OR.js → domain-handler-QRYQO2QK.js} +2 -2
  217. package/dist/cli/chunks/{domain-transfer-FSNH75XW.js → domain-transfer-2OQDOD3G.js} +2 -2
  218. package/dist/cli/chunks/dream-IT4ZQGEO.js +2 -0
  219. package/dist/cli/chunks/{embed-and-insert-pattern-NI7PGONV.js → embed-and-insert-pattern-P2IFC7JL.js} +2 -2
  220. package/dist/cli/chunks/{eval-6ZAF2RY3.js → eval-SBPK37IB.js} +2 -2
  221. package/dist/cli/chunks/{experience-capture-middleware-JMXR7N5G.js → experience-capture-middleware-3GMFND3F.js} +3 -3
  222. package/dist/cli/chunks/{fast-paths-YB7XZZ76.js → fast-paths-4OYYII2F.js} +2 -2
  223. package/dist/cli/chunks/{feature-flags-2RC4GFC4.js → feature-flags-BM6QTMMC.js} +2 -2
  224. package/dist/cli/chunks/{feature-flags-KJSP7KR6.js → feature-flags-NFCAYUWO.js} +2 -2
  225. package/dist/cli/chunks/{file-discovery-SUPBXFYI.js → file-discovery-2M3ZUAGC.js} +2 -2
  226. package/dist/cli/chunks/{fleet-KSXFOLFW.js → fleet-QMGGVIDV.js} +3 -3
  227. package/dist/cli/chunks/{gnn-wrapper-DFZ5KPPK.js → gnn-wrapper-WGMAGZMO.js} +2 -2
  228. package/dist/cli/chunks/{heartbeat-handler-G3EADK2H.js → heartbeat-handler-5RSMEZGG.js} +4 -4
  229. package/dist/cli/chunks/heartbeat-scheduler-UUWSPHF2.js +2 -0
  230. package/dist/cli/chunks/hnsw-adapter-YUJVSFPD.js +2 -0
  231. package/dist/cli/chunks/hnsw-index-FQZ47RSJ.js +2 -0
  232. package/dist/cli/chunks/{hnsw-legacy-bridge-MA676GER.js → hnsw-legacy-bridge-TYPQ2T6P.js} +2 -2
  233. package/dist/cli/chunks/{better-sqlite3-FE55OGYB.js → hnswlib-node-GMRPPMDM.js} +2 -2
  234. package/dist/cli/chunks/{hooks-HTCPMZNZ.js → hooks-NUC5P3OJ.js} +10 -10
  235. package/dist/cli/chunks/hybrid-router-T5MF73NF.js +2 -0
  236. package/dist/cli/chunks/{hypergraph-engine-QPB3IH4A.js → hypergraph-engine-OIB7WK54.js} +2 -2
  237. package/dist/cli/chunks/{hypergraph-handler-GBFSVD7N.js → hypergraph-handler-XX2N75QC.js} +3 -3
  238. package/dist/cli/chunks/impact-analyzer-AEGELYMD.js +2 -0
  239. package/dist/cli/chunks/{init-handler-XYBTBCPD.js → init-handler-AKSTJMZY.js} +6 -6
  240. package/dist/cli/chunks/init-wizard-WKX3OGWM.js +2 -0
  241. package/dist/cli/chunks/kernel-5CVWFIGR.js +2 -0
  242. package/dist/cli/chunks/{kilocode-installer-LY6JOBFY.js → kilocode-installer-375V5ZZB.js} +2 -2
  243. package/dist/cli/chunks/{kiro-installer-JF6NXTJL.js → kiro-installer-GKY5GB5Q.js} +2 -2
  244. package/dist/cli/chunks/knowledge-graph-EGPMNDMT.js +2 -0
  245. package/dist/cli/chunks/{learning-BIISN67N.js → learning-2CQE3QP6.js} +3 -3
  246. package/dist/cli/chunks/{llm-router-YZUNVZQE.js → llm-router-FTQNRF45.js} +5 -5
  247. package/dist/cli/chunks/llm-router-service-H4LXOARB.js +2 -0
  248. package/dist/cli/chunks/{load-MTWNBNLL.js → load-3DBAO5ZG.js} +2 -2
  249. package/dist/cli/chunks/load-test-OOOGITSN.js +2 -0
  250. package/dist/cli/chunks/{mcp-37PYMNHQ.js → mcp-AWR6TDXM.js} +2 -2
  251. package/dist/cli/chunks/{memory-IXUUDCI3.js → memory-GI4LCNXY.js} +5 -5
  252. package/dist/cli/chunks/memory-backend-O2YOT4LW.js +2 -0
  253. package/dist/cli/chunks/{memory-handlers-RM2VOFJX.js → memory-handlers-MALKG7GP.js} +2 -2
  254. package/dist/cli/chunks/{multi-model-executor-RKKS5XYG.js → multi-model-executor-SWFT5U72.js} +2 -2
  255. package/dist/cli/chunks/{opencode-installer-3VXI5MTR.js → opencode-installer-EYXGYJX5.js} +2 -2
  256. package/dist/cli/chunks/{orchestrator-UO3ZOGFZ.js → orchestrator-MP3EAZVC.js} +5 -5
  257. package/dist/cli/chunks/pattern-null-store-WBOHE2XL.js +2 -0
  258. package/dist/cli/chunks/{pattern-usage-recorder-YJKRL2GI.js → pattern-usage-recorder-25P3R3W7.js} +2 -2
  259. package/dist/cli/chunks/{pipeline-GJQJKXWX.js → pipeline-LSAFL25D.js} +2 -2
  260. package/dist/cli/chunks/{platform-RHVCZK6C.js → platform-IJ6DJ2PG.js} +2 -2
  261. package/dist/cli/chunks/{plugin-ZKAIW7O6.js → plugin-OXOZRZW2.js} +2 -2
  262. package/dist/cli/chunks/{prime-radiant-advanced-wasm-4X3DSKQV.js → prime-radiant-advanced-wasm-HJNJQQ3R.js} +2 -2
  263. package/dist/cli/chunks/protocol-executor-JCNTPW5J.js +2 -0
  264. package/dist/cli/chunks/{protocol-handler-KKYQZMB2.js → protocol-handler-TCMUH2HL.js} +2 -2
  265. package/dist/cli/chunks/{prove-OD6RPKWX.js → prove-ADXQ2GOX.js} +2 -2
  266. package/dist/cli/chunks/provider-manager-LPGQ5GOO.js +2 -0
  267. package/dist/cli/chunks/qe-reasoning-bank-FWVYVSPP.js +2 -0
  268. package/dist/cli/chunks/{quality-ZRWBXCKO.js → quality-EWP36ORX.js} +2 -2
  269. package/dist/cli/chunks/{quality-gate-Y6BWQV7J.js → quality-gate-3BIG7PVU.js} +3 -3
  270. package/dist/cli/chunks/queen-coordinator-UXNALRVD.js +2 -0
  271. package/dist/cli/chunks/{real-embeddings-YYEUO4P2.js → real-embeddings-D4NBT7W5.js} +2 -2
  272. package/dist/cli/chunks/{roocode-installer-JBCPS3FK.js → roocode-installer-DOPWH6YV.js} +2 -2
  273. package/dist/cli/chunks/router-C6LUIQYY.js +2 -0
  274. package/dist/cli/chunks/routing-feedback-KMSGGDVD.js +2 -0
  275. package/dist/cli/chunks/{routing-handler-KTPJOSBJ.js → routing-handler-5ADEFOHS.js} +2 -2
  276. package/dist/cli/chunks/{ruvector-commands-SCZZVRE7.js → ruvector-commands-PLMEIHSN.js} +2 -2
  277. package/dist/cli/chunks/{rvf-dual-writer-IP7GELQJ.js → rvf-dual-writer-EQWKVNQB.js} +2 -2
  278. package/dist/cli/chunks/{rvf-migration-adapter-WLFTDARU.js → rvf-migration-adapter-2OWFUUCG.js} +2 -2
  279. package/dist/cli/chunks/{rvf-migration-coordinator-MGFDQ5WD.js → rvf-migration-coordinator-URAETAPU.js} +2 -2
  280. package/dist/cli/chunks/rvf-native-adapter-K54BELUE.js +2 -0
  281. package/dist/cli/chunks/{rvf-store-integrity-OTOAGT5W.js → rvf-store-integrity-4AWPW4TF.js} +2 -2
  282. package/dist/cli/chunks/safe-db-NGOZWF2D.js +2 -0
  283. package/dist/cli/chunks/schedule-B3Y5P64E.js +2 -0
  284. package/dist/cli/chunks/scheduler-Z6QVRMTB.js +2 -0
  285. package/dist/cli/chunks/{security-B2CLZKRB.js → security-HDLZVM62.js} +3 -3
  286. package/dist/cli/chunks/{shared-rvf-adapter-2PMFAQMN.js → shared-rvf-adapter-YQT7PF7X.js} +2 -2
  287. package/dist/cli/chunks/{shared-rvf-dual-writer-B6P732AV.js → shared-rvf-dual-writer-N5D3NSJ7.js} +2 -2
  288. package/dist/cli/chunks/sqlite-persistence-PLOUGATS.js +2 -0
  289. package/dist/cli/chunks/{status-handler-M6SN2W2D.js → status-handler-KLYRJ2MR.js} +2 -2
  290. package/dist/cli/chunks/{structural-health-YCCTGI3K.js → structural-health-6LKVRP6Y.js} +2 -2
  291. package/dist/cli/chunks/sync-7VMFPBVB.js +2 -0
  292. package/dist/cli/chunks/{sync-KSRF77ID.js → sync-YYOW6L6W.js} +2 -2
  293. package/dist/cli/chunks/{task-handler-MIKRB2SL.js → task-handler-RKQDGFN2.js} +2 -2
  294. package/dist/cli/chunks/{task-handlers-YXKRUBQ4.js → task-handlers-6YJ4QTEP.js} +3 -3
  295. package/dist/cli/chunks/{test-MLOLQCB7.js → test-ASPUIUJH.js} +4 -4
  296. package/dist/cli/chunks/{test-scheduling-3KXESUZS.js → test-scheduling-I7ABQBBU.js} +3 -3
  297. package/dist/cli/chunks/{token-bootstrap-6V2PMDBJ.js → token-bootstrap-2XZBTODN.js} +2 -2
  298. package/dist/cli/chunks/{token-usage-DP6THJ3I.js → token-usage-TMUE6PTF.js} +2 -2
  299. package/dist/cli/chunks/transformers-FDHHH4SL.js +2 -0
  300. package/dist/cli/chunks/{tree-sitter-wasm-parser-COK2XERS.js → tree-sitter-wasm-parser-G7PGZA5C.js} +2 -2
  301. package/dist/cli/chunks/{types-PYHUCVOZ.js → types-JGT57UFP.js} +2 -2
  302. package/dist/cli/chunks/unified-memory-P5YVLMFI.js +2 -0
  303. package/dist/cli/chunks/unified-memory-hnsw-7HI43A2O.js +2 -0
  304. package/dist/cli/chunks/unified-persistence-U26YP3N3.js +2 -0
  305. package/dist/cli/chunks/{upgrade-ONP2HNGL.js → upgrade-V6UQODJF.js} +2 -2
  306. package/dist/cli/chunks/{validate-NWSICDAY.js → validate-UBZAE5RW.js} +2 -2
  307. package/dist/cli/chunks/{validate-swarm-KXS5P3U7.js → validate-swarm-TSO2MI5X.js} +2 -2
  308. package/dist/cli/chunks/{vibium-TZSGZRCQ.js → vibium-7G3VYSQA.js} +2 -2
  309. package/dist/cli/chunks/visual-security-6FCDY5FF.js +2 -0
  310. package/dist/cli/chunks/{web-tree-sitter-V2FADNRA.js → web-tree-sitter-MIYJSF2L.js} +2 -2
  311. package/dist/cli/chunks/{windsurf-installer-GQM7KWDC.js → windsurf-installer-5TLZSQIJ.js} +2 -2
  312. package/dist/cli/chunks/witness-chain-I3K3WQID.js +2 -0
  313. package/dist/cli/chunks/{witness-chain-GTITDIA2.js → witness-chain-LTV7H2HM.js} +2 -2
  314. package/dist/cli/chunks/{witness-key-manager-AHRM2M52.js → witness-key-manager-PAJ2J4AL.js} +2 -2
  315. package/dist/cli/chunks/{workflow-XCGHEL3I.js → workflow-DL3ESR2H.js} +4 -4
  316. package/dist/cli/chunks/workflow-orchestrator-MAALP4WA.js +2 -0
  317. package/dist/cli/chunks/{wrappers-VGO2GO4J.js → wrappers-5HSU665E.js} +2 -2
  318. package/dist/cli/commands/llm-router.js +1 -0
  319. package/dist/cli/handlers/init-handler.js +1 -1
  320. package/dist/coordination/handlers/coverage-collection.d.ts +161 -0
  321. package/dist/coordination/handlers/coverage-collection.js +639 -0
  322. package/dist/coordination/handlers/coverage-handlers.js +199 -146
  323. package/dist/coordination/handlers/handler-types.d.ts +6 -1
  324. package/dist/coordination/handlers/handler-utils.js +10 -3
  325. package/dist/coordination/handlers/security-handlers.js +17 -2
  326. package/dist/coordination/handlers/test-execution-handlers.js +16 -1
  327. package/dist/coordination/result-saver.js +119 -97
  328. package/dist/coordination/task-executor.d.ts +26 -1
  329. package/dist/coordination/task-executor.js +52 -4
  330. package/dist/domains/code-intelligence/services/knowledge-graph.js +8 -0
  331. package/dist/domains/coverage-analysis/services/coverage-analyzer.js +4 -0
  332. package/dist/domains/coverage-analysis/services/gap-detector.js +4 -0
  333. package/dist/domains/defect-intelligence/services/defect-predictor.js +4 -0
  334. package/dist/domains/defect-intelligence/services/root-cause-analyzer.js +4 -0
  335. package/dist/domains/quality-assessment/services/deployment-advisor.js +4 -0
  336. package/dist/domains/quality-assessment/services/quality-analyzer.js +4 -0
  337. package/dist/domains/security-compliance/services/scanners/sast-scanner.js +4 -0
  338. package/dist/domains/test-generation/index.js +17 -2
  339. package/dist/domains/test-generation/services/test-generator.js +31 -9
  340. package/dist/init/codex-installer.d.ts +13 -0
  341. package/dist/init/codex-installer.js +122 -1
  342. package/dist/init/phases/09-assets.js +4 -0
  343. package/dist/init/phases/phase-interface.d.ts +1 -1
  344. package/dist/init/skills-installer.js +1 -0
  345. package/dist/integrations/embeddings/base/EmbeddingGenerator.js +13 -1
  346. package/dist/kernel/unified-memory.js +4 -0
  347. package/dist/learning/qe-flywheel/corpus-scorer.js +10 -7
  348. package/dist/learning/qe-flywheel/generation.d.ts +7 -0
  349. package/dist/learning/qe-flywheel/generation.js +5 -0
  350. package/dist/learning/qe-flywheel/witness-verify.d.ts +86 -0
  351. package/dist/learning/qe-flywheel/witness-verify.js +156 -0
  352. package/dist/learning/real-embeddings.js +15 -1
  353. package/dist/mcp/bundle.js +455 -434
  354. package/dist/mcp/handlers/domain-handler-configs.js +79 -14
  355. package/dist/mcp/types.d.ts +42 -4
  356. package/dist/optimization/session-cache.d.ts +13 -1
  357. package/dist/optimization/session-cache.js +27 -2
  358. package/dist/shared/db-recovery.d.ts +55 -0
  359. package/dist/shared/db-recovery.js +184 -0
  360. package/dist/shared/llm/billing-modes.js +5 -2
  361. package/dist/shared/llm/cost-tracker.js +1 -0
  362. package/dist/shared/llm/interfaces.d.ts +14 -1
  363. package/dist/shared/llm/llm-router-service.js +59 -4
  364. package/dist/shared/llm/provider-manager.d.ts +1 -1
  365. package/dist/shared/llm/provider-manager.js +7 -3
  366. package/dist/shared/llm/providers/claude-code.js +12 -3
  367. package/dist/shared/llm/providers/codex.d.ts +58 -0
  368. package/dist/shared/llm/providers/codex.js +305 -0
  369. package/dist/shared/llm/providers/index.d.ts +1 -0
  370. package/dist/shared/llm/providers/index.js +1 -0
  371. package/dist/shared/llm/router/agent-router-config.d.ts +46 -2
  372. package/dist/shared/llm/router/agent-router-config.js +124 -2
  373. package/dist/shared/llm/router/config-store.d.ts +17 -1
  374. package/dist/shared/llm/router/config-store.js +108 -0
  375. package/dist/shared/llm/router/hybrid-router.js +2 -2
  376. package/dist/shared/llm/router/index.d.ts +2 -2
  377. package/dist/shared/llm/router/index.js +2 -0
  378. package/dist/shared/llm/router/types.d.ts +44 -0
  379. package/dist/shared/llm/router/types.js +1 -0
  380. package/dist/shared/llm/spend-ledger.d.ts +24 -0
  381. package/dist/shared/llm/spend-ledger.js +86 -15
  382. package/dist/shared/llm/translation/message-formatter.js +1 -0
  383. package/dist/shared/safe-db.d.ts +10 -0
  384. package/dist/shared/safe-db.js +17 -0
  385. package/dist/skills/qe-court/referee.d.ts +62 -0
  386. package/dist/skills/qe-court/referee.js +78 -0
  387. package/dist/validation/gate-reexecute.d.ts +9 -0
  388. package/dist/validation/gate-reexecute.js +61 -0
  389. package/dist/validation/paired-bootstrap.d.ts +36 -0
  390. package/dist/validation/paired-bootstrap.js +58 -0
  391. package/package.json +9 -2
  392. package/dist/cli/chunks/adapter-D657MKZY.js +0 -2
  393. package/dist/cli/chunks/aqe-learning-engine-AFR6OZJK.js +0 -2
  394. package/dist/cli/chunks/base-K5QRGZWE.js +0 -2
  395. package/dist/cli/chunks/browser-workflow-ZMMKCGYW.js +0 -2
  396. package/dist/cli/chunks/chunk-6HQDPDN5.js +0 -2
  397. package/dist/cli/chunks/chunk-6SQ72FG7.js +0 -2
  398. package/dist/cli/chunks/chunk-7XUM4LBC.js +0 -2
  399. package/dist/cli/chunks/chunk-FHHCH7WL.js +0 -2
  400. package/dist/cli/chunks/chunk-G5OGKVLO.js +0 -2
  401. package/dist/cli/chunks/chunk-ILRKO6A5.js +0 -43
  402. package/dist/cli/chunks/chunk-NX522PRH.js +0 -153
  403. package/dist/cli/chunks/chunk-PPUDKQ4X.js +0 -29
  404. package/dist/cli/chunks/chunk-RSZOCQOL.js +0 -2
  405. package/dist/cli/chunks/chunk-ULQCEM7K.js +0 -2
  406. package/dist/cli/chunks/chunk-XQ5JT7KM.js +0 -3
  407. package/dist/cli/chunks/client-WI7RRUZO.js +0 -2
  408. package/dist/cli/chunks/codex-installer-E5BVXZVA.js +0 -8
  409. package/dist/cli/chunks/core-handlers-T6URR57V.js +0 -2
  410. package/dist/cli/chunks/cross-domain-router-WHTTKHWM.js +0 -2
  411. package/dist/cli/chunks/dream-QUL6SURC.js +0 -2
  412. package/dist/cli/chunks/heartbeat-scheduler-VZNKE33K.js +0 -2
  413. package/dist/cli/chunks/hnsw-adapter-LGWLDZLC.js +0 -2
  414. package/dist/cli/chunks/hnsw-index-66FOOI7U.js +0 -2
  415. package/dist/cli/chunks/hybrid-router-I5MEVQDF.js +0 -2
  416. package/dist/cli/chunks/impact-analyzer-K6ANYIY3.js +0 -2
  417. package/dist/cli/chunks/init-wizard-URHGXJ32.js +0 -2
  418. package/dist/cli/chunks/kernel-OKI5ZY5P.js +0 -2
  419. package/dist/cli/chunks/knowledge-graph-VQQSK7T5.js +0 -2
  420. package/dist/cli/chunks/llm-router-service-TISH33SY.js +0 -2
  421. package/dist/cli/chunks/load-test-KWKWC4Q7.js +0 -2
  422. package/dist/cli/chunks/memory-backend-JSQQMXVS.js +0 -2
  423. package/dist/cli/chunks/pattern-null-store-SXBIUKE5.js +0 -2
  424. package/dist/cli/chunks/protocol-executor-D3Q5P3WY.js +0 -2
  425. package/dist/cli/chunks/provider-manager-2EIX7E5Q.js +0 -2
  426. package/dist/cli/chunks/qe-reasoning-bank-ITOW2ZHC.js +0 -2
  427. package/dist/cli/chunks/queen-coordinator-TO5X2EXL.js +0 -2
  428. package/dist/cli/chunks/router-GZJQEJU3.js +0 -2
  429. package/dist/cli/chunks/routing-feedback-CRXSKFNS.js +0 -2
  430. package/dist/cli/chunks/rvf-native-adapter-WHADT5HX.js +0 -2
  431. package/dist/cli/chunks/safe-db-MIZ2OFWC.js +0 -2
  432. package/dist/cli/chunks/schedule-XFILYTYC.js +0 -2
  433. package/dist/cli/chunks/scheduler-EIPJ777A.js +0 -2
  434. package/dist/cli/chunks/sqlite-persistence-PFU3GSRD.js +0 -2
  435. package/dist/cli/chunks/sync-3SDMVAIU.js +0 -2
  436. package/dist/cli/chunks/transformers-QFOBOP2Y.js +0 -2
  437. package/dist/cli/chunks/unified-memory-OUVCMFGK.js +0 -2
  438. package/dist/cli/chunks/unified-memory-hnsw-YGQPOHXB.js +0 -2
  439. package/dist/cli/chunks/unified-persistence-GFRZVDOW.js +0 -2
  440. package/dist/cli/chunks/visual-security-LVOOYQ64.js +0 -2
  441. package/dist/cli/chunks/witness-chain-QNFPV4UL.js +0 -2
  442. package/dist/cli/chunks/workflow-orchestrator-MIVBCALG.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.12.3");process.exit(0)}
2
- import{a as l}from"./chunk-7Q74K3HZ.js";import{a as m}from"./chunk-NKTLKMUB.js";import{i as a}from"./chunk-EOUJ6X5H.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.12.3");process.exit(0)}
2
- import{b as k,c as p}from"./chunk-NJDLJ3KD.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.12.3");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.12.3");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.12.3");process.exit(0)}
2
- import{a as g}from"./chunk-Y6XNISHP.js";import{b as p,c}from"./chunk-NKTLKMUB.js";import{a as x,b as f,c as w}from"./chunk-2LNDU7AW.js";import{i as v}from"./chunk-EOUJ6X5H.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.12.3");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.12.3");process.exit(0)}
2
- import{i as e}from"./chunk-EOUJ6X5H.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.12.3");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-M32DTUZM.js";import{b as v,d as T}from"./chunk-OBL6W4Z5.js";import{a as y,c as A}from"./chunk-2LNDU7AW.js";import{a as _,b as re}from"./chunk-ULQCEM7K.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-FE55OGYB.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-VQQSK7T5.js"),{InMemoryBackend:n}=await import("./memory-backend-JSQQMXVS.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
@@ -0,0 +1,29 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.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
+ INSERT INTO ${u} (${p.join(", ")})
4
+ VALUES ${s.join(", ")}
5
+ ${h}
6
+ `;try{return(await this.client.query(y,a)).rowCount||0}catch(f){throw N.debug(`Upsert failed for ${e}`,{error:d(f)}),f}}async execute(e,t){if(!this.client)throw new Error("Not connected");await this.client.query(e,t)}async query(e,t){if(!this.client)throw new Error("Not connected");return(await this.client.query(e,t)).rows}async close(){this.inTransaction&&await this.rollback(),this.client&&(await this.client.end(),this.client=null,this.connected=!1,console.log("[PostgresWriter] Connection closed"))}serializeValue(e,t){if(e==null)return null;if(Buffer.isBuffer(e)){try{let n=new Float32Array(e.buffer,e.byteOffset,e.length/4);if(n.length>0&&n.length<=1024)return`[${Array.from(n).join(",")}]`}catch(n){N.debug("Buffer to float array conversion failed",{error:n instanceof Error?n.message:String(n)})}return null}if(typeof e=="number")return e>9466848e5&&e<41024448e5?new Date(e).toISOString():e>946684800&&e<4102444800?new Date(e*1e3).toISOString():e;if(Array.isArray(e))return e.length>0&&typeof e[0]=="number"?`[${e.join(",")}]`:JSON.stringify(e);if(typeof e=="object"){let n=JSON.stringify(e);if(t&&this.isJsonbColumn(t)){n=n.replace(/\u0000/g,"");try{JSON.parse(n)}catch{return JSON.stringify(String(e))}}return n}if(typeof e=="string"){if(e===""&&t&&["created_at","updated_at","last_used_at","started_at","ended_at","completed_at","expires_at","last_update"].includes(t))return null;if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(e))return e;let n=parseInt(e,10);if(!isNaN(n)&&n>9466848e5&&n<41024448e5)return new Date(n).toISOString();if(t&&this.isJsonbColumn(t)){let r=e.replace(/\u0000/g,"");try{return JSON.parse(r),r}catch{return JSON.stringify(r)}}}return e}isJsonbColumn(e){return["action_value","state","action","next_state","preconditions","effects","metadata","value","payload","context_json","template_json","execution_trace","action_sequence","initial_state","goal_state","sequence","task_json","decision_json","steps_json","metadata_json"].includes(e)}inferConflictColumns(e,t){let n=e.includes(".")?e.split(".")[1]:e,r=["qe_patterns","sona_patterns","goap_actions","goap_plans","patterns","events","routing_outcomes","qe_trajectories","dream_insights","intelligence_memories"];return t.includes("id")&&r.includes(n)?["id"]:n==="memory_entries"&&t.includes("key")&&t.includes("source_env")?t.includes("partition")?["key","partition","source_env"]:["key","source_env"]:n==="claude_flow_memory"&&t.includes("key")&&t.includes("source_env")?["key","source_env"]:n==="qlearning_patterns"&&t.includes("state")&&t.includes("action")&&t.includes("source_env")?["state","action","source_env"]:n==="claude_flow_workers"&&t.includes("worker_type")&&t.includes("source_env")?["worker_type","source_env"]:[]}createMockClient(){let e=[];return{async connect(){console.log("[MockPgClient] Connected (mock mode)")},async query(t,n){return console.log(`[MockPgClient] Query: ${t.slice(0,100)}... (${n?.length||0} params)`),{rows:e,rowCount:0}},async end(){console.log("[MockPgClient] Disconnected (mock mode)")}}}};function O(l){return new J(l)}k();P();v();var G=b.create("postgres-reader"),Q=class{writer;environment;constructor(e){this.writer=e.writer,this.environment=e.environment}sanitizeCloudTable(e){let t=e.indexOf(".");if(t===-1||t===0||t===e.length-1)throw new Error(`Invalid cloud table format '${e}': expected 'schema.table' (e.g., 'aqe.qe_patterns')`);let n=e.substring(0,t),r=e.substring(t+1);return`${E(n)}.${E(r)}`}async readAll(e){let t=this.sanitizeCloudTable(e.cloudTable),n,r;this.environment!=="all"?(n=`SELECT * FROM ${t} WHERE source_env = $1`,r=[this.environment]):(n=`SELECT * FROM ${t}`,r=[]);try{let i=await this.writer.query(n,r);return G.debug(`Read ${i.length} records from ${e.cloudTable}`,{env:this.environment}),i.map(o=>this.transformRecord(o,e))}catch(i){throw new Error(`Failed to read from ${e.cloudTable}: ${d(i)}`)}}async readChanged(e,t){let n=this.sanitizeCloudTable(e.cloudTable),r=await this.findTimestampColumn(n);if(!r)return G.debug(`No timestamp column found for ${e.cloudTable}, falling back to readAll`),this.readAll(e);let i,o;this.environment!=="all"?(i=`SELECT * FROM ${n} WHERE ${E(r)} > $1 AND source_env = $2`,o=[t.toISOString(),this.environment]):(i=`SELECT * FROM ${n} WHERE ${E(r)} > $1`,o=[t.toISOString()]);try{return(await this.writer.query(i,o)).map(a=>this.transformRecord(a,e))}catch(s){return G.debug(`Changed query failed for ${e.cloudTable}, falling back to readAll`,{error:d(s)}),this.readAll(e)}}async count(e){let t=this.sanitizeCloudTable(e.cloudTable),n,r;this.environment!=="all"?(n=`SELECT COUNT(*) as count FROM ${t} WHERE source_env = $1`,r=[this.environment]):(n=`SELECT COUNT(*) as count FROM ${t}`,r=[]);try{await this.writer.beginTransaction(),await this.writer.execute("SET LOCAL enable_indexonlyscan = off");let i=await this.writer.query(n,r);return await this.writer.commit(),typeof i[0]?.count=="string"?parseInt(i[0].count,10):i[0]?.count||0}catch(i){try{await this.writer.rollback()}catch{}return G.debug(`Count query failed for ${e.cloudTable}`,{error:d(i)}),-1}}transformRecord(e,t){let n={};for(let[r,i]of Object.entries(e)){if(t.dropColumns?.includes(r))continue;let o=t.columnMap?.[r]||r;n[o]=this.transformValue(i,r,t.transforms)}return n}transformValue(e,t,n){if(e==null)return null;let r=n?.[t];return r==="boolean-to-int"?typeof e=="boolean"?e?1:0:e==="true"||e==="t"?1:e==="false"||e==="f"?0:e:r==="jsonb-to-text"?typeof e=="object"?JSON.stringify(e):e:r==="timestamptz-to-text"?e instanceof Date?e.toISOString():e:typeof e=="object"&&!Buffer.isBuffer(e)?JSON.stringify(e):e instanceof Date?e.toISOString():typeof e=="boolean"?e?1:0:e}async findTimestampColumn(e){let t=["updated_at","created_at","last_update","last_used_at"];try{let n=e.split(".")[0],r=e.split(".")[1],o=(await this.writer.query(`SELECT column_name FROM information_schema.columns
7
+ WHERE table_schema = $1 AND table_name = $2
8
+ AND data_type IN ('timestamp with time zone', 'timestamp without time zone')`,[n,r])).map(s=>s.column_name);for(let s of t)if(o.includes(s))return s;return o[0]||null}catch{return null}}};function ie(l){return new Q(l)}z();k();P();v();import*as fe from"fs";var D=b.create("sqlite-writer"),V=class{db=null;dbPath;batchSize;constructor(e){this.dbPath=e.dbPath,this.batchSize=e.batchSize||500}async connect(){if(!this.db){if(!fe.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}. Run 'aqe init' to create it.`);try{this.db=T(this.dbPath),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),D.debug(`Opened SQLite database: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${d(e)}`)}}}async upsert(e,t){if(!this.db)throw new Error("Not connected");if(t.length===0)return 0;let n=w(e);if(!this.tableExists(e))return console.warn(`[SQLiteWriter] Table '${e}' does not exist in local database \u2014 ${t.length} records skipped. Run 'aqe init' to create schema.`),0;let r=this.getTableColumns(e);if(r.length===0)return D.debug(`No columns found for table ${e}`),0;let i=new Set(r),o=0;for(let s=0;s<t.length;s+=this.batchSize){let a=t.slice(s,s+this.batchSize);try{let c=this.upsertBatch(n,a,i);o+=c}catch(c){let u=Math.floor(s/this.batchSize)+1;D.debug(`Batch ${u} failed for ${e}, retrying individually`,{error:d(c)});let p=0;for(let m of a)try{p+=this.upsertBatch(n,[m],i)}catch(g){let h=m.id||m.key||"?";D.debug(`Skipped record ${String(h).slice(0,50)} in ${e}`,{error:d(g)})}o+=p}}return o}async count(e){if(!this.db)throw new Error("Not connected");if(!this.tableExists(e))return 0;try{let t=w(e);return this.db.prepare(`SELECT COUNT(*) as count FROM ${t}`).get().count}catch{return 0}}async close(){this.db&&(this.db.close(),this.db=null,D.debug("SQLite writer closed"))}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch{return!1}}getTableColumns(e){if(!this.db)return[];try{let t=w(e);return this.db.prepare(`PRAGMA table_info(${t})`).all().map(r=>r.name)}catch{return[]}}getPrimaryKeyColumns(e){if(!this.db)return[];try{let t=w(e);return this.db.prepare(`PRAGMA table_info(${t})`).all().filter(i=>i.pk>0).sort((i,o)=>i.pk-o.pk).map(i=>i.name)}catch{return[]}}upsertBatch(e,t,n){if(!this.db||t.length===0)return 0;let r=t[0],i=Object.keys(r).filter(g=>n.has(g));if(i.length===0)return 0;let o=i.map(E),s=i.map(()=>"?").join(", "),a=e.replace(/"/g,""),c=this.getPrimaryKeyColumns(a),u;if(c.length>0){let g=c.map(E),h=i.filter(y=>!c.includes(y));if(h.length>0){let y=h.map(f=>`${E(f)} = excluded.${E(f)}`).join(", ");u=`INSERT INTO ${e} (${o.join(", ")}) VALUES (${s}) ON CONFLICT(${g.join(", ")}) DO UPDATE SET ${y}`}else u=`INSERT OR IGNORE INTO ${e} (${o.join(", ")}) VALUES (${s})`}else u=`INSERT OR IGNORE INTO ${e} (${o.join(", ")}) VALUES (${s})`;let p=this.db.prepare(u);return this.db.transaction(g=>{let h=0;for(let y of g){let f=i.map(S=>this.serializeValue(y[S]));p.run(...f),h++}return h})(t)}serializeValue(e){return e==null?null:typeof e=="object"&&!Buffer.isBuffer(e)&&!(e instanceof Date)?JSON.stringify(e):e instanceof Date?e.toISOString():typeof e=="boolean"?e?1:0:(Buffer.isBuffer(e),e)}};function oe(l){return new V(l)}v();P();var Me=b.create("sync-agent"),H=class{config;readers=new Map;writer=null;report=null;constructor(e={}){this.config={...x,...e,local:{...x.local,...e.local},cloud:{...x.cloud,...e.cloud},sync:{...x.sync,...e.sync}}}async initialize(){this.log("Initializing sync agent...");let e=this.config.sync.sources.filter(t=>t.enabled!==!1);for(let t of e){let n=this.createReader(t);if(n)try{await n.initialize(),this.readers.set(t.name,n),this.log(`Initialized reader: ${t.name}`)}catch(r){this.log(`Warning: Failed to initialize reader ${t.name}: ${r}`,"warn")}}this.log(`Initialized ${this.readers.size} readers`)}async syncAll(){this.report=this.createReport("full");try{await this.connectToCloud();let e=this.config.sync.sources.filter(r=>r.enabled!==!1&&this.readers.has(r.name)).sort((r,i)=>{let o={high:0,medium:1,low:2};return o[r.priority]-o[i.priority]}),t=0,n=e.length;for(let r of e){this.progress(`Syncing ${r.name}...`,t/n);let i=await this.syncSource(r);this.report.results.push(i),t++}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(e){this.report.status="failed",this.report.errors.push(d(e))}finally{await this.disconnect(),this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((e,t)=>e+t.recordsSynced,0),this.report.totalConflictsResolved=this.report.results.reduce((e,t)=>e+t.conflictsResolved,0)}return this.report}async syncIncremental(e){this.report=this.createReport("incremental");let t=e||new Date(Date.now()-1440*60*1e3);try{await this.connectToCloud();let n=this.config.sync.sources.filter(r=>r.enabled!==!1&&this.readers.has(r.name)&&r.mode!=="full").sort((r,i)=>{let o={high:0,medium:1,low:2};return o[r.priority]-o[i.priority]});for(let r of n){this.progress(`Incremental sync ${r.name}...`,0);let i=await this.syncSourceIncremental(r,t);this.report.results.push(i)}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(n){this.report.status="failed",this.report.errors.push(d(n))}finally{await this.disconnect(),this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((n,r)=>n+r.recordsSynced,0)}return this.report}async syncSource(e){let t=Date.now(),n={success:!1,table:e.targetTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0,warnings:[]};try{let r=this.readers.get(e.name);if(!r)throw new Error(`Reader not found: ${e.name}`);let i=await r.readAll();if(this.log(`Read ${i.length} records from ${e.name}`),i.length===0)return n.success=!0,n.durationMs=Date.now()-t,n;if(this.writer&&!this.config.sync.dryRun){let o=await this.writer.upsert(e.targetTable,i,{skipIfExists:e.mode==="append"});n.recordsSynced=o}else n.recordsSynced=i.length,this.log(`[DRY RUN] Would sync ${i.length} records to ${e.targetTable}`);n.success=!0}catch(r){n.error=d(r),this.config.onError?.(L(r),e.name)}return n.durationMs=Date.now()-t,n}async syncSourceIncremental(e,t){let n=Date.now(),r={success:!1,table:e.targetTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0};try{let i=this.readers.get(e.name);if(!i)throw new Error(`Reader not found: ${e.name}`);let o=await i.readChanged(t);if(this.log(`Read ${o.length} changed records from ${e.name} (since ${t.toISOString()})`),o.length===0)return r.success=!0,r.durationMs=Date.now()-n,r;if(this.writer&&!this.config.sync.dryRun){let s=await this.writer.upsert(e.targetTable,o);r.recordsSynced=s}else r.recordsSynced=o.length;r.success=!0}catch(i){r.error=d(i)}return r.durationMs=Date.now()-n,r}async getStatus(){let e=[];for(let t of this.config.sync.sources){let n=this.readers.get(t.name);if(n){let r=await n.count();e.push({name:t.name,type:t.type,targetTable:t.targetTable,recordCount:r,enabled:t.enabled!==!1,priority:t.priority})}else e.push({name:t.name,type:t.type,targetTable:t.targetTable,recordCount:0,enabled:t.enabled!==!1,priority:t.priority,error:"Reader not initialized"})}return{sources:e}}async verify(){let e=[];for(let t of this.config.sync.sources.filter(n=>n.enabled!==!1)){let n=this.readers.get(t.name);if(!n)continue;let r=await n.count(),i=0;if(this.writer)try{await this.writer.beginTransaction(),await this.writer.execute("SET LOCAL enable_indexonlyscan = off");let o=await this.writer.query(`SELECT COUNT(*) as count FROM ${t.targetTable} WHERE source_env = $1`,[this.config.environment]);await this.writer.commit(),i=o[0]?.count||0}catch(o){try{await this.writer.rollback()}catch{}Me.debug("Cloud count query failed",{source:t.name,error:o instanceof Error?o.message:String(o)}),i=-1}e.push({source:t.name,table:t.targetTable,localCount:r,cloudCount:i,match:r===i,diff:r-i})}return{verified:e.every(t=>t.match||t.cloudCount===-1),results:e}}async close(){await this.disconnect();for(let e of Array.from(this.readers.entries())){let[t,n]=e;try{await n.close()}catch(r){this.log(`Warning: Failed to close reader ${t}: ${r}`,"warn")}}this.readers.clear(),this.log("Sync agent closed")}createReader(e){let t=process.cwd(),n=this.config.environment;return e.type==="sqlite"?re({source:e,baseDir:t,environment:n}):e.type==="json"?ne({source:e,baseDir:t,environment:n}):null}async connectToCloud(){if(this.writer)return;let e=M(this.config.cloud);this.writer=O({cloud:this.config.cloud,tunnelManager:e}),await this.writer.connect(),this.log("Connected to cloud database")}async disconnect(){this.writer&&(await this.writer.close(),this.writer=null)}createReport(e){return{syncId:I(),startedAt:new Date,status:"running",environment:this.config.environment,mode:e,results:[],totalRecordsSynced:0,totalConflictsResolved:0,totalDurationMs:0,errors:[]}}log(e,t="info"){if(!this.config.verbose&&t==="info")return;let n=`[CloudSync:${this.config.environment}]`;switch(t){case"warn":console.warn(`${n} ${e}`);break;case"error":console.error(`${n} ${e}`);break;default:console.log(`${n} ${e}`)}}progress(e,t){this.config.onProgress?.(e,t),this.log(e)}};function se(l){return new H(l)}async function Ne(l){let e=se({...l,verbose:!0});await e.initialize();try{return await e.syncAll()}finally{await e.close()}}async function Oe(l,e){let t=se({...e,verbose:!0});await t.initialize();try{return await t.syncIncremental(l)}finally{await t.close()}}import*as Y from"fs";import*as ae from"path";ue();P();v();var qt=b.create("pull-agent"),X=class{config;reader=null;writer=null;cloudWriter=null;report=null;constructor(e={}){this.config={...A,...e,cloud:{...A.cloud,...e.cloud},sources:e.sources||A.sources}}async initialize(){this.log("Initializing pull sync agent...");let e=M(this.config.cloud);this.cloudWriter=O({cloud:this.config.cloud,tunnelManager:e}),await this.cloudWriter.connect(),this.log("Connected to cloud database"),this.reader=ie({writer:this.cloudWriter,environment:this.config.environment});let t=this.resolveTargetDb();this.writer=oe({dbPath:t}),await this.writer.connect(),this.log(`Connected to local database: ${t}`)}async pullAll(){this.report=this.createReport("full");try{this.ensureInitialized(),this.backupLocalDb();let e=this.getEnabledSources(),t=0;for(let n of e){this.progress(`Pulling ${n.name}...`,t/e.length);let r=await this.pullTable(n);this.report.results.push(r),t++}this.report.status=this.report.results.every(n=>n.success)?"completed":"partial"}catch(e){this.report.status="failed",this.report.errors.push(d(e))}finally{this.finalizeReport()}return this.report}async pullIncremental(e){this.report=this.createReport("incremental");let t=e||new Date(Date.now()-1440*60*1e3);try{this.ensureInitialized(),this.backupLocalDb();let n=this.getEnabledSources().filter(r=>r.mode!=="full");for(let r of n){this.progress(`Incremental pull ${r.name}...`,0);let i=await this.pullTableIncremental(r,t);this.report.results.push(i)}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(n){this.report.status="failed",this.report.errors.push(d(n))}finally{this.finalizeReport()}return this.report}async pullTable(e){let t=Date.now(),n={success:!1,table:e.localTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0,warnings:[]};try{this.ensureInitialized();let r=await this.reader.readAll(e);if(this.log(`Read ${r.length} records from cloud ${e.cloudTable}`),r.length===0)return n.success=!0,n.durationMs=Date.now()-t,n;if(this.config.dryRun)n.recordsSynced=r.length,this.log(`[DRY RUN] Would write ${r.length} records to local ${e.localTable}`);else{let i=await this.writer.upsert(e.localTable,r);n.recordsSynced=i,n.recordsSkipped=r.length-i}n.success=!0}catch(r){n.error=d(r),this.config.onError?.(L(r),e.name)}return n.durationMs=Date.now()-t,n}async pullTableIncremental(e,t){let n=Date.now(),r={success:!1,table:e.localTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0};try{this.ensureInitialized();let i=await this.reader.readChanged(e,t);if(this.log(`Read ${i.length} changed records from cloud ${e.cloudTable} (since ${t.toISOString()})`),i.length===0)return r.success=!0,r.durationMs=Date.now()-n,r;if(this.config.dryRun)r.recordsSynced=i.length;else{let o=await this.writer.upsert(e.localTable,i);r.recordsSynced=o}r.success=!0}catch(i){r.error=d(i)}return r.durationMs=Date.now()-n,r}async verify(){this.ensureInitialized();let e=[];for(let t of this.getEnabledSources()){let n=await this.reader.count(t),r=await this.writer.count(t.localTable);e.push({source:t.name,cloudTable:t.cloudTable,localTable:t.localTable,cloudCount:n,localCount:r,match:n===r||n===-1,diff:r-n})}return{verified:e.every(t=>t.match),results:e}}async close(){this.writer&&(await this.writer.close(),this.writer=null),this.cloudWriter&&(await this.cloudWriter.close(),this.cloudWriter=null),this.reader=null,this.log("Pull sync agent closed")}ensureInitialized(){if(!this.reader||!this.writer)throw new Error("PullSyncAgent not initialized. Call initialize() first.")}getEnabledSources(){let e=this.config.sources.filter(n=>n.enabled);if(this.config.tables&&this.config.tables.length>0){let n=new Set(this.config.tables);e=e.filter(r=>n.has(r.localTable)||n.has(r.name))}let t={high:0,medium:1,low:2};return e.sort((n,r)=>t[n.priority]-t[r.priority])}resolveTargetDb(){return this.config.targetDb?ae.resolve(this.config.targetDb):ae.resolve(j(),".agentic-qe/memory.db")}backupLocalDb(){if(this.config.dryRun)return;let e=this.resolveTargetDb();if(!Y.existsSync(e))return;let t=Math.floor(Date.now()/1e3),n=`${e}.bak-${t}`;try{Y.copyFileSync(e,n),this.log(`Backed up local DB to ${n}`)}catch(r){this.log(`Warning: Failed to backup local DB: ${d(r)}`,"warn")}}createReport(e){return{syncId:I(),startedAt:new Date,status:"running",environment:this.config.environment,mode:e,results:[],totalRecordsSynced:0,totalConflictsResolved:0,totalDurationMs:0,errors:[]}}finalizeReport(){this.report&&(this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((e,t)=>e+t.recordsSynced,0),this.report.totalConflictsResolved=this.report.results.reduce((e,t)=>e+t.conflictsResolved,0))}log(e,t="info"){if(!this.config.verbose&&t==="info")return;let n=`[PullSync:${this.config.environment}]`;switch(t){case"warn":console.warn(`${n} ${e}`);break;case"error":console.error(`${n} ${e}`);break;default:console.log(`${n} ${e}`)}}progress(e,t){this.config.onProgress?.(e,t),this.log(e)}};function ce(l){return new X(l)}async function De(l){let e=ce({...l,verbose:!0});await e.initialize();try{return await e.pullAll()}finally{await e.close()}}async function qe(l,e){let t=ce({...e,verbose:!0});await t.initialize();try{return await t.pullIncremental(l)}finally{await t.close()}}z();ue();ee();import{join as ye}from"path";import{existsSync as Le,mkdirSync as Ie}from"fs";var K=class{memoryCache;maxSize;ttl;persistent;compression;db=null;storagePath;useUnified;unifiedMemory=null;pendingWrites=[];dbInitializing=!1;constructor(e={}){this.maxSize=e.maxSize||1e4,this.ttl=e.ttl||0,this.persistent=e.persistent??!0,this.compression=e.compression??!0,this.useUnified=e.useUnified??!0,this.storagePath=e.storagePath||ye(j(),".agentic-qe","embeddings-cache.db"),this.memoryCache=new Map;let t=["text","code","test","coverage","defect"];for(let n of t)this.memoryCache.set(n,new Map);this.persistent&&this.initializePersistentStorage()}initializePersistentStorage(){try{if(this.useUnified)this.unifiedMemory=de(),this.dbInitializing=!0,this.unifiedMemory.initialize().then(()=>{this.db=this.unifiedMemory.getDatabase(),this.dbInitializing=!1,console.log(`[EmbeddingCache] Using unified storage: ${this.unifiedMemory.getDbPath()}`),this.loadFromDisk(),this.flushPendingWrites()}).catch(e=>{console.warn("[EmbeddingCache] Failed to initialize unified storage:",e),this.db=null,this.dbInitializing=!1,this.unifiedMemory=null,this.pendingWrites=[]});else{let e=ye(this.storagePath,"..");Le(e)||Ie(e,{recursive:!0}),this.db=T(this.storagePath),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.exec(`
9
+ CREATE TABLE IF NOT EXISTS embeddings (
10
+ key TEXT NOT NULL,
11
+ namespace TEXT NOT NULL,
12
+ vector BLOB NOT NULL,
13
+ dimension INTEGER NOT NULL,
14
+ text TEXT NOT NULL,
15
+ timestamp INTEGER NOT NULL,
16
+ quantization TEXT NOT NULL,
17
+ metadata TEXT,
18
+ access_count INTEGER DEFAULT 1,
19
+ last_access INTEGER NOT NULL,
20
+ PRIMARY KEY (key, namespace)
21
+ );
22
+
23
+ CREATE INDEX IF NOT EXISTS idx_namespace ON embeddings(namespace);
24
+ CREATE INDEX IF NOT EXISTS idx_timestamp ON embeddings(timestamp);
25
+ `),console.log(`[EmbeddingCache] Initialized (legacy): ${this.storagePath}`),this.loadFromDisk()}}catch(e){console.warn("Failed to initialize persistent storage:",e),this.db=null}}get(e,t="text"){let n=this.memoryCache.get(t);if(!n)return null;let r=n.get(e);return r?this.ttl>0&&Date.now()-r.lastAccess>this.ttl*1e3?(n.delete(e),null):(r.accessCount++,r.lastAccess=Date.now(),r.embedding):null}set(e,t,n="text"){let r=this.memoryCache.get(n);if(!r)return;r.size>=this.maxSize&&!r.has(e)&&this.evictLRU(n);let i={key:e,embedding:t,accessCount:1,lastAccess:Date.now()};r.set(e,i),this.persistent&&(this.db?this.persistToDisk(e,t,n):this.dbInitializing&&this.pendingWrites.push({key:e,embedding:t,namespace:n}))}has(e,t="text"){return this.memoryCache.get(t)?.has(e)||!1}delete(e,t="text"){let r=this.memoryCache.get(t)?.delete(e)||!1;return r&&this.persistent&&this.db&&this.db.prepare("DELETE FROM embeddings WHERE key = ? AND namespace = ?").run(e,t),r}clear(e){if(e)this.memoryCache.get(e)?.clear(),this.persistent&&this.db&&this.db.prepare("DELETE FROM embeddings WHERE namespace = ?").run(e);else{for(let t of this.memoryCache.values())t.clear();this.persistent&&this.db&&this.db.exec("DELETE FROM embeddings")}}getAll(e){let t=[];if(e)this.memoryCache.get(e)?.forEach(r=>t.push(r.embedding));else for(let n of this.memoryCache.values())n.forEach(r=>t.push(r.embedding));return t}evictLRU(e){let t=this.memoryCache.get(e);if(!t||t.size===0)return;let n=null,r=1/0;for(let[i,o]of t.entries())o.lastAccess<r&&(r=o.lastAccess,n=i);n&&(t.delete(n),this.persistent&&this.db&&this.db.prepare("DELETE FROM embeddings WHERE key = ? AND namespace = ?").run(n,e))}persistToDisk(e,t,n){if(this.db)try{let r=this.serializeVector(t.vector),i=t.metadata?JSON.stringify(t.metadata):null;this.db.prepare(`
26
+ INSERT OR REPLACE INTO embeddings
27
+ (key, namespace, vector, dimension, text, timestamp, quantization, metadata, last_access)
28
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
29
+ `).run(e,n,r,t.dimension,t.text,t.timestamp,t.quantization,i,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.12.3");process.exit(0)}
2
- import{b as f,d as v}from"./chunk-OBL6W4Z5.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,9 +1,9 @@
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.12.3");process.exit(0)}
2
- import{a as b}from"./chunk-UZ7FXVH5.js";import{a as te,b as ne}from"./chunk-VFYMWDSJ.js";import{b as ee}from"./chunk-J2RJOJ5Q.js";import{b as E,d as ve}from"./chunk-OBL6W4Z5.js";import{a as k,c as T}from"./chunk-2LNDU7AW.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.12.3"}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(`
6
- `),n=this.removeDelimitedBlocks(n,'"""','"""'),n=this.removeDelimitedBlocks(n,"'''","'''"),n=this.removeDelimitedBlocks(n,'"','"'),n=this.removeDelimitedBlocks(n,"'","'")),n}calculateComplexity(e){let t=1,n=[{pattern:/(?<![a-zA-Z])if\s*\(/g,name:"if"},{pattern:/\bfor\s*\(/g,name:"for"},{pattern:/\bwhile\s*\(/g,name:"while"},{pattern:/\bcase\s+[^:]+:/g,name:"case"},{pattern:/\bcatch\s*\(/g,name:"catch"},{pattern:/&&/g,name:"&&"},{pattern:/\|\|/g,name:"||"},{pattern:/\?[^?:]+:/g,name:"ternary"},{pattern:/\belif\s+/g,name:"elif"},{pattern:/\bexcept\s*(?:\w+)?:/g,name:"except"},{pattern:/\bfor\s+\w+\s+in\s+/g,name:"for-in"},{pattern:/\bselect\s*\{/g,name:"select"}];for(let{pattern:i}of n){let s=e.match(i);s&&(t+=s.length)}return t}async measureCoverage(){let e=["coverage/lcov-report/index.html","coverage/coverage-summary.json","coverage/clover.xml","coverage/lcov.info","htmlcov/index.html"];for(let t of e){let n=g(this.projectRoot,t);if(p(n)){if(t.endsWith(".json"))try{let s=E(C(n,"utf-8")).total||{};return{lines:s.lines?.pct||0,branches:s.branches?.pct||0,functions:s.functions?.pct||0,statements:s.statements?.pct||0,hasReport:!0,reportPath:t}}catch(i){console.debug("[ProjectAnalyzer] Coverage report parse failed:",i instanceof Error?i.message:i)}return{lines:0,branches:0,functions:0,statements:0,hasReport:!0,reportPath:t}}}return{lines:0,branches:0,functions:0,statements:0,hasReport:!1}}detectProjectType(){if(p(g(this.projectRoot,"lerna.json"))||p(g(this.projectRoot,"pnpm-workspace.yaml"))||p(g(this.projectRoot,"packages")))return"monorepo";let e=S(this.projectRoot);return e?.workspaces?"monorepo":e?.main||e?.module||e?.exports?"library":"single"}detectPackageManager(){return p(g(this.projectRoot,"bun.lockb"))?"bun":p(g(this.projectRoot,"pnpm-lock.yaml"))?"pnpm":p(g(this.projectRoot,"yarn.lock"))?"yarn":p(g(this.projectRoot,"package-lock.json"))?"npm":"unknown"}detectCIConfig(){return[".github/workflows",".gitlab-ci.yml","Jenkinsfile",".circleci/config.yml",".travis.yml","azure-pipelines.yml"].some(t=>p(g(this.projectRoot,t)))}detectCIProvider(){if(p(g(this.projectRoot,".github/workflows")))return"github-actions";if(p(g(this.projectRoot,".gitlab-ci.yml")))return"gitlab-ci";if(p(g(this.projectRoot,"Jenkinsfile")))return"jenkins";if(p(g(this.projectRoot,".circleci/config.yml")))return"circleci";if(this.detectCIConfig())return"other"}};function Ue(r){return new W(r)}var se=[{name:"typescript-vitest",condition:r=>r.hasTypeScript&&r.frameworks.some(e=>e.name==="vitest"),apply:r=>{r.learning.embeddingModel="transformer",r.routing.confidenceThreshold=.75}},{name:"large-codebase",condition:r=>r.codeComplexity.totalFiles>500,apply:r=>{r.learning.hnswConfig.M=32,r.learning.hnswConfig.efConstruction=400,r.learning.hnswConfig.efSearch=200,r.agents.maxConcurrent=15}},{name:"small-project",condition:r=>r.codeComplexity.totalFiles<50,apply:r=>{r.learning.hnswConfig.M=8,r.learning.hnswConfig.efConstruction=100,r.workers.enabled=["pattern-consolidator","routing-accuracy-monitor"],r.workers.maxConcurrent=2,r.agents.maxConcurrent=5}},{name:"high-complexity",condition:r=>r.codeComplexity.recommendation==="complex",apply:r=>{r.autoTuning.parameters.push("complexity.analysisDepth"),r.domains.enabled=L}},{name:"low-coverage",condition:r=>r.coverage.hasReport&&r.coverage.lines<50,apply:r=>{r.workers.enabled.push("coverage-gap-scanner"),r.workers.intervals["coverage-gap-scanner"]=1800*1e3}},{name:"monorepo",condition:r=>r.projectType==="monorepo",apply:r=>{r.agents.maxConcurrent=15,r.workers.maxConcurrent=6,r.domains.enabled=[...new Set([...r.domains.enabled,"code-intelligence"])]}},{name:"has-e2e",condition:r=>r.frameworks.some(e=>["playwright","cypress"].includes(e.name))||r.existingTests.byType.e2e>0,apply:r=>{r.domains.enabled=[...new Set([...r.domains.enabled,"visual-accessibility","chaos-resilience"])]}},{name:"has-ci",condition:r=>r.hasCIConfig,apply:r=>{r.hooks.ciIntegration=!0,r.domains.enabled=[...new Set([...r.domains.enabled,"quality-assessment"])]}},{name:"github-actions",condition:r=>r.ciProvider==="github-actions",apply:r=>{r.hooks.ciIntegration=!0,r.hooks.claudeCode=!0}},{name:"python-project",condition:r=>r.languages.some(e=>e.name==="python"&&e.percentage>30),apply:r=>{r.routing.mode="hybrid",r.domains.enabled=[...new Set([...r.domains.enabled,"security-compliance"])]}},{name:"java-project",condition:r=>r.languages.some(e=>e.name==="java"&&e.percentage>30),apply:r=>{r.agents.defaultTimeout=12e4}},{name:"no-tests",condition:r=>r.existingTests.totalCount===0,apply:r=>{r.workers.enabled=["pattern-consolidator"],r.learning.qualityThreshold=.5,r.learning.promotionThreshold=2}},{name:"many-tests",condition:r=>r.existingTests.totalCount>500,apply:r=>{r.workers.enabled=[...new Set([...r.workers.enabled,"flaky-test-detector"])],r.domains.enabled=[...new Set([...r.domains.enabled,"test-execution"])]}},{name:"security-focus",condition:r=>r.codeComplexity.totalFiles>100,apply:r=>{r.domains.enabled=[...new Set([...r.domains.enabled,"security-compliance"])]}}],z=class{rules;constructor(e={}){this.rules=e.minimal?se.filter(t=>["typescript-vitest","large-codebase","small-project"].includes(t.name)):[...se,...e.customRules||[]]}recommend(e){let t={version:M(),project:{name:e.projectName,root:e.projectRoot,type:e.projectType==="unknown"?"single":e.projectType},learning:this.recommendLearning(e),routing:this.recommendRouting(e),workers:this.recommendWorkers(e),hooks:this.recommendHooks(e),skills:this.recommendSkills(e),autoTuning:this.recommendAutoTuning(e),domains:{enabled:this.recommendDomains(e),disabled:[]},agents:{maxConcurrent:this.recommendMaxAgents(e),defaultTimeout:6e4}},n=[];for(let i of this.rules)i.condition(e)&&(i.apply(t,e),n.push(i.name));return t.domains.enabled=[...new Set(t.domains.enabled)],t.workers.enabled=[...new Set(t.workers.enabled)],t}getApplicableRules(e){return this.rules.filter(t=>t.condition(e)).map(t=>t.name)}recommendLearning(e){let t={...P};return e.codeComplexity.totalFiles>1e3?t.hnswConfig={M:32,efConstruction:400,efSearch:200}:e.codeComplexity.totalFiles<100&&(t.hnswConfig={M:8,efConstruction:100,efSearch:50}),e.languages.some(n=>["typescript","javascript"].includes(n.name))&&(t.embeddingModel="transformer"),t}recommendRouting(e){let t={..._};return e.codeComplexity.recommendation==="simple"?t.mode="rules":e.codeComplexity.recommendation==="complex"?t.mode="ml":t.mode="hybrid",t}recommendWorkers(e){let t={...F},n=new Set(["pattern-consolidator","routing-accuracy-monitor"]);return(!e.coverage.hasReport||e.coverage.lines<70)&&n.add("coverage-gap-scanner"),e.existingTests.totalCount>100&&n.add("flaky-test-detector"),t.enabled=Array.from(n),e.codeComplexity.totalFiles>500?t.maxConcurrent=6:e.codeComplexity.totalFiles<50&&(t.maxConcurrent=2),t}recommendHooks(e){let t={...$};return t.ciIntegration=e.hasCIConfig,t.preCommit=e.existingTests.totalCount>50,t}recommendSkills(e){let t={...N};return t.install=!0,t.installV2=!0,t.installV3=!0,t}recommendAutoTuning(e){let t={...O};return e.codeComplexity.totalFiles<20&&(t.enabled=!1),t}recommendDomains(e){return["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization"]}recommendMaxAgents(e){return e.projectType==="monorepo"?15:e.codeComplexity.totalFiles>500?12:e.codeComplexity.totalFiles>100?8:5}};function Ke(r){return new z(r)}import{existsSync as oe,readFileSync as we,writeFileSync as Ce}from"fs";function Ze(r){if(!oe(r))return null;let e=`${r}.backup`;if(oe(e))return null;try{return Ce(e,we(r,"utf-8"),"utf-8"),e}catch{return null}}var De=[/\baqe\b/i,/\bagentic-qe\b/i,/\bnpx\s+agentic-qe\b/i,/\bnpx\s+@anthropics\/agentic-qe\b/i,/aqe-hook\.cjs/i,/brain-checkpoint\.cjs/i,/statusline-v3\.cjs/i];function je(r){let e=r;return!e?.hooks||!Array.isArray(e.hooks)?!1:e.hooks.some(t=>!t.command||typeof t.command!="string"?!1:De.some(n=>n.test(t.command)))}function Xe(r,e){let t={};for(let[n,i]of Object.entries(e)){let s=r[n]||[],o=Array.isArray(s)?s.filter(a=>!je(a)):[];t[n]=[...i,...o]}for(let[n,i]of Object.entries(r))t[n]||(t[n]=i);return t}function et(r,e){return{...e,...r||{}}}function tt(r){let e=r.domains?.enabled||[];return{AQE_MEMORY_PATH:".agentic-qe/memory.db",AQE_MEMORY_ENABLED:"true",AQE_LEARNING_ENABLED:r.learning?.enabled?"true":"false",AQE_V3_MODE:"true",AQE_V3_DDD_ENABLED:"true",AQE_V3_DOMAINS:e.join(","),AQE_V3_SWARM_SIZE:String(r.agents?.maxConcurrent??15),AQE_V3_TOPOLOGY:"hierarchical",AQE_V3_SUBLINEAR_ENABLED:"true",AQE_V3_HNSW_ENABLED:r.learning?.hnswConfig?"true":"false",AQE_V3_HOOKS_ENABLED:"true",AQE_V3_AISP_ENABLED:"true",AQE_V3_REASONING_BANK:".agentic-qe/memory.db",AQE_V3_PATTERN_PROMOTION_THRESHOLD:String(r.learning?.promotionThreshold??3),AQE_V3_SUCCESS_RATE_THRESHOLD:String(r.learning?.qualityThreshold??.7)}}function Re(r){let e=r?.command;return typeof e=="string"&&/statusline-v3\.cjs|Agentic QE v3/.test(e)}function le(r,e){if(!ae(r)||!ae(e))return e;let t={...r};for(let[n,i]of Object.entries(e))t[n]=le(t[n],i);return t}function ae(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function nt(r,e){for(let[t,n]of Object.entries(e))if(t==="_aqePermissions"){let i=r.permissions||{},s=i.allow||[],o=[...new Set([...s,...n])];r.permissions={...i,allow:o}}else t==="statusLine"?(r.statusLine===void 0||Re(r.statusLine))&&(r.statusLine=n):t==="includeCoAuthoredBy"?r.includeCoAuthoredBy===void 0&&(r.includeCoAuthoredBy=n):r[t]=le(r[t],n);return r}function rt(r,e){let t=r.domains?.enabled||[];return{aqe:{version:r.version??"3.0.0",initialized:new Date().toISOString(),hooksConfigured:!0},statusLine:{type:"command",command:`sh -c 'node "\${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/statusline-v3.cjs" 2>/dev/null || echo "\u258A Agentic QE v3"'`,refreshMs:5e3,enabled:!0},_aqePermissions:["Bash(npx agentic-qe:*)","Bash(npx @anthropics/agentic-qe:*)","mcp__agentic-qe__*"],includeCoAuthoredBy:!0,v3Configuration:{domains:{total:t.length,names:t},swarm:{totalAgents:r.agents?.maxConcurrent??15,topology:"hierarchical",coordination:"queen-led"}},v3Learning:{enabled:r.learning?.enabled??!0,reasoningBank:{dbPath:".agentic-qe/memory.db",enableHNSW:!!r.learning?.hnswConfig},patternPromotion:{threshold:r.learning?.promotionThreshold??3,successRateMin:r.learning?.qualityThreshold??.7}}}}T();import{existsSync as h,mkdirSync as j,readdirSync as R,statSync as G,readFileSync as Ie,writeFileSync as qe,copyFileSync as Te,unlinkSync as Ee,rmdirSync as Pe}from"fs";import{join as m}from"path";var U=["qe-test-generation","qe-test-execution","qe-coverage-analysis","qe-quality-assessment","qe-defect-intelligence","qe-requirements-validation","qe-code-intelligence","qe-browser","pentest-validation","qe-visual-accessibility","qe-chaos-resilience","qe-learning-optimization","qe-iterative-loop","strict-tdd","no-skip","coverage-guard","freeze-tests","security-watch","skill-stats","test-failure-investigator","coverage-drop-investigator","e2e-flow-verifier","test-metrics-dashboard"],H=["v3-core-implementation","v3-cli-modernization","v3-ddd-architecture","v3-integration-deep","v3-mcp-optimization","v3-memory-unification","v3-performance-optimization","v3-security-overhaul","v3-swarm-coordination","v3-qe-core-implementation","v3-qe-ddd-architecture","v3-qe-cli","v3-qe-memory-system","v3-qe-performance","v3-qe-security","v3-qe-mcp","v3-qe-mcp-optimization","v3-qe-memory-unification","v3-qe-integration","v3-qe-agentic-flow-integration","v3-qe-fleet-coordination","agentdb-advanced","agentdb-learning","agentdb-memory-patterns","agentdb-optimization","agentdb-vector-search","github-code-review","github-multi-repo","github-project-management","github-release-management","github-workflow-automation","flow-nexus-neural","flow-nexus-platform","flow-nexus-swarm","reasoningbank-agentdb","reasoningbank-intelligence","swarm-orchestration","swarm-advanced","sparc-methodology","hooks-automation","hive-mind-advanced","stream-chain","agentic-jujutsu","iterative-loop","performance-analysis","skill-builder","qe-agentic-flow-integration","release"],_e=["qe-contract-testing","qe-security-compliance","aqe-v2-v3-migration"],B=class{projectRoot;options;sourceSkillsDir;constructor(e){this.projectRoot=e.projectRoot,this.options={installV2Skills:!0,installV3Skills:!0,overwrite:!1,exclude:[],include:void 0,...e},this.sourceSkillsDir=this.findSourceSkillsDir()}findSourceSkillsDir(){let e=b(import.meta.url),t=[];e&&(t.push(m(e,"assets/skills")),t.push(m(e,".claude/skills"))),t.push(m(this.projectRoot,"node_modules/agentic-qe/assets/skills"));for(let n of t)if(h(n))return n;return t[0]}async install(){let e={installed:[],skipped:[],removed:[],errors:[],totalCount:0,skillsDir:m(this.projectRoot,".claude","skills"),validationInstalled:!1};if(!h(this.sourceSkillsDir))return e.errors.push(`Source skills directory not found: ${this.sourceSkillsDir}`),e;let t=m(this.projectRoot,".claude","skills");h(t)||j(t,{recursive:!0});let n=this.getAvailableSkills();e.totalCount=n.length;let i=this.filterSkills(n);for(let s of i)try{let o=await this.installSkill(s,t);o?e.installed.push(o):e.skipped.push(s)}catch(o){e.errors.push(`Failed to install ${s}: ${k(o)}`)}return this.options.overwrite&&(e.removed=this.removeDeprecatedSkills(t)),e.validationInstalled=this.installValidationInfrastructure(t),await this.createSkillsIndex(t,e.installed),e}installValidationInfrastructure(e){let t=m(this.sourceSkillsDir,".validation"),n=m(e,".validation");if(!h(t))return console.debug("[SkillsInstaller] Validation infrastructure not found in source"),!1;if(h(n)&&!this.options.overwrite)return console.debug("[SkillsInstaller] Validation infrastructure already exists, skipping"),!0;try{return h(n)||j(n,{recursive:!0}),this.copyDirectoryRecursive(t,n),console.debug("[SkillsInstaller] Validation infrastructure installed successfully"),!0}catch(i){return console.error("[SkillsInstaller] Failed to install validation infrastructure:",i instanceof Error?i.message:i),!1}}removeDeprecatedSkills(e){let t=[];for(let n of _e){let i=m(e,n);if(h(i))try{this.removeDirectoryRecursive(i),t.push(n)}catch(s){console.error(`[SkillsInstaller] Failed to remove deprecated skill ${n}:`,s instanceof Error?s.message:s)}}return t.length>0&&console.debug(`[SkillsInstaller] Removed ${t.length} deprecated skills: ${t.join(", ")}`),t}removeDirectoryRecursive(e){let t=R(e,{withFileTypes:!0});for(let n of t){let i=m(e,n.name);n.isDirectory()?this.removeDirectoryRecursive(i):Ee(i)}Pe(e)}getAvailableSkills(){try{return R(this.sourceSkillsDir).filter(t=>{let n=m(this.sourceSkillsDir,t);return G(n).isDirectory()&&!t.startsWith(".")})}catch{return[]}}filterSkills(e){let t=e;return t=t.filter(n=>!H.includes(n)),this.options.include&&this.options.include.length>0&&(t=t.filter(n=>this.options.include.includes(n))),this.options.exclude&&this.options.exclude.length>0&&(t=t.filter(n=>!this.options.exclude.some(i=>n.includes(i)||n.match(new RegExp(i))))),this.options.installV3Skills||(t=t.filter(n=>!U.includes(n))),this.options.installV2Skills||(t=t.filter(n=>U.includes(n))),t}async installSkill(e,t){let n=m(this.sourceSkillsDir,e),i=m(t,e);if(h(i)&&!this.options.overwrite)return null;h(i)||j(i,{recursive:!0}),this.copyDirectoryRecursive(n,i);let s=this.getSkillType(e),o=this.getSkillDescription(i),a=h(m(i,"resources"));return{name:e,type:s,description:o,hasResources:a}}copyDirectoryRecursive(e,t){let n=R(e);for(let i of n){let s=m(e,i),o=m(t,i);G(s).isDirectory()?(h(o)||j(o,{recursive:!0}),this.copyDirectoryRecursive(s,o)):Te(s,o)}}getSkillType(e){return U.includes(e)?"v3-domain":"v2-methodology"}getSkillDescription(e){let t=m(e,"SKILL.md");if(h(t))try{let n=Ie(t,"utf-8"),i=n.match(/description:\s*["']?([^"'\n]+)["']?/i);if(i)return i[1].trim();let s=n.split(`
6
+ `),n=this.removeDelimitedBlocks(n,'"""','"""'),n=this.removeDelimitedBlocks(n,"'''","'''"),n=this.removeDelimitedBlocks(n,'"','"'),n=this.removeDelimitedBlocks(n,"'","'")),n}calculateComplexity(e){let t=1,n=[{pattern:/(?<![a-zA-Z])if\s*\(/g,name:"if"},{pattern:/\bfor\s*\(/g,name:"for"},{pattern:/\bwhile\s*\(/g,name:"while"},{pattern:/\bcase\s+[^:]+:/g,name:"case"},{pattern:/\bcatch\s*\(/g,name:"catch"},{pattern:/&&/g,name:"&&"},{pattern:/\|\|/g,name:"||"},{pattern:/\?[^?:]+:/g,name:"ternary"},{pattern:/\belif\s+/g,name:"elif"},{pattern:/\bexcept\s*(?:\w+)?:/g,name:"except"},{pattern:/\bfor\s+\w+\s+in\s+/g,name:"for-in"},{pattern:/\bselect\s*\{/g,name:"select"}];for(let{pattern:i}of n){let s=e.match(i);s&&(t+=s.length)}return t}async measureCoverage(){let e=["coverage/lcov-report/index.html","coverage/coverage-summary.json","coverage/clover.xml","coverage/lcov.info","htmlcov/index.html"];for(let t of e){let n=g(this.projectRoot,t);if(p(n)){if(t.endsWith(".json"))try{let s=E(C(n,"utf-8")).total||{};return{lines:s.lines?.pct||0,branches:s.branches?.pct||0,functions:s.functions?.pct||0,statements:s.statements?.pct||0,hasReport:!0,reportPath:t}}catch(i){console.debug("[ProjectAnalyzer] Coverage report parse failed:",i instanceof Error?i.message:i)}return{lines:0,branches:0,functions:0,statements:0,hasReport:!0,reportPath:t}}}return{lines:0,branches:0,functions:0,statements:0,hasReport:!1}}detectProjectType(){if(p(g(this.projectRoot,"lerna.json"))||p(g(this.projectRoot,"pnpm-workspace.yaml"))||p(g(this.projectRoot,"packages")))return"monorepo";let e=S(this.projectRoot);return e?.workspaces?"monorepo":e?.main||e?.module||e?.exports?"library":"single"}detectPackageManager(){return p(g(this.projectRoot,"bun.lockb"))?"bun":p(g(this.projectRoot,"pnpm-lock.yaml"))?"pnpm":p(g(this.projectRoot,"yarn.lock"))?"yarn":p(g(this.projectRoot,"package-lock.json"))?"npm":"unknown"}detectCIConfig(){return[".github/workflows",".gitlab-ci.yml","Jenkinsfile",".circleci/config.yml",".travis.yml","azure-pipelines.yml"].some(t=>p(g(this.projectRoot,t)))}detectCIProvider(){if(p(g(this.projectRoot,".github/workflows")))return"github-actions";if(p(g(this.projectRoot,".gitlab-ci.yml")))return"gitlab-ci";if(p(g(this.projectRoot,"Jenkinsfile")))return"jenkins";if(p(g(this.projectRoot,".circleci/config.yml")))return"circleci";if(this.detectCIConfig())return"other"}};function Ue(r){return new W(r)}var se=[{name:"typescript-vitest",condition:r=>r.hasTypeScript&&r.frameworks.some(e=>e.name==="vitest"),apply:r=>{r.learning.embeddingModel="transformer",r.routing.confidenceThreshold=.75}},{name:"large-codebase",condition:r=>r.codeComplexity.totalFiles>500,apply:r=>{r.learning.hnswConfig.M=32,r.learning.hnswConfig.efConstruction=400,r.learning.hnswConfig.efSearch=200,r.agents.maxConcurrent=15}},{name:"small-project",condition:r=>r.codeComplexity.totalFiles<50,apply:r=>{r.learning.hnswConfig.M=8,r.learning.hnswConfig.efConstruction=100,r.workers.enabled=["pattern-consolidator","routing-accuracy-monitor"],r.workers.maxConcurrent=2,r.agents.maxConcurrent=5}},{name:"high-complexity",condition:r=>r.codeComplexity.recommendation==="complex",apply:r=>{r.autoTuning.parameters.push("complexity.analysisDepth"),r.domains.enabled=L}},{name:"low-coverage",condition:r=>r.coverage.hasReport&&r.coverage.lines<50,apply:r=>{r.workers.enabled.push("coverage-gap-scanner"),r.workers.intervals["coverage-gap-scanner"]=1800*1e3}},{name:"monorepo",condition:r=>r.projectType==="monorepo",apply:r=>{r.agents.maxConcurrent=15,r.workers.maxConcurrent=6,r.domains.enabled=[...new Set([...r.domains.enabled,"code-intelligence"])]}},{name:"has-e2e",condition:r=>r.frameworks.some(e=>["playwright","cypress"].includes(e.name))||r.existingTests.byType.e2e>0,apply:r=>{r.domains.enabled=[...new Set([...r.domains.enabled,"visual-accessibility","chaos-resilience"])]}},{name:"has-ci",condition:r=>r.hasCIConfig,apply:r=>{r.hooks.ciIntegration=!0,r.domains.enabled=[...new Set([...r.domains.enabled,"quality-assessment"])]}},{name:"github-actions",condition:r=>r.ciProvider==="github-actions",apply:r=>{r.hooks.ciIntegration=!0,r.hooks.claudeCode=!0}},{name:"python-project",condition:r=>r.languages.some(e=>e.name==="python"&&e.percentage>30),apply:r=>{r.routing.mode="hybrid",r.domains.enabled=[...new Set([...r.domains.enabled,"security-compliance"])]}},{name:"java-project",condition:r=>r.languages.some(e=>e.name==="java"&&e.percentage>30),apply:r=>{r.agents.defaultTimeout=12e4}},{name:"no-tests",condition:r=>r.existingTests.totalCount===0,apply:r=>{r.workers.enabled=["pattern-consolidator"],r.learning.qualityThreshold=.5,r.learning.promotionThreshold=2}},{name:"many-tests",condition:r=>r.existingTests.totalCount>500,apply:r=>{r.workers.enabled=[...new Set([...r.workers.enabled,"flaky-test-detector"])],r.domains.enabled=[...new Set([...r.domains.enabled,"test-execution"])]}},{name:"security-focus",condition:r=>r.codeComplexity.totalFiles>100,apply:r=>{r.domains.enabled=[...new Set([...r.domains.enabled,"security-compliance"])]}}],z=class{rules;constructor(e={}){this.rules=e.minimal?se.filter(t=>["typescript-vitest","large-codebase","small-project"].includes(t.name)):[...se,...e.customRules||[]]}recommend(e){let t={version:M(),project:{name:e.projectName,root:e.projectRoot,type:e.projectType==="unknown"?"single":e.projectType},learning:this.recommendLearning(e),routing:this.recommendRouting(e),workers:this.recommendWorkers(e),hooks:this.recommendHooks(e),skills:this.recommendSkills(e),autoTuning:this.recommendAutoTuning(e),domains:{enabled:this.recommendDomains(e),disabled:[]},agents:{maxConcurrent:this.recommendMaxAgents(e),defaultTimeout:6e4}},n=[];for(let i of this.rules)i.condition(e)&&(i.apply(t,e),n.push(i.name));return t.domains.enabled=[...new Set(t.domains.enabled)],t.workers.enabled=[...new Set(t.workers.enabled)],t}getApplicableRules(e){return this.rules.filter(t=>t.condition(e)).map(t=>t.name)}recommendLearning(e){let t={...P};return e.codeComplexity.totalFiles>1e3?t.hnswConfig={M:32,efConstruction:400,efSearch:200}:e.codeComplexity.totalFiles<100&&(t.hnswConfig={M:8,efConstruction:100,efSearch:50}),e.languages.some(n=>["typescript","javascript"].includes(n.name))&&(t.embeddingModel="transformer"),t}recommendRouting(e){let t={..._};return e.codeComplexity.recommendation==="simple"?t.mode="rules":e.codeComplexity.recommendation==="complex"?t.mode="ml":t.mode="hybrid",t}recommendWorkers(e){let t={...F},n=new Set(["pattern-consolidator","routing-accuracy-monitor"]);return(!e.coverage.hasReport||e.coverage.lines<70)&&n.add("coverage-gap-scanner"),e.existingTests.totalCount>100&&n.add("flaky-test-detector"),t.enabled=Array.from(n),e.codeComplexity.totalFiles>500?t.maxConcurrent=6:e.codeComplexity.totalFiles<50&&(t.maxConcurrent=2),t}recommendHooks(e){let t={...$};return t.ciIntegration=e.hasCIConfig,t.preCommit=e.existingTests.totalCount>50,t}recommendSkills(e){let t={...N};return t.install=!0,t.installV2=!0,t.installV3=!0,t}recommendAutoTuning(e){let t={...O};return e.codeComplexity.totalFiles<20&&(t.enabled=!1),t}recommendDomains(e){return["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization"]}recommendMaxAgents(e){return e.projectType==="monorepo"?15:e.codeComplexity.totalFiles>500?12:e.codeComplexity.totalFiles>100?8:5}};function Ke(r){return new z(r)}import{existsSync as oe,readFileSync as we,writeFileSync as Ce}from"fs";function Ze(r){if(!oe(r))return null;let e=`${r}.backup`;if(oe(e))return null;try{return Ce(e,we(r,"utf-8"),"utf-8"),e}catch{return null}}var De=[/\baqe\b/i,/\bagentic-qe\b/i,/\bnpx\s+agentic-qe\b/i,/\bnpx\s+@anthropics\/agentic-qe\b/i,/aqe-hook\.cjs/i,/brain-checkpoint\.cjs/i,/statusline-v3\.cjs/i];function je(r){let e=r;return!e?.hooks||!Array.isArray(e.hooks)?!1:e.hooks.some(t=>!t.command||typeof t.command!="string"?!1:De.some(n=>n.test(t.command)))}function Xe(r,e){let t={};for(let[n,i]of Object.entries(e)){let s=r[n]||[],o=Array.isArray(s)?s.filter(a=>!je(a)):[];t[n]=[...i,...o]}for(let[n,i]of Object.entries(r))t[n]||(t[n]=i);return t}function et(r,e){return{...e,...r||{}}}function tt(r){let e=r.domains?.enabled||[];return{AQE_MEMORY_PATH:".agentic-qe/memory.db",AQE_MEMORY_ENABLED:"true",AQE_LEARNING_ENABLED:r.learning?.enabled?"true":"false",AQE_V3_MODE:"true",AQE_V3_DDD_ENABLED:"true",AQE_V3_DOMAINS:e.join(","),AQE_V3_SWARM_SIZE:String(r.agents?.maxConcurrent??15),AQE_V3_TOPOLOGY:"hierarchical",AQE_V3_SUBLINEAR_ENABLED:"true",AQE_V3_HNSW_ENABLED:r.learning?.hnswConfig?"true":"false",AQE_V3_HOOKS_ENABLED:"true",AQE_V3_AISP_ENABLED:"true",AQE_V3_REASONING_BANK:".agentic-qe/memory.db",AQE_V3_PATTERN_PROMOTION_THRESHOLD:String(r.learning?.promotionThreshold??3),AQE_V3_SUCCESS_RATE_THRESHOLD:String(r.learning?.qualityThreshold??.7)}}function Re(r){let e=r?.command;return typeof e=="string"&&/statusline-v3\.cjs|Agentic QE v3/.test(e)}function le(r,e){if(!ae(r)||!ae(e))return e;let t={...r};for(let[n,i]of Object.entries(e))t[n]=le(t[n],i);return t}function ae(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function nt(r,e){for(let[t,n]of Object.entries(e))if(t==="_aqePermissions"){let i=r.permissions||{},s=i.allow||[],o=[...new Set([...s,...n])];r.permissions={...i,allow:o}}else t==="statusLine"?(r.statusLine===void 0||Re(r.statusLine))&&(r.statusLine=n):t==="includeCoAuthoredBy"?r.includeCoAuthoredBy===void 0&&(r.includeCoAuthoredBy=n):r[t]=le(r[t],n);return r}function rt(r,e){let t=r.domains?.enabled||[];return{aqe:{version:r.version??"3.0.0",initialized:new Date().toISOString(),hooksConfigured:!0},statusLine:{type:"command",command:`sh -c 'node "\${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/statusline-v3.cjs" 2>/dev/null || echo "\u258A Agentic QE v3"'`,refreshMs:5e3,enabled:!0},_aqePermissions:["Bash(npx agentic-qe:*)","Bash(npx @anthropics/agentic-qe:*)","mcp__agentic-qe__*"],includeCoAuthoredBy:!0,v3Configuration:{domains:{total:t.length,names:t},swarm:{totalAgents:r.agents?.maxConcurrent??15,topology:"hierarchical",coordination:"queen-led"}},v3Learning:{enabled:r.learning?.enabled??!0,reasoningBank:{dbPath:".agentic-qe/memory.db",enableHNSW:!!r.learning?.hnswConfig},patternPromotion:{threshold:r.learning?.promotionThreshold??3,successRateMin:r.learning?.qualityThreshold??.7}}}}T();import{existsSync as h,mkdirSync as j,readdirSync as R,statSync as G,readFileSync as Ie,writeFileSync as qe,copyFileSync as Te,unlinkSync as Ee,rmdirSync as Pe}from"fs";import{join as m}from"path";var U=["qe-test-generation","qe-test-execution","qe-coverage-analysis","qe-quality-assessment","qe-defect-intelligence","qe-requirements-validation","qe-code-intelligence","qe-browser","pentest-validation","qe-visual-accessibility","qe-chaos-resilience","qe-learning-optimization","qe-court","qe-iterative-loop","strict-tdd","no-skip","coverage-guard","freeze-tests","security-watch","skill-stats","test-failure-investigator","coverage-drop-investigator","e2e-flow-verifier","test-metrics-dashboard"],H=["v3-core-implementation","v3-cli-modernization","v3-ddd-architecture","v3-integration-deep","v3-mcp-optimization","v3-memory-unification","v3-performance-optimization","v3-security-overhaul","v3-swarm-coordination","v3-qe-core-implementation","v3-qe-ddd-architecture","v3-qe-cli","v3-qe-memory-system","v3-qe-performance","v3-qe-security","v3-qe-mcp","v3-qe-mcp-optimization","v3-qe-memory-unification","v3-qe-integration","v3-qe-agentic-flow-integration","v3-qe-fleet-coordination","agentdb-advanced","agentdb-learning","agentdb-memory-patterns","agentdb-optimization","agentdb-vector-search","github-code-review","github-multi-repo","github-project-management","github-release-management","github-workflow-automation","flow-nexus-neural","flow-nexus-platform","flow-nexus-swarm","reasoningbank-agentdb","reasoningbank-intelligence","swarm-orchestration","swarm-advanced","sparc-methodology","hooks-automation","hive-mind-advanced","stream-chain","agentic-jujutsu","iterative-loop","performance-analysis","skill-builder","qe-agentic-flow-integration","release"],_e=["qe-contract-testing","qe-security-compliance","aqe-v2-v3-migration"],B=class{projectRoot;options;sourceSkillsDir;constructor(e){this.projectRoot=e.projectRoot,this.options={installV2Skills:!0,installV3Skills:!0,overwrite:!1,exclude:[],include:void 0,...e},this.sourceSkillsDir=this.findSourceSkillsDir()}findSourceSkillsDir(){let e=b(import.meta.url),t=[];e&&(t.push(m(e,"assets/skills")),t.push(m(e,".claude/skills"))),t.push(m(this.projectRoot,"node_modules/agentic-qe/assets/skills"));for(let n of t)if(h(n))return n;return t[0]}async install(){let e={installed:[],skipped:[],removed:[],errors:[],totalCount:0,skillsDir:m(this.projectRoot,".claude","skills"),validationInstalled:!1};if(!h(this.sourceSkillsDir))return e.errors.push(`Source skills directory not found: ${this.sourceSkillsDir}`),e;let t=m(this.projectRoot,".claude","skills");h(t)||j(t,{recursive:!0});let n=this.getAvailableSkills();e.totalCount=n.length;let i=this.filterSkills(n);for(let s of i)try{let o=await this.installSkill(s,t);o?e.installed.push(o):e.skipped.push(s)}catch(o){e.errors.push(`Failed to install ${s}: ${k(o)}`)}return this.options.overwrite&&(e.removed=this.removeDeprecatedSkills(t)),e.validationInstalled=this.installValidationInfrastructure(t),await this.createSkillsIndex(t,e.installed),e}installValidationInfrastructure(e){let t=m(this.sourceSkillsDir,".validation"),n=m(e,".validation");if(!h(t))return console.debug("[SkillsInstaller] Validation infrastructure not found in source"),!1;if(h(n)&&!this.options.overwrite)return console.debug("[SkillsInstaller] Validation infrastructure already exists, skipping"),!0;try{return h(n)||j(n,{recursive:!0}),this.copyDirectoryRecursive(t,n),console.debug("[SkillsInstaller] Validation infrastructure installed successfully"),!0}catch(i){return console.error("[SkillsInstaller] Failed to install validation infrastructure:",i instanceof Error?i.message:i),!1}}removeDeprecatedSkills(e){let t=[];for(let n of _e){let i=m(e,n);if(h(i))try{this.removeDirectoryRecursive(i),t.push(n)}catch(s){console.error(`[SkillsInstaller] Failed to remove deprecated skill ${n}:`,s instanceof Error?s.message:s)}}return t.length>0&&console.debug(`[SkillsInstaller] Removed ${t.length} deprecated skills: ${t.join(", ")}`),t}removeDirectoryRecursive(e){let t=R(e,{withFileTypes:!0});for(let n of t){let i=m(e,n.name);n.isDirectory()?this.removeDirectoryRecursive(i):Ee(i)}Pe(e)}getAvailableSkills(){try{return R(this.sourceSkillsDir).filter(t=>{let n=m(this.sourceSkillsDir,t);return G(n).isDirectory()&&!t.startsWith(".")})}catch{return[]}}filterSkills(e){let t=e;return t=t.filter(n=>!H.includes(n)),this.options.include&&this.options.include.length>0&&(t=t.filter(n=>this.options.include.includes(n))),this.options.exclude&&this.options.exclude.length>0&&(t=t.filter(n=>!this.options.exclude.some(i=>n.includes(i)||n.match(new RegExp(i))))),this.options.installV3Skills||(t=t.filter(n=>!U.includes(n))),this.options.installV2Skills||(t=t.filter(n=>U.includes(n))),t}async installSkill(e,t){let n=m(this.sourceSkillsDir,e),i=m(t,e);if(h(i)&&!this.options.overwrite)return null;h(i)||j(i,{recursive:!0}),this.copyDirectoryRecursive(n,i);let s=this.getSkillType(e),o=this.getSkillDescription(i),a=h(m(i,"resources"));return{name:e,type:s,description:o,hasResources:a}}copyDirectoryRecursive(e,t){let n=R(e);for(let i of n){let s=m(e,i),o=m(t,i);G(s).isDirectory()?(h(o)||j(o,{recursive:!0}),this.copyDirectoryRecursive(s,o)):Te(s,o)}}getSkillType(e){return U.includes(e)?"v3-domain":"v2-methodology"}getSkillDescription(e){let t=m(e,"SKILL.md");if(h(t))try{let n=Ie(t,"utf-8"),i=n.match(/description:\s*["']?([^"'\n]+)["']?/i);if(i)return i[1].trim();let s=n.split(`
7
7
  `);for(let o of s){let a=o.trim();if(a&&!a.startsWith("#")&&!a.startsWith("-")&&!a.startsWith("```"))return a.slice(0,100)+(a.length>100?"...":"")}}catch(n){console.debug("[SkillsInstaller] Failed to read skill description:",n instanceof Error?n.message:n)}}async createSkillsIndex(e,t){let n=this.scanSkillsDirectory(e),i=n.filter(c=>!H.includes(c.name)),s=i.filter(c=>c.type==="v2-methodology"),o=i.filter(c=>c.type==="v3-domain"),a=n.filter(c=>H.includes(c.name)),l=h(m(e,".validation")),u=`# AQE Skills Index
8
8
 
9
9
  This directory contains Quality Engineering skills managed by Agentic QE.
@@ -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.12.3");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};