agentic-qe 3.15.5 → 3.15.7

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 (584) hide show
  1. package/.claude/skills/qe-court/evals/fixtures/seeded-mutant-delivery/README.md +9 -2
  2. package/.claude/skills/qe-court/evals/qe-court.yaml +3 -2
  3. package/.claude/skills/qe-quality-assessment/schemas/output.json +12 -2
  4. package/.claude/skills/skills-manifest.json +1 -1
  5. package/CHANGELOG.md +262 -0
  6. package/README.md +2 -0
  7. package/assets/skills/qe-court/evals/fixtures/seeded-mutant-delivery/README.md +9 -2
  8. package/assets/skills/qe-court/evals/qe-court.yaml +3 -2
  9. package/assets/skills/qe-quality-assessment/schemas/output.json +12 -2
  10. package/assets/skills/skills-manifest.json +1 -1
  11. package/dist/cli/bundle.js +8 -6
  12. package/dist/cli/chunks/adapter-PEOUNYXJ.js +2 -0
  13. package/dist/cli/chunks/{agent-booster-wasm-CCTTGCQS.js → agent-booster-wasm-OS5G7KMQ.js} +2 -2
  14. package/dist/cli/chunks/{agent-handler-DHYUF3NX.js → agent-handler-PI4I7PME.js} +2 -2
  15. package/dist/cli/chunks/{agent-memory-branch-642W7CYX.js → agent-memory-branch-J7TXHX4U.js} +2 -2
  16. package/dist/cli/chunks/aqe-learning-engine-DHKZI5RX.js +2 -0
  17. package/dist/cli/chunks/{arena-MUCC7UUN.js → arena-FXESDCFR.js} +4 -4
  18. package/dist/cli/chunks/{arena-NW2JVAFY.js → arena-OWUGXKNT.js} +2 -2
  19. package/dist/cli/chunks/{audit-VKQTZJAA.js → audit-EPAWLYIZ.js} +3 -3
  20. package/dist/cli/chunks/base-QZWK3D5P.js +2 -0
  21. package/dist/cli/chunks/{better-sqlite3-7ZUFVWLQ.js → better-sqlite3-IYVR5EQY.js} +2 -2
  22. package/dist/cli/chunks/{brain-handler-7LKAWSBI.js → brain-handler-3W2E6TC6.js} +3 -3
  23. package/dist/cli/chunks/{branch-enumerator-HUNXJKM4.js → branch-enumerator-HU7VACJ4.js} +2 -2
  24. package/dist/cli/chunks/{browser-ZSZEYUDP.js → browser-72XOR6E2.js} +2 -2
  25. package/dist/cli/chunks/browser-workflow-ITPX72RX.js +2 -0
  26. package/dist/cli/chunks/{chunk-PVAE65B4.js → chunk-2423JAA5.js} +1 -1
  27. package/dist/cli/chunks/{chunk-VLOIEVER.js → chunk-24CENUT4.js} +3 -3
  28. package/dist/cli/chunks/chunk-2AYBYXOA.js +4 -0
  29. package/dist/cli/chunks/{chunk-FWYJ6UDX.js → chunk-2E3XWKEU.js} +2 -2
  30. package/dist/cli/chunks/{chunk-L375O3CZ.js → chunk-2RJYA6WK.js} +2 -2
  31. package/dist/cli/chunks/{chunk-SDWMLT7B.js → chunk-2YVJ5OUL.js} +5 -5
  32. package/dist/cli/chunks/{chunk-WN55MNZ2.js → chunk-34JLY3U6.js} +2 -2
  33. package/dist/cli/chunks/{chunk-6ZIDZ4TJ.js → chunk-3JD2USUH.js} +2 -2
  34. package/dist/cli/chunks/{chunk-5BOZCMXZ.js → chunk-3RM46XFP.js} +1 -1
  35. package/dist/cli/chunks/{chunk-UE22ODHN.js → chunk-44DPYNPE.js} +1 -1
  36. package/dist/cli/chunks/{chunk-AUZXRFOX.js → chunk-4DIZ5BT6.js} +2 -2
  37. package/dist/cli/chunks/{chunk-RUSLEOMC.js → chunk-4G2VNW4C.js} +2 -2
  38. package/dist/cli/chunks/{chunk-VML4SG3X.js → chunk-56ZKQYZY.js} +3 -3
  39. package/dist/cli/chunks/{chunk-FHUJCVT3.js → chunk-5KCBX225.js} +2 -2
  40. package/dist/cli/chunks/chunk-5KS7HA37.js +2 -0
  41. package/dist/cli/chunks/{chunk-IJ2EXSMO.js → chunk-5PBRBS7D.js} +2 -2
  42. package/dist/cli/chunks/chunk-5Q22XPTH.js +2 -0
  43. package/dist/cli/chunks/{chunk-PDPEMBFV.js → chunk-634D2ENF.js} +2 -2
  44. package/dist/cli/chunks/{chunk-BYXNHGQC.js → chunk-6AYRAOCA.js} +2 -2
  45. package/dist/cli/chunks/{chunk-ORTBRO7F.js → chunk-6BO3WCK7.js} +2 -2
  46. package/dist/cli/chunks/{chunk-6LG5UEQE.js → chunk-6FEQ73BF.js} +2 -2
  47. package/dist/cli/chunks/{chunk-JYY7AYGA.js → chunk-6JT73S5B.js} +1 -1
  48. package/dist/cli/chunks/{chunk-LNO5IWGH.js → chunk-6OS7HREG.js} +1 -1
  49. package/dist/cli/chunks/{chunk-XNEEYXR2.js → chunk-6PKCQXEW.js} +2 -2
  50. package/dist/cli/chunks/{chunk-KHCALIFP.js → chunk-7EX4DEQR.js} +2 -2
  51. package/dist/cli/chunks/chunk-7UCVYYWL.js +3 -0
  52. package/dist/cli/chunks/chunk-AAA4SHEG.js +2 -0
  53. package/dist/cli/chunks/{chunk-DTJODGCE.js → chunk-AXO7OOOA.js} +2 -2
  54. package/dist/cli/chunks/{chunk-ZT3GUYM5.js → chunk-B7M323VL.js} +2 -2
  55. package/dist/cli/chunks/{chunk-L6SVCNXK.js → chunk-BB7OLQKO.js} +1 -1
  56. package/dist/cli/chunks/{chunk-6UYN5PHA.js → chunk-BTIBXGVQ.js} +4 -4
  57. package/dist/cli/chunks/chunk-BTYKGVJ5.js +2 -0
  58. package/dist/cli/chunks/{chunk-6JFGB2JB.js → chunk-C2CUPJGR.js} +1 -1
  59. package/dist/cli/chunks/{chunk-EAYQCBXL.js → chunk-C2MDBBFF.js} +3 -3
  60. package/dist/cli/chunks/{chunk-3AYYGR6W.js → chunk-CG5DZCOZ.js} +1 -1
  61. package/dist/cli/chunks/chunk-CIFWOMNX.js +2 -0
  62. package/dist/cli/chunks/{chunk-Y2WMPEUP.js → chunk-CWPRU7ZI.js} +2 -2
  63. package/dist/cli/chunks/{chunk-XNHB6TLC.js → chunk-CXTJ47QS.js} +2 -2
  64. package/dist/cli/chunks/{chunk-4PT5KNXL.js → chunk-DCJW2DPL.js} +4 -4
  65. package/dist/cli/chunks/{chunk-VCKDVOPD.js → chunk-DGK6GQMO.js} +2 -2
  66. package/dist/cli/chunks/{chunk-47GEI2LT.js → chunk-DVPGBDBP.js} +3 -3
  67. package/dist/cli/chunks/chunk-EB2PP6X2.js +2 -0
  68. package/dist/cli/chunks/{chunk-CXOXUBYU.js → chunk-ECSLJJOQ.js} +1 -1
  69. package/dist/cli/chunks/{chunk-A2WOQO2N.js → chunk-ED32XJ5R.js} +2 -2
  70. package/dist/cli/chunks/{chunk-35MDATQE.js → chunk-EDU72RTW.js} +1 -1
  71. package/dist/cli/chunks/{chunk-PCCIZFD7.js → chunk-EL75G2A3.js} +1 -1
  72. package/dist/cli/chunks/{chunk-4UXPDV7E.js → chunk-EV2BYY6T.js} +1 -1
  73. package/dist/cli/chunks/{chunk-3YASZPLO.js → chunk-F62EKVVC.js} +2 -2
  74. package/dist/cli/chunks/{chunk-AQN5EDBM.js → chunk-FTTFJ7SJ.js} +1 -1
  75. package/dist/cli/chunks/chunk-FVBFASOD.js +2 -0
  76. package/dist/cli/chunks/{chunk-QXY3IRBW.js → chunk-G762PEFO.js} +26 -26
  77. package/dist/cli/chunks/{chunk-A5J4XJS6.js → chunk-G7YTZTGU.js} +1 -1
  78. package/dist/cli/chunks/{chunk-YINFES3E.js → chunk-GY2SAIXP.js} +2 -2
  79. package/dist/cli/chunks/chunk-H4WHDFB5.js +4 -0
  80. package/dist/cli/chunks/chunk-HLZATDD2.js +2 -0
  81. package/dist/cli/chunks/{chunk-7EZLOC4K.js → chunk-HPG7354V.js} +2 -2
  82. package/dist/cli/chunks/{chunk-HLFDC4SF.js → chunk-HSDOOFV7.js} +1 -1
  83. package/dist/cli/chunks/{chunk-MQGEZA2A.js → chunk-HTWIGQL4.js} +2 -2
  84. package/dist/cli/chunks/{chunk-HBYQYGXP.js → chunk-HXBAQKMH.js} +2 -2
  85. package/dist/cli/chunks/chunk-HZFT3P5B.js +2 -0
  86. package/dist/cli/chunks/{chunk-MS3Z2CP5.js → chunk-I7H4IP7T.js} +2 -2
  87. package/dist/cli/chunks/{chunk-IHFUEPZH.js → chunk-IARSGAG7.js} +2 -2
  88. package/dist/cli/chunks/{chunk-ZTC5FBL6.js → chunk-IC2WSSD5.js} +8 -8
  89. package/dist/cli/chunks/{chunk-GKPRECLL.js → chunk-ICPALF4Q.js} +2 -2
  90. package/dist/cli/chunks/{chunk-FQKEZVN6.js → chunk-IWQQIXHO.js} +2 -2
  91. package/dist/cli/chunks/{chunk-DWZI3IVB.js → chunk-IYQ7XNE5.js} +2 -2
  92. package/dist/cli/chunks/{chunk-ZLBBX24Q.js → chunk-J26GADQE.js} +418 -412
  93. package/dist/cli/chunks/{chunk-NMJVG22Z.js → chunk-J43DV3ME.js} +1 -1
  94. package/dist/cli/chunks/{chunk-EUEHBERE.js → chunk-JFPXCQNP.js} +1 -1
  95. package/dist/cli/chunks/{chunk-3YNP33GB.js → chunk-JK6B3ULP.js} +2 -2
  96. package/dist/cli/chunks/{chunk-FBEXG4HD.js → chunk-JPHDMHFG.js} +2 -2
  97. package/dist/cli/chunks/{chunk-U6OVPMQX.js → chunk-JVYPXW6Y.js} +2 -2
  98. package/dist/cli/chunks/{chunk-X52TMBHU.js → chunk-JY4AIEZ7.js} +1 -1
  99. package/dist/cli/chunks/{chunk-MNQ36MAF.js → chunk-JY4WLN3K.js} +2 -2
  100. package/dist/cli/chunks/{chunk-E4VIVMDL.js → chunk-JYXOFN3E.js} +2 -2
  101. package/dist/cli/chunks/{chunk-CR2JUANW.js → chunk-K7W55B7Q.js} +3 -3
  102. package/dist/cli/chunks/{chunk-WLIYWBQR.js → chunk-KPOPBUUJ.js} +2 -2
  103. package/dist/cli/chunks/{chunk-DXVZBJE4.js → chunk-LDXQRNTT.js} +1 -1
  104. package/dist/cli/chunks/{chunk-W3ZGNNDV.js → chunk-LDZWIV2O.js} +1 -1
  105. package/dist/cli/chunks/{chunk-VRJPH3LG.js → chunk-LGBN7TKC.js} +2 -2
  106. package/dist/cli/chunks/{chunk-RUJLVJDE.js → chunk-LMEU64TR.js} +2 -2
  107. package/dist/cli/chunks/{chunk-JI77KJP7.js → chunk-LP4AS2E4.js} +1 -1
  108. package/dist/cli/chunks/{chunk-QPV3OKX2.js → chunk-LQOVA4YX.js} +2 -2
  109. package/dist/cli/chunks/{chunk-NLDFNAOS.js → chunk-LVEX4GID.js} +2 -2
  110. package/dist/cli/chunks/{chunk-U4TV75AC.js → chunk-M63QB466.js} +2 -2
  111. package/dist/cli/chunks/{chunk-SAPIRK2G.js → chunk-MDC4G323.js} +1 -1
  112. package/dist/cli/chunks/chunk-MHZPC4HJ.js +2 -0
  113. package/dist/cli/chunks/{chunk-WR64BKUE.js → chunk-MJJC6HUK.js} +1 -1
  114. package/dist/cli/chunks/{chunk-Y7GPLOXB.js → chunk-MKFQNCXI.js} +2 -2
  115. package/dist/cli/chunks/{chunk-BZFT4QDQ.js → chunk-MMXG3LL6.js} +2 -2
  116. package/dist/cli/chunks/{chunk-HGBJ2QQ4.js → chunk-MNCF643K.js} +2 -2
  117. package/dist/cli/chunks/{chunk-XIE7OHML.js → chunk-MNZFEIE5.js} +1 -1
  118. package/dist/cli/chunks/{chunk-FE3AIZI6.js → chunk-MQ6OF6DU.js} +1 -1
  119. package/dist/cli/chunks/{chunk-3QD7U3FY.js → chunk-MRHM4COP.js} +2 -2
  120. package/dist/cli/chunks/{chunk-663ZFPUL.js → chunk-N4PMPSJJ.js} +2 -2
  121. package/dist/cli/chunks/{chunk-DL5JENWD.js → chunk-NZQPP533.js} +3 -3
  122. package/dist/cli/chunks/{chunk-4XSCZVON.js → chunk-OA4GR3EZ.js} +2 -2
  123. package/dist/cli/chunks/{chunk-IJOFZBXD.js → chunk-OJEZNLB6.js} +2 -2
  124. package/dist/cli/chunks/{chunk-OU4ZAWCC.js → chunk-ONVALAZN.js} +2 -2
  125. package/dist/cli/chunks/{chunk-A337MD3C.js → chunk-PEKDSJBC.js} +2 -2
  126. package/dist/cli/chunks/{chunk-D3G2NN7F.js → chunk-PG64YV6C.js} +66 -65
  127. package/dist/cli/chunks/{chunk-VYDNLQJN.js → chunk-PQV7E7XH.js} +2 -2
  128. package/dist/cli/chunks/chunk-PTK66HEY.js +2 -0
  129. package/dist/cli/chunks/{chunk-LRASYSGV.js → chunk-PUECC4WI.js} +2 -2
  130. package/dist/cli/chunks/{chunk-3OAQPN2N.js → chunk-PXZKPUW6.js} +2 -2
  131. package/dist/cli/chunks/chunk-PYHYOKYT.js +2 -0
  132. package/dist/cli/chunks/{chunk-WT3JC4A6.js → chunk-PZG3542B.js} +2 -2
  133. package/dist/cli/chunks/{chunk-RMJ7PJOS.js → chunk-Q2T5FXEA.js} +2 -2
  134. package/dist/cli/chunks/chunk-QJE6ZW2X.js +6 -0
  135. package/dist/cli/chunks/{chunk-2XYTS2WY.js → chunk-QNQSM2OG.js} +2 -2
  136. package/dist/cli/chunks/{chunk-EVCFUYYK.js → chunk-QQT6QENQ.js} +9 -9
  137. package/dist/cli/chunks/{chunk-VH3EB6ZG.js → chunk-QVG4ZDXX.js} +3 -3
  138. package/dist/cli/chunks/chunk-QWLTHFZW.js +16 -0
  139. package/dist/cli/chunks/{chunk-GGDKOJVF.js → chunk-RCYLCA7E.js} +10 -6
  140. package/dist/cli/chunks/{chunk-BMWAWZAN.js → chunk-REEIFA6A.js} +2 -2
  141. package/dist/cli/chunks/{chunk-Y2E3IJ53.js → chunk-RNYX4CPI.js} +2 -2
  142. package/dist/cli/chunks/{chunk-BY646JOM.js → chunk-RORZ5O5Z.js} +2 -2
  143. package/dist/cli/chunks/{chunk-JNMUVBAJ.js → chunk-RRPYWBFX.js} +2 -2
  144. package/dist/cli/chunks/{chunk-XQRE2HWM.js → chunk-RXAFLK34.js} +2 -2
  145. package/dist/cli/chunks/{chunk-UXZEVIFX.js → chunk-SQHLC6I5.js} +1 -1
  146. package/dist/cli/chunks/{chunk-DPV33C77.js → chunk-SSP2B2WR.js} +2 -2
  147. package/dist/cli/chunks/chunk-SX2YSHE7.js +115 -0
  148. package/dist/cli/chunks/chunk-T3ZDVU6F.js +5 -0
  149. package/dist/cli/chunks/{chunk-JCC7QEKZ.js → chunk-T6W5APYP.js} +1 -1
  150. package/dist/cli/chunks/{chunk-DEGWCUMY.js → chunk-TU4LIIOP.js} +2 -2
  151. package/dist/cli/chunks/{chunk-CQMHDAJS.js → chunk-UBYCR3O4.js} +2 -2
  152. package/dist/cli/chunks/{chunk-PHP4UJYP.js → chunk-UCLN6AME.js} +1 -1
  153. package/dist/cli/chunks/{chunk-HIUNCO2W.js → chunk-UIYKR2SA.js} +2 -2
  154. package/dist/cli/chunks/{chunk-ONCH5AXU.js → chunk-UUHIEM2M.js} +18 -18
  155. package/dist/cli/chunks/{chunk-CFPR24YK.js → chunk-UY3REQOK.js} +2 -2
  156. package/dist/cli/chunks/{chunk-FNAYDITO.js → chunk-V2SAEMZY.js} +1 -1
  157. package/dist/cli/chunks/{chunk-JANLATHN.js → chunk-V5NGBQAQ.js} +2 -2
  158. package/dist/cli/chunks/{chunk-644DFAGS.js → chunk-VCA6YYII.js} +1 -1
  159. package/dist/cli/chunks/chunk-VJRZFWR5.js +2 -0
  160. package/dist/cli/chunks/{chunk-7BIYJRQJ.js → chunk-VKPKYMCT.js} +2 -2
  161. package/dist/cli/chunks/{chunk-2KWI3MT3.js → chunk-VNW5Q2CX.js} +2 -2
  162. package/dist/cli/chunks/chunk-VUFRTGML.js +3 -0
  163. package/dist/cli/chunks/{chunk-PHAQWAEV.js → chunk-W4X2VTIY.js} +2 -2
  164. package/dist/cli/chunks/{chunk-PURHGLEC.js → chunk-WTLIEBDH.js} +1 -1
  165. package/dist/cli/chunks/{chunk-3SH23PS3.js → chunk-WUV5RZUI.js} +2 -2
  166. package/dist/cli/chunks/{chunk-OGYWWZU7.js → chunk-WXI2STKQ.js} +2 -2
  167. package/dist/cli/chunks/{chunk-OW42F2TX.js → chunk-XEWXYGJI.js} +2 -2
  168. package/dist/cli/chunks/{chunk-DPYDUKVZ.js → chunk-XNSQZ3O7.js} +2 -2
  169. package/dist/cli/chunks/{chunk-B2UHTA4Q.js → chunk-XTJMY3KS.js} +1 -1
  170. package/dist/cli/chunks/{chunk-NF6AFIAX.js → chunk-XXAVQACL.js} +1 -1
  171. package/dist/cli/chunks/{chunk-V7GNUVYI.js → chunk-Y4SAWE45.js} +1 -1
  172. package/dist/cli/chunks/{chunk-WC47GICZ.js → chunk-Y6A46M3B.js} +2 -2
  173. package/dist/cli/chunks/{chunk-3DTEQHFB.js → chunk-YDZJWDR6.js} +3 -3
  174. package/dist/cli/chunks/{chunk-KJ3KBP24.js → chunk-YFOBQSOW.js} +2 -2
  175. package/dist/cli/chunks/{chunk-MB4VFAJC.js → chunk-YK3NOC2R.js} +2 -2
  176. package/dist/cli/chunks/{chunk-GRIPCYW5.js → chunk-YUC7RJGR.js} +1 -1
  177. package/dist/cli/chunks/{chunk-HPLMX62I.js → chunk-Z3VJLWRR.js} +2 -2
  178. package/dist/cli/chunks/{chunk-EOR3RECZ.js → chunk-ZLVQSEZK.js} +2 -2
  179. package/dist/cli/chunks/{chunk-4AZP7ZCW.js → chunk-ZRLNACPY.js} +2 -2
  180. package/dist/cli/chunks/{chunk-OQDC7GCM.js → chunk-ZTMZFF25.js} +2 -2
  181. package/dist/cli/chunks/chunk-ZUMDDMDE.js +3 -0
  182. package/dist/cli/chunks/ci-5HEXJZ2C.js +81 -0
  183. package/dist/cli/chunks/{ci-config-XDDZOOEI.js → ci-config-WU4NPDAM.js} +2 -2
  184. package/dist/cli/chunks/{ci-output-7ZUQI4U6.js → ci-output-BJQVXX5E.js} +2 -2
  185. package/dist/cli/chunks/{circuit-breaker-ALXKCFAL.js → circuit-breaker-3BMGTQCB.js} +2 -2
  186. package/dist/cli/chunks/{claude-flow-setup-RL7K2NI2.js → claude-flow-setup-GVDGJWMU.js} +2 -2
  187. package/dist/cli/chunks/client-S7GNYTZ5.js +2 -0
  188. package/dist/cli/chunks/{cline-installer-2Z2QQKC3.js → cline-installer-V4MRGWVA.js} +2 -2
  189. package/dist/cli/chunks/{code-QSZTDINQ.js → code-A3TGQPEO.js} +3 -3
  190. package/dist/cli/chunks/{code-index-extractor-5CGR5D3Y.js → code-index-extractor-YJQSYWD3.js} +2 -2
  191. package/dist/cli/chunks/{codex-installer-7JLSEDE5.js → codex-installer-7N7UQPAH.js} +2 -2
  192. package/dist/cli/chunks/{completions-U4NBSXEB.js → completions-PPGVYLZS.js} +2 -2
  193. package/dist/cli/chunks/{complexity-analyzer-WYZD2YSY.js → complexity-analyzer-XZTFLYV5.js} +2 -2
  194. package/dist/cli/chunks/{continuedev-installer-UPXINJFT.js → continuedev-installer-Z5I57RAH.js} +2 -2
  195. package/dist/cli/chunks/{copilot-installer-WIVYQRIF.js → copilot-installer-F5YZ6BHB.js} +2 -2
  196. package/dist/cli/chunks/core-handlers-CUEPOQIO.js +2 -0
  197. package/dist/cli/chunks/{cost-tracker-RIN4JDDM.js → cost-tracker-GO33ZQAP.js} +2 -2
  198. package/dist/cli/chunks/coverage-GSHKLY74.js +49 -0
  199. package/dist/cli/chunks/cross-domain-router-CXN5QFEV.js +2 -0
  200. package/dist/cli/chunks/{cursor-installer-POM7NGCC.js → cursor-installer-JJ7IVJZB.js} +2 -2
  201. package/dist/cli/chunks/daemon-3DQCKRYO.js +10 -0
  202. package/dist/cli/chunks/{daemon-HFGKQ6LB.js → daemon-IRL7QRNE.js} +5 -5
  203. package/dist/cli/chunks/{dag-attention-scheduler-HJXM7Q5P.js → dag-attention-scheduler-ORXSUHPA.js} +2 -2
  204. package/dist/cli/chunks/{detect-XKQGLZYN.js → detect-RHU62KRI.js} +2 -2
  205. package/dist/cli/chunks/{dist-node-SSKB53QL.js → dist-node-3VKV4Z6C.js} +2 -2
  206. package/dist/cli/chunks/{domain-handler-6BNDHATU.js → domain-handler-SFIML4FK.js} +2 -2
  207. package/dist/cli/chunks/{domain-plugins-DOX54YE3.js → domain-plugins-CJ4FA3OC.js} +2 -2
  208. package/dist/cli/chunks/{domain-transfer-FW4ZX3Z7.js → domain-transfer-BCRKPCAA.js} +2 -2
  209. package/dist/cli/chunks/dream-5AUNJW24.js +2 -0
  210. package/dist/cli/chunks/embed-and-insert-pattern-VL3HFLPV.js +3 -0
  211. package/dist/cli/chunks/{eval-K7E4XXBS.js → eval-GGKRI4P5.js} +2 -2
  212. package/dist/cli/chunks/experience-capture-middleware-F72TIRQY.js +40 -0
  213. package/dist/cli/chunks/{fast-paths-5JXXTYAG.js → fast-paths-7KOOF3MA.js} +2 -2
  214. package/dist/cli/chunks/{feature-flags-2CR3CO23.js → feature-flags-FNHBTHBH.js} +2 -2
  215. package/dist/cli/chunks/{feature-flags-RB72LHOJ.js → feature-flags-IOZEWWFU.js} +2 -2
  216. package/dist/cli/chunks/file-discovery-AYWF357I.js +2 -0
  217. package/dist/cli/chunks/{fleet-SDU7QEOA.js → fleet-QX5KXTRC.js} +3 -3
  218. package/dist/cli/chunks/{gnn-wrapper-AWCFODUV.js → gnn-wrapper-OH2DOQP7.js} +2 -2
  219. package/dist/cli/chunks/{heartbeat-handler-A4PJ3NFP.js → heartbeat-handler-W67NXTNE.js} +4 -4
  220. package/dist/cli/chunks/heartbeat-scheduler-7ZIDVXIP.js +2 -0
  221. package/dist/cli/chunks/hnsw-adapter-P77OC7FM.js +2 -0
  222. package/dist/cli/chunks/hnsw-index-3LBOTQAW.js +2 -0
  223. package/dist/cli/chunks/{hnsw-legacy-bridge-KRS7SSFM.js → hnsw-legacy-bridge-6MLLOGOE.js} +2 -2
  224. package/dist/cli/chunks/{hnswlib-node-OGGCPKPO.js → hnswlib-node-4UDISJ3G.js} +2 -2
  225. package/dist/cli/chunks/{hooks-XNRNMUBW.js → hooks-NOQJWQ4P.js} +43 -43
  226. package/dist/cli/chunks/hybrid-backend-LOM54PDD.js +2 -0
  227. package/dist/cli/chunks/{hypergraph-engine-X35LTXYT.js → hypergraph-engine-2OD3APVP.js} +2 -2
  228. package/dist/cli/chunks/{hypergraph-handler-M6THKAG6.js → hypergraph-handler-5AZGMBUM.js} +3 -3
  229. package/dist/cli/chunks/impact-analyzer-QSDJVBPS.js +2 -0
  230. package/dist/cli/chunks/init-guard-SMGJ45PW.js +2 -0
  231. package/dist/cli/chunks/init-handler-5T4MP2NM.js +88 -0
  232. package/dist/cli/chunks/init-wizard-MK2325JJ.js +2 -0
  233. package/dist/cli/chunks/kernel-2NJQQ2KT.js +2 -0
  234. package/dist/cli/chunks/{kilocode-installer-TEPR2ZJD.js → kilocode-installer-RLZYLVQJ.js} +2 -2
  235. package/dist/cli/chunks/{kiro-installer-RUKHGDEE.js → kiro-installer-LFZOC7VD.js} +2 -2
  236. package/dist/cli/chunks/knowledge-graph-SDISHO62.js +2 -0
  237. package/dist/cli/chunks/learning-XRPGLUWR.js +122 -0
  238. package/dist/cli/chunks/{llm-router-7GECMDCP.js → llm-router-OMK5HYPH.js} +4 -4
  239. package/dist/cli/chunks/llm-router-service-YTCMRBAN.js +2 -0
  240. package/dist/cli/chunks/{load-NTJ4Y4ZR.js → load-XADC7KCU.js} +2 -2
  241. package/dist/cli/chunks/load-test-RPKHLBCC.js +2 -0
  242. package/dist/cli/chunks/{mcp-4335GTTG.js → mcp-PIBKSSVU.js} +2 -2
  243. package/dist/cli/chunks/{memory-HYC4M4XS.js → memory-AP7EZERS.js} +5 -5
  244. package/dist/cli/chunks/memory-backend-BZXFO4JZ.js +2 -0
  245. package/dist/cli/chunks/memory-handlers-MOFDNB6E.js +2 -0
  246. package/dist/cli/chunks/{multi-model-executor-T7FYKM6T.js → multi-model-executor-7JJ2FZ33.js} +2 -2
  247. package/dist/cli/chunks/{opencode-installer-3USXVT5M.js → opencode-installer-ZZZ6EBYJ.js} +2 -2
  248. package/dist/cli/chunks/orchestrator-2H2YKSGJ.js +452 -0
  249. package/dist/cli/chunks/pattern-null-store-4PRPIOR6.js +2 -0
  250. package/dist/cli/chunks/{pattern-usage-recorder-CMZLPX2K.js → pattern-usage-recorder-7MJJWC2Z.js} +2 -2
  251. package/dist/cli/chunks/{pipeline-BTRZOVSL.js → pipeline-LIE5BWQY.js} +2 -2
  252. package/dist/cli/chunks/{platform-2MCRKC25.js → platform-SMYUNLGX.js} +2 -2
  253. package/dist/cli/chunks/plugin-LJDIXQNT.js +27 -0
  254. package/dist/cli/chunks/{prime-radiant-advanced-wasm-TXFEMBP6.js → prime-radiant-advanced-wasm-RIDNE5D2.js} +2 -2
  255. package/dist/cli/chunks/project-root-NBIQF63D.js +2 -0
  256. package/dist/cli/chunks/protocol-executor-BRPGIYWQ.js +2 -0
  257. package/dist/cli/chunks/{protocol-handler-DZ26OYVZ.js → protocol-handler-YVM66DLI.js} +2 -2
  258. package/dist/cli/chunks/{prove-QWONEJWX.js → prove-ZBDT52GD.js} +2 -2
  259. package/dist/cli/chunks/qe-reasoning-bank-GDZACWKW.js +2 -0
  260. package/dist/cli/chunks/{quality-WFH54FY7.js → quality-DUKXGDDO.js} +2 -2
  261. package/dist/cli/chunks/{quality-gate-ONJB7XU7.js → quality-gate-SM3RXF4V.js} +3 -3
  262. package/dist/cli/chunks/queen-coordinator-LDKLBPD5.js +2 -0
  263. package/dist/cli/chunks/real-embeddings-4QLQZDB5.js +2 -0
  264. package/dist/cli/chunks/{ref-validation-HW5Y55ZC.js → ref-validation-M3EO32YQ.js} +2 -2
  265. package/dist/cli/chunks/{roocode-installer-5OABDNZT.js → roocode-installer-S6Q5OLV5.js} +2 -2
  266. package/dist/cli/chunks/router-H5YSIRH2.js +2 -0
  267. package/dist/cli/chunks/routing-feedback-5R36TJDH.js +2 -0
  268. package/dist/cli/chunks/{routing-handler-CVHVOQTC.js → routing-handler-55FMUACP.js} +2 -2
  269. package/dist/cli/chunks/{ruvector-commands-KKDKFGIQ.js → ruvector-commands-QATKAAPK.js} +2 -2
  270. package/dist/cli/chunks/rvf-dual-writer-TT2DBQQQ.js +2 -0
  271. package/dist/cli/chunks/rvf-migration-adapter-BCLFJKSK.js +2 -0
  272. package/dist/cli/chunks/rvf-migration-coordinator-RFXFU6JD.js +2 -0
  273. package/dist/cli/chunks/rvf-native-adapter-UXI66OQJ.js +2 -0
  274. package/dist/cli/chunks/{rvf-store-integrity-UGUXKIFX.js → rvf-store-integrity-PKDVXQAW.js} +2 -2
  275. package/dist/cli/chunks/safe-db-MSTD2GDH.js +2 -0
  276. package/dist/cli/chunks/schedule-KST6KIFD.js +2 -0
  277. package/dist/cli/chunks/scheduler-FTQS6YK3.js +2 -0
  278. package/dist/cli/chunks/security-CMRB6WA3.js +18 -0
  279. package/dist/cli/chunks/shared-rvf-adapter-YHLLNFHF.js +2 -0
  280. package/dist/cli/chunks/{shared-rvf-dual-writer-ZSHYG5IA.js → shared-rvf-dual-writer-4BGDVPQ7.js} +2 -2
  281. package/dist/cli/chunks/sqlite-persistence-ZX5QFDMR.js +2 -0
  282. package/dist/cli/chunks/{standalone-memory-MHZEEYMK.js → standalone-memory-LUHKQAGM.js} +2 -2
  283. package/dist/cli/chunks/{status-handler-JKXPJ22K.js → status-handler-S6S5PNR7.js} +2 -2
  284. package/dist/cli/chunks/{structural-health-J4RKCYWF.js → structural-health-PQ7NZAJ4.js} +2 -2
  285. package/dist/cli/chunks/{sync-PDPORHVN.js → sync-Q6KRQXU6.js} +2 -2
  286. package/dist/cli/chunks/sync-S744AEJC.js +2 -0
  287. package/dist/cli/chunks/{task-handler-VERADM44.js → task-handler-GAMGEHUW.js} +2 -2
  288. package/dist/cli/chunks/{task-handlers-4RUCWUR2.js → task-handlers-6CRDEELN.js} +3 -3
  289. package/dist/cli/chunks/{test-DMBJFQNL.js → test-FNH67DBK.js} +12 -12
  290. package/dist/cli/chunks/{test-scheduling-LUPTVGCD.js → test-scheduling-NZA5SHK6.js} +3 -3
  291. package/dist/cli/chunks/token-bootstrap-CXKG55JD.js +2 -0
  292. package/dist/cli/chunks/{token-usage-VOA34IKM.js → token-usage-M7WWEDJX.js} +2 -2
  293. package/dist/cli/chunks/{transformers-GU4TYAN5.js → transformers-2IFMCK6A.js} +2 -2
  294. package/dist/cli/chunks/{tree-sitter-wasm-parser-MZPXAH7C.js → tree-sitter-wasm-parser-NMNA6RJC.js} +2 -2
  295. package/dist/cli/chunks/{types-K4FLXR2K.js → types-N7FWTOLD.js} +2 -2
  296. package/dist/cli/chunks/unified-memory-2Z2F446J.js +2 -0
  297. package/dist/cli/chunks/unified-memory-hnsw-A4EWYPJQ.js +2 -0
  298. package/dist/cli/chunks/unified-persistence-Z6N6JZFA.js +2 -0
  299. package/dist/cli/chunks/{upgrade-M3ATDRMK.js → upgrade-KDB5RGL7.js} +2 -2
  300. package/dist/cli/chunks/{validate-AAP773B3.js → validate-KMUV5FUA.js} +2 -2
  301. package/dist/cli/chunks/{validate-swarm-7RGAZX5F.js → validate-swarm-ANZWRCJU.js} +2 -2
  302. package/dist/cli/chunks/visual-security-GXYZV7KR.js +2 -0
  303. package/dist/cli/chunks/{web-tree-sitter-GQMRHGGI.js → web-tree-sitter-SXXC4NMS.js} +2 -2
  304. package/dist/cli/chunks/{windsurf-installer-HG6HF2GF.js → windsurf-installer-2LWSKMBU.js} +2 -2
  305. package/dist/cli/chunks/witness-chain-52PEIEGK.js +2 -0
  306. package/dist/cli/chunks/{witness-chain-WKU3ZIBQ.js → witness-chain-JJMSJFZP.js} +2 -2
  307. package/dist/cli/chunks/witness-chain-repair-OX7VFW6T.js +2 -0
  308. package/dist/cli/chunks/{witness-chain-verifier-Q2KW3QEQ.js → witness-chain-verifier-QLSMXHAZ.js} +2 -2
  309. package/dist/cli/chunks/witness-key-manager-3DS4L7LE.js +2 -0
  310. package/dist/cli/chunks/{workflow-CX6SHFBW.js → workflow-ARWAMHD3.js} +28 -28
  311. package/dist/cli/chunks/workflow-orchestrator-DORMQMG7.js +2 -0
  312. package/dist/cli/chunks/wrappers-J6KGTUSJ.js +2 -0
  313. package/dist/cli/commands/ci.js +47 -25
  314. package/dist/cli/commands/coverage.d.ts +1 -28
  315. package/dist/cli/commands/coverage.js +63 -134
  316. package/dist/cli/commands/daemon.js +7 -1
  317. package/dist/cli/commands/hooks-handlers/stats-hooks.d.ts +15 -0
  318. package/dist/cli/commands/hooks-handlers/stats-hooks.js +54 -2
  319. package/dist/cli/commands/learning.js +50 -9
  320. package/dist/cli/commands/security.d.ts +16 -0
  321. package/dist/cli/commands/security.js +76 -9
  322. package/dist/cli/commands/test.js +6 -7
  323. package/dist/cli/commands/workflow.js +9 -5
  324. package/dist/cli/handlers/init-guard.d.ts +33 -0
  325. package/dist/cli/handlers/init-guard.js +66 -0
  326. package/dist/cli/handlers/init-handler.d.ts +3 -0
  327. package/dist/cli/handlers/init-handler.js +64 -54
  328. package/dist/cli/handlers/interfaces.js +5 -1
  329. package/dist/cli/index.js +11 -0
  330. package/dist/cli/scheduler/persistent-scheduler.d.ts +6 -2
  331. package/dist/cli/scheduler/persistent-scheduler.js +107 -41
  332. package/dist/cli/utils/ci-output.d.ts +13 -1
  333. package/dist/cli/utils/ci-output.js +21 -2
  334. package/dist/cli/utils/coverage-data.d.ts +3 -0
  335. package/dist/cli/utils/coverage-data.js +14 -39
  336. package/dist/cli/utils/coverage-verdict.d.ts +130 -0
  337. package/dist/cli/utils/coverage-verdict.js +193 -0
  338. package/dist/cli/utils/file-discovery.js +5 -0
  339. package/dist/coordination/deterministic-actions.js +24 -13
  340. package/dist/coordination/handlers/code-intelligence-handlers.d.ts +8 -0
  341. package/dist/coordination/handlers/code-intelligence-handlers.js +39 -0
  342. package/dist/coordination/handlers/coverage-handlers.js +34 -6
  343. package/dist/coordination/handlers/coverage-runner.d.ts +22 -0
  344. package/dist/coordination/handlers/coverage-runner.js +105 -10
  345. package/dist/coordination/handlers/coverage-target.d.ts +1 -0
  346. package/dist/coordination/handlers/coverage-target.js +4 -1
  347. package/dist/coordination/handlers/handler-types.d.ts +9 -0
  348. package/dist/coordination/handlers/handler-utils.d.ts +14 -1
  349. package/dist/coordination/handlers/handler-utils.js +46 -22
  350. package/dist/coordination/handlers/quality-handlers.js +108 -18
  351. package/dist/coordination/handlers/security-handlers.js +22 -6
  352. package/dist/coordination/handlers/test-execution-handlers.js +4 -1
  353. package/dist/coordination/protocols/defect-investigation.d.ts +2 -1
  354. package/dist/coordination/protocols/defect-investigation.js +12 -3
  355. package/dist/coordination/protocols/quality-gate.js +10 -6
  356. package/dist/coordination/protocols/security-audit.js +11 -0
  357. package/dist/coordination/result-saver.d.ts +31 -0
  358. package/dist/coordination/result-saver.js +146 -46
  359. package/dist/coordination/task-executor.d.ts +7 -0
  360. package/dist/coordination/task-executor.js +32 -3
  361. package/dist/domains/code-intelligence/plugin.js +4 -0
  362. package/dist/domains/code-intelligence/services/metric-collector/index.js +9 -2
  363. package/dist/domains/code-intelligence/services/metric-collector/interfaces.d.ts +21 -0
  364. package/dist/domains/code-intelligence/services/metric-collector/interfaces.js +25 -0
  365. package/dist/domains/code-intelligence/services/metric-collector/loc-counter.d.ts +12 -0
  366. package/dist/domains/code-intelligence/services/metric-collector/loc-counter.js +69 -3
  367. package/dist/domains/code-intelligence/services/metric-collector/test-counter.js +4 -1
  368. package/dist/domains/coverage-analysis/collected-metrics.d.ts +35 -0
  369. package/dist/domains/coverage-analysis/collected-metrics.js +42 -0
  370. package/dist/domains/coverage-analysis/coordinator.js +18 -6
  371. package/dist/domains/coverage-analysis/interfaces.d.ts +44 -0
  372. package/dist/domains/coverage-analysis/interfaces.js +6 -1
  373. package/dist/domains/coverage-analysis/services/coverage-analyzer.js +61 -34
  374. package/dist/domains/coverage-analysis/services/gap-detector.js +7 -2
  375. package/dist/domains/defect-intelligence/plugin.js +4 -0
  376. package/dist/domains/defect-intelligence/services/defect-predictor.js +13 -8
  377. package/dist/domains/learning-optimization/coordinator.js +4 -0
  378. package/dist/domains/learning-optimization/plugin.js +4 -0
  379. package/dist/domains/quality-assessment/coordinator-rl-integration.d.ts +14 -0
  380. package/dist/domains/quality-assessment/coordinator-rl-integration.js +54 -16
  381. package/dist/domains/quality-assessment/coordinator.js +10 -6
  382. package/dist/domains/quality-assessment/coverage-report-event.d.ts +32 -8
  383. package/dist/domains/quality-assessment/coverage-report-event.js +28 -6
  384. package/dist/domains/quality-assessment/index.d.ts +1 -1
  385. package/dist/domains/quality-assessment/interfaces.d.ts +50 -0
  386. package/dist/domains/quality-assessment/quality-evidence.d.ts +49 -3
  387. package/dist/domains/quality-assessment/quality-evidence.js +62 -0
  388. package/dist/domains/quality-assessment/services/quality-analyzer.d.ts +23 -2
  389. package/dist/domains/quality-assessment/services/quality-analyzer.js +197 -112
  390. package/dist/domains/quality-assessment/services/quality-gate.js +12 -3
  391. package/dist/domains/security-compliance/dependency-advisory-engine.d.ts +52 -0
  392. package/dist/domains/security-compliance/dependency-advisory-engine.js +113 -0
  393. package/dist/domains/security-compliance/interfaces.d.ts +30 -0
  394. package/dist/domains/security-compliance/plugin.d.ts +7 -1
  395. package/dist/domains/security-compliance/plugin.js +19 -0
  396. package/dist/domains/security-compliance/services/scanners/dast-scanner.js +22 -16
  397. package/dist/domains/security-compliance/services/scanners/dependency-resolver.d.ts +71 -0
  398. package/dist/domains/security-compliance/services/scanners/dependency-resolver.js +232 -0
  399. package/dist/domains/security-compliance/services/scanners/dependency-scanner.d.ts +21 -6
  400. package/dist/domains/security-compliance/services/scanners/dependency-scanner.js +142 -64
  401. package/dist/domains/security-compliance/services/scanners/lockfile-versions.d.ts +43 -0
  402. package/dist/domains/security-compliance/services/scanners/lockfile-versions.js +248 -0
  403. package/dist/domains/security-compliance/services/scanners/scanner-types.d.ts +30 -2
  404. package/dist/domains/security-compliance/services/security-auditor.d.ts +19 -6
  405. package/dist/domains/security-compliance/services/security-auditor.js +133 -92
  406. package/dist/domains/test-execution/interfaces.d.ts +10 -6
  407. package/dist/domains/test-execution/plugin.js +4 -0
  408. package/dist/domains/test-execution/services/retry-handler.js +17 -6
  409. package/dist/domains/test-execution/services/test-executor.d.ts +1 -0
  410. package/dist/domains/test-execution/services/test-executor.js +239 -109
  411. package/dist/domains/test-generation/coordinator.js +4 -0
  412. package/dist/domains/test-generation/plugin.js +4 -0
  413. package/dist/feedback/coverage-learner.js +4 -1
  414. package/dist/feedback/coverage-session-provenance.d.ts +29 -0
  415. package/dist/feedback/coverage-session-provenance.js +39 -0
  416. package/dist/init/orchestrator.js +2 -0
  417. package/dist/init/phases/09-assets.d.ts +4 -0
  418. package/dist/init/phases/09-assets.js +35 -0
  419. package/dist/init/retired-assets.d.ts +86 -0
  420. package/dist/init/retired-assets.js +230 -0
  421. package/dist/init/skills-installer.d.ts +2 -0
  422. package/dist/init/skills-installer.js +4 -0
  423. package/dist/init/types.d.ts +3 -0
  424. package/dist/integrations/ruvector/rvf-native-adapter.d.ts +2 -0
  425. package/dist/integrations/ruvector/rvf-native-adapter.js +5 -0
  426. package/dist/integrations/ruvector/server-client.js +4 -12
  427. package/dist/kernel/project-root.d.ts +17 -0
  428. package/dist/kernel/project-root.js +54 -2
  429. package/dist/kernel/shared-dirs.d.ts +66 -0
  430. package/dist/kernel/shared-dirs.js +180 -0
  431. package/dist/learning/daily-log.js +2 -1
  432. package/dist/learning/experience-capture-middleware.d.ts +22 -0
  433. package/dist/learning/experience-capture-middleware.js +35 -0
  434. package/dist/learning/learnable-result.d.ts +16 -0
  435. package/dist/learning/learnable-result.js +24 -0
  436. package/dist/learning/pattern-mutation-error.d.ts +8 -0
  437. package/dist/learning/pattern-mutation-error.js +12 -0
  438. package/dist/learning/qe-reasoning-bank.d.ts +10 -0
  439. package/dist/learning/qe-reasoning-bank.js +50 -1
  440. package/dist/learning/rvf-reconcile.d.ts +39 -0
  441. package/dist/learning/rvf-reconcile.js +40 -0
  442. package/dist/learning/sqlite-persistence.d.ts +14 -0
  443. package/dist/learning/sqlite-persistence.js +36 -0
  444. package/dist/mcp/bundle.js +908 -896
  445. package/dist/mcp/handlers/domain-handler-configs.d.ts +35 -1
  446. package/dist/mcp/handlers/domain-handler-configs.js +42 -4
  447. package/dist/mcp/handlers/handler-factory.js +40 -14
  448. package/dist/mcp/protocol-server.js +29 -3
  449. package/dist/mcp/tool-cache-scope.d.ts +31 -0
  450. package/dist/mcp/tool-cache-scope.js +71 -0
  451. package/dist/mcp/tools/code-intelligence/analyze.js +5 -3
  452. package/dist/mcp/types.d.ts +10 -0
  453. package/dist/optimization/session-cache.d.ts +19 -1
  454. package/dist/optimization/session-cache.js +36 -2
  455. package/dist/plugins/cache.js +2 -1
  456. package/dist/plugins/sources/github.js +2 -1
  457. package/dist/plugins/sources/npm.js +2 -1
  458. package/dist/shared/aqe-managed-dirs.d.ts +24 -0
  459. package/dist/shared/aqe-managed-dirs.js +56 -0
  460. package/dist/shared/events/domain-events.d.ts +18 -3
  461. package/dist/shared/events/domain-events.js +4 -0
  462. package/dist/shared/http/http-client.d.ts +6 -0
  463. package/dist/shared/http/http-client.js +13 -15
  464. package/dist/shared/io/file-reader.d.ts +26 -0
  465. package/dist/shared/io/file-reader.js +111 -17
  466. package/dist/shared/llm/providers/response-deadline.d.ts +7 -2
  467. package/dist/shared/llm/providers/response-deadline.js +17 -5
  468. package/dist/shared/metrics/code-metrics.d.ts +24 -0
  469. package/dist/shared/metrics/code-metrics.js +93 -6
  470. package/dist/shared/metrics/index.d.ts +1 -1
  471. package/dist/shared/security/index.d.ts +2 -2
  472. package/dist/shared/security/index.js +1 -1
  473. package/dist/shared/security/osv-client.d.ts +79 -132
  474. package/dist/shared/security/osv-client.js +344 -167
  475. package/dist/shared/security/osv-lookup.d.ts +124 -0
  476. package/dist/shared/security/osv-lookup.js +246 -0
  477. package/dist/shared/security/osv-types.d.ts +119 -0
  478. package/dist/shared/security/osv-types.js +6 -0
  479. package/dist/workers/interfaces.d.ts +15 -2
  480. package/dist/workers/namespaced-keys.d.ts +16 -0
  481. package/dist/workers/namespaced-keys.js +24 -0
  482. package/dist/workers/quality-daemon/coverage-delta.d.ts +4 -3
  483. package/dist/workers/quality-daemon/coverage-delta.js +13 -6
  484. package/dist/workers/quality-daemon/index.js +6 -5
  485. package/dist/workers/quality-daemon/notification-service.js +3 -3
  486. package/dist/workers/quality-daemon/persistent-memory.d.ts +3 -3
  487. package/dist/workers/quality-daemon/persistent-memory.js +4 -4
  488. package/dist/workers/worker-manager.js +10 -3
  489. package/dist/workers/workers/coverage-tracker.js +69 -33
  490. package/dist/workers/workers/defect-predictor.d.ts +25 -8
  491. package/dist/workers/workers/defect-predictor.js +223 -216
  492. package/dist/workers/workers/performance-baseline.d.ts +24 -9
  493. package/dist/workers/workers/performance-baseline.js +187 -230
  494. package/dist/workers/workers/quality-gate.d.ts +11 -9
  495. package/dist/workers/workers/quality-gate.js +125 -267
  496. package/dist/workers/workers/regression-monitor.d.ts +18 -1
  497. package/dist/workers/workers/regression-monitor.js +276 -117
  498. package/dist/workers/workers/security-scan-records.d.ts +111 -0
  499. package/dist/workers/workers/security-scan-records.js +128 -0
  500. package/dist/workers/workers/security-scan.d.ts +25 -7
  501. package/dist/workers/workers/security-scan.js +187 -164
  502. package/package.json +2 -2
  503. package/dist/cli/chunks/adapter-EGIPTX5H.js +0 -2
  504. package/dist/cli/chunks/aqe-learning-engine-WP4GCBDT.js +0 -2
  505. package/dist/cli/chunks/base-6ORFD62I.js +0 -2
  506. package/dist/cli/chunks/browser-workflow-PIXGERWP.js +0 -2
  507. package/dist/cli/chunks/chunk-2WFTZSRT.js +0 -2
  508. package/dist/cli/chunks/chunk-7YB2KELI.js +0 -5
  509. package/dist/cli/chunks/chunk-BBL6YXD3.js +0 -2
  510. package/dist/cli/chunks/chunk-BJ5P4IV2.js +0 -2
  511. package/dist/cli/chunks/chunk-BO4PKNYP.js +0 -102
  512. package/dist/cli/chunks/chunk-DFPL5N3Q.js +0 -16
  513. package/dist/cli/chunks/chunk-DLY4YEN3.js +0 -2
  514. package/dist/cli/chunks/chunk-ERGWWI4Y.js +0 -3
  515. package/dist/cli/chunks/chunk-GTSOFCMQ.js +0 -2
  516. package/dist/cli/chunks/chunk-KZVJW2SD.js +0 -2
  517. package/dist/cli/chunks/chunk-L336HFFE.js +0 -2
  518. package/dist/cli/chunks/chunk-N2TJNIHA.js +0 -2
  519. package/dist/cli/chunks/chunk-RCXMUEZN.js +0 -3
  520. package/dist/cli/chunks/chunk-SEZLYRCS.js +0 -2
  521. package/dist/cli/chunks/chunk-TDLKXLJC.js +0 -4
  522. package/dist/cli/chunks/chunk-WOZIXXY5.js +0 -7
  523. package/dist/cli/chunks/ci-KP4GZKJ7.js +0 -81
  524. package/dist/cli/chunks/client-C3KHVRM6.js +0 -2
  525. package/dist/cli/chunks/core-handlers-KSQM6Q6S.js +0 -2
  526. package/dist/cli/chunks/coverage-SPFVHRRU.js +0 -43
  527. package/dist/cli/chunks/coverage-target-GSRBNHXE.js +0 -2
  528. package/dist/cli/chunks/cross-domain-router-CTGNOVCF.js +0 -2
  529. package/dist/cli/chunks/daemon-M5TD5Y6T.js +0 -10
  530. package/dist/cli/chunks/dream-MIK2E4UL.js +0 -2
  531. package/dist/cli/chunks/embed-and-insert-pattern-QST77T2B.js +0 -3
  532. package/dist/cli/chunks/experience-capture-middleware-X66IYSRV.js +0 -40
  533. package/dist/cli/chunks/file-discovery-3NHRUQQB.js +0 -2
  534. package/dist/cli/chunks/heartbeat-scheduler-OCKRACUW.js +0 -2
  535. package/dist/cli/chunks/hnsw-adapter-X67XG73C.js +0 -2
  536. package/dist/cli/chunks/hnsw-index-I7KCQBQR.js +0 -2
  537. package/dist/cli/chunks/hybrid-backend-FOUHTKAK.js +0 -2
  538. package/dist/cli/chunks/impact-analyzer-GXYVX46O.js +0 -2
  539. package/dist/cli/chunks/init-handler-2AXMXHYF.js +0 -86
  540. package/dist/cli/chunks/init-wizard-C2MRX2QG.js +0 -2
  541. package/dist/cli/chunks/kernel-Q2IUDIDC.js +0 -2
  542. package/dist/cli/chunks/knowledge-graph-E2Z6K5EE.js +0 -2
  543. package/dist/cli/chunks/learning-BEA26RNA.js +0 -122
  544. package/dist/cli/chunks/llm-router-service-YATYFEDD.js +0 -2
  545. package/dist/cli/chunks/load-test-LV77JXWA.js +0 -2
  546. package/dist/cli/chunks/memory-backend-XME3X3QX.js +0 -2
  547. package/dist/cli/chunks/memory-handlers-VG47X5DX.js +0 -2
  548. package/dist/cli/chunks/orchestrator-VHUXUYIM.js +0 -452
  549. package/dist/cli/chunks/pattern-null-store-TAXMLENP.js +0 -2
  550. package/dist/cli/chunks/plugin-2VAYWAO3.js +0 -27
  551. package/dist/cli/chunks/project-root-CFFPBGPX.js +0 -2
  552. package/dist/cli/chunks/protocol-executor-ML76QAVQ.js +0 -2
  553. package/dist/cli/chunks/qe-reasoning-bank-LUZH6RYV.js +0 -2
  554. package/dist/cli/chunks/queen-coordinator-EWXNIXB6.js +0 -2
  555. package/dist/cli/chunks/real-embeddings-GZV4VKK4.js +0 -2
  556. package/dist/cli/chunks/router-MXOBVEBF.js +0 -2
  557. package/dist/cli/chunks/routing-feedback-T6CCRUEK.js +0 -2
  558. package/dist/cli/chunks/rvf-dual-writer-WHXVT3V3.js +0 -2
  559. package/dist/cli/chunks/rvf-migration-adapter-JFPWIRCG.js +0 -2
  560. package/dist/cli/chunks/rvf-migration-coordinator-D4KUBNRZ.js +0 -2
  561. package/dist/cli/chunks/rvf-native-adapter-KOXR7TJL.js +0 -2
  562. package/dist/cli/chunks/safe-db-CI6IPSIN.js +0 -2
  563. package/dist/cli/chunks/schedule-X4HW6TVJ.js +0 -2
  564. package/dist/cli/chunks/scheduler-KCNJ2ON3.js +0 -2
  565. package/dist/cli/chunks/security-7723AZZ4.js +0 -13
  566. package/dist/cli/chunks/shared-rvf-adapter-KEQ5CLNI.js +0 -2
  567. package/dist/cli/chunks/sqlite-persistence-PGHU6VUR.js +0 -2
  568. package/dist/cli/chunks/sync-EFWXMA2H.js +0 -2
  569. package/dist/cli/chunks/token-bootstrap-S346YBVO.js +0 -2
  570. package/dist/cli/chunks/unified-memory-6CK3TUNQ.js +0 -2
  571. package/dist/cli/chunks/unified-memory-hnsw-A7BWBGYN.js +0 -2
  572. package/dist/cli/chunks/unified-persistence-GEPMDBQZ.js +0 -2
  573. package/dist/cli/chunks/visual-security-L4J7LQWT.js +0 -2
  574. package/dist/cli/chunks/witness-chain-CDUMX623.js +0 -2
  575. package/dist/cli/chunks/witness-chain-repair-WNYH6O4L.js +0 -2
  576. package/dist/cli/chunks/witness-key-manager-NQ5DAAC4.js +0 -2
  577. package/dist/cli/chunks/workflow-orchestrator-USJDWVDR.js +0 -2
  578. package/dist/cli/chunks/wrappers-CZDI6Z3X.js +0 -2
  579. /package/.claude/skills/qe-court/evals/fixtures/seeded-mutant-delivery/{budget.test.ts → budget-tests.ts.fixture} +0 -0
  580. /package/.claude/skills/qe-court/evals/fixtures/seeded-mutant-delivery/{budget.ts → budget.ts.fixture} +0 -0
  581. /package/.claude/skills/testability-scoring/resources/templates/{testability-scoring.spec.template.js → testability-scoring-spec.template.js} +0 -0
  582. /package/assets/skills/qe-court/evals/fixtures/seeded-mutant-delivery/{budget.test.ts → budget-tests.ts.fixture} +0 -0
  583. /package/assets/skills/qe-court/evals/fixtures/seeded-mutant-delivery/{budget.ts → budget.ts.fixture} +0 -0
  584. /package/assets/skills/testability-scoring/resources/templates/{testability-scoring.spec.template.js → testability-scoring-spec.template.js} +0 -0
@@ -0,0 +1,4 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.7");process.exit(0)}
2
+ import{b as L,d as B}from"./chunk-5Q22XPTH.js";import*as a from"fs";import*as v from"path";import{createRequire as K}from"node:module";var Z=K(import.meta.url),b=Z("semver"),F="3.15.7",y=t=>typeof t=="string"&&b.valid(t)===t.split("+")[0],E=t=>b.validRange(t)!==null,x=(t,e)=>b.satisfies(t,e),C=(t,e)=>b.compare(t,e),N=(t,e)=>C(e,t)||t.localeCompare(e);B();var R=class{cacheDir;keepVersions;constructor(e={}){this.cacheDir=e.cacheDir??L("plugins"),this.keepVersions=e.keepVersions??2}has(e,n){let s=this.versionDir(e,n);return a.existsSync(s)&&a.existsSync(v.join(s,"qe-plugin.json"))}get(e,n){if(!this.has(e,n))return;let s=this.versionDir(e,n),i=a.readFileSync(v.join(s,"qe-plugin.json"),"utf-8"),r=JSON.parse(i),l=a.statSync(s);return{manifest:r,path:s,cachedAt:l.birthtime.toISOString()}}store(e,n){let s=this.versionDir(e.name,e.version);if(a.existsSync(s))return s;a.mkdirSync(s,{recursive:!0});try{this.copyDir(n,s),a.writeFileSync(v.join(s,"qe-plugin.json"),JSON.stringify(e,null,2))}catch(i){throw a.rmSync(s,{recursive:!0,force:!0}),i}return this.pruneOldVersions(e.name),s}remove(e,n){let s=this.versionDir(e,n);return a.existsSync(s)?(a.rmSync(s,{recursive:!0,force:!0}),!0):!1}listVersions(e){let n=v.join(this.cacheDir,e);if(!a.existsSync(n))return[];let s=[],i=a.readdirSync(n);for(let r of i){let l=v.join(n,r),d=v.join(l,"qe-plugin.json");if(a.existsSync(d))try{let p=a.readFileSync(d,"utf-8"),m=JSON.parse(p);if(!y(m.version)){console.warn(`[PluginCache] Skipping cached plugin ${e}@${r}: invalid version ${JSON.stringify(m.version)}`);continue}let c=a.statSync(l);s.push({manifest:m,path:l,cachedAt:c.birthtime.toISOString()})}catch{}}return s}listAll(){if(!a.existsSync(this.cacheDir))return[];let e=[],n=a.readdirSync(this.cacheDir);for(let s of n){let i=this.listVersions(s);i.length>0&&(i.sort((r,l)=>N(r.manifest.version,l.manifest.version)),e.push(i[0]))}return e}listCandidates(){return a.existsSync(this.cacheDir)?a.readdirSync(this.cacheDir).flatMap(e=>this.listVersions(e)):[]}versionDir(e,n){return v.join(this.cacheDir,e,n)}pruneOldVersions(e){let n=this.listVersions(e);if(n.length<=this.keepVersions)return;n.sort((i,r)=>i.cachedAt.localeCompare(r.cachedAt));let s=n.slice(0,n.length-this.keepVersions);for(let i of s)a.rmSync(i.path,{recursive:!0,force:!0})}copyDir(e,n){if(!a.existsSync(e))return;let s=a.readdirSync(e,{withFileTypes:!0});for(let i of s){let r=v.join(e,i.name),l=v.join(n,i.name);if(i.isDirectory()){if(i.name===".git"||i.name==="node_modules")continue;a.mkdirSync(l,{recursive:!0}),this.copyDir(r,l)}else a.copyFileSync(r,l)}}};var ee=/^[a-z][a-z0-9-]*$/,se=["aqe-core-","agentic-qe-core-"],G=64,T=500;function k(t){let e=[],n=[];if(!t||typeof t!="object")return{valid:!1,errors:["Manifest must be a non-null object"],warnings:[]};let s=t;if(!s.name||typeof s.name!="string"?e.push("name is required and must be a string"):ne(s.name,e,n),!s.version||typeof s.version!="string"?e.push("version is required and must be a string"):y(s.version)||e.push(`version "${s.version}" is not valid semver (expected: major.minor.patch)`),!s.description||typeof s.description!="string"?e.push("description is required and must be a string"):s.description.length>T&&n.push(`description exceeds ${T} characters`),(!s.author||typeof s.author!="string")&&e.push("author is required and must be a string"),!Array.isArray(s.domains)||s.domains.length===0)e.push("domains is required and must be a non-empty array");else for(let i of s.domains)if(typeof i!="string"){e.push("Each domain must be a string");break}if(!s.entryPoint||typeof s.entryPoint!="string"?e.push("entryPoint is required and must be a string"):te(s.entryPoint,e),s.dependencies!==void 0)if(typeof s.dependencies!="object"||s.dependencies===null||Array.isArray(s.dependencies))e.push("dependencies must be an object mapping plugin names to semver ranges");else for(let[i,r]of Object.entries(s.dependencies))typeof r!="string"?e.push(`Dependency "${i}" must have a string version range`):E(r)||e.push(`Dependency "${i}" has an invalid semver range`);if(s.hooks!==void 0)if(typeof s.hooks!="object"||s.hooks===null||Array.isArray(s.hooks))e.push("hooks must be an object mapping event names to handler paths");else for(let[,i]of Object.entries(s.hooks)){if(typeof i!="string"){e.push("Hook handler paths must be strings");break}i.includes("..")&&e.push(`Hook handler path "${i}" must not contain ".." (path traversal)`)}if(s.minAqeVersion!==void 0&&(typeof s.minAqeVersion!="string"||!y(s.minAqeVersion))&&e.push("minAqeVersion must be valid semver"),s.permissions!==void 0){if(!Array.isArray(s.permissions))e.push("permissions must be an array of strings");else for(let i of s.permissions)if(typeof i!="string"){e.push("Each permission must be a string");break}}return{valid:e.length===0,errors:e,warnings:n}}function U(t){let e=typeof t=="string"?JSON.parse(t):t,n=k(e);if(!n.valid)throw new Error(`Invalid plugin manifest:
3
+ - ${n.errors.join(`
4
+ - `)}`);return e}function ne(t,e,n){t.length>G&&e.push(`name must be ${G} characters or fewer`),ee.test(t)||e.push("name must be lowercase alphanumeric with hyphens, starting with a letter"),/[^\x00-\x7F]/.test(t)&&e.push("name must contain only ASCII characters");for(let s of se)t.startsWith(s)&&e.push(`name cannot start with reserved prefix "${s}"`);["plugin","test","tool"].includes(t)&&n.push(`name "${t}" is very generic \u2014 consider a more descriptive name`)}function te(t,e){t.includes("..")&&e.push('entryPoint must not contain ".." (path traversal)'),(t.startsWith("/")||t.startsWith("\\"))&&e.push("entryPoint must be a relative path"),!t.endsWith(".js")&&!t.endsWith(".ts")&&!t.endsWith(".mjs")&&e.push("entryPoint must end in .js, .ts, or .mjs")}var I=class{constructor(e=F){this.aqeVersion=e}aqeVersion;resolve(e,n){let s=new Map,i=new Map;for(let o of e){let u=s.get(o.name)??[];s.set(o.name,u);let f=this.validateVersions(o);f?i.set(o.name,[...i.get(o.name)??[],f]):u.push(o)}for(let o of s.values())o.sort((u,f)=>N(u.version,f.version));let r=new Map,l=[],d=o=>({ordered:o.map((u,f)=>({manifest:u,order:f})),missing:r,errors:l,selectedVersions:Object.fromEntries(o.map(u=>[u.name,u.version])),aqeVersion:this.aqeVersion}),p=[...n??s.keys()].sort(),m=new Set(p),c=new Map,_=0,h=!1,X=()=>{for(let o of c.values())for(let[u,f]of Object.entries(o.dependencies??{})){let g=c.get(u);if(!(g?[g]:s.get(u)??[]).some(M=>x(M.version,f)))return!1}return!0},A,z=()=>{let o=new Set,u=new Set,f=(g,P)=>{if(u.has(g))return[...P.slice(P.indexOf(g)),g];if(!o.has(g)){u.add(g);for(let M of Object.keys(c.get(g)?.dependencies??{})){let Q=f(M,[...P,g]);if(Q)return Q}u.delete(g),o.add(g)}};for(let g of c.keys()){let P=f(g,[]);if(P)return P}},j=()=>{let o=new Set(p);for(let f of c.values())for(let g of Object.keys(f.dependencies??{}))o.add(g);let u=[...o].sort().find(f=>!c.has(f));if(!u){let f=z();return f?(A=f,!1):!0}m.add(u);for(let f of s.get(u)??[]){if(++_>1e4)return h=!0,!1;if(c.set(u,f),X()&&j())return!0;if(c.delete(u),h)return!1}return!1};if(!j()){if(A&&!h)throw new Error(`Dependency cycle detected: ${A.join(" -> ")}`);for(let o of m)s.get(o)?.length||l.push(...i.get(o)??[]);for(let[o,u]of s){let f=[...new Set(u.flatMap(g=>Object.keys(g.dependencies??{})))].filter(g=>!s.has(g));f.length&&r.set(o,f)}return l.push({code:h?"RESOLUTION_LIMIT":r.size?"MISSING_DEPENDENCY":"UNSATISFIED_DEPENDENCY_RANGE",plugin:p.join(", "),message:h?"Plugin dependency search exceeded 10000 candidates":"No cached plugin selection satisfies all dependency ranges"}),d([])}let O=[],q=new Set,w=new Set,$=(o,u)=>{if(q.has(o))return;if(w.has(o))throw new Error(`Dependency cycle detected: ${[...u.slice(u.indexOf(o)),o].join(" -> ")}`);w.add(o);let f=c.get(o);for(let g of Object.keys(f.dependencies??{}))$(g,[...u,o]);w.delete(o),q.add(o),O.push(f)};for(let o of[...c.keys()].sort())$(o,[]);return d(O)}resolveAvailable(e){let n=[],s=this.resolve(e,[]),i=[],r=new Map;for(let l of[...new Set(e.map(d=>d.name))].sort())try{let d=this.resolve(e,[...n,l]);if(d.errors.length){i.push(...d.errors.map(p=>({...p,plugin:l})));for(let[p,m]of d.missing)r.set(p,m);continue}n.push(l),s=d}catch(d){i.push({code:"DEPENDENCY_CYCLE",plugin:l,message:d instanceof Error?d.message:String(d)})}return{...s,errors:i,missing:r}}canLoad(e,n){let s=Object.entries(e.dependencies??{}).filter(([i,r])=>{let l=n instanceof Set?void 0:n.get(i);return!l||!E(r)||!x(l,r)}).map(([i])=>i);return{canLoad:!this.validateVersions(e)&&s.length===0,missingDeps:s}}validateVersions(e){if(!y(e.version))return{code:"INVALID_PLUGIN_VERSION",plugin:e.name,message:"Invalid plugin version"};for(let n of Object.values(e.dependencies??{}))if(!E(n))return{code:"INVALID_DEPENDENCY_RANGE",plugin:e.name,message:"Invalid dependency range"};if(e.minAqeVersion&&(!y(e.minAqeVersion)||!y(this.aqeVersion)||C(this.aqeVersion,e.minAqeVersion)<0))return{code:"AQE_VERSION_INCOMPATIBLE",plugin:e.name,message:`Requires AQE ${e.minAqeVersion}; running ${this.aqeVersion}`}}};var ie=["aqe-core-","agentic-qe-core-","agentic-qe-internal-"],Y=new Set(["aqe","agentic-qe","ruflo","claude-flow"]),re=["..","~","/etc/","/proc/","/dev/","node_modules/"];function W(t){let e=[];return oe(t.name,e),ae(t.entryPoint,e),ce(t.hooks,e),ue(t.permissions,e),{safe:e.length===0,violations:e}}function oe(t,e){/[^\x20-\x7E]/.test(t)&&e.push(`Plugin name "${t}" contains non-ASCII characters`),Y.has(t.toLowerCase())&&e.push(`Plugin name "${t}" is a reserved name`);for(let s of ie)t.toLowerCase().startsWith(s)&&e.push(`Plugin name "${t}" uses reserved prefix "${s}"`);let n=t.toLowerCase().replace(/[0o]/g,"o").replace(/[1il]/g,"l").replace(/[-_]/g,"");Y.has(n)&&e.push(`Plugin name "${t}" is visually similar to a reserved name`)}function ae(t,e){H(t,"entryPoint",e),(t.startsWith("/")||t.startsWith("\\"))&&e.push("entryPoint must be a relative path, not absolute")}function ce(t,e){if(t)for(let[n,s]of Object.entries(t))H(s,`hook[${n}]`,e)}function H(t,e,n){for(let s of re)t.includes(s)&&n.push(`${e} contains dangerous path pattern "${s}"`);t.includes("\0")&&n.push(`${e} contains null byte (path injection attempt)`)}function ue(t,e){if(!t)return;let n=["fs:write-root","net:arbitrary","exec:shell"];for(let s of t)n.includes(s)&&e.push(`Plugin requests dangerous permission: ${s}`)}import*as S from"fs";import*as V from"path";var D=class{type="local";async resolve(e){let n=V.resolve(e),s=V.join(n,"qe-plugin.json");if(!S.existsSync(s))throw new Error(`No qe-plugin.json found at ${s}`);let i=S.readFileSync(s,"utf-8");return U(i)}async getPluginPath(e){let n=V.resolve(e);if(!S.existsSync(n))throw new Error(`Plugin directory does not exist: ${n}`);return n}};var J=class{cache;resolver;sources=new Map;constructor(e={}){this.cache=e.cache??new R,this.resolver=new I;let n=new D;if(this.sources.set("local",n),e.sources)for(let s of e.sources)this.sources.set(s.type,s)}async install(e,n="local"){if(process.env.AQE_PLUGINS_DISABLED==="true")return{success:!1,errors:["Plugin loading is disabled (AQE_PLUGINS_DISABLED=true)"],securityViolations:[]};let s=[],i=this.sources.get(n);if(!i)return{success:!1,errors:[`Unknown source type: ${n}. Available: ${[...this.sources.keys()].join(", ")}`],securityViolations:[]};let r;try{r=await i.resolve(e)}catch(c){return{success:!1,errors:[`Failed to resolve plugin: ${c instanceof Error?c.message:String(c)}`],securityViolations:[]}}let l=k(r);if(!l.valid)return{success:!1,manifest:r,errors:l.errors,securityViolations:[]};let d=W(r);if(!d.safe)return{success:!1,manifest:r,errors:["Plugin failed security checks"],securityViolations:d.violations};try{let c=this.cache.listCandidates().map(h=>h.manifest).filter(h=>h.name!==r.name),_=this.resolver.resolve([...c,r],[r.name]);if(_.errors.length)return{success:!1,manifest:r,errors:_.errors.map(h=>`${h.code}: ${h.message}`),securityViolations:[]}}catch(c){return{success:!1,manifest:r,errors:[c instanceof Error?c.message:String(c)],securityViolations:[]}}if(this.cache.has(r.name,r.version)){let c=this.cache.get(r.name,r.version);return{success:!0,manifest:r,cachePath:c.path,errors:[],securityViolations:[]}}let p;try{p=await i.getPluginPath(e)}catch(c){return{success:!1,manifest:r,errors:[`Failed to get plugin path: ${c instanceof Error?c.message:String(c)}`],securityViolations:[]}}let m=this.cache.store(r,p);return{success:!0,manifest:r,cachePath:m,errors:s,securityViolations:[]}}remove(e,n){if(n)return this.cache.remove(e,n);let s=this.cache.listVersions(e),i=!1;for(let r of s)this.cache.remove(e,r.manifest.version)&&(i=!0);return i}list(){return this.cache.listAll().map(n=>({name:n.manifest.name,version:n.manifest.version,description:n.manifest.description,domains:n.manifest.domains,source:"cached",cachePath:n.path}))}resolveLoadOrder(){let e=this.cache.listCandidates();return this.resolver.resolveAvailable(e.map(n=>n.manifest))}registerSource(e){this.sources.set(e.type,e)}};export{U as a,R as b,J as c};
@@ -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.7");process.exit(0)}
2
+ import{h as g}from"./chunk-G762PEFO.js";import{i as h}from"./chunk-FTTFJ7SJ.js";import{c as p,d}from"./chunk-CG5DZCOZ.js";import{b as m,e as f}from"./chunk-LVEX4GID.js";f();var I={maxDepth:5,riskWeights:{directImpact:.4,transitiveImpact:.2,testCoverage:.2,criticalPath:.15,dependencyCount:.05},testPatterns:["**/*.test.ts","**/*.test.tsx","**/*.spec.ts","**/*.spec.tsx","**/test_*.py","**/*_test.py","**/*_test.go"],criticalPaths:["**/auth/**","**/security/**","**/payment/**","**/api/**","**/core/**"],namespace:"code-intelligence:impact"},u=class{constructor(e,t,i={}){this.memory=e;this.config={...I,...i},this.knowledgeGraph=t||new g(e)}memory;config;knowledgeGraph;async analyzeImpact(e){try{let{changedFiles:t,depth:i=this.config.maxDepth,includeTests:r=!0}=e;if(t.length===0)return p({directImpact:[],transitiveImpact:[],impactedTests:[],riskLevel:"info",recommendations:[]});let n=await this.analyzeDirectImpact(t),l=await this.analyzeTransitiveImpact(t,n,i),s=[];if(r){let a=await this.getImpactedTests(t);a.success&&(s=a.value)}let c={directImpact:n,transitiveImpact:l,impactedTests:s,riskLevel:"info",recommendations:[]};return c.riskLevel=this.calculateRiskLevel(c),c.recommendations=this.getRecommendations(c),await this.storeAnalysis(t,c),p(c)}catch(t){return d(m(t))}}async getImpactedTests(e){try{let t=new Set;for(let i of e){if(this.isTestFile(i)){t.add(i);continue}let r=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:3});if(r.success)for(let s of r.value.nodes)this.isTestFile(s.path)&&t.add(s.path);let n=this.getBaseName(i),l=[`${n}.test`,`${n}.spec`,`test_${n}`,`${n}_test`];for(let s of l){let c=await this.memory.search(`code-intelligence:kg:node:*${s}*`,10,{namespace:"code-intelligence:kg"});for(let a of c){let o=await this.memory.get(a,{namespace:"code-intelligence:kg"});o?.properties?.path&&this.isTestFile(o.properties.path)&&t.add(o.properties.path)}}}return p(Array.from(t))}catch(t){return d(m(t))}}calculateRiskLevel(e){let t=this.config.riskWeights,i=0,r=Math.min(1,e.directImpact.length/10);i+=r*t.directImpact;let n=Math.min(1,e.transitiveImpact.length/20);i+=n*t.transitiveImpact;let l=e.impactedTests.length>0?Math.max(0,1-e.impactedTests.length/(e.directImpact.length||1)):1;i+=l*t.testCoverage;let s=this.countCriticalFiles([...e.directImpact.map(o=>o.file),...e.transitiveImpact.map(o=>o.file)]),c=Math.min(1,s/5);i+=c*t.criticalPath;let a=this.calculateAverageRiskScore([...e.directImpact,...e.transitiveImpact]);return i+=a*t.dependencyCount,i>=.8?"critical":i>=.6?"high":i>=.4?"medium":i>=.2?"low":"info"}getRecommendations(e){let t=[];(e.riskLevel==="critical"||e.riskLevel==="high")&&t.push("This change has significant impact - consider peer review before merging"),e.impactedTests.length===0&&e.directImpact.length>0?t.push("No tests found for impacted files - add test coverage"):e.impactedTests.length<e.directImpact.length/2&&t.push("Test coverage appears low for impacted files"),e.impactedTests.length>0&&(e.impactedTests.length<=10?t.push(`Run these ${e.impactedTests.length} tests: ${e.impactedTests.slice(0,3).join(", ")}${e.impactedTests.length>3?"...":""}`):t.push(`Run all ${e.impactedTests.length} impacted tests before deployment`));let i=[...e.directImpact,...e.transitiveImpact].filter(n=>this.isCriticalPath(n.file));i.length>0&&t.push(`${i.length} critical path files affected - extra scrutiny recommended`),e.transitiveImpact.length>10&&t.push("Large transitive impact - consider breaking down into smaller changes");let r=[...e.directImpact,...e.transitiveImpact].filter(n=>n.riskScore>=.7);return r.length>0&&t.push(`${r.length} high-risk files impacted: ${r.slice(0,2).map(n=>this.getFileName(n.file)).join(", ")}`),t}async analyzeDirectImpact(e){let t=[];for(let i of e){let r=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:1});if(r.success){let{nodes:n,edges:l}=r.value;for(let s of n){if(s.path===i)continue;let c=l.find(o=>o.target===s.id||o.source===s.id),a=this.calculateFileRiskScore(s.path,s.inDegree,s.outDegree);t.push({file:s.path,reason:`Directly ${c?.type||"depends on"} ${this.getFileName(i)}`,distance:1,riskScore:a})}}}return this.deduplicateImpact(t)}async analyzeTransitiveImpact(e,t,i){let r=[],n=new Set([...e,...t.map(s=>s.file)]),l=t.map(s=>({file:s.file,distance:1}));for(;l.length>0;){let s=l.shift();if(s.distance>=i)continue;let c=await this.knowledgeGraph.mapDependencies({files:[s.file],direction:"incoming",depth:1});if(c.success)for(let a of c.value.nodes){if(n.has(a.path)||a.path===s.file)continue;n.add(a.path);let o=this.calculateFileRiskScore(a.path,a.inDegree,a.outDegree,s.distance+1);r.push({file:a.path,reason:`Transitively depends via ${this.getFileName(s.file)}`,distance:s.distance+1,riskScore:o}),l.push({file:a.path,distance:s.distance+1})}}return this.deduplicateImpact(r)}calculateFileRiskScore(e,t,i,r=1){let n=0;return n+=Math.min(.3,t/20),n+=Math.min(.2,i/30),this.isCriticalPath(e)&&(n+=.3),this.isEntryPoint(e)&&(n+=.2),n=n*Math.pow(.8,r-1),Math.min(1,Math.max(0,n))}calculateAverageRiskScore(e){return e.length===0?0:e.reduce((i,r)=>i+r.riskScore,0)/e.length}countCriticalFiles(e){return e.filter(t=>this.isCriticalPath(t)).length}isTestFile(e){return[/\.test\.[tj]sx?$/,/\.spec\.[tj]sx?$/,/_test\.[tj]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/].some(i=>i.test(e))}isCriticalPath(e){return this.config.criticalPaths.map(i=>i.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*")).some(i=>new RegExp(i).test(e))}isEntryPoint(e){return[/\/index\.[tj]sx?$/,/\/main\.[tj]sx?$/,/\/app\.[tj]sx?$/,/^src\/[^/]+\.[tj]sx?$/,/\/server\.[tj]sx?$/,/\/__init__\.py$/,/\/main\.go$/].some(i=>i.test(e))}getBaseName(e){return this.getFileName(e).replace(/\.[^.]+$/,"")}getFileName(e){return e.split(/[/\\]/).pop()||e}deduplicateImpact(e){let t=new Map;for(let i of e){let r=t.get(i.file);(!r||i.distance<r.distance)&&t.set(i.file,i)}return Array.from(t.values()).sort((i,r)=>r.riskScore!==i.riskScore?r.riskScore-i.riskScore:i.distance-r.distance)}async storeAnalysis(e,t){let i=h();await this.memory.set(`${this.config.namespace}:analysis:${i}`,{id:i,changedFiles:e,analysis:t,timestamp:new Date().toISOString()},{namespace:this.config.namespace,persist:!0})}};export{u as a};
@@ -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.5");process.exit(0)}
2
- import{a as p}from"./chunk-L336HFFE.js";import{e as g}from"./chunk-E4VIVMDL.js";p();import{format as R}from"node:util";var c=2,E={debug:0,info:1,warn:2,warning:2,error:3,silent:4,none:4,off:4},C=new Set(["1","true","yes","on"]),b=/\x1b\[[0-9;]*m/g,N=/^\[(?:\d{2}:\d{2}:\d{2}\.\d{3}|\d{4}-\d{2}-\d{2}T[^\]]+)\]\s+\[(DEBUG|INFO|WARN|ERROR)\s*\]/,O=/^\[[A-Za-z][\w./:-]*\]\s/,S={debug:0,log:1,info:1,warn:2,error:3},d=c;function s(o){if(o)return E[o.trim().toLowerCase()]}function _(o=process.env,e=c){let t=s(o.AQE_LOG_LEVEL)??s(o.LOG_LEVEL);return t!==void 0?t:o.AQE_VERBOSE&&C.has(o.AQE_VERBOSE.trim().toLowerCase())?1:e}function x(o,e){if(typeof e!="string")return null;let t=e.replace(b,""),r=N.exec(t.trimStart());return r?E[r[1].toLowerCase()]:O.test(t)?S[o]:null}function I(o=process.env){return s(o.AQE_LOG_LEVEL)!==void 0||s(o.LOG_LEVEL)!==void 0}function m(o,e=process.env){return o.verbose!==!0||I(e)||a(1)?!1:(f(1),!0)}function a(o){return o>=d&&d!==4}function f(o){d=o,g.setLevel(o)}function k(o={}){let e=o.target??console,t=o.writeStderr??(n=>{process.stderr.write(n)});f(o.level??_());let r={log:e.log.bind(e),info:e.info.bind(e),debug:e.debug.bind(e),warn:e.warn.bind(e),error:e.error.bind(e)},l=n=>t(R(...n)+`
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.7");process.exit(0)}
2
+ import{a as p}from"./chunk-VJRZFWR5.js";import{e as g}from"./chunk-JYXOFN3E.js";p();import{format as R}from"node:util";var c=2,E={debug:0,info:1,warn:2,warning:2,error:3,silent:4,none:4,off:4},C=new Set(["1","true","yes","on"]),b=/\x1b\[[0-9;]*m/g,N=/^\[(?:\d{2}:\d{2}:\d{2}\.\d{3}|\d{4}-\d{2}-\d{2}T[^\]]+)\]\s+\[(DEBUG|INFO|WARN|ERROR)\s*\]/,O=/^\[[A-Za-z][\w./:-]*\]\s/,S={debug:0,log:1,info:1,warn:2,error:3},d=c;function s(o){if(o)return E[o.trim().toLowerCase()]}function _(o=process.env,e=c){let t=s(o.AQE_LOG_LEVEL)??s(o.LOG_LEVEL);return t!==void 0?t:o.AQE_VERBOSE&&C.has(o.AQE_VERBOSE.trim().toLowerCase())?1:e}function x(o,e){if(typeof e!="string")return null;let t=e.replace(b,""),r=N.exec(t.trimStart());return r?E[r[1].toLowerCase()]:O.test(t)?S[o]:null}function I(o=process.env){return s(o.AQE_LOG_LEVEL)!==void 0||s(o.LOG_LEVEL)!==void 0}function m(o,e=process.env){return o.verbose!==!0||I(e)||a(1)?!1:(f(1),!0)}function a(o){return o>=d&&d!==4}function f(o){d=o,g.setLevel(o)}function k(o={}){let e=o.target??console,t=o.writeStderr??(n=>{process.stderr.write(n)});f(o.level??_());let r={log:e.log.bind(e),info:e.info.bind(e),debug:e.debug.bind(e),warn:e.warn.bind(e),error:e.error.bind(e)},l=n=>t(R(...n)+`
3
3
  `),i=(n,v,w)=>(...L)=>{let u=x(n,L[0]);u===null?v(L):a(u)&&w(L)};return e.log=i("log",n=>r.log(...n),l),e.debug=i("debug",n=>r.debug(...n),l),e.info=i("info",l,l),e.warn=i("warn",n=>r.warn(...n),n=>r.warn(...n)),e.error=i("error",n=>r.error(...n),n=>r.error(...n)),()=>{e.log=r.log,e.info=r.info,e.debug=r.debug,e.warn=r.warn,e.error=r.error}}export{_ as a,m as b,a as c,f as d,k as e};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.5");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.7");process.exit(0)}
2
2
  var h=Object.create;var f=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var k=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty;var m=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var n=(a,b,c)=>()=>{if(c)throw c[0];try{return a&&(b=a(a=0)),b}catch(d){throw c=[d],d}};var o=(a,b)=>()=>{try{return b||a((b={exports:{}}).exports,b),b.exports}catch(c){throw b=0,c}},p=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0})},g=(a,b,c,d)=>{if(b&&typeof b=="object"||typeof b=="function")for(let e of j(b))!l.call(a,e)&&e!==c&&f(a,e,{get:()=>b[e],enumerable:!(d=i(b,e))||d.enumerable});return a};var q=(a,b,c)=>(c=a!=null?h(k(a)):{},g(b||!a||!a.__esModule?f(c,"default",{value:a,enumerable:!0}):c,a)),r=a=>g(f({},"__esModule",{value:!0}),a);export{m as a,n as b,o as c,p as d,q as e,r as f};
@@ -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.5");process.exit(0)}
2
- import{b as t}from"./chunk-HLFDC4SF.js";import{randomInt as o}from"node:crypto";function a(){return Math.random()}function m(n,e){return o(n,e)}function c(n,e){return n+Math.random()*(e-n)}var r=t(()=>{"use strict"});export{a,m as b,c,r as d};
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.7");process.exit(0)}
2
+ import{b as t}from"./chunk-HSDOOFV7.js";import{randomInt as o}from"node:crypto";function a(){return Math.random()}function m(n,e){return o(n,e)}function c(n,e){return n+Math.random()*(e-n)}var r=t(()=>{"use strict"});export{a,m as b,c,r as d};
@@ -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.5");process.exit(0)}
2
- import{l as m}from"./chunk-6LG5UEQE.js";import{a as l,e as d}from"./chunk-NLDFNAOS.js";d();var c=class extends m{config={name:"qe/tests/load",description:"Run agent load tests to validate fleet scalability. Supports light, medium, and heavy workload profiles. Uses mock agents by default (safe); set mockMode=false to test with real fleet agents (requires fleet_init). Reports bottlenecks and pass/fail criteria.",domain:"test-execution",schema:this.buildSchema(),timeout:3e5};buildSchema(){return{type:"object",properties:{targetAgents:{type:"number",description:"Target number of concurrent agents to simulate",default:10,minimum:1,maximum:200},profile:{type:"string",description:"Workload profile: light, medium, or heavy",enum:["light","medium","heavy"],default:"medium"},durationMs:{type:"number",description:"Test duration in milliseconds",default:3e4,minimum:5e3,maximum:3e5},mockMode:{type:"boolean",description:"Use mock agents (true, default) or real fleet agents (false, requires fleet_init)",default:!0}}}}async execute(t,u){try{let{createAgentLoadTester:r}=await import("./load-NTJ4Y4ZR.js"),a=t.profile||"medium",o=t.targetAgents||10,i=t.durationMs||3e4,n=t.mockMode!==!1,s=await r({maxAgents:o,workloadProfile:a,mockMode:n}).runTest(o,i),e=s.bottlenecks;return{success:!0,data:{testId:u.requestId,profile:a,targetAgents:o,duration:s.duration,mockMode:n,passed:s.success,bottleneckCount:e?.bottlenecks?.length??0,report:{overallSeverity:e?.overallSeverity??"none",hasCritical:e?.hasCritical??!1,checksPerformed:e?.summary?.totalChecks??0,bottlenecksDetected:e?.summary?.detected??0},summary:`Load test (${a}, ${n?"mock":"real"}): ${o} agents, ${i}ms \u2014 ${s.success?"PASSED":"FAILED"}`+(e?.hasCritical?" [CRITICAL BOTTLENECKS]":"")}}}catch(r){return{success:!1,error:l(r)}}}};export{c as a};
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.7");process.exit(0)}
2
+ import{l as m}from"./chunk-6FEQ73BF.js";import{a as l,e as d}from"./chunk-LVEX4GID.js";d();var c=class extends m{config={name:"qe/tests/load",description:"Run agent load tests to validate fleet scalability. Supports light, medium, and heavy workload profiles. Uses mock agents by default (safe); set mockMode=false to test with real fleet agents (requires fleet_init). Reports bottlenecks and pass/fail criteria.",domain:"test-execution",schema:this.buildSchema(),timeout:3e5};buildSchema(){return{type:"object",properties:{targetAgents:{type:"number",description:"Target number of concurrent agents to simulate",default:10,minimum:1,maximum:200},profile:{type:"string",description:"Workload profile: light, medium, or heavy",enum:["light","medium","heavy"],default:"medium"},durationMs:{type:"number",description:"Test duration in milliseconds",default:3e4,minimum:5e3,maximum:3e5},mockMode:{type:"boolean",description:"Use mock agents (true, default) or real fleet agents (false, requires fleet_init)",default:!0}}}}async execute(t,u){try{let{createAgentLoadTester:r}=await import("./load-XADC7KCU.js"),a=t.profile||"medium",o=t.targetAgents||10,i=t.durationMs||3e4,n=t.mockMode!==!1,s=await r({maxAgents:o,workloadProfile:a,mockMode:n}).runTest(o,i),e=s.bottlenecks;return{success:!0,data:{testId:u.requestId,profile:a,targetAgents:o,duration:s.duration,mockMode:n,passed:s.success,bottleneckCount:e?.bottlenecks?.length??0,report:{overallSeverity:e?.overallSeverity??"none",hasCritical:e?.hasCritical??!1,checksPerformed:e?.summary?.totalChecks??0,bottlenecksDetected:e?.summary?.detected??0},summary:`Load test (${a}, ${n?"mock":"real"}): ${o} agents, ${i}ms \u2014 ${s.success?"PASSED":"FAILED"}`+(e?.hasCritical?" [CRITICAL BOTTLENECKS]":"")}}}catch(r){return{success:!1,error:l(r)}}}};export{c as a};
@@ -0,0 +1,2 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.7");process.exit(0)}
2
+ var r="insufficient-evidence";function s(t,n){let e=n&&typeof n=="object"?n:null;return e&&(e.status===r||e.evidenceStatus===r)?!1:t==="coverage-analysis"?e?.measured===!0:!0}export{s as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.5");process.exit(0)}
2
- import{a as v,b as k}from"./chunk-EVCFUYYK.js";import{o as g,s as P}from"./chunk-EOR3RECZ.js";import{a as d,b as y,e as R}from"./chunk-NLDFNAOS.js";R();import{randomUUID as M}from"crypto";var p=class{constructor(e){this.config=e}config;_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let r=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let n,t;for(let a=0;a<=this.config.retryCount;a++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");t=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(u){n=y(u),e.logger.warn(`Worker ${this.config.id} attempt ${a+1} failed: ${n.message}`),a<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let o=Date.now()-r;return t?(this._successfulExecutions++,this._lastResult=t):(this._failedExecutions++,t=this.createErrorResult(n,o),this._lastResult=t),this._executionDurations.push(o),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:t.success,durationMs:o}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=t.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:t.success,durationMs:o,findingsCount:t.findings.length,healthScore:t.metrics.healthScore}}),t}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((n,t)=>n+t,0)/this._executionDurations.length:0,r=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(r*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,r,n){return new Promise((t,o)=>{let a=setTimeout(()=>{o(new Error(`Worker execution timed out after ${r}ms`))},r),u=()=>{clearTimeout(a),o(new Error("Worker execution aborted"))};n.addEventListener("abort",u,{once:!0}),e().then(c=>{clearTimeout(a),n.removeEventListener("abort",u),t(c)}).catch(c=>{clearTimeout(a),n.removeEventListener("abort",u),o(c)})})}createErrorResult(e,r){return{workerId:this.config.id,timestamp:new Date,durationMs:r,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,r,n,t){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:r,findings:n,recommendations:t}}delay(e){return new Promise(r=>setTimeout(r,e))}generateId(){return`${Date.now()}-${M().slice(0,9)}`}};P();R();var W={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},b=class extends p{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(W),this.dailyLogger=new k}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=g();await e.initialize();let r=e.getDatabase();return this.lifecycleManager=v(r,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return g().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let r=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let n=[],t=[],o=await this.getLifecycleManager();if(!o)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-r,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let a=0,u=0;try{let s=o.promoteEligiblePatterns();a=s.promoted,u=s.checked,a>0&&n.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${a} of ${u} short-term patterns promoted to long-term`})}catch(s){e.logger.warn("Pattern promotion failed",{error:d(s)})}let c=0,h=0;try{let s=o.deprecateStalePatterns();c=s.deprecated,h=s.checked,c>0&&n.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${c} of ${h} patterns deprecated (stale, failed, or low confidence)`})}catch(s){e.logger.warn("Stale pattern detection failed",{error:d(s)})}let l=0;try{let s=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;l=o.applyConfidenceDecay(Math.min(s,7)).decayed}catch(s){e.logger.warn("Confidence decay failed",{error:d(s)})}let m=this.getPendingExperienceCount(),i={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{i=o.getStats()}catch(s){e.logger.warn("Stats retrieval failed",{error:d(s)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${a} promoted, ${c} deprecated, ${l} decayed, ${m} pending exp, ${i.activePatterns} active patterns (avg conf: ${i.avgConfidence.toFixed(2)})`,details:{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,totalPatterns:i.totalPatterns,activePatterns:i.activePatterns,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}),this.dailyLogger.flush()}catch(s){e.logger.warn("Daily log write failed",{error:d(s)})}this.lastRunTimestamp=Date.now(),i.activePatterns>0&&i.patternsNearDeprecation/i.activePatterns>.5&&t.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${i.patternsNearDeprecation} of ${i.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let f=this.calculateHealthScore(i,a,c),D=this.determineTrend(a,c,i.activePatterns),_=Math.max(u,h),x=a+c+i.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,healthScore:f}),this.createResult(Date.now()-r,{itemsAnalyzed:_,issuesFound:x,healthScore:f,trend:D,domainMetrics:{promoted:a,deprecated:c,decayed:l,stalePatterns:i.patternsNearDeprecation,pendingExperiences:m,avgConfidence:Number(i.avgConfidence.toFixed(3)),avgSuccessRate:Number(i.avgSuccessRate.toFixed(3))}},n,t)}calculateHealthScore(e,r,n){let t=70;if(t+=Math.min(15,r*5),e.avgConfidence>0&&(t+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let o=n/e.activePatterns;t-=Math.round(o*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(t-=10),Math.max(0,Math.min(100,Math.round(t)))}determineTrend(e,r,n){return n===0?"stable":e>r?"improving":r>e&&r/n>.1?"degrading":"stable"}};export{p as a,b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.7");process.exit(0)}
2
+ import{a as v,b as k}from"./chunk-QQT6QENQ.js";import{o as g,s as P}from"./chunk-ZLVQSEZK.js";import{a as d,b as y,e as R}from"./chunk-LVEX4GID.js";R();import{randomUUID as M}from"crypto";var p=class{constructor(e){this.config=e}config;_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let r=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let n,t;for(let a=0;a<=this.config.retryCount;a++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");t=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(u){n=y(u),e.logger.warn(`Worker ${this.config.id} attempt ${a+1} failed: ${n.message}`),a<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let o=Date.now()-r;return t?(this._successfulExecutions++,this._lastResult=t):(this._failedExecutions++,t=this.createErrorResult(n,o),this._lastResult=t),this._executionDurations.push(o),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:t.success,durationMs:o}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=t.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:t.success,durationMs:o,findingsCount:t.findings.length,healthScore:t.metrics.healthScore}}),t}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((n,t)=>n+t,0)/this._executionDurations.length:0,r=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(r*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,r,n){return new Promise((t,o)=>{let a=setTimeout(()=>{o(new Error(`Worker execution timed out after ${r}ms`))},r),u=()=>{clearTimeout(a),o(new Error("Worker execution aborted"))};n.addEventListener("abort",u,{once:!0}),e().then(c=>{clearTimeout(a),n.removeEventListener("abort",u),t(c)}).catch(c=>{clearTimeout(a),n.removeEventListener("abort",u),o(c)})})}createErrorResult(e,r){return{workerId:this.config.id,timestamp:new Date,durationMs:r,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,r,n,t){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:r,findings:n,recommendations:t}}delay(e){return new Promise(r=>setTimeout(r,e))}generateId(){return`${Date.now()}-${M().slice(0,9)}`}};P();R();var W={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},b=class extends p{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(W),this.dailyLogger=new k}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=g();await e.initialize();let r=e.getDatabase();return this.lifecycleManager=v(r,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return g().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let r=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let n=[],t=[],o=await this.getLifecycleManager();if(!o)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-r,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let a=0,u=0;try{let s=o.promoteEligiblePatterns();a=s.promoted,u=s.checked,a>0&&n.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${a} of ${u} short-term patterns promoted to long-term`})}catch(s){e.logger.warn("Pattern promotion failed",{error:d(s)})}let c=0,h=0;try{let s=o.deprecateStalePatterns();c=s.deprecated,h=s.checked,c>0&&n.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${c} of ${h} patterns deprecated (stale, failed, or low confidence)`})}catch(s){e.logger.warn("Stale pattern detection failed",{error:d(s)})}let l=0;try{let s=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;l=o.applyConfidenceDecay(Math.min(s,7)).decayed}catch(s){e.logger.warn("Confidence decay failed",{error:d(s)})}let m=this.getPendingExperienceCount(),i={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{i=o.getStats()}catch(s){e.logger.warn("Stats retrieval failed",{error:d(s)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${a} promoted, ${c} deprecated, ${l} decayed, ${m} pending exp, ${i.activePatterns} active patterns (avg conf: ${i.avgConfidence.toFixed(2)})`,details:{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,totalPatterns:i.totalPatterns,activePatterns:i.activePatterns,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}),this.dailyLogger.flush()}catch(s){e.logger.warn("Daily log write failed",{error:d(s)})}this.lastRunTimestamp=Date.now(),i.activePatterns>0&&i.patternsNearDeprecation/i.activePatterns>.5&&t.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${i.patternsNearDeprecation} of ${i.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let f=this.calculateHealthScore(i,a,c),D=this.determineTrend(a,c,i.activePatterns),_=Math.max(u,h),x=a+c+i.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,healthScore:f}),this.createResult(Date.now()-r,{itemsAnalyzed:_,issuesFound:x,healthScore:f,trend:D,domainMetrics:{promoted:a,deprecated:c,decayed:l,stalePatterns:i.patternsNearDeprecation,pendingExperiences:m,avgConfidence:Number(i.avgConfidence.toFixed(3)),avgSuccessRate:Number(i.avgSuccessRate.toFixed(3))}},n,t)}calculateHealthScore(e,r,n){let t=70;if(t+=Math.min(15,r*5),e.avgConfidence>0&&(t+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let o=n/e.activePatterns;t-=Math.round(o*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(t-=10),Math.max(0,Math.min(100,Math.round(t)))}determineTrend(e,r,n){return n===0?"stable":e>r?"improving":r>e&&r/n>.1?"degrading":"stable"}};export{p as a,b};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.5");process.exit(0)}
2
- import{a as u,q as E}from"./chunk-U6OVPMQX.js";import{b as k}from"./chunk-HLFDC4SF.js";import{existsSync as i,renameSync as p,copyFileSync as T,readdirSync as x,statSync as h,openSync as R,readSync as v,closeSync as B,writeFileSync as O,rmSync as $}from"node:fs";import{join as w,dirname as M}from"node:path";function D(e){if(!i(e))return!0;let t;try{t=h(e).size}catch{return!1}if(t===0)return!0;if(t<d.length)return!1;let r;try{r=R(e,"r");let o=Buffer.alloc(d.length);return v(r,o,0,d.length,0),o.equals(d)}catch{return!1}finally{if(r!==void 0)try{B(r)}catch{}}}function U(e){let t;try{return t=new u(e,{readonly:!0,fileMustExist:!0}),t.pragma("integrity_check",{simple:!0})==="ok"}catch{return!1}finally{try{t?.close()}catch{}}}function Q(e){return w(M(e),"backups","verified")}function C(e){if(!i(e))return null;let t=x(e).filter(r=>r.startsWith("memory-")&&r.endsWith(".db")).map(r=>{let o=w(e,r);return{path:o,mtime:h(o).mtimeMs}}).sort((r,o)=>o.mtime-r.mtime);for(let r of t)if(U(r.path))return r.path;return null}function S(e,t){if(D(e))return{restored:!1,reason:"healthy"};let r=t?.backupDir??Q(e),o=C(r);if(!o)return{restored:!1,reason:"no-verified-backup"};let f=`${e}.restore.lock`;try{O(f,String(process.pid),{flag:"wx"})}catch{return{restored:!1,reason:"restore-in-progress"}}try{if(D(e))return{restored:!1,reason:"healthy"};let l=t?.now??Date.now(),s=`${e}.corrupt-${l}`;try{i(e)&&p(e,s);for(let n of["-wal","-shm"])i(e+n)&&p(e+n,s+n)}catch{return{restored:!1,reason:"park-failed"}}let c=`${e}.restoring-${l}`;try{T(o,c),p(c,e)}catch{try{i(c)&&$(c,{force:!0}),!i(e)&&i(s)&&p(s,e)}catch{}return{restored:!1,reason:"copy-failed"}}return{restored:!0,reason:"restored-from-backup",backupUsed:o,parkedTo:s}}finally{try{$(f,{force:!0})}catch{}}}var d,_=k(()=>{"use strict";E();d=Buffer.concat([Buffer.from("SQLite format 3","latin1"),Buffer.from([0])])});import{basename as I}from"node:path";function H(e,t){let r=t?.readonly??!1,o=t?.fileMustExist??!1,f=t?.busyTimeout??5e3,l=t?.walMode??!r;if(t?.autoRestore&&!r){let a=S(e,{backupDir:t.backupDir});a.restored?console.warn(`[safe-db] memory DB at ${e} was malformed; auto-restored from ${a.backupUsed}. Corrupt original parked at ${a.parkedTo}.`):a.reason==="no-verified-backup"&&console.error(`[safe-db] memory DB at ${e} appears malformed and NO verified backup was found to restore from. Leaving it in place for manual inspection.`)}let s=(process.env.AQE_JOURNAL_MODE??"").trim().toUpperCase(),c=process.env.AQE_DISABLE_WAL==="1"||s==="DELETE"||s==="TRUNCATE",n=new u(e,{readonly:r,fileMustExist:o});if(n.pragma(`busy_timeout = ${f}`),c){if(!r){let a=(s||"DELETE").toUpperCase(),m=String(n.pragma("journal_mode",{simple:!0})??"").toUpperCase();if(m!==a){try{n.pragma(`journal_mode = ${a}`)}catch(y){let b=y?.code;if(n.close(),b!=="SQLITE_BUSY"&&b!=="SQLITE_LOCKED")throw y;let A=I(e),L=process.env.AQE_DISABLE_WAL==="1"?"AQE_DISABLE_WAL=1":`AQE_JOURNAL_MODE=${s}`;throw new Error(`[safe-db] cannot switch ${e} from '${m}' to '${a}' \u2014 another process holds the database open. ${L} declares WAL unsafe on this filesystem, so writing in '${m}' is NOT safe and this open is refused. Find the holder with:
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.7");process.exit(0)}
2
+ import{a as u,q as E}from"./chunk-JVYPXW6Y.js";import{b as k}from"./chunk-HSDOOFV7.js";import{existsSync as i,renameSync as p,copyFileSync as T,readdirSync as x,statSync as h,openSync as R,readSync as v,closeSync as B,writeFileSync as O,rmSync as $}from"node:fs";import{join as w,dirname as M}from"node:path";function D(e){if(!i(e))return!0;let t;try{t=h(e).size}catch{return!1}if(t===0)return!0;if(t<d.length)return!1;let r;try{r=R(e,"r");let o=Buffer.alloc(d.length);return v(r,o,0,d.length,0),o.equals(d)}catch{return!1}finally{if(r!==void 0)try{B(r)}catch{}}}function U(e){let t;try{return t=new u(e,{readonly:!0,fileMustExist:!0}),t.pragma("integrity_check",{simple:!0})==="ok"}catch{return!1}finally{try{t?.close()}catch{}}}function Q(e){return w(M(e),"backups","verified")}function C(e){if(!i(e))return null;let t=x(e).filter(r=>r.startsWith("memory-")&&r.endsWith(".db")).map(r=>{let o=w(e,r);return{path:o,mtime:h(o).mtimeMs}}).sort((r,o)=>o.mtime-r.mtime);for(let r of t)if(U(r.path))return r.path;return null}function S(e,t){if(D(e))return{restored:!1,reason:"healthy"};let r=t?.backupDir??Q(e),o=C(r);if(!o)return{restored:!1,reason:"no-verified-backup"};let f=`${e}.restore.lock`;try{O(f,String(process.pid),{flag:"wx"})}catch{return{restored:!1,reason:"restore-in-progress"}}try{if(D(e))return{restored:!1,reason:"healthy"};let l=t?.now??Date.now(),s=`${e}.corrupt-${l}`;try{i(e)&&p(e,s);for(let n of["-wal","-shm"])i(e+n)&&p(e+n,s+n)}catch{return{restored:!1,reason:"park-failed"}}let c=`${e}.restoring-${l}`;try{T(o,c),p(c,e)}catch{try{i(c)&&$(c,{force:!0}),!i(e)&&i(s)&&p(s,e)}catch{}return{restored:!1,reason:"copy-failed"}}return{restored:!0,reason:"restored-from-backup",backupUsed:o,parkedTo:s}}finally{try{$(f,{force:!0})}catch{}}}var d,_=k(()=>{"use strict";E();d=Buffer.concat([Buffer.from("SQLite format 3","latin1"),Buffer.from([0])])});import{basename as I}from"node:path";function H(e,t){let r=t?.readonly??!1,o=t?.fileMustExist??!1,f=t?.busyTimeout??5e3,l=t?.walMode??!r;if(t?.autoRestore&&!r){let a=S(e,{backupDir:t.backupDir});a.restored?console.warn(`[safe-db] memory DB at ${e} was malformed; auto-restored from ${a.backupUsed}. Corrupt original parked at ${a.parkedTo}.`):a.reason==="no-verified-backup"&&console.error(`[safe-db] memory DB at ${e} appears malformed and NO verified backup was found to restore from. Leaving it in place for manual inspection.`)}let s=(process.env.AQE_JOURNAL_MODE??"").trim().toUpperCase(),c=process.env.AQE_DISABLE_WAL==="1"||s==="DELETE"||s==="TRUNCATE",n=new u(e,{readonly:r,fileMustExist:o});if(n.pragma(`busy_timeout = ${f}`),c){if(!r){let a=(s||"DELETE").toUpperCase(),m=String(n.pragma("journal_mode",{simple:!0})??"").toUpperCase();if(m!==a){try{n.pragma(`journal_mode = ${a}`)}catch(y){let b=y?.code;if(n.close(),b!=="SQLITE_BUSY"&&b!=="SQLITE_LOCKED")throw y;let A=I(e),L=process.env.AQE_DISABLE_WAL==="1"?"AQE_DISABLE_WAL=1":`AQE_JOURNAL_MODE=${s}`;throw new Error(`[safe-db] cannot switch ${e} from '${m}' to '${a}' \u2014 another process holds the database open. ${L} declares WAL unsafe on this filesystem, so writing in '${m}' is NOT safe and this open is refused. Find the holder with:
3
3
  for p in /proc/[0-9]*; do for f in $p/fd/*; do readlink "$f" 2>/dev/null | grep -q ${JSON.stringify(A)} && echo "$(basename $p) $(tr '\\0' ' ' < $p/cmdline)"; done; done | sort -u
4
4
  then stop it and retry. Original error: ${y.message}`)}let g=String(n.pragma("journal_mode",{simple:!0})??"").toUpperCase();if(g!==a)throw n.close(),new Error(`[safe-db] journal_mode switch to '${a}' silently did not take on ${e} (still '${g}'). Refusing to write in an unsafe mode.`)}}}else l&&n.pragma("journal_mode = WAL");return n}var W=k(()=>{E();_()});export{H as a,W as b};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.5");process.exit(0)}
2
- import{a as D,b as _,c as X,d as I,f as ne}from"./chunk-4UXPDV7E.js";import{a as K,d as J}from"./chunk-4PT5KNXL.js";import{c as Z,d as ee,e as te,f as re}from"./chunk-4AZP7ZCW.js";import{b as C,g as $,j as H}from"./chunk-FNAYDITO.js";import{b as k}from"./chunk-OW42F2TX.js";import{d as Y}from"./chunk-GGDKOJVF.js";import{o as j,s as fe}from"./chunk-EOR3RECZ.js";import{p as U}from"./chunk-EAYQCBXL.js";import{c as q,d as E}from"./chunk-3AYYGR6W.js";import{a as G}from"./chunk-L336HFFE.js";import{e as T}from"./chunk-E4VIVMDL.js";import{a as h,b as W,e as z}from"./chunk-NLDFNAOS.js";import{S as he,b as B}from"./chunk-VRJPH3LG.js";G();z();var M={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var A=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
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.7");process.exit(0)}
2
+ import{a as I,b as _,c as X,d as M,f as ne}from"./chunk-EV2BYY6T.js";import{a as K,e as J}from"./chunk-DCJW2DPL.js";import{c as Z,d as ee,e as te,f as re}from"./chunk-ZRLNACPY.js";import{b as D,g as $,j as H}from"./chunk-V2SAEMZY.js";import{b as k}from"./chunk-XEWXYGJI.js";import{d as Y}from"./chunk-RCYLCA7E.js";import{o as U,s as ye}from"./chunk-ZLVQSEZK.js";import{p as T}from"./chunk-C2MDBBFF.js";import{c as C,d as E}from"./chunk-CG5DZCOZ.js";import{a as G}from"./chunk-VJRZFWR5.js";import{e as A}from"./chunk-JYXOFN3E.js";import{a as f,b as B,e as z}from"./chunk-LVEX4GID.js";import{S as he,b as j}from"./chunk-LGBN7TKC.js";G();z();function ie(i,e,r,t){let n={missing:0,ingested:0,rejected:0,capped:!1};if(typeof i.has!="function")return n;let o=u=>u.filter(h=>!i.has(h)),s=o(e.getEmbeddingIdsInSpace(r));if(s.length===0)return n;let a=Number.isFinite(t)&&t>0?Math.floor(t):1e3;s.length>a&&(s=o(e.getEmbeddingIdsInSpace(r,{ordered:!0})));let c=s.slice(0,a),d=e.getEmbeddingsByIds(c).filter(({embedding:u})=>u&&u.length>0).map(({patternId:u,embedding:h})=>({id:u,vector:new Float32Array(h)})),{accepted:l,rejected:m}=d.length>0?i.ingest(d):{accepted:0,rejected:0};return{missing:s.length,ingested:l,rejected:m,capped:s.length>a}}var N={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var q=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
3
3
  describe('{{methodName}}', () => {
4
4
  it('should {{expectedBehavior}}', {{async}} () => {
5
5
  // Arrange
@@ -278,7 +278,7 @@ On promotion:
278
278
  - Move from short-term to long-term tier
279
279
  - Boost confidence by 10%
280
280
  - Enable for cross-domain transfer to related domains
281
- - Mark as reusable for token savings optimization`,variables:[{name:"patternName",type:"string",required:!0,description:"Pattern to evaluate for promotion"}]},context:{tags:["promotion","learning","quality","pipeline"]},confidence:.6}];import{randomInt as ie}from"crypto";var x={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88,languages:["typescript","javascript"]},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}},ye=.4,be=20,ve=3;function Pe(i){return 1/(1+Math.exp(-i))}function we(i,e){if(!e||e.visits===0)return{score:i,qWeight:0,qValue:0,qVisits:0};let r=Math.min(e.visits/be,1)*ye,t=Pe(e.qValue);return{score:i*(1-r)+t*r,qWeight:r,qValue:e.qValue,qVisits:e.visits}}function ae(i){let e=i.envOverride,r=e!==void 0?Number.parseFloat(e):NaN,t=Number.isFinite(r)&&r>=0&&r<=1?r:.05,n=i.topologyCritical?.2:1;return{epsilon:Math.min(Math.max(t*n,0),1),baseEpsilon:t,safetyMultiplier:n}}function oe(i,e){if(e<=0||i.length<2)return;let r=Math.round(e*1e6);if(r<=0||ie(0,1e6)>=r)return;let t=Math.min(4,i.length),n=ie(1,t),o=i[n];i[n]=i[0],i[0]=o,i[0].exploration=!0,i[0].reasoning=[...i[0].reasoning,"(exploration)"]}function se(i){let e=i.toLowerCase();return/\bgenerate[- ]?test|\btest[- ]?gen|\bgenerate.+spec/.test(e)?"test-generation":/\bcoverage|\banalyze.+cover/.test(e)?"coverage-analysis":/\bquality|\bassess|\baudit/.test(e)?"quality-assessment":/\bsecurity|\bvulnerab|\bcompliance/.test(e)?"security-compliance":/\bdefect|\bbug|\bdiagnos/.test(e)?"defect-intelligence":/\brequirement|\bspec\b/.test(e)?"requirements-validation":/\brefactor|\brewrite|\boptim/.test(e)?"refactoring":/\btest|\brun.+test/.test(e)?"test-execution":"unknown"}function ce(i){return`${i.taskType}|${i.priority??"normal"}|${i.domain??"any"}`}function N(i,e,r,t,n=x,o,s){let a=[];for(let[c,u]of Object.entries(n)){let l=0,m=[],p=i.filter(f=>u.domains.includes(f)).length,b=Math.min(i.length,ve),y=p>0?Math.min(p/b,1)*.4:0;if(l+=y*t.similarity,y>0&&m.push(`Domain match: ${(y*100).toFixed(0)}%`),e&&e.length>0){let f=e.filter(v=>u.capabilities.some(P=>P.toLowerCase().includes(v.toLowerCase()))).length,d=f>0?f/e.length*.3:0;l+=d*t.capabilities,d>0&&m.push(`Capability match: ${(d*100).toFixed(0)}%`)}else l+=.15*t.capabilities;if(l+=u.performanceScore*.3*t.performance,m.push(`Performance score: ${(u.performanceScore*100).toFixed(0)}%`),o&&u.languages&&u.languages.length>0){let f=t.language??1,d=o.toLowerCase();if(u.languages.some(P=>P.toLowerCase()===d)){let P=.15*f;l+=P,m.push(`Language match: ${o}`)}}let S=r.get(c)||0;if(S>0){let f=Math.min(.1,S*.02);l+=f,m.push(`Pattern matches: ${S}`)}let R=l;if(s){let f=s(c),d=we(R,f);l=d.score,d.qWeight>0&&m.push(`Q-bonus (w=${d.qWeight.toFixed(2)}, v=${d.qVisits})`),a.push({agent:c,score:l,reasoning:m,staticScore:R,qWeight:d.qWeight,qValue:d.qValue,qVisits:d.qVisits})}else a.push({agent:c,score:l,reasoning:m,staticScore:R})}return a.sort((c,u)=>u.score-c.score),a}var Q={"test-generation":["test-execution","coverage-analysis","requirements-validation"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence"]};function le(){try{return!re()||!te()||Z().getVerticesByType("agent").length===0?!1:ee().isCritical()}catch{return!1}}fe();function ue(i,e){if(i.length===e)return i;if(i.length>e){let r=i.length/e,t=new Array(e).fill(0);for(let n=0;n<e;n++){let o=Math.floor(n*r),s=Math.floor((n+1)*r),a=0;for(let c=o;c<s;c++)a+=i[c];t[n]=a/(s-o)}return O(t)}else{let r=new Array(e).fill(0),t=(i.length-1)/(e-1);for(let n=0;n<e;n++){let o=n*t,s=Math.floor(o),a=Math.min(s+1,i.length-1),c=o-s;r[n]=i[s]*(1-c)+i[a]*c}return O(r)}}function de(i,e){let r=new Array(e).fill(0),t=i.toLowerCase().trim();for(let n=0;n<3;n++)for(let o=0;o<t.length;o++){let s=t.charCodeAt(o),a=s*(o+1)*(n+1)%e;r[a]+=Math.sin(s*(n+1))/(o+1)}return O(r)}function O(i){let e=Math.sqrt(i.reduce((r,t)=>r+t*t,0));if(e>0)for(let r=0;r<i.length;r++)i[r]/=e;return i}G();z();he();var w=T.create("PatternPromotion");async function pe(i,e){let r=$(i);if(!r.meetsUsageCriteria||!r.meetsQualityCriteria)return!1;if(e.coherenceService&&e.coherenceService.isInitialized()){let t=await e.searchPatterns("",{tier:"long-term",limit:1e3}),s=[...t.success?t.value.map(c=>c.pattern):[],i].map(c=>({id:c.id,embedding:c.embedding||[],weight:c.confidence,metadata:{name:c.name,domain:c.qeDomain}})),a=await e.coherenceService.checkCoherence(s);if(a.energy>=e.coherenceThreshold){let c={patternId:i.id,patternName:i.name,reason:"coherence_violation",energy:a.energy,existingPatternConflicts:a.contradictions?.map(u=>u.nodeIds).flat()};return e.eventBus&&await e.eventBus.publish({id:`pattern-promotion-blocked-${i.id}`,type:"pattern:promotion_blocked",timestamp:new Date,source:"learning-optimization",payload:c}),w.info("Pattern promotion blocked due to coherence violation",{name:i.name,energy:a.energy}),!1}}return!0}async function L(i,e){let r=await e.patternStore.promote(i);if(r.success){try{e.getSqliteStore().promotePattern(i)}catch(t){w.warn("SQLite pattern promotion persist failed",{error:h(t)})}if(B().useSublinearSolver)try{let t=e.getSqliteStore().getDatabase?.();if(t){let n=new F(t),o=await e.getPattern(i);if(o){let s=await e.searchPatterns("",{domain:o.qeDomain,tier:"long-term",limit:20});if(s.success)for(let{pattern:a}of s.value)a.id!==i&&n.recordCoOccurrence(i,a.id)}}}catch(t){w.warn("Citation graph update failed (non-fatal)",{error:h(t)})}if(e.rvfDualWriter)try{let t=await e.getPattern(i);t?.embedding&&t.embedding.length>0&&e.rvfDualWriter.writePattern(i,t.embedding)}catch(t){w.warn("RVF dual-write on promote failed (non-fatal)",{patternId:i,error:h(t)})}return k().then(t=>t.append("PATTERN_PROMOTE",{patternId:i},"reasoning-bank")).catch(t=>{w.warn("Witness chain PATTERN_PROMOTE failed",{error:h(t)})}),w.info("Promoted pattern to long-term",{patternId:i}),e.eventBus&&await e.eventBus.publish({id:`pattern-promoted-${i}`,type:"pattern:promoted",timestamp:new Date,source:"learning-optimization",payload:{patternId:i,newTier:"long-term"}}),r}else return w.error("Failed to promote pattern",r.error,{patternId:i}),r}async function me(i){let{signal:e}=i;e?.throwIfAborted();let r=await i.patternStore.getStats(),t=0,n=0;for(let[o,s]of Object.entries(Q)){e?.throwIfAborted();let a=o,c=r.byDomain[a]||0;if(c===0)continue;let u=await i.searchPatterns("",{domain:a,limit:50});if(u.success)for(let l of s){if(e?.throwIfAborted(),(r.byDomain[l]||0)>=c){n++;continue}for(let{pattern:p}of u.value){e?.throwIfAborted();let b=await i.searchPatterns(p.name,{domain:l,limit:1});if(b.success&&b.value.length>0&&b.value[0].score>.8){n++;continue}let y=Math.max(.3,(p.confidence||.5)*.8);(await i.storePattern({patternType:p.patternType,qeDomain:l,name:`${p.name} (from ${a})`,description:`${p.description} [Transferred from ${a} domain]`,template:p.template,context:{...p.context,relatedDomains:[a,l],tags:[...p.context.tags,"cross-domain-transfer",`source:${a}`]},confidence:y})).success?t++:n++}}}return w.info("Cross-domain transfer complete",{transferred:t,skipped:n}),{transferred:t,skipped:n}}var Se=`
281
+ - Mark as reusable for token savings optimization`,variables:[{name:"patternName",type:"string",required:!0,description:"Pattern to evaluate for promotion"}]},context:{tags:["promotion","learning","quality","pipeline"]},confidence:.6}];import{randomInt as ae}from"crypto";var x={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88,languages:["typescript","javascript"]},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}},be=.4,ve=20,Pe=3;function Re(i){return 1/(1+Math.exp(-i))}function Se(i,e){if(!e||e.visits===0)return{score:i,qWeight:0,qValue:0,qVisits:0};let r=Math.min(e.visits/ve,1)*be,t=Re(e.qValue);return{score:i*(1-r)+t*r,qWeight:r,qValue:e.qValue,qVisits:e.visits}}function oe(i){let e=i.envOverride,r=e!==void 0?Number.parseFloat(e):NaN,t=Number.isFinite(r)&&r>=0&&r<=1?r:.05,n=i.topologyCritical?.2:1;return{epsilon:Math.min(Math.max(t*n,0),1),baseEpsilon:t,safetyMultiplier:n}}function se(i,e){if(e<=0||i.length<2)return;let r=Math.round(e*1e6);if(r<=0||ae(0,1e6)>=r)return;let t=Math.min(4,i.length),n=ae(1,t),o=i[n];i[n]=i[0],i[0]=o,i[0].exploration=!0,i[0].reasoning=[...i[0].reasoning,"(exploration)"]}function ce(i){let e=i.toLowerCase();return/\bgenerate[- ]?test|\btest[- ]?gen|\bgenerate.+spec/.test(e)?"test-generation":/\bcoverage|\banalyze.+cover/.test(e)?"coverage-analysis":/\bquality|\bassess|\baudit/.test(e)?"quality-assessment":/\bsecurity|\bvulnerab|\bcompliance/.test(e)?"security-compliance":/\bdefect|\bbug|\bdiagnos/.test(e)?"defect-intelligence":/\brequirement|\bspec\b/.test(e)?"requirements-validation":/\brefactor|\brewrite|\boptim/.test(e)?"refactoring":/\btest|\brun.+test/.test(e)?"test-execution":"unknown"}function le(i){return`${i.taskType}|${i.priority??"normal"}|${i.domain??"any"}`}function Q(i,e,r,t,n=x,o,s){let a=[];for(let[c,d]of Object.entries(n)){let l=0,m=[],u=i.filter(y=>d.domains.includes(y)).length,h=Math.min(i.length,Pe),b=u>0?Math.min(u/h,1)*.4:0;if(l+=b*t.similarity,b>0&&m.push(`Domain match: ${(b*100).toFixed(0)}%`),e&&e.length>0){let y=e.filter(v=>d.capabilities.some(P=>P.toLowerCase().includes(v.toLowerCase()))).length,p=y>0?y/e.length*.3:0;l+=p*t.capabilities,p>0&&m.push(`Capability match: ${(p*100).toFixed(0)}%`)}else l+=.15*t.capabilities;if(l+=d.performanceScore*.3*t.performance,m.push(`Performance score: ${(d.performanceScore*100).toFixed(0)}%`),o&&d.languages&&d.languages.length>0){let y=t.language??1,p=o.toLowerCase();if(d.languages.some(P=>P.toLowerCase()===p)){let P=.15*y;l+=P,m.push(`Language match: ${o}`)}}let S=r.get(c)||0;if(S>0){let y=Math.min(.1,S*.02);l+=y,m.push(`Pattern matches: ${S}`)}let w=l;if(s){let y=s(c),p=Se(w,y);l=p.score,p.qWeight>0&&m.push(`Q-bonus (w=${p.qWeight.toFixed(2)}, v=${p.qVisits})`),a.push({agent:c,score:l,reasoning:m,staticScore:w,qWeight:p.qWeight,qValue:p.qValue,qVisits:p.qVisits})}else a.push({agent:c,score:l,reasoning:m,staticScore:w})}return a.sort((c,d)=>d.score-c.score),a}var O={"test-generation":["test-execution","coverage-analysis","requirements-validation"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence"]};function ue(){try{return!re()||!te()||Z().getVerticesByType("agent").length===0?!1:ee().isCritical()}catch{return!1}}ye();function de(i,e){if(i.length===e)return i;if(i.length>e){let r=i.length/e,t=new Array(e).fill(0);for(let n=0;n<e;n++){let o=Math.floor(n*r),s=Math.floor((n+1)*r),a=0;for(let c=o;c<s;c++)a+=i[c];t[n]=a/(s-o)}return F(t)}else{let r=new Array(e).fill(0),t=(i.length-1)/(e-1);for(let n=0;n<e;n++){let o=n*t,s=Math.floor(o),a=Math.min(s+1,i.length-1),c=o-s;r[n]=i[s]*(1-c)+i[a]*c}return F(r)}}function pe(i,e){let r=new Array(e).fill(0),t=i.toLowerCase().trim();for(let n=0;n<3;n++)for(let o=0;o<t.length;o++){let s=t.charCodeAt(o),a=s*(o+1)*(n+1)%e;r[a]+=Math.sin(s*(n+1))/(o+1)}return F(r)}function F(i){let e=Math.sqrt(i.reduce((r,t)=>r+t*t,0));if(e>0)for(let r=0;r<i.length;r++)i[r]/=e;return i}G();z();he();var R=A.create("PatternPromotion");async function me(i,e){let r=$(i);if(!r.meetsUsageCriteria||!r.meetsQualityCriteria)return!1;if(e.coherenceService&&e.coherenceService.isInitialized()){let t=await e.searchPatterns("",{tier:"long-term",limit:1e3}),s=[...t.success?t.value.map(c=>c.pattern):[],i].map(c=>({id:c.id,embedding:c.embedding||[],weight:c.confidence,metadata:{name:c.name,domain:c.qeDomain}})),a=await e.coherenceService.checkCoherence(s);if(a.energy>=e.coherenceThreshold){let c={patternId:i.id,patternName:i.name,reason:"coherence_violation",energy:a.energy,existingPatternConflicts:a.contradictions?.map(d=>d.nodeIds).flat()};return e.eventBus&&await e.eventBus.publish({id:`pattern-promotion-blocked-${i.id}`,type:"pattern:promotion_blocked",timestamp:new Date,source:"learning-optimization",payload:c}),R.info("Pattern promotion blocked due to coherence violation",{name:i.name,energy:a.energy}),!1}}return!0}async function V(i,e){let r=await e.patternStore.promote(i);if(r.success){try{e.getSqliteStore().promotePattern(i)}catch(t){R.warn("SQLite pattern promotion persist failed",{error:f(t)})}if(j().useSublinearSolver)try{let t=e.getSqliteStore().getDatabase?.();if(t){let n=new L(t),o=await e.getPattern(i);if(o){let s=await e.searchPatterns("",{domain:o.qeDomain,tier:"long-term",limit:20});if(s.success)for(let{pattern:a}of s.value)a.id!==i&&n.recordCoOccurrence(i,a.id)}}}catch(t){R.warn("Citation graph update failed (non-fatal)",{error:f(t)})}if(e.rvfDualWriter)try{let t=await e.getPattern(i);t?.embedding&&t.embedding.length>0&&e.rvfDualWriter.writePattern(i,t.embedding)}catch(t){R.warn("RVF dual-write on promote failed (non-fatal)",{patternId:i,error:f(t)})}return k().then(t=>t.append("PATTERN_PROMOTE",{patternId:i},"reasoning-bank")).catch(t=>{R.warn("Witness chain PATTERN_PROMOTE failed",{error:f(t)})}),R.info("Promoted pattern to long-term",{patternId:i}),e.eventBus&&await e.eventBus.publish({id:`pattern-promoted-${i}`,type:"pattern:promoted",timestamp:new Date,source:"learning-optimization",payload:{patternId:i,newTier:"long-term"}}),r}else return R.error("Failed to promote pattern",r.error,{patternId:i}),r}async function ge(i){let{signal:e}=i;e?.throwIfAborted();let r=await i.patternStore.getStats(),t=0,n=0;for(let[o,s]of Object.entries(O)){e?.throwIfAborted();let a=o,c=r.byDomain[a]||0;if(c===0)continue;let d=await i.searchPatterns("",{domain:a,limit:50});if(d.success)for(let l of s){if(e?.throwIfAborted(),(r.byDomain[l]||0)>=c){n++;continue}for(let{pattern:u}of d.value){e?.throwIfAborted();let h=await i.searchPatterns(u.name,{domain:l,limit:1});if(h.success&&h.value.length>0&&h.value[0].score>.8){n++;continue}let b=Math.max(.3,(u.confidence||.5)*.8);(await i.storePattern({patternType:u.patternType,qeDomain:l,name:`${u.name} (from ${a})`,description:`${u.description} [Transferred from ${a} domain]`,template:u.template,context:{...u.context,relatedDomains:[a,l],tags:[...u.context.tags,"cross-domain-transfer",`source:${a}`]},confidence:b})).success?t++:n++}}}return R.info("Cross-domain transfer complete",{transferred:t,skipped:n}),{transferred:t,skipped:n}}var we=`
282
282
  CREATE TABLE IF NOT EXISTS pattern_citations (
283
283
  source_pattern_id TEXT NOT NULL,
284
284
  target_pattern_id TEXT NOT NULL,
@@ -289,7 +289,7 @@ On promotion:
289
289
  );
290
290
  CREATE INDEX IF NOT EXISTS idx_citations_source ON pattern_citations(source_pattern_id);
291
291
  CREATE INDEX IF NOT EXISTS idx_citations_target ON pattern_citations(target_pattern_id);
292
- `,F=class{constructor(e){this.db=e}db;initialized=!1;ensureSchema(){this.initialized||(this.db.exec(Se),this.initialized=!0)}recordCoOccurrence(e,r){this.ensureSchema();let[t,n]=e<r?[e,r]:[r,e];this.db.prepare(`
292
+ `,L=class{constructor(e){this.db=e}db;initialized=!1;ensureSchema(){this.initialized||(this.db.exec(we),this.initialized=!0)}recordCoOccurrence(e,r){this.ensureSchema();let[t,n]=e<r?[e,r]:[r,e];this.db.prepare(`
293
293
  INSERT INTO pattern_citations (source_pattern_id, target_pattern_id, weight, relationship)
294
294
  VALUES (?, ?, 1.0, 'co-occurrence')
295
295
  ON CONFLICT(source_pattern_id, target_pattern_id)
@@ -301,20 +301,20 @@ On promotion:
301
301
  DO UPDATE SET weight = MAX(weight, 2.0), relationship = 'derivation'
302
302
  `).run(e,r)}buildGraph(){this.ensureSchema();let e=this.db.prepare("SELECT source_pattern_id, target_pattern_id, weight, relationship FROM pattern_citations").all(),r=new Set;for(let s of e)r.add(s.source_pattern_id),r.add(s.target_pattern_id);let t=Array.from(r),n=new Map;t.forEach((s,a)=>n.set(s,a));let o=[];for(let s of e){let a=n.get(s.source_pattern_id),c=n.get(s.target_pattern_id);o.push([a,c,s.weight]),s.relationship==="co-occurrence"&&o.push([c,a,s.weight])}return{nodes:t,edges:o}}bootstrapFromExistingData(){this.ensureSchema();let e=0,r=this.db.prepare(`
303
303
  SELECT id, qe_domain FROM qe_patterns WHERE qe_domain IS NOT NULL ORDER BY qe_domain
304
- `).all(),t=new Map;for(let u of r){let l=t.get(u.qe_domain)??[];l.push(u.id),t.set(u.qe_domain,l)}let n=this.db.prepare(`
304
+ `).all(),t=new Map;for(let d of r){let l=t.get(d.qe_domain)??[];l.push(d.id),t.set(d.qe_domain,l)}let n=this.db.prepare(`
305
305
  INSERT OR IGNORE INTO pattern_citations (source_pattern_id, target_pattern_id, weight, relationship)
306
306
  VALUES (?, ?, 1.0, 'co-occurrence')
307
- `),o=this.db.transaction(u=>{for(let[l,m]of u)n.run(l,m).changes>0&&e++}),s=[];for(let[,u]of t){let l=u.slice(0,50);for(let m=0;m<l.length;m++)for(let p=m+1;p<l.length;p++){let[b,y]=l[m]<l[p]?[l[m],l[p]]:[l[p],l[m]];s.push([b,y])}}o(s);let a=this.db.prepare(`
307
+ `),o=this.db.transaction(d=>{for(let[l,m]of d)n.run(l,m).changes>0&&e++}),s=[];for(let[,d]of t){let l=d.slice(0,50);for(let m=0;m<l.length;m++)for(let u=m+1;u<l.length;u++){let[h,b]=l[m]<l[u]?[l[m],l[u]]:[l[u],l[m]];s.push([h,b])}}o(s);let a=this.db.prepare(`
308
308
  SELECT source_pattern_id, target_pattern_id, relationship_type
309
309
  FROM pattern_relationships
310
310
  WHERE relationship_type IN ('merged', 'derived', 'superseded')
311
311
  `).all(),c=this.db.prepare(`
312
312
  INSERT OR IGNORE INTO pattern_citations (source_pattern_id, target_pattern_id, weight, relationship)
313
313
  VALUES (?, ?, 2.0, 'derivation')
314
- `);for(let u of a)c.run(u.source_pattern_id,u.target_pattern_id).changes>0&&e++;return e}getEdgeCount(){return this.ensureSchema(),this.db.prepare("SELECT COUNT(*) as cnt FROM pattern_citations").get().cnt}};var g=T.create("QEReasoningBank"),V=class{constructor(e,r,t={},n){this.memory=e;this.eventBus=r;this.coherenceService=n;this.config={...M,...t},t.rvfDualWriter&&(this.rvfDualWriter=t.rvfDualWriter),this.patternStore=J(e,{embeddingDimension:this.config.embeddingDimension,...t.patternStore})}memory;eventBus;coherenceService;config;embeddingProvenance=new WeakMap;patternStore;initialized=!1;sqliteStore=null;rvfDualWriter=null;getSqliteStore(){return this.sqliteStore||(this.sqliteStore=Y(),this.sqliteStore.initialize().catch(e=>{g.warn("SQLitePatternStore init failed",{error:h(e)})})),this.sqliteStore}setRvfDualWriter(e){this.rvfDualWriter=e}stats={routingRequests:0,totalRoutingConfidence:0,learningOutcomes:0,successfulOutcomes:0};async initialize(e){if(this.initialized)return;let r=e?.signal;r?.throwIfAborted(),await this.patternStore.initialize(),r?.throwIfAborted();try{let t=this.getSqliteStore();await t.initialize(),this.patternStore.setSqliteStore?.(t)}catch(t){g.warn("Failed to wire SQLitePatternStore into PatternStore",{error:h(t)})}r?.throwIfAborted(),this.initialized=!0,await this.loadPretrainedPatterns(r),r?.throwIfAborted();try{let t="reasoning-bank:cross-domain-seeded";if(!await this.memory.get(t))await this.memory.set(t,!0),await this.seedCrossDomainPatterns(r);else{let o=await this.patternStore.getStats();g.info("Cross-domain transfer already complete",{totalPatterns:o.totalPatterns})}}catch(t){if(r?.aborted)throw t;g.warn("Cross-domain seeding failed (non-fatal)",{error:t})}g.info("Initialized")}async loadPretrainedPatterns(e){e?.throwIfAborted();let r=await this.patternStore.getStats();if(r.totalPatterns>0){g.info("Found existing patterns",{totalPatterns:r.totalPatterns});let t=this.patternStore.getAdapter?.();if(t&&(t.status()?.totalVectors??0)===0)try{let n=(()=>{let a=process.env.AQE_RVF_BACKFILL_LIMIT,c=a?Number(a):NaN;return Number.isFinite(c)&&c>0?Math.floor(c):1e3})(),s=this.getSqliteStore().getRecentEmbeddings(n).filter(({embedding:a})=>a&&a.length>0).map(({patternId:a,embedding:c})=>({id:a,vector:c instanceof Float32Array?c:new Float32Array(c)}));if(s.length>0){let{accepted:a,rejected:c}=t.ingest(s);g.info("Backfilled RVF from SQLite",{requested:s.length,accepted:a,cap:n,truncated:s.length>=n}),c>0&&g.warn("RVF backfill partially rejected",{accepted:a,rejected:c})}}catch(n){g.warn("RVF backfill failed (non-fatal)",{error:h(n)})}return}for(let t of A){e?.throwIfAborted();try{await this.storePattern(t)}catch(n){if(e?.aborted)throw n;g.warn("Failed to load pattern",{name:t.name,error:n})}}g.info("Loaded foundational patterns",{count:A.length})}async seedCrossDomainPatterns(e){return this.initialized||await this.initialize({signal:e}),me({searchPatterns:this.searchPatterns.bind(this),storePattern:this.storePattern.bind(this),patternStore:this.patternStore,signal:e})}async storePattern(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return E(new Error("Pattern learning is disabled"));if(!e.embedding){let n=await this.embed(`${e.name} ${e.description} ${e.context?.tags?.join(" ")||""}`);e={...e,embedding:n}}let r=await this.patternStore.create(e),t=r.success?r.value:null;if(!r.success&&r.error instanceof K&&r.error.disposition==="COMMITTED_PENDING_INDEX")try{t=await this.patternStore.get(r.error.patternId)}catch(n){g.warn("Committed pattern lookup failed",{patternId:r.error.patternId,error:h(n)})}if(t){let n=t;if(k().then(o=>o.append("PATTERN_CREATE",{patternId:n.id,domain:n.qeDomain,confidence:n.confidence,name:n.name},"reasoning-bank")).catch(o=>{g.warn("Witness chain PATTERN_CREATE failed",{error:h(o)})}),this.rvfDualWriter&&n.embedding&&n.embedding.length>0)try{this.rvfDualWriter.writePattern(n.id,n.embedding)}catch(o){g.warn("RVF dual-write failed (non-fatal)",{patternId:n.id,error:h(o)})}}return r}async searchPatterns(e,r){this.initialized||await this.initialize();let t=e,n=!0;if(typeof e=="string")if(e.trim()==="")n=!1,t="";else{let o=await this.embed(e);t=this.embeddingProvenance.has(o)?o:e,n=Array.isArray(t)}return this.patternStore.search(t,{...r,textQuery:typeof e=="string"&&e.trim()?e:r?.textQuery,useVectorSearch:n,embeddingSpaceId:typeof e=="string"?Array.isArray(t)?this.embeddingProvenance.get(t):void 0:r?.embeddingSpaceId})}async getPattern(e){return this.initialized||await this.initialize(),this.patternStore.get(e)}async recordOutcome(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return q(void 0);let r=await this.patternStore.recordUsage(e.patternId,e.success,e.metrics,e.feedback);if(r.success){this.stats.learningOutcomes++,e.success&&this.stats.successfulOutcomes++,k().then(o=>o.append("PATTERN_UPDATE",{patternId:e.patternId,success:e.success},"reasoning-bank")).catch(o=>{g.warn("Witness chain PATTERN_UPDATE failed",{error:h(o)})});let t=await this.getPattern(e.patternId),n=this.getPromotionDeps();t&&await pe(t,n)&&(await L(e.patternId,n),g.info("Pattern promoted to long-term",{name:t.name}))}return r}async promotePattern(e){return this.initialized||await this.initialize(),await this.getPattern(e)?L(e,this.getPromotionDeps()):E(new Error(`Pattern not found: ${e}`))}getPromotionDeps(){return{patternStore:this.patternStore,coherenceService:this.coherenceService,eventBus:this.eventBus,coherenceThreshold:this.config.coherenceThreshold||.4,getSqliteStore:this.getSqliteStore.bind(this),rvfDualWriter:this.rvfDualWriter,searchPatterns:this.searchPatterns.bind(this),getPattern:this.getPattern.bind(this)}}async routeTask(e){if(this.initialized||await this.initialize(),!this.config.enableRouting)return E(new Error("Task routing is disabled"));this.stats.routingRequests++;try{let r=e.domain?[e.domain]:C(e.task);r.length===0&&r.push("test-generation");let t=await this.embed(e.task),n=this.embeddingProvenance.get(t),o=await this.patternStore.search(n?t:e.task,{limit:this.config.maxRoutingCandidates,domain:r[0],useVectorSearch:!!n,textQuery:e.task,embeddingSpaceId:n}),s=o.success?o.value.map(d=>d.pattern):[],a=new Map;for(let[d,v]of Object.entries(x)){let P=s.filter(ge=>v.domains.includes(ge.qeDomain)).length;P>0&&a.set(d,P)}let c=ce({taskType:se(e.task),priority:"normal",domain:r[0]}),u=this.buildQValueLookup(c),l=N(r,e.capabilities,a,this.config.routingWeights,x,e.context?.language,u),m=1;try{let d=le(),v=ae({envOverride:process.env.AQE_ROUTER_EXPLORATION_RATE,topologyCritical:d});m=v.safetyMultiplier,oe(l,v.epsilon)}catch{}let p=l[0],b=l.slice(1,4),y=[];if(this.config.enableGuidance&&r.length>0){let d=_(r[0],{framework:e.context?.framework,language:e.context?.language,includeAntiPatterns:!0});y.push(...d.slice(0,5))}this.stats.totalRoutingConfidence+=p.score;let S=l.reduce((d,v)=>d+(v.qWeight??0),0),R=l.length>0?S/l.length:0,f={recommendedAgent:p.agent,confidence:p.score,alternatives:b.map(d=>({agent:d.agent,score:d.score})),domains:r,patterns:s,guidance:y,reasoning:p.reasoning.join("; "),exploration:p.exploration===!0,criticality:m,qWeight:R};return q(ne(e.includePatternGuidance,f,o.success?o.value:[]))}catch(r){return E(W(r))}}buildQValueLookup(e){try{let r=j();if(!r.isInitialized())return()=>{};let t=r.getDatabase();if(!t.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='rl_q_values'").get())return()=>{};let o=t.prepare(`
314
+ `);for(let d of a)c.run(d.source_pattern_id,d.target_pattern_id).changes>0&&e++;return e}getEdgeCount(){return this.ensureSchema(),this.db.prepare("SELECT COUNT(*) as cnt FROM pattern_citations").get().cnt}};var g=A.create("QEReasoningBank"),W=class{constructor(e,r,t={},n){this.memory=e;this.eventBus=r;this.coherenceService=n;this.config={...N,...t},t.rvfDualWriter&&(this.rvfDualWriter=t.rvfDualWriter),this.patternStore=J(e,{embeddingDimension:this.config.embeddingDimension,...t.patternStore})}memory;eventBus;coherenceService;config;embeddingProvenance=new WeakMap;patternStore;initialized=!1;sqliteStore=null;rvfDualWriter=null;getSqliteStore(){return this.sqliteStore||(this.sqliteStore=Y(),this.sqliteStore.initialize().catch(e=>{g.warn("SQLitePatternStore init failed",{error:f(e)})})),this.sqliteStore}setRvfDualWriter(e){this.rvfDualWriter=e}stats={routingRequests:0,totalRoutingConfidence:0,learningOutcomes:0,successfulOutcomes:0};async initialize(e){if(this.initialized)return;let r=e?.signal;r?.throwIfAborted(),await this.patternStore.initialize(),r?.throwIfAborted();try{let t=this.getSqliteStore();await t.initialize(),this.patternStore.setSqliteStore?.(t)}catch(t){g.warn("Failed to wire SQLitePatternStore into PatternStore",{error:f(t)})}r?.throwIfAborted(),this.initialized=!0,await this.loadPretrainedPatterns(r),r?.throwIfAborted();try{let t="reasoning-bank:cross-domain-seeded";if(!await this.memory.get(t))await this.memory.set(t,!0),await this.seedCrossDomainPatterns(r);else{let o=await this.patternStore.getStats();g.info("Cross-domain transfer already complete",{totalPatterns:o.totalPatterns})}}catch(t){if(r?.aborted)throw t;g.warn("Cross-domain seeding failed (non-fatal)",{error:t})}g.info("Initialized")}lastVectorReconcile=null;getLastVectorReconcile(){return this.lastVectorReconcile}reconcileVectorIndex(){let e=this.patternStore.getAdapter?.(),r=T()?.spaceId;if(!e||!r)return null;try{let t=Number(process.env.AQE_RVF_BACKFILL_LIMIT),n=Number.isFinite(t)&&t>0?Math.floor(t):1e3,o=ie(e,this.getSqliteStore(),r,n);return o.missing>0&&g.info("Reconciled RVF index with SQLite vectors",{...o}),this.lastVectorReconcile=o,o}catch(t){return g.warn("RVF reconcile failed (non-fatal)",{error:f(t)}),null}}async loadPretrainedPatterns(e){e?.throwIfAborted();let r=await this.patternStore.getStats();if(r.totalPatterns>0){g.info("Found existing patterns",{totalPatterns:r.totalPatterns});let t=this.patternStore.getAdapter?.();if(t&&(t.status()?.totalVectors??0)===0)try{let n=(()=>{let a=process.env.AQE_RVF_BACKFILL_LIMIT,c=a?Number(a):NaN;return Number.isFinite(c)&&c>0?Math.floor(c):1e3})(),s=this.getSqliteStore().getRecentEmbeddings(n).filter(({embedding:a})=>a&&a.length>0).map(({patternId:a,embedding:c})=>({id:a,vector:c instanceof Float32Array?c:new Float32Array(c)}));if(s.length>0){let{accepted:a,rejected:c}=t.ingest(s);g.info("Backfilled RVF from SQLite",{requested:s.length,accepted:a,cap:n,truncated:s.length>=n}),c>0&&g.warn("RVF backfill partially rejected",{accepted:a,rejected:c})}}catch(n){g.warn("RVF backfill failed (non-fatal)",{error:f(n)})}else t&&this.reconcileVectorIndex();return}for(let t of q){e?.throwIfAborted();try{await this.storePattern(t)}catch(n){if(e?.aborted)throw n;g.warn("Failed to load pattern",{name:t.name,error:n})}}g.info("Loaded foundational patterns",{count:q.length})}async seedCrossDomainPatterns(e){return this.initialized||await this.initialize({signal:e}),ge({searchPatterns:this.searchPatterns.bind(this),storePattern:this.storePattern.bind(this),patternStore:this.patternStore,signal:e})}async storePattern(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return E(new Error("Pattern learning is disabled"));if(!e.embedding){let n=await this.embed(`${e.name} ${e.description} ${e.context?.tags?.join(" ")||""}`);this.embeddingProvenance.has(n)||!!T()?.spaceId?e={...e,embedding:n}:g.debug("No embedding runtime provenance; storing pattern without a vector",{name:e.name})}let r=await this.patternStore.create(e),t=r.success?r.value:null;if(!r.success&&r.error instanceof K&&r.error.disposition==="COMMITTED_PENDING_INDEX")try{t=await this.patternStore.get(r.error.patternId)}catch(n){g.warn("Committed pattern lookup failed",{patternId:r.error.patternId,error:f(n)})}if(t){let n=t;if(k().then(o=>o.append("PATTERN_CREATE",{patternId:n.id,domain:n.qeDomain,confidence:n.confidence,name:n.name},"reasoning-bank")).catch(o=>{g.warn("Witness chain PATTERN_CREATE failed",{error:f(o)})}),this.rvfDualWriter&&n.embedding&&n.embedding.length>0)try{this.rvfDualWriter.writePattern(n.id,n.embedding)}catch(o){g.warn("RVF dual-write failed (non-fatal)",{patternId:n.id,error:f(o)})}}return r}async searchPatterns(e,r){this.initialized||await this.initialize();let t=e,n=!0;if(typeof e=="string")if(e.trim()==="")n=!1,t="";else{let o=await this.embed(e);t=this.embeddingProvenance.has(o)?o:e,n=Array.isArray(t)}return this.patternStore.search(t,{...r,textQuery:typeof e=="string"&&e.trim()?e:r?.textQuery,useVectorSearch:n,embeddingSpaceId:typeof e=="string"?Array.isArray(t)?this.embeddingProvenance.get(t):void 0:r?.embeddingSpaceId})}async getPattern(e){return this.initialized||await this.initialize(),this.patternStore.get(e)}async recordOutcome(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return C(void 0);let r=await this.patternStore.recordUsage(e.patternId,e.success,e.metrics,e.feedback);if(r.success){this.stats.learningOutcomes++,e.success&&this.stats.successfulOutcomes++,k().then(o=>o.append("PATTERN_UPDATE",{patternId:e.patternId,success:e.success},"reasoning-bank")).catch(o=>{g.warn("Witness chain PATTERN_UPDATE failed",{error:f(o)})});let t=await this.getPattern(e.patternId),n=this.getPromotionDeps();t&&await me(t,n)&&(await V(e.patternId,n),g.info("Pattern promoted to long-term",{name:t.name}))}return r}async promotePattern(e){return this.initialized||await this.initialize(),await this.getPattern(e)?V(e,this.getPromotionDeps()):E(new Error(`Pattern not found: ${e}`))}getPromotionDeps(){return{patternStore:this.patternStore,coherenceService:this.coherenceService,eventBus:this.eventBus,coherenceThreshold:this.config.coherenceThreshold||.4,getSqliteStore:this.getSqliteStore.bind(this),rvfDualWriter:this.rvfDualWriter,searchPatterns:this.searchPatterns.bind(this),getPattern:this.getPattern.bind(this)}}async routeTask(e){if(this.initialized||await this.initialize(),!this.config.enableRouting)return E(new Error("Task routing is disabled"));this.stats.routingRequests++;try{let r=e.domain?[e.domain]:D(e.task);r.length===0&&r.push("test-generation");let t=await this.embed(e.task),n=this.embeddingProvenance.get(t),o=await this.patternStore.search(n?t:e.task,{limit:this.config.maxRoutingCandidates,domain:r[0],useVectorSearch:!!n,textQuery:e.task,embeddingSpaceId:n}),s=o.success?o.value.map(p=>p.pattern):[],a=new Map;for(let[p,v]of Object.entries(x)){let P=s.filter(fe=>v.domains.includes(fe.qeDomain)).length;P>0&&a.set(p,P)}let c=le({taskType:ce(e.task),priority:"normal",domain:r[0]}),d=this.buildQValueLookup(c),l=Q(r,e.capabilities,a,this.config.routingWeights,x,e.context?.language,d),m=1;try{let p=ue(),v=oe({envOverride:process.env.AQE_ROUTER_EXPLORATION_RATE,topologyCritical:p});m=v.safetyMultiplier,se(l,v.epsilon)}catch{}let u=l[0],h=l.slice(1,4),b=[];if(this.config.enableGuidance&&r.length>0){let p=_(r[0],{framework:e.context?.framework,language:e.context?.language,includeAntiPatterns:!0});b.push(...p.slice(0,5))}this.stats.totalRoutingConfidence+=u.score;let S=l.reduce((p,v)=>p+(v.qWeight??0),0),w=l.length>0?S/l.length:0,y={recommendedAgent:u.agent,confidence:u.score,alternatives:h.map(p=>({agent:p.agent,score:p.score})),domains:r,patterns:s,guidance:b,reasoning:u.reasoning.join("; "),exploration:u.exploration===!0,criticality:m,qWeight:w};return C(ne(e.includePatternGuidance,y,o.success?o.value:[]))}catch(r){return E(B(r))}}buildQValueLookup(e){try{let r=U();if(!r.isInitialized())return()=>{};let t=r.getDatabase();if(!t.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='rl_q_values'").get())return()=>{};let o=t.prepare(`
315
315
  SELECT q_value, visits FROM rl_q_values
316
316
  WHERE algorithm = 'q-learning'
317
317
  AND agent_id = 'aqe-hook-router'
318
318
  AND state_key = ?
319
319
  AND action_key = ?
320
- `);return s=>{try{let a=o.get(e,s);return a?{qValue:a.q_value,visits:a.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return D(e)}generateContext(e,r){return I(e,r||{})}checkAntiPatterns(e,r){return X(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-GZV4VKK4.js"),t=await r(e);if(t.length!==this.config.embeddingDimension)return ue(t,this.config.embeddingDimension);let n=U()?.spaceId;return n&&this.embeddingProvenance.set(t,n),t}catch(r){let{isUsingEndpoint:t}=await import("./real-embeddings-GZV4VKK4.js");if(t())throw r;process.env.DEBUG&&g.warn("ONNX embeddings unavailable, using hash fallback",{error:h(r)})}return de(e,this.config.embeddingDimension)}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let a of H)r[a]=e.byDomain[a]||0;let t=this.stats.routingRequests,n=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,o=this.stats.learningOutcomes,s=this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0;try{let a=this.getSqliteStore().getAggregateOutcomeStats();a.routingRequests>t&&(t=a.routingRequests,n=a.avgRoutingConfidence),a.learningOutcomes>o&&(o=a.learningOutcomes,s=a.learningOutcomes>0?a.successfulOutcomes/a.learningOutcomes:a.avgPatternSuccessRate)}catch{}return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:n,learningOutcomes:o,patternSuccessRate:s,patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function Et(i,e,r,t){return new V(i,e,r,t)}export{M as a,A as b,x as c,se as d,N as e,Q as f,V as g,Et as h};
320
+ `);return s=>{try{let a=o.get(e,s);return a?{qValue:a.q_value,visits:a.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return I(e)}generateContext(e,r){return M(e,r||{})}checkAntiPatterns(e,r){return X(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-4QLQZDB5.js"),t=await r(e);if(t.length!==this.config.embeddingDimension)return de(t,this.config.embeddingDimension);let n=T()?.spaceId;return n&&this.embeddingProvenance.set(t,n),t}catch(r){let{isUsingEndpoint:t}=await import("./real-embeddings-4QLQZDB5.js");if(t())throw r;process.env.DEBUG&&g.warn("ONNX embeddings unavailable, using hash fallback",{error:f(r)})}return pe(e,this.config.embeddingDimension)}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let a of H)r[a]=e.byDomain[a]||0;let t=this.stats.routingRequests,n=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,o=this.stats.learningOutcomes,s=this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0;try{let a=this.getSqliteStore().getAggregateOutcomeStats();a.routingRequests>t&&(t=a.routingRequests,n=a.avgRoutingConfidence),a.learningOutcomes>o&&(o=a.learningOutcomes,s=a.learningOutcomes>0?a.successfulOutcomes/a.learningOutcomes:a.avgPatternSuccessRate)}catch{}return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:n,learningOutcomes:o,patternSuccessRate:s,patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function At(i,e,r,t){return new W(i,e,r,t)}export{N as a,q as b,x as c,ce as d,Q as e,O as f,W as g,At as h};
@@ -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.5");process.exit(0)}
2
- import{b as u}from"./chunk-HLFDC4SF.js";function t(){return{...e}}function o(r){e={...e,...r}}function i(){e={...s}}function a(){return e.useBrowserMode}function E(){return e.useScreenshotCapture}function l(){return e.useVisualRegression}function c(){return e.useE2EExecution}function f(){return e.defaultHeadless}function d(){return e.useAutoRetry}function _(){return e.logPerformanceMetrics}function I(){return e.useAxeCore}function p(){let r={};process.env.VIBIUM_USE_BROWSER_MODE!==void 0&&(r.useBrowserMode=process.env.VIBIUM_USE_BROWSER_MODE==="true"),process.env.VIBIUM_USE_SCREENSHOT_CAPTURE!==void 0&&(r.useScreenshotCapture=process.env.VIBIUM_USE_SCREENSHOT_CAPTURE==="true"),process.env.VIBIUM_USE_VISUAL_REGRESSION!==void 0&&(r.useVisualRegression=process.env.VIBIUM_USE_VISUAL_REGRESSION==="true"),process.env.VIBIUM_USE_E2E_EXECUTION!==void 0&&(r.useE2EExecution=process.env.VIBIUM_USE_E2E_EXECUTION==="true"),process.env.VIBIUM_DEFAULT_HEADLESS!==void 0&&(r.defaultHeadless=process.env.VIBIUM_DEFAULT_HEADLESS==="true"),process.env.VIBIUM_USE_AUTO_RETRY!==void 0&&(r.useAutoRetry=process.env.VIBIUM_USE_AUTO_RETRY==="true"),process.env.VIBIUM_LOG_PERFORMANCE_METRICS!==void 0&&(r.logPerformanceMetrics=process.env.VIBIUM_LOG_PERFORMANCE_METRICS==="true"),process.env.VIBIUM_USE_AXE_CORE!==void 0&&(r.useAxeCore=process.env.VIBIUM_USE_AXE_CORE==="true"),o(r)}function U(){o({defaultHeadless:!0,useAutoRetry:!0,logPerformanceMetrics:!0})}function R(){o({defaultHeadless:!1,logPerformanceMetrics:!0})}function S(){o({useBrowserMode:!1,useScreenshotCapture:!1,useVisualRegression:!1,useE2EExecution:!1,useAxeCore:!1})}var s,e,n=u(()=>{s={useBrowserMode:!0,useScreenshotCapture:!0,useVisualRegression:!0,useE2EExecution:!0,defaultHeadless:!1,useAutoRetry:!0,logPerformanceMetrics:!0,useAxeCore:!0},e={...s}});export{s as a,t as b,o as c,i as d,a as e,E as f,l as g,c as h,f as i,d as j,_ as k,I as l,p as m,U as n,R as o,S as p,n as q};
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.7");process.exit(0)}
2
+ import{b as u}from"./chunk-HSDOOFV7.js";function t(){return{...e}}function o(r){e={...e,...r}}function i(){e={...s}}function a(){return e.useBrowserMode}function E(){return e.useScreenshotCapture}function l(){return e.useVisualRegression}function c(){return e.useE2EExecution}function f(){return e.defaultHeadless}function d(){return e.useAutoRetry}function _(){return e.logPerformanceMetrics}function I(){return e.useAxeCore}function p(){let r={};process.env.VIBIUM_USE_BROWSER_MODE!==void 0&&(r.useBrowserMode=process.env.VIBIUM_USE_BROWSER_MODE==="true"),process.env.VIBIUM_USE_SCREENSHOT_CAPTURE!==void 0&&(r.useScreenshotCapture=process.env.VIBIUM_USE_SCREENSHOT_CAPTURE==="true"),process.env.VIBIUM_USE_VISUAL_REGRESSION!==void 0&&(r.useVisualRegression=process.env.VIBIUM_USE_VISUAL_REGRESSION==="true"),process.env.VIBIUM_USE_E2E_EXECUTION!==void 0&&(r.useE2EExecution=process.env.VIBIUM_USE_E2E_EXECUTION==="true"),process.env.VIBIUM_DEFAULT_HEADLESS!==void 0&&(r.defaultHeadless=process.env.VIBIUM_DEFAULT_HEADLESS==="true"),process.env.VIBIUM_USE_AUTO_RETRY!==void 0&&(r.useAutoRetry=process.env.VIBIUM_USE_AUTO_RETRY==="true"),process.env.VIBIUM_LOG_PERFORMANCE_METRICS!==void 0&&(r.logPerformanceMetrics=process.env.VIBIUM_LOG_PERFORMANCE_METRICS==="true"),process.env.VIBIUM_USE_AXE_CORE!==void 0&&(r.useAxeCore=process.env.VIBIUM_USE_AXE_CORE==="true"),o(r)}function U(){o({defaultHeadless:!0,useAutoRetry:!0,logPerformanceMetrics:!0})}function R(){o({defaultHeadless:!1,logPerformanceMetrics:!0})}function S(){o({useBrowserMode:!1,useScreenshotCapture:!1,useVisualRegression:!1,useE2EExecution:!1,useAxeCore:!1})}var s,e,n=u(()=>{s={useBrowserMode:!0,useScreenshotCapture:!0,useVisualRegression:!0,useE2EExecution:!0,defaultHeadless:!1,useAutoRetry:!0,logPerformanceMetrics:!0,useAxeCore:!0},e={...s}});export{s as a,t as b,o as c,i as d,a as e,E as f,l as g,c as h,f as i,d as j,_ as k,I as l,p as m,U as n,R as o,S as p,n as q};
@@ -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.5");process.exit(0)}
2
- import{d as g,e as S,p as E,q as _}from"./chunk-EAYQCBXL.js";function R(i,e){return{ingest(t){i.ingest(t)},search(t,r){return i.search(t,r).map(s=>({id:s.id,score:s.score}))},delete(t){i.delete(t)},status(){let t=i.status();return{totalVectors:t.totalVectors,dimensions:e,totalSegments:t.totalSegments,fileSizeBytes:t.fileSizeBytes,epoch:t.epoch,witnessValid:t.witnessValid,witnessEntries:t.witnessEntries}},close(){i.close()},compact(){return i.compact()}}}function f(i,e){return(i.prepare("SELECT COUNT(*) as cnt FROM sqlite_master WHERE type='table' AND name=?").get(e)?.cnt??0)>0}function m(i,e,t){return i.prepare(`PRAGMA table_info(${e})`).all().some(s=>s.name===t)}var h=class{db;config;rvfStore=null;rvfAvailable=!1;constructor(e,t){this.db=e,this.config={...t,dimensions:t.dimensions??384},f(this.db,"qe_pattern_embeddings")&&!m(this.db,"qe_pattern_embeddings","space_id")&&(this.db.exec("ALTER TABLE qe_pattern_embeddings ADD COLUMN space_id TEXT"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_qe_pattern_embeddings_space ON qe_pattern_embeddings(space_id)"))}activeSpaceId(){return this.config.embeddingSpaceId??E()?.spaceId}async initialize(){if(this.config.mode==="sqlite-only"){this.rvfAvailable=!1;return}try{let e=await import("./rvf-native-adapter-KOXR7TJL.js");if(!e.isRvfNativeAvailable()){this.rvfAvailable=!1;return}if(this.activeSpaceId()||await _(),!this.activeSpaceId()){this.rvfAvailable=!1,g();return}let{isRvfLockHeldError:t,removeStaleRvfLock:r,quarantineUnusableStore:s}=await import("./rvf-store-integrity-UGUXKIFX.js"),l=()=>{try{return{store:e.openRvfStore(this.config.rvfPath),error:null}}catch(o){return{store:null,error:o}}},{store:n,error:a}=l();if(!n&&t(a)&&(!r(this.config.rvfPath)||({store:n,error:a}=l(),!n&&t(a))))throw a;if(!n)try{n=e.createRvfStore(this.config.rvfPath,this.config.dimensions)}catch(o){if({store:n,error:a}=l(),!n){if(t(a))throw a;if(!s(this.config.rvfPath,o instanceof Error?o.message:String(o),a))throw o;n=e.createRvfStore(this.config.rvfPath,this.config.dimensions)}}this.rvfStore=R(n,this.config.dimensions),S(this.config.rvfPath,this.activeSpaceId()??null,this.rvfStore.status().totalVectors),this.rvfAvailable=!0}catch(e){try{this.rvfStore?.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1,console.warn(`[RVF] Dual-writer disabled for ${this.config.rvfPath}; falling back to SQLite: ${e instanceof Error?e.message:String(e)}`)}}setRvfStore(e){this.rvfStore=e,this.rvfAvailable=!0}writePattern(e,t){let r={sqliteSuccess:!1,rvfSuccess:!1};if(!m(this.db,"qe_pattern_embeddings","space_id")||!this.activeSpaceId())return{...r,divergence:"VECTOR_SPACE_UNVERIFIED"};try{this.writeSqliteEmbedding(e,t),r.sqliteSuccess=!0}catch{r.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.ingest([{id:e,vector:t instanceof Float32Array?Array.from(t):t}]),r.rvfSuccess=!0}catch{r.rvfSuccess=!1,r.divergence="rvf-write-failed"}return r}deletePattern(e){let t={sqliteSuccess:!1,rvfSuccess:!1};try{this.deleteSqliteEmbedding(e),t.sqliteSuccess=!0}catch{t.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.delete([e]),t.rvfSuccess=!0}catch{t.rvfSuccess=!1,t.divergence="rvf-delete-failed"}return t}search(e,t){if(!this.hasCompatibleEmbeddingSpace())return[];if(this.config.mode==="rvf-primary"&&this.rvfAvailable&&this.rvfStore)try{return this.rvfStore.search(e,t)}catch{}return this.searchSqlite(e,t)}getDivergenceReport(){let e={totalChecked:0,divergences:0,details:[]},t=this.getSqliteEmbeddingCount();if(e.totalChecked=t,!this.rvfAvailable||!this.rvfStore)return this.config.mode!=="sqlite-only"&&t>0&&(e.divergences=1,e.details.push({patternId:"*",issue:"count-mismatch"})),e;let s=this.rvfStore.status().totalVectors;return t!==s&&(e.divergences=1,e.details.push({patternId:"*",issue:"count-mismatch"})),e}isPromotionSafe(){return this.getDivergenceReport().divergences===0}status(){let e=this.getSqlitePatternCount(),t=this.getSqliteEmbeddingCount(),r=null;if(this.rvfAvailable&&this.rvfStore)try{r=this.rvfStore.status()}catch{r=null}return{sqlite:{patternCount:e,vectorCount:t},rvf:r,mode:this.config.mode}}close(){if(this.rvfStore){try{this.rvfStore.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1}}compact(){if(!this.rvfStore||!this.rvfAvailable||!this.rvfStore.compact)return null;try{return this.rvfStore.compact()??null}catch{return null}}shouldWriteRvf(){return(this.config.mode==="dual-write"||this.config.mode==="rvf-primary")&&this.rvfAvailable&&this.rvfStore!==null}hasCompatibleEmbeddingSpace(){if(!m(this.db,"qe_pattern_embeddings","space_id"))return!1;let e=this.activeSpaceId();return e?(this.db.prepare(`
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.7");process.exit(0)}
2
+ import{d as g,e as S,p as E,q as _}from"./chunk-C2MDBBFF.js";function R(i,e){return{ingest(t){i.ingest(t)},search(t,r){return i.search(t,r).map(s=>({id:s.id,score:s.score}))},delete(t){i.delete(t)},status(){let t=i.status();return{totalVectors:t.totalVectors,dimensions:e,totalSegments:t.totalSegments,fileSizeBytes:t.fileSizeBytes,epoch:t.epoch,witnessValid:t.witnessValid,witnessEntries:t.witnessEntries}},close(){i.close()},compact(){return i.compact()}}}function f(i,e){return(i.prepare("SELECT COUNT(*) as cnt FROM sqlite_master WHERE type='table' AND name=?").get(e)?.cnt??0)>0}function m(i,e,t){return i.prepare(`PRAGMA table_info(${e})`).all().some(s=>s.name===t)}var h=class{db;config;rvfStore=null;rvfAvailable=!1;constructor(e,t){this.db=e,this.config={...t,dimensions:t.dimensions??384},f(this.db,"qe_pattern_embeddings")&&!m(this.db,"qe_pattern_embeddings","space_id")&&(this.db.exec("ALTER TABLE qe_pattern_embeddings ADD COLUMN space_id TEXT"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_qe_pattern_embeddings_space ON qe_pattern_embeddings(space_id)"))}activeSpaceId(){return this.config.embeddingSpaceId??E()?.spaceId}async initialize(){if(this.config.mode==="sqlite-only"){this.rvfAvailable=!1;return}try{let e=await import("./rvf-native-adapter-UXI66OQJ.js");if(!e.isRvfNativeAvailable()){this.rvfAvailable=!1;return}if(this.activeSpaceId()||await _(),!this.activeSpaceId()){this.rvfAvailable=!1,g();return}let{isRvfLockHeldError:t,removeStaleRvfLock:r,quarantineUnusableStore:s}=await import("./rvf-store-integrity-PKDVXQAW.js"),l=()=>{try{return{store:e.openRvfStore(this.config.rvfPath),error:null}}catch(o){return{store:null,error:o}}},{store:n,error:a}=l();if(!n&&t(a)&&(!r(this.config.rvfPath)||({store:n,error:a}=l(),!n&&t(a))))throw a;if(!n)try{n=e.createRvfStore(this.config.rvfPath,this.config.dimensions)}catch(o){if({store:n,error:a}=l(),!n){if(t(a))throw a;if(!s(this.config.rvfPath,o instanceof Error?o.message:String(o),a))throw o;n=e.createRvfStore(this.config.rvfPath,this.config.dimensions)}}this.rvfStore=R(n,this.config.dimensions),S(this.config.rvfPath,this.activeSpaceId()??null,this.rvfStore.status().totalVectors),this.rvfAvailable=!0}catch(e){try{this.rvfStore?.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1,console.warn(`[RVF] Dual-writer disabled for ${this.config.rvfPath}; falling back to SQLite: ${e instanceof Error?e.message:String(e)}`)}}setRvfStore(e){this.rvfStore=e,this.rvfAvailable=!0}writePattern(e,t){let r={sqliteSuccess:!1,rvfSuccess:!1};if(!m(this.db,"qe_pattern_embeddings","space_id")||!this.activeSpaceId())return{...r,divergence:"VECTOR_SPACE_UNVERIFIED"};try{this.writeSqliteEmbedding(e,t),r.sqliteSuccess=!0}catch{r.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.ingest([{id:e,vector:t instanceof Float32Array?Array.from(t):t}]),r.rvfSuccess=!0}catch{r.rvfSuccess=!1,r.divergence="rvf-write-failed"}return r}deletePattern(e){let t={sqliteSuccess:!1,rvfSuccess:!1};try{this.deleteSqliteEmbedding(e),t.sqliteSuccess=!0}catch{t.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.delete([e]),t.rvfSuccess=!0}catch{t.rvfSuccess=!1,t.divergence="rvf-delete-failed"}return t}search(e,t){if(!this.hasCompatibleEmbeddingSpace())return[];if(this.config.mode==="rvf-primary"&&this.rvfAvailable&&this.rvfStore)try{return this.rvfStore.search(e,t)}catch{}return this.searchSqlite(e,t)}getDivergenceReport(){let e={totalChecked:0,divergences:0,details:[]},t=this.getSqliteEmbeddingCount();if(e.totalChecked=t,!this.rvfAvailable||!this.rvfStore)return this.config.mode!=="sqlite-only"&&t>0&&(e.divergences=1,e.details.push({patternId:"*",issue:"count-mismatch"})),e;let s=this.rvfStore.status().totalVectors;return t!==s&&(e.divergences=1,e.details.push({patternId:"*",issue:"count-mismatch"})),e}isPromotionSafe(){return this.getDivergenceReport().divergences===0}status(){let e=this.getSqlitePatternCount(),t=this.getSqliteEmbeddingCount(),r=null;if(this.rvfAvailable&&this.rvfStore)try{r=this.rvfStore.status()}catch{r=null}return{sqlite:{patternCount:e,vectorCount:t},rvf:r,mode:this.config.mode}}close(){if(this.rvfStore){try{this.rvfStore.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1}}compact(){if(!this.rvfStore||!this.rvfAvailable||!this.rvfStore.compact)return null;try{return this.rvfStore.compact()??null}catch{return null}}shouldWriteRvf(){return(this.config.mode==="dual-write"||this.config.mode==="rvf-primary")&&this.rvfAvailable&&this.rvfStore!==null}hasCompatibleEmbeddingSpace(){if(!m(this.db,"qe_pattern_embeddings","space_id"))return!1;let e=this.activeSpaceId();return e?(this.db.prepare(`
3
3
  SELECT COUNT(*) AS incompatible
4
4
  FROM qe_pattern_embeddings
5
5
  WHERE space_id IS NULL OR space_id <> ?
@@ -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.5");process.exit(0)}
2
- import{a as _}from"./chunk-WR64BKUE.js";import{a as w}from"./chunk-3SH23PS3.js";import{d as k,f as q}from"./chunk-JANLATHN.js";import{o as M,s as U}from"./chunk-EOR3RECZ.js";import{b as f,d as P}from"./chunk-RUSLEOMC.js";import{a as g,e as F}from"./chunk-NLDFNAOS.js";import{a as R}from"./chunk-HLFDC4SF.js";import{randomUUID as Q}from"crypto";U();P();F();var x={alpha:.1,minOutcomes:10,weightFloor:.2,weightCeiling:2},p=class{records=new Map;config;constructor(e){this.config={...x,...e}}recordOutcome(e,t,o){let{alpha:i,minOutcomes:r,weightFloor:s,weightCeiling:n}=this.config,c=this.records.get(e),d=t?1:0,a=Math.max(0,Math.min(1,o)),l,u;c?(l=i*d+(1-i)*c.emaAccuracy,u=i*a+(1-i)*c.emaQuality):(l=d,u=a);let h=(c?.totalOutcomes??0)+1,C;h>=r?C=Math.max(s,Math.min(n,l*2)):C=1;let S={agentId:e,emaAccuracy:l,emaQuality:u,calibratedWeight:C,totalOutcomes:h,lastUpdated:new Date};return this.records.set(e,S),S}getCalibration(e){return this.records.get(e)??null}getCalibratedWeight(e){let t=this.records.get(e);return!t||t.totalOutcomes<this.config.minOutcomes?1:t.calibratedWeight}getAllCalibrations(){return Array.from(this.records.values())}reset(e){e!==void 0?this.records.delete(e):this.records.clear()}serialize(){let e={};for(let[t,o]of this.records)e[t]={...o};return e}deserialize(e){this.records.clear();for(let[t,o]of Object.entries(e))this.records.set(t,{...o,lastUpdated:new Date(o.lastUpdated)})}};var D={escalateAfterFailures:2,deEscalateAfterSuccesses:5,maxTier:"opus",minTier:"haiku"},I=["booster","haiku","sonnet","opus"],b=class{config;tierOrder;states=new Map;constructor(e){this.config={...D,...e},this.tierOrder=this.config.tierOrder??I}tierIndex(e){return this.tierOrder.indexOf(e)}recordOutcome(e,t,o){let i=this.states.get(e);i||(i={agentId:e,currentTier:o,baseTier:o,consecutiveFailures:0,consecutiveSuccesses:0,escalationCount:0,deEscalationCount:0,lastAction:"none",lastActionTimestamp:new Date},this.states.set(e,i));let r=i.currentTier;if(t){if(i.consecutiveSuccesses++,i.consecutiveFailures=0,i.consecutiveSuccesses>=this.config.deEscalateAfterSuccesses){let s=this.tierIndex(i.currentTier),n=this.tierIndex(this.config.minTier);if(s>n)return i.currentTier=this.tierOrder[s-1],i.deEscalationCount++,i.consecutiveSuccesses=0,i.lastAction="de-escalate",i.lastActionTimestamp=new Date,{action:"de-escalate",previousTier:r,newTier:i.currentTier}}}else if(i.consecutiveFailures++,i.consecutiveSuccesses=0,i.consecutiveFailures>=this.config.escalateAfterFailures){let s=this.tierIndex(i.currentTier),n=this.tierIndex(this.config.maxTier);if(s>=0&&s<n)return i.currentTier=this.tierOrder[s+1],i.escalationCount++,i.consecutiveFailures=0,i.lastAction="escalate",i.lastActionTimestamp=new Date,{action:"escalate",previousTier:r,newTier:i.currentTier}}return{action:"none",previousTier:r,newTier:i.currentTier}}getCurrentTier(e){return this.states.get(e)?.currentTier??null}getState(e){return this.states.get(e)??null}getAllStates(){return Array.from(this.states.values())}reset(e){e?this.states.delete(e):this.states.clear()}};var T={booster:{avgInputTokens:0,avgOutputTokens:0,costPerTask:0},haiku:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.0035},sonnet:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.021},opus:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.105}},v=["booster","haiku","sonnet","opus"],y=T.opus.costPerTask,L={qualityWeight:.6,costWeight:.4,budgetPerHourUsd:0,budgetPerDayUsd:0,minQualityThreshold:.5,enabled:!0},N=.15,E=class{config;costTracker;tierQualityEstimates=new Map;tierOutcomeCounts=new Map;constructor(e,t){let o={...L,...t};o.qualityWeight=Math.max(0,Math.min(1,o.qualityWeight)),o.costWeight=Math.max(0,Math.min(1,o.costWeight)),o.minQualityThreshold=Math.max(0,Math.min(1,o.minQualityThreshold)),o.budgetPerHourUsd=Math.max(0,o.budgetPerHourUsd),o.budgetPerDayUsd=Math.max(0,o.budgetPerDayUsd);let i=o.qualityWeight+o.costWeight;i>0&&i!==1&&(o.qualityWeight/=i,o.costWeight/=i),this.config=o,this.costTracker=e,this.tierQualityEstimates.set("booster",.3),this.tierQualityEstimates.set("haiku",.55),this.tierQualityEstimates.set("sonnet",.75),this.tierQualityEstimates.set("opus",.9)}scoreTiers(e){let t=v.map(o=>{let i=this.getQualityEstimate(o,e),r=T[o].costPerTask,s=r>0?i/r:i>0?1/0:0,n=y>0?1-r/y:1,c=this.config.qualityWeight*i+this.config.costWeight*n;return{tier:o,qualityScore:i,estimatedCostUsd:r,qualityPerDollar:s,economicScore:c}});return t.sort((o,i)=>i.economicScore-o.economicScore),t}selectTier(e){let t=this.scoreTiers(e);for(let r of t)if(!(r.qualityScore<this.config.minQualityThreshold)&&!this.wouldExceedBudget(r.tier))return{tier:r.tier,reason:`Best economic score (${r.economicScore.toFixed(3)}): quality=${r.qualityScore.toFixed(2)}, cost=$${r.estimatedCostUsd.toFixed(4)}`,scores:t};let o=t.filter(r=>r.qualityScore>=this.config.minQualityThreshold);if(o.length>0){let r=[...o].sort((s,n)=>s.estimatedCostUsd-n.estimatedCostUsd)[0];return{tier:r.tier,reason:`Budget constrained fallback to ${r.tier}`,scores:t}}let i=[...t].sort((r,s)=>s.qualityScore-r.qualityScore)[0];return{tier:i.tier,reason:`No tier meets quality threshold ${this.config.minQualityThreshold}; using best quality: ${i.tier}`,scores:t}}wouldExceedBudget(e){let t=T[e].costPerTask;if(t===0)return!1;let o=this.costTracker.getCurrentCost("hour"),i=this.costTracker.getCurrentCost("day");return this.config.budgetPerHourUsd>0&&o+t>this.config.budgetPerHourUsd||this.config.budgetPerDayUsd>0&&i+t>this.config.budgetPerDayUsd}updateFromOutcome(e,t){let o=e.outcome.qualityScore,i=this.tierQualityEstimates.get(t)??.5,r=this.tierOutcomeCounts.get(t)??0,s=r<5?.4:N,n=i*(1-s)+o*s;this.tierQualityEstimates.set(t,n),this.tierOutcomeCounts.set(t,r+1)}getEconomicReport(){let e=this.scoreTiers(.5),t=this.costTracker.getCurrentCost("hour"),o=this.costTracker.getCurrentCost("day"),i={hourly:this.config.budgetPerHourUsd>0?Math.max(0,this.config.budgetPerHourUsd-t):null,daily:this.config.budgetPerDayUsd>0?Math.max(0,this.config.budgetPerDayUsd-o):null},r=null,s=[...e].sort((a,l)=>l.qualityPerDollar-a.qualityPerDollar),n=s.find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar)),c=[...s].reverse().find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar));if(n&&c&&n.tier!==c.tier){let a=c.estimatedCostUsd-n.estimatedCostUsd;a>0&&(r={usd:a,description:`Switch from ${c.tier} ($${c.estimatedCostUsd.toFixed(4)}/task) to ${n.tier} ($${n.estimatedCostUsd.toFixed(4)}/task) for comparable tasks to save ~$${a.toFixed(4)}/task`})}let d=this.generateRecommendation(e,i);return{tierEfficiency:e,currentHourlyCostUsd:t,currentDailyCostUsd:o,budgetRemaining:i,recommendation:d,savingsOpportunity:r}}computeCostAdjustedReward(e,t,o){let i=T[t].costPerTask;if(y===0)return e;let r=i/y,s=Math.max(0,o-this.config.minQualityThreshold),n=r*(1-s),c=e-n*this.config.costWeight;return Math.max(-1,Math.min(1,c))}serializeEstimates(){let e={};for(let t of v)e[t]={quality:this.tierQualityEstimates.get(t)??.5,count:this.tierOutcomeCounts.get(t)??0};return e}deserializeEstimates(e){for(let t of v)e[t]&&(this.tierQualityEstimates.set(t,e[t].quality),this.tierOutcomeCounts.set(t,e[t].count))}getConfig(){return{...this.config}}getQualityEstimate(e,t){let o=this.tierQualityEstimates.get(e)??.5,i=e==="booster"?t*.4:e==="haiku"?t*.2:0;return Math.max(0,Math.min(1,o-i))}generateRecommendation(e,t){if(t.hourly!==null&&t.hourly<.01)return"Hourly budget nearly exhausted. Consider increasing budget or routing to cheaper tiers.";if(t.daily!==null&&t.daily<.1)return"Daily budget nearly exhausted. Only critical tasks should use expensive tiers.";let o=e[0];return o?`Most cost-efficient tier: ${o.tier} (score=${o.economicScore.toFixed(3)}, quality=${o.qualityScore.toFixed(2)})`:"No economic data available yet."}};q();var A=class{outcomes=[];maxOutcomes;constructor(e=1e4){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getByAgent(e,t=100){return this.outcomes.filter(o=>o.usedAgent===e).slice(-t)}getAll(e=1e3){return this.outcomes.slice(-e)}getRecentOverrides(e=50){return this.outcomes.filter(t=>!t.followedRecommendation).slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},O=class m{static schemaMigrated=!1;outcomeStore;router=null;db=null;calibrator=null;escalationTracker=null;economicModel=null;economicPersistCounter=0;static ECONOMIC_PERSIST_INTERVAL=10;persistCount=0;maxOutcomes;static RETENTION_CLEANUP_INTERVAL=100;constructor(e=1e4,t){this.maxOutcomes=e,this.outcomeStore=new A(e),t?.enableEMACalibration&&this.enableCalibration(),t?.enableAutoEscalation&&this.enableAutoEscalation()}async initialize(){try{this.db=M(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb(),this.loadCalibratorState()}catch(e){console.warn("[RoutingFeedbackCollector] DB init failed, using memory-only:",g(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
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.7");process.exit(0)}
2
+ import{a as _}from"./chunk-MJJC6HUK.js";import{a as w}from"./chunk-WUV5RZUI.js";import{d as k,f as q}from"./chunk-V5NGBQAQ.js";import{o as M,s as U}from"./chunk-ZLVQSEZK.js";import{b as f,d as P}from"./chunk-4G2VNW4C.js";import{a as g,e as F}from"./chunk-LVEX4GID.js";import{a as R}from"./chunk-HSDOOFV7.js";import{randomUUID as Q}from"crypto";U();P();F();var x={alpha:.1,minOutcomes:10,weightFloor:.2,weightCeiling:2},p=class{records=new Map;config;constructor(e){this.config={...x,...e}}recordOutcome(e,t,o){let{alpha:i,minOutcomes:r,weightFloor:s,weightCeiling:n}=this.config,c=this.records.get(e),d=t?1:0,a=Math.max(0,Math.min(1,o)),l,u;c?(l=i*d+(1-i)*c.emaAccuracy,u=i*a+(1-i)*c.emaQuality):(l=d,u=a);let h=(c?.totalOutcomes??0)+1,C;h>=r?C=Math.max(s,Math.min(n,l*2)):C=1;let S={agentId:e,emaAccuracy:l,emaQuality:u,calibratedWeight:C,totalOutcomes:h,lastUpdated:new Date};return this.records.set(e,S),S}getCalibration(e){return this.records.get(e)??null}getCalibratedWeight(e){let t=this.records.get(e);return!t||t.totalOutcomes<this.config.minOutcomes?1:t.calibratedWeight}getAllCalibrations(){return Array.from(this.records.values())}reset(e){e!==void 0?this.records.delete(e):this.records.clear()}serialize(){let e={};for(let[t,o]of this.records)e[t]={...o};return e}deserialize(e){this.records.clear();for(let[t,o]of Object.entries(e))this.records.set(t,{...o,lastUpdated:new Date(o.lastUpdated)})}};var D={escalateAfterFailures:2,deEscalateAfterSuccesses:5,maxTier:"opus",minTier:"haiku"},I=["booster","haiku","sonnet","opus"],b=class{config;tierOrder;states=new Map;constructor(e){this.config={...D,...e},this.tierOrder=this.config.tierOrder??I}tierIndex(e){return this.tierOrder.indexOf(e)}recordOutcome(e,t,o){let i=this.states.get(e);i||(i={agentId:e,currentTier:o,baseTier:o,consecutiveFailures:0,consecutiveSuccesses:0,escalationCount:0,deEscalationCount:0,lastAction:"none",lastActionTimestamp:new Date},this.states.set(e,i));let r=i.currentTier;if(t){if(i.consecutiveSuccesses++,i.consecutiveFailures=0,i.consecutiveSuccesses>=this.config.deEscalateAfterSuccesses){let s=this.tierIndex(i.currentTier),n=this.tierIndex(this.config.minTier);if(s>n)return i.currentTier=this.tierOrder[s-1],i.deEscalationCount++,i.consecutiveSuccesses=0,i.lastAction="de-escalate",i.lastActionTimestamp=new Date,{action:"de-escalate",previousTier:r,newTier:i.currentTier}}}else if(i.consecutiveFailures++,i.consecutiveSuccesses=0,i.consecutiveFailures>=this.config.escalateAfterFailures){let s=this.tierIndex(i.currentTier),n=this.tierIndex(this.config.maxTier);if(s>=0&&s<n)return i.currentTier=this.tierOrder[s+1],i.escalationCount++,i.consecutiveFailures=0,i.lastAction="escalate",i.lastActionTimestamp=new Date,{action:"escalate",previousTier:r,newTier:i.currentTier}}return{action:"none",previousTier:r,newTier:i.currentTier}}getCurrentTier(e){return this.states.get(e)?.currentTier??null}getState(e){return this.states.get(e)??null}getAllStates(){return Array.from(this.states.values())}reset(e){e?this.states.delete(e):this.states.clear()}};var T={booster:{avgInputTokens:0,avgOutputTokens:0,costPerTask:0},haiku:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.0035},sonnet:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.021},opus:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.105}},v=["booster","haiku","sonnet","opus"],y=T.opus.costPerTask,L={qualityWeight:.6,costWeight:.4,budgetPerHourUsd:0,budgetPerDayUsd:0,minQualityThreshold:.5,enabled:!0},N=.15,E=class{config;costTracker;tierQualityEstimates=new Map;tierOutcomeCounts=new Map;constructor(e,t){let o={...L,...t};o.qualityWeight=Math.max(0,Math.min(1,o.qualityWeight)),o.costWeight=Math.max(0,Math.min(1,o.costWeight)),o.minQualityThreshold=Math.max(0,Math.min(1,o.minQualityThreshold)),o.budgetPerHourUsd=Math.max(0,o.budgetPerHourUsd),o.budgetPerDayUsd=Math.max(0,o.budgetPerDayUsd);let i=o.qualityWeight+o.costWeight;i>0&&i!==1&&(o.qualityWeight/=i,o.costWeight/=i),this.config=o,this.costTracker=e,this.tierQualityEstimates.set("booster",.3),this.tierQualityEstimates.set("haiku",.55),this.tierQualityEstimates.set("sonnet",.75),this.tierQualityEstimates.set("opus",.9)}scoreTiers(e){let t=v.map(o=>{let i=this.getQualityEstimate(o,e),r=T[o].costPerTask,s=r>0?i/r:i>0?1/0:0,n=y>0?1-r/y:1,c=this.config.qualityWeight*i+this.config.costWeight*n;return{tier:o,qualityScore:i,estimatedCostUsd:r,qualityPerDollar:s,economicScore:c}});return t.sort((o,i)=>i.economicScore-o.economicScore),t}selectTier(e){let t=this.scoreTiers(e);for(let r of t)if(!(r.qualityScore<this.config.minQualityThreshold)&&!this.wouldExceedBudget(r.tier))return{tier:r.tier,reason:`Best economic score (${r.economicScore.toFixed(3)}): quality=${r.qualityScore.toFixed(2)}, cost=$${r.estimatedCostUsd.toFixed(4)}`,scores:t};let o=t.filter(r=>r.qualityScore>=this.config.minQualityThreshold);if(o.length>0){let r=[...o].sort((s,n)=>s.estimatedCostUsd-n.estimatedCostUsd)[0];return{tier:r.tier,reason:`Budget constrained fallback to ${r.tier}`,scores:t}}let i=[...t].sort((r,s)=>s.qualityScore-r.qualityScore)[0];return{tier:i.tier,reason:`No tier meets quality threshold ${this.config.minQualityThreshold}; using best quality: ${i.tier}`,scores:t}}wouldExceedBudget(e){let t=T[e].costPerTask;if(t===0)return!1;let o=this.costTracker.getCurrentCost("hour"),i=this.costTracker.getCurrentCost("day");return this.config.budgetPerHourUsd>0&&o+t>this.config.budgetPerHourUsd||this.config.budgetPerDayUsd>0&&i+t>this.config.budgetPerDayUsd}updateFromOutcome(e,t){let o=e.outcome.qualityScore,i=this.tierQualityEstimates.get(t)??.5,r=this.tierOutcomeCounts.get(t)??0,s=r<5?.4:N,n=i*(1-s)+o*s;this.tierQualityEstimates.set(t,n),this.tierOutcomeCounts.set(t,r+1)}getEconomicReport(){let e=this.scoreTiers(.5),t=this.costTracker.getCurrentCost("hour"),o=this.costTracker.getCurrentCost("day"),i={hourly:this.config.budgetPerHourUsd>0?Math.max(0,this.config.budgetPerHourUsd-t):null,daily:this.config.budgetPerDayUsd>0?Math.max(0,this.config.budgetPerDayUsd-o):null},r=null,s=[...e].sort((a,l)=>l.qualityPerDollar-a.qualityPerDollar),n=s.find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar)),c=[...s].reverse().find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar));if(n&&c&&n.tier!==c.tier){let a=c.estimatedCostUsd-n.estimatedCostUsd;a>0&&(r={usd:a,description:`Switch from ${c.tier} ($${c.estimatedCostUsd.toFixed(4)}/task) to ${n.tier} ($${n.estimatedCostUsd.toFixed(4)}/task) for comparable tasks to save ~$${a.toFixed(4)}/task`})}let d=this.generateRecommendation(e,i);return{tierEfficiency:e,currentHourlyCostUsd:t,currentDailyCostUsd:o,budgetRemaining:i,recommendation:d,savingsOpportunity:r}}computeCostAdjustedReward(e,t,o){let i=T[t].costPerTask;if(y===0)return e;let r=i/y,s=Math.max(0,o-this.config.minQualityThreshold),n=r*(1-s),c=e-n*this.config.costWeight;return Math.max(-1,Math.min(1,c))}serializeEstimates(){let e={};for(let t of v)e[t]={quality:this.tierQualityEstimates.get(t)??.5,count:this.tierOutcomeCounts.get(t)??0};return e}deserializeEstimates(e){for(let t of v)e[t]&&(this.tierQualityEstimates.set(t,e[t].quality),this.tierOutcomeCounts.set(t,e[t].count))}getConfig(){return{...this.config}}getQualityEstimate(e,t){let o=this.tierQualityEstimates.get(e)??.5,i=e==="booster"?t*.4:e==="haiku"?t*.2:0;return Math.max(0,Math.min(1,o-i))}generateRecommendation(e,t){if(t.hourly!==null&&t.hourly<.01)return"Hourly budget nearly exhausted. Consider increasing budget or routing to cheaper tiers.";if(t.daily!==null&&t.daily<.1)return"Daily budget nearly exhausted. Only critical tasks should use expensive tiers.";let o=e[0];return o?`Most cost-efficient tier: ${o.tier} (score=${o.economicScore.toFixed(3)}, quality=${o.qualityScore.toFixed(2)})`:"No economic data available yet."}};q();var A=class{outcomes=[];maxOutcomes;constructor(e=1e4){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getByAgent(e,t=100){return this.outcomes.filter(o=>o.usedAgent===e).slice(-t)}getAll(e=1e3){return this.outcomes.slice(-e)}getRecentOverrides(e=50){return this.outcomes.filter(t=>!t.followedRecommendation).slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},O=class m{static schemaMigrated=!1;outcomeStore;router=null;db=null;calibrator=null;escalationTracker=null;economicModel=null;economicPersistCounter=0;static ECONOMIC_PERSIST_INTERVAL=10;persistCount=0;maxOutcomes;static RETENTION_CLEANUP_INTERVAL=100;constructor(e=1e4,t){this.maxOutcomes=e,this.outcomeStore=new A(e),t?.enableEMACalibration&&this.enableCalibration(),t?.enableAutoEscalation&&this.enableAutoEscalation()}async initialize(){try{this.db=M(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb(),this.loadCalibratorState()}catch(e){console.warn("[RoutingFeedbackCollector] DB init failed, using memory-only:",g(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
3
3
  SELECT * FROM routing_outcomes ORDER BY created_at DESC LIMIT ?
4
4
  `).all(this.maxOutcomes);for(let o of t.reverse()){let i={id:o.id,task:f(o.task_json),decision:f(o.decision_json),usedAgent:o.used_agent,followedRecommendation:!!o.followed_recommendation,outcome:{success:!!o.success,qualityScore:o.quality_score,durationMs:o.duration_ms,error:o.error||void 0},timestamp:new Date(o.created_at),advisorConsultation:o.advisor_consultation_json?f(o.advisor_consultation_json):void 0};this.outcomeStore.add(i)}t.length>0&&console.log(`[RoutingFeedbackCollector] Loaded ${t.length} outcomes from DB`)}persistOutcome(e){if(this.db)try{let t=this.db.getDatabase();if(!m.schemaMigrated){for(let r of["ALTER TABLE routing_outcomes ADD COLUMN model_tier TEXT","ALTER TABLE routing_outcomes ADD COLUMN advisor_consultation_json TEXT"])try{t.prepare(r).run()}catch{}_(t),m.schemaMigrated=!0}let o=this.inferTier(e.usedAgent),i=e.advisorConsultation?JSON.stringify(e.advisorConsultation):null;t.prepare(`
5
5
  INSERT OR REPLACE INTO routing_outcomes (