agentic-qe 3.15.9 → 3.15.10

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 (568) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +251 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/adapters/a2ui/catalog/component-schemas.js +2 -1
  5. package/dist/adapters/a2ui/data/json-pointer-resolver.js +10 -5
  6. package/dist/adapters/a2ui/integration/agui-sync.js +10 -6
  7. package/dist/adapters/a2ui/integration/surface-state-bridge.js +9 -5
  8. package/dist/adapters/ag-ui/json-patch.js +10 -6
  9. package/dist/audit/witness-chain.d.ts +1 -1
  10. package/dist/cli/bundle.js +6 -6
  11. package/dist/cli/chunks/adapter-TR5SLAZC.js +2 -0
  12. package/dist/cli/chunks/agent-booster-wasm-H7ANGXW4.js +2 -0
  13. package/dist/cli/chunks/{agent-handler-RIYHTHVZ.js → agent-handler-SVXSHEET.js} +2 -2
  14. package/dist/cli/chunks/{agent-memory-branch-WSUCUHOO.js → agent-memory-branch-WKQH36XL.js} +2 -2
  15. package/dist/cli/chunks/aqe-learning-engine-DXWKCHY2.js +2 -0
  16. package/dist/cli/chunks/{arena-KRIBMIXX.js → arena-EKOOFVST.js} +2 -2
  17. package/dist/cli/chunks/{arena-YAJZX6MC.js → arena-OPS36NFZ.js} +4 -4
  18. package/dist/cli/chunks/{audit-7ZNOXWP3.js → audit-AO5NDZRI.js} +3 -3
  19. package/dist/cli/chunks/base-GTB6POYE.js +2 -0
  20. package/dist/cli/chunks/{better-sqlite3-ZQAT4I6H.js → better-sqlite3-TFLVEMMY.js} +2 -2
  21. package/dist/cli/chunks/{brain-handler-452WCPZC.js → brain-handler-ADBBJPYW.js} +3 -3
  22. package/dist/cli/chunks/{branch-enumerator-IJFXJRPN.js → branch-enumerator-HGHUYYL5.js} +2 -2
  23. package/dist/cli/chunks/browser-5LU6P4SZ.js +4 -0
  24. package/dist/cli/chunks/browser-workflow-MSBOLYUY.js +2 -0
  25. package/dist/cli/chunks/{chunk-UOJBR4J3.js → chunk-2SXBBUM6.js} +2 -2
  26. package/dist/cli/chunks/{chunk-7JKB3Q7O.js → chunk-2T7RRL6G.js} +1 -1
  27. package/dist/cli/chunks/{chunk-HCYQHWI2.js → chunk-2XGVTYVX.js} +2 -2
  28. package/dist/cli/chunks/{chunk-3LYU7BLY.js → chunk-2ZI5FKSF.js} +2 -2
  29. package/dist/cli/chunks/chunk-2ZMF4NCF.js +4 -0
  30. package/dist/cli/chunks/{chunk-F3PQZX44.js → chunk-37OWRCUN.js} +1 -1
  31. package/dist/cli/chunks/{chunk-YRBBBUJX.js → chunk-3P34JFQH.js} +4 -4
  32. package/dist/cli/chunks/{chunk-ICP2ORGI.js → chunk-3Y7SPD72.js} +2 -2
  33. package/dist/cli/chunks/{chunk-WGDR2KIR.js → chunk-4G63WT4F.js} +2 -2
  34. package/dist/cli/chunks/chunk-4SJYIX54.js +3 -0
  35. package/dist/cli/chunks/chunk-5E6GHSTY.js +3 -0
  36. package/dist/cli/chunks/{chunk-OXTFSIGN.js → chunk-5LPYV3TK.js} +1 -1
  37. package/dist/cli/chunks/{chunk-XWIUFYM3.js → chunk-62OAY5KJ.js} +1 -1
  38. package/dist/cli/chunks/{chunk-VCMINU7K.js → chunk-6C3II5OM.js} +2 -2
  39. package/dist/cli/chunks/{chunk-EFBLP43U.js → chunk-6GP6W46M.js} +2 -2
  40. package/dist/cli/chunks/{chunk-4JCY45KV.js → chunk-6KIL6CMD.js} +2 -2
  41. package/dist/cli/chunks/{chunk-CTZJUV5I.js → chunk-6MVVSSID.js} +1 -1
  42. package/dist/cli/chunks/{chunk-JEP4ULR6.js → chunk-6P7424AO.js} +2 -2
  43. package/dist/cli/chunks/{chunk-SVHUYVUR.js → chunk-6PX4OXQO.js} +2 -2
  44. package/dist/cli/chunks/{chunk-LEAKYZ37.js → chunk-6S3WJGUV.js} +2 -2
  45. package/dist/cli/chunks/{chunk-7X2Y727E.js → chunk-6TB6YOCZ.js} +1 -1
  46. package/dist/cli/chunks/{chunk-VU2EL424.js → chunk-6X5DHU6Q.js} +1 -1
  47. package/dist/cli/chunks/{chunk-DDPPSSHW.js → chunk-6XCMKIZN.js} +1 -1
  48. package/dist/cli/chunks/{chunk-ZANDSVCK.js → chunk-7LFZ4CHM.js} +2 -2
  49. package/dist/cli/chunks/{chunk-UYLYMWV5.js → chunk-7OZVZIBE.js} +2 -2
  50. package/dist/cli/chunks/{chunk-32UTLDNY.js → chunk-7PJIR4ST.js} +2 -2
  51. package/dist/cli/chunks/{chunk-DINZR5CF.js → chunk-7TB6FK4B.js} +1 -1
  52. package/dist/cli/chunks/{chunk-KVBEGOJE.js → chunk-7ZCDZHDB.js} +2 -2
  53. package/dist/cli/chunks/{chunk-55HRSNGN.js → chunk-A55QKKT2.js} +2 -2
  54. package/dist/cli/chunks/{chunk-LCJTEUDC.js → chunk-ABFFWZPC.js} +428 -433
  55. package/dist/cli/chunks/{chunk-PVIA2FPD.js → chunk-ACWFKES2.js} +2 -2
  56. package/dist/cli/chunks/{chunk-2BA45H64.js → chunk-AH3ZD3NJ.js} +2 -2
  57. package/dist/cli/chunks/{chunk-OG2UI6A3.js → chunk-AI4VYSFS.js} +2 -2
  58. package/dist/cli/chunks/chunk-APSRPR4W.js +2 -0
  59. package/dist/cli/chunks/chunk-ATHWDAXB.js +3 -0
  60. package/dist/cli/chunks/{chunk-TSYQDRNK.js → chunk-B6LTH6YV.js} +2 -2
  61. package/dist/cli/chunks/chunk-BQUAE3CP.js +3 -0
  62. package/dist/cli/chunks/{chunk-OCESWNAZ.js → chunk-C522H7XR.js} +54 -33
  63. package/dist/cli/chunks/{chunk-TUYJ53V4.js → chunk-CESIR27V.js} +2 -2
  64. package/dist/cli/chunks/{chunk-PBZI2ZPV.js → chunk-CFBEBXLO.js} +3 -3
  65. package/dist/cli/chunks/{chunk-FJ4VTLLK.js → chunk-CMBLM26R.js} +2 -2
  66. package/dist/cli/chunks/{chunk-YZYDTABJ.js → chunk-CZ2IF6MC.js} +1 -1
  67. package/dist/cli/chunks/{chunk-GKPQ2GRR.js → chunk-CZGOSJQ4.js} +2 -2
  68. package/dist/cli/chunks/{chunk-FL3OYGCS.js → chunk-D6DA2KFD.js} +2 -2
  69. package/dist/cli/chunks/{chunk-37BIGMJI.js → chunk-DBMNJSBV.js} +1 -1
  70. package/dist/cli/chunks/{chunk-BHKXMIWX.js → chunk-DE4YJQJF.js} +2 -2
  71. package/dist/cli/chunks/{chunk-3CJCROMW.js → chunk-DEF34AFL.js} +2 -2
  72. package/dist/cli/chunks/chunk-DKAC3E3B.js +3 -0
  73. package/dist/cli/chunks/{chunk-AOFO4N32.js → chunk-DMFTELBS.js} +2 -2
  74. package/dist/cli/chunks/{chunk-KLGYIEJK.js → chunk-DNRWGATA.js} +10 -10
  75. package/dist/cli/chunks/{chunk-JWGRWMZP.js → chunk-DT7SIJOA.js} +2 -2
  76. package/dist/cli/chunks/{chunk-6PXA2BQJ.js → chunk-DURHK377.js} +67 -67
  77. package/dist/cli/chunks/{chunk-HAROIAJE.js → chunk-EAU5KDFO.js} +1 -1
  78. package/dist/cli/chunks/{chunk-L42JPFCC.js → chunk-EDLFX4ZB.js} +2 -2
  79. package/dist/cli/chunks/{chunk-6OOYIO3W.js → chunk-EN2QSKFF.js} +2 -2
  80. package/dist/cli/chunks/{chunk-UNUTC6TX.js → chunk-ERQKYIP7.js} +2 -2
  81. package/dist/cli/chunks/{chunk-KFUUIAR4.js → chunk-ESUO3GTJ.js} +2 -2
  82. package/dist/cli/chunks/{chunk-4V27J6YN.js → chunk-EWFECZ2U.js} +2 -2
  83. package/dist/cli/chunks/{chunk-4W4DYVSH.js → chunk-FAUCT5KR.js} +3 -3
  84. package/dist/cli/chunks/{chunk-IFEIY3NQ.js → chunk-FB6TI3BH.js} +2 -2
  85. package/dist/cli/chunks/{chunk-2TDIS6YK.js → chunk-FBXTQNRH.js} +2 -2
  86. package/dist/cli/chunks/{chunk-XOLDMK23.js → chunk-FESZBPUB.js} +2 -2
  87. package/dist/cli/chunks/chunk-FFTPAWM6.js +141 -0
  88. package/dist/cli/chunks/{chunk-A6YIH4C4.js → chunk-FKL3R5JQ.js} +2 -2
  89. package/dist/cli/chunks/{chunk-N5PDFGCQ.js → chunk-FPUDRSFJ.js} +2 -2
  90. package/dist/cli/chunks/{chunk-7QGYJ5OY.js → chunk-FZOWULMH.js} +1 -1
  91. package/dist/cli/chunks/{chunk-AVB5QY2Q.js → chunk-G3CZCUPM.js} +2 -2
  92. package/dist/cli/chunks/{chunk-FV3NHVC7.js → chunk-G5I6KGMW.js} +3 -3
  93. package/dist/cli/chunks/{chunk-N3KEY4XJ.js → chunk-GHBNRMSJ.js} +2 -2
  94. package/dist/cli/chunks/{chunk-2YH62JCN.js → chunk-GJHWY3ZX.js} +2 -2
  95. package/dist/cli/chunks/{chunk-ZXBCCO2H.js → chunk-GJMLK5UT.js} +2 -2
  96. package/dist/cli/chunks/{chunk-NHZIWIQZ.js → chunk-GRCIBCJ2.js} +2 -2
  97. package/dist/cli/chunks/{chunk-J3DTDJDT.js → chunk-GWZZ7DAO.js} +2 -2
  98. package/dist/cli/chunks/{chunk-4SUOVLJ6.js → chunk-GZLZCZ42.js} +2 -2
  99. package/dist/cli/chunks/{chunk-MZS32SYS.js → chunk-H2PYU7MN.js} +1 -1
  100. package/dist/cli/chunks/{chunk-ABFDB4X3.js → chunk-H32EPIR2.js} +1 -1
  101. package/dist/cli/chunks/{chunk-KIXYKUCI.js → chunk-H74Q7TJN.js} +1 -1
  102. package/dist/cli/chunks/chunk-HOZUDE4C.js +2 -0
  103. package/dist/cli/chunks/{chunk-PMCRCEW5.js → chunk-I33O4BRQ.js} +2 -2
  104. package/dist/cli/chunks/{chunk-N3NP6PTT.js → chunk-IKISCIGH.js} +2 -2
  105. package/dist/cli/chunks/{chunk-Q3JVJRVJ.js → chunk-IPJ7Q3AJ.js} +1 -1
  106. package/dist/cli/chunks/{chunk-WRRCQ2UE.js → chunk-IU2IV4NE.js} +1 -1
  107. package/dist/cli/chunks/{chunk-QQ5SZH4D.js → chunk-JHIY4VCC.js} +2 -2
  108. package/dist/cli/chunks/{chunk-W32YU3VI.js → chunk-KG336OV3.js} +2 -2
  109. package/dist/cli/chunks/{chunk-W5VJRDDG.js → chunk-KI73QCR5.js} +2 -2
  110. package/dist/cli/chunks/{chunk-HGTWAZWU.js → chunk-KNQ2ERFX.js} +2 -2
  111. package/dist/cli/chunks/{chunk-SNBYYO6F.js → chunk-KOBVYY6H.js} +2 -2
  112. package/dist/cli/chunks/{chunk-VQHVHVSF.js → chunk-KSIWGGJI.js} +8 -8
  113. package/dist/cli/chunks/{chunk-REUFWGMA.js → chunk-LMS3Y7JD.js} +2 -2
  114. package/dist/cli/chunks/{chunk-LMU5DUDK.js → chunk-LQEURY7C.js} +1 -1
  115. package/dist/cli/chunks/{chunk-AJ4YDSOI.js → chunk-LRZY4KS2.js} +2 -2
  116. package/dist/cli/chunks/{chunk-KIKWJM6J.js → chunk-M2QV7PT7.js} +2 -2
  117. package/dist/cli/chunks/{chunk-TNMQVG4A.js → chunk-MA7JIQ6U.js} +2 -2
  118. package/dist/cli/chunks/{chunk-I6S35FRO.js → chunk-MG27QY4D.js} +2 -2
  119. package/dist/cli/chunks/chunk-MNN5J4GU.js +12 -0
  120. package/dist/cli/chunks/chunk-N6PIIK6G.js +3 -0
  121. package/dist/cli/chunks/chunk-NAXGWDVM.js +12 -0
  122. package/dist/cli/chunks/{chunk-XOVNZT7F.js → chunk-NGKNYIQZ.js} +1 -1
  123. package/dist/cli/chunks/chunk-NNFZUTDH.js +2 -0
  124. package/dist/cli/chunks/{chunk-ZVSLCEVC.js → chunk-NPPHWFA2.js} +3 -3
  125. package/dist/cli/chunks/{chunk-JNNZK7KH.js → chunk-NSHU347M.js} +1 -1
  126. package/dist/cli/chunks/{chunk-PX2B5TS2.js → chunk-NVYIZCSR.js} +2 -2
  127. package/dist/cli/chunks/{chunk-5NS3USRW.js → chunk-NW5JUCCG.js} +1 -1
  128. package/dist/cli/chunks/{chunk-KR3M44CF.js → chunk-NZYLNXT6.js} +3 -3
  129. package/dist/cli/chunks/{chunk-5D2I7JUP.js → chunk-OBAREPDC.js} +2 -2
  130. package/dist/cli/chunks/{chunk-F4JYIRW2.js → chunk-ODJNUMV3.js} +2 -2
  131. package/dist/cli/chunks/{chunk-K5DJXMAA.js → chunk-OEKP73MC.js} +2 -2
  132. package/dist/cli/chunks/{chunk-2URBI52G.js → chunk-OPFGRS5S.js} +2 -2
  133. package/dist/cli/chunks/{chunk-HZ5NC6U5.js → chunk-OY2AHLSF.js} +1 -1
  134. package/dist/cli/chunks/{chunk-GII5WVAK.js → chunk-OY3NJNP2.js} +1 -1
  135. package/dist/cli/chunks/{chunk-P73W2K7T.js → chunk-PCEW6Q2C.js} +1 -1
  136. package/dist/cli/chunks/{chunk-7QTB5VJZ.js → chunk-PFG6VQ5Z.js} +2 -2
  137. package/dist/cli/chunks/{chunk-7KII4CQG.js → chunk-PGYMKGOE.js} +2 -2
  138. package/dist/cli/chunks/{chunk-BXO536GT.js → chunk-PPSAMXYN.js} +3 -3
  139. package/dist/cli/chunks/chunk-RK73HB2F.js +2 -0
  140. package/dist/cli/chunks/{chunk-ZBDRLF43.js → chunk-RPHY2DU6.js} +2 -2
  141. package/dist/cli/chunks/{chunk-XDBD4GXO.js → chunk-RWWOHCMG.js} +25 -20
  142. package/dist/cli/chunks/{chunk-J5KNRVXR.js → chunk-S75EYIJG.js} +1 -1
  143. package/dist/cli/chunks/{chunk-ETG7O5E5.js → chunk-SKQUUE4F.js} +5 -5
  144. package/dist/cli/chunks/chunk-SO45NA4D.js +180 -0
  145. package/dist/cli/chunks/{chunk-47V7FQGX.js → chunk-SU5H66SD.js} +2 -2
  146. package/dist/cli/chunks/{chunk-NTAD5UX4.js → chunk-SY2IB442.js} +2 -2
  147. package/dist/cli/chunks/{chunk-D6XVGFTI.js → chunk-TBLI254A.js} +2 -2
  148. package/dist/cli/chunks/{chunk-47TYABPD.js → chunk-TNMBRDCA.js} +3 -3
  149. package/dist/cli/chunks/{chunk-P2CXVNKK.js → chunk-TYFZXDGZ.js} +2 -2
  150. package/dist/cli/chunks/{chunk-2XITOPYV.js → chunk-U4OICXV2.js} +2 -2
  151. package/dist/cli/chunks/{chunk-JAV5WPSY.js → chunk-U53ZB4IX.js} +2 -2
  152. package/dist/cli/chunks/chunk-UARKIZAS.js +2 -0
  153. package/dist/cli/chunks/{chunk-2HL3UM5P.js → chunk-UCJMVXO4.js} +2 -2
  154. package/dist/cli/chunks/{chunk-HWK5L7IJ.js → chunk-UHTTW3IT.js} +2 -2
  155. package/dist/cli/chunks/{chunk-OXZLKP6C.js → chunk-V2M2XCR5.js} +1 -1
  156. package/dist/cli/chunks/{chunk-YZGSJG34.js → chunk-V2RSNVMW.js} +1 -1
  157. package/dist/cli/chunks/{chunk-5JWGCIQW.js → chunk-V6JBOIMX.js} +1 -1
  158. package/dist/cli/chunks/{chunk-JUVHZG7I.js → chunk-VFKF2XO7.js} +1 -1
  159. package/dist/cli/chunks/{chunk-XQ3DDY7X.js → chunk-VFSYMOAL.js} +2 -2
  160. package/dist/cli/chunks/{chunk-V5PXQSFS.js → chunk-VJQYDYAJ.js} +2 -2
  161. package/dist/cli/chunks/{chunk-A4RU67VX.js → chunk-VKRTTFB6.js} +2 -2
  162. package/dist/cli/chunks/{chunk-H3KBIWTO.js → chunk-VWNFAW2M.js} +2 -2
  163. package/dist/cli/chunks/{chunk-72AMFDC7.js → chunk-WBM6N6IM.js} +1 -1
  164. package/dist/cli/chunks/{chunk-XUIA5KMS.js → chunk-WDQ7IEZY.js} +2 -2
  165. package/dist/cli/chunks/{chunk-FLASM2XB.js → chunk-WDVRE6GN.js} +2 -2
  166. package/dist/cli/chunks/{chunk-FV7VAG74.js → chunk-WQ4PYWSW.js} +1 -1
  167. package/dist/cli/chunks/{chunk-DGTLJNJH.js → chunk-WSF24I3D.js} +2 -2
  168. package/dist/cli/chunks/{chunk-6YL6JOQB.js → chunk-XBVUVFJK.js} +2 -2
  169. package/dist/cli/chunks/{chunk-VRGCKBF7.js → chunk-XEB3NLJR.js} +2 -2
  170. package/dist/cli/chunks/{chunk-XYCKHYBM.js → chunk-XFVTGAAJ.js} +2 -2
  171. package/dist/cli/chunks/{chunk-2I2UPJS7.js → chunk-XLZYRTNO.js} +2 -2
  172. package/dist/cli/chunks/{chunk-AR2E4B7K.js → chunk-XUZDBQ5X.js} +5 -5
  173. package/dist/cli/chunks/{chunk-AQTVVLNP.js → chunk-Y76IAYQD.js} +1 -1
  174. package/dist/cli/chunks/{chunk-UOWHE77F.js → chunk-YAKGBHO4.js} +2 -2
  175. package/dist/cli/chunks/{chunk-JK2ME6IT.js → chunk-YBSBABOS.js} +2 -2
  176. package/dist/cli/chunks/{chunk-NDKLQW6N.js → chunk-YCGP5VFP.js} +2 -2
  177. package/dist/cli/chunks/{chunk-GBUIG3FS.js → chunk-YDAQK5UF.js} +1 -1
  178. package/dist/cli/chunks/{chunk-HTZJSQ3C.js → chunk-YK3BVZY6.js} +2 -2
  179. package/dist/cli/chunks/{chunk-GCWSX2NY.js → chunk-YK7JN5N7.js} +4 -4
  180. package/dist/cli/chunks/{chunk-C6RTMTEH.js → chunk-YKMU4LBV.js} +1 -1
  181. package/dist/cli/chunks/{chunk-JP4P3P3D.js → chunk-YYTGXD3R.js} +2 -2
  182. package/dist/cli/chunks/{chunk-763SUL4B.js → chunk-Z2O2YJAF.js} +2 -2
  183. package/dist/cli/chunks/{chunk-QTVWUQTB.js → chunk-Z7IYW5U7.js} +1 -1
  184. package/dist/cli/chunks/{chunk-XZJ2O3VC.js → chunk-ZG5666GJ.js} +1 -1
  185. package/dist/cli/chunks/{chunk-6EPHNJTL.js → chunk-ZXPY654C.js} +1 -1
  186. package/dist/cli/chunks/{ci-7SGRCFPS.js → ci-MSKMVH5X.js} +2 -2
  187. package/dist/cli/chunks/{ci-config-MX3URPZA.js → ci-config-7ODMNAUM.js} +2 -2
  188. package/dist/cli/chunks/{ci-output-M47NJY6D.js → ci-output-FXZ7ZZW3.js} +2 -2
  189. package/dist/cli/chunks/{circuit-breaker-5GAK45SW.js → circuit-breaker-4VOUEPOX.js} +2 -2
  190. package/dist/cli/chunks/{claude-flow-setup-YXYSRH4Y.js → claude-flow-setup-7D4SGLM4.js} +2 -2
  191. package/dist/cli/chunks/client-POSVREVS.js +2 -0
  192. package/dist/cli/chunks/{cline-installer-DLJ5QD5N.js → cline-installer-WRRT7BGQ.js} +2 -2
  193. package/dist/cli/chunks/{code-ONKLMVQ2.js → code-ZDJRIL3S.js} +3 -3
  194. package/dist/cli/chunks/{code-index-extractor-2232LGZN.js → code-index-extractor-4S4SHM56.js} +2 -2
  195. package/dist/cli/chunks/{codex-installer-UOWLYCMH.js → codex-installer-YTRHNDWR.js} +2 -2
  196. package/dist/cli/chunks/{completions-MHX7GCC7.js → completions-6N64JUXJ.js} +2 -2
  197. package/dist/cli/chunks/{complexity-analyzer-43ZUJKZU.js → complexity-analyzer-I4A26VCJ.js} +2 -2
  198. package/dist/cli/chunks/{continuedev-installer-6Q5JR4FF.js → continuedev-installer-IIDR66LB.js} +2 -2
  199. package/dist/cli/chunks/{copilot-installer-CZUMVHSI.js → copilot-installer-SVVFY3S2.js} +2 -2
  200. package/dist/cli/chunks/core-handlers-V243GY7X.js +2 -0
  201. package/dist/cli/chunks/{cost-tracker-VS5ZW3XN.js → cost-tracker-VGFS6IBX.js} +2 -2
  202. package/dist/cli/chunks/{coverage-VWKTWZ6D.js → coverage-B7MCGNTE.js} +3 -3
  203. package/dist/cli/chunks/cross-domain-router-N3AIEM3B.js +2 -0
  204. package/dist/cli/chunks/{cursor-installer-YIFEMORH.js → cursor-installer-UPETT57E.js} +2 -2
  205. package/dist/cli/chunks/daemon-7BDJHEIJ.js +18 -0
  206. package/dist/cli/chunks/{daemon-SHWJSJW5.js → daemon-CQFNZLXU.js} +3 -3
  207. package/dist/cli/chunks/{dag-attention-scheduler-TCC2WM46.js → dag-attention-scheduler-PJVABHON.js} +2 -2
  208. package/dist/cli/chunks/{detect-IGTWSQMA.js → detect-56SKAGWX.js} +2 -2
  209. package/dist/cli/chunks/{dist-node-TCOTJVQX.js → dist-node-UYTYUMLN.js} +2 -2
  210. package/dist/cli/chunks/{domain-handler-55ZVYODR.js → domain-handler-YOYLBYJE.js} +2 -2
  211. package/dist/cli/chunks/{domain-plugins-GJRWOHQP.js → domain-plugins-7TARX2XF.js} +2 -2
  212. package/dist/cli/chunks/domain-transfer-AKVSBD6E.js +2 -0
  213. package/dist/cli/chunks/dream-UA7MKOPQ.js +2 -0
  214. package/dist/cli/chunks/{embed-and-insert-pattern-XAMNIKQL.js → embed-and-insert-pattern-IS6HSR66.js} +2 -2
  215. package/dist/cli/chunks/{eval-GO22R4OZ.js → eval-GNB574IM.js} +2 -2
  216. package/dist/cli/chunks/{experience-capture-middleware-F2BRMJ3Y.js → experience-capture-middleware-RCAOCKM7.js} +3 -3
  217. package/dist/cli/chunks/{fast-paths-6RGPYALD.js → fast-paths-KTZ5SF54.js} +2 -2
  218. package/dist/cli/chunks/{feature-flags-ZGS3KLPH.js → feature-flags-ITX5LQ57.js} +2 -2
  219. package/dist/cli/chunks/{feature-flags-MIWQIOHU.js → feature-flags-KFHSR5YF.js} +2 -2
  220. package/dist/cli/chunks/file-discovery-YCMNKZAK.js +2 -0
  221. package/dist/cli/chunks/fleet-2Y3ZE6CE.js +46 -0
  222. package/dist/cli/chunks/{gnn-wrapper-ALBJVW6T.js → gnn-wrapper-RLFW3GSX.js} +2 -2
  223. package/dist/cli/chunks/{heartbeat-handler-ZMM53NDY.js → heartbeat-handler-EM2URCYZ.js} +4 -4
  224. package/dist/cli/chunks/heartbeat-scheduler-QH5V6G2P.js +2 -0
  225. package/dist/cli/chunks/hnsw-adapter-OJNFAGJS.js +2 -0
  226. package/dist/cli/chunks/hnsw-index-DFUNARVD.js +2 -0
  227. package/dist/cli/chunks/{hnsw-legacy-bridge-RYUJPA7B.js → hnsw-legacy-bridge-JMHEOIBH.js} +2 -2
  228. package/dist/cli/chunks/{hnswlib-node-XM6XF3YV.js → hnswlib-node-CBP73QHY.js} +2 -2
  229. package/dist/cli/chunks/{hooks-X62O7TJO.js → hooks-IP7XE34Z.js} +34 -34
  230. package/dist/cli/chunks/hybrid-backend-SSGQQEQ2.js +2 -0
  231. package/dist/cli/chunks/{hypergraph-engine-ZBWUPTVD.js → hypergraph-engine-ONAYHU25.js} +2 -2
  232. package/dist/cli/chunks/{hypergraph-handler-DUMF6SJV.js → hypergraph-handler-VINJRAID.js} +3 -3
  233. package/dist/cli/chunks/impact-analyzer-CRGCA7ZD.js +2 -0
  234. package/dist/cli/chunks/{init-guard-S4I2R46S.js → init-guard-RYVV5R3Z.js} +2 -2
  235. package/dist/cli/chunks/{init-handler-L4KJHVWS.js → init-handler-MPRGWMOE.js} +6 -6
  236. package/dist/cli/chunks/init-wizard-NIMZ4J55.js +2 -0
  237. package/dist/cli/chunks/kernel-JQK7PRAI.js +2 -0
  238. package/dist/cli/chunks/{kilocode-installer-GNNB5FCZ.js → kilocode-installer-OPD7JBRL.js} +2 -2
  239. package/dist/cli/chunks/{kiro-installer-HR6ZAH7T.js → kiro-installer-M4OPUNK2.js} +2 -2
  240. package/dist/cli/chunks/knowledge-graph-YPVVIKEU.js +2 -0
  241. package/dist/cli/chunks/{learning-4IEEOHJS.js → learning-4UWTQLMF.js} +24 -24
  242. package/dist/cli/chunks/{llm-router-ZFMORP36.js → llm-router-SQ56FF6Z.js} +4 -4
  243. package/dist/cli/chunks/llm-router-service-5OGAUOXF.js +2 -0
  244. package/dist/cli/chunks/{load-ZM43WGDO.js → load-HPHKDGGL.js} +2 -2
  245. package/dist/cli/chunks/load-test-UKNV5MWW.js +2 -0
  246. package/dist/cli/chunks/mcp-TELMAC7Z.js +2 -0
  247. package/dist/cli/chunks/{memory-W5FZGVAD.js → memory-PFQ3KPVJ.js} +5 -5
  248. package/dist/cli/chunks/memory-backend-ZW4BTRNK.js +2 -0
  249. package/dist/cli/chunks/memory-handlers-FCXN437E.js +2 -0
  250. package/dist/cli/chunks/{multi-model-executor-SXXGAQ2G.js → multi-model-executor-3VDRX6TZ.js} +2 -2
  251. package/dist/cli/chunks/{opencode-installer-PIRBUAB5.js → opencode-installer-PJ576R63.js} +2 -2
  252. package/dist/cli/chunks/{orchestrator-H5SQCQTB.js → orchestrator-72QP4UU7.js} +63 -19
  253. package/dist/cli/chunks/pattern-null-store-4DUV6MQC.js +2 -0
  254. package/dist/cli/chunks/{pattern-usage-recorder-XZTWDI2T.js → pattern-usage-recorder-754YQW7C.js} +2 -2
  255. package/dist/cli/chunks/pipeline-AVXY4MVB.js +19 -0
  256. package/dist/cli/chunks/{platform-KJDABL5C.js → platform-3E3DXLYB.js} +2 -2
  257. package/dist/cli/chunks/{plugin-V4KSBVVM.js → plugin-7FUQAKRE.js} +2 -2
  258. package/dist/cli/chunks/{prime-radiant-advanced-wasm-JDHTKQAT.js → prime-radiant-advanced-wasm-NIB4F5NV.js} +2 -2
  259. package/dist/cli/chunks/project-root-JCAUNL6O.js +2 -0
  260. package/dist/cli/chunks/protocol-executor-RNZNZP3A.js +2 -0
  261. package/dist/cli/chunks/{protocol-handler-BNRONTQV.js → protocol-handler-BQRYMUTG.js} +2 -2
  262. package/dist/cli/chunks/{prove-ELLL6XMX.js → prove-H52QGC6B.js} +2 -2
  263. package/dist/cli/chunks/qe-reasoning-bank-WK6TQOG2.js +2 -0
  264. package/dist/cli/chunks/{quality-NH2QA4D4.js → quality-QO4XPAUM.js} +2 -2
  265. package/dist/cli/chunks/{quality-gate-JTKLF7GW.js → quality-gate-FBKE5E6F.js} +3 -3
  266. package/dist/cli/chunks/queen-coordinator-4452SXZQ.js +2 -0
  267. package/dist/cli/chunks/{real-embeddings-J3KCKLPB.js → real-embeddings-RWGOVOXO.js} +2 -2
  268. package/dist/cli/chunks/{ref-validation-HNXQRP4F.js → ref-validation-LF76ZOBD.js} +2 -2
  269. package/dist/cli/chunks/{roocode-installer-COJ6CX6S.js → roocode-installer-3BYEBTQ7.js} +2 -2
  270. package/dist/cli/chunks/router-3DIS5X4R.js +2 -0
  271. package/dist/cli/chunks/routing-feedback-OPXRCXM7.js +2 -0
  272. package/dist/cli/chunks/{routing-handler-WM33ZILE.js → routing-handler-DST7BVCU.js} +2 -2
  273. package/dist/cli/chunks/{ruvector-commands-BBLXEA7A.js → ruvector-commands-XE32PGKC.js} +2 -2
  274. package/dist/cli/chunks/rvf-dual-writer-JL6T727I.js +2 -0
  275. package/dist/cli/chunks/rvf-migration-adapter-V7IBDUCS.js +2 -0
  276. package/dist/cli/chunks/{rvf-migration-coordinator-P7H6HCAG.js → rvf-migration-coordinator-VP32XC75.js} +2 -2
  277. package/dist/cli/chunks/rvf-native-adapter-O3UQTEBK.js +2 -0
  278. package/dist/cli/chunks/{rvf-store-integrity-R5SPVRFP.js → rvf-store-integrity-SH2AMVI7.js} +2 -2
  279. package/dist/cli/chunks/safe-db-EVB4ZC7T.js +2 -0
  280. package/dist/cli/chunks/schedule-ORDDXXY4.js +2 -0
  281. package/dist/cli/chunks/scheduler-XFLJSFIU.js +2 -0
  282. package/dist/cli/chunks/{security-AUDTRX3I.js → security-VSPNKCDS.js} +3 -3
  283. package/dist/cli/chunks/{shared-rvf-adapter-PVDGBGI2.js → shared-rvf-adapter-HX6AHL3P.js} +2 -2
  284. package/dist/cli/chunks/{shared-rvf-dual-writer-LZ2GMSS2.js → shared-rvf-dual-writer-MX4FC2JE.js} +2 -2
  285. package/dist/cli/chunks/sqlite-persistence-Y7B42CJ3.js +2 -0
  286. package/dist/cli/chunks/{standalone-memory-XNOAI4G4.js → standalone-memory-O4QUTK6L.js} +2 -2
  287. package/dist/cli/chunks/{status-handler-K72XZE4T.js → status-handler-Z2BP6EOG.js} +2 -2
  288. package/dist/cli/chunks/{structural-health-NF3YY7U5.js → structural-health-R36WNLQG.js} +2 -2
  289. package/dist/cli/chunks/sync-2ELWUFQU.js +2 -0
  290. package/dist/cli/chunks/{sync-VBD5Y3E2.js → sync-QF5Y3EMZ.js} +2 -2
  291. package/dist/cli/chunks/{task-handler-24S3WFVJ.js → task-handler-43PYE75J.js} +2 -2
  292. package/dist/cli/chunks/task-handlers-KPWAEMKH.js +9 -0
  293. package/dist/cli/chunks/{test-XFSGQELD.js → test-UWA377D4.js} +16 -16
  294. package/dist/cli/chunks/test-runner-process-3XZUYST2.js +2 -0
  295. package/dist/cli/chunks/{test-scheduling-VYUQ4CDE.js → test-scheduling-YQZPJRRN.js} +3 -3
  296. package/dist/cli/chunks/token-bootstrap-F7C6UKTC.js +2 -0
  297. package/dist/cli/chunks/{token-usage-VLQ6WO2L.js → token-usage-DO6WLMXP.js} +2 -2
  298. package/dist/cli/chunks/{transformers-TOFMWWNM.js → transformers-H5RGFKVO.js} +2 -2
  299. package/dist/cli/chunks/tree-sitter-wasm-parser-YTBCBHUO.js +2 -0
  300. package/dist/cli/chunks/{types-JTWLBAZJ.js → types-PJS2FGPF.js} +2 -2
  301. package/dist/cli/chunks/unified-memory-EHD4VNFW.js +2 -0
  302. package/dist/cli/chunks/unified-memory-hnsw-ZODGM4UK.js +2 -0
  303. package/dist/cli/chunks/unified-persistence-MHSI7ABK.js +2 -0
  304. package/dist/cli/chunks/{upgrade-4ABM72T4.js → upgrade-4IC4F6AB.js} +2 -2
  305. package/dist/cli/chunks/{validate-UDJCWKXI.js → validate-DHUWW7PF.js} +2 -2
  306. package/dist/cli/chunks/{validate-swarm-TODOUWNN.js → validate-swarm-OERQNOX5.js} +2 -2
  307. package/dist/cli/chunks/visual-security-54MLFKWY.js +2 -0
  308. package/dist/cli/chunks/{web-tree-sitter-WBMAJPM5.js → web-tree-sitter-TV7DMKES.js} +2 -2
  309. package/dist/cli/chunks/{windsurf-installer-BTT53TUL.js → windsurf-installer-QZPWSH37.js} +2 -2
  310. package/dist/cli/chunks/witness-chain-LC6Q2W27.js +2 -0
  311. package/dist/cli/chunks/witness-chain-QUIBAF3W.js +2 -0
  312. package/dist/cli/chunks/witness-chain-repair-RUXIOE7F.js +2 -0
  313. package/dist/cli/chunks/{witness-chain-verifier-FRY3LMGH.js → witness-chain-verifier-YXENHB42.js} +2 -2
  314. package/dist/cli/chunks/{witness-key-manager-X7QHQQWL.js → witness-key-manager-HL26AGFO.js} +2 -2
  315. package/dist/cli/chunks/{workflow-QMZPAWQW.js → workflow-EOVVCN2E.js} +4 -4
  316. package/dist/cli/chunks/workflow-orchestrator-UKHEJVSK.js +2 -0
  317. package/dist/cli/chunks/wrappers-AGODHBOO.js +2 -0
  318. package/dist/cli/commands/fleet.js +19 -12
  319. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +9 -2
  320. package/dist/cli/commands/hooks-handlers/session-hooks.js +2 -2
  321. package/dist/cli/commands/hooks-handlers/stats-hooks.js +3 -2
  322. package/dist/cli/commands/learning.js +5 -3
  323. package/dist/cli/commands/ruvector-commands.js +2 -1
  324. package/dist/cli/commands/test.js +6 -0
  325. package/dist/cli/utils/ci-output.d.ts +9 -0
  326. package/dist/cli/utils/fleet-operation.d.ts +32 -0
  327. package/dist/cli/utils/fleet-operation.js +71 -0
  328. package/dist/cli/utils/fleet-result.d.ts +31 -0
  329. package/dist/cli/utils/fleet-result.js +124 -0
  330. package/dist/context/sources/git-source.js +6 -2
  331. package/dist/coordination/handlers/code-intelligence-handlers.js +60 -5
  332. package/dist/coordination/handlers/coverage-handlers.js +10 -1
  333. package/dist/coordination/handlers/requirements-handlers.js +16 -2
  334. package/dist/coordination/handlers/security-handlers.js +11 -1
  335. package/dist/coordination/handlers/test-execution-handlers.js +25 -7
  336. package/dist/coordination/mincut/queen-integration.d.ts +39 -1
  337. package/dist/coordination/mincut/queen-integration.js +83 -6
  338. package/dist/coordination/protocols/learning-consolidation-archive.d.ts +2 -6
  339. package/dist/coordination/protocols/learning-consolidation-archive.js +4 -27
  340. package/dist/coordination/protocols/learning-consolidation.d.ts +24 -0
  341. package/dist/coordination/protocols/learning-consolidation.js +71 -22
  342. package/dist/coordination/queen-coordinator.d.ts +1 -1
  343. package/dist/coordination/queen-coordinator.js +19 -7
  344. package/dist/coordination/queen-event-handlers.js +13 -0
  345. package/dist/coordination/queen-task-management.d.ts +18 -24
  346. package/dist/coordination/queen-task-management.js +62 -168
  347. package/dist/coordination/queen-task-queue.d.ts +41 -0
  348. package/dist/coordination/queen-task-queue.js +194 -0
  349. package/dist/coordination/queen-types.d.ts +1 -1
  350. package/dist/coordination/queen-work-stealing.d.ts +6 -1
  351. package/dist/coordination/queen-work-stealing.js +7 -4
  352. package/dist/coordination/result-saver-adapters.d.ts +15 -0
  353. package/dist/coordination/result-saver-adapters.js +57 -0
  354. package/dist/coordination/result-saver.d.ts +1 -1
  355. package/dist/coordination/result-saver.js +8 -5
  356. package/dist/coordination/yaml-pipeline-loader.js +5 -2
  357. package/dist/domains/code-intelligence/index-path-guard.d.ts +5 -2
  358. package/dist/domains/code-intelligence/index-path-guard.js +20 -50
  359. package/dist/domains/code-intelligence/plugin.js +5 -1
  360. package/dist/domains/code-intelligence/services/metric-collector/index.d.ts +2 -2
  361. package/dist/domains/code-intelligence/services/metric-collector/index.js +2 -3
  362. package/dist/domains/code-intelligence/services/metric-collector/loc-counter.d.ts +1 -1
  363. package/dist/domains/code-intelligence/services/metric-collector/loc-counter.js +11 -36
  364. package/dist/domains/code-intelligence/services/metric-collector/test-counter.d.ts +1 -1
  365. package/dist/domains/code-intelligence/services/metric-collector/test-counter.js +45 -103
  366. package/dist/domains/contract-testing/services/api-compatibility.js +7 -6
  367. package/dist/domains/contract-testing/services/contract-validator.js +6 -4
  368. package/dist/domains/contract-testing/services/schema-validator.js +8 -5
  369. package/dist/domains/defect-intelligence/interfaces.d.ts +2 -0
  370. package/dist/domains/defect-intelligence/plugin.js +11 -2
  371. package/dist/domains/defect-intelligence/prediction-history.d.ts +27 -0
  372. package/dist/domains/defect-intelligence/prediction-history.js +68 -0
  373. package/dist/domains/defect-intelligence/services/defect-predictor.js +25 -10
  374. package/dist/domains/enterprise-integration/services/message-broker-service.js +3 -2
  375. package/dist/domains/enterprise-integration/services/odata-service.js +2 -1
  376. package/dist/domains/enterprise-integration/services/sap-integration-service.js +3 -2
  377. package/dist/domains/learning-optimization/active-patterns.d.ts +2 -2
  378. package/dist/domains/learning-optimization/active-patterns.js +2 -2
  379. package/dist/domains/learning-optimization/coordinator.js +9 -5
  380. package/dist/domains/learning-optimization/interfaces.d.ts +6 -2
  381. package/dist/domains/learning-optimization/pattern-archive.d.ts +31 -0
  382. package/dist/domains/learning-optimization/pattern-archive.js +56 -0
  383. package/dist/domains/learning-optimization/pattern-consolidation.d.ts +12 -0
  384. package/dist/domains/learning-optimization/pattern-consolidation.js +41 -0
  385. package/dist/domains/learning-optimization/reward-source.d.ts +13 -0
  386. package/dist/domains/learning-optimization/reward-source.js +8 -1
  387. package/dist/domains/learning-optimization/services/learning-coordinator.d.ts +5 -3
  388. package/dist/domains/learning-optimization/services/learning-coordinator.js +45 -58
  389. package/dist/domains/security-compliance/plugin.js +17 -3
  390. package/dist/domains/security-compliance/sast-path-guard.d.ts +9 -0
  391. package/dist/domains/security-compliance/sast-path-guard.js +17 -0
  392. package/dist/domains/security-compliance/services/scanners/dast-auth-testing.js +46 -56
  393. package/dist/domains/security-compliance/services/scanners/dast-helpers.js +76 -91
  394. package/dist/domains/security-compliance/services/scanners/dast-injection-testing.js +52 -62
  395. package/dist/domains/security-compliance/services/scanners/dast-scanner.d.ts +21 -1
  396. package/dist/domains/security-compliance/services/scanners/dast-scanner.js +29 -24
  397. package/dist/domains/security-compliance/services/scanners/scanner-orchestrator.js +4 -1
  398. package/dist/domains/test-execution/coordinator.d.ts +5 -0
  399. package/dist/domains/test-execution/coordinator.js +35 -20
  400. package/dist/domains/test-execution/interfaces.d.ts +25 -0
  401. package/dist/domains/test-execution/plugin.js +19 -4
  402. package/dist/domains/test-execution/services/flaky-detector.js +9 -7
  403. package/dist/domains/test-execution/services/retry-handler.js +46 -7
  404. package/dist/domains/test-execution/services/runner-test-cases.d.ts +11 -0
  405. package/dist/domains/test-execution/services/runner-test-cases.js +20 -2
  406. package/dist/domains/test-execution/services/test-executor.js +8 -8
  407. package/dist/domains/test-generation/plugin.js +7 -2
  408. package/dist/domains/test-generation/services/test-data-generator.js +3 -1
  409. package/dist/domains/visual-accessibility/services/axe-core-audit.js +1 -1
  410. package/dist/hooks/cross-phase-hooks.js +2 -1
  411. package/dist/init/phases/10-workers.js +50 -6
  412. package/dist/integrations/browser/agent-browser/client.js +37 -52
  413. package/dist/integrations/browser/agent-browser/command-executor.d.ts +33 -27
  414. package/dist/integrations/browser/agent-browser/command-executor.js +53 -54
  415. package/dist/integrations/browser/agent-browser/session-manager.d.ts +1 -1
  416. package/dist/integrations/browser/agent-browser/session-manager.js +8 -9
  417. package/dist/integrations/browser/web-content-fetcher.js +9 -3
  418. package/dist/integrations/vibium/client.js +2 -2
  419. package/dist/integrations/vibium/runtime.d.ts +1 -1
  420. package/dist/integrations/vibium/runtime.js +14 -11
  421. package/dist/kernel/unified-memory-schemas.d.ts +3 -2
  422. package/dist/kernel/unified-memory-schemas.js +3 -2
  423. package/dist/kernel/unified-memory.js +25 -6
  424. package/dist/learning/dream/dream-commit.d.ts +65 -0
  425. package/dist/learning/dream/dream-commit.js +104 -0
  426. package/dist/learning/dream/dream-engine.d.ts +81 -31
  427. package/dist/learning/dream/dream-engine.js +225 -168
  428. package/dist/learning/dream/dream-insights-pruner.d.ts +9 -3
  429. package/dist/learning/dream/dream-insights-pruner.js +16 -30
  430. package/dist/learning/dream/index.d.ts +3 -2
  431. package/dist/learning/dream/index.js +3 -1
  432. package/dist/learning/dream/rvcow-branch-manager.d.ts +8 -1
  433. package/dist/learning/dream/rvcow-branch-manager.js +8 -1
  434. package/dist/learning/dream/speculative-dreamer.d.ts +50 -74
  435. package/dist/learning/dream/speculative-dreamer.js +64 -111
  436. package/dist/learning/dream/spreading-activation.d.ts +2 -1
  437. package/dist/learning/dream/spreading-activation.js +15 -6
  438. package/dist/learning/experience-capture.d.ts +9 -0
  439. package/dist/learning/experience-capture.js +18 -4
  440. package/dist/learning/qe-reasoning-bank-types.d.ts +17 -2
  441. package/dist/learning/qe-reasoning-bank.js +22 -11
  442. package/dist/learning/sqlite-persistence.d.ts +6 -0
  443. package/dist/learning/sqlite-persistence.js +16 -2
  444. package/dist/learning/usage-outcome.d.ts +68 -0
  445. package/dist/learning/usage-outcome.js +84 -0
  446. package/dist/mcp/background-workers.d.ts +13 -1
  447. package/dist/mcp/background-workers.js +17 -3
  448. package/dist/mcp/bundle.js +607 -580
  449. package/dist/mcp/handlers/core-handlers.js +11 -0
  450. package/dist/mcp/handlers/domain-handler-configs.d.ts +5 -0
  451. package/dist/mcp/handlers/domain-handler-configs.js +11 -3
  452. package/dist/mcp/handlers/handler-factory.d.ts +2 -1
  453. package/dist/mcp/handlers/handler-factory.js +36 -15
  454. package/dist/mcp/handlers/orchestrate-routes.d.ts +36 -0
  455. package/dist/mcp/handlers/orchestrate-routes.js +88 -0
  456. package/dist/mcp/handlers/task-handlers.d.ts +3 -0
  457. package/dist/mcp/handlers/task-handlers.js +35 -8
  458. package/dist/mcp/handlers/validation-pipeline-handler.js +6 -2
  459. package/dist/mcp/protocol-server.js +2 -0
  460. package/dist/mcp/security/schema-validator.js +3 -2
  461. package/dist/mcp/tools/code-intelligence/c4.js +11 -1
  462. package/dist/mcp/tools/coverage-analysis/index.js +31 -2
  463. package/dist/mcp/tools/learning-optimization/dream.d.ts +8 -8
  464. package/dist/mcp/tools/learning-optimization/dream.js +38 -34
  465. package/dist/mcp/tools/learning-optimization/optimize.d.ts +18 -2
  466. package/dist/mcp/tools/learning-optimization/optimize.js +58 -10
  467. package/dist/mcp/tools/quality-assessment/gate.js +12 -1
  468. package/dist/mcp/tools/requirements-validation/quality-criteria.js +9 -2
  469. package/dist/migration/agent-compat.js +7 -5
  470. package/dist/migrations/20261018_add_dream_insights_archive.d.ts +27 -0
  471. package/dist/migrations/20261018_add_dream_insights_archive.js +57 -0
  472. package/dist/shared/git/git-analyzer.d.ts +49 -0
  473. package/dist/shared/git/git-analyzer.js +159 -319
  474. package/dist/shared/git/git-process.d.ts +22 -0
  475. package/dist/shared/git/git-process.js +37 -0
  476. package/dist/shared/git/index.d.ts +1 -0
  477. package/dist/shared/git/index.js +1 -0
  478. package/dist/shared/io/payload-path-guard.d.ts +75 -0
  479. package/dist/shared/io/payload-path-guard.js +190 -0
  480. package/dist/shared/llm/router/agent-router-config.js +2 -1
  481. package/dist/shared/llm/translation/tool-translator.js +2 -1
  482. package/dist/shared/test-runner-args.d.ts +5 -0
  483. package/dist/shared/test-runner-args.js +6 -1
  484. package/dist/shared/test-runner-process.d.ts +6 -0
  485. package/dist/shared/test-runner-process.js +14 -0
  486. package/dist/shared/test-runner-verdict.d.ts +9 -1
  487. package/dist/shared/test-runner-verdict.js +15 -4
  488. package/dist/shared/utils/namespaced-search.d.ts +14 -0
  489. package/dist/shared/utils/namespaced-search.js +19 -1
  490. package/dist/shared/utils/safe-expression-evaluator.js +4 -3
  491. package/dist/strange-loop/infra-healing/recovery-playbook.js +13 -3
  492. package/dist/validation/gate-reexecute.js +7 -4
  493. package/dist/workers/daemon.js +13 -1
  494. package/dist/workers/quality-daemon/git-watcher.js +9 -9
  495. package/dist/workers/workers/defect-predictor.d.ts +8 -3
  496. package/dist/workers/workers/defect-predictor.js +48 -49
  497. package/dist/workers/workers/learning-consolidation.d.ts +2 -0
  498. package/dist/workers/workers/learning-consolidation.js +12 -1
  499. package/dist/workflows/browser/workflow-loader.js +8 -5
  500. package/package.json +1 -1
  501. package/dist/cli/chunks/adapter-R2Q4QGXQ.js +0 -2
  502. package/dist/cli/chunks/agent-booster-wasm-427FRKWG.js +0 -2
  503. package/dist/cli/chunks/aqe-learning-engine-3RENLQWP.js +0 -2
  504. package/dist/cli/chunks/base-67DXSAYM.js +0 -2
  505. package/dist/cli/chunks/browser-CT3MTV6G.js +0 -4
  506. package/dist/cli/chunks/browser-workflow-NDXRROWZ.js +0 -2
  507. package/dist/cli/chunks/chunk-4URT6JO2.js +0 -2
  508. package/dist/cli/chunks/chunk-5LAAZLUC.js +0 -4
  509. package/dist/cli/chunks/chunk-7DMA5NYL.js +0 -4
  510. package/dist/cli/chunks/chunk-F2SQPP6U.js +0 -4
  511. package/dist/cli/chunks/chunk-G3BKZNFL.js +0 -120
  512. package/dist/cli/chunks/chunk-GR3JYE5A.js +0 -2
  513. package/dist/cli/chunks/chunk-J3WGK22W.js +0 -2
  514. package/dist/cli/chunks/chunk-KHSRIPBP.js +0 -180
  515. package/dist/cli/chunks/chunk-KTSLTZSG.js +0 -2
  516. package/dist/cli/chunks/chunk-O3JLOVZX.js +0 -4
  517. package/dist/cli/chunks/chunk-THAY7WHO.js +0 -12
  518. package/dist/cli/chunks/chunk-VXZJOKOX.js +0 -2
  519. package/dist/cli/chunks/chunk-VYLM2YV5.js +0 -12
  520. package/dist/cli/chunks/client-ZP3CTVRF.js +0 -2
  521. package/dist/cli/chunks/core-handlers-JSRXQWPE.js +0 -2
  522. package/dist/cli/chunks/cross-domain-router-7UKODQWG.js +0 -2
  523. package/dist/cli/chunks/daemon-YIFT46FH.js +0 -34
  524. package/dist/cli/chunks/domain-transfer-6EF75EKU.js +0 -2
  525. package/dist/cli/chunks/dream-UDLM6M55.js +0 -2
  526. package/dist/cli/chunks/file-discovery-THWOUQ7Z.js +0 -2
  527. package/dist/cli/chunks/fleet-ADL57COA.js +0 -44
  528. package/dist/cli/chunks/heartbeat-scheduler-HGOC5KH3.js +0 -2
  529. package/dist/cli/chunks/hnsw-adapter-EPSA6AP7.js +0 -2
  530. package/dist/cli/chunks/hnsw-index-RMFOPYGY.js +0 -2
  531. package/dist/cli/chunks/hybrid-backend-NZ3G4WBX.js +0 -2
  532. package/dist/cli/chunks/impact-analyzer-WZC6NHFP.js +0 -2
  533. package/dist/cli/chunks/init-wizard-422UZYQ5.js +0 -2
  534. package/dist/cli/chunks/kernel-N7PJ6FCE.js +0 -2
  535. package/dist/cli/chunks/knowledge-graph-SZCVQF37.js +0 -2
  536. package/dist/cli/chunks/llm-router-service-4DE5WDUZ.js +0 -2
  537. package/dist/cli/chunks/load-test-POMIF4Q4.js +0 -2
  538. package/dist/cli/chunks/mcp-CRZKZE37.js +0 -2
  539. package/dist/cli/chunks/memory-backend-4P6AHSOY.js +0 -2
  540. package/dist/cli/chunks/memory-handlers-NK6NV3GE.js +0 -2
  541. package/dist/cli/chunks/pattern-null-store-CCHQHGQG.js +0 -2
  542. package/dist/cli/chunks/pipeline-5LMLBIJ7.js +0 -19
  543. package/dist/cli/chunks/project-root-X72FSM2F.js +0 -2
  544. package/dist/cli/chunks/protocol-executor-QW6XN6QN.js +0 -2
  545. package/dist/cli/chunks/qe-reasoning-bank-ZD3WF647.js +0 -2
  546. package/dist/cli/chunks/queen-coordinator-S4U4MKK2.js +0 -2
  547. package/dist/cli/chunks/router-CXZKOOTR.js +0 -2
  548. package/dist/cli/chunks/routing-feedback-IYFANYY5.js +0 -2
  549. package/dist/cli/chunks/rvf-dual-writer-HCLQ5WUQ.js +0 -2
  550. package/dist/cli/chunks/rvf-migration-adapter-XCLUWOO3.js +0 -2
  551. package/dist/cli/chunks/rvf-native-adapter-MRT5H3IP.js +0 -2
  552. package/dist/cli/chunks/safe-db-WFODRGVZ.js +0 -2
  553. package/dist/cli/chunks/schedule-RO55OQXG.js +0 -2
  554. package/dist/cli/chunks/scheduler-XXMJCH24.js +0 -2
  555. package/dist/cli/chunks/sqlite-persistence-AWRIS4MK.js +0 -2
  556. package/dist/cli/chunks/sync-UVXA6CT2.js +0 -2
  557. package/dist/cli/chunks/task-handlers-GUYW2EPJ.js +0 -9
  558. package/dist/cli/chunks/token-bootstrap-EDK6FNQ3.js +0 -2
  559. package/dist/cli/chunks/tree-sitter-wasm-parser-MI3NZKUD.js +0 -2
  560. package/dist/cli/chunks/unified-memory-6JWHV6EF.js +0 -2
  561. package/dist/cli/chunks/unified-memory-hnsw-4UANU6NU.js +0 -2
  562. package/dist/cli/chunks/unified-persistence-KGGNA46H.js +0 -2
  563. package/dist/cli/chunks/visual-security-6VZNQLH7.js +0 -2
  564. package/dist/cli/chunks/witness-chain-AKKHWEWU.js +0 -2
  565. package/dist/cli/chunks/witness-chain-TATPXQRK.js +0 -2
  566. package/dist/cli/chunks/witness-chain-repair-2HGJGE7O.js +0 -2
  567. package/dist/cli/chunks/workflow-orchestrator-4GAW7HNZ.js +0 -2
  568. package/dist/cli/chunks/wrappers-ZD5NBHYI.js +0 -2
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.9");process.exit(0)}
2
- import{c as Re}from"./chunk-J3WGK22W.js";import{d as Le}from"./chunk-JP4P3P3D.js";import{a as Pe,b as je}from"./chunk-UOJBR4J3.js";import{m as Ie,n as _e}from"./chunk-XYCKHYBM.js";import{b as D,d as we}from"./chunk-PVIA2FPD.js";import{c as C,d as I}from"./chunk-JNNZK7KH.js";import{a as Oe}from"./chunk-KTSLTZSG.js";import{e as xe,f as ve,g as De}from"./chunk-O3JLOVZX.js";import{a as G,b as A,e as Y}from"./chunk-N3KEY4XJ.js";import{c as Ee,d as ke}from"./chunk-4V27J6YN.js";Oe();import{createRequire as $e}from"module";var O;function W(){if(!O){let p=$e(import.meta.url);try{O=p("typescript")}catch{try{O=p("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(p,e){return W()[e]},has(p,e){return e in W()},ownKeys(){return Object.keys(W())},getOwnPropertyDescriptor(p,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"}},nt=new N,Z=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}}},it=new Z;De();var L=1e3;function R(p){let e=p.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.15.10");process.exit(0)}
2
+ import{g as Re}from"./chunk-APSRPR4W.js";import{d as Le}from"./chunk-YYTGXD3R.js";import{a as Pe,b as je}from"./chunk-2SXBBUM6.js";import{m as Ie,n as _e}from"./chunk-XFVTGAAJ.js";import{b as D,d as we}from"./chunk-ACWFKES2.js";import{c as C,d as I}from"./chunk-NSHU347M.js";import{a as Oe}from"./chunk-HOZUDE4C.js";import{c as xe,d as ve,e as De}from"./chunk-ATHWDAXB.js";import{a as G,b as A,e as Y}from"./chunk-GHBNRMSJ.js";import{c as Ee,d as ke}from"./chunk-EWFECZ2U.js";Oe();import{createRequire as $e}from"module";var O;function W(){if(!O){let p=$e(import.meta.url);try{O=p("typescript")}catch{try{O=p("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(p,e){return W()[e]},has(p,e){return e in W()},ownKeys(){return Object.keys(W())},getOwnPropertyDescriptor(p,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"}},nt=new N,Z=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}}},it=new Z;De();var L=1e3;function R(p){let e=p.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 u of d)u==="("?o++:u===")"?o=Math.max(0,o-1):u==="<"?r++:u===">"?r=Math.max(0,r-1):u==="["?a++:u==="]"&&(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(p,e,t="<",s=">"){if(p[e]!==t)return;let n=1,i=e+1;for(;i<p.length&&n>0;)p[i]===t?n++:p[i]===s&&n--,i++;if(n===0)return p.substring(e+1,i-1)}function M(p,e,t){let s=[];for(let n=e-1;n>=0;n--){let i=p[n].trim();if(i.startsWith(t))s.unshift(i);else{if(i===""||i.startsWith("//")||i.startsWith("*")||i.startsWith("#"))continue;break}}return s}function T(p){let e=[],t=0,s="";for(let n of p)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 de(p){let e=0,t=!1,s="";for(let n=0;n<p.length;n++){let i=p[n];if(t){i===s&&p[n-1]!=="\\"&&(t=!1);continue}i==='"'||i==="'"||i==="`"?(t=!0,s=i):i==="{"?e++:i==="}"&&e--}return e}var ee=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}=R(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>L)continue;let a=n[r].match(o);if(a){let c=a[1].length,l=!!a[2],d=a[3],u=a[4],h=a[5]?.trim(),f=i[r]-1,y=f+1;for(let g=f+1;g<s.length;g++){let x=s[g];if(x.trim()===""||x.trim().startsWith("#"))continue;if((x.match(/^(\s*)/)?.[1].length??0)<=c&&x.trim()!==""){y=g;break}y=g+1}let b=M(s,f,"@");t.push({name:d,parameters:this.parseParams(u),returnType:h,isAsync:l,isPublic:!d.startsWith("_"),complexity:1,decorators:b,genericParams:[],startLine:i[r],endLine:y})}}return t}extractClasses(e){let t=[],s=e.split(`
5
5
  `),{logicalLines:n,lineMap:i}=R(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(g=>g.trim()):[],u=i[r]-1,h=u+1;for(let g=u+1;g<s.length;g++){let x=s[g];if(x.trim()===""||x.trim().startsWith("#"))continue;if((x.match(/^(\s*)/)?.[1].length??0)<=c&&x.trim()!==""){h=g;break}h=g+1}let f=s.slice(u+1,h).join(`
@@ -20,7 +20,7 @@ import{c as Re}from"./chunk-J3WGK22W.js";import{d as Le}from"./chunk-JP4P3P3D.js
20
20
  `),{logicalLines:n,lineMap:i}=R(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>L){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",u=!!l[2],h=l[3],f=l[4],y=l[5]?.trim();if(y&&y.includes("<")){let x=y.indexOf("<"),w=B(y,x);w!==void 0&&(y=y.substring(0,x)+"<"+w+">")}let b=i[a]-1,g=M(s,b,"@");t.push({name:h,parameters:this.parseParams(f),returnType:y,isAsync:u,isPublic:d==="public",complexity:1,decorators:g,genericParams:[],startLine:i[a],endLine:i[a]})}r+=de(c),r<0&&(r=0)}return t}extractClasses(e){let t=[],s=e.split(`
21
21
  `),{logicalLines:n,lineMap:i}=R(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>L)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,u=M(s,d,"@");t.push({name:c,methods:[],properties:[],isPublic:(a[1]||"public")==="public",implements:l.slice(1),extends:l[0]||void 0,decorators:u,startLine: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()?T(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}}):[]}},oe=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}=R(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>L)continue;let a=r.match(i);if(a){let c=a[1].trim(),l=c;if(c&&c.includes("<")){let f=c.indexOf("<"),y=B(c,f);y!==void 0&&(l=c.substring(0,f)+"<"+y+">")}let d=a[2],u=a[3],h=!!a[4]||l.includes("Future");t.push({name:d,parameters:this.parseParams(u),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}=R(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>L)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 T(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=ve("ParserRegistry"),Ce=["python","java","csharp","rust","swift"],ce=class p{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<p.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>=p.MAX_WASM_RETRIES;z.warn(`[${this.language}] tree-sitter WASM parser failed (attempt ${this.wasmFailCount}/${p.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)}},le=class{parsers=new Map;_wasmInitPromise=null;constructor(){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.register(new ae),this.register(new oe),this._wasmInitPromise=this._tryLoadWasmParsers()}async _tryLoadWasmParsers(){try{let e=await import("./tree-sitter-wasm-parser-MI3NZKUD.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 Ce){let n=t.get(s),i=this.parsers.get(s);n&&i&&this.parsers.set(s,new ce(n,i))}z.info("tree-sitter WASM parsers available for: "+Ce.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)}},ot=new le;import*as P from"node:fs/promises";import*as E from"node:path";var Ke=[/\.\./,/%2e%2e/i,/%252e%252e/i,/\.\.%2f/i,/%2f\.\./i,/\.\.%5c/i,/\.\.\\/,/%c0%ae/i,/%c0%2f/i,/%c1%9c/i,/\0/,/%00/i],Ue=[/^\/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],pe=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 Ke)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 Ue)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()}`,y=d.toLowerCase();if(o.length>0&&o.some(g=>g.toLowerCase()===f||g.toLowerCase()===y))return{valid:!1,error:`File extension '${d}' is not allowed`,riskLevel:"high"};if(i.length>0&&!i.some(g=>g.toLowerCase()===f||g.toLowerCase()===y))return{valid:!1,error:`File extension '${d}' is not in allowed list`,riskLevel:"medium"}}let u=s?this.joinPathsAbsolute(s,c):c,h=s.startsWith("/")?`/${this.normalizePath(s)}`:this.normalizePath(s);return s&&!u.startsWith(h)?{valid:!1,error:"Path escapes base directory",riskLevel:"critical"}:{valid:!0,normalizedPath:u,riskLevel:"none"}}normalizePath(e){let t=e.replace(/\\/g,"/");t=t.replace(/\/+/g,"/");let s=t.split("/"),n=[];for(let 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}},Ge=new pe,Se=(p,e)=>Ge.validate(p,e);we();var Me=[".exe",".bat",".cmd",".ps1",".dll",".so"],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},S=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};function ue(p,e){let t=p,s;switch(t.code){case"ENOENT":s="File not found: "+e;break;case"EACCES":s="Permission denied: "+e;break;case"EISDIR":s="Path is a directory: "+e;break;default:s="Failed to read file: "+e}return new F(s,e,t.code,t)}async function We(p,e,t){let s=async o=>{let r=await P.stat(o).catch(()=>null);return r!==null&&r.dev===t.dev&&r.ino===t.ino},n=await P.realpath(`/proc/self/fd/${p}`).catch(()=>null);if(n&&E.isAbsolute(n)&&await s(n))return n;let i=await P.realpath(e).catch(()=>null);return i&&await s(i)?i:null}function Te(p,e){let t=E.relative(p,e);return t===""||!t.startsWith(`..${E.sep}`)&&t!==".."&&!E.isAbsolute(t)}var me=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 ze(p){let e="",t=0;for(;t<p.length;){let s=p[t],n=p[t+1];s==="*"&&n==="*"?p[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 Fe(p,e,t,s){try{let n=await P.readdir(p,{withFileTypes:!0});for(let i of n){let o=E.join(p,i.name),r=E.relative(s,o);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&await Fe(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;projectRoot;projectRootReal;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.projectRoot=e.projectRoot?E.resolve(e.projectRoot):void 0,this.cache=new me(e.maxCacheSize??100,e.cacheTtlMs??300*1e3)}resolvePath(e){let t=E.isAbsolute(e),s=E.resolve(this.basePath),n=E.resolve(s,e),i=E.relative(s,n);if(this.basePath&&(i===".."||i.startsWith(`..${E.sep}`)||E.isAbsolute(i)))throw new S(e,["Path escapes base directory"],"critical");let o=this.basePath?s.split(/[\\/]/).filter(Boolean).length:0,r=Se(e,{basePath:t?"":this.basePath,allowAbsolute:!0,maxDepth:10+(t?o:0),deniedExtensions:Me});if(!r.valid)throw new S(e,[r.error||"Path validation failed"],r.riskLevel);return t?n:r.normalizedPath?r.normalizedPath:t?e:E.resolve(this.basePath,e)}async inProjectRoot(e){if(!this.projectRoot)return;if(e.includes("\0"))throw new S(e,["Null byte in path"],"critical");let t=E.resolve(this.basePath,e);if(!Te(this.projectRoot,t))return;if(Me.includes(E.extname(t).toLowerCase()))throw new S(e,[`File extension '${E.extname(t)}' is not allowed`],"high");this.projectRootReal??=P.realpath(this.projectRoot).catch(()=>null);let s=await this.projectRootReal;if(s)return{lexical:t,rootReal:s}}async readContained(e,t,s){this.stats.totalReads++;let n;try{n=await P.open(t,"r")}catch(i){return I(ue(i,t))}try{let i=await n.stat(),o=await We(n.fd,t,i);return!o||!Te(s,o)?I(new S(e,["Path resolves outside the project root"],"critical")):i.isFile()?C(await n.readFile("utf-8")):I(new F("Path is a directory: "+t,t,"EISDIR"))}catch(i){return I(ue(i,t))}finally{await n.close().catch(()=>{})}}async readFile(e){let t;try{let s=await this.inProjectRoot(e);if(s)return this.readContained(e,s.lexical,s.rootReal);t=this.resolvePath(e)}catch(s){if(s instanceof S)return I(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(),C(s);this.stats.cacheMisses++}try{let s=await P.readFile(t,"utf-8");return this.enableCache&&(this.cache.set(t,s,Buffer.byteLength(s,"utf-8")),this.updateCacheStats()),C(s)}catch(s){return I(ue(s,t))}}async readJSON(e){let t=await this.readFile(e);if(!t.success)return t;try{let s=D(t.value);return C(s)}catch(s){let n=s,i=e;try{i=this.resolvePath(e)}catch{}return I(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 S)return I(s);throw s}try{return await P.access(t,P.constants.F_OK),C(!0)}catch(s){let n=s;return n.code==="ENOENT"?C(!1):I(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 S)return I(n);throw n}try{if(!(await P.stat(s)).isDirectory())return I(new F("Base path is not a directory: "+s,s,"ENOTDIR"));let i=ze(e),o=[];return await Fe(s,i,o,s),o.sort(),C(o)}catch(n){let i=n;return I(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}};Y();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"};je();var _=class{baseUrl;maxRetries;retryDelayMs;timeoutMs;constructor(e=Pe(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{return await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3,async e=>{if(!e.ok)return!1;let t=await e.json();return t.models?t.models.some(s=>s.name===v.MODEL||s.name?.startsWith(`${v.MODEL}:`)||s.model===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,async o=>{if(!o.ok){let r=await o.text();throw new Error(`Ollama API error (${o.status}): ${r}`)}return await o.json()});if(i.embedding.length!==v.DIMENSIONS)throw new Error(`Invalid embedding dimensions: expected ${v.DIMENSIONS}, got ${i.embedding.length}`);return i.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,n){let i=new AbortController,o=setTimeout(()=>i.abort(),s);try{let r=await fetch(e,{...t,signal:i.signal});return await n(r)}finally{clearTimeout(o)}}sleep(e){return new Promise(t=>setTimeout(t,e))}async getServerInfo(){try{return await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3,async e=>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 Be}from"crypto";var j=class{cache;maxSize;hits;misses;constructor(e=1e4){this.cache=new Map,this.maxSize=e,this.hits=0,this.misses=0}hashContent(e,t,s){return Be("sha256").update(JSON.stringify(s===void 0?[t,e]:[t,s,e])).digest("hex")}get(e,t,s){let n=this.hashContent(e,t,s),i=this.cache.get(n);return i?(this.hits++,this.cache.delete(n),this.cache.set(n,i),[...i.embedding]):(this.misses++,null)}set(e,t,s,n){let i=this.hashContent(e,t,n);if(this.cache.size>=this.maxSize&&!this.cache.has(i)){let r=this.cache.keys().next().value;r&&this.cache.delete(r)}let o={embedding:[...s],timestamp:Date.now(),model:t};this.cache.set(i,o)}has(e,t,s){let n=this.hashContent(e,t,s);return this.cache.has(n)}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,embedding:[...t.embedding]}}))}import(e){this.cache.clear();for(let{key:t,entry:s}of e)this.cache.size<this.maxSize&&this.cache.set(t,{...s,embedding:[...s.embedding]})}};Y();var q="pseudo-embedding",he="verified-backend-v1",H=p=>p===v.MODEL?he:void 0,$=class{client;cache;batchSize;enableFallback;ollamaAvailable=null;constructor(e={}){this.client=new _(e.ollamaBaseUrl),this.cache=e.cache??new j(e.maxCacheSize),this.batchSize=e.batchSize??v.BATCH_SIZE,this.enableFallback=e.enableFallback??!0}async embed(e){let t=this.cache.has(e,v.MODEL,he)||await this.isOllamaAvailable()||!this.enableFallback?v.MODEL:q,s=this.cache.get(e,t,H(t));if(s)return s;let n;if(await this.isOllamaAvailable())t=v.MODEL,n=await this.client.generateEmbedding(e);else if(this.enableFallback)t=q,n=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,t,n,H(t)),n}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 u of d)u.cached?i++:o++;if(t){let u=c+l.length,h=e.length,y=(Date.now()-s)/u,g=(h-u)*y;t({current:u,total:h,percentage:u/h*100,estimatedTimeRemainingMs:g})}}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=t||this.cache.has(r,v.MODEL,he)?v.MODEL:q,l=this.cache.get(r,c,H(c));if(l)return{chunkId:o.id,embedding:l,model:c,cached:!0,computeTimeMs:Date.now()-a};try{let d;t?d=await this.client.generateEmbedding(r):d=this.generatePseudoEmbedding(r);let u=t?v.MODEL:q;return this.cache.set(r,u,d,H(u)),{chunkId:o.id,embedding:d,model:u,cached:!1,computeTimeMs:Date.now()-a}}catch(d){throw new Error(`Failed to generate embedding for chunk ${o.id}: ${G(d)}`)}}),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}}};ke();Y();we();import{existsSync as Xe,statSync as Je}from"fs";import{dirname as Qe,resolve as Ye,join as X}from"path";function Ve(p){switch(p){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 K=p=>p.startPosition.row+1,U=(p,e)=>p.childForFieldName(e)?.text??"";function ge(p){for(let e=0;e<p.childCount;e++){let t=p.child(e);if(t){if(t.type==="async")return!0;if(t.type==="function"||t.type==="function_declaration")break}}return!1}function qe(p){for(let e=0;e<p.childCount;e++)if(p.child(e)?.type==="accessibility_modifier"){let s=p.child(e).text;if(s==="private")return"private";if(s==="protected")return"protected"}return"public"}function He(p){let e=U(p,"name")||"(anonymous)",t=p.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:U(i,"name"),startLine:K(i),isAsync:ge(i),visibility:qe(i)})}return{name:e,startLine:K(p),methods:s}}function fe(p){return p.replace(/^['"`]|['"`]$/g,"")}async function ye(p,e){let t=Ve(e);if(!t)return null;let s=await Le(t);if(!s)return null;let n=null;try{let i=s.parse(p);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:U(c,"name"),startLine:K(c),isAsync:ge(c),visibility:"public"}),l=!1;break;case"class_declaration":case"class":r.classes.push(He(c)),l=!1;break;case"interface_declaration":r.interfaces.push({name:U(c,"name"),startLine:K(c)}),l=!1;break;case"lexical_declaration":case"variable_declaration":{for(let d=0;d<c.childCount;d++){let u=c.child(d);if(!u||u.type!=="variable_declarator")continue;let h=u.childForFieldName("value");if(h&&(h.type==="arrow_function"||h.type==="function"||h.type==="function_expression"))r.functions.push({name:U(u,"name"),startLine:K(u),isAsync:ge(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(fe(f.text))}}l=!1;break}case"import_statement":{let d=c.childForFieldName("source");d&&r.imports.push(fe(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(fe(h.text))}break}}if(l)for(let d=c.childCount-1;d>=0;d--){let u=c.child(d);u&&a.push(u)}}return r}catch{return null}finally{n?.delete?.()}}_e();var Ze={maxNodes:1e5,maxEdgesPerNode:500,namespace:"code-intelligence:kg",enableVectorEmbeddings:!0,embeddingDimension:384,enableLLMExtraction:!0,llmModelTier:2,llmMaxTokens:2048},be=xe.create("code-intelligence/knowledge-graph"),J=new Set(["ts","tsx","js","jsx"]),Ae=class{config;memory;nodeCache=new Map;edgeIndex=new Map;allEdgesCache;tsParser;fileReader;projectRoot;embedder;llmRouter;constructor(e,t={}){this.config={...Ze,...t},this.isKnowledgeGraphDependencies(e)?(this.memory=e.memory,this.llmRouter=e.llmRouter):(this.memory=e,this.llmRouter=void 0),this.tsParser=new N,this.projectRoot=this.config.projectRoot??this.config.basePath??Ee(),this.fileReader=new k({...this.config.basePath?{basePath:this.config.basePath}:{},projectRoot:this.projectRoot}),this.embedder=new $({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,{accepted:d,skipped:u}=await Re(r,this.projectRoot,this.config.basePath??process.cwd()),h=0;if(!a)await this.clear();else for(let b of u)b.reason==="not-found"&&await this.removeFileFromGraph(b.path);for(let b of d)try{if(l&&l.length>0){let w=this.getFileExtension(b);if(!this.matchesLanguage(w,l)){u.push({path:b,reason:"excluded-by-language"});continue}}if(!c&&this.isTestFile(b)){u.push({path:b,reason:"excluded-test-file"});continue}let g=this.getFileExtension(b);J.has(g)||o.set(g||"(none)",(o.get(g||"(none)")??0)+1);let x=await this.indexFile(b,a);n+=x.nodes,i+=x.edges,h++}catch(g){s.push({file:b,error:G(g)})}let f=Date.now()-t,y=[];if(o.size>0){let b=Array.from(J).join(", ");for(let[g,x]of o){let w=`${x} file(s) with extension '.${g}' were indexed as plain nodes: no dependency extractor for this language, so 'deps'/'impact' will report 0 edges for them. Supported: ${b}.`;y.push(w),be.warn(w)}}return await this.storeIndexMetadata({filesIndexed:h,nodesCreated:n,edgesCreated:i,duration:f,indexedAt:new Date().toISOString()}),C({filesIndexed:h,nodesCreated:n,edgesCreated:i,duration:f,errors:s,warnings:y,skipped:u})}catch(r){return I(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 I(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 C({nodes:i,edges:o,cycles:a,metrics:c})}catch(t){return I(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 Ie(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 T(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=ve("ParserRegistry"),Ce=["python","java","csharp","rust","swift"],ce=class p{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<p.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>=p.MAX_WASM_RETRIES;z.warn(`[${this.language}] tree-sitter WASM parser failed (attempt ${this.wasmFailCount}/${p.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)}},le=class{parsers=new Map;_wasmInitPromise=null;constructor(){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.register(new ae),this.register(new oe),this._wasmInitPromise=this._tryLoadWasmParsers()}async _tryLoadWasmParsers(){try{let e=await import("./tree-sitter-wasm-parser-YTBCBHUO.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 Ce){let n=t.get(s),i=this.parsers.get(s);n&&i&&this.parsers.set(s,new ce(n,i))}z.info("tree-sitter WASM parsers available for: "+Ce.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)}},ot=new le;import*as P from"node:fs/promises";import*as E from"node:path";var Ke=[/\.\./,/%2e%2e/i,/%252e%252e/i,/\.\.%2f/i,/%2f\.\./i,/\.\.%5c/i,/\.\.\\/,/%c0%ae/i,/%c0%2f/i,/%c1%9c/i,/\0/,/%00/i],Ue=[/^\/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],pe=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 Ke)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 Ue)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()}`,y=d.toLowerCase();if(o.length>0&&o.some(g=>g.toLowerCase()===f||g.toLowerCase()===y))return{valid:!1,error:`File extension '${d}' is not allowed`,riskLevel:"high"};if(i.length>0&&!i.some(g=>g.toLowerCase()===f||g.toLowerCase()===y))return{valid:!1,error:`File extension '${d}' is not in allowed list`,riskLevel:"medium"}}let u=s?this.joinPathsAbsolute(s,c):c,h=s.startsWith("/")?`/${this.normalizePath(s)}`:this.normalizePath(s);return s&&!u.startsWith(h)?{valid:!1,error:"Path escapes base directory",riskLevel:"critical"}:{valid:!0,normalizedPath:u,riskLevel:"none"}}normalizePath(e){let t=e.replace(/\\/g,"/");t=t.replace(/\/+/g,"/");let s=t.split("/"),n=[];for(let 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}},Ge=new pe,Se=(p,e)=>Ge.validate(p,e);we();var Me=[".exe",".bat",".cmd",".ps1",".dll",".so"],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},S=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};function ue(p,e){let t=p,s;switch(t.code){case"ENOENT":s="File not found: "+e;break;case"EACCES":s="Permission denied: "+e;break;case"EISDIR":s="Path is a directory: "+e;break;default:s="Failed to read file: "+e}return new F(s,e,t.code,t)}async function We(p,e,t){let s=async o=>{let r=await P.stat(o).catch(()=>null);return r!==null&&r.dev===t.dev&&r.ino===t.ino},n=await P.realpath(`/proc/self/fd/${p}`).catch(()=>null);if(n&&E.isAbsolute(n)&&await s(n))return n;let i=await P.realpath(e).catch(()=>null);return i&&await s(i)?i:null}function Te(p,e){let t=E.relative(p,e);return t===""||!t.startsWith(`..${E.sep}`)&&t!==".."&&!E.isAbsolute(t)}var me=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 ze(p){let e="",t=0;for(;t<p.length;){let s=p[t],n=p[t+1];s==="*"&&n==="*"?p[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 Fe(p,e,t,s){try{let n=await P.readdir(p,{withFileTypes:!0});for(let i of n){let o=E.join(p,i.name),r=E.relative(s,o);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&await Fe(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;projectRoot;projectRootReal;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.projectRoot=e.projectRoot?E.resolve(e.projectRoot):void 0,this.cache=new me(e.maxCacheSize??100,e.cacheTtlMs??300*1e3)}resolvePath(e){let t=E.isAbsolute(e),s=E.resolve(this.basePath),n=E.resolve(s,e),i=E.relative(s,n);if(this.basePath&&(i===".."||i.startsWith(`..${E.sep}`)||E.isAbsolute(i)))throw new S(e,["Path escapes base directory"],"critical");let o=this.basePath?s.split(/[\\/]/).filter(Boolean).length:0,r=Se(e,{basePath:t?"":this.basePath,allowAbsolute:!0,maxDepth:10+(t?o:0),deniedExtensions:Me});if(!r.valid)throw new S(e,[r.error||"Path validation failed"],r.riskLevel);return t?n:r.normalizedPath?r.normalizedPath:t?e:E.resolve(this.basePath,e)}async inProjectRoot(e){if(!this.projectRoot)return;if(e.includes("\0"))throw new S(e,["Null byte in path"],"critical");let t=E.resolve(this.basePath,e);if(!Te(this.projectRoot,t))return;if(Me.includes(E.extname(t).toLowerCase()))throw new S(e,[`File extension '${E.extname(t)}' is not allowed`],"high");this.projectRootReal??=P.realpath(this.projectRoot).catch(()=>null);let s=await this.projectRootReal;if(s)return{lexical:t,rootReal:s}}async readContained(e,t,s){this.stats.totalReads++;let n;try{n=await P.open(t,"r")}catch(i){return I(ue(i,t))}try{let i=await n.stat(),o=await We(n.fd,t,i);return!o||!Te(s,o)?I(new S(e,["Path resolves outside the project root"],"critical")):i.isFile()?C(await n.readFile("utf-8")):I(new F("Path is a directory: "+t,t,"EISDIR"))}catch(i){return I(ue(i,t))}finally{await n.close().catch(()=>{})}}async readFile(e){let t;try{let s=await this.inProjectRoot(e);if(s)return this.readContained(e,s.lexical,s.rootReal);t=this.resolvePath(e)}catch(s){if(s instanceof S)return I(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(),C(s);this.stats.cacheMisses++}try{let s=await P.readFile(t,"utf-8");return this.enableCache&&(this.cache.set(t,s,Buffer.byteLength(s,"utf-8")),this.updateCacheStats()),C(s)}catch(s){return I(ue(s,t))}}async readJSON(e){let t=await this.readFile(e);if(!t.success)return t;try{let s=D(t.value);return C(s)}catch(s){let n=s,i=e;try{i=this.resolvePath(e)}catch{}return I(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 S)return I(s);throw s}try{return await P.access(t,P.constants.F_OK),C(!0)}catch(s){let n=s;return n.code==="ENOENT"?C(!1):I(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 S)return I(n);throw n}try{if(!(await P.stat(s)).isDirectory())return I(new F("Base path is not a directory: "+s,s,"ENOTDIR"));let i=ze(e),o=[];return await Fe(s,i,o,s),o.sort(),C(o)}catch(n){let i=n;return I(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}};Y();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"};je();var _=class{baseUrl;maxRetries;retryDelayMs;timeoutMs;constructor(e=Pe(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{return await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3,async e=>{if(!e.ok)return!1;let t=await e.json();return t.models?t.models.some(s=>s.name===v.MODEL||s.name?.startsWith(`${v.MODEL}:`)||s.model===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,async o=>{if(!o.ok){let r=await o.text();throw new Error(`Ollama API error (${o.status}): ${r}`)}return await o.json()});if(i.embedding.length!==v.DIMENSIONS)throw new Error(`Invalid embedding dimensions: expected ${v.DIMENSIONS}, got ${i.embedding.length}`);return i.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,n){let i=new AbortController,o=setTimeout(()=>i.abort(),s);try{let r=await fetch(e,{...t,signal:i.signal});return await n(r)}finally{clearTimeout(o)}}sleep(e){return new Promise(t=>setTimeout(t,e))}async getServerInfo(){try{return await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3,async e=>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 Be}from"crypto";var j=class{cache;maxSize;hits;misses;constructor(e=1e4){this.cache=new Map,this.maxSize=e,this.hits=0,this.misses=0}hashContent(e,t,s){return Be("sha256").update(JSON.stringify(s===void 0?[t,e]:[t,s,e])).digest("hex")}get(e,t,s){let n=this.hashContent(e,t,s),i=this.cache.get(n);return i?(this.hits++,this.cache.delete(n),this.cache.set(n,i),[...i.embedding]):(this.misses++,null)}set(e,t,s,n){let i=this.hashContent(e,t,n);if(this.cache.size>=this.maxSize&&!this.cache.has(i)){let r=this.cache.keys().next().value;r&&this.cache.delete(r)}let o={embedding:[...s],timestamp:Date.now(),model:t};this.cache.set(i,o)}has(e,t,s){let n=this.hashContent(e,t,s);return this.cache.has(n)}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,embedding:[...t.embedding]}}))}import(e){this.cache.clear();for(let{key:t,entry:s}of e)this.cache.size<this.maxSize&&this.cache.set(t,{...s,embedding:[...s.embedding]})}};Y();var q="pseudo-embedding",he="verified-backend-v1",H=p=>p===v.MODEL?he:void 0,$=class{client;cache;batchSize;enableFallback;ollamaAvailable=null;constructor(e={}){this.client=new _(e.ollamaBaseUrl),this.cache=e.cache??new j(e.maxCacheSize),this.batchSize=e.batchSize??v.BATCH_SIZE,this.enableFallback=e.enableFallback??!0}async embed(e){let t=this.cache.has(e,v.MODEL,he)||await this.isOllamaAvailable()||!this.enableFallback?v.MODEL:q,s=this.cache.get(e,t,H(t));if(s)return s;let n;if(await this.isOllamaAvailable())t=v.MODEL,n=await this.client.generateEmbedding(e);else if(this.enableFallback)t=q,n=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,t,n,H(t)),n}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 u of d)u.cached?i++:o++;if(t){let u=c+l.length,h=e.length,y=(Date.now()-s)/u,g=(h-u)*y;t({current:u,total:h,percentage:u/h*100,estimatedTimeRemainingMs:g})}}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=t||this.cache.has(r,v.MODEL,he)?v.MODEL:q,l=this.cache.get(r,c,H(c));if(l)return{chunkId:o.id,embedding:l,model:c,cached:!0,computeTimeMs:Date.now()-a};try{let d;t?d=await this.client.generateEmbedding(r):d=this.generatePseudoEmbedding(r);let u=t?v.MODEL:q;return this.cache.set(r,u,d,H(u)),{chunkId:o.id,embedding:d,model:u,cached:!1,computeTimeMs:Date.now()-a}}catch(d){throw new Error(`Failed to generate embedding for chunk ${o.id}: ${G(d)}`)}}),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}}};ke();Y();we();import{existsSync as Xe,statSync as Je}from"fs";import{dirname as Qe,resolve as Ye,join as X}from"path";function Ve(p){switch(p){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 K=p=>p.startPosition.row+1,U=(p,e)=>p.childForFieldName(e)?.text??"";function ge(p){for(let e=0;e<p.childCount;e++){let t=p.child(e);if(t){if(t.type==="async")return!0;if(t.type==="function"||t.type==="function_declaration")break}}return!1}function qe(p){for(let e=0;e<p.childCount;e++)if(p.child(e)?.type==="accessibility_modifier"){let s=p.child(e).text;if(s==="private")return"private";if(s==="protected")return"protected"}return"public"}function He(p){let e=U(p,"name")||"(anonymous)",t=p.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:U(i,"name"),startLine:K(i),isAsync:ge(i),visibility:qe(i)})}return{name:e,startLine:K(p),methods:s}}function fe(p){return p.replace(/^['"`]|['"`]$/g,"")}async function ye(p,e){let t=Ve(e);if(!t)return null;let s=await Le(t);if(!s)return null;let n=null;try{let i=s.parse(p);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:U(c,"name"),startLine:K(c),isAsync:ge(c),visibility:"public"}),l=!1;break;case"class_declaration":case"class":r.classes.push(He(c)),l=!1;break;case"interface_declaration":r.interfaces.push({name:U(c,"name"),startLine:K(c)}),l=!1;break;case"lexical_declaration":case"variable_declaration":{for(let d=0;d<c.childCount;d++){let u=c.child(d);if(!u||u.type!=="variable_declarator")continue;let h=u.childForFieldName("value");if(h&&(h.type==="arrow_function"||h.type==="function"||h.type==="function_expression"))r.functions.push({name:U(u,"name"),startLine:K(u),isAsync:ge(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(fe(f.text))}}l=!1;break}case"import_statement":{let d=c.childForFieldName("source");d&&r.imports.push(fe(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(fe(h.text))}break}}if(l)for(let d=c.childCount-1;d>=0;d--){let u=c.child(d);u&&a.push(u)}}return r}catch{return null}finally{n?.delete?.()}}_e();var Ze={maxNodes:1e5,maxEdgesPerNode:500,namespace:"code-intelligence:kg",enableVectorEmbeddings:!0,embeddingDimension:384,enableLLMExtraction:!0,llmModelTier:2,llmMaxTokens:2048},be=xe.create("code-intelligence/knowledge-graph"),J=new Set(["ts","tsx","js","jsx"]),Ae=class{config;memory;nodeCache=new Map;edgeIndex=new Map;allEdgesCache;tsParser;fileReader;projectRoot;embedder;llmRouter;constructor(e,t={}){this.config={...Ze,...t},this.isKnowledgeGraphDependencies(e)?(this.memory=e.memory,this.llmRouter=e.llmRouter):(this.memory=e,this.llmRouter=void 0),this.tsParser=new N,this.projectRoot=this.config.projectRoot??this.config.basePath??Ee(),this.fileReader=new k({...this.config.basePath?{basePath:this.config.basePath}:{},projectRoot:this.projectRoot}),this.embedder=new $({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,{accepted:d,skipped:u}=await Re(r,this.projectRoot,this.config.basePath??process.cwd()),h=0;if(!a)await this.clear();else for(let b of u)b.reason==="not-found"&&await this.removeFileFromGraph(b.path);for(let b of d)try{if(l&&l.length>0){let w=this.getFileExtension(b);if(!this.matchesLanguage(w,l)){u.push({path:b,reason:"excluded-by-language"});continue}}if(!c&&this.isTestFile(b)){u.push({path:b,reason:"excluded-test-file"});continue}let g=this.getFileExtension(b);J.has(g)||o.set(g||"(none)",(o.get(g||"(none)")??0)+1);let x=await this.indexFile(b,a);n+=x.nodes,i+=x.edges,h++}catch(g){s.push({file:b,error:G(g)})}let f=Date.now()-t,y=[];if(o.size>0){let b=Array.from(J).join(", ");for(let[g,x]of o){let w=`${x} file(s) with extension '.${g}' were indexed as plain nodes: no dependency extractor for this language, so 'deps'/'impact' will report 0 edges for them. Supported: ${b}.`;y.push(w),be.warn(w)}}return await this.storeIndexMetadata({filesIndexed:h,nodesCreated:n,edgesCreated:i,duration:f,indexedAt:new Date().toISOString()}),C({filesIndexed:h,nodesCreated:n,edgesCreated:i,duration:f,errors:s,warnings:y,skipped:u})}catch(r){return I(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 I(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 C({nodes:i,edges:o,cycles:a,metrics:c})}catch(t){return I(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 Ie(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,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.9");process.exit(0)}
2
- import{b as o}from"./chunk-HZ5NC6U5.js";function s(n){return n instanceof Error?n.message:String(n)}function u(n){return n instanceof Error?n:new Error(String(n))}function a(n){return n instanceof r||typeof n=="object"&&n!==null&&n.callerError===!0}var r,e=o(()=>{"use strict";r=class extends Error{callerError=!0;constructor(t){super(t),this.name="CallerInputError"}}});export{s as a,u as b,r as c,a as d,e};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.10");process.exit(0)}
2
+ import{b as o}from"./chunk-OY2AHLSF.js";function s(n){return n instanceof Error?n.message:String(n)}function u(n){return n instanceof Error?n:new Error(String(n))}function a(n){return n instanceof r||typeof n=="object"&&n!==null&&n.callerError===!0}var r,e=o(()=>{"use strict";r=class extends Error{callerError=!0;constructor(t){super(t),this.name="CallerInputError"}}});export{s as a,u as b,r as c,a as d,e};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.9");process.exit(0)}
2
- import{a as v,b as k}from"./chunk-VQHVHVSF.js";import{o as g,s as P}from"./chunk-OCESWNAZ.js";import{a as d,b as y,e as R}from"./chunk-N3KEY4XJ.js";R();import{randomUUID as M}from"crypto";var p=class{constructor(e){this.config=e}config;_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let r=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let n,t;for(let a=0;a<=this.config.retryCount;a++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");t=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(u){n=y(u),e.logger.warn(`Worker ${this.config.id} attempt ${a+1} failed: ${n.message}`),a<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let o=Date.now()-r;return t?(this._successfulExecutions++,this._lastResult=t):(this._failedExecutions++,t=this.createErrorResult(n,o),this._lastResult=t),this._executionDurations.push(o),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:t.success,durationMs:o}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=t.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:t.success,durationMs:o,findingsCount:t.findings.length,healthScore:t.metrics.healthScore}}),t}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((n,t)=>n+t,0)/this._executionDurations.length:0,r=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(r*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,r,n){return new Promise((t,o)=>{let a=setTimeout(()=>{o(new Error(`Worker execution timed out after ${r}ms`))},r),u=()=>{clearTimeout(a),o(new Error("Worker execution aborted"))};n.addEventListener("abort",u,{once:!0}),e().then(c=>{clearTimeout(a),n.removeEventListener("abort",u),t(c)}).catch(c=>{clearTimeout(a),n.removeEventListener("abort",u),o(c)})})}createErrorResult(e,r){return{workerId:this.config.id,timestamp:new Date,durationMs:r,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,r,n,t){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:r,findings:n,recommendations:t}}delay(e){return new Promise(r=>setTimeout(r,e))}generateId(){return`${Date.now()}-${M().slice(0,9)}`}};P();R();var W={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},b=class extends p{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(W),this.dailyLogger=new k}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=g();await e.initialize();let r=e.getDatabase();return this.lifecycleManager=v(r,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return g().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let r=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let n=[],t=[],o=await this.getLifecycleManager();if(!o)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-r,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let a=0,u=0;try{let s=o.promoteEligiblePatterns();a=s.promoted,u=s.checked,a>0&&n.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${a} of ${u} short-term patterns promoted to long-term`})}catch(s){e.logger.warn("Pattern promotion failed",{error:d(s)})}let c=0,h=0;try{let s=o.deprecateStalePatterns();c=s.deprecated,h=s.checked,c>0&&n.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${c} of ${h} patterns deprecated (stale, failed, or low confidence)`})}catch(s){e.logger.warn("Stale pattern detection failed",{error:d(s)})}let l=0;try{let s=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;l=o.applyConfidenceDecay(Math.min(s,7)).decayed}catch(s){e.logger.warn("Confidence decay failed",{error:d(s)})}let m=this.getPendingExperienceCount(),i={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{i=o.getStats()}catch(s){e.logger.warn("Stats retrieval failed",{error:d(s)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${a} promoted, ${c} deprecated, ${l} decayed, ${m} pending exp, ${i.activePatterns} active patterns (avg conf: ${i.avgConfidence.toFixed(2)})`,details:{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,totalPatterns:i.totalPatterns,activePatterns:i.activePatterns,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}),this.dailyLogger.flush()}catch(s){e.logger.warn("Daily log write failed",{error:d(s)})}this.lastRunTimestamp=Date.now(),i.activePatterns>0&&i.patternsNearDeprecation/i.activePatterns>.5&&t.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${i.patternsNearDeprecation} of ${i.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let f=this.calculateHealthScore(i,a,c),D=this.determineTrend(a,c,i.activePatterns),_=Math.max(u,h),x=a+c+i.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,healthScore:f}),this.createResult(Date.now()-r,{itemsAnalyzed:_,issuesFound:x,healthScore:f,trend:D,domainMetrics:{promoted:a,deprecated:c,decayed:l,stalePatterns:i.patternsNearDeprecation,pendingExperiences:m,avgConfidence:Number(i.avgConfidence.toFixed(3)),avgSuccessRate:Number(i.avgSuccessRate.toFixed(3))}},n,t)}calculateHealthScore(e,r,n){let t=70;if(t+=Math.min(15,r*5),e.avgConfidence>0&&(t+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let o=n/e.activePatterns;t-=Math.round(o*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(t-=10),Math.max(0,Math.min(100,Math.round(t)))}determineTrend(e,r,n){return n===0?"stable":e>r?"improving":r>e&&r/n>.1?"degrading":"stable"}};export{p as a,b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.10");process.exit(0)}
2
+ import{a as v,b as k}from"./chunk-KSIWGGJI.js";import{r as g,v as P}from"./chunk-C522H7XR.js";import{a as d,b as y,e as R}from"./chunk-GHBNRMSJ.js";R();import{randomUUID as M}from"crypto";var p=class{constructor(e){this.config=e}config;_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let r=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let n,t;for(let a=0;a<=this.config.retryCount;a++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");t=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(u){n=y(u),e.logger.warn(`Worker ${this.config.id} attempt ${a+1} failed: ${n.message}`),a<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let o=Date.now()-r;return t?(this._successfulExecutions++,this._lastResult=t):(this._failedExecutions++,t=this.createErrorResult(n,o),this._lastResult=t),this._executionDurations.push(o),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:t.success,durationMs:o}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=t.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:t.success,durationMs:o,findingsCount:t.findings.length,healthScore:t.metrics.healthScore}}),t}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((n,t)=>n+t,0)/this._executionDurations.length:0,r=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(r*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,r,n){return new Promise((t,o)=>{let a=setTimeout(()=>{o(new Error(`Worker execution timed out after ${r}ms`))},r),u=()=>{clearTimeout(a),o(new Error("Worker execution aborted"))};n.addEventListener("abort",u,{once:!0}),e().then(c=>{clearTimeout(a),n.removeEventListener("abort",u),t(c)}).catch(c=>{clearTimeout(a),n.removeEventListener("abort",u),o(c)})})}createErrorResult(e,r){return{workerId:this.config.id,timestamp:new Date,durationMs:r,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,r,n,t){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:r,findings:n,recommendations:t}}delay(e){return new Promise(r=>setTimeout(r,e))}generateId(){return`${Date.now()}-${M().slice(0,9)}`}};P();R();var W={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},b=class extends p{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(W),this.dailyLogger=new k}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=g();await e.initialize();let r=e.getDatabase();return this.lifecycleManager=v(r,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return g().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let r=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let n=[],t=[],o=await this.getLifecycleManager();if(!o)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-r,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let a=0,u=0;try{let s=o.promoteEligiblePatterns();a=s.promoted,u=s.checked,a>0&&n.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${a} of ${u} short-term patterns promoted to long-term`})}catch(s){e.logger.warn("Pattern promotion failed",{error:d(s)})}let c=0,h=0;try{let s=o.deprecateStalePatterns();c=s.deprecated,h=s.checked,c>0&&n.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${c} of ${h} patterns deprecated (stale, failed, or low confidence)`})}catch(s){e.logger.warn("Stale pattern detection failed",{error:d(s)})}let l=0;try{let s=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;l=o.applyConfidenceDecay(Math.min(s,7)).decayed}catch(s){e.logger.warn("Confidence decay failed",{error:d(s)})}let m=this.getPendingExperienceCount(),i={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{i=o.getStats()}catch(s){e.logger.warn("Stats retrieval failed",{error:d(s)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${a} promoted, ${c} deprecated, ${l} decayed, ${m} pending exp, ${i.activePatterns} active patterns (avg conf: ${i.avgConfidence.toFixed(2)})`,details:{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,totalPatterns:i.totalPatterns,activePatterns:i.activePatterns,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}),this.dailyLogger.flush()}catch(s){e.logger.warn("Daily log write failed",{error:d(s)})}this.lastRunTimestamp=Date.now(),i.activePatterns>0&&i.patternsNearDeprecation/i.activePatterns>.5&&t.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${i.patternsNearDeprecation} of ${i.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let f=this.calculateHealthScore(i,a,c),D=this.determineTrend(a,c,i.activePatterns),_=Math.max(u,h),x=a+c+i.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,healthScore:f}),this.createResult(Date.now()-r,{itemsAnalyzed:_,issuesFound:x,healthScore:f,trend:D,domainMetrics:{promoted:a,deprecated:c,decayed:l,stalePatterns:i.patternsNearDeprecation,pendingExperiences:m,avgConfidence:Number(i.avgConfidence.toFixed(3)),avgSuccessRate:Number(i.avgSuccessRate.toFixed(3))}},n,t)}calculateHealthScore(e,r,n){let t=70;if(t+=Math.min(15,r*5),e.avgConfidence>0&&(t+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let o=n/e.activePatterns;t-=Math.round(o*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(t-=10),Math.max(0,Math.min(100,Math.round(t)))}determineTrend(e,r,n){return n===0?"stable":e>r?"improving":r>e&&r/n>.1?"degrading":"stable"}};export{p as a,b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.9");process.exit(0)}
2
- import{b as t,d as o}from"./chunk-HZ5NC6U5.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>m,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>g,TensorCompress:()=>c,default:()=>i,differentiableSearch:()=>l,getCompressionLevel:()=>s,hierarchicalForward:()=>p,init:()=>u,pipeline:()=>v});import{createRequire as n}from"module";var r,e,i,a,c,l,p,s,u,m,d,A,f,h,_,g,v,b=t(()=>{r=n(import.meta.url),e=r("@ruvector/gnn"),i=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:p,getCompressionLevel:s,init:u,FlashAttention:m,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:g,pipeline:v}=e||{}});export{L as a,b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.10");process.exit(0)}
2
+ import{b as t,d as o}from"./chunk-OY2AHLSF.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>m,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>g,TensorCompress:()=>c,default:()=>i,differentiableSearch:()=>l,getCompressionLevel:()=>s,hierarchicalForward:()=>p,init:()=>u,pipeline:()=>v});import{createRequire as n}from"module";var r,e,i,a,c,l,p,s,u,m,d,A,f,h,_,g,v,b=t(()=>{r=n(import.meta.url),e=r("@ruvector/gnn"),i=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:p,getCompressionLevel:s,init:u,FlashAttention:m,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:g,pipeline:v}=e||{}});export{L as a,b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.9");process.exit(0)}
2
- import{a as n}from"./chunk-IFEIY3NQ.js";import{a as i}from"./chunk-3CJCROMW.js";import{a as o,e as d}from"./chunk-7KII4CQG.js";import{existsSync as m,statSync as s}from"node:fs";import{extname as l,join as c}from"node:path";d();var _=o.CLEANUP_INTERVAL_MS,y=".agentic-qe/memory.db";async function p(t,r=!0){let e;switch(t.type){case"memory":e=new i;break;case"sqlite":e=new n({sqlite:t.sqlite,enableFallback:!0});break;case"agentdb":e=new n({sqlite:{path:t.agentdb?.path??y},enableFallback:!0});break;case"hybrid":e=new n(t.hybrid);break;default:throw new Error(`Unknown memory backend type: ${t.type}`)}return r&&await e.initialize(),{backend:e,type:t.type,initialized:r}}async function P(t=!0){let r=process.env.AQE_MEMORY_BACKEND??"memory",e=process.env.AQE_MEMORY_PATH,a=e?e===":memory:"?e:m(e)?s(e).isDirectory()?c(e,"memory.db"):e:/\.(db|sqlite|sqlite3)$/i.test(l(e))?e:c(e,"memory.db"):y;return p({type:r,sqlite:{path:a,walMode:!0},agentdb:{path:a},hybrid:{enableFallback:!0,sqlite:{path:a}}},t)}export{p as a,P as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.10");process.exit(0)}
2
+ import{a as n}from"./chunk-FB6TI3BH.js";import{a as i}from"./chunk-DEF34AFL.js";import{a as o,e as d}from"./chunk-PGYMKGOE.js";import{existsSync as m,statSync as s}from"node:fs";import{extname as l,join as c}from"node:path";d();var _=o.CLEANUP_INTERVAL_MS,y=".agentic-qe/memory.db";async function p(t,r=!0){let e;switch(t.type){case"memory":e=new i;break;case"sqlite":e=new n({sqlite:t.sqlite,enableFallback:!0});break;case"agentdb":e=new n({sqlite:{path:t.agentdb?.path??y},enableFallback:!0});break;case"hybrid":e=new n(t.hybrid);break;default:throw new Error(`Unknown memory backend type: ${t.type}`)}return r&&await e.initialize(),{backend:e,type:t.type,initialized:r}}async function P(t=!0){let r=process.env.AQE_MEMORY_BACKEND??"memory",e=process.env.AQE_MEMORY_PATH,a=e?e===":memory:"?e:m(e)?s(e).isDirectory()?c(e,"memory.db"):e:/\.(db|sqlite|sqlite3)$/i.test(l(e))?e:c(e,"memory.db"):y;return p({type:r,sqlite:{path:a,walMode:!0},agentdb:{path:a},hybrid:{enableFallback:!0,sqlite:{path:a}}},t)}export{p as a,P as b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.9");process.exit(0)}
2
- import{h as U}from"./chunk-K5DJXMAA.js";import{c as D,d as R,e as h,g as x}from"./chunk-JAV5WPSY.js";import{a as v}from"./chunk-A6YIH4C4.js";var f=class{config;trackers;globalCostTodayUsd=0;lastGlobalReset=new Date;constructor(e){this.config=e,this.trackers=new Map;for(let t of[0,1,2,3,4])this.trackers.set(t,{tier:t,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,lastHourlyReset:new Date,lastDailyReset:new Date,requestHistory:[]})}async checkBudget(e,t){if(!this.config.enabled)return this.createAllowedDecision(e,e,t,!1,[]);this.autoReset();let r=this.config.tierBudgets[e];if(!r||!r.enabled)return this.createAllowedDecision(e,e,t,!1,["Tier budget not configured or disabled"]);let s=this.getUsage(e),i=[],c=this.config.maxDailyCostUsd-this.globalCostTodayUsd;if(this.globalCostTodayUsd+t>this.config.maxDailyCostUsd)return this.handleBudgetExceeded(e,t,s,"Global daily budget would be exceeded");if(this.globalCostTodayUsd+t>=this.config.maxDailyCostUsd*this.config.warningThreshold&&(i.push(`Approaching global daily budget limit: $${this.globalCostTodayUsd.toFixed(2)}/$${this.config.maxDailyCostUsd.toFixed(2)}`),this.config.onBudgetWarning==="downgrade"))return this.downgradeTier(e,t,s,i);let a=[{exceeded:s.costSpentTodayUsd+t>r.maxDailyCostUsd,message:`Tier ${e} daily cost limit would be exceeded: $${s.costSpentTodayUsd.toFixed(2)}/$${r.maxDailyCostUsd.toFixed(2)}`},{exceeded:s.requestsThisHour>=r.maxRequestsPerHour,message:`Tier ${e} hourly request limit reached: ${s.requestsThisHour}/${r.maxRequestsPerHour}`},{exceeded:s.requestsToday>=r.maxRequestsPerDay,message:`Tier ${e} daily request limit reached: ${s.requestsToday}/${r.maxRequestsPerDay}`},{exceeded:t>r.maxCostPerRequest,message:`Tier ${e} per-request cost limit would be exceeded: $${t.toFixed(4)}/$${r.maxCostPerRequest.toFixed(4)}`}];for(let n of a)if(n.exceeded)return this.handleBudgetExceeded(e,t,s,n.message);return s.budgetUtilization>=this.config.warningThreshold&&(i.push(`Tier ${e} at ${(s.budgetUtilization*100).toFixed(1)}% of daily budget`),this.config.onBudgetWarning==="downgrade")?this.downgradeTier(e,t,s,i):this.createAllowedDecision(e,e,t,!1,i)}async recordCost(e,t){if(!this.config.enabled)return;let r=this.trackers.get(e);r&&(this.autoReset(),r.costSpentTodayUsd+=t,r.requestsThisHour++,r.requestsToday++,this.globalCostTodayUsd+=t,r.requestHistory.push({timestamp:new Date,costUsd:t}),r.requestHistory.length>1e3&&(r.requestHistory=r.requestHistory.slice(-1e3)))}getUsage(e){this.autoReset();let t=this.trackers.get(e);if(!t)return this.createEmptyUsage(e);let r=this.config.tierBudgets[e];if(!r)return this.createEmptyUsage(e);let s=r.maxDailyCostUsd>0?t.costSpentTodayUsd/r.maxDailyCostUsd:0,i=t.costSpentTodayUsd>=r.maxDailyCostUsd||t.requestsThisHour>=r.maxRequestsPerHour||t.requestsToday>=r.maxRequestsPerDay,c=s>=this.config.warningThreshold,a=new Date,n=new Date(a);return n.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:t.costSpentTodayUsd,requestsThisHour:t.requestsThisHour,requestsToday:t.requestsToday,budgetUtilization:s,isExceeded:i,isNearLimit:c,resetTime:n,remainingBudgetUsd:Math.max(0,r.maxDailyCostUsd-t.costSpentTodayUsd),remainingRequestsThisHour:Math.max(0,r.maxRequestsPerHour-t.requestsThisHour),remainingRequestsToday:Math.max(0,r.maxRequestsPerDay-t.requestsToday)}}getAllUsage(){let e={};for(let t of[0,1,2,3,4])e[t]=this.getUsage(t);return e}reset(){let e=new Date;for(let t of this.trackers.values())t.costSpentTodayUsd=0,t.requestsThisHour=0,t.requestsToday=0,t.lastHourlyReset=e,t.lastDailyReset=e,t.requestHistory=[];this.globalCostTodayUsd=0,this.lastGlobalReset=e}handleBudgetExceeded(e,t,r,s){switch(this.config.onBudgetExceeded){case"error":throw new h(`Budget exceeded: ${s}`,e,r);case"downgrade":return this.downgradeTier(e,t,r,[s]);case"queue":throw new h(`Budget exceeded (queueing not yet implemented): ${s}`,e,r);default:throw new h(`Budget exceeded: ${s}`,e,r)}}downgradeTier(e,t,r,s){for(let i=e-1;i>=0;i--){let c=this.config.tierBudgets[i];if(!c||!c.enabled)continue;let a=this.getUsage(i);if(!a.isExceeded){let n=t*.5;if(a.costSpentTodayUsd+n<=c.maxDailyCostUsd)return this.createAllowedDecision(e,i,n,!0,[...s,`Downgraded from Tier ${e} to Tier ${i} due to budget constraints`])}}throw new h(`Budget exceeded and no lower tier available: ${s.join("; ")}`,e,r)}createAllowedDecision(e,t,r,s,i){let c=this.getUsage(t);return{allowed:!0,reason:s?`Budget enforced: downgraded to Tier ${t}`:"Budget check passed",requestedTier:e,approvedTier:t,wasDowngraded:s,estimatedCostUsd:r,currentUsage:c,warnings:i}}createEmptyUsage(e){let t=new Date,r=new Date(t);return r.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,budgetUtilization:0,isExceeded:!1,isNearLimit:!1,resetTime:r,remainingBudgetUsd:0,remainingRequestsThisHour:0,remainingRequestsToday:0}}autoReset(){let e=new Date;this.shouldResetDaily(this.lastGlobalReset,e)&&(this.globalCostTodayUsd=0,this.lastGlobalReset=e);for(let t of this.trackers.values())this.shouldResetHourly(t.lastHourlyReset,e)&&(t.requestsThisHour=0,t.lastHourlyReset=e),this.shouldResetDaily(t.lastDailyReset,e)&&(t.costSpentTodayUsd=0,t.requestsToday=0,t.requestHistory=[],t.lastDailyReset=e)}shouldResetHourly(e,t){return(t.getTime()-e.getTime())/36e5>=1}shouldResetDaily(e,t){return t.getUTCDate()!==e.getUTCDate()||t.getUTCMonth()!==e.getUTCMonth()||t.getUTCFullYear()!==e.getUTCFullYear()}getSessionCostSummary(){this.autoReset();let e=this.config.maxDailyCostUsd,t=0,r={},s={0:"AgentBooster",1:"Haiku",2:"Sonnet",3:"SonnetExtended",4:"Opus"};for(let[c,a]of this.trackers.entries()){let n=this.config.tierBudgets[c],o=s[c]??`Tier${c}`;t+=a.costSpentTodayUsd,r[o]={spent:a.costSpentTodayUsd,limit:n?.maxDailyCostUsd??0,requests:a.requestsToday}}let i=e>0?Math.round(t/e*100):0;return{totalSpentUsd:t,dailyLimitUsd:e,utilizationPercent:i,byTier:r}}};var w=class{cache=new Map;maxSize;ttlMs;enabled;constructor(e,t,r){this.enabled=e,this.maxSize=t,this.ttlMs=r}generateKey(e){return`${e.agentType||"unknown"}:${e.domain||"unknown"}:${e.task.slice(0,100)}`}get(e){if(!this.enabled)return null;let t=this.generateKey(e),r=this.cache.get(t);return r?Date.now()>r.expiresAt?(this.cache.delete(t),null):{...r.decision,metadata:{...r.decision.metadata,fromCache:!0,decisionTimeMs:0}}:null}set(e,t){if(!this.enabled)return;let r=this.generateKey(e);if(this.cache.size>=this.maxSize){let s=this.cache.keys().next().value;s&&this.cache.delete(s)}this.cache.set(r,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},M=class{events=[];enabled;maxEvents=1e4;constructor(e){this.enabled=e}record(e){this.enabled&&(this.events.push(e),this.events.length>this.maxEvents&&(this.events=this.events.slice(-this.maxEvents)))}getMetrics(){if(this.events.length===0)return this.createEmptyMetrics();let e=new Date,t={};for(let o of[0,1,2,3,4]){let d=this.events.filter(l=>l.tier===o);if(d.length===0)continue;let T=d.filter(l=>l.success),m=d.filter(l=>!l.wasManualOverride),b=d.filter(l=>l.wasDowngraded),y=d.map(l=>l.latencyMs).sort((l,g)=>l-g),B=Math.floor(y.length*.95);t[o]={tier:o,selectionCount:d.length,autoRouteCount:m.length,manualOverrideCount:d.length-m.length,budgetDowngradeCount:b.length,successRate:T.length/d.length,avgComplexity:d.reduce((l,g)=>l+g.complexity,0)/d.length,totalCostUsd:d.reduce((l,g)=>l+g.costUsd,0),avgLatencyMs:d.reduce((l,g)=>l+g.latencyMs,0)/d.length,p95LatencyMs:y[B]||0,budgetUtilization:0}}let r=this.events.map(o=>o.latencyMs).sort((o,d)=>o-d),s=Math.floor(r.length*.95),i=Math.floor(r.length*.99),c=this.events.filter(o=>o.agentBoosterEligible).length,a=this.events.filter(o=>o.tier===0).length,n=this.events.filter(o=>o.tier===0&&o.success).length;return{byTier:t,totalDecisions:this.events.length,avgDecisionTimeMs:this.events.reduce((o,d)=>o+d.latencyMs,0)/this.events.length,p95DecisionTimeMs:r[s]||0,p99DecisionTimeMs:r[i]||0,fallbackRate:this.events.filter(o=>o.wasDowngraded).length/this.events.length,ruleMatchRate:this.events.filter(o=>!o.wasManualOverride).length/this.events.length,estimatedCostSavings:0,agentBoosterStats:{eligible:c,used:a,fallbackToLLM:Math.max(0,c-a),successRate:a>0?n/a:0},budgetStats:{totalSpentUsd:this.events.reduce((o,d)=>o+d.costUsd,0),budgetUtilization:0,downgradeCount:this.events.filter(o=>o.wasDowngraded).length,overrideCount:this.events.filter(o=>o.wasManualOverride).length},period:{start:this.events[0]?.timestamp||e,end:this.events[this.events.length-1]?.timestamp||e}}}reset(){this.events=[]}createEmptyMetrics(){let e=new Date;return{byTier:{},totalDecisions:0,avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:0,ruleMatchRate:0,estimatedCostSavings:0,agentBoosterStats:{eligible:0,used:0,fallbackToLLM:0,successRate:0},budgetStats:{totalSpentUsd:0,budgetUtilization:0,downgradeCount:0,overrideCount:0},period:{start:e,end:e}}}},p=class{config;complexityAnalyzer;budgetEnforcer;agentBoosterAdapter;cache;metrics;persistentMetricsTracker;patternsLoaded=!1;tierHierarchyFromPatterns=null;constructor(e={},t,r){this.config={...D,...e},this.agentBoosterAdapter=t,this.persistentMetricsTracker=r,this.complexityAnalyzer=U(this.config,t),this.budgetEnforcer=new f(this.config.budgetConfig),this.cache=new w(this.config.enableDecisionCache,1e3,this.config.decisionCacheTtlMs),this.metrics=new M(this.config.enableMetrics)}setPersistentMetricsTracker(e){this.persistentMetricsTracker=e}async loadPatternsFromLoader(){try{let t=await v().getTierHierarchy();if(t){this.tierHierarchyFromPatterns=t,this.patternsLoaded=!0,console.info("[ModelRouter] Loaded tier hierarchy from PatternLoader",{tiers:Object.keys(t)});return}console.debug("[ModelRouter] PatternLoader returned no tier hierarchy, using defaults")}catch(e){console.warn("[ModelRouter] Failed to load patterns from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.patternsLoaded=!1}getPatternsLoaded(){return this.patternsLoaded}getTierHierarchyFromPatterns(){return this.tierHierarchyFromPatterns}async route(e){let t=Date.now(),r=e.metadata?.correlationId;try{let s=this.cache.get(e);if(s)return s;let i=await Promise.race([this.routeInternal(e,t,r),new Promise((c,a)=>setTimeout(()=>a(new x("Routing decision timed out",this.config.maxDecisionTimeMs)),this.config.maxDecisionTimeMs))]);return this.cache.set(e,i),this.recordMetrics(i,!0),i}catch(s){let i=await this.createFallbackDecision(e,t,r,s instanceof Error?s:new Error("Unknown error"));return this.recordMetrics(i,!1),i}}getMetrics(){return this.metrics.getMetrics()}async getAgentBoosterHealth(){if(!this.agentBoosterAdapter)throw new R("Agent Booster adapter not available","AGENT_BOOSTER_UNAVAILABLE");return this.agentBoosterAdapter.getHealth()}resetMetrics(){this.metrics.reset()}async dispose(){this.cache.clear(),this.metrics.reset(),this.agentBoosterAdapter&&await this.agentBoosterAdapter.dispose()}async routeInternal(e,t,r){let s=[];if(e.manualTier!==void 0&&this.config.allowManualOverrides)return this.handleManualOverride(e,e.manualTier,t,r);let i=await this.complexityAnalyzer.analyze(e),c=i.recommendedTier,a=this.estimateCost(c,e.task.length),n=await this.budgetEnforcer.checkBudget(c,a),o=n.approvedTier;s.push(...n.warnings);let d=o===0&&i.signals.isMechanicalTransform,T=this.getModelIdForTier(o),m=this.buildRationale(i,n,o),b=this.buildAlternatives(i,o),y=Date.now()-t;return{tier:o,modelId:T,complexityAnalysis:i,budgetDecision:n,confidence:i.confidence,rationale:m,agentBoosterEligible:d,agentBoosterTransform:d?i.signals.detectedTransformType:void 0,alternativeTiers:b,metadata:{timestamp:new Date,decisionTimeMs:y,fromCache:!1,correlationId:r},warnings:s}}async handleManualOverride(e,t,r,s){let i=await this.complexityAnalyzer.analyze(e),c=this.estimateCost(t,e.task.length),a=await this.budgetEnforcer.checkBudget(t,c);!a.allowed&&e.isCritical&&this.config.budgetConfig.allowCriticalOverrides&&(a={...a,allowed:!0,reason:"Critical task override",warnings:[...a.warnings,"Budget exceeded but allowed due to critical task override"]});let n=a.approvedTier,o=this.getModelIdForTier(n),d=Date.now()-r;return{tier:n,modelId:o,complexityAnalysis:i,budgetDecision:a,confidence:1,rationale:`Manual override to Tier ${n}${a.wasDowngraded?" (downgraded due to budget)":""}`,agentBoosterEligible:n===0,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:d,fromCache:!1,correlationId:s},warnings:a.warnings}}async createFallbackDecision(e,t,r,s){let i=this.config.fallbackTier,c=this.getModelIdForTier(i),a={overall:50,codeComplexity:50,reasoningComplexity:50,scopeComplexity:50,confidence:.3,signals:{hasArchitectureScope:!1,hasSecurityScope:!1,requiresMultiStepReasoning:!1,requiresCrossDomainCoordination:!1,isMechanicalTransform:!1,requiresCreativity:!1,keywordMatches:{simple:[],moderate:[],complex:[],critical:[]}},recommendedTier:i,alternateTiers:[],explanation:`Fallback to Tier ${i} due to routing error`},n={allowed:!0,reason:"Fallback routing",requestedTier:i,approvedTier:i,wasDowngraded:!1,estimatedCostUsd:0,currentUsage:this.budgetEnforcer.getUsage(i),warnings:[]},o=Date.now()-t;return{tier:i,modelId:c,complexityAnalysis:a,budgetDecision:n,confidence:.3,rationale:`Fallback to Tier ${i} due to error: ${s.message}`,agentBoosterEligible:!1,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:o,fromCache:!1,correlationId:r},warnings:[`Routing error: ${s.message}`,"Using fallback tier"]}}estimateCost(e,t){let r=[0,.001,.01,.05,.2],s=Math.max(1,t/1e3);return r[e]*s}getModelIdForTier(e){return this.config.tierModels[e]||`tier-${e}-default`}buildRationale(e,t,r){let s=[];return s.push(`Complexity: ${e.overall}/100`),s.push(`Tier ${r} selected`),t.wasDowngraded&&s.push(`Downgraded due to budget: ${t.reason}`),s.push(e.explanation),s.join(". ")}buildAlternatives(e,t){return e.alternateTiers.filter(r=>r!==t).map(r=>({tier:r,modelId:this.getModelIdForTier(r),reason:`Alternative tier ${r}`}))}recordMetrics(e,t){this.metrics.record({timestamp:e.metadata.timestamp,tier:e.tier,complexity:e.complexityAnalysis.overall,costUsd:e.budgetDecision.estimatedCostUsd,latencyMs:e.metadata.decisionTimeMs,wasDowngraded:e.budgetDecision.wasDowngraded,wasManualOverride:!1,agentBoosterEligible:e.agentBoosterEligible,success:t}),this.recordPersistentMetrics(e,t).catch(console.error)}async recordPersistentMetrics(e,t){if(this.persistentMetricsTracker)try{let r=`router-tier${e.tier}-${Date.now()}`;await this.persistentMetricsTracker.recordOutcome("router",r,t,e.metadata.decisionTimeMs,{subType:`tier-${e.tier}`,confidence:e.confidence,usedFallback:e.budgetDecision.wasDowngraded})}catch(r){console.warn("[ModelRouter] Failed to record persistent metrics:",r)}}};function H(u={},e,t){return new p(u,e,t)}async function $(u={},e){let{createAgentBoosterAdapter:t}=await import("./adapter-R2Q4QGXQ.js"),r=await t({enabled:!0}),s=new p(u,r,e);return await s.loadPatternsFromLoader(),s}export{p as a,H as b,$ as c};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.10");process.exit(0)}
2
+ import{a as v}from"./chunk-FKL3R5JQ.js";import{h as U}from"./chunk-OEKP73MC.js";import{c as D,d as R,e as h,g as x}from"./chunk-U53ZB4IX.js";var f=class{config;trackers;globalCostTodayUsd=0;lastGlobalReset=new Date;constructor(e){this.config=e,this.trackers=new Map;for(let t of[0,1,2,3,4])this.trackers.set(t,{tier:t,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,lastHourlyReset:new Date,lastDailyReset:new Date,requestHistory:[]})}async checkBudget(e,t){if(!this.config.enabled)return this.createAllowedDecision(e,e,t,!1,[]);this.autoReset();let r=this.config.tierBudgets[e];if(!r||!r.enabled)return this.createAllowedDecision(e,e,t,!1,["Tier budget not configured or disabled"]);let s=this.getUsage(e),i=[],c=this.config.maxDailyCostUsd-this.globalCostTodayUsd;if(this.globalCostTodayUsd+t>this.config.maxDailyCostUsd)return this.handleBudgetExceeded(e,t,s,"Global daily budget would be exceeded");if(this.globalCostTodayUsd+t>=this.config.maxDailyCostUsd*this.config.warningThreshold&&(i.push(`Approaching global daily budget limit: $${this.globalCostTodayUsd.toFixed(2)}/$${this.config.maxDailyCostUsd.toFixed(2)}`),this.config.onBudgetWarning==="downgrade"))return this.downgradeTier(e,t,s,i);let a=[{exceeded:s.costSpentTodayUsd+t>r.maxDailyCostUsd,message:`Tier ${e} daily cost limit would be exceeded: $${s.costSpentTodayUsd.toFixed(2)}/$${r.maxDailyCostUsd.toFixed(2)}`},{exceeded:s.requestsThisHour>=r.maxRequestsPerHour,message:`Tier ${e} hourly request limit reached: ${s.requestsThisHour}/${r.maxRequestsPerHour}`},{exceeded:s.requestsToday>=r.maxRequestsPerDay,message:`Tier ${e} daily request limit reached: ${s.requestsToday}/${r.maxRequestsPerDay}`},{exceeded:t>r.maxCostPerRequest,message:`Tier ${e} per-request cost limit would be exceeded: $${t.toFixed(4)}/$${r.maxCostPerRequest.toFixed(4)}`}];for(let n of a)if(n.exceeded)return this.handleBudgetExceeded(e,t,s,n.message);return s.budgetUtilization>=this.config.warningThreshold&&(i.push(`Tier ${e} at ${(s.budgetUtilization*100).toFixed(1)}% of daily budget`),this.config.onBudgetWarning==="downgrade")?this.downgradeTier(e,t,s,i):this.createAllowedDecision(e,e,t,!1,i)}async recordCost(e,t){if(!this.config.enabled)return;let r=this.trackers.get(e);r&&(this.autoReset(),r.costSpentTodayUsd+=t,r.requestsThisHour++,r.requestsToday++,this.globalCostTodayUsd+=t,r.requestHistory.push({timestamp:new Date,costUsd:t}),r.requestHistory.length>1e3&&(r.requestHistory=r.requestHistory.slice(-1e3)))}getUsage(e){this.autoReset();let t=this.trackers.get(e);if(!t)return this.createEmptyUsage(e);let r=this.config.tierBudgets[e];if(!r)return this.createEmptyUsage(e);let s=r.maxDailyCostUsd>0?t.costSpentTodayUsd/r.maxDailyCostUsd:0,i=t.costSpentTodayUsd>=r.maxDailyCostUsd||t.requestsThisHour>=r.maxRequestsPerHour||t.requestsToday>=r.maxRequestsPerDay,c=s>=this.config.warningThreshold,a=new Date,n=new Date(a);return n.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:t.costSpentTodayUsd,requestsThisHour:t.requestsThisHour,requestsToday:t.requestsToday,budgetUtilization:s,isExceeded:i,isNearLimit:c,resetTime:n,remainingBudgetUsd:Math.max(0,r.maxDailyCostUsd-t.costSpentTodayUsd),remainingRequestsThisHour:Math.max(0,r.maxRequestsPerHour-t.requestsThisHour),remainingRequestsToday:Math.max(0,r.maxRequestsPerDay-t.requestsToday)}}getAllUsage(){let e={};for(let t of[0,1,2,3,4])e[t]=this.getUsage(t);return e}reset(){let e=new Date;for(let t of this.trackers.values())t.costSpentTodayUsd=0,t.requestsThisHour=0,t.requestsToday=0,t.lastHourlyReset=e,t.lastDailyReset=e,t.requestHistory=[];this.globalCostTodayUsd=0,this.lastGlobalReset=e}handleBudgetExceeded(e,t,r,s){switch(this.config.onBudgetExceeded){case"error":throw new h(`Budget exceeded: ${s}`,e,r);case"downgrade":return this.downgradeTier(e,t,r,[s]);case"queue":throw new h(`Budget exceeded (queueing not yet implemented): ${s}`,e,r);default:throw new h(`Budget exceeded: ${s}`,e,r)}}downgradeTier(e,t,r,s){for(let i=e-1;i>=0;i--){let c=this.config.tierBudgets[i];if(!c||!c.enabled)continue;let a=this.getUsage(i);if(!a.isExceeded){let n=t*.5;if(a.costSpentTodayUsd+n<=c.maxDailyCostUsd)return this.createAllowedDecision(e,i,n,!0,[...s,`Downgraded from Tier ${e} to Tier ${i} due to budget constraints`])}}throw new h(`Budget exceeded and no lower tier available: ${s.join("; ")}`,e,r)}createAllowedDecision(e,t,r,s,i){let c=this.getUsage(t);return{allowed:!0,reason:s?`Budget enforced: downgraded to Tier ${t}`:"Budget check passed",requestedTier:e,approvedTier:t,wasDowngraded:s,estimatedCostUsd:r,currentUsage:c,warnings:i}}createEmptyUsage(e){let t=new Date,r=new Date(t);return r.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,budgetUtilization:0,isExceeded:!1,isNearLimit:!1,resetTime:r,remainingBudgetUsd:0,remainingRequestsThisHour:0,remainingRequestsToday:0}}autoReset(){let e=new Date;this.shouldResetDaily(this.lastGlobalReset,e)&&(this.globalCostTodayUsd=0,this.lastGlobalReset=e);for(let t of this.trackers.values())this.shouldResetHourly(t.lastHourlyReset,e)&&(t.requestsThisHour=0,t.lastHourlyReset=e),this.shouldResetDaily(t.lastDailyReset,e)&&(t.costSpentTodayUsd=0,t.requestsToday=0,t.requestHistory=[],t.lastDailyReset=e)}shouldResetHourly(e,t){return(t.getTime()-e.getTime())/36e5>=1}shouldResetDaily(e,t){return t.getUTCDate()!==e.getUTCDate()||t.getUTCMonth()!==e.getUTCMonth()||t.getUTCFullYear()!==e.getUTCFullYear()}getSessionCostSummary(){this.autoReset();let e=this.config.maxDailyCostUsd,t=0,r={},s={0:"AgentBooster",1:"Haiku",2:"Sonnet",3:"SonnetExtended",4:"Opus"};for(let[c,a]of this.trackers.entries()){let n=this.config.tierBudgets[c],o=s[c]??`Tier${c}`;t+=a.costSpentTodayUsd,r[o]={spent:a.costSpentTodayUsd,limit:n?.maxDailyCostUsd??0,requests:a.requestsToday}}let i=e>0?Math.round(t/e*100):0;return{totalSpentUsd:t,dailyLimitUsd:e,utilizationPercent:i,byTier:r}}};var w=class{cache=new Map;maxSize;ttlMs;enabled;constructor(e,t,r){this.enabled=e,this.maxSize=t,this.ttlMs=r}generateKey(e){return`${e.agentType||"unknown"}:${e.domain||"unknown"}:${e.task.slice(0,100)}`}get(e){if(!this.enabled)return null;let t=this.generateKey(e),r=this.cache.get(t);return r?Date.now()>r.expiresAt?(this.cache.delete(t),null):{...r.decision,metadata:{...r.decision.metadata,fromCache:!0,decisionTimeMs:0}}:null}set(e,t){if(!this.enabled)return;let r=this.generateKey(e);if(this.cache.size>=this.maxSize){let s=this.cache.keys().next().value;s&&this.cache.delete(s)}this.cache.set(r,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},M=class{events=[];enabled;maxEvents=1e4;constructor(e){this.enabled=e}record(e){this.enabled&&(this.events.push(e),this.events.length>this.maxEvents&&(this.events=this.events.slice(-this.maxEvents)))}getMetrics(){if(this.events.length===0)return this.createEmptyMetrics();let e=new Date,t={};for(let o of[0,1,2,3,4]){let d=this.events.filter(l=>l.tier===o);if(d.length===0)continue;let T=d.filter(l=>l.success),m=d.filter(l=>!l.wasManualOverride),b=d.filter(l=>l.wasDowngraded),y=d.map(l=>l.latencyMs).sort((l,g)=>l-g),B=Math.floor(y.length*.95);t[o]={tier:o,selectionCount:d.length,autoRouteCount:m.length,manualOverrideCount:d.length-m.length,budgetDowngradeCount:b.length,successRate:T.length/d.length,avgComplexity:d.reduce((l,g)=>l+g.complexity,0)/d.length,totalCostUsd:d.reduce((l,g)=>l+g.costUsd,0),avgLatencyMs:d.reduce((l,g)=>l+g.latencyMs,0)/d.length,p95LatencyMs:y[B]||0,budgetUtilization:0}}let r=this.events.map(o=>o.latencyMs).sort((o,d)=>o-d),s=Math.floor(r.length*.95),i=Math.floor(r.length*.99),c=this.events.filter(o=>o.agentBoosterEligible).length,a=this.events.filter(o=>o.tier===0).length,n=this.events.filter(o=>o.tier===0&&o.success).length;return{byTier:t,totalDecisions:this.events.length,avgDecisionTimeMs:this.events.reduce((o,d)=>o+d.latencyMs,0)/this.events.length,p95DecisionTimeMs:r[s]||0,p99DecisionTimeMs:r[i]||0,fallbackRate:this.events.filter(o=>o.wasDowngraded).length/this.events.length,ruleMatchRate:this.events.filter(o=>!o.wasManualOverride).length/this.events.length,estimatedCostSavings:0,agentBoosterStats:{eligible:c,used:a,fallbackToLLM:Math.max(0,c-a),successRate:a>0?n/a:0},budgetStats:{totalSpentUsd:this.events.reduce((o,d)=>o+d.costUsd,0),budgetUtilization:0,downgradeCount:this.events.filter(o=>o.wasDowngraded).length,overrideCount:this.events.filter(o=>o.wasManualOverride).length},period:{start:this.events[0]?.timestamp||e,end:this.events[this.events.length-1]?.timestamp||e}}}reset(){this.events=[]}createEmptyMetrics(){let e=new Date;return{byTier:{},totalDecisions:0,avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:0,ruleMatchRate:0,estimatedCostSavings:0,agentBoosterStats:{eligible:0,used:0,fallbackToLLM:0,successRate:0},budgetStats:{totalSpentUsd:0,budgetUtilization:0,downgradeCount:0,overrideCount:0},period:{start:e,end:e}}}},p=class{config;complexityAnalyzer;budgetEnforcer;agentBoosterAdapter;cache;metrics;persistentMetricsTracker;patternsLoaded=!1;tierHierarchyFromPatterns=null;constructor(e={},t,r){this.config={...D,...e},this.agentBoosterAdapter=t,this.persistentMetricsTracker=r,this.complexityAnalyzer=U(this.config,t),this.budgetEnforcer=new f(this.config.budgetConfig),this.cache=new w(this.config.enableDecisionCache,1e3,this.config.decisionCacheTtlMs),this.metrics=new M(this.config.enableMetrics)}setPersistentMetricsTracker(e){this.persistentMetricsTracker=e}async loadPatternsFromLoader(){try{let t=await v().getTierHierarchy();if(t){this.tierHierarchyFromPatterns=t,this.patternsLoaded=!0,console.info("[ModelRouter] Loaded tier hierarchy from PatternLoader",{tiers:Object.keys(t)});return}console.debug("[ModelRouter] PatternLoader returned no tier hierarchy, using defaults")}catch(e){console.warn("[ModelRouter] Failed to load patterns from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.patternsLoaded=!1}getPatternsLoaded(){return this.patternsLoaded}getTierHierarchyFromPatterns(){return this.tierHierarchyFromPatterns}async route(e){let t=Date.now(),r=e.metadata?.correlationId;try{let s=this.cache.get(e);if(s)return s;let i=await Promise.race([this.routeInternal(e,t,r),new Promise((c,a)=>setTimeout(()=>a(new x("Routing decision timed out",this.config.maxDecisionTimeMs)),this.config.maxDecisionTimeMs))]);return this.cache.set(e,i),this.recordMetrics(i,!0),i}catch(s){let i=await this.createFallbackDecision(e,t,r,s instanceof Error?s:new Error("Unknown error"));return this.recordMetrics(i,!1),i}}getMetrics(){return this.metrics.getMetrics()}async getAgentBoosterHealth(){if(!this.agentBoosterAdapter)throw new R("Agent Booster adapter not available","AGENT_BOOSTER_UNAVAILABLE");return this.agentBoosterAdapter.getHealth()}resetMetrics(){this.metrics.reset()}async dispose(){this.cache.clear(),this.metrics.reset(),this.agentBoosterAdapter&&await this.agentBoosterAdapter.dispose()}async routeInternal(e,t,r){let s=[];if(e.manualTier!==void 0&&this.config.allowManualOverrides)return this.handleManualOverride(e,e.manualTier,t,r);let i=await this.complexityAnalyzer.analyze(e),c=i.recommendedTier,a=this.estimateCost(c,e.task.length),n=await this.budgetEnforcer.checkBudget(c,a),o=n.approvedTier;s.push(...n.warnings);let d=o===0&&i.signals.isMechanicalTransform,T=this.getModelIdForTier(o),m=this.buildRationale(i,n,o),b=this.buildAlternatives(i,o),y=Date.now()-t;return{tier:o,modelId:T,complexityAnalysis:i,budgetDecision:n,confidence:i.confidence,rationale:m,agentBoosterEligible:d,agentBoosterTransform:d?i.signals.detectedTransformType:void 0,alternativeTiers:b,metadata:{timestamp:new Date,decisionTimeMs:y,fromCache:!1,correlationId:r},warnings:s}}async handleManualOverride(e,t,r,s){let i=await this.complexityAnalyzer.analyze(e),c=this.estimateCost(t,e.task.length),a=await this.budgetEnforcer.checkBudget(t,c);!a.allowed&&e.isCritical&&this.config.budgetConfig.allowCriticalOverrides&&(a={...a,allowed:!0,reason:"Critical task override",warnings:[...a.warnings,"Budget exceeded but allowed due to critical task override"]});let n=a.approvedTier,o=this.getModelIdForTier(n),d=Date.now()-r;return{tier:n,modelId:o,complexityAnalysis:i,budgetDecision:a,confidence:1,rationale:`Manual override to Tier ${n}${a.wasDowngraded?" (downgraded due to budget)":""}`,agentBoosterEligible:n===0,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:d,fromCache:!1,correlationId:s},warnings:a.warnings}}async createFallbackDecision(e,t,r,s){let i=this.config.fallbackTier,c=this.getModelIdForTier(i),a={overall:50,codeComplexity:50,reasoningComplexity:50,scopeComplexity:50,confidence:.3,signals:{hasArchitectureScope:!1,hasSecurityScope:!1,requiresMultiStepReasoning:!1,requiresCrossDomainCoordination:!1,isMechanicalTransform:!1,requiresCreativity:!1,keywordMatches:{simple:[],moderate:[],complex:[],critical:[]}},recommendedTier:i,alternateTiers:[],explanation:`Fallback to Tier ${i} due to routing error`},n={allowed:!0,reason:"Fallback routing",requestedTier:i,approvedTier:i,wasDowngraded:!1,estimatedCostUsd:0,currentUsage:this.budgetEnforcer.getUsage(i),warnings:[]},o=Date.now()-t;return{tier:i,modelId:c,complexityAnalysis:a,budgetDecision:n,confidence:.3,rationale:`Fallback to Tier ${i} due to error: ${s.message}`,agentBoosterEligible:!1,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:o,fromCache:!1,correlationId:r},warnings:[`Routing error: ${s.message}`,"Using fallback tier"]}}estimateCost(e,t){let r=[0,.001,.01,.05,.2],s=Math.max(1,t/1e3);return r[e]*s}getModelIdForTier(e){return this.config.tierModels[e]||`tier-${e}-default`}buildRationale(e,t,r){let s=[];return s.push(`Complexity: ${e.overall}/100`),s.push(`Tier ${r} selected`),t.wasDowngraded&&s.push(`Downgraded due to budget: ${t.reason}`),s.push(e.explanation),s.join(". ")}buildAlternatives(e,t){return e.alternateTiers.filter(r=>r!==t).map(r=>({tier:r,modelId:this.getModelIdForTier(r),reason:`Alternative tier ${r}`}))}recordMetrics(e,t){this.metrics.record({timestamp:e.metadata.timestamp,tier:e.tier,complexity:e.complexityAnalysis.overall,costUsd:e.budgetDecision.estimatedCostUsd,latencyMs:e.metadata.decisionTimeMs,wasDowngraded:e.budgetDecision.wasDowngraded,wasManualOverride:!1,agentBoosterEligible:e.agentBoosterEligible,success:t}),this.recordPersistentMetrics(e,t).catch(console.error)}async recordPersistentMetrics(e,t){if(this.persistentMetricsTracker)try{let r=`router-tier${e.tier}-${Date.now()}`;await this.persistentMetricsTracker.recordOutcome("router",r,t,e.metadata.decisionTimeMs,{subType:`tier-${e.tier}`,confidence:e.confidence,usedFallback:e.budgetDecision.wasDowngraded})}catch(r){console.warn("[ModelRouter] Failed to record persistent metrics:",r)}}};function H(u={},e,t){return new p(u,e,t)}async function $(u={},e){let{createAgentBoosterAdapter:t}=await import("./adapter-TR5SLAZC.js"),r=await t({enabled:!0}),s=new p(u,r,e);return await s.loadPatternsFromLoader(),s}export{p as a,H as b,$ as c};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.9");process.exit(0)}
2
- import{a as ae,b as oe}from"./chunk-ZXBCCO2H.js";import{S as ie,i as D,p as $}from"./chunk-2I2UPJS7.js";import{b as g,d as ne,f as W}from"./chunk-HZ5NC6U5.js";var I,E=g(()=>{"use strict";I={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}});function se(){if(z)return A!==null;try{let i=(oe(),W(ae));if(A=i.differentiableSearch,P=i.init,P)try{P()}catch{}return z=!0,!0}catch{return z=!0,!1}}function j(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function ce(i,e,r,t){let n=r*t;if(n===0)return 0;let a=0,o=Math.min(i.length,e.length);for(let c=0;c<o;c++)a+=i[c]*e[c];return a/n}function q(i,e){let r=0,t=Math.min(i.length,e.length);for(let n=0;n<t;n++){let a=i[n]-e[n];r+=a*a}return Math.sqrt(r)}function le(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}var A,P,z,S,B=g(()=>{"use strict";E();A=null,P=null,z=!1;S=class{config;entries=[];idToIndex=new Map;hasRuvector=!1;loaded=!1;constructor(e){this.config={...I,...e}}ensureLoaded(){this.loaded||(this.hasRuvector=se(),this.loaded=!0)}normalizeVector(e){return e.length===this.config.dimensions?e:le(e,this.config.dimensions)}add(e,r,t){this.ensureLoaded();let n=this.normalizeVector(r),a=j(n);if(this.idToIndex.has(e)){let c=this.idToIndex.get(e);this.entries[c]={id:e,vector:n,norm:a,metadata:t};return}let o=this.entries.length;this.entries.push({id:e,vector:n,norm:a,metadata:t}),this.idToIndex.set(e,o)}search(e,r){if(this.ensureLoaded(),this.entries.length===0)return[];let t=this.normalizeVector(e),n=j(t),a=Math.min(r,this.entries.length),o=this.entries.length>0?this.entries[0].vector.length:0,c=t.length===o;if(this.config.metric==="cosine")return this.bruteForcSearch(t,n,a);if(this.hasRuvector&&c&&A)try{let s=this.entries.map(u=>u.vector),l=A(t,s,a,1).indices.map(u=>{let h=this.entries[u],m=-q(t,h.vector);return{id:h.id,score:m,metadata:h.metadata}});return l.sort((u,h)=>h.score-u.score),l}catch{}return this.bruteForcSearch(t,n,a)}bruteForcSearch(e,r,t){let n=[];for(let a of this.entries){let o;this.config.metric==="cosine"?o=ce(e,a.vector,r,a.norm):o=-q(e,a.vector),n.push({id:a.id,score:o,metadata:a.metadata})}return n.sort((a,o)=>o.score-a.score),n.slice(0,t)}remove(e){let r=this.idToIndex.get(e);if(r===void 0)return!1;let t=this.entries.length-1;if(r!==t){let n=this.entries[t];this.entries[r]=n,this.idToIndex.set(n.id,r)}return this.entries.pop(),this.idToIndex.delete(e),!0}size(){return this.entries.length}dimensions(){return this.config.dimensions}recall(){return this.hasRuvector,1}isRuvectorAvailable(){return this.ensureLoaded(),this.hasRuvector}getConfig(){return{...this.config}}clear(){this.entries=[],this.idToIndex.clear()}dispose(){this.clear()}}});import{createRequire as he}from"module";function de(){if(U){if(k)return k;throw new b(O??"Unknown load error")}U=!0;try{let i=ue("hnswlib-node");if(!i.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return k=i,k}catch(i){let e=i instanceof Error?i.message:String(i);throw O=e,new b(e)}}function me(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}function K(i){let e=new Array(i.length);for(let r=0;r<i.length;r++)e[r]=i[r];return e}var ue,b,k,U,O,J,w,Q=g(()=>{"use strict";E();ue=he(import.meta.url),b=class extends Error{constructor(e){super(`Native HNSW backend unavailable: ${e}`),this.name="NativeHnswUnavailableError"}},k=null,U=!1,O=null;J=1e4,w=class{config;nativeIndex=null;currentMaxElements=J;liveIds=new Set;metadataStore=new Map;_metrics={totalSearches:0,totalAdds:0,totalRemoves:0,avgSearchLatencyMs:0,maxSearchLatencyMs:0,lastSearchLatencyMs:0,fallbackSearchCount:0,bruteForceSearchCount:0,nativeSearchCount:0,fallbackRate:0,allSearchesBruteForce:!1};constructor(e){this.config={...I,...e},this.nativeIndex=this.createFreshIndex()}createFreshIndex(){let e=de(),r=this.config.metric==="euclidean"?"l2":"cosine";try{let t=new e.HierarchicalNSW(r,this.config.dimensions);return t.initIndex(this.currentMaxElements,this.config.M,this.config.efConstruction,100,!0),t.setEf(this.config.efSearch),t}catch(t){let n=t instanceof Error?t.message:String(t);throw new b(`HierarchicalNSW init failed: ${n}`)}}add(e,r,t){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");let n=this.normalizeVector(r);if(!this.liveIds.has(e)&&this.liveIds.size>=this.currentMaxElements){let a=this.currentMaxElements*2;this.nativeIndex.resizeIndex(a),this.currentMaxElements=a}this.nativeIndex.addPoint(K(n),e,!0),this.liveIds.add(e),t?this.metadataStore.set(e,t):this.metadataStore.delete(e),this._metrics.totalAdds++}search(e,r){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");if(this.liveIds.size===0||r<=0)return[];let t=performance.now(),n=this.normalizeVector(e),a=Math.min(r,this.liveIds.size),o=Math.min(this.liveIds.size,Math.max(a,this.config.efSearch)*2),c=this.nativeIndex.searchKnn(K(n),o),s=this.config.metric==="cosine",d=new Map;for(let h=0;h<c.neighbors.length;h++){let m=c.neighbors[h];if(!this.liveIds.has(m))continue;let x=c.distances[h],f=s?1-x:-x,G=d.get(m);(G===void 0||f>G.score)&&d.set(m,{id:m,score:f,metadata:this.metadataStore.get(m)})}let l=Array.from(d.values());l.sort((h,m)=>m.score-h.score),l.length>a&&(l.length=a);let u=performance.now()-t;return this.updateSearchMetrics(u),this._metrics.nativeSearchCount=this._metrics.totalSearches,u>50&&console.warn(`[NativeHNSW] search took ${u.toFixed(1)}ms (k=${r}, results=${l.length})`),l}remove(e){if(!this.nativeIndex||!this.liveIds.has(e))return!1;try{this.nativeIndex.markDelete(e)}catch{return!1}return this.liveIds.delete(e),this.metadataStore.delete(e),this._metrics.totalRemoves++,!0}size(){return this.liveIds.size}dimensions(){return this.config.dimensions}recall(){return .99}getMetrics(){return{...this._metrics}}get lastSearchLatencyMs(){return this._metrics.lastSearchLatencyMs}getConfig(){return{...this.config}}clear(){this.nativeIndex&&(this.liveIds.clear(),this.metadataStore.clear(),this.currentMaxElements=J,this.nativeIndex=this.createFreshIndex())}dispose(){this.liveIds.clear(),this.metadataStore.clear(),this.nativeIndex=null}isNativeAvailable(){return this.nativeIndex!==null}normalizeVector(e){return e.length===this.config.dimensions?e:me(e,this.config.dimensions)}updateSearchMetrics(e){this._metrics.totalSearches++,this._metrics.lastSearchLatencyMs=e,e>this._metrics.maxSearchLatencyMs&&(this._metrics.maxSearchLatencyMs=e);let r=this._metrics.totalSearches;this._metrics.avgSearchLatencyMs=this._metrics.avgSearchLatencyMs*((r-1)/r)+e/r}}});function X(i,e){let r=Array.from({length:e},()=>new Float64Array(e));for(let t=0;t<e;t++){let n=i[t].length;r[t][t]=n;for(let a of i[t])r[t][a]=-1}return r}function N(i,e){let r=e.length,t=new Float64Array(r);for(let n=0;n<r;n++){let a=i[n].length;t[n]=a*e[n];for(let o of i[n])t[n]-=e[o]}return t}function H(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function R(i){let e=H(i);if(e>0)for(let r=0;r<i.length;r++)i[r]/=e}function v(i,e){let r=0;for(let t=0;t<i.length;t++)r+=i[t]*e[t];for(let t=0;t<i.length;t++)i[t]-=r*e[t]}function y(i,e,r=100,t=1e-6){if(e<=1)return 0;if(e===2)return i[0].includes(1)?2:0;let n=new Float64Array(e).fill(1/Math.sqrt(e)),a=new Float64Array(e);for(let l=0;l<e;l++)a[l]=Math.random()-.5;v(a,n),R(a);let o=0;for(let l=0;l<30;l++){let u=N(i,a);if(v(u,n),o=H(u),o>0)for(let h=0;h<e;h++)a[h]=u[h]/o}if(o<t)return 0;let c=new Float64Array(e);for(let l=0;l<e;l++)c[l]=Math.random()-.5;v(c,n),R(c);let s=0;for(let l=0;l<r;l++){let u=N(i,c),h=new Float64Array(e);for(let f=0;f<e;f++)h[f]=o*c[f]-u[f];v(h,n);let m=H(h);if(m<t)break;let x=m;for(let f=0;f<e;f++)c[f]=h[f]/m;if(Math.abs(x-s)<t)break;s=x}let d=o-s;return Math.max(0,d)}function F(i,e,r=100,t=1e-6){return y(i,e,r,t)}function C(i,e,r=50,t){if(e<=1)return 0;let n=t??y(i,e);if(n<1e-10)return 1/0;let o=2*Math.max(...i.map(d=>d.length),1),s=2*(Math.log(o/n)/(o-n));return Math.max(0,s)}function M(i,e,r){let t=1-Math.exp(-i/.05),n=1-Math.exp(-e/.5),a=r===1/0?0:1/(1+r/5),o=.4*t+.3*n+.3*a;return Math.max(0,Math.min(1,o))}var _=g(()=>{"use strict"});var ee={};ne(ee,{ALERT_THRESHOLDS:()=>fe,DEFAULT_HNSW_HEALTH_CONFIG:()=>Y,HnswHealthMonitor:()=>L,_resetNativeLoader:()=>be,approximateFiedlerValue:()=>y,approximateSpectralGap:()=>F,buildAdjacencyFromIndex:()=>Z,buildLaplacian:()=>X,computeCoherenceScore:()=>M,createHnswHealthMonitor:()=>ge,deflateVector:()=>v,estimateEffectiveResistance:()=>C,laplacianMultiply:()=>N,normalizeInPlace:()=>R,vectorNorm:()=>H});function pe(){return V?T:(V=!0,T=null,null)}function be(){T=null,V=!1}function Z(i,e=16,r){let t=i.size();if(t===0)return{adjacency:[],nodeCount:0,adjacencySource:"approximate"};let n=Array.from({length:t},()=>[]),a=Math.min(e,t-1);if(a===0)return{adjacency:n,nodeCount:t,adjacencySource:"approximate"};if(r&&r.size>0){let o=Array.from(r.keys()).slice(0,t),c=new Map;for(let s=0;s<o.length;s++)c.set(o[s],s);for(let s=0;s<o.length;s++){let d=r.get(o[s]);if(!d)continue;let l=i.search(d,a+1);for(let u of l){if(u.id===o[s])continue;let h=c.get(u.id);h!==void 0&&(n[s].includes(h)||n[s].push(h),n[h].includes(s)||n[h].push(s))}}return{adjacency:n,nodeCount:t,adjacencySource:"actual-search"}}console.warn("[HnswHealthMonitor] No stored vectors provided \u2014 using approximate circular adjacency. Pass stored vectors for accurate health metrics.");for(let o=0;o<t;o++)for(let c=0;c<a;c++){let s=(o+c+1)%t;n[o].includes(s)||n[o].push(s),n[s].includes(o)||n[s].push(o)}return{adjacency:n,nodeCount:t,adjacencySource:"approximate"}}function ge(i){return new L(i)}var Y,fe,T,V,L,te=g(()=>{"use strict";_();_();Y={fiedlerThreshold:.01,spectralGapThreshold:.1,resistanceThreshold:10,coherenceThreshold:.3,maxPowerIterations:100,convergenceTolerance:1e-6,resistanceSampleSize:50,maxHistoryEntries:200,minIndexSize:3},fe={FragileIndex:.01,PoorExpansion:.1,HighResistance:10,LowCoherence:.3},T=null,V=!1;L=class{config;alerts=[];history=[];lastReport=null;useNative=!1;nativeChecked=!1;constructor(e){this.config={...Y,...e}}checkHealth(e){let r=performance.now(),t=e.size();if(t<this.config.minIndexSize)return this.createSmallIndexReport(t,performance.now()-r);this.nativeChecked||(this.nativeChecked=!0,this.useNative=pe()!==null);let{adjacency:n,nodeCount:a,adjacencySource:o}=Z(e),c=this.useNative?this.computeNativeMetrics(n):this.computeApproximateMetrics(n,a),s=this.generateAlerts(c);this.alerts.length=0,this.alerts.push(...s);let d=performance.now()-r,l={healthy:s.length===0,metrics:c,alerts:s,indexSize:t,usedNativeBackend:this.useNative,adjacencySource:o,checkDurationMs:d,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:c.coherenceScore,fiedlerValue:c.fiedlerValue,indexSize:t,healthy:l.healthy,timestamp:l.checkedAt}),this.lastReport=l,l}getAlerts(){return[...this.alerts]}getMetricsHistory(e){let r=[...this.history];return e!==void 0&&e<r.length?r.slice(-e):r}isHealthy(){return this.lastReport===null?!0:this.lastReport.healthy}getLastReport(){return this.lastReport}clearHistory(){this.history.length=0,this.alerts.length=0,this.lastReport=null}computeNativeMetrics(e){let r=T,t=r.computeFiedlerValue(e),n=r.computeSpectralGap(e),a=r.computeEffectiveResistance(e),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}computeApproximateMetrics(e,r){let t=y(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),n=F(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),a=C(e,r,this.config.resistanceSampleSize,t),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}generateAlerts(e){let r=[],t=new Date;return e.fiedlerValue<this.config.fiedlerThreshold&&r.push({type:"FragileIndex",message:`Fiedler value ${e.fiedlerValue.toFixed(6)} is below threshold ${this.config.fiedlerThreshold}. The index graph has weak algebraic connectivity.`,value:e.fiedlerValue,threshold:this.config.fiedlerThreshold,timestamp:t}),e.spectralGap<this.config.spectralGapThreshold&&r.push({type:"PoorExpansion",message:`Spectral gap ${e.spectralGap.toFixed(6)} is below threshold ${this.config.spectralGapThreshold}. The index graph has poor expansion properties.`,value:e.spectralGap,threshold:this.config.spectralGapThreshold,timestamp:t}),e.effectiveResistance>this.config.resistanceThreshold&&r.push({type:"HighResistance",message:`Average effective resistance ${e.effectiveResistance.toFixed(4)} exceeds threshold ${this.config.resistanceThreshold}. Nodes are poorly connected.`,value:e.effectiveResistance,threshold:this.config.resistanceThreshold,timestamp:t}),e.coherenceScore<this.config.coherenceThreshold&&r.push({type:"LowCoherence",message:`Coherence score ${e.coherenceScore.toFixed(4)} is below threshold ${this.config.coherenceThreshold}. Overall index health is degraded.`,value:e.coherenceScore,threshold:this.config.coherenceThreshold,timestamp:t}),r}createSmallIndexReport(e,r){let t={fiedlerValue:e>0?1:0,spectralGap:e>0?1:0,effectiveResistance:e>0?.5:0,coherenceScore:e>0?1:0},n={healthy:!0,metrics:t,alerts:[],indexSize:e,usedNativeBackend:!1,adjacencySource:"approximate",checkDurationMs:r,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:t.coherenceScore,fiedlerValue:t.fiedlerValue,indexSize:e,healthy:!0,timestamp:n.checkedAt}),this.lastReport=n,n}addHistoryPoint(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}}});var ve,p,re,ye=g(()=>{B();Q();ie();ve={patterns:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},"qe-memory":{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},learning:{dimensions:384,M:16,efConstruction:200,efSearch:50,metric:"cosine"},coverage:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}},p=new Map,re=class i{backend;_isNativeBackend;indexName;stringToNumericId=new Map;numericToStringId=new Map;nextAutoId=0;healthMonitor=null;healthMonitorLoaded=!1;operationsSinceLastCheck=0;healthCheckFrequency=100;lastHealthReport=null;constructor(e,r){this.indexName=e;let n={...ve[e]??{},...r},{backend:a,isNative:o}=i.createBackend(n);this.backend=a,this._isNativeBackend=o}add(e,r,t){this.backend.add(e,r,t),this.maybeRunHealthCheck()}search(e,r){let t=performance.now(),n=this.backend.search(e,r),a=performance.now()-t;return a>50&&console.warn(`[HNSW] search took ${a.toFixed(1)}ms (k=${r}, results=${n.length})`),this._lastSearchLatencyMs=a,n}_lastSearchLatencyMs=0;get lastSearchLatencyMs(){return this._lastSearchLatencyMs}remove(e){return this.backend.remove(e)}size(){return this.backend.size()}dimensions(){return this.backend.dimensions()}recall(){return this.backend.recall()}addByStringId(e,r){let t=this.stringToNumericId.get(e);t!==void 0?this.backend.remove(t):(t=this.nextAutoId++,this.stringToNumericId.set(e,t),this.numericToStringId.set(t,e)),this.backend.add(t,new Float32Array(r))}searchByArray(e,r){return this.backend.search(new Float32Array(e),r).map(n=>({id:this.numericToStringId.get(n.id)??String(n.id),score:n.score}))}removeByStringId(e){let r=this.stringToNumericId.get(e);if(r===void 0)return!1;let t=this.backend.remove(r);return t&&(this.stringToNumericId.delete(e),this.numericToStringId.delete(r)),t}clear(){this.backend.clear?.(),this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}dispose(){try{this.backend.dispose?.()}catch{}this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}isRuvectorAvailable(){return this.backend instanceof S?this.backend.isRuvectorAvailable():this.backend instanceof w?this.backend.isNativeAvailable():!1}isNativeBackend(){return this._isNativeBackend}getName(){return this.indexName}setHealthCheckFrequency(e){this.healthCheckFrequency=Math.max(1,e)}getHealthCheckFrequency(){return this.healthCheckFrequency}getLastHealthReport(){return this.lastHealthReport}getHealthMonitor(){return this.healthMonitor}maybeRunHealthCheck(){if($()&&(this.operationsSinceLastCheck++,!(this.operationsSinceLastCheck<this.healthCheckFrequency)&&(this.operationsSinceLastCheck=0,this.ensureHealthMonitor(),this.healthMonitor)))try{this.lastHealthReport=this.healthMonitor.checkHealth(this.backend),this.lastHealthReport.healthy||console.warn(`[HNSW-Health] Index "${this.indexName}" health check failed: ${this.lastHealthReport.alerts.length} alert(s). Coherence: ${this.lastHealthReport.metrics.coherenceScore.toFixed(3)}`)}catch(e){console.warn(`[HNSW-Health] Health check error for "${this.indexName}":`,e)}}ensureHealthMonitor(){if(!this.healthMonitorLoaded){this.healthMonitorLoaded=!0;try{let e=(te(),W(ee));this.healthMonitor=e.createHnswHealthMonitor()}catch(e){process.env.DEBUG&&console.debug("[HNSW-Health] Monitor module unavailable:",e instanceof Error?e.message:e),this.healthMonitor=null}}}static createBackend(e){if(D())try{return{backend:new w(e),isNative:!0}}catch(r){r instanceof b?console.info(`[HNSW] Native backend unavailable, falling back to JS: ${r.message}`):console.warn("[HNSW] Unexpected error creating native backend, falling back to JS:",r)}return{backend:new S(e),isNative:!1}}static create(e,r){let t=p.get(e);if(t instanceof i)return t;let n=new i(e,r);return p.set(e,n),n}static get(e){let r=p.get(e);return r instanceof i?r:void 0}static close(e){let r=p.get(e);r instanceof i&&r.dispose(),p.delete(e)}static closeAll(){for(let[e]of p)i.close(e);p.clear()}static listIndexes(){return Array.from(p.keys())}}});export{re as a,ye as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.10");process.exit(0)}
2
+ import{a as ae,b as oe}from"./chunk-GJMLK5UT.js";import{S as ie,i as D,p as $}from"./chunk-XLZYRTNO.js";import{b as g,d as ne,f as W}from"./chunk-OY2AHLSF.js";var I,E=g(()=>{"use strict";I={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}});function se(){if(z)return A!==null;try{let i=(oe(),W(ae));if(A=i.differentiableSearch,P=i.init,P)try{P()}catch{}return z=!0,!0}catch{return z=!0,!1}}function j(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function ce(i,e,r,t){let n=r*t;if(n===0)return 0;let a=0,o=Math.min(i.length,e.length);for(let c=0;c<o;c++)a+=i[c]*e[c];return a/n}function q(i,e){let r=0,t=Math.min(i.length,e.length);for(let n=0;n<t;n++){let a=i[n]-e[n];r+=a*a}return Math.sqrt(r)}function le(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}var A,P,z,S,B=g(()=>{"use strict";E();A=null,P=null,z=!1;S=class{config;entries=[];idToIndex=new Map;hasRuvector=!1;loaded=!1;constructor(e){this.config={...I,...e}}ensureLoaded(){this.loaded||(this.hasRuvector=se(),this.loaded=!0)}normalizeVector(e){return e.length===this.config.dimensions?e:le(e,this.config.dimensions)}add(e,r,t){this.ensureLoaded();let n=this.normalizeVector(r),a=j(n);if(this.idToIndex.has(e)){let c=this.idToIndex.get(e);this.entries[c]={id:e,vector:n,norm:a,metadata:t};return}let o=this.entries.length;this.entries.push({id:e,vector:n,norm:a,metadata:t}),this.idToIndex.set(e,o)}search(e,r){if(this.ensureLoaded(),this.entries.length===0)return[];let t=this.normalizeVector(e),n=j(t),a=Math.min(r,this.entries.length),o=this.entries.length>0?this.entries[0].vector.length:0,c=t.length===o;if(this.config.metric==="cosine")return this.bruteForcSearch(t,n,a);if(this.hasRuvector&&c&&A)try{let s=this.entries.map(u=>u.vector),l=A(t,s,a,1).indices.map(u=>{let h=this.entries[u],m=-q(t,h.vector);return{id:h.id,score:m,metadata:h.metadata}});return l.sort((u,h)=>h.score-u.score),l}catch{}return this.bruteForcSearch(t,n,a)}bruteForcSearch(e,r,t){let n=[];for(let a of this.entries){let o;this.config.metric==="cosine"?o=ce(e,a.vector,r,a.norm):o=-q(e,a.vector),n.push({id:a.id,score:o,metadata:a.metadata})}return n.sort((a,o)=>o.score-a.score),n.slice(0,t)}remove(e){let r=this.idToIndex.get(e);if(r===void 0)return!1;let t=this.entries.length-1;if(r!==t){let n=this.entries[t];this.entries[r]=n,this.idToIndex.set(n.id,r)}return this.entries.pop(),this.idToIndex.delete(e),!0}size(){return this.entries.length}dimensions(){return this.config.dimensions}recall(){return this.hasRuvector,1}isRuvectorAvailable(){return this.ensureLoaded(),this.hasRuvector}getConfig(){return{...this.config}}clear(){this.entries=[],this.idToIndex.clear()}dispose(){this.clear()}}});import{createRequire as he}from"module";function de(){if(U){if(k)return k;throw new b(O??"Unknown load error")}U=!0;try{let i=ue("hnswlib-node");if(!i.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return k=i,k}catch(i){let e=i instanceof Error?i.message:String(i);throw O=e,new b(e)}}function me(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}function K(i){let e=new Array(i.length);for(let r=0;r<i.length;r++)e[r]=i[r];return e}var ue,b,k,U,O,J,w,Q=g(()=>{"use strict";E();ue=he(import.meta.url),b=class extends Error{constructor(e){super(`Native HNSW backend unavailable: ${e}`),this.name="NativeHnswUnavailableError"}},k=null,U=!1,O=null;J=1e4,w=class{config;nativeIndex=null;currentMaxElements=J;liveIds=new Set;metadataStore=new Map;_metrics={totalSearches:0,totalAdds:0,totalRemoves:0,avgSearchLatencyMs:0,maxSearchLatencyMs:0,lastSearchLatencyMs:0,fallbackSearchCount:0,bruteForceSearchCount:0,nativeSearchCount:0,fallbackRate:0,allSearchesBruteForce:!1};constructor(e){this.config={...I,...e},this.nativeIndex=this.createFreshIndex()}createFreshIndex(){let e=de(),r=this.config.metric==="euclidean"?"l2":"cosine";try{let t=new e.HierarchicalNSW(r,this.config.dimensions);return t.initIndex(this.currentMaxElements,this.config.M,this.config.efConstruction,100,!0),t.setEf(this.config.efSearch),t}catch(t){let n=t instanceof Error?t.message:String(t);throw new b(`HierarchicalNSW init failed: ${n}`)}}add(e,r,t){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");let n=this.normalizeVector(r);if(!this.liveIds.has(e)&&this.liveIds.size>=this.currentMaxElements){let a=this.currentMaxElements*2;this.nativeIndex.resizeIndex(a),this.currentMaxElements=a}this.nativeIndex.addPoint(K(n),e,!0),this.liveIds.add(e),t?this.metadataStore.set(e,t):this.metadataStore.delete(e),this._metrics.totalAdds++}search(e,r){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");if(this.liveIds.size===0||r<=0)return[];let t=performance.now(),n=this.normalizeVector(e),a=Math.min(r,this.liveIds.size),o=Math.min(this.liveIds.size,Math.max(a,this.config.efSearch)*2),c=this.nativeIndex.searchKnn(K(n),o),s=this.config.metric==="cosine",d=new Map;for(let h=0;h<c.neighbors.length;h++){let m=c.neighbors[h];if(!this.liveIds.has(m))continue;let x=c.distances[h],f=s?1-x:-x,G=d.get(m);(G===void 0||f>G.score)&&d.set(m,{id:m,score:f,metadata:this.metadataStore.get(m)})}let l=Array.from(d.values());l.sort((h,m)=>m.score-h.score),l.length>a&&(l.length=a);let u=performance.now()-t;return this.updateSearchMetrics(u),this._metrics.nativeSearchCount=this._metrics.totalSearches,u>50&&console.warn(`[NativeHNSW] search took ${u.toFixed(1)}ms (k=${r}, results=${l.length})`),l}remove(e){if(!this.nativeIndex||!this.liveIds.has(e))return!1;try{this.nativeIndex.markDelete(e)}catch{return!1}return this.liveIds.delete(e),this.metadataStore.delete(e),this._metrics.totalRemoves++,!0}size(){return this.liveIds.size}dimensions(){return this.config.dimensions}recall(){return .99}getMetrics(){return{...this._metrics}}get lastSearchLatencyMs(){return this._metrics.lastSearchLatencyMs}getConfig(){return{...this.config}}clear(){this.nativeIndex&&(this.liveIds.clear(),this.metadataStore.clear(),this.currentMaxElements=J,this.nativeIndex=this.createFreshIndex())}dispose(){this.liveIds.clear(),this.metadataStore.clear(),this.nativeIndex=null}isNativeAvailable(){return this.nativeIndex!==null}normalizeVector(e){return e.length===this.config.dimensions?e:me(e,this.config.dimensions)}updateSearchMetrics(e){this._metrics.totalSearches++,this._metrics.lastSearchLatencyMs=e,e>this._metrics.maxSearchLatencyMs&&(this._metrics.maxSearchLatencyMs=e);let r=this._metrics.totalSearches;this._metrics.avgSearchLatencyMs=this._metrics.avgSearchLatencyMs*((r-1)/r)+e/r}}});function X(i,e){let r=Array.from({length:e},()=>new Float64Array(e));for(let t=0;t<e;t++){let n=i[t].length;r[t][t]=n;for(let a of i[t])r[t][a]=-1}return r}function N(i,e){let r=e.length,t=new Float64Array(r);for(let n=0;n<r;n++){let a=i[n].length;t[n]=a*e[n];for(let o of i[n])t[n]-=e[o]}return t}function H(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function R(i){let e=H(i);if(e>0)for(let r=0;r<i.length;r++)i[r]/=e}function v(i,e){let r=0;for(let t=0;t<i.length;t++)r+=i[t]*e[t];for(let t=0;t<i.length;t++)i[t]-=r*e[t]}function y(i,e,r=100,t=1e-6){if(e<=1)return 0;if(e===2)return i[0].includes(1)?2:0;let n=new Float64Array(e).fill(1/Math.sqrt(e)),a=new Float64Array(e);for(let l=0;l<e;l++)a[l]=Math.random()-.5;v(a,n),R(a);let o=0;for(let l=0;l<30;l++){let u=N(i,a);if(v(u,n),o=H(u),o>0)for(let h=0;h<e;h++)a[h]=u[h]/o}if(o<t)return 0;let c=new Float64Array(e);for(let l=0;l<e;l++)c[l]=Math.random()-.5;v(c,n),R(c);let s=0;for(let l=0;l<r;l++){let u=N(i,c),h=new Float64Array(e);for(let f=0;f<e;f++)h[f]=o*c[f]-u[f];v(h,n);let m=H(h);if(m<t)break;let x=m;for(let f=0;f<e;f++)c[f]=h[f]/m;if(Math.abs(x-s)<t)break;s=x}let d=o-s;return Math.max(0,d)}function F(i,e,r=100,t=1e-6){return y(i,e,r,t)}function C(i,e,r=50,t){if(e<=1)return 0;let n=t??y(i,e);if(n<1e-10)return 1/0;let o=2*Math.max(...i.map(d=>d.length),1),s=2*(Math.log(o/n)/(o-n));return Math.max(0,s)}function M(i,e,r){let t=1-Math.exp(-i/.05),n=1-Math.exp(-e/.5),a=r===1/0?0:1/(1+r/5),o=.4*t+.3*n+.3*a;return Math.max(0,Math.min(1,o))}var _=g(()=>{"use strict"});var ee={};ne(ee,{ALERT_THRESHOLDS:()=>fe,DEFAULT_HNSW_HEALTH_CONFIG:()=>Y,HnswHealthMonitor:()=>L,_resetNativeLoader:()=>be,approximateFiedlerValue:()=>y,approximateSpectralGap:()=>F,buildAdjacencyFromIndex:()=>Z,buildLaplacian:()=>X,computeCoherenceScore:()=>M,createHnswHealthMonitor:()=>ge,deflateVector:()=>v,estimateEffectiveResistance:()=>C,laplacianMultiply:()=>N,normalizeInPlace:()=>R,vectorNorm:()=>H});function pe(){return V?T:(V=!0,T=null,null)}function be(){T=null,V=!1}function Z(i,e=16,r){let t=i.size();if(t===0)return{adjacency:[],nodeCount:0,adjacencySource:"approximate"};let n=Array.from({length:t},()=>[]),a=Math.min(e,t-1);if(a===0)return{adjacency:n,nodeCount:t,adjacencySource:"approximate"};if(r&&r.size>0){let o=Array.from(r.keys()).slice(0,t),c=new Map;for(let s=0;s<o.length;s++)c.set(o[s],s);for(let s=0;s<o.length;s++){let d=r.get(o[s]);if(!d)continue;let l=i.search(d,a+1);for(let u of l){if(u.id===o[s])continue;let h=c.get(u.id);h!==void 0&&(n[s].includes(h)||n[s].push(h),n[h].includes(s)||n[h].push(s))}}return{adjacency:n,nodeCount:t,adjacencySource:"actual-search"}}console.warn("[HnswHealthMonitor] No stored vectors provided \u2014 using approximate circular adjacency. Pass stored vectors for accurate health metrics.");for(let o=0;o<t;o++)for(let c=0;c<a;c++){let s=(o+c+1)%t;n[o].includes(s)||n[o].push(s),n[s].includes(o)||n[s].push(o)}return{adjacency:n,nodeCount:t,adjacencySource:"approximate"}}function ge(i){return new L(i)}var Y,fe,T,V,L,te=g(()=>{"use strict";_();_();Y={fiedlerThreshold:.01,spectralGapThreshold:.1,resistanceThreshold:10,coherenceThreshold:.3,maxPowerIterations:100,convergenceTolerance:1e-6,resistanceSampleSize:50,maxHistoryEntries:200,minIndexSize:3},fe={FragileIndex:.01,PoorExpansion:.1,HighResistance:10,LowCoherence:.3},T=null,V=!1;L=class{config;alerts=[];history=[];lastReport=null;useNative=!1;nativeChecked=!1;constructor(e){this.config={...Y,...e}}checkHealth(e){let r=performance.now(),t=e.size();if(t<this.config.minIndexSize)return this.createSmallIndexReport(t,performance.now()-r);this.nativeChecked||(this.nativeChecked=!0,this.useNative=pe()!==null);let{adjacency:n,nodeCount:a,adjacencySource:o}=Z(e),c=this.useNative?this.computeNativeMetrics(n):this.computeApproximateMetrics(n,a),s=this.generateAlerts(c);this.alerts.length=0,this.alerts.push(...s);let d=performance.now()-r,l={healthy:s.length===0,metrics:c,alerts:s,indexSize:t,usedNativeBackend:this.useNative,adjacencySource:o,checkDurationMs:d,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:c.coherenceScore,fiedlerValue:c.fiedlerValue,indexSize:t,healthy:l.healthy,timestamp:l.checkedAt}),this.lastReport=l,l}getAlerts(){return[...this.alerts]}getMetricsHistory(e){let r=[...this.history];return e!==void 0&&e<r.length?r.slice(-e):r}isHealthy(){return this.lastReport===null?!0:this.lastReport.healthy}getLastReport(){return this.lastReport}clearHistory(){this.history.length=0,this.alerts.length=0,this.lastReport=null}computeNativeMetrics(e){let r=T,t=r.computeFiedlerValue(e),n=r.computeSpectralGap(e),a=r.computeEffectiveResistance(e),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}computeApproximateMetrics(e,r){let t=y(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),n=F(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),a=C(e,r,this.config.resistanceSampleSize,t),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}generateAlerts(e){let r=[],t=new Date;return e.fiedlerValue<this.config.fiedlerThreshold&&r.push({type:"FragileIndex",message:`Fiedler value ${e.fiedlerValue.toFixed(6)} is below threshold ${this.config.fiedlerThreshold}. The index graph has weak algebraic connectivity.`,value:e.fiedlerValue,threshold:this.config.fiedlerThreshold,timestamp:t}),e.spectralGap<this.config.spectralGapThreshold&&r.push({type:"PoorExpansion",message:`Spectral gap ${e.spectralGap.toFixed(6)} is below threshold ${this.config.spectralGapThreshold}. The index graph has poor expansion properties.`,value:e.spectralGap,threshold:this.config.spectralGapThreshold,timestamp:t}),e.effectiveResistance>this.config.resistanceThreshold&&r.push({type:"HighResistance",message:`Average effective resistance ${e.effectiveResistance.toFixed(4)} exceeds threshold ${this.config.resistanceThreshold}. Nodes are poorly connected.`,value:e.effectiveResistance,threshold:this.config.resistanceThreshold,timestamp:t}),e.coherenceScore<this.config.coherenceThreshold&&r.push({type:"LowCoherence",message:`Coherence score ${e.coherenceScore.toFixed(4)} is below threshold ${this.config.coherenceThreshold}. Overall index health is degraded.`,value:e.coherenceScore,threshold:this.config.coherenceThreshold,timestamp:t}),r}createSmallIndexReport(e,r){let t={fiedlerValue:e>0?1:0,spectralGap:e>0?1:0,effectiveResistance:e>0?.5:0,coherenceScore:e>0?1:0},n={healthy:!0,metrics:t,alerts:[],indexSize:e,usedNativeBackend:!1,adjacencySource:"approximate",checkDurationMs:r,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:t.coherenceScore,fiedlerValue:t.fiedlerValue,indexSize:e,healthy:!0,timestamp:n.checkedAt}),this.lastReport=n,n}addHistoryPoint(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}}});var ve,p,re,ye=g(()=>{B();Q();ie();ve={patterns:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},"qe-memory":{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},learning:{dimensions:384,M:16,efConstruction:200,efSearch:50,metric:"cosine"},coverage:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}},p=new Map,re=class i{backend;_isNativeBackend;indexName;stringToNumericId=new Map;numericToStringId=new Map;nextAutoId=0;healthMonitor=null;healthMonitorLoaded=!1;operationsSinceLastCheck=0;healthCheckFrequency=100;lastHealthReport=null;constructor(e,r){this.indexName=e;let n={...ve[e]??{},...r},{backend:a,isNative:o}=i.createBackend(n);this.backend=a,this._isNativeBackend=o}add(e,r,t){this.backend.add(e,r,t),this.maybeRunHealthCheck()}search(e,r){let t=performance.now(),n=this.backend.search(e,r),a=performance.now()-t;return a>50&&console.warn(`[HNSW] search took ${a.toFixed(1)}ms (k=${r}, results=${n.length})`),this._lastSearchLatencyMs=a,n}_lastSearchLatencyMs=0;get lastSearchLatencyMs(){return this._lastSearchLatencyMs}remove(e){return this.backend.remove(e)}size(){return this.backend.size()}dimensions(){return this.backend.dimensions()}recall(){return this.backend.recall()}addByStringId(e,r){let t=this.stringToNumericId.get(e);t!==void 0?this.backend.remove(t):(t=this.nextAutoId++,this.stringToNumericId.set(e,t),this.numericToStringId.set(t,e)),this.backend.add(t,new Float32Array(r))}searchByArray(e,r){return this.backend.search(new Float32Array(e),r).map(n=>({id:this.numericToStringId.get(n.id)??String(n.id),score:n.score}))}removeByStringId(e){let r=this.stringToNumericId.get(e);if(r===void 0)return!1;let t=this.backend.remove(r);return t&&(this.stringToNumericId.delete(e),this.numericToStringId.delete(r)),t}clear(){this.backend.clear?.(),this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}dispose(){try{this.backend.dispose?.()}catch{}this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}isRuvectorAvailable(){return this.backend instanceof S?this.backend.isRuvectorAvailable():this.backend instanceof w?this.backend.isNativeAvailable():!1}isNativeBackend(){return this._isNativeBackend}getName(){return this.indexName}setHealthCheckFrequency(e){this.healthCheckFrequency=Math.max(1,e)}getHealthCheckFrequency(){return this.healthCheckFrequency}getLastHealthReport(){return this.lastHealthReport}getHealthMonitor(){return this.healthMonitor}maybeRunHealthCheck(){if($()&&(this.operationsSinceLastCheck++,!(this.operationsSinceLastCheck<this.healthCheckFrequency)&&(this.operationsSinceLastCheck=0,this.ensureHealthMonitor(),this.healthMonitor)))try{this.lastHealthReport=this.healthMonitor.checkHealth(this.backend),this.lastHealthReport.healthy||console.warn(`[HNSW-Health] Index "${this.indexName}" health check failed: ${this.lastHealthReport.alerts.length} alert(s). Coherence: ${this.lastHealthReport.metrics.coherenceScore.toFixed(3)}`)}catch(e){console.warn(`[HNSW-Health] Health check error for "${this.indexName}":`,e)}}ensureHealthMonitor(){if(!this.healthMonitorLoaded){this.healthMonitorLoaded=!0;try{let e=(te(),W(ee));this.healthMonitor=e.createHnswHealthMonitor()}catch(e){process.env.DEBUG&&console.debug("[HNSW-Health] Monitor module unavailable:",e instanceof Error?e.message:e),this.healthMonitor=null}}}static createBackend(e){if(D())try{return{backend:new w(e),isNative:!0}}catch(r){r instanceof b?console.info(`[HNSW] Native backend unavailable, falling back to JS: ${r.message}`):console.warn("[HNSW] Unexpected error creating native backend, falling back to JS:",r)}return{backend:new S(e),isNative:!1}}static create(e,r){let t=p.get(e);if(t instanceof i)return t;let n=new i(e,r);return p.set(e,n),n}static get(e){let r=p.get(e);return r instanceof i?r:void 0}static close(e){let r=p.get(e);r instanceof i&&r.dispose(),p.delete(e)}static closeAll(){for(let[e]of p)i.close(e);p.clear()}static listIndexes(){return Array.from(p.keys())}}});export{re as a,ye as b};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.9");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.10");process.exit(0)}
2
2
  var o={domain:"test-generation",bestPractices:["Follow Arrange-Act-Assert (AAA) pattern for clear test structure","One logical assertion per test - test one behavior at a time","Use descriptive test names: should_returnValue_when_condition","Mock external dependencies to isolate unit under test","Test edge cases and boundary conditions, not just happy paths","Keep tests deterministic - avoid time-dependent assertions","Use test data builders or factories for complex objects","Prefer integration tests for workflows, unit tests for logic","Maintain test independence - no shared mutable state between tests","Write failing test first (TDD Red) before implementation"],antiPatterns:[{name:"God Test",description:"A single test that verifies too many behaviors",reason:"Hard to diagnose failures, brittle, slow to run",alternative:"Split into focused tests, each verifying one behavior",detection:"expect.*expect.*expect.*expect.*expect"},{name:"Mystery Guest",description:"Test relies on external data files or state not visible in test",reason:"Tests are hard to understand and maintain",alternative:"Make test data explicit within the test or use fixtures"},{name:"Eager Test",description:"Test that verifies more than needed for the current behavior",reason:"Creates unnecessary coupling, breaks easily",alternative:"Only assert what is necessary for this specific test case"},{name:"Flaky Assertion",description:"Assertions that depend on timing, order, or external state",reason:"Creates unreliable test suite, erodes trust",alternative:"Use deterministic assertions, mock time/random",detection:"setTimeout|Date\\.now|Math\\.random"},{name:"Test Code Duplication",description:"Same setup or assertion code repeated across tests",reason:"Maintenance burden, inconsistency risk",alternative:"Extract to beforeEach, helpers, or fixtures"}],frameworkGuidance:{jest:["Use describe blocks to group related tests","Prefer toEqual for deep equality, toBe for primitives","Use jest.mock() at module level for consistent mocking","Use jest.spyOn for partial mocking of objects","Enable --coverage to track test coverage"],vitest:["Use vi.mock() for module mocking","Prefer vi.fn() over jest.fn() syntax","Use vitest/ui for interactive test debugging","Enable browser mode for component tests","Use inline snapshots for small expected values"],mocha:["Use beforeEach/afterEach for setup/teardown","Combine with chai for assertions","Use sinon for spies, stubs, and mocks","Set appropriate timeouts for async tests"],pytest:["Use fixtures for reusable test setup","Use parametrize for data-driven tests","Use conftest.py for shared fixtures","Use pytest.raises for exception testing","Use pytest-cov for coverage reporting"],junit:["Use @BeforeEach and @AfterEach for setup/teardown","Use @DisplayName for readable test names","Use @ParameterizedTest for data-driven tests","Use Mockito for mocking dependencies"],testng:["Use @BeforeMethod and @AfterMethod appropriately","Use @DataProvider for parameterized tests","Configure test groups for selective execution"],playwright:["Use page.locator() for resilient element selection","Use expect(locator) for auto-waiting assertions","Use page.waitForLoadState for navigation","Use test.describe for grouping tests","Use fixtures for reusable browser contexts"],cypress:["Use cy.intercept() for API mocking","Avoid conditional testing - use deterministic state","Use data-cy attributes for stable selectors","Use cy.within() for scoped queries","Prefer cy.contains() for text-based selection"],selenium:["Use explicit waits over implicit waits","Use Page Object Model for maintainability","Handle stale element references with retry logic","Clean up browser state between tests"]},languageGuidance:{typescript:["Use type assertions in tests for better IDE support","Create typed test fixtures and builders","Use satisfies operator for test data validation","Mock types with ts-mockito or typed mocking libs"],javascript:["Use JSDoc comments for test documentation","Consider TypeScript for larger test suites","Use ESLint with testing plugins"],python:["Use type hints in test functions","Use dataclasses for test data","Follow PEP 8 naming: test_should_do_something"],java:["Use AssertJ for fluent assertions","Use Lombok for test data classes","Follow naming: shouldDoSomething_whenCondition"],go:["Use table-driven tests for multiple cases","Use testify for assertions and mocking","Place tests in _test.go files"],rust:["Use #[test] attribute for test functions","Use assert!, assert_eq!, assert_ne! macros","Place unit tests in same file with #[cfg(test)]"],csharp:["Use xUnit or NUnit for testing","Use FluentAssertions for readable assertions","Use Moq for mocking interfaces"],kotlin:["Use kotest for BDD-style testing","Use MockK for Kotlin-first mocking","Use data classes for test fixtures"]},examples:[{title:"Unit Test Template (TypeScript + Vitest)",description:"Standard AAA pattern for unit tests",content:`describe('UserService', () => {
3
3
  describe('createUser', () => {
4
4
  it('should create user with valid data', async () => {
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.9");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.10");process.exit(0)}
2
2
  var o=!1;function r(t){if(!o){for(let e of["ALTER TABLE routing_outcomes ADD COLUMN exploration INTEGER NOT NULL DEFAULT 0","ALTER TABLE routing_outcomes ADD COLUMN criticality REAL","ALTER TABLE routing_outcomes ADD COLUMN q_weight REAL"])try{t.prepare(e).run()}catch{}try{t.prepare("CREATE INDEX IF NOT EXISTS idx_routing_outcomes_exploration ON routing_outcomes(exploration)").run()}catch{}o=!0}}export{r as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.9");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.10");process.exit(0)}
2
2
  var l=["var-to-const","add-types","remove-console","promise-to-async","cjs-to-esm","func-to-arrow"],p={"var-to-const":{type:"var-to-const",name:"Var to Const/Let",description:"Convert var declarations to const (if not reassigned) or let (if reassigned)",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"add-types":{type:"add-types",name:"Add TypeScript Types",description:"Add TypeScript type annotations to function parameters and return types",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"remove-console":{type:"remove-console",name:"Remove Console Statements",description:"Remove all console.log, console.warn, console.error, etc. statements",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"promise-to-async":{type:"promise-to-async",name:"Promise to Async/Await",description:"Convert Promise .then()/.catch() chains to async/await syntax",complexity:"complex",wasmAvailable:!0,typicalLatencyMs:10},"cjs-to-esm":{type:"cjs-to-esm",name:"CommonJS to ES Modules",description:"Convert require() calls to import statements and module.exports to export",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"func-to-arrow":{type:"func-to-arrow",name:"Function to Arrow",description:"Convert function declarations and expressions to arrow functions",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:3}},u={enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7,transforms:[],maxFileSizeBytes:1024*1024,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},t=class extends Error{constructor(e,s,o){super(e);this.code=s;this.cause=o;this.name="AgentBoosterError"}code;cause},a=class extends t{constructor(e,s,o){super(e,"TRANSFORM_ERROR",o);this.transformType=s;this.name="TransformError"}transformType},i=class extends t{constructor(r="WASM module is not available",e){super(r,"WASM_UNAVAILABLE",e),this.name="WasmUnavailableError"}},c=class extends t{constructor(e,s,o){super(e,"TRANSFORM_TIMEOUT");this.transformType=s;this.timeoutMs=o;this.name="TransformTimeoutError"}transformType;timeoutMs},m=class extends t{constructor(e,s,o){super(`File ${e} is too large (${s} bytes, max ${o} bytes)`,"FILE_TOO_LARGE");this.filePath=e;this.sizeBytes=s;this.maxSizeBytes=o;this.name="FileTooLargeError"}filePath;sizeBytes;maxSizeBytes};export{l as a,p as b,u as c,a as d,i as e,c as f,m as g};
@@ -0,0 +1,2 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.10");process.exit(0)}
2
+ import{a as e,b as g,e as t}from"./chunk-ATHWDAXB.js";import{d as r}from"./chunk-N6PIIK6G.js";import{b as o}from"./chunk-OY2AHLSF.js";var L=o(()=>{"use strict";e();g();t();r()});export{L as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.9");process.exit(0)}
2
- import{a as r,h as n}from"./chunk-XUIA5KMS.js";var a={claude:"metered-api","claude-code":"subscription",codex:"subscription",openai:"metered-api",openrouter:"metered-api",gemini:"metered-api","azure-openai":"metered-api",bedrock:"metered-api",cognitum:"metered-capped",ollama:"local"};function o(e){return r(e)?a[e]:void 0}function p(e){return e.billingMode??o(e.type)??"metered-api"}function c(e){return o(e)??"metered-api"}function g(e,t){switch(t){case"metered-api":return`\u26A0\uFE0F LLM provider "${e}" bills a pay-per-token API key (not your Claude subscription) and has no server-side spend cap. Set a budget with --max-budget-usd / AQE_MAX_BUDGET_USD, or use AQE_LLM_PROVIDER=claude-code to run on your Claude Code subscription instead.`;case"metered-capped":return`\u2139\uFE0F LLM provider "${e}" bills per-token but enforces a server-side hard spend cap; it will pause at the cap rather than overspend.`;case"subscription":{let i=n(e);if(i){let d=i.detail?`declared by ${i.detail}`:`declared by ${i.source==="config"?"config":"the registering caller"}`;return`\u2139\uFE0F LLM provider "${e}" is an external provider that reports subscription billing (${d}) \u2014 AQE does not verify this. It draws on that host's own plan, not on your Claude Code or ChatGPT subscription.`}return`\u2139\uFE0F LLM provider "${e}" runs on your ${e==="codex"?"ChatGPT":"Claude Code"} subscription (shared plan usage). Worst case is hitting your plan's rate limit and pausing \u2014 no per-token API charges.`}case"local":return}}export{p as a,c as b,g as c};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.10");process.exit(0)}
2
+ import{a as r,h as n}from"./chunk-WDQ7IEZY.js";var a={claude:"metered-api","claude-code":"subscription",codex:"subscription",openai:"metered-api",openrouter:"metered-api",gemini:"metered-api","azure-openai":"metered-api",bedrock:"metered-api",cognitum:"metered-capped",ollama:"local"};function o(e){return r(e)?a[e]:void 0}function p(e){return e.billingMode??o(e.type)??"metered-api"}function c(e){return o(e)??"metered-api"}function g(e,t){switch(t){case"metered-api":return`\u26A0\uFE0F LLM provider "${e}" bills a pay-per-token API key (not your Claude subscription) and has no server-side spend cap. Set a budget with --max-budget-usd / AQE_MAX_BUDGET_USD, or use AQE_LLM_PROVIDER=claude-code to run on your Claude Code subscription instead.`;case"metered-capped":return`\u2139\uFE0F LLM provider "${e}" bills per-token but enforces a server-side hard spend cap; it will pause at the cap rather than overspend.`;case"subscription":{let i=n(e);if(i){let d=i.detail?`declared by ${i.detail}`:`declared by ${i.source==="config"?"config":"the registering caller"}`;return`\u2139\uFE0F LLM provider "${e}" is an external provider that reports subscription billing (${d}) \u2014 AQE does not verify this. It draws on that host's own plan, not on your Claude Code or ChatGPT subscription.`}return`\u2139\uFE0F LLM provider "${e}" runs on your ${e==="codex"?"ChatGPT":"Claude Code"} subscription (shared plan usage). Worst case is hitting your plan's rate limit and pausing \u2014 no per-token API charges.`}case"local":return}}export{p as a,c as b,g as c};