agentic-qe 3.8.13 → 3.9.0

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 (359) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +48 -0
  3. package/dist/adapters/a2ui/integration/agui-sync.js +2 -1
  4. package/dist/audit/witness-chain.js +15 -3
  5. package/dist/boot/fast-paths.d.ts +24 -0
  6. package/dist/boot/fast-paths.js +43 -0
  7. package/dist/boot/parallel-prefetch.d.ts +26 -0
  8. package/dist/boot/parallel-prefetch.js +36 -0
  9. package/dist/cli/bundle.js +12 -9431
  10. package/dist/cli/chunks/adapter-WBR5NXS3.js +2 -0
  11. package/dist/cli/chunks/agent-booster-wasm-PQYB7VRU.js +2 -0
  12. package/dist/cli/chunks/agent-handler-QDAB5NQS.js +33 -0
  13. package/dist/cli/chunks/aqe-learning-engine-TK4JQCGT.js +2 -0
  14. package/dist/cli/chunks/audit-S7JUYYVP.js +3 -0
  15. package/dist/cli/chunks/base-2WXOSMBQ.js +2 -0
  16. package/dist/cli/chunks/better-sqlite3-7KY2RDXO.js +2 -0
  17. package/dist/cli/chunks/brain-handler-PPEGDCN4.js +68 -0
  18. package/dist/cli/chunks/branch-enumerator-XK4V5W7L.js +7 -0
  19. package/dist/cli/chunks/browser-PALA5PL3.js +4 -0
  20. package/dist/cli/chunks/browser-workflow-42F7GK5T.js +2 -0
  21. package/dist/cli/chunks/chunk-24FKIJNC.js +15 -0
  22. package/dist/cli/chunks/chunk-263XS447.js +2 -0
  23. package/dist/cli/chunks/chunk-2BZFNEN2.js +4 -0
  24. package/dist/cli/chunks/chunk-2E5NQNSU.js +180 -0
  25. package/dist/cli/chunks/chunk-2I7J3O6V.js +2 -0
  26. package/dist/cli/chunks/chunk-3ADGXLTM.js +14 -0
  27. package/dist/cli/chunks/chunk-3IHG3WOY.js +12 -0
  28. package/dist/cli/chunks/chunk-3IUNFTIF.js +2 -0
  29. package/dist/cli/chunks/chunk-3JPRUND5.js +2 -0
  30. package/dist/cli/chunks/chunk-3NZLZHJI.js +2 -0
  31. package/dist/cli/chunks/chunk-3THRQEZ2.js +95 -0
  32. package/dist/cli/chunks/chunk-3ZOONQG6.js +2 -0
  33. package/dist/cli/chunks/chunk-4B6NCELM.js +2 -0
  34. package/dist/cli/chunks/chunk-4I2IOUS4.js +2 -0
  35. package/dist/cli/chunks/chunk-4VBTXZRM.js +2 -0
  36. package/dist/cli/chunks/chunk-4VUPRTVX.js +3 -0
  37. package/dist/cli/chunks/chunk-4YOMLWEK.js +70 -0
  38. package/dist/cli/chunks/chunk-4YS3IJ45.js +2 -0
  39. package/dist/cli/chunks/chunk-5SKGFSKD.js +2 -0
  40. package/dist/cli/chunks/chunk-5T2ZQWKF.js +27 -0
  41. package/dist/cli/chunks/chunk-62ADTHV7.js +2 -0
  42. package/dist/cli/chunks/chunk-6EOS7KX2.js +2 -0
  43. package/dist/cli/chunks/chunk-6SVX4DJC.js +6 -0
  44. package/dist/cli/chunks/chunk-72WOAVK6.js +2 -0
  45. package/dist/cli/chunks/chunk-7R6YMLVS.js +3 -0
  46. package/dist/cli/chunks/chunk-7VDBAVTY.js +2 -0
  47. package/dist/cli/chunks/chunk-AFLLQ5PP.js +15 -0
  48. package/dist/cli/chunks/chunk-AKE543X2.js +2 -0
  49. package/dist/cli/chunks/chunk-B36CDR4U.js +2 -0
  50. package/dist/cli/chunks/chunk-B6LLWYQ6.js +2 -0
  51. package/dist/cli/chunks/chunk-BDIEMZ22.js +91 -0
  52. package/dist/cli/chunks/chunk-BGXNSCXX.js +4 -0
  53. package/dist/cli/chunks/chunk-BLBRY5UD.js +2 -0
  54. package/dist/cli/chunks/chunk-BPWXXEH2.js +3029 -0
  55. package/dist/cli/chunks/chunk-BR26T7ZS.js +180 -0
  56. package/dist/cli/chunks/chunk-BTREG4IW.js +2 -0
  57. package/dist/cli/chunks/chunk-BULKFVYX.js +2 -0
  58. package/dist/cli/chunks/chunk-BXAXGEFC.js +24 -0
  59. package/dist/cli/chunks/chunk-CL6POIX4.js +2 -0
  60. package/dist/cli/chunks/chunk-CS2KS7LP.js +2 -0
  61. package/dist/cli/chunks/chunk-CWFB6BSA.js +316 -0
  62. package/dist/cli/chunks/chunk-DRT3WKQW.js +2 -0
  63. package/dist/cli/chunks/chunk-EHDQJQ6Y.js +27 -0
  64. package/dist/cli/chunks/chunk-ESVQ6MEB.js +2 -0
  65. package/dist/cli/chunks/chunk-FEKY7T6Q.js +2 -0
  66. package/dist/cli/chunks/chunk-FGA7VIFR.js +7 -0
  67. package/dist/cli/chunks/chunk-FIA6X7UL.js +2 -0
  68. package/dist/cli/chunks/chunk-GAOJV3OX.js +2 -0
  69. package/dist/cli/chunks/chunk-GKNNSCLC.js +5 -0
  70. package/dist/cli/chunks/chunk-GPQ57KA4.js +2 -0
  71. package/dist/cli/chunks/chunk-GRUUQAR6.js +2 -0
  72. package/dist/cli/chunks/chunk-HRO6OZQD.js +2 -0
  73. package/dist/cli/chunks/chunk-HY6PMO5W.js +66 -0
  74. package/dist/cli/chunks/chunk-IAV2JMIX.js +167 -0
  75. package/dist/cli/chunks/chunk-IFNIIK34.js +21 -0
  76. package/dist/cli/chunks/chunk-IGJPMN4I.js +3 -0
  77. package/dist/cli/chunks/chunk-J3KWWR6Z.js +1 -0
  78. package/dist/cli/chunks/chunk-JBANAPWG.js +2 -0
  79. package/dist/cli/chunks/chunk-JJO7Y4H3.js +604 -0
  80. package/dist/cli/chunks/chunk-JRYGQO2W.js +2 -0
  81. package/dist/cli/chunks/chunk-JXM26HEE.js +2 -0
  82. package/dist/cli/chunks/chunk-JZSDOIXA.js +2 -0
  83. package/dist/cli/chunks/chunk-KP5NUODU.js +3 -0
  84. package/dist/cli/chunks/chunk-LHJQD2VU.js +750 -0
  85. package/dist/cli/chunks/chunk-LNQIY6BP.js +2 -0
  86. package/dist/cli/chunks/chunk-MDUHYUHF.js +2 -0
  87. package/dist/cli/chunks/chunk-MV6CMOJQ.js +65 -0
  88. package/dist/cli/chunks/chunk-MZOFWJTM.js +2 -0
  89. package/dist/cli/chunks/chunk-N2NS2PHA.js +45 -0
  90. package/dist/cli/chunks/chunk-N4TL73TH.js +314 -0
  91. package/dist/cli/chunks/chunk-N5UXCLFI.js +2 -0
  92. package/dist/cli/chunks/chunk-NZ2VCPN4.js +2 -0
  93. package/dist/cli/chunks/chunk-OF4D7MYI.js +2 -0
  94. package/dist/cli/chunks/chunk-OI5NGQO2.js +2 -0
  95. package/dist/cli/chunks/chunk-OLHKGP35.js +2 -0
  96. package/dist/cli/chunks/chunk-QOVHWZEP.js +1 -0
  97. package/dist/cli/chunks/chunk-RFSN6IDA.js +79 -0
  98. package/dist/cli/chunks/chunk-RTGGL7D7.js +4 -0
  99. package/dist/cli/chunks/chunk-RU5WAHB7.js +3 -0
  100. package/dist/cli/chunks/chunk-SUSEVMZT.js +2 -0
  101. package/dist/cli/chunks/chunk-TLHP5EII.js +2 -0
  102. package/dist/cli/chunks/chunk-TWUWL5EJ.js +2 -0
  103. package/dist/cli/chunks/chunk-U5RN7YQW.js +2 -0
  104. package/dist/cli/chunks/chunk-UFUVUO3J.js +2 -0
  105. package/dist/cli/chunks/chunk-UQHYFOBX.js +16 -0
  106. package/dist/cli/chunks/chunk-VOS4NQSF.js +2 -0
  107. package/dist/cli/chunks/chunk-VSVXUTJN.js +256 -0
  108. package/dist/cli/chunks/chunk-WBQSXPBI.js +2 -0
  109. package/dist/cli/chunks/chunk-WGMPEW2T.js +2 -0
  110. package/dist/cli/chunks/chunk-WIEC7VKK.js +2 -0
  111. package/dist/cli/chunks/chunk-WJ3DLOXF.js +14 -0
  112. package/dist/cli/chunks/chunk-X3KI6JOY.js +9 -0
  113. package/dist/cli/chunks/chunk-X5IJGWYG.js +2 -0
  114. package/dist/cli/chunks/chunk-XIBDETCS.js +146 -0
  115. package/dist/cli/chunks/chunk-XLRQYLWW.js +2 -0
  116. package/dist/cli/chunks/chunk-XO6PVK2P.js +3 -0
  117. package/dist/cli/chunks/chunk-XRE2HCWG.js +3 -0
  118. package/dist/cli/chunks/chunk-XT2V2322.js +2 -0
  119. package/dist/cli/chunks/chunk-Y7BHKZFJ.js +18 -0
  120. package/dist/cli/chunks/chunk-YAGODYIG.js +59 -0
  121. package/dist/cli/chunks/chunk-YANUP2RO.js +2 -0
  122. package/dist/cli/chunks/chunk-YPFOCNOE.js +30 -0
  123. package/dist/cli/chunks/chunk-YR6ZZGH7.js +81 -0
  124. package/dist/cli/chunks/chunk-YVA65UZL.js +2 -0
  125. package/dist/cli/chunks/chunk-YW2THB5Q.js +2 -0
  126. package/dist/cli/chunks/chunk-ZAPS3UGQ.js +20 -0
  127. package/dist/cli/chunks/chunk-ZDATDCYN.js +2 -0
  128. package/dist/cli/chunks/ci-J374KDLI.js +81 -0
  129. package/dist/cli/chunks/ci-output-7JN7F6CI.js +2 -0
  130. package/dist/cli/chunks/claude-flow-setup-245JLJCN.js +2 -0
  131. package/dist/cli/chunks/client-MCSNSH2C.js +2 -0
  132. package/dist/cli/chunks/cline-installer-LBA2M5N3.js +4 -0
  133. package/dist/cli/chunks/code-U4N4WONM.js +38 -0
  134. package/dist/cli/chunks/code-index-extractor-A57Z6BO4.js +3 -0
  135. package/dist/cli/chunks/codex-installer-UXMK2N4T.js +8 -0
  136. package/dist/cli/chunks/completions-W66BSCOE.js +1364 -0
  137. package/dist/cli/chunks/complexity-analyzer-AB4OZARV.js +2 -0
  138. package/dist/cli/chunks/continuedev-installer-LRFZ2SJM.js +14 -0
  139. package/dist/cli/chunks/copilot-installer-CQ3JYBIB.js +3 -0
  140. package/dist/cli/chunks/cost-tracker-4F723RB6.js +2 -0
  141. package/dist/cli/chunks/coverage-4PUEQXAY.js +27 -0
  142. package/dist/cli/chunks/cross-domain-router-OWR5IJ5G.js +2 -0
  143. package/dist/cli/chunks/cursor-installer-JZEDEDHA.js +3 -0
  144. package/dist/cli/chunks/daemon-B7TWGHXQ.js +19 -0
  145. package/dist/cli/chunks/dag-attention-scheduler-JWO6XI6A.js +2 -0
  146. package/dist/cli/chunks/detect-L6ZZHUSX.js +2 -0
  147. package/dist/cli/chunks/domain-handler-FT5FLZWL.js +25 -0
  148. package/dist/cli/chunks/domain-transfer-5Y4FGJAJ.js +2 -0
  149. package/dist/cli/chunks/dream-4TDBIYED.js +2 -0
  150. package/dist/cli/chunks/esm-node-2PKHKOTS.js +2 -0
  151. package/dist/cli/chunks/eval-GHMPFGWV.js +15 -0
  152. package/dist/cli/chunks/fast-paths-B3R647KN.js +2 -0
  153. package/dist/cli/chunks/feature-flags-DWS7ARSX.js +2 -0
  154. package/dist/cli/chunks/feature-flags-IVQ3AL4Q.js +2 -0
  155. package/dist/cli/chunks/file-discovery-QFPA6GMV.js +2 -0
  156. package/dist/cli/chunks/fleet-EKOKMOMW.js +43 -0
  157. package/dist/cli/chunks/gnn-wrapper-OYC55N5E.js +2 -0
  158. package/dist/cli/chunks/heartbeat-handler-MBBS4IBU.js +48 -0
  159. package/dist/cli/chunks/heartbeat-scheduler-XDGMOT7X.js +2 -0
  160. package/dist/cli/chunks/hnsw-index-YO7CT23I.js +2 -0
  161. package/dist/cli/chunks/hnswlib-node-56YWVXFE.js +2 -0
  162. package/dist/cli/chunks/hooks-L5VLZGEK.js +101 -0
  163. package/dist/cli/chunks/hypergraph-engine-A4Y2ZRAG.js +2 -0
  164. package/dist/cli/chunks/hypergraph-handler-3HDGB5SZ.js +35 -0
  165. package/dist/cli/chunks/impact-analyzer-UEIGXSZ4.js +2 -0
  166. package/dist/cli/chunks/init-handler-JDET6WUN.js +68 -0
  167. package/dist/cli/chunks/init-wizard-JWZUGIPJ.js +2 -0
  168. package/dist/cli/chunks/kernel-YNDTVKIW.js +2 -0
  169. package/dist/cli/chunks/kilocode-installer-GZZG5AFW.js +4 -0
  170. package/dist/cli/chunks/kiro-installer-IWNY5TKH.js +74 -0
  171. package/dist/cli/chunks/knowledge-graph-NGJKFTSN.js +2 -0
  172. package/dist/cli/chunks/learning-722ZNSZ6.js +107 -0
  173. package/dist/cli/chunks/llm-router-DNAV746L.js +30 -0
  174. package/dist/cli/chunks/load-Y3GCUFM4.js +2 -0
  175. package/dist/cli/chunks/load-test-GZUBXFF3.js +2 -0
  176. package/dist/cli/chunks/mcp-LKPIBZ3W.js +2 -0
  177. package/dist/cli/chunks/memory-L57MLFOP.js +32 -0
  178. package/dist/cli/chunks/memory-backend-3NQIZUXE.js +2 -0
  179. package/dist/cli/chunks/memory-handlers-MDZQ7HVW.js +2 -0
  180. package/dist/cli/chunks/opencode-installer-4HUB36H5.js +3 -0
  181. package/dist/cli/chunks/orchestrator-QHSBB2UC.js +371 -0
  182. package/dist/cli/chunks/pipeline-D3QER35Z.js +19 -0
  183. package/dist/cli/chunks/platform-T4E7Q3RD.js +2 -0
  184. package/dist/cli/chunks/plugin-JHW2YPRC.js +27 -0
  185. package/dist/cli/chunks/prime-radiant-advanced-wasm-G7CFNNQV.js +2 -0
  186. package/dist/cli/chunks/protocol-executor-SPUVRDWT.js +2 -0
  187. package/dist/cli/chunks/protocol-handler-2BQQ4HDM.js +20 -0
  188. package/dist/cli/chunks/prove-UQ6JFT73.js +3 -0
  189. package/dist/cli/chunks/qe-reasoning-bank-3HBK2FVD.js +2 -0
  190. package/dist/cli/chunks/quality-JRZYMC77.js +7 -0
  191. package/dist/cli/chunks/queen-coordinator-RW3NKO5A.js +2 -0
  192. package/dist/cli/chunks/real-embeddings-GK63VF35.js +2 -0
  193. package/dist/cli/chunks/roocode-installer-F4E2LAYR.js +4 -0
  194. package/dist/cli/chunks/router-RJGHWDQ3.js +2 -0
  195. package/dist/cli/chunks/routing-feedback-ZXBXFKX6.js +2 -0
  196. package/dist/cli/chunks/routing-handler-VNKFUUGB.js +20 -0
  197. package/dist/cli/chunks/ruvector-commands-2TLNHC3A.js +8 -0
  198. package/dist/cli/chunks/rvf-dual-writer-MQW2SJLT.js +2 -0
  199. package/dist/cli/chunks/rvf-native-adapter-LKFKTMUN.js +2 -0
  200. package/dist/cli/chunks/safe-db-G22E5ROA.js +2 -0
  201. package/dist/cli/chunks/schedule-Y7VVCPYV.js +2 -0
  202. package/dist/cli/chunks/scheduler-AUQIFQB7.js +2 -0
  203. package/dist/cli/chunks/security-EBEG2OPU.js +14 -0
  204. package/dist/cli/chunks/shared-rvf-dual-writer-BVSCQAFS.js +2 -0
  205. package/dist/cli/chunks/sqlite-persistence-JAVHUGGL.js +2 -0
  206. package/dist/cli/chunks/status-handler-VZ32M4G4.js +45 -0
  207. package/dist/cli/chunks/structural-health-K6LRCKV6.js +2 -0
  208. package/dist/cli/chunks/sync-MHSHNLIM.js +23 -0
  209. package/dist/cli/chunks/task-handler-JNOIBZ2G.js +49 -0
  210. package/dist/cli/chunks/task-handlers-P5DSUKND.js +2 -0
  211. package/dist/cli/chunks/test-DO22BNIL.js +33 -0
  212. package/dist/cli/chunks/test-scheduling-VLRQZEFL.js +15 -0
  213. package/dist/cli/chunks/token-bootstrap-4VJKGVMK.js +2 -0
  214. package/dist/cli/chunks/token-usage-LG3PXRXH.js +25 -0
  215. package/dist/cli/chunks/transformers-GY7SIKEU.js +2 -0
  216. package/dist/cli/chunks/tree-sitter-wasm-parser-FT2KB66N.js +2 -0
  217. package/dist/cli/chunks/types-QJGNBKP2.js +2 -0
  218. package/dist/cli/chunks/unified-memory-XYGENQUT.js +2 -0
  219. package/dist/cli/chunks/unified-memory-hnsw-MVEGQBF3.js +2 -0
  220. package/dist/cli/chunks/unified-persistence-PFRCWEUG.js +2 -0
  221. package/dist/cli/chunks/validate-VQCRSVNQ.js +21 -0
  222. package/dist/cli/chunks/validate-swarm-A5DHAWTP.js +14 -0
  223. package/dist/cli/chunks/vibium-RZBSL4EB.js +2 -0
  224. package/dist/cli/chunks/visual-security-V47BLGJM.js +2 -0
  225. package/dist/cli/chunks/web-tree-sitter-7C4NXEOF.js +2 -0
  226. package/dist/cli/chunks/windsurf-installer-ES3KPQG3.js +7 -0
  227. package/dist/cli/chunks/witness-chain-BR63P4A7.js +2 -0
  228. package/dist/cli/chunks/workflow-JETHX4ML.js +51 -0
  229. package/dist/cli/chunks/workflow-orchestrator-7PZMX3JZ.js +2 -0
  230. package/dist/cli/chunks/wrappers-WP5RH745.js +2 -0
  231. package/dist/cli/commands/daemon.d.ts +13 -0
  232. package/dist/cli/commands/daemon.js +224 -0
  233. package/dist/cli/commands/hooks-handlers/hooks-shared.js +2 -1
  234. package/dist/cli/commands/plugin.d.ts +12 -0
  235. package/dist/cli/commands/plugin.js +135 -0
  236. package/dist/cli/commands/workflow.d.ts +10 -0
  237. package/dist/cli/commands/workflow.js +587 -0
  238. package/dist/cli/handlers/brain-handler.js +13 -8
  239. package/dist/cli/handlers/heartbeat-handler.d.ts +1 -0
  240. package/dist/cli/handlers/heartbeat-handler.js +20 -10
  241. package/dist/cli/handlers/hypergraph-handler.js +3 -3
  242. package/dist/cli/handlers/init-handler.js +10 -9
  243. package/dist/cli/handlers/interfaces.d.ts +4 -4
  244. package/dist/cli/index.js +159 -638
  245. package/dist/cli/lazy-registry.d.ts +27 -0
  246. package/dist/cli/lazy-registry.js +70 -0
  247. package/dist/context/compaction/context-budget.d.ts +71 -0
  248. package/dist/context/compaction/context-budget.js +120 -0
  249. package/dist/context/compaction/index.d.ts +96 -0
  250. package/dist/context/compaction/index.js +259 -0
  251. package/dist/context/compaction/llm-caller-adapter.d.ts +14 -0
  252. package/dist/context/compaction/llm-caller-adapter.js +47 -0
  253. package/dist/context/compaction/tier1-microcompact.d.ts +33 -0
  254. package/dist/context/compaction/tier1-microcompact.js +47 -0
  255. package/dist/context/compaction/tier2-session-summary.d.ts +72 -0
  256. package/dist/context/compaction/tier2-session-summary.js +172 -0
  257. package/dist/context/compaction/tier3-llm-compact.d.ts +65 -0
  258. package/dist/context/compaction/tier3-llm-compact.js +166 -0
  259. package/dist/context/compaction/tier4-reactive.d.ts +54 -0
  260. package/dist/context/compaction/tier4-reactive.js +129 -0
  261. package/dist/coordination/consensus/providers/claude-provider.d.ts +1 -0
  262. package/dist/coordination/consensus/providers/claude-provider.js +23 -3
  263. package/dist/domains/test-generation/generators/base-test-generator.d.ts +1 -1
  264. package/dist/domains/test-generation/generators/base-test-generator.js +11 -11
  265. package/dist/domains/test-generation/generators/go-test-generator.js +12 -12
  266. package/dist/domains/test-generation/generators/junit5-generator.js +9 -9
  267. package/dist/domains/test-generation/generators/kotlin-junit-generator.js +10 -10
  268. package/dist/domains/test-generation/generators/pytest-generator.js +8 -8
  269. package/dist/domains/test-generation/generators/swift-testing-generator.js +8 -8
  270. package/dist/domains/test-generation/generators/test-value-helpers.d.ts +20 -0
  271. package/dist/domains/test-generation/generators/test-value-helpers.js +48 -0
  272. package/dist/domains/test-generation/generators/xunit-generator.js +11 -11
  273. package/dist/hooks/cross-phase-hooks.d.ts +11 -0
  274. package/dist/hooks/cross-phase-hooks.js +73 -9
  275. package/dist/hooks/security/config-snapshot.d.ts +21 -0
  276. package/dist/hooks/security/config-snapshot.js +33 -0
  277. package/dist/hooks/security/exit-codes.d.ts +28 -0
  278. package/dist/hooks/security/exit-codes.js +33 -0
  279. package/dist/hooks/security/index.d.ts +15 -0
  280. package/dist/hooks/security/index.js +15 -0
  281. package/dist/hooks/security/ssrf-guard.d.ts +25 -0
  282. package/dist/hooks/security/ssrf-guard.js +69 -0
  283. package/dist/index.d.ts +1 -1
  284. package/dist/index.js +1 -2
  285. package/dist/init/init-wizard-hooks.js +15 -1
  286. package/dist/init/phases/07-hooks.js +2 -2
  287. package/dist/init/settings-merge.js +3 -7
  288. package/dist/kernel/kernel.js +35 -0
  289. package/dist/kernel/memory-backend.js +3 -1
  290. package/dist/mcp/bundle.js +416 -362
  291. package/dist/mcp/entry.js +132 -77
  292. package/dist/mcp/http-server.js +4 -1
  293. package/dist/mcp/index.d.ts +2 -2
  294. package/dist/mcp/index.js +5 -4
  295. package/dist/mcp/middleware/batch-executor.d.ts +46 -0
  296. package/dist/mcp/middleware/batch-executor.js +150 -0
  297. package/dist/mcp/middleware/microcompact.d.ts +97 -0
  298. package/dist/mcp/middleware/microcompact.js +179 -0
  299. package/dist/mcp/middleware/middleware-chain.d.ts +37 -0
  300. package/dist/mcp/middleware/middleware-chain.js +60 -0
  301. package/dist/mcp/protocol-server.d.ts +16 -0
  302. package/dist/mcp/protocol-server.js +140 -36
  303. package/dist/mcp/services/session-durability-middleware.d.ts +22 -0
  304. package/dist/mcp/services/session-durability-middleware.js +64 -0
  305. package/dist/mcp/services/session-resume.d.ts +29 -0
  306. package/dist/mcp/services/session-resume.js +221 -0
  307. package/dist/mcp/services/session-store.d.ts +84 -0
  308. package/dist/mcp/services/session-store.js +163 -0
  309. package/dist/mcp/tool-registry.d.ts +9 -0
  310. package/dist/mcp/tool-registry.js +30 -1
  311. package/dist/mcp/types.d.ts +1 -0
  312. package/dist/plugins/cache.d.ts +44 -0
  313. package/dist/plugins/cache.js +149 -0
  314. package/dist/plugins/index.d.ts +15 -0
  315. package/dist/plugins/index.js +15 -0
  316. package/dist/plugins/lifecycle.d.ts +67 -0
  317. package/dist/plugins/lifecycle.js +175 -0
  318. package/dist/plugins/manifest.d.ts +45 -0
  319. package/dist/plugins/manifest.js +173 -0
  320. package/dist/plugins/resolver.d.ts +37 -0
  321. package/dist/plugins/resolver.js +80 -0
  322. package/dist/plugins/security.d.ts +23 -0
  323. package/dist/plugins/security.js +125 -0
  324. package/dist/plugins/sources/github.d.ts +17 -0
  325. package/dist/plugins/sources/github.js +77 -0
  326. package/dist/plugins/sources/local.d.ts +20 -0
  327. package/dist/plugins/sources/local.js +32 -0
  328. package/dist/plugins/sources/npm.d.ts +18 -0
  329. package/dist/plugins/sources/npm.js +82 -0
  330. package/dist/shared/llm/retry.d.ts +5 -2
  331. package/dist/shared/llm/retry.js +7 -3
  332. package/dist/shared/prompt-cache-latch.d.ts +41 -0
  333. package/dist/shared/prompt-cache-latch.js +63 -0
  334. package/dist/shared/retry-engine.d.ts +77 -0
  335. package/dist/shared/retry-engine.js +194 -0
  336. package/dist/workers/daemon.d.ts +8 -0
  337. package/dist/workers/daemon.js +13 -0
  338. package/dist/workers/quality-daemon/ci-monitor.d.ts +55 -0
  339. package/dist/workers/quality-daemon/ci-monitor.js +147 -0
  340. package/dist/workers/quality-daemon/coverage-delta.d.ts +72 -0
  341. package/dist/workers/quality-daemon/coverage-delta.js +135 -0
  342. package/dist/workers/quality-daemon/git-watcher.d.ts +51 -0
  343. package/dist/workers/quality-daemon/git-watcher.js +209 -0
  344. package/dist/workers/quality-daemon/index.d.ts +119 -0
  345. package/dist/workers/quality-daemon/index.js +343 -0
  346. package/dist/workers/quality-daemon/nightly-consolidation.d.ts +74 -0
  347. package/dist/workers/quality-daemon/nightly-consolidation.js +136 -0
  348. package/dist/workers/quality-daemon/notification-service.d.ts +67 -0
  349. package/dist/workers/quality-daemon/notification-service.js +178 -0
  350. package/dist/workers/quality-daemon/persistent-memory.d.ts +31 -0
  351. package/dist/workers/quality-daemon/persistent-memory.js +30 -0
  352. package/dist/workers/quality-daemon/priority-queue.d.ts +97 -0
  353. package/dist/workers/quality-daemon/priority-queue.js +126 -0
  354. package/dist/workers/quality-daemon/test-suggester.d.ts +50 -0
  355. package/dist/workers/quality-daemon/test-suggester.js +121 -0
  356. package/dist/workers/worker-manager.js +2 -1
  357. package/package.json +1 -1
  358. package/dist/mcp/server.d.ts +0 -46
  359. package/dist/mcp/server.js +0 -802
@@ -0,0 +1,59 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{b as w,c as L}from"./chunk-3ZOONQG6.js";import{a as ye}from"./chunk-3JPRUND5.js";import{c as oe,d as ce,e as fe}from"./chunk-4VUPRTVX.js";import{b as N,d as le}from"./chunk-WGMPEW2T.js";import{a as j,b as D,c as V}from"./chunk-JZSDOIXA.js";ye();import{createRequire as be}from"module";var O;function W(){if(!O){let h=be(import.meta.url);try{O=h("typescript")}catch{try{O=h("typescript/lib/typescript.js")}catch{O=new Proxy({},{get(e,t){if(!(t==="__esModule"||typeof t=="symbol"))throw new Error("TypeScript is required for code analysis. Install it: npm install -g typescript")}})}}}return O}var p=new Proxy({},{get(h,e){return W()[e]},has(h,e){return e in W()},ownKeys(){return Object.keys(W())},getOwnPropertyDescriptor(h,e){let t=W()[e];if(t!==void 0)return{configurable:!0,enumerable:!0,value:t}}});var F=class{parseFile(e,t){return p.createSourceFile(e,t,p.ScriptTarget.Latest,!0,this.getScriptKind(e))}extractFunctions(e){let t=[],s=n=>{p.isFunctionDeclaration(n)&&n.name?t.push(this.extractFunctionDeclaration(n,e)):p.isVariableStatement(n)&&this.extractArrowFunctions(n,e,t),p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractClasses(e){let t=[],s=n=>{p.isClassDeclaration(n)&&n.name&&t.push(this.extractClassDeclaration(n,e)),p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractImports(e){let t=[],s=n=>{p.isImportDeclaration(n)&&t.push(this.extractImportDeclaration(n)),p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractExports(e){let t=[],s=n=>{if(p.isExportDeclaration(n))this.extractExportDeclaration(n,t);else if(p.isExportAssignment(n))t.push({name:this.getExportAssignmentName(n),type:"unknown",isDefault:!0,isReexport:!1,sourceModule:void 0});else if(p.isFunctionDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"function",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(p.isClassDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"class",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(p.isVariableStatement(n)&&this.hasExportModifier(n))for(let r of n.declarationList.declarations)p.isIdentifier(r.name)&&t.push({name:r.name.text,type:"variable",isDefault:!1,isReexport:!1,sourceModule:void 0});else p.isInterfaceDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"interface",isDefault:!1,isReexport:!1,sourceModule:void 0}):p.isTypeAliasDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"type",isDefault:!1,isReexport:!1,sourceModule:void 0}):p.isEnumDeclaration(n)&&this.hasExportModifier(n)&&t.push({name:n.name.text,type:"enum",isDefault:!1,isReexport:!1,sourceModule:void 0});p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractInterfaces(e){let t=[],s=n=>{p.isInterfaceDeclaration(n)&&t.push(this.extractInterfaceDeclaration(n,e)),p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractEntities(e,t){let s=this.parseFile(t,e),n=[],r=this.extractFunctions(s);for(let a of r)n.push({name:a.name,type:"function",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:a.isAsync,isExported:a.isExported,parameters:a.parameters,returnType:a.returnType});let o=this.extractClasses(s);for(let a of o)n.push({name:a.name,type:"class",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported,extends:a.extends,implements:a.implements});let i=this.extractInterfaces(s);for(let a of i)n.push({name:a.name,type:"interface",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported});return n}getScriptKind(e){return e.endsWith(".tsx")?p.ScriptKind.TSX:e.endsWith(".ts")?p.ScriptKind.TS:e.endsWith(".jsx")?p.ScriptKind.JSX:e.endsWith(".js")?p.ScriptKind.JS:p.ScriptKind.TS}extractFunctionDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:e.name?.text??"anonymous",parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,startLine:s+1,endLine:n+1,isAsync:this.hasAsyncModifier(e),isExported:this.hasExportModifier(e),isGenerator:!!e.asteriskToken,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractArrowFunctions(e,t,s){for(let n of e.declarationList.declarations)if(p.isIdentifier(n.name)&&n.initializer&&p.isArrowFunction(n.initializer)){let r=n.initializer,{line:o}=t.getLineAndCharacterOfPosition(e.getStart()),{line:i}=t.getLineAndCharacterOfPosition(e.getEnd());s.push({name:n.name.text,parameters:this.extractParameters(r.parameters),returnType:r.type?r.type.getText(t):void 0,startLine:o+1,endLine:i+1,isAsync:this.hasAsyncModifier(r),isExported:this.hasExportModifier(e),isGenerator:!1,typeParameters:this.extractTypeParameters(r.typeParameters)})}}extractClassDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),r=[],o=[];for(let c of e.members)p.isMethodDeclaration(c)&&c.name?r.push(this.extractMethodDeclaration(c,t)):p.isPropertyDeclaration(c)&&c.name?o.push(this.extractPropertyDeclaration(c,t)):p.isConstructorDeclaration(c)&&(r.push(this.extractConstructor(c,t)),this.extractParameterProperties(c,o,t));let i,a=[];if(e.heritageClauses){for(let c of e.heritageClauses)if(c.token===p.SyntaxKind.ExtendsKeyword)i=c.types[0]?.expression.getText(t);else if(c.token===p.SyntaxKind.ImplementsKeyword)for(let l of c.types)a.push(l.expression.getText(t))}return{name:e.name?.text??"anonymous",methods:r,properties:o,extends:i,implements:a,isAbstract:this.hasAbstractModifier(e),isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractMethodDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:this.getPropertyName(e.name,t),parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,isAsync:this.hasAsyncModifier(e),isStatic:this.hasStaticModifier(e),isAbstract:this.hasAbstractModifier(e),visibility:this.getVisibility(e),startLine:s+1,endLine:n+1}}extractConstructor(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:"constructor",parameters:this.extractParameters(e.parameters),returnType:void 0,isAsync:!1,isStatic:!1,isAbstract:!1,visibility:"public",startLine:s+1,endLine:n+1}}extractParameterProperties(e,t,s){for(let n of e.parameters)this.isParameterProperty(n)&&t.push({name:p.isIdentifier(n.name)?n.name.text:n.name.getText(s),type:n.type?n.type.getText(s):void 0,isStatic:!1,isReadonly:this.hasReadonlyModifier(n),visibility:this.getVisibility(n),hasInitializer:!!n.initializer})}isParameterProperty(e){return!!e.modifiers?.some(t=>t.kind===p.SyntaxKind.PublicKeyword||t.kind===p.SyntaxKind.PrivateKeyword||t.kind===p.SyntaxKind.ProtectedKeyword||t.kind===p.SyntaxKind.ReadonlyKeyword)}extractPropertyDeclaration(e,t){return{name:this.getPropertyName(e.name,t),type:e.type?e.type.getText(t):void 0,isStatic:this.hasStaticModifier(e),isReadonly:this.hasReadonlyModifier(e),visibility:this.getVisibility(e),hasInitializer:!!e.initializer}}extractImportDeclaration(e){let t=e.moduleSpecifier.text,s=[],n,r,o=e.importClause?.isTypeOnly??!1;if(e.importClause&&(e.importClause.name&&(n=e.importClause.name.text),e.importClause.namedBindings)){if(p.isNamespaceImport(e.importClause.namedBindings))r=e.importClause.namedBindings.name.text;else if(p.isNamedImports(e.importClause.namedBindings))for(let i of e.importClause.namedBindings.elements)s.push({name:i.propertyName?.text??i.name.text,alias:i.propertyName?i.name.text:void 0})}return{module:t,namedImports:s,defaultImport:n,namespaceImport:r,isTypeOnly:o}}extractExportDeclaration(e,t){let s=e.moduleSpecifier?e.moduleSpecifier.text:void 0;if(e.exportClause&&p.isNamedExports(e.exportClause))for(let n of e.exportClause.elements)t.push({name:n.name.text,type:"unknown",isDefault:!1,isReexport:!!s,sourceModule:s});else!e.exportClause&&s&&t.push({name:"*",type:"unknown",isDefault:!1,isReexport:!0,sourceModule:s})}extractInterfaceDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),r=[],o=[];for(let a of e.members)p.isPropertySignature(a)&&a.name?r.push({name:this.getPropertyName(a.name,t),type:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken,isReadonly:this.hasReadonlyModifier(a)}):p.isMethodSignature(a)&&a.name&&o.push({name:this.getPropertyName(a.name,t),parameters:this.extractParameters(a.parameters),returnType:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken});let i=[];if(e.heritageClauses){for(let a of e.heritageClauses)if(a.token===p.SyntaxKind.ExtendsKeyword)for(let c of a.types)i.push(c.expression.getText(t))}return{name:e.name.text,properties:r,methods:o,extends:i,isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractParameters(e){return e.map(t=>{let s=t.getSourceFile();return{name:p.isIdentifier(t.name)?t.name.text:t.name.getText(s),type:t.type?t.type.getText(s):void 0,isOptional:!!t.questionToken||!!t.initializer,isRest:!!t.dotDotDotToken,defaultValue:t.initializer?t.initializer.getText(s):void 0}})}extractTypeParameters(e){return e?e.map(t=>t.name.text):[]}getPropertyName(e,t){return p.isIdentifier(e)||p.isStringLiteral(e)||p.isNumericLiteral(e)?e.text:e.getText(t)}getExportAssignmentName(e){return p.isIdentifier(e.expression)?e.expression.text:"default"}hasExportModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.ExportKeyword)}hasDefaultModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.DefaultKeyword)}hasAsyncModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.AsyncKeyword)}hasStaticModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.StaticKeyword)}hasAbstractModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.AbstractKeyword)}hasReadonlyModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.ReadonlyKeyword)}getVisibility(e){if(!p.canHaveModifiers(e))return"public";let t=p.getModifiers(e);return t?t.some(s=>s.kind===p.SyntaxKind.PrivateKeyword)?"private":t.some(s=>s.kind===p.SyntaxKind.ProtectedKeyword)?"protected":"public":"public"}},Me=new F,q=class{language="typescript";supportedExtensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];parser=new F;async parseFile(e,t){let s=this.parser.parseFile(t,e),n=this.parser.extractFunctions(s),r=this.parser.extractClasses(s),o=this.parser.extractImports(s);return{functions:n.map(i=>this.mapFunction(i)),classes:r.map(i=>this.mapClass(i)),imports:o.map(i=>this.mapImport(i)),language:t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":"typescript",filePath:t}}mapFunction(e){return{name:e.name,parameters:e.parameters.map(t=>({name:t.name,type:t.type,isOptional:t.isOptional,defaultValue:t.defaultValue})),returnType:e.returnType,isAsync:e.isAsync,isPublic:e.isExported,complexity:1,decorators:[],genericParams:e.typeParameters,startLine:e.startLine,endLine:e.endLine}}mapClass(e){return{name:e.name,methods:e.methods.map(t=>({name:t.name,parameters:t.parameters.map(s=>({name:s.name,type:s.type,isOptional:s.isOptional,defaultValue:s.defaultValue})),returnType:t.returnType,isAsync:t.isAsync,isPublic:t.visibility==="public",complexity:1,decorators:[],genericParams:[],startLine:t.startLine,endLine:t.endLine})),properties:e.properties.map(t=>this.mapProperty(t)),isPublic:e.isExported,implements:e.implements,extends:e.extends,decorators:[],startLine:e.startLine,endLine:e.endLine}}mapProperty(e){return{name:e.name,type:e.type,isPublic:e.visibility==="public",isReadonly:e.isReadonly}}mapImport(e){return{module:e.module,namedImports:e.namedImports.map(t=>t.alias||t.name),isTypeOnly:e.isTypeOnly}}},Se=new q;fe();var E=1e3;function I(h){let e=h.split(`
3
+ `),t=[],s=[],n="",r=0,o=0,i=0,a=0;for(let c=0;c<e.length;c++){let l=e[c],d=l.trim();if(d===""||d.startsWith("//")||d.startsWith("#")||d.startsWith("*")){if(n){n+=" "+d;continue}t.push(l),s.push(c+1);continue}n||(r=c+1),n=n?n+" "+d:l;for(let u of d)u==="("?o++:u===")"?o=Math.max(0,o-1):u==="<"?i++:u===">"?i=Math.max(0,i-1):u==="["?a++:u==="]"&&(a=Math.max(0,a-1));o===0&&i===0&&a===0&&(t.push(n),s.push(r),n="")}return n&&(t.push(n),s.push(r)),{logicalLines:t,lineMap:s}}function G(h,e,t="<",s=">"){if(h[e]!==t)return;let n=1,r=e+1;for(;r<h.length&&n>0;)h[r]===t?n++:h[r]===s&&n--,r++;if(n===0)return h.substring(e+1,r-1)}function R(h,e,t){let s=[];for(let n=e-1;n>=0;n--){let r=h[n].trim();if(r.startsWith(t))s.unshift(r);else{if(r===""||r.startsWith("//")||r.startsWith("*")||r.startsWith("#"))continue;break}}return s}function S(h){let e=[],t=0,s="";for(let n of h)n==="<"||n==="("?t++:(n===">"||n===")")&&t--,n===","&&t===0?(e.push(s.trim()),s=""):s+=n;return s.trim()&&e.push(s.trim()),e}function re(h){let e=0,t=!1,s="";for(let n=0;n<h.length;n++){let r=h[n];if(t){r===s&&h[n-1]!=="\\"&&(t=!1);continue}r==='"'||r==="'"||r==="`"?(t=!0,s=r):r==="{"?e++:r==="}"&&e--}return e}var H=class{language="python";supportedExtensions=[".py"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"python",filePath:t}}extractFunctions(e){let t=[],s=e.split(`
4
+ `),{logicalLines:n,lineMap:r}=I(e),o=/^(\s*)(async\s+)?def\s+(\w+)\s*\(([^)]*)\)(?:\s*->\s*([^:]*\S))?\s*:/;for(let i=0;i<n.length;i++){if(n[i].length>E)continue;let a=n[i].match(o);if(a){let c=a[1].length,l=!!a[2],d=a[3],u=a[4],m=a[5]?.trim(),g=r[i]-1,f=g+1;for(let y=g+1;y<s.length;y++){let b=s[y];if(b.trim()===""||b.trim().startsWith("#"))continue;if((b.match(/^(\s*)/)?.[1].length??0)<=c&&b.trim()!==""){f=y;break}f=y+1}let x=R(s,g,"@");t.push({name:d,parameters:this.parseParams(u),returnType:m,isAsync:l,isPublic:!d.startsWith("_"),complexity:1,decorators:x,genericParams:[],startLine:r[i],endLine:f})}}return t}extractClasses(e){let t=[],s=e.split(`
5
+ `),{logicalLines:n,lineMap:r}=I(e),o=/^(\s*)class\s+(\w+)(?:\(([^)]*)\))?\s*:/;for(let i=0;i<n.length;i++){let a=n[i].match(o);if(a){let c=a[1].length,l=a[2],d=a[3]?a[3].split(",").map(y=>y.trim()):[],u=r[i]-1,m=u+1;for(let y=u+1;y<s.length;y++){let b=s[y];if(b.trim()===""||b.trim().startsWith("#"))continue;if((b.match(/^(\s*)/)?.[1].length??0)<=c&&b.trim()!==""){m=y;break}m=y+1}let g=s.slice(u+1,m).join(`
6
+ `),f=this.extractFunctions(g).map(y=>({...y,startLine:y.startLine+u,endLine:y.endLine+u})),x=R(s,u,"@");t.push({name:l,methods:f,properties:[],isPublic:!l.startsWith("_"),implements:[],extends:d[0]||void 0,decorators:x,startLine:r[i],endLine:m})}}return t}extractImports(e){let t=[],s=e.split(`
7
+ `);for(let n of s){if(n.length>E)continue;let r=n.match(/^\s*from\s+(\S+)\s+import\s+(.+)/);if(r){let i=r[2].split(",").map(a=>a.trim().split(" as ")[0]);t.push({module:r[1],namedImports:i,isTypeOnly:!1});continue}let o=n.match(/^\s*import\s+(\S+)/);o&&t.push({module:o[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){return e.trim()?S(e).map(t=>t.trim()).filter(t=>t&&t!=="self"&&t!=="cls").map(t=>{let[s,n]=t.split(":").map(i=>i.trim()),[r,o]=s.split("=").map(i=>i.trim());return{name:r,type:n?.split("=")[0].trim()||void 0,isOptional:!!o||r.startsWith("*"),defaultValue:o||void 0}}):[]}},J=class{language="java";supportedExtensions=[".java"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"java",filePath:t}}extractFunctions(e){let t=[],s=e.split(`
8
+ `),{logicalLines:n,lineMap:r}=I(e),o=/^\s*(public|private|protected)?\s*(static)?\s*(async)?\s*(?:<\S+>\s+)?([\w<>,.[\]?]+(?:\s+[\w<>,.[\]?]+)*)\s+(\w+)\s*\(([^)]*)\)/;for(let i=0;i<n.length;i++){let a=n[i];if(a.includes(" class ")||a.includes(" interface ")||a.length>E)continue;let c=a.match(o);if(c){let l=c[1]||"default",d=c[5],u=c[6],m=c[4]?.trim(),g=m;if(m&&m.includes("<")){let y=m.indexOf("<"),b=G(m,y);b!==void 0&&(g=m.substring(0,y)+"<"+b+">")}let f=r[i]-1,x=R(s,f,"@");t.push({name:d,parameters:this.parseParams(u),returnType:g==="void"?void 0:g,isAsync:g?.includes("CompletableFuture")||!1,isPublic:l==="public",complexity:1,decorators:x,genericParams:[],startLine:r[i],endLine:r[i]})}}return t}extractClasses(e){let t=[],s=e.split(`
9
+ `),{logicalLines:n,lineMap:r}=I(e),o=/^\s*(public|private|protected)?\s*(abstract)?\s*class\s+(\w+)(?:<[^{]*>)?(?:\s+extends\s+(\w+))?(?:\s+implements\s+([^{\s]+(?:\s+[^{\s]+)*))?\s*\{?/;for(let i=0;i<n.length;i++){if(n[i].length>E)continue;let a=n[i].match(o);if(a){let c=a[3],l=a[4],d=a[5]?a[5].split(",").map(g=>g.trim()):[],u=r[i]-1,m=R(s,u,"@");t.push({name:c,methods:[],properties:[],isPublic:(a[1]||"default")==="public",implements:d,extends:l,decorators:m,startLine:r[i],endLine:r[i]})}}return t}extractImports(e){let t=[],s=e.split(`
10
+ `);for(let n of s){if(n.length>E)continue;let r=n.match(/^\s*import +(static +)?(\S[^;]*);/);if(r){let o=r[2].trim(),i=o.split("."),a=i[i.length-1];t.push({module:o,namedImports:a==="*"?[]:[a],isTypeOnly:!1})}}return t}parseParams(e){return e.trim()?S(e).map(t=>{let n=t.trim().split(/\s+/).filter(i=>!i.startsWith("@")),r=n[n.length-1]||"",o=n.slice(0,-1).join(" ")||void 0;return{name:r,type:o,isOptional:!1,defaultValue:void 0}}):[]}},Q=class{language="csharp";supportedExtensions=[".cs"];async parseFile(e,t){return{functions:this.extractMethods(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"csharp",filePath:t}}extractMethods(e){let t=[],s=e.split(`
11
+ `),{logicalLines:n,lineMap:r}=I(e),o=/^\s*(public|private|protected|internal)?\s*(static)?\s*(async)?\s*([\w<>,.[\]?]+(?:\s+[\w<>,.[\]?]+)*)\s+(\w+)\s*\(([^)]*)\)/;for(let i=0;i<n.length;i++){let a=n[i];if(a.includes(" class ")||a.includes(" interface ")||a.includes(" namespace ")||a.length>E)continue;let c=a.match(o);if(c){let l=c[1]||"private",d=!!c[3]||c[4]?.includes("Task")||!1,u=c[4]?.trim(),m=u;if(u&&u.includes("<")){let b=u.indexOf("<"),P=G(u,b);P!==void 0&&(m=u.substring(0,b)+"<"+P+">")}let g=c[5],f=c[6],x=r[i]-1,y=R(s,x,"[");t.push({name:g,parameters:this.parseParams(f),returnType:m==="void"?void 0:m,isAsync:d,isPublic:l==="public",complexity:1,decorators:y,genericParams:[],startLine:r[i],endLine:r[i]})}}return t}extractClasses(e){let t=[],s=e.split(`
12
+ `),{logicalLines:n,lineMap:r}=I(e),o=/^\s*(public|private|protected|internal)?\s*(abstract|sealed|static|partial)?\s*class\s+(\w+)(?:<[^{]*>)?(?:\s*:\s*([^{\s]+(?:\s+[^{\s]+)*))?\s*\{?/;for(let i=0;i<n.length;i++){if(n[i].length>E)continue;let a=n[i].match(o);if(a){let c=a[3],l=a[4]?a[4].split(",").map(m=>m.trim()):[],d=r[i]-1,u=R(s,d,"[");t.push({name:c,methods:[],properties:[],isPublic:(a[1]||"internal")==="public",implements:l.slice(1),extends:l[0]||void 0,decorators:u,startLine:r[i],endLine:r[i]})}}return t}extractImports(e){let t=[],s=e.split(`
13
+ `);for(let n of s){if(n.length>E)continue;let r=n.match(/^\s*using +(static +)?(\S[^;]*);/);r&&t.push({module:r[2].trim(),namedImports:[],isTypeOnly:!1})}return t}parseParams(e){return e.trim()?S(e).map(t=>{let s=t.trim().split(/\s+/),n=s[s.length-1]||"",r=s.slice(0,-1).join(" ")||void 0;return{name:n,type:r,isOptional:r?.endsWith("?")||!1,defaultValue:void 0}}):[]}},X=class{language="go";supportedExtensions=[".go"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractStructs(e),imports:this.extractImports(e),language:"go",filePath:t}}extractFunctions(e){let t=[],s=e.split(`
14
+ `),{logicalLines:n,lineMap:r}=I(e),o=/^\s*func\s+(?:\((\w+)\s+\*?(\w+)\)\s+)?(\w+)\s*\(([^)]*)\)\s*([\w*[\](),\s]*)\s*\{?/,i=0;for(let a=0;a<n.length;a++){let c=n[a];if(c.length>E){i+=(c.match(/\{/g)?.length??0)-(c.match(/\}/g)?.length??0);continue}let l=c.match(o);if(l&&i===0){let d=l[3],u=l[4],m=l[5]?.trim()||void 0;t.push({name:d,parameters:this.parseParams(u),returnType:m||void 0,isAsync:!1,isPublic:d[0]===d[0].toUpperCase(),complexity:1,decorators:[],genericParams:[],startLine:r[a],endLine:r[a]})}i+=re(c),i<0&&(i=0)}return t}extractStructs(e){let t=[],{logicalLines:s,lineMap:n}=I(e),r=/^\s*type\s+(\w+)\s+struct\s*\{/;for(let o=0;o<s.length;o++){let i=s[o].match(r);if(i){let a=i[1];t.push({name:a,methods:[],properties:[],isPublic:a[0]===a[0].toUpperCase(),implements:[],extends:void 0,decorators:[],startLine:n[o],endLine:n[o]})}}return t}extractImports(e){let t=[],s=/^\s*import\s+"([^"]+)"/,n=/^\s*import\s*\(/,r=/^\s*"([^"]+)"/,o=e.split(`
15
+ `),i=!1;for(let a of o)if(i){if(a.includes(")")){i=!1;continue}let c=a.match(r);c&&t.push({module:c[1],namedImports:[],isTypeOnly:!1})}else{let c=a.match(s);c?t.push({module:c[1],namedImports:[],isTypeOnly:!1}):n.test(a)&&(i=!0)}return t}parseParams(e){return e.trim()?S(e).map(t=>{let s=t.trim().split(/\s+/),n=s[0]||"",r=s.slice(1).join(" ")||void 0;return{name:n,type:r,isOptional:!1,defaultValue:void 0}}):[]}},Y=class{language="rust";supportedExtensions=[".rs"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractStructsAndImpls(e),imports:this.extractImports(e),language:"rust",filePath:t}}extractFunctions(e){let t=[],s=e.split(`
16
+ `),{logicalLines:n,lineMap:r}=I(e),o=/^\s*(pub(?:\(crate\))? +)?(async +)?fn\s+(\w+)(?:<[^{]*>)?\s*\(([^)]*)\)(?:\s*->\s*([^{\s]+(?:\s+[^{\s]+)*))?\s*(?:where\s+[^{\s]+(?:\s+[^{\s]+)*)?\s*\{?/,i=0;for(let a=0;a<n.length;a++){let c=n[a],l=c.match(o);if(l&&i<=1){let d=!!l[1],u=!!l[2],m=l[3],g=l[4],f=l[5]?.trim(),x=r[a]-1,y=R(s,x,"#[");t.push({name:m,parameters:this.parseParams(g),returnType:f,isAsync:u,isPublic:d,complexity:1,decorators:y,genericParams:[],startLine:r[a],endLine:r[a]})}i+=re(c),i<0&&(i=0)}return t}extractStructsAndImpls(e){let t=[],s=e.split(`
17
+ `),{logicalLines:n,lineMap:r}=I(e),o=/^\s*(pub(?:\(crate\))?\s+)?struct\s+(\w+)(?:<[^{]*>)?\s*/;for(let i=0;i<n.length;i++){let a=n[i].match(o);if(a){let c=r[i]-1,l=R(s,c,"#[");t.push({name:a[2],methods:[],properties:[],isPublic:!!a[1],implements:[],extends:void 0,decorators:l,startLine:r[i],endLine:r[i]})}}return t}extractImports(e){let t=[],s=e.split(`
18
+ `);for(let n of s){if(n.length>E)continue;let r=n.match(/^\s*use +(\S[^;]*);/);r&&t.push({module:r[1].trim(),namedImports:[],isTypeOnly:!1})}return t}parseParams(e){return e.trim()?S(e).map(t=>t.trim()).filter(t=>t&&t!=="&self"&&t!=="&mut self"&&t!=="self").map(t=>{let s=t.indexOf(":");if(s===-1)return{name:t,type:void 0,isOptional:!1,defaultValue:void 0};let n=t.substring(0,s).trim(),r=t.substring(s+1).trim();return{name:n,type:r,isOptional:!1,defaultValue:void 0}}):[]}},Z=class{language="swift";supportedExtensions=[".swift"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"swift",filePath:t}}extractFunctions(e){let t=[],{logicalLines:s,lineMap:n}=I(e),r=/^\s*(public|private|internal|open)?\s*(static)?\s*func\s+(\w+)(?:<[^{]*>)?\s*\(([^)]*)\)(?:\s*(async))?\s*(?:throws +)?(?:->\s*([^{\s]+(?:\s+[^{\s]+)*))?\s*\{?/;for(let o=0;o<s.length;o++){if(s[o].length>E)continue;let i=s[o].match(r);if(i){let a=i[1]||"internal",c=!!i[5],l=i[3],d=i[4],u=i[6]?.trim();t.push({name:l,parameters:this.parseParams(d),returnType:u,isAsync:c,isPublic:a==="public"||a==="open",complexity:1,decorators:[],genericParams:[],startLine:n[o],endLine:n[o]})}}return t}extractClasses(e){let t=[],{logicalLines:s,lineMap:n}=I(e),r=/^\s*(public|private|internal|open)?\s*(class|struct|protocol)\s+(\w+)(?:<[^{]*>)?(?:\s*:\s*([^{\s]+(?:\s+[^{\s]+)*))?\s*\{?/;for(let o=0;o<s.length;o++){if(s[o].length>E)continue;let i=s[o].match(r);if(i){let a=i[3],c=i[4]?i[4].split(",").map(l=>l.trim()):[];t.push({name:a,methods:[],properties:[],isPublic:(i[1]||"internal")==="public"||i[1]==="open",implements:c.slice(1),extends:c[0]||void 0,decorators:[],startLine:n[o],endLine:n[o]})}}return t}extractImports(e){let t=[],s=e.split(`
19
+ `);for(let n of s){let r=n.match(/^\s*import\s+(\w+)/);r&&t.push({module:r[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){return e.trim()?S(e).map(t=>{let s=t.trim().split(":"),n=s[0]?.trim().split(/\s+/)||[],r=n[n.length-1]||"",o=s.slice(1).join(":").trim();return{name:r,type:o||void 0,isOptional:o?.endsWith("?")||!1,defaultValue:void 0}}):[]}},ee=class{language="kotlin";supportedExtensions=[".kt",".kts"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"kotlin",filePath:t}}extractFunctions(e){let t=[],s=e.split(`
20
+ `),{logicalLines:n,lineMap:r}=I(e),o=/^\s*(public|private|protected|internal)?\s*(suspend)?\s*fun\s+(?:<[^{]*> +)?(\w+)\s*\(([^)]*)\)(?:\s*:\s*([^{=\s]+(?:\s+[^{=\s]+)*))?\s*/,i=0;for(let a=0;a<n.length;a++){let c=n[a];if(c.length>E){i+=(c.match(/\{/g)?.length??0)-(c.match(/\}/g)?.length??0);continue}let l=c.match(o);if(l&&i<=1){let d=l[1]||"public",u=!!l[2],m=l[3],g=l[4],f=l[5]?.trim();if(f&&f.includes("<")){let b=f.indexOf("<"),P=G(f,b);P!==void 0&&(f=f.substring(0,b)+"<"+P+">")}let x=r[a]-1,y=R(s,x,"@");t.push({name:m,parameters:this.parseParams(g),returnType:f,isAsync:u,isPublic:d==="public",complexity:1,decorators:y,genericParams:[],startLine:r[a],endLine:r[a]})}i+=re(c),i<0&&(i=0)}return t}extractClasses(e){let t=[],s=e.split(`
21
+ `),{logicalLines:n,lineMap:r}=I(e),o=/^\s*(public|private|protected|internal)?\s*(data|sealed|abstract|open)?\s*class\s+(\w+)(?:<[^{]*>)?(?:\s*(?:\([^)]*\))?\s*:\s*([^{\s]+(?:\s+[^{\s]+)*))?\s*\{?/;for(let i=0;i<n.length;i++){if(n[i].length>E)continue;let a=n[i].match(o);if(a){let c=a[3],l=a[4]?a[4].split(",").map(m=>m.trim().split("(")[0].trim()):[],d=r[i]-1,u=R(s,d,"@");t.push({name:c,methods:[],properties:[],isPublic:(a[1]||"public")==="public",implements:l.slice(1),extends:l[0]||void 0,decorators:u,startLine:r[i],endLine:r[i]})}}return t}extractImports(e){let t=[],s=e.split(`
22
+ `);for(let n of s){let r=n.match(/^\s*import\s+([^\s]+)/);r&&t.push({module:r[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){return e.trim()?S(e).map(t=>{let s=t.indexOf(":");if(s===-1)return{name:t.replace("val ","").replace("var ","").trim(),type:void 0,isOptional:!1,defaultValue:void 0};let n=t.substring(0,s).replace("val ","").replace("var ","").trim(),r=t.substring(s+1).trim(),o=r.indexOf("="),i=o>=0?r.substring(0,o).trim():r,a=o>=0;return{name:n,type:i,isOptional:a||i?.endsWith("?")||!1,defaultValue:void 0}}):[]}},te=class{language="dart";supportedExtensions=[".dart"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"dart",filePath:t}}extractFunctions(e){let t=[],{logicalLines:s,lineMap:n}=I(e),r=/^\s*([\w<>,.?]+(?:\s+[\w<>,.?]+)*)\s+(\w+)\s*\(([^)]*)\)(?:\s*(async))?\s*\{/;for(let o=0;o<s.length;o++){let i=s[o];if(i.includes(" class ")||i.length>E)continue;let a=i.match(r);if(a){let c=a[1].trim(),l=c;if(c&&c.includes("<")){let g=c.indexOf("<"),f=G(c,g);f!==void 0&&(l=c.substring(0,g)+"<"+f+">")}let d=a[2],u=a[3],m=!!a[4]||l.includes("Future");t.push({name:d,parameters:this.parseParams(u),returnType:l==="void"?void 0:l,isAsync:m,isPublic:!d.startsWith("_"),complexity:1,decorators:[],genericParams:[],startLine:n[o],endLine:n[o]})}}return t}extractClasses(e){let t=[],{logicalLines:s,lineMap:n}=I(e),r=/^\s*(abstract +)?class\s+(\w+)(?:<[^{]*>)?(?:\s+extends\s+(\w+))?(?:\s+(?:with|implements)\s+([^{\s]+(?:\s+[^{\s]+)*))?\s*\{/;for(let o=0;o<s.length;o++){if(s[o].length>E)continue;let i=s[o].match(r);if(i){let a=i[2],c=i[3],l=i[4]?i[4].split(",").map(d=>d.trim()):[];t.push({name:a,methods:[],properties:[],isPublic:!a.startsWith("_"),implements:l,extends:c,decorators:[],startLine:n[o],endLine:n[o]})}}return t}extractImports(e){let t=[],s=e.split(`
23
+ `);for(let n of s){let r=n.match(/^\s*import\s+'([^']+)'/);r&&t.push({module:r[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){if(!e.trim())return[];let t=e.replace(/[{}[\]]/g,"");return S(t).map(s=>s.trim()).filter(s=>s).map(s=>{let n=s.replace("required ","").trim().split(/\s+/),r=n[n.length-1]||"",o=n.slice(0,-1).join(" ")||void 0;return{name:r,type:o,isOptional:s.includes("?")||s.includes("{"),defaultValue:void 0}})}},$=ce("ParserRegistry"),de=["python","java","csharp","rust","swift"],se=class h{language;supportedExtensions;wasmParser;regexParser;wasmFailCount=0;static MAX_WASM_RETRIES=3;constructor(e,t){this.wasmParser=e,this.regexParser=t,this.language=e.language,this.supportedExtensions=e.supportedExtensions}async parseFile(e,t){if(this.wasmFailCount<h.MAX_WASM_RETRIES)try{return await this.wasmParser.parseFile(e,t)}catch(s){this.wasmFailCount++;let n=s instanceof Error?s.message:String(s),r=this.wasmFailCount>=h.MAX_WASM_RETRIES;$.warn(`[${this.language}] tree-sitter WASM parser failed (attempt ${this.wasmFailCount}/${h.MAX_WASM_RETRIES}): ${n}. Falling back to regex parser (~97-98% accuracy). `+(r?"Set AQE_PARSER_REGEX_ONLY=1 to silence this warning.":"Will retry WASM on next parse."))}return this.regexParser.parseFile(e,t)}},ne=class{parsers=new Map;_wasmInitPromise=null;constructor(){this.register(new H),this.register(new J),this.register(new Q),this.register(new X),this.register(new Y),this.register(new Z),this.register(new ee),this.register(new te),this._wasmInitPromise=this._tryLoadWasmParsers()}async _tryLoadWasmParsers(){try{let e=await import("./tree-sitter-wasm-parser-FT2KB66N.js");if(!e.isWasmAvailable()){$.info("tree-sitter WASM parsers disabled or unavailable. Using regex parsers (~97-98% accuracy). Set AQE_PARSER_REGEX_ONLY=0 or ensure web-tree-sitter is installed to enable WASM.");return}let t=e.createWasmParsers();for(let s of de){let n=t.get(s),r=this.parsers.get(s);n&&r&&this.parsers.set(s,new se(n,r))}$.info("tree-sitter WASM parsers available for: "+de.join(", "))}catch{$.info("tree-sitter WASM parser module not available. Using regex parsers for all languages.")}}register(e){this.parsers.set(e.language,e)}getParser(e){return this.parsers.get(e)}async parseFile(e,t,s){this._wasmInitPromise&&(await this._wasmInitPromise,this._wasmInitPromise=null);let n=this.parsers.get(s);if(n)return n.parseFile(e,t)}getSupportedLanguages(){return Array.from(this.parsers.keys())}supportsLanguage(e){return this.parsers.has(e)}},De=new ne;import*as M from"node:fs/promises";import*as C from"node:path";var xe=[/\.\./,/%2e%2e/i,/%252e%252e/i,/\.\.%2f/i,/%2f\.\./i,/\.\.%5c/i,/\.\.\\/,/%c0%ae/i,/%c0%2f/i,/%c1%9c/i,/\0/,/%00/i],ve=[/^\/etc\//i,/^\/proc\//i,/^\/sys\//i,/^\/dev\//i,/^\/root\//i,/^\/home\/.+\/\./i,/^[A-Z]:\\Windows/i,/^[A-Z]:\\System/i,/^[A-Z]:\\Users\\.+\\AppData/i],ie=class{name="path-traversal";getRiskLevel(){return"critical"}validate(e,t={}){let{basePath:s="",allowAbsolute:n=!1,allowedExtensions:r=[],deniedExtensions:o=[".exe",".bat",".cmd",".sh",".ps1",".dll",".so"],maxDepth:i=10,maxLength:a=4096}=t;if(e.length>a)return{valid:!1,error:`Path exceeds maximum length of ${a}`,riskLevel:"medium"};for(let g of xe)if(g.test(e))return{valid:!1,error:"Path traversal attempt detected",riskLevel:"critical"};if(!n&&(e.startsWith("/")||/^[A-Z]:/i.test(e)))return{valid:!1,error:"Absolute paths are not allowed",riskLevel:"high"};for(let g of ve)if(g.test(e))return{valid:!1,error:"Access to system paths is not allowed",riskLevel:"critical"};let c=this.normalizePath(e);if(c.includes(".."))return{valid:!1,error:"Path traversal detected after normalization",riskLevel:"critical"};if(c.split("/").filter(Boolean).length>i)return{valid:!1,error:`Path depth exceeds maximum of ${i}`,riskLevel:"low"};let d=this.getExtension(c);if(d){let g=`.${d.toLowerCase()}`,f=d.toLowerCase();if(o.length>0&&o.some(y=>y.toLowerCase()===g||y.toLowerCase()===f))return{valid:!1,error:`File extension '${d}' is not allowed`,riskLevel:"high"};if(r.length>0&&!r.some(y=>y.toLowerCase()===g||y.toLowerCase()===f))return{valid:!1,error:`File extension '${d}' is not in allowed list`,riskLevel:"medium"}}let u=s?this.joinPathsAbsolute(s,c):c,m=s.startsWith("/")?`/${this.normalizePath(s)}`:this.normalizePath(s);return s&&!u.startsWith(m)?{valid:!1,error:"Path escapes base directory",riskLevel:"critical"}:{valid:!0,normalizedPath:u,riskLevel:"none"}}normalizePath(e){let t=e.replace(/\\/g,"/");t=t.replace(/\/+/g,"/");let s=t.split("/"),n=[];for(let r of s)r==="."||r===""||(r===".."?n.length>0&&n[n.length-1]!==".."&&n.pop():n.push(r));return n.join("/")}joinPaths(...e){return e.length===0?"":e.map(t=>t.replace(/^\/+/,"").replace(/\/+$/,"")).filter(Boolean).join("/")}joinPathsAbsolute(...e){if(e.length===0)return"";let t=e[0].startsWith("/"),s=e.map(n=>{for(;n.startsWith("/");)n=n.slice(1);for(;n.endsWith("/");)n=n.slice(0,-1);return n}).filter(Boolean).join("/");return t?`/${s}`:s}getExtension(e){let t=e.match(/\.([^./\\]+)$/);return t?t[1]:null}},Ee=new ie,pe=(h,e)=>Ee.validate(h,e);le();var A=class extends Error{constructor(t,s,n,r){super(t);this.filePath=s;this.code=n;this.cause=r;this.name="FileReadError"}},z=class extends Error{constructor(t,s,n){super(t);this.filePath=s;this.cause=n;this.name="JsonParseError"}},T=class extends Error{constructor(t,s,n){super(`Path traversal detected: ${s.join(", ")}`);this.requestedPath=t;this.issues=s;this.riskLevel=n;this.name="PathTraversalError"}},ae=class{constructor(e,t){this.maxSize=e;this.ttlMs=t}cache=new Map;accessOrder=[];get(e){let t=this.cache.get(e);if(t){if(Date.now()-t.timestamp>this.ttlMs){this.delete(e);return}return this.updateAccessOrder(e),t.value}}set(e,t,s){for(this.cache.has(e)&&this.delete(e);this.cache.size>=this.maxSize&&this.accessOrder.length>0;){let n=this.accessOrder.shift();n&&this.cache.delete(n)}this.cache.set(e,{value:t,timestamp:Date.now(),size:s}),this.accessOrder.push(e)}delete(e){let t=this.cache.delete(e);if(t){let s=this.accessOrder.indexOf(e);s>-1&&this.accessOrder.splice(s,1)}return t}clear(){this.cache.clear(),this.accessOrder=[]}get size(){return this.cache.size}get totalBytes(){let e=0;return this.cache.forEach(t=>{e+=t.size}),e}updateAccessOrder(e){let t=this.accessOrder.indexOf(e);t>-1&&(this.accessOrder.splice(t,1),this.accessOrder.push(e))}prune(){let e=Date.now(),t=0,s=[];return this.cache.forEach((n,r)=>{e-n.timestamp>this.ttlMs&&s.push(r)}),s.forEach(n=>{this.delete(n),t++}),t}};function Ie(h){let e="",t=0;for(;t<h.length;){let s=h[t],n=h[t+1];s==="*"&&n==="*"?h[t+2]==="/"?(e+="(?:.*/)?",t+=3):(e+=".*",t+=2):s==="*"?(e+="[^/]*",t++):s==="?"?(e+="[^/]",t++):".+^${}()|[]\\".includes(s)?(e+="\\"+s,t++):(e+=s,t++)}return new RegExp("^"+e+"$")}async function ue(h,e,t,s){try{let n=await M.readdir(h,{withFileTypes:!0});for(let r of n){let o=C.join(h,r.name),i=C.relative(s,o);if(r.isDirectory())r.name!=="node_modules"&&!r.name.startsWith(".")&&await ue(o,e,t,s);else if(r.isFile()){let a=i.replace(/\\/g,"/");e.test(a)&&t.push(o)}}}catch(n){console.debug("[FileReader] Directory read error:",n instanceof Error?n.message:n)}}var k=class{basePath;cache;enableCache;stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:0,cacheEntries:0};constructor(e={}){this.basePath=e.basePath??process.cwd(),this.enableCache=e.enableCache??!0,this.cache=new ae(e.maxCacheSize??100,e.cacheTtlMs??300*1e3)}resolvePath(e){let t=C.isAbsolute(e),s=pe(e,{basePath:t?"":this.basePath,allowAbsolute:!0,deniedExtensions:[".exe",".bat",".cmd",".ps1",".dll",".so"]});if(!s.valid)throw new T(e,[s.error||"Path validation failed"],s.riskLevel);if(t&&this.basePath){let n=C.resolve(this.basePath),r=C.resolve(e);if(!r.startsWith(n))throw new T(e,["Path escapes base directory"],"critical");return r}return s.normalizedPath?s.normalizedPath:t?e:C.resolve(this.basePath,e)}async readFile(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}if(this.stats.totalReads++,this.enableCache){let s=this.cache.get(t);if(s!==void 0)return this.stats.cacheHits++,this.updateCacheStats(),w(s);this.stats.cacheMisses++}try{let s=await M.readFile(t,"utf-8");return this.enableCache&&(this.cache.set(t,s,Buffer.byteLength(s,"utf-8")),this.updateCacheStats()),w(s)}catch(s){let n=s,r;switch(n.code){case"ENOENT":r="File not found: "+t;break;case"EACCES":r="Permission denied: "+t;break;case"EISDIR":r="Path is a directory: "+t;break;default:r="Failed to read file: "+t}return L(new A(r,t,n.code,n))}}async readJSON(e){let t=await this.readFile(e);if(!t.success)return t;try{let s=N(t.value);return w(s)}catch(s){let n=s,r=e;try{r=this.resolvePath(e)}catch{}return L(new z("Invalid JSON in file: "+r+" - "+n.message,r,n))}}async fileExists(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}try{return await M.access(t,M.constants.F_OK),w(!0)}catch(s){let n=s;return n.code==="ENOENT"?w(!1):L(new A("Cannot check file existence: "+t,t,n.code,n))}}async listFiles(e,t){let s;try{s=t?this.resolvePath(t):this.basePath}catch(n){if(n instanceof T)return L(n);throw n}try{if(!(await M.stat(s)).isDirectory())return L(new A("Base path is not a directory: "+s,s,"ENOTDIR"));let r=Ie(e),o=[];return await ue(s,r,o,s),o.sort(),w(o)}catch(n){let r=n;return L(new A("Failed to list files in: "+s,s,r.code,r))}}invalidateCache(e){let t=this.resolvePath(e);this.cache.delete(t),this.updateCacheStats()}clearCache(){this.cache.clear(),this.updateCacheStats()}pruneCache(){let e=this.cache.prune();return this.updateCacheStats(),e}getStats(){return{...this.stats}}resetStats(){this.stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:this.cache.totalBytes,cacheEntries:this.cache.size}}updateCacheStats(){this.stats.cacheSize=this.cache.totalBytes,this.stats.cacheEntries=this.cache.size}};V();var v={MODEL:"all-MiniLM-L6-v2",DIMENSIONS:384,CONTEXT_WINDOW:8192,BATCH_SIZE:100,MAX_RETRIES:3,RETRY_DELAY_MS:1e3,TIMEOUT_MS:3e4,DEFAULT_OLLAMA_URL:"http://localhost:11434"};var K=class{baseUrl;maxRetries;retryDelayMs;timeoutMs;constructor(e=v.DEFAULT_OLLAMA_URL,t=v.MAX_RETRIES,s=v.RETRY_DELAY_MS,n=v.TIMEOUT_MS){this.baseUrl=e.replace(/\/$/,""),this.maxRetries=t,this.retryDelayMs=s,this.timeoutMs=n}async healthCheck(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);if(!e.ok)return!1;let t=await e.json();return t.models?t.models.some(s=>s.name?.startsWith(v.MODEL)||s.model?.startsWith(v.MODEL)):!1}catch{return!1}}async generateEmbedding(e){let t={model:v.MODEL,prompt:e},s=null;for(let n=0;n<this.maxRetries;n++)try{let r=await this.fetchWithTimeout(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},this.timeoutMs);if(!r.ok){let i=await r.text();throw new Error(`Ollama API error (${r.status}): ${i}`)}let o=await r.json();if(o.embedding.length!==v.DIMENSIONS)throw new Error(`Invalid embedding dimensions: expected ${v.DIMENSIONS}, got ${o.embedding.length}`);return o.embedding}catch(r){if(s=D(r),s.message.includes("Invalid embedding dimensions"))throw s;if(n<this.maxRetries-1){let o=this.retryDelayMs*Math.pow(2,n);await this.sleep(o)}}throw new Error(`Failed to generate embedding after ${this.maxRetries} attempts: ${s?.message}`)}async fetchWithTimeout(e,t,s){let n=new AbortController,r=setTimeout(()=>n.abort(),s);try{return await fetch(e,{...t,signal:n.signal})}finally{clearTimeout(r)}}sleep(e){return new Promise(t=>setTimeout(t,e))}async getServerInfo(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);return e.ok?await e.json():null}catch{return null}}async ensureModelAvailable(){if(!await this.healthCheck())throw new Error(`Ollama model '${v.MODEL}' is not available. Please run: ollama pull ${v.MODEL}`)}};import{createHash as Pe}from"crypto";var U=class{cache;maxSize;hits;misses;constructor(e=1e4){this.cache=new Map,this.maxSize=e,this.hits=0,this.misses=0}hashContent(e,t){return Pe("sha256").update(`${t}:${e}`).digest("hex")}get(e,t){let s=this.hashContent(e,t),n=this.cache.get(s);return n?(this.hits++,this.cache.delete(s),this.cache.set(s,n),n.embedding):(this.misses++,null)}set(e,t,s){let n=this.hashContent(e,t);if(this.cache.size>=this.maxSize&&!this.cache.has(n)){let o=this.cache.keys().next().value;o&&this.cache.delete(o)}let r={embedding:s,timestamp:Date.now(),model:t};this.cache.set(n,r)}has(e,t){let s=this.hashContent(e,t);return this.cache.has(s)}getStats(){let e=this.hits+this.misses,t=e>0?this.hits/e:0;return{size:this.cache.size,hitRate:t,hits:this.hits,misses:this.misses}}clear(){this.cache.clear(),this.hits=0,this.misses=0}evictOlderThan(e){let s=Date.now()-e,n=0;for(let[r,o]of this.cache.entries())o.timestamp<s&&(this.cache.delete(r),n++);return n}getMemoryUsageEstimate(){return this.cache.size*3172}export(){return Array.from(this.cache.entries()).map(([e,t])=>({key:e,entry:t}))}import(e){this.cache.clear();for(let{key:t,entry:s}of e)this.cache.size<this.maxSize&&this.cache.set(t,s)}};V();var _=class{client;cache;batchSize;enableFallback;ollamaAvailable=null;constructor(e={}){this.client=new K(e.ollamaBaseUrl),this.cache=e.cache??new U(e.maxCacheSize),this.batchSize=e.batchSize??v.BATCH_SIZE,this.enableFallback=e.enableFallback??!0}async embed(e){let t=this.cache.get(e,v.MODEL);if(t)return t;let s;if(await this.isOllamaAvailable())s=await this.client.generateEmbedding(e);else if(this.enableFallback)s=this.generatePseudoEmbedding(e);else throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);return this.cache.set(e,v.MODEL,s),s}formatForEmbedding(e){let t=[];e.language&&t.push(e.language),e.type&&t.push(e.type),e.name&&t.push(e.name);let s=t.length>0?`${t.join(" ")}: `:"",n=v.CONTEXT_WINDOW*4,r=e.content.trim();if(s.length+r.length>n){let o=n-s.length-3;r=r.substring(0,o)+"..."}return s+r}async embedBatch(e){let t=[];for(let s of e){let n=await this.embed(s);t.push(n)}return t}async embedCodeChunks(e,t){let s=Date.now(),n=[],r=0,o=0,i=await this.isOllamaAvailable();if(i)await this.client.ensureModelAvailable();else if(!this.enableFallback)throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);for(let c=0;c<e.length;c+=this.batchSize){let l=e.slice(c,Math.min(c+this.batchSize,e.length)),d=await this.processBatch(l,i);n.push(...d);for(let u of d)u.cached?r++:o++;if(t){let u=c+l.length,m=e.length,f=(Date.now()-s)/u,y=(m-u)*f;t({current:u,total:m,percentage:u/m*100,estimatedTimeRemainingMs:y})}}let a=Date.now()-s;return{results:n,stats:{totalChunks:e.length,cachedHits:r,computedNew:o,totalTimeMs:a,avgTimePerChunk:a/e.length}}}async processBatch(e,t){let s=[],n=e.map(async o=>{let i=this.formatForEmbedding(o),a=Date.now(),c=this.cache.get(i,v.MODEL);if(c)return{chunkId:o.id,embedding:c,model:v.MODEL,cached:!0,computeTimeMs:Date.now()-a};try{let l;return t?l=await this.client.generateEmbedding(i):l=this.generatePseudoEmbedding(i),this.cache.set(i,v.MODEL,l),{chunkId:o.id,embedding:l,model:t?v.MODEL:"pseudo-embedding",cached:!1,computeTimeMs:Date.now()-a}}catch(l){throw new Error(`Failed to generate embedding for chunk ${o.id}: ${j(l)}`)}}),r=await Promise.all(n);return s.push(...r),s}async isOllamaAvailable(){return this.ollamaAvailable!==null?this.ollamaAvailable:(this.ollamaAvailable=await this.client.healthCheck(),this.ollamaAvailable)}resetOllamaCheck(){this.ollamaAvailable=null}generatePseudoEmbedding(e){let t=new Array(v.DIMENSIONS).fill(0),s=e.split(/\s+|[^\w]+/).filter(o=>o.length>0);for(let o=0;o<s.length;o++){let i=s[o];for(let a=0;a<i.length&&a<t.length;a++)t[(o+a)%t.length]+=i.charCodeAt(a)/1e3}let n=[[/class\s+\w+/,0],[/function\s+\w+/,1],[/async\s+|await\s+|Promise/,2],[/interface\s+\w+/,3],[/export\s+/,4],[/import\s+/,5],[/try\s*{/,6],[/\.(map|filter|reduce)\(/,7]];for(let[o,i]of n)o.test(e)&&(t[i]+=.5);let r=Math.sqrt(t.reduce((o,i)=>o+i*i,0))||1;return t.map(o=>o/r)}clearCache(){this.cache.clear()}getCacheStats(){return this.cache.getStats()}async healthCheck(){return await this.client.healthCheck()}async getServerInfo(){return await this.client.getServerInfo()}getDimensions(){return v.DIMENSIONS}getConfig(){return{model:v.MODEL,dimensions:v.DIMENSIONS,contextWindow:v.CONTEXT_WINDOW,batchSize:this.batchSize,maxRetries:v.MAX_RETRIES,enableFallback:this.enableFallback}}};V();le();var we={maxNodes:1e5,maxEdgesPerNode:500,namespace:"code-intelligence:kg",enableVectorEmbeddings:!0,embeddingDimension:384,enableLLMExtraction:!0,llmModelTier:2,llmMaxTokens:2048},me=oe.create("code-intelligence/knowledge-graph"),he=class{config;memory;nodeCache=new Map;edgeIndex=new Map;tsParser;fileReader;embedder;llmRouter;constructor(e,t={}){this.config={...we,...t},this.isKnowledgeGraphDependencies(e)?(this.memory=e.memory,this.llmRouter=e.llmRouter):(this.memory=e,this.llmRouter=void 0),this.tsParser=new F,this.fileReader=new k,this.embedder=new _({enableFallback:!0})}isKnowledgeGraphDependencies(e){return e.memory!==void 0}async index(e){let t=Date.now(),s=[],n=0,r=0;try{let{paths:o,incremental:i=!1,includeTests:a=!0,languages:c}=e;i||await this.clear();for(let d of o)try{if(c&&c.length>0){let m=this.getFileExtension(d);if(!this.matchesLanguage(m,c))continue}if(!a&&this.isTestFile(d))continue;let u=await this.indexFile(d);n+=u.nodes,r+=u.edges}catch(u){s.push({file:d,error:j(u)})}let l=Date.now()-t;return await this.storeIndexMetadata({filesIndexed:o.length-s.length,nodesCreated:n,edgesCreated:r,duration:l,indexedAt:new Date().toISOString()}),w({filesIndexed:o.length-s.length,nodesCreated:n,edgesCreated:r,duration:l,errors:s})}catch(o){return L(D(o))}}async query(e){try{let{query:t,type:s,limit:n=100}=e;return s==="cypher"?this.executeCypherQuery(t,n):this.executeNaturalLanguageQuery(t,n)}catch(t){return L(D(t))}}async mapDependencies(e){try{let{files:t,direction:s,depth:n=3}=e,r=[],o=[],i=new Set,a=[];for(let l of t)await this.traverseDependencies(l,s,n,i,r,o,[],a);let c=this.calculateDependencyMetrics(r,o);return w({nodes:r,edges:o,cycles:a,metrics:c})}catch(t){return L(D(t))}}async getNode(e){if(this.nodeCache.has(e))return this.nodeCache.get(e);let t=`${this.config.namespace}:node:${e}`,s=await this.memory.get(t);return s&&this.nodeCache.set(e,s),s}async getEdges(e,t){let s=[],n=this.edgeIndex.get(e);if(n)return this.filterEdgesByDirection(n,e,t);let r=`${this.config.namespace}:edge:*`,o=await this.memory.search(r,this.config.maxEdgesPerNode*2);for(let i of o){let a=await this.memory.get(i);a&&(t!=="outgoing"&&a.target===e||t!=="incoming"&&a.source===e)&&s.push(a)}return s}async clear(){this.nodeCache.clear(),this.edgeIndex.clear()}isLLMExtractionAvailable(){return this.config.enableLLMExtraction===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){case 1:return"claude-3-5-haiku-20241022";case 2:return"claude-sonnet-4-20250514";case 3:return"claude-sonnet-4-20250514";case 4:return"claude-opus-4-5-20251101";default:return"claude-sonnet-4-20250514"}}async extractRelationshipsWithLLM(e,t){if(!this.llmRouter)return{semanticRelationships:[],designPatterns:[],architecturalBoundaries:[],dependencyImpacts:[]};try{let s=this.buildRelationshipExtractionPrompt(e,t),n=this.getModelForTier(this.config.llmModelTier??2),r=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software architect analyzing code structure. Extract:
24
+ 1. Semantic relationships between code entities (inheritance, composition, dependency, collaboration)
25
+ 2. Design patterns used (Factory, Singleton, Observer, Strategy, etc.)
26
+ 3. Architectural boundaries (layers, modules, domains)
27
+ 4. Dependency impact analysis (which changes would affect which components)
28
+
29
+ Return a JSON object with:
30
+ {
31
+ "semanticRelationships": [{"source": "...", "target": "...", "type": "...", "description": "..."}],
32
+ "designPatterns": [{"pattern": "...", "participants": ["..."], "location": "...", "confidence": 0.0-1.0}],
33
+ "architecturalBoundaries": [{"name": "...", "type": "layer|module|domain", "entities": ["..."]}],
34
+ "dependencyImpacts": [{"entity": "...", "impactedBy": ["..."], "impacts": ["..."], "severity": "low|medium|high"}]
35
+ }
36
+
37
+ Be precise and only report high-confidence findings.`},{role:"user",content:s}],model:n,maxTokens:this.config.llmMaxTokens??2048,temperature:.2});return r.content?this.parseLLMRelationshipResponse(r.content):{semanticRelationships:[],designPatterns:[],architecturalBoundaries:[],dependencyImpacts:[]}}catch{return me.warn("LLM relationship extraction failed:"),{semanticRelationships:[],designPatterns:[],architecturalBoundaries:[],dependencyImpacts:[]}}}buildRelationshipExtractionPrompt(e,t){let s=`## Code to Analyze:
38
+ \`\`\`typescript
39
+ ${e}
40
+ \`\`\`
41
+
42
+ `;if(t.length>0){s+=`## Already Identified Entities:
43
+ `;for(let n of t)s+=`- ${n.type}: ${n.name} (line ${n.line}, ${n.visibility})
44
+ `;s+=`
45
+ `}return s+=`## Analysis Requirements:
46
+ `,s+=`1. Identify semantic relationships between the entities above
47
+ `,s+=`2. Detect any design patterns in use
48
+ `,s+=`3. Identify architectural boundaries or layers
49
+ `,s+=`4. Analyze which entities would be impacted by changes to others
50
+ `,s}parseLLMRelationshipResponse(e){try{let t=e.match(/\{[\s\S]*\}/);if(t){let s=N(t[0]);return{semanticRelationships:Array.isArray(s.semanticRelationships)?s.semanticRelationships:[],designPatterns:Array.isArray(s.designPatterns)?s.designPatterns:[],architecturalBoundaries:Array.isArray(s.architecturalBoundaries)?s.architecturalBoundaries:[],dependencyImpacts:Array.isArray(s.dependencyImpacts)?s.dependencyImpacts:[]}}}catch{}return{semanticRelationships:[],designPatterns:[],architecturalBoundaries:[],dependencyImpacts:[]}}async enhanceQueryWithLLM(e,t){if(!this.llmRouter||t.length===0)return{enhancedResults:t,insights:[]};try{let s=this.getModelForTier(this.config.llmModelTier??2),n=await this.llmRouter.chat({messages:[{role:"system",content:`You are a code intelligence assistant. Given a query and search results from a knowledge graph, provide:
51
+ 1. Ranking of results by relevance to the query
52
+ 2. Key insights about how the results relate to the query
53
+ 3. Suggestions for related code to explore
54
+
55
+ Return JSON: { "rankedIds": ["id1", "id2", ...], "insights": ["insight1", "insight2", ...] }`},{role:"user",content:`Query: "${e}"
56
+
57
+ Results:
58
+ ${JSON.stringify(t.map(r=>({id:r.id,label:r.label,properties:r.properties})),null,2)}`}],model:s,maxTokens:1024,temperature:.3});if(n.content)try{let r=n.content.match(/\{[\s\S]*\}/);if(r){let o=N(r[0]),i=o.rankedIds||[],a=o.insights||[],c=new Map(t.map(d=>[d.id,d])),l=[];for(let d of i){let u=c.get(d);u&&(l.push(u),c.delete(d))}return l.push(...Array.from(c.values())),{enhancedResults:l,insights:a}}}catch{}return{enhancedResults:t,insights:[]}}catch{return me.warn("LLM query enhancement failed:"),{enhancedResults:t,insights:[]}}}async indexFile(e){let t=0,s=0,n=await this.createFileNode(e);t++;let r=await this.extractEntities(e);for(let i of r){let a=await this.createEntityNode(i,e);t++,await this.createEdge(n.id,a.id,"contains"),s++}let o=await this.extractImports(e);for(let i of o){let a=this.pathToNodeId(i);await this.createEdge(n.id,a,"import"),s++}if(this.isLLMExtractionAvailable()){let i=await this.fileReader.readFile(e);if(i.success){let a=await this.extractRelationshipsWithLLM(i.value,r);s+=await this.storeLLMRelationships(n.id,a)}}return{nodes:t,edges:s}}async storeLLMRelationships(e,t){let s=0;for(let r of t.semanticRelationships){let o=`${e}:*:${r.source}`,i=`${e}:*:${r.target}`;await this.createEdge(o,i,r.type),s++}let n=this.nodeCache.get(e);return n&&(t.designPatterns.length>0&&(n.properties.designPatterns=t.designPatterns),t.architecturalBoundaries.length>0&&(n.properties.architecturalBoundaries=t.architecturalBoundaries),t.dependencyImpacts.length>0&&(n.properties.dependencyImpacts=t.dependencyImpacts),this.nodeCache.set(e,n)),s}async createFileNode(e){let s={id:this.pathToNodeId(e),label:"File",properties:{path:e,name:this.getFileName(e),extension:this.getFileExtension(e),type:this.getFileType(e)}};return await this.storeNode(s),s}async createEntityNode(e,t){let s=`${this.pathToNodeId(t)}:${e.type}:${e.name}`,n={id:s,label:e.type,properties:{name:e.name,file:t,line:e.line,visibility:e.visibility,async:e.isAsync}};if(await this.storeNode(n),this.config.enableVectorEmbeddings){let r=await this.generateEmbedding(e);await this.memory.storeVector(`${this.config.namespace}:node:${s}`,r,{nodeId:s,type:e.type,name:e.name})}return n}async createEdge(e,t,s){let n=`${e}--${s}-->${t}`,r={source:e,target:t,type:s},o=this.edgeIndex.get(e)||[];return o.push(r),this.edgeIndex.set(e,o),r}async storeNode(e){if(this.nodeCache.size>=this.config.maxNodes){let t=this.nodeCache.keys().next().value;t&&(this.nodeCache.delete(t),this.edgeIndex.delete(t))}this.nodeCache.set(e.id,e)}async extractEntities(e){let t=this.getFileExtension(e),s=[];if(["ts","tsx","js","jsx"].includes(t)){let n=await this.fileReader.readFile(e);if(n.success){let r=this.getFileName(e),o=this.tsParser.parseFile(r,n.value),i=this.tsParser.extractFunctions(o);for(let l of i)s.push({type:"function",name:l.name,line:l.startLine,visibility:"public",isAsync:l.isAsync});let a=this.tsParser.extractClasses(o);for(let l of a){s.push({type:"class",name:l.name,line:l.startLine,visibility:"public",isAsync:!1});for(let d of l.methods)s.push({type:"function",name:`${l.name}.${d.name}`,line:d.startLine,visibility:d.visibility,isAsync:d.isAsync})}let c=this.tsParser.extractInterfaces(o);for(let l of c)s.push({type:"interface",name:l.name,line:l.startLine,visibility:"public",isAsync:!1});s.length===0&&s.push({type:"module",name:r.replace(/\.[^.]+$/,""),line:1,visibility:"public",isAsync:!1})}else s.push({type:"module",name:this.getFileName(e).replace(/\.[^.]+$/,""),line:1,visibility:"public",isAsync:!1})}else if(t==="py"){let n=await this.fileReader.readFile(e);if(n.success){let o=n.value.split(`
59
+ `),i=/^class\s+(\w+)\s*(?:\([^)]*\))?\s*:/,a=/^(async\s+)?def\s+(\w+)\s*\(/,c=null,l=0;for(let d=0;d<o.length;d++){let u=o[d],m=d+1,g=u.trimStart(),f=u.length-g.length;c&&f<=l&&(c=null);let x=g.match(i);if(x){let b=x[1];s.push({type:"class",name:b,line:m,visibility:b.startsWith("_")?"private":"public",isAsync:!1}),c=b,l=f;continue}let y=g.match(a);if(y){let b=!!y[1],P=y[2],ge=c!==null&&f>l,B="public";P.startsWith("__")&&!P.endsWith("__")?B="private":P.startsWith("_")&&(B="protected"),s.push({type:"function",name:ge?`${c}.${P}`:P,line:m,visibility:B,isAsync:b})}}s.length===0&&s.push({type:"module",name:this.getFileName(e).replace(".py",""),line:1,visibility:"public",isAsync:!1})}else s.push({type:"module",name:this.getFileName(e).replace(".py",""),line:1,visibility:"public",isAsync:!1})}return s}async extractImports(e){let t=this.getFileExtension(e),s=[];if(["ts","tsx","js","jsx"].includes(t)){let n=await this.fileReader.readFile(e);if(n.success){let r=this.getFileName(e),o=this.tsParser.parseFile(r,n.value),i=this.tsParser.extractImports(o);for(let a of i)a.module.startsWith("node:")||s.push(a.module)}}return s}async executeCypherQuery(e,t){let s=[],n=[],r=new Map,o=/MATCH\s+\((\w+):(\w+)\)\s*-\[(\w+)?:?(\w+)?\]\s*->\s*\((\w+):(\w+)\)/i.exec(e);if(o){let[,a,c,,l,d,u]=o,m=await this.findNodesByLabel(c,t*2);r.set(a,m);for(let g of m.slice(0,t)){let f=await this.getEdges(g.id,"outgoing");for(let x of f){if(l&&x.type!==l)continue;let y=await this.getNode(x.target);y&&y.label===u&&(s.some(b=>b.id===g.id)||s.push(g),s.some(b=>b.id===y.id)||s.push(y),n.some(b=>b.source===x.source&&b.target===x.target&&b.type===x.type)||n.push(x))}}d&&r.set(d,s.filter(g=>g.label===u))}else{let a=/MATCH\s+\((\w+):(\w+)\)/i.exec(e);if(a){let[,c,l]=a,d=await this.findNodesByLabel(l,t);r.set(c,d),s.push(...d)}}let i=/WHERE\s+(\w+)\.(\w+)\s*=\s*['"]?([^'")\s]+)['"]?/i.exec(e);if(i){let[,a,c,l]=i,u=(r.get(a)||s).filter(f=>{let x=f.properties[c];return x!==void 0&&String(x)===l});s.length=0,s.push(...u.slice(0,t));let m=new Set(s.map(f=>f.id)),g=n.filter(f=>m.has(f.source)&&m.has(f.target));n.length=0,n.push(...g)}return w({nodes:s.slice(0,t),edges:n,metadata:{query:e,type:"cypher",resultCount:s.length,edgeCount:n.length}})}async findNodesByLabel(e,t){let s=[],n=`${this.config.namespace}:node:*`,r=await this.memory.search(n,t*2);for(let o of r){let i=await this.memory.get(o);if(i&&i.label===e&&(s.push(i),s.length>=t))break}return s}async executeNaturalLanguageQuery(e,t){if(this.config.enableVectorEmbeddings){let i=await this.generateQueryEmbedding(e),a=await this.memory.vectorSearch(i,t),c=[];for(let l of a){let d=l.metadata?.nodeId;if(d){let u=await this.getNode(d);u&&c.push(u)}}return w({nodes:c,edges:[],metadata:{query:e,type:"natural-language",resultCount:c.length,searchScores:a.map(l=>l.score)}})}let s=e.toLowerCase().split(/\s+/),n=`${this.config.namespace}:node:*`,r=await this.memory.search(n,t*3),o=[];for(let i of r){let a=await this.memory.get(i);if(a){let c=JSON.stringify(a.properties).toLowerCase();if(s.some(l=>c.includes(l))&&(o.push(a),o.length>=t))break}}return w({nodes:o,edges:[],metadata:{query:e,type:"keyword",resultCount:o.length}})}async traverseDependencies(e,t,s,n,r,o,i,a){if(s<=0||n.has(e)){let m=i.indexOf(e);m>=0&&a.push([...i.slice(m),e]);return}n.add(e),i.push(e);let c=this.pathToNodeId(e),l=await this.getEdges(c,t),d=l.filter(m=>m.target===c).length,u=l.filter(m=>m.source===c).length;r.push({id:c,path:e,type:"file",inDegree:d,outDegree:u});for(let m of l){let g={source:m.source,target:m.target,type:m.type};o.some(x=>x.source===g.source&&x.target===g.target)||o.push(g);let f=m.source===c?this.nodeIdToPath(m.target):this.nodeIdToPath(m.source);f&&await this.traverseDependencies(f,t,s-1,n,r,o,i,a)}i.pop()}calculateDependencyMetrics(e,t){let s=e.length,n=t.length,r=s>0?e.reduce((a,c)=>a+c.inDegree+c.outDegree,0)/s:0,o=0;if(e.length>0){let a=new Map;for(let l of t){let d=a.get(l.source)||[];d.push(l.target),a.set(l.source,d)}let c=new Map;for(let l of e)c.has(l.id)||this.bfsDepth(l.id,a,c),o=Math.max(o,c.get(l.id)||0)}let i=n-s+2;return{totalNodes:s,totalEdges:n,avgDegree:Math.round(r*100)/100,maxDepth:o,cyclomaticComplexity:Math.max(1,i)}}bfsDepth(e,t,s){let n=[{id:e,depth:0}];for(;n.length>0;){let r=n.shift(),o=s.get(r.id)??-1;r.depth>o&&s.set(r.id,r.depth);let i=t.get(r.id)||[];for(let a of i)(!s.has(a)||(s.get(a)??0)<r.depth+1)&&n.push({id:a,depth:r.depth+1})}}filterEdgesByDirection(e,t,s){return e.filter(n=>s==="incoming"?n.target===t:s==="outgoing"?n.source===t:!0)}async storeIndexMetadata(e){}async generateEmbedding(e){let t=`${e.type} ${e.name} ${e.visibility}${e.isAsync?" async":""}`;try{return await this.embedder.embed(t)}catch{return this.fallbackEmbedding(t)}}async generateQueryEmbedding(e){try{return await this.embedder.embed(e)}catch{return this.fallbackEmbedding(e)}}fallbackEmbedding(e){let t=new Array(this.config.embeddingDimension).fill(0),s=e.toLowerCase().split(/\s+/);for(let r=0;r<s.length;r++){let o=s[r];for(let i=0;i<o.length&&i<t.length;i++)t[(r+i)%t.length]+=o.charCodeAt(i)/1e3}let n=Math.sqrt(t.reduce((r,o)=>r+o*o,0))||1;return t.map(r=>r/n)}pathToNodeId(e){return e.replace(/[/\\]/g,":").replace(/\./g,"_")}nodeIdToPath(e){let t=e.replace(/:/g,"/").replace(/_(?=[^_]*$)/,".");return t.includes("/")?t:null}getFileName(e){return e.split(/[/\\]/).pop()||e}getFileExtension(e){let s=this.getFileName(e).split(".");return s.length>1?s.pop():""}getFileType(e){let t=this.getFileExtension(e);return{ts:"typescript",tsx:"typescript-react",js:"javascript",jsx:"javascript-react",py:"python",go:"go",java:"java",rs:"rust",rb:"ruby",cs:"csharp",swift:"swift"}[t]||"unknown"}matchesLanguage(e,t){let s={typescript:["ts","tsx"],javascript:["js","jsx"],python:["py"],go:["go"],java:["java"],rust:["rs"],csharp:["cs"],swift:["swift"]};return t.some(n=>(s[n.toLowerCase()]||[n]).includes(e))}isTestFile(e){return[/\.test\.[tj]sx?$/,/\.spec\.[tj]sx?$/,/_test\.[tj]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/].some(s=>s.test(e))}destroy(){this.nodeCache.clear(),this.edgeIndex.clear()}};export{p as a,De as b,v as c,_ as d,F as e,k as f,he as g};
@@ -0,0 +1,2 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import r from"chalk";function s(e){switch(e){case"healthy":case"completed":return r.green(e);case"idle":return r.cyan(e);case"degraded":case"running":return r.yellow(e);case"unhealthy":case"failed":return r.red(e);default:return r.gray(e)}}function a(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:e<36e5?`${(e/6e4).toFixed(1)}m`:`${(e/36e5).toFixed(1)}h`}function l(e){let t=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4),o=Math.floor(e%6e4/1e3);return`${t}h ${n}m ${o}s`}export{s as a,a as b,l as c};
@@ -0,0 +1,30 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ var i={domain:"test-generation",bestPractices:["Follow Arrange-Act-Assert (AAA) pattern for clear test structure","One logical assertion per test - test one behavior at a time","Use descriptive test names: should_returnValue_when_condition","Mock external dependencies to isolate unit under test","Test edge cases and boundary conditions, not just happy paths","Keep tests deterministic - avoid time-dependent assertions","Use test data builders or factories for complex objects","Prefer integration tests for workflows, unit tests for logic","Maintain test independence - no shared mutable state between tests","Write failing test first (TDD Red) before implementation"],antiPatterns:[{name:"God Test",description:"A single test that verifies too many behaviors",reason:"Hard to diagnose failures, brittle, slow to run",alternative:"Split into focused tests, each verifying one behavior",detection:"expect.*expect.*expect.*expect.*expect"},{name:"Mystery Guest",description:"Test relies on external data files or state not visible in test",reason:"Tests are hard to understand and maintain",alternative:"Make test data explicit within the test or use fixtures"},{name:"Eager Test",description:"Test that verifies more than needed for the current behavior",reason:"Creates unnecessary coupling, breaks easily",alternative:"Only assert what is necessary for this specific test case"},{name:"Flaky Assertion",description:"Assertions that depend on timing, order, or external state",reason:"Creates unreliable test suite, erodes trust",alternative:"Use deterministic assertions, mock time/random",detection:"setTimeout|Date\\.now|Math\\.random"},{name:"Test Code Duplication",description:"Same setup or assertion code repeated across tests",reason:"Maintenance burden, inconsistency risk",alternative:"Extract to beforeEach, helpers, or fixtures"}],frameworkGuidance:{jest:["Use describe blocks to group related tests","Prefer toEqual for deep equality, toBe for primitives","Use jest.mock() at module level for consistent mocking","Use jest.spyOn for partial mocking of objects","Enable --coverage to track test coverage"],vitest:["Use vi.mock() for module mocking","Prefer vi.fn() over jest.fn() syntax","Use vitest/ui for interactive test debugging","Enable browser mode for component tests","Use inline snapshots for small expected values"],mocha:["Use beforeEach/afterEach for setup/teardown","Combine with chai for assertions","Use sinon for spies, stubs, and mocks","Set appropriate timeouts for async tests"],pytest:["Use fixtures for reusable test setup","Use parametrize for data-driven tests","Use conftest.py for shared fixtures","Use pytest.raises for exception testing","Use pytest-cov for coverage reporting"],junit:["Use @BeforeEach and @AfterEach for setup/teardown","Use @DisplayName for readable test names","Use @ParameterizedTest for data-driven tests","Use Mockito for mocking dependencies"],testng:["Use @BeforeMethod and @AfterMethod appropriately","Use @DataProvider for parameterized tests","Configure test groups for selective execution"],playwright:["Use page.locator() for resilient element selection","Use expect(locator) for auto-waiting assertions","Use page.waitForLoadState for navigation","Use test.describe for grouping tests","Use fixtures for reusable browser contexts"],cypress:["Use cy.intercept() for API mocking","Avoid conditional testing - use deterministic state","Use data-cy attributes for stable selectors","Use cy.within() for scoped queries","Prefer cy.contains() for text-based selection"],selenium:["Use explicit waits over implicit waits","Use Page Object Model for maintainability","Handle stale element references with retry logic","Clean up browser state between tests"]},languageGuidance:{typescript:["Use type assertions in tests for better IDE support","Create typed test fixtures and builders","Use satisfies operator for test data validation","Mock types with ts-mockito or typed mocking libs"],javascript:["Use JSDoc comments for test documentation","Consider TypeScript for larger test suites","Use ESLint with testing plugins"],python:["Use type hints in test functions","Use dataclasses for test data","Follow PEP 8 naming: test_should_do_something"],java:["Use AssertJ for fluent assertions","Use Lombok for test data classes","Follow naming: shouldDoSomething_whenCondition"],go:["Use table-driven tests for multiple cases","Use testify for assertions and mocking","Place tests in _test.go files"],rust:["Use #[test] attribute for test functions","Use assert!, assert_eq!, assert_ne! macros","Place unit tests in same file with #[cfg(test)]"],csharp:["Use xUnit or NUnit for testing","Use FluentAssertions for readable assertions","Use Moq for mocking interfaces"],kotlin:["Use kotest for BDD-style testing","Use MockK for Kotlin-first mocking","Use data classes for test fixtures"]},examples:[{title:"Unit Test Template (TypeScript + Vitest)",description:"Standard AAA pattern for unit tests",content:`describe('UserService', () => {
3
+ describe('createUser', () => {
4
+ it('should create user with valid data', async () => {
5
+ // Arrange
6
+ const userData = { name: 'John', email: 'john@example.com' };
7
+ const mockRepo = { save: vi.fn().mockResolvedValue({ id: '1', ...userData }) };
8
+ const service = new UserService(mockRepo);
9
+
10
+ // Act
11
+ const result = await service.createUser(userData);
12
+
13
+ // Assert
14
+ expect(result.id).toBeDefined();
15
+ expect(result.name).toBe(userData.name);
16
+ expect(mockRepo.save).toHaveBeenCalledWith(userData);
17
+ });
18
+
19
+ it('should throw when email is invalid', async () => {
20
+ // Arrange
21
+ const userData = { name: 'John', email: 'invalid' };
22
+ const service = new UserService(mockRepo);
23
+
24
+ // Act & Assert
25
+ await expect(service.createUser(userData))
26
+ .rejects.toThrow('Invalid email');
27
+ });
28
+ });
29
+ });`,context:{language:"typescript",framework:"vitest"}}]},c={domain:"coverage-analysis",bestPractices:["Focus on risk-weighted coverage, not just percentage","Prioritize untested critical paths and business logic","Use mutation testing to validate test quality beyond line coverage","Target branch coverage over statement coverage","Use O(log n) sublinear algorithms for large codebases","Track coverage trends over time, not just snapshots","Exclude generated code, config, and third-party from metrics","Set realistic targets: 80% coverage for critical code","Identify coverage gaps by risk, not just location","Use coverage as a guide, not a goal"],antiPatterns:[{name:"Coverage Chasing",description:"Writing tests just to increase coverage percentage",reason:"Low-quality tests that exercise code without verifying behavior",alternative:"Write tests that verify behavior, measure mutation score"},{name:"Ignoring Branches",description:"Only tracking line coverage, missing conditional branches",reason:"Miss critical edge cases in conditionals",alternative:"Track branch coverage and ensure all paths tested"},{name:"Coverage Ratchet Too Tight",description:"Requiring 100% coverage on all code",reason:"Leads to test pollution, hard to maintain",alternative:"Risk-based coverage targets, allow exceptions"}],frameworkGuidance:{jest:["Use --coverage flag","Configure coverageThreshold in jest.config"],vitest:["Use --coverage flag","Use c8 or istanbul provider"],mocha:["Use nyc (Istanbul) for coverage"],pytest:["Use pytest-cov plugin","Use --cov flag"],junit:["Use JaCoCo for coverage reporting"],testng:["Use JaCoCo with TestNG"],playwright:["Use coverage API for browser code coverage"],cypress:["Use @cypress/code-coverage plugin"],selenium:["Integrate with build tool coverage (Maven/Gradle)"]},languageGuidance:{typescript:["Use c8 or istanbul for Node.js coverage"],javascript:["Use nyc or c8 for coverage"],python:["Use coverage.py or pytest-cov"],java:["Use JaCoCo or Cobertura"],go:["Use go test -cover","Use go tool cover for reports"],rust:["Use cargo-tarpaulin or grcov"],csharp:["Use coverlet or OpenCover"],kotlin:["Use JaCoCo with Kotlin support"]},examples:[]};var l={domain:"contract-testing",bestPractices:["Use contract testing for API boundaries (Pact, etc.)","Test both successful and error responses","Validate response schemas, not just status codes","Test authentication and authorization flows",'Use realistic test data, not just "test" strings',"Test rate limiting and pagination","Verify idempotency for applicable operations","Test with different content types (JSON, XML)","Document APIs with OpenAPI/Swagger specs","Use consumer-driven contracts for microservices"],antiPatterns:[{name:"Testing Implementation",description:"Tests that verify internal implementation details",reason:"Breaks when implementation changes, even if behavior unchanged",alternative:"Test the contract and behavior, not implementation"},{name:"Hardcoded URLs",description:"API URLs hardcoded in tests",reason:"Fails across environments, hard to maintain",alternative:"Use environment variables or config files"},{name:"No Schema Validation",description:"Only checking status codes, not response structure",reason:"Miss contract violations that break consumers",alternative:"Validate response against OpenAPI schema"}],frameworkGuidance:{jest:["Use supertest for HTTP testing"],vitest:["Use supertest or fetch for HTTP testing"],mocha:["Use supertest with chai-http"],pytest:["Use requests or httpx for API testing"],junit:["Use REST Assured for API testing"],testng:["Use REST Assured with TestNG"],playwright:["Use API testing with request context"],cypress:["Use cy.request() for API testing"],selenium:["Integrate with API testing libraries separately"]},languageGuidance:{typescript:["Use supertest, got, or axios"],javascript:["Use supertest, got, or axios"],python:["Use requests, httpx, or pytest-httpx"],java:["Use REST Assured or OkHttp"],go:["Use net/http/httptest package"],rust:["Use reqwest for HTTP testing"],csharp:["Use RestSharp or HttpClient"],kotlin:["Use Fuel or Ktor client"]},examples:[]},u={domain:"security-compliance",bestPractices:["Follow OWASP Top 10 for vulnerability testing","Test authentication bypass scenarios","Test SQL injection in all input fields","Test XSS in all output contexts","Verify CSRF protection on state-changing operations","Test authorization for all endpoints and actions","Scan dependencies for known vulnerabilities (SCA)","Use SAST tools in CI/CD pipeline","Test secrets management and exposure","Validate input sanitization and output encoding"],antiPatterns:[{name:"Security by Obscurity",description:"Relying on hidden endpoints or non-standard auth",reason:"Security through obscurity always fails",alternative:"Use standard authentication and authorization"},{name:"Testing Only Happy Path",description:"Only testing valid inputs",reason:"Miss injection and bypass vulnerabilities",alternative:"Test with malicious inputs and edge cases"}],frameworkGuidance:{jest:["Use for testing security functions and middleware"],vitest:["Use for testing security functions and middleware"],mocha:["Use for testing security functions"],pytest:["Use for testing security functions"],junit:["Use for testing security functions"],testng:["Use for testing security functions"],playwright:["Test for XSS, CSRF in browser context"],cypress:["Test for XSS, CSRF in browser context"],selenium:["Test for XSS, CSRF in browser context"]},languageGuidance:{typescript:["Use snyk, npm audit for dependency scanning"],javascript:["Use snyk, npm audit for dependency scanning"],python:["Use bandit for SAST, safety for SCA"],java:["Use SpotBugs, FindSecBugs for SAST"],go:["Use gosec for security scanning"],rust:["Use cargo-audit for vulnerability scanning"],csharp:["Use Security Code Scan for SAST"],kotlin:["Use detekt with security rules"]},examples:[]},d={domain:"visual-accessibility",bestPractices:["Capture screenshots at consistent viewport sizes","Use baseline images for comparison","Handle dynamic content (dates, avatars) with masks","Test across multiple browsers and devices","Use percy or chromatic for visual regression","Maintain baseline images in version control","Set appropriate diff thresholds for noise tolerance","Test responsive breakpoints systematically","Capture full-page and component screenshots","Use stable selectors for screenshot regions"],antiPatterns:[{name:"Pixel-Perfect Obsession",description:"Zero tolerance for any pixel differences",reason:"Anti-aliasing and rendering differences cause false failures",alternative:"Use appropriate diff thresholds (typically 0.1-5%)"},{name:"Unmasked Dynamic Content",description:"Not masking timestamps, avatars, ads",reason:"Causes constant baseline updates",alternative:"Mask or mock dynamic content consistently"}],frameworkGuidance:{jest:["Use jest-image-snapshot"],vitest:["Use vitest-image-snapshot"],mocha:["Use chai-image-snapshot"],pytest:["Use pytest-playwright with screenshots"],junit:["Use ashot for Java screenshot comparison"],testng:["Use ashot with TestNG"],playwright:["Use expect(page).toHaveScreenshot()"],cypress:["Use cypress-image-snapshot or percy"],selenium:["Use ashot or built-in screenshot"]},languageGuidance:{typescript:["Use playwright or puppeteer for screenshots"],javascript:["Use playwright or puppeteer for screenshots"],python:["Use playwright-python or selenium"],java:["Use ashot with Selenium"],go:["Use chromedp for browser automation"],rust:["Use headless-chrome or fantoccini"],csharp:["Use Selenium with screenshot comparison"],kotlin:["Use Selenium or Playwright with Kotlin"]},examples:[]};var p={domain:"chaos-resilience",bestPractices:["Define clear SLAs and performance budgets","Test under realistic load patterns","Monitor resource usage (CPU, memory, network)","Test both response time and throughput","Include performance tests in CI/CD","Use production-like test environments","Test with realistic data volumes","Profile before optimizing","Test under peak and sustained load","Monitor for memory leaks during extended tests"],antiPatterns:[{name:"Production Load Testing",description:"Running load tests against production",reason:"Can cause outages and affect real users",alternative:"Use staging environment with production-like data"},{name:"Single-Metric Focus",description:"Only measuring response time",reason:"Miss throughput, resource, and concurrency issues",alternative:"Track response time, throughput, errors, resources"}],frameworkGuidance:{jest:["Use for micro-benchmarks only"],vitest:["Use bench() for micro-benchmarks"],mocha:["Use for micro-benchmarks only"],pytest:["Use pytest-benchmark for micro-benchmarks"],junit:["Use JMH for micro-benchmarks"],testng:["Use JMH with TestNG"],playwright:["Use for frontend performance metrics"],cypress:["Use for frontend performance metrics"],selenium:["Limited - use dedicated perf tools"]},languageGuidance:{typescript:["Use k6, artillery, or autocannon"],javascript:["Use k6, artillery, or autocannon"],python:["Use locust for load testing"],java:["Use JMeter, Gatling, or k6"],go:["Use vegeta or hey for load testing"],rust:["Use criterion for benchmarks, drill for load"],csharp:["Use NBomber or k6"],kotlin:["Use Gatling with Kotlin DSL"]},examples:[]},o={"test-generation":i,"test-execution":i,"coverage-analysis":c,"quality-assessment":i,"defect-intelligence":i,"requirements-validation":i,"code-intelligence":c,"security-compliance":u,"contract-testing":l,"visual-accessibility":d,"chaos-resilience":p,"learning-optimization":i};function g(n){return o[n]}function m(n,s){let a=o[n],t=[...a.bestPractices];if(s.framework){let e=a.frameworkGuidance[s.framework];e&&t.push(...e.map(r=>`[${s.framework}] ${r}`))}if(s.language){let e=a.languageGuidance[s.language];e&&t.push(...e.map(r=>`[${s.language}] ${r}`))}if(s.includeAntiPatterns)for(let e of a.antiPatterns)t.push(`[AVOID] ${e.name}: ${e.description}`);return t}function f(n,s){let a=o[n],t=[];for(let e of a.antiPatterns)e.detection&&new RegExp(e.detection,"gi").test(s)&&t.push(e);return t}function h(n,s){let a=o[n],t=[];t.push(`## QE Guidance: ${n}`),t.push(""),t.push("### Best Practices");for(let e of a.bestPractices.slice(0,5))t.push(`- ${e}`);if(s.framework){let e=a.frameworkGuidance[s.framework];if(e&&e.length>0){t.push(""),t.push(`### ${s.framework} Tips`);for(let r of e.slice(0,3))t.push(`- ${r}`)}}if(s.language){let e=a.languageGuidance[s.language];if(e&&e.length>0){t.push(""),t.push(`### ${s.language} Tips`);for(let r of e.slice(0,3))t.push(`- ${r}`)}}t.push(""),t.push("### Anti-Patterns to Avoid");for(let e of a.antiPatterns.slice(0,3))t.push(`- **${e.name}**: ${e.description}`);return t.join(`
30
+ `)}export{g as a,m as b,f as c,h as d};
@@ -0,0 +1,81 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{writeFileSync as p,readFileSync as m}from"node:fs";import{resolve as f,dirname as c,join as d}from"node:path";import{mkdirSync as g}from"node:fs";import{fileURLToPath as h}from"node:url";function $(){try{let e=typeof __dirname<"u"?__dirname:c(h(import.meta.url));for(let t=0;t<5;t++){let n=d(e,"package.json");try{let r=JSON.parse(m(n,"utf-8"));if(r.version)return r.version}catch{}e=c(e)}}catch{}return"unknown"}var T=["-F, --format <format>","Output format (text|json|sarif|junit|markdown)","text"],x=["-o, --output <path>","Write output to file instead of stdout"];function C(e,t,n){if(t){let r=f(t);g(c(r),{recursive:!0}),p(r,e,"utf-8"),n&&console.log(n),console.log(`Output written to: ${r}`)}else console.log(e)}function R(e){return JSON.stringify(e,null,2)}var v="https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json";function w(e){let t=i=>{switch(i.toLowerCase()){case"critical":case"high":return"error";case"medium":return"warning";case"low":case"info":return"note";default:return"warning"}},n=new Map,r=[];for(let i of e.vulnerabilities){let o=i.ruleId||`AQE/${i.type.replace(/\s+/g,"-").toLowerCase()}`;n.has(o)||n.set(o,{id:o,name:i.type,shortDescription:i.type,...i.cweId?{helpUri:`https://cwe.mitre.org/data/definitions/${i.cweId.replace("CWE-","")}.html`}:{}}),r.push({ruleId:o,level:t(i.severity),message:{text:i.message},locations:[{physicalLocation:{artifactLocation:{uri:i.file,uriBaseId:"%SRCROOT%"},region:{startLine:i.line,startColumn:1}}}],...i.cweId?{taxa:[{id:i.cweId,toolComponent:{name:"CWE"}}]}:{}})}let s={$schema:v,version:"2.1.0",runs:[{tool:{driver:{name:"agentic-qe",version:$(),informationUri:"https://github.com/proffesor-for-testing/agentic-qe",rules:Array.from(n.values()).map(i=>({id:i.id,name:i.name,shortDescription:{text:i.shortDescription},...i.helpUri?{helpUri:i.helpUri}:{},defaultConfiguration:{level:"warning"}}))}},results:r,invocations:[{executionSuccessful:!0,commandLine:`aqe security --sast --format sarif -t ${e.target}`}]}]};return JSON.stringify(s,null,2)}function a(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function I(e){let t=e.tests||[],n=e.passed+e.failed+e.skipped,r=(e.duration/1e3).toFixed(3),s=`<?xml version="1.0" encoding="UTF-8"?>
3
+ `;if(s+=`<testsuites tests="${n}" failures="${e.failed}" errors="0" time="${r}">
4
+ `,s+=` <testsuite name="aqe-test-run" tests="${n}" failures="${e.failed}" errors="0" skipped="${e.skipped}" time="${r}" id="${a(e.runId)}">
5
+ `,t.length>0)for(let i of t){let o=(i.duration/1e3).toFixed(3),l=a(i.suite||i.file||"aqe"),u=a(i.name);s+=` <testcase classname="${l}" name="${u}" time="${o}"`,!i.passed&&i.error?(s+=`>
6
+ `,s+=` <failure message="${a(i.error)}">${a(i.error)}</failure>
7
+ `,s+=` </testcase>
8
+ `):s+=` />
9
+ `}else{for(let i=0;i<e.passed;i++)s+=` <testcase classname="aqe" name="test-${i+1}" time="0" />
10
+ `;for(let i=0;i<e.failed;i++)s+=` <testcase classname="aqe" name="failed-test-${i+1}" time="0">
11
+ `,s+=` <failure message="Test failed">Test failed</failure>
12
+ `,s+=` </testcase>
13
+ `;for(let i=0;i<e.skipped;i++)s+=` <testcase classname="aqe" name="skipped-test-${i+1}" time="0">
14
+ `,s+=` <skipped />
15
+ `,s+=` </testcase>
16
+ `}return s+=` </testsuite>
17
+ `,s+=`</testsuites>
18
+ `,s}function O(e){let t=`# Coverage Report
19
+
20
+ `;if(t+=`| Metric | Value | Status |
21
+ `,t+=`|--------|-------|--------|
22
+ `,t+=`| Lines | ${e.summary.line}% | ${e.summary.line>=e.threshold?"\u2705":"\u274C"} |
23
+ `,t+=`| Branches | ${e.summary.branch}% | ${e.summary.branch>=e.threshold?"\u2705":"\u274C"} |
24
+ `,t+=`| Functions | ${e.summary.function}% | ${e.summary.function>=e.threshold?"\u2705":"\u274C"} |
25
+ `,t+=`| Statements | ${e.summary.statement}% | ${e.summary.statement>=e.threshold?"\u2705":"\u274C"} |
26
+ `,t+=`
27
+ **Threshold:** ${e.threshold}% \u2014 ${e.meetsThreshold?"\u2705 Met":"\u274C Not met"}
28
+ `,e.gaps&&e.gaps.length>0){t+=`
29
+ ## Coverage Gaps
30
+
31
+ `,t+=`| File | Uncovered Lines | Risk | Severity |
32
+ `,t+=`|------|----------------|------|----------|
33
+ `;for(let n of e.gaps.slice(0,20))t+=`| ${n.file} | ${n.lines.length} | ${(n.riskScore*100).toFixed(0)}% | ${n.severity} |
34
+ `}if(e.recommendations&&e.recommendations.length>0){t+=`
35
+ ## Recommendations
36
+
37
+ `;for(let n of e.recommendations)t+=`- ${n}
38
+ `}return t}function F(e){let t=`# Quality Gate Report
39
+
40
+ `;t+=`**Result:** ${e.passed?"\u2705 PASSED":"\u274C FAILED"}
41
+ `,t+=`**Score:** ${e.score}
42
+
43
+ `,t+=`## Checks
44
+
45
+ `,t+=`| Check | Value | Threshold | Status |
46
+ `,t+=`|-------|-------|-----------|--------|
47
+ `;for(let n of e.checks)t+=`| ${n.name} | ${n.value} | ${n.threshold} | ${n.passed?"\u2705":"\u274C"} |
48
+ `;if(e.recommendations&&e.recommendations.length>0){t+=`
49
+ ## Recommendations
50
+
51
+ `;for(let n of e.recommendations)t+=`- ${n}
52
+ `}return t}function A(e){let t=`# Security Scan Report
53
+
54
+ `;if(t+=`**Target:** ${e.target}
55
+ `,t+=`**Scan Type:** ${e.scanType}
56
+ `,t+=`**Vulnerabilities Found:** ${e.vulnerabilities.length}
57
+
58
+ `,e.vulnerabilities.length>0){t+=`## Vulnerabilities
59
+
60
+ `,t+=`| Severity | Type | File | Line | Message |
61
+ `,t+=`|----------|------|------|------|---------|
62
+ `;for(let n of e.vulnerabilities)t+=`| ${n.severity} | ${n.type} | ${n.file} | ${n.line} | ${n.message} |
63
+ `}if(e.compliance&&(t+=`
64
+ ## Compliance
65
+
66
+ `,t+=`**Status:** ${e.compliance.compliant?"\u2705 Compliant":"\u274C Non-compliant"}
67
+ `,e.compliance.issues))for(let n of e.compliance.issues)t+=`- **${n.framework}:** ${n.issue}
68
+ `;return t}function L(e){let t=e.passed+e.failed+e.skipped,n=`# Test Run Report
69
+
70
+ `;return n+=`**Run ID:** ${e.runId}
71
+ `,n+=`**Duration:** ${e.duration}ms
72
+
73
+ `,n+=`| Metric | Count |
74
+ `,n+=`|--------|-------|
75
+ `,n+=`| Total | ${t} |
76
+ `,n+=`| Passed | ${e.passed} |
77
+ `,n+=`| Failed | ${e.failed} |
78
+ `,n+=`| Skipped | ${e.skipped} |
79
+ `,n+=`
80
+ **Result:** ${e.failed===0?"\u2705 All tests passed":"\u274C Some tests failed"}
81
+ `,n}export{T as a,x as b,C as c,R as d,w as e,I as f,O as g,F as h,A as i,L as j};
@@ -0,0 +1,2 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{randomUUID as v}from"crypto";var m={"claude-opus-4-5-20251101":{input:15,output:75,provider:"claude"},"claude-sonnet-4-20250514":{input:3,output:15,provider:"claude"},"claude-3-5-haiku-20241022":{input:1,output:5,provider:"claude"},"claude-3-opus-20240229":{input:15,output:75,provider:"claude"},"claude-3-sonnet-20240229":{input:3,output:15,provider:"claude"},"claude-3-haiku-20240307":{input:.25,output:1.25,provider:"claude"},"gpt-4o":{input:5,output:15,provider:"openai"},"gpt-4o-mini":{input:.15,output:.6,provider:"openai"},"gpt-4-turbo":{input:10,output:30,provider:"openai"},"gpt-4":{input:30,output:60,provider:"openai"},"gpt-3.5-turbo":{input:.5,output:1.5,provider:"openai"},llama3:{input:0,output:0,provider:"ollama"},"llama3.1":{input:0,output:0,provider:"ollama"},codellama:{input:0,output:0,provider:"ollama"},mistral:{input:0,output:0,provider:"ollama"},mixtral:{input:0,output:0,provider:"ollama"},phi3:{input:0,output:0,provider:"ollama"},qwen2:{input:0,output:0,provider:"ollama"},"anthropic/claude-3.5-sonnet":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3.5-sonnet:beta":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3-opus":{input:15,output:75,provider:"openrouter"},"anthropic/claude-3-sonnet":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3-haiku":{input:.25,output:1.25,provider:"openrouter"},"openai/gpt-4o":{input:5,output:15,provider:"openrouter"},"openai/gpt-4o-mini":{input:.15,output:.6,provider:"openrouter"},"openai/gpt-4-turbo":{input:10,output:30,provider:"openrouter"},"openai/gpt-3.5-turbo":{input:.5,output:1.5,provider:"openrouter"},"google/gemini-pro":{input:.125,output:.375,provider:"openrouter"},"google/gemini-pro-1.5":{input:3.5,output:10.5,provider:"openrouter"},"meta-llama/llama-3.1-70b-instruct":{input:.59,output:.79,provider:"openrouter"},"meta-llama/llama-3.1-8b-instruct":{input:.06,output:.06,provider:"openrouter"},"mistralai/mistral-large":{input:2,output:6,provider:"openrouter"},"mistralai/mixtral-8x7b-instruct":{input:.24,output:.24,provider:"openrouter"},"mistralai/mistral-7b-instruct":{input:.06,output:.06,provider:"openrouter"},"anthropic.claude-opus-4-5-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-opus-4-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-sonnet-4-5-v2:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-sonnet-4-v1:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-3-5-haiku-v1:0":{input:1,output:5,provider:"bedrock"},"anthropic.claude-3-opus-20240229-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-3-sonnet-20240229-v1:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-3-haiku-20240307-v1:0":{input:.25,output:1.25,provider:"bedrock"},"anthropic.claude-3-5-sonnet-20241022-v2:0":{input:3,output:15,provider:"bedrock"},"azure/gpt-4o":{input:5,output:15,provider:"azure-openai"},"azure/gpt-4o-mini":{input:.15,output:.6,provider:"azure-openai"},"azure/gpt-4-turbo":{input:10,output:30,provider:"azure-openai"},"azure/gpt-4":{input:30,output:60,provider:"azure-openai"},"azure/gpt-35-turbo":{input:.5,output:1.5,provider:"azure-openai"},"azure/text-embedding-ada-002":{input:.1,output:0,provider:"azure-openai"},"azure/text-embedding-3-small":{input:.02,output:0,provider:"azure-openai"},"azure/text-embedding-3-large":{input:.13,output:0,provider:"azure-openai"},"gemini-pro":{input:.5,output:1.5,provider:"gemini"},"gemini-1.0-pro":{input:.5,output:1.5,provider:"gemini"},"gemini-1.5-pro":{input:3.5,output:10.5,provider:"gemini"},"gemini-1.5-pro-latest":{input:3.5,output:10.5,provider:"gemini"},"gemini-1.5-flash":{input:.075,output:.3,provider:"gemini"},"gemini-1.5-flash-latest":{input:.075,output:.3,provider:"gemini"},"gemini-2.0-flash-exp":{input:.075,output:.3,provider:"gemini"},"gemini-ultra":{input:7,output:21,provider:"gemini"},"gemini-1.0-ultra":{input:7,output:21,provider:"gemini"},"text-embedding-004":{input:.025,output:0,provider:"gemini"}},d=class c{records=[];alerts=[];maxRecords;alertCheckInterval;constructor(t=1e4){this.maxRecords=t}static calculateCost(t,r){let e=m[t];if(!e)return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"};let i=r.promptTokens/1e6*e.input,o=r.completionTokens/1e6*e.output;return{inputCost:i,outputCost:o,totalCost:i+o,currency:"USD"}}static getCostPerToken(t){let r=m[t];return r?{input:r.input/1e6,output:r.output/1e6}:{input:0,output:0}}recordUsage(t,r,e,i,o){let n=c.calculateCost(r,e),p={timestamp:new Date,provider:t,model:r,usage:e,cost:n,requestId:i,metadata:o};return this.records.push(p),this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords)),this.checkAlerts(),n}getSummary(t){let r=new Date,e=this.getPeriodStart(r,t),i=r,o=this.records.filter(s=>s.timestamp>=e&&s.timestamp<=i),n={claude:0,openai:0,ollama:0,openrouter:0,bedrock:0,"azure-openai":0,gemini:0},p={},u=0,l=0;for(let s of o)u+=s.cost.totalCost,l+=s.usage.totalTokens,n[s.provider]+=s.cost.totalCost,p[s.model]=(p[s.model]||0)+s.cost.totalCost;return{period:t,periodStart:e,periodEnd:i,totalCost:u,byProvider:n,byModel:p,totalTokens:l,totalRequests:o.length}}getCurrentCost(t){return this.getSummary(t).totalCost}getTotalTokens(t){return this.getSummary(t).totalTokens}getUsageByProvider(t,r="all"){let e=this.getPeriodStart(new Date,r),i=this.records.filter(u=>u.provider===t&&u.timestamp>=e),o={},n=0,p=0;for(let u of i)n+=u.cost.totalCost,p+=u.usage.totalTokens,o[u.model]||(o[u.model]={cost:0,tokens:0,requests:0}),o[u.model].cost+=u.cost.totalCost,o[u.model].tokens+=u.usage.totalTokens,o[u.model].requests+=1;return{totalCost:n,totalTokens:p,totalRequests:i.length,models:o}}addAlert(t,r,e){let i=`alert-${Date.now()}-${v().slice(0,12)}`;return this.alerts.push({threshold:t,period:r,onThreshold:e,active:!0}),this.alertCheckInterval||(this.alertCheckInterval=setInterval(()=>this.checkAlerts(),6e4)),i}removeAlert(t){return t>=0&&t<this.alerts.length?(this.alerts.splice(t,1),this.alerts.length===0&&this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0),!0):!1}getRecords(){return[...this.records]}importRecords(t){for(let r of t)r.timestamp=new Date(r.timestamp),this.records.push(r);this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords))}clear(){this.records=[]}getRecentRequests(t=10){return this.records.slice(-t)}estimateCost(t,r,e){return c.calculateCost(t,{promptTokens:r,completionTokens:e,totalTokens:r+e})}wouldExceedLimit(t,r,e,i,o){let n=this.getCurrentCost(o),p=this.estimateCost(t,r,e);return n+p.totalCost>i}dispose(){this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}getPeriodStart(t,r){let e=new Date(t);switch(r){case"minute":e.setSeconds(0,0),e.setMinutes(e.getMinutes()-1);break;case"hour":e.setMinutes(0,0,0),e.setHours(e.getHours()-1);break;case"day":e.setHours(0,0,0,0);break;case"week":e.setHours(0,0,0,0),e.setDate(e.getDate()-7);break;case"month":e.setHours(0,0,0,0),e.setDate(1);break;case"all":return new Date(0)}return e}checkAlerts(){for(let t of this.alerts){if(!t.active)continue;let r=this.getSummary(t.period);if(r.totalCost>=t.threshold){t.active=!1;try{t.onThreshold(r)}catch(e){console.error("Cost alert callback error:",e)}}}}},a;function h(){return a||(a=new d),a}function b(){a&&(a.dispose(),a=void 0)}export{m as a,d as b,h as c,b as d};
@@ -0,0 +1,2 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{a as F,c as D}from"./chunk-JZSDOIXA.js";import{d as $}from"./chunk-B36CDR4U.js";$();D();var b=null,l=null,d=null,g=!1,f="",h={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4},o=new Map,P=36e5;function I(t){let e=t.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function A(t={}){if(g)throw new Error(`Transformer initialization previously failed: ${f}`);if(d)return d;let e={...h,...t};return d=(async()=>{try{b=(await import("./transformers-GY7SIKEU.js")).pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let a=performance.now();l=await b("feature-extraction",e.modelName,{quantized:e.quantized});let s=performance.now()-a;console.log(`[RealEmbeddings] Model loaded in ${s.toFixed(0)}ms`)}catch(r){throw g=!0,f=F(r),new Error(`Failed to initialize transformer model: ${f}`)}})(),d}async function q(t,e={}){let r={...h,...e};if(I(t))return new Array(N()).fill(0);if(r.enableCache){let i=o.get(t);if(i&&Date.now()-i.timestamp<P)return i.embedding}if(l||await A(e),!l)throw new Error("Embedding model failed to initialize");let a=performance.now(),s=await l(t,{pooling:"mean",normalize:!0}),m=Array.from(s.data),n=performance.now()-a;if(n>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${n.toFixed(1)}ms for "${t.slice(0,50)}..."`),r.enableCache){if(o.size>=r.maxCacheSize){let i=o.keys().next().value;i&&o.delete(i)}o.set(t,{embedding:m,timestamp:Date.now()})}return m}async function B(t,e={}){let r={...h,...e},a=[],s=[],m=new Array(t.length).fill(null);if(r.enableCache)for(let n=0;n<t.length;n++){let i=o.get(t[n]);i&&Date.now()-i.timestamp<P?m[n]=i.embedding:(a.push(t[n]),s.push(n))}else{a.push(...t);for(let n=0;n<t.length;n++)s.push(n)}if(a.length>0){if(l||await A(e),!l)throw new Error("Embedding model failed to initialize");let n=performance.now(),i=32;for(let c=0;c<a.length;c+=i){let M=Math.min(c+i,a.length),p=a.slice(c,M),E=await l(p,{pooling:"mean",normalize:!0}),w=E.dims||[p.length,384],R=w[0],C=w[1];for(let u=0;u<R;u++){let z=u*C,x=Array.from(E.data.slice(z,z+C)),y=c+u,v=s[y];if(m[v]=x,r.enableCache){if(o.size>=r.maxCacheSize){let T=o.keys().next().value;T&&o.delete(T)}o.set(a[y],{embedding:x,timestamp:Date.now()})}}}let S=performance.now()-n;console.log(`[RealEmbeddings] Batch computed ${a.length} embeddings in ${S.toFixed(0)}ms`)}return m.filter(n=>n!==null)}function O(){o.clear(),console.log("[RealEmbeddings] Cache cleared")}function W(){return{size:o.size,hitRate:0}}function k(){return!g&&l!==null}function N(){return 384}function G(){b=null,l=null,d=null,g=!1,f="",o.clear()}export{h as a,q as b,B as c,O as d,W as e,k as f,N as g,G as h};
@@ -0,0 +1,20 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{a as E}from"./chunk-4YS3IJ45.js";import{a as b}from"./chunk-3JPRUND5.js";import{c as y}from"./chunk-4VUPRTVX.js";import{a as f,c as k}from"./chunk-JZSDOIXA.js";k();b();var l=y.create("qe-hooks"),u={PreTestGeneration:"qe:pre-test-generation",PostTestGeneration:"qe:post-test-generation",TestExecutionResult:"qe:test-execution-result",PreCoverageAnalysis:"qe:pre-coverage-analysis",PostCoverageAnalysis:"qe:post-coverage-analysis",CoverageGapIdentified:"qe:coverage-gap-identified",QEAgentRouting:"qe:agent-routing",QEAgentCompletion:"qe:agent-completion",QualityScoreCalculated:"qe:quality-score",RiskAssessmentComplete:"qe:risk-assessment",PatternLearned:"qe:pattern-learned",PatternApplied:"qe:pattern-applied",PatternPromoted:"qe:pattern-promoted",PreCompaction:"qe:pre-compaction"};function h(i){return{[u.PreTestGeneration]:async t=>{let{targetFile:s,testType:a,framework:e,language:r}=t.data,n=await i.routeTask({task:`Generate ${a} tests for ${s}`,taskType:"test-generation",context:{framework:e,language:r,testType:a}});if(!n.success)return{success:!1,error:n.error.message};let o=[];try{let{getUnifiedMemory:c}=await import("./unified-memory-XYGENQUT.js");o=c().getDatabase().prepare(`
3
+ SELECT u.pattern_id, u.success, u.feedback
4
+ FROM qe_pattern_usage u
5
+ JOIN qe_patterns p ON u.pattern_id = p.id
6
+ WHERE p.qe_domain = 'test-generation'
7
+ ORDER BY u.created_at DESC
8
+ LIMIT 10
9
+ `).all()}catch{}return{success:!0,routing:n.value,guidance:n.value.guidance,data:{recommendedAgent:n.value.recommendedAgent,patterns:n.value.patterns.map(c=>c.id),recentExperiences:o}}},[u.PostTestGeneration]:async t=>{let{targetFile:s,generatedTests:a,testCount:e,framework:r,language:n,success:o,patternId:c}=t.data,p=0;if(c&&await i.recordOutcome({patternId:c,success:o,metrics:{testsPassed:0,testsFailed:0}}),o&&a&&e>0)try{(await i.storePattern({patternType:"test-template",name:`Generated tests for ${s.split("/").pop()}`,description:`Test template extracted from successful test generation for ${s}`,template:{type:"code",content:a,variables:[]},context:{framework:r,language:n,testType:"unit",tags:["generated","test-template",r,n]}})).success&&(p=1)}catch(d){l.debug("Pattern learning failed",{error:d instanceof Error?d.message:String(d)})}return{success:!0,patternsLearned:p,data:{learned:p>0}}},[u.TestExecutionResult]:async t=>{let{runId:s,patternId:a,passed:e,failed:r,duration:n,flaky:o}=t.data;if(a){let c=e+r>0?e/(e+r):0;await i.recordOutcome({patternId:a,success:c>.8&&!o,metrics:{testsPassed:e,testsFailed:r,executionTimeMs:n}})}return{success:!0,data:{runId:s,successRate:e+r>0?e/(e+r):0}}},[u.PreCoverageAnalysis]:async t=>{let{targetPath:s,currentCoverage:a}=t.data,e=await i.routeTask({task:`Analyze coverage gaps for ${s} (current: ${a}%)`,taskType:"analysis",domain:"coverage-analysis"});if(!e.success)return{success:!1,error:e.error.message};let r=[];try{let{getUnifiedMemory:n}=await import("./unified-memory-XYGENQUT.js");r=n().getDatabase().prepare(`
10
+ SELECT u.pattern_id, u.success, u.feedback
11
+ FROM qe_pattern_usage u
12
+ JOIN qe_patterns p ON u.pattern_id = p.id
13
+ WHERE p.qe_domain = 'coverage-analysis'
14
+ ORDER BY u.created_at DESC
15
+ LIMIT 10
16
+ `).all()}catch{}return{success:!0,routing:e.value,guidance:e.value.guidance,data:{recentExperiences:r}}},[u.PostCoverageAnalysis]:async t=>{let{targetPath:s,previousCoverage:a,newCoverage:e,gapsFound:r,strategy:n,patternId:o}=t.data,c=e-a,p=c>0;o&&await i.recordOutcome({patternId:o,success:p,metrics:{coverageImprovement:c}});let d=0;if(p&&n&&c>5)try{(await i.storePattern({patternType:"coverage-strategy",name:`Coverage strategy for ${s.split("/").pop()}`,description:`Strategy that improved coverage by ${c.toFixed(1)}%`,template:{type:"prompt",content:n,variables:[]},context:{tags:["coverage","strategy","successful"]}})).success&&(d=1)}catch(g){l.debug("Coverage strategy pattern storage failed",{error:g instanceof Error?g.message:String(g)})}return{success:!0,patternsLearned:d,data:{improvement:c,gapsFound:r}}},[u.CoverageGapIdentified]:async t=>{let{file:s,lines:a,branches:e,riskScore:r,suggestedTests:n}=t.data;if(n&&r>.5)try{await i.storePattern({patternType:"coverage-strategy",name:`Coverage gap: ${s.split("/").pop()}`,description:`Coverage gap pattern with ${a?.length||0} uncovered lines, risk ${r}`,template:{type:"prompt",content:`Suggested tests for coverage gap:
17
+ ${n}`,variables:[]},context:{tags:["coverage-gap","high-risk","suggested-tests"]}})}catch(o){l.debug("Coverage gap pattern storage failed",{error:o instanceof Error?o.message:String(o)})}return{success:!0,data:{file:s,riskScore:r}}},[u.QEAgentRouting]:async t=>{let{task:s,taskType:a,capabilities:e,context:r}=t.data,n=await i.routeTask({task:s,taskType:a,capabilities:e,context:r});return n.success?{success:!0,routing:n.value,guidance:n.value.guidance,data:{agent:n.value.recommendedAgent,confidence:n.value.confidence}}:{success:!1,error:n.error.message}},[u.QEAgentCompletion]:async t=>{let{agentType:s,task:a,success:e,duration:r,patternId:n,feedback:o}=t.data,c=0,p=n;if(p){try{if(!await i.getPattern(p)){let g=s||"unknown",v=E(a||g)||"learning-optimization";await i.storePattern({patternType:"test-template",qeDomain:v,name:`Auto: ${g} completion`,description:`Auto-created pattern for ${g} task completion tracking`,template:{type:"prompt",content:`Agent ${g} task pattern`,variables:[]},context:{tags:["auto-created","agent-completion",g]},confidence:.5}),c=1}}catch(d){l.debug("Auto-create pattern failed",{error:d instanceof Error?d.message:String(d)})}await i.recordOutcome({patternId:p,success:e,metrics:{executionTimeMs:r},feedback:o})}return{success:!0,patternsLearned:c,data:{agentType:s,success:e,duration:r}}},[u.QualityScoreCalculated]:async t=>{let{score:s,components:a,threshold:e,passed:r}=t.data,n=[];return t.data.coverageScore&&t.data.coverageScore<.8&&n.push("Coverage is below target. Focus on critical paths."),t.data.testQualityScore&&t.data.testQualityScore<.7&&n.push("Test quality needs improvement. Review test assertions."),{success:!0,guidance:n,data:{score:s,passed:r}}},[u.RiskAssessmentComplete]:async t=>{let{file:s,riskScore:a,riskFactors:e}=t.data;if(a>.7&&e)try{await i.storePattern({patternType:"coverage-strategy",name:`High risk: ${s.split("/").pop()}`,description:`Risk factors: ${e.join(", ")}`,template:{type:"prompt",content:`Risk assessment for ${s}:
18
+ Score: ${a}
19
+ Factors: ${e.join(`
20
+ - `)}`,variables:[]},context:{tags:["risk","high-priority","assessment"]}})}catch(r){l.debug("Risk assessment pattern storage failed",{error:r instanceof Error?r.message:String(r)})}return{success:!0,data:{file:s,riskScore:a}}},[u.PatternLearned]:async t=>{let{patternId:s,patternType:a,domain:e,confidence:r}=t.data;return console.log(`[QEHooks] Pattern learned: ${s} (${a}, ${e}, confidence: ${r})`),{success:!0,patternsLearned:1,data:{patternId:s}}},[u.PatternApplied]:async t=>{let{patternId:s,success:a}=t.data;return await i.recordOutcome({patternId:s,success:a}),{success:!0,data:{patternId:s,success:a}}},[u.PatternPromoted]:async t=>{let{patternId:s,newTier:a,successfulUses:e}=t.data;return console.log(`[QEHooks] Pattern promoted: ${s} -> ${a} (${e} successful uses)`),{success:!0,data:{patternId:s,newTier:a}}},[u.PreCompaction]:async t=>{let s={experiencesFlushed:0,patternsPromoted:0};if(t.data?.experienceCaptureService){let a=t.data.experienceCaptureService,e=a.getPendingCount?.()??0;if(e>0){let r=await a.flushPending?.();s.experiencesFlushed=r??e}}if(t.data?.patternLifecycleManager){let e=t.data.patternLifecycleManager.runPromotionSweep?.();e&&(s.patternsPromoted=e.promoted??0)}return console.log("[QEHooks] Pre-compaction flush:",s),{success:!0,data:s}}}}var m=class{constructor(t){this.eventBus=t}handlers=new Map;reasoningBank;initialize(t){this.reasoningBank=t;let s=h(t);for(let[a,e]of Object.entries(s))this.register(a,e);if(this.eventBus)for(let a of Object.values(u))this.eventBus.subscribe(a,async e=>{await this.emit(a,e.payload)})}register(t,s){this.handlers.has(t)||this.handlers.set(t,[]),this.handlers.get(t).push(s)}unregister(t,s){let a=this.handlers.get(t);if(a){let e=a.indexOf(s);e!==-1&&a.splice(e,1)}}async emit(t,s){let a=this.handlers.get(t)||[],e=[],r={eventId:`${t}-${Date.now()}`,timestamp:new Date,data:s};for(let n of a)try{let o=await n(r);e.push(o),o.data&&Object.assign(r.data,o.data)}catch(o){e.push({success:!1,error:f(o)})}return e}getRegisteredEvents(){return Array.from(this.handlers.keys())}clear(){this.handlers.clear()}};function w(i,t){let s=new m(t);return s.initialize(i),s}export{u as a,m as b,w as c};
@@ -0,0 +1,2 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ var l=class{approxMinCut(e){let t=Date.now();if(e.isEmpty())return this.emptyResult(t,"weighted-degree");let r=e.getVertexIds(),n=1/0,i=null;for(let o of r){let c=e.weightedDegree(o);c<n&&(n=c,i=o)}if(i===null||r.length===1)return this.emptyResult(t,"weighted-degree");let a=e.getEdgesForVertex(i);return{value:n,sourceSide:[i],targetSide:r.filter(o=>o!==i),cutEdges:a,calculatedAt:new Date,algorithm:"weighted-degree",durationMs:Date.now()-t}}findWeakVertices(e,t){if(e.isEmpty())return[];let r=e.getVertices(),n=[],i=new Map,a=0;for(let g of r){let h=e.weightedDegree(g.id);i.set(g.id,h),a+=h}let o=a/r.length,c=0;for(let g of i.values())c+=(g-o)**2;let s=Math.sqrt(c/r.length),d=1/0;for(let g of i.values())g<d&&(d=g);let u=t??o-s;for(let g of r){let h=i.get(g.id);if(h<=u){let w=this.calculateRiskScore(h,o,s,d),y=this.determineWeakReason(g,h,o,e),v=this.generateStrengtheningActions(g,e,h);n.push({vertexId:g.id,vertex:g,weightedDegree:h,riskScore:w,reason:y,suggestions:v})}}return n.sort((g,h)=>h.riskScore-g.riskScore),n}getMinCutValue(e){if(e.isEmpty())return 0;let t=1/0;for(let r of e.getVertexIds()){let n=e.weightedDegree(r);n<t&&(t=n)}return t===1/0?0:t}isConnectivityCritical(e,t){return this.getMinCutValue(e)<t}getMinDegreeVertex(e){if(e.isEmpty())return null;let t=1/0,r=null;for(let n of e.getVertexIds()){let i=e.weightedDegree(n);i<t&&(t=i,r=n)}return r?{vertexId:r,degree:t}:null}getLocalMinCut(e,t){return e.hasVertex(t)?e.weightedDegree(t):0}findPartitioningPoints(e){if(e.isEmpty()||e.vertexCount<2)return[];let t=this.findArticulationPoints(e),r=[];for(let n of e.getVertices()){let i=this.getLocalMinCut(e,n.id);r.push({vertexId:n.id,localMinCut:i,wouldDisconnect:t.has(n.id)&&e.vertexCount>2})}return r.sort((n,i)=>n.localMinCut-i.localMinCut),r}findArticulationPoints(e){let t=new Map,r=new Map,n=new Map,i=new Set,a=0,o=e.getVertexIds();for(let s of o)t.set(s,-1),r.set(s,-1),n.set(s,null);let c=s=>{let d=0;t.set(s,a),r.set(s,a),a++;for(let u of e.neighborIds(s))t.get(u)===-1?(d++,n.set(u,s),c(u),r.set(s,Math.min(r.get(s),r.get(u))),n.get(s)===null&&d>1&&i.add(s),n.get(s)!==null&&r.get(u)>=t.get(s)&&i.add(s)):u!==n.get(s)&&r.set(s,Math.min(r.get(s),t.get(u)))};for(let s of o)t.get(s)===-1&&c(s);return i}suggestEdgeAdditions(e,t){let r=this.findWeakVertices(e),n=[],i=0,a=e.getVertices().map(o=>({vertex:o,degree:e.weightedDegree(o.id)})).sort((o,c)=>c.degree-o.degree);for(let o of r){if(i>=t)break;let c=new Set(e.neighborIds(o.vertexId));for(let{vertex:s}of a){if(s.id===o.vertexId||c.has(s.id))continue;let d={source:o.vertexId,target:s.id,weight:1,type:"coordination",bidirectional:!0};n.push(d),i+=1;break}}return n}emptyResult(e,t){return{value:0,sourceSide:[],targetSide:[],cutEdges:[],calculatedAt:new Date,algorithm:t,durationMs:Date.now()-e}}calculateRiskScore(e,t,r,n){if(r===0)return .5;let i=(t-e)/r,a=1/(1+Math.exp(-i)),o=n>0?n/e:1;return Math.min(1,a*o)}determineWeakReason(e,t,r,n){return t===0?"Isolated vertex with no connections":n.degree(e.id)===1?"Single connection point (leaf node)":t<r*.5?`Low connectivity (${(t/r*100).toFixed(0)}% of average)`:"Below average connectivity threshold"}generateStrengtheningActions(e,t,r){let n=[],i=new Set(t.neighborIds(e.id)),a=t.getStats().averageDegree,o=Math.max(a,3),c=Math.ceil(o-r),s=t.getVertices().filter(d=>d.id!==e.id&&!i.has(d.id)).sort((d,u)=>t.weightedDegree(u.id)-t.weightedDegree(d.id)).slice(0,c);for(let d of s)n.push({type:"add_edge",targetVertex:d.id,priority:"high",estimatedImprovement:1});return e.type==="agent"&&e.domain&&r<1&&n.push({type:"spawn_agent",domain:e.domain,priority:"critical",estimatedImprovement:2}),i.size>0&&i.size<3&&n.push({type:"increase_weight",weightDelta:.5,priority:"medium",estimatedImprovement:.5*i.size}),n}};function p(){return new l}var f=class m{vertices=new Map;edges=new Map;adjacencyList=new Map;totalWeight=0;addVertex(e){if(this.vertices.has(e.id)){this.vertices.set(e.id,e);return}this.vertices.set(e.id,e),this.adjacencyList.set(e.id,[])}removeVertex(e){if(!this.vertices.has(e))return!1;let t=this.adjacencyList.get(e)||[];for(let r of t)this.removeEdge(e,r.neighborId);for(let[,r]of this.adjacencyList){let n=r.findIndex(i=>i.neighborId===e);n!==-1&&(this.totalWeight-=r[n].weight,r.splice(n,1))}return this.vertices.delete(e),this.adjacencyList.delete(e),!0}getVertex(e){return this.vertices.get(e)}hasVertex(e){return this.vertices.has(e)}getVertices(){return Array.from(this.vertices.values())}getVertexIds(){return Array.from(this.vertices.keys())}getVerticesByDomain(e){return this.getVertices().filter(t=>t.domain===e)}getVerticesByType(e){return this.getVertices().filter(t=>t.type===e)}addEdge(e){if(!this.vertices.has(e.source))throw new Error(`Source vertex ${e.source} does not exist`);if(!this.vertices.has(e.target))throw new Error(`Target vertex ${e.target} does not exist`);let t=this.edgeKey(e.source,e.target);if(this.edges.has(t)){let r=this.edges.get(t);this.totalWeight-=r.weight,this.removeFromAdjacency(e.source,e.target),r.bidirectional&&this.removeFromAdjacency(e.target,e.source)}this.edges.set(t,e),this.totalWeight+=e.weight,this.addToAdjacency(e.source,e.target,e.weight,e),e.bidirectional&&this.addToAdjacency(e.target,e.source,e.weight,e)}removeEdge(e,t){let r=this.edgeKey(e,t),n=this.edges.get(r);return n?(this.totalWeight-=n.weight,this.edges.delete(r),this.removeFromAdjacency(e,t),n.bidirectional&&this.removeFromAdjacency(t,e),!0):!1}getEdge(e,t){return this.edges.get(this.edgeKey(e,t))}hasEdge(e,t){return this.edges.has(this.edgeKey(e,t))}getEdges(){return Array.from(this.edges.values())}getEdgesForVertex(e){return(this.adjacencyList.get(e)||[]).map(r=>r.edge)}degree(e){return this.adjacencyList.get(e)?.length||0}weightedDegree(e){let t=this.adjacencyList.get(e);return t?t.reduce((r,n)=>r+n.weight,0):0}neighbors(e){return(this.adjacencyList.get(e)||[]).map(r=>({vertex:this.vertices.get(r.neighborId),weight:r.weight})).filter(r=>r.vertex!==void 0)}neighborIds(e){return(this.adjacencyList.get(e)||[]).map(r=>r.neighborId)}getStats(){let e=this.vertices.size,t=this.edges.size,r=0;for(let[,s]of this.adjacencyList)r+=s.length;let n=e>0?r/e:0,i=e>1?e*(e-1)/2:0,a=i>0?t/i:0,o=this.countConnectedComponents(),c=o===1&&e>0;return{vertexCount:e,edgeCount:t,totalWeight:this.totalWeight,averageDegree:n,density:a,isConnected:c,componentCount:o}}countConnectedComponents(){let e=new Set,t=0;for(let r of this.vertices.keys())e.has(r)||(this.dfs(r,e),t++);return t}dfs(e,t){t.add(e);let r=this.adjacencyList.get(e)||[];for(let n of r)t.has(n.neighborId)||this.dfs(n.neighborId,t)}isConnected(){if(this.vertices.size===0||this.vertices.size===1)return!0;let e=new Set,t=this.vertices.keys().next().value;return t===void 0?!0:(this.dfs(t,e),e.size===this.vertices.size)}getConnectedComponent(e){if(!this.vertices.has(e))return[];let t=new Set;return this.dfs(e,t),Array.from(t)}snapshot(){return{timestamp:new Date,vertices:this.getVertices(),edges:this.getEdges(),stats:this.getStats()}}clone(){let e=new m;for(let t of this.vertices.values())e.addVertex({...t});for(let t of this.edges.values())e.addEdge({...t});return e}static fromSnapshot(e){let t=new m;for(let r of e.vertices)t.addVertex(r);for(let r of e.edges)t.addEdge(r);return t}clear(){this.vertices.clear(),this.edges.clear(),this.adjacencyList.clear(),this.totalWeight=0}get vertexCount(){return this.vertices.size}get edgeCount(){return this.edges.size}isEmpty(){return this.vertices.size===0}edgeKey(e,t){return e<t?`${e}:${t}`:`${t}:${e}`}addToAdjacency(e,t,r,n){let i=this.adjacencyList.get(e);i&&(i.find(o=>o.neighborId===t)||i.push({neighborId:t,weight:r,edge:n}))}removeFromAdjacency(e,t){let r=this.adjacencyList.get(e);if(r){let n=r.findIndex(i=>i.neighborId===t);n!==-1&&r.splice(n,1)}}};function x(){return new f}export{l as a,p as b,f as c,x as d};
@@ -0,0 +1,81 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{a as D}from"./chunk-BGXNSCXX.js";import{c as x,d as $}from"./chunk-YR6ZZGH7.js";import{a as j}from"./chunk-RU5WAHB7.js";import"./chunk-3ZOONQG6.js";import"./chunk-4I2IOUS4.js";import{Command as U}from"commander";import o from"chalk";import*as I from"fs";import*as p from"path";import*as F from"fs";import*as R from"path";var P={version:"1",name:"aqe-ci",phases:[{name:"Test Generation",type:"test",enabled:!0,config:{target:".",framework:"vitest",type:"unit"},continueOnFailure:!1,timeout:300},{name:"Coverage Analysis",type:"coverage",enabled:!0,config:{target:".",threshold:80},continueOnFailure:!0,timeout:300},{name:"Security Scan",type:"security",enabled:!0,config:{sast:!0},continueOnFailure:!0,timeout:300},{name:"Quality Gate",type:"quality-gate",enabled:!0,config:{},continueOnFailure:!1,timeout:60}],output:{format:"json",directory:".aqe-ci-output",combinedReport:!0},qualityGate:{enforced:!0,thresholds:{coverage:80,security:"medium",quality:70}}},Q=[".aqe-ci.yml",".aqe-ci.yaml","aqe-ci.yml","aqe-ci.yaml"];function G(s=process.cwd()){let n=R.resolve(s);for(let r=0;r<10;r++){for(let a of Q){let e=R.join(n,a);if(F.existsSync(e))return e}let l=R.dirname(n);if(l===n)break;n=l}return null}function T(s){if(!F.existsSync(s))return{success:!1,errors:[`Config file not found: ${s}`]};let n;try{n=F.readFileSync(s,"utf-8")}catch(r){return{success:!1,errors:[`Failed to read config: ${r}`]}}return N(n,s)}function N(s,n){let r=[],l;try{l=j(s)}catch(e){return{success:!1,errors:[`Invalid YAML: ${e}`]}}let a={version:l.version||P.version,name:l.name||P.name,phases:[],output:{...P.output},qualityGate:{...P.qualityGate,thresholds:{...P.qualityGate.thresholds}}};if(l.output&&typeof l.output=="object"){let e=l.output;e.format&&(a.output.format=e.format),e.directory&&(a.output.directory=e.directory),e.combined_report!==void 0&&(a.output.combinedReport=e.combined_report)}if(l.quality_gate&&typeof l.quality_gate=="object"){let e=l.quality_gate;if(e.enforced!==void 0&&(a.qualityGate.enforced=e.enforced),e.thresholds&&typeof e.thresholds=="object"){let t=e.thresholds;t.coverage!==void 0&&(a.qualityGate.thresholds.coverage=t.coverage),t.security!==void 0&&(a.qualityGate.thresholds.security=t.security),t.quality!==void 0&&(a.qualityGate.thresholds.quality=t.quality)}}if(l.phases&&Array.isArray(l.phases))for(let e=0;e<l.phases.length;e++){let t=l.phases[e];if(!t.name){r.push(`Phase ${e+1} must have a "name" field`);continue}if(!t.type){r.push(`Phase "${t.name}" must have a "type" field`);continue}let i=["test","coverage","security","quality-gate","code-intelligence","custom"];if(!i.includes(t.type)){r.push(`Phase "${t.name}" has invalid type "${t.type}". Valid: ${i.join(", ")}`);continue}let h={name:t.name,type:t.type,enabled:t.enabled!==!1,config:t.config||{},continueOnFailure:t.continue_on_failure||!1,timeout:t.timeout||300};a.phases.push(h)}else a.phases=[...P.phases];return a.phases.length===0&&r.push("Config must have at least one phase"),r.length>0?{success:!1,config:a,errors:r}:{success:!0,config:a,errors:[],configPath:n}}function E(){return{...P,phases:P.phases.map(s=>({...s,config:{...s.config}})),output:{...P.output},qualityGate:{...P.qualityGate,thresholds:{...P.qualityGate.thresholds}}}}async function W(s,n,r,l){let a=Date.now(),e=[];if(!s.enabled)return{phase:s.name,type:s.type,status:"skipped",duration:0,exitCode:0,summary:"Phase disabled",artifacts:[]};try{let t={},i="passed",h="";switch(s.type){case"test":{let f=await n.kernel.getDomainAPIAsync("test-generation");if(!f)return A(s,a,"failed",1,"Test generation domain not available",e);let C=s.config.target||".",{walkSourceFiles:m}=await import("./file-discovery-QFPA6GMV.js"),w=p.resolve(C),v=m(w,{includeTests:!1}),y=await f.generateTests({sourceFiles:v,testType:s.config.type||"unit",framework:s.config.framework||"vitest",coverageTarget:80});if(y.success&&y.value){let g=y.value;t={testsGenerated:g.tests.length,coverageEstimate:g.coverageEstimate},h=`Generated ${g.tests.length} tests (est. ${g.coverageEstimate}% coverage)`;let d=p.join(r,"test-generation.json");I.writeFileSync(d,$(g),"utf-8"),e.push(d)}else i="failed",h=y.error?.message||"Test generation failed";break}case"coverage":{let f=await n.kernel.getDomainAPIAsync("coverage-analysis");if(!f)return A(s,a,"failed",1,"Coverage analysis domain not available",e);let C=s.config.target||".",m=s.config.threshold||80,{walkSourceFiles:w}=await import("./file-discovery-QFPA6GMV.js"),v=p.resolve(C),y=w(v,{includeTests:!1}),g=D(y),d=await f.analyze({coverageData:g,threshold:m,includeFileDetails:!0});if(d.success&&d.value){let b=d.value;t={...b.summary,meetsThreshold:b.meetsThreshold,threshold:m},i=b.meetsThreshold?"passed":"warning",h=`Line: ${b.summary.line}%, Branch: ${b.summary.branch}% \u2014 ${b.meetsThreshold?"meets":"below"} ${m}% threshold`;let q=p.join(r,"coverage.json");I.writeFileSync(q,$(d.value),"utf-8"),e.push(q)}else i="failed",h=d.error?.message||"Coverage analysis failed";break}case"security":{let f=await n.kernel.getDomainAPIAsync("security-compliance");if(!f)return A(s,a,"failed",1,"Security domain not available",e);let C=s.config.target||".",{walkSourceFiles:m}=await import("./file-discovery-QFPA6GMV.js"),w=p.resolve(C),v=m(w,{includeTests:!0}),y=await f.runSASTScan(v);if(y.success&&y.value){let g=y.value,d=g.vulnerabilities||[],b=d.filter(S=>S.severity==="high"||S.severity==="critical").length;t={vulnerabilities:d.length,high:b},i=b>0?"failed":d.length>0?"warning":"passed",h=d.length===0?"No vulnerabilities found":`${d.length} vulnerabilities (${b} high/critical)`;let{toSARIF:q}=await import("./ci-output-7JN7F6CI.js"),c=p.join(r,"security.sarif");I.writeFileSync(c,q({vulnerabilities:d,target:C,scanType:"SAST"}),"utf-8"),e.push(c);let u=p.join(r,"security.json");I.writeFileSync(u,$(g),"utf-8"),e.push(u)}else i="failed",h=y.error?.message||"Security scan failed";break}case"quality-gate":{let f=await n.kernel.getDomainAPIAsync("quality-assessment");if(!f)return A(s,a,"failed",1,"Quality assessment domain not available",e);let C=await f.evaluate({runGate:!0,includeAdvice:!0});if(C.success&&C.value){let m=C.value,w=m.passed??m.meetsThreshold??!0;t={passed:w,score:m.score||m.grade,checks:m.checks},i=w?"passed":"failed",h=`Quality gate: ${w?"PASSED":"FAILED"} (score: ${m.score||m.grade||"N/A"})`;let v=p.join(r,"quality-gate.json");I.writeFileSync(v,$(m),"utf-8"),e.push(v)}else i="failed",h=C.error?.message||"Quality gate evaluation failed";break}case"code-intelligence":{let f=await n.kernel.getDomainAPIAsync("code-intelligence");if(!f)return A(s,a,"failed",1,"Code intelligence domain not available",e);let C=s.config.target||".",{walkSourceFiles:m}=await import("./file-discovery-QFPA6GMV.js"),w=p.resolve(C),v=m(w,{includeTests:!1}),y=await f.index({paths:v,incremental:!0});if(y.success&&y.value){let g=y.value;t=g,h=`Indexed ${g.filesIndexed} files, ${g.nodesCreated} nodes`;let d=p.join(r,"code-intelligence.json");I.writeFileSync(d,$(g),"utf-8"),e.push(d)}else i="warning",h=y.error?.message||"Code intelligence indexing incomplete";break}default:h=`Custom phase "${s.name}" \u2014 no built-in handler`,i="warning"}let k=Date.now()-a;return{phase:s.name,type:s.type,status:i,duration:k,exitCode:i==="failed"?1:0,summary:h,artifacts:e,details:t}}catch(t){let i=Date.now()-a;return{phase:s.name,type:s.type,status:"failed",duration:i,exitCode:1,summary:`Error: ${t instanceof Error?t.message:String(t)}`,artifacts:e}}}function A(s,n,r,l,a,e){return{phase:s.name,type:s.type,status:r,duration:Date.now()-n,exitCode:l,summary:a,artifacts:e}}function _(s){let n=`# AQE CI/CD Report
3
+
4
+ `;n+=`**Status:** ${s.overallStatus==="passed"?"PASSED":s.overallStatus==="warning"?"WARNING":"FAILED"}
5
+ `,n+=`**Duration:** ${(s.duration/1e3).toFixed(1)}s
6
+ `,n+=`**Quality Gate:** ${s.qualityGatePassed?"Passed":"Failed"}
7
+
8
+ `,n+=`## Phases
9
+
10
+ `,n+=`| Phase | Type | Status | Duration | Summary |
11
+ `,n+=`|-------|------|--------|----------|---------|
12
+ `;for(let r of s.phases){let l=r.status==="passed"?"PASS":r.status==="failed"?"FAIL":r.status==="warning"?"WARN":"SKIP";n+=`| ${r.phase} | ${r.type} | ${l} | ${(r.duration/1e3).toFixed(1)}s | ${r.summary} |
13
+ `}n+=`
14
+ ## Artifacts
15
+
16
+ `;for(let r of s.phases)if(r.artifacts.length>0){n+=`### ${r.phase}
17
+ `;for(let l of r.artifacts)n+=`- \`${p.basename(l)}\`
18
+ `;n+=`
19
+ `}return n}function H(s,n,r){let l=new U("ci").description("CI/CD pipeline orchestration");return l.command("run").description("Execute CI pipeline from .aqe-ci.yml").option("-c, --config <path>","Path to .aqe-ci.yml config file").option("--phase <phases>","Run only specific phases (comma-separated)").option("--no-quality-gate","Skip quality gate enforcement").option("-F, --format <format>","Output format (text|json|markdown)","text").option("-o, --output <path>","Write combined report to file").action(async a=>{if(await r())try{let e,t=null;if(a.config){let c=T(p.resolve(a.config));if(!c.success){console.error(o.red(`
20
+ Config errors:`));for(let u of c.errors)console.error(o.red(` - ${u}`));await n(1);return}e=c.config,t=a.config}else if(t=G(),t){let c=T(t);if(!c.success){console.error(o.red(`
21
+ Config errors:`));for(let u of c.errors)console.error(o.red(` - ${u}`));await n(1);return}e=c.config}else e=E(),t="(defaults)";if(a.phase){let c=a.phase.split(",").map(u=>u.trim().toLowerCase());e.phases=e.phases.filter(u=>c.includes(u.name.toLowerCase())||c.includes(u.type))}a.qualityGate===!1&&(e.qualityGate.enforced=!1);let i=a.format,h=new Date;i==="text"&&(console.log(o.blue(`
22
+ AQE CI Pipeline
23
+ `)),console.log(o.gray(` Config: ${t}`)),console.log(o.gray(` Phases: ${e.phases.length}`)),console.log(o.gray(` Quality Gate: ${e.qualityGate.enforced?"enforced":"advisory"}
24
+ `)));let k=p.resolve(e.output.directory);I.mkdirSync(k,{recursive:!0});let f=[],C=!1;for(let c of e.phases){if(i==="text"){let S=` [${f.length+1}/${e.phases.length}] ${c.name}...`;process.stdout.write(o.cyan(S))}let u=await W(c,s,k,e.output.format);if(f.push(u),i==="text"){let S=u.status==="passed"?o.green:u.status==="failed"?o.red:u.status==="warning"?o.yellow:o.gray,O=u.status.toUpperCase(),L=`${(u.duration/1e3).toFixed(1)}s`;process.stdout.write(`\r [${f.length}/${e.phases.length}] ${c.name} ${S(O)} (${L})
25
+ `),u.summary&&console.log(o.gray(` ${u.summary}`))}if(u.status==="failed"&&(C=!0,!c.continueOnFailure)){i==="text"&&console.log(o.red(`
26
+ Pipeline stopped: "${c.name}" failed (continue_on_failure: false)
27
+ `));break}}let m=f.some(c=>c.status==="failed"),w=f.some(c=>c.status==="warning"),v=f.find(c=>c.type==="quality-gate"),y=!e.qualityGate.enforced||!v||v.status==="passed",g=m||!y?"failed":w?"warning":"passed",d=new Date,b=d.getTime()-h.getTime(),q={config:t||"(defaults)",startedAt:h,completedAt:d,duration:b,phases:f,qualityGatePassed:y,overallStatus:g,exitCode:g==="failed"?1:0};if(e.output.combinedReport){let c=p.join(k,"ci-report.md");I.writeFileSync(c,_(q),"utf-8");let u=p.join(k,"ci-report.json");I.writeFileSync(u,$(q),"utf-8")}if(i==="json")x($(q),a.output);else if(i==="markdown")x(_(q),a.output);else{console.log("");let c=g==="passed"?o.green:g==="failed"?o.red:o.yellow;console.log(` ${c(`Pipeline: ${g.toUpperCase()}`)} (${(b/1e3).toFixed(1)}s)`),console.log(` Quality Gate: ${y?o.green("PASSED"):o.red("FAILED")}`),console.log(o.gray(` Artifacts: ${k}/`)),console.log("")}await n(q.exitCode)}catch(e){console.error(o.red(`
28
+ CI pipeline failed:`),e),await n(1)}}),l.command("init").description("Create a .aqe-ci.yml config file").option("--force","Overwrite existing config").action(async a=>{let e=G();if(e&&!a.force){console.log(o.yellow(`
29
+ Config already exists: ${e}`)),console.log(o.gray(` Use --force to overwrite
30
+ `)),await n(0);return}let t=`# AQE CI/CD Pipeline Configuration
31
+ # Documentation: https://github.com/proffesor-for-testing/agentic-qe
32
+
33
+ version: '1'
34
+ name: ${p.basename(process.cwd())}
35
+
36
+ phases:
37
+ - name: Test Generation
38
+ type: test
39
+ config:
40
+ target: .
41
+ framework: vitest
42
+ type: unit
43
+ timeout: 300
44
+
45
+ - name: Coverage Analysis
46
+ type: coverage
47
+ continue_on_failure: true
48
+ config:
49
+ target: .
50
+ threshold: 80
51
+ timeout: 300
52
+
53
+ - name: Security Scan
54
+ type: security
55
+ continue_on_failure: true
56
+ config:
57
+ sast: true
58
+ timeout: 300
59
+
60
+ - name: Quality Gate
61
+ type: quality-gate
62
+ timeout: 60
63
+
64
+ output:
65
+ format: json
66
+ directory: .aqe-ci-output
67
+ combined_report: true
68
+
69
+ quality_gate:
70
+ enforced: true
71
+ thresholds:
72
+ coverage: 80
73
+ security: medium
74
+ quality: 70
75
+ `,i=p.join(process.cwd(),".aqe-ci.yml");I.writeFileSync(i,t,"utf-8"),console.log(o.green(`
76
+ Created: ${i}`)),console.log(o.gray(" Edit the file to customize your CI pipeline")),console.log(o.gray(` Run: aqe ci run
77
+ `)),await n(0)}),l.command("validate").description("Validate .aqe-ci.yml config").option("-c, --config <path>","Path to config file").action(async a=>{let e=a.config?p.resolve(a.config):G();if(!e){console.log(o.red(`
78
+ No .aqe-ci.yml found`)),console.log(o.gray(` Run: aqe ci init
79
+ `)),await n(1);return}let t=T(e);if(t.success){console.log(o.green(`
80
+ Config valid: ${e}`)),console.log(o.gray(` Phases: ${t.config.phases.length}`));for(let i of t.config.phases){let h=i.enabled?o.green("*"):o.gray("o");console.log(` ${h} ${i.name} (${i.type})`)}console.log(o.gray(` Quality Gate: ${t.config.qualityGate.enforced?"enforced":"advisory"}`)),console.log(""),await n(0)}else{console.log(o.red(`
81
+ Config invalid: ${e}`));for(let i of t.errors)console.log(o.red(` - ${i}`));console.log(""),await n(1)}}),l}export{H as createCICommand};
@@ -0,0 +1,2 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{a,b,c,d,e,f,g,h,i,j}from"./chunk-YR6ZZGH7.js";import"./chunk-4I2IOUS4.js";export{a as FORMAT_OPTION,b as OUTPUT_OPTION,g as coverageToMarkdown,h as qualityGateToMarkdown,i as securityToMarkdown,j as testRunToMarkdown,d as toJSON,f as toJUnit,e as toSARIF,c as writeOutput};
@@ -0,0 +1,2 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{b as p}from"./chunk-XO6PVK2P.js";import{b as f,d as h}from"./chunk-WGMPEW2T.js";import{a as c,c as b}from"./chunk-JZSDOIXA.js";import{a as v}from"./chunk-4I2IOUS4.js";h();b();import{existsSync as u,writeFileSync as g,readFileSync as m}from"node:fs";import{join as a}from"node:path";import{execSync as C}from"node:child_process";async function y(t,e){let o=p(t);if(e&&o.available&&console.log(`[ClaudeFlow] Detected via ${o.method}${o.version?`: v${o.version}`:""}`),!o.available)return{available:!1};let n={"mcp-config":"mcp","local-binary":"cli","npx-cached":"cli","npm-dependency":"npm"};return{available:!0,version:o.version,method:o.method?n[o.method]:void 0}}async function F(t){return{trajectories:!0,modelRouting:!0,pretrain:!0,workers:!0,patternSearch:!0}}function S(t,e){return{version:"1.0",projectRoot:t,integration:{enabled:!0,features:{trajectories:e.trajectories,modelRouting:e.modelRouting,pretrain:e.pretrain,workers:e.workers}},learning:{trajectoryStorage:e.trajectories?"claude-flow":"local",patternSearch:e.patternSearch?"claude-flow":"local"},routing:{modelRouting:e.modelRouting?"claude-flow":"rule-based",preferences:{simple:"haiku",standard:"sonnet",complex:"opus"}},pretrain:{enabled:e.pretrain,depth:"medium",autoRun:!0},workers:{enabled:e.workers,autoDispatch:["optimize","consolidate"]}}}function R(t){let e=a(t,".claude","settings.json"),o={};if(u(e))try{o=f(m(e,"utf-8"))}catch{}o.mcpServers||(o.mcpServers={});let n=o.mcpServers;!n.ruflo&&!n["claude-flow"]&&(n.ruflo={command:"npx",args:["ruflo@3.5.18","mcp"],env:{}}),g(e,JSON.stringify(o,null,2))}async function j(t,e){try{e&&console.log("[ClaudeFlow] Running pretrain analysis..."),C("npx --no-install ruflo hooks pretrain --depth medium",{encoding:"utf-8",timeout:12e4,cwd:t,stdio:["pipe","pipe","pipe"]}),e&&console.log("[ClaudeFlow] Pretrain analysis complete")}catch(o){e&&console.log("[ClaudeFlow] Pretrain analysis skipped:",c(o))}}async function D(t){let{projectRoot:e,force:o,checkOnly:n,debug:s}=t,r=await y(e,s);if(!r.available&&!o)return{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,workers:!1,patternSearch:!1}};let i=await F(e);if(n)return{available:r.available,version:r.version,features:i};let w=a(e,".agentic-qe"),d=a(w,"claude-flow-integration.json");try{let l=S(e,i);g(d,JSON.stringify(l,null,2)),s&&console.log(`[ClaudeFlow] Config written to: ${d}`)}catch(l){return{available:r.available,version:r.version,features:i,error:`Failed to write config: ${c(l)}`}}try{R(e)}catch(l){s&&console.log("[ClaudeFlow] MCP config update failed:",c(l))}return i.pretrain&&await j(e,s),{available:!0,version:r.version,features:i,configPath:d}}function J(t){let e=a(t,".agentic-qe","claude-flow-integration.json");return u(e)}function N(t){let e=a(t,".agentic-qe","claude-flow-integration.json");if(!u(e))return null;try{return f(m(e,"utf-8"))}catch{return null}}function I(t){let e=a(t,".agentic-qe","claude-flow-integration.json");if(u(e))try{return v("node:fs").rmSync(e),!0}catch{return!1}return!0}export{N as getClaudeFlowConfig,J as isClaudeFlowConfigured,I as removeClaudeFlowIntegration,D as setupClaudeFlowIntegration};
@@ -0,0 +1,2 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{c as a,d as b,e as c}from"./chunk-3IHG3WOY.js";import"./chunk-OI5NGQO2.js";import"./chunk-JZSDOIXA.js";import"./chunk-4I2IOUS4.js";c();export{a as VibiumClientImpl,b as VibiumClientProvider};
@@ -0,0 +1,4 @@
1
+ if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
+ import{b as p}from"./chunk-4YOMLWEK.js";import{a as f,c as v}from"./chunk-JZSDOIXA.js";import"./chunk-4I2IOUS4.js";v();import{existsSync as s,mkdirSync as m,readFileSync as u,writeFileSync as a}from"fs";import{join as h,dirname as d}from"path";var l=class{projectRoot;overwrite;generator;constructor(r){this.projectRoot=r.projectRoot,this.overwrite=r.overwrite??!1,this.generator=p()}async install(){let r={success:!0,mcpConfigured:!1,modeInstalled:!1,errors:[],configPath:"",modePath:""};try{let t=this.generator.generateMcpConfig("cline"),e=h(this.projectRoot,t.path);if(r.configPath=e,!s(e)||this.overwrite){let o=d(e);if(s(o)||m(o,{recursive:!0}),s(e)&&this.overwrite){let c=this.mergeExistingConfig(e,t.content);a(e,c)}else a(e,t.content);r.mcpConfigured=!0}let n=this.generator.generateBehavioralRules("cline"),i=h(this.projectRoot,n.path);if(r.modePath=i,!s(i)||this.overwrite){let o=d(i);if(s(o)||m(o,{recursive:!0}),s(i)&&this.overwrite){let c=this.mergeExistingModes(i,n.content);a(i,c)}else a(i,n.content);r.modeInstalled=!0}}catch(t){r.success=!1,r.errors.push(`Cline installation failed: ${f(t)}`)}return r}mergeExistingConfig(r,t){try{let e=JSON.parse(u(r,"utf-8")),n=JSON.parse(t);return e.mcpServers||(e.mcpServers={}),Object.assign(e.mcpServers,n.mcpServers),JSON.stringify(e,null,2)+`
3
+ `}catch{return t}}mergeExistingModes(r,t){try{let e=JSON.parse(u(r,"utf-8")),n=JSON.parse(t);if(!Array.isArray(e))return t;let i=e.filter(o=>o.slug!=="qe-engineer");return i.push(...n),JSON.stringify(i,null,2)+`
4
+ `}catch{return t}}};function x(g){return new l(g)}export{l as ClineInstaller,x as createClineInstaller};