agentic-qe 3.15.13 → 3.15.15

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 (426) hide show
  1. package/.claude/agents/v3/templates/qx-report-template.html +1 -1
  2. package/.claude/helpers/brain-checkpoint.cjs +124 -5
  3. package/.claude/skills/skills-manifest.json +1 -1
  4. package/CHANGELOG.md +124 -0
  5. package/assets/agents/v3/templates/qx-report-template.html +1 -1
  6. package/assets/skills/skills-manifest.json +1 -1
  7. package/dist/cli/bundle.js +6 -6
  8. package/dist/cli/chunks/adapter-QU6INSKP.js +2 -0
  9. package/dist/cli/chunks/agent-booster-wasm-EUF4XVUC.js +2 -0
  10. package/dist/cli/chunks/{agent-handler-AOH6TV7W.js → agent-handler-MOX6PSIQ.js} +2 -2
  11. package/dist/cli/chunks/{agent-memory-branch-2P54SF5N.js → agent-memory-branch-AEXKIGDG.js} +2 -2
  12. package/dist/cli/chunks/aqe-learning-engine-PAJPENJD.js +2 -0
  13. package/dist/cli/chunks/{arena-NSVFCAF5.js → arena-IQ5ZZDRF.js} +2 -2
  14. package/dist/cli/chunks/{arena-X6MOGQHA.js → arena-M7GA3CVG.js} +4 -4
  15. package/dist/cli/chunks/{audit-27DJLQNM.js → audit-4IPBMKWB.js} +3 -3
  16. package/dist/cli/chunks/base-OTGSN6IC.js +2 -0
  17. package/dist/cli/chunks/{better-sqlite3-BU5GXILS.js → better-sqlite3-IKDKJ2IE.js} +2 -2
  18. package/dist/cli/chunks/brain-handler-5NQUDH4W.js +95 -0
  19. package/dist/cli/chunks/{branch-enumerator-5CLULOCU.js → branch-enumerator-KSXELWRC.js} +2 -2
  20. package/dist/cli/chunks/{browser-R4DMU3LN.js → browser-6LACARWE.js} +2 -2
  21. package/dist/cli/chunks/browser-workflow-WLZGR6SB.js +2 -0
  22. package/dist/cli/chunks/{chunk-LUZNKJE6.js → chunk-22UKJGGN.js} +3 -3
  23. package/dist/cli/chunks/{chunk-BLSLEVDI.js → chunk-27HE2BHC.js} +2 -2
  24. package/dist/cli/chunks/{chunk-K4CZA77U.js → chunk-2CKERSMB.js} +2 -2
  25. package/dist/cli/chunks/{chunk-YSZ5OE3Z.js → chunk-2IIXCEMS.js} +2 -2
  26. package/dist/cli/chunks/{chunk-F3YS57NF.js → chunk-2LUTPMBO.js} +2 -2
  27. package/dist/cli/chunks/{chunk-GHM6MQNK.js → chunk-2ZFLULL4.js} +2 -2
  28. package/dist/cli/chunks/{chunk-7CMTY45A.js → chunk-337Z52QM.js} +2 -2
  29. package/dist/cli/chunks/{chunk-W26B7ERY.js → chunk-3CYNZFKH.js} +1 -1
  30. package/dist/cli/chunks/chunk-3HVFIITW.js +2 -0
  31. package/dist/cli/chunks/{chunk-K3TLLJMX.js → chunk-3J3RNJNX.js} +1 -1
  32. package/dist/cli/chunks/{chunk-MAMQA43L.js → chunk-4ATQP3PR.js} +1 -1
  33. package/dist/cli/chunks/{chunk-YXRASAPI.js → chunk-4D4CWP72.js} +2 -2
  34. package/dist/cli/chunks/{chunk-GHY6Z6KO.js → chunk-4HKAD25N.js} +3 -3
  35. package/dist/cli/chunks/{chunk-XNBOGCF3.js → chunk-4X3SWKBA.js} +2 -2
  36. package/dist/cli/chunks/{chunk-IJUHSJ2U.js → chunk-5AFVEWMT.js} +2 -2
  37. package/dist/cli/chunks/{chunk-SE4VNN4I.js → chunk-5C62XMJR.js} +3 -3
  38. package/dist/cli/chunks/{chunk-KDNJ4F3P.js → chunk-5G4UFTV4.js} +2 -2
  39. package/dist/cli/chunks/{chunk-DVGRPK7A.js → chunk-5I7357KS.js} +2 -2
  40. package/dist/cli/chunks/{chunk-YZWBNBTW.js → chunk-5KA5TVPR.js} +2 -2
  41. package/dist/cli/chunks/{chunk-JGZ722G3.js → chunk-5PTAFGJT.js} +2 -2
  42. package/dist/cli/chunks/{chunk-SVLQRAMF.js → chunk-6BRQPHMZ.js} +1 -1
  43. package/dist/cli/chunks/{chunk-KDVZND5Q.js → chunk-6KCSKGVY.js} +1 -1
  44. package/dist/cli/chunks/{chunk-LWR3FV3Y.js → chunk-6LE362LZ.js} +2 -2
  45. package/dist/cli/chunks/{chunk-WKGTGOYS.js → chunk-6NBRMD25.js} +3 -3
  46. package/dist/cli/chunks/{chunk-HQZGPJYG.js → chunk-6RBTS3NF.js} +2 -2
  47. package/dist/cli/chunks/{chunk-WOCGL4QP.js → chunk-6YVMX2TC.js} +2 -2
  48. package/dist/cli/chunks/{chunk-I3C7JOXC.js → chunk-73PBAWAF.js} +2 -2
  49. package/dist/cli/chunks/{chunk-75RDHBAX.js → chunk-74YG72NQ.js} +3 -3
  50. package/dist/cli/chunks/{chunk-O6FGXMHD.js → chunk-76P32JVU.js} +1 -1
  51. package/dist/cli/chunks/{chunk-LL7LDPXS.js → chunk-7ACCBHRB.js} +1 -1
  52. package/dist/cli/chunks/{chunk-3LJ7LQMV.js → chunk-7BLZHFKD.js} +1 -1
  53. package/dist/cli/chunks/{chunk-CM4LSLKR.js → chunk-7O45RQHF.js} +2 -2
  54. package/dist/cli/chunks/{chunk-NU3W5WFT.js → chunk-7XB3FCKM.js} +2 -2
  55. package/dist/cli/chunks/{chunk-E56B6IDX.js → chunk-AHMWD6JG.js} +2 -2
  56. package/dist/cli/chunks/{chunk-G2Q66Z23.js → chunk-AJPROCDW.js} +2 -2
  57. package/dist/cli/chunks/{chunk-NW7IBHJA.js → chunk-AKZO6GGG.js} +13 -13
  58. package/dist/cli/chunks/{chunk-IC3TQEOA.js → chunk-AOKKUB5F.js} +1 -1
  59. package/dist/cli/chunks/{chunk-4OVC4RIL.js → chunk-AP2W7Z3A.js} +1 -1
  60. package/dist/cli/chunks/{chunk-PHP5UBT4.js → chunk-BBRROA3Z.js} +2 -2
  61. package/dist/cli/chunks/{chunk-5FKWCZNF.js → chunk-BDKEAGQ2.js} +2 -2
  62. package/dist/cli/chunks/{chunk-BTVEYBW2.js → chunk-BFQTLF5X.js} +2 -2
  63. package/dist/cli/chunks/{chunk-HZ5NXFXH.js → chunk-BLL2XU7A.js} +2 -2
  64. package/dist/cli/chunks/{chunk-UTRV7T2N.js → chunk-BP5T3OEV.js} +2 -2
  65. package/dist/cli/chunks/{chunk-GB6HBNH2.js → chunk-BQ47GQPK.js} +2 -2
  66. package/dist/cli/chunks/{chunk-RFNW2LGD.js → chunk-BU4UQR36.js} +2 -2
  67. package/dist/cli/chunks/{chunk-WO274FRI.js → chunk-BZULJMGH.js} +2 -2
  68. package/dist/cli/chunks/{chunk-GU5HNCWI.js → chunk-C4KLXFJP.js} +1 -1
  69. package/dist/cli/chunks/{chunk-LFJALJOA.js → chunk-C4RTAVC6.js} +2 -2
  70. package/dist/cli/chunks/{chunk-WNQS4WTS.js → chunk-C5CXL3JP.js} +2 -2
  71. package/dist/cli/chunks/{chunk-MGZ5FJUW.js → chunk-CAOUV5GZ.js} +2 -2
  72. package/dist/cli/chunks/{chunk-XPRVF4YE.js → chunk-CBK5CT6T.js} +2 -2
  73. package/dist/cli/chunks/{chunk-JRRXCODW.js → chunk-DEKR3CTS.js} +2 -2
  74. package/dist/cli/chunks/{chunk-AQSVJNEH.js → chunk-DKX4GNRU.js} +2 -2
  75. package/dist/cli/chunks/{chunk-6KATY3KS.js → chunk-DUKE27HC.js} +2 -2
  76. package/dist/cli/chunks/{chunk-W2QWSQVE.js → chunk-DURD37JZ.js} +2 -2
  77. package/dist/cli/chunks/{chunk-KCW47QR5.js → chunk-E3MRDIZF.js} +1 -1
  78. package/dist/cli/chunks/{chunk-6Z7PRBSG.js → chunk-E56PVVWC.js} +2 -2
  79. package/dist/cli/chunks/{chunk-WQL7WCIZ.js → chunk-E5G4WZ2T.js} +1 -1
  80. package/dist/cli/chunks/{chunk-PB6J6HAA.js → chunk-EBTNMQSS.js} +2 -2
  81. package/dist/cli/chunks/{chunk-KADFXPPN.js → chunk-EFUJDMNC.js} +2 -2
  82. package/dist/cli/chunks/{chunk-QPNG5ZN2.js → chunk-EKP2SC77.js} +2 -2
  83. package/dist/cli/chunks/{chunk-U2FUXDDJ.js → chunk-EMSZVUYA.js} +3 -3
  84. package/dist/cli/chunks/{chunk-XEAEYC6Y.js → chunk-ERN56H6S.js} +1 -1
  85. package/dist/cli/chunks/{chunk-DNDL7SOS.js → chunk-FOOW4JVS.js} +2 -2
  86. package/dist/cli/chunks/{chunk-HOAJUIBQ.js → chunk-FTRSS64D.js} +2 -2
  87. package/dist/cli/chunks/{chunk-TOQWL2ZF.js → chunk-G242G224.js} +2 -2
  88. package/dist/cli/chunks/{chunk-VTDFVFST.js → chunk-G6RDCCFV.js} +2 -2
  89. package/dist/cli/chunks/{chunk-TWDW32W2.js → chunk-GCHYOPRZ.js} +2 -2
  90. package/dist/cli/chunks/{chunk-MFW5HSG4.js → chunk-GGQGCT4Y.js} +2 -2
  91. package/dist/cli/chunks/{chunk-G6WDYBLQ.js → chunk-GKSMRBHU.js} +1 -1
  92. package/dist/cli/chunks/{chunk-CCMKSHAT.js → chunk-GQABPCQE.js} +2 -2
  93. package/dist/cli/chunks/{chunk-G77ERMUD.js → chunk-GV2QE5TO.js} +1 -1
  94. package/dist/cli/chunks/{chunk-756CGMEH.js → chunk-H5DER3JY.js} +1 -1
  95. package/dist/cli/chunks/{chunk-W3PPFHI5.js → chunk-HH4ED4F7.js} +52 -50
  96. package/dist/cli/chunks/{chunk-3Y2ROSCL.js → chunk-HL2ANKN3.js} +2 -2
  97. package/dist/cli/chunks/{chunk-T3PGQFDI.js → chunk-HTZSRMHW.js} +2 -2
  98. package/dist/cli/chunks/{chunk-3QZEGE67.js → chunk-IXL5ZHWJ.js} +1 -1
  99. package/dist/cli/chunks/{chunk-5ZGM3RMH.js → chunk-J3FP5UGL.js} +1 -1
  100. package/dist/cli/chunks/{chunk-FZ76G4QJ.js → chunk-JCQGJGGZ.js} +1 -1
  101. package/dist/cli/chunks/chunk-JCZCJE6X.js +86 -0
  102. package/dist/cli/chunks/{chunk-YZEXYO4W.js → chunk-JKJOB65O.js} +1 -1
  103. package/dist/cli/chunks/{chunk-A64JFBWI.js → chunk-JUDUBQHA.js} +2 -2
  104. package/dist/cli/chunks/{chunk-PIDQVU3L.js → chunk-JW74KRBC.js} +2 -2
  105. package/dist/cli/chunks/{chunk-EXGMJFAT.js → chunk-K3WZICFA.js} +1 -1
  106. package/dist/cli/chunks/{chunk-ASQYASNV.js → chunk-K3XBQC3R.js} +1 -1
  107. package/dist/cli/chunks/{chunk-E7CLYGS7.js → chunk-KCQNFBBR.js} +1 -1
  108. package/dist/cli/chunks/chunk-KJBPB7P5.js +3 -0
  109. package/dist/cli/chunks/chunk-KLTMOXIK.js +3 -0
  110. package/dist/cli/chunks/{chunk-5MDERQH3.js → chunk-L32JNNKL.js} +1 -1
  111. package/dist/cli/chunks/{chunk-32ZMWEP3.js → chunk-LB2LGEDP.js} +2 -2
  112. package/dist/cli/chunks/{chunk-42J34YG4.js → chunk-LHMQIZ6B.js} +2 -2
  113. package/dist/cli/chunks/{chunk-NURIILUB.js → chunk-LJMYRTJ7.js} +1 -1
  114. package/dist/cli/chunks/{chunk-M6AAGIG7.js → chunk-LNX74WHQ.js} +1 -1
  115. package/dist/cli/chunks/{chunk-P7A4NKTZ.js → chunk-LTQVUAPH.js} +2 -2
  116. package/dist/cli/chunks/{chunk-3YNLWPBF.js → chunk-LVABQNRF.js} +2 -2
  117. package/dist/cli/chunks/{chunk-2G7TVT6W.js → chunk-LYJHUNBK.js} +2 -2
  118. package/dist/cli/chunks/{chunk-DLD7RUZ4.js → chunk-M4CJCPCQ.js} +2 -2
  119. package/dist/cli/chunks/{chunk-Q3UDLV5Z.js → chunk-M4WMSCAE.js} +1 -1
  120. package/dist/cli/chunks/{chunk-UDQSYWVF.js → chunk-MIA447GY.js} +1 -1
  121. package/dist/cli/chunks/{chunk-RF7HWBHN.js → chunk-MPFPWJTH.js} +2 -2
  122. package/dist/cli/chunks/{chunk-BK577VL7.js → chunk-MV55NXTD.js} +2 -2
  123. package/dist/cli/chunks/{chunk-JQGMW45H.js → chunk-NQS3BWS6.js} +1 -1
  124. package/dist/cli/chunks/{chunk-BEGR4D6N.js → chunk-NWIIYHT6.js} +2 -2
  125. package/dist/cli/chunks/{chunk-SSU73QAX.js → chunk-O6EWL5DQ.js} +2 -2
  126. package/dist/cli/chunks/chunk-OBDONJQM.js +2 -0
  127. package/dist/cli/chunks/chunk-OLZH5LRT.js +141 -0
  128. package/dist/cli/chunks/{chunk-W3INMZZ6.js → chunk-OQG3UQQ7.js} +1 -1
  129. package/dist/cli/chunks/{chunk-72ASBE35.js → chunk-PFQCV6YS.js} +3 -3
  130. package/dist/cli/chunks/{chunk-7YTGHGK4.js → chunk-PS6UMZVK.js} +2 -2
  131. package/dist/cli/chunks/{chunk-OCAEXYFA.js → chunk-PXATBHWN.js} +2 -2
  132. package/dist/cli/chunks/{chunk-ARJW4I2O.js → chunk-PYPS65P7.js} +2 -2
  133. package/dist/cli/chunks/{chunk-SYV2V3PL.js → chunk-Q6I4SIUU.js} +4 -4
  134. package/dist/cli/chunks/{chunk-H4H2YSFH.js → chunk-QFGYH6HD.js} +1 -1
  135. package/dist/cli/chunks/{chunk-526QYFJU.js → chunk-QGBGSQ2E.js} +2 -2
  136. package/dist/cli/chunks/{chunk-YBQH2VOP.js → chunk-QRKTBSZT.js} +2 -2
  137. package/dist/cli/chunks/{chunk-C7JM7CD3.js → chunk-R6LHJ7ME.js} +2 -2
  138. package/dist/cli/chunks/{chunk-TSQC2KKZ.js → chunk-RBKUU7WF.js} +2 -2
  139. package/dist/cli/chunks/{chunk-CE7B5LU7.js → chunk-RDMRY7CT.js} +1 -1
  140. package/dist/cli/chunks/chunk-RIRZHOS2.js +8 -0
  141. package/dist/cli/chunks/{chunk-CRWPZT74.js → chunk-SHRI7TKJ.js} +2 -2
  142. package/dist/cli/chunks/{chunk-KWYH3FI4.js → chunk-SJCKCSN3.js} +1 -1
  143. package/dist/cli/chunks/{chunk-DFUASIKA.js → chunk-SON6ZRH3.js} +2 -2
  144. package/dist/cli/chunks/{chunk-J2ZIFFM6.js → chunk-SZAZQZWI.js} +2 -2
  145. package/dist/cli/chunks/{chunk-HD7YIFOI.js → chunk-T4GE7MPI.js} +2 -2
  146. package/dist/cli/chunks/{chunk-3Y7TJFHU.js → chunk-T66PPF4D.js} +2 -2
  147. package/dist/cli/chunks/{chunk-3RZV5DGO.js → chunk-T67R2MUN.js} +2 -2
  148. package/dist/cli/chunks/{chunk-H4GG2NLO.js → chunk-TDQWTSBS.js} +2 -2
  149. package/dist/cli/chunks/{chunk-TWJTK4CC.js → chunk-TODNOP7C.js} +2 -2
  150. package/dist/cli/chunks/{chunk-NZ3GUMB2.js → chunk-TX2CHQD7.js} +2 -2
  151. package/dist/cli/chunks/{chunk-AL6FBH3E.js → chunk-TZIHDJZD.js} +2 -2
  152. package/dist/cli/chunks/{chunk-GII6UM3F.js → chunk-U62OUXBF.js} +1 -1
  153. package/dist/cli/chunks/{chunk-YQFLQE53.js → chunk-UAQZI6N4.js} +2 -2
  154. package/dist/cli/chunks/{chunk-R7SYRCRP.js → chunk-UE2J6MA5.js} +1 -1
  155. package/dist/cli/chunks/{chunk-VRHRBAEM.js → chunk-UGYM4U44.js} +1 -1
  156. package/dist/cli/chunks/{chunk-NT4DBXSX.js → chunk-UJABDXST.js} +2 -2
  157. package/dist/cli/chunks/{chunk-OFACHK5O.js → chunk-UORB2QDU.js} +9 -9
  158. package/dist/cli/chunks/{chunk-QDEJ4CI2.js → chunk-UQPA33UK.js} +2 -2
  159. package/dist/cli/chunks/{chunk-TCBBNUBP.js → chunk-UUBIQR6A.js} +3 -3
  160. package/dist/cli/chunks/{chunk-NZD4DPSU.js → chunk-UXIY4IAI.js} +2 -2
  161. package/dist/cli/chunks/{chunk-SG3NX7QE.js → chunk-VCXI4XC4.js} +2 -2
  162. package/dist/cli/chunks/{chunk-PSFSPGUD.js → chunk-VMAM46HQ.js} +2 -2
  163. package/dist/cli/chunks/{chunk-3AN5TNGD.js → chunk-VY4U6DPO.js} +3 -3
  164. package/dist/cli/chunks/{chunk-X7N2JF2X.js → chunk-W27AJ5B4.js} +2 -2
  165. package/dist/cli/chunks/{chunk-CT6SAVXQ.js → chunk-W5ZJG2OU.js} +2 -2
  166. package/dist/cli/chunks/{chunk-KV4T4MXK.js → chunk-W62OOK7A.js} +2 -2
  167. package/dist/cli/chunks/{chunk-5K26BEYB.js → chunk-WNTA4YKE.js} +2 -2
  168. package/dist/cli/chunks/{chunk-LZYQHVD4.js → chunk-WUOOX7UG.js} +2 -2
  169. package/dist/cli/chunks/{chunk-7NA7JXNB.js → chunk-WVXJ2QIG.js} +2 -2
  170. package/dist/cli/chunks/{chunk-KB56CPU4.js → chunk-X33CWRDF.js} +2 -2
  171. package/dist/cli/chunks/{chunk-7JUC2MVZ.js → chunk-XG4F4XH4.js} +2 -2
  172. package/dist/cli/chunks/{chunk-ZAKQLAHT.js → chunk-XH4JMX5O.js} +1 -1
  173. package/dist/cli/chunks/{chunk-X2Z7F4EU.js → chunk-XHHWABJV.js} +2 -2
  174. package/dist/cli/chunks/{chunk-7PLIEBY7.js → chunk-XHLYGXYE.js} +2 -2
  175. package/dist/cli/chunks/{chunk-UXZSUMEA.js → chunk-XIVVTYM2.js} +2 -2
  176. package/dist/cli/chunks/{chunk-MVVB7C2E.js → chunk-XM6ZVFM5.js} +156 -156
  177. package/dist/cli/chunks/{chunk-VTOBUZL6.js → chunk-XWIAZG3C.js} +2 -2
  178. package/dist/cli/chunks/{chunk-CV77DMDQ.js → chunk-Y2OX6KGN.js} +2 -2
  179. package/dist/cli/chunks/{chunk-VRVMIPTM.js → chunk-YUS6TWAL.js} +2 -2
  180. package/dist/cli/chunks/{chunk-VU5TBX2V.js → chunk-ZIPAB5J6.js} +2 -2
  181. package/dist/cli/chunks/{chunk-KUAKV3IW.js → chunk-ZSOMUTNL.js} +1 -1
  182. package/dist/cli/chunks/{chunk-UOC3O6RP.js → chunk-ZWBGYJ7K.js} +2 -2
  183. package/dist/cli/chunks/{chunk-5VMAV6T6.js → chunk-ZYJB6FML.js} +1 -1
  184. package/dist/cli/chunks/{ci-ENOASTYB.js → ci-UCUJOSBW.js} +2 -2
  185. package/dist/cli/chunks/{ci-config-B26OXHQM.js → ci-config-2XILD3XG.js} +2 -2
  186. package/dist/cli/chunks/{ci-output-JTCLLNOQ.js → ci-output-BL6KWOHW.js} +2 -2
  187. package/dist/cli/chunks/{circuit-breaker-23JMFNM5.js → circuit-breaker-5XLIOXE5.js} +2 -2
  188. package/dist/cli/chunks/{claude-flow-setup-ON6L462G.js → claude-flow-setup-4IMP6ACS.js} +2 -2
  189. package/dist/cli/chunks/client-KKRNPX4F.js +2 -0
  190. package/dist/cli/chunks/{cline-installer-OWQ4D2FQ.js → cline-installer-RYLHCDK7.js} +2 -2
  191. package/dist/cli/chunks/{code-2ZRL7SEU.js → code-WY3GJXHX.js} +3 -3
  192. package/dist/cli/chunks/{code-index-extractor-JXSQVM67.js → code-index-extractor-Y4MZBZCW.js} +2 -2
  193. package/dist/cli/chunks/{codex-installer-7LXZYBSQ.js → codex-installer-SCJ3T3DX.js} +4 -4
  194. package/dist/cli/chunks/{completions-C2LR623C.js → completions-CN2DXQFU.js} +2 -2
  195. package/dist/cli/chunks/{complexity-analyzer-TGQLHCYJ.js → complexity-analyzer-7MDPPIBH.js} +2 -2
  196. package/dist/cli/chunks/{continuedev-installer-RUGD24D2.js → continuedev-installer-GCEJRK34.js} +2 -2
  197. package/dist/cli/chunks/{copilot-installer-ZLFVLEJP.js → copilot-installer-BHPDSELY.js} +2 -2
  198. package/dist/cli/chunks/core-handlers-47MPMED7.js +2 -0
  199. package/dist/cli/chunks/{cost-tracker-RT4QL745.js → cost-tracker-VO5MFWR6.js} +2 -2
  200. package/dist/cli/chunks/coverage-LYFQYNH6.js +51 -0
  201. package/dist/cli/chunks/cross-domain-router-U6MBFHEC.js +2 -0
  202. package/dist/cli/chunks/{cursor-installer-LJKLNFF6.js → cursor-installer-KP4HA7TV.js} +2 -2
  203. package/dist/cli/chunks/{daemon-BMDXCQT5.js → daemon-7RC7TS57.js} +3 -3
  204. package/dist/cli/chunks/{daemon-FBH3IRYN.js → daemon-AXLVPKVO.js} +4 -4
  205. package/dist/cli/chunks/{dag-attention-scheduler-JGDED55I.js → dag-attention-scheduler-NKA44RSR.js} +2 -2
  206. package/dist/cli/chunks/{detect-SZIHIVCJ.js → detect-CMYAJWYF.js} +2 -2
  207. package/dist/cli/chunks/{dist-node-FV3KWXQ6.js → dist-node-EN3PYEGW.js} +2 -2
  208. package/dist/cli/chunks/{domain-handler-GI5JWQOV.js → domain-handler-EXSZCX7A.js} +2 -2
  209. package/dist/cli/chunks/{domain-plugins-BUWY36TL.js → domain-plugins-HCQFSNL7.js} +2 -2
  210. package/dist/cli/chunks/{domain-transfer-GCY7W5DA.js → domain-transfer-3LGSNTPO.js} +2 -2
  211. package/dist/cli/chunks/dream-76L6EEN7.js +2 -0
  212. package/dist/cli/chunks/{embed-and-insert-pattern-GPRR3ZGD.js → embed-and-insert-pattern-B6MNHICW.js} +2 -2
  213. package/dist/cli/chunks/{eval-XPB3IGAP.js → eval-OQELIWJK.js} +2 -2
  214. package/dist/cli/chunks/{experience-capture-middleware-2E554UB3.js → experience-capture-middleware-SUFILYPW.js} +3 -3
  215. package/dist/cli/chunks/{fast-paths-ZSMWZPUC.js → fast-paths-UV4NDEWM.js} +2 -2
  216. package/dist/cli/chunks/{feature-flags-GIWVDVVC.js → feature-flags-CKTYX67J.js} +2 -2
  217. package/dist/cli/chunks/{feature-flags-N7EOGE5P.js → feature-flags-H7H33B6C.js} +2 -2
  218. package/dist/cli/chunks/file-discovery-VSFKZ3LJ.js +2 -0
  219. package/dist/cli/chunks/{fleet-HCHDOUCX.js → fleet-ZJBCAKRG.js} +3 -3
  220. package/dist/cli/chunks/{gnn-wrapper-CZNCNXXZ.js → gnn-wrapper-RUE2QZRG.js} +2 -2
  221. package/dist/cli/chunks/{heartbeat-handler-6YUIF2YQ.js → heartbeat-handler-XRV327M7.js} +4 -4
  222. package/dist/cli/chunks/heartbeat-scheduler-NIK3KKEH.js +2 -0
  223. package/dist/cli/chunks/hnsw-adapter-WJG7LUJJ.js +2 -0
  224. package/dist/cli/chunks/hnsw-index-D6PRI5HC.js +2 -0
  225. package/dist/cli/chunks/{hnsw-legacy-bridge-J3M3IK24.js → hnsw-legacy-bridge-UJID6ZZ4.js} +2 -2
  226. package/dist/cli/chunks/{hnswlib-node-ULGTGDZW.js → hnswlib-node-WS43R4AX.js} +2 -2
  227. package/dist/cli/chunks/{hooks-C4BUGYUQ.js → hooks-YZNJKXAJ.js} +10 -10
  228. package/dist/cli/chunks/hybrid-backend-RIUR3I7F.js +2 -0
  229. package/dist/cli/chunks/{hypergraph-engine-WINGVMPG.js → hypergraph-engine-XQJSIMTS.js} +2 -2
  230. package/dist/cli/chunks/{hypergraph-handler-GADMWKAU.js → hypergraph-handler-ZD2NYXMR.js} +3 -3
  231. package/dist/cli/chunks/impact-analyzer-C36YYTJ5.js +2 -0
  232. package/dist/cli/chunks/{init-guard-K2T4QWAO.js → init-guard-DSRUAVRT.js} +2 -2
  233. package/dist/cli/chunks/{init-handler-PCZTDZYI.js → init-handler-RJU5QMAP.js} +6 -6
  234. package/dist/cli/chunks/init-wizard-JCKNGIGT.js +2 -0
  235. package/dist/cli/chunks/kernel-F7ILJTYD.js +2 -0
  236. package/dist/cli/chunks/{kilocode-installer-XENXNEIU.js → kilocode-installer-BCPOCVMC.js} +2 -2
  237. package/dist/cli/chunks/{kiro-installer-3PG2TJ67.js → kiro-installer-GFCWCB2S.js} +2 -2
  238. package/dist/cli/chunks/knowledge-graph-VTXDBHB2.js +2 -0
  239. package/dist/cli/chunks/learning-FZTD72CF.js +131 -0
  240. package/dist/cli/chunks/{llm-router-RKVDEWU2.js → llm-router-GJVKGRJL.js} +4 -4
  241. package/dist/cli/chunks/llm-router-service-TNOWQINA.js +2 -0
  242. package/dist/cli/chunks/{load-ITHC564X.js → load-YKTPOYBE.js} +2 -2
  243. package/dist/cli/chunks/load-test-FPVBK2EV.js +2 -0
  244. package/dist/cli/chunks/{mcp-TCL5UW3N.js → mcp-LT6R2IKS.js} +2 -2
  245. package/dist/cli/chunks/{memory-BKDAY2N2.js → memory-4HKKOLRY.js} +5 -5
  246. package/dist/cli/chunks/memory-backend-2QE7O67A.js +2 -0
  247. package/dist/cli/chunks/{memory-handlers-WN4FXFOA.js → memory-handlers-X4CMVBXB.js} +2 -2
  248. package/dist/cli/chunks/{multi-model-executor-VHAT7ZPF.js → multi-model-executor-2YPM2WTK.js} +2 -2
  249. package/dist/cli/chunks/{opencode-installer-E3VM3EEY.js → opencode-installer-WBAJMH5K.js} +2 -2
  250. package/dist/cli/chunks/{orchestrator-BMQ6X762.js → orchestrator-5W5WVMVJ.js} +109 -25
  251. package/dist/cli/chunks/pattern-null-store-UI35ORHW.js +2 -0
  252. package/dist/cli/chunks/{pattern-usage-recorder-GOOR2BV5.js → pattern-usage-recorder-GXRMNPAZ.js} +2 -2
  253. package/dist/cli/chunks/{pipeline-5NSFQQIX.js → pipeline-2NA4DRDA.js} +2 -2
  254. package/dist/cli/chunks/{platform-SQM34J5G.js → platform-BGERNQ5V.js} +2 -2
  255. package/dist/cli/chunks/{plugin-UQJZRMZG.js → plugin-L4EPVENR.js} +2 -2
  256. package/dist/cli/chunks/{prime-radiant-advanced-wasm-WMDJOL4S.js → prime-radiant-advanced-wasm-RTQRTPTM.js} +2 -2
  257. package/dist/cli/chunks/project-root-S7WDFTMU.js +2 -0
  258. package/dist/cli/chunks/protocol-executor-OPANXQVB.js +2 -0
  259. package/dist/cli/chunks/{protocol-handler-OBDCVY6X.js → protocol-handler-SYQXM6JK.js} +2 -2
  260. package/dist/cli/chunks/{prove-XDC7I4XT.js → prove-5O7GPJCU.js} +2 -2
  261. package/dist/cli/chunks/qe-reasoning-bank-3OTF4DYQ.js +2 -0
  262. package/dist/cli/chunks/{quality-L4GQ6WX4.js → quality-KIIDHGNF.js} +2 -2
  263. package/dist/cli/chunks/{quality-gate-MJG66LKN.js → quality-gate-H65VECD3.js} +3 -3
  264. package/dist/cli/chunks/queen-coordinator-WTYH4TAN.js +2 -0
  265. package/dist/cli/chunks/{real-embeddings-HW4G2LWL.js → real-embeddings-DYIOLKQ3.js} +2 -2
  266. package/dist/cli/chunks/{ref-validation-FC7JOJ2C.js → ref-validation-CSBJOMZM.js} +2 -2
  267. package/dist/cli/chunks/{roocode-installer-KWS4CEIC.js → roocode-installer-G7OVYXEN.js} +2 -2
  268. package/dist/cli/chunks/router-DBBW4NC2.js +2 -0
  269. package/dist/cli/chunks/routing-feedback-W35QHCL4.js +2 -0
  270. package/dist/cli/chunks/{routing-handler-QF4WVB2S.js → routing-handler-ZNZPPI5Y.js} +2 -2
  271. package/dist/cli/chunks/{ruvector-commands-2MTCOUK6.js → ruvector-commands-C6IG3OY3.js} +2 -2
  272. package/dist/cli/chunks/rvf-dual-writer-X3NSL25Z.js +2 -0
  273. package/dist/cli/chunks/rvf-migration-adapter-TZR7GDOK.js +2 -0
  274. package/dist/cli/chunks/{rvf-migration-coordinator-BREJCXWN.js → rvf-migration-coordinator-4ATTHGHD.js} +2 -2
  275. package/dist/cli/chunks/rvf-native-adapter-HD25ZYV5.js +2 -0
  276. package/dist/cli/chunks/{rvf-store-integrity-KKC6HOJD.js → rvf-store-integrity-3G6LFLT3.js} +2 -2
  277. package/dist/cli/chunks/safe-db-ZS2QKANY.js +2 -0
  278. package/dist/cli/chunks/schedule-ZH6VNA32.js +2 -0
  279. package/dist/cli/chunks/scheduler-T6CD74B6.js +2 -0
  280. package/dist/cli/chunks/{security-OSAE7VAP.js → security-A3IMVLFM.js} +3 -3
  281. package/dist/cli/chunks/{shared-rvf-adapter-COUOS665.js → shared-rvf-adapter-VHWQ6US5.js} +2 -2
  282. package/dist/cli/chunks/{shared-rvf-dual-writer-YXMPZKQE.js → shared-rvf-dual-writer-JB3QS7IG.js} +2 -2
  283. package/dist/cli/chunks/sqlite-persistence-47WU5EKZ.js +2 -0
  284. package/dist/cli/chunks/{standalone-memory-E6JBMOIL.js → standalone-memory-DDNXCSBD.js} +2 -2
  285. package/dist/cli/chunks/{status-handler-AFTCIYIX.js → status-handler-2HK7XPEK.js} +2 -2
  286. package/dist/cli/chunks/{structural-health-2FROCEI4.js → structural-health-DSJVLEPV.js} +2 -2
  287. package/dist/cli/chunks/{sync-VAYTOWDC.js → sync-3MUV6S5E.js} +2 -2
  288. package/dist/cli/chunks/{sync-YIQYOFGW.js → sync-NTUR53PI.js} +2 -2
  289. package/dist/cli/chunks/{task-handler-KVQHDEX3.js → task-handler-74MZN2EO.js} +2 -2
  290. package/dist/cli/chunks/{task-handlers-MVVECQA6.js → task-handlers-VJR6EHRZ.js} +3 -3
  291. package/dist/cli/chunks/{test-5JSVTOMY.js → test-O6FK3FVF.js} +4 -4
  292. package/dist/cli/chunks/test-runner-process-2NPW3UDQ.js +2 -0
  293. package/dist/cli/chunks/{test-scheduling-HBOHVLI3.js → test-scheduling-Q6QEEOS6.js} +3 -3
  294. package/dist/cli/chunks/{token-bootstrap-5VEPTPFA.js → token-bootstrap-TTRCECLP.js} +2 -2
  295. package/dist/cli/chunks/{token-usage-TBJHDLY6.js → token-usage-YEEFWSSI.js} +2 -2
  296. package/dist/cli/chunks/{transformers-VAWYMHMZ.js → transformers-BZCHJJJT.js} +2 -2
  297. package/dist/cli/chunks/tree-sitter-wasm-parser-RZAND65G.js +2 -0
  298. package/dist/cli/chunks/{types-R5SDZU2E.js → types-4AOKZYOX.js} +2 -2
  299. package/dist/cli/chunks/unified-memory-FZ5K2C7W.js +2 -0
  300. package/dist/cli/chunks/unified-memory-hnsw-VREWX56M.js +2 -0
  301. package/dist/cli/chunks/unified-persistence-YZGMKX6B.js +2 -0
  302. package/dist/cli/chunks/{upgrade-K5PIHXRB.js → upgrade-2MWW6BT2.js} +2 -2
  303. package/dist/cli/chunks/{validate-RPTS7RYJ.js → validate-PAEV3GT5.js} +2 -2
  304. package/dist/cli/chunks/{validate-swarm-B2ZL556X.js → validate-swarm-ZIXACK5K.js} +2 -2
  305. package/dist/cli/chunks/visual-security-GXGSFBVA.js +2 -0
  306. package/dist/cli/chunks/{web-tree-sitter-K4DUJC32.js → web-tree-sitter-VLTXZFAB.js} +2 -2
  307. package/dist/cli/chunks/{windsurf-installer-OK2AJN35.js → windsurf-installer-VELMLOZF.js} +2 -2
  308. package/dist/cli/chunks/witness-chain-MRJKVCOW.js +2 -0
  309. package/dist/cli/chunks/witness-chain-WWHJKITG.js +2 -0
  310. package/dist/cli/chunks/{witness-chain-repair-L6Y5RFXR.js → witness-chain-repair-5SAXPETG.js} +2 -2
  311. package/dist/cli/chunks/{witness-chain-verifier-N4CW7FZX.js → witness-chain-verifier-MIDWD4JS.js} +2 -2
  312. package/dist/cli/chunks/{witness-key-manager-TDNPS3WD.js → witness-key-manager-OSVCWOB2.js} +2 -2
  313. package/dist/cli/chunks/{workflow-XRZA3YCY.js → workflow-MK7A7QCX.js} +4 -4
  314. package/dist/cli/chunks/workflow-orchestrator-SG7DV72E.js +2 -0
  315. package/dist/cli/chunks/{wrappers-5JIFWKN6.js → wrappers-5QFMCKXL.js} +2 -2
  316. package/dist/cli/commands/coverage.js +6 -0
  317. package/dist/cli/commands/learning-prune.d.ts +14 -0
  318. package/dist/cli/commands/learning-prune.js +105 -0
  319. package/dist/cli/commands/learning.js +9 -0
  320. package/dist/cli/handlers/brain-handler.js +12 -1
  321. package/dist/cli/utils/coverage-verdict.js +14 -3
  322. package/dist/context/compaction/index.d.ts +7 -0
  323. package/dist/context/compaction/index.js +30 -6
  324. package/dist/coordination/handlers/coverage-evidence.d.ts +19 -0
  325. package/dist/coordination/handlers/coverage-evidence.js +31 -2
  326. package/dist/coordination/handlers/coverage-handlers.js +5 -1
  327. package/dist/coordination/handlers/coverage-target.js +8 -1
  328. package/dist/coordination/handlers/quality-handlers.js +9 -1
  329. package/dist/coordination/result-saver-adapters.js +1 -0
  330. package/dist/coordination/result-saver.js +9 -5
  331. package/dist/domains/chaos-resilience/services/chaos-engineer.d.ts +1 -0
  332. package/dist/domains/chaos-resilience/services/chaos-engineer.js +23 -45
  333. package/dist/domains/coverage-analysis/collected-metrics.d.ts +22 -6
  334. package/dist/domains/coverage-analysis/collected-metrics.js +37 -12
  335. package/dist/domains/coverage-analysis/services/coverage-analyzer.js +2 -0
  336. package/dist/domains/defect-intelligence/services/defect-predictor.js +3 -6
  337. package/dist/domains/quality-assessment/coverage-report-event.d.ts +8 -0
  338. package/dist/domains/quality-assessment/coverage-report-event.js +22 -1
  339. package/dist/domains/quality-assessment/interfaces.d.ts +6 -0
  340. package/dist/domains/quality-assessment/services/quality-analyzer.d.ts +4 -0
  341. package/dist/domains/quality-assessment/services/quality-analyzer.js +63 -17
  342. package/dist/domains/test-execution/interfaces.d.ts +5 -0
  343. package/dist/domains/test-execution/services/test-executor.js +6 -0
  344. package/dist/init/init-wizard-hooks.d.ts +1 -1
  345. package/dist/init/init-wizard-hooks.js +7 -8
  346. package/dist/init/phases/07-hooks.js +90 -6
  347. package/dist/init/phases/08-mcp.js +9 -0
  348. package/dist/init/settings-merge.d.ts +13 -0
  349. package/dist/init/settings-merge.js +49 -2
  350. package/dist/integrations/agent-booster-wasm/agent_booster_wasm.js +849 -0
  351. package/dist/integrations/agent-booster-wasm/agent_booster_wasm_bg.wasm +0 -0
  352. package/dist/integrations/agent-booster-wasm/index.d.ts +8 -0
  353. package/dist/integrations/agent-booster-wasm/index.js +25 -2
  354. package/dist/integrations/agent-booster-wasm/package.json +16 -0
  355. package/dist/integrations/ruvector/brain-rvf-exporter.d.ts +25 -0
  356. package/dist/integrations/ruvector/brain-rvf-exporter.js +154 -61
  357. package/dist/learning/dream/dream-engine.d.ts +27 -3
  358. package/dist/learning/dream/dream-engine.js +97 -28
  359. package/dist/learning/dream/dream-lock-retry.d.ts +38 -0
  360. package/dist/learning/dream/dream-lock-retry.js +66 -0
  361. package/dist/learning/dream/speculative-dreamer.js +1 -1
  362. package/dist/learning/learning-retention.d.ts +103 -0
  363. package/dist/learning/learning-retention.js +213 -0
  364. package/dist/mcp/bundle.js +501 -496
  365. package/dist/mcp/handlers/domain-handler-configs.d.ts +9 -1
  366. package/dist/mcp/handlers/domain-handler-configs.js +24 -14
  367. package/dist/mcp/protocol-server.js +1 -1
  368. package/dist/mcp/tools/chaos-resilience/inject.d.ts +3 -4
  369. package/dist/mcp/tools/chaos-resilience/inject.js +11 -81
  370. package/dist/mcp/tools/learning-optimization/dream.d.ts +8 -0
  371. package/dist/mcp/tools/learning-optimization/dream.js +4 -0
  372. package/package.json +4 -2
  373. package/dist/cli/chunks/adapter-KCQDVYY2.js +0 -2
  374. package/dist/cli/chunks/agent-booster-wasm-6RRQWMNE.js +0 -2
  375. package/dist/cli/chunks/aqe-learning-engine-SAQOHSGN.js +0 -2
  376. package/dist/cli/chunks/base-WCACU3FN.js +0 -2
  377. package/dist/cli/chunks/brain-handler-GTQNHHZS.js +0 -94
  378. package/dist/cli/chunks/browser-workflow-G6IASEAP.js +0 -2
  379. package/dist/cli/chunks/chunk-C6JTLKG7.js +0 -141
  380. package/dist/cli/chunks/chunk-K65CGKLD.js +0 -8
  381. package/dist/cli/chunks/chunk-MB46UBGY.js +0 -3
  382. package/dist/cli/chunks/chunk-N4CYAKOX.js +0 -79
  383. package/dist/cli/chunks/chunk-PT4FMJPQ.js +0 -3
  384. package/dist/cli/chunks/chunk-S5AZCIZS.js +0 -2
  385. package/dist/cli/chunks/chunk-UT2VZ33P.js +0 -2
  386. package/dist/cli/chunks/client-TV3V2YZ5.js +0 -2
  387. package/dist/cli/chunks/core-handlers-PZT4OLWR.js +0 -2
  388. package/dist/cli/chunks/coverage-NV3C4IMM.js +0 -50
  389. package/dist/cli/chunks/cross-domain-router-QOFCZ7G4.js +0 -2
  390. package/dist/cli/chunks/dream-TRFBGDSQ.js +0 -2
  391. package/dist/cli/chunks/file-discovery-WCKGMSPZ.js +0 -2
  392. package/dist/cli/chunks/heartbeat-scheduler-P44A2OX3.js +0 -2
  393. package/dist/cli/chunks/hnsw-adapter-ZJQIQJKC.js +0 -2
  394. package/dist/cli/chunks/hnsw-index-HMG2GH3Z.js +0 -2
  395. package/dist/cli/chunks/hybrid-backend-B7M74PZG.js +0 -2
  396. package/dist/cli/chunks/impact-analyzer-PZYOVKQO.js +0 -2
  397. package/dist/cli/chunks/init-wizard-TZDJQK3U.js +0 -2
  398. package/dist/cli/chunks/kernel-Y6RRIOKW.js +0 -2
  399. package/dist/cli/chunks/knowledge-graph-BVD5Z66M.js +0 -2
  400. package/dist/cli/chunks/learning-6KDH7FK4.js +0 -122
  401. package/dist/cli/chunks/llm-router-service-KHCAMSUU.js +0 -2
  402. package/dist/cli/chunks/load-test-RUF7DZA5.js +0 -2
  403. package/dist/cli/chunks/memory-backend-7ZLFOVGG.js +0 -2
  404. package/dist/cli/chunks/pattern-null-store-RY6CVYHP.js +0 -2
  405. package/dist/cli/chunks/project-root-IO5KRNGL.js +0 -2
  406. package/dist/cli/chunks/protocol-executor-U2CUDWDE.js +0 -2
  407. package/dist/cli/chunks/qe-reasoning-bank-DQSSX2IP.js +0 -2
  408. package/dist/cli/chunks/queen-coordinator-6FN4BZIX.js +0 -2
  409. package/dist/cli/chunks/router-YUO3I7RU.js +0 -2
  410. package/dist/cli/chunks/routing-feedback-36SLQGJE.js +0 -2
  411. package/dist/cli/chunks/rvf-dual-writer-FRYZH3WZ.js +0 -2
  412. package/dist/cli/chunks/rvf-migration-adapter-XXNITL5I.js +0 -2
  413. package/dist/cli/chunks/rvf-native-adapter-D2WWKJIV.js +0 -2
  414. package/dist/cli/chunks/safe-db-4RRIGRXD.js +0 -2
  415. package/dist/cli/chunks/schedule-25RTO4DQ.js +0 -2
  416. package/dist/cli/chunks/scheduler-BPIOJZ5P.js +0 -2
  417. package/dist/cli/chunks/sqlite-persistence-EDF47DDX.js +0 -2
  418. package/dist/cli/chunks/test-runner-process-LEPF2OSS.js +0 -2
  419. package/dist/cli/chunks/tree-sitter-wasm-parser-TSZTCMFV.js +0 -2
  420. package/dist/cli/chunks/unified-memory-TLGSSLMI.js +0 -2
  421. package/dist/cli/chunks/unified-memory-hnsw-MSUR7ZOO.js +0 -2
  422. package/dist/cli/chunks/unified-persistence-VFFOTWK7.js +0 -2
  423. package/dist/cli/chunks/visual-security-6Q44XNLB.js +0 -2
  424. package/dist/cli/chunks/witness-chain-KDOMXDQX.js +0 -2
  425. package/dist/cli/chunks/witness-chain-N3OY2RMH.js +0 -2
  426. package/dist/cli/chunks/workflow-orchestrator-CVNNT2RJ.js +0 -2
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.13");process.exit(0)}
2
- import{b as Me,c as Ae,e as Te}from"./chunk-2G7TVT6W.js";import{a as y,b as ee}from"./chunk-7PLIEBY7.js";import{b as Ce}from"./chunk-CRWPZT74.js";import{a as Re}from"./chunk-CM4LSLKR.js";import"./chunk-CE7B5LU7.js";import"./chunk-EXGMJFAT.js";import{a as we,c as x}from"./chunk-YZEXYO4W.js";import{a as E}from"./chunk-S5AZCIZS.js";import{c as Se}from"./chunk-756CGMEH.js";import{a as Z,e as Q,f as ke,h as be,i as U,l as De}from"./chunk-K3TLLJMX.js";import{a as fe,v as ve}from"./chunk-C6JTLKG7.js";import{b as ye}from"./chunk-N4CYAKOX.js";import"./chunk-JQGMW45H.js";import"./chunk-A64JFBWI.js";import"./chunk-3AN5TNGD.js";import"./chunk-3YNLWPBF.js";import"./chunk-72ASBE35.js";import"./chunk-TSQC2KKZ.js";import"./chunk-SYV2V3PL.js";import"./chunk-NZD4DPSU.js";import"./chunk-E7CLYGS7.js";import"./chunk-GU5HNCWI.js";import"./chunk-5VMAV6T6.js";import"./chunk-TWJTK4CC.js";import"./chunk-GHM6MQNK.js";import"./chunk-XEAEYC6Y.js";import"./chunk-QDEJ4CI2.js";import"./chunk-T3PGQFDI.js";import"./chunk-VRVMIPTM.js";import"./chunk-4OVC4RIL.js";import"./chunk-UTRV7T2N.js";import{g as w,h as he,i as Ke,r as I,v as Ye}from"./chunk-3Y7TJFHU.js";import"./chunk-7CMTY45A.js";import"./chunk-VTOBUZL6.js";import"./chunk-KDNJ4F3P.js";import"./chunk-JRRXCODW.js";import"./chunk-XNBOGCF3.js";import"./chunk-KV4T4MXK.js";import"./chunk-TWDW32W2.js";import"./chunk-AQSVJNEH.js";import"./chunk-OCAEXYFA.js";import"./chunk-WKGTGOYS.js";import"./chunk-DVGRPK7A.js";import"./chunk-H4H2YSFH.js";import{a as M}from"./chunk-NURIILUB.js";import"./chunk-TOQWL2ZF.js";import"./chunk-UT2VZ33P.js";import"./chunk-GB6HBNH2.js";import"./chunk-UOC3O6RP.js";import"./chunk-NT4DBXSX.js";import"./chunk-WOCGL4QP.js";import"./chunk-W2QWSQVE.js";import{c as j,d as Ue}from"./chunk-J2ZIFFM6.js";import"./chunk-RF7HWBHN.js";import"./chunk-IC3TQEOA.js";import"./chunk-HD7YIFOI.js";import"./chunk-DNDL7SOS.js";import{a as D,e as J}from"./chunk-3Y2ROSCL.js";import"./chunk-WO274FRI.js";import"./chunk-ZAKQLAHT.js";var te=class{handlers=[];async publish(e){for(let t of this.handlers)try{t(e)}catch(i){console.debug("[WorkerManager] Event handler error:",i instanceof Error?i.message:i)}}subscribe(e){return this.handlers.push(e),()=>{let t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)}}dispose(){this.handlers=[]}get handlerCount(){return this.handlers.length}},ne=class{store=new Map;async get(e,t){if(!t?.namespace)return this.store.get(e)}async set(e,t){this.store.set(e,t)}async search(e,t,i){if(i?.namespace)return[];let r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(r.replace(/\*/g,".*")),s=Array.from(this.store.keys()).filter(a=>n.test(a));return t===void 0?s:s.slice(0,t)}clear(){this.store.clear()}get size(){return this.store.size}},re=class{constructor(e){this.workerId=e}workerId;format(e,t,i){let r=new Date().toISOString(),n=i?` ${JSON.stringify(i)}`:"";return`[${r}] [${e}] [${this.workerId}] ${t}${n}`}debug(e,t){process.env.DEBUG&&console.debug(this.format("DEBUG",e,t))}info(e,t){console.info(this.format("INFO",e,t))}warn(e,t){console.warn(this.format("WARN",e,t))}error(e,t){console.error(this.format("ERROR",e,t))}},K=class{constructor(e){this.kernelGetter=e}kernelGetter;getDomainAPI(e){let t=this.kernelGetter();if(t)return t.getDomainAPI(e)}getDomainHealth(e){let t=this.kernelGetter();if(!t)return{status:"unknown",errors:["Kernel not available"]};let r=t.getHealth().domains[e];return r?{status:r.status,errors:r.errors||[]}:{status:"unknown",errors:[`Domain ${e} not found`]}}},Y=class{getDomainAPI(e){}getDomainHealth(e){return{status:"healthy",errors:[]}}},X=class{workers=new Map;timers=new Map;abortControllers=new Map;eventBus;memory;domainAccess;running=!1;kernelRef;constructor(e){this.eventBus=e?.eventBus??new te,this.memory=e?.memory??new ne,this.kernelRef=e?.kernel,e?.domainAccess?this.domainAccess=e.domainAccess:e?.kernel?this.domainAccess=new K(()=>this.kernelRef):this.domainAccess=new Y}setKernel(e){this.kernelRef=e,this.domainAccess instanceof Y&&(this.domainAccess=new K(()=>this.kernelRef))}setMemory(e){this.memory=e}register(e){if(this.workers.has(e.config.id))throw new Error(`Worker ${e.config.id} is already registered`);this.workers.set(e.config.id,e)}unregister(e){this.workers.get(e)&&(this.stopWorker(e),this.workers.delete(e))}get(e){return this.workers.get(e)}list(){return Array.from(this.workers.values())}async startAll(){this.running=!0;for(let e of Array.from(this.workers.values())){if(!this.running)break;e.config.enabled&&await this.startWorker(e)}}async stopAll(){this.running=!1;let e=[];for(let t of Array.from(this.workers.keys()))e.push(this.stopWorker(t));await Promise.all(e)}async runNow(e){let t=this.workers.get(e);if(!t)throw new Error(`Worker ${e} not found`);let i=this.timers.get(e);i&&clearTimeout(i);let r=new AbortController;this.abortControllers.set(e,r);let n=this.createContext(e,r.signal),s=await t.execute(n);return this.running&&t.config.enabled&&t.status!=="stopped"&&this.scheduleNextRun(t),s}getHealth(){let e={},t=0,i=0,r=0,n=0;for(let[a,o]of Array.from(this.workers.entries())){let l=o.getHealth();switch(e[a]=l,n+=l.healthScore,o.status){case"running":t++;break;case"paused":i++;break;case"error":r++;break}}let s=this.workers.size>0?Math.round(n/this.workers.size):100;return{totalWorkers:this.workers.size,runningWorkers:t,pausedWorkers:i,errorWorkers:r,healthScore:s,workers:e}}onWorkerEvent(e){return this.eventBus.subscribe(e)}async startWorker(e){await e.initialize();let t=new AbortController;this.abortControllers.set(e.config.id,t);let i=this.createContext(e.config.id,t.signal);try{await e.execute(i)}catch(r){console.error(`Worker ${e.config.id} initial execution failed:`,r)}this.scheduleNextRun(e)}async stopWorker(e){let t=this.timers.get(e);t&&(clearTimeout(t),this.timers.delete(e));let i=this.abortControllers.get(e);i&&(i.abort(),this.abortControllers.delete(e));let r=this.workers.get(e);r&&await r.stop()}scheduleNextRun(e){let t=setTimeout(async()=>{if(!this.running||e.status==="stopped"||e.status==="paused")return;let i=new AbortController;this.abortControllers.set(e.config.id,i);let r=this.createContext(e.config.id,i.signal);try{await e.execute(r)}catch(n){console.error(`Worker ${e.config.id} execution failed:`,n)}this.running&&e.config.enabled&&e.status!=="error"&&this.scheduleNextRun(e)},e.config.intervalMs);t.unref?.(),this.timers.set(e.config.id,t)}createContext(e,t){return{eventBus:this.eventBus,memory:this.memory,logger:new re(e),domains:this.domainAccess,signal:t}}};J();var Xe={id:"test-health",name:"Test Health Monitor",description:"Monitors test suite health metrics including pass rates, execution times, and reliability",intervalMs:300*1e3,priority:"high",targetDomains:["test-execution","test-generation"],enabled:!0,timeoutMs:6e4,retryCount:2,retryDelayMs:5e3},W=class extends y{previousMetrics;constructor(){super(Xe)}async doExecute(e){let t=Date.now();e.logger.info("Starting test health analysis");let i=[],r=[],n=await this.collectMetrics(e);this.analyzePassRate(n,i,r),this.analyzeExecutionTime(n,i,r),this.analyzeReliability(n,i,r),this.analyzeGrowth(n,i,r),this.compareToPrevious(n,i,r),await e.memory.set("test-health:previous-metrics",n),this.previousMetrics=n;let s=this.calculateHealthScore(n),a=this.determineTrend(n);return e.logger.info("Test health analysis complete",{healthScore:s,findingsCount:i.length}),this.createResult(Date.now()-t,{itemsAnalyzed:n.totalTests,issuesFound:i.length,healthScore:s,trend:a,domainMetrics:{passRate:`${(n.passingTests/n.totalTests*100).toFixed(1)}%`,avgExecutionTime:`${n.avgExecutionTimeMs}ms`,reliability:`${n.reliability}%`,totalTests:n.totalTests}},i,r)}async collectMetrics(e){let t=await e.memory.get("test-health:previous-metrics");if(t&&(this.previousMetrics=t),!e.domains.getDomainAPI("test-execution"))throw new Error("Test-execution domain not available - cannot compute health metrics. Ensure the test-execution domain is properly initialized before running this worker.");try{let r=await e.memory.search("test-health:run-result:*");if(r.length===0)throw new Error('No test run data found in memory - cannot compute health metrics. Run some tests first or ensure test results are being stored with keys matching "test-health:run-result:*".');let n=0,s=0,a=0,o=0,l=0,d=0;for(let p of r.slice(0,50)){let f=await e.memory.get(p);f&&(n+=f.total,s+=f.passed,a+=f.failed,o+=f.skipped,l+=f.duration,d++)}let u=d>0?Math.round(l/d):0,m=n>0?Math.round(s/n*100):0,g=await e.memory.get("test-health:growth-metrics");return{totalTests:n||0,passingTests:s||0,failingTests:a||0,skippedTests:o||0,avgExecutionTimeMs:u,reliability:m,growth:{testsAddedLast7Days:g?.testsAddedLast7Days||0,testsRemovedLast7Days:g?.testsRemovedLast7Days||0}}}catch(r){let n=D(r);throw new Error(`Failed to collect test health metrics: ${n}. Check memory service connectivity and test result data availability.`)}}analyzePassRate(e,t,i){let r=e.passingTests/e.totalTests*100;r<95&&(t.push({type:"low-pass-rate",severity:r<90?"high":"medium",domain:"test-execution",title:"Low Test Pass Rate",description:`Test pass rate is ${r.toFixed(1)}%, below the 95% target`,context:{passing:e.passingTests,failing:e.failingTests,total:e.totalTests}}),i.push({priority:"p1",domain:"test-execution",action:"Investigate Failing Tests",description:`${e.failingTests} tests are currently failing. Review and fix to improve pass rate.`,estimatedImpact:"high",effort:"medium",autoFixable:!1}))}analyzeExecutionTime(e,t,i){e.avgExecutionTimeMs>500&&(t.push({type:"slow-tests",severity:e.avgExecutionTimeMs>1e3?"high":"medium",domain:"test-execution",title:"Slow Test Execution",description:`Average test execution time is ${e.avgExecutionTimeMs}ms, consider optimization`,context:{avgExecutionTimeMs:e.avgExecutionTimeMs}}),i.push({priority:"p2",domain:"test-execution",action:"Optimize Test Execution Time",description:"Review and optimize slow-running tests. Consider parallelization or mocking slow dependencies.",estimatedImpact:"medium",effort:"medium",autoFixable:!1}))}analyzeReliability(e,t,i){e.reliability<95&&(t.push({type:"reliability-issue",severity:e.reliability<85?"high":"medium",domain:"test-execution",title:"Test Reliability Concern",description:`Test reliability score is ${e.reliability}%, indicating potential flaky tests`,context:{reliability:e.reliability}}),i.push({priority:"p1",domain:"test-execution",action:"Address Flaky Tests",description:"Identify and fix flaky tests to improve overall test reliability.",estimatedImpact:"high",effort:"medium",autoFixable:!1}))}analyzeGrowth(e,t,i){let r=e.growth.testsAddedLast7Days-e.growth.testsRemovedLast7Days;r<0&&(t.push({type:"test-coverage-decline",severity:"medium",domain:"test-generation",title:"Test Coverage Declining",description:`Net loss of ${Math.abs(r)} tests in the last 7 days`,context:{added:e.growth.testsAddedLast7Days,removed:e.growth.testsRemovedLast7Days}}),i.push({priority:"p2",domain:"test-generation",action:"Review Test Coverage Strategy",description:"More tests are being removed than added. Ensure adequate test coverage is maintained.",estimatedImpact:"medium",effort:"low",autoFixable:!1}))}compareToPrevious(e,t,i){if(!this.previousMetrics)return;let r=e.passingTests/e.totalTests-this.previousMetrics.passingTests/this.previousMetrics.totalTests;r<-.05&&t.push({type:"pass-rate-regression",severity:"high",domain:"test-execution",title:"Pass Rate Regression Detected",description:`Pass rate dropped by ${(Math.abs(r)*100).toFixed(1)}% since last check`,context:{previousPassRate:`${(this.previousMetrics.passingTests/this.previousMetrics.totalTests*100).toFixed(1)}%`,currentPassRate:`${(e.passingTests/e.totalTests*100).toFixed(1)}%`}})}calculateHealthScore(e){let t=e.passingTests/e.totalTests*40,i=e.reliability/100*30,r=Math.max(0,20-e.avgExecutionTimeMs/100),n=Math.min(10,e.growth.testsAddedLast7Days/10*10);return Math.round(t+i+r+n)}determineTrend(e){if(!this.previousMetrics)return"stable";let t=e.passingTests/e.totalTests,i=this.previousMetrics.passingTests/this.previousMetrics.totalTests;return t>i+.02?"improving":t<i-.02?"degrading":"stable"}};var Je={id:"coverage-tracker",name:"Coverage Tracker",description:"Tracks coverage trends over time including gaps, hotspots, and critical paths",intervalMs:600*1e3,priority:"high",targetDomains:["coverage-analysis","test-generation"],enabled:!0,timeoutMs:12e4,retryCount:2,retryDelayMs:1e4},F=class extends y{constructor(){super(Je)}async doExecute(e){let t=Date.now();e.logger.info("Starting coverage tracking analysis");let i=[],r=[],n=await this.collectCoverageTrend(e),s=await this.identifyCoverageGaps(e);this.analyzeCoverageGaps(s,i,r);let a=n.current;a?(this.analyzeCoverageThresholds(a,i,r),this.analyzeCoverageTrends({...n,current:a},i,r),await e.memory.set("coverage:current",a)):i.push({type:"coverage-unmeasured",severity:"info",domain:"coverage-analysis",title:"Coverage Unmeasured",description:"No measured coverage exists yet (no instrumented coverage:latest). Nothing was tracked; this is not 0% coverage. Run tests with coverage or coverage_analyze_sublinear."}),await e.memory.set("coverage:gaps",s);let o=this.calculateHealthScore(a,s);e.logger.info("Coverage tracking complete",{healthScore:o,measured:a!==null,findingsCount:i.length,gapsFound:s.length});let l=d=>d==null?"n/a":`${d}%`;return this.createResult(Date.now()-t,{itemsAnalyzed:s.length+(a?4:0),issuesFound:i.filter(d=>d.severity!=="info").length,healthScore:o,trend:a?this.determineTrend({...n,current:a}):"stable",domainMetrics:{coverageMeasured:a?"true":"false",lineCoverage:a?l(a.line):"unmeasured",branchCoverage:a?l(a.branch):"unmeasured",functionCoverage:a?l(a.function):"unmeasured",statementCoverage:a?l(a.statement):"unmeasured",gapsCount:s.length}},i,r)}async collectCoverageTrend(e){let t=await e.memory.get("coverage:current"),i=t&&t.measured===!0&&Number.isFinite(t.line)?t:void 0,r=E(await e.memory.get("coverage:latest"));return r?{current:{line:r.line,branch:r.branch,function:r.function,statement:r.statement,timestamp:new Date,measured:!0},previous:i}:{current:null,previous:i}}async identifyCoverageGaps(e){let t=await e.memory.search("gap-pattern:*");if(t.length>0){let i=[];for(let r of t){let n=await e.memory.get(r);n&&typeof n.riskScore=="number"&&i.push(n)}if(i.length>0)return i}return[]}analyzeCoverageThresholds(e,t,i){let r={line:80,branch:70,function:80,statement:80};e.line<r.line&&t.push({type:"low-line-coverage",severity:e.line<60?"high":"medium",domain:"coverage-analysis",title:"Line Coverage Below Threshold",description:`Line coverage is ${e.line}%, below ${r.line}% target`,context:{current:e.line,target:r.line}}),e.branch!==null&&e.branch<r.branch&&(t.push({type:"low-branch-coverage",severity:e.branch<50?"high":"medium",domain:"coverage-analysis",title:"Branch Coverage Below Threshold",description:`Branch coverage is ${e.branch}%, below ${r.branch}% target`,context:{current:e.branch,target:r.branch}}),i.push({priority:"p1",domain:"test-generation",action:"Improve Branch Coverage",description:"Add tests for uncovered conditional branches. Focus on complex decision points.",estimatedImpact:"high",effort:"medium",autoFixable:!0})),e.function!==null&&e.function<r.function&&t.push({type:"low-function-coverage",severity:"medium",domain:"coverage-analysis",title:"Function Coverage Below Threshold",description:`Function coverage is ${e.function}%, below ${r.function}% target`,context:{current:e.function,target:r.function}})}analyzeCoverageGaps(e,t,i){let r=e.filter(s=>s.riskScore>.8);for(let s of r)t.push({type:"high-risk-coverage-gap",severity:"high",domain:"coverage-analysis",title:"High-Risk Coverage Gap",description:`${s.file} has ${s.uncoveredLines} uncovered lines with complexity ${s.complexity}`,resource:s.file,context:{uncoveredLines:s.uncoveredLines,totalLines:s.totalLines,coveragePercent:((s.totalLines-s.uncoveredLines)/s.totalLines*100).toFixed(1),complexity:s.complexity,riskScore:s.riskScore}});r.length>0&&i.push({priority:"p0",domain:"test-generation",action:"Address High-Risk Coverage Gaps",description:`${r.length} files have high-risk coverage gaps. Prioritize testing for complex, uncovered code.`,estimatedImpact:"high",effort:"high",autoFixable:!0});let n=e.filter(s=>(s.totalLines-s.uncoveredLines)/s.totalLines<.5);n.length>0&&t.push({type:"critical-coverage-gaps",severity:"critical",domain:"coverage-analysis",title:"Critical Coverage Gaps Detected",description:`${n.length} files have less than 50% coverage`,context:{files:n.map(s=>s.file)}})}analyzeCoverageTrends(e,t,i){if(!e.previous)return;let r=e.current.line-e.previous.line,n=e.current.branch!==null&&e.previous.branch!==null?e.current.branch-e.previous.branch:0;r<-2&&(t.push({type:"coverage-regression",severity:r<-5?"high":"medium",domain:"coverage-analysis",title:"Coverage Regression Detected",description:`Line coverage dropped by ${Math.abs(r).toFixed(1)}% since last check`,context:{previous:e.previous.line,current:e.current.line,change:r}}),i.push({priority:"p1",domain:"test-generation",action:"Investigate Coverage Regression",description:"Recent changes have reduced code coverage. Review new code and add missing tests.",estimatedImpact:"high",effort:"medium",autoFixable:!1})),n<-3&&t.push({type:"branch-coverage-regression",severity:"medium",domain:"coverage-analysis",title:"Branch Coverage Regression",description:`Branch coverage dropped by ${Math.abs(n).toFixed(1)}%`,context:{previous:e.previous.branch,current:e.current.branch,change:n}})}calculateHealthScore(e,t){let i=t.filter(l=>l.riskScore>.8).length,r=Math.max(0,10-i*2);if(!e)return r*10;let s=[[e.line,25],[e.branch,25],[e.function,20],[e.statement,20]].filter(l=>l[0]!==null),a=s.reduce((l,[,d])=>l+d,0),o=s.reduce((l,[d,u])=>l+d/100*u,0)*(90/a);return Math.round(o+r)}determineTrend(e){if(!e.previous)return"stable";let t=n=>{let s=[n.line,n.branch,n.function,n.statement].filter(a=>a!==null);return s.reduce((a,o)=>a+o,0)/s.length},i=t(e.current),r=t(e.previous);return i>r+1?"improving":i<r-1?"degrading":"stable"}};var Ze={id:"flaky-detector",name:"Flaky Test Detector",description:"Detects flaky test patterns through statistical analysis of test execution history",intervalMs:900*1e3,priority:"high",targetDomains:["test-execution"],enabled:!0,timeoutMs:18e4,retryCount:2,retryDelayMs:1e4},$=class extends y{constructor(){super(Ze)}async doExecute(e){let t=Date.now();e.logger.info("Starting flaky test detection");let i=[],r=[],n=await this.collectTestHistory(e),s=this.detectFlakyTests(n);this.generateFindings(s,i,r),await e.memory.set("flaky:detected",s),await e.memory.set("flaky:lastAnalysis",new Date().toISOString());let a=this.calculateHealthScore(n.length,s);return e.logger.info("Flaky test detection complete",{healthScore:a,testsAnalyzed:n.length,flakyTestsFound:s.length}),this.createResult(Date.now()-t,{itemsAnalyzed:n.length,issuesFound:s.length,healthScore:a,trend:"stable",domainMetrics:{testsAnalyzed:n.length,flakyTests:s.length,flakinessRate:`${(s.length/n.length*100).toFixed(1)}%`,avgFlakinessScore:s.length>0?(s.reduce((o,l)=>o+l.flakinessScore,0)/s.length).toFixed(1):"0"}},i,r)}async collectTestHistory(e){if(!e.domains.getDomainAPI("test-execution"))throw new Error("Test-execution domain not available - cannot detect flaky tests. Ensure the test-execution domain is properly initialized before running this worker.");let i=await e.memory.search("flaky:history:*");if(i.length===0)throw new Error('No test execution history found in memory - cannot detect flaky tests. Run tests multiple times and ensure history is stored with keys matching "flaky:history:*" before running this worker.');let r=[],n=[];for(let s of i)try{let a=await e.memory.get(s);a&&r.push(a)}catch{n.push(s)}if(r.length===0)throw new Error(`Found ${i.length} test history keys but failed to retrieve any data. Failed keys: ${n.slice(0,5).join(", ")}${n.length>5?"...":""}. Check memory service connectivity and data format.`);return r}detectFlakyTests(e){let t=[];for(let i of e){let r=this.analyzeTestFlakiness(i);r.flakinessScore>20&&t.push(r)}return t.sort((i,r)=>r.flakinessScore-i.flakinessScore)}analyzeTestFlakiness(e){let t=e.executions,r=t.filter(p=>p.passed).length/t.length,n=t.map(p=>p.durationMs),s=n.reduce((p,f)=>p+f,0)/n.length,a=n.reduce((p,f)=>p+Math.pow(f-s,2),0)/n.length,l=Math.sqrt(a)/s,d=t.slice(-5).filter(p=>!p.passed).length,u=this.determinePattern(e,l),m=0;r>0&&r<1&&(m+=(1-r)*50),l>.5&&(m+=Math.min(25,l*10)),m+=d*5;let g=this.suggestFix(u);return{testId:e.testId,testName:e.testName,file:e.file,flakinessScore:Math.min(100,Math.round(m)),pattern:u,passRate:r*100,avgDuration:s,durationVariance:l,recentFailures:d,suggestedFix:g}}determinePattern(e,t){let i=e.executions.filter(n=>!n.passed);if(t>1||i.some(n=>n.error?.includes("Timeout")))return"timing";if(i.some(n=>n.error?.includes("Resource")||n.error?.includes("connection")))return"resource";if(i.some(n=>n.error?.includes("Race")||n.error?.includes("async")))return"intermittent";let r=e.executions.map(n=>n.passed);return this.hasOrderPattern(r)?"order-dependent":"intermittent"}hasOrderPattern(e){let t=e.map((n,s)=>n?-1:s).filter(n=>n>=0);if(t.length<2)return!1;let i=t.every(n=>n%2===0),r=t.every(n=>n%2===1);return i||r}suggestFix(e){switch(e){case"timing":return"Add explicit waits, increase timeouts, or use async utilities like waitFor";case"resource":return"Ensure proper resource cleanup, use test isolation, or implement connection pooling";case"order-dependent":return"Make tests independent, reset state in beforeEach, avoid shared mutable state";case"intermittent":return"Add retry logic, investigate race conditions, or use proper synchronization";default:return"Review test for potential issues with async operations or shared state"}}generateFindings(e,t,i){let r=e.filter(o=>o.flakinessScore>=70),n=e.filter(o=>o.flakinessScore>=50&&o.flakinessScore<70),s=e.filter(o=>o.flakinessScore>=20&&o.flakinessScore<50);for(let o of r)t.push({type:"critical-flaky-test",severity:"critical",domain:"test-execution",title:`Critical Flaky Test: ${o.testName}`,description:`Test has ${o.flakinessScore}% flakiness score with ${o.passRate.toFixed(0)}% pass rate`,resource:o.file,context:{testId:o.testId,pattern:o.pattern,recentFailures:o.recentFailures,suggestedFix:o.suggestedFix}});for(let o of n)t.push({type:"high-flaky-test",severity:"high",domain:"test-execution",title:`Flaky Test: ${o.testName}`,description:`Test has ${o.flakinessScore}% flakiness score (${o.pattern} pattern)`,resource:o.file,context:{testId:o.testId,pattern:o.pattern,suggestedFix:o.suggestedFix}});for(let o of s)t.push({type:"medium-flaky-test",severity:"medium",domain:"test-execution",title:`Potentially Flaky Test: ${o.testName}`,description:`Test shows flakiness indicators (score: ${o.flakinessScore}%)`,resource:o.file,context:{testId:o.testId,pattern:o.pattern}});r.length>0&&i.push({priority:"p0",domain:"test-execution",action:"Fix Critical Flaky Tests",description:`${r.length} tests have critical flakiness. These severely impact CI reliability.`,estimatedImpact:"high",effort:"high",autoFixable:!1});let a=e.filter(o=>o.pattern==="timing");a.length>0&&i.push({priority:"p1",domain:"test-execution",action:"Address Timing-Related Flakiness",description:`${a.length} tests have timing issues. Consider using proper async utilities.`,estimatedImpact:"medium",effort:"medium",autoFixable:!1})}calculateHealthScore(e,t){if(e===0)return 100;let i=t.length/e,r=t.length>0?t.reduce((a,o)=>a+o.flakinessScore,0)/t.length:0,n=100;n-=i*50,n-=r/100*30;let s=t.filter(a=>a.flakinessScore>=70).length;return n-=s*5,Math.max(0,Math.round(n))}};var N=["critical","high","medium","low","informational"],et=/^CVE-\d{4}-\d{4,}$/,ie=c=>typeof c=="number"&&Number.isInteger(c)&&c>=0,R=c=>!!c&&typeof c=="object"&&!Array.isArray(c);function tt(c){if(!R(c))return null;let e={};for(let t of N){if(!ie(c[t]))return null;e[t]=c[t]}return e}function nt(c,e){if(typeof c!="string")return null;let t=Date.parse(c);return!Number.isFinite(t)||t>e+6e4||e-t>6048e5?null:c}function rt(c,e){if(!R(c))return null;let t=c.severity;if(!N.includes(t)||typeof c.title!="string")return null;let i=R(c.location)?c.location:{},r=R(c.remediation)?c.remediation:{},n={severity:t,title:c.title,description:typeof c.description=="string"?c.description:"",category:typeof c.category=="string"?c.category:"other",references:Array.isArray(c.references)?c.references.filter(s=>typeof s=="string"):[]};if(typeof c.cveId=="string"&&et.test(c.cveId)&&(n.cve=c.cveId),e==="dependency"){let s=R(i.dependency)&&typeof i.dependency.name=="string"?i.dependency.name:typeof i.snippet=="string"?/^"([^"]+)":/.exec(i.snippet)?.[1]:void 0;s&&(n.package=s);let a=typeof r.fixExample=="string"?/@([^@\s]+)$/.exec(r.fixExample)?.[1]:void 0;a&&(n.fixedIn=a)}else typeof i.file=="string"&&(n.location=typeof i.line=="number"?`${i.file}:${i.line}`:i.file);return n}function it(c){return Array.isArray(c)?c.filter(R).map(e=>({name:typeof e.name=="string"?e.name:"?",version:typeof e.version=="string"?e.version:"?",reason:typeof e.reason=="string"?e.reason:"unknown"})):[]}function st(c){return c.measured===!0&&c.status==="complete"?{complete:!0}:{complete:!1,status:c.status==="incomplete"||c.status==="failed"?c.status:"unknown",...typeof c.error=="string"&&c.error?{error:c.error}:{},uncheckedPackages:it(c.uncheckedPackages),...ie(c.packagesChecked)?{packagesChecked:c.packagesChecked}:{}}}var Pe={critical:"Critical",high:"High Severity",medium:"Medium Severity",low:"Low Severity",informational:"Informational"};function se(c){return c?c.scan.summary.critical*20+c.scan.summary.high*10:0}function ae(c){return c?{dependencyVulnerabilitiesInCheckedPackages:c.scan.total,dependencyPackagesUnchecked:c.uncheckedPackages.length}:{}}function Ie(c,e){if(!R(c))return null;let t=c.scanType;if(t!=="dependency"&&t!=="sast")return null;let i=nt(c.timestamp,e),r=tt(c.summary);if(typeof c.scanId!="string"||!i||!r)return null;let n=t==="dependency"?c.vulnerabilities:c.criticalVulnerabilities;if(!Array.isArray(n))return null;let s=n.map(d=>rt(d,t));if(s.some(d=>d===null))return null;let a=N.reduce((d,u)=>d+r[u],0),o=t==="sast"&&ie(c.vulnerabilityCount)?c.vulnerabilityCount:a,l={scanId:c.scanId,scannedAt:i,summary:r,vulnerabilities:s,total:o};return t==="sast"?{kind:t,scan:l}:{kind:t,scan:l,completeness:st(c)}}var ot={id:"security-scan",name:"Security Vulnerability Scanner",description:"Scans for security vulnerabilities in dependencies, code patterns, and configurations",intervalMs:1800*1e3,priority:"critical",targetDomains:["security-compliance"],enabled:!0,timeoutMs:3e5,retryCount:3,retryDelayMs:3e4},oe="security-compliance",Ee="security:scan:*",ct="security:lastScan",lt=1e3,L=class extends y{constructor(){super(ot)}async doExecute(e){let t=Date.now();e.logger.info("Starting security vulnerability scan");let i=[],r=[],{scan:n,incompleteDependency:s}=await this.readRecordedScans(e);if(s&&this.reportIncompleteDependencyScan(s,i,r),!n)return s||i.push({type:"security-unmeasured",severity:"info",domain:"security-compliance",title:"Security Scan Unmeasured",description:"No dependency or SAST scan has been recorded in the last 7 days, so no vulnerabilities are reported and nothing was stored. Run security_scan_comprehensive (or `aqe security`) to scan the project."}),e.logger.info("Security scan complete",{measured:!1}),this.createResult(Date.now()-t,{itemsAnalyzed:s?.scan.total??0,issuesFound:i.filter(o=>o.severity!=="info").length,healthScore:Math.max(0,100-se(s)),trend:"stable",domainMetrics:{dependencyScan:"unmeasured",codeScan:"unmeasured",dependencyVulnerabilities:"unmeasured",codeSecurityIssues:"unmeasured",...ae(s)}},i,r);n.dependency&&this.analyzeDependencyVulnerabilities(n.dependency,i,r),n.code&&this.analyzeCodeSecurityIssues(n.code,i,r),await e.memory.set(ct,n),await e.memory.set("security:lastScanTime",n.evaluatedAt);let a=Math.max(0,this.calculateHealthScore(n)-se(s));return e.logger.info("Security scan complete",{measured:!0,healthScore:a,dependencyScanId:n.dependency?.scanId??null,codeScanId:n.code?.scanId??null}),this.createResult(Date.now()-t,{itemsAnalyzed:(n.dependency?.total??0)+(n.code?.total??0),issuesFound:i.length,healthScore:a,trend:"stable",domainMetrics:{dependencyScan:n.dependency?n.dependency.scannedAt:"unmeasured",codeScan:n.code?n.code.scannedAt:"unmeasured",dependencyVulnerabilities:n.dependency?n.dependency.total:"unmeasured",codeSecurityIssues:n.code?n.code.total:"unmeasured",...ae(s)}},i,r)}async readRecordedScans(e){let t=await e.memory.search(Ee,lt,{namespace:oe}),i=Date.now(),r=null,n=null,s=(d,u)=>!u||Date.parse(d.scannedAt)>Date.parse(u.scannedAt);for(let d of t){let u=x(d,oe,Ee),m=Ie(await e.memory.get(u,{namespace:oe}),i);m&&(m.kind==="dependency"&&s(m.scan,r?.scan??null)&&(r=m),m.kind==="sast"&&s(m.scan,n)&&(n=m.scan))}let a=r?.completeness,o=r&&a?.complete?r.scan:null,l=r&&a&&!a.complete?{scan:r.scan,status:a.status,...a.error?{error:a.error}:{},uncheckedPackages:a.uncheckedPackages,...a.packagesChecked!==void 0?{packagesChecked:a.packagesChecked}:{}}:null;return!o&&!n?{scan:null,incompleteDependency:l}:{incompleteDependency:l,scan:{measured:!0,schemaVersion:1,evaluatedAt:new Date().toISOString(),dependency:o?{...o,source:"osv"}:null,code:n?{...n,source:"sast"}:null}}}reportIncompleteDependencyScan(e,t,i){let{scan:r,status:n,error:s,uncheckedPackages:a,packagesChecked:o}=e,l=a.map(g=>`${g.name}@${g.version} (${g.reason})`),d=r.summary,u=r.total>0?` OSV reported ${r.total} advisory finding(s) in the ${o??""}${o===void 0?"":" "}checked package(s) (${d.critical} critical, ${d.high} high, ${d.medium} medium, ${d.low} low); they are listed as separate findings.`:"",m=n==="unknown"?"was recorded before scans stated whether every package was checked, so a failed lookup cannot be told apart from a clean one":`is ${n}${s?` (${s})`:""}`;t.push({type:"dependency-scan-incomplete",severity:"info",domain:"security-compliance",title:"Dependency Scan Unmeasured",description:`The latest dependency scan (${r.scannedAt}) ${m}; its result is not a vulnerability count.`+(l.length>0?` Unchecked packages: ${l.join(", ")}.`:"")+u+" Re-run the dependency scan.",context:{scanId:r.scanId,status:n,...s?{error:s}:{},uncheckedPackages:a,...o!==void 0?{packagesChecked:o}:{},advisoriesInCheckedPackages:r.total}}),this.analyzeDependencyVulnerabilities(r,t,i,!0)}analyzeDependencyVulnerabilities(e,t,i,r=!1){let n=e.vulnerabilities.filter(o=>o.severity==="critical"),s=e.vulnerabilities.filter(o=>o.severity==="high"),a=r?N.flatMap(o=>e.vulnerabilities.filter(l=>l.severity===o)):[...n,...s];for(let o of a){let l=o.package??o.title;t.push({type:`${o.severity}-vulnerability`,severity:o.severity==="informational"?"info":o.severity,domain:"security-compliance",title:`${Pe[o.severity]} Vulnerability in ${l}`,description:o.description?`${o.title}: ${o.description}`:o.title,resource:l,context:{advisorySource:"osv",scanId:e.scanId,scannedAt:e.scannedAt,...o.cve?{cve:o.cve}:{},...o.fixedIn?{fixedIn:o.fixedIn}:{},references:o.references,...r?{partialScan:!0}:{}}})}n.length>0&&i.push({priority:"p0",domain:"security-compliance",action:"Update Critical Vulnerabilities Immediately",description:`The dependency scan of ${e.scannedAt} reported ${n.length} critical vulnerabilities. Update to patched versions.`,estimatedImpact:"high",effort:"low",autoFixable:!0}),s.length>0&&i.push({priority:"p1",domain:"security-compliance",action:"Address High Severity Vulnerabilities",description:`The dependency scan of ${e.scannedAt} reported ${s.length} high severity vulnerabilities. Plan updates within current sprint.`,estimatedImpact:"high",effort:"low",autoFixable:!0})}analyzeCodeSecurityIssues(e,t,i){for(let s of e.vulnerabilities)t.push({type:`code-security-${s.category}`,severity:s.severity==="informational"?"info":s.severity,domain:"security-compliance",title:`Security Issue: ${s.title}`,description:s.description||s.title,...s.location?{resource:s.location}:{},context:{category:s.category,scanId:e.scanId,scannedAt:e.scannedAt,...s.cve?{cve:s.cve}:{}}});let r=e.vulnerabilities.filter(s=>s.category==="injection");r.length>0&&i.push({priority:"p0",domain:"security-compliance",action:"Fix Injection Vulnerabilities",description:`The SAST scan of ${e.scannedAt} reported ${r.length} potential injection vulnerabilities. Use parameterized queries and avoid eval().`,estimatedImpact:"high",effort:"medium",autoFixable:!1});let n=e.vulnerabilities.filter(s=>s.category==="sensitive-data");n.length>0&&i.push({priority:"p1",domain:"security-compliance",action:"Review Sensitive Data Handling",description:`The SAST scan of ${e.scannedAt} reported ${n.length} sensitive-data issues. Ensure secure algorithms and key management.`,estimatedImpact:"high",effort:"high",autoFixable:!1})}calculateHealthScore(e){let t=100;return e.dependency&&(t-=e.dependency.summary.critical*20,t-=e.dependency.summary.high*10),e.code&&(t-=e.code.summary.critical*15,t-=e.code.summary.high*8),Math.max(0,Math.round(t))}};var dt={id:"quality-gate",name:"Quality Gate Evaluator",description:"Continuously evaluates quality gates and release readiness across all quality dimensions",intervalMs:300*1e3,priority:"critical",targetDomains:["quality-assessment"],enabled:!0,timeoutMs:12e4,retryCount:2,retryDelayMs:5e3},xe="quality-gate:current",We="quality-gate:history",Fe=1,ut=100;function mt(c){if(!c||typeof c!="object")return null;let e=c;return e.measured!==!0||e.schemaVersion!==Fe||typeof e.passed!="boolean"||!Array.isArray(e.checks)?null:e}var pt=c=>c.direction==="min"?">=":"<=",_=class extends y{constructor(){super(dt)}async doExecute(e){let t=Date.now();e.logger.info("Starting quality gate evaluation");let i=[],r=[],{values:n,problems:s}=await be(e.memory),a=Object.fromEntries(Z.map(p=>[p,n[p]??"unmeasured"]));if(s.length>0){let p=s.map(f=>f.metric);i.push({type:"quality-gate-insufficient-evidence",severity:"info",domain:"quality-assessment",title:"Quality Gate Not Evaluated: Insufficient Evidence",description:`${p.length} of ${Z.length} gate metrics have no usable measured evidence (${p.join(", ")}), so no verdict was reached and nothing was stored.`,context:{status:Q,unmeasured:p,problems:s}});for(let f of ke(p))r.push({priority:"p3",domain:"quality-assessment",action:"Record Measured Quality Evidence",description:f,estimatedImpact:"medium",effort:"low",autoFixable:!1});return e.logger.info("Quality gate evaluation complete",{status:Q,unmeasured:p}),this.createResult(Date.now()-t,{itemsAnalyzed:0,issuesFound:0,healthScore:100,trend:"stable",domainMetrics:{gateStatus:Q,gatePassed:"unmeasured",releaseReady:"unmeasured",unmeasuredMetrics:p.length,...a}},i,r)}let o=De(n),l=o.checks.filter(p=>!p.passed),d={measured:!0,schemaVersion:Fe,evaluatedAt:new Date().toISOString(),passed:o.passed,passedChecks:o.checks.length-l.length,failedChecks:l.length,checks:o.checks};this.analyzeGateResults(d,i,r),await this.compareToPrevious(e,d,i),await e.memory.set(xe,d),await e.memory.set("quality-gate:lastCheck",d.evaluatedAt);let u=await e.memory.get(We),m=Array.isArray(u)?u:[];for(m.push(d);m.length>ut;)m.shift();await e.memory.set(We,m);let g=this.calculateHealthScore(d);return e.logger.info("Quality gate evaluation complete",{healthScore:g,passed:d.passed,failedChecks:d.failedChecks}),this.createResult(Date.now()-t,{itemsAnalyzed:d.checks.length,issuesFound:d.failedChecks,healthScore:g,trend:"stable",domainMetrics:{gateStatus:"evaluated",gatePassed:d.passed?"YES":"NO",releaseReady:d.passed?"YES":"NO",passedChecks:d.passedChecks,failedChecks:d.failedChecks,...a}},i,r)}analyzeGateResults(e,t,i){let r=e.checks.filter(n=>!n.passed);for(let n of r)t.push({type:"quality-gate-failure",severity:n.severity,domain:"quality-assessment",title:`Quality Gate Failed: ${n.name}`,description:`Measured ${n.name} is ${n.value}, threshold is ${pt(n)} ${n.threshold}`,context:{metric:n.name,value:n.value,threshold:n.threshold,direction:n.direction}});r.length>0&&(t.push({type:"release-blocked",severity:r.some(n=>n.severity==="critical")?"critical":"high",domain:"quality-assessment",title:"Release Blocked",description:`${r.length} measured quality checks fail the gate`,context:{failingMetrics:r.map(n=>n.name)}}),i.push({priority:"p0",domain:"quality-assessment",action:"Resolve Failing Quality Checks",description:`Fix ${r.map(n=>n.name).join(", ")} before proceeding with release.`,estimatedImpact:"high",effort:"medium",autoFixable:!1}))}async compareToPrevious(e,t,i){let r=mt(await e.memory.get(xe));r&&(r.passed&&!t.passed&&i.push({type:"quality-gate-regression",severity:"high",domain:"quality-assessment",title:"Quality Gate Regression",description:"The measured quality gate was passing previously but is now failing",context:{previousEvaluatedAt:r.evaluatedAt,currentFailedChecks:t.failedChecks}}),!r.passed&&t.passed&&i.push({type:"quality-gate-improvement",severity:"info",domain:"quality-assessment",title:"Quality Gate Now Passing",description:"The measured quality gate is now passing after previous failures",context:{previousEvaluatedAt:r.evaluatedAt}}))}calculateHealthScore(e){if(e.checks.length===0)return 100;let t=e.passedChecks/e.checks.length*90;return e.passed&&(t+=10),Math.max(0,Math.min(100,Math.round(t)))}};Ye();J();Ke();var gt=30;function $e(c,e){return c.prepare(`PRAGMA table_info(${e})`).all().map(t=>t.name)}function Ne(c,e={}){let t=e.retentionDays??gt;if(!c.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='dream_insights'").get())return{pruned:0,archived:0,skippedNullId:0};let{cutoff:r}=c.prepare("SELECT datetime('now', ?) AS cutoff").get(`-${t} days`),n="d.applied = 0 AND d.created_at < ? AND d.id IS NOT NULL",s=c.prepare("SELECT COUNT(*) AS n FROM dream_insights d WHERE d.applied = 0 AND d.created_at < ? AND d.id IS NULL").get(r).n;return c.transaction(()=>{let o=c.prepare(`SELECT COUNT(*) AS n FROM dream_insights d WHERE ${n}`).get(r).n;if(o===0)return{pruned:0,archived:0,skippedNullId:s};c.exec(he);let l=new Set($e(c,w));if(!l.has("archive_id"))throw new Error(`${w} has no archive_id column; nothing deleted`);let d=$e(c,"dream_insights").filter(k=>k!=="archived_at"&&k!=="archive_id"&&l.has(k)),u=d.map(k=>`"${k}"`).join(", "),{mark:m}=c.prepare(`SELECT COALESCE(MAX(archive_id), 0) AS mark FROM ${w}`).get(),g=c.prepare(`INSERT INTO ${w} (${u}, archived_at)
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.15");process.exit(0)}
2
+ import{b as Me,c as Ae,e as Te}from"./chunk-LYJHUNBK.js";import{a as y,b as ee}from"./chunk-XHLYGXYE.js";import{b as Ce}from"./chunk-SHRI7TKJ.js";import{a as Re}from"./chunk-7O45RQHF.js";import"./chunk-RDMRY7CT.js";import"./chunk-K3WZICFA.js";import{a as we,c as x}from"./chunk-JKJOB65O.js";import{a as E}from"./chunk-OBDONJQM.js";import{c as Se}from"./chunk-H5DER3JY.js";import{a as Z,e as Q,f as ke,h as be,i as U,l as De}from"./chunk-3J3RNJNX.js";import{a as fe,v as ve}from"./chunk-OLZH5LRT.js";import{b as ye}from"./chunk-JCZCJE6X.js";import"./chunk-NQS3BWS6.js";import"./chunk-JUDUBQHA.js";import"./chunk-VY4U6DPO.js";import"./chunk-LVABQNRF.js";import"./chunk-PFQCV6YS.js";import"./chunk-RBKUU7WF.js";import"./chunk-Q6I4SIUU.js";import"./chunk-UXIY4IAI.js";import"./chunk-KCQNFBBR.js";import"./chunk-C4KLXFJP.js";import"./chunk-ZYJB6FML.js";import"./chunk-TODNOP7C.js";import"./chunk-2ZFLULL4.js";import"./chunk-ERN56H6S.js";import"./chunk-UQPA33UK.js";import"./chunk-HTZSRMHW.js";import"./chunk-YUS6TWAL.js";import"./chunk-AP2W7Z3A.js";import"./chunk-BP5T3OEV.js";import{g as w,h as he,i as Ke,r as I,v as Ye}from"./chunk-T66PPF4D.js";import"./chunk-337Z52QM.js";import"./chunk-XWIAZG3C.js";import"./chunk-5G4UFTV4.js";import"./chunk-DEKR3CTS.js";import"./chunk-4X3SWKBA.js";import"./chunk-W62OOK7A.js";import"./chunk-GCHYOPRZ.js";import"./chunk-DKX4GNRU.js";import"./chunk-PXATBHWN.js";import"./chunk-6NBRMD25.js";import"./chunk-5I7357KS.js";import"./chunk-QFGYH6HD.js";import{a as M}from"./chunk-LJMYRTJ7.js";import"./chunk-G242G224.js";import"./chunk-3HVFIITW.js";import"./chunk-BQ47GQPK.js";import"./chunk-ZWBGYJ7K.js";import"./chunk-UJABDXST.js";import"./chunk-6YVMX2TC.js";import"./chunk-DURD37JZ.js";import{c as j,d as Ue}from"./chunk-SZAZQZWI.js";import"./chunk-MPFPWJTH.js";import"./chunk-AOKKUB5F.js";import"./chunk-T4GE7MPI.js";import"./chunk-FOOW4JVS.js";import{a as D,e as J}from"./chunk-HL2ANKN3.js";import"./chunk-BZULJMGH.js";import"./chunk-XH4JMX5O.js";var te=class{handlers=[];async publish(e){for(let t of this.handlers)try{t(e)}catch(i){console.debug("[WorkerManager] Event handler error:",i instanceof Error?i.message:i)}}subscribe(e){return this.handlers.push(e),()=>{let t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)}}dispose(){this.handlers=[]}get handlerCount(){return this.handlers.length}},ne=class{store=new Map;async get(e,t){if(!t?.namespace)return this.store.get(e)}async set(e,t){this.store.set(e,t)}async search(e,t,i){if(i?.namespace)return[];let r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(r.replace(/\*/g,".*")),s=Array.from(this.store.keys()).filter(a=>n.test(a));return t===void 0?s:s.slice(0,t)}clear(){this.store.clear()}get size(){return this.store.size}},re=class{constructor(e){this.workerId=e}workerId;format(e,t,i){let r=new Date().toISOString(),n=i?` ${JSON.stringify(i)}`:"";return`[${r}] [${e}] [${this.workerId}] ${t}${n}`}debug(e,t){process.env.DEBUG&&console.debug(this.format("DEBUG",e,t))}info(e,t){console.info(this.format("INFO",e,t))}warn(e,t){console.warn(this.format("WARN",e,t))}error(e,t){console.error(this.format("ERROR",e,t))}},K=class{constructor(e){this.kernelGetter=e}kernelGetter;getDomainAPI(e){let t=this.kernelGetter();if(t)return t.getDomainAPI(e)}getDomainHealth(e){let t=this.kernelGetter();if(!t)return{status:"unknown",errors:["Kernel not available"]};let r=t.getHealth().domains[e];return r?{status:r.status,errors:r.errors||[]}:{status:"unknown",errors:[`Domain ${e} not found`]}}},Y=class{getDomainAPI(e){}getDomainHealth(e){return{status:"healthy",errors:[]}}},X=class{workers=new Map;timers=new Map;abortControllers=new Map;eventBus;memory;domainAccess;running=!1;kernelRef;constructor(e){this.eventBus=e?.eventBus??new te,this.memory=e?.memory??new ne,this.kernelRef=e?.kernel,e?.domainAccess?this.domainAccess=e.domainAccess:e?.kernel?this.domainAccess=new K(()=>this.kernelRef):this.domainAccess=new Y}setKernel(e){this.kernelRef=e,this.domainAccess instanceof Y&&(this.domainAccess=new K(()=>this.kernelRef))}setMemory(e){this.memory=e}register(e){if(this.workers.has(e.config.id))throw new Error(`Worker ${e.config.id} is already registered`);this.workers.set(e.config.id,e)}unregister(e){this.workers.get(e)&&(this.stopWorker(e),this.workers.delete(e))}get(e){return this.workers.get(e)}list(){return Array.from(this.workers.values())}async startAll(){this.running=!0;for(let e of Array.from(this.workers.values())){if(!this.running)break;e.config.enabled&&await this.startWorker(e)}}async stopAll(){this.running=!1;let e=[];for(let t of Array.from(this.workers.keys()))e.push(this.stopWorker(t));await Promise.all(e)}async runNow(e){let t=this.workers.get(e);if(!t)throw new Error(`Worker ${e} not found`);let i=this.timers.get(e);i&&clearTimeout(i);let r=new AbortController;this.abortControllers.set(e,r);let n=this.createContext(e,r.signal),s=await t.execute(n);return this.running&&t.config.enabled&&t.status!=="stopped"&&this.scheduleNextRun(t),s}getHealth(){let e={},t=0,i=0,r=0,n=0;for(let[a,o]of Array.from(this.workers.entries())){let l=o.getHealth();switch(e[a]=l,n+=l.healthScore,o.status){case"running":t++;break;case"paused":i++;break;case"error":r++;break}}let s=this.workers.size>0?Math.round(n/this.workers.size):100;return{totalWorkers:this.workers.size,runningWorkers:t,pausedWorkers:i,errorWorkers:r,healthScore:s,workers:e}}onWorkerEvent(e){return this.eventBus.subscribe(e)}async startWorker(e){await e.initialize();let t=new AbortController;this.abortControllers.set(e.config.id,t);let i=this.createContext(e.config.id,t.signal);try{await e.execute(i)}catch(r){console.error(`Worker ${e.config.id} initial execution failed:`,r)}this.scheduleNextRun(e)}async stopWorker(e){let t=this.timers.get(e);t&&(clearTimeout(t),this.timers.delete(e));let i=this.abortControllers.get(e);i&&(i.abort(),this.abortControllers.delete(e));let r=this.workers.get(e);r&&await r.stop()}scheduleNextRun(e){let t=setTimeout(async()=>{if(!this.running||e.status==="stopped"||e.status==="paused")return;let i=new AbortController;this.abortControllers.set(e.config.id,i);let r=this.createContext(e.config.id,i.signal);try{await e.execute(r)}catch(n){console.error(`Worker ${e.config.id} execution failed:`,n)}this.running&&e.config.enabled&&e.status!=="error"&&this.scheduleNextRun(e)},e.config.intervalMs);t.unref?.(),this.timers.set(e.config.id,t)}createContext(e,t){return{eventBus:this.eventBus,memory:this.memory,logger:new re(e),domains:this.domainAccess,signal:t}}};J();var Xe={id:"test-health",name:"Test Health Monitor",description:"Monitors test suite health metrics including pass rates, execution times, and reliability",intervalMs:300*1e3,priority:"high",targetDomains:["test-execution","test-generation"],enabled:!0,timeoutMs:6e4,retryCount:2,retryDelayMs:5e3},W=class extends y{previousMetrics;constructor(){super(Xe)}async doExecute(e){let t=Date.now();e.logger.info("Starting test health analysis");let i=[],r=[],n=await this.collectMetrics(e);this.analyzePassRate(n,i,r),this.analyzeExecutionTime(n,i,r),this.analyzeReliability(n,i,r),this.analyzeGrowth(n,i,r),this.compareToPrevious(n,i,r),await e.memory.set("test-health:previous-metrics",n),this.previousMetrics=n;let s=this.calculateHealthScore(n),a=this.determineTrend(n);return e.logger.info("Test health analysis complete",{healthScore:s,findingsCount:i.length}),this.createResult(Date.now()-t,{itemsAnalyzed:n.totalTests,issuesFound:i.length,healthScore:s,trend:a,domainMetrics:{passRate:`${(n.passingTests/n.totalTests*100).toFixed(1)}%`,avgExecutionTime:`${n.avgExecutionTimeMs}ms`,reliability:`${n.reliability}%`,totalTests:n.totalTests}},i,r)}async collectMetrics(e){let t=await e.memory.get("test-health:previous-metrics");if(t&&(this.previousMetrics=t),!e.domains.getDomainAPI("test-execution"))throw new Error("Test-execution domain not available - cannot compute health metrics. Ensure the test-execution domain is properly initialized before running this worker.");try{let r=await e.memory.search("test-health:run-result:*");if(r.length===0)throw new Error('No test run data found in memory - cannot compute health metrics. Run some tests first or ensure test results are being stored with keys matching "test-health:run-result:*".');let n=0,s=0,a=0,o=0,l=0,d=0;for(let p of r.slice(0,50)){let f=await e.memory.get(p);f&&(n+=f.total,s+=f.passed,a+=f.failed,o+=f.skipped,l+=f.duration,d++)}let u=d>0?Math.round(l/d):0,m=n>0?Math.round(s/n*100):0,g=await e.memory.get("test-health:growth-metrics");return{totalTests:n||0,passingTests:s||0,failingTests:a||0,skippedTests:o||0,avgExecutionTimeMs:u,reliability:m,growth:{testsAddedLast7Days:g?.testsAddedLast7Days||0,testsRemovedLast7Days:g?.testsRemovedLast7Days||0}}}catch(r){let n=D(r);throw new Error(`Failed to collect test health metrics: ${n}. Check memory service connectivity and test result data availability.`)}}analyzePassRate(e,t,i){let r=e.passingTests/e.totalTests*100;r<95&&(t.push({type:"low-pass-rate",severity:r<90?"high":"medium",domain:"test-execution",title:"Low Test Pass Rate",description:`Test pass rate is ${r.toFixed(1)}%, below the 95% target`,context:{passing:e.passingTests,failing:e.failingTests,total:e.totalTests}}),i.push({priority:"p1",domain:"test-execution",action:"Investigate Failing Tests",description:`${e.failingTests} tests are currently failing. Review and fix to improve pass rate.`,estimatedImpact:"high",effort:"medium",autoFixable:!1}))}analyzeExecutionTime(e,t,i){e.avgExecutionTimeMs>500&&(t.push({type:"slow-tests",severity:e.avgExecutionTimeMs>1e3?"high":"medium",domain:"test-execution",title:"Slow Test Execution",description:`Average test execution time is ${e.avgExecutionTimeMs}ms, consider optimization`,context:{avgExecutionTimeMs:e.avgExecutionTimeMs}}),i.push({priority:"p2",domain:"test-execution",action:"Optimize Test Execution Time",description:"Review and optimize slow-running tests. Consider parallelization or mocking slow dependencies.",estimatedImpact:"medium",effort:"medium",autoFixable:!1}))}analyzeReliability(e,t,i){e.reliability<95&&(t.push({type:"reliability-issue",severity:e.reliability<85?"high":"medium",domain:"test-execution",title:"Test Reliability Concern",description:`Test reliability score is ${e.reliability}%, indicating potential flaky tests`,context:{reliability:e.reliability}}),i.push({priority:"p1",domain:"test-execution",action:"Address Flaky Tests",description:"Identify and fix flaky tests to improve overall test reliability.",estimatedImpact:"high",effort:"medium",autoFixable:!1}))}analyzeGrowth(e,t,i){let r=e.growth.testsAddedLast7Days-e.growth.testsRemovedLast7Days;r<0&&(t.push({type:"test-coverage-decline",severity:"medium",domain:"test-generation",title:"Test Coverage Declining",description:`Net loss of ${Math.abs(r)} tests in the last 7 days`,context:{added:e.growth.testsAddedLast7Days,removed:e.growth.testsRemovedLast7Days}}),i.push({priority:"p2",domain:"test-generation",action:"Review Test Coverage Strategy",description:"More tests are being removed than added. Ensure adequate test coverage is maintained.",estimatedImpact:"medium",effort:"low",autoFixable:!1}))}compareToPrevious(e,t,i){if(!this.previousMetrics)return;let r=e.passingTests/e.totalTests-this.previousMetrics.passingTests/this.previousMetrics.totalTests;r<-.05&&t.push({type:"pass-rate-regression",severity:"high",domain:"test-execution",title:"Pass Rate Regression Detected",description:`Pass rate dropped by ${(Math.abs(r)*100).toFixed(1)}% since last check`,context:{previousPassRate:`${(this.previousMetrics.passingTests/this.previousMetrics.totalTests*100).toFixed(1)}%`,currentPassRate:`${(e.passingTests/e.totalTests*100).toFixed(1)}%`}})}calculateHealthScore(e){let t=e.passingTests/e.totalTests*40,i=e.reliability/100*30,r=Math.max(0,20-e.avgExecutionTimeMs/100),n=Math.min(10,e.growth.testsAddedLast7Days/10*10);return Math.round(t+i+r+n)}determineTrend(e){if(!this.previousMetrics)return"stable";let t=e.passingTests/e.totalTests,i=this.previousMetrics.passingTests/this.previousMetrics.totalTests;return t>i+.02?"improving":t<i-.02?"degrading":"stable"}};var Je={id:"coverage-tracker",name:"Coverage Tracker",description:"Tracks coverage trends over time including gaps, hotspots, and critical paths",intervalMs:600*1e3,priority:"high",targetDomains:["coverage-analysis","test-generation"],enabled:!0,timeoutMs:12e4,retryCount:2,retryDelayMs:1e4},F=class extends y{constructor(){super(Je)}async doExecute(e){let t=Date.now();e.logger.info("Starting coverage tracking analysis");let i=[],r=[],n=await this.collectCoverageTrend(e),s=await this.identifyCoverageGaps(e);this.analyzeCoverageGaps(s,i,r);let a=n.current;a?(this.analyzeCoverageThresholds(a,i,r),this.analyzeCoverageTrends({...n,current:a},i,r),await e.memory.set("coverage:current",a)):i.push({type:"coverage-unmeasured",severity:"info",domain:"coverage-analysis",title:"Coverage Unmeasured",description:"No measured coverage exists yet (no instrumented coverage:latest). Nothing was tracked; this is not 0% coverage. Run tests with coverage or coverage_analyze_sublinear."}),await e.memory.set("coverage:gaps",s);let o=this.calculateHealthScore(a,s);e.logger.info("Coverage tracking complete",{healthScore:o,measured:a!==null,findingsCount:i.length,gapsFound:s.length});let l=d=>d==null?"n/a":`${d}%`;return this.createResult(Date.now()-t,{itemsAnalyzed:s.length+(a?4:0),issuesFound:i.filter(d=>d.severity!=="info").length,healthScore:o,trend:a?this.determineTrend({...n,current:a}):"stable",domainMetrics:{coverageMeasured:a?"true":"false",lineCoverage:a?l(a.line):"unmeasured",branchCoverage:a?l(a.branch):"unmeasured",functionCoverage:a?l(a.function):"unmeasured",statementCoverage:a?l(a.statement):"unmeasured",gapsCount:s.length}},i,r)}async collectCoverageTrend(e){let t=await e.memory.get("coverage:current"),i=t&&t.measured===!0&&Number.isFinite(t.line)?t:void 0,r=E(await e.memory.get("coverage:latest"));return r?{current:{line:r.line,branch:r.branch,function:r.function,statement:r.statement,timestamp:new Date,measured:!0},previous:i}:{current:null,previous:i}}async identifyCoverageGaps(e){let t=await e.memory.search("gap-pattern:*");if(t.length>0){let i=[];for(let r of t){let n=await e.memory.get(r);n&&typeof n.riskScore=="number"&&i.push(n)}if(i.length>0)return i}return[]}analyzeCoverageThresholds(e,t,i){let r={line:80,branch:70,function:80,statement:80};e.line<r.line&&t.push({type:"low-line-coverage",severity:e.line<60?"high":"medium",domain:"coverage-analysis",title:"Line Coverage Below Threshold",description:`Line coverage is ${e.line}%, below ${r.line}% target`,context:{current:e.line,target:r.line}}),e.branch!==null&&e.branch<r.branch&&(t.push({type:"low-branch-coverage",severity:e.branch<50?"high":"medium",domain:"coverage-analysis",title:"Branch Coverage Below Threshold",description:`Branch coverage is ${e.branch}%, below ${r.branch}% target`,context:{current:e.branch,target:r.branch}}),i.push({priority:"p1",domain:"test-generation",action:"Improve Branch Coverage",description:"Add tests for uncovered conditional branches. Focus on complex decision points.",estimatedImpact:"high",effort:"medium",autoFixable:!0})),e.function!==null&&e.function<r.function&&t.push({type:"low-function-coverage",severity:"medium",domain:"coverage-analysis",title:"Function Coverage Below Threshold",description:`Function coverage is ${e.function}%, below ${r.function}% target`,context:{current:e.function,target:r.function}})}analyzeCoverageGaps(e,t,i){let r=e.filter(s=>s.riskScore>.8);for(let s of r)t.push({type:"high-risk-coverage-gap",severity:"high",domain:"coverage-analysis",title:"High-Risk Coverage Gap",description:`${s.file} has ${s.uncoveredLines} uncovered lines with complexity ${s.complexity}`,resource:s.file,context:{uncoveredLines:s.uncoveredLines,totalLines:s.totalLines,coveragePercent:((s.totalLines-s.uncoveredLines)/s.totalLines*100).toFixed(1),complexity:s.complexity,riskScore:s.riskScore}});r.length>0&&i.push({priority:"p0",domain:"test-generation",action:"Address High-Risk Coverage Gaps",description:`${r.length} files have high-risk coverage gaps. Prioritize testing for complex, uncovered code.`,estimatedImpact:"high",effort:"high",autoFixable:!0});let n=e.filter(s=>(s.totalLines-s.uncoveredLines)/s.totalLines<.5);n.length>0&&t.push({type:"critical-coverage-gaps",severity:"critical",domain:"coverage-analysis",title:"Critical Coverage Gaps Detected",description:`${n.length} files have less than 50% coverage`,context:{files:n.map(s=>s.file)}})}analyzeCoverageTrends(e,t,i){if(!e.previous)return;let r=e.current.line-e.previous.line,n=e.current.branch!==null&&e.previous.branch!==null?e.current.branch-e.previous.branch:0;r<-2&&(t.push({type:"coverage-regression",severity:r<-5?"high":"medium",domain:"coverage-analysis",title:"Coverage Regression Detected",description:`Line coverage dropped by ${Math.abs(r).toFixed(1)}% since last check`,context:{previous:e.previous.line,current:e.current.line,change:r}}),i.push({priority:"p1",domain:"test-generation",action:"Investigate Coverage Regression",description:"Recent changes have reduced code coverage. Review new code and add missing tests.",estimatedImpact:"high",effort:"medium",autoFixable:!1})),n<-3&&t.push({type:"branch-coverage-regression",severity:"medium",domain:"coverage-analysis",title:"Branch Coverage Regression",description:`Branch coverage dropped by ${Math.abs(n).toFixed(1)}%`,context:{previous:e.previous.branch,current:e.current.branch,change:n}})}calculateHealthScore(e,t){let i=t.filter(l=>l.riskScore>.8).length,r=Math.max(0,10-i*2);if(!e)return r*10;let s=[[e.line,25],[e.branch,25],[e.function,20],[e.statement,20]].filter(l=>l[0]!==null),a=s.reduce((l,[,d])=>l+d,0),o=s.reduce((l,[d,u])=>l+d/100*u,0)*(90/a);return Math.round(o+r)}determineTrend(e){if(!e.previous)return"stable";let t=n=>{let s=[n.line,n.branch,n.function,n.statement].filter(a=>a!==null);return s.reduce((a,o)=>a+o,0)/s.length},i=t(e.current),r=t(e.previous);return i>r+1?"improving":i<r-1?"degrading":"stable"}};var Ze={id:"flaky-detector",name:"Flaky Test Detector",description:"Detects flaky test patterns through statistical analysis of test execution history",intervalMs:900*1e3,priority:"high",targetDomains:["test-execution"],enabled:!0,timeoutMs:18e4,retryCount:2,retryDelayMs:1e4},$=class extends y{constructor(){super(Ze)}async doExecute(e){let t=Date.now();e.logger.info("Starting flaky test detection");let i=[],r=[],n=await this.collectTestHistory(e),s=this.detectFlakyTests(n);this.generateFindings(s,i,r),await e.memory.set("flaky:detected",s),await e.memory.set("flaky:lastAnalysis",new Date().toISOString());let a=this.calculateHealthScore(n.length,s);return e.logger.info("Flaky test detection complete",{healthScore:a,testsAnalyzed:n.length,flakyTestsFound:s.length}),this.createResult(Date.now()-t,{itemsAnalyzed:n.length,issuesFound:s.length,healthScore:a,trend:"stable",domainMetrics:{testsAnalyzed:n.length,flakyTests:s.length,flakinessRate:`${(s.length/n.length*100).toFixed(1)}%`,avgFlakinessScore:s.length>0?(s.reduce((o,l)=>o+l.flakinessScore,0)/s.length).toFixed(1):"0"}},i,r)}async collectTestHistory(e){if(!e.domains.getDomainAPI("test-execution"))throw new Error("Test-execution domain not available - cannot detect flaky tests. Ensure the test-execution domain is properly initialized before running this worker.");let i=await e.memory.search("flaky:history:*");if(i.length===0)throw new Error('No test execution history found in memory - cannot detect flaky tests. Run tests multiple times and ensure history is stored with keys matching "flaky:history:*" before running this worker.');let r=[],n=[];for(let s of i)try{let a=await e.memory.get(s);a&&r.push(a)}catch{n.push(s)}if(r.length===0)throw new Error(`Found ${i.length} test history keys but failed to retrieve any data. Failed keys: ${n.slice(0,5).join(", ")}${n.length>5?"...":""}. Check memory service connectivity and data format.`);return r}detectFlakyTests(e){let t=[];for(let i of e){let r=this.analyzeTestFlakiness(i);r.flakinessScore>20&&t.push(r)}return t.sort((i,r)=>r.flakinessScore-i.flakinessScore)}analyzeTestFlakiness(e){let t=e.executions,r=t.filter(p=>p.passed).length/t.length,n=t.map(p=>p.durationMs),s=n.reduce((p,f)=>p+f,0)/n.length,a=n.reduce((p,f)=>p+Math.pow(f-s,2),0)/n.length,l=Math.sqrt(a)/s,d=t.slice(-5).filter(p=>!p.passed).length,u=this.determinePattern(e,l),m=0;r>0&&r<1&&(m+=(1-r)*50),l>.5&&(m+=Math.min(25,l*10)),m+=d*5;let g=this.suggestFix(u);return{testId:e.testId,testName:e.testName,file:e.file,flakinessScore:Math.min(100,Math.round(m)),pattern:u,passRate:r*100,avgDuration:s,durationVariance:l,recentFailures:d,suggestedFix:g}}determinePattern(e,t){let i=e.executions.filter(n=>!n.passed);if(t>1||i.some(n=>n.error?.includes("Timeout")))return"timing";if(i.some(n=>n.error?.includes("Resource")||n.error?.includes("connection")))return"resource";if(i.some(n=>n.error?.includes("Race")||n.error?.includes("async")))return"intermittent";let r=e.executions.map(n=>n.passed);return this.hasOrderPattern(r)?"order-dependent":"intermittent"}hasOrderPattern(e){let t=e.map((n,s)=>n?-1:s).filter(n=>n>=0);if(t.length<2)return!1;let i=t.every(n=>n%2===0),r=t.every(n=>n%2===1);return i||r}suggestFix(e){switch(e){case"timing":return"Add explicit waits, increase timeouts, or use async utilities like waitFor";case"resource":return"Ensure proper resource cleanup, use test isolation, or implement connection pooling";case"order-dependent":return"Make tests independent, reset state in beforeEach, avoid shared mutable state";case"intermittent":return"Add retry logic, investigate race conditions, or use proper synchronization";default:return"Review test for potential issues with async operations or shared state"}}generateFindings(e,t,i){let r=e.filter(o=>o.flakinessScore>=70),n=e.filter(o=>o.flakinessScore>=50&&o.flakinessScore<70),s=e.filter(o=>o.flakinessScore>=20&&o.flakinessScore<50);for(let o of r)t.push({type:"critical-flaky-test",severity:"critical",domain:"test-execution",title:`Critical Flaky Test: ${o.testName}`,description:`Test has ${o.flakinessScore}% flakiness score with ${o.passRate.toFixed(0)}% pass rate`,resource:o.file,context:{testId:o.testId,pattern:o.pattern,recentFailures:o.recentFailures,suggestedFix:o.suggestedFix}});for(let o of n)t.push({type:"high-flaky-test",severity:"high",domain:"test-execution",title:`Flaky Test: ${o.testName}`,description:`Test has ${o.flakinessScore}% flakiness score (${o.pattern} pattern)`,resource:o.file,context:{testId:o.testId,pattern:o.pattern,suggestedFix:o.suggestedFix}});for(let o of s)t.push({type:"medium-flaky-test",severity:"medium",domain:"test-execution",title:`Potentially Flaky Test: ${o.testName}`,description:`Test shows flakiness indicators (score: ${o.flakinessScore}%)`,resource:o.file,context:{testId:o.testId,pattern:o.pattern}});r.length>0&&i.push({priority:"p0",domain:"test-execution",action:"Fix Critical Flaky Tests",description:`${r.length} tests have critical flakiness. These severely impact CI reliability.`,estimatedImpact:"high",effort:"high",autoFixable:!1});let a=e.filter(o=>o.pattern==="timing");a.length>0&&i.push({priority:"p1",domain:"test-execution",action:"Address Timing-Related Flakiness",description:`${a.length} tests have timing issues. Consider using proper async utilities.`,estimatedImpact:"medium",effort:"medium",autoFixable:!1})}calculateHealthScore(e,t){if(e===0)return 100;let i=t.length/e,r=t.length>0?t.reduce((a,o)=>a+o.flakinessScore,0)/t.length:0,n=100;n-=i*50,n-=r/100*30;let s=t.filter(a=>a.flakinessScore>=70).length;return n-=s*5,Math.max(0,Math.round(n))}};var N=["critical","high","medium","low","informational"],et=/^CVE-\d{4}-\d{4,}$/,ie=c=>typeof c=="number"&&Number.isInteger(c)&&c>=0,R=c=>!!c&&typeof c=="object"&&!Array.isArray(c);function tt(c){if(!R(c))return null;let e={};for(let t of N){if(!ie(c[t]))return null;e[t]=c[t]}return e}function nt(c,e){if(typeof c!="string")return null;let t=Date.parse(c);return!Number.isFinite(t)||t>e+6e4||e-t>6048e5?null:c}function rt(c,e){if(!R(c))return null;let t=c.severity;if(!N.includes(t)||typeof c.title!="string")return null;let i=R(c.location)?c.location:{},r=R(c.remediation)?c.remediation:{},n={severity:t,title:c.title,description:typeof c.description=="string"?c.description:"",category:typeof c.category=="string"?c.category:"other",references:Array.isArray(c.references)?c.references.filter(s=>typeof s=="string"):[]};if(typeof c.cveId=="string"&&et.test(c.cveId)&&(n.cve=c.cveId),e==="dependency"){let s=R(i.dependency)&&typeof i.dependency.name=="string"?i.dependency.name:typeof i.snippet=="string"?/^"([^"]+)":/.exec(i.snippet)?.[1]:void 0;s&&(n.package=s);let a=typeof r.fixExample=="string"?/@([^@\s]+)$/.exec(r.fixExample)?.[1]:void 0;a&&(n.fixedIn=a)}else typeof i.file=="string"&&(n.location=typeof i.line=="number"?`${i.file}:${i.line}`:i.file);return n}function it(c){return Array.isArray(c)?c.filter(R).map(e=>({name:typeof e.name=="string"?e.name:"?",version:typeof e.version=="string"?e.version:"?",reason:typeof e.reason=="string"?e.reason:"unknown"})):[]}function st(c){return c.measured===!0&&c.status==="complete"?{complete:!0}:{complete:!1,status:c.status==="incomplete"||c.status==="failed"?c.status:"unknown",...typeof c.error=="string"&&c.error?{error:c.error}:{},uncheckedPackages:it(c.uncheckedPackages),...ie(c.packagesChecked)?{packagesChecked:c.packagesChecked}:{}}}var Pe={critical:"Critical",high:"High Severity",medium:"Medium Severity",low:"Low Severity",informational:"Informational"};function se(c){return c?c.scan.summary.critical*20+c.scan.summary.high*10:0}function ae(c){return c?{dependencyVulnerabilitiesInCheckedPackages:c.scan.total,dependencyPackagesUnchecked:c.uncheckedPackages.length}:{}}function Ie(c,e){if(!R(c))return null;let t=c.scanType;if(t!=="dependency"&&t!=="sast")return null;let i=nt(c.timestamp,e),r=tt(c.summary);if(typeof c.scanId!="string"||!i||!r)return null;let n=t==="dependency"?c.vulnerabilities:c.criticalVulnerabilities;if(!Array.isArray(n))return null;let s=n.map(d=>rt(d,t));if(s.some(d=>d===null))return null;let a=N.reduce((d,u)=>d+r[u],0),o=t==="sast"&&ie(c.vulnerabilityCount)?c.vulnerabilityCount:a,l={scanId:c.scanId,scannedAt:i,summary:r,vulnerabilities:s,total:o};return t==="sast"?{kind:t,scan:l}:{kind:t,scan:l,completeness:st(c)}}var ot={id:"security-scan",name:"Security Vulnerability Scanner",description:"Scans for security vulnerabilities in dependencies, code patterns, and configurations",intervalMs:1800*1e3,priority:"critical",targetDomains:["security-compliance"],enabled:!0,timeoutMs:3e5,retryCount:3,retryDelayMs:3e4},oe="security-compliance",Ee="security:scan:*",ct="security:lastScan",lt=1e3,L=class extends y{constructor(){super(ot)}async doExecute(e){let t=Date.now();e.logger.info("Starting security vulnerability scan");let i=[],r=[],{scan:n,incompleteDependency:s}=await this.readRecordedScans(e);if(s&&this.reportIncompleteDependencyScan(s,i,r),!n)return s||i.push({type:"security-unmeasured",severity:"info",domain:"security-compliance",title:"Security Scan Unmeasured",description:"No dependency or SAST scan has been recorded in the last 7 days, so no vulnerabilities are reported and nothing was stored. Run security_scan_comprehensive (or `aqe security`) to scan the project."}),e.logger.info("Security scan complete",{measured:!1}),this.createResult(Date.now()-t,{itemsAnalyzed:s?.scan.total??0,issuesFound:i.filter(o=>o.severity!=="info").length,healthScore:Math.max(0,100-se(s)),trend:"stable",domainMetrics:{dependencyScan:"unmeasured",codeScan:"unmeasured",dependencyVulnerabilities:"unmeasured",codeSecurityIssues:"unmeasured",...ae(s)}},i,r);n.dependency&&this.analyzeDependencyVulnerabilities(n.dependency,i,r),n.code&&this.analyzeCodeSecurityIssues(n.code,i,r),await e.memory.set(ct,n),await e.memory.set("security:lastScanTime",n.evaluatedAt);let a=Math.max(0,this.calculateHealthScore(n)-se(s));return e.logger.info("Security scan complete",{measured:!0,healthScore:a,dependencyScanId:n.dependency?.scanId??null,codeScanId:n.code?.scanId??null}),this.createResult(Date.now()-t,{itemsAnalyzed:(n.dependency?.total??0)+(n.code?.total??0),issuesFound:i.length,healthScore:a,trend:"stable",domainMetrics:{dependencyScan:n.dependency?n.dependency.scannedAt:"unmeasured",codeScan:n.code?n.code.scannedAt:"unmeasured",dependencyVulnerabilities:n.dependency?n.dependency.total:"unmeasured",codeSecurityIssues:n.code?n.code.total:"unmeasured",...ae(s)}},i,r)}async readRecordedScans(e){let t=await e.memory.search(Ee,lt,{namespace:oe}),i=Date.now(),r=null,n=null,s=(d,u)=>!u||Date.parse(d.scannedAt)>Date.parse(u.scannedAt);for(let d of t){let u=x(d,oe,Ee),m=Ie(await e.memory.get(u,{namespace:oe}),i);m&&(m.kind==="dependency"&&s(m.scan,r?.scan??null)&&(r=m),m.kind==="sast"&&s(m.scan,n)&&(n=m.scan))}let a=r?.completeness,o=r&&a?.complete?r.scan:null,l=r&&a&&!a.complete?{scan:r.scan,status:a.status,...a.error?{error:a.error}:{},uncheckedPackages:a.uncheckedPackages,...a.packagesChecked!==void 0?{packagesChecked:a.packagesChecked}:{}}:null;return!o&&!n?{scan:null,incompleteDependency:l}:{incompleteDependency:l,scan:{measured:!0,schemaVersion:1,evaluatedAt:new Date().toISOString(),dependency:o?{...o,source:"osv"}:null,code:n?{...n,source:"sast"}:null}}}reportIncompleteDependencyScan(e,t,i){let{scan:r,status:n,error:s,uncheckedPackages:a,packagesChecked:o}=e,l=a.map(g=>`${g.name}@${g.version} (${g.reason})`),d=r.summary,u=r.total>0?` OSV reported ${r.total} advisory finding(s) in the ${o??""}${o===void 0?"":" "}checked package(s) (${d.critical} critical, ${d.high} high, ${d.medium} medium, ${d.low} low); they are listed as separate findings.`:"",m=n==="unknown"?"was recorded before scans stated whether every package was checked, so a failed lookup cannot be told apart from a clean one":`is ${n}${s?` (${s})`:""}`;t.push({type:"dependency-scan-incomplete",severity:"info",domain:"security-compliance",title:"Dependency Scan Unmeasured",description:`The latest dependency scan (${r.scannedAt}) ${m}; its result is not a vulnerability count.`+(l.length>0?` Unchecked packages: ${l.join(", ")}.`:"")+u+" Re-run the dependency scan.",context:{scanId:r.scanId,status:n,...s?{error:s}:{},uncheckedPackages:a,...o!==void 0?{packagesChecked:o}:{},advisoriesInCheckedPackages:r.total}}),this.analyzeDependencyVulnerabilities(r,t,i,!0)}analyzeDependencyVulnerabilities(e,t,i,r=!1){let n=e.vulnerabilities.filter(o=>o.severity==="critical"),s=e.vulnerabilities.filter(o=>o.severity==="high"),a=r?N.flatMap(o=>e.vulnerabilities.filter(l=>l.severity===o)):[...n,...s];for(let o of a){let l=o.package??o.title;t.push({type:`${o.severity}-vulnerability`,severity:o.severity==="informational"?"info":o.severity,domain:"security-compliance",title:`${Pe[o.severity]} Vulnerability in ${l}`,description:o.description?`${o.title}: ${o.description}`:o.title,resource:l,context:{advisorySource:"osv",scanId:e.scanId,scannedAt:e.scannedAt,...o.cve?{cve:o.cve}:{},...o.fixedIn?{fixedIn:o.fixedIn}:{},references:o.references,...r?{partialScan:!0}:{}}})}n.length>0&&i.push({priority:"p0",domain:"security-compliance",action:"Update Critical Vulnerabilities Immediately",description:`The dependency scan of ${e.scannedAt} reported ${n.length} critical vulnerabilities. Update to patched versions.`,estimatedImpact:"high",effort:"low",autoFixable:!0}),s.length>0&&i.push({priority:"p1",domain:"security-compliance",action:"Address High Severity Vulnerabilities",description:`The dependency scan of ${e.scannedAt} reported ${s.length} high severity vulnerabilities. Plan updates within current sprint.`,estimatedImpact:"high",effort:"low",autoFixable:!0})}analyzeCodeSecurityIssues(e,t,i){for(let s of e.vulnerabilities)t.push({type:`code-security-${s.category}`,severity:s.severity==="informational"?"info":s.severity,domain:"security-compliance",title:`Security Issue: ${s.title}`,description:s.description||s.title,...s.location?{resource:s.location}:{},context:{category:s.category,scanId:e.scanId,scannedAt:e.scannedAt,...s.cve?{cve:s.cve}:{}}});let r=e.vulnerabilities.filter(s=>s.category==="injection");r.length>0&&i.push({priority:"p0",domain:"security-compliance",action:"Fix Injection Vulnerabilities",description:`The SAST scan of ${e.scannedAt} reported ${r.length} potential injection vulnerabilities. Use parameterized queries and avoid eval().`,estimatedImpact:"high",effort:"medium",autoFixable:!1});let n=e.vulnerabilities.filter(s=>s.category==="sensitive-data");n.length>0&&i.push({priority:"p1",domain:"security-compliance",action:"Review Sensitive Data Handling",description:`The SAST scan of ${e.scannedAt} reported ${n.length} sensitive-data issues. Ensure secure algorithms and key management.`,estimatedImpact:"high",effort:"high",autoFixable:!1})}calculateHealthScore(e){let t=100;return e.dependency&&(t-=e.dependency.summary.critical*20,t-=e.dependency.summary.high*10),e.code&&(t-=e.code.summary.critical*15,t-=e.code.summary.high*8),Math.max(0,Math.round(t))}};var dt={id:"quality-gate",name:"Quality Gate Evaluator",description:"Continuously evaluates quality gates and release readiness across all quality dimensions",intervalMs:300*1e3,priority:"critical",targetDomains:["quality-assessment"],enabled:!0,timeoutMs:12e4,retryCount:2,retryDelayMs:5e3},xe="quality-gate:current",We="quality-gate:history",Fe=1,ut=100;function mt(c){if(!c||typeof c!="object")return null;let e=c;return e.measured!==!0||e.schemaVersion!==Fe||typeof e.passed!="boolean"||!Array.isArray(e.checks)?null:e}var pt=c=>c.direction==="min"?">=":"<=",_=class extends y{constructor(){super(dt)}async doExecute(e){let t=Date.now();e.logger.info("Starting quality gate evaluation");let i=[],r=[],{values:n,problems:s}=await be(e.memory),a=Object.fromEntries(Z.map(p=>[p,n[p]??"unmeasured"]));if(s.length>0){let p=s.map(f=>f.metric);i.push({type:"quality-gate-insufficient-evidence",severity:"info",domain:"quality-assessment",title:"Quality Gate Not Evaluated: Insufficient Evidence",description:`${p.length} of ${Z.length} gate metrics have no usable measured evidence (${p.join(", ")}), so no verdict was reached and nothing was stored.`,context:{status:Q,unmeasured:p,problems:s}});for(let f of ke(p))r.push({priority:"p3",domain:"quality-assessment",action:"Record Measured Quality Evidence",description:f,estimatedImpact:"medium",effort:"low",autoFixable:!1});return e.logger.info("Quality gate evaluation complete",{status:Q,unmeasured:p}),this.createResult(Date.now()-t,{itemsAnalyzed:0,issuesFound:0,healthScore:100,trend:"stable",domainMetrics:{gateStatus:Q,gatePassed:"unmeasured",releaseReady:"unmeasured",unmeasuredMetrics:p.length,...a}},i,r)}let o=De(n),l=o.checks.filter(p=>!p.passed),d={measured:!0,schemaVersion:Fe,evaluatedAt:new Date().toISOString(),passed:o.passed,passedChecks:o.checks.length-l.length,failedChecks:l.length,checks:o.checks};this.analyzeGateResults(d,i,r),await this.compareToPrevious(e,d,i),await e.memory.set(xe,d),await e.memory.set("quality-gate:lastCheck",d.evaluatedAt);let u=await e.memory.get(We),m=Array.isArray(u)?u:[];for(m.push(d);m.length>ut;)m.shift();await e.memory.set(We,m);let g=this.calculateHealthScore(d);return e.logger.info("Quality gate evaluation complete",{healthScore:g,passed:d.passed,failedChecks:d.failedChecks}),this.createResult(Date.now()-t,{itemsAnalyzed:d.checks.length,issuesFound:d.failedChecks,healthScore:g,trend:"stable",domainMetrics:{gateStatus:"evaluated",gatePassed:d.passed?"YES":"NO",releaseReady:d.passed?"YES":"NO",passedChecks:d.passedChecks,failedChecks:d.failedChecks,...a}},i,r)}analyzeGateResults(e,t,i){let r=e.checks.filter(n=>!n.passed);for(let n of r)t.push({type:"quality-gate-failure",severity:n.severity,domain:"quality-assessment",title:`Quality Gate Failed: ${n.name}`,description:`Measured ${n.name} is ${n.value}, threshold is ${pt(n)} ${n.threshold}`,context:{metric:n.name,value:n.value,threshold:n.threshold,direction:n.direction}});r.length>0&&(t.push({type:"release-blocked",severity:r.some(n=>n.severity==="critical")?"critical":"high",domain:"quality-assessment",title:"Release Blocked",description:`${r.length} measured quality checks fail the gate`,context:{failingMetrics:r.map(n=>n.name)}}),i.push({priority:"p0",domain:"quality-assessment",action:"Resolve Failing Quality Checks",description:`Fix ${r.map(n=>n.name).join(", ")} before proceeding with release.`,estimatedImpact:"high",effort:"medium",autoFixable:!1}))}async compareToPrevious(e,t,i){let r=mt(await e.memory.get(xe));r&&(r.passed&&!t.passed&&i.push({type:"quality-gate-regression",severity:"high",domain:"quality-assessment",title:"Quality Gate Regression",description:"The measured quality gate was passing previously but is now failing",context:{previousEvaluatedAt:r.evaluatedAt,currentFailedChecks:t.failedChecks}}),!r.passed&&t.passed&&i.push({type:"quality-gate-improvement",severity:"info",domain:"quality-assessment",title:"Quality Gate Now Passing",description:"The measured quality gate is now passing after previous failures",context:{previousEvaluatedAt:r.evaluatedAt}}))}calculateHealthScore(e){if(e.checks.length===0)return 100;let t=e.passedChecks/e.checks.length*90;return e.passed&&(t+=10),Math.max(0,Math.min(100,Math.round(t)))}};Ye();J();Ke();var gt=30;function $e(c,e){return c.prepare(`PRAGMA table_info(${e})`).all().map(t=>t.name)}function Ne(c,e={}){let t=e.retentionDays??gt;if(!c.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='dream_insights'").get())return{pruned:0,archived:0,skippedNullId:0};let{cutoff:r}=c.prepare("SELECT datetime('now', ?) AS cutoff").get(`-${t} days`),n="d.applied = 0 AND d.created_at < ? AND d.id IS NOT NULL",s=c.prepare("SELECT COUNT(*) AS n FROM dream_insights d WHERE d.applied = 0 AND d.created_at < ? AND d.id IS NULL").get(r).n;return c.transaction(()=>{let o=c.prepare(`SELECT COUNT(*) AS n FROM dream_insights d WHERE ${n}`).get(r).n;if(o===0)return{pruned:0,archived:0,skippedNullId:s};c.exec(he);let l=new Set($e(c,w));if(!l.has("archive_id"))throw new Error(`${w} has no archive_id column; nothing deleted`);let d=$e(c,"dream_insights").filter(k=>k!=="archived_at"&&k!=="archive_id"&&l.has(k)),u=d.map(k=>`"${k}"`).join(", "),{mark:m}=c.prepare(`SELECT COALESCE(MAX(archive_id), 0) AS mark FROM ${w}`).get(),g=c.prepare(`INSERT INTO ${w} (${u}, archived_at)
3
3
  SELECT ${d.map(k=>`d."${k}"`).join(", ")}, datetime('now')
4
4
  FROM dream_insights d WHERE ${n}`).run(r).changes,p=c.prepare(`SELECT COUNT(*) AS n FROM dream_insights d
5
5
  WHERE ${n}
@@ -9,10 +9,10 @@ import{b as Me,c as Ae,e as Te}from"./chunk-2G7TVT6W.js";import{a as y,b as ee}f
9
9
  AND id IN (SELECT id FROM ${w} WHERE archive_id > ?)`).run(r,m).changes,h=c.prepare(`SELECT COUNT(*) AS n FROM dream_insights d WHERE ${n}`).get(r).n;if(f!==o||h!==0)throw new Error(`dream_insights delete check failed: deleted ${f} of ${o}, ${h} left; rolled back`);return{pruned:f,archived:g,skippedNullId:s}}).immediate()}var Le={id:"learning-consolidation",name:"Learning Consolidation",description:"Consolidates learning patterns across domains and optimizes strategies",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:3e5,retryCount:2,retryDelayMs:3e4},ht="learning:consolidation-cursor:",z=1,H=class extends y{lifecycleManager=null;lastRunTimestamp=0;dreamInsightsPruneNotBefore=Date.now()+Le.intervalMs;retentionWarningLogged=!1;nullIdRowsReported=0;constructor(){super(Le)}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=I();await e.initialize();let t=e.getDatabase();return this.lifecycleManager=Re(t,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch(e){return console.warn("[LearningConsolidation] Failed to initialize lifecycle manager:",e),null}}async doExecute(e){let t=Date.now();e.logger.info("Starting learning consolidation (Phase 7: Continuous Learning Loop)");let i=[],r=[],n={success:!1};try{let s=0,a=0,o=0,l=0,d=0,u=0,m=0,g=0,p=await this.getLifecycleManager();if(p){let b=await this.runContinuousLearningLoop(e,p,i,r);s=b.experiencesProcessed,a=b.patternCandidatesFound,o=b.patternsPromoted,l=b.patternsDeprecated,d=b.confidenceDecayApplied,u=b.patternsMined,m=b.domainsMined,g=b.dreamInsightsPruned}let f=await this.collectPatterns(e),h=await this.consolidatePatterns(e,f);h.experiencesProcessed=s,h.patternCandidatesFound=a,h.patternsPromoted=o,h.patternsDeprecated=l,h.confidenceDecayApplied=d,h.patternsMined=u,h.domainsMined=m,h.dreamInsightsPruned=g,this.identifyCrossDomainPatterns(f,i,r),this.pruneIneffectivePatterns(f,i,r),this.generateOptimizations(f,i,r);let k=await this.runDreamCycle(e,f,i,r);h.dreamInsights=k.insights,h.dreamPatternsCreated=k.patternsCreated,await e.memory.set("learning:lastConsolidation",h),await e.memory.set("learning:consolidatedPatterns",f),n={success:!0},this.lastRunTimestamp=Date.now();let v=this.calculateHealthScore(h,f);return e.logger.info("Learning consolidation complete",{healthScore:v,patternsAnalyzed:h.patternsAnalyzed,newInsights:h.newInsights,experiencesProcessed:s,patternsPromoted:o,patternsDeprecated:l}),this.createResult(Date.now()-t,{itemsAnalyzed:h.patternsAnalyzed,issuesFound:h.patternsPruned+h.patternsDeprecated,healthScore:v,trend:this.determineTrend(h),domainMetrics:{patternsAnalyzed:h.patternsAnalyzed,patternsPruned:h.patternsPruned,patternsConsolidated:h.patternsConsolidated,newInsights:h.newInsights,crossDomainPatterns:h.crossDomainPatterns,dreamInsights:h.dreamInsights,dreamPatternsCreated:h.dreamPatternsCreated,experiencesProcessed:h.experiencesProcessed,patternCandidatesFound:h.patternCandidatesFound,patternsPromoted:h.patternsPromoted,patternsDeprecated:h.patternsDeprecated,confidenceDecayApplied:h.confidenceDecayApplied,patternsMined:h.patternsMined,domainsMined:h.domainsMined,dreamInsightsPruned:h.dreamInsightsPruned}},i,r)}catch(s){throw n={success:!1,error:s instanceof Error?s.message:String(s)},s}finally{try{await fe(e.memory,"learningWorker",n)}catch(a){e.logger.warn("recordLoopHealth failed (non-fatal)",{error:a instanceof Error?a.message:String(a)})}let s=ye(j());try{await s.initialize(),await s.saveSnapshot()}catch(a){e.logger.warn("learning_daily_snapshots saveSnapshot failed (non-fatal)",{error:a instanceof Error?a.message:String(a)})}finally{s.close()}}}pruneDreamInsights(e){let t=Ae();t.warning&&!this.retentionWarningLogged&&(this.retentionWarningLogged=!0,process.stderr.write(`[AQE] WARN ${t.warning}
10
10
  `));let i=t.retentionDays;if(i===null||Date.now()<this.dreamInsightsPruneNotBefore)return 0;let r=I().getDatabase(),{pruned:n,archived:s,skippedNullId:a}=Ne(r,{retentionDays:i});return a!==this.nullIdRowsReported&&(this.nullIdRowsReported=a,a>0&&process.stderr.write(`[AQE] WARN dream_insights retention: ${a} stale insight(s) have no id and were left in place (they cannot be archived); the other stale insights were archived as usual
11
11
  `)),n>0&&(process.stderr.write(`[AQE] dream_insights retention: moved ${n} unapplied insight(s) older than ${i} days to ${w} (set AQE_DREAM_INSIGHTS_RETENTION_DAYS=off to keep them in place)
12
- `),e.push({type:"dream-insights-pruned",severity:"info",domain:"learning-optimization",title:"Stale Dream Insights Archived",description:`${n} unapplied dream insights older than ${i} days moved to ${w}`,context:{pruned:n,archived:s,retentionDays:i}})),n}async runContinuousLearningLoop(e,t,i,r){e.logger.info("Running continuous learning loop (Phase 7)");let n=0,s=0,a=0,o=0,l=0,d=0,u=0,m=0;try{let g=t.getRecentExperiences({minReward:.7,limit:100,sinceDays:7});if(n=g.length,g.length>0){e.logger.debug("Processing recent experiences",{count:g.length});let v=t.findPatternCandidates(g);if(s=v.length,v.length>0){let b=await this.createPatternsFromCandidates(v);i.push({type:"pattern-extraction",severity:"info",domain:"learning-optimization",title:"New Patterns Extracted from Experiences",description:`${b} new patterns extracted from ${n} high-reward experiences`,context:{candidatesFound:s,patternsCreated:b,topCandidate:v[0]?.name}})}}let p=t.promoteEligiblePatterns();a=p.promoted,a>0&&i.push({type:"pattern-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted to Long-Term",description:`${a} patterns promoted after meeting quality thresholds`,context:{checked:p.checked,promoted:a}});let f=t.deprecateStalePatterns();o=f.deprecated,o>0&&(i.push({type:"pattern-deprecation",severity:"low",domain:"learning-optimization",title:"Underperforming Patterns Deprecated",description:`${o} patterns deprecated due to failures, staleness, or low confidence`,context:{checked:f.checked,deprecated:o}}),r.push({priority:"p3",domain:"learning-optimization",action:"Review Deprecated Patterns",description:`${o} patterns were deprecated. Review for potential recovery or permanent removal.`,estimatedImpact:"low",effort:"low",autoFixable:!1}));try{let b=I().getDatabase(),ge=new Ce;await ge.initialize(b);let C=await ge.consolidateAll();(C.merged>0||C.archived>0)&&i.push({type:"experience-consolidation",severity:"info",domain:"learning-optimization",title:"Experiences Consolidated",description:`${C.merged} merged, ${C.archived} archived across ${C.domainsProcessed.length} domains`,context:{merged:C.merged,archived:C.archived,activeRemaining:C.activeRemaining,domains:C.domainsProcessed}})}catch(v){e.logger.warn("Experience consolidation failed",{error:D(v)})}let h=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/(1e3*60*60*24):1;h>=.5&&(l=t.applyConfidenceDecay(Math.min(h,7)).decayed);let k=t.getStats();this.addLifecycleStatsFinding(k,i,r);try{let v=await this.mineExperiencesPerDomain(e,i);d=v.patternsMined,u=v.domainsMined}catch(v){e.logger.warn("Pattern mining sweep failed",{error:D(v)})}try{m=this.pruneDreamInsights(i)}catch(v){e.logger.warn("Dream insights pruning failed",{error:D(v)})}e.logger.info("Continuous learning loop complete",{experiencesProcessed:n,patternCandidatesFound:s,patternsPromoted:a,patternsDeprecated:o,confidenceDecayApplied:l,patternsMined:d,domainsMined:u,dreamInsightsPruned:m})}catch(g){e.logger.warn("Continuous learning loop partially failed",{error:D(g)})}return{experiencesProcessed:n,patternCandidatesFound:s,patternsPromoted:a,patternsDeprecated:o,confidenceDecayApplied:l,patternsMined:d,domainsMined:u,dreamInsightsPruned:m}}async mineExperiencesPerDomain(e,t){let i=e.domains.getDomainAPI("learning-optimization");if(!i||typeof i.getLearningService!="function")return e.logger.debug("mineExperiencesPerDomain: learning-optimization API unavailable"),{patternsMined:0,domainsMined:0};let r=i.getLearningService();if(!r)return e.logger.debug("mineExperiencesPerDomain: learning service not initialized"),{patternsMined:0,domainsMined:0};let n=new Date,s=0,a=0;for(let o of M){let l=`${ht}${o}`,d;try{let u=await e.memory.get(l);if(u){let m=new Date(u);if(!isNaN(m.getTime())&&m<n){let g=new Date(n.getTime()-z*24*60*60*1e3);d=m>g?m:g}else d=new Date(n.getTime()-z*24*60*60*1e3)}else d=new Date(n.getTime()-z*24*60*60*1e3)}catch{d=new Date(n.getTime()-z*24*60*60*1e3)}try{let u=Se.create(d,n),m=await r.mineExperiences(o,u);if(!m.success){e.logger.debug(`mineExperiences failed for ${o}`,{error:D(m.error)});continue}let{experienceCount:g,patterns:p}=m.value;g>0&&(s+=p.length,a++,await e.memory.set(l,n.toISOString()))}catch(u){e.logger.debug(`mineExperiences threw for ${o}`,{error:D(u)})}}return s>0&&t.push({type:"pattern-mining",severity:"info",domain:"learning-optimization",title:"Patterns Mined from Experience Replay",description:`${s} patterns mined into learning:pattern:* kv across ${a} domain(s) since their last consolidation tick`,context:{patternsMined:s,domainsMined:a,lookbackDays:z}}),{patternsMined:s,domainsMined:a}}async createPatternsFromCandidates(e){let t=0;try{let r=I().getDatabase();for(let n of e)try{let{v4:s}=await import("./dist-node-FV3KWXQ6.js"),a=s(),o=`Auto-extracted pattern from ${n.sourceExperiences} experiences. Avg reward: ${n.avgReward.toFixed(3)}`;r.prepare(`
12
+ `),e.push({type:"dream-insights-pruned",severity:"info",domain:"learning-optimization",title:"Stale Dream Insights Archived",description:`${n} unapplied dream insights older than ${i} days moved to ${w}`,context:{pruned:n,archived:s,retentionDays:i}})),n}async runContinuousLearningLoop(e,t,i,r){e.logger.info("Running continuous learning loop (Phase 7)");let n=0,s=0,a=0,o=0,l=0,d=0,u=0,m=0;try{let g=t.getRecentExperiences({minReward:.7,limit:100,sinceDays:7});if(n=g.length,g.length>0){e.logger.debug("Processing recent experiences",{count:g.length});let v=t.findPatternCandidates(g);if(s=v.length,v.length>0){let b=await this.createPatternsFromCandidates(v);i.push({type:"pattern-extraction",severity:"info",domain:"learning-optimization",title:"New Patterns Extracted from Experiences",description:`${b} new patterns extracted from ${n} high-reward experiences`,context:{candidatesFound:s,patternsCreated:b,topCandidate:v[0]?.name}})}}let p=t.promoteEligiblePatterns();a=p.promoted,a>0&&i.push({type:"pattern-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted to Long-Term",description:`${a} patterns promoted after meeting quality thresholds`,context:{checked:p.checked,promoted:a}});let f=t.deprecateStalePatterns();o=f.deprecated,o>0&&(i.push({type:"pattern-deprecation",severity:"low",domain:"learning-optimization",title:"Underperforming Patterns Deprecated",description:`${o} patterns deprecated due to failures, staleness, or low confidence`,context:{checked:f.checked,deprecated:o}}),r.push({priority:"p3",domain:"learning-optimization",action:"Review Deprecated Patterns",description:`${o} patterns were deprecated. Review for potential recovery or permanent removal.`,estimatedImpact:"low",effort:"low",autoFixable:!1}));try{let b=I().getDatabase(),ge=new Ce;await ge.initialize(b);let C=await ge.consolidateAll();(C.merged>0||C.archived>0)&&i.push({type:"experience-consolidation",severity:"info",domain:"learning-optimization",title:"Experiences Consolidated",description:`${C.merged} merged, ${C.archived} archived across ${C.domainsProcessed.length} domains`,context:{merged:C.merged,archived:C.archived,activeRemaining:C.activeRemaining,domains:C.domainsProcessed}})}catch(v){e.logger.warn("Experience consolidation failed",{error:D(v)})}let h=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/(1e3*60*60*24):1;h>=.5&&(l=t.applyConfidenceDecay(Math.min(h,7)).decayed);let k=t.getStats();this.addLifecycleStatsFinding(k,i,r);try{let v=await this.mineExperiencesPerDomain(e,i);d=v.patternsMined,u=v.domainsMined}catch(v){e.logger.warn("Pattern mining sweep failed",{error:D(v)})}try{m=this.pruneDreamInsights(i)}catch(v){e.logger.warn("Dream insights pruning failed",{error:D(v)})}e.logger.info("Continuous learning loop complete",{experiencesProcessed:n,patternCandidatesFound:s,patternsPromoted:a,patternsDeprecated:o,confidenceDecayApplied:l,patternsMined:d,domainsMined:u,dreamInsightsPruned:m})}catch(g){e.logger.warn("Continuous learning loop partially failed",{error:D(g)})}return{experiencesProcessed:n,patternCandidatesFound:s,patternsPromoted:a,patternsDeprecated:o,confidenceDecayApplied:l,patternsMined:d,domainsMined:u,dreamInsightsPruned:m}}async mineExperiencesPerDomain(e,t){let i=e.domains.getDomainAPI("learning-optimization");if(!i||typeof i.getLearningService!="function")return e.logger.debug("mineExperiencesPerDomain: learning-optimization API unavailable"),{patternsMined:0,domainsMined:0};let r=i.getLearningService();if(!r)return e.logger.debug("mineExperiencesPerDomain: learning service not initialized"),{patternsMined:0,domainsMined:0};let n=new Date,s=0,a=0;for(let o of M){let l=`${ht}${o}`,d;try{let u=await e.memory.get(l);if(u){let m=new Date(u);if(!isNaN(m.getTime())&&m<n){let g=new Date(n.getTime()-z*24*60*60*1e3);d=m>g?m:g}else d=new Date(n.getTime()-z*24*60*60*1e3)}else d=new Date(n.getTime()-z*24*60*60*1e3)}catch{d=new Date(n.getTime()-z*24*60*60*1e3)}try{let u=Se.create(d,n),m=await r.mineExperiences(o,u);if(!m.success){e.logger.debug(`mineExperiences failed for ${o}`,{error:D(m.error)});continue}let{experienceCount:g,patterns:p}=m.value;g>0&&(s+=p.length,a++,await e.memory.set(l,n.toISOString()))}catch(u){e.logger.debug(`mineExperiences threw for ${o}`,{error:D(u)})}}return s>0&&t.push({type:"pattern-mining",severity:"info",domain:"learning-optimization",title:"Patterns Mined from Experience Replay",description:`${s} patterns mined into learning:pattern:* kv across ${a} domain(s) since their last consolidation tick`,context:{patternsMined:s,domainsMined:a,lookbackDays:z}}),{patternsMined:s,domainsMined:a}}async createPatternsFromCandidates(e){let t=0;try{let r=I().getDatabase();for(let n of e)try{let{v4:s}=await import("./dist-node-EN3PYEGW.js"),a=s(),o=`Auto-extracted pattern from ${n.sourceExperiences} experiences. Avg reward: ${n.avgReward.toFixed(3)}`;r.prepare(`
13
13
  INSERT INTO qe_patterns (
14
14
  id, pattern_type, qe_domain, domain, name, description,
15
15
  confidence, usage_count, success_rate, quality_score, tier,
16
16
  template_json, context_json, created_at, last_used_at, successful_uses
17
17
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'), datetime('now'), ?)
18
- `).run(a,n.patternType,n.domain,n.domain,n.name,o,n.confidence,n.sourceExperiences,n.successRate,n.confidence*.3+Math.min(n.sourceExperiences,100)/100*.2+n.successRate*.5,"short-term",JSON.stringify({type:"workflow",content:n.templateContent,variables:[]}),JSON.stringify({tags:n.actions,sourceType:"experience-extraction",extractedAt:new Date().toISOString()}),Math.round(n.sourceExperiences*n.successRate));let{ensurePatternEmbedding:l}=await import("./embed-and-insert-pattern-GPRR3ZGD.js");await l(r,a,n.name,o,n.actions),t++}catch(s){console.debug("[LearningConsolidation] Failed to create pattern:",s)}}catch(i){console.warn("[LearningConsolidation] Pattern creation batch failed:",i)}return t}addLifecycleStatsFinding(e,t,i){t.push({type:"lifecycle-stats",severity:"info",domain:"learning-optimization",title:"Pattern Lifecycle Statistics",description:`Active: ${e.activePatterns}, Promoted: ${e.promotedPatterns}, Deprecated: ${e.deprecatedPatterns}`,context:{total:e.totalPatterns,active:e.activePatterns,shortTerm:e.shortTermPatterns,longTerm:e.longTermPatterns,deprecated:e.deprecatedPatterns,avgConfidence:e.avgConfidence.toFixed(3),avgSuccessRate:e.avgSuccessRate.toFixed(3),nearDeprecation:e.patternsNearDeprecation}}),e.patternsNearDeprecation>0&&i.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${e.patternsNearDeprecation} patterns are near deprecation threshold. Consider improving their usage or archiving them.`,estimatedImpact:"medium",effort:"low",autoFixable:!1}),e.avgSuccessRate<.6&&i.push({priority:"p2",domain:"learning-optimization",action:"Improve Pattern Quality",description:`Average success rate (${(e.avgSuccessRate*100).toFixed(1)}%) is below target. Focus on quality over quantity.`,estimatedImpact:"high",effort:"medium",autoFixable:!1})}determineTrend(e){let t=e.patternsPromoted/Math.max(1,e.patternsAnalyzed),i=e.patternsDeprecated/Math.max(1,e.patternsAnalyzed),r=e.patternCandidatesFound/Math.max(1,e.experiencesProcessed);return t>.1&&r>.2?"improving":i>.2||e.patternsPruned>e.newInsights?"degrading":"stable"}async collectPatterns(e){let t=[],i=[];for(let r of M)try{let n=await this.getDomainPatterns(e,r);t.push(...n)}catch(n){let s=D(n);i.push(`${r}: ${s}`),e.logger.warn(`Failed to collect patterns from ${r}`,{error:n})}if(t.length===0&&i.length>0)throw new Error(`Failed to collect any learning patterns. Errors from domains: ${i.join("; ")}. Ensure at least one domain is available and has pattern data.`);if(t.length===0)throw new Error("No learning patterns to consolidate yet. Patterns accumulate as the captured-experience bridge feeds hook activity into the learning-optimization domain \u2014 first runs may be empty until a kernel-owning process (CLI/MCP) has been alive long enough to drain the captured_experiences table.");return t}async getDomainPatterns(e,t){let i=e.domains.getDomainAPI("learning-optimization");if(!i)throw new Error(`Learning-optimization domain not available for ${t} - cannot retrieve patterns. Ensure the learning-optimization domain is properly initialized.`);let r=await i.getPatternStats(t);if(!r.success)throw new Error(`Failed to get pattern stats for ${t}: Unknown error. Check domain service health and data availability.`);return!r.value||!r.value.topPatterns||r.value.topPatterns.length===0?(e.logger.debug(`No patterns found for domain ${t}`),[]):r.value.topPatterns.map(s=>({id:s.id,domain:s.domain,type:s.type,pattern:s.name,confidence:s.confidence,occurrences:s.usageCount,lastSeen:new Date(s.lastUsedAt),effectiveness:s.successRate}))}async consolidatePatterns(e,t){let i=0,r=0,n=0,s=new Map;for(let d of t){let u=`${d.type}:${d.pattern}`,m=s.get(u)||[];m.push(d),s.set(u,m)}for(let[,d]of Array.from(s.entries()))d.length>1&&(r+=d.length-1);i=t.filter(d=>d.confidence<.5).length;let o=t.filter(d=>{let u=(Date.now()-d.lastSeen.getTime())/864e5;return d.effectiveness>.8&&u<7});n=o.length;let l=this.findCrossDomainPatterns(t);return await e.memory.set("learning:insights",{recentHighPerformers:o,crossDomainPatterns:l,timestamp:new Date().toISOString()}),{patternsAnalyzed:t.length,patternsPruned:i,patternsConsolidated:r,newInsights:n,strategyUpdates:0,crossDomainPatterns:l.length,dreamInsights:0,dreamPatternsCreated:0,experiencesProcessed:0,patternCandidatesFound:0,patternsPromoted:0,patternsDeprecated:0,confidenceDecayApplied:0,experiencesMerged:0,experiencesArchived:0,patternsMined:0,domainsMined:0,dreamInsightsPruned:0}}async runDreamCycle(e,t,i,r){if(t.length<10)return e.logger.debug("Skipping dream cycle - insufficient patterns",{patternCount:t.length,required:10}),{insights:0,patternsCreated:0};let n=null;try{n=new ve,await n.initialize();let s=t.map(l=>({id:l.id,name:l.pattern,description:`${l.type} pattern from ${l.domain} (effectiveness: ${l.effectiveness})`,domain:l.domain,patternType:l.type,confidence:l.confidence,successRate:l.effectiveness}));await n.loadPatternsAsConcepts(s),e.logger.debug("Starting dream cycle",{patternCount:t.length});let a=await n.dream(),o=a.insights.filter(l=>l.actionable&&l.confidenceScore>.7);return o.length>0&&(i.push({type:"dream-insights",severity:"info",domain:"learning-optimization",title:"Dream Cycle Insights Generated",description:`${o.length} actionable insights discovered through pattern association`,context:{totalInsights:a.insights.length,actionableInsights:o.length,topInsight:o[0]?.description,activationIterations:a.activationStats.totalIterations}}),r.push({priority:"p2",domain:"learning-optimization",action:"Apply Dream Insights",description:`${o.length} insights from dream cycle can improve pattern effectiveness`,estimatedImpact:"medium",effort:"low",autoFixable:!0})),await e.memory.set("learning:dreamInsights",{cycleId:a.cycle.id,insights:o,timestamp:new Date().toISOString()}),e.logger.info("Dream cycle completed",{insights:a.insights.length,actionable:o.length,duration:a.cycle.durationMs}),{insights:a.insights.length,patternsCreated:a.patternsCreated}}catch(s){return e.logger.warn("Dream cycle failed",{error:D(s)}),{insights:0,patternsCreated:0}}finally{n&&await n.close()}}findCrossDomainPatterns(e){let t=new Map;for(let r of e){let n=t.get(r.type)||[];n.push(r),t.set(r.type,n)}let i=[];for(let[r,n]of Array.from(t.entries())){let s=Array.from(new Set(n.map(a=>a.domain)));s.length>=3&&i.push({pattern:r,domains:s,avgEffectiveness:n.reduce((a,o)=>a+o.effectiveness,0)/n.length})}return i}identifyCrossDomainPatterns(e,t,i){let r=this.findCrossDomainPatterns(e);r.length>0&&(t.push({type:"cross-domain-patterns",severity:"info",domain:"learning-optimization",title:"Cross-Domain Patterns Identified",description:`${r.length} patterns are effective across multiple domains`,context:{patterns:r.map(n=>({type:n.pattern,domains:n.domains.length,effectiveness:n.avgEffectiveness.toFixed(2)}))}}),i.push({priority:"p2",domain:"learning-optimization",action:"Leverage Cross-Domain Patterns",description:"Apply successful cross-domain patterns to domains where they are not yet used.",estimatedImpact:"medium",effort:"low",autoFixable:!0}))}pruneIneffectivePatterns(e,t,i){let r=e.filter(s=>s.effectiveness<.3&&s.occurrences>10),n=e.filter(s=>(Date.now()-s.lastSeen.getTime())/864e5>30);r.length>0&&(t.push({type:"ineffective-patterns",severity:"low",domain:"learning-optimization",title:"Ineffective Patterns Detected",description:`${r.length} patterns have low effectiveness despite many occurrences`,context:{count:r.length,domains:Array.from(new Set(r.map(s=>s.domain)))}}),i.push({priority:"p3",domain:"learning-optimization",action:"Review Ineffective Patterns",description:"Consider removing or refining patterns that consistently underperform.",estimatedImpact:"low",effort:"low",autoFixable:!0})),n.length>0&&t.push({type:"stale-patterns",severity:"info",domain:"learning-optimization",title:"Stale Patterns Identified",description:`${n.length} patterns have not been seen in over 30 days`,context:{count:n.length}})}generateOptimizations(e,t,i){let r=new Map;for(let a of e)r.set(a.domain,(r.get(a.domain)||0)+1);let n=M.filter(a=>(r.get(a)||0)<3);n.length>0&&(t.push({type:"learning-gaps",severity:"medium",domain:"learning-optimization",title:"Learning Gaps Identified",description:`${n.length} domains have few learned patterns`,context:{domains:n}}),i.push({priority:"p2",domain:"learning-optimization",action:"Improve Learning Coverage",description:`Focus learning efforts on domains with few patterns: ${n.join(", ")}`,estimatedImpact:"medium",effort:"medium",autoFixable:!1}));let s=e.filter(a=>a.effectiveness>.9&&a.occurrences>20).sort((a,o)=>o.effectiveness-a.effectiveness).slice(0,5);s.length>0&&t.push({type:"top-patterns",severity:"info",domain:"learning-optimization",title:"Top Performing Patterns",description:`${s.length} patterns show exceptional effectiveness`,context:{patterns:s.map(a=>({domain:a.domain,type:a.type,effectiveness:a.effectiveness.toFixed(2)}))}})}calculateHealthScore(e,t){if(t.length===0)return 50;let r=t.reduce((s,a)=>s+a.effectiveness,0)/t.length*50;r+=Math.min(20,e.newInsights*4),r+=Math.min(15,e.crossDomainPatterns*3),r+=Math.min(10,e.dreamInsights*2);let n=e.patternsPruned/e.patternsAnalyzed;return r-=n*15,Math.max(0,Math.min(100,Math.round(r)))}};import*as V from"fs";import*as S from"path";Ue();var ft={id:"defect-predictor",name:"Defect Predictor",description:"Uses ML patterns to predict potential defects and identify high-risk code areas",intervalMs:900*1e3,priority:"high",targetDomains:["defect-intelligence"],enabled:!0,timeoutMs:18e4,retryCount:2,retryDelayMs:15e3},ce="defect-intelligence",_e="defect-intelligence:predictor:prediction:*",le="defect:predictions",ze=1;function yt(c,e){let t;try{t=V.realpathSync(S.resolve(e,c))}catch{let r=S.resolve(e,c),n=S.relative(e,r);return n&&!n.startsWith("..")&&!S.isAbsolute(n)?"missing":"outside"}let i=S.relative(e,t);if(i===""||i.startsWith("..")||S.isAbsolute(i))return"outside";try{return V.statSync(t).isFile()?"inside":"missing"}catch{return"missing"}}function vt(){let c=j();try{return V.realpathSync(c)}catch{return S.resolve(c)}}var O=class extends y{constructor(){super(ft)}async doExecute(e){let t=Date.now();e.logger.info("Starting defect prediction analysis");let i=[],r=[],{measured:n,unusable:s}=await this.readLatestPrediction(e);if(!n)return i.push({type:"defect-prediction-unmeasured",severity:"info",domain:"defect-intelligence",title:"Defect Prediction Unmeasured",description:(s?.ambiguous?"Multiple defect predictions have the same timestamp, so no unique latest analysis can be identified. No risk is reported. ":s?`The latest defect prediction (${s.id}) names no file inside this project (${s.outside} outside the project root, ${s.missing} missing), so no risk is reported. `:"No defect prediction for files in this project has been recorded in the last 7 days, so no risk is reported. ")+"Run defect_predict on the files to assess."}),s&&await this.markPreviousStale(e,s.id),e.logger.info("Defect prediction complete",{measured:!1}),this.createResult(Date.now()-t,{itemsAnalyzed:0,issuesFound:0,healthScore:100,trend:"stable",domainMetrics:{filesAnalyzed:0,highRiskFiles:0,hotspots:"unmeasured",avgDefectProbability:"unmeasured"}},i,r);let{predictions:a}=n;n.filesSkipped&&i.push({type:"defect-prediction-partial",severity:"info",domain:"defect-intelligence",title:"Partial Defect Prediction",description:`${n.filesSkipped} source files could not be read; risk estimates cover only ${a.length} successfully analyzed files.`}),this.analyzeHighRiskPredictions(a,i,r,n.estimated===!0),await e.memory.set(le,n),await e.memory.set("defect:lastAnalysis",n.evaluatedAt);let o=this.calculateHealthScore(a),l=a.filter(d=>d.riskLevel==="high"||d.riskLevel==="critical").length;return e.logger.info("Defect prediction complete",{measured:!0,healthScore:o,predictionId:n.predictionId,predictionsCount:a.length}),this.createResult(Date.now()-t,{itemsAnalyzed:a.length,issuesFound:a.filter(d=>d.probability>.5).length,healthScore:o,trend:"stable",domainMetrics:{filesAnalyzed:a.length,filesSkipped:n.filesSkipped??0,scanStatus:n.filesSkipped?"partial":"complete",highRiskFiles:l,missingFilesSkipped:n.missingFilesSkipped,outsideProjectSkipped:n.outsideProjectSkipped,hotspots:"unmeasured",avgDefectProbability:(a.reduce((d,u)=>d+u.probability,0)/a.length).toFixed(2)}},i,r)}async markPreviousStale(e,t){let i=await e.memory.get(le);!i||typeof i!="object"||i.measured!==!0||i.schemaVersion!==ze||i.stale===!0||i.predictionId===t||await e.memory.set(le,{...i,stale:!0,staleSince:new Date().toISOString(),supersededBy:t})}async readLatestPrediction(e){let t=await e.memory.search(_e,Number.MAX_SAFE_INTEGER,{namespace:ce}),i=Date.now(),r=null,n=!1;for(let u of t){let m=x(u,ce,_e),g=we(await e.memory.get(m,{namespace:ce}),i);g&&(!r||Date.parse(g.timestamp)>Date.parse(r.timestamp)?(r=g,n=!1):Date.parse(g.timestamp)===Date.parse(r.timestamp)&&g.id!==r.id&&(n=!0))}if(!r)return{measured:null,unusable:null};if(n)return{measured:null,unusable:{id:`ambiguous:${r.timestamp}`,outside:0,missing:0,ambiguous:!0}};let s=vt(),a=r.predictions.map(u=>yt(u.file,s)),o=r.predictions.filter((u,m)=>a[m]==="inside"),l=a.filter(u=>u==="outside").length,d=a.filter(u=>u==="missing").length;return l>0&&e.logger.warn("Ignoring defect predictions for paths outside the project root",{predictionId:r.id,outside:l}),o.length===0?(e.logger.info("Latest defect prediction names no file inside the project",{predictionId:r.id}),{measured:null,unusable:{id:r.id,outside:l,missing:d}}):{unusable:null,measured:{measured:!0,schemaVersion:ze,source:"defect-intelligence",predictionId:r.id,...r.estimated?{estimated:!0,predictionMethod:r.predictionMethod,filesSkipped:r.filesSkipped}:{},predictedAt:r.timestamp,evaluatedAt:new Date().toISOString(),predictions:o,missingFilesSkipped:d,outsideProjectSkipped:l}}}analyzeHighRiskPredictions(e,t,i,r=!1){let n=e.filter(d=>d.riskLevel==="critical"),s=e.filter(d=>d.riskLevel==="high");for(let d of[...n,...s]){let u=d.file.split(/[\\/]/).pop();t.push({type:`${d.riskLevel}-defect-risk`,severity:d.riskLevel,domain:"defect-intelligence",title:`${d.riskLevel==="critical"?"Critical":"High"} Defect Risk: ${u}`,description:r?`${(d.probability*100).toFixed(0)}% estimated code-risk score (static-code-indicators); not a calibrated defect probability`:`${(d.probability*100).toFixed(0)}% predicted defect probability (defect-intelligence predictor)`,resource:d.file,context:{probability:d.probability,...r?{estimated:!0,predictionMethod:"static-code-indicators"}:{},factors:d.factors,recommendations:d.recommendations}})}if(n.length===0&&s.length===0)return;i.push({priority:"p0",domain:"defect-intelligence",action:"Prioritize Code Review for High-Risk Files",description:`${n.length+s.length} files have elevated predicted defect risk. Schedule focused code reviews.`,estimatedImpact:"high",effort:"medium",autoFixable:!1});let a=[...n,...s],o=a.filter(d=>d.factors.some(u=>u.name==="codeComplexity"&&u.contribution>.1));o.length>0&&i.push({priority:"p1",domain:"defect-intelligence",action:"Reduce Code Complexity",description:`${o.length} high-risk files have code complexity as a major risk factor. Consider refactoring.`,estimatedImpact:"high",effort:"high",autoFixable:!1});let l=a.filter(d=>d.factors.some(u=>u.name==="testCoverage"&&u.contribution>.1));l.length>0&&i.push({priority:"p1",domain:"defect-intelligence",action:"Improve Test Coverage for Risky Files",description:`${l.length} high-risk files have low test coverage as a major risk factor. Add targeted tests.`,estimatedImpact:"high",effort:"medium",autoFixable:!0})}calculateHealthScore(e){if(e.length===0)return 100;let t=e.reduce((n,s)=>n+s.probability,0)/e.length,i=e.filter(n=>n.riskLevel==="critical"||n.riskLevel==="high").length,r=(1-t)*80-i/e.length*20+20;return Math.max(0,Math.min(100,Math.round(r)))}};var kt={id:"regression-monitor",name:"Regression Monitor",description:"Monitors for regressions in test results, performance, coverage, and quality metrics",intervalMs:600*1e3,priority:"high",targetDomains:["test-execution","coverage-analysis","quality-assessment"],enabled:!0,timeoutMs:12e4,retryCount:2,retryDelayMs:1e4},He="regression:baseline",Oe="regression:history",de=2,Ve=c=>typeof c=="number"&&Number.isFinite(c)&&c>=0&&c<=100,A=c=>Math.round(c*100)/100;function bt(c){if(!c||typeof c!="object")return null;let e=c;if(e.measured!==!0||e.schemaVersion!==de)return null;let t=e.coverage===null?null:E(e.coverage);if(e.coverage!==null&&!t)return null;let i=e.tests===null?null:Dt(e.tests);return e.tests!==null&&!i||!t&&!i?null:{measured:!0,schemaVersion:de,timestamp:typeof e.timestamp=="string"?e.timestamp:"",coverage:t,tests:i}}function Dt(c){if(!c||typeof c!="object")return null;let e=c;if(!Ve(e.passRate)||typeof e.measuredAt!="string"||typeof e.source!="string")return null;let t=Array.isArray(e.failedTests)&&e.failedTests.every(r=>typeof r=="string")?e.failedTests:null,i=e.avgTestDurationMs;return{testSet:Be(e.testSet),passRate:e.passRate,runId:typeof e.runId=="string"?e.runId:null,runStatus:e.runStatus==="passed"||e.runStatus==="failed"?e.runStatus:null,measuredAt:e.measuredAt,source:e.source,failedTests:t,avgTestDurationMs:typeof i=="number"&&Number.isFinite(i)&&i>=0?i:null}}function Be(c){if(!c||typeof c!="object")return null;let e=c,{total:t}=e;if(typeof t!="number"||!Number.isInteger(t)||t<=0)return null;let i=wt(e.files);return i?{total:t,files:i}:null}function wt(c){return!Array.isArray(c)||c.length===0||!c.every(e=>typeof e=="string")?null:[...new Set(c)].sort()}var St=(c,e)=>c!==null&&e!==null&&c.total===e.total&&c.files.length===e.files.length&&c.files.every((t,i)=>t===e.files[i]),B=class extends y{constructor(){super(kt)}async doExecute(e){let t=Date.now();e.logger.info("Starting regression monitoring");let i=[],r=[],n=await this.collectCurrentSnapshot(e),s=await e.memory.get(He),a=bt(s),o=this.baselineStatus(s,a);o==="legacy-ignored"?e.logger.info("Ignoring a regression:baseline without the measured stamp (written by <= 3.15.5)"):o==="invalid-ignored"&&e.logger.warn("Ignoring a malformed measured regression:baseline");let l=[],d=0;if(a&&n&&({regressions:l,metricsCompared:d}=this.detectRegressions(a,n),this.analyzeRegressions(l,i,r)),n){let f={...n,coverage:n.coverage??a?.coverage??null,tests:n.tests??a?.tests??null};await e.memory.set(He,f)}else i.push({type:"regression-unmeasured",severity:"info",domain:"quality-assessment",title:"Regression Baseline Unmeasured",description:"No measured coverage (stamped coverage:latest) and no current testsPassing evidence exist, so nothing was stored or compared. Run the tests (with coverage) to start regression tracking."});if(l.length>0){let f=new Date().toISOString(),h=await e.memory.get(Oe),k=Array.isArray(h)?h:[];for(k.push(...l.map(v=>({...v,measured:!0,detectedAt:f})));k.length>100;)k.shift();await e.memory.set(Oe,k)}let u=this.calculateHealthScore(l);e.logger.info("Regression monitoring complete",{healthScore:u,measured:n!==null,baselineStatus:o,regressionsDetected:l.length});let m=f=>f===null?"n/a":`${A(f)}%`,g=n?.tests??null,p=n?.coverage??null;return this.createResult(Date.now()-t,{itemsAnalyzed:d,issuesFound:l.length,healthScore:u,trend:l.length>0?"degrading":"stable",domainMetrics:{baselineStatus:o,testPassRate:g?m(g.passRate):"unmeasured",lineCoverage:p?m(p.line):"unmeasured",branchCoverage:p?m(p.branch):"unmeasured",avgTestDuration:g&&g.avgTestDurationMs!==null?`${A(g.avgTestDurationMs)}ms`:"unmeasured",regressionsDetected:l.length}},i,r)}baselineStatus(e,t){return t?"measured":e==null?"none":typeof e=="object"&&e.measured===!0?"invalid-ignored":"legacy-ignored"}async collectCurrentSnapshot(e){let t=E(await e.memory.get("coverage:latest")),i=await this.collectMeasuredTests(e);return!t&&!i?null:{measured:!0,schemaVersion:de,timestamp:new Date().toISOString(),coverage:t,tests:i}}async collectMeasuredTests(e){let t=await U(e.memory,"testsPassing");if(!t||!Ve(t.value))return null;let i=null,r=null,n=null;if(t.runId){let s=await e.memory.get(`test-run:${t.runId}`,{namespace:"test-execution"});if(s&&typeof s=="object"){Array.isArray(s.failedTests)&&(i=s.failedTests.map(l=>l&&typeof l=="object"?l.testName:void 0).filter(l=>typeof l=="string"));let{total:a,duration:o}=s;typeof a=="number"&&a>0&&typeof o=="number"&&Number.isFinite(o)&&o>=0&&(r=o/a),n=Be({total:a,files:s.testFiles})}}return{passRate:t.value,runId:t.runId??null,runStatus:t.runStatus??null,measuredAt:t.measuredAt,source:t.source,failedTests:i,avgTestDurationMs:r,testSet:n}}detectRegressions(e,t){let i=[],r=0,n=e.tests,s=t.tests;if(n&&s){if(r++,s.passRate<n.passRate-1){let u=s.passRate-n.passRate;i.push({type:"test",metric:"testPassRate",previousValue:A(n.passRate),currentValue:A(s.passRate),changePercent:u,severity:u<-5?"critical":u<-2?"high":"medium",...s.failedTests?{affectedTests:s.failedTests}:{}})}if(n.failedTests&&s.failedTests){r++;let u=new Set(n.failedTests),m=s.failedTests.filter(g=>!u.has(g));m.length>0&&i.push({type:"test",metric:"newFailures",previousValue:0,currentValue:m.length,changePercent:100,severity:m.length>5?"critical":m.length>2?"high":"medium",affectedTests:m})}let l=n.avgTestDurationMs,d=s.avgTestDurationMs;if(l!==null&&d!==null&&l>0&&St(n.testSet,s.testSet)){r++;let u=(d-l)/l*100;u>20&&i.push({type:"performance",metric:"avgTestDuration",previousValue:A(l),currentValue:A(d),changePercent:u,severity:u>50?"high":"medium"})}}let a=e.coverage,o=t.coverage;if(a&&o){if(r++,o.line<a.line-2){let l=o.line-a.line;i.push({type:"coverage",metric:"lineCoverage",previousValue:a.line,currentValue:o.line,changePercent:l,severity:l<-5?"high":"medium"})}if(a.branch!==null&&o.branch!==null&&(r++,o.branch<a.branch-3)){let l=o.branch-a.branch;i.push({type:"coverage",metric:"branchCoverage",previousValue:a.branch,currentValue:o.branch,changePercent:l,severity:l<-5?"high":"medium"})}}return{regressions:i,metricsCompared:r}}analyzeRegressions(e,t,i){for(let a of e){let o=this.getDomainForType(a.type);t.push({type:`${a.type}-regression`,severity:a.severity,domain:o,title:`${this.formatMetricName(a.metric)} Regression Detected`,description:this.formatRegressionDescription(a),context:{metric:a.metric,previousValue:a.previousValue,currentValue:a.currentValue,changePercent:a.changePercent.toFixed(2),affectedTests:a.affectedTests}})}let r=e.filter(a=>a.type==="test");if(r.length>0){let a=r.filter(o=>o.severity==="critical"||o.severity==="high");a.length>0&&i.push({priority:"p0",domain:"test-execution",action:"Investigate Test Regressions Immediately",description:`${a.length} significant test regressions detected. Review recent changes.`,estimatedImpact:"high",effort:"medium",autoFixable:!1})}e.filter(a=>a.type==="coverage").length>0&&i.push({priority:"p1",domain:"coverage-analysis",action:"Address Coverage Regression",description:"Code coverage has decreased. Add tests for new/changed code.",estimatedImpact:"medium",effort:"medium",autoFixable:!0}),e.filter(a=>a.type==="performance").length>0&&i.push({priority:"p2",domain:"test-execution",action:"Investigate Performance Regression",description:"Test execution has slowed. Review for new slow tests or infrastructure issues.",estimatedImpact:"medium",effort:"low",autoFixable:!1})}getDomainForType(e){return e==="coverage"?"coverage-analysis":"test-execution"}formatMetricName(e){return{testPassRate:"Test Pass Rate",lineCoverage:"Line Coverage",branchCoverage:"Branch Coverage",avgTestDuration:"Test Duration",newFailures:"New Test Failures"}[e]||e}formatRegressionDescription(e){if(e.metric==="newFailures")return`${e.currentValue} new test failures detected since last check`;let t=e.changePercent>0?"increased":"decreased",i=e.type==="performance"?"ms":"%";return`${this.formatMetricName(e.metric)} ${t} from ${e.previousValue}${i} to ${e.currentValue}${i} (${e.changePercent>0?"+":""}${e.changePercent.toFixed(1)}%)`}calculateHealthScore(e){if(e.length===0)return 100;let t=100;for(let i of e)switch(i.severity){case"critical":t-=25;break;case"high":t-=15;break;case"medium":t-=8;break;case"low":t-=3;break}return Math.max(0,Math.round(t))}};var Ct={id:"performance-baseline",name:"Performance Baseline Tracker",description:"Tracks performance trends and establishes baselines for test execution and builds",intervalMs:3600*1e3,priority:"normal",targetDomains:["test-execution","chaos-resilience"],enabled:!0,timeoutMs:3e5,retryCount:2,retryDelayMs:3e4},Ge="performance:baseline",qe="performance:history",ue=1,Rt=1.3,je=.1,Mt=168,me=c=>typeof c=="number"&&Number.isFinite(c)&&c>=0,T=c=>Math.round(c*100)/100;function Qe(c){if(!c||typeof c!="object")return null;let{total:e,files:t}=c;return typeof e!="number"||!Number.isInteger(e)||e<=0||!Array.isArray(t)||t.length===0||!t.every(i=>typeof i=="string")?null:{total:e,files:[...new Set(t)].sort()}}var At=(c,e)=>c!==null&&e!==null&&c.total===e.total&&c.files.length===e.files.length&&c.files.every((t,i)=>t===e.files[i]);function Tt(c){if(!c||typeof c!="object")return null;let e=c;if(e.measured!==!0||e.schemaVersion!==ue)return null;let t=e.testExecution;return!t||typeof t!="object"||!me(t.avgTestDurationMs)||!me(t.totalDurationMs)||typeof t.samples!="number"||!Number.isInteger(t.samples)||t.samples<1||typeof t.lastRunId!="string"?null:{measured:!0,schemaVersion:ue,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:"",testExecution:{avgTestDurationMs:t.avgTestDurationMs,totalDurationMs:t.totalDurationMs,samples:t.samples,lastRunId:t.lastRunId,testSet:Qe(t.testSet)}}}var G=class extends y{constructor(){super(Ct)}async doExecute(e){let t=Date.now();e.logger.info("Starting performance baseline tracking");let i=[],r=[],n=await this.collectMeasuredRun(e),s=await e.memory.get(Ge),a=Tt(s),o=this.baselineStatus(s,a);o==="legacy-ignored"?e.logger.info("Ignoring a performance:baseline without the measured stamp (written by <= 3.15.6)"):o==="invalid-ignored"&&e.logger.warn("Ignoring a malformed measured performance:baseline");let l=[],d=!1;n?a?.testExecution.lastRunId===n.runId?e.logger.debug("Latest measured run already in the performance baseline",{runId:n.runId}):(a&&At(a.testExecution.testSet,n.testSet)&&(d=!0,l=this.detectAnomalies(n,a),this.analyzeAnomalies(l,i,r)),await e.memory.set(Ge,this.nextBaseline(n,d?a:null)),await this.appendHistory(e,n)):i.push({type:"performance-unmeasured",severity:"info",domain:"test-execution",title:"Performance Baseline Unmeasured",description:"No recorded test run backs the current testsPassing evidence, so no timing was stored or compared. Run the test suite (test_execute_parallel, or `aqe test execute`) to start tracking. Build and resource figures are not measured by AQE."});let u=this.calculateHealthScore(l);return e.logger.info("Performance baseline tracking complete",{healthScore:u,measured:n!==null,baselineStatus:o,anomaliesDetected:l.length}),this.createResult(Date.now()-t,{itemsAnalyzed:d?2:0,issuesFound:l.length,healthScore:u,trend:l.length>0?"degrading":"stable",domainMetrics:{baselineStatus:o,avgTestDuration:n?`${T(n.avgTestDurationMs)}ms`:"unmeasured",totalTestDuration:n?`${T(n.totalDurationMs)}ms`:"unmeasured",compileDuration:"unmeasured",bundleSize:"unmeasured",peakMemory:"unmeasured",anomalies:l.length}},i,r)}baselineStatus(e,t){return t?"measured":e==null?"none":typeof e=="object"&&e.measured===!0?"invalid-ignored":"legacy-ignored"}async collectMeasuredRun(e){let t=await U(e.memory,"testsPassing");if(!t?.runId)return null;let i=await e.memory.get(`test-run:${t.runId}`,{namespace:"test-execution"});if(!i||typeof i!="object")return null;let{total:r,duration:n}=i;return typeof r!="number"||!Number.isInteger(r)||r<=0||!me(n)?null:{measured:!0,runId:t.runId,measuredAt:t.measuredAt,totalDurationMs:n,testCount:r,avgTestDurationMs:n/r,testSet:Qe({total:r,files:i.testFiles})}}detectAnomalies(e,t){let i=[],r=(n,s,a)=>{if(a<=0)return;let o=s/a;o>Rt&&i.push({metric:n,currentValue:T(s),baselineValue:T(a),deviationPercent:(o-1)*100,severity:o>1.5?"high":"medium"})};return r("avgTestDuration",e.avgTestDurationMs,t.testExecution.avgTestDurationMs),r("totalTestDuration",e.totalDurationMs,t.testExecution.totalDurationMs),i}analyzeAnomalies(e,t,i){for(let r of e)t.push({type:"performance-anomaly-test",severity:r.severity,domain:"test-execution",title:`Performance Anomaly: ${this.formatMetricName(r.metric)}`,description:`${this.formatMetricName(r.metric)} is ${r.deviationPercent.toFixed(1)}% above the measured baseline`,context:{currentValue:r.currentValue,baselineValue:r.baselineValue,deviationPercent:r.deviationPercent.toFixed(1)}});e.length>0&&i.push({priority:e.some(r=>r.severity==="high")?"p1":"p2",domain:"test-execution",action:"Investigate Test Performance Degradation",description:"Test execution times have increased. Review for slow tests or infrastructure issues.",estimatedImpact:"medium",effort:"medium",autoFixable:!1})}formatMetricName(e){return e==="avgTestDuration"?"Average Test Duration":"Total Test Duration"}nextBaseline(e,t){let i=t?.testExecution,r=(n,s)=>n*(1-je)+s*je;return{measured:!0,schemaVersion:ue,updatedAt:new Date().toISOString(),testExecution:{avgTestDurationMs:i?T(r(i.avgTestDurationMs,e.avgTestDurationMs)):e.avgTestDurationMs,totalDurationMs:i?T(r(i.totalDurationMs,e.totalDurationMs)):e.totalDurationMs,samples:i?i.samples+1:1,lastRunId:e.runId,testSet:e.testSet}}}async appendHistory(e,t){let i=await e.memory.get(qe),r=Array.isArray(i)?i:[];for(r.push(t);r.length>Mt;)r.shift();await e.memory.set(qe,r)}calculateHealthScore(e){let t=100;for(let i of e){let r=i.severity==="high"?15:8;t-=r+Math.min(10,i.deviationPercent/10)}return Math.max(0,Math.round(t))}};var Pt={id:"compliance-checker",name:"ADR/DDD Compliance Checker",description:"Verifies compliance with Architecture Decision Records and DDD patterns",intervalMs:1800*1e3,priority:"normal",targetDomains:["quality-assessment"],enabled:!0,timeoutMs:24e4,retryCount:2,retryDelayMs:3e4},q=class extends y{constructor(){super(Pt)}async doExecute(e){let t=Date.now();e.logger.info("Starting compliance checking");let i=[],r=[],n=await this.checkADRCompliance(e),s=await this.checkDDDCompliance(e),a=await this.checkStructuralCompliance(e);this.analyzeADRCompliance(n,i,r),this.analyzeDDDCompliance(s,i,r),this.analyzeStructuralCompliance(a,i,r),await e.memory.set("compliance:adr",n),await e.memory.set("compliance:ddd",s),await e.memory.set("compliance:structural",a),await e.memory.set("compliance:lastCheck",new Date().toISOString());let o=this.calculateHealthScore(n,s,a);return e.logger.info("Compliance checking complete",{healthScore:o,adrChecks:n.length,domainChecks:s.length}),this.createResult(Date.now()-t,{itemsAnalyzed:n.length+s.length+a.length,issuesFound:i.length,healthScore:o,trend:"stable",domainMetrics:{adrCompliance:`${this.calculateAvgScore(n)}%`,dddCompliance:`${this.calculateDDDAvgScore(s)}%`,structuralCompliance:`${this.calculateStructuralScore(a)}%`,totalViolations:n.reduce((l,d)=>l+d.violations.length,0)+s.reduce((l,d)=>l+d.violations.length,0)}},i,r)}async checkADRCompliance(e){if(!e.domains.getDomainAPI("quality-assessment"))throw new Error("Quality-assessment domain not available - cannot check ADR compliance. Ensure the quality-assessment domain is properly initialized before running this worker.");let i=await e.memory.search("compliance:adr:*");if(i.length===0)throw new Error('No ADR compliance data found in memory - cannot check ADR compliance. Ensure ADR compliance data is stored with keys matching "compliance:adr:*" before running this worker.');let r=[],n=[];for(let s of i)try{let a=await e.memory.get(s);a&&r.push(a)}catch{n.push(s)}if(r.length===0)throw new Error(`Found ${i.length} ADR compliance keys but failed to retrieve any data. Failed keys: ${n.join(", ")}. Check memory service connectivity.`);return r}async checkDDDCompliance(e){let t=[];for(let i of M)try{let r=await this.checkDomainCompliance(e,i);t.push(r)}catch(r){e.logger.warn(`Failed to check DDD compliance for ${i}`,{error:r})}return t}async checkDomainCompliance(e,t){let i=e.domains.getDomainHealth(t),r=e.domains.getDomainAPI(t),n=i.status!=="unhealthy",s=r!==void 0,a=s,o=s,l=await e.memory.get(`compliance:ddd:${t}`),d=l?.hasEntities??!1,u=l?.hasEvents??!1,m=l?.hasRepositories??!1,g=l?.namingCompliant??s,p=[];d||p.push("Missing domain entities"),u||p.push("Missing domain events"),m||p.push("Missing repositories"),n||p.push("Domain coordinator not available"),s||p.push("Domain plugin not loaded");let f=[n,s,a,o,d,u,m,g],h=Math.round(f.filter(Boolean).length/f.length*100);return{domain:t,hasCoordinator:n,hasPlugin:s,hasInterfaces:a,hasServices:o,hasEntities:d,hasEvents:u,hasRepositories:m,namingCompliant:g,score:h,violations:p}}async checkStructuralCompliance(e){let t=await e.memory.search("compliance:structural:*");if(t.length===0)throw new Error('No structural compliance data found in memory - cannot check structural compliance. Ensure structural compliance data is stored with keys matching "compliance:structural:*" before running this worker.');let i=[],r=[];for(let n of t)try{let s=await e.memory.get(n);s&&i.push(s)}catch(s){r.push(n),e.logger.warn(`Failed to retrieve structural compliance data: ${n}`,{error:s})}if(i.length===0)throw new Error(`Found ${t.length} structural compliance keys but failed to retrieve any data. Failed keys: ${r.join(", ")}. Check memory service connectivity.`);return i}analyzeADRCompliance(e,t,i){let r=e.filter(s=>s.status==="non-compliant"),n=e.filter(s=>s.status==="partial");for(let s of r)t.push({type:"adr-non-compliance",severity:"high",domain:"quality-assessment",title:`ADR Non-Compliance: ${s.adrId}`,description:`${s.title} is not compliant (score: ${s.score}%)`,context:{adrId:s.adrId,violations:s.violations}});for(let s of n)t.push({type:"adr-partial-compliance",severity:"medium",domain:"quality-assessment",title:`ADR Partial Compliance: ${s.adrId}`,description:`${s.title} is partially compliant (score: ${s.score}%)`,context:{adrId:s.adrId,violations:s.violations}});r.length>0&&i.push({priority:"p1",domain:"quality-assessment",action:"Address ADR Non-Compliance",description:`${r.length} ADRs are not being followed. Review and implement required patterns.`,estimatedImpact:"high",effort:"high",autoFixable:!1})}analyzeDDDCompliance(e,t,i){let r=e.filter(a=>a.score<70),n=e.filter(a=>!a.hasEntities),s=e.filter(a=>!a.hasEvents);r.length>0&&t.push({type:"ddd-low-compliance",severity:"medium",domain:"quality-assessment",title:`${r.length} Domains Have Low DDD Compliance`,description:"Some domains are missing required DDD components",context:{domains:r.map(a=>({domain:a.domain,score:a.score}))}}),n.length>0&&(t.push({type:"ddd-missing-entities",severity:"low",domain:"quality-assessment",title:"Domains Missing Entity Definitions",description:`${n.length} domains lack proper entity definitions`,context:{domains:n.map(a=>a.domain)}}),i.push({priority:"p3",domain:"quality-assessment",action:"Add Domain Entities",description:"Define rich domain entities for domains that currently lack them.",estimatedImpact:"medium",effort:"medium",autoFixable:!1})),s.length>0&&i.push({priority:"p3",domain:"quality-assessment",action:"Implement Domain Events",description:`${s.length} domains are missing domain event definitions.`,estimatedImpact:"medium",effort:"medium",autoFixable:!1})}analyzeStructuralCompliance(e,t,i){let r=e.filter(n=>!n.compliant);for(let n of r)t.push({type:"structural-violation",severity:"medium",domain:"quality-assessment",title:`Structural Violation: ${n.category}`,description:`Rule "${n.rule}" is not being followed: ${n.details}`,context:{category:n.category,rule:n.rule}});r.length>0&&i.push({priority:"p2",domain:"quality-assessment",action:"Fix Structural Violations",description:`${r.length} structural rules are being violated. Review architecture guidelines.`,estimatedImpact:"medium",effort:"medium",autoFixable:!1})}calculateAvgScore(e){return e.length===0?100:Math.round(e.reduce((t,i)=>t+i.score,0)/e.length)}calculateDDDAvgScore(e){return e.length===0?100:Math.round(e.reduce((t,i)=>t+i.score,0)/e.length)}calculateStructuralScore(e){if(e.length===0)return 100;let t=e.filter(i=>i.compliant).length;return Math.round(t/e.length*100)}calculateHealthScore(e,t,i){let r=this.calculateAvgScore(e)*.4,n=this.calculateDDDAvgScore(t)*.4,s=this.calculateStructuralScore(i)*.2;return Math.round(r+n+s)}};J();var Wn={id:"cloud-sync",name:"Cloud Sync",description:"Periodically syncs local learning data to cloud PostgreSQL",intervalMs:parseInt(process.env.AQE_SYNC_INTERVAL||"3600000",10),priority:"low",targetDomains:["learning-optimization"],enabled:process.env.AQE_CLOUD_SYNC_ENABLED==="true",timeoutMs:6e5,retryCount:3,retryDelayMs:6e4};var It={autoStart:!0,enabledWorkers:[],disabledWorkers:[],logLevel:"info",healthCheckIntervalMs:6e4},pe=class{_running=!1;_startedAt;_healthCheckTimer;workerManager;config;_qualityDaemon;unknownDisabledIds=[];constructor(e){this.config={...It,...e,disabledWorkers:(e?.disabledWorkers??Me()).map(t=>t.toLowerCase())},this.workerManager=new X,this.registerWorkers()}get running(){return this._running}get uptime(){return this._startedAt?Math.floor((Date.now()-this._startedAt.getTime())/1e3):0}async start(){if(this._running){console.info("[Daemon] Already running");return}if(console.info("[Daemon] Starting QE Background Workers..."),this.unknownDisabledIds.length>0&&console.warn(`[AQE] WARN AQE_DISABLED_WORKERS: unknown worker id(s) ignored: ${this.unknownDisabledIds.join(", ")}`),this._running=!0,this._startedAt=new Date,this._healthCheckTimer=setInterval(()=>{this.performHealthCheck()},this.config.healthCheckIntervalMs),this._healthCheckTimer.unref?.(),this.config.autoStart){try{await this.workerManager.startAll()}catch(t){throw this._running=!1,this._startedAt=void 0,this._healthCheckTimer&&clearInterval(this._healthCheckTimer),this._healthCheckTimer=void 0,await this.workerManager.stopAll().catch(()=>{}),t}console.info("[Daemon] All workers started")}let e=this.workerManager.list();console.info(`[Daemon] Registered ${e.length} workers:`);for(let t of e)console.info(` - ${t.config.id}: ${t.config.name} (interval: ${t.config.intervalMs}ms)`)}async stop(){if(!this._running){console.info("[Daemon] Not running");return}console.info("[Daemon] Stopping..."),this._healthCheckTimer&&(clearInterval(this._healthCheckTimer),this._healthCheckTimer=void 0),await this.workerManager.stopAll(),this._running=!1,console.info("[Daemon] Stopped")}async restart(){console.info("[Daemon] Restarting..."),await this.stop(),await this.start(),console.info("[Daemon] Restarted")}getStatus(){return{running:this._running,pid:process.pid,uptime:this.uptime,startedAt:this._startedAt,workerManager:this.workerManager.getHealth()}}getWorkerManager(){return this.workerManager}getQualityDaemon(e){return this._qualityDaemon||(this._qualityDaemon=new Te(e)),this._qualityDaemon}async runWorker(e){let t=await this.workerManager.runNow(e);console.info(`[Daemon] Worker ${e} completed:`,{success:t.success,duration:`${t.durationMs}ms`,findings:t.findings.length,healthScore:t.metrics.healthScore})}registerWorkers(){let e=[new W,new F,new $,new L,new _,new H,new O,new B,new G,new q,new ee];for(let i of e)this.config.disabledWorkers.includes(i.config.id)||(this.config.enabledWorkers.length===0||this.config.enabledWorkers.includes(i.config.id))&&this.workerManager.register(i);let t=new Set(e.map(i=>i.config.id));this.unknownDisabledIds=this.config.disabledWorkers.filter(i=>!t.has(i))}performHealthCheck(){let e=this.workerManager.getHealth();e.errorWorkers>0&&console.warn(`[Daemon] Health check: ${e.errorWorkers} workers in error state`),e.healthScore<70&&console.warn(`[Daemon] Health score degraded: ${e.healthScore}%`),this.config.logLevel==="debug"&&console.debug("[Daemon] Health check:",e)}};function Et(c){return new pe(c)}var P;function Zn(c){return P||(P=Et(c)),P}function er(){P?.running&&P.stop().catch(console.error),P=void 0}export{pe as QEDaemon,Et as createDaemon,Zn as getDaemon,er as resetDaemon};
18
+ `).run(a,n.patternType,n.domain,n.domain,n.name,o,n.confidence,n.sourceExperiences,n.successRate,n.confidence*.3+Math.min(n.sourceExperiences,100)/100*.2+n.successRate*.5,"short-term",JSON.stringify({type:"workflow",content:n.templateContent,variables:[]}),JSON.stringify({tags:n.actions,sourceType:"experience-extraction",extractedAt:new Date().toISOString()}),Math.round(n.sourceExperiences*n.successRate));let{ensurePatternEmbedding:l}=await import("./embed-and-insert-pattern-B6MNHICW.js");await l(r,a,n.name,o,n.actions),t++}catch(s){console.debug("[LearningConsolidation] Failed to create pattern:",s)}}catch(i){console.warn("[LearningConsolidation] Pattern creation batch failed:",i)}return t}addLifecycleStatsFinding(e,t,i){t.push({type:"lifecycle-stats",severity:"info",domain:"learning-optimization",title:"Pattern Lifecycle Statistics",description:`Active: ${e.activePatterns}, Promoted: ${e.promotedPatterns}, Deprecated: ${e.deprecatedPatterns}`,context:{total:e.totalPatterns,active:e.activePatterns,shortTerm:e.shortTermPatterns,longTerm:e.longTermPatterns,deprecated:e.deprecatedPatterns,avgConfidence:e.avgConfidence.toFixed(3),avgSuccessRate:e.avgSuccessRate.toFixed(3),nearDeprecation:e.patternsNearDeprecation}}),e.patternsNearDeprecation>0&&i.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${e.patternsNearDeprecation} patterns are near deprecation threshold. Consider improving their usage or archiving them.`,estimatedImpact:"medium",effort:"low",autoFixable:!1}),e.avgSuccessRate<.6&&i.push({priority:"p2",domain:"learning-optimization",action:"Improve Pattern Quality",description:`Average success rate (${(e.avgSuccessRate*100).toFixed(1)}%) is below target. Focus on quality over quantity.`,estimatedImpact:"high",effort:"medium",autoFixable:!1})}determineTrend(e){let t=e.patternsPromoted/Math.max(1,e.patternsAnalyzed),i=e.patternsDeprecated/Math.max(1,e.patternsAnalyzed),r=e.patternCandidatesFound/Math.max(1,e.experiencesProcessed);return t>.1&&r>.2?"improving":i>.2||e.patternsPruned>e.newInsights?"degrading":"stable"}async collectPatterns(e){let t=[],i=[];for(let r of M)try{let n=await this.getDomainPatterns(e,r);t.push(...n)}catch(n){let s=D(n);i.push(`${r}: ${s}`),e.logger.warn(`Failed to collect patterns from ${r}`,{error:n})}if(t.length===0&&i.length>0)throw new Error(`Failed to collect any learning patterns. Errors from domains: ${i.join("; ")}. Ensure at least one domain is available and has pattern data.`);if(t.length===0)throw new Error("No learning patterns to consolidate yet. Patterns accumulate as the captured-experience bridge feeds hook activity into the learning-optimization domain \u2014 first runs may be empty until a kernel-owning process (CLI/MCP) has been alive long enough to drain the captured_experiences table.");return t}async getDomainPatterns(e,t){let i=e.domains.getDomainAPI("learning-optimization");if(!i)throw new Error(`Learning-optimization domain not available for ${t} - cannot retrieve patterns. Ensure the learning-optimization domain is properly initialized.`);let r=await i.getPatternStats(t);if(!r.success)throw new Error(`Failed to get pattern stats for ${t}: Unknown error. Check domain service health and data availability.`);return!r.value||!r.value.topPatterns||r.value.topPatterns.length===0?(e.logger.debug(`No patterns found for domain ${t}`),[]):r.value.topPatterns.map(s=>({id:s.id,domain:s.domain,type:s.type,pattern:s.name,confidence:s.confidence,occurrences:s.usageCount,lastSeen:new Date(s.lastUsedAt),effectiveness:s.successRate}))}async consolidatePatterns(e,t){let i=0,r=0,n=0,s=new Map;for(let d of t){let u=`${d.type}:${d.pattern}`,m=s.get(u)||[];m.push(d),s.set(u,m)}for(let[,d]of Array.from(s.entries()))d.length>1&&(r+=d.length-1);i=t.filter(d=>d.confidence<.5).length;let o=t.filter(d=>{let u=(Date.now()-d.lastSeen.getTime())/864e5;return d.effectiveness>.8&&u<7});n=o.length;let l=this.findCrossDomainPatterns(t);return await e.memory.set("learning:insights",{recentHighPerformers:o,crossDomainPatterns:l,timestamp:new Date().toISOString()}),{patternsAnalyzed:t.length,patternsPruned:i,patternsConsolidated:r,newInsights:n,strategyUpdates:0,crossDomainPatterns:l.length,dreamInsights:0,dreamPatternsCreated:0,experiencesProcessed:0,patternCandidatesFound:0,patternsPromoted:0,patternsDeprecated:0,confidenceDecayApplied:0,experiencesMerged:0,experiencesArchived:0,patternsMined:0,domainsMined:0,dreamInsightsPruned:0}}async runDreamCycle(e,t,i,r){if(t.length<10)return e.logger.debug("Skipping dream cycle - insufficient patterns",{patternCount:t.length,required:10}),{insights:0,patternsCreated:0};let n=null;try{n=new ve,await n.initialize();let s=t.map(l=>({id:l.id,name:l.pattern,description:`${l.type} pattern from ${l.domain} (effectiveness: ${l.effectiveness})`,domain:l.domain,patternType:l.type,confidence:l.confidence,successRate:l.effectiveness}));await n.loadPatternsAsConcepts(s),e.logger.debug("Starting dream cycle",{patternCount:t.length});let a=await n.dream(),o=a.insights.filter(l=>l.actionable&&l.confidenceScore>.7);return o.length>0&&(i.push({type:"dream-insights",severity:"info",domain:"learning-optimization",title:"Dream Cycle Insights Generated",description:`${o.length} actionable insights discovered through pattern association`,context:{totalInsights:a.insights.length,actionableInsights:o.length,topInsight:o[0]?.description,activationIterations:a.activationStats.totalIterations}}),r.push({priority:"p2",domain:"learning-optimization",action:"Apply Dream Insights",description:`${o.length} insights from dream cycle can improve pattern effectiveness`,estimatedImpact:"medium",effort:"low",autoFixable:!0})),await e.memory.set("learning:dreamInsights",{cycleId:a.cycle.id,insights:o,timestamp:new Date().toISOString()}),e.logger.info("Dream cycle completed",{insights:a.insights.length,actionable:o.length,duration:a.cycle.durationMs}),{insights:a.insights.length,patternsCreated:a.patternsCreated}}catch(s){return e.logger.warn("Dream cycle failed",{error:D(s)}),{insights:0,patternsCreated:0}}finally{n&&await n.close()}}findCrossDomainPatterns(e){let t=new Map;for(let r of e){let n=t.get(r.type)||[];n.push(r),t.set(r.type,n)}let i=[];for(let[r,n]of Array.from(t.entries())){let s=Array.from(new Set(n.map(a=>a.domain)));s.length>=3&&i.push({pattern:r,domains:s,avgEffectiveness:n.reduce((a,o)=>a+o.effectiveness,0)/n.length})}return i}identifyCrossDomainPatterns(e,t,i){let r=this.findCrossDomainPatterns(e);r.length>0&&(t.push({type:"cross-domain-patterns",severity:"info",domain:"learning-optimization",title:"Cross-Domain Patterns Identified",description:`${r.length} patterns are effective across multiple domains`,context:{patterns:r.map(n=>({type:n.pattern,domains:n.domains.length,effectiveness:n.avgEffectiveness.toFixed(2)}))}}),i.push({priority:"p2",domain:"learning-optimization",action:"Leverage Cross-Domain Patterns",description:"Apply successful cross-domain patterns to domains where they are not yet used.",estimatedImpact:"medium",effort:"low",autoFixable:!0}))}pruneIneffectivePatterns(e,t,i){let r=e.filter(s=>s.effectiveness<.3&&s.occurrences>10),n=e.filter(s=>(Date.now()-s.lastSeen.getTime())/864e5>30);r.length>0&&(t.push({type:"ineffective-patterns",severity:"low",domain:"learning-optimization",title:"Ineffective Patterns Detected",description:`${r.length} patterns have low effectiveness despite many occurrences`,context:{count:r.length,domains:Array.from(new Set(r.map(s=>s.domain)))}}),i.push({priority:"p3",domain:"learning-optimization",action:"Review Ineffective Patterns",description:"Consider removing or refining patterns that consistently underperform.",estimatedImpact:"low",effort:"low",autoFixable:!0})),n.length>0&&t.push({type:"stale-patterns",severity:"info",domain:"learning-optimization",title:"Stale Patterns Identified",description:`${n.length} patterns have not been seen in over 30 days`,context:{count:n.length}})}generateOptimizations(e,t,i){let r=new Map;for(let a of e)r.set(a.domain,(r.get(a.domain)||0)+1);let n=M.filter(a=>(r.get(a)||0)<3);n.length>0&&(t.push({type:"learning-gaps",severity:"medium",domain:"learning-optimization",title:"Learning Gaps Identified",description:`${n.length} domains have few learned patterns`,context:{domains:n}}),i.push({priority:"p2",domain:"learning-optimization",action:"Improve Learning Coverage",description:`Focus learning efforts on domains with few patterns: ${n.join(", ")}`,estimatedImpact:"medium",effort:"medium",autoFixable:!1}));let s=e.filter(a=>a.effectiveness>.9&&a.occurrences>20).sort((a,o)=>o.effectiveness-a.effectiveness).slice(0,5);s.length>0&&t.push({type:"top-patterns",severity:"info",domain:"learning-optimization",title:"Top Performing Patterns",description:`${s.length} patterns show exceptional effectiveness`,context:{patterns:s.map(a=>({domain:a.domain,type:a.type,effectiveness:a.effectiveness.toFixed(2)}))}})}calculateHealthScore(e,t){if(t.length===0)return 50;let r=t.reduce((s,a)=>s+a.effectiveness,0)/t.length*50;r+=Math.min(20,e.newInsights*4),r+=Math.min(15,e.crossDomainPatterns*3),r+=Math.min(10,e.dreamInsights*2);let n=e.patternsPruned/e.patternsAnalyzed;return r-=n*15,Math.max(0,Math.min(100,Math.round(r)))}};import*as V from"fs";import*as S from"path";Ue();var ft={id:"defect-predictor",name:"Defect Predictor",description:"Uses ML patterns to predict potential defects and identify high-risk code areas",intervalMs:900*1e3,priority:"high",targetDomains:["defect-intelligence"],enabled:!0,timeoutMs:18e4,retryCount:2,retryDelayMs:15e3},ce="defect-intelligence",_e="defect-intelligence:predictor:prediction:*",le="defect:predictions",ze=1;function yt(c,e){let t;try{t=V.realpathSync(S.resolve(e,c))}catch{let r=S.resolve(e,c),n=S.relative(e,r);return n&&!n.startsWith("..")&&!S.isAbsolute(n)?"missing":"outside"}let i=S.relative(e,t);if(i===""||i.startsWith("..")||S.isAbsolute(i))return"outside";try{return V.statSync(t).isFile()?"inside":"missing"}catch{return"missing"}}function vt(){let c=j();try{return V.realpathSync(c)}catch{return S.resolve(c)}}var O=class extends y{constructor(){super(ft)}async doExecute(e){let t=Date.now();e.logger.info("Starting defect prediction analysis");let i=[],r=[],{measured:n,unusable:s}=await this.readLatestPrediction(e);if(!n)return i.push({type:"defect-prediction-unmeasured",severity:"info",domain:"defect-intelligence",title:"Defect Prediction Unmeasured",description:(s?.ambiguous?"Multiple defect predictions have the same timestamp, so no unique latest analysis can be identified. No risk is reported. ":s?`The latest defect prediction (${s.id}) names no file inside this project (${s.outside} outside the project root, ${s.missing} missing), so no risk is reported. `:"No defect prediction for files in this project has been recorded in the last 7 days, so no risk is reported. ")+"Run defect_predict on the files to assess."}),s&&await this.markPreviousStale(e,s.id),e.logger.info("Defect prediction complete",{measured:!1}),this.createResult(Date.now()-t,{itemsAnalyzed:0,issuesFound:0,healthScore:100,trend:"stable",domainMetrics:{filesAnalyzed:0,highRiskFiles:0,hotspots:"unmeasured",avgDefectProbability:"unmeasured"}},i,r);let{predictions:a}=n;n.filesSkipped&&i.push({type:"defect-prediction-partial",severity:"info",domain:"defect-intelligence",title:"Partial Defect Prediction",description:`${n.filesSkipped} source files could not be read; risk estimates cover only ${a.length} successfully analyzed files.`}),this.analyzeHighRiskPredictions(a,i,r,n.estimated===!0),await e.memory.set(le,n),await e.memory.set("defect:lastAnalysis",n.evaluatedAt);let o=this.calculateHealthScore(a),l=a.filter(d=>d.riskLevel==="high"||d.riskLevel==="critical").length;return e.logger.info("Defect prediction complete",{measured:!0,healthScore:o,predictionId:n.predictionId,predictionsCount:a.length}),this.createResult(Date.now()-t,{itemsAnalyzed:a.length,issuesFound:a.filter(d=>d.probability>.5).length,healthScore:o,trend:"stable",domainMetrics:{filesAnalyzed:a.length,filesSkipped:n.filesSkipped??0,scanStatus:n.filesSkipped?"partial":"complete",highRiskFiles:l,missingFilesSkipped:n.missingFilesSkipped,outsideProjectSkipped:n.outsideProjectSkipped,hotspots:"unmeasured",avgDefectProbability:(a.reduce((d,u)=>d+u.probability,0)/a.length).toFixed(2)}},i,r)}async markPreviousStale(e,t){let i=await e.memory.get(le);!i||typeof i!="object"||i.measured!==!0||i.schemaVersion!==ze||i.stale===!0||i.predictionId===t||await e.memory.set(le,{...i,stale:!0,staleSince:new Date().toISOString(),supersededBy:t})}async readLatestPrediction(e){let t=await e.memory.search(_e,Number.MAX_SAFE_INTEGER,{namespace:ce}),i=Date.now(),r=null,n=!1;for(let u of t){let m=x(u,ce,_e),g=we(await e.memory.get(m,{namespace:ce}),i);g&&(!r||Date.parse(g.timestamp)>Date.parse(r.timestamp)?(r=g,n=!1):Date.parse(g.timestamp)===Date.parse(r.timestamp)&&g.id!==r.id&&(n=!0))}if(!r)return{measured:null,unusable:null};if(n)return{measured:null,unusable:{id:`ambiguous:${r.timestamp}`,outside:0,missing:0,ambiguous:!0}};let s=vt(),a=r.predictions.map(u=>yt(u.file,s)),o=r.predictions.filter((u,m)=>a[m]==="inside"),l=a.filter(u=>u==="outside").length,d=a.filter(u=>u==="missing").length;return l>0&&e.logger.warn("Ignoring defect predictions for paths outside the project root",{predictionId:r.id,outside:l}),o.length===0?(e.logger.info("Latest defect prediction names no file inside the project",{predictionId:r.id}),{measured:null,unusable:{id:r.id,outside:l,missing:d}}):{unusable:null,measured:{measured:!0,schemaVersion:ze,source:"defect-intelligence",predictionId:r.id,...r.estimated?{estimated:!0,predictionMethod:r.predictionMethod,filesSkipped:r.filesSkipped}:{},predictedAt:r.timestamp,evaluatedAt:new Date().toISOString(),predictions:o,missingFilesSkipped:d,outsideProjectSkipped:l}}}analyzeHighRiskPredictions(e,t,i,r=!1){let n=e.filter(d=>d.riskLevel==="critical"),s=e.filter(d=>d.riskLevel==="high");for(let d of[...n,...s]){let u=d.file.split(/[\\/]/).pop();t.push({type:`${d.riskLevel}-defect-risk`,severity:d.riskLevel,domain:"defect-intelligence",title:`${d.riskLevel==="critical"?"Critical":"High"} Defect Risk: ${u}`,description:r?`${(d.probability*100).toFixed(0)}% estimated code-risk score (static-code-indicators); not a calibrated defect probability`:`${(d.probability*100).toFixed(0)}% predicted defect probability (defect-intelligence predictor)`,resource:d.file,context:{probability:d.probability,...r?{estimated:!0,predictionMethod:"static-code-indicators"}:{},factors:d.factors,recommendations:d.recommendations}})}if(n.length===0&&s.length===0)return;i.push({priority:"p0",domain:"defect-intelligence",action:"Prioritize Code Review for High-Risk Files",description:`${n.length+s.length} files have elevated predicted defect risk. Schedule focused code reviews.`,estimatedImpact:"high",effort:"medium",autoFixable:!1});let a=[...n,...s],o=a.filter(d=>d.factors.some(u=>u.name==="codeComplexity"&&u.contribution>.1));o.length>0&&i.push({priority:"p1",domain:"defect-intelligence",action:"Reduce Code Complexity",description:`${o.length} high-risk files have code complexity as a major risk factor. Consider refactoring.`,estimatedImpact:"high",effort:"high",autoFixable:!1});let l=a.filter(d=>d.factors.some(u=>u.name==="testCoverage"&&u.contribution>.1));l.length>0&&i.push({priority:"p1",domain:"defect-intelligence",action:"Improve Test Coverage for Risky Files",description:`${l.length} high-risk files have low test coverage as a major risk factor. Add targeted tests.`,estimatedImpact:"high",effort:"medium",autoFixable:!0})}calculateHealthScore(e){if(e.length===0)return 100;let t=e.reduce((n,s)=>n+s.probability,0)/e.length,i=e.filter(n=>n.riskLevel==="critical"||n.riskLevel==="high").length,r=(1-t)*80-i/e.length*20+20;return Math.max(0,Math.min(100,Math.round(r)))}};var kt={id:"regression-monitor",name:"Regression Monitor",description:"Monitors for regressions in test results, performance, coverage, and quality metrics",intervalMs:600*1e3,priority:"high",targetDomains:["test-execution","coverage-analysis","quality-assessment"],enabled:!0,timeoutMs:12e4,retryCount:2,retryDelayMs:1e4},He="regression:baseline",Oe="regression:history",de=2,Ve=c=>typeof c=="number"&&Number.isFinite(c)&&c>=0&&c<=100,A=c=>Math.round(c*100)/100;function bt(c){if(!c||typeof c!="object")return null;let e=c;if(e.measured!==!0||e.schemaVersion!==de)return null;let t=e.coverage===null?null:E(e.coverage);if(e.coverage!==null&&!t)return null;let i=e.tests===null?null:Dt(e.tests);return e.tests!==null&&!i||!t&&!i?null:{measured:!0,schemaVersion:de,timestamp:typeof e.timestamp=="string"?e.timestamp:"",coverage:t,tests:i}}function Dt(c){if(!c||typeof c!="object")return null;let e=c;if(!Ve(e.passRate)||typeof e.measuredAt!="string"||typeof e.source!="string")return null;let t=Array.isArray(e.failedTests)&&e.failedTests.every(r=>typeof r=="string")?e.failedTests:null,i=e.avgTestDurationMs;return{testSet:Be(e.testSet),passRate:e.passRate,runId:typeof e.runId=="string"?e.runId:null,runStatus:e.runStatus==="passed"||e.runStatus==="failed"?e.runStatus:null,measuredAt:e.measuredAt,source:e.source,failedTests:t,avgTestDurationMs:typeof i=="number"&&Number.isFinite(i)&&i>=0?i:null}}function Be(c){if(!c||typeof c!="object")return null;let e=c,{total:t}=e;if(typeof t!="number"||!Number.isInteger(t)||t<=0)return null;let i=wt(e.files);return i?{total:t,files:i}:null}function wt(c){return!Array.isArray(c)||c.length===0||!c.every(e=>typeof e=="string")?null:[...new Set(c)].sort()}var St=(c,e)=>c!==null&&e!==null&&c.total===e.total&&c.files.length===e.files.length&&c.files.every((t,i)=>t===e.files[i]),B=class extends y{constructor(){super(kt)}async doExecute(e){let t=Date.now();e.logger.info("Starting regression monitoring");let i=[],r=[],n=await this.collectCurrentSnapshot(e),s=await e.memory.get(He),a=bt(s),o=this.baselineStatus(s,a);o==="legacy-ignored"?e.logger.info("Ignoring a regression:baseline without the measured stamp (written by <= 3.15.5)"):o==="invalid-ignored"&&e.logger.warn("Ignoring a malformed measured regression:baseline");let l=[],d=0;if(a&&n&&({regressions:l,metricsCompared:d}=this.detectRegressions(a,n),this.analyzeRegressions(l,i,r)),n){let f={...n,coverage:n.coverage??a?.coverage??null,tests:n.tests??a?.tests??null};await e.memory.set(He,f)}else i.push({type:"regression-unmeasured",severity:"info",domain:"quality-assessment",title:"Regression Baseline Unmeasured",description:"No measured coverage (stamped coverage:latest) and no current testsPassing evidence exist, so nothing was stored or compared. Run the tests (with coverage) to start regression tracking."});if(l.length>0){let f=new Date().toISOString(),h=await e.memory.get(Oe),k=Array.isArray(h)?h:[];for(k.push(...l.map(v=>({...v,measured:!0,detectedAt:f})));k.length>100;)k.shift();await e.memory.set(Oe,k)}let u=this.calculateHealthScore(l);e.logger.info("Regression monitoring complete",{healthScore:u,measured:n!==null,baselineStatus:o,regressionsDetected:l.length});let m=f=>f===null?"n/a":`${A(f)}%`,g=n?.tests??null,p=n?.coverage??null;return this.createResult(Date.now()-t,{itemsAnalyzed:d,issuesFound:l.length,healthScore:u,trend:l.length>0?"degrading":"stable",domainMetrics:{baselineStatus:o,testPassRate:g?m(g.passRate):"unmeasured",lineCoverage:p?m(p.line):"unmeasured",branchCoverage:p?m(p.branch):"unmeasured",avgTestDuration:g&&g.avgTestDurationMs!==null?`${A(g.avgTestDurationMs)}ms`:"unmeasured",regressionsDetected:l.length}},i,r)}baselineStatus(e,t){return t?"measured":e==null?"none":typeof e=="object"&&e.measured===!0?"invalid-ignored":"legacy-ignored"}async collectCurrentSnapshot(e){let t=E(await e.memory.get("coverage:latest")),i=await this.collectMeasuredTests(e);return!t&&!i?null:{measured:!0,schemaVersion:de,timestamp:new Date().toISOString(),coverage:t,tests:i}}async collectMeasuredTests(e){let t=await U(e.memory,"testsPassing");if(!t||!Ve(t.value))return null;let i=null,r=null,n=null;if(t.runId){let s=await e.memory.get(`test-run:${t.runId}`,{namespace:"test-execution"});if(s&&typeof s=="object"){Array.isArray(s.failedTests)&&(i=s.failedTests.map(l=>l&&typeof l=="object"?l.testName:void 0).filter(l=>typeof l=="string"));let{total:a,duration:o}=s;typeof a=="number"&&a>0&&typeof o=="number"&&Number.isFinite(o)&&o>=0&&(r=o/a),n=Be({total:a,files:s.testFiles})}}return{passRate:t.value,runId:t.runId??null,runStatus:t.runStatus??null,measuredAt:t.measuredAt,source:t.source,failedTests:i,avgTestDurationMs:r,testSet:n}}detectRegressions(e,t){let i=[],r=0,n=e.tests,s=t.tests;if(n&&s){if(r++,s.passRate<n.passRate-1){let u=s.passRate-n.passRate;i.push({type:"test",metric:"testPassRate",previousValue:A(n.passRate),currentValue:A(s.passRate),changePercent:u,severity:u<-5?"critical":u<-2?"high":"medium",...s.failedTests?{affectedTests:s.failedTests}:{}})}if(n.failedTests&&s.failedTests){r++;let u=new Set(n.failedTests),m=s.failedTests.filter(g=>!u.has(g));m.length>0&&i.push({type:"test",metric:"newFailures",previousValue:0,currentValue:m.length,changePercent:100,severity:m.length>5?"critical":m.length>2?"high":"medium",affectedTests:m})}let l=n.avgTestDurationMs,d=s.avgTestDurationMs;if(l!==null&&d!==null&&l>0&&St(n.testSet,s.testSet)){r++;let u=(d-l)/l*100;u>20&&i.push({type:"performance",metric:"avgTestDuration",previousValue:A(l),currentValue:A(d),changePercent:u,severity:u>50?"high":"medium"})}}let a=e.coverage,o=t.coverage;if(a&&o){if(r++,o.line<a.line-2){let l=o.line-a.line;i.push({type:"coverage",metric:"lineCoverage",previousValue:a.line,currentValue:o.line,changePercent:l,severity:l<-5?"high":"medium"})}if(a.branch!==null&&o.branch!==null&&(r++,o.branch<a.branch-3)){let l=o.branch-a.branch;i.push({type:"coverage",metric:"branchCoverage",previousValue:a.branch,currentValue:o.branch,changePercent:l,severity:l<-5?"high":"medium"})}}return{regressions:i,metricsCompared:r}}analyzeRegressions(e,t,i){for(let a of e){let o=this.getDomainForType(a.type);t.push({type:`${a.type}-regression`,severity:a.severity,domain:o,title:`${this.formatMetricName(a.metric)} Regression Detected`,description:this.formatRegressionDescription(a),context:{metric:a.metric,previousValue:a.previousValue,currentValue:a.currentValue,changePercent:a.changePercent.toFixed(2),affectedTests:a.affectedTests}})}let r=e.filter(a=>a.type==="test");if(r.length>0){let a=r.filter(o=>o.severity==="critical"||o.severity==="high");a.length>0&&i.push({priority:"p0",domain:"test-execution",action:"Investigate Test Regressions Immediately",description:`${a.length} significant test regressions detected. Review recent changes.`,estimatedImpact:"high",effort:"medium",autoFixable:!1})}e.filter(a=>a.type==="coverage").length>0&&i.push({priority:"p1",domain:"coverage-analysis",action:"Address Coverage Regression",description:"Code coverage has decreased. Add tests for new/changed code.",estimatedImpact:"medium",effort:"medium",autoFixable:!0}),e.filter(a=>a.type==="performance").length>0&&i.push({priority:"p2",domain:"test-execution",action:"Investigate Performance Regression",description:"Test execution has slowed. Review for new slow tests or infrastructure issues.",estimatedImpact:"medium",effort:"low",autoFixable:!1})}getDomainForType(e){return e==="coverage"?"coverage-analysis":"test-execution"}formatMetricName(e){return{testPassRate:"Test Pass Rate",lineCoverage:"Line Coverage",branchCoverage:"Branch Coverage",avgTestDuration:"Test Duration",newFailures:"New Test Failures"}[e]||e}formatRegressionDescription(e){if(e.metric==="newFailures")return`${e.currentValue} new test failures detected since last check`;let t=e.changePercent>0?"increased":"decreased",i=e.type==="performance"?"ms":"%";return`${this.formatMetricName(e.metric)} ${t} from ${e.previousValue}${i} to ${e.currentValue}${i} (${e.changePercent>0?"+":""}${e.changePercent.toFixed(1)}%)`}calculateHealthScore(e){if(e.length===0)return 100;let t=100;for(let i of e)switch(i.severity){case"critical":t-=25;break;case"high":t-=15;break;case"medium":t-=8;break;case"low":t-=3;break}return Math.max(0,Math.round(t))}};var Ct={id:"performance-baseline",name:"Performance Baseline Tracker",description:"Tracks performance trends and establishes baselines for test execution and builds",intervalMs:3600*1e3,priority:"normal",targetDomains:["test-execution","chaos-resilience"],enabled:!0,timeoutMs:3e5,retryCount:2,retryDelayMs:3e4},Ge="performance:baseline",qe="performance:history",ue=1,Rt=1.3,je=.1,Mt=168,me=c=>typeof c=="number"&&Number.isFinite(c)&&c>=0,T=c=>Math.round(c*100)/100;function Qe(c){if(!c||typeof c!="object")return null;let{total:e,files:t}=c;return typeof e!="number"||!Number.isInteger(e)||e<=0||!Array.isArray(t)||t.length===0||!t.every(i=>typeof i=="string")?null:{total:e,files:[...new Set(t)].sort()}}var At=(c,e)=>c!==null&&e!==null&&c.total===e.total&&c.files.length===e.files.length&&c.files.every((t,i)=>t===e.files[i]);function Tt(c){if(!c||typeof c!="object")return null;let e=c;if(e.measured!==!0||e.schemaVersion!==ue)return null;let t=e.testExecution;return!t||typeof t!="object"||!me(t.avgTestDurationMs)||!me(t.totalDurationMs)||typeof t.samples!="number"||!Number.isInteger(t.samples)||t.samples<1||typeof t.lastRunId!="string"?null:{measured:!0,schemaVersion:ue,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:"",testExecution:{avgTestDurationMs:t.avgTestDurationMs,totalDurationMs:t.totalDurationMs,samples:t.samples,lastRunId:t.lastRunId,testSet:Qe(t.testSet)}}}var G=class extends y{constructor(){super(Ct)}async doExecute(e){let t=Date.now();e.logger.info("Starting performance baseline tracking");let i=[],r=[],n=await this.collectMeasuredRun(e),s=await e.memory.get(Ge),a=Tt(s),o=this.baselineStatus(s,a);o==="legacy-ignored"?e.logger.info("Ignoring a performance:baseline without the measured stamp (written by <= 3.15.6)"):o==="invalid-ignored"&&e.logger.warn("Ignoring a malformed measured performance:baseline");let l=[],d=!1;n?a?.testExecution.lastRunId===n.runId?e.logger.debug("Latest measured run already in the performance baseline",{runId:n.runId}):(a&&At(a.testExecution.testSet,n.testSet)&&(d=!0,l=this.detectAnomalies(n,a),this.analyzeAnomalies(l,i,r)),await e.memory.set(Ge,this.nextBaseline(n,d?a:null)),await this.appendHistory(e,n)):i.push({type:"performance-unmeasured",severity:"info",domain:"test-execution",title:"Performance Baseline Unmeasured",description:"No recorded test run backs the current testsPassing evidence, so no timing was stored or compared. Run the test suite (test_execute_parallel, or `aqe test execute`) to start tracking. Build and resource figures are not measured by AQE."});let u=this.calculateHealthScore(l);return e.logger.info("Performance baseline tracking complete",{healthScore:u,measured:n!==null,baselineStatus:o,anomaliesDetected:l.length}),this.createResult(Date.now()-t,{itemsAnalyzed:d?2:0,issuesFound:l.length,healthScore:u,trend:l.length>0?"degrading":"stable",domainMetrics:{baselineStatus:o,avgTestDuration:n?`${T(n.avgTestDurationMs)}ms`:"unmeasured",totalTestDuration:n?`${T(n.totalDurationMs)}ms`:"unmeasured",compileDuration:"unmeasured",bundleSize:"unmeasured",peakMemory:"unmeasured",anomalies:l.length}},i,r)}baselineStatus(e,t){return t?"measured":e==null?"none":typeof e=="object"&&e.measured===!0?"invalid-ignored":"legacy-ignored"}async collectMeasuredRun(e){let t=await U(e.memory,"testsPassing");if(!t?.runId)return null;let i=await e.memory.get(`test-run:${t.runId}`,{namespace:"test-execution"});if(!i||typeof i!="object")return null;let{total:r,duration:n}=i;return typeof r!="number"||!Number.isInteger(r)||r<=0||!me(n)?null:{measured:!0,runId:t.runId,measuredAt:t.measuredAt,totalDurationMs:n,testCount:r,avgTestDurationMs:n/r,testSet:Qe({total:r,files:i.testFiles})}}detectAnomalies(e,t){let i=[],r=(n,s,a)=>{if(a<=0)return;let o=s/a;o>Rt&&i.push({metric:n,currentValue:T(s),baselineValue:T(a),deviationPercent:(o-1)*100,severity:o>1.5?"high":"medium"})};return r("avgTestDuration",e.avgTestDurationMs,t.testExecution.avgTestDurationMs),r("totalTestDuration",e.totalDurationMs,t.testExecution.totalDurationMs),i}analyzeAnomalies(e,t,i){for(let r of e)t.push({type:"performance-anomaly-test",severity:r.severity,domain:"test-execution",title:`Performance Anomaly: ${this.formatMetricName(r.metric)}`,description:`${this.formatMetricName(r.metric)} is ${r.deviationPercent.toFixed(1)}% above the measured baseline`,context:{currentValue:r.currentValue,baselineValue:r.baselineValue,deviationPercent:r.deviationPercent.toFixed(1)}});e.length>0&&i.push({priority:e.some(r=>r.severity==="high")?"p1":"p2",domain:"test-execution",action:"Investigate Test Performance Degradation",description:"Test execution times have increased. Review for slow tests or infrastructure issues.",estimatedImpact:"medium",effort:"medium",autoFixable:!1})}formatMetricName(e){return e==="avgTestDuration"?"Average Test Duration":"Total Test Duration"}nextBaseline(e,t){let i=t?.testExecution,r=(n,s)=>n*(1-je)+s*je;return{measured:!0,schemaVersion:ue,updatedAt:new Date().toISOString(),testExecution:{avgTestDurationMs:i?T(r(i.avgTestDurationMs,e.avgTestDurationMs)):e.avgTestDurationMs,totalDurationMs:i?T(r(i.totalDurationMs,e.totalDurationMs)):e.totalDurationMs,samples:i?i.samples+1:1,lastRunId:e.runId,testSet:e.testSet}}}async appendHistory(e,t){let i=await e.memory.get(qe),r=Array.isArray(i)?i:[];for(r.push(t);r.length>Mt;)r.shift();await e.memory.set(qe,r)}calculateHealthScore(e){let t=100;for(let i of e){let r=i.severity==="high"?15:8;t-=r+Math.min(10,i.deviationPercent/10)}return Math.max(0,Math.round(t))}};var Pt={id:"compliance-checker",name:"ADR/DDD Compliance Checker",description:"Verifies compliance with Architecture Decision Records and DDD patterns",intervalMs:1800*1e3,priority:"normal",targetDomains:["quality-assessment"],enabled:!0,timeoutMs:24e4,retryCount:2,retryDelayMs:3e4},q=class extends y{constructor(){super(Pt)}async doExecute(e){let t=Date.now();e.logger.info("Starting compliance checking");let i=[],r=[],n=await this.checkADRCompliance(e),s=await this.checkDDDCompliance(e),a=await this.checkStructuralCompliance(e);this.analyzeADRCompliance(n,i,r),this.analyzeDDDCompliance(s,i,r),this.analyzeStructuralCompliance(a,i,r),await e.memory.set("compliance:adr",n),await e.memory.set("compliance:ddd",s),await e.memory.set("compliance:structural",a),await e.memory.set("compliance:lastCheck",new Date().toISOString());let o=this.calculateHealthScore(n,s,a);return e.logger.info("Compliance checking complete",{healthScore:o,adrChecks:n.length,domainChecks:s.length}),this.createResult(Date.now()-t,{itemsAnalyzed:n.length+s.length+a.length,issuesFound:i.length,healthScore:o,trend:"stable",domainMetrics:{adrCompliance:`${this.calculateAvgScore(n)}%`,dddCompliance:`${this.calculateDDDAvgScore(s)}%`,structuralCompliance:`${this.calculateStructuralScore(a)}%`,totalViolations:n.reduce((l,d)=>l+d.violations.length,0)+s.reduce((l,d)=>l+d.violations.length,0)}},i,r)}async checkADRCompliance(e){if(!e.domains.getDomainAPI("quality-assessment"))throw new Error("Quality-assessment domain not available - cannot check ADR compliance. Ensure the quality-assessment domain is properly initialized before running this worker.");let i=await e.memory.search("compliance:adr:*");if(i.length===0)throw new Error('No ADR compliance data found in memory - cannot check ADR compliance. Ensure ADR compliance data is stored with keys matching "compliance:adr:*" before running this worker.');let r=[],n=[];for(let s of i)try{let a=await e.memory.get(s);a&&r.push(a)}catch{n.push(s)}if(r.length===0)throw new Error(`Found ${i.length} ADR compliance keys but failed to retrieve any data. Failed keys: ${n.join(", ")}. Check memory service connectivity.`);return r}async checkDDDCompliance(e){let t=[];for(let i of M)try{let r=await this.checkDomainCompliance(e,i);t.push(r)}catch(r){e.logger.warn(`Failed to check DDD compliance for ${i}`,{error:r})}return t}async checkDomainCompliance(e,t){let i=e.domains.getDomainHealth(t),r=e.domains.getDomainAPI(t),n=i.status!=="unhealthy",s=r!==void 0,a=s,o=s,l=await e.memory.get(`compliance:ddd:${t}`),d=l?.hasEntities??!1,u=l?.hasEvents??!1,m=l?.hasRepositories??!1,g=l?.namingCompliant??s,p=[];d||p.push("Missing domain entities"),u||p.push("Missing domain events"),m||p.push("Missing repositories"),n||p.push("Domain coordinator not available"),s||p.push("Domain plugin not loaded");let f=[n,s,a,o,d,u,m,g],h=Math.round(f.filter(Boolean).length/f.length*100);return{domain:t,hasCoordinator:n,hasPlugin:s,hasInterfaces:a,hasServices:o,hasEntities:d,hasEvents:u,hasRepositories:m,namingCompliant:g,score:h,violations:p}}async checkStructuralCompliance(e){let t=await e.memory.search("compliance:structural:*");if(t.length===0)throw new Error('No structural compliance data found in memory - cannot check structural compliance. Ensure structural compliance data is stored with keys matching "compliance:structural:*" before running this worker.');let i=[],r=[];for(let n of t)try{let s=await e.memory.get(n);s&&i.push(s)}catch(s){r.push(n),e.logger.warn(`Failed to retrieve structural compliance data: ${n}`,{error:s})}if(i.length===0)throw new Error(`Found ${t.length} structural compliance keys but failed to retrieve any data. Failed keys: ${r.join(", ")}. Check memory service connectivity.`);return i}analyzeADRCompliance(e,t,i){let r=e.filter(s=>s.status==="non-compliant"),n=e.filter(s=>s.status==="partial");for(let s of r)t.push({type:"adr-non-compliance",severity:"high",domain:"quality-assessment",title:`ADR Non-Compliance: ${s.adrId}`,description:`${s.title} is not compliant (score: ${s.score}%)`,context:{adrId:s.adrId,violations:s.violations}});for(let s of n)t.push({type:"adr-partial-compliance",severity:"medium",domain:"quality-assessment",title:`ADR Partial Compliance: ${s.adrId}`,description:`${s.title} is partially compliant (score: ${s.score}%)`,context:{adrId:s.adrId,violations:s.violations}});r.length>0&&i.push({priority:"p1",domain:"quality-assessment",action:"Address ADR Non-Compliance",description:`${r.length} ADRs are not being followed. Review and implement required patterns.`,estimatedImpact:"high",effort:"high",autoFixable:!1})}analyzeDDDCompliance(e,t,i){let r=e.filter(a=>a.score<70),n=e.filter(a=>!a.hasEntities),s=e.filter(a=>!a.hasEvents);r.length>0&&t.push({type:"ddd-low-compliance",severity:"medium",domain:"quality-assessment",title:`${r.length} Domains Have Low DDD Compliance`,description:"Some domains are missing required DDD components",context:{domains:r.map(a=>({domain:a.domain,score:a.score}))}}),n.length>0&&(t.push({type:"ddd-missing-entities",severity:"low",domain:"quality-assessment",title:"Domains Missing Entity Definitions",description:`${n.length} domains lack proper entity definitions`,context:{domains:n.map(a=>a.domain)}}),i.push({priority:"p3",domain:"quality-assessment",action:"Add Domain Entities",description:"Define rich domain entities for domains that currently lack them.",estimatedImpact:"medium",effort:"medium",autoFixable:!1})),s.length>0&&i.push({priority:"p3",domain:"quality-assessment",action:"Implement Domain Events",description:`${s.length} domains are missing domain event definitions.`,estimatedImpact:"medium",effort:"medium",autoFixable:!1})}analyzeStructuralCompliance(e,t,i){let r=e.filter(n=>!n.compliant);for(let n of r)t.push({type:"structural-violation",severity:"medium",domain:"quality-assessment",title:`Structural Violation: ${n.category}`,description:`Rule "${n.rule}" is not being followed: ${n.details}`,context:{category:n.category,rule:n.rule}});r.length>0&&i.push({priority:"p2",domain:"quality-assessment",action:"Fix Structural Violations",description:`${r.length} structural rules are being violated. Review architecture guidelines.`,estimatedImpact:"medium",effort:"medium",autoFixable:!1})}calculateAvgScore(e){return e.length===0?100:Math.round(e.reduce((t,i)=>t+i.score,0)/e.length)}calculateDDDAvgScore(e){return e.length===0?100:Math.round(e.reduce((t,i)=>t+i.score,0)/e.length)}calculateStructuralScore(e){if(e.length===0)return 100;let t=e.filter(i=>i.compliant).length;return Math.round(t/e.length*100)}calculateHealthScore(e,t,i){let r=this.calculateAvgScore(e)*.4,n=this.calculateDDDAvgScore(t)*.4,s=this.calculateStructuralScore(i)*.2;return Math.round(r+n+s)}};J();var Wn={id:"cloud-sync",name:"Cloud Sync",description:"Periodically syncs local learning data to cloud PostgreSQL",intervalMs:parseInt(process.env.AQE_SYNC_INTERVAL||"3600000",10),priority:"low",targetDomains:["learning-optimization"],enabled:process.env.AQE_CLOUD_SYNC_ENABLED==="true",timeoutMs:6e5,retryCount:3,retryDelayMs:6e4};var It={autoStart:!0,enabledWorkers:[],disabledWorkers:[],logLevel:"info",healthCheckIntervalMs:6e4},pe=class{_running=!1;_startedAt;_healthCheckTimer;workerManager;config;_qualityDaemon;unknownDisabledIds=[];constructor(e){this.config={...It,...e,disabledWorkers:(e?.disabledWorkers??Me()).map(t=>t.toLowerCase())},this.workerManager=new X,this.registerWorkers()}get running(){return this._running}get uptime(){return this._startedAt?Math.floor((Date.now()-this._startedAt.getTime())/1e3):0}async start(){if(this._running){console.info("[Daemon] Already running");return}if(console.info("[Daemon] Starting QE Background Workers..."),this.unknownDisabledIds.length>0&&console.warn(`[AQE] WARN AQE_DISABLED_WORKERS: unknown worker id(s) ignored: ${this.unknownDisabledIds.join(", ")}`),this._running=!0,this._startedAt=new Date,this._healthCheckTimer=setInterval(()=>{this.performHealthCheck()},this.config.healthCheckIntervalMs),this._healthCheckTimer.unref?.(),this.config.autoStart){try{await this.workerManager.startAll()}catch(t){throw this._running=!1,this._startedAt=void 0,this._healthCheckTimer&&clearInterval(this._healthCheckTimer),this._healthCheckTimer=void 0,await this.workerManager.stopAll().catch(()=>{}),t}console.info("[Daemon] All workers started")}let e=this.workerManager.list();console.info(`[Daemon] Registered ${e.length} workers:`);for(let t of e)console.info(` - ${t.config.id}: ${t.config.name} (interval: ${t.config.intervalMs}ms)`)}async stop(){if(!this._running){console.info("[Daemon] Not running");return}console.info("[Daemon] Stopping..."),this._healthCheckTimer&&(clearInterval(this._healthCheckTimer),this._healthCheckTimer=void 0),await this.workerManager.stopAll(),this._running=!1,console.info("[Daemon] Stopped")}async restart(){console.info("[Daemon] Restarting..."),await this.stop(),await this.start(),console.info("[Daemon] Restarted")}getStatus(){return{running:this._running,pid:process.pid,uptime:this.uptime,startedAt:this._startedAt,workerManager:this.workerManager.getHealth()}}getWorkerManager(){return this.workerManager}getQualityDaemon(e){return this._qualityDaemon||(this._qualityDaemon=new Te(e)),this._qualityDaemon}async runWorker(e){let t=await this.workerManager.runNow(e);console.info(`[Daemon] Worker ${e} completed:`,{success:t.success,duration:`${t.durationMs}ms`,findings:t.findings.length,healthScore:t.metrics.healthScore})}registerWorkers(){let e=[new W,new F,new $,new L,new _,new H,new O,new B,new G,new q,new ee];for(let i of e)this.config.disabledWorkers.includes(i.config.id)||(this.config.enabledWorkers.length===0||this.config.enabledWorkers.includes(i.config.id))&&this.workerManager.register(i);let t=new Set(e.map(i=>i.config.id));this.unknownDisabledIds=this.config.disabledWorkers.filter(i=>!t.has(i))}performHealthCheck(){let e=this.workerManager.getHealth();e.errorWorkers>0&&console.warn(`[Daemon] Health check: ${e.errorWorkers} workers in error state`),e.healthScore<70&&console.warn(`[Daemon] Health score degraded: ${e.healthScore}%`),this.config.logLevel==="debug"&&console.debug("[Daemon] Health check:",e)}};function Et(c){return new pe(c)}var P;function Zn(c){return P||(P=Et(c)),P}function er(){P?.running&&P.stop().catch(console.error),P=void 0}export{pe as QEDaemon,Et as createDaemon,Zn as getDaemon,er as resetDaemon};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.13");process.exit(0)}
2
- import{a,b}from"./chunk-3QZEGE67.js";import"./chunk-ZAKQLAHT.js";export{a as DAGAttentionScheduler,b as createDAGAttentionScheduler};
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.15");process.exit(0)}
2
+ import{a,b}from"./chunk-IXL5ZHWJ.js";import"./chunk-XH4JMX5O.js";export{a as DAGAttentionScheduler,b as createDAGAttentionScheduler};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.13");process.exit(0)}
2
- import{a,b,c,d}from"./chunk-QDEJ4CI2.js";import"./chunk-VTOBUZL6.js";import"./chunk-ZAKQLAHT.js";export{a as clearDetectionCache,b as detectClaudeFlow,d as getClaudeFlowNotFoundMessage,c as resolveCliPackage};
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.15");process.exit(0)}
2
+ import{a,b,c,d}from"./chunk-UQPA33UK.js";import"./chunk-XWIAZG3C.js";import"./chunk-XH4JMX5O.js";export{a as clearDetectionCache,b as detectClaudeFlow,d as getClaudeFlowNotFoundMessage,c as resolveCliPackage};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.13");process.exit(0)}
2
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n}from"./chunk-H4H2YSFH.js";import"./chunk-ZAKQLAHT.js";export{a as MAX,b as NIL,d as parse,e as stringify,f as v1,g as v1ToV6,h as v3,i as v4,j as v5,k as v6,l as v6ToV1,m as v7,c as validate,n as version};
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.15");process.exit(0)}
2
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n}from"./chunk-QFGYH6HD.js";import"./chunk-XH4JMX5O.js";export{a as MAX,b as NIL,d as parse,e as stringify,f as v1,g as v1ToV6,h as v3,i as v4,j as v5,k as v6,l as v6ToV1,m as v7,c as validate,n as version};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.13");process.exit(0)}
2
- import{a as i}from"./chunk-G77ERMUD.js";import"./chunk-5MDERQH3.js";import{a as r}from"./chunk-NURIILUB.js";import"./chunk-ZAKQLAHT.js";import n from"chalk";var s=class{name="domain";description="Domain operations";cleanupAndExit;ensureInitialized;constructor(o,t){this.cleanupAndExit=o,this.ensureInitialized=t}register(o,t){let e=o.command("domain").description(this.description);e.command("list").description("List all domains").action(async()=>{await this.executeList(t)}),e.command("health <domain>").description("Get domain health").action(async a=>{await this.executeHealth(a,t)})}async executeList(o){if(await this.ensureInitialized())try{console.log(n.blue(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.15");process.exit(0)}
2
+ import{a as i}from"./chunk-GV2QE5TO.js";import"./chunk-L32JNNKL.js";import{a as r}from"./chunk-LJMYRTJ7.js";import"./chunk-XH4JMX5O.js";import n from"chalk";var s=class{name="domain";description="Domain operations";cleanupAndExit;ensureInitialized;constructor(o,t){this.cleanupAndExit=o,this.ensureInitialized=t}register(o,t){let e=o.command("domain").description(this.description);e.command("list").description("List all domains").action(async()=>{await this.executeList(t)}),e.command("health <domain>").description("Get domain health").action(async a=>{await this.executeHealth(a,t)})}async executeList(o){if(await this.ensureInitialized())try{console.log(n.blue(`
3
3
  Domains
4
4
  `));for(let t of r){let e=o.queen.getDomainHealth(t),a=o.queen.getDomainLoad(t);console.log(` ${n.cyan(t)}`),console.log(` Status: ${i(e?.status||"unknown")}`),console.log(` Load: ${a} tasks`),e&&console.log(` Agents: ${e.agents.active}/${e.agents.total}`),console.log("")}}catch(t){console.error(n.red(`
5
5
  Failed to list domains:`),t),await this.cleanupAndExit(1)}}async executeHealth(o,t){if(await this.ensureInitialized())try{let e=t.queen.getDomainHealth(o);if(!e){console.log(n.red(`
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.13");process.exit(0)}
2
- import{a}from"./chunk-SVLQRAMF.js";import"./chunk-ZAKQLAHT.js";export{a as loadCLIDomainPlugins};
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.15");process.exit(0)}
2
+ import{a}from"./chunk-6BRQPHMZ.js";import"./chunk-XH4JMX5O.js";export{a as loadCLIDomainPlugins};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.13");process.exit(0)}
2
- import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h}from"./chunk-CV77DMDQ.js";import"./chunk-UT2VZ33P.js";import"./chunk-GB6HBNH2.js";import"./chunk-UOC3O6RP.js";import"./chunk-NT4DBXSX.js";import"./chunk-WOCGL4QP.js";import"./chunk-ZAKQLAHT.js";export{f as CuriosityBonus,b as DEFAULT_DOMAIN_TRANSFER_CONFIG,c as DecayingBeta,g as DomainTransferEngine,e as ParetoFront,d as PlateauDetector,a as ThompsonSampler,h as createDomainTransferEngine};
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.15");process.exit(0)}
2
+ import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h}from"./chunk-Y2OX6KGN.js";import"./chunk-3HVFIITW.js";import"./chunk-BQ47GQPK.js";import"./chunk-ZWBGYJ7K.js";import"./chunk-UJABDXST.js";import"./chunk-6YVMX2TC.js";import"./chunk-XH4JMX5O.js";export{f as CuriosityBonus,b as DEFAULT_DOMAIN_TRANSFER_CONFIG,c as DecayingBeta,g as DomainTransferEngine,e as ParetoFront,d as PlateauDetector,a as ThompsonSampler,h as createDomainTransferEngine};
@@ -0,0 +1,2 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.15");process.exit(0)}
2
+ import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i,k as j,l as k,m as l,n as m,o as n,p as o,q as p,r as q,s as r,t as s,u as t,v as u,w as v,x as w,y as x,z as y}from"./chunk-OLZH5LRT.js";import"./chunk-JCZCJE6X.js";import"./chunk-VY4U6DPO.js";import"./chunk-LVABQNRF.js";import"./chunk-PFQCV6YS.js";import"./chunk-RBKUU7WF.js";import"./chunk-Q6I4SIUU.js";import"./chunk-UXIY4IAI.js";import"./chunk-KCQNFBBR.js";import"./chunk-C4KLXFJP.js";import"./chunk-ZYJB6FML.js";import"./chunk-TODNOP7C.js";import"./chunk-2ZFLULL4.js";import"./chunk-ERN56H6S.js";import"./chunk-UQPA33UK.js";import"./chunk-HTZSRMHW.js";import"./chunk-YUS6TWAL.js";import"./chunk-AP2W7Z3A.js";import"./chunk-BP5T3OEV.js";import"./chunk-T66PPF4D.js";import"./chunk-337Z52QM.js";import"./chunk-XWIAZG3C.js";import"./chunk-5G4UFTV4.js";import"./chunk-DEKR3CTS.js";import"./chunk-4X3SWKBA.js";import"./chunk-W62OOK7A.js";import"./chunk-GCHYOPRZ.js";import"./chunk-DKX4GNRU.js";import"./chunk-PXATBHWN.js";import"./chunk-6NBRMD25.js";import"./chunk-5I7357KS.js";import"./chunk-QFGYH6HD.js";import"./chunk-LJMYRTJ7.js";import"./chunk-G242G224.js";import"./chunk-3HVFIITW.js";import"./chunk-BQ47GQPK.js";import"./chunk-ZWBGYJ7K.js";import"./chunk-UJABDXST.js";import"./chunk-6YVMX2TC.js";import"./chunk-DURD37JZ.js";import"./chunk-SZAZQZWI.js";import"./chunk-MPFPWJTH.js";import"./chunk-AOKKUB5F.js";import"./chunk-T4GE7MPI.js";import"./chunk-FOOW4JVS.js";import"./chunk-HL2ANKN3.js";import"./chunk-BZULJMGH.js";import"./chunk-XH4JMX5O.js";export{q as ABANDONED_CYCLE_GRACE_MS,x as BUILT_IN_STRATEGIES,e as ConceptGraph,j as DEFAULT_ACTIVATION_CONFIG,d as DEFAULT_CONCEPT_GRAPH_CONFIG,s as DEFAULT_DREAM_CONFIG,a as DEFAULT_DREAM_SCHEDULER_CONFIG,l as DEFAULT_INSIGHT_CONFIG,n as DEFAULT_VALIDATION_THRESHOLDS,t as DreamAlreadyRunningError,u as DreamEngine,b as DreamScheduler,i as HISTORY_TRIM_TARGET_RATIO,m as InsightGenerator,g as MAX_ACTIVATION_HISTORY_ENTRIES,h as MAX_COACTIVATION_ENTRIES,o as RVCOWBranchManager,y as SpeculativeDreamer,k as SpreadingActivation,p as commitDream,f as createConceptGraph,v as createDreamEngine,c as createDreamScheduler,w as default,r as markAbandonedCycles};
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.13");process.exit(0)}
2
- import{g as i,h as a,s as d}from"./chunk-WKGTGOYS.js";import"./chunk-DVGRPK7A.js";import"./chunk-J2ZIFFM6.js";import"./chunk-RF7HWBHN.js";import"./chunk-3Y2ROSCL.js";import"./chunk-ZAKQLAHT.js";async function u(o,s,m,g,f,t={}){try{let e=`${m??""} ${g??""} ${(f??[]).join(" ")}`.trim();if(!e)return;let n=await a(e,t);if(!n||n.length===0)return;let E=Buffer.from(new Float32Array(n).buffer),b={...i,...t},r=d()?.spaceId;if(!r)throw new Error("VECTOR_SPACE_UNVERIFIED: embedder has no runtime provenance");o.prepare(`INSERT OR REPLACE INTO qe_pattern_embeddings (pattern_id, embedding, dimension, model, space_id)
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.15");process.exit(0)}
2
+ import{g as i,h as a,s as d}from"./chunk-6NBRMD25.js";import"./chunk-5I7357KS.js";import"./chunk-SZAZQZWI.js";import"./chunk-MPFPWJTH.js";import"./chunk-HL2ANKN3.js";import"./chunk-XH4JMX5O.js";async function u(o,s,m,g,f,t={}){try{let e=`${m??""} ${g??""} ${(f??[]).join(" ")}`.trim();if(!e)return;let n=await a(e,t);if(!n||n.length===0)return;let E=Buffer.from(new Float32Array(n).buffer),b={...i,...t},r=d()?.spaceId;if(!r)throw new Error("VECTOR_SPACE_UNVERIFIED: embedder has no runtime provenance");o.prepare(`INSERT OR REPLACE INTO qe_pattern_embeddings (pattern_id, embedding, dimension, model, space_id)
3
3
  VALUES (?, ?, ?, ?, ?)`).run(s,E,n.length,b.modelName,r)}catch(e){console.debug("[ensurePatternEmbedding] non-fatal:",e instanceof Error?e.message:String(e))}}export{u as ensurePatternEmbedding};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.13");process.exit(0)}
2
- import{a as S,b,c as f,d as P,e as x,f as L}from"./chunk-ARJW4I2O.js";import{a as T}from"./chunk-F3YS57NF.js";import{a as w}from"./chunk-CCMKSHAT.js";import"./chunk-CE7B5LU7.js";import"./chunk-CT6SAVXQ.js";import"./chunk-UDQSYWVF.js";import"./chunk-YBQH2VOP.js";import"./chunk-TSQC2KKZ.js";import"./chunk-SYV2V3PL.js";import"./chunk-E7CLYGS7.js";import"./chunk-5VMAV6T6.js";import"./chunk-TCBBNUBP.js";import"./chunk-H4GG2NLO.js";import"./chunk-YSZ5OE3Z.js";import"./chunk-SSU73QAX.js";import"./chunk-QPNG5ZN2.js";import"./chunk-PHP5UBT4.js";import{i as R,n as I}from"./chunk-P7A4NKTZ.js";import"./chunk-VRVMIPTM.js";import"./chunk-4OVC4RIL.js";import"./chunk-UTRV7T2N.js";import"./chunk-3Y7TJFHU.js";import"./chunk-7CMTY45A.js";import"./chunk-VTOBUZL6.js";import"./chunk-KDNJ4F3P.js";import"./chunk-JRRXCODW.js";import"./chunk-XNBOGCF3.js";import"./chunk-KV4T4MXK.js";import"./chunk-TWDW32W2.js";import"./chunk-AQSVJNEH.js";import"./chunk-OCAEXYFA.js";import"./chunk-WKGTGOYS.js";import"./chunk-DVGRPK7A.js";import"./chunk-H4H2YSFH.js";import"./chunk-NURIILUB.js";import"./chunk-TOQWL2ZF.js";import"./chunk-UT2VZ33P.js";import"./chunk-GB6HBNH2.js";import"./chunk-UOC3O6RP.js";import"./chunk-NT4DBXSX.js";import"./chunk-WOCGL4QP.js";import"./chunk-W2QWSQVE.js";import"./chunk-J2ZIFFM6.js";import"./chunk-RF7HWBHN.js";import"./chunk-IC3TQEOA.js";import"./chunk-HD7YIFOI.js";import"./chunk-DNDL7SOS.js";import"./chunk-3Y2ROSCL.js";import"./chunk-WO274FRI.js";import"./chunk-ZAKQLAHT.js";import{Command as _}from"commander";import o from"chalk";import*as p from"fs";import*as m from"path";import*as C from"yaml";I();var h=["accessibility-testing","security-testing","performance-testing","chaos-engineering-resilience","contract-testing"],F=["risk-based-testing","test-design-techniques","regression-testing","test-data-management","localization-testing"],B=["quality-metrics","refactoring-patterns","iterative-loop","stream-chain"];function D(e){typeof e=="number"&&Number.isFinite(e)&&e>0&&(process.env.AQE_MAX_BUDGET_USD=String(e),console.log(o.gray(` Budget cap: $${e.toFixed(2)} for this run`)))}function N(e){switch(e){case 3:return h;case 2:return[...h,...F];case 1:return[...h,...F,...B];default:return h}}var v="";function U(e){let t=Math.round(e.completedTasks/e.totalTasks*100),s=k(e.elapsedMs),n=k(e.estimatedRemainingMs),r=j(t,30),u=`${o.cyan("Progress:")} ${r} ${t}% | ${o.green(e.completedTasks)}/${e.totalTasks} tasks | ${o.yellow(e.failedTasks)} failed | ${o.blue(e.activeWorkers)} workers | ${s} elapsed, ~${n} remaining`;v&&process.stdout.write("\r"+" ".repeat(v.length)+"\r"),process.stdout.write(u),v=u}function j(e,t){let s=Math.round(e/100*t),n=t-s;return o.green("=".repeat(s))+o.gray("-".repeat(n))}function k(e){if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;let t=Math.floor(e/6e4),s=Math.round(e%6e4/1e3);return`${t}m ${s}s`}function O(e){let t=[];t.push(""),t.push(o.bold(`Eval Results: ${e.skill}`)+o.dim(` (${e.model})`)),t.push("=".repeat(60));let s=e.passed?o.green("PASSED"):o.red("FAILED");t.push(`Status: ${s}`),t.push(""),t.push(o.bold("Metrics:")),t.push(` Total Tests: ${e.totalTests}`),t.push(` Passed: ${o.green(e.passedTests)}`),t.push(` Failed: ${o.red(e.failedTests)}`),t.push(` Skipped: ${o.yellow(e.skippedTests)}`),t.push(` Pass Rate: ${(e.passRate*100).toFixed(1)}%`),t.push(` Reasoning Avg: ${(e.avgReasoningQuality*100).toFixed(1)}%`),t.push(""),t.push(o.bold("Performance:")),t.push(` Duration: ${k(e.totalDurationMs)}`),t.push(` Workers Used: ${e.workersUsed}`),t.push(` Parallel Speedup: ${o.cyan(e.parallelSpeedup.toFixed(2)+"x")}`),t.push("");let n=e.testResults.filter(r=>!r.passed);if(n.length>0){t.push(o.bold.red("Failed Tests:"));for(let r of n.slice(0,5))t.push(` ${o.red("x")} ${r.testId}`),r.error&&t.push(` ${o.dim(r.error)}`);n.length>5&&t.push(` ... and ${n.length-5} more`),t.push("")}return t.join(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.15");process.exit(0)}
2
+ import{a as S,b,c as f,d as P,e as x,f as L}from"./chunk-PYPS65P7.js";import{a as T}from"./chunk-2LUTPMBO.js";import{a as w}from"./chunk-GQABPCQE.js";import"./chunk-RDMRY7CT.js";import"./chunk-W5ZJG2OU.js";import"./chunk-MIA447GY.js";import"./chunk-QRKTBSZT.js";import"./chunk-RBKUU7WF.js";import"./chunk-Q6I4SIUU.js";import"./chunk-KCQNFBBR.js";import"./chunk-ZYJB6FML.js";import"./chunk-UUBIQR6A.js";import"./chunk-TDQWTSBS.js";import"./chunk-2IIXCEMS.js";import"./chunk-O6EWL5DQ.js";import"./chunk-EKP2SC77.js";import"./chunk-BBRROA3Z.js";import{i as R,n as I}from"./chunk-LTQVUAPH.js";import"./chunk-YUS6TWAL.js";import"./chunk-AP2W7Z3A.js";import"./chunk-BP5T3OEV.js";import"./chunk-T66PPF4D.js";import"./chunk-337Z52QM.js";import"./chunk-XWIAZG3C.js";import"./chunk-5G4UFTV4.js";import"./chunk-DEKR3CTS.js";import"./chunk-4X3SWKBA.js";import"./chunk-W62OOK7A.js";import"./chunk-GCHYOPRZ.js";import"./chunk-DKX4GNRU.js";import"./chunk-PXATBHWN.js";import"./chunk-6NBRMD25.js";import"./chunk-5I7357KS.js";import"./chunk-QFGYH6HD.js";import"./chunk-LJMYRTJ7.js";import"./chunk-G242G224.js";import"./chunk-3HVFIITW.js";import"./chunk-BQ47GQPK.js";import"./chunk-ZWBGYJ7K.js";import"./chunk-UJABDXST.js";import"./chunk-6YVMX2TC.js";import"./chunk-DURD37JZ.js";import"./chunk-SZAZQZWI.js";import"./chunk-MPFPWJTH.js";import"./chunk-AOKKUB5F.js";import"./chunk-T4GE7MPI.js";import"./chunk-FOOW4JVS.js";import"./chunk-HL2ANKN3.js";import"./chunk-BZULJMGH.js";import"./chunk-XH4JMX5O.js";import{Command as _}from"commander";import o from"chalk";import*as p from"fs";import*as m from"path";import*as C from"yaml";I();var h=["accessibility-testing","security-testing","performance-testing","chaos-engineering-resilience","contract-testing"],F=["risk-based-testing","test-design-techniques","regression-testing","test-data-management","localization-testing"],B=["quality-metrics","refactoring-patterns","iterative-loop","stream-chain"];function D(e){typeof e=="number"&&Number.isFinite(e)&&e>0&&(process.env.AQE_MAX_BUDGET_USD=String(e),console.log(o.gray(` Budget cap: $${e.toFixed(2)} for this run`)))}function N(e){switch(e){case 3:return h;case 2:return[...h,...F];case 1:return[...h,...F,...B];default:return h}}var v="";function U(e){let t=Math.round(e.completedTasks/e.totalTasks*100),s=k(e.elapsedMs),n=k(e.estimatedRemainingMs),r=j(t,30),u=`${o.cyan("Progress:")} ${r} ${t}% | ${o.green(e.completedTasks)}/${e.totalTasks} tasks | ${o.yellow(e.failedTasks)} failed | ${o.blue(e.activeWorkers)} workers | ${s} elapsed, ~${n} remaining`;v&&process.stdout.write("\r"+" ".repeat(v.length)+"\r"),process.stdout.write(u),v=u}function j(e,t){let s=Math.round(e/100*t),n=t-s;return o.green("=".repeat(s))+o.gray("-".repeat(n))}function k(e){if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;let t=Math.floor(e/6e4),s=Math.round(e%6e4/1e3);return`${t}m ${s}s`}function O(e){let t=[];t.push(""),t.push(o.bold(`Eval Results: ${e.skill}`)+o.dim(` (${e.model})`)),t.push("=".repeat(60));let s=e.passed?o.green("PASSED"):o.red("FAILED");t.push(`Status: ${s}`),t.push(""),t.push(o.bold("Metrics:")),t.push(` Total Tests: ${e.totalTests}`),t.push(` Passed: ${o.green(e.passedTests)}`),t.push(` Failed: ${o.red(e.failedTests)}`),t.push(` Skipped: ${o.yellow(e.skippedTests)}`),t.push(` Pass Rate: ${(e.passRate*100).toFixed(1)}%`),t.push(` Reasoning Avg: ${(e.avgReasoningQuality*100).toFixed(1)}%`),t.push(""),t.push(o.bold("Performance:")),t.push(` Duration: ${k(e.totalDurationMs)}`),t.push(` Workers Used: ${e.workersUsed}`),t.push(` Parallel Speedup: ${o.cyan(e.parallelSpeedup.toFixed(2)+"x")}`),t.push("");let n=e.testResults.filter(r=>!r.passed);if(n.length>0){t.push(o.bold.red("Failed Tests:"));for(let r of n.slice(0,5))t.push(` ${o.red("x")} ${r.testId}`),r.error&&t.push(` ${o.dim(r.error)}`);n.length>5&&t.push(` ... and ${n.length-5} more`),t.push("")}return t.join(`
3
3
  `)}function Q(e){let t=[];t.push("# Skill Evaluation Report"),t.push(""),t.push(`Generated: ${new Date().toISOString()}`),t.push(""),t.push("## Summary"),t.push(""),t.push("| Skill | Model | Pass Rate | Duration | Speedup | Status |"),t.push("|-------|-------|-----------|----------|---------|--------|");for(let s of e){let n=s.passed?"PASSED":"FAILED";t.push(`| ${s.skill} | ${s.model} | ${(s.passRate*100).toFixed(1)}% | ${k(s.totalDurationMs)} | ${s.parallelSpeedup.toFixed(2)}x | ${n} |`)}t.push(""),t.push("## Detailed Results"),t.push("");for(let s of e){t.push(`### ${s.skill} (${s.model})`),t.push(""),t.push(`- **Total Tests:** ${s.totalTests}`),t.push(`- **Passed:** ${s.passedTests}`),t.push(`- **Failed:** ${s.failedTests}`),t.push(`- **Pass Rate:** ${(s.passRate*100).toFixed(1)}%`),t.push(`- **Avg Reasoning Quality:** ${(s.avgReasoningQuality*100).toFixed(1)}%`),t.push("");let n=s.testResults.filter(r=>!r.passed);if(n.length>0){t.push("**Failed Tests:**"),t.push("");for(let r of n)t.push(`- \`${r.testId}\`: ${r.error||"No error message"}`);t.push("")}}return t.join(`
4
4
  `)}var q=".claude/skills";function V(e){let t=m.join(process.cwd(),q,e,"evals",`${e}.yaml`);if(!p.existsSync(t))return null;try{let s=C.parse(p.readFileSync(t,"utf-8"));return x(s)?"command":"llm"}catch{return null}}function z(e,t){return{skill:e.skill,model:t,totalTests:e.totalTests,passedTests:e.passedTests,failedTests:e.failedTests,skippedTests:0,passRate:e.passRate,testResults:e.testResults.map(s=>G(s)),totalDurationMs:e.totalDurationMs,parallelSpeedup:1,avgReasoningQuality:0,passed:e.passed,workersUsed:1,timestamp:e.timestamp}}function G(e){let t=[];return e.setupFailure&&t.push(e.setupFailure),e.failures.length&&t.push(...e.failures),{testId:e.testId,passed:e.passed,expectedPatterns:[],actualPatterns:[],reasoningQuality:0,executionTimeMs:e.durationMs,category:e.category??"uncategorized",priority:e.priority??"medium",error:t.length?t.join("; "):void 0}}async function $(){let e=await T({sqlite:{dbPath:".agentic-qe/eval-runner.db"},hnsw:{M:16,efConstruction:100,efSearch:50}});await e.initialize();let t=w(e);return{runner:f(t),learner:t,reasoningBank:e}}async function W(e){if(console.log(o.bold(`
5
5
  AQE Parallel Eval Runner`)),console.log(o.dim(`ADR-056 Phase 5: Worker Pool Pattern