agentic-qe 3.13.12 → 3.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (415) hide show
  1. package/.claude/skills/qe-court/SKILL.md +4 -4
  2. package/.claude/skills/qe-court/config-schema.json +38 -0
  3. package/.claude/skills/qe-court/evals/qe-court.yaml +8 -8
  4. package/.claude/skills/skills-manifest.json +1 -1
  5. package/CHANGELOG.md +53 -0
  6. package/assets/skills/qe-court/SKILL.md +4 -4
  7. package/assets/skills/qe-court/config-schema.json +38 -0
  8. package/assets/skills/qe-court/evals/qe-court.yaml +8 -8
  9. package/assets/skills/skills-manifest.json +1 -1
  10. package/dist/cli/brain-commands.d.ts +1 -0
  11. package/dist/cli/brain-commands.js +1 -0
  12. package/dist/cli/bundle.js +5 -5
  13. package/dist/cli/chunks/adapter-3VBXL7DO.js +2 -0
  14. package/dist/cli/chunks/{agent-booster-wasm-7I7LZFNC.js → agent-booster-wasm-JZO6VUW4.js} +2 -2
  15. package/dist/cli/chunks/{agent-handler-QZZT52BH.js → agent-handler-534KFGEJ.js} +2 -2
  16. package/dist/cli/chunks/{agent-memory-branch-MLQS5Y26.js → agent-memory-branch-B7KWLWY4.js} +2 -2
  17. package/dist/cli/chunks/aqe-learning-engine-NXRNKJNA.js +2 -0
  18. package/dist/cli/chunks/{arena-IM4CP6LP.js → arena-7CCD3S3I.js} +2 -2
  19. package/dist/cli/chunks/{arena-WRIY37EJ.js → arena-OW5MELJX.js} +4 -4
  20. package/dist/cli/chunks/{audit-BSAQ4EFN.js → audit-BHVKN4E2.js} +3 -3
  21. package/dist/cli/chunks/base-F6GMOKU2.js +2 -0
  22. package/dist/cli/chunks/{better-sqlite3-X2XZUXWZ.js → better-sqlite3-P5FA6WFK.js} +2 -2
  23. package/dist/cli/chunks/brain-handler-WNW5LOV7.js +90 -0
  24. package/dist/cli/chunks/{branch-enumerator-NI4Q7DSJ.js → branch-enumerator-TVZ2ODKH.js} +2 -2
  25. package/dist/cli/chunks/{browser-PXBLORUZ.js → browser-TCEB2W2F.js} +2 -2
  26. package/dist/cli/chunks/browser-workflow-QRDC46LR.js +2 -0
  27. package/dist/cli/chunks/{chunk-4FVOJBEU.js → chunk-2D7UBX5S.js} +1 -1
  28. package/dist/cli/chunks/{chunk-NG6A7LCG.js → chunk-2HYVOX6N.js} +1 -1
  29. package/dist/cli/chunks/{chunk-MGKH4LCM.js → chunk-2NO4H35K.js} +1 -1
  30. package/dist/cli/chunks/{chunk-UC4EIULB.js → chunk-2O4DDPEA.js} +19 -19
  31. package/dist/cli/chunks/{chunk-IT5QIUUA.js → chunk-3EM2MK3Z.js} +2 -2
  32. package/dist/cli/chunks/chunk-3GUO4ERR.js +24 -0
  33. package/dist/cli/chunks/{chunk-XIKYUBIV.js → chunk-3JIJBR4V.js} +2 -2
  34. package/dist/cli/chunks/{chunk-NL2SCAGJ.js → chunk-3QT6S3A3.js} +3 -3
  35. package/dist/cli/chunks/{chunk-SOS37ECY.js → chunk-3RYTAYR6.js} +1 -1
  36. package/dist/cli/chunks/chunk-43GPSYAL.js +14 -0
  37. package/dist/cli/chunks/{chunk-IPDM3CAK.js → chunk-4FEJEVG7.js} +1 -1
  38. package/dist/cli/chunks/{chunk-M3354CE4.js → chunk-4MK2G6TK.js} +2 -2
  39. package/dist/cli/chunks/{chunk-AM42ROKZ.js → chunk-4XTHRAUV.js} +1 -1
  40. package/dist/cli/chunks/{chunk-LRO74LPA.js → chunk-4ZVGSVHV.js} +4 -4
  41. package/dist/cli/chunks/{chunk-I5SXLV7D.js → chunk-52DFCV57.js} +2 -2
  42. package/dist/cli/chunks/{chunk-WYFAPA2G.js → chunk-5LEAGKX5.js} +2 -2
  43. package/dist/cli/chunks/{chunk-OZ53BIY5.js → chunk-5MZF4N4Q.js} +1 -1
  44. package/dist/cli/chunks/{chunk-NDRZZSD5.js → chunk-5VDVYTO5.js} +2 -2
  45. package/dist/cli/chunks/chunk-5XGVSQS2.js +11 -0
  46. package/dist/cli/chunks/{chunk-SXFSJJZF.js → chunk-6AOZU3UN.js} +2 -2
  47. package/dist/cli/chunks/{chunk-2VTX4SYW.js → chunk-6AYO3IR2.js} +2 -2
  48. package/dist/cli/chunks/{chunk-4AITMWFZ.js → chunk-6DPAMYLU.js} +2 -2
  49. package/dist/cli/chunks/{chunk-WE3VKDMK.js → chunk-6IJMD2ZL.js} +3 -3
  50. package/dist/cli/chunks/{chunk-5E76HULA.js → chunk-6IZQSLYZ.js} +2 -2
  51. package/dist/cli/chunks/{chunk-VBHA4SDU.js → chunk-6W42XWLL.js} +2 -2
  52. package/dist/cli/chunks/{chunk-ASWWBNX2.js → chunk-7BOPFN3Y.js} +2 -2
  53. package/dist/cli/chunks/{chunk-SCQNISGS.js → chunk-7OUMJCJT.js} +1 -1
  54. package/dist/cli/chunks/{chunk-M73KM3AZ.js → chunk-7RAB2BZY.js} +160 -26
  55. package/dist/cli/chunks/{chunk-4ANJV6I4.js → chunk-7RVAHJQZ.js} +3 -3
  56. package/dist/cli/chunks/{chunk-VQCLSX7T.js → chunk-A2WZEMWT.js} +1 -1
  57. package/dist/cli/chunks/{chunk-YQOQVSYU.js → chunk-A7SKM6JL.js} +1 -1
  58. package/dist/cli/chunks/chunk-AFGT26NR.js +2 -0
  59. package/dist/cli/chunks/{chunk-JVFZAJ5N.js → chunk-AR6SATU3.js} +2 -2
  60. package/dist/cli/chunks/{chunk-YL2GOJF6.js → chunk-AVLA5PBJ.js} +2 -2
  61. package/dist/cli/chunks/{chunk-R7LGVJMZ.js → chunk-B3H4K7CY.js} +2 -2
  62. package/dist/cli/chunks/{chunk-UWZYXI3R.js → chunk-BQCTO7UB.js} +2 -2
  63. package/dist/cli/chunks/{chunk-HAJG44BD.js → chunk-BZ4QVFP2.js} +2 -2
  64. package/dist/cli/chunks/{chunk-NNLZAVFH.js → chunk-CIUOC5F3.js} +1 -1
  65. package/dist/cli/chunks/{chunk-KRZYWVS3.js → chunk-CIZ6LSNV.js} +2 -2
  66. package/dist/cli/chunks/{chunk-HQWFZQMJ.js → chunk-DDPJUAXQ.js} +2 -2
  67. package/dist/cli/chunks/{chunk-X3JNFQW2.js → chunk-DJITEQYS.js} +2 -2
  68. package/dist/cli/chunks/{chunk-TB2N3CAK.js → chunk-DOWCOZDO.js} +2 -2
  69. package/dist/cli/chunks/{chunk-GJJWXRAD.js → chunk-E4NU4BJA.js} +2 -2
  70. package/dist/cli/chunks/{chunk-H3GAR4SV.js → chunk-E722WNWC.js} +2 -2
  71. package/dist/cli/chunks/chunk-ECTPFCON.js +2 -0
  72. package/dist/cli/chunks/{chunk-4YFXF5AQ.js → chunk-EJ6IP7DE.js} +5 -5
  73. package/dist/cli/chunks/{chunk-AN5CGTTJ.js → chunk-ENGKLFLY.js} +2 -2
  74. package/dist/cli/chunks/{chunk-7A4WTRWI.js → chunk-FF43SRP6.js} +1 -1
  75. package/dist/cli/chunks/{chunk-52VGZJSD.js → chunk-FOHYBR3O.js} +1 -1
  76. package/dist/cli/chunks/{chunk-6KI6LAAZ.js → chunk-FRL3X2QA.js} +2 -2
  77. package/dist/cli/chunks/{chunk-3ASVQILY.js → chunk-GKNDP5VK.js} +2 -2
  78. package/dist/cli/chunks/{chunk-2VY7FL6A.js → chunk-GVEJP5T7.js} +2 -2
  79. package/dist/cli/chunks/{chunk-VD53LBF7.js → chunk-H3YDDKBW.js} +3 -3
  80. package/dist/cli/chunks/{chunk-Z6DSYLAG.js → chunk-H6NFDOMK.js} +1 -1
  81. package/dist/cli/chunks/{chunk-BZIPYXSW.js → chunk-H76TV4UU.js} +3 -3
  82. package/dist/cli/chunks/{chunk-XT473WPO.js → chunk-HJIAVR6P.js} +2 -2
  83. package/dist/cli/chunks/{chunk-MLXLGBQZ.js → chunk-HLNQDRHA.js} +1 -1
  84. package/dist/cli/chunks/{chunk-DGFINXUE.js → chunk-HNKPLVYS.js} +1 -1
  85. package/dist/cli/chunks/{chunk-WXU7FAEB.js → chunk-HQ7243G3.js} +2 -2
  86. package/dist/cli/chunks/{chunk-VA2ORJB5.js → chunk-HQHLHSJO.js} +2 -2
  87. package/dist/cli/chunks/{chunk-2W3D5A4R.js → chunk-I3VHXA2W.js} +2 -2
  88. package/dist/cli/chunks/{chunk-EG73WYAW.js → chunk-IE5LC7MB.js} +2 -2
  89. package/dist/cli/chunks/{chunk-S6WHYOWV.js → chunk-IL4AEB3J.js} +27 -25
  90. package/dist/cli/chunks/{chunk-TWUWLSGQ.js → chunk-IL6QRXRP.js} +6 -6
  91. package/dist/cli/chunks/{chunk-5PNQNBDZ.js → chunk-IQ3JFHZN.js} +1 -1
  92. package/dist/cli/chunks/{chunk-MB2KLJ6Q.js → chunk-IQLRA4FV.js} +1 -1
  93. package/dist/cli/chunks/{chunk-A5RWLPVT.js → chunk-J3XSHJGK.js} +2 -2
  94. package/dist/cli/chunks/{chunk-U5G6OC2C.js → chunk-JAK5UUWH.js} +2 -2
  95. package/dist/cli/chunks/{chunk-E67ZXRG6.js → chunk-JGROLJ33.js} +1 -1
  96. package/dist/cli/chunks/{chunk-VNODKACB.js → chunk-JMKMDSXG.js} +2 -2
  97. package/dist/cli/chunks/{chunk-LXVT6JXO.js → chunk-JRKEBESE.js} +2 -2
  98. package/dist/cli/chunks/{chunk-AKUDUB3O.js → chunk-JTWJR2KY.js} +2 -2
  99. package/dist/cli/chunks/{chunk-IOJ34SXJ.js → chunk-JY4VZ6BN.js} +2 -2
  100. package/dist/cli/chunks/{chunk-AYH3DMW2.js → chunk-K6CGQR5R.js} +1 -1
  101. package/dist/cli/chunks/{chunk-QXO35J6F.js → chunk-KDIZQHG5.js} +2 -2
  102. package/dist/cli/chunks/{chunk-7LATB5IR.js → chunk-KTSCZ7AW.js} +2 -2
  103. package/dist/cli/chunks/{chunk-M7CPJW53.js → chunk-L4C42WYI.js} +2 -2
  104. package/dist/cli/chunks/{chunk-QG5L2JM5.js → chunk-LCSVROU7.js} +10 -10
  105. package/dist/cli/chunks/{chunk-6BSZHNOC.js → chunk-LKR7T3OZ.js} +1 -1
  106. package/dist/cli/chunks/{chunk-GJUGG6UR.js → chunk-LZHTCUCO.js} +2 -2
  107. package/dist/cli/chunks/{chunk-7RVLVIAI.js → chunk-M3HUZD2I.js} +1 -1
  108. package/dist/cli/chunks/{chunk-RP5VFZJO.js → chunk-MO7EITJK.js} +2 -2
  109. package/dist/cli/chunks/{chunk-44NPKZGI.js → chunk-N2YAUDAV.js} +2 -2
  110. package/dist/cli/chunks/{chunk-G6FJHDUG.js → chunk-NDPQ2WPU.js} +1 -1
  111. package/dist/cli/chunks/{chunk-UBOGJHWC.js → chunk-NKWO2X3T.js} +1 -1
  112. package/dist/cli/chunks/{chunk-NJ3QXJ54.js → chunk-NOPVFBQM.js} +2 -2
  113. package/dist/cli/chunks/{chunk-AOOCV56W.js → chunk-NYARYONH.js} +1 -1
  114. package/dist/cli/chunks/{chunk-6KKVMPPR.js → chunk-O2MZZL54.js} +2 -2
  115. package/dist/cli/chunks/{chunk-2JAC57JE.js → chunk-OIYUSWHX.js} +1 -1
  116. package/dist/cli/chunks/{chunk-BODFJ3DC.js → chunk-OONCRNFA.js} +2 -2
  117. package/dist/cli/chunks/{chunk-ZMYV4R32.js → chunk-PEW6FZ47.js} +1 -1
  118. package/dist/cli/chunks/{chunk-42AS3HPO.js → chunk-Q73RRTLE.js} +2 -2
  119. package/dist/cli/chunks/{chunk-IQH2RDN3.js → chunk-QKQZ4IJF.js} +5 -5
  120. package/dist/cli/chunks/{chunk-MYVKTG55.js → chunk-QMMDN4WX.js} +3 -3
  121. package/dist/cli/chunks/chunk-QQCENKCX.js +2 -0
  122. package/dist/cli/chunks/{chunk-7PCIN7UN.js → chunk-QSPRQPEL.js} +2 -2
  123. package/dist/cli/chunks/{chunk-ZSAGRDXA.js → chunk-QZPFUFZG.js} +2 -2
  124. package/dist/cli/chunks/chunk-R2B6EE45.js +2 -0
  125. package/dist/cli/chunks/{chunk-33YZGOT6.js → chunk-R6WJF4D5.js} +2 -2
  126. package/dist/cli/chunks/{chunk-QM4Z7TQH.js → chunk-RGVD6ZUX.js} +1 -1
  127. package/dist/cli/chunks/{chunk-VQD2ELNL.js → chunk-RKUYVVGJ.js} +2 -2
  128. package/dist/cli/chunks/{chunk-5VSS2RBD.js → chunk-S5YVLPXU.js} +2 -2
  129. package/dist/cli/chunks/{chunk-IPZEBALY.js → chunk-SROZXIMT.js} +37 -37
  130. package/dist/cli/chunks/{chunk-GMLRIZ4E.js → chunk-SSV6KSFT.js} +1 -1
  131. package/dist/cli/chunks/{chunk-PVINNJ4P.js → chunk-SUSMHSXT.js} +2 -2
  132. package/dist/cli/chunks/{chunk-KXSUDN46.js → chunk-T3BZAFLP.js} +1 -1
  133. package/dist/cli/chunks/{chunk-MLFELTJX.js → chunk-TGOGCA74.js} +2 -2
  134. package/dist/cli/chunks/{chunk-G45AOQDZ.js → chunk-TKYEP7OR.js} +1 -1
  135. package/dist/cli/chunks/{chunk-KYJBJ56M.js → chunk-TQJE7DNL.js} +2 -2
  136. package/dist/cli/chunks/{chunk-5PI75QYP.js → chunk-TRDEULS7.js} +2 -2
  137. package/dist/cli/chunks/{chunk-OG3DBHIV.js → chunk-U4GZWPKM.js} +2 -2
  138. package/dist/cli/chunks/{chunk-NJ4YVAG7.js → chunk-UI6WSPEK.js} +3 -3
  139. package/dist/cli/chunks/{chunk-4M7YZ2X7.js → chunk-UUJ5VQJM.js} +1 -1
  140. package/dist/cli/chunks/{chunk-UJUK6T4V.js → chunk-VESOYP6A.js} +2 -2
  141. package/dist/cli/chunks/{chunk-7ZVO7I4Q.js → chunk-VOSISOFD.js} +1 -1
  142. package/dist/cli/chunks/{chunk-HRTSYT4N.js → chunk-VPVZHJSU.js} +2 -2
  143. package/dist/cli/chunks/{chunk-66OQ7AB3.js → chunk-VRRG66XB.js} +1 -1
  144. package/dist/cli/chunks/{chunk-4Z4X2ND4.js → chunk-VXU53F7Z.js} +2 -2
  145. package/dist/cli/chunks/{chunk-XM5I7J5S.js → chunk-VYENTZ45.js} +2 -2
  146. package/dist/cli/chunks/chunk-WJXHE52V.js +65 -0
  147. package/dist/cli/chunks/{chunk-3XVZHJQT.js → chunk-WKNWRDA5.js} +1 -1
  148. package/dist/cli/chunks/{chunk-DFLASG3B.js → chunk-WTHAVFIC.js} +1 -1
  149. package/dist/cli/chunks/{chunk-NTALX2YC.js → chunk-WWWX76QB.js} +2 -2
  150. package/dist/cli/chunks/{chunk-L3GBNX7B.js → chunk-XITTURP2.js} +2 -2
  151. package/dist/cli/chunks/{chunk-FI6J3UHJ.js → chunk-XXFKN7LB.js} +1 -1
  152. package/dist/cli/chunks/{chunk-RP2BRRLX.js → chunk-YEAC3DC6.js} +2 -2
  153. package/dist/cli/chunks/{chunk-JTYCOFTD.js → chunk-YKWMKRYB.js} +1 -1
  154. package/dist/cli/chunks/chunk-YKZV7O65.js +2 -0
  155. package/dist/cli/chunks/{chunk-N4OQ4D4V.js → chunk-YW4RNZWT.js} +2 -2
  156. package/dist/cli/chunks/{chunk-P6EFKHNI.js → chunk-ZAAYOENS.js} +2 -2
  157. package/dist/cli/chunks/chunk-ZBKGX72B.js +13 -0
  158. package/dist/cli/chunks/{chunk-TJVTV3HP.js → chunk-ZBOWR4XT.js} +2 -2
  159. package/dist/cli/chunks/{chunk-4THFPRFM.js → chunk-ZCVJCCQQ.js} +2 -2
  160. package/dist/cli/chunks/{chunk-X2SZCVDA.js → chunk-ZI3UO7QR.js} +8 -7
  161. package/dist/cli/chunks/{chunk-DCVFHVPR.js → chunk-ZNSMVQCG.js} +2 -2
  162. package/dist/cli/chunks/{chunk-Z56BBX77.js → chunk-ZQSXG7FA.js} +2 -2
  163. package/dist/cli/chunks/{ci-QAUD62WH.js → ci-B432UH6N.js} +2 -2
  164. package/dist/cli/chunks/{ci-output-TZDVTNE7.js → ci-output-GTHH7WYG.js} +2 -2
  165. package/dist/cli/chunks/{circuit-breaker-ZWPHJ7YJ.js → circuit-breaker-VW75DLME.js} +2 -2
  166. package/dist/cli/chunks/{claude-flow-setup-SCB4EURN.js → claude-flow-setup-RE3IVT7U.js} +2 -2
  167. package/dist/cli/chunks/client-HNBZUEVV.js +2 -0
  168. package/dist/cli/chunks/{cline-installer-EHZLMLXF.js → cline-installer-NUBZZ55N.js} +2 -2
  169. package/dist/cli/chunks/{code-3N6PBJMK.js → code-K6JCWKNW.js} +2 -2
  170. package/dist/cli/chunks/{code-index-extractor-6DIKHNRI.js → code-index-extractor-I4ILB5JN.js} +2 -2
  171. package/dist/cli/chunks/{codex-installer-P7DPQMYL.js → codex-installer-AKQ5BCHU.js} +2 -2
  172. package/dist/cli/chunks/{completions-5MKWWCCE.js → completions-V3KJVJF4.js} +2 -2
  173. package/dist/cli/chunks/{complexity-analyzer-TPM4IPEK.js → complexity-analyzer-HRG7OOY3.js} +2 -2
  174. package/dist/cli/chunks/{continuedev-installer-VXODKGVX.js → continuedev-installer-CNTDONWG.js} +2 -2
  175. package/dist/cli/chunks/{copilot-installer-PVD5O56P.js → copilot-installer-XPWWIWYA.js} +2 -2
  176. package/dist/cli/chunks/core-handlers-TB7NLYXL.js +2 -0
  177. package/dist/cli/chunks/{cost-tracker-JOMZEQF3.js → cost-tracker-MFNLQ56K.js} +2 -2
  178. package/dist/cli/chunks/{coverage-HTXLEV3B.js → coverage-KOIK654V.js} +3 -3
  179. package/dist/cli/chunks/cross-domain-router-MDSI553U.js +2 -0
  180. package/dist/cli/chunks/{cursor-installer-SHKDTDDZ.js → cursor-installer-S5MKLRQQ.js} +2 -2
  181. package/dist/cli/chunks/{daemon-FCFEWVVJ.js → daemon-DUS6JYW6.js} +3 -3
  182. package/dist/cli/chunks/{daemon-PN4FEPLE.js → daemon-Z7VPGWHY.js} +4 -4
  183. package/dist/cli/chunks/{dag-attention-scheduler-PLOHU5SR.js → dag-attention-scheduler-7CQ3ARNI.js} +2 -2
  184. package/dist/cli/chunks/{detect-F3H4ZEZY.js → detect-WORBCAYF.js} +2 -2
  185. package/dist/cli/chunks/{dist-node-5TC665N6.js → dist-node-KRNI6OYW.js} +2 -2
  186. package/dist/cli/chunks/{domain-handler-ZIWVFXCU.js → domain-handler-KRUR2VQG.js} +2 -2
  187. package/dist/cli/chunks/{domain-transfer-7Q5JYMYR.js → domain-transfer-VEOVLV54.js} +2 -2
  188. package/dist/cli/chunks/dream-X7ISHFEE.js +2 -0
  189. package/dist/cli/chunks/embed-and-insert-pattern-QU3NQVA5.js +3 -0
  190. package/dist/cli/chunks/{eval-E2K2T75A.js → eval-AYQ7BSUP.js} +2 -2
  191. package/dist/cli/chunks/{experience-capture-middleware-Z5SE2O53.js → experience-capture-middleware-AWQBL6LT.js} +3 -3
  192. package/dist/cli/chunks/{fast-paths-3H52RSUK.js → fast-paths-V5EL4BYJ.js} +2 -2
  193. package/dist/cli/chunks/{feature-flags-LUHSMHPS.js → feature-flags-BXX7BP22.js} +2 -2
  194. package/dist/cli/chunks/{feature-flags-ONIKUZVK.js → feature-flags-P34BPRWU.js} +2 -2
  195. package/dist/cli/chunks/{file-discovery-FLYSYSS4.js → file-discovery-MS6BKQ2U.js} +2 -2
  196. package/dist/cli/chunks/{fleet-6OJUAAKV.js → fleet-7WVVPA4W.js} +3 -3
  197. package/dist/cli/chunks/{gnn-wrapper-PUL6B7KZ.js → gnn-wrapper-7WQ3LEPG.js} +2 -2
  198. package/dist/cli/chunks/{heartbeat-handler-HGHHDUDY.js → heartbeat-handler-P7QD3BZH.js} +4 -4
  199. package/dist/cli/chunks/heartbeat-scheduler-2C5XGFQT.js +2 -0
  200. package/dist/cli/chunks/hnsw-adapter-KCVMXLUL.js +2 -0
  201. package/dist/cli/chunks/hnsw-index-OGWZS6MP.js +2 -0
  202. package/dist/cli/chunks/{hnsw-legacy-bridge-NDZSNMYX.js → hnsw-legacy-bridge-Y3GAR3UP.js} +2 -2
  203. package/dist/cli/chunks/{hnswlib-node-PISLKSO2.js → hnswlib-node-5QUXZQWQ.js} +2 -2
  204. package/dist/cli/chunks/{hooks-WYG54MRI.js → hooks-2D64KPRY.js} +10 -10
  205. package/dist/cli/chunks/{hypergraph-engine-EDHKHZZ2.js → hypergraph-engine-5INXEZDP.js} +2 -2
  206. package/dist/cli/chunks/{hypergraph-handler-OCHZAPPL.js → hypergraph-handler-YJJJ3ESZ.js} +3 -3
  207. package/dist/cli/chunks/impact-analyzer-IBJ43GQL.js +2 -0
  208. package/dist/cli/chunks/{init-handler-5TCJ672H.js → init-handler-QSFYJN5Q.js} +6 -6
  209. package/dist/cli/chunks/init-wizard-6XMFD5LP.js +2 -0
  210. package/dist/cli/chunks/kernel-UDUMUPB3.js +2 -0
  211. package/dist/cli/chunks/{kilocode-installer-SWUQRCTZ.js → kilocode-installer-3N3QGTJU.js} +2 -2
  212. package/dist/cli/chunks/{kiro-installer-L22EBAM5.js → kiro-installer-GIWVTFZQ.js} +2 -2
  213. package/dist/cli/chunks/knowledge-graph-JRYTUG3W.js +2 -0
  214. package/dist/cli/chunks/learning-SGO2DQ5Q.js +122 -0
  215. package/dist/cli/chunks/{llm-router-F2L4LFT2.js → llm-router-HBBULO65.js} +14 -14
  216. package/dist/cli/chunks/llm-router-service-KF5ZALUQ.js +2 -0
  217. package/dist/cli/chunks/{load-A4ZF2KHC.js → load-B5OFYB4H.js} +2 -2
  218. package/dist/cli/chunks/load-test-LHMBCNCH.js +2 -0
  219. package/dist/cli/chunks/{mcp-T2Z46NNK.js → mcp-FG3LNQR4.js} +2 -2
  220. package/dist/cli/chunks/{memory-PUC3J6XC.js → memory-SPS7ZWLC.js} +5 -5
  221. package/dist/cli/chunks/memory-backend-WZHKHBZK.js +2 -0
  222. package/dist/cli/chunks/memory-handlers-P7FTPWP3.js +2 -0
  223. package/dist/cli/chunks/{multi-model-executor-U5L4FI4O.js → multi-model-executor-PUB7E6KH.js} +2 -2
  224. package/dist/cli/chunks/{opencode-installer-UWI6KHYH.js → opencode-installer-TGCSGVG2.js} +2 -2
  225. package/dist/cli/chunks/{orchestrator-3BEI7R5D.js → orchestrator-S5FTJFGB.js} +10 -13
  226. package/dist/cli/chunks/pattern-null-store-UZSHCRL2.js +2 -0
  227. package/dist/cli/chunks/{pattern-usage-recorder-EGWUI5LU.js → pattern-usage-recorder-LCXXGRAB.js} +2 -2
  228. package/dist/cli/chunks/{pipeline-JG6M4RHD.js → pipeline-ENOSRHKW.js} +2 -2
  229. package/dist/cli/chunks/{platform-F76G6RUI.js → platform-WCRBO3Z7.js} +2 -2
  230. package/dist/cli/chunks/{plugin-EEGN3PMK.js → plugin-JZ5ODJSU.js} +2 -2
  231. package/dist/cli/chunks/{prime-radiant-advanced-wasm-7KZAINFT.js → prime-radiant-advanced-wasm-DPJUPNCG.js} +2 -2
  232. package/dist/cli/chunks/protocol-executor-42NLVDTC.js +2 -0
  233. package/dist/cli/chunks/{protocol-handler-UCEHYK2R.js → protocol-handler-IP4NLVY3.js} +2 -2
  234. package/dist/cli/chunks/{prove-JSNG75VD.js → prove-P6FM4RU7.js} +2 -2
  235. package/dist/cli/chunks/qe-reasoning-bank-W74RSMMU.js +2 -0
  236. package/dist/cli/chunks/{quality-7SRM2HBM.js → quality-UHP4XO26.js} +2 -2
  237. package/dist/cli/chunks/{quality-gate-A5MPWHST.js → quality-gate-63DDBSGM.js} +3 -3
  238. package/dist/cli/chunks/queen-coordinator-XELKSRMS.js +2 -0
  239. package/dist/cli/chunks/real-embeddings-6SO5MFRQ.js +2 -0
  240. package/dist/cli/chunks/{roocode-installer-UYQK64BZ.js → roocode-installer-WTWUOFCH.js} +2 -2
  241. package/dist/cli/chunks/router-GTW2EQZV.js +2 -0
  242. package/dist/cli/chunks/routing-feedback-NVOBWEMK.js +2 -0
  243. package/dist/cli/chunks/{routing-handler-PY3KPDTH.js → routing-handler-IK7HYERQ.js} +2 -2
  244. package/dist/cli/chunks/{ruvector-commands-GCAOUTYS.js → ruvector-commands-THLB4NIM.js} +2 -2
  245. package/dist/cli/chunks/rvf-dual-writer-5OPVMXNL.js +2 -0
  246. package/dist/cli/chunks/rvf-migration-adapter-5S4YFTX4.js +2 -0
  247. package/dist/cli/chunks/rvf-migration-coordinator-BUKCSHBD.js +2 -0
  248. package/dist/cli/chunks/rvf-native-adapter-LYSJHEVX.js +2 -0
  249. package/dist/cli/chunks/{rvf-store-integrity-HNDKOM4L.js → rvf-store-integrity-ECTADZIN.js} +2 -2
  250. package/dist/cli/chunks/safe-db-AEB3JMLD.js +2 -0
  251. package/dist/cli/chunks/schedule-4QNPCQNT.js +2 -0
  252. package/dist/cli/chunks/scheduler-S3DFHX6A.js +2 -0
  253. package/dist/cli/chunks/{security-MQ2VB7PY.js → security-HN4UXFXX.js} +3 -3
  254. package/dist/cli/chunks/{shared-rvf-adapter-TAZEU6QK.js → shared-rvf-adapter-XJCPX5SN.js} +2 -2
  255. package/dist/cli/chunks/{shared-rvf-dual-writer-B7N6AOCY.js → shared-rvf-dual-writer-23X5PNY5.js} +2 -2
  256. package/dist/cli/chunks/sqlite-persistence-L2KISU2H.js +2 -0
  257. package/dist/cli/chunks/{status-handler-NZP7DFHE.js → status-handler-ZXANTHKT.js} +2 -2
  258. package/dist/cli/chunks/{structural-health-ALLUQ4X6.js → structural-health-LR6WI3AH.js} +2 -2
  259. package/dist/cli/chunks/{sync-WJJG5J6V.js → sync-4OEI3BC2.js} +2 -2
  260. package/dist/cli/chunks/{sync-MM7OCUYD.js → sync-I5IUJF33.js} +2 -2
  261. package/dist/cli/chunks/{task-handler-CAQUEEB4.js → task-handler-R3ATJKU5.js} +2 -2
  262. package/dist/cli/chunks/{task-handlers-25BJ7D3W.js → task-handlers-4X357AEW.js} +3 -3
  263. package/dist/cli/chunks/{test-HW7GVGVN.js → test-PR2B5H2F.js} +4 -4
  264. package/dist/cli/chunks/{test-scheduling-HTMFJMSP.js → test-scheduling-ZNOSQVLD.js} +3 -3
  265. package/dist/cli/chunks/token-bootstrap-LYXOI72S.js +2 -0
  266. package/dist/cli/chunks/{token-usage-RJZDMBDP.js → token-usage-R6EQZBX2.js} +2 -2
  267. package/dist/cli/chunks/{transformers-3YFW3EUO.js → transformers-COQWK27J.js} +2 -2
  268. package/dist/cli/chunks/{tree-sitter-wasm-parser-U3PQPIK7.js → tree-sitter-wasm-parser-LLIW2X3M.js} +2 -2
  269. package/dist/cli/chunks/{types-7Q762WDO.js → types-MEYTZITK.js} +2 -2
  270. package/dist/cli/chunks/unified-memory-5KQMA7FV.js +2 -0
  271. package/dist/cli/chunks/unified-memory-hnsw-PQRPTYOD.js +2 -0
  272. package/dist/cli/chunks/unified-persistence-YDONVPJB.js +2 -0
  273. package/dist/cli/chunks/{upgrade-F7MKJWBQ.js → upgrade-DVIJ456A.js} +2 -2
  274. package/dist/cli/chunks/{validate-B27AVRA6.js → validate-UYTSMJ5X.js} +2 -2
  275. package/dist/cli/chunks/{validate-swarm-GYZR3GNL.js → validate-swarm-P32WCJR6.js} +2 -2
  276. package/dist/cli/chunks/{vibium-W4XQMPJP.js → vibium-JGVOLM6X.js} +2 -2
  277. package/dist/cli/chunks/visual-security-RJ7RTNGJ.js +2 -0
  278. package/dist/cli/chunks/{web-tree-sitter-I7CDCFJU.js → web-tree-sitter-5ZGNCTPN.js} +2 -2
  279. package/dist/cli/chunks/{windsurf-installer-UYLHFDHU.js → windsurf-installer-IILSSQAE.js} +2 -2
  280. package/dist/cli/chunks/{witness-chain-B66SYZKU.js → witness-chain-JZMXCG3B.js} +2 -2
  281. package/dist/cli/chunks/witness-chain-YXXXNGAM.js +2 -0
  282. package/dist/cli/chunks/{witness-key-manager-U4JPAHVW.js → witness-key-manager-UUTLNUIH.js} +2 -2
  283. package/dist/cli/chunks/{workflow-DYMO47FF.js → workflow-NS7HXVHZ.js} +4 -4
  284. package/dist/cli/chunks/workflow-orchestrator-5KUAVSTH.js +2 -0
  285. package/dist/cli/chunks/{wrappers-7S6DQTEA.js → wrappers-XKEDSV5W.js} +2 -2
  286. package/dist/cli/commands/learning.js +44 -0
  287. package/dist/cli/commands/llm-router.js +27 -21
  288. package/dist/cli/handlers/brain-handler.js +2 -0
  289. package/dist/context/compaction/index.d.ts +1 -0
  290. package/dist/context/compaction/index.js +3 -0
  291. package/dist/context/compaction/instruction-provenance.d.ts +20 -0
  292. package/dist/context/compaction/instruction-provenance.js +18 -0
  293. package/dist/context/compaction/tier2-session-summary.d.ts +8 -0
  294. package/dist/context/compaction/tier2-session-summary.js +20 -0
  295. package/dist/context/compaction/tier3-llm-compact.d.ts +4 -0
  296. package/dist/context/compaction/tier3-llm-compact.js +32 -4
  297. package/dist/init/phases/07-hooks.js +0 -3
  298. package/dist/integrations/embeddings/base/EmbeddingGenerator.js +4 -2
  299. package/dist/integrations/ruvector/brain-exporter.d.ts +1 -1
  300. package/dist/integrations/ruvector/brain-exporter.js +15 -3
  301. package/dist/integrations/ruvector/brain-rvf-exporter.d.ts +4 -0
  302. package/dist/integrations/ruvector/brain-rvf-exporter.js +118 -37
  303. package/dist/integrations/ruvector/brain-search.d.ts +1 -1
  304. package/dist/integrations/ruvector/brain-search.js +1 -1
  305. package/dist/integrations/ruvector/brain-shared.d.ts +4 -2
  306. package/dist/integrations/ruvector/brain-shared.js +11 -4
  307. package/dist/integrations/ruvector/brain-table-ddl.d.ts +2 -2
  308. package/dist/integrations/ruvector/brain-table-ddl.js +20 -8
  309. package/dist/integrations/ruvector/cognitive-container.js +1 -1
  310. package/dist/integrations/ruvector/rvf-dual-writer.d.ts +4 -0
  311. package/dist/integrations/ruvector/rvf-dual-writer.js +57 -9
  312. package/dist/integrations/ruvector/rvf-store-integrity.js +1 -1
  313. package/dist/kernel/unified-memory-schemas.d.ts +4 -3
  314. package/dist/kernel/unified-memory-schemas.js +19 -9
  315. package/dist/kernel/unified-memory.d.ts +2 -0
  316. package/dist/kernel/unified-memory.js +19 -0
  317. package/dist/learning/embed-and-insert-pattern.js +6 -3
  318. package/dist/learning/embedding-space.d.ts +50 -0
  319. package/dist/learning/embedding-space.js +128 -0
  320. package/dist/learning/evidence-admission-store.d.ts +15 -0
  321. package/dist/learning/evidence-admission-store.js +68 -0
  322. package/dist/learning/index.d.ts +4 -0
  323. package/dist/learning/index.js +2 -0
  324. package/dist/learning/learning-evidence-admission.d.ts +44 -0
  325. package/dist/learning/learning-evidence-admission.js +97 -0
  326. package/dist/learning/pattern-store.d.ts +5 -0
  327. package/dist/learning/pattern-store.js +36 -7
  328. package/dist/learning/qe-flywheel/coupled-anchor.d.ts +8 -0
  329. package/dist/learning/qe-flywheel/coupled-anchor.js +46 -3
  330. package/dist/learning/qe-reasoning-bank.js +4 -0
  331. package/dist/learning/real-embeddings.d.ts +3 -0
  332. package/dist/learning/real-embeddings.js +40 -3
  333. package/dist/learning/real-qe-reasoning-bank.js +7 -3
  334. package/dist/learning/rvf-pattern-migration.d.ts +2 -0
  335. package/dist/learning/rvf-pattern-migration.js +5 -3
  336. package/dist/learning/rvf-pattern-store.d.ts +3 -0
  337. package/dist/learning/rvf-pattern-store.js +21 -1
  338. package/dist/learning/sqlite-persistence.d.ts +7 -2
  339. package/dist/learning/sqlite-persistence.js +58 -21
  340. package/dist/mcp/bundle.js +603 -447
  341. package/dist/mcp/handlers/memory-handlers.js +6 -2
  342. package/dist/migrations/20260830_add_learning_evidence_tables.d.ts +7 -0
  343. package/dist/migrations/20260830_add_learning_evidence_tables.js +173 -0
  344. package/dist/persistence/rvf-migration-adapter.d.ts +2 -0
  345. package/dist/persistence/rvf-migration-adapter.js +56 -12
  346. package/dist/shared/llm/llm-router-service.d.ts +8 -0
  347. package/dist/shared/llm/llm-router-service.js +21 -3
  348. package/dist/shared/sql-safety.js +4 -0
  349. package/dist/skills/qe-court/cli.d.ts +3 -0
  350. package/dist/skills/qe-court/cli.js +54 -0
  351. package/dist/verification/adversarial-verify/calibrate.d.ts +46 -2
  352. package/dist/verification/adversarial-verify/calibrate.js +104 -2
  353. package/dist/verification/adversarial-verify/index.d.ts +1 -1
  354. package/dist/verification/adversarial-verify/index.js +1 -1
  355. package/package.json +8 -3
  356. package/dist/cli/chunks/adapter-FUV6LBJT.js +0 -2
  357. package/dist/cli/chunks/aqe-learning-engine-QNFNA3J4.js +0 -2
  358. package/dist/cli/chunks/base-37W2XIXC.js +0 -2
  359. package/dist/cli/chunks/brain-handler-TVTTWZGP.js +0 -89
  360. package/dist/cli/chunks/browser-workflow-PDIUEK7B.js +0 -2
  361. package/dist/cli/chunks/chunk-EDRPTLAX.js +0 -2
  362. package/dist/cli/chunks/chunk-GEQWCK4F.js +0 -2
  363. package/dist/cli/chunks/chunk-GQLJYTXN.js +0 -2
  364. package/dist/cli/chunks/chunk-NLZUGANH.js +0 -11
  365. package/dist/cli/chunks/chunk-O4BWESH5.js +0 -2
  366. package/dist/cli/chunks/chunk-PGFCKE4G.js +0 -12
  367. package/dist/cli/chunks/chunk-RACWX2ZX.js +0 -9
  368. package/dist/cli/chunks/chunk-SNC73DWF.js +0 -2
  369. package/dist/cli/chunks/chunk-TDVMILKO.js +0 -2
  370. package/dist/cli/chunks/chunk-TK5XLF3Z.js +0 -65
  371. package/dist/cli/chunks/chunk-UQ4UCHO7.js +0 -2
  372. package/dist/cli/chunks/chunk-VZGP77YU.js +0 -12
  373. package/dist/cli/chunks/chunk-WA6CSEOX.js +0 -2
  374. package/dist/cli/chunks/chunk-WYIXNHPF.js +0 -2
  375. package/dist/cli/chunks/client-4W3KWTAU.js +0 -2
  376. package/dist/cli/chunks/core-handlers-BDU2XBLO.js +0 -2
  377. package/dist/cli/chunks/cross-domain-router-BPB6IHN4.js +0 -2
  378. package/dist/cli/chunks/dream-WFCZGFDY.js +0 -2
  379. package/dist/cli/chunks/embed-and-insert-pattern-VESJQSYD.js +0 -3
  380. package/dist/cli/chunks/heartbeat-scheduler-HWS4SHRM.js +0 -2
  381. package/dist/cli/chunks/hnsw-adapter-7QOBHKRB.js +0 -2
  382. package/dist/cli/chunks/hnsw-index-6WUKYJH7.js +0 -2
  383. package/dist/cli/chunks/hybrid-router-525JTRA5.js +0 -2
  384. package/dist/cli/chunks/impact-analyzer-GG6CJEOK.js +0 -2
  385. package/dist/cli/chunks/init-wizard-4VFAOK4Y.js +0 -2
  386. package/dist/cli/chunks/kernel-N3FQGOST.js +0 -2
  387. package/dist/cli/chunks/knowledge-graph-I5QIHB4G.js +0 -2
  388. package/dist/cli/chunks/learning-TQOGG3CR.js +0 -119
  389. package/dist/cli/chunks/llm-router-service-NCJZYJLG.js +0 -2
  390. package/dist/cli/chunks/load-test-DCJEYIXD.js +0 -2
  391. package/dist/cli/chunks/memory-backend-O6KO2KTX.js +0 -2
  392. package/dist/cli/chunks/memory-handlers-4Z43WEKD.js +0 -2
  393. package/dist/cli/chunks/pattern-null-store-5WIJKX2K.js +0 -2
  394. package/dist/cli/chunks/protocol-executor-5TPNAZTB.js +0 -2
  395. package/dist/cli/chunks/provider-manager-3VMOZ6HV.js +0 -2
  396. package/dist/cli/chunks/qe-reasoning-bank-BATV4NTT.js +0 -2
  397. package/dist/cli/chunks/queen-coordinator-EIHGYBUO.js +0 -2
  398. package/dist/cli/chunks/real-embeddings-ZBF5EQOG.js +0 -2
  399. package/dist/cli/chunks/router-EMVGY4HU.js +0 -2
  400. package/dist/cli/chunks/routing-feedback-JUP4OFB2.js +0 -2
  401. package/dist/cli/chunks/rvf-dual-writer-BUNP4SKD.js +0 -2
  402. package/dist/cli/chunks/rvf-migration-adapter-VSOAPLMB.js +0 -2
  403. package/dist/cli/chunks/rvf-migration-coordinator-LSWEHAWX.js +0 -2
  404. package/dist/cli/chunks/rvf-native-adapter-LOC42TQ6.js +0 -2
  405. package/dist/cli/chunks/safe-db-WQ62IQKV.js +0 -2
  406. package/dist/cli/chunks/schedule-XJRP57TE.js +0 -2
  407. package/dist/cli/chunks/scheduler-EZH5SDIM.js +0 -2
  408. package/dist/cli/chunks/sqlite-persistence-HPEVCTIB.js +0 -2
  409. package/dist/cli/chunks/token-bootstrap-F2DCLWGW.js +0 -2
  410. package/dist/cli/chunks/unified-memory-ATILROKR.js +0 -2
  411. package/dist/cli/chunks/unified-memory-hnsw-XJXAX7DW.js +0 -2
  412. package/dist/cli/chunks/unified-persistence-3TN5PBWE.js +0 -2
  413. package/dist/cli/chunks/visual-security-VFWRBCNA.js +0 -2
  414. package/dist/cli/chunks/witness-chain-JC5LEXRV.js +0 -2
  415. package/dist/cli/chunks/workflow-orchestrator-TKQUF2KN.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.13.12");process.exit(0)}
2
- import{d as xe}from"./chunk-OG3DBHIV.js";import{a as be,b as Re}from"./chunk-WYFAPA2G.js";import{a as Ce}from"./chunk-GEQWCK4F.js";import{c as fe,d as ge,e as Le}from"./chunk-IOJ34SXJ.js";import{b as D,d as ye}from"./chunk-VA2ORJB5.js";import{b as P,c as L}from"./chunk-E67ZXRG6.js";import{a as G,b as A,c as J}from"./chunk-L3GBNX7B.js";Ce();import{createRequire as Se}from"module";var O;function W(){if(!O){let u=Se(import.meta.url);try{O=u("typescript")}catch{try{O=u("typescript/lib/typescript.js")}catch{O=new Proxy({},{get(e,t){if(!(t==="__esModule"||typeof t=="symbol"))throw new Error("TypeScript is required for code analysis. Install it: npm install -g typescript")}})}}}return O}var m=new Proxy({},{get(u,e){return W()[e]},has(u,e){return e in W()},ownKeys(){return Object.keys(W())},getOwnPropertyDescriptor(u,e){let t=W()[e];if(t!==void 0)return{configurable:!0,enumerable:!0,value:t}}});var N=class{parseFile(e,t){return m.createSourceFile(e,t,m.ScriptTarget.Latest,!0,this.getScriptKind(e))}extractFunctions(e){let t=[],s=n=>{m.isFunctionDeclaration(n)&&n.name?t.push(this.extractFunctionDeclaration(n,e)):m.isVariableStatement(n)&&this.extractArrowFunctions(n,e,t),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractClasses(e){let t=[],s=n=>{m.isClassDeclaration(n)&&n.name&&t.push(this.extractClassDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractImports(e){let t=[],s=n=>{m.isImportDeclaration(n)&&t.push(this.extractImportDeclaration(n)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractExports(e){let t=[],s=n=>{if(m.isExportDeclaration(n))this.extractExportDeclaration(n,t);else if(m.isExportAssignment(n))t.push({name:this.getExportAssignmentName(n),type:"unknown",isDefault:!0,isReexport:!1,sourceModule:void 0});else if(m.isFunctionDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"function",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(m.isClassDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"class",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(m.isVariableStatement(n)&&this.hasExportModifier(n))for(let i of n.declarationList.declarations)m.isIdentifier(i.name)&&t.push({name:i.name.text,type:"variable",isDefault:!1,isReexport:!1,sourceModule:void 0});else m.isInterfaceDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"interface",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isTypeAliasDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"type",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isEnumDeclaration(n)&&this.hasExportModifier(n)&&t.push({name:n.name.text,type:"enum",isDefault:!1,isReexport:!1,sourceModule:void 0});m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractInterfaces(e){let t=[],s=n=>{m.isInterfaceDeclaration(n)&&t.push(this.extractInterfaceDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractEntities(e,t){let s=this.parseFile(t,e),n=[],i=this.extractFunctions(s);for(let a of i)n.push({name:a.name,type:"function",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:a.isAsync,isExported:a.isExported,parameters:a.parameters,returnType:a.returnType});let o=this.extractClasses(s);for(let a of o)n.push({name:a.name,type:"class",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported,extends:a.extends,implements:a.implements});let r=this.extractInterfaces(s);for(let a of r)n.push({name:a.name,type:"interface",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported});return n}getScriptKind(e){return e.endsWith(".tsx")?m.ScriptKind.TSX:e.endsWith(".ts")?m.ScriptKind.TS:e.endsWith(".jsx")?m.ScriptKind.JSX:e.endsWith(".js")?m.ScriptKind.JS:m.ScriptKind.TS}extractFunctionDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:e.name?.text??"anonymous",parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,startLine:s+1,endLine:n+1,isAsync:this.hasAsyncModifier(e),isExported:this.hasExportModifier(e),isGenerator:!!e.asteriskToken,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractArrowFunctions(e,t,s){for(let n of e.declarationList.declarations)if(m.isIdentifier(n.name)&&n.initializer&&m.isArrowFunction(n.initializer)){let i=n.initializer,{line:o}=t.getLineAndCharacterOfPosition(e.getStart()),{line:r}=t.getLineAndCharacterOfPosition(e.getEnd());s.push({name:n.name.text,parameters:this.extractParameters(i.parameters),returnType:i.type?i.type.getText(t):void 0,startLine:o+1,endLine:r+1,isAsync:this.hasAsyncModifier(i),isExported:this.hasExportModifier(e),isGenerator:!1,typeParameters:this.extractTypeParameters(i.typeParameters)})}}extractClassDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),i=[],o=[];for(let c of e.members)m.isMethodDeclaration(c)&&c.name?i.push(this.extractMethodDeclaration(c,t)):m.isPropertyDeclaration(c)&&c.name?o.push(this.extractPropertyDeclaration(c,t)):m.isConstructorDeclaration(c)&&(i.push(this.extractConstructor(c,t)),this.extractParameterProperties(c,o,t));let r,a=[];if(e.heritageClauses){for(let c of e.heritageClauses)if(c.token===m.SyntaxKind.ExtendsKeyword)r=c.types[0]?.expression.getText(t);else if(c.token===m.SyntaxKind.ImplementsKeyword)for(let l of c.types)a.push(l.expression.getText(t))}return{name:e.name?.text??"anonymous",methods:i,properties:o,extends:r,implements:a,isAbstract:this.hasAbstractModifier(e),isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractMethodDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:this.getPropertyName(e.name,t),parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,isAsync:this.hasAsyncModifier(e),isStatic:this.hasStaticModifier(e),isAbstract:this.hasAbstractModifier(e),visibility:this.getVisibility(e),startLine:s+1,endLine:n+1}}extractConstructor(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:"constructor",parameters:this.extractParameters(e.parameters),returnType:void 0,isAsync:!1,isStatic:!1,isAbstract:!1,visibility:"public",startLine:s+1,endLine:n+1}}extractParameterProperties(e,t,s){for(let n of e.parameters)this.isParameterProperty(n)&&t.push({name:m.isIdentifier(n.name)?n.name.text:n.name.getText(s),type:n.type?n.type.getText(s):void 0,isStatic:!1,isReadonly:this.hasReadonlyModifier(n),visibility:this.getVisibility(n),hasInitializer:!!n.initializer})}isParameterProperty(e){return!!e.modifiers?.some(t=>t.kind===m.SyntaxKind.PublicKeyword||t.kind===m.SyntaxKind.PrivateKeyword||t.kind===m.SyntaxKind.ProtectedKeyword||t.kind===m.SyntaxKind.ReadonlyKeyword)}extractPropertyDeclaration(e,t){return{name:this.getPropertyName(e.name,t),type:e.type?e.type.getText(t):void 0,isStatic:this.hasStaticModifier(e),isReadonly:this.hasReadonlyModifier(e),visibility:this.getVisibility(e),hasInitializer:!!e.initializer}}extractImportDeclaration(e){let t=e.moduleSpecifier.text,s=[],n,i,o=e.importClause?.isTypeOnly??!1;if(e.importClause&&(e.importClause.name&&(n=e.importClause.name.text),e.importClause.namedBindings)){if(m.isNamespaceImport(e.importClause.namedBindings))i=e.importClause.namedBindings.name.text;else if(m.isNamedImports(e.importClause.namedBindings))for(let r of e.importClause.namedBindings.elements)s.push({name:r.propertyName?.text??r.name.text,alias:r.propertyName?r.name.text:void 0})}return{module:t,namedImports:s,defaultImport:n,namespaceImport:i,isTypeOnly:o}}extractExportDeclaration(e,t){let s=e.moduleSpecifier?e.moduleSpecifier.text:void 0;if(e.exportClause&&m.isNamedExports(e.exportClause))for(let n of e.exportClause.elements)t.push({name:n.name.text,type:"unknown",isDefault:!1,isReexport:!!s,sourceModule:s});else!e.exportClause&&s&&t.push({name:"*",type:"unknown",isDefault:!1,isReexport:!0,sourceModule:s})}extractInterfaceDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),i=[],o=[];for(let a of e.members)m.isPropertySignature(a)&&a.name?i.push({name:this.getPropertyName(a.name,t),type:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken,isReadonly:this.hasReadonlyModifier(a)}):m.isMethodSignature(a)&&a.name&&o.push({name:this.getPropertyName(a.name,t),parameters:this.extractParameters(a.parameters),returnType:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken});let r=[];if(e.heritageClauses){for(let a of e.heritageClauses)if(a.token===m.SyntaxKind.ExtendsKeyword)for(let c of a.types)r.push(c.expression.getText(t))}return{name:e.name.text,properties:i,methods:o,extends:r,isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractParameters(e){return e.map(t=>{let s=t.getSourceFile();return{name:m.isIdentifier(t.name)?t.name.text:t.name.getText(s),type:t.type?t.type.getText(s):void 0,isOptional:!!t.questionToken||!!t.initializer,isRest:!!t.dotDotDotToken,defaultValue:t.initializer?t.initializer.getText(s):void 0}})}extractTypeParameters(e){return e?e.map(t=>t.name.text):[]}getPropertyName(e,t){return m.isIdentifier(e)||m.isStringLiteral(e)||m.isNumericLiteral(e)?e.text:e.getText(t)}getExportAssignmentName(e){return m.isIdentifier(e.expression)?e.expression.text:"default"}hasExportModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ExportKeyword)}hasDefaultModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.DefaultKeyword)}hasAsyncModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AsyncKeyword)}hasStaticModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.StaticKeyword)}hasAbstractModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AbstractKeyword)}hasReadonlyModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ReadonlyKeyword)}getVisibility(e){if(!m.canHaveModifiers(e))return"public";let t=m.getModifiers(e);return t?t.some(s=>s.kind===m.SyntaxKind.PrivateKeyword)?"private":t.some(s=>s.kind===m.SyntaxKind.ProtectedKeyword)?"protected":"public":"public"}},Be=new N,Q=class{language="typescript";supportedExtensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];parser=new N;async parseFile(e,t){let s=this.parser.parseFile(t,e),n=this.parser.extractFunctions(s),i=this.parser.extractClasses(s),o=this.parser.extractImports(s);return{functions:n.map(r=>this.mapFunction(r)),classes:i.map(r=>this.mapClass(r)),imports:o.map(r=>this.mapImport(r)),language:t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":"typescript",filePath:t}}mapFunction(e){return{name:e.name,parameters:e.parameters.map(t=>({name:t.name,type:t.type,isOptional:t.isOptional,defaultValue:t.defaultValue})),returnType:e.returnType,isAsync:e.isAsync,isPublic:e.isExported,complexity:1,decorators:[],genericParams:e.typeParameters,startLine:e.startLine,endLine:e.endLine}}mapClass(e){return{name:e.name,methods:e.methods.map(t=>({name:t.name,parameters:t.parameters.map(s=>({name:s.name,type:s.type,isOptional:s.isOptional,defaultValue:s.defaultValue})),returnType:t.returnType,isAsync:t.isAsync,isPublic:t.visibility==="public",complexity:1,decorators:[],genericParams:[],startLine:t.startLine,endLine:t.endLine})),properties:e.properties.map(t=>this.mapProperty(t)),isPublic:e.isExported,implements:e.implements,extends:e.extends,decorators:[],startLine:e.startLine,endLine:e.endLine}}mapProperty(e){return{name:e.name,type:e.type,isPublic:e.visibility==="public",isReadonly:e.isReadonly}}mapImport(e){return{module:e.module,namedImports:e.namedImports.map(t=>t.alias||t.name),isTypeOnly:e.isTypeOnly}}},Ve=new Q;Le();var E=1e3;function I(u){let e=u.split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
+ import{d as xe}from"./chunk-U4GZWPKM.js";import{a as be,b as Re}from"./chunk-5LEAGKX5.js";import{a as Ce}from"./chunk-R2B6EE45.js";import{c as fe,d as ge,e as Le}from"./chunk-JY4VZ6BN.js";import{b as D,d as ye}from"./chunk-HQHLHSJO.js";import{b as P,c as L}from"./chunk-JGROLJ33.js";import{a as G,b as A,c as J}from"./chunk-XITTURP2.js";Ce();import{createRequire as Se}from"module";var O;function W(){if(!O){let u=Se(import.meta.url);try{O=u("typescript")}catch{try{O=u("typescript/lib/typescript.js")}catch{O=new Proxy({},{get(e,t){if(!(t==="__esModule"||typeof t=="symbol"))throw new Error("TypeScript is required for code analysis. Install it: npm install -g typescript")}})}}}return O}var m=new Proxy({},{get(u,e){return W()[e]},has(u,e){return e in W()},ownKeys(){return Object.keys(W())},getOwnPropertyDescriptor(u,e){let t=W()[e];if(t!==void 0)return{configurable:!0,enumerable:!0,value:t}}});var N=class{parseFile(e,t){return m.createSourceFile(e,t,m.ScriptTarget.Latest,!0,this.getScriptKind(e))}extractFunctions(e){let t=[],s=n=>{m.isFunctionDeclaration(n)&&n.name?t.push(this.extractFunctionDeclaration(n,e)):m.isVariableStatement(n)&&this.extractArrowFunctions(n,e,t),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractClasses(e){let t=[],s=n=>{m.isClassDeclaration(n)&&n.name&&t.push(this.extractClassDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractImports(e){let t=[],s=n=>{m.isImportDeclaration(n)&&t.push(this.extractImportDeclaration(n)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractExports(e){let t=[],s=n=>{if(m.isExportDeclaration(n))this.extractExportDeclaration(n,t);else if(m.isExportAssignment(n))t.push({name:this.getExportAssignmentName(n),type:"unknown",isDefault:!0,isReexport:!1,sourceModule:void 0});else if(m.isFunctionDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"function",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(m.isClassDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"class",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(m.isVariableStatement(n)&&this.hasExportModifier(n))for(let i of n.declarationList.declarations)m.isIdentifier(i.name)&&t.push({name:i.name.text,type:"variable",isDefault:!1,isReexport:!1,sourceModule:void 0});else m.isInterfaceDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"interface",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isTypeAliasDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"type",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isEnumDeclaration(n)&&this.hasExportModifier(n)&&t.push({name:n.name.text,type:"enum",isDefault:!1,isReexport:!1,sourceModule:void 0});m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractInterfaces(e){let t=[],s=n=>{m.isInterfaceDeclaration(n)&&t.push(this.extractInterfaceDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractEntities(e,t){let s=this.parseFile(t,e),n=[],i=this.extractFunctions(s);for(let a of i)n.push({name:a.name,type:"function",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:a.isAsync,isExported:a.isExported,parameters:a.parameters,returnType:a.returnType});let o=this.extractClasses(s);for(let a of o)n.push({name:a.name,type:"class",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported,extends:a.extends,implements:a.implements});let r=this.extractInterfaces(s);for(let a of r)n.push({name:a.name,type:"interface",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported});return n}getScriptKind(e){return e.endsWith(".tsx")?m.ScriptKind.TSX:e.endsWith(".ts")?m.ScriptKind.TS:e.endsWith(".jsx")?m.ScriptKind.JSX:e.endsWith(".js")?m.ScriptKind.JS:m.ScriptKind.TS}extractFunctionDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:e.name?.text??"anonymous",parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,startLine:s+1,endLine:n+1,isAsync:this.hasAsyncModifier(e),isExported:this.hasExportModifier(e),isGenerator:!!e.asteriskToken,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractArrowFunctions(e,t,s){for(let n of e.declarationList.declarations)if(m.isIdentifier(n.name)&&n.initializer&&m.isArrowFunction(n.initializer)){let i=n.initializer,{line:o}=t.getLineAndCharacterOfPosition(e.getStart()),{line:r}=t.getLineAndCharacterOfPosition(e.getEnd());s.push({name:n.name.text,parameters:this.extractParameters(i.parameters),returnType:i.type?i.type.getText(t):void 0,startLine:o+1,endLine:r+1,isAsync:this.hasAsyncModifier(i),isExported:this.hasExportModifier(e),isGenerator:!1,typeParameters:this.extractTypeParameters(i.typeParameters)})}}extractClassDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),i=[],o=[];for(let c of e.members)m.isMethodDeclaration(c)&&c.name?i.push(this.extractMethodDeclaration(c,t)):m.isPropertyDeclaration(c)&&c.name?o.push(this.extractPropertyDeclaration(c,t)):m.isConstructorDeclaration(c)&&(i.push(this.extractConstructor(c,t)),this.extractParameterProperties(c,o,t));let r,a=[];if(e.heritageClauses){for(let c of e.heritageClauses)if(c.token===m.SyntaxKind.ExtendsKeyword)r=c.types[0]?.expression.getText(t);else if(c.token===m.SyntaxKind.ImplementsKeyword)for(let l of c.types)a.push(l.expression.getText(t))}return{name:e.name?.text??"anonymous",methods:i,properties:o,extends:r,implements:a,isAbstract:this.hasAbstractModifier(e),isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractMethodDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:this.getPropertyName(e.name,t),parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,isAsync:this.hasAsyncModifier(e),isStatic:this.hasStaticModifier(e),isAbstract:this.hasAbstractModifier(e),visibility:this.getVisibility(e),startLine:s+1,endLine:n+1}}extractConstructor(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:"constructor",parameters:this.extractParameters(e.parameters),returnType:void 0,isAsync:!1,isStatic:!1,isAbstract:!1,visibility:"public",startLine:s+1,endLine:n+1}}extractParameterProperties(e,t,s){for(let n of e.parameters)this.isParameterProperty(n)&&t.push({name:m.isIdentifier(n.name)?n.name.text:n.name.getText(s),type:n.type?n.type.getText(s):void 0,isStatic:!1,isReadonly:this.hasReadonlyModifier(n),visibility:this.getVisibility(n),hasInitializer:!!n.initializer})}isParameterProperty(e){return!!e.modifiers?.some(t=>t.kind===m.SyntaxKind.PublicKeyword||t.kind===m.SyntaxKind.PrivateKeyword||t.kind===m.SyntaxKind.ProtectedKeyword||t.kind===m.SyntaxKind.ReadonlyKeyword)}extractPropertyDeclaration(e,t){return{name:this.getPropertyName(e.name,t),type:e.type?e.type.getText(t):void 0,isStatic:this.hasStaticModifier(e),isReadonly:this.hasReadonlyModifier(e),visibility:this.getVisibility(e),hasInitializer:!!e.initializer}}extractImportDeclaration(e){let t=e.moduleSpecifier.text,s=[],n,i,o=e.importClause?.isTypeOnly??!1;if(e.importClause&&(e.importClause.name&&(n=e.importClause.name.text),e.importClause.namedBindings)){if(m.isNamespaceImport(e.importClause.namedBindings))i=e.importClause.namedBindings.name.text;else if(m.isNamedImports(e.importClause.namedBindings))for(let r of e.importClause.namedBindings.elements)s.push({name:r.propertyName?.text??r.name.text,alias:r.propertyName?r.name.text:void 0})}return{module:t,namedImports:s,defaultImport:n,namespaceImport:i,isTypeOnly:o}}extractExportDeclaration(e,t){let s=e.moduleSpecifier?e.moduleSpecifier.text:void 0;if(e.exportClause&&m.isNamedExports(e.exportClause))for(let n of e.exportClause.elements)t.push({name:n.name.text,type:"unknown",isDefault:!1,isReexport:!!s,sourceModule:s});else!e.exportClause&&s&&t.push({name:"*",type:"unknown",isDefault:!1,isReexport:!0,sourceModule:s})}extractInterfaceDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),i=[],o=[];for(let a of e.members)m.isPropertySignature(a)&&a.name?i.push({name:this.getPropertyName(a.name,t),type:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken,isReadonly:this.hasReadonlyModifier(a)}):m.isMethodSignature(a)&&a.name&&o.push({name:this.getPropertyName(a.name,t),parameters:this.extractParameters(a.parameters),returnType:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken});let r=[];if(e.heritageClauses){for(let a of e.heritageClauses)if(a.token===m.SyntaxKind.ExtendsKeyword)for(let c of a.types)r.push(c.expression.getText(t))}return{name:e.name.text,properties:i,methods:o,extends:r,isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractParameters(e){return e.map(t=>{let s=t.getSourceFile();return{name:m.isIdentifier(t.name)?t.name.text:t.name.getText(s),type:t.type?t.type.getText(s):void 0,isOptional:!!t.questionToken||!!t.initializer,isRest:!!t.dotDotDotToken,defaultValue:t.initializer?t.initializer.getText(s):void 0}})}extractTypeParameters(e){return e?e.map(t=>t.name.text):[]}getPropertyName(e,t){return m.isIdentifier(e)||m.isStringLiteral(e)||m.isNumericLiteral(e)?e.text:e.getText(t)}getExportAssignmentName(e){return m.isIdentifier(e.expression)?e.expression.text:"default"}hasExportModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ExportKeyword)}hasDefaultModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.DefaultKeyword)}hasAsyncModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AsyncKeyword)}hasStaticModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.StaticKeyword)}hasAbstractModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AbstractKeyword)}hasReadonlyModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ReadonlyKeyword)}getVisibility(e){if(!m.canHaveModifiers(e))return"public";let t=m.getModifiers(e);return t?t.some(s=>s.kind===m.SyntaxKind.PrivateKeyword)?"private":t.some(s=>s.kind===m.SyntaxKind.ProtectedKeyword)?"protected":"public":"public"}},Be=new N,Q=class{language="typescript";supportedExtensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];parser=new N;async parseFile(e,t){let s=this.parser.parseFile(t,e),n=this.parser.extractFunctions(s),i=this.parser.extractClasses(s),o=this.parser.extractImports(s);return{functions:n.map(r=>this.mapFunction(r)),classes:i.map(r=>this.mapClass(r)),imports:o.map(r=>this.mapImport(r)),language:t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":"typescript",filePath:t}}mapFunction(e){return{name:e.name,parameters:e.parameters.map(t=>({name:t.name,type:t.type,isOptional:t.isOptional,defaultValue:t.defaultValue})),returnType:e.returnType,isAsync:e.isAsync,isPublic:e.isExported,complexity:1,decorators:[],genericParams:e.typeParameters,startLine:e.startLine,endLine:e.endLine}}mapClass(e){return{name:e.name,methods:e.methods.map(t=>({name:t.name,parameters:t.parameters.map(s=>({name:s.name,type:s.type,isOptional:s.isOptional,defaultValue:s.defaultValue})),returnType:t.returnType,isAsync:t.isAsync,isPublic:t.visibility==="public",complexity:1,decorators:[],genericParams:[],startLine:t.startLine,endLine:t.endLine})),properties:e.properties.map(t=>this.mapProperty(t)),isPublic:e.isExported,implements:e.implements,extends:e.extends,decorators:[],startLine:e.startLine,endLine:e.endLine}}mapProperty(e){return{name:e.name,type:e.type,isPublic:e.visibility==="public",isReadonly:e.isReadonly}}mapImport(e){return{module:e.module,namedImports:e.namedImports.map(t=>t.alias||t.name),isTypeOnly:e.isTypeOnly}}},Ve=new Q;Le();var E=1e3;function I(u){let e=u.split(`
3
3
  `),t=[],s=[],n="",i=0,o=0,r=0,a=0;for(let c=0;c<e.length;c++){let l=e[c],d=l.trim();if(d===""||d.startsWith("//")||d.startsWith("#")||d.startsWith("*")){if(n){n+=" "+d;continue}t.push(l),s.push(c+1);continue}n||(i=c+1),n=n?n+" "+d:l;for(let p of d)p==="("?o++:p===")"?o=Math.max(0,o-1):p==="<"?r++:p===">"?r=Math.max(0,r-1):p==="["?a++:p==="]"&&(a=Math.max(0,a-1));o===0&&r===0&&a===0&&(t.push(n),s.push(i),n="")}return n&&(t.push(n),s.push(i)),{logicalLines:t,lineMap:s}}function B(u,e,t="<",s=">"){if(u[e]!==t)return;let n=1,i=e+1;for(;i<u.length&&n>0;)u[i]===t?n++:u[i]===s&&n--,i++;if(n===0)return u.substring(e+1,i-1)}function C(u,e,t){let s=[];for(let n=e-1;n>=0;n--){let i=u[n].trim();if(i.startsWith(t))s.unshift(i);else{if(i===""||i.startsWith("//")||i.startsWith("*")||i.startsWith("#"))continue;break}}return s}function M(u){let e=[],t=0,s="";for(let n of u)n==="<"||n==="("?t++:(n===">"||n===")")&&t--,n===","&&t===0?(e.push(s.trim()),s=""):s+=n;return s.trim()&&e.push(s.trim()),e}function ce(u){let e=0,t=!1,s="";for(let n=0;n<u.length;n++){let i=u[n];if(t){i===s&&u[n-1]!=="\\"&&(t=!1);continue}i==='"'||i==="'"||i==="`"?(t=!0,s=i):i==="{"?e++:i==="}"&&e--}return e}var Y=class{language="python";supportedExtensions=[".py"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"python",filePath:t}}extractFunctions(e){let t=[],s=e.split(`
4
4
  `),{logicalLines:n,lineMap:i}=I(e),o=/^(\s*)(async\s+)?def\s+(\w+)\s*\(([^)]*)\)(?:\s*->\s*([^:]*\S))?\s*:/;for(let r=0;r<n.length;r++){if(n[r].length>E)continue;let a=n[r].match(o);if(a){let c=a[1].length,l=!!a[2],d=a[3],p=a[4],h=a[5]?.trim(),f=i[r]-1,g=f+1;for(let y=f+1;y<s.length;y++){let x=s[y];if(x.trim()===""||x.trim().startsWith("#"))continue;if((x.match(/^(\s*)/)?.[1].length??0)<=c&&x.trim()!==""){g=y;break}g=y+1}let b=C(s,f,"@");t.push({name:d,parameters:this.parseParams(p),returnType:h,isAsync:l,isPublic:!d.startsWith("_"),complexity:1,decorators:b,genericParams:[],startLine:i[r],endLine:g})}}return t}extractClasses(e){let t=[],s=e.split(`
5
5
  `),{logicalLines:n,lineMap:i}=I(e),o=/^(\s*)class\s+(\w+)(?:\(([^)]*)\))?\s*:/;for(let r=0;r<n.length;r++){let a=n[r].match(o);if(a){let c=a[1].length,l=a[2],d=a[3]?a[3].split(",").map(y=>y.trim()):[],p=i[r]-1,h=p+1;for(let y=p+1;y<s.length;y++){let x=s[y];if(x.trim()===""||x.trim().startsWith("#"))continue;if((x.match(/^(\s*)/)?.[1].length??0)<=c&&x.trim()!==""){h=y;break}h=y+1}let f=s.slice(p+1,h).join(`
@@ -20,7 +20,7 @@ import{d as xe}from"./chunk-OG3DBHIV.js";import{a as be,b as Re}from"./chunk-WYF
20
20
  `),{logicalLines:n,lineMap:i}=I(e),o=/^\s*(public|private|protected|internal)?\s*(suspend)?\s*fun\s+(?:<[^{]*> +)?(\w+)\s*\(([^)]*)\)(?:\s*:\s*([^{=\s]+(?:\s+[^{=\s]+)*))?\s*/,r=0;for(let a=0;a<n.length;a++){let c=n[a];if(c.length>E){r+=(c.match(/\{/g)?.length??0)-(c.match(/\}/g)?.length??0);continue}let l=c.match(o);if(l&&r<=1){let d=l[1]||"public",p=!!l[2],h=l[3],f=l[4],g=l[5]?.trim();if(g&&g.includes("<")){let x=g.indexOf("<"),w=B(g,x);w!==void 0&&(g=g.substring(0,x)+"<"+w+">")}let b=i[a]-1,y=C(s,b,"@");t.push({name:h,parameters:this.parseParams(f),returnType:g,isAsync:p,isPublic:d==="public",complexity:1,decorators:y,genericParams:[],startLine:i[a],endLine:i[a]})}r+=ce(c),r<0&&(r=0)}return t}extractClasses(e){let t=[],s=e.split(`
21
21
  `),{logicalLines:n,lineMap:i}=I(e),o=/^\s*(public|private|protected|internal)?\s*(data|sealed|abstract|open)?\s*class\s+(\w+)(?:<[^{]*>)?(?:\s*(?:\([^)]*\))?\s*:\s*([^{\s]+(?:\s+[^{\s]+)*))?\s*\{?/;for(let r=0;r<n.length;r++){if(n[r].length>E)continue;let a=n[r].match(o);if(a){let c=a[3],l=a[4]?a[4].split(",").map(h=>h.trim().split("(")[0].trim()):[],d=i[r]-1,p=C(s,d,"@");t.push({name:c,methods:[],properties:[],isPublic:(a[1]||"public")==="public",implements:l.slice(1),extends:l[0]||void 0,decorators:p,startLine:i[r],endLine:i[r]})}}return t}extractImports(e){let t=[],s=e.split(`
22
22
  `);for(let n of s){let i=n.match(/^\s*import\s+([^\s]+)/);i&&t.push({module:i[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){return e.trim()?M(e).map(t=>{let s=t.indexOf(":");if(s===-1)return{name:t.replace("val ","").replace("var ","").trim(),type:void 0,isOptional:!1,defaultValue:void 0};let n=t.substring(0,s).replace("val ","").replace("var ","").trim(),i=t.substring(s+1).trim(),o=i.indexOf("="),r=o>=0?i.substring(0,o).trim():i,a=o>=0;return{name:n,type:r,isOptional:a||r?.endsWith("?")||!1,defaultValue:void 0}}):[]}},re=class{language="dart";supportedExtensions=[".dart"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"dart",filePath:t}}extractFunctions(e){let t=[],{logicalLines:s,lineMap:n}=I(e),i=/^\s*([\w<>,.?]+(?:\s+[\w<>,.?]+)*)\s+(\w+)\s*\(([^)]*)\)(?:\s*(async))?\s*\{/;for(let o=0;o<s.length;o++){let r=s[o];if(r.includes(" class ")||r.length>E)continue;let a=r.match(i);if(a){let c=a[1].trim(),l=c;if(c&&c.includes("<")){let f=c.indexOf("<"),g=B(c,f);g!==void 0&&(l=c.substring(0,f)+"<"+g+">")}let d=a[2],p=a[3],h=!!a[4]||l.includes("Future");t.push({name:d,parameters:this.parseParams(p),returnType:l==="void"?void 0:l,isAsync:h,isPublic:!d.startsWith("_"),complexity:1,decorators:[],genericParams:[],startLine:n[o],endLine:n[o]})}}return t}extractClasses(e){let t=[],{logicalLines:s,lineMap:n}=I(e),i=/^\s*(abstract +)?class\s+(\w+)(?:<[^{]*>)?(?:\s+extends\s+(\w+))?(?:\s+(?:with|implements)\s+([^{\s]+(?:\s+[^{\s]+)*))?\s*\{/;for(let o=0;o<s.length;o++){if(s[o].length>E)continue;let r=s[o].match(i);if(r){let a=r[2],c=r[3],l=r[4]?r[4].split(",").map(d=>d.trim()):[];t.push({name:a,methods:[],properties:[],isPublic:!a.startsWith("_"),implements:l,extends:c,decorators:[],startLine:n[o],endLine:n[o]})}}return t}extractImports(e){let t=[],s=e.split(`
23
- `);for(let n of s){let i=n.match(/^\s*import\s+'([^']+)'/);i&&t.push({module:i[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){if(!e.trim())return[];let t=e.replace(/[{}[\]]/g,"");return M(t).map(s=>s.trim()).filter(s=>s).map(s=>{let n=s.replace("required ","").trim().split(/\s+/),i=n[n.length-1]||"",o=n.slice(0,-1).join(" ")||void 0;return{name:i,type:o,isOptional:s.includes("?")||s.includes("{"),defaultValue:void 0}})}},z=ge("ParserRegistry"),ve=["python","java","csharp","rust","swift"],ae=class u{language;supportedExtensions;wasmParser;regexParser;wasmFailCount=0;static MAX_WASM_RETRIES=3;constructor(e,t){this.wasmParser=e,this.regexParser=t,this.language=e.language,this.supportedExtensions=e.supportedExtensions}async parseFile(e,t){if(this.wasmFailCount<u.MAX_WASM_RETRIES)try{return await this.wasmParser.parseFile(e,t)}catch(s){this.wasmFailCount++;let n=s instanceof Error?s.message:String(s),i=this.wasmFailCount>=u.MAX_WASM_RETRIES;z.warn(`[${this.language}] tree-sitter WASM parser failed (attempt ${this.wasmFailCount}/${u.MAX_WASM_RETRIES}): ${n}. Falling back to regex parser (~97-98% accuracy). `+(i?"Set AQE_PARSER_REGEX_ONLY=1 to silence this warning.":"Will retry WASM on next parse."))}return this.regexParser.parseFile(e,t)}},oe=class{parsers=new Map;_wasmInitPromise=null;constructor(){this.register(new Y),this.register(new Z),this.register(new ee),this.register(new te),this.register(new se),this.register(new ne),this.register(new ie),this.register(new re),this._wasmInitPromise=this._tryLoadWasmParsers()}async _tryLoadWasmParsers(){try{let e=await import("./tree-sitter-wasm-parser-U3PQPIK7.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 ve){let n=t.get(s),i=this.parsers.get(s);n&&i&&this.parsers.set(s,new ae(n,i))}z.info("tree-sitter WASM parsers available for: "+ve.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)}},Xe=new oe;import*as S from"node:fs/promises";import*as R from"node:path";var Me=[/\.\./,/%2e%2e/i,/%252e%252e/i,/\.\.%2f/i,/%2f\.\./i,/\.\.%5c/i,/\.\.\\/,/%c0%ae/i,/%c0%2f/i,/%c1%9c/i,/\0/,/%00/i],Te=[/^\/etc\//i,/^\/proc\//i,/^\/sys\//i,/^\/dev\//i,/^\/root\//i,/^\/home\/.+\/\./i,/^[A-Z]:\\Windows/i,/^[A-Z]:\\System/i,/^[A-Z]:\\Users\\.+\\AppData/i],le=class{name="path-traversal";getRiskLevel(){return"critical"}validate(e,t={}){let{basePath:s="",allowAbsolute:n=!1,allowedExtensions:i=[],deniedExtensions:o=[".exe",".bat",".cmd",".sh",".ps1",".dll",".so"],maxDepth:r=10,maxLength:a=4096}=t;if(e.length>a)return{valid:!1,error:`Path exceeds maximum length of ${a}`,riskLevel:"medium"};for(let f of Me)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 Te)if(f.test(e))return{valid:!1,error:"Access to system paths is not allowed",riskLevel:"critical"};let c=this.normalizePath(e);if(c.includes(".."))return{valid:!1,error:"Path traversal detected after normalization",riskLevel:"critical"};if(c.split("/").filter(Boolean).length>r)return{valid:!1,error:`Path depth exceeds maximum of ${r}`,riskLevel:"low"};let d=this.getExtension(c);if(d){let f=`.${d.toLowerCase()}`,g=d.toLowerCase();if(o.length>0&&o.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not allowed`,riskLevel:"high"};if(i.length>0&&!i.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not in allowed list`,riskLevel:"medium"}}let p=s?this.joinPathsAbsolute(s,c):c,h=s.startsWith("/")?`/${this.normalizePath(s)}`:this.normalizePath(s);return s&&!p.startsWith(h)?{valid:!1,error:"Path escapes base directory",riskLevel:"critical"}:{valid:!0,normalizedPath:p,riskLevel:"none"}}normalizePath(e){let t=e.replace(/\\/g,"/");t=t.replace(/\/+/g,"/");let s=t.split("/"),n=[];for(let i of s)i==="."||i===""||(i===".."?n.length>0&&n[n.length-1]!==".."&&n.pop():n.push(i));return n.join("/")}joinPaths(...e){return e.length===0?"":e.map(t=>t.replace(/^\/+/,"").replace(/\/+$/,"")).filter(Boolean).join("/")}joinPathsAbsolute(...e){if(e.length===0)return"";let t=e[0].startsWith("/"),s=e.map(n=>{for(;n.startsWith("/");)n=n.slice(1);for(;n.endsWith("/");)n=n.slice(0,-1);return n}).filter(Boolean).join("/");return t?`/${s}`:s}getExtension(e){let t=e.match(/\.([^./\\]+)$/);return t?t[1]:null}},Fe=new le,Ee=(u,e)=>Fe.validate(u,e);ye();var F=class extends Error{constructor(t,s,n,i){super(t);this.filePath=s;this.code=n;this.cause=i;this.name="FileReadError"}filePath;code;cause},V=class extends Error{constructor(t,s,n){super(t);this.filePath=s;this.cause=n;this.name="JsonParseError"}filePath;cause},T=class extends Error{constructor(t,s,n){super(`Path traversal detected: ${s.join(", ")}`);this.requestedPath=t;this.issues=s;this.riskLevel=n;this.name="PathTraversalError"}requestedPath;issues;riskLevel},de=class{constructor(e,t){this.maxSize=e;this.ttlMs=t}maxSize;ttlMs;cache=new Map;accessOrder=[];get(e){let t=this.cache.get(e);if(t){if(Date.now()-t.timestamp>this.ttlMs){this.delete(e);return}return this.updateAccessOrder(e),t.value}}set(e,t,s){for(this.cache.has(e)&&this.delete(e);this.cache.size>=this.maxSize&&this.accessOrder.length>0;){let n=this.accessOrder.shift();n&&this.cache.delete(n)}this.cache.set(e,{value:t,timestamp:Date.now(),size:s}),this.accessOrder.push(e)}delete(e){let t=this.cache.delete(e);if(t){let s=this.accessOrder.indexOf(e);s>-1&&this.accessOrder.splice(s,1)}return t}clear(){this.cache.clear(),this.accessOrder=[]}get size(){return this.cache.size}get totalBytes(){let e=0;return this.cache.forEach(t=>{e+=t.size}),e}updateAccessOrder(e){let t=this.accessOrder.indexOf(e);t>-1&&(this.accessOrder.splice(t,1),this.accessOrder.push(e))}prune(){let e=Date.now(),t=0,s=[];return this.cache.forEach((n,i)=>{e-n.timestamp>this.ttlMs&&s.push(i)}),s.forEach(n=>{this.delete(n),t++}),t}};function Ae(u){let e="",t=0;for(;t<u.length;){let s=u[t],n=u[t+1];s==="*"&&n==="*"?u[t+2]==="/"?(e+="(?:.*/)?",t+=3):(e+=".*",t+=2):s==="*"?(e+="[^/]*",t++):s==="?"?(e+="[^/]",t++):".+^${}()|[]\\".includes(s)?(e+="\\"+s,t++):(e+=s,t++)}return new RegExp("^"+e+"$")}async function Ie(u,e,t,s){try{let n=await S.readdir(u,{withFileTypes:!0});for(let i of n){let o=R.join(u,i.name),r=R.relative(s,o);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&await Ie(o,e,t,s);else if(i.isFile()){let a=r.replace(/\\/g,"/");e.test(a)&&t.push(o)}}}catch(n){console.debug("[FileReader] Directory read error:",n instanceof Error?n.message:n)}}var k=class{basePath;cache;enableCache;stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:0,cacheEntries:0};constructor(e={}){this.basePath=e.basePath??process.cwd(),this.enableCache=e.enableCache??!0,this.cache=new de(e.maxCacheSize??100,e.cacheTtlMs??300*1e3)}resolvePath(e){let t=R.isAbsolute(e),s=Ee(e,{basePath:t?"":this.basePath,allowAbsolute:!0,deniedExtensions:[".exe",".bat",".cmd",".ps1",".dll",".so"]});if(!s.valid)throw new T(e,[s.error||"Path validation failed"],s.riskLevel);if(t&&this.basePath){let n=R.resolve(this.basePath),i=R.resolve(e);if(!i.startsWith(n))throw new T(e,["Path escapes base directory"],"critical");return i}return s.normalizedPath?s.normalizedPath:t?e:R.resolve(this.basePath,e)}async readFile(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}if(this.stats.totalReads++,this.enableCache){let s=this.cache.get(t);if(s!==void 0)return this.stats.cacheHits++,this.updateCacheStats(),P(s);this.stats.cacheMisses++}try{let s=await S.readFile(t,"utf-8");return this.enableCache&&(this.cache.set(t,s,Buffer.byteLength(s,"utf-8")),this.updateCacheStats()),P(s)}catch(s){let n=s,i;switch(n.code){case"ENOENT":i="File not found: "+t;break;case"EACCES":i="Permission denied: "+t;break;case"EISDIR":i="Path is a directory: "+t;break;default:i="Failed to read file: "+t}return L(new F(i,t,n.code,n))}}async readJSON(e){let t=await this.readFile(e);if(!t.success)return t;try{let s=D(t.value);return P(s)}catch(s){let n=s,i=e;try{i=this.resolvePath(e)}catch{}return L(new V("Invalid JSON in file: "+i+" - "+n.message,i,n))}}async fileExists(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}try{return await S.access(t,S.constants.F_OK),P(!0)}catch(s){let n=s;return n.code==="ENOENT"?P(!1):L(new F("Cannot check file existence: "+t,t,n.code,n))}}async listFiles(e,t){let s;try{s=t?this.resolvePath(t):this.basePath}catch(n){if(n instanceof T)return L(n);throw n}try{if(!(await S.stat(s)).isDirectory())return L(new F("Base path is not a directory: "+s,s,"ENOTDIR"));let i=Ae(e),o=[];return await Ie(s,i,o,s),o.sort(),P(o)}catch(n){let i=n;return L(new F("Failed to list files in: "+s,s,i.code,i))}}invalidateCache(e){let t=this.resolvePath(e);this.cache.delete(t),this.updateCacheStats()}clearCache(){this.cache.clear(),this.updateCacheStats()}pruneCache(){let e=this.cache.prune();return this.updateCacheStats(),e}getStats(){return{...this.stats}}resetStats(){this.stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:this.cache.totalBytes,cacheEntries:this.cache.size}}updateCacheStats(){this.stats.cacheSize=this.cache.totalBytes,this.stats.cacheEntries=this.cache.size}};J();var v={MODEL:"all-MiniLM-L6-v2",DIMENSIONS:384,CONTEXT_WINDOW:8192,BATCH_SIZE:100,MAX_RETRIES:3,RETRY_DELAY_MS:1e3,TIMEOUT_MS:3e4,DEFAULT_OLLAMA_URL:"http://localhost:11434"};Re();var _=class{baseUrl;maxRetries;retryDelayMs;timeoutMs;constructor(e=be(v.DEFAULT_OLLAMA_URL),t=v.MAX_RETRIES,s=v.RETRY_DELAY_MS,n=v.TIMEOUT_MS){this.baseUrl=e.replace(/\/$/,""),this.maxRetries=t,this.retryDelayMs=s,this.timeoutMs=n}async healthCheck(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);if(!e.ok)return!1;let t=await e.json();return t.models?t.models.some(s=>s.name?.startsWith(v.MODEL)||s.model?.startsWith(v.MODEL)):!1}catch{return!1}}async generateEmbedding(e){let t={model:v.MODEL,prompt:e},s=null;for(let n=0;n<this.maxRetries;n++)try{let i=await this.fetchWithTimeout(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},this.timeoutMs);if(!i.ok){let r=await i.text();throw new Error(`Ollama API error (${i.status}): ${r}`)}let o=await i.json();if(o.embedding.length!==v.DIMENSIONS)throw new Error(`Invalid embedding dimensions: expected ${v.DIMENSIONS}, got ${o.embedding.length}`);return o.embedding}catch(i){if(s=A(i),s.message.includes("Invalid embedding dimensions"))throw s;if(n<this.maxRetries-1){let o=this.retryDelayMs*Math.pow(2,n);await this.sleep(o)}}throw new Error(`Failed to generate embedding after ${this.maxRetries} attempts: ${s?.message}`)}async fetchWithTimeout(e,t,s){let n=new AbortController,i=setTimeout(()=>n.abort(),s);try{return await fetch(e,{...t,signal:n.signal})}finally{clearTimeout(i)}}sleep(e){return new Promise(t=>setTimeout(t,e))}async getServerInfo(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);return e.ok?await e.json():null}catch{return null}}async ensureModelAvailable(){if(!await this.healthCheck())throw new Error(`Ollama model '${v.MODEL}' is not available. Please run: ollama pull ${v.MODEL}`)}};import{createHash as Ne}from"crypto";var $=class{cache;maxSize;hits;misses;constructor(e=1e4){this.cache=new Map,this.maxSize=e,this.hits=0,this.misses=0}hashContent(e,t){return Ne("sha256").update(`${t}:${e}`).digest("hex")}get(e,t){let s=this.hashContent(e,t),n=this.cache.get(s);return n?(this.hits++,this.cache.delete(s),this.cache.set(s,n),n.embedding):(this.misses++,null)}set(e,t,s){let n=this.hashContent(e,t);if(this.cache.size>=this.maxSize&&!this.cache.has(n)){let o=this.cache.keys().next().value;o&&this.cache.delete(o)}let i={embedding:s,timestamp:Date.now(),model:t};this.cache.set(n,i)}has(e,t){let s=this.hashContent(e,t);return this.cache.has(s)}getStats(){let e=this.hits+this.misses,t=e>0?this.hits/e:0;return{size:this.cache.size,hitRate:t,hits:this.hits,misses:this.misses}}clear(){this.cache.clear(),this.hits=0,this.misses=0}evictOlderThan(e){let s=Date.now()-e,n=0;for(let[i,o]of this.cache.entries())o.timestamp<s&&(this.cache.delete(i),n++);return n}getMemoryUsageEstimate(){return this.cache.size*3172}export(){return Array.from(this.cache.entries()).map(([e,t])=>({key:e,entry:t}))}import(e){this.cache.clear();for(let{key:t,entry:s}of e)this.cache.size<this.maxSize&&this.cache.set(t,s)}};J();var K=class{client;cache;batchSize;enableFallback;ollamaAvailable=null;constructor(e={}){this.client=new _(e.ollamaBaseUrl),this.cache=e.cache??new $(e.maxCacheSize),this.batchSize=e.batchSize??v.BATCH_SIZE,this.enableFallback=e.enableFallback??!0}async embed(e){let t=this.cache.get(e,v.MODEL);if(t)return t;let s;if(await this.isOllamaAvailable())s=await this.client.generateEmbedding(e);else if(this.enableFallback)s=this.generatePseudoEmbedding(e);else throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);return this.cache.set(e,v.MODEL,s),s}formatForEmbedding(e){let t=[];e.language&&t.push(e.language),e.type&&t.push(e.type),e.name&&t.push(e.name);let s=t.length>0?`${t.join(" ")}: `:"",n=v.CONTEXT_WINDOW*4,i=e.content.trim();if(s.length+i.length>n){let o=n-s.length-3;i=i.substring(0,o)+"..."}return s+i}async embedBatch(e){let t=[];for(let s of e){let n=await this.embed(s);t.push(n)}return t}async embedCodeChunks(e,t){let s=Date.now(),n=[],i=0,o=0,r=await this.isOllamaAvailable();if(r)await this.client.ensureModelAvailable();else if(!this.enableFallback)throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);for(let c=0;c<e.length;c+=this.batchSize){let l=e.slice(c,Math.min(c+this.batchSize,e.length)),d=await this.processBatch(l,r);n.push(...d);for(let p of d)p.cached?i++:o++;if(t){let p=c+l.length,h=e.length,g=(Date.now()-s)/p,y=(h-p)*g;t({current:p,total:h,percentage:p/h*100,estimatedTimeRemainingMs:y})}}let a=Date.now()-s;return{results:n,stats:{totalChunks:e.length,cachedHits:i,computedNew:o,totalTimeMs:a,avgTimePerChunk:a/e.length}}}async processBatch(e,t){let s=[],n=e.map(async o=>{let r=this.formatForEmbedding(o),a=Date.now(),c=this.cache.get(r,v.MODEL);if(c)return{chunkId:o.id,embedding:c,model:v.MODEL,cached:!0,computeTimeMs:Date.now()-a};try{let l;return t?l=await this.client.generateEmbedding(r):l=this.generatePseudoEmbedding(r),this.cache.set(r,v.MODEL,l),{chunkId:o.id,embedding:l,model:t?v.MODEL:"pseudo-embedding",cached:!1,computeTimeMs:Date.now()-a}}catch(l){throw new Error(`Failed to generate embedding for chunk ${o.id}: ${G(l)}`)}}),i=await Promise.all(n);return s.push(...i),s}async isOllamaAvailable(){return this.ollamaAvailable!==null?this.ollamaAvailable:(this.ollamaAvailable=await this.client.healthCheck(),this.ollamaAvailable)}resetOllamaCheck(){this.ollamaAvailable=null}generatePseudoEmbedding(e){let t=new Array(v.DIMENSIONS).fill(0),s=e.split(/\s+|[^\w]+/).filter(o=>o.length>0);for(let o=0;o<s.length;o++){let r=s[o];for(let a=0;a<r.length&&a<t.length;a++)t[(o+a)%t.length]+=r.charCodeAt(a)/1e3}let n=[[/class\s+\w+/,0],[/function\s+\w+/,1],[/async\s+|await\s+|Promise/,2],[/interface\s+\w+/,3],[/export\s+/,4],[/import\s+/,5],[/try\s*{/,6],[/\.(map|filter|reduce)\(/,7]];for(let[o,r]of n)o.test(e)&&(t[r]+=.5);let i=Math.sqrt(t.reduce((o,r)=>o+r*r,0))||1;return t.map(o=>o/i)}clearCache(){this.cache.clear()}getCacheStats(){return this.cache.getStats()}async healthCheck(){return await this.client.healthCheck()}async getServerInfo(){return await this.client.getServerInfo()}getDimensions(){return v.DIMENSIONS}getConfig(){return{model:v.MODEL,dimensions:v.DIMENSIONS,contextWindow:v.CONTEXT_WINDOW,batchSize:this.batchSize,maxRetries:v.MAX_RETRIES,enableFallback:this.enableFallback}}};J();ye();import{existsSync as _e,statSync as $e}from"fs";import{dirname as Ke,resolve as Ue,join as q}from"path";function De(u){switch(u){case"ts":case"mts":case"cts":return"tree-sitter-typescript.wasm";case"tsx":return"tree-sitter-tsx.wasm";case"js":case"jsx":case"mjs":case"cjs":return"tree-sitter-javascript.wasm";default:return null}}var U=u=>u.startPosition.row+1,j=(u,e)=>u.childForFieldName(e)?.text??"";function ue(u){for(let e=0;e<u.childCount;e++){let t=u.child(e);if(t){if(t.type==="async")return!0;if(t.type==="function"||t.type==="function_declaration")break}}return!1}function Oe(u){for(let e=0;e<u.childCount;e++)if(u.child(e)?.type==="accessibility_modifier"){let s=u.child(e).text;if(s==="private")return"private";if(s==="protected")return"protected"}return"public"}function ke(u){let e=j(u,"name")||"(anonymous)",t=u.childForFieldName("body"),s=[];if(t)for(let n=0;n<t.childCount;n++){let i=t.child(n);i&&i.type==="method_definition"&&s.push({name:j(i,"name"),startLine:U(i),isAsync:ue(i),visibility:Oe(i)})}return{name:e,startLine:U(u),methods:s}}function pe(u){return u.replace(/^['"`]|['"`]$/g,"")}async function me(u,e){let t=De(e);if(!t)return null;let s=await xe(t);if(!s)return null;let n=null;try{let i=s.parse(u);n=i;let o=i.rootNode;if(!o)return null;let r={functions:[],classes:[],interfaces:[],imports:[]},a=[o];for(;a.length;){let c=a.pop(),l=!0;switch(c.type){case"function_declaration":case"generator_function_declaration":r.functions.push({name:j(c,"name"),startLine:U(c),isAsync:ue(c),visibility:"public"}),l=!1;break;case"class_declaration":case"class":r.classes.push(ke(c)),l=!1;break;case"interface_declaration":r.interfaces.push({name:j(c,"name"),startLine:U(c)}),l=!1;break;case"lexical_declaration":case"variable_declaration":{for(let d=0;d<c.childCount;d++){let p=c.child(d);if(!p||p.type!=="variable_declarator")continue;let h=p.childForFieldName("value");if(h&&(h.type==="arrow_function"||h.type==="function"||h.type==="function_expression"))r.functions.push({name:j(p,"name"),startLine:U(p),isAsync:ue(h),visibility:"public"});else if(h&&h.type==="call_expression"&&h.child(0)?.text==="require"){let f=h.childForFieldName("arguments")?.child(1);f&&f.type==="string"&&r.imports.push(pe(f.text))}}l=!1;break}case"import_statement":{let d=c.childForFieldName("source");d&&r.imports.push(pe(d.text)),l=!1;break}case"call_expression":{let d=c.child(0);if(d&&d.text==="require"){let h=c.childForFieldName("arguments")?.child(1);h&&h.type==="string"&&r.imports.push(pe(h.text))}break}}if(l)for(let d=c.childCount-1;d>=0;d--){let p=c.child(d);p&&a.push(p)}}return r}catch{return null}finally{n?.delete?.()}}var je={maxNodes:1e5,maxEdgesPerNode:500,namespace:"code-intelligence:kg",enableVectorEmbeddings:!0,embeddingDimension:384,enableLLMExtraction:!0,llmModelTier:2,llmMaxTokens:2048},he=fe.create("code-intelligence/knowledge-graph"),H=new Set(["ts","tsx","js","jsx"]),we=class{config;memory;nodeCache=new Map;edgeIndex=new Map;allEdgesCache;tsParser;fileReader;embedder;llmRouter;constructor(e,t={}){this.config={...je,...t},this.isKnowledgeGraphDependencies(e)?(this.memory=e.memory,this.llmRouter=e.llmRouter):(this.memory=e,this.llmRouter=void 0),this.tsParser=new N,this.fileReader=new k(this.config.basePath?{basePath:this.config.basePath}:void 0),this.embedder=new K({enableFallback:!0})}isKnowledgeGraphDependencies(e){return e.memory!==void 0}get nsOpts(){return{namespace:this.config.namespace}}async index(e){let t=Date.now(),s=[],n=0,i=0,o=new Map;try{let{paths:r,incremental:a=!1,includeTests:c=!0,languages:l}=e;a||await this.clear();for(let h of r)try{if(l&&l.length>0){let b=this.getFileExtension(h);if(!this.matchesLanguage(b,l))continue}if(!c&&this.isTestFile(h))continue;let f=this.getFileExtension(h);H.has(f)||o.set(f||"(none)",(o.get(f||"(none)")??0)+1);let g=await this.indexFile(h,a);n+=g.nodes,i+=g.edges}catch(f){s.push({file:h,error:G(f)})}let d=Date.now()-t,p=[];if(o.size>0){let h=Array.from(H).join(", ");for(let[f,g]of o){let b=`${g} file(s) with extension '.${f}' were indexed as plain nodes: no dependency extractor for this language, so 'deps'/'impact' will report 0 edges for them. Supported: ${h}.`;p.push(b),he.warn(b)}}return await this.storeIndexMetadata({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,indexedAt:new Date().toISOString()}),P({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,errors:s,warnings:p})}catch(r){return L(A(r))}}async query(e){try{let{query:t,type:s,limit:n=100}=e;return s==="cypher"?this.executeCypherQuery(t,n):this.executeNaturalLanguageQuery(t,n)}catch(t){return L(A(t))}}async mapDependencies(e){try{let{files:t,direction:s,depth:n=3}=e,i=[],o=[],r=new Set,a=[];for(let l of t)await this.traverseDependencies(l,s,n,r,i,o,[],a);let c=this.calculateDependencyMetrics(i,o);return P({nodes:i,edges:o,cycles:a,metrics:c})}catch(t){return L(A(t))}}async getNode(e){if(this.nodeCache.has(e))return this.nodeCache.get(e);let t=`${this.config.namespace}:node:${e}`,s=await this.memory.get(t,this.nsOpts);return s&&this.nodeCache.set(e,s),s}async getEdges(e,t){let s=await this.loadAllEdges();return this.filterEdgesByDirection(s,e,t)}async loadAllEdges(){if(this.allEdgesCache)return this.allEdgesCache;let e=[],t=`${this.config.namespace}:edge:*`,s=await this.memory.search(t,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let n of s){let i=await this.memory.get(n,this.nsOpts);i&&e.push(i)}return this.allEdgesCache=e,e}async clear(){this.nodeCache.clear(),this.edgeIndex.clear(),this.allEdgesCache=void 0;for(let e of[`${this.config.namespace}:node:`,`${this.config.namespace}:edge:`]){let t=await this.memory.search(`${e}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let s of t)await this.memory.delete(s,this.nsOpts)}}async removeFileFromGraph(e){let t=this.pathToNodeId(e),s=this.config.namespace,n=await this.memory.search(`${s}:node:${t}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of n)await this.memory.delete(o,this.nsOpts),this.nodeCache.delete(o.slice(`${s}:node:`.length));let i=await this.memory.search(`${s}:edge:*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of i){let r=await this.memory.get(o,this.nsOpts);r&&(r.source===t||r.source.startsWith(`${t}:`))&&await this.memory.delete(o,this.nsOpts)}this.edgeIndex.delete(t),this.allEdgesCache=void 0}isLLMExtractionAvailable(){return this.config.enableLLMExtraction===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){case 1:return"claude-haiku-4-5-20251001";case 2:return"claude-sonnet-4-6";case 3:return"claude-sonnet-4-6";case 4:return"claude-opus-4-7";default:return"claude-sonnet-4-6"}}async extractRelationshipsWithLLM(e,t){if(!this.llmRouter)return{semanticRelationships:[],designPatterns:[],architecturalBoundaries:[],dependencyImpacts:[]};try{let s=this.buildRelationshipExtractionPrompt(e,t),n=this.getModelForTier(this.config.llmModelTier??2),i=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software architect analyzing code structure. Extract:
23
+ `);for(let n of s){let i=n.match(/^\s*import\s+'([^']+)'/);i&&t.push({module:i[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){if(!e.trim())return[];let t=e.replace(/[{}[\]]/g,"");return M(t).map(s=>s.trim()).filter(s=>s).map(s=>{let n=s.replace("required ","").trim().split(/\s+/),i=n[n.length-1]||"",o=n.slice(0,-1).join(" ")||void 0;return{name:i,type:o,isOptional:s.includes("?")||s.includes("{"),defaultValue:void 0}})}},z=ge("ParserRegistry"),ve=["python","java","csharp","rust","swift"],ae=class u{language;supportedExtensions;wasmParser;regexParser;wasmFailCount=0;static MAX_WASM_RETRIES=3;constructor(e,t){this.wasmParser=e,this.regexParser=t,this.language=e.language,this.supportedExtensions=e.supportedExtensions}async parseFile(e,t){if(this.wasmFailCount<u.MAX_WASM_RETRIES)try{return await this.wasmParser.parseFile(e,t)}catch(s){this.wasmFailCount++;let n=s instanceof Error?s.message:String(s),i=this.wasmFailCount>=u.MAX_WASM_RETRIES;z.warn(`[${this.language}] tree-sitter WASM parser failed (attempt ${this.wasmFailCount}/${u.MAX_WASM_RETRIES}): ${n}. Falling back to regex parser (~97-98% accuracy). `+(i?"Set AQE_PARSER_REGEX_ONLY=1 to silence this warning.":"Will retry WASM on next parse."))}return this.regexParser.parseFile(e,t)}},oe=class{parsers=new Map;_wasmInitPromise=null;constructor(){this.register(new Y),this.register(new Z),this.register(new ee),this.register(new te),this.register(new se),this.register(new ne),this.register(new ie),this.register(new re),this._wasmInitPromise=this._tryLoadWasmParsers()}async _tryLoadWasmParsers(){try{let e=await import("./tree-sitter-wasm-parser-LLIW2X3M.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 ve){let n=t.get(s),i=this.parsers.get(s);n&&i&&this.parsers.set(s,new ae(n,i))}z.info("tree-sitter WASM parsers available for: "+ve.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)}},Xe=new oe;import*as S from"node:fs/promises";import*as R from"node:path";var Me=[/\.\./,/%2e%2e/i,/%252e%252e/i,/\.\.%2f/i,/%2f\.\./i,/\.\.%5c/i,/\.\.\\/,/%c0%ae/i,/%c0%2f/i,/%c1%9c/i,/\0/,/%00/i],Te=[/^\/etc\//i,/^\/proc\//i,/^\/sys\//i,/^\/dev\//i,/^\/root\//i,/^\/home\/.+\/\./i,/^[A-Z]:\\Windows/i,/^[A-Z]:\\System/i,/^[A-Z]:\\Users\\.+\\AppData/i],le=class{name="path-traversal";getRiskLevel(){return"critical"}validate(e,t={}){let{basePath:s="",allowAbsolute:n=!1,allowedExtensions:i=[],deniedExtensions:o=[".exe",".bat",".cmd",".sh",".ps1",".dll",".so"],maxDepth:r=10,maxLength:a=4096}=t;if(e.length>a)return{valid:!1,error:`Path exceeds maximum length of ${a}`,riskLevel:"medium"};for(let f of Me)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 Te)if(f.test(e))return{valid:!1,error:"Access to system paths is not allowed",riskLevel:"critical"};let c=this.normalizePath(e);if(c.includes(".."))return{valid:!1,error:"Path traversal detected after normalization",riskLevel:"critical"};if(c.split("/").filter(Boolean).length>r)return{valid:!1,error:`Path depth exceeds maximum of ${r}`,riskLevel:"low"};let d=this.getExtension(c);if(d){let f=`.${d.toLowerCase()}`,g=d.toLowerCase();if(o.length>0&&o.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not allowed`,riskLevel:"high"};if(i.length>0&&!i.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not in allowed list`,riskLevel:"medium"}}let p=s?this.joinPathsAbsolute(s,c):c,h=s.startsWith("/")?`/${this.normalizePath(s)}`:this.normalizePath(s);return s&&!p.startsWith(h)?{valid:!1,error:"Path escapes base directory",riskLevel:"critical"}:{valid:!0,normalizedPath:p,riskLevel:"none"}}normalizePath(e){let t=e.replace(/\\/g,"/");t=t.replace(/\/+/g,"/");let s=t.split("/"),n=[];for(let i of s)i==="."||i===""||(i===".."?n.length>0&&n[n.length-1]!==".."&&n.pop():n.push(i));return n.join("/")}joinPaths(...e){return e.length===0?"":e.map(t=>t.replace(/^\/+/,"").replace(/\/+$/,"")).filter(Boolean).join("/")}joinPathsAbsolute(...e){if(e.length===0)return"";let t=e[0].startsWith("/"),s=e.map(n=>{for(;n.startsWith("/");)n=n.slice(1);for(;n.endsWith("/");)n=n.slice(0,-1);return n}).filter(Boolean).join("/");return t?`/${s}`:s}getExtension(e){let t=e.match(/\.([^./\\]+)$/);return t?t[1]:null}},Fe=new le,Ee=(u,e)=>Fe.validate(u,e);ye();var F=class extends Error{constructor(t,s,n,i){super(t);this.filePath=s;this.code=n;this.cause=i;this.name="FileReadError"}filePath;code;cause},V=class extends Error{constructor(t,s,n){super(t);this.filePath=s;this.cause=n;this.name="JsonParseError"}filePath;cause},T=class extends Error{constructor(t,s,n){super(`Path traversal detected: ${s.join(", ")}`);this.requestedPath=t;this.issues=s;this.riskLevel=n;this.name="PathTraversalError"}requestedPath;issues;riskLevel},de=class{constructor(e,t){this.maxSize=e;this.ttlMs=t}maxSize;ttlMs;cache=new Map;accessOrder=[];get(e){let t=this.cache.get(e);if(t){if(Date.now()-t.timestamp>this.ttlMs){this.delete(e);return}return this.updateAccessOrder(e),t.value}}set(e,t,s){for(this.cache.has(e)&&this.delete(e);this.cache.size>=this.maxSize&&this.accessOrder.length>0;){let n=this.accessOrder.shift();n&&this.cache.delete(n)}this.cache.set(e,{value:t,timestamp:Date.now(),size:s}),this.accessOrder.push(e)}delete(e){let t=this.cache.delete(e);if(t){let s=this.accessOrder.indexOf(e);s>-1&&this.accessOrder.splice(s,1)}return t}clear(){this.cache.clear(),this.accessOrder=[]}get size(){return this.cache.size}get totalBytes(){let e=0;return this.cache.forEach(t=>{e+=t.size}),e}updateAccessOrder(e){let t=this.accessOrder.indexOf(e);t>-1&&(this.accessOrder.splice(t,1),this.accessOrder.push(e))}prune(){let e=Date.now(),t=0,s=[];return this.cache.forEach((n,i)=>{e-n.timestamp>this.ttlMs&&s.push(i)}),s.forEach(n=>{this.delete(n),t++}),t}};function Ae(u){let e="",t=0;for(;t<u.length;){let s=u[t],n=u[t+1];s==="*"&&n==="*"?u[t+2]==="/"?(e+="(?:.*/)?",t+=3):(e+=".*",t+=2):s==="*"?(e+="[^/]*",t++):s==="?"?(e+="[^/]",t++):".+^${}()|[]\\".includes(s)?(e+="\\"+s,t++):(e+=s,t++)}return new RegExp("^"+e+"$")}async function Ie(u,e,t,s){try{let n=await S.readdir(u,{withFileTypes:!0});for(let i of n){let o=R.join(u,i.name),r=R.relative(s,o);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&await Ie(o,e,t,s);else if(i.isFile()){let a=r.replace(/\\/g,"/");e.test(a)&&t.push(o)}}}catch(n){console.debug("[FileReader] Directory read error:",n instanceof Error?n.message:n)}}var k=class{basePath;cache;enableCache;stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:0,cacheEntries:0};constructor(e={}){this.basePath=e.basePath??process.cwd(),this.enableCache=e.enableCache??!0,this.cache=new de(e.maxCacheSize??100,e.cacheTtlMs??300*1e3)}resolvePath(e){let t=R.isAbsolute(e),s=Ee(e,{basePath:t?"":this.basePath,allowAbsolute:!0,deniedExtensions:[".exe",".bat",".cmd",".ps1",".dll",".so"]});if(!s.valid)throw new T(e,[s.error||"Path validation failed"],s.riskLevel);if(t&&this.basePath){let n=R.resolve(this.basePath),i=R.resolve(e);if(!i.startsWith(n))throw new T(e,["Path escapes base directory"],"critical");return i}return s.normalizedPath?s.normalizedPath:t?e:R.resolve(this.basePath,e)}async readFile(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}if(this.stats.totalReads++,this.enableCache){let s=this.cache.get(t);if(s!==void 0)return this.stats.cacheHits++,this.updateCacheStats(),P(s);this.stats.cacheMisses++}try{let s=await S.readFile(t,"utf-8");return this.enableCache&&(this.cache.set(t,s,Buffer.byteLength(s,"utf-8")),this.updateCacheStats()),P(s)}catch(s){let n=s,i;switch(n.code){case"ENOENT":i="File not found: "+t;break;case"EACCES":i="Permission denied: "+t;break;case"EISDIR":i="Path is a directory: "+t;break;default:i="Failed to read file: "+t}return L(new F(i,t,n.code,n))}}async readJSON(e){let t=await this.readFile(e);if(!t.success)return t;try{let s=D(t.value);return P(s)}catch(s){let n=s,i=e;try{i=this.resolvePath(e)}catch{}return L(new V("Invalid JSON in file: "+i+" - "+n.message,i,n))}}async fileExists(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}try{return await S.access(t,S.constants.F_OK),P(!0)}catch(s){let n=s;return n.code==="ENOENT"?P(!1):L(new F("Cannot check file existence: "+t,t,n.code,n))}}async listFiles(e,t){let s;try{s=t?this.resolvePath(t):this.basePath}catch(n){if(n instanceof T)return L(n);throw n}try{if(!(await S.stat(s)).isDirectory())return L(new F("Base path is not a directory: "+s,s,"ENOTDIR"));let i=Ae(e),o=[];return await Ie(s,i,o,s),o.sort(),P(o)}catch(n){let i=n;return L(new F("Failed to list files in: "+s,s,i.code,i))}}invalidateCache(e){let t=this.resolvePath(e);this.cache.delete(t),this.updateCacheStats()}clearCache(){this.cache.clear(),this.updateCacheStats()}pruneCache(){let e=this.cache.prune();return this.updateCacheStats(),e}getStats(){return{...this.stats}}resetStats(){this.stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:this.cache.totalBytes,cacheEntries:this.cache.size}}updateCacheStats(){this.stats.cacheSize=this.cache.totalBytes,this.stats.cacheEntries=this.cache.size}};J();var v={MODEL:"all-MiniLM-L6-v2",DIMENSIONS:384,CONTEXT_WINDOW:8192,BATCH_SIZE:100,MAX_RETRIES:3,RETRY_DELAY_MS:1e3,TIMEOUT_MS:3e4,DEFAULT_OLLAMA_URL:"http://localhost:11434"};Re();var _=class{baseUrl;maxRetries;retryDelayMs;timeoutMs;constructor(e=be(v.DEFAULT_OLLAMA_URL),t=v.MAX_RETRIES,s=v.RETRY_DELAY_MS,n=v.TIMEOUT_MS){this.baseUrl=e.replace(/\/$/,""),this.maxRetries=t,this.retryDelayMs=s,this.timeoutMs=n}async healthCheck(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);if(!e.ok)return!1;let t=await e.json();return t.models?t.models.some(s=>s.name?.startsWith(v.MODEL)||s.model?.startsWith(v.MODEL)):!1}catch{return!1}}async generateEmbedding(e){let t={model:v.MODEL,prompt:e},s=null;for(let n=0;n<this.maxRetries;n++)try{let i=await this.fetchWithTimeout(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},this.timeoutMs);if(!i.ok){let r=await i.text();throw new Error(`Ollama API error (${i.status}): ${r}`)}let o=await i.json();if(o.embedding.length!==v.DIMENSIONS)throw new Error(`Invalid embedding dimensions: expected ${v.DIMENSIONS}, got ${o.embedding.length}`);return o.embedding}catch(i){if(s=A(i),s.message.includes("Invalid embedding dimensions"))throw s;if(n<this.maxRetries-1){let o=this.retryDelayMs*Math.pow(2,n);await this.sleep(o)}}throw new Error(`Failed to generate embedding after ${this.maxRetries} attempts: ${s?.message}`)}async fetchWithTimeout(e,t,s){let n=new AbortController,i=setTimeout(()=>n.abort(),s);try{return await fetch(e,{...t,signal:n.signal})}finally{clearTimeout(i)}}sleep(e){return new Promise(t=>setTimeout(t,e))}async getServerInfo(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);return e.ok?await e.json():null}catch{return null}}async ensureModelAvailable(){if(!await this.healthCheck())throw new Error(`Ollama model '${v.MODEL}' is not available. Please run: ollama pull ${v.MODEL}`)}};import{createHash as Ne}from"crypto";var $=class{cache;maxSize;hits;misses;constructor(e=1e4){this.cache=new Map,this.maxSize=e,this.hits=0,this.misses=0}hashContent(e,t){return Ne("sha256").update(`${t}:${e}`).digest("hex")}get(e,t){let s=this.hashContent(e,t),n=this.cache.get(s);return n?(this.hits++,this.cache.delete(s),this.cache.set(s,n),n.embedding):(this.misses++,null)}set(e,t,s){let n=this.hashContent(e,t);if(this.cache.size>=this.maxSize&&!this.cache.has(n)){let o=this.cache.keys().next().value;o&&this.cache.delete(o)}let i={embedding:s,timestamp:Date.now(),model:t};this.cache.set(n,i)}has(e,t){let s=this.hashContent(e,t);return this.cache.has(s)}getStats(){let e=this.hits+this.misses,t=e>0?this.hits/e:0;return{size:this.cache.size,hitRate:t,hits:this.hits,misses:this.misses}}clear(){this.cache.clear(),this.hits=0,this.misses=0}evictOlderThan(e){let s=Date.now()-e,n=0;for(let[i,o]of this.cache.entries())o.timestamp<s&&(this.cache.delete(i),n++);return n}getMemoryUsageEstimate(){return this.cache.size*3172}export(){return Array.from(this.cache.entries()).map(([e,t])=>({key:e,entry:t}))}import(e){this.cache.clear();for(let{key:t,entry:s}of e)this.cache.size<this.maxSize&&this.cache.set(t,s)}};J();var K=class{client;cache;batchSize;enableFallback;ollamaAvailable=null;constructor(e={}){this.client=new _(e.ollamaBaseUrl),this.cache=e.cache??new $(e.maxCacheSize),this.batchSize=e.batchSize??v.BATCH_SIZE,this.enableFallback=e.enableFallback??!0}async embed(e){let t=this.cache.get(e,v.MODEL);if(t)return t;let s;if(await this.isOllamaAvailable())s=await this.client.generateEmbedding(e);else if(this.enableFallback)s=this.generatePseudoEmbedding(e);else throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);return this.cache.set(e,v.MODEL,s),s}formatForEmbedding(e){let t=[];e.language&&t.push(e.language),e.type&&t.push(e.type),e.name&&t.push(e.name);let s=t.length>0?`${t.join(" ")}: `:"",n=v.CONTEXT_WINDOW*4,i=e.content.trim();if(s.length+i.length>n){let o=n-s.length-3;i=i.substring(0,o)+"..."}return s+i}async embedBatch(e){let t=[];for(let s of e){let n=await this.embed(s);t.push(n)}return t}async embedCodeChunks(e,t){let s=Date.now(),n=[],i=0,o=0,r=await this.isOllamaAvailable();if(r)await this.client.ensureModelAvailable();else if(!this.enableFallback)throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);for(let c=0;c<e.length;c+=this.batchSize){let l=e.slice(c,Math.min(c+this.batchSize,e.length)),d=await this.processBatch(l,r);n.push(...d);for(let p of d)p.cached?i++:o++;if(t){let p=c+l.length,h=e.length,g=(Date.now()-s)/p,y=(h-p)*g;t({current:p,total:h,percentage:p/h*100,estimatedTimeRemainingMs:y})}}let a=Date.now()-s;return{results:n,stats:{totalChunks:e.length,cachedHits:i,computedNew:o,totalTimeMs:a,avgTimePerChunk:a/e.length}}}async processBatch(e,t){let s=[],n=e.map(async o=>{let r=this.formatForEmbedding(o),a=Date.now(),c=this.cache.get(r,v.MODEL);if(c)return{chunkId:o.id,embedding:c,model:v.MODEL,cached:!0,computeTimeMs:Date.now()-a};try{let l;return t?l=await this.client.generateEmbedding(r):l=this.generatePseudoEmbedding(r),this.cache.set(r,v.MODEL,l),{chunkId:o.id,embedding:l,model:t?v.MODEL:"pseudo-embedding",cached:!1,computeTimeMs:Date.now()-a}}catch(l){throw new Error(`Failed to generate embedding for chunk ${o.id}: ${G(l)}`)}}),i=await Promise.all(n);return s.push(...i),s}async isOllamaAvailable(){return this.ollamaAvailable!==null?this.ollamaAvailable:(this.ollamaAvailable=await this.client.healthCheck(),this.ollamaAvailable)}resetOllamaCheck(){this.ollamaAvailable=null}generatePseudoEmbedding(e){let t=new Array(v.DIMENSIONS).fill(0),s=e.split(/\s+|[^\w]+/).filter(o=>o.length>0);for(let o=0;o<s.length;o++){let r=s[o];for(let a=0;a<r.length&&a<t.length;a++)t[(o+a)%t.length]+=r.charCodeAt(a)/1e3}let n=[[/class\s+\w+/,0],[/function\s+\w+/,1],[/async\s+|await\s+|Promise/,2],[/interface\s+\w+/,3],[/export\s+/,4],[/import\s+/,5],[/try\s*{/,6],[/\.(map|filter|reduce)\(/,7]];for(let[o,r]of n)o.test(e)&&(t[r]+=.5);let i=Math.sqrt(t.reduce((o,r)=>o+r*r,0))||1;return t.map(o=>o/i)}clearCache(){this.cache.clear()}getCacheStats(){return this.cache.getStats()}async healthCheck(){return await this.client.healthCheck()}async getServerInfo(){return await this.client.getServerInfo()}getDimensions(){return v.DIMENSIONS}getConfig(){return{model:v.MODEL,dimensions:v.DIMENSIONS,contextWindow:v.CONTEXT_WINDOW,batchSize:this.batchSize,maxRetries:v.MAX_RETRIES,enableFallback:this.enableFallback}}};J();ye();import{existsSync as _e,statSync as $e}from"fs";import{dirname as Ke,resolve as Ue,join as q}from"path";function De(u){switch(u){case"ts":case"mts":case"cts":return"tree-sitter-typescript.wasm";case"tsx":return"tree-sitter-tsx.wasm";case"js":case"jsx":case"mjs":case"cjs":return"tree-sitter-javascript.wasm";default:return null}}var U=u=>u.startPosition.row+1,j=(u,e)=>u.childForFieldName(e)?.text??"";function ue(u){for(let e=0;e<u.childCount;e++){let t=u.child(e);if(t){if(t.type==="async")return!0;if(t.type==="function"||t.type==="function_declaration")break}}return!1}function Oe(u){for(let e=0;e<u.childCount;e++)if(u.child(e)?.type==="accessibility_modifier"){let s=u.child(e).text;if(s==="private")return"private";if(s==="protected")return"protected"}return"public"}function ke(u){let e=j(u,"name")||"(anonymous)",t=u.childForFieldName("body"),s=[];if(t)for(let n=0;n<t.childCount;n++){let i=t.child(n);i&&i.type==="method_definition"&&s.push({name:j(i,"name"),startLine:U(i),isAsync:ue(i),visibility:Oe(i)})}return{name:e,startLine:U(u),methods:s}}function pe(u){return u.replace(/^['"`]|['"`]$/g,"")}async function me(u,e){let t=De(e);if(!t)return null;let s=await xe(t);if(!s)return null;let n=null;try{let i=s.parse(u);n=i;let o=i.rootNode;if(!o)return null;let r={functions:[],classes:[],interfaces:[],imports:[]},a=[o];for(;a.length;){let c=a.pop(),l=!0;switch(c.type){case"function_declaration":case"generator_function_declaration":r.functions.push({name:j(c,"name"),startLine:U(c),isAsync:ue(c),visibility:"public"}),l=!1;break;case"class_declaration":case"class":r.classes.push(ke(c)),l=!1;break;case"interface_declaration":r.interfaces.push({name:j(c,"name"),startLine:U(c)}),l=!1;break;case"lexical_declaration":case"variable_declaration":{for(let d=0;d<c.childCount;d++){let p=c.child(d);if(!p||p.type!=="variable_declarator")continue;let h=p.childForFieldName("value");if(h&&(h.type==="arrow_function"||h.type==="function"||h.type==="function_expression"))r.functions.push({name:j(p,"name"),startLine:U(p),isAsync:ue(h),visibility:"public"});else if(h&&h.type==="call_expression"&&h.child(0)?.text==="require"){let f=h.childForFieldName("arguments")?.child(1);f&&f.type==="string"&&r.imports.push(pe(f.text))}}l=!1;break}case"import_statement":{let d=c.childForFieldName("source");d&&r.imports.push(pe(d.text)),l=!1;break}case"call_expression":{let d=c.child(0);if(d&&d.text==="require"){let h=c.childForFieldName("arguments")?.child(1);h&&h.type==="string"&&r.imports.push(pe(h.text))}break}}if(l)for(let d=c.childCount-1;d>=0;d--){let p=c.child(d);p&&a.push(p)}}return r}catch{return null}finally{n?.delete?.()}}var je={maxNodes:1e5,maxEdgesPerNode:500,namespace:"code-intelligence:kg",enableVectorEmbeddings:!0,embeddingDimension:384,enableLLMExtraction:!0,llmModelTier:2,llmMaxTokens:2048},he=fe.create("code-intelligence/knowledge-graph"),H=new Set(["ts","tsx","js","jsx"]),we=class{config;memory;nodeCache=new Map;edgeIndex=new Map;allEdgesCache;tsParser;fileReader;embedder;llmRouter;constructor(e,t={}){this.config={...je,...t},this.isKnowledgeGraphDependencies(e)?(this.memory=e.memory,this.llmRouter=e.llmRouter):(this.memory=e,this.llmRouter=void 0),this.tsParser=new N,this.fileReader=new k(this.config.basePath?{basePath:this.config.basePath}:void 0),this.embedder=new K({enableFallback:!0})}isKnowledgeGraphDependencies(e){return e.memory!==void 0}get nsOpts(){return{namespace:this.config.namespace}}async index(e){let t=Date.now(),s=[],n=0,i=0,o=new Map;try{let{paths:r,incremental:a=!1,includeTests:c=!0,languages:l}=e;a||await this.clear();for(let h of r)try{if(l&&l.length>0){let b=this.getFileExtension(h);if(!this.matchesLanguage(b,l))continue}if(!c&&this.isTestFile(h))continue;let f=this.getFileExtension(h);H.has(f)||o.set(f||"(none)",(o.get(f||"(none)")??0)+1);let g=await this.indexFile(h,a);n+=g.nodes,i+=g.edges}catch(f){s.push({file:h,error:G(f)})}let d=Date.now()-t,p=[];if(o.size>0){let h=Array.from(H).join(", ");for(let[f,g]of o){let b=`${g} file(s) with extension '.${f}' were indexed as plain nodes: no dependency extractor for this language, so 'deps'/'impact' will report 0 edges for them. Supported: ${h}.`;p.push(b),he.warn(b)}}return await this.storeIndexMetadata({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,indexedAt:new Date().toISOString()}),P({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,errors:s,warnings:p})}catch(r){return L(A(r))}}async query(e){try{let{query:t,type:s,limit:n=100}=e;return s==="cypher"?this.executeCypherQuery(t,n):this.executeNaturalLanguageQuery(t,n)}catch(t){return L(A(t))}}async mapDependencies(e){try{let{files:t,direction:s,depth:n=3}=e,i=[],o=[],r=new Set,a=[];for(let l of t)await this.traverseDependencies(l,s,n,r,i,o,[],a);let c=this.calculateDependencyMetrics(i,o);return P({nodes:i,edges:o,cycles:a,metrics:c})}catch(t){return L(A(t))}}async getNode(e){if(this.nodeCache.has(e))return this.nodeCache.get(e);let t=`${this.config.namespace}:node:${e}`,s=await this.memory.get(t,this.nsOpts);return s&&this.nodeCache.set(e,s),s}async getEdges(e,t){let s=await this.loadAllEdges();return this.filterEdgesByDirection(s,e,t)}async loadAllEdges(){if(this.allEdgesCache)return this.allEdgesCache;let e=[],t=`${this.config.namespace}:edge:*`,s=await this.memory.search(t,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let n of s){let i=await this.memory.get(n,this.nsOpts);i&&e.push(i)}return this.allEdgesCache=e,e}async clear(){this.nodeCache.clear(),this.edgeIndex.clear(),this.allEdgesCache=void 0;for(let e of[`${this.config.namespace}:node:`,`${this.config.namespace}:edge:`]){let t=await this.memory.search(`${e}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let s of t)await this.memory.delete(s,this.nsOpts)}}async removeFileFromGraph(e){let t=this.pathToNodeId(e),s=this.config.namespace,n=await this.memory.search(`${s}:node:${t}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of n)await this.memory.delete(o,this.nsOpts),this.nodeCache.delete(o.slice(`${s}:node:`.length));let i=await this.memory.search(`${s}:edge:*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of i){let r=await this.memory.get(o,this.nsOpts);r&&(r.source===t||r.source.startsWith(`${t}:`))&&await this.memory.delete(o,this.nsOpts)}this.edgeIndex.delete(t),this.allEdgesCache=void 0}isLLMExtractionAvailable(){return this.config.enableLLMExtraction===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){case 1:return"claude-haiku-4-5-20251001";case 2:return"claude-sonnet-4-6";case 3:return"claude-sonnet-4-6";case 4:return"claude-opus-4-7";default:return"claude-sonnet-4-6"}}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.13.12");process.exit(0)}
2
- import{a as y}from"./chunk-DGFINXUE.js";import{a as g,c as h}from"./chunk-OZ53BIY5.js";import{S as b,b as p}from"./chunk-AN5CGTTJ.js";b();var m=class{calculator;constructor(){this.calculator=new h}computeLambda(t){let n=this.maybeSparsify(t),e=this.toSwarmGraph(n);return this.calculator.getMinCutValue(e)}computeRoutingTier(t,n){let e=this.buildTaskGraphFromTopology(n),o=this.toSwarmGraph(e),s=this.calculator.getMinCutValue(o),r=Math.max(n.length-1,1),a=Math.min(s/r,1),{tier:i,label:d}=this.lambdaToTier(a),c=this.computeConfidence(o,a),l=this.buildRationale(t,a,i,n.length);return{tier:i,label:d,lambda:s,normalizedLambda:a,confidence:c,rationale:l}}getStructuralHealth(t){let n=this.maybeSparsify(t),e=this.toSwarmGraph(n);if(e.isEmpty())return this.emptyHealthReport();let o=this.calculator.getMinCutValue(e),s=e.getStats(),r=Math.max(s.vertexCount-1,1),a=Math.min(o/r,1),i=this.calculator.findWeakVertices(e),d=i.map(f=>f.vertexId),c=1-a,l=a>=.4,u=this.generateHealthSuggestions(a,i.length,s);return{lambda:o,normalizedLambda:a,healthy:l,weakPoints:d,riskScore:c,componentCount:s.componentCount,isConnected:s.isConnected,suggestions:u,analyzedAt:new Date}}maybeSparsify(t){if(!p().useSpectralSparsification||t.edges.length<=100)return t;let n=new Map;t.nodes.forEach((i,d)=>n.set(i.id,d));let e=[];for(let i of t.edges){let d=n.get(i.source),c=n.get(i.target);d!==void 0&&c!==void 0&&e.push([d,c,i.weight])}let o={nodeCount:t.nodes.length,edges:e},r=new y({epsilon:.3}).sparsify(o),a=[];for(let[i,d,c]of r.edges){let l=t.nodes[i],u=t.nodes[d];l&&u&&a.push({source:l.id,target:u.id,weight:c,edgeType:"coordination"})}return{nodes:t.nodes,edges:a}}toSwarmGraph(t){let n=new g;for(let e of t.nodes){let o={id:e.id,type:e.type==="task"||e.type==="agent"?"agent":"domain",domain:e.domain,weight:e.weight,createdAt:new Date,metadata:e.metadata};n.addVertex(o)}for(let e of t.edges)if(n.hasVertex(e.source)&&n.hasVertex(e.target)){let o={source:e.source,target:e.target,weight:e.weight,type:e.edgeType==="dependency"?"dependency":e.edgeType==="communication"?"communication":e.edgeType==="workflow"?"workflow":"coordination",bidirectional:e.edgeType!=="dependency"};n.addEdge(o)}return n}buildTaskGraphFromTopology(t){let n=t.map(r=>({id:r.id,label:r.name,type:"agent",domain:r.domain,weight:r.weight})),e=[],o=new Set(t.map(r=>r.id));for(let r of t)for(let a of r.dependsOn)o.has(a)&&e.push({source:r.id,target:a,weight:1,edgeType:"dependency"});let s=new Map;for(let r of t){let a=s.get(r.domain)||[];a.push(r.id),s.set(r.domain,a)}for(let[,r]of s)for(let a=0;a<r.length;a++)for(let i=a+1;i<r.length;i++)e.push({source:r[a],target:r[i],weight:.5,edgeType:"coordination"});return{nodes:n,edges:e}}lambdaToTier(t){return t>=.8?{tier:1,label:"Haiku"}:t>=.4?{tier:2,label:"Sonnet"}:{tier:3,label:"Opus"}}computeConfidence(t,n){let e=t.getStats();if(e.vertexCount<3)return .4;let o=Math.min(Math.abs(n-.4),Math.abs(n-.8)),s=Math.min(.95,.5+o*2.25),r=Math.min(1,e.density*2);return Math.min(.99,s*(.7+.3*r))}buildRationale(t,n,e,o){let s=t.slice(0,80),r=n>=.8?"highly connected":n>=.4?"moderately connected":"fragmented";return`Task "${s}" routed to ${e===1?"Haiku":e===2?"Sonnet":"Opus"} (Tier ${e}). Fleet topology is ${r} (lambda=${n.toFixed(3)}) across ${o} agents.`}generateHealthSuggestions(t,n,e){let o=[];return e.isConnected||o.push(`Graph has ${e.componentCount} disconnected components. Add cross-domain coordination edges to improve connectivity.`),t<.2?o.push("Critical: Fleet connectivity is very low. Consider spawning coordination agents."):t<.4&&o.push("Warning: Fleet connectivity is below healthy threshold. Reinforce weak connections."),n>0&&o.push(`${n} weak point(s) detected. Add redundant connections to these agents.`),e.vertexCount<3&&o.push("Fleet has fewer than 3 agents. MinCut analysis is most useful with larger topologies."),o}emptyHealthReport(){return{lambda:0,normalizedLambda:0,healthy:!1,weakPoints:[],riskScore:1,componentCount:0,isConnected:!0,suggestions:["No agents in fleet. Spawn agents to build a topology."],analyzedAt:new Date}}};function C(){return new m}export{C as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
+ import{a as y}from"./chunk-HNKPLVYS.js";import{a as g,c as h}from"./chunk-5MZF4N4Q.js";import{S as b,b as p}from"./chunk-ENGKLFLY.js";b();var m=class{calculator;constructor(){this.calculator=new h}computeLambda(t){let n=this.maybeSparsify(t),e=this.toSwarmGraph(n);return this.calculator.getMinCutValue(e)}computeRoutingTier(t,n){let e=this.buildTaskGraphFromTopology(n),o=this.toSwarmGraph(e),s=this.calculator.getMinCutValue(o),r=Math.max(n.length-1,1),a=Math.min(s/r,1),{tier:i,label:d}=this.lambdaToTier(a),c=this.computeConfidence(o,a),l=this.buildRationale(t,a,i,n.length);return{tier:i,label:d,lambda:s,normalizedLambda:a,confidence:c,rationale:l}}getStructuralHealth(t){let n=this.maybeSparsify(t),e=this.toSwarmGraph(n);if(e.isEmpty())return this.emptyHealthReport();let o=this.calculator.getMinCutValue(e),s=e.getStats(),r=Math.max(s.vertexCount-1,1),a=Math.min(o/r,1),i=this.calculator.findWeakVertices(e),d=i.map(f=>f.vertexId),c=1-a,l=a>=.4,u=this.generateHealthSuggestions(a,i.length,s);return{lambda:o,normalizedLambda:a,healthy:l,weakPoints:d,riskScore:c,componentCount:s.componentCount,isConnected:s.isConnected,suggestions:u,analyzedAt:new Date}}maybeSparsify(t){if(!p().useSpectralSparsification||t.edges.length<=100)return t;let n=new Map;t.nodes.forEach((i,d)=>n.set(i.id,d));let e=[];for(let i of t.edges){let d=n.get(i.source),c=n.get(i.target);d!==void 0&&c!==void 0&&e.push([d,c,i.weight])}let o={nodeCount:t.nodes.length,edges:e},r=new y({epsilon:.3}).sparsify(o),a=[];for(let[i,d,c]of r.edges){let l=t.nodes[i],u=t.nodes[d];l&&u&&a.push({source:l.id,target:u.id,weight:c,edgeType:"coordination"})}return{nodes:t.nodes,edges:a}}toSwarmGraph(t){let n=new g;for(let e of t.nodes){let o={id:e.id,type:e.type==="task"||e.type==="agent"?"agent":"domain",domain:e.domain,weight:e.weight,createdAt:new Date,metadata:e.metadata};n.addVertex(o)}for(let e of t.edges)if(n.hasVertex(e.source)&&n.hasVertex(e.target)){let o={source:e.source,target:e.target,weight:e.weight,type:e.edgeType==="dependency"?"dependency":e.edgeType==="communication"?"communication":e.edgeType==="workflow"?"workflow":"coordination",bidirectional:e.edgeType!=="dependency"};n.addEdge(o)}return n}buildTaskGraphFromTopology(t){let n=t.map(r=>({id:r.id,label:r.name,type:"agent",domain:r.domain,weight:r.weight})),e=[],o=new Set(t.map(r=>r.id));for(let r of t)for(let a of r.dependsOn)o.has(a)&&e.push({source:r.id,target:a,weight:1,edgeType:"dependency"});let s=new Map;for(let r of t){let a=s.get(r.domain)||[];a.push(r.id),s.set(r.domain,a)}for(let[,r]of s)for(let a=0;a<r.length;a++)for(let i=a+1;i<r.length;i++)e.push({source:r[a],target:r[i],weight:.5,edgeType:"coordination"});return{nodes:n,edges:e}}lambdaToTier(t){return t>=.8?{tier:1,label:"Haiku"}:t>=.4?{tier:2,label:"Sonnet"}:{tier:3,label:"Opus"}}computeConfidence(t,n){let e=t.getStats();if(e.vertexCount<3)return .4;let o=Math.min(Math.abs(n-.4),Math.abs(n-.8)),s=Math.min(.95,.5+o*2.25),r=Math.min(1,e.density*2);return Math.min(.99,s*(.7+.3*r))}buildRationale(t,n,e,o){let s=t.slice(0,80),r=n>=.8?"highly connected":n>=.4?"moderately connected":"fragmented";return`Task "${s}" routed to ${e===1?"Haiku":e===2?"Sonnet":"Opus"} (Tier ${e}). Fleet topology is ${r} (lambda=${n.toFixed(3)}) across ${o} agents.`}generateHealthSuggestions(t,n,e){let o=[];return e.isConnected||o.push(`Graph has ${e.componentCount} disconnected components. Add cross-domain coordination edges to improve connectivity.`),t<.2?o.push("Critical: Fleet connectivity is very low. Consider spawning coordination agents."):t<.4&&o.push("Warning: Fleet connectivity is below healthy threshold. Reinforce weak connections."),n>0&&o.push(`${n} weak point(s) detected. Add redundant connections to these agents.`),e.vertexCount<3&&o.push("Fleet has fewer than 3 agents. MinCut analysis is most useful with larger topologies."),o}emptyHealthReport(){return{lambda:0,normalizedLambda:0,healthy:!1,weakPoints:[],riskScore:1,componentCount:0,isConnected:!0,suggestions:["No agents in fleet. Spawn agents to build a topology."],analyzedAt:new Date}}};function C(){return new m}export{C 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.13.12");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
2
  import{existsSync as d,readFileSync as g,readdirSync as _,statSync as w}from"fs";import{join as o,extname as T}from"path";var E=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".pyw",".go",".rs",".java",".kt",".kts",".rb",".cs",".php",".swift",".c",".h",".cpp",".hpp",".cc",".scala"]),v=[".test.",".spec.","_test.","_spec."],F=new Set(["node_modules","dist","build","coverage",".git","__pycache__",".venv","venv",".tox",".mypy_cache","target",".gradle","vendor",".bundle",".next",".nuxt",".output"]);function O(s,n={}){let{maxDepth:r=6,includeTests:m=!1,testsOnly:x=!1,extraExtensions:y=[]}=n;if(!d(s))return[];let c=w(s);if(c.isFile())return[s];if(!c.isDirectory())return[];let S=new Set(y.map(e=>e.startsWith(".")?e:`.${e}`)),i=[];function a(e,u){if(u>r)return;let l;try{l=_(e,{withFileTypes:!0})}catch{return}for(let t of l)if(t.isDirectory()){if(F.has(t.name))continue;a(o(e,t.name),u+1)}else if(t.isFile()){let p=T(t.name).toLowerCase();if(!(E.has(p)||S.has(p))||t.name.endsWith(".d.ts"))continue;let f=v.some(h=>t.name.includes(h))||t.name.startsWith("test_");x?f&&i.push(o(e,t.name)):(m||!f)&&i.push(o(e,t.name))}}return a(s,0),i}function D(s,n){return n!=="node"&&n!=="node-test"?s:s.filter(r=>{try{return!/@playwright\/test|require\(\s*['"]playwright['"]\s*\)/.test(g(r,"utf8"))}catch{return!0}})}export{E as a,O as b,D 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.13.12");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
2
  function M(u){let e=u|0;return()=>{e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}var A=2,y=10,x=200,p=1e-8,b=class{epsilon;seed;constructor(e){if(this.epsilon=e?.epsilon??.3,this.seed=e?.seed,this.epsilon<=0||this.epsilon>=1)throw new Error("SparsifierConfig.epsilon must be in (0, 1)")}sparsify(e){if(e.nodeCount<=0||e.edges.length===0)return{nodeCount:e.nodeCount,edges:[]};let n=this.seed!==void 0?M(this.seed):Math.random,t=this.approximateEffectiveResistances(e),i=e.nodeCount,r=e.edges.length,o=Math.max(1,Math.log(i)),m=this.epsilon*this.epsilon,l=Math.min(r,Math.max(i-1,A*(i-1)*(1-this.epsilon))),s=new Float64Array(r),c=0;for(let a=0;a<r;a++){let d=e.edges[a][2];s[a]=d*t[a],c+=s[a]}if(c<=0)return{nodeCount:e.nodeCount,edges:[]};let f=[];for(let a=0;a<r;a++){let[d,C,E]=e.edges[a],g=Math.min(1,s[a]/c*l);if(n()<g){let w=E/g;f.push([d,C,w])}}return{nodeCount:e.nodeCount,edges:f}}validateSpectral(e,n){let t=Math.min(y,Math.max(1,e.nodeCount-1)),i=this.computeLaplacian(e),r=this.computeLaplacian(n),o=this.computeTopEigenvalues(i,t),m=this.computeTopEigenvalues(r,t),l=[],s=!0,c=this.epsilon;for(let f=0;f<o.length;f++){if(o[f]<1e-10)continue;let a=m[f]/o[f];l.push(a),(a<1-c||a>1+c)&&(s=!1)}return{isValid:s,eigenvalueRatios:l,originalEdgeCount:e.edges.length,sparsifiedEdgeCount:n.edges.length,compressionRatio:e.edges.length>0?n.edges.length/e.edges.length:0}}computeLaplacian(e){let n=e.nodeCount,t=Array.from({length:n},()=>new Array(n).fill(0));for(let[i,r,o]of e.edges)i<0||i>=n||r<0||r>=n||(t[i][i]+=o,t[r][r]+=o,t[i][r]-=o,t[r][i]-=o);return t}computeTopEigenvalues(e,n){let t=e.length;if(t===0)return[];let i=[],r=[],o=e.map(m=>[...m]);for(let m=0;m<Math.min(n,t);m++){let l=this.powerIteration(o,t,r);if(l===null)break;i.push(l.eigenvalue),r.push(l.eigenvector),V(o,l.eigenvalue,l.eigenvector)}return i}approximateEffectiveResistances(e){let n=e.nodeCount,t=new Float64Array(n);for(let[r,o,m]of e.edges)r>=0&&r<n&&(t[r]+=m),o>=0&&o<n&&(t[o]+=m);let i=new Array(e.edges.length);for(let r=0;r<e.edges.length;r++){let[o,m]=e.edges[r],l=t[o]||1,s=t[m]||1;i[r]=1/l+1/s}return i}powerIteration(e,n,t){let i=0;for(let s=0;s<n;s++)for(let c=0;c<n;c++)i+=e[s][c]*e[s][c];if(i<p*p)return null;let r=t.length,o=new Array(n);for(let s=0;s<n;s++)o[s]=Math.sin((s+1)*(r+1)*1.618033988749895)+.1*(s-n/2);for(let s of t)h(o,s);if(R(o)<p)return null;let l=0;for(let s=0;s<x;s++){let c=L(e,o);for(let d of t)h(c,d);let f=S(c,o),a=v(c);if(a<p)return{eigenvalue:0,eigenvector:o};for(let d=0;d<n;d++)o[d]=c[d]/a;if(Math.abs(f-l)<p){l=f;break}l=f}return{eigenvalue:Math.abs(l),eigenvector:o}}};function L(u,e){let n=u.length,t=new Array(n).fill(0);for(let i=0;i<n;i++){let r=0;for(let o=0;o<n;o++)r+=u[i][o]*e[o];t[i]=r}return t}function v(u){let e=0;for(let n=0;n<u.length;n++)e+=u[n]*u[n];return Math.sqrt(e)}function R(u){let e=v(u);if(e>0)for(let n=0;n<u.length;n++)u[n]/=e;return e}function S(u,e){let n=0;for(let t=0;t<u.length;t++)n+=u[t]*e[t];return n}function h(u,e){let n=S(u,e);for(let t=0;t<u.length;t++)u[t]-=n*e[t]}function V(u,e,n){let t=n.length;for(let i=0;i<t;i++)for(let r=0;r<t;r++)u[i][r]-=e*n[i]*n[r]}export{b as a};
@@ -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.13.12");process.exit(0)}
2
- import{a as w,b as A,c as O,e as D,f as z}from"./chunk-KRZYWVS3.js";import{b as S,d as $}from"./chunk-VA2ORJB5.js";import{a as N,c as F}from"./chunk-L3GBNX7B.js";import{i as v}from"./chunk-52VGZJSD.js";import*as I from"node:path";z();$();var P=["function","module","test","file","class"],L=["calls","imports","tests","depends_on","covers"],b=class{ensureSchema(e){e.transaction(()=>{e.exec(w),e.exec(A),e.exec(O)})()}schemaExists(e){return D(e)}getNodeTypes(){return P}getEdgeTypes(){return L}isValidNodeType(e){return P.includes(e)}isValidEdgeType(e){return L.includes(e)}getStats(e){if(!this.schemaExists(e))return{nodeCount:0,edgeCount:0};let t=e.prepare("SELECT COUNT(*) as count FROM hypergraph_nodes").get().count,r=e.prepare("SELECT COUNT(*) as count FROM hypergraph_edges").get().count;return{nodeCount:t,edgeCount:r}}dropSchema(e){let t=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_nodes").get()?.cnt??0,r=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_edges").get()?.cnt??0;if(t>0||r>0)throw new Error(`REFUSING to drop hypergraph schema: tables contain data (${t} nodes, ${r} edges). Backup and manually drop if needed.`);e.transaction(()=>{e.exec("DROP TABLE IF EXISTS hypergraph_edges"),e.exec("DROP TABLE IF EXISTS hypergraph_nodes")})()}};function C(n){return{id:n.id,type:n.type,name:n.name,file_path:n.filePath??null,line_start:n.lineStart??null,line_end:n.lineEnd??null,complexity:n.complexity??null,coverage:n.coverage??null,metadata:n.metadata?JSON.stringify(n.metadata):null,embedding:n.embedding?U(n.embedding):null}}function T(n){return{id:n.id,type:n.type,name:n.name,filePath:n.file_path??void 0,lineStart:n.line_start??void 0,lineEnd:n.line_end??void 0,complexity:n.complexity??void 0,coverage:n.coverage??void 0,metadata:n.metadata?S(n.metadata):void 0,embedding:n.embedding?W(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function M(n){return{id:n.id,source_id:n.sourceId,target_id:n.targetId,type:n.type,weight:n.weight??1,properties:n.properties?JSON.stringify(n.properties):null}}function H(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?S(n.properties):void 0,createdAt:n.created_at}}function x(n,e,t){return`${n}--${t}-->${e}`}function U(n){let e=Buffer.alloc(n.length*4);for(let t=0;t<n.length;t++)e.writeFloatLE(n[t],t*4);return e}function W(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}F();var B={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},R=class{config;schemaManager;initialized=!1;constructor(e){this.config={...B,...e},this.schemaManager=new b}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=v(),r={id:t,...e},s=C(r);return this.config.db.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
+ import{a as w,b as A,c as O,e as D,f as z}from"./chunk-CIZ6LSNV.js";import{b as S,d as $}from"./chunk-HQHLHSJO.js";import{a as N,c as F}from"./chunk-XITTURP2.js";import{i as v}from"./chunk-FOHYBR3O.js";import*as I from"node:path";z();$();var P=["function","module","test","file","class"],L=["calls","imports","tests","depends_on","covers"],b=class{ensureSchema(e){e.transaction(()=>{e.exec(w),e.exec(A),e.exec(O)})()}schemaExists(e){return D(e)}getNodeTypes(){return P}getEdgeTypes(){return L}isValidNodeType(e){return P.includes(e)}isValidEdgeType(e){return L.includes(e)}getStats(e){if(!this.schemaExists(e))return{nodeCount:0,edgeCount:0};let t=e.prepare("SELECT COUNT(*) as count FROM hypergraph_nodes").get().count,r=e.prepare("SELECT COUNT(*) as count FROM hypergraph_edges").get().count;return{nodeCount:t,edgeCount:r}}dropSchema(e){let t=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_nodes").get()?.cnt??0,r=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_edges").get()?.cnt??0;if(t>0||r>0)throw new Error(`REFUSING to drop hypergraph schema: tables contain data (${t} nodes, ${r} edges). Backup and manually drop if needed.`);e.transaction(()=>{e.exec("DROP TABLE IF EXISTS hypergraph_edges"),e.exec("DROP TABLE IF EXISTS hypergraph_nodes")})()}};function C(n){return{id:n.id,type:n.type,name:n.name,file_path:n.filePath??null,line_start:n.lineStart??null,line_end:n.lineEnd??null,complexity:n.complexity??null,coverage:n.coverage??null,metadata:n.metadata?JSON.stringify(n.metadata):null,embedding:n.embedding?U(n.embedding):null}}function T(n){return{id:n.id,type:n.type,name:n.name,filePath:n.file_path??void 0,lineStart:n.line_start??void 0,lineEnd:n.line_end??void 0,complexity:n.complexity??void 0,coverage:n.coverage??void 0,metadata:n.metadata?S(n.metadata):void 0,embedding:n.embedding?W(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function M(n){return{id:n.id,source_id:n.sourceId,target_id:n.targetId,type:n.type,weight:n.weight??1,properties:n.properties?JSON.stringify(n.properties):null}}function H(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?S(n.properties):void 0,createdAt:n.created_at}}function x(n,e,t){return`${n}--${t}-->${e}`}function U(n){let e=Buffer.alloc(n.length*4);for(let t=0;t<n.length;t++)e.writeFloatLE(n[t],t*4);return e}function W(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}F();var B={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},R=class{config;schemaManager;initialized=!1;constructor(e){this.config={...B,...e},this.schemaManager=new b}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=v(),r={id:t,...e},s=C(r);return this.config.db.prepare(`
3
3
  INSERT INTO hypergraph_nodes (id, type, name, file_path, line_start, line_end, complexity, coverage, metadata, embedding)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5
5
  `).run(s.id,s.type,s.name,s.file_path,s.line_start,s.line_end,s.complexity,s.coverage,s.metadata,s.embedding),t}async addEdge(e){this.ensureInitialized();let t=x(e.sourceId,e.targetId,e.type),r={id:t,...e},s=M(r);return this.config.db.prepare(`
@@ -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.13.12");process.exit(0)}
2
- import{c as w,d as E,f as T}from"./chunk-ZMYV4R32.js";var d=E((b,u)=>{"use strict";var _=typeof Buffer<"u",a=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,l=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function p(r,t,e){e==null&&t!==null&&typeof t=="object"&&(e=t,t=void 0),_&&Buffer.isBuffer(r)&&(r=r.toString()),r&&r.charCodeAt(0)===65279&&(r=r.slice(1));let o=JSON.parse(r,t);if(o===null||typeof o!="object")return o;let n=e&&e.protoAction||"error",c=e&&e.constructorAction||"error";if(n==="ignore"&&c==="ignore")return o;if(n!=="ignore"&&c!=="ignore"){if(a.test(r)===!1&&l.test(r)===!1)return o}else if(n!=="ignore"&&c==="ignore"){if(a.test(r)===!1)return o}else if(l.test(r)===!1)return o;return y(o,{protoAction:n,constructorAction:c,safe:e&&e.safe})}function y(r,{protoAction:t="error",constructorAction:e="error",safe:o}={}){let n=[r];for(;n.length;){let c=n;n=[];for(let s of c){if(t!=="ignore"&&Object.prototype.hasOwnProperty.call(s,"__proto__")){if(o===!0)return null;if(t==="error")throw new SyntaxError("Object contains forbidden prototype property");delete s.__proto__}if(e!=="ignore"&&Object.prototype.hasOwnProperty.call(s,"constructor")&&s.constructor!==null&&typeof s.constructor=="object"&&Object.prototype.hasOwnProperty.call(s.constructor,"prototype")){if(o===!0)return null;if(e==="error")throw new SyntaxError("Object contains forbidden prototype property");delete s.constructor}for(let h in s){let f=s[h];f&&typeof f=="object"&&n.push(f)}}}return r}function i(r,t,e){let{stackTraceLimit:o}=Error;Error.stackTraceLimit=0;try{return p(r,t,e)}finally{Error.stackTraceLimit=o}}function m(r,t){let{stackTraceLimit:e}=Error;Error.stackTraceLimit=0;try{return p(r,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=e}}u.exports=i;u.exports.default=i;u.exports.parse=i;u.exports.safeParse=m;u.exports.scan=y});function F(r){return g.default.parse(r,void 0,{protoAction:"remove",constructorAction:"remove"})}function j(r,t){try{return F(r)}catch(e){throw new Error(`Invalid JSON in --${t}: ${e instanceof Error?e.message:"Parse error"}`)}}var g,O=w(()=>{"use strict";g=T(d(),1)});export{d as a,F as b,j as c,O as d};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
+ import{c as w,d as E,f as T}from"./chunk-PEW6FZ47.js";var d=E((b,u)=>{"use strict";var _=typeof Buffer<"u",a=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,l=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function p(r,t,e){e==null&&t!==null&&typeof t=="object"&&(e=t,t=void 0),_&&Buffer.isBuffer(r)&&(r=r.toString()),r&&r.charCodeAt(0)===65279&&(r=r.slice(1));let o=JSON.parse(r,t);if(o===null||typeof o!="object")return o;let n=e&&e.protoAction||"error",c=e&&e.constructorAction||"error";if(n==="ignore"&&c==="ignore")return o;if(n!=="ignore"&&c!=="ignore"){if(a.test(r)===!1&&l.test(r)===!1)return o}else if(n!=="ignore"&&c==="ignore"){if(a.test(r)===!1)return o}else if(l.test(r)===!1)return o;return y(o,{protoAction:n,constructorAction:c,safe:e&&e.safe})}function y(r,{protoAction:t="error",constructorAction:e="error",safe:o}={}){let n=[r];for(;n.length;){let c=n;n=[];for(let s of c){if(t!=="ignore"&&Object.prototype.hasOwnProperty.call(s,"__proto__")){if(o===!0)return null;if(t==="error")throw new SyntaxError("Object contains forbidden prototype property");delete s.__proto__}if(e!=="ignore"&&Object.prototype.hasOwnProperty.call(s,"constructor")&&s.constructor!==null&&typeof s.constructor=="object"&&Object.prototype.hasOwnProperty.call(s.constructor,"prototype")){if(o===!0)return null;if(e==="error")throw new SyntaxError("Object contains forbidden prototype property");delete s.constructor}for(let h in s){let f=s[h];f&&typeof f=="object"&&n.push(f)}}}return r}function i(r,t,e){let{stackTraceLimit:o}=Error;Error.stackTraceLimit=0;try{return p(r,t,e)}finally{Error.stackTraceLimit=o}}function m(r,t){let{stackTraceLimit:e}=Error;Error.stackTraceLimit=0;try{return p(r,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=e}}u.exports=i;u.exports.default=i;u.exports.parse=i;u.exports.safeParse=m;u.exports.scan=y});function F(r){return g.default.parse(r,void 0,{protoAction:"remove",constructorAction:"remove"})}function j(r,t){try{return F(r)}catch(e){throw new Error(`Invalid JSON in --${t}: ${e instanceof Error?e.message:"Parse error"}`)}}var g,O=w(()=>{"use strict";g=T(d(),1)});export{d as a,F as b,j as c,O as d};
@@ -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.13.12");process.exit(0)}
2
- import{b as l,c}from"./chunk-3ASVQILY.js";import{i}from"./chunk-52VGZJSD.js";c();var u=.15,d=.03,p=.25,s=class{constructor(t){this.db=t;l(t)}db;recordNull(t){this.db.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
+ import{b as l,c}from"./chunk-GKNDP5VK.js";import{i}from"./chunk-FOHYBR3O.js";c();var u=.15,d=.03,p=.25,s=class{constructor(t){this.db=t;l(t)}db;recordNull(t){this.db.prepare(`
3
3
  INSERT INTO qe_pattern_nulls (id, pattern_id, context_fingerprint, failure_mode, trajectory_ref, evidence_class)
4
4
  VALUES (?, ?, ?, ?, ?, ?)
5
5
  ON CONFLICT(pattern_id, context_fingerprint) DO UPDATE SET
@@ -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.13.12");process.exit(0)}
2
- import{c as j,e as V}from"./chunk-NLZUGANH.js";import{a as U,b as W,d as G}from"./chunk-UC4EIULB.js";import{b as F}from"./chunk-SNC73DWF.js";import{a as T,c as N}from"./chunk-L3GBNX7B.js";import{b as D,c as $,d as Y}from"./chunk-4Z4X2ND4.js";N();Y();import*as C from"fs";import*as b from"path";import*as H from"yaml";var z=5,X=4,Z=3e4,ee=".claude/skills",te=5e3,se=500,K=100,re=1e3,q=500,ne=.8,ae=.2,ie=.1,w=.1,oe=.1,le=.1,ce=.1,ue=200,de=500,pe=300,me=1,ge=.9,Q={maxWorkers:z,batchSize:X,retryFailedTests:!0,timeout:Z,skillsDir:ee,progressIntervalMs:te},S=class{async execute(e,r,s){let t=$(K,se+K);return await new Promise(i=>setTimeout(i,t)),{output:this.generateMockResponse(e),tokensUsed:D(q,re+q),durationMs:t}}generateMockResponse(e){let r=[];return e.includes("alt")&&r.push("alt","1.1.1","perceivable"),e.includes("contrast")&&r.push("contrast","1.4.3","4.5:1"),e.includes("keyboard")&&r.push("keyboard","2.1.1","operable","button"),e.includes("label")&&r.push("label","3.3.2","understandable"),e.includes("ARIA")&&r.push("ARIA","4.1.2","robust"),e.includes("focus")&&r.push("focus","2.4.7","outline"),e.includes("lang")&&r.push("lang","3.1.1","language"),e.includes("caption")&&r.push("caption","1.2.2","track"),e.includes("accessible")&&r.push("accessible","compliant"),r.length===0&&r.push("accessibility","WCAG","finding"),`Analysis complete. Found issues related to: ${r.join(", ")}.
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
+ import{a as U,b as W,c as G}from"./chunk-2O4DDPEA.js";import{b as F}from"./chunk-AFGT26NR.js";import{o as j,q as V}from"./chunk-5XGVSQS2.js";import{a as T,c as N}from"./chunk-XITTURP2.js";import{b as D,c as $,d as Y}from"./chunk-VXU53F7Z.js";N();Y();import*as C from"fs";import*as b from"path";import*as H from"yaml";var z=5,X=4,Z=3e4,ee=".claude/skills",te=5e3,se=500,K=100,re=1e3,q=500,ne=.8,ae=.2,ie=.1,w=.1,oe=.1,le=.1,ce=.1,ue=200,de=500,pe=300,me=1,ge=.9,Q={maxWorkers:z,batchSize:X,retryFailedTests:!0,timeout:Z,skillsDir:ee,progressIntervalMs:te},S=class{async execute(e,r,s){let t=$(K,se+K);return await new Promise(i=>setTimeout(i,t)),{output:this.generateMockResponse(e),tokensUsed:D(q,re+q),durationMs:t}}generateMockResponse(e){let r=[];return e.includes("alt")&&r.push("alt","1.1.1","perceivable"),e.includes("contrast")&&r.push("contrast","1.4.3","4.5:1"),e.includes("keyboard")&&r.push("keyboard","2.1.1","operable","button"),e.includes("label")&&r.push("label","3.3.2","understandable"),e.includes("ARIA")&&r.push("ARIA","4.1.2","robust"),e.includes("focus")&&r.push("focus","2.4.7","outline"),e.includes("lang")&&r.push("lang","3.1.1","language"),e.includes("caption")&&r.push("caption","1.2.2","track"),e.includes("accessible")&&r.push("accessible","compliant"),r.length===0&&r.push("accessibility","WCAG","finding"),`Analysis complete. Found issues related to: ${r.join(", ")}.
3
3
  Recommendations: Implement proper ${r[0]} attributes for better accessibility.
4
4
  Severity: ${e.includes("critical")?"critical":"serious"}`}},P=class{constructor(e,r,s){this.executor=r;this.config=s;this.id=e}executor;config;id;status="idle";tasksCompleted=0;tasksFailed=0;lastHeartbeat=Date.now();async executeBatch(e){this.status="running";let r=[];for(let s of e){this.lastHeartbeat=Date.now();try{let t=await this.executeTestCase(s);if(r.push(t),t.passed)this.tasksCompleted++;else if(this.tasksFailed++,this.config.retryFailedTests&&!t.passed){let a=await this.executeTestCase(s,!0);a.passed&&(r[r.length-1]=a,this.tasksCompleted++,this.tasksFailed--)}}catch(t){this.tasksFailed++,r.push({testId:s.testCaseId,passed:!1,expectedPatterns:s.testCase.expected_output.must_contain||[],actualPatterns:[],reasoningQuality:0,category:s.testCase.category,priority:s.testCase.priority,error:T(t)})}}return this.status="idle",r}async executeTestCase(e,r=!1){let s=Date.now(),t=this.buildPrompt(e),a=await this.executor.execute(t,e.model,{timeout:this.config.timeout}),i=this.validateResponse(a.output,e.testCase.expected_output,e.testCase.validation);return{testId:e.testCaseId,passed:i.passed,expectedPatterns:e.testCase.expected_output.must_contain||[],actualPatterns:i.foundPatterns,reasoningQuality:i.reasoningQuality,executionTimeMs:Date.now()-s,category:e.testCase.category,priority:e.testCase.priority,error:i.error}}buildPrompt(e){let{testCase:r}=e,s=r.input.context;return`Analyze the following ${s.language||"HTML"} code for accessibility issues.
5
5
  Context: ${s.description||r.description}
@@ -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.13.12");process.exit(0)}
2
- import{c as R,g as N,i as O}from"./chunk-PGFCKE4G.js";import{i as S,m as w}from"./chunk-M73KM3AZ.js";import{b as T,d as D}from"./chunk-VA2ORJB5.js";import{a as L}from"./chunk-7ZVO7I4Q.js";import{a as u,c as q}from"./chunk-L3GBNX7B.js";import{i as f}from"./chunk-52VGZJSD.js";import{a as h,b as C}from"./chunk-Z56BBX77.js";C();D();q();w();var P={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:256*1024*1024,cacheSize:-64e3,foreignKeys:!0,useUnified:!0};function G(_,e=384){let n=new Array(e).fill(0),t=_.toLowerCase().trim();for(let a=0;a<3;a++)for(let s=0;s<t.length;s++){let i=t.charCodeAt(s),o=i*(s+1)*(a+1)%e;n[o]+=Math.sin(i*(a+1))/(s+1)}let r=Math.sqrt(n.reduce((a,s)=>a+s*s,0));if(r>0)for(let a=0;a<e;a++)n[a]/=r;return n}var g=class{db=null;config;prepared=new Map;initialized=!1;unifiedMemory=null;constructor(e={}){this.config={...P,...e}}getDatabase(){return this.db}async initialize(){if(!this.initialized)try{if(this.config.useUnified)this.unifiedMemory=S(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),console.log(`[SQLitePatternStore] Using unified storage: ${this.unifiedMemory.getDbPath()}`);else{let e=await import("path"),n=await import("fs"),t=e.dirname(this.config.dbPath);n.existsSync(t)||n.mkdirSync(t,{recursive:!0}),this.db=h(this.config.dbPath),this.db.pragma(`mmap_size = ${this.config.mmapSize}`),this.db.pragma(`cache_size = ${this.config.cacheSize}`),this.config.foreignKeys&&this.db.pragma("foreign_keys = ON"),this.createSchema(),console.log(`[SQLitePatternStore] Initialized (legacy): ${this.config.dbPath}`)}this.deduplicatePatterns(),this.prepareStatements(),this.initialized=!0}catch(e){throw new Error(`Failed to initialize SQLite: ${u(e)}`)}}createSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
+ import{a as L,b as I,f,j as A,l as y,n as l}from"./chunk-ZBKGX72B.js";import{k as O,o as M}from"./chunk-7RAB2BZY.js";import{b,d as U}from"./chunk-HQHLHSJO.js";import{a as C}from"./chunk-VOSISOFD.js";import{a as p,c as P}from"./chunk-XITTURP2.js";import{i as R}from"./chunk-FOHYBR3O.js";import{a as N,b as F}from"./chunk-ZQSXG7FA.js";F();U();P();M();var v={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:256*1024*1024,cacheSize:-64e3,foreignKeys:!0,useUnified:!0};function W(T,e=384){let t=new Array(e).fill(0),n=T.toLowerCase().trim();for(let a=0;a<3;a++)for(let s=0;s<n.length;s++){let i=n.charCodeAt(s),o=i*(s+1)*(a+1)%e;t[o]+=Math.sin(i*(a+1))/(s+1)}let r=Math.sqrt(t.reduce((a,s)=>a+s*s,0));if(r>0)for(let a=0;a<e;a++)t[a]/=r;return t}var h=class{db=null;config;prepared=new Map;initialized=!1;unifiedMemory=null;constructor(e={}){this.config={...v,...e}}getDatabase(){return this.db}async initialize(){if(!this.initialized)try{if(this.config.useUnified)this.unifiedMemory=O(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),console.log(`[SQLitePatternStore] Using unified storage: ${this.unifiedMemory.getDbPath()}`);else{let e=await import("path"),t=await import("fs"),n=e.dirname(this.config.dbPath);t.existsSync(n)||t.mkdirSync(n,{recursive:!0}),this.db=N(this.config.dbPath),this.db.pragma(`mmap_size = ${this.config.mmapSize}`),this.db.pragma(`cache_size = ${this.config.cacheSize}`),this.config.foreignKeys&&this.db.pragma("foreign_keys = ON"),this.createSchema(),console.log(`[SQLitePatternStore] Initialized (legacy): ${this.config.dbPath}`)}this.deduplicatePatterns(),this.ensureEmbeddingSpaceSchema(),this.prepareStatements(),this.initialized=!0}catch(e){throw new Error(`Failed to initialize SQLite: ${p(e)}`)}}createSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
3
3
  -- QE Patterns table
4
4
  CREATE TABLE IF NOT EXISTS qe_patterns (
5
5
  id TEXT PRIMARY KEY,
@@ -27,6 +27,7 @@ import{c as R,g as N,i as O}from"./chunk-PGFCKE4G.js";import{i as S,m as w}from"
27
27
  embedding BLOB NOT NULL,
28
28
  dimension INTEGER NOT NULL,
29
29
  model TEXT DEFAULT 'all-MiniLM-L6-v2',
30
+ space_id TEXT,
30
31
  created_at TEXT DEFAULT (datetime('now')),
31
32
  FOREIGN KEY (pattern_id) REFERENCES qe_patterns(id) ON DELETE CASCADE
32
33
  );
@@ -126,19 +127,19 @@ import{c as R,g as N,i as O}from"./chunk-PGFCKE4G.js";import{i as S,m as w}from"
126
127
  SELECT name, qe_domain, pattern_type, COUNT(*) as c
127
128
  FROM qe_patterns GROUP BY name, qe_domain, pattern_type HAVING c > 1
128
129
  )
129
- `).get()?.cnt||0)>0){let t=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get()?.cnt||0,r=this.db.prepare(`
130
+ `).get()?.cnt||0)>0){let n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get()?.cnt||0,r=this.db.prepare(`
130
131
  SELECT COUNT(*) as cnt FROM (
131
132
  SELECT MIN(rowid) FROM qe_patterns GROUP BY name, qe_domain, pattern_type
132
133
  )
133
- `).get()?.cnt||0,a=t-r;a>t*.1?console.warn(`[SQLitePatternStore] SKIPPING dedup: would delete ${a}/${t} patterns (>${Math.round(t*.1)} safety limit). Investigate manually.`):(this.db.exec(`
134
+ `).get()?.cnt||0,a=n-r;a>n*.1?console.warn(`[SQLitePatternStore] SKIPPING dedup: would delete ${a}/${n} patterns (>${Math.round(n*.1)} safety limit). Investigate manually.`):(this.db.exec(`
134
135
  DELETE FROM qe_patterns WHERE rowid NOT IN (
135
136
  SELECT MIN(rowid) FROM qe_patterns
136
137
  GROUP BY name, qe_domain, pattern_type
137
138
  )
138
- `),console.log(`[SQLitePatternStore] Deduplicated: removed ${a} duplicates from ${t} patterns (${r} kept)`))}this.db.exec(`
139
+ `),console.log(`[SQLitePatternStore] Deduplicated: removed ${a} duplicates from ${n} patterns (${r} kept)`))}this.db.exec(`
139
140
  CREATE UNIQUE INDEX IF NOT EXISTS idx_patterns_unique_name_domain_type
140
141
  ON qe_patterns(name, qe_domain, pattern_type)
141
- `)}catch(e){console.debug("[SQLitePatternStore] Deduplication migration:",u(e))}}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("insertPattern",this.db.prepare(`
142
+ `)}catch(e){console.debug("[SQLitePatternStore] Deduplication migration:",p(e))}}ensureEmbeddingSpaceSchema(){if(!this.db)throw new Error("Database not initialized");this.db.prepare("PRAGMA table_info('qe_pattern_embeddings')").all().some(t=>t.name==="space_id")||this.db.exec("ALTER TABLE qe_pattern_embeddings ADD COLUMN space_id TEXT"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_qe_pattern_embeddings_space ON qe_pattern_embeddings(space_id)")}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("insertPattern",this.db.prepare(`
142
143
  INSERT INTO qe_patterns (
143
144
  id, pattern_type, qe_domain, domain, name, description,
144
145
  confidence, tier, template_json, context_json
@@ -156,12 +157,12 @@ import{c as R,g as N,i as O}from"./chunk-PGFCKE4G.js";import{i as S,m as w}from"
156
157
  context_json = excluded.context_json,
157
158
  updated_at = datetime('now')
158
159
  `)),this.prepared.set("insertEmbedding",this.db.prepare(`
159
- INSERT OR REPLACE INTO qe_pattern_embeddings (pattern_id, embedding, dimension, model)
160
- VALUES (?, ?, ?, ?)
160
+ INSERT OR REPLACE INTO qe_pattern_embeddings (pattern_id, embedding, dimension, model, space_id)
161
+ VALUES (?, ?, ?, ?, ?)
161
162
  `)),this.prepared.set("getPattern",this.db.prepare(`
162
163
  SELECT * FROM qe_patterns WHERE id = ?
163
164
  `)),this.prepared.set("getPatternWithEmbedding",this.db.prepare(`
164
- SELECT p.*, e.embedding, e.dimension
165
+ SELECT p.*, e.embedding, e.dimension, e.space_id
165
166
  FROM qe_patterns p
166
167
  LEFT JOIN qe_pattern_embeddings e ON p.id = e.pattern_id
167
168
  WHERE p.id = ?
@@ -185,9 +186,9 @@ import{c as R,g as N,i as O}from"./chunk-PGFCKE4G.js";import{i as S,m as w}from"
185
186
  `)),this.prepared.set("getPatternsByDomain",this.db.prepare(`
186
187
  SELECT * FROM qe_patterns WHERE qe_domain = ? ORDER BY quality_score DESC LIMIT ?
187
188
  `)),this.prepared.set("getAllEmbeddings",this.db.prepare(`
188
- SELECT pattern_id, embedding, dimension FROM qe_pattern_embeddings
189
+ SELECT pattern_id, embedding, dimension, space_id FROM qe_pattern_embeddings
189
190
  `)),this.prepared.set("getRecentEmbeddings",this.db.prepare(`
190
- SELECT e.pattern_id, e.embedding, e.dimension
191
+ SELECT e.pattern_id, e.embedding, e.dimension, e.space_id
191
192
  FROM qe_pattern_embeddings e
192
193
  LEFT JOIN qe_patterns p ON p.id = e.pattern_id
193
194
  ORDER BY COALESCE(p.last_used_at, p.created_at, e.created_at) DESC
@@ -196,41 +197,41 @@ import{c as R,g as N,i as O}from"./chunk-PGFCKE4G.js";import{i as S,m as w}from"
196
197
  SELECT COUNT(*) as count FROM qe_patterns
197
198
  `)),this.prepared.set("countByDomain",this.db.prepare(`
198
199
  SELECT qe_domain, COUNT(*) as count FROM qe_patterns GROUP BY qe_domain
199
- `))}storePattern(e,n){if(!this.db)throw new Error("Database not initialized");let t=e.id||f(),r=this.prepared.get("insertPattern"),a=this.prepared.get("insertEmbedding");if(!r||!a)throw new Error("Prepared statements not ready");let s=t;return this.db.transaction(()=>{r.run(t,e.patternType,e.qeDomain,e.domain,e.name,e.description||"",e.confidence,e.tier||"short-term",JSON.stringify(e.template),JSON.stringify(e.context));let o=this.db.prepare("SELECT id FROM qe_patterns WHERE name = ? AND qe_domain = ? AND pattern_type = ?").get(e.name,e.qeDomain??"",e.patternType??"");if(s=o?o.id:t,n){let c=Buffer.from(new Float32Array(n).buffer);a.run(s,c,n.length,"all-MiniLM-L6-v2")}})(),s}getPattern(e){if(!this.db)throw new Error("Database not initialized");let n=this.prepared.get("getPatternWithEmbedding");if(!n)throw new Error("Prepared statement not ready");let t=n.get(e);return t?this.rowToPattern(t):null}getPatterns(e={}){if(!this.db)throw new Error("Database not initialized");let n=e.limit||1e3,t,r;return e.domain?(t=this.prepared.get("getPatternsByDomain"),r=t.all(e.domain,n)):(t=this.prepared.get("getAllPatterns"),r=t.all(n)),r.map(a=>this.rowToPattern(a))}searchFTS(e,n=20){if(!this.db)throw new Error("Database not initialized");if(!e.trim())return[];let t='"'+e.replace(/"/g,'""')+'"',r=performance.now();try{let a=this.db.prepare(`
200
+ `))}storePattern(e,t,n){if(!this.db)throw new Error("Database not initialized");let r=e.id||R(),a=this.prepared.get("insertPattern"),s=this.prepared.get("insertEmbedding");if(!a||!s)throw new Error("Prepared statements not ready");let i=r;return this.db.transaction(()=>{a.run(r,e.patternType,e.qeDomain,e.domain,e.name,e.description||"",e.confidence,e.tier||"short-term",JSON.stringify(e.template),JSON.stringify(e.context));let c=this.db.prepare("SELECT id FROM qe_patterns WHERE name = ? AND qe_domain = ? AND pattern_type = ?").get(e.name,e.qeDomain??"",e.patternType??"");if(i=c?c.id:r,t){let m=n??l()?.spaceId;if(!m)throw new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist an embedding without runtime provenance");let u=Buffer.from(new Float32Array(t).buffer);s.run(i,u,t.length,"all-MiniLM-L6-v2",m)}})(),i}getPattern(e){if(!this.db)throw new Error("Database not initialized");let t=this.prepared.get("getPatternWithEmbedding");if(!t)throw new Error("Prepared statement not ready");let n=t.get(e);return n?this.rowToPattern(n):null}getPatterns(e={}){if(!this.db)throw new Error("Database not initialized");let t=e.limit||1e3,n,r;return e.domain?(n=this.prepared.get("getPatternsByDomain"),r=n.all(e.domain,t)):(n=this.prepared.get("getAllPatterns"),r=n.all(t)),r.map(a=>this.rowToPattern(a))}searchFTS(e,t=20){if(!this.db)throw new Error("Database not initialized");if(!e.trim())return[];let n='"'+e.replace(/"/g,'""')+'"',r=performance.now();try{let a=this.db.prepare(`
200
201
  SELECT p.id, rank AS fts_score
201
202
  FROM qe_patterns_fts fts
202
203
  JOIN qe_patterns p ON p.rowid = fts.rowid
203
204
  WHERE qe_patterns_fts MATCH ?
204
205
  ORDER BY rank
205
206
  LIMIT ?
206
- `).all(t,n),s=performance.now()-r;s>50&&console.warn(`[FTS5] searchFTS took ${s.toFixed(1)}ms (results=${a.length})`),this._lastFtsLatencyMs=s;let i=Math.max(...a.map(o=>Math.abs(o.fts_score)),1);return a.map(o=>({id:o.id,ftsScore:Math.abs(o.fts_score)/i}))}catch{return[]}}_lastFtsLatencyMs=0;get lastFtsLatencyMs(){return this._lastFtsLatencyMs}getGhostPatternCount(){if(!this.db)throw new Error("Database not initialized");let e=this.db.prepare("SELECT COUNT(*) as c FROM qe_patterns WHERE id NOT LIKE 'bench-%'").get().c,n=this.db.prepare(`
207
+ `).all(n,t),s=performance.now()-r;s>50&&console.warn(`[FTS5] searchFTS took ${s.toFixed(1)}ms (results=${a.length})`),this._lastFtsLatencyMs=s;let i=Math.max(...a.map(o=>Math.abs(o.fts_score)),1);return a.map(o=>({id:o.id,ftsScore:Math.abs(o.fts_score)/i}))}catch{return[]}}_lastFtsLatencyMs=0;get lastFtsLatencyMs(){return this._lastFtsLatencyMs}getGhostPatternCount(){if(!this.db)throw new Error("Database not initialized");let e=this.db.prepare("SELECT COUNT(*) as c FROM qe_patterns WHERE id NOT LIKE 'bench-%'").get().c,t=this.db.prepare(`
207
208
  SELECT COUNT(*) as c FROM qe_patterns p
208
209
  WHERE p.id NOT LIKE 'bench-%'
209
210
  AND p.id NOT IN (SELECT pattern_id FROM qe_pattern_embeddings)
210
- `).get().c,t=this.db.prepare(`
211
+ `).get().c,n=this.db.prepare(`
211
212
  SELECT p.id FROM qe_patterns p
212
213
  WHERE p.id NOT LIKE 'bench-%'
213
214
  AND p.id NOT IN (SELECT pattern_id FROM qe_pattern_embeddings)
214
215
  LIMIT 10
215
- `).all();return{total:e,withoutEmbeddings:n,sampleGhostIds:t.map(r=>r.id)}}getAllEmbeddings(){if(!this.db)throw new Error("Database not initialized");let e=this.prepared.get("getAllEmbeddings");if(!e)throw new Error("Prepared statement not ready");return e.all().map(t=>({patternId:t.pattern_id,embedding:Array.from(new Float32Array(t.embedding.buffer,t.embedding.byteOffset,t.dimension))}))}getRecentEmbeddings(e){if(!this.db)throw new Error("Database not initialized");let n=Number.isFinite(e)&&e>0?Math.floor(e):1e3,t=this.prepared.get("getRecentEmbeddings");if(!t)throw new Error("Prepared statement not ready");return t.all(n).map(a=>({patternId:a.pattern_id,embedding:Array.from(new Float32Array(a.embedding.buffer,a.embedding.byteOffset,a.dimension))}))}recordUsage(e,n,t,r){if(!this.db)throw new Error("Database not initialized");if(!L(this.db,{patternId:e,success:n,metrics:t,feedback:r}).updated)throw new Error(`Pattern not found: ${e}`)}deletePattern(e){if(!this.db)throw new Error("Database not initialized");this.db.transaction(()=>{this.db.prepare("DELETE FROM qe_pattern_embeddings WHERE pattern_id = ?").run(e),this.db.prepare("DELETE FROM qe_pattern_usage WHERE pattern_id = ?").run(e),this.db.prepare("DELETE FROM qe_patterns WHERE id = ?").run(e)})()}promotePattern(e){if(!this.db)throw new Error("Database not initialized");let n=this.prepared.get("promotePattern");if(!n)throw new Error("Prepared statement not ready");n.run(e)}getStats(){if(!this.db)throw new Error("Database not initialized");let e=this.prepared.get("countPatterns"),n=this.prepared.get("countByDomain");if(!e||!n)throw new Error("Prepared statements not ready");let t=e.get().count,r=n.all(),a={};for(let o of r)a[o.qe_domain]=o.count;let s=this.db.prepare(`
216
+ `).all();return{total:e,withoutEmbeddings:t,sampleGhostIds:n.map(r=>r.id)}}getAllEmbeddings(){if(!this.db)throw new Error("Database not initialized");let e=this.prepared.get("getAllEmbeddings");if(!e)throw new Error("Prepared statement not ready");return e.all().map(n=>({patternId:n.pattern_id,embedding:Array.from(new Float32Array(n.embedding.buffer,n.embedding.byteOffset,n.dimension)),spaceId:n.space_id}))}getRecentEmbeddings(e){if(!this.db)throw new Error("Database not initialized");let t=Number.isFinite(e)&&e>0?Math.floor(e):1e3,n=this.prepared.get("getRecentEmbeddings");if(!n)throw new Error("Prepared statement not ready");return n.all(t).map(a=>({patternId:a.pattern_id,embedding:Array.from(new Float32Array(a.embedding.buffer,a.embedding.byteOffset,a.dimension)),spaceId:a.space_id}))}getEmbeddingSpaceDiagnostics(e=l()?.spaceId??null){if(!this.db)throw new Error("Database not initialized");let t=this.db.prepare("SELECT space_id AS spaceId FROM qe_pattern_embeddings").all();return I(t,e)}recordUsage(e,t,n,r){if(!this.db)throw new Error("Database not initialized");if(!C(this.db,{patternId:e,success:t,metrics:n,feedback:r}).updated)throw new Error(`Pattern not found: ${e}`)}deletePattern(e){if(!this.db)throw new Error("Database not initialized");this.db.transaction(()=>{this.db.prepare("DELETE FROM qe_pattern_embeddings WHERE pattern_id = ?").run(e),this.db.prepare("DELETE FROM qe_pattern_usage WHERE pattern_id = ?").run(e),this.db.prepare("DELETE FROM qe_patterns WHERE id = ?").run(e)})()}promotePattern(e){if(!this.db)throw new Error("Database not initialized");let t=this.prepared.get("promotePattern");if(!t)throw new Error("Prepared statement not ready");t.run(e)}getStats(){if(!this.db)throw new Error("Database not initialized");let e=this.prepared.get("countPatterns"),t=this.prepared.get("countByDomain");if(!e||!t)throw new Error("Prepared statements not ready");let n=e.get().count,r=t.all(),a={};for(let o of r)a[o.qe_domain]=o.count;let s=this.db.prepare(`
216
217
  SELECT tier, COUNT(*) as count FROM qe_patterns GROUP BY tier
217
- `).all(),i={};for(let o of s)i[o.tier]=o.count;return{totalPatterns:t,byDomain:a,byTier:i}}getAggregateOutcomeStats(){let e={routingRequests:0,avgRoutingConfidence:0,successfulRoutings:0,learningOutcomes:0,successfulOutcomes:0,avgPatternSuccessRate:0};if(!this.db)return e;let n=s=>{try{return this.db.prepare(s).get()}catch{return}},t=n(`
218
+ `).all(),i={};for(let o of s)i[o.tier]=o.count;return{totalPatterns:n,byDomain:a,byTier:i}}getAggregateOutcomeStats(){let e={routingRequests:0,avgRoutingConfidence:0,successfulRoutings:0,learningOutcomes:0,successfulOutcomes:0,avgPatternSuccessRate:0};if(!this.db)return e;let t=s=>{try{return this.db.prepare(s).get()}catch{return}},n=t(`
218
219
  SELECT
219
220
  COUNT(*) AS total,
220
221
  COUNT(CASE WHEN quality_score >= 0 THEN 1 END) AS closed,
221
222
  AVG(CASE WHEN quality_score >= 0 THEN quality_score END) AS avg_q,
222
223
  COALESCE(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END), 0) AS succ
223
224
  FROM routing_outcomes
224
- `),r=n(`
225
+ `),r=t(`
225
226
  SELECT
226
227
  COUNT(*) AS total,
227
228
  COALESCE(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END), 0) AS succ
228
229
  FROM qe_pattern_usage
229
- `),a=n(`
230
+ `),a=t(`
230
231
  SELECT AVG(success_rate) AS avg_sr
231
232
  FROM qe_patterns
232
233
  WHERE usage_count > 0
233
- `);return{routingRequests:t?.total??0,avgRoutingConfidence:t?.avg_q??0,successfulRoutings:t?.succ??0,learningOutcomes:r?.total??0,successfulOutcomes:r?.succ??0,avgPatternSuccessRate:a?.avg_sr??0}}hasAnyHistoricalData(){if(!this.db)return!1;try{let e=["SELECT COUNT(*) as cnt FROM qe_pattern_embeddings","SELECT COUNT(*) as cnt FROM qe_pattern_usage","SELECT COUNT(*) as cnt FROM qe_trajectories"];for(let n of e)try{let t=this.db.prepare(n).get();if(t&&t.cnt>0)return!0}catch{}return!1}catch{return!1}}rowToPattern(e){let n;return e.embedding&&(n=Array.from(new Float32Array(e.embedding.buffer,e.embedding.byteOffset,e.dimension))),{id:e.id,patternType:e.pattern_type,qeDomain:e.qe_domain,domain:e.domain,name:e.name,description:e.description,confidence:e.confidence,usageCount:e.usage_count,successRate:e.success_rate,qualityScore:e.quality_score,tier:e.tier,template:T(e.template_json||"{}"),context:T(e.context_json||"{}"),createdAt:new Date(e.created_at),lastUsedAt:e.last_used_at?new Date(e.last_used_at):new Date(e.created_at),successfulUses:e.successful_uses,embedding:n,tokensUsed:e.tokens_used,inputTokens:e.input_tokens,outputTokens:e.output_tokens,latencyMs:e.latency_ms,reusable:e.reusable===1,reuseCount:e.reuse_count||0,averageTokenSavings:e.average_token_savings||0,totalTokensSaved:e.total_tokens_saved}}updatePattern(e,n){if(!this.db)throw new Error("Database not initialized");let t=[],r=[];if(n.usageCount!==void 0&&(t.push("usage_count = ?"),r.push(n.usageCount)),n.successfulUses!==void 0&&(t.push("successful_uses = ?"),r.push(n.successfulUses)),n.successRate!==void 0&&(t.push("success_rate = ?"),r.push(n.successRate)),n.qualityScore!==void 0&&(t.push("quality_score = ?"),r.push(n.qualityScore)),n.confidence!==void 0&&(t.push("confidence = ?"),r.push(n.confidence)),n.tier!==void 0&&(t.push("tier = ?"),r.push(n.tier)),t.length===0)return;t.push("updated_at = datetime('now')"),r.push(e);let a=`UPDATE qe_patterns SET ${t.join(", ")} WHERE id = ?`;this.db.prepare(a).run(...r)}storePatternEmbedding(e,n){if(!this.db)throw new Error("Database not initialized");let t=this.prepared.get("insertEmbedding");if(!t)throw new Error("Prepared statements not ready");let r=Buffer.from(new Float32Array(n).buffer);t.run(e,r,n.length,"all-MiniLM-L6-v2")}recordPatternReuse(e,n,t,r=!1,a=0,s){if(!this.db)throw new Error("Database not initialized");try{this.db.exec(`
234
+ `);return{routingRequests:n?.total??0,avgRoutingConfidence:n?.avg_q??0,successfulRoutings:n?.succ??0,learningOutcomes:r?.total??0,successfulOutcomes:r?.succ??0,avgPatternSuccessRate:a?.avg_sr??0}}hasAnyHistoricalData(){if(!this.db)return!1;try{let e=["SELECT COUNT(*) as cnt FROM qe_pattern_embeddings","SELECT COUNT(*) as cnt FROM qe_pattern_usage","SELECT COUNT(*) as cnt FROM qe_trajectories"];for(let t of e)try{let n=this.db.prepare(t).get();if(n&&n.cnt>0)return!0}catch{}return!1}catch{return!1}}rowToPattern(e){let t;return e.embedding&&(t=Array.from(new Float32Array(e.embedding.buffer,e.embedding.byteOffset,e.dimension))),{id:e.id,patternType:e.pattern_type,qeDomain:e.qe_domain,domain:e.domain,name:e.name,description:e.description,confidence:e.confidence,usageCount:e.usage_count,successRate:e.success_rate,qualityScore:e.quality_score,tier:e.tier,template:b(e.template_json||"{}"),context:b(e.context_json||"{}"),createdAt:new Date(e.created_at),lastUsedAt:e.last_used_at?new Date(e.last_used_at):new Date(e.created_at),successfulUses:e.successful_uses,embedding:t,tokensUsed:e.tokens_used,inputTokens:e.input_tokens,outputTokens:e.output_tokens,latencyMs:e.latency_ms,reusable:e.reusable===1,reuseCount:e.reuse_count||0,averageTokenSavings:e.average_token_savings||0,totalTokensSaved:e.total_tokens_saved}}updatePattern(e,t){if(!this.db)throw new Error("Database not initialized");let n=[],r=[];if(t.usageCount!==void 0&&(n.push("usage_count = ?"),r.push(t.usageCount)),t.successfulUses!==void 0&&(n.push("successful_uses = ?"),r.push(t.successfulUses)),t.successRate!==void 0&&(n.push("success_rate = ?"),r.push(t.successRate)),t.qualityScore!==void 0&&(n.push("quality_score = ?"),r.push(t.qualityScore)),t.confidence!==void 0&&(n.push("confidence = ?"),r.push(t.confidence)),t.tier!==void 0&&(n.push("tier = ?"),r.push(t.tier)),n.length===0)return;n.push("updated_at = datetime('now')"),r.push(e);let a=`UPDATE qe_patterns SET ${n.join(", ")} WHERE id = ?`;this.db.prepare(a).run(...r)}storePatternEmbedding(e,t,n){if(!this.db)throw new Error("Database not initialized");let r=this.prepared.get("insertEmbedding");if(!r)throw new Error("Prepared statements not ready");let a=Buffer.from(new Float32Array(t).buffer),s=n??l()?.spaceId;if(!s)throw new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist an embedding without runtime provenance");r.run(e,a,t.length,"all-MiniLM-L6-v2",s)}recordPatternReuse(e,t,n,r=!1,a=0,s){if(!this.db)throw new Error("Database not initialized");try{this.db.exec(`
234
235
  CREATE TABLE IF NOT EXISTS qe_pattern_reuse (
235
236
  id INTEGER PRIMARY KEY AUTOINCREMENT,
236
237
  pattern_id TEXT NOT NULL,
@@ -247,9 +248,9 @@ import{c as R,g as N,i as O}from"./chunk-PGFCKE4G.js";import{i as S,m as w}from"
247
248
  INSERT INTO qe_pattern_reuse (
248
249
  pattern_id, task_description, similarity_score, was_reused, tokens_saved, routing_context_json
249
250
  ) VALUES (?, ?, ?, ?, ?, ?)
250
- `).run(e,n.slice(0,1e3),t,r?1:0,a,s?JSON.stringify(s):null)}catch(i){console.debug("[SQLitePatternStore] Failed to record pattern reuse:",u(i))}}getPatternReuseStats(e,n=7){if(!this.db)throw new Error("Database not initialized");try{if(!this.db.prepare(`
251
+ `).run(e,t.slice(0,1e3),n,r?1:0,a,s?JSON.stringify(s):null)}catch(i){console.debug("[SQLitePatternStore] Failed to record pattern reuse:",p(i))}}getPatternReuseStats(e,t=7){if(!this.db)throw new Error("Database not initialized");try{if(!this.db.prepare(`
251
252
  SELECT name FROM sqlite_master WHERE type='table' AND name='qe_pattern_reuse'
252
- `).get())return{totalSearches:0,totalReused:0,reuseRate:0,totalTokensSaved:0,avgSimilarity:0,topPatterns:[]};let r=new Date(Date.now()-n*24*60*60*1e3).toISOString(),a=e?"WHERE pattern_id = ? AND created_at >= ?":"WHERE created_at >= ?",s=e?[e,r]:[r],i=this.db.prepare(`
253
+ `).get())return{totalSearches:0,totalReused:0,reuseRate:0,totalTokensSaved:0,avgSimilarity:0,topPatterns:[]};let r=new Date(Date.now()-t*24*60*60*1e3).toISOString(),a=e?"WHERE pattern_id = ? AND created_at >= ?":"WHERE created_at >= ?",s=e?[e,r]:[r],i=this.db.prepare(`
253
254
  SELECT
254
255
  COUNT(*) as total_searches,
255
256
  SUM(CASE WHEN was_reused = 1 THEN 1 ELSE 0 END) as total_reused,
@@ -267,12 +268,13 @@ import{c as R,g as N,i as O}from"./chunk-PGFCKE4G.js";import{i as S,m as w}from"
267
268
  GROUP BY pattern_id
268
269
  ORDER BY reuse_count DESC
269
270
  LIMIT 10
270
- `).all(r);return{totalSearches:i.total_searches||0,totalReused:i.total_reused||0,reuseRate:i.total_searches>0?(i.total_reused||0)/i.total_searches:0,totalTokensSaved:i.total_tokens_saved||0,avgSimilarity:i.avg_similarity||0,topPatterns:o.map(c=>({patternId:c.pattern_id,reuseCount:c.reuse_count,avgSimilarity:c.avg_similarity}))}}catch(t){return console.debug("[SQLitePatternStore] Failed to get reuse stats:",u(t)),{totalSearches:0,totalReused:0,reuseRate:0,totalTokensSaved:0,avgSimilarity:0,topPatterns:[]}}}async backfillEmbeddings(e=32){if(!this.db)throw new Error("Database not initialized");let n=N(),t=this.db.prepare(`
271
+ `).all(r);return{totalSearches:i.total_searches||0,totalReused:i.total_reused||0,reuseRate:i.total_searches>0?(i.total_reused||0)/i.total_searches:0,totalTokensSaved:i.total_tokens_saved||0,avgSimilarity:i.avg_similarity||0,topPatterns:o.map(c=>({patternId:c.pattern_id,reuseCount:c.reuse_count,avgSimilarity:c.avg_similarity}))}}catch(n){return console.debug("[SQLitePatternStore] Failed to get reuse stats:",p(n)),{totalSearches:0,totalReused:0,reuseRate:0,totalTokensSaved:0,avgSimilarity:0,topPatterns:[]}}}async backfillEmbeddings(e=32){if(!this.db)throw new Error("Database not initialized");let t=A();await f([L]);let n=l()?.spaceId;if(!n)throw new Error("VECTOR_SPACE_UNVERIFIED: backfill embedder has no runtime provenance");let r=this.db.prepare(`
271
272
  SELECT p.id, p.name, p.description, p.pattern_type, p.qe_domain
272
273
  FROM qe_patterns p
273
- WHERE p.id NOT IN (SELECT pattern_id FROM qe_pattern_embeddings)
274
+ LEFT JOIN qe_pattern_embeddings e ON e.pattern_id = p.id
275
+ WHERE (e.pattern_id IS NULL OR e.space_id IS NULL OR e.space_id <> ?)
274
276
  AND p.id NOT LIKE 'bench-%'
275
277
  ORDER BY p.quality_score DESC
276
- `).all(),r=this.db.prepare(`
278
+ `).all(n),a=this.db.prepare(`
277
279
  SELECT COUNT(*) as c FROM qe_pattern_embeddings
278
- `).get();if(t.length===0)return console.log(`[SQLitePatternStore] Backfill: all patterns already have embeddings (${r.c} total)`),{processed:0,skipped:0,errors:0,alreadyHad:r.c,method:"transformer"};console.log(`[SQLitePatternStore] Backfill: ${t.length} patterns need embeddings (${r.c} already have)`);let a=this.prepared.get("insertEmbedding");if(!a)throw new Error("Prepared statements not ready");let s=0,i=0,o=0,c="transformer";for(let m=0;m<t.length;m+=e){let y=t.slice(m,m+e),p=[];for(let d of y){let E=[d.name,d.description,d.pattern_type,d.qe_domain].filter(Boolean).join(" ");if(!E.trim()){i++;continue}p.push({id:d.id,text:E})}if(p.length===0)continue;let b;try{b=await R(p.map(d=>d.text))}catch(d){throw O()?new Error(`[SQLitePatternStore] external embedder endpoint failed during backfill; aborting to protect HNSW index. Original error: ${u(d)}`):new Error(`[SQLitePatternStore] semantic embedding unavailable; refusing to write hash proxies. Install @huggingface/transformers or configure AQE_EMBEDDER_ENDPOINT. Original error: ${u(d)}`)}let A=c==="transformer"?"transformer-backfill":"hash-backfill";this.db.transaction(()=>{for(let d=0;d<p.length;d++)try{let E=b[d];if(!E||E.length!==n){o++;continue}let I=Buffer.from(new Float32Array(E).buffer);a.run(p[d].id,I,n,A),s++}catch(E){o++,o<=3&&console.warn(`[SQLitePatternStore] Backfill error for ${p[d].id}:`,u(E))}})();let l=Math.min(m+e,t.length);(l%100===0||l>=t.length)&&console.log(`[SQLitePatternStore] Backfill progress: ${l}/${t.length}`)}return console.log(`[SQLitePatternStore] Backfill complete (${c}): ${s} processed, ${i} skipped, ${o} errors`),{processed:s,skipped:i,errors:o,alreadyHad:r.c,method:c}}close(){this.db&&(this.unifiedMemory?console.log("[SQLitePatternStore] Detached from unified storage (not closing shared connection)"):(this.db.close(),console.log("[SQLitePatternStore] Database closed")),this.db=null,this.unifiedMemory=null,this.initialized=!1,this.prepared.clear())}exec(e){if(!this.db)throw new Error("Database not initialized");this.db.exec(e)}getDb(){if(!this.db)throw new Error("Database not initialized");return this.db}};function H(_={}){return new g(_)}export{P as a,G as b,g as c,H as d};
280
+ `).get();if(r.length===0)return console.log(`[SQLitePatternStore] Backfill: all patterns already have embeddings (${a.c} total)`),{processed:0,skipped:0,errors:0,alreadyHad:a.c,method:"transformer"};console.log(`[SQLitePatternStore] Backfill: ${r.length} patterns need embeddings (${a.c} already have)`);let s=this.prepared.get("insertEmbedding");if(!s)throw new Error("Prepared statements not ready");let i=0,o=0,c=0,m="transformer";for(let u=0;u<r.length;u+=e){let q=r.slice(u,u+e),_=[];for(let d of q){let E=[d.name,d.description,d.pattern_type,d.qe_domain].filter(Boolean).join(" ");if(!E.trim()){o++;continue}_.push({id:d.id,text:E})}if(_.length===0)continue;let S;try{S=await f(_.map(d=>d.text))}catch(d){throw y()?new Error(`[SQLitePatternStore] external embedder endpoint failed during backfill; aborting to protect HNSW index. Original error: ${p(d)}`):new Error(`[SQLitePatternStore] semantic embedding unavailable; refusing to write hash proxies. Install @huggingface/transformers or configure AQE_EMBEDDER_ENDPOINT. Original error: ${p(d)}`)}let D=m==="transformer"?"transformer-backfill":"hash-backfill";this.db.transaction(()=>{for(let d=0;d<_.length;d++)try{let E=S[d];if(!E||E.length!==t){c++;continue}let w=Buffer.from(new Float32Array(E).buffer);s.run(_[d].id,w,t,D,n),i++}catch(E){c++,c<=3&&console.warn(`[SQLitePatternStore] Backfill error for ${_[d].id}:`,p(E))}})();let g=Math.min(u+e,r.length);(g%100===0||g>=r.length)&&console.log(`[SQLitePatternStore] Backfill progress: ${g}/${r.length}`)}return console.log(`[SQLitePatternStore] Backfill complete (${m}): ${i} processed, ${o} skipped, ${c} errors`),{processed:i,skipped:o,errors:c,alreadyHad:a.c,method:m}}close(){this.db&&(this.unifiedMemory?console.log("[SQLitePatternStore] Detached from unified storage (not closing shared connection)"):(this.db.close(),console.log("[SQLitePatternStore] Database closed")),this.db=null,this.unifiedMemory=null,this.initialized=!1,this.prepared.clear())}exec(e){if(!this.db)throw new Error("Database not initialized");this.db.exec(e)}getDb(){if(!this.db)throw new Error("Database not initialized");return this.db}};function Y(T={}){return new h(T)}export{v as a,W as b,h as c,Y as d};