agentic-qe 3.9.2 → 3.9.4

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 (296) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/dist/cli/bundle.js +5 -5
  3. package/dist/cli/chunks/adapter-5ODIX6ZG.js +2 -0
  4. package/dist/cli/chunks/{agent-booster-wasm-AKAOHSCX.js → agent-booster-wasm-MGGEPROV.js} +2 -2
  5. package/dist/cli/chunks/{agent-handler-MTGPOUVP.js → agent-handler-AFHYFQXV.js} +2 -2
  6. package/dist/cli/chunks/{agent-memory-branch-UFPKWUFK.js → agent-memory-branch-SQ3KDIG6.js} +2 -2
  7. package/dist/cli/chunks/aqe-learning-engine-PWGRS6KK.js +2 -0
  8. package/dist/cli/chunks/{audit-VBEZHNHO.js → audit-SM5CK2K5.js} +2 -2
  9. package/dist/cli/chunks/base-TJGIYR7L.js +2 -0
  10. package/dist/cli/chunks/{better-sqlite3-IRPHIXRU.js → better-sqlite3-UGOYRNXI.js} +2 -2
  11. package/dist/cli/chunks/{brain-handler-7EO3FFRZ.js → brain-handler-SKXTB63O.js} +3 -3
  12. package/dist/cli/chunks/{branch-enumerator-MZRGP35N.js → branch-enumerator-77NSOLNK.js} +2 -2
  13. package/dist/cli/chunks/{browser-VSIWQE7J.js → browser-MCE5DWPV.js} +2 -2
  14. package/dist/cli/chunks/browser-workflow-GUR7RLFP.js +2 -0
  15. package/dist/cli/chunks/{chunk-5RL66XSH.js → chunk-27FNBMUC.js} +2 -2
  16. package/dist/cli/chunks/{chunk-FRJLP7IB.js → chunk-27P4VTCY.js} +2 -2
  17. package/dist/cli/chunks/{chunk-2VVV73PW.js → chunk-2JLKOGNU.js} +1 -1
  18. package/dist/cli/chunks/{chunk-PJFLO37I.js → chunk-2MQMXI7C.js} +2 -2
  19. package/dist/cli/chunks/{chunk-BKCTNRC5.js → chunk-3MN7E6HY.js} +2 -2
  20. package/dist/cli/chunks/{chunk-BY47GV4T.js → chunk-3MRFR534.js} +2 -2
  21. package/dist/cli/chunks/{chunk-563PJBDM.js → chunk-3RHIPCBG.js} +2 -2
  22. package/dist/cli/chunks/{chunk-WXWY2GAF.js → chunk-3SPYUOSS.js} +2 -2
  23. package/dist/cli/chunks/{chunk-5AUKULWO.js → chunk-4BQTEPAD.js} +2 -2
  24. package/dist/cli/chunks/{chunk-N3F3CX4V.js → chunk-4GJAYXB7.js} +2 -2
  25. package/dist/cli/chunks/{chunk-7NOIIC7G.js → chunk-4TZTGYBQ.js} +1 -1
  26. package/dist/cli/chunks/{chunk-VL7YOOC2.js → chunk-53M65YFH.js} +2 -2
  27. package/dist/cli/chunks/{chunk-QNBQBSAI.js → chunk-54OLXGXJ.js} +2 -2
  28. package/dist/cli/chunks/{chunk-HW4ISY5B.js → chunk-5UKAEBKC.js} +3 -3
  29. package/dist/cli/chunks/{chunk-CQP7ZFME.js → chunk-72EC26AS.js} +2 -2
  30. package/dist/cli/chunks/{chunk-J4BS6IWE.js → chunk-7EL65Y27.js} +1 -1
  31. package/dist/cli/chunks/{chunk-PFNFC43Q.js → chunk-7FJIIB4H.js} +1 -1
  32. package/dist/cli/chunks/{chunk-AKSJQ6B3.js → chunk-7ST2YENJ.js} +2 -2
  33. package/dist/cli/chunks/{chunk-SNVM4YJS.js → chunk-7ZXNJT4Q.js} +2 -2
  34. package/dist/cli/chunks/{chunk-BOH22AKC.js → chunk-A6ZBQCYB.js} +2 -2
  35. package/dist/cli/chunks/{chunk-VHVWAXCF.js → chunk-B252DDC5.js} +1 -1
  36. package/dist/cli/chunks/{chunk-2EC5Z2J4.js → chunk-B6HLXE3D.js} +9 -9
  37. package/dist/cli/chunks/{chunk-L5WZUPZF.js → chunk-BH5XPYA3.js} +2 -2
  38. package/dist/cli/chunks/{chunk-LMMEUVE5.js → chunk-BZ22GI4E.js} +1 -1
  39. package/dist/cli/chunks/{chunk-YXCU4CJX.js → chunk-C2HGOUEB.js} +1 -1
  40. package/dist/cli/chunks/{chunk-JV7LX6OT.js → chunk-C3BXT3ZC.js} +4 -4
  41. package/dist/cli/chunks/{chunk-3GZKAORV.js → chunk-C567IO5M.js} +2 -2
  42. package/dist/cli/chunks/{chunk-SCF7NRVE.js → chunk-COIRFVFO.js} +1 -1
  43. package/dist/cli/chunks/{chunk-RITN3XR4.js → chunk-DHJJJ24V.js} +2 -2
  44. package/dist/cli/chunks/{chunk-RC5CPXON.js → chunk-DLMEBVLF.js} +2 -2
  45. package/dist/cli/chunks/{chunk-XFMKJ3UD.js → chunk-DZHGYZJP.js} +1 -1
  46. package/dist/cli/chunks/{chunk-V6XBAZNH.js → chunk-EEARIB4C.js} +1 -1
  47. package/dist/cli/chunks/{chunk-NM6TIEJ3.js → chunk-EFD2J6GG.js} +3 -3
  48. package/dist/cli/chunks/{chunk-Z5HXGVXZ.js → chunk-EHGTXIT7.js} +1 -1
  49. package/dist/cli/chunks/{chunk-QODE4LM6.js → chunk-ENKPW6MA.js} +2 -2
  50. package/dist/cli/chunks/{chunk-4PKXIBX2.js → chunk-EZTUUOVI.js} +1 -1
  51. package/dist/cli/chunks/{chunk-SDTVHR63.js → chunk-F6AU2MAZ.js} +2 -2
  52. package/dist/cli/chunks/{chunk-GK72GUHA.js → chunk-G6RTCJFY.js} +2 -2
  53. package/dist/cli/chunks/{chunk-E25S5E2D.js → chunk-G72E5DL3.js} +1 -1
  54. package/dist/cli/chunks/{chunk-FUIHWBVF.js → chunk-GAG2P4I2.js} +1 -1
  55. package/dist/cli/chunks/{chunk-KDDZYXP4.js → chunk-GQ7DCSKS.js} +2 -2
  56. package/dist/cli/chunks/{chunk-WG4GHAML.js → chunk-GSKZL36U.js} +2 -2
  57. package/dist/cli/chunks/{chunk-Z2IKNC5M.js → chunk-GT35EJKR.js} +1 -1
  58. package/dist/cli/chunks/{chunk-56IWS2KY.js → chunk-GVFHRHXC.js} +2 -2
  59. package/dist/cli/chunks/{chunk-CCYMJKWX.js → chunk-GX7MEHQ2.js} +1 -1
  60. package/dist/cli/chunks/{chunk-4UH25U4O.js → chunk-HKTNFHWI.js} +1 -1
  61. package/dist/cli/chunks/{chunk-X6LCMOGC.js → chunk-IGJ472XJ.js} +2 -2
  62. package/dist/cli/chunks/{chunk-XH53ARZD.js → chunk-IQE6GOH6.js} +2 -2
  63. package/dist/cli/chunks/{chunk-RJROC5M3.js → chunk-J222JLZ6.js} +2 -2
  64. package/dist/cli/chunks/{chunk-DSE57A5N.js → chunk-J6KBI5NW.js} +1 -1
  65. package/dist/cli/chunks/{chunk-CQBSGYRA.js → chunk-J72Q6ERO.js} +2 -2
  66. package/dist/cli/chunks/{chunk-ICDXWIFZ.js → chunk-JMBUIVVE.js} +1 -1
  67. package/dist/cli/chunks/{chunk-6SOJVEU7.js → chunk-JVUNZBKX.js} +2 -2
  68. package/dist/cli/chunks/{chunk-MN742FIH.js → chunk-KELYPHMV.js} +2 -2
  69. package/dist/cli/chunks/{chunk-DHE66JRR.js → chunk-KSMQH2CV.js} +1 -1
  70. package/dist/cli/chunks/{chunk-GPLERTZU.js → chunk-LH3ZL2OK.js} +2 -2
  71. package/dist/cli/chunks/{chunk-GITD7SRQ.js → chunk-LW3DV23G.js} +2 -2
  72. package/dist/cli/chunks/chunk-MDFXPCBO.js +2 -0
  73. package/dist/cli/chunks/{chunk-KZUJBZ7B.js → chunk-MGRE767N.js} +2 -2
  74. package/dist/cli/chunks/{chunk-DBE34QES.js → chunk-MN2MYLVW.js} +2 -2
  75. package/dist/cli/chunks/{chunk-25LFUL2K.js → chunk-MR5I6UR2.js} +2 -2
  76. package/dist/cli/chunks/{chunk-S3RDH5CI.js → chunk-MS6LTE4L.js} +2 -2
  77. package/dist/cli/chunks/{chunk-QEQTC4WQ.js → chunk-MUX762XZ.js} +2 -2
  78. package/dist/cli/chunks/{chunk-4Z27TRQF.js → chunk-NEYZXYFH.js} +2 -2
  79. package/dist/cli/chunks/{chunk-7SLN2JGP.js → chunk-NRH2QE4X.js} +3 -3
  80. package/dist/cli/chunks/{chunk-CL3K5EJK.js → chunk-NS4CCCTZ.js} +2 -2
  81. package/dist/cli/chunks/{chunk-NJY7ZA77.js → chunk-NZ5LY2BT.js} +1 -1
  82. package/dist/cli/chunks/{chunk-UKDOMLBI.js → chunk-O6QAOPUA.js} +3 -3
  83. package/dist/cli/chunks/{chunk-QPRVX4H2.js → chunk-OHZ6RJLS.js} +2 -2
  84. package/dist/cli/chunks/{chunk-DNLMZTE2.js → chunk-ONOYANDX.js} +1 -1
  85. package/dist/cli/chunks/chunk-OZC42UMD.js +2 -0
  86. package/dist/cli/chunks/{chunk-34U7JDCN.js → chunk-P3EOWBME.js} +2 -2
  87. package/dist/cli/chunks/{chunk-4DAOZQ3V.js → chunk-Q2ZYUIS2.js} +2 -2
  88. package/dist/cli/chunks/{chunk-RQGYJK7H.js → chunk-Q6FSXNQP.js} +2 -2
  89. package/dist/cli/chunks/{chunk-X35GP7TR.js → chunk-QEYPK7KS.js} +1 -1
  90. package/dist/cli/chunks/{chunk-T5GV6UIO.js → chunk-QOU4R6AF.js} +2 -2
  91. package/dist/cli/chunks/{chunk-KZTO5EVM.js → chunk-QPC4STR6.js} +2 -2
  92. package/dist/cli/chunks/{chunk-4FT3PND7.js → chunk-QVZSIFSJ.js} +3 -3
  93. package/dist/cli/chunks/{chunk-GCMVJS5X.js → chunk-RAZ2PGZD.js} +2 -2
  94. package/dist/cli/chunks/{chunk-727BDQ3K.js → chunk-RE6XD6RI.js} +2 -2
  95. package/dist/cli/chunks/{chunk-STE42EMB.js → chunk-RGRYL4MG.js} +2 -2
  96. package/dist/cli/chunks/{chunk-XYJL6DKI.js → chunk-RN3SN4ZC.js} +2 -2
  97. package/dist/cli/chunks/{chunk-JOVINE23.js → chunk-RPYUKEAH.js} +2 -2
  98. package/dist/cli/chunks/{chunk-5L6AU3QK.js → chunk-RRQEIGLS.js} +2 -2
  99. package/dist/cli/chunks/{chunk-VUAO4VFC.js → chunk-RS7ZGWHV.js} +2 -2
  100. package/dist/cli/chunks/{chunk-KTYUCZEM.js → chunk-RTC3ZCPK.js} +5 -5
  101. package/dist/cli/chunks/{chunk-4LA7IW3V.js → chunk-RUJU5XEQ.js} +1 -1
  102. package/dist/cli/chunks/{chunk-SRRFWTNF.js → chunk-SHJZ3YNX.js} +2 -2
  103. package/dist/cli/chunks/{chunk-FAXVVLPL.js → chunk-SKWI5QBM.js} +2 -2
  104. package/dist/cli/chunks/{chunk-NRCKGXJJ.js → chunk-TNWTQWLL.js} +1 -1
  105. package/dist/cli/chunks/{chunk-KBA7FBK3.js → chunk-TT2TB6UF.js} +3 -3
  106. package/dist/cli/chunks/{chunk-Z54EO6E6.js → chunk-U7YC7VCM.js} +2 -2
  107. package/dist/cli/chunks/{chunk-TKF447CW.js → chunk-UJLSCJJS.js} +1 -1
  108. package/dist/cli/chunks/{chunk-MY4LMIG7.js → chunk-UPJZRDZK.js} +2 -2
  109. package/dist/cli/chunks/{chunk-KQTJ2YLI.js → chunk-UUL3D5HR.js} +4 -4
  110. package/dist/cli/chunks/{chunk-TTOE336G.js → chunk-V57PXZIK.js} +3 -3
  111. package/dist/cli/chunks/{chunk-SGAW2WLI.js → chunk-VBXJBXMG.js} +4 -4
  112. package/dist/cli/chunks/{chunk-BIVIPF4O.js → chunk-VBYREHZI.js} +1 -1
  113. package/dist/cli/chunks/{chunk-PNL5G6TE.js → chunk-VFXTZWNF.js} +2 -2
  114. package/dist/cli/chunks/{chunk-2WBCYSUN.js → chunk-VSNPI2NO.js} +8 -8
  115. package/dist/cli/chunks/{chunk-Y6O7CDLI.js → chunk-WHT46PJM.js} +2 -2
  116. package/dist/cli/chunks/{chunk-L5YEPSDU.js → chunk-XB5HXTL4.js} +2 -2
  117. package/dist/cli/chunks/{chunk-4FMHBBG5.js → chunk-XYVMKCSI.js} +1 -1
  118. package/dist/cli/chunks/{chunk-AA33R5U4.js → chunk-YDJKQKQH.js} +2 -2
  119. package/dist/cli/chunks/{chunk-4D2ZG2QO.js → chunk-YS6C2Q4F.js} +1 -1
  120. package/dist/cli/chunks/{chunk-65M7C6SH.js → chunk-Z75DMTMI.js} +1 -1
  121. package/dist/cli/chunks/{chunk-Q4A72ZTV.js → chunk-ZKWNZ3ZK.js} +2 -2
  122. package/dist/cli/chunks/{chunk-2Z2TFEOL.js → chunk-ZODUKKPC.js} +2 -2
  123. package/dist/cli/chunks/{chunk-KNVAAVHH.js → chunk-ZQSEPDIJ.js} +2 -2
  124. package/dist/cli/chunks/{chunk-QIH3E775.js → chunk-ZW5DRPZY.js} +2 -2
  125. package/dist/cli/chunks/{ci-2BCOBWFG.js → ci-THZEECIQ.js} +2 -2
  126. package/dist/cli/chunks/{ci-output-FB4OJHAC.js → ci-output-G6QLGL4S.js} +2 -2
  127. package/dist/cli/chunks/{claude-flow-setup-NEEFZTMB.js → claude-flow-setup-5MTYQM34.js} +2 -2
  128. package/dist/cli/chunks/client-IFMC3AYQ.js +2 -0
  129. package/dist/cli/chunks/{cline-installer-ODO2PS4K.js → cline-installer-E2LF2DQS.js} +2 -2
  130. package/dist/cli/chunks/{code-NSOF62VE.js → code-QRF7ZGXG.js} +2 -2
  131. package/dist/cli/chunks/{code-index-extractor-YQL5XN52.js → code-index-extractor-II6IRWU6.js} +2 -2
  132. package/dist/cli/chunks/{codex-installer-SPEY6VYT.js → codex-installer-LGOQ23ZS.js} +2 -2
  133. package/dist/cli/chunks/{completions-OWKBUMBE.js → completions-LB2RR2OQ.js} +2 -2
  134. package/dist/cli/chunks/{complexity-analyzer-PGTXKP73.js → complexity-analyzer-PUIPIRX3.js} +2 -2
  135. package/dist/cli/chunks/{continuedev-installer-KGOXAC7L.js → continuedev-installer-HQAEAQZU.js} +2 -2
  136. package/dist/cli/chunks/{copilot-installer-BF3UA3TG.js → copilot-installer-3PKCX5K5.js} +2 -2
  137. package/dist/cli/chunks/{cost-tracker-2HDJ66E2.js → cost-tracker-JG3SZ2Q3.js} +2 -2
  138. package/dist/cli/chunks/{coverage-KPA2PHIN.js → coverage-D3PZTOKT.js} +3 -3
  139. package/dist/cli/chunks/cross-domain-router-2LPBUUWY.js +2 -0
  140. package/dist/cli/chunks/{cursor-installer-7CDZFHTV.js → cursor-installer-UY6GWKTO.js} +2 -2
  141. package/dist/cli/chunks/{daemon-4BPGCKDJ.js → daemon-UNO3LRRN.js} +3 -3
  142. package/dist/cli/chunks/{dag-attention-scheduler-2MAVGSBB.js → dag-attention-scheduler-S2MXANYL.js} +2 -2
  143. package/dist/cli/chunks/{detect-WRPWTGP5.js → detect-DU2FTRKR.js} +2 -2
  144. package/dist/cli/chunks/{domain-handler-JZVSJ7AG.js → domain-handler-KPNO36LF.js} +2 -2
  145. package/dist/cli/chunks/{domain-transfer-XGIZOR2X.js → domain-transfer-6X3ZZF6A.js} +2 -2
  146. package/dist/cli/chunks/dream-NGRDMOTE.js +2 -0
  147. package/dist/cli/chunks/esm-node-3COTOSO3.js +2 -0
  148. package/dist/cli/chunks/{eval-T7YPAS4G.js → eval-6RXEDTBZ.js} +2 -2
  149. package/dist/cli/chunks/{fast-paths-QECJTKCQ.js → fast-paths-FYODFGZB.js} +2 -2
  150. package/dist/cli/chunks/{feature-flags-LIFURSFZ.js → feature-flags-YOULURDA.js} +2 -2
  151. package/dist/cli/chunks/{feature-flags-R4QZYTIW.js → feature-flags-ZJ42B4IL.js} +2 -2
  152. package/dist/cli/chunks/{file-discovery-4W3K3W4C.js → file-discovery-KOL7FSBQ.js} +2 -2
  153. package/dist/cli/chunks/{fleet-NLLQWCI5.js → fleet-22I74LGD.js} +3 -3
  154. package/dist/cli/chunks/{gnn-wrapper-XEII72LN.js → gnn-wrapper-DFHTHLIZ.js} +2 -2
  155. package/dist/cli/chunks/{heartbeat-handler-DJ65RE5D.js → heartbeat-handler-SQ6VYEAA.js} +4 -4
  156. package/dist/cli/chunks/{heartbeat-scheduler-H664265Q.js → heartbeat-scheduler-W6PQJ5SG.js} +2 -2
  157. package/dist/cli/chunks/hnsw-adapter-BASJNTEV.js +2 -0
  158. package/dist/cli/chunks/hnsw-index-NFN2AUIX.js +2 -0
  159. package/dist/cli/chunks/{hnsw-legacy-bridge-SQIDTWAA.js → hnsw-legacy-bridge-AYTRT54U.js} +2 -2
  160. package/dist/cli/chunks/{hnswlib-node-WICYCU5U.js → hnswlib-node-4IA56UH4.js} +2 -2
  161. package/dist/cli/chunks/{hooks-GZUHUD63.js → hooks-T6UMR72X.js} +6 -6
  162. package/dist/cli/chunks/{hypergraph-engine-MLCDZ6BL.js → hypergraph-engine-WVPYKMFY.js} +2 -2
  163. package/dist/cli/chunks/{hypergraph-handler-NNDDI4R3.js → hypergraph-handler-NB6GL4CR.js} +3 -3
  164. package/dist/cli/chunks/impact-analyzer-ZMQXHQDV.js +2 -0
  165. package/dist/cli/chunks/init-handler-UOFNBXEP.js +68 -0
  166. package/dist/cli/chunks/init-wizard-QHAA4GWF.js +2 -0
  167. package/dist/cli/chunks/kernel-SNJFYN3T.js +2 -0
  168. package/dist/cli/chunks/{kilocode-installer-EPZFFPFE.js → kilocode-installer-VWMNI4QX.js} +2 -2
  169. package/dist/cli/chunks/{kiro-installer-5VACG3HU.js → kiro-installer-RNM47FV5.js} +15 -15
  170. package/dist/cli/chunks/knowledge-graph-EP5UTODP.js +2 -0
  171. package/dist/cli/chunks/{learning-6FITK6XY.js → learning-L4RB5XYP.js} +3 -3
  172. package/dist/cli/chunks/{llm-router-4DDC6AKJ.js → llm-router-BZYZL3YI.js} +2 -2
  173. package/dist/cli/chunks/{load-KGDNVUBX.js → load-4UGEGRMO.js} +2 -2
  174. package/dist/cli/chunks/load-test-KMMRHABK.js +2 -0
  175. package/dist/cli/chunks/mcp-FWWZIWCI.js +2 -0
  176. package/dist/cli/chunks/{memory-II4I4QMO.js → memory-5OXPMXU6.js} +5 -5
  177. package/dist/cli/chunks/memory-backend-Q5MWPMDE.js +2 -0
  178. package/dist/cli/chunks/{memory-handlers-TQXTOJGQ.js → memory-handlers-JS7BTWJK.js} +2 -2
  179. package/dist/cli/chunks/{opencode-installer-EU6JCWBW.js → opencode-installer-BS5TQKHB.js} +2 -2
  180. package/dist/cli/chunks/orchestrator-G6BUZ6QE.js +370 -0
  181. package/dist/cli/chunks/{pipeline-MPZJWYKK.js → pipeline-3MZ5COPR.js} +2 -2
  182. package/dist/cli/chunks/{platform-YH35ZZFZ.js → platform-TKD4JCUG.js} +2 -2
  183. package/dist/cli/chunks/{plugin-B7JYZFNQ.js → plugin-XXJ7R6SY.js} +2 -2
  184. package/dist/cli/chunks/{prime-radiant-advanced-wasm-KTUK6UE2.js → prime-radiant-advanced-wasm-JLJ6NKIP.js} +2 -2
  185. package/dist/cli/chunks/protocol-executor-ORFR4WJ3.js +2 -0
  186. package/dist/cli/chunks/{protocol-handler-3NXMVU34.js → protocol-handler-ZLYGQPHG.js} +2 -2
  187. package/dist/cli/chunks/{prove-H5LMGSUC.js → prove-E2WZ335X.js} +2 -2
  188. package/dist/cli/chunks/qe-reasoning-bank-PLTOH4SG.js +2 -0
  189. package/dist/cli/chunks/{quality-RCWHY6GO.js → quality-6MHHBINU.js} +2 -2
  190. package/dist/cli/chunks/queen-coordinator-L3TRAX7H.js +2 -0
  191. package/dist/cli/chunks/{real-embeddings-NKH4VURF.js → real-embeddings-QN5BY3WS.js} +2 -2
  192. package/dist/cli/chunks/{roocode-installer-SB7QJYM3.js → roocode-installer-GTVII272.js} +2 -2
  193. package/dist/cli/chunks/router-3PBJJLRQ.js +2 -0
  194. package/dist/cli/chunks/routing-feedback-Q775MZ3Z.js +2 -0
  195. package/dist/cli/chunks/{routing-handler-SY7GKG2W.js → routing-handler-HYKZ3ISS.js} +2 -2
  196. package/dist/cli/chunks/{ruvector-commands-HATTO3UQ.js → ruvector-commands-LBWHPUTZ.js} +2 -2
  197. package/dist/cli/chunks/{rvf-dual-writer-D57EXQUD.js → rvf-dual-writer-TVCJ2Y6N.js} +2 -2
  198. package/dist/cli/chunks/{rvf-migration-adapter-OWDYN6KD.js → rvf-migration-adapter-34ITXLU3.js} +2 -2
  199. package/dist/cli/chunks/{rvf-migration-coordinator-SIQVJB5S.js → rvf-migration-coordinator-SX2C7777.js} +2 -2
  200. package/dist/cli/chunks/rvf-native-adapter-HLY2652E.js +2 -0
  201. package/dist/cli/chunks/safe-db-CCKCBZ5I.js +2 -0
  202. package/dist/cli/chunks/schedule-WZ5VV55N.js +2 -0
  203. package/dist/cli/chunks/scheduler-6PIKLCH7.js +2 -0
  204. package/dist/cli/chunks/{security-DS3XLZWN.js → security-7A4EW77M.js} +3 -3
  205. package/dist/cli/chunks/shared-rvf-adapter-VCJNSACZ.js +2 -0
  206. package/dist/cli/chunks/{shared-rvf-dual-writer-YB7AH6XJ.js → shared-rvf-dual-writer-27L4R5WK.js} +2 -2
  207. package/dist/cli/chunks/sqlite-persistence-HMXYD56G.js +2 -0
  208. package/dist/cli/chunks/{status-handler-TUYHE4FT.js → status-handler-JN6PRYLD.js} +2 -2
  209. package/dist/cli/chunks/{structural-health-XNGBNRRD.js → structural-health-JSY3DY7H.js} +2 -2
  210. package/dist/cli/chunks/{sync-K6CIRKBB.js → sync-ET3LYW2V.js} +10 -10
  211. package/dist/cli/chunks/{task-handler-7PJY67DR.js → task-handler-R24MR74L.js} +2 -2
  212. package/dist/cli/chunks/{task-handlers-WB5CDWUR.js → task-handlers-YNPEEPPZ.js} +2 -2
  213. package/dist/cli/chunks/{test-WV5ALEBB.js → test-7BZXFZCT.js} +4 -4
  214. package/dist/cli/chunks/{test-scheduling-N55ZGGA2.js → test-scheduling-EVIFD5EY.js} +3 -3
  215. package/dist/cli/chunks/{token-bootstrap-SINWHAKR.js → token-bootstrap-QYYQRXM5.js} +2 -2
  216. package/dist/cli/chunks/{token-usage-R7TGEVGL.js → token-usage-H4OZA77I.js} +2 -2
  217. package/dist/cli/chunks/{transformers-6DBLXPV7.js → transformers-ILQFO5HZ.js} +2 -2
  218. package/dist/cli/chunks/{tree-sitter-wasm-parser-7C7FKMQW.js → tree-sitter-wasm-parser-KTST5NWH.js} +2 -2
  219. package/dist/cli/chunks/{types-VNPMOKQT.js → types-4Z7XELU6.js} +2 -2
  220. package/dist/cli/chunks/unified-memory-RBHCTAWW.js +2 -0
  221. package/dist/cli/chunks/unified-memory-hnsw-UBF5PT6D.js +2 -0
  222. package/dist/cli/chunks/unified-persistence-ZIJDP6GW.js +2 -0
  223. package/dist/cli/chunks/{validate-53MNIRAF.js → validate-GSQCH6VN.js} +2 -2
  224. package/dist/cli/chunks/{validate-swarm-ZY4RGUFO.js → validate-swarm-SP2RPOYD.js} +2 -2
  225. package/dist/cli/chunks/{vibium-PBADBIV6.js → vibium-2SGOFYTF.js} +2 -2
  226. package/dist/cli/chunks/visual-security-WKIWOUTH.js +2 -0
  227. package/dist/cli/chunks/{web-tree-sitter-O7VI6RLB.js → web-tree-sitter-QSQ27UTH.js} +2 -2
  228. package/dist/cli/chunks/{windsurf-installer-HV3C3TAD.js → windsurf-installer-NIEH46E2.js} +2 -2
  229. package/dist/cli/chunks/witness-chain-4BRX3GGH.js +2 -0
  230. package/dist/cli/chunks/{witness-chain-4WIMYP4X.js → witness-chain-62GJTCT5.js} +2 -2
  231. package/dist/cli/chunks/{workflow-5RVAQ4TM.js → workflow-WZMV2MGW.js} +4 -4
  232. package/dist/cli/chunks/workflow-orchestrator-G6VU7QZ4.js +2 -0
  233. package/dist/cli/chunks/{wrappers-RRHCCA3E.js → wrappers-LNTV533I.js} +2 -2
  234. package/dist/cli/commands/init.js +2 -0
  235. package/dist/cli/commands/mcp.js +27 -17
  236. package/dist/cli/commands/sync.js +25 -8
  237. package/dist/cli/handlers/init-handler.d.ts +1 -0
  238. package/dist/cli/handlers/init-handler.js +2 -0
  239. package/dist/init/governance-installer.js +46 -14
  240. package/dist/init/kiro-installer.js +15 -2
  241. package/dist/init/orchestrator.js +1 -0
  242. package/dist/init/phases/06-code-intelligence.d.ts +46 -1
  243. package/dist/init/phases/06-code-intelligence.js +164 -10
  244. package/dist/init/phases/10-workers.d.ts +0 -14
  245. package/dist/init/phases/10-workers.js +19 -164
  246. package/dist/init/phases/phase-interface.d.ts +9 -0
  247. package/dist/kernel/hnsw-adapter.d.ts +14 -0
  248. package/dist/kernel/hnsw-adapter.js +25 -1
  249. package/dist/kernel/hnsw-index-provider.d.ts +16 -0
  250. package/dist/kernel/native-hnsw-backend.d.ts +11 -0
  251. package/dist/kernel/native-hnsw-backend.js +20 -0
  252. package/dist/kernel/progressive-hnsw-backend.d.ts +9 -0
  253. package/dist/kernel/progressive-hnsw-backend.js +41 -12
  254. package/dist/kernel/unified-memory.js +10 -0
  255. package/dist/mcp/bundle.js +216 -216
  256. package/dist/optimization/token-optimizer-service.d.ts +31 -2
  257. package/dist/optimization/token-optimizer-service.js +85 -23
  258. package/package.json +1 -1
  259. package/dist/cli/chunks/adapter-53WBPKXU.js +0 -2
  260. package/dist/cli/chunks/aqe-learning-engine-MV7NGY24.js +0 -2
  261. package/dist/cli/chunks/base-DZVGMQN2.js +0 -2
  262. package/dist/cli/chunks/browser-workflow-3J5YNMEI.js +0 -2
  263. package/dist/cli/chunks/chunk-LCAA6H4J.js +0 -2
  264. package/dist/cli/chunks/chunk-XIBVVZGB.js +0 -2
  265. package/dist/cli/chunks/client-EF555KYW.js +0 -2
  266. package/dist/cli/chunks/cross-domain-router-GXFNK5TS.js +0 -2
  267. package/dist/cli/chunks/dream-3IKF5XH4.js +0 -2
  268. package/dist/cli/chunks/esm-node-DHAE52OW.js +0 -2
  269. package/dist/cli/chunks/hnsw-adapter-DML5KXQR.js +0 -2
  270. package/dist/cli/chunks/hnsw-index-BUPPGVR6.js +0 -2
  271. package/dist/cli/chunks/impact-analyzer-DPTMJRYS.js +0 -2
  272. package/dist/cli/chunks/init-handler-IJ6BHE6A.js +0 -68
  273. package/dist/cli/chunks/init-wizard-35PUDJPW.js +0 -2
  274. package/dist/cli/chunks/kernel-2HZ44ZJ4.js +0 -2
  275. package/dist/cli/chunks/knowledge-graph-JL62G72U.js +0 -2
  276. package/dist/cli/chunks/load-test-LN245SSD.js +0 -2
  277. package/dist/cli/chunks/mcp-4LETGVIV.js +0 -2
  278. package/dist/cli/chunks/memory-backend-SVM7YRIE.js +0 -2
  279. package/dist/cli/chunks/orchestrator-YLMGJVSP.js +0 -371
  280. package/dist/cli/chunks/protocol-executor-IEN2XB4L.js +0 -2
  281. package/dist/cli/chunks/qe-reasoning-bank-Q3ZV3JRG.js +0 -2
  282. package/dist/cli/chunks/queen-coordinator-E6ON3JUR.js +0 -2
  283. package/dist/cli/chunks/router-WMC3LZ3C.js +0 -2
  284. package/dist/cli/chunks/routing-feedback-VKCZRCE3.js +0 -2
  285. package/dist/cli/chunks/rvf-native-adapter-C7NBH5UN.js +0 -2
  286. package/dist/cli/chunks/safe-db-5KLXCNXN.js +0 -2
  287. package/dist/cli/chunks/schedule-HAWWOXWB.js +0 -2
  288. package/dist/cli/chunks/scheduler-HTRDY5BC.js +0 -2
  289. package/dist/cli/chunks/shared-rvf-adapter-6I2Z5UGL.js +0 -2
  290. package/dist/cli/chunks/sqlite-persistence-WNNRGTGG.js +0 -2
  291. package/dist/cli/chunks/unified-memory-72SKVZ7Y.js +0 -2
  292. package/dist/cli/chunks/unified-memory-hnsw-TMN2L77W.js +0 -2
  293. package/dist/cli/chunks/unified-persistence-MDN3SRCR.js +0 -2
  294. package/dist/cli/chunks/visual-security-TRBCXPIB.js +0 -2
  295. package/dist/cli/chunks/witness-chain-JOI2YYGK.js +0 -2
  296. package/dist/cli/chunks/workflow-orchestrator-2NQ72S3C.js +0 -2
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.2");process.exit(0)}
2
- import{g}from"./chunk-UKDOMLBI.js";import{b as p,c as d}from"./chunk-BIVIPF4O.js";import{b as m,c as f}from"./chunk-SDTVHR63.js";import{f as h}from"./chunk-E25S5E2D.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)}config;knowledgeGraph;async analyzeImpact(e){try{let{changedFiles:t,depth:i=this.config.maxDepth,includeTests:n=!0}=e;if(t.length===0)return p({directImpact:[],transitiveImpact:[],impactedTests:[],riskLevel:"info",recommendations:[]});let r=await this.analyzeDirectImpact(t),l=await this.analyzeTransitiveImpact(t,r,i),s=[];if(n){let a=await this.getImpactedTests(t);a.success&&(s=a.value)}let c={directImpact:r,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 n=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:3});if(n.success)for(let s of n.value.nodes)this.isTestFile(s.path)&&t.add(s.path);let r=this.getBaseName(i),l=[`${r}.test`,`${r}.spec`,`test_${r}`,`${r}_test`];for(let s of l){let c=await this.memory.search(`code-intelligence:kg:node:*${s}*`,10);for(let a of c){let o=await this.memory.get(a);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,n=Math.min(1,e.directImpact.length/10);i+=n*t.directImpact;let r=Math.min(1,e.transitiveImpact.length/20);i+=r*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(r=>this.isCriticalPath(r.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 n=[...e.directImpact,...e.transitiveImpact].filter(r=>r.riskScore>=.7);return n.length>0&&t.push(`${n.length} high-risk files impacted: ${n.slice(0,2).map(r=>this.getFileName(r.file)).join(", ")}`),t}async analyzeDirectImpact(e){let t=[];for(let i of e){let n=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:1});if(n.success){let{nodes:r,edges:l}=n.value;for(let s of r){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 n=[],r=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(r.has(a.path)||a.path===s.file)continue;r.add(a.path);let o=this.calculateFileRiskScore(a.path,a.inDegree,a.outDegree,s.distance+1);n.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(n)}calculateFileRiskScore(e,t,i,n=1){let r=0;return r+=Math.min(.3,t/20),r+=Math.min(.2,i/30),this.isCriticalPath(e)&&(r+=.3),this.isEntryPoint(e)&&(r+=.2),r=r*Math.pow(.8,n-1),Math.min(1,Math.max(0,r))}calculateAverageRiskScore(e){return e.length===0?0:e.reduce((i,n)=>i+n.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 n=t.get(i.file);(!n||i.distance<n.distance)&&t.set(i.file,i)}return Array.from(t.values()).sort((i,n)=>n.riskScore!==i.riskScore?n.riskScore-i.riskScore:i.distance-n.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
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
2
+ import{g}from"./chunk-O6QAOPUA.js";import{b as p,c as d}from"./chunk-VBYREHZI.js";import{b as m,c as f}from"./chunk-F6AU2MAZ.js";import{f as h}from"./chunk-G72E5DL3.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)}config;knowledgeGraph;async analyzeImpact(e){try{let{changedFiles:t,depth:i=this.config.maxDepth,includeTests:n=!0}=e;if(t.length===0)return p({directImpact:[],transitiveImpact:[],impactedTests:[],riskLevel:"info",recommendations:[]});let r=await this.analyzeDirectImpact(t),l=await this.analyzeTransitiveImpact(t,r,i),s=[];if(n){let a=await this.getImpactedTests(t);a.success&&(s=a.value)}let c={directImpact:r,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 n=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:3});if(n.success)for(let s of n.value.nodes)this.isTestFile(s.path)&&t.add(s.path);let r=this.getBaseName(i),l=[`${r}.test`,`${r}.spec`,`test_${r}`,`${r}_test`];for(let s of l){let c=await this.memory.search(`code-intelligence:kg:node:*${s}*`,10);for(let a of c){let o=await this.memory.get(a);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,n=Math.min(1,e.directImpact.length/10);i+=n*t.directImpact;let r=Math.min(1,e.transitiveImpact.length/20);i+=r*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(r=>this.isCriticalPath(r.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 n=[...e.directImpact,...e.transitiveImpact].filter(r=>r.riskScore>=.7);return n.length>0&&t.push(`${n.length} high-risk files impacted: ${n.slice(0,2).map(r=>this.getFileName(r.file)).join(", ")}`),t}async analyzeDirectImpact(e){let t=[];for(let i of e){let n=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:1});if(n.success){let{nodes:r,edges:l}=n.value;for(let s of r){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 n=[],r=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(r.has(a.path)||a.path===s.file)continue;r.add(a.path);let o=this.calculateFileRiskScore(a.path,a.inDegree,a.outDegree,s.distance+1);n.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(n)}calculateFileRiskScore(e,t,i,n=1){let r=0;return r+=Math.min(.3,t/20),r+=Math.min(.2,i/30),this.isCriticalPath(e)&&(r+=.3),this.isEntryPoint(e)&&(r+=.2),r=r*Math.pow(.8,n-1),Math.min(1,Math.max(0,r))}calculateAverageRiskScore(e){return e.length===0?0:e.reduce((i,n)=>i+n.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 n=t.get(i.file);(!n||i.distance<n.distance)&&t.set(i.file,i)}return Array.from(t.values()).sort((i,n)=>n.riskScore!==i.riskScore?n.riskScore-i.riskScore:i.distance-n.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,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.9.2");process.exit(0)}
2
- import{c as t,e as o}from"./chunk-YXCU4CJX.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>m,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>g,TensorCompress:()=>c,default:()=>i,differentiableSearch:()=>l,getCompressionLevel:()=>s,hierarchicalForward:()=>p,init:()=>u,pipeline:()=>v});import{createRequire as n}from"module";var r,e,i,a,c,l,p,s,u,m,d,A,f,h,_,g,v,b=t(()=>{r=n(import.meta.url),e=r("@ruvector/gnn"),i=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:p,getCompressionLevel:s,init:u,FlashAttention:m,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:g,pipeline:v}=e||{}});export{L 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.9.4");process.exit(0)}
2
+ import{c as t,e as o}from"./chunk-C2HGOUEB.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>m,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>g,TensorCompress:()=>c,default:()=>i,differentiableSearch:()=>l,getCompressionLevel:()=>s,hierarchicalForward:()=>p,init:()=>u,pipeline:()=>v});import{createRequire as n}from"module";var r,e,i,a,c,l,p,s,u,m,d,A,f,h,_,g,v,b=t(()=>{r=n(import.meta.url),e=r("@ruvector/gnn"),i=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:p,getCompressionLevel:s,init:u,FlashAttention:m,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:g,pipeline:v}=e||{}});export{L as a,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.9.2");process.exit(0)}
2
- import{a as I}from"./chunk-VL7YOOC2.js";import{n as F,o as q}from"./chunk-GK72GUHA.js";import{a as A,b as m,c as d}from"./chunk-BIVIPF4O.js";import{a as b,b as W,c as O}from"./chunk-SDTVHR63.js";import{f as D}from"./chunk-E25S5E2D.js";import{g as T}from"./chunk-YXCU4CJX.js";O();var w={WorkflowStarted:"workflow.WorkflowStarted",WorkflowCompleted:"workflow.WorkflowCompleted",WorkflowFailed:"workflow.WorkflowFailed",WorkflowCancelled:"workflow.WorkflowCancelled",StepStarted:"workflow.StepStarted",StepCompleted:"workflow.StepCompleted",StepFailed:"workflow.StepFailed",StepSkipped:"workflow.StepSkipped",StepAwaitingApproval:"workflow.StepAwaitingApproval",StepApproved:"workflow.StepApproved",StepRejected:"workflow.StepRejected"},E={maxConcurrentWorkflows:10,defaultStepTimeout:6e4,defaultWorkflowTimeout:6e5,enableEventTriggers:!0,persistExecutions:!0};function S(){try{let{getUnifiedMemory:s}=(q(),T(F)),e=s();return e.isInitialized()?e.getDatabase():null}catch{return null}}var N={id:"quality-gate-check",domain:"quality-assessment",action:"gate-check",async execute(s){let e=typeof s.coverageMin=="number"?s.coverageMin:80,t=typeof s.testsPassingMin=="number"?s.testsPassingMin:90,i=typeof s.maxBugs=="number"?s.maxBugs:5,r=typeof s.currentCoverage=="number"?s.currentCoverage:null,n=typeof s.currentTestsPassingRate=="number"?s.currentTestsPassingRate:null,o=typeof s.currentBugs=="number"?s.currentBugs:null;if(r===null||n===null||o===null){let p=S();if(p)try{if(r===null&&(r=p.prepare("SELECT after_lines FROM coverage_sessions ORDER BY created_at DESC LIMIT 1").get()?.after_lines??0),n===null){let y=p.prepare(`SELECT COUNT(*) as total,
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.9.4");process.exit(0)}
2
+ import{a as I}from"./chunk-53M65YFH.js";import{n as F,o as q}from"./chunk-G6RTCJFY.js";import{a as A,b as m,c as d}from"./chunk-VBYREHZI.js";import{a as b,b as W,c as O}from"./chunk-F6AU2MAZ.js";import{f as D}from"./chunk-G72E5DL3.js";import{g as T}from"./chunk-C2HGOUEB.js";O();var w={WorkflowStarted:"workflow.WorkflowStarted",WorkflowCompleted:"workflow.WorkflowCompleted",WorkflowFailed:"workflow.WorkflowFailed",WorkflowCancelled:"workflow.WorkflowCancelled",StepStarted:"workflow.StepStarted",StepCompleted:"workflow.StepCompleted",StepFailed:"workflow.StepFailed",StepSkipped:"workflow.StepSkipped",StepAwaitingApproval:"workflow.StepAwaitingApproval",StepApproved:"workflow.StepApproved",StepRejected:"workflow.StepRejected"},E={maxConcurrentWorkflows:10,defaultStepTimeout:6e4,defaultWorkflowTimeout:6e5,enableEventTriggers:!0,persistExecutions:!0};function S(){try{let{getUnifiedMemory:s}=(q(),T(F)),e=s();return e.isInitialized()?e.getDatabase():null}catch{return null}}var N={id:"quality-gate-check",domain:"quality-assessment",action:"gate-check",async execute(s){let e=typeof s.coverageMin=="number"?s.coverageMin:80,t=typeof s.testsPassingMin=="number"?s.testsPassingMin:90,i=typeof s.maxBugs=="number"?s.maxBugs:5,r=typeof s.currentCoverage=="number"?s.currentCoverage:null,n=typeof s.currentTestsPassingRate=="number"?s.currentTestsPassingRate:null,o=typeof s.currentBugs=="number"?s.currentBugs:null;if(r===null||n===null||o===null){let p=S();if(p)try{if(r===null&&(r=p.prepare("SELECT after_lines FROM coverage_sessions ORDER BY created_at DESC LIMIT 1").get()?.after_lines??0),n===null){let y=p.prepare(`SELECT COUNT(*) as total,
3
3
  SUM(CASE WHEN passed = 1 THEN 1 ELSE 0 END) as passed
4
4
  FROM test_outcomes
5
5
  WHERE created_at > datetime('now', '-7 days')`).get();n=y&&y.total>0?y.passed/y.total*100:0}o===null&&(o=p.prepare(`SELECT COUNT(*) as bugs FROM test_outcomes
@@ -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.9.2");process.exit(0)}
2
- import{a as t,q as r}from"./chunk-L5YEPSDU.js";import{c as l}from"./chunk-YXCU4CJX.js";function m(s,e){let o=e?.readonly??!1,n=e?.fileMustExist??!1,i=e?.busyTimeout??5e3,b=e?.walMode??!o,a=new t(s,{readonly:o,fileMustExist:n});return a.pragma(`busy_timeout = ${i}`),b&&a.pragma("journal_mode = WAL"),a}var u=l(()=>{r()});export{m as a,u as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
2
+ import{a as t,q as r}from"./chunk-XB5HXTL4.js";import{c as l}from"./chunk-C2HGOUEB.js";function m(s,e){let o=e?.readonly??!1,n=e?.fileMustExist??!1,i=e?.busyTimeout??5e3,b=e?.walMode??!o,a=new t(s,{readonly:o,fileMustExist:n});return a.pragma(`busy_timeout = ${i}`),b&&a.pragma("journal_mode = WAL"),a}var u=l(()=>{r()});export{m as a,u as b};
@@ -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.9.2");process.exit(0)}
2
- import{c}from"./chunk-YXCU4CJX.js";function u(r){switch(r.toUpperCase()){case"DEBUG":return 0;case"INFO":return 1;case"WARN":case"WARNING":return 2;case"ERROR":return 3;case"SILENT":case"NONE":case"OFF":return 4;default:return 1}}var f,l=c(()=>{"use strict";f={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR",4:"SILENT"}});var a,s,g,d=c(()=>{"use strict";l();a={includeTimestamp:!0,includeLevel:!0,timestampFormat:"short",prettyPrint:!1,maxContextDepth:3},s=class r{domain;level;config;inheritedContext;constructor(e,n=1,o={},t={}){this.domain=e,this.level=n,this.config={...a,...o},this.inheritedContext=t}debug(e,n){this.level<=0&&this.output(0,e,n)}info(e,n){this.level<=1&&this.output(1,e,n)}warn(e,n){this.level<=2&&this.output(2,e,n)}error(e,n,o){if(this.level<=3){let t={...o};if(n){t.errorName=n.name,t.errorMessage=n.message,n.stack&&(t.stack=n.stack);let i=n;i.cause!==void 0&&(t.cause=String(i.cause))}this.output(3,e,t)}}isEnabled(e){return this.level<=e}getDomain(){return this.domain}child(e){return new r(this.domain,this.level,this.config,{...this.inheritedContext,...e})}output(e,n,o){let t=this.format(e,n,o);switch(e){case 0:console.debug(t);break;case 1:console.info(t);break;case 2:console.warn(t);break;case 3:console.error(t);break}}format(e,n,o){let t=[];this.config.includeTimestamp&&t.push(this.formatTimestamp()),this.config.includeLevel&&t.push(this.formatLevel(e)),t.push(`[${this.domain}]`),t.push(n);let i=this.mergeContext(o);return i&&Object.keys(i).length>0&&t.push(this.formatContext(i)),t.join(" ")}formatTimestamp(){let e=new Date;if(this.config.timestampFormat==="iso")return`[${e.toISOString()}]`;let n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),t=String(e.getSeconds()).padStart(2,"0"),i=String(e.getMilliseconds()).padStart(3,"0");return`[${n}:${o}:${t}.${i}]`}formatLevel(e){return`[${f[e].padEnd(5)}]`}mergeContext(e){if(!(!e&&Object.keys(this.inheritedContext).length===0))return{...this.inheritedContext,...e}}formatContext(e){try{return this.config.prettyPrint?`
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.9.4");process.exit(0)}
2
+ import{c}from"./chunk-C2HGOUEB.js";function u(r){switch(r.toUpperCase()){case"DEBUG":return 0;case"INFO":return 1;case"WARN":case"WARNING":return 2;case"ERROR":return 3;case"SILENT":case"NONE":case"OFF":return 4;default:return 1}}var f,l=c(()=>{"use strict";f={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR",4:"SILENT"}});var a,s,g,d=c(()=>{"use strict";l();a={includeTimestamp:!0,includeLevel:!0,timestampFormat:"short",prettyPrint:!1,maxContextDepth:3},s=class r{domain;level;config;inheritedContext;constructor(e,n=1,o={},t={}){this.domain=e,this.level=n,this.config={...a,...o},this.inheritedContext=t}debug(e,n){this.level<=0&&this.output(0,e,n)}info(e,n){this.level<=1&&this.output(1,e,n)}warn(e,n){this.level<=2&&this.output(2,e,n)}error(e,n,o){if(this.level<=3){let t={...o};if(n){t.errorName=n.name,t.errorMessage=n.message,n.stack&&(t.stack=n.stack);let i=n;i.cause!==void 0&&(t.cause=String(i.cause))}this.output(3,e,t)}}isEnabled(e){return this.level<=e}getDomain(){return this.domain}child(e){return new r(this.domain,this.level,this.config,{...this.inheritedContext,...e})}output(e,n,o){let t=this.format(e,n,o);switch(e){case 0:console.debug(t);break;case 1:console.info(t);break;case 2:console.warn(t);break;case 3:console.error(t);break}}format(e,n,o){let t=[];this.config.includeTimestamp&&t.push(this.formatTimestamp()),this.config.includeLevel&&t.push(this.formatLevel(e)),t.push(`[${this.domain}]`),t.push(n);let i=this.mergeContext(o);return i&&Object.keys(i).length>0&&t.push(this.formatContext(i)),t.join(" ")}formatTimestamp(){let e=new Date;if(this.config.timestampFormat==="iso")return`[${e.toISOString()}]`;let n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),t=String(e.getSeconds()).padStart(2,"0"),i=String(e.getMilliseconds()).padStart(3,"0");return`[${n}:${o}:${t}.${i}]`}formatLevel(e){return`[${f[e].padEnd(5)}]`}mergeContext(e){if(!(!e&&Object.keys(this.inheritedContext).length===0))return{...this.inheritedContext,...e}}formatContext(e){try{return this.config.prettyPrint?`
3
3
  `+JSON.stringify(e,this.createReplacer(),2):JSON.stringify(e,this.createReplacer())}catch{return"[unserializable context]"}}createReplacer(){let e=new WeakSet,n=0;return(o,t)=>{if(typeof t=="object"&&t!==null){if(n>=this.config.maxContextDepth)return"[object]";if(e.has(t))return"[circular]";e.add(t),n++}return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:typeof t=="bigint"?t.toString():typeof t=="function"?"[function]":typeof t=="symbol"?t.toString():t}}},g=class{domain;constructor(e="null"){this.domain=e}debug(e,n){}info(e,n){}warn(e,n){}error(e,n,o){}isEnabled(e){return!1}getDomain(){return this.domain}child(e){return this}}});function F(r,e){return L.create(r,e)}var v,L,m=c(()=>{"use strict";l();d();v={defaultLevel:1,domainLevels:new Map,consoleConfig:a,silent:!1},L=class{static config={...v};static customProvider=null;static instances=new Map;static setLevel(e){this.config.defaultLevel=e,this.instances.clear()}static setLevelFromString(e){this.setLevel(u(e))}static getLevel(){return this.config.defaultLevel}static setDomainLevel(e,n){this.config.domainLevels.set(e,n),this.instances.delete(e)}static getDomainLevel(e){return this.config.domainLevels.get(e)??this.config.defaultLevel}static clearDomainLevel(e){this.config.domainLevels.delete(e),this.instances.delete(e)}static configure(e){this.config.consoleConfig={...this.config.consoleConfig,...e},this.instances.clear()}static setSilent(e){this.config.silent=e,this.instances.clear()}static isSilent(){return this.config.silent}static setProvider(e){this.customProvider=e,this.instances.clear()}static create(e,n){if(!n&&this.instances.has(e))return this.instances.get(e);let o=this.getDomainLevel(e),t;return this.config.silent?t=new g(e):this.customProvider?t=this.customProvider(e,o,n):t=new s(e,o,this.config.consoleConfig,n),n||this.instances.set(e,t),t}static getLogger(e,n){return this.create(e,n)}static reset(){this.config={defaultLevel:1,domainLevels:new Map,consoleConfig:{...a},silent:!1},this.customProvider=null,this.instances.clear()}static initFromEnv(){let e=process.env.LOG_LEVEL;e&&this.setLevelFromString(e);let n=process.env.LOG_TIMESTAMP;n!==void 0&&this.configure({includeTimestamp:n.toLowerCase()==="true"});let o=process.env.LOG_PRETTY;o!==void 0&&this.configure({prettyPrint:o.toLowerCase()==="true"})}static getStats(){return{cachedLoggers:this.instances.size,domains:Array.from(this.instances.keys()),domainOverrides:this.config.domainLevels.size,currentLevel:this.config.defaultLevel,silent:this.config.silent}}}});export{l as a,d as b,L as c,F as d,m as e};
@@ -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.9.2");process.exit(0)}
2
- import{c as R,g as L}from"./chunk-563PJBDM.js";import{k as N,o as w}from"./chunk-GK72GUHA.js";import{b,d as q}from"./chunk-N3F3CX4V.js";import{a as _,c as I}from"./chunk-SDTVHR63.js";import{f}from"./chunk-E25S5E2D.js";import{a as S,b as A}from"./chunk-XYJL6DKI.js";A();q();I();w();var D={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:256*1024*1024,cacheSize:-64e3,foreignKeys:!0,useUnified:!0};function C(m,e=384){let n=new Array(e).fill(0),t=m.toLowerCase().trim();for(let a=0;a<3;a++)for(let i=0;i<t.length;i++){let s=t.charCodeAt(i),o=s*(i+1)*(a+1)%e;n[o]+=Math.sin(s*(a+1))/(i+1)}let r=Math.sqrt(n.reduce((a,i)=>a+i*i,0));if(r>0)for(let a=0;a<e;a++)n[a]/=r;return n}var h=class{db=null;config;prepared=new Map;initialized=!1;unifiedMemory=null;constructor(e={}){this.config={...D,...e}}getDatabase(){return this.db}async initialize(){if(!this.initialized)try{if(this.config.useUnified)this.unifiedMemory=N(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),console.log(`[SQLitePatternStore] Using unified storage: ${this.unifiedMemory.getDbPath()}`);else{let e=await import("path"),n=await import("fs"),t=e.dirname(this.config.dbPath);n.existsSync(t)||n.mkdirSync(t,{recursive:!0}),this.db=S(this.config.dbPath),this.db.pragma(`mmap_size = ${this.config.mmapSize}`),this.db.pragma(`cache_size = ${this.config.cacheSize}`),this.config.foreignKeys&&this.db.pragma("foreign_keys = ON"),this.createSchema(),console.log(`[SQLitePatternStore] Initialized (legacy): ${this.config.dbPath}`)}this.deduplicatePatterns(),this.prepareStatements(),this.initialized=!0}catch(e){throw new Error(`Failed to initialize SQLite: ${_(e)}`)}}createSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
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.9.4");process.exit(0)}
2
+ import{c as R,g as L}from"./chunk-3RHIPCBG.js";import{k as N,o as w}from"./chunk-G6RTCJFY.js";import{b,d as q}from"./chunk-4GJAYXB7.js";import{a as _,c as I}from"./chunk-F6AU2MAZ.js";import{f}from"./chunk-G72E5DL3.js";import{a as S,b as A}from"./chunk-RN3SN4ZC.js";A();q();I();w();var D={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:256*1024*1024,cacheSize:-64e3,foreignKeys:!0,useUnified:!0};function C(m,e=384){let n=new Array(e).fill(0),t=m.toLowerCase().trim();for(let a=0;a<3;a++)for(let i=0;i<t.length;i++){let s=t.charCodeAt(i),o=s*(i+1)*(a+1)%e;n[o]+=Math.sin(s*(a+1))/(i+1)}let r=Math.sqrt(n.reduce((a,i)=>a+i*i,0));if(r>0)for(let a=0;a<e;a++)n[a]/=r;return n}var h=class{db=null;config;prepared=new Map;initialized=!1;unifiedMemory=null;constructor(e={}){this.config={...D,...e}}getDatabase(){return this.db}async initialize(){if(!this.initialized)try{if(this.config.useUnified)this.unifiedMemory=N(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),console.log(`[SQLitePatternStore] Using unified storage: ${this.unifiedMemory.getDbPath()}`);else{let e=await import("path"),n=await import("fs"),t=e.dirname(this.config.dbPath);n.existsSync(t)||n.mkdirSync(t,{recursive:!0}),this.db=S(this.config.dbPath),this.db.pragma(`mmap_size = ${this.config.mmapSize}`),this.db.pragma(`cache_size = ${this.config.cacheSize}`),this.config.foreignKeys&&this.db.pragma("foreign_keys = ON"),this.createSchema(),console.log(`[SQLitePatternStore] Initialized (legacy): ${this.config.dbPath}`)}this.deduplicatePatterns(),this.prepareStatements(),this.initialized=!0}catch(e){throw new Error(`Failed to initialize SQLite: ${_(e)}`)}}createSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
3
3
  -- QE Patterns table
4
4
  CREATE TABLE IF NOT EXISTS qe_patterns (
5
5
  id TEXT PRIMARY KEY,
@@ -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.9.2");process.exit(0)}
2
- import{a as o,e as l}from"./chunk-MN742FIH.js";import{a,d as u}from"./chunk-4DAOZQ3V.js";u();l();var c=class{store=new Map;vectors=new Map;cleanupInterval;async initialize(){this.cleanupInterval=setInterval(()=>this.cleanup(),o.CLEANUP_INTERVAL_MS),this.cleanupInterval.unref&&this.cleanupInterval.unref()}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.store.clear(),this.vectors.clear()}async set(t,r,e){let s={value:r,namespace:e?.namespace??"default",createdAt:Date.now()};e?.ttl&&(s.expiresAt=Date.now()+e.ttl*o.TTL_MULTIPLIER_MS);let n=this.buildKey(t,e?.namespace);this.store.set(n,s)}async get(t,r){let e=this.buildKey(t,r),s=this.store.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.store.delete(e);return}return s.value}}async delete(t,r){let e=this.buildKey(t,r);return this.store.delete(e)}async has(t,r){return await this.get(t,r)!==void 0}async search(t,r=o.DEFAULT_SEARCH_LIMIT){let e=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(e.replace(/\*/g,".*")),n=[];for(let i of this.store.keys())if(s.test(i)&&(n.push(i),n.length>=r))break;return n}async vectorSearch(t,r){let e=[];for(let[s,n]of this.vectors.entries()){let i=a(t,n.embedding);e.push({key:s,score:i,metadata:n.metadata})}return e.sort((s,n)=>n.score-s.score).slice(0,r)}async storeVector(t,r,e){this.vectors.set(t,{embedding:r,metadata:e})}buildKey(t,r){return r?`${r}:${t}`:t}cleanup(){let t=Date.now();for(let[r,e]of this.store.entries())e.expiresAt&&t>e.expiresAt&&this.store.delete(r)}getStats(){return{entries:this.store.size,vectors:this.vectors.size}}async clear(t){if(t){let r=`${t}:`;for(let e of this.store.keys())e.startsWith(r)&&this.store.delete(e)}else this.store.clear()}async count(t){let r=0,e=`${t}:`;for(let s of this.store.keys())if(s.startsWith(e)){let n=this.store.get(s);n&&(!n.expiresAt||Date.now()<=n.expiresAt)&&r++}return r}async hasCodeIntelligenceIndex(){return await this.count("code-intelligence:kg")>0}};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.9.4");process.exit(0)}
2
+ import{a as o,e as l}from"./chunk-KELYPHMV.js";import{a,d as u}from"./chunk-Q2ZYUIS2.js";u();l();var c=class{store=new Map;vectors=new Map;cleanupInterval;async initialize(){this.cleanupInterval=setInterval(()=>this.cleanup(),o.CLEANUP_INTERVAL_MS),this.cleanupInterval.unref&&this.cleanupInterval.unref()}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.store.clear(),this.vectors.clear()}async set(t,r,e){let s={value:r,namespace:e?.namespace??"default",createdAt:Date.now()};e?.ttl&&(s.expiresAt=Date.now()+e.ttl*o.TTL_MULTIPLIER_MS);let n=this.buildKey(t,e?.namespace);this.store.set(n,s)}async get(t,r){let e=this.buildKey(t,r),s=this.store.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.store.delete(e);return}return s.value}}async delete(t,r){let e=this.buildKey(t,r);return this.store.delete(e)}async has(t,r){return await this.get(t,r)!==void 0}async search(t,r=o.DEFAULT_SEARCH_LIMIT){let e=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(e.replace(/\*/g,".*")),n=[];for(let i of this.store.keys())if(s.test(i)&&(n.push(i),n.length>=r))break;return n}async vectorSearch(t,r){let e=[];for(let[s,n]of this.vectors.entries()){let i=a(t,n.embedding);e.push({key:s,score:i,metadata:n.metadata})}return e.sort((s,n)=>n.score-s.score).slice(0,r)}async storeVector(t,r,e){this.vectors.set(t,{embedding:r,metadata:e})}buildKey(t,r){return r?`${r}:${t}`:t}cleanup(){let t=Date.now();for(let[r,e]of this.store.entries())e.expiresAt&&t>e.expiresAt&&this.store.delete(r)}getStats(){return{entries:this.store.size,vectors:this.vectors.size}}async clear(t){if(t){let r=`${t}:`;for(let e of this.store.keys())e.startsWith(r)&&this.store.delete(e)}else this.store.clear()}async count(t){let r=0,e=`${t}:`;for(let s of this.store.keys())if(s.startsWith(e)){let n=this.store.get(s);n&&(!n.expiresAt||Date.now()<=n.expiresAt)&&r++}return r}async hasCodeIntelligenceIndex(){return await this.count("code-intelligence:kg")>0}};export{c as a};
@@ -1,7 +1,7 @@
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.9.2");process.exit(0)}
2
- import{a as I}from"./chunk-SGAW2WLI.js";import{a as A}from"./chunk-TKF447CW.js";import{k as _,n as B,o as U}from"./chunk-GK72GUHA.js";import{d as P,e as K}from"./chunk-JOVINE23.js";import{b as w,d as Q}from"./chunk-N3F3CX4V.js";import{a as g,c as R}from"./chunk-SDTVHR63.js";import{g as N}from"./chunk-YXCU4CJX.js";U();R();Q();K();import{randomUUID as z}from"crypto";var D=P("TokenTracker"),O={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},j={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},S=class c{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=j;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${z().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=O}initialize(e){this.initialized||(this.initialized=!0,e&&(this.costConfig={...O,...e}),this.initializeDb().catch(t=>{D.warn("DB initialization failed",{error:t instanceof Error?t.message:String(t)})}),this.startAutoSave())}setCostConfig(e){this.costConfig={...this.costConfig,...e}}recordTokenUsage(e,t,i,n,s,o){this.ensureInitialized();let l,u,r,a,m,d;typeof t=="object"?(l="default",u="unknown",r="unknown",a=t,m=!1,d=0):(l=t,u=i??"unknown",r=n??"unknown",a=s,m=o?.patternReused??!1,d=o?.tokensSaved??0),a.estimatedCostUsd===void 0&&(a.estimatedCostUsd=this.calculateCost(a));let h={taskId:e,agentId:l,domain:u,operation:r,timestamp:Date.now(),usage:a,patternReused:m,tokensSaved:d};this.taskMetrics.push(h),this.updateAgentMetrics(l,a,m,d),this.updateDomainMetrics(u,a),m&&this.totalPatternsReused++,d>0&&(this.totalTokensSaved+=d),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(e,t){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=t;let i={taskId:e,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:t};this.taskMetrics.push(i),this.isDirty=!0}recordCacheHit(e){this.cacheHits++,this.totalTokensSaved+=e,this.isDirty=!0}recordEarlyExit(e){this.earlyExits++,this.totalTokensSaved+=e,this.isDirty=!0}getSessionSummary(e){this.ensureInitialized();let t=this.filterByTimeframe(this.taskMetrics,e),i=this.aggregateTokenUsage(t),n=new Map;for(let r of t){let a=n.get(r.agentId);a?(a.totalInputTokens+=r.usage.inputTokens,a.totalOutputTokens+=r.usage.outputTokens,a.totalTokens+=r.usage.totalTokens,a.totalCost+=r.usage.estimatedCostUsd||0,a.tasksExecuted++,r.patternReused&&a.patternsReused++,a.estimatedTokensSaved+=r.tokensSaved||0):n.set(r.agentId,{agentId:r.agentId,totalInputTokens:r.usage.inputTokens,totalOutputTokens:r.usage.outputTokens,totalTokens:r.usage.totalTokens,totalCost:r.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:r.patternReused?1:0,estimatedTokensSaved:r.tokensSaved||0})}let s=new Map;for(let r of t){let a=s.get(r.domain);a?(a.inputTokens+=r.usage.inputTokens,a.outputTokens+=r.usage.outputTokens,a.totalTokens+=r.usage.totalTokens,a.estimatedCostUsd=(a.estimatedCostUsd||0)+(r.usage.estimatedCostUsd||0)):s.set(r.domain,{...r.usage})}let o=i.totalTokens,l=this.totalTokensSaved,u=o+l>0?l/(o+l)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:n,byDomain:s,totalUsage:i,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(u*100)/100}}}getAgentMetrics(e,t){this.ensureInitialized();let i=this.filterByTimeframe(this.taskMetrics,t);if(e){let s=i.filter(o=>o.agentId===e);return this.aggregateAgentMetrics(e,s)}let n=new Map;for(let s of i){let o=n.get(s.agentId)||[];o.push(s),n.set(s.agentId,o)}return Array.from(n.entries()).map(([s,o])=>this.aggregateAgentMetrics(s,o))}getDomainMetrics(e,t){this.ensureInitialized();let i=this.filterByTimeframe(this.taskMetrics,t);if(e){let s=i.filter(o=>o.domain===e);return this.aggregateTokenUsage(s)}let n=new Map;for(let s of i){let o=n.get(s.domain);o?(o.inputTokens+=s.usage.inputTokens,o.outputTokens+=s.usage.outputTokens,o.totalTokens+=s.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):n.set(s.domain,{...s.usage})}return n}getTaskMetrics(e){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,e)}getEfficiencyReport(e){return this.getTokenEfficiency(e)}getTokenEfficiency(e){this.ensureInitialized();let t=this.filterByTimeframe(this.taskMetrics,e),n=this.aggregateTokenUsage(t).totalTokens,s=this.totalTokensSaved,o=n+s>0?s/(n+s)*100:0,l=t.length,u=l>0?t.filter(m=>m.patternReused).length/l:0,r=l>0?n/l:0,a=this.generateRecommendations(t);return{totalTokensUsed:n,totalTokensSaved:s,savingsPercentage:Math.round(o*100)/100,patternReuseRate:Math.round(u*100)/100,averageTokensPerTask:Math.round(r),recommendations:a}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${z().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(e){this.persistenceConfig={...this.persistenceConfig,...e},e.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),e.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(e=>{console.warn("[TokenMetricsCollector] Auto-save failed:",e)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let e=await import("fs"),t=await import("path"),i={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},n=t.resolve(this.persistenceConfig.filePath),s=t.dirname(n);e.existsSync(s)||e.mkdirSync(s,{recursive:!0}),e.writeFileSync(n,JSON.stringify(i,null,2)),this.isDirty=!1}async load(){let e=await import("fs"),i=(await import("path")).resolve(this.persistenceConfig.filePath);if(!e.existsSync(i))return!1;try{let n=e.readFileSync(i,"utf-8"),s=w(n);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let o=s.taskMetrics||[];this.taskMetrics=[...o,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let l of o)this.updateAgentMetrics(l.agentId,l.usage,l.patternReused,l.tokensSaved||0),this.updateDomainMetrics(l.domain,l.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(n){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",n),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=_(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(e){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",g(e)),this.db=null}}async persistToKv(){if(!this.db)return;let e={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(c.KV_KEY,e,c.KV_NAMESPACE,c.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let e=await this.db.kvGet(c.KV_KEY,c.KV_NAMESPACE);if(!e)return!1;if(!e.version||!e.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let t=e.taskMetrics||[];this.taskMetrics=[...t,...this.taskMetrics],this.cacheHits+=e.optimizationStats?.cacheHits||0,this.earlyExits+=e.optimizationStats?.earlyExits||0,this.totalTokensSaved+=e.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=e.optimizationStats?.totalPatternsReused||0;for(let i of t)this.updateAgentMetrics(i.agentId,i.usage,i.patternReused,i.tokensSaved||0),this.updateDomainMetrics(i.domain,i.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=c.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(e=>{D.warn("KV persist failed",{error:e instanceof Error?e.message:String(e)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(e){let t=e.inputTokens*this.costConfig.costPerInputToken,i=e.outputTokens*this.costConfig.costPerOutputToken;return Math.round((t+i)*1e5)/1e5}filterByTimeframe(e,t){if(!t)return e;let i=Date.now(),n;switch(t){case"1h":n=i-3600*1e3;break;case"24h":n=i-1440*60*1e3;break;case"7d":n=i-10080*60*1e3;break;case"30d":n=i-720*60*60*1e3;break;default:return e}return e.filter(s=>s.timestamp>=n)}aggregateTokenUsage(e){let t=0,i=0,n=0,s=0;for(let o of e)t+=o.usage.inputTokens,i+=o.usage.outputTokens,n+=o.usage.totalTokens,s+=o.usage.estimatedCostUsd||0;return{inputTokens:t,outputTokens:i,totalTokens:n,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(e,t){let i=0,n=0,s=0,o=0,l=0,u=0;for(let r of t)i+=r.usage.inputTokens,n+=r.usage.outputTokens,s+=r.usage.totalTokens,o+=r.usage.estimatedCostUsd||0,r.patternReused&&l++,u+=r.tokensSaved||0;return{agentId:e,totalInputTokens:i,totalOutputTokens:n,totalTokens:s,totalCost:Math.round(o*1e5)/1e5,tasksExecuted:t.length,patternsReused:l,estimatedTokensSaved:u}}updateAgentMetrics(e,t,i,n){let s=this.agentMetrics.get(e);s?(s.totalInputTokens+=t.inputTokens,s.totalOutputTokens+=t.outputTokens,s.totalTokens+=t.totalTokens,s.totalCost+=t.estimatedCostUsd||0,s.tasksExecuted++,i&&s.patternsReused++,s.estimatedTokensSaved+=n):this.agentMetrics.set(e,{agentId:e,totalInputTokens:t.inputTokens,totalOutputTokens:t.outputTokens,totalTokens:t.totalTokens,totalCost:t.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i?1:0,estimatedTokensSaved:n})}updateDomainMetrics(e,t){let i=this.domainMetrics.get(e);i?(i.inputTokens+=t.inputTokens,i.outputTokens+=t.outputTokens,i.totalTokens+=t.totalTokens,i.estimatedCostUsd=(i.estimatedCostUsd||0)+(t.estimatedCostUsd||0)):this.domainMetrics.set(e,{...t})}generateRecommendations(e){let t=[];if(e.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let i=e.filter(r=>r.patternReused).length/e.length;i<.2?t.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):i>.5&&t.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let n=new Map;for(let r of e){let a=n.get(r.domain)||0;n.set(r.domain,a+r.usage.totalTokens)}let s=Array.from(n.entries()).sort((r,a)=>a[1]-r[1]);if(s.length>0){let r=s[0];t.push(`Highest token consumer: ${r[0]} (${r[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let o=e.reduce((r,a)=>r+a.usage.inputTokens,0);return e.reduce((r,a)=>r+a.usage.outputTokens,0)/(o||1)>2&&t.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&e.length>10&&t.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&e.length>20&&t.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),t}};function F(c){return c.toLocaleString("en-US")}function $(c){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!c){let u=p.getSessionSummary(),r=u.totalUsage.totalTokens,a=u.totalUsage.estimatedCostUsd??0,m=u.optimizationStats.tokensSaved,d=r>0?a/r:0,h=m*d;c={totalTokens:r,totalCostUsd:a,savedTokens:m,savedCostUsd:h}}let e=c.totalTokens??0,t=c.totalCostUsd??0,i=c.savedTokens??0,n=c.savedCostUsd??0,s=c.budgetLimitUsd;if(e===0&&i===0)return"Token Dashboard: No data available";let o=`Token Usage: ${F(e)} tokens ($${t.toFixed(2)})`;i>0&&(o+=` | Saved: ${F(i)} tokens ($${n.toFixed(2)}) via pattern reuse`);let l=[];if(s!==void 0&&s>0){let u=Math.round(t/s*100);l.push(`Budget: $${t.toFixed(2)} / $${s.toFixed(2)} (${u}%)`)}if(c.tierSplit&&Object.keys(c.tierSplit).length>0){let u=Object.entries(c.tierSplit).sort((r,a)=>a[1]-r[1]).map(([r,a])=>`${r} ${a}%`);l.push(`Tier split: ${u.join(" | ")}`)}return l.length===0?o:`${o}
3
- ${l.join(" | ")}`}var p=new S;function te(c){return`$${c.toFixed(2)}`}import{createHash as V}from"crypto";var G={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function E(c){if(c==null||typeof c!="object")return JSON.stringify(c);if(Array.isArray(c))return"["+c.map(n=>E(n)).join(",")+"]";let e=c;return"{"+Object.keys(e).sort().map(n=>JSON.stringify(n)+":"+E(e[n])).join(",")+"}"}var b=class{cache=new Map;config;hits=0;misses=0;constructor(e){this.config={...G,...e}}computeFingerprint(e,t,i){let n=E({action:t,domain:e,input:i});return V("sha256").update(n).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,i,n,s){if(!this.config.enabled)return;this.cache.size>=this.config.maxEntries&&this.evictOldest();let o={fingerprint:e,domain:t,action:i,result:n,tokensSaved:s,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,o),this.config.persistToDb&&this.persistEntry(o)}loadFromDb(){try{let e=H();if(!e)return;let t=Date.now()-this.config.ttlMs,i=e.prepare(`SELECT key, value FROM kv_store
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.9.4");process.exit(0)}
2
+ import{a as A}from"./chunk-VBXJBXMG.js";import{a as z}from"./chunk-UJLSCJJS.js";import{k as _,n as Q,o as U}from"./chunk-G6RTCJFY.js";import{d as P,e as B}from"./chunk-RPYUKEAH.js";import{b as w,d as K}from"./chunk-4GJAYXB7.js";import{a as p,c as R}from"./chunk-F6AU2MAZ.js";import{g as N}from"./chunk-C2HGOUEB.js";U();R();K();B();import{randomUUID as I}from"crypto";var D=P("TokenTracker"),O={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},j={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},S=class c{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=j;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${I().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=O}initialize(e){this.initialized||(this.initialized=!0,e&&(this.costConfig={...O,...e}),this.initializeDb().catch(t=>{D.warn("DB initialization failed",{error:t instanceof Error?t.message:String(t)})}),this.startAutoSave())}setCostConfig(e){this.costConfig={...this.costConfig,...e}}recordTokenUsage(e,t,n,i,s,o){this.ensureInitialized();let l,u,r,a,m,d;typeof t=="object"?(l="default",u="unknown",r="unknown",a=t,m=!1,d=0):(l=t,u=n??"unknown",r=i??"unknown",a=s,m=o?.patternReused??!1,d=o?.tokensSaved??0),a.estimatedCostUsd===void 0&&(a.estimatedCostUsd=this.calculateCost(a));let h={taskId:e,agentId:l,domain:u,operation:r,timestamp:Date.now(),usage:a,patternReused:m,tokensSaved:d};this.taskMetrics.push(h),this.updateAgentMetrics(l,a,m,d),this.updateDomainMetrics(u,a),m&&this.totalPatternsReused++,d>0&&(this.totalTokensSaved+=d),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(e,t){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=t;let n={taskId:e,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:t};this.taskMetrics.push(n),this.isDirty=!0}recordCacheHit(e){this.cacheHits++,this.totalTokensSaved+=e,this.isDirty=!0}recordEarlyExit(e){this.earlyExits++,this.totalTokensSaved+=e,this.isDirty=!0}getSessionSummary(e){this.ensureInitialized();let t=this.filterByTimeframe(this.taskMetrics,e),n=this.aggregateTokenUsage(t),i=new Map;for(let r of t){let a=i.get(r.agentId);a?(a.totalInputTokens+=r.usage.inputTokens,a.totalOutputTokens+=r.usage.outputTokens,a.totalTokens+=r.usage.totalTokens,a.totalCost+=r.usage.estimatedCostUsd||0,a.tasksExecuted++,r.patternReused&&a.patternsReused++,a.estimatedTokensSaved+=r.tokensSaved||0):i.set(r.agentId,{agentId:r.agentId,totalInputTokens:r.usage.inputTokens,totalOutputTokens:r.usage.outputTokens,totalTokens:r.usage.totalTokens,totalCost:r.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:r.patternReused?1:0,estimatedTokensSaved:r.tokensSaved||0})}let s=new Map;for(let r of t){let a=s.get(r.domain);a?(a.inputTokens+=r.usage.inputTokens,a.outputTokens+=r.usage.outputTokens,a.totalTokens+=r.usage.totalTokens,a.estimatedCostUsd=(a.estimatedCostUsd||0)+(r.usage.estimatedCostUsd||0)):s.set(r.domain,{...r.usage})}let o=n.totalTokens,l=this.totalTokensSaved,u=o+l>0?l/(o+l)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:i,byDomain:s,totalUsage:n,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(u*100)/100}}}getAgentMetrics(e,t){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,t);if(e){let s=n.filter(o=>o.agentId===e);return this.aggregateAgentMetrics(e,s)}let i=new Map;for(let s of n){let o=i.get(s.agentId)||[];o.push(s),i.set(s.agentId,o)}return Array.from(i.entries()).map(([s,o])=>this.aggregateAgentMetrics(s,o))}getDomainMetrics(e,t){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,t);if(e){let s=n.filter(o=>o.domain===e);return this.aggregateTokenUsage(s)}let i=new Map;for(let s of n){let o=i.get(s.domain);o?(o.inputTokens+=s.usage.inputTokens,o.outputTokens+=s.usage.outputTokens,o.totalTokens+=s.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):i.set(s.domain,{...s.usage})}return i}getTaskMetrics(e){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,e)}getEfficiencyReport(e){return this.getTokenEfficiency(e)}getTokenEfficiency(e){this.ensureInitialized();let t=this.filterByTimeframe(this.taskMetrics,e),i=this.aggregateTokenUsage(t).totalTokens,s=this.totalTokensSaved,o=i+s>0?s/(i+s)*100:0,l=t.length,u=l>0?t.filter(m=>m.patternReused).length/l:0,r=l>0?i/l:0,a=this.generateRecommendations(t);return{totalTokensUsed:i,totalTokensSaved:s,savingsPercentage:Math.round(o*100)/100,patternReuseRate:Math.round(u*100)/100,averageTokensPerTask:Math.round(r),recommendations:a}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${I().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(e){this.persistenceConfig={...this.persistenceConfig,...e},e.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),e.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(e=>{console.warn("[TokenMetricsCollector] Auto-save failed:",e)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let e=await import("fs"),t=await import("path"),n={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},i=t.resolve(this.persistenceConfig.filePath),s=t.dirname(i);e.existsSync(s)||e.mkdirSync(s,{recursive:!0}),e.writeFileSync(i,JSON.stringify(n,null,2)),this.isDirty=!1}async load(){let e=await import("fs"),n=(await import("path")).resolve(this.persistenceConfig.filePath);if(!e.existsSync(n))return!1;try{let i=e.readFileSync(n,"utf-8"),s=w(i);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let o=s.taskMetrics||[];this.taskMetrics=[...o,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let l of o)this.updateAgentMetrics(l.agentId,l.usage,l.patternReused,l.tokensSaved||0),this.updateDomainMetrics(l.domain,l.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(i){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",i),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=_(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(e){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",p(e)),this.db=null}}async persistToKv(){if(!this.db)return;let e={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(c.KV_KEY,e,c.KV_NAMESPACE,c.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let e=await this.db.kvGet(c.KV_KEY,c.KV_NAMESPACE);if(!e)return!1;if(!e.version||!e.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let t=e.taskMetrics||[];this.taskMetrics=[...t,...this.taskMetrics],this.cacheHits+=e.optimizationStats?.cacheHits||0,this.earlyExits+=e.optimizationStats?.earlyExits||0,this.totalTokensSaved+=e.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=e.optimizationStats?.totalPatternsReused||0;for(let n of t)this.updateAgentMetrics(n.agentId,n.usage,n.patternReused,n.tokensSaved||0),this.updateDomainMetrics(n.domain,n.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=c.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(e=>{D.warn("KV persist failed",{error:e instanceof Error?e.message:String(e)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(e){let t=e.inputTokens*this.costConfig.costPerInputToken,n=e.outputTokens*this.costConfig.costPerOutputToken;return Math.round((t+n)*1e5)/1e5}filterByTimeframe(e,t){if(!t)return e;let n=Date.now(),i;switch(t){case"1h":i=n-3600*1e3;break;case"24h":i=n-1440*60*1e3;break;case"7d":i=n-10080*60*1e3;break;case"30d":i=n-720*60*60*1e3;break;default:return e}return e.filter(s=>s.timestamp>=i)}aggregateTokenUsage(e){let t=0,n=0,i=0,s=0;for(let o of e)t+=o.usage.inputTokens,n+=o.usage.outputTokens,i+=o.usage.totalTokens,s+=o.usage.estimatedCostUsd||0;return{inputTokens:t,outputTokens:n,totalTokens:i,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(e,t){let n=0,i=0,s=0,o=0,l=0,u=0;for(let r of t)n+=r.usage.inputTokens,i+=r.usage.outputTokens,s+=r.usage.totalTokens,o+=r.usage.estimatedCostUsd||0,r.patternReused&&l++,u+=r.tokensSaved||0;return{agentId:e,totalInputTokens:n,totalOutputTokens:i,totalTokens:s,totalCost:Math.round(o*1e5)/1e5,tasksExecuted:t.length,patternsReused:l,estimatedTokensSaved:u}}updateAgentMetrics(e,t,n,i){let s=this.agentMetrics.get(e);s?(s.totalInputTokens+=t.inputTokens,s.totalOutputTokens+=t.outputTokens,s.totalTokens+=t.totalTokens,s.totalCost+=t.estimatedCostUsd||0,s.tasksExecuted++,n&&s.patternsReused++,s.estimatedTokensSaved+=i):this.agentMetrics.set(e,{agentId:e,totalInputTokens:t.inputTokens,totalOutputTokens:t.outputTokens,totalTokens:t.totalTokens,totalCost:t.estimatedCostUsd||0,tasksExecuted:1,patternsReused:n?1:0,estimatedTokensSaved:i})}updateDomainMetrics(e,t){let n=this.domainMetrics.get(e);n?(n.inputTokens+=t.inputTokens,n.outputTokens+=t.outputTokens,n.totalTokens+=t.totalTokens,n.estimatedCostUsd=(n.estimatedCostUsd||0)+(t.estimatedCostUsd||0)):this.domainMetrics.set(e,{...t})}generateRecommendations(e){let t=[];if(e.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let n=e.filter(r=>r.patternReused).length/e.length;n<.2?t.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):n>.5&&t.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let i=new Map;for(let r of e){let a=i.get(r.domain)||0;i.set(r.domain,a+r.usage.totalTokens)}let s=Array.from(i.entries()).sort((r,a)=>a[1]-r[1]);if(s.length>0){let r=s[0];t.push(`Highest token consumer: ${r[0]} (${r[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let o=e.reduce((r,a)=>r+a.usage.inputTokens,0);return e.reduce((r,a)=>r+a.usage.outputTokens,0)/(o||1)>2&&t.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&e.length>10&&t.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&e.length>20&&t.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),t}};function F(c){return c.toLocaleString("en-US")}function $(c){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!c){let u=g.getSessionSummary(),r=u.totalUsage.totalTokens,a=u.totalUsage.estimatedCostUsd??0,m=u.optimizationStats.tokensSaved,d=r>0?a/r:0,h=m*d;c={totalTokens:r,totalCostUsd:a,savedTokens:m,savedCostUsd:h}}let e=c.totalTokens??0,t=c.totalCostUsd??0,n=c.savedTokens??0,i=c.savedCostUsd??0,s=c.budgetLimitUsd;if(e===0&&n===0)return"Token Dashboard: No data available";let o=`Token Usage: ${F(e)} tokens ($${t.toFixed(2)})`;n>0&&(o+=` | Saved: ${F(n)} tokens ($${i.toFixed(2)}) via pattern reuse`);let l=[];if(s!==void 0&&s>0){let u=Math.round(t/s*100);l.push(`Budget: $${t.toFixed(2)} / $${s.toFixed(2)} (${u}%)`)}if(c.tierSplit&&Object.keys(c.tierSplit).length>0){let u=Object.entries(c.tierSplit).sort((r,a)=>a[1]-r[1]).map(([r,a])=>`${r} ${a}%`);l.push(`Tier split: ${u.join(" | ")}`)}return l.length===0?o:`${o}
3
+ ${l.join(" | ")}`}var g=new S;function te(c){return`$${c.toFixed(2)}`}import{createHash as V}from"crypto";var G={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function E(c){if(c==null||typeof c!="object")return JSON.stringify(c);if(Array.isArray(c))return"["+c.map(i=>E(i)).join(",")+"]";let e=c;return"{"+Object.keys(e).sort().map(i=>JSON.stringify(i)+":"+E(e[i])).join(",")+"}"}var b=class{cache=new Map;config;hits=0;misses=0;constructor(e){this.config={...G,...e}}computeFingerprint(e,t,n){let i=E({action:t,domain:e,input:n});return V("sha256").update(i).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,n,i,s){if(!this.config.enabled)return;this.cache.size>=this.config.maxEntries&&this.evictOldest();let o={fingerprint:e,domain:t,action:n,result:i,tokensSaved:s,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,o),this.config.persistToDb&&this.persistEntry(o)}loadFromDb(){try{let e=H();if(!e)return;let t=Date.now()-this.config.ttlMs,n=e.prepare(`SELECT key, value FROM kv_store
4
4
  WHERE namespace = 'session_cache'
5
5
  AND created_at > ?
6
- ORDER BY created_at DESC LIMIT ?`).all(t,this.config.maxEntries);for(let n of i)try{let s=JSON.parse(n.value);Date.now()-s.cachedAt<=this.config.ttlMs&&this.cache.set(s.fingerprint,s)}catch{}}catch{}}getStats(){let e=this.hits+this.misses,t=0;for(let i of this.cache.values())t+=i.tokensSaved*i.hitCount;return{size:this.cache.size,hits:this.hits,misses:this.misses,hitRate:e>0?this.hits/e:0,estimatedTokensSaved:t}}clear(){this.cache.clear(),this.hits=0,this.misses=0}evictOldest(){let e=null,t=1/0;for(let[i,n]of this.cache)n.cachedAt<t&&(t=n.cachedAt,e=i);e&&this.cache.delete(e)}persistEntry(e){try{let t=H();if(!t)return;t.prepare(`INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
7
- VALUES (?, 'session_cache', ?, ?)`).run(`session_cache:${e.fingerprint}`,JSON.stringify(e),Date.now())}catch{}}};function H(){try{let{getUnifiedMemory:c}=(U(),N(B)),e=c();return e.isInitialized()?e.getDatabase():null}catch{return null}}var f=null;function k(c){return f||(f=new b(c),f.loadFromDb()),f}import{randomUUID as q}from"crypto";R();var x={minConfidenceForExit:.85,minSuccessRate:.9,maxPatternAge:10080*60*1e3,minQualityScore:.7,minSuccessfulUses:2,maxSearchResults:5,similarityThreshold:.8,verbose:!1},ae={minConfidenceForExit:.75,minSuccessRate:.8,maxPatternAge:336*60*60*1e3,minQualityScore:.6,minSuccessfulUses:1,maxSearchResults:10,similarityThreshold:.7,verbose:!1},ce={minConfidenceForExit:.92,minSuccessRate:.95,maxPatternAge:4320*60*1e3,minQualityScore:.85,minSuccessfulUses:3,maxSearchResults:3,similarityThreshold:.9,verbose:!1},T=class{patternStore;config;reuseHistory=[];attemptHistory=[];constructor(e,t){this.patternStore=e,this.config={...x,...t}}async checkEarlyExit(e){let t=performance.now(),i=new Date;try{let n=e.domain??A(e.description)??void 0,s={limit:this.config.maxSearchResults*2,useVectorSearch:!!e.embedding};n&&(s.domain=n),e.context&&(s.context={language:e.context.language,framework:e.context.framework,testType:e.context.testType});let o=e.embedding??e.description,l=await this.patternStore.search(o,s),u=performance.now()-t;if(!l.success){let d="error"in l?l.error.message:"Unknown error",h=this.createResult(!1,"search_error",`Pattern search failed: ${d}`,u);return this.recordAttempt("search_error",n),h}let r=l.value;if(r.length===0){let d=this.createResult(!1,"no_matching_pattern","No matching patterns found in store",u);return this.recordAttempt("no_matching_pattern",n),d}let a=null;for(let{pattern:d,score:h}of r){let y=this.evaluatePatternEligibility(d,h,i);if(y.eligible){let v=this.estimateTokensSaved(d),L={canExit:!0,reusedPattern:d,estimatedTokensSaved:v,confidence:d.confidence,similarityScore:h,reason:"pattern_reused",explanation:`Reusing pattern "${d.name}" with ${(d.confidence*100).toFixed(1)}% confidence`,searchLatencyMs:u};return this.recordReuse(d.id,v,d.confidence,h,u,n),this.config.verbose&&console.log(`[EarlyExitTokenOptimizer] Pattern reuse: ${d.name} (confidence: ${d.confidence.toFixed(2)}, similarity: ${h.toFixed(2)}, tokens saved: ${v})`),L}a===null&&(a={reason:y.reason,explanation:y.explanation})}if(a){let d=this.createResult(!1,a.reason,a.explanation,u);return this.recordAttempt(a.reason,n),d}let m=this.createResult(!1,"no_matching_pattern",`Found ${r.length} patterns but none met eligibility criteria`,u);return this.recordAttempt("no_matching_pattern",n),m}catch(n){let s=performance.now()-t,o=this.createResult(!1,"search_error",`Error during pattern search: ${g(n)}`,s);return this.recordAttempt("search_error"),o}}evaluatePatternEligibility(e,t,i){if(t<this.config.similarityThreshold)return{eligible:!1,reason:"similarity_too_low",explanation:`Similarity ${(t*100).toFixed(1)}% < threshold ${(this.config.similarityThreshold*100).toFixed(1)}%`};if(e.confidence<this.config.minConfidenceForExit)return{eligible:!1,reason:"confidence_too_low",explanation:`Confidence ${(e.confidence*100).toFixed(1)}% < threshold ${(this.config.minConfidenceForExit*100).toFixed(1)}%`};if(e.successRate<this.config.minSuccessRate)return{eligible:!1,reason:"success_rate_too_low",explanation:`Success rate ${(e.successRate*100).toFixed(1)}% < threshold ${(this.config.minSuccessRate*100).toFixed(1)}%`};let n=i.getTime()-e.lastUsedAt.getTime();if(n>this.config.maxPatternAge){let s=Math.floor(n/864e5),o=Math.floor(this.config.maxPatternAge/(1440*60*1e3));return{eligible:!1,reason:"pattern_too_old",explanation:`Pattern age ${s} days > max ${o} days`}}return e.qualityScore<this.config.minQualityScore?{eligible:!1,reason:"quality_score_too_low",explanation:`Quality score ${(e.qualityScore*100).toFixed(1)}% < threshold ${(this.config.minQualityScore*100).toFixed(1)}%`}:e.successfulUses<this.config.minSuccessfulUses?{eligible:!1,reason:"insufficient_uses",explanation:`Successful uses ${e.successfulUses} < minimum ${this.config.minSuccessfulUses}`}:{eligible:!0,reason:"pattern_reused",explanation:"Pattern meets all eligibility criteria"}}estimateTokensSaved(e){let t=100,i=Math.ceil(e.template.content.length/4);t+=i,t+=50;let o={"test-template":1.5,"assertion-pattern":1,"mock-pattern":1.2,"coverage-strategy":1.3,"api-contract":1.4,"visual-baseline":1.1,"perf-benchmark":1.4,"flaky-fix":1.3,"error-handling":1.2}[e.patternType]??1;return Math.ceil(t*o)}createResult(e,t,i,n){return{canExit:e,reason:t,explanation:i,searchLatencyMs:n}}recordReuse(e,t,i,n,s,o){this.reuseHistory.push({patternId:e,tokensSaved:t,confidence:i,similarity:n,latencyMs:s,domain:o,timestamp:new Date}),this.attemptHistory.push({reason:"pattern_reused",domain:o,timestamp:new Date}),this.reuseHistory.length>1e4&&(this.reuseHistory=this.reuseHistory.slice(-1e4))}recordAttempt(e,t){this.attemptHistory.push({reason:e,domain:t,timestamp:new Date}),this.attemptHistory.length>1e4&&(this.attemptHistory=this.attemptHistory.slice(-1e4))}recordSuccessfulReuse(e){this.patternStore.recordUsage(e,!0).catch(t=>{console.warn(`[EarlyExitTokenOptimizer] Failed to record successful reuse for ${e}:`,t)})}recordFailedReuse(e){this.patternStore.recordUsage(e,!1).catch(t=>{console.warn(`[EarlyExitTokenOptimizer] Failed to record failed reuse for ${e}:`,t)})}getReuseStats(){let e=this.reuseHistory.length,t=this.attemptHistory.length,i=0,n=0,s=0,o=0;for(let r of this.reuseHistory)i+=r.tokensSaved,n+=r.confidence,s+=r.similarity,o+=r.latencyMs;let l={pattern_reused:0,no_matching_pattern:0,confidence_too_low:0,success_rate_too_low:0,pattern_too_old:0,quality_score_too_low:0,insufficient_uses:0,similarity_too_low:0,search_error:0};for(let r of this.attemptHistory)l[r.reason]++;let u={};for(let r of this.reuseHistory){let a=r.domain??"unknown";u[a]||(u[a]={reuses:0,tokens:0}),u[a].reuses++,u[a].tokens+=r.tokensSaved}return{totalReuses:e,tokensSaved:i,avgConfidence:e>0?n/e:0,avgSimilarity:e>0?s/e:0,avgSearchLatencyMs:e>0?o/e:0,totalAttempts:t,exitRate:t>0?e/t:0,reasonBreakdown:l,domainBreakdown:u}}resetStats(){this.reuseHistory=[],this.attemptHistory=[]}getConfig(){return{...this.config}}updateConfig(e){Object.assign(this.config,e)}};var C={enabled:!0,earlyExit:x,verbose:!1},M=class{optimizer=null;patternStore=null;config=C;initialized=!1;async initialize(e,t){if(!this.initialized){if(this.config={...C,...t},!this.config.enabled){this.config.verbose&&console.log("[TokenOptimizerService] Service disabled by configuration");return}try{this.patternStore=I(e),await this.patternStore.initialize(),this.optimizer=new T(this.patternStore,this.config.earlyExit),this.initialized=!0,this.config.verbose&&console.log("[TokenOptimizerService] Initialized with EarlyExitTokenOptimizer")}catch(i){console.warn("[TokenOptimizerService] Failed to initialize:",i)}}}async checkEarlyExit(e){if(!this.initialized||!this.optimizer)return{canExit:!1,reason:"no_matching_pattern",explanation:"Token optimizer service not initialized",searchLatencyMs:0};try{let i=k(),n=i.computeFingerprint(e.domain??"unknown",e.description,e.context??{}),s=i.get(n);if(s)return p.recordEarlyExit(s.tokensSaved),this.config.verbose&&console.log(`[TokenOptimizerService] Session cache hit: ${n.slice(0,8)}... (saved ${s.tokensSaved} tokens)`),{canExit:!0,estimatedTokensSaved:s.tokensSaved,confidence:1,similarityScore:1,reason:"pattern_reused",explanation:`Session cache exact match (fingerprint: ${n.slice(0,8)}...)`,searchLatencyMs:0}}catch{}let t=await this.optimizer.checkEarlyExit(e);return t.canExit&&t.estimatedTokensSaved&&(p.recordEarlyExit(t.estimatedTokensSaved),this.config.verbose&&console.log(`[TokenOptimizerService] Early exit: ${t.reusedPattern?.name} (saved ${t.estimatedTokensSaved} tokens)`)),t}async checkTaskEarlyExit(e,t){return this.checkEarlyExit({description:e,domain:t})}recordSuccessfulReuse(e){this.optimizer&&this.optimizer.recordSuccessfulReuse(e)}recordFailedReuse(e){this.optimizer&&this.optimizer.recordFailedReuse(e)}async storePattern(e){if(!this.patternStore)return null;try{let t=await this.patternStore.store({...e,id:`pattern-${Date.now()}-${q().slice(0,8)}`,createdAt:new Date,lastUsedAt:new Date});return t.success?t.value:null}catch(t){return console.warn("[TokenOptimizerService] Failed to store pattern:",t),null}}getReuseStats(){return this.optimizer?this.optimizer.getReuseStats():null}isEnabled(){return this.initialized&&this.config.enabled}getConfig(){return{...this.config}}getDashboardSummary(){return $()}cacheOperationResult(e,t,i,n,s){try{let o=k(),l=o.computeFingerprint(e,t,i);o.set(l,e,t,n,s)}catch{}}getSessionCacheStats(){try{return k().getStats()}catch{return{size:0,hits:0,misses:0,hitRate:0,estimatedTokensSaved:0}}}reset(){this.optimizer&&this.optimizer.resetStats(),this.optimizer=null,this.patternStore=null,this.initialized=!1,this.config=C}},J=new M;async function ye(c,e){await J.initialize(c,e)}export{$ as a,p as b,te as c,k as d,J as e,ye as f};
6
+ ORDER BY created_at DESC LIMIT ?`).all(t,this.config.maxEntries);for(let i of n)try{let s=JSON.parse(i.value);Date.now()-s.cachedAt<=this.config.ttlMs&&this.cache.set(s.fingerprint,s)}catch{}}catch{}}getStats(){let e=this.hits+this.misses,t=0;for(let n of this.cache.values())t+=n.tokensSaved*n.hitCount;return{size:this.cache.size,hits:this.hits,misses:this.misses,hitRate:e>0?this.hits/e:0,estimatedTokensSaved:t}}clear(){this.cache.clear(),this.hits=0,this.misses=0}evictOldest(){let e=null,t=1/0;for(let[n,i]of this.cache)i.cachedAt<t&&(t=i.cachedAt,e=n);e&&this.cache.delete(e)}persistEntry(e){try{let t=H();if(!t)return;t.prepare(`INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
7
+ VALUES (?, 'session_cache', ?, ?)`).run(`session_cache:${e.fingerprint}`,JSON.stringify(e),Date.now())}catch{}}};function H(){try{let{getUnifiedMemory:c}=(U(),N(Q)),e=c();return e.isInitialized()?e.getDatabase():null}catch{return null}}var f=null;function k(c){return f||(f=new b(c),f.loadFromDb()),f}import{randomUUID as q}from"crypto";R();var x={minConfidenceForExit:.85,minSuccessRate:.9,maxPatternAge:10080*60*1e3,minQualityScore:.7,minSuccessfulUses:2,maxSearchResults:5,similarityThreshold:.8,verbose:!1},ae={minConfidenceForExit:.75,minSuccessRate:.8,maxPatternAge:336*60*60*1e3,minQualityScore:.6,minSuccessfulUses:1,maxSearchResults:10,similarityThreshold:.7,verbose:!1},ce={minConfidenceForExit:.92,minSuccessRate:.95,maxPatternAge:4320*60*1e3,minQualityScore:.85,minSuccessfulUses:3,maxSearchResults:3,similarityThreshold:.9,verbose:!1},T=class{patternStore;config;reuseHistory=[];attemptHistory=[];constructor(e,t){this.patternStore=e,this.config={...x,...t}}async checkEarlyExit(e){let t=performance.now(),n=new Date;try{let i=e.domain??z(e.description)??void 0,s={limit:this.config.maxSearchResults*2,useVectorSearch:!!e.embedding};i&&(s.domain=i),e.context&&(s.context={language:e.context.language,framework:e.context.framework,testType:e.context.testType});let o=e.embedding??e.description,l=await this.patternStore.search(o,s),u=performance.now()-t;if(!l.success){let d="error"in l?l.error.message:"Unknown error",h=this.createResult(!1,"search_error",`Pattern search failed: ${d}`,u);return this.recordAttempt("search_error",i),h}let r=l.value;if(r.length===0){let d=this.createResult(!1,"no_matching_pattern","No matching patterns found in store",u);return this.recordAttempt("no_matching_pattern",i),d}let a=null;for(let{pattern:d,score:h}of r){let y=this.evaluatePatternEligibility(d,h,n);if(y.eligible){let v=this.estimateTokensSaved(d),L={canExit:!0,reusedPattern:d,estimatedTokensSaved:v,confidence:d.confidence,similarityScore:h,reason:"pattern_reused",explanation:`Reusing pattern "${d.name}" with ${(d.confidence*100).toFixed(1)}% confidence`,searchLatencyMs:u};return this.recordReuse(d.id,v,d.confidence,h,u,i),this.config.verbose&&console.log(`[EarlyExitTokenOptimizer] Pattern reuse: ${d.name} (confidence: ${d.confidence.toFixed(2)}, similarity: ${h.toFixed(2)}, tokens saved: ${v})`),L}a===null&&(a={reason:y.reason,explanation:y.explanation})}if(a){let d=this.createResult(!1,a.reason,a.explanation,u);return this.recordAttempt(a.reason,i),d}let m=this.createResult(!1,"no_matching_pattern",`Found ${r.length} patterns but none met eligibility criteria`,u);return this.recordAttempt("no_matching_pattern",i),m}catch(i){let s=performance.now()-t,o=this.createResult(!1,"search_error",`Error during pattern search: ${p(i)}`,s);return this.recordAttempt("search_error"),o}}evaluatePatternEligibility(e,t,n){if(t<this.config.similarityThreshold)return{eligible:!1,reason:"similarity_too_low",explanation:`Similarity ${(t*100).toFixed(1)}% < threshold ${(this.config.similarityThreshold*100).toFixed(1)}%`};if(e.confidence<this.config.minConfidenceForExit)return{eligible:!1,reason:"confidence_too_low",explanation:`Confidence ${(e.confidence*100).toFixed(1)}% < threshold ${(this.config.minConfidenceForExit*100).toFixed(1)}%`};if(e.successRate<this.config.minSuccessRate)return{eligible:!1,reason:"success_rate_too_low",explanation:`Success rate ${(e.successRate*100).toFixed(1)}% < threshold ${(this.config.minSuccessRate*100).toFixed(1)}%`};let i=n.getTime()-e.lastUsedAt.getTime();if(i>this.config.maxPatternAge){let s=Math.floor(i/864e5),o=Math.floor(this.config.maxPatternAge/(1440*60*1e3));return{eligible:!1,reason:"pattern_too_old",explanation:`Pattern age ${s} days > max ${o} days`}}return e.qualityScore<this.config.minQualityScore?{eligible:!1,reason:"quality_score_too_low",explanation:`Quality score ${(e.qualityScore*100).toFixed(1)}% < threshold ${(this.config.minQualityScore*100).toFixed(1)}%`}:e.successfulUses<this.config.minSuccessfulUses?{eligible:!1,reason:"insufficient_uses",explanation:`Successful uses ${e.successfulUses} < minimum ${this.config.minSuccessfulUses}`}:{eligible:!0,reason:"pattern_reused",explanation:"Pattern meets all eligibility criteria"}}estimateTokensSaved(e){let t=100,n=Math.ceil(e.template.content.length/4);t+=n,t+=50;let o={"test-template":1.5,"assertion-pattern":1,"mock-pattern":1.2,"coverage-strategy":1.3,"api-contract":1.4,"visual-baseline":1.1,"perf-benchmark":1.4,"flaky-fix":1.3,"error-handling":1.2}[e.patternType]??1;return Math.ceil(t*o)}createResult(e,t,n,i){return{canExit:e,reason:t,explanation:n,searchLatencyMs:i}}recordReuse(e,t,n,i,s,o){this.reuseHistory.push({patternId:e,tokensSaved:t,confidence:n,similarity:i,latencyMs:s,domain:o,timestamp:new Date}),this.attemptHistory.push({reason:"pattern_reused",domain:o,timestamp:new Date}),this.reuseHistory.length>1e4&&(this.reuseHistory=this.reuseHistory.slice(-1e4))}recordAttempt(e,t){this.attemptHistory.push({reason:e,domain:t,timestamp:new Date}),this.attemptHistory.length>1e4&&(this.attemptHistory=this.attemptHistory.slice(-1e4))}recordSuccessfulReuse(e){this.patternStore.recordUsage(e,!0).catch(t=>{console.warn(`[EarlyExitTokenOptimizer] Failed to record successful reuse for ${e}:`,t)})}recordFailedReuse(e){this.patternStore.recordUsage(e,!1).catch(t=>{console.warn(`[EarlyExitTokenOptimizer] Failed to record failed reuse for ${e}:`,t)})}getReuseStats(){let e=this.reuseHistory.length,t=this.attemptHistory.length,n=0,i=0,s=0,o=0;for(let r of this.reuseHistory)n+=r.tokensSaved,i+=r.confidence,s+=r.similarity,o+=r.latencyMs;let l={pattern_reused:0,no_matching_pattern:0,confidence_too_low:0,success_rate_too_low:0,pattern_too_old:0,quality_score_too_low:0,insufficient_uses:0,similarity_too_low:0,search_error:0};for(let r of this.attemptHistory)l[r.reason]++;let u={};for(let r of this.reuseHistory){let a=r.domain??"unknown";u[a]||(u[a]={reuses:0,tokens:0}),u[a].reuses++,u[a].tokens+=r.tokensSaved}return{totalReuses:e,tokensSaved:n,avgConfidence:e>0?i/e:0,avgSimilarity:e>0?s/e:0,avgSearchLatencyMs:e>0?o/e:0,totalAttempts:t,exitRate:t>0?e/t:0,reasonBreakdown:l,domainBreakdown:u}}resetStats(){this.reuseHistory=[],this.attemptHistory=[]}getConfig(){return{...this.config}}updateConfig(e){Object.assign(this.config,e)}};var C={enabled:!0,earlyExit:x,verbose:!1},M=class{optimizer=null;patternStore=null;config=C;initialized=!1;readyPromise=null;memoryBackend=null;async initialize(e,t){this.initialized||(this.readyPromise=null,this.patternStore=null,this.optimizer=null,this.config={...C,...t},this.memoryBackend=e,this.initialized=!0,this.config.verbose&&console.log("[TokenOptimizerService] Registered (lazy \u2014 pattern store not yet created)"))}async ensurePatternStoreReady(){if(!this.optimizer&&!(!this.initialized||!this.config.enabled||!this.memoryBackend))return this.readyPromise?this.readyPromise:(this.readyPromise=(async()=>{try{this.patternStore=A(this.memoryBackend),await this.patternStore.initialize(),this.optimizer=new T(this.patternStore,this.config.earlyExit),this.config.verbose&&console.log("[TokenOptimizerService] Pattern store ready (lazy init)")}catch(e){console.warn("[TokenOptimizerService] Lazy pattern store init failed:",e)}})(),this.readyPromise)}async checkEarlyExit(e){if(!this.initialized||!this.config.enabled)return{canExit:!1,reason:"no_matching_pattern",explanation:"Token optimizer service not initialized",searchLatencyMs:0};try{let n=k(),i=n.computeFingerprint(e.domain??"unknown",e.description,e.context??{}),s=n.get(i);if(s)return g.recordEarlyExit(s.tokensSaved),this.config.verbose&&console.log(`[TokenOptimizerService] Session cache hit: ${i.slice(0,8)}... (saved ${s.tokensSaved} tokens)`),{canExit:!0,estimatedTokensSaved:s.tokensSaved,confidence:1,similarityScore:1,reason:"pattern_reused",explanation:`Session cache exact match (fingerprint: ${i.slice(0,8)}...)`,searchLatencyMs:0}}catch{}if(await this.ensurePatternStoreReady(),!this.optimizer)return{canExit:!1,reason:"no_matching_pattern",explanation:"Pattern store unavailable (lazy init failed or disabled)",searchLatencyMs:0};let t=await this.optimizer.checkEarlyExit(e);return t.canExit&&t.estimatedTokensSaved&&(g.recordEarlyExit(t.estimatedTokensSaved),this.config.verbose&&console.log(`[TokenOptimizerService] Early exit: ${t.reusedPattern?.name} (saved ${t.estimatedTokensSaved} tokens)`)),t}async checkTaskEarlyExit(e,t){return this.checkEarlyExit({description:e,domain:t})}recordSuccessfulReuse(e){this.optimizer&&this.optimizer.recordSuccessfulReuse(e)}recordFailedReuse(e){this.optimizer&&this.optimizer.recordFailedReuse(e)}async storePattern(e){if(await this.ensurePatternStoreReady(),!this.patternStore)return null;try{let t=await this.patternStore.store({...e,id:`pattern-${Date.now()}-${q().slice(0,8)}`,createdAt:new Date,lastUsedAt:new Date});return t.success?t.value:null}catch(t){return console.warn("[TokenOptimizerService] Failed to store pattern:",t),null}}getReuseStats(){return this.optimizer?this.optimizer.getReuseStats():null}isEnabled(){return this.initialized&&this.config.enabled}getConfig(){return{...this.config}}getDashboardSummary(){return $()}cacheOperationResult(e,t,n,i,s){try{let o=k(),l=o.computeFingerprint(e,t,n);o.set(l,e,t,i,s)}catch{}}getSessionCacheStats(){try{return k().getStats()}catch{return{size:0,hits:0,misses:0,hitRate:0,estimatedTokensSaved:0}}}reset(){this.optimizer&&this.optimizer.resetStats(),this.optimizer=null,this.patternStore=null,this.initialized=!1,this.readyPromise=null,this.memoryBackend=null,this.config=C}},J=new M;async function ye(c,e){await J.initialize(c,e)}export{$ as a,g as b,te as c,k as d,J as e,ye as f};
@@ -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.9.2");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.9.4");process.exit(0)}
2
2
  var p={"||":1,"&&":2,"===":3,"!==":3,"==":3,"!=":3,"<":4,">":4,"<=":4,">=":4,"+":5,"-":5,"*":6,"/":6,"%":6},l=new Set(Object.keys(p)),w=new Set(["!","-","+"]);function h(r){let n=[],e=0;for(;e<r.length;){let t=r[e];if(/\s/.test(t)){e++;continue}if(/\d/.test(t)||t==="."&&/\d/.test(r[e+1])){let s="";for(;e<r.length&&/[\d.]/.test(r[e]);)s+=r[e++];n.push({type:"NUMBER",value:parseFloat(s),raw:s});continue}if(t==='"'||t==="'"){let s=t,u="";for(e++;e<r.length&&r[e]!==s;){if(r[e]==="\\"&&e+1<r.length){e++;let c=r[e];switch(c){case"n":u+=`
3
3
  `;break;case"t":u+=" ";break;case"r":u+="\r";break;default:u+=c}}else u+=r[e];e++}e++,n.push({type:"STRING",value:u,raw:`${s}${u}${s}`});continue}if(/[a-zA-Z_$]/.test(t)){let s="";for(;e<r.length&&/[a-zA-Z0-9_$]/.test(r[e]);)s+=r[e++];s==="true"?n.push({type:"BOOLEAN",value:!0,raw:s}):s==="false"?n.push({type:"BOOLEAN",value:!1,raw:s}):s==="null"?n.push({type:"NULL",value:null,raw:s}):s==="undefined"?n.push({type:"UNDEFINED",value:void 0,raw:s}):n.push({type:"IDENTIFIER",value:s,raw:s});continue}let a=r.slice(e,e+2),o=r.slice(e,e+3);if(o==="==="||o==="!=="){n.push({type:"OPERATOR",value:o,raw:o}),e+=3;continue}if(a==="=="||a==="!="||a==="<="||a===">="||a==="&&"||a==="||"){n.push({type:"OPERATOR",value:a,raw:a}),e+=2;continue}if(t==="("){n.push({type:"LPAREN",value:"(",raw:"("}),e++;continue}if(t===")"){n.push({type:"RPAREN",value:")",raw:")"}),e++;continue}if(t==="."){n.push({type:"DOT",value:".",raw:"."}),e++;continue}if("+-*/%<>!".includes(t)){n.push({type:"OPERATOR",value:t,raw:t}),e++;continue}throw new Error(`Unexpected character at position ${e}: ${t}`)}return n.push({type:"EOF",value:"",raw:""}),n}var i=class{tokens;pos=0;context;constructor(n,e){this.tokens=n,this.context=e}current(){return this.tokens[this.pos]}advance(){return this.tokens[this.pos++]}expect(n){let e=this.current();if(e.type!==n)throw new Error(`Expected ${n}, got ${e.type}`);return this.advance()}parse(){let n=this.parseExpression(0);if(this.current().type!=="EOF")throw new Error(`Unexpected token: ${this.current().raw}`);return n}parseExpression(n){let e=this.parseUnary();for(;;){let t=this.current();if(t.type!=="OPERATOR"||!l.has(t.value))break;let a=p[t.value];if(a<n)break;let o=this.advance().value,s=this.parseExpression(a+1);e=this.applyBinaryOperator(o,e,s)}return e}parseUnary(){let n=this.current();if(n.type==="OPERATOR"&&w.has(n.value)){let e=this.advance().value,t=this.parseUnary();return this.applyUnaryOperator(e,t)}return this.parsePrimary()}parsePrimary(){let n=this.current();switch(n.type){case"NUMBER":case"STRING":case"BOOLEAN":case"NULL":case"UNDEFINED":return this.advance(),n.value;case"IDENTIFIER":return this.parseIdentifier();case"LPAREN":this.advance();let e=this.parseExpression(0);return this.expect("RPAREN"),e;default:throw new Error(`Unexpected token: ${n.raw}`)}}parseIdentifier(){let n=this.context,e=this.advance().value;for(typeof n=="object"&&n!==null&&(e in n)?n=n[e]:n=void 0;this.current().type==="DOT";){this.advance();let t=this.expect("IDENTIFIER").value;n!=null&&typeof n=="object"?n=n[t]:n=void 0}return n}applyBinaryOperator(n,e,t){switch(n){case"===":return e===t;case"!==":return e!==t;case"==":return e==t;case"!=":return e!=t;case"<":return e<t;case">":return e>t;case"<=":return e<=t;case">=":return e>=t;case"&&":return e&&t;case"||":return e||t;case"+":return e+t;case"-":return e-t;case"*":return e*t;case"/":return e/t;case"%":return e%t;default:throw new Error(`Unknown operator: ${n}`)}}applyUnaryOperator(n,e){switch(n){case"!":return!e;case"-":return-e;case"+":return+e;default:throw new Error(`Unknown unary operator: ${n}`)}}};function E(r,n={}){if(!r||typeof r!="string")throw new Error("Expression must be a non-empty string");let e=[/\beval\b/i,/\bFunction\b/,/\bconstructor\b/,/\b__proto__\b/,/\bprototype\b/,/\bimport\b/,/\brequire\b/,/\bprocess\b/,/\bglobal\b/,/\bwindow\b/,/\bdocument\b/,/\[\s*['"`]/,/\[.*\]/];for(let o of e)if(o.test(r))throw new Error(`Expression contains potentially dangerous pattern: ${r}`);let t=h(r.trim());return new i(t,n).parse()}function b(r,n={},e=!1){try{return!!E(r,n)}catch(t){return console.warn(`[SafeEvaluator] Failed to evaluate expression: ${r}`,t),e}}export{b 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.9.2");process.exit(0)}
2
- import{a as l}from"./chunk-7NOIIC7G.js";import{a as m}from"./chunk-BIVIPF4O.js";import{f as a}from"./chunk-E25S5E2D.js";var u=class{constructor(t,e){this.eventBus=t;this.maxHistorySize=e?.maxHistorySize??1e4,this.eventHistory=new l(this.maxHistorySize),this.correlationTimeout=e?.correlationTimeout??6e4,this.maxEventsPerCorrelation=e?.maxEventsPerCorrelation??100}subscriptions=new Map;correlations=new Map;eventHistory;routes=[];domainSubscriptions=new Map;maxHistorySize;correlationTimeout;maxEventsPerCorrelation;initialized=!1;async initialize(){if(!this.initialized){for(let t of m){let e=this.eventBus.subscribeToChannel(t,async i=>{await this.handleIncomingEvent(i)});this.domainSubscriptions.set(t,e)}this.eventBus.subscribe("*",async t=>{m.includes(t.source)||await this.handleIncomingEvent(t)}),this.initialized=!0}}subscribeToDoamin(t,e){let i=`sub_domain_${a()}`;return this.subscriptions.set(i,{id:i,type:"domain",filter:t,handler:e,active:!0}),i}subscribeToEventType(t,e){let i=`sub_type_${a()}`;return this.subscriptions.set(i,{id:i,type:"eventType",filter:t,handler:e,active:!0}),i}unsubscribe(t){let e=this.subscriptions.get(t);return e?(e.active=!1,this.subscriptions.delete(t),!0):!1}async route(t){this.addToHistory(t),t.correlationId&&this.trackCorrelation(t);let i=this.findMatchingSubscriptions(t).map(async o=>{try{await o.handler(t)}catch(n){console.error(`Error in subscription handler ${o.id}:`,n instanceof Error?n.message:n)}}),r=await this.applyRoutes(t);await Promise.allSettled([...i,...r])}getCorrelation(t){let e=this.correlations.get(t);if(e)return{correlationId:e.correlationId,events:[...e.events],domains:new Set(e.domains),startedAt:e.startedAt,lastEventAt:e.lastEventAt,complete:e.complete}}trackCorrelation(t){if(!t.correlationId)return;let e=this.correlations.get(t.correlationId);e||(e={correlationId:t.correlationId,events:[],domains:new Set,startedAt:t.timestamp,lastEventAt:t.timestamp,complete:!1,timeout:null},this.correlations.set(t.correlationId,e)),e.events.length<this.maxEventsPerCorrelation&&(e.events.push(t),e.domains.add(t.source),e.lastEventAt=t.timestamp),e.timeout&&clearTimeout(e.timeout),e.timeout=setTimeout(()=>{e.complete=!0,e.timeout=null},this.correlationTimeout)}aggregate(t,e){let i=this.eventHistory.toArray().filter(s=>s.timestamp>=t&&s.timestamp<=e),r=new Map,o=new Map;for(let s of i)r.set(s.type,(r.get(s.type)??0)+1),o.set(s.source,(o.get(s.source)??0)+1);let n={totalEvents:i.length,uniqueEventTypes:r.size,uniqueDomains:o.size,eventsPerSecond:i.length>0?i.length/((e.getTime()-t.getTime())/1e3):0};return{id:a(),windowStart:t,windowEnd:e,events:i,countByType:r,countByDomain:o,metrics:n}}getHistory(t){let e=this.eventHistory.toArray();return t&&(t.eventTypes?.length&&(e=e.filter(i=>t.eventTypes.includes(i.type))),t.domains?.length&&(e=e.filter(i=>t.domains.includes(i.source))),t.fromTimestamp&&(e=e.filter(i=>i.timestamp>=t.fromTimestamp)),t.toTimestamp&&(e=e.filter(i=>i.timestamp<=t.toTimestamp)),t.limit&&(e=e.slice(-t.limit))),e}addRoute(t){let e=t.priority??0,i=this.routes.findIndex(r=>(r.priority??0)<e);i===-1?this.routes.push(t):this.routes.splice(i,0,t)}removeRoute(t,e){let i=this.routes.findIndex(r=>r.eventPattern===t&&(e===void 0||r.source===e));return i!==-1?(this.routes.splice(i,1),!0):!1}async dispose(){this.subscriptions.clear();for(let t of this.domainSubscriptions.values())t.unsubscribe();this.domainSubscriptions.clear();for(let t of this.correlations.values())t.timeout&&clearTimeout(t.timeout);this.correlations.clear(),this.eventHistory.clear(),this.initialized=!1}async handleIncomingEvent(t){await this.route(t)}findMatchingSubscriptions(t){let e=[];for(let i of this.subscriptions.values())i.active&&(i.type==="domain"&&i.filter===t.source||i.type==="eventType"&&this.matchEventType(t.type,i.filter))&&e.push(i);return e}matchEventType(t,e){if(e==="*")return!0;let i=e.replace(/\\/g,"\\\\").replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${i}$`).test(t)}async applyRoutes(t){let e=[];for(let i of this.routes){if(!(i.source==="*"||i.source===t.source||Array.isArray(i.source)&&i.source.includes(t.source))||!this.matchEventType(t.type,i.eventPattern)||i.filter&&!i.filter(t))continue;let o=i.transform?i.transform(t):t;for(let n of i.targets)n!==t.source&&e.push(this.eventBus.publish({...o,id:a(),correlationId:t.correlationId??t.id}))}return e}addToHistory(t){this.eventHistory.push(t)}};function y(c,t){return new u(c,t)}export{u as a,y as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
2
+ import{a as l}from"./chunk-4TZTGYBQ.js";import{a as m}from"./chunk-VBYREHZI.js";import{f as a}from"./chunk-G72E5DL3.js";var u=class{constructor(t,e){this.eventBus=t;this.maxHistorySize=e?.maxHistorySize??1e4,this.eventHistory=new l(this.maxHistorySize),this.correlationTimeout=e?.correlationTimeout??6e4,this.maxEventsPerCorrelation=e?.maxEventsPerCorrelation??100}subscriptions=new Map;correlations=new Map;eventHistory;routes=[];domainSubscriptions=new Map;maxHistorySize;correlationTimeout;maxEventsPerCorrelation;initialized=!1;async initialize(){if(!this.initialized){for(let t of m){let e=this.eventBus.subscribeToChannel(t,async i=>{await this.handleIncomingEvent(i)});this.domainSubscriptions.set(t,e)}this.eventBus.subscribe("*",async t=>{m.includes(t.source)||await this.handleIncomingEvent(t)}),this.initialized=!0}}subscribeToDoamin(t,e){let i=`sub_domain_${a()}`;return this.subscriptions.set(i,{id:i,type:"domain",filter:t,handler:e,active:!0}),i}subscribeToEventType(t,e){let i=`sub_type_${a()}`;return this.subscriptions.set(i,{id:i,type:"eventType",filter:t,handler:e,active:!0}),i}unsubscribe(t){let e=this.subscriptions.get(t);return e?(e.active=!1,this.subscriptions.delete(t),!0):!1}async route(t){this.addToHistory(t),t.correlationId&&this.trackCorrelation(t);let i=this.findMatchingSubscriptions(t).map(async o=>{try{await o.handler(t)}catch(n){console.error(`Error in subscription handler ${o.id}:`,n instanceof Error?n.message:n)}}),r=await this.applyRoutes(t);await Promise.allSettled([...i,...r])}getCorrelation(t){let e=this.correlations.get(t);if(e)return{correlationId:e.correlationId,events:[...e.events],domains:new Set(e.domains),startedAt:e.startedAt,lastEventAt:e.lastEventAt,complete:e.complete}}trackCorrelation(t){if(!t.correlationId)return;let e=this.correlations.get(t.correlationId);e||(e={correlationId:t.correlationId,events:[],domains:new Set,startedAt:t.timestamp,lastEventAt:t.timestamp,complete:!1,timeout:null},this.correlations.set(t.correlationId,e)),e.events.length<this.maxEventsPerCorrelation&&(e.events.push(t),e.domains.add(t.source),e.lastEventAt=t.timestamp),e.timeout&&clearTimeout(e.timeout),e.timeout=setTimeout(()=>{e.complete=!0,e.timeout=null},this.correlationTimeout)}aggregate(t,e){let i=this.eventHistory.toArray().filter(s=>s.timestamp>=t&&s.timestamp<=e),r=new Map,o=new Map;for(let s of i)r.set(s.type,(r.get(s.type)??0)+1),o.set(s.source,(o.get(s.source)??0)+1);let n={totalEvents:i.length,uniqueEventTypes:r.size,uniqueDomains:o.size,eventsPerSecond:i.length>0?i.length/((e.getTime()-t.getTime())/1e3):0};return{id:a(),windowStart:t,windowEnd:e,events:i,countByType:r,countByDomain:o,metrics:n}}getHistory(t){let e=this.eventHistory.toArray();return t&&(t.eventTypes?.length&&(e=e.filter(i=>t.eventTypes.includes(i.type))),t.domains?.length&&(e=e.filter(i=>t.domains.includes(i.source))),t.fromTimestamp&&(e=e.filter(i=>i.timestamp>=t.fromTimestamp)),t.toTimestamp&&(e=e.filter(i=>i.timestamp<=t.toTimestamp)),t.limit&&(e=e.slice(-t.limit))),e}addRoute(t){let e=t.priority??0,i=this.routes.findIndex(r=>(r.priority??0)<e);i===-1?this.routes.push(t):this.routes.splice(i,0,t)}removeRoute(t,e){let i=this.routes.findIndex(r=>r.eventPattern===t&&(e===void 0||r.source===e));return i!==-1?(this.routes.splice(i,1),!0):!1}async dispose(){this.subscriptions.clear();for(let t of this.domainSubscriptions.values())t.unsubscribe();this.domainSubscriptions.clear();for(let t of this.correlations.values())t.timeout&&clearTimeout(t.timeout);this.correlations.clear(),this.eventHistory.clear(),this.initialized=!1}async handleIncomingEvent(t){await this.route(t)}findMatchingSubscriptions(t){let e=[];for(let i of this.subscriptions.values())i.active&&(i.type==="domain"&&i.filter===t.source||i.type==="eventType"&&this.matchEventType(t.type,i.filter))&&e.push(i);return e}matchEventType(t,e){if(e==="*")return!0;let i=e.replace(/\\/g,"\\\\").replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${i}$`).test(t)}async applyRoutes(t){let e=[];for(let i of this.routes){if(!(i.source==="*"||i.source===t.source||Array.isArray(i.source)&&i.source.includes(t.source))||!this.matchEventType(t.type,i.eventPattern)||i.filter&&!i.filter(t))continue;let o=i.transform?i.transform(t):t;for(let n of i.targets)n!==t.source&&e.push(this.eventBus.publish({...o,id:a(),correlationId:t.correlationId??t.id}))}return e}addToHistory(t){this.eventHistory.push(t)}};function y(c,t){return new u(c,t)}export{u as a,y as b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.2");process.exit(0)}
2
- import{a as f}from"./chunk-XIBVVZGB.js";import{c as p}from"./chunk-JOVINE23.js";import{a as l,d as b}from"./chunk-34U7JDCN.js";import{a as d,c as g}from"./chunk-LCAA6H4J.js";f();g();b();var v={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},S=p.create("coverage-analysis/hnsw-index"),u=class{constructor(e,t={}){this.memory=e;this.config={...v,...t},this.stats={vectorCount:0,searchOperations:0,insertOperations:0}}config;stats;searchLatencies=[];backendType="ruvector-gnn";adapter=null;initialized=!1;metadataStore=new Map;async initialize(){if(this.initialized)return;let e=this.config.metric==="cosine"?"cosine":"euclidean",t=`coverage-${this.config.namespace}`;d.close(t),this.adapter=d.create(t,{dimensions:this.config.dimensions,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:e}),S.info(`HnswAdapter initialized: dimension=${this.config.dimensions}, metric=${this.config.metric}, M=${this.config.M} (unified backend via ADR-071)`),this.initialized=!0}isNativeAvailable(){return this.initialized&&this.adapter!==null}getBackendType(){return this.backendType}isRuvectorAvailable(){return this.initialized&&this.adapter!==null&&this.adapter.isRuvectorAvailable()}async insert(e,t,a){this.initialized||await this.initialize(),t=this.validateVector(t),this.adapter.addByStringId(e,t),a&&this.metadataStore.set(e,a),this.stats.insertOperations++,this.stats.vectorCount=this.adapter.size()}async search(e,t){this.initialized||await this.initialize(),e=this.validateVector(e);let a=performance.now(),n=[];this.adapter.size()>0&&(n=this.adapter.searchByArray(e,t).map(({id:i,score:o})=>({key:i,score:o,distance:1-o,metadata:this.metadataStore.get(i)})));let s=performance.now()-a;return this.recordSearchLatency(s),this.stats.searchOperations++,n}async batchInsert(e){this.initialized||await this.initialize();let t=100;for(let a=0;a<e.length;a+=t){let n=e.slice(a,a+t);await Promise.all(n.map(r=>this.insert(r.key,r.vector,r.metadata)))}}async delete(e){if(!this.adapter)return!1;let t=this.adapter.removeByStringId(e);if(t){this.metadataStore.delete(e);let a=this.buildKey(e);await this.memory.delete(a),this.stats.vectorCount=this.adapter.size()}return t}async getStats(){return{nativeHNSW:this.initialized&&this.adapter!==null,backendType:this.backendType,vectorCount:this.stats.vectorCount,indexSizeBytes:this.stats.vectorCount*this.config.dimensions*4,avgSearchLatencyMs:this.calculateAvgLatency(),p95SearchLatencyMs:this.calculatePercentileLatency(95),p99SearchLatencyMs:this.calculatePercentileLatency(99),searchOperations:this.stats.searchOperations,insertOperations:this.stats.insertOperations}}async clear(){this.metadataStore.clear(),this.adapter&&this.adapter.clear(),this.stats.vectorCount=0,this.searchLatencies=[]}validateVector(e){if(e.length!==this.config.dimensions)return this.resizeVector(e,this.config.dimensions);for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t]))throw new Error(`Invalid vector value at index ${t}: ${e[t]}`);return e}resizeVector(e,t){if(e.length===t)return e;if(e.length>t){let n=new Array(t).fill(0),r=e.length/t;for(let s=0;s<t;s++){let h=Math.floor(s*r),i=Math.floor((s+1)*r),o=0;for(let m=h;m<i;m++)o+=e[m];n[s]=o/(i-h)}return n}let a=new Array(t).fill(0);for(let n=0;n<e.length;n++)a[n]=e[n];return a}buildKey(e){return`${this.config.namespace}:${e}`}recordSearchLatency(e){this.searchLatencies.push(e);let t=1e3;this.searchLatencies.length>t&&(this.searchLatencies=this.searchLatencies.slice(-t))}calculateAvgLatency(){return this.searchLatencies.length===0?0:this.searchLatencies.reduce((t,a)=>t+a,0)/this.searchLatencies.length}calculatePercentileLatency(e){if(this.searchLatencies.length===0)return 0;let t=[...this.searchLatencies].sort((n,r)=>n-r),a=Math.ceil(e/100*t.length)-1;return t[Math.max(0,a)]}setEfSearch(e){this.config.efSearch=e}};function C(c,e){return new u(c,e)}async function H(c,e=1e4,t=1e3){let n=performance.now();for(let i=0;i<e;i++){let o=Array.from({length:384},()=>l());await c.insert(`bench-${i}`,o)}let r=performance.now()-n,s=performance.now();for(let i=0;i<t;i++){let o=Array.from({length:384},()=>l());await c.search(o,10)}let h=performance.now()-s;return{insertTimeMs:r,searchTimeMs:h,avgSearchLatencyMs:h/t,isNative:c.isNativeAvailable(),backendType:c.getBackendType()}}export{v as a,u as b,C as c,H 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.9.4");process.exit(0)}
2
+ import{a as f}from"./chunk-MDFXPCBO.js";import{c as p}from"./chunk-RPYUKEAH.js";import{a as l,d as b}from"./chunk-P3EOWBME.js";import{a as d,c as g}from"./chunk-OZC42UMD.js";f();g();b();var v={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},S=p.create("coverage-analysis/hnsw-index"),u=class{constructor(e,t={}){this.memory=e;this.config={...v,...t},this.stats={vectorCount:0,searchOperations:0,insertOperations:0}}config;stats;searchLatencies=[];backendType="ruvector-gnn";adapter=null;initialized=!1;metadataStore=new Map;async initialize(){if(this.initialized)return;let e=this.config.metric==="cosine"?"cosine":"euclidean",t=`coverage-${this.config.namespace}`;d.close(t),this.adapter=d.create(t,{dimensions:this.config.dimensions,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:e}),S.info(`HnswAdapter initialized: dimension=${this.config.dimensions}, metric=${this.config.metric}, M=${this.config.M} (unified backend via ADR-071)`),this.initialized=!0}isNativeAvailable(){return this.initialized&&this.adapter!==null}getBackendType(){return this.backendType}isRuvectorAvailable(){return this.initialized&&this.adapter!==null&&this.adapter.isRuvectorAvailable()}async insert(e,t,a){this.initialized||await this.initialize(),t=this.validateVector(t),this.adapter.addByStringId(e,t),a&&this.metadataStore.set(e,a),this.stats.insertOperations++,this.stats.vectorCount=this.adapter.size()}async search(e,t){this.initialized||await this.initialize(),e=this.validateVector(e);let a=performance.now(),n=[];this.adapter.size()>0&&(n=this.adapter.searchByArray(e,t).map(({id:i,score:o})=>({key:i,score:o,distance:1-o,metadata:this.metadataStore.get(i)})));let s=performance.now()-a;return this.recordSearchLatency(s),this.stats.searchOperations++,n}async batchInsert(e){this.initialized||await this.initialize();let t=100;for(let a=0;a<e.length;a+=t){let n=e.slice(a,a+t);await Promise.all(n.map(r=>this.insert(r.key,r.vector,r.metadata)))}}async delete(e){if(!this.adapter)return!1;let t=this.adapter.removeByStringId(e);if(t){this.metadataStore.delete(e);let a=this.buildKey(e);await this.memory.delete(a),this.stats.vectorCount=this.adapter.size()}return t}async getStats(){return{nativeHNSW:this.initialized&&this.adapter!==null,backendType:this.backendType,vectorCount:this.stats.vectorCount,indexSizeBytes:this.stats.vectorCount*this.config.dimensions*4,avgSearchLatencyMs:this.calculateAvgLatency(),p95SearchLatencyMs:this.calculatePercentileLatency(95),p99SearchLatencyMs:this.calculatePercentileLatency(99),searchOperations:this.stats.searchOperations,insertOperations:this.stats.insertOperations}}async clear(){this.metadataStore.clear(),this.adapter&&this.adapter.clear(),this.stats.vectorCount=0,this.searchLatencies=[]}validateVector(e){if(e.length!==this.config.dimensions)return this.resizeVector(e,this.config.dimensions);for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t]))throw new Error(`Invalid vector value at index ${t}: ${e[t]}`);return e}resizeVector(e,t){if(e.length===t)return e;if(e.length>t){let n=new Array(t).fill(0),r=e.length/t;for(let s=0;s<t;s++){let h=Math.floor(s*r),i=Math.floor((s+1)*r),o=0;for(let m=h;m<i;m++)o+=e[m];n[s]=o/(i-h)}return n}let a=new Array(t).fill(0);for(let n=0;n<e.length;n++)a[n]=e[n];return a}buildKey(e){return`${this.config.namespace}:${e}`}recordSearchLatency(e){this.searchLatencies.push(e);let t=1e3;this.searchLatencies.length>t&&(this.searchLatencies=this.searchLatencies.slice(-t))}calculateAvgLatency(){return this.searchLatencies.length===0?0:this.searchLatencies.reduce((t,a)=>t+a,0)/this.searchLatencies.length}calculatePercentileLatency(e){if(this.searchLatencies.length===0)return 0;let t=[...this.searchLatencies].sort((n,r)=>n-r),a=Math.ceil(e/100*t.length)-1;return t[Math.max(0,a)]}setEfSearch(e){this.config.efSearch=e}};function C(c,e){return new u(c,e)}async function H(c,e=1e4,t=1e3){let n=performance.now();for(let i=0;i<e;i++){let o=Array.from({length:384},()=>l());await c.insert(`bench-${i}`,o)}let r=performance.now()-n,s=performance.now();for(let i=0;i<t;i++){let o=Array.from({length:384},()=>l());await c.search(o,10)}let h=performance.now()-s;return{insertTimeMs:r,searchTimeMs:h,avgSearchLatencyMs:h/t,isNative:c.isNativeAvailable(),backendType:c.getBackendType()}}export{v as a,u as b,C as c,H as d};
@@ -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.9.2");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.9.4");process.exit(0)}
2
2
  import{readFileSync as R,existsSync as v,readdirSync as y}from"fs";import{join as S}from"path";var M=100*1024,b=/mcp__([a-z][a-z0-9-]*)__([a-z][a-z0-9_]*)/g,x=/^```/;function w(e,r){let n=e.length>M?e.slice(0,M):e,o=[],i=n.split(`
3
3
  `),a=!1;for(let s=0;s<i.length;s++){let p=i[s];if(x.test(p.trim())){a=!a;continue}let l,c=new RegExp(b.source,"g");for(;(l=c.exec(p))!==null;){let t=l[1],g=l[2],f=l[0],d=a?"code-block":"prose",u=d==="prose"?.9:.5;o.push({toolName:f,serverName:t,actionName:g,confidence:u,context:d,lineNumber:s+1})}}return o}function E(e){let r=new Map;for(let n of e)r.has(n.serverName)||r.set(n.serverName,[]),r.get(n.serverName).push(n);return r}function N(e){let r=[],n=[S(e,".claude","mcp.json"),S(e,".mcp.json")],o=process.env.HOME||process.env.USERPROFILE||"";o&&n.push(S(o,".claude","mcp.json"));for(let i of n)if(v(i))try{let a=R(i,"utf-8"),s=JSON.parse(a);s.mcpServers&&typeof s.mcpServers=="object"&&r.push(...Object.keys(s.mcpServers))}catch{}return[...new Set(r)]}function h(e,r,n){if(!v(e))return{agentName:r,references:[],requiredServers:[],availableServers:n,missingServers:[],warnings:[`Agent file not found: ${e}`],allSatisfied:!0};let o;try{o=R(e,"utf-8")}catch{return{agentName:r,references:[],requiredServers:[],availableServers:n,missingServers:[],warnings:[`Failed to read agent file: ${e}`],allSatisfied:!0}}let i=w(o,r),a=E(i),s=[...a.keys()],p=new Set(n),l=s.filter(t=>!p.has(t)),c=[];for(let t of l){let g=a.get(t)||[],f=Math.max(...g.map(m=>m.confidence)),d=g.length,u=[...new Set(g.map(m=>m.context))].join(", ");c.push(`[advisory] Agent "${r}" references MCP server "${t}" (${d} tool ref${d>1?"s":""}, confidence: ${f}, context: ${u}) but server is not configured. Agent may have reduced capabilities.`)}return{agentName:r,references:i,requiredServers:s,availableServers:n,missingServers:l,warnings:c,allSatisfied:l.length===0}}function C(e,r){let n=Date.now(),o=[],i=[],a=N(r);if(!v(e))return{agents:[],totalServersReferenced:0,globalMissingServers:[],agentsWithMissingDeps:[],warnings:[`Agents directory not found: ${e}`],durationMs:Date.now()-n};try{let c=y(e);for(let g of c){if(!g.endsWith(".md"))continue;let f=g.replace(".md",""),d=S(e,g),u=h(d,f,a);o.push(u),i.push(...u.warnings)}let t=S(e,"subagents");if(v(t)){let g=y(t);for(let f of g){if(!f.endsWith(".md"))continue;let d=f.replace(".md",""),u=S(t,f),m=h(u,d,a);o.push(m),i.push(...m.warnings)}}}catch(c){i.push(`Error scanning agents directory: ${c.message}`)}let s=new Set,p=new Set,l=[];for(let c of o){for(let t of c.requiredServers)s.add(t);for(let t of c.missingServers)p.add(t);c.missingServers.length>0&&l.push(c.agentName)}return{agents:o,totalServersReferenced:s.size,globalMissingServers:[...p],agentsWithMissingDeps:l,warnings:i,durationMs:Date.now()-n}}export{N as a,C as b};
@@ -1,6 +1,6 @@
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.9.2");process.exit(0)}
2
- import{a as F}from"./chunk-BOH22AKC.js";import{a as b,b as E,c as z,d as M,e as C,f as P,g as B}from"./chunk-4D2ZG2QO.js";function W(s,e){let n=s.slice(0,e).split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
2
+ import{a as F}from"./chunk-A6ZBQCYB.js";import{a as b,b as E,c as z,d as M,e as C,f as P,g as B}from"./chunk-YS6C2Q4F.js";function W(s,e){let n=s.slice(0,e).split(`
3
3
  `),r=n.length,o=(n[n.length-1]||"").length;return{line:r,column:o,offset:e}}function p(s,e,n,r,o){return{start:W(s,e),end:W(s,n),oldText:s.slice(e,n),newText:r,description:o}}function _(s,e){let n=[...e].sort((o,t)=>t.start.offset-o.start.offset),r=s;for(let o of n)r=r.slice(0,o.start.offset)+o.newText+r.slice(o.end.offset);return r}function U(s,e){if(s.length===0)return 1;let n=s.reduce((t,a)=>t+Math.abs(a.newText.length-a.oldText.length),0)/s.length,r=Math.max(.5,1-n/1e3),o=Math.max(.7,1-s.length/100);return Math.min(1,e*r*o)}function T(s,e,n,r,o=.9){let t=_(s,n),a=Date.now()-r;return{success:!0,transformType:e,originalCode:s,transformedCode:t,edits:n,changeCount:n.length,confidence:U(n,o),durationMs:a,implementationUsed:"typescript",usedFallback:!1,warnings:[]}}function w(s,e,n,r){return{success:!1,transformType:e,originalCode:s,transformedCode:s,edits:[],changeCount:0,confidence:0,durationMs:Date.now()-r,implementationUsed:"typescript",usedFallback:!1,error:n,warnings:[]}}function Z(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/\bvar\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,a=/([a-zA-Z_$][a-zA-Z0-9_$]*)\s*(?:\+\+|--|[+\-*/%&|^]=|\?\?=|&&=|\|\|=|=(?!=))/g,i=[],l;for(;(l=t.exec(s))!==null;)i.push({name:l[1],offset:l.index});let m=new Set;for(;(l=a.exec(s))!==null;)m.add(l[1]);let u=/\bfor\s*\(\s*var\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,c=new Set;for(;(l=u.exec(s))!==null;)c.add(l[1]);for(let g of i){let d=c.has(g.name)||m.has(g.name)?"let":"const";r.push(p(s,g.offset,g.offset+3,d,`Convert var ${g.name} to ${d}`))}e.debug("var-to-const transform completed",{declarations:i.length,reassigned:m.size,loopVars:c.size});let f=T(s,"var-to-const",r,n,.95);return f.warnings=o,f}catch(t){return e.error("var-to-const transform failed",t),w(s,"var-to-const",t instanceof Error?t.message:"Unknown error",n)}}function O(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(([^)]*)\)/g,a=/(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*\(([^)]*)\)\s*=>/g,i=/([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(([^)]*)\)\s*(?::\s*[^{]+)?\s*\{/g,l;for(;(l=t.exec(s))!==null;){let u=l[2].trim();if(u&&!u.includes(":")){let c=u.split(",").map(d=>{let h=d.trim().replace(/\s*=.*$/,"");return h&&!h.includes(":")?`${h}: unknown`:d.trim()}).join(", "),f=l.index+l[0].indexOf("(")+1,g=f+l[2].length;r.push(p(s,f,g,c,`Add types to function ${l[1]} parameters`))}}for(;(l=a.exec(s))!==null;){let u=l[2].trim();if(u&&!u.includes(":")){let c=u.split(",").map(d=>{let h=d.trim().replace(/\s*=.*$/,"");return h&&!h.includes(":")?`${h}: unknown`:d.trim()}).join(", "),f=l.index+l[0].indexOf("(")+1,g=f+l[2].length;r.push(p(s,f,g,c,`Add types to arrow function ${l[1]} parameters`))}}e.debug("add-types transform completed",{edits:r.length});let m=T(s,"add-types",r,n,.7);return m.warnings=o,r.length>0&&m.warnings.push('Type annotations use "unknown" - manual review recommended'),m}catch(t){return e.error("add-types transform failed",t),w(s,"add-types",t instanceof Error?t.message:"Unknown error",n)}}function I(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/^\s*console\.(log|warn|error|info|debug|trace|dir|table|time|timeEnd|group|groupEnd|assert)\s*\([^)]*\);?\s*$/gm,a=/console\.(log|warn|error|info|debug|trace|dir|table|time|timeEnd|group|groupEnd|assert)\s*\([^)]*\)/g,i,l=new Set;for(;(i=t.exec(s))!==null;)l.has(i.index)||(l.add(i.index),r.push(p(s,i.index,i.index+i[0].length,"",`Remove console.${i[1]}() statement`)));for(;(i=a.exec(s))!==null;){if(l.has(i.index))continue;let u=s.lastIndexOf(`
4
4
  `,i.index)+1,c=s.indexOf(`
5
5
  `,i.index),f=s.slice(u,c===-1?void 0:c);/^\s*console\./.test(f)||(l.add(i.index),o.push(`Inline console.${i[1]}() at offset ${i.index} - consider manual review`))}e.debug("remove-console transform completed",{removed:r.length,warnings:o.length});let m=T(s,"remove-console",r,n,.95);return m.warnings=o,m}catch(t){return e.error("remove-console transform failed",t),w(s,"remove-console",t instanceof Error?t.message:"Unknown error",n)}}function j(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/([a-zA-Z_$][a-zA-Z0-9_$]*(?:\([^)]*\))?)\s*\.then\s*\(\s*(?:async\s*)?\(?\s*([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\)?\s*=>\s*([^)]+)\)/g,a;for(;(a=t.exec(s))!==null;){let[l,m,u,c]=a;if(c.includes(".then")||c.includes(".catch")){o.push(`Complex promise chain at offset ${a.index} - manual review recommended`);continue}let f=`const ${u} = await ${m};
6
- ${c.trim()}`;r.push(p(s,a.index,a.index+l.length,f,"Convert .then() to await"))}e.debug("promise-to-async transform completed",{converted:r.length,warnings:o.length});let i=T(s,"promise-to-async",r,n,.65);return i.warnings=o,r.length>0&&i.warnings.push("Promise chains converted to await - ensure containing function is async"),i}catch(t){return e.error("promise-to-async transform failed",t),w(s,"promise-to-async",t instanceof Error?t.message:"Unknown error",n)}}function N(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t,a=/(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*require\s*\(\s*(['"`][^'"`]+['"`])\s*\)\s*;?/g;for(;(t=a.exec(s))!==null;){let[c,f,g]=t,d=`import ${f} from ${g};`;r.push(p(s,t.index,t.index+c.length,d,"Convert require to import"))}let i=/(?:const|let|var)\s+\{\s*([^}]+)\s*\}\s*=\s*require\s*\(\s*(['"`][^'"`]+['"`])\s*\)\s*;?/g;for(;(t=i.exec(s))!==null;){let[c,f,g]=t,d=`import { ${f.trim()} } from ${g};`;r.push(p(s,t.index,t.index+c.length,d,"Convert destructured require to import"))}let l=/module\.exports\s*=\s*([^;]+);?/g;for(;(t=l.exec(s))!==null;){let[c,f]=t,g=`export default ${f.trim()};`;r.push(p(s,t.index,t.index+c.length,g,"Convert module.exports to export default"))}let m=/exports\.([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*([^;]+);?/g;for(;(t=m.exec(s))!==null;){let[c,f,g]=t,d=g.trim(),h;d.startsWith("function")||d.startsWith("class")?h=`export ${d}`:d.startsWith("async function")?h=`export ${d}`:h=`export const ${f} = ${d};`,r.push(p(s,t.index,t.index+c.length,h,`Convert exports.${f} to named export`))}e.debug("cjs-to-esm transform completed",{edits:r.length});let u=T(s,"cjs-to-esm",r,n,.85);return u.warnings=o,u}catch(t){return e.error("cjs-to-esm transform failed",t),w(s,"cjs-to-esm",t instanceof Error?t.message:"Unknown error",n)}}function H(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/(const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*function\s*\(([^)]*)\)\s*\{/g,a;for(;(a=t.exec(s))!==null;){let[m,u,c,f]=a,g=a.index,d=1,h=g+m.length;for(;d>0&&h<s.length;)s[h]==="{"&&d++,s[h]==="}"&&d--,h++;let S=s.slice(g,h);if(/\bthis\b/.test(S)){o.push(`Function ${c} uses 'this' - skipping arrow conversion (would change binding)`);continue}if(/\barguments\b/.test(S)){o.push(`Function ${c} uses 'arguments' - skipping arrow conversion (not available in arrow functions)`);continue}let D=`${u} ${c} = (${f}) => {`;r.push(p(s,a.index,a.index+m.length,D,`Convert function ${c} to arrow function`))}let i=/function\s*\(([^)]*)\)\s*\{\s*return\s+([^;]+);\s*\}/g;for(;(a=i.exec(s))!==null;){let[m,u,c]=a;if(/\b(this|arguments)\b/.test(m))continue;let f=u.includes(",")||u.trim()===""?`(${u}) => ${c}`:`${u.trim()} => ${c}`;r.push(p(s,a.index,a.index+m.length,f,"Convert callback to arrow function"))}e.debug("func-to-arrow transform completed",{converted:r.length,warnings:o.length});let l=T(s,"func-to-arrow",r,n,.85);return l.warnings=o,l}catch(t){return e.error("func-to-arrow transform failed",t),w(s,"func-to-arrow",t instanceof Error?t.message:"Unknown error",n)}}var V={"var-to-const":Z,"add-types":O,"remove-console":I,"promise-to-async":j,"cjs-to-esm":N,"func-to-arrow":H};function $(s,e,n){let r=V[e];return r?r(s,n):{success:!1,transformType:e,originalCode:s,transformedCode:s,edits:[],changeCount:0,confidence:0,durationMs:0,implementationUsed:"typescript",usedFallback:!1,error:`Unknown transform type: ${e}`,warnings:[]}}var q={JavaScript:0,TypeScript:1,Python:2,Rust:3,Go:4,Java:5,C:6,Cpp:7},y=null,A=null,x=null,R=!1,k=null;async function G(){if(R)return k===null;if(k)return!1;try{let s=await import("./agent-booster-wasm-AKAOHSCX.js");return y=s.transform,A=s.warmup,x=s.isWasmAvailable,R=!0,!0}catch(s){return k=s,R=!0,!1}}function K(s){return q.TypeScript}var L=class{cache=new Map;ttlMs;enabled;constructor(e,n){this.enabled=e,this.ttlMs=n}generateKey(e,n){let r=0;for(let o=0;o<e.length;o++){let t=e.charCodeAt(o);r=(r<<5)-r+t,r=r&r}return`${n}:${r}:${e.length}`}get(e,n){if(!this.enabled)return null;let r=this.generateKey(e,n),o=this.cache.get(r);return o?Date.now()>o.expiresAt?(this.cache.delete(r),null):o.result:null}set(e,n,r){if(!this.enabled)return;let o=this.generateKey(e,n);this.cache.set(o,{result:r,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},v=class{config;logger;cache;enabledTransforms;metricsTracker;initialized=!1;wasmAvailable=!1;wasmModule=null;patternsLoaded=!1;totalTransforms=0;successfulTransforms=0;totalDurationMs=0;cacheHits=0;cacheMisses=0;constructor(e={},n,r){this.config={...z,...e},this.logger=n||{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.metricsTracker=r,this.cache=new L(this.config.cacheEnabled,this.config.cacheTtlMs),this.config.transforms.length===0?this.enabledTransforms=new Set(b):this.enabledTransforms=new Set(this.config.transforms)}setMetricsTracker(e){this.metricsTracker=e}async initialize(){this.initialized||(this.logger.info("Initializing Agent Booster adapter",{enabled:this.config.enabled,transforms:Array.from(this.enabledTransforms)}),this.config.transforms.length===0&&await this.loadEligibleTransformsFromPatterns(),this.config.enabled&&await this.tryLoadWasm(),this.initialized=!0,this.logger.info("Agent Booster adapter initialized",{wasmAvailable:this.wasmAvailable,enabledTransforms:Array.from(this.enabledTransforms),patternsLoaded:this.patternsLoaded}))}async loadEligibleTransformsFromPatterns(){try{let n=await F().getEligibleBoosterTransforms();if(n.length>0){let r=n.filter(o=>b.includes(o));if(r.length>0){this.enabledTransforms=new Set(r),this.patternsLoaded=!0,this.logger.info("Loaded eligible transforms from PatternLoader",{fromPatterns:r,invalidIgnored:n.length-r.length});return}}this.logger.debug("PatternLoader returned empty transforms, using defaults")}catch(e){this.logger.warn("Failed to load transforms from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.enabledTransforms=new Set(b),this.patternsLoaded=!1}async tryLoadWasm(){try{if(this.logger.debug("Loading WASM module"),!await G()||!x){this.logger.debug("WASM module could not be loaded, using TypeScript fallback"),this.wasmAvailable=!1;return}this.logger.debug("Checking WASM availability from local module"),await x()&&y&&A?(this.logger.debug("Warming up WASM module"),await A(),this.wasmModule={transform:y,warmup:A,isAvailable:x},this.wasmAvailable=!0,this.logger.info("WASM Agent Booster loaded and warmed up successfully",{source:"local-module"})):(this.logger.debug("WASM not available from local module, using TypeScript fallback"),this.wasmAvailable=!1)}catch(e){this.logger.warn("Failed to load WASM module",{error:e instanceof Error?e.message:"Unknown error"}),this.wasmAvailable=!1}}async dispose(){this.cache.clear(),this.wasmModule=null,this.wasmAvailable=!1,this.initialized=!1,this.logger.info("Agent Booster adapter disposed")}async transform(e,n){this.ensureInitialized(),this.ensureEnabled();let r=Date.now();if(this.totalTransforms++,!this.enabledTransforms.has(n))return this.createErrorResult(e,n,`Transform type '${n}' is not enabled`,r);let o=this.cache.get(e,n);if(o)return this.cacheHits++,this.logger.debug("Cache hit for transform",{type:n}),{...o,durationMs:Date.now()-r};this.cacheMisses++;let t;try{t=await this.executeWithFallback(e,n,r)}catch(a){return this.createErrorResult(e,n,a instanceof Error?a.message:"Unknown error",r)}return t.success&&(this.successfulTransforms++,this.cache.set(e,n,t)),this.totalDurationMs+=t.durationMs,await this.recordMetrics(t,n),t}async recordMetrics(e,n){if(this.metricsTracker)try{let r=`booster-${n}-${Date.now()}`;await this.metricsTracker.recordOutcome("booster",r,e.success,e.durationMs,{subType:n,confidence:e.confidence,usedFallback:e.usedFallback,implementationUsed:e.implementationUsed,itemCount:e.changeCount,errorMessage:e.error})}catch(r){this.logger.warn("Failed to record metrics",{error:r instanceof Error?r.message:"Unknown error"})}}async executeWithFallback(e,n,r){if(this.wasmAvailable)try{let t=await this.executeWasmTransform(e,n,r);if(t.success&&t.confidence>=this.config.confidenceThreshold)return t;this.logger.debug("WASM transform low confidence, trying TypeScript",{confidence:t.confidence,threshold:this.config.confidenceThreshold})}catch(t){this.logger.warn("WASM transform failed, falling back to TypeScript",{error:t instanceof Error?t.message:"Unknown error"})}let o=$(e,n,this.logger);return o.durationMs=Date.now()-r,this.config.fallbackToLLM&&o.confidence<this.config.confidenceThreshold&&(this.logger.debug("TypeScript transform low confidence, LLM fallback available",{confidence:o.confidence,threshold:this.config.confidenceThreshold}),o.warnings.push(`Confidence ${o.confidence.toFixed(2)} is below threshold ${this.config.confidenceThreshold}. LLM fallback recommended for review.`),o.usedFallback=!0),o}async executeWasmTransform(e,n,r){if(!this.wasmAvailable)throw new C;let o=K(n),t=$(e,n,this.logger);if(t.changeCount===0)return{...t,durationMs:Date.now()-r,implementationUsed:"wasm"};if(!y)throw new C("WASM transform function not loaded");let a=await Promise.race([y(e,t.transformedCode,o,{confidenceThreshold:this.config.confidenceThreshold,allowFallback:!0}),new Promise((m,u)=>setTimeout(()=>u(new P("WASM transform timed out",n,this.config.timeoutMs)),this.config.timeoutMs))]),i=Date.now()-r,l=a.success&&a.mergedCode!==e?t.changeCount:0;return{success:a.success,transformType:n,originalCode:e,transformedCode:a.mergedCode,edits:t.edits,changeCount:l,confidence:a.confidence,durationMs:i,implementationUsed:a.source==="wasm"?"wasm":"typescript",usedFallback:a.source!=="wasm",error:a.error,warnings:a.syntaxValid?[]:["WASM reported syntax may be invalid"]}}async batchTransform(e,n){this.ensureInitialized(),this.ensureEnabled();let r=Date.now(),o=[],t=[],a=0,i=0,l=0,m=0;for(let u of e){if(u.content.length>this.config.maxFileSizeBytes){let c=new B(u.path,u.content.length,this.config.maxFileSizeBytes);t.push({path:u.path,error:c.message}),i++;continue}try{let c=await this.transform(u.content,n);o.push({path:u.path,result:c}),c.success?c.changeCount>0?(a++,m+=c.changeCount):l++:(i++,c.error&&t.push({path:u.path,error:c.error}))}catch(c){i++,t.push({path:u.path,error:c instanceof Error?c.message:"Unknown error"})}}return{success:i===0,transformType:n,files:o,totalFiles:e.length,successCount:a,failureCount:i,noChangeCount:l,totalChanges:m,durationMs:Date.now()-r,errors:t}}async detectTransformOpportunities(e){this.ensureInitialized(),this.ensureEnabled();let n=Date.now(),r=[],o={},t=[];for(let a of b)o[a]=0;for(let a of Array.from(this.enabledTransforms))try{let i=await this.transform(e,a);if(i.changeCount>0)for(let l of i.edits){let m={type:a,confidence:i.confidence,location:l.start,codeSnippet:l.oldText.slice(0,100)+(l.oldText.length>100?"...":""),suggestedCode:l.newText.slice(0,100)+(l.newText.length>100?"...":""),reason:l.description,risk:this.confidenceToRisk(i.confidence),estimatedDurationMs:E[a].typicalLatencyMs};r.push(m),o[a]++}}catch(i){t.push(`Failed to analyze for ${a}: ${i instanceof Error?i.message:"Unknown error"}`)}return r.sort((a,i)=>i.confidence-a.confidence),{opportunities:r,totalCount:r.length,byType:o,durationMs:Date.now()-n,complete:t.length===0,warnings:t}}isTransformAvailable(e){return this.enabledTransforms.has(e)}getTransformMetadata(e){return E[e]}getAvailableTransforms(){return Array.from(this.enabledTransforms)}isWasmAvailable(){return this.wasmAvailable}getHealth(){let e=this.totalTransforms>0?this.totalDurationMs/this.totalTransforms:0,n=this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0,r=[];return this.initialized||r.push("Adapter not initialized"),this.config.enabled||r.push("Adapter is disabled"),this.wasmAvailable||r.push("WASM module not loaded (using TypeScript fallback)"),this.patternsLoaded||r.push("Patterns not loaded from PatternLoader (using defaults)"),{ready:this.initialized&&this.config.enabled,wasmAvailable:this.wasmAvailable,patternsLoaded:this.patternsLoaded,availableTransforms:Array.from(this.enabledTransforms),lastChecked:new Date,issues:r,metrics:{totalTransforms:this.totalTransforms,successfulTransforms:this.successfulTransforms,averageDurationMs:e,cacheHitRate:n}}}ensureInitialized(){if(!this.initialized)throw new M("AgentBoosterAdapter not initialized. Call initialize() first.","var-to-const")}ensureEnabled(){if(!this.config.enabled)throw new M("AgentBoosterAdapter is disabled. Set enabled: true in config.","var-to-const")}createErrorResult(e,n,r,o){return{success:!1,transformType:n,originalCode:e,transformedCode:e,edits:[],changeCount:0,confidence:0,durationMs:Date.now()-o,implementationUsed:"typescript",usedFallback:!1,error:r,warnings:[]}}confidenceToRisk(e){return e>=.95?"info":e>=.85?"low":e>=.7?"medium":e>=.5?"high":"critical"}};async function ee(s={},e,n){let r=new v(s,e,n);return await r.initialize(),r}function re(s={},e,n){return new v(s,e,n)}export{v as a,ee as b,re as c};
6
+ ${c.trim()}`;r.push(p(s,a.index,a.index+l.length,f,"Convert .then() to await"))}e.debug("promise-to-async transform completed",{converted:r.length,warnings:o.length});let i=T(s,"promise-to-async",r,n,.65);return i.warnings=o,r.length>0&&i.warnings.push("Promise chains converted to await - ensure containing function is async"),i}catch(t){return e.error("promise-to-async transform failed",t),w(s,"promise-to-async",t instanceof Error?t.message:"Unknown error",n)}}function N(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t,a=/(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*require\s*\(\s*(['"`][^'"`]+['"`])\s*\)\s*;?/g;for(;(t=a.exec(s))!==null;){let[c,f,g]=t,d=`import ${f} from ${g};`;r.push(p(s,t.index,t.index+c.length,d,"Convert require to import"))}let i=/(?:const|let|var)\s+\{\s*([^}]+)\s*\}\s*=\s*require\s*\(\s*(['"`][^'"`]+['"`])\s*\)\s*;?/g;for(;(t=i.exec(s))!==null;){let[c,f,g]=t,d=`import { ${f.trim()} } from ${g};`;r.push(p(s,t.index,t.index+c.length,d,"Convert destructured require to import"))}let l=/module\.exports\s*=\s*([^;]+);?/g;for(;(t=l.exec(s))!==null;){let[c,f]=t,g=`export default ${f.trim()};`;r.push(p(s,t.index,t.index+c.length,g,"Convert module.exports to export default"))}let m=/exports\.([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*([^;]+);?/g;for(;(t=m.exec(s))!==null;){let[c,f,g]=t,d=g.trim(),h;d.startsWith("function")||d.startsWith("class")?h=`export ${d}`:d.startsWith("async function")?h=`export ${d}`:h=`export const ${f} = ${d};`,r.push(p(s,t.index,t.index+c.length,h,`Convert exports.${f} to named export`))}e.debug("cjs-to-esm transform completed",{edits:r.length});let u=T(s,"cjs-to-esm",r,n,.85);return u.warnings=o,u}catch(t){return e.error("cjs-to-esm transform failed",t),w(s,"cjs-to-esm",t instanceof Error?t.message:"Unknown error",n)}}function H(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/(const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*function\s*\(([^)]*)\)\s*\{/g,a;for(;(a=t.exec(s))!==null;){let[m,u,c,f]=a,g=a.index,d=1,h=g+m.length;for(;d>0&&h<s.length;)s[h]==="{"&&d++,s[h]==="}"&&d--,h++;let S=s.slice(g,h);if(/\bthis\b/.test(S)){o.push(`Function ${c} uses 'this' - skipping arrow conversion (would change binding)`);continue}if(/\barguments\b/.test(S)){o.push(`Function ${c} uses 'arguments' - skipping arrow conversion (not available in arrow functions)`);continue}let D=`${u} ${c} = (${f}) => {`;r.push(p(s,a.index,a.index+m.length,D,`Convert function ${c} to arrow function`))}let i=/function\s*\(([^)]*)\)\s*\{\s*return\s+([^;]+);\s*\}/g;for(;(a=i.exec(s))!==null;){let[m,u,c]=a;if(/\b(this|arguments)\b/.test(m))continue;let f=u.includes(",")||u.trim()===""?`(${u}) => ${c}`:`${u.trim()} => ${c}`;r.push(p(s,a.index,a.index+m.length,f,"Convert callback to arrow function"))}e.debug("func-to-arrow transform completed",{converted:r.length,warnings:o.length});let l=T(s,"func-to-arrow",r,n,.85);return l.warnings=o,l}catch(t){return e.error("func-to-arrow transform failed",t),w(s,"func-to-arrow",t instanceof Error?t.message:"Unknown error",n)}}var V={"var-to-const":Z,"add-types":O,"remove-console":I,"promise-to-async":j,"cjs-to-esm":N,"func-to-arrow":H};function $(s,e,n){let r=V[e];return r?r(s,n):{success:!1,transformType:e,originalCode:s,transformedCode:s,edits:[],changeCount:0,confidence:0,durationMs:0,implementationUsed:"typescript",usedFallback:!1,error:`Unknown transform type: ${e}`,warnings:[]}}var q={JavaScript:0,TypeScript:1,Python:2,Rust:3,Go:4,Java:5,C:6,Cpp:7},y=null,A=null,x=null,R=!1,k=null;async function G(){if(R)return k===null;if(k)return!1;try{let s=await import("./agent-booster-wasm-MGGEPROV.js");return y=s.transform,A=s.warmup,x=s.isWasmAvailable,R=!0,!0}catch(s){return k=s,R=!0,!1}}function K(s){return q.TypeScript}var L=class{cache=new Map;ttlMs;enabled;constructor(e,n){this.enabled=e,this.ttlMs=n}generateKey(e,n){let r=0;for(let o=0;o<e.length;o++){let t=e.charCodeAt(o);r=(r<<5)-r+t,r=r&r}return`${n}:${r}:${e.length}`}get(e,n){if(!this.enabled)return null;let r=this.generateKey(e,n),o=this.cache.get(r);return o?Date.now()>o.expiresAt?(this.cache.delete(r),null):o.result:null}set(e,n,r){if(!this.enabled)return;let o=this.generateKey(e,n);this.cache.set(o,{result:r,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},v=class{config;logger;cache;enabledTransforms;metricsTracker;initialized=!1;wasmAvailable=!1;wasmModule=null;patternsLoaded=!1;totalTransforms=0;successfulTransforms=0;totalDurationMs=0;cacheHits=0;cacheMisses=0;constructor(e={},n,r){this.config={...z,...e},this.logger=n||{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.metricsTracker=r,this.cache=new L(this.config.cacheEnabled,this.config.cacheTtlMs),this.config.transforms.length===0?this.enabledTransforms=new Set(b):this.enabledTransforms=new Set(this.config.transforms)}setMetricsTracker(e){this.metricsTracker=e}async initialize(){this.initialized||(this.logger.info("Initializing Agent Booster adapter",{enabled:this.config.enabled,transforms:Array.from(this.enabledTransforms)}),this.config.transforms.length===0&&await this.loadEligibleTransformsFromPatterns(),this.config.enabled&&await this.tryLoadWasm(),this.initialized=!0,this.logger.info("Agent Booster adapter initialized",{wasmAvailable:this.wasmAvailable,enabledTransforms:Array.from(this.enabledTransforms),patternsLoaded:this.patternsLoaded}))}async loadEligibleTransformsFromPatterns(){try{let n=await F().getEligibleBoosterTransforms();if(n.length>0){let r=n.filter(o=>b.includes(o));if(r.length>0){this.enabledTransforms=new Set(r),this.patternsLoaded=!0,this.logger.info("Loaded eligible transforms from PatternLoader",{fromPatterns:r,invalidIgnored:n.length-r.length});return}}this.logger.debug("PatternLoader returned empty transforms, using defaults")}catch(e){this.logger.warn("Failed to load transforms from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.enabledTransforms=new Set(b),this.patternsLoaded=!1}async tryLoadWasm(){try{if(this.logger.debug("Loading WASM module"),!await G()||!x){this.logger.debug("WASM module could not be loaded, using TypeScript fallback"),this.wasmAvailable=!1;return}this.logger.debug("Checking WASM availability from local module"),await x()&&y&&A?(this.logger.debug("Warming up WASM module"),await A(),this.wasmModule={transform:y,warmup:A,isAvailable:x},this.wasmAvailable=!0,this.logger.info("WASM Agent Booster loaded and warmed up successfully",{source:"local-module"})):(this.logger.debug("WASM not available from local module, using TypeScript fallback"),this.wasmAvailable=!1)}catch(e){this.logger.warn("Failed to load WASM module",{error:e instanceof Error?e.message:"Unknown error"}),this.wasmAvailable=!1}}async dispose(){this.cache.clear(),this.wasmModule=null,this.wasmAvailable=!1,this.initialized=!1,this.logger.info("Agent Booster adapter disposed")}async transform(e,n){this.ensureInitialized(),this.ensureEnabled();let r=Date.now();if(this.totalTransforms++,!this.enabledTransforms.has(n))return this.createErrorResult(e,n,`Transform type '${n}' is not enabled`,r);let o=this.cache.get(e,n);if(o)return this.cacheHits++,this.logger.debug("Cache hit for transform",{type:n}),{...o,durationMs:Date.now()-r};this.cacheMisses++;let t;try{t=await this.executeWithFallback(e,n,r)}catch(a){return this.createErrorResult(e,n,a instanceof Error?a.message:"Unknown error",r)}return t.success&&(this.successfulTransforms++,this.cache.set(e,n,t)),this.totalDurationMs+=t.durationMs,await this.recordMetrics(t,n),t}async recordMetrics(e,n){if(this.metricsTracker)try{let r=`booster-${n}-${Date.now()}`;await this.metricsTracker.recordOutcome("booster",r,e.success,e.durationMs,{subType:n,confidence:e.confidence,usedFallback:e.usedFallback,implementationUsed:e.implementationUsed,itemCount:e.changeCount,errorMessage:e.error})}catch(r){this.logger.warn("Failed to record metrics",{error:r instanceof Error?r.message:"Unknown error"})}}async executeWithFallback(e,n,r){if(this.wasmAvailable)try{let t=await this.executeWasmTransform(e,n,r);if(t.success&&t.confidence>=this.config.confidenceThreshold)return t;this.logger.debug("WASM transform low confidence, trying TypeScript",{confidence:t.confidence,threshold:this.config.confidenceThreshold})}catch(t){this.logger.warn("WASM transform failed, falling back to TypeScript",{error:t instanceof Error?t.message:"Unknown error"})}let o=$(e,n,this.logger);return o.durationMs=Date.now()-r,this.config.fallbackToLLM&&o.confidence<this.config.confidenceThreshold&&(this.logger.debug("TypeScript transform low confidence, LLM fallback available",{confidence:o.confidence,threshold:this.config.confidenceThreshold}),o.warnings.push(`Confidence ${o.confidence.toFixed(2)} is below threshold ${this.config.confidenceThreshold}. LLM fallback recommended for review.`),o.usedFallback=!0),o}async executeWasmTransform(e,n,r){if(!this.wasmAvailable)throw new C;let o=K(n),t=$(e,n,this.logger);if(t.changeCount===0)return{...t,durationMs:Date.now()-r,implementationUsed:"wasm"};if(!y)throw new C("WASM transform function not loaded");let a=await Promise.race([y(e,t.transformedCode,o,{confidenceThreshold:this.config.confidenceThreshold,allowFallback:!0}),new Promise((m,u)=>setTimeout(()=>u(new P("WASM transform timed out",n,this.config.timeoutMs)),this.config.timeoutMs))]),i=Date.now()-r,l=a.success&&a.mergedCode!==e?t.changeCount:0;return{success:a.success,transformType:n,originalCode:e,transformedCode:a.mergedCode,edits:t.edits,changeCount:l,confidence:a.confidence,durationMs:i,implementationUsed:a.source==="wasm"?"wasm":"typescript",usedFallback:a.source!=="wasm",error:a.error,warnings:a.syntaxValid?[]:["WASM reported syntax may be invalid"]}}async batchTransform(e,n){this.ensureInitialized(),this.ensureEnabled();let r=Date.now(),o=[],t=[],a=0,i=0,l=0,m=0;for(let u of e){if(u.content.length>this.config.maxFileSizeBytes){let c=new B(u.path,u.content.length,this.config.maxFileSizeBytes);t.push({path:u.path,error:c.message}),i++;continue}try{let c=await this.transform(u.content,n);o.push({path:u.path,result:c}),c.success?c.changeCount>0?(a++,m+=c.changeCount):l++:(i++,c.error&&t.push({path:u.path,error:c.error}))}catch(c){i++,t.push({path:u.path,error:c instanceof Error?c.message:"Unknown error"})}}return{success:i===0,transformType:n,files:o,totalFiles:e.length,successCount:a,failureCount:i,noChangeCount:l,totalChanges:m,durationMs:Date.now()-r,errors:t}}async detectTransformOpportunities(e){this.ensureInitialized(),this.ensureEnabled();let n=Date.now(),r=[],o={},t=[];for(let a of b)o[a]=0;for(let a of Array.from(this.enabledTransforms))try{let i=await this.transform(e,a);if(i.changeCount>0)for(let l of i.edits){let m={type:a,confidence:i.confidence,location:l.start,codeSnippet:l.oldText.slice(0,100)+(l.oldText.length>100?"...":""),suggestedCode:l.newText.slice(0,100)+(l.newText.length>100?"...":""),reason:l.description,risk:this.confidenceToRisk(i.confidence),estimatedDurationMs:E[a].typicalLatencyMs};r.push(m),o[a]++}}catch(i){t.push(`Failed to analyze for ${a}: ${i instanceof Error?i.message:"Unknown error"}`)}return r.sort((a,i)=>i.confidence-a.confidence),{opportunities:r,totalCount:r.length,byType:o,durationMs:Date.now()-n,complete:t.length===0,warnings:t}}isTransformAvailable(e){return this.enabledTransforms.has(e)}getTransformMetadata(e){return E[e]}getAvailableTransforms(){return Array.from(this.enabledTransforms)}isWasmAvailable(){return this.wasmAvailable}getHealth(){let e=this.totalTransforms>0?this.totalDurationMs/this.totalTransforms:0,n=this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0,r=[];return this.initialized||r.push("Adapter not initialized"),this.config.enabled||r.push("Adapter is disabled"),this.wasmAvailable||r.push("WASM module not loaded (using TypeScript fallback)"),this.patternsLoaded||r.push("Patterns not loaded from PatternLoader (using defaults)"),{ready:this.initialized&&this.config.enabled,wasmAvailable:this.wasmAvailable,patternsLoaded:this.patternsLoaded,availableTransforms:Array.from(this.enabledTransforms),lastChecked:new Date,issues:r,metrics:{totalTransforms:this.totalTransforms,successfulTransforms:this.successfulTransforms,averageDurationMs:e,cacheHitRate:n}}}ensureInitialized(){if(!this.initialized)throw new M("AgentBoosterAdapter not initialized. Call initialize() first.","var-to-const")}ensureEnabled(){if(!this.config.enabled)throw new M("AgentBoosterAdapter is disabled. Set enabled: true in config.","var-to-const")}createErrorResult(e,n,r,o){return{success:!1,transformType:n,originalCode:e,transformedCode:e,edits:[],changeCount:0,confidence:0,durationMs:Date.now()-o,implementationUsed:"typescript",usedFallback:!1,error:r,warnings:[]}}confidenceToRisk(e){return e>=.95?"info":e>=.85?"low":e>=.7?"medium":e>=.5?"high":"critical"}};async function ee(s={},e,n){let r=new v(s,e,n);return await r.initialize(),r}function re(s={},e,n){return new v(s,e,n)}export{v as a,ee as b,re as c};
@@ -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.9.2");process.exit(0)}
2
- import{e as a}from"./chunk-KZTO5EVM.js";import{b as w,d as y}from"./chunk-N3F3CX4V.js";import{a as f,c as P}from"./chunk-SDTVHR63.js";import{randomUUID as v}from"crypto";import*as i from"fs";import*as n from"path";import*as c from"os";y();P();var k=".aqe",b="schedules.json",F="1.0.0",g=5e3,x=50,p=10*1024*1024,d=class{schedulesPath;debug;lockFile;initialized=!1;constructor(e={}){e.schedulesPath&&this.validateSchedulesPath(e.schedulesPath),this.schedulesPath=e.schedulesPath??this.getDefaultSchedulesPath(),this.lockFile=`${this.schedulesPath}.lock`,this.debug=e.debug??!1}validateSchedulesPath(e){let s=c.homedir(),t=n.resolve(e),r=n.resolve(s);if(t.startsWith(r+n.sep)||t===r)return;let l=process.cwd(),h=n.resolve(l);if(t.startsWith(h+n.sep)||t===h)return;let u=c.tmpdir(),S=n.resolve(u);if(!(t.startsWith(S+n.sep)||t===S))throw new Error(`Security: Custom schedulesPath must be within home directory (${s}), current working directory (${l}), or temp directory (${u}). Provided path: ${e}`)}getDefaultSchedulesPath(){let e=c.homedir();return n.join(e,k,b)}async initialize(){if(this.initialized)return;let e=n.dirname(this.schedulesPath);i.existsSync(e)||(i.mkdirSync(e,{recursive:!0}),this.log(`Created directory: ${e}`)),this.initialized=!0}async loadSchedules(){if(await this.initialize(),!i.existsSync(this.schedulesPath))return this.log("Schedules file does not exist, returning empty array"),[];try{let e=i.readFileSync(this.schedulesPath,"utf-8"),s=this.parseSchedulesFile(e);return this.log(`Loaded ${s.schedules.length} schedules`),s.schedules}catch(e){return await this.handleCorruptFile(e),[]}}async saveSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.findIndex(r=>r.id===e.id);t>=0?(s[t]=e,this.log(`Updated schedule: ${e.id}`)):(s.push(e),this.log(`Added schedule: ${e.id}`)),await this.writeSchedules(s)})}async removeSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.filter(r=>r.id!==e);if(t.length===s.length){this.log(`Schedule not found: ${e}`);return}await this.writeSchedules(t),this.log(`Removed schedule: ${e}`)})}async getSchedules(){return this.loadSchedules()}async getSchedule(e){return(await this.loadSchedules()).find(t=>t.id===e)}async getDueSchedules(){let e=await this.loadSchedules(),s=new Date;return e.filter(t=>t.enabled?new Date(t.nextRun)<=s:!1)}async markExecuted(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.find(l=>l.id===e);if(!t)throw new Error(`Schedule not found: ${e}`);let r=new Date;t.lastRun=r.toISOString(),t.nextRun=a(t.schedule,r).toISOString(),await this.writeSchedules(s),this.log(`Marked executed: ${e}, next run: ${t.nextRun}`)})}async setEnabled(e,s){await this.initialize(),await this.withFileLock(async()=>{let t=await this.loadSchedulesUnsafe(),r=t.find(l=>l.id===e);if(!r)throw new Error(`Schedule not found: ${e}`);r.enabled=s,s&&(r.nextRun=a(r.schedule,new Date).toISOString()),await this.writeSchedules(t),this.log(`Set enabled=${s}: ${e}`)})}async getEnabledSchedules(){return(await this.loadSchedules()).filter(s=>s.enabled)}async getSchedulesByWorkflow(e){return(await this.loadSchedules()).filter(t=>t.workflowId===e)}async clearAll(){await this.initialize(),await this.withFileLock(async()=>{await this.writeSchedules([]),this.log("Cleared all schedules")})}async getStats(){let e=await this.loadSchedules(),s=new Date;return{total:e.length,enabled:e.filter(t=>t.enabled).length,disabled:e.filter(t=>!t.enabled).length,due:e.filter(t=>t.enabled&&new Date(t.nextRun)<=s).length}}async loadSchedulesUnsafe(){if(!i.existsSync(this.schedulesPath))return[];try{let e=i.readFileSync(this.schedulesPath,"utf-8");return this.parseSchedulesFile(e).schedules}catch{return[]}}parseSchedulesFile(e){let s=Buffer.byteLength(e,"utf-8");if(s>p)throw new Error(`Schedules file exceeds maximum allowed size (${p/(1024*1024)}MB). File is ${(s/(1024*1024)).toFixed(2)}MB.`);let t=w(e);if(!t.schedules||!Array.isArray(t.schedules))throw new Error("Invalid schedules file: missing schedules array");for(let r of t.schedules)if(!r.id||!r.workflowId||!r.schedule)throw new Error("Invalid schedule entry: missing required fields");return t}async writeSchedules(e){let s={version:F,updatedAt:new Date().toISOString(),schedules:e},t=JSON.stringify(s,null,2);i.writeFileSync(this.schedulesPath,t,"utf-8"),this.log(`Wrote ${e.length} schedules to disk`)}async handleCorruptFile(e){let s=f(e);this.log(`Corrupt schedules file detected: ${s}`);let t=`${this.schedulesPath}.corrupt.${Date.now()}`;try{i.existsSync(this.schedulesPath)&&(i.copyFileSync(this.schedulesPath,t),this.log(`Backed up corrupt file to: ${t}`))}catch(r){this.log(`Failed to backup corrupt file: ${r}`)}try{i.existsSync(this.schedulesPath)&&(i.unlinkSync(this.schedulesPath),this.log("Removed corrupt schedules file"))}catch(r){this.log(`Failed to remove corrupt file: ${r}`)}}async withFileLock(e){await this.acquireLock();try{return await e()}finally{this.releaseLock()}}async acquireLock(){let e=Date.now();for(;i.existsSync(this.lockFile);){try{let s=i.statSync(this.lockFile);if(Date.now()-s.mtimeMs>g){i.unlinkSync(this.lockFile),this.log("Removed stale lock file");break}}catch{break}if(Date.now()-e>g)throw new Error("Timeout waiting for scheduler lock");await this.sleep(x)}try{i.writeFileSync(this.lockFile,`${process.pid}:${Date.now()}`,{flag:"wx"})}catch(s){if(s.code==="EEXIST")return this.acquireLock();throw s}}releaseLock(){try{i.existsSync(this.lockFile)&&i.unlinkSync(this.lockFile)}catch(e){console.debug("[PersistentScheduler] Lock release error:",e instanceof Error?e.message:e)}}sleep(e){return new Promise(s=>setTimeout(s,e))}log(e){this.debug&&console.log(`[PersistentScheduler] ${e}`)}};function E(o={}){return new d(o)}function m(){let o=Date.now().toString(36),e=v().slice(0,8);return`sched-${o}-${e}`}function $(o){let e=new Date;return{id:m(),workflowId:o.workflowId,pipelinePath:o.pipelinePath,schedule:o.schedule,scheduleDescription:o.scheduleDescription,nextRun:a(o.schedule,e).toISOString(),enabled:o.enabled??!0,createdAt:e.toISOString()}}export{d as a,E as b,m as c,$ 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.9.4");process.exit(0)}
2
+ import{e as a}from"./chunk-QPC4STR6.js";import{b as w,d as y}from"./chunk-4GJAYXB7.js";import{a as f,c as P}from"./chunk-F6AU2MAZ.js";import{randomUUID as v}from"crypto";import*as i from"fs";import*as n from"path";import*as c from"os";y();P();var k=".aqe",b="schedules.json",F="1.0.0",g=5e3,x=50,p=10*1024*1024,d=class{schedulesPath;debug;lockFile;initialized=!1;constructor(e={}){e.schedulesPath&&this.validateSchedulesPath(e.schedulesPath),this.schedulesPath=e.schedulesPath??this.getDefaultSchedulesPath(),this.lockFile=`${this.schedulesPath}.lock`,this.debug=e.debug??!1}validateSchedulesPath(e){let s=c.homedir(),t=n.resolve(e),r=n.resolve(s);if(t.startsWith(r+n.sep)||t===r)return;let l=process.cwd(),h=n.resolve(l);if(t.startsWith(h+n.sep)||t===h)return;let u=c.tmpdir(),S=n.resolve(u);if(!(t.startsWith(S+n.sep)||t===S))throw new Error(`Security: Custom schedulesPath must be within home directory (${s}), current working directory (${l}), or temp directory (${u}). Provided path: ${e}`)}getDefaultSchedulesPath(){let e=c.homedir();return n.join(e,k,b)}async initialize(){if(this.initialized)return;let e=n.dirname(this.schedulesPath);i.existsSync(e)||(i.mkdirSync(e,{recursive:!0}),this.log(`Created directory: ${e}`)),this.initialized=!0}async loadSchedules(){if(await this.initialize(),!i.existsSync(this.schedulesPath))return this.log("Schedules file does not exist, returning empty array"),[];try{let e=i.readFileSync(this.schedulesPath,"utf-8"),s=this.parseSchedulesFile(e);return this.log(`Loaded ${s.schedules.length} schedules`),s.schedules}catch(e){return await this.handleCorruptFile(e),[]}}async saveSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.findIndex(r=>r.id===e.id);t>=0?(s[t]=e,this.log(`Updated schedule: ${e.id}`)):(s.push(e),this.log(`Added schedule: ${e.id}`)),await this.writeSchedules(s)})}async removeSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.filter(r=>r.id!==e);if(t.length===s.length){this.log(`Schedule not found: ${e}`);return}await this.writeSchedules(t),this.log(`Removed schedule: ${e}`)})}async getSchedules(){return this.loadSchedules()}async getSchedule(e){return(await this.loadSchedules()).find(t=>t.id===e)}async getDueSchedules(){let e=await this.loadSchedules(),s=new Date;return e.filter(t=>t.enabled?new Date(t.nextRun)<=s:!1)}async markExecuted(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.find(l=>l.id===e);if(!t)throw new Error(`Schedule not found: ${e}`);let r=new Date;t.lastRun=r.toISOString(),t.nextRun=a(t.schedule,r).toISOString(),await this.writeSchedules(s),this.log(`Marked executed: ${e}, next run: ${t.nextRun}`)})}async setEnabled(e,s){await this.initialize(),await this.withFileLock(async()=>{let t=await this.loadSchedulesUnsafe(),r=t.find(l=>l.id===e);if(!r)throw new Error(`Schedule not found: ${e}`);r.enabled=s,s&&(r.nextRun=a(r.schedule,new Date).toISOString()),await this.writeSchedules(t),this.log(`Set enabled=${s}: ${e}`)})}async getEnabledSchedules(){return(await this.loadSchedules()).filter(s=>s.enabled)}async getSchedulesByWorkflow(e){return(await this.loadSchedules()).filter(t=>t.workflowId===e)}async clearAll(){await this.initialize(),await this.withFileLock(async()=>{await this.writeSchedules([]),this.log("Cleared all schedules")})}async getStats(){let e=await this.loadSchedules(),s=new Date;return{total:e.length,enabled:e.filter(t=>t.enabled).length,disabled:e.filter(t=>!t.enabled).length,due:e.filter(t=>t.enabled&&new Date(t.nextRun)<=s).length}}async loadSchedulesUnsafe(){if(!i.existsSync(this.schedulesPath))return[];try{let e=i.readFileSync(this.schedulesPath,"utf-8");return this.parseSchedulesFile(e).schedules}catch{return[]}}parseSchedulesFile(e){let s=Buffer.byteLength(e,"utf-8");if(s>p)throw new Error(`Schedules file exceeds maximum allowed size (${p/(1024*1024)}MB). File is ${(s/(1024*1024)).toFixed(2)}MB.`);let t=w(e);if(!t.schedules||!Array.isArray(t.schedules))throw new Error("Invalid schedules file: missing schedules array");for(let r of t.schedules)if(!r.id||!r.workflowId||!r.schedule)throw new Error("Invalid schedule entry: missing required fields");return t}async writeSchedules(e){let s={version:F,updatedAt:new Date().toISOString(),schedules:e},t=JSON.stringify(s,null,2);i.writeFileSync(this.schedulesPath,t,"utf-8"),this.log(`Wrote ${e.length} schedules to disk`)}async handleCorruptFile(e){let s=f(e);this.log(`Corrupt schedules file detected: ${s}`);let t=`${this.schedulesPath}.corrupt.${Date.now()}`;try{i.existsSync(this.schedulesPath)&&(i.copyFileSync(this.schedulesPath,t),this.log(`Backed up corrupt file to: ${t}`))}catch(r){this.log(`Failed to backup corrupt file: ${r}`)}try{i.existsSync(this.schedulesPath)&&(i.unlinkSync(this.schedulesPath),this.log("Removed corrupt schedules file"))}catch(r){this.log(`Failed to remove corrupt file: ${r}`)}}async withFileLock(e){await this.acquireLock();try{return await e()}finally{this.releaseLock()}}async acquireLock(){let e=Date.now();for(;i.existsSync(this.lockFile);){try{let s=i.statSync(this.lockFile);if(Date.now()-s.mtimeMs>g){i.unlinkSync(this.lockFile),this.log("Removed stale lock file");break}}catch{break}if(Date.now()-e>g)throw new Error("Timeout waiting for scheduler lock");await this.sleep(x)}try{i.writeFileSync(this.lockFile,`${process.pid}:${Date.now()}`,{flag:"wx"})}catch(s){if(s.code==="EEXIST")return this.acquireLock();throw s}}releaseLock(){try{i.existsSync(this.lockFile)&&i.unlinkSync(this.lockFile)}catch(e){console.debug("[PersistentScheduler] Lock release error:",e instanceof Error?e.message:e)}}sleep(e){return new Promise(s=>setTimeout(s,e))}log(e){this.debug&&console.log(`[PersistentScheduler] ${e}`)}};function E(o={}){return new d(o)}function m(){let o=Date.now().toString(36),e=v().slice(0,8);return`sched-${o}-${e}`}function $(o){let e=new Date;return{id:m(),workflowId:o.workflowId,pipelinePath:o.pipelinePath,schedule:o.schedule,scheduleDescription:o.scheduleDescription,nextRun:a(o.schedule,e).toISOString(),enabled:o.enabled??!0,createdAt:e.toISOString()}}export{d as a,E as b,m as c,$ 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.9.2");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.9.4");process.exit(0)}
2
2
  var s={"test-generation":/test|spec|describe|it\(|expect|assert|mock|stub|fixture|tdd|bdd/i,"test-execution":/run|execute|parallel|retry|flaky|timeout|worker|orchestrat/i,"coverage-analysis":/coverage|branch|line|uncovered|gap|untested|percentage|sublinear/i,"quality-assessment":/quality|gate|deploy|readiness|metric|threshold|sla|score/i,"defect-intelligence":/defect|bug|predict|root.?cause|regression|failure|incident/i,"requirements-validation":/requirement|bdd|gherkin|testabil|accept|criteri|scenario/i,"code-intelligence":/semantic|knowledge|graph|ast|symbol|reference|impact|depend/i,"security-compliance":/vuln|cve|owasp|xss|sqli|injection|csrf|auth|secret|compliance|sast|dast/i,"contract-testing":/contract|pact|openapi|swagger|graphql|schema|endpoint|api/i,"visual-accessibility":/screenshot|visual|snapshot|pixel|percy|a11y|aria|wcag|screen.?reader|accessible|contrast/i,"chaos-resilience":/chaos|resilience|fault|inject|blast|recover|latency|failure|stress|load/i,"learning-optimization":/learn|pattern|optim|neural|embedding|vector|memory|adapt|train/i};function l(e){for(let[t,a]of Object.entries(s))if(a.test(e))return t;return null}function m(e){let t=[];for(let[a,n]of Object.entries(s))n.test(e)&&t.push(a);return t}function u(e){return e}function d(e){let t=Math.min(e.usageCount/100,1);return e.confidence*.3+t*.2+e.successRate*.5}var c=3;function p(e,t,a=.4){let n=e.tier==="short-term"&&e.successfulUses>=c,r=e.successRate>=.7&&e.confidence>=.6,i=t===void 0||t<a,o;return n?r?i||(o="coherence_violation"):o="low_quality":o="insufficient_usage",{meetsUsageCriteria:n,meetsQualityCriteria:r,meetsCoherenceCriteria:i,blockReason:o}}function y(e){let t=[];if(e.id||t.push("Pattern ID is required"),e.patternType||t.push("Pattern type is required"),e.qeDomain||t.push("QE domain is required"),e.name||t.push("Pattern name is required"),e.template?.content||t.push("Template content is required"),e.confidence!==void 0&&(e.confidence<0||e.confidence>1)&&t.push("Confidence must be between 0 and 1"),e.successRate!==void 0&&(e.successRate<0||e.successRate>1)&&t.push("Success rate must be between 0 and 1"),e.template?.variables){let a=new Set;for(let n of e.template.variables)a.has(n.name)&&t.push(`Duplicate variable name: ${n.name}`),a.add(n.name),e.template.content.includes(`{{${n.name}}}`)||t.push(`Variable ${n.name} not referenced in template`)}return{valid:t.length===0,errors:t}}function f(e,t){let a=e.content;for(let n of e.variables){let r=t[n.name]??n.defaultValue;if(n.required&&r===void 0)throw new Error(`Required variable ${n.name} not provided`);if(r!==void 0){let i=`{{${n.name}}}`,o=typeof r=="object"?JSON.stringify(r):String(r);a=a.split(i).join(o)}}return a}var g=Object.keys(s);export{l as a,m as b,u as c,d,c as e,p as f,y as g,f as h,g as i};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.2");process.exit(0)}
2
- import{a as te,b as ne}from"./chunk-PFNFC43Q.js";import{a as b}from"./chunk-CCYMJKWX.js";import{b as ee}from"./chunk-NRCKGXJJ.js";import{b as E,d as fe}from"./chunk-N3F3CX4V.js";import{a as k,c as T}from"./chunk-SDTVHR63.js";var he={M:16,efConstruction:200,efSearch:100},P={enabled:!0,pretrainedPatterns:!0,hnswConfig:he,promotionThreshold:3,qualityThreshold:.7,embeddingModel:"auto"},_={mode:"hybrid",confidenceThreshold:.7,feedbackEnabled:!0,cacheEnabled:!0,cacheTTLMs:300*1e3},F={enabled:["pattern-consolidator","coverage-gap-scanner","flaky-test-detector","routing-accuracy-monitor"],intervals:{"pattern-consolidator":1800*1e3,"coverage-gap-scanner":3600*1e3,"flaky-test-detector":7200*1e3,"routing-accuracy-monitor":900*1e3},maxConcurrent:4,daemonAutoStart:!0},N={claudeCode:!0,preCommit:!1,ciIntegration:!1},$={install:!0,installV2:!0,installV3:!0,overwrite:!1},O={enabled:!0,parameters:["hnsw.efSearch","routing.confidenceThreshold","pattern.promotionThreshold","testGen.complexityLimit"],tuningIntervalMs:10080*60*1e3,evaluationPeriodMs:5e3};var L=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization","enterprise-integration"];function M(){return"3.9.2"}function Fe(i,e){return{version:M(),project:{name:i,root:e,type:"single"},learning:P,routing:_,workers:F,hooks:N,skills:$,autoTuning:O,domains:{enabled:L,disabled:[]},agents:{maxConcurrent:15,defaultTimeout:6e4}}}fe();import{readFileSync as w,existsSync as p,statSync as ye,readdirSync as ve}from"fs";import{join as u,basename as ie,extname as re,relative as V}from"path";var ke=[{name:"jest",detect:i=>{let e=["jest.config.js","jest.config.ts","jest.config.mjs","jest.config.cjs"];for(let n of e)if(p(u(i,n)))return{name:"jest",version:A(i,"jest"),configFile:n,confidence:1};let t=S(i);return t?.jest?{name:"jest",version:A(i,"jest"),configFile:"package.json",confidence:.9}:t?.devDependencies?.jest||t?.dependencies?.jest?{name:"jest",version:t.devDependencies?.jest||t.dependencies?.jest,confidence:.7}:null}},{name:"vitest",detect:i=>{let e=["vitest.config.ts","vitest.config.js","vitest.config.mts","vite.config.ts"];for(let n of e)if(p(u(i,n)))return{name:"vitest",version:A(i,"vitest"),configFile:n,confidence:1};let t=S(i);return t?.devDependencies?.vitest||t?.dependencies?.vitest?{name:"vitest",version:t.devDependencies?.vitest,confidence:.8}:null}},{name:"mocha",detect:i=>{let e=[".mocharc.js",".mocharc.json",".mocharc.yaml",".mocharc.yml"];for(let n of e)if(p(u(i,n)))return{name:"mocha",version:A(i,"mocha"),configFile:n,confidence:1};let t=S(i);return t?.devDependencies?.mocha?{name:"mocha",version:t.devDependencies?.mocha,confidence:.8}:null}},{name:"pytest",detect:i=>{let e=["pytest.ini","pyproject.toml","setup.cfg"];for(let n of e){let r=u(i,n);if(p(r))try{let s=w(r,"utf-8");if(s.includes("[pytest]")||s.includes("[tool.pytest]"))return{name:"pytest",configFile:n,confidence:1}}catch(s){console.debug("[ProjectAnalyzer] Config read failed:",s instanceof Error?s.message:s)}}let t=u(i,"requirements.txt");if(p(t))try{if(w(t,"utf-8").includes("pytest"))return{name:"pytest",configFile:"requirements.txt",confidence:.8}}catch(n){console.debug("[ProjectAnalyzer] requirements.txt read failed:",n instanceof Error?n.message:n)}return null}},{name:"playwright",detect:i=>{let e=["playwright.config.ts","playwright.config.js"];for(let n of e)if(p(u(i,n)))return{name:"playwright",version:A(i,"@playwright/test"),configFile:n,confidence:1};let t=S(i);return t?.devDependencies?.["@playwright/test"]?{name:"playwright",version:t.devDependencies["@playwright/test"],confidence:.8}:null}},{name:"cypress",detect:i=>{let e=["cypress.config.ts","cypress.config.js","cypress.json"];for(let t of e)if(p(u(i,t)))return{name:"cypress",version:A(i,"cypress"),configFile:t,confidence:1};return p(u(i,"cypress"))?{name:"cypress",configFile:"cypress/",confidence:.9}:null}}],be=[{name:"typescript",extensions:[".ts",".tsx",".mts",".cts"]},{name:"javascript",extensions:[".js",".jsx",".mjs",".cjs"]},{name:"python",extensions:[".py",".pyw"]},{name:"java",extensions:[".java"]},{name:"go",extensions:[".go"]},{name:"rust",extensions:[".rs"]},{name:"csharp",extensions:[".cs"]},{name:"ruby",extensions:[".rb"]},{name:"php",extensions:[".php"]},{name:"kotlin",extensions:[".kt",".kts"]},{name:"swift",extensions:[".swift"]}];function S(i){let e=u(i,"package.json");if(!p(e))return null;try{return E(w(e,"utf-8"))}catch{return null}}function A(i,e){let t=S(i);if(t)return t.devDependencies?.[e]||t.dependencies?.[e]}function Q(i,e,t={}){let{maxDepth:n=10,exclude:r=["node_modules",".git","dist","build","coverage",".next","__pycache__"]}=t;function s(o,a){if(a>n)return;let l;try{l=ve(o)}catch{return}for(let g of l){if(r.includes(g))continue;let c=u(o,g),x;try{x=ye(c)}catch{continue}x.isDirectory()?s(c,a+1):x.isFile()&&e(c)}}s(i,0)}var W=class{projectRoot;constructor(e){this.projectRoot=e}async analyze(){let e=Date.now(),[t,n,r,s,o]=await Promise.all([this.detectFrameworks(),this.detectLanguages(),this.detectExistingTests(),this.analyzeComplexity(),this.measureCoverage()]);return{projectName:S(this.projectRoot)?.name||ie(this.projectRoot),projectRoot:this.projectRoot,projectType:this.detectProjectType(),frameworks:t,languages:n,existingTests:r,codeComplexity:s,coverage:o,packageManager:this.detectPackageManager(),hasTypeScript:p(u(this.projectRoot,"tsconfig.json")),hasCIConfig:this.detectCIConfig(),ciProvider:this.detectCIProvider(),analysisTimestamp:new Date,analysisDurationMs:Date.now()-e}}async detectFrameworks(){let e=[];for(let t of ke){let n=t.detect(this.projectRoot);n&&e.push(n)}return e.sort((t,n)=>n.confidence-t.confidence)}async detectLanguages(){let e=new Map,t=0;Q(this.projectRoot,r=>{let s=re(r).toLowerCase();if(s){for(let o of be)if(o.extensions.includes(s)){let a=e.get(o.name)||{count:0,extensions:new Set};a.count++,a.extensions.add(s),e.set(o.name,a),t++;break}}});let n=[];for(let[r,s]of e)n.push({name:r,percentage:t>0?Math.round(s.count/t*100):0,fileCount:s.count,extensions:Array.from(s.extensions)});return n.sort((r,s)=>s.fileCount-r.fileCount)}async detectExistingTests(){let e={totalCount:0,byFramework:{},byType:{unit:0,integration:0,e2e:0,unknown:0},directories:[]},t=new Set,n=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/_test\.[jt]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/,/.*Test\.java$/];return Q(this.projectRoot,r=>{let s=ie(r);if(n.some(a=>a.test(s))){e.totalCount++;let a=V(this.projectRoot,r).toLowerCase();a.includes("e2e")||a.includes("cypress")||a.includes("playwright")?e.byType.e2e++:a.includes("integration")||a.includes("int-test")?e.byType.integration++:a.includes("unit")||a.includes("__tests__")||a.includes("test/")?e.byType.unit++:e.byType.unknown++;let l=V(this.projectRoot,u(r,".."));t.add(l)}}),e.directories=Array.from(t).slice(0,10),e}async analyzeComplexity(){let e=[],t=[],n=0,r=0;Q(this.projectRoot,a=>{let l=re(a);if([".ts",".tsx",".js",".jsx",".py",".java",".go"].includes(l))try{let g=w(a,"utf-8"),c=this.calculateFileComplexity(g,l);t.push(...c.functionComplexities),c.maxComplexity>n&&(n=c.maxComplexity),r++,c.maxComplexity>10&&e.push(V(this.projectRoot,a))}catch(g){console.debug("[ProjectAnalyzer] Complexity analysis read failed:",g instanceof Error?g.message:g)}});let s=t.reduce((a,l)=>a+l,0),o=t.length>0?s/t.length:0;return{averageCyclomatic:Math.round(o*10)/10,maxCyclomatic:n,totalFiles:r,complexFiles:e.slice(0,20),recommendation:o<5?"simple":o<15?"medium":"complex"}}calculateFileComplexity(e,t){let n=this.stripCommentsAndStrings(e,t),r=this.calculateComplexity(n);return{functionComplexities:[r],maxComplexity:r}}removeDelimitedBlocks(e,t,n){let r="",s=0;for(;s<e.length;){let o=e.indexOf(t,s);if(o===-1){r+=e.slice(s);break}r+=e.slice(s,o);let a=e.indexOf(n,o+t.length);if(a===-1)break;s=a+n.length}return r}stripCommentsAndStrings(e,t){let n=e;return[".ts",".tsx",".js",".jsx",".java",".go"].includes(t)?(n=n.split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
2
+ import{a as te,b as ne}from"./chunk-7FJIIB4H.js";import{a as b}from"./chunk-GX7MEHQ2.js";import{b as ee}from"./chunk-TNWTQWLL.js";import{b as E,d as fe}from"./chunk-4GJAYXB7.js";import{a as k,c as T}from"./chunk-F6AU2MAZ.js";var he={M:16,efConstruction:200,efSearch:100},P={enabled:!0,pretrainedPatterns:!0,hnswConfig:he,promotionThreshold:3,qualityThreshold:.7,embeddingModel:"auto"},_={mode:"hybrid",confidenceThreshold:.7,feedbackEnabled:!0,cacheEnabled:!0,cacheTTLMs:300*1e3},F={enabled:["pattern-consolidator","coverage-gap-scanner","flaky-test-detector","routing-accuracy-monitor"],intervals:{"pattern-consolidator":1800*1e3,"coverage-gap-scanner":3600*1e3,"flaky-test-detector":7200*1e3,"routing-accuracy-monitor":900*1e3},maxConcurrent:4,daemonAutoStart:!0},N={claudeCode:!0,preCommit:!1,ciIntegration:!1},$={install:!0,installV2:!0,installV3:!0,overwrite:!1},O={enabled:!0,parameters:["hnsw.efSearch","routing.confidenceThreshold","pattern.promotionThreshold","testGen.complexityLimit"],tuningIntervalMs:10080*60*1e3,evaluationPeriodMs:5e3};var L=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization","enterprise-integration"];function M(){return"3.9.4"}function Fe(i,e){return{version:M(),project:{name:i,root:e,type:"single"},learning:P,routing:_,workers:F,hooks:N,skills:$,autoTuning:O,domains:{enabled:L,disabled:[]},agents:{maxConcurrent:15,defaultTimeout:6e4}}}fe();import{readFileSync as w,existsSync as p,statSync as ye,readdirSync as ve}from"fs";import{join as u,basename as ie,extname as re,relative as V}from"path";var ke=[{name:"jest",detect:i=>{let e=["jest.config.js","jest.config.ts","jest.config.mjs","jest.config.cjs"];for(let n of e)if(p(u(i,n)))return{name:"jest",version:A(i,"jest"),configFile:n,confidence:1};let t=S(i);return t?.jest?{name:"jest",version:A(i,"jest"),configFile:"package.json",confidence:.9}:t?.devDependencies?.jest||t?.dependencies?.jest?{name:"jest",version:t.devDependencies?.jest||t.dependencies?.jest,confidence:.7}:null}},{name:"vitest",detect:i=>{let e=["vitest.config.ts","vitest.config.js","vitest.config.mts","vite.config.ts"];for(let n of e)if(p(u(i,n)))return{name:"vitest",version:A(i,"vitest"),configFile:n,confidence:1};let t=S(i);return t?.devDependencies?.vitest||t?.dependencies?.vitest?{name:"vitest",version:t.devDependencies?.vitest,confidence:.8}:null}},{name:"mocha",detect:i=>{let e=[".mocharc.js",".mocharc.json",".mocharc.yaml",".mocharc.yml"];for(let n of e)if(p(u(i,n)))return{name:"mocha",version:A(i,"mocha"),configFile:n,confidence:1};let t=S(i);return t?.devDependencies?.mocha?{name:"mocha",version:t.devDependencies?.mocha,confidence:.8}:null}},{name:"pytest",detect:i=>{let e=["pytest.ini","pyproject.toml","setup.cfg"];for(let n of e){let r=u(i,n);if(p(r))try{let s=w(r,"utf-8");if(s.includes("[pytest]")||s.includes("[tool.pytest]"))return{name:"pytest",configFile:n,confidence:1}}catch(s){console.debug("[ProjectAnalyzer] Config read failed:",s instanceof Error?s.message:s)}}let t=u(i,"requirements.txt");if(p(t))try{if(w(t,"utf-8").includes("pytest"))return{name:"pytest",configFile:"requirements.txt",confidence:.8}}catch(n){console.debug("[ProjectAnalyzer] requirements.txt read failed:",n instanceof Error?n.message:n)}return null}},{name:"playwright",detect:i=>{let e=["playwright.config.ts","playwright.config.js"];for(let n of e)if(p(u(i,n)))return{name:"playwright",version:A(i,"@playwright/test"),configFile:n,confidence:1};let t=S(i);return t?.devDependencies?.["@playwright/test"]?{name:"playwright",version:t.devDependencies["@playwright/test"],confidence:.8}:null}},{name:"cypress",detect:i=>{let e=["cypress.config.ts","cypress.config.js","cypress.json"];for(let t of e)if(p(u(i,t)))return{name:"cypress",version:A(i,"cypress"),configFile:t,confidence:1};return p(u(i,"cypress"))?{name:"cypress",configFile:"cypress/",confidence:.9}:null}}],be=[{name:"typescript",extensions:[".ts",".tsx",".mts",".cts"]},{name:"javascript",extensions:[".js",".jsx",".mjs",".cjs"]},{name:"python",extensions:[".py",".pyw"]},{name:"java",extensions:[".java"]},{name:"go",extensions:[".go"]},{name:"rust",extensions:[".rs"]},{name:"csharp",extensions:[".cs"]},{name:"ruby",extensions:[".rb"]},{name:"php",extensions:[".php"]},{name:"kotlin",extensions:[".kt",".kts"]},{name:"swift",extensions:[".swift"]}];function S(i){let e=u(i,"package.json");if(!p(e))return null;try{return E(w(e,"utf-8"))}catch{return null}}function A(i,e){let t=S(i);if(t)return t.devDependencies?.[e]||t.dependencies?.[e]}function Q(i,e,t={}){let{maxDepth:n=10,exclude:r=["node_modules",".git","dist","build","coverage",".next","__pycache__"]}=t;function s(o,a){if(a>n)return;let l;try{l=ve(o)}catch{return}for(let g of l){if(r.includes(g))continue;let c=u(o,g),x;try{x=ye(c)}catch{continue}x.isDirectory()?s(c,a+1):x.isFile()&&e(c)}}s(i,0)}var W=class{projectRoot;constructor(e){this.projectRoot=e}async analyze(){let e=Date.now(),[t,n,r,s,o]=await Promise.all([this.detectFrameworks(),this.detectLanguages(),this.detectExistingTests(),this.analyzeComplexity(),this.measureCoverage()]);return{projectName:S(this.projectRoot)?.name||ie(this.projectRoot),projectRoot:this.projectRoot,projectType:this.detectProjectType(),frameworks:t,languages:n,existingTests:r,codeComplexity:s,coverage:o,packageManager:this.detectPackageManager(),hasTypeScript:p(u(this.projectRoot,"tsconfig.json")),hasCIConfig:this.detectCIConfig(),ciProvider:this.detectCIProvider(),analysisTimestamp:new Date,analysisDurationMs:Date.now()-e}}async detectFrameworks(){let e=[];for(let t of ke){let n=t.detect(this.projectRoot);n&&e.push(n)}return e.sort((t,n)=>n.confidence-t.confidence)}async detectLanguages(){let e=new Map,t=0;Q(this.projectRoot,r=>{let s=re(r).toLowerCase();if(s){for(let o of be)if(o.extensions.includes(s)){let a=e.get(o.name)||{count:0,extensions:new Set};a.count++,a.extensions.add(s),e.set(o.name,a),t++;break}}});let n=[];for(let[r,s]of e)n.push({name:r,percentage:t>0?Math.round(s.count/t*100):0,fileCount:s.count,extensions:Array.from(s.extensions)});return n.sort((r,s)=>s.fileCount-r.fileCount)}async detectExistingTests(){let e={totalCount:0,byFramework:{},byType:{unit:0,integration:0,e2e:0,unknown:0},directories:[]},t=new Set,n=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/_test\.[jt]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/,/.*Test\.java$/];return Q(this.projectRoot,r=>{let s=ie(r);if(n.some(a=>a.test(s))){e.totalCount++;let a=V(this.projectRoot,r).toLowerCase();a.includes("e2e")||a.includes("cypress")||a.includes("playwright")?e.byType.e2e++:a.includes("integration")||a.includes("int-test")?e.byType.integration++:a.includes("unit")||a.includes("__tests__")||a.includes("test/")?e.byType.unit++:e.byType.unknown++;let l=V(this.projectRoot,u(r,".."));t.add(l)}}),e.directories=Array.from(t).slice(0,10),e}async analyzeComplexity(){let e=[],t=[],n=0,r=0;Q(this.projectRoot,a=>{let l=re(a);if([".ts",".tsx",".js",".jsx",".py",".java",".go"].includes(l))try{let g=w(a,"utf-8"),c=this.calculateFileComplexity(g,l);t.push(...c.functionComplexities),c.maxComplexity>n&&(n=c.maxComplexity),r++,c.maxComplexity>10&&e.push(V(this.projectRoot,a))}catch(g){console.debug("[ProjectAnalyzer] Complexity analysis read failed:",g instanceof Error?g.message:g)}});let s=t.reduce((a,l)=>a+l,0),o=t.length>0?s/t.length:0;return{averageCyclomatic:Math.round(o*10)/10,maxCyclomatic:n,totalFiles:r,complexFiles:e.slice(0,20),recommendation:o<5?"simple":o<15?"medium":"complex"}}calculateFileComplexity(e,t){let n=this.stripCommentsAndStrings(e,t),r=this.calculateComplexity(n);return{functionComplexities:[r],maxComplexity:r}}removeDelimitedBlocks(e,t,n){let r="",s=0;for(;s<e.length;){let o=e.indexOf(t,s);if(o===-1){r+=e.slice(s);break}r+=e.slice(s,o);let a=e.indexOf(n,o+t.length);if(a===-1)break;s=a+n.length}return r}stripCommentsAndStrings(e,t){let n=e;return[".ts",".tsx",".js",".jsx",".java",".go"].includes(t)?(n=n.split(`
3
3
  `).map(r=>{let s=r.indexOf("//");return s>=0?r.slice(0,s):r}).join(`
4
4
  `),n=this.removeDelimitedBlocks(n,"/*","*/"),n=this.removeDelimitedBlocks(n,"`","`"),n=this.removeDelimitedBlocks(n,'"','"'),n=this.removeDelimitedBlocks(n,"'","'")):t===".py"&&(n=n.split(`
5
5
  `).map(r=>{let s=r.indexOf("#");return s>=0?r.slice(0,s):r}).join(`