agentic-qe 3.15.17 → 3.15.18

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 (495) hide show
  1. package/.claude/helpers/brain-checkpoint.cjs +107 -10
  2. package/.claude/skills/agentic-quality-engineering/SKILL.md +67 -44
  3. package/.claude/skills/brutal-honesty-review/SKILL.md +12 -7
  4. package/.claude/skills/brutal-honesty-review/evals/brutal-honesty-review.yaml +120 -0
  5. package/.claude/skills/brutal-honesty-review/schemas/output.json +9 -3
  6. package/.claude/skills/code-review-quality/SKILL.md +2 -2
  7. package/.claude/skills/holistic-testing-pact/SKILL.md +11 -11
  8. package/.claude/skills/sherlock-review/SKILL.md +4 -2
  9. package/.claude/skills/sherlock-review/evals/sherlock-review.yaml +124 -0
  10. package/.claude/skills/skills-manifest.json +1 -1
  11. package/.claude/skills/technical-writing/SKILL.md +12 -6
  12. package/.claude/skills/technical-writing/evals/technical-writing.yaml +96 -0
  13. package/.opencode/skills/qe-agentic-quality-engineering.yaml +2 -2
  14. package/.opencode/skills/qe-holistic-testing-pact.yaml +2 -2
  15. package/CHANGELOG.md +123 -0
  16. package/assets/skills/agentic-quality-engineering/SKILL.md +67 -44
  17. package/assets/skills/brutal-honesty-review/SKILL.md +12 -8
  18. package/assets/skills/brutal-honesty-review/evals/brutal-honesty-review.yaml +120 -0
  19. package/assets/skills/brutal-honesty-review/schemas/output.json +9 -3
  20. package/assets/skills/code-review-quality/SKILL.md +2 -2
  21. package/assets/skills/holistic-testing-pact/SKILL.md +11 -11
  22. package/assets/skills/sherlock-review/SKILL.md +4 -3
  23. package/assets/skills/sherlock-review/evals/sherlock-review.yaml +124 -0
  24. package/assets/skills/skills-manifest.json +1 -1
  25. package/assets/skills/technical-writing/SKILL.md +12 -6
  26. package/assets/skills/technical-writing/evals/technical-writing.yaml +96 -0
  27. package/dist/cli/brain-commands.d.ts +5 -0
  28. package/dist/cli/brain-commands.js +4 -0
  29. package/dist/cli/bundle.js +6 -6
  30. package/dist/cli/chunks/adapter-WRSDXLOT.js +2 -0
  31. package/dist/cli/chunks/{agent-booster-wasm-6BUOFQZA.js → agent-booster-wasm-UFNJNF3M.js} +2 -2
  32. package/dist/cli/chunks/{agent-handler-HPDK3JI3.js → agent-handler-EAYVRJXN.js} +2 -2
  33. package/dist/cli/chunks/{agent-memory-branch-5QKUTWK5.js → agent-memory-branch-M65C6WAQ.js} +2 -2
  34. package/dist/cli/chunks/aqe-learning-engine-O6NJBCCM.js +2 -0
  35. package/dist/cli/chunks/{arena-HZ35LESR.js → arena-2GDICP6R.js} +4 -4
  36. package/dist/cli/chunks/{arena-7OKPMNHD.js → arena-CG3X67OE.js} +2 -2
  37. package/dist/cli/chunks/{audit-XI575SVK.js → audit-F4FSPJPL.js} +3 -3
  38. package/dist/cli/chunks/base-J2FXOE77.js +2 -0
  39. package/dist/cli/chunks/{better-sqlite3-YO5X7ZJS.js → better-sqlite3-2MCFXW4J.js} +2 -2
  40. package/dist/cli/chunks/brain-handler-WGTJNYNB.js +95 -0
  41. package/dist/cli/chunks/{branch-enumerator-N6G44UU2.js → branch-enumerator-KL7C535H.js} +2 -2
  42. package/dist/cli/chunks/{browser-EVKPTLOI.js → browser-SJEXDVHS.js} +2 -2
  43. package/dist/cli/chunks/browser-workflow-LXGER6ZD.js +2 -0
  44. package/dist/cli/chunks/{chunk-VLTDW7XJ.js → chunk-244RKAEP.js} +2 -2
  45. package/dist/cli/chunks/{chunk-CVPXHDQU.js → chunk-27TUMXPD.js} +1 -1
  46. package/dist/cli/chunks/{chunk-FBBPRVNF.js → chunk-2MBYDPCP.js} +2 -2
  47. package/dist/cli/chunks/{chunk-P3D7SEHW.js → chunk-2Q6DTBMT.js} +1 -1
  48. package/dist/cli/chunks/{chunk-NE3LRUNC.js → chunk-355MI7RV.js} +13 -13
  49. package/dist/cli/chunks/{chunk-YCVLKU6H.js → chunk-3LX5OKBD.js} +2 -2
  50. package/dist/cli/chunks/{chunk-74MDUIAZ.js → chunk-3RPDKJGV.js} +1 -1
  51. package/dist/cli/chunks/{chunk-OWIQR6N2.js → chunk-3YMIT73A.js} +2 -2
  52. package/dist/cli/chunks/{chunk-VKREKVFI.js → chunk-43KUVBSU.js} +2 -2
  53. package/dist/cli/chunks/chunk-477FKXSS.js +2 -0
  54. package/dist/cli/chunks/{chunk-XPTCQKVE.js → chunk-4BIMTRRX.js} +1 -1
  55. package/dist/cli/chunks/{chunk-HD6W6PHV.js → chunk-4CVNVBX5.js} +2 -2
  56. package/dist/cli/chunks/{chunk-CQER6IJ5.js → chunk-4HL3SD4A.js} +1 -1
  57. package/dist/cli/chunks/{chunk-ZNXM6WVL.js → chunk-4PEG4DU2.js} +2 -2
  58. package/dist/cli/chunks/{chunk-BSIWI4ES.js → chunk-4QSQKFED.js} +2 -2
  59. package/dist/cli/chunks/chunk-53ZBETYR.js +16 -0
  60. package/dist/cli/chunks/{chunk-BHQ2DLJU.js → chunk-544KDWL4.js} +1 -1
  61. package/dist/cli/chunks/chunk-54RCGMLB.js +8 -0
  62. package/dist/cli/chunks/{chunk-TDZ6N43D.js → chunk-5AGXIZQ5.js} +2 -2
  63. package/dist/cli/chunks/{chunk-RKCN4B26.js → chunk-5M24X6W7.js} +2 -2
  64. package/dist/cli/chunks/{chunk-GG7PMTHD.js → chunk-5O5T4LEU.js} +1 -1
  65. package/dist/cli/chunks/{chunk-OWIZBZLN.js → chunk-5RFXX4IF.js} +2 -2
  66. package/dist/cli/chunks/{chunk-VQFV2IPV.js → chunk-62MLAQRJ.js} +1 -1
  67. package/dist/cli/chunks/{chunk-PCL5JRKN.js → chunk-6D6TGL2E.js} +2 -2
  68. package/dist/cli/chunks/{chunk-WBDWHHKP.js → chunk-6IHZDSDL.js} +2 -2
  69. package/dist/cli/chunks/{chunk-UOVCTK5L.js → chunk-6P3Y45QL.js} +2 -2
  70. package/dist/cli/chunks/{chunk-45223KK6.js → chunk-6TEVM3X3.js} +10 -10
  71. package/dist/cli/chunks/{chunk-K7WAI662.js → chunk-7XTUKKRA.js} +1 -1
  72. package/dist/cli/chunks/chunk-A3GDX6UF.js +2 -0
  73. package/dist/cli/chunks/{chunk-GN6OE3JT.js → chunk-A5YTKKNA.js} +1 -1
  74. package/dist/cli/chunks/{chunk-KR2TAAF6.js → chunk-ADNGZAT2.js} +1 -1
  75. package/dist/cli/chunks/{chunk-J7Q5TXFZ.js → chunk-AWQAE3SW.js} +2 -2
  76. package/dist/cli/chunks/{chunk-ZN35XSKF.js → chunk-AXDBQFR4.js} +2 -2
  77. package/dist/cli/chunks/{chunk-ND72UDVH.js → chunk-AXVD7O3F.js} +2 -2
  78. package/dist/cli/chunks/{chunk-SAEECT23.js → chunk-B52ULNYO.js} +2 -2
  79. package/dist/cli/chunks/chunk-B6S4FC7M.js +3 -0
  80. package/dist/cli/chunks/{chunk-Z7SKUC6P.js → chunk-BDVFSMOQ.js} +1 -1
  81. package/dist/cli/chunks/{chunk-CXCMATZ6.js → chunk-BGXXMX3Y.js} +2 -2
  82. package/dist/cli/chunks/{chunk-R3KBOQ3O.js → chunk-BKMQQY5T.js} +2 -2
  83. package/dist/cli/chunks/{chunk-SAZ4PJBR.js → chunk-BN2FROBQ.js} +2 -2
  84. package/dist/cli/chunks/{chunk-G2X3OLMN.js → chunk-BO6EQNOC.js} +2 -2
  85. package/dist/cli/chunks/{chunk-776K4ZLE.js → chunk-BOVAKCDC.js} +2 -2
  86. package/dist/cli/chunks/{chunk-QSQNXBD2.js → chunk-BSXKZDKO.js} +2 -2
  87. package/dist/cli/chunks/{chunk-MGZ6XZHU.js → chunk-C5QVJ5XQ.js} +1 -1
  88. package/dist/cli/chunks/{chunk-LOLSZG5J.js → chunk-CFQLLF3D.js} +2 -2
  89. package/dist/cli/chunks/{chunk-J6QRNQJF.js → chunk-DUCVLT3F.js} +7 -7
  90. package/dist/cli/chunks/{chunk-QTQDX4TZ.js → chunk-E4RMJCGA.js} +3 -3
  91. package/dist/cli/chunks/{chunk-MLMD3I75.js → chunk-EONDCWY4.js} +1 -1
  92. package/dist/cli/chunks/{chunk-7BSOO3CY.js → chunk-F4AGNKL2.js} +2 -2
  93. package/dist/cli/chunks/{chunk-IKB3M7OF.js → chunk-F6YD3BOW.js} +1 -1
  94. package/dist/cli/chunks/{chunk-LIF6UWHV.js → chunk-FQRS7WVA.js} +2 -2
  95. package/dist/cli/chunks/{chunk-QJSSUBO3.js → chunk-FT24SSDG.js} +2 -2
  96. package/dist/cli/chunks/chunk-FV4YNSAJ.js +5 -0
  97. package/dist/cli/chunks/{chunk-VITV7AEC.js → chunk-FVDM3X42.js} +2 -2
  98. package/dist/cli/chunks/{chunk-LN7NKE3N.js → chunk-FVH7TXWU.js} +2 -2
  99. package/dist/cli/chunks/{chunk-FBSBXCZS.js → chunk-FWR5QY37.js} +2 -2
  100. package/dist/cli/chunks/{chunk-X2DWHGCC.js → chunk-FYINK2B7.js} +2 -2
  101. package/dist/cli/chunks/{chunk-ECKHDHR2.js → chunk-GGISVPOZ.js} +2 -2
  102. package/dist/cli/chunks/{chunk-SRBCBVSI.js → chunk-GPIJIZJQ.js} +2 -2
  103. package/dist/cli/chunks/{chunk-YR5QBUHZ.js → chunk-GXEVOT5F.js} +2 -2
  104. package/dist/cli/chunks/{chunk-ZTP3DQ5M.js → chunk-GZ4VB5RI.js} +1 -1
  105. package/dist/cli/chunks/{chunk-HWQPMUSN.js → chunk-HBDSCYSK.js} +2 -2
  106. package/dist/cli/chunks/{chunk-XBTGEYED.js → chunk-HGG4HR7C.js} +2 -2
  107. package/dist/cli/chunks/{chunk-YD2C6EPN.js → chunk-HSCKWWO2.js} +2 -2
  108. package/dist/cli/chunks/{chunk-LOMT4UC2.js → chunk-HSQ3GUYJ.js} +2 -2
  109. package/dist/cli/chunks/{chunk-ZC3KDNJW.js → chunk-HZQBW5EM.js} +3 -3
  110. package/dist/cli/chunks/{chunk-SUAZ5Z47.js → chunk-IGIYANVT.js} +2 -2
  111. package/dist/cli/chunks/{chunk-IHQGNDMX.js → chunk-IPWMSXBF.js} +2 -2
  112. package/dist/cli/chunks/{chunk-6V6BD6PH.js → chunk-IWVNC7VY.js} +1 -1
  113. package/dist/cli/chunks/{chunk-M2YI5YUR.js → chunk-IZODXKZD.js} +2 -2
  114. package/dist/cli/chunks/{chunk-LG5PPJT7.js → chunk-J2MT2OJV.js} +1 -1
  115. package/dist/cli/chunks/{chunk-6LSZCEW2.js → chunk-JKIJVVSP.js} +1 -1
  116. package/dist/cli/chunks/{chunk-REY52O7J.js → chunk-JMRDT2XK.js} +1 -1
  117. package/dist/cli/chunks/{chunk-XEYFZLIT.js → chunk-JR2UMTKG.js} +1 -1
  118. package/dist/cli/chunks/{chunk-DJDVD6RM.js → chunk-K6CH4CFF.js} +2 -2
  119. package/dist/cli/chunks/{chunk-2PCEMDIX.js → chunk-K7KW5QB5.js} +78 -87
  120. package/dist/cli/chunks/{chunk-EPVPXHL7.js → chunk-KFCQP434.js} +2 -2
  121. package/dist/cli/chunks/{chunk-TWBZONKT.js → chunk-KH4T6STG.js} +2 -2
  122. package/dist/cli/chunks/{chunk-JI33PMPZ.js → chunk-KJBYZO57.js} +1 -1
  123. package/dist/cli/chunks/{chunk-PK34KJH7.js → chunk-KP4OKOKV.js} +2 -2
  124. package/dist/cli/chunks/chunk-L2MBKVSE.js +2 -0
  125. package/dist/cli/chunks/{chunk-JVWZAE2H.js → chunk-L3IPUIT3.js} +2 -2
  126. package/dist/cli/chunks/{chunk-KT2QCXO6.js → chunk-L7PSU2YN.js} +2 -2
  127. package/dist/cli/chunks/{chunk-HAQJFUAQ.js → chunk-LA3JPGQA.js} +2 -2
  128. package/dist/cli/chunks/{chunk-LV7UIK4Q.js → chunk-LC2QRN7V.js} +14 -13
  129. package/dist/cli/chunks/{chunk-KTORRIX3.js → chunk-LHY7TMTM.js} +2 -2
  130. package/dist/cli/chunks/{chunk-IJSROBM6.js → chunk-LLQ2UMF6.js} +3 -3
  131. package/dist/cli/chunks/{chunk-NKUHMA4T.js → chunk-LOJ7OO6W.js} +2 -2
  132. package/dist/cli/chunks/{chunk-OJIUIEI4.js → chunk-LPUSH3VF.js} +1 -1
  133. package/dist/cli/chunks/{chunk-WAOEQA3W.js → chunk-LSEC2BU7.js} +2 -2
  134. package/dist/cli/chunks/{chunk-YMUY3TES.js → chunk-LTGB7OIU.js} +2 -2
  135. package/dist/cli/chunks/{chunk-CVYPMGUM.js → chunk-LUG7YNVZ.js} +2 -2
  136. package/dist/cli/chunks/{chunk-YAJOBZE5.js → chunk-LWAFRYKE.js} +2 -2
  137. package/dist/cli/chunks/{chunk-ZP5AWQRO.js → chunk-M24ZAZ4U.js} +2 -2
  138. package/dist/cli/chunks/{chunk-HFZD5KLR.js → chunk-MKRKRXTX.js} +1 -1
  139. package/dist/cli/chunks/{chunk-4YM45Z5B.js → chunk-MNNLONAD.js} +1 -1
  140. package/dist/cli/chunks/{chunk-CMN7PU2H.js → chunk-MQM37KAR.js} +2 -2
  141. package/dist/cli/chunks/{chunk-COTQ44YO.js → chunk-MSX2OHYT.js} +2 -2
  142. package/dist/cli/chunks/{chunk-4UKTIQDT.js → chunk-MVYQRVLP.js} +2 -2
  143. package/dist/cli/chunks/{chunk-HRUHHHVR.js → chunk-MZC5WM2P.js} +2 -2
  144. package/dist/cli/chunks/{chunk-YKRLUTK7.js → chunk-MZRBNBB3.js} +2 -2
  145. package/dist/cli/chunks/{chunk-XEMCHGAJ.js → chunk-N3KQU4UC.js} +2 -2
  146. package/dist/cli/chunks/{chunk-DS5IFRY6.js → chunk-NKU3FFM4.js} +2 -2
  147. package/dist/cli/chunks/chunk-O5EWFR76.js +2 -0
  148. package/dist/cli/chunks/{chunk-J3QFJI2Y.js → chunk-O5RDHD5T.js} +2 -2
  149. package/dist/cli/chunks/chunk-O6UWIXME.js +3 -0
  150. package/dist/cli/chunks/{chunk-Q6F3DYZN.js → chunk-OA4EQDC4.js} +2 -2
  151. package/dist/cli/chunks/{chunk-NQFDJ6BT.js → chunk-OBCXCRXK.js} +1 -1
  152. package/dist/cli/chunks/{chunk-S3TBOKAZ.js → chunk-OHU5P25N.js} +4 -4
  153. package/dist/cli/chunks/{chunk-DNVRTJKB.js → chunk-OOSV2RIA.js} +2 -2
  154. package/dist/cli/chunks/{chunk-NZJVDOUN.js → chunk-OW23N2Y5.js} +2 -2
  155. package/dist/cli/chunks/{chunk-ZWUF27P4.js → chunk-OXOO3YDL.js} +2 -2
  156. package/dist/cli/chunks/{chunk-4L6WX5KC.js → chunk-OYGKSSSI.js} +1 -1
  157. package/dist/cli/chunks/{chunk-DCDSN67A.js → chunk-PGO46IIW.js} +1 -1
  158. package/dist/cli/chunks/{chunk-C7QLLMYI.js → chunk-PZOYQHWS.js} +1 -1
  159. package/dist/cli/chunks/{chunk-BKHEQIRZ.js → chunk-Q2BZSG7Z.js} +2 -2
  160. package/dist/cli/chunks/{chunk-5FSPELOG.js → chunk-Q7V722K5.js} +2 -2
  161. package/dist/cli/chunks/{chunk-2EQK7B5L.js → chunk-QZU6M5IO.js} +2 -2
  162. package/dist/cli/chunks/{chunk-HVT7RMGV.js → chunk-R55Y76SJ.js} +1 -1
  163. package/dist/cli/chunks/{chunk-POPSZDI2.js → chunk-RMEQYJPU.js} +4 -4
  164. package/dist/cli/chunks/{chunk-H2LHWZRE.js → chunk-RTYXFXTI.js} +2 -2
  165. package/dist/cli/chunks/{chunk-QN7HP2UW.js → chunk-SJF3O4FX.js} +236 -236
  166. package/dist/cli/chunks/{chunk-2YWYW7NU.js → chunk-SOUS7Z2H.js} +2 -2
  167. package/dist/cli/chunks/{chunk-U5SMBJ6F.js → chunk-SRVNR3R3.js} +2 -2
  168. package/dist/cli/chunks/{chunk-ZAQMRFBB.js → chunk-SU3SXMVG.js} +2 -2
  169. package/dist/cli/chunks/chunk-SWGPLXWW.js +32 -0
  170. package/dist/cli/chunks/{chunk-S3DT5TPR.js → chunk-TRB3EVH3.js} +2 -2
  171. package/dist/cli/chunks/{chunk-IJZFJPHS.js → chunk-TVBDUMKT.js} +2 -2
  172. package/dist/cli/chunks/{chunk-7SNSI4VY.js → chunk-TWTXPSFU.js} +1 -1
  173. package/dist/cli/chunks/{chunk-ORQ2YBRR.js → chunk-ULYUVUL2.js} +2 -2
  174. package/dist/cli/chunks/{chunk-MVVVGQJ6.js → chunk-UNTBVJ5X.js} +2 -2
  175. package/dist/cli/chunks/{chunk-5WATBVU6.js → chunk-UQAA4PHU.js} +2 -2
  176. package/dist/cli/chunks/{chunk-5WYZVSL2.js → chunk-UWSJVKTE.js} +1 -1
  177. package/dist/cli/chunks/{chunk-JHKKIJT2.js → chunk-V2LJ54KP.js} +2 -2
  178. package/dist/cli/chunks/{chunk-2UUZCQSD.js → chunk-VCCTTKP3.js} +2 -2
  179. package/dist/cli/chunks/{chunk-P4OB6WDJ.js → chunk-VEGUYUVS.js} +1 -1
  180. package/dist/cli/chunks/{chunk-WX4PO65Q.js → chunk-VUQPVWNK.js} +2 -2
  181. package/dist/cli/chunks/{chunk-IQL6XRF5.js → chunk-VVGUE2T2.js} +2 -2
  182. package/dist/cli/chunks/{chunk-HZ5O7G2P.js → chunk-W5ASDHJQ.js} +1 -1
  183. package/dist/cli/chunks/{chunk-U4S74IIZ.js → chunk-WGXT5NWQ.js} +1 -1
  184. package/dist/cli/chunks/chunk-WJN3V7QB.js +7 -0
  185. package/dist/cli/chunks/chunk-WPCRQIIF.js +29 -0
  186. package/dist/cli/chunks/{chunk-AGCS5GSO.js → chunk-WQNLXUWA.js} +6 -6
  187. package/dist/cli/chunks/{chunk-LRY6UIRI.js → chunk-WZVRMKG2.js} +2 -2
  188. package/dist/cli/chunks/{chunk-KPIPVSIP.js → chunk-X27IUWTD.js} +2 -2
  189. package/dist/cli/chunks/{chunk-VDEKVIP5.js → chunk-X4B345B6.js} +2 -2
  190. package/dist/cli/chunks/{chunk-ERYADKMZ.js → chunk-X5I2Y4VO.js} +2 -2
  191. package/dist/cli/chunks/{chunk-EUWG2JG4.js → chunk-X7IQIFTS.js} +2 -2
  192. package/dist/cli/chunks/chunk-XJN3RKUD.js +3 -0
  193. package/dist/cli/chunks/{chunk-JRIJM4LE.js → chunk-XQMGXTHJ.js} +3 -3
  194. package/dist/cli/chunks/{chunk-VYPVU3JF.js → chunk-XTSAMB2Q.js} +2 -2
  195. package/dist/cli/chunks/{chunk-4NKZU2JZ.js → chunk-XZLIF4O2.js} +2 -2
  196. package/dist/cli/chunks/{chunk-XFTX3KLE.js → chunk-Y4LSEOZ3.js} +1 -1
  197. package/dist/cli/chunks/{chunk-ZVMSSCTH.js → chunk-Y4YN2RXR.js} +2 -2
  198. package/dist/cli/chunks/{chunk-X5QD76IU.js → chunk-YDI56L35.js} +2 -2
  199. package/dist/cli/chunks/{chunk-LRKLATSH.js → chunk-YFILS5D5.js} +2 -2
  200. package/dist/cli/chunks/{chunk-AVHYJ3XP.js → chunk-YISDX6WB.js} +2 -2
  201. package/dist/cli/chunks/{chunk-GPPTRKEM.js → chunk-YP2GHQSV.js} +2 -2
  202. package/dist/cli/chunks/{chunk-OO2M2QUV.js → chunk-YSX756AM.js} +4 -4
  203. package/dist/cli/chunks/{chunk-E7XIMOKW.js → chunk-YWANOASW.js} +2 -2
  204. package/dist/cli/chunks/{chunk-UHJVZEQA.js → chunk-YYIJLG7S.js} +2 -2
  205. package/dist/cli/chunks/{chunk-LCWEQRZI.js → chunk-Z7SD7LXM.js} +2 -2
  206. package/dist/cli/chunks/{chunk-TM75GAXG.js → chunk-ZDWD73UF.js} +2 -2
  207. package/dist/cli/chunks/{chunk-IRHXGCQR.js → chunk-ZFT3RLA4.js} +2 -2
  208. package/dist/cli/chunks/{chunk-ZGV7L4MW.js → chunk-ZNTHX5G3.js} +1 -1
  209. package/dist/cli/chunks/{chunk-D75GLKEL.js → chunk-ZS27R7VL.js} +2 -2
  210. package/dist/cli/chunks/{chunk-INI3Q4CN.js → chunk-ZXHHHR7K.js} +1 -1
  211. package/dist/cli/chunks/{ci-3RTTTS2D.js → ci-N5MOMNXH.js} +2 -2
  212. package/dist/cli/chunks/{ci-config-XRUR3I4K.js → ci-config-6L2ROQCW.js} +2 -2
  213. package/dist/cli/chunks/{ci-output-E5IAMU2U.js → ci-output-DSRBYEIK.js} +2 -2
  214. package/dist/cli/chunks/{circuit-breaker-SHR2P44P.js → circuit-breaker-VRPTNBL7.js} +2 -2
  215. package/dist/cli/chunks/{claude-flow-setup-ZDDILFMF.js → claude-flow-setup-4YFG3FU5.js} +2 -2
  216. package/dist/cli/chunks/client-I3L6BKRQ.js +2 -0
  217. package/dist/cli/chunks/{cline-installer-BGYVUM6G.js → cline-installer-7RGYJWGN.js} +2 -2
  218. package/dist/cli/chunks/{code-PJ4MC3MC.js → code-ISC6NW2K.js} +3 -3
  219. package/dist/cli/chunks/{code-index-extractor-IW2P22YG.js → code-index-extractor-2FID75YV.js} +2 -2
  220. package/dist/cli/chunks/{codex-installer-A7WZ6OGL.js → codex-installer-DZ7OG6KM.js} +2 -2
  221. package/dist/cli/chunks/{completions-KS23WD5J.js → completions-SM3LICWK.js} +2 -2
  222. package/dist/cli/chunks/{complexity-analyzer-Q7GLSR2E.js → complexity-analyzer-ZWD2CTAD.js} +2 -2
  223. package/dist/cli/chunks/{continuedev-installer-SK55BFW2.js → continuedev-installer-AGASOA26.js} +2 -2
  224. package/dist/cli/chunks/{copilot-installer-3N5J3WTM.js → copilot-installer-CLPZYTQC.js} +2 -2
  225. package/dist/cli/chunks/core-handlers-5EFOJ37H.js +2 -0
  226. package/dist/cli/chunks/{cost-tracker-NENVSO4A.js → cost-tracker-7PIGQYDV.js} +2 -2
  227. package/dist/cli/chunks/{coverage-5L7UQWDH.js → coverage-T2GEBTYS.js} +9 -9
  228. package/dist/cli/chunks/cross-domain-router-65WJAKVD.js +2 -0
  229. package/dist/cli/chunks/{cursor-installer-XXBO2ZE6.js → cursor-installer-KXBID4MB.js} +2 -2
  230. package/dist/cli/chunks/daemon-43MXIVH3.js +18 -0
  231. package/dist/cli/chunks/{daemon-CDCQU3LR.js → daemon-VAMJLQJ5.js} +3 -3
  232. package/dist/cli/chunks/{dag-attention-scheduler-HOMMF7FA.js → dag-attention-scheduler-UBP4VHTA.js} +2 -2
  233. package/dist/cli/chunks/{detect-FXCOUG6X.js → detect-QWFIQRKI.js} +2 -2
  234. package/dist/cli/chunks/{dist-node-GXQ7FMTY.js → dist-node-I2GICS3W.js} +2 -2
  235. package/dist/cli/chunks/{domain-handler-TI3JBAPC.js → domain-handler-Z66ISB2A.js} +2 -2
  236. package/dist/cli/chunks/{domain-plugins-R7LTUM32.js → domain-plugins-KHMD3FKT.js} +2 -2
  237. package/dist/cli/chunks/{domain-transfer-LBIAFHIQ.js → domain-transfer-JWGNNA6K.js} +2 -2
  238. package/dist/cli/chunks/dream-VQ2PZCVR.js +2 -0
  239. package/dist/cli/chunks/embed-and-insert-pattern-F5P5B6JX.js +3 -0
  240. package/dist/cli/chunks/{embedding-space-HHLWTBF5.js → embedding-space-KHG6TITM.js} +2 -2
  241. package/dist/cli/chunks/{eval-KDOZMAXJ.js → eval-43OHU7EI.js} +2 -2
  242. package/dist/cli/chunks/{experience-capture-middleware-X45PECQN.js → experience-capture-middleware-KXD47H6P.js} +3 -3
  243. package/dist/cli/chunks/{fast-paths-462V6UUB.js → fast-paths-6D75D5KD.js} +2 -2
  244. package/dist/cli/chunks/{feature-flags-NIRQ4YDM.js → feature-flags-IE35Y55N.js} +2 -2
  245. package/dist/cli/chunks/{feature-flags-G66OT3AS.js → feature-flags-OYYHY7LS.js} +2 -2
  246. package/dist/cli/chunks/file-discovery-LGBTY3ID.js +2 -0
  247. package/dist/cli/chunks/{fleet-PXWGB7CU.js → fleet-AGVJMFGD.js} +16 -16
  248. package/dist/cli/chunks/{gnn-wrapper-7MUW3M5M.js → gnn-wrapper-5L66A7LW.js} +2 -2
  249. package/dist/cli/chunks/{heartbeat-handler-5237PB35.js → heartbeat-handler-2BY6YYOT.js} +5 -5
  250. package/dist/cli/chunks/heartbeat-scheduler-3DU3M5AT.js +2 -0
  251. package/dist/cli/chunks/hnsw-adapter-N2IMSRPV.js +2 -0
  252. package/dist/cli/chunks/hnsw-index-DVU7TTJE.js +2 -0
  253. package/dist/cli/chunks/{hnsw-legacy-bridge-OSQPW7JP.js → hnsw-legacy-bridge-RYMWFNAH.js} +2 -2
  254. package/dist/cli/chunks/{hnswlib-node-GX6WG2GB.js → hnswlib-node-GG47HP2P.js} +2 -2
  255. package/dist/cli/chunks/{hooks-GUWHL7VC.js → hooks-FQNACS24.js} +10 -10
  256. package/dist/cli/chunks/hybrid-backend-AS2PNHOD.js +2 -0
  257. package/dist/cli/chunks/{hypergraph-engine-SRWLLCU3.js → hypergraph-engine-6BYNJQEP.js} +2 -2
  258. package/dist/cli/chunks/{hypergraph-handler-AVOPRHHO.js → hypergraph-handler-CYTAXZKJ.js} +3 -3
  259. package/dist/cli/chunks/impact-analyzer-Y4OONLFP.js +2 -0
  260. package/dist/cli/chunks/{init-guard-P4N6EVZS.js → init-guard-METTAV5O.js} +2 -2
  261. package/dist/cli/chunks/{init-handler-LRGWOJMD.js → init-handler-GFT74U5Y.js} +6 -6
  262. package/dist/cli/chunks/init-wizard-HLNUBJQN.js +2 -0
  263. package/dist/cli/chunks/kernel-XKFWCL7Y.js +2 -0
  264. package/dist/cli/chunks/{kilocode-installer-7R2EPOQ6.js → kilocode-installer-GZV2D3FF.js} +2 -2
  265. package/dist/cli/chunks/{kiro-installer-QNM7DPOB.js → kiro-installer-Q4ZXUFC7.js} +2 -2
  266. package/dist/cli/chunks/knowledge-graph-CNL77CSZ.js +2 -0
  267. package/dist/cli/chunks/{learning-7OIZBPXZ.js → learning-WA2QEYL7.js} +35 -34
  268. package/dist/cli/chunks/{llm-router-SIDXES23.js → llm-router-GRTCHWH7.js} +4 -4
  269. package/dist/cli/chunks/llm-router-service-UIYTYKP6.js +2 -0
  270. package/dist/cli/chunks/{load-EI2E2C3S.js → load-WXN3Q7Y5.js} +2 -2
  271. package/dist/cli/chunks/load-test-PXLW4A5B.js +2 -0
  272. package/dist/cli/chunks/{mcp-IOE5WOCS.js → mcp-LIQCPSJN.js} +2 -2
  273. package/dist/cli/chunks/{memory-DLYGJAP7.js → memory-OP6CHRFH.js} +5 -5
  274. package/dist/cli/chunks/memory-backend-XYOSO73Q.js +2 -0
  275. package/dist/cli/chunks/memory-handlers-PQFYVNVG.js +2 -0
  276. package/dist/cli/chunks/{multi-model-executor-WHH4YCHM.js → multi-model-executor-H54DEVRZ.js} +2 -2
  277. package/dist/cli/chunks/{opencode-installer-63FDZAMS.js → opencode-installer-BSQV6UAT.js} +2 -2
  278. package/dist/cli/chunks/{orchestrator-3LA776KK.js → orchestrator-TJDPQ4VL.js} +122 -35
  279. package/dist/cli/chunks/pattern-null-store-BKGTQFNF.js +2 -0
  280. package/dist/cli/chunks/{pattern-usage-recorder-NW54QUGI.js → pattern-usage-recorder-FOVS4M5L.js} +2 -2
  281. package/dist/cli/chunks/{pipeline-P3TYX6J6.js → pipeline-4AY2ZIC6.js} +2 -2
  282. package/dist/cli/chunks/{platform-FNA2WLI6.js → platform-FCSITYMR.js} +2 -2
  283. package/dist/cli/chunks/{plugin-NJS7BC2S.js → plugin-E56TV5S2.js} +2 -2
  284. package/dist/cli/chunks/{prime-radiant-advanced-wasm-NIAVL2OT.js → prime-radiant-advanced-wasm-ACOPC533.js} +2 -2
  285. package/dist/cli/chunks/project-root-MPX7CN2C.js +2 -0
  286. package/dist/cli/chunks/protocol-executor-CRQOCC4A.js +2 -0
  287. package/dist/cli/chunks/{protocol-handler-JU5C4JHY.js → protocol-handler-KRVXF4LS.js} +2 -2
  288. package/dist/cli/chunks/{prove-35VOSLYP.js → prove-KMFPSKGD.js} +2 -2
  289. package/dist/cli/chunks/qe-reasoning-bank-UEGQ3O7F.js +2 -0
  290. package/dist/cli/chunks/{quality-ET74X7HN.js → quality-6DBI3HLB.js} +2 -2
  291. package/dist/cli/chunks/{quality-gate-FEDQISNB.js → quality-gate-3ROZMEIL.js} +3 -3
  292. package/dist/cli/chunks/queen-coordinator-32574XSG.js +2 -0
  293. package/dist/cli/chunks/real-embeddings-MIGZNKK3.js +2 -0
  294. package/dist/cli/chunks/{ref-validation-DTBPYCEB.js → ref-validation-EYIP7DHW.js} +2 -2
  295. package/dist/cli/chunks/{roocode-installer-LYQEMR4J.js → roocode-installer-IGGZHR2Y.js} +2 -2
  296. package/dist/cli/chunks/router-CZJY5WX6.js +2 -0
  297. package/dist/cli/chunks/routing-feedback-RC3UBNFX.js +2 -0
  298. package/dist/cli/chunks/{routing-handler-DJOJFPII.js → routing-handler-BWNHBYDC.js} +2 -2
  299. package/dist/cli/chunks/{ruvector-commands-VXYGJDPW.js → ruvector-commands-PXIHF432.js} +2 -2
  300. package/dist/cli/chunks/rvf-dual-writer-OG7OV2AK.js +2 -0
  301. package/dist/cli/chunks/rvf-migration-adapter-THYMW7ZO.js +2 -0
  302. package/dist/cli/chunks/rvf-migration-coordinator-3H6CLFU7.js +2 -0
  303. package/dist/cli/chunks/rvf-native-adapter-6JQJIKKW.js +2 -0
  304. package/dist/cli/chunks/{rvf-store-integrity-GA2ZYOEG.js → rvf-store-integrity-CVB3NMSL.js} +2 -2
  305. package/dist/cli/chunks/safe-db-QFKCVTIJ.js +2 -0
  306. package/dist/cli/chunks/schedule-6JLVMMYB.js +2 -0
  307. package/dist/cli/chunks/scheduler-3MPZRMJD.js +2 -0
  308. package/dist/cli/chunks/{security-MM6YOECX.js → security-DCRGOTWU.js} +3 -3
  309. package/dist/cli/chunks/{shared-rvf-adapter-6AHPA3V5.js → shared-rvf-adapter-GKD74QUB.js} +2 -2
  310. package/dist/cli/chunks/{shared-rvf-dual-writer-EYAVY2GZ.js → shared-rvf-dual-writer-HVAAVEOH.js} +2 -2
  311. package/dist/cli/chunks/sqlite-persistence-LGTIKAEX.js +2 -0
  312. package/dist/cli/chunks/{standalone-memory-A3PLB4CZ.js → standalone-memory-O7O2U5N4.js} +2 -2
  313. package/dist/cli/chunks/{status-handler-OSSFAP4Z.js → status-handler-BQTPJJTL.js} +2 -2
  314. package/dist/cli/chunks/{structural-health-PGY5XUNO.js → structural-health-4H6J4OHK.js} +2 -2
  315. package/dist/cli/chunks/sync-DJ4TF6QX.js +2 -0
  316. package/dist/cli/chunks/{sync-CWEHYGNN.js → sync-WW5TAVYW.js} +2 -2
  317. package/dist/cli/chunks/{task-handler-LHMQ75W4.js → task-handler-HEM4IEOW.js} +2 -2
  318. package/dist/cli/chunks/{task-handlers-S2TX5FTR.js → task-handlers-JRA3NXIR.js} +3 -3
  319. package/dist/cli/chunks/{test-4EGZZ6NJ.js → test-772ZXVG2.js} +4 -4
  320. package/dist/cli/chunks/test-runner-process-XGF2U3NG.js +2 -0
  321. package/dist/cli/chunks/{test-scheduling-YJQHH3XE.js → test-scheduling-4TRB7LZ7.js} +3 -3
  322. package/dist/cli/chunks/token-bootstrap-CICBIJ7T.js +2 -0
  323. package/dist/cli/chunks/{token-usage-WPNOJR6H.js → token-usage-B7PEKE2G.js} +2 -2
  324. package/dist/cli/chunks/{transformers-4MRPXCPU.js → transformers-V7X7BDZX.js} +2 -2
  325. package/dist/cli/chunks/tree-sitter-wasm-parser-OXPFKFZS.js +2 -0
  326. package/dist/cli/chunks/{types-6P5FB4EB.js → types-AHHTUY3I.js} +2 -2
  327. package/dist/cli/chunks/unified-memory-GUR3IUI6.js +2 -0
  328. package/dist/cli/chunks/unified-memory-hnsw-NJP2F2RY.js +2 -0
  329. package/dist/cli/chunks/unified-persistence-NILBWXDP.js +2 -0
  330. package/dist/cli/chunks/{upgrade-4ICTN63Y.js → upgrade-DZ4DLUQ5.js} +2 -2
  331. package/dist/cli/chunks/{validate-HQF5GZ7L.js → validate-4DTLIDJE.js} +2 -2
  332. package/dist/cli/chunks/{validate-swarm-45JYG7VW.js → validate-swarm-A26UFVIS.js} +2 -2
  333. package/dist/cli/chunks/visual-security-YECYZ27X.js +2 -0
  334. package/dist/cli/chunks/{web-tree-sitter-UOTWZLNH.js → web-tree-sitter-F2C7QRYT.js} +2 -2
  335. package/dist/cli/chunks/{windsurf-installer-WDWSBXGN.js → windsurf-installer-OOBTDA6W.js} +2 -2
  336. package/dist/cli/chunks/{witness-chain-DOYMNPC7.js → witness-chain-KGFZJP32.js} +2 -2
  337. package/dist/cli/chunks/witness-chain-LYBXFLJB.js +2 -0
  338. package/dist/cli/chunks/witness-chain-repair-CNTXOGPN.js +2 -0
  339. package/dist/cli/chunks/{witness-chain-verifier-JB42X62J.js → witness-chain-verifier-OB7ZZOI3.js} +2 -2
  340. package/dist/cli/chunks/{witness-key-manager-LXXO6L2G.js → witness-key-manager-YCKGKGQI.js} +2 -2
  341. package/dist/cli/chunks/{workflow-6ARK47NF.js → workflow-PRERHWKY.js} +4 -4
  342. package/dist/cli/chunks/workflow-orchestrator-UIBGWCU3.js +2 -0
  343. package/dist/cli/chunks/wrappers-L4UY4V63.js +2 -0
  344. package/dist/cli/commands/coverage.js +4 -1
  345. package/dist/cli/commands/learning-prune.js +9 -1
  346. package/dist/cli/handlers/brain-handler.js +32 -2
  347. package/dist/cli/handlers/heartbeat-handler.js +3 -1
  348. package/dist/cli/utils/coverage-data.js +5 -1
  349. package/dist/cli/utils/coverage-verdict.d.ts +10 -2
  350. package/dist/cli/utils/coverage-verdict.js +23 -8
  351. package/dist/cli/utils/fleet-operation.js +9 -3
  352. package/dist/coordination/handlers/code-intelligence-handlers.js +17 -3
  353. package/dist/coordination/handlers/coverage-handlers.js +22 -9
  354. package/dist/coordination/handlers/coverage-target.d.ts +22 -2
  355. package/dist/coordination/handlers/coverage-target.js +45 -9
  356. package/dist/coordination/handlers/handler-utils.d.ts +19 -0
  357. package/dist/coordination/handlers/handler-utils.js +22 -8
  358. package/dist/coordination/protocols/code-intelligence-index.js +6 -3
  359. package/dist/coordination/protocols/learning-consolidation-archive.d.ts +6 -3
  360. package/dist/coordination/protocols/learning-consolidation-archive.js +4 -3
  361. package/dist/coordination/workflow-builtin.js +1 -0
  362. package/dist/domains/defect-intelligence/interfaces.d.ts +2 -0
  363. package/dist/domains/defect-intelligence/prediction-history.d.ts +15 -1
  364. package/dist/domains/defect-intelligence/prediction-history.js +63 -7
  365. package/dist/domains/defect-intelligence/services/defect-predictor.d.ts +1 -0
  366. package/dist/domains/defect-intelligence/services/defect-predictor.js +33 -13
  367. package/dist/domains/learning-optimization/coordinator.js +17 -10
  368. package/dist/domains/learning-optimization/domain-ranking.d.ts +26 -0
  369. package/dist/domains/learning-optimization/domain-ranking.js +28 -0
  370. package/dist/domains/learning-optimization/interfaces.d.ts +5 -0
  371. package/dist/domains/learning-optimization/pattern-archive.d.ts +55 -8
  372. package/dist/domains/learning-optimization/pattern-archive.js +90 -17
  373. package/dist/domains/learning-optimization/pattern-consolidation.js +18 -2
  374. package/dist/domains/learning-optimization/pattern-merge.d.ts +26 -0
  375. package/dist/domains/learning-optimization/pattern-merge.js +127 -0
  376. package/dist/domains/learning-optimization/services/learning-coordinator.js +21 -35
  377. package/dist/domains/test-execution/services/test-executor.js +6 -2
  378. package/dist/init/init-wizard-steps.js +3 -1
  379. package/dist/init/phases/07-hooks.js +97 -10
  380. package/dist/integrations/embeddings/cache/EmbeddingCache.js +1 -1
  381. package/dist/integrations/ruvector/brain-rvf-exporter.d.ts +16 -1
  382. package/dist/integrations/ruvector/brain-rvf-exporter.js +18 -32
  383. package/dist/integrations/ruvector/brain-rvf-richness.d.ts +75 -0
  384. package/dist/integrations/ruvector/brain-rvf-richness.js +127 -0
  385. package/dist/kernel/unified-memory-migration.js +1 -1
  386. package/dist/learning/checkpoint-shrink-ack.d.ts +25 -0
  387. package/dist/learning/checkpoint-shrink-ack.js +57 -0
  388. package/dist/learning/dream/dream-engine.d.ts +44 -3
  389. package/dist/learning/dream/dream-engine.js +6 -2
  390. package/dist/learning/embedder-identity-store.js +3 -1
  391. package/dist/learning/embedding-space-legacy-adoption.d.ts +53 -0
  392. package/dist/learning/embedding-space-legacy-adoption.js +115 -0
  393. package/dist/learning/embedding-space-registry.d.ts +15 -0
  394. package/dist/learning/embedding-space-registry.js +50 -11
  395. package/dist/learning/experience-capture.d.ts +3 -1
  396. package/dist/learning/experience-capture.js +15 -5
  397. package/dist/learning/experience-space-verification.d.ts +2 -0
  398. package/dist/learning/experience-space-verification.js +3 -2
  399. package/dist/learning/learning-retention.js +4 -0
  400. package/dist/learning/pattern-promotion.d.ts +7 -0
  401. package/dist/learning/pattern-promotion.js +64 -12
  402. package/dist/learning/real-embeddings.js +31 -7
  403. package/dist/learning/rvf-pattern-store.js +6 -1
  404. package/dist/mcp/bundle.js +570 -558
  405. package/dist/mcp/handlers/domain-handler-configs.d.ts +3 -0
  406. package/dist/mcp/handlers/domain-handler-configs.js +1 -0
  407. package/dist/mcp/handlers/heartbeat-handlers.d.ts +4 -2
  408. package/dist/mcp/tools/learning-optimization/optimize.d.ts +6 -1
  409. package/dist/mcp/tools/learning-optimization/optimize.js +20 -11
  410. package/dist/planning/goap-planner.js +4 -0
  411. package/dist/planning/plan-executor.js +6 -2
  412. package/dist/shared/git/git-analyzer.d.ts +30 -11
  413. package/dist/shared/git/git-analyzer.js +95 -48
  414. package/dist/shared/io/confined-read.d.ts +32 -7
  415. package/dist/shared/io/confined-read.js +58 -25
  416. package/dist/shared/io/file-reader.js +4 -1
  417. package/dist/shared/safe-db.d.ts +1 -1
  418. package/dist/shared/safe-db.js +20 -5
  419. package/dist/shared/sqlite-journal-mode.d.ts +39 -0
  420. package/dist/shared/sqlite-journal-mode.js +53 -0
  421. package/dist/sync/claude-flow-bridge.js +1 -1
  422. package/dist/sync/readers/sqlite-reader.js +3 -4
  423. package/dist/sync/writers/sqlite-writer.js +1 -1
  424. package/dist/workers/interfaces.d.ts +2 -2
  425. package/dist/workers/quality-daemon/git-watcher.d.ts +8 -0
  426. package/dist/workers/quality-daemon/git-watcher.js +54 -12
  427. package/dist/workers/quality-daemon/index.js +1 -1
  428. package/dist/workers/quality-daemon/priority-queue.d.ts +2 -1
  429. package/dist/workers/workers/defect-predictor.d.ts +9 -4
  430. package/dist/workers/workers/defect-predictor.js +98 -37
  431. package/package.json +1 -1
  432. package/dist/cli/chunks/adapter-OMILP6KH.js +0 -2
  433. package/dist/cli/chunks/aqe-learning-engine-OXH5CCOS.js +0 -2
  434. package/dist/cli/chunks/base-MAK2BLTG.js +0 -2
  435. package/dist/cli/chunks/brain-handler-GCQZFZGQ.js +0 -95
  436. package/dist/cli/chunks/browser-workflow-IR3VF2TL.js +0 -2
  437. package/dist/cli/chunks/chunk-4EJLHNER.js +0 -12
  438. package/dist/cli/chunks/chunk-A4BVDYIL.js +0 -2
  439. package/dist/cli/chunks/chunk-BE7ZHM34.js +0 -3
  440. package/dist/cli/chunks/chunk-DHKSPOUQ.js +0 -16
  441. package/dist/cli/chunks/chunk-FAQ24UHB.js +0 -29
  442. package/dist/cli/chunks/chunk-IOWEBPXJ.js +0 -5
  443. package/dist/cli/chunks/chunk-KB34MTFZ.js +0 -3
  444. package/dist/cli/chunks/chunk-MCXW3DKE.js +0 -8
  445. package/dist/cli/chunks/chunk-O7VJ3VKD.js +0 -2
  446. package/dist/cli/chunks/chunk-PIWGKGWP.js +0 -3
  447. package/dist/cli/chunks/chunk-SFITYZLV.js +0 -7
  448. package/dist/cli/chunks/chunk-TIVKDIF7.js +0 -2
  449. package/dist/cli/chunks/client-NO5FOWT4.js +0 -2
  450. package/dist/cli/chunks/core-handlers-JNAZPXE2.js +0 -2
  451. package/dist/cli/chunks/cross-domain-router-HEBM767Z.js +0 -2
  452. package/dist/cli/chunks/daemon-JEBJGEUK.js +0 -18
  453. package/dist/cli/chunks/dream-GQDCEJMS.js +0 -2
  454. package/dist/cli/chunks/embed-and-insert-pattern-33KLHDD5.js +0 -3
  455. package/dist/cli/chunks/file-discovery-33USPLB5.js +0 -2
  456. package/dist/cli/chunks/heartbeat-scheduler-LIXLC5IH.js +0 -2
  457. package/dist/cli/chunks/hnsw-adapter-62D5UH27.js +0 -2
  458. package/dist/cli/chunks/hnsw-index-GSGUMQQC.js +0 -2
  459. package/dist/cli/chunks/hybrid-backend-FRWP4BOY.js +0 -2
  460. package/dist/cli/chunks/impact-analyzer-7KF3AQXV.js +0 -2
  461. package/dist/cli/chunks/init-wizard-XWWAXY25.js +0 -2
  462. package/dist/cli/chunks/kernel-ZEJPNDBW.js +0 -2
  463. package/dist/cli/chunks/knowledge-graph-RRZQS7KY.js +0 -2
  464. package/dist/cli/chunks/llm-router-service-3OSW67LC.js +0 -2
  465. package/dist/cli/chunks/load-test-7TRIH2WJ.js +0 -2
  466. package/dist/cli/chunks/memory-backend-G7ZW6Q2B.js +0 -2
  467. package/dist/cli/chunks/memory-handlers-TPF3KCO5.js +0 -2
  468. package/dist/cli/chunks/pattern-null-store-OU3ZC3NR.js +0 -2
  469. package/dist/cli/chunks/project-root-GMOFJEKD.js +0 -2
  470. package/dist/cli/chunks/protocol-executor-AD345XRO.js +0 -2
  471. package/dist/cli/chunks/qe-reasoning-bank-NLTP26RC.js +0 -2
  472. package/dist/cli/chunks/queen-coordinator-2TB4FWS6.js +0 -2
  473. package/dist/cli/chunks/real-embeddings-II6CXTCI.js +0 -2
  474. package/dist/cli/chunks/router-PLM3MWME.js +0 -2
  475. package/dist/cli/chunks/routing-feedback-I7VOX2HU.js +0 -2
  476. package/dist/cli/chunks/rvf-dual-writer-GQZHFWO2.js +0 -2
  477. package/dist/cli/chunks/rvf-migration-adapter-3TVKBCAM.js +0 -2
  478. package/dist/cli/chunks/rvf-migration-coordinator-XUHKLMT6.js +0 -2
  479. package/dist/cli/chunks/rvf-native-adapter-5GUTYOWS.js +0 -2
  480. package/dist/cli/chunks/safe-db-RZPQGLGQ.js +0 -2
  481. package/dist/cli/chunks/schedule-G7JMQDUX.js +0 -2
  482. package/dist/cli/chunks/scheduler-4SEGPCKD.js +0 -2
  483. package/dist/cli/chunks/sqlite-persistence-IVE4SQXR.js +0 -2
  484. package/dist/cli/chunks/sync-PM6D7EQF.js +0 -2
  485. package/dist/cli/chunks/test-runner-process-72YACW6M.js +0 -2
  486. package/dist/cli/chunks/token-bootstrap-DJNETMVW.js +0 -2
  487. package/dist/cli/chunks/tree-sitter-wasm-parser-UVWSDXFR.js +0 -2
  488. package/dist/cli/chunks/unified-memory-2VMGSGQL.js +0 -2
  489. package/dist/cli/chunks/unified-memory-hnsw-3KULVD3N.js +0 -2
  490. package/dist/cli/chunks/unified-persistence-QCSLU2SV.js +0 -2
  491. package/dist/cli/chunks/visual-security-ZYP2KPH7.js +0 -2
  492. package/dist/cli/chunks/witness-chain-5QRT7EMX.js +0 -2
  493. package/dist/cli/chunks/witness-chain-repair-CUF2AFQB.js +0 -2
  494. package/dist/cli/chunks/workflow-orchestrator-RYDDWIXN.js +0 -2
  495. package/dist/cli/chunks/wrappers-CYQBOMPL.js +0 -2
@@ -1,11 +1,11 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
- import{a as We}from"./chunk-INI3Q4CN.js";import{a as Lr}from"./chunk-2YWYW7NU.js";import{b as jr}from"./chunk-YR5QBUHZ.js";import{a as qr,b as Ga,c as $r,d as ja,e as fn,f as za,g as Ua,h as Ba,i as Ha,j as Va,k as Qa,l as Wa,m as Ka,n as Xa,o as Ya,p as Gr}from"./chunk-MCXW3DKE.js";import{a as no,c as ro,d as io}from"./chunk-PK34KJH7.js";import{a as Ja,b as Za,c as eo}from"./chunk-OJIUIEI4.js";import{a as La,b as qa}from"./chunk-SUAZ5Z47.js";import{b as to}from"./chunk-HFZD5KLR.js";import{a as $a}from"./chunk-ECKHDHR2.js";import{a as so}from"./chunk-YCVLKU6H.js";import{a as ao}from"./chunk-ZVMSSCTH.js";import{a as oo}from"./chunk-VDEKVIP5.js";import{a as co}from"./chunk-ZAQMRFBB.js";import{c as q,e as hn,i as V,j as yn,l as A}from"./chunk-AVHYJ3XP.js";import{a as lo}from"./chunk-ORQ2YBRR.js";import{b as mn}from"./chunk-JRIJM4LE.js";import{b as pn,c as gn}from"./chunk-VKREKVFI.js";import{a as Ke}from"./chunk-IJZFJPHS.js";import{A as Ra,B as Pa,C as xa,D as Aa,E as Fr,F as ka,G as Ma,H as Ia,I as Ve,J as Qe,K as Oa,a as ws,b as rn,c as Dr,d as Rl,e as Ls,f as Zs,g as ea,h as na,i as ra,j as ia,k as sa,l as un,m as aa,n as oa,o as ca,p as da,q as ma,r as ga,s as fa,t as ha,u as ya,v as ba,x as Ta,y as Ea,z as wa}from"./chunk-QN7HP2UW.js";import{g as Pe,h as Ys,m as Js}from"./chunk-PIWGKGWP.js";import{a as Fs,c as nn,d as an,e as Gs,f as js,g as zs,i as Us,j as Hs,l as Vs,m as Qs}from"./chunk-X2DWHGCC.js";import{c as Xs}from"./chunk-NQFDJ6BT.js";import{b as la}from"./chunk-A4BVDYIL.js";import{d as ua}from"./chunk-4UKTIQDT.js";import{a as Ca,c as wt,d as Sa}from"./chunk-MLMD3I75.js";import{b as Re,c as on,e as He,f as Nr,g as Ws,j as cn,l as Ks}from"./chunk-CQER6IJ5.js";import{a as ta}from"./chunk-DCDSN67A.js";import{a as De,b as sn,c as $s,d as Or,e as Bs}from"./chunk-OWIQR6N2.js";import{u as Ds,w as _s}from"./chunk-J6QRNQJF.js";import{i as Is}from"./chunk-LV7UIK4Q.js";import{c as Da,d as _a}from"./chunk-DHKSPOUQ.js";import{d as Na}from"./chunk-QTQDX4TZ.js";import{a as Fa}from"./chunk-HRUHHHVR.js";import{a as Be}from"./chunk-74MDUIAZ.js";import{c as qs}from"./chunk-S3DT5TPR.js";import{d as _r}from"./chunk-XEMCHGAJ.js";import{c as ln,e as Pl}from"./chunk-Q6F3DYZN.js";import{a as va}from"./chunk-DNVRTJKB.js";import{c as we,h as dn}from"./chunk-S3TBOKAZ.js";import{a as Ns,b as Ir,c as ue}from"./chunk-O7VJ3VKD.js";import{d as pa}from"./chunk-HWQPMUSN.js";import{a as ne,c as Os,d as K}from"./chunk-EPVPXHL7.js";import{a as ks,b as Ms,c as Te,d as Ee}from"./chunk-M2YI5YUR.js";import{h as Mr}from"./chunk-45223KK6.js";import{e as xs,f as As}from"./chunk-TDZ6N43D.js";import{e as xr}from"./chunk-POPSZDI2.js";import{c as Ar,d as kr}from"./chunk-MVVVGQJ6.js";import{d as Se}from"./chunk-IKB3M7OF.js";import{a as Es,b as oe,c as Y}from"./chunk-JVWZAE2H.js";import{m as Ts,n as wl}from"./chunk-H2LHWZRE.js";import{c as Rs}from"./chunk-IQL6XRF5.js";import{a as Pr,b as Ps}from"./chunk-YMUY3TES.js";import{i as U}from"./chunk-XPTCQKVE.js";import{C as pe,w as X}from"./chunk-NZJVDOUN.js";import{b as I,d as ee}from"./chunk-CMN7PU2H.js";import{a as bs,b as Rr,e as Cs}from"./chunk-YKRLUTK7.js";import{a as be,c as Ie,d as tn}from"./chunk-U5SMBJ6F.js";import{d as Ue,o as Ce}from"./chunk-4EJLHNER.js";import{c as Et,d as vs}from"./chunk-LRKLATSH.js";import{b as Ss}from"./chunk-CXCMATZ6.js";import{a as ve,d as El}from"./chunk-ZP5AWQRO.js";import{a as wr,c as F,d as L}from"./chunk-REY52O7J.js";import{a as hs}from"./chunk-TIVKDIF7.js";import{c as Jt,d as ye,e as Zt}from"./chunk-DS5IFRY6.js";import{a as je,d as fs}from"./chunk-5FSPELOG.js";import{R as Sl,S as Yt,b as Ge}from"./chunk-JHKKIJT2.js";import{b as en,c as ze,d as Tt}from"./chunk-GPPTRKEM.js";import{d as ys,e as Tl}from"./chunk-SFITYZLV.js";import{a as w,b as B,c as le,d as $e,e as D}from"./chunk-J7Q5TXFZ.js";import{a as vl,b as bl,d as Cl,f as gs}from"./chunk-Z7SKUC6P.js";var Ko={};Cl(Ko,{DEFAULT_QEC_CONFIG:()=>Qo,ReasoningQEC:()=>Bn,createReasoningQEC:()=>Wo,processReasoning:()=>Od});async function _d(){return Vo?Ho!==null:(Ho=null,Vo=!0,!1)}function Wo(o){return new Bn(o)}function Od(o,e){return Wo(e).process(o)}var bi,Qo,Id,Dd,Ho,Vo,Bn,Xo=bl(()=>{"use strict";Zt();Yt();bi=ye("ReasoningQEC"),Qo={minPaths:3,confidenceThreshold:.5,majorityThreshold:.5,useNativeBackend:!0,votingMethod:"weighted"},Id={"test-generation":["specification-driven","boundary-analysis","mutation-testing"],"security-audit":["threat-modeling","attack-surface","defense-in-depth"],"defect-triage":["root-cause-analysis","impact-assessment","risk-prioritization"]},Dd=["analytical","empirical","heuristic"],Ho=null,Vo=!1;Bn=class{config;nativeAvailable=!1;constructor(e={}){this.config={...Qo,...e}}async initialize(){if(this.config.useNativeBackend){let e=Ge();(e.useQEFlashAttention||e.useQEGNNIndex)&&(this.nativeAvailable=await _d())}}generatePaths(e){let t=Math.max(this.config.minPaths,3),n=Id[e.type]??Dd,r=[];for(let i=0;i<t;i++){let s=n[i%n.length],a=this.generatePathSteps(e,i,s),c=this.deriveConclusion(a,s),l=this.calculatePathConfidence(a);r.push({id:i,steps:a,conclusion:c,confidence:l})}return bi.debug(`Generated ${r.length} reasoning paths for problem type: ${e.type}`),r}extractSyndromes(e){if(e.length<2)return[];let t=[],n=Math.max(...e.map(i=>i.steps.length));for(let i=0;i<n;i++){let s=new Map;for(let l of e){let d=l.steps[i];if(!d)continue;let u=s.get(d.conclusion)??[];u.push(l.id),s.set(d.conclusion,u)}if(s.size<=1)continue;let a=[...s.entries()].map(([l,d])=>d.map(u=>({pathId:u,conclusion:l}))).flat(),c=this.classifySyndromeSeverity(s,e.length);t.push({stepIndex:i,disagreements:a,severity:c})}let r=new Map;for(let i of e){let s=r.get(i.conclusion)??[];s.push(i.id),r.set(i.conclusion,s)}if(r.size>1){let i=[...r.entries()].map(([a,c])=>c.map(l=>({pathId:l,conclusion:a}))).flat(),s=this.classifySyndromeSeverity(r,e.length);t.push({stepIndex:-1,disagreements:i,severity:s})}return bi.debug(`Extracted ${t.length} syndromes: ${t.filter(i=>i.severity==="critical").length} critical, ${t.filter(i=>i.severity==="major").length} major, ${t.filter(i=>i.severity==="minor").length} minor`),t}correctErrors(e,t){if(e.length===0)return{steps:[],conclusion:"",confidence:0,corrections:[],syndromeCount:t.length};let n=new Set(t.filter(d=>d.stepIndex>=0).map(d=>d.stepIndex)),r=Math.max(...e.map(d=>d.steps.length)),i=[],s=[];for(let d=0;d<r;d++)if(n.has(d)){let{step:u,correction:m}=this.correctStep(e,d);i.push(u),m&&s.push(m)}else{let u=e[0].steps[d];u&&i.push({...u})}let a=this.correctConclusion(e),c=this.calculateCorrectedConfidence(e,t),l={steps:i,conclusion:a,confidence:c,corrections:s,syndromeCount:t.length};return bi.debug(`Error correction applied: ${s.length} corrections, confidence: ${c.toFixed(3)}`),l}validate(e){let t=[];e.confidence<this.config.confidenceThreshold&&t.push({stepIndex:-1,type:"low-confidence",description:`Overall confidence ${e.confidence.toFixed(3)} is below threshold ${this.config.confidenceThreshold}`});for(let i of e.steps)i.evidence.length===0&&t.push({stepIndex:i.index,type:"inconsistent-evidence",description:`Step ${i.index} has no supporting evidence`});e.syndromeCount>0&&e.confidence<.3&&t.push({stepIndex:-1,type:"all-divergent",description:`${e.syndromeCount} syndromes with confidence ${e.confidence.toFixed(3)} suggests all paths diverged significantly`});for(let i of e.corrections)i.reason.includes("no clear majority")&&t.push({stepIndex:i.stepIndex,type:"no-majority",description:`Step ${i.stepIndex}: ${i.reason}`});let n=t.length===0,r=n?e.confidence:e.confidence*(1-t.length*.1);return{valid:n,confidence:Math.max(0,r),issues:t}}process(e){let t=this.generatePaths(e),n=this.extractSyndromes(t),r=this.correctErrors(t,n),i=this.validate(r);return{paths:t,syndromes:n,corrected:r,validation:i}}getConfig(){return{...this.config}}isNativeAvailable(){return this.nativeAvailable}generatePathSteps(e,t,n){return e.steps.map((r,i)=>{let s=this.generateStepConclusion(r,n,e.context,t),a=this.gatherEvidence(r,n,e.context);return{index:i,description:`[${n}] ${r}`,conclusion:s,evidence:a}})}generateStepConclusion(e,t,n,r){let i=Object.keys(n).sort(),s={0:l=>l.length>0?`Focused on ${l[0]}`:"Primary analysis",1:l=>l.length>1?`Focused on ${l[l.length-1]}`:"Secondary analysis",2:l=>l.length>0?`Cross-referencing ${l.join(" and ")}`:"Holistic analysis"},c=(s[r%3]??s[0])(i);return`[${t}] ${e}: ${c}`}gatherEvidence(e,t,n){let r=[];r.push(`Analysis via ${t}: ${e}`);for(let[i,s]of Object.entries(n))(typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&r.push(`Context[${i}]: ${String(s)}`);return r}deriveConclusion(e,t){if(e.length===0)return`No conclusion (${t})`;let n=e[e.length-1];return`${t}: ${n.conclusion}`}calculatePathConfidence(e){if(e.length===0)return 0;let t=e.reduce((n,r)=>n+r.evidence.length,0)/e.length;return Math.min(1,.5+t*.1)}classifySyndromeSeverity(e,t){let n=Math.max(...[...e.values()].map(r=>r.length));return n>=Math.ceil(t*2/3)?"minor":n>=Math.ceil(t/2)?"major":"critical"}correctStep(e,t){let n=new Map,r=new Map,i=this.config.votingMethod==="weighted";for(let g of e){let f=g.steps[t];if(!f)continue;let h=n.get(f.conclusion)??0,v=i?g.confidence:1;n.set(f.conclusion,h+v),r.set(f.conclusion,f)}if(n.size===0)return{step:{index:t,description:`Step ${t} (no data)`,conclusion:"",evidence:[]},correction:null};let s=[...n.entries()].sort((g,f)=>f[1]-g[1]||g[0].localeCompare(f[0])),[a,c]=s[0],l=r.get(a),d=new Set;for(let g of e){let f=g.steps[t];if(f)for(let h of f.evidence)d.add(h)}let u={index:t,description:l.description,conclusion:a,evidence:[...d]},m=e[0].steps[t]?.conclusion,p=null;if(m&&m!==a){let g=e.filter(C=>C.steps[t]).length,f=[...n.values()].reduce((C,b)=>C+b,0),v=c/f>this.config.majorityThreshold;p={stepIndex:t,original:m,corrected:a,reason:v?`${i?"Weighted vote":"Majority vote"} (${c.toFixed(2)}/${f.toFixed(2)} weight from ${g} paths)`:`Selected highest ${i?"weight":"count"} (${c.toFixed(2)}/${f.toFixed(2)}), no clear majority`}}return{step:u,correction:p}}correctConclusion(e){let t=new Map,n=this.config.votingMethod==="weighted";for(let i of e){let s=t.get(i.conclusion)??0,a=n?i.confidence:1;t.set(i.conclusion,s+a)}return[...t.entries()].sort((i,s)=>s[1]-i[1]||i[0].localeCompare(s[0]))[0]?.[0]??""}calculateCorrectedConfidence(e,t){let n=e.reduce((l,d)=>l+d.confidence,0)/e.length,r=t.filter(l=>l.severity==="critical").length,i=t.filter(l=>l.severity==="major").length,s=t.filter(l=>l.severity==="minor").length,a=r*.2+i*.1+s*.03,c=t.length===0?.1:0;return Math.max(0,Math.min(1,n-a+c))}}});D();ee();Tt();import*as G from"fs/promises";import*as N from"path";import{createHash as mo,randomBytes as zr}from"crypto";var vn=o=>o!==null&&typeof o=="object"?o:{};function xl(o){let e=vn(o),t=vn(e.summary),n=Array.isArray(e.vulnerabilities)?e.vulnerabilities:[],r=i=>typeof t[i]=="number"?t[i]:0;return{vulnerabilities:n.length,critical:r("critical"),high:r("high"),medium:r("medium"),low:r("low"),topVulnerabilities:n.slice(0,10).map(i=>({type:i.title??i.category??"finding",severity:i.severity??"unknown",file:i.location?.file??"",line:i.location?.line??0})),findings:n.map(i=>({title:i.title,type:i.category,severity:i.severity??"unknown",location:i.location?.file?{file:i.location.file,line:i.location.line}:void 0,description:i.description})),recommendations:[],evidence:e.evidence,coverage:e.coverage,analysisDepth:"sast-patterns"}}function Al(o){let e=vn(o),t=vn(e.score),n=Array.isArray(e.metrics)?e.metrics:[],r=Array.isArray(e.unmeasured)?e.unmeasured.map(i=>i.metric).filter(i=>!!i):[];return{...typeof t.overall=="number"?{qualityScore:t.overall}:{},...typeof e.subsetScore=="number"?{subsetScore:e.subsetScore}:{},passed:!1,gateEvaluated:!1,metrics:Object.fromEntries(n.filter(i=>i.name&&typeof i.value=="number").map(i=>[i.name,i.value])),recommendations:Array.isArray(e.recommendations)?e.recommendations:[],unmeasured:r,evidenceStatus:r.length>0?"insufficient-evidence":"measured",scoreBasis:n.map(i=>i.name).filter(i=>!!i)}}function uo(o,e){switch(o){case"sast-scan":return{saveType:"scan-security",report:xl(e)};case"analyze-quality":return{saveType:"assess-quality",report:Al(e)};default:return{saveType:o,report:e}}}var kl=100;function Ur(o){return o.evidence?.completeness==="complete"?"completed":o.evidence?.completeness==="partial"?"partial":o.evidence?"unavailable":"unverified"}var Ml={typescript:{jest:".test.ts",vitest:".test.ts",mocha:".spec.ts",default:".test.ts"},javascript:{jest:".test.js",vitest:".test.js",mocha:".spec.js",default:".test.js"},python:{pytest:"test_",unittest:"_test",default:"test_"},java:{junit:"Test.java",testng:"Test.java",default:"Test.java"},go:{testing:"_test.go",default:"_test.go"},rust:{cargo:"_test.rs",default:"_test.rs"},ruby:{rspec:"_spec.rb",minitest:"_test.rb",default:"_spec.rb"},php:{phpunit:"Test.php",pest:".test.php",default:"Test.php"},csharp:{xunit:"Tests.cs",nunit:"Tests.cs",mstest:"Tests.cs",default:"Tests.cs"},kotlin:{junit:"Test.kt",kotest:"Spec.kt",default:"Test.kt"},swift:{xctest:"Tests.swift",default:"Tests.swift"}},Br=class{baseDir;resultsDir;constructor(e=en()){this.baseDir=e,this.resultsDir=N.join(e,"results")}async save(e,t,n,r={}){let{saveType:i,report:s}=uo(t,n),a=new Date,c=[];if(process.env.AQE_MEMORY_BACKEND==="memory")return{taskId:e,taskType:t,timestamp:a,files:c,summary:this.extractSummary(i,s)};await this.ensureDirectories(t);let l=this.formatTimestamp(a),d=r.filenamePrefix||`${l}_${this.uniqueSuffix(e)}`;switch(i){case"generate-tests":c.push(...await this.saveTestGeneration(s,d,r));break;case"analyze-coverage":c.push(...await this.saveCoverage(s,d,r));break;case"scan-security":c.push(...await this.saveSecurityScan(s,d,r));break;case"assess-quality":c.push(...await this.saveQualityAssessment(s,d,r));break;case"index-code":c.push(...await this.saveCodeIndex(s,d,r));break;case"predict-defects":c.push(...await this.saveDefectPrediction(s,d,r));break;case"validate-contracts":c.push(...await this.saveContractValidation(s,d,r));break;case"test-accessibility":c.push(...await this.saveAccessibilityTest(s,d,r));break;case"run-chaos":c.push(...await this.saveChaosTest(s,d,r));break;default:c.push(...await this.saveGeneric(i,s,d))}let u=this.extractSummary(i,s);return await this.updateIndex(e,t,a,c,u),{taskId:e,taskType:t,timestamp:a,files:c,summary:u}}async saveTestGeneration(e,t,n){let r=[],i=e,s=N.join(this.resultsDir,"tests","generated");await G.mkdir(s,{recursive:!0});let a=N.join(this.resultsDir,"tests",`${t}_manifest.json`),c=JSON.stringify({generated:new Date().toISOString(),testsGenerated:i.testsGenerated,coverageEstimate:i.coverageEstimate,patternsUsed:i.patternsUsed,language:n.language||"typescript",framework:n.framework||"vitest",tests:i.tests},null,2);if(r.push(await this.writeNewFile(a,c,"json")),i.tests)for(let u of i.tests){let m=u.testCode??u.code;if(m){let p=this.getTestExtension(n.language||"typescript",n.framework||"vitest"),g=this.generatedTestFilename(u,p),f=N.join(s,g);try{r.push(await this.replaceFile(f,m,"source"))}catch(h){console.warn(`ResultSaver: could not write generated test ${g}: ${h.message}`)}}}let l=N.join(this.resultsDir,"tests",`${t}_report.md`),d=this.generateTestReport(i,n);return r.push(await this.writeNewFile(l,d,"markdown")),r}async saveCoverage(e,t,n){let r=[],i=e,s=N.join(this.resultsDir,"coverage"),a=N.join(s,`${t}_coverage.json`);if(r.push(await this.writeNewFile(a,JSON.stringify(i,null,2),"json")),n.includeSecondary!==!1&&i.measured===!0){let d=N.join(s,`${t}_coverage.lcov`),u=this.generateLcov(i);r.push(await this.writeNewFile(d,u,"lcov"))}let c=N.join(s,`${t}_report.md`),l=this.generateCoverageReport(i);return r.push(await this.writeNewFile(c,l,"markdown")),r}async saveSecurityScan(e,t,n){let r=[],i=e,s=N.join(this.resultsDir,"security"),a=N.join(s,`${t}_scan.json`);if(r.push(await this.writeNewFile(a,JSON.stringify(i,null,2),"json")),n.includeSecondary!==!1){let d=N.join(s,`${t}_scan.sarif`),u=this.generateSarif(i);r.push(await this.writeNewFile(d,u,"sarif"))}let c=N.join(s,`${t}_report.md`),l=this.generateSecurityReport(i);return r.push(await this.writeNewFile(c,l,"markdown")),r}async saveQualityAssessment(e,t,n){let r=[],i=e,s=N.join(this.resultsDir,"quality"),a=N.join(s,`${t}_assessment.json`);r.push(await this.writeNewFile(a,JSON.stringify(i,null,2),"json"));let c=N.join(s,`${t}_report.md`),l=this.generateQualityReport(i);return r.push(await this.writeNewFile(c,l,"markdown")),r}async saveCodeIndex(e,t,n){let r=[],i=e,s=N.join(this.resultsDir,"code-index");await G.mkdir(s,{recursive:!0});let a=N.join(s,`${t}_index.json`);return r.push(await this.writeNewFile(a,JSON.stringify(i,null,2),"json")),r}async saveDefectPrediction(e,t,n){let r=[],i=N.join(this.resultsDir,"defects");await G.mkdir(i,{recursive:!0});let s=N.join(i,`${t}_prediction.json`);return r.push(await this.writeNewFile(s,JSON.stringify(e,null,2),"json")),r}async saveContractValidation(e,t,n){let r=[],i=N.join(this.resultsDir,"contracts");await G.mkdir(i,{recursive:!0});let s=N.join(i,`${t}_validation.json`);return r.push(await this.writeNewFile(s,JSON.stringify(e,null,2),"json")),r}async saveAccessibilityTest(e,t,n){let r=[],i=N.join(this.resultsDir,"accessibility");await G.mkdir(i,{recursive:!0});let s=N.join(i,`${t}_test.json`);return r.push(await this.writeNewFile(s,JSON.stringify(e,null,2),"json")),r}async saveChaosTest(e,t,n){let r=[],i=N.join(this.resultsDir,"chaos");await G.mkdir(i,{recursive:!0});let s=N.join(i,`${t}_chaos.json`);return r.push(await this.writeNewFile(s,JSON.stringify(e,null,2),"json")),r}async saveGeneric(e,t,n){let r=[],i=N.join(this.resultsDir,"other");await G.mkdir(i,{recursive:!0});let s=N.join(i,`${n}_${e}.json`);return r.push(await this.writeNewFile(s,JSON.stringify(t,null,2),"json")),r}generateLcov(e){let t=Math.round(e.lineCoverage??0);return`TN:agentic-qe-coverage
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.18");process.exit(0)}
2
+ import{a as Ke}from"./chunk-ZXHHHR7K.js";import{a as qr}from"./chunk-SOUS7Z2H.js";import{b as zr}from"./chunk-GXEVOT5F.js";import{a as $r,b as za,c as Gr,d as Ua,e as fn,f as Ba,g as Ha,h as Va,i as Qa,j as Wa,k as Ka,l as Xa,m as Ya,n as Ja,o as Za,p as eo,q as jr}from"./chunk-54RCGMLB.js";import{a as so,c as ao,d as oo}from"./chunk-KP4OKOKV.js";import{a as to,b as no,c as ro}from"./chunk-LPUSH3VF.js";import{a as $a,b as Ga}from"./chunk-IGIYANVT.js";import{b as io}from"./chunk-MKRKRXTX.js";import{a as ja}from"./chunk-GGISVPOZ.js";import{a as co}from"./chunk-3LX5OKBD.js";import{a as lo}from"./chunk-Y4YN2RXR.js";import{a as uo}from"./chunk-X4B345B6.js";import{a as mo}from"./chunk-SU3SXMVG.js";import{c as $,e as hn,i as Q,j as yn,l as A}from"./chunk-YISDX6WB.js";import{a as po}from"./chunk-ULYUVUL2.js";import{b as mn}from"./chunk-XQMGXTHJ.js";import{b as pn,c as gn}from"./chunk-43KUVBSU.js";import{a as Xe}from"./chunk-TVBDUMKT.js";import{A as Pa,B as xa,C as Aa,D as ka,E as Lr,F as Ma,G as Ia,H as Da,I as _a,J as Qe,K as We,L as Fa,a as Rs,b as rn,c as Dr,d as Tl,e as qs,f as ea,g as ta,h as ra,i as ia,j as sa,k as aa,l as un,m as oa,n as ca,o as la,p as ma,q as pa,r as fa,s as ha,t as ya,u as va,v as Ca,x as Ea,y as wa,z as Ra}from"./chunk-SJF3O4FX.js";import{g as Pe,h as Js,m as Zs}from"./chunk-XJN3RKUD.js";import{a as Ls,c as nn,d as an,e as js,f as zs,g as Us,i as Bs,j as Vs,l as Qs,m as Ws}from"./chunk-FYINK2B7.js";import{c as Ys}from"./chunk-OBCXCRXK.js";import{a as Fr,d as ua}from"./chunk-477FKXSS.js";import{d as da}from"./chunk-MVYQRVLP.js";import{a as Sa,c as Rt,d as Ta}from"./chunk-EONDCWY4.js";import{b as Re,c as on,e as Ve,f as Nr,g as Ks,j as cn,l as Xs}from"./chunk-4HL3SD4A.js";import{a as na}from"./chunk-PGO46IIW.js";import{a as De,b as sn,c as Gs,d as Or,e as Hs}from"./chunk-3YMIT73A.js";import{u as _s,w as Os}from"./chunk-DUCVLT3F.js";import{n as Ds}from"./chunk-LC2QRN7V.js";import{c as Oa,d as Na}from"./chunk-53ZBETYR.js";import{d as La}from"./chunk-E4RMJCGA.js";import{a as qa}from"./chunk-MZC5WM2P.js";import{a as He}from"./chunk-3RPDKJGV.js";import{c as $s}from"./chunk-TRB3EVH3.js";import{d as _r}from"./chunk-N3KQU4UC.js";import{c as ln,e as El}from"./chunk-OA4EQDC4.js";import{a as ba}from"./chunk-OOSV2RIA.js";import{c as we,h as dn}from"./chunk-OHU5P25N.js";import{a as Fs,b as Ir,c as de}from"./chunk-A3GDX6UF.js";import{d as ga}from"./chunk-HBDSCYSK.js";import{a as ne,c as Ns,d as X}from"./chunk-KFCQP434.js";import{a as Ms,b as Is,c as Te,d as Ee}from"./chunk-IZODXKZD.js";import{h as Mr}from"./chunk-6TEVM3X3.js";import{e as As,f as ks}from"./chunk-5AGXIZQ5.js";import{e as xr}from"./chunk-RMEQYJPU.js";import{c as Ar,d as kr}from"./chunk-UNTBVJ5X.js";import{d as Se}from"./chunk-F6YD3BOW.js";import{a as ws,b as le,c as J}from"./chunk-L3IPUIT3.js";import{m as Es,n as Sl}from"./chunk-RTYXFXTI.js";import{c as Ps}from"./chunk-VVGUE2T2.js";import{a as Pr,b as xs}from"./chunk-LTGB7OIU.js";import{i as U}from"./chunk-4BIMTRRX.js";import{C as ge,w as Y}from"./chunk-OW23N2Y5.js";import{a as bs,b as Rr,e as Cs}from"./chunk-MZRBNBB3.js";import{a as be,c as Ie,d as tn}from"./chunk-SRVNR3R3.js";import{b as ie,c as Ss,d as Ts,g as Be,r as Ce}from"./chunk-SWGPLXWW.js";import{c as wt,d as vs}from"./chunk-YFILS5D5.js";import{b as I,d as te}from"./chunk-MQM37KAR.js";import{a as Ue}from"./chunk-M24ZAZ4U.js";import{a as wr,c as F,d as q}from"./chunk-JMRDT2XK.js";import{a as hs}from"./chunk-O5EWFR76.js";import{c as Jt,d as ve,e as Zt}from"./chunk-NKU3FFM4.js";import{a as je,d as fs}from"./chunk-Q7V722K5.js";import{R as bl,S as Yt,b as Ge}from"./chunk-V2LJ54KP.js";import{b as en,c as ze,d as Et}from"./chunk-YP2GHQSV.js";import{d as ys,e as Cl}from"./chunk-WJN3V7QB.js";import{a as w,b as B,c as re,d as $e,e as M}from"./chunk-AWQAE3SW.js";import{a as hl,b as yl,d as vl,f as gs}from"./chunk-BDVFSMOQ.js";var Qo={};vl(Qo,{DEFAULT_QEC_CONFIG:()=>Ho,ReasoningQEC:()=>Bn,createReasoningQEC:()=>Vo,processReasoning:()=>Ad});async function xd(){return Bo?Uo!==null:(Uo=null,Bo=!0,!1)}function Vo(o){return new Bn(o)}function Ad(o,e){return Vo(e).process(o)}var bi,Ho,Rd,Pd,Uo,Bo,Bn,Wo=yl(()=>{"use strict";Zt();Yt();bi=ve("ReasoningQEC"),Ho={minPaths:3,confidenceThreshold:.5,majorityThreshold:.5,useNativeBackend:!0,votingMethod:"weighted"},Rd={"test-generation":["specification-driven","boundary-analysis","mutation-testing"],"security-audit":["threat-modeling","attack-surface","defense-in-depth"],"defect-triage":["root-cause-analysis","impact-assessment","risk-prioritization"]},Pd=["analytical","empirical","heuristic"],Uo=null,Bo=!1;Bn=class{config;nativeAvailable=!1;constructor(e={}){this.config={...Ho,...e}}async initialize(){if(this.config.useNativeBackend){let e=Ge();(e.useQEFlashAttention||e.useQEGNNIndex)&&(this.nativeAvailable=await xd())}}generatePaths(e){let t=Math.max(this.config.minPaths,3),n=Rd[e.type]??Pd,r=[];for(let i=0;i<t;i++){let s=n[i%n.length],a=this.generatePathSteps(e,i,s),c=this.deriveConclusion(a,s),l=this.calculatePathConfidence(a);r.push({id:i,steps:a,conclusion:c,confidence:l})}return bi.debug(`Generated ${r.length} reasoning paths for problem type: ${e.type}`),r}extractSyndromes(e){if(e.length<2)return[];let t=[],n=Math.max(...e.map(i=>i.steps.length));for(let i=0;i<n;i++){let s=new Map;for(let l of e){let u=l.steps[i];if(!u)continue;let d=s.get(u.conclusion)??[];d.push(l.id),s.set(u.conclusion,d)}if(s.size<=1)continue;let a=[...s.entries()].map(([l,u])=>u.map(d=>({pathId:d,conclusion:l}))).flat(),c=this.classifySyndromeSeverity(s,e.length);t.push({stepIndex:i,disagreements:a,severity:c})}let r=new Map;for(let i of e){let s=r.get(i.conclusion)??[];s.push(i.id),r.set(i.conclusion,s)}if(r.size>1){let i=[...r.entries()].map(([a,c])=>c.map(l=>({pathId:l,conclusion:a}))).flat(),s=this.classifySyndromeSeverity(r,e.length);t.push({stepIndex:-1,disagreements:i,severity:s})}return bi.debug(`Extracted ${t.length} syndromes: ${t.filter(i=>i.severity==="critical").length} critical, ${t.filter(i=>i.severity==="major").length} major, ${t.filter(i=>i.severity==="minor").length} minor`),t}correctErrors(e,t){if(e.length===0)return{steps:[],conclusion:"",confidence:0,corrections:[],syndromeCount:t.length};let n=new Set(t.filter(u=>u.stepIndex>=0).map(u=>u.stepIndex)),r=Math.max(...e.map(u=>u.steps.length)),i=[],s=[];for(let u=0;u<r;u++)if(n.has(u)){let{step:d,correction:m}=this.correctStep(e,u);i.push(d),m&&s.push(m)}else{let d=e[0].steps[u];d&&i.push({...d})}let a=this.correctConclusion(e),c=this.calculateCorrectedConfidence(e,t),l={steps:i,conclusion:a,confidence:c,corrections:s,syndromeCount:t.length};return bi.debug(`Error correction applied: ${s.length} corrections, confidence: ${c.toFixed(3)}`),l}validate(e){let t=[];e.confidence<this.config.confidenceThreshold&&t.push({stepIndex:-1,type:"low-confidence",description:`Overall confidence ${e.confidence.toFixed(3)} is below threshold ${this.config.confidenceThreshold}`});for(let i of e.steps)i.evidence.length===0&&t.push({stepIndex:i.index,type:"inconsistent-evidence",description:`Step ${i.index} has no supporting evidence`});e.syndromeCount>0&&e.confidence<.3&&t.push({stepIndex:-1,type:"all-divergent",description:`${e.syndromeCount} syndromes with confidence ${e.confidence.toFixed(3)} suggests all paths diverged significantly`});for(let i of e.corrections)i.reason.includes("no clear majority")&&t.push({stepIndex:i.stepIndex,type:"no-majority",description:`Step ${i.stepIndex}: ${i.reason}`});let n=t.length===0,r=n?e.confidence:e.confidence*(1-t.length*.1);return{valid:n,confidence:Math.max(0,r),issues:t}}process(e){let t=this.generatePaths(e),n=this.extractSyndromes(t),r=this.correctErrors(t,n),i=this.validate(r);return{paths:t,syndromes:n,corrected:r,validation:i}}getConfig(){return{...this.config}}isNativeAvailable(){return this.nativeAvailable}generatePathSteps(e,t,n){return e.steps.map((r,i)=>{let s=this.generateStepConclusion(r,n,e.context,t),a=this.gatherEvidence(r,n,e.context);return{index:i,description:`[${n}] ${r}`,conclusion:s,evidence:a}})}generateStepConclusion(e,t,n,r){let i=Object.keys(n).sort(),s={0:l=>l.length>0?`Focused on ${l[0]}`:"Primary analysis",1:l=>l.length>1?`Focused on ${l[l.length-1]}`:"Secondary analysis",2:l=>l.length>0?`Cross-referencing ${l.join(" and ")}`:"Holistic analysis"},c=(s[r%3]??s[0])(i);return`[${t}] ${e}: ${c}`}gatherEvidence(e,t,n){let r=[];r.push(`Analysis via ${t}: ${e}`);for(let[i,s]of Object.entries(n))(typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&r.push(`Context[${i}]: ${String(s)}`);return r}deriveConclusion(e,t){if(e.length===0)return`No conclusion (${t})`;let n=e[e.length-1];return`${t}: ${n.conclusion}`}calculatePathConfidence(e){if(e.length===0)return 0;let t=e.reduce((n,r)=>n+r.evidence.length,0)/e.length;return Math.min(1,.5+t*.1)}classifySyndromeSeverity(e,t){let n=Math.max(...[...e.values()].map(r=>r.length));return n>=Math.ceil(t*2/3)?"minor":n>=Math.ceil(t/2)?"major":"critical"}correctStep(e,t){let n=new Map,r=new Map,i=this.config.votingMethod==="weighted";for(let f of e){let g=f.steps[t];if(!g)continue;let h=n.get(g.conclusion)??0,y=i?f.confidence:1;n.set(g.conclusion,h+y),r.set(g.conclusion,g)}if(n.size===0)return{step:{index:t,description:`Step ${t} (no data)`,conclusion:"",evidence:[]},correction:null};let s=[...n.entries()].sort((f,g)=>g[1]-f[1]||f[0].localeCompare(g[0])),[a,c]=s[0],l=r.get(a),u=new Set;for(let f of e){let g=f.steps[t];if(g)for(let h of g.evidence)u.add(h)}let d={index:t,description:l.description,conclusion:a,evidence:[...u]},m=e[0].steps[t]?.conclusion,p=null;if(m&&m!==a){let f=e.filter(b=>b.steps[t]).length,g=[...n.values()].reduce((b,C)=>b+C,0),y=c/g>this.config.majorityThreshold;p={stepIndex:t,original:m,corrected:a,reason:y?`${i?"Weighted vote":"Majority vote"} (${c.toFixed(2)}/${g.toFixed(2)} weight from ${f} paths)`:`Selected highest ${i?"weight":"count"} (${c.toFixed(2)}/${g.toFixed(2)}), no clear majority`}}return{step:d,correction:p}}correctConclusion(e){let t=new Map,n=this.config.votingMethod==="weighted";for(let i of e){let s=t.get(i.conclusion)??0,a=n?i.confidence:1;t.set(i.conclusion,s+a)}return[...t.entries()].sort((i,s)=>s[1]-i[1]||i[0].localeCompare(s[0]))[0]?.[0]??""}calculateCorrectedConfidence(e,t){let n=e.reduce((l,u)=>l+u.confidence,0)/e.length,r=t.filter(l=>l.severity==="critical").length,i=t.filter(l=>l.severity==="major").length,s=t.filter(l=>l.severity==="minor").length,a=r*.2+i*.1+s*.03,c=t.length===0?.1:0;return Math.max(0,Math.min(1,n-a+c))}}});M();te();Et();import*as j from"fs/promises";import*as O from"path";import{createHash as fo,randomBytes as Ur}from"crypto";var vn=o=>o!==null&&typeof o=="object"?o:{};function wl(o){let e=vn(o),t=vn(e.summary),n=Array.isArray(e.vulnerabilities)?e.vulnerabilities:[],r=i=>typeof t[i]=="number"?t[i]:0;return{vulnerabilities:n.length,critical:r("critical"),high:r("high"),medium:r("medium"),low:r("low"),topVulnerabilities:n.slice(0,10).map(i=>({type:i.title??i.category??"finding",severity:i.severity??"unknown",file:i.location?.file??"",line:i.location?.line??0})),findings:n.map(i=>({title:i.title,type:i.category,severity:i.severity??"unknown",location:i.location?.file?{file:i.location.file,line:i.location.line}:void 0,description:i.description})),recommendations:[],evidence:e.evidence,coverage:e.coverage,analysisDepth:"sast-patterns"}}function Rl(o){let e=vn(o),t=vn(e.score),n=Array.isArray(e.metrics)?e.metrics:[],r=Array.isArray(e.unmeasured)?e.unmeasured.map(i=>i.metric).filter(i=>!!i):[];return{...typeof t.overall=="number"?{qualityScore:t.overall}:{},...typeof e.subsetScore=="number"?{subsetScore:e.subsetScore}:{},passed:!1,gateEvaluated:!1,metrics:Object.fromEntries(n.filter(i=>i.name&&typeof i.value=="number").map(i=>[i.name,i.value])),recommendations:Array.isArray(e.recommendations)?e.recommendations:[],unmeasured:r,evidenceStatus:r.length>0?"insufficient-evidence":"measured",scoreBasis:n.map(i=>i.name).filter(i=>!!i)}}function go(o,e){switch(o){case"sast-scan":return{saveType:"scan-security",report:wl(e)};case"analyze-quality":return{saveType:"assess-quality",report:Rl(e)};default:return{saveType:o,report:e}}}var Pl=100;function Br(o){return o.evidence?.completeness==="complete"?"completed":o.evidence?.completeness==="partial"?"partial":o.evidence?"unavailable":"unverified"}var xl={typescript:{jest:".test.ts",vitest:".test.ts",mocha:".spec.ts",default:".test.ts"},javascript:{jest:".test.js",vitest:".test.js",mocha:".spec.js",default:".test.js"},python:{pytest:"test_",unittest:"_test",default:"test_"},java:{junit:"Test.java",testng:"Test.java",default:"Test.java"},go:{testing:"_test.go",default:"_test.go"},rust:{cargo:"_test.rs",default:"_test.rs"},ruby:{rspec:"_spec.rb",minitest:"_test.rb",default:"_spec.rb"},php:{phpunit:"Test.php",pest:".test.php",default:"Test.php"},csharp:{xunit:"Tests.cs",nunit:"Tests.cs",mstest:"Tests.cs",default:"Tests.cs"},kotlin:{junit:"Test.kt",kotest:"Spec.kt",default:"Test.kt"},swift:{xctest:"Tests.swift",default:"Tests.swift"}},Hr=class{baseDir;resultsDir;constructor(e=en()){this.baseDir=e,this.resultsDir=O.join(e,"results")}async save(e,t,n,r={}){let{saveType:i,report:s}=go(t,n),a=new Date,c=[];if(process.env.AQE_MEMORY_BACKEND==="memory")return{taskId:e,taskType:t,timestamp:a,files:c,summary:this.extractSummary(i,s)};await this.ensureDirectories(t);let l=this.formatTimestamp(a),u=r.filenamePrefix||`${l}_${this.uniqueSuffix(e)}`;switch(i){case"generate-tests":c.push(...await this.saveTestGeneration(s,u,r));break;case"analyze-coverage":c.push(...await this.saveCoverage(s,u,r));break;case"scan-security":c.push(...await this.saveSecurityScan(s,u,r));break;case"assess-quality":c.push(...await this.saveQualityAssessment(s,u,r));break;case"index-code":c.push(...await this.saveCodeIndex(s,u,r));break;case"predict-defects":c.push(...await this.saveDefectPrediction(s,u,r));break;case"validate-contracts":c.push(...await this.saveContractValidation(s,u,r));break;case"test-accessibility":c.push(...await this.saveAccessibilityTest(s,u,r));break;case"run-chaos":c.push(...await this.saveChaosTest(s,u,r));break;default:c.push(...await this.saveGeneric(i,s,u))}let d=this.extractSummary(i,s);return await this.updateIndex(e,t,a,c,d),{taskId:e,taskType:t,timestamp:a,files:c,summary:d}}async saveTestGeneration(e,t,n){let r=[],i=e,s=O.join(this.resultsDir,"tests","generated");await j.mkdir(s,{recursive:!0});let a=O.join(this.resultsDir,"tests",`${t}_manifest.json`),c=JSON.stringify({generated:new Date().toISOString(),testsGenerated:i.testsGenerated,coverageEstimate:i.coverageEstimate,patternsUsed:i.patternsUsed,language:n.language||"typescript",framework:n.framework||"vitest",tests:i.tests},null,2);if(r.push(await this.writeNewFile(a,c,"json")),i.tests)for(let d of i.tests){let m=d.testCode??d.code;if(m){let p=this.getTestExtension(n.language||"typescript",n.framework||"vitest"),f=this.generatedTestFilename(d,p),g=O.join(s,f);try{r.push(await this.replaceFile(g,m,"source"))}catch(h){console.warn(`ResultSaver: could not write generated test ${f}: ${h.message}`)}}}let l=O.join(this.resultsDir,"tests",`${t}_report.md`),u=this.generateTestReport(i,n);return r.push(await this.writeNewFile(l,u,"markdown")),r}async saveCoverage(e,t,n){let r=[],i=e,s=O.join(this.resultsDir,"coverage"),a=O.join(s,`${t}_coverage.json`);if(r.push(await this.writeNewFile(a,JSON.stringify(i,null,2),"json")),n.includeSecondary!==!1&&i.measured===!0){let u=O.join(s,`${t}_coverage.lcov`),d=this.generateLcov(i);r.push(await this.writeNewFile(u,d,"lcov"))}let c=O.join(s,`${t}_report.md`),l=this.generateCoverageReport(i);return r.push(await this.writeNewFile(c,l,"markdown")),r}async saveSecurityScan(e,t,n){let r=[],i=e,s=O.join(this.resultsDir,"security"),a=O.join(s,`${t}_scan.json`);if(r.push(await this.writeNewFile(a,JSON.stringify(i,null,2),"json")),n.includeSecondary!==!1){let u=O.join(s,`${t}_scan.sarif`),d=this.generateSarif(i);r.push(await this.writeNewFile(u,d,"sarif"))}let c=O.join(s,`${t}_report.md`),l=this.generateSecurityReport(i);return r.push(await this.writeNewFile(c,l,"markdown")),r}async saveQualityAssessment(e,t,n){let r=[],i=e,s=O.join(this.resultsDir,"quality"),a=O.join(s,`${t}_assessment.json`);r.push(await this.writeNewFile(a,JSON.stringify(i,null,2),"json"));let c=O.join(s,`${t}_report.md`),l=this.generateQualityReport(i);return r.push(await this.writeNewFile(c,l,"markdown")),r}async saveCodeIndex(e,t,n){let r=[],i=e,s=O.join(this.resultsDir,"code-index");await j.mkdir(s,{recursive:!0});let a=O.join(s,`${t}_index.json`);return r.push(await this.writeNewFile(a,JSON.stringify(i,null,2),"json")),r}async saveDefectPrediction(e,t,n){let r=[],i=O.join(this.resultsDir,"defects");await j.mkdir(i,{recursive:!0});let s=O.join(i,`${t}_prediction.json`);return r.push(await this.writeNewFile(s,JSON.stringify(e,null,2),"json")),r}async saveContractValidation(e,t,n){let r=[],i=O.join(this.resultsDir,"contracts");await j.mkdir(i,{recursive:!0});let s=O.join(i,`${t}_validation.json`);return r.push(await this.writeNewFile(s,JSON.stringify(e,null,2),"json")),r}async saveAccessibilityTest(e,t,n){let r=[],i=O.join(this.resultsDir,"accessibility");await j.mkdir(i,{recursive:!0});let s=O.join(i,`${t}_test.json`);return r.push(await this.writeNewFile(s,JSON.stringify(e,null,2),"json")),r}async saveChaosTest(e,t,n){let r=[],i=O.join(this.resultsDir,"chaos");await j.mkdir(i,{recursive:!0});let s=O.join(i,`${t}_chaos.json`);return r.push(await this.writeNewFile(s,JSON.stringify(e,null,2),"json")),r}async saveGeneric(e,t,n){let r=[],i=O.join(this.resultsDir,"other");await j.mkdir(i,{recursive:!0});let s=O.join(i,`${n}_${e}.json`);return r.push(await this.writeNewFile(s,JSON.stringify(t,null,2),"json")),r}generateLcov(e){let t=Math.round(e.lineCoverage??0);return`TN:agentic-qe-coverage
3
3
  SF:summary
4
4
  DA:1,${t}
5
5
  LF:100
6
6
  LH:${t}
7
7
  end_of_record
8
- `}generateSarif(e){let t=Ur(e),n=e.findings??e.topVulnerabilities;return JSON.stringify({$schema:"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",version:"2.1.0",runs:[{tool:{driver:{name:"agentic-qe-v3",version:"3.0.0",informationUri:"https://github.com/ruvnet/agentic-qe"}},properties:{securityScan:{status:t,evidence:e.evidence,coverage:e.coverage,limitations:e.limitations,analysisDepth:e.analysisDepth}},invocations:[{executionSuccessful:e.evidence?.completeness==="complete",...e.evidence?.completeness==="complete"?{}:{toolExecutionNotifications:[{level:"warning",message:{text:`Security analysis ${t}; findings do not establish complete coverage.`}}]}}],results:n.map((r,i)=>({ruleId:`VULN-${String(i+1).padStart(3,"0")}`,level:r.severity==="critical"||r.severity==="high"?"error":"warning",message:{text:r.type??r.title??"Security finding"},locations:[{physicalLocation:{artifactLocation:{uri:r.file??r.location?.file??""},...(r.line??r.location?.line??0)>0?{region:{startLine:r.line??r.location?.line}}:{}}}]}))}]},null,2)}generateTestReport(e,t){return`# Test Generation Report
8
+ `}generateSarif(e){let t=Br(e),n=e.findings??e.topVulnerabilities;return JSON.stringify({$schema:"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",version:"2.1.0",runs:[{tool:{driver:{name:"agentic-qe-v3",version:"3.0.0",informationUri:"https://github.com/ruvnet/agentic-qe"}},properties:{securityScan:{status:t,evidence:e.evidence,coverage:e.coverage,limitations:e.limitations,analysisDepth:e.analysisDepth}},invocations:[{executionSuccessful:e.evidence?.completeness==="complete",...e.evidence?.completeness==="complete"?{}:{toolExecutionNotifications:[{level:"warning",message:{text:`Security analysis ${t}; findings do not establish complete coverage.`}}]}}],results:n.map((r,i)=>({ruleId:`VULN-${String(i+1).padStart(3,"0")}`,level:r.severity==="critical"||r.severity==="high"?"error":"warning",message:{text:r.type??r.title??"Security finding"},locations:[{physicalLocation:{artifactLocation:{uri:r.file??r.location?.file??""},...(r.line??r.location?.line??0)>0?{region:{startLine:r.line??r.location?.line}}:{}}}]}))}]},null,2)}generateTestReport(e,t){return`# Test Generation Report
9
9
 
10
10
  **Generated:** ${new Date().toISOString()}
11
11
  **Language:** ${t.language||"typescript"}
@@ -64,7 +64,7 @@ ${e.gaps.length===0?"No significant gaps detected.":e.gaps.map(r=>`### ${r.file}
64
64
 
65
65
  **Generated:** ${new Date().toISOString()}
66
66
  **Scanner:** Agentic QE v3 Security
67
- **Execution:** ${Ur(e)}
67
+ **Execution:** ${Br(e)}
68
68
 
69
69
  ## Execution receipts
70
70
 
@@ -126,7 +126,7 @@ ${Object.entries(e.metrics).map(([a,c])=>`| ${a} | ${Number.isFinite(c)&&c>=0?c.
126
126
 
127
127
  ${e.recommendations.length===0?s:e.recommendations.map((a,c)=>`${c+1}. ${a}`).join(`
128
128
  `)}
129
- `}async ensureDirectories(e){let t=[this.resultsDir,N.join(this.resultsDir,"security"),N.join(this.resultsDir,"coverage"),N.join(this.resultsDir,"quality"),N.join(this.resultsDir,"tests"),N.join(this.resultsDir,"tests","generated")];for(let n of t)await G.mkdir(n,{recursive:!0})}formatTimestamp(e){return e.toISOString().replace(/[:.]/g,"-").slice(0,23)}uniqueSuffix(e){return`${this.sanitizeFilename(e).slice(-12)||"task"}-${zr(3).toString("hex")}`}async replaceFile(e,t,n){let r=`${e}.${process.pid}.${zr(4).toString("hex")}.tmp`;try{await G.writeFile(r,t,{flag:"wx"}),await G.rename(r,e)}catch(i){throw await G.rm(r,{force:!0}),i}return this.createFileEntry(e,n)}async writeNewFile(e,t,n){let r=N.dirname(e),i=N.basename(e),s=i.indexOf(".",1),a=s>0?i.slice(0,s):i,c=s>0?i.slice(s):"";for(let l=0;l<1e3;l++){let d=l===0?e:N.join(r,`${a}-${l}${c}`);try{return await G.writeFile(d,t,{flag:"wx"}),this.createFileEntry(d,n)}catch(u){if(u.code!=="EEXIST")throw u}}throw new Error(`ResultSaver: no free file name for ${e}`)}generatedTestFilename(e,t){let n=this.sanitizeFilename(e.name).slice(0,kl)||"test",r=mo("sha256").update(`${e.file??""}\0${e.name}`).digest("hex").slice(0,8);return`${n}-${r}${t}`}sanitizeFilename(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_").toLowerCase()}getTestExtension(e,t){let n=Ml[e.toLowerCase()];return n&&(n[t.toLowerCase()]||n.default)||".test.ts"}async createFileEntry(e,t){let n=await G.readFile(e),r=await G.stat(e),i=mo("sha256").update(n).digest("hex").slice(0,16);return{path:e,format:t,size:r.size,checksum:i}}extractSummary(e,t){let n=t;switch(e){case"scan-security":return{status:Ur(n),vulnerabilities:n.vulnerabilities,critical:n.critical,high:n.high};case"analyze-coverage":return{lineCoverage:n.lineCoverage,branchCoverage:n.branchCoverage};case"assess-quality":return{...typeof n.qualityScore=="number"&&n.qualityScore>=0&&n.evidenceStatus!=="insufficient-evidence"?{qualityScore:n.qualityScore}:{},passed:n.passed,...n.evidenceStatus!==void 0?{evidenceStatus:n.evidenceStatus}:{}};case"generate-tests":return{testsGenerated:n.testsGenerated,coverageEstimate:n.coverageEstimate};default:return{}}}updateIndex(e,t,n,r,i){let s=N.resolve(this.resultsDir,"index.json"),c=(bn.get(s)??Promise.resolve()).catch(()=>{}).then(()=>this.writeIndexEntry(s,e,t,n,r,i));bn.set(s,c);let l=()=>{bn.get(s)===c&&bn.delete(s)};return c.then(l,l),c}async writeIndexEntry(e,t,n,r,i,s){let a;try{let l=await G.readFile(e,"utf-8");a=I(l)}catch{a={version:"1.0",created:new Date().toISOString(),updated:new Date().toISOString(),results:[],trends:{}}}a.results.push({id:t,type:n,timestamp:r.toISOString(),files:i.map(l=>N.relative(this.resultsDir,l.path)),summary:s}),a.updated=new Date().toISOString(),a.results.length>100&&(a.results=a.results.slice(-100));let c=`${e}.${process.pid}.${zr(4).toString("hex")}.tmp`;await G.writeFile(c,JSON.stringify(a,null,2)),await G.rename(c,e)}},bn=new Map;function po(o){return new Br(o)}Tt();Zt();wl();pe();ee();var Xl=["think","thinking","reasoning","reasoning_scratchpad"],Yl=new RegExp(`<(${Xl.join("|")})(?:\\s[^>]*)?>[\\s\\S]*?</\\1\\s*>`,"gi");function Z(o){if(!o||typeof o!="string"||!o.includes("<"))return o;let e=o;for(let t=0;t<5;t++){let n=e.replace(Yl," ");if(n===e)break;e=n}return e===o?o:e.replace(/[ \t]{2,}/g," ").trim()}function Cn(o){if(typeof o=="string")return Z(o);if(Array.isArray(o))return o.map(e=>Cn(e));if(o!==null&&typeof o=="object"){let e={};for(let[t,n]of Object.entries(o))e[t]=Cn(n);return e}return o}var Jl={maxStepsPerTrajectory:100,autoEndTimeoutMs:1800*1e3,minQualityThreshold:.5,recentBufferSize:100},Sn=class{config;unifiedMemory=null;db=null;prepared=new Map;initialized=!1;activeTrajectories=new Map;recentTrajectories;stats={trajectoriesStarted:0,trajectoriesCompleted:0,trajectoriesAbandoned:0,totalStepsRecorded:0,averageQuality:0,totalQualitySum:0};constructor(e={}){this.config={...Jl,...e},this.recentTrajectories=new Be(this.config.recentBufferSize)}async initialize(){this.initialized||(this.unifiedMemory=X(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),this.ensureSchema(),this.prepareStatements(),await this.loadRecentTrajectories(),await this.cleanupOrphanedTrajectories(),this.initialized=!0,console.log("[TrajectoryTracker] Initialized"))}async cleanupOrphanedTrajectories(){let e=this.db;if(!(!e||!this.unifiedMemory))try{let t=await this.unifiedMemory.writeWhenUnlocked(()=>e.prepare(`
129
+ `}async ensureDirectories(e){let t=[this.resultsDir,O.join(this.resultsDir,"security"),O.join(this.resultsDir,"coverage"),O.join(this.resultsDir,"quality"),O.join(this.resultsDir,"tests"),O.join(this.resultsDir,"tests","generated")];for(let n of t)await j.mkdir(n,{recursive:!0})}formatTimestamp(e){return e.toISOString().replace(/[:.]/g,"-").slice(0,23)}uniqueSuffix(e){return`${this.sanitizeFilename(e).slice(-12)||"task"}-${Ur(3).toString("hex")}`}async replaceFile(e,t,n){let r=`${e}.${process.pid}.${Ur(4).toString("hex")}.tmp`;try{await j.writeFile(r,t,{flag:"wx"}),await j.rename(r,e)}catch(i){throw await j.rm(r,{force:!0}),i}return this.createFileEntry(e,n)}async writeNewFile(e,t,n){let r=O.dirname(e),i=O.basename(e),s=i.indexOf(".",1),a=s>0?i.slice(0,s):i,c=s>0?i.slice(s):"";for(let l=0;l<1e3;l++){let u=l===0?e:O.join(r,`${a}-${l}${c}`);try{return await j.writeFile(u,t,{flag:"wx"}),this.createFileEntry(u,n)}catch(d){if(d.code!=="EEXIST")throw d}}throw new Error(`ResultSaver: no free file name for ${e}`)}generatedTestFilename(e,t){let n=this.sanitizeFilename(e.name).slice(0,Pl)||"test",r=fo("sha256").update(`${e.file??""}\0${e.name}`).digest("hex").slice(0,8);return`${n}-${r}${t}`}sanitizeFilename(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_").toLowerCase()}getTestExtension(e,t){let n=xl[e.toLowerCase()];return n&&(n[t.toLowerCase()]||n.default)||".test.ts"}async createFileEntry(e,t){let n=await j.readFile(e),r=await j.stat(e),i=fo("sha256").update(n).digest("hex").slice(0,16);return{path:e,format:t,size:r.size,checksum:i}}extractSummary(e,t){let n=t;switch(e){case"scan-security":return{status:Br(n),vulnerabilities:n.vulnerabilities,critical:n.critical,high:n.high};case"analyze-coverage":return{lineCoverage:n.lineCoverage,branchCoverage:n.branchCoverage};case"assess-quality":return{...typeof n.qualityScore=="number"&&n.qualityScore>=0&&n.evidenceStatus!=="insufficient-evidence"?{qualityScore:n.qualityScore}:{},passed:n.passed,...n.evidenceStatus!==void 0?{evidenceStatus:n.evidenceStatus}:{}};case"generate-tests":return{testsGenerated:n.testsGenerated,coverageEstimate:n.coverageEstimate};default:return{}}}updateIndex(e,t,n,r,i){let s=O.resolve(this.resultsDir,"index.json"),c=(bn.get(s)??Promise.resolve()).catch(()=>{}).then(()=>this.writeIndexEntry(s,e,t,n,r,i));bn.set(s,c);let l=()=>{bn.get(s)===c&&bn.delete(s)};return c.then(l,l),c}async writeIndexEntry(e,t,n,r,i,s){let a;try{let l=await j.readFile(e,"utf-8");a=I(l)}catch{a={version:"1.0",created:new Date().toISOString(),updated:new Date().toISOString(),results:[],trends:{}}}a.results.push({id:t,type:n,timestamp:r.toISOString(),files:i.map(l=>O.relative(this.resultsDir,l.path)),summary:s}),a.updated=new Date().toISOString(),a.results.length>100&&(a.results=a.results.slice(-100));let c=`${e}.${process.pid}.${Ur(4).toString("hex")}.tmp`;await j.writeFile(c,JSON.stringify(a,null,2)),await j.rename(c,e)}},bn=new Map;function ho(o){return new Hr(o)}Et();Zt();Sl();ge();te();var Ql={maxStepsPerTrajectory:100,autoEndTimeoutMs:1800*1e3,minQualityThreshold:.5,recentBufferSize:100},Cn=class{config;unifiedMemory=null;db=null;prepared=new Map;initialized=!1;activeTrajectories=new Map;recentTrajectories;stats={trajectoriesStarted:0,trajectoriesCompleted:0,trajectoriesAbandoned:0,totalStepsRecorded:0,averageQuality:0,totalQualitySum:0};constructor(e={}){this.config={...Ql,...e},this.recentTrajectories=new He(this.config.recentBufferSize)}async initialize(){this.initialized||(this.unifiedMemory=Y(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),this.ensureSchema(),this.prepareStatements(),await this.loadRecentTrajectories(),await this.cleanupOrphanedTrajectories(),this.initialized=!0,console.log("[TrajectoryTracker] Initialized"))}async cleanupOrphanedTrajectories(){let e=this.db;if(!(!e||!this.unifiedMemory))try{let t=await this.unifiedMemory.writeWhenUnlocked(()=>e.prepare(`
130
130
  UPDATE qe_trajectories
131
131
  SET success = 0,
132
132
  ended_at = datetime('now'),
@@ -186,18 +186,9 @@ ${e.recommendations.length===0?s:e.recommendations.map((a,c)=>`${c+1}. ${a}`).jo
186
186
  WHERE domain = ? AND success = 1
187
187
  ORDER BY ended_at DESC
188
188
  LIMIT ?
189
- `))}async loadRecentTrajectories(){let e=this.prepared.get("getRecentTrajectories");if(!e)return;let t=e.all(this.config.recentBufferSize);for(let n of t){let r=await this.rowToTrajectory(n);r&&this.recentTrajectories.push(r)}console.log(`[TrajectoryTracker] Loaded ${t.length} recent trajectories`)}async startTrajectory(e,t={}){this.ensureInitialized(),e=Z(e);let n=U(),r=new Date;this.activeTrajectories.set(n,{id:n,task:e,agent:t.agent,domain:t.domain,steps:[],startedAt:r,context:t.context});let i=this.prepared.get("insertTrajectory");if(i){let s=()=>i.run(n,e,t.agent||null,t.domain||null,r.toISOString(),t.context?JSON.stringify(t.context):null);await(this.unifiedMemory?this.unifiedMemory.writeWhenUnlocked(s):s())}return this.stats.trajectoriesStarted++,setTimeout(()=>{this.activeTrajectories.has(n)&&(console.warn(`[TrajectoryTracker] Auto-ending abandoned trajectory: ${n}`),this.endTrajectory(n,!1,"Abandoned - timeout").catch(console.error),this.stats.trajectoriesAbandoned++)},this.config.autoEndTimeoutMs),n}async recordStep(e,t,n,r={}){this.ensureInitialized();let i=this.activeTrajectories.get(e);if(!i)throw new Error(`Trajectory not found or already ended: ${e}`);if(i.steps.length>=this.config.maxStepsPerTrajectory)throw new Error(`Maximum steps (${this.config.maxStepsPerTrajectory}) exceeded for trajectory`);let s=U(),a=r.quality??this.calculateStepQuality(n);t=Z(t),n={...n,data:n.data?Cn(n.data):n.data,error:n.error?Z(n.error):n.error};let c={id:s,action:t,result:n,quality:a,durationMs:r.durationMs??0,timestamp:new Date,context:r.context,tokensUsed:r.tokensUsed};i.steps.push(c);let l=this.prepared.get("insertStep");l&&l.run(s,e,i.steps.length-1,t,n.outcome,a,r.durationMs??0,r.tokensUsed??null,n.data?JSON.stringify(n.data):null,n.error??null,n.metrics?JSON.stringify(n.metrics):null,r.context?JSON.stringify(r.context):null),this.stats.totalStepsRecorded++,this.stats.totalQualitySum+=a,this.stats.averageQuality=this.stats.totalQualitySum/this.stats.totalStepsRecorded}async endTrajectory(e,t,n){this.ensureInitialized();let r=this.activeTrajectories.get(e);if(!r)throw new Error(`Trajectory not found or already ended: ${e}`);let i=new Date,s=this.calculateMetrics(r.steps),a;t&&s.averageQuality>=this.config.minQualityThreshold?a="success":t?a="partial":a="failure";let c={id:e,task:r.task,agent:r.agent,domain:r.domain,steps:r.steps,outcome:a,metrics:s,startedAt:r.startedAt,endedAt:i,feedback:n},l=this.prepared.get("updateTrajectory");if(l){let d=()=>l.run(i.toISOString(),t?1:0,JSON.stringify(r.steps),JSON.stringify({metrics:s,context:r.context}),null,n??null,null,e);await(this.unifiedMemory?this.unifiedMemory.writeWhenUnlocked(d):d())}return this.activeTrajectories.delete(e),this.recentTrajectories.push(c),this.stats.trajectoriesCompleted++,c}async getTrajectory(e){this.ensureInitialized();let t=this.activeTrajectories.get(e);if(t)return{id:t.id,task:t.task,agent:t.agent,domain:t.domain,steps:t.steps,outcome:"partial",metrics:this.calculateMetrics(t.steps),startedAt:t.startedAt};let n=this.prepared.get("getTrajectory");if(!n)return null;let r=n.get(e);return r?this.rowToTrajectory(r):null}async getSuccessfulTrajectories(e,t=10){this.ensureInitialized();let n=this.prepared.get("getTrajectoryByDomain");if(!n)return[];let r=n.all(e,t),i=[];for(let s of r){let a=await this.rowToTrajectory(s);a&&i.push(a)}return i}async findSimilarTrajectories(e,t=5){this.ensureInitialized();let n=e.toLowerCase().split(/\s+/).filter(s=>s.length>3);return this.recentTrajectories.toArray().map(s=>{let a=s.task.toLowerCase(),c=n.filter(l=>a.includes(l)).length;return{trajectory:s,score:c/n.length}}).filter(s=>s.score>.2).sort((s,a)=>a.score-s.score).slice(0,t).map(s=>s.trajectory)}getStats(){return{...this.stats,activeTrajectories:this.activeTrajectories.size,recentBufferSize:this.recentTrajectories.length}}async cleanup(e=30){if(this.ensureInitialized(),!this.db)return 0;let t=new Date;return t.setDate(t.getDate()-e),this.db.prepare(`
189
+ `))}async loadRecentTrajectories(){let e=this.prepared.get("getRecentTrajectories");if(!e)return;let t=e.all(this.config.recentBufferSize);for(let n of t){let r=await this.rowToTrajectory(n);r&&this.recentTrajectories.push(r)}console.log(`[TrajectoryTracker] Loaded ${t.length} recent trajectories`)}async startTrajectory(e,t={}){this.ensureInitialized(),e=ie(e);let n=U(),r=new Date;this.activeTrajectories.set(n,{id:n,task:e,agent:t.agent,domain:t.domain,steps:[],startedAt:r,context:t.context});let i=this.prepared.get("insertTrajectory");if(i){let s=()=>i.run(n,e,t.agent||null,t.domain||null,r.toISOString(),t.context?JSON.stringify(t.context):null);await(this.unifiedMemory?this.unifiedMemory.writeWhenUnlocked(s):s())}return this.stats.trajectoriesStarted++,setTimeout(()=>{this.activeTrajectories.has(n)&&(console.warn(`[TrajectoryTracker] Auto-ending abandoned trajectory: ${n}`),this.endTrajectory(n,!1,"Abandoned - timeout").catch(console.error),this.stats.trajectoriesAbandoned++)},this.config.autoEndTimeoutMs),n}async recordStep(e,t,n,r={}){this.ensureInitialized();let i=this.activeTrajectories.get(e);if(!i)throw new Error(`Trajectory not found or already ended: ${e}`);if(i.steps.length>=this.config.maxStepsPerTrajectory)throw new Error(`Maximum steps (${this.config.maxStepsPerTrajectory}) exceeded for trajectory`);let s=U(),a=r.quality??this.calculateStepQuality(n);t=ie(t),n={...n,data:n.data?Ss(n.data):n.data,error:n.error?ie(n.error):n.error};let c={id:s,action:t,result:n,quality:a,durationMs:r.durationMs??0,timestamp:new Date,context:r.context,tokensUsed:r.tokensUsed};i.steps.push(c);let l=this.prepared.get("insertStep");l&&l.run(s,e,i.steps.length-1,t,n.outcome,a,r.durationMs??0,r.tokensUsed??null,n.data?JSON.stringify(n.data):null,n.error??null,n.metrics?JSON.stringify(n.metrics):null,r.context?JSON.stringify(r.context):null),this.stats.totalStepsRecorded++,this.stats.totalQualitySum+=a,this.stats.averageQuality=this.stats.totalQualitySum/this.stats.totalStepsRecorded}async endTrajectory(e,t,n){this.ensureInitialized();let r=this.activeTrajectories.get(e);if(!r)throw new Error(`Trajectory not found or already ended: ${e}`);let i=new Date,s=this.calculateMetrics(r.steps),a;t&&s.averageQuality>=this.config.minQualityThreshold?a="success":t?a="partial":a="failure";let c={id:e,task:r.task,agent:r.agent,domain:r.domain,steps:r.steps,outcome:a,metrics:s,startedAt:r.startedAt,endedAt:i,feedback:n},l=this.prepared.get("updateTrajectory");if(l){let u=()=>l.run(i.toISOString(),t?1:0,JSON.stringify(r.steps),JSON.stringify({metrics:s,context:r.context}),null,n??null,null,e);await(this.unifiedMemory?this.unifiedMemory.writeWhenUnlocked(u):u())}return this.activeTrajectories.delete(e),this.recentTrajectories.push(c),this.stats.trajectoriesCompleted++,c}async getTrajectory(e){this.ensureInitialized();let t=this.activeTrajectories.get(e);if(t)return{id:t.id,task:t.task,agent:t.agent,domain:t.domain,steps:t.steps,outcome:"partial",metrics:this.calculateMetrics(t.steps),startedAt:t.startedAt};let n=this.prepared.get("getTrajectory");if(!n)return null;let r=n.get(e);return r?this.rowToTrajectory(r):null}async getSuccessfulTrajectories(e,t=10){this.ensureInitialized();let n=this.prepared.get("getTrajectoryByDomain");if(!n)return[];let r=n.all(e,t),i=[];for(let s of r){let a=await this.rowToTrajectory(s);a&&i.push(a)}return i}async findSimilarTrajectories(e,t=5){this.ensureInitialized();let n=e.toLowerCase().split(/\s+/).filter(s=>s.length>3);return this.recentTrajectories.toArray().map(s=>{let a=s.task.toLowerCase(),c=n.filter(l=>a.includes(l)).length;return{trajectory:s,score:c/n.length}}).filter(s=>s.score>.2).sort((s,a)=>a.score-s.score).slice(0,t).map(s=>s.trajectory)}getStats(){return{...this.stats,activeTrajectories:this.activeTrajectories.size,recentBufferSize:this.recentTrajectories.length}}async cleanup(e=30){if(this.ensureInitialized(),!this.db)return 0;let t=new Date;return t.setDate(t.getDate()-e),this.db.prepare(`
190
190
  DELETE FROM qe_trajectories WHERE ended_at < ?
191
- `).run(t.toISOString()).changes}async dispose(){this.activeTrajectories.clear(),this.recentTrajectories.clear(),this.prepared.clear(),this.db=null,this.unifiedMemory=null,this.initialized=!1,console.log("[TrajectoryTracker] Disposed")}ensureInitialized(){if(!this.initialized)throw new Error("TrajectoryTracker not initialized. Call initialize() first.")}calculateStepQuality(e){switch(e.outcome){case"success":return 1;case"partial":return .6;case"skipped":return .5;case"failure":return 0;default:return .5}}calculateMetrics(e){if(e.length===0)return{totalDurationMs:0,successfulSteps:0,failedSteps:0,averageQuality:0,totalTokensUsed:0,efficiencyScore:0};let t=0,n=0,r=0,i=0,s=0;for(let d of e)t+=d.durationMs,i+=d.quality,s+=d.tokensUsed??0,d.result.outcome==="success"?n++:d.result.outcome==="failure"&&r++;let a=i/e.length,l=n/e.length*a;return{totalDurationMs:t,successfulSteps:n,failedSteps:r,averageQuality:a,totalTokensUsed:s,efficiencyScore:l}}async rowToTrajectory(e){if(!e)return null;let t=this.prepared.get("getSteps"),n=[];if(t)n=t.all(e.id).map(a=>({id:a.id,action:a.action,result:{outcome:a.outcome,data:a.result_data?I(a.result_data):void 0,error:a.error_message??void 0,metrics:a.metrics_json?I(a.metrics_json):void 0},quality:a.quality,durationMs:a.duration_ms,timestamp:new Date(a.timestamp),context:a.context_json?I(a.context_json):void 0,tokensUsed:a.tokens_used??void 0}));else if(e.steps_json)try{n=I(e.steps_json)}catch{n=[]}let i=(e.metadata_json?I(e.metadata_json):{}).metrics??this.calculateMetrics(n);return{id:e.id,task:e.task,agent:e.agent??void 0,domain:e.domain,steps:n,outcome:e.success===1?"success":e.success===0?"failure":"partial",metrics:i,startedAt:new Date(e.started_at),endedAt:e.ended_at?new Date(e.ended_at):void 0,feedback:e.feedback??void 0,embedding:e.embedding?this.bufferToFloatArray(e.embedding):void 0,relatedPatternIds:e.related_patterns?I(e.related_patterns):void 0}}bufferToFloatArray(e){let t=e.length/4,n=[];for(let r=0;r<t;r++)n.push(e.readFloatLE(r*4));return n}};function Hr(o={}){return new Sn(o)}pe();El();ee();var ho="_system",yo=o=>`experience-space-verified-rowid:${o}`;function go(o){let e=`${o.domain??""}: ${o.task}`,t=new Set([e.slice(0,512),Z(e).slice(0,512)]);if(o.source==="experience-replay"){let n=I(o.steps_json||"[]");Array.isArray(n)&&t.add(`${o.task} ${o.agent??""} ${n.join(" ")}`)}return[...t]}function Zl(o){if(o.embedding.length<o.embedding_dimension*4)return null;let e=[];for(let t=0;t<o.embedding_dimension;t++)e.push(o.embedding.readFloatLE(t*4));return e}function fo(o,e){try{let t=o.prepare("SELECT value FROM kv_store WHERE namespace = ? AND key = ?").get(ho,yo(e));return t&&Number(t.value)||0}catch{return 0}}function eu(o,e,t){try{o.prepare("INSERT OR REPLACE INTO kv_store (key, namespace, value) VALUES (?, ?, ?)").run(yo(e),ho,String(t))}catch{}}async function vo(o,e){let t=e.write??(l=>l()),n={spaceId:null,checked:0,stamped:[],left:0},r=e.activeSpaceId(),i=l=>o.prepare(`
192
- SELECT rowid, id, task, agent, domain, steps_json, source, embedding, embedding_dimension
193
- FROM captured_experiences
194
- WHERE rowid > ? AND embedding IS NOT NULL AND embedding_space_id IS NULL
195
- AND embedding_dimension > 0 AND consolidated_into IS NULL
196
- ORDER BY rowid LIMIT ?
197
- `).all(l,e.limit??200),s=i(r?fo(o,r):0);if(s.length===0)return n;if(!r){if(await e.embed(go(s[0])[0]),r=e.activeSpaceId(),!r)return n;s=i(fo(o,r))}n.spaceId=r;let a=o.prepare(`
198
- UPDATE captured_experiences SET embedding_space_id = ?
199
- WHERE id = ? AND embedding_space_id IS NULL AND embedding = ?
200
- `),c=0;try{for(let l of s){let d=Zl(l),u=!1;if(d)for(let m of go(l)){let p=await e.embed(m);if(e.activeSpaceId()!==r)return n;if(p.length===d.length&&ve(d,p)>=Ss){u=!0;break}}u&&(await t(()=>a.run(r,l.id,l.embedding))).changes>0?n.stamped.push(l.id):n.left++,n.checked++,c=l.rowid}}finally{c>0&&await t(()=>eu(o,r,c))}return n}ee();Yt();var tu={minQualityThreshold:.6,maxExperiencesPerDomain:500,similarityThreshold:.7,topK:5,embedding:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0},autoPrune:!0,pruneThreshold:.3},Tn=class{config;unifiedMemory=null;db=null;prepared=new Map;initialized=!1;initializationPromise=null;embedderRecovery;embedderWorked=!1;hnswIndex;idToExperienceId=new Map;experienceIdToHnswId=new Map;nextHnswId=0;indexSpaceId=null;recentExperiences;reservoirBuffer=null;stats={experiencesStored:0,experiencesApplied:0,totalTokensSaved:0,avgSimilarityOnRetrieval:0,totalRetrievals:0};constructor(e={}){this.config={...tu,...e},this.recentExperiences=new Be(100),this.embedderRecovery=new As({retryIntervalMs:this.config.embedderRetryIntervalMs,probe:()=>xs(this.config.embedding),onRecovered:()=>console.log("[ExperienceReplay] Embedder available again: similar-experience guidance uses vectors")}),this.hnswIndex=new La({dimension:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"})}async initialize(){if(!this.initialized){if(this.initializationPromise)return this.initializationPromise;this.initializationPromise=this.initializeOnce();try{await this.initializationPromise}catch(e){throw this.initializationPromise=null,e}}}async initializeOnce(){this.unifiedMemory=X(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),this.ensureSchema(),this.prepareStatements(),await this.loadEmbeddingIndex(Ce()?.spaceId??null),(async()=>{try{if(!this.db)return;let e=this.db.prepare(`
191
+ `).run(t.toISOString()).changes}async dispose(){this.activeTrajectories.clear(),this.recentTrajectories.clear(),this.prepared.clear(),this.db=null,this.unifiedMemory=null,this.initialized=!1,console.log("[TrajectoryTracker] Disposed")}ensureInitialized(){if(!this.initialized)throw new Error("TrajectoryTracker not initialized. Call initialize() first.")}calculateStepQuality(e){switch(e.outcome){case"success":return 1;case"partial":return .6;case"skipped":return .5;case"failure":return 0;default:return .5}}calculateMetrics(e){if(e.length===0)return{totalDurationMs:0,successfulSteps:0,failedSteps:0,averageQuality:0,totalTokensUsed:0,efficiencyScore:0};let t=0,n=0,r=0,i=0,s=0;for(let u of e)t+=u.durationMs,i+=u.quality,s+=u.tokensUsed??0,u.result.outcome==="success"?n++:u.result.outcome==="failure"&&r++;let a=i/e.length,l=n/e.length*a;return{totalDurationMs:t,successfulSteps:n,failedSteps:r,averageQuality:a,totalTokensUsed:s,efficiencyScore:l}}async rowToTrajectory(e){if(!e)return null;let t=this.prepared.get("getSteps"),n=[];if(t)n=t.all(e.id).map(a=>({id:a.id,action:a.action,result:{outcome:a.outcome,data:a.result_data?I(a.result_data):void 0,error:a.error_message??void 0,metrics:a.metrics_json?I(a.metrics_json):void 0},quality:a.quality,durationMs:a.duration_ms,timestamp:new Date(a.timestamp),context:a.context_json?I(a.context_json):void 0,tokensUsed:a.tokens_used??void 0}));else if(e.steps_json)try{n=I(e.steps_json)}catch{n=[]}let i=(e.metadata_json?I(e.metadata_json):{}).metrics??this.calculateMetrics(n);return{id:e.id,task:e.task,agent:e.agent??void 0,domain:e.domain,steps:n,outcome:e.success===1?"success":e.success===0?"failure":"partial",metrics:i,startedAt:new Date(e.started_at),endedAt:e.ended_at?new Date(e.ended_at):void 0,feedback:e.feedback??void 0,embedding:e.embedding?this.bufferToFloatArray(e.embedding):void 0,relatedPatternIds:e.related_patterns?I(e.related_patterns):void 0}}bufferToFloatArray(e){let t=e.length/4,n=[];for(let r=0;r<t;r++)n.push(e.readFloatLE(r*4));return n}};function Vr(o={}){return new Cn(o)}ge();te();Yt();var Wl={minQualityThreshold:.6,maxExperiencesPerDomain:500,similarityThreshold:.7,topK:5,embedding:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0},autoPrune:!0,pruneThreshold:.3},Sn=class{config;unifiedMemory=null;db=null;prepared=new Map;initialized=!1;initializationPromise=null;embedderRecovery;embedderWorked=!1;hnswIndex;idToExperienceId=new Map;experienceIdToHnswId=new Map;nextHnswId=0;indexSpaceId=null;recentExperiences;reservoirBuffer=null;stats={experiencesStored:0,experiencesApplied:0,totalTokensSaved:0,avgSimilarityOnRetrieval:0,totalRetrievals:0};constructor(e={}){this.config={...Wl,...e},this.recentExperiences=new He(100),this.embedderRecovery=new ks({retryIntervalMs:this.config.embedderRetryIntervalMs,probe:()=>As(this.config.embedding),onRecovered:()=>console.log("[ExperienceReplay] Embedder available again: similar-experience guidance uses vectors")}),this.hnswIndex=new $a({dimension:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"})}async initialize(){if(!this.initialized){if(this.initializationPromise)return this.initializationPromise;this.initializationPromise=this.initializeOnce();try{await this.initializationPromise}catch(e){throw this.initializationPromise=null,e}}}async initializeOnce(){this.unifiedMemory=Y(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),this.ensureSchema(),this.prepareStatements(),await this.loadEmbeddingIndex(Ce()?.spaceId??null),(async()=>{try{if(!this.db)return;let e=this.db.prepare(`
201
192
  SELECT id, domain, task FROM captured_experiences
202
193
  WHERE embedding IS NULL AND consolidated_into IS NULL
203
194
  LIMIT 200
@@ -205,11 +196,11 @@ ${e.recommendations.length===0?s:e.recommendations.map((a,c)=>`${c+1}. ${a}`).jo
205
196
  UPDATE captured_experiences
206
197
  SET embedding = ?, embedding_dimension = ?, embedding_space_id = ?
207
198
  WHERE id = ?
208
- `),n=0;for(let r of e){let i=Z(`${r.domain??""}: ${r.task}`).slice(0,512),s=await Ue(i),a=Ce()?.spaceId;if(!a)break;let c=Buffer.from(new Float32Array(s).buffer);await this.unifiedMemory.writeWhenUnlocked(()=>t.run(c,s.length,a,r.id)),this.indexExperience(r.id,s,a),n++}console.log(`[ExperienceReplay] Backfilled ${n} captured_experiences embeddings`)}catch(e){console.warn("[ExperienceReplay] Embedding backfill failed:",e instanceof Error?e.message:e)}})(),(async()=>{try{if(!this.db)return;let e=await vo(this.db,{embed:t=>Ue(t,this.config.embedding),activeSpaceId:()=>Ce()?.spaceId,write:t=>this.unifiedMemory.writeWhenUnlocked(t)});if(e.checked===0)return;e.stamped.length>0&&e.spaceId&&await this.loadEmbeddingIndex(e.spaceId),console.log(`[ExperienceReplay] Checked ${e.checked} experience vectors without an embedding space: ${e.stamped.length} match the active embedder, ${e.left} left uncompared`)}catch(e){console.warn("[ExperienceReplay] Embedding-space check failed:",e instanceof Error?e.message:e)}})(),(async()=>{try{if(!this.db||!this.db.prepare("PRAGMA table_info(qe_trajectories)").all().some(i=>i.name==="embedding"))return;let t=this.db.prepare(`
199
+ `),n=0;for(let r of e){let i=ie(`${r.domain??""}: ${r.task}`).slice(0,512),s=await Be(i),a=Ce()?.spaceId;if(!a)break;let c=Buffer.from(new Float32Array(s).buffer);await this.unifiedMemory.writeWhenUnlocked(()=>t.run(c,s.length,a,r.id)),this.indexExperience(r.id,s,a),n++}console.log(`[ExperienceReplay] Backfilled ${n} captured_experiences embeddings`)}catch(e){console.warn("[ExperienceReplay] Embedding backfill failed:",e instanceof Error?e.message:e)}})(),(async()=>{try{if(!this.db)return;let e=await Ts(this.db,{embed:t=>Be(t,this.config.embedding),activeSpaceId:()=>Ce()?.spaceId,write:t=>this.unifiedMemory.writeWhenUnlocked(t)});if(e.checked===0)return;e.stamped.length>0&&e.spaceId&&await this.loadEmbeddingIndex(e.spaceId),console.log(`[ExperienceReplay] Checked ${e.checked} experience vectors without an embedding space: ${e.stamped.length} match the active embedder, ${e.left} left uncompared`)}catch(e){console.warn("[ExperienceReplay] Embedding-space check failed:",e instanceof Error?e.message:e)}})(),(async()=>{try{if(!this.db||!this.db.prepare("PRAGMA table_info(qe_trajectories)").all().some(i=>i.name==="embedding"))return;let t=this.db.prepare(`
209
200
  SELECT id, domain, task FROM qe_trajectories
210
201
  WHERE embedding IS NULL AND ended_at IS NOT NULL
211
202
  LIMIT 200
212
- `).all();if(t.length===0)return;let n=this.db.prepare("UPDATE qe_trajectories SET embedding = ? WHERE id = ?"),r=0;for(let i of t){let s=Z(`${i.domain??""}: ${i.task}`).slice(0,512),a=await Ue(s);await this.unifiedMemory.writeWhenUnlocked(()=>n.run(Buffer.from(new Float32Array(a).buffer),i.id)),r++}console.log(`[ExperienceReplay] Backfilled ${r} qe_trajectories embeddings`)}catch(e){console.warn("[ExperienceReplay] Trajectory embedding backfill failed:",e instanceof Error?e.message:e)}})(),Ge().useReservoirReplay&&(this.reservoirBuffer=new ba({capacity:1e4}),console.log("[ExperienceReplay] Reservoir replay buffer enabled")),this.initialized=!0,console.log("[ExperienceReplay] Initialized")}ensureSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
203
+ `).all();if(t.length===0)return;let n=this.db.prepare("UPDATE qe_trajectories SET embedding = ? WHERE id = ?"),r=0;for(let i of t){let s=ie(`${i.domain??""}: ${i.task}`).slice(0,512),a=await Be(s);await this.unifiedMemory.writeWhenUnlocked(()=>n.run(Buffer.from(new Float32Array(a).buffer),i.id)),r++}console.log(`[ExperienceReplay] Backfilled ${r} qe_trajectories embeddings`)}catch(e){console.warn("[ExperienceReplay] Trajectory embedding backfill failed:",e instanceof Error?e.message:e)}})(),Ge().useReservoirReplay&&(this.reservoirBuffer=new Ca({capacity:1e4}),console.log("[ExperienceReplay] Reservoir replay buffer enabled")),this.initialized=!0,console.log("[ExperienceReplay] Initialized")}ensureSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
213
204
  CREATE TABLE IF NOT EXISTS captured_experiences (
214
205
  id TEXT PRIMARY KEY,
215
206
  task TEXT NOT NULL,
@@ -285,7 +276,7 @@ ${e.recommendations.length===0?s:e.recommendations.map((a,c)=>`${c+1}. ${a}`).jo
285
276
  VALUES (?, ?, ?, ?, ?, ?)
286
277
  `)),this.prepared.set("countByDomain",this.db.prepare(`
287
278
  SELECT domain, COUNT(*) as count FROM captured_experiences WHERE consolidated_into IS NULL GROUP BY domain
288
- `))}async loadEmbeddingIndex(e){let t=this.prepared.get("getAllEmbeddings");if(!t)return;let n=e?t.all(e):[];this.idToExperienceId.clear(),this.experienceIdToHnswId.clear(),this.hnswIndex.clearIndex("experiences"),this.nextHnswId=0,this.indexSpaceId=e;for(let r of n)if(r.embedding&&r.embedding_dimension){let i=this.bufferToFloatArray(r.embedding,r.embedding_dimension),s=this.nextHnswId++,a={vector:i,dimension:384,namespace:"experiences",text:r.id,timestamp:Date.now(),quantization:"none",metadata:{}};this.hnswIndex.addEmbedding(a,s),this.idToExperienceId.set(s,r.id),this.experienceIdToHnswId.set(r.id,s)}console.log(`[ExperienceReplay] Loaded ${this.idToExperienceId.size} embeddings into HNSW index`)}async storeExperience(e,t,n=[]){if(this.ensureInitialized(),e.metrics.efficiencyScore<this.config.minQualityThreshold)return console.log(`[ExperienceReplay] Trajectory quality too low: ${e.metrics.efficiencyScore}`),null;let r=Z(e.task);t=Z(t);let i=e.steps.filter(p=>p.result.outcome==="success").map(p=>Z(p.action)),s=`${r} ${t} ${i.join(" ")}`,a=await this.embedOrNull(s)??void 0,c=a?Ce()?.spaceId:void 0,l=U(),d=e.domain||"test-generation",u={id:l,trajectoryId:e.id,task:r,domain:d,strategy:t,keyActions:i,qualityScore:e.metrics.efficiencyScore,applicationCount:0,successRate:1,avgTokenSavings:0,embedding:c?a:void 0,embeddingSpaceId:c,createdAt:new Date,originalMetrics:e.metrics,tags:n},m=this.prepared.get("insertExperience");if(m){let p=u.embedding?this.floatArrayToBuffer(u.embedding):null,g=()=>m.run(l,r,t,d,e.metrics.efficiencyScore,JSON.stringify(i),JSON.stringify(e.metrics),p,u.embedding?.length??null,c??null,JSON.stringify(n));await(this.unifiedMemory?this.unifiedMemory.writeWhenUnlocked(g):g())}return u.embedding&&c&&this.indexExperience(l,u.embedding,c),this.recentExperiences.push(u),this.reservoirBuffer&&this.reservoirBuffer.admit(u.id,u,u.qualityScore),this.stats.experiencesStored++,this.config.autoPrune&&await this.autoConsolidate(d),u}async embedOrNull(e){if(!this.embedderRecovery.isAvailable())return null;try{let t=await Ue(e,this.config.embedding);return this.embedderWorked=!0,t}catch(t){let n=t instanceof Error?t.message:String(t),r=this.embedderWorked?`Embedder failed at runtime: ${n}`:n;return this.embedderRecovery.markUnavailable(r)&&console.warn(this.embedderWorked?"[ExperienceReplay] Embedder failed; experiences are stored without vectors and similar-experience guidance is unavailable until it recovers:":"[ExperienceReplay] No embedding runtime; experiences are stored without vectors and similar-experience guidance is unavailable:",n),null}}getEmbedderStatus(){let e=this.embedderRecovery.unavailableReason;return e===null?{mode:"vector"}:{mode:"unavailable",reason:e}}async getGuidance(e,t){this.ensureInitialized();let n=await this.embedOrNull(Z(e)),r=Ce()?.spaceId;if(!n||!r)return null;let i=await this.findSimilarExperiences(e,t);if(this.reservoirBuffer&&this.reservoirBuffer.size()>0){let f=this.reservoirBuffer.sample(Math.max(2,Math.floor(this.config.topK/2)),.6);for(let h of f){let v=h.data;if(i.some(C=>C.experience.id===v.id)||t&&v.domain!==t||!v.embedding||v.embeddingSpaceId!==r||v.embedding.length!==n.length)continue;let y=ve(n,v.embedding);y<this.config.similarityThreshold||i.push({experience:v,similarity:y})}}if(i.length===0)return null;this.stats.totalRetrievals++;let s=i.reduce((f,h)=>f+h.similarity,0)/i.length;this.stats.avgSimilarityOnRetrieval=(this.stats.avgSimilarityOnRetrieval*(this.stats.totalRetrievals-1)+s)/this.stats.totalRetrievals;let a=i.map(f=>({...f,weight:f.similarity*f.experience.qualityScore}));a.sort((f,h)=>h.weight-f.weight);let l=a[0].experience.strategy,d=new Map;for(let f of a)for(let h of f.experience.keyActions)d.set(h,(d.get(h)||0)+f.weight);let u=Array.from(d.entries()).sort((f,h)=>h[1]-f[1]).slice(0,5).map(([f])=>f),m=[],p=a.reduce((f,h)=>f+h.weight,0)/a.length,g=a.reduce((f,h)=>f+h.experience.avgTokenSavings*h.similarity,0)/a.length;return{recommendedStrategy:l,suggestedActions:u,pitfallsToAvoid:m,confidence:Math.min(p,1),sourceExperiences:a.slice(0,3).map(f=>({id:f.experience.id,similarity:f.similarity,qualityScore:f.experience.qualityScore})),estimatedTokenSavings:g}}async findSimilarExperiences(e,t,n){this.ensureInitialized();let r=n??this.config.topK,i=Ce()?.spaceId??null;if(this.idToExperienceId.size===0&&i!==null&&i===this.indexSpaceId)return[];e=Z(e);let s=await this.embedOrNull(e);if(!s)return[];let a=Ce()?.spaceId??null;if(!a)return[];if(a!==this.indexSpaceId&&await this.loadEmbeddingIndex(a),this.idToExperienceId.size===0)return[];let c={vector:s,dimension:384,namespace:"experiences",text:e,timestamp:Date.now(),quantization:"none",metadata:{}},l=t?r*4:r*2,d=this.hnswIndex.search(c,{limit:l,namespace:"experiences"}),u=[],m=this.prepared.get("getExperience");for(let{id:p,distance:g}of d){let f=1-g;if(f<this.config.similarityThreshold)continue;let h=this.idToExperienceId.get(p);if(h&&m){let v=m.get(h);if(v){if(t&&v.domain!==t)continue;let y=this.rowToExperience(v);if(y&&(u.push({experience:y,similarity:f}),u.length>=r))break}}}return u}async recordApplication(e,t,n,r=0,i){this.ensureInitialized();let s=this.prepared.get("updateApplication");s&&s.run(r,e);let a=this.prepared.get("insertApplication");a&&a.run(U(),e,t,n?1:0,r,i??null),this.stats.experiencesApplied++,this.stats.totalTokensSaved+=r}async getExperience(e){this.ensureInitialized();let t=this.prepared.get("getExperience");if(!t)return null;let n=t.get(e);return n?this.rowToExperience(n):null}async getExperiencesByDomain(e,t=10){this.ensureInitialized();let n=this.prepared.get("getExperiencesByDomain");return n?n.all(e,t).map(i=>this.rowToExperience(i)).filter(i=>i!==null):[]}async autoConsolidate(e){if(!this.db)return 0;let t=this.prepared.get("countByDomain");if(!t)return 0;let r=t.all().find(i=>i.domain===e)?.count??0;if(r>400)try{let i=new qa;await i.initialize(this.db);let s=await i.consolidateDomain(e,r);return s.merged>0&&await this.loadEmbeddingIndex(this.indexSpaceId),console.log(`[ExperienceReplay] Auto-consolidated ${e}: ${s.merged} merged, ${s.archived} archived`),s.merged+s.archived}catch(i){console.warn("[ExperienceReplay] Auto-consolidation failed, skipping:",i)}return 0}async recordReuse(e,t){if(this.ensureInitialized(),!this.db)return;let n=t?"reuse_success_count":"reuse_failure_count";try{this.db.prepare(`UPDATE captured_experiences SET ${n} = ${n} + 1 WHERE id = ?`).run(e)}catch{}}getStats(){return{...this.stats,embeddingIndexSize:this.idToExperienceId.size,hnswIndexSize:this.hnswIndex.getSize("experiences"),recentBufferSize:this.recentExperiences.length}}getReservoirStats(){if(!this.reservoirBuffer)return null;let e=this.reservoirBuffer.getStats();return{size:e.size,totalAdmitted:e.totalAdmitted,totalRejected:e.totalRejected,tierCounts:e.tierCounts}}async dispose(){this.hnswIndex.clearIndex("experiences"),this.idToExperienceId.clear(),this.experienceIdToHnswId.clear(),this.recentExperiences.clear(),this.prepared.clear(),this.db=null,this.unifiedMemory=null,this.initialized=!1,console.log("[ExperienceReplay] Disposed")}ensureInitialized(){if(!this.initialized)throw new Error("ExperienceReplay not initialized. Call initialize() first.")}rowToExperience(e){return e?{id:e.id,trajectoryId:e.id,task:e.task,domain:e.domain,strategy:e.agent,keyActions:I(e.steps_json||"[]"),qualityScore:e.quality,applicationCount:e.application_count??0,successRate:e.success?1:0,avgTokenSavings:e.avg_token_savings??0,embedding:e.embedding&&e.embedding_dimension?this.bufferToFloatArray(e.embedding,e.embedding_dimension):void 0,embeddingSpaceId:e.embedding_space_id??void 0,createdAt:new Date(e.started_at),lastAppliedAt:e.last_applied_at?new Date(e.last_applied_at):void 0,originalMetrics:I(e.routing_json||"{}"),tags:I(e.tags||"[]")}:null}indexExperience(e,t,n){if(n!==this.indexSpaceId){this.loadEmbeddingIndex(n);return}let r=this.nextHnswId++,i={vector:t,dimension:384,namespace:"experiences",text:e,timestamp:Date.now(),quantization:"none",metadata:{}};this.hnswIndex.addEmbedding(i,r),this.idToExperienceId.set(r,e),this.experienceIdToHnswId.set(e,r)}floatArrayToBuffer(e){let t=Buffer.alloc(e.length*4);for(let n=0;n<e.length;n++)t.writeFloatLE(e[n],n*4);return t}bufferToFloatArray(e,t){let n=[];for(let r=0;r<t;r++)n.push(e.readFloatLE(r*4));return n}};function Vr(o={}){return new Tn(o)}pe();ee();var nu={driftThreshold:.3,mergeSimilarityThreshold:.85,minQualityForRetention:.3,obsoleteDaysThreshold:60,maxPatternsPerDomain:200,embedding:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0},historyBufferSize:500},En=class{config;unifiedMemory=null;db=null;prepared=new Map;initialized=!1;embeddingCache=new Map;recentEvents;stats={versionsTracked:0,driftDetections:0,significantDrifts:0,patternsMerged:0,patternsPruned:0,consolidationRuns:0};constructor(e={}){this.config={...nu,...e},this.recentEvents=new Be(this.config.historyBufferSize)}async initialize(){this.initialized||(this.unifiedMemory=X(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),this.ensureSchema(),this.prepareStatements(),await this.loadEmbeddingCache(),this.initialized=!0,console.log("[PatternEvolution] Initialized"))}ensureSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
279
+ `))}async loadEmbeddingIndex(e){let t=this.prepared.get("getAllEmbeddings");if(!t)return;let n=e?t.all(e):[];this.idToExperienceId.clear(),this.experienceIdToHnswId.clear(),this.hnswIndex.clearIndex("experiences"),this.nextHnswId=0,this.indexSpaceId=e;for(let r of n)if(r.embedding&&r.embedding_dimension){let i=this.bufferToFloatArray(r.embedding,r.embedding_dimension),s=this.nextHnswId++,a={vector:i,dimension:384,namespace:"experiences",text:r.id,timestamp:Date.now(),quantization:"none",metadata:{}};this.hnswIndex.addEmbedding(a,s),this.idToExperienceId.set(s,r.id),this.experienceIdToHnswId.set(r.id,s)}console.log(`[ExperienceReplay] Loaded ${this.idToExperienceId.size} embeddings into HNSW index`)}async storeExperience(e,t,n=[]){if(this.ensureInitialized(),e.metrics.efficiencyScore<this.config.minQualityThreshold)return console.log(`[ExperienceReplay] Trajectory quality too low: ${e.metrics.efficiencyScore}`),null;let r=ie(e.task);t=ie(t);let i=e.steps.filter(p=>p.result.outcome==="success").map(p=>ie(p.action)),s=`${r} ${t} ${i.join(" ")}`,a=await this.embedOrNull(s)??void 0,c=a?Ce()?.spaceId:void 0,l=U(),u=e.domain||"test-generation",d={id:l,trajectoryId:e.id,task:r,domain:u,strategy:t,keyActions:i,qualityScore:e.metrics.efficiencyScore,applicationCount:0,successRate:1,avgTokenSavings:0,embedding:c?a:void 0,embeddingSpaceId:c,createdAt:new Date,originalMetrics:e.metrics,tags:n},m=this.prepared.get("insertExperience");if(m){let p=d.embedding?this.floatArrayToBuffer(d.embedding):null,f=()=>m.run(l,r,t,u,e.metrics.efficiencyScore,JSON.stringify(i),JSON.stringify(e.metrics),p,d.embedding?.length??null,c??null,JSON.stringify(n));await(this.unifiedMemory?this.unifiedMemory.writeWhenUnlocked(f):f())}return d.embedding&&c&&this.indexExperience(l,d.embedding,c),this.recentExperiences.push(d),this.reservoirBuffer&&this.reservoirBuffer.admit(d.id,d,d.qualityScore),this.stats.experiencesStored++,this.config.autoPrune&&await this.autoConsolidate(u),d}async embedOrNull(e){if(!this.embedderRecovery.isAvailable())return null;try{let t=await Be(e,this.config.embedding);return this.embedderWorked=!0,t}catch(t){let n=t instanceof Error?t.message:String(t),r=this.embedderWorked?`Embedder failed at runtime: ${n}`:n;return this.embedderRecovery.markUnavailable(r)&&console.warn(this.embedderWorked?"[ExperienceReplay] Embedder failed; experiences are stored without vectors and similar-experience guidance is unavailable until it recovers:":"[ExperienceReplay] No embedding runtime; experiences are stored without vectors and similar-experience guidance is unavailable:",n),null}}getEmbedderStatus(){let e=this.embedderRecovery.unavailableReason;return e===null?{mode:"vector"}:{mode:"unavailable",reason:e}}async getGuidance(e,t){this.ensureInitialized();let n=await this.embedOrNull(ie(e)),r=Ce()?.spaceId;if(!n||!r)return null;let i=await this.findSimilarExperiences(e,t);if(this.reservoirBuffer&&this.reservoirBuffer.size()>0){let g=this.reservoirBuffer.sample(Math.max(2,Math.floor(this.config.topK/2)),.6);for(let h of g){let y=h.data;if(i.some(b=>b.experience.id===y.id)||t&&y.domain!==t||!y.embedding||y.embeddingSpaceId!==r||y.embedding.length!==n.length)continue;let v=Ue(n,y.embedding);v<this.config.similarityThreshold||i.push({experience:y,similarity:v})}}if(i.length===0)return null;this.stats.totalRetrievals++;let s=i.reduce((g,h)=>g+h.similarity,0)/i.length;this.stats.avgSimilarityOnRetrieval=(this.stats.avgSimilarityOnRetrieval*(this.stats.totalRetrievals-1)+s)/this.stats.totalRetrievals;let a=i.map(g=>({...g,weight:g.similarity*g.experience.qualityScore}));a.sort((g,h)=>h.weight-g.weight);let l=a[0].experience.strategy,u=new Map;for(let g of a)for(let h of g.experience.keyActions)u.set(h,(u.get(h)||0)+g.weight);let d=Array.from(u.entries()).sort((g,h)=>h[1]-g[1]).slice(0,5).map(([g])=>g),m=[],p=a.reduce((g,h)=>g+h.weight,0)/a.length,f=a.reduce((g,h)=>g+h.experience.avgTokenSavings*h.similarity,0)/a.length;return{recommendedStrategy:l,suggestedActions:d,pitfallsToAvoid:m,confidence:Math.min(p,1),sourceExperiences:a.slice(0,3).map(g=>({id:g.experience.id,similarity:g.similarity,qualityScore:g.experience.qualityScore})),estimatedTokenSavings:f}}async findSimilarExperiences(e,t,n){this.ensureInitialized();let r=n??this.config.topK,i=Ce()?.spaceId??null;if(this.idToExperienceId.size===0&&i!==null&&i===this.indexSpaceId)return[];e=ie(e);let s=await this.embedOrNull(e);if(!s)return[];let a=Ce()?.spaceId??null;if(!a)return[];if(a!==this.indexSpaceId&&await this.loadEmbeddingIndex(a),this.idToExperienceId.size===0)return[];let c={vector:s,dimension:384,namespace:"experiences",text:e,timestamp:Date.now(),quantization:"none",metadata:{}},l=t?r*4:r*2,u=this.hnswIndex.search(c,{limit:l,namespace:"experiences"}),d=[],m=this.prepared.get("getExperience");for(let{id:p,distance:f}of u){let g=1-f;if(g<this.config.similarityThreshold)continue;let h=this.idToExperienceId.get(p);if(h&&m){let y=m.get(h);if(y){if(t&&y.domain!==t)continue;let v=this.rowToExperience(y);if(v&&(d.push({experience:v,similarity:g}),d.length>=r))break}}}return d}async recordApplication(e,t,n,r=0,i){this.ensureInitialized();let s=this.prepared.get("updateApplication");s&&s.run(r,e);let a=this.prepared.get("insertApplication");a&&a.run(U(),e,t,n?1:0,r,i??null),this.stats.experiencesApplied++,this.stats.totalTokensSaved+=r}async getExperience(e){this.ensureInitialized();let t=this.prepared.get("getExperience");if(!t)return null;let n=t.get(e);return n?this.rowToExperience(n):null}async getExperiencesByDomain(e,t=10){this.ensureInitialized();let n=this.prepared.get("getExperiencesByDomain");return n?n.all(e,t).map(i=>this.rowToExperience(i)).filter(i=>i!==null):[]}async autoConsolidate(e){if(!this.db)return 0;let t=this.prepared.get("countByDomain");if(!t)return 0;let r=t.all().find(i=>i.domain===e)?.count??0;if(r>400)try{let i=new Ga;await i.initialize(this.db);let s=await i.consolidateDomain(e,r);return s.merged>0&&await this.loadEmbeddingIndex(this.indexSpaceId),console.log(`[ExperienceReplay] Auto-consolidated ${e}: ${s.merged} merged, ${s.archived} archived`),s.merged+s.archived}catch(i){console.warn("[ExperienceReplay] Auto-consolidation failed, skipping:",i)}return 0}async recordReuse(e,t){if(this.ensureInitialized(),!this.db)return;let n=t?"reuse_success_count":"reuse_failure_count";try{this.db.prepare(`UPDATE captured_experiences SET ${n} = ${n} + 1 WHERE id = ?`).run(e)}catch{}}getStats(){return{...this.stats,embeddingIndexSize:this.idToExperienceId.size,hnswIndexSize:this.hnswIndex.getSize("experiences"),recentBufferSize:this.recentExperiences.length}}getReservoirStats(){if(!this.reservoirBuffer)return null;let e=this.reservoirBuffer.getStats();return{size:e.size,totalAdmitted:e.totalAdmitted,totalRejected:e.totalRejected,tierCounts:e.tierCounts}}async dispose(){this.hnswIndex.clearIndex("experiences"),this.idToExperienceId.clear(),this.experienceIdToHnswId.clear(),this.recentExperiences.clear(),this.prepared.clear(),this.db=null,this.unifiedMemory=null,this.initialized=!1,console.log("[ExperienceReplay] Disposed")}ensureInitialized(){if(!this.initialized)throw new Error("ExperienceReplay not initialized. Call initialize() first.")}rowToExperience(e){return e?{id:e.id,trajectoryId:e.id,task:e.task,domain:e.domain,strategy:e.agent,keyActions:I(e.steps_json||"[]"),qualityScore:e.quality,applicationCount:e.application_count??0,successRate:e.success?1:0,avgTokenSavings:e.avg_token_savings??0,embedding:e.embedding&&e.embedding_dimension?this.bufferToFloatArray(e.embedding,e.embedding_dimension):void 0,embeddingSpaceId:e.embedding_space_id??void 0,createdAt:new Date(e.started_at),lastAppliedAt:e.last_applied_at?new Date(e.last_applied_at):void 0,originalMetrics:I(e.routing_json||"{}"),tags:I(e.tags||"[]")}:null}indexExperience(e,t,n){if(n!==this.indexSpaceId){this.loadEmbeddingIndex(n);return}let r=this.nextHnswId++,i={vector:t,dimension:384,namespace:"experiences",text:e,timestamp:Date.now(),quantization:"none",metadata:{}};this.hnswIndex.addEmbedding(i,r),this.idToExperienceId.set(r,e),this.experienceIdToHnswId.set(e,r)}floatArrayToBuffer(e){let t=Buffer.alloc(e.length*4);for(let n=0;n<e.length;n++)t.writeFloatLE(e[n],n*4);return t}bufferToFloatArray(e,t){let n=[];for(let r=0;r<t;r++)n.push(e.readFloatLE(r*4));return n}};function Qr(o={}){return new Sn(o)}ge();te();var Kl={driftThreshold:.3,mergeSimilarityThreshold:.85,minQualityForRetention:.3,obsoleteDaysThreshold:60,maxPatternsPerDomain:200,embedding:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0},historyBufferSize:500},Tn=class{config;unifiedMemory=null;db=null;prepared=new Map;initialized=!1;embeddingCache=new Map;recentEvents;stats={versionsTracked:0,driftDetections:0,significantDrifts:0,patternsMerged:0,patternsPruned:0,consolidationRuns:0};constructor(e={}){this.config={...Kl,...e},this.recentEvents=new He(this.config.historyBufferSize)}async initialize(){this.initialized||(this.unifiedMemory=Y(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),this.ensureSchema(),this.prepareStatements(),await this.loadEmbeddingCache(),this.initialized=!0,console.log("[PatternEvolution] Initialized"))}ensureSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
289
280
  CREATE TABLE IF NOT EXISTS pattern_versions (
290
281
  id TEXT PRIMARY KEY,
291
282
  pattern_id TEXT NOT NULL,
@@ -357,7 +348,7 @@ ${e.recommendations.length===0?s:e.recommendations.map((a,c)=>`${c+1}. ${a}`).jo
357
348
  FROM qe_patterns
358
349
  WHERE qe_domain = ? AND quality_score < ?
359
350
  ORDER BY quality_score ASC
360
- `))}async loadEmbeddingCache(){let e=this.prepared.get("getAllPatternEmbeddings");if(!e)return;let t=e.all();this.embeddingCache.clear();for(let n of t){let r=this.bufferToFloatArray(n.embedding,n.dimension);this.embeddingCache.set(n.pattern_id,r)}console.log(`[PatternEvolution] Loaded ${this.embeddingCache.size} pattern embeddings`)}async trackVersion(e,t,n=[],r="manual"){this.ensureInitialized();let i=U(),s=this.floatArrayToBuffer(t),a=await this.write(()=>{let u=(this.prepared.get("getVersionCount")?.get(e)?.count??0)+1,p=this.prepared.get("getPattern")?.get(e),g={id:i,patternId:e,version:u,embedding:t,changes:n,qualityScore:p?.quality_score??.5,successRate:p?.success_rate??.5,timestamp:new Date,trigger:r},f=this.prepared.get("insertVersion");return f&&f.run(i,e,u,s,t.length,JSON.stringify(n),g.qualityScore,g.successRate,r),g}),c=a.version;return this.embeddingCache.set(e,t),await this.recordEvent(e,"updated",{version:c,changes:n,trigger:r}),this.stats.versionsTracked++,a}async detectDrift(e){this.ensureInitialized(),this.stats.driftDetections++;let t=this.prepared.get("getVersionHistory");if(!t)return null;let n=t.all(e,10);if(n.length<2)return null;let r=n[0],i=n[n.length-1],s=this.bufferToFloatArray(r.embedding,r.embedding_dimension),a=this.bufferToFloatArray(i.embedding,i.embedding_dimension),l=1-ve(s,a),d=l>this.config.driftThreshold;d&&this.stats.significantDrifts++;let u,m;return l<.1?(u="keep",m="Pattern is stable with minimal drift"):l<this.config.driftThreshold?(u="keep",m="Drift is within acceptable range"):l<.6?(u="update",m="Moderate drift detected - consider versioning"):l<.8?(u="split",m="Significant drift - pattern may represent multiple concepts"):(u="archive",m="Severe drift - pattern has fundamentally changed"),{patternId:e,currentEmbedding:s,originalEmbedding:a,driftScore:l,hasSignificantDrift:d,recommendation:u,reason:m}}async findMergeCandidates(e){this.ensureInitialized();let t=this.prepared.get("getPatternEmbeddings");if(!t)return[];let n=t.all(e),r=[],i=this.prepared.get("getPattern");for(let s=0;s<n.length;s++)for(let a=s+1;a<n.length;a++){let c=this.bufferToFloatArray(n[s].embedding,n[s].dimension),l=this.bufferToFloatArray(n[a].embedding,n[a].dimension),d=ve(c,l);if(d>=this.config.mergeSimilarityThreshold){let u=i?.get(n[s].pattern_id),m=i?.get(n[a].pattern_id),p=((u?.quality_score??0)+(m?.quality_score??0))/2,g=d*p;r.push({patternId1:n[s].pattern_id,patternId2:n[a].pattern_id,similarity:d,mergeBenefit:g,suggestedName:`${u?.name??"Pattern"} + ${m?.name??"Pattern"}`})}}return r.sort((s,a)=>a.mergeBenefit-s.mergeBenefit)}async findPruneCandidates(e){this.ensureInitialized();let t=[],n=this.prepared.get("getPatternsForPruning");if(n){let i=n.all(e,this.config.minQualityForRetention);for(let s of i){let a=s.last_used_at?new Date(s.last_used_at):new Date(0),c=Math.floor((Date.now()-a.getTime())/(1e3*60*60*24)),l;c>this.config.obsoleteDaysThreshold?l="obsolete":(s.quality_score??0)<.2?l="low-quality":l="unused",t.push({patternId:s.id,name:s.name,reason:l,qualityScore:s.quality_score??0,daysSinceLastUse:c})}}let r=await this.findMergeCandidates(e);for(let i of r){let s=this.prepared.get("getPattern")?.get(i.patternId1),a=this.prepared.get("getPattern")?.get(i.patternId2);if(s&&a&&Math.abs((s.quality_score??0)-(a.quality_score??0))>.3){let l=(s.quality_score??0)<(a.quality_score??0)?s:a,d=(s.quality_score??0)>=(a.quality_score??0)?s:a;t.find(u=>u.patternId===l.id)||t.push({patternId:l.id,name:l.name,reason:"redundant",qualityScore:l.quality_score??0,daysSinceLastUse:0,similarPatterns:[d.id]})}}return t}async mergePatterns(e,t,n){this.ensureInitialized();let r=this.db;if(!r)return null;let i=this.prepared.get("getPattern"),s=i?.get(e),a=i?.get(t);if(!s||!a)return null;let[c,l]=(s.quality_score??0)>=(a.quality_score??0)?[s,a]:[a,s];n&&await this.write(()=>r.prepare("UPDATE qe_patterns SET name = ? WHERE id = ?").run(n,c.id));let d=(c.usage_count??0)+(l.usage_count??0),u=(c.successful_uses??0)+(l.successful_uses??0),m=d>0?u/d:0;await this.write(()=>r.prepare(`
351
+ `))}async loadEmbeddingCache(){let e=this.prepared.get("getAllPatternEmbeddings");if(!e)return;let t=e.all();this.embeddingCache.clear();for(let n of t){let r=this.bufferToFloatArray(n.embedding,n.dimension);this.embeddingCache.set(n.pattern_id,r)}console.log(`[PatternEvolution] Loaded ${this.embeddingCache.size} pattern embeddings`)}async trackVersion(e,t,n=[],r="manual"){this.ensureInitialized();let i=U(),s=this.floatArrayToBuffer(t),a=await this.write(()=>{let d=(this.prepared.get("getVersionCount")?.get(e)?.count??0)+1,p=this.prepared.get("getPattern")?.get(e),f={id:i,patternId:e,version:d,embedding:t,changes:n,qualityScore:p?.quality_score??.5,successRate:p?.success_rate??.5,timestamp:new Date,trigger:r},g=this.prepared.get("insertVersion");return g&&g.run(i,e,d,s,t.length,JSON.stringify(n),f.qualityScore,f.successRate,r),f}),c=a.version;return this.embeddingCache.set(e,t),await this.recordEvent(e,"updated",{version:c,changes:n,trigger:r}),this.stats.versionsTracked++,a}async detectDrift(e){this.ensureInitialized(),this.stats.driftDetections++;let t=this.prepared.get("getVersionHistory");if(!t)return null;let n=t.all(e,10);if(n.length<2)return null;let r=n[0],i=n[n.length-1],s=this.bufferToFloatArray(r.embedding,r.embedding_dimension),a=this.bufferToFloatArray(i.embedding,i.embedding_dimension),l=1-Ue(s,a),u=l>this.config.driftThreshold;u&&this.stats.significantDrifts++;let d,m;return l<.1?(d="keep",m="Pattern is stable with minimal drift"):l<this.config.driftThreshold?(d="keep",m="Drift is within acceptable range"):l<.6?(d="update",m="Moderate drift detected - consider versioning"):l<.8?(d="split",m="Significant drift - pattern may represent multiple concepts"):(d="archive",m="Severe drift - pattern has fundamentally changed"),{patternId:e,currentEmbedding:s,originalEmbedding:a,driftScore:l,hasSignificantDrift:u,recommendation:d,reason:m}}async findMergeCandidates(e){this.ensureInitialized();let t=this.prepared.get("getPatternEmbeddings");if(!t)return[];let n=t.all(e),r=[],i=this.prepared.get("getPattern");for(let s=0;s<n.length;s++)for(let a=s+1;a<n.length;a++){let c=this.bufferToFloatArray(n[s].embedding,n[s].dimension),l=this.bufferToFloatArray(n[a].embedding,n[a].dimension),u=Ue(c,l);if(u>=this.config.mergeSimilarityThreshold){let d=i?.get(n[s].pattern_id),m=i?.get(n[a].pattern_id),p=((d?.quality_score??0)+(m?.quality_score??0))/2,f=u*p;r.push({patternId1:n[s].pattern_id,patternId2:n[a].pattern_id,similarity:u,mergeBenefit:f,suggestedName:`${d?.name??"Pattern"} + ${m?.name??"Pattern"}`})}}return r.sort((s,a)=>a.mergeBenefit-s.mergeBenefit)}async findPruneCandidates(e){this.ensureInitialized();let t=[],n=this.prepared.get("getPatternsForPruning");if(n){let i=n.all(e,this.config.minQualityForRetention);for(let s of i){let a=s.last_used_at?new Date(s.last_used_at):new Date(0),c=Math.floor((Date.now()-a.getTime())/(1e3*60*60*24)),l;c>this.config.obsoleteDaysThreshold?l="obsolete":(s.quality_score??0)<.2?l="low-quality":l="unused",t.push({patternId:s.id,name:s.name,reason:l,qualityScore:s.quality_score??0,daysSinceLastUse:c})}}let r=await this.findMergeCandidates(e);for(let i of r){let s=this.prepared.get("getPattern")?.get(i.patternId1),a=this.prepared.get("getPattern")?.get(i.patternId2);if(s&&a&&Math.abs((s.quality_score??0)-(a.quality_score??0))>.3){let l=(s.quality_score??0)<(a.quality_score??0)?s:a,u=(s.quality_score??0)>=(a.quality_score??0)?s:a;t.find(d=>d.patternId===l.id)||t.push({patternId:l.id,name:l.name,reason:"redundant",qualityScore:l.quality_score??0,daysSinceLastUse:0,similarPatterns:[u.id]})}}return t}async mergePatterns(e,t,n){this.ensureInitialized();let r=this.db;if(!r)return null;let i=this.prepared.get("getPattern"),s=i?.get(e),a=i?.get(t);if(!s||!a)return null;let[c,l]=(s.quality_score??0)>=(a.quality_score??0)?[s,a]:[a,s];n&&await this.write(()=>r.prepare("UPDATE qe_patterns SET name = ? WHERE id = ?").run(n,c.id));let u=(c.usage_count??0)+(l.usage_count??0),d=(c.successful_uses??0)+(l.successful_uses??0),m=u>0?d/u:0;await this.write(()=>r.prepare(`
361
352
  UPDATE qe_patterns SET
362
353
  usage_count = ?,
363
354
  successful_uses = ?,
@@ -369,68 +360,68 @@ ${e.recommendations.length===0?s:e.recommendations.map((a,c)=>`${c+1}. ${a}`).jo
369
360
  END,
370
361
  updated_at = datetime('now')
371
362
  WHERE id = ?
372
- `).run(d,u,m,l.last_used_at,l.last_used_at,l.last_used_at,c.id));let p=this.prepared.get("insertRelationship");if(p){let g=U();await this.write(()=>p.run(g,l.id,c.id,"merged",1))}return await this.write(()=>r.prepare("UPDATE qe_patterns SET tier = 'archived' WHERE id = ?").run(l.id)),await this.recordEvent(c.id,"merged",{absorbedFrom:l.id}),await this.recordEvent(l.id,"archived",{mergedInto:c.id}),this.stats.patternsMerged++,c.id}async autoConsolidate(e){this.ensureInitialized(),this.stats.consolidationRuns++;let t=0,n=0,r=await this.findMergeCandidates(e);for(let a of r.slice(0,5))await this.mergePatterns(a.patternId1,a.patternId2)&&t++;let i=await this.findPruneCandidates(e);for(let a of i)if(a.reason==="low-quality"||a.reason==="obsolete"){let c=this.db;c&&(await this.write(()=>c.prepare("DELETE FROM qe_patterns WHERE id = ?").run(a.patternId)),this.embeddingCache.delete(a.patternId),await this.recordEvent(a.patternId,"pruned",{reason:a.reason}),n++,this.stats.patternsPruned++)}let s=this.db?.prepare(`
363
+ `).run(u,d,m,l.last_used_at,l.last_used_at,l.last_used_at,c.id));let p=this.prepared.get("insertRelationship");if(p){let f=U();await this.write(()=>p.run(f,l.id,c.id,"merged",1))}return await this.write(()=>r.prepare("UPDATE qe_patterns SET tier = 'archived' WHERE id = ?").run(l.id)),await this.recordEvent(c.id,"merged",{absorbedFrom:l.id}),await this.recordEvent(l.id,"archived",{mergedInto:c.id}),this.stats.patternsMerged++,c.id}async autoConsolidate(e){this.ensureInitialized(),this.stats.consolidationRuns++;let t=0,n=0,r=await this.findMergeCandidates(e);for(let a of r.slice(0,5))await this.mergePatterns(a.patternId1,a.patternId2)&&t++;let i=await this.findPruneCandidates(e);for(let a of i)if(a.reason==="low-quality"||a.reason==="obsolete"){let c=this.db;c&&(await this.write(()=>c.prepare("DELETE FROM qe_patterns WHERE id = ?").run(a.patternId)),this.embeddingCache.delete(a.patternId),await this.recordEvent(a.patternId,"pruned",{reason:a.reason}),n++,this.stats.patternsPruned++)}let s=this.db?.prepare(`
373
364
  SELECT COUNT(*) as count FROM qe_patterns WHERE qe_domain = ? AND tier != 'archived'
374
- `).get(e);return{merged:t,pruned:n,retained:s?.count??0}}async getEvolutionHistory(e,t=20){this.ensureInitialized();let i=(this.prepared.get("getVersionHistory")?.all(e,t)??[]).map(l=>({id:l.id,patternId:l.pattern_id,version:l.version,embedding:this.bufferToFloatArray(l.embedding,l.embedding_dimension),changes:I(l.changes||"[]"),qualityScore:l.quality_score,successRate:l.success_rate,timestamp:new Date(l.created_at),trigger:l.trigger})),c=(this.prepared.get("getEvents")?.all(e,t)??[]).map(l=>({id:l.id,patternId:l.pattern_id,eventType:l.event_type,details:I(l.details||"{}"),timestamp:new Date(l.created_at)}));return{versions:i,events:c}}async recordEvent(e,t,n){let r=this.prepared.get("insertEvent");if(r){let i={id:U(),patternId:e,eventType:t,details:n,timestamp:new Date};await this.write(()=>r.run(i.id,e,t,JSON.stringify(n))),this.recentEvents.push(i)}}write(e){return this.unifiedMemory?this.unifiedMemory.writeWhenUnlocked(e):Promise.resolve(e())}getStats(){return{...this.stats,embeddingCacheSize:this.embeddingCache.size,recentEventsSize:this.recentEvents.length}}async dispose(){this.embeddingCache.clear(),this.recentEvents.clear(),this.prepared.clear(),this.db=null,this.unifiedMemory=null,this.initialized=!1,console.log("[PatternEvolution] Disposed")}ensureInitialized(){if(!this.initialized)throw new Error("PatternEvolution not initialized. Call initialize() first.")}floatArrayToBuffer(e){let t=Buffer.alloc(e.length*4);for(let n=0;n<e.length;n++)t.writeFloatLE(e[n],n*4);return t}bufferToFloatArray(e,t){let n=[];for(let r=0;r<t;r++)n.push(e.readFloatLE(r*4));return n}};function Qr(o={}){return new En(o)}D();var ru={base:{},trajectoryTracker:{},experienceReplay:{},patternEvolution:{},enableTrajectories:!0,enableExperienceReplay:!0,enablePatternEvolution:!0,autoStoreExperiences:!0,autoConsolidate:!0,consolidationIntervalMs:3600*1e3},Wr=class{config;reasoningBank=null;trajectoryTracker=null;experienceReplay=null;patternEvolution=null;initialized=!1;consolidationTimer=null;stats={tasksRouted:0,trajectoriesCompleted:0,experiencesApplied:0,tokensSavedEstimate:0,avgTaskSpeedupPercent:0,successRate:0,totalSuccesses:0,totalTasks:0};constructor(e={}){this.config={...ru,...e}}async initialize(){if(this.initialized)return;let e=performance.now();this.reasoningBank=Lr(this.config.base),await this.reasoningBank.initialize(),this.config.enableTrajectories&&(this.trajectoryTracker=Hr(this.config.trajectoryTracker),await this.trajectoryTracker.initialize()),this.config.enableExperienceReplay&&(this.experienceReplay=Vr(this.config.experienceReplay),await this.experienceReplay.initialize()),this.config.enablePatternEvolution&&(this.patternEvolution=Qr(this.config.patternEvolution),await this.patternEvolution.initialize()),this.config.autoConsolidate&&this.patternEvolution&&this.startConsolidationTimer(),this.initialized=!0;let t=performance.now()-e;console.log(`[EnhancedReasoningBank] Initialized in ${t.toFixed(0)}ms`)}async routeTaskWithExperience(e){this.ensureInitialized(),this.stats.tasksRouted++;try{let t=await this.reasoningBank.routeTask(e);if(!t.success)return t;let n={...t.value};if(this.experienceReplay){let r=await this.experienceReplay.getGuidance(e.task,e.domain);r&&(n.experienceGuidance=r,n.guidance=[`Strategy: ${r.recommendedStrategy}`,...r.suggestedActions.map(i=>`Action: ${i}`),...n.guidance])}if(this.trajectoryTracker){let r=await this.trajectoryTracker.findSimilarTrajectories(e.task,3);r.length>0&&(n.similarTrajectories=r.map(i=>({id:i.id,task:i.task,outcome:i.outcome,similarity:.8})))}return F(n)}catch(t){return L(B(t))}}async startTaskTrajectory(e,t={}){if(this.ensureInitialized(),!this.trajectoryTracker)throw new Error("Trajectory tracking not enabled");return this.trajectoryTracker.startTrajectory(e,t)}async recordTaskStep(e,t,n,r){if(this.ensureInitialized(),!this.trajectoryTracker)throw new Error("Trajectory tracking not enabled");await this.trajectoryTracker.recordStep(e,t,n,r)}async endTaskTrajectory(e,t,n){if(this.ensureInitialized(),!this.trajectoryTracker)throw new Error("Trajectory tracking not enabled");let r=await this.trajectoryTracker.endTrajectory(e,t,n);if(this.stats.trajectoriesCompleted++,this.stats.totalTasks++,t&&this.stats.totalSuccesses++,this.stats.successRate=this.stats.totalSuccesses/this.stats.totalTasks,this.config.autoStoreExperiences&&t&&this.experienceReplay){let i=this.deriveStrategy(r);await this.experienceReplay.storeExperience(r,i)}return r}async getTrajectory(e){return this.ensureInitialized(),this.trajectoryTracker?.getTrajectory(e)??null}async getExperienceGuidance(e,t){return this.ensureInitialized(),this.experienceReplay?this.experienceReplay.getGuidance(e,t):null}async recordExperienceApplication(e,t,n,r=0){this.ensureInitialized(),this.experienceReplay&&(await this.experienceReplay.recordApplication(e,t,n,r),this.stats.experiencesApplied++,this.stats.tokensSavedEstimate+=r)}async storePattern(e){this.ensureInitialized();let t=await this.reasoningBank.storeQEPattern(e);return t.success&&this.patternEvolution&&t.value.embedding&&await this.patternEvolution.trackVersion(t.value.id,t.value.embedding,["Initial version"],"initial"),t}async searchPatterns(e,t){return this.ensureInitialized(),this.reasoningBank.searchQEPatterns(e,t)}getPatternSearchStatus(){return this.ensureInitialized(),this.reasoningBank.getPatternSearchStatus()}getExperienceGuidanceStatus(){return this.ensureInitialized(),this.experienceReplay?.getEmbedderStatus()??null}async recordPatternOutcome(e){this.ensureInitialized();let t=await this.reasoningBank.recordOutcome(e);if(this.patternEvolution&&e.success!==void 0){let n=await this.patternEvolution.detectDrift(e.patternId);n?.hasSignificantDrift&&console.log(`[EnhancedReasoningBank] Pattern drift detected: ${e.patternId}, recommendation: ${n.recommendation}`)}return t}async detectPatternDrift(e){return this.ensureInitialized(),this.patternEvolution?.detectDrift(e)??null}async findMergeCandidates(e){return this.ensureInitialized(),this.patternEvolution?.findMergeCandidates(e)??[]}async consolidatePatterns(e){return this.ensureInitialized(),this.patternEvolution?this.patternEvolution.autoConsolidate(e):{merged:0,pruned:0,retained:0}}async getPatternHistory(e){return this.ensureInitialized(),this.patternEvolution?.getEvolutionHistory(e)??null}async getStats(){return this.ensureInitialized(),{adapter:this.stats,reasoningBank:await this.reasoningBank.getQEStats(),trajectoryTracker:this.trajectoryTracker?.getStats(),experienceReplay:this.experienceReplay?.getStats(),patternEvolution:this.patternEvolution?.getStats()}}async dispose(){this.consolidationTimer&&(clearInterval(this.consolidationTimer),this.consolidationTimer=null),await this.patternEvolution?.dispose(),await this.experienceReplay?.dispose(),await this.trajectoryTracker?.dispose(),await this.reasoningBank?.dispose(),this.patternEvolution=null,this.experienceReplay=null,this.trajectoryTracker=null,this.reasoningBank=null,this.initialized=!1,console.log("[EnhancedReasoningBank] Disposed")}ensureInitialized(){if(!this.initialized||!this.reasoningBank)throw new Error("EnhancedReasoningBankAdapter not initialized. Call initialize() first.")}startConsolidationTimer(){this.consolidationTimer=setInterval(async()=>{try{let e=["test-generation","coverage-analysis","test-execution","quality-assessment"];for(let t of e){let n=await this.patternEvolution.autoConsolidate(t);(n.merged>0||n.pruned>0)&&console.log(`[EnhancedReasoningBank] Consolidated ${t}: merged=${n.merged}, pruned=${n.pruned}, retained=${n.retained}`)}}catch(e){console.error("[EnhancedReasoningBank] Consolidation error:",e)}},this.config.consolidationIntervalMs)}deriveStrategy(e){let t=e.steps.filter(n=>n.result.outcome==="success").map(n=>n.action);return t.length===0?`Attempted ${e.steps.length} actions for: ${e.task}`:`Used ${t.join(" -> ")} pattern for: ${e.task.substring(0,50)}`}};function cf(o={}){return new Wr(o)}import{randomUUID as fu}from"crypto";var $=class extends Error{constructor(t,n,r){super(n);this.type=t;this.details=r;this.name="EmbeddingError"}type;details};var wn=class{cache;maxSize;hits=0;misses=0;constructor(e){this.maxSize=e,this.cache=new Map}get(e){let t=this.cache.get(e);if(t)return this.hits++,this.cache.delete(e),this.cache.set(e,t),t;this.misses++}set(e,t){if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,t)}clear(){this.cache.clear(),this.hits=0,this.misses=0}getStats(){return{hits:this.hits,misses:this.misses,size:this.cache.size}}},Xe=class{config;cache;totalGenerated=0;generationTimes=[];isInitialized=!1;onnxRuntime=null;constructor(e={}){this.config={model:e.model??"all-MiniLM-L6-v2",normalize:e.normalize??!0,hyperbolic:e.hyperbolic??!1,cacheSize:e.cacheSize??256,curvature:e.curvature??-1},this.cache=new wn(this.config.cacheSize)}async initialize(){if(!this.isInitialized)try{let{computeRealEmbedding:e}=await import("./real-embeddings-II6CXTCI.js");this.onnxRuntime={generateEmbedding:async(t,n)=>{let r=await e(t);if(this.config.normalize){let i=Math.sqrt(r.reduce((s,a)=>s+a*a,0));if(i>0)return r.map(s=>s/i)}return r},isAvailable:()=>!0},this.isInitialized=!0}catch(e){throw new $("RUNTIME_UNAVAILABLE","Failed to initialize ONNX runtime",e)}}async generate(e){if(this.isInitialized||await this.initialize(),!e||e.trim().length===0)throw new $("INVALID_INPUT","Text cannot be empty");let t=this.getCacheKey(e),n=this.cache.get(t);if(n)return n;let r=Date.now();try{if(!this.onnxRuntime)throw new $("RUNTIME_UNAVAILABLE","ONNX runtime not available");let i=await this.onnxRuntime.generateEmbedding(e,this.config.model),s=i,a=!1;this.config.hyperbolic&&(s=this.euclideanToPoincare(i),a=!0);let c={vector:s,dimensions:s.length,model:this.config.model,isHyperbolic:a};return this.cache.set(t,c),this.totalGenerated++,this.generationTimes.push(Date.now()-r),this.generationTimes.length>100&&this.generationTimes.shift(),c}catch(i){throw new $("MODEL_LOAD_FAILED",`Failed to generate embedding: ${i instanceof Error?i.message:"Unknown error"}`,i)}}async generateBatch(e){if(!e.texts||e.texts.length===0)throw new $("INVALID_INPUT","Batch request must contain at least one text");let t=Date.now(),n=0,r=[],i={...this.config};e.config&&(this.config={...this.config,...e.config});try{for(let s of e.texts){let a=this.getCacheKey(s),c=this.cache.get(a);if(c)r.push(c),n++;else{let l=await this.generate(s);r.push(l)}}return{embeddings:r,duration:Date.now()-t,cacheHits:n}}finally{this.config=i}}getStats(){let e=this.cache.getStats(),t=this.generationTimes.length>0?this.generationTimes.reduce((n,r)=>n+r,0)/this.generationTimes.length:0;return{totalGenerated:this.totalGenerated,cacheHits:e.hits,cacheMisses:e.misses,avgGenerationTime:t,currentModel:this.config.model,vectorsStored:e.size}}clearCache(){this.cache.clear()}updateConfig(e){let t=e.model&&e.model!==this.config.model;this.config={...this.config,...e},e.cacheSize!==void 0&&e.cacheSize!==this.cache.getStats().size&&(this.cache=new wn(e.cacheSize)),t&&(this.isInitialized=!1)}getCacheKey(e){let{model:t,hyperbolic:n,normalize:r,curvature:i}=this.config;return JSON.stringify([t,n,r,i,e])}euclideanToPoincare(e){let t=Math.sqrt(e.reduce((s,a)=>s+a*a,0));if(t===0)return e;let n=Math.abs(this.config.curvature),r=Math.sqrt(n),i=Math.tanh(r*t/2)/(r*t);return e.map(s=>s*i)}isReady(){return this.isInitialized&&this.onnxRuntime!==null}};var Ye=class{embeddings;searchCount=0;searchTimes=[];constructor(){this.embeddings=new Map}store(e){this.embeddings.set(e.id,e)}storeBatch(e){for(let t of e)this.store(t)}remove(e){return this.embeddings.delete(e)}clear(){this.embeddings.clear()}async search(e,t={}){let n=Date.now(),r={metric:t.metric??"cosine",topK:t.topK??5,threshold:t.threshold??.5,namespace:t.namespace};try{let i=Array.from(this.embeddings.values());r.namespace&&(i=i.filter(d=>d.namespace===r.namespace));let s=[];for(let d of i){if(d.embedding.dimensions!==e.dimensions)continue;let u=this.calculateSimilarity(e.vector,d.embedding.vector,r.metric);(r.metric==="cosine"?u>=r.threshold:u<=r.threshold)&&s.push({stored:d,score:u})}let a=r.metric==="cosine"?-1:1;s.sort((d,u)=>a*(d.score-u.score));let l=s.slice(0,r.topK).map(({stored:d,score:u})=>({text:d.text,embedding:d.embedding,score:u,metadata:d.metadata}));return this.searchCount++,this.searchTimes.push(Date.now()-n),this.searchTimes.length>100&&this.searchTimes.shift(),l}catch(i){throw new $("DIMENSION_MISMATCH",`Search failed: ${i instanceof Error?i.message:"Unknown error"}`,i)}}async findMostSimilar(e,t={}){let n=await this.search(e,{...t,topK:1});return n.length>0?n[0]:null}calculateSimilarity(e,t,n){if(e.length!==t.length)throw new $("DIMENSION_MISMATCH",`Vector dimensions do not match: ${e.length} vs ${t.length}`);switch(n){case"cosine":return this.cosineSimilarity(e,t);case"euclidean":return this.euclideanDistance(e,t);case"poincare":return this.poincareDistance(e,t);default:throw new $("INVALID_INPUT",`Unknown similarity metric: ${n}`)}}getStats(){let e=this.searchTimes.length>0?this.searchTimes.reduce((t,n)=>t+n,0)/this.searchTimes.length:0;return{searchCount:this.searchCount,avgSearchTime:e,storedCount:this.embeddings.size}}getAll(e){let t=Array.from(this.embeddings.values());return e?t.filter(n=>n.namespace===e):t}get(e){return this.embeddings.get(e)}cosineSimilarity(e,t){let n=0,r=0,i=0;for(let a=0;a<e.length;a++)n+=e[a]*t[a],r+=e[a]*e[a],i+=t[a]*t[a];let s=Math.sqrt(r)*Math.sqrt(i);return s===0?0:n/s}euclideanDistance(e,t){let n=0;for(let r=0;r<e.length;r++){let i=e[r]-t[r];n+=i*i}return Math.sqrt(n)}poincareDistance(e,t,n=-1){let r=Math.abs(n),i=Math.sqrt(r),s=e.reduce((p,g)=>p+g*g,0),a=t.reduce((p,g)=>p+g*g,0),c=0;for(let p=0;p<e.length;p++){let g=e[p]-t[p];c+=g*g}let l=2*c,d=(1-s)*(1-a);if(d<=0)return 1/0;let u=l/d;return Math.acosh(1+u)/i}async searchBatch(e,t={}){let n=[];for(let r of e){let i=await this.search(r,t);n.push(i)}return n}async findInRadius(e,t,n="cosine"){return this.search(e,{metric:n,threshold:t,topK:this.embeddings.size})}};var Je=class{config;constructor(e={}){if(this.config={curvature:e.curvature??-1,epsilon:e.epsilon??1e-7},this.config.curvature>=0)throw new $("HYPERBOLIC_ERROR","Curvature must be negative for hyperbolic space")}euclideanToPoincare(e){if(e.isHyperbolic)return e;let t=e.vector,n=this.norm(t);if(n<this.config.epsilon)return{...e,isHyperbolic:!0};let r=Math.abs(this.config.curvature),i=Math.sqrt(r),s=Math.tanh(i*n/2)/(i*n),a=t.map(l=>l*s),c=this.norm(a);if(c>=1-this.config.epsilon)throw new $("HYPERBOLIC_ERROR",`Poincar\xE9 ball constraint violated: norm = ${c}`);return{vector:a,dimensions:e.dimensions,model:e.model,isHyperbolic:!0}}poincareToEuclidean(e){if(!e.isHyperbolic)return e;let t=e.vector,n=this.norm(t);if(n<this.config.epsilon)return{...e,isHyperbolic:!1};let r=Math.abs(this.config.curvature),i=Math.sqrt(r),s=i*n;if(s>=1)throw new $("HYPERBOLIC_ERROR","Point is on or outside Poincar\xE9 ball boundary");let a=2/i*Math.atanh(s)/n;return{vector:t.map(l=>l*a),dimensions:e.dimensions,model:e.model,isHyperbolic:!1}}distance(e,t){if(e.dimensions!==t.dimensions)throw new $("DIMENSION_MISMATCH","Embeddings must have same dimensions");if(!e.isHyperbolic||!t.isHyperbolic)throw new $("HYPERBOLIC_ERROR","Both embeddings must be in hyperbolic space");let n=e.vector,r=t.vector,i=Math.abs(this.config.curvature),s=Math.sqrt(i),a=this.normSquared(n),c=this.normSquared(r),d=2*this.euclideanDistanceSquared(n,r),u=(1-a)*(1-c);if(u<=this.config.epsilon)return 1/0;let m=d/u;return Math.acosh(1+m)/s}midpoint(e,t){if(e.dimensions!==t.dimensions)throw new $("DIMENSION_MISMATCH","Embeddings must have same dimensions");if(!e.isHyperbolic||!t.isHyperbolic)throw new $("HYPERBOLIC_ERROR","Both embeddings must be in hyperbolic space");let n=e.vector,r=t.vector;return{vector:this.mobiusAddition(n,this.mobiusScalarMultiply(this.mobiusAddition(this.mobiusNegate(n),r),.5)),dimensions:e.dimensions,model:e.model,isHyperbolic:!0}}mobiusAddition(e,t){let n=Math.abs(this.config.curvature),r=this.dot(e,t),i=this.normSquared(e),s=this.normSquared(t),a=1+2*n*r+n*s,c=1-n*i,l=1+2*n*r+n*n*i*s;if(Math.abs(l)<this.config.epsilon)throw new $("HYPERBOLIC_ERROR","M\xF6bius addition denominator is zero");return e.map((u,m)=>(a*u+c*t[m])/l)}mobiusScalarMultiply(e,t){let n=Math.abs(this.config.curvature),r=Math.sqrt(n),i=this.norm(e);if(i<this.config.epsilon)return e;let s=r*i;if(Math.abs(s)>=1)throw new $("HYPERBOLIC_ERROR","M\xF6bius scalar multiplication out of bounds");let a=Math.tanh(t*Math.atanh(s))/(r*i);return e.map(c=>c*a)}mobiusNegate(e){return e.map(t=>-t)}projectToBall(e){let t=this.norm(e);if(t>=1-this.config.epsilon){let n=(1-this.config.epsilon)/t;return e.map(r=>r*n)}return e}norm(e){return Math.sqrt(this.normSquared(e))}normSquared(e){return e.reduce((t,n)=>t+n*n,0)}dot(e,t){return e.reduce((n,r,i)=>n+r*t[i],0)}euclideanDistanceSquared(e,t){return e.reduce((n,r,i)=>{let s=r-t[i];return n+s*s},0)}updateConfig(e){if(e.curvature!==void 0&&e.curvature>=0)throw new $("HYPERBOLIC_ERROR","Curvature must be negative");this.config={...this.config,...e}}getConfig(){return{...this.config}}};pe();var Pt=class{generator;search;hyperbolic;isInitialized=!1;constructor(e={}){this.generator=new Xe(e.embedding),this.search=new Ye,this.hyperbolic=new Je(e.hyperbolic),e.autoInitialize!==!1&&this.initialize().catch(t=>{console.error("Failed to auto-initialize ONNX embeddings:",t)})}async initialize(){if(!this.isInitialized)try{await this.generator.initialize(),this.isInitialized=!0}catch(e){throw new $("RUNTIME_UNAVAILABLE","Failed to initialize ONNX embeddings adapter",e)}}async getHealth(){try{let e=this.generator.isReady();return{available:e,modelLoaded:e?this.getStats().currentModel:null,system:{memory:process.memoryUsage().heapUsed,threads:1}}}catch(e){return{available:!1,modelLoaded:null,error:e instanceof Error?e.message:"Unknown error",system:{memory:process.memoryUsage().heapUsed,threads:0}}}}async generateEmbedding(e){return await this.ensureInitialized(),this.generator.generate(e)}async generateBatch(e){return await this.ensureInitialized(),this.generator.generateBatch(e)}async generateAndStore(e,t){let n=await this.generateEmbedding(e),r={id:t?.id??this.generateId(),text:e,embedding:n,namespace:t?.namespace,metadata:t?.customData,createdAt:Date.now()};this.search.store(r);try{let i=X();await i.initialize(),await i.vectorStore(r.id,r.embedding.vector,r.namespace??"onnx",{text:r.text,customData:r.metadata,createdAt:r.createdAt})}catch{}return r}async searchByText(e,t){let n=await this.generateEmbedding(e);return this.search.search(n,t)}async searchByEmbedding(e,t){return this.search.search(e,t)}async findMostSimilar(e,t){let n=await this.generateEmbedding(e);return this.search.findMostSimilar(n,t)}async compareSimilarity(e,t,n="cosine"){let[r,i]=await this.generateBatch({texts:[e,t]}).then(s=>s.embeddings);return this.search.calculateSimilarity(r.vector,i.vector,n)}storeEmbedding(e){this.search.store(e)}storeBatch(e){this.search.storeBatch(e)}removeEmbedding(e){return this.search.remove(e)}getEmbedding(e){return this.search.get(e)}getAllEmbeddings(e){return this.search.getAll(e)}clearEmbeddings(){this.search.clear()}toHyperbolic(e){return this.hyperbolic.euclideanToPoincare(e)}toEuclidean(e){return this.hyperbolic.poincareToEuclidean(e)}hyperbolicDistance(e,t){return this.hyperbolic.distance(e,t)}hyperbolicMidpoint(e,t){return this.hyperbolic.midpoint(e,t)}projectToBall(e){return this.hyperbolic.projectToBall(e)}getStats(){let e=this.generator.getStats(),t=this.search.getStats();return{totalGenerated:e.totalGenerated??0,cacheHits:e.cacheHits??0,cacheMisses:e.cacheMisses??0,totalSearches:t.searchCount,avgGenerationTime:e.avgGenerationTime??0,avgSearchTime:t.avgSearchTime,currentModel:e.currentModel??"all-MiniLM-L6-v2",vectorsStored:t.storedCount}}updateEmbeddingConfig(e){this.generator.updateConfig(e)}updateHyperbolicConfig(e){this.hyperbolic.updateConfig(e)}clearCaches(){this.generator.clearCache()}reset(){this.clearCaches(),this.clearEmbeddings()}async bridgeToMCPGenerate(e,t=!1){let n=await this.generateEmbedding(e);return t?this.toHyperbolic(n):n}async bridgeToMCPSearch(e,t){return this.searchByText(e,t)}async bridgeToMCPCompare(e,t,n="cosine"){return this.compareSimilarity(e,t,n)}async ensureInitialized(){this.isInitialized||await this.initialize()}generateId(){return`emb_${Date.now()}_${fu().slice(0,9)}`}isReady(){return this.isInitialized&&this.generator.isReady()}};function xn(o){return new Pt(o)}var Kr={enabled:!0,dbPath:".agentic-qe/memory.db",maxOutcomes:1e5,retentionDays:90,autoCleanup:!0,cleanupIntervalMs:3600*1e3};pe();D();ee();var Eu={enabled:!0,haikuThreshold:.8,sonnetThreshold:.4,includeHealthSnapshot:!1,enableLogging:!0},Xr=class{config;minCutService;constructor(e){this.config={...Eu,...e},this.minCutService=$a()}route(e){let t=Date.now();if(!this.config.enabled)return this.createFallbackResult(e,t,"MinCut routing disabled");let n=e.agentTopology||this.config.defaultTopology;if(!n||n.length===0)return this.createFallbackResult(e,t,"No agent topology available for mincut analysis");try{let r=this.minCutService.computeRoutingTier(e.task,n),i=this.routingTierToModelTier(r.tier);e.isCritical&&i<2&&(i=2);let s=this.modelTierToLabel(i),a;if(this.config.includeHealthSnapshot){let d=e.taskGraph||this.minCutService.buildTaskGraphFromTopology(n);a=this.minCutService.getStructuralHealth(d)}let c=Date.now()-t,l={modelTier:i,tierLabel:s,lambda:r.lambda,normalizedLambda:r.normalizedLambda,confidence:r.confidence,rationale:r.rationale,usedMinCut:!0,healthSnapshot:a,decisionTimeMs:c};return this.config.enableLogging&&this.logDecision(l),l}catch(r){return this.createFallbackResult(e,t,`MinCut routing error: ${r instanceof Error?r.message:String(r)}`)}}getMinCutService(){return this.minCutService}isEnabled(){return this.config.enabled}routingTierToModelTier(e){switch(e){case 1:return 1;case 2:return 2;case 3:return 4;default:return 2}}modelTierToLabel(e){switch(e){case 0:return"Booster";case 1:return"Haiku";case 2:return"Sonnet";case 3:return"Sonnet-Extended";case 4:return"Opus";default:return"Sonnet"}}createFallbackResult(e,t,n){return{modelTier:(e.isCritical,2),tierLabel:"Sonnet",lambda:0,normalizedLambda:0,confidence:.3,rationale:`Fallback to Sonnet: ${n}`,usedMinCut:!1,decisionTimeMs:Date.now()-t}}logDecision(e){let t=e.usedMinCut?"MinCut":"Fallback";console.error(`[MinCutRouter] [${t}] Tier ${e.modelTier} (${e.tierLabel}) | Lambda: ${e.normalizedLambda.toFixed(3)} | Confidence: ${(e.confidence*100).toFixed(0)}% | Time: ${e.decisionTimeMs}ms`)}};function So(o){return new Xr(o)}import{existsSync as wu}from"fs";import{join as Ru}from"path";var An=class{id="memory";name="Pattern Memory";priority=80;maxTokens=2e3;async gather(e){let t=[];try{let n=Ru(process.cwd(),".agentic-qe","memory.db");if(!wu(n))return this.fallbackGather(e);let{openDatabase:r}=await import("./safe-db-RZPQGLGQ.js"),i=r(n,{readonly:!0});try{let s=this.extractDomainKeywords(e.taskDescription);if(s.length>0){let a=s.map(()=>"domain LIKE ?").join(" OR "),c=s.map(u=>`%${u}%`),d=i.prepare(`SELECT name, domain, description, confidence
365
+ `).get(e);return{merged:t,pruned:n,retained:s?.count??0}}async getEvolutionHistory(e,t=20){this.ensureInitialized();let i=(this.prepared.get("getVersionHistory")?.all(e,t)??[]).map(l=>({id:l.id,patternId:l.pattern_id,version:l.version,embedding:this.bufferToFloatArray(l.embedding,l.embedding_dimension),changes:I(l.changes||"[]"),qualityScore:l.quality_score,successRate:l.success_rate,timestamp:new Date(l.created_at),trigger:l.trigger})),c=(this.prepared.get("getEvents")?.all(e,t)??[]).map(l=>({id:l.id,patternId:l.pattern_id,eventType:l.event_type,details:I(l.details||"{}"),timestamp:new Date(l.created_at)}));return{versions:i,events:c}}async recordEvent(e,t,n){let r=this.prepared.get("insertEvent");if(r){let i={id:U(),patternId:e,eventType:t,details:n,timestamp:new Date};await this.write(()=>r.run(i.id,e,t,JSON.stringify(n))),this.recentEvents.push(i)}}write(e){return this.unifiedMemory?this.unifiedMemory.writeWhenUnlocked(e):Promise.resolve(e())}getStats(){return{...this.stats,embeddingCacheSize:this.embeddingCache.size,recentEventsSize:this.recentEvents.length}}async dispose(){this.embeddingCache.clear(),this.recentEvents.clear(),this.prepared.clear(),this.db=null,this.unifiedMemory=null,this.initialized=!1,console.log("[PatternEvolution] Disposed")}ensureInitialized(){if(!this.initialized)throw new Error("PatternEvolution not initialized. Call initialize() first.")}floatArrayToBuffer(e){let t=Buffer.alloc(e.length*4);for(let n=0;n<e.length;n++)t.writeFloatLE(e[n],n*4);return t}bufferToFloatArray(e,t){let n=[];for(let r=0;r<t;r++)n.push(e.readFloatLE(r*4));return n}};function Wr(o={}){return new Tn(o)}M();var Xl={base:{},trajectoryTracker:{},experienceReplay:{},patternEvolution:{},enableTrajectories:!0,enableExperienceReplay:!0,enablePatternEvolution:!0,autoStoreExperiences:!0,autoConsolidate:!0,consolidationIntervalMs:3600*1e3},Kr=class{config;reasoningBank=null;trajectoryTracker=null;experienceReplay=null;patternEvolution=null;initialized=!1;consolidationTimer=null;stats={tasksRouted:0,trajectoriesCompleted:0,experiencesApplied:0,tokensSavedEstimate:0,avgTaskSpeedupPercent:0,successRate:0,totalSuccesses:0,totalTasks:0};constructor(e={}){this.config={...Xl,...e}}async initialize(){if(this.initialized)return;let e=performance.now();this.reasoningBank=qr(this.config.base),await this.reasoningBank.initialize(),this.config.enableTrajectories&&(this.trajectoryTracker=Vr(this.config.trajectoryTracker),await this.trajectoryTracker.initialize()),this.config.enableExperienceReplay&&(this.experienceReplay=Qr(this.config.experienceReplay),await this.experienceReplay.initialize()),this.config.enablePatternEvolution&&(this.patternEvolution=Wr(this.config.patternEvolution),await this.patternEvolution.initialize()),this.config.autoConsolidate&&this.patternEvolution&&this.startConsolidationTimer(),this.initialized=!0;let t=performance.now()-e;console.log(`[EnhancedReasoningBank] Initialized in ${t.toFixed(0)}ms`)}async routeTaskWithExperience(e){this.ensureInitialized(),this.stats.tasksRouted++;try{let t=await this.reasoningBank.routeTask(e);if(!t.success)return t;let n={...t.value};if(this.experienceReplay){let r=await this.experienceReplay.getGuidance(e.task,e.domain);r&&(n.experienceGuidance=r,n.guidance=[`Strategy: ${r.recommendedStrategy}`,...r.suggestedActions.map(i=>`Action: ${i}`),...n.guidance])}if(this.trajectoryTracker){let r=await this.trajectoryTracker.findSimilarTrajectories(e.task,3);r.length>0&&(n.similarTrajectories=r.map(i=>({id:i.id,task:i.task,outcome:i.outcome,similarity:.8})))}return F(n)}catch(t){return q(B(t))}}async startTaskTrajectory(e,t={}){if(this.ensureInitialized(),!this.trajectoryTracker)throw new Error("Trajectory tracking not enabled");return this.trajectoryTracker.startTrajectory(e,t)}async recordTaskStep(e,t,n,r){if(this.ensureInitialized(),!this.trajectoryTracker)throw new Error("Trajectory tracking not enabled");await this.trajectoryTracker.recordStep(e,t,n,r)}async endTaskTrajectory(e,t,n){if(this.ensureInitialized(),!this.trajectoryTracker)throw new Error("Trajectory tracking not enabled");let r=await this.trajectoryTracker.endTrajectory(e,t,n);if(this.stats.trajectoriesCompleted++,this.stats.totalTasks++,t&&this.stats.totalSuccesses++,this.stats.successRate=this.stats.totalSuccesses/this.stats.totalTasks,this.config.autoStoreExperiences&&t&&this.experienceReplay){let i=this.deriveStrategy(r);await this.experienceReplay.storeExperience(r,i)}return r}async getTrajectory(e){return this.ensureInitialized(),this.trajectoryTracker?.getTrajectory(e)??null}async getExperienceGuidance(e,t){return this.ensureInitialized(),this.experienceReplay?this.experienceReplay.getGuidance(e,t):null}async recordExperienceApplication(e,t,n,r=0){this.ensureInitialized(),this.experienceReplay&&(await this.experienceReplay.recordApplication(e,t,n,r),this.stats.experiencesApplied++,this.stats.tokensSavedEstimate+=r)}async storePattern(e){this.ensureInitialized();let t=await this.reasoningBank.storeQEPattern(e);return t.success&&this.patternEvolution&&t.value.embedding&&await this.patternEvolution.trackVersion(t.value.id,t.value.embedding,["Initial version"],"initial"),t}async searchPatterns(e,t){return this.ensureInitialized(),this.reasoningBank.searchQEPatterns(e,t)}getPatternSearchStatus(){return this.ensureInitialized(),this.reasoningBank.getPatternSearchStatus()}getExperienceGuidanceStatus(){return this.ensureInitialized(),this.experienceReplay?.getEmbedderStatus()??null}async recordPatternOutcome(e){this.ensureInitialized();let t=await this.reasoningBank.recordOutcome(e);if(this.patternEvolution&&e.success!==void 0){let n=await this.patternEvolution.detectDrift(e.patternId);n?.hasSignificantDrift&&console.log(`[EnhancedReasoningBank] Pattern drift detected: ${e.patternId}, recommendation: ${n.recommendation}`)}return t}async detectPatternDrift(e){return this.ensureInitialized(),this.patternEvolution?.detectDrift(e)??null}async findMergeCandidates(e){return this.ensureInitialized(),this.patternEvolution?.findMergeCandidates(e)??[]}async consolidatePatterns(e){return this.ensureInitialized(),this.patternEvolution?this.patternEvolution.autoConsolidate(e):{merged:0,pruned:0,retained:0}}async getPatternHistory(e){return this.ensureInitialized(),this.patternEvolution?.getEvolutionHistory(e)??null}async getStats(){return this.ensureInitialized(),{adapter:this.stats,reasoningBank:await this.reasoningBank.getQEStats(),trajectoryTracker:this.trajectoryTracker?.getStats(),experienceReplay:this.experienceReplay?.getStats(),patternEvolution:this.patternEvolution?.getStats()}}async dispose(){this.consolidationTimer&&(clearInterval(this.consolidationTimer),this.consolidationTimer=null),await this.patternEvolution?.dispose(),await this.experienceReplay?.dispose(),await this.trajectoryTracker?.dispose(),await this.reasoningBank?.dispose(),this.patternEvolution=null,this.experienceReplay=null,this.trajectoryTracker=null,this.reasoningBank=null,this.initialized=!1,console.log("[EnhancedReasoningBank] Disposed")}ensureInitialized(){if(!this.initialized||!this.reasoningBank)throw new Error("EnhancedReasoningBankAdapter not initialized. Call initialize() first.")}startConsolidationTimer(){this.consolidationTimer=setInterval(async()=>{try{let e=["test-generation","coverage-analysis","test-execution","quality-assessment"];for(let t of e){let n=await this.patternEvolution.autoConsolidate(t);(n.merged>0||n.pruned>0)&&console.log(`[EnhancedReasoningBank] Consolidated ${t}: merged=${n.merged}, pruned=${n.pruned}, retained=${n.retained}`)}}catch(e){console.error("[EnhancedReasoningBank] Consolidation error:",e)}},this.config.consolidationIntervalMs)}deriveStrategy(e){let t=e.steps.filter(n=>n.result.outcome==="success").map(n=>n.action);return t.length===0?`Attempted ${e.steps.length} actions for: ${e.task}`:`Used ${t.join(" -> ")} pattern for: ${e.task.substring(0,50)}`}};function Kg(o={}){return new Kr(o)}import{randomUUID as cu}from"crypto";var G=class extends Error{constructor(t,n,r){super(n);this.type=t;this.details=r;this.name="EmbeddingError"}type;details};var En=class{cache;maxSize;hits=0;misses=0;constructor(e){this.maxSize=e,this.cache=new Map}get(e){let t=this.cache.get(e);if(t)return this.hits++,this.cache.delete(e),this.cache.set(e,t),t;this.misses++}set(e,t){if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,t)}clear(){this.cache.clear(),this.hits=0,this.misses=0}getStats(){return{hits:this.hits,misses:this.misses,size:this.cache.size}}},Ye=class{config;cache;totalGenerated=0;generationTimes=[];isInitialized=!1;onnxRuntime=null;constructor(e={}){this.config={model:e.model??"all-MiniLM-L6-v2",normalize:e.normalize??!0,hyperbolic:e.hyperbolic??!1,cacheSize:e.cacheSize??256,curvature:e.curvature??-1},this.cache=new En(this.config.cacheSize)}async initialize(){if(!this.isInitialized)try{let{computeRealEmbedding:e}=await import("./real-embeddings-MIGZNKK3.js");this.onnxRuntime={generateEmbedding:async(t,n)=>{let r=await e(t);if(this.config.normalize){let i=Math.sqrt(r.reduce((s,a)=>s+a*a,0));if(i>0)return r.map(s=>s/i)}return r},isAvailable:()=>!0},this.isInitialized=!0}catch(e){throw new G("RUNTIME_UNAVAILABLE","Failed to initialize ONNX runtime",e)}}async generate(e){if(this.isInitialized||await this.initialize(),!e||e.trim().length===0)throw new G("INVALID_INPUT","Text cannot be empty");let t=this.getCacheKey(e),n=this.cache.get(t);if(n)return n;let r=Date.now();try{if(!this.onnxRuntime)throw new G("RUNTIME_UNAVAILABLE","ONNX runtime not available");let i=await this.onnxRuntime.generateEmbedding(e,this.config.model),s=i,a=!1;this.config.hyperbolic&&(s=this.euclideanToPoincare(i),a=!0);let c={vector:s,dimensions:s.length,model:this.config.model,isHyperbolic:a};return this.cache.set(t,c),this.totalGenerated++,this.generationTimes.push(Date.now()-r),this.generationTimes.length>100&&this.generationTimes.shift(),c}catch(i){throw new G("MODEL_LOAD_FAILED",`Failed to generate embedding: ${i instanceof Error?i.message:"Unknown error"}`,i)}}async generateBatch(e){if(!e.texts||e.texts.length===0)throw new G("INVALID_INPUT","Batch request must contain at least one text");let t=Date.now(),n=0,r=[],i={...this.config};e.config&&(this.config={...this.config,...e.config});try{for(let s of e.texts){let a=this.getCacheKey(s),c=this.cache.get(a);if(c)r.push(c),n++;else{let l=await this.generate(s);r.push(l)}}return{embeddings:r,duration:Date.now()-t,cacheHits:n}}finally{this.config=i}}getStats(){let e=this.cache.getStats(),t=this.generationTimes.length>0?this.generationTimes.reduce((n,r)=>n+r,0)/this.generationTimes.length:0;return{totalGenerated:this.totalGenerated,cacheHits:e.hits,cacheMisses:e.misses,avgGenerationTime:t,currentModel:this.config.model,vectorsStored:e.size}}clearCache(){this.cache.clear()}updateConfig(e){let t=e.model&&e.model!==this.config.model;this.config={...this.config,...e},e.cacheSize!==void 0&&e.cacheSize!==this.cache.getStats().size&&(this.cache=new En(e.cacheSize)),t&&(this.isInitialized=!1)}getCacheKey(e){let{model:t,hyperbolic:n,normalize:r,curvature:i}=this.config;return JSON.stringify([t,n,r,i,e])}euclideanToPoincare(e){let t=Math.sqrt(e.reduce((s,a)=>s+a*a,0));if(t===0)return e;let n=Math.abs(this.config.curvature),r=Math.sqrt(n),i=Math.tanh(r*t/2)/(r*t);return e.map(s=>s*i)}isReady(){return this.isInitialized&&this.onnxRuntime!==null}};var Je=class{embeddings;searchCount=0;searchTimes=[];constructor(){this.embeddings=new Map}store(e){this.embeddings.set(e.id,e)}storeBatch(e){for(let t of e)this.store(t)}remove(e){return this.embeddings.delete(e)}clear(){this.embeddings.clear()}async search(e,t={}){let n=Date.now(),r={metric:t.metric??"cosine",topK:t.topK??5,threshold:t.threshold??.5,namespace:t.namespace};try{let i=Array.from(this.embeddings.values());r.namespace&&(i=i.filter(u=>u.namespace===r.namespace));let s=[];for(let u of i){if(u.embedding.dimensions!==e.dimensions)continue;let d=this.calculateSimilarity(e.vector,u.embedding.vector,r.metric);(r.metric==="cosine"?d>=r.threshold:d<=r.threshold)&&s.push({stored:u,score:d})}let a=r.metric==="cosine"?-1:1;s.sort((u,d)=>a*(u.score-d.score));let l=s.slice(0,r.topK).map(({stored:u,score:d})=>({text:u.text,embedding:u.embedding,score:d,metadata:u.metadata}));return this.searchCount++,this.searchTimes.push(Date.now()-n),this.searchTimes.length>100&&this.searchTimes.shift(),l}catch(i){throw new G("DIMENSION_MISMATCH",`Search failed: ${i instanceof Error?i.message:"Unknown error"}`,i)}}async findMostSimilar(e,t={}){let n=await this.search(e,{...t,topK:1});return n.length>0?n[0]:null}calculateSimilarity(e,t,n){if(e.length!==t.length)throw new G("DIMENSION_MISMATCH",`Vector dimensions do not match: ${e.length} vs ${t.length}`);switch(n){case"cosine":return this.cosineSimilarity(e,t);case"euclidean":return this.euclideanDistance(e,t);case"poincare":return this.poincareDistance(e,t);default:throw new G("INVALID_INPUT",`Unknown similarity metric: ${n}`)}}getStats(){let e=this.searchTimes.length>0?this.searchTimes.reduce((t,n)=>t+n,0)/this.searchTimes.length:0;return{searchCount:this.searchCount,avgSearchTime:e,storedCount:this.embeddings.size}}getAll(e){let t=Array.from(this.embeddings.values());return e?t.filter(n=>n.namespace===e):t}get(e){return this.embeddings.get(e)}cosineSimilarity(e,t){let n=0,r=0,i=0;for(let a=0;a<e.length;a++)n+=e[a]*t[a],r+=e[a]*e[a],i+=t[a]*t[a];let s=Math.sqrt(r)*Math.sqrt(i);return s===0?0:n/s}euclideanDistance(e,t){let n=0;for(let r=0;r<e.length;r++){let i=e[r]-t[r];n+=i*i}return Math.sqrt(n)}poincareDistance(e,t,n=-1){let r=Math.abs(n),i=Math.sqrt(r),s=e.reduce((p,f)=>p+f*f,0),a=t.reduce((p,f)=>p+f*f,0),c=0;for(let p=0;p<e.length;p++){let f=e[p]-t[p];c+=f*f}let l=2*c,u=(1-s)*(1-a);if(u<=0)return 1/0;let d=l/u;return Math.acosh(1+d)/i}async searchBatch(e,t={}){let n=[];for(let r of e){let i=await this.search(r,t);n.push(i)}return n}async findInRadius(e,t,n="cosine"){return this.search(e,{metric:n,threshold:t,topK:this.embeddings.size})}};var Ze=class{config;constructor(e={}){if(this.config={curvature:e.curvature??-1,epsilon:e.epsilon??1e-7},this.config.curvature>=0)throw new G("HYPERBOLIC_ERROR","Curvature must be negative for hyperbolic space")}euclideanToPoincare(e){if(e.isHyperbolic)return e;let t=e.vector,n=this.norm(t);if(n<this.config.epsilon)return{...e,isHyperbolic:!0};let r=Math.abs(this.config.curvature),i=Math.sqrt(r),s=Math.tanh(i*n/2)/(i*n),a=t.map(l=>l*s),c=this.norm(a);if(c>=1-this.config.epsilon)throw new G("HYPERBOLIC_ERROR",`Poincar\xE9 ball constraint violated: norm = ${c}`);return{vector:a,dimensions:e.dimensions,model:e.model,isHyperbolic:!0}}poincareToEuclidean(e){if(!e.isHyperbolic)return e;let t=e.vector,n=this.norm(t);if(n<this.config.epsilon)return{...e,isHyperbolic:!1};let r=Math.abs(this.config.curvature),i=Math.sqrt(r),s=i*n;if(s>=1)throw new G("HYPERBOLIC_ERROR","Point is on or outside Poincar\xE9 ball boundary");let a=2/i*Math.atanh(s)/n;return{vector:t.map(l=>l*a),dimensions:e.dimensions,model:e.model,isHyperbolic:!1}}distance(e,t){if(e.dimensions!==t.dimensions)throw new G("DIMENSION_MISMATCH","Embeddings must have same dimensions");if(!e.isHyperbolic||!t.isHyperbolic)throw new G("HYPERBOLIC_ERROR","Both embeddings must be in hyperbolic space");let n=e.vector,r=t.vector,i=Math.abs(this.config.curvature),s=Math.sqrt(i),a=this.normSquared(n),c=this.normSquared(r),u=2*this.euclideanDistanceSquared(n,r),d=(1-a)*(1-c);if(d<=this.config.epsilon)return 1/0;let m=u/d;return Math.acosh(1+m)/s}midpoint(e,t){if(e.dimensions!==t.dimensions)throw new G("DIMENSION_MISMATCH","Embeddings must have same dimensions");if(!e.isHyperbolic||!t.isHyperbolic)throw new G("HYPERBOLIC_ERROR","Both embeddings must be in hyperbolic space");let n=e.vector,r=t.vector;return{vector:this.mobiusAddition(n,this.mobiusScalarMultiply(this.mobiusAddition(this.mobiusNegate(n),r),.5)),dimensions:e.dimensions,model:e.model,isHyperbolic:!0}}mobiusAddition(e,t){let n=Math.abs(this.config.curvature),r=this.dot(e,t),i=this.normSquared(e),s=this.normSquared(t),a=1+2*n*r+n*s,c=1-n*i,l=1+2*n*r+n*n*i*s;if(Math.abs(l)<this.config.epsilon)throw new G("HYPERBOLIC_ERROR","M\xF6bius addition denominator is zero");return e.map((d,m)=>(a*d+c*t[m])/l)}mobiusScalarMultiply(e,t){let n=Math.abs(this.config.curvature),r=Math.sqrt(n),i=this.norm(e);if(i<this.config.epsilon)return e;let s=r*i;if(Math.abs(s)>=1)throw new G("HYPERBOLIC_ERROR","M\xF6bius scalar multiplication out of bounds");let a=Math.tanh(t*Math.atanh(s))/(r*i);return e.map(c=>c*a)}mobiusNegate(e){return e.map(t=>-t)}projectToBall(e){let t=this.norm(e);if(t>=1-this.config.epsilon){let n=(1-this.config.epsilon)/t;return e.map(r=>r*n)}return e}norm(e){return Math.sqrt(this.normSquared(e))}normSquared(e){return e.reduce((t,n)=>t+n*n,0)}dot(e,t){return e.reduce((n,r,i)=>n+r*t[i],0)}euclideanDistanceSquared(e,t){return e.reduce((n,r,i)=>{let s=r-t[i];return n+s*s},0)}updateConfig(e){if(e.curvature!==void 0&&e.curvature>=0)throw new G("HYPERBOLIC_ERROR","Curvature must be negative");this.config={...this.config,...e}}getConfig(){return{...this.config}}};ge();var xt=class{generator;search;hyperbolic;isInitialized=!1;constructor(e={}){this.generator=new Ye(e.embedding),this.search=new Je,this.hyperbolic=new Ze(e.hyperbolic),e.autoInitialize!==!1&&this.initialize().catch(t=>{console.error("Failed to auto-initialize ONNX embeddings:",t)})}async initialize(){if(!this.isInitialized)try{await this.generator.initialize(),this.isInitialized=!0}catch(e){throw new G("RUNTIME_UNAVAILABLE","Failed to initialize ONNX embeddings adapter",e)}}async getHealth(){try{let e=this.generator.isReady();return{available:e,modelLoaded:e?this.getStats().currentModel:null,system:{memory:process.memoryUsage().heapUsed,threads:1}}}catch(e){return{available:!1,modelLoaded:null,error:e instanceof Error?e.message:"Unknown error",system:{memory:process.memoryUsage().heapUsed,threads:0}}}}async generateEmbedding(e){return await this.ensureInitialized(),this.generator.generate(e)}async generateBatch(e){return await this.ensureInitialized(),this.generator.generateBatch(e)}async generateAndStore(e,t){let n=await this.generateEmbedding(e),r={id:t?.id??this.generateId(),text:e,embedding:n,namespace:t?.namespace,metadata:t?.customData,createdAt:Date.now()};this.search.store(r);try{let i=Y();await i.initialize(),await i.vectorStore(r.id,r.embedding.vector,r.namespace??"onnx",{text:r.text,customData:r.metadata,createdAt:r.createdAt})}catch{}return r}async searchByText(e,t){let n=await this.generateEmbedding(e);return this.search.search(n,t)}async searchByEmbedding(e,t){return this.search.search(e,t)}async findMostSimilar(e,t){let n=await this.generateEmbedding(e);return this.search.findMostSimilar(n,t)}async compareSimilarity(e,t,n="cosine"){let[r,i]=await this.generateBatch({texts:[e,t]}).then(s=>s.embeddings);return this.search.calculateSimilarity(r.vector,i.vector,n)}storeEmbedding(e){this.search.store(e)}storeBatch(e){this.search.storeBatch(e)}removeEmbedding(e){return this.search.remove(e)}getEmbedding(e){return this.search.get(e)}getAllEmbeddings(e){return this.search.getAll(e)}clearEmbeddings(){this.search.clear()}toHyperbolic(e){return this.hyperbolic.euclideanToPoincare(e)}toEuclidean(e){return this.hyperbolic.poincareToEuclidean(e)}hyperbolicDistance(e,t){return this.hyperbolic.distance(e,t)}hyperbolicMidpoint(e,t){return this.hyperbolic.midpoint(e,t)}projectToBall(e){return this.hyperbolic.projectToBall(e)}getStats(){let e=this.generator.getStats(),t=this.search.getStats();return{totalGenerated:e.totalGenerated??0,cacheHits:e.cacheHits??0,cacheMisses:e.cacheMisses??0,totalSearches:t.searchCount,avgGenerationTime:e.avgGenerationTime??0,avgSearchTime:t.avgSearchTime,currentModel:e.currentModel??"all-MiniLM-L6-v2",vectorsStored:t.storedCount}}updateEmbeddingConfig(e){this.generator.updateConfig(e)}updateHyperbolicConfig(e){this.hyperbolic.updateConfig(e)}clearCaches(){this.generator.clearCache()}reset(){this.clearCaches(),this.clearEmbeddings()}async bridgeToMCPGenerate(e,t=!1){let n=await this.generateEmbedding(e);return t?this.toHyperbolic(n):n}async bridgeToMCPSearch(e,t){return this.searchByText(e,t)}async bridgeToMCPCompare(e,t,n="cosine"){return this.compareSimilarity(e,t,n)}async ensureInitialized(){this.isInitialized||await this.initialize()}generateId(){return`emb_${Date.now()}_${cu().slice(0,9)}`}isReady(){return this.isInitialized&&this.generator.isReady()}};function Pn(o){return new xt(o)}var Xr={enabled:!0,dbPath:".agentic-qe/memory.db",maxOutcomes:1e5,retentionDays:90,autoCleanup:!0,cleanupIntervalMs:3600*1e3};ge();M();te();var hu={enabled:!0,haikuThreshold:.8,sonnetThreshold:.4,includeHealthSnapshot:!1,enableLogging:!0},Yr=class{config;minCutService;constructor(e){this.config={...hu,...e},this.minCutService=ja()}route(e){let t=Date.now();if(!this.config.enabled)return this.createFallbackResult(e,t,"MinCut routing disabled");let n=e.agentTopology||this.config.defaultTopology;if(!n||n.length===0)return this.createFallbackResult(e,t,"No agent topology available for mincut analysis");try{let r=this.minCutService.computeRoutingTier(e.task,n),i=this.routingTierToModelTier(r.tier);e.isCritical&&i<2&&(i=2);let s=this.modelTierToLabel(i),a;if(this.config.includeHealthSnapshot){let u=e.taskGraph||this.minCutService.buildTaskGraphFromTopology(n);a=this.minCutService.getStructuralHealth(u)}let c=Date.now()-t,l={modelTier:i,tierLabel:s,lambda:r.lambda,normalizedLambda:r.normalizedLambda,confidence:r.confidence,rationale:r.rationale,usedMinCut:!0,healthSnapshot:a,decisionTimeMs:c};return this.config.enableLogging&&this.logDecision(l),l}catch(r){return this.createFallbackResult(e,t,`MinCut routing error: ${r instanceof Error?r.message:String(r)}`)}}getMinCutService(){return this.minCutService}isEnabled(){return this.config.enabled}routingTierToModelTier(e){switch(e){case 1:return 1;case 2:return 2;case 3:return 4;default:return 2}}modelTierToLabel(e){switch(e){case 0:return"Booster";case 1:return"Haiku";case 2:return"Sonnet";case 3:return"Sonnet-Extended";case 4:return"Opus";default:return"Sonnet"}}createFallbackResult(e,t,n){return{modelTier:(e.isCritical,2),tierLabel:"Sonnet",lambda:0,normalizedLambda:0,confidence:.3,rationale:`Fallback to Sonnet: ${n}`,usedMinCut:!1,decisionTimeMs:Date.now()-t}}logDecision(e){let t=e.usedMinCut?"MinCut":"Fallback";console.error(`[MinCutRouter] [${t}] Tier ${e.modelTier} (${e.tierLabel}) | Lambda: ${e.normalizedLambda.toFixed(3)} | Confidence: ${(e.confidence*100).toFixed(0)}% | Time: ${e.decisionTimeMs}ms`)}};function bo(o){return new Yr(o)}import{existsSync as yu}from"fs";import{join as vu}from"path";var xn=class{id="memory";name="Pattern Memory";priority=80;maxTokens=2e3;async gather(e){let t=[];try{let n=vu(process.cwd(),".agentic-qe","memory.db");if(!yu(n))return this.fallbackGather(e);let{openDatabase:r}=await import("./safe-db-QFKCVTIJ.js"),i=r(n,{readonly:!0});try{let s=this.extractDomainKeywords(e.taskDescription);if(s.length>0){let a=s.map(()=>"domain LIKE ?").join(" OR "),c=s.map(d=>`%${d}%`),u=i.prepare(`SELECT name, domain, description, confidence
375
366
  FROM qe_patterns
376
367
  WHERE ${a}
377
368
  ORDER BY confidence DESC
378
- LIMIT 10`).all(...c);if(d.length>0){let u=d.map(m=>`- **${m.name}** (${m.domain}, confidence: ${(m.confidence*100).toFixed(0)}%): ${m.description||"No description"}`).join(`
379
- `);t.push({sourceId:this.id,title:"Relevant Patterns from Learning Database",content:`Found ${d.length} relevant patterns:
369
+ LIMIT 10`).all(...c);if(u.length>0){let d=u.map(m=>`- **${m.name}** (${m.domain}, confidence: ${(m.confidence*100).toFixed(0)}%): ${m.description||"No description"}`).join(`
370
+ `);t.push({sourceId:this.id,title:"Relevant Patterns from Learning Database",content:`Found ${u.length} relevant patterns:
380
371
 
381
- ${u}`,estimatedTokens:Math.ceil(u.length/3.5),relevance:.8})}}}finally{i.close()}}catch{return this.fallbackGather(e)}return t.length===0?this.fallbackGather(e):t}fallbackGather(e){let t=[`Task: ${e.taskDescription}`,`Agent: ${e.agentType}`,`Files: ${e.targetFiles.join(", ")}`].join(`
382
- `);return[{sourceId:this.id,title:"Task Context",content:t,estimatedTokens:Math.ceil(t.length/3.5),relevance:.5}]}extractDomainKeywords(e){let t=[],n=e.toLowerCase(),r={"test-generation":["test","generate","create test","unit test","spec"],"coverage-analysis":["coverage","gap","branch","uncovered"],"security-compliance":["security","vulnerability","owasp","injection","auth"],"quality-assessment":["quality","review","code review","assessment"],"defect-intelligence":["defect","bug","regression","root cause"]};for(let[i,s]of Object.entries(r))s.some(a=>n.includes(a))&&t.push(i);return t.length>0?t:["test-generation"]}};var kn=class{constructor(e){this.cwd=e}cwd;id="git";name="Git History";priority=60;maxTokens=1500;async gather(e){let t=[];for(let n of e.targetFiles.slice(0,5))try{let r=(await ua(["log","--oneline","-5","--",n],{cwd:this.cwd??process.cwd(),timeout:5e3})).trim();if(r){let i=`Recent commits for ${n}:
383
- ${r}`;t.push({sourceId:this.id,title:`Git history: ${n}`,content:i,estimatedTokens:Math.ceil(i.length/3.5),relevance:.5})}}catch{}return t}};import{existsSync as Pu,readFileSync as xu}from"fs";import{basename as Yr,dirname as Au,join as Jr}from"path";var Mn=class{id="tests";name="Existing Tests";priority=70;maxTokens=2e3;async gather(e){let t=[];for(let n of e.targetFiles.slice(0,3)){let r=this.findTestPaths(n);for(let i of r)if(Pu(i))try{let a=xu(i,"utf-8").match(/(?:it|test|describe)\s*\(\s*['"`]([^'"`]+)['"`]/g)||[];if(a.length>0){let c=`Tests for ${Yr(n)} (${i}):
372
+ ${d}`,estimatedTokens:Math.ceil(d.length/3.5),relevance:.8})}}}finally{i.close()}}catch{return this.fallbackGather(e)}return t.length===0?this.fallbackGather(e):t}fallbackGather(e){let t=[`Task: ${e.taskDescription}`,`Agent: ${e.agentType}`,`Files: ${e.targetFiles.join(", ")}`].join(`
373
+ `);return[{sourceId:this.id,title:"Task Context",content:t,estimatedTokens:Math.ceil(t.length/3.5),relevance:.5}]}extractDomainKeywords(e){let t=[],n=e.toLowerCase(),r={"test-generation":["test","generate","create test","unit test","spec"],"coverage-analysis":["coverage","gap","branch","uncovered"],"security-compliance":["security","vulnerability","owasp","injection","auth"],"quality-assessment":["quality","review","code review","assessment"],"defect-intelligence":["defect","bug","regression","root cause"]};for(let[i,s]of Object.entries(r))s.some(a=>n.includes(a))&&t.push(i);return t.length>0?t:["test-generation"]}};var An=class{constructor(e){this.cwd=e}cwd;id="git";name="Git History";priority=60;maxTokens=1500;async gather(e){let t=[];for(let n of e.targetFiles.slice(0,5))try{let r=(await da(["log","--oneline","-5","--",n],{cwd:this.cwd??process.cwd(),timeout:5e3})).trim();if(r){let i=`Recent commits for ${n}:
374
+ ${r}`;t.push({sourceId:this.id,title:`Git history: ${n}`,content:i,estimatedTokens:Math.ceil(i.length/3.5),relevance:.5})}}catch{}return t}};import{existsSync as bu,readFileSync as Cu}from"fs";import{basename as Jr,dirname as Su,join as Zr}from"path";var kn=class{id="tests";name="Existing Tests";priority=70;maxTokens=2e3;async gather(e){let t=[];for(let n of e.targetFiles.slice(0,3)){let r=this.findTestPaths(n);for(let i of r)if(bu(i))try{let a=Cu(i,"utf-8").match(/(?:it|test|describe)\s*\(\s*['"`]([^'"`]+)['"`]/g)||[];if(a.length>0){let c=`Tests for ${Jr(n)} (${i}):
384
375
  ${a.join(`
385
- `)}`;t.push({sourceId:this.id,title:`Tests: ${Yr(n)}`,content:c,estimatedTokens:Math.ceil(c.length/3.5),relevance:.8})}}catch{}}return t}findTestPaths(e){let t=Yr(e).replace(/\.(ts|js|tsx|jsx)$/,""),n=Au(e),r=[".test.ts",".spec.ts",".test.js",".spec.js"],i=[];for(let s of r)i.push(Jr(n,`${t}${s}`)),i.push(Jr(n,"__tests__",`${t}${s}`)),i.push(Jr(n,"..","tests",`${t}${s}`));return i}};import{existsSync as ku,readFileSync as Mu}from"fs";import{join as Zr,basename as Iu}from"path";var In=class{id="coverage";name="Coverage Data";priority=50;maxTokens=1e3;async gather(e){let t=[],n=[Zr(process.cwd(),"coverage","coverage-summary.json"),Zr(process.cwd(),"coverage","coverage-final.json"),Zr(process.cwd(),".coverage","coverage-summary.json")];for(let r of n)if(ku(r))try{let i=Mu(r,"utf-8"),s=JSON.parse(i),a=[];for(let c of e.targetFiles){let l=Iu(c);for(let[d,u]of Object.entries(s))if(d.includes(l)&&u&&typeof u=="object"){let m=u,p=m.lines?.pct??m.statements?.pct,g=m.branches?.pct,f=m.functions?.pct;p!==void 0&&a.push(`${l}: lines=${p}%${g!==void 0?`, branches=${g}%`:""}${f!==void 0?`, functions=${f}%`:""}`)}}if(a.length>0){let c=`Coverage for target files:
376
+ `)}`;t.push({sourceId:this.id,title:`Tests: ${Jr(n)}`,content:c,estimatedTokens:Math.ceil(c.length/3.5),relevance:.8})}}catch{}}return t}findTestPaths(e){let t=Jr(e).replace(/\.(ts|js|tsx|jsx)$/,""),n=Su(e),r=[".test.ts",".spec.ts",".test.js",".spec.js"],i=[];for(let s of r)i.push(Zr(n,`${t}${s}`)),i.push(Zr(n,"__tests__",`${t}${s}`)),i.push(Zr(n,"..","tests",`${t}${s}`));return i}};import{existsSync as Tu,readFileSync as Eu}from"fs";import{join as ei,basename as wu}from"path";var Mn=class{id="coverage";name="Coverage Data";priority=50;maxTokens=1e3;async gather(e){let t=[],n=[ei(process.cwd(),"coverage","coverage-summary.json"),ei(process.cwd(),"coverage","coverage-final.json"),ei(process.cwd(),".coverage","coverage-summary.json")];for(let r of n)if(Tu(r))try{let i=Eu(r,"utf-8"),s=JSON.parse(i),a=[];for(let c of e.targetFiles){let l=wu(c);for(let[u,d]of Object.entries(s))if(u.includes(l)&&d&&typeof d=="object"){let m=d,p=m.lines?.pct??m.statements?.pct,f=m.branches?.pct,g=m.functions?.pct;p!==void 0&&a.push(`${l}: lines=${p}%${f!==void 0?`, branches=${f}%`:""}${g!==void 0?`, functions=${g}%`:""}`)}}if(a.length>0){let c=`Coverage for target files:
386
377
  ${a.join(`
387
- `)}`;t.push({sourceId:this.id,title:"File Coverage Data",content:c,estimatedTokens:Math.ceil(c.length/3.5),relevance:.6})}if(s.total&&typeof s.total=="object"){let c=s.total,l=`Project coverage: lines=${c.lines?.pct??"?"}%, branches=${c.branches?.pct??"?"}%, functions=${c.functions?.pct??"?"}%`;t.push({sourceId:this.id,title:"Project Coverage Summary",content:l,estimatedTokens:Math.ceil(l.length/3.5),relevance:.4})}break}catch{continue}return t}};import{existsSync as Du}from"fs";import{join as _u}from"path";var Dn=class{id="requirements";name="Requirements Traceability";priority=75;maxTokens=2e3;async gather(e){let t=[];try{let n=_u(process.cwd(),".agentic-qe","memory.db");if(!Du(n))return this.fallbackGather(e);let{openDatabase:r}=await import("./safe-db-RZPQGLGQ.js"),i=r(n,{readonly:!0});try{if(!i.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='qe_patterns'").get())return this.fallbackGather(e);let a=e.targetFiles.map(l=>`%${l.split("/").pop()}%`);if(a.length>0){let l=a.map(()=>"description LIKE ?").join(" OR "),u=i.prepare(`SELECT name, domain, description, confidence
378
+ `)}`;t.push({sourceId:this.id,title:"File Coverage Data",content:c,estimatedTokens:Math.ceil(c.length/3.5),relevance:.6})}if(s.total&&typeof s.total=="object"){let c=s.total,l=`Project coverage: lines=${c.lines?.pct??"?"}%, branches=${c.branches?.pct??"?"}%, functions=${c.functions?.pct??"?"}%`;t.push({sourceId:this.id,title:"Project Coverage Summary",content:l,estimatedTokens:Math.ceil(l.length/3.5),relevance:.4})}break}catch{continue}return t}};import{existsSync as Ru}from"fs";import{join as Pu}from"path";var In=class{id="requirements";name="Requirements Traceability";priority=75;maxTokens=2e3;async gather(e){let t=[];try{let n=Pu(process.cwd(),".agentic-qe","memory.db");if(!Ru(n))return this.fallbackGather(e);let{openDatabase:r}=await import("./safe-db-QFKCVTIJ.js"),i=r(n,{readonly:!0});try{if(!i.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='qe_patterns'").get())return this.fallbackGather(e);let a=e.targetFiles.map(l=>`%${l.split("/").pop()}%`);if(a.length>0){let l=a.map(()=>"description LIKE ?").join(" OR "),d=i.prepare(`SELECT name, domain, description, confidence
388
379
  FROM qe_patterns
389
380
  WHERE domain LIKE '%requirement%'
390
381
  AND (${l})
391
382
  ORDER BY confidence DESC
392
- LIMIT 10`).all(...a);if(u.length>0){let m=u.map(p=>`- **${p.name}** (confidence: ${(p.confidence*100).toFixed(0)}%): ${p.description||"No description"}`).join(`
393
- `);t.push({sourceId:this.id,title:"Linked Requirements",content:`Found ${u.length} requirements linked to target files:
383
+ LIMIT 10`).all(...a);if(d.length>0){let m=d.map(p=>`- **${p.name}** (confidence: ${(p.confidence*100).toFixed(0)}%): ${p.description||"No description"}`).join(`
384
+ `);t.push({sourceId:this.id,title:"Linked Requirements",content:`Found ${d.length} requirements linked to target files:
394
385
 
395
- ${m}`,estimatedTokens:Math.ceil(m.length/3.5),relevance:.75})}}let c=this.extractRequirementKeywords(e.taskDescription);if(c.length>0){let l=c.map(()=>"name LIKE ? OR description LIKE ?").join(" OR "),d=c.flatMap(p=>[`%${p}%`,`%${p}%`]),m=i.prepare(`SELECT DISTINCT name, domain, description, confidence
386
+ ${m}`,estimatedTokens:Math.ceil(m.length/3.5),relevance:.75})}}let c=this.extractRequirementKeywords(e.taskDescription);if(c.length>0){let l=c.map(()=>"name LIKE ? OR description LIKE ?").join(" OR "),u=c.flatMap(p=>[`%${p}%`,`%${p}%`]),m=i.prepare(`SELECT DISTINCT name, domain, description, confidence
396
387
  FROM qe_patterns
397
388
  WHERE domain LIKE '%requirement%'
398
389
  AND (${l})
399
390
  ORDER BY confidence DESC
400
- LIMIT 5`).all(...d);if(m.length>0){let p=m.map(g=>`- **${g.name}**: ${g.description||"No description"}`).join(`
391
+ LIMIT 5`).all(...u);if(m.length>0){let p=m.map(f=>`- **${f.name}**: ${f.description||"No description"}`).join(`
401
392
  `);t.push({sourceId:this.id,title:"Related Requirements",content:`Requirements related to task:
402
393
 
403
- ${p}`,estimatedTokens:Math.ceil(p.length/3.5),relevance:.6})}}}finally{i.close()}}catch{return this.fallbackGather(e)}return t.length===0?this.fallbackGather(e):t}fallbackGather(e){let n=`No requirements traceability data found for: ${e.targetFiles.join(", ")}. Consider running requirements validation to establish traceability.`;return[{sourceId:this.id,title:"Requirements Context",content:n,estimatedTokens:Math.ceil(n.length/3.5),relevance:.3}]}extractRequirementKeywords(e){let t=[],n=e.toLowerCase(),r=n.match(/(?:req|us|story|epic|feat)-?\d+/gi)||[];t.push(...r);let i=["authentication","authorization","payment","registration","notification","search","api","login","user","admin","report","dashboard","import","export","integration"];for(let s of i)n.includes(s)&&t.push(s);return t.slice(0,5)}};import{existsSync as Ou}from"fs";import{join as Nu}from"path";var _n=class{id="defects";name="Defect Intelligence";priority=65;maxTokens=1500;async gather(e){let t=[];try{let n=Nu(process.cwd(),".agentic-qe","memory.db");if(!Ou(n))return[];let{openDatabase:r}=await import("./safe-db-RZPQGLGQ.js"),i=r(n,{readonly:!0});try{if(!i.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='qe_patterns'").get())return[];let a=e.targetFiles.map(l=>`%${l.split("/").pop()}%`);if(a.length>0){let l=a.map(()=>"description LIKE ?").join(" OR "),u=i.prepare(`SELECT name, domain, description, confidence
394
+ ${p}`,estimatedTokens:Math.ceil(p.length/3.5),relevance:.6})}}}finally{i.close()}}catch{return this.fallbackGather(e)}return t.length===0?this.fallbackGather(e):t}fallbackGather(e){let n=`No requirements traceability data found for: ${e.targetFiles.join(", ")}. Consider running requirements validation to establish traceability.`;return[{sourceId:this.id,title:"Requirements Context",content:n,estimatedTokens:Math.ceil(n.length/3.5),relevance:.3}]}extractRequirementKeywords(e){let t=[],n=e.toLowerCase(),r=n.match(/(?:req|us|story|epic|feat)-?\d+/gi)||[];t.push(...r);let i=["authentication","authorization","payment","registration","notification","search","api","login","user","admin","report","dashboard","import","export","integration"];for(let s of i)n.includes(s)&&t.push(s);return t.slice(0,5)}};import{existsSync as xu}from"fs";import{join as Au}from"path";var Dn=class{id="defects";name="Defect Intelligence";priority=65;maxTokens=1500;async gather(e){let t=[];try{let n=Au(process.cwd(),".agentic-qe","memory.db");if(!xu(n))return[];let{openDatabase:r}=await import("./safe-db-QFKCVTIJ.js"),i=r(n,{readonly:!0});try{if(!i.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='qe_patterns'").get())return[];let a=e.targetFiles.map(l=>`%${l.split("/").pop()}%`);if(a.length>0){let l=a.map(()=>"description LIKE ?").join(" OR "),d=i.prepare(`SELECT name, domain, description, confidence
404
395
  FROM qe_patterns
405
396
  WHERE domain LIKE '%defect%'
406
397
  AND (${l})
407
398
  ORDER BY confidence DESC
408
- LIMIT 8`).all(...a);if(u.length>0){let m=u.map(p=>`- **${p.name}** (confidence: ${(p.confidence*100).toFixed(0)}%): ${p.description||"No description"}`).join(`
409
- `);t.push({sourceId:this.id,title:"Historical Defect Patterns",content:`Found ${u.length} defect patterns for target files:
399
+ LIMIT 8`).all(...a);if(d.length>0){let m=d.map(p=>`- **${p.name}** (confidence: ${(p.confidence*100).toFixed(0)}%): ${p.description||"No description"}`).join(`
400
+ `);t.push({sourceId:this.id,title:"Historical Defect Patterns",content:`Found ${d.length} defect patterns for target files:
410
401
 
411
- ${m}`,estimatedTokens:Math.ceil(m.length/3.5),relevance:.7})}}let c=this.extractDefectKeywords(e.taskDescription);if(c.length>0){let l=c.map(()=>"description LIKE ?").join(" OR "),d=c.map(p=>`%${p}%`),m=i.prepare(`SELECT name, domain, description, confidence
402
+ ${m}`,estimatedTokens:Math.ceil(m.length/3.5),relevance:.7})}}let c=this.extractDefectKeywords(e.taskDescription);if(c.length>0){let l=c.map(()=>"description LIKE ?").join(" OR "),u=c.map(p=>`%${p}%`),m=i.prepare(`SELECT name, domain, description, confidence
412
403
  FROM qe_patterns
413
404
  WHERE (domain LIKE '%defect%' OR domain LIKE '%regression%')
414
405
  AND (${l})
415
406
  ORDER BY confidence DESC
416
- LIMIT 5`).all(...d);if(m.length>0){let p=m.map(g=>`- **${g.name}**: ${g.description||"No description"}`).join(`
407
+ LIMIT 5`).all(...u);if(m.length>0){let p=m.map(f=>`- **${f.name}**: ${f.description||"No description"}`).join(`
417
408
  `);t.push({sourceId:this.id,title:"Regression Hotspots",content:`Known regression patterns:
418
409
 
419
- ${p}`,estimatedTokens:Math.ceil(p.length/3.5),relevance:.6})}}}finally{i.close()}}catch{return[]}return t}extractDefectKeywords(e){let t=[],n=e.toLowerCase(),r=["bug","defect","regression","fix","crash","error","null","undefined","timeout","race condition","deadlock","memory leak","overflow","injection","broken"];for(let i of r)n.includes(i)&&t.push(i);return t.slice(0,5)}};var Fu=8e3,Lu=300*1e3;function qu(){return[new An,new Dn,new Mn,new _n,new kn,new In]}var On=class{sources;maxTokenBudget;cache=new Map;cacheTtl;constructor(e){this.sources=e?.sources||qu(),this.maxTokenBudget=e?.maxTokenBudget||Fu,this.cacheTtl=e?.cacheTtlMs||Lu}async compile(e){let t=Date.now(),n=this.buildCacheKey(e),r=this.cache.get(n);if(r&&Date.now()-r.timestamp<this.cacheTtl)return r.result;let i=e.maxTokenBudget||this.maxTokenBudget,s=await Promise.allSettled(this.sources.map(async p=>{try{let g=await p.gather(e);return{sourceId:p.id,sourceName:p.name,priority:p.priority,fragments:g}}catch{return{sourceId:p.id,sourceName:p.name,priority:p.priority,fragments:[]}}})),a=[],c=[];for(let p of s)if(p.status==="fulfilled"){let{sourceId:g,priority:f,fragments:h}=p.value;if(h.length>0){c.push(g);for(let v of h)a.push({...v,sourcePriority:f})}}a.sort((p,g)=>p.sourcePriority!==g.sourcePriority?g.sourcePriority-p.sourcePriority:g.relevance-p.relevance);let l=[],d=0;for(let p of a)if(d+p.estimatedTokens<=i){let{sourcePriority:g,...f}=p;l.push(f),d+=p.estimatedTokens}let m={summary:this.generateSummary(e,l,c),fragments:l,totalTokens:d,sources:c,timestamp:new Date().toISOString(),duration:Date.now()-t};return this.cache.set(n,{result:m,timestamp:Date.now()}),m}clearCache(){this.cache.clear()}getCacheStats(){return{size:this.cache.size,ttlMs:this.cacheTtl}}buildCacheKey(e){let t=[...e.targetFiles].sort();return JSON.stringify([e.agentType,t,e.taskDescription.slice(0,100)])}generateSummary(e,t,n){return[`Context compiled for ${e.agentType} agent.`,`Target: ${e.targetFiles.length} file(s).`,`Sources: ${n.join(", ")}.`,`Fragments: ${t.length} (${t.reduce((r,i)=>r+i.estimatedTokens,0)} est. tokens).`].join(" ")}};function To(o){let e=[];e.push("## Compiled Context"),e.push(""),e.push(o.summary),e.push("");for(let t of o.fragments)e.push(`### ${t.title}`),e.push(t.content),e.push("");return e.push(`_Context compiled: ${o.timestamp} (${o.duration}ms)_`),e.join(`
420
- `)}var $u={enabled:!0,enableAgentBooster:!0,enableLogging:!0,maxLogEntries:1e3},ei=class o{static instance=null;static initializationPromise=null;config;modelRouter;minCutRouter;routingLog=[];contextCompiler;disposed=!1;constructor(e,t){this.config=e,this.modelRouter=t,this.contextCompiler=new On,this.minCutRouter=So({enableLogging:e.enableLogging})}static async getInstance(e){if(o.instance&&!o.instance.disposed)return o.instance;if(o.initializationPromise)return o.initializationPromise;o.initializationPromise=o.create(e);try{return o.instance=await o.initializationPromise,o.instance}finally{o.initializationPromise=null}}static async create(e){let t={...$u,...e},n;t.enableAgentBooster?n=await gn(t.modelRouterConfig):n=pn(t.modelRouterConfig);let r=new o(t,n);return t.enableLogging&&console.error(`[TaskRouter] Initialized with Agent Booster: ${t.enableAgentBooster}`),r}async routeTask(e){if(!this.config.enabled)return this.createDisabledResult(e);if(this.disposed)throw new Error("TaskRouterService has been disposed");let t=null;if(this.minCutRouter.isEnabled()&&e.agentTopology)try{t=this.minCutRouter.route({task:e.task,domain:e.domain,agentType:e.agentType,agentTopology:e.agentTopology,isCritical:e.isCritical})}catch(g){this.config.enableLogging&&console.error(`[TaskRouter] MinCut routing failed, falling back to heuristic: ${g instanceof Error?g.message:String(g)}`)}let n={task:e.task,codeContext:e.codeContext,filePaths:e.filePaths,manualTier:e.manualTier,isCritical:e.isCritical,agentType:e.agentType,domain:e.domain,metadata:e.metadata},r=await this.modelRouter.route(n),i=r;if(t&&t.usedMinCut){let g=t.modelTier;g!==r.tier&&(i={...r,tier:g,rationale:`[MinCut] ${t.rationale} (heuristic suggested Tier ${r.tier})`},this.config.enableLogging&&console.error(`[TaskRouter] MinCut override: Tier ${r.tier} -> Tier ${g} (lambda=${t.normalizedLambda.toFixed(3)})`))}let s=Ke[i.tier],a=this.mapTierToStrategy(i.tier),c={timestamp:i.metadata.timestamp,taskDescription:e.task.slice(0,200),requestedTier:e.manualTier,selectedTier:i.tier,modelId:i.modelId,complexity:i.complexityAnalysis.overall,confidence:i.confidence,wasDowngraded:i.budgetDecision.wasDowngraded,agentBoosterEligible:i.agentBoosterEligible,decisionTimeMs:i.metadata.decisionTimeMs,rationale:i.rationale};this.addLogEntry(c),this.config.enableLogging&&this.logRoutingDecision(c);let l=e.patternHints,d=l&&l.length>0?this.formatPatternContext(l):void 0,u=e.agentType,m=u?_r(u)||_r(u.replace("v3-qe-","qe-")):void 0,p;if(e.filePaths&&e.filePaths.length>0)try{let g=await this.contextCompiler.compile({targetFiles:e.filePaths,agentType:e.agentType||"unknown",taskDescription:e.task});p=To(g)}catch{}return{decision:i,executionStrategy:a,useAgentBooster:i.agentBoosterEligible,modelId:i.modelId,tierInfo:{tier:i.tier,name:s.name,typicalLatencyMs:s.typicalLatencyMs,relativeCost:s.relativeCost},logEntry:c,patternHints:l,patternContext:d,overlayConfig:m,compiledContext:p}}formatPatternContext(e){if(!e||e.length===0)return"";let t=["--- Relevant Patterns from Learning ---",""];for(let n of e){let r=n.canReuse?" [REUSABLE]":"";t.push(`[${n.name}]${r}`,` ${n.description}`,` Similarity: ${(n.similarity*100).toFixed(0)}% | Confidence: ${(n.confidence*100).toFixed(0)}%`,"")}return t.push("Use these patterns as guidance when applicable."),t.join(`
421
- `)}async quickRoute(e){return this.routeTask({task:e})}async routeBatch(e){return Promise.all(e.map(t=>this.routeTask(t)))}getMetrics(){return this.modelRouter.getMetrics()}getRoutingLog(e=100,t=0){return this.routingLog.slice(t,t+e)}getRoutingStats(){let e=this.routingLog;if(e.length===0)return this.createEmptyStats();let t=new Map,n=0,r=0,i=0,s=0;for(let c of e)t.set(c.selectedTier,(t.get(c.selectedTier)||0)+1),n+=c.complexity,r+=c.decisionTimeMs,c.wasDowngraded&&i++,c.agentBoosterEligible&&s++;let a={};for(let[c,l]of t)a[c]=l/e.length;return{totalRouted:e.length,avgComplexity:n/e.length,avgDecisionTimeMs:r/e.length,downgradeRate:i/e.length,agentBoosterRate:s/e.length,tierDistribution:a,period:{start:e[0].timestamp,end:e[e.length-1].timestamp}}}reset(){this.routingLog.length=0,this.modelRouter.resetMetrics(),this.config.enableLogging&&console.error("[TaskRouter] Reset routing log and metrics")}async dispose(){this.disposed||(this.disposed=!0,await this.modelRouter.dispose(),o.instance=null,this.config.enableLogging&&console.error("[TaskRouter] Disposed"))}isEnabled(){return this.config.enabled&&!this.disposed}mapTierToStrategy(e){switch(e){case 0:return"booster";case 1:return"haiku";case 2:return"sonnet";case 3:return"sonnet-extended";case 4:return"opus";default:return"sonnet"}}addLogEntry(e){this.routingLog.push(e),this.routingLog.length>this.config.maxLogEntries&&this.routingLog.splice(0,this.routingLog.length-this.config.maxLogEntries)}logRoutingDecision(e){let t=Ke[e.selectedTier].name,n=e.agentBoosterEligible?"[AgentBooster]":`[Tier${e.selectedTier}]`;console.error(`[TaskRouter] ${n} ${t} | Complexity: ${e.complexity.toFixed(0)} | Confidence: ${(e.confidence*100).toFixed(0)}% | Time: ${e.decisionTimeMs.toFixed(1)}ms`+(e.wasDowngraded?" [DOWNGRADED]":""))}createDisabledResult(e){let n=Ke[2],r={timestamp:new Date,taskDescription:e.task.slice(0,200),selectedTier:2,modelId:n.exampleModels[0],complexity:50,confidence:.5,wasDowngraded:!1,agentBoosterEligible:!1,decisionTimeMs:0,rationale:"Routing disabled - using default tier"};return{decision:{tier:2,modelId:n.exampleModels[0],complexityAnalysis:{overall:50,codeComplexity:50,reasoningComplexity:50,scopeComplexity:50,confidence:.5,signals:{hasArchitectureScope:!1,hasSecurityScope:!1,requiresMultiStepReasoning:!1,requiresCrossDomainCoordination:!1,isMechanicalTransform:!1,requiresCreativity:!1,keywordMatches:{simple:[],moderate:[],complex:[],critical:[]}},recommendedTier:2,alternateTiers:[],explanation:"Routing disabled"},budgetDecision:{allowed:!0,reason:"Routing disabled",requestedTier:2,approvedTier:2,wasDowngraded:!1,estimatedCostUsd:0,currentUsage:{tier:2,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,budgetUtilization:0,isExceeded:!1,isNearLimit:!1,resetTime:new Date,remainingBudgetUsd:100,remainingRequestsThisHour:100,remainingRequestsToday:1e3},warnings:[]},confidence:.5,rationale:"Routing disabled - using default tier",agentBoosterEligible:!1,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:0,fromCache:!1},warnings:["Routing is disabled"]},executionStrategy:"sonnet",useAgentBooster:!1,modelId:n.exampleModels[0],tierInfo:{tier:2,name:n.name,typicalLatencyMs:n.typicalLatencyMs,relativeCost:n.relativeCost},logEntry:r}}createEmptyStats(){let e=new Date;return{totalRouted:0,avgComplexity:0,avgDecisionTimeMs:0,downgradeRate:0,agentBoosterRate:0,tierDistribution:{},period:{start:e,end:e}}}};async function Nn(o){return ei.getInstance(o)}Zt();Yt();var ti=ye("CoherenceActionGate"),Gu={structuralPermit:.4,structuralDeny:.2,shiftPermit:.5,shiftDeny:.25,evidencePermit:.5,evidenceDeny:.2,combinedPermit:.5,combinedDeny:.25},ni={structural:.3,shift:.35,evidence:.35},ju={low:1,medium:.9,high:.75,critical:.6},Eo=1e3,Fn=class{thresholds;advisoryMode;nativeAvailable=null;evaluationHistory=[];permitCount=0;deferCount=0;denyCount=0;totalCombinedScore=0;totalStructuralScore=0;totalShiftScore=0;totalEvidenceScore=0;cusumHigh=0;cusumLow=0;cusumMean=.7;cusumK=.05;cusumH=4;cusumSampleCount=0;cusumAlertActive=!1;constructor(e){this.advisoryMode=e?.advisory??!0,this.thresholds={...Gu,...e?.thresholds}}evaluate(e){let t=this.computeStructuralScore(e),n=this.computeShiftScore(e),r=this.computeEvidenceScore(e),i=t*ni.structural+n*ni.shift+r*ni.evidence,s=ju[e.riskLevel]??1,a=i*s,c=this.computeDecision(t,n,r,a),l=this.buildReasoning(e,c,t,n,r,a),d={decision:c,structuralScore:t,shiftScore:n,evidenceScore:r,combinedScore:a,reasoning:l,advisory:this.advisoryMode};return this.recordEvaluation(d),ti.debug("Action gate evaluation",{action:e.type,domain:e.domain,decision:c,combinedScore:a,advisory:this.advisoryMode}),d}getStatistics(){let e=this.evaluationHistory.length;return{totalEvaluations:e,permitCount:this.permitCount,deferCount:this.deferCount,denyCount:this.denyCount,averageCombinedScore:e>0?this.totalCombinedScore/e:0,averageStructuralScore:e>0?this.totalStructuralScore/e:0,averageShiftScore:e>0?this.totalShiftScore/e:0,averageEvidenceScore:e>0?this.totalEvidenceScore/e:0,advisoryMode:this.advisoryMode}}configureThresholds(e){this.thresholds={...this.thresholds,...e},ti.info("Action gate thresholds updated",{thresholds:this.thresholds})}getThresholds(){return{...this.thresholds}}isAdvisory(){return this.advisoryMode}getEvaluationHistory(){return[...this.evaluationHistory]}resetStatistics(){this.evaluationHistory=[],this.permitCount=0,this.deferCount=0,this.denyCount=0,this.totalCombinedScore=0,this.totalStructuralScore=0,this.totalShiftScore=0,this.totalEvidenceScore=0,this.resetCusum()}resetCusum(){this.cusumHigh=0,this.cusumLow=0,this.cusumAlertActive=!1,this.cusumSampleCount=0}computeStructuralScore(e){let t=.5;["generate-test","modify-code","analyze-coverage","scan-security","assess-quality","validate-contracts","test-accessibility","execute-tests","index-code","predict-defects","validate-requirements","deploy","run-chaos","optimize-learning"].includes(e.type)&&(t+=.2),JSON.stringify(e.context).toLowerCase().includes(e.domain.toLowerCase())&&(t+=.15);let i=Object.keys(e.context);return i.length>=3?t+=.15:i.length>=1&&(t+=.05),Math.min(Math.max(t,0),1)}computeShiftScore(e){let t=e.confidence,r={low:.25,medium:.5,high:.75,critical:1}[e.riskLevel]??.5,i=Math.max(0,r-e.confidence);t-=i*.3;let s=e.context;(s.stale===!0||s.outdated===!0)&&(t-=.3),(s.distributionShift===!0||s.contextChanged===!0)&&(t-=.4),this.cusumSampleCount++;let a=e.confidence;return this.cusumHigh=Math.max(0,this.cusumHigh+(a-this.cusumMean)-this.cusumK),this.cusumLow=Math.max(0,this.cusumLow-(a-this.cusumMean)-this.cusumK),this.cusumHigh>this.cusumH||this.cusumLow>this.cusumH?(t-=.2,this.cusumAlertActive||(this.cusumAlertActive=!0,ti.warn("CUSUM shift detected",{cusumHigh:this.cusumHigh,cusumLow:this.cusumLow}))):this.cusumAlertActive=!1,Math.min(Math.max(t,0),1)}computeEvidenceScore(e){let t=.5,n=e.context,r=["testResults","coverageData","securityScan","qualityReport","peerReview","analysisResult","validationPassed","precedent","historicalSuccess"];for(let s of r)n[s]!==void 0&&n[s]!==null&&(t*=1+.15);let i=["errors","failures","warnings","regressions","conflictingResults","noTestCoverage"];for(let s of i)n[s]!==void 0&&n[s]!==null&&(t*=1-.18);if((e.riskLevel==="critical"||e.riskLevel==="high")&&!n.testResults&&!n.peerReview&&(t-=.15),typeof n.evidenceCount=="number"){let s=n.evidenceCount;t+=Math.min(s*.05,.2)}return Math.min(Math.max(t,0),1)}computeDecision(e,t,n,r){return e<this.thresholds.structuralDeny||t<this.thresholds.shiftDeny||n<this.thresholds.evidenceDeny||r<this.thresholds.combinedDeny?"DENY":e>=this.thresholds.structuralPermit&&t>=this.thresholds.shiftPermit&&n>=this.thresholds.evidencePermit&&r>=this.thresholds.combinedPermit?"PERMIT":"DEFER"}buildReasoning(e,t,n,r,i,s){let a=[];if(a.push(`Decision: ${t} for ${e.type} (${e.domain}).`),a.push(`Scores: structural=${n.toFixed(2)}, shift=${r.toFixed(2)}, evidence=${i.toFixed(2)}, combined=${s.toFixed(2)}.`),t==="DENY")n<this.thresholds.structuralDeny&&a.push("Structural filter failed: action does not fit codebase graph."),r<this.thresholds.shiftDeny&&a.push("Shift filter failed: significant context distribution shift detected."),i<this.thresholds.evidenceDeny&&a.push("Evidence filter failed: insufficient evidence to justify action."),s<this.thresholds.combinedDeny&&a.push("Combined score below minimum threshold.");else if(t==="DEFER"){let c=[];n<this.thresholds.structuralPermit&&c.push("structural"),r<this.thresholds.shiftPermit&&c.push("shift"),i<this.thresholds.evidencePermit&&c.push("evidence"),c.length>0&&a.push(`Marginal filters: ${c.join(", ")}. Human review recommended.`)}return this.advisoryMode&&a.push("(Advisory mode: decision logged only, not enforced.)"),a.join(" ")}recordEvaluation(e){switch(this.evaluationHistory.push(e),this.evaluationHistory.length>Eo&&(this.evaluationHistory=this.evaluationHistory.slice(-Eo)),this.totalCombinedScore+=e.combinedScore,this.totalStructuralScore+=e.structuralScore,this.totalShiftScore+=e.shiftScore,this.totalEvidenceScore+=e.evidenceScore,e.decision){case"PERMIT":this.permitCount++;break;case"DEFER":this.deferCount++;break;case"DENY":this.denyCount++;break}}};function wo(o){return new Fn(o)}function Ro(o,e,t,n,r,i){if(!Ge().useCoherenceActionGate)return null;let a=i??new Fn,c={type:o,domain:e,confidence:t,context:r,riskLevel:n};return a.evaluate(c)}import*as Ln from"fs/promises";D();Pl();function zu(o){return o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Uu(o,e,t,n){if(!t)return{testCode:o,sourceFile:e};let r=m=>m.replace(/\.[a-z]+$/i,""),i=n?n.match(/\.(ts|tsx|js|jsx|mjs|cjs)$/i)?r(n):n:"./module-under-test",s=n?"":`// TODO: replace './module-under-test' with the actual import path of the module under test
422
- `,a=r(t),c=zu(a),l=new RegExp(c+"(?:\\.[a-zA-Z]+){0,2}","g");return{testCode:o&&s+o.replace(l,i),sourceFile:e===t&&n||e}}async function Bu(o,e){let t=zs();try{let{command:n,args:r}=js(o.map(p=>Or(p)),t.path),i=await ln(n,r,{cwd:e,timeout:12e4,env:{...process.env,...Gs}}),s=[i.stderr,i.stdout].filter(Boolean).join(`
423
- `);if(i.error||i.signal){let p=i.error?.message??`Terminated by ${i.signal}`;return L(new De(`pytest could not complete: ${sn(`${p}
424
- ${s}`)}`))}let a=Us(t.read(),o,i.status,s,n);if(!a.success)return a;let c=a.value.tests.map(p=>{let g=p.failureMessage&&Zs(p.failureMessage);return{name:p.name,file:p.file,status:p.status,...p.duration!==void 0?{duration:p.duration}:{},...g?{failureMessage:g}:{}}}),{total:l,passed:d,failed:u,skipped:m}=a.value;return F({total:l,passed:d,failed:u,skipped:m,testCases:c})}finally{t.cleanup()}}async function Hu(o,e){if(o.some(an))return Bu(o,e);let t={cwd:e,timeout:12e4},n=()=>ln("npx",["jest",...o.map(c=>Bs(c)),"--json"],t),r="vitest",i,s="";if(Hs(e)==="jest")r="jest",i=await n(),s=i.stdout||"";else{let c=ta();try{i=await ln("npx",["vitest","run",...o.map(l=>Or(l)),"--reporter=json",...c.args],t),s=i.error||i.signal?"":c.read(i.stdout||"")??""}finally{c.cleanup()}!s.includes("{")&&i.status!==0&&!i.error&&!i.signal&&(r="jest",i=await n(),s=i.stdout||"")}let a=[i.error?.message,i.signal&&`Terminated by ${i.signal}`,i.stderr,s].filter(Boolean).join(`
425
- `);if(i.error)return L(new De(`${r} could not complete: ${sn(a)}`));try{let c=s.indexOf("{");if(c>=0){let l=JSON.parse(s.slice(c));if(l.testResults){let d=l.numTotalTests||0,u=l.numPassedTests||0,m=l.numFailedTests||0,p=d-u-m,g=$s(r,o.join(", "),i.status,{passed:u,failed:m,skipped:p},a,l);if(g)return L(g);let f=ea(l,o.join(", "));return F({total:d,passed:u,failed:m,skipped:p,...f&&f.length===d?{testCases:f}:{}})}}}catch{}return L(new De(`Could not parse ${r} results (exit code ${i.status??"unknown"}):
426
- ${sn(a)}`))}function ri(o){o.registerHandler("generate-tests",async e=>{let t=e.payload;try{let n=await o.getTestGenerator(t.aiEnhancement!==!1),r=[],i;if(t.sourceFiles&&t.sourceFiles.length>0?r=t.sourceFiles:t.filePath&&!t.sourceCode&&(r=[t.filePath]),r.length>0){let m=t.sourceFiles?.length?"sourceFiles":"filePath",p=await Os("generate-tests",m,r,{maxBytes:ne});if(!p.success)return p;r=p.value}else if(t.sourceCode){let p={python:".py",typescript:".ts",javascript:".js",go:".go",rust:".rs",java:".java",ruby:".rb",kotlin:".kt",csharp:".cs",php:".php",swift:".swift",cpp:".cpp",c:".c",scala:".scala"}[t.language?.toLowerCase()||"typescript"]||".ts";i=`/tmp/aqe-temp-${U()}${p}`,await Ln.writeFile(i,t.sourceCode,"utf-8"),r=[i]}if(r.length===0)return F({testsGenerated:0,coverageEstimate:null,tests:[],patternsUsed:[],warning:"No source files or code provided for test generation. Provide sourceCode, filePath, or sourceFiles in the payload."});let s=t.framework||"vitest",a=i?{[i]:t.filePath?t.filePath.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/i,""):"./module-under-test"}:void 0,c=await n.generateTests({sourceFiles:r,testType:t.testType||"unit",framework:s,coverageTarget:t.coverageGoal||80,patterns:[],importPathOverrides:a,behaviorExamples:t.behaviorExamples});if(i)try{await Ln.unlink(i)}catch{}if(!c.success)return c;let l=c.value,d=l.tests.map(m=>{let p=Uu(m.testCode,m.sourceFile,i,t.filePath);return{name:m.name,file:m.testFile,type:m.type,sourceFile:p.sourceFile,assertions:m.assertions,generationMode:m.generationMode,generationLimits:m.generationLimits,testCode:p.testCode}}),u=l.tests.some(m=>m.llmEnhanced===!0);return F({testsGenerated:d.length,coverageEstimate:l.coverageEstimate,tests:d,patternsUsed:l.patternsUsed,llmEnhanced:u,...u?{}:{generationMode:l.tests.some(m=>m.generationMode==="behavior-examples")?"behavior-examples":"deterministic-template",note:l.tests.some(m=>m.generationMode==="behavior-examples")?"Assertions use caller-supplied specification examples. Coverage is unmeasured; inspect generationLimits on each test.":t.aiEnhancement===!1?"LLM enhancement was disabled by the caller (aiEnhancement: false). Coverage is unmeasured; inspect generationLimits on each test.":"No LLM provider was available, so tests are deterministic template scaffolding rather than source-aware. Configure a provider in .agentic-qe/llm-config.json (or set a provider API key) and ensure AQE_LLM_ROUTER_DISABLED is not set."}})}catch(n){return L(B(n))}}),o.registerHandler("execute-tests",async e=>{let t=e.payload;try{let n=t.testFiles||[];if(n.length===0)return L(new De("No test files specified. Provide testFiles array with paths to test files."));let r=/^[a-zA-Z0-9_./@-]+$/;if(n.some(m=>!r.test(m)))return L(new De("Some test file paths contain invalid characters and were rejected. Provide concrete paths; expand glob patterns before calling."));let i=await Qs("execute-tests",n,t.projectRoot);if(!i.success)return i;let{testFiles:s,projectRoot:a}=i.value;if(e.executionOwner==="caller"){let m=await o.getTestExecutionAPI?.();if(!m)return L(new De("Test-execution domain is unavailable."));let p=await m.runTests({testFiles:s,parallel:t.parallel,timeout:t.timeout,workers:t.parallelism,retryCount:t.retryCount??0,projectRoot:a});return p.success?F({...p.value,coverage:p.value.coverage?.line??null}):p}let c=a?[s.filter(an),s.filter(m=>!an(m))].filter(m=>m.length>0).map(m=>({cwd:a,files:m})):Vs(s),l={total:0,passed:0,failed:0,skipped:0},d=[],u=!0;for(let m of c){let p=await Hu(m.files,m.cwd);if(!p.success)return p;l.total+=p.value.total,l.passed+=p.value.passed,l.failed+=p.value.failed,l.skipped+=p.value.skipped,p.value.testCases?d.push(...p.value.testCases):u=!1}return F({...l,duration:0,coverage:null,failedTests:[],...u?{testCases:d}:{}})}catch(n){return L(B(n))}})}D();import{randomUUID as dd}from"crypto";import*as _o from"path";ee();import{spawn as Ku,spawnSync as Xu}from"child_process";import*as H from"fs";import*as Gn from"os";import*as j from"path";fs();var qn=64*1024,Po=2048,Vu=4096,Qu=512,Wu=/^.*(?:error|\[[A-Z][A-Z_]{2,}\]|ERR_[A-Z_]+).*$/im;function xo(o,e,t){let n=je(e,Number.POSITIVE_INFINITY);if(t<=Po)return n.trim();let r=je(o,Number.POSITIVE_INFINITY).slice(0,Vu),i=n.slice(-Po),a=(Wu.exec(r)?.[0]?.trim()??r.slice(0,Qu)).trim();return a&&i.includes(a)?i.trim():`${a}
410
+ ${p}`,estimatedTokens:Math.ceil(p.length/3.5),relevance:.6})}}}finally{i.close()}}catch{return[]}return t}extractDefectKeywords(e){let t=[],n=e.toLowerCase(),r=["bug","defect","regression","fix","crash","error","null","undefined","timeout","race condition","deadlock","memory leak","overflow","injection","broken"];for(let i of r)n.includes(i)&&t.push(i);return t.slice(0,5)}};var ku=8e3,Mu=300*1e3;function Iu(){return[new xn,new In,new kn,new Dn,new An,new Mn]}var _n=class{sources;maxTokenBudget;cache=new Map;cacheTtl;constructor(e){this.sources=e?.sources||Iu(),this.maxTokenBudget=e?.maxTokenBudget||ku,this.cacheTtl=e?.cacheTtlMs||Mu}async compile(e){let t=Date.now(),n=this.buildCacheKey(e),r=this.cache.get(n);if(r&&Date.now()-r.timestamp<this.cacheTtl)return r.result;let i=e.maxTokenBudget||this.maxTokenBudget,s=await Promise.allSettled(this.sources.map(async p=>{try{let f=await p.gather(e);return{sourceId:p.id,sourceName:p.name,priority:p.priority,fragments:f}}catch{return{sourceId:p.id,sourceName:p.name,priority:p.priority,fragments:[]}}})),a=[],c=[];for(let p of s)if(p.status==="fulfilled"){let{sourceId:f,priority:g,fragments:h}=p.value;if(h.length>0){c.push(f);for(let y of h)a.push({...y,sourcePriority:g})}}a.sort((p,f)=>p.sourcePriority!==f.sourcePriority?f.sourcePriority-p.sourcePriority:f.relevance-p.relevance);let l=[],u=0;for(let p of a)if(u+p.estimatedTokens<=i){let{sourcePriority:f,...g}=p;l.push(g),u+=p.estimatedTokens}let m={summary:this.generateSummary(e,l,c),fragments:l,totalTokens:u,sources:c,timestamp:new Date().toISOString(),duration:Date.now()-t};return this.cache.set(n,{result:m,timestamp:Date.now()}),m}clearCache(){this.cache.clear()}getCacheStats(){return{size:this.cache.size,ttlMs:this.cacheTtl}}buildCacheKey(e){let t=[...e.targetFiles].sort();return JSON.stringify([e.agentType,t,e.taskDescription.slice(0,100)])}generateSummary(e,t,n){return[`Context compiled for ${e.agentType} agent.`,`Target: ${e.targetFiles.length} file(s).`,`Sources: ${n.join(", ")}.`,`Fragments: ${t.length} (${t.reduce((r,i)=>r+i.estimatedTokens,0)} est. tokens).`].join(" ")}};function Co(o){let e=[];e.push("## Compiled Context"),e.push(""),e.push(o.summary),e.push("");for(let t of o.fragments)e.push(`### ${t.title}`),e.push(t.content),e.push("");return e.push(`_Context compiled: ${o.timestamp} (${o.duration}ms)_`),e.join(`
411
+ `)}var Du={enabled:!0,enableAgentBooster:!0,enableLogging:!0,maxLogEntries:1e3},ti=class o{static instance=null;static initializationPromise=null;config;modelRouter;minCutRouter;routingLog=[];contextCompiler;disposed=!1;constructor(e,t){this.config=e,this.modelRouter=t,this.contextCompiler=new _n,this.minCutRouter=bo({enableLogging:e.enableLogging})}static async getInstance(e){if(o.instance&&!o.instance.disposed)return o.instance;if(o.initializationPromise)return o.initializationPromise;o.initializationPromise=o.create(e);try{return o.instance=await o.initializationPromise,o.instance}finally{o.initializationPromise=null}}static async create(e){let t={...Du,...e},n;t.enableAgentBooster?n=await gn(t.modelRouterConfig):n=pn(t.modelRouterConfig);let r=new o(t,n);return t.enableLogging&&console.error(`[TaskRouter] Initialized with Agent Booster: ${t.enableAgentBooster}`),r}async routeTask(e){if(!this.config.enabled)return this.createDisabledResult(e);if(this.disposed)throw new Error("TaskRouterService has been disposed");let t=null;if(this.minCutRouter.isEnabled()&&e.agentTopology)try{t=this.minCutRouter.route({task:e.task,domain:e.domain,agentType:e.agentType,agentTopology:e.agentTopology,isCritical:e.isCritical})}catch(f){this.config.enableLogging&&console.error(`[TaskRouter] MinCut routing failed, falling back to heuristic: ${f instanceof Error?f.message:String(f)}`)}let n={task:e.task,codeContext:e.codeContext,filePaths:e.filePaths,manualTier:e.manualTier,isCritical:e.isCritical,agentType:e.agentType,domain:e.domain,metadata:e.metadata},r=await this.modelRouter.route(n),i=r;if(t&&t.usedMinCut){let f=t.modelTier;f!==r.tier&&(i={...r,tier:f,rationale:`[MinCut] ${t.rationale} (heuristic suggested Tier ${r.tier})`},this.config.enableLogging&&console.error(`[TaskRouter] MinCut override: Tier ${r.tier} -> Tier ${f} (lambda=${t.normalizedLambda.toFixed(3)})`))}let s=Xe[i.tier],a=this.mapTierToStrategy(i.tier),c={timestamp:i.metadata.timestamp,taskDescription:e.task.slice(0,200),requestedTier:e.manualTier,selectedTier:i.tier,modelId:i.modelId,complexity:i.complexityAnalysis.overall,confidence:i.confidence,wasDowngraded:i.budgetDecision.wasDowngraded,agentBoosterEligible:i.agentBoosterEligible,decisionTimeMs:i.metadata.decisionTimeMs,rationale:i.rationale};this.addLogEntry(c),this.config.enableLogging&&this.logRoutingDecision(c);let l=e.patternHints,u=l&&l.length>0?this.formatPatternContext(l):void 0,d=e.agentType,m=d?_r(d)||_r(d.replace("v3-qe-","qe-")):void 0,p;if(e.filePaths&&e.filePaths.length>0)try{let f=await this.contextCompiler.compile({targetFiles:e.filePaths,agentType:e.agentType||"unknown",taskDescription:e.task});p=Co(f)}catch{}return{decision:i,executionStrategy:a,useAgentBooster:i.agentBoosterEligible,modelId:i.modelId,tierInfo:{tier:i.tier,name:s.name,typicalLatencyMs:s.typicalLatencyMs,relativeCost:s.relativeCost},logEntry:c,patternHints:l,patternContext:u,overlayConfig:m,compiledContext:p}}formatPatternContext(e){if(!e||e.length===0)return"";let t=["--- Relevant Patterns from Learning ---",""];for(let n of e){let r=n.canReuse?" [REUSABLE]":"";t.push(`[${n.name}]${r}`,` ${n.description}`,` Similarity: ${(n.similarity*100).toFixed(0)}% | Confidence: ${(n.confidence*100).toFixed(0)}%`,"")}return t.push("Use these patterns as guidance when applicable."),t.join(`
412
+ `)}async quickRoute(e){return this.routeTask({task:e})}async routeBatch(e){return Promise.all(e.map(t=>this.routeTask(t)))}getMetrics(){return this.modelRouter.getMetrics()}getRoutingLog(e=100,t=0){return this.routingLog.slice(t,t+e)}getRoutingStats(){let e=this.routingLog;if(e.length===0)return this.createEmptyStats();let t=new Map,n=0,r=0,i=0,s=0;for(let c of e)t.set(c.selectedTier,(t.get(c.selectedTier)||0)+1),n+=c.complexity,r+=c.decisionTimeMs,c.wasDowngraded&&i++,c.agentBoosterEligible&&s++;let a={};for(let[c,l]of t)a[c]=l/e.length;return{totalRouted:e.length,avgComplexity:n/e.length,avgDecisionTimeMs:r/e.length,downgradeRate:i/e.length,agentBoosterRate:s/e.length,tierDistribution:a,period:{start:e[0].timestamp,end:e[e.length-1].timestamp}}}reset(){this.routingLog.length=0,this.modelRouter.resetMetrics(),this.config.enableLogging&&console.error("[TaskRouter] Reset routing log and metrics")}async dispose(){this.disposed||(this.disposed=!0,await this.modelRouter.dispose(),o.instance=null,this.config.enableLogging&&console.error("[TaskRouter] Disposed"))}isEnabled(){return this.config.enabled&&!this.disposed}mapTierToStrategy(e){switch(e){case 0:return"booster";case 1:return"haiku";case 2:return"sonnet";case 3:return"sonnet-extended";case 4:return"opus";default:return"sonnet"}}addLogEntry(e){this.routingLog.push(e),this.routingLog.length>this.config.maxLogEntries&&this.routingLog.splice(0,this.routingLog.length-this.config.maxLogEntries)}logRoutingDecision(e){let t=Xe[e.selectedTier].name,n=e.agentBoosterEligible?"[AgentBooster]":`[Tier${e.selectedTier}]`;console.error(`[TaskRouter] ${n} ${t} | Complexity: ${e.complexity.toFixed(0)} | Confidence: ${(e.confidence*100).toFixed(0)}% | Time: ${e.decisionTimeMs.toFixed(1)}ms`+(e.wasDowngraded?" [DOWNGRADED]":""))}createDisabledResult(e){let n=Xe[2],r={timestamp:new Date,taskDescription:e.task.slice(0,200),selectedTier:2,modelId:n.exampleModels[0],complexity:50,confidence:.5,wasDowngraded:!1,agentBoosterEligible:!1,decisionTimeMs:0,rationale:"Routing disabled - using default tier"};return{decision:{tier:2,modelId:n.exampleModels[0],complexityAnalysis:{overall:50,codeComplexity:50,reasoningComplexity:50,scopeComplexity:50,confidence:.5,signals:{hasArchitectureScope:!1,hasSecurityScope:!1,requiresMultiStepReasoning:!1,requiresCrossDomainCoordination:!1,isMechanicalTransform:!1,requiresCreativity:!1,keywordMatches:{simple:[],moderate:[],complex:[],critical:[]}},recommendedTier:2,alternateTiers:[],explanation:"Routing disabled"},budgetDecision:{allowed:!0,reason:"Routing disabled",requestedTier:2,approvedTier:2,wasDowngraded:!1,estimatedCostUsd:0,currentUsage:{tier:2,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,budgetUtilization:0,isExceeded:!1,isNearLimit:!1,resetTime:new Date,remainingBudgetUsd:100,remainingRequestsThisHour:100,remainingRequestsToday:1e3},warnings:[]},confidence:.5,rationale:"Routing disabled - using default tier",agentBoosterEligible:!1,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:0,fromCache:!1},warnings:["Routing is disabled"]},executionStrategy:"sonnet",useAgentBooster:!1,modelId:n.exampleModels[0],tierInfo:{tier:2,name:n.name,typicalLatencyMs:n.typicalLatencyMs,relativeCost:n.relativeCost},logEntry:r}}createEmptyStats(){let e=new Date;return{totalRouted:0,avgComplexity:0,avgDecisionTimeMs:0,downgradeRate:0,agentBoosterRate:0,tierDistribution:{},period:{start:e,end:e}}}};async function On(o){return ti.getInstance(o)}Zt();Yt();var ni=ve("CoherenceActionGate"),_u={structuralPermit:.4,structuralDeny:.2,shiftPermit:.5,shiftDeny:.25,evidencePermit:.5,evidenceDeny:.2,combinedPermit:.5,combinedDeny:.25},ri={structural:.3,shift:.35,evidence:.35},Ou={low:1,medium:.9,high:.75,critical:.6},So=1e3,Nn=class{thresholds;advisoryMode;nativeAvailable=null;evaluationHistory=[];permitCount=0;deferCount=0;denyCount=0;totalCombinedScore=0;totalStructuralScore=0;totalShiftScore=0;totalEvidenceScore=0;cusumHigh=0;cusumLow=0;cusumMean=.7;cusumK=.05;cusumH=4;cusumSampleCount=0;cusumAlertActive=!1;constructor(e){this.advisoryMode=e?.advisory??!0,this.thresholds={..._u,...e?.thresholds}}evaluate(e){let t=this.computeStructuralScore(e),n=this.computeShiftScore(e),r=this.computeEvidenceScore(e),i=t*ri.structural+n*ri.shift+r*ri.evidence,s=Ou[e.riskLevel]??1,a=i*s,c=this.computeDecision(t,n,r,a),l=this.buildReasoning(e,c,t,n,r,a),u={decision:c,structuralScore:t,shiftScore:n,evidenceScore:r,combinedScore:a,reasoning:l,advisory:this.advisoryMode};return this.recordEvaluation(u),ni.debug("Action gate evaluation",{action:e.type,domain:e.domain,decision:c,combinedScore:a,advisory:this.advisoryMode}),u}getStatistics(){let e=this.evaluationHistory.length;return{totalEvaluations:e,permitCount:this.permitCount,deferCount:this.deferCount,denyCount:this.denyCount,averageCombinedScore:e>0?this.totalCombinedScore/e:0,averageStructuralScore:e>0?this.totalStructuralScore/e:0,averageShiftScore:e>0?this.totalShiftScore/e:0,averageEvidenceScore:e>0?this.totalEvidenceScore/e:0,advisoryMode:this.advisoryMode}}configureThresholds(e){this.thresholds={...this.thresholds,...e},ni.info("Action gate thresholds updated",{thresholds:this.thresholds})}getThresholds(){return{...this.thresholds}}isAdvisory(){return this.advisoryMode}getEvaluationHistory(){return[...this.evaluationHistory]}resetStatistics(){this.evaluationHistory=[],this.permitCount=0,this.deferCount=0,this.denyCount=0,this.totalCombinedScore=0,this.totalStructuralScore=0,this.totalShiftScore=0,this.totalEvidenceScore=0,this.resetCusum()}resetCusum(){this.cusumHigh=0,this.cusumLow=0,this.cusumAlertActive=!1,this.cusumSampleCount=0}computeStructuralScore(e){let t=.5;["generate-test","modify-code","analyze-coverage","scan-security","assess-quality","validate-contracts","test-accessibility","execute-tests","index-code","predict-defects","validate-requirements","deploy","run-chaos","optimize-learning"].includes(e.type)&&(t+=.2),JSON.stringify(e.context).toLowerCase().includes(e.domain.toLowerCase())&&(t+=.15);let i=Object.keys(e.context);return i.length>=3?t+=.15:i.length>=1&&(t+=.05),Math.min(Math.max(t,0),1)}computeShiftScore(e){let t=e.confidence,r={low:.25,medium:.5,high:.75,critical:1}[e.riskLevel]??.5,i=Math.max(0,r-e.confidence);t-=i*.3;let s=e.context;(s.stale===!0||s.outdated===!0)&&(t-=.3),(s.distributionShift===!0||s.contextChanged===!0)&&(t-=.4),this.cusumSampleCount++;let a=e.confidence;return this.cusumHigh=Math.max(0,this.cusumHigh+(a-this.cusumMean)-this.cusumK),this.cusumLow=Math.max(0,this.cusumLow-(a-this.cusumMean)-this.cusumK),this.cusumHigh>this.cusumH||this.cusumLow>this.cusumH?(t-=.2,this.cusumAlertActive||(this.cusumAlertActive=!0,ni.warn("CUSUM shift detected",{cusumHigh:this.cusumHigh,cusumLow:this.cusumLow}))):this.cusumAlertActive=!1,Math.min(Math.max(t,0),1)}computeEvidenceScore(e){let t=.5,n=e.context,r=["testResults","coverageData","securityScan","qualityReport","peerReview","analysisResult","validationPassed","precedent","historicalSuccess"];for(let s of r)n[s]!==void 0&&n[s]!==null&&(t*=1+.15);let i=["errors","failures","warnings","regressions","conflictingResults","noTestCoverage"];for(let s of i)n[s]!==void 0&&n[s]!==null&&(t*=1-.18);if((e.riskLevel==="critical"||e.riskLevel==="high")&&!n.testResults&&!n.peerReview&&(t-=.15),typeof n.evidenceCount=="number"){let s=n.evidenceCount;t+=Math.min(s*.05,.2)}return Math.min(Math.max(t,0),1)}computeDecision(e,t,n,r){return e<this.thresholds.structuralDeny||t<this.thresholds.shiftDeny||n<this.thresholds.evidenceDeny||r<this.thresholds.combinedDeny?"DENY":e>=this.thresholds.structuralPermit&&t>=this.thresholds.shiftPermit&&n>=this.thresholds.evidencePermit&&r>=this.thresholds.combinedPermit?"PERMIT":"DEFER"}buildReasoning(e,t,n,r,i,s){let a=[];if(a.push(`Decision: ${t} for ${e.type} (${e.domain}).`),a.push(`Scores: structural=${n.toFixed(2)}, shift=${r.toFixed(2)}, evidence=${i.toFixed(2)}, combined=${s.toFixed(2)}.`),t==="DENY")n<this.thresholds.structuralDeny&&a.push("Structural filter failed: action does not fit codebase graph."),r<this.thresholds.shiftDeny&&a.push("Shift filter failed: significant context distribution shift detected."),i<this.thresholds.evidenceDeny&&a.push("Evidence filter failed: insufficient evidence to justify action."),s<this.thresholds.combinedDeny&&a.push("Combined score below minimum threshold.");else if(t==="DEFER"){let c=[];n<this.thresholds.structuralPermit&&c.push("structural"),r<this.thresholds.shiftPermit&&c.push("shift"),i<this.thresholds.evidencePermit&&c.push("evidence"),c.length>0&&a.push(`Marginal filters: ${c.join(", ")}. Human review recommended.`)}return this.advisoryMode&&a.push("(Advisory mode: decision logged only, not enforced.)"),a.join(" ")}recordEvaluation(e){switch(this.evaluationHistory.push(e),this.evaluationHistory.length>So&&(this.evaluationHistory=this.evaluationHistory.slice(-So)),this.totalCombinedScore+=e.combinedScore,this.totalStructuralScore+=e.structuralScore,this.totalShiftScore+=e.shiftScore,this.totalEvidenceScore+=e.evidenceScore,e.decision){case"PERMIT":this.permitCount++;break;case"DEFER":this.deferCount++;break;case"DENY":this.denyCount++;break}}};function To(o){return new Nn(o)}function Eo(o,e,t,n,r,i){if(!Ge().useCoherenceActionGate)return null;let a=i??new Nn,c={type:o,domain:e,confidence:t,context:r,riskLevel:n};return a.evaluate(c)}import*as Fn from"fs/promises";M();El();function Nu(o){return o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Fu(o,e,t,n){if(!t)return{testCode:o,sourceFile:e};let r=m=>m.replace(/\.[a-z]+$/i,""),i=n?n.match(/\.(ts|tsx|js|jsx|mjs|cjs)$/i)?r(n):n:"./module-under-test",s=n?"":`// TODO: replace './module-under-test' with the actual import path of the module under test
413
+ `,a=r(t),c=Nu(a),l=new RegExp(c+"(?:\\.[a-zA-Z]+){0,2}","g");return{testCode:o&&s+o.replace(l,i),sourceFile:e===t&&n||e}}async function Lu(o,e){let t=Us();try{let{command:n,args:r}=zs(o.map(p=>Or(p)),t.path),i=await ln(n,r,{cwd:e,timeout:12e4,env:{...process.env,...js}}),s=[i.stderr,i.stdout].filter(Boolean).join(`
414
+ `);if(i.error||i.signal){let p=i.error?.message??`Terminated by ${i.signal}`;return q(new De(`pytest could not complete: ${sn(`${p}
415
+ ${s}`)}`))}let a=Bs(t.read(),o,i.status,s,n);if(!a.success)return a;let c=a.value.tests.map(p=>{let f=p.failureMessage&&ea(p.failureMessage);return{name:p.name,file:p.file,status:p.status,...p.duration!==void 0?{duration:p.duration}:{},...f?{failureMessage:f}:{}}}),{total:l,passed:u,failed:d,skipped:m}=a.value;return F({total:l,passed:u,failed:d,skipped:m,testCases:c})}finally{t.cleanup()}}async function qu(o,e){if(o.some(an))return Lu(o,e);let t={cwd:e,timeout:12e4},n=()=>ln("npx",["jest",...o.map(c=>Hs(c)),"--json"],t),r="vitest",i,s="";if(Vs(e)==="jest")r="jest",i=await n(),s=i.stdout||"";else{let c=na();try{i=await ln("npx",["vitest","run",...o.map(l=>Or(l)),"--reporter=json",...c.args],t),s=i.error||i.signal?"":c.read(i.stdout||"")??""}finally{c.cleanup()}!s.includes("{")&&i.status!==0&&!i.error&&!i.signal&&(r="jest",i=await n(),s=i.stdout||"")}let a=[i.error?.message,i.signal&&`Terminated by ${i.signal}`,i.stderr,s].filter(Boolean).join(`
416
+ `);if(i.error)return q(new De(`${r} could not complete: ${sn(a)}`));try{let c=s.indexOf("{");if(c>=0){let l=JSON.parse(s.slice(c));if(l.testResults){let u=l.numTotalTests||0,d=l.numPassedTests||0,m=l.numFailedTests||0,p=u-d-m,f=Gs(r,o.join(", "),i.status,{passed:d,failed:m,skipped:p},a,l);if(f)return q(f);let g=ta(l,o.join(", "));return F({total:u,passed:d,failed:m,skipped:p,...g&&g.length===u?{testCases:g}:{}})}}}catch{}return q(new De(`Could not parse ${r} results (exit code ${i.status??"unknown"}):
417
+ ${sn(a)}`))}function ii(o){o.registerHandler("generate-tests",async e=>{let t=e.payload;try{let n=await o.getTestGenerator(t.aiEnhancement!==!1),r=[],i;if(t.sourceFiles&&t.sourceFiles.length>0?r=t.sourceFiles:t.filePath&&!t.sourceCode&&(r=[t.filePath]),r.length>0){let m=t.sourceFiles?.length?"sourceFiles":"filePath",p=await Ns("generate-tests",m,r,{maxBytes:ne});if(!p.success)return p;r=p.value}else if(t.sourceCode){let p={python:".py",typescript:".ts",javascript:".js",go:".go",rust:".rs",java:".java",ruby:".rb",kotlin:".kt",csharp:".cs",php:".php",swift:".swift",cpp:".cpp",c:".c",scala:".scala"}[t.language?.toLowerCase()||"typescript"]||".ts";i=`/tmp/aqe-temp-${U()}${p}`,await Fn.writeFile(i,t.sourceCode,"utf-8"),r=[i]}if(r.length===0)return F({testsGenerated:0,coverageEstimate:null,tests:[],patternsUsed:[],warning:"No source files or code provided for test generation. Provide sourceCode, filePath, or sourceFiles in the payload."});let s=t.framework||"vitest",a=i?{[i]:t.filePath?t.filePath.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/i,""):"./module-under-test"}:void 0,c=await n.generateTests({sourceFiles:r,testType:t.testType||"unit",framework:s,coverageTarget:t.coverageGoal||80,patterns:[],importPathOverrides:a,behaviorExamples:t.behaviorExamples});if(i)try{await Fn.unlink(i)}catch{}if(!c.success)return c;let l=c.value,u=l.tests.map(m=>{let p=Fu(m.testCode,m.sourceFile,i,t.filePath);return{name:m.name,file:m.testFile,type:m.type,sourceFile:p.sourceFile,assertions:m.assertions,generationMode:m.generationMode,generationLimits:m.generationLimits,testCode:p.testCode}}),d=l.tests.some(m=>m.llmEnhanced===!0);return F({testsGenerated:u.length,coverageEstimate:l.coverageEstimate,tests:u,patternsUsed:l.patternsUsed,llmEnhanced:d,...d?{}:{generationMode:l.tests.some(m=>m.generationMode==="behavior-examples")?"behavior-examples":"deterministic-template",note:l.tests.some(m=>m.generationMode==="behavior-examples")?"Assertions use caller-supplied specification examples. Coverage is unmeasured; inspect generationLimits on each test.":t.aiEnhancement===!1?"LLM enhancement was disabled by the caller (aiEnhancement: false). Coverage is unmeasured; inspect generationLimits on each test.":"No LLM provider was available, so tests are deterministic template scaffolding rather than source-aware. Configure a provider in .agentic-qe/llm-config.json (or set a provider API key) and ensure AQE_LLM_ROUTER_DISABLED is not set."}})}catch(n){return q(B(n))}}),o.registerHandler("execute-tests",async e=>{let t=e.payload;try{let n=t.testFiles||[];if(n.length===0)return q(new De("No test files specified. Provide testFiles array with paths to test files."));let r=/^[a-zA-Z0-9_./@-]+$/;if(n.some(m=>!r.test(m)))return q(new De("Some test file paths contain invalid characters and were rejected. Provide concrete paths; expand glob patterns before calling."));let i=await Ws("execute-tests",n,t.projectRoot);if(!i.success)return i;let{testFiles:s,projectRoot:a}=i.value;if(e.executionOwner==="caller"){let m=await o.getTestExecutionAPI?.();if(!m)return q(new De("Test-execution domain is unavailable."));let p=await m.runTests({testFiles:s,parallel:t.parallel,timeout:t.timeout,workers:t.parallelism,retryCount:t.retryCount??0,projectRoot:a});return p.success?F({...p.value,coverage:p.value.coverage?.line??null}):p}let c=a?[s.filter(an),s.filter(m=>!an(m))].filter(m=>m.length>0).map(m=>({cwd:a,files:m})):Qs(s),l={total:0,passed:0,failed:0,skipped:0},u=[],d=!0;for(let m of c){let p=await qu(m.files,m.cwd);if(!p.success)return p;l.total+=p.value.total,l.passed+=p.value.passed,l.failed+=p.value.failed,l.skipped+=p.value.skipped,p.value.testCases?u.push(...p.value.testCases):d=!1}return F({...l,duration:0,coverage:null,failedTests:[],...d?{testCases:u}:{}})}catch(n){return q(B(n))}})}M();import{randomUUID as id}from"crypto";import*as Mo from"path";te();import{spawn as zu,spawnSync as Uu}from"child_process";import*as H from"fs";import*as $n from"os";import*as z from"path";fs();var Ln=64*1024,wo=2048,$u=4096,Gu=512,ju=/^.*(?:error|\[[A-Z][A-Z_]{2,}\]|ERR_[A-Z_]+).*$/im;function Ro(o,e,t){let n=je(e,Number.POSITIVE_INFINITY);if(t<=wo)return n.trim();let r=je(o,Number.POSITIVE_INFINITY).slice(0,$u),i=n.slice(-wo),a=(ju.exec(r)?.[0]?.trim()??r.slice(0,Gu)).trim();return a&&i.includes(a)?i.trim():`${a}
427
418
  \u2026
428
- ${i.trim()}`}function ai(o){return typeof o.numFailedTests=="number"||typeof o.numFailedTestSuites=="number"?(o.numFailedTests??0)>0||(o.numFailedTestSuites??0)>0?"failed":"passed":o.exitedCleanly?"passed":"failed"}var Yu="test-results.json";function Ju(o,e,t=e,n=10){let r=j.resolve(o);for(let i=0;i<=n;i++){let s=j.join(r,"node_modules",e);try{let c=JSON.parse(H.readFileSync(j.join(s,"package.json"),"utf-8")),l=typeof c.bin=="string"?c.bin:c.bin?.[t];if(l){let d=j.join(s,l);if(H.existsSync(d))return d}}catch{}let a=j.dirname(r);if(a===r)break;r=a}return null}function Zu(o){try{let e=I(H.readFileSync(j.join(o,"package.json"),"utf-8"));return{...e.devDependencies||{},...e.dependencies||{}}}catch{return{}}}var ed=["jest","@jest/core","mocha","nyc","vitest"];function oi(o,e=10){let t=[],n=null;try{n=H.realpathSync(Gn.homedir())}catch{n=null}let r=j.resolve(o);for(let i=0;i<=e&&!(i>0&&n!==null&&r===n||(t.push(r),H.existsSync(j.join(r,".git"))||td(r)));i++){let s=j.dirname(r);if(s===r)break;r=s}return t}function td(o){try{return JSON.parse(H.readFileSync(j.join(o,"package.json"),"utf-8")).workspaces!==void 0}catch{return!1}}function nd(o){for(let e of oi(o)){let t=Zu(e);if(ed.some(n=>t[n]))return t}return{}}function rd(o){return oi(o).map(e=>j.join(e,"node_modules",".bin")).filter(e=>H.existsSync(e))}function id(o){return oi(o).some(e=>H.existsSync(j.join(e,".pnp.cjs"))||H.existsSync(j.join(e,".pnp.js")))}function sd(o,e,t){let n=j.join(e,Yu),r=nd(o),i="vitest",s,a=n;r.jest||r["@jest/core"]?(i="jest",s=["--coverage",`--coverageDirectory=${e}`,"--coverageReporters=json","--json",`--outputFile=${n}`]):r.mocha||r.nyc?(i="nyc",s=[`--report-dir=${e}`,`--temp-dir=${j.join(e,".nyc_output")}`,"--reporter=json","mocha"],a=null):s=["run","--coverage",`--coverage.reportsDirectory=${e}`,"--coverage.reporter=json","--coverage.reportOnFailure=true","--reporter=json",`--outputFile=${n}`],t&&i!=="nyc"&&s.push(i==="jest"?t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):t);let c=Ju(o,i==="jest"?"jest":i);return{runner:i,command:c?process.execPath:null,args:c?[c,...s]:s,resultsFile:a}}var ii={numTotalTests:null,numPassedTests:null,numFailedTests:null,numPendingTests:null,numFailedTestSuites:null};function ad(o){if(!o)return ii;try{let e=JSON.parse(H.readFileSync(o,"utf-8")),t=n=>typeof e[n]=="number"?e[n]:null;return{numTotalTests:t("numTotalTests"),numPassedTests:t("numPassedTests"),numFailedTests:t("numFailedTests"),numPendingTests:t("numPendingTests"),numFailedTestSuites:t("numFailedTestSuites")}}catch{return ii}}async function od(o){let e=await Ha(o);if(e)return e;try{let t=JSON.parse(H.readFileSync(o,"utf-8"));if(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0)return{files:[],summary:{line:0,branch:0,function:0,statement:0,files:0}}}catch{}return null}var $n=new Map,Ao=!1;function xt(o,e){if(process.platform==="win32"){try{Xu("taskkill",["/pid",String(o),"/T","/F"],{stdio:"ignore"})}catch{}return}try{process.kill(-o,e)}catch{}}function cd(){for(let[o,e]of $n)if(xt(o,"SIGKILL"),e)try{H.rmSync(e,{recursive:!0,force:!0})}catch{}$n.clear()}function ld(){Ao||(process.on("exit",cd),Ao=!0)}function si(o){try{return process.kill(-o,0),!0}catch{return!1}}async function ko(o,e){if(process.platform==="win32")return;let t=Date.now()+e;for(;si(o)&&Date.now()<t;)await new Promise(n=>setTimeout(n,50))}async function ud(o,e,t){let n=t.graceMs??3e3,r=process.platform==="win32";return ld(),new Promise(i=>{let s=!1,a=!1,c="",l="",d=0,u=Ku(o,e,{cwd:t.cwd,env:t.env??process.env,detached:!r,shell:!1,stdio:["ignore","ignore","pipe"],windowsHide:!0});u.pid!==void 0&&$n.set(u.pid,t.cleanupDir),u.stderr?.on("data",g=>{let f=g.toString("utf-8");d+=g.length,l.length<qn&&(l=(l+f).slice(0,qn)),c=(c+f).slice(-qn)}),u.stderr?.on("error",()=>{});let m=async(g,f)=>{a||(a=!0,clearTimeout(p),u.pid!==void 0&&!r&&si(u.pid)&&(xt(u.pid,"SIGTERM"),await ko(u.pid,n),si(u.pid)&&xt(u.pid,"SIGKILL"),await ko(u.pid,n)),u.stderr?.destroy(),u.pid!==void 0&&$n.delete(u.pid),i({exitCode:g,timedOut:s,spawnError:f,pid:u.pid,stderrTail:xo(l,c,d)}))},p=setTimeout(()=>{s=!0,u.pid!==void 0&&(xt(u.pid,"SIGTERM"),setTimeout(()=>{!a&&u.pid!==void 0&&xt(u.pid,"SIGKILL")},n).unref())},t.timeoutMs);u.on("error",()=>{m(null,!0)}),u.on("exit",g=>{m(g,!1)})})}async function ci(o,e={}){let t=e.timeoutMs??12e4,n=H.mkdtempSync(j.join(Gn.tmpdir(),"aqe-js-cov-"));try{let r=sd(o,n,e.pathFilter);if(!r.command)return{runner:r.runner,missing:!0,exitCode:null,exitedCleanly:!1,timedOut:!1,timeoutMs:t,data:null,numTotalTests:null,stderrTail:""};let i=rd(o),s=j.join(n,"tmp");H.mkdirSync(s);let a={...process.env,PATH:[...i,process.env.PATH??""].join(j.delimiter),TMPDIR:s,TMP:s,TEMP:s},c=await ud(r.command,r.args,{cwd:o,timeoutMs:t,cleanupDir:n,env:a}),l=c.timedOut?null:await od(j.join(n,"coverage-final.json"));return{runner:r.runner,missing:!1,exitCode:c.exitCode,exitedCleanly:c.exitCode===0&&!c.timedOut,timedOut:c.timedOut,timeoutMs:t,data:l,...c.timedOut?ii:ad(r.resultsFile),stderrTail:c.stderrTail}}finally{try{H.rmSync(n,{recursive:!0,force:!0})}catch{}}}function Mo(o,e){if(o.missing&&id(e))return`${o.runner} could not be resolved for ${e}: this project uses Yarn Plug'n'Play, and agentic-qe resolves test runners only from node_modules. Nothing was run and nothing was downloaded. Generate a coverage report (e.g. \`yarn ${o.runner} --coverage\`) and pass it as the target, or use the node-modules linker.`;if(o.missing)return`${o.runner} is not installed in ${e} (no node_modules/${o.runner} found); nothing was run and nothing was downloaded. Install it, or generate a coverage report and pass it as the target.`;if(o.timedOut)return`The coverage run timed out after ${Math.round(o.timeoutMs/1e3)}s and was stopped.`;if(o.exitCode!==0){let t=o.stderrTail?`: ${o.stderrTail}`:"";return`Test runner (${o.runner}) exited with code ${o.exitCode??"unknown"} without a coverage report${t}`}return`Test runner (${o.runner}) exited cleanly but wrote no coverage report. Ensure a coverage provider is configured (e.g., @vitest/coverage-v8, istanbul).`}function Io(o=process.env){let e=Number.parseInt(o.AQE_COVERAGE_TIMEOUT_MS??"",10);return Number.isFinite(e)&&e>0?e:12e4}function Oo(o){let e=s=>o.reduce((a,c)=>a+s(c),0),t=(s,a)=>a>0?Math.round(s/a*100):0,n=e(s=>s.lines.total),r=e(s=>s.lines.covered),i=e(s=>s.statements.total);return{line:t(r,n),branch:t(e(s=>s.branches.covered),e(s=>s.branches.total)),function:t(e(s=>s.functions.covered),e(s=>s.functions.total)),statement:i>0?t(e(s=>s.statements.covered),i):t(r,n),files:o.length}}function md(o){return{data:{files:o,summary:Oo(o)},provenance:{method:"instrumented-report",estimated:!1,branchDataCollected:o.some(e=>e.branches.total>0),functionDataCollected:o.some(e=>e.functions.total>0),notes:[]}}}function Do(o,e,t){return o.status==="measured"?{collected:md(o.files),ranTests:e,projectRoot:t,evidence:o.evidence}:{collected:null,ranTests:e,noData:o.reason,projectRoot:t}}async function pd(o){let e=await Wa(o);if(e.status==="target-missing")return{collected:null,ranTests:!1,noData:"target-missing",projectRoot:null};if(e.status==="evaluated")return Do(e.evaluation,!1,e.projectRoot);let{target:t}=e,n=e.projectRoot;if($r(t)){let u=await ja(t);if(u){let m=Ga(t)??n,p=Va(u.data,m,t);return p.length===0?{collected:null,ranTests:!0,noData:"target-not-covered",projectRoot:m}:{collected:p.length===u.data.files.length?u:{data:{files:p,summary:Oo(p)},provenance:u.provenance},ranTests:!0,projectRoot:m}}return{collected:fn(t),ranTests:!1,projectRoot:n}}if(qr())return{collected:fn(t),ranTests:!1,projectRoot:n};let r=Ba(t,n),i=await ci(n,{timeoutMs:Io(),pathFilter:r}),s=i.missing&&i.numTotalTests===null,a=!i.missing&&i.numTotalTests===0&&ai(i)==="passed"&&(i.exitCode===0||i.exitCode===1);r&&!i.timedOut&&(s||a)&&(n=_o.resolve(n,r),i=await ci(n,{timeoutMs:Io()}));let c=i.data!==null&&i.data.files.length===0&&i.numTotalTests===null&&!i.exitedCleanly;if(i.data&&!c||i.numTotalTests===0){let u=i.data?Qa(i.data,n,t,{numTotalTests:i.numTotalTests}):{status:"no-data",reason:"no-tests-ran"},m=Do(u,i.exitedCleanly||i.data!==null,n);return m.collected&&(m.runStatus=ai(i),typeof i.numPassedTests=="number"&&typeof i.numFailedTests=="number"&&(m.testRun={runId:dd(),passed:i.numPassedTests,failed:i.numFailedTests,skipped:i.numPendingTests??0})),m}let l=fn(t),d=Mo(i,n);return l&&(l.provenance.notes=[`${d} These numbers are a STATIC ESTIMATE derived from source shape \u2014 not measured coverage, and must not be reported as such.`,...l.provenance.notes.filter(u=>!/^No instrumentation ran/.test(u))]),{collected:l,ranTests:i.exitedCleanly,projectRoot:n,notes:l?[]:[d]}}function gd(o,e,t,n){return o?Gr(o,t,n):e?"Tests ran but no coverage output was generated. Ensure a coverage provider is configured (e.g., @vitest/coverage-v8, istanbul).":"No coverage data found and could not run tests automatically. "+No(t)}function No(o){return qr()?"Coverage tooling execution is disabled (AQE_COVERAGE_NO_EXEC). No tests were run and no build tooling was invoked. Unset it, or generate a coverage report yourself and re-run, to get real measurements.":$r(o)?"To get real measurements for this Rust crate, install cargo-llvm-cov (`cargo install cargo-llvm-cov`) and re-run; agentic-qe will invoke it automatically.":"To get real measurements, run your tests with coverage enabled (e.g. `npm test -- --coverage`, `pytest --cov`) and re-run this analysis."}function li(o){o.registerHandler("analyze-coverage",async e=>{let t=e.payload;try{let n=t.target||process.cwd();if(t.target&&t.target!=="."){let k=await K("analyze-coverage","target",t.target,{allowDirectory:!0,allowMissing:!0});if(!k.success)return k;n=k.value}let r=o.getCoverageAnalyzer(),i=t.threshold||80,{collected:s,ranTests:a,noData:c,projectRoot:l,notes:d,runStatus:u,testRun:m,evidence:p}=await pd(n);if(c==="target-missing")return L(new Error(Gr("target-missing",n,null)));if(!s){let k=c!==void 0&&Ya(c);return F({lineCoverage:null,branchCoverage:null,functionCoverage:null,statementCoverage:null,totalFiles:0,coverageByFile:[],gaps:[],estimated:!1,measured:!1,coverageMethod:"none",...k?{unmeasured:!0}:{},algorithm:"sublinear-O(log n)",warning:d?.length?d.join(" "):gd(c,a,n,l)})}let{data:g,provenance:f}=s,h=await r.analyze({coverageData:g,threshold:i,includeFileDetails:t.detectGaps,measured:!f.estimated,...l?{projectRoot:l}:{},...u&&!f.estimated?{runStatus:u}:{},...m&&!f.estimated?{testRun:m}:{}});if(!h.success)return h;let v=h.value,y=[];if(t.detectGaps){let k=await r.findGaps(g,i);k.success&&(y=k.value.gaps.map(z=>({file:z.file,lines:z.lines,risk:z.severity,estimated:f.estimated,...f.estimated?{confidence:.2,reason:"Possible coverage gap (STATIC ESTIMATE \u2014 no instrumentation ran)"}:{}})))}let C=k=>Math.round(k*10)/10,b=(k,z)=>z>0?Math.round(k/z*1e3)/10:null,E=za(p,l??n),T=[...f.notes,...d??[]];f.estimated&&T.push(No(n)),E.length>0&&T.push(`INSUFFICIENT EVIDENCE \u2014 the threshold is not met on this report: ${E.join("; ").replace(/\.?$/,".")}`),T.push(...Ua(p));let S=f.estimated||Js(g.files).statement,x={branch:f.branchDataCollected,function:f.functionDataCollected,statement:S},M=Ka(v.summary,i,x),O=Xa(v.recommendations,M,i,x);return F({lineCoverage:C(v.summary.line),branchCoverage:f.branchDataCollected?C(v.summary.branch):null,functionCoverage:f.functionDataCollected?C(v.summary.function):null,statementCoverage:S?C(v.summary.statement):null,totalFiles:v.summary.files,coverageByFile:g.files.map(k=>({file:k.path,lineCoverage:b(k.lines.covered,k.lines.total)??0,branchCoverage:f.branchDataCollected?b(k.branches.covered,k.branches.total):null,functionCoverage:f.functionDataCollected?b(k.functions.covered,k.functions.total):null})),gaps:y,meetsThreshold:M.meetsThreshold&&E.length===0,...p?{evidenceStatus:p.status,unmeasuredFiles:p.unmeasuredFiles,...p.stale?{staleReport:p.stale}:{},...p.conflictingFiles?{conflictingFiles:p.conflictingFiles}:{},...p.excludedEntries?{excludedReportEntries:p.excludedEntries}:{}}:{},delta:v.delta,recommendations:O,algorithm:"sublinear-O(log n)",estimated:f.estimated,measured:!f.estimated,coverageMethod:f.method,branchDataCollected:f.branchDataCollected,functionDataCollected:f.functionDataCollected,statementDataCollected:S,...u&&!f.estimated?{runStatus:u}:{},...T.length>0?{warning:T.join(" ")}:{}})}catch(n){return L(B(n))}})}import*as Un from"path";D();import{createHash as jn}from"node:crypto";import{realpath as fd}from"node:fs/promises";import*as qo from"node:path";var ui="Dangerous eval/exec usage";function hd(o){return/\[CWE-95\]/.test(o.description??"")||(o.references??[]).some(e=>/\/definitions\/95\.html$/.test(e))}var yd={informational:0,low:1,medium:2,high:3,critical:4},Fo=o=>yd[o??""]??-1;async function Lo(o,e){let t=qo.resolve(o),n=e.get(t);return n===void 0&&(n=await fd(t).catch(()=>t),e.set(t,n)),n}async function $o(o,e,t){let n=e.filter(hd);if(n.length===0)return[...o];let r=new Map,i=new Map;for(let a of n){let c=`${await Lo(a.location.file,r)}:${a.location.line??0}`;i.set(c,Math.max(i.get(c)??-1,Fo(a.severity)))}let s=[];for(let a of o){let c=`${await Lo(a.location.file,r)}:${a.location.line??0}`,l=i.get(c);a.title===ui&&t(a)&&l!==void 0&&l>=Fo(a.severity)||s.push(a)}return s}function mi(o){o.registerHandler("scan-security",async e=>{let t=e.payload;try{let n=Un.resolve(t.target||process.cwd()),r=t.sast!==!1||t.dependencies===!0;if(t.target&&t.target!=="."&&r){let R=await K("scan-security","target",t.target,{allowDirectory:!0,allowMissing:!0,maxBytes:ne});if(!R.success)return R;n=R.value}let i=t.sast!==!1,s=i?await Za(n):void 0,a=s?.files??[],c=[],l=[],d=new Map,u=[],m=[],p=new Map,g=[],f=a.filter(R=>/\.(ts|tsx|js|jsx|mjs|cjs)$/i.test(R)),h=a.filter(R=>!/\.(ts|tsx|js|jsx|mjs|cjs)$/i.test(R)),v=[],y=new Set;for(let R of a){if(!Ja(R)){c.push({path:R,engineId:"generic-patterns",status:"unsupported",readLines:0,analyzedLines:0,reason:"Outside the declared source-language policy."});continue}try{let te=await Ir(R,{outsideRoot:"allow"}),J=te.toString("utf-8"),Q=J.split(`
429
- `);c.push({path:R,engineId:"generic-patterns",status:"analyzed",sourceDigest:jn("sha256").update(te).digest("hex"),readLines:Q.length,analyzedLines:Q.length});let ke=[{regex:/\w*(?:secret|password|passwd|api_key|apikey|private_key|jwt_secret)\w*\s*[=:]\s*['"][^'"]{4,}['"]/gi,title:"Hardcoded secret",severity:"critical"},{regex:/\w*(?:token|auth_token|access_key|secret_key)\w*\s*[=:]\s*['"][^'"]{8,}['"]/gi,title:"Hardcoded credential",severity:"critical"},{regex:/(?:AWS_SECRET|GITHUB_TOKEN|SLACK_TOKEN|OPENAI_API_KEY)\s*[=:]\s*['"][^'"]+['"]/gi,title:"Hardcoded cloud credential",severity:"critical"}];for(let[W,ae]of ke.entries()){d.set(`secret-${W}`,ae.regex.toString());for(let Me=0;Me<Q.length;Me++){let yl=[...Q[Me].matchAll(ae.regex)];for(let og of yl)v.push({title:ae.title,severity:ae.severity,location:{file:R,line:Me+1},description:`Potential hardcoded secret found at line ${Me+1}`,category:"sensitive-data"})}}let St=/(?:execute|query|cursor\.execute)\s*\(\s*(?:f['"]|['"].*%s|['"].*\+\s*\w)/gi;d.set("sql-interpolation",St.toString());for(let W=0;W<Q.length;W++)St.test(Q[W])&&v.push({title:"Potential SQL injection",severity:"high",location:{file:R,line:W+1},description:"String interpolation in SQL query \u2014 use parameterized queries",category:"injection"}),St.lastIndex=0;let me=[/allow_origins\s*=\s*\[?\s*['"]?\*['"]?\s*\]?/i,/cors\(\s*\{[^}]*origin:\s*['"]?\*['"]?/i,/Access-Control-Allow-Origin['":\s]+\*/i,/@CrossOrigin\(\s*origins?\s*=\s*["']\*["']/i,/\.Header\(\)\.Set\(["']Access-Control-Allow-Origin["'],\s*["']\*["']/i];for(let[W,ae]of me.entries())if(d.set(`cors-${W}`,ae.toString()),ae.test(J)){v.push({title:"CORS wildcard origin",severity:"high",location:{file:R,line:Q.findIndex(Me=>ae.test(Me))+1},description:"CORS configured with wildcard (*) origin \u2014 restrict to specific domains",category:"security-misconfiguration"});break}d.set("debug-mode","/(?:DEBUG|debug)\\s*[=:]\\s*(?:True|true|1)/i"),/(?:DEBUG|debug)\s*[=:]\s*(?:True|true|1)/i.test(J)&&v.push({title:"Debug mode enabled",severity:"medium",location:{file:R,line:Q.findIndex(W=>/DEBUG\s*[=:]\s*(?:True|true|1)/i.test(W))+1},description:"Debug mode should be disabled in production",category:"security-misconfiguration"}),d.set("eval-exec","/\\b(?:eval|exec)\\s*\\(/i");for(let W=0;W<Q.length;W++){if(!/\b(?:eval|exec)\s*\(/i.test(Q[W]))continue;let ae={title:ui,severity:"high",location:{file:R,line:W+1},description:"eval/exec can lead to code injection \u2014 avoid using with user input",category:"injection"};v.push(ae),/\bexec\s*\(/i.test(Q[W])||y.add(ae)}}catch(te){let J=`Source read failed: ${di(te)}`;u.push(`${R}: ${J}`),c.push({path:R,engineId:"generic-patterns",status:"unreadable",readLines:0,analyzedLines:0,reason:J})}}let C=["requirements.txt","pyproject.toml","Gemfile","go.mod","Cargo.toml"];for(let R of i?C:[]){let te=Un.join(n,R);try{let J=await Ir(te,{outsideRoot:"allow"}),Q=J.toString("utf-8"),ke=Q.split(`
430
- `).length;if(c.push({path:te,engineId:"dependency-manifest-patterns",status:"analyzed",sourceDigest:jn("sha256").update(J).digest("hex"),readLines:ke,analyzedLines:ke}),p.set("dependency-audit-advisory","Presence of a supported dependency manifest"),v.push({title:"Dependency audit recommended",severity:"informational",location:{file:R,line:1},description:`Found ${R} \u2014 run language-specific dependency audit (e.g., pip-audit, npm audit, cargo audit)`,category:"dependencies"}),R==="requirements.txt"||R==="pyproject.toml"){let St=[{pkg:"python-jose",pattern:/python-jose/i,cve:"CVE-2024-33663",severity:"high",title:"python-jose ECDSA key confusion (CVE-2024-33663)",description:"python-jose allows ECDSA key confusion \u2014 upgrade to >=3.3.0 or switch to PyJWT"},{pkg:"python-jose",pattern:/python-jose/i,cve:"CVE-2024-33664",severity:"high",title:"python-jose JWT algorithm confusion (CVE-2024-33664)",description:"python-jose JWT algorithm confusion vulnerability \u2014 upgrade or switch to PyJWT"},{pkg:"python-multipart",pattern:/python-multipart/i,cve:"CVE-2026-24486",severity:"critical",title:"python-multipart DoS (CVE-2026-24486)",description:"python-multipart denial of service via crafted multipart data \u2014 upgrade to >=0.0.18"}];for(let me of St)p.set(me.cve,me.pattern.toString()),me.pattern.test(Q)&&v.push({title:me.title,severity:me.severity,location:{file:R,line:Q.split(`
431
- `).findIndex(W=>me.pattern.test(W))+1},description:me.description,category:"dependencies"})}}catch(J){let Q=J.code;if(Q!=="ENOENT"&&Q!=="ENOTDIR"){let ke=`Manifest read failed: ${di(J)}`;m.push(`${te}: ${ke}`),c.push({path:te,engineId:"dependency-manifest-patterns",status:"unreadable",readLines:0,analyzedLines:0,reason:ke})}}}let b=c.filter(R=>R.engineId==="generic-patterns"&&R.status==="analyzed").length,E=c.filter(R=>R.engineId==="dependency-manifest-patterns"&&R.status==="analyzed").length;l.push({id:"dependency-manifest-patterns",requested:i,required:!1,status:i?m.length>0?E>0?"partial":"failed":E>0?"completed":"not-run":"disabled",scope:"parent-directory",target:n,analyzedFiles:E,ruleIds:[...p.keys()].sort(),rulesetDigest:jn("sha256").update(JSON.stringify([...p.entries()].sort())).digest("hex"),ruleCoverage:"known",errors:m,limitations:["Manifest name patterns are advisories, not a resolved dependency or version audit."]});let T=["Generic text patterns do not establish language-specific or dependency vulnerability coverage."];l.push({id:"generic-patterns",requested:i,required:i,status:i?u.length>0?b>0?"partial":"failed":b===a.length&&b>0?"completed":b>0?"partial":a.length>0?"unavailable":"not-run":"disabled",scope:"requested-files",analyzedFiles:b,ruleIds:[...d.keys()].sort(),rulesetDigest:jn("sha256").update(JSON.stringify([...d.entries()].sort())).digest("hex"),ruleCoverage:"known",errors:u,limitations:T});let S=f.map(R=>Ca.create(R)),x=null;if(i&&S.length>0)try{let R=await o.getSecurityScanner().scanFiles(S);R.success?(x=R.value,x.evidence?(c.push(...x.evidence.files),l.push(...x.evidence.engines),g.push(...x.evidence.limitations)):l.push(Go("sast","requested-files"))):l.push(zn("sast","requested-files",R.error))}catch(R){l.push(zn("sast","requested-files",R))}else l.push({id:"sast",requested:i,required:!1,status:i?"not-run":"disabled",scope:"requested-files",analyzedFiles:0,ruleCoverage:"unknown",errors:[],limitations:i?["No JS/TS files were available for language-specific SAST."]:[]});let M=null;if(t.dast&&t.targetUrl)try{let R=await o.getSecurityScanner().scanUrl(t.targetUrl,{activeScanning:!0,maxDepth:3,timeout:3e4});R.success?(M=R.value,l.push(M.status==="incomplete"?{...vd(M.failedRequests),target:t.targetUrl}:{...Go("dast","url"),target:t.targetUrl})):l.push({...zn("dast","url",R.error),target:t.targetUrl})}catch(R){l.push({...zn("dast","url",R),target:t.targetUrl})}else l.push({id:"dast",requested:t.dast===!0,required:t.dast===!0,status:t.dast?"not-run":"disabled",scope:"url",ruleCoverage:"unknown",errors:t.dast?["DAST was requested without targetUrl."]:[],limitations:[]});let O=null;t.dependencies===!0&&(O=await eo(o.getSecurityScanner(),n),l.push(O.engine)),t.compliance?.length&&l.push({id:"compliance",requested:!0,required:!0,status:"not-run",scope:"requested-files",ruleCoverage:"unknown",errors:[],limitations:["Requested compliance checks are not executed by this task handler."]});let k=new Set(a),z=new Set(c.filter(R=>R.status==="analyzed"&&k.has(R.path)).map(R=>R.path)),se=l.filter(R=>R.requested&&R.required),Xt=z.size>0||(O?.report.packagesChecked??0)>0,ht={schemaVersion:1,completeness:Xt&&se.every(R=>R.status==="completed")&&(!s||s.discovery.status==="complete")?"complete":Xt?"partial":"none",requestedFiles:a.length,requestedPaths:a,duplicateInputs:0,files:c,engines:l,limitations:[...new Set([...g,...l.flatMap(R=>[...R.limitations,...R.errors]),...s?.discovery.issues.map(R=>`${R.path}: ${R.reason}`)??[]])],...s?{discovery:s.discovery}:{}},Er=!!x?.evidence?.engines.some(R=>R.id==="patterns"&&(R.status==="completed"||R.status==="partial")&&(R.analyzedFiles??0)>0),qe=await $o(v,x?.vulnerabilities??[],R=>y.has(R)),yt={critical:qe.filter(R=>R.severity==="critical").length,high:qe.filter(R=>R.severity==="high").length,medium:qe.filter(R=>R.severity==="medium").length,low:qe.filter(R=>R.severity==="low").length,informational:qe.filter(R=>R.severity==="informational").length},ms=O?.vulnerabilities??[],vt=R=>ms.filter(te=>te.severity===R).length,bt={critical:(x?.summary?.critical||0)+(M?.summary?.critical||0)+yt.critical+vt("critical"),high:(x?.summary?.high||0)+(M?.summary?.high||0)+yt.high+vt("high"),medium:(x?.summary?.medium||0)+(M?.summary?.medium||0)+yt.medium+vt("medium"),low:(x?.summary?.low||0)+(M?.summary?.low||0)+yt.low+vt("low"),informational:(x?.summary?.informational||0)+(M?.summary?.informational||0)+yt.informational+vt("informational")},Ct=[...x?.vulnerabilities||[],...M?.vulnerabilities||[],...qe,...ms],hl=Ct.sort((R,te)=>{let J={critical:0,high:1,medium:2,low:3,informational:4};return J[R.severity]-J[te.severity]}).slice(0,10).map(R=>({type:R.title,severity:R.severity,file:R.location.file,line:R.location.line,description:R.description})),ps=Ct.length===0&&ht.completeness!=="complete"?["No findings reported; requested analysis is incomplete or unverified. Inspect execution receipts."]:Ys(Ct);return O&&O.report.status!=="complete"&&ps.unshift(O.report.message),F({vulnerabilities:Ct.length,critical:bt.critical,high:bt.high,medium:bt.medium,low:bt.low,informational:bt.informational,topVulnerabilities:hl,findings:Ct,recommendations:ps,scanTypes:{sast:t.sast!==!1,dast:t.dast||!1,dependencies:t.dependencies===!0},...O?{dependencyScan:O.report}:{},status:ht.completeness==="complete"?"completed":ht.completeness==="partial"?"partial":"unavailable",evidence:ht,limitations:ht.limitations,filesScanned:z.size,jstsFilesScanned:f.filter(R=>z.has(R)).length,otherFilesScanned:h.filter(R=>z.has(R)).length,...x?.evidence?{coverage:x.coverage}:{},deepAnalysisPerformed:Er,analysisDepth:Er?h.length>0?"sast-patterns-on-js-ts; generic-patterns-on-other-languages":"sast-patterns":b>0?"pattern-matching-only":"none",...Er?{}:{note:"No verified language-specific SAST ran. Generic pattern matches and partial findings do not establish that the target is free of vulnerabilities."}})}catch(n){return L(B(n))}})}function zn(o,e,t){let n=o==="sast"&&t instanceof Error&&t.message.startsWith("No valid rule sets found:")?"No valid rule sets configured.":`${o} execution failed (${di(t)}).`;return{id:o,requested:!0,required:!0,status:"failed",scope:e,ruleCoverage:"unknown",errors:[n],limitations:[]}}function di(o){let e=o?.code;return typeof e=="string"&&/^[A-Z0-9_]{1,32}$/.test(e)?e:"UNKNOWN"}function vd(o){let e=[...new Set(o.map(t=>t.code))].join(", ");return{id:"dast",requested:!0,required:!0,status:"partial",scope:"url",ruleCoverage:"unknown",errors:[`dast incomplete: ${o.length} request(s) not answered (${e}).`],limitations:o.slice(0,20).map(t=>`dast not answered: ${t.url} (${t.code}: ${t.reason})`)}}function Go(o,e){return{id:o,requested:!0,required:!0,status:"unverified",scope:e,ruleCoverage:"unknown",errors:[],limitations:[`${o} returned no execution receipt; coverage is unverified.`]}}import*as de from"node:path";import{existsSync as bd,promises as pi}from"node:fs";D();Tt();var Cd=["coverage","complexity","maintainability","testability"],_e=-1,jo="Static analysis only; no quality gate was evaluated. Call quality_assess with runGate: true (or `aqe quality --gate`) for a pass/fail gate on measured evidence.";function At(o){return sa(o)?o:_e}function Sd(o,e){let t=new Map((e??[]).map(n=>[n.metric,n.reason]));return Object.fromEntries(o.map(n=>[n,t.get(n)??(n==="security"?"static analysis never measures security":"the static analyzer produced no measured value")]))}var Td=50;function zo(o,e){let t=de.relative(o,e);return t===""||t!==".."&&!t.startsWith(`..${de.sep}`)&&!de.isAbsolute(t)}async function Uo(o,e,t){let n=de.resolve(e,o);if(o.includes("\0")||!zo(e,n))throw new le(`${t} ${JSON.stringify(o)} is outside the project root (${e}).`);let r;try{r=await pi.realpath(n)}catch{return n}let i=await pi.realpath(e).catch(()=>e);if(!zo(i,r))throw new le(`${t} ${JSON.stringify(o)} resolves outside the project root (${e}).`);return n}async function Ed(o){let e=ze();if(Array.isArray(o.sourceFiles)&&o.sourceFiles.length>0){let r=[];for(let i of o.sourceFiles){if(typeof i!="string"||i.trim()==="")throw new le("sourceFiles must be a non-empty array of file paths.");r.push(await Uo(i,e,"sourceFile"))}return{sourceFiles:r,explicitFiles:r,scope:"sourceFiles"}}if(typeof o.target=="string"&&o.target.trim()!==""){let r=await Uo(o.target,e,"target"),i=await pi.stat(r).catch(()=>null);if(!i)throw new le(`target ${JSON.stringify(o.target)} does not exist.`);return i.isFile()?{sourceFiles:[r],explicitFiles:[r],scope:r}:{sourceFiles:await Pe(r,{includeTests:!1,completeScope:!0}),explicitFiles:[],scope:r}}let t=de.join(e,"src"),n=bd(t)?t:e;return{sourceFiles:await Pe(n,{includeTests:!1,completeScope:!0}),explicitFiles:[],scope:n}}function wd(o){return(o??[]).map(e=>`Partial evidence: ${e.metric} measured over ${e.analysedFiles} of ${e.totalFiles} file(s) (${Math.round(e.coverageOfScope*1e3)/10}%); not analysed: `+e.failed.slice(0,3).map(t=>t.reason).join("; ")+(e.failed.length>3?`; and ${e.failed.length-3} more`:"")+".")}function Rd(o){if(o===void 0)return Cd;try{return un(o)}catch(e){throw new le(B(e).message)}}async function Pd(o){try{let{findCIConfigFile:e,parseCIConfigFile:t}=await import("./ci-config-XRUR3I4K.js"),n=e(o);if(!n)return;let r=t(n);return r.success?r.config?.qualityGate.thresholds.coverage:void 0}catch{return}}async function xd(o){let e=o.thresholdSource==="default"?void 0:o.threshold;if(e!==void 0&&(typeof e!="number"||!Number.isFinite(e)||e<0||e>100))throw new le("threshold must be a finite number between 0 and 100.");return ia(e,e===void 0?await Pd(process.cwd()):void 0)}function gi(o){o.registerHandler("assess-quality",async e=>{let t=e.payload;try{if(t.runGate===!0){let C=await cn(o.memory);return F({...Ks(C),metrics:C,evidenceStatus:"measured",unmeasured:[],gateEvaluated:!0})}let n=Rd(t.metrics),r=await xd(t),i=o.getQualityAnalyzer(),s=t.threshold||80,{sourceFiles:a,explicitFiles:c,scope:l}=await Ed(t);if(a.length===0)return F({qualityScore:_e,passed:!1,threshold:s,metrics:{coverage:_e,complexity:_e,maintainability:_e,testability:_e},recommendations:[...Nr(n),"No source files found for quality assessment"],warning:"No source files found",evidenceStatus:He,unmeasured:n,unmeasuredReasons:Object.fromEntries(n.map(C=>[C,"no source files found to analyse"])),measuredFailures:[],gateEvaluated:!1,confidence:0,note:jo});let d=await i.analyzeQuality({sourceFiles:a,includeMetrics:n,explicitFiles:c});if(!d.success)return d;let u=d.value,m={};for(let C of u.metrics)m[C.name]=C.value;let p=aa(n,m),g=oa(p.measured,m,{coverage:r}),f=p.evidenceStatus!=="measured",h=!f&&g.length===0&&u.score.overall>=s,v=u.recommendations.map(C=>`[${C.type}] ${C.title}: ${C.description}`),y=u.subsetScore??u.score.overall;return F({qualityScore:f?_e:u.score.overall,...f?{qualityScoreReason:`not computed: ${p.unmeasured.join(", ")} unmeasured`,...y>=0?{subsetScore:y}:{}}:{},passed:h,threshold:s,metrics:{coverage:At(m.coverage),complexity:At(m.complexity),maintainability:At(m.maintainability),security:At(m.security),...Object.fromEntries(n.map(C=>[C,At(m[C])])),...m},unmeasuredReasons:Sd(p.unmeasured,u.unmeasured),...f||(u.partial?.length??0)>0?{scoreBasis:u.metrics.map(C=>C.name)}:{},recommendations:[...g.map(ca),...Nr(p.unmeasured),...wd(u.partial),...v],...u.partial&&u.partial.length>0?{partialMetrics:u.partial}:{},...u.excluded&&u.excluded.length>0?{excludedFiles:u.excluded.slice(0,Td),excludedCount:u.excluded.length}:{},scope:l,evidenceStatus:p.evidenceStatus,unmeasured:p.unmeasured,measuredFailures:g,gateEvaluated:!1,confidence:p.confidence,note:jo,trends:u.trends.map(C=>({metric:C.metric,direction:C.direction,dataPoints:C.dataPoints.length})),filesAnalyzed:a.length})}catch(n){return L(B(n))}})}D();function fi(o){o.registerHandler("validate-requirements",async e=>{let t=e.payload;try{let n=process.cwd();if(t.requirementsPath){let a=await K("validate-requirements","requirementsPath",t.requirementsPath,{allowDirectory:!0,allowMissing:!0});if(!a.success)return a;n=a.value}let r=await Pe(n,{includeTests:!1,languages:[]}),i=[".md",".feature",".gherkin",".txt",".rst"],s=[];for(let a of r)i.some(c=>a.endsWith(c))&&s.push(a);return F({requirementsAnalyzed:s.length,testable:0,ambiguous:0,untestable:0,coverage:0,bddScenarios:[],warning:s.length===0?"No requirement files (.md, .feature, .gherkin) found. Provide requirementsPath or add requirement docs.":"Requirements validation requires LLM analysis. File inventory returned \u2014 use task_orchestrate for deep analysis.",files:s.map(a=>a.startsWith(n)?a.slice(n.length+1):a).slice(0,20)})}catch(n){return L(B(n))}}),o.registerHandler("validate-contracts",async e=>{let t=e.payload;try{if(!t.contractPath)return F({contractPath:"",valid:!1,breakingChanges:[],warnings:[],coverage:0,error:"contractPath is required. Provide a path to an OpenAPI spec, JSON Schema, or Protocol Buffer file."});let n=await K("validate-contracts","contractPath",t.contractPath,{allowMissing:!0,maxBytes:ne});if(!n.success)return n;try{let r=await ue(n.value,{maxBytes:ne}),i=t.contractPath.endsWith(".json"),s=t.contractPath.endsWith(".yaml")||t.contractPath.endsWith(".yml");return i&&JSON.parse(r),F({contractPath:t.contractPath,valid:!0,format:i?"json":s?"yaml":"unknown",breakingChanges:[],warnings:[],linesAnalyzed:r.split(`
432
- `).length,note:"Structural validation passed. For semantic contract testing, use consumer-driven contract tests."})}catch(r){return F({contractPath:t.contractPath,valid:!1,breakingChanges:[],warnings:[],error:`Could not read or parse contract file: ${w(r)}`})}}catch(n){return L(B(n))}})}import{randomUUID as Ad}from"node:crypto";import*as Ze from"path";D();Zt();var hi=ye("CodeIntelligenceHandlers");async function kd(o,e,t){if(!o.getCodeIntelligenceCoordinator)return;let n=ma(t,{target:Ze.resolve(e)});if(!n){hi.debug("Skipping project metrics: no project root resolved (filesystem root or no paths)");return}try{let r=await o.getCodeIntelligenceCoordinator();if(!r)return;let i=await r.collectProjectMetrics(n);if(!i.success){hi.debug(`Project metrics unavailable: ${i.error.message}`);return}return{root:n,loc:i.value.loc.total,locByLanguage:i.value.loc.byLanguage,tests:i.value.tests.total,toolsUsed:i.value.toolsUsed}}catch(r){hi.debug(`Project metrics unavailable: ${B(r).message}`);return}}async function Bo(o,e){return!e||e==="."?F(void 0):K(o,"target",e,{allowDirectory:!0,allowMissing:!0})}async function Md(o,e){let t="Search index not updated: the code-intelligence domain is unavailable, so a code search will not find these files.";if(!o.getCodeIntelligenceCoordinator)return[t];try{let n=await o.getCodeIntelligenceCoordinator();return n?(await n.indexForSearch(e)).warnings:[t]}catch(n){return[`Search index not updated: ${B(n).message}`]}}function yi(o){o.registerHandler("index-code",async e=>{let t=e.payload;try{let n=await Bo("index-code",t.target);if(!n.success)return n;let r=o.getKnowledgeGraph(),i=n.value??(t.target||process.cwd()),s=Date.now(),a=await Pe(i,{includeTests:t.includeTests!==!1,languages:t.languages});if(a.length===0)return F({filesIndexed:0,nodesCreated:0,edgesCreated:0,target:i,incremental:t.incremental||!1,languages:t.languages||[],duration:Date.now()-s,warning:`No source files found in ${i}. Searched for: TypeScript, JavaScript, Python, Go, Rust, Java, Ruby, C/C++, and more.`});let c=await r.index({paths:a,incremental:t.incremental||!1,includeTests:t.includeTests!==!1,languages:t.languages});if(!c.success)return c;let l=c.value;if(l.filesIndexed===0)return L(pa(a.length,l.skipped??[],l.errors));let d=new Set([...(l.skipped??[]).map(h=>h.path),...l.errors.map(h=>h.file)]),u=a.filter(h=>!d.has(h)),m=await kd(o,i,u),p=await Md(o,u),g=new Set,f={ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",py:"python",pyw:"python",go:"go",rs:"rust",java:"java",kt:"kotlin",kts:"kotlin",rb:"ruby",cs:"csharp",php:"php",swift:"swift",c:"c",h:"c",cpp:"cpp",hpp:"cpp",cc:"cpp",scala:"scala"};for(let h of u){let v=Ze.extname(h).slice(1),y=f[v];y&&g.add(y)}return F({filesIndexed:l.filesIndexed,nodesCreated:l.nodesCreated,edgesCreated:l.edgesCreated,symbolsExtracted:l.nodesCreated,relationsFound:l.edgesCreated,target:i,incremental:t.incremental||!1,languages:Array.from(g),duration:l.duration,errors:l.errors,warnings:[...l.warnings??[],...p],skipped:l.skipped??[],...m?{projectMetrics:m}:{}})}catch(n){return L(B(n))}}),o.registerHandler("predict-defects",async e=>{let t=e.payload;try{let n=await Bo("predict-defects",t.target);if(!n.success)return n;let r=n.value??Ze.resolve(t.target||process.cwd()),i=t.minConfidence||.5,s=await Pe(r,{includeTests:!1});if(s.length===0)return F({predictedDefects:[],riskScore:0,recommendations:[`No source files found in ${r}. Ensure the path contains source code files.`],warning:`No source files found in ${r}`,filesAnalyzed:0});let a=[],c=[],l=0;for(let g of s)try{let f=await ue(g,{outsideRoot:"allow"}),h=f.split(`
433
- `),v=h.length,y=0,C=[];v>500?(y+=.25,C.push(`Large file (${v} lines)`)):v>300&&(y+=.15,C.push(`Medium-large file (${v} lines)`));let b=f.match(/\b(if|else|switch|case|for|while|catch|&&|\|\|)\b/g)||[],E=b.length/Math.max(v,1);E>.15?(y+=.25,C.push(`High branch density (${b.length} branches in ${v} lines)`)):E>.08&&(y+=.1,C.push("Moderate branch complexity")),Math.max(...h.map(O=>{let k=O.match(/^(\s*)/);return k?k[1].length:0}))>20&&(y+=.15,C.push("Deep nesting detected"));let S=(f.match(/\b(TODO|FIXME|HACK|XXX|WORKAROUND)\b/gi)||[]).length;S>3&&(y+=.15,C.push(`${S} technical debt markers`));let x=(f.match(/\b(function|def|func|async)\b/g)||[]).length;x>0&&v/x>80&&(y+=.1,C.push("Potentially long functions")),y=Math.min(y,.95);let M=Math.round(y*100)/100;if(c.push({file:Ze.resolve(g),probability:M,riskLevel:y>=.8?"critical":y>=.6?"high":y>=.4?"medium":y>=.2?"low":"info",factors:[{name:"staticCodeIndicators",contribution:M}],recommendations:C}),y>=i){let O=g.startsWith(r)?g.slice(r.length).replace(/^\//,""):g;a.push({file:O,probability:Math.round(y*100)/100,reason:C.join("; ")})}}catch{l++}if(c.length===0)return L(new Error(`Defect prediction could not read any of ${s.length} source files`));let d=Ad();await o.memory.set(`defect-intelligence:predictor:prediction:${d}`,{id:d,timestamp:new Date().toISOString(),predictions:c,predictionMethod:"static-code-indicators",estimated:!0,filesSkipped:l,scanStatus:l>0?"partial":"complete"},{namespace:"defect-intelligence",ttl:86400*7}),await la(o.memory),a.sort((g,f)=>f.probability-g.probability);let u=a.length>0?a.reduce((g,f)=>g+f.probability,0)/a.length:0,m=Math.round(u*100),p=[];if(a.length>0){p.push(`${a.length} files flagged for potential defects out of ${c.length} analyzed`);let g=a[0];p.push(`Highest risk: ${g.file} (${Math.round(g.probability*100)}%) \u2014 ${g.reason}`)}return a.some(g=>g.reason.includes("Large file"))&&p.push("Consider splitting large files to reduce complexity"),a.some(g=>g.reason.includes("technical debt"))&&p.push("Address TODO/FIXME comments to reduce technical debt"),a.length===0&&p.push(l>0?`No analyzed files exceeded the threshold; ${l} unreadable source files remain unassessed`:"No files exceeded the defect probability threshold \u2014 code looks healthy"),F({predictedDefects:a.slice(0,20),riskScore:m,recommendations:p,filesAnalyzed:c.length,filesSkipped:l,scanStatus:l>0?"partial":"complete",predictionMethod:"static-code-indicators",estimated:!0})}catch(n){return L(B(n))}})}function vi(o){o.registerHandler("test-accessibility",async e=>{let t=e.payload;return F({url:t.url||"",standard:t.standard||"wcag21-aa",passed:!1,violations:[],warnings:[],score:-1,measured:!1,note:"Accessibility NOT MEASURED: this is not a failing result. Accessibility testing requires a browser environment (Puppeteer/Playwright). Use tools like axe-core, pa11y, or Lighthouse CLI for WCAG compliance testing. Example: npx pa11y "+(t.url||"<url>")})}),o.registerHandler("run-chaos",async e=>{let t=e.payload;return F({faultType:t.faultType||"unknown",target:t.target||"unknown",dryRun:t.dryRun??!0,duration:t.duration||0,systemBehavior:"not-executed",resilience:null,note:"Chaos engineering requires infrastructure-level fault injection. Use tools like Chaos Monkey, Litmus, or toxiproxy for real resilience testing. For Node.js apps, consider: nock (HTTP faults), testcontainers (dependency failures)."})}),o.registerHandler("optimize-learning",async e=>{try{let t=await import("./unified-memory-hnsw-3KULVD3N.js");return F({patternsLearned:0,modelsUpdated:0,memoryConsolidated:!1,note:'Learning optimization runs during the dream cycle (SessionEnd hook). Use "npx agentic-qe hooks session-end --save-state" to trigger pattern consolidation.'})}catch{return F({patternsLearned:0,modelsUpdated:0,memoryConsolidated:!1,note:'Learning system not initialized. Run "aqe init --auto" first.'})}})}var ce=ye("TaskExecutor");function Nd(o){return Qe.resolve(Ve.CoverageAnalyzerService)(o)}function Fd(o){return Qe.resolve(Ve.SecurityScannerService)(o)}function Yo(o,e){return Qe.resolve(Ve.createTestGeneratorService)(o,e)}function Ld(o){return Qe.resolve(Ve.KnowledgeGraphService)(o)}function qd(o){return Qe.resolve(Ve.QualityAnalyzerService)(o)}function Jo(o){return o instanceof Ws?{...o.toDetails()}:$e(o)?{callerError:!0}:void 0}function Zo(o){return o===0?"agent-booster":Ts(o)}function $d(o){if(["generate-tests","analyze-coverage","scan-security","execute-tests","assess-quality","validate-contracts","test-accessibility","chaos-test","predict-defects","validate-requirements","index-code"].includes(o.type))return null;let t=o.payload?.codeContext||"",n=o.payload?.sourceCode||"",r=t||n;return r?r.includes("var ")&&!r.includes("const ")&&!r.includes("let ")?"var-to-const":r.includes("console.log")||r.includes("console.warn")||r.includes("console.error")?"remove-console":r.includes(".then(")&&r.includes(".catch(")?"promise-to-async":r.includes("require(")&&!r.includes("import ")?"cjs-to-esm":r.includes("function ")&&!r.includes("=>")?"func-to-arrow":null:null}var Ci=class{constructor(e,t,n){this.kernel=e;this.eventBus=t;this._config={timeout:n?.timeout??3e5,maxRetries:n?.maxRetries??3,enableCaching:n?.enableCaching??!0,saveResults:n?.saveResults??!0,resultsDir:n?.resultsDir??en(),defaultLanguage:n?.defaultLanguage??"typescript",defaultFramework:n?.defaultFramework??"vitest"},this.resultSaver=po(this._config.resultsDir),this.registerHandlers()}kernel;eventBus;_config;resultSaver;coverageAnalyzer=null;securityScanner=null;testGenerator=null;deterministicTestGenerator=null;knowledgeGraph=null;qualityAnalyzer=null;agentBooster=null;taskRouter=null;qualityFeedbackLoop=null;coherenceActionGate=null;taskHandlers=new Map;get memory(){return this.kernel.memory}get config(){return this._config}registerHandler(e,t){this.taskHandlers.set(e,t)}setQualityFeedbackLoop(e){this.qualityFeedbackLoop=e}getCoverageAnalyzer(){return this.coverageAnalyzer||(this.coverageAnalyzer=Nd(this.kernel.memory)),this.coverageAnalyzer}getSecurityScanner(){return this.securityScanner||(this.securityScanner=Fd(this.kernel.memory)),this.securityScanner}async getTestGenerator(e=!0){return e?(this.testGenerator||(this.testGenerator=Yo(this.kernel.memory,await this.resolveLLMRouter())),this.testGenerator):(this.deterministicTestGenerator||(this.deterministicTestGenerator=Yo(this.kernel.memory)),this.deterministicTestGenerator)}async resolveLLMRouter(){if(this.kernel.llmRouter)return this.kernel.llmRouter;try{let{getSharedLLMRouter:e}=await import("./base-MAK2BLTG.js");return await e()??void 0}catch(e){ce.debug("LLM router unavailable; using deterministic generation",{error:w(e)});return}}getKnowledgeGraph(){return this.knowledgeGraph||(this.knowledgeGraph=Ld(this.kernel.memory)),this.knowledgeGraph}async getCodeIntelligenceCoordinator(){try{let e=this.kernel.getDomainAPIAsync?await this.kernel.getDomainAPIAsync("code-intelligence"):this.kernel.getDomainAPI("code-intelligence");return typeof e?.getCoordinator=="function"?e.getCoordinator():void 0}catch(e){ce.debug("code-intelligence coordinator unavailable for project metrics",{error:e instanceof Error?e.message:String(e)});return}}getQualityAnalyzer(){return this.qualityAnalyzer||(this.qualityAnalyzer=qd(this.kernel.memory)),this.qualityAnalyzer}async getTestExecutionAPI(){return this.kernel.getDomainAPIAsync?this.kernel.getDomainAPIAsync("test-execution"):this.kernel.getDomainAPI("test-execution")}registerHandlers(){ri(this),li(this),mi(this),gi(this),fi(this),yi(this),vi(this)}async getAgentBooster(){return this.agentBooster||(this.agentBooster=await mn({enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7})),this.agentBooster}async getTaskRouterInstance(){if(!this.taskRouter)try{this.taskRouter=await Nn()}catch{return null}return this.taskRouter}async executeWithAgentBooster(e,t,n){let r=$d(e);if(!r)return console.debug(`[TaskExecutor] No applicable Agent Booster transform for task ${e.id}`),null;try{let i=await this.getAgentBooster(),s=e.payload?.codeContext||e.payload?.sourceCode||"",a=await i.transform(s,r);return a.success&&a.confidence>=.7?(console.debug(`[TaskExecutor] Agent Booster transform succeeded: ${r}, confidence=${a.confidence}`),{taskId:e.id,success:!0,data:{transformed:!0,transformType:r,originalCode:a.originalCode,transformedCode:a.transformedCode,confidence:a.confidence,implementationUsed:a.implementationUsed,durationMs:a.durationMs,changeCount:a.changeCount,tier:0,model:"agent-booster"},duration:Date.now()-t,domain:n}):(console.debug(`[TaskExecutor] Agent Booster low confidence (${a.confidence}), falling back to Tier 1`),null)}catch(i){return console.warn(`[TaskExecutor] Agent Booster error, falling back: ${i}`),null}}async recordOutcome(e,t,n,r){try{if(!await this.getTaskRouterInstance())return;if(console.debug(`[TaskExecutor] Outcome recorded: task=${e.id}, tier=${t}, model=${Zo(t)}, success=${n}, duration=${r}ms`),this.qualityFeedbackLoop){let s=e.targetDomains||[],a=n?1:0,c=r<100?1:r<500?.8:r<2e3?.6:r<5e3?.4:r<1e4?.2:.1,l=.25*a+.325+.1*c;await this.qualityFeedbackLoop.recordRoutingOutcome({taskId:e.id,taskDescription:e.type,recommendedAgent:String(t),usedAgent:String(t),followedRecommendation:!0,success:n,qualityScore:l,durationMs:r,timestamp:new Date,error:n?void 0:"Task execution failed"})}}catch(i){console.warn("[TaskExecutor] Failed to record outcome:",i)}}async execute(e){let t=Date.now(),n=this.getTaskDomain(e.type),r=e.payload,i=r?.routingTier??2,s=r?.useAgentBooster??!1,a=r?.compiledContext??void 0,c=Zo(i);a&&e.payload&&(e.payload.__compiledContext=a),console.debug(`[TaskExecutor] Executing task ${e.id}: type=${e.type}, tier=${i}, model=${c}, useAgentBooster=${s}${a?", hasContext=true":""}`);let l=this.evaluateCoherenceGate(e,n);l&&console.debug(`[TaskExecutor] Coherence gate: task=${e.id}, decision=${l.decision}, combined=${l.combinedScore.toFixed(3)}, advisory=${l.advisory}`),this.validateWithReasoningQEC(e,n);try{if(i===0||s){let p=await this.executeWithAgentBooster(e,t,n);if(p)return this.recordOutcome(e,0,!0,Date.now()-t).catch(g=>{ce.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})}),await this.publishTaskCompleted(e.id,p.data,n),p;console.debug(`[TaskExecutor] Agent Booster fallback to Tier 1 for task ${e.id}`)}let d=this.taskHandlers.get(e.type);if(!d){let p={taskId:e.id,success:!1,error:`No handler registered for task type: ${e.type}`,duration:Date.now()-t,domain:n};return this.recordOutcome(e,i,!1,Date.now()-t).catch(g=>{ce.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})}),p}let u=await Promise.race([d(e),this.timeout(e.timeout||this._config.timeout)]);if(!u.success){let p="error"in u?u.error.message:"Unknown error";await this.publishTaskFailed(e.id,p,n,"error"in u&&$e(u.error)),this.recordOutcome(e,i,!1,Date.now()-t).catch(f=>{ce.warn("recordOutcome failed",{error:f instanceof Error?f.message:String(f),taskId:e.id})});let g="error"in u?Jo(u.error):void 0;return{taskId:e.id,success:!1,error:p,duration:Date.now()-t,domain:n,...g?{errorDetails:g}:{}}}await this.publishTaskCompleted(e.id,u.value,n),We(n,u.value)&&this.recordOutcome(e,i,!0,Date.now()-t).catch(p=>{ce.warn("recordOutcome failed",{error:p instanceof Error?p.message:String(p),taskId:e.id})});let m;if(this._config.saveResults&&r?.saveResults!==!1)try{let p={language:r?.language||this._config.defaultLanguage,framework:r?.framework||this._config.defaultFramework,includeSecondary:!0};m=(await this.resultSaver.save(e.id,e.type,u.value,p)).files.map(f=>f.path)}catch(p){console.error(`[TaskExecutor] Failed to save results: ${p}`)}return{taskId:e.id,success:!0,data:{...u.value,_routing:{tier:i,model:c,usedAgentBooster:!1}},duration:Date.now()-t,domain:n,savedFiles:m}}catch(d){let u=w(d);await this.publishTaskFailed(e.id,u,n,$e(d)),this.recordOutcome(e,i,!1,Date.now()-t).catch(p=>{ce.warn("recordOutcome failed",{error:p instanceof Error?p.message:String(p),taskId:e.id})});let m=Jo(d);return{taskId:e.id,success:!1,error:u,duration:Date.now()-t,domain:n,...m?{errorDetails:m}:{}}}}async resetServiceCaches(){if(this.coverageAnalyzer=null,this.securityScanner=null,this.testGenerator=null,this.knowledgeGraph=null,this.qualityAnalyzer=null,this.coherenceActionGate=null,this.agentBooster){try{await this.agentBooster.dispose()}catch(e){console.debug("[TaskExecutor] Agent Booster disposal error:",e instanceof Error?e.message:e)}this.agentBooster=null}this.taskRouter=null}resetServiceCachesSync(){this.coverageAnalyzer=null,this.securityScanner=null,this.testGenerator=null,this.knowledgeGraph=null,this.qualityAnalyzer=null,this.agentBooster=null,this.taskRouter=null,this.coherenceActionGate=null}evaluateCoherenceGate(e,t){try{this.coherenceActionGate||(this.coherenceActionGate=wo({advisory:!0}));let n=e.payload,r=typeof n?.confidence=="number"?n.confidence:.7,i=n?.riskLevel??"medium";return Ro(e.type,t,r,i,n??{},this.coherenceActionGate)}catch(n){return ce.warn("Coherence gate evaluation error (continuing)",{error:n instanceof Error?n.message:String(n),taskId:e.id}),null}}_reasoningQEC=null;_reasoningQECLoaded=!1;validateWithReasoningQEC(e,t){try{if(!this._reasoningQECLoaded){this._reasoningQECLoaded=!0;try{let{isReasoningQECEnabled:s}=(Yt(),gs(Sl));if(s()){let{createReasoningQEC:a}=(Xo(),gs(Ko));this._reasoningQEC=a()}}catch(s){ce.debug("ReasoningQEC module unavailable",{error:s instanceof Error?s.message:String(s)})}}if(!this._reasoningQEC)return;let n=e.payload,r=n?.reasoningSteps;if(!r||r.length<2)return;let i=this._reasoningQEC.validate({type:t,context:n,steps:r});i.valid||ce.warn("ReasoningQEC validation found issues (advisory)",{taskId:e.id,domain:t,confidence:i.confidence,issues:i.issues.length})}catch(n){ce.debug("ReasoningQEC evaluation error",{error:n instanceof Error?n.message:String(n),taskId:e.id})}}getTaskDomain(e){return{"generate-tests":"test-generation","execute-tests":"test-execution","analyze-coverage":"coverage-analysis","assess-quality":"quality-assessment","predict-defects":"defect-intelligence","validate-requirements":"requirements-validation","index-code":"code-intelligence","scan-security":"security-compliance","validate-contracts":"contract-testing","test-accessibility":"visual-accessibility","run-chaos":"chaos-resilience","optimize-learning":"learning-optimization","cross-domain-workflow":"learning-optimization","protocol-execution":"learning-optimization","ideation-assessment":"requirements-validation"}[e]||"learning-optimization"}async timeout(e){return new Promise((t,n)=>{setTimeout(()=>n(new Error(`Task execution timed out after ${e}ms`)),e)})}async publishTaskCompleted(e,t,n){await this.eventBus.publish({id:U(),type:"TaskCompleted",timestamp:new Date,source:n,payload:{taskId:e,result:t}})}async publishTaskFailed(e,t,n,r=!1){await this.eventBus.publish({id:U(),type:"TaskFailed",timestamp:new Date,source:n,payload:{taskId:e,error:t,...r?{callerError:!0}:{}}})}};function ec(o,e){return new Ci(o,o.eventBus,e)}async function tc(){}import{randomUUID as et}from"crypto";D();var Si=".agentic-qe/results/";function nc(o){if(o===null||typeof o!="object")return!0;let e=o.saveResults;if(e==null)return!0;if(typeof e!="boolean")throw new Error(`saveResults must be a boolean (true or false), got ${typeof e}.`);return e}function Hn(o,e){if(!o)return{resultsSaved:!1,savedFiles:[],resultsNote:`saveResults was false: no files were written under ${Si}.`};let t=e??[];return t.length===0?{resultsSaved:!1,savedFiles:[],resultsNote:`No result files were written under ${Si} (saving is disabled or failed).`}:{resultsSaved:!0,savedFiles:t,resultsNote:`Saved ${t.length} result file(s) under ${Si}; see savedFiles. Pass saveResults: false to skip.`}}var Ti={effectiveness:.25,coverage:.2,mutationKill:.15,stability:.15,maintainability:.15,performance:.1},Ei={"short-term":{minSuccessCount:0,minSuccessRate:0,minQualityScore:0,minAgeDays:0},working:{minSuccessCount:3,minSuccessRate:.6,minQualityScore:.5,minAgeDays:1},"long-term":{minSuccessCount:10,minSuccessRate:.75,minQualityScore:.7,minAgeDays:7},permanent:{minSuccessCount:50,minSuccessRate:.9,minQualityScore:.85,minAgeDays:30}},xe={qualityWeights:Ti,promotionCriteria:Ei,autoPromote:!0,autoDemote:!0,minCoverageImprovementToLearn:5,maxOutcomesInMemory:1e4,persistOutcomes:!0,batchSize:100};pe();D();ee();var wi=class{outcomes=[];maxOutcomes;constructor(e){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getAll(){return[...this.outcomes]}getByPattern(e){return this.outcomes.filter(t=>t.patternId===e)}getByAgent(e){return this.outcomes.filter(t=>t.generatedBy===e)}getByDomain(e){return this.outcomes.filter(t=>t.domain===e)}getRecent(e){return this.outcomes.slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},Ri=class o{store;reasoningBank=null;config;db=null;persistCount=0;static RETENTION_CLEANUP_INTERVAL=100;patternMetrics=new Map;constructor(e={}){this.config={...xe,...e},this.store=new wi(this.config.maxOutcomesInMemory)}connectReasoningBank(e){this.reasoningBank=e}async initialize(){try{this.db=X(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb()}catch(e){console.warn("[TestOutcomeTracker] DB initialization failed, using memory-only:",w(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
419
+ ${i.trim()}`}function oi(o){return typeof o.numFailedTests=="number"||typeof o.numFailedTestSuites=="number"?(o.numFailedTests??0)>0||(o.numFailedTestSuites??0)>0?"failed":"passed":o.exitedCleanly?"passed":"failed"}var Bu="test-results.json";function Hu(o,e,t=e,n=10){let r=z.resolve(o);for(let i=0;i<=n;i++){let s=z.join(r,"node_modules",e);try{let c=JSON.parse(H.readFileSync(z.join(s,"package.json"),"utf-8")),l=typeof c.bin=="string"?c.bin:c.bin?.[t];if(l){let u=z.join(s,l);if(H.existsSync(u))return u}}catch{}let a=z.dirname(r);if(a===r)break;r=a}return null}function Vu(o){try{let e=I(H.readFileSync(z.join(o,"package.json"),"utf-8"));return{...e.devDependencies||{},...e.dependencies||{}}}catch{return{}}}var Qu=["jest","@jest/core","mocha","nyc","vitest"];function ci(o,e=10){let t=[],n=null;try{n=H.realpathSync($n.homedir())}catch{n=null}let r=z.resolve(o);for(let i=0;i<=e&&!(i>0&&n!==null&&r===n||(t.push(r),H.existsSync(z.join(r,".git"))||Wu(r)));i++){let s=z.dirname(r);if(s===r)break;r=s}return t}function Wu(o){try{return JSON.parse(H.readFileSync(z.join(o,"package.json"),"utf-8")).workspaces!==void 0}catch{return!1}}function Ku(o){for(let e of ci(o)){let t=Vu(e);if(Qu.some(n=>t[n]))return t}return{}}function Xu(o){return ci(o).map(e=>z.join(e,"node_modules",".bin")).filter(e=>H.existsSync(e))}function Yu(o){return ci(o).some(e=>H.existsSync(z.join(e,".pnp.cjs"))||H.existsSync(z.join(e,".pnp.js")))}function Ju(o,e,t){let n=z.join(e,Bu),r=Ku(o),i="vitest",s,a=n;r.jest||r["@jest/core"]?(i="jest",s=["--coverage",`--coverageDirectory=${e}`,"--coverageReporters=json","--json",`--outputFile=${n}`]):r.mocha||r.nyc?(i="nyc",s=[`--report-dir=${e}`,`--temp-dir=${z.join(e,".nyc_output")}`,"--reporter=json","mocha"],a=null):s=["run","--coverage",`--coverage.reportsDirectory=${e}`,"--coverage.reporter=json","--coverage.reportOnFailure=true","--reporter=json",`--outputFile=${n}`],t&&i!=="nyc"&&s.push(i==="jest"?t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):t);let c=Hu(o,i==="jest"?"jest":i);return{runner:i,command:c?process.execPath:null,args:c?[c,...s]:s,resultsFile:a}}var si={numTotalTests:null,numPassedTests:null,numFailedTests:null,numPendingTests:null,numFailedTestSuites:null};function Zu(o){if(!o)return si;try{let e=JSON.parse(H.readFileSync(o,"utf-8")),t=n=>typeof e[n]=="number"?e[n]:null;return{numTotalTests:t("numTotalTests"),numPassedTests:t("numPassedTests"),numFailedTests:t("numFailedTests"),numPendingTests:t("numPendingTests"),numFailedTestSuites:t("numFailedTestSuites")}}catch{return si}}async function ed(o){let e=await Qa(o);if(e)return e;try{let t=JSON.parse(H.readFileSync(o,"utf-8"));if(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0)return{files:[],summary:{line:0,branch:0,function:0,statement:0,files:0}}}catch{}return null}var qn=new Map,Po=!1;function At(o,e){if(process.platform==="win32"){try{Uu("taskkill",["/pid",String(o),"/T","/F"],{stdio:"ignore"})}catch{}return}try{process.kill(-o,e)}catch{}}function td(){for(let[o,e]of qn)if(At(o,"SIGKILL"),e)try{H.rmSync(e,{recursive:!0,force:!0})}catch{}qn.clear()}function nd(){Po||(process.on("exit",td),Po=!0)}function ai(o){try{return process.kill(-o,0),!0}catch{return!1}}async function xo(o,e){if(process.platform==="win32")return;let t=Date.now()+e;for(;ai(o)&&Date.now()<t;)await new Promise(n=>setTimeout(n,50))}async function rd(o,e,t){let n=t.graceMs??3e3,r=process.platform==="win32";return nd(),new Promise(i=>{let s=!1,a=!1,c="",l="",u=0,d=zu(o,e,{cwd:t.cwd,env:t.env??process.env,detached:!r,shell:!1,stdio:["ignore","ignore","pipe"],windowsHide:!0});d.pid!==void 0&&qn.set(d.pid,t.cleanupDir),d.stderr?.on("data",f=>{let g=f.toString("utf-8");u+=f.length,l.length<Ln&&(l=(l+g).slice(0,Ln)),c=(c+g).slice(-Ln)}),d.stderr?.on("error",()=>{});let m=async(f,g)=>{a||(a=!0,clearTimeout(p),d.pid!==void 0&&!r&&ai(d.pid)&&(At(d.pid,"SIGTERM"),await xo(d.pid,n),ai(d.pid)&&At(d.pid,"SIGKILL"),await xo(d.pid,n)),d.stderr?.destroy(),d.pid!==void 0&&qn.delete(d.pid),i({exitCode:f,timedOut:s,spawnError:g,pid:d.pid,stderrTail:Ro(l,c,u)}))},p=setTimeout(()=>{s=!0,d.pid!==void 0&&(At(d.pid,"SIGTERM"),setTimeout(()=>{!a&&d.pid!==void 0&&At(d.pid,"SIGKILL")},n).unref())},t.timeoutMs);d.on("error",()=>{m(null,!0)}),d.on("exit",f=>{m(f,!1)})})}async function li(o,e={}){let t=e.timeoutMs??12e4,n=H.mkdtempSync(z.join($n.tmpdir(),"aqe-js-cov-"));try{let r=Ju(o,n,e.pathFilter);if(!r.command)return{runner:r.runner,missing:!0,exitCode:null,exitedCleanly:!1,timedOut:!1,timeoutMs:t,data:null,numTotalTests:null,stderrTail:""};let i=Xu(o),s=z.join(n,"tmp");H.mkdirSync(s);let a={...process.env,PATH:[...i,process.env.PATH??""].join(z.delimiter),TMPDIR:s,TMP:s,TEMP:s},c=await rd(r.command,r.args,{cwd:o,timeoutMs:t,cleanupDir:n,env:a}),l=c.timedOut?null:await ed(z.join(n,"coverage-final.json"));return{runner:r.runner,missing:!1,exitCode:c.exitCode,exitedCleanly:c.exitCode===0&&!c.timedOut,timedOut:c.timedOut,timeoutMs:t,data:l,...c.timedOut?si:Zu(r.resultsFile),stderrTail:c.stderrTail}}finally{try{H.rmSync(n,{recursive:!0,force:!0})}catch{}}}function Ao(o,e){if(o.missing&&Yu(e))return`${o.runner} could not be resolved for ${e}: this project uses Yarn Plug'n'Play, and agentic-qe resolves test runners only from node_modules. Nothing was run and nothing was downloaded. Generate a coverage report (e.g. \`yarn ${o.runner} --coverage\`) and pass it as the target, or use the node-modules linker.`;if(o.missing)return`${o.runner} is not installed in ${e} (no node_modules/${o.runner} found); nothing was run and nothing was downloaded. Install it, or generate a coverage report and pass it as the target.`;if(o.timedOut)return`The coverage run timed out after ${Math.round(o.timeoutMs/1e3)}s and was stopped.`;if(o.exitCode!==0){let t=o.stderrTail?`: ${o.stderrTail}`:"";return`Test runner (${o.runner}) exited with code ${o.exitCode??"unknown"} without a coverage report${t}`}return`Test runner (${o.runner}) exited cleanly but wrote no coverage report. Ensure a coverage provider is configured (e.g., @vitest/coverage-v8, istanbul).`}function ko(o=process.env){let e=Number.parseInt(o.AQE_COVERAGE_TIMEOUT_MS??"",10);return Number.isFinite(e)&&e>0?e:12e4}function Io(o){let e=s=>o.reduce((a,c)=>a+s(c),0),t=(s,a)=>a>0?Math.round(s/a*100):0,n=e(s=>s.lines.total),r=e(s=>s.lines.covered),i=e(s=>s.statements.total);return{line:t(r,n),branch:t(e(s=>s.branches.covered),e(s=>s.branches.total)),function:t(e(s=>s.functions.covered),e(s=>s.functions.total)),statement:i>0?t(e(s=>s.statements.covered),i):t(r,n),files:o.length}}function sd(o){return{data:{files:o,summary:Io(o)},provenance:{method:"instrumented-report",estimated:!1,branchDataCollected:o.some(e=>e.branches.total>0),functionDataCollected:o.some(e=>e.functions.total>0),notes:[]}}}function Do(o,e,t){return o.status==="measured"?{collected:sd(o.files),ranTests:e,projectRoot:t,evidence:o.evidence}:{collected:null,ranTests:e,noData:o.reason,projectRoot:t,...o.refused?{refused:o.refused}:{}}}async function ad(o){let e=await Xa(o);if(e.status==="target-missing")return{collected:null,ranTests:!1,noData:"target-missing",projectRoot:null};if(e.status==="evaluated")return Do(e.evaluation,!1,e.projectRoot);let t=await od(e.target,e.projectRoot);return e.refused.length>0?{...t,refused:e.refused}:t}async function od(o,e){if(Gr(o)){let l=await Ua(o);if(l){let u=za(o)??e,d=Wa(l.data,u,o);return d.length===0?{collected:null,ranTests:!0,noData:"target-not-covered",projectRoot:u}:{collected:d.length===l.data.files.length?l:{data:{files:d,summary:Io(d)},provenance:l.provenance},ranTests:!0,projectRoot:u}}return{collected:fn(o),ranTests:!1,projectRoot:e}}if($r())return{collected:fn(o),ranTests:!1,projectRoot:e};let t=Va(o,e),n=await li(e,{timeoutMs:ko(),pathFilter:t}),r=n.missing&&n.numTotalTests===null,i=!n.missing&&n.numTotalTests===0&&oi(n)==="passed"&&(n.exitCode===0||n.exitCode===1);t&&!n.timedOut&&(r||i)&&(e=Mo.resolve(e,t),n=await li(e,{timeoutMs:ko()}));let s=n.data!==null&&n.data.files.length===0&&n.numTotalTests===null&&!n.exitedCleanly;if(n.data&&!s||n.numTotalTests===0){let l=n.data?Ka(n.data,e,o,{numTotalTests:n.numTotalTests}):{status:"no-data",reason:"no-tests-ran"},u=Do(l,n.exitedCleanly||n.data!==null,e);return u.collected&&(u.runStatus=oi(n),typeof n.numPassedTests=="number"&&typeof n.numFailedTests=="number"&&(u.testRun={runId:id(),passed:n.numPassedTests,failed:n.numFailedTests,skipped:n.numPendingTests??0})),u}let a=fn(o),c=Ao(n,e);return a&&(a.provenance.notes=[`${c} These numbers are a STATIC ESTIMATE derived from source shape \u2014 not measured coverage, and must not be reported as such.`,...a.provenance.notes.filter(l=>!/^No instrumentation ran/.test(l))]),{collected:a,ranTests:n.exitedCleanly,projectRoot:e,notes:a?[]:[c]}}function cd(o,e,t,n,r=[]){return o?jr(o,t,n,r):e?"Tests ran but no coverage output was generated. Ensure a coverage provider is configured (e.g., @vitest/coverage-v8, istanbul).":"No coverage data found and could not run tests automatically. "+_o(t)}function _o(o){return $r()?"Coverage tooling execution is disabled (AQE_COVERAGE_NO_EXEC). No tests were run and no build tooling was invoked. Unset it, or generate a coverage report yourself and re-run, to get real measurements.":Gr(o)?"To get real measurements for this Rust crate, install cargo-llvm-cov (`cargo install cargo-llvm-cov`) and re-run; agentic-qe will invoke it automatically.":"To get real measurements, run your tests with coverage enabled (e.g. `npm test -- --coverage`, `pytest --cov`) and re-run this analysis."}function ui(o){o.registerHandler("analyze-coverage",async e=>{let t=e.payload;try{let n=t.target||process.cwd();if(t.target&&t.target!=="."){let L=await X("analyze-coverage","target",t.target,{allowDirectory:!0,allowMissing:!0});if(!L.success)return L;n=L.value}let r=o.getCoverageAnalyzer(),i=t.threshold||80,{collected:s,ranTests:a,noData:c,projectRoot:l,notes:u,runStatus:d,testRun:m,evidence:p,refused:f}=await ad(n),g=f?.length&&c!=="refused-report"?[eo(f)]:[];if(c==="target-missing")return q(new Error(jr("target-missing",n,null)));if(!s){let L=c!==void 0&&Za(c);return F({lineCoverage:null,branchCoverage:null,functionCoverage:null,statementCoverage:null,totalFiles:0,coverageByFile:[],gaps:[],estimated:!1,measured:!1,coverageMethod:"none",...L?{unmeasured:!0}:{},algorithm:"sublinear-O(log n)",warning:[...g,u?.length?u.join(" "):cd(c,a,n,l,f)].join(" ")})}let{data:h,provenance:y}=s,v=await r.analyze({coverageData:h,threshold:i,includeFileDetails:t.detectGaps,measured:!y.estimated,...l?{projectRoot:l}:{},...d&&!y.estimated?{runStatus:d}:{},...m&&!y.estimated?{testRun:m}:{}});if(!v.success)return v;let b=v.value,C=[];if(t.detectGaps){let L=await r.findGaps(h,i);L.success&&(C=L.value.gaps.map(oe=>({file:oe.file,lines:oe.lines,risk:oe.severity,estimated:y.estimated,...y.estimated?{confidence:.2,reason:"Possible coverage gap (STATIC ESTIMATE \u2014 no instrumentation ran)"}:{}})))}let E=L=>Math.round(L*10)/10,T=(L,oe)=>oe>0?Math.round(L/oe*1e3)/10:null,S=Ba(p,l??n),x=[...g,...y.notes,...u??[]];y.estimated&&x.push(_o(n)),S.length>0&&x.push(`INSUFFICIENT EVIDENCE \u2014 the threshold is not met on this report: ${S.join("; ").replace(/\.?$/,".")}`),x.push(...Ha(p));let k=y.estimated||Zs(h.files).statement,_={branch:y.branchDataCollected,function:y.functionDataCollected,statement:k},N=Ya(b.summary,i,_),V=Ja(b.recommendations,N,i,_);return F({lineCoverage:E(b.summary.line),branchCoverage:y.branchDataCollected?E(b.summary.branch):null,functionCoverage:y.functionDataCollected?E(b.summary.function):null,statementCoverage:k?E(b.summary.statement):null,totalFiles:b.summary.files,coverageByFile:h.files.map(L=>({file:L.path,lineCoverage:T(L.lines.covered,L.lines.total)??0,branchCoverage:y.branchDataCollected?T(L.branches.covered,L.branches.total):null,functionCoverage:y.functionDataCollected?T(L.functions.covered,L.functions.total):null})),gaps:C,meetsThreshold:N.meetsThreshold&&S.length===0,...p?{evidenceStatus:p.status,unmeasuredFiles:p.unmeasuredFiles,...p.stale?{staleReport:p.stale}:{},...p.conflictingFiles?{conflictingFiles:p.conflictingFiles}:{},...p.excludedEntries?{excludedReportEntries:p.excludedEntries}:{}}:{},delta:b.delta,recommendations:V,algorithm:"sublinear-O(log n)",estimated:y.estimated,measured:!y.estimated,coverageMethod:y.method,branchDataCollected:y.branchDataCollected,functionDataCollected:y.functionDataCollected,statementDataCollected:k,...d&&!y.estimated?{runStatus:d}:{},...x.length>0?{warning:x.join(" ")}:{}})}catch(n){return q(B(n))}})}import*as zn from"path";M();import{createHash as Gn}from"node:crypto";import{realpath as ld}from"node:fs/promises";import*as Fo from"node:path";var di="Dangerous eval/exec usage";function ud(o){return/\[CWE-95\]/.test(o.description??"")||(o.references??[]).some(e=>/\/definitions\/95\.html$/.test(e))}var dd={informational:0,low:1,medium:2,high:3,critical:4},Oo=o=>dd[o??""]??-1;async function No(o,e){let t=Fo.resolve(o),n=e.get(t);return n===void 0&&(n=await ld(t).catch(()=>t),e.set(t,n)),n}async function Lo(o,e,t){let n=e.filter(ud);if(n.length===0)return[...o];let r=new Map,i=new Map;for(let a of n){let c=`${await No(a.location.file,r)}:${a.location.line??0}`;i.set(c,Math.max(i.get(c)??-1,Oo(a.severity)))}let s=[];for(let a of o){let c=`${await No(a.location.file,r)}:${a.location.line??0}`,l=i.get(c);a.title===di&&t(a)&&l!==void 0&&l>=Oo(a.severity)||s.push(a)}return s}function pi(o){o.registerHandler("scan-security",async e=>{let t=e.payload;try{let n=zn.resolve(t.target||process.cwd()),r=t.sast!==!1||t.dependencies===!0;if(t.target&&t.target!=="."&&r){let R=await X("scan-security","target",t.target,{allowDirectory:!0,allowMissing:!0,maxBytes:ne});if(!R.success)return R;n=R.value}let i=t.sast!==!1,s=i?await no(n):void 0,a=s?.files??[],c=[],l=[],u=new Map,d=[],m=[],p=new Map,f=[],g=a.filter(R=>/\.(ts|tsx|js|jsx|mjs|cjs)$/i.test(R)),h=a.filter(R=>!/\.(ts|tsx|js|jsx|mjs|cjs)$/i.test(R)),y=[],v=new Set;for(let R of a){if(!to(R)){c.push({path:R,engineId:"generic-patterns",status:"unsupported",readLines:0,analyzedLines:0,reason:"Outside the declared source-language policy."});continue}try{let ee=await Ir(R,{outsideRoot:"allow"}),Z=ee.toString("utf-8"),W=Z.split(`
420
+ `);c.push({path:R,engineId:"generic-patterns",status:"analyzed",sourceDigest:Gn("sha256").update(ee).digest("hex"),readLines:W.length,analyzedLines:W.length});let ke=[{regex:/\w*(?:secret|password|passwd|api_key|apikey|private_key|jwt_secret)\w*\s*[=:]\s*['"][^'"]{4,}['"]/gi,title:"Hardcoded secret",severity:"critical"},{regex:/\w*(?:token|auth_token|access_key|secret_key)\w*\s*[=:]\s*['"][^'"]{8,}['"]/gi,title:"Hardcoded credential",severity:"critical"},{regex:/(?:AWS_SECRET|GITHUB_TOKEN|SLACK_TOKEN|OPENAI_API_KEY)\s*[=:]\s*['"][^'"]+['"]/gi,title:"Hardcoded cloud credential",severity:"critical"}];for(let[K,ce]of ke.entries()){u.set(`secret-${K}`,ce.regex.toString());for(let Me=0;Me<W.length;Me++){let fl=[...W[Me].matchAll(ce.regex)];for(let tg of fl)y.push({title:ce.title,severity:ce.severity,location:{file:R,line:Me+1},description:`Potential hardcoded secret found at line ${Me+1}`,category:"sensitive-data"})}}let Tt=/(?:execute|query|cursor\.execute)\s*\(\s*(?:f['"]|['"].*%s|['"].*\+\s*\w)/gi;u.set("sql-interpolation",Tt.toString());for(let K=0;K<W.length;K++)Tt.test(W[K])&&y.push({title:"Potential SQL injection",severity:"high",location:{file:R,line:K+1},description:"String interpolation in SQL query \u2014 use parameterized queries",category:"injection"}),Tt.lastIndex=0;let pe=[/allow_origins\s*=\s*\[?\s*['"]?\*['"]?\s*\]?/i,/cors\(\s*\{[^}]*origin:\s*['"]?\*['"]?/i,/Access-Control-Allow-Origin['":\s]+\*/i,/@CrossOrigin\(\s*origins?\s*=\s*["']\*["']/i,/\.Header\(\)\.Set\(["']Access-Control-Allow-Origin["'],\s*["']\*["']/i];for(let[K,ce]of pe.entries())if(u.set(`cors-${K}`,ce.toString()),ce.test(Z)){y.push({title:"CORS wildcard origin",severity:"high",location:{file:R,line:W.findIndex(Me=>ce.test(Me))+1},description:"CORS configured with wildcard (*) origin \u2014 restrict to specific domains",category:"security-misconfiguration"});break}u.set("debug-mode","/(?:DEBUG|debug)\\s*[=:]\\s*(?:True|true|1)/i"),/(?:DEBUG|debug)\s*[=:]\s*(?:True|true|1)/i.test(Z)&&y.push({title:"Debug mode enabled",severity:"medium",location:{file:R,line:W.findIndex(K=>/DEBUG\s*[=:]\s*(?:True|true|1)/i.test(K))+1},description:"Debug mode should be disabled in production",category:"security-misconfiguration"}),u.set("eval-exec","/\\b(?:eval|exec)\\s*\\(/i");for(let K=0;K<W.length;K++){if(!/\b(?:eval|exec)\s*\(/i.test(W[K]))continue;let ce={title:di,severity:"high",location:{file:R,line:K+1},description:"eval/exec can lead to code injection \u2014 avoid using with user input",category:"injection"};y.push(ce),/\bexec\s*\(/i.test(W[K])||v.add(ce)}}catch(ee){let Z=`Source read failed: ${mi(ee)}`;d.push(`${R}: ${Z}`),c.push({path:R,engineId:"generic-patterns",status:"unreadable",readLines:0,analyzedLines:0,reason:Z})}}let b=["requirements.txt","pyproject.toml","Gemfile","go.mod","Cargo.toml"];for(let R of i?b:[]){let ee=zn.join(n,R);try{let Z=await Ir(ee,{outsideRoot:"allow"}),W=Z.toString("utf-8"),ke=W.split(`
421
+ `).length;if(c.push({path:ee,engineId:"dependency-manifest-patterns",status:"analyzed",sourceDigest:Gn("sha256").update(Z).digest("hex"),readLines:ke,analyzedLines:ke}),p.set("dependency-audit-advisory","Presence of a supported dependency manifest"),y.push({title:"Dependency audit recommended",severity:"informational",location:{file:R,line:1},description:`Found ${R} \u2014 run language-specific dependency audit (e.g., pip-audit, npm audit, cargo audit)`,category:"dependencies"}),R==="requirements.txt"||R==="pyproject.toml"){let Tt=[{pkg:"python-jose",pattern:/python-jose/i,cve:"CVE-2024-33663",severity:"high",title:"python-jose ECDSA key confusion (CVE-2024-33663)",description:"python-jose allows ECDSA key confusion \u2014 upgrade to >=3.3.0 or switch to PyJWT"},{pkg:"python-jose",pattern:/python-jose/i,cve:"CVE-2024-33664",severity:"high",title:"python-jose JWT algorithm confusion (CVE-2024-33664)",description:"python-jose JWT algorithm confusion vulnerability \u2014 upgrade or switch to PyJWT"},{pkg:"python-multipart",pattern:/python-multipart/i,cve:"CVE-2026-24486",severity:"critical",title:"python-multipart DoS (CVE-2026-24486)",description:"python-multipart denial of service via crafted multipart data \u2014 upgrade to >=0.0.18"}];for(let pe of Tt)p.set(pe.cve,pe.pattern.toString()),pe.pattern.test(W)&&y.push({title:pe.title,severity:pe.severity,location:{file:R,line:W.split(`
422
+ `).findIndex(K=>pe.pattern.test(K))+1},description:pe.description,category:"dependencies"})}}catch(Z){let W=Z.code;if(W!=="ENOENT"&&W!=="ENOTDIR"){let ke=`Manifest read failed: ${mi(Z)}`;m.push(`${ee}: ${ke}`),c.push({path:ee,engineId:"dependency-manifest-patterns",status:"unreadable",readLines:0,analyzedLines:0,reason:ke})}}}let C=c.filter(R=>R.engineId==="generic-patterns"&&R.status==="analyzed").length,E=c.filter(R=>R.engineId==="dependency-manifest-patterns"&&R.status==="analyzed").length;l.push({id:"dependency-manifest-patterns",requested:i,required:!1,status:i?m.length>0?E>0?"partial":"failed":E>0?"completed":"not-run":"disabled",scope:"parent-directory",target:n,analyzedFiles:E,ruleIds:[...p.keys()].sort(),rulesetDigest:Gn("sha256").update(JSON.stringify([...p.entries()].sort())).digest("hex"),ruleCoverage:"known",errors:m,limitations:["Manifest name patterns are advisories, not a resolved dependency or version audit."]});let T=["Generic text patterns do not establish language-specific or dependency vulnerability coverage."];l.push({id:"generic-patterns",requested:i,required:i,status:i?d.length>0?C>0?"partial":"failed":C===a.length&&C>0?"completed":C>0?"partial":a.length>0?"unavailable":"not-run":"disabled",scope:"requested-files",analyzedFiles:C,ruleIds:[...u.keys()].sort(),rulesetDigest:Gn("sha256").update(JSON.stringify([...u.entries()].sort())).digest("hex"),ruleCoverage:"known",errors:d,limitations:T});let S=g.map(R=>Sa.create(R)),x=null;if(i&&S.length>0)try{let R=await o.getSecurityScanner().scanFiles(S);R.success?(x=R.value,x.evidence?(c.push(...x.evidence.files),l.push(...x.evidence.engines),f.push(...x.evidence.limitations)):l.push(qo("sast","requested-files"))):l.push(jn("sast","requested-files",R.error))}catch(R){l.push(jn("sast","requested-files",R))}else l.push({id:"sast",requested:i,required:!1,status:i?"not-run":"disabled",scope:"requested-files",analyzedFiles:0,ruleCoverage:"unknown",errors:[],limitations:i?["No JS/TS files were available for language-specific SAST."]:[]});let k=null;if(t.dast&&t.targetUrl)try{let R=await o.getSecurityScanner().scanUrl(t.targetUrl,{activeScanning:!0,maxDepth:3,timeout:3e4});R.success?(k=R.value,l.push(k.status==="incomplete"?{...md(k.failedRequests),target:t.targetUrl}:{...qo("dast","url"),target:t.targetUrl})):l.push({...jn("dast","url",R.error),target:t.targetUrl})}catch(R){l.push({...jn("dast","url",R),target:t.targetUrl})}else l.push({id:"dast",requested:t.dast===!0,required:t.dast===!0,status:t.dast?"not-run":"disabled",scope:"url",ruleCoverage:"unknown",errors:t.dast?["DAST was requested without targetUrl."]:[],limitations:[]});let _=null;t.dependencies===!0&&(_=await ro(o.getSecurityScanner(),n),l.push(_.engine)),t.compliance?.length&&l.push({id:"compliance",requested:!0,required:!0,status:"not-run",scope:"requested-files",ruleCoverage:"unknown",errors:[],limitations:["Requested compliance checks are not executed by this task handler."]});let N=new Set(a),V=new Set(c.filter(R=>R.status==="analyzed"&&N.has(R.path)).map(R=>R.path)),L=l.filter(R=>R.requested&&R.required),oe=V.size>0||(_?.report.packagesChecked??0)>0,yt={schemaVersion:1,completeness:oe&&L.every(R=>R.status==="completed")&&(!s||s.discovery.status==="complete")?"complete":oe?"partial":"none",requestedFiles:a.length,requestedPaths:a,duplicateInputs:0,files:c,engines:l,limitations:[...new Set([...f,...l.flatMap(R=>[...R.limitations,...R.errors]),...s?.discovery.issues.map(R=>`${R.path}: ${R.reason}`)??[]])],...s?{discovery:s.discovery}:{}},Er=!!x?.evidence?.engines.some(R=>R.id==="patterns"&&(R.status==="completed"||R.status==="partial")&&(R.analyzedFiles??0)>0),qe=await Lo(y,x?.vulnerabilities??[],R=>v.has(R)),vt={critical:qe.filter(R=>R.severity==="critical").length,high:qe.filter(R=>R.severity==="high").length,medium:qe.filter(R=>R.severity==="medium").length,low:qe.filter(R=>R.severity==="low").length,informational:qe.filter(R=>R.severity==="informational").length},ms=_?.vulnerabilities??[],bt=R=>ms.filter(ee=>ee.severity===R).length,Ct={critical:(x?.summary?.critical||0)+(k?.summary?.critical||0)+vt.critical+bt("critical"),high:(x?.summary?.high||0)+(k?.summary?.high||0)+vt.high+bt("high"),medium:(x?.summary?.medium||0)+(k?.summary?.medium||0)+vt.medium+bt("medium"),low:(x?.summary?.low||0)+(k?.summary?.low||0)+vt.low+bt("low"),informational:(x?.summary?.informational||0)+(k?.summary?.informational||0)+vt.informational+bt("informational")},St=[...x?.vulnerabilities||[],...k?.vulnerabilities||[],...qe,...ms],gl=St.sort((R,ee)=>{let Z={critical:0,high:1,medium:2,low:3,informational:4};return Z[R.severity]-Z[ee.severity]}).slice(0,10).map(R=>({type:R.title,severity:R.severity,file:R.location.file,line:R.location.line,description:R.description})),ps=St.length===0&&yt.completeness!=="complete"?["No findings reported; requested analysis is incomplete or unverified. Inspect execution receipts."]:Js(St);return _&&_.report.status!=="complete"&&ps.unshift(_.report.message),F({vulnerabilities:St.length,critical:Ct.critical,high:Ct.high,medium:Ct.medium,low:Ct.low,informational:Ct.informational,topVulnerabilities:gl,findings:St,recommendations:ps,scanTypes:{sast:t.sast!==!1,dast:t.dast||!1,dependencies:t.dependencies===!0},..._?{dependencyScan:_.report}:{},status:yt.completeness==="complete"?"completed":yt.completeness==="partial"?"partial":"unavailable",evidence:yt,limitations:yt.limitations,filesScanned:V.size,jstsFilesScanned:g.filter(R=>V.has(R)).length,otherFilesScanned:h.filter(R=>V.has(R)).length,...x?.evidence?{coverage:x.coverage}:{},deepAnalysisPerformed:Er,analysisDepth:Er?h.length>0?"sast-patterns-on-js-ts; generic-patterns-on-other-languages":"sast-patterns":C>0?"pattern-matching-only":"none",...Er?{}:{note:"No verified language-specific SAST ran. Generic pattern matches and partial findings do not establish that the target is free of vulnerabilities."}})}catch(n){return q(B(n))}})}function jn(o,e,t){let n=o==="sast"&&t instanceof Error&&t.message.startsWith("No valid rule sets found:")?"No valid rule sets configured.":`${o} execution failed (${mi(t)}).`;return{id:o,requested:!0,required:!0,status:"failed",scope:e,ruleCoverage:"unknown",errors:[n],limitations:[]}}function mi(o){let e=o?.code;return typeof e=="string"&&/^[A-Z0-9_]{1,32}$/.test(e)?e:"UNKNOWN"}function md(o){let e=[...new Set(o.map(t=>t.code))].join(", ");return{id:"dast",requested:!0,required:!0,status:"partial",scope:"url",ruleCoverage:"unknown",errors:[`dast incomplete: ${o.length} request(s) not answered (${e}).`],limitations:o.slice(0,20).map(t=>`dast not answered: ${t.url} (${t.code}: ${t.reason})`)}}function qo(o,e){return{id:o,requested:!0,required:!0,status:"unverified",scope:e,ruleCoverage:"unknown",errors:[],limitations:[`${o} returned no execution receipt; coverage is unverified.`]}}import*as me from"node:path";import{existsSync as pd,promises as gi}from"node:fs";M();Et();var gd=["coverage","complexity","maintainability","testability"],_e=-1,$o="Static analysis only; no quality gate was evaluated. Call quality_assess with runGate: true (or `aqe quality --gate`) for a pass/fail gate on measured evidence.";function kt(o){return aa(o)?o:_e}function fd(o,e){let t=new Map((e??[]).map(n=>[n.metric,n.reason]));return Object.fromEntries(o.map(n=>[n,t.get(n)??(n==="security"?"static analysis never measures security":"the static analyzer produced no measured value")]))}var hd=50;function Go(o,e){let t=me.relative(o,e);return t===""||t!==".."&&!t.startsWith(`..${me.sep}`)&&!me.isAbsolute(t)}async function jo(o,e,t){let n=me.resolve(e,o);if(o.includes("\0")||!Go(e,n))throw new re(`${t} ${JSON.stringify(o)} is outside the project root (${e}).`);let r;try{r=await gi.realpath(n)}catch{return n}let i=await gi.realpath(e).catch(()=>e);if(!Go(i,r))throw new re(`${t} ${JSON.stringify(o)} resolves outside the project root (${e}).`);return n}async function yd(o){let e=ze();if(Array.isArray(o.sourceFiles)&&o.sourceFiles.length>0){let r=[];for(let i of o.sourceFiles){if(typeof i!="string"||i.trim()==="")throw new re("sourceFiles must be a non-empty array of file paths.");r.push(await jo(i,e,"sourceFile"))}return{sourceFiles:r,explicitFiles:r,scope:"sourceFiles"}}if(typeof o.target=="string"&&o.target.trim()!==""){let r=await jo(o.target,e,"target"),i=await gi.stat(r).catch(()=>null);if(!i)throw new re(`target ${JSON.stringify(o.target)} does not exist.`);return i.isFile()?{sourceFiles:[r],explicitFiles:[r],scope:r}:{sourceFiles:await Pe(r,{includeTests:!1,completeScope:!0}),explicitFiles:[],scope:r}}let t=me.join(e,"src"),n=pd(t)?t:e;return{sourceFiles:await Pe(n,{includeTests:!1,completeScope:!0}),explicitFiles:[],scope:n}}function vd(o){return(o??[]).map(e=>`Partial evidence: ${e.metric} measured over ${e.analysedFiles} of ${e.totalFiles} file(s) (${Math.round(e.coverageOfScope*1e3)/10}%); not analysed: `+e.failed.slice(0,3).map(t=>t.reason).join("; ")+(e.failed.length>3?`; and ${e.failed.length-3} more`:"")+".")}function bd(o){if(o===void 0)return gd;try{return un(o)}catch(e){throw new re(B(e).message)}}async function Cd(o){try{let{findCIConfigFile:e,parseCIConfigFile:t}=await import("./ci-config-6L2ROQCW.js"),n=e(o);if(!n)return;let r=t(n);return r.success?r.config?.qualityGate.thresholds.coverage:void 0}catch{return}}async function Sd(o){let e=o.thresholdSource==="default"?void 0:o.threshold;if(e!==void 0&&(typeof e!="number"||!Number.isFinite(e)||e<0||e>100))throw new re("threshold must be a finite number between 0 and 100.");return sa(e,e===void 0?await Cd(process.cwd()):void 0)}function fi(o){o.registerHandler("assess-quality",async e=>{let t=e.payload;try{if(t.runGate===!0){let b=await cn(o.memory);return F({...Xs(b),metrics:b,evidenceStatus:"measured",unmeasured:[],gateEvaluated:!0})}let n=bd(t.metrics),r=await Sd(t),i=o.getQualityAnalyzer(),s=t.threshold||80,{sourceFiles:a,explicitFiles:c,scope:l}=await yd(t);if(a.length===0)return F({qualityScore:_e,passed:!1,threshold:s,metrics:{coverage:_e,complexity:_e,maintainability:_e,testability:_e},recommendations:[...Nr(n),"No source files found for quality assessment"],warning:"No source files found",evidenceStatus:Ve,unmeasured:n,unmeasuredReasons:Object.fromEntries(n.map(b=>[b,"no source files found to analyse"])),measuredFailures:[],gateEvaluated:!1,confidence:0,note:$o});let u=await i.analyzeQuality({sourceFiles:a,includeMetrics:n,explicitFiles:c});if(!u.success)return u;let d=u.value,m={};for(let b of d.metrics)m[b.name]=b.value;let p=oa(n,m),f=ca(p.measured,m,{coverage:r}),g=p.evidenceStatus!=="measured",h=!g&&f.length===0&&d.score.overall>=s,y=d.recommendations.map(b=>`[${b.type}] ${b.title}: ${b.description}`),v=d.subsetScore??d.score.overall;return F({qualityScore:g?_e:d.score.overall,...g?{qualityScoreReason:`not computed: ${p.unmeasured.join(", ")} unmeasured`,...v>=0?{subsetScore:v}:{}}:{},passed:h,threshold:s,metrics:{coverage:kt(m.coverage),complexity:kt(m.complexity),maintainability:kt(m.maintainability),security:kt(m.security),...Object.fromEntries(n.map(b=>[b,kt(m[b])])),...m},unmeasuredReasons:fd(p.unmeasured,d.unmeasured),...g||(d.partial?.length??0)>0?{scoreBasis:d.metrics.map(b=>b.name)}:{},recommendations:[...f.map(la),...Nr(p.unmeasured),...vd(d.partial),...y],...d.partial&&d.partial.length>0?{partialMetrics:d.partial}:{},...d.excluded&&d.excluded.length>0?{excludedFiles:d.excluded.slice(0,hd),excludedCount:d.excluded.length}:{},scope:l,evidenceStatus:p.evidenceStatus,unmeasured:p.unmeasured,measuredFailures:f,gateEvaluated:!1,confidence:p.confidence,note:$o,trends:d.trends.map(b=>({metric:b.metric,direction:b.direction,dataPoints:b.dataPoints.length})),filesAnalyzed:a.length})}catch(n){return q(B(n))}})}M();function hi(o){o.registerHandler("validate-requirements",async e=>{let t=e.payload;try{let n=process.cwd();if(t.requirementsPath){let a=await X("validate-requirements","requirementsPath",t.requirementsPath,{allowDirectory:!0,allowMissing:!0});if(!a.success)return a;n=a.value}let r=await Pe(n,{includeTests:!1,languages:[]}),i=[".md",".feature",".gherkin",".txt",".rst"],s=[];for(let a of r)i.some(c=>a.endsWith(c))&&s.push(a);return F({requirementsAnalyzed:s.length,testable:0,ambiguous:0,untestable:0,coverage:0,bddScenarios:[],warning:s.length===0?"No requirement files (.md, .feature, .gherkin) found. Provide requirementsPath or add requirement docs.":"Requirements validation requires LLM analysis. File inventory returned \u2014 use task_orchestrate for deep analysis.",files:s.map(a=>a.startsWith(n)?a.slice(n.length+1):a).slice(0,20)})}catch(n){return q(B(n))}}),o.registerHandler("validate-contracts",async e=>{let t=e.payload;try{if(!t.contractPath)return F({contractPath:"",valid:!1,breakingChanges:[],warnings:[],coverage:0,error:"contractPath is required. Provide a path to an OpenAPI spec, JSON Schema, or Protocol Buffer file."});let n=await X("validate-contracts","contractPath",t.contractPath,{allowMissing:!0,maxBytes:ne});if(!n.success)return n;try{let r=await de(n.value,{maxBytes:ne}),i=t.contractPath.endsWith(".json"),s=t.contractPath.endsWith(".yaml")||t.contractPath.endsWith(".yml");return i&&JSON.parse(r),F({contractPath:t.contractPath,valid:!0,format:i?"json":s?"yaml":"unknown",breakingChanges:[],warnings:[],linesAnalyzed:r.split(`
423
+ `).length,note:"Structural validation passed. For semantic contract testing, use consumer-driven contract tests."})}catch(r){return F({contractPath:t.contractPath,valid:!1,breakingChanges:[],warnings:[],error:`Could not read or parse contract file: ${w(r)}`})}}catch(n){return q(B(n))}})}import{randomUUID as Td}from"node:crypto";import*as et from"path";M();Zt();var Un=ve("CodeIntelligenceHandlers");async function Ed(o,e,t){if(!o.getCodeIntelligenceCoordinator)return;let n=pa(t,{target:et.resolve(e)});if(!n){Un.debug("Skipping project metrics: no project root resolved (filesystem root or no paths)");return}try{let r=await o.getCodeIntelligenceCoordinator();if(!r)return;let i=await r.collectProjectMetrics(n);if(!i.success){Un.debug(`Project metrics unavailable: ${i.error.message}`);return}return{root:n,loc:i.value.loc.total,locByLanguage:i.value.loc.byLanguage,tests:i.value.tests.total,toolsUsed:i.value.toolsUsed}}catch(r){Un.debug(`Project metrics unavailable: ${B(r).message}`);return}}async function zo(o,e){return!e||e==="."?F(void 0):typeof e=="string"&&e.length>Fr?q(new re(`Invalid ${o} payload: 'target' is ${e.length} characters; the limit is ${Fr}`)):X(o,"target",e,{allowDirectory:!0,allowMissing:!0})}async function wd(o,e){let t="Search index not updated: the code-intelligence domain is unavailable, so a code search will not find these files.";if(!o.getCodeIntelligenceCoordinator)return[t];try{let n=await o.getCodeIntelligenceCoordinator();return n?(await n.indexForSearch(e)).warnings:[t]}catch(n){return[`Search index not updated: ${B(n).message}`]}}function yi(o){o.registerHandler("index-code",async e=>{let t=e.payload;try{let n=await zo("index-code",t.target);if(!n.success)return n;let r=o.getKnowledgeGraph(),i=n.value??(t.target||process.cwd()),s=Date.now(),a=await Pe(i,{includeTests:t.includeTests!==!1,languages:t.languages});if(a.length===0)return F({filesIndexed:0,nodesCreated:0,edgesCreated:0,target:i,incremental:t.incremental||!1,languages:t.languages||[],duration:Date.now()-s,warning:`No source files found in ${i}. Searched for: TypeScript, JavaScript, Python, Go, Rust, Java, Ruby, C/C++, and more.`});let c=await r.index({paths:a,incremental:t.incremental||!1,includeTests:t.includeTests!==!1,languages:t.languages});if(!c.success)return c;let l=c.value;if(l.filesIndexed===0)return q(ga(a.length,l.skipped??[],l.errors));let u=new Set([...(l.skipped??[]).map(h=>h.path),...l.errors.map(h=>h.file)]),d=a.filter(h=>!u.has(h)),m=await Ed(o,i,d),p=await wd(o,d),f=new Set,g={ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",py:"python",pyw:"python",go:"go",rs:"rust",java:"java",kt:"kotlin",kts:"kotlin",rb:"ruby",cs:"csharp",php:"php",swift:"swift",c:"c",h:"c",cpp:"cpp",hpp:"cpp",cc:"cpp",scala:"scala"};for(let h of d){let y=et.extname(h).slice(1),v=g[y];v&&f.add(v)}return F({filesIndexed:l.filesIndexed,nodesCreated:l.nodesCreated,edgesCreated:l.edgesCreated,symbolsExtracted:l.nodesCreated,relationsFound:l.edgesCreated,target:i,incremental:t.incremental||!1,languages:Array.from(f),duration:l.duration,errors:l.errors,warnings:[...l.warnings??[],...p],skipped:l.skipped??[],...m?{projectMetrics:m}:{}})}catch(n){return q(B(n))}}),o.registerHandler("predict-defects",async e=>{let t=e.payload;try{let n=await zo("predict-defects",t.target);if(!n.success)return n;let r=n.value??et.resolve(t.target||process.cwd()),i=t.minConfidence||.5,s=await Pe(r,{includeTests:!1});if(s.length===0)return F({predictedDefects:[],riskScore:0,recommendations:[`No source files found in ${r}. Ensure the path contains source code files.`],warning:`No source files found in ${r}`,filesAnalyzed:0});let a=[],c=[],l=0;for(let g of s)try{let h=await de(g,{outsideRoot:"allow"}),y=h.split(`
424
+ `),v=y.length,b=0,C=[];v>500?(b+=.25,C.push(`Large file (${v} lines)`)):v>300&&(b+=.15,C.push(`Medium-large file (${v} lines)`));let E=h.match(/\b(if|else|switch|case|for|while|catch|&&|\|\|)\b/g)||[],T=E.length/Math.max(v,1);T>.15?(b+=.25,C.push(`High branch density (${E.length} branches in ${v} lines)`)):T>.08&&(b+=.1,C.push("Moderate branch complexity")),Math.max(...y.map(N=>{let V=N.match(/^(\s*)/);return V?V[1].length:0}))>20&&(b+=.15,C.push("Deep nesting detected"));let x=(h.match(/\b(TODO|FIXME|HACK|XXX|WORKAROUND)\b/gi)||[]).length;x>3&&(b+=.15,C.push(`${x} technical debt markers`));let k=(h.match(/\b(function|def|func|async)\b/g)||[]).length;k>0&&v/k>80&&(b+=.1,C.push("Potentially long functions")),b=Math.min(b,.95);let _=Math.round(b*100)/100;if(c.push({file:et.resolve(g),probability:_,riskLevel:b>=.8?"critical":b>=.6?"high":b>=.4?"medium":b>=.2?"low":"info",factors:[{name:"staticCodeIndicators",contribution:_}],recommendations:C}),b>=i){let N=g.startsWith(r)?g.slice(r.length).replace(/^\//,""):g;a.push({file:N,probability:Math.round(b*100)/100,reason:C.join("; ")})}}catch{l++}if(c.length===0)return q(new Error(`Defect prediction could not read any of ${s.length} source files`));let u=Td();await o.memory.set(`defect-intelligence:predictor:prediction:${u}`,{id:u,target:r,timestamp:new Date().toISOString(),predictions:c,predictionMethod:"static-code-indicators",estimated:!0,filesSkipped:l,scanStatus:l>0?"partial":"complete"},{namespace:"defect-intelligence",ttl:86400*7});let d;try{await ua(o.memory)}catch(g){d=w(g),Un.warn("Defect prediction stored, but pruning older runs failed",{error:d})}a.sort((g,h)=>h.probability-g.probability);let m=a.length>0?a.reduce((g,h)=>g+h.probability,0)/a.length:0,p=Math.round(m*100),f=[];if(a.length>0){f.push(`${a.length} files flagged for potential defects out of ${c.length} analyzed`);let g=a[0];f.push(`Highest risk: ${g.file} (${Math.round(g.probability*100)}%) \u2014 ${g.reason}`)}return a.some(g=>g.reason.includes("Large file"))&&f.push("Consider splitting large files to reduce complexity"),a.some(g=>g.reason.includes("technical debt"))&&f.push("Address TODO/FIXME comments to reduce technical debt"),a.length===0&&f.push(l>0?`No analyzed files exceeded the threshold; ${l} unreadable source files remain unassessed`:"No files exceeded the defect probability threshold \u2014 code looks healthy"),F({predictedDefects:a.slice(0,20),riskScore:p,recommendations:f,filesAnalyzed:c.length,filesSkipped:l,scanStatus:l>0?"partial":"complete",predictionMethod:"static-code-indicators",estimated:!0,...d?{retention:"failed",retentionError:d}:{}})}catch(n){return q(B(n))}})}function vi(o){o.registerHandler("test-accessibility",async e=>{let t=e.payload;return F({url:t.url||"",standard:t.standard||"wcag21-aa",passed:!1,violations:[],warnings:[],score:-1,measured:!1,note:"Accessibility NOT MEASURED: this is not a failing result. Accessibility testing requires a browser environment (Puppeteer/Playwright). Use tools like axe-core, pa11y, or Lighthouse CLI for WCAG compliance testing. Example: npx pa11y "+(t.url||"<url>")})}),o.registerHandler("run-chaos",async e=>{let t=e.payload;return F({faultType:t.faultType||"unknown",target:t.target||"unknown",dryRun:t.dryRun??!0,duration:t.duration||0,systemBehavior:"not-executed",resilience:null,note:"Chaos engineering requires infrastructure-level fault injection. Use tools like Chaos Monkey, Litmus, or toxiproxy for real resilience testing. For Node.js apps, consider: nock (HTTP faults), testcontainers (dependency failures)."})}),o.registerHandler("optimize-learning",async e=>{try{let t=await import("./unified-memory-hnsw-NJP2F2RY.js");return F({patternsLearned:0,modelsUpdated:0,memoryConsolidated:!1,note:'Learning optimization runs during the dream cycle (SessionEnd hook). Use "npx agentic-qe hooks session-end --save-state" to trigger pattern consolidation.'})}catch{return F({patternsLearned:0,modelsUpdated:0,memoryConsolidated:!1,note:'Learning system not initialized. Run "aqe init --auto" first.'})}})}var ue=ve("TaskExecutor");function kd(o){return We.resolve(Qe.CoverageAnalyzerService)(o)}function Md(o){return We.resolve(Qe.SecurityScannerService)(o)}function Ko(o,e){return We.resolve(Qe.createTestGeneratorService)(o,e)}function Id(o){return We.resolve(Qe.KnowledgeGraphService)(o)}function Dd(o){return We.resolve(Qe.QualityAnalyzerService)(o)}function Xo(o){return o instanceof Ks?{...o.toDetails()}:$e(o)?{callerError:!0}:void 0}function Yo(o){return o===0?"agent-booster":Es(o)}function _d(o){if(["generate-tests","analyze-coverage","scan-security","execute-tests","assess-quality","validate-contracts","test-accessibility","chaos-test","predict-defects","validate-requirements","index-code"].includes(o.type))return null;let t=o.payload?.codeContext||"",n=o.payload?.sourceCode||"",r=t||n;return r?r.includes("var ")&&!r.includes("const ")&&!r.includes("let ")?"var-to-const":r.includes("console.log")||r.includes("console.warn")||r.includes("console.error")?"remove-console":r.includes(".then(")&&r.includes(".catch(")?"promise-to-async":r.includes("require(")&&!r.includes("import ")?"cjs-to-esm":r.includes("function ")&&!r.includes("=>")?"func-to-arrow":null:null}var Ci=class{constructor(e,t,n){this.kernel=e;this.eventBus=t;this._config={timeout:n?.timeout??3e5,maxRetries:n?.maxRetries??3,enableCaching:n?.enableCaching??!0,saveResults:n?.saveResults??!0,resultsDir:n?.resultsDir??en(),defaultLanguage:n?.defaultLanguage??"typescript",defaultFramework:n?.defaultFramework??"vitest"},this.resultSaver=ho(this._config.resultsDir),this.registerHandlers()}kernel;eventBus;_config;resultSaver;coverageAnalyzer=null;securityScanner=null;testGenerator=null;deterministicTestGenerator=null;knowledgeGraph=null;qualityAnalyzer=null;agentBooster=null;taskRouter=null;qualityFeedbackLoop=null;coherenceActionGate=null;taskHandlers=new Map;get memory(){return this.kernel.memory}get config(){return this._config}registerHandler(e,t){this.taskHandlers.set(e,t)}setQualityFeedbackLoop(e){this.qualityFeedbackLoop=e}getCoverageAnalyzer(){return this.coverageAnalyzer||(this.coverageAnalyzer=kd(this.kernel.memory)),this.coverageAnalyzer}getSecurityScanner(){return this.securityScanner||(this.securityScanner=Md(this.kernel.memory)),this.securityScanner}async getTestGenerator(e=!0){return e?(this.testGenerator||(this.testGenerator=Ko(this.kernel.memory,await this.resolveLLMRouter())),this.testGenerator):(this.deterministicTestGenerator||(this.deterministicTestGenerator=Ko(this.kernel.memory)),this.deterministicTestGenerator)}async resolveLLMRouter(){if(this.kernel.llmRouter)return this.kernel.llmRouter;try{let{getSharedLLMRouter:e}=await import("./base-J2FXOE77.js");return await e()??void 0}catch(e){ue.debug("LLM router unavailable; using deterministic generation",{error:w(e)});return}}getKnowledgeGraph(){return this.knowledgeGraph||(this.knowledgeGraph=Id(this.kernel.memory)),this.knowledgeGraph}async getCodeIntelligenceCoordinator(){try{let e=this.kernel.getDomainAPIAsync?await this.kernel.getDomainAPIAsync("code-intelligence"):this.kernel.getDomainAPI("code-intelligence");return typeof e?.getCoordinator=="function"?e.getCoordinator():void 0}catch(e){ue.debug("code-intelligence coordinator unavailable for project metrics",{error:e instanceof Error?e.message:String(e)});return}}getQualityAnalyzer(){return this.qualityAnalyzer||(this.qualityAnalyzer=Dd(this.kernel.memory)),this.qualityAnalyzer}async getTestExecutionAPI(){return this.kernel.getDomainAPIAsync?this.kernel.getDomainAPIAsync("test-execution"):this.kernel.getDomainAPI("test-execution")}registerHandlers(){ii(this),ui(this),pi(this),fi(this),hi(this),yi(this),vi(this)}async getAgentBooster(){return this.agentBooster||(this.agentBooster=await mn({enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7})),this.agentBooster}async getTaskRouterInstance(){if(!this.taskRouter)try{this.taskRouter=await On()}catch{return null}return this.taskRouter}async executeWithAgentBooster(e,t,n){let r=_d(e);if(!r)return console.debug(`[TaskExecutor] No applicable Agent Booster transform for task ${e.id}`),null;try{let i=await this.getAgentBooster(),s=e.payload?.codeContext||e.payload?.sourceCode||"",a=await i.transform(s,r);return a.success&&a.confidence>=.7?(console.debug(`[TaskExecutor] Agent Booster transform succeeded: ${r}, confidence=${a.confidence}`),{taskId:e.id,success:!0,data:{transformed:!0,transformType:r,originalCode:a.originalCode,transformedCode:a.transformedCode,confidence:a.confidence,implementationUsed:a.implementationUsed,durationMs:a.durationMs,changeCount:a.changeCount,tier:0,model:"agent-booster"},duration:Date.now()-t,domain:n}):(console.debug(`[TaskExecutor] Agent Booster low confidence (${a.confidence}), falling back to Tier 1`),null)}catch(i){return console.warn(`[TaskExecutor] Agent Booster error, falling back: ${i}`),null}}async recordOutcome(e,t,n,r){try{if(!await this.getTaskRouterInstance())return;if(console.debug(`[TaskExecutor] Outcome recorded: task=${e.id}, tier=${t}, model=${Yo(t)}, success=${n}, duration=${r}ms`),this.qualityFeedbackLoop){let s=e.targetDomains||[],a=n?1:0,c=r<100?1:r<500?.8:r<2e3?.6:r<5e3?.4:r<1e4?.2:.1,l=.25*a+.325+.1*c;await this.qualityFeedbackLoop.recordRoutingOutcome({taskId:e.id,taskDescription:e.type,recommendedAgent:String(t),usedAgent:String(t),followedRecommendation:!0,success:n,qualityScore:l,durationMs:r,timestamp:new Date,error:n?void 0:"Task execution failed"})}}catch(i){console.warn("[TaskExecutor] Failed to record outcome:",i)}}async execute(e){let t=Date.now(),n=this.getTaskDomain(e.type),r=e.payload,i=r?.routingTier??2,s=r?.useAgentBooster??!1,a=r?.compiledContext??void 0,c=Yo(i);a&&e.payload&&(e.payload.__compiledContext=a),console.debug(`[TaskExecutor] Executing task ${e.id}: type=${e.type}, tier=${i}, model=${c}, useAgentBooster=${s}${a?", hasContext=true":""}`);let l=this.evaluateCoherenceGate(e,n);l&&console.debug(`[TaskExecutor] Coherence gate: task=${e.id}, decision=${l.decision}, combined=${l.combinedScore.toFixed(3)}, advisory=${l.advisory}`),this.validateWithReasoningQEC(e,n);try{if(i===0||s){let p=await this.executeWithAgentBooster(e,t,n);if(p)return this.recordOutcome(e,0,!0,Date.now()-t).catch(f=>{ue.warn("recordOutcome failed",{error:f instanceof Error?f.message:String(f),taskId:e.id})}),await this.publishTaskCompleted(e.id,p.data,n),p;console.debug(`[TaskExecutor] Agent Booster fallback to Tier 1 for task ${e.id}`)}let u=this.taskHandlers.get(e.type);if(!u){let p={taskId:e.id,success:!1,error:`No handler registered for task type: ${e.type}`,duration:Date.now()-t,domain:n};return this.recordOutcome(e,i,!1,Date.now()-t).catch(f=>{ue.warn("recordOutcome failed",{error:f instanceof Error?f.message:String(f),taskId:e.id})}),p}let d=await Promise.race([u(e),this.timeout(e.timeout||this._config.timeout)]);if(!d.success){let p="error"in d?d.error.message:"Unknown error";await this.publishTaskFailed(e.id,p,n,"error"in d&&$e(d.error)),this.recordOutcome(e,i,!1,Date.now()-t).catch(g=>{ue.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})});let f="error"in d?Xo(d.error):void 0;return{taskId:e.id,success:!1,error:p,duration:Date.now()-t,domain:n,...f?{errorDetails:f}:{}}}await this.publishTaskCompleted(e.id,d.value,n),Ke(n,d.value)&&this.recordOutcome(e,i,!0,Date.now()-t).catch(p=>{ue.warn("recordOutcome failed",{error:p instanceof Error?p.message:String(p),taskId:e.id})});let m;if(this._config.saveResults&&r?.saveResults!==!1)try{let p={language:r?.language||this._config.defaultLanguage,framework:r?.framework||this._config.defaultFramework,includeSecondary:!0};m=(await this.resultSaver.save(e.id,e.type,d.value,p)).files.map(g=>g.path)}catch(p){console.error(`[TaskExecutor] Failed to save results: ${p}`)}return{taskId:e.id,success:!0,data:{...d.value,_routing:{tier:i,model:c,usedAgentBooster:!1}},duration:Date.now()-t,domain:n,savedFiles:m}}catch(u){let d=w(u);await this.publishTaskFailed(e.id,d,n,$e(u)),this.recordOutcome(e,i,!1,Date.now()-t).catch(p=>{ue.warn("recordOutcome failed",{error:p instanceof Error?p.message:String(p),taskId:e.id})});let m=Xo(u);return{taskId:e.id,success:!1,error:d,duration:Date.now()-t,domain:n,...m?{errorDetails:m}:{}}}}async resetServiceCaches(){if(this.coverageAnalyzer=null,this.securityScanner=null,this.testGenerator=null,this.knowledgeGraph=null,this.qualityAnalyzer=null,this.coherenceActionGate=null,this.agentBooster){try{await this.agentBooster.dispose()}catch(e){console.debug("[TaskExecutor] Agent Booster disposal error:",e instanceof Error?e.message:e)}this.agentBooster=null}this.taskRouter=null}resetServiceCachesSync(){this.coverageAnalyzer=null,this.securityScanner=null,this.testGenerator=null,this.knowledgeGraph=null,this.qualityAnalyzer=null,this.agentBooster=null,this.taskRouter=null,this.coherenceActionGate=null}evaluateCoherenceGate(e,t){try{this.coherenceActionGate||(this.coherenceActionGate=To({advisory:!0}));let n=e.payload,r=typeof n?.confidence=="number"?n.confidence:.7,i=n?.riskLevel??"medium";return Eo(e.type,t,r,i,n??{},this.coherenceActionGate)}catch(n){return ue.warn("Coherence gate evaluation error (continuing)",{error:n instanceof Error?n.message:String(n),taskId:e.id}),null}}_reasoningQEC=null;_reasoningQECLoaded=!1;validateWithReasoningQEC(e,t){try{if(!this._reasoningQECLoaded){this._reasoningQECLoaded=!0;try{let{isReasoningQECEnabled:s}=(Yt(),gs(bl));if(s()){let{createReasoningQEC:a}=(Wo(),gs(Qo));this._reasoningQEC=a()}}catch(s){ue.debug("ReasoningQEC module unavailable",{error:s instanceof Error?s.message:String(s)})}}if(!this._reasoningQEC)return;let n=e.payload,r=n?.reasoningSteps;if(!r||r.length<2)return;let i=this._reasoningQEC.validate({type:t,context:n,steps:r});i.valid||ue.warn("ReasoningQEC validation found issues (advisory)",{taskId:e.id,domain:t,confidence:i.confidence,issues:i.issues.length})}catch(n){ue.debug("ReasoningQEC evaluation error",{error:n instanceof Error?n.message:String(n),taskId:e.id})}}getTaskDomain(e){return{"generate-tests":"test-generation","execute-tests":"test-execution","analyze-coverage":"coverage-analysis","assess-quality":"quality-assessment","predict-defects":"defect-intelligence","validate-requirements":"requirements-validation","index-code":"code-intelligence","scan-security":"security-compliance","validate-contracts":"contract-testing","test-accessibility":"visual-accessibility","run-chaos":"chaos-resilience","optimize-learning":"learning-optimization","cross-domain-workflow":"learning-optimization","protocol-execution":"learning-optimization","ideation-assessment":"requirements-validation"}[e]||"learning-optimization"}async timeout(e){return new Promise((t,n)=>{setTimeout(()=>n(new Error(`Task execution timed out after ${e}ms`)),e)})}async publishTaskCompleted(e,t,n){await this.eventBus.publish({id:U(),type:"TaskCompleted",timestamp:new Date,source:n,payload:{taskId:e,result:t}})}async publishTaskFailed(e,t,n,r=!1){await this.eventBus.publish({id:U(),type:"TaskFailed",timestamp:new Date,source:n,payload:{taskId:e,error:t,...r?{callerError:!0}:{}}})}};function Jo(o,e){return new Ci(o,o.eventBus,e)}async function Zo(){}import{randomUUID as tt}from"crypto";M();var Si=".agentic-qe/results/";function ec(o){if(o===null||typeof o!="object")return!0;let e=o.saveResults;if(e==null)return!0;if(typeof e!="boolean")throw new Error(`saveResults must be a boolean (true or false), got ${typeof e}.`);return e}function Hn(o,e){if(!o)return{resultsSaved:!1,savedFiles:[],resultsNote:`saveResults was false: no files were written under ${Si}.`};let t=e??[];return t.length===0?{resultsSaved:!1,savedFiles:[],resultsNote:`No result files were written under ${Si} (saving is disabled or failed).`}:{resultsSaved:!0,savedFiles:t,resultsNote:`Saved ${t.length} result file(s) under ${Si}; see savedFiles. Pass saveResults: false to skip.`}}var Ti={effectiveness:.25,coverage:.2,mutationKill:.15,stability:.15,maintainability:.15,performance:.1},Ei={"short-term":{minSuccessCount:0,minSuccessRate:0,minQualityScore:0,minAgeDays:0},working:{minSuccessCount:3,minSuccessRate:.6,minQualityScore:.5,minAgeDays:1},"long-term":{minSuccessCount:10,minSuccessRate:.75,minQualityScore:.7,minAgeDays:7},permanent:{minSuccessCount:50,minSuccessRate:.9,minQualityScore:.85,minAgeDays:30}},xe={qualityWeights:Ti,promotionCriteria:Ei,autoPromote:!0,autoDemote:!0,minCoverageImprovementToLearn:5,maxOutcomesInMemory:1e4,persistOutcomes:!0,batchSize:100};ge();M();te();var wi=class{outcomes=[];maxOutcomes;constructor(e){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getAll(){return[...this.outcomes]}getByPattern(e){return this.outcomes.filter(t=>t.patternId===e)}getByAgent(e){return this.outcomes.filter(t=>t.generatedBy===e)}getByDomain(e){return this.outcomes.filter(t=>t.domain===e)}getRecent(e){return this.outcomes.slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},Ri=class o{store;reasoningBank=null;config;db=null;persistCount=0;static RETENTION_CLEANUP_INTERVAL=100;patternMetrics=new Map;constructor(e={}){this.config={...xe,...e},this.store=new wi(this.config.maxOutcomesInMemory)}connectReasoningBank(e){this.reasoningBank=e}async initialize(){try{this.db=Y(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb()}catch(e){console.warn("[TestOutcomeTracker] DB initialization failed, using memory-only:",w(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
434
425
  SELECT * FROM test_outcomes ORDER BY created_at DESC LIMIT ?
435
426
  `).all(this.config.maxOutcomesInMemory);for(let n of t.reverse()){let r={id:n.id,testId:n.test_id,testName:n.test_name,generatedBy:n.generated_by,patternId:n.pattern_id||void 0,framework:n.framework,language:n.language,domain:n.domain,passed:!!n.passed,errorMessage:n.error_message||void 0,coverage:{lines:n.coverage_lines,branches:n.coverage_branches,functions:n.coverage_functions},mutationScore:n.mutation_score??void 0,executionTimeMs:n.execution_time_ms,flaky:!!n.flaky,flakinessScore:n.flakiness_score??void 0,maintainabilityScore:n.maintainability_score,complexity:n.complexity??void 0,linesOfCode:n.lines_of_code??void 0,assertionCount:n.assertion_count??void 0,filePath:n.file_path||void 0,sourceFilePath:n.source_file_path||void 0,timestamp:new Date(n.created_at),metadata:n.metadata_json?I(n.metadata_json):void 0};this.store.add(r),r.patternId&&this.updatePatternMetrics(r)}t.length>0&&console.log(`[TestOutcomeTracker] Loaded ${t.length} outcomes from DB`)}async persistOutcome(e){if(this.db)try{let t=this.db,n=t.getDatabase();await t.writeWhenUnlocked(()=>n.prepare(`
436
427
  INSERT OR REPLACE INTO test_outcomes (
@@ -445,8 +436,8 @@ ${i.trim()}`}function ai(o){return typeof o.numFailedTests=="number"||typeof o.n
445
436
  DELETE FROM test_outcomes WHERE id NOT IN (
446
437
  SELECT id FROM test_outcomes ORDER BY created_at DESC LIMIT ?
447
438
  )
448
- `).run(n))}catch(t){console.warn("[TestOutcomeTracker] Retention cleanup failed:",w(t))}}async track(e){this.store.add(e),await this.persistOutcome(e),e.patternId&&(this.updatePatternMetrics(e),this.reasoningBank&&await this.updateReasoningBankPattern(e),(this.config.autoPromote||this.config.autoDemote)&&await this.checkPatternTierChange(e.patternId))}async trackBatch(e){for(let t of e)await this.track(t)}updatePatternMetrics(e){let t=e.patternId,n=this.patternMetrics.get(t)||{successCount:0,failureCount:0,totalQuality:0,outcomes:0};e.passed&&!e.flaky?n.successCount++:n.failureCount++,n.totalQuality+=e.maintainabilityScore,n.outcomes++,this.patternMetrics.set(t,n)}async updateReasoningBankPattern(e){if(!this.reasoningBank||!e.patternId)return;let t=this.calculateOutcomeQuality(e),n=e.passed&&!e.flaky;await this.reasoningBank.recordPatternOutcome(e.patternId,n,t)}calculateOutcomeQuality(e){let t=this.config.qualityWeights,n=e.passed&&!e.flaky?1:0,r=(e.coverage.lines+e.coverage.branches+e.coverage.functions)/3/100,i=e.mutationScore??.5,s=e.flaky?.2:1-(e.flakinessScore??0),a=e.maintainabilityScore,l=Math.max(0,1-e.executionTimeMs/1e4);return t.effectiveness*n+t.coverage*r+t.mutationKill*i+t.stability*s+t.maintainability*a+t.performance*l}async checkPatternTierChange(e){if(!this.reasoningBank)return;let t=this.patternMetrics.get(e);if(!t)return;let n=t.successCount/(t.successCount+t.failureCount),r=t.totalQuality/t.outcomes;if(this.config.autoPromote&&await this.reasoningBank.checkPatternPromotion(e,t.successCount,n,r)&&await this.reasoningBank.promotePattern(e),this.config.autoDemote){let i=this.store.getByPattern(e).slice(-10);i.length>=5&&i.filter(a=>a.passed&&!a.flaky).length/i.length<.3&&await this.reasoningBank.demotePattern(e)}}getStats(){let e=this.store.getAll();if(e.length===0)return this.emptyStats();let t=e.filter(p=>p.passed).length,n={lines:e.reduce((p,g)=>p+g.coverage.lines,0)/e.length,branches:e.reduce((p,g)=>p+g.coverage.branches,0)/e.length,functions:e.reduce((p,g)=>p+g.coverage.functions,0)/e.length},r=e.filter(p=>p.mutationScore!==void 0),i=r.length>0?r.reduce((p,g)=>p+g.mutationScore,0)/r.length:0,s=e.reduce((p,g)=>p+g.executionTimeMs,0)/e.length,a=e.filter(p=>p.flaky).length,c=e.reduce((p,g)=>p+g.maintainabilityScore,0)/e.length,l=new Map,d=this.groupBy(e,p=>p.generatedBy);for(let[p,g]of d)l.set(p,{total:g.length,passed:g.filter(f=>f.passed).length,avgCoverage:g.reduce((f,h)=>f+h.coverage.lines,0)/g.length,avgMaintainability:g.reduce((f,h)=>f+h.maintainabilityScore,0)/g.length});let u=new Map,m=this.groupBy(e,p=>p.domain);for(let[p,g]of m)u.set(p,{total:g.length,passed:g.filter(f=>f.passed).length,avgCoverage:g.reduce((f,h)=>f+h.coverage.lines,0)/g.length});return{totalTests:e.length,passedTests:t,passRate:t/e.length,avgCoverage:n,avgMutationScore:i,avgExecutionTimeMs:s,flakyTests:a,avgMaintainability:c,byAgent:l,byDomain:u}}getPatternMetrics(e){let t=this.patternMetrics.get(e);if(!t)return null;let n=t.successCount+t.failureCount;return{successCount:t.successCount,failureCount:t.failureCount,successRate:n>0?t.successCount/n:0,avgQuality:t.outcomes>0?t.totalQuality/t.outcomes:0}}getAllPatternMetrics(){let e=new Map;for(let[t,n]of this.patternMetrics)e.set(t,this.getPatternMetrics(t));return e}getAgentOutcomes(e){return this.store.getByAgent(e)}getRecentOutcomes(e){return this.store.getRecent(e)}exportOutcomes(){return this.store.getAll()}importOutcomes(e){for(let t of e)this.store.add(t),t.patternId&&this.updatePatternMetrics(t)}clear(){this.store.clear(),this.patternMetrics.clear()}getTrackerStats(){return{totalOutcomes:this.store.size,patternsTracked:this.patternMetrics.size,hasReasoningBank:this.reasoningBank!==null}}emptyStats(){return{totalTests:0,passedTests:0,passRate:0,avgCoverage:{lines:0,branches:0,functions:0},avgMutationScore:0,avgExecutionTimeMs:0,flakyTests:0,avgMaintainability:0,byAgent:new Map,byDomain:new Map}}groupBy(e,t){let n=new Map;for(let r of e){let i=t(r),s=n.get(i)||[];s.push(r),n.set(i,s)}return n}};function rc(o){return new Ri(o)}import{randomUUID as Gd}from"crypto";pe();D();ee();var Pi=class{sessions=[];maxSessions;constructor(e){this.maxSessions=e}add(e){this.sessions.push(e),this.sessions.length>this.maxSessions&&(this.sessions=this.sessions.slice(-this.maxSessions))}getAll(){return[...this.sessions]}getByTechnique(e){return this.sessions.filter(t=>t.technique===e)}getByAgent(e){return this.sessions.filter(t=>t.agentId===e)}getSuccessful(e){return this.sessions.filter(t=>this.calculateImprovement(t)>=e)}calculateImprovement(e){return(e.afterCoverage.lines-e.beforeCoverage.lines+(e.afterCoverage.branches-e.beforeCoverage.branches)+(e.afterCoverage.functions-e.beforeCoverage.functions))/3}clear(){this.sessions=[]}get size(){return this.sessions.length}},xi=class o{sessionStore;strategies=new Map;reasoningBank=null;config;db=null;persistCount=0;static RETENTION_CLEANUP_INTERVAL=50;constructor(e={}){this.config={...xe,...e},this.sessionStore=new Pi(this.config.maxOutcomesInMemory)}connectReasoningBank(e){this.reasoningBank=e}async initialize(){try{this.db=X(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb()}catch(e){console.warn("[CoverageLearner] DB init failed, using memory-only:",w(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
449
- SELECT * FROM coverage_sessions WHERE ${Da} ORDER BY created_at DESC LIMIT ?
439
+ `).run(n))}catch(t){console.warn("[TestOutcomeTracker] Retention cleanup failed:",w(t))}}async track(e){this.store.add(e),await this.persistOutcome(e),e.patternId&&(this.updatePatternMetrics(e),this.reasoningBank&&await this.updateReasoningBankPattern(e),(this.config.autoPromote||this.config.autoDemote)&&await this.checkPatternTierChange(e.patternId))}async trackBatch(e){for(let t of e)await this.track(t)}updatePatternMetrics(e){let t=e.patternId,n=this.patternMetrics.get(t)||{successCount:0,failureCount:0,totalQuality:0,outcomes:0};e.passed&&!e.flaky?n.successCount++:n.failureCount++,n.totalQuality+=e.maintainabilityScore,n.outcomes++,this.patternMetrics.set(t,n)}async updateReasoningBankPattern(e){if(!this.reasoningBank||!e.patternId)return;let t=this.calculateOutcomeQuality(e),n=e.passed&&!e.flaky;await this.reasoningBank.recordPatternOutcome(e.patternId,n,t)}calculateOutcomeQuality(e){let t=this.config.qualityWeights,n=e.passed&&!e.flaky?1:0,r=(e.coverage.lines+e.coverage.branches+e.coverage.functions)/3/100,i=e.mutationScore??.5,s=e.flaky?.2:1-(e.flakinessScore??0),a=e.maintainabilityScore,l=Math.max(0,1-e.executionTimeMs/1e4);return t.effectiveness*n+t.coverage*r+t.mutationKill*i+t.stability*s+t.maintainability*a+t.performance*l}async checkPatternTierChange(e){if(!this.reasoningBank)return;let t=this.patternMetrics.get(e);if(!t)return;let n=t.successCount/(t.successCount+t.failureCount),r=t.totalQuality/t.outcomes;if(this.config.autoPromote&&await this.reasoningBank.checkPatternPromotion(e,t.successCount,n,r)&&await this.reasoningBank.promotePattern(e),this.config.autoDemote){let i=this.store.getByPattern(e).slice(-10);i.length>=5&&i.filter(a=>a.passed&&!a.flaky).length/i.length<.3&&await this.reasoningBank.demotePattern(e)}}getStats(){let e=this.store.getAll();if(e.length===0)return this.emptyStats();let t=e.filter(p=>p.passed).length,n={lines:e.reduce((p,f)=>p+f.coverage.lines,0)/e.length,branches:e.reduce((p,f)=>p+f.coverage.branches,0)/e.length,functions:e.reduce((p,f)=>p+f.coverage.functions,0)/e.length},r=e.filter(p=>p.mutationScore!==void 0),i=r.length>0?r.reduce((p,f)=>p+f.mutationScore,0)/r.length:0,s=e.reduce((p,f)=>p+f.executionTimeMs,0)/e.length,a=e.filter(p=>p.flaky).length,c=e.reduce((p,f)=>p+f.maintainabilityScore,0)/e.length,l=new Map,u=this.groupBy(e,p=>p.generatedBy);for(let[p,f]of u)l.set(p,{total:f.length,passed:f.filter(g=>g.passed).length,avgCoverage:f.reduce((g,h)=>g+h.coverage.lines,0)/f.length,avgMaintainability:f.reduce((g,h)=>g+h.maintainabilityScore,0)/f.length});let d=new Map,m=this.groupBy(e,p=>p.domain);for(let[p,f]of m)d.set(p,{total:f.length,passed:f.filter(g=>g.passed).length,avgCoverage:f.reduce((g,h)=>g+h.coverage.lines,0)/f.length});return{totalTests:e.length,passedTests:t,passRate:t/e.length,avgCoverage:n,avgMutationScore:i,avgExecutionTimeMs:s,flakyTests:a,avgMaintainability:c,byAgent:l,byDomain:d}}getPatternMetrics(e){let t=this.patternMetrics.get(e);if(!t)return null;let n=t.successCount+t.failureCount;return{successCount:t.successCount,failureCount:t.failureCount,successRate:n>0?t.successCount/n:0,avgQuality:t.outcomes>0?t.totalQuality/t.outcomes:0}}getAllPatternMetrics(){let e=new Map;for(let[t,n]of this.patternMetrics)e.set(t,this.getPatternMetrics(t));return e}getAgentOutcomes(e){return this.store.getByAgent(e)}getRecentOutcomes(e){return this.store.getRecent(e)}exportOutcomes(){return this.store.getAll()}importOutcomes(e){for(let t of e)this.store.add(t),t.patternId&&this.updatePatternMetrics(t)}clear(){this.store.clear(),this.patternMetrics.clear()}getTrackerStats(){return{totalOutcomes:this.store.size,patternsTracked:this.patternMetrics.size,hasReasoningBank:this.reasoningBank!==null}}emptyStats(){return{totalTests:0,passedTests:0,passRate:0,avgCoverage:{lines:0,branches:0,functions:0},avgMutationScore:0,avgExecutionTimeMs:0,flakyTests:0,avgMaintainability:0,byAgent:new Map,byDomain:new Map}}groupBy(e,t){let n=new Map;for(let r of e){let i=t(r),s=n.get(i)||[];s.push(r),n.set(i,s)}return n}};function tc(o){return new Ri(o)}import{randomUUID as Od}from"crypto";ge();M();te();var Pi=class{sessions=[];maxSessions;constructor(e){this.maxSessions=e}add(e){this.sessions.push(e),this.sessions.length>this.maxSessions&&(this.sessions=this.sessions.slice(-this.maxSessions))}getAll(){return[...this.sessions]}getByTechnique(e){return this.sessions.filter(t=>t.technique===e)}getByAgent(e){return this.sessions.filter(t=>t.agentId===e)}getSuccessful(e){return this.sessions.filter(t=>this.calculateImprovement(t)>=e)}calculateImprovement(e){return(e.afterCoverage.lines-e.beforeCoverage.lines+(e.afterCoverage.branches-e.beforeCoverage.branches)+(e.afterCoverage.functions-e.beforeCoverage.functions))/3}clear(){this.sessions=[]}get size(){return this.sessions.length}},xi=class o{sessionStore;strategies=new Map;reasoningBank=null;config;db=null;persistCount=0;static RETENTION_CLEANUP_INTERVAL=50;constructor(e={}){this.config={...xe,...e},this.sessionStore=new Pi(this.config.maxOutcomesInMemory)}connectReasoningBank(e){this.reasoningBank=e}async initialize(){try{this.db=Y(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb()}catch(e){console.warn("[CoverageLearner] DB init failed, using memory-only:",w(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
440
+ SELECT * FROM coverage_sessions WHERE ${Oa} ORDER BY created_at DESC LIMIT ?
450
441
  `).all(this.config.maxOutcomesInMemory);for(let n of t.reverse()){let r={id:n.id,targetPath:n.target_path,agentId:n.agent_id,technique:n.technique,beforeCoverage:{lines:n.before_lines,branches:n.before_branches,functions:n.before_functions},afterCoverage:{lines:n.after_lines,branches:n.after_branches,functions:n.after_functions},testsGenerated:n.tests_generated,testsPassed:n.tests_passed,gapsTargeted:n.gaps_json?I(n.gaps_json):[],durationMs:n.duration_ms,startedAt:new Date(n.started_at),completedAt:new Date(n.completed_at),context:n.context_json?I(n.context_json):void 0};this.sessionStore.add(r);let i=(r.afterCoverage.lines-r.beforeCoverage.lines)*.4+(r.afterCoverage.branches-r.beforeCoverage.branches)*.35+(r.afterCoverage.functions-r.beforeCoverage.functions)*.25;if(i>=this.config.minCoverageImprovementToLearn){let s=this.extractFilePattern(r.targetPath),a=`${r.technique}:${s}`,c=this.strategies.get(a);c?this.strategies.set(a,{...c,avgImprovement:(c.avgImprovement*c.successCount+i)/(c.successCount+1),successCount:c.successCount+1,confidence:Math.min(1,c.confidence+.05),lastUsedAt:new Date(n.completed_at)}):this.strategies.set(a,{id:`strategy-${n.id}`,description:`Coverage strategy: ${r.technique} for ${s} files`,technique:r.technique,filePatterns:[s],avgImprovement:i,successCount:1,confidence:.5,createdAt:new Date(n.started_at),lastUsedAt:new Date(n.completed_at)})}}t.length>0&&console.log(`[CoverageLearner] Loaded ${t.length} sessions from DB`)}async persistSession(e){if(this.db)try{let t=this.db,n=t.getDatabase();await t.writeWhenUnlocked(()=>n.prepare(`
451
442
  INSERT OR REPLACE INTO coverage_sessions (
452
443
  id, target_path, agent_id, technique,
@@ -459,19 +450,19 @@ ${i.trim()}`}function ai(o){return typeof o.numFailedTests=="number"||typeof o.n
459
450
  DELETE FROM coverage_sessions WHERE id NOT IN (
460
451
  SELECT id FROM coverage_sessions ORDER BY created_at DESC LIMIT ?
461
452
  )
462
- `).run(n))}catch(t){console.warn("[CoverageLearner] Retention cleanup failed:",w(t))}}async learnFromSession(e){this.sessionStore.add(e),await this.persistSession(e);let t=this.calculateOverallImprovement(e);if(t<this.config.minCoverageImprovementToLearn)return null;let n=await this.extractStrategy(e,t);return this.reasoningBank&&n&&await this.storeStrategyAsPattern(n),n}calculateOverallImprovement(e){let t=e.beforeCoverage,n=e.afterCoverage,r=n.lines-t.lines,i=n.branches-t.branches,s=n.functions-t.functions;return r*.4+i*.35+s*.25}async extractStrategy(e,t){let n=this.extractFilePattern(e.targetPath),r=`${e.technique}:${n}`,i=this.strategies.get(r);return i?i={...i,avgImprovement:(i.avgImprovement*i.successCount+t)/(i.successCount+1),successCount:i.successCount+1,confidence:Math.min(1,i.confidence+.05),lastUsedAt:new Date}:i={id:`strategy-${Date.now()}-${Gd().slice(0,8)}`,description:this.generateStrategyDescription(e,t),technique:e.technique,filePatterns:[n],avgImprovement:t,successCount:1,confidence:.5,createdAt:new Date,lastUsedAt:new Date},this.strategies.set(r,i),i}extractFilePattern(e){let t=e.split("/"),r=t[t.length-1].split(".").pop()||"";return t.length>=2?`${t[t.length-2]}/*.${r}`:`*.${r}`}generateStrategyDescription(e,t){let r={"gap-analysis":"Identify and target uncovered code paths","branch-coverage":"Focus on branch conditions and decision points","edge-case-generation":"Generate tests for edge cases and boundary conditions","mutation-guided":"Use mutation testing to identify weak test areas","risk-based":"Prioritize high-risk code paths","semantic-analysis":"Use code semantics to generate meaningful tests","boundary-testing":"Test boundary conditions and limits","state-machine":"Model state transitions and test state changes","data-flow":"Follow data flow paths through the code"}[e.technique]||e.technique,i=e.gapsTargeted.filter(a=>a.addressed).length,s=e.gapsTargeted.length;return`${r} for ${this.extractFilePattern(e.targetPath)} files. Achieved ${t.toFixed(1)}% improvement. Addressed ${i}/${s} gaps with ${e.testsGenerated} tests.`}async storeStrategyAsPattern(e){this.reasoningBank&&await this.reasoningBank.storeQEPattern({patternType:"coverage-strategy",name:`Coverage Strategy: ${e.technique}`,description:e.description,template:{type:"workflow",content:JSON.stringify({technique:e.technique,filePatterns:e.filePatterns,avgImprovement:e.avgImprovement}),variables:[{name:"targetFile",type:"string",required:!0,description:"Target file to analyze"},{name:"currentCoverage",type:"number",required:!0,description:"Current coverage percentage"}]},context:{tags:["coverage",e.technique,...e.filePatterns]}})}getRecommendedStrategy(e){let t=this.extractFilePattern(e),n=null,r=0;for(let i of this.strategies.values())if(i.filePatterns.some(a=>t.includes(a.split("/").pop()||"")||a.includes(t.split("/").pop()||""))||i.filePatterns.length===0){let a=(Date.now()-i.lastUsedAt.getTime())/864e5,c=Math.max(.5,1-a/30),l=i.avgImprovement*i.confidence*c;l>r&&(r=l,n=i)}return n}getAllStrategies(){return Array.from(this.strategies.values())}getStrategiesByTechnique(e){return this.getAllStrategies().filter(t=>t.technique===e)}getSessionStats(){let e=this.sessionStore.getAll();if(e.length===0)return{totalSessions:0,successfulSessions:0,avgImprovement:0,byTechnique:new Map,strategiesLearned:0};let t=e.map(a=>this.calculateOverallImprovement(a)),n=t.filter(a=>a>=this.config.minCoverageImprovementToLearn).length,r=t.reduce((a,c)=>a+c,0)/t.length,i=new Map,s=new Map;for(let a of e){let c=s.get(a.technique)||[];c.push(a),s.set(a.technique,c)}for(let[a,c]of s){let l=c.map(d=>this.calculateOverallImprovement(d));i.set(a,{count:c.length,avgImprovement:l.reduce((d,u)=>d+u,0)/l.length})}return{totalSessions:e.length,successfulSessions:n,avgImprovement:r,byTechnique:i,strategiesLearned:this.strategies.size}}analyzeGapResolution(){let t=this.sessionStore.getAll().flatMap(i=>i.gapsTargeted);if(t.length===0)return{totalGapsTargeted:0,gapsAddressed:0,resolutionRate:0,byGapType:new Map};let n=t.filter(i=>i.addressed).length,r=new Map;for(let i of t){let s=r.get(i.type)||{targeted:0,addressed:0};s.targeted++,i.addressed&&s.addressed++,r.set(i.type,s)}return{totalGapsTargeted:t.length,gapsAddressed:n,resolutionRate:n/t.length,byGapType:r}}exportSessions(){return this.sessionStore.getAll()}importSessions(e){for(let t of e)this.sessionStore.add(t)}exportStrategies(){return this.getAllStrategies()}importStrategies(e){for(let t of e){let n=`${t.technique}:${t.filePatterns[0]||"*"}`;this.strategies.set(n,t)}}clear(){this.sessionStore.clear(),this.strategies.clear()}getLearnerStats(){return{totalSessions:this.sessionStore.size,totalStrategies:this.strategies.size,hasReasoningBank:this.reasoningBank!==null,minImprovementThreshold:this.config.minCoverageImprovementToLearn}}};function ic(o){return new xi(o)}var Ai=class{weights;historicalScores=[];maxHistory;constructor(e={},t=100){this.weights={...Ti,...e},this.maxHistory=t}calculateFromOutcome(e){let t=this.calculateDimensions(e),n=this.calculateOverall(t);return this.trackScore(n),{overall:n,dimensions:t,weights:this.weights,trend:this.calculateTrend(),calculatedAt:new Date}}calculateDimensions(e){return{effectiveness:this.calculateEffectiveness(e),coverage:this.calculateCoverageScore(e.coverage),mutationKill:e.mutationScore??.5,stability:this.calculateStability(e),maintainability:e.maintainabilityScore,performance:this.calculatePerformanceScore(e.executionTimeMs)}}calculateEffectiveness(e){return e.passed?e.flaky?.3:1:0}calculateCoverageScore(e){return(e.lines*.4+e.branches*.35+e.functions*.25)/100}calculateStability(e){return e.flaky?.2:e.flakinessScore!==void 0?1-e.flakinessScore:1}calculatePerformanceScore(e){return e<100?1:e<500?.8:e<2e3?.6:e<5e3?.4:e<1e4?.2:.1}calculateOverall(e){return this.weights.effectiveness*e.effectiveness+this.weights.coverage*e.coverage+this.weights.mutationKill*e.mutationKill+this.weights.stability*e.stability+this.weights.maintainability*e.maintainability+this.weights.performance*e.performance}trackScore(e){this.historicalScores.push(e),this.historicalScores.length>this.maxHistory&&(this.historicalScores=this.historicalScores.slice(-this.maxHistory))}calculateTrend(){if(this.historicalScores.length<10)return"stable";let e=this.historicalScores.slice(-10),t=this.historicalScores.slice(-20,-10);if(t.length===0)return"stable";let n=e.reduce((s,a)=>s+a,0)/e.length,r=t.reduce((s,a)=>s+a,0)/t.length,i=n-r;return i>.05?"improving":i<-.05?"declining":"stable"}calculateAggregate(e){if(e.length===0)return{overall:0,dimensions:{effectiveness:0,coverage:0,mutationKill:0,stability:0,maintainability:0,performance:0},weights:this.weights,trend:"stable",calculatedAt:new Date};let t={effectiveness:0,coverage:0,mutationKill:0,stability:0,maintainability:0,performance:0};for(let s of e){let a=this.calculateDimensions(s);t.effectiveness+=a.effectiveness,t.coverage+=a.coverage,t.mutationKill+=a.mutationKill,t.stability+=a.stability,t.maintainability+=a.maintainability,t.performance+=a.performance}let n=e.length,r={effectiveness:t.effectiveness/n,coverage:t.coverage/n,mutationKill:t.mutationKill/n,stability:t.stability/n,maintainability:t.maintainability/n,performance:t.performance/n};return{overall:this.calculateOverall(r),dimensions:r,weights:this.weights,trend:this.calculateTrend(),calculatedAt:new Date}}calculateDelta(e,t){let n={effectiveness:t.dimensions.effectiveness-e.dimensions.effectiveness,coverage:t.dimensions.coverage-e.dimensions.coverage,mutationKill:t.dimensions.mutationKill-e.dimensions.mutationKill,stability:t.dimensions.stability-e.dimensions.stability,maintainability:t.dimensions.maintainability-e.dimensions.maintainability,performance:t.dimensions.performance-e.dimensions.performance},r=t.overall-e.overall;return{overallDelta:r,dimensionDeltas:n,improved:r>0}}getRecommendations(e){let t=[],n=e.dimensions;return n.effectiveness<.8&&t.push("Improve test pass rate - investigate failing tests"),n.coverage<.7&&t.push("Increase code coverage - target uncovered paths"),n.mutationKill<.6&&t.push("Strengthen assertions - tests may be too weak"),n.stability<.9&&t.push("Address test flakiness - stabilize intermittent tests"),n.maintainability<.7&&t.push("Improve test maintainability - reduce complexity"),n.performance<.6&&t.push("Optimize test performance - reduce execution time"),t.length===0&&t.push("Quality is excellent - maintain current practices"),t}updateWeights(e){this.weights={...this.weights,...e}}getWeights(){return{...this.weights}}getStats(){let e=this.historicalScores.slice(-10),t=e.length>0?e.reduce((n,r)=>n+r,0)/e.length:0;return{scoresTracked:this.historicalScores.length,currentTrend:this.calculateTrend(),avgRecentScore:t}}clearHistory(){this.historicalScores=[]}};function sc(o,e){return new Ai(o,e)}var ki=class{criteria;promotionHistory=[];demotionHistory=[];reasoningBank=null;config;constructor(e={}){this.config={...xe,...e},this.criteria={...Ei}}connectReasoningBank(e){this.reasoningBank=e}evaluatePromotion(e,t){let n=e.tier,r=this.getNextTier(n);if(!r)return null;let i=this.criteria[r];if(this.meetsPromotionCriteria(t,i)){let s={patternId:e.id,fromTier:n,toTier:r,reason:this.generatePromotionReason(t,i),metrics:{successCount:t.successCount,successRate:t.successRate,qualityScore:t.qualityScore,ageDays:t.ageDays},timestamp:new Date};return this.promotionHistory.push(s),s}return null}evaluateDemotion(e,t){if(!this.config.autoDemote)return null;let n=e.tier;if(n==="short-term")return null;if(t.recentSuccessRate<.4||t.recentFailureCount>=5||t.qualityScore<.3){let i=this.getPreviousTier(n);if(!i)return null;let s={patternId:e.id,fromTier:n,toTier:i,reason:this.generateDemotionReason(t),metrics:{recentSuccessRate:t.recentSuccessRate,recentQualityScore:t.qualityScore,failureCount:t.recentFailureCount},timestamp:new Date};return this.demotionHistory.push(s),s}return null}async processPatternChange(e,t){let n=this.evaluateDemotion(e,t);if(n)return this.reasoningBank&&await this.reasoningBank.demotePattern(e.id),{action:"demoted",event:n};let r=this.evaluatePromotion(e,t);return r?(this.reasoningBank&&await this.reasoningBank.promotePattern(e.id),{action:"promoted",event:r}):{action:"unchanged"}}meetsPromotionCriteria(e,t){return e.successCount>=t.minSuccessCount&&e.successRate>=t.minSuccessRate&&e.qualityScore>=t.minQualityScore&&e.ageDays>=t.minAgeDays}getNextTier(e){let t=["short-term","working","long-term","permanent"],n=t.indexOf(e);return n<t.length-1?t[n+1]:null}getPreviousTier(e){let t=["short-term","working","long-term","permanent"],n=t.indexOf(e);return n>0?t[n-1]:null}generatePromotionReason(e,t){let n=[];return e.successCount>=t.minSuccessCount&&n.push(`${e.successCount} successful uses (>=${t.minSuccessCount})`),e.successRate>=t.minSuccessRate&&n.push(`${(e.successRate*100).toFixed(0)}% success rate (>=${t.minSuccessRate*100}%)`),e.qualityScore>=t.minQualityScore&&n.push(`${(e.qualityScore*100).toFixed(0)}% quality score (>=${t.minQualityScore*100}%)`),`Pattern promoted: ${n.join(", ")}`}generateDemotionReason(e){let t=[];return e.recentSuccessRate<.4&&t.push(`low recent success rate (${(e.recentSuccessRate*100).toFixed(0)}%)`),e.recentFailureCount>=5&&t.push(`${e.recentFailureCount} recent failures`),e.qualityScore<.3&&t.push(`low quality score (${(e.qualityScore*100).toFixed(0)}%)`),`Pattern demoted: ${t.join(", ")}`}updateCriteria(e,t){this.criteria[e]={...this.criteria[e],...t}}getCriteria(e){return{...this.criteria[e]}}getAllCriteria(){return{...this.criteria}}getPromotionHistory(e=100){return this.promotionHistory.slice(-e)}getDemotionHistory(e=100){return this.demotionHistory.slice(-e)}getStats(){let e={"short-term":0,working:0,"long-term":0,permanent:0};for(let s of this.promotionHistory)e[s.toTier]++;let t={"short-term":0,working:0,"long-term":0,permanent:0};for(let s of this.demotionHistory)t[s.toTier]++;let n=Date.now()-10080*60*1e3,r=this.promotionHistory.filter(s=>s.timestamp.getTime()>n).length,i=this.demotionHistory.filter(s=>s.timestamp.getTime()>n).length;return{totalPromotions:this.promotionHistory.length,totalDemotions:this.demotionHistory.length,promotionsByTier:e,demotionsByTier:t,recentPromotions:r,recentDemotions:i}}exportHistory(){return{promotions:[...this.promotionHistory],demotions:[...this.demotionHistory]}}importHistory(e){e.promotions&&this.promotionHistory.push(...e.promotions),e.demotions&&this.demotionHistory.push(...e.demotions)}clearHistory(){this.promotionHistory=[],this.demotionHistory=[]}};function ac(o){return new ki(o)}var Mi=class{outcomeTracker;coverageLearner;qualityCalculator;promotionManager;routingFeedback;reasoningBank=null;config;constructor(e={}){this.config={...xe,...e},this.outcomeTracker=rc(this.config),this.coverageLearner=ic(this.config),this.qualityCalculator=sc(this.config.qualityWeights),this.promotionManager=ac(this.config),this.routingFeedback=qs(this.config.maxOutcomesInMemory)}async initialize(){await Promise.all([this.outcomeTracker.initialize(),this.coverageLearner.initialize(),this.routingFeedback.initialize()])}connectReasoningBank(e){this.reasoningBank=e,this.outcomeTracker.connectReasoningBank(e),this.coverageLearner.connectReasoningBank(e),this.promotionManager.connectReasoningBank(e)}async recordTestOutcome(e){await this.outcomeTracker.track(e);let t=this.qualityCalculator.calculateFromOutcome(e),n;if(e.patternId&&this.reasoningBank){let r=await this.reasoningBank.searchQEPatterns(e.patternId,{limit:1});if(r.success&&r.value.length>0){let i=r.value[0].pattern,s=this.outcomeTracker.getPatternMetrics(e.patternId);if(s){let a=await this.promotionManager.processPatternChange(i,{patternId:e.patternId,successCount:s.successCount,failureCount:s.failureCount,successRate:s.successRate,qualityScore:s.avgQuality,ageDays:this.calculateAgeDays(i.createdAt),recentSuccessRate:this.calculateRecentSuccessRate(e.patternId),recentFailureCount:this.calculateRecentFailures(e.patternId)});n={action:a.action,tier:a.event&&"toTier"in a.event?a.event.toTier:void 0}}}}return{qualityScore:t,patternUpdate:n}}async recordCoverageSession(e){let t=await this.coverageLearner.learnFromSession(e);return{improvement:(e.afterCoverage.lines-e.beforeCoverage.lines+e.afterCoverage.branches-e.beforeCoverage.branches+e.afterCoverage.functions-e.beforeCoverage.functions)/3,strategyLearned:t!==null,strategyId:t?.id}}getRecommendedCoverageStrategy(e){return this.coverageLearner.getRecommendedStrategy(e)}getQualityRecommendations(){let e=this.outcomeTracker.getRecentOutcomes(50);if(e.length===0)return["No test outcomes recorded yet. Start tracking test results to get recommendations."];let t=this.qualityCalculator.calculateAggregate(e);return this.qualityCalculator.getRecommendations(t)}async recordRoutingOutcome(e){let t={id:e.taskId,description:e.taskDescription,complexity:"medium",domains:["test-generation"],context:{}},n={recommended:e.recommendedAgent,confidence:.8,reasoning:"Recorded from feedback",alternatives:[],scores:{similarity:.8,performance:.8,capabilities:.8,combined:.8},latencyMs:0,timestamp:e.timestamp};this.routingFeedback.recordOutcome(t,n,e.usedAgent,{success:e.success,qualityScore:e.qualityScore,durationMs:e.durationMs,error:e.error})}getRoutingAnalysis(){let e=this.routingFeedback.analyzeRoutingAccuracy(),t=this.routingFeedback.getImprovementRecommendations();return{totalOutcomes:e.totalOutcomes,recommendationFollowRate:1-e.overrideRate,successRateWhenFollowed:e.recommendationSuccessRate,successRateWhenOverridden:e.overrideSuccessRate,confidenceCorrelation:e.confidenceCorrelation,recommendations:t}}calculateAgeDays(e){return(Date.now()-e.getTime())/(1e3*60*60*24)}calculateRecentSuccessRate(e){let t=this.outcomeTracker.exportOutcomes().filter(r=>r.patternId===e).slice(-10);return t.length===0?0:t.filter(r=>r.passed&&!r.flaky).length/t.length}calculateRecentFailures(e){return this.outcomeTracker.exportOutcomes().filter(n=>n.patternId===e).slice(-10).filter(n=>!n.passed||n.flaky).length}getStats(){let e=this.outcomeTracker.getStats(),t=this.coverageLearner.getSessionStats(),n=this.promotionManager.getStats(),r=this.qualityCalculator.getStats(),i=this.outcomeTracker.getTrackerStats(),s=this.routingFeedback.analyzeRoutingAccuracy();return{testOutcomes:{total:e.totalTests,passRate:e.passRate,avgQuality:e.avgMaintainability,flakyCount:e.flakyTests},coverage:{totalSessions:t.totalSessions,successfulSessions:t.successfulSessions,avgImprovement:t.avgImprovement,strategiesLearned:t.strategiesLearned},patterns:{promoted:n.totalPromotions,demoted:n.totalDemotions,tracked:i.patternsTracked},quality:{currentTrend:r.currentTrend,avgRecentScore:r.avgRecentScore},routing:{totalOutcomes:s.totalOutcomes,recommendationFollowRate:1-s.overrideRate,successRateWhenFollowed:s.recommendationSuccessRate,successRateWhenOverridden:s.overrideSuccessRate},integrationStatus:{reasoningBankConnected:this.reasoningBank!==null}}}exportData(){return{outcomes:this.outcomeTracker.exportOutcomes(),sessions:this.coverageLearner.exportSessions(),strategies:this.coverageLearner.exportStrategies(),promotionHistory:this.promotionManager.exportHistory(),routingOutcomes:this.routingFeedback.exportOutcomes()}}importData(e){e.outcomes&&this.outcomeTracker.importOutcomes(e.outcomes),e.sessions&&this.coverageLearner.importSessions(e.sessions),e.strategies&&this.coverageLearner.importStrategies(e.strategies),e.promotionHistory&&this.promotionManager.importHistory(e.promotionHistory),e.routingOutcomes&&this.routingFeedback.importOutcomes(e.routingOutcomes)}clear(){this.outcomeTracker.clear(),this.coverageLearner.clear(),this.qualityCalculator.clearHistory(),this.promotionManager.clearHistory(),this.routingFeedback.clear()}};async function oc(o){let e=new Mi(o);return await e.initialize(),cc=e,e}var cc=null;function lc(){return cc}fs();function tt(){return`test-${et()}`}function uc(o){return`${o}-${et()}`}function Di(o){return{enabled:!0,agentId:uc(o),message:"Experience captured asynchronously via learning pipeline"}}async function jd(o,e,t,n,r,i=Pr(e,n),s){let a=uc(o);try{let{kernel:c}=Mt();if(!c)return{enabled:!1,agentId:a,message:"Learning engine not available - kernel not initialized"};let l=await Ud();if(!l)return{enabled:!1,agentId:a,message:"Learning engine not available"};let d=l.getExperienceCaptureService();if(!d)return{enabled:!1,agentId:a,message:"Experience capture service not available"};let u=zd(e),m=d.startCapture(`${e}: ${JSON.stringify(t).slice(0,200)}`,{agent:o,domain:u||void 0,metadata:{tool:e,durationMs:r,...s?{runId:s}:{}}}),p=i.measured?i.success===!0:!0,g=p?.7:.3;d.recordStep(m,{action:`execute-${e}`,result:typeof n=="object"?JSON.stringify(n).slice(0,500):String(n).slice(0,500),quality:g});let f=await d.completeCapture(m,{success:p,quality:g,...i.measured?{outcomeBasis:i.basis}:{}});if(f.success){let h=f.value;return{enabled:!0,agentId:a,message:`Experience captured: ${h.id} (domain: ${u||"general"}, quality: ${h.quality})`,experienceId:h.id,domain:u||"general"}}return{enabled:!0,agentId:a,message:"Experience capture completed (no pattern extracted)"}}catch(c){return{enabled:!1,agentId:a,message:`Learning capture failed: ${w(c)}`}}}function zd(o){return{test_generate_enhanced:"test-generation",test_execute_parallel:"test-execution",coverage_analyze_sublinear:"coverage-analysis",quality_assess:"quality-assessment",security_scan_comprehensive:"security-compliance",contract_validate:"contract-testing",accessibility_test:"visual-accessibility",chaos_test:"chaos-resilience",defect_predict:"defect-intelligence",requirements_validate:"requirements-validation",code_index:"code-intelligence"}[o]||null}async function Ud(){return hc()}async function Bd(o,e,t,n){let r=lc();if(!r&&Ii&&(r=await Ii),!!r){if(o==="test-generation"&&e){let i=e.tests||e.generatedTests||[];for(let s of i.slice(0,20)){let a={id:String(s.id||et()),testId:String(s.id||s.name||et()),testName:String(s.name||s.testName||"generated-test"),generatedBy:"qe-test-generation",patternId:s.patternId,framework:s.framework||n.framework||"vitest",language:s.language||n.language||"typescript",domain:"test-generation",passed:s.passed!==!1,coverage:{lines:Number(s.coverageLines||0),branches:Number(s.coverageBranches||0),functions:Number(s.coverageFunctions||0)},executionTimeMs:Number(s.executionTimeMs||t/Math.max(i.length,1)),flaky:!!s.flaky,maintainabilityScore:Number(s.qualityScore||s.maintainability||.7),timestamp:new Date};await r.recordTestOutcome(a)}}if(o==="coverage-analysis"&&e&&We(o,e)){let i={id:et(),targetPath:String(n.target||n.targetPath||"src/"),agentId:"qe-coverage-analysis",technique:n.technique||"gap-analysis",beforeCoverage:{lines:Number(e.beforeCoverage?.lines||0),branches:Number(e.beforeCoverage?.branches||0),functions:Number(e.beforeCoverage?.functions||0)},afterCoverage:{lines:Number(e.lineCoverage||e.lines||0),branches:Number(e.branchCoverage||e.branches||0),functions:Number(e.functionCoverage||e.functions||0)},testsGenerated:Number(e.testsGenerated||0),testsPassed:Number(e.testsPassed||0),gapsTargeted:(e.gaps||[]).map((s,a)=>({id:String(s.id||`gap-${et().slice(0,8)}-${a}`),type:["uncovered-line","uncovered-branch","uncovered-function","partial-branch"].includes(String(s.type))?String(s.type):"uncovered-line",filePath:String(s.file||s.filePath||""),startLine:Number(s.line||s.startLine||0),endLine:s.endLine?Number(s.endLine):void 0,riskScore:Number(s.riskScore||.5),addressed:!!s.addressed})),durationMs:t,startedAt:new Date(Date.now()-t),completedAt:new Date,context:{measured:!0,coverageMethod:e.coverageMethod??"instrumented-report",branchDataCollected:e.branchCoverage!==null&&e.branchCoverage!==void 0,functionDataCollected:e.functionCoverage!==null&&e.functionCoverage!==void 0,...e.runStatus==="passed"||e.runStatus==="failed"?{runStatus:e.runStatus}:{}}};await r.recordCoverageSession(i)}}}function dc(o){let e=o.split(`
463
- `).length,t=(o.match(/if|switch|for|while|catch/g)||[]).length;return{score:e+t*2,level:t>5?"high":t>2?"medium":"low"}}function mc(o,e){let t=[];return o.level==="high"&&(t.push("Consider refactoring complex functions"),t.push("Add unit tests for each branch")),t.push("Consider adding edge case tests"),t.push("Add error handling tests"),e==="integration"&&(t.push("Add mock external dependencies"),t.push("Test API contract boundaries")),{recommendations:t,estimatedTime:`${Math.round(o.score*.5)} minutes`,confidence:.85}}function pc(o,e,t,n){let r=[],i=/(?:function\s+(\w+)|const\s+(\w+)\s*=|def\s+(\w+)|func\s+(\w+))/g,s=[],a;for(;(a=i.exec(o))!==null;){let l=a[1]||a[2]||a[3]||a[4];l&&s.push(l)}for(let l=0;l<Math.min(s.length,n);l++){let d=s[l]||"exampleFunction";r.push({id:tt(),name:`test_${d}_${l}`,type:e,parameters:[],assertions:[`${d}() === null`],expectedResult:null,estimatedDuration:e==="integration"?2e3:1e3,aiGenerated:!0})}(e==="integration"||n>s.length)&&r.push({id:tt(),name:`integration_ComponentA_${r.length}`,type:"integration",parameters:[],assertions:["ComponentA integration test passes"],expectedResult:null,estimatedDuration:2e3,aiGenerated:!0});let c=["high-complexity","deep-nesting","null-handling","empty-input"];for(let l=r.length;l<n&&l-r.length<c.length;l++)r.push({id:tt(),name:`edge_case_${c[l-r.length]}_${l}`,type:"unit",parameters:[],assertions:[`${c[l-r.length]} edge case handled`],expectedResult:null,estimatedDuration:1500,aiGenerated:!0});return r}function gc(o,e){let t=[],n=o.split(`
464
- `);return o.includes("eval(")&&t.push({type:"dangerous-eval",line:n.findIndex(r=>r.includes("eval("))+1,severity:"critical",suggestion:"Replace eval() with safer alternatives"}),o.includes("var ")&&(e==="javascript"||e==="typescript")&&t.push({type:"var-usage",line:n.findIndex(r=>r.includes("var "))+1,severity:"low",suggestion:"Use const or let instead of var"}),o.includes("any")&&e==="typescript"&&t.push({type:"any-type",line:n.findIndex(r=>r.includes("any"))+1,severity:"medium",suggestion:"Replace any with specific types"}),t}var kt=null,Ii=null,ge=null,Hd=Number(process.env.AQE_ROUTE_TIMEOUT_MS)||5e3;function Vd(o,e,t){return new Promise(n=>{let r=!1,i=setTimeout(()=>{r||(r=!0,n(t))},e);typeof i.unref=="function"&&i.unref(),o.then(s=>{r||(r=!0,clearTimeout(i),n(s))},()=>{r||(r=!0,clearTimeout(i),n(t))})})}function Qd(){if(!kt){let{kernel:o}=Mt();if(!o)throw new Error("Kernel not initialized");kt=ec(o);let e=kt;Ii=oc().then(t=>(e.setQualityFeedbackLoop(t),t)).catch(t=>(console.warn("[HandlerFactory] Failed to initialize QualityFeedbackLoop:",t),null))}return kt}function fc(){if(kt=null,ge){let o=ge;ge=null,o.dispose().catch(()=>{})}}async function hc(){if(ge)return ge;try{let{kernel:o}=Mt();if(!o)return null;let{createAQELearningEngine:e}=await import("./aqe-learning-engine-OXH5CCOS.js"),t=o.memory,n=e(t,{projectRoot:process.cwd(),enableClaudeFlow:!1});return await n.initialize(),ge=n,ge}catch(o){return console.debug("[HandlerFactory] Learning engine init failed:",w(o)),null}}async function Wd(o,e){try{let t=await hc();if(!t)return[];let n=e,r=await t.searchPatterns(o,{limit:5,minConfidence:.4,domain:n,useVectorSearch:!0});return!r.success||r.value.length===0?[]:r.value.filter(i=>i.similarity>=.4).map(i=>({name:i.pattern.name,description:i.pattern.description,similarity:i.similarity,confidence:i.pattern.confidence,canReuse:i.canReuse,patternId:i.pattern.id}))}catch(t){return console.debug("[HandlerFactory] Pattern search failed:",w(t)),[]}}async function Kd(o,e,t){try{let n=await Wd(o,e);return n.length>0&&console.debug(`[HandlerFactory] Found ${n.length} relevant patterns for ${e}`),await(await Nn()).routeTask({task:o,domain:e,codeContext:t,agentType:`qe-${e}`,enablePatternSearch:!0,patternHints:n.length>0?n:void 0})}catch(n){return console.error(`[HandlerFactory] Routing failed for ${e}: ${n}`),null}}async function Xd(o,e,t,n,r){if(!o||o.length===0||!e.measured||!ge)return;let i=e.success===!0;try{for(let s of o)s.patternId&&await ge.recordOutcome({patternId:s.patternId,success:i,metrics:{executionTimeMs:n,...Ps(e,r)},feedback:`Domain handler ${t} outcome ${i?"succeeded":"failed"} (${e.basis})`})}catch{}}function re(o){let{domain:e,taskType:t,priority:n="p1",defaultTimeout:r=18e4,buildTaskDescription:i,mapToPayload:s,mapToResult:a,calculateTimeout:c,includeCodeContext:l}=o;return async d=>{if(!nt())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:u}=Mt(),m=null;try{let p=nc(d),g=i(d),f=l?.(d);m=await Vd(Kd(g,e,f),Hd,null);let h=s(d,m);p||(h.saveResults=!1);let v=c?.(d)??r,y=await u.submitTask({type:t,executionOwner:"caller",priority:n,targetDomains:[e],payload:h,timeout:v});if(!y.success)return{success:!1,error:y.error.message};let C=Qd(),b=u.getTaskStatus(y.value);if(!b)return{success:!1,error:"Task not found after submission"};let E=await C.execute(b.task);if(!E.success)return{success:!1,error:E.error?je(E.error,Number.POSITIVE_INFINITY):"Task execution failed",...E.errorDetails?{data:E.errorDetails}:{}};let T=E.data,S=a(y.value,T,E.duration,E.savedFiles,d);if(Object.assign(S,Hn(p,E.savedFiles)),We(e,T)&&We("",S)){let M=Pr(t,S);Xd(m?.patternHints,M,e,E.duration,y.value),jd(`qe-${e}`,t,d,T,E.duration,M,y.value).catch(()=>{});try{await Bd(e,T,E.duration,d)}catch{}}return{success:!0,data:S}}catch(p){let g=w(p),f=$e(p);return{success:!1,error:je(`Failed to ${t.replace(/-/g," ")}: ${g}`,Number.POSITIVE_INFINITY),...f?{data:{callerError:!0}}:{}}}}}var Vn=class{taskMetrics=[];agentMetrics=new Map;resourceSnapshots=[];workerLoads=new Map;activeTasks=new Map;lastCpuUsage=null;snapshotInterval=null;initialized=!1;initialize(){this.initialized||(this.initialized=!0,this.lastCpuUsage=process.cpuUsage(),this.snapshotInterval=setInterval(()=>{this.takeResourceSnapshot()},1e3),this.snapshotInterval.unref&&this.snapshotInterval.unref())}shutdown(){this.snapshotInterval&&(clearInterval(this.snapshotInterval),this.snapshotInterval=null),this.initialized=!1}startTask(e,t){this.ensureInitialized();let n={taskId:e,agentId:t,startTime:process.hrtime(),success:!1,retries:0};this.activeTasks.set(e,n),this.updateWorkerLoad(t,1,0)}recordRetry(e){let t=this.activeTasks.get(e);t&&t.retries++}completeTask(e,t){let n=this.activeTasks.get(e);if(!n)return 0;n.endTime=process.hrtime(),n.success=t;let r=process.hrtime(n.startTime);return n.durationMs=r[0]*1e3+r[1]/1e6,this.updateAgentMetrics(n),this.updateWorkerLoad(n.agentId,-1,1),this.taskMetrics.push(n),this.taskMetrics.length>100&&this.taskMetrics.shift(),this.activeTasks.delete(e),n.durationMs}getCpuUsagePercent(){if(this.ensureInitialized(),!this.lastCpuUsage)return this.lastCpuUsage=process.cpuUsage(),0;let e=process.cpuUsage(this.lastCpuUsage);this.lastCpuUsage=process.cpuUsage();let t=e.user+e.system,r=1e3*1e3,i=t/r*100;return Math.min(100,Math.max(0,i))}getMemoryUsagePercent(){let e=process.memoryUsage(),t=e.heapUsed/e.heapTotal*100;return Math.min(100,Math.max(0,t))}getResourceStats(e){return{cpu:this.getCpuUsagePercent(),memory:this.getMemoryUsagePercent()}}getAgentTaskStats(e){let t=this.agentMetrics.get(e);if(!t||t.taskCount===0)return{tasksCompleted:0,averageTime:0,successRate:1};let n=t.tasksCompleted+t.tasksFailed,r=n>0?t.tasksCompleted/n:1,i=t.taskCount>0?t.totalDurationMs/t.taskCount:0;return{tasksCompleted:t.tasksCompleted,averageTime:Math.round(i),successRate:Math.min(1,Math.max(0,r))}}getRecordedTaskCount(){return this.taskMetrics.length}getWorkerEfficiency(){if(this.taskMetrics.length===0)return null;let t=this.taskMetrics.filter(a=>a.success).length/this.taskMetrics.length,r=this.taskMetrics.reduce((a,c)=>a+c.retries,0)/this.taskMetrics.length,i=Math.min(.2,r*.1),s=t*(1-i);return Math.min(1,Math.max(0,s))}getLoadBalanceScore(){if(this.workerLoads.size===0)return null;let e=Array.from(this.workerLoads.values()).map(a=>a.completedTaskCount);if(e.length<=1)return 1;let t=e.reduce((a,c)=>a+c,0)/e.length;if(t===0)return 1;let n=e.reduce((a,c)=>a+Math.pow(c-t,2),0)/e.length,s=1/(1+Math.sqrt(n)/t);return Math.min(1,Math.max(0,s))}getRetryStats(){let e=0,t=0,n=0;for(let r of this.agentMetrics.values())e+=r.totalRetries,t+=r.successfulRetries,n+=r.maxRetriesReached;return{totalRetries:e,successfulRetries:t,maxRetriesReached:n}}getAverageExecutionTime(){if(this.taskMetrics.length===0)return 0;let e=this.taskMetrics.reduce((t,n)=>t+(n.durationMs||0),0);return Math.round(e/this.taskMetrics.length)}getWorkersUsed(){return this.workerLoads.size}recordSuccessfulRetry(e){let t=this.agentMetrics.get(e);t&&t.successfulRetries++}recordMaxRetriesReached(e){let t=this.agentMetrics.get(e);t&&t.maxRetriesReached++}reset(){this.taskMetrics=[],this.agentMetrics.clear(),this.resourceSnapshots=[],this.workerLoads.clear(),this.activeTasks.clear(),this.lastCpuUsage=null}ensureInitialized(){this.initialized||this.initialize()}updateAgentMetrics(e){let t=this.agentMetrics.get(e.agentId);t||(t={agentId:e.agentId,tasksCompleted:0,tasksFailed:0,totalRetries:0,successfulRetries:0,maxRetriesReached:0,totalDurationMs:0,taskCount:0},this.agentMetrics.set(e.agentId,t)),e.success?(t.tasksCompleted++,e.retries>0&&t.successfulRetries++):t.tasksFailed++,t.totalRetries+=e.retries,t.totalDurationMs+=e.durationMs||0,t.taskCount++}updateWorkerLoad(e,t,n){let r=this.workerLoads.get(e);r||(r={workerId:e,activeTaskCount:0,completedTaskCount:0,lastActivityTime:Date.now()},this.workerLoads.set(e,r)),r.activeTaskCount=Math.max(0,r.activeTaskCount+t),r.completedTaskCount+=n,r.lastActivityTime=Date.now()}takeResourceSnapshot(){let e=process.memoryUsage(),t=process.cpuUsage(),n={timestamp:Date.now(),cpuUser:t.user,cpuSystem:t.system,memoryHeapUsed:e.heapUsed,memoryHeapTotal:e.heapTotal,memoryExternal:e.external,memoryRss:e.rss};this.resourceSnapshots.push(n),this.resourceSnapshots.length>60&&this.resourceSnapshots.shift()}},It=new Vn;D();Rl();var _i="^(?:UNKNOWN|[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,255})$",Oi="(?:^|[._:/@+\\-])(?:(?:[sS][kK]|[rR][kK]|[gG][hH][pPoOuUsSrR]|[gG][iI][tT][hH][uU][bB]_[pP][aA][tT]|[xX][oO][xX][bBaApPrRsS]|[nN][pP][mM]|[gG][lL][pP][aA][tT]|[pP][aA][tT])(?:[-_][A-Za-z0-9_-]*|(?=$|[.:/@+\\-]))|(?:[aA][kK][iI][aA]|[aA][sS][iI][aA]|[aA][iI][zZ][aA])[A-Za-z0-9]*)",Ni="(?:^|[^A-Za-z0-9_-])(?:eyJ[A-Za-z0-9_-]*|e30|ew[A-Za-z0-9_-]*)\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+(?:$|[^A-Za-z0-9_-])",Fi="(?:^|[._:/@+\\-])[A-Za-z0-9]{32,}(?:$|[._:/@+\\-])",Li="(?:(?:^|[.:@\\-])[A-Za-z0-9+/]{32,}={0,2}(?:$|[.:@\\-])|(?:^|[.:/@+\\-])[A-Za-z0-9_-]{48,}(?:$|[.:/@+\\-]))",qi="^\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])T(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d{1,9})?Z$",qb=new RegExp(_i),$b=new RegExp(Oi),Gb=new RegExp(Ni),jb=new RegExp(Fi),zb=new RegExp(Li),Ub=new RegExp(qi);function Yd(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function Jd(o){return Array.isArray(o)&&o.every(e=>typeof e=="string")}function Zd(o){return typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=1}function vc(o){let e=[];return Yd(o)?(o.contract!=="risk-decision@1"&&e.push('contract must be "risk-decision@1"'),["approve","block","escalate"].includes(o.decision)||e.push("decision must be approve|block|escalate"),Jd(o.riskFactors)||e.push("riskFactors must be string[]"),Zd(o.confidence)||e.push("confidence must be a number in [0,1]"),(typeof o.rationale!="string"||o.rationale.length===0)&&e.push("rationale must be a non-empty string"),{valid:e.length===0,errors:e}):{valid:!1,errors:["not an object"]}}var em=.7;function bc(o){let{passed:e,qualityScore:t,recommendations:n=[],unmeasured:r=[],failedMetrics:i=[],gateEvaluated:s}=o,a=s===!1?" (no quality gate was evaluated)":"",c=typeof t=="number"?` with score ${t}`:"";if(i.length>0){let m=r.length>0?`; also unmeasured: ${r.join(", ")}`:"";return{contract:"risk-decision@1",decision:"block",riskFactors:[`failed: ${i.join(", ")}`,...r.length>0?[`unmeasured: ${r.join(", ")}`]:[],...n].slice(0,10),confidence:.9,rationale:`Measured ${i.join(", ")} failed its threshold${m}${a}`}}if(r.length>0){let m=typeof o.evidenceConfidence=="number"&&Number.isFinite(o.evidenceConfidence)?Math.min(1,Math.max(0,o.evidenceConfidence)):0;return{contract:"risk-decision@1",decision:"escalate",riskFactors:[`unmeasured: ${r.join(", ")}`,...n].slice(0,10),confidence:Math.round(.5*m*100)/100,rationale:`Insufficient evidence: ${r.join(", ")} not measured${a} \u2014 measure the missing metrics or run the measured quality gate before deciding`}}let l=e===!0?"approve":e===!1?"block":"escalate",d=s===!1?"Static analysis":"Quality gate",u=l==="escalate"?.5:l==="approve"&&s===!1?em:.9;return{contract:"risk-decision@1",decision:l,riskFactors:n.slice(0,10),confidence:u,rationale:l==="escalate"?"Quality gate outcome indeterminate \u2014 manual review required":`${d} ${e?"passed":"failed"}${c}${a}`}}var tm={type:"number",minimum:0,maximum:1},yc={type:"array",items:{type:"string"}};function rt(o){return{type:"string",pattern:_i,allOf:[{not:{pattern:Oi}},{not:{pattern:Ni}},{not:{pattern:o==="provider"||o==="requestedModel"||o==="resolvedModel"?Fi:Li}}]}}var it={type:"string",pattern:"^(?:UNKNOWN|sha256:[a-f0-9]{64})$"},ie={type:"string",pattern:"^sha256:[a-f0-9]{64}$"};var Wb={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://agentic-qe.dev/schemas/finding-verdict.schema.json",title:"FindingVerdict",type:"object",required:["contract","id","title","severity","confidence","evidence","verdict","refutations"],additionalProperties:!0,properties:{contract:{const:"finding-verdict@1"},id:{type:"string",minLength:1},title:{type:"string",minLength:1},file:{type:"string"},severity:{enum:["critical","high","medium","low","info"]},confidence:tm,evidence:yc,verdict:{enum:["upheld","refuted","uncertain"]},refutations:yc,measurementReceipts:{type:"array",items:{type:"object",required:["contract","provider","requestedModel","resolvedModel","endpointClass","snapshotIdentity","semantics","fingerprint","requestHash","promptHash","configHash","parserSchemaHash","outputHash","parsedVoteHash","temperature","topP","seed","deterministic","cacheStatus","retryCount","timestamp","windowId","latencyMs","requestId"],additionalProperties:!1,properties:{contract:{const:"judge-measurement@1"},provider:rt("provider"),requestedModel:rt("requestedModel"),resolvedModel:rt("resolvedModel"),endpointClass:{enum:["shared","dedicated","local","UNKNOWN"]},snapshotIdentity:{enum:["L0_UNKNOWN","L1_NAMED","L2_CONTENT_BOUND"]},semantics:{enum:["verified","provider-asserted","UNKNOWN"]},fingerprint:rt("fingerprint"),requestHash:it,promptHash:it,configHash:it,parserSchemaHash:it,outputHash:it,parsedVoteHash:it,temperature:{type:["number","null"],minimum:0},topP:{type:["number","null"],minimum:0,maximum:1},seed:{type:["integer","null"],minimum:Number.MIN_SAFE_INTEGER,maximum:Number.MAX_SAFE_INTEGER},deterministic:{type:["boolean","null"]},cacheStatus:{enum:["hit","miss","bypass","UNKNOWN"]},retryCount:{type:"integer",minimum:0,maximum:Number.MAX_SAFE_INTEGER},timestamp:{anyOf:[{const:"UNKNOWN"},{type:"string",pattern:qi,format:"date-time"}]},windowId:rt("windowId"),latencyMs:{type:["number","null"],minimum:0},requestId:rt("requestId")},allOf:[{if:{properties:{snapshotIdentity:{const:"L2_CONTENT_BOUND"}}},then:{properties:{fingerprint:{not:{const:"UNKNOWN"}},requestHash:ie,promptHash:ie,configHash:ie,parserSchemaHash:ie,outputHash:ie,parsedVoteHash:ie}}},{if:{properties:{snapshotIdentity:{const:"L1_NAMED"}}},then:{properties:{resolvedModel:{not:{const:"UNKNOWN"}}}}},{if:{properties:{semantics:{const:"verified"}}},then:{properties:{snapshotIdentity:{const:"L2_CONTENT_BOUND"},fingerprint:{not:{const:"UNKNOWN"}},requestHash:ie,promptHash:ie,configHash:ie,parserSchemaHash:ie,outputHash:ie,parsedVoteHash:ie}}},{if:{properties:{semantics:{enum:["verified","provider-asserted"]}}},then:{properties:{snapshotIdentity:{not:{const:"L0_UNKNOWN"}},fingerprint:{not:{const:"UNKNOWN"}}}}}]}}}};var Cc=Object.keys(rn);function nm(o){if(!o)return"typescript";let e=o.toLowerCase().trim(),t={ts:"typescript",js:"javascript",py:"python","c#":"csharp","c-sharp":"csharp",cs:"csharp",golang:"go",rs:"rust",kt:"kotlin"};return t[e]?t[e]:Cc.includes(e)?e:null}var Sc={domain:"test-generation",taskType:"generate-tests",priority:"p1",defaultTimeout:12e4,buildTaskDescription:o=>`Generate ${o.testType||"unit"} tests for ${o.language||"typescript"} code`,includeCodeContext:o=>o.sourceCode,mapToPayload:(o,e)=>{let t=nm(o.language);if(t===null)throw new Error(`Unsupported language '${o.language}'. Supported languages: ${Cc.join(", ")}. Open a feature request for additional language support.`);let n;if(o.framework){n=o.framework;let i=Object.hasOwn(Dr,n)?Dr[n]:void 0;if(i&&i!==t){let s=a=>a==="javascript"||a==="typescript";if(!(s(i)&&s(t)))throw new Error(`Framework '${n}' targets ${i}, but language was '${t}'. Either pick a matching framework or omit \`framework\` to use the default (${rn[t]}).`)}}else n=rn[t];let r=nn(o.behaviorExamples);return{sourceCode:o.sourceCode,behaviorExamples:r,filePath:o.filePath,language:t,framework:n,testType:o.testType||"unit",coverageGoal:o.coverageGoal||80,aiEnhancement:o.aiEnhancement!==!1,detectAntiPatterns:o.detectAntiPatterns||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(o,e,t,n,r)=>{let i=r?.sourceCode||"",s=r?.language||"typescript",a=r?.testType||"unit",c=e.testsGenerated||6,l=dc(i),d=r?.aiEnhancement!==!1?mc(l,a):{recommendations:[],estimatedTime:"0 minutes",confidence:0},u=r?.detectAntiPatterns?gc(i,s):[],m=Di("test-generator"),p=e.tests,g=Array.isArray(p)&&p.length>0&&p[0].testCode,f=e.llmEnhanced===!0,h=g?p.map((v,y)=>({id:tt(),name:v.name||`test_${y}`,type:v.type||a,parameters:[],assertions:v.testCode?rm(v.testCode):[`test assertion ${y}`],expectedResult:null,estimatedDuration:v.type==="integration"?2e3:1e3,aiGenerated:f,testCode:v.testCode,generationMode:v.generationMode,generationLimits:v.generationLimits,sourceFile:v.sourceFile,testFile:v.testFile||v.file})):pc(i,a,s,c);return{tests:h,antiPatterns:u,suggestions:u.map(v=>`Fix: ${v.type} - ${v.suggestion}`),aiInsights:d,coverage:{predicted:e.coverageEstimate??null,confidence:e.coverageEstimate==null?0:f?.9:0,achievable:e.coverageEstimate==null?null:!0},properties:h.filter(v=>v.type==="property").map(v=>({name:v.name,invariant:"output_matches_expectation"})),language:s,complexity:l,learning:m,taskId:o,status:"completed",testsGenerated:h.length,coverageEstimate:e.coverageEstimate??null,patternsUsed:e.patternsUsed||["assertion-patterns","mock-generation","edge-case-detection"],duration:t,...Hn(r?.saveResults!==!1,n),llmEnhanced:f,...e.generationMode?{generationMode:e.generationMode}:{},...e.note?{note:e.note}:{}}}},Tc={domain:"test-execution",taskType:"execute-tests",priority:"p1",defaultTimeout:3e5,buildTaskDescription:o=>`Execute ${o.testFiles?.length||0} test files with ${o.parallel!==!1?"parallel":"sequential"} execution`,mapToPayload:(o,e)=>({testFiles:o.testFiles||[],testSuites:o.testSuites||[],parallel:o.parallel!==!1,parallelism:o.parallelism||4,retryCount:o.retryCount??2,timeout:o.timeout||6e4,collectCoverage:o.collectCoverage||!1,reportFormat:o.reportFormat||"json",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext,...o.projectRoot!==void 0?{projectRoot:o.projectRoot}:{}}),calculateTimeout:o=>o.timeout||3e5,mapToResult:(o,e,t,n)=>{let r=e.total||0,i=e.passed||0,s=e.failed||0,a=typeof e.flaky=="number"&&e.flaky>0?e.flaky:void 0,c=typeof e.coverage=="number"&&Number.isFinite(e.coverage)?e.coverage:null,l=[],d={},u=(T,S)=>{l.push(T),d[T]=S},m=Array.isArray(e.testCases)?e.testCases:void 0,p=m?.map(T=>({id:tt(),...T}));p||u("results","The test runner report did not list every test case, so per-test results are omitted.");let g=(m??[]).map(T=>T.duration).filter(T=>typeof T=="number"&&Number.isFinite(T)),f=g.length>0?g.reduce((T,S)=>T+S,0)/g.length:void 0;if(f===void 0){let T="The runner reported no per-test durations; the task wall time is in `duration`.";u("workerStats.avgExecutionTime",T),u("summary.avgDuration",T)}let h=f!==void 0?{avgExecutionTime:f}:{},v="No worker tasks were recorded by the metrics collector for this process.",y=It.getWorkersUsed();y>0?h.workersUsed=y:u("workerStats.workersUsed",v);let C=It.getWorkerEfficiency();C!==null?h.efficiency=C:u("workerStats.efficiency",v);let b=It.getLoadBalanceScore();b!==null?h.loadBalance=b:u("workerStats.loadBalance",v);let E;return e.retries&&typeof e.retries=="object"?E={...e.retries}:u("retryStats","The run reported no retry outcome: no retries were requested, or the retry step failed."),{workerStats:h,...E?{retryStats:E}:{},...p?{results:p}:{},summary:{totalTests:r,passRate:r>0?i/r*100:0,...a!==void 0?{flaky:a}:{},...f!==void 0?{avgDuration:f}:{},...C!==null?{parallelEfficiency:C}:{}},...l.length>0?{unmeasured:l,unmeasuredReasons:d}:{},taskId:o,status:"completed",total:r,passed:i,failed:s,...a!==void 0?{flaky:a}:{},duration:t,coverage:c,savedFiles:n}}},Ec={domain:"coverage-analysis",taskType:"analyze-coverage",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Analyze coverage for ${o.target||"project"} with gap detection`,mapToPayload:(o,e)=>({target:o.target||".",includeRisk:o.includeRisk||!1,detectGaps:o.detectGaps!==!1,mlPowered:o.mlPowered||!1,prioritization:o.prioritization||"complexity",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>{let r=e.summary,i=r?.files??e.totalFiles??0,s=e.gaps||[],a=e.branchDataCollected===!0,c=e.functionDataCollected===!0,l=a?r?.branch??e.branchCoverage??null:null,d=c?r?.function??e.functionCoverage??null:null,u=e.estimated===!0,m=e.measured===!0,g=r?.line??e.lineCoverage??null,f=r?.statement??e.statementCoverage,h=f===void 0?g:f,v=Di("coverage-analyzer"),y=s.map((E,T)=>{let S=E;return S?.file?{id:`gap-${Date.now()}-${T}`,file:S.file,line:S.lines?.[0]||0,uncoveredLines:S.lines||[],type:S.type||"uncovered-line",severity:S.severity||"medium",reason:S.reason||"Missing test case",priority:S.priority||"medium",suggestion:S.suggestedTest||"Add test coverage",suggestedTest:S.suggestedTest||"Add test coverage",riskScore:S.riskScore||.5,confidence:S.confidence??(m?.7:.2),estimated:S.estimated===!0||u}:null}).filter(E=>E!==null),C=e.coverageByFile;return{coverageByFile:C?C.map(E=>({file:E.file,lineCoverage:E.lineCoverage||0,branchCoverage:E.branchCoverage??null,functionCoverage:E.functionCoverage??null})):[],gapAnalysis:{totalGaps:y.length,highPriority:y.filter(E=>E.priority==="high").length,gaps:y},trends:{lineCoverageTrend:i>0?"stable":"no-data",branchCoverageTrend:i>0?"stable":"no-data",weeklyChange:0},aiInsights:i>0?{recommendations:u?["ESTIMATED RESULT \u2014 no instrumentation ran. The figures below are a static guess from source shape, not measured coverage. Do not act on individual gaps without running real instrumentation first.",...e.recommendations||[]]:e.recommendations||["Run tests with coverage enabled to get accurate metrics"],riskAssessment:u||!m||g===null?"unknown":g<70?"high":g<85?"medium":"low",confidence:u?.2:m?.88:0}:{recommendations:["No coverage data found. Run tests with coverage first (e.g., npm test -- --coverage, or pytest --cov)"],riskAssessment:"unknown",confidence:0},learning:v,taskId:o,status:"completed",lineCoverage:g,branchCoverage:l,functionCoverage:d,statementCoverage:h,totalFiles:i,gaps:y,duration:t,savedFiles:n,estimated:u,measured:m,coverageMethod:e.coverageMethod??"unknown",branchDataCollected:a,functionDataCollected:c,...e.runStatus==="passed"||e.runStatus==="failed"?{runStatus:e.runStatus}:{},...e.unmeasured===!0?{unmeasured:!0}:{},...e.evidenceStatus==="complete"||e.evidenceStatus==="insufficient-evidence"?{evidenceStatus:e.evidenceStatus}:{},...Array.isArray(e.unmeasuredFiles)?{unmeasuredFiles:e.unmeasuredFiles}:{},...e.staleReport?{staleReport:e.staleReport}:{},...e.warning?{warning:e.warning}:{}}}},wc={domain:"quality-assessment",taskType:"assess-quality",priority:"p0",defaultTimeout:18e4,buildTaskDescription:o=>`Assess quality with ${o.runGate?"quality gate":"metrics analysis"}`,mapToPayload:(o,e)=>{if(o.runGate!==void 0&&typeof o.runGate!="boolean")throw new Error("runGate must be a boolean.");let t=o.metrics===void 0?["coverage","complexity","maintainability"]:un(o.metrics);if(o.target!==void 0&&(typeof o.target!="string"||o.target.trim()===""))throw new le("target must be a non-empty string path.");if(o.sourceFiles!==void 0&&(!Array.isArray(o.sourceFiles)||o.sourceFiles.length===0||o.sourceFiles.some(n=>typeof n!="string"||n.trim()==="")))throw new le("sourceFiles must be a non-empty array of file paths.");return{runGate:o.runGate??!1,...o.target!==void 0?{target:o.target}:{},...o.sourceFiles!==void 0?{sourceFiles:o.sourceFiles}:{},threshold:o.threshold||80,thresholdSource:o.threshold===void 0?"default":"request",metrics:t,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(o,e,t,n)=>{let r=Array.isArray(e.unmeasured)?e.unmeasured.filter(g=>typeof g=="string"):void 0,i=(r?.length??0)>0||e.evidenceStatus===He,s=typeof e.gateEvaluated=="boolean"?e.gateEvaluated:void 0,a=typeof e.confidence=="number"?e.confidence:void 0,c=Array.isArray(e.measuredFailures)?e.measuredFailures:void 0,l=(c??[]).map(g=>g.metric),d=e.unmeasuredReasons&&typeof e.unmeasuredReasons=="object"&&Object.values(e.unmeasuredReasons).every(g=>typeof g=="string")?e.unmeasuredReasons:void 0,u=typeof e.qualityScore=="number"&&e.qualityScore>=0?e.qualityScore:void 0,m=!i&&l.length===0&&e.passed===!0,p=bc({passed:i||l.length>0?!1:typeof e.passed=="boolean"?e.passed:void 0,qualityScore:i?void 0:u,recommendations:e.recommendations||[],unmeasured:i?r?.length?r:["unknown"]:[],failedMetrics:l,evidenceConfidence:a,gateEvaluated:s});return{taskId:o,status:i?He:"completed",...typeof e.qualityScore=="number"?{qualityScore:i&&!Array.isArray(e.checks)?-1:e.qualityScore}:{},...typeof e.qualityScoreReason=="string"?{qualityScoreReason:e.qualityScoreReason}:{},...typeof e.subsetScore=="number"?{subsetScore:e.subsetScore}:i&&u!==void 0&&!Array.isArray(e.checks)?{subsetScore:u}:{},...Array.isArray(e.checks)?{checks:e.checks}:{},passed:m,metrics:e.metrics||{},recommendations:e.recommendations||[],...e.evidenceStatus==="measured"||i?{evidenceStatus:i?He:"measured"}:{},...r?{unmeasured:r}:{},...d?{unmeasuredReasons:d}:{},...Array.isArray(e.partialMetrics)?{partialMetrics:e.partialMetrics}:{},...Array.isArray(e.excludedFiles)?{excludedFiles:e.excludedFiles}:{},...typeof e.excludedCount=="number"?{excludedCount:e.excludedCount}:{},...typeof e.scope=="string"?{scope:e.scope}:{},...Array.isArray(e.scoreBasis)&&e.scoreBasis.every(g=>typeof g=="string")?{scoreBasis:e.scoreBasis}:{},...c?{measuredFailures:c}:{},...s!==void 0?{gateEvaluated:s}:{},...a!==void 0?{confidence:a}:{},...typeof e.note=="string"?{note:e.note}:{},duration:t,savedFiles:n,...vc(p).valid?{riskDecision:p}:{}}}},Rc={domain:"security-compliance",taskType:"scan-security",priority:"p0",defaultTimeout:6e5,buildTaskDescription:o=>{let e=[];return o.sast!==!1&&e.push("SAST"),o.dast&&e.push("DAST"),o.dependencies&&e.push("dependency advisories"),`Security scan (${e.join(", ")}) for ${o.target||"project"}`},mapToPayload:(o,e)=>{for(let t of["sast","dast","dependencies"])if(o[t]!==void 0&&typeof o[t]!="boolean")throw new Error(`${t} must be a boolean`);return{sast:o.sast!==!1,dast:o.dast||!1,dependencies:o.dependencies===!0,compliance:o.compliance||[],target:o.target||".",targetUrl:o.targetUrl,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(o,e,t,n)=>({taskId:o,status:e.evidence?.completeness==="complete"?"completed":e.evidence?.completeness==="partial"?"partial":e.evidence?"unavailable":"unverified",vulnerabilities:e.vulnerabilities||0,critical:e.critical||0,high:e.high||0,medium:e.medium||0,low:e.low||0,informational:e.informational||0,topVulnerabilities:e.topVulnerabilities||[],findings:e.findings,recommendations:e.recommendations||[],evidence:e.evidence,limitations:e.limitations||["Execution receipts unavailable; scan completeness is unverified."],...e.evidence?{filesScanned:e.filesScanned,jstsFilesScanned:e.jstsFilesScanned,otherFilesScanned:e.otherFilesScanned,coverage:e.coverage}:{},deepAnalysisPerformed:!!(e.evidence&&e.deepAnalysisPerformed===!0),analysisDepth:e.analysisDepth,scanTypes:e.scanTypes,...e.dependencyScan?{dependencyScan:e.dependencyScan}:{},note:e.note,duration:t,savedFiles:n})},Pc={domain:"contract-testing",taskType:"validate-contracts",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Validate API contract at ${o.contractPath}`,mapToPayload:(o,e)=>({contractPath:o.contractPath,providerUrl:o.providerUrl,consumerName:o.consumerName,checkBreakingChanges:o.checkBreakingChanges!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",valid:e.valid||!1,breakingChanges:e.breakingChanges||[],warnings:e.warnings||[],duration:t,savedFiles:n})},xc={domain:"visual-accessibility",taskType:"test-accessibility",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Test accessibility for ${o.url} against ${o.standard||"WCAG 2.1 AA"} standard`,mapToPayload:(o,e)=>({url:o.url,standard:o.standard||"wcag21-aa",includeScreenReader:o.includeScreenReader||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:e.measured===!0?"completed":"not-measured",passed:e.passed||!1,score:e.measured===!0&&typeof e.score=="number"?e.score:-1,violations:e.violations||[],warnings:e.warnings||[],measured:e.measured===!0,...typeof e.note=="string"?{note:e.note}:{},duration:t,savedFiles:n})},Ac={domain:"chaos-resilience",taskType:"run-chaos",priority:"p2",defaultTimeout:9e4,buildTaskDescription:o=>`Run chaos test with ${o.faultType||"latency"} fault injection on ${o.target}`,mapToPayload:(o,e)=>({faultType:o.faultType||"latency",target:o.target,duration:o.duration||3e4,intensity:o.intensity||50,dryRun:o.dryRun!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:o=>(o.duration||3e4)+6e4,mapToResult:(o,e,t,n)=>{let r=e.resilience??null,i=e.systemBehavior!=="not-executed"&&r!==null;return{taskId:o,status:i?"completed":"not-executed",faultType:e.faultType||"latency",resilience:i?r:null,...typeof e.note=="string"?{note:e.note}:{},duration:t,savedFiles:n}}},kc={domain:"defect-intelligence",taskType:"predict-defects",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Predict defects in ${o.target||"codebase"} with ${o.lookback||30} day lookback`,mapToPayload:(o,e)=>({target:o.target||".",lookback:o.lookback||30,minConfidence:o.minConfidence||.7,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",...e.predictionMethod==="static-code-indicators"?{predictionMethod:"static-code-indicators",estimated:!0,filesAnalyzed:e.filesAnalyzed,filesSkipped:e.filesSkipped,scanStatus:e.scanStatus}:{},predictedDefects:e.predictedDefects||[],riskScore:e.riskScore||0,recommendations:e.recommendations||[],duration:t,savedFiles:n})},Mc={domain:"requirements-validation",taskType:"validate-requirements",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Validate requirements${o.generateBDD?" and generate BDD scenarios":""}`,mapToPayload:(o,e)=>({requirementsPath:o.requirementsPath,testPath:o.testPath,generateBDD:o.generateBDD||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",requirementsAnalyzed:e.requirementsAnalyzed||0,testable:e.testable||0,coverage:e.coverage||0,bddScenarios:e.bddScenarios||[],duration:t,savedFiles:n})},Ic={domain:"code-intelligence",taskType:"index-code",priority:"p2",defaultTimeout:3e5,buildTaskDescription:o=>`Index code in ${o.target||"codebase"}${o.incremental?" incrementally":""}`,mapToPayload:(o,e)=>({target:o.target||".",incremental:o.incremental||!1,gitSince:o.gitSince,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",filesIndexed:e.filesIndexed||0,symbolsExtracted:e.symbolsExtracted||0,relationsFound:e.relationsFound||0,...e.projectMetrics?{projectMetrics:e.projectMetrics}:{},...Array.isArray(e.warnings)&&e.warnings.length>0?{warnings:e.warnings}:{},...Array.isArray(e.skipped)&&e.skipped.length>0?{skipped:e.skipped}:{},duration:t,savedFiles:n})};function rm(o){let e=[],t=o.split(`
465
- `);for(let n of t){let r=n.trim(),i=r.match(/expect\((.+?)\)\.(to\w+)\((.+?)\)/);if(i){e.push(`expect(${i[1]}).${i[2]}(${i[3]})`);continue}let s=r.match(/assert\w*\((.+)\)/);if(s){e.push(s[0]);continue}let a=r.match(/(?:it|test)\s*\(\s*['"`](.+?)['"`]/);a&&e.push(a[1])}return e.length>0?e:["test generated from source analysis"]}function Dc(){fc()}var wC=re(Sc),RC=re(Tc),PC=re(Ec),xC=re(wc),AC=re(Rc),kC=re(Pc),MC=re(xc),IC=re(Ac),DC=re(kc),_C=re(Mc),OC=re(Ic);D();var Wn=class extends A{config={name:"qe/tests/generate",description:"Generate tests for source code files. Supports unit, integration, and e2e tests with AI-powered pattern recognition.",domain:"test-generation",schema:im,streaming:!0,timeout:12e4};testGeneratorService=null;async getService(e){if(!this.testGeneratorService){let t=await q(),n=await V(e);this.testGeneratorService=Ls({memory:t,llmRouter:n},{defaultFramework:"vitest",maxTestsPerFile:50,coverageTargetDefault:80,enableAIGeneration:!0})}return this.testGeneratorService}async execute(e,t){let{sourceFiles:n,testType:r="unit",framework:i="vitest",language:s="typescript",coverageTarget:a=80,patterns:c=[],aiEnhancement:l=!0,detectAntiPatterns:d=!1}=e;try{let u=nn(e.behaviorExamples);if(this.emitStream(t,{status:"analyzing",message:`Analyzing ${n.length} source files`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};if(jr.isEnabled()){let y=`Generate ${r} tests for ${n.length} files using ${i}`,C=await jr.checkTaskEarlyExit(y,"test-generation");C.canExit&&C.reusedPattern&&(this.emitStream(t,{status:"pattern-reuse",message:`Reusing pattern: ${C.reusedPattern.name}`,tokensSaved:C.estimatedTokensSaved}),console.log(`[TestGenerateTool] Early exit: reusing pattern ${C.reusedPattern.name}, saving ~${C.estimatedTokensSaved} tokens`))}let m=await this.getService(t),p={behaviorExamples:u,sourceFiles:n,testType:r,framework:i,coverageTarget:a,patterns:c},g=await m.generateTests(p);if(!g.success)return{success:!1,error:g.error?.message||"Test generation failed"};let f=g.value,h=f.tests.map(y=>({id:y.id,name:y.name,sourceFile:y.sourceFile,testFile:y.testFile,testCode:y.testCode,type:y.type,assertions:y.assertions,generationMode:y.generationMode,generationLimits:y.generationLimits}));this.emitStream(t,{status:"generating",message:`Generated ${h.length} test files`,progress:50});let v=d?sm(n):[];return this.emitStream(t,{status:"complete",message:"Test generation complete",progress:100}),{success:!0,data:{tests:h,coverageEstimate:f.coverageEstimate,patternsUsed:f.patternsUsed,suggestions:cm(h,l),antiPatterns:v.length>0?v:void 0}}}catch(u){return{success:!1,error:`Test generation failed: ${w(u)}`}}}resetInstanceCache(){this.testGeneratorService=null}},im={type:"object",properties:{behaviorExamples:{type:"array",description:"Trusted JSON specification fixtures: functionName, args, expected",items:Fs},sourceFiles:{type:"array",description:"Array of source file paths to generate tests for",items:{type:"string",description:"File path"}},testType:{type:"string",description:"Type of tests to generate",enum:["unit","integration","e2e"],default:"unit"},framework:{type:"string",description:"Test framework to use",enum:["jest","vitest","mocha","pytest"],default:"vitest"},language:{type:"string",description:"Programming language of source files",enum:["typescript","javascript","python","java","go"],default:"typescript"},coverageTarget:{type:"number",description:"Target code coverage percentage (0-100)",minimum:0,maximum:100,default:80},patterns:{type:"array",description:"Test patterns to apply",items:{type:"string",description:"Pattern name"}},aiEnhancement:{type:"boolean",description:"Enable AI-powered test enhancement",default:!0},detectAntiPatterns:{type:"boolean",description:"Detect and report anti-patterns in source code",default:!1}},required:["sourceFiles"]};function sm(o){let e=[],t=vl("fs");for(let n of o)try{let r;try{r=t.readFileSync(n,"utf-8")}catch{continue}let i=r.split(`
466
- `),s=/(?<![\w.])(\d{2,}|[2-9]\d*)(?![\w.])/g,a=new Set(["10","100","1000","60","24","365","404","500","200","201"]);i.forEach((g,f)=>{if(g.trim().startsWith("//")||g.trim().startsWith("*")||g.includes("import")||g.includes("require"))return;let h=g.match(s);if(h)for(let v of h){if(a.has(v))continue;let y=g.substring(0,g.indexOf(v)),C=(y.match(/'/g)||[]).length,b=(y.match(/"/g)||[]).length,E=(y.match(/`/g)||[]).length;if(!(C%2===1||b%2===1||E%2===1)){e.push({name:"magic-number",location:`${n}:${f+1}`,severity:"medium",suggestion:`Consider extracting ${v} into a named constant to improve readability and maintainability`});break}}});let c=/(?:it|test)\s*\(\s*['"`]([^'"`]+)['"`]\s*,/g,l;for(;(l=c.exec(r))!==null;){let g=l.index,f=l[1],h=r.substring(g),v=am(h);if(v){let y=/expect\s*\(/.test(v),C=/assert[\.\(]/.test(v),b=/\.should[\.\(]/.test(v),E=/\.toBe|\.toEqual|\.toMatch|\.toThrow|\.toContain/.test(v);if(!y&&!C&&!b&&!E){let T=r.substring(0,g).split(`
467
- `).length;e.push({name:"no-assertions",location:`${n}:${T}`,severity:"high",suggestion:`Test "${f}" has no assertions. Add expect() or assert() calls to verify behavior`})}}}let d=[{pattern:/let\s+\w+\s*=\s*(?!undefined|null)/g,name:"mutable-let-declaration"},{pattern:/(?:^|\s)var\s+\w+\s*=/g,name:"mutable-var-declaration"}],u=r.match(/describe\s*\([^)]+,\s*(?:function\s*\(\)|(?:\(\s*\))?\s*=>)\s*\{/g);if(u)for(let g of u){let f=r.indexOf(g),h=om(r.substring(f));if(h){let v=h.match(/^\s*let\s+(\w+)\s*(?::\s*\w+)?\s*(?:=|;)/m);if(v){let y=v[1];if((h.match(new RegExp(`(?:it|test)\\s*\\([^)]+,[^]*?${y}\\s*=`,"g"))||[]).length>=2){let b=r.substring(0,f+h.indexOf(v[0])).split(`
468
- `).length;e.push({name:"test-interdependence",location:`${n}:${b}`,severity:"high",suggestion:`Shared mutable variable '${y}' is modified in multiple tests, causing test interdependence. Use beforeEach to reset state or isolate test data`})}}}}if(/\.test\.|\.spec\./.test(n)){let g=r.match(/import\s+.*from\s+['"].*(?:\.test|\.spec)['"]/g);g&&g.length>0&&e.push({name:"test-importing-tests",location:n,severity:"medium",suggestion:"Test file imports from another test file. Extract shared test utilities to a separate module"})}let m=/(?:it|test|describe)\s*\(\s*['"`]([^'"`]{100,})['"`]/g,p;for(;(p=m.exec(r))!==null;){let g=r.substring(0,p.index).split(`
469
- `).length;e.push({name:"long-test-description",location:`${n}:${g}`,severity:"low",suggestion:"Test description is too long. Consider breaking into smaller, focused tests or using a more concise description"})}if(/setTimeout|setInterval/.test(r)&&!/useFakeTimers|fakeTimers|clock/.test(r)){let f=r.match(/setTimeout|setInterval/);if(f){let h=r.substring(0,r.indexOf(f[0])).split(`
470
- `).length;e.push({name:"real-timers-in-tests",location:`${n}:${h}`,severity:"medium",suggestion:"Using real timers in tests can cause flakiness. Consider using fake timers (jest.useFakeTimers() or vi.useFakeTimers())"})}}}catch{continue}return e}function am(o){let e=0,t=-1,n=-1;for(let r=0;r<o.length;r++)if(o[r]==="{")t===-1&&(t=r),e++;else if(o[r]==="}"&&(e--,e===0&&t!==-1)){n=r;break}return t!==-1&&n!==-1?o.substring(t+1,n):null}function om(o){let e=0,t=-1,n=-1;for(let r=0;r<o.length;r++)if(o[r]==="{")t===-1&&(t=r),e++;else if(o[r]==="}"&&(e--,e===0&&t!==-1)){n=r;break}return t!==-1&&n!==-1?o.substring(t+1,n):null}function cm(o,e){let t=[];return o.length===0&&t.push("No tests generated. Ensure source files are valid."),e&&(t.push("Consider adding property-based tests for edge case coverage"),t.push("Parameterized tests can reduce duplication")),t}D();tn();var Kn=class extends A{config={name:"qe/tests/execute",description:"Execute test suites with parallel execution, retry logic, and coverage collection. Detects flaky tests.",domain:"test-execution",schema:lm,streaming:!0,timeout:3e5};async execute(e,t){let{testFiles:n=[],testSuites:r=[],pattern:i,parallel:s=!0,parallelism:a=4,retryCount:c=2,collectCoverage:l=!1,failFast:d=!1}=e,u=Date.now();try{let m=n.length>0?n:r.length>0?r:i?[i]:["**/*.test.ts"];if(this.emitStream(t,{status:"starting",message:`Executing ${m.length} test files`,parallel:s,parallelism:a}),this.isAborted(t))return{success:!1,error:"Test execution aborted"};let p=[],g=[];for(let y=0;y<m.length;y++){let C=m[y];this.emitStream(t,{status:"running",message:`Executing ${C}`,progress:Math.round(y/m.length*100)});let b=be()>.1,E={id:`test-${y}`,name:`Test suite for ${C.split("/").pop()}`,file:C,status:b?"passed":"failed",duration:be()*5e3,error:b?void 0:"Assertion failed",retries:b?0:Math.min(c,2)};if(p.push(E),!b&&be()>.7&&g.push({name:E.name,file:E.file,flakinessScore:Ie(.5,1),failurePattern:"intermittent-timeout"}),d&&!b)break}let f={total:p.length,passed:p.filter(y=>y.status==="passed").length,failed:p.filter(y=>y.status==="failed").length,skipped:p.filter(y=>y.status==="skipped").length,pending:p.filter(y=>y.status==="pending").length,passRate:0};f.passRate=f.total>0?Math.round(f.passed/f.total*100):0;let h=l?{lines:Ie(70,100),branches:Ie(60,80),functions:Ie(65,90),statements:Ie(70,95)}:void 0,v=Date.now()-u;return this.emitStream(t,{status:"complete",message:`Test execution complete: ${f.passed}/${f.total} passed`,progress:100}),{success:f.failed===0,data:{summary:f,testResults:p,coverage:h,flakyTests:g.length>0?g:void 0,duration:v}}}catch(m){return{success:!1,error:`Test execution failed: ${w(m)}`}}}},lm={type:"object",properties:{testFiles:{type:"array",description:"Specific test files to execute",items:{type:"string",description:"Test file path"}},testSuites:{type:"array",description:"Test suite names to execute",items:{type:"string",description:"Suite name"}},pattern:{type:"string",description:"Glob pattern to match test files"},parallel:{type:"boolean",description:"Enable parallel test execution",default:!0},parallelism:{type:"number",description:"Number of parallel workers",minimum:1,maximum:16,default:4},retryCount:{type:"number",description:"Number of retries for failed tests",minimum:0,maximum:5,default:2},timeout:{type:"number",description:"Test timeout in milliseconds",minimum:1e3,default:6e4},collectCoverage:{type:"boolean",description:"Collect code coverage",default:!1},reportFormat:{type:"string",description:"Report output format",enum:["json","junit","html","markdown"],default:"json"},failFast:{type:"boolean",description:"Stop on first failure",default:!1},watch:{type:"boolean",description:"Watch mode for continuous testing",default:!1}}};ee();import*as Gc from"fs/promises";import*as _ from"path";function fe(o){return ue(o,{outsideRoot:"allow"})}async function $i(o,e){let t=await fe(o);return jc(t,e||_.dirname(o))}function jc(o,e){let t=new Map,n=o.split(`
471
- `),r=null,i=new Map,s=[],a=[],c=0,l=0,d=0,u=0,m=0,p=0;for(let g of n){let f=g.trim();if(f.startsWith("SF:")){let h=f.slice(3);r={path:h,relativePath:_.relative(e,h)},i=new Map,s=[],a=[],c=0,l=0,d=0,u=0,m=0,p=0}else if(f.startsWith("DA:")){let[h,v]=f.slice(3).split(",").map(Number);!isNaN(h)&&!isNaN(v)&&(i.set(h,v),c++,v>0&&l++)}else if(f.startsWith("LF:")){let h=parseInt(f.slice(3),10);isNaN(h)||(c=h)}else if(f.startsWith("LH:")){let h=parseInt(f.slice(3),10);isNaN(h)||(l=h)}else if(f.startsWith("BRDA:")){let h=f.slice(5).split(",");if(h.length>=4){let v=parseInt(h[0],10),y=parseInt(h[1],10),C=parseInt(h[2],10),b=h[3]==="-"?0:parseInt(h[3],10);s.push({line:v,block:y,branch:C,taken:b>0,hits:b}),d++,b>0&&u++}}else if(f.startsWith("BRF:")){let h=parseInt(f.slice(4),10);isNaN(h)||(d=h)}else if(f.startsWith("BRH:")){let h=parseInt(f.slice(4),10);isNaN(h)||(u=h)}else if(f.startsWith("FN:")){let h=f.indexOf(",",3);if(h>0){let v=parseInt(f.slice(3,h),10),y=f.slice(h+1);a.find(b=>b.name===y)||a.push({name:y,line:v,hits:0})}}else if(f.startsWith("FNDA:")){let h=f.indexOf(",",5);if(h>0){let v=parseInt(f.slice(5,h),10),y=f.slice(h+1),C=a.find(b=>b.name===y);C?C.hits=v:a.push({name:y,line:0,hits:v}),m++,v>0&&p++}}else if(f.startsWith("FNF:")){let h=parseInt(f.slice(4),10);isNaN(h)||(m=h)}else if(f.startsWith("FNH:")){let h=parseInt(f.slice(4),10);isNaN(h)||(p=h)}else if(f==="end_of_record"&&r?.path){let h=Array.from(i.entries()).filter(([,b])=>b===0).map(([b])=>b).sort((b,E)=>b-E),v=s.filter(b=>!b.taken),y=a.filter(b=>b.hits===0).map(b=>b.name),C={path:r.path,relativePath:r.relativePath||r.path,lines:{total:c,covered:l,percentage:c>0?l/c*100:0,details:i,uncoveredLines:h},branches:{total:d,covered:u,percentage:d>0?u/d*100:0,uncoveredBranches:v},functions:{total:m,covered:p,percentage:m>0?p/m*100:0,details:a,uncoveredFunctions:y},statements:{total:c,covered:l,percentage:c>0?l/c*100:0},coveragePercentage:zi(l,c,u,d)};t.set(r.path,C),r=null}}return{timestamp:new Date,format:"lcov",files:t,summary:Oe(t)}}async function Gi(o,e){let t=await fe(o),n=I(t),r=e||_.dirname(o),i=new Map;for(let[s,a]of Object.entries(n)){if(typeof a!="object"||!a.statementMap)continue;let c=new Map,l=[],d=0,u=0;for(let[b,E]of Object.entries(a.s||{})){let T=a.statementMap[b];if(T?.start?.line){let S=T.start.line,x=c.get(S)||0;c.set(S,x+E)}d++,E>0&&u++}for(let[b,E]of c.entries())E===0&&l.push(b);let m=[],p=0,g=0;for(let[b,E]of Object.entries(a.branchMap||{})){let T=a.b?.[b]||[];for(let S=0;S<T.length;S++)m.push({line:E.loc?.start?.line||0,block:parseInt(b,10),branch:S,taken:T[S]>0,hits:T[S]}),p++,T[S]>0&&g++}let f=[],h=0,v=0;for(let[b,E]of Object.entries(a.fnMap||{})){let T=a.f?.[b]||0;f.push({name:E.name||`anonymous_${b}`,line:E.loc?.start?.line||E.decl?.start?.line||0,hits:T}),h++,T>0&&v++}let y=c.size,C=Array.from(c.values()).filter(b=>b>0).length;i.set(s,{path:s,relativePath:_.relative(r,s),lines:{total:y,covered:C,percentage:y>0?C/y*100:0,details:c,uncoveredLines:l.sort((b,E)=>b-E)},branches:{total:p,covered:g,percentage:p>0?g/p*100:0,uncoveredBranches:m.filter(b=>!b.taken)},functions:{total:h,covered:v,percentage:h>0?v/h*100:0,details:f,uncoveredFunctions:f.filter(b=>b.hits===0).map(b=>b.name)},statements:{total:d,covered:u,percentage:d>0?u/d*100:0},coveragePercentage:zi(C,y,g,p)})}return{timestamp:new Date,format:"json",files:i,summary:Oe(i)}}async function _c(o,e){let t=await fe(o);return Xn(t,e||_.dirname(o))}function Xn(o,e){let t=new Map,n=/<package\s+name="([^"]*)">([\s\S]*?)<\/package>/g,r;for(;(r=n.exec(o))!==null;){let i=r[1].replace(/\//g,_.sep),s=r[2],a=/<sourcefile\s+name="([^"]*)">([\s\S]*?)<\/sourcefile>/g,c;for(;(c=a.exec(s))!==null;){let l=c[1],d=c[2],u=_.join(e,i,l),m=um(d),p=new Map,g=/<line\s+nr="(\d+)"\s+mi="(\d+)"\s+ci="(\d+)"/g,f;for(;(f=g.exec(d))!==null;){let v=parseInt(f[1],10),y=parseInt(f[3],10);p.set(v,y)}let h=Array.from(p.entries()).filter(([,v])=>v===0).map(([v])=>v).sort((v,y)=>v-y);t.set(u,{path:u,relativePath:_.join(i,l),lines:{total:m.LINE.total,covered:m.LINE.covered,percentage:m.LINE.total>0?m.LINE.covered/m.LINE.total*100:0,details:p,uncoveredLines:h},branches:{total:m.BRANCH.total,covered:m.BRANCH.covered,percentage:m.BRANCH.total>0?m.BRANCH.covered/m.BRANCH.total*100:0,uncoveredBranches:[]},functions:{total:m.METHOD.total,covered:m.METHOD.covered,percentage:m.METHOD.total>0?m.METHOD.covered/m.METHOD.total*100:0,details:[],uncoveredFunctions:[]},statements:{total:m.INSTRUCTION.total,covered:m.INSTRUCTION.covered,percentage:m.INSTRUCTION.total>0?m.INSTRUCTION.covered/m.INSTRUCTION.total*100:0},coveragePercentage:zi(m.LINE.covered,m.LINE.total,m.BRANCH.covered,m.BRANCH.total)})}}return{timestamp:new Date,format:"jacoco",language:"java",files:t,summary:Oe(t)}}function um(o){let e={LINE:{covered:0,total:0},BRANCH:{covered:0,total:0},METHOD:{covered:0,total:0},INSTRUCTION:{covered:0,total:0}},t=/<counter\s+type="(\w+)"\s+missed="(\d+)"\s+covered="(\d+)"\s*\/>/g,n;for(;(n=t.exec(o))!==null;){let r=n[1],i=parseInt(n[2],10),s=parseInt(n[3],10);e[r]&&(e[r].covered+=s,e[r].total+=i+s)}return e}async function Oc(o,e){let t=await fe(o);return zc(t,e||_.dirname(o))}function zc(o,e){let t=new Map,n=new Map,r=/<File\s+Index="(\d+)"\s+Name="([^"]*)"\s*\/>/g,i;for(;(i=r.exec(o))!==null;)n.set(i[1],i[2]);let s=/<Statement\s+FileIndex="(\d+)"\s+Line="(\d+)"\s+Column="\d+"\s+EndLine="\d+"\s+EndColumn="\d+"\s+Covered="(\w+)"\s*\/>/g,a=new Map,c=new Map,l=0,d;for(;(d=s.exec(o))!==null;){l++;let m=d[1],p=parseInt(d[2],10),g=d[3]==="True",f=n.get(m);if(!f){c.set(m,(c.get(m)??0)+1);continue}a.has(f)||a.set(f,{lineDetails:new Map,total:0,covered:0});let h=a.get(f);h.lineDetails.set(p,g?1:0),h.total++,g&&h.covered++}let u=[];if(c.size>0){let m=[...c.values()].reduce((p,g)=>p+g,0);u.push(`dotCover report references FileIndex ${[...c.keys()].join(", ")} missing from its file table; ${m} statement(s) skipped and their coverage is not reported`)}if(l===0){let p=/CoveredStatements="(\d+)"\s+TotalStatements="(\d+)"/.exec(o);if(p){let g=parseInt(p[1],10),f=parseInt(p[2],10),h=_.join(e,"aggregate");u.push("dotCover report has no per-file statements; report totals are listed under 'aggregate', which is not a project file"),t.set(h,{path:h,relativePath:"aggregate",lines:{total:f,covered:g,percentage:f>0?g/f*100:0,details:new Map,uncoveredLines:[]},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:f,covered:g,percentage:f>0?g/f*100:0},coveragePercentage:f>0?g/f*100:0})}}for(let[m,p]of a.entries()){let g=Array.from(p.lineDetails.entries()).filter(([,f])=>f===0).map(([f])=>f).sort((f,h)=>f-h);t.set(m,{path:m,relativePath:_.relative(e,m),lines:{total:p.lineDetails.size,covered:Array.from(p.lineDetails.values()).filter(f=>f>0).length,percentage:p.lineDetails.size>0?Array.from(p.lineDetails.values()).filter(f=>f>0).length/p.lineDetails.size*100:0,details:p.lineDetails,uncoveredLines:g},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:p.total,covered:p.covered,percentage:p.total>0?p.covered/p.total*100:0},coveragePercentage:p.total>0?p.covered/p.total*100:0})}return{timestamp:new Date,format:"dotcover",language:"csharp",files:t,summary:Oe(t),...u.length>0?{warnings:u}:{}}}async function Nc(o,e){let t=await fe(o),n=e||_.dirname(o);if(t.includes("SF:")&&t.includes("end_of_record")){let r=jc(t,n);return r.format="tarpaulin",r.language="rust",r}return Uc(t,n)}function Uc(o,e){let t=new Map,n=I(o);for(let r of n?.files||[]){let i=r.path||"",s=new Map,a=0,c=0;for(let d of r.traces||[]){let u=d.line,m=d.stats?.Line??d.stats?.line??0;typeof u=="number"&&(s.set(u,m),a++,m>0&&c++)}let l=Array.from(s.entries()).filter(([,d])=>d===0).map(([d])=>d).sort((d,u)=>d-u);t.set(i,{path:i,relativePath:_.relative(e,i),lines:{total:a,covered:c,percentage:a>0?c/a*100:0,details:s,uncoveredLines:l},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:a,covered:c,percentage:a>0?c/a*100:0},coveragePercentage:a>0?c/a*100:0})}return{timestamp:new Date,format:"tarpaulin",language:"rust",files:t,summary:Oe(t)}}async function Fc(o,e){let t=await fe(o);return Bc(t,e||_.dirname(o))}function Bc(o,e){let t=new Map,n=new Map,r=o.split(`
472
- `);for(let i of r){let s=i.trim();if(!s||s.startsWith("mode:"))continue;let a=s.match(/^(.+):(\d+)\.\d+,(\d+)\.\d+\s+(\d+)\s+(\d+)$/);if(!a)continue;let c=a[1],l=parseInt(a[2],10),d=parseInt(a[3],10),u=parseInt(a[4],10),m=parseInt(a[5],10);n.has(c)||n.set(c,{lineDetails:new Map,stmtTotal:0,stmtCovered:0});let p=n.get(c);for(let g=l;g<=d;g++){let f=p.lineDetails.get(g)||0;p.lineDetails.set(g,f+m)}p.stmtTotal+=u,m>0&&(p.stmtCovered+=u)}for(let[i,s]of n.entries()){let a=s.lineDetails.size,c=Array.from(s.lineDetails.values()).filter(d=>d>0).length,l=Array.from(s.lineDetails.entries()).filter(([,d])=>d===0).map(([d])=>d).sort((d,u)=>d-u);t.set(i,{path:i,relativePath:_.relative(e,i),lines:{total:a,covered:c,percentage:a>0?c/a*100:0,details:s.lineDetails,uncoveredLines:l},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:s.stmtTotal,covered:s.stmtCovered,percentage:s.stmtTotal>0?s.stmtCovered/s.stmtTotal*100:0},coveragePercentage:s.stmtTotal>0?s.stmtCovered/s.stmtTotal*100:0})}return{timestamp:new Date,format:"gocover",language:"go",files:t,summary:Oe(t)}}async function Lc(o,e){let t=await fe(o),n=Xn(t,e||_.dirname(o));return n.format="kover",n.language="kotlin",n}async function qc(o,e){let t=await fe(o);return Hc(t,e||_.dirname(o))}function Hc(o,e){let t=new Map,r=I(o)?.targets||[];for(let i of r)for(let s of i.files||[]){let a=s.path||"",c=s.executableLines||0,l=s.coveredLines||0,d=s.lineCoverage||0,u=[],m=0,p=0;for(let g of s.functions||[]){let f=g.coveredLines>0?1:0;u.push({name:g.name||"unknown",line:g.lineNumber||0,hits:f}),m++,f>0&&p++}t.set(a,{path:a,relativePath:_.relative(e,a),lines:{total:c,covered:l,percentage:d*100,details:new Map,uncoveredLines:[]},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:m,covered:p,percentage:m>0?p/m*100:0,details:u,uncoveredFunctions:u.filter(g=>g.hits===0).map(g=>g.name)},statements:{total:c,covered:l,percentage:d*100},coveragePercentage:d*100})}return{timestamp:new Date,format:"xcresult",language:"swift",files:t,summary:Oe(t)}}var $c={java:["jacoco","cobertura","lcov"],kotlin:["kover","jacoco"],csharp:["dotcover","cobertura"],rust:["tarpaulin","lcov"],go:["gocover"],swift:["xcresult"],dart:["lcov"],typescript:["lcov","json"],javascript:["lcov","json"],python:["lcov","cobertura","json"]};async function Dt(o,e,t,n){if(t)switch(t){case"lcov":return $i(o,e);case"json":return Gi(o,e);case"jacoco":return _c(o,e);case"dotcover":return Oc(o,e);case"tarpaulin":return Nc(o,e);case"gocover":return Fc(o,e);case"kover":return Lc(o,e);case"xcresult":return qc(o,e);default:break}let r=_.extname(o).toLowerCase(),i=_.basename(o).toLowerCase();if(r===".json"||i.includes("coverage-final"))return Gi(o,e);if(i==="lcov.info"||r===".info"||i.includes("lcov"))return $i(o,e);if(i.includes("jacoco")&&r===".xml")return _c(o,e);if(i.includes("dotcover")&&r===".xml")return Oc(o,e);if(i.includes("tarpaulin"))return Nc(o,e);if(i.includes("kover")&&r===".xml")return Lc(o,e);if(i.includes("coverage")&&r===".out")return Fc(o,e);if(i.includes("xcresult")||i.includes("xccov"))return qc(o,e);let s=await fe(o),a=s.trim();if(a.startsWith("{"))return a.includes('"files"')&&a.includes('"traces"')?Uc(s,e||_.dirname(o)):a.includes('"targets"')&&a.includes('"lineCoverage"')?Hc(s,e||_.dirname(o)):Gi(o,e);if(s.includes("SF:")&&s.includes("end_of_record"))return $i(o,e);if(a.startsWith("mode:"))return Bc(s,e||_.dirname(o));if(a.startsWith("<?xml")||a.startsWith("<")){if(s.includes('<counter type="')||s.includes("<report ")){if(n==="kotlin"){let c=Xn(s,e||_.dirname(o));return c.format="kover",c.language="kotlin",c}return Xn(s,e||_.dirname(o))}if(s.includes("CoveredStatements=")||s.includes("<Root"))return zc(s,e||_.dirname(o))}if(n){let c=n.toLowerCase(),l=Object.hasOwn($c,c)?$c[c]:void 0;if(l&&l.length>0)try{return await Dt(o,e,l[0])}catch{}}throw new Error(`Unknown coverage format: ${o}`)}async function ji(o,e){let t=e||o,n=[_.join(o,"coverage","lcov.info"),_.join(o,"coverage","coverage-final.json"),_.join(o,"lcov.info"),_.join(o,".nyc_output","coverage.json"),_.join(o,"target","site","jacoco","jacoco.xml"),_.join(o,"build","reports","jacoco","test","jacocoTestReport.xml"),_.join(o,"dotcover-report.xml"),_.join(o,"tarpaulin-report.json"),_.join(o,"cobertura.xml"),_.join(o,"coverage.out"),_.join(o,"cover.out"),_.join(o,"build","reports","kover","report.xml"),_.join(o,"coverage.json")];for(let r of n)try{return await Gc.access(r),Dt(r,t)}catch{}return null}function zi(o,e,t,n){let r=e>0?o/e*100:0,i=n>0?t/n*100:0;return n===0?r:r*.7+i*.3}function Oe(o){let e=0,t=0,n=0,r=0,i=0,s=0,a=0,c=0;for(let l of o.values())e+=l.lines.total,t+=l.lines.covered,n+=l.branches.total,r+=l.branches.covered,i+=l.functions.total,s+=l.functions.covered,a+=l.statements.total,c+=l.statements.covered;return{totalFiles:o.size,lines:{total:e,covered:t,percentage:e>0?t/e*100:0},branches:{total:n,covered:r,percentage:n>0?r/n*100:0},functions:{total:i,covered:s,percentage:i>0?s/i*100:0},statements:{total:a,covered:c,percentage:a>0?c/a*100:0}}}D();async function Vc(o,e,t){let n=e;if(e!=="."){let i=await K(o,"target",e,{allowDirectory:!0,allowMissing:!0});if(!i.success)return{error:i.error.message};n=i.value}if(t===void 0)return{target:n};let r=await K(o,"coverageFile",t);return r.success?{target:n,coverageFile:r.value}:{error:r.error.message}}function Qc(o){return o?.warnings?.length?` ${o.warnings.join(". ")}.`:""}function Wc(o){let e=0,t=0,n=0,r=0,i=0,s=0,a=0,c=0;for(let l of o)e+=l.lines.total,t+=l.lines.covered,n+=l.branches.total,r+=l.branches.covered,i+=l.functions.total,s+=l.functions.covered,a+=l.statements.total,c+=l.statements.covered;return{line:e>0?t/e*100:0,branch:n>0?r/n*100:0,function:i>0?s/i*100:0,statement:a>0?c/a*100:0,files:o.length}}function Kc(o){let e=[];for(let[t,n]of o.files.entries())e.push({path:n.relativePath||t,lines:{covered:n.lines.covered,total:n.lines.total},branches:{covered:n.branches.covered,total:n.branches.total},functions:{covered:n.functions.covered,total:n.functions.total},statements:{covered:n.statements.covered,total:n.statements.total},uncoveredLines:n.lines.uncoveredLines,uncoveredBranches:n.branches.uncoveredBranches.map(r=>r.line)});return e}var Yn=class extends A{config={name:"qe/coverage/analyze",description:"Analyze code coverage using real LCOV/JSON parsing and compare against thresholds. Includes risk scoring and trend analysis.",domain:"coverage-analysis",schema:dm,streaming:!0,timeout:18e4};analyzerService=null;async getService(e){if(!this.analyzerService){let t=e.memory??await q(),n=await V(e);this.analyzerService=new na({memory:t,llmRouter:n})}return this.analyzerService}async execute(e,t){let{target:n=".",coverageFile:r,thresholds:i={lines:80,branches:70,functions:80,statements:80},includeRisk:s=!1,includeRiskScoring:a=!1,dryRun:c=!1,coverageFormat:l,language:d}=e,u=s||a,m=await Vc("qe/coverage/analyze",n,r);if("error"in m)return{success:!1,error:m.error};let{target:p,coverageFile:g}=m;try{if(this.emitStream(t,{status:"analyzing",message:`Analyzing coverage for ${p}`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};if(this.isDemoMode(t)||c)return this.markAsDemoData(t,"Demo mode explicitly requested"),this.getDemoResult(p,i,u,t);let f=null;if(g)try{f=await Dt(g,p,l,d)}catch(k){return{success:!1,error:`Failed to parse coverage file '${g}': ${w(k)}`}}else f=await ji(p);if(!f||f.files.size===0)return{success:!1,error:`No coverage data found in '${p}'. Run your test suite with coverage enabled (e.g., 'npm test -- --coverage') and ensure coverage reports are generated (lcov.info, coverage-final.json, etc.)${Qc(f)}`};this.markAsRealData();let h=Kc(f),y=await(await this.getService(t)).analyze({coverageData:{files:h,summary:Wc(h)},threshold:i.lines||80,includeFileDetails:!0,measured:!0});if(!y.success)return{success:!1,error:`Analysis failed: ${y.error?.message||"Unknown error"}`};let C=y.value,b={lines:{covered:f.summary.lines.covered,total:f.summary.lines.total,percentage:Math.round(f.summary.lines.percentage*100)/100},branches:{covered:f.summary.branches.covered,total:f.summary.branches.total,percentage:Math.round(f.summary.branches.percentage*100)/100},functions:{covered:f.summary.functions.covered,total:f.summary.functions.total,percentage:Math.round(f.summary.functions.percentage*100)/100},statements:{covered:f.summary.statements.covered,total:f.summary.statements.total,percentage:Math.round(f.summary.statements.percentage*100)/100}},E=h.map(k=>({file:k.path,lines:Math.round(k.lines.covered/(k.lines.total||1)*100),branches:Math.round(k.branches.covered/(k.branches.total||1)*100),functions:Math.round(k.functions.covered/(k.functions.total||1)*100),uncoveredLines:k.uncoveredLines.slice(0,20)})),T=b.lines.percentage>=(i.lines||0)&&b.branches.percentage>=(i.branches||0)&&b.functions.percentage>=(i.functions||0)&&b.statements.percentage>=(i.statements||0),S;if(u){let k=h.reduce((se,Xt)=>se+Xt.uncoveredLines.length,0),z=(b.lines.percentage+b.branches.percentage+b.functions.percentage)/3;S=Math.round((1-z/100+Math.min(k/1e3,.5))*100)/100}let x;C.delta&&(x={direction:C.delta.trend,delta:Math.round((C.delta.line+C.delta.branch+C.delta.function)/3*100)/100,history:[{date:new Date(Date.now()-10080*60*1e3).toISOString().split("T")[0],coverage:b.lines.percentage-(C.delta.line||0)},{date:new Date().toISOString().split("T")[0],coverage:b.lines.percentage}]}),this.emitStream(t,{status:"complete",message:`Coverage analysis complete: ${b.lines.percentage}% lines covered`,progress:100});let M=e.language||f.language,O=f.format;return{success:!0,data:{summary:b,byFile:E,thresholdsPassed:T,riskScore:S,trends:x,language:M,format:O,...f.warnings?{warnings:f.warnings}:{}}}}catch(f){return{success:!1,error:`Coverage analysis failed: ${w(f)}`}}}getDemoResult(e,t,n,r){let i={lines:{covered:850,total:1e3,percentage:85},branches:{covered:120,total:150,percentage:80},functions:{covered:90,total:100,percentage:90},statements:{covered:900,total:1050,percentage:85.71}},s=[{file:`${e}/service.ts`,lines:92,branches:85,functions:95,uncoveredLines:[45,67,89]},{file:`${e}/utils.ts`,lines:78,branches:70,functions:85,uncoveredLines:[12,34,56,78,90]},{file:`${e}/handler.ts`,lines:88,branches:82,functions:90,uncoveredLines:[23,45]}],a=i.lines.percentage>=(t.lines||0)&&i.branches.percentage>=(t.branches||0)&&i.functions.percentage>=(t.functions||0)&&i.statements.percentage>=(t.statements||0);return this.emitStream(r,{status:"complete",message:`Coverage analysis complete (sample data): ${i.lines.percentage}% lines covered`,progress:100}),{success:!0,data:{summary:i,byFile:s,thresholdsPassed:a,riskScore:n?.25:void 0,trends:{direction:"improving",delta:2.5,history:[{date:new Date(Date.now()-10080*60*1e3).toISOString().split("T")[0],coverage:82.5},{date:new Date().toISOString().split("T")[0],coverage:85}]}}}}resetInstanceCache(){this.analyzerService=null}},Jn=class extends A{config={name:"qe/coverage/gaps",description:"Find coverage gaps using O(log n) HNSW vector search. Prioritizes by risk, complexity, or ML confidence using real coverage data.",domain:"coverage-analysis",schema:mm,streaming:!0,timeout:12e4};gapService=null;async getService(e){if(!this.gapService){let t=e.memory??await q(),n=await V(e);this.gapService=new ra({memory:t,llmRouter:n})}return this.gapService}async execute(e,t){let{target:n=".",coverageFile:r,minRisk:i=.3,limit:s=20,prioritization:a="complexity",coverageFormat:c,language:l}=e,d=await Vc("qe/coverage/gaps",n,r);if("error"in d)return{success:!1,error:d.error};let{target:u,coverageFile:m}=d;try{if(this.emitStream(t,{status:"detecting",message:`Detecting coverage gaps in ${u} (O(log n) search)`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let p=null;if(m)try{p=await Dt(m,u,c,l)}catch(T){return{success:!1,error:`Failed to parse coverage file: ${w(T)}`}}else p=await ji(u);if(this.isDemoMode(t))return this.markAsDemoData(t,"Demo mode explicitly requested"),this.getDemoGapsResult(u,i,s,t);if(!p||p.files.size===0)return m?{success:!1,error:`Coverage file '${m}' contains no usable coverage data (parsed 0 files). Verify the file is a non-empty Istanbul/LCOV/JaCoCo/etc. report.${Qc(p)}`}:{success:!1,error:`No coverage data found by autodiscovery under target '${u}'. Run your test suite with coverage enabled, or pass coverageFile pointing to an existing report.`};this.markAsRealData();let g=Kc(p),f=await this.getService(t),h=a==="change-frequency"?"recent-changes":"risk",v=await f.detectGaps({coverageData:{files:g,summary:Wc(g)},minCoverage:80,prioritize:h});if(!v.success)return{success:!1,error:`Gap detection failed: ${v.error?.message||"Unknown error"}`};let y=v.value,C=y.gaps.filter(T=>T.riskScore>=i).slice(0,s).map(T=>({file:T.file,lines:T.lines,type:T.branches.length>0?"uncovered-branch":"uncovered-line",severity:T.severity,riskScore:Math.round(T.riskScore*100)/100,reason:T.recommendation})),b=C.slice(0,5).map((T,S)=>({file:T.file.replace(/\.ts$/,".test.ts"),description:`Add tests for ${T.lines.length} uncovered lines in ${T.file}`,estimatedCoverageGain:Math.round(T.lines.length/(y.totalUncoveredLines||1)*100*100)/100,priority:S+1})),E;if(e.includeGhost)try{let T=await yn(t);if(T?.getDomainAPIAsync){let S=await T.getDomainAPIAsync("coverage-analysis");if(S?.analyzeGhostCoverage){let x=await S.analyzeGhostCoverage(g.map(M=>M.path),u);x?.success&&x.value&&(E=(x.value.gaps||[]).map(M=>({category:M.category,severity:M.severity,description:M.description,confidence:M.confidence})))}}}catch{}return this.emitStream(t,{status:"complete",message:`Found ${C.length} coverage gaps (${y.totalUncoveredLines} uncovered lines)`,progress:100}),{success:!0,data:{gaps:C,totalGaps:y.gaps.length,criticalGaps:C.filter(T=>T.severity==="critical").length,suggestedTests:b,...E?{ghostGaps:E}:{},...p.warnings?{warnings:p.warnings}:{}}}}catch(p){return{success:!1,error:`Gap detection failed: ${w(p)}`}}}getDemoGapsResult(e,t,n,r){let s=[{file:`${e}/service.ts`,lines:[45,67,89,102,115],type:"uncovered-line",severity:"high",riskScore:.85,reason:"Core business logic with no test coverage"},{file:`${e}/utils.ts`,lines:[12,34,56],type:"uncovered-branch",severity:"medium",riskScore:.65,reason:"Utility functions missing edge case tests"},{file:`${e}/handler.ts`,lines:[23,45,67,89],type:"uncovered-function",severity:"critical",riskScore:.92,reason:"Error handling paths untested"},{file:`${e}/validator.ts`,lines:[10,20,30],type:"uncovered-line",severity:"low",riskScore:.35,reason:"Simple validation logic"}].filter(c=>c.riskScore>=t).slice(0,n),a=s.slice(0,5).map((c,l)=>({file:c.file.replace(/\.ts$/,".test.ts"),description:`Add tests for ${c.lines.length} uncovered lines in ${c.file}`,estimatedCoverageGain:Math.round(c.lines.length/50*100*100)/100,priority:l+1}));return this.emitStream(r,{status:"complete",message:`Found ${s.length} coverage gaps (sample data)`,progress:100}),{success:!0,data:{gaps:s,totalGaps:s.length,criticalGaps:s.filter(c=>c.severity==="critical").length,suggestedTests:a}}}resetInstanceCache(){this.gapService=null}},dm={type:"object",properties:{target:{type:"string",description:"Target directory to analyze (searches for coverage files)",default:"."},coverageFile:{type:"string",description:"Path to coverage report file (lcov.info, coverage-final.json, etc.)"},thresholds:{type:"object",description:"Coverage thresholds",properties:{lines:{type:"number",description:"Line coverage threshold"},branches:{type:"number",description:"Branch coverage threshold"},functions:{type:"number",description:"Function coverage threshold"},statements:{type:"number",description:"Statement coverage threshold"}}},includeRisk:{type:"boolean",description:"Include risk score analysis",default:!1},mlPowered:{type:"boolean",description:"Use ML-powered analysis (vector similarity)",default:!1},language:{type:"string",description:"Source language hint (java, csharp, go, rust, kotlin, swift, dart, typescript, python)"},coverageFormat:{type:"string",description:"Coverage format hint",enum:["lcov","json","jacoco","dotcover","tarpaulin","gocover","kover","xcresult"]}}},mm={type:"object",properties:{target:{type:"string",description:"Target directory to analyze",default:"."},coverageFile:{type:"string",description:"Path to coverage report file"},minRisk:{type:"number",description:"Minimum risk score to include (0-1)",minimum:0,maximum:1,default:.3},limit:{type:"number",description:"Maximum number of gaps to return",minimum:1,maximum:100,default:20},prioritization:{type:"string",description:"Gap prioritization strategy",enum:["complexity","criticality","change-frequency","ml-confidence"],default:"complexity"},includeGhost:{type:"boolean",description:"Include ADR-059 ghost intent coverage analysis (detect untested behavioral intents)",default:!1},language:{type:"string",description:"Source language filter (java, csharp, go, rust, kotlin, swift, dart)"},coverageFormat:{type:"string",description:"Coverage format hint",enum:["lcov","json","jacoco","dotcover","tarpaulin","gocover","kover","xcresult"]}}};D();var Zn=class extends A{config={name:"qe/quality/evaluate",description:"Evaluate quality gates and provide deployment recommendations. Analyzes coverage, bugs, complexity, and security.",domain:"quality-assessment",schema:pm,streaming:!0,timeout:12e4};async execute(e,t){let{metrics:n,gateName:r="default",thresholds:i=gm(),includeAdvice:s=!0,riskTolerance:a="medium"}=e;try{let c=await hn(t);if(n&&!e.evidence)return{success:!1,error:"Timestamped evidence provenance is required when supplying quality metrics."};n&&e.evidence&&await on(c,n,e.evidence);let l=n??await cn(c),u=[["coverage",i.coverage],["testsPassing",i.testsPassing],["criticalBugs",i.criticalBugs],["codeSmells",i.codeSmells],["securityVulnerabilities",i.securityVulnerabilities],["technicalDebt",i.technicalDebt],["duplications",i.duplications]].filter(([b,E])=>E!==void 0&&l[b]===void 0).map(([b])=>b);if(u.length>0)return{success:!1,error:`Measured quality evidence missing configured metrics: ${u.join(", ")}.`};if(this.emitStream(t,{status:"evaluating",message:`Evaluating quality gate: ${r}`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let m=[];i.coverage&&l.coverage!==void 0&&m.push({name:"Coverage",passed:l.coverage>=i.coverage.min,value:l.coverage,threshold:i.coverage.min,severity:"high",message:l.coverage>=i.coverage.min?`Coverage ${l.coverage}% meets threshold`:`Coverage ${l.coverage}% below ${i.coverage.min}% threshold`}),i.testsPassing&&l.testsPassing!==void 0&&m.push({name:"Tests Passing",passed:l.testsPassing>=i.testsPassing.min,value:l.testsPassing,threshold:i.testsPassing.min,severity:"critical",message:l.testsPassing>=i.testsPassing.min?`${l.testsPassing}% tests passing`:`Only ${l.testsPassing}% tests passing`}),i.criticalBugs&&l.criticalBugs!==void 0&&m.push({name:"Critical Bugs",passed:l.criticalBugs<=i.criticalBugs.max,value:l.criticalBugs,threshold:i.criticalBugs.max,severity:"critical",message:l.criticalBugs<=i.criticalBugs.max?`${l.criticalBugs} critical bugs within threshold`:`${l.criticalBugs} critical bugs exceed threshold of ${i.criticalBugs.max}`}),i.securityVulnerabilities&&l.securityVulnerabilities!==void 0&&m.push({name:"Security Vulnerabilities",passed:l.securityVulnerabilities<=i.securityVulnerabilities.max,value:l.securityVulnerabilities,threshold:i.securityVulnerabilities.max,severity:"critical",message:l.securityVulnerabilities<=i.securityVulnerabilities.max?`${l.securityVulnerabilities} vulnerabilities within threshold`:`${l.securityVulnerabilities} vulnerabilities found`}),i.codeSmells&&l.codeSmells!==void 0&&m.push({name:"Code Smells",passed:l.codeSmells<=i.codeSmells.max,value:l.codeSmells,threshold:i.codeSmells.max,severity:"medium",message:l.codeSmells<=i.codeSmells.max?`${l.codeSmells} code smells within threshold`:`${l.codeSmells} code smells detected`}),i.technicalDebt&&l.technicalDebt!==void 0&&m.push({name:"Technical Debt",passed:l.technicalDebt<=i.technicalDebt.max,value:l.technicalDebt,threshold:i.technicalDebt.max,severity:"medium",message:l.technicalDebt<=i.technicalDebt.max?`${l.technicalDebt}h technical debt within threshold`:`${l.technicalDebt}h technical debt exceeds threshold of ${i.technicalDebt.max}h`}),i.duplications&&l.duplications!==void 0&&m.push({name:"Duplications",passed:l.duplications<=i.duplications.max,value:l.duplications,threshold:i.duplications.max,severity:"low",message:l.duplications<=i.duplications.max?`${l.duplications}% duplication within threshold`:`${l.duplications}% duplication exceeds threshold of ${i.duplications.max}%`});let p=m.filter(b=>b.passed).length,g=m.length,f=g>0?Math.round(p/g*100):100,h=fm(f,m),v=m.every(b=>b.passed),y=s?hm(v,f,m,a):void 0,C=ym(m,l);return this.emitStream(t,{status:"complete",message:`Quality evaluation complete: ${h} (${f}%)`,progress:100}),{success:!0,data:{passed:v,score:f,grade:h,checks:m,deploymentAdvice:y,recommendations:C}}}catch(c){return{success:!1,error:`Quality evaluation failed: ${w(c)}`}}}},pm={type:"object",properties:{metrics:{type:"object",description:"Quality metrics to evaluate",properties:{coverage:{type:"number",description:"Code coverage percentage"},testsPassing:{type:"number",description:"Percentage of passing tests"},criticalBugs:{type:"number",description:"Number of critical bugs"},codeSmells:{type:"number",description:"Number of code smells"},securityVulnerabilities:{type:"number",description:"Number of security vulnerabilities"},technicalDebt:{type:"number",description:"Technical debt in hours"},duplications:{type:"number",description:"Code duplication percentage"},complexity:{type:"number",description:"Cyclomatic complexity"}}},gateName:{type:"string",description:"Name of the quality gate",default:"default"},thresholds:{type:"object",description:"Quality gate thresholds"},includeAdvice:{type:"boolean",description:"Include deployment advice",default:!0},riskTolerance:{type:"string",description:"Risk tolerance level",enum:["low","medium","high"],default:"medium"},evidence:{type:"object",description:"Provenance required to persist supplied metrics as canonical measured evidence",properties:{measuredAt:{type:"string",description:"ISO-8601 measurement timestamp"},source:{type:"string",description:"Scanner or analyzer that produced the metrics"}}}}};function gm(){return{coverage:{min:Re.coverage.value},testsPassing:{min:Re.testsPassing.value},criticalBugs:{max:Re.criticalBugs.value},securityVulnerabilities:{max:Re.securityVulnerabilities.value},codeSmells:{max:Re.codeSmells.value},technicalDebt:{max:Re.technicalDebt.value},duplications:{max:Re.duplications.value}}}function fm(o,e){return e.some(n=>!n.passed&&n.severity==="critical")?"F":o>=90?"A":o>=80?"B":o>=70?"C":o>=60?"D":"F"}function hm(o,e,t,n){let r=t.filter(u=>!u.passed&&u.severity==="critical"),i=t.filter(u=>!u.passed&&u.severity==="high"),s=r.length*.4+i.length*.2+(100-e)/100,a=Math.min(s,1),c,d={low:{block:.2,warn:.1},medium:{block:.4,warn:.2},high:{block:.6,warn:.4}}[n];return a>=d.block||r.length>0?c="blocked":a>=d.warn?c="warning":c="approved",{decision:c,confidence:Math.round((1-a)*100)/100,riskScore:Math.round(a*100)/100,reasons:[...r.map(u=>`Critical: ${u.name} - ${u.message}`),...i.map(u=>`High: ${u.name} - ${u.message}`)],conditions:c==="warning"?["Monitor closely after deployment","Prepare rollback plan"]:void 0,rollbackPlan:c!=="approved"?"Revert to previous version if issues detected":void 0}}function ym(o,e){let t=[],n=o.filter(r=>!r.passed);for(let r of n)t.push({type:r.severity==="critical"?"critical":r.severity==="high"?"warning":"improvement",title:`Fix ${r.name}`,description:r.message,impact:r.severity==="critical"||r.severity==="high"?"high":"medium",effort:"medium"});return(e.coverage||0)<90&&t.push({type:"improvement",title:"Increase test coverage",description:`Current coverage is ${e.coverage}%. Consider adding tests for critical paths.`,impact:"medium",effort:"medium"}),t}D();Tt();var er=class extends A{config={name:"qe/quality/gate",description:"Two-gate, three-valued quality verdict (ADR-119): mechanical oracle gate plus a frontier judge grading plus failure-mode verification reach. Returns pass|fail|inconclusive.",domain:"quality-assessment",schema:vm,streaming:!1,timeout:12e4};async execute(e,t){try{if(!e.checklistId)return{success:!1,error:"checklistId is required"};if(typeof e.artifact!="string"||e.artifact.length===0)return{success:!1,error:"artifact (non-empty string) is required"};let n,r;if(e.anchorPath!==void 0){let c=await K("qe/quality/gate","anchorPath",e.anchorPath,{basePath:ze(),maxBytes:ne});if(!c.success)return{success:!1,error:c.error.message};n=c.value,r=to(await ue(n,{maxBytes:ne}),e.anchorPath)}let i=await V(t),s=i?ro(i,{...e.model?{model:e.model}:{},logger:c=>this.logger.warn(c,{requestId:t.requestId})}):io("no LLM provider configured \u2014 set a frontier provider API key");return i||this.markAsDemoData(t,"no LLM router \u2014 frontier judge unavailable, verdict will be inconclusive"),{success:!0,data:await no({oracleResult:e.oracle??null,artifact:e.artifact,checklistId:e.checklistId,judge:s,anchorPath:n,anchor:r,verificationManifest:e.verificationManifest})}}catch(n){return{success:!1,error:`Quality gate failed: ${w(n)}`}}}},vm={type:"object",properties:{checklistId:{type:"string",description:'Pinned ADR-117 anchor checklist id (e.g. "A1-inRange")'},artifact:{type:"string",description:"The artifact under judgement (produced test source / spec output)"},oracle:{type:"object",description:"ADR-113 mechanical oracle result. Omit \u21D2 mechanical fail (test did not execute).",properties:{passed:{type:"boolean",description:"Mutation score met threshold"},baselinePassed:{type:"boolean",description:"Tests executed against the reference impl"}}},anchorPath:{type:"string",description:"Override the frozen anchor path (ADR-117)"},verificationManifest:{type:"object",description:"Hashed, revision-bound failure-mode verification reach manifest (#651)"},model:{type:"string",description:"Frontier judge model id (ADR-111: always frontier-tier)"}},required:["checklistId","artifact"]};D();var tr={codeComplexity:"High cyclomatic complexity increases defect probability",changeFrequency:"Frequently modified files are more prone to defects",bugHistory:"Previous defects in this area indicate higher risk",testCoverage:"Low test coverage increases undetected defect risk",developerExperience:"Code written by less experienced developers may have more issues",codeAge:"New code is more likely to have defects than mature, stable code",complexity:"High cyclomatic complexity increases defect probability",churn:"Frequently modified files are more prone to defects",history:"Previous defects in this area indicate higher risk",coverage:"Low test coverage increases undetected defect risk",coupling:"High coupling makes changes risky",age:"New code may have more defects than stable code"},nr=class extends A{config={name:"qe/defects/predict",description:"Predict defect probability for files using ML models. Analyzes code complexity, change frequency, git history, and test coverage.",domain:"defect-intelligence",schema:bm,streaming:!0,timeout:18e4};predictorService=null;async getService(e){if(!this.predictorService){let t=e.memory??await q(),n=await V(e);this.predictorService=new da({memory:t,llmRouter:n})}return this.predictorService}async execute(e,t){let{files:n=[],threshold:r=.5,minConfidence:i=.7,features:s=[{name:"codeComplexity",weight:.25},{name:"changeFrequency",weight:.2},{name:"developerExperience",weight:.15},{name:"testCoverage",weight:.2},{name:"codeAge",weight:.1},{name:"bugHistory",weight:.1}]}=e;try{if(this.emitStream(t,{status:"analyzing",message:`Analyzing ${n.length||"provided"} files using ML-based prediction`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};if(this.isDemoMode(t))return this.markAsDemoData(t,"Demo mode explicitly requested"),this.getDemoResult(n);let a=await this.getService(t),c=await a.predictDefects({files:n,features:s.map(g=>({name:g.name,weight:g.weight??.25})),threshold:r});if(!c.success)return{success:!1,error:`Defect prediction failed: ${c.error?.message||"Service unavailable"}. Ensure the defect-intelligence domain is properly initialized.`};this.markAsRealData();let u=c.value.predictions.filter(g=>g.probability>=1-i).map(g=>({file:g.file,probability:Math.round(g.probability*100)/100,riskLevel:Cm(g.riskLevel),factors:g.factors.map(f=>({name:f.name,contribution:f.contribution,description:tr[f.name]||`${f.name} contributes to defect risk`})),recommendations:g.recommendations}));u.sort((g,f)=>f.probability-g.probability);let m=Sm(u),p=await a.getModelMetrics();return this.emitStream(t,{status:"complete",message:`Analyzed ${n.length} files, ${u.length} with elevated risk`,progress:100}),{success:!0,data:{predictions:u,modelConfidence:c.value.modelConfidence,topRiskFactors:m,recommendations:Em(u),modelMetrics:{accuracy:p.accuracy,precision:p.precision,recall:p.recall,f1Score:p.f1Score}}}}catch(a){return{success:!1,error:`Defect prediction failed: ${w(a)}`}}}getDemoResult(e){let n=(e.length>0?e:["src/service.ts","src/handler.ts","src/utils.ts"]).map((r,i)=>({file:r,probability:Math.max(.9-i*.15,.35),riskLevel:i===0?"high":i===1?"medium":"low",factors:[{name:"codeComplexity",contribution:.35,description:tr.codeComplexity},{name:"changeFrequency",contribution:.25,description:tr.changeFrequency},{name:"testCoverage",contribution:.2,description:tr.testCoverage}],recommendations:[`Increase test coverage for ${r}`,"Consider refactoring complex functions","Review recent changes for potential issues"]}));return{success:!0,data:{predictions:n,modelConfidence:.85,topRiskFactors:[{name:"High Complexity",impact:.35,affectedFiles:n.length},{name:"Frequent Changes",impact:.25,affectedFiles:Math.ceil(n.length*.7)},{name:"Low Coverage",impact:.2,affectedFiles:Math.ceil(n.length*.5)}],recommendations:["Focus testing on files with highest defect probability","Increase test coverage in high-risk areas","Review recent changes to frequently-modified files","Consider refactoring complex modules"],modelMetrics:{accuracy:.82,precision:.78,recall:.85,f1Score:.81}}}}resetInstanceCache(){this.predictorService=null}},bm={type:"object",properties:{files:{type:"array",description:"Specific files to analyze",items:{type:"string",description:"File path"}},target:{type:"string",description:"Target directory to analyze",default:"."},lookback:{type:"number",description:"Days of history to consider",minimum:7,maximum:365,default:30},threshold:{type:"number",description:"Risk threshold for classification (0-1)",minimum:0,maximum:1,default:.5},minConfidence:{type:"number",description:"Minimum prediction confidence (0-1)",minimum:0,maximum:1,default:.7},features:{type:"array",description:"Features to use for prediction",items:{type:"object",description:"Prediction feature",properties:{name:{type:"string",description:"Feature name"},weight:{type:"number",description:"Feature weight"}}}}}};function Cm(o){switch(o){case"critical":return"critical";case"high":return"high";case"medium":return"medium";default:return"low"}}function Sm(o){let e=new Map;for(let n of o)for(let r of n.factors){let i=e.get(r.name)||{impact:0,count:0};i.impact+=r.contribution,i.count+=1,e.set(r.name,i)}let t=[];for(let[n,r]of e)t.push({name:Tm(n),impact:Math.round(r.impact/r.count*100)/100,affectedFiles:r.count});return t.sort((n,r)=>r.impact-n.impact),t.slice(0,5)}function Tm(o){return{codeComplexity:"High Complexity",changeFrequency:"Frequent Changes",bugHistory:"Bug History",testCoverage:"Low Coverage",developerExperience:"Developer Experience",codeAge:"Code Age"}[o]||o.replace(/([A-Z])/g," $1").trim()}function Em(o){let e=[],t=o.filter(i=>i.riskLevel==="critical").length,n=o.filter(i=>i.riskLevel==="high").length,r=o.length>0?o.reduce((i,s)=>i+s.probability,0)/o.length:0;return t>0&&(e.push(`CRITICAL: ${t} files require immediate attention`),e.push("Consider code review and comprehensive testing before deployment")),n>0&&(e.push(`High risk detected in ${n} files`),e.push("Increase test coverage in high-risk areas")),r>.5?(e.push("Overall defect risk is elevated - consider delaying release"),e.push("Run full regression test suite before deployment")):e.push("Focus testing on files with highest defect probability"),e.push("Review recent changes to frequently-modified files"),e.push("Consider refactoring complex modules"),[...new Set(e)]}D();var rr=class extends A{config={name:"qe/requirements/validate",description:"Validate requirements for testability. Scores each requirement, detects ambiguity, and optionally generates BDD scenarios.",domain:"requirements-validation",schema:wm,streaming:!0,timeout:12e4};async execute(e,t){let{requirements:n,generateBDD:r=!1,checkAmbiguity:i=!0,minTestability:s=60}=e;try{if(this.emitStream(t,{status:"validating",message:`Validating ${n.length} requirements`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let a=[],c=[];for(let d of n){this.emitStream(t,{status:"processing",message:`Analyzing: ${d.title}`});let u=Rm(d),m=Pm(d,s,u),p=i?xm(d):void 0;a.push({requirementId:d.id,isValid:m.filter(g=>g.severity==="error").length===0,testabilityScore:u,errors:m,ambiguityReport:p}),r&&u.value>=s&&c.push(...km(d))}let l={total:n.length,valid:a.filter(d=>d.isValid).length,invalid:a.filter(d=>!d.isValid).length,avgTestability:a.reduce((d,u)=>d+u.testabilityScore.value,0)/n.length,blockers:a.filter(d=>d.errors.some(u=>u.severity==="error")).length};return this.emitStream(t,{status:"complete",message:`Validation complete: ${l.valid}/${l.total} valid`,progress:100}),{success:!0,data:{validationResults:a,summary:l,bddScenarios:c.length>0?c:void 0,recommendations:Mm(a)}}}catch(a){return{success:!1,error:`Validation failed: ${w(a)}`}}}},wm={type:"object",properties:{requirements:{type:"array",description:"Requirements to validate",items:{type:"object",description:"Requirement input",properties:{id:{type:"string",description:"Requirement ID"},title:{type:"string",description:"Requirement title"},description:{type:"string",description:"Requirement description"},acceptanceCriteria:{type:"array",description:"Acceptance criteria",items:{type:"string",description:"Criterion"}},type:{type:"string",description:"Requirement type",enum:["user-story","functional","non-functional","technical"]}},required:["id","title","description"]}},generateBDD:{type:"boolean",description:"Generate BDD scenarios from requirements",default:!1},checkAmbiguity:{type:"boolean",description:"Check for ambiguous language",default:!0},minTestability:{type:"number",description:"Minimum testability score (0-100)",minimum:0,maximum:100,default:60}},required:["requirements"]};function Rm(o){let e=[],t=o.acceptanceCriteria&&o.acceptanceCriteria.length>0?90:40;e.push({name:"Acceptance Criteria",score:t,issues:t<70?["Missing or incomplete acceptance criteria"]:[]});let n=o.description.length,r=n>100?85:n>50?70:50;e.push({name:"Description Clarity",score:r,issues:r<70?["Description may be too brief"]:[]});let a=["should","must","when","then","verify","validate"].some(l=>o.description.toLowerCase().includes(l))?80:50;e.push({name:"Measurability",score:a,issues:a<70?["Requirement lacks measurable criteria"]:[]});let c=Math.round(e.reduce((l,d)=>l+d.score,0)/e.length);return{value:c,category:c>=80?"excellent":c>=70?"good":c>=50?"fair":"poor",factors:e}}function Pm(o,e,t){let n=[];return t.value<e&&n.push({code:"LOW_TESTABILITY",message:`Testability score ${t.value} is below minimum ${e}`,severity:"error",suggestion:"Add clear acceptance criteria and measurable outcomes"}),(!o.acceptanceCriteria||o.acceptanceCriteria.length===0)&&n.push({code:"MISSING_AC",message:"No acceptance criteria defined",severity:"warning",suggestion:"Define specific, testable acceptance criteria"}),o.description.length<30&&n.push({code:"BRIEF_DESC",message:"Description is too brief",severity:"warning",suggestion:"Expand description with more context and details"}),n}function xm(o){let e=[],t=["some","few","many","fast","slow","good","better","appropriate"];for(let n of t)o.description.toLowerCase().includes(n)&&e.push({term:n,context:`Found in: "${o.description.substring(0,50)}..."`,alternatives:Am(n)});return{ambiguousTerms:e,overallScore:Math.max(0,100-e.length*15),suggestions:e.length>0?["Replace vague terms with specific, measurable criteria"]:["Requirement language is clear"]}}function Am(o){return{some:["exactly N","at least N","between N and M"],few:["1-3","less than 5"],many:["more than 10","at least N"],fast:["within X milliseconds","response time < Xs"],slow:["longer than X seconds"],good:["score >= 80%","passes all criteria"],better:["improves by X%","exceeds baseline by N"],appropriate:["meets requirement X","validates against schema"]}[o]||["Be more specific"]}function km(o){let e=[];return e.push({id:`scenario-${o.id}-1`,feature:o.title,scenario:`Verify ${o.title}`,given:["the system is initialized","the user is authenticated"],when:["the user performs the action"],then:["the expected outcome is observed","the system state is updated"],tags:["@generated",`@${o.type||"functional"}`]}),o.acceptanceCriteria&&o.acceptanceCriteria.length>0&&o.acceptanceCriteria.forEach((t,n)=>{e.push({id:`scenario-${o.id}-ac${n+1}`,feature:o.title,scenario:`Acceptance Criteria: ${t.substring(0,50)}`,given:["the preconditions are met"],when:["the specified action is taken"],then:[t],tags:["@generated","@acceptance"]})}),e}function Mm(o){let e=[],t=o.filter(r=>r.testabilityScore.value<60).length,n=o.filter(r=>r.errors.some(i=>i.code==="MISSING_AC")).length;return t>0&&e.push(`${t} requirements have low testability scores. Consider adding acceptance criteria.`),n>0&&e.push(`${n} requirements lack acceptance criteria. Define testable criteria for each.`),o.every(r=>r.isValid)&&e.push("All requirements are valid and testable."),e}import{existsSync as Ui,readFileSync as Xc}from"fs";import{join as Bi,dirname as Im}from"path";import{fileURLToPath as Dm}from"url";var st=["Capability","Reliability","Usability","Charisma","Security","Scalability","Compatibility","Performance","Installability","Development"],at=["Capability","Reliability","Security","Performance","Development"];var _m=Dm(import.meta.url),Om=Im(_m),_t=class{config;templateCache=null;constructor(e={}){this.config={enableSemanticAnalysis:e.enableSemanticAnalysis??!0,defaultOutputFormat:e.defaultOutputFormat??"html",templatePath:e.templatePath??this.findTemplatePath(),minimumCategories:e.minimumCategories??8}}findTemplatePath(){let e=[Bi(process.cwd(),".claude/helpers/v3/quality-criteria/quality-criteria-reference-template.html"),Bi(process.cwd(),"node_modules/agentic-qe/assets/agents/v3/helpers/quality-criteria/quality-criteria-reference-template.html"),Bi(Om,"../../../../../assets/agents/v3/helpers/quality-criteria/quality-criteria-reference-template.html")];for(let t of e)if(Ui(t))return t;return e[0]}analyze(e){let t=e.epicContent||"";if(e.epicPath&&Ui(e.epicPath)&&(t=Xc(e.epicPath,"utf-8")),!t&&!e.epicPath)throw new Error("Either epicPath or epicContent is required for analysis");return{agentInvocation:{required:!0,agentType:"qe-quality-criteria-recommender",prompt:this.buildAgentPrompt({assessmentName:e.assessmentName,epicContent:t,epicPath:e.epicPath,sourcePaths:e.sourcePaths,outputFormat:e.outputFormat,outputPath:e.outputPath}),timeout:3e5,expectedOutput:"QualityCriteriaAnalysis",instructions:`Claude Code MUST spawn the qe-quality-criteria-recommender agent with this prompt. The agent will perform real semantic HTSM analysis using Claude's reasoning capabilities. Use: Task("HTSM Quality Criteria Analysis", { prompt: <this prompt> }, "qe-quality-criteria-recommender")`},message:"AGENT INVOCATION REQUIRED: This service cannot perform semantic HTSM analysis alone. Claude Code must spawn the qe-quality-criteria-recommender agent with the provided prompt."}}buildAgentPrompt(e){let{assessmentName:t,epicContent:n,epicPath:r,sourcePaths:i,outputFormat:s,outputPath:a}=e,c=i&&i.length>0?`
453
+ `).run(n))}catch(t){console.warn("[CoverageLearner] Retention cleanup failed:",w(t))}}async learnFromSession(e){this.sessionStore.add(e),await this.persistSession(e);let t=this.calculateOverallImprovement(e);if(t<this.config.minCoverageImprovementToLearn)return null;let n=await this.extractStrategy(e,t);return this.reasoningBank&&n&&await this.storeStrategyAsPattern(n),n}calculateOverallImprovement(e){let t=e.beforeCoverage,n=e.afterCoverage,r=n.lines-t.lines,i=n.branches-t.branches,s=n.functions-t.functions;return r*.4+i*.35+s*.25}async extractStrategy(e,t){let n=this.extractFilePattern(e.targetPath),r=`${e.technique}:${n}`,i=this.strategies.get(r);return i?i={...i,avgImprovement:(i.avgImprovement*i.successCount+t)/(i.successCount+1),successCount:i.successCount+1,confidence:Math.min(1,i.confidence+.05),lastUsedAt:new Date}:i={id:`strategy-${Date.now()}-${Od().slice(0,8)}`,description:this.generateStrategyDescription(e,t),technique:e.technique,filePatterns:[n],avgImprovement:t,successCount:1,confidence:.5,createdAt:new Date,lastUsedAt:new Date},this.strategies.set(r,i),i}extractFilePattern(e){let t=e.split("/"),r=t[t.length-1].split(".").pop()||"";return t.length>=2?`${t[t.length-2]}/*.${r}`:`*.${r}`}generateStrategyDescription(e,t){let r={"gap-analysis":"Identify and target uncovered code paths","branch-coverage":"Focus on branch conditions and decision points","edge-case-generation":"Generate tests for edge cases and boundary conditions","mutation-guided":"Use mutation testing to identify weak test areas","risk-based":"Prioritize high-risk code paths","semantic-analysis":"Use code semantics to generate meaningful tests","boundary-testing":"Test boundary conditions and limits","state-machine":"Model state transitions and test state changes","data-flow":"Follow data flow paths through the code"}[e.technique]||e.technique,i=e.gapsTargeted.filter(a=>a.addressed).length,s=e.gapsTargeted.length;return`${r} for ${this.extractFilePattern(e.targetPath)} files. Achieved ${t.toFixed(1)}% improvement. Addressed ${i}/${s} gaps with ${e.testsGenerated} tests.`}async storeStrategyAsPattern(e){this.reasoningBank&&await this.reasoningBank.storeQEPattern({patternType:"coverage-strategy",name:`Coverage Strategy: ${e.technique}`,description:e.description,template:{type:"workflow",content:JSON.stringify({technique:e.technique,filePatterns:e.filePatterns,avgImprovement:e.avgImprovement}),variables:[{name:"targetFile",type:"string",required:!0,description:"Target file to analyze"},{name:"currentCoverage",type:"number",required:!0,description:"Current coverage percentage"}]},context:{tags:["coverage",e.technique,...e.filePatterns]}})}getRecommendedStrategy(e){let t=this.extractFilePattern(e),n=null,r=0;for(let i of this.strategies.values())if(i.filePatterns.some(a=>t.includes(a.split("/").pop()||"")||a.includes(t.split("/").pop()||""))||i.filePatterns.length===0){let a=(Date.now()-i.lastUsedAt.getTime())/864e5,c=Math.max(.5,1-a/30),l=i.avgImprovement*i.confidence*c;l>r&&(r=l,n=i)}return n}getAllStrategies(){return Array.from(this.strategies.values())}getStrategiesByTechnique(e){return this.getAllStrategies().filter(t=>t.technique===e)}getSessionStats(){let e=this.sessionStore.getAll();if(e.length===0)return{totalSessions:0,successfulSessions:0,avgImprovement:0,byTechnique:new Map,strategiesLearned:0};let t=e.map(a=>this.calculateOverallImprovement(a)),n=t.filter(a=>a>=this.config.minCoverageImprovementToLearn).length,r=t.reduce((a,c)=>a+c,0)/t.length,i=new Map,s=new Map;for(let a of e){let c=s.get(a.technique)||[];c.push(a),s.set(a.technique,c)}for(let[a,c]of s){let l=c.map(u=>this.calculateOverallImprovement(u));i.set(a,{count:c.length,avgImprovement:l.reduce((u,d)=>u+d,0)/l.length})}return{totalSessions:e.length,successfulSessions:n,avgImprovement:r,byTechnique:i,strategiesLearned:this.strategies.size}}analyzeGapResolution(){let t=this.sessionStore.getAll().flatMap(i=>i.gapsTargeted);if(t.length===0)return{totalGapsTargeted:0,gapsAddressed:0,resolutionRate:0,byGapType:new Map};let n=t.filter(i=>i.addressed).length,r=new Map;for(let i of t){let s=r.get(i.type)||{targeted:0,addressed:0};s.targeted++,i.addressed&&s.addressed++,r.set(i.type,s)}return{totalGapsTargeted:t.length,gapsAddressed:n,resolutionRate:n/t.length,byGapType:r}}exportSessions(){return this.sessionStore.getAll()}importSessions(e){for(let t of e)this.sessionStore.add(t)}exportStrategies(){return this.getAllStrategies()}importStrategies(e){for(let t of e){let n=`${t.technique}:${t.filePatterns[0]||"*"}`;this.strategies.set(n,t)}}clear(){this.sessionStore.clear(),this.strategies.clear()}getLearnerStats(){return{totalSessions:this.sessionStore.size,totalStrategies:this.strategies.size,hasReasoningBank:this.reasoningBank!==null,minImprovementThreshold:this.config.minCoverageImprovementToLearn}}};function nc(o){return new xi(o)}var Ai=class{weights;historicalScores=[];maxHistory;constructor(e={},t=100){this.weights={...Ti,...e},this.maxHistory=t}calculateFromOutcome(e){let t=this.calculateDimensions(e),n=this.calculateOverall(t);return this.trackScore(n),{overall:n,dimensions:t,weights:this.weights,trend:this.calculateTrend(),calculatedAt:new Date}}calculateDimensions(e){return{effectiveness:this.calculateEffectiveness(e),coverage:this.calculateCoverageScore(e.coverage),mutationKill:e.mutationScore??.5,stability:this.calculateStability(e),maintainability:e.maintainabilityScore,performance:this.calculatePerformanceScore(e.executionTimeMs)}}calculateEffectiveness(e){return e.passed?e.flaky?.3:1:0}calculateCoverageScore(e){return(e.lines*.4+e.branches*.35+e.functions*.25)/100}calculateStability(e){return e.flaky?.2:e.flakinessScore!==void 0?1-e.flakinessScore:1}calculatePerformanceScore(e){return e<100?1:e<500?.8:e<2e3?.6:e<5e3?.4:e<1e4?.2:.1}calculateOverall(e){return this.weights.effectiveness*e.effectiveness+this.weights.coverage*e.coverage+this.weights.mutationKill*e.mutationKill+this.weights.stability*e.stability+this.weights.maintainability*e.maintainability+this.weights.performance*e.performance}trackScore(e){this.historicalScores.push(e),this.historicalScores.length>this.maxHistory&&(this.historicalScores=this.historicalScores.slice(-this.maxHistory))}calculateTrend(){if(this.historicalScores.length<10)return"stable";let e=this.historicalScores.slice(-10),t=this.historicalScores.slice(-20,-10);if(t.length===0)return"stable";let n=e.reduce((s,a)=>s+a,0)/e.length,r=t.reduce((s,a)=>s+a,0)/t.length,i=n-r;return i>.05?"improving":i<-.05?"declining":"stable"}calculateAggregate(e){if(e.length===0)return{overall:0,dimensions:{effectiveness:0,coverage:0,mutationKill:0,stability:0,maintainability:0,performance:0},weights:this.weights,trend:"stable",calculatedAt:new Date};let t={effectiveness:0,coverage:0,mutationKill:0,stability:0,maintainability:0,performance:0};for(let s of e){let a=this.calculateDimensions(s);t.effectiveness+=a.effectiveness,t.coverage+=a.coverage,t.mutationKill+=a.mutationKill,t.stability+=a.stability,t.maintainability+=a.maintainability,t.performance+=a.performance}let n=e.length,r={effectiveness:t.effectiveness/n,coverage:t.coverage/n,mutationKill:t.mutationKill/n,stability:t.stability/n,maintainability:t.maintainability/n,performance:t.performance/n};return{overall:this.calculateOverall(r),dimensions:r,weights:this.weights,trend:this.calculateTrend(),calculatedAt:new Date}}calculateDelta(e,t){let n={effectiveness:t.dimensions.effectiveness-e.dimensions.effectiveness,coverage:t.dimensions.coverage-e.dimensions.coverage,mutationKill:t.dimensions.mutationKill-e.dimensions.mutationKill,stability:t.dimensions.stability-e.dimensions.stability,maintainability:t.dimensions.maintainability-e.dimensions.maintainability,performance:t.dimensions.performance-e.dimensions.performance},r=t.overall-e.overall;return{overallDelta:r,dimensionDeltas:n,improved:r>0}}getRecommendations(e){let t=[],n=e.dimensions;return n.effectiveness<.8&&t.push("Improve test pass rate - investigate failing tests"),n.coverage<.7&&t.push("Increase code coverage - target uncovered paths"),n.mutationKill<.6&&t.push("Strengthen assertions - tests may be too weak"),n.stability<.9&&t.push("Address test flakiness - stabilize intermittent tests"),n.maintainability<.7&&t.push("Improve test maintainability - reduce complexity"),n.performance<.6&&t.push("Optimize test performance - reduce execution time"),t.length===0&&t.push("Quality is excellent - maintain current practices"),t}updateWeights(e){this.weights={...this.weights,...e}}getWeights(){return{...this.weights}}getStats(){let e=this.historicalScores.slice(-10),t=e.length>0?e.reduce((n,r)=>n+r,0)/e.length:0;return{scoresTracked:this.historicalScores.length,currentTrend:this.calculateTrend(),avgRecentScore:t}}clearHistory(){this.historicalScores=[]}};function rc(o,e){return new Ai(o,e)}var ki=class{criteria;promotionHistory=[];demotionHistory=[];reasoningBank=null;config;constructor(e={}){this.config={...xe,...e},this.criteria={...Ei}}connectReasoningBank(e){this.reasoningBank=e}evaluatePromotion(e,t){let n=e.tier,r=this.getNextTier(n);if(!r)return null;let i=this.criteria[r];if(this.meetsPromotionCriteria(t,i)){let s={patternId:e.id,fromTier:n,toTier:r,reason:this.generatePromotionReason(t,i),metrics:{successCount:t.successCount,successRate:t.successRate,qualityScore:t.qualityScore,ageDays:t.ageDays},timestamp:new Date};return this.promotionHistory.push(s),s}return null}evaluateDemotion(e,t){if(!this.config.autoDemote)return null;let n=e.tier;if(n==="short-term")return null;if(t.recentSuccessRate<.4||t.recentFailureCount>=5||t.qualityScore<.3){let i=this.getPreviousTier(n);if(!i)return null;let s={patternId:e.id,fromTier:n,toTier:i,reason:this.generateDemotionReason(t),metrics:{recentSuccessRate:t.recentSuccessRate,recentQualityScore:t.qualityScore,failureCount:t.recentFailureCount},timestamp:new Date};return this.demotionHistory.push(s),s}return null}async processPatternChange(e,t){let n=this.evaluateDemotion(e,t);if(n)return this.reasoningBank&&await this.reasoningBank.demotePattern(e.id),{action:"demoted",event:n};let r=this.evaluatePromotion(e,t);return r?(this.reasoningBank&&await this.reasoningBank.promotePattern(e.id),{action:"promoted",event:r}):{action:"unchanged"}}meetsPromotionCriteria(e,t){return e.successCount>=t.minSuccessCount&&e.successRate>=t.minSuccessRate&&e.qualityScore>=t.minQualityScore&&e.ageDays>=t.minAgeDays}getNextTier(e){let t=["short-term","working","long-term","permanent"],n=t.indexOf(e);return n<t.length-1?t[n+1]:null}getPreviousTier(e){let t=["short-term","working","long-term","permanent"],n=t.indexOf(e);return n>0?t[n-1]:null}generatePromotionReason(e,t){let n=[];return e.successCount>=t.minSuccessCount&&n.push(`${e.successCount} successful uses (>=${t.minSuccessCount})`),e.successRate>=t.minSuccessRate&&n.push(`${(e.successRate*100).toFixed(0)}% success rate (>=${t.minSuccessRate*100}%)`),e.qualityScore>=t.minQualityScore&&n.push(`${(e.qualityScore*100).toFixed(0)}% quality score (>=${t.minQualityScore*100}%)`),`Pattern promoted: ${n.join(", ")}`}generateDemotionReason(e){let t=[];return e.recentSuccessRate<.4&&t.push(`low recent success rate (${(e.recentSuccessRate*100).toFixed(0)}%)`),e.recentFailureCount>=5&&t.push(`${e.recentFailureCount} recent failures`),e.qualityScore<.3&&t.push(`low quality score (${(e.qualityScore*100).toFixed(0)}%)`),`Pattern demoted: ${t.join(", ")}`}updateCriteria(e,t){this.criteria[e]={...this.criteria[e],...t}}getCriteria(e){return{...this.criteria[e]}}getAllCriteria(){return{...this.criteria}}getPromotionHistory(e=100){return this.promotionHistory.slice(-e)}getDemotionHistory(e=100){return this.demotionHistory.slice(-e)}getStats(){let e={"short-term":0,working:0,"long-term":0,permanent:0};for(let s of this.promotionHistory)e[s.toTier]++;let t={"short-term":0,working:0,"long-term":0,permanent:0};for(let s of this.demotionHistory)t[s.toTier]++;let n=Date.now()-10080*60*1e3,r=this.promotionHistory.filter(s=>s.timestamp.getTime()>n).length,i=this.demotionHistory.filter(s=>s.timestamp.getTime()>n).length;return{totalPromotions:this.promotionHistory.length,totalDemotions:this.demotionHistory.length,promotionsByTier:e,demotionsByTier:t,recentPromotions:r,recentDemotions:i}}exportHistory(){return{promotions:[...this.promotionHistory],demotions:[...this.demotionHistory]}}importHistory(e){e.promotions&&this.promotionHistory.push(...e.promotions),e.demotions&&this.demotionHistory.push(...e.demotions)}clearHistory(){this.promotionHistory=[],this.demotionHistory=[]}};function ic(o){return new ki(o)}var Mi=class{outcomeTracker;coverageLearner;qualityCalculator;promotionManager;routingFeedback;reasoningBank=null;config;constructor(e={}){this.config={...xe,...e},this.outcomeTracker=tc(this.config),this.coverageLearner=nc(this.config),this.qualityCalculator=rc(this.config.qualityWeights),this.promotionManager=ic(this.config),this.routingFeedback=$s(this.config.maxOutcomesInMemory)}async initialize(){await Promise.all([this.outcomeTracker.initialize(),this.coverageLearner.initialize(),this.routingFeedback.initialize()])}connectReasoningBank(e){this.reasoningBank=e,this.outcomeTracker.connectReasoningBank(e),this.coverageLearner.connectReasoningBank(e),this.promotionManager.connectReasoningBank(e)}async recordTestOutcome(e){await this.outcomeTracker.track(e);let t=this.qualityCalculator.calculateFromOutcome(e),n;if(e.patternId&&this.reasoningBank){let r=await this.reasoningBank.searchQEPatterns(e.patternId,{limit:1});if(r.success&&r.value.length>0){let i=r.value[0].pattern,s=this.outcomeTracker.getPatternMetrics(e.patternId);if(s){let a=await this.promotionManager.processPatternChange(i,{patternId:e.patternId,successCount:s.successCount,failureCount:s.failureCount,successRate:s.successRate,qualityScore:s.avgQuality,ageDays:this.calculateAgeDays(i.createdAt),recentSuccessRate:this.calculateRecentSuccessRate(e.patternId),recentFailureCount:this.calculateRecentFailures(e.patternId)});n={action:a.action,tier:a.event&&"toTier"in a.event?a.event.toTier:void 0}}}}return{qualityScore:t,patternUpdate:n}}async recordCoverageSession(e){let t=await this.coverageLearner.learnFromSession(e);return{improvement:(e.afterCoverage.lines-e.beforeCoverage.lines+e.afterCoverage.branches-e.beforeCoverage.branches+e.afterCoverage.functions-e.beforeCoverage.functions)/3,strategyLearned:t!==null,strategyId:t?.id}}getRecommendedCoverageStrategy(e){return this.coverageLearner.getRecommendedStrategy(e)}getQualityRecommendations(){let e=this.outcomeTracker.getRecentOutcomes(50);if(e.length===0)return["No test outcomes recorded yet. Start tracking test results to get recommendations."];let t=this.qualityCalculator.calculateAggregate(e);return this.qualityCalculator.getRecommendations(t)}async recordRoutingOutcome(e){let t={id:e.taskId,description:e.taskDescription,complexity:"medium",domains:["test-generation"],context:{}},n={recommended:e.recommendedAgent,confidence:.8,reasoning:"Recorded from feedback",alternatives:[],scores:{similarity:.8,performance:.8,capabilities:.8,combined:.8},latencyMs:0,timestamp:e.timestamp};this.routingFeedback.recordOutcome(t,n,e.usedAgent,{success:e.success,qualityScore:e.qualityScore,durationMs:e.durationMs,error:e.error})}getRoutingAnalysis(){let e=this.routingFeedback.analyzeRoutingAccuracy(),t=this.routingFeedback.getImprovementRecommendations();return{totalOutcomes:e.totalOutcomes,recommendationFollowRate:1-e.overrideRate,successRateWhenFollowed:e.recommendationSuccessRate,successRateWhenOverridden:e.overrideSuccessRate,confidenceCorrelation:e.confidenceCorrelation,recommendations:t}}calculateAgeDays(e){return(Date.now()-e.getTime())/(1e3*60*60*24)}calculateRecentSuccessRate(e){let t=this.outcomeTracker.exportOutcomes().filter(r=>r.patternId===e).slice(-10);return t.length===0?0:t.filter(r=>r.passed&&!r.flaky).length/t.length}calculateRecentFailures(e){return this.outcomeTracker.exportOutcomes().filter(n=>n.patternId===e).slice(-10).filter(n=>!n.passed||n.flaky).length}getStats(){let e=this.outcomeTracker.getStats(),t=this.coverageLearner.getSessionStats(),n=this.promotionManager.getStats(),r=this.qualityCalculator.getStats(),i=this.outcomeTracker.getTrackerStats(),s=this.routingFeedback.analyzeRoutingAccuracy();return{testOutcomes:{total:e.totalTests,passRate:e.passRate,avgQuality:e.avgMaintainability,flakyCount:e.flakyTests},coverage:{totalSessions:t.totalSessions,successfulSessions:t.successfulSessions,avgImprovement:t.avgImprovement,strategiesLearned:t.strategiesLearned},patterns:{promoted:n.totalPromotions,demoted:n.totalDemotions,tracked:i.patternsTracked},quality:{currentTrend:r.currentTrend,avgRecentScore:r.avgRecentScore},routing:{totalOutcomes:s.totalOutcomes,recommendationFollowRate:1-s.overrideRate,successRateWhenFollowed:s.recommendationSuccessRate,successRateWhenOverridden:s.overrideSuccessRate},integrationStatus:{reasoningBankConnected:this.reasoningBank!==null}}}exportData(){return{outcomes:this.outcomeTracker.exportOutcomes(),sessions:this.coverageLearner.exportSessions(),strategies:this.coverageLearner.exportStrategies(),promotionHistory:this.promotionManager.exportHistory(),routingOutcomes:this.routingFeedback.exportOutcomes()}}importData(e){e.outcomes&&this.outcomeTracker.importOutcomes(e.outcomes),e.sessions&&this.coverageLearner.importSessions(e.sessions),e.strategies&&this.coverageLearner.importStrategies(e.strategies),e.promotionHistory&&this.promotionManager.importHistory(e.promotionHistory),e.routingOutcomes&&this.routingFeedback.importOutcomes(e.routingOutcomes)}clear(){this.outcomeTracker.clear(),this.coverageLearner.clear(),this.qualityCalculator.clearHistory(),this.promotionManager.clearHistory(),this.routingFeedback.clear()}};async function sc(o){let e=new Mi(o);return await e.initialize(),ac=e,e}var ac=null;function oc(){return ac}fs();function nt(){return`test-${tt()}`}function cc(o){return`${o}-${tt()}`}function Di(o){return{enabled:!0,agentId:cc(o),message:"Experience captured asynchronously via learning pipeline"}}async function Nd(o,e,t,n,r,i=Pr(e,n),s){let a=cc(o);try{let{kernel:c}=It();if(!c)return{enabled:!1,agentId:a,message:"Learning engine not available - kernel not initialized"};let l=await Ld();if(!l)return{enabled:!1,agentId:a,message:"Learning engine not available"};let u=l.getExperienceCaptureService();if(!u)return{enabled:!1,agentId:a,message:"Experience capture service not available"};let d=Fd(e),m=u.startCapture(`${e}: ${JSON.stringify(t).slice(0,200)}`,{agent:o,domain:d||void 0,metadata:{tool:e,durationMs:r,...s?{runId:s}:{}}}),p=i.measured?i.success===!0:!0,f=p?.7:.3;u.recordStep(m,{action:`execute-${e}`,result:typeof n=="object"?JSON.stringify(n).slice(0,500):String(n).slice(0,500),quality:f});let g=await u.completeCapture(m,{success:p,quality:f,...i.measured?{outcomeBasis:i.basis}:{}});if(g.success){let h=g.value;return{enabled:!0,agentId:a,message:`Experience captured: ${h.id} (domain: ${d||"general"}, quality: ${h.quality})`,experienceId:h.id,domain:d||"general"}}return{enabled:!0,agentId:a,message:"Experience capture completed (no pattern extracted)"}}catch(c){return{enabled:!1,agentId:a,message:`Learning capture failed: ${w(c)}`}}}function Fd(o){return{test_generate_enhanced:"test-generation",test_execute_parallel:"test-execution",coverage_analyze_sublinear:"coverage-analysis",quality_assess:"quality-assessment",security_scan_comprehensive:"security-compliance",contract_validate:"contract-testing",accessibility_test:"visual-accessibility",chaos_test:"chaos-resilience",defect_predict:"defect-intelligence",requirements_validate:"requirements-validation",code_index:"code-intelligence"}[o]||null}async function Ld(){return gc()}async function qd(o,e,t,n){let r=oc();if(!r&&Ii&&(r=await Ii),!!r){if(o==="test-generation"&&e){let i=e.tests||e.generatedTests||[];for(let s of i.slice(0,20)){let a={id:String(s.id||tt()),testId:String(s.id||s.name||tt()),testName:String(s.name||s.testName||"generated-test"),generatedBy:"qe-test-generation",patternId:s.patternId,framework:s.framework||n.framework||"vitest",language:s.language||n.language||"typescript",domain:"test-generation",passed:s.passed!==!1,coverage:{lines:Number(s.coverageLines||0),branches:Number(s.coverageBranches||0),functions:Number(s.coverageFunctions||0)},executionTimeMs:Number(s.executionTimeMs||t/Math.max(i.length,1)),flaky:!!s.flaky,maintainabilityScore:Number(s.qualityScore||s.maintainability||.7),timestamp:new Date};await r.recordTestOutcome(a)}}if(o==="coverage-analysis"&&e&&Ke(o,e)){let i={id:tt(),targetPath:String(n.target||n.targetPath||"src/"),agentId:"qe-coverage-analysis",technique:n.technique||"gap-analysis",beforeCoverage:{lines:Number(e.beforeCoverage?.lines||0),branches:Number(e.beforeCoverage?.branches||0),functions:Number(e.beforeCoverage?.functions||0)},afterCoverage:{lines:Number(e.lineCoverage||e.lines||0),branches:Number(e.branchCoverage||e.branches||0),functions:Number(e.functionCoverage||e.functions||0)},testsGenerated:Number(e.testsGenerated||0),testsPassed:Number(e.testsPassed||0),gapsTargeted:(e.gaps||[]).map((s,a)=>({id:String(s.id||`gap-${tt().slice(0,8)}-${a}`),type:["uncovered-line","uncovered-branch","uncovered-function","partial-branch"].includes(String(s.type))?String(s.type):"uncovered-line",filePath:String(s.file||s.filePath||""),startLine:Number(s.line||s.startLine||0),endLine:s.endLine?Number(s.endLine):void 0,riskScore:Number(s.riskScore||.5),addressed:!!s.addressed})),durationMs:t,startedAt:new Date(Date.now()-t),completedAt:new Date,context:{measured:!0,coverageMethod:e.coverageMethod??"instrumented-report",branchDataCollected:e.branchCoverage!==null&&e.branchCoverage!==void 0,functionDataCollected:e.functionCoverage!==null&&e.functionCoverage!==void 0,...e.runStatus==="passed"||e.runStatus==="failed"?{runStatus:e.runStatus}:{}}};await r.recordCoverageSession(i)}}}function lc(o){let e=o.split(`
454
+ `).length,t=(o.match(/if|switch|for|while|catch/g)||[]).length;return{score:e+t*2,level:t>5?"high":t>2?"medium":"low"}}function uc(o,e){let t=[];return o.level==="high"&&(t.push("Consider refactoring complex functions"),t.push("Add unit tests for each branch")),t.push("Consider adding edge case tests"),t.push("Add error handling tests"),e==="integration"&&(t.push("Add mock external dependencies"),t.push("Test API contract boundaries")),{recommendations:t,estimatedTime:`${Math.round(o.score*.5)} minutes`,confidence:.85}}function dc(o,e,t,n){let r=[],i=/(?:function\s+(\w+)|const\s+(\w+)\s*=|def\s+(\w+)|func\s+(\w+))/g,s=[],a;for(;(a=i.exec(o))!==null;){let l=a[1]||a[2]||a[3]||a[4];l&&s.push(l)}for(let l=0;l<Math.min(s.length,n);l++){let u=s[l]||"exampleFunction";r.push({id:nt(),name:`test_${u}_${l}`,type:e,parameters:[],assertions:[`${u}() === null`],expectedResult:null,estimatedDuration:e==="integration"?2e3:1e3,aiGenerated:!0})}(e==="integration"||n>s.length)&&r.push({id:nt(),name:`integration_ComponentA_${r.length}`,type:"integration",parameters:[],assertions:["ComponentA integration test passes"],expectedResult:null,estimatedDuration:2e3,aiGenerated:!0});let c=["high-complexity","deep-nesting","null-handling","empty-input"];for(let l=r.length;l<n&&l-r.length<c.length;l++)r.push({id:nt(),name:`edge_case_${c[l-r.length]}_${l}`,type:"unit",parameters:[],assertions:[`${c[l-r.length]} edge case handled`],expectedResult:null,estimatedDuration:1500,aiGenerated:!0});return r}function mc(o,e){let t=[],n=o.split(`
455
+ `);return o.includes("eval(")&&t.push({type:"dangerous-eval",line:n.findIndex(r=>r.includes("eval("))+1,severity:"critical",suggestion:"Replace eval() with safer alternatives"}),o.includes("var ")&&(e==="javascript"||e==="typescript")&&t.push({type:"var-usage",line:n.findIndex(r=>r.includes("var "))+1,severity:"low",suggestion:"Use const or let instead of var"}),o.includes("any")&&e==="typescript"&&t.push({type:"any-type",line:n.findIndex(r=>r.includes("any"))+1,severity:"medium",suggestion:"Replace any with specific types"}),t}var Mt=null,Ii=null,fe=null,$d=Number(process.env.AQE_ROUTE_TIMEOUT_MS)||5e3;function Gd(o,e,t){return new Promise(n=>{let r=!1,i=setTimeout(()=>{r||(r=!0,n(t))},e);typeof i.unref=="function"&&i.unref(),o.then(s=>{r||(r=!0,clearTimeout(i),n(s))},()=>{r||(r=!0,clearTimeout(i),n(t))})})}function jd(){if(!Mt){let{kernel:o}=It();if(!o)throw new Error("Kernel not initialized");Mt=Jo(o);let e=Mt;Ii=sc().then(t=>(e.setQualityFeedbackLoop(t),t)).catch(t=>(console.warn("[HandlerFactory] Failed to initialize QualityFeedbackLoop:",t),null))}return Mt}function pc(){if(Mt=null,fe){let o=fe;fe=null,o.dispose().catch(()=>{})}}async function gc(){if(fe)return fe;try{let{kernel:o}=It();if(!o)return null;let{createAQELearningEngine:e}=await import("./aqe-learning-engine-O6NJBCCM.js"),t=o.memory,n=e(t,{projectRoot:process.cwd(),enableClaudeFlow:!1});return await n.initialize(),fe=n,fe}catch(o){return console.debug("[HandlerFactory] Learning engine init failed:",w(o)),null}}async function zd(o,e){try{let t=await gc();if(!t)return[];let n=e,r=await t.searchPatterns(o,{limit:5,minConfidence:.4,domain:n,useVectorSearch:!0});return!r.success||r.value.length===0?[]:r.value.filter(i=>i.similarity>=.4).map(i=>({name:i.pattern.name,description:i.pattern.description,similarity:i.similarity,confidence:i.pattern.confidence,canReuse:i.canReuse,patternId:i.pattern.id}))}catch(t){return console.debug("[HandlerFactory] Pattern search failed:",w(t)),[]}}async function Ud(o,e,t){try{let n=await zd(o,e);return n.length>0&&console.debug(`[HandlerFactory] Found ${n.length} relevant patterns for ${e}`),await(await On()).routeTask({task:o,domain:e,codeContext:t,agentType:`qe-${e}`,enablePatternSearch:!0,patternHints:n.length>0?n:void 0})}catch(n){return console.error(`[HandlerFactory] Routing failed for ${e}: ${n}`),null}}async function Bd(o,e,t,n,r){if(!o||o.length===0||!e.measured||!fe)return;let i=e.success===!0;try{for(let s of o)s.patternId&&await fe.recordOutcome({patternId:s.patternId,success:i,metrics:{executionTimeMs:n,...xs(e,r)},feedback:`Domain handler ${t} outcome ${i?"succeeded":"failed"} (${e.basis})`})}catch{}}function se(o){let{domain:e,taskType:t,priority:n="p1",defaultTimeout:r=18e4,buildTaskDescription:i,mapToPayload:s,mapToResult:a,calculateTimeout:c,includeCodeContext:l}=o;return async u=>{if(!rt())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:d}=It(),m=null;try{let p=ec(u),f=i(u),g=l?.(u);m=await Gd(Ud(f,e,g),$d,null);let h=s(u,m);p||(h.saveResults=!1);let y=c?.(u)??r,v=await d.submitTask({type:t,executionOwner:"caller",priority:n,targetDomains:[e],payload:h,timeout:y});if(!v.success)return{success:!1,error:v.error.message};let b=jd(),C=d.getTaskStatus(v.value);if(!C)return{success:!1,error:"Task not found after submission"};let E=await b.execute(C.task);if(!E.success)return{success:!1,error:E.error?je(E.error,Number.POSITIVE_INFINITY):"Task execution failed",...E.errorDetails?{data:E.errorDetails}:{}};let T=E.data,S=a(v.value,T,E.duration,E.savedFiles,u);if(Object.assign(S,Hn(p,E.savedFiles)),Ke(e,T)&&Ke("",S)){let k=Pr(t,S);Bd(m?.patternHints,k,e,E.duration,v.value),Nd(`qe-${e}`,t,u,T,E.duration,k,v.value).catch(()=>{});try{await qd(e,T,E.duration,u)}catch{}}return{success:!0,data:S}}catch(p){let f=w(p),g=$e(p);return{success:!1,error:je(`Failed to ${t.replace(/-/g," ")}: ${f}`,Number.POSITIVE_INFINITY),...g?{data:{callerError:!0}}:{}}}}}var Vn=class{taskMetrics=[];agentMetrics=new Map;resourceSnapshots=[];workerLoads=new Map;activeTasks=new Map;lastCpuUsage=null;snapshotInterval=null;initialized=!1;initialize(){this.initialized||(this.initialized=!0,this.lastCpuUsage=process.cpuUsage(),this.snapshotInterval=setInterval(()=>{this.takeResourceSnapshot()},1e3),this.snapshotInterval.unref&&this.snapshotInterval.unref())}shutdown(){this.snapshotInterval&&(clearInterval(this.snapshotInterval),this.snapshotInterval=null),this.initialized=!1}startTask(e,t){this.ensureInitialized();let n={taskId:e,agentId:t,startTime:process.hrtime(),success:!1,retries:0};this.activeTasks.set(e,n),this.updateWorkerLoad(t,1,0)}recordRetry(e){let t=this.activeTasks.get(e);t&&t.retries++}completeTask(e,t){let n=this.activeTasks.get(e);if(!n)return 0;n.endTime=process.hrtime(),n.success=t;let r=process.hrtime(n.startTime);return n.durationMs=r[0]*1e3+r[1]/1e6,this.updateAgentMetrics(n),this.updateWorkerLoad(n.agentId,-1,1),this.taskMetrics.push(n),this.taskMetrics.length>100&&this.taskMetrics.shift(),this.activeTasks.delete(e),n.durationMs}getCpuUsagePercent(){if(this.ensureInitialized(),!this.lastCpuUsage)return this.lastCpuUsage=process.cpuUsage(),0;let e=process.cpuUsage(this.lastCpuUsage);this.lastCpuUsage=process.cpuUsage();let t=e.user+e.system,r=1e3*1e3,i=t/r*100;return Math.min(100,Math.max(0,i))}getMemoryUsagePercent(){let e=process.memoryUsage(),t=e.heapUsed/e.heapTotal*100;return Math.min(100,Math.max(0,t))}getResourceStats(e){return{cpu:this.getCpuUsagePercent(),memory:this.getMemoryUsagePercent()}}getAgentTaskStats(e){let t=this.agentMetrics.get(e);if(!t||t.taskCount===0)return{tasksCompleted:0,averageTime:0,successRate:1};let n=t.tasksCompleted+t.tasksFailed,r=n>0?t.tasksCompleted/n:1,i=t.taskCount>0?t.totalDurationMs/t.taskCount:0;return{tasksCompleted:t.tasksCompleted,averageTime:Math.round(i),successRate:Math.min(1,Math.max(0,r))}}getRecordedTaskCount(){return this.taskMetrics.length}getWorkerEfficiency(){if(this.taskMetrics.length===0)return null;let t=this.taskMetrics.filter(a=>a.success).length/this.taskMetrics.length,r=this.taskMetrics.reduce((a,c)=>a+c.retries,0)/this.taskMetrics.length,i=Math.min(.2,r*.1),s=t*(1-i);return Math.min(1,Math.max(0,s))}getLoadBalanceScore(){if(this.workerLoads.size===0)return null;let e=Array.from(this.workerLoads.values()).map(a=>a.completedTaskCount);if(e.length<=1)return 1;let t=e.reduce((a,c)=>a+c,0)/e.length;if(t===0)return 1;let n=e.reduce((a,c)=>a+Math.pow(c-t,2),0)/e.length,s=1/(1+Math.sqrt(n)/t);return Math.min(1,Math.max(0,s))}getRetryStats(){let e=0,t=0,n=0;for(let r of this.agentMetrics.values())e+=r.totalRetries,t+=r.successfulRetries,n+=r.maxRetriesReached;return{totalRetries:e,successfulRetries:t,maxRetriesReached:n}}getAverageExecutionTime(){if(this.taskMetrics.length===0)return 0;let e=this.taskMetrics.reduce((t,n)=>t+(n.durationMs||0),0);return Math.round(e/this.taskMetrics.length)}getWorkersUsed(){return this.workerLoads.size}recordSuccessfulRetry(e){let t=this.agentMetrics.get(e);t&&t.successfulRetries++}recordMaxRetriesReached(e){let t=this.agentMetrics.get(e);t&&t.maxRetriesReached++}reset(){this.taskMetrics=[],this.agentMetrics.clear(),this.resourceSnapshots=[],this.workerLoads.clear(),this.activeTasks.clear(),this.lastCpuUsage=null}ensureInitialized(){this.initialized||this.initialize()}updateAgentMetrics(e){let t=this.agentMetrics.get(e.agentId);t||(t={agentId:e.agentId,tasksCompleted:0,tasksFailed:0,totalRetries:0,successfulRetries:0,maxRetriesReached:0,totalDurationMs:0,taskCount:0},this.agentMetrics.set(e.agentId,t)),e.success?(t.tasksCompleted++,e.retries>0&&t.successfulRetries++):t.tasksFailed++,t.totalRetries+=e.retries,t.totalDurationMs+=e.durationMs||0,t.taskCount++}updateWorkerLoad(e,t,n){let r=this.workerLoads.get(e);r||(r={workerId:e,activeTaskCount:0,completedTaskCount:0,lastActivityTime:Date.now()},this.workerLoads.set(e,r)),r.activeTaskCount=Math.max(0,r.activeTaskCount+t),r.completedTaskCount+=n,r.lastActivityTime=Date.now()}takeResourceSnapshot(){let e=process.memoryUsage(),t=process.cpuUsage(),n={timestamp:Date.now(),cpuUser:t.user,cpuSystem:t.system,memoryHeapUsed:e.heapUsed,memoryHeapTotal:e.heapTotal,memoryExternal:e.external,memoryRss:e.rss};this.resourceSnapshots.push(n),this.resourceSnapshots.length>60&&this.resourceSnapshots.shift()}},Dt=new Vn;M();Tl();var _i="^(?:UNKNOWN|[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,255})$",Oi="(?:^|[._:/@+\\-])(?:(?:[sS][kK]|[rR][kK]|[gG][hH][pPoOuUsSrR]|[gG][iI][tT][hH][uU][bB]_[pP][aA][tT]|[xX][oO][xX][bBaApPrRsS]|[nN][pP][mM]|[gG][lL][pP][aA][tT]|[pP][aA][tT])(?:[-_][A-Za-z0-9_-]*|(?=$|[.:/@+\\-]))|(?:[aA][kK][iI][aA]|[aA][sS][iI][aA]|[aA][iI][zZ][aA])[A-Za-z0-9]*)",Ni="(?:^|[^A-Za-z0-9_-])(?:eyJ[A-Za-z0-9_-]*|e30|ew[A-Za-z0-9_-]*)\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+(?:$|[^A-Za-z0-9_-])",Fi="(?:^|[._:/@+\\-])[A-Za-z0-9]{32,}(?:$|[._:/@+\\-])",Li="(?:(?:^|[.:@\\-])[A-Za-z0-9+/]{32,}={0,2}(?:$|[.:@\\-])|(?:^|[.:/@+\\-])[A-Za-z0-9_-]{48,}(?:$|[.:/@+\\-]))",qi="^\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])T(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d{1,9})?Z$",Pb=new RegExp(_i),xb=new RegExp(Oi),Ab=new RegExp(Ni),kb=new RegExp(Fi),Mb=new RegExp(Li),Ib=new RegExp(qi);function Hd(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function Vd(o){return Array.isArray(o)&&o.every(e=>typeof e=="string")}function Qd(o){return typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=1}function hc(o){let e=[];return Hd(o)?(o.contract!=="risk-decision@1"&&e.push('contract must be "risk-decision@1"'),["approve","block","escalate"].includes(o.decision)||e.push("decision must be approve|block|escalate"),Vd(o.riskFactors)||e.push("riskFactors must be string[]"),Qd(o.confidence)||e.push("confidence must be a number in [0,1]"),(typeof o.rationale!="string"||o.rationale.length===0)&&e.push("rationale must be a non-empty string"),{valid:e.length===0,errors:e}):{valid:!1,errors:["not an object"]}}var Wd=.7;function yc(o){let{passed:e,qualityScore:t,recommendations:n=[],unmeasured:r=[],failedMetrics:i=[],gateEvaluated:s}=o,a=s===!1?" (no quality gate was evaluated)":"",c=typeof t=="number"?` with score ${t}`:"";if(i.length>0){let m=r.length>0?`; also unmeasured: ${r.join(", ")}`:"";return{contract:"risk-decision@1",decision:"block",riskFactors:[`failed: ${i.join(", ")}`,...r.length>0?[`unmeasured: ${r.join(", ")}`]:[],...n].slice(0,10),confidence:.9,rationale:`Measured ${i.join(", ")} failed its threshold${m}${a}`}}if(r.length>0){let m=typeof o.evidenceConfidence=="number"&&Number.isFinite(o.evidenceConfidence)?Math.min(1,Math.max(0,o.evidenceConfidence)):0;return{contract:"risk-decision@1",decision:"escalate",riskFactors:[`unmeasured: ${r.join(", ")}`,...n].slice(0,10),confidence:Math.round(.5*m*100)/100,rationale:`Insufficient evidence: ${r.join(", ")} not measured${a} \u2014 measure the missing metrics or run the measured quality gate before deciding`}}let l=e===!0?"approve":e===!1?"block":"escalate",u=s===!1?"Static analysis":"Quality gate",d=l==="escalate"?.5:l==="approve"&&s===!1?Wd:.9;return{contract:"risk-decision@1",decision:l,riskFactors:n.slice(0,10),confidence:d,rationale:l==="escalate"?"Quality gate outcome indeterminate \u2014 manual review required":`${u} ${e?"passed":"failed"}${c}${a}`}}var Kd={type:"number",minimum:0,maximum:1},fc={type:"array",items:{type:"string"}};function it(o){return{type:"string",pattern:_i,allOf:[{not:{pattern:Oi}},{not:{pattern:Ni}},{not:{pattern:o==="provider"||o==="requestedModel"||o==="resolvedModel"?Fi:Li}}]}}var st={type:"string",pattern:"^(?:UNKNOWN|sha256:[a-f0-9]{64})$"},ae={type:"string",pattern:"^sha256:[a-f0-9]{64}$"};var Fb={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://agentic-qe.dev/schemas/finding-verdict.schema.json",title:"FindingVerdict",type:"object",required:["contract","id","title","severity","confidence","evidence","verdict","refutations"],additionalProperties:!0,properties:{contract:{const:"finding-verdict@1"},id:{type:"string",minLength:1},title:{type:"string",minLength:1},file:{type:"string"},severity:{enum:["critical","high","medium","low","info"]},confidence:Kd,evidence:fc,verdict:{enum:["upheld","refuted","uncertain"]},refutations:fc,measurementReceipts:{type:"array",items:{type:"object",required:["contract","provider","requestedModel","resolvedModel","endpointClass","snapshotIdentity","semantics","fingerprint","requestHash","promptHash","configHash","parserSchemaHash","outputHash","parsedVoteHash","temperature","topP","seed","deterministic","cacheStatus","retryCount","timestamp","windowId","latencyMs","requestId"],additionalProperties:!1,properties:{contract:{const:"judge-measurement@1"},provider:it("provider"),requestedModel:it("requestedModel"),resolvedModel:it("resolvedModel"),endpointClass:{enum:["shared","dedicated","local","UNKNOWN"]},snapshotIdentity:{enum:["L0_UNKNOWN","L1_NAMED","L2_CONTENT_BOUND"]},semantics:{enum:["verified","provider-asserted","UNKNOWN"]},fingerprint:it("fingerprint"),requestHash:st,promptHash:st,configHash:st,parserSchemaHash:st,outputHash:st,parsedVoteHash:st,temperature:{type:["number","null"],minimum:0},topP:{type:["number","null"],minimum:0,maximum:1},seed:{type:["integer","null"],minimum:Number.MIN_SAFE_INTEGER,maximum:Number.MAX_SAFE_INTEGER},deterministic:{type:["boolean","null"]},cacheStatus:{enum:["hit","miss","bypass","UNKNOWN"]},retryCount:{type:"integer",minimum:0,maximum:Number.MAX_SAFE_INTEGER},timestamp:{anyOf:[{const:"UNKNOWN"},{type:"string",pattern:qi,format:"date-time"}]},windowId:it("windowId"),latencyMs:{type:["number","null"],minimum:0},requestId:it("requestId")},allOf:[{if:{properties:{snapshotIdentity:{const:"L2_CONTENT_BOUND"}}},then:{properties:{fingerprint:{not:{const:"UNKNOWN"}},requestHash:ae,promptHash:ae,configHash:ae,parserSchemaHash:ae,outputHash:ae,parsedVoteHash:ae}}},{if:{properties:{snapshotIdentity:{const:"L1_NAMED"}}},then:{properties:{resolvedModel:{not:{const:"UNKNOWN"}}}}},{if:{properties:{semantics:{const:"verified"}}},then:{properties:{snapshotIdentity:{const:"L2_CONTENT_BOUND"},fingerprint:{not:{const:"UNKNOWN"}},requestHash:ae,promptHash:ae,configHash:ae,parserSchemaHash:ae,outputHash:ae,parsedVoteHash:ae}}},{if:{properties:{semantics:{enum:["verified","provider-asserted"]}}},then:{properties:{snapshotIdentity:{not:{const:"L0_UNKNOWN"}},fingerprint:{not:{const:"UNKNOWN"}}}}}]}}}};var vc=Object.keys(rn);function Xd(o){if(!o)return"typescript";let e=o.toLowerCase().trim(),t={ts:"typescript",js:"javascript",py:"python","c#":"csharp","c-sharp":"csharp",cs:"csharp",golang:"go",rs:"rust",kt:"kotlin"};return t[e]?t[e]:vc.includes(e)?e:null}var bc={domain:"test-generation",taskType:"generate-tests",priority:"p1",defaultTimeout:12e4,buildTaskDescription:o=>`Generate ${o.testType||"unit"} tests for ${o.language||"typescript"} code`,includeCodeContext:o=>o.sourceCode,mapToPayload:(o,e)=>{let t=Xd(o.language);if(t===null)throw new Error(`Unsupported language '${o.language}'. Supported languages: ${vc.join(", ")}. Open a feature request for additional language support.`);let n;if(o.framework){n=o.framework;let i=Object.hasOwn(Dr,n)?Dr[n]:void 0;if(i&&i!==t){let s=a=>a==="javascript"||a==="typescript";if(!(s(i)&&s(t)))throw new Error(`Framework '${n}' targets ${i}, but language was '${t}'. Either pick a matching framework or omit \`framework\` to use the default (${rn[t]}).`)}}else n=rn[t];let r=nn(o.behaviorExamples);return{sourceCode:o.sourceCode,behaviorExamples:r,filePath:o.filePath,language:t,framework:n,testType:o.testType||"unit",coverageGoal:o.coverageGoal||80,aiEnhancement:o.aiEnhancement!==!1,detectAntiPatterns:o.detectAntiPatterns||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(o,e,t,n,r)=>{let i=r?.sourceCode||"",s=r?.language||"typescript",a=r?.testType||"unit",c=e.testsGenerated||6,l=lc(i),u=r?.aiEnhancement!==!1?uc(l,a):{recommendations:[],estimatedTime:"0 minutes",confidence:0},d=r?.detectAntiPatterns?mc(i,s):[],m=Di("test-generator"),p=e.tests,f=Array.isArray(p)&&p.length>0&&p[0].testCode,g=e.llmEnhanced===!0,h=f?p.map((y,v)=>({id:nt(),name:y.name||`test_${v}`,type:y.type||a,parameters:[],assertions:y.testCode?Yd(y.testCode):[`test assertion ${v}`],expectedResult:null,estimatedDuration:y.type==="integration"?2e3:1e3,aiGenerated:g,testCode:y.testCode,generationMode:y.generationMode,generationLimits:y.generationLimits,sourceFile:y.sourceFile,testFile:y.testFile||y.file})):dc(i,a,s,c);return{tests:h,antiPatterns:d,suggestions:d.map(y=>`Fix: ${y.type} - ${y.suggestion}`),aiInsights:u,coverage:{predicted:e.coverageEstimate??null,confidence:e.coverageEstimate==null?0:g?.9:0,achievable:e.coverageEstimate==null?null:!0},properties:h.filter(y=>y.type==="property").map(y=>({name:y.name,invariant:"output_matches_expectation"})),language:s,complexity:l,learning:m,taskId:o,status:"completed",testsGenerated:h.length,coverageEstimate:e.coverageEstimate??null,patternsUsed:e.patternsUsed||["assertion-patterns","mock-generation","edge-case-detection"],duration:t,...Hn(r?.saveResults!==!1,n),llmEnhanced:g,...e.generationMode?{generationMode:e.generationMode}:{},...e.note?{note:e.note}:{}}}},Cc={domain:"test-execution",taskType:"execute-tests",priority:"p1",defaultTimeout:3e5,buildTaskDescription:o=>`Execute ${o.testFiles?.length||0} test files with ${o.parallel!==!1?"parallel":"sequential"} execution`,mapToPayload:(o,e)=>({testFiles:o.testFiles||[],testSuites:o.testSuites||[],parallel:o.parallel!==!1,parallelism:o.parallelism||4,retryCount:o.retryCount??2,timeout:o.timeout||6e4,collectCoverage:o.collectCoverage||!1,reportFormat:o.reportFormat||"json",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext,...o.projectRoot!==void 0?{projectRoot:o.projectRoot}:{}}),calculateTimeout:o=>o.timeout||3e5,mapToResult:(o,e,t,n)=>{let r=e.total||0,i=e.passed||0,s=e.failed||0,a=typeof e.flaky=="number"&&e.flaky>0?e.flaky:void 0,c=typeof e.coverage=="number"&&Number.isFinite(e.coverage)?e.coverage:null,l=[],u={},d=(T,S)=>{l.push(T),u[T]=S},m=Array.isArray(e.testCases)?e.testCases:void 0,p=m?.map(T=>({id:nt(),...T}));p||d("results","The test runner report did not list every test case, so per-test results are omitted.");let f=(m??[]).map(T=>T.duration).filter(T=>typeof T=="number"&&Number.isFinite(T)),g=f.length>0?f.reduce((T,S)=>T+S,0)/f.length:void 0;if(g===void 0){let T="The runner reported no per-test durations; the task wall time is in `duration`.";d("workerStats.avgExecutionTime",T),d("summary.avgDuration",T)}let h=g!==void 0?{avgExecutionTime:g}:{},y="No worker tasks were recorded by the metrics collector for this process.",v=Dt.getWorkersUsed();v>0?h.workersUsed=v:d("workerStats.workersUsed",y);let b=Dt.getWorkerEfficiency();b!==null?h.efficiency=b:d("workerStats.efficiency",y);let C=Dt.getLoadBalanceScore();C!==null?h.loadBalance=C:d("workerStats.loadBalance",y);let E;return e.retries&&typeof e.retries=="object"?E={...e.retries}:d("retryStats","The run reported no retry outcome: no retries were requested, or the retry step failed."),{workerStats:h,...E?{retryStats:E}:{},...p?{results:p}:{},summary:{totalTests:r,passRate:r>0?i/r*100:0,...a!==void 0?{flaky:a}:{},...g!==void 0?{avgDuration:g}:{},...b!==null?{parallelEfficiency:b}:{}},...l.length>0?{unmeasured:l,unmeasuredReasons:u}:{},taskId:o,status:"completed",total:r,passed:i,failed:s,...a!==void 0?{flaky:a}:{},duration:t,coverage:c,savedFiles:n}}},Sc={domain:"coverage-analysis",taskType:"analyze-coverage",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Analyze coverage for ${o.target||"project"} with gap detection`,mapToPayload:(o,e)=>({target:o.target||".",includeRisk:o.includeRisk||!1,detectGaps:o.detectGaps!==!1,mlPowered:o.mlPowered||!1,prioritization:o.prioritization||"complexity",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>{let r=e.summary,i=r?.files??e.totalFiles??0,s=e.gaps||[],a=e.branchDataCollected===!0,c=e.functionDataCollected===!0,l=a?r?.branch??e.branchCoverage??null:null,u=c?r?.function??e.functionCoverage??null:null,d=e.estimated===!0,m=e.measured===!0,f=r?.line??e.lineCoverage??null,g=r?.statement??e.statementCoverage,h=g===void 0?f:g,y=Di("coverage-analyzer"),v=s.map((E,T)=>{let S=E;return S?.file?{id:`gap-${Date.now()}-${T}`,file:S.file,line:S.lines?.[0]||0,uncoveredLines:S.lines||[],type:S.type||"uncovered-line",severity:S.severity||"medium",reason:S.reason||"Missing test case",priority:S.priority||"medium",suggestion:S.suggestedTest||"Add test coverage",suggestedTest:S.suggestedTest||"Add test coverage",riskScore:S.riskScore||.5,confidence:S.confidence??(m?.7:.2),estimated:S.estimated===!0||d}:null}).filter(E=>E!==null),b=e.coverageByFile;return{coverageByFile:b?b.map(E=>({file:E.file,lineCoverage:E.lineCoverage||0,branchCoverage:E.branchCoverage??null,functionCoverage:E.functionCoverage??null})):[],gapAnalysis:{totalGaps:v.length,highPriority:v.filter(E=>E.priority==="high").length,gaps:v},trends:{lineCoverageTrend:i>0?"stable":"no-data",branchCoverageTrend:i>0?"stable":"no-data",weeklyChange:0},aiInsights:i>0?{recommendations:d?["ESTIMATED RESULT \u2014 no instrumentation ran. The figures below are a static guess from source shape, not measured coverage. Do not act on individual gaps without running real instrumentation first.",...e.recommendations||[]]:e.recommendations||["Run tests with coverage enabled to get accurate metrics"],riskAssessment:d||!m||f===null?"unknown":f<70?"high":f<85?"medium":"low",confidence:d?.2:m?.88:0}:{recommendations:["No coverage data found. Run tests with coverage first (e.g., npm test -- --coverage, or pytest --cov)"],riskAssessment:"unknown",confidence:0},learning:y,taskId:o,status:"completed",lineCoverage:f,branchCoverage:l,functionCoverage:u,statementCoverage:h,totalFiles:i,gaps:v,duration:t,savedFiles:n,estimated:d,measured:m,coverageMethod:e.coverageMethod??"unknown",branchDataCollected:a,functionDataCollected:c,...e.runStatus==="passed"||e.runStatus==="failed"?{runStatus:e.runStatus}:{},...e.unmeasured===!0?{unmeasured:!0}:{},...e.evidenceStatus==="complete"||e.evidenceStatus==="insufficient-evidence"?{evidenceStatus:e.evidenceStatus}:{},...Array.isArray(e.unmeasuredFiles)?{unmeasuredFiles:e.unmeasuredFiles}:{},...e.staleReport?{staleReport:e.staleReport}:{},...e.warning?{warning:e.warning}:{}}}},Tc={domain:"quality-assessment",taskType:"assess-quality",priority:"p0",defaultTimeout:18e4,buildTaskDescription:o=>`Assess quality with ${o.runGate?"quality gate":"metrics analysis"}`,mapToPayload:(o,e)=>{if(o.runGate!==void 0&&typeof o.runGate!="boolean")throw new Error("runGate must be a boolean.");let t=o.metrics===void 0?["coverage","complexity","maintainability"]:un(o.metrics);if(o.target!==void 0&&(typeof o.target!="string"||o.target.trim()===""))throw new re("target must be a non-empty string path.");if(o.sourceFiles!==void 0&&(!Array.isArray(o.sourceFiles)||o.sourceFiles.length===0||o.sourceFiles.some(n=>typeof n!="string"||n.trim()==="")))throw new re("sourceFiles must be a non-empty array of file paths.");return{runGate:o.runGate??!1,...o.target!==void 0?{target:o.target}:{},...o.sourceFiles!==void 0?{sourceFiles:o.sourceFiles}:{},threshold:o.threshold||80,thresholdSource:o.threshold===void 0?"default":"request",metrics:t,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(o,e,t,n)=>{let r=Array.isArray(e.unmeasured)?e.unmeasured.filter(f=>typeof f=="string"):void 0,i=(r?.length??0)>0||e.evidenceStatus===Ve,s=typeof e.gateEvaluated=="boolean"?e.gateEvaluated:void 0,a=typeof e.confidence=="number"?e.confidence:void 0,c=Array.isArray(e.measuredFailures)?e.measuredFailures:void 0,l=(c??[]).map(f=>f.metric),u=e.unmeasuredReasons&&typeof e.unmeasuredReasons=="object"&&Object.values(e.unmeasuredReasons).every(f=>typeof f=="string")?e.unmeasuredReasons:void 0,d=typeof e.qualityScore=="number"&&e.qualityScore>=0?e.qualityScore:void 0,m=!i&&l.length===0&&e.passed===!0,p=yc({passed:i||l.length>0?!1:typeof e.passed=="boolean"?e.passed:void 0,qualityScore:i?void 0:d,recommendations:e.recommendations||[],unmeasured:i?r?.length?r:["unknown"]:[],failedMetrics:l,evidenceConfidence:a,gateEvaluated:s});return{taskId:o,status:i?Ve:"completed",...typeof e.qualityScore=="number"?{qualityScore:i&&!Array.isArray(e.checks)?-1:e.qualityScore}:{},...typeof e.qualityScoreReason=="string"?{qualityScoreReason:e.qualityScoreReason}:{},...typeof e.subsetScore=="number"?{subsetScore:e.subsetScore}:i&&d!==void 0&&!Array.isArray(e.checks)?{subsetScore:d}:{},...Array.isArray(e.checks)?{checks:e.checks}:{},passed:m,metrics:e.metrics||{},recommendations:e.recommendations||[],...e.evidenceStatus==="measured"||i?{evidenceStatus:i?Ve:"measured"}:{},...r?{unmeasured:r}:{},...u?{unmeasuredReasons:u}:{},...Array.isArray(e.partialMetrics)?{partialMetrics:e.partialMetrics}:{},...Array.isArray(e.excludedFiles)?{excludedFiles:e.excludedFiles}:{},...typeof e.excludedCount=="number"?{excludedCount:e.excludedCount}:{},...typeof e.scope=="string"?{scope:e.scope}:{},...Array.isArray(e.scoreBasis)&&e.scoreBasis.every(f=>typeof f=="string")?{scoreBasis:e.scoreBasis}:{},...c?{measuredFailures:c}:{},...s!==void 0?{gateEvaluated:s}:{},...a!==void 0?{confidence:a}:{},...typeof e.note=="string"?{note:e.note}:{},duration:t,savedFiles:n,...hc(p).valid?{riskDecision:p}:{}}}},Ec={domain:"security-compliance",taskType:"scan-security",priority:"p0",defaultTimeout:6e5,buildTaskDescription:o=>{let e=[];return o.sast!==!1&&e.push("SAST"),o.dast&&e.push("DAST"),o.dependencies&&e.push("dependency advisories"),`Security scan (${e.join(", ")}) for ${o.target||"project"}`},mapToPayload:(o,e)=>{for(let t of["sast","dast","dependencies"])if(o[t]!==void 0&&typeof o[t]!="boolean")throw new Error(`${t} must be a boolean`);return{sast:o.sast!==!1,dast:o.dast||!1,dependencies:o.dependencies===!0,compliance:o.compliance||[],target:o.target||".",targetUrl:o.targetUrl,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(o,e,t,n)=>({taskId:o,status:e.evidence?.completeness==="complete"?"completed":e.evidence?.completeness==="partial"?"partial":e.evidence?"unavailable":"unverified",vulnerabilities:e.vulnerabilities||0,critical:e.critical||0,high:e.high||0,medium:e.medium||0,low:e.low||0,informational:e.informational||0,topVulnerabilities:e.topVulnerabilities||[],findings:e.findings,recommendations:e.recommendations||[],evidence:e.evidence,limitations:e.limitations||["Execution receipts unavailable; scan completeness is unverified."],...e.evidence?{filesScanned:e.filesScanned,jstsFilesScanned:e.jstsFilesScanned,otherFilesScanned:e.otherFilesScanned,coverage:e.coverage}:{},deepAnalysisPerformed:!!(e.evidence&&e.deepAnalysisPerformed===!0),analysisDepth:e.analysisDepth,scanTypes:e.scanTypes,...e.dependencyScan?{dependencyScan:e.dependencyScan}:{},note:e.note,duration:t,savedFiles:n})},wc={domain:"contract-testing",taskType:"validate-contracts",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Validate API contract at ${o.contractPath}`,mapToPayload:(o,e)=>({contractPath:o.contractPath,providerUrl:o.providerUrl,consumerName:o.consumerName,checkBreakingChanges:o.checkBreakingChanges!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",valid:e.valid||!1,breakingChanges:e.breakingChanges||[],warnings:e.warnings||[],duration:t,savedFiles:n})},Rc={domain:"visual-accessibility",taskType:"test-accessibility",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Test accessibility for ${o.url} against ${o.standard||"WCAG 2.1 AA"} standard`,mapToPayload:(o,e)=>({url:o.url,standard:o.standard||"wcag21-aa",includeScreenReader:o.includeScreenReader||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:e.measured===!0?"completed":"not-measured",passed:e.passed||!1,score:e.measured===!0&&typeof e.score=="number"?e.score:-1,violations:e.violations||[],warnings:e.warnings||[],measured:e.measured===!0,...typeof e.note=="string"?{note:e.note}:{},duration:t,savedFiles:n})},Pc={domain:"chaos-resilience",taskType:"run-chaos",priority:"p2",defaultTimeout:9e4,buildTaskDescription:o=>`Run chaos test with ${o.faultType||"latency"} fault injection on ${o.target}`,mapToPayload:(o,e)=>({faultType:o.faultType||"latency",target:o.target,duration:o.duration||3e4,intensity:o.intensity||50,dryRun:o.dryRun!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:o=>(o.duration||3e4)+6e4,mapToResult:(o,e,t,n)=>{let r=e.resilience??null,i=e.systemBehavior!=="not-executed"&&r!==null;return{taskId:o,status:i?"completed":"not-executed",faultType:e.faultType||"latency",resilience:i?r:null,...typeof e.note=="string"?{note:e.note}:{},duration:t,savedFiles:n}}},xc={domain:"defect-intelligence",taskType:"predict-defects",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Predict defects in ${o.target||"codebase"} with ${o.lookback||30} day lookback`,mapToPayload:(o,e)=>({target:o.target||".",lookback:o.lookback||30,minConfidence:o.minConfidence||.7,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",...e.predictionMethod==="static-code-indicators"?{predictionMethod:"static-code-indicators",estimated:!0,filesAnalyzed:e.filesAnalyzed,filesSkipped:e.filesSkipped,scanStatus:e.scanStatus}:{},...e.retention==="failed"?{retention:"failed",retentionError:String(e.retentionError??"")}:{},predictedDefects:e.predictedDefects||[],riskScore:e.riskScore||0,recommendations:e.recommendations||[],duration:t,savedFiles:n})},Ac={domain:"requirements-validation",taskType:"validate-requirements",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Validate requirements${o.generateBDD?" and generate BDD scenarios":""}`,mapToPayload:(o,e)=>({requirementsPath:o.requirementsPath,testPath:o.testPath,generateBDD:o.generateBDD||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",requirementsAnalyzed:e.requirementsAnalyzed||0,testable:e.testable||0,coverage:e.coverage||0,bddScenarios:e.bddScenarios||[],duration:t,savedFiles:n})},kc={domain:"code-intelligence",taskType:"index-code",priority:"p2",defaultTimeout:3e5,buildTaskDescription:o=>`Index code in ${o.target||"codebase"}${o.incremental?" incrementally":""}`,mapToPayload:(o,e)=>({target:o.target||".",incremental:o.incremental||!1,gitSince:o.gitSince,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",filesIndexed:e.filesIndexed||0,symbolsExtracted:e.symbolsExtracted||0,relationsFound:e.relationsFound||0,...e.projectMetrics?{projectMetrics:e.projectMetrics}:{},...Array.isArray(e.warnings)&&e.warnings.length>0?{warnings:e.warnings}:{},...Array.isArray(e.skipped)&&e.skipped.length>0?{skipped:e.skipped}:{},duration:t,savedFiles:n})};function Yd(o){let e=[],t=o.split(`
456
+ `);for(let n of t){let r=n.trim(),i=r.match(/expect\((.+?)\)\.(to\w+)\((.+?)\)/);if(i){e.push(`expect(${i[1]}).${i[2]}(${i[3]})`);continue}let s=r.match(/assert\w*\((.+)\)/);if(s){e.push(s[0]);continue}let a=r.match(/(?:it|test)\s*\(\s*['"`](.+?)['"`]/);a&&e.push(a[1])}return e.length>0?e:["test generated from source analysis"]}function Mc(){pc()}var mC=se(bc),pC=se(Cc),gC=se(Sc),fC=se(Tc),hC=se(Ec),yC=se(wc),vC=se(Rc),bC=se(Pc),CC=se(xc),SC=se(Ac),TC=se(kc);M();var Wn=class extends A{config={name:"qe/tests/generate",description:"Generate tests for source code files. Supports unit, integration, and e2e tests with AI-powered pattern recognition.",domain:"test-generation",schema:Jd,streaming:!0,timeout:12e4};testGeneratorService=null;async getService(e){if(!this.testGeneratorService){let t=await $(),n=await Q(e);this.testGeneratorService=qs({memory:t,llmRouter:n},{defaultFramework:"vitest",maxTestsPerFile:50,coverageTargetDefault:80,enableAIGeneration:!0})}return this.testGeneratorService}async execute(e,t){let{sourceFiles:n,testType:r="unit",framework:i="vitest",language:s="typescript",coverageTarget:a=80,patterns:c=[],aiEnhancement:l=!0,detectAntiPatterns:u=!1}=e;try{let d=nn(e.behaviorExamples);if(this.emitStream(t,{status:"analyzing",message:`Analyzing ${n.length} source files`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};if(zr.isEnabled()){let v=`Generate ${r} tests for ${n.length} files using ${i}`,b=await zr.checkTaskEarlyExit(v,"test-generation");b.canExit&&b.reusedPattern&&(this.emitStream(t,{status:"pattern-reuse",message:`Reusing pattern: ${b.reusedPattern.name}`,tokensSaved:b.estimatedTokensSaved}),console.log(`[TestGenerateTool] Early exit: reusing pattern ${b.reusedPattern.name}, saving ~${b.estimatedTokensSaved} tokens`))}let m=await this.getService(t),p={behaviorExamples:d,sourceFiles:n,testType:r,framework:i,coverageTarget:a,patterns:c},f=await m.generateTests(p);if(!f.success)return{success:!1,error:f.error?.message||"Test generation failed"};let g=f.value,h=g.tests.map(v=>({id:v.id,name:v.name,sourceFile:v.sourceFile,testFile:v.testFile,testCode:v.testCode,type:v.type,assertions:v.assertions,generationMode:v.generationMode,generationLimits:v.generationLimits}));this.emitStream(t,{status:"generating",message:`Generated ${h.length} test files`,progress:50});let y=u?Zd(n):[];return this.emitStream(t,{status:"complete",message:"Test generation complete",progress:100}),{success:!0,data:{tests:h,coverageEstimate:g.coverageEstimate,patternsUsed:g.patternsUsed,suggestions:nm(h,l),antiPatterns:y.length>0?y:void 0}}}catch(d){return{success:!1,error:`Test generation failed: ${w(d)}`}}}resetInstanceCache(){this.testGeneratorService=null}},Jd={type:"object",properties:{behaviorExamples:{type:"array",description:"Trusted JSON specification fixtures: functionName, args, expected",items:Ls},sourceFiles:{type:"array",description:"Array of source file paths to generate tests for",items:{type:"string",description:"File path"}},testType:{type:"string",description:"Type of tests to generate",enum:["unit","integration","e2e"],default:"unit"},framework:{type:"string",description:"Test framework to use",enum:["jest","vitest","mocha","pytest"],default:"vitest"},language:{type:"string",description:"Programming language of source files",enum:["typescript","javascript","python","java","go"],default:"typescript"},coverageTarget:{type:"number",description:"Target code coverage percentage (0-100)",minimum:0,maximum:100,default:80},patterns:{type:"array",description:"Test patterns to apply",items:{type:"string",description:"Pattern name"}},aiEnhancement:{type:"boolean",description:"Enable AI-powered test enhancement",default:!0},detectAntiPatterns:{type:"boolean",description:"Detect and report anti-patterns in source code",default:!1}},required:["sourceFiles"]};function Zd(o){let e=[],t=hl("fs");for(let n of o)try{let r;try{r=t.readFileSync(n,"utf-8")}catch{continue}let i=r.split(`
457
+ `),s=/(?<![\w.])(\d{2,}|[2-9]\d*)(?![\w.])/g,a=new Set(["10","100","1000","60","24","365","404","500","200","201"]);i.forEach((f,g)=>{if(f.trim().startsWith("//")||f.trim().startsWith("*")||f.includes("import")||f.includes("require"))return;let h=f.match(s);if(h)for(let y of h){if(a.has(y))continue;let v=f.substring(0,f.indexOf(y)),b=(v.match(/'/g)||[]).length,C=(v.match(/"/g)||[]).length,E=(v.match(/`/g)||[]).length;if(!(b%2===1||C%2===1||E%2===1)){e.push({name:"magic-number",location:`${n}:${g+1}`,severity:"medium",suggestion:`Consider extracting ${y} into a named constant to improve readability and maintainability`});break}}});let c=/(?:it|test)\s*\(\s*['"`]([^'"`]+)['"`]\s*,/g,l;for(;(l=c.exec(r))!==null;){let f=l.index,g=l[1],h=r.substring(f),y=em(h);if(y){let v=/expect\s*\(/.test(y),b=/assert[\.\(]/.test(y),C=/\.should[\.\(]/.test(y),E=/\.toBe|\.toEqual|\.toMatch|\.toThrow|\.toContain/.test(y);if(!v&&!b&&!C&&!E){let T=r.substring(0,f).split(`
458
+ `).length;e.push({name:"no-assertions",location:`${n}:${T}`,severity:"high",suggestion:`Test "${g}" has no assertions. Add expect() or assert() calls to verify behavior`})}}}let u=[{pattern:/let\s+\w+\s*=\s*(?!undefined|null)/g,name:"mutable-let-declaration"},{pattern:/(?:^|\s)var\s+\w+\s*=/g,name:"mutable-var-declaration"}],d=r.match(/describe\s*\([^)]+,\s*(?:function\s*\(\)|(?:\(\s*\))?\s*=>)\s*\{/g);if(d)for(let f of d){let g=r.indexOf(f),h=tm(r.substring(g));if(h){let y=h.match(/^\s*let\s+(\w+)\s*(?::\s*\w+)?\s*(?:=|;)/m);if(y){let v=y[1];if((h.match(new RegExp(`(?:it|test)\\s*\\([^)]+,[^]*?${v}\\s*=`,"g"))||[]).length>=2){let C=r.substring(0,g+h.indexOf(y[0])).split(`
459
+ `).length;e.push({name:"test-interdependence",location:`${n}:${C}`,severity:"high",suggestion:`Shared mutable variable '${v}' is modified in multiple tests, causing test interdependence. Use beforeEach to reset state or isolate test data`})}}}}if(/\.test\.|\.spec\./.test(n)){let f=r.match(/import\s+.*from\s+['"].*(?:\.test|\.spec)['"]/g);f&&f.length>0&&e.push({name:"test-importing-tests",location:n,severity:"medium",suggestion:"Test file imports from another test file. Extract shared test utilities to a separate module"})}let m=/(?:it|test|describe)\s*\(\s*['"`]([^'"`]{100,})['"`]/g,p;for(;(p=m.exec(r))!==null;){let f=r.substring(0,p.index).split(`
460
+ `).length;e.push({name:"long-test-description",location:`${n}:${f}`,severity:"low",suggestion:"Test description is too long. Consider breaking into smaller, focused tests or using a more concise description"})}if(/setTimeout|setInterval/.test(r)&&!/useFakeTimers|fakeTimers|clock/.test(r)){let g=r.match(/setTimeout|setInterval/);if(g){let h=r.substring(0,r.indexOf(g[0])).split(`
461
+ `).length;e.push({name:"real-timers-in-tests",location:`${n}:${h}`,severity:"medium",suggestion:"Using real timers in tests can cause flakiness. Consider using fake timers (jest.useFakeTimers() or vi.useFakeTimers())"})}}}catch{continue}return e}function em(o){let e=0,t=-1,n=-1;for(let r=0;r<o.length;r++)if(o[r]==="{")t===-1&&(t=r),e++;else if(o[r]==="}"&&(e--,e===0&&t!==-1)){n=r;break}return t!==-1&&n!==-1?o.substring(t+1,n):null}function tm(o){let e=0,t=-1,n=-1;for(let r=0;r<o.length;r++)if(o[r]==="{")t===-1&&(t=r),e++;else if(o[r]==="}"&&(e--,e===0&&t!==-1)){n=r;break}return t!==-1&&n!==-1?o.substring(t+1,n):null}function nm(o,e){let t=[];return o.length===0&&t.push("No tests generated. Ensure source files are valid."),e&&(t.push("Consider adding property-based tests for edge case coverage"),t.push("Parameterized tests can reduce duplication")),t}M();tn();var Kn=class extends A{config={name:"qe/tests/execute",description:"Execute test suites with parallel execution, retry logic, and coverage collection. Detects flaky tests.",domain:"test-execution",schema:rm,streaming:!0,timeout:3e5};async execute(e,t){let{testFiles:n=[],testSuites:r=[],pattern:i,parallel:s=!0,parallelism:a=4,retryCount:c=2,collectCoverage:l=!1,failFast:u=!1}=e,d=Date.now();try{let m=n.length>0?n:r.length>0?r:i?[i]:["**/*.test.ts"];if(this.emitStream(t,{status:"starting",message:`Executing ${m.length} test files`,parallel:s,parallelism:a}),this.isAborted(t))return{success:!1,error:"Test execution aborted"};let p=[],f=[];for(let v=0;v<m.length;v++){let b=m[v];this.emitStream(t,{status:"running",message:`Executing ${b}`,progress:Math.round(v/m.length*100)});let C=be()>.1,E={id:`test-${v}`,name:`Test suite for ${b.split("/").pop()}`,file:b,status:C?"passed":"failed",duration:be()*5e3,error:C?void 0:"Assertion failed",retries:C?0:Math.min(c,2)};if(p.push(E),!C&&be()>.7&&f.push({name:E.name,file:E.file,flakinessScore:Ie(.5,1),failurePattern:"intermittent-timeout"}),u&&!C)break}let g={total:p.length,passed:p.filter(v=>v.status==="passed").length,failed:p.filter(v=>v.status==="failed").length,skipped:p.filter(v=>v.status==="skipped").length,pending:p.filter(v=>v.status==="pending").length,passRate:0};g.passRate=g.total>0?Math.round(g.passed/g.total*100):0;let h=l?{lines:Ie(70,100),branches:Ie(60,80),functions:Ie(65,90),statements:Ie(70,95)}:void 0,y=Date.now()-d;return this.emitStream(t,{status:"complete",message:`Test execution complete: ${g.passed}/${g.total} passed`,progress:100}),{success:g.failed===0,data:{summary:g,testResults:p,coverage:h,flakyTests:f.length>0?f:void 0,duration:y}}}catch(m){return{success:!1,error:`Test execution failed: ${w(m)}`}}}},rm={type:"object",properties:{testFiles:{type:"array",description:"Specific test files to execute",items:{type:"string",description:"Test file path"}},testSuites:{type:"array",description:"Test suite names to execute",items:{type:"string",description:"Suite name"}},pattern:{type:"string",description:"Glob pattern to match test files"},parallel:{type:"boolean",description:"Enable parallel test execution",default:!0},parallelism:{type:"number",description:"Number of parallel workers",minimum:1,maximum:16,default:4},retryCount:{type:"number",description:"Number of retries for failed tests",minimum:0,maximum:5,default:2},timeout:{type:"number",description:"Test timeout in milliseconds",minimum:1e3,default:6e4},collectCoverage:{type:"boolean",description:"Collect code coverage",default:!1},reportFormat:{type:"string",description:"Report output format",enum:["json","junit","html","markdown"],default:"json"},failFast:{type:"boolean",description:"Stop on first failure",default:!1},watch:{type:"boolean",description:"Watch mode for continuous testing",default:!1}}};te();import*as qc from"fs/promises";import*as D from"path";function he(o){return de(o,{outsideRoot:"allow"})}async function $i(o,e){let t=await he(o);return $c(t,e||D.dirname(o))}function $c(o,e){let t=new Map,n=o.split(`
462
+ `),r=null,i=new Map,s=[],a=[],c=0,l=0,u=0,d=0,m=0,p=0;for(let f of n){let g=f.trim();if(g.startsWith("SF:")){let h=g.slice(3);r={path:h,relativePath:D.relative(e,h)},i=new Map,s=[],a=[],c=0,l=0,u=0,d=0,m=0,p=0}else if(g.startsWith("DA:")){let[h,y]=g.slice(3).split(",").map(Number);!isNaN(h)&&!isNaN(y)&&(i.set(h,y),c++,y>0&&l++)}else if(g.startsWith("LF:")){let h=parseInt(g.slice(3),10);isNaN(h)||(c=h)}else if(g.startsWith("LH:")){let h=parseInt(g.slice(3),10);isNaN(h)||(l=h)}else if(g.startsWith("BRDA:")){let h=g.slice(5).split(",");if(h.length>=4){let y=parseInt(h[0],10),v=parseInt(h[1],10),b=parseInt(h[2],10),C=h[3]==="-"?0:parseInt(h[3],10);s.push({line:y,block:v,branch:b,taken:C>0,hits:C}),u++,C>0&&d++}}else if(g.startsWith("BRF:")){let h=parseInt(g.slice(4),10);isNaN(h)||(u=h)}else if(g.startsWith("BRH:")){let h=parseInt(g.slice(4),10);isNaN(h)||(d=h)}else if(g.startsWith("FN:")){let h=g.indexOf(",",3);if(h>0){let y=parseInt(g.slice(3,h),10),v=g.slice(h+1);a.find(C=>C.name===v)||a.push({name:v,line:y,hits:0})}}else if(g.startsWith("FNDA:")){let h=g.indexOf(",",5);if(h>0){let y=parseInt(g.slice(5,h),10),v=g.slice(h+1),b=a.find(C=>C.name===v);b?b.hits=y:a.push({name:v,line:0,hits:y}),m++,y>0&&p++}}else if(g.startsWith("FNF:")){let h=parseInt(g.slice(4),10);isNaN(h)||(m=h)}else if(g.startsWith("FNH:")){let h=parseInt(g.slice(4),10);isNaN(h)||(p=h)}else if(g==="end_of_record"&&r?.path){let h=Array.from(i.entries()).filter(([,C])=>C===0).map(([C])=>C).sort((C,E)=>C-E),y=s.filter(C=>!C.taken),v=a.filter(C=>C.hits===0).map(C=>C.name),b={path:r.path,relativePath:r.relativePath||r.path,lines:{total:c,covered:l,percentage:c>0?l/c*100:0,details:i,uncoveredLines:h},branches:{total:u,covered:d,percentage:u>0?d/u*100:0,uncoveredBranches:y},functions:{total:m,covered:p,percentage:m>0?p/m*100:0,details:a,uncoveredFunctions:v},statements:{total:c,covered:l,percentage:c>0?l/c*100:0},coveragePercentage:zi(l,c,d,u)};t.set(r.path,b),r=null}}return{timestamp:new Date,format:"lcov",files:t,summary:Oe(t)}}async function Gi(o,e){let t=await he(o),n=I(t),r=e||D.dirname(o),i=new Map;for(let[s,a]of Object.entries(n)){if(typeof a!="object"||!a.statementMap)continue;let c=new Map,l=[],u=0,d=0;for(let[C,E]of Object.entries(a.s||{})){let T=a.statementMap[C];if(T?.start?.line){let S=T.start.line,x=c.get(S)||0;c.set(S,x+E)}u++,E>0&&d++}for(let[C,E]of c.entries())E===0&&l.push(C);let m=[],p=0,f=0;for(let[C,E]of Object.entries(a.branchMap||{})){let T=a.b?.[C]||[];for(let S=0;S<T.length;S++)m.push({line:E.loc?.start?.line||0,block:parseInt(C,10),branch:S,taken:T[S]>0,hits:T[S]}),p++,T[S]>0&&f++}let g=[],h=0,y=0;for(let[C,E]of Object.entries(a.fnMap||{})){let T=a.f?.[C]||0;g.push({name:E.name||`anonymous_${C}`,line:E.loc?.start?.line||E.decl?.start?.line||0,hits:T}),h++,T>0&&y++}let v=c.size,b=Array.from(c.values()).filter(C=>C>0).length;i.set(s,{path:s,relativePath:D.relative(r,s),lines:{total:v,covered:b,percentage:v>0?b/v*100:0,details:c,uncoveredLines:l.sort((C,E)=>C-E)},branches:{total:p,covered:f,percentage:p>0?f/p*100:0,uncoveredBranches:m.filter(C=>!C.taken)},functions:{total:h,covered:y,percentage:h>0?y/h*100:0,details:g,uncoveredFunctions:g.filter(C=>C.hits===0).map(C=>C.name)},statements:{total:u,covered:d,percentage:u>0?d/u*100:0},coveragePercentage:zi(b,v,f,p)})}return{timestamp:new Date,format:"json",files:i,summary:Oe(i)}}async function Ic(o,e){let t=await he(o);return Xn(t,e||D.dirname(o))}function Xn(o,e){let t=new Map,n=/<package\s+name="([^"]*)">([\s\S]*?)<\/package>/g,r;for(;(r=n.exec(o))!==null;){let i=r[1].replace(/\//g,D.sep),s=r[2],a=/<sourcefile\s+name="([^"]*)">([\s\S]*?)<\/sourcefile>/g,c;for(;(c=a.exec(s))!==null;){let l=c[1],u=c[2],d=D.join(e,i,l),m=im(u),p=new Map,f=/<line\s+nr="(\d+)"\s+mi="(\d+)"\s+ci="(\d+)"/g,g;for(;(g=f.exec(u))!==null;){let y=parseInt(g[1],10),v=parseInt(g[3],10);p.set(y,v)}let h=Array.from(p.entries()).filter(([,y])=>y===0).map(([y])=>y).sort((y,v)=>y-v);t.set(d,{path:d,relativePath:D.join(i,l),lines:{total:m.LINE.total,covered:m.LINE.covered,percentage:m.LINE.total>0?m.LINE.covered/m.LINE.total*100:0,details:p,uncoveredLines:h},branches:{total:m.BRANCH.total,covered:m.BRANCH.covered,percentage:m.BRANCH.total>0?m.BRANCH.covered/m.BRANCH.total*100:0,uncoveredBranches:[]},functions:{total:m.METHOD.total,covered:m.METHOD.covered,percentage:m.METHOD.total>0?m.METHOD.covered/m.METHOD.total*100:0,details:[],uncoveredFunctions:[]},statements:{total:m.INSTRUCTION.total,covered:m.INSTRUCTION.covered,percentage:m.INSTRUCTION.total>0?m.INSTRUCTION.covered/m.INSTRUCTION.total*100:0},coveragePercentage:zi(m.LINE.covered,m.LINE.total,m.BRANCH.covered,m.BRANCH.total)})}}return{timestamp:new Date,format:"jacoco",language:"java",files:t,summary:Oe(t)}}function im(o){let e={LINE:{covered:0,total:0},BRANCH:{covered:0,total:0},METHOD:{covered:0,total:0},INSTRUCTION:{covered:0,total:0}},t=/<counter\s+type="(\w+)"\s+missed="(\d+)"\s+covered="(\d+)"\s*\/>/g,n;for(;(n=t.exec(o))!==null;){let r=n[1],i=parseInt(n[2],10),s=parseInt(n[3],10);e[r]&&(e[r].covered+=s,e[r].total+=i+s)}return e}async function Dc(o,e){let t=await he(o);return Gc(t,e||D.dirname(o))}function Gc(o,e){let t=new Map,n=new Map,r=/<File\s+Index="(\d+)"\s+Name="([^"]*)"\s*\/>/g,i;for(;(i=r.exec(o))!==null;)n.set(i[1],i[2]);let s=/<Statement\s+FileIndex="(\d+)"\s+Line="(\d+)"\s+Column="\d+"\s+EndLine="\d+"\s+EndColumn="\d+"\s+Covered="(\w+)"\s*\/>/g,a=new Map,c=new Map,l=0,u;for(;(u=s.exec(o))!==null;){l++;let m=u[1],p=parseInt(u[2],10),f=u[3]==="True",g=n.get(m);if(!g){c.set(m,(c.get(m)??0)+1);continue}a.has(g)||a.set(g,{lineDetails:new Map,total:0,covered:0});let h=a.get(g);h.lineDetails.set(p,f?1:0),h.total++,f&&h.covered++}let d=[];if(c.size>0){let m=[...c.values()].reduce((p,f)=>p+f,0);d.push(`dotCover report references FileIndex ${[...c.keys()].join(", ")} missing from its file table; ${m} statement(s) skipped and their coverage is not reported`)}if(l===0){let p=/CoveredStatements="(\d+)"\s+TotalStatements="(\d+)"/.exec(o);if(p){let f=parseInt(p[1],10),g=parseInt(p[2],10),h=D.join(e,"aggregate");d.push("dotCover report has no per-file statements; report totals are listed under 'aggregate', which is not a project file"),t.set(h,{path:h,relativePath:"aggregate",lines:{total:g,covered:f,percentage:g>0?f/g*100:0,details:new Map,uncoveredLines:[]},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:g,covered:f,percentage:g>0?f/g*100:0},coveragePercentage:g>0?f/g*100:0})}}for(let[m,p]of a.entries()){let f=Array.from(p.lineDetails.entries()).filter(([,g])=>g===0).map(([g])=>g).sort((g,h)=>g-h);t.set(m,{path:m,relativePath:D.relative(e,m),lines:{total:p.lineDetails.size,covered:Array.from(p.lineDetails.values()).filter(g=>g>0).length,percentage:p.lineDetails.size>0?Array.from(p.lineDetails.values()).filter(g=>g>0).length/p.lineDetails.size*100:0,details:p.lineDetails,uncoveredLines:f},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:p.total,covered:p.covered,percentage:p.total>0?p.covered/p.total*100:0},coveragePercentage:p.total>0?p.covered/p.total*100:0})}return{timestamp:new Date,format:"dotcover",language:"csharp",files:t,summary:Oe(t),...d.length>0?{warnings:d}:{}}}async function _c(o,e){let t=await he(o),n=e||D.dirname(o);if(t.includes("SF:")&&t.includes("end_of_record")){let r=$c(t,n);return r.format="tarpaulin",r.language="rust",r}return jc(t,n)}function jc(o,e){let t=new Map,n=I(o);for(let r of n?.files||[]){let i=r.path||"",s=new Map,a=0,c=0;for(let u of r.traces||[]){let d=u.line,m=u.stats?.Line??u.stats?.line??0;typeof d=="number"&&(s.set(d,m),a++,m>0&&c++)}let l=Array.from(s.entries()).filter(([,u])=>u===0).map(([u])=>u).sort((u,d)=>u-d);t.set(i,{path:i,relativePath:D.relative(e,i),lines:{total:a,covered:c,percentage:a>0?c/a*100:0,details:s,uncoveredLines:l},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:a,covered:c,percentage:a>0?c/a*100:0},coveragePercentage:a>0?c/a*100:0})}return{timestamp:new Date,format:"tarpaulin",language:"rust",files:t,summary:Oe(t)}}async function Oc(o,e){let t=await he(o);return zc(t,e||D.dirname(o))}function zc(o,e){let t=new Map,n=new Map,r=o.split(`
463
+ `);for(let i of r){let s=i.trim();if(!s||s.startsWith("mode:"))continue;let a=s.match(/^(.+):(\d+)\.\d+,(\d+)\.\d+\s+(\d+)\s+(\d+)$/);if(!a)continue;let c=a[1],l=parseInt(a[2],10),u=parseInt(a[3],10),d=parseInt(a[4],10),m=parseInt(a[5],10);n.has(c)||n.set(c,{lineDetails:new Map,stmtTotal:0,stmtCovered:0});let p=n.get(c);for(let f=l;f<=u;f++){let g=p.lineDetails.get(f)||0;p.lineDetails.set(f,g+m)}p.stmtTotal+=d,m>0&&(p.stmtCovered+=d)}for(let[i,s]of n.entries()){let a=s.lineDetails.size,c=Array.from(s.lineDetails.values()).filter(u=>u>0).length,l=Array.from(s.lineDetails.entries()).filter(([,u])=>u===0).map(([u])=>u).sort((u,d)=>u-d);t.set(i,{path:i,relativePath:D.relative(e,i),lines:{total:a,covered:c,percentage:a>0?c/a*100:0,details:s.lineDetails,uncoveredLines:l},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:s.stmtTotal,covered:s.stmtCovered,percentage:s.stmtTotal>0?s.stmtCovered/s.stmtTotal*100:0},coveragePercentage:s.stmtTotal>0?s.stmtCovered/s.stmtTotal*100:0})}return{timestamp:new Date,format:"gocover",language:"go",files:t,summary:Oe(t)}}async function Nc(o,e){let t=await he(o),n=Xn(t,e||D.dirname(o));return n.format="kover",n.language="kotlin",n}async function Fc(o,e){let t=await he(o);return Uc(t,e||D.dirname(o))}function Uc(o,e){let t=new Map,r=I(o)?.targets||[];for(let i of r)for(let s of i.files||[]){let a=s.path||"",c=s.executableLines||0,l=s.coveredLines||0,u=s.lineCoverage||0,d=[],m=0,p=0;for(let f of s.functions||[]){let g=f.coveredLines>0?1:0;d.push({name:f.name||"unknown",line:f.lineNumber||0,hits:g}),m++,g>0&&p++}t.set(a,{path:a,relativePath:D.relative(e,a),lines:{total:c,covered:l,percentage:u*100,details:new Map,uncoveredLines:[]},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:m,covered:p,percentage:m>0?p/m*100:0,details:d,uncoveredFunctions:d.filter(f=>f.hits===0).map(f=>f.name)},statements:{total:c,covered:l,percentage:u*100},coveragePercentage:u*100})}return{timestamp:new Date,format:"xcresult",language:"swift",files:t,summary:Oe(t)}}var Lc={java:["jacoco","cobertura","lcov"],kotlin:["kover","jacoco"],csharp:["dotcover","cobertura"],rust:["tarpaulin","lcov"],go:["gocover"],swift:["xcresult"],dart:["lcov"],typescript:["lcov","json"],javascript:["lcov","json"],python:["lcov","cobertura","json"]};async function _t(o,e,t,n){if(t)switch(t){case"lcov":return $i(o,e);case"json":return Gi(o,e);case"jacoco":return Ic(o,e);case"dotcover":return Dc(o,e);case"tarpaulin":return _c(o,e);case"gocover":return Oc(o,e);case"kover":return Nc(o,e);case"xcresult":return Fc(o,e);default:break}let r=D.extname(o).toLowerCase(),i=D.basename(o).toLowerCase();if(r===".json"||i.includes("coverage-final"))return Gi(o,e);if(i==="lcov.info"||r===".info"||i.includes("lcov"))return $i(o,e);if(i.includes("jacoco")&&r===".xml")return Ic(o,e);if(i.includes("dotcover")&&r===".xml")return Dc(o,e);if(i.includes("tarpaulin"))return _c(o,e);if(i.includes("kover")&&r===".xml")return Nc(o,e);if(i.includes("coverage")&&r===".out")return Oc(o,e);if(i.includes("xcresult")||i.includes("xccov"))return Fc(o,e);let s=await he(o),a=s.trim();if(a.startsWith("{"))return a.includes('"files"')&&a.includes('"traces"')?jc(s,e||D.dirname(o)):a.includes('"targets"')&&a.includes('"lineCoverage"')?Uc(s,e||D.dirname(o)):Gi(o,e);if(s.includes("SF:")&&s.includes("end_of_record"))return $i(o,e);if(a.startsWith("mode:"))return zc(s,e||D.dirname(o));if(a.startsWith("<?xml")||a.startsWith("<")){if(s.includes('<counter type="')||s.includes("<report ")){if(n==="kotlin"){let c=Xn(s,e||D.dirname(o));return c.format="kover",c.language="kotlin",c}return Xn(s,e||D.dirname(o))}if(s.includes("CoveredStatements=")||s.includes("<Root"))return Gc(s,e||D.dirname(o))}if(n){let c=n.toLowerCase(),l=Object.hasOwn(Lc,c)?Lc[c]:void 0;if(l&&l.length>0)try{return await _t(o,e,l[0])}catch{}}throw new Error(`Unknown coverage format: ${o}`)}async function ji(o,e){let t=e||o,n=[D.join(o,"coverage","lcov.info"),D.join(o,"coverage","coverage-final.json"),D.join(o,"lcov.info"),D.join(o,".nyc_output","coverage.json"),D.join(o,"target","site","jacoco","jacoco.xml"),D.join(o,"build","reports","jacoco","test","jacocoTestReport.xml"),D.join(o,"dotcover-report.xml"),D.join(o,"tarpaulin-report.json"),D.join(o,"cobertura.xml"),D.join(o,"coverage.out"),D.join(o,"cover.out"),D.join(o,"build","reports","kover","report.xml"),D.join(o,"coverage.json")];for(let r of n)try{return await qc.access(r),_t(r,t)}catch{}return null}function zi(o,e,t,n){let r=e>0?o/e*100:0,i=n>0?t/n*100:0;return n===0?r:r*.7+i*.3}function Oe(o){let e=0,t=0,n=0,r=0,i=0,s=0,a=0,c=0;for(let l of o.values())e+=l.lines.total,t+=l.lines.covered,n+=l.branches.total,r+=l.branches.covered,i+=l.functions.total,s+=l.functions.covered,a+=l.statements.total,c+=l.statements.covered;return{totalFiles:o.size,lines:{total:e,covered:t,percentage:e>0?t/e*100:0},branches:{total:n,covered:r,percentage:n>0?r/n*100:0},functions:{total:i,covered:s,percentage:i>0?s/i*100:0},statements:{total:a,covered:c,percentage:a>0?c/a*100:0}}}M();async function Bc(o,e,t){let n=e;if(e!=="."){let i=await X(o,"target",e,{allowDirectory:!0,allowMissing:!0});if(!i.success)return{error:i.error.message};n=i.value}if(t===void 0)return{target:n};let r=await X(o,"coverageFile",t);return r.success?{target:n,coverageFile:r.value}:{error:r.error.message}}function Hc(o){return o?.warnings?.length?` ${o.warnings.join(". ")}.`:""}function Vc(o){let e=0,t=0,n=0,r=0,i=0,s=0,a=0,c=0;for(let l of o)e+=l.lines.total,t+=l.lines.covered,n+=l.branches.total,r+=l.branches.covered,i+=l.functions.total,s+=l.functions.covered,a+=l.statements.total,c+=l.statements.covered;return{line:e>0?t/e*100:0,branch:n>0?r/n*100:0,function:i>0?s/i*100:0,statement:a>0?c/a*100:0,files:o.length}}function Qc(o){let e=[];for(let[t,n]of o.files.entries())e.push({path:n.relativePath||t,lines:{covered:n.lines.covered,total:n.lines.total},branches:{covered:n.branches.covered,total:n.branches.total},functions:{covered:n.functions.covered,total:n.functions.total},statements:{covered:n.statements.covered,total:n.statements.total},uncoveredLines:n.lines.uncoveredLines,uncoveredBranches:n.branches.uncoveredBranches.map(r=>r.line)});return e}var Yn=class extends A{config={name:"qe/coverage/analyze",description:"Analyze code coverage using real LCOV/JSON parsing and compare against thresholds. Includes risk scoring and trend analysis.",domain:"coverage-analysis",schema:sm,streaming:!0,timeout:18e4};analyzerService=null;async getService(e){if(!this.analyzerService){let t=e.memory??await $(),n=await Q(e);this.analyzerService=new ra({memory:t,llmRouter:n})}return this.analyzerService}async execute(e,t){let{target:n=".",coverageFile:r,thresholds:i={lines:80,branches:70,functions:80,statements:80},includeRisk:s=!1,includeRiskScoring:a=!1,dryRun:c=!1,coverageFormat:l,language:u}=e,d=s||a,m=await Bc("qe/coverage/analyze",n,r);if("error"in m)return{success:!1,error:m.error};let{target:p,coverageFile:f}=m;try{if(this.emitStream(t,{status:"analyzing",message:`Analyzing coverage for ${p}`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};if(this.isDemoMode(t)||c)return this.markAsDemoData(t,"Demo mode explicitly requested"),this.getDemoResult(p,i,d,t);let g=null;if(f)try{g=await _t(f,p,l,u)}catch(N){return{success:!1,error:`Failed to parse coverage file '${f}': ${w(N)}`}}else g=await ji(p);if(!g||g.files.size===0)return{success:!1,error:`No coverage data found in '${p}'. Run your test suite with coverage enabled (e.g., 'npm test -- --coverage') and ensure coverage reports are generated (lcov.info, coverage-final.json, etc.)${Hc(g)}`};this.markAsRealData();let h=Qc(g),v=await(await this.getService(t)).analyze({coverageData:{files:h,summary:Vc(h)},threshold:i.lines||80,includeFileDetails:!0,measured:!0});if(!v.success)return{success:!1,error:`Analysis failed: ${v.error?.message||"Unknown error"}`};let b=v.value,C={lines:{covered:g.summary.lines.covered,total:g.summary.lines.total,percentage:Math.round(g.summary.lines.percentage*100)/100},branches:{covered:g.summary.branches.covered,total:g.summary.branches.total,percentage:Math.round(g.summary.branches.percentage*100)/100},functions:{covered:g.summary.functions.covered,total:g.summary.functions.total,percentage:Math.round(g.summary.functions.percentage*100)/100},statements:{covered:g.summary.statements.covered,total:g.summary.statements.total,percentage:Math.round(g.summary.statements.percentage*100)/100}},E=h.map(N=>({file:N.path,lines:Math.round(N.lines.covered/(N.lines.total||1)*100),branches:Math.round(N.branches.covered/(N.branches.total||1)*100),functions:Math.round(N.functions.covered/(N.functions.total||1)*100),uncoveredLines:N.uncoveredLines.slice(0,20)})),T=C.lines.percentage>=(i.lines||0)&&C.branches.percentage>=(i.branches||0)&&C.functions.percentage>=(i.functions||0)&&C.statements.percentage>=(i.statements||0),S;if(d){let N=h.reduce((L,oe)=>L+oe.uncoveredLines.length,0),V=(C.lines.percentage+C.branches.percentage+C.functions.percentage)/3;S=Math.round((1-V/100+Math.min(N/1e3,.5))*100)/100}let x;b.delta&&(x={direction:b.delta.trend,delta:Math.round((b.delta.line+b.delta.branch+b.delta.function)/3*100)/100,history:[{date:new Date(Date.now()-10080*60*1e3).toISOString().split("T")[0],coverage:C.lines.percentage-(b.delta.line||0)},{date:new Date().toISOString().split("T")[0],coverage:C.lines.percentage}]}),this.emitStream(t,{status:"complete",message:`Coverage analysis complete: ${C.lines.percentage}% lines covered`,progress:100});let k=e.language||g.language,_=g.format;return{success:!0,data:{summary:C,byFile:E,thresholdsPassed:T,riskScore:S,trends:x,language:k,format:_,...g.warnings?{warnings:g.warnings}:{}}}}catch(g){return{success:!1,error:`Coverage analysis failed: ${w(g)}`}}}getDemoResult(e,t,n,r){let i={lines:{covered:850,total:1e3,percentage:85},branches:{covered:120,total:150,percentage:80},functions:{covered:90,total:100,percentage:90},statements:{covered:900,total:1050,percentage:85.71}},s=[{file:`${e}/service.ts`,lines:92,branches:85,functions:95,uncoveredLines:[45,67,89]},{file:`${e}/utils.ts`,lines:78,branches:70,functions:85,uncoveredLines:[12,34,56,78,90]},{file:`${e}/handler.ts`,lines:88,branches:82,functions:90,uncoveredLines:[23,45]}],a=i.lines.percentage>=(t.lines||0)&&i.branches.percentage>=(t.branches||0)&&i.functions.percentage>=(t.functions||0)&&i.statements.percentage>=(t.statements||0);return this.emitStream(r,{status:"complete",message:`Coverage analysis complete (sample data): ${i.lines.percentage}% lines covered`,progress:100}),{success:!0,data:{summary:i,byFile:s,thresholdsPassed:a,riskScore:n?.25:void 0,trends:{direction:"improving",delta:2.5,history:[{date:new Date(Date.now()-10080*60*1e3).toISOString().split("T")[0],coverage:82.5},{date:new Date().toISOString().split("T")[0],coverage:85}]}}}}resetInstanceCache(){this.analyzerService=null}},Jn=class extends A{config={name:"qe/coverage/gaps",description:"Find coverage gaps using O(log n) HNSW vector search. Prioritizes by risk, complexity, or ML confidence using real coverage data.",domain:"coverage-analysis",schema:am,streaming:!0,timeout:12e4};gapService=null;async getService(e){if(!this.gapService){let t=e.memory??await $(),n=await Q(e);this.gapService=new ia({memory:t,llmRouter:n})}return this.gapService}async execute(e,t){let{target:n=".",coverageFile:r,minRisk:i=.3,limit:s=20,prioritization:a="complexity",coverageFormat:c,language:l}=e,u=await Bc("qe/coverage/gaps",n,r);if("error"in u)return{success:!1,error:u.error};let{target:d,coverageFile:m}=u;try{if(this.emitStream(t,{status:"detecting",message:`Detecting coverage gaps in ${d} (O(log n) search)`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let p=null;if(m)try{p=await _t(m,d,c,l)}catch(T){return{success:!1,error:`Failed to parse coverage file: ${w(T)}`}}else p=await ji(d);if(this.isDemoMode(t))return this.markAsDemoData(t,"Demo mode explicitly requested"),this.getDemoGapsResult(d,i,s,t);if(!p||p.files.size===0)return m?{success:!1,error:`Coverage file '${m}' contains no usable coverage data (parsed 0 files). Verify the file is a non-empty Istanbul/LCOV/JaCoCo/etc. report.${Hc(p)}`}:{success:!1,error:`No coverage data found by autodiscovery under target '${d}'. Run your test suite with coverage enabled, or pass coverageFile pointing to an existing report.`};this.markAsRealData();let f=Qc(p),g=await this.getService(t),h=a==="change-frequency"?"recent-changes":"risk",y=await g.detectGaps({coverageData:{files:f,summary:Vc(f)},minCoverage:80,prioritize:h});if(!y.success)return{success:!1,error:`Gap detection failed: ${y.error?.message||"Unknown error"}`};let v=y.value,b=v.gaps.filter(T=>T.riskScore>=i).slice(0,s).map(T=>({file:T.file,lines:T.lines,type:T.branches.length>0?"uncovered-branch":"uncovered-line",severity:T.severity,riskScore:Math.round(T.riskScore*100)/100,reason:T.recommendation})),C=b.slice(0,5).map((T,S)=>({file:T.file.replace(/\.ts$/,".test.ts"),description:`Add tests for ${T.lines.length} uncovered lines in ${T.file}`,estimatedCoverageGain:Math.round(T.lines.length/(v.totalUncoveredLines||1)*100*100)/100,priority:S+1})),E;if(e.includeGhost)try{let T=await yn(t);if(T?.getDomainAPIAsync){let S=await T.getDomainAPIAsync("coverage-analysis");if(S?.analyzeGhostCoverage){let x=await S.analyzeGhostCoverage(f.map(k=>k.path),d);x?.success&&x.value&&(E=(x.value.gaps||[]).map(k=>({category:k.category,severity:k.severity,description:k.description,confidence:k.confidence})))}}}catch{}return this.emitStream(t,{status:"complete",message:`Found ${b.length} coverage gaps (${v.totalUncoveredLines} uncovered lines)`,progress:100}),{success:!0,data:{gaps:b,totalGaps:v.gaps.length,criticalGaps:b.filter(T=>T.severity==="critical").length,suggestedTests:C,...E?{ghostGaps:E}:{},...p.warnings?{warnings:p.warnings}:{}}}}catch(p){return{success:!1,error:`Gap detection failed: ${w(p)}`}}}getDemoGapsResult(e,t,n,r){let s=[{file:`${e}/service.ts`,lines:[45,67,89,102,115],type:"uncovered-line",severity:"high",riskScore:.85,reason:"Core business logic with no test coverage"},{file:`${e}/utils.ts`,lines:[12,34,56],type:"uncovered-branch",severity:"medium",riskScore:.65,reason:"Utility functions missing edge case tests"},{file:`${e}/handler.ts`,lines:[23,45,67,89],type:"uncovered-function",severity:"critical",riskScore:.92,reason:"Error handling paths untested"},{file:`${e}/validator.ts`,lines:[10,20,30],type:"uncovered-line",severity:"low",riskScore:.35,reason:"Simple validation logic"}].filter(c=>c.riskScore>=t).slice(0,n),a=s.slice(0,5).map((c,l)=>({file:c.file.replace(/\.ts$/,".test.ts"),description:`Add tests for ${c.lines.length} uncovered lines in ${c.file}`,estimatedCoverageGain:Math.round(c.lines.length/50*100*100)/100,priority:l+1}));return this.emitStream(r,{status:"complete",message:`Found ${s.length} coverage gaps (sample data)`,progress:100}),{success:!0,data:{gaps:s,totalGaps:s.length,criticalGaps:s.filter(c=>c.severity==="critical").length,suggestedTests:a}}}resetInstanceCache(){this.gapService=null}},sm={type:"object",properties:{target:{type:"string",description:"Target directory to analyze (searches for coverage files)",default:"."},coverageFile:{type:"string",description:"Path to coverage report file (lcov.info, coverage-final.json, etc.)"},thresholds:{type:"object",description:"Coverage thresholds",properties:{lines:{type:"number",description:"Line coverage threshold"},branches:{type:"number",description:"Branch coverage threshold"},functions:{type:"number",description:"Function coverage threshold"},statements:{type:"number",description:"Statement coverage threshold"}}},includeRisk:{type:"boolean",description:"Include risk score analysis",default:!1},mlPowered:{type:"boolean",description:"Use ML-powered analysis (vector similarity)",default:!1},language:{type:"string",description:"Source language hint (java, csharp, go, rust, kotlin, swift, dart, typescript, python)"},coverageFormat:{type:"string",description:"Coverage format hint",enum:["lcov","json","jacoco","dotcover","tarpaulin","gocover","kover","xcresult"]}}},am={type:"object",properties:{target:{type:"string",description:"Target directory to analyze",default:"."},coverageFile:{type:"string",description:"Path to coverage report file"},minRisk:{type:"number",description:"Minimum risk score to include (0-1)",minimum:0,maximum:1,default:.3},limit:{type:"number",description:"Maximum number of gaps to return",minimum:1,maximum:100,default:20},prioritization:{type:"string",description:"Gap prioritization strategy",enum:["complexity","criticality","change-frequency","ml-confidence"],default:"complexity"},includeGhost:{type:"boolean",description:"Include ADR-059 ghost intent coverage analysis (detect untested behavioral intents)",default:!1},language:{type:"string",description:"Source language filter (java, csharp, go, rust, kotlin, swift, dart)"},coverageFormat:{type:"string",description:"Coverage format hint",enum:["lcov","json","jacoco","dotcover","tarpaulin","gocover","kover","xcresult"]}}};M();var Zn=class extends A{config={name:"qe/quality/evaluate",description:"Evaluate quality gates and provide deployment recommendations. Analyzes coverage, bugs, complexity, and security.",domain:"quality-assessment",schema:om,streaming:!0,timeout:12e4};async execute(e,t){let{metrics:n,gateName:r="default",thresholds:i=cm(),includeAdvice:s=!0,riskTolerance:a="medium"}=e;try{let c=await hn(t);if(n&&!e.evidence)return{success:!1,error:"Timestamped evidence provenance is required when supplying quality metrics."};n&&e.evidence&&await on(c,n,e.evidence);let l=n??await cn(c),d=[["coverage",i.coverage],["testsPassing",i.testsPassing],["criticalBugs",i.criticalBugs],["codeSmells",i.codeSmells],["securityVulnerabilities",i.securityVulnerabilities],["technicalDebt",i.technicalDebt],["duplications",i.duplications]].filter(([C,E])=>E!==void 0&&l[C]===void 0).map(([C])=>C);if(d.length>0)return{success:!1,error:`Measured quality evidence missing configured metrics: ${d.join(", ")}.`};if(this.emitStream(t,{status:"evaluating",message:`Evaluating quality gate: ${r}`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let m=[];i.coverage&&l.coverage!==void 0&&m.push({name:"Coverage",passed:l.coverage>=i.coverage.min,value:l.coverage,threshold:i.coverage.min,severity:"high",message:l.coverage>=i.coverage.min?`Coverage ${l.coverage}% meets threshold`:`Coverage ${l.coverage}% below ${i.coverage.min}% threshold`}),i.testsPassing&&l.testsPassing!==void 0&&m.push({name:"Tests Passing",passed:l.testsPassing>=i.testsPassing.min,value:l.testsPassing,threshold:i.testsPassing.min,severity:"critical",message:l.testsPassing>=i.testsPassing.min?`${l.testsPassing}% tests passing`:`Only ${l.testsPassing}% tests passing`}),i.criticalBugs&&l.criticalBugs!==void 0&&m.push({name:"Critical Bugs",passed:l.criticalBugs<=i.criticalBugs.max,value:l.criticalBugs,threshold:i.criticalBugs.max,severity:"critical",message:l.criticalBugs<=i.criticalBugs.max?`${l.criticalBugs} critical bugs within threshold`:`${l.criticalBugs} critical bugs exceed threshold of ${i.criticalBugs.max}`}),i.securityVulnerabilities&&l.securityVulnerabilities!==void 0&&m.push({name:"Security Vulnerabilities",passed:l.securityVulnerabilities<=i.securityVulnerabilities.max,value:l.securityVulnerabilities,threshold:i.securityVulnerabilities.max,severity:"critical",message:l.securityVulnerabilities<=i.securityVulnerabilities.max?`${l.securityVulnerabilities} vulnerabilities within threshold`:`${l.securityVulnerabilities} vulnerabilities found`}),i.codeSmells&&l.codeSmells!==void 0&&m.push({name:"Code Smells",passed:l.codeSmells<=i.codeSmells.max,value:l.codeSmells,threshold:i.codeSmells.max,severity:"medium",message:l.codeSmells<=i.codeSmells.max?`${l.codeSmells} code smells within threshold`:`${l.codeSmells} code smells detected`}),i.technicalDebt&&l.technicalDebt!==void 0&&m.push({name:"Technical Debt",passed:l.technicalDebt<=i.technicalDebt.max,value:l.technicalDebt,threshold:i.technicalDebt.max,severity:"medium",message:l.technicalDebt<=i.technicalDebt.max?`${l.technicalDebt}h technical debt within threshold`:`${l.technicalDebt}h technical debt exceeds threshold of ${i.technicalDebt.max}h`}),i.duplications&&l.duplications!==void 0&&m.push({name:"Duplications",passed:l.duplications<=i.duplications.max,value:l.duplications,threshold:i.duplications.max,severity:"low",message:l.duplications<=i.duplications.max?`${l.duplications}% duplication within threshold`:`${l.duplications}% duplication exceeds threshold of ${i.duplications.max}%`});let p=m.filter(C=>C.passed).length,f=m.length,g=f>0?Math.round(p/f*100):100,h=lm(g,m),y=m.every(C=>C.passed),v=s?um(y,g,m,a):void 0,b=dm(m,l);return this.emitStream(t,{status:"complete",message:`Quality evaluation complete: ${h} (${g}%)`,progress:100}),{success:!0,data:{passed:y,score:g,grade:h,checks:m,deploymentAdvice:v,recommendations:b}}}catch(c){return{success:!1,error:`Quality evaluation failed: ${w(c)}`}}}},om={type:"object",properties:{metrics:{type:"object",description:"Quality metrics to evaluate",properties:{coverage:{type:"number",description:"Code coverage percentage"},testsPassing:{type:"number",description:"Percentage of passing tests"},criticalBugs:{type:"number",description:"Number of critical bugs"},codeSmells:{type:"number",description:"Number of code smells"},securityVulnerabilities:{type:"number",description:"Number of security vulnerabilities"},technicalDebt:{type:"number",description:"Technical debt in hours"},duplications:{type:"number",description:"Code duplication percentage"},complexity:{type:"number",description:"Cyclomatic complexity"}}},gateName:{type:"string",description:"Name of the quality gate",default:"default"},thresholds:{type:"object",description:"Quality gate thresholds"},includeAdvice:{type:"boolean",description:"Include deployment advice",default:!0},riskTolerance:{type:"string",description:"Risk tolerance level",enum:["low","medium","high"],default:"medium"},evidence:{type:"object",description:"Provenance required to persist supplied metrics as canonical measured evidence",properties:{measuredAt:{type:"string",description:"ISO-8601 measurement timestamp"},source:{type:"string",description:"Scanner or analyzer that produced the metrics"}}}}};function cm(){return{coverage:{min:Re.coverage.value},testsPassing:{min:Re.testsPassing.value},criticalBugs:{max:Re.criticalBugs.value},securityVulnerabilities:{max:Re.securityVulnerabilities.value},codeSmells:{max:Re.codeSmells.value},technicalDebt:{max:Re.technicalDebt.value},duplications:{max:Re.duplications.value}}}function lm(o,e){return e.some(n=>!n.passed&&n.severity==="critical")?"F":o>=90?"A":o>=80?"B":o>=70?"C":o>=60?"D":"F"}function um(o,e,t,n){let r=t.filter(d=>!d.passed&&d.severity==="critical"),i=t.filter(d=>!d.passed&&d.severity==="high"),s=r.length*.4+i.length*.2+(100-e)/100,a=Math.min(s,1),c,u={low:{block:.2,warn:.1},medium:{block:.4,warn:.2},high:{block:.6,warn:.4}}[n];return a>=u.block||r.length>0?c="blocked":a>=u.warn?c="warning":c="approved",{decision:c,confidence:Math.round((1-a)*100)/100,riskScore:Math.round(a*100)/100,reasons:[...r.map(d=>`Critical: ${d.name} - ${d.message}`),...i.map(d=>`High: ${d.name} - ${d.message}`)],conditions:c==="warning"?["Monitor closely after deployment","Prepare rollback plan"]:void 0,rollbackPlan:c!=="approved"?"Revert to previous version if issues detected":void 0}}function dm(o,e){let t=[],n=o.filter(r=>!r.passed);for(let r of n)t.push({type:r.severity==="critical"?"critical":r.severity==="high"?"warning":"improvement",title:`Fix ${r.name}`,description:r.message,impact:r.severity==="critical"||r.severity==="high"?"high":"medium",effort:"medium"});return(e.coverage||0)<90&&t.push({type:"improvement",title:"Increase test coverage",description:`Current coverage is ${e.coverage}%. Consider adding tests for critical paths.`,impact:"medium",effort:"medium"}),t}M();Et();var er=class extends A{config={name:"qe/quality/gate",description:"Two-gate, three-valued quality verdict (ADR-119): mechanical oracle gate plus a frontier judge grading plus failure-mode verification reach. Returns pass|fail|inconclusive.",domain:"quality-assessment",schema:mm,streaming:!1,timeout:12e4};async execute(e,t){try{if(!e.checklistId)return{success:!1,error:"checklistId is required"};if(typeof e.artifact!="string"||e.artifact.length===0)return{success:!1,error:"artifact (non-empty string) is required"};let n,r;if(e.anchorPath!==void 0){let c=await X("qe/quality/gate","anchorPath",e.anchorPath,{basePath:ze(),maxBytes:ne});if(!c.success)return{success:!1,error:c.error.message};n=c.value,r=io(await de(n,{maxBytes:ne}),e.anchorPath)}let i=await Q(t),s=i?ao(i,{...e.model?{model:e.model}:{},logger:c=>this.logger.warn(c,{requestId:t.requestId})}):oo("no LLM provider configured \u2014 set a frontier provider API key");return i||this.markAsDemoData(t,"no LLM router \u2014 frontier judge unavailable, verdict will be inconclusive"),{success:!0,data:await so({oracleResult:e.oracle??null,artifact:e.artifact,checklistId:e.checklistId,judge:s,anchorPath:n,anchor:r,verificationManifest:e.verificationManifest})}}catch(n){return{success:!1,error:`Quality gate failed: ${w(n)}`}}}},mm={type:"object",properties:{checklistId:{type:"string",description:'Pinned ADR-117 anchor checklist id (e.g. "A1-inRange")'},artifact:{type:"string",description:"The artifact under judgement (produced test source / spec output)"},oracle:{type:"object",description:"ADR-113 mechanical oracle result. Omit \u21D2 mechanical fail (test did not execute).",properties:{passed:{type:"boolean",description:"Mutation score met threshold"},baselinePassed:{type:"boolean",description:"Tests executed against the reference impl"}}},anchorPath:{type:"string",description:"Override the frozen anchor path (ADR-117)"},verificationManifest:{type:"object",description:"Hashed, revision-bound failure-mode verification reach manifest (#651)"},model:{type:"string",description:"Frontier judge model id (ADR-111: always frontier-tier)"}},required:["checklistId","artifact"]};M();var tr={codeComplexity:"High cyclomatic complexity increases defect probability",changeFrequency:"Frequently modified files are more prone to defects",bugHistory:"Previous defects in this area indicate higher risk",testCoverage:"Low test coverage increases undetected defect risk",developerExperience:"Code written by less experienced developers may have more issues",codeAge:"New code is more likely to have defects than mature, stable code",complexity:"High cyclomatic complexity increases defect probability",churn:"Frequently modified files are more prone to defects",history:"Previous defects in this area indicate higher risk",coverage:"Low test coverage increases undetected defect risk",coupling:"High coupling makes changes risky",age:"New code may have more defects than stable code"},nr=class extends A{config={name:"qe/defects/predict",description:"Predict defect probability for files using ML models. Analyzes code complexity, change frequency, git history, and test coverage.",domain:"defect-intelligence",schema:pm,streaming:!0,timeout:18e4};predictorService=null;async getService(e){if(!this.predictorService){let t=e.memory??await $(),n=await Q(e);this.predictorService=new ma({memory:t,llmRouter:n})}return this.predictorService}async execute(e,t){let{files:n=[],threshold:r=.5,minConfidence:i=.7,features:s=[{name:"codeComplexity",weight:.25},{name:"changeFrequency",weight:.2},{name:"developerExperience",weight:.15},{name:"testCoverage",weight:.2},{name:"codeAge",weight:.1},{name:"bugHistory",weight:.1}]}=e;try{if(this.emitStream(t,{status:"analyzing",message:`Analyzing ${n.length||"provided"} files using ML-based prediction`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};if(this.isDemoMode(t))return this.markAsDemoData(t,"Demo mode explicitly requested"),this.getDemoResult(n);let a=await this.getService(t),c=await a.predictDefects({files:n,features:s.map(f=>({name:f.name,weight:f.weight??.25})),threshold:r});if(!c.success)return{success:!1,error:`Defect prediction failed: ${c.error?.message||"Service unavailable"}. Ensure the defect-intelligence domain is properly initialized.`};this.markAsRealData();let d=c.value.predictions.filter(f=>f.probability>=1-i).map(f=>({file:f.file,probability:Math.round(f.probability*100)/100,riskLevel:gm(f.riskLevel),factors:f.factors.map(g=>({name:g.name,contribution:g.contribution,description:tr[g.name]||`${g.name} contributes to defect risk`})),recommendations:f.recommendations}));d.sort((f,g)=>g.probability-f.probability);let m=fm(d),p=await a.getModelMetrics();return this.emitStream(t,{status:"complete",message:`Analyzed ${n.length} files, ${d.length} with elevated risk`,progress:100}),{success:!0,data:{predictions:d,modelConfidence:c.value.modelConfidence,topRiskFactors:m,recommendations:ym(d),modelMetrics:{accuracy:p.accuracy,precision:p.precision,recall:p.recall,f1Score:p.f1Score}}}}catch(a){return{success:!1,error:`Defect prediction failed: ${w(a)}`}}}getDemoResult(e){let n=(e.length>0?e:["src/service.ts","src/handler.ts","src/utils.ts"]).map((r,i)=>({file:r,probability:Math.max(.9-i*.15,.35),riskLevel:i===0?"high":i===1?"medium":"low",factors:[{name:"codeComplexity",contribution:.35,description:tr.codeComplexity},{name:"changeFrequency",contribution:.25,description:tr.changeFrequency},{name:"testCoverage",contribution:.2,description:tr.testCoverage}],recommendations:[`Increase test coverage for ${r}`,"Consider refactoring complex functions","Review recent changes for potential issues"]}));return{success:!0,data:{predictions:n,modelConfidence:.85,topRiskFactors:[{name:"High Complexity",impact:.35,affectedFiles:n.length},{name:"Frequent Changes",impact:.25,affectedFiles:Math.ceil(n.length*.7)},{name:"Low Coverage",impact:.2,affectedFiles:Math.ceil(n.length*.5)}],recommendations:["Focus testing on files with highest defect probability","Increase test coverage in high-risk areas","Review recent changes to frequently-modified files","Consider refactoring complex modules"],modelMetrics:{accuracy:.82,precision:.78,recall:.85,f1Score:.81}}}}resetInstanceCache(){this.predictorService=null}},pm={type:"object",properties:{files:{type:"array",description:"Specific files to analyze",items:{type:"string",description:"File path"}},target:{type:"string",description:"Target directory to analyze",default:"."},lookback:{type:"number",description:"Days of history to consider",minimum:7,maximum:365,default:30},threshold:{type:"number",description:"Risk threshold for classification (0-1)",minimum:0,maximum:1,default:.5},minConfidence:{type:"number",description:"Minimum prediction confidence (0-1)",minimum:0,maximum:1,default:.7},features:{type:"array",description:"Features to use for prediction",items:{type:"object",description:"Prediction feature",properties:{name:{type:"string",description:"Feature name"},weight:{type:"number",description:"Feature weight"}}}}}};function gm(o){switch(o){case"critical":return"critical";case"high":return"high";case"medium":return"medium";default:return"low"}}function fm(o){let e=new Map;for(let n of o)for(let r of n.factors){let i=e.get(r.name)||{impact:0,count:0};i.impact+=r.contribution,i.count+=1,e.set(r.name,i)}let t=[];for(let[n,r]of e)t.push({name:hm(n),impact:Math.round(r.impact/r.count*100)/100,affectedFiles:r.count});return t.sort((n,r)=>r.impact-n.impact),t.slice(0,5)}function hm(o){return{codeComplexity:"High Complexity",changeFrequency:"Frequent Changes",bugHistory:"Bug History",testCoverage:"Low Coverage",developerExperience:"Developer Experience",codeAge:"Code Age"}[o]||o.replace(/([A-Z])/g," $1").trim()}function ym(o){let e=[],t=o.filter(i=>i.riskLevel==="critical").length,n=o.filter(i=>i.riskLevel==="high").length,r=o.length>0?o.reduce((i,s)=>i+s.probability,0)/o.length:0;return t>0&&(e.push(`CRITICAL: ${t} files require immediate attention`),e.push("Consider code review and comprehensive testing before deployment")),n>0&&(e.push(`High risk detected in ${n} files`),e.push("Increase test coverage in high-risk areas")),r>.5?(e.push("Overall defect risk is elevated - consider delaying release"),e.push("Run full regression test suite before deployment")):e.push("Focus testing on files with highest defect probability"),e.push("Review recent changes to frequently-modified files"),e.push("Consider refactoring complex modules"),[...new Set(e)]}M();var rr=class extends A{config={name:"qe/requirements/validate",description:"Validate requirements for testability. Scores each requirement, detects ambiguity, and optionally generates BDD scenarios.",domain:"requirements-validation",schema:vm,streaming:!0,timeout:12e4};async execute(e,t){let{requirements:n,generateBDD:r=!1,checkAmbiguity:i=!0,minTestability:s=60}=e;try{if(this.emitStream(t,{status:"validating",message:`Validating ${n.length} requirements`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let a=[],c=[];for(let u of n){this.emitStream(t,{status:"processing",message:`Analyzing: ${u.title}`});let d=bm(u),m=Cm(u,s,d),p=i?Sm(u):void 0;a.push({requirementId:u.id,isValid:m.filter(f=>f.severity==="error").length===0,testabilityScore:d,errors:m,ambiguityReport:p}),r&&d.value>=s&&c.push(...Em(u))}let l={total:n.length,valid:a.filter(u=>u.isValid).length,invalid:a.filter(u=>!u.isValid).length,avgTestability:a.reduce((u,d)=>u+d.testabilityScore.value,0)/n.length,blockers:a.filter(u=>u.errors.some(d=>d.severity==="error")).length};return this.emitStream(t,{status:"complete",message:`Validation complete: ${l.valid}/${l.total} valid`,progress:100}),{success:!0,data:{validationResults:a,summary:l,bddScenarios:c.length>0?c:void 0,recommendations:wm(a)}}}catch(a){return{success:!1,error:`Validation failed: ${w(a)}`}}}},vm={type:"object",properties:{requirements:{type:"array",description:"Requirements to validate",items:{type:"object",description:"Requirement input",properties:{id:{type:"string",description:"Requirement ID"},title:{type:"string",description:"Requirement title"},description:{type:"string",description:"Requirement description"},acceptanceCriteria:{type:"array",description:"Acceptance criteria",items:{type:"string",description:"Criterion"}},type:{type:"string",description:"Requirement type",enum:["user-story","functional","non-functional","technical"]}},required:["id","title","description"]}},generateBDD:{type:"boolean",description:"Generate BDD scenarios from requirements",default:!1},checkAmbiguity:{type:"boolean",description:"Check for ambiguous language",default:!0},minTestability:{type:"number",description:"Minimum testability score (0-100)",minimum:0,maximum:100,default:60}},required:["requirements"]};function bm(o){let e=[],t=o.acceptanceCriteria&&o.acceptanceCriteria.length>0?90:40;e.push({name:"Acceptance Criteria",score:t,issues:t<70?["Missing or incomplete acceptance criteria"]:[]});let n=o.description.length,r=n>100?85:n>50?70:50;e.push({name:"Description Clarity",score:r,issues:r<70?["Description may be too brief"]:[]});let a=["should","must","when","then","verify","validate"].some(l=>o.description.toLowerCase().includes(l))?80:50;e.push({name:"Measurability",score:a,issues:a<70?["Requirement lacks measurable criteria"]:[]});let c=Math.round(e.reduce((l,u)=>l+u.score,0)/e.length);return{value:c,category:c>=80?"excellent":c>=70?"good":c>=50?"fair":"poor",factors:e}}function Cm(o,e,t){let n=[];return t.value<e&&n.push({code:"LOW_TESTABILITY",message:`Testability score ${t.value} is below minimum ${e}`,severity:"error",suggestion:"Add clear acceptance criteria and measurable outcomes"}),(!o.acceptanceCriteria||o.acceptanceCriteria.length===0)&&n.push({code:"MISSING_AC",message:"No acceptance criteria defined",severity:"warning",suggestion:"Define specific, testable acceptance criteria"}),o.description.length<30&&n.push({code:"BRIEF_DESC",message:"Description is too brief",severity:"warning",suggestion:"Expand description with more context and details"}),n}function Sm(o){let e=[],t=["some","few","many","fast","slow","good","better","appropriate"];for(let n of t)o.description.toLowerCase().includes(n)&&e.push({term:n,context:`Found in: "${o.description.substring(0,50)}..."`,alternatives:Tm(n)});return{ambiguousTerms:e,overallScore:Math.max(0,100-e.length*15),suggestions:e.length>0?["Replace vague terms with specific, measurable criteria"]:["Requirement language is clear"]}}function Tm(o){return{some:["exactly N","at least N","between N and M"],few:["1-3","less than 5"],many:["more than 10","at least N"],fast:["within X milliseconds","response time < Xs"],slow:["longer than X seconds"],good:["score >= 80%","passes all criteria"],better:["improves by X%","exceeds baseline by N"],appropriate:["meets requirement X","validates against schema"]}[o]||["Be more specific"]}function Em(o){let e=[];return e.push({id:`scenario-${o.id}-1`,feature:o.title,scenario:`Verify ${o.title}`,given:["the system is initialized","the user is authenticated"],when:["the user performs the action"],then:["the expected outcome is observed","the system state is updated"],tags:["@generated",`@${o.type||"functional"}`]}),o.acceptanceCriteria&&o.acceptanceCriteria.length>0&&o.acceptanceCriteria.forEach((t,n)=>{e.push({id:`scenario-${o.id}-ac${n+1}`,feature:o.title,scenario:`Acceptance Criteria: ${t.substring(0,50)}`,given:["the preconditions are met"],when:["the specified action is taken"],then:[t],tags:["@generated","@acceptance"]})}),e}function wm(o){let e=[],t=o.filter(r=>r.testabilityScore.value<60).length,n=o.filter(r=>r.errors.some(i=>i.code==="MISSING_AC")).length;return t>0&&e.push(`${t} requirements have low testability scores. Consider adding acceptance criteria.`),n>0&&e.push(`${n} requirements lack acceptance criteria. Define testable criteria for each.`),o.every(r=>r.isValid)&&e.push("All requirements are valid and testable."),e}import{existsSync as Ui,readFileSync as Wc}from"fs";import{join as Bi,dirname as Rm}from"path";import{fileURLToPath as Pm}from"url";var at=["Capability","Reliability","Usability","Charisma","Security","Scalability","Compatibility","Performance","Installability","Development"],ot=["Capability","Reliability","Security","Performance","Development"];var xm=Pm(import.meta.url),Am=Rm(xm),Ot=class{config;templateCache=null;constructor(e={}){this.config={enableSemanticAnalysis:e.enableSemanticAnalysis??!0,defaultOutputFormat:e.defaultOutputFormat??"html",templatePath:e.templatePath??this.findTemplatePath(),minimumCategories:e.minimumCategories??8}}findTemplatePath(){let e=[Bi(process.cwd(),".claude/helpers/v3/quality-criteria/quality-criteria-reference-template.html"),Bi(process.cwd(),"node_modules/agentic-qe/assets/agents/v3/helpers/quality-criteria/quality-criteria-reference-template.html"),Bi(Am,"../../../../../assets/agents/v3/helpers/quality-criteria/quality-criteria-reference-template.html")];for(let t of e)if(Ui(t))return t;return e[0]}analyze(e){let t=e.epicContent||"";if(e.epicPath&&Ui(e.epicPath)&&(t=Wc(e.epicPath,"utf-8")),!t&&!e.epicPath)throw new Error("Either epicPath or epicContent is required for analysis");return{agentInvocation:{required:!0,agentType:"qe-quality-criteria-recommender",prompt:this.buildAgentPrompt({assessmentName:e.assessmentName,epicContent:t,epicPath:e.epicPath,sourcePaths:e.sourcePaths,outputFormat:e.outputFormat,outputPath:e.outputPath}),timeout:3e5,expectedOutput:"QualityCriteriaAnalysis",instructions:`Claude Code MUST spawn the qe-quality-criteria-recommender agent with this prompt. The agent will perform real semantic HTSM analysis using Claude's reasoning capabilities. Use: Task("HTSM Quality Criteria Analysis", { prompt: <this prompt> }, "qe-quality-criteria-recommender")`},message:"AGENT INVOCATION REQUIRED: This service cannot perform semantic HTSM analysis alone. Claude Code must spawn the qe-quality-criteria-recommender agent with the provided prompt."}}buildAgentPrompt(e){let{assessmentName:t,epicContent:n,epicPath:r,sourcePaths:i,outputFormat:s,outputPath:a}=e,c=i&&i.length>0?`
473
464
  ## Source Paths to Analyze
474
- ${i.map(d=>`- ${d}`).join(`
465
+ ${i.map(u=>`- ${u}`).join(`
475
466
  `)}
476
467
  `:"",l=a?`
477
468
  ## Output
@@ -497,11 +488,11 @@ ${c}
497
488
  Perform HTSM v6.3 Quality Criteria analysis on the above requirements.
498
489
 
499
490
  ### HTSM Categories to Analyze
500
- ${st.map((d,u)=>`${u+1}. ${d}`).join(`
491
+ ${at.map((u,d)=>`${d+1}. ${u}`).join(`
501
492
  `)}
502
493
 
503
494
  ### Categories That CANNOT Be Omitted
504
- ${at.map(d=>`- ${d}`).join(`
495
+ ${ot.map(u=>`- ${u}`).join(`
505
496
  `)}
506
497
 
507
498
  ### Evidence Classification
@@ -542,7 +533,7 @@ Return a complete QualityCriteriaAnalysis object with:
542
533
  ${l}
543
534
  ## Begin Analysis
544
535
 
545
- Analyze the requirements above and return the complete QualityCriteriaAnalysis.`}validateEvidence(e){let t=[];for(let n of e)this.isValidSourceReference(n.sourceReference)||t.push(`Invalid source reference format: ${n.sourceReference}. Expected file:line format.`),["Direct","Inferred","Claimed"].includes(n.type)||t.push(`Invalid evidence type: ${n.type}. Must be Direct, Inferred, or Claimed.`),n.type==="Claimed"&&(!n.reasoning.includes("requires verification")&&!n.reasoning.includes("needs inspection")&&!n.reasoning.includes("needs code inspection")&&t.push(`Claimed evidence must state "requires verification": ${n.sourceReference}`),(n.reasoning.includes("could")||n.reasoning.includes("might"))&&t.push(`Claimed evidence must not speculate (no "could" or "might"): ${n.sourceReference}`)),n.reasoning.length<20&&t.push(`Reasoning too short for ${n.sourceReference}. Explain WHY it matters.`);return{valid:t.length===0,errors:t}}isValidSourceReference(e){if(e==="N/A (verified via Glob/Grep search)"||e==="Project search")return!0;let t=/^[\w\-./]+\.(ts|js|tsx|jsx|md|json|html|css|yaml|yml):\d+-\d+$/,n=/^[\w\-./]+\.(ts|js|tsx|jsx|md|json|html|css|yaml|yml)(\s*\(\d+\s*LOC\))?$/;return t.test(e)||n.test(e)}extractComponent(e){let t=e.match(/component:\s*["']?([^"'\n]+)["']?/i);if(t)return t[1].trim();let n=e.match(/^#\s+(.+)$/m);if(n)return n[1].trim()}generateHTML(e){if(!this.templateCache&&Ui(this.config.templatePath)&&(this.templateCache=Xc(this.config.templatePath,"utf-8")),!this.templateCache)return this.generateFallbackHTML(e);let t=this.templateCache;return t=t.replace(/\{EPIC_TITLE\}/g,e.epic),t=t.replace(/\{COMPONENT_NAME\}/g,e.component||"N/A"),t=t.replace(/\{DATE\}/g,e.timestamp.toISOString().split("T")[0]),t=t.replace(/\{COVERAGE_METRIC\}/g,e.coverageMetric),t}generateFallbackHTML(e){return`<!DOCTYPE html>
536
+ Analyze the requirements above and return the complete QualityCriteriaAnalysis.`}validateEvidence(e){let t=[];for(let n of e)this.isValidSourceReference(n.sourceReference)||t.push(`Invalid source reference format: ${n.sourceReference}. Expected file:line format.`),["Direct","Inferred","Claimed"].includes(n.type)||t.push(`Invalid evidence type: ${n.type}. Must be Direct, Inferred, or Claimed.`),n.type==="Claimed"&&(!n.reasoning.includes("requires verification")&&!n.reasoning.includes("needs inspection")&&!n.reasoning.includes("needs code inspection")&&t.push(`Claimed evidence must state "requires verification": ${n.sourceReference}`),(n.reasoning.includes("could")||n.reasoning.includes("might"))&&t.push(`Claimed evidence must not speculate (no "could" or "might"): ${n.sourceReference}`)),n.reasoning.length<20&&t.push(`Reasoning too short for ${n.sourceReference}. Explain WHY it matters.`);return{valid:t.length===0,errors:t}}isValidSourceReference(e){if(e==="N/A (verified via Glob/Grep search)"||e==="Project search")return!0;let t=/^[\w\-./]+\.(ts|js|tsx|jsx|md|json|html|css|yaml|yml):\d+-\d+$/,n=/^[\w\-./]+\.(ts|js|tsx|jsx|md|json|html|css|yaml|yml)(\s*\(\d+\s*LOC\))?$/;return t.test(e)||n.test(e)}extractComponent(e){let t=e.match(/component:\s*["']?([^"'\n]+)["']?/i);if(t)return t[1].trim();let n=e.match(/^#\s+(.+)$/m);if(n)return n[1].trim()}generateHTML(e){if(!this.templateCache&&Ui(this.config.templatePath)&&(this.templateCache=Wc(this.config.templatePath,"utf-8")),!this.templateCache)return this.generateFallbackHTML(e);let t=this.templateCache;return t=t.replace(/\{EPIC_TITLE\}/g,e.epic),t=t.replace(/\{COMPONENT_NAME\}/g,e.component||"N/A"),t=t.replace(/\{DATE\}/g,e.timestamp.toISOString().split("T")[0]),t=t.replace(/\{COVERAGE_METRIC\}/g,e.coverageMetric),t}generateFallbackHTML(e){return`<!DOCTYPE html>
546
537
  <html lang="en">
547
538
  <head>
548
539
  <meta charset="UTF-8">
@@ -576,9 +567,9 @@ Analyze the requirements above and return the complete QualityCriteriaAnalysis.`
576
567
  </footer>
577
568
  </body>
578
569
  </html>`}generateMarkdown(e){let t=["# Quality Criteria Recommendations","",`**Epic:** ${e.epic}`,`**Component:** ${e.component||"N/A"}`,`**Date:** ${e.timestamp.toISOString().split("T")[0]}`,`**Coverage:** ${e.coverageMetric}`,"","## Executive Summary","",e.executiveSummary||"_Analysis pending. Run qe-quality-criteria-recommender agent for full semantic analysis._","","## Categories Analyzed","",...e.categoriesAnalyzed.map(n=>`- ${n}`),""];if(e.categoriesOmitted.length>0){t.push("## Categories Omitted"),t.push("");for(let n of e.categoriesOmitted)t.push(`- **${n.category}**: ${n.reason}`);t.push("")}if(e.recommendations.length>0){t.push("## Recommendations"),t.push("");for(let n of e.recommendations){t.push(`### ${n.category} (${n.priority})`),t.push(""),t.push(`**Why It Matters:** ${n.whyItMatters}`),t.push(""),t.push(`**Business Impact:** ${n.businessImpact}`),t.push(""),t.push("**Test Focus Areas:**");for(let r of n.testFocusAreas)t.push(`- ${r}`);t.push("")}}return t.push("---"),t.push(""),t.push("*Generated by Agentic QE \u2014 qe-quality-criteria-recommender*"),t.push("*Analysis Method: AI Semantic Understanding | Framework: James Bach's HTSM v6.3*"),t.join(`
579
- `)}};function ir(o){return new _t(o)}D();D();var Ot=class extends A{config={name:"qe/requirements/quality-criteria",description:'HTSM v6.3 Quality Criteria analysis tool. For "analyze" action: Returns an agentInvocation that MUST be executed to get real semantic analysis. For "validate-evidence": Validates evidence points programmatically. For "format": Formats a completed analysis into HTML/JSON/Markdown.',domain:"requirements-validation",schema:Fm,streaming:!0,timeout:12e4};service=null;getService(){return this.service||(this.service=ir()),this.service}async execute(e,t){let{assessmentName:n,epicPath:r,epicContent:i,sourcePaths:s,outputFormat:a="html",outputPath:c,evidencePoints:l,completedAnalysis:d,action:u="analyze"}=e;try{let m=this.getService();if(this.emitStream(t,{status:"starting",message:`Quality Criteria: ${u} - ${n}`,action:u}),this.isAborted(t))return{success:!1,error:"Operation aborted"};if(u==="validate-evidence"){if(!l||l.length===0)return{success:!1,error:"validate-evidence action requires evidencePoints array"};this.emitStream(t,{status:"validating",message:`Validating ${l.length} evidence points`});let h=m.validateEvidence(l);return{success:!0,data:{evidenceValidation:h,message:h.valid?`All ${l.length} evidence points are valid`:`Validation failed with ${h.errors.length} errors`}}}if(u==="format"){if(!d)return{success:!1,error:"format action requires completedAnalysis object"};this.emitStream(t,{status:"formatting",message:`Formatting analysis as ${a}`});let h,v,y;switch(a){case"html":h=m.generateHTML(d);break;case"json":v=JSON.stringify(d,null,2);break;case"markdown":y=m.generateMarkdown(d);break}return{success:!0,data:{html:h,json:v,markdown:y,message:`Analysis formatted as ${a}`}}}this.emitStream(t,{status:"preparing",message:"Preparing agent invocation for semantic HTSM analysis"});let p=i||"";if(r){let h=await K("quality-criteria","epicPath",r,{allowMissing:!0,maxBytes:ne});if(!h.success)return{success:!1,error:h.error.message};try{p=await ue(h.value,{maxBytes:ne})}catch(v){if(!(v instanceof Ns)||v.reason!=="not-found")return{success:!1,error:w(v)}}}if(!p&&!r)return{success:!1,error:"Either epicPath or epicContent is required for analysis"};let f={required:!0,agentType:"qe-quality-criteria-recommender",prompt:this.buildAgentPrompt({assessmentName:n,epicContent:p,epicPath:r,sourcePaths:s,outputFormat:a,outputPath:c}),timeout:3e5,expectedOutput:"QualityCriteriaAnalysis",instructions:`Claude Code MUST spawn the qe-quality-criteria-recommender agent with this prompt. The agent will perform real semantic HTSM analysis using Claude's reasoning capabilities. Use: Task("HTSM Quality Criteria Analysis", { prompt: <this prompt> }, "qe-quality-criteria-recommender")`};return this.emitStream(t,{status:"agent-required",message:"Agent invocation prepared. Claude Code must spawn qe-quality-criteria-recommender agent.",agentType:"qe-quality-criteria-recommender"}),{success:!0,data:{agentInvocation:f,message:"AGENT INVOCATION REQUIRED: This tool cannot perform semantic HTSM analysis alone. Claude Code must spawn the qe-quality-criteria-recommender agent with the provided prompt."}}}catch(m){return{success:!1,error:`Quality Criteria tool failed: ${w(m)}`}}}buildAgentPrompt(e){let{assessmentName:t,epicContent:n,epicPath:r,sourcePaths:i,outputFormat:s,outputPath:a}=e,c=i&&i.length>0?`
570
+ `)}};function ir(o){return new Ot(o)}M();M();var Nt=class extends A{config={name:"qe/requirements/quality-criteria",description:'HTSM v6.3 Quality Criteria analysis tool. For "analyze" action: Returns an agentInvocation that MUST be executed to get real semantic analysis. For "validate-evidence": Validates evidence points programmatically. For "format": Formats a completed analysis into HTML/JSON/Markdown.',domain:"requirements-validation",schema:Mm,streaming:!0,timeout:12e4};service=null;getService(){return this.service||(this.service=ir()),this.service}async execute(e,t){let{assessmentName:n,epicPath:r,epicContent:i,sourcePaths:s,outputFormat:a="html",outputPath:c,evidencePoints:l,completedAnalysis:u,action:d="analyze"}=e;try{let m=this.getService();if(this.emitStream(t,{status:"starting",message:`Quality Criteria: ${d} - ${n}`,action:d}),this.isAborted(t))return{success:!1,error:"Operation aborted"};if(d==="validate-evidence"){if(!l||l.length===0)return{success:!1,error:"validate-evidence action requires evidencePoints array"};this.emitStream(t,{status:"validating",message:`Validating ${l.length} evidence points`});let h=m.validateEvidence(l);return{success:!0,data:{evidenceValidation:h,message:h.valid?`All ${l.length} evidence points are valid`:`Validation failed with ${h.errors.length} errors`}}}if(d==="format"){if(!u)return{success:!1,error:"format action requires completedAnalysis object"};this.emitStream(t,{status:"formatting",message:`Formatting analysis as ${a}`});let h,y,v;switch(a){case"html":h=m.generateHTML(u);break;case"json":y=JSON.stringify(u,null,2);break;case"markdown":v=m.generateMarkdown(u);break}return{success:!0,data:{html:h,json:y,markdown:v,message:`Analysis formatted as ${a}`}}}this.emitStream(t,{status:"preparing",message:"Preparing agent invocation for semantic HTSM analysis"});let p=i||"";if(r){let h=await X("quality-criteria","epicPath",r,{allowMissing:!0,maxBytes:ne});if(!h.success)return{success:!1,error:h.error.message};try{p=await de(h.value,{maxBytes:ne})}catch(y){if(!(y instanceof Fs)||y.reason!=="not-found")return{success:!1,error:w(y)}}}if(!p&&!r)return{success:!1,error:"Either epicPath or epicContent is required for analysis"};let g={required:!0,agentType:"qe-quality-criteria-recommender",prompt:this.buildAgentPrompt({assessmentName:n,epicContent:p,epicPath:r,sourcePaths:s,outputFormat:a,outputPath:c}),timeout:3e5,expectedOutput:"QualityCriteriaAnalysis",instructions:`Claude Code MUST spawn the qe-quality-criteria-recommender agent with this prompt. The agent will perform real semantic HTSM analysis using Claude's reasoning capabilities. Use: Task("HTSM Quality Criteria Analysis", { prompt: <this prompt> }, "qe-quality-criteria-recommender")`};return this.emitStream(t,{status:"agent-required",message:"Agent invocation prepared. Claude Code must spawn qe-quality-criteria-recommender agent.",agentType:"qe-quality-criteria-recommender"}),{success:!0,data:{agentInvocation:g,message:"AGENT INVOCATION REQUIRED: This tool cannot perform semantic HTSM analysis alone. Claude Code must spawn the qe-quality-criteria-recommender agent with the provided prompt."}}}catch(m){return{success:!1,error:`Quality Criteria tool failed: ${w(m)}`}}}buildAgentPrompt(e){let{assessmentName:t,epicContent:n,epicPath:r,sourcePaths:i,outputFormat:s,outputPath:a}=e,c=i&&i.length>0?`
580
571
  ## Source Paths to Analyze
581
- ${i.map(d=>`- ${d}`).join(`
572
+ ${i.map(u=>`- ${u}`).join(`
582
573
  `)}
583
574
  `:"",l=a?`
584
575
  ## Output
@@ -605,11 +596,11 @@ ${c}
605
596
  Perform HTSM v6.3 Quality Criteria analysis on the above requirements.
606
597
 
607
598
  ### HTSM Categories to Analyze
608
- ${st.map((d,u)=>`${u+1}. ${d}`).join(`
599
+ ${at.map((u,d)=>`${d+1}. ${u}`).join(`
609
600
  `)}
610
601
 
611
602
  ### Categories That CANNOT Be Omitted
612
- ${at.map(d=>`- ${d}`).join(`
603
+ ${ot.map(u=>`- ${u}`).join(`
613
604
  `)}
614
605
 
615
606
  ### Evidence Classification
@@ -650,25 +641,25 @@ Return a complete QualityCriteriaAnalysis object with:
650
641
  ${l}
651
642
  ## Begin Analysis
652
643
 
653
- Analyze the requirements above and return the complete QualityCriteriaAnalysis.`}resetInstanceCache(){this.service=null}},Fm={type:"object",properties:{assessmentName:{type:"string",description:"Assessment name (e.g., Epic title or feature name)"},epicPath:{type:"string",description:"Path to epic/requirements document"},epicContent:{type:"string",description:"Epic content as string (alternative to epicPath)"},sourcePaths:{type:"array",description:"Source code paths to analyze for evidence",items:{type:"string",description:"Source path glob pattern"}},outputFormat:{type:"string",description:"Output format for the report",enum:["html","json","markdown"],default:"html"},outputPath:{type:"string",description:"Path to save the output report"},evidencePoints:{type:"array",description:"Evidence points to validate (for validate-evidence action)",items:{type:"object",description:"Evidence point object",properties:{sourceReference:{type:"string",description:"Source reference in file:line format"},type:{type:"string",enum:["Direct","Inferred","Claimed"],description:"Evidence type"},qualityImplication:{type:"string",description:"Quality implication of this evidence"},reasoning:{type:"string",description:"Reasoning explaining WHY it matters"}},required:["sourceReference","type","qualityImplication","reasoning"]}},completedAnalysis:{type:"object",description:"Completed QualityCriteriaAnalysis object (for format action)"},action:{type:"string",description:'Action to perform. "analyze" (default) returns agentInvocation for real analysis. "validate-evidence" validates evidence format. "format" formats completed analysis.',enum:["analyze","validate-evidence","format"],default:"analyze"}},required:["assessmentName"]},jT=new Ot;import*as Hi from"fs";import*as Ae from"path";D();var sr=class extends A{config={name:"qe/code/analyze",description:"Analyze code using knowledge graph and semantic search. Supports indexing, searching, impact analysis, and dependency mapping.",domain:"code-intelligence",schema:Lm,streaming:!0,timeout:3e5};knowledgeGraph=null;semanticAnalyzer=null;impactAnalyzer=null;async getKnowledgeGraph(e){if(!this.knowledgeGraph){let t=e.memory??await q(),n=await V(e);this.knowledgeGraph=new dn({memory:t,llmRouter:n})}return this.knowledgeGraph}async getSemanticAnalyzer(e){if(!this.semanticAnalyzer){let t=e.memory;this.semanticAnalyzer=new ya(t||await q())}return this.semanticAnalyzer}async getImpactAnalyzer(e){if(!this.impactAnalyzer){let t=e.memory,n=await this.getKnowledgeGraph(e);this.impactAnalyzer=new va(t||await q(),n)}return this.impactAnalyzer}async execute(e,t){let{action:n,paths:r=["."],query:i,changedFiles:s=[],depth:a=3,incremental:c=!1}=e;try{if(this.emitStream(t,{status:"processing",message:`Executing ${n} action`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let l={action:n};switch(n){case"index":l.indexResult=await this.executeIndex(r,c,t);break;case"search":if(!i)return{success:!1,error:"Query is required for search action"};l.searchResult=await this.executeSearch(i,r,t);break;case"impact":if(s.length===0)return{success:!1,error:"changedFiles is required for impact action"};l.impactResult=await this.executeImpact(s,a,t);break;case"dependencies":l.dependencyResult=await this.executeDependencies(r,a,t);break;default:return{success:!1,error:`Unknown action: ${n}`}}return this.emitStream(t,{status:"complete",message:`${n} complete`,progress:100}),{success:!0,data:l}}catch(l){return{success:!1,error:`Code analysis failed: ${w(l)}`}}}async executeIndex(e,t,n){this.emitStream(n,{status:"indexing",message:`Indexing ${e.length} paths (${t?"incremental":"full"})`});let r=await this.getKnowledgeGraph(n),i=await this.expandPaths(e),s=await r.index({paths:i,incremental:t,includeTests:!0,languages:["typescript","javascript"]});if(!s.success)throw new Error(s.error?.message||"Indexing failed");return{filesIndexed:s.value.filesIndexed,nodesCreated:s.value.nodesCreated,edgesCreated:s.value.edgesCreated,duration:s.value.duration,errors:s.value.errors}}async executeSearch(e,t,n){let r=Date.now();if(this.isDemoMode(n)){let l=Date.now()-r;return this.markAsDemoData(n,"Demo mode explicitly requested"),this.getDemoSearchResult(e,l)}this.emitStream(n,{status:"searching",message:`Searching for: ${e}`});let s=await(await this.getSemanticAnalyzer(n)).search({query:e,type:"semantic",limit:20,scope:t.length>0&&t[0]!=="."?t:void 0}),a=Date.now()-r;if(!s.success)throw s.error;return s.value.results.length===0?(this.markAsRealData(),{results:[],total:0,searchTime:a}):(this.markAsRealData(),{results:s.value.results.map(l=>({file:l.file,line:l.line,snippet:l.snippet.substring(0,200)+(l.snippet.length>200?"...":""),score:l.score,highlights:qm(l.snippet,e)})),total:s.value.total,searchTime:a})}getDemoSearchResult(e,t){return{results:[{file:"src/services/UserService.ts",line:15,snippet:`export class ${e} { constructor() { /* initialization */ } }...`,score:.95,highlights:[e,`class ${e}`,`${e}Service`]},{file:"src/handlers/user-handler.ts",line:42,snippet:`const service = new ${e}(); await service.initialize()...`,score:.85,highlights:[`new ${e}()`,`service.${e.toLowerCase()}`]},{file:"tests/services/UserService.test.ts",line:8,snippet:`describe('${e}', () => { it('should initialize correctly'...`,score:.78,highlights:[`describe('${e}'`,`test ${e}`]}],total:3,searchTime:t}}getDemoImpactResult(e){let t=e[0]||"src/service.ts",n=t.split("/").pop()?.replace(".ts","")||"service";return{directImpact:[{file:`src/handlers/${n}-handler.ts`,reason:`Direct import from ${t}`,distance:0,riskScore:.75},{file:`src/controllers/${n}-controller.ts`,reason:`Uses exported functions from ${t}`,distance:0,riskScore:.65}],transitiveImpact:[{file:"src/routes/api.ts",reason:`Imports from ${n}-handler.ts`,distance:1,riskScore:.45},{file:"src/app.ts",reason:"Imports API routes",distance:2,riskScore:.25}],impactedTests:[`tests/${n}.test.ts`,`tests/${n}-handler.test.ts`,"tests/integration/api.test.ts"],riskLevel:"medium",recommendations:[`Review changes in ${t} for breaking changes`,"Run affected test suites before merging","Consider updating dependent documentation"]}}async executeImpact(e,t,n){if(this.isDemoMode(n))return this.markAsDemoData(n,"Demo mode explicitly requested"),this.getDemoImpactResult(e);this.emitStream(n,{status:"analyzing",message:`Analyzing impact of ${e.length} changed files`});try{let i=await(await this.getImpactAnalyzer(n)).analyzeImpact({changedFiles:e,depth:t,includeTests:!0});if(!i.success)return{directImpact:[],transitiveImpact:[],impactedTests:[],riskLevel:"low",recommendations:[`Impact analysis failed: ${i.error?.message||"Unknown error"}. Ensure the code index is built first using action: 'index'.`]};this.markAsRealData();let s=i.value;return{directImpact:s.directImpact,transitiveImpact:s.transitiveImpact,impactedTests:s.impactedTests,riskLevel:s.riskLevel,recommendations:s.recommendations}}catch(r){return{directImpact:[],transitiveImpact:[],impactedTests:[],riskLevel:"low",recommendations:[`Impact analysis error: ${r instanceof Error?r.message:"Unknown error"}. Check that files exist and index is built.`]}}}async executeDependencies(e,t,n){this.emitStream(n,{status:"mapping",message:`Mapping dependencies to depth ${t}`});let r=await this.getKnowledgeGraph(n),i=await this.expandPaths(e),s=await r.mapDependencies({files:i,direction:"both",depth:t});if(!s.success)throw new Error(s.error?.message||"Dependency mapping failed");let a=s.value,c=a.nodes.map(d=>({id:d.id,path:d.path,type:d.type,inDegree:d.inDegree,outDegree:d.outDegree})),l=a.edges.map(d=>({source:d.source,target:d.target,type:d.type}));return{nodes:c,edges:l,cycles:a.cycles,metrics:{totalNodes:a.metrics.totalNodes,totalEdges:a.metrics.totalEdges,avgDegree:a.metrics.avgDegree,maxDepth:a.metrics.maxDepth}}}async expandPaths(e){let t=[];for(let n of e){let r=Ae.isAbsolute(n)?n:Ae.resolve(process.cwd(),n);try{let i=await Hi.promises.stat(r);if(i.isDirectory()){let s=await this.findSourceFiles(r);t.push(...s)}else i.isFile()&&t.push(r)}catch{}}return t}async findSourceFiles(e,t=!0){let n=[],r=[".ts",".tsx",".js",".jsx"],i=["node_modules",".git","dist","build","coverage"];try{let s=await Hi.promises.readdir(e,{withFileTypes:!0});for(let a of s){let c=Ae.join(e,a.name);if(a.isDirectory()){if(!i.includes(a.name)&&!Xs(e,a.name,t)){let l=await this.findSourceFiles(c,!1);n.push(...l)}}else if(a.isFile()){let l=Ae.extname(a.name);r.includes(l)&&n.push(c)}}}catch{}return n}},Lm={type:"object",properties:{action:{type:"string",description:"Analysis action to perform",enum:["index","search","impact","dependencies"]},paths:{type:"array",description:"Paths to analyze",items:{type:"string",description:"File or directory path"},default:["."]},query:{type:"string",description:"Search query (for search action)"},changedFiles:{type:"array",description:"Changed files to analyze (for impact action)",items:{type:"string",description:"File path"}},depth:{type:"number",description:"Analysis depth",minimum:1,maximum:10,default:3},incremental:{type:"boolean",description:"Incremental indexing (for index action)",default:!1}},required:["action"]};function qm(o,e){let t=[],n=e.toLowerCase().split(/\s+/),r=o.toLowerCase();for(let i of n){if(i.length<2)continue;let s=0;for(;(s=r.indexOf(i,s))!==-1;){let a=Math.max(0,s-20),c=Math.min(o.length,s+i.length+20),l=o.substring(a,c);if(t.includes(l)||t.push(l),s+=i.length,t.length>=3)break}if(t.length>=3)break}return t}D();var Vi=(o,e)=>o==="all"||o===e,ar=class extends A{config={name:"qe/code/c4",description:"Generate C4 architecture diagrams (Context/Container/Component, Mermaid) from a codebase with a deterministic confidence gate, or semantically search previously generated diagrams.",domain:"code-intelligence",schema:$m,streaming:!1,timeout:3e5};bridge=null;searchService=null;async getBridge(e){if(!this.bridge){let t=e.memory??await q();this.bridge=new fa(new ws,t,{publishEvents:!1,enableC4Embeddings:!0,relationshipResolver:ha(n=>new dn(t,{basePath:n}))})}return this.bridge}async getSearchService(e){if(!this.searchService){let t=e.memory??await q();this.searchService=new ga(t,{enableEmbeddings:!0})}return this.searchService}async execute(e,t){let{action:n,projectPath:r=".",level:i="all",query:s,limit:a=10}=e,c=r;if(r!=="."){let l=await K("qe/code/c4","projectPath",r,{allowDirectory:!0});if(!l.success)return{success:!1,error:l.error.message};c=l.value}try{if(this.isAborted(t))return{success:!1,error:"Operation aborted"};let l={action:n};switch(n){case"generate":{let u=await(await this.getBridge(t)).requestC4Diagrams({projectPath:c,includeContext:Vi(i,"context"),includeContainer:Vi(i,"container"),includeComponent:Vi(i,"component"),includeDependency:i==="all",analyzeComponents:!0,detectExternalSystems:!0,analyzeCoupling:!0});if(!u.success)return{success:!1,error:w(u.error)};let m=u.value;l.generateResult={diagrams:m.diagrams,confidence:m.metadata.analysisMetadata?.confidence,componentsDetected:m.components.length,externalSystemsDetected:m.externalSystems.length,relationshipsDetected:m.relationships.length,circularDependencies:(m.couplingAnalysis??[]).filter(p=>p.isCircular).length};break}case"search":{if(!s)return{success:!1,error:"Query is required for search action"};let u=await(await this.getSearchService(t)).searchDiagrams(s,a);if(!u.success)return{success:!1,error:w(u.error)};l.searchResult={results:u.value.map(m=>({key:m.key,type:m.type,title:m.title,score:m.score,preview:m.preview})),total:u.value.length};break}default:return{success:!1,error:`Unknown action: ${n}`}}return{success:!0,data:l}}catch(l){return{success:!1,error:w(l)}}}},$m={type:"object",properties:{action:{type:"string",description:"C4 action to perform",enum:["generate","search"]},projectPath:{type:"string",description:"Project root to analyze (generate action). Defaults to the current directory."},level:{type:"string",description:"C4 level to generate (generate action)",enum:["context","container","component","all"]},query:{type:"string",description:"Semantic search query over stored diagrams (search action)"},limit:{type:"number",description:"Max search results (search action)"}},required:["action"]};D();ee();Cs();var Yc=[{id:"secret-key-assignment",pattern:/(?:SECRET_KEY|secret_key|SECRET|PRIVATE_KEY)\s*=\s*['"][^'"]{4,}['"]/g,severity:"critical",title:"Hardcoded Secret Key",description:"Secret key assigned as string literal in source code",cweId:"CWE-798",remediation:'Use environment variables: SECRET_KEY = os.environ["SECRET_KEY"]'},{id:"cors-wildcard-credentials",pattern:/allow_origins\s*=\s*\[\s*["']\*["']\s*\]/g,severity:"high",title:"CORS Wildcard Origin",description:"CORS configured to allow all origins \u2014 combined with credentials this is a security risk",cweId:"CWE-942",remediation:"Restrict CORS origins to specific trusted domains"},{id:"cors-allow-credentials-wildcard",pattern:/allow_credentials\s*=\s*True/g,severity:"medium",title:"CORS Credentials Enabled",description:"CORS credentials enabled \u2014 verify origins are restricted",cweId:"CWE-942",remediation:'Ensure allow_origins does not include "*" when credentials are enabled'},{id:"token-hardcoded",pattern:/(?:token|TOKEN)\s*[:=]\s*['"][a-zA-Z0-9_\-.]{20,}['"]/g,severity:"high",title:"Hardcoded Token",description:"Hardcoded token found in source code",cweId:"CWE-798",remediation:"Use environment variables or secrets manager for tokens"}],or=class extends A{config={name:"qe/security/scan",description:"Comprehensive security scanning including SAST, DAST, dependency analysis, and compliance validation.",domain:"security-compliance",schema:Gm,streaming:!0,timeout:6e5};async execute(e,t){let{target:n=".",scanType:r=["sast","dependency"],compliance:i=[],dastUrl:s,depth:a="standard",failOnSeverity:c="critical"}=e,l=Date.now();try{if(this.emitStream(t,{status:"scanning",message:`Starting security scan (${r.join(", ")})`,depth:a}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let d=await Um(n,a);this.emitStream(t,{status:"discovered",message:`Found ${d.length} files to scan`});let u=[];if(r.includes("sast")||r.includes("secret")){this.emitStream(t,{status:"sast",message:"Running static analysis"});let y=await Bm(d,r);u.push(...y)}if(r.includes("dependency")){this.emitStream(t,{status:"dependency",message:"Scanning dependencies"});let y=await Hm(n);u.push(...y)}r.includes("dast")&&s&&(this.emitStream(t,{status:"dast",message:`Scanning ${s}`}),u.push(...Jm(s)));let m=i.map(y=>Zm(y,u)),p={critical:u.filter(y=>y.severity==="critical").length,high:u.filter(y=>y.severity==="high").length,medium:u.filter(y=>y.severity==="medium").length,low:u.filter(y=>y.severity==="low").length,informational:u.filter(y=>y.severity==="informational").length,totalFiles:d.length,scanDurationMs:Date.now()-l},g=["critical","high","medium","low","informational"],f=g.indexOf(c),v=(u.length>0?Math.min(...u.map(y=>g.indexOf(y.severity))):g.length)>f;return await on(await hn(t),{securityVulnerabilities:u.length},{measuredAt:new Date().toISOString(),source:"qe/security/scan"}),this.emitStream(t,{status:"complete",message:`Scan complete: ${u.length} vulnerabilities found in ${d.length} files`,progress:100}),{success:!0,data:{scanId:t.requestId,summary:p,vulnerabilities:u,complianceResults:m.length>0?m:void 0,recommendations:ep(u,p),passed:v}}}catch(d){return{success:!1,error:`Security scan failed: ${w(d)}`}}}},Gm={type:"object",properties:{target:{type:"string",description:"Target directory or file to scan",default:"."},scanType:{type:"array",description:"Types of security scans to run",items:{type:"string",description:"Scan type",enum:["sast","dast","dependency","secret"]},default:["sast","dependency"]},compliance:{type:"array",description:"Compliance standards to validate against",items:{type:"string",description:"Standard",enum:["owasp","gdpr","hipaa","pci-dss","soc2"]}},dastUrl:{type:"string",description:"URL for DAST scanning"},depth:{type:"string",description:"Scan depth",enum:["quick","standard","deep"],default:"standard"},failOnSeverity:{type:"string",description:"Fail threshold severity",enum:["critical","high","medium","low"],default:"critical"}}},jm=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".pyw",".java",".kt",".scala",".go",".rb",".php",".rs",".cs",".yaml",".yml",".json",".toml",".cfg",".ini",".env",".env.local",".env.production",".sh",".bash"]),zm=new Set(["node_modules",".git","__pycache__",".venv","venv","dist","build",".next",".nuxt","coverage",".tox"]);async function Um(o,e){let t=await import("fs"),n=await import("path"),r=n.resolve(o),i=[],s=e==="quick"?50:e==="standard"?500:2e3,a=e==="quick"?3:e==="standard"?8:20;function c(l,d){if(i.length>=s||d>a)return;let u;try{u=t.readdirSync(l,{withFileTypes:!0})}catch{return}for(let m of u){if(i.length>=s)break;let p=n.join(l,m.name);if(m.isDirectory()){let g=new Set([".github",".docker",".aws",".circleci",".gitlab"]);zm.has(m.name)||m.name.startsWith(".")&&!g.has(m.name)||c(p,d+1)}else if(m.isFile()){let g=n.extname(m.name).toLowerCase();(jm.has(g)||m.name==="Dockerfile"||m.name==="Makefile"||m.name.startsWith(".env"))&&i.push(p)}}}try{t.statSync(r).isFile()?i.push(r):c(r,0)}catch{}return i}async function Bm(o,e){let t=await import("fs"),n=await import("path"),r=[],i=0,s=[];if(e.includes("sast")){for(let a of Ea)s.push({id:a.id,pattern:new RegExp(a.pattern.source,a.pattern.flags),severity:a.severity,title:a.title,description:a.description,cweId:a.cweId,remediation:a.remediation,category:a.category});for(let a of Yc)s.push({id:a.id,pattern:new RegExp(a.pattern.source,a.pattern.flags),severity:a.severity,title:a.title,description:a.description,cweId:a.cweId,remediation:a.remediation,category:"sensitive-data"})}if(e.includes("secret")){for(let a of Ta)s.some(c=>c.id===a.id)||s.push({id:a.id,pattern:new RegExp(a.pattern.source,a.pattern.flags),severity:a.severity,title:a.title,description:a.description,cweId:a.cweId,remediation:a.remediation,category:a.category});for(let a of Yc)s.some(c=>c.id===a.id)||s.push({...a,category:"sensitive-data"})}for(let a of o){let c;try{c=t.readFileSync(a,"utf-8")}catch{continue}if(c.includes("\0")||c.length>1e6)continue;let l=c.split(`
654
- `),d=n.relative(process.cwd(),a);for(let u of s){let m=new RegExp(u.pattern.source,u.pattern.flags),p;for(;(p=m.exec(c))!==null;){i++;let g=c.substring(0,p.index).split(`
655
- `).length,f=l[g-1]||"",h=f.trim().length>100?f.trim().substring(0,100)+"...":f.trim();if(r.push({id:`${u.id}-${i}`,title:u.title,severity:u.severity,category:u.category||"security-misconfiguration",location:{file:d,line:g,snippet:h},description:u.description,remediation:u.remediation,cweId:u.cweId,references:[]}),i>200)break}}}return r}async function Hm(o){let e=await import("fs"),t=await import("path"),n=[],r=t.resolve(o),i=t.join(r,"package.json");if(e.existsSync(i))try{let c=I(e.readFileSync(i,"utf-8")),l={...c.dependencies,...c.devDependencies};n.push(...Qm(l,"package.json"))}catch{}let s=t.join(r,"pyproject.toml");if(e.existsSync(s))try{let c=e.readFileSync(s,"utf-8"),l=Km(c);n.push(...Jc(l,"pyproject.toml"))}catch{}let a=t.join(r,"requirements.txt");if(e.existsSync(a))try{let c=e.readFileSync(a,"utf-8"),l=Xm(c);n.push(...Jc(l,"requirements.txt"))}catch{}if(n.length===0){let c=[i,s,a].filter(l=>e.existsSync(l));c.length>0&&n.push({id:"DEP-INFO-001",title:"Dependency audit recommended",severity:"informational",category:"vulnerable-components",location:{file:t.relative(process.cwd(),c[0])},description:`Found ${t.basename(c[0])} \u2014 run language-specific dependency audit for comprehensive results`,remediation:"Run npm audit, pip-audit, or equivalent for full vulnerability check",references:[]})}return n}var Vm={lodash:{maxSafe:"4.17.21",cve:"CVE-2021-23337",severity:"high",desc:"Prototype pollution in lodash"},minimist:{maxSafe:"1.2.6",cve:"CVE-2021-44906",severity:"critical",desc:"Prototype pollution in minimist"},"node-fetch":{maxSafe:"2.6.7",cve:"CVE-2022-0235",severity:"high",desc:"Information exposure in node-fetch"},express:{maxSafe:"4.19.2",cve:"CVE-2024-29041",severity:"medium",desc:"Open redirect in express"}};function Qm(o,e){let t=[];for(let[n,r]of Object.entries(o)){let i=Rr(Vm,n);if(i){let s=r.replace(/^[\^~>=<]+/,"");Ym(s,i.maxSafe)<0&&t.push({id:`DEP-${n}-${i.cve}`,title:`Vulnerable ${n} version`,severity:i.severity,category:"vulnerable-components",location:{file:e,dependency:{name:n,version:s}},description:i.desc,remediation:`Upgrade ${n} to >= ${i.maxSafe}`,cveId:i.cve,references:[`https://nvd.nist.gov/vuln/detail/${i.cve}`]})}}return t}var Wm={"python-jose":{cve:"CVE-2024-33663",severity:"critical",desc:"python-jose is abandoned and has known JWT vulnerabilities"},pyjwt:{cve:"CVE-2022-29217",severity:"high",desc:"PyJWT algorithm confusion vulnerability (upgrade to >= 2.4.0)"},"python-multipart":{cve:"CVE-2026-24486",severity:"high",desc:"python-multipart DoS vulnerability"},jinja2:{cve:"CVE-2024-34064",severity:"medium",desc:"Jinja2 XSS via template injection"},urllib3:{cve:"CVE-2023-45803",severity:"medium",desc:"urllib3 request body exposure on redirect"},requests:{cve:"CVE-2023-32681",severity:"medium",desc:"Requests proxy credential exposure"}};function Km(o){let e=[],t=o.match(/dependencies\s*=\s*\[([\s\S]*?)\]/);if(t){let n=t[1].matchAll(/["']([a-zA-Z0-9_-]+)/g);for(let r of n)e.push(r[1].toLowerCase())}return e}function Xm(o){return o.split(`
656
- `).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")).map(e=>e.split(/[>=<!~\[]/)[0].trim().toLowerCase()).filter(Boolean)}function Jc(o,e){let t=[];for(let n of o){let r=Rr(Wm,n);r&&t.push({id:`DEP-py-${n}-${r.cve}`,title:`Vulnerable Python dependency: ${n}`,severity:r.severity,category:"vulnerable-components",location:{file:e,dependency:{name:n,version:"any"}},description:r.desc,remediation:n==="python-jose"?"Migrate to PyJWT or joserfc":`Check for updates to ${n}`,cveId:r.cve,references:[`https://nvd.nist.gov/vuln/detail/${r.cve}`]})}return t}function Ym(o,e){let t=o.split(".").map(Number),n=e.split(".").map(Number);for(let r=0;r<3;r++){let i=t[r]||0,s=n[r]||0;if(i<s)return-1;if(i>s)return 1}return 0}function Jm(o){return[{id:"DAST-INFO-001",title:"DAST scan target noted",severity:"informational",category:"security-misconfiguration",location:{file:o},description:`DAST target ${o} recorded. Full DAST requires integration with a dynamic scanner (e.g., ZAP, Burp).`,remediation:"Configure a DAST tool to scan the live application",references:["https://owasp.org/www-project-zap/"]}]}function Zm(o,e){let t=e.filter(n=>o==="owasp"?!0:o==="pci-dss"?n.category==="injection"||n.category==="sensitive-data":o==="gdpr"?n.category==="sensitive-data":!1);return{standard:o,passed:t.filter(n=>n.severity==="critical"||n.severity==="high").length===0,score:Math.max(0,100-t.length*15),violations:t.map(n=>({ruleId:n.id,ruleName:n.title,location:n.location,details:n.description,remediation:n.remediation}))}}function ep(o,e){let t=[];return e.critical>0&&t.push("URGENT: Address critical vulnerabilities immediately"),e.high>0&&t.push("Prioritize high-severity issues in next sprint"),o.some(n=>n.category==="injection")&&t.push("Review input validation across the application"),o.some(n=>n.category==="sensitive-data")&&t.push("Implement proper secrets management"),o.some(n=>n.category==="vulnerable-components")&&t.push("Run full dependency audit and update vulnerable packages"),t.length===0&&t.push("No critical issues found. Continue regular security reviews."),t}ee();D();function Zc(o){try{let e=new URL(o);if(!["http:","https:"].includes(e.protocol))return{valid:!1,error:`Invalid protocol: ${e.protocol}. Only http/https allowed.`};let t=e.hostname.toLowerCase(),n=[/^localhost$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2[0-9]|3[01])\./,/^192\.168\./,/^0\.0\.0\.0$/,/^\[::1\]$/,/^169\.254\./];for(let r of n)if(r.test(t))return{valid:!1,error:`Blocked hostname: ${t}. Cannot access internal/private addresses.`};return{valid:!0}}catch{return{valid:!1,error:`Invalid URL format: ${o}`}}}var cr=class extends A{config={name:"qe/contracts/validate",description:"Validate API contracts, detect breaking changes, and verify provider-consumer compatibility.",domain:"contract-testing",schema:tp,streaming:!0,timeout:18e4};contractValidator=null;apiCompatibility=null;async getServices(e){if(!this.contractValidator||!this.apiCompatibility){let t=e.memory||await q(),n=await V(e);this.contractValidator=new wa({memory:t,llmRouter:n}),this.apiCompatibility=new Ra(t)}return{contractValidator:this.contractValidator,apiCompatibility:this.apiCompatibility}}async execute(e,t){let{contractPath:n,contractContent:r,providerUrl:i,consumerName:s,baselineVersion:a,baselineContent:c,checkBreakingChanges:l=!0,format:d="openapi"}=e,{contractValidator:u,apiCompatibility:m}=await this.getServices(t);try{if(!n&&!r)return{success:!1,error:"Either contractPath or contractContent is required"};if(this.emitStream(t,{status:"validating",message:`Validating ${d} contract`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let p=r||n||"",g=[],f,h,v;if(d==="openapi"){let b=await u.validateOpenAPI(p);if(b.success){let E=b.value;for(let T of E.errors)g.push({path:T.path,message:T.message,code:T.code,severity:"error"});for(let T of E.warnings)g.push({path:"",message:T,code:"WARNING",severity:"warning"});this.emitStream(t,{status:"analyzed",message:`Found ${E.endpointCount} endpoints, ${E.schemaCount} schemas`})}}else{let b=this.buildContractFromContent(p,d,s),E=await u.validateContract(b);if(E.success){let T=E.value;for(let S of T.errors)g.push(this.convertValidationError(S));for(let S of T.warnings)g.push({path:"",message:S,code:"WARNING",severity:"warning"})}}if(l&&(a||c)){this.emitStream(t,{status:"comparing",message:"Detecting breaking changes"});let b=this.buildContractFromContent(p,d,s),E=this.buildContractFromContent(c||p,d,s,a),T=await m.compareVersions(E,b);T.success?(f=T.value.breakingChanges.map(S=>this.convertBreakingChange(S)),v={isBackwardCompatible:T.value.isCompatible,breakingChangeCount:T.value.breakingChanges.length,nonBreakingChangeCount:T.value.nonBreakingChanges.length,deprecations:T.value.deprecations.map(S=>this.convertDeprecation(S))}):v=this.generateDefaultCompatibility(g,f)}else v=this.generateDefaultCompatibility(g,f);i&&(this.emitStream(t,{status:"verifying",message:"Verifying against provider"}),h=await this.verifyAgainstProvider(i,s||"default",p,d,u));let y=g.filter(b=>b.severity==="error").length===0,C=this.generateRecommendations(g,f,h);return this.emitStream(t,{status:"complete",message:y?"Contract is valid":`Found ${g.length} issues`,progress:100}),{success:!0,data:{isValid:y,validationErrors:g,breakingChanges:f,verificationResult:h,compatibility:v,recommendations:C}}}catch(p){return{success:!1,error:`Contract validation failed: ${w(p)}`}}}buildContractFromContent(e,t,n,r){let i=`contract-${Date.now()}`,s=Sa.parse(r||"1.0.0"),a=[],c=[];if(t==="openapi")try{let l=I(e),u=l.components?.schemas||{};for(let[p,g]of Object.entries(u))a.push({id:p,name:p,type:"openapi",content:JSON.stringify(g)});let m=l.paths||{};for(let[p,g]of Object.entries(m))if(typeof g=="object"&&g!==null){let f=g,h=["get","post","put","patch","delete","head","options"];for(let v of h)v in f&&c.push({path:p,method:v.toUpperCase(),examples:[]})}}catch{}else if(t==="graphql")a.push({id:"graphql-schema",name:"GraphQL Schema",type:"graphql",content:e});else if(t==="pact")try{let d=I(e).interactions||[];for(let u of d){let m=u.request;m&&c.push({path:m.path||"/",method:(m.method||"GET").toUpperCase(),examples:[]})}}catch{}return{id:i,name:`${t}-contract`,version:s,type:t,provider:{name:"provider",version:"1.0.0"},consumers:[{name:n||"default",version:"1.0.0"}],endpoints:c,schemas:a}}convertValidationError(e){return{path:e.path,message:e.message,code:e.code,severity:"error"}}convertBreakingChange(e){return{type:e.type,location:e.location,description:e.description,impact:e.impact,affectedConsumers:e.affectedConsumers,migrationPath:e.migrationPath}}convertDeprecation(e){return{location:e.location,reason:e.reason,removalVersion:e.removalVersion,replacement:e.replacement}}generateDefaultCompatibility(e,t){return{isBackwardCompatible:!t||t.length===0,breakingChangeCount:t?.length||0,nonBreakingChangeCount:e.filter(n=>n.severity!=="error").length,deprecations:[]}}async verifyAgainstProvider(e,t,n,r,i){let s=[],a=[],c=Zc(e);if(!c.valid)return{provider:e,consumer:t,passed:!1,failures:[{endpoint:e,type:"validation-error",expected:"Valid HTTP/HTTPS URL",actual:c.error||"Invalid URL",message:`Provider URL validation failed: ${c.error}`}],warnings:[]};let l=this.buildContractFromContent(n,r,t);for(let d of l.endpoints)try{let u=`${e}${d.path}`,m=Zc(u);if(!m.valid){s.push({endpoint:`${d.method} ${d.path}`,type:"validation-error",expected:"Valid URL",actual:m.error||"Invalid URL",message:`URL validation failed: ${m.error}`});continue}let p=await fetch(u,{method:d.method==="GET"?"GET":"OPTIONS",headers:{Accept:"application/json"}});if(!p.ok&&p.status!==405&&(p.status===404?s.push({endpoint:`${d.method} ${d.path}`,type:"missing-endpoint",expected:"Endpoint should exist",actual:`Got ${p.status}`,message:"Endpoint not found at provider"}):a.push({endpoint:`${d.method} ${d.path}`,message:`Unexpected status ${p.status}`,severity:"medium"})),d.responseSchema&&p.ok){let g=await p.json(),f=l.schemas.find(h=>h.id===d.responseSchema);if(f){let h=await i.validateResponse(g,f);if(h.success&&!h.value.isValid)for(let v of h.value.errors)s.push({endpoint:`${d.method} ${d.path}`,type:"schema-mismatch",expected:`Schema ${d.responseSchema}`,actual:v.message,message:`Response does not match schema: ${v.message}`})}}}catch(u){a.push({endpoint:`${d.method} ${d.path}`,message:`Failed to verify: ${w(u)}`,severity:"high"})}return{provider:e,consumer:t,passed:s.length===0,failures:s,warnings:a}}generateRecommendations(e,t,n){let r=[],i=e.filter(a=>a.severity==="error").length;if(i>0&&r.push(`Fix ${i} validation error${i>1?"s":""} before deploying`),t&&t.length>0){let a=t.filter(c=>c.impact==="high").length;a>0&&r.push(`Address ${a} high-impact breaking change${a>1?"s":""} before release`),r.push("Coordinate with affected consumers before releasing breaking changes"),r.push("Consider versioning the API to maintain backward compatibility")}n&&(n.passed||(r.push(`Provider verification failed with ${n.failures.length} failure${n.failures.length>1?"s":""}`),n.failures.filter(l=>l.type==="missing-endpoint").length>0&&r.push("Ensure all contract endpoints are implemented in the provider"),n.failures.filter(l=>l.type==="schema-mismatch").length>0&&r.push("Update provider responses to match the contract schema")),n.warnings.length>0&&n.warnings.filter(c=>c.severity==="high").length>0&&r.push("Investigate high-severity verification warnings"));let s=e.filter(a=>a.severity==="warning").length;return s>0&&r.push(`Review ${s} warning${s>1?"s":""} for potential issues`),r.length===0&&r.push("Contract is valid and backward compatible"),r}},tp={type:"object",properties:{contractPath:{type:"string",description:"Path to contract file"},contractContent:{type:"string",description:"Contract content as string"},providerUrl:{type:"string",description:"Provider URL for verification"},consumerName:{type:"string",description:"Consumer name for contract"},baselineVersion:{type:"string",description:"Baseline version for breaking change detection"},baselineContent:{type:"string",description:"Baseline contract content for comparison"},checkBreakingChanges:{type:"boolean",description:"Check for breaking changes",default:!0},format:{type:"string",description:"Contract format",enum:["openapi","pact","graphql","asyncapi"],default:"openapi"}}};D();var lr=class extends A{config={name:"qe/visual/compare",description:"Visual regression testing with screenshot comparison, diff detection, and baseline management.",domain:"visual-accessibility",schema:np,streaming:!0,timeout:3e5};visualTester=null;async getService(e){if(!this.visualTester){let t=e.memory??await q(),n=await V(e);this.visualTester=Pa({memory:t,llmRouter:n})}return this.visualTester}async execute(e,t){let{urls:n,viewports:r=[{width:1920,height:1080,name:"desktop"}],baselineDir:i=".visual-baselines",threshold:s=.1,fullPage:a=!0}=e;try{if(this.emitStream(t,{status:"capturing",message:`Capturing ${n.length} URLs across ${r.length} viewports`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};this.markAsRealData();let c=await this.getService(t),l=[],d=[];for(let m of n)for(let p of r){this.emitStream(t,{status:"comparing",message:`Comparing ${m} at ${p.width}x${p.height}`});let g={width:p.width,height:p.height,deviceScaleFactor:1,isMobile:p.isMobile||!1,hasTouch:p.isMobile||!1},f=await c.captureScreenshot(m,{viewport:g,fullPage:a});if(!f.success){l.push({url:m,viewport:p,status:"failed",diffPercentage:100,diffPixels:0});continue}let h=f.value,v=await c.getBaseline(m,g);if(!v)await c.setBaseline(h),d.push(h.path.value),l.push({url:m,viewport:p,status:"new",diffPercentage:0,diffPixels:0,screenshotPath:h.path.value});else{let y=await c.compare(h,v.id);if(!y.success){l.push({url:m,viewport:p,status:"failed",diffPercentage:100,diffPixels:0});continue}let C=y.value,b=C.diffPercentage<=s;l.push({url:m,viewport:p,status:b?"passed":"failed",diffPercentage:C.diffPercentage,diffPixels:C.diffPixels,screenshotPath:h.path.value,baselinePath:v.path.value,diffImagePath:C.diffImagePath?.value,regions:C.regions?.map(E=>({x:E.x,y:E.y,width:E.width,height:E.height,changeType:E.changeType,significance:E.significance}))})}}let u={total:l.length,passed:l.filter(m=>m.status==="passed").length,failed:l.filter(m=>m.status==="failed").length,new:l.filter(m=>m.status==="new").length,avgDiffPercentage:l.length>0?l.reduce((m,p)=>m+p.diffPercentage,0)/l.length:0};return this.emitStream(t,{status:"complete",message:`Visual comparison complete: ${u.passed}/${u.total} passed`,progress:100}),{success:!0,data:{comparisons:l,summary:u,newBaselines:d,recommendations:sp(l,u)}}}catch(c){return{success:!1,error:`Visual comparison failed: ${w(c)}`}}}},ur=class extends A{config={name:"qe/a11y/audit",description:"WCAG accessibility auditing with violation detection, contrast checking, and keyboard navigation testing.",domain:"visual-accessibility",schema:rp,streaming:!0,timeout:18e4};accessibilityTester=null;async getService(e){if(!this.accessibilityTester){let t=e.memory;this.accessibilityTester=new xa(t||await q(),{enableColorContrastCheck:!0,enableKeyboardCheck:!0})}return this.accessibilityTester}async execute(e,t){let{urls:n,standard:r="wcag21-aa",includeWarnings:i=!0,checkContrast:s=!0,checkKeyboard:a=!0}=e;try{if(this.emitStream(t,{status:"auditing",message:`Auditing ${n.length} URLs against ${r}`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};this.markAsRealData();let c=await this.getService(t),l=[],d=ip(r);for(let f of n){this.emitStream(t,{status:"scanning",message:`Scanning ${f}`});let h=await c.audit(f,{wcagLevel:d,includeWarnings:i});if(!h.success||h.value.measured!==!0){l.push({url:f,score:-1,passed:!1,violations:[],warnings:[],passedRules:0,measured:!1,notMeasuredReason:h.success?h.value.notMeasuredReason??"not measured":h.error.message});continue}let v=h.value,y=[],C=[];if(s){let x=await c.checkContrast(f);if(x.success){let M=x.value.filter(O=>!O.passes);if(M.length>0){let O=k=>k.ratio>=1?`${k.ratio}:1`:"not measured";C=M.map(k=>({id:"color-contrast",impact:"serious",description:"Elements must have sufficient color contrast",help:`Element ${k.element} has contrast ratio ${O(k)} but requires ${k.requiredRatio}:1`,helpUrl:"https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum",wcagCriteria:["1.4.3"],nodes:[{selector:k.element,html:`<${k.element.replace(".",' class="')}>...</${k.element.split(".")[0]}>`,failureSummary:`Contrast ratio ${O(k)} is below required ${k.requiredRatio}:1`,fixSuggestion:`Change foreground color to achieve at least ${k.requiredRatio}:1 contrast`}]}))}}else y.push({id:"color-contrast-not-measured",description:x.error.message,nodes:0})}let b=[];if(a){let x=await c.checkKeyboardNavigation(f);if(x.success){let M=x.value;M.notMeasured&&M.notMeasured.length>0&&y.push({id:"keyboard-not-measured",description:`Keyboard check did not measure: ${M.notMeasured.join("; ")}`,nodes:0});for(let O of M.issues)b.push({id:O.type,impact:O.type==="no-focus-indicator"?"serious":"moderate",description:O.description,help:"Ensure keyboard navigation is fully supported",helpUrl:"https://www.w3.org/WAI/WCAG22/Understanding/focus-visible",wcagCriteria:["2.4.7"],nodes:[{selector:O.selector,html:`<element>${O.selector}</element>`,failureSummary:O.description,fixSuggestion:"Add visible focus styles with :focus or :focus-visible"}]});for(let O of M.traps)b.push({id:"keyboard-trap",impact:"critical",description:O.description,help:O.escapePath||"No escape path available",helpUrl:"https://www.w3.org/WAI/WCAG22/Understanding/no-keyboard-trap",wcagCriteria:["2.1.2"],nodes:[{selector:O.selector,html:`<element>${O.selector}</element>`,failureSummary:O.description,fixSuggestion:O.escapePath}]})}else y.push({id:"keyboard-not-measured",description:x.error.message,nodes:0})}let E=[...v.violations.map(x=>({id:x.id,impact:x.impact,description:x.description,help:x.help,helpUrl:x.helpUrl,wcagCriteria:x.wcagCriteria.map(M=>M.id),nodes:x.nodes.map(M=>({selector:M.selector,html:M.html,failureSummary:M.failureSummary,fixSuggestion:M.fixSuggestion}))})),...C,...b],T=[...v.incomplete.map(x=>({id:x.id,description:x.description,nodes:x.nodes.length})),...y],S=E.some(x=>x.impact==="critical"||x.impact==="serious");l.push({url:f,score:v.score,passed:!S,violations:E,warnings:T,passedRules:v.passes.length,measured:!0})}let u=l.filter(f=>f.measured===!0),m={totalUrls:l.length,measuredUrls:u.length,passingUrls:u.filter(f=>f.passed).length,avgScore:u.length>0?Math.round(u.reduce((f,h)=>f+h.score,0)/u.length):-1,criticalViolations:l.reduce((f,h)=>f+h.violations.filter(v=>v.impact==="critical").length,0),seriousViolations:l.reduce((f,h)=>f+h.violations.filter(v=>v.impact==="serious").length,0),totalViolations:l.reduce((f,h)=>f+h.violations.length,0)},p=ap(l),g=op(p);return this.emitStream(t,{status:"complete",message:m.avgScore<0?`Audit complete: no URL measured (0/${m.totalUrls}); no score`:`Audit complete: ${m.measuredUrls}/${m.totalUrls} URL(s) measured, avg score ${m.avgScore}%`,progress:100}),{success:!0,data:{audits:l,summary:m,topIssues:p,remediationPlan:g}}}catch(c){return{success:!1,error:`Accessibility audit failed: ${w(c)}`}}}},np={type:"object",properties:{urls:{type:"array",description:"URLs to capture and compare",items:{type:"string",description:"URL"}},viewports:{type:"array",description:"Viewport configurations",items:{type:"object",description:"Viewport",properties:{width:{type:"number",description:"Width in pixels"},height:{type:"number",description:"Height in pixels"},name:{type:"string",description:"Viewport name"}}}},baselineDir:{type:"string",description:"Directory for baseline images",default:".visual-baselines"},threshold:{type:"number",description:"Acceptable diff percentage (0-1)",minimum:0,maximum:1,default:.1},fullPage:{type:"boolean",description:"Capture full page",default:!0},hideSelectors:{type:"array",description:"CSS selectors to hide before capture",items:{type:"string",description:"Selector"}},waitForSelector:{type:"string",description:"Wait for selector before capture"}},required:["urls"]},rp={type:"object",properties:{urls:{type:"array",description:"URLs to audit",items:{type:"string",description:"URL"}},standard:{type:"string",description:"WCAG standard to validate against",enum:["wcag21-aa","wcag21-aaa","wcag22-aa","section508"],default:"wcag21-aa"},includeWarnings:{type:"boolean",description:"Include warnings in results",default:!0},checkContrast:{type:"boolean",description:"Check color contrast",default:!0},checkKeyboard:{type:"boolean",description:"Check keyboard navigation",default:!0},rules:{type:"array",description:"Specific rules to check",items:{type:"string",description:"Rule ID"}}},required:["urls"]};function ip(o){return o==="wcag21-aaa"?"AAA":"AA"}function sp(o,e){let t=[];return e.failed>0&&t.push(`Review ${e.failed} failed comparisons for intentional vs unintentional changes`),e.new>0&&t.push(`${e.new} new baselines created - review and approve if correct`),e.avgDiffPercentage>1&&t.push("Consider increasing diff threshold or reviewing major changes"),t.length>0?t:["All visual tests passed"]}function ap(o){let e=new Map;for(let t of o)for(let n of t.violations){let r=e.get(n.id);r?(r.occurrences++,r.affectedUrls.includes(t.url)||r.affectedUrls.push(t.url)):e.set(n.id,{ruleId:n.id,description:n.description,occurrences:1,impact:n.impact,affectedUrls:[t.url]})}return Array.from(e.values()).sort((t,n)=>n.occurrences-t.occurrences)}function op(o){return o.map((e,t)=>({violationId:e.ruleId,description:e.description,fix:`Fix ${e.ruleId} across ${e.occurrences} occurrences`,effort:e.occurrences>10?"moderate":"minor",priority:t+1}))}D();var dr=class extends A{config={name:"qe/chaos/inject",description:"Inject faults for chaos engineering. Supports latency, errors, CPU/memory stress, network issues, and more.",domain:"chaos-resilience",schema:cp,streaming:!0,timeout:3e5};chaosEngineer=null;async getService(e){if(!this.chaosEngineer){let t=e.memory||await q(),n=await V(e);this.chaosEngineer=new Aa({memory:t,llmRouter:n},{enableDryRun:!0,autoRollbackOnFailure:!0})}return this.chaosEngineer}async execute(e,t){let{faultType:n,target:r,duration:i=3e4,intensity:s=50,dryRun:a=!0,hypothesis:c,rollbackOnFailure:l=!0}=e,d=await this.getService(t);try{if(this.emitStream(t,{status:"preparing",message:`Preparing ${n} fault injection on ${r}`,dryRun:a}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let u=t.requestId||U(),m=this.buildExperiment(u,n,r,i,s,c,l);this.emitStream(t,{status:"verifying",message:"Verifying steady state"});let p=await d.verifySteadyState(m.steadyState),g=p.success&&p.value;if(!g&&!a)return{success:!1,error:"Steady state verification failed. System not in healthy state for chaos experiment."};let f=await d.createExperiment(m);if(!f.success)return{success:!1,error:`Failed to create experiment: ${f.error.message}`};this.emitStream(t,{status:"injecting",message:a?`[DRY RUN] Planning ${n} fault (not injected)`:`Injecting ${n} fault`});let h=!1,v,y="pending",C=[],b={faultDuration:i,targetAffected:!a},E;if(a)h=!1,y="not-executed",E=`Dry run: the ${n} experiment was planned but no fault was injected, so no metrics were measured and the hypothesis was not tested.`;else{let S=await d.runExperiment(u);if(S.success){let x=S.value;h=x.faultResults.some(M=>M.injected),v=x.hypothesisValidated,y=x.status;for(let M of x.incidents)C.push(this.convertIncident(M));b=this.extractMetrics(x,n,i)}else y="failed",C.push({type:"error",severity:"critical",message:S.error.message,timestamp:new Date().toISOString(),resolved:!1})}this.emitStream(t,{status:"monitoring",message:"Monitoring system behavior"}),!a&&C.some(S=>S.severity==="critical"&&!S.resolved)&&(y=l?"rolled-back":"failed");let T=this.generateRecommendations(n,b,C,v);return this.emitStream(t,{status:"complete",message:`Chaos experiment ${y}`,progress:100}),{success:!0,data:{experimentId:u,status:y,faultInjected:h,hypothesisValidated:v,steadyStateVerified:g,metrics:b,incidents:C,recommendations:T,...E?{note:E}:{}}}}catch(u){return{success:!1,error:`Chaos injection failed: ${w(u)}`}}}buildExperiment(e,t,n,r,i,s,a=!0){let c={id:`fault-${e}`,type:t,target:{type:"service",selector:n},duration:r,parameters:this.buildFaultParameters(t,i)},l={description:`Steady state for ${n}`,probes:[{name:"target-health",type:n.startsWith("http")?"http":"command",target:n.startsWith("http")?n:`echo "checking ${n}"`,expected:n.startsWith("http")?200:"OK",timeout:5e3}]},d=s||`System should remain stable under ${t} fault`;return{id:e,name:`${t}-experiment-${Date.now()}`,description:`Chaos experiment: ${t} on ${n}`,hypothesis:{statement:d,metrics:[{metric:t==="latency"?"response_time":"error_rate",operator:"lt",value:t==="latency"?5e3:50}],tolerances:[{metric:"availability",maxDeviation:20,unit:"percent"}]},steadyState:l,faults:[c],blastRadius:{scope:"single",maxAffected:1,excludeProduction:!0},rollbackPlan:{automatic:a,triggerConditions:[{type:"error-rate",condition:"error_rate > 50%"}],steps:[{order:1,action:"remove-fault",target:c.id,timeout:1e4}]},schedule:{type:"once"}}}buildFaultParameters(e,t){let n={};switch(e){case"latency":n.latencyMs=100+t*20;break;case"error":n.errorCode=500,n.errorRate=t/100;break;case"timeout":n.timeoutMs=5e3+t*250;break;case"cpu-stress":n.cpuPercent=t,n.cores=Math.max(1,Math.floor(t/25));break;case"memory-stress":n.memoryBytes=t/100*512*1024*1024;break;case"network-partition":n.partitionPercent=t;break;case"packet-loss":n.packetLossPercent=t;break;case"dns-failure":n.failureRate=t/100;break;case"process-kill":n.signal="SIGTERM";break}return n}extractMetrics(e,t,n){let r={faultDuration:n,targetAffected:e.faultResults.some(c=>c.injected&&c.affectedTargets>0)},i=e.metrics;e.endTime&&e.startTime&&(r.recoveryTime=e.endTime.getTime()-e.startTime.getTime());let s=i.find(c=>c.name.includes("latency")||c.name.includes("response"));s&&(r.latencyP99=s.value);let a=i.find(c=>c.name.includes("error")||c.name.includes("failure"));return a&&(r.errorRate=a.value),r}convertIncident(e){return{type:e.type,severity:e.severity,message:e.message,timestamp:e.timestamp instanceof Date?e.timestamp.toISOString():String(e.timestamp),resolved:e.resolved}}generateRecommendations(e,t,n,r){let i=[];switch(r===!1&&i.push("Hypothesis was not validated - review resilience patterns"),t.recoveryTime&&t.recoveryTime>3e4&&i.push("Recovery time exceeds 30s - consider adding circuit breakers"),t.errorRate&&t.errorRate>20&&i.push("High error rate observed - implement retry with backoff"),n.some(s=>s.severity==="critical")&&i.push("Critical incidents occurred - review fault tolerance mechanisms"),e){case"latency":t.latencyP99&&t.latencyP99>1e3&&i.push("P99 latency exceeds 1s - consider timeout configurations");break;case"network-partition":i.push("Ensure services can operate in degraded mode during network issues");break;case"cpu-stress":case"memory-stress":i.push("Review resource limits and auto-scaling policies");break;case"error":i.push("Implement proper error handling and fallback mechanisms");break;case"timeout":i.push("Configure appropriate timeout values and circuit breakers");break}return i.length===0&&i.push("System showed good resilience - continue regular chaos experiments"),i}},cp={type:"object",properties:{faultType:{type:"string",description:"Type of fault to inject",enum:["latency","error","timeout","cpu-stress","memory-stress","network-partition","packet-loss","dns-failure","process-kill"]},target:{type:"string",description:"Target service, pod, or endpoint"},duration:{type:"number",description:"Fault duration in milliseconds",minimum:1e3,maximum:3e5,default:3e4},intensity:{type:"number",description:"Fault intensity (0-100)",minimum:0,maximum:100,default:50},dryRun:{type:"boolean",description:"Plan the experiment without injecting a fault; nothing is measured",default:!0},hypothesis:{type:"string",description:'Hypothesis to validate (e.g., "System should recover within 30s")'},rollbackOnFailure:{type:"boolean",description:"Auto-rollback on critical failure",default:!0}},required:["faultType","target"]};D();var Nt=class extends A{config={name:"qe/learning/optimize",description:"Cross-domain learning, pattern recognition, strategy optimization, and knowledge transfer.",domain:"learning-optimization",schema:lp,streaming:!0,timeout:3e5};learningCoordinator=null;metricsOptimizer=null;transferSpecialist=null;async getServices(e){if(!this.learningCoordinator||!this.metricsOptimizer||!this.transferSpecialist){let t=e.memory||await q(),n=await V(e);this.learningCoordinator=new ka({memory:t,llmRouter:n}),this.metricsOptimizer=new Ia(t),this.transferSpecialist=new Ma(t)}return{learningCoordinator:this.learningCoordinator,metricsOptimizer:this.metricsOptimizer,transferSpecialist:this.transferSpecialist}}async execute(e,t){let{action:n,domain:r,experienceIds:i,targetDomain:s,objective:a}=e;try{if(this.emitStream(t,{status:"processing",message:`Executing ${n} action`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let c={action:n};switch(n){case"learn":c.learnResult=await this.executeLearn(r,i,t),c.learnResult.evidenceStatus==="insufficient-evidence"&&(c.evidenceStatus="insufficient-evidence");break;case"optimize":if(!a)return{success:!1,error:"Objective is required for optimize action"};c.optimizeResult=await this.executeOptimize(r,a,t),c.optimizeResult.evidenceStatus==="insufficient-evidence"&&(c.evidenceStatus="insufficient-evidence");break;case"transfer":if(!r||!s)return{success:!1,error:"Both domain and targetDomain are required for transfer action"};c.transferResult=await this.executeTransfer(r,s,t);break;case"patterns":c.patternResult=await this.executePatterns(r,t),c.patternResult.evidenceStatus==="insufficient-evidence"&&(c.evidenceStatus="insufficient-evidence");break;case"dashboard":c.dashboardResult=await this.executeDashboard(t),c.dashboardResult.evidenceStatus==="insufficient-evidence"&&(c.evidenceStatus="insufficient-evidence");break;default:return{success:!1,error:`Unknown action: ${n}`}}return this.emitStream(t,{status:"complete",message:`${n} complete`,progress:100}),{success:!0,data:c}}catch(c){return{success:!1,error:`Learning optimization failed: ${w(c)}`}}}async executeLearn(e,t,n){let r=e||"learning-optimization";if(this.isDemoMode(n))return this.markAsDemoData(n,"Demo mode explicitly requested"),this.getDemoLearnResult(r);let{learningCoordinator:i}=await this.getServices(n);if(this.emitStream(n,{status:"learning",message:`Learning from ${t?.length||"recent"} experiences`}),t&&t.length>0)return this.learnFromExperienceIds(i,t);let s=wt.lastNDays(7),a=await i.mineExperiences(r,s),c=[],l=0,d={};if(a.success){l=a.value.experienceCount,d={measuredExperiences:a.value.measuredExperienceCount??l,assignedRewardsExcluded:a.value.assignedRewardsExcluded??0,...a.value.evidenceStatus?{evidenceStatus:a.value.evidenceStatus}:{}};for(let u of a.value.patterns)c.push({id:u.id,type:u.type,name:u.name,description:u.description,confidence:u.confidence,usageCount:u.usageCount,successRate:u.successRate})}return this.markAsRealData(),{experiencesProcessed:l,...d,patternsLearned:c.length,newPatterns:c,improvement:null,unmeasured:["improvement"]}}async learnFromExperienceIds(e,t){let n=await e.getExperiencesByIds(t);if(!n.success)throw n.error;let r=n.value,{measured:i,assignedExcluded:s}=Fr(r),a=i.length>0?await e.learnPattern(r):null,c=a?.success?[{id:a.value.id,type:a.value.type,name:a.value.name,description:a.value.description,confidence:a.value.confidence,usageCount:a.value.usageCount,successRate:a.value.successRate}]:[];return this.markAsRealData(),{experiencesProcessed:r.length,experienceIdsNotFound:new Set(t).size-r.length,measuredExperiences:i.length,assignedRewardsExcluded:s,...i.length===0?{evidenceStatus:"insufficient-evidence"}:{},patternsLearned:c.length,newPatterns:c,improvement:null,unmeasured:["improvement"]}}getDemoLearnResult(e){return{experiencesProcessed:150,patternsLearned:12,newPatterns:[{id:`pattern-${e}-001`,type:"optimization",name:"Parallel Execution Pattern",description:`Optimal parallelism settings discovered for ${e}`,confidence:.92,usageCount:45,successRate:.87},{id:`pattern-${e}-002`,type:"retry",name:"Exponential Backoff Pattern",description:"Effective retry strategy for flaky operations",confidence:.88,usageCount:32,successRate:.91},{id:`pattern-${e}-003`,type:"caching",name:"Result Caching Pattern",description:"Cache frequently computed results for faster access",confidence:.85,usageCount:28,successRate:.82}],improvement:15.5}}async executeOptimize(e,t,n){let{learningCoordinator:r,metricsOptimizer:i}=await this.getServices(n);this.emitStream(n,{status:"optimizing",message:`Optimizing for ${t.metric}`});let s=e||"learning-optimization",a=wt.lastNDays(30),c=await r.getExperiences(s,a);if(!c.success)throw c.error;let{measured:l,assignedExcluded:d}=Fr(c.value),u=l.filter(T=>{let S=T.result.outcome[t.metric];return typeof S=="number"&&Number.isFinite(S)}),m={name:`${s}-current`,parameters:{parallelism:4,retryCount:3,timeout:3e4},expectedOutcome:{}},p=(t.constraints||[]).map(T=>({metric:T.metric,operator:T.operator,value:T.value})),g={metric:t.metric,direction:t.direction,constraints:p},f=m,h=0,v=0,y=[],C=[],b,E;if(u.length>=20){let T=await i.optimizeStrategy(m,g,u);if(!T.success)throw T.error;f={name:T.value.optimizedStrategy.name,parameters:T.value.optimizedStrategy.parameters,expectedOutcome:T.value.optimizedStrategy.expectedOutcome},h=T.value.improvement*100,v=T.value.confidence,y=T.value.validationResults;let S=T.value.evaluation;S&&(E={method:S.method,trainingSamples:S.trainingSamples,heldOutSamples:S.heldOutSamples},b=S.estimated,C=[...S.unmeasured??[]])}else{let T={tags:[s,t.metric],objective:{metric:t.metric,direction:t.direction}},S=await i.recommendStrategy(T);if(!S.success)throw S.error;f={name:S.value.name,parameters:S.value.parameters,expectedOutcome:S.value.expectedOutcome},C=["improvement","confidence"]}return Object.keys(f.expectedOutcome).length===0&&C.push("expectedOutcome"),{inputSource:"recorded-experiences",experiencesUsed:u.length,...d>0?{assignedRewardsExcluded:d}:{},strategiesEvaluated:u.length>=20?1:0,...u.length<20?{evidenceStatus:"insufficient-evidence"}:{},...C.length>0?{unmeasured:C}:{},...b?{estimated:b}:{},...E?{evaluation:E}:{},bestStrategy:f,improvement:h,confidence:v,validationResults:y}}async executeTransfer(e,t,n){let{transferSpecialist:r}=await this.getServices(n);this.emitStream(n,{status:"transferring",message:`Transferring knowledge from ${e} to ${t}`});let i=await r.queryKnowledge({domain:e,minRelevance:.5,limit:50}),s=0,a=0,c=0;if(i.success){s=i.value.length;for(let d of i.value){let u=await r.transferKnowledge(d,t);u.success&&(a++,Math.abs(u.value.relevanceScore-d.relevanceScore)>.1&&c++)}}let l=s>0?a/s:0;return{sourcePatterns:s,transferredPatterns:a,adaptedPatterns:c,successRate:l,targetDomainUpdated:a>0}}async executePatterns(e,t){let{learningCoordinator:n}=await this.getServices(t),r=await this.getSONASnapshot(t);this.emitStream(t,{status:"analyzing",message:`Analyzing patterns${e?` for ${e}`:""}`});let i=await n.getPatternStats(e);if(!i.success)return{totalPatterns:0,byType:{},byDomain:{},topPatterns:[],avgConfidence:null,avgSuccessRate:null,evidenceStatus:"insufficient-evidence",sona:r};let s=i.value,a=s.topPatterns.map(l=>({id:l.id,type:l.type,name:l.name,description:l.description,confidence:l.confidence,usageCount:l.usageCount,successRate:l.successRate})),c=s.totalPatterns>0;return{totalPatterns:s.totalPatterns,byType:s.byType,byDomain:s.byDomain,topPatterns:a,avgConfidence:c?s.avgConfidence:null,avgSuccessRate:c?s.avgSuccessRate:null,...s.assignedPatternsExcluded?{assignedPatternsExcluded:s.assignedPatternsExcluded}:{},...s.legacyPatternsExcluded?{legacyPatternsExcluded:s.legacyPatternsExcluded}:{},...c?{}:{evidenceStatus:"insufficient-evidence"},sona:r}}async executeDashboard(e){let{learningCoordinator:t,transferSpecialist:n}=await this.getServices(e),r=await this.getSONASnapshot(e);this.emitStream(e,{status:"aggregating",message:"Aggregating learning metrics"});let i=await t.getPatternStats(),s=await n.queryKnowledge({minRelevance:0,limit:1e3}),a=wt.lastNDays(1),c=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","learning-optimization"],l=0,d=0,u=[];for(let T of c){let S=await t.mineExperiences(T,a);if(S.success){l+=S.value.experienceCount,d+=S.value.assignedRewardsExcluded??0;let{successRate:x}=S.value;x!==null&&u.push({domain:T,successRate:x})}}u.sort((T,S)=>S.successRate-T.successRate);let m=u.slice(0,3).map(T=>T.domain),p=i.success?i.value.totalPatterns:0,g=i.success?i.value.assignedPatternsExcluded??0:0,f=i.success?i.value.legacyPatternsExcluded??0:0,h=p>0&&i.success?i.value.avgSuccessRate:null,v=h,y=[],C=new Date;for(let T=6;T>=0;T--){let S=new Date(C.getTime()-T*24*60*60*1e3),x=new Date(S.getTime()+1440*60*1e3),M=wt.create(S,x),O=0;for(let k of c.slice(0,3)){let z=await t.mineExperiences(k,M);z.success&&(O+=z.value.patterns.length)}y.push({timestamp:S.toISOString(),metric:"patterns-learned",value:O})}let b=[];p>=100&&b.push({name:`Reached ${Math.floor(p/50)*50} patterns`,achievedAt:null,domain:"learning-optimization"}),h!==null&&h>=.8&&b.push({name:`${Math.round(h*100)}% pattern success rate`,achievedAt:null,domain:m[0]||"learning-optimization"});let E=[];return v===null&&E.push("overallLearningRate"),m.length===0&&E.push("topPerformingDomains"),{overallLearningRate:v,totalPatterns:p,totalKnowledge:s.success?s.value.length:0,experiencesLast24h:l,...d>0?{assignedRewardsExcluded:d}:{},...g>0?{assignedPatternsExcluded:g}:{},...f>0?{legacyPatternsExcluded:f}:{},topPerformingDomains:m,...E.length>0?{evidenceStatus:"insufficient-evidence",unmeasured:E}:{},learningTrend:y,recentMilestones:b,sona:r}}async getSONASnapshot(e){let t=e.kernel?.getDomainAPI("learning-optimization");if(!t?.isSONAAvailable())return{available:!1,stats:null};try{return{available:!0,stats:await t.getSONAPersistedStats()}}catch(n){return this.logger.warn("Failed to read persisted SONA statistics",{requestId:e.requestId,error:w(n)}),{available:!1,stats:null}}}},lp={type:"object",properties:{action:{type:"string",description:"Learning action to perform",enum:["learn","optimize","transfer","patterns","dashboard"]},domain:{type:"string",description:"Source domain for learning/optimization",enum:["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization"]},experienceIds:{type:"array",description:"Specific experience IDs to learn from",items:{type:"string",description:"Experience ID"}},targetDomain:{type:"string",description:"Target domain for knowledge transfer"},objective:{type:"object",description:"Optimization objective",properties:{metric:{type:"string",description:"Metric to optimize"},direction:{type:"string",description:"maximize or minimize",enum:["maximize","minimize"]},constraints:{type:"array",description:"Optimization constraints",items:{type:"object",description:"Constraint"}}}}},required:["action"]};D();var up={type:"object",properties:{action:{type:"string",enum:["dream","insights","apply","history","status"],description:"Action to perform: dream (run cycle), insights (view pending), apply (create pattern), history (view past), status (current state)"},durationMs:{type:"number",description:"Duration of dream cycle in milliseconds (default: 30000, max: 60000)",default:3e4},minPatterns:{type:"number",description:"Minimum patterns required to start dreaming (default: 10)",default:10},insightId:{type:"string",description:"Insight ID to apply (required for apply action)"},limit:{type:"number",description:"Maximum results to return (default: 20)",default:20},loadFromReasoningBank:{type:"boolean",description:"Load patterns from ReasoningBank before dreaming (default: true)",default:!0}},required:["action"]},Ft=class extends A{config={name:"qe/learning/dream",description:"Trigger dream cycles for pattern discovery. Dreams find novel associations between patterns through spreading activation, generating actionable insights.",domain:"learning-optimization",schema:up,streaming:!1,timeout:12e4};engine=null;enginePending=null;async getEngine(){if(this.engine)return this.engine;if(!this.enginePending){let t=(async()=>{let r=_s();return await r.initialize(),this.enginePending===t?this.engine=r:r.close().catch(()=>{}),r})();this.enginePending=t;let n=()=>{this.enginePending===t&&(this.enginePending=null)};t.then(n,n)}return this.enginePending}async loadPatternsFromReasoningBank(e){try{let t=await q(),n=Mr(t);await n.initialize();try{let{getSharedRvfDualWriter:a}=await import("./shared-rvf-dual-writer-EYAVY2GZ.js"),c=await a();c&&n.setRvfDualWriter(c)}catch(a){process.env.DEBUG&&this.logger.info("RVF wiring skipped",{error:String(a)})}let r=await n.searchPatterns("",{limit:100,minConfidence:.3});if(!r.success||!r.value.length)return this.logger.info("No patterns found in ReasoningBank to load"),0;let i=r.value.map(a=>({id:a.pattern.id,name:a.pattern.name,description:a.pattern.description||`${a.pattern.patternType} pattern`,domain:a.pattern.qeDomain||"learning-optimization",patternType:a.pattern.patternType,confidence:a.pattern.confidence,successRate:a.pattern.usageCount>0?a.pattern.successRate:void 0})),s=await e.loadPatternsAsConcepts(i);return this.logger.info(`Loaded ${s} patterns as concepts from ReasoningBank`),s}catch(t){return this.logger.warn("Failed to load patterns from ReasoningBank",{error:String(t)}),0}}async execute(e,t){let{action:n}=e;try{switch(n){case"dream":return this.runDreamCycle(e,t);case"insights":return this.getPendingInsights(e,t);case"apply":return this.applyInsight(e,t);case"history":return this.getDreamHistory(e,t);case"status":return this.getDreamStatus(e,t);default:return{success:!1,error:`Unknown action: ${n}`,data:{action:n,success:!1,error:`Unknown action: ${n}`}}}}catch(r){let i=w(r);return{success:!1,error:i,data:{action:n,success:!1,error:i}}}}async runDreamCycle(e,t){let n=Math.min(e.durationMs||3e4,6e4),r=e.minPatterns||10,i=e.loadFromReasoningBank!==!1;this.logger.info(`Starting dream cycle (${n}ms, min: ${r} patterns)`);let s=await this.getEngine(),a=s.getCurrentCycle();if(a)throw new Ds(a.id);if(i){let u=await this.loadPatternsFromReasoningBank(s);this.logger.info(`Loaded ${u} patterns from ReasoningBank`)}let c=await s.dream(n,{minConceptsRequired:r}),l={cycleId:c.cycle.id,status:c.cycle.status,durationMs:c.cycle.durationMs||0,conceptsProcessed:c.cycle.conceptsProcessed,associationsFound:c.cycle.associationsFound,insightsGenerated:c.cycle.insightsGenerated,activationStats:c.activationStats,patternsCreated:c.patternsCreated,commitDurationMs:c.commitDurationMs,retention:c.retention?{enabled:c.retention.enabled,steps:Is(c.retention)}:void 0},d=c.insights.map(u=>({id:u.id,type:u.type,description:u.description,noveltyScore:u.noveltyScore,confidenceScore:u.confidenceScore,actionable:u.actionable,applied:u.applied||!1,suggestedAction:u.suggestedAction,createdAt:u.createdAt?.toISOString()||new Date().toISOString()}));return this.logger.info(`Dream cycle complete: ${c.cycle.insightsGenerated} insights, ${c.cycle.associationsFound} associations found`),{success:!0,data:{action:"dream",success:!0,dreamResult:l,insights:d}}}async getPendingInsights(e,t){let n=e.limit||20;return{success:!0,data:{action:"insights",success:!0,insights:(await(await this.getEngine()).getPendingInsights(n)).map(a=>({id:a.id,type:a.type,description:a.description,noveltyScore:a.noveltyScore,confidenceScore:a.confidenceScore,actionable:a.actionable,applied:a.applied||!1,suggestedAction:a.suggestedAction,createdAt:a.createdAt?.toISOString()||new Date().toISOString()}))}}}async applyInsight(e,t){if(!e.insightId)return{success:!1,error:"insightId is required for apply action",data:{action:"apply",success:!1,error:"insightId is required for apply action"}};try{let r=await(await this.getEngine()).applyInsight(e.insightId);return r.success?(this.logger.info(`Applied insight ${e.insightId} \u2192 REAL pattern ${r.patternId} in ReasoningBank`),{success:!0,data:{action:"apply",success:!0,applyResult:{insightId:e.insightId,...r}}}):{success:!1,error:r.error,data:{action:"apply",success:!1,error:r.error}}}catch(n){let r=w(n);return{success:!1,error:r,data:{action:"apply",success:!1,error:r}}}}async getDreamHistory(e,t){let n=e.limit||20;return{success:!0,data:{action:"history",success:!0,history:(await(await this.getEngine()).getDreamHistory(n)).map(a=>({id:a.id,startTime:a.startTime.toISOString(),endTime:a.endTime?.toISOString(),durationMs:a.durationMs,status:a.status,conceptsProcessed:a.conceptsProcessed,associationsFound:a.associationsFound,insightsGenerated:a.insightsGenerated}))}}}async getDreamStatus(e,t){let n=await this.getEngine(),r=n.isDreaming(),i=n.getCurrentCycle(),s=await n.getDreamHistory(100),a=await n.getPendingInsights(100),c=s.reduce((u,m)=>u+m.insightsGenerated,0),l=s[0];return{success:!0,data:{action:"status",success:!0,status:{isDreaming:r,currentCycle:i?{id:i.id,startTime:i.startTime.toISOString(),endTime:i.endTime?.toISOString(),durationMs:i.durationMs,status:i.status,conceptsProcessed:i.conceptsProcessed,associationsFound:i.associationsFound,insightsGenerated:i.insightsGenerated}:void 0,totalCycles:s.length,totalInsights:c,pendingInsights:a.length,lastDreamTime:l?.startTime.toISOString()}}}}resetInstanceCache(){this.enginePending=null,this.engine&&(this.engine.close().catch(console.error),this.engine=null)}};D();var mr=class extends A{config={name:"qe/analysis/token_usage",description:"Analyze token consumption patterns and identify optimization opportunities across agents and domains.",domain:"learning-optimization",schema:dp,streaming:!1,timeout:3e4};async execute(e,t){let{operation:n,timeframe:r,agentId:i,domain:s}=e;try{if(this.isAborted(t))return{success:!1,error:"Operation aborted"};let a;switch(n){case"session":a=this.getSessionUsage(r);break;case"agent":a=this.getAgentUsage(i,r);break;case"domain":a=this.getDomainUsage(s,r);break;case"task":a=this.getTaskUsage(r);break;case"efficiency":a=this.getEfficiencyReport(r);break;case"dashboard":return{success:!0,data:{operation:"dashboard",timeframe:r||"all",summary:{totalTokens:0,totalCost:"$0.00",tokensSaved:0,savingsPercentage:0},optimization:{patternsReused:0,cacheHits:0,earlyExits:0,recommendations:[Es()]}}};default:return{success:!1,error:`Unknown operation: ${n}`}}return{success:!0,data:a}}catch(a){return{success:!1,error:`Token usage analysis failed: ${w(a)}`}}}getSessionUsage(e){let t=oe.getSessionSummary(e),n={};for(let[i,s]of t.byAgent)n[i]={tokens:s.totalTokens,cost:Y(s.totalCost),tasks:s.tasksExecuted};let r={};for(let[i,s]of t.byDomain)r[i]={tokens:s.totalTokens,cost:Y(s.estimatedCostUsd||0)};return{operation:"session",timeframe:e||"all",summary:{totalTokens:t.totalUsage.totalTokens,totalCost:Y(t.totalUsage.estimatedCostUsd||0),tokensSaved:t.optimizationStats.tokensSaved,savingsPercentage:t.optimizationStats.savingsPercentage},breakdown:{byAgent:Object.keys(n).length>0?n:void 0,byDomain:Object.keys(r).length>0?r:void 0},optimization:{patternsReused:t.optimizationStats.patternsReused,cacheHits:t.optimizationStats.cacheHits,earlyExits:t.optimizationStats.earlyExits,recommendations:this.generateSessionRecommendations(t)}}}getAgentUsage(e,t){let n=oe.getAgentMetrics(e,t),r=oe.getSessionSummary(t);if(e&&!Array.isArray(n)){let u=n,m=u.tasksExecuted>0?u.patternsReused/u.tasksExecuted:0;return{operation:"agent",timeframe:t||"all",summary:{totalTokens:u.totalTokens,totalCost:Y(u.totalCost),tokensSaved:u.estimatedTokensSaved,savingsPercentage:this.calculateSavingsPercentage(u.totalTokens,u.estimatedTokensSaved)},optimization:{patternsReused:u.patternsReused,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateAgentRecommendations(u)},details:{agentMetrics:{agentId:u.agentId,totalInputTokens:u.totalInputTokens,totalOutputTokens:u.totalOutputTokens,totalTokens:u.totalTokens,totalCost:Y(u.totalCost),tasksExecuted:u.tasksExecuted,patternsReused:u.patternsReused,tokensSaved:u.estimatedTokensSaved,efficiency:Math.round(m*100)}}}}let i=Array.isArray(n)?n:[n],s={},a=0,c=0,l=0,d=0;for(let u of i)s[u.agentId]={tokens:u.totalTokens,cost:Y(u.totalCost),tasks:u.tasksExecuted},a+=u.totalTokens,c+=u.totalCost,l+=u.estimatedTokensSaved,d+=u.patternsReused;return{operation:"agent",timeframe:t||"all",summary:{totalTokens:a,totalCost:Y(c),tokensSaved:l,savingsPercentage:this.calculateSavingsPercentage(a,l)},breakdown:{byAgent:Object.keys(s).length>0?s:void 0},optimization:{patternsReused:d,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateMultiAgentRecommendations(i)}}}getDomainUsage(e,t){let n=oe.getDomainMetrics(e,t),r=oe.getSessionSummary(t);if(e&&!(n instanceof Map)){let l=n;return{operation:"domain",timeframe:t||"all",summary:{totalTokens:l.totalTokens,totalCost:Y(l.estimatedCostUsd||0),tokensSaved:r.optimizationStats.tokensSaved,savingsPercentage:r.optimizationStats.savingsPercentage},optimization:{patternsReused:r.optimizationStats.patternsReused,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateDomainRecommendations(e,l)},details:{domainMetrics:{domain:e,inputTokens:l.inputTokens,outputTokens:l.outputTokens,totalTokens:l.totalTokens,cost:Y(l.estimatedCostUsd||0)}}}}let i=n instanceof Map?n:new Map,s={},a=0,c=0;for(let[l,d]of i)s[l]={tokens:d.totalTokens,cost:Y(d.estimatedCostUsd||0)},a+=d.totalTokens,c+=d.estimatedCostUsd||0;return{operation:"domain",timeframe:t||"all",summary:{totalTokens:a,totalCost:Y(c),tokensSaved:r.optimizationStats.tokensSaved,savingsPercentage:r.optimizationStats.savingsPercentage},breakdown:{byDomain:Object.keys(s).length>0?s:void 0},optimization:{patternsReused:r.optimizationStats.patternsReused,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateMultiDomainRecommendations(i)}}}getTaskUsage(e){let t=oe.getTaskMetrics(e),n=oe.getSessionSummary(e),r=t.slice(-100).map(i=>({taskId:i.taskId,agentId:i.agentId,domain:i.domain,operation:i.operation,tokens:i.usage.totalTokens,cost:Y(i.usage.estimatedCostUsd||0),patternReused:i.patternReused,tokensSaved:i.tokensSaved||0,timestamp:new Date(i.timestamp).toISOString()}));return{operation:"task",timeframe:e||"all",summary:{totalTokens:n.totalUsage.totalTokens,totalCost:Y(n.totalUsage.estimatedCostUsd||0),tokensSaved:n.optimizationStats.tokensSaved,savingsPercentage:n.optimizationStats.savingsPercentage},optimization:{patternsReused:n.optimizationStats.patternsReused,cacheHits:n.optimizationStats.cacheHits,earlyExits:n.optimizationStats.earlyExits,recommendations:[`${t.length} tasks analyzed in timeframe`]},details:{taskMetrics:r}}}getEfficiencyReport(e){let t=oe.getEfficiencyReport(e),n=oe.getSessionSummary(e);return{operation:"efficiency",timeframe:e||"all",summary:{totalTokens:t.totalTokensUsed,totalCost:Y(t.totalTokensUsed*3e-6+t.totalTokensUsed*15e-6),tokensSaved:t.totalTokensSaved,savingsPercentage:t.savingsPercentage},optimization:{patternsReused:n.optimizationStats.patternsReused,cacheHits:n.optimizationStats.cacheHits,earlyExits:n.optimizationStats.earlyExits,recommendations:t.recommendations}}}generateSessionRecommendations(e){let t=[];if(e.totalUsage.totalTokens===0)return["No token usage recorded yet. Start executing tasks to track consumption."];let{patternsReused:n,cacheHits:r,earlyExits:i,savingsPercentage:s}=e.optimizationStats;return s<10&&t.push("Token savings below 10%. Enable pattern reuse and caching for better efficiency."),n===0&&e.byAgent.size>0&&t.push("No patterns reused. Consider enabling the pattern store for similar tasks."),r===0&&e.totalUsage.totalTokens>1e4&&t.push("No cache hits detected. Enable response caching to reduce API calls."),i===0&&e.byAgent.size>1&&t.push("Early exit optimization not used. Enable high-confidence pattern matching."),s>25&&t.push(`Excellent token efficiency! ${s.toFixed(1)}% savings achieved.`),t.length>0?t:["Token usage is within normal parameters."]}generateAgentRecommendations(e){let t=[];if(e.tasksExecuted===0)return["No tasks executed by this agent yet."];e.patternsReused/e.tasksExecuted<.1&&t.push("Low pattern reuse rate. Consider caching successful patterns.");let r=e.totalTokens/e.tasksExecuted;return r>5e3&&t.push(`High average tokens per task (${Math.round(r)}). Consider optimizing prompts.`),e.totalOutputTokens>e.totalInputTokens*2&&t.push("High output-to-input ratio. Request more concise responses."),t.length>0?t:["Agent token usage is efficient."]}generateMultiAgentRecommendations(e){let t=[];if(e.length===0)return["No agent data available."];let n=[...e].sort((s,a)=>a.totalTokens-s.totalTokens);n[0].totalTokens>0&&t.push(`Highest consumer: ${n[0].agentId} (${n[0].totalTokens.toLocaleString()} tokens)`);let r=e.reduce((s,a)=>s+a.totalTokens,0);return n[0].totalTokens/(r||1)>.5&&e.length>1&&t.push("Token usage imbalanced. Consider distributing workload across agents."),t}generateDomainRecommendations(e,t){let n=[];return t.totalTokens===0?[`No token usage recorded for ${e}.`]:(e==="test-generation"&&t.totalTokens>1e4&&n.push("Test generation consuming significant tokens. Consider batching test requests."),e==="code-intelligence"&&t.outputTokens>t.inputTokens*3&&n.push("Code intelligence generating verbose output. Consider summary-only mode."),n.length>0?n:[`${e} token usage is normal.`])}generateMultiDomainRecommendations(e){let t=[];if(e.size===0)return["No domain data available."];let n=Array.from(e.entries()).sort((r,i)=>i[1].totalTokens-r[1].totalTokens);return n[0][1].totalTokens>0&&t.push(`Highest consuming domain: ${n[0][0]} (${n[0][1].totalTokens.toLocaleString()} tokens)`),t}calculateSavingsPercentage(e,t){let n=e+t;return n===0?0:Math.round(t/n*1e4)/100}},dp={type:"object",properties:{operation:{type:"string",description:"Type of analysis to perform",enum:["session","agent","domain","task","efficiency","dashboard"]},timeframe:{type:"string",description:"Time period to analyze",enum:["1h","24h","7d","30d"]},agentId:{type:"string",description:"Specific agent ID to analyze (for agent operation)"},domain:{type:"string",description:"Specific domain to analyze (for domain operation)",enum:["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization"]}},required:["operation"]};D();function Lt(o){return o===void 0?null:typeof o!="number"||!Number.isInteger(o)||o<1?`constraints.maxSteps must be a positive integer, got ${String(o)}`:null}var Qi={coverage:{line:0,branch:0,function:0,target:80,measured:!1},quality:{testsPassing:0,totalTests:0,securityScore:100,performanceScore:100},fleet:{activeAgents:0,availableAgents:[],maxAgents:8},resources:{timeRemaining:3600,memoryAvailable:4096,parallelSlots:4},context:{environment:"development",riskLevel:"medium"},patterns:{available:0,reusable:0}};var mp=[{name:"measure-coverage",description:"Run coverage analysis on the codebase to determine current coverage metrics",agentType:"qe-coverage-specialist",preconditions:{"coverage.measured":!1},effects:{"coverage.measured":!0},cost:2,estimatedDurationMs:3e4,successRate:.95,category:"coverage",qeDomain:"coverage-analysis",method:"analyze",params:{},implemented:!0},{name:"analyze-coverage-gaps",description:"Identify uncovered code paths and prioritize them by risk and complexity",agentType:"qe-gap-detector",preconditions:{"coverage.measured":!0},effects:{"coverage.gapsIdentified":!0},cost:1.5,estimatedDurationMs:15e3,successRate:.9,category:"coverage",qeDomain:"coverage-analysis",method:"detectGaps",params:{},implemented:!0},{name:"generate-coverage-tests",description:"Generate tests targeting identified coverage gaps using AI-powered analysis",agentType:"qe-test-generator",preconditions:{"coverage.gapsIdentified":!0},effects:{"coverage.line":{delta:10}},cost:4,estimatedDurationMs:6e4,successRate:.8,category:"coverage",qeDomain:"test-generation",method:"generateTests",params:{},implemented:!0},{name:"run-mutation-testing",description:"Run mutation testing to validate test effectiveness and find weak spots",agentType:"qe-mutation-tester",preconditions:{"coverage.line":{min:60}},effects:{"quality.mutationScore":{set:!0}},cost:5,estimatedDurationMs:12e4,successRate:.85,category:"coverage",qeDomain:"coverage-analysis",implemented:!1},{name:"prioritize-uncovered-paths",description:"Use sublinear O(log n) analysis to identify highest-risk uncovered paths",agentType:"qe-coverage-specialist",preconditions:{"coverage.gapsIdentified":!0},effects:{"coverage.riskPrioritized":!0},cost:1,estimatedDurationMs:1e4,successRate:.92,category:"coverage",qeDomain:"coverage-analysis",method:"calculateRisk",params:{},implemented:!0},{name:"generate-branch-tests",description:"Generate tests specifically targeting branch coverage improvements",agentType:"qe-test-generator",preconditions:{"coverage.measured":!0,"coverage.branch":{max:70}},effects:{"coverage.branch":{delta:8}},cost:3.5,estimatedDurationMs:45e3,successRate:.78,category:"coverage",qeDomain:"test-generation",method:"generateTests",params:{},implemented:!0}],pp=[{name:"run-unit-tests",description:"Execute unit test suite with parallel execution",agentType:"qe-test-executor",preconditions:{},effects:{"quality.unitTestsRun":!0},cost:1,estimatedDurationMs:2e4,successRate:.95,category:"test",qeDomain:"test-execution",method:"runTests",params:{},implemented:!0},{name:"run-integration-tests",description:"Execute integration test suite with real database connections",agentType:"qe-test-executor",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.integrationTestsRun":!0},cost:2.5,estimatedDurationMs:45e3,successRate:.85,category:"test",qeDomain:"test-execution",method:"execute",params:{},implemented:!0},{name:"run-e2e-tests",description:"Execute end-to-end tests using Playwright or Cypress",agentType:"qe-e2e-tester",preconditions:{"quality.integrationTestsRun":!0},effects:{"quality.e2eTestsRun":!0},cost:4,estimatedDurationMs:9e4,successRate:.8,category:"test",qeDomain:"test-execution",method:"executeE2ETestSuite",params:{},implemented:!0},{name:"fix-failing-tests",description:"Analyze and fix failing tests based on error messages and stack traces",agentType:"qe-tdd-specialist",preconditions:{"quality.testsPassing":{max:90}},effects:{"quality.testsPassing":{delta:10}},cost:3,estimatedDurationMs:3e4,successRate:.75,category:"test",qeDomain:"test-generation",implemented:!1},{name:"fix-flaky-tests",description:"Identify and stabilize flaky tests by analyzing timing and async issues",agentType:"qe-flaky-hunter",preconditions:{"quality.flakyTests":{min:1}},effects:{"quality.flakyTests":{delta:-3}},cost:4,estimatedDurationMs:45e3,successRate:.7,category:"test",qeDomain:"test-execution",method:"detectFlaky",params:{},implemented:!0},{name:"generate-property-tests",description:"Generate property-based tests using fast-check or similar library",agentType:"qe-test-generator",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.propertyTestsGenerated":!0},cost:3.5,estimatedDurationMs:4e4,successRate:.82,category:"test",qeDomain:"test-generation",method:"generatePropertyTests",params:{},implemented:!0},{name:"run-contract-tests",description:"Execute consumer-driven contract tests using Pact or similar",agentType:"qe-contract-tester",preconditions:{"context.hasApiContracts":!0},effects:{"quality.contractTestsRun":!0},cost:2,estimatedDurationMs:25e3,successRate:.88,category:"test",qeDomain:"contract-testing",method:"verifyAllConsumers",params:{},implemented:!0}],gp=[{name:"security-scan",description:"Run comprehensive security scan using SAST and dependency analysis",agentType:"qe-security-scanner",preconditions:{},effects:{"quality.securityScanned":!0},cost:2,estimatedDurationMs:3e4,successRate:.95,category:"security",qeDomain:"security-compliance",method:"runSecurityAudit",params:{},implemented:!0},{name:"fix-vulnerabilities",description:"Remediate identified security vulnerabilities and update dependencies",agentType:"qe-security-auditor",preconditions:{"quality.securityScanned":!0,"quality.vulnerabilities":{min:1}},effects:{"quality.vulnerabilities":{delta:-5},"quality.securityScore":{delta:10}},cost:5,estimatedDurationMs:6e4,successRate:.7,category:"security",qeDomain:"security-compliance",implemented:!1},{name:"owasp-audit",description:"Perform OWASP Top 10 security audit on the application",agentType:"qe-security-auditor",preconditions:{"quality.securityScanned":!0},effects:{"quality.owaspCompliant":!0},cost:3,estimatedDurationMs:45e3,successRate:.85,category:"security",qeDomain:"security-compliance",method:"runComplianceCheck",params:{standard:"owasp"},implemented:!0},{name:"scan-secrets",description:"Scan codebase for hardcoded secrets and credentials",agentType:"qe-security-scanner",preconditions:{},effects:{"quality.secretsScanned":!0},cost:1,estimatedDurationMs:15e3,successRate:.98,category:"security",qeDomain:"security-compliance",method:"runSecurityAudit",params:{includeSecrets:!0},implemented:!0},{name:"run-dast",description:"Run dynamic application security testing against running application",agentType:"qe-security-auditor",preconditions:{"context.environment":"staging"},effects:{"quality.dastCompleted":!0},cost:4.5,estimatedDurationMs:12e4,successRate:.8,category:"security",qeDomain:"security-compliance",method:"runDASTScan",params:{},implemented:!0}],fp=[{name:"run-benchmarks",description:"Execute performance benchmarks to establish baseline metrics",agentType:"qe-performance-tester",preconditions:{},effects:{"quality.benchmarked":!0},cost:2,estimatedDurationMs:45e3,successRate:.9,category:"performance",qeDomain:"chaos-resilience",implemented:!1},{name:"load-test",description:"Run load testing with simulated concurrent traffic",agentType:"qe-load-tester",preconditions:{"context.environment":"staging"},effects:{"quality.loadTested":!0},cost:3.5,estimatedDurationMs:12e4,successRate:.85,category:"performance",qeDomain:"chaos-resilience",method:"runLoadTestSuite",params:{},implemented:!0},{name:"stress-test",description:"Run stress testing to find breaking points and system limits",agentType:"qe-chaos-engineer",preconditions:{"context.environment":"staging","quality.loadTested":!0},effects:{"quality.stressTested":!0},cost:4,estimatedDurationMs:9e4,successRate:.8,category:"performance",qeDomain:"chaos-resilience",method:"runTest",params:{type:"stress"},implemented:!0},{name:"profile-memory",description:"Profile memory usage and identify memory leaks",agentType:"qe-performance-tester",preconditions:{"quality.benchmarked":!0},effects:{"quality.memoryProfiled":!0},cost:2.5,estimatedDurationMs:6e4,successRate:.88,category:"performance",qeDomain:"chaos-resilience",implemented:!1},{name:"optimize-slow-tests",description:"Identify and optimize slow-running tests to improve CI/CD speed",agentType:"qe-performance-tester",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.testsOptimized":!0},cost:2,estimatedDurationMs:3e4,successRate:.82,category:"performance",qeDomain:"test-execution",implemented:!1}],hp=[{name:"analyze-complexity",description:"Measure cyclomatic and cognitive complexity of codebase",agentType:"code-analyzer",preconditions:{},effects:{"quality.complexityAnalyzed":!0},cost:1,estimatedDurationMs:15e3,successRate:.95,category:"analysis",qeDomain:"quality-assessment",method:"analyzeComplexity",params:{},implemented:!0},{name:"detect-code-smells",description:"Identify code smells and anti-patterns using static analysis",agentType:"code-analyzer",preconditions:{},effects:{"quality.smellsDetected":!0},cost:1.5,estimatedDurationMs:2e4,successRate:.9,category:"analysis",qeDomain:"code-intelligence",implemented:!1},{name:"analyze-dependencies",description:"Analyze dependency graph and identify circular or outdated dependencies",agentType:"code-analyzer",preconditions:{},effects:{"quality.dependenciesAnalyzed":!0},cost:1,estimatedDurationMs:15e3,successRate:.92,category:"analysis",qeDomain:"code-intelligence",method:"mapDependencies",params:{},implemented:!0},{name:"measure-technical-debt",description:"Calculate technical debt metrics and generate remediation plan",agentType:"code-analyzer",preconditions:{"quality.complexityAnalyzed":!0,"quality.smellsDetected":!0},effects:{"quality.technicalDebtMeasured":!0},cost:2,estimatedDurationMs:25e3,successRate:.88,category:"analysis",qeDomain:"code-intelligence",implemented:!1},{name:"build-knowledge-graph",description:"Build semantic knowledge graph of codebase for intelligent context retrieval",agentType:"qe-intelligence-builder",preconditions:{"quality.dependenciesAnalyzed":!0},effects:{"quality.knowledgeGraphBuilt":!0},cost:3,estimatedDurationMs:6e4,successRate:.85,category:"analysis",qeDomain:"code-intelligence",method:"index",params:{},implemented:!0}],yp=[{name:"spawn-test-agent",description:"Spawn additional test execution agent for parallel work",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{max:10}},effects:{"fleet.activeAgents":{delta:1}},cost:.5,estimatedDurationMs:5e3,successRate:.95,category:"fleet",qeDomain:"test-execution",implemented:!1},{name:"optimize-fleet-topology",description:"Reconfigure fleet topology for optimal task distribution",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:3}},effects:{"fleet.efficiency":{delta:15}},cost:1,estimatedDurationMs:1e4,successRate:.85,category:"fleet",implemented:!1},{name:"scale-down-fleet",description:"Reduce fleet size to conserve resources during low-activity periods",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:5}},effects:{"fleet.activeAgents":{delta:-2}},cost:.3,estimatedDurationMs:3e3,successRate:.98,category:"fleet",implemented:!1},{name:"spawn-specialist-agent",description:"Spawn a specialized agent for specific domain work",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{max:12},"context.specialistNeeded":!0},effects:{"fleet.activeAgents":{delta:1},"fleet.specialistAvailable":!0},cost:1,estimatedDurationMs:8e3,successRate:.9,category:"fleet",implemented:!1},{name:"rebalance-workload",description:"Redistribute tasks across agents based on current load",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:2}},effects:{"fleet.workloadBalanced":!0},cost:.5,estimatedDurationMs:5e3,successRate:.92,category:"fleet",implemented:!1}],vp=[{name:"generate-quality-report",description:"Generate comprehensive quality report combining all metrics",agentType:"qe-quality-gate",preconditions:{"coverage.measured":!0,"quality.unitTestsRun":!0},effects:{"quality.reported":!0},cost:1,estimatedDurationMs:1e4,successRate:.95,category:"quality",qeDomain:"quality-assessment",method:"analyzeQuality",params:{},implemented:!0},{name:"enforce-quality-gate",description:"Check if all quality gates pass and report status",agentType:"qe-quality-gate",preconditions:{"quality.reported":!0},effects:{"quality.gatePassed":!0},cost:.5,estimatedDurationMs:5e3,successRate:.9,category:"quality",qeDomain:"quality-assessment",method:"evaluateGate",params:{},implemented:!0},{name:"validate-requirements",description:"Validate that tests cover all documented requirements",agentType:"qe-requirements-validator",preconditions:{"context.hasRequirements":!0},effects:{"quality.requirementsValidated":!0},cost:2,estimatedDurationMs:2e4,successRate:.88,category:"quality",qeDomain:"requirements-validation",method:"validate",params:{},implemented:!0},{name:"predict-defects",description:"Use ML-based defect prediction to identify high-risk code areas",agentType:"qe-defect-predictor",preconditions:{"quality.complexityAnalyzed":!0,"coverage.measured":!0},effects:{"quality.defectsPredicted":!0},cost:2.5,estimatedDurationMs:3e4,successRate:.82,category:"quality",qeDomain:"defect-intelligence",method:"predictDefects",params:{},implemented:!0},{name:"generate-deployment-report",description:"Generate deployment readiness report with all quality metrics",agentType:"qe-quality-gate",preconditions:{"quality.gatePassed":!0,"quality.securityScanned":!0},effects:{"quality.deploymentReady":!0},cost:1.5,estimatedDurationMs:15e3,successRate:.9,category:"quality",qeDomain:"quality-assessment",method:"getDeploymentAdvice",params:{},implemented:!0}],bp=[{name:"run-accessibility-audit",description:"Run WCAG 2.2 accessibility audit using axe-core or similar",agentType:"qe-accessibility-tester",preconditions:{"context.hasUI":!0},effects:{"quality.accessibilityAudited":!0},cost:2,estimatedDurationMs:3e4,successRate:.9,category:"quality",qeDomain:"visual-accessibility",method:"runAccessibilityAudit",params:{},implemented:!0},{name:"run-visual-regression",description:"Run visual regression testing with screenshot comparison",agentType:"qe-visual-tester",preconditions:{"context.hasUI":!0},effects:{"quality.visualRegressionRun":!0},cost:3,estimatedDurationMs:6e4,successRate:.85,category:"quality",qeDomain:"visual-accessibility",method:"runVisualTests",params:{},implemented:!0}],el=[...mp,...pp,...gp,...fp,...hp,...yp,...vp,...bp];function Cp(o){return`action-${o}`}function tl(o){return{...o,id:Cp(o.name),executionCount:0}}function he(){return el.map(tl)}var ot=[{name:"achieve-90-percent-coverage",description:"Reach 90% line coverage through targeted test generation",conditions:{"coverage.line":{min:90}},priority:1,qeDomain:"coverage-analysis"},{name:"all-tests-passing",description:"All tests green with 100% pass rate",conditions:{"quality.testsPassing":{min:100}},priority:1,qeDomain:"test-execution"},{name:"security-compliant",description:"Pass security audit with no critical vulnerabilities",conditions:{"quality.securityScanned":!0,"quality.vulnerabilities":{max:0}},priority:2,qeDomain:"security-compliance"},{name:"deployment-ready",description:"Ready for production deployment with all quality gates passed",conditions:{"coverage.line":{min:80},"quality.testsPassing":{min:100},"quality.securityScanned":!0,"quality.gatePassed":!0},priority:1},{name:"performance-validated",description:"Performance benchmarks and load tests completed successfully",conditions:{"quality.benchmarked":!0,"quality.loadTested":!0},priority:2,qeDomain:"chaos-resilience"},{name:"code-quality-excellent",description:"Excellent code quality with low complexity and no code smells",conditions:{"quality.complexityAnalyzed":!0,"quality.smellsDetected":!0,"quality.technicalDebtMeasured":!0},priority:3,qeDomain:"code-intelligence"},{name:"full-test-suite",description:"Complete test suite with unit, integration, and e2e tests",conditions:{"quality.unitTestsRun":!0,"quality.integrationTestsRun":!0,"quality.e2eTestsRun":!0},priority:2,qeDomain:"test-execution"},{name:"accessibility-compliant",description:"WCAG 2.2 compliant with visual regression coverage",conditions:{"quality.accessibilityAudited":!0,"quality.visualRegressionRun":!0},priority:2,qeDomain:"visual-accessibility"}];ee();vs();import{randomUUID as Ne}from"crypto";var pr=1e3,Xi=class{data=[];cmp;constructor(e){this.cmp=e}get length(){return this.data.length}push(e){this.data.push(e),this.bubbleUp(this.data.length-1)}pop(){if(this.data.length===0)return;let e=this.data[0],t=this.data.pop();return this.data.length>0&&(this.data[0]=t,this.sinkDown(0)),e}bubbleUp(e){for(;e>0;){let t=e-1>>1;if(this.cmp(this.data[e],this.data[t])<0)[this.data[e],this.data[t]]=[this.data[t],this.data[e]],e=t;else break}}sinkDown(e){let t=this.data.length;for(;;){let n=e,r=2*e+1,i=2*e+2;if(r<t&&this.cmp(this.data[r],this.data[n])<0&&(n=r),i<t&&this.cmp(this.data[i],this.data[n])<0&&(n=i),n!==e)[this.data[e],this.data[n]]=[this.data[n],this.data[e]],e=n;else break}}},Sp=new Set(["__proto__","constructor","prototype"]),gr=class o{db=null;persistence=null;actions=new Map;initialized=!1;enablePlanReuse=!0;constructor(){}ensureDb(){if(!this.db)throw new Error("GOAPPlanner not initialized - call initialize() first");return this.db}write(e){let t=this.ensureDb();return Et(t,()=>e(t))}async initialize(){if(this.initialized)return;this.persistence=Rs(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.ensureDb().prepare("SELECT COUNT(*) as count FROM goap_actions").get().count===0&&this.seedDefaultActions(),this.backfillActionMethodBindings(),this.backfillActionDurationEstimates(),await this.loadActions(),this.initialized=!0,console.log(`[GOAPPlanner] Initialized: ${this.persistence.getDbPath()}`)}seedDefaultActions(){let e=he(),t=this.ensureDb(),n=t.prepare(`
644
+ Analyze the requirements above and return the complete QualityCriteriaAnalysis.`}resetInstanceCache(){this.service=null}},Mm={type:"object",properties:{assessmentName:{type:"string",description:"Assessment name (e.g., Epic title or feature name)"},epicPath:{type:"string",description:"Path to epic/requirements document"},epicContent:{type:"string",description:"Epic content as string (alternative to epicPath)"},sourcePaths:{type:"array",description:"Source code paths to analyze for evidence",items:{type:"string",description:"Source path glob pattern"}},outputFormat:{type:"string",description:"Output format for the report",enum:["html","json","markdown"],default:"html"},outputPath:{type:"string",description:"Path to save the output report"},evidencePoints:{type:"array",description:"Evidence points to validate (for validate-evidence action)",items:{type:"object",description:"Evidence point object",properties:{sourceReference:{type:"string",description:"Source reference in file:line format"},type:{type:"string",enum:["Direct","Inferred","Claimed"],description:"Evidence type"},qualityImplication:{type:"string",description:"Quality implication of this evidence"},reasoning:{type:"string",description:"Reasoning explaining WHY it matters"}},required:["sourceReference","type","qualityImplication","reasoning"]}},completedAnalysis:{type:"object",description:"Completed QualityCriteriaAnalysis object (for format action)"},action:{type:"string",description:'Action to perform. "analyze" (default) returns agentInvocation for real analysis. "validate-evidence" validates evidence format. "format" formats completed analysis.',enum:["analyze","validate-evidence","format"],default:"analyze"}},required:["assessmentName"]},kT=new Nt;import*as Hi from"fs";import*as Ae from"path";M();var sr=class extends A{config={name:"qe/code/analyze",description:"Analyze code using knowledge graph and semantic search. Supports indexing, searching, impact analysis, and dependency mapping.",domain:"code-intelligence",schema:Im,streaming:!0,timeout:3e5};knowledgeGraph=null;semanticAnalyzer=null;impactAnalyzer=null;async getKnowledgeGraph(e){if(!this.knowledgeGraph){let t=e.memory??await $(),n=await Q(e);this.knowledgeGraph=new dn({memory:t,llmRouter:n})}return this.knowledgeGraph}async getSemanticAnalyzer(e){if(!this.semanticAnalyzer){let t=e.memory;this.semanticAnalyzer=new va(t||await $())}return this.semanticAnalyzer}async getImpactAnalyzer(e){if(!this.impactAnalyzer){let t=e.memory,n=await this.getKnowledgeGraph(e);this.impactAnalyzer=new ba(t||await $(),n)}return this.impactAnalyzer}async execute(e,t){let{action:n,paths:r=["."],query:i,changedFiles:s=[],depth:a=3,incremental:c=!1}=e;try{if(this.emitStream(t,{status:"processing",message:`Executing ${n} action`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let l={action:n};switch(n){case"index":l.indexResult=await this.executeIndex(r,c,t);break;case"search":if(!i)return{success:!1,error:"Query is required for search action"};l.searchResult=await this.executeSearch(i,r,t);break;case"impact":if(s.length===0)return{success:!1,error:"changedFiles is required for impact action"};l.impactResult=await this.executeImpact(s,a,t);break;case"dependencies":l.dependencyResult=await this.executeDependencies(r,a,t);break;default:return{success:!1,error:`Unknown action: ${n}`}}return this.emitStream(t,{status:"complete",message:`${n} complete`,progress:100}),{success:!0,data:l}}catch(l){return{success:!1,error:`Code analysis failed: ${w(l)}`}}}async executeIndex(e,t,n){this.emitStream(n,{status:"indexing",message:`Indexing ${e.length} paths (${t?"incremental":"full"})`});let r=await this.getKnowledgeGraph(n),i=await this.expandPaths(e),s=await r.index({paths:i,incremental:t,includeTests:!0,languages:["typescript","javascript"]});if(!s.success)throw new Error(s.error?.message||"Indexing failed");return{filesIndexed:s.value.filesIndexed,nodesCreated:s.value.nodesCreated,edgesCreated:s.value.edgesCreated,duration:s.value.duration,errors:s.value.errors}}async executeSearch(e,t,n){let r=Date.now();if(this.isDemoMode(n)){let l=Date.now()-r;return this.markAsDemoData(n,"Demo mode explicitly requested"),this.getDemoSearchResult(e,l)}this.emitStream(n,{status:"searching",message:`Searching for: ${e}`});let s=await(await this.getSemanticAnalyzer(n)).search({query:e,type:"semantic",limit:20,scope:t.length>0&&t[0]!=="."?t:void 0}),a=Date.now()-r;if(!s.success)throw s.error;return s.value.results.length===0?(this.markAsRealData(),{results:[],total:0,searchTime:a}):(this.markAsRealData(),{results:s.value.results.map(l=>({file:l.file,line:l.line,snippet:l.snippet.substring(0,200)+(l.snippet.length>200?"...":""),score:l.score,highlights:Dm(l.snippet,e)})),total:s.value.total,searchTime:a})}getDemoSearchResult(e,t){return{results:[{file:"src/services/UserService.ts",line:15,snippet:`export class ${e} { constructor() { /* initialization */ } }...`,score:.95,highlights:[e,`class ${e}`,`${e}Service`]},{file:"src/handlers/user-handler.ts",line:42,snippet:`const service = new ${e}(); await service.initialize()...`,score:.85,highlights:[`new ${e}()`,`service.${e.toLowerCase()}`]},{file:"tests/services/UserService.test.ts",line:8,snippet:`describe('${e}', () => { it('should initialize correctly'...`,score:.78,highlights:[`describe('${e}'`,`test ${e}`]}],total:3,searchTime:t}}getDemoImpactResult(e){let t=e[0]||"src/service.ts",n=t.split("/").pop()?.replace(".ts","")||"service";return{directImpact:[{file:`src/handlers/${n}-handler.ts`,reason:`Direct import from ${t}`,distance:0,riskScore:.75},{file:`src/controllers/${n}-controller.ts`,reason:`Uses exported functions from ${t}`,distance:0,riskScore:.65}],transitiveImpact:[{file:"src/routes/api.ts",reason:`Imports from ${n}-handler.ts`,distance:1,riskScore:.45},{file:"src/app.ts",reason:"Imports API routes",distance:2,riskScore:.25}],impactedTests:[`tests/${n}.test.ts`,`tests/${n}-handler.test.ts`,"tests/integration/api.test.ts"],riskLevel:"medium",recommendations:[`Review changes in ${t} for breaking changes`,"Run affected test suites before merging","Consider updating dependent documentation"]}}async executeImpact(e,t,n){if(this.isDemoMode(n))return this.markAsDemoData(n,"Demo mode explicitly requested"),this.getDemoImpactResult(e);this.emitStream(n,{status:"analyzing",message:`Analyzing impact of ${e.length} changed files`});try{let i=await(await this.getImpactAnalyzer(n)).analyzeImpact({changedFiles:e,depth:t,includeTests:!0});if(!i.success)return{directImpact:[],transitiveImpact:[],impactedTests:[],riskLevel:"low",recommendations:[`Impact analysis failed: ${i.error?.message||"Unknown error"}. Ensure the code index is built first using action: 'index'.`]};this.markAsRealData();let s=i.value;return{directImpact:s.directImpact,transitiveImpact:s.transitiveImpact,impactedTests:s.impactedTests,riskLevel:s.riskLevel,recommendations:s.recommendations}}catch(r){return{directImpact:[],transitiveImpact:[],impactedTests:[],riskLevel:"low",recommendations:[`Impact analysis error: ${r instanceof Error?r.message:"Unknown error"}. Check that files exist and index is built.`]}}}async executeDependencies(e,t,n){this.emitStream(n,{status:"mapping",message:`Mapping dependencies to depth ${t}`});let r=await this.getKnowledgeGraph(n),i=await this.expandPaths(e),s=await r.mapDependencies({files:i,direction:"both",depth:t});if(!s.success)throw new Error(s.error?.message||"Dependency mapping failed");let a=s.value,c=a.nodes.map(u=>({id:u.id,path:u.path,type:u.type,inDegree:u.inDegree,outDegree:u.outDegree})),l=a.edges.map(u=>({source:u.source,target:u.target,type:u.type}));return{nodes:c,edges:l,cycles:a.cycles,metrics:{totalNodes:a.metrics.totalNodes,totalEdges:a.metrics.totalEdges,avgDegree:a.metrics.avgDegree,maxDepth:a.metrics.maxDepth}}}async expandPaths(e){let t=[];for(let n of e){let r=Ae.isAbsolute(n)?n:Ae.resolve(process.cwd(),n);try{let i=await Hi.promises.stat(r);if(i.isDirectory()){let s=await this.findSourceFiles(r);t.push(...s)}else i.isFile()&&t.push(r)}catch{}}return t}async findSourceFiles(e,t=!0){let n=[],r=[".ts",".tsx",".js",".jsx"],i=["node_modules",".git","dist","build","coverage"];try{let s=await Hi.promises.readdir(e,{withFileTypes:!0});for(let a of s){let c=Ae.join(e,a.name);if(a.isDirectory()){if(!i.includes(a.name)&&!Ys(e,a.name,t)){let l=await this.findSourceFiles(c,!1);n.push(...l)}}else if(a.isFile()){let l=Ae.extname(a.name);r.includes(l)&&n.push(c)}}}catch{}return n}},Im={type:"object",properties:{action:{type:"string",description:"Analysis action to perform",enum:["index","search","impact","dependencies"]},paths:{type:"array",description:"Paths to analyze",items:{type:"string",description:"File or directory path"},default:["."]},query:{type:"string",description:"Search query (for search action)"},changedFiles:{type:"array",description:"Changed files to analyze (for impact action)",items:{type:"string",description:"File path"}},depth:{type:"number",description:"Analysis depth",minimum:1,maximum:10,default:3},incremental:{type:"boolean",description:"Incremental indexing (for index action)",default:!1}},required:["action"]};function Dm(o,e){let t=[],n=e.toLowerCase().split(/\s+/),r=o.toLowerCase();for(let i of n){if(i.length<2)continue;let s=0;for(;(s=r.indexOf(i,s))!==-1;){let a=Math.max(0,s-20),c=Math.min(o.length,s+i.length+20),l=o.substring(a,c);if(t.includes(l)||t.push(l),s+=i.length,t.length>=3)break}if(t.length>=3)break}return t}M();var Vi=(o,e)=>o==="all"||o===e,ar=class extends A{config={name:"qe/code/c4",description:"Generate C4 architecture diagrams (Context/Container/Component, Mermaid) from a codebase with a deterministic confidence gate, or semantically search previously generated diagrams.",domain:"code-intelligence",schema:_m,streaming:!1,timeout:3e5};bridge=null;searchService=null;async getBridge(e){if(!this.bridge){let t=e.memory??await $();this.bridge=new ha(new Rs,t,{publishEvents:!1,enableC4Embeddings:!0,relationshipResolver:ya(n=>new dn(t,{basePath:n}))})}return this.bridge}async getSearchService(e){if(!this.searchService){let t=e.memory??await $();this.searchService=new fa(t,{enableEmbeddings:!0})}return this.searchService}async execute(e,t){let{action:n,projectPath:r=".",level:i="all",query:s,limit:a=10}=e,c=r;if(r!=="."){let l=await X("qe/code/c4","projectPath",r,{allowDirectory:!0});if(!l.success)return{success:!1,error:l.error.message};c=l.value}try{if(this.isAborted(t))return{success:!1,error:"Operation aborted"};let l={action:n};switch(n){case"generate":{let d=await(await this.getBridge(t)).requestC4Diagrams({projectPath:c,includeContext:Vi(i,"context"),includeContainer:Vi(i,"container"),includeComponent:Vi(i,"component"),includeDependency:i==="all",analyzeComponents:!0,detectExternalSystems:!0,analyzeCoupling:!0});if(!d.success)return{success:!1,error:w(d.error)};let m=d.value;l.generateResult={diagrams:m.diagrams,confidence:m.metadata.analysisMetadata?.confidence,componentsDetected:m.components.length,externalSystemsDetected:m.externalSystems.length,relationshipsDetected:m.relationships.length,circularDependencies:(m.couplingAnalysis??[]).filter(p=>p.isCircular).length};break}case"search":{if(!s)return{success:!1,error:"Query is required for search action"};let d=await(await this.getSearchService(t)).searchDiagrams(s,a);if(!d.success)return{success:!1,error:w(d.error)};l.searchResult={results:d.value.map(m=>({key:m.key,type:m.type,title:m.title,score:m.score,preview:m.preview})),total:d.value.length};break}default:return{success:!1,error:`Unknown action: ${n}`}}return{success:!0,data:l}}catch(l){return{success:!1,error:w(l)}}}},_m={type:"object",properties:{action:{type:"string",description:"C4 action to perform",enum:["generate","search"]},projectPath:{type:"string",description:"Project root to analyze (generate action). Defaults to the current directory."},level:{type:"string",description:"C4 level to generate (generate action)",enum:["context","container","component","all"]},query:{type:"string",description:"Semantic search query over stored diagrams (search action)"},limit:{type:"number",description:"Max search results (search action)"}},required:["action"]};M();te();Cs();var Kc=[{id:"secret-key-assignment",pattern:/(?:SECRET_KEY|secret_key|SECRET|PRIVATE_KEY)\s*=\s*['"][^'"]{4,}['"]/g,severity:"critical",title:"Hardcoded Secret Key",description:"Secret key assigned as string literal in source code",cweId:"CWE-798",remediation:'Use environment variables: SECRET_KEY = os.environ["SECRET_KEY"]'},{id:"cors-wildcard-credentials",pattern:/allow_origins\s*=\s*\[\s*["']\*["']\s*\]/g,severity:"high",title:"CORS Wildcard Origin",description:"CORS configured to allow all origins \u2014 combined with credentials this is a security risk",cweId:"CWE-942",remediation:"Restrict CORS origins to specific trusted domains"},{id:"cors-allow-credentials-wildcard",pattern:/allow_credentials\s*=\s*True/g,severity:"medium",title:"CORS Credentials Enabled",description:"CORS credentials enabled \u2014 verify origins are restricted",cweId:"CWE-942",remediation:'Ensure allow_origins does not include "*" when credentials are enabled'},{id:"token-hardcoded",pattern:/(?:token|TOKEN)\s*[:=]\s*['"][a-zA-Z0-9_\-.]{20,}['"]/g,severity:"high",title:"Hardcoded Token",description:"Hardcoded token found in source code",cweId:"CWE-798",remediation:"Use environment variables or secrets manager for tokens"}],or=class extends A{config={name:"qe/security/scan",description:"Comprehensive security scanning including SAST, DAST, dependency analysis, and compliance validation.",domain:"security-compliance",schema:Om,streaming:!0,timeout:6e5};async execute(e,t){let{target:n=".",scanType:r=["sast","dependency"],compliance:i=[],dastUrl:s,depth:a="standard",failOnSeverity:c="critical"}=e,l=Date.now();try{if(this.emitStream(t,{status:"scanning",message:`Starting security scan (${r.join(", ")})`,depth:a}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let u=await Lm(n,a);this.emitStream(t,{status:"discovered",message:`Found ${u.length} files to scan`});let d=[];if(r.includes("sast")||r.includes("secret")){this.emitStream(t,{status:"sast",message:"Running static analysis"});let v=await qm(u,r);d.push(...v)}if(r.includes("dependency")){this.emitStream(t,{status:"dependency",message:"Scanning dependencies"});let v=await $m(n);d.push(...v)}r.includes("dast")&&s&&(this.emitStream(t,{status:"dast",message:`Scanning ${s}`}),d.push(...Vm(s)));let m=i.map(v=>Qm(v,d)),p={critical:d.filter(v=>v.severity==="critical").length,high:d.filter(v=>v.severity==="high").length,medium:d.filter(v=>v.severity==="medium").length,low:d.filter(v=>v.severity==="low").length,informational:d.filter(v=>v.severity==="informational").length,totalFiles:u.length,scanDurationMs:Date.now()-l},f=["critical","high","medium","low","informational"],g=f.indexOf(c),y=(d.length>0?Math.min(...d.map(v=>f.indexOf(v.severity))):f.length)>g;return await on(await hn(t),{securityVulnerabilities:d.length},{measuredAt:new Date().toISOString(),source:"qe/security/scan"}),this.emitStream(t,{status:"complete",message:`Scan complete: ${d.length} vulnerabilities found in ${u.length} files`,progress:100}),{success:!0,data:{scanId:t.requestId,summary:p,vulnerabilities:d,complianceResults:m.length>0?m:void 0,recommendations:Wm(d,p),passed:y}}}catch(u){return{success:!1,error:`Security scan failed: ${w(u)}`}}}},Om={type:"object",properties:{target:{type:"string",description:"Target directory or file to scan",default:"."},scanType:{type:"array",description:"Types of security scans to run",items:{type:"string",description:"Scan type",enum:["sast","dast","dependency","secret"]},default:["sast","dependency"]},compliance:{type:"array",description:"Compliance standards to validate against",items:{type:"string",description:"Standard",enum:["owasp","gdpr","hipaa","pci-dss","soc2"]}},dastUrl:{type:"string",description:"URL for DAST scanning"},depth:{type:"string",description:"Scan depth",enum:["quick","standard","deep"],default:"standard"},failOnSeverity:{type:"string",description:"Fail threshold severity",enum:["critical","high","medium","low"],default:"critical"}}},Nm=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".pyw",".java",".kt",".scala",".go",".rb",".php",".rs",".cs",".yaml",".yml",".json",".toml",".cfg",".ini",".env",".env.local",".env.production",".sh",".bash"]),Fm=new Set(["node_modules",".git","__pycache__",".venv","venv","dist","build",".next",".nuxt","coverage",".tox"]);async function Lm(o,e){let t=await import("fs"),n=await import("path"),r=n.resolve(o),i=[],s=e==="quick"?50:e==="standard"?500:2e3,a=e==="quick"?3:e==="standard"?8:20;function c(l,u){if(i.length>=s||u>a)return;let d;try{d=t.readdirSync(l,{withFileTypes:!0})}catch{return}for(let m of d){if(i.length>=s)break;let p=n.join(l,m.name);if(m.isDirectory()){let f=new Set([".github",".docker",".aws",".circleci",".gitlab"]);Fm.has(m.name)||m.name.startsWith(".")&&!f.has(m.name)||c(p,u+1)}else if(m.isFile()){let f=n.extname(m.name).toLowerCase();(Nm.has(f)||m.name==="Dockerfile"||m.name==="Makefile"||m.name.startsWith(".env"))&&i.push(p)}}}try{t.statSync(r).isFile()?i.push(r):c(r,0)}catch{}return i}async function qm(o,e){let t=await import("fs"),n=await import("path"),r=[],i=0,s=[];if(e.includes("sast")){for(let a of wa)s.push({id:a.id,pattern:new RegExp(a.pattern.source,a.pattern.flags),severity:a.severity,title:a.title,description:a.description,cweId:a.cweId,remediation:a.remediation,category:a.category});for(let a of Kc)s.push({id:a.id,pattern:new RegExp(a.pattern.source,a.pattern.flags),severity:a.severity,title:a.title,description:a.description,cweId:a.cweId,remediation:a.remediation,category:"sensitive-data"})}if(e.includes("secret")){for(let a of Ea)s.some(c=>c.id===a.id)||s.push({id:a.id,pattern:new RegExp(a.pattern.source,a.pattern.flags),severity:a.severity,title:a.title,description:a.description,cweId:a.cweId,remediation:a.remediation,category:a.category});for(let a of Kc)s.some(c=>c.id===a.id)||s.push({...a,category:"sensitive-data"})}for(let a of o){let c;try{c=t.readFileSync(a,"utf-8")}catch{continue}if(c.includes("\0")||c.length>1e6)continue;let l=c.split(`
645
+ `),u=n.relative(process.cwd(),a);for(let d of s){let m=new RegExp(d.pattern.source,d.pattern.flags),p;for(;(p=m.exec(c))!==null;){i++;let f=c.substring(0,p.index).split(`
646
+ `).length,g=l[f-1]||"",h=g.trim().length>100?g.trim().substring(0,100)+"...":g.trim();if(r.push({id:`${d.id}-${i}`,title:d.title,severity:d.severity,category:d.category||"security-misconfiguration",location:{file:u,line:f,snippet:h},description:d.description,remediation:d.remediation,cweId:d.cweId,references:[]}),i>200)break}}}return r}async function $m(o){let e=await import("fs"),t=await import("path"),n=[],r=t.resolve(o),i=t.join(r,"package.json");if(e.existsSync(i))try{let c=I(e.readFileSync(i,"utf-8")),l={...c.dependencies,...c.devDependencies};n.push(...jm(l,"package.json"))}catch{}let s=t.join(r,"pyproject.toml");if(e.existsSync(s))try{let c=e.readFileSync(s,"utf-8"),l=Um(c);n.push(...Xc(l,"pyproject.toml"))}catch{}let a=t.join(r,"requirements.txt");if(e.existsSync(a))try{let c=e.readFileSync(a,"utf-8"),l=Bm(c);n.push(...Xc(l,"requirements.txt"))}catch{}if(n.length===0){let c=[i,s,a].filter(l=>e.existsSync(l));c.length>0&&n.push({id:"DEP-INFO-001",title:"Dependency audit recommended",severity:"informational",category:"vulnerable-components",location:{file:t.relative(process.cwd(),c[0])},description:`Found ${t.basename(c[0])} \u2014 run language-specific dependency audit for comprehensive results`,remediation:"Run npm audit, pip-audit, or equivalent for full vulnerability check",references:[]})}return n}var Gm={lodash:{maxSafe:"4.17.21",cve:"CVE-2021-23337",severity:"high",desc:"Prototype pollution in lodash"},minimist:{maxSafe:"1.2.6",cve:"CVE-2021-44906",severity:"critical",desc:"Prototype pollution in minimist"},"node-fetch":{maxSafe:"2.6.7",cve:"CVE-2022-0235",severity:"high",desc:"Information exposure in node-fetch"},express:{maxSafe:"4.19.2",cve:"CVE-2024-29041",severity:"medium",desc:"Open redirect in express"}};function jm(o,e){let t=[];for(let[n,r]of Object.entries(o)){let i=Rr(Gm,n);if(i){let s=r.replace(/^[\^~>=<]+/,"");Hm(s,i.maxSafe)<0&&t.push({id:`DEP-${n}-${i.cve}`,title:`Vulnerable ${n} version`,severity:i.severity,category:"vulnerable-components",location:{file:e,dependency:{name:n,version:s}},description:i.desc,remediation:`Upgrade ${n} to >= ${i.maxSafe}`,cveId:i.cve,references:[`https://nvd.nist.gov/vuln/detail/${i.cve}`]})}}return t}var zm={"python-jose":{cve:"CVE-2024-33663",severity:"critical",desc:"python-jose is abandoned and has known JWT vulnerabilities"},pyjwt:{cve:"CVE-2022-29217",severity:"high",desc:"PyJWT algorithm confusion vulnerability (upgrade to >= 2.4.0)"},"python-multipart":{cve:"CVE-2026-24486",severity:"high",desc:"python-multipart DoS vulnerability"},jinja2:{cve:"CVE-2024-34064",severity:"medium",desc:"Jinja2 XSS via template injection"},urllib3:{cve:"CVE-2023-45803",severity:"medium",desc:"urllib3 request body exposure on redirect"},requests:{cve:"CVE-2023-32681",severity:"medium",desc:"Requests proxy credential exposure"}};function Um(o){let e=[],t=o.match(/dependencies\s*=\s*\[([\s\S]*?)\]/);if(t){let n=t[1].matchAll(/["']([a-zA-Z0-9_-]+)/g);for(let r of n)e.push(r[1].toLowerCase())}return e}function Bm(o){return o.split(`
647
+ `).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")).map(e=>e.split(/[>=<!~\[]/)[0].trim().toLowerCase()).filter(Boolean)}function Xc(o,e){let t=[];for(let n of o){let r=Rr(zm,n);r&&t.push({id:`DEP-py-${n}-${r.cve}`,title:`Vulnerable Python dependency: ${n}`,severity:r.severity,category:"vulnerable-components",location:{file:e,dependency:{name:n,version:"any"}},description:r.desc,remediation:n==="python-jose"?"Migrate to PyJWT or joserfc":`Check for updates to ${n}`,cveId:r.cve,references:[`https://nvd.nist.gov/vuln/detail/${r.cve}`]})}return t}function Hm(o,e){let t=o.split(".").map(Number),n=e.split(".").map(Number);for(let r=0;r<3;r++){let i=t[r]||0,s=n[r]||0;if(i<s)return-1;if(i>s)return 1}return 0}function Vm(o){return[{id:"DAST-INFO-001",title:"DAST scan target noted",severity:"informational",category:"security-misconfiguration",location:{file:o},description:`DAST target ${o} recorded. Full DAST requires integration with a dynamic scanner (e.g., ZAP, Burp).`,remediation:"Configure a DAST tool to scan the live application",references:["https://owasp.org/www-project-zap/"]}]}function Qm(o,e){let t=e.filter(n=>o==="owasp"?!0:o==="pci-dss"?n.category==="injection"||n.category==="sensitive-data":o==="gdpr"?n.category==="sensitive-data":!1);return{standard:o,passed:t.filter(n=>n.severity==="critical"||n.severity==="high").length===0,score:Math.max(0,100-t.length*15),violations:t.map(n=>({ruleId:n.id,ruleName:n.title,location:n.location,details:n.description,remediation:n.remediation}))}}function Wm(o,e){let t=[];return e.critical>0&&t.push("URGENT: Address critical vulnerabilities immediately"),e.high>0&&t.push("Prioritize high-severity issues in next sprint"),o.some(n=>n.category==="injection")&&t.push("Review input validation across the application"),o.some(n=>n.category==="sensitive-data")&&t.push("Implement proper secrets management"),o.some(n=>n.category==="vulnerable-components")&&t.push("Run full dependency audit and update vulnerable packages"),t.length===0&&t.push("No critical issues found. Continue regular security reviews."),t}te();M();function Yc(o){try{let e=new URL(o);if(!["http:","https:"].includes(e.protocol))return{valid:!1,error:`Invalid protocol: ${e.protocol}. Only http/https allowed.`};let t=e.hostname.toLowerCase(),n=[/^localhost$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2[0-9]|3[01])\./,/^192\.168\./,/^0\.0\.0\.0$/,/^\[::1\]$/,/^169\.254\./];for(let r of n)if(r.test(t))return{valid:!1,error:`Blocked hostname: ${t}. Cannot access internal/private addresses.`};return{valid:!0}}catch{return{valid:!1,error:`Invalid URL format: ${o}`}}}var cr=class extends A{config={name:"qe/contracts/validate",description:"Validate API contracts, detect breaking changes, and verify provider-consumer compatibility.",domain:"contract-testing",schema:Km,streaming:!0,timeout:18e4};contractValidator=null;apiCompatibility=null;async getServices(e){if(!this.contractValidator||!this.apiCompatibility){let t=e.memory||await $(),n=await Q(e);this.contractValidator=new Ra({memory:t,llmRouter:n}),this.apiCompatibility=new Pa(t)}return{contractValidator:this.contractValidator,apiCompatibility:this.apiCompatibility}}async execute(e,t){let{contractPath:n,contractContent:r,providerUrl:i,consumerName:s,baselineVersion:a,baselineContent:c,checkBreakingChanges:l=!0,format:u="openapi"}=e,{contractValidator:d,apiCompatibility:m}=await this.getServices(t);try{if(!n&&!r)return{success:!1,error:"Either contractPath or contractContent is required"};if(this.emitStream(t,{status:"validating",message:`Validating ${u} contract`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let p=r||n||"",f=[],g,h,y;if(u==="openapi"){let C=await d.validateOpenAPI(p);if(C.success){let E=C.value;for(let T of E.errors)f.push({path:T.path,message:T.message,code:T.code,severity:"error"});for(let T of E.warnings)f.push({path:"",message:T,code:"WARNING",severity:"warning"});this.emitStream(t,{status:"analyzed",message:`Found ${E.endpointCount} endpoints, ${E.schemaCount} schemas`})}}else{let C=this.buildContractFromContent(p,u,s),E=await d.validateContract(C);if(E.success){let T=E.value;for(let S of T.errors)f.push(this.convertValidationError(S));for(let S of T.warnings)f.push({path:"",message:S,code:"WARNING",severity:"warning"})}}if(l&&(a||c)){this.emitStream(t,{status:"comparing",message:"Detecting breaking changes"});let C=this.buildContractFromContent(p,u,s),E=this.buildContractFromContent(c||p,u,s,a),T=await m.compareVersions(E,C);T.success?(g=T.value.breakingChanges.map(S=>this.convertBreakingChange(S)),y={isBackwardCompatible:T.value.isCompatible,breakingChangeCount:T.value.breakingChanges.length,nonBreakingChangeCount:T.value.nonBreakingChanges.length,deprecations:T.value.deprecations.map(S=>this.convertDeprecation(S))}):y=this.generateDefaultCompatibility(f,g)}else y=this.generateDefaultCompatibility(f,g);i&&(this.emitStream(t,{status:"verifying",message:"Verifying against provider"}),h=await this.verifyAgainstProvider(i,s||"default",p,u,d));let v=f.filter(C=>C.severity==="error").length===0,b=this.generateRecommendations(f,g,h);return this.emitStream(t,{status:"complete",message:v?"Contract is valid":`Found ${f.length} issues`,progress:100}),{success:!0,data:{isValid:v,validationErrors:f,breakingChanges:g,verificationResult:h,compatibility:y,recommendations:b}}}catch(p){return{success:!1,error:`Contract validation failed: ${w(p)}`}}}buildContractFromContent(e,t,n,r){let i=`contract-${Date.now()}`,s=Ta.parse(r||"1.0.0"),a=[],c=[];if(t==="openapi")try{let l=I(e),d=l.components?.schemas||{};for(let[p,f]of Object.entries(d))a.push({id:p,name:p,type:"openapi",content:JSON.stringify(f)});let m=l.paths||{};for(let[p,f]of Object.entries(m))if(typeof f=="object"&&f!==null){let g=f,h=["get","post","put","patch","delete","head","options"];for(let y of h)y in g&&c.push({path:p,method:y.toUpperCase(),examples:[]})}}catch{}else if(t==="graphql")a.push({id:"graphql-schema",name:"GraphQL Schema",type:"graphql",content:e});else if(t==="pact")try{let u=I(e).interactions||[];for(let d of u){let m=d.request;m&&c.push({path:m.path||"/",method:(m.method||"GET").toUpperCase(),examples:[]})}}catch{}return{id:i,name:`${t}-contract`,version:s,type:t,provider:{name:"provider",version:"1.0.0"},consumers:[{name:n||"default",version:"1.0.0"}],endpoints:c,schemas:a}}convertValidationError(e){return{path:e.path,message:e.message,code:e.code,severity:"error"}}convertBreakingChange(e){return{type:e.type,location:e.location,description:e.description,impact:e.impact,affectedConsumers:e.affectedConsumers,migrationPath:e.migrationPath}}convertDeprecation(e){return{location:e.location,reason:e.reason,removalVersion:e.removalVersion,replacement:e.replacement}}generateDefaultCompatibility(e,t){return{isBackwardCompatible:!t||t.length===0,breakingChangeCount:t?.length||0,nonBreakingChangeCount:e.filter(n=>n.severity!=="error").length,deprecations:[]}}async verifyAgainstProvider(e,t,n,r,i){let s=[],a=[],c=Yc(e);if(!c.valid)return{provider:e,consumer:t,passed:!1,failures:[{endpoint:e,type:"validation-error",expected:"Valid HTTP/HTTPS URL",actual:c.error||"Invalid URL",message:`Provider URL validation failed: ${c.error}`}],warnings:[]};let l=this.buildContractFromContent(n,r,t);for(let u of l.endpoints)try{let d=`${e}${u.path}`,m=Yc(d);if(!m.valid){s.push({endpoint:`${u.method} ${u.path}`,type:"validation-error",expected:"Valid URL",actual:m.error||"Invalid URL",message:`URL validation failed: ${m.error}`});continue}let p=await fetch(d,{method:u.method==="GET"?"GET":"OPTIONS",headers:{Accept:"application/json"}});if(!p.ok&&p.status!==405&&(p.status===404?s.push({endpoint:`${u.method} ${u.path}`,type:"missing-endpoint",expected:"Endpoint should exist",actual:`Got ${p.status}`,message:"Endpoint not found at provider"}):a.push({endpoint:`${u.method} ${u.path}`,message:`Unexpected status ${p.status}`,severity:"medium"})),u.responseSchema&&p.ok){let f=await p.json(),g=l.schemas.find(h=>h.id===u.responseSchema);if(g){let h=await i.validateResponse(f,g);if(h.success&&!h.value.isValid)for(let y of h.value.errors)s.push({endpoint:`${u.method} ${u.path}`,type:"schema-mismatch",expected:`Schema ${u.responseSchema}`,actual:y.message,message:`Response does not match schema: ${y.message}`})}}}catch(d){a.push({endpoint:`${u.method} ${u.path}`,message:`Failed to verify: ${w(d)}`,severity:"high"})}return{provider:e,consumer:t,passed:s.length===0,failures:s,warnings:a}}generateRecommendations(e,t,n){let r=[],i=e.filter(a=>a.severity==="error").length;if(i>0&&r.push(`Fix ${i} validation error${i>1?"s":""} before deploying`),t&&t.length>0){let a=t.filter(c=>c.impact==="high").length;a>0&&r.push(`Address ${a} high-impact breaking change${a>1?"s":""} before release`),r.push("Coordinate with affected consumers before releasing breaking changes"),r.push("Consider versioning the API to maintain backward compatibility")}n&&(n.passed||(r.push(`Provider verification failed with ${n.failures.length} failure${n.failures.length>1?"s":""}`),n.failures.filter(l=>l.type==="missing-endpoint").length>0&&r.push("Ensure all contract endpoints are implemented in the provider"),n.failures.filter(l=>l.type==="schema-mismatch").length>0&&r.push("Update provider responses to match the contract schema")),n.warnings.length>0&&n.warnings.filter(c=>c.severity==="high").length>0&&r.push("Investigate high-severity verification warnings"));let s=e.filter(a=>a.severity==="warning").length;return s>0&&r.push(`Review ${s} warning${s>1?"s":""} for potential issues`),r.length===0&&r.push("Contract is valid and backward compatible"),r}},Km={type:"object",properties:{contractPath:{type:"string",description:"Path to contract file"},contractContent:{type:"string",description:"Contract content as string"},providerUrl:{type:"string",description:"Provider URL for verification"},consumerName:{type:"string",description:"Consumer name for contract"},baselineVersion:{type:"string",description:"Baseline version for breaking change detection"},baselineContent:{type:"string",description:"Baseline contract content for comparison"},checkBreakingChanges:{type:"boolean",description:"Check for breaking changes",default:!0},format:{type:"string",description:"Contract format",enum:["openapi","pact","graphql","asyncapi"],default:"openapi"}}};M();var lr=class extends A{config={name:"qe/visual/compare",description:"Visual regression testing with screenshot comparison, diff detection, and baseline management.",domain:"visual-accessibility",schema:Xm,streaming:!0,timeout:3e5};visualTester=null;async getService(e){if(!this.visualTester){let t=e.memory??await $(),n=await Q(e);this.visualTester=xa({memory:t,llmRouter:n})}return this.visualTester}async execute(e,t){let{urls:n,viewports:r=[{width:1920,height:1080,name:"desktop"}],baselineDir:i=".visual-baselines",threshold:s=.1,fullPage:a=!0}=e;try{if(this.emitStream(t,{status:"capturing",message:`Capturing ${n.length} URLs across ${r.length} viewports`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};this.markAsRealData();let c=await this.getService(t),l=[],u=[];for(let m of n)for(let p of r){this.emitStream(t,{status:"comparing",message:`Comparing ${m} at ${p.width}x${p.height}`});let f={width:p.width,height:p.height,deviceScaleFactor:1,isMobile:p.isMobile||!1,hasTouch:p.isMobile||!1},g=await c.captureScreenshot(m,{viewport:f,fullPage:a});if(!g.success){l.push({url:m,viewport:p,status:"failed",diffPercentage:100,diffPixels:0});continue}let h=g.value,y=await c.getBaseline(m,f);if(!y)await c.setBaseline(h),u.push(h.path.value),l.push({url:m,viewport:p,status:"new",diffPercentage:0,diffPixels:0,screenshotPath:h.path.value});else{let v=await c.compare(h,y.id);if(!v.success){l.push({url:m,viewport:p,status:"failed",diffPercentage:100,diffPixels:0});continue}let b=v.value,C=b.diffPercentage<=s;l.push({url:m,viewport:p,status:C?"passed":"failed",diffPercentage:b.diffPercentage,diffPixels:b.diffPixels,screenshotPath:h.path.value,baselinePath:y.path.value,diffImagePath:b.diffImagePath?.value,regions:b.regions?.map(E=>({x:E.x,y:E.y,width:E.width,height:E.height,changeType:E.changeType,significance:E.significance}))})}}let d={total:l.length,passed:l.filter(m=>m.status==="passed").length,failed:l.filter(m=>m.status==="failed").length,new:l.filter(m=>m.status==="new").length,avgDiffPercentage:l.length>0?l.reduce((m,p)=>m+p.diffPercentage,0)/l.length:0};return this.emitStream(t,{status:"complete",message:`Visual comparison complete: ${d.passed}/${d.total} passed`,progress:100}),{success:!0,data:{comparisons:l,summary:d,newBaselines:u,recommendations:Zm(l,d)}}}catch(c){return{success:!1,error:`Visual comparison failed: ${w(c)}`}}}},ur=class extends A{config={name:"qe/a11y/audit",description:"WCAG accessibility auditing with violation detection, contrast checking, and keyboard navigation testing.",domain:"visual-accessibility",schema:Ym,streaming:!0,timeout:18e4};accessibilityTester=null;async getService(e){if(!this.accessibilityTester){let t=e.memory;this.accessibilityTester=new Aa(t||await $(),{enableColorContrastCheck:!0,enableKeyboardCheck:!0})}return this.accessibilityTester}async execute(e,t){let{urls:n,standard:r="wcag21-aa",includeWarnings:i=!0,checkContrast:s=!0,checkKeyboard:a=!0}=e;try{if(this.emitStream(t,{status:"auditing",message:`Auditing ${n.length} URLs against ${r}`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};this.markAsRealData();let c=await this.getService(t),l=[],u=Jm(r);for(let g of n){this.emitStream(t,{status:"scanning",message:`Scanning ${g}`});let h=await c.audit(g,{wcagLevel:u,includeWarnings:i});if(!h.success||h.value.measured!==!0){l.push({url:g,score:-1,passed:!1,violations:[],warnings:[],passedRules:0,measured:!1,notMeasuredReason:h.success?h.value.notMeasuredReason??"not measured":h.error.message});continue}let y=h.value,v=[],b=[];if(s){let x=await c.checkContrast(g);if(x.success){let k=x.value.filter(_=>!_.passes);if(k.length>0){let _=N=>N.ratio>=1?`${N.ratio}:1`:"not measured";b=k.map(N=>({id:"color-contrast",impact:"serious",description:"Elements must have sufficient color contrast",help:`Element ${N.element} has contrast ratio ${_(N)} but requires ${N.requiredRatio}:1`,helpUrl:"https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum",wcagCriteria:["1.4.3"],nodes:[{selector:N.element,html:`<${N.element.replace(".",' class="')}>...</${N.element.split(".")[0]}>`,failureSummary:`Contrast ratio ${_(N)} is below required ${N.requiredRatio}:1`,fixSuggestion:`Change foreground color to achieve at least ${N.requiredRatio}:1 contrast`}]}))}}else v.push({id:"color-contrast-not-measured",description:x.error.message,nodes:0})}let C=[];if(a){let x=await c.checkKeyboardNavigation(g);if(x.success){let k=x.value;k.notMeasured&&k.notMeasured.length>0&&v.push({id:"keyboard-not-measured",description:`Keyboard check did not measure: ${k.notMeasured.join("; ")}`,nodes:0});for(let _ of k.issues)C.push({id:_.type,impact:_.type==="no-focus-indicator"?"serious":"moderate",description:_.description,help:"Ensure keyboard navigation is fully supported",helpUrl:"https://www.w3.org/WAI/WCAG22/Understanding/focus-visible",wcagCriteria:["2.4.7"],nodes:[{selector:_.selector,html:`<element>${_.selector}</element>`,failureSummary:_.description,fixSuggestion:"Add visible focus styles with :focus or :focus-visible"}]});for(let _ of k.traps)C.push({id:"keyboard-trap",impact:"critical",description:_.description,help:_.escapePath||"No escape path available",helpUrl:"https://www.w3.org/WAI/WCAG22/Understanding/no-keyboard-trap",wcagCriteria:["2.1.2"],nodes:[{selector:_.selector,html:`<element>${_.selector}</element>`,failureSummary:_.description,fixSuggestion:_.escapePath}]})}else v.push({id:"keyboard-not-measured",description:x.error.message,nodes:0})}let E=[...y.violations.map(x=>({id:x.id,impact:x.impact,description:x.description,help:x.help,helpUrl:x.helpUrl,wcagCriteria:x.wcagCriteria.map(k=>k.id),nodes:x.nodes.map(k=>({selector:k.selector,html:k.html,failureSummary:k.failureSummary,fixSuggestion:k.fixSuggestion}))})),...b,...C],T=[...y.incomplete.map(x=>({id:x.id,description:x.description,nodes:x.nodes.length})),...v],S=E.some(x=>x.impact==="critical"||x.impact==="serious");l.push({url:g,score:y.score,passed:!S,violations:E,warnings:T,passedRules:y.passes.length,measured:!0})}let d=l.filter(g=>g.measured===!0),m={totalUrls:l.length,measuredUrls:d.length,passingUrls:d.filter(g=>g.passed).length,avgScore:d.length>0?Math.round(d.reduce((g,h)=>g+h.score,0)/d.length):-1,criticalViolations:l.reduce((g,h)=>g+h.violations.filter(y=>y.impact==="critical").length,0),seriousViolations:l.reduce((g,h)=>g+h.violations.filter(y=>y.impact==="serious").length,0),totalViolations:l.reduce((g,h)=>g+h.violations.length,0)},p=ep(l),f=tp(p);return this.emitStream(t,{status:"complete",message:m.avgScore<0?`Audit complete: no URL measured (0/${m.totalUrls}); no score`:`Audit complete: ${m.measuredUrls}/${m.totalUrls} URL(s) measured, avg score ${m.avgScore}%`,progress:100}),{success:!0,data:{audits:l,summary:m,topIssues:p,remediationPlan:f}}}catch(c){return{success:!1,error:`Accessibility audit failed: ${w(c)}`}}}},Xm={type:"object",properties:{urls:{type:"array",description:"URLs to capture and compare",items:{type:"string",description:"URL"}},viewports:{type:"array",description:"Viewport configurations",items:{type:"object",description:"Viewport",properties:{width:{type:"number",description:"Width in pixels"},height:{type:"number",description:"Height in pixels"},name:{type:"string",description:"Viewport name"}}}},baselineDir:{type:"string",description:"Directory for baseline images",default:".visual-baselines"},threshold:{type:"number",description:"Acceptable diff percentage (0-1)",minimum:0,maximum:1,default:.1},fullPage:{type:"boolean",description:"Capture full page",default:!0},hideSelectors:{type:"array",description:"CSS selectors to hide before capture",items:{type:"string",description:"Selector"}},waitForSelector:{type:"string",description:"Wait for selector before capture"}},required:["urls"]},Ym={type:"object",properties:{urls:{type:"array",description:"URLs to audit",items:{type:"string",description:"URL"}},standard:{type:"string",description:"WCAG standard to validate against",enum:["wcag21-aa","wcag21-aaa","wcag22-aa","section508"],default:"wcag21-aa"},includeWarnings:{type:"boolean",description:"Include warnings in results",default:!0},checkContrast:{type:"boolean",description:"Check color contrast",default:!0},checkKeyboard:{type:"boolean",description:"Check keyboard navigation",default:!0},rules:{type:"array",description:"Specific rules to check",items:{type:"string",description:"Rule ID"}}},required:["urls"]};function Jm(o){return o==="wcag21-aaa"?"AAA":"AA"}function Zm(o,e){let t=[];return e.failed>0&&t.push(`Review ${e.failed} failed comparisons for intentional vs unintentional changes`),e.new>0&&t.push(`${e.new} new baselines created - review and approve if correct`),e.avgDiffPercentage>1&&t.push("Consider increasing diff threshold or reviewing major changes"),t.length>0?t:["All visual tests passed"]}function ep(o){let e=new Map;for(let t of o)for(let n of t.violations){let r=e.get(n.id);r?(r.occurrences++,r.affectedUrls.includes(t.url)||r.affectedUrls.push(t.url)):e.set(n.id,{ruleId:n.id,description:n.description,occurrences:1,impact:n.impact,affectedUrls:[t.url]})}return Array.from(e.values()).sort((t,n)=>n.occurrences-t.occurrences)}function tp(o){return o.map((e,t)=>({violationId:e.ruleId,description:e.description,fix:`Fix ${e.ruleId} across ${e.occurrences} occurrences`,effort:e.occurrences>10?"moderate":"minor",priority:t+1}))}M();var dr=class extends A{config={name:"qe/chaos/inject",description:"Inject faults for chaos engineering. Supports latency, errors, CPU/memory stress, network issues, and more.",domain:"chaos-resilience",schema:np,streaming:!0,timeout:3e5};chaosEngineer=null;async getService(e){if(!this.chaosEngineer){let t=e.memory||await $(),n=await Q(e);this.chaosEngineer=new ka({memory:t,llmRouter:n},{enableDryRun:!0,autoRollbackOnFailure:!0})}return this.chaosEngineer}async execute(e,t){let{faultType:n,target:r,duration:i=3e4,intensity:s=50,dryRun:a=!0,hypothesis:c,rollbackOnFailure:l=!0}=e,u=await this.getService(t);try{if(this.emitStream(t,{status:"preparing",message:`Preparing ${n} fault injection on ${r}`,dryRun:a}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let d=t.requestId||U(),m=this.buildExperiment(d,n,r,i,s,c,l);this.emitStream(t,{status:"verifying",message:"Verifying steady state"});let p=await u.verifySteadyState(m.steadyState),f=p.success&&p.value;if(!f&&!a)return{success:!1,error:"Steady state verification failed. System not in healthy state for chaos experiment."};let g=await u.createExperiment(m);if(!g.success)return{success:!1,error:`Failed to create experiment: ${g.error.message}`};this.emitStream(t,{status:"injecting",message:a?`[DRY RUN] Planning ${n} fault (not injected)`:`Injecting ${n} fault`});let h=!1,y,v="pending",b=[],C={faultDuration:i,targetAffected:!a},E;if(a)h=!1,v="not-executed",E=`Dry run: the ${n} experiment was planned but no fault was injected, so no metrics were measured and the hypothesis was not tested.`;else{let S=await u.runExperiment(d);if(S.success){let x=S.value;h=x.faultResults.some(k=>k.injected),y=x.hypothesisValidated,v=x.status;for(let k of x.incidents)b.push(this.convertIncident(k));C=this.extractMetrics(x,n,i)}else v="failed",b.push({type:"error",severity:"critical",message:S.error.message,timestamp:new Date().toISOString(),resolved:!1})}this.emitStream(t,{status:"monitoring",message:"Monitoring system behavior"}),!a&&b.some(S=>S.severity==="critical"&&!S.resolved)&&(v=l?"rolled-back":"failed");let T=this.generateRecommendations(n,C,b,y);return this.emitStream(t,{status:"complete",message:`Chaos experiment ${v}`,progress:100}),{success:!0,data:{experimentId:d,status:v,faultInjected:h,hypothesisValidated:y,steadyStateVerified:f,metrics:C,incidents:b,recommendations:T,...E?{note:E}:{}}}}catch(d){return{success:!1,error:`Chaos injection failed: ${w(d)}`}}}buildExperiment(e,t,n,r,i,s,a=!0){let c={id:`fault-${e}`,type:t,target:{type:"service",selector:n},duration:r,parameters:this.buildFaultParameters(t,i)},l={description:`Steady state for ${n}`,probes:[{name:"target-health",type:n.startsWith("http")?"http":"command",target:n.startsWith("http")?n:`echo "checking ${n}"`,expected:n.startsWith("http")?200:"OK",timeout:5e3}]},u=s||`System should remain stable under ${t} fault`;return{id:e,name:`${t}-experiment-${Date.now()}`,description:`Chaos experiment: ${t} on ${n}`,hypothesis:{statement:u,metrics:[{metric:t==="latency"?"response_time":"error_rate",operator:"lt",value:t==="latency"?5e3:50}],tolerances:[{metric:"availability",maxDeviation:20,unit:"percent"}]},steadyState:l,faults:[c],blastRadius:{scope:"single",maxAffected:1,excludeProduction:!0},rollbackPlan:{automatic:a,triggerConditions:[{type:"error-rate",condition:"error_rate > 50%"}],steps:[{order:1,action:"remove-fault",target:c.id,timeout:1e4}]},schedule:{type:"once"}}}buildFaultParameters(e,t){let n={};switch(e){case"latency":n.latencyMs=100+t*20;break;case"error":n.errorCode=500,n.errorRate=t/100;break;case"timeout":n.timeoutMs=5e3+t*250;break;case"cpu-stress":n.cpuPercent=t,n.cores=Math.max(1,Math.floor(t/25));break;case"memory-stress":n.memoryBytes=t/100*512*1024*1024;break;case"network-partition":n.partitionPercent=t;break;case"packet-loss":n.packetLossPercent=t;break;case"dns-failure":n.failureRate=t/100;break;case"process-kill":n.signal="SIGTERM";break}return n}extractMetrics(e,t,n){let r={faultDuration:n,targetAffected:e.faultResults.some(c=>c.injected&&c.affectedTargets>0)},i=e.metrics;e.endTime&&e.startTime&&(r.recoveryTime=e.endTime.getTime()-e.startTime.getTime());let s=i.find(c=>c.name.includes("latency")||c.name.includes("response"));s&&(r.latencyP99=s.value);let a=i.find(c=>c.name.includes("error")||c.name.includes("failure"));return a&&(r.errorRate=a.value),r}convertIncident(e){return{type:e.type,severity:e.severity,message:e.message,timestamp:e.timestamp instanceof Date?e.timestamp.toISOString():String(e.timestamp),resolved:e.resolved}}generateRecommendations(e,t,n,r){let i=[];switch(r===!1&&i.push("Hypothesis was not validated - review resilience patterns"),t.recoveryTime&&t.recoveryTime>3e4&&i.push("Recovery time exceeds 30s - consider adding circuit breakers"),t.errorRate&&t.errorRate>20&&i.push("High error rate observed - implement retry with backoff"),n.some(s=>s.severity==="critical")&&i.push("Critical incidents occurred - review fault tolerance mechanisms"),e){case"latency":t.latencyP99&&t.latencyP99>1e3&&i.push("P99 latency exceeds 1s - consider timeout configurations");break;case"network-partition":i.push("Ensure services can operate in degraded mode during network issues");break;case"cpu-stress":case"memory-stress":i.push("Review resource limits and auto-scaling policies");break;case"error":i.push("Implement proper error handling and fallback mechanisms");break;case"timeout":i.push("Configure appropriate timeout values and circuit breakers");break}return i.length===0&&i.push("System showed good resilience - continue regular chaos experiments"),i}},np={type:"object",properties:{faultType:{type:"string",description:"Type of fault to inject",enum:["latency","error","timeout","cpu-stress","memory-stress","network-partition","packet-loss","dns-failure","process-kill"]},target:{type:"string",description:"Target service, pod, or endpoint"},duration:{type:"number",description:"Fault duration in milliseconds",minimum:1e3,maximum:3e5,default:3e4},intensity:{type:"number",description:"Fault intensity (0-100)",minimum:0,maximum:100,default:50},dryRun:{type:"boolean",description:"Plan the experiment without injecting a fault; nothing is measured",default:!0},hypothesis:{type:"string",description:'Hypothesis to validate (e.g., "System should recover within 30s")'},rollbackOnFailure:{type:"boolean",description:"Auto-rollback on critical failure",default:!0}},required:["faultType","target"]};M();var Ft=class extends A{config={name:"qe/learning/optimize",description:"Cross-domain learning, pattern recognition, strategy optimization, and knowledge transfer.",domain:"learning-optimization",schema:rp,streaming:!0,timeout:3e5};learningCoordinator=null;metricsOptimizer=null;transferSpecialist=null;async getServices(e){if(!this.learningCoordinator||!this.metricsOptimizer||!this.transferSpecialist){let t=e.memory||await $(),n=await Q(e);this.learningCoordinator=new Ia({memory:t,llmRouter:n}),this.metricsOptimizer=new _a(t),this.transferSpecialist=new Da(t)}return{learningCoordinator:this.learningCoordinator,metricsOptimizer:this.metricsOptimizer,transferSpecialist:this.transferSpecialist}}async execute(e,t){let{action:n,domain:r,experienceIds:i,targetDomain:s,objective:a}=e;try{if(this.emitStream(t,{status:"processing",message:`Executing ${n} action`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let c={action:n};switch(n){case"learn":c.learnResult=await this.executeLearn(r,i,t),c.learnResult.evidenceStatus==="insufficient-evidence"&&(c.evidenceStatus="insufficient-evidence");break;case"optimize":if(!a)return{success:!1,error:"Objective is required for optimize action"};c.optimizeResult=await this.executeOptimize(r,a,t),c.optimizeResult.evidenceStatus==="insufficient-evidence"&&(c.evidenceStatus="insufficient-evidence");break;case"transfer":if(!r||!s)return{success:!1,error:"Both domain and targetDomain are required for transfer action"};c.transferResult=await this.executeTransfer(r,s,t);break;case"patterns":c.patternResult=await this.executePatterns(r,t),c.patternResult.evidenceStatus==="insufficient-evidence"&&(c.evidenceStatus="insufficient-evidence");break;case"dashboard":c.dashboardResult=await this.executeDashboard(t),c.dashboardResult.evidenceStatus==="insufficient-evidence"&&(c.evidenceStatus="insufficient-evidence");break;default:return{success:!1,error:`Unknown action: ${n}`}}return this.emitStream(t,{status:"complete",message:`${n} complete`,progress:100}),{success:!0,data:c}}catch(c){return{success:!1,error:`Learning optimization failed: ${w(c)}`}}}async executeLearn(e,t,n){let r=e||"learning-optimization";if(this.isDemoMode(n))return this.markAsDemoData(n,"Demo mode explicitly requested"),this.getDemoLearnResult(r);let{learningCoordinator:i}=await this.getServices(n);if(this.emitStream(n,{status:"learning",message:`Learning from ${t?.length||"recent"} experiences`}),t&&t.length>0)return this.learnFromExperienceIds(i,t);let s=Rt.lastNDays(7),a=await i.mineExperiences(r,s),c=[],l=0,u={};if(a.success){l=a.value.experienceCount,u={measuredExperiences:a.value.measuredExperienceCount??l,assignedRewardsExcluded:a.value.assignedRewardsExcluded??0,...a.value.evidenceStatus?{evidenceStatus:a.value.evidenceStatus}:{}};for(let d of a.value.patterns)c.push({id:d.id,type:d.type,name:d.name,description:d.description,confidence:d.confidence,usageCount:d.usageCount,successRate:d.successRate})}return this.markAsRealData(),{experiencesProcessed:l,...u,patternsLearned:c.length,newPatterns:c,improvement:null,unmeasured:["improvement"]}}async learnFromExperienceIds(e,t){let n=await e.getExperiencesByIds(t);if(!n.success)throw n.error;let r=n.value,i=new Set(t).size,{measured:s,assignedExcluded:a}=Lr(r),c=s.length>0?await e.learnPattern(r):null,l;r.length===0?l=`None of the ${i} requested experience ID(s) were found.`:s.length===0?l=`None of the ${r.length} experience(s) read has a measured outcome`+(a>0?` (${a} with an assigned reward excluded).`:"."):c&&!c.success&&(l=c.error.message);let u=c?.success?[{id:c.value.id,type:c.value.type,name:c.value.name,description:c.value.description,confidence:c.value.confidence,usageCount:c.value.usageCount,successRate:c.value.successRate}]:[];return this.markAsRealData(),{experiencesProcessed:r.length,experienceIdsNotFound:i-r.length,measuredExperiences:s.length,assignedRewardsExcluded:a,...s.length===0?{evidenceStatus:"insufficient-evidence"}:{},patternsLearned:u.length,...l?{noPatternReason:l}:{},newPatterns:u,improvement:null,unmeasured:["improvement"]}}getDemoLearnResult(e){return{experiencesProcessed:150,patternsLearned:12,newPatterns:[{id:`pattern-${e}-001`,type:"optimization",name:"Parallel Execution Pattern",description:`Optimal parallelism settings discovered for ${e}`,confidence:.92,usageCount:45,successRate:.87},{id:`pattern-${e}-002`,type:"retry",name:"Exponential Backoff Pattern",description:"Effective retry strategy for flaky operations",confidence:.88,usageCount:32,successRate:.91},{id:`pattern-${e}-003`,type:"caching",name:"Result Caching Pattern",description:"Cache frequently computed results for faster access",confidence:.85,usageCount:28,successRate:.82}],improvement:15.5}}async executeOptimize(e,t,n){let{learningCoordinator:r,metricsOptimizer:i}=await this.getServices(n);this.emitStream(n,{status:"optimizing",message:`Optimizing for ${t.metric}`});let s=e||"learning-optimization",a=Rt.lastNDays(30),c=await r.getExperiences(s,a);if(!c.success)throw c.error;let{measured:l,assignedExcluded:u}=Lr(c.value),d=l.filter(T=>{let S=T.result.outcome[t.metric];return typeof S=="number"&&Number.isFinite(S)}),m={name:`${s}-current`,parameters:{parallelism:4,retryCount:3,timeout:3e4},expectedOutcome:{}},p=(t.constraints||[]).map(T=>({metric:T.metric,operator:T.operator,value:T.value})),f={metric:t.metric,direction:t.direction,constraints:p},g=m,h=0,y=0,v=[],b=[],C,E;if(d.length>=20){let T=await i.optimizeStrategy(m,f,d);if(!T.success)throw T.error;g={name:T.value.optimizedStrategy.name,parameters:T.value.optimizedStrategy.parameters,expectedOutcome:T.value.optimizedStrategy.expectedOutcome},h=T.value.improvement*100,y=T.value.confidence,v=T.value.validationResults;let S=T.value.evaluation;S&&(E={method:S.method,trainingSamples:S.trainingSamples,heldOutSamples:S.heldOutSamples},C=S.estimated,b=[...S.unmeasured??[]])}else{let T={tags:[s,t.metric],objective:{metric:t.metric,direction:t.direction}},S=await i.recommendStrategy(T);if(!S.success)throw S.error;g={name:S.value.name,parameters:S.value.parameters,expectedOutcome:S.value.expectedOutcome},b=["improvement","confidence"]}return Object.keys(g.expectedOutcome).length===0&&b.push("expectedOutcome"),{inputSource:"recorded-experiences",experiencesUsed:d.length,...u>0?{assignedRewardsExcluded:u}:{},strategiesEvaluated:d.length>=20?1:0,...d.length<20?{evidenceStatus:"insufficient-evidence"}:{},...b.length>0?{unmeasured:b}:{},...C?{estimated:C}:{},...E?{evaluation:E}:{},bestStrategy:g,improvement:h,confidence:y,validationResults:v}}async executeTransfer(e,t,n){let{transferSpecialist:r}=await this.getServices(n);this.emitStream(n,{status:"transferring",message:`Transferring knowledge from ${e} to ${t}`});let i=await r.queryKnowledge({domain:e,minRelevance:.5,limit:50}),s=0,a=0,c=0;if(i.success){s=i.value.length;for(let u of i.value){let d=await r.transferKnowledge(u,t);d.success&&(a++,Math.abs(d.value.relevanceScore-u.relevanceScore)>.1&&c++)}}let l=s>0?a/s:0;return{sourcePatterns:s,transferredPatterns:a,adaptedPatterns:c,successRate:l,targetDomainUpdated:a>0}}async executePatterns(e,t){let{learningCoordinator:n}=await this.getServices(t),r=await this.getSONASnapshot(t);this.emitStream(t,{status:"analyzing",message:`Analyzing patterns${e?` for ${e}`:""}`});let i=await n.getPatternStats(e);if(!i.success)return{totalPatterns:0,byType:{},byDomain:{},topPatterns:[],avgConfidence:null,avgSuccessRate:null,evidenceStatus:"insufficient-evidence",sona:r};let s=i.value,a=s.topPatterns.map(l=>({id:l.id,type:l.type,name:l.name,description:l.description,confidence:l.confidence,usageCount:l.usageCount,successRate:l.successRate})),c=s.totalPatterns>0;return{totalPatterns:s.totalPatterns,byType:s.byType,byDomain:s.byDomain,topPatterns:a,avgConfidence:c?s.avgConfidence:null,avgSuccessRate:c?s.avgSuccessRate:null,...s.assignedPatternsExcluded?{assignedPatternsExcluded:s.assignedPatternsExcluded}:{},...s.legacyPatternsExcluded?{legacyPatternsExcluded:s.legacyPatternsExcluded}:{},...c?{}:{evidenceStatus:"insufficient-evidence"},sona:r}}async executeDashboard(e){let{learningCoordinator:t,transferSpecialist:n}=await this.getServices(e),r=await this.getSONASnapshot(e);this.emitStream(e,{status:"aggregating",message:"Aggregating learning metrics"});let i=await t.getPatternStats(),s=await n.queryKnowledge({minRelevance:0,limit:1e3}),a=Rt.lastNDays(1),c=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","learning-optimization"],l=0,u=0,d=[];for(let S of c){let x=await t.mineExperiences(S,a);x.success&&(l+=x.value.experienceCount,u+=x.value.assignedRewardsExcluded??0,d.push({domain:S,successRate:x.value.successRate}))}let{topPerformingDomains:m,measuredDomains:p}=Ma(d),f=i.success?i.value.totalPatterns:0,g=i.success?i.value.assignedPatternsExcluded??0:0,h=i.success?i.value.legacyPatternsExcluded??0:0,y=f>0&&i.success?i.value.avgSuccessRate:null,v=y,b=[],C=new Date;for(let S=6;S>=0;S--){let x=new Date(C.getTime()-S*24*60*60*1e3),k=new Date(x.getTime()+1440*60*1e3),_=Rt.create(x,k),N=0;for(let V of c.slice(0,3)){let L=await t.mineExperiences(V,_);L.success&&(N+=L.value.patterns.length)}b.push({timestamp:x.toISOString(),metric:"patterns-learned",value:N})}let E=[];f>=100&&E.push({name:`Reached ${Math.floor(f/50)*50} patterns`,achievedAt:null,domain:"learning-optimization"}),y!==null&&y>=.8&&E.push({name:`${Math.round(y*100)}% pattern success rate`,achievedAt:null,domain:m[0]||"learning-optimization"});let T=[];return v===null&&T.push("overallLearningRate"),p===0&&T.push("topPerformingDomains"),{overallLearningRate:v,totalPatterns:f,totalKnowledge:s.success?s.value.length:0,experiencesLast24h:l,...u>0?{assignedRewardsExcluded:u}:{},...g>0?{assignedPatternsExcluded:g}:{},...h>0?{legacyPatternsExcluded:h}:{},topPerformingDomains:m,...T.length>0?{evidenceStatus:"insufficient-evidence",unmeasured:T}:{},learningTrend:b,recentMilestones:E,sona:r}}async getSONASnapshot(e){let t=e.kernel?.getDomainAPI("learning-optimization");if(!t?.isSONAAvailable())return{available:!1,stats:null};try{return{available:!0,stats:await t.getSONAPersistedStats()}}catch(n){return this.logger.warn("Failed to read persisted SONA statistics",{requestId:e.requestId,error:w(n)}),{available:!1,stats:null}}}},rp={type:"object",properties:{action:{type:"string",description:"Learning action to perform",enum:["learn","optimize","transfer","patterns","dashboard"]},domain:{type:"string",description:"Source domain for learning/optimization",enum:["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization"]},experienceIds:{type:"array",description:"Specific experience IDs to learn from",items:{type:"string",description:"Experience ID"}},targetDomain:{type:"string",description:"Target domain for knowledge transfer"},objective:{type:"object",description:"Optimization objective",properties:{metric:{type:"string",description:"Metric to optimize"},direction:{type:"string",description:"maximize or minimize",enum:["maximize","minimize"]},constraints:{type:"array",description:"Optimization constraints",items:{type:"object",description:"Constraint"}}}}},required:["action"]};M();var ip={type:"object",properties:{action:{type:"string",enum:["dream","insights","apply","history","status"],description:"Action to perform: dream (run cycle), insights (view pending), apply (create pattern), history (view past), status (current state)"},durationMs:{type:"number",description:"Duration of dream cycle in milliseconds (default: 30000, max: 60000)",default:3e4},minPatterns:{type:"number",description:"Minimum patterns required to start dreaming (default: 10)",default:10},insightId:{type:"string",description:"Insight ID to apply (required for apply action)"},limit:{type:"number",description:"Maximum results to return (default: 20)",default:20},loadFromReasoningBank:{type:"boolean",description:"Load patterns from ReasoningBank before dreaming (default: true)",default:!0}},required:["action"]},Lt=class extends A{config={name:"qe/learning/dream",description:"Trigger dream cycles for pattern discovery. Dreams find novel associations between patterns through spreading activation, generating actionable insights.",domain:"learning-optimization",schema:ip,streaming:!1,timeout:12e4};engine=null;enginePending=null;async getEngine(){if(this.engine)return this.engine;if(!this.enginePending){let t=(async()=>{let r=Os();return await r.initialize(),this.enginePending===t?this.engine=r:r.close().catch(()=>{}),r})();this.enginePending=t;let n=()=>{this.enginePending===t&&(this.enginePending=null)};t.then(n,n)}return this.enginePending}async loadPatternsFromReasoningBank(e){try{let t=await $(),n=Mr(t);await n.initialize();try{let{getSharedRvfDualWriter:a}=await import("./shared-rvf-dual-writer-HVAAVEOH.js"),c=await a();c&&n.setRvfDualWriter(c)}catch(a){process.env.DEBUG&&this.logger.info("RVF wiring skipped",{error:String(a)})}let r=await n.searchPatterns("",{limit:100,minConfidence:.3});if(!r.success||!r.value.length)return this.logger.info("No patterns found in ReasoningBank to load"),0;let i=r.value.map(a=>({id:a.pattern.id,name:a.pattern.name,description:a.pattern.description||`${a.pattern.patternType} pattern`,domain:a.pattern.qeDomain||"learning-optimization",patternType:a.pattern.patternType,confidence:a.pattern.confidence,successRate:a.pattern.usageCount>0?a.pattern.successRate:void 0})),s=await e.loadPatternsAsConcepts(i);return this.logger.info(`Loaded ${s} patterns as concepts from ReasoningBank`),s}catch(t){return this.logger.warn("Failed to load patterns from ReasoningBank",{error:String(t)}),0}}async execute(e,t){let{action:n}=e;try{switch(n){case"dream":return this.runDreamCycle(e,t);case"insights":return this.getPendingInsights(e,t);case"apply":return this.applyInsight(e,t);case"history":return this.getDreamHistory(e,t);case"status":return this.getDreamStatus(e,t);default:return{success:!1,error:`Unknown action: ${n}`,data:{action:n,success:!1,error:`Unknown action: ${n}`}}}}catch(r){let i=w(r);return{success:!1,error:i,data:{action:n,success:!1,error:i}}}}async runDreamCycle(e,t){let n=Math.min(e.durationMs||3e4,6e4),r=e.minPatterns||10,i=e.loadFromReasoningBank!==!1;this.logger.info(`Starting dream cycle (${n}ms, min: ${r} patterns)`);let s=await this.getEngine(),a=s.getCurrentCycle();if(a)throw new _s(a.id);if(i){let d=await this.loadPatternsFromReasoningBank(s);this.logger.info(`Loaded ${d} patterns from ReasoningBank`)}let c=await s.dream(n,{minConceptsRequired:r}),l={cycleId:c.cycle.id,status:c.cycle.status,durationMs:c.cycle.durationMs||0,conceptsProcessed:c.cycle.conceptsProcessed,associationsFound:c.cycle.associationsFound,insightsGenerated:c.cycle.insightsGenerated,activationStats:c.activationStats,patternsCreated:c.patternsCreated,commitDurationMs:c.commitDurationMs,retention:c.retention?{enabled:c.retention.enabled,steps:Ds(c.retention)}:void 0},u=c.insights.map(d=>({id:d.id,type:d.type,description:d.description,noveltyScore:d.noveltyScore,confidenceScore:d.confidenceScore,actionable:d.actionable,applied:d.applied||!1,suggestedAction:d.suggestedAction,createdAt:d.createdAt?.toISOString()||new Date().toISOString()}));return this.logger.info(`Dream cycle complete: ${c.cycle.insightsGenerated} insights, ${c.cycle.associationsFound} associations found`),{success:!0,data:{action:"dream",success:!0,dreamResult:l,insights:u}}}async getPendingInsights(e,t){let n=e.limit||20;return{success:!0,data:{action:"insights",success:!0,insights:(await(await this.getEngine()).getPendingInsights(n)).map(a=>({id:a.id,type:a.type,description:a.description,noveltyScore:a.noveltyScore,confidenceScore:a.confidenceScore,actionable:a.actionable,applied:a.applied||!1,suggestedAction:a.suggestedAction,createdAt:a.createdAt?.toISOString()||new Date().toISOString()}))}}}async applyInsight(e,t){if(!e.insightId)return{success:!1,error:"insightId is required for apply action",data:{action:"apply",success:!1,error:"insightId is required for apply action"}};try{let r=await(await this.getEngine()).applyInsight(e.insightId);return r.success?(this.logger.info(`Applied insight ${e.insightId} \u2192 REAL pattern ${r.patternId} in ReasoningBank`),{success:!0,data:{action:"apply",success:!0,applyResult:{insightId:e.insightId,...r}}}):{success:!1,error:r.error,data:{action:"apply",success:!1,error:r.error}}}catch(n){let r=w(n);return{success:!1,error:r,data:{action:"apply",success:!1,error:r}}}}async getDreamHistory(e,t){let n=e.limit||20;return{success:!0,data:{action:"history",success:!0,history:(await(await this.getEngine()).getDreamHistory(n)).map(a=>({id:a.id,startTime:a.startTime.toISOString(),endTime:a.endTime?.toISOString(),durationMs:a.durationMs,status:a.status,conceptsProcessed:a.conceptsProcessed,associationsFound:a.associationsFound,insightsGenerated:a.insightsGenerated}))}}}async getDreamStatus(e,t){let n=await this.getEngine(),r=n.isDreaming(),i=n.getCurrentCycle(),s=await n.getDreamHistory(100),a=await n.getPendingInsights(100),c=s.reduce((d,m)=>d+m.insightsGenerated,0),l=s[0];return{success:!0,data:{action:"status",success:!0,status:{isDreaming:r,currentCycle:i?{id:i.id,startTime:i.startTime.toISOString(),endTime:i.endTime?.toISOString(),durationMs:i.durationMs,status:i.status,conceptsProcessed:i.conceptsProcessed,associationsFound:i.associationsFound,insightsGenerated:i.insightsGenerated}:void 0,totalCycles:s.length,totalInsights:c,pendingInsights:a.length,lastDreamTime:l?.startTime.toISOString()}}}}resetInstanceCache(){this.enginePending=null,this.engine&&(this.engine.close().catch(console.error),this.engine=null)}};M();var mr=class extends A{config={name:"qe/analysis/token_usage",description:"Analyze token consumption patterns and identify optimization opportunities across agents and domains.",domain:"learning-optimization",schema:sp,streaming:!1,timeout:3e4};async execute(e,t){let{operation:n,timeframe:r,agentId:i,domain:s}=e;try{if(this.isAborted(t))return{success:!1,error:"Operation aborted"};let a;switch(n){case"session":a=this.getSessionUsage(r);break;case"agent":a=this.getAgentUsage(i,r);break;case"domain":a=this.getDomainUsage(s,r);break;case"task":a=this.getTaskUsage(r);break;case"efficiency":a=this.getEfficiencyReport(r);break;case"dashboard":return{success:!0,data:{operation:"dashboard",timeframe:r||"all",summary:{totalTokens:0,totalCost:"$0.00",tokensSaved:0,savingsPercentage:0},optimization:{patternsReused:0,cacheHits:0,earlyExits:0,recommendations:[ws()]}}};default:return{success:!1,error:`Unknown operation: ${n}`}}return{success:!0,data:a}}catch(a){return{success:!1,error:`Token usage analysis failed: ${w(a)}`}}}getSessionUsage(e){let t=le.getSessionSummary(e),n={};for(let[i,s]of t.byAgent)n[i]={tokens:s.totalTokens,cost:J(s.totalCost),tasks:s.tasksExecuted};let r={};for(let[i,s]of t.byDomain)r[i]={tokens:s.totalTokens,cost:J(s.estimatedCostUsd||0)};return{operation:"session",timeframe:e||"all",summary:{totalTokens:t.totalUsage.totalTokens,totalCost:J(t.totalUsage.estimatedCostUsd||0),tokensSaved:t.optimizationStats.tokensSaved,savingsPercentage:t.optimizationStats.savingsPercentage},breakdown:{byAgent:Object.keys(n).length>0?n:void 0,byDomain:Object.keys(r).length>0?r:void 0},optimization:{patternsReused:t.optimizationStats.patternsReused,cacheHits:t.optimizationStats.cacheHits,earlyExits:t.optimizationStats.earlyExits,recommendations:this.generateSessionRecommendations(t)}}}getAgentUsage(e,t){let n=le.getAgentMetrics(e,t),r=le.getSessionSummary(t);if(e&&!Array.isArray(n)){let d=n,m=d.tasksExecuted>0?d.patternsReused/d.tasksExecuted:0;return{operation:"agent",timeframe:t||"all",summary:{totalTokens:d.totalTokens,totalCost:J(d.totalCost),tokensSaved:d.estimatedTokensSaved,savingsPercentage:this.calculateSavingsPercentage(d.totalTokens,d.estimatedTokensSaved)},optimization:{patternsReused:d.patternsReused,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateAgentRecommendations(d)},details:{agentMetrics:{agentId:d.agentId,totalInputTokens:d.totalInputTokens,totalOutputTokens:d.totalOutputTokens,totalTokens:d.totalTokens,totalCost:J(d.totalCost),tasksExecuted:d.tasksExecuted,patternsReused:d.patternsReused,tokensSaved:d.estimatedTokensSaved,efficiency:Math.round(m*100)}}}}let i=Array.isArray(n)?n:[n],s={},a=0,c=0,l=0,u=0;for(let d of i)s[d.agentId]={tokens:d.totalTokens,cost:J(d.totalCost),tasks:d.tasksExecuted},a+=d.totalTokens,c+=d.totalCost,l+=d.estimatedTokensSaved,u+=d.patternsReused;return{operation:"agent",timeframe:t||"all",summary:{totalTokens:a,totalCost:J(c),tokensSaved:l,savingsPercentage:this.calculateSavingsPercentage(a,l)},breakdown:{byAgent:Object.keys(s).length>0?s:void 0},optimization:{patternsReused:u,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateMultiAgentRecommendations(i)}}}getDomainUsage(e,t){let n=le.getDomainMetrics(e,t),r=le.getSessionSummary(t);if(e&&!(n instanceof Map)){let l=n;return{operation:"domain",timeframe:t||"all",summary:{totalTokens:l.totalTokens,totalCost:J(l.estimatedCostUsd||0),tokensSaved:r.optimizationStats.tokensSaved,savingsPercentage:r.optimizationStats.savingsPercentage},optimization:{patternsReused:r.optimizationStats.patternsReused,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateDomainRecommendations(e,l)},details:{domainMetrics:{domain:e,inputTokens:l.inputTokens,outputTokens:l.outputTokens,totalTokens:l.totalTokens,cost:J(l.estimatedCostUsd||0)}}}}let i=n instanceof Map?n:new Map,s={},a=0,c=0;for(let[l,u]of i)s[l]={tokens:u.totalTokens,cost:J(u.estimatedCostUsd||0)},a+=u.totalTokens,c+=u.estimatedCostUsd||0;return{operation:"domain",timeframe:t||"all",summary:{totalTokens:a,totalCost:J(c),tokensSaved:r.optimizationStats.tokensSaved,savingsPercentage:r.optimizationStats.savingsPercentage},breakdown:{byDomain:Object.keys(s).length>0?s:void 0},optimization:{patternsReused:r.optimizationStats.patternsReused,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateMultiDomainRecommendations(i)}}}getTaskUsage(e){let t=le.getTaskMetrics(e),n=le.getSessionSummary(e),r=t.slice(-100).map(i=>({taskId:i.taskId,agentId:i.agentId,domain:i.domain,operation:i.operation,tokens:i.usage.totalTokens,cost:J(i.usage.estimatedCostUsd||0),patternReused:i.patternReused,tokensSaved:i.tokensSaved||0,timestamp:new Date(i.timestamp).toISOString()}));return{operation:"task",timeframe:e||"all",summary:{totalTokens:n.totalUsage.totalTokens,totalCost:J(n.totalUsage.estimatedCostUsd||0),tokensSaved:n.optimizationStats.tokensSaved,savingsPercentage:n.optimizationStats.savingsPercentage},optimization:{patternsReused:n.optimizationStats.patternsReused,cacheHits:n.optimizationStats.cacheHits,earlyExits:n.optimizationStats.earlyExits,recommendations:[`${t.length} tasks analyzed in timeframe`]},details:{taskMetrics:r}}}getEfficiencyReport(e){let t=le.getEfficiencyReport(e),n=le.getSessionSummary(e);return{operation:"efficiency",timeframe:e||"all",summary:{totalTokens:t.totalTokensUsed,totalCost:J(t.totalTokensUsed*3e-6+t.totalTokensUsed*15e-6),tokensSaved:t.totalTokensSaved,savingsPercentage:t.savingsPercentage},optimization:{patternsReused:n.optimizationStats.patternsReused,cacheHits:n.optimizationStats.cacheHits,earlyExits:n.optimizationStats.earlyExits,recommendations:t.recommendations}}}generateSessionRecommendations(e){let t=[];if(e.totalUsage.totalTokens===0)return["No token usage recorded yet. Start executing tasks to track consumption."];let{patternsReused:n,cacheHits:r,earlyExits:i,savingsPercentage:s}=e.optimizationStats;return s<10&&t.push("Token savings below 10%. Enable pattern reuse and caching for better efficiency."),n===0&&e.byAgent.size>0&&t.push("No patterns reused. Consider enabling the pattern store for similar tasks."),r===0&&e.totalUsage.totalTokens>1e4&&t.push("No cache hits detected. Enable response caching to reduce API calls."),i===0&&e.byAgent.size>1&&t.push("Early exit optimization not used. Enable high-confidence pattern matching."),s>25&&t.push(`Excellent token efficiency! ${s.toFixed(1)}% savings achieved.`),t.length>0?t:["Token usage is within normal parameters."]}generateAgentRecommendations(e){let t=[];if(e.tasksExecuted===0)return["No tasks executed by this agent yet."];e.patternsReused/e.tasksExecuted<.1&&t.push("Low pattern reuse rate. Consider caching successful patterns.");let r=e.totalTokens/e.tasksExecuted;return r>5e3&&t.push(`High average tokens per task (${Math.round(r)}). Consider optimizing prompts.`),e.totalOutputTokens>e.totalInputTokens*2&&t.push("High output-to-input ratio. Request more concise responses."),t.length>0?t:["Agent token usage is efficient."]}generateMultiAgentRecommendations(e){let t=[];if(e.length===0)return["No agent data available."];let n=[...e].sort((s,a)=>a.totalTokens-s.totalTokens);n[0].totalTokens>0&&t.push(`Highest consumer: ${n[0].agentId} (${n[0].totalTokens.toLocaleString()} tokens)`);let r=e.reduce((s,a)=>s+a.totalTokens,0);return n[0].totalTokens/(r||1)>.5&&e.length>1&&t.push("Token usage imbalanced. Consider distributing workload across agents."),t}generateDomainRecommendations(e,t){let n=[];return t.totalTokens===0?[`No token usage recorded for ${e}.`]:(e==="test-generation"&&t.totalTokens>1e4&&n.push("Test generation consuming significant tokens. Consider batching test requests."),e==="code-intelligence"&&t.outputTokens>t.inputTokens*3&&n.push("Code intelligence generating verbose output. Consider summary-only mode."),n.length>0?n:[`${e} token usage is normal.`])}generateMultiDomainRecommendations(e){let t=[];if(e.size===0)return["No domain data available."];let n=Array.from(e.entries()).sort((r,i)=>i[1].totalTokens-r[1].totalTokens);return n[0][1].totalTokens>0&&t.push(`Highest consuming domain: ${n[0][0]} (${n[0][1].totalTokens.toLocaleString()} tokens)`),t}calculateSavingsPercentage(e,t){let n=e+t;return n===0?0:Math.round(t/n*1e4)/100}},sp={type:"object",properties:{operation:{type:"string",description:"Type of analysis to perform",enum:["session","agent","domain","task","efficiency","dashboard"]},timeframe:{type:"string",description:"Time period to analyze",enum:["1h","24h","7d","30d"]},agentId:{type:"string",description:"Specific agent ID to analyze (for agent operation)"},domain:{type:"string",description:"Specific domain to analyze (for domain operation)",enum:["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization"]}},required:["operation"]};M();function qt(o){return o===void 0?null:typeof o!="number"||!Number.isInteger(o)||o<1?`constraints.maxSteps must be a positive integer, got ${String(o)}`:null}var Qi={coverage:{line:0,branch:0,function:0,target:80,measured:!1},quality:{testsPassing:0,totalTests:0,securityScore:100,performanceScore:100},fleet:{activeAgents:0,availableAgents:[],maxAgents:8},resources:{timeRemaining:3600,memoryAvailable:4096,parallelSlots:4},context:{environment:"development",riskLevel:"medium"},patterns:{available:0,reusable:0}};var ap=[{name:"measure-coverage",description:"Run coverage analysis on the codebase to determine current coverage metrics",agentType:"qe-coverage-specialist",preconditions:{"coverage.measured":!1},effects:{"coverage.measured":!0},cost:2,estimatedDurationMs:3e4,successRate:.95,category:"coverage",qeDomain:"coverage-analysis",method:"analyze",params:{},implemented:!0},{name:"analyze-coverage-gaps",description:"Identify uncovered code paths and prioritize them by risk and complexity",agentType:"qe-gap-detector",preconditions:{"coverage.measured":!0},effects:{"coverage.gapsIdentified":!0},cost:1.5,estimatedDurationMs:15e3,successRate:.9,category:"coverage",qeDomain:"coverage-analysis",method:"detectGaps",params:{},implemented:!0},{name:"generate-coverage-tests",description:"Generate tests targeting identified coverage gaps using AI-powered analysis",agentType:"qe-test-generator",preconditions:{"coverage.gapsIdentified":!0},effects:{"coverage.line":{delta:10}},cost:4,estimatedDurationMs:6e4,successRate:.8,category:"coverage",qeDomain:"test-generation",method:"generateTests",params:{},implemented:!0},{name:"run-mutation-testing",description:"Run mutation testing to validate test effectiveness and find weak spots",agentType:"qe-mutation-tester",preconditions:{"coverage.line":{min:60}},effects:{"quality.mutationScore":{set:!0}},cost:5,estimatedDurationMs:12e4,successRate:.85,category:"coverage",qeDomain:"coverage-analysis",implemented:!1},{name:"prioritize-uncovered-paths",description:"Use sublinear O(log n) analysis to identify highest-risk uncovered paths",agentType:"qe-coverage-specialist",preconditions:{"coverage.gapsIdentified":!0},effects:{"coverage.riskPrioritized":!0},cost:1,estimatedDurationMs:1e4,successRate:.92,category:"coverage",qeDomain:"coverage-analysis",method:"calculateRisk",params:{},implemented:!0},{name:"generate-branch-tests",description:"Generate tests specifically targeting branch coverage improvements",agentType:"qe-test-generator",preconditions:{"coverage.measured":!0,"coverage.branch":{max:70}},effects:{"coverage.branch":{delta:8}},cost:3.5,estimatedDurationMs:45e3,successRate:.78,category:"coverage",qeDomain:"test-generation",method:"generateTests",params:{},implemented:!0}],op=[{name:"run-unit-tests",description:"Execute unit test suite with parallel execution",agentType:"qe-test-executor",preconditions:{},effects:{"quality.unitTestsRun":!0},cost:1,estimatedDurationMs:2e4,successRate:.95,category:"test",qeDomain:"test-execution",method:"runTests",params:{},implemented:!0},{name:"run-integration-tests",description:"Execute integration test suite with real database connections",agentType:"qe-test-executor",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.integrationTestsRun":!0},cost:2.5,estimatedDurationMs:45e3,successRate:.85,category:"test",qeDomain:"test-execution",method:"execute",params:{},implemented:!0},{name:"run-e2e-tests",description:"Execute end-to-end tests using Playwright or Cypress",agentType:"qe-e2e-tester",preconditions:{"quality.integrationTestsRun":!0},effects:{"quality.e2eTestsRun":!0},cost:4,estimatedDurationMs:9e4,successRate:.8,category:"test",qeDomain:"test-execution",method:"executeE2ETestSuite",params:{},implemented:!0},{name:"fix-failing-tests",description:"Analyze and fix failing tests based on error messages and stack traces",agentType:"qe-tdd-specialist",preconditions:{"quality.testsPassing":{max:90}},effects:{"quality.testsPassing":{delta:10}},cost:3,estimatedDurationMs:3e4,successRate:.75,category:"test",qeDomain:"test-generation",implemented:!1},{name:"fix-flaky-tests",description:"Identify and stabilize flaky tests by analyzing timing and async issues",agentType:"qe-flaky-hunter",preconditions:{"quality.flakyTests":{min:1}},effects:{"quality.flakyTests":{delta:-3}},cost:4,estimatedDurationMs:45e3,successRate:.7,category:"test",qeDomain:"test-execution",method:"detectFlaky",params:{},implemented:!0},{name:"generate-property-tests",description:"Generate property-based tests using fast-check or similar library",agentType:"qe-test-generator",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.propertyTestsGenerated":!0},cost:3.5,estimatedDurationMs:4e4,successRate:.82,category:"test",qeDomain:"test-generation",method:"generatePropertyTests",params:{},implemented:!0},{name:"run-contract-tests",description:"Execute consumer-driven contract tests using Pact or similar",agentType:"qe-contract-tester",preconditions:{"context.hasApiContracts":!0},effects:{"quality.contractTestsRun":!0},cost:2,estimatedDurationMs:25e3,successRate:.88,category:"test",qeDomain:"contract-testing",method:"verifyAllConsumers",params:{},implemented:!0}],cp=[{name:"security-scan",description:"Run comprehensive security scan using SAST and dependency analysis",agentType:"qe-security-scanner",preconditions:{},effects:{"quality.securityScanned":!0},cost:2,estimatedDurationMs:3e4,successRate:.95,category:"security",qeDomain:"security-compliance",method:"runSecurityAudit",params:{},implemented:!0},{name:"fix-vulnerabilities",description:"Remediate identified security vulnerabilities and update dependencies",agentType:"qe-security-auditor",preconditions:{"quality.securityScanned":!0,"quality.vulnerabilities":{min:1}},effects:{"quality.vulnerabilities":{delta:-5},"quality.securityScore":{delta:10}},cost:5,estimatedDurationMs:6e4,successRate:.7,category:"security",qeDomain:"security-compliance",implemented:!1},{name:"owasp-audit",description:"Perform OWASP Top 10 security audit on the application",agentType:"qe-security-auditor",preconditions:{"quality.securityScanned":!0},effects:{"quality.owaspCompliant":!0},cost:3,estimatedDurationMs:45e3,successRate:.85,category:"security",qeDomain:"security-compliance",method:"runComplianceCheck",params:{standard:"owasp"},implemented:!0},{name:"scan-secrets",description:"Scan codebase for hardcoded secrets and credentials",agentType:"qe-security-scanner",preconditions:{},effects:{"quality.secretsScanned":!0},cost:1,estimatedDurationMs:15e3,successRate:.98,category:"security",qeDomain:"security-compliance",method:"runSecurityAudit",params:{includeSecrets:!0},implemented:!0},{name:"run-dast",description:"Run dynamic application security testing against running application",agentType:"qe-security-auditor",preconditions:{"context.environment":"staging"},effects:{"quality.dastCompleted":!0},cost:4.5,estimatedDurationMs:12e4,successRate:.8,category:"security",qeDomain:"security-compliance",method:"runDASTScan",params:{},implemented:!0}],lp=[{name:"run-benchmarks",description:"Execute performance benchmarks to establish baseline metrics",agentType:"qe-performance-tester",preconditions:{},effects:{"quality.benchmarked":!0},cost:2,estimatedDurationMs:45e3,successRate:.9,category:"performance",qeDomain:"chaos-resilience",implemented:!1},{name:"load-test",description:"Run load testing with simulated concurrent traffic",agentType:"qe-load-tester",preconditions:{"context.environment":"staging"},effects:{"quality.loadTested":!0},cost:3.5,estimatedDurationMs:12e4,successRate:.85,category:"performance",qeDomain:"chaos-resilience",method:"runLoadTestSuite",params:{},implemented:!0},{name:"stress-test",description:"Run stress testing to find breaking points and system limits",agentType:"qe-chaos-engineer",preconditions:{"context.environment":"staging","quality.loadTested":!0},effects:{"quality.stressTested":!0},cost:4,estimatedDurationMs:9e4,successRate:.8,category:"performance",qeDomain:"chaos-resilience",method:"runTest",params:{type:"stress"},implemented:!0},{name:"profile-memory",description:"Profile memory usage and identify memory leaks",agentType:"qe-performance-tester",preconditions:{"quality.benchmarked":!0},effects:{"quality.memoryProfiled":!0},cost:2.5,estimatedDurationMs:6e4,successRate:.88,category:"performance",qeDomain:"chaos-resilience",implemented:!1},{name:"optimize-slow-tests",description:"Identify and optimize slow-running tests to improve CI/CD speed",agentType:"qe-performance-tester",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.testsOptimized":!0},cost:2,estimatedDurationMs:3e4,successRate:.82,category:"performance",qeDomain:"test-execution",implemented:!1}],up=[{name:"analyze-complexity",description:"Measure cyclomatic and cognitive complexity of codebase",agentType:"code-analyzer",preconditions:{},effects:{"quality.complexityAnalyzed":!0},cost:1,estimatedDurationMs:15e3,successRate:.95,category:"analysis",qeDomain:"quality-assessment",method:"analyzeComplexity",params:{},implemented:!0},{name:"detect-code-smells",description:"Identify code smells and anti-patterns using static analysis",agentType:"code-analyzer",preconditions:{},effects:{"quality.smellsDetected":!0},cost:1.5,estimatedDurationMs:2e4,successRate:.9,category:"analysis",qeDomain:"code-intelligence",implemented:!1},{name:"analyze-dependencies",description:"Analyze dependency graph and identify circular or outdated dependencies",agentType:"code-analyzer",preconditions:{},effects:{"quality.dependenciesAnalyzed":!0},cost:1,estimatedDurationMs:15e3,successRate:.92,category:"analysis",qeDomain:"code-intelligence",method:"mapDependencies",params:{},implemented:!0},{name:"measure-technical-debt",description:"Calculate technical debt metrics and generate remediation plan",agentType:"code-analyzer",preconditions:{"quality.complexityAnalyzed":!0,"quality.smellsDetected":!0},effects:{"quality.technicalDebtMeasured":!0},cost:2,estimatedDurationMs:25e3,successRate:.88,category:"analysis",qeDomain:"code-intelligence",implemented:!1},{name:"build-knowledge-graph",description:"Build semantic knowledge graph of codebase for intelligent context retrieval",agentType:"qe-intelligence-builder",preconditions:{"quality.dependenciesAnalyzed":!0},effects:{"quality.knowledgeGraphBuilt":!0},cost:3,estimatedDurationMs:6e4,successRate:.85,category:"analysis",qeDomain:"code-intelligence",method:"index",params:{},implemented:!0}],dp=[{name:"spawn-test-agent",description:"Spawn additional test execution agent for parallel work",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{max:10}},effects:{"fleet.activeAgents":{delta:1}},cost:.5,estimatedDurationMs:5e3,successRate:.95,category:"fleet",qeDomain:"test-execution",implemented:!1},{name:"optimize-fleet-topology",description:"Reconfigure fleet topology for optimal task distribution",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:3}},effects:{"fleet.efficiency":{delta:15}},cost:1,estimatedDurationMs:1e4,successRate:.85,category:"fleet",implemented:!1},{name:"scale-down-fleet",description:"Reduce fleet size to conserve resources during low-activity periods",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:5}},effects:{"fleet.activeAgents":{delta:-2}},cost:.3,estimatedDurationMs:3e3,successRate:.98,category:"fleet",implemented:!1},{name:"spawn-specialist-agent",description:"Spawn a specialized agent for specific domain work",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{max:12},"context.specialistNeeded":!0},effects:{"fleet.activeAgents":{delta:1},"fleet.specialistAvailable":!0},cost:1,estimatedDurationMs:8e3,successRate:.9,category:"fleet",implemented:!1},{name:"rebalance-workload",description:"Redistribute tasks across agents based on current load",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:2}},effects:{"fleet.workloadBalanced":!0},cost:.5,estimatedDurationMs:5e3,successRate:.92,category:"fleet",implemented:!1}],mp=[{name:"generate-quality-report",description:"Generate comprehensive quality report combining all metrics",agentType:"qe-quality-gate",preconditions:{"coverage.measured":!0,"quality.unitTestsRun":!0},effects:{"quality.reported":!0},cost:1,estimatedDurationMs:1e4,successRate:.95,category:"quality",qeDomain:"quality-assessment",method:"analyzeQuality",params:{},implemented:!0},{name:"enforce-quality-gate",description:"Check if all quality gates pass and report status",agentType:"qe-quality-gate",preconditions:{"quality.reported":!0},effects:{"quality.gatePassed":!0},cost:.5,estimatedDurationMs:5e3,successRate:.9,category:"quality",qeDomain:"quality-assessment",method:"evaluateGate",params:{},implemented:!0},{name:"validate-requirements",description:"Validate that tests cover all documented requirements",agentType:"qe-requirements-validator",preconditions:{"context.hasRequirements":!0},effects:{"quality.requirementsValidated":!0},cost:2,estimatedDurationMs:2e4,successRate:.88,category:"quality",qeDomain:"requirements-validation",method:"validate",params:{},implemented:!0},{name:"predict-defects",description:"Use ML-based defect prediction to identify high-risk code areas",agentType:"qe-defect-predictor",preconditions:{"quality.complexityAnalyzed":!0,"coverage.measured":!0},effects:{"quality.defectsPredicted":!0},cost:2.5,estimatedDurationMs:3e4,successRate:.82,category:"quality",qeDomain:"defect-intelligence",method:"predictDefects",params:{},implemented:!0},{name:"generate-deployment-report",description:"Generate deployment readiness report with all quality metrics",agentType:"qe-quality-gate",preconditions:{"quality.gatePassed":!0,"quality.securityScanned":!0},effects:{"quality.deploymentReady":!0},cost:1.5,estimatedDurationMs:15e3,successRate:.9,category:"quality",qeDomain:"quality-assessment",method:"getDeploymentAdvice",params:{},implemented:!0}],pp=[{name:"run-accessibility-audit",description:"Run WCAG 2.2 accessibility audit using axe-core or similar",agentType:"qe-accessibility-tester",preconditions:{"context.hasUI":!0},effects:{"quality.accessibilityAudited":!0},cost:2,estimatedDurationMs:3e4,successRate:.9,category:"quality",qeDomain:"visual-accessibility",method:"runAccessibilityAudit",params:{},implemented:!0},{name:"run-visual-regression",description:"Run visual regression testing with screenshot comparison",agentType:"qe-visual-tester",preconditions:{"context.hasUI":!0},effects:{"quality.visualRegressionRun":!0},cost:3,estimatedDurationMs:6e4,successRate:.85,category:"quality",qeDomain:"visual-accessibility",method:"runVisualTests",params:{},implemented:!0}],Jc=[...ap,...op,...cp,...lp,...up,...dp,...mp,...pp];function gp(o){return`action-${o}`}function Zc(o){return{...o,id:gp(o.name),executionCount:0}}function ye(){return Jc.map(Zc)}var ct=[{name:"achieve-90-percent-coverage",description:"Reach 90% line coverage through targeted test generation",conditions:{"coverage.line":{min:90}},priority:1,qeDomain:"coverage-analysis"},{name:"all-tests-passing",description:"All tests green with 100% pass rate",conditions:{"quality.testsPassing":{min:100}},priority:1,qeDomain:"test-execution"},{name:"security-compliant",description:"Pass security audit with no critical vulnerabilities",conditions:{"quality.securityScanned":!0,"quality.vulnerabilities":{max:0}},priority:2,qeDomain:"security-compliance"},{name:"deployment-ready",description:"Ready for production deployment with all quality gates passed",conditions:{"coverage.line":{min:80},"quality.testsPassing":{min:100},"quality.securityScanned":!0,"quality.gatePassed":!0},priority:1},{name:"performance-validated",description:"Performance benchmarks and load tests completed successfully",conditions:{"quality.benchmarked":!0,"quality.loadTested":!0},priority:2,qeDomain:"chaos-resilience"},{name:"code-quality-excellent",description:"Excellent code quality with low complexity and no code smells",conditions:{"quality.complexityAnalyzed":!0,"quality.smellsDetected":!0,"quality.technicalDebtMeasured":!0},priority:3,qeDomain:"code-intelligence"},{name:"full-test-suite",description:"Complete test suite with unit, integration, and e2e tests",conditions:{"quality.unitTestsRun":!0,"quality.integrationTestsRun":!0,"quality.e2eTestsRun":!0},priority:2,qeDomain:"test-execution"},{name:"accessibility-compliant",description:"WCAG 2.2 compliant with visual regression coverage",conditions:{"quality.accessibilityAudited":!0,"quality.visualRegressionRun":!0},priority:2,qeDomain:"visual-accessibility"}];te();vs();import{randomUUID as Ne}from"crypto";var pr=1e3,Xi=class{data=[];cmp;constructor(e){this.cmp=e}get length(){return this.data.length}push(e){this.data.push(e),this.bubbleUp(this.data.length-1)}pop(){if(this.data.length===0)return;let e=this.data[0],t=this.data.pop();return this.data.length>0&&(this.data[0]=t,this.sinkDown(0)),e}bubbleUp(e){for(;e>0;){let t=e-1>>1;if(this.cmp(this.data[e],this.data[t])<0)[this.data[e],this.data[t]]=[this.data[t],this.data[e]],e=t;else break}}sinkDown(e){let t=this.data.length;for(;;){let n=e,r=2*e+1,i=2*e+2;if(r<t&&this.cmp(this.data[r],this.data[n])<0&&(n=r),i<t&&this.cmp(this.data[i],this.data[n])<0&&(n=i),n!==e)[this.data[e],this.data[n]]=[this.data[n],this.data[e]],e=n;else break}}},fp=new Set(["__proto__","constructor","prototype"]),gr=class o{db=null;persistence=null;actions=new Map;initialized=!1;enablePlanReuse=!0;constructor(){}ensureDb(){if(!this.db)throw new Error("GOAPPlanner not initialized - call initialize() first");return this.db}write(e){let t=this.ensureDb();return wt(t,()=>e(t))}async initialize(){if(this.initialized)return;this.persistence=Ps(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.ensureDb().prepare("SELECT COUNT(*) as count FROM goap_actions").get().count===0&&this.seedDefaultActions(),this.backfillActionMethodBindings(),this.backfillActionDurationEstimates(),await this.loadActions(),this.initialized=!0,console.log(`[GOAPPlanner] Initialized: ${this.persistence.getDbPath()}`)}seedDefaultActions(){let e=ye(),t=this.ensureDb(),n=t.prepare(`
657
648
  INSERT INTO goap_actions (id, name, description, category, preconditions, effects, cost, qe_domain, agent_type, method, params, implemented, estimated_duration_ms)
658
649
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
659
650
  `);for(let i of e){let s=`action-${Date.now()}-${Ne().slice(0,8)}`;n.run(s,i.name,i.description,i.category,JSON.stringify(i.preconditions),JSON.stringify(i.effects),i.cost,i.qeDomain??null,i.agentType??null,i.method??null,i.params?JSON.stringify(i.params):null,i.implemented?1:0,i.estimatedDurationMs??null)}let r=t.prepare(`
660
651
  INSERT INTO goap_goals (id, name, description, conditions, priority, qe_domain)
661
652
  VALUES (?, ?, ?, ?, ?, ?)
662
- `);for(let i of ot){let s=`goal-${Date.now()}-${Ne().slice(0,8)}`;r.run(s,i.name,i.description,JSON.stringify(i.conditions),i.priority,i.qeDomain??null)}console.log(`[GOAPPlanner] Seeded ${e.length} actions and ${ot.length} goals`)}backfillActionMethodBindings(){let t=this.ensureDb().prepare(`
653
+ `);for(let i of ct){let s=`goal-${Date.now()}-${Ne().slice(0,8)}`;r.run(s,i.name,i.description,JSON.stringify(i.conditions),i.priority,i.qeDomain??null)}console.log(`[GOAPPlanner] Seeded ${e.length} actions and ${ct.length} goals`)}backfillActionMethodBindings(){let t=this.ensureDb().prepare(`
663
654
  UPDATE goap_actions SET method = ?, params = ?, implemented = 1
664
655
  WHERE name = ? AND (method IS NULL OR implemented = 0)
665
- `);for(let n of he())!n.implemented||!n.method||t.run(n.method,n.params?JSON.stringify(n.params):"{}",n.name)}backfillActionDurationEstimates(){let e=this.ensureDb();if(!e.prepare("SELECT 1 FROM goap_actions WHERE estimated_duration_ms IS NULL LIMIT 1").get())return;let n=e.prepare(`
656
+ `);for(let n of ye())!n.implemented||!n.method||t.run(n.method,n.params?JSON.stringify(n.params):"{}",n.name)}backfillActionDurationEstimates(){let e=this.ensureDb();if(!e.prepare("SELECT 1 FROM goap_actions WHERE estimated_duration_ms IS NULL LIMIT 1").get())return;let n=e.prepare(`
666
657
  UPDATE goap_actions SET estimated_duration_ms = ?
667
658
  WHERE estimated_duration_ms IS NULL AND name = ?
668
659
  AND agent_type IS ? AND category = ? AND qe_domain IS ?
669
660
  AND preconditions = ? AND effects = ?
670
661
  AND method IS ? AND params IS ? AND implemented = ?
671
- `);e.transaction(()=>{for(let r of he())r.estimatedDurationMs!==void 0&&n.run(r.estimatedDurationMs,r.name,r.agentType??null,r.category,r.qeDomain??null,JSON.stringify(r.preconditions),JSON.stringify(r.effects),r.method??null,r.params?JSON.stringify(r.params):null,r.implemented?1:0)})()}async findPlan(e,t,n){let r=Lt(n?.maxSteps);if(r)throw new Error(r);await this.initialize();let i=Date.now();if(this.enablePlanReuse){let d=await this.findSimilarPlan(t,.75);if(d&&this.validatePlanForState(d,e)&&this.planSatisfiesConstraints(d,e,t,n)){await this.recordPlanReuse(d.id,!0);let u={...d,estimatedDurationMs:d.actions.reduce((m,p)=>m+(p.estimatedDurationMs??pr),0),id:`plan-${Date.now()}-${Ne().slice(0,8)}`,initialState:this.cloneState(e),reusedFrom:d.id,status:"pending"};return await this.savePlan(u),u}}let s=this.getAvailableActions(n),a=this.aStarSearch(e,t,s,n);if(!a)return null;let c={id:`plan-${Date.now()}-${Ne().slice(0,8)}`,initialState:this.cloneState(e),goalState:t,actions:a,totalCost:a.reduce((d,u)=>d+u.cost,0),estimatedDurationMs:a.reduce((d,u)=>d+(u.estimatedDurationMs??pr),0),status:"pending"};await this.savePlan(c),await this.storePlanSignature(c);let l=Date.now()-i;return l>500&&console.warn(`[GOAPPlanner] Plan finding took ${l}ms (target: <500ms)`),c}aStarSearch(e,t,n,r){if(!this.canAnyActionAffectGoal(n,t))return null;let i=new Xi((y,C)=>y.f-C.f),s=new Set,a=new Map,c=new Map,l=this.buildHeuristic(t,n),d=l(e);if(!Number.isFinite(d))return null;let u={state:this.cloneState(e),action:null,parent:null,g:0,h:d,f:0,depth:0,estimatedDurationMs:0};u.f=u.g+u.h,i.push(u),a.set(this.hashState(e),0),c.set(this.hashState(e),[u]);let m=1e4,p=r?.maxSteps??20,g=r?.maxCost??1/0,f=r?.maxDurationMs??1/0,h=Number.isFinite(f),v=0;for(;i.length>0&&v<m;){v++;let y=i.pop(),C=this.hashState(y.state);if(!(h&&!c.get(C)?.includes(y))){if(this.meetsConditions(y.state,t))return this.reconstructPlan(y);if(!h){if(s.has(C))continue;s.add(C),a.delete(C)}if(!(y.depth>=p))for(let b of n){if(!this.meetsConditions(y.state,b.preconditions))continue;let E=this.applyAction(y.state,b),T=this.hashState(E);if(!h&&s.has(T))continue;let S=y.g+this.getActionCost(b,y.state),x=l(E);if(!Number.isFinite(x))continue;let M=S+x;if(S>g)continue;let O=y.estimatedDurationMs+(b.estimatedDurationMs??pr);if(O>f)continue;let k={state:E,action:b,parent:y,g:S,h:x,f:M,depth:y.depth+1,estimatedDurationMs:O};if(h){let z=c.get(T)??[];if(z.some(se=>se.g<=S&&se.estimatedDurationMs<=O&&se.depth<=k.depth))continue;c.set(T,[...z.filter(se=>!(S<=se.g&&O<=se.estimatedDurationMs&&k.depth<=se.depth)),k])}else{let z=a.get(T);if(z!==void 0&&S>=z)continue;a.set(T,S)}i.push(k)}}}return null}canAnyActionAffectGoal(e,t){let n=Object.keys(t);for(let r of e)for(let i of Object.keys(r.effects))for(let s of n)if(i===s||i.startsWith(s)||s.startsWith(i))return!0;return!1}reconstructPlan(e){let t=[],n=e;for(;n&&n.action;)t.unshift(n.action),n=n.parent;return t}applyAction(e,t){let n=this.cloneState(e);for(let[r,i]of Object.entries(t.effects))this.applyEffect(n,r,i);return n}applyEffect(e,t,n){if(typeof n=="string"||typeof n=="number"||typeof n=="boolean"){this.setStateValue(e,t,n);return}if(typeof n=="object"&&n!==null){let r=this.getStateValue(e,t);if("set"in n&&n.set!==void 0&&this.setStateValue(e,t,n.set),"delta"in n&&n.delta!==void 0&&typeof r=="number"){let i=Math.max(0,Math.min(100,r+n.delta));this.setStateValue(e,t,i)}}}meetsConditions(e,t){for(let[n,r]of Object.entries(t))if(!this.checkCondition(e,n,r))return!1;return!0}checkCondition(e,t,n){let r=this.getStateValue(e,t);return typeof n=="string"||typeof n=="number"||typeof n=="boolean"?r===n:!(typeof n=="object"&&n!==null&&("min"in n&&n.min!==void 0&&(typeof r!="number"||r<n.min)||"max"in n&&n.max!==void 0&&(typeof r!="number"||r>n.max)||"eq"in n&&n.eq!==void 0&&r!==n.eq))}buildHeuristic(e,t){let n=i=>i.successRate>0&&i.successRate<1?i.cost/i.successRate:i.cost,r=new Map;for(let i of Object.keys(e)){let s={setCost:1/0,upDelta:0,upCost:1/0,downDelta:0,downCost:1/0};for(let a of t){if(!Object.hasOwn(a.effects,i))continue;let c=a.effects[i],l=n(a);if(typeof c!="object"||c===null){s.setCost=Math.min(s.setCost,l);continue}"set"in c&&c.set!==void 0&&(s.setCost=Math.min(s.setCost,l)),"delta"in c&&typeof c.delta=="number"&&(c.delta>0?(s.upDelta=Math.max(s.upDelta,c.delta),s.upCost=Math.min(s.upCost,l)):c.delta<0&&(s.downDelta=Math.max(s.downDelta,-c.delta),s.downCost=Math.min(s.downCost,l)))}r.set(i,s)}return i=>{let s=0;for(let[a,c]of Object.entries(e)){if(this.checkCondition(i,a,c))continue;let l=r.get(a),d=this.getStateValue(i,a),u=l.setCost;if(typeof d=="number"&&typeof c=="object"&&c!==null?"min"in c&&typeof c.min=="number"&&d<c.min&&l.upDelta>0?u=Math.min(u,Math.ceil((c.min-d)/l.upDelta)*l.upCost):"max"in c&&typeof c.max=="number"&&d>c.max&&l.downDelta>0?u=Math.min(u,Math.ceil((d-c.max)/l.downDelta)*l.downCost):"eq"in c&&typeof c.eq=="number"&&(u=Math.min(u,l.upCost,l.downCost)):typeof d=="number"&&typeof c=="number"&&(u=Math.min(u,l.upCost,l.downCost)),!Number.isFinite(u))return 1/0;s=Math.max(s,u)}return s}}getStateValue(e,t){let n=t.split("."),r=e;for(let i of n){if(r==null||typeof r!="object"||!Object.hasOwn(r,i))return;r=r[i]}return r}setStateValue(e,t,n){let r=t.split(".");for(let a of r)if(Sp.has(a)){console.warn(`[GOAPPlanner] Blocked prototype pollution attempt: ${t}`);return}let i=e;for(let a=0;a<r.length-1;a++){let c=r[a];Object.hasOwn(i,c)||Object.defineProperty(i,c,{value:Object.create(null),writable:!0,enumerable:!0,configurable:!0});let l=Object.getOwnPropertyDescriptor(i,c);if(!l)return;i=l.value}let s=r[r.length-1];Object.defineProperty(i,s,{value:n,writable:!0,enumerable:!0,configurable:!0})}hashState(e){return o.stableStateKey(e,"")}static stableStateKey(e,t){if(e==null)return String(e);if(typeof e=="number")return Number.isFinite(e)?String(t==="resources.timeRemaining"?Math.floor(e/60):Math.round(e*1e6)/1e6):String(e);if(typeof e=="string")return JSON.stringify(e);if(typeof e=="boolean")return e?"true":"false";if(Array.isArray(e))return`[${e.map(n=>o.stableStateKey(n,t)).sort().join(",")}]`;if(typeof e=="object"){let n=e;return`{${Object.keys(n).sort().map(i=>`${i}:${o.stableStateKey(n[i],t?`${t}.${i}`:i)}`).join(",")}}`}return typeof e}cloneState(e){return{coverage:{...e.coverage},quality:{...e.quality},fleet:{...e.fleet,availableAgents:[...e.fleet.availableAgents]},resources:{...e.resources},context:{...e.context},patterns:{...e.patterns}}}getActionCost(e,t){let n=e.cost;return e.successRate<1&&(n=n/e.successRate),t.context.riskLevel==="high"&&(e.category==="performance"||e.category==="fleet")&&(n*=1.5),n}async loadActions(){let e=this.ensureDb().prepare("SELECT * FROM goap_actions ORDER BY category, cost").all();this.actions.clear();for(let t of e){let n={id:t.id,name:t.name,description:t.description??void 0,agentType:t.agent_type,preconditions:I(t.preconditions),effects:I(t.effects),cost:t.cost,estimatedDurationMs:t.estimated_duration_ms??void 0,successRate:t.success_rate,executionCount:t.execution_count,category:t.category,qeDomain:t.qe_domain,method:t.method??void 0,params:t.params?I(t.params):void 0,implemented:t.implemented===1};this.actions.set(n.id,n)}}async addAction(e){await this.initialize();let t=`action-${Date.now()}-${Ne().slice(0,8)}`;await this.write(r=>r.prepare(`
662
+ `);e.transaction(()=>{for(let r of ye())r.estimatedDurationMs!==void 0&&n.run(r.estimatedDurationMs,r.name,r.agentType??null,r.category,r.qeDomain??null,JSON.stringify(r.preconditions),JSON.stringify(r.effects),r.method??null,r.params?JSON.stringify(r.params):null,r.implemented?1:0)})()}async findPlan(e,t,n){let r=qt(n?.maxSteps);if(r)throw new Error(r);await this.initialize();let i=Date.now();if(this.enablePlanReuse){let u=await this.findSimilarPlan(t,.75);if(u&&this.validatePlanForState(u,e)&&this.planSatisfiesConstraints(u,e,t,n)){await this.recordPlanReuse(u.id,!0);let d={...u,estimatedDurationMs:u.actions.reduce((m,p)=>m+(p.estimatedDurationMs??pr),0),id:`plan-${Date.now()}-${Ne().slice(0,8)}`,initialState:this.cloneState(e),reusedFrom:u.id,status:"pending"};return await this.savePlan(d),d}}let s=this.getAvailableActions(n),a=this.aStarSearch(e,t,s,n);if(!a)return null;let c={id:`plan-${Date.now()}-${Ne().slice(0,8)}`,initialState:this.cloneState(e),goalState:t,actions:a,totalCost:a.reduce((u,d)=>u+d.cost,0),estimatedDurationMs:a.reduce((u,d)=>u+(d.estimatedDurationMs??pr),0),status:"pending"};await this.savePlan(c),await this.storePlanSignature(c);let l=Date.now()-i;return l>500&&console.warn(`[GOAPPlanner] Plan finding took ${l}ms (target: <500ms)`),c}aStarSearch(e,t,n,r){if(!this.canAnyActionAffectGoal(n,t))return null;let i=new Xi((v,b)=>v.f-b.f),s=new Set,a=new Map,c=new Map,l=this.buildHeuristic(t,n),u=l(e);if(!Number.isFinite(u))return null;let d={state:this.cloneState(e),action:null,parent:null,g:0,h:u,f:0,depth:0,estimatedDurationMs:0};d.f=d.g+d.h,i.push(d),a.set(this.hashState(e),0),c.set(this.hashState(e),[d]);let m=1e4,p=r?.maxSteps??20,f=r?.maxCost??1/0,g=r?.maxDurationMs??1/0,h=Number.isFinite(g),y=0;for(;i.length>0&&y<m;){y++;let v=i.pop(),b=this.hashState(v.state);if(!(h&&!c.get(b)?.includes(v))){if(this.meetsConditions(v.state,t))return this.reconstructPlan(v);if(!h){if(s.has(b))continue;s.add(b),a.delete(b)}if(!(v.depth>=p))for(let C of n){if(!this.meetsConditions(v.state,C.preconditions))continue;let E=this.applyAction(v.state,C),T=this.hashState(E);if(!h&&s.has(T))continue;let S=v.g+this.getActionCost(C,v.state),x=l(E);if(!Number.isFinite(x))continue;let k=S+x;if(S>f)continue;let _=v.estimatedDurationMs+(C.estimatedDurationMs??pr);if(_>g)continue;let N={state:E,action:C,parent:v,g:S,h:x,f:k,depth:v.depth+1,estimatedDurationMs:_};if(h){let V=c.get(T)??[];if(V.some(L=>L.g<=S&&L.estimatedDurationMs<=_&&L.depth<=N.depth))continue;c.set(T,[...V.filter(L=>!(S<=L.g&&_<=L.estimatedDurationMs&&N.depth<=L.depth)),N])}else{let V=a.get(T);if(V!==void 0&&S>=V)continue;a.set(T,S)}i.push(N)}}}return null}canAnyActionAffectGoal(e,t){let n=Object.keys(t);for(let r of e)for(let i of Object.keys(r.effects))for(let s of n)if(i===s||i.startsWith(s)||s.startsWith(i))return!0;return!1}reconstructPlan(e){let t=[],n=e;for(;n&&n.action;)t.unshift(n.action),n=n.parent;return t}applyAction(e,t){let n=this.cloneState(e);for(let[r,i]of Object.entries(t.effects))this.applyEffect(n,r,i);return n}applyEffect(e,t,n){if(typeof n=="string"||typeof n=="number"||typeof n=="boolean"){this.setStateValue(e,t,n);return}if(typeof n=="object"&&n!==null){let r=this.getStateValue(e,t);if("set"in n&&n.set!==void 0&&this.setStateValue(e,t,n.set),"delta"in n&&n.delta!==void 0&&typeof r=="number"){let i=Math.max(0,Math.min(100,r+n.delta));this.setStateValue(e,t,i)}}}meetsConditions(e,t){for(let[n,r]of Object.entries(t))if(!this.checkCondition(e,n,r))return!1;return!0}checkCondition(e,t,n){let r=this.getStateValue(e,t);return typeof n=="string"||typeof n=="number"||typeof n=="boolean"?r===n:!(typeof n=="object"&&n!==null&&("min"in n&&n.min!==void 0&&(typeof r!="number"||r<n.min)||"max"in n&&n.max!==void 0&&(typeof r!="number"||r>n.max)||"eq"in n&&n.eq!==void 0&&r!==n.eq))}buildHeuristic(e,t){let n=i=>i.successRate>0&&i.successRate<1?i.cost/i.successRate:i.cost,r=new Map;for(let i of Object.keys(e)){let s={setCost:1/0,upDelta:0,upCost:1/0,downDelta:0,downCost:1/0};for(let a of t){if(!Object.hasOwn(a.effects,i))continue;let c=a.effects[i],l=n(a);if(typeof c!="object"||c===null){s.setCost=Math.min(s.setCost,l);continue}"set"in c&&c.set!==void 0&&(s.setCost=Math.min(s.setCost,l)),"delta"in c&&typeof c.delta=="number"&&(c.delta>0?(s.upDelta=Math.max(s.upDelta,c.delta),s.upCost=Math.min(s.upCost,l)):c.delta<0&&(s.downDelta=Math.max(s.downDelta,-c.delta),s.downCost=Math.min(s.downCost,l)))}r.set(i,s)}return i=>{let s=0;for(let[a,c]of Object.entries(e)){if(this.checkCondition(i,a,c))continue;let l=r.get(a),u=this.getStateValue(i,a),d=l.setCost;if(typeof u=="number"&&typeof c=="object"&&c!==null?"min"in c&&typeof c.min=="number"&&u<c.min&&l.upDelta>0?d=Math.min(d,Math.ceil((c.min-u)/l.upDelta)*l.upCost):"max"in c&&typeof c.max=="number"&&u>c.max&&l.downDelta>0?d=Math.min(d,Math.ceil((u-c.max)/l.downDelta)*l.downCost):"eq"in c&&typeof c.eq=="number"&&(d=Math.min(d,l.upCost,l.downCost)):typeof u=="number"&&typeof c=="number"&&(d=Math.min(d,l.upCost,l.downCost)),!Number.isFinite(d))return 1/0;s=Math.max(s,d)}return s}}getStateValue(e,t){let n=t.split("."),r=e;for(let i of n){if(r==null||typeof r!="object"||!Object.hasOwn(r,i))return;r=r[i]}return r}setStateValue(e,t,n){let r=t.split(".");for(let a of r)if(fp.has(a)){console.warn(`[GOAPPlanner] Blocked prototype pollution attempt: ${t}`);return}let i=e;for(let a=0;a<r.length-1;a++){let c=r[a];Object.hasOwn(i,c)||Object.defineProperty(i,c,{value:Object.create(null),writable:!0,enumerable:!0,configurable:!0});let l=Object.getOwnPropertyDescriptor(i,c);if(!l)return;i=l.value}let s=r[r.length-1];Object.defineProperty(i,s,{value:n,writable:!0,enumerable:!0,configurable:!0})}hashState(e){return o.stableStateKey(e,"")}static stableStateKey(e,t){if(e==null)return String(e);if(typeof e=="number")return Number.isFinite(e)?String(t==="resources.timeRemaining"?Math.floor(e/60):Math.round(e*1e6)/1e6):String(e);if(typeof e=="string")return JSON.stringify(e);if(typeof e=="boolean")return e?"true":"false";if(Array.isArray(e))return`[${e.map(n=>o.stableStateKey(n,t)).sort().join(",")}]`;if(typeof e=="object"){let n=e;return`{${Object.keys(n).sort().map(i=>`${i}:${o.stableStateKey(n[i],t?`${t}.${i}`:i)}`).join(",")}}`}return typeof e}cloneState(e){return{coverage:{...e.coverage},quality:{...e.quality},fleet:{...e.fleet,availableAgents:[...e.fleet.availableAgents]},resources:{...e.resources},context:{...e.context},patterns:{...e.patterns}}}getActionCost(e,t){let n=e.cost;return e.successRate<1&&(n=n/e.successRate),t.context.riskLevel==="high"&&(e.category==="performance"||e.category==="fleet")&&(n*=1.5),n}async loadActions(){let e=this.ensureDb().prepare("SELECT * FROM goap_actions ORDER BY category, cost").all();this.actions.clear();for(let t of e){let n={id:t.id,name:t.name,description:t.description??void 0,agentType:t.agent_type,preconditions:I(t.preconditions),effects:I(t.effects),cost:t.cost,estimatedDurationMs:t.estimated_duration_ms??void 0,successRate:t.success_rate,executionCount:t.execution_count,category:t.category,qeDomain:t.qe_domain,method:t.method??void 0,params:t.params?I(t.params):void 0,implemented:t.implemented===1};this.actions.set(n.id,n)}}async addAction(e){await this.initialize();let t=`action-${Date.now()}-${Ne().slice(0,8)}`;await this.write(r=>r.prepare(`
672
663
  INSERT INTO goap_actions (
673
664
  id, name, description, agent_type, preconditions, effects,
674
665
  cost, estimated_duration_ms, success_rate, execution_count, category, qe_domain,
@@ -688,7 +679,7 @@ Analyze the requirements above and return the complete QualityCriteriaAnalysis.`
688
679
  FROM goap_plans${r}
689
680
  ORDER BY created_at DESC, id DESC
690
681
  LIMIT ?
691
- `).all(...i,s),l=[],d=[];for(let u of c){let m;try{m=I(u.action_sequence)}catch{d.push(u.id);continue}if(!Array.isArray(m)||!m.every(p=>typeof p=="string")){d.push(u.id);continue}l.push({id:u.id,status:u.status,stepCount:m.length,totalCost:u.total_cost,createdAt:u.created_at})}return{plans:l,count:a,...d.length?{invalidPlanIds:d}:{}}}async findSimilarPlan(e,t=.75){await this.initialize();let n=this.hashGoalConditions(e),r=this.ensureDb().prepare(`
682
+ `).all(...i,s),l=[],u=[];for(let d of c){let m;try{m=I(d.action_sequence)}catch{u.push(d.id);continue}if(!Array.isArray(m)||!m.every(p=>typeof p=="string")){u.push(d.id);continue}l.push({id:d.id,status:d.status,stepCount:m.length,totalCost:d.total_cost,createdAt:d.created_at})}return{plans:l,count:a,...u.length?{invalidPlanIds:u}:{}}}async findSimilarPlan(e,t=.75){await this.initialize();let n=this.hashGoalConditions(e),r=this.ensureDb().prepare(`
692
683
  SELECT * FROM goap_plan_signatures
693
684
  WHERE goal_hash = ? AND success_rate >= 0.5
694
685
  ORDER BY usage_count DESC, success_rate DESC
@@ -701,10 +692,10 @@ Analyze the requirements above and return the complete QualityCriteriaAnalysis.`
701
692
  UPDATE goap_plan_signatures
702
693
  SET usage_count = ?, success_rate = ?
703
694
  WHERE plan_id = ?
704
- `).run(i,a,t)}validatePlanForState(e,t){let n=this.cloneState(t);for(let r of e.actions){if(!this.meetsConditions(n,r.preconditions))return!1;n=this.applyAction(n,r)}return!0}planSatisfiesConstraints(e,t,n,r){let i=r?.maxSteps??20;if(e.actions.length>i||r?.maxDurationMs!==void 0&&e.actions.reduce((l,d)=>l+(d.estimatedDurationMs??pr),0)>r.maxDurationMs)return!1;let s=new Set(this.getAvailableActions(r).map(l=>l.id));if(!e.actions.every(l=>s.has(l.id)))return!1;let a=this.cloneState(t),c=0;for(let l of e.actions)c+=this.getActionCost(l,a),a=this.applyAction(a,l);return r?.maxCost!==void 0&&c>r.maxCost?!1:this.meetsConditions(a,n)}hashGoalConditions(e){let t=this.sortObjectKeys(e);return JSON.stringify(t)}sortObjectKeys(e){return e===null||typeof e!="object"?e:Array.isArray(e)?e.map(t=>this.sortObjectKeys(t)):Object.keys(e).sort().reduce((t,n)=>(t[n]=this.sortObjectKeys(e[n]),t),{})}extractStateVector(e){return[e.coverage.line/100,e.coverage.branch/100,e.coverage.function/100,e.coverage.measured?1:0,e.quality.testsPassing/100,e.quality.securityScore/100,e.quality.performanceScore/100,Math.min(e.fleet.activeAgents/10,1),Math.min(e.resources.timeRemaining/3600,1),Math.min(e.resources.parallelSlots/8,1)]}async addGoal(e){await this.initialize();let t=`goal-${Date.now()}-${Ne().slice(0,8)}`;return await this.write(n=>n.prepare(`
695
+ `).run(i,a,t)}validatePlanForState(e,t){let n=this.cloneState(t);for(let r of e.actions){if(!this.meetsConditions(n,r.preconditions))return!1;n=this.applyAction(n,r)}return!0}planSatisfiesConstraints(e,t,n,r){let i=r?.maxSteps??20;if(e.actions.length>i||r?.maxDurationMs!==void 0&&e.actions.reduce((l,u)=>l+(u.estimatedDurationMs??pr),0)>r.maxDurationMs)return!1;let s=new Set(this.getAvailableActions(r).map(l=>l.id));if(!e.actions.every(l=>s.has(l.id)))return!1;let a=this.cloneState(t),c=0;for(let l of e.actions)c+=this.getActionCost(l,a),a=this.applyAction(a,l);return r?.maxCost!==void 0&&c>r.maxCost?!1:this.meetsConditions(a,n)}hashGoalConditions(e){let t=this.sortObjectKeys(e);return JSON.stringify(t)}sortObjectKeys(e){return e===null||typeof e!="object"?e:Array.isArray(e)?e.map(t=>this.sortObjectKeys(t)):Object.keys(e).sort().reduce((t,n)=>(t[n]=this.sortObjectKeys(e[n]),t),{})}extractStateVector(e){return[e.coverage.line/100,e.coverage.branch/100,e.coverage.function/100,e.coverage.measured?1:0,e.quality.testsPassing/100,e.quality.securityScore/100,e.quality.performanceScore/100,Math.min(e.fleet.activeAgents/10,1),Math.min(e.resources.timeRemaining/3600,1),Math.min(e.resources.parallelSlots/8,1)]}async addGoal(e){await this.initialize();let t=`goal-${Date.now()}-${Ne().slice(0,8)}`;return await this.write(n=>n.prepare(`
705
696
  INSERT INTO goap_goals (id, name, description, conditions, priority, qe_domain)
706
697
  VALUES (?, ?, ?, ?, ?, ?)
707
- `).run(t,e.name,e.description??null,JSON.stringify(e.conditions),e.priority,e.qeDomain??null)),t}async getGoals(){return await this.initialize(),this.ensureDb().prepare("SELECT * FROM goap_goals ORDER BY priority DESC").all().map(t=>({id:t.id,name:t.name,description:t.description??void 0,conditions:I(t.conditions),priority:t.priority,qeDomain:t.qe_domain}))}setPlanReuseEnabled(e){this.enablePlanReuse=e}isPlanReuseEnabled(){return this.enablePlanReuse}async getPlanReuseStats(){await this.initialize();let e=this.ensureDb(),t=e.prepare("SELECT COUNT(*) as count FROM goap_plan_signatures").get(),n=e.prepare("SELECT COUNT(*) as count FROM goap_plan_signatures WHERE usage_count > 0").get(),r=e.prepare("SELECT AVG(success_rate) as avg FROM goap_plan_signatures WHERE usage_count > 0").get();return{totalPlans:t.count,reusedPlans:n.count,reuseRate:t.count>0?n.count/t.count:0,avgSuccessRate:r.avg??0}}async close(){this.actions.clear(),this.db=null,this.persistence=null,this.initialized=!1}},Wi=null;function Fe(){return Wi||(Wi=new gr),Wi}Tl();tn();pe();D();ee();vs();import{randomUUID as Yi}from"crypto";var Tp={maxRetries:2,stepTimeoutMs:6e4,replanOnFailure:!0,maxReplans:3,parallelExecution:!1,recordWorldState:!0,useUnified:!0,dryRun:!1};function rl(o,e=2e3){try{let t=typeof o=="string"?o:JSON.stringify(o);return t.length>e?`${t.slice(0,e)}...(truncated)`:t}catch{return String(o)}}function Ep(o){if(o==null)return"unknown error";if(o instanceof Error||typeof o=="string")return w(o);let e=o.message;return typeof e=="string"?e:rl(o,500)}var fr="__execution_cancelled__",nl="cancelled",ct=class{constructor(e,t,n,r,i){this.getDomainAPI=i;this.planner=e,this.spawner=t,this.config={...Tp,...r},this.config.useUnified||(this.db=ys(n??":memory:",{walMode:!1}),this.db.pragma("journal_mode = WAL"))}getDomainAPI;db;planner;spawner;config;currentExecution=null;initialized=!1;unifiedMemory=null;async initialize(){if(!this.initialized){if(this.config.useUnified)try{this.unifiedMemory=X(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),console.log(`[PlanExecutor] Using unified storage: ${this.unifiedMemory.getDbPath()}`)}catch(e){console.warn("[PlanExecutor] Failed to initialize unified storage, falling back to in-memory:",e),this.db=new(await import("./better-sqlite3-YO5X7ZJS.js")).default(":memory:"),this.db.pragma("journal_mode = WAL"),this.unifiedMemory=null,this.createTables()}else this.createTables();this.initialized=!0}}createTables(){this.db.exec(`
698
+ `).run(t,e.name,e.description??null,JSON.stringify(e.conditions),e.priority,e.qeDomain??null)),t}async getGoals(){return await this.initialize(),this.ensureDb().prepare("SELECT * FROM goap_goals ORDER BY priority DESC").all().map(t=>({id:t.id,name:t.name,description:t.description??void 0,conditions:I(t.conditions),priority:t.priority,qeDomain:t.qe_domain}))}setPlanReuseEnabled(e){this.enablePlanReuse=e}isPlanReuseEnabled(){return this.enablePlanReuse}async getPlanReuseStats(){await this.initialize();let e=this.ensureDb(),t=e.prepare("SELECT COUNT(*) as count FROM goap_plan_signatures").get(),n=e.prepare("SELECT COUNT(*) as count FROM goap_plan_signatures WHERE usage_count > 0").get(),r=e.prepare("SELECT AVG(success_rate) as avg FROM goap_plan_signatures WHERE usage_count > 0").get();return{totalPlans:t.count,reusedPlans:n.count,reuseRate:t.count>0?n.count/t.count:0,avgSuccessRate:r.avg??0}}async close(){this.actions.clear(),this.db=null,this.persistence=null,this.initialized=!1}},Wi=null;function Fe(){return Wi||(Wi=new gr),Wi}Cl();tn();ge();M();te();vs();import{randomUUID as Yi}from"crypto";var hp={maxRetries:2,stepTimeoutMs:6e4,replanOnFailure:!0,maxReplans:3,parallelExecution:!1,recordWorldState:!0,useUnified:!0,dryRun:!1};function tl(o,e=2e3){try{let t=typeof o=="string"?o:JSON.stringify(o);return t.length>e?`${t.slice(0,e)}...(truncated)`:t}catch{return String(o)}}function yp(o){if(o==null)return"unknown error";if(o instanceof Error||typeof o=="string")return w(o);let e=o.message;return typeof e=="string"?e:tl(o,500)}var fr="__execution_cancelled__",el="cancelled",lt=class{constructor(e,t,n,r,i){this.getDomainAPI=i;this.planner=e,this.spawner=t,this.config={...hp,...r},this.config.useUnified||(this.db=ys(n??":memory:"))}getDomainAPI;db;planner;spawner;config;currentExecution=null;initialized=!1;unifiedMemory=null;async initialize(){if(!this.initialized){if(this.config.useUnified)try{this.unifiedMemory=Y(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),console.log(`[PlanExecutor] Using unified storage: ${this.unifiedMemory.getDbPath()}`)}catch(e){console.warn("[PlanExecutor] Failed to initialize unified storage, falling back to in-memory:",e),this.db=new(await import("./better-sqlite3-2MCFXW4J.js")).default(":memory:"),this.db.pragma("journal_mode = WAL"),this.unifiedMemory=null,this.createTables()}else this.createTables();this.initialized=!0}}createTables(){this.db.exec(`
708
699
  CREATE TABLE IF NOT EXISTS goap_execution_steps (
709
700
  id TEXT PRIMARY KEY,
710
701
  plan_id TEXT NOT NULL,
@@ -726,7 +717,7 @@ Analyze the requirements above and return the complete QualityCriteriaAnalysis.`
726
717
  CREATE INDEX IF NOT EXISTS idx_goap_exec_steps_plan ON goap_execution_steps(plan_id);
727
718
  CREATE INDEX IF NOT EXISTS idx_goap_exec_steps_execution ON goap_execution_steps(execution_id);
728
719
  CREATE INDEX IF NOT EXISTS idx_goap_exec_steps_action ON goap_execution_steps(action_id);
729
- `)}async execute(e,t){return await this.initialize(),this.executeWithCallbacks(e,()=>{},()=>{},t)}async executeWithCallbacks(e,t,n,r){await this.initialize();let i=`exec-${Date.now()}-${Yi().slice(0,8)}`;this.currentExecution={planId:e.id,cancelled:!1};try{let s=await this.runPlan(e,t,n,r,{excludedActions:new Set,replanDepth:0});return await this.persistExecutionResult(i,s),s}finally{this.currentExecution=null}}async runPlan(e,t,n,r,i){let s=Date.now(),a={planId:e.id,status:"completed",stepsCompleted:0,stepsFailed:0,totalDurationMs:0,steps:[]},c=r?this.cloneState(r):this.cloneState(e.initialState),l=e.actions.map((d,u)=>({id:`step-${Date.now()}-${Yi().slice(0,8)}`,planId:e.id,action:d,stepOrder:u,status:"pending"}));for(let d of l){if(this.currentExecution?.cancelled){a.status="cancelled",a.error="Execution was cancelled";break}this.config.recordWorldState&&(d.worldStateBefore=this.cloneState(c)),t(d);let u=!1,m,p=0,g,f,h=Date.now();for(let y=0;y<=this.config.maxRetries;y++){let C=await this.executeStep(d,c);if(C.success){u=!0,c=C.newState,g=C.output,f=C.agentId;break}if(m=C.error,p=y,C.retryable===!1)break;y<this.config.maxRetries&&await this.delay(Math.min(1e3*Math.pow(2,y),5e3))}let v={...d,status:u?"completed":"failed",retries:p,startedAt:new Date(h),completedAt:new Date,durationMs:Date.now()-h,agentId:f,agentOutput:g,worldStateAfter:this.config.recordWorldState?this.cloneState(c):void 0,error:m};if(a.steps.push(v),n(v),u)a.stepsCompleted++,await this.updateActionStats(d.action.id,!0,v.durationMs??0);else{a.stepsFailed++,await this.updateActionStats(d.action.id,!1,0);let y=this.config.maxReplans??3;if(this.config.replanOnFailure&&i.replanDepth<y){i.excludedActions.add(d.action.id);let C=await this.replanFromFailure(e,d.stepOrder,c,[...i.excludedActions]);if(C){let b=await this.runPlan(C,t,n,c,{excludedActions:i.excludedActions,replanDepth:i.replanDepth+1});a.steps.push(...b.steps),a.stepsCompleted+=b.stepsCompleted,a.stepsFailed+=b.stepsFailed,b.status==="completed"&&b.finalWorldState?c=b.finalWorldState:(a.status=b.status==="cancelled"?"cancelled":"failed",a.error=`Step ${d.stepOrder} failed (${m}); replanning did not recover: ${b.error||"unknown error"}`);break}else{a.status="failed",a.error=`Step ${d.stepOrder} failed and replanning unsuccessful: ${m}`;break}}else{a.status="failed",a.error=`Step ${d.stepOrder} failed: ${m}`;break}}}return a.finalWorldState=c,a.totalDurationMs=Date.now()-s,a}async executeStep(e,t){let n=e.action;if(!this.meetsConditions(t,n.preconditions))return{success:!1,newState:t,error:`Preconditions not met for action: ${n.name}`,retryable:!1};if(n.implemented===!1)return{success:!1,newState:t,error:`Action '${n.name}' has no real implementation yet (not simulated \u2014 see GOAPAction.implemented)`,retryable:!1};if(!this.config.dryRun&&this.getDomainAPI&&n.implemented===!0)return this.executeRealAction(n,t);let r=this.buildTaskDescription(n);try{let i=await this.withStepTimeout(this.spawner.spawn(n.agentType,r));return i.success?{success:!0,newState:this.applyEffects(t,n.effects),output:i.output,agentId:i.agentId}:{success:!1,newState:t,agentId:i.agentId,error:i.error||"Agent execution failed"}}catch(i){return{success:!1,newState:t,error:w(i)}}}async executeRealAction(e,t){if(!e.qeDomain)return{success:!1,newState:t,error:`Action '${e.name}' has no qeDomain to resolve a real API from`,retryable:!1};if(!e.method)return{success:!1,newState:t,error:`Action '${e.name}' is marked implemented but has no method binding`,retryable:!1};let n;try{n=this.getDomainAPI(e.qeDomain)}catch(i){return{success:!1,newState:t,error:`Failed to resolve domain '${e.qeDomain}': ${w(i)}`}}if(!n)return{success:!1,newState:t,error:`Domain '${e.qeDomain}' is not available (kernel not initialized, or the domain isn't loaded \u2014 try fleet_init)`,retryable:!1};let r=n[e.method];if(typeof r!="function")return{success:!1,newState:t,error:`Domain '${e.qeDomain}' has no method '${e.method}'`,retryable:!1};try{let i=r.call(n,e.params??{}),s=await this.withStepTimeout(i);if(typeof s=="object"&&s!==null&&s.success===!1){let c=s.error;return{success:!1,newState:t,agentId:`domain:${e.qeDomain}`,error:`Domain '${e.qeDomain}' method '${e.method}' returned an error: `+Ep(c)}}return{success:!0,newState:this.applyEffects(t,e.effects),output:rl(s),agentId:`domain:${e.qeDomain}`}}catch(i){return{success:!1,newState:t,error:w(i)}}}async withStepTimeout(e){let t,n=new Promise((r,i)=>{t=setTimeout(()=>i(new Error(`Step timeout after ${this.config.stepTimeoutMs}ms`)),this.config.stepTimeoutMs)});try{return await Promise.race([e,n])}finally{t!==void 0&&clearTimeout(t)}}buildTaskDescription(e){let t=`Execute action: ${e.name}`;e.description&&(t+=`
720
+ `)}async execute(e,t){return await this.initialize(),this.executeWithCallbacks(e,()=>{},()=>{},t)}async executeWithCallbacks(e,t,n,r){await this.initialize();let i=`exec-${Date.now()}-${Yi().slice(0,8)}`;this.currentExecution={planId:e.id,cancelled:!1};try{let s=await this.runPlan(e,t,n,r,{excludedActions:new Set,replanDepth:0});return await this.persistExecutionResult(i,s),s}finally{this.currentExecution=null}}async runPlan(e,t,n,r,i){let s=Date.now(),a={planId:e.id,status:"completed",stepsCompleted:0,stepsFailed:0,totalDurationMs:0,steps:[]},c=r?this.cloneState(r):this.cloneState(e.initialState),l=e.actions.map((u,d)=>({id:`step-${Date.now()}-${Yi().slice(0,8)}`,planId:e.id,action:u,stepOrder:d,status:"pending"}));for(let u of l){if(this.currentExecution?.cancelled){a.status="cancelled",a.error="Execution was cancelled";break}this.config.recordWorldState&&(u.worldStateBefore=this.cloneState(c)),t(u);let d=!1,m,p=0,f,g,h=Date.now();for(let v=0;v<=this.config.maxRetries;v++){let b=await this.executeStep(u,c);if(b.success){d=!0,c=b.newState,f=b.output,g=b.agentId;break}if(m=b.error,p=v,b.retryable===!1)break;v<this.config.maxRetries&&await this.delay(Math.min(1e3*Math.pow(2,v),5e3))}let y={...u,status:d?"completed":"failed",retries:p,startedAt:new Date(h),completedAt:new Date,durationMs:Date.now()-h,agentId:g,agentOutput:f,worldStateAfter:this.config.recordWorldState?this.cloneState(c):void 0,error:m};if(a.steps.push(y),n(y),d)a.stepsCompleted++,await this.updateActionStats(u.action.id,!0,y.durationMs??0);else{a.stepsFailed++,await this.updateActionStats(u.action.id,!1,0);let v=this.config.maxReplans??3;if(this.config.replanOnFailure&&i.replanDepth<v){i.excludedActions.add(u.action.id);let b=await this.replanFromFailure(e,u.stepOrder,c,[...i.excludedActions]);if(b){let C=await this.runPlan(b,t,n,c,{excludedActions:i.excludedActions,replanDepth:i.replanDepth+1});a.steps.push(...C.steps),a.stepsCompleted+=C.stepsCompleted,a.stepsFailed+=C.stepsFailed,C.status==="completed"&&C.finalWorldState?c=C.finalWorldState:(a.status=C.status==="cancelled"?"cancelled":"failed",a.error=`Step ${u.stepOrder} failed (${m}); replanning did not recover: ${C.error||"unknown error"}`);break}else{a.status="failed",a.error=`Step ${u.stepOrder} failed and replanning unsuccessful: ${m}`;break}}else{a.status="failed",a.error=`Step ${u.stepOrder} failed: ${m}`;break}}}return a.finalWorldState=c,a.totalDurationMs=Date.now()-s,a}async executeStep(e,t){let n=e.action;if(!this.meetsConditions(t,n.preconditions))return{success:!1,newState:t,error:`Preconditions not met for action: ${n.name}`,retryable:!1};if(n.implemented===!1)return{success:!1,newState:t,error:`Action '${n.name}' has no real implementation yet (not simulated \u2014 see GOAPAction.implemented)`,retryable:!1};if(!this.config.dryRun&&this.getDomainAPI&&n.implemented===!0)return this.executeRealAction(n,t);let r=this.buildTaskDescription(n);try{let i=await this.withStepTimeout(this.spawner.spawn(n.agentType,r));return i.success?{success:!0,newState:this.applyEffects(t,n.effects),output:i.output,agentId:i.agentId}:{success:!1,newState:t,agentId:i.agentId,error:i.error||"Agent execution failed"}}catch(i){return{success:!1,newState:t,error:w(i)}}}async executeRealAction(e,t){if(!e.qeDomain)return{success:!1,newState:t,error:`Action '${e.name}' has no qeDomain to resolve a real API from`,retryable:!1};if(!e.method)return{success:!1,newState:t,error:`Action '${e.name}' is marked implemented but has no method binding`,retryable:!1};let n;try{n=this.getDomainAPI(e.qeDomain)}catch(i){return{success:!1,newState:t,error:`Failed to resolve domain '${e.qeDomain}': ${w(i)}`}}if(!n)return{success:!1,newState:t,error:`Domain '${e.qeDomain}' is not available (kernel not initialized, or the domain isn't loaded \u2014 try fleet_init)`,retryable:!1};let r=n[e.method];if(typeof r!="function")return{success:!1,newState:t,error:`Domain '${e.qeDomain}' has no method '${e.method}'`,retryable:!1};try{let i=r.call(n,e.params??{}),s=await this.withStepTimeout(i);if(typeof s=="object"&&s!==null&&s.success===!1){let c=s.error;return{success:!1,newState:t,agentId:`domain:${e.qeDomain}`,error:`Domain '${e.qeDomain}' method '${e.method}' returned an error: `+yp(c)}}return{success:!0,newState:this.applyEffects(t,e.effects),output:tl(s),agentId:`domain:${e.qeDomain}`}}catch(i){return{success:!1,newState:t,error:w(i)}}}async withStepTimeout(e){let t,n=new Promise((r,i)=>{t=setTimeout(()=>i(new Error(`Step timeout after ${this.config.stepTimeoutMs}ms`)),this.config.stepTimeoutMs)});try{return await Promise.race([e,n])}finally{t!==void 0&&clearTimeout(t)}}buildTaskDescription(e){let t=`Execute action: ${e.name}`;e.description&&(t+=`
730
721
 
731
722
  Description: ${e.description}`),t+=`
732
723
 
@@ -745,13 +736,13 @@ Expected effects:`;for(let[n,r]of Object.entries(e.effects))typeof r=="object"&&
745
736
  SUM(CASE WHEN action_id = '${fr}' THEN 1 ELSE 0 END) as cancelled_markers,
746
737
  MAX(CASE WHEN status = 'failed' THEN error_message END) as last_error
747
738
  FROM goap_execution_steps
748
- `,r=[];e&&(n+=" WHERE plan_id = ?",r.push(e)),n+=" GROUP BY execution_id, plan_id ORDER BY started_at DESC LIMIT ?",r.push(t);let i=this.db.prepare(n).all(...r);return Promise.all(i.map(async s=>{let a=await this.getExecutedSteps(s.execution_id),c=[...a].reverse().find(m=>m.worldStateAfter)?.worldStateAfter,l=this.getPlannedActionCount(s.plan_id),d=a[a.length-1],u;return s.cancelled_markers>0?u="cancelled":d?.status==="failed"?u="failed":s.steps_failed>0?u="completed":l!=null&&s.steps_recorded<l?u="cancelled":u="completed",{planId:s.plan_id,status:u,stepsCompleted:s.steps_completed,stepsFailed:s.steps_failed,totalDurationMs:s.total_duration_ms,finalWorldState:c,error:s.last_error??void 0,steps:a}}))}getPlannedActionCount(e){let t=this.db.prepare("SELECT action_sequence FROM goap_plans WHERE id = ?").get(e);if(!t)return null;let n=I(t.action_sequence);return Array.isArray(n)?n.length:null}async getExecutedSteps(e){return this.db.prepare("SELECT * FROM goap_execution_steps WHERE execution_id = ? AND action_id != ? ORDER BY step_order").all(e,fr).map(n=>({id:n.id,planId:n.plan_id,action:{id:n.action_id,name:"",agentType:"",preconditions:{},effects:{},cost:1,successRate:1,executionCount:0,category:"analysis"},stepOrder:n.step_order,status:n.status,durationMs:n.duration_ms??void 0,agentId:n.agent_id??void 0,error:n.error_message??void 0,retries:n.retries,startedAt:n.started_at?new Date(n.started_at):new Date(n.created_at),completedAt:n.started_at&&n.duration_ms!=null?new Date(new Date(n.started_at).getTime()+n.duration_ms):void 0,agentOutput:n.agent_output??void 0,worldStateBefore:n.world_state_before?I(n.world_state_before):void 0,worldStateAfter:n.world_state_after?I(n.world_state_after):void 0}))}async persistExecutionResult(e,t){let n=this.db.prepare(`
739
+ `,r=[];e&&(n+=" WHERE plan_id = ?",r.push(e)),n+=" GROUP BY execution_id, plan_id ORDER BY started_at DESC LIMIT ?",r.push(t);let i=this.db.prepare(n).all(...r);return Promise.all(i.map(async s=>{let a=await this.getExecutedSteps(s.execution_id),c=[...a].reverse().find(m=>m.worldStateAfter)?.worldStateAfter,l=this.getPlannedActionCount(s.plan_id),u=a[a.length-1],d;return s.cancelled_markers>0?d="cancelled":u?.status==="failed"?d="failed":s.steps_failed>0?d="completed":l!=null&&s.steps_recorded<l?d="cancelled":d="completed",{planId:s.plan_id,status:d,stepsCompleted:s.steps_completed,stepsFailed:s.steps_failed,totalDurationMs:s.total_duration_ms,finalWorldState:c,error:s.last_error??void 0,steps:a}}))}getPlannedActionCount(e){let t=this.db.prepare("SELECT action_sequence FROM goap_plans WHERE id = ?").get(e);if(!t)return null;let n=I(t.action_sequence);return Array.isArray(n)?n.length:null}async getExecutedSteps(e){return this.db.prepare("SELECT * FROM goap_execution_steps WHERE execution_id = ? AND action_id != ? ORDER BY step_order").all(e,fr).map(n=>({id:n.id,planId:n.plan_id,action:{id:n.action_id,name:"",agentType:"",preconditions:{},effects:{},cost:1,successRate:1,executionCount:0,category:"analysis"},stepOrder:n.step_order,status:n.status,durationMs:n.duration_ms??void 0,agentId:n.agent_id??void 0,error:n.error_message??void 0,retries:n.retries,startedAt:n.started_at?new Date(n.started_at):new Date(n.created_at),completedAt:n.started_at&&n.duration_ms!=null?new Date(new Date(n.started_at).getTime()+n.duration_ms):void 0,agentOutput:n.agent_output??void 0,worldStateBefore:n.world_state_before?I(n.world_state_before):void 0,worldStateAfter:n.world_state_after?I(n.world_state_after):void 0}))}async persistExecutionResult(e,t){let n=this.db.prepare(`
749
740
  INSERT INTO goap_execution_steps (
750
741
  id, plan_id, execution_id, action_id, step_order, status,
751
742
  retries, started_at, duration_ms, agent_id,
752
743
  agent_output, world_state_before, world_state_after, error_message
753
744
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
754
- `),r=this.db.transaction(()=>{t.steps.forEach((i,s)=>{n.run(i.id,t.planId,e,i.action.id,s,i.status,i.retries,i.startedAt.toISOString(),i.durationMs??null,i.agentId??null,i.agentOutput??null,i.worldStateBefore?JSON.stringify(i.worldStateBefore):null,i.worldStateAfter?JSON.stringify(i.worldStateAfter):null,i.error??null)}),t.status==="cancelled"&&n.run(`${e}-${nl}`,t.planId,e,fr,t.steps.length,nl,0,new Date().toISOString(),null,null,null,null,null,t.error??"Execution was cancelled")});await Et(this.db,()=>r());try{let i=new Date(Date.now()-t.totalDurationMs).toISOString(),s=new Date().toISOString();await Et(this.db,()=>this.db.prepare(`
745
+ `),r=this.db.transaction(()=>{t.steps.forEach((i,s)=>{n.run(i.id,t.planId,e,i.action.id,s,i.status,i.retries,i.startedAt.toISOString(),i.durationMs??null,i.agentId??null,i.agentOutput??null,i.worldStateBefore?JSON.stringify(i.worldStateBefore):null,i.worldStateAfter?JSON.stringify(i.worldStateAfter):null,i.error??null)}),t.status==="cancelled"&&n.run(`${e}-${el}`,t.planId,e,fr,t.steps.length,el,0,new Date().toISOString(),null,null,null,null,null,t.error??"Execution was cancelled")});await wt(this.db,()=>r());try{let i=new Date(Date.now()-t.totalDurationMs).toISOString(),s=new Date().toISOString();await wt(this.db,()=>this.db.prepare(`
755
746
  UPDATE goap_plans SET status = ?, executed_at = COALESCE(executed_at, ?), completed_at = ?
756
747
  WHERE id = ?
757
- `).run(t.status==="completed"?"completed":t.status==="cancelled"?"cancelled":"failed",i,s,t.planId))}catch(i){console.warn("[PlanExecutor] Failed to update goap_plans status (non-fatal):",i)}}async updateActionStats(e,t,n){try{"updateActionStats"in this.planner&&await this.planner.updateActionStats(e,t,n)}catch(r){console.warn("[PlanExecutor] Failed to update action stats:",r)}}meetsConditions(e,t){for(let[n,r]of Object.entries(t))if(!this.checkCondition(e,n,r))return!1;return!0}checkCondition(e,t,n){let r=this.getStateValue(e,t);return typeof n=="string"||typeof n=="number"||typeof n=="boolean"?r===n:!(typeof n=="object"&&n!==null&&("min"in n&&n.min!==void 0&&(typeof r!="number"||r<n.min)||"max"in n&&n.max!==void 0&&(typeof r!="number"||r>n.max)||"eq"in n&&n.eq!==void 0&&r!==n.eq))}applyEffects(e,t){let n=this.cloneState(e);for(let[r,i]of Object.entries(t))this.applyEffect(n,r,i);return n}applyEffect(e,t,n){if(typeof n=="string"||typeof n=="number"||typeof n=="boolean"){this.setStateValue(e,t,n);return}if(typeof n=="object"&&n!==null){let r=this.getStateValue(e,t);if("set"in n&&n.set!==void 0&&this.setStateValue(e,t,n.set),"delta"in n&&n.delta!==void 0&&typeof r=="number"){let i=Math.max(0,Math.min(100,r+n.delta));this.setStateValue(e,t,i)}}}getStateValue(e,t){let n=t.split("."),r=e;for(let i of n){if(r==null||typeof r!="object"||!Object.hasOwn(r,i))return;r=r[i]}return r}setStateValue(e,t,n){let r=t.split("."),i=new Set(["__proto__","constructor","prototype"]);for(let c of r)if(i.has(c)){console.warn(`[PlanExecutor] Blocked prototype pollution attempt: ${t}`);return}let s=e;for(let c=0;c<r.length-1;c++){let l=r[c];Object.hasOwn(s,l)||Object.defineProperty(s,l,{value:Object.create(null),writable:!0,enumerable:!0,configurable:!0});let d=Object.getOwnPropertyDescriptor(s,l);if(!d)return;s=d.value}let a=r[r.length-1];Object.defineProperty(s,a,{value:n,writable:!0,enumerable:!0,configurable:!0})}cloneState(e){return{coverage:{...e.coverage},quality:{...e.quality},fleet:{...e.fleet,availableAgents:[...e.fleet.availableAgents]},resources:{...e.resources},context:{...e.context},patterns:{...e.patterns}}}delay(e){return new Promise(t=>setTimeout(t,e))}async close(){this.currentExecution&&await this.cancel(),this.db&&(this.unifiedMemory?console.log("[PlanExecutor] Detached from unified storage (not closing shared connection)"):(this.db.close(),console.log("[PlanExecutor] Database closed"))),this.unifiedMemory=null,this.initialized=!1}},lt=class{successRate;executionDelay;constructor(e){this.successRate=e?.successRate??1,this.executionDelay=e?.executionDelay??100}async spawn(e,t){await new Promise(i=>setTimeout(i,this.executionDelay));let n=be()<this.successRate,r=`mock-agent-${Yi().slice(0,8)}`;return n?{agentId:r,output:`Successfully executed task for ${e}: ${t.slice(0,50)}...`,success:!0}:{agentId:r,output:"",success:!1,error:`Simulated failure for ${e}`}}};function Ji(o,e){let t=new lt({successRate:e?.successRate??1});return new ct(o,t,e?.dbPath,e?.config)}import*as hr from"fs";import*as ns from"path";Tt();var wp=["coverage.line","coverage.branch","coverage.function","coverage.target","coverage.measured","quality.testsPassing","quality.totalTests","quality.securityScore","quality.performanceScore","fleet.activeAgents","fleet.availableAgents","fleet.maxAgents","resources.timeRemaining","resources.memoryAvailable","resources.parallelSlots","context.environment","context.riskLevel","patterns.available","patterns.reusable"],il=ns.join("coverage","coverage-summary.json"),Rp=32*1024*1024;async function Pp(){try{let{getFleetState:o,isFleetInitialized:e}=await import("./core-handlers-JNAZPXE2.js");if(!e())return null;let{queen:t,kernel:n}=o();if(!t||!n)return null;let r=t.listAllAgents(),i=[...new Set(r.filter(s=>s.status==="running"||s.status==="idle").map(s=>s.type))].sort();return{activeAgents:r.filter(s=>s.status==="running").length,maxAgents:n.getConfig().maxConcurrentAgents,availableAgents:i}}catch{return null}}function Zi(o){return typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=100}function xp(o=ze()){let e=ns.join(o,il);try{let t=hr.statSync(e);if(!t.isFile()||t.size>Rp)return null;let n=JSON.parse(hr.readFileSync(e,"utf-8")),r=n.total?.lines?.pct,i=n.total?.branches?.pct,s=n.total?.functions?.pct;return!Zi(r)||!Zi(i)||!Zi(s)?null:{line:r,branch:i,function:s,source:il,measuredAt:t.mtime.toISOString()}}catch{return null}}function Ap(){let o=Qi;return{coverage:{...o.coverage},quality:{...o.quality},fleet:{...o.fleet,availableAgents:[...o.fleet.availableAgents]},resources:{...o.resources},context:{...o.context},patterns:{...o.patterns}}}async function qt(o={}){let e=Ap(),t={};for(let s of wp)t[s]="default";let n=await(o.readFleet??Pp)();n&&(e.fleet.activeAgents=n.activeAgents,e.fleet.maxAgents=n.maxAgents,e.fleet.availableAgents=[...n.availableAgents],t["fleet.activeAgents"]="live",t["fleet.maxAgents"]="live",t["fleet.availableAgents"]="live");let r=(o.readCoverage??(()=>xp()))(),i;if(r){e.coverage.line=r.line,e.coverage.branch=r.branch,e.coverage.function=r.function,e.coverage.measured=!0;for(let s of["coverage.line","coverage.branch","coverage.function","coverage.measured"])t[s]="measured";i={source:r.source,measuredAt:r.measuredAt}}return{state:e,provenance:t,fleetInitialized:n!==null,coverageReport:i}}var Le=o=>typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=100?null:"a number between 0 and 100",ut=o=>typeof o=="number"&&Number.isInteger(o)&&o>=0?null:"a non-negative integer",sl=o=>typeof o=="number"&&Number.isFinite(o)&&o>=0?null:"a non-negative number",kp=o=>typeof o=="boolean"?null:"a boolean",Mp=o=>Array.isArray(o)&&o.every(e=>typeof e=="string")?null:"an array of strings",al=(...o)=>e=>typeof e=="string"&&o.includes(e)?null:`one of ${o.join(", ")}`,Ip={"coverage.line":Le,"coverage.branch":Le,"coverage.function":Le,"coverage.target":Le,"coverage.measured":kp,"quality.testsPassing":Le,"quality.totalTests":ut,"quality.securityScore":Le,"quality.performanceScore":Le,"fleet.activeAgents":ut,"fleet.availableAgents":Mp,"fleet.maxAgents":ut,"resources.timeRemaining":sl,"resources.memoryAvailable":sl,"resources.parallelSlots":ut,"context.environment":al("development","staging","production"),"context.riskLevel":al("low","medium","high"),"patterns.available":ut,"patterns.reusable":ut},ts=["coverage","quality","fleet","resources","context","patterns"],es=null;function Dp(){if(!es){let o=new Set;for(let e of he()){for(let t of Object.keys(e.preconditions))o.add(t);for(let t of Object.keys(e.effects))o.add(t)}for(let e of ot)for(let t of Object.keys(e.conditions))o.add(t);es=o}return es}function ol(o,e=[]){if(typeof o!="object"||o===null||Array.isArray(o))return"currentState must be an object";let t=new Set([...Dp(),...e]);for(let[n,r]of Object.entries(o)){if(!ts.includes(n))return`currentState.${n} is not a world-state section (expected one of ${ts.join(", ")})`;if(typeof r!="object"||r===null||Array.isArray(r))return`currentState.${n} must be an object`;for(let[i,s]of Object.entries(r)){let a=`${n}.${i}`,c=Ip[a];if(c){let l=c(s);if(l)return`currentState.${a} must be ${l}, got ${JSON.stringify(s)}`;continue}if(!t.has(a))return`currentState.${a} is not a known world-state field`;if(typeof s!="boolean"&&typeof s!="string"&&!(typeof s=="number"&&Number.isFinite(s)))return`currentState.${a} must be a boolean, string or finite number, got ${JSON.stringify(s)}`}}return null}function cl(o,e){let t=o.state,n={...o.provenance};for(let r of ts){let i=e[r];if(!(typeof i!="object"||i===null||Array.isArray(i)))for(let[s,a]of Object.entries(i))s==="__proto__"||s==="constructor"||s==="prototype"||(t[r][s]=Array.isArray(a)?[...a]:a,n[`${r}.${s}`]="caller")}return{...o,provenance:n}}function yr(o){return Object.entries(o).filter(([,e])=>e==="default").map(([e])=>e).sort()}var ll=["maxCost","maxDurationMs","maxSteps","requiredAgentTypes","excludedActions"],$t=class extends A{constructor(t={}){super();this.worldStateSources=t}worldStateSources;planner=null;config={name:"qe/planning/goap_plan",description:'Find optimal action plan to achieve a QE goal using A* search. Supports named goals (e.g., "achieve-90-percent-coverage") or custom goal conditions.',domain:"coordination",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{goal:{type:"string",description:'Goal name (e.g., "achieve-90-percent-coverage") or custom goal conditions as JSON object'},currentState:{type:"object",description:"Current world state (auto-detected if not provided). Contains coverage, quality, fleet, resources, context, and patterns."},constraints:{type:"object",description:"Plan constraints",properties:{maxCost:{type:"number",description:"Maximum total cost allowed"},maxDurationMs:{type:"number",description:"Maximum total duration in milliseconds"},maxSteps:{type:"number",description:"Maximum number of steps (actions) in the plan; positive integer",minimum:1},requiredAgentTypes:{type:"array",description:"Only use actions that these agent types can execute",items:{type:"string",description:"Agent type"}},excludedActions:{type:"array",description:"Exclude these specific action IDs",items:{type:"string",description:"Action ID"}}}}},required:["goal"]}}async getPlanner(){return this.planner||(this.planner=Fe(),await this.planner.initialize()),this.planner}resetInstanceCache(){this.planner=null}async execute(t,n){try{let r=this.validateConstraints(t.constraints);if(r)return{success:!1,error:r};let i=await this.getPlanner(),s;if(typeof t.goal=="string"){let m=await i.getGoals(),p=m.find(g=>g.name===t.goal);if(!p){let g=m.map(f=>f.name).join(", ");return{success:!1,error:`Unknown goal: ${t.goal}. Available goals: ${g||"none (seed actions first)"}`}}s=p.conditions}else s=t.goal;if(t.currentState!==void 0){let m=ol(t.currentState,[...i.getReferencedStateKeys(),...Object.keys(s)]);if(m)return{success:!1,error:`Invalid currentState: ${m}`}}let a=t.currentState?cl(await qt(this.worldStateSources),t.currentState):await qt(this.worldStateSources),c=a.state,l=yr(a.provenance),d=t.constraints?{maxCost:t.constraints.maxCost,maxDurationMs:t.constraints.maxDurationMs,maxSteps:t.constraints.maxSteps,requiredAgentTypes:t.constraints.requiredAgentTypes,excludedActions:t.constraints.excludedActions}:void 0,u=await i.findPlan(c,s,d);return u?(l.length===0?this.markAsRealData():this.markAsEstimatedData(),{success:!0,data:{planId:u.id,goal:t.goal,actions:u.actions.map(m=>({name:m.name,agentType:m.agentType,cost:m.cost,category:m.category,description:m.description})),totalCost:u.totalCost,estimatedDurationMs:u.estimatedDurationMs,stepCount:u.actions.length,reusedFrom:u.reusedFrom,similarityScore:u.similarityScore,stateProvenance:a.provenance,defaultedFields:l}}):{success:!1,error:`No valid plan found for the given goal and constraints${d?.maxSteps!==void 0?` (maxSteps: ${d.maxSteps} \u2014 the goal may need more steps)`:""}. Try relaxing constraints or seeding more actions.`}}catch(r){return{success:!1,error:w(r)}}}validateConstraints(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return"constraints must be an object";let n=t,r=Object.keys(n).filter(s=>!ll.includes(s));if(r.length>0)return`Unknown constraint(s): ${r.join(", ")}. Supported constraints: ${ll.join(", ")}`;for(let s of["maxCost","maxDurationMs"]){let a=n[s];if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)||a<0))return`constraints.${s} must be a non-negative number, got ${String(a)}`}let i=Lt(n.maxSteps);if(i)return i;for(let s of["requiredAgentTypes","excludedActions"]){let a=n[s];if(a!==void 0&&(!Array.isArray(a)||!a.every(c=>typeof c=="string")))return`constraints.${s} must be an array of strings`}return null}};D();var Gt=class extends A{planner=null;executor=null;config={name:"qe/planning/goap_execute",description:"Execute a GOAP plan. Each action dispatches to a real domain API method when the action is marked implemented and a kernel is available (run fleet_init first); actions with no real implementation, or with no domain/kernel available, fail with a specific reason rather than reporting a fabricated success. Supports dry-run mode to preview the plan without executing anything.",domain:"coordination",schema:this.buildSchema(),timeout:3e5};buildSchema(){return{type:"object",properties:{planId:{type:"string",description:"ID of plan to execute (from goap_plan result)"},dryRun:{type:"boolean",description:"Simulate execution without spawning agents (default: false)",default:!1},stepByStep:{type:"boolean",description:"Execute one step at a time (default: false)",default:!1},maxRetries:{type:"number",description:"Max retries per failed step (default: 2)",default:2,minimum:0,maximum:5}},required:["planId"]}}async getPlanner(){return this.planner||(this.planner=Fe(),await this.planner.initialize()),this.planner}async getExecutor(e){if(!this.executor){let t=await this.getPlanner(),n=r=>e?.getDomainAPI(r);this.executor=new ct(t,new lt,void 0,{maxRetries:2,stepTimeoutMs:6e4,replanOnFailure:!0,parallelExecution:!1,recordWorldState:!0},n),await this.executor.initialize()}return this.executor}resetInstanceCache(){this.planner=null,this.executor=null}async execute(e,t){try{let r=await(await this.getPlanner()).getPlan(e.planId);if(!r)return{success:!1,error:`Plan not found: ${e.planId}. Create a plan first using goap_plan.`};if(e.dryRun)return this.markAsRealData(),{success:!0,data:{planId:r.id,mode:"dry-run",status:"completed",stepsCompleted:r.actions.length,stepsFailed:0,totalDurationMs:r.estimatedDurationMs,steps:r.actions.map(c=>({action:c.name,status:"would-execute",retries:0,durationMs:c.estimatedDurationMs}))}};let i=await yn(t),s=await this.getExecutor(i);if(s.isExecuting())return{success:!1,error:"Another plan is currently executing. Wait for completion or cancel it."};let a=await s.execute(r,r.initialState);return this.markAsRealData(),{success:a.status==="completed",data:{planId:a.planId,mode:"execution",status:a.status,stepsCompleted:a.stepsCompleted,stepsFailed:a.stepsFailed,totalDurationMs:a.totalDurationMs,steps:a.steps.map(c=>({action:c.action.name,status:c.status,retries:c.retries,durationMs:c.durationMs,error:c.error})),error:a.error},error:a.status!=="completed"?a.error:void 0}}catch(n){return{success:!1,error:w(n)}}}};D();var rs=["pending","executing","completed","failed","cancelled"],jt=class extends A{constructor(t={}){super();this.worldStateSources=t}worldStateSources;planner=null;executor=null;config={name:"qe/planning/goap_status",description:"Get GOAP system status: world state, available goals, actions, or plans. Use to understand current state and available planning options.",domain:"coordination",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{type:{type:"string",description:"What to get status of",enum:["world","goals","actions","plans","execution"]},filter:{type:"object",description:"Optional filters",properties:{category:{type:"string",description:"Filter actions by category (test, security, coverage, etc.)"},status:{type:"string",description:"Filter plans by status (pending, executing, completed, failed, cancelled)",enum:[...rs]},limit:{type:"number",description:"Maximum number of results (default: 20)",default:20,minimum:1,maximum:100}}}},required:["type"]}}async getPlanner(){return this.planner||(this.planner=Fe(),await this.planner.initialize()),this.planner}async getExecutor(){if(!this.executor){let t=await this.getPlanner();this.executor=Ji(t),await this.executor.initialize()}return this.executor}resetInstanceCache(){this.planner=null,this.executor=null}async execute(t,n){try{switch(t.type){case"world":return this.getWorldState();case"goals":return this.getGoals();case"actions":return this.getActions(t.filter?.category,t.filter?.limit);case"plans":return this.getPlans(t.filter?.status,t.filter?.limit);case"execution":return this.getExecutionStatus();default:return{success:!1,error:`Unknown status type: ${t.type}`}}}catch(r){return{success:!1,error:w(r)}}}async getWorldState(){let t=await qt(this.worldStateSources),{state:n,provenance:r}=t,i=l=>r[l]!=="default",s=(l,d)=>i(l)?d:null,a=yr(r);return["coverage.line","coverage.branch","coverage.function","quality.testsPassing","quality.securityScore","quality.performanceScore","fleet.activeAgents","fleet.maxAgents","resources.timeRemaining","resources.parallelSlots"].every(i)?this.markAsRealData():this.markAsEstimatedData(),{success:!0,data:{type:"world",data:{coverage:{line:s("coverage.line",n.coverage.line),branch:s("coverage.branch",n.coverage.branch),function:s("coverage.function",n.coverage.function),measured:n.coverage.measured,...t.coverageReport?{report:t.coverageReport}:{}},quality:{testsPassing:s("quality.testsPassing",n.quality.testsPassing),securityScore:s("quality.securityScore",n.quality.securityScore),performanceScore:s("quality.performanceScore",n.quality.performanceScore)},fleet:{initialized:t.fleetInitialized,activeAgents:n.fleet.activeAgents,maxAgents:s("fleet.maxAgents",n.fleet.maxAgents),availableAgents:[...n.fleet.availableAgents]},resources:{timeRemaining:s("resources.timeRemaining",n.resources.timeRemaining),parallelSlots:s("resources.parallelSlots",n.resources.parallelSlots)},provenance:r,defaultedFields:a}}}}async getGoals(){let n=await(await this.getPlanner()).getGoals();return this.markAsRealData(),{success:!0,data:{type:"goals",data:{goals:n.map(r=>({id:r.id,name:r.name,description:r.description,priority:r.priority,conditionCount:Object.keys(r.conditions).length})),count:n.length}}}}async getActions(t,n=50){let r=[],i=he(),s=t?i.filter(c=>c.category===t):i;r=s.slice(0,n).map((c,l)=>({id:`action-${l}`,name:c.name,category:c.category,agentType:c.agentType,cost:c.cost,successRate:c.successRate}));let a={};for(let c of i)a[c.category]=(a[c.category]||0)+1;return this.markAsRealData(),{success:!0,data:{type:"actions",data:{actions:r,count:s.length,byCategory:a}}}}async getPlans(t,n=20){if(t!==void 0&&!rs.includes(t))return{success:!1,error:`filter.status must be one of: ${rs.join(", ")}`};let r=await this.getPlanner(),[{plans:i,count:s,invalidPlanIds:a},c]=await Promise.all([r.listPlanSummaries(t,n),r.getPlanReuseStats()]);return this.markAsRealData(),{success:!0,data:{type:"plans",data:{plans:i,count:s,...a?{invalidPlanIds:a}:{},reuseStats:{totalPlans:c.totalPlans,reusedPlans:c.reusedPlans,reuseRate:c.reuseRate,avgSuccessRate:c.avgSuccessRate}}}}}async getExecutionStatus(){let n=(await this.getExecutor()).isExecuting();return this.markAsRealData(),{success:!0,data:{type:"execution",data:{isExecuting:n,message:n?"Plan execution in progress":"No active execution"}}}}};D();tn();pe();D();D();tn();var zt={HEALTH:"qe/mincut/health",ANALYZE:"qe/mincut/analyze",STRENGTHEN:"qe/mincut/strengthen"};function os(){return Ar()}function $p(){return kr()}var is=class extends A{config={name:zt.HEALTH,description:"Analyze swarm topology health using MinCut algorithms. Reports connectivity, weak points, and health trends.",domain:"coordination",schema:{type:"object",properties:{agents:{type:"array",description:"Agent vertices to add to the graph before analysis",items:{type:"object",description:"Agent vertex { id, domain, weight? }"}},edges:{type:"array",description:"Edges to add between agents",items:{type:"object",description:"Edge { source, target, weight? }"}},includeWeakVertices:{type:"boolean",description:"Include detailed weak vertex analysis",default:!0},includeHistory:{type:"boolean",description:"Include historical health data",default:!1}},additionalProperties:!0}};async execute(e,t){let n=os(),r=$p(),i=Se();if(e.agents)for(let l of e.agents)n.hasVertex(l.id)||n.addVertex({id:l.id,type:"agent",domain:l.domain,weight:l.weight??1,createdAt:new Date});if(e.edges)for(let l of e.edges)n.hasVertex(l.source)&&n.hasVertex(l.target)&&(n.hasEdge(l.source,l.target)||n.addEdge({source:l.source,target:l.target,weight:l.weight??1,type:"coordination",bidirectional:!0}));let s=r.checkHealth(),a=e.includeWeakVertices!==!1?i.findWeakVertices(n):[],c={health:{status:s.status,minCutValue:s.minCutValue,healthyThreshold:s.healthyThreshold,warningThreshold:s.warningThreshold,weakVertexCount:s.weakVertexCount,trend:s.trend},topology:{vertexCount:n.vertexCount,edgeCount:n.edgeCount,isConnected:n.isConnected()}};return e.includeWeakVertices!==!1&&a.length>0&&(c.weakVertices=a.map(l=>({id:l.vertexId,domain:l.vertex?.domain,weightedDegree:l.weightedDegree,riskScore:l.riskScore,reason:l.reason}))),e.includeHistory&&(c.history=s.history.map(l=>({timestamp:l.timestamp,value:l.value}))),this.markAsRealData(),{success:!0,data:c,metadata:this.createMetadata(t.startTime,t.requestId)}}},ss=class extends A{config={name:zt.ANALYZE,description:"Deep analysis of swarm topology using MinCut algorithms. Identifies weak points, suggests improvements.",domain:"coordination",schema:{type:"object",properties:{weaknessThreshold:{type:"number",description:"Threshold for weak vertex detection"},includePartitioningPoints:{type:"boolean",description:"Include analysis of potential partitioning points",default:!1}},additionalProperties:!0}};async execute(e,t){let n=os(),r=Se(),i=r.getMinCutValue(n),s=r.getMinDegreeVertex(n),a=r.findWeakVertices(n,e.weaknessThreshold),c=r.suggestEdgeAdditions(n,2),l={minCutValue:i,minDegreeVertex:s,weakVertices:a.map(d=>({id:d.vertexId,weightedDegree:d.weightedDegree,riskScore:d.riskScore,reason:d.reason,suggestions:d.suggestions.map(u=>({type:u.type,priority:u.priority,estimatedImprovement:u.estimatedImprovement}))})),suggestedEdges:c.map(d=>({source:d.source,target:d.target,weight:d.weight}))};return e.includePartitioningPoints&&(l.partitioningPoints=r.findPartitioningPoints(n)),this.markAsRealData(),{success:!0,data:l,metadata:this.createMetadata(t.startTime,t.requestId)}}},as=class extends A{config={name:zt.STRENGTHEN,description:"Strengthen swarm topology by adding edges between weak and strong vertices.",domain:"coordination",schema:{type:"object",properties:{targetImprovement:{type:"number",description:"Target improvement in MinCut value",default:1},targetVertices:{type:"array",description:"Specific vertices to strengthen",items:{type:"string",description:"Vertex ID"}},apply:{type:"boolean",description:"Apply changes (true) or simulate (false)",default:!1}},additionalProperties:!0}};async execute(e,t){let n=os(),r=Se(),i=r.getMinCutValue(n),s=e.targetImprovement??1,a=r.suggestEdgeAdditions(n,s),c=[];if(e.apply)for(let d of a)n.addEdge({source:d.source,target:d.target,weight:d.weight,type:"coordination",bidirectional:!0}),c.push({type:"add_edge",source:d.source,target:d.target,weight:d.weight});else for(let d of a)c.push({type:"add_edge",source:d.source,target:d.target,weight:d.weight});let l=r.getMinCutValue(n);return this.markAsRealData(),{success:!0,data:{beforeMinCut:i,afterMinCut:e.apply?l:i+s,improvement:e.apply?l-i:s,actionsApplied:c,applied:e.apply??!1},metadata:this.createMetadata(t.startTime,t.requestId)}}},ml=[new is,new ss,new as];D();var cs=null,vr=null;async function Ut(){return cs||vr||(vr=(async()=>{let o=xn({embedding:{model:"all-MiniLM-L6-v2",cacheSize:1e3,normalize:!0,hyperbolic:!1,curvature:-1},autoInitialize:!1});return await o.initialize(),cs=o,console.error("[EmbeddingTool] ONNX adapter initialized"),o})(),vr)}var dt=class extends A{config={name:"qe/embeddings/generate",description:"Generate a vector embedding for text using local ONNX model",domain:"learning-optimization",schema:{type:"object",properties:{text:{type:"string",description:"Text to generate embedding for",minLength:1,maxLength:1e4},hyperbolic:{type:"boolean",description:"Use hyperbolic space for hierarchical data",default:!1}},required:["text"]}};async execute(e,t){let n=performance.now();try{let r=await Ut(),i=await r.generateEmbedding(e.text);e.hyperbolic&&(i=r.toHyperbolic(i));let s=performance.now()-n;return this.markAsRealData(),{success:!0,data:{embedding:Array.from(i.vector),dimension:i.dimensions,isHyperbolic:i.isHyperbolic,latencyMs:s,model:i.model}}}catch(r){return{success:!1,error:`Embedding generation failed: ${w(r)}`}}}},mt=class extends A{config={name:"qe/embeddings/compare",description:"Compare semantic similarity between two texts",domain:"learning-optimization",schema:{type:"object",properties:{text1:{type:"string",description:"First text to compare",minLength:1},text2:{type:"string",description:"Second text to compare",minLength:1},metric:{type:"string",description:"Similarity metric",enum:["cosine","euclidean","poincare"],default:"cosine"}},required:["text1","text2"]}};async execute(e,t){let n=performance.now();try{let r=await Ut(),i=e.metric||"cosine",s=i==="cosine"?"cosine":i==="euclidean"?"euclidean":"poincare",a=await r.compareSimilarity(e.text1,e.text2,s),c=performance.now()-n;return this.markAsRealData(),{success:!0,data:{similarity:a,metric:i,isSimilar:a>.7,latencyMs:c}}}catch(r){return{success:!1,error:`Similarity comparison failed: ${w(r)}`}}}},pt=class extends A{config={name:"qe/embeddings/search",description:"Search for semantically similar texts using vector search",domain:"learning-optimization",schema:{type:"object",properties:{query:{type:"string",description:"Query text to search for",minLength:1},namespace:{type:"string",description:"Namespace to search in",default:"default"},topK:{type:"number",description:"Number of results to return",minimum:1,maximum:100,default:10},threshold:{type:"number",description:"Minimum similarity threshold (0-1)",minimum:0,maximum:1,default:.5}},required:["query"]}};async execute(e,t){let n=performance.now();try{let i=await(await Ut()).searchByText(e.query,{metric:"cosine",topK:e.topK??10,threshold:e.threshold??.5,namespace:e.namespace}),s=performance.now()-n;return this.markAsRealData(),{success:!0,data:{results:i.map(a=>({text:a.text,score:a.score,metadata:a.metadata})),totalFound:i.length,latencyMs:s}}}catch(r){return{success:!1,error:`Search failed: ${w(r)}`}}}},gt=class extends A{config={name:"qe/embeddings/store",description:"Store text with its embedding for later retrieval",domain:"learning-optimization",schema:{type:"object",properties:{text:{type:"string",description:"Text to store",minLength:1},id:{type:"string",description:"Optional ID for the stored embedding"},namespace:{type:"string",description:"Namespace for organization",default:"default"},metadata:{type:"object",description:"Additional metadata to store"}},required:["text"]}};async execute(e,t){let n=performance.now();try{let r=await Ut(),i=e.namespace||"default",s=await r.generateAndStore(e.text,{id:e.id,namespace:i,customData:e.metadata}),a=performance.now()-n;return this.markAsRealData(),{success:!0,data:{id:s.id,namespace:s.namespace||i,latencyMs:a}}}catch(r){return{success:!1,error:`Store failed: ${w(r)}`}}}},ft=class extends A{config={name:"qe/embeddings/stats",description:"Get ONNX embedding system statistics",domain:"learning-optimization",schema:{type:"object",properties:{}}};async execute(e,t){try{let n=await Ut(),r=n.getStats(),i=await n.getHealth(),s=r.cacheHits+r.cacheMisses,a=s>0?r.cacheHits/s:0;return this.markAsRealData(),{success:!0,data:{totalGenerated:r.totalGenerated,vectorsStored:r.vectorsStored,cache:{hits:r.cacheHits,misses:r.cacheMisses,hitRate:a},model:{name:r.currentModel,dimension:r.currentModel==="all-MiniLM-L6-v2"?384:768},healthy:i.available}}}catch(n){return{success:!1,error:`Stats failed: ${w(n)}`}}}},Gp=new dt,jp=new mt,zp=new pt,Up=new gt,Bp=new ft;D();var Hp={type:"object",properties:{nodes:{type:"array",description:"Array of nodes to check for coherence. Each node must have an id and embedding vector.",items:{type:"object",description:"Node with id, embedding vector, optional weight and metadata"}},energyThreshold:{type:"number",description:"Custom energy threshold for contradiction detection (default: 0.4)",minimum:0,maximum:1}},required:["nodes"]},Bt=class extends A{config={name:"qe/coherence/check",description:"Check mathematical coherence of beliefs/facts using Prime Radiant sheaf cohomology. Detects contradictions and computes coherence energy for multi-agent coordination.",domain:"learning-optimization",schema:Hp,streaming:!1,timeout:3e4};coherenceService=null;async getService(){return this.coherenceService||(this.coherenceService=await Te(Ee)),this.coherenceService}resetInstanceCache(){this.coherenceService&&(this.coherenceService.dispose(),this.coherenceService=null)}async execute(e,t){let n=Date.now(),{nodes:r,energyThreshold:i=.4}=e;if(!r||r.length===0)return{success:!1,error:"At least one node is required for coherence check"};for(let s of r)if(!s.embedding||!Array.isArray(s.embedding))return{success:!1,error:`Node ${s.id} has invalid embedding - must be an array of numbers`};try{let s=await this.getService(),a=r.map(m=>({id:m.id,embedding:m.embedding,weight:m.weight??1,metadata:m.metadata})),c=await s.checkCoherence(a),l=[...c.recommendations,...this.generateAdditionalRecommendations(c,i)],d=c.contradictions.map(m=>({nodeIds:m.nodeIds,severity:String(m.severity),description:m.description||`Contradiction between nodes ${m.nodeIds[0]} and ${m.nodeIds[1]}`})),u=Date.now()-n;return this.markAsRealData(),{success:!0,data:{isCoherent:c.isCoherent,energy:c.energy,lane:c.lane,contradictions:d,recommendations:l,nodeCount:r.length,executionTimeMs:u,usedFallback:c.usedFallback}}}catch(s){return s instanceof Error&&s.message.includes("WASM")?(this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{isCoherent:!0,energy:.1,lane:"reflex",contradictions:[],recommendations:["WASM module unavailable - coherence check running in fallback mode","Install prime-radiant-advanced-wasm for full coherence verification"],nodeCount:r.length,executionTimeMs:Date.now()-n,usedFallback:!0}}):{success:!1,error:w(s)}}}generateAdditionalRecommendations(e,t){let n=[];switch(e.energy>t&&n.push(`High coherence energy (${e.energy.toFixed(3)}) detected - review contradicting beliefs`),e.lane){case"reflex":n.push("Low energy - safe for immediate execution");break;case"retrieval":n.push("Moderate energy - consider fetching additional context");break;case"heavy":n.push("High energy - deep analysis recommended");break;case"human":n.push("Critical energy - escalate to Queen coordinator");break}return n}};var Vp=["rename","framework-transfer","reordered-steps","distractor-terminology","cross-domain-transfer"],Fx=[["async-race","observe completion before assertion","await the operation","increase the timeout","completion probe","unit","vitest"],["stale-cache","invalidate on every state mutation","invalidate the cache","retry the read","freshness assertion","integration","redis"],["transaction-leak","rollback isolates each test","rollback the transaction","truncate a shared table","row-count check","database","postgres"],["clock-skew","compare times in one clock domain","inject a monotonic clock","widen the time window","clock boundary check","unit","node"],["event-loss","subscribe before publishing","register the listener first","publish twice","delivery assertion","events","eventemitter"],["resource-leak","release resources on every exit","close in a finally block","raise the pool limit","handle-count check","integration","playwright"],["eventual-consistency","poll the observable state","poll with a bounded deadline","sleep for a fixed delay","state convergence","distributed","kubernetes"],["identity-confusion","compare canonical identities","normalize the identifier","use display names","identity equality","security","oauth"],["partial-write","publish only complete state","commit through an atomic swap","ignore missing fields","atomicity check","filesystem","node"],["order-dependence","tests start from isolated state","reset state in setup","force alphabetical order","shuffle repeat","unit","jest"],["schema-drift","validate at the boundary","reject the incompatible schema","cast the payload","schema validator","api","zod"],["backpressure-loss","producer respects consumer capacity","await the drain signal","increase buffer memory","loss counter","performance","streams"],["retry-duplication","retries preserve idempotency","attach an idempotency key","disable all retries","duplicate detector","api","fetch"],["permission-bypass","authorization precedes mutation","check permission before write","hide the user interface","denial assertion","security","express"],["encoding-mismatch","encode and decode with one charset","set UTF-8 explicitly","strip non-ASCII text","round-trip equality","api","json"],["pagination-gap","cursor advances from the last item","use the returned cursor","increase page size","set equality","api","graphql"],["cancellation-leak","cancellation propagates to children","forward the abort signal","wait for natural completion","abort observation","integration","abortcontroller"],["floating-point-boundary","compare numeric results by tolerance","use an error bound","round every input","relative-error check","unit","vitest"],["locale-dependence","format under an explicit locale","pass the locale explicitly","update the snapshot locally","multi-locale check","ui","intl"],["lock-starvation","lock acquisition remains fair","queue lock waiters","raise retry count","bounded-wait check","concurrency","mutex"]].map(([o,e,t,n,r,i,s])=>({mechanism:o,invariant:e,action:t,wrongAction:n,oracle:r,domain:i,framework:s}));var Qp=Object.freeze([...Vp]);hs();D();var Yx=Jt.create("qe-unified-memory");var Kp={"test-suites":{dimensions:we.DIMENSIONS,M:8,efConstruction:100,efSearch:50,metric:"cosine",namespace:"test-suites-hnsw",maxElements:1e5},coverage:{dimensions:we.DIMENSIONS,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},defects:{dimensions:we.DIMENSIONS,M:32,efConstruction:400,efSearch:200,metric:"cosine",namespace:"defects-hnsw",maxElements:1e5},quality:{dimensions:we.DIMENSIONS,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"quality-hnsw",maxElements:1e5},learning:{dimensions:we.DIMENSIONS,M:24,efConstruction:300,efSearch:150,metric:"cosine",namespace:"learning-hnsw",maxElements:1e5},coordination:{dimensions:we.DIMENSIONS,M:8,efConstruction:100,efSearch:50,metric:"cosine",namespace:"coordination-hnsw",maxElements:5e4}},Xp={enableHNSW:{"test-suites":!0,coverage:!0,defects:!0,quality:!0,learning:!0,coordination:!0},defaultNamespace:"qe-unified",enableCrossDomainSearch:!0,embeddingDimension:we.DIMENSIONS};hs();D();Cs();import{randomUUID as Yp}from"crypto";var ls=Jt.create("MemoryAuditor"),us={batchSize:50,energyThreshold:.4,hotspotThreshold:.6,maxRecommendations:10},br=class{constructor(e,t,n=us){this.coherenceService=e;this.eventBus=t;this.config=n}coherenceService;eventBus;config;isAuditing=!1;async auditPatterns(e){let t=Date.now();await this.emitEvent("memory:audit_started",{totalPatterns:e.length,timestamp:new Date});try{let n=this.groupByDomain(e),r=[],i=0,s=0;for(let[p,g]of Object.entries(n)){if(g.length<2)continue;let f=this.patternsToNodes(g),h=await this.coherenceService.checkCoherence(f);s+=h.energy,i+=h.contradictions.length,h.energy>this.config.hotspotThreshold&&r.push({domain:p,patternIds:g.map(v=>v.id),energy:h.energy,description:this.describeHotspot(h,p)})}let a=Object.keys(n).length,c=a>0?s/a:0,l=await this.identifyHotspots(e),d=await this.generateRecommendations(l,e),u=Date.now()-t,m={totalPatterns:e.length,scannedPatterns:e.length,contradictionCount:i,globalEnergy:c,hotspots:l,recommendations:d,duration:u,timestamp:new Date};return await this.emitEvent("memory:audit_completed",{result:m,timestamp:new Date}),m}catch(n){try{await this.emitEvent("memory:audit_failed",{error:w(n),timestamp:new Date})}catch(r){ls.warn("Failed to emit audit_failed event",{error:w(r)})}throw n}}async identifyHotspots(e){let t=[],n=this.groupByDomain(e);for(let[r,i]of Object.entries(n)){if(i.length<2)continue;let s=this.patternsToNodes(i),a=await this.coherenceService.checkCoherence(s);a.energy>this.config.hotspotThreshold&&t.push({domain:r,patternIds:i.map(c=>c.id),energy:a.energy,description:this.describeHotspot(a,r)})}return t}async generateRecommendations(e,t){let n=[],r=new Map(t.map(i=>[i.id,i]));for(let i of e){let s=i.patternIds.map(d=>r.get(d)).filter(d=>d!==void 0),a=this.findDuplicates(s);a.length>0&&n.push({type:"merge",patternIds:a,reason:`Detected ${a.length} similar patterns in ${i.domain} domain`,priority:"high"});let c=this.findOutdated(s);c.length>0&&n.push({type:"remove",patternIds:c,reason:`Found ${c.length} outdated patterns with low usage/success`,priority:"medium"}),i.energy>.7&&n.push({type:"review",patternIds:i.patternIds,reason:`Critical coherence energy (${i.energy.toFixed(2)}) in ${i.domain}`,priority:"high"});let l=this.findBroadPatterns(s);l.length>0&&n.push({type:"split",patternIds:l,reason:`Found ${l.length} overly generic patterns that should be specialized`,priority:"low"})}return n.sort((i,s)=>this.priorityValue(s.priority)-this.priorityValue(i.priority)).slice(0,this.config.maxRecommendations)}async runBackgroundAudit(e){if(this.isAuditing){ls.warn("Audit already in progress, skipping");return}this.isAuditing=!0;try{await this.emitEvent("memory:audit_progress",{status:"fetching_patterns",timestamp:new Date});let t=await e();await this.emitEvent("memory:audit_progress",{status:"analyzing_coherence",totalPatterns:t.length,timestamp:new Date});let n=await this.auditPatterns(t);await this.emitEvent("memory:audit_progress",{status:"completed",result:n,timestamp:new Date})}catch(t){await this.emitEvent("memory:audit_progress",{status:"failed",error:w(t),timestamp:new Date})}finally{this.isAuditing=!1}}groupByDomain(e){let t=bs();for(let n of e){let r=n.qeDomain;t[r]||(t[r]=[]),t[r].push(n)}return t}patternsToNodes(e){return e.map(t=>({id:t.id,embedding:t.embedding||this.createFallbackEmbedding(t),weight:t.qualityScore,metadata:{name:t.name,description:t.description,domain:t.qeDomain,confidence:t.confidence,usageCount:t.usageCount,successRate:t.successRate}}))}createFallbackEmbedding(e){let t=`${e.name} ${e.description}`,n=[];for(let r=0;r<64;r++){let i=t.charCodeAt(r%t.length);n.push(i/255*2-1)}return n}describeHotspot(e,t){let n=e.energy.toFixed(2),r=e.contradictions.length;return r>0?`${t} has ${r} contradiction(s) with energy ${n}`:`${t} has high coherence energy (${n}) indicating potential inconsistencies`}findDuplicates(e){let t=[],n=new Map;for(let r of e){let i=this.normalizeText(`${r.name} ${r.description}`);n.has(i)||n.set(i,[]),n.get(i).push(r.id)}for(let[r,i]of n)i.length>1&&t.push(...i.slice(1));return t}findOutdated(e){return e.filter(t=>t.usageCount<5&&t.successRate<.5).map(t=>t.id)}findBroadPatterns(e){return e.filter(t=>{let n=/generic|general|common|basic/i.test(t.name),r=t.context?.tags,i=!r||r.length<2;return n||i}).map(t=>t.id)}normalizeText(e){return e.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim()}priorityValue(e){switch(e){case"high":return 3;case"medium":return 2;case"low":return 1;default:return 0}}async emitEvent(e,t){if(this.eventBus)try{await this.eventBus.publish({id:`memory-audit-${Date.now()}-${Yp().split("-")[0]}`,type:e,source:"learning-optimization",timestamp:new Date,payload:t})}catch(n){ls.warn("Failed to emit event",{eventType:e,error:w(n)})}}};function ds(o,e,t){return new br(o,e,{...us,...t})}D();var Jp={type:"object",properties:{namespace:{type:"string",description:"Namespace to audit (default: qe-patterns)",default:"qe-patterns"},maxPatterns:{type:"number",description:"Maximum patterns to scan (default: 1000)",default:1e3,minimum:1,maximum:1e4},energyThreshold:{type:"number",description:"Energy threshold for flagging issues (default: 0.4)",default:.4,minimum:0,maximum:1},includeDetails:{type:"boolean",description:"Include detailed pattern information in results",default:!1}},required:[]},Ht=class extends A{config={name:"qe/coherence/audit",description:"Audit QE memory for contradictions and coherence issues. Scans patterns, detects hotspots, and generates remediation recommendations.",domain:"learning-optimization",schema:Jp,streaming:!1,timeout:6e4};coherenceService=null;auditor=null;async getService(){return this.coherenceService||(this.coherenceService=await Te(Ee)),this.coherenceService}resetInstanceCache(){this.coherenceService&&(this.coherenceService.dispose(),this.coherenceService=null),this.auditor=null}async execute(e,t){let{namespace:n="qe-patterns",maxPatterns:r=1e3,energyThreshold:i=.4}=e;try{let s=await this.getService();this.auditor||(this.auditor=ds(s,void 0,{energyThreshold:i,hotspotThreshold:i+.2,maxRecommendations:10}));let a=await q(),c=xr(a,{namespace:n,embeddingDimension:384});await c.initialize();let l=await c.search("",{limit:r,useVectorSearch:!1}),d=l.success?l.value.map(p=>p.pattern):[],u;d.length>0?u=await this.auditor.auditPatterns(d):u={totalPatterns:0,scannedPatterns:0,contradictionCount:0,globalEnergy:0,hotspots:[],recommendations:[],duration:0,timestamp:new Date};let m=this.calculateHealthScore(u);return this.markAsRealData(),{success:!0,data:{totalPatterns:u.totalPatterns,scannedPatterns:u.scannedPatterns,contradictionCount:u.contradictionCount,globalEnergy:u.globalEnergy,hotspots:u.hotspots.map(p=>({domain:p.domain,patternIds:p.patternIds,energy:p.energy,description:p.description})),recommendations:u.recommendations.map(p=>({type:p.type,patternIds:p.patternIds,reason:p.reason,priority:p.priority})),durationMs:u.duration,timestamp:u.timestamp.toISOString(),healthScore:m}}}catch(s){return s instanceof Error&&s.message.includes("WASM")?(this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{totalPatterns:0,scannedPatterns:0,contradictionCount:0,globalEnergy:0,hotspots:[],recommendations:[{type:"review",patternIds:[],reason:"WASM module unavailable - install prime-radiant-advanced-wasm for full audit",priority:"medium"}],durationMs:0,timestamp:new Date().toISOString(),healthScore:100}}):{success:!1,error:w(s)}}}calculateHealthScore(e){let t=100;t-=Math.min(30,e.contradictionCount*5),t-=Math.min(30,e.globalEnergy*50),t-=Math.min(20,e.hotspots.length*5);let n=e.recommendations.filter(r=>r.priority==="high").length;return t-=Math.min(20,n*5),Math.max(0,Math.round(t))}};D();function Zp(o){let e="Each vote must be { agentId: string, verdict: string | number | boolean, confidence: number 0-1 }.";for(let t=0;t<o.length;t++){let n=o[t];if(typeof n!="object"||n===null||Array.isArray(n))return`votes[${t}] must be an object. ${e}`;let{agentId:r,verdict:i,confidence:s}=n;if(typeof r!="string"||r.trim()==="")return`votes[${t}].agentId must be a non-empty string. ${e}`;let a=typeof i;if(a!=="string"&&a!=="number"&&a!=="boolean")return`votes[${t}].verdict is required (string, number, or boolean), got ${i===null?"null":a}. ${e}`;if(typeof s!="number"||!Number.isFinite(s)||s<0||s>1)return`votes[${t}].confidence must be a number between 0 and 1, got ${JSON.stringify(s)??"undefined"}. ${e}`}return null}var eg={type:"object",properties:{votes:{type:"array",description:"Array of agent votes to verify for consensus (at least 2). Each vote is an object { agentId: string, verdict: string | number | boolean, confidence: number 0-1, agentType?: string, reasoning?: string }.",items:{type:"object",description:"One agent vote",properties:{agentId:{type:"string",description:"Agent identifier",minLength:1},agentType:{type:"string",description:"Agent type (default: worker)"},confidence:{type:"number",description:"Confidence in the verdict",minimum:0,maximum:1},reasoning:{type:"string",description:"Optional reasoning text"}},required:["agentId","confidence"]}},confidenceThreshold:{type:"number",description:"Minimum confidence threshold (0-1, default: 0.5)",default:.5,minimum:0,maximum:1}},required:["votes"]},Vt=class extends A{config={name:"qe/coherence/consensus",description:"Verify multi-agent consensus mathematically using spectral analysis. Detects false consensus where agents appear to agree but have divergent beliefs.",domain:"learning-optimization",schema:eg,streaming:!1,timeout:3e4};coherenceService=null;async getService(){return this.coherenceService||(this.coherenceService=await Te(Ee)),this.coherenceService}resetInstanceCache(){this.coherenceService&&(this.coherenceService.dispose(),this.coherenceService=null)}async execute(e,t){let n=Date.now(),{votes:r,confidenceThreshold:i=.5}=e;if(!r||r.length===0)return{success:!1,error:"At least one vote is required for consensus verification"};if(r.length<2)return{success:!1,error:"At least two votes are required to verify consensus"};let s=Zp(r);if(s)return{success:!1,error:s};try{let a=await this.getService(),c=r.map(p=>({agentId:p.agentId,agentType:p.agentType||"worker",verdict:p.verdict,confidence:p.confidence,reasoning:p.reasoning,timestamp:new Date})),l=await a.verifyConsensus(c),d=l.recommendation,u=r.reduce((p,g)=>p+g.confidence,0)/r.length;u<i&&(d=`Low average confidence (${(u*100).toFixed(1)}%) - consider gathering more evidence. `+d);let m=Date.now()-n;return this.markAsRealData(),{success:!0,data:{isValid:l.isValid,isFalseConsensus:l.isFalseConsensus,confidence:l.confidence,fiedlerValue:l.fiedlerValue,collapseRisk:l.collapseRisk,recommendation:d,usedFallback:l.usedFallback,executionTimeMs:m}}}catch(a){if(a instanceof Error&&a.message.includes("WASM")){let c=this.simpleMajorityAnalysis(r);return this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{...c,recommendation:`Running in fallback mode (simple analysis): ${Ms(ks(r))} across ${r.length} votes. Install prime-radiant-advanced-wasm for spectral consensus analysis.`,usedFallback:!0,executionTimeMs:Date.now()-n}}}return{success:!1,error:w(a)}}}simpleMajorityAnalysis(e){let t=new Map;for(let s of e){let a=String(s.verdict);t.set(a,(t.get(a)||0)+1)}let n=0;for(let s of t.values())s>n&&(n=s);let r=n/e.length,i=e.reduce((s,a)=>s+a.confidence,0)/e.length;return{isValid:r>=.5&&i>=.5,isFalseConsensus:!1,confidence:i,fiedlerValue:0,collapseRisk:1-r}}};D();var tg={type:"object",properties:{swarmState:{type:"object",description:"Current state of the swarm including agents and task info"},riskThreshold:{type:"number",description:"Risk threshold for warning (0-1, default: 0.5)",default:.5,minimum:0,maximum:1}},required:["swarmState"]},Qt=class extends A{config={name:"qe/coherence/collapse",description:"Predict swarm collapse risk using spectral analysis. Identifies vulnerable vertices and provides mitigation recommendations.",domain:"learning-optimization",schema:tg,streaming:!1,timeout:3e4};coherenceService=null;async getService(){return this.coherenceService||(this.coherenceService=await Te(Ee)),this.coherenceService}resetInstanceCache(){this.coherenceService&&(this.coherenceService.dispose(),this.coherenceService=null)}async execute(e,t){let n=Date.now(),{swarmState:r,riskThreshold:i=.5}=e;if(!r)return{success:!1,error:"swarmState is required"};if(!r.agents||r.agents.length<1)return{success:!1,error:"At least one agent is required in swarmState"};try{let s=await this.getService(),a={agents:r.agents.map(g=>({agentId:g.agentId,agentType:g.agentType||"worker",health:Number.isFinite(g.health)?g.health:1,beliefs:[],lastActivity:new Date,errorCount:g.errorCount??0,successRate:Number.isFinite(g.successRate)?g.successRate:1})),activeTasks:Number.isFinite(r.activeTasks)?r.activeTasks:0,pendingTasks:Number.isFinite(r.pendingTasks)?r.pendingTasks:0,errorRate:Number.isFinite(r.errorRate)?r.errorRate:0,utilization:Number.isFinite(r.utilization)?r.utilization:0,timestamp:new Date},c=await s.predictCollapse(a),l=Number.isFinite(c.risk)?c.risk:0,d=this.categorizeRisk(l),u=[...c.recommendations,...this.generateAdditionalRecommendations(c,r)],m=Date.now()-n;this.markAsRealData();let p=d==="high"||d==="critical"||d==="medium"&&l>=i;return{success:!0,data:{risk:l,isAtRisk:p,riskLevel:d,fiedlerValue:c.fiedlerValue,collapseImminent:c.collapseImminent,weakVertices:c.weakVertices,recommendations:u,executionTimeMs:m,usedFallback:c.usedFallback}}}catch(s){if(s instanceof Error&&s.message.includes("WASM")){let a=this.heuristicAnalysis(r,i);return this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{...a,recommendations:["Running in fallback mode (heuristic analysis)","Install prime-radiant-advanced-wasm for spectral collapse prediction",...a.recommendations],usedFallback:!0,executionTimeMs:Date.now()-n}}}return{success:!1,error:w(s)}}}categorizeRisk(e){return!Number.isFinite(e)||e<.25?"low":e<.5?"medium":e<.75?"high":"critical"}generateAdditionalRecommendations(e,t){let n=[];t.errorRate>.1&&n.push(`High system error rate (${(t.errorRate*100).toFixed(1)}%) - investigate root causes`),t.utilization>.85&&n.push(`High resource utilization (${(t.utilization*100).toFixed(1)}%) - consider scaling`),t.pendingTasks>t.activeTasks*2&&n.push(`Large task backlog (${t.pendingTasks} pending) - may need more agents`);let r=t.agents.filter(i=>i.health<.5);return r.length>0&&n.push(`${r.length} agent(s) with low health - consider replacement`),e.risk>=.75&&n.unshift("\u26A0\uFE0F CRITICAL: Immediate action required to prevent collapse"),n}heuristicAnalysis(e,t){let n=0,r=[],i=[],s=Number.isFinite(e.errorRate)?e.errorRate:0,a=Number.isFinite(e.utilization)?e.utilization:0,c=Number.isFinite(e.pendingTasks)?e.pendingTasks:0,l=Number.isFinite(e.activeTasks)?e.activeTasks:0,d=e.agents.map(f=>Number.isFinite(f.health)?f.health:1),u=d.length>0?d.reduce((f,h)=>f+h,0)/d.length:1;n+=(1-u)*.3,n+=Math.min(.25,s*2.5),a>.7&&(n+=(a-.7)*.5);let m=c/Math.max(1,l);m>1&&(n+=Math.min(.2,(m-1)*.1)),e.agents.forEach((f,h)=>{(d[h]<.5||(f.errorCount??0)>5)&&i.push(f.agentId)}),n=Math.min(1,n),n>=t&&(r.push("Consider reducing task load"),r.push("Monitor agent health closely")),i.length>0&&r.push(`Reinforce weak agents: ${i.join(", ")}`),n<.25&&r.push("Swarm appears stable - continue normal operations");let p=this.categorizeRisk(n),g=p==="high"||p==="critical"||p==="medium"&&n>=t;return{risk:n,isAtRisk:g,riskLevel:p,fiedlerValue:0,collapseImminent:n>=.75,weakVertices:i,recommendations:r}}};var pl=[new Bt,new Ht,new Vt,new Qt],gl={COHERENCE_CHECK:"qe/coherence/check",COHERENCE_AUDIT:"qe/coherence/audit",COHERENCE_CONSENSUS:"qe/coherence/consensus",COHERENCE_COLLAPSE:"qe/coherence/collapse"};var Wt=(S=>(S.PROBLEM_UNDERSTANDING="H1.1-problem-understanding",S.RULE_OF_THREE="H1.2-rule-of-three",S.PROBLEM_COMPLEXITY="H1.3-problem-complexity",S.USER_NEEDS_IDENTIFICATION="H2.1-user-needs-identification",S.USER_NEEDS_SUITABILITY="H2.2-user-needs-suitability",S.USER_NEEDS_VALIDATION="H2.3-user-needs-validation",S.BUSINESS_NEEDS_IDENTIFICATION="H3.1-business-needs-identification",S.USER_VS_BUSINESS_BALANCE="H3.2-user-vs-business-balance",S.KPI_IMPACT_ANALYSIS="H3.3-kpi-impact-analysis",S.ORACLE_PROBLEM_DETECTION="H4.1-oracle-problem-detection",S.WHAT_MUST_NOT_CHANGE="H4.2-what-must-not-change",S.SUPPORTING_DATA_ANALYSIS="H4.3-supporting-data-analysis",S.GUI_FLOW_IMPACT="H5.1-gui-flow-impact",S.USER_FEELINGS_IMPACT="H5.2-user-feelings-impact",S.CROSS_FUNCTIONAL_IMPACT="H5.3-cross-functional-impact",S.DATA_DEPENDENT_IMPACT="H5.4-data-dependent-impact",S.COMPETITIVE_ANALYSIS="H6.1-competitive-analysis",S.DOMAIN_INSPIRATION="H6.2-domain-inspiration",S.INNOVATIVE_SOLUTIONS="H6.3-innovative-solutions",S.EXACTNESS_AND_CLARITY="H7.1-exactness-and-clarity",S.INTUITIVE_DESIGN="H7.2-intuitive-design",S.COUNTER_INTUITIVE_DESIGN="H7.3-counter-intuitive-design",S.CONSISTENCY_ANALYSIS="H7.4-consistency-analysis",S))(Wt||{});var Cr=class{enabledHeuristics;minConfidence;constructor(e={}){this.enabledHeuristics=e.enabledHeuristics||Object.values(Wt),this.minConfidence=e.minConfidence||.7}async applyAll(e,t,n,r){let i=[];for(let s of this.enabledHeuristics){let a=await this.apply(s,e,t,n,r);i.push(a)}return i}async apply(e,t,n,r,i){let s=this.getHeuristicCategory(e),a=[],c=[],l=[],d=75;switch(e){case"H7.4-consistency-analysis":t.domMetrics?.semanticStructure?.hasHeader&&t.domMetrics?.semanticStructure?.hasFooter?(d=85,a.push("Consistent page structure with header and footer")):(d=60,l.push("Add consistent header/footer structure"));break;case"H7.2-intuitive-design":{let u=t.domMetrics?.semanticStructure?.hasNav,m=t.accessibility?.focusableElementsCount||0;u&&m>10?(d=82,a.push("Intuitive navigation and interaction design")):(d=55,c.push({description:"Navigation or interaction patterns unclear",severity:"medium"}));break}case"H7.1-exactness-and-clarity":{d=70;let u=t.domMetrics?.semanticStructure,m=[u?.hasHeader,u?.hasMain,u?.hasNav,u?.hasFooter].filter(Boolean).length;d=50+m*10,m>=3?a.push("Strong visual hierarchy with semantic HTML elements"):m>=2?(a.push("Moderate visual hierarchy - some semantic elements present"),l.push("Add more semantic HTML5 elements for clarity")):(c.push({description:"Weak visual hierarchy - missing semantic structure",severity:"high"}),l.push("Implement semantic HTML5: header, nav, main, footer")),t.metadata?.description&&t.metadata.description.length>20&&(d+=10,a.push("Page has descriptive metadata"));break}case"H7.3-counter-intuitive-design":{d=85;let u=!t.domMetrics?.semanticStructure?.hasNav&&(t.domMetrics?.interactiveElements||0)>10,m=!t.domMetrics?.semanticStructure?.hasHeader&&!t.domMetrics?.semanticStructure?.hasFooter;u&&(d=45,c.push({description:"Navigation structure may be counter-intuitive",severity:"high"}),l.push("Add semantic navigation elements")),m&&(d-=15,c.push({description:"Page structure lacks expected header/footer",severity:"medium"})),d>75&&a.push("No counter-intuitive design patterns detected");break}case"H5.2-user-feelings-impact":{let u=t.accessibility?.altTextsCoverage||0,m=t.performance?.loadTime||0,p=t.accessibility?.ariaLabelsCount||0,g=t.accessibility?.focusableElementsCount||0;d=60,u>=90?(d+=20,a.push("Excellent accessibility (90%+ alt coverage) creates inclusive, positive experience")):u>=70?(d+=12,a.push("Good accessibility creates generally positive user feelings")):u<50&&(d-=15,c.push({description:"Poor accessibility (<50% alt coverage) frustrates users with disabilities",severity:"high"}),l.push("Improve alt text coverage to at least 80% for better accessibility")),p>5&&(d+=8,a.push("Strong ARIA labeling enhances screen reader experience")),m<1500?(d+=15,a.push("Very fast load time (<1.5s) delights users")):m<2500?(d+=8,a.push("Fast load time enhances user satisfaction")):m>4e3?(d-=20,c.push({description:"Very slow load time (>4s) causes significant frustration",severity:"critical"}),l.push("Optimize page load time - target under 2.5 seconds")):m>3e3&&(d-=12,c.push({description:"Slow load time causes user frustration",severity:"high"})),t.errorIndicators?.hasErrorMessages&&(d-=12,c.push({description:"Visible errors reduce user confidence and satisfaction",severity:"high"}),l.push("Review and fix visible error messages")),g>20?(d+=5,a.push("Rich interactive elements provide user control and engagement")):g<5&&(d-=8,c.push({description:"Limited interactivity may feel restrictive",severity:"medium"})),d=Math.max(20,Math.min(100,d));break}case"H5.1-gui-flow-impact":{let u=t.domMetrics?.interactiveElements||0,m=t.domMetrics?.forms||0;u>20&&(d=75,a.push(`${u} interactive elements provide user control`)),m>0&&(a.push(`${m} forms impact user input flows`),d=Math.min(100,d+10)),u===0&&(d=30,c.push({description:"Limited user interaction capability",severity:"high"}));break}case"H5.3-cross-functional-impact":d=70,t.accessibility&&(t.accessibility.altTextsCoverage||0)<100&&a.push("Content team needed for alt text creation"),t.performance&&(t.performance.loadTime||0)>2e3&&a.push("Engineering team needed for performance optimization"),n.complexity==="complex"&&a.push("QA team needed for comprehensive testing"),d=70+a.length*5;break;case"H5.4-data-dependent-impact":t.domMetrics?.forms&&t.domMetrics.forms>0?(d=75,a.push(`${t.domMetrics.forms} forms depend on backend data processing`)):(d=50,a.push("Limited data-dependent features"));break;case"H1.1-problem-understanding":d=n.clarityScore,n.clarityScore>80?a.push("Problem is well-defined"):c.push({description:"Problem clarity needs improvement",severity:"medium"}),a.push(...n.breakdown);break;case"H1.2-rule-of-three":d=n.potentialFailures.length>=3?85:60,a.push(`${n.potentialFailures.length} potential failure modes identified`),n.potentialFailures.length<3&&l.push("Identify at least 3 potential failure modes (Rule of Three)");break;case"H1.3-problem-complexity":d=n.complexity==="simple"?90:n.complexity==="moderate"?75:60,a.push(`Problem complexity: ${n.complexity}`);break;case"H2.1-user-needs-identification":{d=r.alignmentScore,a.push(`${r.needs.length} user needs identified`);let u=r.needs.filter(m=>m.priority==="must-have").length;a.push(`${u} must-have features`),r.challenges.length>0&&c.push({description:`${r.challenges.length} user need challenges found`,severity:"medium"});break}case"H2.2-user-needs-suitability":d=r.suitability==="excellent"?95:r.suitability==="good"?80:r.suitability==="adequate"?65:45,a.push(`User needs suitability: ${r.suitability}`);break;case"H2.3-user-needs-validation":{let u=r.needs.filter(m=>m.addressed).length;d=r.needs.length>0?u/r.needs.length*100:50,a.push(`${u}/${r.needs.length} needs validated and addressed`);break}case"H3.1-business-needs-identification":d=i.alignmentScore,a.push(`Primary goal: ${i.primaryGoal}`),a.push(`${i.kpisAffected.length} KPIs affected`),a.push(`${i.crossTeamImpact.length} cross-team impacts`);break;case"H3.2-user-vs-business-balance":{let u=100-Math.abs(r.alignmentScore-i.alignmentScore);d=u,u>80?a.push("Good balance between user and business needs"):(c.push({description:"Imbalance between user and business priorities",severity:"medium"}),l.push("Align user and business objectives more closely"));break}case"H3.3-kpi-impact-analysis":d=i.impactsKPIs?85:50,a.push(`KPIs impacted: ${i.kpisAffected.join(", ")}`),i.compromisesUX&&(c.push({description:"Business ease compromises user experience",severity:"high"}),d-=20);break;case"H4.1-oracle-problem-detection":d=75,a.push("Oracle problem detection capability active");break;case"H4.2-what-must-not-change":d=80,t.domMetrics?.semanticStructure?.hasMain&&a.push("Main content structure is immutable"),t.accessibility&&(t.accessibility.focusableElementsCount||0)>0&&a.push("Keyboard navigation support must be maintained");break;case"H4.3-supporting-data-analysis":{d=75,(t.domMetrics?.forms||0)>0||(t.domMetrics?.interactiveElements||0)>20?(d=82,a.push("Sufficient data points for informed decision-making")):(d=60,c.push({description:"Limited data for comprehensive analysis",severity:"medium"}),l.push("Collect more user interaction data"));break}case"H6.1-competitive-analysis":d=70,a.push("Competitive analysis capability available"),t.domMetrics?.semanticStructure?.hasNav&&t.domMetrics?.interactiveElements&&t.domMetrics.interactiveElements>15?(d=78,a.push("Navigation and interaction patterns follow industry standards")):l.push("Compare interaction patterns with leading competitors");break;case"H6.2-domain-inspiration":{d=72,t.accessibility&&(t.accessibility.ariaLabelsCount||0)>0?(d=80,a.push("Modern accessibility patterns show domain inspiration")):l.push("Research domain-specific design patterns and best practices");break}case"H6.3-innovative-solutions":{d=65,(t.accessibility?.landmarkRoles||0)>3?(d=75,a.push("Advanced accessibility features show innovative thinking")):l.push("Explore innovative UX patterns to differentiate experience");break}default:s==="user-needs"?d=r.alignmentScore:s==="business-needs"?d=i.alignmentScore:s==="problem"&&(d=n.clarityScore);break}return{id:e,name:this.getHeuristicName(e),category:s,applied:!0,score:Math.min(100,Math.max(0,d)),findings:a,issues:c,recommendations:l}}getHeuristicCategory(e){return e.includes("problem")?"problem":e.includes("user-needs")||e.includes("user-vs")?"user-needs":e.includes("business")?"business-needs":e.includes("oracle")||e.includes("balance")||e.includes("what-must")||e.includes("supporting-data")?"balance":e.includes("impact")||e.includes("gui-flow")||e.includes("feelings")||e.includes("cross-functional")||e.includes("data-dependent")?"impact":e.includes("competitive")||e.includes("inspiration")||e.includes("innovative")?"creativity":"design"}getHeuristicName(e){return{"H1.1-problem-understanding":"Problem Understanding","H1.2-rule-of-three":"Rule of Three","H1.3-problem-complexity":"Problem Complexity","H2.1-user-needs-identification":"User Needs Identification","H2.2-user-needs-suitability":"User Needs Suitability","H2.3-user-needs-validation":"User Needs Validation","H3.1-business-needs-identification":"Business Needs Identification","H3.2-user-vs-business-balance":"User vs Business Balance","H3.3-kpi-impact-analysis":"KPI Impact Analysis","H4.1-oracle-problem-detection":"Oracle Problem Detection","H4.2-what-must-not-change":"What Must Not Change","H4.3-supporting-data-analysis":"Supporting Data Analysis","H5.1-gui-flow-impact":"GUI Flow Impact","H5.2-user-feelings-impact":"User Feelings Impact","H5.3-cross-functional-impact":"Cross-Functional Impact","H5.4-data-dependent-impact":"Data-Dependent Impact","H6.1-competitive-analysis":"Competitive Analysis","H6.2-domain-inspiration":"Domain Inspiration","H6.3-innovative-solutions":"Innovative Solutions","H7.1-exactness-and-clarity":"Exactness & Clarity","H7.2-intuitive-design":"Intuitive Design","H7.3-counter-intuitive-design":"Counter-Intuitive Design","H7.4-consistency-analysis":"Consistency Analysis"}[e]||e}};var Sr=class{minSeverity;constructor(e="medium"){this.minSeverity=e}detect(e,t,n){let r=[];Math.abs(t.alignmentScore-n.alignmentScore)>20&&r.push({type:"user-vs-business",description:"Significant gap between user needs and business objectives",severity:"high",stakeholders:["Users","Business"],resolutionApproach:["Gather supporting data from both perspectives","Facilitate discussion between stakeholders","Find compromise solutions that address both needs"]}),(t.challenges.length>0||n.compromisesUX)&&r.push({type:"unclear-criteria",description:"Quality criteria unclear due to conflicting information",severity:"medium",missingInfo:t.challenges,resolutionApproach:["Collect missing information from stakeholders","Define clear acceptance criteria"]});let i=(e.title||"").toLowerCase(),s=(e.metadata?.description||"").toLowerCase();return(i.includes("hotel")||i.includes("booking")||i.includes("travel")||i.includes("shop")||i.includes("store")||s.includes("book"))&&(n.kpisAffected.some(a=>a.toLowerCase().includes("conversion")||a.toLowerCase().includes("engagement"))&&r.push({type:"user-vs-business",description:"Potential conflict between conversion optimization (business) and user experience quality (user trust)",severity:"medium",stakeholders:["Marketing","Product","Users"],resolutionApproach:["A/B test aggressive vs. subtle conversion tactics","Measure both conversion rate and user satisfaction metrics","Balance urgency messaging with transparent communication"]}),r.push({type:"unclear-criteria",description:"Unclear criteria for price display timing - when to show fees, taxes, and final price",severity:"medium",stakeholders:["Users","Legal","Business"],resolutionApproach:["Define regulatory compliance requirements for price display","Balance business desire for competitive base pricing vs user need for full price transparency","Establish clear standards for fee disclosure timing"]})),(i.includes("blog")||i.includes("article")||i.includes("news")||i.includes("magazine")||i.includes("testing"))&&r.push({type:"user-vs-business",description:"Content depth (user need) vs. publication frequency (business engagement goals) trade-off",severity:"low",stakeholders:["Readers","Content Team","Editorial"],resolutionApproach:["Define content quality standards and acceptance criteria","Balance editorial calendar with quality thresholds","Consider mix of in-depth and quick-read content formats"]}),(i.includes("health")||i.includes("medical")||i.includes("patient")||i.includes("care")||i.includes("nhs"))&&(r.push({type:"stakeholder-conflict",description:"Healthcare compliance requirements may conflict with streamlined user experience",severity:"medium",stakeholders:["Patients","Healthcare Providers","Compliance","Legal"],resolutionApproach:["Map regulatory requirements to UX touchpoints","Identify where compliance can be achieved without friction","Engage compliance team early in UX design reviews","Document consent and data handling requirements clearly"]}),e.accessibility&&(e.accessibility.altTextsCoverage||0)<80&&r.push({type:"technical-constraint",description:"Healthcare accessibility requirements not fully met - critical for patient inclusivity",severity:"high",stakeholders:["Patients","Accessibility Team","Legal"],resolutionApproach:["Prioritize WCAG 2.1 AA compliance for healthcare content","Ensure screen reader compatibility for medical information","Test with assistive technology users"]})),(i.includes("bank")||i.includes("finance")||i.includes("payment")||i.includes("money"))&&r.push({type:"stakeholder-conflict",description:"Security requirements vs user convenience - authentication friction vs fraud prevention",severity:"high",stakeholders:["Users","Security Team","Product","Compliance"],resolutionApproach:["Implement risk-based authentication to reduce friction for trusted sessions","Use biometrics where available for convenient yet secure access","A/B test authentication flows for security effectiveness and user completion rates"]}),((e.domMetrics?.totalElements||0)>500||(e.domMetrics?.interactiveElements||0)>50)&&r.push({type:"technical-constraint",description:"Platform technical limitations may restrict advanced UX features or accessibility enhancements",severity:"low",stakeholders:["Development","Product","Users"],resolutionApproach:["Evaluate platform capabilities and constraints","Prioritize features based on user impact vs. implementation complexity","Consider gradual enhancement approach"]}),e.performance&&(e.performance.loadTime||0)>3e3&&r.push({type:"technical-constraint",description:"Performance optimization needed but may require trade-offs with visual richness",severity:"medium",stakeholders:["Users","Development","Design"],resolutionApproach:["Profile and identify performance bottlenecks","Consider progressive loading for visual elements","Balance image quality with load time"]}),r.filter(a=>this.meetsMinimumSeverity(a.severity))}meetsMinimumSeverity(e){let t=["low","medium","high","critical"],n=t.indexOf(this.minSeverity);return t.indexOf(e)>=n}};var Tr=class o{static LOAD_TIME_FEELINGS=[[4001,1/0,"Impatient - Very slow load time causes significant frustration"],[3001,4e3,"Impatient - Slow load time causes frustration"],[2001,3e3,"Mildly Annoyed - Noticeable load time"],[0,1499,"Delighted - Fast load time enhances experience"],[1500,1999,"Satisfied - Good load time meets expectations"]];static DOMAIN_REQUIREMENTS=[[["health","medical","care"],["Must comply with healthcare accessibility standards","Must protect patient data privacy"]],[["bank","finance","payment"],["Must maintain PCI DSS compliance for payment data","Must support secure authentication flows"]]];static VISIBLE_SCORE_ADJUSTMENTS=[[["Positive","Satisfied","Delighted"],20],[["Oriented"],10],[["Frustrated","Confused","Impatient"],-15],[["Disoriented"],-10]];analyze(e,t){let n=this.analyzeEndUserFlow(e),r=this.analyzeInternalFlow(e),i=this.analyzeUserFeelings(e),s=this.analyzePerformance(e),a=this.analyzeSecurity(e),c=this.analyzeImmutableRequirements(e,t),l=this.calculateVisibleScore(n,i),d=this.calculateInvisibleScore(s,a),u=Math.round((l+d)/2);return{visible:{guiFlow:{forEndUser:n,forInternalUser:r},userFeelings:i,score:l},invisible:{performance:s,security:a,score:d},immutableRequirements:c,overallImpactScore:u}}analyzeEndUserFlow(e){let t=[],n=e.domMetrics?.interactiveElements||0,r=e.domMetrics?.forms||0;return n>0&&t.push(`${n} interactive elements affect user journey`),r>0&&t.push(`${r} forms impact user input flows`),e.domMetrics?.semanticStructure?.hasNav&&t.push("Navigation structure enables exploration flow"),e.domMetrics?.semanticStructure?.hasMain&&t.push("Clear main content area guides user focus"),t}analyzeInternalFlow(e){let t=[];return(e.domMetrics?.forms||0)>0&&t.push("Form submissions create data processing workflows"),e.domMetrics?.semanticStructure?.hasAside&&t.push("Sidebar content may require separate management"),t}analyzeUserFeelings(e){let t=[],n=e.accessibility?.altTextsCoverage||0;n>80?t.push("Positive - Good accessibility creates inclusive experience"):n>=50?t.push("Neutral - Moderate accessibility; some users may struggle"):n<50&&t.push("Frustrated - Poor accessibility excludes some users");let r=e.performance?.loadTime||0;for(let[i,s,a]of o.LOAD_TIME_FEELINGS)if(r>=i&&r<=s){t.push(a);break}return e.errorIndicators?.hasErrorMessages&&t.push("Confused - Visible errors reduce confidence"),this.analyzeStructureFeelings(e,t),t}analyzeStructureFeelings(e,t){let n=e.domMetrics?.semanticStructure;if(!n)return;let r=[n.hasHeader,n.hasNav,n.hasMain,n.hasFooter].filter(Boolean).length;r>=3?t.push("Oriented - Clear page structure helps navigation"):r<2&&t.push("Disoriented - Unclear page structure may confuse users")}analyzePerformance(e){let t=[],n=e.performance?.loadTime||0;return n>2e3&&t.push(`Load time ${n}ms impacts user retention`),e.metadata?.viewport||t.push("Missing viewport tag affects mobile performance"),e.performance?.firstContentfulPaint&&e.performance.firstContentfulPaint>2500&&t.push(`First Contentful Paint ${e.performance.firstContentfulPaint}ms delays perceived readiness`),t}analyzeSecurity(e){let t=[];return(e.domMetrics?.forms||0)>0&&t.push("Form data handling requires secure transmission"),e.accessibility&&(e.accessibility.ariaLabelsCount||0)>0&&t.push("ARIA labels may expose internal element names - review for sensitive info"),t}analyzeImmutableRequirements(e,t){let n=[];e.domMetrics?.semanticStructure?.hasMain&&n.push("Must maintain main content accessibility"),e.accessibility&&(e.accessibility.focusableElementsCount||0)>0&&n.push("Must support keyboard navigation"),t.complexity==="complex"&&n.push("Must maintain system stability with complex interactions");let r=(e.title||"").toLowerCase();for(let[i,s]of o.DOMAIN_REQUIREMENTS)i.some(a=>r.includes(a))&&n.push(...s);return n}calculateVisibleScore(e,t){let n=50;e.length>0&&(n+=15);for(let[r,i]of o.VISIBLE_SCORE_ADJUSTMENTS)t.some(s=>r.some(a=>s.includes(a)))&&(n+=i);return Math.max(0,Math.min(100,n))}calculateInvisibleScore(e,t){let n=50;return e.length===0&&(n+=20),t.length===0&&(n+=10),e.length>2&&(n-=15),Math.max(0,Math.min(100,n))}};D();var ng={type:"object",properties:{target:{type:"string",description:"Target URL or identifier to analyze"},context:{type:"object",description:"Pre-collected QX context (optional)"},mode:{type:"string",description:"Analysis mode: full, quick, or targeted",enum:["full","quick","targeted"],default:"full"},heuristics:{type:"array",description:"Specific heuristics to apply (default: all)",items:{type:"string",description:"Heuristic name"}},minOracleSeverity:{type:"string",description:"Minimum oracle problem severity to report",enum:["low","medium","high","critical"],default:"medium"},includeCreativity:{type:"boolean",description:"Include creativity analysis from diverse domains",default:!0},includeDesign:{type:"boolean",description:"Include design quality analysis",default:!0}},required:["target"]},Kt=class extends A{config={name:"qe/qx/analyze",description:"Comprehensive Quality Experience (QX) analysis combining QA and UX perspectives. Applies 23+ programmatic heuristics, detects oracle problems, and analyzes impacts. QX = Marriage between QA (Quality Advocacy) and UX (User Experience).",domain:"quality-assessment",schema:ng,streaming:!0,timeout:18e4};async execute(e,t){let{target:n,context:r=this.createMinimalContext(n),mode:i="full",heuristics:s,minOracleSeverity:a="medium",includeCreativity:c=!0,includeDesign:l=!0}=e;try{this.emitStream(t,{status:"starting",message:`Starting QX analysis for: ${n}`,phase:"initialization"}),this.emitStream(t,{status:"analyzing",phase:"problem-analysis"});let d=this.analyzeProblem(r);if(this.isAborted(t))return{success:!1,error:"Operation aborted"};this.emitStream(t,{status:"analyzing",phase:"user-needs"});let u=this.analyzeUserNeeds(r,d);this.emitStream(t,{status:"analyzing",phase:"business-needs"});let m=this.analyzeBusinessNeeds(r,d);this.emitStream(t,{status:"analyzing",phase:"creativity"});let p=c?this.analyzeCreativity(r,d):this.createMinimalCreativityAnalysis();this.emitStream(t,{status:"analyzing",phase:"design"});let g=l?this.analyzeDesign(r):this.createMinimalDesignAnalysis();this.emitStream(t,{status:"analyzing",phase:"oracle-detection"});let h=new Sr(a).detect(r,u,m);this.emitStream(t,{status:"analyzing",phase:"impact-analysis"});let y=new Tr().analyze(r,d);this.emitStream(t,{status:"analyzing",phase:"heuristics",count:23});let b=await new Cr({enabledHeuristics:s||Object.values(Wt)}).applyAll(r,d,u,m);this.emitStream(t,{status:"analyzing",phase:"recommendations"});let E=this.generateRecommendations(d,u,m,h,y,b),T=this.calculateOverallScore(d,u,m,p,g,y,b),S=this.scoreToGrade(T),x={overallScore:T,grade:S,timestamp:new Date().toISOString(),target:n,problemAnalysis:d,userNeeds:u,businessNeeds:m,creativityAnalysis:p,designAnalysis:g,oracleProblems:h,impactAnalysis:y,heuristics:b,recommendations:E,context:r};return this.emitStream(t,{status:"complete",score:T,grade:S,heuristicsApplied:b.length,oracleProblemsFound:h.length}),{success:!0,data:x,metadata:this.createMetadata(t.startTime,t.requestId)}}catch(d){return{success:!1,error:`QX analysis failed: ${w(d)}`}}}analyzeProblem(e){let t=e.title||"Untitled page",n=e.metadata?.description||"",r=e.errorIndicators?.hasErrorMessages||!1,i=`Evaluate quality experience of "${t}"`;n&&(i+=` - ${n.substring(0,100)}`);let s=e.domMetrics?.totalElements||0,a=e.domMetrics?.interactiveElements||0,c=e.domMetrics?.forms||0,l;s>500||a>50||c>3?l="complex":s>200||a>20||c>1?l="moderate":l="simple";let d=[];e.domMetrics?.semanticStructure?.hasNav&&d.push("Navigation structure"),c>0&&d.push(`Form interactions (${c} forms)`),a>0&&d.push(`User interactions (${a} elements)`),e.accessibility&&d.push("Accessibility compliance"),e.performance&&d.push("Performance metrics");let u=[],m=t.toLowerCase();for((m.includes("health")||m.includes("care")||m.includes("nhs"))&&(u.push({description:"Healthcare information may not be accessible to users with visual impairments",severity:"high",likelihood:"likely"}),u.push({description:"Patient journey complexity may cause confusion during registration or booking",severity:"medium",likelihood:"possible"}),u.push({description:"Emergency contact information may not be prominently visible",severity:"high",likelihood:"possible"})),e.domMetrics?.semanticStructure?.hasMain||u.push({description:"Missing main content landmark - users may struggle to find primary content",severity:"medium",likelihood:"likely"}),e.accessibility&&(e.accessibility.altTextsCoverage||0)<80&&u.push({description:"Poor image alt text coverage - screen reader users affected",severity:"high",likelihood:"very-likely"}),r&&u.push({description:"Visible error messages detected - potential usability issues",severity:"medium",likelihood:"likely"}),e.performance&&(e.performance.loadTime||0)>3e3&&u.push({description:"Slow load time - user frustration and abandonment risk",severity:"high",likelihood:"very-likely"});u.length<3;)l==="complex"?u.push({description:"Complex interaction flows may confuse first-time users",severity:"medium",likelihood:"possible"}):l==="moderate"?u.push({description:"Multiple interactive elements increase cognitive load",severity:"low",likelihood:"possible"}):u.push({description:"Limited interactivity may not meet user expectations",severity:"low",likelihood:"possible"});let p=50;return t&&t!=="Untitled page"&&(p+=15),n&&(p+=15),d.length>=3&&(p+=10),e.domMetrics?.semanticStructure?.hasMain&&(p+=10),p=Math.min(100,p),{problemStatement:i,complexity:l,breakdown:d,potentialFailures:u.slice(0,5),clarityScore:p}}analyzeUserNeeds(e,t){let n=[],r=[],i=e.domMetrics?.semanticStructure,s=e.accessibility,a=e.domMetrics?.interactiveElements||0,c=e.domMetrics?.forms||0;i?.hasNav?n.push({description:"Clear navigation to find content",priority:"must-have",addressed:!0}):(r.push("Missing navigation structure - users cannot easily explore site"),n.push({description:"Clear navigation to find content",priority:"must-have",addressed:!1})),a>0&&n.push({description:"Interactive elements for engagement",priority:"must-have",addressed:!0}),s&&(s.focusableElementsCount||0)>0?n.push({description:"Keyboard navigation support",priority:"must-have",addressed:!0}):(r.push("Limited keyboard navigation - inaccessible to some users"),n.push({description:"Keyboard navigation support",priority:"must-have",addressed:!1})),i?.hasHeader&&n.push({description:"Consistent page header for orientation",priority:"should-have",addressed:!0}),i?.hasFooter&&n.push({description:"Footer with supporting information",priority:"should-have",addressed:!0}),s&&(s.altTextsCoverage||0)>50?n.push({description:"Image descriptions for screen readers",priority:"should-have",addressed:!0}):s&&(s.altTextsCoverage||0)<50&&(r.push("Poor alt text coverage - images not accessible"),n.push({description:"Image descriptions for screen readers",priority:"should-have",addressed:!1})),e.performance&&(e.performance.loadTime||0)<3e3?n.push({description:"Fast page load time",priority:"should-have",addressed:!0}):e.performance&&(e.performance.loadTime||0)>=3e3&&(r.push("Slow load time - user frustration risk"),n.push({description:"Fast page load time",priority:"should-have",addressed:!1})),i?.hasAside&&n.push({description:"Supplementary content sections",priority:"nice-to-have",addressed:!0}),s&&(s.landmarkRoles||0)>3&&n.push({description:"Rich ARIA landmarks for navigation",priority:"nice-to-have",addressed:!0}),c>0&&n.push({description:"Form interactions for user input",priority:"nice-to-have",addressed:!0});let l=n.filter(m=>m.priority==="must-have"&&m.addressed).length,d;r.length===0&&l>=3?d="excellent":r.length<=1&&l>=2?d="good":r.length<=2&&l>=2?d="adequate":d="poor";let u=40;return u+=l*10,u+=n.filter(m=>m.priority==="should-have"&&m.addressed).length*5,u+=n.filter(m=>m.priority==="nice-to-have"&&m.addressed).length*2,u-=r.length*8,u=Math.max(0,Math.min(100,u)),{needs:n,suitability:d,challenges:r,alignmentScore:u}}analyzeBusinessNeeds(e,t){let n=e.domMetrics?.forms||0,r=e.domMetrics?.interactiveElements||0,i=e.performance,s=e.errorIndicators?.hasErrorMessages||!1,a,c=[];n>2?(a="business-ease",c=["Form completion rate","Lead generation","User sign-ups"]):r>30?(a="user-experience",c=["Time on site","Click-through rate","User engagement"]):(a="balanced",c=["Content consumption","Bounce rate","Page views"]);let l=(e.title||"").toLowerCase();(l.includes("health")||l.includes("care"))&&c.push("Patient satisfaction","Appointment completion rate","Information accessibility");let d=[];n>0&&(d.push({team:"Marketing",impactType:"positive",description:"Form conversion optimization needed"}),d.push({team:"Development",impactType:"neutral",description:"Form validation and submission handling"})),e.accessibility&&(e.accessibility.altTextsCoverage||0)<100&&d.push({team:"Content",impactType:"negative",description:"Image alt text creation required"}),i&&(i.loadTime||0)>2e3&&d.push({team:"Engineering",impactType:"negative",description:"Performance optimization needed"}),t.complexity==="complex"&&d.push({team:"QA",impactType:"neutral",description:"Comprehensive testing strategy required"});let u=!1;s&&(u=!0),e.accessibility&&(e.accessibility.altTextsCoverage||0)<50&&(u=!0),i&&(i.loadTime||0)>4e3&&(u=!0);let m=50;return c.length>0&&(m+=15),d.length>0&&(m+=10),u||(m+=20),m=Math.min(100,m),{primaryGoal:a,kpisAffected:c,crossTeamImpact:d,compromisesUX:u,impactsKPIs:c.length>0,alignmentScore:m}}analyzeCreativity(e,t){let n=[];(t.complexity==="complex"||t.complexity==="moderate")&&(n.push({description:"Question fundamental assumptions about user mental models and expected workflows",inspirationSource:"philosophy",applicability:"high",novelty:"moderately-novel"}),e.errorIndicators?.hasErrorMessages&&n.push({description:"Apply diagnostic testing - systematically isolate error sources through controlled scenarios",inspirationSource:"medicine",applicability:"high",novelty:"moderately-novel"})),e.domMetrics?.forms&&e.domMetrics.forms>0&&n.push({description:"Test checkout/form flows like fashion retail - focus on friction points, abandonment triggers",inspirationSource:"e-commerce",applicability:"high",novelty:"incremental"}),n.push({description:"Analyze through diverse demographic lenses (age, gender, culture, ability) for inclusive testing",inspirationSource:"social science",applicability:"high",novelty:"moderately-novel"}),e.domMetrics?.interactiveElements&&e.domMetrics.interactiveElements>20&&n.push({description:'Test for "game-breaking" exploits - unexpected interaction sequences, boundary conditions',inspirationSource:"gaming",applicability:"medium",novelty:"highly-novel"});let r=[...new Set(n.map(a=>a.inspirationSource))],i=["Unexperienced user perspective (fresh eyes)","Power user perspective (efficiency focus)","Accessibility perspective (assistive tech users)","International perspective (cultural differences)"],s=50;return s+=n.length*8,s+=r.length*5,s=Math.min(100,s),{innovativeApproaches:n,domainsExplored:r,perspectives:i,creativityScore:s,notes:["Creativity draws from diverse domains to uncover unconventional testing approaches","Higher complexity problems benefit from cross-disciplinary inspiration",`Applied ${n.length} creative approaches from ${r.length} domains`]}}analyzeDesign(e){let t=[],n=[];e.domMetrics?.semanticStructure?.hasNav&&t.push("Navigation structure clearly defined with semantic <nav> element"),e.domMetrics?.semanticStructure?.hasMain&&t.push("Main content area clearly identified"),e.domMetrics?.semanticStructure?.hasHeader&&e.domMetrics?.semanticStructure?.hasFooter&&t.push("Header and footer provide clear page structure");let r=e.accessibility?.ariaLabelsCount||0,i=e.domMetrics?.interactiveElements||0;i>0&&r<i*.5&&n.push("Many interactive elements lack ARIA labels for clarity");let s=50+t.length*15-n.length*10;s=Math.max(0,Math.min(100,s));let a=s>=80?"excellent":s>=60?"good":s>=40?"adequate":"poor",c=[],l=[],d=!0;e.domMetrics?.semanticStructure?.hasNav&&c.push("Standard navigation placement"),e.domMetrics?.semanticStructure?.hasHeader&&c.push("Header follows common layout conventions"),!e.domMetrics?.semanticStructure?.hasNav&&i>10&&(d=!1,l.push("Non-standard navigation pattern may confuse users from different regions"));let u=50+c.length*15;d||(u-=20),u=Math.max(0,Math.min(100,u));let m=Math.round((s+u)/2);return{exactness:{clarity:a,clearElements:t,unclearElements:n,score:s},intuitive:{followsConventions:d,intuitivePatterns:c,culturalIssues:l,score:u},counterIntuitive:{deviations:[],innovativeJustification:!1,freshEyesPerspective:!0,issuesCount:0},overallDesignScore:m}}generateRecommendations(e,t,n,r,i,s){let a=[],c=1;for(let l of s){for(let d of l.issues)(d.severity==="critical"||d.severity==="high")&&a.push({principle:l.name,recommendation:d.description,severity:d.severity,impact:d.severity==="critical"?90:75,effort:"medium",priority:c++,category:"qx"});for(let d of l.recommendations)a.push({principle:l.name,recommendation:d,severity:"medium",impact:60,effort:"medium",priority:c++,category:"qx"})}for(let l of r)a.push({principle:`Oracle: ${l.type}`,recommendation:l.description,severity:l.severity,impact:l.severity==="critical"?95:l.severity==="high"?80:60,effort:"high",priority:c++,category:"process",evidence:l.resolutionApproach});for(let l of t.challenges)a.push({principle:"User Needs",recommendation:l,severity:"medium",impact:65,effort:"medium",priority:c++,category:"ux"});return a.sort((l,d)=>{let u={critical:0,high:1,medium:2,low:3},m=u[l.severity]-u[d.severity];return m!==0?m:d.impact-l.impact}).slice(0,15)}calculateOverallScore(e,t,n,r,i,s,a){let c=a.reduce((d,u)=>d+u.score,0)/a.length||0,l=e.clarityScore*.1+t.alignmentScore*.2+n.alignmentScore*.15+r.creativityScore*.1+i.overallDesignScore*.15+(100-s.overallImpactScore)*.1+c*.2;return Math.round(Math.max(0,Math.min(100,l)))}scoreToGrade(e){return e>=90?"A":e>=80?"B":e>=70?"C":e>=60?"D":"F"}createMinimalContext(e){return{url:e,title:e}}createMinimalCreativityAnalysis(){return{innovativeApproaches:[],domainsExplored:[],perspectives:[],creativityScore:50,notes:["Creativity analysis skipped"]}}createMinimalDesignAnalysis(){return{exactness:{clarity:"adequate",clearElements:[],unclearElements:[],score:50},intuitive:{followsConventions:!0,intuitivePatterns:[],culturalIssues:[],score:50},counterIntuitive:{deviations:[],innovativeJustification:!1,freshEyesPerspective:!1,issuesCount:0},overallDesignScore:50}}emitStream(e,t){e.streaming&&e.onStream&&e.onStream(t)}isAborted(e){return e.abortSignal?.aborted||!1}createMetadata(e,t){return{executionTime:Date.now()-e,timestamp:new Date().toISOString(),requestId:t}}},II=new Kt;var iD={TEST_GENERATE:"qe/tests/generate",TEST_EXECUTE:"qe/tests/execute",COVERAGE_ANALYZE:"qe/coverage/analyze",COVERAGE_GAPS:"qe/coverage/gaps",QUALITY_EVALUATE:"qe/quality/evaluate",QUALITY_GATE:"qe/quality/gate",DEFECT_PREDICT:"qe/defects/predict",REQUIREMENTS_VALIDATE:"qe/requirements/validate",QUALITY_CRITERIA:"qe/requirements/quality-criteria",CODE_ANALYZE:"qe/code/analyze",CODE_C4:"qe/code/c4",SECURITY_SCAN:"qe/security/scan",CONTRACT_VALIDATE:"qe/contracts/validate",VISUAL_COMPARE:"qe/visual/compare",A11Y_AUDIT:"qe/a11y/audit",CHAOS_INJECT:"qe/chaos/inject",LEARNING_OPTIMIZE:"qe/learning/optimize",LEARNING_DREAM:"qe/learning/dream",TOKEN_USAGE:"qe/analysis/token_usage",GOAP_PLAN:"qe/planning/goap_plan",GOAP_EXECUTE:"qe/planning/goap_execute",GOAP_STATUS:"qe/planning/goap_status",...zt,EMBEDDING_GENERATE:"qe/embeddings/generate",EMBEDDING_COMPARE:"qe/embeddings/compare",EMBEDDING_SEARCH:"qe/embeddings/search",EMBEDDING_STORE:"qe/embeddings/store",EMBEDDING_STATS:"qe/embeddings/stats",...gl,QX_ANALYZE:"qe/qx/analyze",TEST_SCHEDULE:"qe/tests/schedule",LOAD_TEST:"qe/tests/load",URL_VALIDATE:"qe/security/url-validate",BROWSER_WORKFLOW:"qe/workflows/browser-load"},rg=[new Wn,new Kn,new Yn,new Jn,new Zn,new er,new nr,new rr,new Ot,new sr,new ar,new or,new cr,new lr,new ur,new dr,new Nt,new Ft,new mr,new $t,new Gt,new jt,...ml,new dt,new mt,new pt,new gt,new ft,...pl,new Kt,new so,new ao,new oo,new co];function fl(){for(let o of rg)o.resetInstanceCache()}D();var ig=wr.filter(o=>o!=="coordination"),P={fleetId:null,kernel:null,queen:null,router:null,workflowOrchestrator:null,initialized:!1,initTime:null,topology:"hierarchical",agentLevels:new Map};function Mt(){return P}function nt(){return P.initialized&&P.kernel!==null&&P.queen!==null}function bD(o){return nt()||(P.fleetId=`fleet-${U().slice(0,8)}`,P.kernel=o.kernel,P.queen=o.queen,P.router=o.router??null,P.workflowOrchestrator=o.workflowOrchestrator??null,P.initialized=!0,P.initTime=new Date,P.topology=o.topology??"hierarchical",P.agentLevels.clear()),P.fleetId}function CD(){return P.topology}function SD(o,e){if(P.topology!=="hierarchical"){let i={agentId:o,domain:e,level:"worker",spawnedAt:new Date};return P.agentLevels.set(o,i),"worker"}let n=Array.from(P.agentLevels.values()).find(i=>i.domain===e&&i.level==="lead")?"worker":"lead",r={agentId:o,domain:e,level:n,spawnedAt:new Date};return P.agentLevels.set(o,r),n}function TD(o){return P.agentLevels.get(o)}function ED(){return P.agentLevels}async function wD(o){try{if(P.initialized&&P.kernel&&P.queen){let l=P.kernel.getConfig();return{success:!0,data:{fleetId:P.fleetId,topology:P.topology,maxAgents:l.maxConcurrentAgents,enabledDomains:l.enabledDomains.filter(d=>d!=="coordination"),status:"ready"}}}P.fleetId=`fleet-${U().slice(0,8)}`;let e=o.enabledDomains||[...wr],t=e.filter(l=>l!=="coordination"),n=process.env.AQE_MEMORY_BACKEND==="memory"?"memory":o.memoryBackend||"hybrid";P.kernel=new Oa({maxConcurrentAgents:o.maxAgents||15,memoryBackend:n,hnswEnabled:!0,lazyLoading:o.lazyLoading!==!1,enabledDomains:e}),await P.kernel.initialize(),P.router=new Fa(P.kernel.eventBus),await P.router.initialize();let r=l=>P.kernel.getDomainAPI(l),i=new lo(P.kernel.eventBus,P.kernel.memory,r),s=P.kernel.plugins;await s.loadAll();let a=new Map;for(let l of s.getLoaded()){let d=s.getPlugin(l);d&&a.set(l,d)}try{let{getDaemon:l}=await import("./daemon-JEBJGEUK.js"),d=l().getWorkerManager();d.setKernel(P.kernel),d.setMemory(P.kernel.memory)}catch(l){console.warn(`[fleet_init] Daemon worker manager wiring skipped: ${w(l)}`)}P.queen=Na(P.kernel,P.router,i,void 0,a),await P.queen.initialize(),P.workflowOrchestrator=new _a(P.kernel.eventBus,P.kernel.memory,P.kernel.coordinator),await P.workflowOrchestrator.initialize(),sg(P.kernel,P.workflowOrchestrator);let{subscribeTrajectoryEvents:c}=await import("./task-handlers-S2TX5FTR.js");return c(P.router),P.initialized=!0,P.initTime=new Date,P.topology=o.topology||"hierarchical",P.agentLevels.clear(),{success:!0,data:{fleetId:P.fleetId,topology:P.topology,maxAgents:o.maxAgents||15,enabledDomains:t,status:"initialized"}}}catch(e){return{success:!1,error:`Failed to initialize fleet: ${w(e)}`}}}async function RD(o){if(!nt())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{let e=P.queen.getHealth(),t=P.queen.getMetrics(),n={status:e.status,uptime:t.uptime,agents:{total:e.totalAgents,active:e.activeAgents,idle:e.totalAgents-e.activeAgents},tasks:{pending:e.pendingTasks,running:e.runningTasks,completed:t.tasksCompleted,failed:t.tasksFailed}};if(o.includeDomains){let i=[];for(let[s,a]of e.domainHealth)i.push({domain:s,status:a.status,agents:a.agents.total,load:P.queen.getDomainLoad(s)});n.domains=i}let r=P.queen.getDomainTeamManager?.();if(r){let i=r.listDomainTeams(),s=0,a=0;for(let c of i)s+=1+c.teammateIds.length,r.getTeamHealth(c.domain)?.healthy&&a++;n.teams={active:i.length,totalAgentsInTeams:s,healthyCount:a}}o.includeMetrics&&(n.metrics={tasksReceived:t.tasksReceived,tasksCompleted:t.tasksCompleted,tasksFailed:t.tasksFailed,agentUtilization:t.agentUtilization,averageTaskDuration:t.averageTaskDuration});try{let{getUnifiedMemory:i}=await import("./unified-memory-2VMGSGQL.js"),s=i();if(s.isInitialized()){let a=l=>{try{return s.queryCount(l)}catch{return 0}},c=await s.vectorCount();n.learning={totalPatterns:a("qe_patterns"),totalExperiences:a("captured_experiences"),totalTrajectories:a("qe_trajectories"),vectorCount:c,experienceApplications:a("experience_applications"),dreamCycles:a("dream_cycles"),embeddingDimension:384}}}catch{}return{success:!0,data:n}}catch(e){return{success:!1,error:`Failed to get fleet status: ${w(e)}`}}}async function PD(o){if(!nt())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{if(o.domain){let n=P.queen.getDomainHealth(o.domain);return n?{success:!0,data:{domain:o.domain,status:n.status,agents:n.agents,errors:n.errors,lastActivity:n.lastActivity?.toISOString()}}:{success:!1,error:`Domain not found: ${o.domain}`}}let e=P.queen.getHealth(),t={status:e.status,totalAgents:e.totalAgents,activeAgents:e.activeAgents,pendingTasks:e.pendingTasks,runningTasks:e.runningTasks,workStealingActive:e.workStealingActive,lastHealthCheck:e.lastHealthCheck.toISOString()};if(o.detailed){let n={};for(let[i,s]of e.domainHealth)n[i]={status:s.status,agents:s.agents,errors:s.errors.length,lastActivity:s.lastActivity?.toISOString()};t.domains=n,t.issues=e.issues.map(i=>({severity:i.severity,message:i.message,domain:i.domain,timestamp:i.timestamp.toISOString()}));let r=e.minCut;r&&(t.minCut={status:r.status,minCutValue:r.minCutValue,fleetStatus:r.fleetStatus,fleetMinCutValue:r.fleetMinCutValue,taskAgents:r.taskAgents})}try{let{StructuralHealthMonitor:n}=await import("./structural-health-PGY5XUNO.js"),r=new n,i=[];for(let[c]of e.domainHealth){let l=P.queen.getAgentsByDomain(c);for(let d of l)i.push({id:d.id,name:d.name,domain:d.domain})}let s=i.map(c=>({id:c.id,name:c.name,domain:c.domain,capabilities:[c.domain],dependsOn:[],weight:1})),a=r.computeFleetHealth(s);t.structuralHealth={lambda:a.lambda,healthy:a.healthy,normalizedLambda:a.normalizedLambda,riskScore:a.riskScore,status:a.status,weakPoints:a.weakPoints,suggestions:a.suggestions}}catch{}return{success:!0,data:t}}catch(e){return{success:!1,error:`Failed to get fleet health: ${w(e)}`}}}async function xD(){if(tc(),Dc(),fl(),P.workflowOrchestrator&&(await P.workflowOrchestrator.dispose(),P.workflowOrchestrator=null),P.queen&&(await P.queen.dispose(),P.queen=null),P.router){try{let{unsubscribeTrajectoryEvents:o}=await import("./task-handlers-S2TX5FTR.js");o(P.router)}catch{}await P.router.dispose(),P.router=null}P.kernel&&(await P.kernel.dispose(),P.kernel=null),P.initialized=!1,P.fleetId=null,P.initTime=null,P.topology="hierarchical",P.agentLevels.clear()}async function AD(){let o=performance.now();try{let e=nt(),t=P.initTime?Date.now()-P.initTime.getTime():0,n={connected:!1,totalEntries:0,namespaces:0},r={enabled:!1,vectorCount:0},i=0;if(e&&P.kernel){let d=P.kernel.memory;try{n.connected=!0;let u=await d.count("default"),m=await d.count("learning"),p=await d.count("patterns");n.totalEntries=u+m+p;let g=0;for(let f of["default","learning","patterns","mcp-tools","coordination"])await d.count(f)>0&&g++;n.namespaces=g}catch{}try{let u=process.env.AQE_V3_HNSW_ENABLED==="true";r.enabled=u;let m=d;u&&typeof m.vectorCount=="function"&&(r.vectorCount=await m.vectorCount())}catch{}try{i=(await d.search("pattern:*",1e3)).length}catch{}}let s=e&&P.kernel?(P.kernel.getLoadedDomains?.()??ig).length:0,a=null;try{let{getSharedRvfDualWriterSync:d}=await import("./shared-rvf-dual-writer-EYAVY2GZ.js"),u=d();if(u){let m=u.status(),p=u.getDivergenceReport();a={mode:m.mode,vectorCount:m.rvf?.totalVectors??0,divergences:p.divergences,promotionSafe:u.isPromotionSafe()}}}catch{}let c=null;try{let{SQLitePatternStore:d}=await import("./sqlite-persistence-IVE4SQXR.js"),u=new d;await u.initialize(),c=u.getGhostPatternCount(),u.close()}catch{}return{success:!0,data:{status:e?"healthy":"unhealthy",version:"3.15.17",loadedDomains:s,memory:n,hnsw:r,rvf:a??void 0,ghostPatterns:c??void 0,loadedPatterns:i,uptimeMs:t,timestamp:new Date().toISOString()},metadata:{executionTime:performance.now()-o,timestamp:new Date().toISOString(),requestId:U(),toolName:"aqe_health"}}}catch(e){return{success:!1,error:w(e),metadata:{executionTime:performance.now()-o,timestamp:new Date().toISOString(),requestId:U(),toolName:"aqe_health"}}}}function sg(o,e){let t=o.getDomainAPI("requirements-validation");t?.registerWorkflowActions&&(t.registerWorkflowActions(e),console.log("[Fleet] Registered requirements-validation workflow actions (includes QCSD Ideation)"));let n=o.getDomainAPI("visual-accessibility");n?.registerWorkflowActions&&(n.registerWorkflowActions(e),console.log("[Fleet] Registered visual-accessibility workflow actions"))}export{cf as a,Nn as b,Qd as c,Mt as d,nt as e,bD as f,CD as g,SD as h,TD as i,ED as j,wD as k,RD as l,PD as m,xD as n,AD as o};
748
+ `).run(t.status==="completed"?"completed":t.status==="cancelled"?"cancelled":"failed",i,s,t.planId))}catch(i){console.warn("[PlanExecutor] Failed to update goap_plans status (non-fatal):",i)}}async updateActionStats(e,t,n){try{"updateActionStats"in this.planner&&await this.planner.updateActionStats(e,t,n)}catch(r){console.warn("[PlanExecutor] Failed to update action stats:",r)}}meetsConditions(e,t){for(let[n,r]of Object.entries(t))if(!this.checkCondition(e,n,r))return!1;return!0}checkCondition(e,t,n){let r=this.getStateValue(e,t);return typeof n=="string"||typeof n=="number"||typeof n=="boolean"?r===n:!(typeof n=="object"&&n!==null&&("min"in n&&n.min!==void 0&&(typeof r!="number"||r<n.min)||"max"in n&&n.max!==void 0&&(typeof r!="number"||r>n.max)||"eq"in n&&n.eq!==void 0&&r!==n.eq))}applyEffects(e,t){let n=this.cloneState(e);for(let[r,i]of Object.entries(t))this.applyEffect(n,r,i);return n}applyEffect(e,t,n){if(typeof n=="string"||typeof n=="number"||typeof n=="boolean"){this.setStateValue(e,t,n);return}if(typeof n=="object"&&n!==null){let r=this.getStateValue(e,t);if("set"in n&&n.set!==void 0&&this.setStateValue(e,t,n.set),"delta"in n&&n.delta!==void 0&&typeof r=="number"){let i=Math.max(0,Math.min(100,r+n.delta));this.setStateValue(e,t,i)}}}getStateValue(e,t){let n=t.split("."),r=e;for(let i of n){if(r==null||typeof r!="object"||!Object.hasOwn(r,i))return;r=r[i]}return r}setStateValue(e,t,n){let r=t.split("."),i=new Set(["__proto__","constructor","prototype"]);for(let c of r)if(i.has(c)){console.warn(`[PlanExecutor] Blocked prototype pollution attempt: ${t}`);return}let s=e;for(let c=0;c<r.length-1;c++){let l=r[c];Object.hasOwn(s,l)||Object.defineProperty(s,l,{value:Object.create(null),writable:!0,enumerable:!0,configurable:!0});let u=Object.getOwnPropertyDescriptor(s,l);if(!u)return;s=u.value}let a=r[r.length-1];Object.defineProperty(s,a,{value:n,writable:!0,enumerable:!0,configurable:!0})}cloneState(e){return{coverage:{...e.coverage},quality:{...e.quality},fleet:{...e.fleet,availableAgents:[...e.fleet.availableAgents]},resources:{...e.resources},context:{...e.context},patterns:{...e.patterns}}}delay(e){return new Promise(t=>setTimeout(t,e))}async close(){this.currentExecution&&await this.cancel(),this.db&&(this.unifiedMemory?console.log("[PlanExecutor] Detached from unified storage (not closing shared connection)"):(this.db.close(),console.log("[PlanExecutor] Database closed"))),this.unifiedMemory=null,this.initialized=!1}},ut=class{successRate;executionDelay;constructor(e){this.successRate=e?.successRate??1,this.executionDelay=e?.executionDelay??100}async spawn(e,t){await new Promise(i=>setTimeout(i,this.executionDelay));let n=be()<this.successRate,r=`mock-agent-${Yi().slice(0,8)}`;return n?{agentId:r,output:`Successfully executed task for ${e}: ${t.slice(0,50)}...`,success:!0}:{agentId:r,output:"",success:!1,error:`Simulated failure for ${e}`}}};function Ji(o,e){let t=new ut({successRate:e?.successRate??1});return new lt(o,t,e?.dbPath,e?.config)}import*as hr from"fs";import*as ns from"path";Et();var vp=["coverage.line","coverage.branch","coverage.function","coverage.target","coverage.measured","quality.testsPassing","quality.totalTests","quality.securityScore","quality.performanceScore","fleet.activeAgents","fleet.availableAgents","fleet.maxAgents","resources.timeRemaining","resources.memoryAvailable","resources.parallelSlots","context.environment","context.riskLevel","patterns.available","patterns.reusable"],nl=ns.join("coverage","coverage-summary.json"),bp=32*1024*1024;async function Cp(){try{let{getFleetState:o,isFleetInitialized:e}=await import("./core-handlers-5EFOJ37H.js");if(!e())return null;let{queen:t,kernel:n}=o();if(!t||!n)return null;let r=t.listAllAgents(),i=[...new Set(r.filter(s=>s.status==="running"||s.status==="idle").map(s=>s.type))].sort();return{activeAgents:r.filter(s=>s.status==="running").length,maxAgents:n.getConfig().maxConcurrentAgents,availableAgents:i}}catch{return null}}function Zi(o){return typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=100}function Sp(o=ze()){let e=ns.join(o,nl);try{let t=hr.statSync(e);if(!t.isFile()||t.size>bp)return null;let n=JSON.parse(hr.readFileSync(e,"utf-8")),r=n.total?.lines?.pct,i=n.total?.branches?.pct,s=n.total?.functions?.pct;return!Zi(r)||!Zi(i)||!Zi(s)?null:{line:r,branch:i,function:s,source:nl,measuredAt:t.mtime.toISOString()}}catch{return null}}function Tp(){let o=Qi;return{coverage:{...o.coverage},quality:{...o.quality},fleet:{...o.fleet,availableAgents:[...o.fleet.availableAgents]},resources:{...o.resources},context:{...o.context},patterns:{...o.patterns}}}async function $t(o={}){let e=Tp(),t={};for(let s of vp)t[s]="default";let n=await(o.readFleet??Cp)();n&&(e.fleet.activeAgents=n.activeAgents,e.fleet.maxAgents=n.maxAgents,e.fleet.availableAgents=[...n.availableAgents],t["fleet.activeAgents"]="live",t["fleet.maxAgents"]="live",t["fleet.availableAgents"]="live");let r=(o.readCoverage??(()=>Sp()))(),i;if(r){e.coverage.line=r.line,e.coverage.branch=r.branch,e.coverage.function=r.function,e.coverage.measured=!0;for(let s of["coverage.line","coverage.branch","coverage.function","coverage.measured"])t[s]="measured";i={source:r.source,measuredAt:r.measuredAt}}return{state:e,provenance:t,fleetInitialized:n!==null,coverageReport:i}}var Le=o=>typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=100?null:"a number between 0 and 100",dt=o=>typeof o=="number"&&Number.isInteger(o)&&o>=0?null:"a non-negative integer",rl=o=>typeof o=="number"&&Number.isFinite(o)&&o>=0?null:"a non-negative number",Ep=o=>typeof o=="boolean"?null:"a boolean",wp=o=>Array.isArray(o)&&o.every(e=>typeof e=="string")?null:"an array of strings",il=(...o)=>e=>typeof e=="string"&&o.includes(e)?null:`one of ${o.join(", ")}`,Rp={"coverage.line":Le,"coverage.branch":Le,"coverage.function":Le,"coverage.target":Le,"coverage.measured":Ep,"quality.testsPassing":Le,"quality.totalTests":dt,"quality.securityScore":Le,"quality.performanceScore":Le,"fleet.activeAgents":dt,"fleet.availableAgents":wp,"fleet.maxAgents":dt,"resources.timeRemaining":rl,"resources.memoryAvailable":rl,"resources.parallelSlots":dt,"context.environment":il("development","staging","production"),"context.riskLevel":il("low","medium","high"),"patterns.available":dt,"patterns.reusable":dt},ts=["coverage","quality","fleet","resources","context","patterns"],es=null;function Pp(){if(!es){let o=new Set;for(let e of ye()){for(let t of Object.keys(e.preconditions))o.add(t);for(let t of Object.keys(e.effects))o.add(t)}for(let e of ct)for(let t of Object.keys(e.conditions))o.add(t);es=o}return es}function sl(o,e=[]){if(typeof o!="object"||o===null||Array.isArray(o))return"currentState must be an object";let t=new Set([...Pp(),...e]);for(let[n,r]of Object.entries(o)){if(!ts.includes(n))return`currentState.${n} is not a world-state section (expected one of ${ts.join(", ")})`;if(typeof r!="object"||r===null||Array.isArray(r))return`currentState.${n} must be an object`;for(let[i,s]of Object.entries(r)){let a=`${n}.${i}`,c=Rp[a];if(c){let l=c(s);if(l)return`currentState.${a} must be ${l}, got ${JSON.stringify(s)}`;continue}if(!t.has(a))return`currentState.${a} is not a known world-state field`;if(typeof s!="boolean"&&typeof s!="string"&&!(typeof s=="number"&&Number.isFinite(s)))return`currentState.${a} must be a boolean, string or finite number, got ${JSON.stringify(s)}`}}return null}function al(o,e){let t=o.state,n={...o.provenance};for(let r of ts){let i=e[r];if(!(typeof i!="object"||i===null||Array.isArray(i)))for(let[s,a]of Object.entries(i))s==="__proto__"||s==="constructor"||s==="prototype"||(t[r][s]=Array.isArray(a)?[...a]:a,n[`${r}.${s}`]="caller")}return{...o,provenance:n}}function yr(o){return Object.entries(o).filter(([,e])=>e==="default").map(([e])=>e).sort()}var ol=["maxCost","maxDurationMs","maxSteps","requiredAgentTypes","excludedActions"],Gt=class extends A{constructor(t={}){super();this.worldStateSources=t}worldStateSources;planner=null;config={name:"qe/planning/goap_plan",description:'Find optimal action plan to achieve a QE goal using A* search. Supports named goals (e.g., "achieve-90-percent-coverage") or custom goal conditions.',domain:"coordination",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{goal:{type:"string",description:'Goal name (e.g., "achieve-90-percent-coverage") or custom goal conditions as JSON object'},currentState:{type:"object",description:"Current world state (auto-detected if not provided). Contains coverage, quality, fleet, resources, context, and patterns."},constraints:{type:"object",description:"Plan constraints",properties:{maxCost:{type:"number",description:"Maximum total cost allowed"},maxDurationMs:{type:"number",description:"Maximum total duration in milliseconds"},maxSteps:{type:"number",description:"Maximum number of steps (actions) in the plan; positive integer",minimum:1},requiredAgentTypes:{type:"array",description:"Only use actions that these agent types can execute",items:{type:"string",description:"Agent type"}},excludedActions:{type:"array",description:"Exclude these specific action IDs",items:{type:"string",description:"Action ID"}}}}},required:["goal"]}}async getPlanner(){return this.planner||(this.planner=Fe(),await this.planner.initialize()),this.planner}resetInstanceCache(){this.planner=null}async execute(t,n){try{let r=this.validateConstraints(t.constraints);if(r)return{success:!1,error:r};let i=await this.getPlanner(),s;if(typeof t.goal=="string"){let m=await i.getGoals(),p=m.find(f=>f.name===t.goal);if(!p){let f=m.map(g=>g.name).join(", ");return{success:!1,error:`Unknown goal: ${t.goal}. Available goals: ${f||"none (seed actions first)"}`}}s=p.conditions}else s=t.goal;if(t.currentState!==void 0){let m=sl(t.currentState,[...i.getReferencedStateKeys(),...Object.keys(s)]);if(m)return{success:!1,error:`Invalid currentState: ${m}`}}let a=t.currentState?al(await $t(this.worldStateSources),t.currentState):await $t(this.worldStateSources),c=a.state,l=yr(a.provenance),u=t.constraints?{maxCost:t.constraints.maxCost,maxDurationMs:t.constraints.maxDurationMs,maxSteps:t.constraints.maxSteps,requiredAgentTypes:t.constraints.requiredAgentTypes,excludedActions:t.constraints.excludedActions}:void 0,d=await i.findPlan(c,s,u);return d?(l.length===0?this.markAsRealData():this.markAsEstimatedData(),{success:!0,data:{planId:d.id,goal:t.goal,actions:d.actions.map(m=>({name:m.name,agentType:m.agentType,cost:m.cost,category:m.category,description:m.description})),totalCost:d.totalCost,estimatedDurationMs:d.estimatedDurationMs,stepCount:d.actions.length,reusedFrom:d.reusedFrom,similarityScore:d.similarityScore,stateProvenance:a.provenance,defaultedFields:l}}):{success:!1,error:`No valid plan found for the given goal and constraints${u?.maxSteps!==void 0?` (maxSteps: ${u.maxSteps} \u2014 the goal may need more steps)`:""}. Try relaxing constraints or seeding more actions.`}}catch(r){return{success:!1,error:w(r)}}}validateConstraints(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return"constraints must be an object";let n=t,r=Object.keys(n).filter(s=>!ol.includes(s));if(r.length>0)return`Unknown constraint(s): ${r.join(", ")}. Supported constraints: ${ol.join(", ")}`;for(let s of["maxCost","maxDurationMs"]){let a=n[s];if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)||a<0))return`constraints.${s} must be a non-negative number, got ${String(a)}`}let i=qt(n.maxSteps);if(i)return i;for(let s of["requiredAgentTypes","excludedActions"]){let a=n[s];if(a!==void 0&&(!Array.isArray(a)||!a.every(c=>typeof c=="string")))return`constraints.${s} must be an array of strings`}return null}};M();var jt=class extends A{planner=null;executor=null;config={name:"qe/planning/goap_execute",description:"Execute a GOAP plan. Each action dispatches to a real domain API method when the action is marked implemented and a kernel is available (run fleet_init first); actions with no real implementation, or with no domain/kernel available, fail with a specific reason rather than reporting a fabricated success. Supports dry-run mode to preview the plan without executing anything.",domain:"coordination",schema:this.buildSchema(),timeout:3e5};buildSchema(){return{type:"object",properties:{planId:{type:"string",description:"ID of plan to execute (from goap_plan result)"},dryRun:{type:"boolean",description:"Simulate execution without spawning agents (default: false)",default:!1},stepByStep:{type:"boolean",description:"Execute one step at a time (default: false)",default:!1},maxRetries:{type:"number",description:"Max retries per failed step (default: 2)",default:2,minimum:0,maximum:5}},required:["planId"]}}async getPlanner(){return this.planner||(this.planner=Fe(),await this.planner.initialize()),this.planner}async getExecutor(e){if(!this.executor){let t=await this.getPlanner(),n=r=>e?.getDomainAPI(r);this.executor=new lt(t,new ut,void 0,{maxRetries:2,stepTimeoutMs:6e4,replanOnFailure:!0,parallelExecution:!1,recordWorldState:!0},n),await this.executor.initialize()}return this.executor}resetInstanceCache(){this.planner=null,this.executor=null}async execute(e,t){try{let r=await(await this.getPlanner()).getPlan(e.planId);if(!r)return{success:!1,error:`Plan not found: ${e.planId}. Create a plan first using goap_plan.`};if(e.dryRun)return this.markAsRealData(),{success:!0,data:{planId:r.id,mode:"dry-run",status:"completed",stepsCompleted:r.actions.length,stepsFailed:0,totalDurationMs:r.estimatedDurationMs,steps:r.actions.map(c=>({action:c.name,status:"would-execute",retries:0,durationMs:c.estimatedDurationMs}))}};let i=await yn(t),s=await this.getExecutor(i);if(s.isExecuting())return{success:!1,error:"Another plan is currently executing. Wait for completion or cancel it."};let a=await s.execute(r,r.initialState);return this.markAsRealData(),{success:a.status==="completed",data:{planId:a.planId,mode:"execution",status:a.status,stepsCompleted:a.stepsCompleted,stepsFailed:a.stepsFailed,totalDurationMs:a.totalDurationMs,steps:a.steps.map(c=>({action:c.action.name,status:c.status,retries:c.retries,durationMs:c.durationMs,error:c.error})),error:a.error},error:a.status!=="completed"?a.error:void 0}}catch(n){return{success:!1,error:w(n)}}}};M();var rs=["pending","executing","completed","failed","cancelled"],zt=class extends A{constructor(t={}){super();this.worldStateSources=t}worldStateSources;planner=null;executor=null;config={name:"qe/planning/goap_status",description:"Get GOAP system status: world state, available goals, actions, or plans. Use to understand current state and available planning options.",domain:"coordination",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{type:{type:"string",description:"What to get status of",enum:["world","goals","actions","plans","execution"]},filter:{type:"object",description:"Optional filters",properties:{category:{type:"string",description:"Filter actions by category (test, security, coverage, etc.)"},status:{type:"string",description:"Filter plans by status (pending, executing, completed, failed, cancelled)",enum:[...rs]},limit:{type:"number",description:"Maximum number of results (default: 20)",default:20,minimum:1,maximum:100}}}},required:["type"]}}async getPlanner(){return this.planner||(this.planner=Fe(),await this.planner.initialize()),this.planner}async getExecutor(){if(!this.executor){let t=await this.getPlanner();this.executor=Ji(t),await this.executor.initialize()}return this.executor}resetInstanceCache(){this.planner=null,this.executor=null}async execute(t,n){try{switch(t.type){case"world":return this.getWorldState();case"goals":return this.getGoals();case"actions":return this.getActions(t.filter?.category,t.filter?.limit);case"plans":return this.getPlans(t.filter?.status,t.filter?.limit);case"execution":return this.getExecutionStatus();default:return{success:!1,error:`Unknown status type: ${t.type}`}}}catch(r){return{success:!1,error:w(r)}}}async getWorldState(){let t=await $t(this.worldStateSources),{state:n,provenance:r}=t,i=l=>r[l]!=="default",s=(l,u)=>i(l)?u:null,a=yr(r);return["coverage.line","coverage.branch","coverage.function","quality.testsPassing","quality.securityScore","quality.performanceScore","fleet.activeAgents","fleet.maxAgents","resources.timeRemaining","resources.parallelSlots"].every(i)?this.markAsRealData():this.markAsEstimatedData(),{success:!0,data:{type:"world",data:{coverage:{line:s("coverage.line",n.coverage.line),branch:s("coverage.branch",n.coverage.branch),function:s("coverage.function",n.coverage.function),measured:n.coverage.measured,...t.coverageReport?{report:t.coverageReport}:{}},quality:{testsPassing:s("quality.testsPassing",n.quality.testsPassing),securityScore:s("quality.securityScore",n.quality.securityScore),performanceScore:s("quality.performanceScore",n.quality.performanceScore)},fleet:{initialized:t.fleetInitialized,activeAgents:n.fleet.activeAgents,maxAgents:s("fleet.maxAgents",n.fleet.maxAgents),availableAgents:[...n.fleet.availableAgents]},resources:{timeRemaining:s("resources.timeRemaining",n.resources.timeRemaining),parallelSlots:s("resources.parallelSlots",n.resources.parallelSlots)},provenance:r,defaultedFields:a}}}}async getGoals(){let n=await(await this.getPlanner()).getGoals();return this.markAsRealData(),{success:!0,data:{type:"goals",data:{goals:n.map(r=>({id:r.id,name:r.name,description:r.description,priority:r.priority,conditionCount:Object.keys(r.conditions).length})),count:n.length}}}}async getActions(t,n=50){let r=[],i=ye(),s=t?i.filter(c=>c.category===t):i;r=s.slice(0,n).map((c,l)=>({id:`action-${l}`,name:c.name,category:c.category,agentType:c.agentType,cost:c.cost,successRate:c.successRate}));let a={};for(let c of i)a[c.category]=(a[c.category]||0)+1;return this.markAsRealData(),{success:!0,data:{type:"actions",data:{actions:r,count:s.length,byCategory:a}}}}async getPlans(t,n=20){if(t!==void 0&&!rs.includes(t))return{success:!1,error:`filter.status must be one of: ${rs.join(", ")}`};let r=await this.getPlanner(),[{plans:i,count:s,invalidPlanIds:a},c]=await Promise.all([r.listPlanSummaries(t,n),r.getPlanReuseStats()]);return this.markAsRealData(),{success:!0,data:{type:"plans",data:{plans:i,count:s,...a?{invalidPlanIds:a}:{},reuseStats:{totalPlans:c.totalPlans,reusedPlans:c.reusedPlans,reuseRate:c.reuseRate,avgSuccessRate:c.avgSuccessRate}}}}}async getExecutionStatus(){let n=(await this.getExecutor()).isExecuting();return this.markAsRealData(),{success:!0,data:{type:"execution",data:{isExecuting:n,message:n?"Plan execution in progress":"No active execution"}}}}};M();tn();ge();M();M();tn();var Ut={HEALTH:"qe/mincut/health",ANALYZE:"qe/mincut/analyze",STRENGTHEN:"qe/mincut/strengthen"};function os(){return Ar()}function _p(){return kr()}var is=class extends A{config={name:Ut.HEALTH,description:"Analyze swarm topology health using MinCut algorithms. Reports connectivity, weak points, and health trends.",domain:"coordination",schema:{type:"object",properties:{agents:{type:"array",description:"Agent vertices to add to the graph before analysis",items:{type:"object",description:"Agent vertex { id, domain, weight? }"}},edges:{type:"array",description:"Edges to add between agents",items:{type:"object",description:"Edge { source, target, weight? }"}},includeWeakVertices:{type:"boolean",description:"Include detailed weak vertex analysis",default:!0},includeHistory:{type:"boolean",description:"Include historical health data",default:!1}},additionalProperties:!0}};async execute(e,t){let n=os(),r=_p(),i=Se();if(e.agents)for(let l of e.agents)n.hasVertex(l.id)||n.addVertex({id:l.id,type:"agent",domain:l.domain,weight:l.weight??1,createdAt:new Date});if(e.edges)for(let l of e.edges)n.hasVertex(l.source)&&n.hasVertex(l.target)&&(n.hasEdge(l.source,l.target)||n.addEdge({source:l.source,target:l.target,weight:l.weight??1,type:"coordination",bidirectional:!0}));let s=r.checkHealth(),a=e.includeWeakVertices!==!1?i.findWeakVertices(n):[],c={health:{status:s.status,minCutValue:s.minCutValue,healthyThreshold:s.healthyThreshold,warningThreshold:s.warningThreshold,weakVertexCount:s.weakVertexCount,trend:s.trend},topology:{vertexCount:n.vertexCount,edgeCount:n.edgeCount,isConnected:n.isConnected()}};return e.includeWeakVertices!==!1&&a.length>0&&(c.weakVertices=a.map(l=>({id:l.vertexId,domain:l.vertex?.domain,weightedDegree:l.weightedDegree,riskScore:l.riskScore,reason:l.reason}))),e.includeHistory&&(c.history=s.history.map(l=>({timestamp:l.timestamp,value:l.value}))),this.markAsRealData(),{success:!0,data:c,metadata:this.createMetadata(t.startTime,t.requestId)}}},ss=class extends A{config={name:Ut.ANALYZE,description:"Deep analysis of swarm topology using MinCut algorithms. Identifies weak points, suggests improvements.",domain:"coordination",schema:{type:"object",properties:{weaknessThreshold:{type:"number",description:"Threshold for weak vertex detection"},includePartitioningPoints:{type:"boolean",description:"Include analysis of potential partitioning points",default:!1}},additionalProperties:!0}};async execute(e,t){let n=os(),r=Se(),i=r.getMinCutValue(n),s=r.getMinDegreeVertex(n),a=r.findWeakVertices(n,e.weaknessThreshold),c=r.suggestEdgeAdditions(n,2),l={minCutValue:i,minDegreeVertex:s,weakVertices:a.map(u=>({id:u.vertexId,weightedDegree:u.weightedDegree,riskScore:u.riskScore,reason:u.reason,suggestions:u.suggestions.map(d=>({type:d.type,priority:d.priority,estimatedImprovement:d.estimatedImprovement}))})),suggestedEdges:c.map(u=>({source:u.source,target:u.target,weight:u.weight}))};return e.includePartitioningPoints&&(l.partitioningPoints=r.findPartitioningPoints(n)),this.markAsRealData(),{success:!0,data:l,metadata:this.createMetadata(t.startTime,t.requestId)}}},as=class extends A{config={name:Ut.STRENGTHEN,description:"Strengthen swarm topology by adding edges between weak and strong vertices.",domain:"coordination",schema:{type:"object",properties:{targetImprovement:{type:"number",description:"Target improvement in MinCut value",default:1},targetVertices:{type:"array",description:"Specific vertices to strengthen",items:{type:"string",description:"Vertex ID"}},apply:{type:"boolean",description:"Apply changes (true) or simulate (false)",default:!1}},additionalProperties:!0}};async execute(e,t){let n=os(),r=Se(),i=r.getMinCutValue(n),s=e.targetImprovement??1,a=r.suggestEdgeAdditions(n,s),c=[];if(e.apply)for(let u of a)n.addEdge({source:u.source,target:u.target,weight:u.weight,type:"coordination",bidirectional:!0}),c.push({type:"add_edge",source:u.source,target:u.target,weight:u.weight});else for(let u of a)c.push({type:"add_edge",source:u.source,target:u.target,weight:u.weight});let l=r.getMinCutValue(n);return this.markAsRealData(),{success:!0,data:{beforeMinCut:i,afterMinCut:e.apply?l:i+s,improvement:e.apply?l-i:s,actionsApplied:c,applied:e.apply??!1},metadata:this.createMetadata(t.startTime,t.requestId)}}},ul=[new is,new ss,new as];M();var cs=null,vr=null;async function Bt(){return cs||vr||(vr=(async()=>{let o=Pn({embedding:{model:"all-MiniLM-L6-v2",cacheSize:1e3,normalize:!0,hyperbolic:!1,curvature:-1},autoInitialize:!1});return await o.initialize(),cs=o,console.error("[EmbeddingTool] ONNX adapter initialized"),o})(),vr)}var mt=class extends A{config={name:"qe/embeddings/generate",description:"Generate a vector embedding for text using local ONNX model",domain:"learning-optimization",schema:{type:"object",properties:{text:{type:"string",description:"Text to generate embedding for",minLength:1,maxLength:1e4},hyperbolic:{type:"boolean",description:"Use hyperbolic space for hierarchical data",default:!1}},required:["text"]}};async execute(e,t){let n=performance.now();try{let r=await Bt(),i=await r.generateEmbedding(e.text);e.hyperbolic&&(i=r.toHyperbolic(i));let s=performance.now()-n;return this.markAsRealData(),{success:!0,data:{embedding:Array.from(i.vector),dimension:i.dimensions,isHyperbolic:i.isHyperbolic,latencyMs:s,model:i.model}}}catch(r){return{success:!1,error:`Embedding generation failed: ${w(r)}`}}}},pt=class extends A{config={name:"qe/embeddings/compare",description:"Compare semantic similarity between two texts",domain:"learning-optimization",schema:{type:"object",properties:{text1:{type:"string",description:"First text to compare",minLength:1},text2:{type:"string",description:"Second text to compare",minLength:1},metric:{type:"string",description:"Similarity metric",enum:["cosine","euclidean","poincare"],default:"cosine"}},required:["text1","text2"]}};async execute(e,t){let n=performance.now();try{let r=await Bt(),i=e.metric||"cosine",s=i==="cosine"?"cosine":i==="euclidean"?"euclidean":"poincare",a=await r.compareSimilarity(e.text1,e.text2,s),c=performance.now()-n;return this.markAsRealData(),{success:!0,data:{similarity:a,metric:i,isSimilar:a>.7,latencyMs:c}}}catch(r){return{success:!1,error:`Similarity comparison failed: ${w(r)}`}}}},gt=class extends A{config={name:"qe/embeddings/search",description:"Search for semantically similar texts using vector search",domain:"learning-optimization",schema:{type:"object",properties:{query:{type:"string",description:"Query text to search for",minLength:1},namespace:{type:"string",description:"Namespace to search in",default:"default"},topK:{type:"number",description:"Number of results to return",minimum:1,maximum:100,default:10},threshold:{type:"number",description:"Minimum similarity threshold (0-1)",minimum:0,maximum:1,default:.5}},required:["query"]}};async execute(e,t){let n=performance.now();try{let i=await(await Bt()).searchByText(e.query,{metric:"cosine",topK:e.topK??10,threshold:e.threshold??.5,namespace:e.namespace}),s=performance.now()-n;return this.markAsRealData(),{success:!0,data:{results:i.map(a=>({text:a.text,score:a.score,metadata:a.metadata})),totalFound:i.length,latencyMs:s}}}catch(r){return{success:!1,error:`Search failed: ${w(r)}`}}}},ft=class extends A{config={name:"qe/embeddings/store",description:"Store text with its embedding for later retrieval",domain:"learning-optimization",schema:{type:"object",properties:{text:{type:"string",description:"Text to store",minLength:1},id:{type:"string",description:"Optional ID for the stored embedding"},namespace:{type:"string",description:"Namespace for organization",default:"default"},metadata:{type:"object",description:"Additional metadata to store"}},required:["text"]}};async execute(e,t){let n=performance.now();try{let r=await Bt(),i=e.namespace||"default",s=await r.generateAndStore(e.text,{id:e.id,namespace:i,customData:e.metadata}),a=performance.now()-n;return this.markAsRealData(),{success:!0,data:{id:s.id,namespace:s.namespace||i,latencyMs:a}}}catch(r){return{success:!1,error:`Store failed: ${w(r)}`}}}},ht=class extends A{config={name:"qe/embeddings/stats",description:"Get ONNX embedding system statistics",domain:"learning-optimization",schema:{type:"object",properties:{}}};async execute(e,t){try{let n=await Bt(),r=n.getStats(),i=await n.getHealth(),s=r.cacheHits+r.cacheMisses,a=s>0?r.cacheHits/s:0;return this.markAsRealData(),{success:!0,data:{totalGenerated:r.totalGenerated,vectorsStored:r.vectorsStored,cache:{hits:r.cacheHits,misses:r.cacheMisses,hitRate:a},model:{name:r.currentModel,dimension:r.currentModel==="all-MiniLM-L6-v2"?384:768},healthy:i.available}}}catch(n){return{success:!1,error:`Stats failed: ${w(n)}`}}}},Op=new mt,Np=new pt,Fp=new gt,Lp=new ft,qp=new ht;M();var $p={type:"object",properties:{nodes:{type:"array",description:"Array of nodes to check for coherence. Each node must have an id and embedding vector.",items:{type:"object",description:"Node with id, embedding vector, optional weight and metadata"}},energyThreshold:{type:"number",description:"Custom energy threshold for contradiction detection (default: 0.4)",minimum:0,maximum:1}},required:["nodes"]},Ht=class extends A{config={name:"qe/coherence/check",description:"Check mathematical coherence of beliefs/facts using Prime Radiant sheaf cohomology. Detects contradictions and computes coherence energy for multi-agent coordination.",domain:"learning-optimization",schema:$p,streaming:!1,timeout:3e4};coherenceService=null;async getService(){return this.coherenceService||(this.coherenceService=await Te(Ee)),this.coherenceService}resetInstanceCache(){this.coherenceService&&(this.coherenceService.dispose(),this.coherenceService=null)}async execute(e,t){let n=Date.now(),{nodes:r,energyThreshold:i=.4}=e;if(!r||r.length===0)return{success:!1,error:"At least one node is required for coherence check"};for(let s of r)if(!s.embedding||!Array.isArray(s.embedding))return{success:!1,error:`Node ${s.id} has invalid embedding - must be an array of numbers`};try{let s=await this.getService(),a=r.map(m=>({id:m.id,embedding:m.embedding,weight:m.weight??1,metadata:m.metadata})),c=await s.checkCoherence(a),l=[...c.recommendations,...this.generateAdditionalRecommendations(c,i)],u=c.contradictions.map(m=>({nodeIds:m.nodeIds,severity:String(m.severity),description:m.description||`Contradiction between nodes ${m.nodeIds[0]} and ${m.nodeIds[1]}`})),d=Date.now()-n;return this.markAsRealData(),{success:!0,data:{isCoherent:c.isCoherent,energy:c.energy,lane:c.lane,contradictions:u,recommendations:l,nodeCount:r.length,executionTimeMs:d,usedFallback:c.usedFallback}}}catch(s){return s instanceof Error&&s.message.includes("WASM")?(this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{isCoherent:!0,energy:.1,lane:"reflex",contradictions:[],recommendations:["WASM module unavailable - coherence check running in fallback mode","Install prime-radiant-advanced-wasm for full coherence verification"],nodeCount:r.length,executionTimeMs:Date.now()-n,usedFallback:!0}}):{success:!1,error:w(s)}}}generateAdditionalRecommendations(e,t){let n=[];switch(e.energy>t&&n.push(`High coherence energy (${e.energy.toFixed(3)}) detected - review contradicting beliefs`),e.lane){case"reflex":n.push("Low energy - safe for immediate execution");break;case"retrieval":n.push("Moderate energy - consider fetching additional context");break;case"heavy":n.push("High energy - deep analysis recommended");break;case"human":n.push("Critical energy - escalate to Queen coordinator");break}return n}};var Gp=["rename","framework-transfer","reordered-steps","distractor-terminology","cross-domain-transfer"],Rx=[["async-race","observe completion before assertion","await the operation","increase the timeout","completion probe","unit","vitest"],["stale-cache","invalidate on every state mutation","invalidate the cache","retry the read","freshness assertion","integration","redis"],["transaction-leak","rollback isolates each test","rollback the transaction","truncate a shared table","row-count check","database","postgres"],["clock-skew","compare times in one clock domain","inject a monotonic clock","widen the time window","clock boundary check","unit","node"],["event-loss","subscribe before publishing","register the listener first","publish twice","delivery assertion","events","eventemitter"],["resource-leak","release resources on every exit","close in a finally block","raise the pool limit","handle-count check","integration","playwright"],["eventual-consistency","poll the observable state","poll with a bounded deadline","sleep for a fixed delay","state convergence","distributed","kubernetes"],["identity-confusion","compare canonical identities","normalize the identifier","use display names","identity equality","security","oauth"],["partial-write","publish only complete state","commit through an atomic swap","ignore missing fields","atomicity check","filesystem","node"],["order-dependence","tests start from isolated state","reset state in setup","force alphabetical order","shuffle repeat","unit","jest"],["schema-drift","validate at the boundary","reject the incompatible schema","cast the payload","schema validator","api","zod"],["backpressure-loss","producer respects consumer capacity","await the drain signal","increase buffer memory","loss counter","performance","streams"],["retry-duplication","retries preserve idempotency","attach an idempotency key","disable all retries","duplicate detector","api","fetch"],["permission-bypass","authorization precedes mutation","check permission before write","hide the user interface","denial assertion","security","express"],["encoding-mismatch","encode and decode with one charset","set UTF-8 explicitly","strip non-ASCII text","round-trip equality","api","json"],["pagination-gap","cursor advances from the last item","use the returned cursor","increase page size","set equality","api","graphql"],["cancellation-leak","cancellation propagates to children","forward the abort signal","wait for natural completion","abort observation","integration","abortcontroller"],["floating-point-boundary","compare numeric results by tolerance","use an error bound","round every input","relative-error check","unit","vitest"],["locale-dependence","format under an explicit locale","pass the locale explicitly","update the snapshot locally","multi-locale check","ui","intl"],["lock-starvation","lock acquisition remains fair","queue lock waiters","raise retry count","bounded-wait check","concurrency","mutex"]].map(([o,e,t,n,r,i,s])=>({mechanism:o,invariant:e,action:t,wrongAction:n,oracle:r,domain:i,framework:s}));var jp=Object.freeze([...Gp]);hs();M();var Gx=Jt.create("qe-unified-memory");var Up={"test-suites":{dimensions:we.DIMENSIONS,M:8,efConstruction:100,efSearch:50,metric:"cosine",namespace:"test-suites-hnsw",maxElements:1e5},coverage:{dimensions:we.DIMENSIONS,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},defects:{dimensions:we.DIMENSIONS,M:32,efConstruction:400,efSearch:200,metric:"cosine",namespace:"defects-hnsw",maxElements:1e5},quality:{dimensions:we.DIMENSIONS,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"quality-hnsw",maxElements:1e5},learning:{dimensions:we.DIMENSIONS,M:24,efConstruction:300,efSearch:150,metric:"cosine",namespace:"learning-hnsw",maxElements:1e5},coordination:{dimensions:we.DIMENSIONS,M:8,efConstruction:100,efSearch:50,metric:"cosine",namespace:"coordination-hnsw",maxElements:5e4}},Bp={enableHNSW:{"test-suites":!0,coverage:!0,defects:!0,quality:!0,learning:!0,coordination:!0},defaultNamespace:"qe-unified",enableCrossDomainSearch:!0,embeddingDimension:we.DIMENSIONS};hs();M();Cs();import{randomUUID as Hp}from"crypto";var ls=Jt.create("MemoryAuditor"),us={batchSize:50,energyThreshold:.4,hotspotThreshold:.6,maxRecommendations:10},br=class{constructor(e,t,n=us){this.coherenceService=e;this.eventBus=t;this.config=n}coherenceService;eventBus;config;isAuditing=!1;async auditPatterns(e){let t=Date.now();await this.emitEvent("memory:audit_started",{totalPatterns:e.length,timestamp:new Date});try{let n=this.groupByDomain(e),r=[],i=0,s=0;for(let[p,f]of Object.entries(n)){if(f.length<2)continue;let g=this.patternsToNodes(f),h=await this.coherenceService.checkCoherence(g);s+=h.energy,i+=h.contradictions.length,h.energy>this.config.hotspotThreshold&&r.push({domain:p,patternIds:f.map(y=>y.id),energy:h.energy,description:this.describeHotspot(h,p)})}let a=Object.keys(n).length,c=a>0?s/a:0,l=await this.identifyHotspots(e),u=await this.generateRecommendations(l,e),d=Date.now()-t,m={totalPatterns:e.length,scannedPatterns:e.length,contradictionCount:i,globalEnergy:c,hotspots:l,recommendations:u,duration:d,timestamp:new Date};return await this.emitEvent("memory:audit_completed",{result:m,timestamp:new Date}),m}catch(n){try{await this.emitEvent("memory:audit_failed",{error:w(n),timestamp:new Date})}catch(r){ls.warn("Failed to emit audit_failed event",{error:w(r)})}throw n}}async identifyHotspots(e){let t=[],n=this.groupByDomain(e);for(let[r,i]of Object.entries(n)){if(i.length<2)continue;let s=this.patternsToNodes(i),a=await this.coherenceService.checkCoherence(s);a.energy>this.config.hotspotThreshold&&t.push({domain:r,patternIds:i.map(c=>c.id),energy:a.energy,description:this.describeHotspot(a,r)})}return t}async generateRecommendations(e,t){let n=[],r=new Map(t.map(i=>[i.id,i]));for(let i of e){let s=i.patternIds.map(u=>r.get(u)).filter(u=>u!==void 0),a=this.findDuplicates(s);a.length>0&&n.push({type:"merge",patternIds:a,reason:`Detected ${a.length} similar patterns in ${i.domain} domain`,priority:"high"});let c=this.findOutdated(s);c.length>0&&n.push({type:"remove",patternIds:c,reason:`Found ${c.length} outdated patterns with low usage/success`,priority:"medium"}),i.energy>.7&&n.push({type:"review",patternIds:i.patternIds,reason:`Critical coherence energy (${i.energy.toFixed(2)}) in ${i.domain}`,priority:"high"});let l=this.findBroadPatterns(s);l.length>0&&n.push({type:"split",patternIds:l,reason:`Found ${l.length} overly generic patterns that should be specialized`,priority:"low"})}return n.sort((i,s)=>this.priorityValue(s.priority)-this.priorityValue(i.priority)).slice(0,this.config.maxRecommendations)}async runBackgroundAudit(e){if(this.isAuditing){ls.warn("Audit already in progress, skipping");return}this.isAuditing=!0;try{await this.emitEvent("memory:audit_progress",{status:"fetching_patterns",timestamp:new Date});let t=await e();await this.emitEvent("memory:audit_progress",{status:"analyzing_coherence",totalPatterns:t.length,timestamp:new Date});let n=await this.auditPatterns(t);await this.emitEvent("memory:audit_progress",{status:"completed",result:n,timestamp:new Date})}catch(t){await this.emitEvent("memory:audit_progress",{status:"failed",error:w(t),timestamp:new Date})}finally{this.isAuditing=!1}}groupByDomain(e){let t=bs();for(let n of e){let r=n.qeDomain;t[r]||(t[r]=[]),t[r].push(n)}return t}patternsToNodes(e){return e.map(t=>({id:t.id,embedding:t.embedding||this.createFallbackEmbedding(t),weight:t.qualityScore,metadata:{name:t.name,description:t.description,domain:t.qeDomain,confidence:t.confidence,usageCount:t.usageCount,successRate:t.successRate}}))}createFallbackEmbedding(e){let t=`${e.name} ${e.description}`,n=[];for(let r=0;r<64;r++){let i=t.charCodeAt(r%t.length);n.push(i/255*2-1)}return n}describeHotspot(e,t){let n=e.energy.toFixed(2),r=e.contradictions.length;return r>0?`${t} has ${r} contradiction(s) with energy ${n}`:`${t} has high coherence energy (${n}) indicating potential inconsistencies`}findDuplicates(e){let t=[],n=new Map;for(let r of e){let i=this.normalizeText(`${r.name} ${r.description}`);n.has(i)||n.set(i,[]),n.get(i).push(r.id)}for(let[r,i]of n)i.length>1&&t.push(...i.slice(1));return t}findOutdated(e){return e.filter(t=>t.usageCount<5&&t.successRate<.5).map(t=>t.id)}findBroadPatterns(e){return e.filter(t=>{let n=/generic|general|common|basic/i.test(t.name),r=t.context?.tags,i=!r||r.length<2;return n||i}).map(t=>t.id)}normalizeText(e){return e.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim()}priorityValue(e){switch(e){case"high":return 3;case"medium":return 2;case"low":return 1;default:return 0}}async emitEvent(e,t){if(this.eventBus)try{await this.eventBus.publish({id:`memory-audit-${Date.now()}-${Hp().split("-")[0]}`,type:e,source:"learning-optimization",timestamp:new Date,payload:t})}catch(n){ls.warn("Failed to emit event",{eventType:e,error:w(n)})}}};function ds(o,e,t){return new br(o,e,{...us,...t})}M();var Vp={type:"object",properties:{namespace:{type:"string",description:"Namespace to audit (default: qe-patterns)",default:"qe-patterns"},maxPatterns:{type:"number",description:"Maximum patterns to scan (default: 1000)",default:1e3,minimum:1,maximum:1e4},energyThreshold:{type:"number",description:"Energy threshold for flagging issues (default: 0.4)",default:.4,minimum:0,maximum:1},includeDetails:{type:"boolean",description:"Include detailed pattern information in results",default:!1}},required:[]},Vt=class extends A{config={name:"qe/coherence/audit",description:"Audit QE memory for contradictions and coherence issues. Scans patterns, detects hotspots, and generates remediation recommendations.",domain:"learning-optimization",schema:Vp,streaming:!1,timeout:6e4};coherenceService=null;auditor=null;async getService(){return this.coherenceService||(this.coherenceService=await Te(Ee)),this.coherenceService}resetInstanceCache(){this.coherenceService&&(this.coherenceService.dispose(),this.coherenceService=null),this.auditor=null}async execute(e,t){let{namespace:n="qe-patterns",maxPatterns:r=1e3,energyThreshold:i=.4}=e;try{let s=await this.getService();this.auditor||(this.auditor=ds(s,void 0,{energyThreshold:i,hotspotThreshold:i+.2,maxRecommendations:10}));let a=await $(),c=xr(a,{namespace:n,embeddingDimension:384});await c.initialize();let l=await c.search("",{limit:r,useVectorSearch:!1}),u=l.success?l.value.map(p=>p.pattern):[],d;u.length>0?d=await this.auditor.auditPatterns(u):d={totalPatterns:0,scannedPatterns:0,contradictionCount:0,globalEnergy:0,hotspots:[],recommendations:[],duration:0,timestamp:new Date};let m=this.calculateHealthScore(d);return this.markAsRealData(),{success:!0,data:{totalPatterns:d.totalPatterns,scannedPatterns:d.scannedPatterns,contradictionCount:d.contradictionCount,globalEnergy:d.globalEnergy,hotspots:d.hotspots.map(p=>({domain:p.domain,patternIds:p.patternIds,energy:p.energy,description:p.description})),recommendations:d.recommendations.map(p=>({type:p.type,patternIds:p.patternIds,reason:p.reason,priority:p.priority})),durationMs:d.duration,timestamp:d.timestamp.toISOString(),healthScore:m}}}catch(s){return s instanceof Error&&s.message.includes("WASM")?(this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{totalPatterns:0,scannedPatterns:0,contradictionCount:0,globalEnergy:0,hotspots:[],recommendations:[{type:"review",patternIds:[],reason:"WASM module unavailable - install prime-radiant-advanced-wasm for full audit",priority:"medium"}],durationMs:0,timestamp:new Date().toISOString(),healthScore:100}}):{success:!1,error:w(s)}}}calculateHealthScore(e){let t=100;t-=Math.min(30,e.contradictionCount*5),t-=Math.min(30,e.globalEnergy*50),t-=Math.min(20,e.hotspots.length*5);let n=e.recommendations.filter(r=>r.priority==="high").length;return t-=Math.min(20,n*5),Math.max(0,Math.round(t))}};M();function Qp(o){let e="Each vote must be { agentId: string, verdict: string | number | boolean, confidence: number 0-1 }.";for(let t=0;t<o.length;t++){let n=o[t];if(typeof n!="object"||n===null||Array.isArray(n))return`votes[${t}] must be an object. ${e}`;let{agentId:r,verdict:i,confidence:s}=n;if(typeof r!="string"||r.trim()==="")return`votes[${t}].agentId must be a non-empty string. ${e}`;let a=typeof i;if(a!=="string"&&a!=="number"&&a!=="boolean")return`votes[${t}].verdict is required (string, number, or boolean), got ${i===null?"null":a}. ${e}`;if(typeof s!="number"||!Number.isFinite(s)||s<0||s>1)return`votes[${t}].confidence must be a number between 0 and 1, got ${JSON.stringify(s)??"undefined"}. ${e}`}return null}var Wp={type:"object",properties:{votes:{type:"array",description:"Array of agent votes to verify for consensus (at least 2). Each vote is an object { agentId: string, verdict: string | number | boolean, confidence: number 0-1, agentType?: string, reasoning?: string }.",items:{type:"object",description:"One agent vote",properties:{agentId:{type:"string",description:"Agent identifier",minLength:1},agentType:{type:"string",description:"Agent type (default: worker)"},confidence:{type:"number",description:"Confidence in the verdict",minimum:0,maximum:1},reasoning:{type:"string",description:"Optional reasoning text"}},required:["agentId","confidence"]}},confidenceThreshold:{type:"number",description:"Minimum confidence threshold (0-1, default: 0.5)",default:.5,minimum:0,maximum:1}},required:["votes"]},Qt=class extends A{config={name:"qe/coherence/consensus",description:"Verify multi-agent consensus mathematically using spectral analysis. Detects false consensus where agents appear to agree but have divergent beliefs.",domain:"learning-optimization",schema:Wp,streaming:!1,timeout:3e4};coherenceService=null;async getService(){return this.coherenceService||(this.coherenceService=await Te(Ee)),this.coherenceService}resetInstanceCache(){this.coherenceService&&(this.coherenceService.dispose(),this.coherenceService=null)}async execute(e,t){let n=Date.now(),{votes:r,confidenceThreshold:i=.5}=e;if(!r||r.length===0)return{success:!1,error:"At least one vote is required for consensus verification"};if(r.length<2)return{success:!1,error:"At least two votes are required to verify consensus"};let s=Qp(r);if(s)return{success:!1,error:s};try{let a=await this.getService(),c=r.map(p=>({agentId:p.agentId,agentType:p.agentType||"worker",verdict:p.verdict,confidence:p.confidence,reasoning:p.reasoning,timestamp:new Date})),l=await a.verifyConsensus(c),u=l.recommendation,d=r.reduce((p,f)=>p+f.confidence,0)/r.length;d<i&&(u=`Low average confidence (${(d*100).toFixed(1)}%) - consider gathering more evidence. `+u);let m=Date.now()-n;return this.markAsRealData(),{success:!0,data:{isValid:l.isValid,isFalseConsensus:l.isFalseConsensus,confidence:l.confidence,fiedlerValue:l.fiedlerValue,collapseRisk:l.collapseRisk,recommendation:u,usedFallback:l.usedFallback,executionTimeMs:m}}}catch(a){if(a instanceof Error&&a.message.includes("WASM")){let c=this.simpleMajorityAnalysis(r);return this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{...c,recommendation:`Running in fallback mode (simple analysis): ${Is(Ms(r))} across ${r.length} votes. Install prime-radiant-advanced-wasm for spectral consensus analysis.`,usedFallback:!0,executionTimeMs:Date.now()-n}}}return{success:!1,error:w(a)}}}simpleMajorityAnalysis(e){let t=new Map;for(let s of e){let a=String(s.verdict);t.set(a,(t.get(a)||0)+1)}let n=0;for(let s of t.values())s>n&&(n=s);let r=n/e.length,i=e.reduce((s,a)=>s+a.confidence,0)/e.length;return{isValid:r>=.5&&i>=.5,isFalseConsensus:!1,confidence:i,fiedlerValue:0,collapseRisk:1-r}}};M();var Kp={type:"object",properties:{swarmState:{type:"object",description:"Current state of the swarm including agents and task info"},riskThreshold:{type:"number",description:"Risk threshold for warning (0-1, default: 0.5)",default:.5,minimum:0,maximum:1}},required:["swarmState"]},Wt=class extends A{config={name:"qe/coherence/collapse",description:"Predict swarm collapse risk using spectral analysis. Identifies vulnerable vertices and provides mitigation recommendations.",domain:"learning-optimization",schema:Kp,streaming:!1,timeout:3e4};coherenceService=null;async getService(){return this.coherenceService||(this.coherenceService=await Te(Ee)),this.coherenceService}resetInstanceCache(){this.coherenceService&&(this.coherenceService.dispose(),this.coherenceService=null)}async execute(e,t){let n=Date.now(),{swarmState:r,riskThreshold:i=.5}=e;if(!r)return{success:!1,error:"swarmState is required"};if(!r.agents||r.agents.length<1)return{success:!1,error:"At least one agent is required in swarmState"};try{let s=await this.getService(),a={agents:r.agents.map(f=>({agentId:f.agentId,agentType:f.agentType||"worker",health:Number.isFinite(f.health)?f.health:1,beliefs:[],lastActivity:new Date,errorCount:f.errorCount??0,successRate:Number.isFinite(f.successRate)?f.successRate:1})),activeTasks:Number.isFinite(r.activeTasks)?r.activeTasks:0,pendingTasks:Number.isFinite(r.pendingTasks)?r.pendingTasks:0,errorRate:Number.isFinite(r.errorRate)?r.errorRate:0,utilization:Number.isFinite(r.utilization)?r.utilization:0,timestamp:new Date},c=await s.predictCollapse(a),l=Number.isFinite(c.risk)?c.risk:0,u=this.categorizeRisk(l),d=[...c.recommendations,...this.generateAdditionalRecommendations(c,r)],m=Date.now()-n;this.markAsRealData();let p=u==="high"||u==="critical"||u==="medium"&&l>=i;return{success:!0,data:{risk:l,isAtRisk:p,riskLevel:u,fiedlerValue:c.fiedlerValue,collapseImminent:c.collapseImminent,weakVertices:c.weakVertices,recommendations:d,executionTimeMs:m,usedFallback:c.usedFallback}}}catch(s){if(s instanceof Error&&s.message.includes("WASM")){let a=this.heuristicAnalysis(r,i);return this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{...a,recommendations:["Running in fallback mode (heuristic analysis)","Install prime-radiant-advanced-wasm for spectral collapse prediction",...a.recommendations],usedFallback:!0,executionTimeMs:Date.now()-n}}}return{success:!1,error:w(s)}}}categorizeRisk(e){return!Number.isFinite(e)||e<.25?"low":e<.5?"medium":e<.75?"high":"critical"}generateAdditionalRecommendations(e,t){let n=[];t.errorRate>.1&&n.push(`High system error rate (${(t.errorRate*100).toFixed(1)}%) - investigate root causes`),t.utilization>.85&&n.push(`High resource utilization (${(t.utilization*100).toFixed(1)}%) - consider scaling`),t.pendingTasks>t.activeTasks*2&&n.push(`Large task backlog (${t.pendingTasks} pending) - may need more agents`);let r=t.agents.filter(i=>i.health<.5);return r.length>0&&n.push(`${r.length} agent(s) with low health - consider replacement`),e.risk>=.75&&n.unshift("\u26A0\uFE0F CRITICAL: Immediate action required to prevent collapse"),n}heuristicAnalysis(e,t){let n=0,r=[],i=[],s=Number.isFinite(e.errorRate)?e.errorRate:0,a=Number.isFinite(e.utilization)?e.utilization:0,c=Number.isFinite(e.pendingTasks)?e.pendingTasks:0,l=Number.isFinite(e.activeTasks)?e.activeTasks:0,u=e.agents.map(g=>Number.isFinite(g.health)?g.health:1),d=u.length>0?u.reduce((g,h)=>g+h,0)/u.length:1;n+=(1-d)*.3,n+=Math.min(.25,s*2.5),a>.7&&(n+=(a-.7)*.5);let m=c/Math.max(1,l);m>1&&(n+=Math.min(.2,(m-1)*.1)),e.agents.forEach((g,h)=>{(u[h]<.5||(g.errorCount??0)>5)&&i.push(g.agentId)}),n=Math.min(1,n),n>=t&&(r.push("Consider reducing task load"),r.push("Monitor agent health closely")),i.length>0&&r.push(`Reinforce weak agents: ${i.join(", ")}`),n<.25&&r.push("Swarm appears stable - continue normal operations");let p=this.categorizeRisk(n),f=p==="high"||p==="critical"||p==="medium"&&n>=t;return{risk:n,isAtRisk:f,riskLevel:p,fiedlerValue:0,collapseImminent:n>=.75,weakVertices:i,recommendations:r}}};var dl=[new Ht,new Vt,new Qt,new Wt],ml={COHERENCE_CHECK:"qe/coherence/check",COHERENCE_AUDIT:"qe/coherence/audit",COHERENCE_CONSENSUS:"qe/coherence/consensus",COHERENCE_COLLAPSE:"qe/coherence/collapse"};var Kt=(S=>(S.PROBLEM_UNDERSTANDING="H1.1-problem-understanding",S.RULE_OF_THREE="H1.2-rule-of-three",S.PROBLEM_COMPLEXITY="H1.3-problem-complexity",S.USER_NEEDS_IDENTIFICATION="H2.1-user-needs-identification",S.USER_NEEDS_SUITABILITY="H2.2-user-needs-suitability",S.USER_NEEDS_VALIDATION="H2.3-user-needs-validation",S.BUSINESS_NEEDS_IDENTIFICATION="H3.1-business-needs-identification",S.USER_VS_BUSINESS_BALANCE="H3.2-user-vs-business-balance",S.KPI_IMPACT_ANALYSIS="H3.3-kpi-impact-analysis",S.ORACLE_PROBLEM_DETECTION="H4.1-oracle-problem-detection",S.WHAT_MUST_NOT_CHANGE="H4.2-what-must-not-change",S.SUPPORTING_DATA_ANALYSIS="H4.3-supporting-data-analysis",S.GUI_FLOW_IMPACT="H5.1-gui-flow-impact",S.USER_FEELINGS_IMPACT="H5.2-user-feelings-impact",S.CROSS_FUNCTIONAL_IMPACT="H5.3-cross-functional-impact",S.DATA_DEPENDENT_IMPACT="H5.4-data-dependent-impact",S.COMPETITIVE_ANALYSIS="H6.1-competitive-analysis",S.DOMAIN_INSPIRATION="H6.2-domain-inspiration",S.INNOVATIVE_SOLUTIONS="H6.3-innovative-solutions",S.EXACTNESS_AND_CLARITY="H7.1-exactness-and-clarity",S.INTUITIVE_DESIGN="H7.2-intuitive-design",S.COUNTER_INTUITIVE_DESIGN="H7.3-counter-intuitive-design",S.CONSISTENCY_ANALYSIS="H7.4-consistency-analysis",S))(Kt||{});var Cr=class{enabledHeuristics;minConfidence;constructor(e={}){this.enabledHeuristics=e.enabledHeuristics||Object.values(Kt),this.minConfidence=e.minConfidence||.7}async applyAll(e,t,n,r){let i=[];for(let s of this.enabledHeuristics){let a=await this.apply(s,e,t,n,r);i.push(a)}return i}async apply(e,t,n,r,i){let s=this.getHeuristicCategory(e),a=[],c=[],l=[],u=75;switch(e){case"H7.4-consistency-analysis":t.domMetrics?.semanticStructure?.hasHeader&&t.domMetrics?.semanticStructure?.hasFooter?(u=85,a.push("Consistent page structure with header and footer")):(u=60,l.push("Add consistent header/footer structure"));break;case"H7.2-intuitive-design":{let d=t.domMetrics?.semanticStructure?.hasNav,m=t.accessibility?.focusableElementsCount||0;d&&m>10?(u=82,a.push("Intuitive navigation and interaction design")):(u=55,c.push({description:"Navigation or interaction patterns unclear",severity:"medium"}));break}case"H7.1-exactness-and-clarity":{u=70;let d=t.domMetrics?.semanticStructure,m=[d?.hasHeader,d?.hasMain,d?.hasNav,d?.hasFooter].filter(Boolean).length;u=50+m*10,m>=3?a.push("Strong visual hierarchy with semantic HTML elements"):m>=2?(a.push("Moderate visual hierarchy - some semantic elements present"),l.push("Add more semantic HTML5 elements for clarity")):(c.push({description:"Weak visual hierarchy - missing semantic structure",severity:"high"}),l.push("Implement semantic HTML5: header, nav, main, footer")),t.metadata?.description&&t.metadata.description.length>20&&(u+=10,a.push("Page has descriptive metadata"));break}case"H7.3-counter-intuitive-design":{u=85;let d=!t.domMetrics?.semanticStructure?.hasNav&&(t.domMetrics?.interactiveElements||0)>10,m=!t.domMetrics?.semanticStructure?.hasHeader&&!t.domMetrics?.semanticStructure?.hasFooter;d&&(u=45,c.push({description:"Navigation structure may be counter-intuitive",severity:"high"}),l.push("Add semantic navigation elements")),m&&(u-=15,c.push({description:"Page structure lacks expected header/footer",severity:"medium"})),u>75&&a.push("No counter-intuitive design patterns detected");break}case"H5.2-user-feelings-impact":{let d=t.accessibility?.altTextsCoverage||0,m=t.performance?.loadTime||0,p=t.accessibility?.ariaLabelsCount||0,f=t.accessibility?.focusableElementsCount||0;u=60,d>=90?(u+=20,a.push("Excellent accessibility (90%+ alt coverage) creates inclusive, positive experience")):d>=70?(u+=12,a.push("Good accessibility creates generally positive user feelings")):d<50&&(u-=15,c.push({description:"Poor accessibility (<50% alt coverage) frustrates users with disabilities",severity:"high"}),l.push("Improve alt text coverage to at least 80% for better accessibility")),p>5&&(u+=8,a.push("Strong ARIA labeling enhances screen reader experience")),m<1500?(u+=15,a.push("Very fast load time (<1.5s) delights users")):m<2500?(u+=8,a.push("Fast load time enhances user satisfaction")):m>4e3?(u-=20,c.push({description:"Very slow load time (>4s) causes significant frustration",severity:"critical"}),l.push("Optimize page load time - target under 2.5 seconds")):m>3e3&&(u-=12,c.push({description:"Slow load time causes user frustration",severity:"high"})),t.errorIndicators?.hasErrorMessages&&(u-=12,c.push({description:"Visible errors reduce user confidence and satisfaction",severity:"high"}),l.push("Review and fix visible error messages")),f>20?(u+=5,a.push("Rich interactive elements provide user control and engagement")):f<5&&(u-=8,c.push({description:"Limited interactivity may feel restrictive",severity:"medium"})),u=Math.max(20,Math.min(100,u));break}case"H5.1-gui-flow-impact":{let d=t.domMetrics?.interactiveElements||0,m=t.domMetrics?.forms||0;d>20&&(u=75,a.push(`${d} interactive elements provide user control`)),m>0&&(a.push(`${m} forms impact user input flows`),u=Math.min(100,u+10)),d===0&&(u=30,c.push({description:"Limited user interaction capability",severity:"high"}));break}case"H5.3-cross-functional-impact":u=70,t.accessibility&&(t.accessibility.altTextsCoverage||0)<100&&a.push("Content team needed for alt text creation"),t.performance&&(t.performance.loadTime||0)>2e3&&a.push("Engineering team needed for performance optimization"),n.complexity==="complex"&&a.push("QA team needed for comprehensive testing"),u=70+a.length*5;break;case"H5.4-data-dependent-impact":t.domMetrics?.forms&&t.domMetrics.forms>0?(u=75,a.push(`${t.domMetrics.forms} forms depend on backend data processing`)):(u=50,a.push("Limited data-dependent features"));break;case"H1.1-problem-understanding":u=n.clarityScore,n.clarityScore>80?a.push("Problem is well-defined"):c.push({description:"Problem clarity needs improvement",severity:"medium"}),a.push(...n.breakdown);break;case"H1.2-rule-of-three":u=n.potentialFailures.length>=3?85:60,a.push(`${n.potentialFailures.length} potential failure modes identified`),n.potentialFailures.length<3&&l.push("Identify at least 3 potential failure modes (Rule of Three)");break;case"H1.3-problem-complexity":u=n.complexity==="simple"?90:n.complexity==="moderate"?75:60,a.push(`Problem complexity: ${n.complexity}`);break;case"H2.1-user-needs-identification":{u=r.alignmentScore,a.push(`${r.needs.length} user needs identified`);let d=r.needs.filter(m=>m.priority==="must-have").length;a.push(`${d} must-have features`),r.challenges.length>0&&c.push({description:`${r.challenges.length} user need challenges found`,severity:"medium"});break}case"H2.2-user-needs-suitability":u=r.suitability==="excellent"?95:r.suitability==="good"?80:r.suitability==="adequate"?65:45,a.push(`User needs suitability: ${r.suitability}`);break;case"H2.3-user-needs-validation":{let d=r.needs.filter(m=>m.addressed).length;u=r.needs.length>0?d/r.needs.length*100:50,a.push(`${d}/${r.needs.length} needs validated and addressed`);break}case"H3.1-business-needs-identification":u=i.alignmentScore,a.push(`Primary goal: ${i.primaryGoal}`),a.push(`${i.kpisAffected.length} KPIs affected`),a.push(`${i.crossTeamImpact.length} cross-team impacts`);break;case"H3.2-user-vs-business-balance":{let d=100-Math.abs(r.alignmentScore-i.alignmentScore);u=d,d>80?a.push("Good balance between user and business needs"):(c.push({description:"Imbalance between user and business priorities",severity:"medium"}),l.push("Align user and business objectives more closely"));break}case"H3.3-kpi-impact-analysis":u=i.impactsKPIs?85:50,a.push(`KPIs impacted: ${i.kpisAffected.join(", ")}`),i.compromisesUX&&(c.push({description:"Business ease compromises user experience",severity:"high"}),u-=20);break;case"H4.1-oracle-problem-detection":u=75,a.push("Oracle problem detection capability active");break;case"H4.2-what-must-not-change":u=80,t.domMetrics?.semanticStructure?.hasMain&&a.push("Main content structure is immutable"),t.accessibility&&(t.accessibility.focusableElementsCount||0)>0&&a.push("Keyboard navigation support must be maintained");break;case"H4.3-supporting-data-analysis":{u=75,(t.domMetrics?.forms||0)>0||(t.domMetrics?.interactiveElements||0)>20?(u=82,a.push("Sufficient data points for informed decision-making")):(u=60,c.push({description:"Limited data for comprehensive analysis",severity:"medium"}),l.push("Collect more user interaction data"));break}case"H6.1-competitive-analysis":u=70,a.push("Competitive analysis capability available"),t.domMetrics?.semanticStructure?.hasNav&&t.domMetrics?.interactiveElements&&t.domMetrics.interactiveElements>15?(u=78,a.push("Navigation and interaction patterns follow industry standards")):l.push("Compare interaction patterns with leading competitors");break;case"H6.2-domain-inspiration":{u=72,t.accessibility&&(t.accessibility.ariaLabelsCount||0)>0?(u=80,a.push("Modern accessibility patterns show domain inspiration")):l.push("Research domain-specific design patterns and best practices");break}case"H6.3-innovative-solutions":{u=65,(t.accessibility?.landmarkRoles||0)>3?(u=75,a.push("Advanced accessibility features show innovative thinking")):l.push("Explore innovative UX patterns to differentiate experience");break}default:s==="user-needs"?u=r.alignmentScore:s==="business-needs"?u=i.alignmentScore:s==="problem"&&(u=n.clarityScore);break}return{id:e,name:this.getHeuristicName(e),category:s,applied:!0,score:Math.min(100,Math.max(0,u)),findings:a,issues:c,recommendations:l}}getHeuristicCategory(e){return e.includes("problem")?"problem":e.includes("user-needs")||e.includes("user-vs")?"user-needs":e.includes("business")?"business-needs":e.includes("oracle")||e.includes("balance")||e.includes("what-must")||e.includes("supporting-data")?"balance":e.includes("impact")||e.includes("gui-flow")||e.includes("feelings")||e.includes("cross-functional")||e.includes("data-dependent")?"impact":e.includes("competitive")||e.includes("inspiration")||e.includes("innovative")?"creativity":"design"}getHeuristicName(e){return{"H1.1-problem-understanding":"Problem Understanding","H1.2-rule-of-three":"Rule of Three","H1.3-problem-complexity":"Problem Complexity","H2.1-user-needs-identification":"User Needs Identification","H2.2-user-needs-suitability":"User Needs Suitability","H2.3-user-needs-validation":"User Needs Validation","H3.1-business-needs-identification":"Business Needs Identification","H3.2-user-vs-business-balance":"User vs Business Balance","H3.3-kpi-impact-analysis":"KPI Impact Analysis","H4.1-oracle-problem-detection":"Oracle Problem Detection","H4.2-what-must-not-change":"What Must Not Change","H4.3-supporting-data-analysis":"Supporting Data Analysis","H5.1-gui-flow-impact":"GUI Flow Impact","H5.2-user-feelings-impact":"User Feelings Impact","H5.3-cross-functional-impact":"Cross-Functional Impact","H5.4-data-dependent-impact":"Data-Dependent Impact","H6.1-competitive-analysis":"Competitive Analysis","H6.2-domain-inspiration":"Domain Inspiration","H6.3-innovative-solutions":"Innovative Solutions","H7.1-exactness-and-clarity":"Exactness & Clarity","H7.2-intuitive-design":"Intuitive Design","H7.3-counter-intuitive-design":"Counter-Intuitive Design","H7.4-consistency-analysis":"Consistency Analysis"}[e]||e}};var Sr=class{minSeverity;constructor(e="medium"){this.minSeverity=e}detect(e,t,n){let r=[];Math.abs(t.alignmentScore-n.alignmentScore)>20&&r.push({type:"user-vs-business",description:"Significant gap between user needs and business objectives",severity:"high",stakeholders:["Users","Business"],resolutionApproach:["Gather supporting data from both perspectives","Facilitate discussion between stakeholders","Find compromise solutions that address both needs"]}),(t.challenges.length>0||n.compromisesUX)&&r.push({type:"unclear-criteria",description:"Quality criteria unclear due to conflicting information",severity:"medium",missingInfo:t.challenges,resolutionApproach:["Collect missing information from stakeholders","Define clear acceptance criteria"]});let i=(e.title||"").toLowerCase(),s=(e.metadata?.description||"").toLowerCase();return(i.includes("hotel")||i.includes("booking")||i.includes("travel")||i.includes("shop")||i.includes("store")||s.includes("book"))&&(n.kpisAffected.some(a=>a.toLowerCase().includes("conversion")||a.toLowerCase().includes("engagement"))&&r.push({type:"user-vs-business",description:"Potential conflict between conversion optimization (business) and user experience quality (user trust)",severity:"medium",stakeholders:["Marketing","Product","Users"],resolutionApproach:["A/B test aggressive vs. subtle conversion tactics","Measure both conversion rate and user satisfaction metrics","Balance urgency messaging with transparent communication"]}),r.push({type:"unclear-criteria",description:"Unclear criteria for price display timing - when to show fees, taxes, and final price",severity:"medium",stakeholders:["Users","Legal","Business"],resolutionApproach:["Define regulatory compliance requirements for price display","Balance business desire for competitive base pricing vs user need for full price transparency","Establish clear standards for fee disclosure timing"]})),(i.includes("blog")||i.includes("article")||i.includes("news")||i.includes("magazine")||i.includes("testing"))&&r.push({type:"user-vs-business",description:"Content depth (user need) vs. publication frequency (business engagement goals) trade-off",severity:"low",stakeholders:["Readers","Content Team","Editorial"],resolutionApproach:["Define content quality standards and acceptance criteria","Balance editorial calendar with quality thresholds","Consider mix of in-depth and quick-read content formats"]}),(i.includes("health")||i.includes("medical")||i.includes("patient")||i.includes("care")||i.includes("nhs"))&&(r.push({type:"stakeholder-conflict",description:"Healthcare compliance requirements may conflict with streamlined user experience",severity:"medium",stakeholders:["Patients","Healthcare Providers","Compliance","Legal"],resolutionApproach:["Map regulatory requirements to UX touchpoints","Identify where compliance can be achieved without friction","Engage compliance team early in UX design reviews","Document consent and data handling requirements clearly"]}),e.accessibility&&(e.accessibility.altTextsCoverage||0)<80&&r.push({type:"technical-constraint",description:"Healthcare accessibility requirements not fully met - critical for patient inclusivity",severity:"high",stakeholders:["Patients","Accessibility Team","Legal"],resolutionApproach:["Prioritize WCAG 2.1 AA compliance for healthcare content","Ensure screen reader compatibility for medical information","Test with assistive technology users"]})),(i.includes("bank")||i.includes("finance")||i.includes("payment")||i.includes("money"))&&r.push({type:"stakeholder-conflict",description:"Security requirements vs user convenience - authentication friction vs fraud prevention",severity:"high",stakeholders:["Users","Security Team","Product","Compliance"],resolutionApproach:["Implement risk-based authentication to reduce friction for trusted sessions","Use biometrics where available for convenient yet secure access","A/B test authentication flows for security effectiveness and user completion rates"]}),((e.domMetrics?.totalElements||0)>500||(e.domMetrics?.interactiveElements||0)>50)&&r.push({type:"technical-constraint",description:"Platform technical limitations may restrict advanced UX features or accessibility enhancements",severity:"low",stakeholders:["Development","Product","Users"],resolutionApproach:["Evaluate platform capabilities and constraints","Prioritize features based on user impact vs. implementation complexity","Consider gradual enhancement approach"]}),e.performance&&(e.performance.loadTime||0)>3e3&&r.push({type:"technical-constraint",description:"Performance optimization needed but may require trade-offs with visual richness",severity:"medium",stakeholders:["Users","Development","Design"],resolutionApproach:["Profile and identify performance bottlenecks","Consider progressive loading for visual elements","Balance image quality with load time"]}),r.filter(a=>this.meetsMinimumSeverity(a.severity))}meetsMinimumSeverity(e){let t=["low","medium","high","critical"],n=t.indexOf(this.minSeverity);return t.indexOf(e)>=n}};var Tr=class o{static LOAD_TIME_FEELINGS=[[4001,1/0,"Impatient - Very slow load time causes significant frustration"],[3001,4e3,"Impatient - Slow load time causes frustration"],[2001,3e3,"Mildly Annoyed - Noticeable load time"],[0,1499,"Delighted - Fast load time enhances experience"],[1500,1999,"Satisfied - Good load time meets expectations"]];static DOMAIN_REQUIREMENTS=[[["health","medical","care"],["Must comply with healthcare accessibility standards","Must protect patient data privacy"]],[["bank","finance","payment"],["Must maintain PCI DSS compliance for payment data","Must support secure authentication flows"]]];static VISIBLE_SCORE_ADJUSTMENTS=[[["Positive","Satisfied","Delighted"],20],[["Oriented"],10],[["Frustrated","Confused","Impatient"],-15],[["Disoriented"],-10]];analyze(e,t){let n=this.analyzeEndUserFlow(e),r=this.analyzeInternalFlow(e),i=this.analyzeUserFeelings(e),s=this.analyzePerformance(e),a=this.analyzeSecurity(e),c=this.analyzeImmutableRequirements(e,t),l=this.calculateVisibleScore(n,i),u=this.calculateInvisibleScore(s,a),d=Math.round((l+u)/2);return{visible:{guiFlow:{forEndUser:n,forInternalUser:r},userFeelings:i,score:l},invisible:{performance:s,security:a,score:u},immutableRequirements:c,overallImpactScore:d}}analyzeEndUserFlow(e){let t=[],n=e.domMetrics?.interactiveElements||0,r=e.domMetrics?.forms||0;return n>0&&t.push(`${n} interactive elements affect user journey`),r>0&&t.push(`${r} forms impact user input flows`),e.domMetrics?.semanticStructure?.hasNav&&t.push("Navigation structure enables exploration flow"),e.domMetrics?.semanticStructure?.hasMain&&t.push("Clear main content area guides user focus"),t}analyzeInternalFlow(e){let t=[];return(e.domMetrics?.forms||0)>0&&t.push("Form submissions create data processing workflows"),e.domMetrics?.semanticStructure?.hasAside&&t.push("Sidebar content may require separate management"),t}analyzeUserFeelings(e){let t=[],n=e.accessibility?.altTextsCoverage||0;n>80?t.push("Positive - Good accessibility creates inclusive experience"):n>=50?t.push("Neutral - Moderate accessibility; some users may struggle"):n<50&&t.push("Frustrated - Poor accessibility excludes some users");let r=e.performance?.loadTime||0;for(let[i,s,a]of o.LOAD_TIME_FEELINGS)if(r>=i&&r<=s){t.push(a);break}return e.errorIndicators?.hasErrorMessages&&t.push("Confused - Visible errors reduce confidence"),this.analyzeStructureFeelings(e,t),t}analyzeStructureFeelings(e,t){let n=e.domMetrics?.semanticStructure;if(!n)return;let r=[n.hasHeader,n.hasNav,n.hasMain,n.hasFooter].filter(Boolean).length;r>=3?t.push("Oriented - Clear page structure helps navigation"):r<2&&t.push("Disoriented - Unclear page structure may confuse users")}analyzePerformance(e){let t=[],n=e.performance?.loadTime||0;return n>2e3&&t.push(`Load time ${n}ms impacts user retention`),e.metadata?.viewport||t.push("Missing viewport tag affects mobile performance"),e.performance?.firstContentfulPaint&&e.performance.firstContentfulPaint>2500&&t.push(`First Contentful Paint ${e.performance.firstContentfulPaint}ms delays perceived readiness`),t}analyzeSecurity(e){let t=[];return(e.domMetrics?.forms||0)>0&&t.push("Form data handling requires secure transmission"),e.accessibility&&(e.accessibility.ariaLabelsCount||0)>0&&t.push("ARIA labels may expose internal element names - review for sensitive info"),t}analyzeImmutableRequirements(e,t){let n=[];e.domMetrics?.semanticStructure?.hasMain&&n.push("Must maintain main content accessibility"),e.accessibility&&(e.accessibility.focusableElementsCount||0)>0&&n.push("Must support keyboard navigation"),t.complexity==="complex"&&n.push("Must maintain system stability with complex interactions");let r=(e.title||"").toLowerCase();for(let[i,s]of o.DOMAIN_REQUIREMENTS)i.some(a=>r.includes(a))&&n.push(...s);return n}calculateVisibleScore(e,t){let n=50;e.length>0&&(n+=15);for(let[r,i]of o.VISIBLE_SCORE_ADJUSTMENTS)t.some(s=>r.some(a=>s.includes(a)))&&(n+=i);return Math.max(0,Math.min(100,n))}calculateInvisibleScore(e,t){let n=50;return e.length===0&&(n+=20),t.length===0&&(n+=10),e.length>2&&(n-=15),Math.max(0,Math.min(100,n))}};M();var Xp={type:"object",properties:{target:{type:"string",description:"Target URL or identifier to analyze"},context:{type:"object",description:"Pre-collected QX context (optional)"},mode:{type:"string",description:"Analysis mode: full, quick, or targeted",enum:["full","quick","targeted"],default:"full"},heuristics:{type:"array",description:"Specific heuristics to apply (default: all)",items:{type:"string",description:"Heuristic name"}},minOracleSeverity:{type:"string",description:"Minimum oracle problem severity to report",enum:["low","medium","high","critical"],default:"medium"},includeCreativity:{type:"boolean",description:"Include creativity analysis from diverse domains",default:!0},includeDesign:{type:"boolean",description:"Include design quality analysis",default:!0}},required:["target"]},Xt=class extends A{config={name:"qe/qx/analyze",description:"Comprehensive Quality Experience (QX) analysis combining QA and UX perspectives. Applies 23+ programmatic heuristics, detects oracle problems, and analyzes impacts. QX = Marriage between QA (Quality Advocacy) and UX (User Experience).",domain:"quality-assessment",schema:Xp,streaming:!0,timeout:18e4};async execute(e,t){let{target:n,context:r=this.createMinimalContext(n),mode:i="full",heuristics:s,minOracleSeverity:a="medium",includeCreativity:c=!0,includeDesign:l=!0}=e;try{this.emitStream(t,{status:"starting",message:`Starting QX analysis for: ${n}`,phase:"initialization"}),this.emitStream(t,{status:"analyzing",phase:"problem-analysis"});let u=this.analyzeProblem(r);if(this.isAborted(t))return{success:!1,error:"Operation aborted"};this.emitStream(t,{status:"analyzing",phase:"user-needs"});let d=this.analyzeUserNeeds(r,u);this.emitStream(t,{status:"analyzing",phase:"business-needs"});let m=this.analyzeBusinessNeeds(r,u);this.emitStream(t,{status:"analyzing",phase:"creativity"});let p=c?this.analyzeCreativity(r,u):this.createMinimalCreativityAnalysis();this.emitStream(t,{status:"analyzing",phase:"design"});let f=l?this.analyzeDesign(r):this.createMinimalDesignAnalysis();this.emitStream(t,{status:"analyzing",phase:"oracle-detection"});let h=new Sr(a).detect(r,d,m);this.emitStream(t,{status:"analyzing",phase:"impact-analysis"});let v=new Tr().analyze(r,u);this.emitStream(t,{status:"analyzing",phase:"heuristics",count:23});let C=await new Cr({enabledHeuristics:s||Object.values(Kt)}).applyAll(r,u,d,m);this.emitStream(t,{status:"analyzing",phase:"recommendations"});let E=this.generateRecommendations(u,d,m,h,v,C),T=this.calculateOverallScore(u,d,m,p,f,v,C),S=this.scoreToGrade(T),x={overallScore:T,grade:S,timestamp:new Date().toISOString(),target:n,problemAnalysis:u,userNeeds:d,businessNeeds:m,creativityAnalysis:p,designAnalysis:f,oracleProblems:h,impactAnalysis:v,heuristics:C,recommendations:E,context:r};return this.emitStream(t,{status:"complete",score:T,grade:S,heuristicsApplied:C.length,oracleProblemsFound:h.length}),{success:!0,data:x,metadata:this.createMetadata(t.startTime,t.requestId)}}catch(u){return{success:!1,error:`QX analysis failed: ${w(u)}`}}}analyzeProblem(e){let t=e.title||"Untitled page",n=e.metadata?.description||"",r=e.errorIndicators?.hasErrorMessages||!1,i=`Evaluate quality experience of "${t}"`;n&&(i+=` - ${n.substring(0,100)}`);let s=e.domMetrics?.totalElements||0,a=e.domMetrics?.interactiveElements||0,c=e.domMetrics?.forms||0,l;s>500||a>50||c>3?l="complex":s>200||a>20||c>1?l="moderate":l="simple";let u=[];e.domMetrics?.semanticStructure?.hasNav&&u.push("Navigation structure"),c>0&&u.push(`Form interactions (${c} forms)`),a>0&&u.push(`User interactions (${a} elements)`),e.accessibility&&u.push("Accessibility compliance"),e.performance&&u.push("Performance metrics");let d=[],m=t.toLowerCase();for((m.includes("health")||m.includes("care")||m.includes("nhs"))&&(d.push({description:"Healthcare information may not be accessible to users with visual impairments",severity:"high",likelihood:"likely"}),d.push({description:"Patient journey complexity may cause confusion during registration or booking",severity:"medium",likelihood:"possible"}),d.push({description:"Emergency contact information may not be prominently visible",severity:"high",likelihood:"possible"})),e.domMetrics?.semanticStructure?.hasMain||d.push({description:"Missing main content landmark - users may struggle to find primary content",severity:"medium",likelihood:"likely"}),e.accessibility&&(e.accessibility.altTextsCoverage||0)<80&&d.push({description:"Poor image alt text coverage - screen reader users affected",severity:"high",likelihood:"very-likely"}),r&&d.push({description:"Visible error messages detected - potential usability issues",severity:"medium",likelihood:"likely"}),e.performance&&(e.performance.loadTime||0)>3e3&&d.push({description:"Slow load time - user frustration and abandonment risk",severity:"high",likelihood:"very-likely"});d.length<3;)l==="complex"?d.push({description:"Complex interaction flows may confuse first-time users",severity:"medium",likelihood:"possible"}):l==="moderate"?d.push({description:"Multiple interactive elements increase cognitive load",severity:"low",likelihood:"possible"}):d.push({description:"Limited interactivity may not meet user expectations",severity:"low",likelihood:"possible"});let p=50;return t&&t!=="Untitled page"&&(p+=15),n&&(p+=15),u.length>=3&&(p+=10),e.domMetrics?.semanticStructure?.hasMain&&(p+=10),p=Math.min(100,p),{problemStatement:i,complexity:l,breakdown:u,potentialFailures:d.slice(0,5),clarityScore:p}}analyzeUserNeeds(e,t){let n=[],r=[],i=e.domMetrics?.semanticStructure,s=e.accessibility,a=e.domMetrics?.interactiveElements||0,c=e.domMetrics?.forms||0;i?.hasNav?n.push({description:"Clear navigation to find content",priority:"must-have",addressed:!0}):(r.push("Missing navigation structure - users cannot easily explore site"),n.push({description:"Clear navigation to find content",priority:"must-have",addressed:!1})),a>0&&n.push({description:"Interactive elements for engagement",priority:"must-have",addressed:!0}),s&&(s.focusableElementsCount||0)>0?n.push({description:"Keyboard navigation support",priority:"must-have",addressed:!0}):(r.push("Limited keyboard navigation - inaccessible to some users"),n.push({description:"Keyboard navigation support",priority:"must-have",addressed:!1})),i?.hasHeader&&n.push({description:"Consistent page header for orientation",priority:"should-have",addressed:!0}),i?.hasFooter&&n.push({description:"Footer with supporting information",priority:"should-have",addressed:!0}),s&&(s.altTextsCoverage||0)>50?n.push({description:"Image descriptions for screen readers",priority:"should-have",addressed:!0}):s&&(s.altTextsCoverage||0)<50&&(r.push("Poor alt text coverage - images not accessible"),n.push({description:"Image descriptions for screen readers",priority:"should-have",addressed:!1})),e.performance&&(e.performance.loadTime||0)<3e3?n.push({description:"Fast page load time",priority:"should-have",addressed:!0}):e.performance&&(e.performance.loadTime||0)>=3e3&&(r.push("Slow load time - user frustration risk"),n.push({description:"Fast page load time",priority:"should-have",addressed:!1})),i?.hasAside&&n.push({description:"Supplementary content sections",priority:"nice-to-have",addressed:!0}),s&&(s.landmarkRoles||0)>3&&n.push({description:"Rich ARIA landmarks for navigation",priority:"nice-to-have",addressed:!0}),c>0&&n.push({description:"Form interactions for user input",priority:"nice-to-have",addressed:!0});let l=n.filter(m=>m.priority==="must-have"&&m.addressed).length,u;r.length===0&&l>=3?u="excellent":r.length<=1&&l>=2?u="good":r.length<=2&&l>=2?u="adequate":u="poor";let d=40;return d+=l*10,d+=n.filter(m=>m.priority==="should-have"&&m.addressed).length*5,d+=n.filter(m=>m.priority==="nice-to-have"&&m.addressed).length*2,d-=r.length*8,d=Math.max(0,Math.min(100,d)),{needs:n,suitability:u,challenges:r,alignmentScore:d}}analyzeBusinessNeeds(e,t){let n=e.domMetrics?.forms||0,r=e.domMetrics?.interactiveElements||0,i=e.performance,s=e.errorIndicators?.hasErrorMessages||!1,a,c=[];n>2?(a="business-ease",c=["Form completion rate","Lead generation","User sign-ups"]):r>30?(a="user-experience",c=["Time on site","Click-through rate","User engagement"]):(a="balanced",c=["Content consumption","Bounce rate","Page views"]);let l=(e.title||"").toLowerCase();(l.includes("health")||l.includes("care"))&&c.push("Patient satisfaction","Appointment completion rate","Information accessibility");let u=[];n>0&&(u.push({team:"Marketing",impactType:"positive",description:"Form conversion optimization needed"}),u.push({team:"Development",impactType:"neutral",description:"Form validation and submission handling"})),e.accessibility&&(e.accessibility.altTextsCoverage||0)<100&&u.push({team:"Content",impactType:"negative",description:"Image alt text creation required"}),i&&(i.loadTime||0)>2e3&&u.push({team:"Engineering",impactType:"negative",description:"Performance optimization needed"}),t.complexity==="complex"&&u.push({team:"QA",impactType:"neutral",description:"Comprehensive testing strategy required"});let d=!1;s&&(d=!0),e.accessibility&&(e.accessibility.altTextsCoverage||0)<50&&(d=!0),i&&(i.loadTime||0)>4e3&&(d=!0);let m=50;return c.length>0&&(m+=15),u.length>0&&(m+=10),d||(m+=20),m=Math.min(100,m),{primaryGoal:a,kpisAffected:c,crossTeamImpact:u,compromisesUX:d,impactsKPIs:c.length>0,alignmentScore:m}}analyzeCreativity(e,t){let n=[];(t.complexity==="complex"||t.complexity==="moderate")&&(n.push({description:"Question fundamental assumptions about user mental models and expected workflows",inspirationSource:"philosophy",applicability:"high",novelty:"moderately-novel"}),e.errorIndicators?.hasErrorMessages&&n.push({description:"Apply diagnostic testing - systematically isolate error sources through controlled scenarios",inspirationSource:"medicine",applicability:"high",novelty:"moderately-novel"})),e.domMetrics?.forms&&e.domMetrics.forms>0&&n.push({description:"Test checkout/form flows like fashion retail - focus on friction points, abandonment triggers",inspirationSource:"e-commerce",applicability:"high",novelty:"incremental"}),n.push({description:"Analyze through diverse demographic lenses (age, gender, culture, ability) for inclusive testing",inspirationSource:"social science",applicability:"high",novelty:"moderately-novel"}),e.domMetrics?.interactiveElements&&e.domMetrics.interactiveElements>20&&n.push({description:'Test for "game-breaking" exploits - unexpected interaction sequences, boundary conditions',inspirationSource:"gaming",applicability:"medium",novelty:"highly-novel"});let r=[...new Set(n.map(a=>a.inspirationSource))],i=["Unexperienced user perspective (fresh eyes)","Power user perspective (efficiency focus)","Accessibility perspective (assistive tech users)","International perspective (cultural differences)"],s=50;return s+=n.length*8,s+=r.length*5,s=Math.min(100,s),{innovativeApproaches:n,domainsExplored:r,perspectives:i,creativityScore:s,notes:["Creativity draws from diverse domains to uncover unconventional testing approaches","Higher complexity problems benefit from cross-disciplinary inspiration",`Applied ${n.length} creative approaches from ${r.length} domains`]}}analyzeDesign(e){let t=[],n=[];e.domMetrics?.semanticStructure?.hasNav&&t.push("Navigation structure clearly defined with semantic <nav> element"),e.domMetrics?.semanticStructure?.hasMain&&t.push("Main content area clearly identified"),e.domMetrics?.semanticStructure?.hasHeader&&e.domMetrics?.semanticStructure?.hasFooter&&t.push("Header and footer provide clear page structure");let r=e.accessibility?.ariaLabelsCount||0,i=e.domMetrics?.interactiveElements||0;i>0&&r<i*.5&&n.push("Many interactive elements lack ARIA labels for clarity");let s=50+t.length*15-n.length*10;s=Math.max(0,Math.min(100,s));let a=s>=80?"excellent":s>=60?"good":s>=40?"adequate":"poor",c=[],l=[],u=!0;e.domMetrics?.semanticStructure?.hasNav&&c.push("Standard navigation placement"),e.domMetrics?.semanticStructure?.hasHeader&&c.push("Header follows common layout conventions"),!e.domMetrics?.semanticStructure?.hasNav&&i>10&&(u=!1,l.push("Non-standard navigation pattern may confuse users from different regions"));let d=50+c.length*15;u||(d-=20),d=Math.max(0,Math.min(100,d));let m=Math.round((s+d)/2);return{exactness:{clarity:a,clearElements:t,unclearElements:n,score:s},intuitive:{followsConventions:u,intuitivePatterns:c,culturalIssues:l,score:d},counterIntuitive:{deviations:[],innovativeJustification:!1,freshEyesPerspective:!0,issuesCount:0},overallDesignScore:m}}generateRecommendations(e,t,n,r,i,s){let a=[],c=1;for(let l of s){for(let u of l.issues)(u.severity==="critical"||u.severity==="high")&&a.push({principle:l.name,recommendation:u.description,severity:u.severity,impact:u.severity==="critical"?90:75,effort:"medium",priority:c++,category:"qx"});for(let u of l.recommendations)a.push({principle:l.name,recommendation:u,severity:"medium",impact:60,effort:"medium",priority:c++,category:"qx"})}for(let l of r)a.push({principle:`Oracle: ${l.type}`,recommendation:l.description,severity:l.severity,impact:l.severity==="critical"?95:l.severity==="high"?80:60,effort:"high",priority:c++,category:"process",evidence:l.resolutionApproach});for(let l of t.challenges)a.push({principle:"User Needs",recommendation:l,severity:"medium",impact:65,effort:"medium",priority:c++,category:"ux"});return a.sort((l,u)=>{let d={critical:0,high:1,medium:2,low:3},m=d[l.severity]-d[u.severity];return m!==0?m:u.impact-l.impact}).slice(0,15)}calculateOverallScore(e,t,n,r,i,s,a){let c=a.reduce((u,d)=>u+d.score,0)/a.length||0,l=e.clarityScore*.1+t.alignmentScore*.2+n.alignmentScore*.15+r.creativityScore*.1+i.overallDesignScore*.15+(100-s.overallImpactScore)*.1+c*.2;return Math.round(Math.max(0,Math.min(100,l)))}scoreToGrade(e){return e>=90?"A":e>=80?"B":e>=70?"C":e>=60?"D":"F"}createMinimalContext(e){return{url:e,title:e}}createMinimalCreativityAnalysis(){return{innovativeApproaches:[],domainsExplored:[],perspectives:[],creativityScore:50,notes:["Creativity analysis skipped"]}}createMinimalDesignAnalysis(){return{exactness:{clarity:"adequate",clearElements:[],unclearElements:[],score:50},intuitive:{followsConventions:!0,intuitivePatterns:[],culturalIssues:[],score:50},counterIntuitive:{deviations:[],innovativeJustification:!1,freshEyesPerspective:!1,issuesCount:0},overallDesignScore:50}}emitStream(e,t){e.streaming&&e.onStream&&e.onStream(t)}isAborted(e){return e.abortSignal?.aborted||!1}createMetadata(e,t){return{executionTime:Date.now()-e,timestamp:new Date().toISOString(),requestId:t}}},CI=new Xt;var QI={TEST_GENERATE:"qe/tests/generate",TEST_EXECUTE:"qe/tests/execute",COVERAGE_ANALYZE:"qe/coverage/analyze",COVERAGE_GAPS:"qe/coverage/gaps",QUALITY_EVALUATE:"qe/quality/evaluate",QUALITY_GATE:"qe/quality/gate",DEFECT_PREDICT:"qe/defects/predict",REQUIREMENTS_VALIDATE:"qe/requirements/validate",QUALITY_CRITERIA:"qe/requirements/quality-criteria",CODE_ANALYZE:"qe/code/analyze",CODE_C4:"qe/code/c4",SECURITY_SCAN:"qe/security/scan",CONTRACT_VALIDATE:"qe/contracts/validate",VISUAL_COMPARE:"qe/visual/compare",A11Y_AUDIT:"qe/a11y/audit",CHAOS_INJECT:"qe/chaos/inject",LEARNING_OPTIMIZE:"qe/learning/optimize",LEARNING_DREAM:"qe/learning/dream",TOKEN_USAGE:"qe/analysis/token_usage",GOAP_PLAN:"qe/planning/goap_plan",GOAP_EXECUTE:"qe/planning/goap_execute",GOAP_STATUS:"qe/planning/goap_status",...Ut,EMBEDDING_GENERATE:"qe/embeddings/generate",EMBEDDING_COMPARE:"qe/embeddings/compare",EMBEDDING_SEARCH:"qe/embeddings/search",EMBEDDING_STORE:"qe/embeddings/store",EMBEDDING_STATS:"qe/embeddings/stats",...ml,QX_ANALYZE:"qe/qx/analyze",TEST_SCHEDULE:"qe/tests/schedule",LOAD_TEST:"qe/tests/load",URL_VALIDATE:"qe/security/url-validate",BROWSER_WORKFLOW:"qe/workflows/browser-load"},Yp=[new Wn,new Kn,new Yn,new Jn,new Zn,new er,new nr,new rr,new Nt,new sr,new ar,new or,new cr,new lr,new ur,new dr,new Ft,new Lt,new mr,new Gt,new jt,new zt,...ul,new mt,new pt,new gt,new ft,new ht,...dl,new Xt,new co,new lo,new uo,new mo];function pl(){for(let o of Yp)o.resetInstanceCache()}M();var Jp=wr.filter(o=>o!=="coordination"),P={fleetId:null,kernel:null,queen:null,router:null,workflowOrchestrator:null,initialized:!1,initTime:null,topology:"hierarchical",agentLevels:new Map};function It(){return P}function rt(){return P.initialized&&P.kernel!==null&&P.queen!==null}function cD(o){return rt()||(P.fleetId=`fleet-${U().slice(0,8)}`,P.kernel=o.kernel,P.queen=o.queen,P.router=o.router??null,P.workflowOrchestrator=o.workflowOrchestrator??null,P.initialized=!0,P.initTime=new Date,P.topology=o.topology??"hierarchical",P.agentLevels.clear()),P.fleetId}function lD(){return P.topology}function uD(o,e){if(P.topology!=="hierarchical"){let i={agentId:o,domain:e,level:"worker",spawnedAt:new Date};return P.agentLevels.set(o,i),"worker"}let n=Array.from(P.agentLevels.values()).find(i=>i.domain===e&&i.level==="lead")?"worker":"lead",r={agentId:o,domain:e,level:n,spawnedAt:new Date};return P.agentLevels.set(o,r),n}function dD(o){return P.agentLevels.get(o)}function mD(){return P.agentLevels}async function pD(o){try{if(P.initialized&&P.kernel&&P.queen){let l=P.kernel.getConfig();return{success:!0,data:{fleetId:P.fleetId,topology:P.topology,maxAgents:l.maxConcurrentAgents,enabledDomains:l.enabledDomains.filter(u=>u!=="coordination"),status:"ready"}}}P.fleetId=`fleet-${U().slice(0,8)}`;let e=o.enabledDomains||[...wr],t=e.filter(l=>l!=="coordination"),n=process.env.AQE_MEMORY_BACKEND==="memory"?"memory":o.memoryBackend||"hybrid";P.kernel=new Fa({maxConcurrentAgents:o.maxAgents||15,memoryBackend:n,hnswEnabled:!0,lazyLoading:o.lazyLoading!==!1,enabledDomains:e}),await P.kernel.initialize(),P.router=new qa(P.kernel.eventBus),await P.router.initialize();let r=l=>P.kernel.getDomainAPI(l),i=new po(P.kernel.eventBus,P.kernel.memory,r),s=P.kernel.plugins;await s.loadAll();let a=new Map;for(let l of s.getLoaded()){let u=s.getPlugin(l);u&&a.set(l,u)}try{let{getDaemon:l}=await import("./daemon-43MXIVH3.js"),u=l().getWorkerManager();u.setKernel(P.kernel),u.setMemory(P.kernel.memory)}catch(l){console.warn(`[fleet_init] Daemon worker manager wiring skipped: ${w(l)}`)}P.queen=La(P.kernel,P.router,i,void 0,a),await P.queen.initialize(),P.workflowOrchestrator=new Na(P.kernel.eventBus,P.kernel.memory,P.kernel.coordinator),await P.workflowOrchestrator.initialize(),Zp(P.kernel,P.workflowOrchestrator);let{subscribeTrajectoryEvents:c}=await import("./task-handlers-JRA3NXIR.js");return c(P.router),P.initialized=!0,P.initTime=new Date,P.topology=o.topology||"hierarchical",P.agentLevels.clear(),{success:!0,data:{fleetId:P.fleetId,topology:P.topology,maxAgents:o.maxAgents||15,enabledDomains:t,status:"initialized"}}}catch(e){return{success:!1,error:`Failed to initialize fleet: ${w(e)}`}}}async function gD(o){if(!rt())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{let e=P.queen.getHealth(),t=P.queen.getMetrics(),n={status:e.status,uptime:t.uptime,agents:{total:e.totalAgents,active:e.activeAgents,idle:e.totalAgents-e.activeAgents},tasks:{pending:e.pendingTasks,running:e.runningTasks,completed:t.tasksCompleted,failed:t.tasksFailed}};if(o.includeDomains){let i=[];for(let[s,a]of e.domainHealth)i.push({domain:s,status:a.status,agents:a.agents.total,load:P.queen.getDomainLoad(s)});n.domains=i}let r=P.queen.getDomainTeamManager?.();if(r){let i=r.listDomainTeams(),s=0,a=0;for(let c of i)s+=1+c.teammateIds.length,r.getTeamHealth(c.domain)?.healthy&&a++;n.teams={active:i.length,totalAgentsInTeams:s,healthyCount:a}}o.includeMetrics&&(n.metrics={tasksReceived:t.tasksReceived,tasksCompleted:t.tasksCompleted,tasksFailed:t.tasksFailed,agentUtilization:t.agentUtilization,averageTaskDuration:t.averageTaskDuration});try{let{getUnifiedMemory:i}=await import("./unified-memory-GUR3IUI6.js"),s=i();if(s.isInitialized()){let a=l=>{try{return s.queryCount(l)}catch{return 0}},c=await s.vectorCount();n.learning={totalPatterns:a("qe_patterns"),totalExperiences:a("captured_experiences"),totalTrajectories:a("qe_trajectories"),vectorCount:c,experienceApplications:a("experience_applications"),dreamCycles:a("dream_cycles"),embeddingDimension:384}}}catch{}return{success:!0,data:n}}catch(e){return{success:!1,error:`Failed to get fleet status: ${w(e)}`}}}async function fD(o){if(!rt())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{if(o.domain){let n=P.queen.getDomainHealth(o.domain);return n?{success:!0,data:{domain:o.domain,status:n.status,agents:n.agents,errors:n.errors,lastActivity:n.lastActivity?.toISOString()}}:{success:!1,error:`Domain not found: ${o.domain}`}}let e=P.queen.getHealth(),t={status:e.status,totalAgents:e.totalAgents,activeAgents:e.activeAgents,pendingTasks:e.pendingTasks,runningTasks:e.runningTasks,workStealingActive:e.workStealingActive,lastHealthCheck:e.lastHealthCheck.toISOString()};if(o.detailed){let n={};for(let[i,s]of e.domainHealth)n[i]={status:s.status,agents:s.agents,errors:s.errors.length,lastActivity:s.lastActivity?.toISOString()};t.domains=n,t.issues=e.issues.map(i=>({severity:i.severity,message:i.message,domain:i.domain,timestamp:i.timestamp.toISOString()}));let r=e.minCut;r&&(t.minCut={status:r.status,minCutValue:r.minCutValue,fleetStatus:r.fleetStatus,fleetMinCutValue:r.fleetMinCutValue,taskAgents:r.taskAgents})}try{let{StructuralHealthMonitor:n}=await import("./structural-health-4H6J4OHK.js"),r=new n,i=[];for(let[c]of e.domainHealth){let l=P.queen.getAgentsByDomain(c);for(let u of l)i.push({id:u.id,name:u.name,domain:u.domain})}let s=i.map(c=>({id:c.id,name:c.name,domain:c.domain,capabilities:[c.domain],dependsOn:[],weight:1})),a=r.computeFleetHealth(s);t.structuralHealth={lambda:a.lambda,healthy:a.healthy,normalizedLambda:a.normalizedLambda,riskScore:a.riskScore,status:a.status,weakPoints:a.weakPoints,suggestions:a.suggestions}}catch{}return{success:!0,data:t}}catch(e){return{success:!1,error:`Failed to get fleet health: ${w(e)}`}}}async function hD(){if(Zo(),Mc(),pl(),P.workflowOrchestrator&&(await P.workflowOrchestrator.dispose(),P.workflowOrchestrator=null),P.queen&&(await P.queen.dispose(),P.queen=null),P.router){try{let{unsubscribeTrajectoryEvents:o}=await import("./task-handlers-JRA3NXIR.js");o(P.router)}catch{}await P.router.dispose(),P.router=null}P.kernel&&(await P.kernel.dispose(),P.kernel=null),P.initialized=!1,P.fleetId=null,P.initTime=null,P.topology="hierarchical",P.agentLevels.clear()}async function yD(){let o=performance.now();try{let e=rt(),t=P.initTime?Date.now()-P.initTime.getTime():0,n={connected:!1,totalEntries:0,namespaces:0},r={enabled:!1,vectorCount:0},i=0;if(e&&P.kernel){let u=P.kernel.memory;try{n.connected=!0;let d=await u.count("default"),m=await u.count("learning"),p=await u.count("patterns");n.totalEntries=d+m+p;let f=0;for(let g of["default","learning","patterns","mcp-tools","coordination"])await u.count(g)>0&&f++;n.namespaces=f}catch{}try{let d=process.env.AQE_V3_HNSW_ENABLED==="true";r.enabled=d;let m=u;d&&typeof m.vectorCount=="function"&&(r.vectorCount=await m.vectorCount())}catch{}try{i=(await u.search("pattern:*",1e3)).length}catch{}}let s=e&&P.kernel?(P.kernel.getLoadedDomains?.()??Jp).length:0,a=null;try{let{getSharedRvfDualWriterSync:u}=await import("./shared-rvf-dual-writer-HVAAVEOH.js"),d=u();if(d){let m=d.status(),p=d.getDivergenceReport();a={mode:m.mode,vectorCount:m.rvf?.totalVectors??0,divergences:p.divergences,promotionSafe:d.isPromotionSafe()}}}catch{}let c=null;try{let{SQLitePatternStore:u}=await import("./sqlite-persistence-LGTIKAEX.js"),d=new u;await d.initialize(),c=d.getGhostPatternCount(),d.close()}catch{}return{success:!0,data:{status:e?"healthy":"unhealthy",version:"3.15.18",loadedDomains:s,memory:n,hnsw:r,rvf:a??void 0,ghostPatterns:c??void 0,loadedPatterns:i,uptimeMs:t,timestamp:new Date().toISOString()},metadata:{executionTime:performance.now()-o,timestamp:new Date().toISOString(),requestId:U(),toolName:"aqe_health"}}}catch(e){return{success:!1,error:w(e),metadata:{executionTime:performance.now()-o,timestamp:new Date().toISOString(),requestId:U(),toolName:"aqe_health"}}}}function Zp(o,e){let t=o.getDomainAPI("requirements-validation");t?.registerWorkflowActions&&(t.registerWorkflowActions(e),console.log("[Fleet] Registered requirements-validation workflow actions (includes QCSD Ideation)"));let n=o.getDomainAPI("visual-accessibility");n?.registerWorkflowActions&&(n.registerWorkflowActions(e),console.log("[Fleet] Registered visual-accessibility workflow actions"))}export{Kg as a,On as b,jd as c,It as d,rt as e,cD as f,lD as g,uD as h,dD as i,mD as j,pD as k,gD as l,fD as m,hD as n,yD as o};