agentic-qe 3.14.4 → 3.14.5

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 (403) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +93 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/audit/witness-chain.d.ts +1 -1
  5. package/dist/audit/witness-chain.js +29 -22
  6. package/dist/cli/bundle.js +13 -10
  7. package/dist/cli/chunks/adapter-IYC62SXA.js +2 -0
  8. package/dist/cli/chunks/{agent-booster-wasm-5PC7D2FW.js → agent-booster-wasm-EDNKP3SP.js} +2 -2
  9. package/dist/cli/chunks/{agent-handler-RDNTK4CA.js → agent-handler-V6CZ7Q6S.js} +2 -2
  10. package/dist/cli/chunks/{agent-memory-branch-NAAMBWIR.js → agent-memory-branch-ZMD6ULC3.js} +2 -2
  11. package/dist/cli/chunks/aqe-learning-engine-LLOU2IXD.js +2 -0
  12. package/dist/cli/chunks/{arena-HXTWJ5YY.js → arena-4UPAEHFT.js} +4 -4
  13. package/dist/cli/chunks/{arena-KXFHRWX4.js → arena-QLSBESC7.js} +2 -2
  14. package/dist/cli/chunks/{audit-YSGA7UWT.js → audit-CVZQMF55.js} +3 -3
  15. package/dist/cli/chunks/base-P3Z4IKCT.js +2 -0
  16. package/dist/cli/chunks/{better-sqlite3-UICJZIDG.js → better-sqlite3-4DSBPDRH.js} +2 -2
  17. package/dist/cli/chunks/brain-handler-GBY4EZ4P.js +94 -0
  18. package/dist/cli/chunks/{branch-enumerator-SS7UNVIA.js → branch-enumerator-XYBVXCNO.js} +2 -2
  19. package/dist/cli/chunks/{browser-77GI6KBE.js → browser-32F6MREU.js} +2 -2
  20. package/dist/cli/chunks/browser-workflow-YYHQQ25X.js +2 -0
  21. package/dist/cli/chunks/{chunk-FGYMFUE2.js → chunk-2JGEZHWY.js} +2 -2
  22. package/dist/cli/chunks/{chunk-MOBNBMFW.js → chunk-2KJQ2UQE.js} +1 -1
  23. package/dist/cli/chunks/{chunk-C2WU3533.js → chunk-2OMLTYQK.js} +1 -1
  24. package/dist/cli/chunks/{chunk-CU46J64M.js → chunk-37TUN44F.js} +2 -2
  25. package/dist/cli/chunks/{chunk-Z3RHREWF.js → chunk-3DDXWYMO.js} +1 -1
  26. package/dist/cli/chunks/{chunk-Q5DO24IJ.js → chunk-3EZ5DR2R.js} +3 -3
  27. package/dist/cli/chunks/{chunk-WLG5AJ4N.js → chunk-3KDL6QDK.js} +2 -2
  28. package/dist/cli/chunks/{chunk-MTZH7AHC.js → chunk-3VIXOHMS.js} +1 -1
  29. package/dist/cli/chunks/{chunk-ISDMD6EU.js → chunk-3YUB5HER.js} +96 -96
  30. package/dist/cli/chunks/{chunk-CDKG6EI7.js → chunk-4FWTLJEP.js} +2 -2
  31. package/dist/cli/chunks/{chunk-HDSAM2RE.js → chunk-52L77RMG.js} +2 -2
  32. package/dist/cli/chunks/{chunk-MEGDYJPV.js → chunk-5D36YHS3.js} +4 -4
  33. package/dist/cli/chunks/{chunk-T6BVLVI5.js → chunk-5WOSWNDN.js} +1 -1
  34. package/dist/cli/chunks/{chunk-M2JBBZQB.js → chunk-67YV75XP.js} +2 -2
  35. package/dist/cli/chunks/{chunk-KHFNNVJA.js → chunk-6A44AOGN.js} +2 -2
  36. package/dist/cli/chunks/{chunk-IPR4QP3H.js → chunk-6CR4VQBQ.js} +2 -2
  37. package/dist/cli/chunks/{chunk-XRT2WRMS.js → chunk-6ITZZIQX.js} +2 -2
  38. package/dist/cli/chunks/{chunk-4OYFXLBK.js → chunk-6LKDHEBY.js} +2 -2
  39. package/dist/cli/chunks/{chunk-FLYOJOKN.js → chunk-6TU7FEMD.js} +1 -1
  40. package/dist/cli/chunks/{chunk-6QYNWR7U.js → chunk-6VAZAHQG.js} +2 -2
  41. package/dist/cli/chunks/{chunk-TWAWHOP7.js → chunk-73EI4C2E.js} +2 -2
  42. package/dist/cli/chunks/{chunk-5R3QL7WN.js → chunk-75QJ5HWE.js} +2 -2
  43. package/dist/cli/chunks/{chunk-Y3MW3YBC.js → chunk-7CD7PBHY.js} +2 -2
  44. package/dist/cli/chunks/chunk-7DETTOPZ.js +14 -0
  45. package/dist/cli/chunks/{chunk-KSKEF7LZ.js → chunk-7JZJJA7U.js} +3 -3
  46. package/dist/cli/chunks/{chunk-AIHDEEJO.js → chunk-7VFY7TUR.js} +2 -2
  47. package/dist/cli/chunks/chunk-7X7JYWT4.js +27 -0
  48. package/dist/cli/chunks/chunk-AF4XKLXO.js +2 -0
  49. package/dist/cli/chunks/{chunk-6KJABXAR.js → chunk-AFEDJ3RU.js} +2 -2
  50. package/dist/cli/chunks/{chunk-5SJHQ2CO.js → chunk-AMMQOV35.js} +2 -2
  51. package/dist/cli/chunks/{chunk-6VRA2QGL.js → chunk-BHFR2EXL.js} +1 -1
  52. package/dist/cli/chunks/{chunk-ZBAKA4YB.js → chunk-BJPL6THQ.js} +1 -1
  53. package/dist/cli/chunks/{chunk-DOTK76IJ.js → chunk-BXVAVFGU.js} +2 -2
  54. package/dist/cli/chunks/{chunk-MNW6QGNJ.js → chunk-BYG36QC5.js} +2 -2
  55. package/dist/cli/chunks/chunk-C3HQL6S4.js +2 -0
  56. package/dist/cli/chunks/{chunk-PZJOPURC.js → chunk-C3Z4VVHP.js} +5 -5
  57. package/dist/cli/chunks/{chunk-OULHKEVH.js → chunk-CPC7FN52.js} +2 -2
  58. package/dist/cli/chunks/{chunk-BFP7KO7P.js → chunk-CVMNJSCB.js} +2 -2
  59. package/dist/cli/chunks/{chunk-AUXFKCQL.js → chunk-CYE2TJFV.js} +2 -2
  60. package/dist/cli/chunks/{chunk-7D777LTF.js → chunk-CZO4BJG5.js} +2 -2
  61. package/dist/cli/chunks/{chunk-VD6QRULW.js → chunk-D6OUCB2H.js} +2 -2
  62. package/dist/cli/chunks/{chunk-6UWGMOND.js → chunk-DDCIYOGT.js} +2 -2
  63. package/dist/cli/chunks/{chunk-STJCATGN.js → chunk-DKUBQQFG.js} +2 -2
  64. package/dist/cli/chunks/{chunk-M4WJKGVK.js → chunk-DLF5BOJD.js} +1 -1
  65. package/dist/cli/chunks/{chunk-DA5K5754.js → chunk-DO6EI5KB.js} +1 -1
  66. package/dist/cli/chunks/{chunk-BDESSCVR.js → chunk-DPBRWP4J.js} +3 -3
  67. package/dist/cli/chunks/{chunk-HV2J7KKQ.js → chunk-E3W6XQ57.js} +2 -2
  68. package/dist/cli/chunks/{chunk-MDWCE7YW.js → chunk-E4AZXCT5.js} +1 -1
  69. package/dist/cli/chunks/{chunk-F3SBRQC6.js → chunk-E4EYPYR3.js} +2 -2
  70. package/dist/cli/chunks/{chunk-55RWDRJD.js → chunk-EFV4ADMO.js} +4 -4
  71. package/dist/cli/chunks/{chunk-5YPYDPBJ.js → chunk-ELBZON4V.js} +2 -2
  72. package/dist/cli/chunks/{chunk-PO3IXGMQ.js → chunk-EOR2UT72.js} +2 -2
  73. package/dist/cli/chunks/{chunk-EDJ3O7RH.js → chunk-F34OAHOM.js} +2 -2
  74. package/dist/cli/chunks/{chunk-XRYF6JV7.js → chunk-FUNGTIF2.js} +2 -2
  75. package/dist/cli/chunks/{chunk-EKQ673SA.js → chunk-G3L5L6YQ.js} +1 -1
  76. package/dist/cli/chunks/{chunk-NJBGXDQ7.js → chunk-G3W6BMVJ.js} +1 -1
  77. package/dist/cli/chunks/{chunk-CIZ5JPDC.js → chunk-GTKCGPJZ.js} +3 -3
  78. package/dist/cli/chunks/{chunk-QGIU2WRL.js → chunk-HBCGYMQU.js} +1 -1
  79. package/dist/cli/chunks/{chunk-V3QLFNA2.js → chunk-HSVKZ5KI.js} +4 -4
  80. package/dist/cli/chunks/{chunk-BGE6FOLM.js → chunk-HVU64GP5.js} +2 -2
  81. package/dist/cli/chunks/chunk-HVXJC3OC.js +2 -0
  82. package/dist/cli/chunks/{chunk-MIQTXNBG.js → chunk-HYEJJJY3.js} +1 -1
  83. package/dist/cli/chunks/{chunk-CLTMDCSE.js → chunk-I2NENQ44.js} +2 -2
  84. package/dist/cli/chunks/{chunk-SGYJ4NFZ.js → chunk-I6X3EGJI.js} +1 -1
  85. package/dist/cli/chunks/{chunk-BOARZKU3.js → chunk-IGBEJ4UJ.js} +2 -2
  86. package/dist/cli/chunks/{chunk-FWGOHAAB.js → chunk-IIAR5S7Q.js} +2 -2
  87. package/dist/cli/chunks/{chunk-DHJPWQBR.js → chunk-IJHCIXJC.js} +2 -2
  88. package/dist/cli/chunks/{chunk-UEM7ZF5K.js → chunk-IUDWEOLX.js} +2 -2
  89. package/dist/cli/chunks/chunk-IUHB5GVS.js +3 -0
  90. package/dist/cli/chunks/{chunk-M5QUBZY6.js → chunk-IYTLXUBO.js} +2 -2
  91. package/dist/cli/chunks/chunk-J27F4NSB.js +2 -0
  92. package/dist/cli/chunks/{chunk-G6T45OIC.js → chunk-J5UNP6W3.js} +2 -2
  93. package/dist/cli/chunks/{chunk-3UPAMMCB.js → chunk-JES6R5KP.js} +1 -1
  94. package/dist/cli/chunks/{chunk-ZBQY5GLF.js → chunk-JROVR6YS.js} +2 -2
  95. package/dist/cli/chunks/chunk-JSZ663MU.js +2 -0
  96. package/dist/cli/chunks/{chunk-PFR4G3DJ.js → chunk-JVQBWYHW.js} +2 -2
  97. package/dist/cli/chunks/{chunk-JBNEE5UH.js → chunk-K27SU3RE.js} +2 -2
  98. package/dist/cli/chunks/{chunk-JZ3ORVZ3.js → chunk-K7NJHFLZ.js} +3 -3
  99. package/dist/cli/chunks/{chunk-3VOQRIQM.js → chunk-KEY43ANX.js} +2 -2
  100. package/dist/cli/chunks/chunk-KIP6WZGV.js +13 -0
  101. package/dist/cli/chunks/{chunk-UDHKLT4C.js → chunk-KKHYJF5U.js} +1 -1
  102. package/dist/cli/chunks/{chunk-ZNEMGX5O.js → chunk-KLTP5IDB.js} +1 -1
  103. package/dist/cli/chunks/{chunk-ONII3572.js → chunk-KO4FNAUR.js} +3 -3
  104. package/dist/cli/chunks/{chunk-TSRSV3LD.js → chunk-KYA5LARK.js} +1 -1
  105. package/dist/cli/chunks/{chunk-2JW3BCGG.js → chunk-LSUILON7.js} +1 -1
  106. package/dist/cli/chunks/chunk-LULD4JV2.js +15 -0
  107. package/dist/cli/chunks/{chunk-FRH6VAUS.js → chunk-M23ZOZVY.js} +1 -1
  108. package/dist/cli/chunks/{chunk-R5NE6B2M.js → chunk-M5AEL7IS.js} +2 -2
  109. package/dist/cli/chunks/chunk-MI5Q55DG.js +65 -0
  110. package/dist/cli/chunks/chunk-N7H767TP.js +4 -0
  111. package/dist/cli/chunks/{chunk-RJCYCLZV.js → chunk-NQI7FWCS.js} +2 -2
  112. package/dist/cli/chunks/{chunk-CXQPR5MY.js → chunk-NRE4NAVA.js} +1 -1
  113. package/dist/cli/chunks/{chunk-ODKLFVYC.js → chunk-NU7UTXMP.js} +2 -2
  114. package/dist/cli/chunks/{chunk-MVPCNSPY.js → chunk-NVYBM3R4.js} +2 -2
  115. package/dist/cli/chunks/{chunk-MVNP7GIR.js → chunk-O3JTQ7N4.js} +1 -1
  116. package/dist/cli/chunks/{chunk-6CQN24ZK.js → chunk-OEIQTWQP.js} +1 -1
  117. package/dist/cli/chunks/{chunk-U5K45TFH.js → chunk-PSPKSUF6.js} +1 -1
  118. package/dist/cli/chunks/{chunk-CDHQFHRP.js → chunk-QIRL6B3C.js} +2 -2
  119. package/dist/cli/chunks/{chunk-OSLYSG3B.js → chunk-QRCIZFNK.js} +2 -2
  120. package/dist/cli/chunks/{chunk-BOZZYWCR.js → chunk-QWUXCG2L.js} +1 -1
  121. package/dist/cli/chunks/{chunk-HIYXCDEP.js → chunk-QYOGD2VW.js} +1 -1
  122. package/dist/cli/chunks/{chunk-A4FYONNU.js → chunk-QZMUXJHZ.js} +2 -2
  123. package/dist/cli/chunks/{chunk-3TW5W5LX.js → chunk-R6IU3EWP.js} +2 -2
  124. package/dist/cli/chunks/{chunk-3X3DJZJJ.js → chunk-R74ZKREV.js} +1 -1
  125. package/dist/cli/chunks/{chunk-HIVA55CJ.js → chunk-RD2VGOUH.js} +1 -1
  126. package/dist/cli/chunks/{chunk-TPGED2IF.js → chunk-RD6TEZ64.js} +2 -2
  127. package/dist/cli/chunks/{chunk-4MHXCAG2.js → chunk-RGGK6VZ7.js} +1 -1
  128. package/dist/cli/chunks/{chunk-UGVHCMUN.js → chunk-RIZVC4XY.js} +3 -3
  129. package/dist/cli/chunks/{chunk-R4VL6E65.js → chunk-RKOUXVZZ.js} +2 -2
  130. package/dist/cli/chunks/{chunk-IFCLB7FJ.js → chunk-RP2ZKPYV.js} +1 -1
  131. package/dist/cli/chunks/{chunk-34WO57CW.js → chunk-SQF6HRXR.js} +1 -1
  132. package/dist/cli/chunks/{chunk-YNXS6CGV.js → chunk-SQKW3B6B.js} +1 -1
  133. package/dist/cli/chunks/{chunk-TDZ53WO2.js → chunk-SX4JLSLV.js} +2 -2
  134. package/dist/cli/chunks/{chunk-PAWXJ73E.js → chunk-TUSSPKRM.js} +1 -1
  135. package/dist/cli/chunks/{chunk-DFZCKIGY.js → chunk-TY5WC3FT.js} +3 -3
  136. package/dist/cli/chunks/{chunk-J6GNQS62.js → chunk-UDHVCKGA.js} +2 -2
  137. package/dist/cli/chunks/{chunk-CIKSHTEQ.js → chunk-UJWAWIRV.js} +4 -4
  138. package/dist/cli/chunks/{chunk-XJ7QNVI5.js → chunk-UKGXWW64.js} +3 -3
  139. package/dist/cli/chunks/{chunk-64PFWE2F.js → chunk-UMGFMKDW.js} +2 -2
  140. package/dist/cli/chunks/{chunk-DPFRKBOG.js → chunk-URVHZPWY.js} +2 -2
  141. package/dist/cli/chunks/{chunk-MCUJEZT6.js → chunk-UTBYJ4RF.js} +2 -2
  142. package/dist/cli/chunks/{chunk-HUWNIPZ5.js → chunk-VD5IO5EO.js} +1 -1
  143. package/dist/cli/chunks/{chunk-7ZIOFPL3.js → chunk-VTOVWHEM.js} +2 -2
  144. package/dist/cli/chunks/{chunk-SRKETSFF.js → chunk-W2XCZU62.js} +1 -1
  145. package/dist/cli/chunks/{chunk-CNG6GQEZ.js → chunk-WJHWH5D2.js} +2 -2
  146. package/dist/cli/chunks/{chunk-ZJ26AQA5.js → chunk-WJTSY5MC.js} +1 -1
  147. package/dist/cli/chunks/{chunk-OCWWP5PL.js → chunk-WK7B4B6Y.js} +2 -2
  148. package/dist/cli/chunks/{chunk-KPA7MZ6C.js → chunk-WLXK2KNU.js} +2 -2
  149. package/dist/cli/chunks/{chunk-ZBJ4XOOV.js → chunk-WOIGKU2N.js} +4 -4
  150. package/dist/cli/chunks/{chunk-ZZDIMOOV.js → chunk-WX6RRIGW.js} +2 -2
  151. package/dist/cli/chunks/{chunk-STM3UDNO.js → chunk-XEZIIQYJ.js} +2 -2
  152. package/dist/cli/chunks/{chunk-3QHGWY7T.js → chunk-XFPPERA2.js} +2 -2
  153. package/dist/cli/chunks/{chunk-VIHTL3U2.js → chunk-XLAUGSW7.js} +2 -2
  154. package/dist/cli/chunks/{chunk-XC7DYDSY.js → chunk-XQSIRBKT.js} +2 -2
  155. package/dist/cli/chunks/{chunk-GPLQ6DOK.js → chunk-XUR2M2WB.js} +2 -2
  156. package/dist/cli/chunks/{chunk-KCZR45PA.js → chunk-XZSMZHM2.js} +2 -2
  157. package/dist/cli/chunks/{chunk-ZNPKDCZR.js → chunk-Y5L3ES4L.js} +2 -2
  158. package/dist/cli/chunks/{chunk-W7BWUTVV.js → chunk-YDFL445W.js} +2 -2
  159. package/dist/cli/chunks/{chunk-AWWNB2T7.js → chunk-YQGPQBCX.js} +2 -2
  160. package/dist/cli/chunks/{chunk-DAEFDCJ4.js → chunk-YXP6BKGS.js} +17 -17
  161. package/dist/cli/chunks/{chunk-OBAP2TXZ.js → chunk-ZBABIZ2D.js} +2 -2
  162. package/dist/cli/chunks/{chunk-CSU5NYOX.js → chunk-ZCWERUYB.js} +4 -4
  163. package/dist/cli/chunks/{ci-464KPQNP.js → ci-RACDAJMR.js} +2 -2
  164. package/dist/cli/chunks/{ci-output-I7FX2RSO.js → ci-output-EHRSZBKG.js} +2 -2
  165. package/dist/cli/chunks/{circuit-breaker-3FW237WW.js → circuit-breaker-GBV7M5XG.js} +2 -2
  166. package/dist/cli/chunks/{claude-flow-setup-6JKMBPGU.js → claude-flow-setup-5LVJOFKP.js} +2 -2
  167. package/dist/cli/chunks/client-HUVFA5PF.js +2 -0
  168. package/dist/cli/chunks/{cline-installer-UWFHT6VY.js → cline-installer-W4NMXJSG.js} +2 -2
  169. package/dist/cli/chunks/{code-KQSUT3FS.js → code-JWXJMYXB.js} +3 -3
  170. package/dist/cli/chunks/{code-index-extractor-PABBNUSC.js → code-index-extractor-RVI2IFTM.js} +2 -2
  171. package/dist/cli/chunks/codex-installer-3BORJINH.js +14 -0
  172. package/dist/cli/chunks/{completions-7RWHAUAR.js → completions-A55NCTAO.js} +2 -2
  173. package/dist/cli/chunks/{complexity-analyzer-XPOAF33E.js → complexity-analyzer-JCXHGGLY.js} +2 -2
  174. package/dist/cli/chunks/{continuedev-installer-V4F2FIZP.js → continuedev-installer-PUVFMGYW.js} +2 -2
  175. package/dist/cli/chunks/{copilot-installer-JMICURQB.js → copilot-installer-4DCMYWHB.js} +2 -2
  176. package/dist/cli/chunks/core-handlers-UEXO3VAA.js +2 -0
  177. package/dist/cli/chunks/{cost-tracker-5OFHEYFJ.js → cost-tracker-5TV2GGKY.js} +2 -2
  178. package/dist/cli/chunks/{coverage-QKN57JDS.js → coverage-NNWM7TX3.js} +3 -3
  179. package/dist/cli/chunks/cross-domain-router-ODU5IZD6.js +2 -0
  180. package/dist/cli/chunks/{cursor-installer-GBJ7YXSM.js → cursor-installer-4NCHGJGK.js} +2 -2
  181. package/dist/cli/chunks/{daemon-IAVSO6HK.js → daemon-QIKCXKWO.js} +4 -4
  182. package/dist/cli/chunks/{daemon-GKP7CMEK.js → daemon-T4JO4IXP.js} +3 -3
  183. package/dist/cli/chunks/{dag-attention-scheduler-S225TCI7.js → dag-attention-scheduler-RPAAIDAD.js} +2 -2
  184. package/dist/cli/chunks/{detect-IUYH422U.js → detect-SBEEVDSN.js} +2 -2
  185. package/dist/cli/chunks/{dist-node-2YRE6A7C.js → dist-node-ZHI6NCSU.js} +2 -2
  186. package/dist/cli/chunks/{domain-handler-PL2TZC6H.js → domain-handler-LBC3GJ7Z.js} +2 -2
  187. package/dist/cli/chunks/{domain-plugins-HCGLXKIT.js → domain-plugins-H6IZ5USZ.js} +2 -2
  188. package/dist/cli/chunks/{domain-transfer-KQJRUPXA.js → domain-transfer-JZA5TMW3.js} +2 -2
  189. package/dist/cli/chunks/dream-HE3OX42F.js +2 -0
  190. package/dist/cli/chunks/embed-and-insert-pattern-AHTR7CRU.js +3 -0
  191. package/dist/cli/chunks/{eval-WCK7KNFN.js → eval-DZU2KISM.js} +2 -2
  192. package/dist/cli/chunks/{experience-capture-middleware-2MSQWSAR.js → experience-capture-middleware-5IQCWKSL.js} +4 -4
  193. package/dist/cli/chunks/{fast-paths-VYOSIBKF.js → fast-paths-2KLDUWCY.js} +2 -2
  194. package/dist/cli/chunks/{feature-flags-UJRHFBRX.js → feature-flags-7AC3XDZA.js} +2 -2
  195. package/dist/cli/chunks/{feature-flags-WCFUKHNQ.js → feature-flags-N6UAEZY4.js} +2 -2
  196. package/dist/cli/chunks/{file-discovery-JDGL4ZWS.js → file-discovery-5SDIW4V2.js} +2 -2
  197. package/dist/cli/chunks/{fleet-ROXVMZ2F.js → fleet-ZIQCAZ2Y.js} +3 -3
  198. package/dist/cli/chunks/{gnn-wrapper-NIO4ZCO3.js → gnn-wrapper-DUMBZJEV.js} +2 -2
  199. package/dist/cli/chunks/{heartbeat-handler-PI42WD3C.js → heartbeat-handler-6HVM6ZMR.js} +4 -4
  200. package/dist/cli/chunks/heartbeat-scheduler-QUIFGGLX.js +2 -0
  201. package/dist/cli/chunks/hnsw-adapter-42KB37KP.js +2 -0
  202. package/dist/cli/chunks/hnsw-index-T2PGO77J.js +2 -0
  203. package/dist/cli/chunks/{hnsw-legacy-bridge-YLC7SPK2.js → hnsw-legacy-bridge-5DRL5FLX.js} +2 -2
  204. package/dist/cli/chunks/{hnswlib-node-LG6OS3B7.js → hnswlib-node-GW67GTCL.js} +2 -2
  205. package/dist/cli/chunks/{hooks-WVALP5GX.js → hooks-QHH6FVO4.js} +10 -10
  206. package/dist/cli/chunks/hybrid-backend-FRNWYRKH.js +2 -0
  207. package/dist/cli/chunks/{hypergraph-engine-GJEMW3EG.js → hypergraph-engine-7XDCCVG2.js} +2 -2
  208. package/dist/cli/chunks/{hypergraph-handler-BLF6LXEV.js → hypergraph-handler-QHF7NOU5.js} +3 -3
  209. package/dist/cli/chunks/impact-analyzer-A5QYOYBR.js +2 -0
  210. package/dist/cli/chunks/{init-handler-K25RWRYY.js → init-handler-5UIVOM7K.js} +6 -6
  211. package/dist/cli/chunks/init-wizard-XBU674YH.js +2 -0
  212. package/dist/cli/chunks/kernel-DV5MTNZD.js +2 -0
  213. package/dist/cli/chunks/{kilocode-installer-BXN6WZ7G.js → kilocode-installer-TGGV6K5Q.js} +2 -2
  214. package/dist/cli/chunks/{kiro-installer-PM362DLN.js → kiro-installer-4XYBHZWW.js} +2 -2
  215. package/dist/cli/chunks/knowledge-graph-4ACGVJQK.js +2 -0
  216. package/dist/cli/chunks/{learning-CPERDDRG.js → learning-STE5W6BS.js} +3 -3
  217. package/dist/cli/chunks/{llm-router-GOAV5FPI.js → llm-router-NKF7J3RI.js} +4 -4
  218. package/dist/cli/chunks/llm-router-service-PSMASERT.js +2 -0
  219. package/dist/cli/chunks/{load-2BG6SHAK.js → load-B2T77UJQ.js} +2 -2
  220. package/dist/cli/chunks/load-test-MRUO2VPF.js +2 -0
  221. package/dist/cli/chunks/mcp-JGSFCEMH.js +2 -0
  222. package/dist/cli/chunks/{memory-4NHBYT6S.js → memory-WRFZKG56.js} +6 -6
  223. package/dist/cli/chunks/memory-backend-2MPGI6JW.js +2 -0
  224. package/dist/cli/chunks/memory-handlers-XT4HMITB.js +2 -0
  225. package/dist/cli/chunks/{multi-model-executor-KCWSGCDT.js → multi-model-executor-26Q5BSVG.js} +2 -2
  226. package/dist/cli/chunks/{opencode-installer-ATZLLK74.js → opencode-installer-J36EMQU7.js} +2 -2
  227. package/dist/cli/chunks/{orchestrator-RKB7XJRG.js → orchestrator-D5IFV65I.js} +18 -18
  228. package/dist/cli/chunks/pattern-null-store-TGWUL237.js +2 -0
  229. package/dist/cli/chunks/{pattern-usage-recorder-7VE4XDAI.js → pattern-usage-recorder-BVMTWI3E.js} +2 -2
  230. package/dist/cli/chunks/{pipeline-LQZSNDD2.js → pipeline-OWAHDUAQ.js} +2 -2
  231. package/dist/cli/chunks/platform-ANGBFWBV.js +2 -0
  232. package/dist/cli/chunks/{plugin-EJ6K2MGU.js → plugin-OO7ON2YW.js} +2 -2
  233. package/dist/cli/chunks/{prime-radiant-advanced-wasm-OIHTKJMN.js → prime-radiant-advanced-wasm-HFG3BXWU.js} +2 -2
  234. package/dist/cli/chunks/project-root-LNOYVTYY.js +2 -0
  235. package/dist/cli/chunks/protocol-executor-GEVH5KD6.js +2 -0
  236. package/dist/cli/chunks/{protocol-handler-NRBROAU7.js → protocol-handler-CE3Q6LY4.js} +2 -2
  237. package/dist/cli/chunks/{prove-EJOGEGD3.js → prove-7XPN53PY.js} +2 -2
  238. package/dist/cli/chunks/qe-reasoning-bank-DJ2JL6QB.js +2 -0
  239. package/dist/cli/chunks/{quality-E55UC73D.js → quality-TT23JRFX.js} +2 -2
  240. package/dist/cli/chunks/{quality-gate-OIQATNT3.js → quality-gate-PPPRP255.js} +3 -3
  241. package/dist/cli/chunks/queen-coordinator-F7E3AS26.js +2 -0
  242. package/dist/cli/chunks/real-embeddings-EYNZIFJE.js +2 -0
  243. package/dist/cli/chunks/{ref-validation-OPO6J7OL.js → ref-validation-QQR64ZXD.js} +2 -2
  244. package/dist/cli/chunks/{roocode-installer-ODY5KRWU.js → roocode-installer-UIGS7ZJD.js} +2 -2
  245. package/dist/cli/chunks/router-OZH3QSAU.js +2 -0
  246. package/dist/cli/chunks/routing-feedback-J2E3ADZB.js +2 -0
  247. package/dist/cli/chunks/{routing-handler-KQM6VWLC.js → routing-handler-6AENUIRG.js} +2 -2
  248. package/dist/cli/chunks/{ruvector-commands-U2GVV6PF.js → ruvector-commands-5AWMEV34.js} +2 -2
  249. package/dist/cli/chunks/rvf-dual-writer-HK525Y5Y.js +2 -0
  250. package/dist/cli/chunks/rvf-migration-adapter-Q7FB3BKR.js +2 -0
  251. package/dist/cli/chunks/rvf-migration-coordinator-NWRJ7C22.js +2 -0
  252. package/dist/cli/chunks/rvf-native-adapter-5ZRCGUI6.js +2 -0
  253. package/dist/cli/chunks/{rvf-store-integrity-KMIHD3LP.js → rvf-store-integrity-ISKRP563.js} +2 -2
  254. package/dist/cli/chunks/safe-db-3OYEPVEH.js +2 -0
  255. package/dist/cli/chunks/schedule-AG4C2EIQ.js +2 -0
  256. package/dist/cli/chunks/scheduler-SQS2CZFZ.js +2 -0
  257. package/dist/cli/chunks/{security-P5NM353C.js → security-325A7FMB.js} +3 -3
  258. package/dist/cli/chunks/{shared-rvf-adapter-LVIUOO4S.js → shared-rvf-adapter-NFL6QSZ6.js} +2 -2
  259. package/dist/cli/chunks/{shared-rvf-dual-writer-2CSG7C4W.js → shared-rvf-dual-writer-THFDYS2Z.js} +2 -2
  260. package/dist/cli/chunks/sqlite-persistence-MAKDFSHC.js +2 -0
  261. package/dist/cli/chunks/standalone-memory-UD4MJ6GZ.js +2 -0
  262. package/dist/cli/chunks/{status-handler-6TU6O37R.js → status-handler-CPFTN4XL.js} +2 -2
  263. package/dist/cli/chunks/{structural-health-KBIJSTXJ.js → structural-health-2MG2IVBL.js} +2 -2
  264. package/dist/cli/chunks/{sync-LNHI5SB7.js → sync-EE4VVKOW.js} +2 -2
  265. package/dist/cli/chunks/{sync-UHOX6RJW.js → sync-MBTW5XBF.js} +2 -2
  266. package/dist/cli/chunks/task-handler-7H5OYJG4.js +54 -0
  267. package/dist/cli/chunks/task-handlers-NH4GJHCJ.js +9 -0
  268. package/dist/cli/chunks/{test-DHAAI3DU.js → test-MPHGT4T6.js} +4 -4
  269. package/dist/cli/chunks/{test-scheduling-XDBZ3QC2.js → test-scheduling-CHQ4ZLLJ.js} +3 -3
  270. package/dist/cli/chunks/token-bootstrap-SSDCYEKK.js +2 -0
  271. package/dist/cli/chunks/{token-usage-Q2YG5YQN.js → token-usage-EBXUJNRB.js} +2 -2
  272. package/dist/cli/chunks/{transformers-F5UQTQCY.js → transformers-ZEKS2OJZ.js} +2 -2
  273. package/dist/cli/chunks/{tree-sitter-wasm-parser-DEGOHS6F.js → tree-sitter-wasm-parser-J6ZMAK37.js} +2 -2
  274. package/dist/cli/chunks/{types-JQ7EQO5Q.js → types-KYAA5VLV.js} +2 -2
  275. package/dist/cli/chunks/unified-memory-DDWMC435.js +2 -0
  276. package/dist/cli/chunks/unified-memory-hnsw-4JA7SGBK.js +2 -0
  277. package/dist/cli/chunks/unified-persistence-F6OSNTXY.js +2 -0
  278. package/dist/cli/chunks/{upgrade-TJRVGHGD.js → upgrade-UJBJ5AYM.js} +2 -2
  279. package/dist/cli/chunks/{validate-BWPCVHBN.js → validate-RUV6YMWS.js} +2 -2
  280. package/dist/cli/chunks/{validate-swarm-QVVKCQLP.js → validate-swarm-IVEVMGVM.js} +2 -2
  281. package/dist/cli/chunks/{vibium-ZFATIWHO.js → vibium-HOGMFJ2Z.js} +2 -2
  282. package/dist/cli/chunks/visual-security-25SMBIYT.js +2 -0
  283. package/dist/cli/chunks/{web-tree-sitter-KPLY7ONR.js → web-tree-sitter-AVWA6HKE.js} +2 -2
  284. package/dist/cli/chunks/{windsurf-installer-H7XM7ISA.js → windsurf-installer-DAH7HI2W.js} +2 -2
  285. package/dist/cli/chunks/{witness-chain-RRN6NDCH.js → witness-chain-PJOQPFUX.js} +2 -2
  286. package/dist/cli/chunks/witness-chain-ZW6KKUZU.js +2 -0
  287. package/dist/cli/chunks/{witness-key-manager-DFRL42GE.js → witness-key-manager-JSTBMG43.js} +2 -2
  288. package/dist/cli/chunks/{workflow-2ZQO6WYI.js → workflow-TWOIA6LZ.js} +4 -4
  289. package/dist/cli/chunks/workflow-orchestrator-UKSIDM7Q.js +2 -0
  290. package/dist/cli/chunks/{wrappers-SUS6XEJD.js → wrappers-UR7BLXKV.js} +2 -2
  291. package/dist/cli/commands/mcp.js +6 -0
  292. package/dist/cli/commands/memory.d.ts +1 -1
  293. package/dist/cli/commands/memory.js +8 -8
  294. package/dist/cli/commands/platform.js +15 -2
  295. package/dist/cli/commands/upgrade.d.ts +3 -3
  296. package/dist/cli/commands/upgrade.js +3 -3
  297. package/dist/cli/handlers/init-handler.d.ts +10 -0
  298. package/dist/cli/handlers/task-handler.js +24 -3
  299. package/dist/cli/helpers/standalone-memory.d.ts +12 -0
  300. package/dist/cli/helpers/standalone-memory.js +46 -0
  301. package/dist/cli/index.js +37 -41
  302. package/dist/cli/log-gate.d.ts +66 -0
  303. package/dist/cli/log-gate.js +170 -0
  304. package/dist/init/codex-installer.js +18 -6
  305. package/dist/init/orchestrator.js +1 -0
  306. package/dist/init/phases/09-assets.d.ts +10 -0
  307. package/dist/init/phases/09-assets.js +3 -0
  308. package/dist/init/token-bootstrap.d.ts +1 -1
  309. package/dist/init/token-bootstrap.js +12 -2
  310. package/dist/init/types.d.ts +10 -0
  311. package/dist/integrations/ruvector/brain-exporter.js +17 -0
  312. package/dist/integrations/ruvector/brain-import-audit.d.ts +20 -0
  313. package/dist/integrations/ruvector/brain-import-audit.js +22 -0
  314. package/dist/integrations/ruvector/brain-rvf-exporter.js +16 -0
  315. package/dist/integrations/ruvector/brain-shared.js +1 -1
  316. package/dist/integrations/ruvector/rvf-dual-writer.js +6 -1
  317. package/dist/kernel/hybrid-backend.d.ts +6 -0
  318. package/dist/kernel/hybrid-backend.js +18 -0
  319. package/dist/kernel/kernel.js +9 -14
  320. package/dist/kernel/project-root.d.ts +1 -1
  321. package/dist/kernel/project-root.js +24 -3
  322. package/dist/learning/embedder-identity-store.js +4 -3
  323. package/dist/learning/pattern-store.js +5 -1
  324. package/dist/learning/real-embeddings.d.ts +8 -0
  325. package/dist/learning/real-embeddings.js +16 -0
  326. package/dist/learning/rvf-pattern-store.js +10 -3
  327. package/dist/mcp/bundle.js +442 -442
  328. package/dist/mcp/entry.js +2 -0
  329. package/dist/mcp/handlers/memory-handlers.d.ts +6 -1
  330. package/dist/mcp/handlers/memory-handlers.js +44 -22
  331. package/dist/mcp/handlers/task-handlers.js +14 -1
  332. package/dist/mcp/protocol-server.js +1 -0
  333. package/dist/mcp/services/session-store.js +5 -1
  334. package/dist/plugins/cache.d.ts +2 -0
  335. package/dist/plugins/cache.js +15 -2
  336. package/dist/plugins/lifecycle.js +15 -2
  337. package/dist/plugins/manifest.js +7 -5
  338. package/dist/plugins/resolver.d.ts +13 -22
  339. package/dist/plugins/resolver.js +169 -61
  340. package/dist/plugins/version-policy.d.ts +13 -0
  341. package/dist/plugins/version-policy.js +18 -0
  342. package/dist/shared/types/index.d.ts +6 -0
  343. package/dist/shared/types/index.js +8 -0
  344. package/package.json +2 -1
  345. package/dist/cli/chunks/adapter-TNNNJRDG.js +0 -2
  346. package/dist/cli/chunks/aqe-learning-engine-5ZRMYJLB.js +0 -2
  347. package/dist/cli/chunks/base-KWZHOPSH.js +0 -2
  348. package/dist/cli/chunks/brain-handler-ET6YAP4B.js +0 -90
  349. package/dist/cli/chunks/browser-workflow-2FZTKDUL.js +0 -2
  350. package/dist/cli/chunks/chunk-33YYYWBQ.js +0 -4
  351. package/dist/cli/chunks/chunk-5Z6XZV7K.js +0 -65
  352. package/dist/cli/chunks/chunk-6J62K3SW.js +0 -2
  353. package/dist/cli/chunks/chunk-6TPKK7LD.js +0 -15
  354. package/dist/cli/chunks/chunk-DEYLEDJN.js +0 -27
  355. package/dist/cli/chunks/chunk-KGT36Z42.js +0 -14
  356. package/dist/cli/chunks/chunk-NA7B2QYB.js +0 -2
  357. package/dist/cli/chunks/chunk-NDPFGIMJ.js +0 -13
  358. package/dist/cli/chunks/chunk-PEPFCPES.js +0 -2
  359. package/dist/cli/chunks/chunk-TT23RRB7.js +0 -2
  360. package/dist/cli/chunks/chunk-XWMZ6D6N.js +0 -2
  361. package/dist/cli/chunks/client-7E4LM2WW.js +0 -2
  362. package/dist/cli/chunks/codex-installer-CQ24DTP5.js +0 -14
  363. package/dist/cli/chunks/core-handlers-IFG3757P.js +0 -2
  364. package/dist/cli/chunks/cross-domain-router-EK7W4PGP.js +0 -2
  365. package/dist/cli/chunks/dream-NFSCSLY7.js +0 -2
  366. package/dist/cli/chunks/embed-and-insert-pattern-ZPAG7235.js +0 -3
  367. package/dist/cli/chunks/heartbeat-scheduler-ZATCDJDK.js +0 -2
  368. package/dist/cli/chunks/hnsw-adapter-WXQABRCA.js +0 -2
  369. package/dist/cli/chunks/hnsw-index-TPSWLEA5.js +0 -2
  370. package/dist/cli/chunks/impact-analyzer-HNIU45P5.js +0 -2
  371. package/dist/cli/chunks/init-wizard-JUIPBMHG.js +0 -2
  372. package/dist/cli/chunks/kernel-5BOZQ754.js +0 -2
  373. package/dist/cli/chunks/knowledge-graph-EWDAENWM.js +0 -2
  374. package/dist/cli/chunks/llm-router-service-3YT7JGBS.js +0 -2
  375. package/dist/cli/chunks/load-test-BP2CPLIV.js +0 -2
  376. package/dist/cli/chunks/mcp-5TTB37DC.js +0 -2
  377. package/dist/cli/chunks/memory-backend-4PYQBPRM.js +0 -2
  378. package/dist/cli/chunks/memory-handlers-2B27NITS.js +0 -2
  379. package/dist/cli/chunks/pattern-null-store-OYOQOV2O.js +0 -2
  380. package/dist/cli/chunks/platform-OD5H5U6G.js +0 -2
  381. package/dist/cli/chunks/protocol-executor-3ATJTXWG.js +0 -2
  382. package/dist/cli/chunks/qe-reasoning-bank-LLMYZT4X.js +0 -2
  383. package/dist/cli/chunks/queen-coordinator-RN7L6KG5.js +0 -2
  384. package/dist/cli/chunks/real-embeddings-FPFFNOSZ.js +0 -2
  385. package/dist/cli/chunks/router-MDHITQ2V.js +0 -2
  386. package/dist/cli/chunks/routing-feedback-5XLNJ3Y3.js +0 -2
  387. package/dist/cli/chunks/rvf-dual-writer-JBW4O3II.js +0 -2
  388. package/dist/cli/chunks/rvf-migration-adapter-BPPQL4XJ.js +0 -2
  389. package/dist/cli/chunks/rvf-migration-coordinator-V2GHCJKN.js +0 -2
  390. package/dist/cli/chunks/rvf-native-adapter-S4562CG5.js +0 -2
  391. package/dist/cli/chunks/safe-db-FIRHSXVF.js +0 -2
  392. package/dist/cli/chunks/schedule-RVXFB4HK.js +0 -2
  393. package/dist/cli/chunks/scheduler-IKKAMAOO.js +0 -2
  394. package/dist/cli/chunks/sqlite-persistence-SQ3HCUQ7.js +0 -2
  395. package/dist/cli/chunks/task-handler-AVDHMLGI.js +0 -49
  396. package/dist/cli/chunks/task-handlers-KYK4VTRA.js +0 -9
  397. package/dist/cli/chunks/token-bootstrap-GUTTLPZX.js +0 -2
  398. package/dist/cli/chunks/unified-memory-CXHLHB5I.js +0 -2
  399. package/dist/cli/chunks/unified-memory-hnsw-I7WAE54M.js +0 -2
  400. package/dist/cli/chunks/unified-persistence-6CPF65WI.js +0 -2
  401. package/dist/cli/chunks/visual-security-GNPHME5H.js +0 -2
  402. package/dist/cli/chunks/witness-chain-VT4UHHBR.js +0 -2
  403. package/dist/cli/chunks/workflow-orchestrator-DB3HIECD.js +0 -2
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.4");process.exit(0)}
2
- import{b as v}from"./chunk-FGYMFUE2.js";import{a as Ce,c as _e}from"./chunk-DOTK76IJ.js";import{b as a,g as Ee}from"./chunk-ZBQY5GLF.js";import{a as le,b as Ke}from"./chunk-ZZDIMOOV.js";import{b as Te,c as _,d as ke,f as S}from"./chunk-F3SBRQC6.js";import{e as G,h as ve,i as ce,n as $}from"./chunk-3TW5W5LX.js";import{b as B,d as ye}from"./chunk-DHJPWQBR.js";import{b as E,c as L}from"./chunk-G6T45OIC.js";import{b as be,d as De}from"./chunk-KCZR45PA.js";import{c as ae}from"./chunk-TT23RRB7.js";import{readFileSync as $e}from"fs";import*as Me from"path";function j(g){return typeof g=="string"&&Fe.includes(g)}function ze(g){try{let e=$e(g,"utf8").match(/^\s*effort_level\s*:\s*['"]?([a-z]+)['"]?\s*$/m);return e&&j(e[1])?e[1]:null}catch{return null}}function Le(g={}){if(g.override&&j(g.override))return g.override;if(g.agentEffort&&j(g.agentEffort))return g.agentEffort;let e=(g.env??process.env).QE_EFFORT_LEVEL;if(e&&j(e))return e;let r=g.fleetDefaultsPath??Me.join(process.cwd(),"config","fleet-defaults.yaml");return z===void 0&&(z=ze(r)),z||We}var Fe,We,z,Pe=ae(()=>{"use strict";Fe=["low","medium","high","xhigh","max"],We="xhigh"});function je(g){try{let t=G(g);return{sendSampling:t.supportsSamplingParams!==!1,supportsEffort:t.supportsEffortXHigh===!0}}catch{return{sendSampling:!1,supportsEffort:!1}}}function H(g,t,e){let r=je(t);if(r.sendSampling&&e.temperature!==void 0&&(g.temperature=e.temperature),r.supportsEffort){let o=e.effort??(He(t)?Le():void 0);o!==void 0&&(g.output_config={effort:o})}return g}function He(g){return ve(g)?.tier==="flagship"}var he=ae(()=>{"use strict";$();Pe()});function lt(g){try{let t=G(g);return{sendSampling:t.supportsSamplingParams!==!1,maxTokensField:t.usesMaxCompletionTokens===!0?"max_completion_tokens":"max_tokens"}}catch{return it.test(g)?{...ct}:{...at}}}function U(g,t,e){let r=lt(t),o=g;return e.maxTokens!==void 0&&(o[r.maxTokensField]=e.maxTokens),r.sendSampling&&e.temperature!==void 0&&(o.temperature=e.temperature),g}var it,at,ct,ge=ae(()=>{"use strict";$();it=/^(openai\/)?(gpt-5|gpt-6|o\d)/i,at={sendSampling:!0,maxTokensField:"max_tokens"},ct={sendSampling:!1,maxTokensField:"max_completion_tokens"}});De();L();var Re={failureThreshold:5,resetTimeoutMs:3e4,halfOpenSuccessThreshold:2,failureWindowMs:6e4,includeTimeouts:!0},ue=class{state="closed";failures=[];successCount=0;totalRequests=0;totalSuccesses=0;totalFailures=0;rejectedCount=0;lastFailureTime;lastSuccessTime;openedAt;halfOpenSuccesses=0;config;providerType;constructor(t,e={}){this.providerType=t,this.config={...Re,...e}}getState(){return this.state==="open"&&this.openedAt&&Date.now()-this.openedAt.getTime()>=this.config.resetTimeoutMs&&this.transitionTo("half-open"),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t!=="open"}async execute(t){if(this.totalRequests++,this.getState()==="open")throw this.rejectedCount++,a(`Circuit breaker is open for provider ${this.providerType}`,"CIRCUIT_OPEN",{provider:this.providerType,retryable:!0,retryAfterMs:this.getTimeUntilTransition()});try{let r=await t();return this.recordSuccess(),r}catch(r){throw this.recordFailure(E(r)),r}}recordSuccess(){this.successCount++,this.totalSuccesses++,this.lastSuccessTime=new Date,this.getState()==="half-open"&&(this.halfOpenSuccesses++,this.halfOpenSuccesses>=this.config.halfOpenSuccessThreshold&&this.transitionTo("closed"))}recordFailure(t){if(this.totalFailures++,this.lastFailureTime=new Date,(t.message.toLowerCase().includes("timeout")||t.name==="TimeoutError"||t.name==="AbortError")&&!this.config.includeTimeouts)return;this.failures.push({timestamp:new Date,error:t}),this.cleanOldFailures();let r=this.getState();if(r==="half-open"){this.transitionTo("open");return}r==="closed"&&this.failures.length>=this.config.failureThreshold&&this.transitionTo("open")}getStats(){return{state:this.getState(),totalRequests:this.totalRequests,successCount:this.totalSuccesses,failureCount:this.totalFailures,rejectedCount:this.rejectedCount,lastFailureTime:this.lastFailureTime,lastSuccessTime:this.lastSuccessTime,timeUntilTransitionMs:this.getTimeUntilTransition()}}reset(){this.state="closed",this.failures=[],this.successCount=0,this.halfOpenSuccesses=0,this.openedAt=void 0}forceOpen(){this.transitionTo("open")}forceHalfOpen(){this.transitionTo("half-open")}getRecentFailures(t=5){return this.failures.slice(-t).map(e=>`[${e.timestamp.toISOString()}] ${e.error.message}`)}transitionTo(t){if(this.state!==t)switch(this.state=t,t){case"open":this.openedAt=new Date,this.halfOpenSuccesses=0;break;case"half-open":this.halfOpenSuccesses=0;break;case"closed":this.failures=[],this.openedAt=void 0,this.halfOpenSuccesses=0;break}}cleanOldFailures(){let t=Date.now()-this.config.failureWindowMs;this.failures=this.failures.filter(e=>e.timestamp.getTime()>t)}getTimeUntilTransition(){if(this.state==="open"&&this.openedAt){let t=Date.now()-this.openedAt.getTime(),e=this.config.resetTimeoutMs-t;return Math.max(0,e)}}},F=class{breakers=new Map;defaultConfig;constructor(t={}){this.defaultConfig={...Re,...t}}getBreaker(t,e){let r=this.breakers.get(t);return r||(r=new ue(t,{...this.defaultConfig,...e}),this.breakers.set(t,r)),r}getAllStats(){let t={};for(let[e,r]of this.breakers)t[e]=r.getStats();return t}getAvailableProviders(){let t=[];for(let[e,r]of this.breakers)r.canExecute()&&t.push(e);return t}resetAll(){for(let t of this.breakers.values())t.reset()}reset(t){let e=this.breakers.get(t);e&&e.reset()}};var we={maxSize:1e3,defaultTtlMs:36e5,enableLRU:!0,cacheGenerations:!0,cacheEmbeddings:!0,cacheCompletions:!0},A=class{cache=new Map;accessOrder=[];config;hits=0;misses=0;evictions=0;constructor(t={}){this.config={...we,...t}}static generateKey(t,e,r){let s=[t,r?.model??"default",String(r?.temperature??.7),String(r?.maxTokens??0),r?.systemPrompt??"",e].join("|"),n=0;for(let i=0;i<s.length;i++){let l=s.charCodeAt(i);n=(n<<5)-n+l,n=n&n}return`${t}:${Math.abs(n).toString(36)}`}get(t){let e=this.cache.get(t);if(!e){this.misses++;return}if(e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs){this.delete(t),this.misses++;return}return this.hits++,e.lastAccessedAt=new Date,e.accessCount++,this.config.enableLRU&&this.updateAccessOrder(t),e.value}set(t,e,r){this.cache.size>=this.config.maxSize&&!this.cache.has(t)&&this.evictLRU();let o={value:e,createdAt:new Date,lastAccessedAt:new Date,accessCount:1,ttlMs:r??this.config.defaultTtlMs,keyHash:t};this.cache.set(t,o),this.config.enableLRU&&this.updateAccessOrder(t)}has(t){let e=this.cache.get(t);return e?e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs?(this.delete(t),!1):!0:!1}delete(t){let e=this.cache.delete(t);if(e){let r=this.accessOrder.indexOf(t);r!==-1&&this.accessOrder.splice(r,1)}return e}clear(){this.cache.clear(),this.accessOrder=[],this.hits=0,this.misses=0,this.evictions=0}getStats(){let t=this.hits+this.misses,e=t>0?this.hits/t:0,r=0;for(let o of this.cache.values())r+=this.estimateSize(o.value);return{size:this.cache.size,maxSize:this.config.maxSize,hits:this.hits,misses:this.misses,hitRate:e,evictions:this.evictions,memoryUsageBytes:r}}keys(){return Array.from(this.cache.keys())}entries(){return Array.from(this.cache.entries())}import(t){for(let[e,r]of t)r.createdAt=new Date(r.createdAt),r.lastAccessedAt=new Date(r.lastAccessedAt),this.cache.set(e,r),this.accessOrder.push(e);for(;this.cache.size>this.config.maxSize;)this.evictLRU()}pruneExpired(){let t=Date.now(),e=0;for(let[r,o]of this.cache.entries())o.ttlMs>0&&t-o.createdAt.getTime()>o.ttlMs&&(this.delete(r),e++);return e}updateAccessOrder(t){let e=this.accessOrder.indexOf(t);e!==-1&&this.accessOrder.splice(e,1),this.accessOrder.push(t)}evictLRU(){if(this.accessOrder.length===0){let e=this.cache.keys().next().value;e&&(this.cache.delete(e),this.evictions++);return}let t=this.accessOrder.shift();t&&(this.cache.delete(t),this.evictions++)}estimateSize(t){return t==null?0:JSON.stringify(t).length*2}},W=class{generationCache;embeddingCache;completionCache;config;constructor(t={}){this.config={...we,...t},this.generationCache=new A(t),this.embeddingCache=new A(t),this.completionCache=new A(t)}getGeneration(t,e){if(!this.config.cacheGenerations)return;let r=A.generateKey("generation",t,e);return this.generationCache.get(r)}setGeneration(t,e,r,o){if(!this.config.cacheGenerations)return;let s=A.generateKey("generation",t,r);this.generationCache.set(s,e,o)}getEmbedding(t,e){if(!this.config.cacheEmbeddings)return;let r=A.generateKey("embedding",t,e);return this.embeddingCache.get(r)}setEmbedding(t,e,r,o){if(!this.config.cacheEmbeddings)return;let s=A.generateKey("embedding",t,r);this.embeddingCache.set(s,e,o)}getCompletion(t,e){if(!this.config.cacheCompletions)return;let r=A.generateKey("completion",t,e);return this.completionCache.get(r)}setCompletion(t,e,r,o){if(!this.config.cacheCompletions)return;let s=A.generateKey("completion",t,r);this.completionCache.set(s,e,o)}getStats(){let t=this.generationCache.getStats(),e=this.embeddingCache.getStats(),r=this.completionCache.getStats(),o=t.hits+e.hits+r.hits,s=t.misses+e.misses+r.misses,n=o+s;return{generation:t,embedding:e,completion:r,total:{size:t.size+e.size+r.size,maxSize:this.config.maxSize*3,hits:o,misses:s,hitRate:n>0?o/n:0,evictions:t.evictions+e.evictions+r.evictions,memoryUsageBytes:t.memoryUsageBytes+e.memoryUsageBytes+r.memoryUsageBytes}}}clear(){this.generationCache.clear(),this.embeddingCache.clear(),this.completionCache.clear()}pruneExpired(){return this.generationCache.pruneExpired()+this.embeddingCache.pruneExpired()+this.completionCache.pruneExpired()}};S();var pe="(unattributed)",qe=`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
+ import{b as v}from"./chunk-2JGEZHWY.js";import{a as Ce,c as _e}from"./chunk-BXVAVFGU.js";import{b as a,g as Ee}from"./chunk-JROVR6YS.js";import{a as le,b as Ke}from"./chunk-WX6RRIGW.js";import{b as Te,c as _,d as ke,f as S}from"./chunk-E4EYPYR3.js";import{e as G,h as ve,i as ce,n as $}from"./chunk-R6IU3EWP.js";import{b as B,d as ye}from"./chunk-IJHCIXJC.js";import{b as E,c as L}from"./chunk-J5UNP6W3.js";import{b as be,d as De}from"./chunk-XZSMZHM2.js";import{b as ae}from"./chunk-JSZ663MU.js";import{readFileSync as $e}from"fs";import*as Me from"path";function j(g){return typeof g=="string"&&Fe.includes(g)}function ze(g){try{let e=$e(g,"utf8").match(/^\s*effort_level\s*:\s*['"]?([a-z]+)['"]?\s*$/m);return e&&j(e[1])?e[1]:null}catch{return null}}function Le(g={}){if(g.override&&j(g.override))return g.override;if(g.agentEffort&&j(g.agentEffort))return g.agentEffort;let e=(g.env??process.env).QE_EFFORT_LEVEL;if(e&&j(e))return e;let r=g.fleetDefaultsPath??Me.join(process.cwd(),"config","fleet-defaults.yaml");return z===void 0&&(z=ze(r)),z||We}var Fe,We,z,Pe=ae(()=>{"use strict";Fe=["low","medium","high","xhigh","max"],We="xhigh"});function je(g){try{let t=G(g);return{sendSampling:t.supportsSamplingParams!==!1,supportsEffort:t.supportsEffortXHigh===!0}}catch{return{sendSampling:!1,supportsEffort:!1}}}function H(g,t,e){let r=je(t);if(r.sendSampling&&e.temperature!==void 0&&(g.temperature=e.temperature),r.supportsEffort){let o=e.effort??(He(t)?Le():void 0);o!==void 0&&(g.output_config={effort:o})}return g}function He(g){return ve(g)?.tier==="flagship"}var he=ae(()=>{"use strict";$();Pe()});function lt(g){try{let t=G(g);return{sendSampling:t.supportsSamplingParams!==!1,maxTokensField:t.usesMaxCompletionTokens===!0?"max_completion_tokens":"max_tokens"}}catch{return it.test(g)?{...ct}:{...at}}}function U(g,t,e){let r=lt(t),o=g;return e.maxTokens!==void 0&&(o[r.maxTokensField]=e.maxTokens),r.sendSampling&&e.temperature!==void 0&&(o.temperature=e.temperature),g}var it,at,ct,ge=ae(()=>{"use strict";$();it=/^(openai\/)?(gpt-5|gpt-6|o\d)/i,at={sendSampling:!0,maxTokensField:"max_tokens"},ct={sendSampling:!1,maxTokensField:"max_completion_tokens"}});De();L();var Re={failureThreshold:5,resetTimeoutMs:3e4,halfOpenSuccessThreshold:2,failureWindowMs:6e4,includeTimeouts:!0},ue=class{state="closed";failures=[];successCount=0;totalRequests=0;totalSuccesses=0;totalFailures=0;rejectedCount=0;lastFailureTime;lastSuccessTime;openedAt;halfOpenSuccesses=0;config;providerType;constructor(t,e={}){this.providerType=t,this.config={...Re,...e}}getState(){return this.state==="open"&&this.openedAt&&Date.now()-this.openedAt.getTime()>=this.config.resetTimeoutMs&&this.transitionTo("half-open"),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t!=="open"}async execute(t){if(this.totalRequests++,this.getState()==="open")throw this.rejectedCount++,a(`Circuit breaker is open for provider ${this.providerType}`,"CIRCUIT_OPEN",{provider:this.providerType,retryable:!0,retryAfterMs:this.getTimeUntilTransition()});try{let r=await t();return this.recordSuccess(),r}catch(r){throw this.recordFailure(E(r)),r}}recordSuccess(){this.successCount++,this.totalSuccesses++,this.lastSuccessTime=new Date,this.getState()==="half-open"&&(this.halfOpenSuccesses++,this.halfOpenSuccesses>=this.config.halfOpenSuccessThreshold&&this.transitionTo("closed"))}recordFailure(t){if(this.totalFailures++,this.lastFailureTime=new Date,(t.message.toLowerCase().includes("timeout")||t.name==="TimeoutError"||t.name==="AbortError")&&!this.config.includeTimeouts)return;this.failures.push({timestamp:new Date,error:t}),this.cleanOldFailures();let r=this.getState();if(r==="half-open"){this.transitionTo("open");return}r==="closed"&&this.failures.length>=this.config.failureThreshold&&this.transitionTo("open")}getStats(){return{state:this.getState(),totalRequests:this.totalRequests,successCount:this.totalSuccesses,failureCount:this.totalFailures,rejectedCount:this.rejectedCount,lastFailureTime:this.lastFailureTime,lastSuccessTime:this.lastSuccessTime,timeUntilTransitionMs:this.getTimeUntilTransition()}}reset(){this.state="closed",this.failures=[],this.successCount=0,this.halfOpenSuccesses=0,this.openedAt=void 0}forceOpen(){this.transitionTo("open")}forceHalfOpen(){this.transitionTo("half-open")}getRecentFailures(t=5){return this.failures.slice(-t).map(e=>`[${e.timestamp.toISOString()}] ${e.error.message}`)}transitionTo(t){if(this.state!==t)switch(this.state=t,t){case"open":this.openedAt=new Date,this.halfOpenSuccesses=0;break;case"half-open":this.halfOpenSuccesses=0;break;case"closed":this.failures=[],this.openedAt=void 0,this.halfOpenSuccesses=0;break}}cleanOldFailures(){let t=Date.now()-this.config.failureWindowMs;this.failures=this.failures.filter(e=>e.timestamp.getTime()>t)}getTimeUntilTransition(){if(this.state==="open"&&this.openedAt){let t=Date.now()-this.openedAt.getTime(),e=this.config.resetTimeoutMs-t;return Math.max(0,e)}}},F=class{breakers=new Map;defaultConfig;constructor(t={}){this.defaultConfig={...Re,...t}}getBreaker(t,e){let r=this.breakers.get(t);return r||(r=new ue(t,{...this.defaultConfig,...e}),this.breakers.set(t,r)),r}getAllStats(){let t={};for(let[e,r]of this.breakers)t[e]=r.getStats();return t}getAvailableProviders(){let t=[];for(let[e,r]of this.breakers)r.canExecute()&&t.push(e);return t}resetAll(){for(let t of this.breakers.values())t.reset()}reset(t){let e=this.breakers.get(t);e&&e.reset()}};var we={maxSize:1e3,defaultTtlMs:36e5,enableLRU:!0,cacheGenerations:!0,cacheEmbeddings:!0,cacheCompletions:!0},A=class{cache=new Map;accessOrder=[];config;hits=0;misses=0;evictions=0;constructor(t={}){this.config={...we,...t}}static generateKey(t,e,r){let s=[t,r?.model??"default",String(r?.temperature??.7),String(r?.maxTokens??0),r?.systemPrompt??"",e].join("|"),n=0;for(let i=0;i<s.length;i++){let l=s.charCodeAt(i);n=(n<<5)-n+l,n=n&n}return`${t}:${Math.abs(n).toString(36)}`}get(t){let e=this.cache.get(t);if(!e){this.misses++;return}if(e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs){this.delete(t),this.misses++;return}return this.hits++,e.lastAccessedAt=new Date,e.accessCount++,this.config.enableLRU&&this.updateAccessOrder(t),e.value}set(t,e,r){this.cache.size>=this.config.maxSize&&!this.cache.has(t)&&this.evictLRU();let o={value:e,createdAt:new Date,lastAccessedAt:new Date,accessCount:1,ttlMs:r??this.config.defaultTtlMs,keyHash:t};this.cache.set(t,o),this.config.enableLRU&&this.updateAccessOrder(t)}has(t){let e=this.cache.get(t);return e?e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs?(this.delete(t),!1):!0:!1}delete(t){let e=this.cache.delete(t);if(e){let r=this.accessOrder.indexOf(t);r!==-1&&this.accessOrder.splice(r,1)}return e}clear(){this.cache.clear(),this.accessOrder=[],this.hits=0,this.misses=0,this.evictions=0}getStats(){let t=this.hits+this.misses,e=t>0?this.hits/t:0,r=0;for(let o of this.cache.values())r+=this.estimateSize(o.value);return{size:this.cache.size,maxSize:this.config.maxSize,hits:this.hits,misses:this.misses,hitRate:e,evictions:this.evictions,memoryUsageBytes:r}}keys(){return Array.from(this.cache.keys())}entries(){return Array.from(this.cache.entries())}import(t){for(let[e,r]of t)r.createdAt=new Date(r.createdAt),r.lastAccessedAt=new Date(r.lastAccessedAt),this.cache.set(e,r),this.accessOrder.push(e);for(;this.cache.size>this.config.maxSize;)this.evictLRU()}pruneExpired(){let t=Date.now(),e=0;for(let[r,o]of this.cache.entries())o.ttlMs>0&&t-o.createdAt.getTime()>o.ttlMs&&(this.delete(r),e++);return e}updateAccessOrder(t){let e=this.accessOrder.indexOf(t);e!==-1&&this.accessOrder.splice(e,1),this.accessOrder.push(t)}evictLRU(){if(this.accessOrder.length===0){let e=this.cache.keys().next().value;e&&(this.cache.delete(e),this.evictions++);return}let t=this.accessOrder.shift();t&&(this.cache.delete(t),this.evictions++)}estimateSize(t){return t==null?0:JSON.stringify(t).length*2}},W=class{generationCache;embeddingCache;completionCache;config;constructor(t={}){this.config={...we,...t},this.generationCache=new A(t),this.embeddingCache=new A(t),this.completionCache=new A(t)}getGeneration(t,e){if(!this.config.cacheGenerations)return;let r=A.generateKey("generation",t,e);return this.generationCache.get(r)}setGeneration(t,e,r,o){if(!this.config.cacheGenerations)return;let s=A.generateKey("generation",t,r);this.generationCache.set(s,e,o)}getEmbedding(t,e){if(!this.config.cacheEmbeddings)return;let r=A.generateKey("embedding",t,e);return this.embeddingCache.get(r)}setEmbedding(t,e,r,o){if(!this.config.cacheEmbeddings)return;let s=A.generateKey("embedding",t,r);this.embeddingCache.set(s,e,o)}getCompletion(t,e){if(!this.config.cacheCompletions)return;let r=A.generateKey("completion",t,e);return this.completionCache.get(r)}setCompletion(t,e,r,o){if(!this.config.cacheCompletions)return;let s=A.generateKey("completion",t,r);this.completionCache.set(s,e,o)}getStats(){let t=this.generationCache.getStats(),e=this.embeddingCache.getStats(),r=this.completionCache.getStats(),o=t.hits+e.hits+r.hits,s=t.misses+e.misses+r.misses,n=o+s;return{generation:t,embedding:e,completion:r,total:{size:t.size+e.size+r.size,maxSize:this.config.maxSize*3,hits:o,misses:s,hitRate:n>0?o/n:0,evictions:t.evictions+e.evictions+r.evictions,memoryUsageBytes:t.memoryUsageBytes+e.memoryUsageBytes+r.memoryUsageBytes}}}clear(){this.generationCache.clear(),this.embeddingCache.clear(),this.completionCache.clear()}pruneExpired(){return this.generationCache.pruneExpired()+this.embeddingCache.pruneExpired()+this.completionCache.pruneExpired()}};S();var pe="(unattributed)",qe=`
3
3
  CREATE TABLE IF NOT EXISTS llm_spend (
4
4
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5
5
  ts INTEGER NOT NULL,
@@ -17,7 +17,7 @@ CREATE INDEX IF NOT EXISTS idx_llm_spend_ts ON llm_spend(ts);
17
17
  VALUES (@ts, @provider, @model, @cost_usd, @cost_source, @prompt_tokens, @completion_tokens, @request_id, @agent_type)`).run({ts:Date.now(),provider:t.provider,model:t.model,cost_usd:t.costUsd,cost_source:t.costSource,prompt_tokens:t.promptTokens,completion_tokens:t.completionTokens,request_id:t.requestId,agent_type:t.agent??null}):this.db.prepare(`INSERT INTO llm_spend
18
18
  (ts, provider, model, cost_usd, cost_source, prompt_tokens, completion_tokens, request_id)
19
19
  VALUES (@ts, @provider, @model, @cost_usd, @cost_source, @prompt_tokens, @completion_tokens, @request_id)`).run({ts:Date.now(),provider:t.provider,model:t.model,cost_usd:t.costUsd,cost_source:t.costSource,prompt_tokens:t.promptTokens,completion_tokens:t.completionTokens,request_id:t.requestId})}catch{}}spentSince(t,e=Date.now()){try{return this.db.prepare("SELECT COALESCE(SUM(cost_usd), 0) AS total FROM llm_spend WHERE ts >= ?").get(e-t)?.total??0}catch{return 0}}spentByAgentSince(t,e=Date.now()){try{let r=this.db.prepare(`SELECT COALESCE(agent_type, ?) AS agent, COALESCE(SUM(cost_usd), 0) AS total
20
- FROM llm_spend WHERE ts >= ? GROUP BY COALESCE(agent_type, ?)`).all(pe,e-t,pe),o={};for(let s of r)o[s.agent]=s.total;return o}catch{return{}}}},K=class{entries=[];record(t){this.entries.push({ts:Date.now(),costUsd:t.costUsd,agent:t.agent??pe})}spentSince(t,e=Date.now()){let r=e-t,o=0;for(let s of this.entries)s.ts>=r&&(o+=s.costUsd);return o}spentByAgentSince(t,e=Date.now()){let r=e-t,o={};for(let s of this.entries)s.ts>=r&&(o[s.agent]=(o[s.agent]??0)+s.costUsd);return o}};async function Ae(){try{let t=(await import("./unified-memory-CXHLHB5I.js")).getUnifiedMemory();return t.isInitialized()||await t.initialize(),new de(t.getDatabase())}catch{return new K}}S();L();function me(g,t,e,r){let o=Math.min(t*Math.pow(2,g),e),s=Math.random()*r*o;return o+s}var Be=1e3,Ge=3e4;function T(g,t=Be,e=Ge){return me(g,t,e,0)}he();$();var Ve={model:ce,maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,anthropicVersion:"2023-06-01",enableCache:!0,enableCircuitBreaker:!0},V=class{type="claude";name="Anthropic Claude";config;requestId=0;constructor(t={}){this.config={...Ve,...t}}async isAvailable(){if(!this.getApiKey())return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){if(!this.getApiKey())return{healthy:!1,error:"API key not configured. Set ANTHROPIC_API_KEY environment variable."};let e=Date.now();try{let r=await this.fetchWithTimeout(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:this.config.model,max_tokens:1,messages:[{role:"user",content:"Hi"}]})},5e3),o=Date.now()-e;if(!r.ok){let s=await r.text();return{healthy:!1,latencyMs:o,error:`API error: ${r.status} - ${s}`}}return{healthy:!0,latencyMs:o,models:this.getSupportedModels(),details:{apiVersion:this.config.anthropicVersion,defaultModel:this.config.model}}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(t,e){if(!this.getApiKey())throw a("Anthropic API key not configured","API_KEY_MISSING",{provider:"claude",retryable:!1});let o=this.formatMessages(t),s=e?.model??this.config.model,n=e?.maxTokens??this.config.maxTokens??4096,i=e?.temperature??this.config.temperature??.7,l=`claude-${++this.requestId}-${Date.now()}`,p=Date.now(),m={model:s,max_tokens:n,messages:o};H(m,s,{temperature:i,effort:e?.effort}),e?.systemPrompt&&(m.system=this.config.enableCache!==!1?[{type:"text",text:e.systemPrompt,cache_control:{type:"ephemeral"}}]:e.systemPrompt),e?.stopSequences&&e.stopSequences.length>0&&(m.stop_sequences=e.stopSequences);try{let c=await this.fetchWithRetry(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(m)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),u=Date.now()-p;if(!c.ok){let k=await c.json().catch(()=>({error:{message:"Unknown error"}}));throw this.handleApiError(c.status,k,s)}let d=await c.json(),h=d.usage.cache_creation_input_tokens??0,f=d.usage.cache_read_input_tokens??0,b={promptTokens:d.usage.input_tokens,completionTokens:d.usage.output_tokens,totalTokens:d.usage.input_tokens+h+f+d.usage.output_tokens,cacheCreationTokens:h,cacheReadTokens:f},y=_.calculateCost(s,b);return v.recordTokenUsage(l,"claude-provider","llm","generate",{inputTokens:d.usage.input_tokens,outputTokens:d.usage.output_tokens,totalTokens:d.usage.input_tokens+d.usage.output_tokens,estimatedCostUsd:y.totalCost}),{content:d.content.filter(k=>k.type==="text").map(k=>k.text).join(""),model:d.model,provider:"claude",usage:b,cost:y,latencyMs:u,finishReason:this.mapFinishReason(d.stop_reason),cached:!1,requestId:l}}catch(c){throw c instanceof Error&&"code"in c?c:a(c instanceof Error?c.message:"Request failed","NETWORK_ERROR",{provider:"claude",model:s,retryable:!0,cause:c})}}async embed(t,e){throw a("Claude does not support native embeddings. Use OpenAI or Ollama for embeddings.","MODEL_NOT_FOUND",{provider:"claude",retryable:!1})}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
20
+ FROM llm_spend WHERE ts >= ? GROUP BY COALESCE(agent_type, ?)`).all(pe,e-t,pe),o={};for(let s of r)o[s.agent]=s.total;return o}catch{return{}}}},K=class{entries=[];record(t){this.entries.push({ts:Date.now(),costUsd:t.costUsd,agent:t.agent??pe})}spentSince(t,e=Date.now()){let r=e-t,o=0;for(let s of this.entries)s.ts>=r&&(o+=s.costUsd);return o}spentByAgentSince(t,e=Date.now()){let r=e-t,o={};for(let s of this.entries)s.ts>=r&&(o[s.agent]=(o[s.agent]??0)+s.costUsd);return o}};async function Ae(){try{let t=(await import("./unified-memory-DDWMC435.js")).getUnifiedMemory();return t.isInitialized()||await t.initialize(),new de(t.getDatabase())}catch{return new K}}S();L();function me(g,t,e,r){let o=Math.min(t*Math.pow(2,g),e),s=Math.random()*r*o;return o+s}var Be=1e3,Ge=3e4;function T(g,t=Be,e=Ge){return me(g,t,e,0)}he();$();var Ve={model:ce,maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,anthropicVersion:"2023-06-01",enableCache:!0,enableCircuitBreaker:!0},V=class{type="claude";name="Anthropic Claude";config;requestId=0;constructor(t={}){this.config={...Ve,...t}}async isAvailable(){if(!this.getApiKey())return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){if(!this.getApiKey())return{healthy:!1,error:"API key not configured. Set ANTHROPIC_API_KEY environment variable."};let e=Date.now();try{let r=await this.fetchWithTimeout(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:this.config.model,max_tokens:1,messages:[{role:"user",content:"Hi"}]})},5e3),o=Date.now()-e;if(!r.ok){let s=await r.text();return{healthy:!1,latencyMs:o,error:`API error: ${r.status} - ${s}`}}return{healthy:!0,latencyMs:o,models:this.getSupportedModels(),details:{apiVersion:this.config.anthropicVersion,defaultModel:this.config.model}}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(t,e){if(!this.getApiKey())throw a("Anthropic API key not configured","API_KEY_MISSING",{provider:"claude",retryable:!1});let o=this.formatMessages(t),s=e?.model??this.config.model,n=e?.maxTokens??this.config.maxTokens??4096,i=e?.temperature??this.config.temperature??.7,l=`claude-${++this.requestId}-${Date.now()}`,p=Date.now(),m={model:s,max_tokens:n,messages:o};H(m,s,{temperature:i,effort:e?.effort}),e?.systemPrompt&&(m.system=this.config.enableCache!==!1?[{type:"text",text:e.systemPrompt,cache_control:{type:"ephemeral"}}]:e.systemPrompt),e?.stopSequences&&e.stopSequences.length>0&&(m.stop_sequences=e.stopSequences);try{let c=await this.fetchWithRetry(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(m)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),u=Date.now()-p;if(!c.ok){let k=await c.json().catch(()=>({error:{message:"Unknown error"}}));throw this.handleApiError(c.status,k,s)}let d=await c.json(),h=d.usage.cache_creation_input_tokens??0,f=d.usage.cache_read_input_tokens??0,b={promptTokens:d.usage.input_tokens,completionTokens:d.usage.output_tokens,totalTokens:d.usage.input_tokens+h+f+d.usage.output_tokens,cacheCreationTokens:h,cacheReadTokens:f},y=_.calculateCost(s,b);return v.recordTokenUsage(l,"claude-provider","llm","generate",{inputTokens:d.usage.input_tokens,outputTokens:d.usage.output_tokens,totalTokens:d.usage.input_tokens+d.usage.output_tokens,estimatedCostUsd:y.totalCost}),{content:d.content.filter(k=>k.type==="text").map(k=>k.text).join(""),model:d.model,provider:"claude",usage:b,cost:y,latencyMs:u,finishReason:this.mapFinishReason(d.stop_reason),cached:!1,requestId:l}}catch(c){throw c instanceof Error&&"code"in c?c:a(c instanceof Error?c.message:"Request failed","NETWORK_ERROR",{provider:"claude",model:s,retryable:!0,cause:c})}}async embed(t,e){throw a("Claude does not support native embeddings. Use OpenAI or Ollama for embeddings.","MODEL_NOT_FOUND",{provider:"claude",retryable:!1})}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
21
21
 
22
22
  `,"```"]});return{completion:r.content,model:r.model,provider:"claude",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return["claude-opus-4-7","claude-sonnet-4-6","claude-haiku-4-5-20251001","claude-3-opus-20240229","claude-3-sonnet-20240229","claude-3-haiku-20240307"]}getCostPerToken(){return _.getCostPerToken(this.config.model)}async dispose(){}getApiKey(){return this.config.apiKey??process.env.ANTHROPIC_API_KEY}getBaseUrl(){return(this.config.baseUrl??process.env.ANTHROPIC_BASE_URL??"https://api.anthropic.com").replace(/\/$/,"")}getHeaders(){return{"Content-Type":"application/json","x-api-key":this.getApiKey(),"anthropic-version":this.config.anthropicVersion??"2023-06-01"}}formatMessages(t){return typeof t=="string"?[{role:"user",content:t}]:t.filter(e=>e.role!=="system").map(e=>({role:e.role,content:e.content}))}mapFinishReason(t){switch(t){case"end_turn":return"stop";case"max_tokens":return"length";case"stop_sequence":return"stop";default:return"stop"}}handleApiError(t,e,r){let o="error"in e?e.error?.message??"Unknown API error":"Unknown API error",s="error"in e&&"type"in e.error?e.error.type:"";switch(t){case 401:throw a(o,"API_KEY_INVALID",{provider:"claude",model:r,retryable:!1});case 429:throw a(o,"RATE_LIMITED",{provider:"claude",model:r,retryable:!0,retryAfterMs:6e4});case 400:throw s==="invalid_request_error"&&o.includes("context")?a(o,"CONTEXT_LENGTH_EXCEEDED",{provider:"claude",model:r,retryable:!1}):a(o,"UNKNOWN",{provider:"claude",model:r,retryable:!1});case 500:case 502:case 503:throw a(o,"PROVIDER_UNAVAILABLE",{provider:"claude",model:r,retryable:!0,retryAfterMs:5e3});default:throw a(o,"UNKNOWN",{provider:"claude",model:r,retryable:!1})}}async fetchWithTimeout(t,e,r){let o=new AbortController,s=setTimeout(()=>o.abort(),r);try{return await fetch(t,{...e,signal:o.signal})}catch(n){throw n instanceof Error&&n.name==="AbortError"?a("Request timed out","TIMEOUT",{provider:"claude",retryable:!0}):n}finally{clearTimeout(s)}}async fetchWithRetry(t,e,r,o){let s;for(let n=0;n<o;n++)try{let i=await this.fetchWithTimeout(t,e,r);if(i.status>=400&&i.status<500&&i.status!==429)return i;if((i.status>=500||i.status===429)&&n<o-1){let l=T(n);await this.sleep(l);continue}return i}catch(i){if(s=E(i),n<o-1){let l=T(n);await this.sleep(l)}}throw s??new Error("Request failed after retries")}sleep(t){return new Promise(e=>setTimeout(e,t))}};import{spawn as Ye}from"node:child_process";var Je=["ANTHROPIC_API_KEY","CLAUDE_API_KEY","ANTHROPIC_AUTH_TOKEN"],Xe={model:"sonnet",maxTokens:4096,temperature:.7,timeoutMs:12e4,maxRetries:1,binaryPath:"claude",maxConcurrency:2,disallowedTools:["Bash","Edit","Write","NotebookEdit","WebFetch","WebSearch","Task"]},Y=class g{type="claude-code";name="Claude Code (subscription)";billingMode="subscription";config;requestId=0;availabilityCache;active=0;queue=[];constructor(t={}){this.config={...Xe,...t};let e=Number.parseInt(process.env.AQE_CLAUDE_CODE_CONCURRENCY??"",10);Number.isFinite(e)&&e>0&&(this.config.maxConcurrency=e)}async isAvailable(){let t=Date.now();if(this.availabilityCache&&t-this.availabilityCache.at<6e4)return this.availabilityCache.available;let e=!1;try{let{code:r}=await this.runProcess(["--version"],void 0,5e3);e=r===0}catch{e=!1}return this.availabilityCache={at:t,available:e},e}async healthCheck(){let t=Date.now(),e=await this.isAvailable(),r=Date.now()-t;return e?{healthy:!0,latencyMs:r,models:this.getSupportedModels(),details:{binaryPath:this.config.binaryPath,billing:"subscription"}}:{healthy:!1,latencyMs:r,error:`Claude Code CLI ("${this.config.binaryPath}") not found or not runnable. Install Claude Code and log in with your Pro/Max account.`}}async generate(t,e){let r=this.toCliModel(e?.model??this.config.model),o=`claude-code-${++this.requestId}-${Date.now()}`,{prompt:s,systemPrompt:n}=this.flatten(t,e?.systemPrompt),i=["-p","--output-format","json","--model",r];n&&i.push("--append-system-prompt",n);let l=this.config.disallowedTools??[];l.length>0&&i.push("--disallowedTools",...l);let p=Date.now(),m=e?.timeoutMs??this.config.timeoutMs??12e4,{code:c,stdout:u,stderr:d}=await this.withConcurrency(()=>this.runProcess(i,s,m)),h=Date.now()-p;if(c!==0&&!u.trim())throw this.classifyError(d||`claude exited with code ${c}`,r);let f;try{f=JSON.parse(u)}catch{throw a(`Could not parse claude -p JSON output: ${u.slice(0,200)}`,"PROVIDER_UNAVAILABLE",{provider:"claude-code",model:r,retryable:!0})}if(f.is_error)throw this.classifyError(f.result??f.api_error_status??"claude error",r);let b=f.usage??{},y={promptTokens:b.input_tokens??0,completionTokens:b.output_tokens??0,totalTokens:(b.input_tokens??0)+(b.output_tokens??0),cacheCreationTokens:b.cache_creation_input_tokens??0,cacheReadTokens:b.cache_read_input_tokens??0},C=f.modelUsage&&Object.keys(f.modelUsage)[0]||r;return v.recordTokenUsage(o,"claude-code-provider","llm","generate",{inputTokens:y.promptTokens,outputTokens:y.completionTokens,totalTokens:y.totalTokens,estimatedCostUsd:0}),{content:f.result??"",model:C,provider:"claude-code",usage:y,cost:{inputCost:0,outputCost:0,totalCost:0,currency:"USD",source:"provider-receipt"},latencyMs:h,finishReason:this.mapFinishReason(f.stop_reason),cached:!1,requestId:o}}async embed(t,e){throw a("Claude Code provider does not support embeddings. Use openai, ollama, or cognitum.","MODEL_NOT_FOUND",{provider:"claude-code",retryable:!1})}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256});return{completion:r.content,model:r.model,provider:"claude-code",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return["opus","sonnet","haiku"]}getCostPerToken(){return{input:0,output:0}}async dispose(){}toCliModel(t){let e=t.toLowerCase();return e.includes("opus")?"opus":e.includes("haiku")?"haiku":e.includes("sonnet")?"sonnet":t}flatten(t,e){if(typeof t=="string")return{prompt:t,systemPrompt:e};let r=t.filter(s=>s.role==="system").map(s=>s.content);return e&&r.unshift(e),{prompt:t.filter(s=>s.role!=="system").map(s=>`${s.role==="assistant"?"Assistant":"User"}: ${s.content}`).join(`
23
23
 
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.4");process.exit(0)}
2
- import{i as c}from"./chunk-T6BVLVI5.js";import{a as p}from"./chunk-NA7B2QYB.js";import{c as m}from"./chunk-Y3MW3YBC.js";import{b as g,d as E}from"./chunk-DHJPWQBR.js";import{a as l,b as _}from"./chunk-BGE6FOLM.js";_();import b from"node:path";import{existsSync as h}from"node:fs";E();p();var T=m.create("metrics-tracker"),d=class{db=null;dbPath;initialized=!1;constructor(e=process.cwd()){this.dbPath=b.join(e,".agentic-qe","memory.db")}async initialize(){if(!this.initialized){if(!h(this.dbPath))throw new Error(`Database not found: ${this.dbPath}. Run "aqe init --auto" first.`);this.db=l(this.dbPath),this.ensureMetricsTable(),this.initialized=!0}}ensureMetricsTable(){this.db&&this.db.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
+ import{i as c}from"./chunk-5WOSWNDN.js";import{b as g,d as E}from"./chunk-IJHCIXJC.js";import{a as p}from"./chunk-J27F4NSB.js";import{c as m}from"./chunk-7CD7PBHY.js";import{a as l,b as _}from"./chunk-HVU64GP5.js";_();import b from"node:path";import{existsSync as h}from"node:fs";E();p();var T=m.create("metrics-tracker"),d=class{db=null;dbPath;initialized=!1;constructor(e=process.cwd()){this.dbPath=b.join(e,".agentic-qe","memory.db")}async initialize(){if(!this.initialized){if(!h(this.dbPath))throw new Error(`Database not found: ${this.dbPath}. Run "aqe init --auto" first.`);this.db=l(this.dbPath),this.ensureMetricsTable(),this.initialized=!0}}ensureMetricsTable(){this.db&&this.db.exec(`
3
3
  CREATE TABLE IF NOT EXISTS learning_daily_snapshots (
4
4
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5
5
  snapshot_date TEXT NOT NULL UNIQUE,
@@ -0,0 +1,13 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
+ import{b as z,c as pe}from"./chunk-C3HQL6S4.js";import{a as F,c as le}from"./chunk-J5UNP6W3.js";import{b as G,d as k}from"./chunk-NU7UTXMP.js";k();le();k();import*as C from"node:http";import*as _ from"node:https";import{createHash as ce}from"node:crypto";import{URL as X}from"node:url";var T={model:"Xenova/all-MiniLM-L6-v2",expectedDim:384,connectTimeoutMs:5e3,requestTimeoutMs:3e4,failureThreshold:3,failureWindowMs:6e4},me="AQE embedder endpoint identity canary v1",ue="/v1/embeddings";function J(t){if(t.startsWith("unix:"))return t;try{let e=new X(t);return e.username||e.password?(e.username="",e.password="",e.toString().replace(/\/$/,"")):t}catch{return t}}function fe(t){if(t.startsWith("unix:")){let r=t.slice(5);if(!r.startsWith("/"))throw new Error(`unix endpoint must be an absolute path: ${t}`);return{transport:"unix",socketPath:r,safeUrl:t}}let e=new X(t);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`unsupported embedder endpoint protocol: ${e.protocol}`);return(e.username||e.password)&&(console.warn("[EmbedderEndpointClient] endpoint URL contained userinfo; stripping. Use AQE_EMBEDDER_TOKEN env var for credentials."),e.username="",e.password=""),{transport:e.protocol==="https:"?"https":"http",host:e.hostname,port:e.port?Number(e.port):e.protocol==="https:"?443:80,protocol:e.protocol,safeUrl:e.toString().replace(/\/$/,"")}}var q=class{constructor(e,n,r=()=>{}){this.threshold=e;this.windowMs=n;this.onRecover=r}threshold;windowMs;onRecover;failures=[];trippedAt=null;recordSuccess(){this.failures=[],this.trippedAt=null}recordFailure(){let e=Date.now();this.failures=this.failures.filter(n=>e-n<this.windowMs),this.failures.push(e),this.failures.length>=this.threshold&&(this.trippedAt=e)}isOpen(){return this.trippedAt===null?!1:Date.now()-this.trippedAt>=this.windowMs?(this.failures=[],this.trippedAt=null,this.onRecover(),!1):!0}getState(){return{open:this.isOpen(),failures:this.failures.length,trippedAt:this.trippedAt}}},R=class{parsed;agent;breaker;opts;cachedIdentity=null;probeInFlight=null;constructor(e){if(this.opts={endpoint:e.endpoint,token:e.token,model:e.model??T.model,expectedDim:e.expectedDim??T.expectedDim,connectTimeoutMs:e.connectTimeoutMs??T.connectTimeoutMs,requestTimeoutMs:e.requestTimeoutMs??T.requestTimeoutMs,failureThreshold:e.failureThreshold??T.failureThreshold,failureWindowMs:e.failureWindowMs??T.failureWindowMs,tlsOptions:e.tlsOptions},this.parsed=fe(e.endpoint),this.parsed.transport==="https"){let n=e.tlsOptions??{};this.agent=new _.Agent({keepAlive:!0,ca:n.ca,cert:n.cert,key:n.key,rejectUnauthorized:n.rejectUnauthorized!==!1,servername:n.servername})}else this.agent=new C.Agent({keepAlive:!0});this.breaker=new q(this.opts.failureThreshold,this.opts.failureWindowMs,()=>{this.cachedIdentity=null})}getSafeEndpoint(){return this.parsed.safeUrl}async embed(e){if(e.length===0)return[];if(this.breaker.isOpen())throw new Error(`[EmbedderEndpointClient] circuit breaker open for ${this.parsed.safeUrl} \u2014 fast-failing`);this.cachedIdentity===null&&await this.ensureProbed();try{let n=await this.postEmbeddings(e),r=this.decodeAndNormalize(n,e.length);return this.breaker.recordSuccess(),r}catch(n){throw this.breaker.recordFailure(),n}}async probe(){return this.probeInFlight?this.probeInFlight:(this.probeInFlight=this.doProbe().finally(()=>{this.probeInFlight=null}),this.probeInFlight)}async ensureProbed(){return this.cachedIdentity?this.cachedIdentity:this.probe()}async doProbe(){let e;try{let a=await this.postEmbeddings([me]);e=this.decodeAndNormalize(a,1)[0],this.breaker.recordSuccess()}catch(a){throw this.breaker.recordFailure(),a}if(!e||e.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch: expected ${this.opts.expectedDim}, got ${e?.length??0} from ${this.parsed.safeUrl}`);let n=Buffer.alloc(e.length*2);for(let a=0;a<e.length;a++){let i=Math.max(-32768,Math.min(32767,Math.round(e[a]*32767)));n.writeInt16LE(i,a*2)}let r=ce("sha256").update(n).digest("hex").slice(0,16);return this.cachedIdentity={dim:e.length,fingerprint:r,endpoint:this.parsed.safeUrl},this.cachedIdentity}getCachedIdentity(){return this.cachedIdentity}getBreakerState(){return this.breaker.getState()}close(){this.agent.destroy()}decodeAndNormalize(e,n){if(!e||typeof e!="object"||!Array.isArray(e.data))throw new Error("[EmbedderEndpointClient] response missing data array");let r=e.data;if(r.length!==n)throw new Error(`[EmbedderEndpointClient] response count mismatch: expected ${n}, got ${r.length}`);let a=r.map((i,s)=>({idx:typeof i.index=="number"?i.index:s,embedding:i.embedding}));return a.sort((i,s)=>i.idx-s.idx),a.map(({embedding:i},s)=>{if(typeof i=="string")throw new Error(`[EmbedderEndpointClient] received base64 embedding at position ${s} \u2014 server ignored encoding_format=float. Configure the server to return float arrays.`);if(!Array.isArray(i))throw new Error(`[EmbedderEndpointClient] missing embedding at position ${s}`);if(i.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch at position ${s}: expected ${this.opts.expectedDim}, got ${i.length}`);return G(i)})}postEmbeddings(e){let n=JSON.stringify({model:this.opts.model,input:e,encoding_format:"float"});return this.request(ue,n)}request(e,n){let r={"content-type":"application/json","content-length":Buffer.byteLength(n),accept:"application/json"};this.opts.token&&(r.authorization=`Bearer ${this.opts.token}`);let a={method:"POST",path:e,headers:r,agent:this.agent},i,s;this.parsed.transport==="unix"?(i={...a,socketPath:this.parsed.socketPath},s=C.request):(i={...a,host:this.parsed.host,port:this.parsed.port,protocol:this.parsed.protocol},s=this.parsed.transport==="https"?_.request:C.request);let o=this.parsed.safeUrl,l=this.opts.connectTimeoutMs,m=this.opts.requestTimeoutMs;return new Promise((b,$)=>{let y=!1,M=d=>{y||(y=!0,b(d))},h=d=>{y||(y=!0,$(d))},w=s(i,d=>{let g=[];d.on("data",u=>g.push(Buffer.from(u))),d.on("end",()=>{let u=Buffer.concat(g).toString("utf-8");if(!d.statusCode||d.statusCode<200||d.statusCode>=300){h(new Error(`[EmbedderEndpointClient] HTTP ${d.statusCode} from ${o}: ${u.slice(0,200)}`));return}try{let E=JSON.parse(u);M(E)}catch(E){h(new Error(`[EmbedderEndpointClient] invalid JSON from ${o}: ${E.message}`))}}),d.on("error",u=>h(u))});w.on("socket",d=>{d.setTimeout(l);let g=()=>{d.setTimeout(m)};d.connecting?d.once("connect",g):g(),d.on("timeout",()=>{let u=d.connecting?"connect":"request",E=d.connecting?l:m,S=new Error(`[EmbedderEndpointClient] ${u} timeout after ${E}ms`);h(S),w.destroy(S)})}),w.on("error",d=>h(d)),w.write(n),w.end()})}};pe();import{join as K,resolve as ge}from"node:path";import{existsSync as he,mkdirSync as Ee}from"node:fs";import{createRequire as be}from"node:module";var ye=be(import.meta.url);function we(){let t=process.env.AQE_MEMORY_PATH;return t&&t.length>0?t===":memory:"?t:ge(z(),t):K(z(),".agentic-qe","memory.db")}var Q="_system",Y="embedder_identity:",x=null,U=!1;function Z(){if(x)return x;if(U)return null;try{let t=ye("better-sqlite3"),e=we(),n=K(e,"..");he(n)||Ee(n,{recursive:!0});let r=new t(e);return r.pragma("journal_mode = WAL"),r.pragma("busy_timeout = 5000"),r.exec(`
3
+ CREATE TABLE IF NOT EXISTS kv_store (
4
+ key TEXT NOT NULL,
5
+ namespace TEXT NOT NULL,
6
+ value TEXT NOT NULL,
7
+ expires_at INTEGER,
8
+ created_at INTEGER DEFAULT (strftime('%s', 'now') * 1000),
9
+ PRIMARY KEY (namespace, key)
10
+ );
11
+ CREATE INDEX IF NOT EXISTS idx_kv_namespace ON kv_store(namespace);
12
+ `),x=r,r}catch{return U=!0,null}}function ee(t){let e=Z();if(!e)return null;try{let n=e.prepare("SELECT value FROM kv_store WHERE namespace = ? AND key = ?").get(Q,Y+t);if(!n)return null;let r=JSON.parse(n.value);return!r.fingerprint||typeof r.dim!="number"?null:{fingerprint:r.fingerprint,dim:r.dim,endpoint:r.endpoint}}catch{return null}}function te(t){let e=Z();if(!e)return;let n={fingerprint:t.fingerprint,dim:t.dim,endpoint:t.endpoint,updatedAt:Date.now()};e.prepare("INSERT OR REPLACE INTO kv_store (key, namespace, value) VALUES (?, ?, ?)").run(Y+t.endpoint,Q,JSON.stringify(n))}function ne(){if(x)try{x.close()}catch{}x=null,U=!1}k();import{createHash as re}from"node:crypto";import{existsSync as ve,readFileSync as Ae,renameSync as Te,writeFileSync as xe}from"node:fs";var ie="aqe embedding-space compatibility canary v1";var I=class extends Error{constructor(n,r){super(`${n}: ${r}`);this.code=n;this.name="EmbeddingSpaceError"}code};function Se(t){return JSON.stringify({provider:t.provider,model:t.model,dimensions:t.dimensions,pooling:t.pooling??null,normalized:t.normalized,preprocessingVersion:t.preprocessingVersion??null,implementation:t.implementation??null,runtimeFingerprint:t.runtimeFingerprint})}function oe(t){let e=Buffer.alloc(t.length*2);for(let n=0;n<t.length;n++){let r=Math.max(-32768,Math.min(32767,Math.round(t[n]*32767)));e.writeInt16LE(r,n*2)}return re("sha256").update(e).digest("hex").slice(0,16)}function B(t){if(!t.runtimeFingerprint)throw new Error("Embedding space identity requires executable runtime evidence");let e=re("sha256").update("aqe:embedding-space:v1\0").update(Se(t)).digest("hex");return{...t,spaceId:e}}function Be(t,e){let n=[...new Set(t.flatMap(o=>o.spaceId?[o.spaceId]:[]))].sort(),r=t.filter(o=>!o.spaceId).length,a=e?t.filter(o=>o.spaceId===e).length:0,i=e?t.filter(o=>o.spaceId!==null&&o.spaceId!==e).length:t.length-r;return{status:r>0||!e?"unverified":i>0||n.length>1?"vector_space_mismatch":"healthy",activeSpaceId:e,storedSpaceIds:n,verifiedVectors:a,mismatchedVectors:i,unverifiedVectors:r}}function Ce(t){return`${t}.space.json`}function Ve(t,e,n){if(!e)throw new I("VECTOR_SPACE_UNVERIFIED",`cannot open ANN index ${t} without runtime provenance`);let r=Ce(t);if(ve(r)){let s;try{s=JSON.parse(Ae(r,"utf8"))}catch{throw new I("VECTOR_SPACE_UNVERIFIED",`ANN index manifest ${r} is unreadable`)}if(s.version!==1||!s.spaceId)throw new I("VECTOR_SPACE_UNVERIFIED",`ANN index manifest ${r} has no verified space`);if(s.spaceId!==e)throw new I("VECTOR_SPACE_MISMATCH",`ANN index space ${s.spaceId} != active space ${e}`);return}if(n>0)throw new I("VECTOR_SPACE_UNVERIFIED",`populated ANN index ${t} has no embedding-space manifest; rebuild required`);let a={version:1,spaceId:e},i=`${r}.${process.pid}.tmp`;xe(i,`${JSON.stringify(a)}
13
+ `,{encoding:"utf8",mode:384}),Te(i,r)}var V=null,f=null,N=null,O=!1,P="",v=null,p=null,A=null,H={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4,endpoint:process.env.AQE_EMBEDDER_ENDPOINT,endpointToken:process.env.AQE_EMBEDDER_TOKEN},c=new Map,se=36e5;function L(t){return p?`endpoint:${p.fingerprint}:${t}`:`inproc:${t}`}function ae(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 W(t={}){if(O)throw new Error(`Transformer initialization previously failed: ${P}`);if(N)return N;let e={...H,...t};return N=(async()=>{try{if(e.endpoint){let l=J(e.endpoint);console.log(`[RealEmbeddings] Using external embedder endpoint: ${l}`),v=new R({endpoint:e.endpoint,token:e.endpointToken,model:e.modelName,expectedDim:D()}),p=await v.probe(),A=B({provider:"openai-compatible-endpoint",model:e.modelName,dimensions:p.dim,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:p.endpoint,runtimeFingerprint:p.fingerprint}),console.log(`[RealEmbeddings] Endpoint identity: dim=${p.dim} fingerprint=${p.fingerprint}`);try{let m=ee(p.endpoint);m&&m.fingerprint!==p.fingerprint&&console.warn(`[RealEmbeddings] WARNING: endpoint identity changed since last run. Previous fingerprint=${m.fingerprint} dim=${m.dim}, current fingerprint=${p.fingerprint} dim=${p.dim}. Vectors written before this change may no longer be comparable.`),te(p)}catch(m){console.warn(`[RealEmbeddings] Could not persist endpoint identity: ${F(m)}`)}f=Ne(v);return}let n;try{n=await import("./transformers-ZEKS2OJZ.js")}catch{throw new Error('In-process embeddings require the optional package "@huggingface/transformers", which is not installed. Configure an embedding endpoint (EmbeddingConfig.endpoint / AQE_EMBEDDER_ENDPOINT) so no local model is loaded. Installing @huggingface/transformers@4.2.0 is an explicit security opt-in: its compatible dependency chain currently has unresolved HIGH advisories GHSA-xcpc-8h2w-3j85 and GHSA-f88m-g3jw-g9cj.')}V=n.pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let r=performance.now();f=await V("feature-extraction",e.modelName,{quantized:e.quantized});let a=f;if(!a)throw new Error("Transformer pipeline returned no embedding model");let i=await a(ie,{pooling:"mean",normalize:!0}),s=Array.from(i.data);A=B({provider:"huggingface-transformers",model:e.modelName,dimensions:s.length,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:`transformers:${e.quantized?"quantized":"full"}`,runtimeFingerprint:oe(s)});let o=performance.now()-r;console.log(`[RealEmbeddings] Model loaded in ${o.toFixed(0)}ms`)}catch(n){throw O=!0,P=F(n),new Error(`Failed to initialize transformer model: ${P}`)}})(),N}function Ne(t){return async e=>{let n=Array.isArray(e)?e:[e],r=await t.embed(n),a=r[0]?.length??D(),i=new Float32Array(n.length*a);for(let s=0;s<r.length;s++)i.set(r[s],s*a);return{data:i,dims:[n.length,a]}}}async function Xe(t,e={}){let n={...H,...e};if(ae(t))return new Array(D()).fill(0);if(f||await W(e),!f)throw new Error("Embedding model failed to initialize");let r=L(t);if(n.enableCache){let l=c.get(r);if(l&&Date.now()-l.timestamp<se)return l.embedding}let a=performance.now(),i=await f(t,{pooling:"mean",normalize:!0}),s=Array.from(i.data),o=performance.now()-a;if(o>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${o.toFixed(1)}ms for "${t.slice(0,50)}..."`),n.enableCache){if(c.size>=n.maxCacheSize){let l=c.keys().next().value;l&&c.delete(l)}c.set(r,{embedding:s,timestamp:Date.now()})}return s}async function Je(t,e={}){let n={...H,...e},r=[],a=[],i=new Array(t.length).fill(null),s=[];for(let o=0;o<t.length;o++)ae(t[o])?i[o]=new Array(D()).fill(0):s.push(o);if(s.length===0)return i;if(f||await W(e),!f)throw new Error("Embedding model failed to initialize");if(n.enableCache)for(let o of s){let l=c.get(L(t[o]));l&&Date.now()-l.timestamp<se?i[o]=l.embedding:(r.push(t[o]),a.push(o))}else for(let o of s)r.push(t[o]),a.push(o);if(r.length>0){let o=performance.now(),l=32;for(let b=0;b<r.length;b+=l){let $=Math.min(b+l,r.length),y=r.slice(b,$),M=await f(y,{pooling:"mean",normalize:!0}),h=M.dims||[y.length,384],w=h[0],d=h[1];for(let g=0;g<w;g++){let u=g*d,E=Array.from(M.data.slice(u,u+d)),S=b+g,de=a[S];if(i[de]=E,n.enableCache){if(c.size>=n.maxCacheSize){let j=c.keys().next().value;j&&c.delete(j)}c.set(L(r[S]),{embedding:E,timestamp:Date.now()})}}}let m=performance.now()-o;console.log(`[RealEmbeddings] Batch computed ${r.length} embeddings in ${m.toFixed(0)}ms`)}return i.filter(o=>o!==null)}function Ke(){c.clear(),console.log("[RealEmbeddings] Cache cleared")}function Qe(){return{size:c.size,hitRate:0}}function Ye(){return!O&&f!==null}function D(){return 384}function Ze(){V=null,f=null,N=null,O=!1,P="",c.clear(),v&&v.close(),v=null,p=null,A=null,ne()}function et(){return v!==null}function tt(){return p}function nt(){return A}async function rt(){if(A)return A;let t=process.env.AQE_EMBEDDER_ENDPOINT;return t?(await W({endpoint:t,endpointToken:process.env.AQE_EMBEDDER_TOKEN}),A):null}export{ie as a,Be as b,Ve as c,H as d,Xe as e,Je as f,Ke as g,Qe as h,Ye as i,D as j,Ze as k,et as l,tt as m,nt as n,rt as o};
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.4");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
2
  var p={"||":1,"&&":2,"===":3,"!==":3,"==":3,"!=":3,"<":4,">":4,"<=":4,">=":4,"+":5,"-":5,"*":6,"/":6,"%":6},l=new Set(Object.keys(p)),w=new Set(["!","-","+"]);function h(r){let n=[],e=0;for(;e<r.length;){let t=r[e];if(/\s/.test(t)){e++;continue}if(/\d/.test(t)||t==="."&&/\d/.test(r[e+1])){let s="";for(;e<r.length&&/[\d.]/.test(r[e]);)s+=r[e++];n.push({type:"NUMBER",value:parseFloat(s),raw:s});continue}if(t==='"'||t==="'"){let s=t,u="";for(e++;e<r.length&&r[e]!==s;){if(r[e]==="\\"&&e+1<r.length){e++;let c=r[e];switch(c){case"n":u+=`
3
3
  `;break;case"t":u+=" ";break;case"r":u+="\r";break;default:u+=c}}else u+=r[e];e++}e++,n.push({type:"STRING",value:u,raw:`${s}${u}${s}`});continue}if(/[a-zA-Z_$]/.test(t)){let s="";for(;e<r.length&&/[a-zA-Z0-9_$]/.test(r[e]);)s+=r[e++];s==="true"?n.push({type:"BOOLEAN",value:!0,raw:s}):s==="false"?n.push({type:"BOOLEAN",value:!1,raw:s}):s==="null"?n.push({type:"NULL",value:null,raw:s}):s==="undefined"?n.push({type:"UNDEFINED",value:void 0,raw:s}):n.push({type:"IDENTIFIER",value:s,raw:s});continue}let a=r.slice(e,e+2),o=r.slice(e,e+3);if(o==="==="||o==="!=="){n.push({type:"OPERATOR",value:o,raw:o}),e+=3;continue}if(a==="=="||a==="!="||a==="<="||a===">="||a==="&&"||a==="||"){n.push({type:"OPERATOR",value:a,raw:a}),e+=2;continue}if(t==="("){n.push({type:"LPAREN",value:"(",raw:"("}),e++;continue}if(t===")"){n.push({type:"RPAREN",value:")",raw:")"}),e++;continue}if(t==="."){n.push({type:"DOT",value:".",raw:"."}),e++;continue}if("+-*/%<>!".includes(t)){n.push({type:"OPERATOR",value:t,raw:t}),e++;continue}throw new Error(`Unexpected character at position ${e}: ${t}`)}return n.push({type:"EOF",value:"",raw:""}),n}var i=class{tokens;pos=0;context;constructor(n,e){this.tokens=n,this.context=e}current(){return this.tokens[this.pos]}advance(){return this.tokens[this.pos++]}expect(n){let e=this.current();if(e.type!==n)throw new Error(`Expected ${n}, got ${e.type}`);return this.advance()}parse(){let n=this.parseExpression(0);if(this.current().type!=="EOF")throw new Error(`Unexpected token: ${this.current().raw}`);return n}parseExpression(n){let e=this.parseUnary();for(;;){let t=this.current();if(t.type!=="OPERATOR"||!l.has(t.value))break;let a=p[t.value];if(a<n)break;let o=this.advance().value,s=this.parseExpression(a+1);e=this.applyBinaryOperator(o,e,s)}return e}parseUnary(){let n=this.current();if(n.type==="OPERATOR"&&w.has(n.value)){let e=this.advance().value,t=this.parseUnary();return this.applyUnaryOperator(e,t)}return this.parsePrimary()}parsePrimary(){let n=this.current();switch(n.type){case"NUMBER":case"STRING":case"BOOLEAN":case"NULL":case"UNDEFINED":return this.advance(),n.value;case"IDENTIFIER":return this.parseIdentifier();case"LPAREN":{this.advance();let e=this.parseExpression(0);return this.expect("RPAREN"),e}default:throw new Error(`Unexpected token: ${n.raw}`)}}parseIdentifier(){let n=this.context,e=this.advance().value;for(typeof n=="object"&&n!==null&&(e in n)?n=n[e]:n=void 0;this.current().type==="DOT";){this.advance();let t=this.expect("IDENTIFIER").value;n!=null&&typeof n=="object"?n=n[t]:n=void 0}return n}applyBinaryOperator(n,e,t){switch(n){case"===":return e===t;case"!==":return e!==t;case"==":return e==t;case"!=":return e!=t;case"<":return e<t;case">":return e>t;case"<=":return e<=t;case">=":return e>=t;case"&&":return e&&t;case"||":return e||t;case"+":return e+t;case"-":return e-t;case"*":return e*t;case"/":return e/t;case"%":return e%t;default:throw new Error(`Unknown operator: ${n}`)}}applyUnaryOperator(n,e){switch(n){case"!":return!e;case"-":return-e;case"+":return+e;default:throw new Error(`Unknown unary operator: ${n}`)}}};function E(r,n={}){if(!r||typeof r!="string")throw new Error("Expression must be a non-empty string");let e=[/\beval\b/i,/\bFunction\b/,/\bconstructor\b/,/\b__proto__\b/,/\bprototype\b/,/\bimport\b/,/\brequire\b/,/\bprocess\b/,/\bglobal\b/,/\bwindow\b/,/\bdocument\b/,/\[\s*['"`]/,/\[.*\]/];for(let o of e)if(o.test(r))throw new Error(`Expression contains potentially dangerous pattern: ${r}`);let t=h(r.trim());return new i(t,n).parse()}function b(r,n={},e=!1){try{return!!E(r,n)}catch(t){return console.warn(`[SafeEvaluator] Failed to evaluate expression: ${r}`,t),e}}export{b as a};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.4");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
2
  import{readFileSync as O,existsSync as x,readdirSync as A}from"fs";import{join as y,basename as v}from"path";function m(r){let e=[];if(!r||typeof r!="object")return e.push("Overlay must be a non-null object"),e;let t=r;if((!t.agent||typeof t.agent!="string")&&e.push('Overlay must have a string "agent" field'),t.replace!==void 0)if(typeof t.replace!="object"||t.replace===null)e.push('"replace" must be an object');else{let n=t.replace;n.description!==void 0&&typeof n.description!="string"&&e.push('"replace.description" must be a string'),n.domains!==void 0&&!Array.isArray(n.domains)&&e.push('"replace.domains" must be an array'),n.complexity!==void 0&&typeof n.complexity!="string"&&e.push('"replace.complexity" must be a string')}if(t.append!==void 0)if(typeof t.append!="object"||t.append===null)e.push('"append" must be an object');else{let n=t.append;n.instructions!==void 0&&typeof n.instructions!="string"&&e.push('"append.instructions" must be a string'),n.capabilities!==void 0&&!Array.isArray(n.capabilities)&&e.push('"append.capabilities" must be an array'),n.tags!==void 0&&!Array.isArray(n.tags)&&e.push('"append.tags" must be an array')}if(t.config!==void 0)if(typeof t.config!="object"||t.config===null)e.push('"config" must be an object');else{let n=t.config;n.minimumFindings!==void 0&&typeof n.minimumFindings!="number"&&e.push('"config.minimumFindings" must be a number'),n.maxParallelAgents!==void 0&&typeof n.maxParallelAgents!="number"&&e.push('"config.maxParallelAgents" must be a number'),n.preferredFrameworks!==void 0&&!Array.isArray(n.preferredFrameworks)&&e.push('"config.preferredFrameworks" must be an array'),n.needsContext!==void 0&&typeof n.needsContext!="boolean"&&e.push('"config.needsContext" must be a boolean')}return e}var w=".claude/agent-overrides";function $(r){let e={},t=r.split(`
3
3
  `),n=null,i=null,s=null,a=null;for(let o of t){let l=o.replace(/\r$/,"");if(l.trim().startsWith("#")||l.trim()==="")continue;let u=l.length-l.trimStart().length,g=l.trim();if(g.startsWith("- ")){let c=g.slice(2).trim().replace(/^["']|["']$/g,"");s&&s.push(c);continue}if(s&&a){if(i&&n){let c=e[n]||{};c[a]=s,e[n]=c}else if(n){let c=e[n]||{};c[a]=s,e[n]=c}s=null,a=null}let f=g.match(/^(\w[\w.-]*)\s*:\s*(.*)$/);if(!f)continue;let[,p,b]=f,d=b.trim().replace(/^["']|["']$/g,"");if(u===0)d===""||d===void 0?(n=p,i=null,e[p]||(e[p]={})):(e[p]=h(d),n=null,i=null);else if(u<=4&&n)if(d===""||d===void 0)i=p,s=[],a=p;else{let c=e[n]||{};c[p]=h(d),e[n]=c}}if(s&&a&&n){let o=e[n]||{};o[a]=s,e[n]=o}return e}function h(r){if(r==="true")return!0;if(r==="false")return!1;if(r==="null")return null;let e=Number(r);return!isNaN(e)&&r!==""?e:r}function N(r){let e=y(r,w),t={overlays:[],warnings:[],errors:[]};if(!x(e))return t;let n;try{n=A(e).filter(i=>(i.endsWith(".yaml")||i.endsWith(".yml"))&&!i.startsWith("_"))}catch(i){return t.errors.push(`Failed to read overrides directory: ${i.message}`),t}for(let i of n){let s=y(e,i);try{let a=O(s,"utf-8"),o=$(a);if(!o.agent){let u=v(i).replace(/\.(override|customize)\.(yaml|yml)$/,"");o.agent=u}let l=m(o);if(l.length>0){t.warnings.push(`Overlay ${i} has validation issues: ${l.join("; ")}. Loading without overlay.`);continue}t.overlays.push(o)}catch(a){t.warnings.push(`Failed to parse overlay ${i}: ${a.message}. Agent loads without overlay.`)}}return t}function E(r,e){let t=r,n={agentName:e.agent,overlayFile:`${e.agent}.override.yaml`,replacedFields:[],appendedFields:[],configOverrides:[]};if(e.replace){if(e.replace.description){let i=/^(description:\s*).+$/m;i.test(t)&&(t=t.replace(i,`$1${e.replace.description}`),n.replacedFields.push("description"))}if(e.replace.domains){let i=/^(domain:\s*).+$/m;i.test(t)&&(t=t.replace(i,`$1${e.replace.domains.join(", ")}`),n.replacedFields.push("domains"))}if(e.replace.complexity){let i=/^(complexity:\s*).+$/m;i.test(t)&&(t=t.replace(i,`$1${e.replace.complexity}`),n.replacedFields.push("complexity"))}}if(e.append){if(e.append.instructions&&(t+=`
4
4
 
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.4");process.exit(0)}
2
- import{d as ve}from"./chunk-R5NE6B2M.js";import{a as xe,b as Me}from"./chunk-ZZDIMOOV.js";import{m as be,n as Se}from"./chunk-3TW5W5LX.js";import{a as Re}from"./chunk-NA7B2QYB.js";import{c as fe,d as ge,e as Ce}from"./chunk-Y3MW3YBC.js";import{b as D,d as ye}from"./chunk-DHJPWQBR.js";import{b as P,c as L}from"./chunk-STM3UDNO.js";import{a as G,b as A,c as J}from"./chunk-G6T45OIC.js";Re();import{createRequire as Te}from"module";var O;function W(){if(!O){let u=Te(import.meta.url);try{O=u("typescript")}catch{try{O=u("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 m=new Proxy({},{get(u,e){return W()[e]},has(u,e){return e in W()},ownKeys(){return Object.keys(W())},getOwnPropertyDescriptor(u,e){let t=W()[e];if(t!==void 0)return{configurable:!0,enumerable:!0,value:t}}});var N=class{parseFile(e,t){return m.createSourceFile(e,t,m.ScriptTarget.Latest,!0,this.getScriptKind(e))}extractFunctions(e){let t=[],s=n=>{m.isFunctionDeclaration(n)&&n.name?t.push(this.extractFunctionDeclaration(n,e)):m.isVariableStatement(n)&&this.extractArrowFunctions(n,e,t),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractClasses(e){let t=[],s=n=>{m.isClassDeclaration(n)&&n.name&&t.push(this.extractClassDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractImports(e){let t=[],s=n=>{m.isImportDeclaration(n)&&t.push(this.extractImportDeclaration(n)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractExports(e){let t=[],s=n=>{if(m.isExportDeclaration(n))this.extractExportDeclaration(n,t);else if(m.isExportAssignment(n))t.push({name:this.getExportAssignmentName(n),type:"unknown",isDefault:!0,isReexport:!1,sourceModule:void 0});else if(m.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(m.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(m.isVariableStatement(n)&&this.hasExportModifier(n))for(let i of n.declarationList.declarations)m.isIdentifier(i.name)&&t.push({name:i.name.text,type:"variable",isDefault:!1,isReexport:!1,sourceModule:void 0});else m.isInterfaceDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"interface",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isTypeAliasDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"type",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isEnumDeclaration(n)&&this.hasExportModifier(n)&&t.push({name:n.name.text,type:"enum",isDefault:!1,isReexport:!1,sourceModule:void 0});m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractInterfaces(e){let t=[],s=n=>{m.isInterfaceDeclaration(n)&&t.push(this.extractInterfaceDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractEntities(e,t){let s=this.parseFile(t,e),n=[],i=this.extractFunctions(s);for(let a of i)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 r=this.extractInterfaces(s);for(let a of r)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")?m.ScriptKind.TSX:e.endsWith(".ts")?m.ScriptKind.TS:e.endsWith(".jsx")?m.ScriptKind.JSX:e.endsWith(".js")?m.ScriptKind.JS:m.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(m.isIdentifier(n.name)&&n.initializer&&m.isArrowFunction(n.initializer)){let i=n.initializer,{line:o}=t.getLineAndCharacterOfPosition(e.getStart()),{line:r}=t.getLineAndCharacterOfPosition(e.getEnd());s.push({name:n.name.text,parameters:this.extractParameters(i.parameters),returnType:i.type?i.type.getText(t):void 0,startLine:o+1,endLine:r+1,isAsync:this.hasAsyncModifier(i),isExported:this.hasExportModifier(e),isGenerator:!1,typeParameters:this.extractTypeParameters(i.typeParameters)})}}extractClassDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),i=[],o=[];for(let c of e.members)m.isMethodDeclaration(c)&&c.name?i.push(this.extractMethodDeclaration(c,t)):m.isPropertyDeclaration(c)&&c.name?o.push(this.extractPropertyDeclaration(c,t)):m.isConstructorDeclaration(c)&&(i.push(this.extractConstructor(c,t)),this.extractParameterProperties(c,o,t));let r,a=[];if(e.heritageClauses){for(let c of e.heritageClauses)if(c.token===m.SyntaxKind.ExtendsKeyword)r=c.types[0]?.expression.getText(t);else if(c.token===m.SyntaxKind.ImplementsKeyword)for(let l of c.types)a.push(l.expression.getText(t))}return{name:e.name?.text??"anonymous",methods:i,properties:o,extends:r,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:m.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===m.SyntaxKind.PublicKeyword||t.kind===m.SyntaxKind.PrivateKeyword||t.kind===m.SyntaxKind.ProtectedKeyword||t.kind===m.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,i,o=e.importClause?.isTypeOnly??!1;if(e.importClause&&(e.importClause.name&&(n=e.importClause.name.text),e.importClause.namedBindings)){if(m.isNamespaceImport(e.importClause.namedBindings))i=e.importClause.namedBindings.name.text;else if(m.isNamedImports(e.importClause.namedBindings))for(let r of e.importClause.namedBindings.elements)s.push({name:r.propertyName?.text??r.name.text,alias:r.propertyName?r.name.text:void 0})}return{module:t,namedImports:s,defaultImport:n,namespaceImport:i,isTypeOnly:o}}extractExportDeclaration(e,t){let s=e.moduleSpecifier?e.moduleSpecifier.text:void 0;if(e.exportClause&&m.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()),i=[],o=[];for(let a of e.members)m.isPropertySignature(a)&&a.name?i.push({name:this.getPropertyName(a.name,t),type:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken,isReadonly:this.hasReadonlyModifier(a)}):m.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 r=[];if(e.heritageClauses){for(let a of e.heritageClauses)if(a.token===m.SyntaxKind.ExtendsKeyword)for(let c of a.types)r.push(c.expression.getText(t))}return{name:e.name.text,properties:i,methods:o,extends:r,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:m.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 m.isIdentifier(e)||m.isStringLiteral(e)||m.isNumericLiteral(e)?e.text:e.getText(t)}getExportAssignmentName(e){return m.isIdentifier(e.expression)?e.expression.text:"default"}hasExportModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ExportKeyword)}hasDefaultModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.DefaultKeyword)}hasAsyncModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AsyncKeyword)}hasStaticModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.StaticKeyword)}hasAbstractModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AbstractKeyword)}hasReadonlyModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ReadonlyKeyword)}getVisibility(e){if(!m.canHaveModifiers(e))return"public";let t=m.getModifiers(e);return t?t.some(s=>s.kind===m.SyntaxKind.PrivateKeyword)?"private":t.some(s=>s.kind===m.SyntaxKind.ProtectedKeyword)?"protected":"public":"public"}},qe=new N,Q=class{language="typescript";supportedExtensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];parser=new N;async parseFile(e,t){let s=this.parser.parseFile(t,e),n=this.parser.extractFunctions(s),i=this.parser.extractClasses(s),o=this.parser.extractImports(s);return{functions:n.map(r=>this.mapFunction(r)),classes:i.map(r=>this.mapClass(r)),imports:o.map(r=>this.mapImport(r)),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}}},He=new Q;Ce();var E=1e3;function I(u){let e=u.split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
+ import{d as ve}from"./chunk-M5AEL7IS.js";import{a as xe,b as Me}from"./chunk-WX6RRIGW.js";import{m as be,n as Se}from"./chunk-R6IU3EWP.js";import{b as D,d as ye}from"./chunk-IJHCIXJC.js";import{c as P,d as L}from"./chunk-XEZIIQYJ.js";import{a as Re}from"./chunk-J27F4NSB.js";import{c as fe,d as ge,e as Ce}from"./chunk-7CD7PBHY.js";import{a as G,b as A,c as J}from"./chunk-J5UNP6W3.js";Re();import{createRequire as Te}from"module";var O;function W(){if(!O){let u=Te(import.meta.url);try{O=u("typescript")}catch{try{O=u("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 m=new Proxy({},{get(u,e){return W()[e]},has(u,e){return e in W()},ownKeys(){return Object.keys(W())},getOwnPropertyDescriptor(u,e){let t=W()[e];if(t!==void 0)return{configurable:!0,enumerable:!0,value:t}}});var N=class{parseFile(e,t){return m.createSourceFile(e,t,m.ScriptTarget.Latest,!0,this.getScriptKind(e))}extractFunctions(e){let t=[],s=n=>{m.isFunctionDeclaration(n)&&n.name?t.push(this.extractFunctionDeclaration(n,e)):m.isVariableStatement(n)&&this.extractArrowFunctions(n,e,t),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractClasses(e){let t=[],s=n=>{m.isClassDeclaration(n)&&n.name&&t.push(this.extractClassDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractImports(e){let t=[],s=n=>{m.isImportDeclaration(n)&&t.push(this.extractImportDeclaration(n)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractExports(e){let t=[],s=n=>{if(m.isExportDeclaration(n))this.extractExportDeclaration(n,t);else if(m.isExportAssignment(n))t.push({name:this.getExportAssignmentName(n),type:"unknown",isDefault:!0,isReexport:!1,sourceModule:void 0});else if(m.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(m.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(m.isVariableStatement(n)&&this.hasExportModifier(n))for(let i of n.declarationList.declarations)m.isIdentifier(i.name)&&t.push({name:i.name.text,type:"variable",isDefault:!1,isReexport:!1,sourceModule:void 0});else m.isInterfaceDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"interface",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isTypeAliasDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"type",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isEnumDeclaration(n)&&this.hasExportModifier(n)&&t.push({name:n.name.text,type:"enum",isDefault:!1,isReexport:!1,sourceModule:void 0});m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractInterfaces(e){let t=[],s=n=>{m.isInterfaceDeclaration(n)&&t.push(this.extractInterfaceDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractEntities(e,t){let s=this.parseFile(t,e),n=[],i=this.extractFunctions(s);for(let a of i)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 r=this.extractInterfaces(s);for(let a of r)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")?m.ScriptKind.TSX:e.endsWith(".ts")?m.ScriptKind.TS:e.endsWith(".jsx")?m.ScriptKind.JSX:e.endsWith(".js")?m.ScriptKind.JS:m.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(m.isIdentifier(n.name)&&n.initializer&&m.isArrowFunction(n.initializer)){let i=n.initializer,{line:o}=t.getLineAndCharacterOfPosition(e.getStart()),{line:r}=t.getLineAndCharacterOfPosition(e.getEnd());s.push({name:n.name.text,parameters:this.extractParameters(i.parameters),returnType:i.type?i.type.getText(t):void 0,startLine:o+1,endLine:r+1,isAsync:this.hasAsyncModifier(i),isExported:this.hasExportModifier(e),isGenerator:!1,typeParameters:this.extractTypeParameters(i.typeParameters)})}}extractClassDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),i=[],o=[];for(let c of e.members)m.isMethodDeclaration(c)&&c.name?i.push(this.extractMethodDeclaration(c,t)):m.isPropertyDeclaration(c)&&c.name?o.push(this.extractPropertyDeclaration(c,t)):m.isConstructorDeclaration(c)&&(i.push(this.extractConstructor(c,t)),this.extractParameterProperties(c,o,t));let r,a=[];if(e.heritageClauses){for(let c of e.heritageClauses)if(c.token===m.SyntaxKind.ExtendsKeyword)r=c.types[0]?.expression.getText(t);else if(c.token===m.SyntaxKind.ImplementsKeyword)for(let l of c.types)a.push(l.expression.getText(t))}return{name:e.name?.text??"anonymous",methods:i,properties:o,extends:r,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:m.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===m.SyntaxKind.PublicKeyword||t.kind===m.SyntaxKind.PrivateKeyword||t.kind===m.SyntaxKind.ProtectedKeyword||t.kind===m.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,i,o=e.importClause?.isTypeOnly??!1;if(e.importClause&&(e.importClause.name&&(n=e.importClause.name.text),e.importClause.namedBindings)){if(m.isNamespaceImport(e.importClause.namedBindings))i=e.importClause.namedBindings.name.text;else if(m.isNamedImports(e.importClause.namedBindings))for(let r of e.importClause.namedBindings.elements)s.push({name:r.propertyName?.text??r.name.text,alias:r.propertyName?r.name.text:void 0})}return{module:t,namedImports:s,defaultImport:n,namespaceImport:i,isTypeOnly:o}}extractExportDeclaration(e,t){let s=e.moduleSpecifier?e.moduleSpecifier.text:void 0;if(e.exportClause&&m.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()),i=[],o=[];for(let a of e.members)m.isPropertySignature(a)&&a.name?i.push({name:this.getPropertyName(a.name,t),type:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken,isReadonly:this.hasReadonlyModifier(a)}):m.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 r=[];if(e.heritageClauses){for(let a of e.heritageClauses)if(a.token===m.SyntaxKind.ExtendsKeyword)for(let c of a.types)r.push(c.expression.getText(t))}return{name:e.name.text,properties:i,methods:o,extends:r,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:m.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 m.isIdentifier(e)||m.isStringLiteral(e)||m.isNumericLiteral(e)?e.text:e.getText(t)}getExportAssignmentName(e){return m.isIdentifier(e.expression)?e.expression.text:"default"}hasExportModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ExportKeyword)}hasDefaultModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.DefaultKeyword)}hasAsyncModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AsyncKeyword)}hasStaticModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.StaticKeyword)}hasAbstractModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AbstractKeyword)}hasReadonlyModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ReadonlyKeyword)}getVisibility(e){if(!m.canHaveModifiers(e))return"public";let t=m.getModifiers(e);return t?t.some(s=>s.kind===m.SyntaxKind.PrivateKeyword)?"private":t.some(s=>s.kind===m.SyntaxKind.ProtectedKeyword)?"protected":"public":"public"}},qe=new N,Q=class{language="typescript";supportedExtensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];parser=new N;async parseFile(e,t){let s=this.parser.parseFile(t,e),n=this.parser.extractFunctions(s),i=this.parser.extractClasses(s),o=this.parser.extractImports(s);return{functions:n.map(r=>this.mapFunction(r)),classes:i.map(r=>this.mapClass(r)),imports:o.map(r=>this.mapImport(r)),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}}},He=new Q;Ce();var E=1e3;function I(u){let e=u.split(`
3
3
  `),t=[],s=[],n="",i=0,o=0,r=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||(i=c+1),n=n?n+" "+d:l;for(let p of d)p==="("?o++:p===")"?o=Math.max(0,o-1):p==="<"?r++:p===">"?r=Math.max(0,r-1):p==="["?a++:p==="]"&&(a=Math.max(0,a-1));o===0&&r===0&&a===0&&(t.push(n),s.push(i),n="")}return n&&(t.push(n),s.push(i)),{logicalLines:t,lineMap:s}}function B(u,e,t="<",s=">"){if(u[e]!==t)return;let n=1,i=e+1;for(;i<u.length&&n>0;)u[i]===t?n++:u[i]===s&&n--,i++;if(n===0)return u.substring(e+1,i-1)}function C(u,e,t){let s=[];for(let n=e-1;n>=0;n--){let i=u[n].trim();if(i.startsWith(t))s.unshift(i);else{if(i===""||i.startsWith("//")||i.startsWith("*")||i.startsWith("#"))continue;break}}return s}function M(u){let e=[],t=0,s="";for(let n of u)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 ce(u){let e=0,t=!1,s="";for(let n=0;n<u.length;n++){let i=u[n];if(t){i===s&&u[n-1]!=="\\"&&(t=!1);continue}i==='"'||i==="'"||i==="`"?(t=!0,s=i):i==="{"?e++:i==="}"&&e--}return e}var Y=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
4
  `),{logicalLines:n,lineMap:i}=I(e),o=/^(\s*)(async\s+)?def\s+(\w+)\s*\(([^)]*)\)(?:\s*->\s*([^:]*\S))?\s*:/;for(let r=0;r<n.length;r++){if(n[r].length>E)continue;let a=n[r].match(o);if(a){let c=a[1].length,l=!!a[2],d=a[3],p=a[4],h=a[5]?.trim(),f=i[r]-1,g=f+1;for(let y=f+1;y<s.length;y++){let x=s[y];if(x.trim()===""||x.trim().startsWith("#"))continue;if((x.match(/^(\s*)/)?.[1].length??0)<=c&&x.trim()!==""){g=y;break}g=y+1}let b=C(s,f,"@");t.push({name:d,parameters:this.parseParams(p),returnType:h,isAsync:l,isPublic:!d.startsWith("_"),complexity:1,decorators:b,genericParams:[],startLine:i[r],endLine:g})}}return t}extractClasses(e){let t=[],s=e.split(`
5
5
  `),{logicalLines:n,lineMap:i}=I(e),o=/^(\s*)class\s+(\w+)(?:\(([^)]*)\))?\s*:/;for(let r=0;r<n.length;r++){let a=n[r].match(o);if(a){let c=a[1].length,l=a[2],d=a[3]?a[3].split(",").map(y=>y.trim()):[],p=i[r]-1,h=p+1;for(let y=p+1;y<s.length;y++){let x=s[y];if(x.trim()===""||x.trim().startsWith("#"))continue;if((x.match(/^(\s*)/)?.[1].length??0)<=c&&x.trim()!==""){h=y;break}h=y+1}let f=s.slice(p+1,h).join(`
@@ -20,7 +20,7 @@ import{d as ve}from"./chunk-R5NE6B2M.js";import{a as xe,b as Me}from"./chunk-ZZD
20
20
  `),{logicalLines:n,lineMap:i}=I(e),o=/^\s*(public|private|protected|internal)?\s*(suspend)?\s*fun\s+(?:<[^{]*> +)?(\w+)\s*\(([^)]*)\)(?:\s*:\s*([^{=\s]+(?:\s+[^{=\s]+)*))?\s*/,r=0;for(let a=0;a<n.length;a++){let c=n[a];if(c.length>E){r+=(c.match(/\{/g)?.length??0)-(c.match(/\}/g)?.length??0);continue}let l=c.match(o);if(l&&r<=1){let d=l[1]||"public",p=!!l[2],h=l[3],f=l[4],g=l[5]?.trim();if(g&&g.includes("<")){let x=g.indexOf("<"),w=B(g,x);w!==void 0&&(g=g.substring(0,x)+"<"+w+">")}let b=i[a]-1,y=C(s,b,"@");t.push({name:h,parameters:this.parseParams(f),returnType:g,isAsync:p,isPublic:d==="public",complexity:1,decorators:y,genericParams:[],startLine:i[a],endLine:i[a]})}r+=ce(c),r<0&&(r=0)}return t}extractClasses(e){let t=[],s=e.split(`
21
21
  `),{logicalLines:n,lineMap:i}=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 r=0;r<n.length;r++){if(n[r].length>E)continue;let a=n[r].match(o);if(a){let c=a[3],l=a[4]?a[4].split(",").map(h=>h.trim().split("(")[0].trim()):[],d=i[r]-1,p=C(s,d,"@");t.push({name:c,methods:[],properties:[],isPublic:(a[1]||"public")==="public",implements:l.slice(1),extends:l[0]||void 0,decorators:p,startLine:i[r],endLine:i[r]})}}return t}extractImports(e){let t=[],s=e.split(`
22
22
  `);for(let n of s){let i=n.match(/^\s*import\s+([^\s]+)/);i&&t.push({module:i[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){return e.trim()?M(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(),i=t.substring(s+1).trim(),o=i.indexOf("="),r=o>=0?i.substring(0,o).trim():i,a=o>=0;return{name:n,type:r,isOptional:a||r?.endsWith("?")||!1,defaultValue:void 0}}):[]}},re=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),i=/^\s*([\w<>,.?]+(?:\s+[\w<>,.?]+)*)\s+(\w+)\s*\(([^)]*)\)(?:\s*(async))?\s*\{/;for(let o=0;o<s.length;o++){let r=s[o];if(r.includes(" class ")||r.length>E)continue;let a=r.match(i);if(a){let c=a[1].trim(),l=c;if(c&&c.includes("<")){let f=c.indexOf("<"),g=B(c,f);g!==void 0&&(l=c.substring(0,f)+"<"+g+">")}let d=a[2],p=a[3],h=!!a[4]||l.includes("Future");t.push({name:d,parameters:this.parseParams(p),returnType:l==="void"?void 0:l,isAsync:h,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),i=/^\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 r=s[o].match(i);if(r){let a=r[2],c=r[3],l=r[4]?r[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 i=n.match(/^\s*import\s+'([^']+)'/);i&&t.push({module:i[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){if(!e.trim())return[];let t=e.replace(/[{}[\]]/g,"");return M(t).map(s=>s.trim()).filter(s=>s).map(s=>{let n=s.replace("required ","").trim().split(/\s+/),i=n[n.length-1]||"",o=n.slice(0,-1).join(" ")||void 0;return{name:i,type:o,isOptional:s.includes("?")||s.includes("{"),defaultValue:void 0}})}},z=ge("ParserRegistry"),Ee=["python","java","csharp","rust","swift"],ae=class u{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<u.MAX_WASM_RETRIES)try{return await this.wasmParser.parseFile(e,t)}catch(s){this.wasmFailCount++;let n=s instanceof Error?s.message:String(s),i=this.wasmFailCount>=u.MAX_WASM_RETRIES;z.warn(`[${this.language}] tree-sitter WASM parser failed (attempt ${this.wasmFailCount}/${u.MAX_WASM_RETRIES}): ${n}. Falling back to regex parser (~97-98% accuracy). `+(i?"Set AQE_PARSER_REGEX_ONLY=1 to silence this warning.":"Will retry WASM on next parse."))}return this.regexParser.parseFile(e,t)}},oe=class{parsers=new Map;_wasmInitPromise=null;constructor(){this.register(new Y),this.register(new Z),this.register(new ee),this.register(new te),this.register(new se),this.register(new ne),this.register(new ie),this.register(new re),this._wasmInitPromise=this._tryLoadWasmParsers()}async _tryLoadWasmParsers(){try{let e=await import("./tree-sitter-wasm-parser-DEGOHS6F.js");if(!e.isWasmAvailable()){z.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 Ee){let n=t.get(s),i=this.parsers.get(s);n&&i&&this.parsers.set(s,new ae(n,i))}z.info("tree-sitter WASM parsers available for: "+Ee.join(", "))}catch{z.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)}},Qe=new oe;import*as S from"node:fs/promises";import*as R from"node:path";var Fe=[/\.\./,/%2e%2e/i,/%252e%252e/i,/\.\.%2f/i,/%2f\.\./i,/\.\.%5c/i,/\.\.\\/,/%c0%ae/i,/%c0%2f/i,/%c1%9c/i,/\0/,/%00/i],Ae=[/^\/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],le=class{name="path-traversal";getRiskLevel(){return"critical"}validate(e,t={}){let{basePath:s="",allowAbsolute:n=!1,allowedExtensions:i=[],deniedExtensions:o=[".exe",".bat",".cmd",".sh",".ps1",".dll",".so"],maxDepth:r=10,maxLength:a=4096}=t;if(e.length>a)return{valid:!1,error:`Path exceeds maximum length of ${a}`,riskLevel:"medium"};for(let f of Fe)if(f.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 f of Ae)if(f.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>r)return{valid:!1,error:`Path depth exceeds maximum of ${r}`,riskLevel:"low"};let d=this.getExtension(c);if(d){let f=`.${d.toLowerCase()}`,g=d.toLowerCase();if(o.length>0&&o.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not allowed`,riskLevel:"high"};if(i.length>0&&!i.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not in allowed list`,riskLevel:"medium"}}let p=s?this.joinPathsAbsolute(s,c):c,h=s.startsWith("/")?`/${this.normalizePath(s)}`:this.normalizePath(s);return s&&!p.startsWith(h)?{valid:!1,error:"Path escapes base directory",riskLevel:"critical"}:{valid:!0,normalizedPath:p,riskLevel:"none"}}normalizePath(e){let t=e.replace(/\\/g,"/");t=t.replace(/\/+/g,"/");let s=t.split("/"),n=[];for(let i of s)i==="."||i===""||(i===".."?n.length>0&&n[n.length-1]!==".."&&n.pop():n.push(i));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}},Ne=new le,Ie=(u,e)=>Ne.validate(u,e);ye();var F=class extends Error{constructor(t,s,n,i){super(t);this.filePath=s;this.code=n;this.cause=i;this.name="FileReadError"}filePath;code;cause},V=class extends Error{constructor(t,s,n){super(t);this.filePath=s;this.cause=n;this.name="JsonParseError"}filePath;cause},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"}requestedPath;issues;riskLevel},de=class{constructor(e,t){this.maxSize=e;this.ttlMs=t}maxSize;ttlMs;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,i)=>{e-n.timestamp>this.ttlMs&&s.push(i)}),s.forEach(n=>{this.delete(n),t++}),t}};function De(u){let e="",t=0;for(;t<u.length;){let s=u[t],n=u[t+1];s==="*"&&n==="*"?u[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 we(u,e,t,s){try{let n=await S.readdir(u,{withFileTypes:!0});for(let i of n){let o=R.join(u,i.name),r=R.relative(s,o);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&await we(o,e,t,s);else if(i.isFile()){let a=r.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 de(e.maxCacheSize??100,e.cacheTtlMs??300*1e3)}resolvePath(e){let t=R.isAbsolute(e),s=Ie(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=R.resolve(this.basePath),i=R.resolve(e);if(!i.startsWith(n))throw new T(e,["Path escapes base directory"],"critical");return i}return s.normalizedPath?s.normalizedPath:t?e:R.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(),P(s);this.stats.cacheMisses++}try{let s=await S.readFile(t,"utf-8");return this.enableCache&&(this.cache.set(t,s,Buffer.byteLength(s,"utf-8")),this.updateCacheStats()),P(s)}catch(s){let n=s,i;switch(n.code){case"ENOENT":i="File not found: "+t;break;case"EACCES":i="Permission denied: "+t;break;case"EISDIR":i="Path is a directory: "+t;break;default:i="Failed to read file: "+t}return L(new F(i,t,n.code,n))}}async readJSON(e){let t=await this.readFile(e);if(!t.success)return t;try{let s=D(t.value);return P(s)}catch(s){let n=s,i=e;try{i=this.resolvePath(e)}catch{}return L(new V("Invalid JSON in file: "+i+" - "+n.message,i,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 S.access(t,S.constants.F_OK),P(!0)}catch(s){let n=s;return n.code==="ENOENT"?P(!1):L(new F("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 S.stat(s)).isDirectory())return L(new F("Base path is not a directory: "+s,s,"ENOTDIR"));let i=De(e),o=[];return await we(s,i,o,s),o.sort(),P(o)}catch(n){let i=n;return L(new F("Failed to list files in: "+s,s,i.code,i))}}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}};J();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"};Me();var _=class{baseUrl;maxRetries;retryDelayMs;timeoutMs;constructor(e=xe(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 i=await this.fetchWithTimeout(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},this.timeoutMs);if(!i.ok){let r=await i.text();throw new Error(`Ollama API error (${i.status}): ${r}`)}let o=await i.json();if(o.embedding.length!==v.DIMENSIONS)throw new Error(`Invalid embedding dimensions: expected ${v.DIMENSIONS}, got ${o.embedding.length}`);return o.embedding}catch(i){if(s=A(i),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,i=setTimeout(()=>n.abort(),s);try{return await fetch(e,{...t,signal:n.signal})}finally{clearTimeout(i)}}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 Oe}from"crypto";var $=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 Oe("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 i={embedding:s,timestamp:Date.now(),model:t};this.cache.set(n,i)}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[i,o]of this.cache.entries())o.timestamp<s&&(this.cache.delete(i),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)}};J();var K=class{client;cache;batchSize;enableFallback;ollamaAvailable=null;constructor(e={}){this.client=new _(e.ollamaBaseUrl),this.cache=e.cache??new $(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,i=e.content.trim();if(s.length+i.length>n){let o=n-s.length-3;i=i.substring(0,o)+"..."}return s+i}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=[],i=0,o=0,r=await this.isOllamaAvailable();if(r)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,r);n.push(...d);for(let p of d)p.cached?i++:o++;if(t){let p=c+l.length,h=e.length,g=(Date.now()-s)/p,y=(h-p)*g;t({current:p,total:h,percentage:p/h*100,estimatedTimeRemainingMs:y})}}let a=Date.now()-s;return{results:n,stats:{totalChunks:e.length,cachedHits:i,computedNew:o,totalTimeMs:a,avgTimePerChunk:a/e.length}}}async processBatch(e,t){let s=[],n=e.map(async o=>{let r=this.formatForEmbedding(o),a=Date.now(),c=this.cache.get(r,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(r):l=this.generatePseudoEmbedding(r),this.cache.set(r,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}: ${G(l)}`)}}),i=await Promise.all(n);return s.push(...i),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 r=s[o];for(let a=0;a<r.length&&a<t.length;a++)t[(o+a)%t.length]+=r.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,r]of n)o.test(e)&&(t[r]+=.5);let i=Math.sqrt(t.reduce((o,r)=>o+r*r,0))||1;return t.map(o=>o/i)}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}}};J();ye();import{existsSync as Ke,statSync as Ue}from"fs";import{dirname as je,resolve as Ge,join as q}from"path";function ke(u){switch(u){case"ts":case"mts":case"cts":return"tree-sitter-typescript.wasm";case"tsx":return"tree-sitter-tsx.wasm";case"js":case"jsx":case"mjs":case"cjs":return"tree-sitter-javascript.wasm";default:return null}}var U=u=>u.startPosition.row+1,j=(u,e)=>u.childForFieldName(e)?.text??"";function ue(u){for(let e=0;e<u.childCount;e++){let t=u.child(e);if(t){if(t.type==="async")return!0;if(t.type==="function"||t.type==="function_declaration")break}}return!1}function _e(u){for(let e=0;e<u.childCount;e++)if(u.child(e)?.type==="accessibility_modifier"){let s=u.child(e).text;if(s==="private")return"private";if(s==="protected")return"protected"}return"public"}function $e(u){let e=j(u,"name")||"(anonymous)",t=u.childForFieldName("body"),s=[];if(t)for(let n=0;n<t.childCount;n++){let i=t.child(n);i&&i.type==="method_definition"&&s.push({name:j(i,"name"),startLine:U(i),isAsync:ue(i),visibility:_e(i)})}return{name:e,startLine:U(u),methods:s}}function pe(u){return u.replace(/^['"`]|['"`]$/g,"")}async function me(u,e){let t=ke(e);if(!t)return null;let s=await ve(t);if(!s)return null;let n=null;try{let i=s.parse(u);n=i;let o=i.rootNode;if(!o)return null;let r={functions:[],classes:[],interfaces:[],imports:[]},a=[o];for(;a.length;){let c=a.pop(),l=!0;switch(c.type){case"function_declaration":case"generator_function_declaration":r.functions.push({name:j(c,"name"),startLine:U(c),isAsync:ue(c),visibility:"public"}),l=!1;break;case"class_declaration":case"class":r.classes.push($e(c)),l=!1;break;case"interface_declaration":r.interfaces.push({name:j(c,"name"),startLine:U(c)}),l=!1;break;case"lexical_declaration":case"variable_declaration":{for(let d=0;d<c.childCount;d++){let p=c.child(d);if(!p||p.type!=="variable_declarator")continue;let h=p.childForFieldName("value");if(h&&(h.type==="arrow_function"||h.type==="function"||h.type==="function_expression"))r.functions.push({name:j(p,"name"),startLine:U(p),isAsync:ue(h),visibility:"public"});else if(h&&h.type==="call_expression"&&h.child(0)?.text==="require"){let f=h.childForFieldName("arguments")?.child(1);f&&f.type==="string"&&r.imports.push(pe(f.text))}}l=!1;break}case"import_statement":{let d=c.childForFieldName("source");d&&r.imports.push(pe(d.text)),l=!1;break}case"call_expression":{let d=c.child(0);if(d&&d.text==="require"){let h=c.childForFieldName("arguments")?.child(1);h&&h.type==="string"&&r.imports.push(pe(h.text))}break}}if(l)for(let d=c.childCount-1;d>=0;d--){let p=c.child(d);p&&a.push(p)}}return r}catch{return null}finally{n?.delete?.()}}Se();var We={maxNodes:1e5,maxEdgesPerNode:500,namespace:"code-intelligence:kg",enableVectorEmbeddings:!0,embeddingDimension:384,enableLLMExtraction:!0,llmModelTier:2,llmMaxTokens:2048},he=fe.create("code-intelligence/knowledge-graph"),H=new Set(["ts","tsx","js","jsx"]),Pe=class{config;memory;nodeCache=new Map;edgeIndex=new Map;allEdgesCache;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 N,this.fileReader=new k(this.config.basePath?{basePath:this.config.basePath}:void 0),this.embedder=new K({enableFallback:!0})}isKnowledgeGraphDependencies(e){return e.memory!==void 0}get nsOpts(){return{namespace:this.config.namespace}}async index(e){let t=Date.now(),s=[],n=0,i=0,o=new Map;try{let{paths:r,incremental:a=!1,includeTests:c=!0,languages:l}=e;a||await this.clear();for(let h of r)try{if(l&&l.length>0){let b=this.getFileExtension(h);if(!this.matchesLanguage(b,l))continue}if(!c&&this.isTestFile(h))continue;let f=this.getFileExtension(h);H.has(f)||o.set(f||"(none)",(o.get(f||"(none)")??0)+1);let g=await this.indexFile(h,a);n+=g.nodes,i+=g.edges}catch(f){s.push({file:h,error:G(f)})}let d=Date.now()-t,p=[];if(o.size>0){let h=Array.from(H).join(", ");for(let[f,g]of o){let b=`${g} file(s) with extension '.${f}' were indexed as plain nodes: no dependency extractor for this language, so 'deps'/'impact' will report 0 edges for them. Supported: ${h}.`;p.push(b),he.warn(b)}}return await this.storeIndexMetadata({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,indexedAt:new Date().toISOString()}),P({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,errors:s,warnings:p})}catch(r){return L(A(r))}}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(A(t))}}async mapDependencies(e){try{let{files:t,direction:s,depth:n=3}=e,i=[],o=[],r=new Set,a=[];for(let l of t)await this.traverseDependencies(l,s,n,r,i,o,[],a);let c=this.calculateDependencyMetrics(i,o);return P({nodes:i,edges:o,cycles:a,metrics:c})}catch(t){return L(A(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,this.nsOpts);return s&&this.nodeCache.set(e,s),s}async getEdges(e,t){let s=await this.loadAllEdges();return this.filterEdgesByDirection(s,e,t)}async loadAllEdges(){if(this.allEdgesCache)return this.allEdgesCache;let e=[],t=`${this.config.namespace}:edge:*`,s=await this.memory.search(t,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let n of s){let i=await this.memory.get(n,this.nsOpts);i&&e.push(i)}return this.allEdgesCache=e,e}async clear(){this.nodeCache.clear(),this.edgeIndex.clear(),this.allEdgesCache=void 0;for(let e of[`${this.config.namespace}:node:`,`${this.config.namespace}:edge:`]){let t=await this.memory.search(`${e}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let s of t)await this.memory.delete(s,this.nsOpts)}}async removeFileFromGraph(e){let t=this.pathToNodeId(e),s=this.config.namespace,n=await this.memory.search(`${s}:node:${t}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of n)await this.memory.delete(o,this.nsOpts),this.nodeCache.delete(o.slice(`${s}:node:`.length));let i=await this.memory.search(`${s}:edge:*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of i){let r=await this.memory.get(o,this.nsOpts);r&&(r.source===t||r.source.startsWith(`${t}:`))&&await this.memory.delete(o,this.nsOpts)}this.edgeIndex.delete(t),this.allEdgesCache=void 0}isLLMExtractionAvailable(){return this.config.enableLLMExtraction===!0&&this.llmRouter!==void 0}getModelForTier(e){return be(e)}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),i=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software architect analyzing code structure. Extract:
23
+ `);for(let n of s){let i=n.match(/^\s*import\s+'([^']+)'/);i&&t.push({module:i[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){if(!e.trim())return[];let t=e.replace(/[{}[\]]/g,"");return M(t).map(s=>s.trim()).filter(s=>s).map(s=>{let n=s.replace("required ","").trim().split(/\s+/),i=n[n.length-1]||"",o=n.slice(0,-1).join(" ")||void 0;return{name:i,type:o,isOptional:s.includes("?")||s.includes("{"),defaultValue:void 0}})}},z=ge("ParserRegistry"),Ee=["python","java","csharp","rust","swift"],ae=class u{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<u.MAX_WASM_RETRIES)try{return await this.wasmParser.parseFile(e,t)}catch(s){this.wasmFailCount++;let n=s instanceof Error?s.message:String(s),i=this.wasmFailCount>=u.MAX_WASM_RETRIES;z.warn(`[${this.language}] tree-sitter WASM parser failed (attempt ${this.wasmFailCount}/${u.MAX_WASM_RETRIES}): ${n}. Falling back to regex parser (~97-98% accuracy). `+(i?"Set AQE_PARSER_REGEX_ONLY=1 to silence this warning.":"Will retry WASM on next parse."))}return this.regexParser.parseFile(e,t)}},oe=class{parsers=new Map;_wasmInitPromise=null;constructor(){this.register(new Y),this.register(new Z),this.register(new ee),this.register(new te),this.register(new se),this.register(new ne),this.register(new ie),this.register(new re),this._wasmInitPromise=this._tryLoadWasmParsers()}async _tryLoadWasmParsers(){try{let e=await import("./tree-sitter-wasm-parser-J6ZMAK37.js");if(!e.isWasmAvailable()){z.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 Ee){let n=t.get(s),i=this.parsers.get(s);n&&i&&this.parsers.set(s,new ae(n,i))}z.info("tree-sitter WASM parsers available for: "+Ee.join(", "))}catch{z.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)}},Qe=new oe;import*as S from"node:fs/promises";import*as R from"node:path";var Fe=[/\.\./,/%2e%2e/i,/%252e%252e/i,/\.\.%2f/i,/%2f\.\./i,/\.\.%5c/i,/\.\.\\/,/%c0%ae/i,/%c0%2f/i,/%c1%9c/i,/\0/,/%00/i],Ae=[/^\/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],le=class{name="path-traversal";getRiskLevel(){return"critical"}validate(e,t={}){let{basePath:s="",allowAbsolute:n=!1,allowedExtensions:i=[],deniedExtensions:o=[".exe",".bat",".cmd",".sh",".ps1",".dll",".so"],maxDepth:r=10,maxLength:a=4096}=t;if(e.length>a)return{valid:!1,error:`Path exceeds maximum length of ${a}`,riskLevel:"medium"};for(let f of Fe)if(f.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 f of Ae)if(f.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>r)return{valid:!1,error:`Path depth exceeds maximum of ${r}`,riskLevel:"low"};let d=this.getExtension(c);if(d){let f=`.${d.toLowerCase()}`,g=d.toLowerCase();if(o.length>0&&o.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not allowed`,riskLevel:"high"};if(i.length>0&&!i.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not in allowed list`,riskLevel:"medium"}}let p=s?this.joinPathsAbsolute(s,c):c,h=s.startsWith("/")?`/${this.normalizePath(s)}`:this.normalizePath(s);return s&&!p.startsWith(h)?{valid:!1,error:"Path escapes base directory",riskLevel:"critical"}:{valid:!0,normalizedPath:p,riskLevel:"none"}}normalizePath(e){let t=e.replace(/\\/g,"/");t=t.replace(/\/+/g,"/");let s=t.split("/"),n=[];for(let i of s)i==="."||i===""||(i===".."?n.length>0&&n[n.length-1]!==".."&&n.pop():n.push(i));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}},Ne=new le,Ie=(u,e)=>Ne.validate(u,e);ye();var F=class extends Error{constructor(t,s,n,i){super(t);this.filePath=s;this.code=n;this.cause=i;this.name="FileReadError"}filePath;code;cause},V=class extends Error{constructor(t,s,n){super(t);this.filePath=s;this.cause=n;this.name="JsonParseError"}filePath;cause},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"}requestedPath;issues;riskLevel},de=class{constructor(e,t){this.maxSize=e;this.ttlMs=t}maxSize;ttlMs;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,i)=>{e-n.timestamp>this.ttlMs&&s.push(i)}),s.forEach(n=>{this.delete(n),t++}),t}};function De(u){let e="",t=0;for(;t<u.length;){let s=u[t],n=u[t+1];s==="*"&&n==="*"?u[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 we(u,e,t,s){try{let n=await S.readdir(u,{withFileTypes:!0});for(let i of n){let o=R.join(u,i.name),r=R.relative(s,o);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&await we(o,e,t,s);else if(i.isFile()){let a=r.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 de(e.maxCacheSize??100,e.cacheTtlMs??300*1e3)}resolvePath(e){let t=R.isAbsolute(e),s=Ie(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=R.resolve(this.basePath),i=R.resolve(e);if(!i.startsWith(n))throw new T(e,["Path escapes base directory"],"critical");return i}return s.normalizedPath?s.normalizedPath:t?e:R.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(),P(s);this.stats.cacheMisses++}try{let s=await S.readFile(t,"utf-8");return this.enableCache&&(this.cache.set(t,s,Buffer.byteLength(s,"utf-8")),this.updateCacheStats()),P(s)}catch(s){let n=s,i;switch(n.code){case"ENOENT":i="File not found: "+t;break;case"EACCES":i="Permission denied: "+t;break;case"EISDIR":i="Path is a directory: "+t;break;default:i="Failed to read file: "+t}return L(new F(i,t,n.code,n))}}async readJSON(e){let t=await this.readFile(e);if(!t.success)return t;try{let s=D(t.value);return P(s)}catch(s){let n=s,i=e;try{i=this.resolvePath(e)}catch{}return L(new V("Invalid JSON in file: "+i+" - "+n.message,i,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 S.access(t,S.constants.F_OK),P(!0)}catch(s){let n=s;return n.code==="ENOENT"?P(!1):L(new F("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 S.stat(s)).isDirectory())return L(new F("Base path is not a directory: "+s,s,"ENOTDIR"));let i=De(e),o=[];return await we(s,i,o,s),o.sort(),P(o)}catch(n){let i=n;return L(new F("Failed to list files in: "+s,s,i.code,i))}}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}};J();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"};Me();var _=class{baseUrl;maxRetries;retryDelayMs;timeoutMs;constructor(e=xe(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 i=await this.fetchWithTimeout(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},this.timeoutMs);if(!i.ok){let r=await i.text();throw new Error(`Ollama API error (${i.status}): ${r}`)}let o=await i.json();if(o.embedding.length!==v.DIMENSIONS)throw new Error(`Invalid embedding dimensions: expected ${v.DIMENSIONS}, got ${o.embedding.length}`);return o.embedding}catch(i){if(s=A(i),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,i=setTimeout(()=>n.abort(),s);try{return await fetch(e,{...t,signal:n.signal})}finally{clearTimeout(i)}}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 Oe}from"crypto";var $=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 Oe("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 i={embedding:s,timestamp:Date.now(),model:t};this.cache.set(n,i)}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[i,o]of this.cache.entries())o.timestamp<s&&(this.cache.delete(i),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)}};J();var K=class{client;cache;batchSize;enableFallback;ollamaAvailable=null;constructor(e={}){this.client=new _(e.ollamaBaseUrl),this.cache=e.cache??new $(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,i=e.content.trim();if(s.length+i.length>n){let o=n-s.length-3;i=i.substring(0,o)+"..."}return s+i}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=[],i=0,o=0,r=await this.isOllamaAvailable();if(r)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,r);n.push(...d);for(let p of d)p.cached?i++:o++;if(t){let p=c+l.length,h=e.length,g=(Date.now()-s)/p,y=(h-p)*g;t({current:p,total:h,percentage:p/h*100,estimatedTimeRemainingMs:y})}}let a=Date.now()-s;return{results:n,stats:{totalChunks:e.length,cachedHits:i,computedNew:o,totalTimeMs:a,avgTimePerChunk:a/e.length}}}async processBatch(e,t){let s=[],n=e.map(async o=>{let r=this.formatForEmbedding(o),a=Date.now(),c=this.cache.get(r,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(r):l=this.generatePseudoEmbedding(r),this.cache.set(r,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}: ${G(l)}`)}}),i=await Promise.all(n);return s.push(...i),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 r=s[o];for(let a=0;a<r.length&&a<t.length;a++)t[(o+a)%t.length]+=r.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,r]of n)o.test(e)&&(t[r]+=.5);let i=Math.sqrt(t.reduce((o,r)=>o+r*r,0))||1;return t.map(o=>o/i)}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}}};J();ye();import{existsSync as Ke,statSync as Ue}from"fs";import{dirname as je,resolve as Ge,join as q}from"path";function ke(u){switch(u){case"ts":case"mts":case"cts":return"tree-sitter-typescript.wasm";case"tsx":return"tree-sitter-tsx.wasm";case"js":case"jsx":case"mjs":case"cjs":return"tree-sitter-javascript.wasm";default:return null}}var U=u=>u.startPosition.row+1,j=(u,e)=>u.childForFieldName(e)?.text??"";function ue(u){for(let e=0;e<u.childCount;e++){let t=u.child(e);if(t){if(t.type==="async")return!0;if(t.type==="function"||t.type==="function_declaration")break}}return!1}function _e(u){for(let e=0;e<u.childCount;e++)if(u.child(e)?.type==="accessibility_modifier"){let s=u.child(e).text;if(s==="private")return"private";if(s==="protected")return"protected"}return"public"}function $e(u){let e=j(u,"name")||"(anonymous)",t=u.childForFieldName("body"),s=[];if(t)for(let n=0;n<t.childCount;n++){let i=t.child(n);i&&i.type==="method_definition"&&s.push({name:j(i,"name"),startLine:U(i),isAsync:ue(i),visibility:_e(i)})}return{name:e,startLine:U(u),methods:s}}function pe(u){return u.replace(/^['"`]|['"`]$/g,"")}async function me(u,e){let t=ke(e);if(!t)return null;let s=await ve(t);if(!s)return null;let n=null;try{let i=s.parse(u);n=i;let o=i.rootNode;if(!o)return null;let r={functions:[],classes:[],interfaces:[],imports:[]},a=[o];for(;a.length;){let c=a.pop(),l=!0;switch(c.type){case"function_declaration":case"generator_function_declaration":r.functions.push({name:j(c,"name"),startLine:U(c),isAsync:ue(c),visibility:"public"}),l=!1;break;case"class_declaration":case"class":r.classes.push($e(c)),l=!1;break;case"interface_declaration":r.interfaces.push({name:j(c,"name"),startLine:U(c)}),l=!1;break;case"lexical_declaration":case"variable_declaration":{for(let d=0;d<c.childCount;d++){let p=c.child(d);if(!p||p.type!=="variable_declarator")continue;let h=p.childForFieldName("value");if(h&&(h.type==="arrow_function"||h.type==="function"||h.type==="function_expression"))r.functions.push({name:j(p,"name"),startLine:U(p),isAsync:ue(h),visibility:"public"});else if(h&&h.type==="call_expression"&&h.child(0)?.text==="require"){let f=h.childForFieldName("arguments")?.child(1);f&&f.type==="string"&&r.imports.push(pe(f.text))}}l=!1;break}case"import_statement":{let d=c.childForFieldName("source");d&&r.imports.push(pe(d.text)),l=!1;break}case"call_expression":{let d=c.child(0);if(d&&d.text==="require"){let h=c.childForFieldName("arguments")?.child(1);h&&h.type==="string"&&r.imports.push(pe(h.text))}break}}if(l)for(let d=c.childCount-1;d>=0;d--){let p=c.child(d);p&&a.push(p)}}return r}catch{return null}finally{n?.delete?.()}}Se();var We={maxNodes:1e5,maxEdgesPerNode:500,namespace:"code-intelligence:kg",enableVectorEmbeddings:!0,embeddingDimension:384,enableLLMExtraction:!0,llmModelTier:2,llmMaxTokens:2048},he=fe.create("code-intelligence/knowledge-graph"),H=new Set(["ts","tsx","js","jsx"]),Pe=class{config;memory;nodeCache=new Map;edgeIndex=new Map;allEdgesCache;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 N,this.fileReader=new k(this.config.basePath?{basePath:this.config.basePath}:void 0),this.embedder=new K({enableFallback:!0})}isKnowledgeGraphDependencies(e){return e.memory!==void 0}get nsOpts(){return{namespace:this.config.namespace}}async index(e){let t=Date.now(),s=[],n=0,i=0,o=new Map;try{let{paths:r,incremental:a=!1,includeTests:c=!0,languages:l}=e;a||await this.clear();for(let h of r)try{if(l&&l.length>0){let b=this.getFileExtension(h);if(!this.matchesLanguage(b,l))continue}if(!c&&this.isTestFile(h))continue;let f=this.getFileExtension(h);H.has(f)||o.set(f||"(none)",(o.get(f||"(none)")??0)+1);let g=await this.indexFile(h,a);n+=g.nodes,i+=g.edges}catch(f){s.push({file:h,error:G(f)})}let d=Date.now()-t,p=[];if(o.size>0){let h=Array.from(H).join(", ");for(let[f,g]of o){let b=`${g} file(s) with extension '.${f}' were indexed as plain nodes: no dependency extractor for this language, so 'deps'/'impact' will report 0 edges for them. Supported: ${h}.`;p.push(b),he.warn(b)}}return await this.storeIndexMetadata({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,indexedAt:new Date().toISOString()}),P({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,errors:s,warnings:p})}catch(r){return L(A(r))}}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(A(t))}}async mapDependencies(e){try{let{files:t,direction:s,depth:n=3}=e,i=[],o=[],r=new Set,a=[];for(let l of t)await this.traverseDependencies(l,s,n,r,i,o,[],a);let c=this.calculateDependencyMetrics(i,o);return P({nodes:i,edges:o,cycles:a,metrics:c})}catch(t){return L(A(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,this.nsOpts);return s&&this.nodeCache.set(e,s),s}async getEdges(e,t){let s=await this.loadAllEdges();return this.filterEdgesByDirection(s,e,t)}async loadAllEdges(){if(this.allEdgesCache)return this.allEdgesCache;let e=[],t=`${this.config.namespace}:edge:*`,s=await this.memory.search(t,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let n of s){let i=await this.memory.get(n,this.nsOpts);i&&e.push(i)}return this.allEdgesCache=e,e}async clear(){this.nodeCache.clear(),this.edgeIndex.clear(),this.allEdgesCache=void 0;for(let e of[`${this.config.namespace}:node:`,`${this.config.namespace}:edge:`]){let t=await this.memory.search(`${e}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let s of t)await this.memory.delete(s,this.nsOpts)}}async removeFileFromGraph(e){let t=this.pathToNodeId(e),s=this.config.namespace,n=await this.memory.search(`${s}:node:${t}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of n)await this.memory.delete(o,this.nsOpts),this.nodeCache.delete(o.slice(`${s}:node:`.length));let i=await this.memory.search(`${s}:edge:*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of i){let r=await this.memory.get(o,this.nsOpts);r&&(r.source===t||r.source.startsWith(`${t}:`))&&await this.memory.delete(o,this.nsOpts)}this.edgeIndex.delete(t),this.allEdgesCache=void 0}isLLMExtractionAvailable(){return this.config.enableLLMExtraction===!0&&this.llmRouter!==void 0}getModelForTier(e){return be(e)}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),i=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software architect analyzing code structure. Extract:
24
24
  1. Semantic relationships between code entities (inheritance, composition, dependency, collaboration)
25
25
  2. Design patterns used (Factory, Singleton, Observer, Strategy, etc.)
26
26
  3. Architectural boundaries (layers, modules, domains)
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.4");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
2
  var P="quality-daemon",x=class{constructor(e){this.backend=e}backend;async get(e){return this.backend.kvGet(e,P)}async set(e,t){await this.backend.kvSet(e,t,P)}async search(e){return this.backend.kvSearch(e,P)}};import{cpus as Z,freemem as ee,totalmem as te,loadavg as ie}from"os";var g=class{queues={now:[],next:[],later:[]};_maxSize;constructor(e=1e3){this._maxSize=e}enqueue(e){return this.size>=this._maxSize?!1:(this.queues[e.priority].push(e),!0)}dequeue(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(;i.length>0;){let o=i.shift();if(!(o.ttlMs&&e-o.createdAt>o.ttlMs))return o}}}peek(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(let o of i)if(!o.ttlMs||e-o.createdAt<=o.ttlMs)return o}}drainPriority(e){let t=this.queues[e].splice(0),i=Date.now();return t.filter(o=>!o.ttlMs||i-o.createdAt<=o.ttlMs)}pruneExpired(){let e=0,t=Date.now();for(let i of["now","next","later"]){let o=this.queues[i].length;this.queues[i]=this.queues[i].filter(r=>!r.ttlMs||t-r.createdAt<=r.ttlMs),e+=o-this.queues[i].length}return e}get size(){return this.queues.now.length+this.queues.next.length+this.queues.later.length}get depths(){return{now:this.queues.now.length,next:this.queues.next.length,later:this.queues.later.length}}get isEmpty(){return this.size===0}clear(){this.queues.now=[],this.queues.next=[],this.queues.later=[]}};import{watch as G}from"fs";import{execFile as Q}from"child_process";import{promisify as $}from"util";import{resolve as q,join as H}from"path";import{existsSync as L,readFileSync as U}from"fs";var _=$(Q),z={repoRoot:process.cwd(),debounceMs:500,maxChangedFiles:200,pollIntervalMs:5e3},p=class{constructor(e,t){this.queue=e;this.options={...z,...t}}queue;watcher;pollTimer;options;lastKnownHeads=new Map;debounceTimer;_running=!1;_polling=!1;get running(){return this._running}async start(){if(this._running)return;let e=q(this.options.repoRoot,".git","refs","heads");if(!L(e))throw new Error(`Git refs directory not found: ${e}`);await this.snapshotHeads(),process.platform==="darwin"||process.platform==="win32"?this.watcher=G(e,{recursive:!0},(i,o)=>{o&&this.handleRefChange(o)}):(this.pollTimer=setInterval(()=>{this.poll().catch(i=>{console.debug("[GitWatcher] Poll error:",i)})},this.options.pollIntervalMs),this.pollTimer.unref?.()),this._running=!0}stop(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0),this.watcher&&(this.watcher.close(),this.watcher=void 0),this._running=!1}async poll(){if(this._polling)return[];this._polling=!0;let e=[];try{let{stdout:t}=await _("git",["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot});for(let i of t.trim().split(`
3
3
  `)){if(!i)continue;let[o,r]=i.split(" "),n=this.lastKnownHeads.get(o);n&&n!==r&&(e.push(o),await this.enqueueCommitAnalysis(o,r)),this.lastKnownHeads.set(o,r)}}catch{}finally{this._polling=!1}return e}handleRefChange(e){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.processRefChange(e).catch(t=>{console.debug("[GitWatcher] Error processing ref change:",t)})},this.options.debounceMs)}async processRefChange(e){let t=e.replace(/\\/g,"/"),i=q(this.options.repoRoot,".git","refs","heads"),o=H(i,e),r;try{r=U(o,"utf-8").trim()}catch{return}this.lastKnownHeads.get(t)!==r&&(this.lastKnownHeads.set(t,r),await this.enqueueCommitAnalysis(t,r))}async enqueueCommitAnalysis(e,t){let i=[];try{let{stdout:n}=await _("git",["diff-tree","--no-commit-id","--name-only","-r",t],{cwd:this.options.repoRoot});i=n.trim().split(`
4
4
  `).filter(Boolean).slice(0,this.options.maxChangedFiles)}catch{}let o={type:"git_commit",branch:e,commitHash:t,changedFiles:i},r={id:`git-${t}-${Date.now()}`,priority:"next",payload:o,createdAt:Date.now(),source:"git-watcher",ttlMs:300*1e3};this.queue.enqueue(r)}async snapshotHeads(){try{let{stdout:e}=await _("git",["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot});for(let t of e.trim().split(`
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.4");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
2
  var i={copilot:{id:"copilot",name:"GitHub Copilot",configPath:".vscode/mcp.json",configFormat:"json",configKey:"servers",rulesPath:".github/copilot-instructions.md",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},cursor:{id:"cursor",name:"Cursor",configPath:".cursor/mcp.json",configFormat:"json",configKey:"mcpServers",rulesPath:".cursorrules",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},cline:{id:"cline",name:"Cline",configPath:".vscode/cline_mcp_settings.json",configFormat:"json",configKey:"mcpServers",rulesPath:".vscode/cline_custom_modes.json",rulesFormat:"json",supportsAutoApprove:!0,supportsCustomModes:!0,globalConfig:!1},kilocode:{id:"kilocode",name:"Kilo Code",configPath:".kilocode/mcp.json",configFormat:"json",configKey:"mcpServers",rulesPath:".kilocode/modes.json",rulesFormat:"json",supportsAutoApprove:!0,supportsCustomModes:!0,globalConfig:!1},roocode:{id:"roocode",name:"Roo Code",configPath:".roo/mcp.json",configFormat:"json",configKey:"mcpServers",rulesPath:".roo/modes.json",rulesFormat:"json",supportsAutoApprove:!0,supportsCustomModes:!0,globalConfig:!1},codex:{id:"codex",name:"OpenAI Codex CLI",configPath:".codex/config.toml",configFormat:"toml",configKey:"mcp_servers",rulesPath:"AGENTS.md",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},windsurf:{id:"windsurf",name:"Windsurf",configPath:".windsurf/mcp_config.json",configFormat:"json",configKey:"mcpServers",rulesPath:".windsurfrules",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},continuedev:{id:"continuedev",name:"Continue.dev",configPath:".continue/config.yaml",configFormat:"yaml",configKey:"mcpServers",rulesPath:".continue/rules/aqe-qe-standards.yaml",rulesFormat:"yaml",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1}},l=["fleet_init","fleet_status","fleet_health","agent_list","agent_metrics","agent_status","team_list","team_health","task_list","task_status","test_generate_enhanced","coverage_analyze_sublinear","quality_assess","defect_predict","code_index","memory_store","memory_retrieve","memory_query","memory_usage","model_route","routing_metrics","aqe_health"];function u(t){return t?{AQE_MEMORY_BACKEND:"memory",AQE_V3_MODE:"true"}:{AQE_MEMORY_PATH:".agentic-qe/memory.db",AQE_V3_MODE:"true"}}function m(t,o){let e={command:"npx",args:["-y","agentic-qe@latest","mcp"],env:u(o)};return t&&(e.disabled=!1,e.alwaysAllow=l),e}function g(t,o){let e=m(t.supportsAutoApprove,o);if(t.id==="copilot"){let r={[t.configKey]:{"agentic-qe":{type:"stdio",...e}}};return JSON.stringify(r,null,2)+`
3
3
  `}let n={[t.configKey]:{"agentic-qe":e}};return JSON.stringify(n,null,2)+`
4
4
  `}function f(t){return`# Agentic QE MCP Server
@@ -0,0 +1,15 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
+ import{h as c,k as d,o as f}from"./chunk-EFV4ADMO.js";import{a as h}from"./chunk-J27F4NSB.js";import{c as l}from"./chunk-7CD7PBHY.js";import{a as r,e as p}from"./chunk-CVMNJSCB.js";f();p();h();import*as m from"path";var u=l.create("hybrid-backend"),s=class{unifiedMemory=null;config;cleanupInterval;cleanupCount=0;initialized=!1;constructor(e){this.config={sqlite:{path:e?.sqlite?.path??".agentic-qe/memory.db",walMode:e?.sqlite?.walMode??!0,poolSize:e?.sqlite?.poolSize??5,busyTimeout:e?.sqlite?.busyTimeout??r.BUSY_TIMEOUT_MS,...e?.sqlite},agentdb:{path:e?.agentdb?.path??".agentic-qe/memory.db",...e?.agentdb},enableFallback:e?.enableFallback??!0,defaultNamespace:e?.defaultNamespace??"default",cleanupInterval:e?.cleanupInterval??r.CLEANUP_INTERVAL_MS}}async initialize(e){if(this.initialized)return;let i=e?.signal;i?.throwIfAborted();let t={dbPath:this.config.sqlite.path??c.dbPath,walMode:this.config.sqlite.walMode??!0,busyTimeout:this.config.sqlite.busyTimeout??r.BUSY_TIMEOUT_MS};this.unifiedMemory=d(t),i?.throwIfAborted(),await this.unifiedMemory.initialize({signal:i}),i?.throwIfAborted(),this.cleanupInterval=setInterval(()=>this.cleanup(),this.config.cleanupInterval),this.cleanupInterval.unref&&this.cleanupInterval.unref(),this.initialized=!0,console.log(`[HybridBackend] Initialized with unified memory: ${this.unifiedMemory.getDbPath()}`)}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.initialized=!1}async set(e,i,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;await this.unifiedMemory.kvSet(e,i,n,t?.ttl)}async get(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvGet(e,t)}async delete(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace,n=await this.unifiedMemory.kvDelete(e,t),a=await this.unifiedMemory.vectorDelete(e);return n||a}async has(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvExists(e,t)}async search(e,i=100,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvSearch(e,n,i)}async vectorSearch(e,i,t){return this.ensureInitialized(),(await this.unifiedMemory.vectorSearch(e,i,void 0,t)).map(a=>({key:a.id,score:a.score,metadata:a.metadata}))}getVectorSearchProvenance(){return this.ensureInitialized(),this.unifiedMemory.getVectorSearchProvenance()}async storeVector(e,i,t){this.ensureInitialized(),await this.unifiedMemory.vectorStore(e,i,this.config.defaultNamespace,t)}getHealth(){return{sqlite:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",sqlitePersistent:!0,agentdb:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",fallback:"inactive"}}isPersistent(){return this.unifiedMemory?.isInitialized()??!1}getConfig(){return{...this.config}}async setWithBackend(e,i,t,n){await this.set(e,i,n)}async getVectorStats(){if(!this.unifiedMemory?.isInitialized())return null;let e=await this.unifiedMemory.vectorCount(),i=this.unifiedMemory.getStats();return{vectorCount:e,indexSize:i.vectorIndexSize}}getUnifiedMemory(){return this.unifiedMemory}async count(e){return this.ensureInitialized(),this.unifiedMemory.getDatabase().prepare(`
3
+ SELECT COUNT(*) as count FROM kv_store
4
+ WHERE namespace LIKE ?
5
+ AND (expires_at IS NULL OR expires_at > ?)
6
+ `).get(`${e}%`,Date.now()).count}async hasCodeIntelligenceIndex(){return this.ensureInitialized(),this.unifiedMemory.getDatabase().prepare(`
7
+ SELECT 1 FROM kv_store
8
+ WHERE namespace = 'code-intelligence:kg'
9
+ AND (expires_at IS NULL OR expires_at > ?)
10
+ LIMIT 1
11
+ `).get(Date.now())!==void 0}ensureInitialized(){if(!this.initialized||!this.unifiedMemory)throw new Error("HybridMemoryBackend not initialized. Call initialize() first.")}async cleanup(){if(this.unifiedMemory?.isInitialized())try{await this.unifiedMemory.kvCleanupExpired();let e=this.unifiedMemory.getDatabase();try{let i=e.prepare("DELETE FROM kv_store WHERE expires_at IS NOT NULL AND expires_at < ?").run(Date.now());i.changes>0&&console.log(`[HybridBackend] Expired ${i.changes} kv_store entries`)}catch(i){u.debug("TTL expiration cleanup failed",{error:i instanceof Error?i.message:String(i)})}if(this.cleanupCount++,this.cleanupCount%10===0)try{if(e.prepare("SELECT COUNT(*) as cnt FROM kv_store").get().cnt>5e3){let t=e.prepare(`
12
+ DELETE FROM kv_store WHERE rowid NOT IN (
13
+ SELECT rowid FROM kv_store ORDER BY rowid DESC LIMIT 5000
14
+ )
15
+ `).run();t.changes>0&&console.log(`[HybridBackend] kv_store retention: pruned ${t.changes} rows (kept 5000)`)}}catch(i){u.debug("KV store retention pruning failed",{error:i instanceof Error?i.message:String(i)})}}catch(e){console.warn("[HybridBackend] Cleanup failed:",e)}}};function I(o){return new s({sqlite:{path:m.join(o,"memory.db"),walMode:!0,poolSize:3,busyTimeout:r.BUSY_TIMEOUT_MS},enableFallback:!0,defaultNamespace:"qe-kernel"})}export{s as a,I as b};
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.4");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
2
  import a from"chalk";import{existsSync as m,statSync as S}from"fs";import{join as p,relative as P}from"path";var l=class{static prompt(t,e){return new Promise(r=>{t.question(e,s=>{r(s)})})}static printStepHeader(t,e,r){console.log(""),console.log(a.cyan(`Step ${t}: ${e}`)),r&&console.log(a.gray(r)),console.log("")}static printWizardHeader(t,e){console.log(""),console.log(a.blue("========================================")),console.log(a.blue.bold(` ${t}`)),console.log(a.blue("========================================")),e&&console.log(a.gray(e)),console.log(a.gray("Press Ctrl+C to cancel at any time")),console.log("")}static printSummaryHeader(){console.log(""),console.log(a.blue("========================================")),console.log(a.blue.bold(" Configuration Summary")),console.log(a.blue("========================================")),console.log("")}static printSummaryField(t,e,r){let s=r?.indent??" ",i=r?.maxItems??5,c=r?.formatValue??(o=>a.cyan(o));if(Array.isArray(e))e.length===0?console.log(a.white(`${s}${t}: ${a.gray("(none)")}`)):e.length<=i?console.log(a.white(`${s}${t}: ${c(e.join(", "))}`)):(console.log(a.white(`${s}${t}:`)),e.slice(0,i).forEach(o=>{console.log(a.gray(`${s} - ${o}`))}),console.log(a.gray(`${s} ... and ${e.length-i} more`)));else{let o=t.padEnd(16);console.log(a.white(`${s}${o}${c(e)}`))}}static printDerivedSettings(t,e=" "){console.log(""),console.log(a.gray(`${e}Derived settings:`));for(let[r,s]of Object.entries(t))console.log(a.gray(`${e} ${r}: ${s}`));console.log("")}};var h=class u{static getSourceDirectories(t){let e=[],r=["src","lib","app","packages","api"];for(let s of r){let i=p(t,s);m(i)&&S(i).isDirectory()&&e.push(s)}return e}static getCoverageTargets(t){let e=u.getSourceDirectories(t),r=["coverage","coverage/lcov.info","coverage/coverage-final.json",".nyc_output"];for(let s of r){let i=p(t,s);m(i)&&e.push(s)}return e}static getSecurityTargets(t){let e=u.getSourceDirectories(t),r=["package.json","package-lock.json","yarn.lock","pnpm-lock.yaml",".env",".env.example","docker-compose.yml","Dockerfile"];for(let s of r){let i=p(t,s);m(i)&&e.push(s)}return e}static getTestSourceFiles(t){let e=[],r=["src","lib","app","packages"];for(let s of r){let i=p(t,s);m(i)&&S(i).isDirectory()&&(e.push(`${s}/**/*.ts`),e.push(s))}return m(p(t,"src"))&&(e.push("src/services/**/*.ts"),e.push("src/utils/**/*.ts"),e.push("src/components/**/*.tsx")),e}static checkPatternsExist(t){return[p(t,".agentic-qe","patterns"),p(t,".agentic-qe","memory.db"),p(t,".aqe","patterns"),p(t,"data","patterns")].some(r=>m(r))}},f=class{static relativePath(t,e){return P(e,t)||"."}static yesNo(t){return t?"Yes":"No"}static enabledDisabled(t){return t?"Enabled":"Disabled"}static percentage(t){return`${t}%`}static truncatedList(t,e=5){return t.length===0?"(none)":t.length<=e?t.join(", "):`${t.slice(0,e).join(", ")}... and ${t.length-e} more`}};import n from"chalk";import{existsSync as w}from"fs";import{resolve as I}from"path";var d=class{constructor(t){this.defaultValue=t}defaultValue;description;getDefaultValue(){return this.defaultValue}success(t){return{value:t,continue:!0}}cancelled(){return{value:this.defaultValue,continue:!1}}error(t){return{value:this.defaultValue,continue:!1,error:t}}};var y=class extends d{id;stepNumber;title;description;options;validValues;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.options=t.options,this.validValues=t.validValues}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.options.forEach(i=>{let c=[];i.isRecommended?c.push(n.green(" (recommended)")):(i.isDefault||i.value===this.defaultValue)&&c.push(n.green(" (default)")),console.log(n.white(` ${i.key}. ${i.label||i.value}${c.join("")}`)),i.description&&console.log(n.gray(` ${i.description}`))}),console.log("");let r=(await l.prompt(t.rl,`Select ${this.title.toLowerCase()} [${n.gray(String(this.defaultValue))}]: `)).trim();if(!r)return this.success(this.defaultValue);let s=parseInt(r,10);return s>=1&&s<=this.options.length?this.success(this.options[s-1].value):this.validValues.includes(r)?this.success(r):(console.log(n.yellow(` Invalid input, using default: ${this.defaultValue}`)),this.success(this.defaultValue))}},b=class extends d{id;stepNumber;title;description;options;validValues;instructions;allowEmpty;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.options=t.options,this.validValues=t.validValues,this.instructions=t.instructions,this.allowEmpty=t.allowEmpty??!1}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.instructions&&(console.log(n.gray(this.instructions)),console.log("")),this.options.forEach(o=>{let N=o.isDefaultSelected||this.defaultValue.includes(o.value)?n.green(" *"):"";console.log(n.white(` ${o.key}. ${o.label||o.value}${N}`)),o.description&&console.log(n.gray(` ${o.description}`))}),console.log(""),console.log(n.gray(" * = included in default selection")),console.log("");let e=this.defaultValue.join(","),s=(await l.prompt(t.rl,`Select options [${n.gray(e)}]: `)).trim();if(!s)return this.success(this.defaultValue);let i=s.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o.length>0),c=[];for(let o of i){let g=parseInt(o,10);g>=1&&g<=this.options.length?c.push(this.options[g-1].value):this.validValues.includes(o)&&c.push(o)}return c.length===0?this.allowEmpty?this.success([]):(console.log(n.yellow(` Invalid input, using default: ${e}`)),this.success(this.defaultValue)):this.success([...new Set(c)])}},v=class extends d{id;stepNumber;title;description;additionalInfo;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.additionalInfo=t.additionalInfo}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.additionalInfo&&(console.log(n.gray(this.additionalInfo)),console.log(""));let e=this.defaultValue?"Y/n":"y/N",s=(await l.prompt(t.rl,`${this.title}? [${n.gray(e)}]: `)).trim().toLowerCase();return s===""?this.success(this.defaultValue):s==="n"||s==="no"?this.success(!1):s==="y"||s==="yes"?this.success(!0):this.success(this.defaultValue)}},x=class extends d{id;stepNumber;title;description;presets;min;max;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.presets=t.presets,this.min=t.min,this.max=t.max}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.presets&&this.presets.length>0&&(this.presets.forEach(i=>{let c=i.value===this.defaultValue?n.green(" (default)"):"";console.log(n.gray(` ${i.key}. ${i.label}${c}`))}),this.min!==void 0&&this.max!==void 0&&console.log(n.gray(` Or enter a custom number (${this.min}-${this.max})`)),console.log(""));let r=(await l.prompt(t.rl,`${this.title} [${n.gray(String(this.defaultValue))}]: `)).trim();if(!r)return this.success(this.defaultValue);let s=parseInt(r,10);if(this.presets){let i=s;if(i>=1&&i<=this.presets.length)return this.success(this.presets[i-1].value)}return isNaN(s)?(console.log(n.yellow(` Invalid input, using default: ${this.defaultValue}`)),this.success(this.defaultValue)):this.min!==void 0&&s<this.min?(console.log(n.yellow(` Value too low, using minimum: ${this.min}`)),this.success(this.min)):this.max!==void 0&&s>this.max?(console.log(n.yellow(` Value too high, using maximum: ${this.max}`)),this.success(this.max)):this.success(s)}},C=class extends d{id;stepNumber;title;description;examples;suggestionsProvider;validatePath;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.examples=t.examples,this.suggestionsProvider=t.suggestionsProvider,this.validatePath=t.validatePath??!0}async execute(t){if(t.nonInteractive){let i=I(t.cwd,this.defaultValue);return this.success(w(i)?i:t.cwd)}if(l.printStepHeader(this.stepNumber,this.title,this.description),this.examples&&(console.log(n.gray(`Examples: ${this.examples}`)),console.log("")),this.suggestionsProvider){let i=this.suggestionsProvider(t.cwd);i.length>0&&(console.log(n.yellow("Detected directories:")),i.slice(0,5).forEach((c,o)=>{console.log(n.gray(` ${o+1}. ${c}`))}),console.log(""))}let r=(await l.prompt(t.rl,`${this.title} [${n.gray(this.defaultValue)}]: `)).trim()||this.defaultValue,s=I(t.cwd,r);return this.validatePath&&!w(s)?(console.log(n.yellow(` Warning: '${r}' does not exist, using current directory.`)),this.success(t.cwd)):this.success(s)}};var T=class extends d{id;stepNumber;title;description;constructor(t){super({}),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description}async execute(t){if(t.nonInteractive)return this.success({});l.printStepHeader(this.stepNumber,this.title,this.description);let e=await l.prompt(t.rl,`Include patterns [${n.gray("e.g., src/**/*.ts")}]: `),r=await l.prompt(t.rl,`Exclude patterns [${n.gray("e.g., **/*.test.ts,dist/**")}]: `),s={};return e.trim()&&(s.include=e.split(",").map(i=>i.trim()).filter(i=>i.length>0)),r.trim()&&(s.exclude=r.split(",").map(i=>i.trim()).filter(i=>i.length>0)),this.success(s)}};import{createInterface as R}from"readline";import $ from"chalk";var V=class{options;cwd;constructor(t){this.options=t,this.cwd=process.cwd()}async run(){if(this.isNonInteractive())return this.getDefaults();let t=R({input:process.stdin,output:process.stdout});try{this.printHeader();let e={},r=this.getCommands();for(let c of r){let o={rl:t,cwd:this.cwd,results:e,nonInteractive:!1},g=await c.execute(o);if(!g.continue)return this.getCancelled();e[c.id]=g.value}let s=this.buildResult(e);return this.printSummary(s),await this.promptConfirmation(t)?s:this.getCancelled()}finally{t.close()}}printHeader(){l.printWizardHeader(this.getTitle(),this.getSubtitle())}async promptConfirmation(t){console.log("");let r=(await l.prompt(t,`${$.green(this.getConfirmationPrompt())} [${$.gray("Y/n")}]: `)).trim().toLowerCase();return r==="n"||r==="no"?(console.log($.yellow(`
3
3
  Wizard cancelled.`)),!1):!0}};export{l as a,h as b,f as c,y as d,b as e,v as f,x as g,C as h,T as i,V as j};