agentic-qe 3.9.3 → 3.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (280) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/cli/bundle.js +5 -5
  3. package/dist/cli/chunks/adapter-5ODIX6ZG.js +2 -0
  4. package/dist/cli/chunks/{agent-booster-wasm-W6GGSB43.js → agent-booster-wasm-MGGEPROV.js} +2 -2
  5. package/dist/cli/chunks/{agent-handler-3IRN5WBS.js → agent-handler-AFHYFQXV.js} +2 -2
  6. package/dist/cli/chunks/{agent-memory-branch-SO63CIPJ.js → agent-memory-branch-SQ3KDIG6.js} +2 -2
  7. package/dist/cli/chunks/aqe-learning-engine-PWGRS6KK.js +2 -0
  8. package/dist/cli/chunks/{audit-TONGHW5H.js → audit-SM5CK2K5.js} +2 -2
  9. package/dist/cli/chunks/base-TJGIYR7L.js +2 -0
  10. package/dist/cli/chunks/{better-sqlite3-OK5DP5FC.js → better-sqlite3-UGOYRNXI.js} +2 -2
  11. package/dist/cli/chunks/{brain-handler-MC2S3UHL.js → brain-handler-SKXTB63O.js} +3 -3
  12. package/dist/cli/chunks/{branch-enumerator-PRKJKPAE.js → branch-enumerator-77NSOLNK.js} +2 -2
  13. package/dist/cli/chunks/{browser-WTMMBSU3.js → browser-MCE5DWPV.js} +2 -2
  14. package/dist/cli/chunks/browser-workflow-GUR7RLFP.js +2 -0
  15. package/dist/cli/chunks/{chunk-TTEXJW2U.js → chunk-27FNBMUC.js} +2 -2
  16. package/dist/cli/chunks/{chunk-LRE4A464.js → chunk-27P4VTCY.js} +2 -2
  17. package/dist/cli/chunks/{chunk-HJEWQD2B.js → chunk-2JLKOGNU.js} +1 -1
  18. package/dist/cli/chunks/{chunk-QB2LOM5O.js → chunk-2MQMXI7C.js} +2 -2
  19. package/dist/cli/chunks/{chunk-PKIBG7OJ.js → chunk-3MN7E6HY.js} +2 -2
  20. package/dist/cli/chunks/{chunk-GGQCAQM4.js → chunk-3MRFR534.js} +2 -2
  21. package/dist/cli/chunks/{chunk-2CPNZVGL.js → chunk-3RHIPCBG.js} +2 -2
  22. package/dist/cli/chunks/{chunk-53YFAERL.js → chunk-3SPYUOSS.js} +2 -2
  23. package/dist/cli/chunks/{chunk-DGRO6LSI.js → chunk-4BQTEPAD.js} +2 -2
  24. package/dist/cli/chunks/{chunk-CU36MONI.js → chunk-4GJAYXB7.js} +2 -2
  25. package/dist/cli/chunks/{chunk-FIQ62VOQ.js → chunk-4TZTGYBQ.js} +1 -1
  26. package/dist/cli/chunks/{chunk-P6OZKWNK.js → chunk-53M65YFH.js} +2 -2
  27. package/dist/cli/chunks/{chunk-66RCUQCI.js → chunk-54OLXGXJ.js} +2 -2
  28. package/dist/cli/chunks/{chunk-M3EFT3XR.js → chunk-5UKAEBKC.js} +3 -3
  29. package/dist/cli/chunks/{chunk-ITFNPXZL.js → chunk-72EC26AS.js} +2 -2
  30. package/dist/cli/chunks/{chunk-JI5MNJSU.js → chunk-7EL65Y27.js} +1 -1
  31. package/dist/cli/chunks/{chunk-WLK5UVRJ.js → chunk-7FJIIB4H.js} +1 -1
  32. package/dist/cli/chunks/{chunk-COIFERYS.js → chunk-7ST2YENJ.js} +2 -2
  33. package/dist/cli/chunks/{chunk-RRELDHZY.js → chunk-7ZXNJT4Q.js} +2 -2
  34. package/dist/cli/chunks/{chunk-SJLDTV5B.js → chunk-A6ZBQCYB.js} +2 -2
  35. package/dist/cli/chunks/{chunk-S23UV7FV.js → chunk-B252DDC5.js} +1 -1
  36. package/dist/cli/chunks/{chunk-WIY3V5VQ.js → chunk-B6HLXE3D.js} +9 -9
  37. package/dist/cli/chunks/{chunk-JZXSKPQB.js → chunk-BH5XPYA3.js} +2 -2
  38. package/dist/cli/chunks/{chunk-5B2KXDWF.js → chunk-BZ22GI4E.js} +1 -1
  39. package/dist/cli/chunks/{chunk-7ASGPJWU.js → chunk-C2HGOUEB.js} +1 -1
  40. package/dist/cli/chunks/{chunk-YTBE2MEW.js → chunk-C3BXT3ZC.js} +4 -4
  41. package/dist/cli/chunks/{chunk-MNZ2HHKI.js → chunk-C567IO5M.js} +2 -2
  42. package/dist/cli/chunks/{chunk-XJII5WMD.js → chunk-COIRFVFO.js} +1 -1
  43. package/dist/cli/chunks/{chunk-FR26EINS.js → chunk-DHJJJ24V.js} +2 -2
  44. package/dist/cli/chunks/{chunk-NZLJWXXM.js → chunk-DLMEBVLF.js} +2 -2
  45. package/dist/cli/chunks/{chunk-2GZ4EG3L.js → chunk-DZHGYZJP.js} +1 -1
  46. package/dist/cli/chunks/{chunk-DTNXHRUF.js → chunk-EEARIB4C.js} +1 -1
  47. package/dist/cli/chunks/{chunk-ERWNQ6NC.js → chunk-EFD2J6GG.js} +3 -3
  48. package/dist/cli/chunks/{chunk-T4RR4YMH.js → chunk-EHGTXIT7.js} +1 -1
  49. package/dist/cli/chunks/{chunk-LHDR6E6F.js → chunk-ENKPW6MA.js} +2 -2
  50. package/dist/cli/chunks/{chunk-AS5WPUDR.js → chunk-EZTUUOVI.js} +1 -1
  51. package/dist/cli/chunks/{chunk-OXR2FPHK.js → chunk-F6AU2MAZ.js} +2 -2
  52. package/dist/cli/chunks/{chunk-LQDAH47F.js → chunk-G6RTCJFY.js} +2 -2
  53. package/dist/cli/chunks/{chunk-EVIXQR4O.js → chunk-G72E5DL3.js} +1 -1
  54. package/dist/cli/chunks/{chunk-WDTFG5AG.js → chunk-GAG2P4I2.js} +1 -1
  55. package/dist/cli/chunks/{chunk-X5C73DW5.js → chunk-GQ7DCSKS.js} +2 -2
  56. package/dist/cli/chunks/{chunk-GBLX5XOH.js → chunk-GSKZL36U.js} +2 -2
  57. package/dist/cli/chunks/{chunk-ZVMAE5JD.js → chunk-GT35EJKR.js} +1 -1
  58. package/dist/cli/chunks/{chunk-3Q5FG6M3.js → chunk-GVFHRHXC.js} +2 -2
  59. package/dist/cli/chunks/{chunk-TSS6LXJ6.js → chunk-GX7MEHQ2.js} +1 -1
  60. package/dist/cli/chunks/{chunk-JTIWAUWW.js → chunk-HKTNFHWI.js} +1 -1
  61. package/dist/cli/chunks/{chunk-2IU6WK32.js → chunk-IGJ472XJ.js} +2 -2
  62. package/dist/cli/chunks/{chunk-5UMSMRJC.js → chunk-IQE6GOH6.js} +2 -2
  63. package/dist/cli/chunks/{chunk-O2O5RO4H.js → chunk-J222JLZ6.js} +2 -2
  64. package/dist/cli/chunks/{chunk-F6O5XLIE.js → chunk-J6KBI5NW.js} +1 -1
  65. package/dist/cli/chunks/{chunk-PRIWFNVU.js → chunk-J72Q6ERO.js} +2 -2
  66. package/dist/cli/chunks/{chunk-WAWCNUIJ.js → chunk-JMBUIVVE.js} +1 -1
  67. package/dist/cli/chunks/{chunk-OBOCKH47.js → chunk-JVUNZBKX.js} +2 -2
  68. package/dist/cli/chunks/{chunk-TPFE3BAI.js → chunk-KELYPHMV.js} +2 -2
  69. package/dist/cli/chunks/{chunk-LMN72H3V.js → chunk-KSMQH2CV.js} +1 -1
  70. package/dist/cli/chunks/{chunk-Z4V3XV7E.js → chunk-LH3ZL2OK.js} +2 -2
  71. package/dist/cli/chunks/{chunk-AWSYGQEB.js → chunk-LW3DV23G.js} +2 -2
  72. package/dist/cli/chunks/chunk-MDFXPCBO.js +2 -0
  73. package/dist/cli/chunks/{chunk-GGEVILIS.js → chunk-MGRE767N.js} +2 -2
  74. package/dist/cli/chunks/{chunk-OJKGRB6D.js → chunk-MN2MYLVW.js} +2 -2
  75. package/dist/cli/chunks/{chunk-J7QGH6PG.js → chunk-MR5I6UR2.js} +2 -2
  76. package/dist/cli/chunks/{chunk-TUHIFT65.js → chunk-MS6LTE4L.js} +2 -2
  77. package/dist/cli/chunks/{chunk-SVXIAQRW.js → chunk-MUX762XZ.js} +2 -2
  78. package/dist/cli/chunks/{chunk-ZQCU62JJ.js → chunk-NEYZXYFH.js} +2 -2
  79. package/dist/cli/chunks/{chunk-EXTVDKH7.js → chunk-NRH2QE4X.js} +3 -3
  80. package/dist/cli/chunks/{chunk-T4GTFSB2.js → chunk-NS4CCCTZ.js} +2 -2
  81. package/dist/cli/chunks/{chunk-QAXJOCTW.js → chunk-NZ5LY2BT.js} +1 -1
  82. package/dist/cli/chunks/{chunk-ELU576GE.js → chunk-O6QAOPUA.js} +3 -3
  83. package/dist/cli/chunks/{chunk-U6QQS5Z3.js → chunk-OHZ6RJLS.js} +2 -2
  84. package/dist/cli/chunks/{chunk-DBSVEWWL.js → chunk-ONOYANDX.js} +1 -1
  85. package/dist/cli/chunks/{chunk-M7PGW5Z5.js → chunk-OZC42UMD.js} +2 -2
  86. package/dist/cli/chunks/{chunk-WSVWVIVR.js → chunk-P3EOWBME.js} +2 -2
  87. package/dist/cli/chunks/{chunk-OV6H3TRU.js → chunk-Q2ZYUIS2.js} +2 -2
  88. package/dist/cli/chunks/{chunk-PS6KLLLQ.js → chunk-Q6FSXNQP.js} +2 -2
  89. package/dist/cli/chunks/{chunk-JXE2DFXM.js → chunk-QEYPK7KS.js} +1 -1
  90. package/dist/cli/chunks/{chunk-OZNJZMQL.js → chunk-QOU4R6AF.js} +2 -2
  91. package/dist/cli/chunks/{chunk-SDHZLA45.js → chunk-QPC4STR6.js} +2 -2
  92. package/dist/cli/chunks/{chunk-UVWKIP3U.js → chunk-QVZSIFSJ.js} +3 -3
  93. package/dist/cli/chunks/{chunk-LDLLHLKE.js → chunk-RAZ2PGZD.js} +2 -2
  94. package/dist/cli/chunks/{chunk-UC3RA5LW.js → chunk-RE6XD6RI.js} +2 -2
  95. package/dist/cli/chunks/{chunk-T5MWENBA.js → chunk-RGRYL4MG.js} +2 -2
  96. package/dist/cli/chunks/{chunk-DBEU5ISS.js → chunk-RN3SN4ZC.js} +2 -2
  97. package/dist/cli/chunks/{chunk-6N26CWST.js → chunk-RPYUKEAH.js} +2 -2
  98. package/dist/cli/chunks/{chunk-SFFI3MDN.js → chunk-RRQEIGLS.js} +2 -2
  99. package/dist/cli/chunks/{chunk-HVOOYPW6.js → chunk-RS7ZGWHV.js} +2 -2
  100. package/dist/cli/chunks/{chunk-DKOOKULB.js → chunk-RTC3ZCPK.js} +2 -2
  101. package/dist/cli/chunks/{chunk-BRCCPQXN.js → chunk-RUJU5XEQ.js} +1 -1
  102. package/dist/cli/chunks/{chunk-CF4T4YSL.js → chunk-SHJZ3YNX.js} +2 -2
  103. package/dist/cli/chunks/{chunk-VNSRA5PY.js → chunk-SKWI5QBM.js} +2 -2
  104. package/dist/cli/chunks/{chunk-5YUNMBIH.js → chunk-TNWTQWLL.js} +1 -1
  105. package/dist/cli/chunks/{chunk-MSKVWOND.js → chunk-TT2TB6UF.js} +3 -3
  106. package/dist/cli/chunks/{chunk-IOW7QTYT.js → chunk-U7YC7VCM.js} +2 -2
  107. package/dist/cli/chunks/{chunk-KV32LAKU.js → chunk-UJLSCJJS.js} +1 -1
  108. package/dist/cli/chunks/{chunk-6B4CTO5D.js → chunk-UPJZRDZK.js} +2 -2
  109. package/dist/cli/chunks/{chunk-JF6AXXAL.js → chunk-UUL3D5HR.js} +4 -4
  110. package/dist/cli/chunks/{chunk-5OL6UOBM.js → chunk-V57PXZIK.js} +3 -3
  111. package/dist/cli/chunks/{chunk-PD5YPC2A.js → chunk-VBXJBXMG.js} +4 -4
  112. package/dist/cli/chunks/{chunk-TA454OEB.js → chunk-VBYREHZI.js} +1 -1
  113. package/dist/cli/chunks/{chunk-3GMN3PNP.js → chunk-VFXTZWNF.js} +2 -2
  114. package/dist/cli/chunks/{chunk-K2DDNM4V.js → chunk-VSNPI2NO.js} +8 -8
  115. package/dist/cli/chunks/{chunk-FSUS5TV6.js → chunk-WHT46PJM.js} +2 -2
  116. package/dist/cli/chunks/{chunk-GGKV5IQR.js → chunk-XB5HXTL4.js} +2 -2
  117. package/dist/cli/chunks/{chunk-ZTIPMKUS.js → chunk-XYVMKCSI.js} +1 -1
  118. package/dist/cli/chunks/{chunk-BK445WWE.js → chunk-YDJKQKQH.js} +2 -2
  119. package/dist/cli/chunks/{chunk-D5GIV6O7.js → chunk-YS6C2Q4F.js} +1 -1
  120. package/dist/cli/chunks/{chunk-D5AQDGTS.js → chunk-Z75DMTMI.js} +1 -1
  121. package/dist/cli/chunks/{chunk-P4RYVWIR.js → chunk-ZKWNZ3ZK.js} +2 -2
  122. package/dist/cli/chunks/{chunk-7HTSXZ77.js → chunk-ZODUKKPC.js} +2 -2
  123. package/dist/cli/chunks/{chunk-ZMUVSL5Q.js → chunk-ZQSEPDIJ.js} +2 -2
  124. package/dist/cli/chunks/{chunk-7JBIDAXT.js → chunk-ZW5DRPZY.js} +2 -2
  125. package/dist/cli/chunks/{ci-XQEZTRJN.js → ci-THZEECIQ.js} +2 -2
  126. package/dist/cli/chunks/{ci-output-ZWGXOIUD.js → ci-output-G6QLGL4S.js} +2 -2
  127. package/dist/cli/chunks/{claude-flow-setup-PFJFHZSD.js → claude-flow-setup-5MTYQM34.js} +2 -2
  128. package/dist/cli/chunks/client-IFMC3AYQ.js +2 -0
  129. package/dist/cli/chunks/{cline-installer-L3WC4KUM.js → cline-installer-E2LF2DQS.js} +2 -2
  130. package/dist/cli/chunks/{code-QMDXXY6C.js → code-QRF7ZGXG.js} +2 -2
  131. package/dist/cli/chunks/{code-index-extractor-YTPMAZPU.js → code-index-extractor-II6IRWU6.js} +2 -2
  132. package/dist/cli/chunks/{codex-installer-KO5G7LHQ.js → codex-installer-LGOQ23ZS.js} +2 -2
  133. package/dist/cli/chunks/{completions-KVDPIXMY.js → completions-LB2RR2OQ.js} +2 -2
  134. package/dist/cli/chunks/{complexity-analyzer-KNIBPEC3.js → complexity-analyzer-PUIPIRX3.js} +2 -2
  135. package/dist/cli/chunks/{continuedev-installer-N2GWI5PC.js → continuedev-installer-HQAEAQZU.js} +2 -2
  136. package/dist/cli/chunks/{copilot-installer-EX3UTDQN.js → copilot-installer-3PKCX5K5.js} +2 -2
  137. package/dist/cli/chunks/{cost-tracker-XX6OMP37.js → cost-tracker-JG3SZ2Q3.js} +2 -2
  138. package/dist/cli/chunks/{coverage-FHDDNCPO.js → coverage-D3PZTOKT.js} +3 -3
  139. package/dist/cli/chunks/cross-domain-router-2LPBUUWY.js +2 -0
  140. package/dist/cli/chunks/{cursor-installer-M47YCQU7.js → cursor-installer-UY6GWKTO.js} +2 -2
  141. package/dist/cli/chunks/{daemon-EV3RXWAG.js → daemon-UNO3LRRN.js} +3 -3
  142. package/dist/cli/chunks/{dag-attention-scheduler-J7JDWG5J.js → dag-attention-scheduler-S2MXANYL.js} +2 -2
  143. package/dist/cli/chunks/{detect-4P5RKV5J.js → detect-DU2FTRKR.js} +2 -2
  144. package/dist/cli/chunks/{domain-handler-Q35TYDGA.js → domain-handler-KPNO36LF.js} +2 -2
  145. package/dist/cli/chunks/{domain-transfer-XC34MV5U.js → domain-transfer-6X3ZZF6A.js} +2 -2
  146. package/dist/cli/chunks/dream-NGRDMOTE.js +2 -0
  147. package/dist/cli/chunks/esm-node-3COTOSO3.js +2 -0
  148. package/dist/cli/chunks/{eval-QZGRW7XD.js → eval-6RXEDTBZ.js} +2 -2
  149. package/dist/cli/chunks/{fast-paths-O42GG56B.js → fast-paths-FYODFGZB.js} +2 -2
  150. package/dist/cli/chunks/{feature-flags-G6SJTDVO.js → feature-flags-YOULURDA.js} +2 -2
  151. package/dist/cli/chunks/{feature-flags-GIGWUPEX.js → feature-flags-ZJ42B4IL.js} +2 -2
  152. package/dist/cli/chunks/{file-discovery-D4NXB3JP.js → file-discovery-KOL7FSBQ.js} +2 -2
  153. package/dist/cli/chunks/{fleet-ZXZ5AAPW.js → fleet-22I74LGD.js} +3 -3
  154. package/dist/cli/chunks/{gnn-wrapper-YK6NAPJV.js → gnn-wrapper-DFHTHLIZ.js} +2 -2
  155. package/dist/cli/chunks/{heartbeat-handler-DD4T6U36.js → heartbeat-handler-SQ6VYEAA.js} +4 -4
  156. package/dist/cli/chunks/{heartbeat-scheduler-CBPO5KUB.js → heartbeat-scheduler-W6PQJ5SG.js} +2 -2
  157. package/dist/cli/chunks/hnsw-adapter-BASJNTEV.js +2 -0
  158. package/dist/cli/chunks/hnsw-index-NFN2AUIX.js +2 -0
  159. package/dist/cli/chunks/{hnsw-legacy-bridge-REKPPJ75.js → hnsw-legacy-bridge-AYTRT54U.js} +2 -2
  160. package/dist/cli/chunks/{hnswlib-node-PMWK24KT.js → hnswlib-node-4IA56UH4.js} +2 -2
  161. package/dist/cli/chunks/{hooks-UDKFTCJ7.js → hooks-T6UMR72X.js} +6 -6
  162. package/dist/cli/chunks/{hypergraph-engine-FIAZJD7K.js → hypergraph-engine-WVPYKMFY.js} +2 -2
  163. package/dist/cli/chunks/{hypergraph-handler-NN2EBNBW.js → hypergraph-handler-NB6GL4CR.js} +3 -3
  164. package/dist/cli/chunks/impact-analyzer-ZMQXHQDV.js +2 -0
  165. package/dist/cli/chunks/init-handler-UOFNBXEP.js +68 -0
  166. package/dist/cli/chunks/init-wizard-QHAA4GWF.js +2 -0
  167. package/dist/cli/chunks/kernel-SNJFYN3T.js +2 -0
  168. package/dist/cli/chunks/{kilocode-installer-6XPW7IAO.js → kilocode-installer-VWMNI4QX.js} +2 -2
  169. package/dist/cli/chunks/{kiro-installer-DOHZGTBZ.js → kiro-installer-RNM47FV5.js} +15 -15
  170. package/dist/cli/chunks/knowledge-graph-EP5UTODP.js +2 -0
  171. package/dist/cli/chunks/{learning-GRSMZRPZ.js → learning-L4RB5XYP.js} +3 -3
  172. package/dist/cli/chunks/{llm-router-MTZPLM7A.js → llm-router-BZYZL3YI.js} +2 -2
  173. package/dist/cli/chunks/{load-CQXXMUR7.js → load-4UGEGRMO.js} +2 -2
  174. package/dist/cli/chunks/load-test-KMMRHABK.js +2 -0
  175. package/dist/cli/chunks/{mcp-IIPV4IWF.js → mcp-FWWZIWCI.js} +2 -2
  176. package/dist/cli/chunks/{memory-GIODHUAL.js → memory-5OXPMXU6.js} +5 -5
  177. package/dist/cli/chunks/memory-backend-Q5MWPMDE.js +2 -0
  178. package/dist/cli/chunks/{memory-handlers-O6UVJSAG.js → memory-handlers-JS7BTWJK.js} +2 -2
  179. package/dist/cli/chunks/{opencode-installer-DDIIEIKL.js → opencode-installer-BS5TQKHB.js} +2 -2
  180. package/dist/cli/chunks/{orchestrator-PAQTJDA3.js → orchestrator-G6BUZ6QE.js} +16 -16
  181. package/dist/cli/chunks/{pipeline-6HFLH75G.js → pipeline-3MZ5COPR.js} +2 -2
  182. package/dist/cli/chunks/{platform-UKK776G2.js → platform-TKD4JCUG.js} +2 -2
  183. package/dist/cli/chunks/{plugin-ERW5YBXU.js → plugin-XXJ7R6SY.js} +2 -2
  184. package/dist/cli/chunks/{prime-radiant-advanced-wasm-WB5A4ULB.js → prime-radiant-advanced-wasm-JLJ6NKIP.js} +2 -2
  185. package/dist/cli/chunks/protocol-executor-ORFR4WJ3.js +2 -0
  186. package/dist/cli/chunks/{protocol-handler-AKDFZI6G.js → protocol-handler-ZLYGQPHG.js} +2 -2
  187. package/dist/cli/chunks/{prove-GT5XEWVF.js → prove-E2WZ335X.js} +2 -2
  188. package/dist/cli/chunks/qe-reasoning-bank-PLTOH4SG.js +2 -0
  189. package/dist/cli/chunks/{quality-VZAG6B54.js → quality-6MHHBINU.js} +2 -2
  190. package/dist/cli/chunks/queen-coordinator-L3TRAX7H.js +2 -0
  191. package/dist/cli/chunks/{real-embeddings-KOOT5MTA.js → real-embeddings-QN5BY3WS.js} +2 -2
  192. package/dist/cli/chunks/{roocode-installer-KHGDU6QK.js → roocode-installer-GTVII272.js} +2 -2
  193. package/dist/cli/chunks/router-3PBJJLRQ.js +2 -0
  194. package/dist/cli/chunks/routing-feedback-Q775MZ3Z.js +2 -0
  195. package/dist/cli/chunks/{routing-handler-HVCNYSJM.js → routing-handler-HYKZ3ISS.js} +2 -2
  196. package/dist/cli/chunks/{ruvector-commands-D46MOJ32.js → ruvector-commands-LBWHPUTZ.js} +2 -2
  197. package/dist/cli/chunks/{rvf-dual-writer-WASNBBMN.js → rvf-dual-writer-TVCJ2Y6N.js} +2 -2
  198. package/dist/cli/chunks/{rvf-migration-adapter-ESLGEE5X.js → rvf-migration-adapter-34ITXLU3.js} +2 -2
  199. package/dist/cli/chunks/{rvf-migration-coordinator-S5NAMHTP.js → rvf-migration-coordinator-SX2C7777.js} +2 -2
  200. package/dist/cli/chunks/rvf-native-adapter-HLY2652E.js +2 -0
  201. package/dist/cli/chunks/safe-db-CCKCBZ5I.js +2 -0
  202. package/dist/cli/chunks/schedule-WZ5VV55N.js +2 -0
  203. package/dist/cli/chunks/scheduler-6PIKLCH7.js +2 -0
  204. package/dist/cli/chunks/{security-4AHBDCJJ.js → security-7A4EW77M.js} +3 -3
  205. package/dist/cli/chunks/shared-rvf-adapter-VCJNSACZ.js +2 -0
  206. package/dist/cli/chunks/{shared-rvf-dual-writer-ZFNW4C3N.js → shared-rvf-dual-writer-27L4R5WK.js} +2 -2
  207. package/dist/cli/chunks/sqlite-persistence-HMXYD56G.js +2 -0
  208. package/dist/cli/chunks/{status-handler-ZVC4HX5J.js → status-handler-JN6PRYLD.js} +2 -2
  209. package/dist/cli/chunks/{structural-health-DPFQ4GEF.js → structural-health-JSY3DY7H.js} +2 -2
  210. package/dist/cli/chunks/{sync-7A5JMQNB.js → sync-ET3LYW2V.js} +10 -10
  211. package/dist/cli/chunks/{task-handler-OFZ5YMXH.js → task-handler-R24MR74L.js} +2 -2
  212. package/dist/cli/chunks/{task-handlers-IRSHSFQW.js → task-handlers-YNPEEPPZ.js} +2 -2
  213. package/dist/cli/chunks/{test-F6XPB2DN.js → test-7BZXFZCT.js} +4 -4
  214. package/dist/cli/chunks/{test-scheduling-CPHQ7DBP.js → test-scheduling-EVIFD5EY.js} +3 -3
  215. package/dist/cli/chunks/{token-bootstrap-5YD6K4LL.js → token-bootstrap-QYYQRXM5.js} +2 -2
  216. package/dist/cli/chunks/{token-usage-KQYGQAEK.js → token-usage-H4OZA77I.js} +2 -2
  217. package/dist/cli/chunks/{transformers-P7TT2MJB.js → transformers-ILQFO5HZ.js} +2 -2
  218. package/dist/cli/chunks/{tree-sitter-wasm-parser-SUSDXGOP.js → tree-sitter-wasm-parser-KTST5NWH.js} +2 -2
  219. package/dist/cli/chunks/{types-OEGMO7AH.js → types-4Z7XELU6.js} +2 -2
  220. package/dist/cli/chunks/unified-memory-RBHCTAWW.js +2 -0
  221. package/dist/cli/chunks/unified-memory-hnsw-UBF5PT6D.js +2 -0
  222. package/dist/cli/chunks/unified-persistence-ZIJDP6GW.js +2 -0
  223. package/dist/cli/chunks/{validate-XI4GTLQR.js → validate-GSQCH6VN.js} +2 -2
  224. package/dist/cli/chunks/{validate-swarm-UZQR6AWZ.js → validate-swarm-SP2RPOYD.js} +2 -2
  225. package/dist/cli/chunks/{vibium-VPJH2KD5.js → vibium-2SGOFYTF.js} +2 -2
  226. package/dist/cli/chunks/visual-security-WKIWOUTH.js +2 -0
  227. package/dist/cli/chunks/{web-tree-sitter-LUNFY67E.js → web-tree-sitter-QSQ27UTH.js} +2 -2
  228. package/dist/cli/chunks/{windsurf-installer-LTJCP7AT.js → windsurf-installer-NIEH46E2.js} +2 -2
  229. package/dist/cli/chunks/witness-chain-4BRX3GGH.js +2 -0
  230. package/dist/cli/chunks/{witness-chain-YWBIN5MQ.js → witness-chain-62GJTCT5.js} +2 -2
  231. package/dist/cli/chunks/{workflow-UGXLNO36.js → workflow-WZMV2MGW.js} +4 -4
  232. package/dist/cli/chunks/workflow-orchestrator-G6VU7QZ4.js +2 -0
  233. package/dist/cli/chunks/{wrappers-LUJRP2YI.js → wrappers-LNTV533I.js} +2 -2
  234. package/dist/cli/commands/init.js +2 -0
  235. package/dist/cli/commands/sync.js +25 -8
  236. package/dist/cli/handlers/init-handler.d.ts +1 -0
  237. package/dist/cli/handlers/init-handler.js +2 -0
  238. package/dist/init/governance-installer.js +46 -14
  239. package/dist/init/kiro-installer.js +15 -2
  240. package/dist/init/orchestrator.js +1 -0
  241. package/dist/init/phases/06-code-intelligence.d.ts +13 -0
  242. package/dist/init/phases/06-code-intelligence.js +46 -7
  243. package/dist/init/phases/phase-interface.d.ts +9 -0
  244. package/dist/mcp/bundle.js +1 -1
  245. package/package.json +1 -1
  246. package/dist/cli/chunks/adapter-WKI55MLS.js +0 -2
  247. package/dist/cli/chunks/aqe-learning-engine-QQHHH3ZL.js +0 -2
  248. package/dist/cli/chunks/base-3ENVJTIL.js +0 -2
  249. package/dist/cli/chunks/browser-workflow-QVT343YP.js +0 -2
  250. package/dist/cli/chunks/chunk-FONTSK2O.js +0 -2
  251. package/dist/cli/chunks/client-VUKA3X4R.js +0 -2
  252. package/dist/cli/chunks/cross-domain-router-5SUV5AP6.js +0 -2
  253. package/dist/cli/chunks/dream-2UNEPNI2.js +0 -2
  254. package/dist/cli/chunks/esm-node-TPR2KU6L.js +0 -2
  255. package/dist/cli/chunks/hnsw-adapter-BLMGBVDE.js +0 -2
  256. package/dist/cli/chunks/hnsw-index-UWMXU7RN.js +0 -2
  257. package/dist/cli/chunks/impact-analyzer-RK2VPRRL.js +0 -2
  258. package/dist/cli/chunks/init-handler-RK256F2M.js +0 -68
  259. package/dist/cli/chunks/init-wizard-HA2VADPV.js +0 -2
  260. package/dist/cli/chunks/kernel-QMZBPOWP.js +0 -2
  261. package/dist/cli/chunks/knowledge-graph-INYQCVMS.js +0 -2
  262. package/dist/cli/chunks/load-test-YSEU2TUL.js +0 -2
  263. package/dist/cli/chunks/memory-backend-MNSPY44E.js +0 -2
  264. package/dist/cli/chunks/protocol-executor-CBKER6RL.js +0 -2
  265. package/dist/cli/chunks/qe-reasoning-bank-C3J4RA2M.js +0 -2
  266. package/dist/cli/chunks/queen-coordinator-ZXTNAEYV.js +0 -2
  267. package/dist/cli/chunks/router-YMQF6M2D.js +0 -2
  268. package/dist/cli/chunks/routing-feedback-MM7LNDS7.js +0 -2
  269. package/dist/cli/chunks/rvf-native-adapter-3EEWPK4C.js +0 -2
  270. package/dist/cli/chunks/safe-db-5P6ABYNG.js +0 -2
  271. package/dist/cli/chunks/schedule-ZGESH3FK.js +0 -2
  272. package/dist/cli/chunks/scheduler-AC4AA2BD.js +0 -2
  273. package/dist/cli/chunks/shared-rvf-adapter-UQQUEC52.js +0 -2
  274. package/dist/cli/chunks/sqlite-persistence-KXDW2Q66.js +0 -2
  275. package/dist/cli/chunks/unified-memory-MNW25PVU.js +0 -2
  276. package/dist/cli/chunks/unified-memory-hnsw-4RZRP37O.js +0 -2
  277. package/dist/cli/chunks/unified-persistence-6UBNXF25.js +0 -2
  278. package/dist/cli/chunks/visual-security-7742DBSK.js +0 -2
  279. package/dist/cli/chunks/witness-chain-QVPNOHDC.js +0 -2
  280. package/dist/cli/chunks/workflow-orchestrator-K3Q2GOEG.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.9.3");process.exit(0)}
2
- import{a as ye}from"./chunk-FONTSK2O.js";import{c as oe,d as ce,e as fe}from"./chunk-6N26CWST.js";import{b as N,d as le}from"./chunk-CU36MONI.js";import{b as w,c as L}from"./chunk-TA454OEB.js";import{a as j,b as D,c as V}from"./chunk-OXR2FPHK.js";ye();import{createRequire as be}from"module";var O;function W(){if(!O){let h=be(import.meta.url);try{O=h("typescript")}catch{try{O=h("typescript/lib/typescript.js")}catch{O=new Proxy({},{get(e,t){if(!(t==="__esModule"||typeof t=="symbol"))throw new Error("TypeScript is required for code analysis. Install it: npm install -g typescript")}})}}}return O}var p=new Proxy({},{get(h,e){return W()[e]},has(h,e){return e in W()},ownKeys(){return Object.keys(W())},getOwnPropertyDescriptor(h,e){let t=W()[e];if(t!==void 0)return{configurable:!0,enumerable:!0,value:t}}});var F=class{parseFile(e,t){return p.createSourceFile(e,t,p.ScriptTarget.Latest,!0,this.getScriptKind(e))}extractFunctions(e){let t=[],s=n=>{p.isFunctionDeclaration(n)&&n.name?t.push(this.extractFunctionDeclaration(n,e)):p.isVariableStatement(n)&&this.extractArrowFunctions(n,e,t),p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractClasses(e){let t=[],s=n=>{p.isClassDeclaration(n)&&n.name&&t.push(this.extractClassDeclaration(n,e)),p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractImports(e){let t=[],s=n=>{p.isImportDeclaration(n)&&t.push(this.extractImportDeclaration(n)),p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractExports(e){let t=[],s=n=>{if(p.isExportDeclaration(n))this.extractExportDeclaration(n,t);else if(p.isExportAssignment(n))t.push({name:this.getExportAssignmentName(n),type:"unknown",isDefault:!0,isReexport:!1,sourceModule:void 0});else if(p.isFunctionDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"function",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(p.isClassDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"class",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(p.isVariableStatement(n)&&this.hasExportModifier(n))for(let r of n.declarationList.declarations)p.isIdentifier(r.name)&&t.push({name:r.name.text,type:"variable",isDefault:!1,isReexport:!1,sourceModule:void 0});else p.isInterfaceDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"interface",isDefault:!1,isReexport:!1,sourceModule:void 0}):p.isTypeAliasDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"type",isDefault:!1,isReexport:!1,sourceModule:void 0}):p.isEnumDeclaration(n)&&this.hasExportModifier(n)&&t.push({name:n.name.text,type:"enum",isDefault:!1,isReexport:!1,sourceModule:void 0});p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractInterfaces(e){let t=[],s=n=>{p.isInterfaceDeclaration(n)&&t.push(this.extractInterfaceDeclaration(n,e)),p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractEntities(e,t){let s=this.parseFile(t,e),n=[],r=this.extractFunctions(s);for(let a of r)n.push({name:a.name,type:"function",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:a.isAsync,isExported:a.isExported,parameters:a.parameters,returnType:a.returnType});let o=this.extractClasses(s);for(let a of o)n.push({name:a.name,type:"class",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported,extends:a.extends,implements:a.implements});let i=this.extractInterfaces(s);for(let a of i)n.push({name:a.name,type:"interface",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported});return n}getScriptKind(e){return e.endsWith(".tsx")?p.ScriptKind.TSX:e.endsWith(".ts")?p.ScriptKind.TS:e.endsWith(".jsx")?p.ScriptKind.JSX:e.endsWith(".js")?p.ScriptKind.JS:p.ScriptKind.TS}extractFunctionDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:e.name?.text??"anonymous",parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,startLine:s+1,endLine:n+1,isAsync:this.hasAsyncModifier(e),isExported:this.hasExportModifier(e),isGenerator:!!e.asteriskToken,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractArrowFunctions(e,t,s){for(let n of e.declarationList.declarations)if(p.isIdentifier(n.name)&&n.initializer&&p.isArrowFunction(n.initializer)){let r=n.initializer,{line:o}=t.getLineAndCharacterOfPosition(e.getStart()),{line:i}=t.getLineAndCharacterOfPosition(e.getEnd());s.push({name:n.name.text,parameters:this.extractParameters(r.parameters),returnType:r.type?r.type.getText(t):void 0,startLine:o+1,endLine:i+1,isAsync:this.hasAsyncModifier(r),isExported:this.hasExportModifier(e),isGenerator:!1,typeParameters:this.extractTypeParameters(r.typeParameters)})}}extractClassDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),r=[],o=[];for(let c of e.members)p.isMethodDeclaration(c)&&c.name?r.push(this.extractMethodDeclaration(c,t)):p.isPropertyDeclaration(c)&&c.name?o.push(this.extractPropertyDeclaration(c,t)):p.isConstructorDeclaration(c)&&(r.push(this.extractConstructor(c,t)),this.extractParameterProperties(c,o,t));let i,a=[];if(e.heritageClauses){for(let c of e.heritageClauses)if(c.token===p.SyntaxKind.ExtendsKeyword)i=c.types[0]?.expression.getText(t);else if(c.token===p.SyntaxKind.ImplementsKeyword)for(let l of c.types)a.push(l.expression.getText(t))}return{name:e.name?.text??"anonymous",methods:r,properties:o,extends:i,implements:a,isAbstract:this.hasAbstractModifier(e),isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractMethodDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:this.getPropertyName(e.name,t),parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,isAsync:this.hasAsyncModifier(e),isStatic:this.hasStaticModifier(e),isAbstract:this.hasAbstractModifier(e),visibility:this.getVisibility(e),startLine:s+1,endLine:n+1}}extractConstructor(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:"constructor",parameters:this.extractParameters(e.parameters),returnType:void 0,isAsync:!1,isStatic:!1,isAbstract:!1,visibility:"public",startLine:s+1,endLine:n+1}}extractParameterProperties(e,t,s){for(let n of e.parameters)this.isParameterProperty(n)&&t.push({name:p.isIdentifier(n.name)?n.name.text:n.name.getText(s),type:n.type?n.type.getText(s):void 0,isStatic:!1,isReadonly:this.hasReadonlyModifier(n),visibility:this.getVisibility(n),hasInitializer:!!n.initializer})}isParameterProperty(e){return!!e.modifiers?.some(t=>t.kind===p.SyntaxKind.PublicKeyword||t.kind===p.SyntaxKind.PrivateKeyword||t.kind===p.SyntaxKind.ProtectedKeyword||t.kind===p.SyntaxKind.ReadonlyKeyword)}extractPropertyDeclaration(e,t){return{name:this.getPropertyName(e.name,t),type:e.type?e.type.getText(t):void 0,isStatic:this.hasStaticModifier(e),isReadonly:this.hasReadonlyModifier(e),visibility:this.getVisibility(e),hasInitializer:!!e.initializer}}extractImportDeclaration(e){let t=e.moduleSpecifier.text,s=[],n,r,o=e.importClause?.isTypeOnly??!1;if(e.importClause&&(e.importClause.name&&(n=e.importClause.name.text),e.importClause.namedBindings)){if(p.isNamespaceImport(e.importClause.namedBindings))r=e.importClause.namedBindings.name.text;else if(p.isNamedImports(e.importClause.namedBindings))for(let i of e.importClause.namedBindings.elements)s.push({name:i.propertyName?.text??i.name.text,alias:i.propertyName?i.name.text:void 0})}return{module:t,namedImports:s,defaultImport:n,namespaceImport:r,isTypeOnly:o}}extractExportDeclaration(e,t){let s=e.moduleSpecifier?e.moduleSpecifier.text:void 0;if(e.exportClause&&p.isNamedExports(e.exportClause))for(let n of e.exportClause.elements)t.push({name:n.name.text,type:"unknown",isDefault:!1,isReexport:!!s,sourceModule:s});else!e.exportClause&&s&&t.push({name:"*",type:"unknown",isDefault:!1,isReexport:!0,sourceModule:s})}extractInterfaceDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),r=[],o=[];for(let a of e.members)p.isPropertySignature(a)&&a.name?r.push({name:this.getPropertyName(a.name,t),type:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken,isReadonly:this.hasReadonlyModifier(a)}):p.isMethodSignature(a)&&a.name&&o.push({name:this.getPropertyName(a.name,t),parameters:this.extractParameters(a.parameters),returnType:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken});let i=[];if(e.heritageClauses){for(let a of e.heritageClauses)if(a.token===p.SyntaxKind.ExtendsKeyword)for(let c of a.types)i.push(c.expression.getText(t))}return{name:e.name.text,properties:r,methods:o,extends:i,isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractParameters(e){return e.map(t=>{let s=t.getSourceFile();return{name:p.isIdentifier(t.name)?t.name.text:t.name.getText(s),type:t.type?t.type.getText(s):void 0,isOptional:!!t.questionToken||!!t.initializer,isRest:!!t.dotDotDotToken,defaultValue:t.initializer?t.initializer.getText(s):void 0}})}extractTypeParameters(e){return e?e.map(t=>t.name.text):[]}getPropertyName(e,t){return p.isIdentifier(e)||p.isStringLiteral(e)||p.isNumericLiteral(e)?e.text:e.getText(t)}getExportAssignmentName(e){return p.isIdentifier(e.expression)?e.expression.text:"default"}hasExportModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.ExportKeyword)}hasDefaultModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.DefaultKeyword)}hasAsyncModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.AsyncKeyword)}hasStaticModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.StaticKeyword)}hasAbstractModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.AbstractKeyword)}hasReadonlyModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.ReadonlyKeyword)}getVisibility(e){if(!p.canHaveModifiers(e))return"public";let t=p.getModifiers(e);return t?t.some(s=>s.kind===p.SyntaxKind.PrivateKeyword)?"private":t.some(s=>s.kind===p.SyntaxKind.ProtectedKeyword)?"protected":"public":"public"}},Me=new F,q=class{language="typescript";supportedExtensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];parser=new F;async parseFile(e,t){let s=this.parser.parseFile(t,e),n=this.parser.extractFunctions(s),r=this.parser.extractClasses(s),o=this.parser.extractImports(s);return{functions:n.map(i=>this.mapFunction(i)),classes:r.map(i=>this.mapClass(i)),imports:o.map(i=>this.mapImport(i)),language:t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":"typescript",filePath:t}}mapFunction(e){return{name:e.name,parameters:e.parameters.map(t=>({name:t.name,type:t.type,isOptional:t.isOptional,defaultValue:t.defaultValue})),returnType:e.returnType,isAsync:e.isAsync,isPublic:e.isExported,complexity:1,decorators:[],genericParams:e.typeParameters,startLine:e.startLine,endLine:e.endLine}}mapClass(e){return{name:e.name,methods:e.methods.map(t=>({name:t.name,parameters:t.parameters.map(s=>({name:s.name,type:s.type,isOptional:s.isOptional,defaultValue:s.defaultValue})),returnType:t.returnType,isAsync:t.isAsync,isPublic:t.visibility==="public",complexity:1,decorators:[],genericParams:[],startLine:t.startLine,endLine:t.endLine})),properties:e.properties.map(t=>this.mapProperty(t)),isPublic:e.isExported,implements:e.implements,extends:e.extends,decorators:[],startLine:e.startLine,endLine:e.endLine}}mapProperty(e){return{name:e.name,type:e.type,isPublic:e.visibility==="public",isReadonly:e.isReadonly}}mapImport(e){return{module:e.module,namedImports:e.namedImports.map(t=>t.alias||t.name),isTypeOnly:e.isTypeOnly}}},Se=new q;fe();var E=1e3;function I(h){let e=h.split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
2
+ import{a as ye}from"./chunk-MDFXPCBO.js";import{c as oe,d as ce,e as fe}from"./chunk-RPYUKEAH.js";import{b as N,d as le}from"./chunk-4GJAYXB7.js";import{b as w,c as L}from"./chunk-VBYREHZI.js";import{a as j,b as D,c as V}from"./chunk-F6AU2MAZ.js";ye();import{createRequire as be}from"module";var O;function W(){if(!O){let h=be(import.meta.url);try{O=h("typescript")}catch{try{O=h("typescript/lib/typescript.js")}catch{O=new Proxy({},{get(e,t){if(!(t==="__esModule"||typeof t=="symbol"))throw new Error("TypeScript is required for code analysis. Install it: npm install -g typescript")}})}}}return O}var p=new Proxy({},{get(h,e){return W()[e]},has(h,e){return e in W()},ownKeys(){return Object.keys(W())},getOwnPropertyDescriptor(h,e){let t=W()[e];if(t!==void 0)return{configurable:!0,enumerable:!0,value:t}}});var F=class{parseFile(e,t){return p.createSourceFile(e,t,p.ScriptTarget.Latest,!0,this.getScriptKind(e))}extractFunctions(e){let t=[],s=n=>{p.isFunctionDeclaration(n)&&n.name?t.push(this.extractFunctionDeclaration(n,e)):p.isVariableStatement(n)&&this.extractArrowFunctions(n,e,t),p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractClasses(e){let t=[],s=n=>{p.isClassDeclaration(n)&&n.name&&t.push(this.extractClassDeclaration(n,e)),p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractImports(e){let t=[],s=n=>{p.isImportDeclaration(n)&&t.push(this.extractImportDeclaration(n)),p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractExports(e){let t=[],s=n=>{if(p.isExportDeclaration(n))this.extractExportDeclaration(n,t);else if(p.isExportAssignment(n))t.push({name:this.getExportAssignmentName(n),type:"unknown",isDefault:!0,isReexport:!1,sourceModule:void 0});else if(p.isFunctionDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"function",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(p.isClassDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"class",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(p.isVariableStatement(n)&&this.hasExportModifier(n))for(let r of n.declarationList.declarations)p.isIdentifier(r.name)&&t.push({name:r.name.text,type:"variable",isDefault:!1,isReexport:!1,sourceModule:void 0});else p.isInterfaceDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"interface",isDefault:!1,isReexport:!1,sourceModule:void 0}):p.isTypeAliasDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"type",isDefault:!1,isReexport:!1,sourceModule:void 0}):p.isEnumDeclaration(n)&&this.hasExportModifier(n)&&t.push({name:n.name.text,type:"enum",isDefault:!1,isReexport:!1,sourceModule:void 0});p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractInterfaces(e){let t=[],s=n=>{p.isInterfaceDeclaration(n)&&t.push(this.extractInterfaceDeclaration(n,e)),p.forEachChild(n,s)};return p.forEachChild(e,s),t}extractEntities(e,t){let s=this.parseFile(t,e),n=[],r=this.extractFunctions(s);for(let a of r)n.push({name:a.name,type:"function",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:a.isAsync,isExported:a.isExported,parameters:a.parameters,returnType:a.returnType});let o=this.extractClasses(s);for(let a of o)n.push({name:a.name,type:"class",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported,extends:a.extends,implements:a.implements});let i=this.extractInterfaces(s);for(let a of i)n.push({name:a.name,type:"interface",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported});return n}getScriptKind(e){return e.endsWith(".tsx")?p.ScriptKind.TSX:e.endsWith(".ts")?p.ScriptKind.TS:e.endsWith(".jsx")?p.ScriptKind.JSX:e.endsWith(".js")?p.ScriptKind.JS:p.ScriptKind.TS}extractFunctionDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:e.name?.text??"anonymous",parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,startLine:s+1,endLine:n+1,isAsync:this.hasAsyncModifier(e),isExported:this.hasExportModifier(e),isGenerator:!!e.asteriskToken,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractArrowFunctions(e,t,s){for(let n of e.declarationList.declarations)if(p.isIdentifier(n.name)&&n.initializer&&p.isArrowFunction(n.initializer)){let r=n.initializer,{line:o}=t.getLineAndCharacterOfPosition(e.getStart()),{line:i}=t.getLineAndCharacterOfPosition(e.getEnd());s.push({name:n.name.text,parameters:this.extractParameters(r.parameters),returnType:r.type?r.type.getText(t):void 0,startLine:o+1,endLine:i+1,isAsync:this.hasAsyncModifier(r),isExported:this.hasExportModifier(e),isGenerator:!1,typeParameters:this.extractTypeParameters(r.typeParameters)})}}extractClassDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),r=[],o=[];for(let c of e.members)p.isMethodDeclaration(c)&&c.name?r.push(this.extractMethodDeclaration(c,t)):p.isPropertyDeclaration(c)&&c.name?o.push(this.extractPropertyDeclaration(c,t)):p.isConstructorDeclaration(c)&&(r.push(this.extractConstructor(c,t)),this.extractParameterProperties(c,o,t));let i,a=[];if(e.heritageClauses){for(let c of e.heritageClauses)if(c.token===p.SyntaxKind.ExtendsKeyword)i=c.types[0]?.expression.getText(t);else if(c.token===p.SyntaxKind.ImplementsKeyword)for(let l of c.types)a.push(l.expression.getText(t))}return{name:e.name?.text??"anonymous",methods:r,properties:o,extends:i,implements:a,isAbstract:this.hasAbstractModifier(e),isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractMethodDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:this.getPropertyName(e.name,t),parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,isAsync:this.hasAsyncModifier(e),isStatic:this.hasStaticModifier(e),isAbstract:this.hasAbstractModifier(e),visibility:this.getVisibility(e),startLine:s+1,endLine:n+1}}extractConstructor(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:"constructor",parameters:this.extractParameters(e.parameters),returnType:void 0,isAsync:!1,isStatic:!1,isAbstract:!1,visibility:"public",startLine:s+1,endLine:n+1}}extractParameterProperties(e,t,s){for(let n of e.parameters)this.isParameterProperty(n)&&t.push({name:p.isIdentifier(n.name)?n.name.text:n.name.getText(s),type:n.type?n.type.getText(s):void 0,isStatic:!1,isReadonly:this.hasReadonlyModifier(n),visibility:this.getVisibility(n),hasInitializer:!!n.initializer})}isParameterProperty(e){return!!e.modifiers?.some(t=>t.kind===p.SyntaxKind.PublicKeyword||t.kind===p.SyntaxKind.PrivateKeyword||t.kind===p.SyntaxKind.ProtectedKeyword||t.kind===p.SyntaxKind.ReadonlyKeyword)}extractPropertyDeclaration(e,t){return{name:this.getPropertyName(e.name,t),type:e.type?e.type.getText(t):void 0,isStatic:this.hasStaticModifier(e),isReadonly:this.hasReadonlyModifier(e),visibility:this.getVisibility(e),hasInitializer:!!e.initializer}}extractImportDeclaration(e){let t=e.moduleSpecifier.text,s=[],n,r,o=e.importClause?.isTypeOnly??!1;if(e.importClause&&(e.importClause.name&&(n=e.importClause.name.text),e.importClause.namedBindings)){if(p.isNamespaceImport(e.importClause.namedBindings))r=e.importClause.namedBindings.name.text;else if(p.isNamedImports(e.importClause.namedBindings))for(let i of e.importClause.namedBindings.elements)s.push({name:i.propertyName?.text??i.name.text,alias:i.propertyName?i.name.text:void 0})}return{module:t,namedImports:s,defaultImport:n,namespaceImport:r,isTypeOnly:o}}extractExportDeclaration(e,t){let s=e.moduleSpecifier?e.moduleSpecifier.text:void 0;if(e.exportClause&&p.isNamedExports(e.exportClause))for(let n of e.exportClause.elements)t.push({name:n.name.text,type:"unknown",isDefault:!1,isReexport:!!s,sourceModule:s});else!e.exportClause&&s&&t.push({name:"*",type:"unknown",isDefault:!1,isReexport:!0,sourceModule:s})}extractInterfaceDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),r=[],o=[];for(let a of e.members)p.isPropertySignature(a)&&a.name?r.push({name:this.getPropertyName(a.name,t),type:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken,isReadonly:this.hasReadonlyModifier(a)}):p.isMethodSignature(a)&&a.name&&o.push({name:this.getPropertyName(a.name,t),parameters:this.extractParameters(a.parameters),returnType:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken});let i=[];if(e.heritageClauses){for(let a of e.heritageClauses)if(a.token===p.SyntaxKind.ExtendsKeyword)for(let c of a.types)i.push(c.expression.getText(t))}return{name:e.name.text,properties:r,methods:o,extends:i,isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractParameters(e){return e.map(t=>{let s=t.getSourceFile();return{name:p.isIdentifier(t.name)?t.name.text:t.name.getText(s),type:t.type?t.type.getText(s):void 0,isOptional:!!t.questionToken||!!t.initializer,isRest:!!t.dotDotDotToken,defaultValue:t.initializer?t.initializer.getText(s):void 0}})}extractTypeParameters(e){return e?e.map(t=>t.name.text):[]}getPropertyName(e,t){return p.isIdentifier(e)||p.isStringLiteral(e)||p.isNumericLiteral(e)?e.text:e.getText(t)}getExportAssignmentName(e){return p.isIdentifier(e.expression)?e.expression.text:"default"}hasExportModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.ExportKeyword)}hasDefaultModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.DefaultKeyword)}hasAsyncModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.AsyncKeyword)}hasStaticModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.StaticKeyword)}hasAbstractModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.AbstractKeyword)}hasReadonlyModifier(e){return p.canHaveModifiers(e)&&!!p.getModifiers(e)?.some(t=>t.kind===p.SyntaxKind.ReadonlyKeyword)}getVisibility(e){if(!p.canHaveModifiers(e))return"public";let t=p.getModifiers(e);return t?t.some(s=>s.kind===p.SyntaxKind.PrivateKeyword)?"private":t.some(s=>s.kind===p.SyntaxKind.ProtectedKeyword)?"protected":"public":"public"}},Me=new F,q=class{language="typescript";supportedExtensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];parser=new F;async parseFile(e,t){let s=this.parser.parseFile(t,e),n=this.parser.extractFunctions(s),r=this.parser.extractClasses(s),o=this.parser.extractImports(s);return{functions:n.map(i=>this.mapFunction(i)),classes:r.map(i=>this.mapClass(i)),imports:o.map(i=>this.mapImport(i)),language:t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":"typescript",filePath:t}}mapFunction(e){return{name:e.name,parameters:e.parameters.map(t=>({name:t.name,type:t.type,isOptional:t.isOptional,defaultValue:t.defaultValue})),returnType:e.returnType,isAsync:e.isAsync,isPublic:e.isExported,complexity:1,decorators:[],genericParams:e.typeParameters,startLine:e.startLine,endLine:e.endLine}}mapClass(e){return{name:e.name,methods:e.methods.map(t=>({name:t.name,parameters:t.parameters.map(s=>({name:s.name,type:s.type,isOptional:s.isOptional,defaultValue:s.defaultValue})),returnType:t.returnType,isAsync:t.isAsync,isPublic:t.visibility==="public",complexity:1,decorators:[],genericParams:[],startLine:t.startLine,endLine:t.endLine})),properties:e.properties.map(t=>this.mapProperty(t)),isPublic:e.isExported,implements:e.implements,extends:e.extends,decorators:[],startLine:e.startLine,endLine:e.endLine}}mapProperty(e){return{name:e.name,type:e.type,isPublic:e.visibility==="public",isReadonly:e.isReadonly}}mapImport(e){return{module:e.module,namedImports:e.namedImports.map(t=>t.alias||t.name),isTypeOnly:e.isTypeOnly}}},Se=new q;fe();var E=1e3;function I(h){let e=h.split(`
3
3
  `),t=[],s=[],n="",r=0,o=0,i=0,a=0;for(let c=0;c<e.length;c++){let l=e[c],d=l.trim();if(d===""||d.startsWith("//")||d.startsWith("#")||d.startsWith("*")){if(n){n+=" "+d;continue}t.push(l),s.push(c+1);continue}n||(r=c+1),n=n?n+" "+d:l;for(let u of d)u==="("?o++:u===")"?o=Math.max(0,o-1):u==="<"?i++:u===">"?i=Math.max(0,i-1):u==="["?a++:u==="]"&&(a=Math.max(0,a-1));o===0&&i===0&&a===0&&(t.push(n),s.push(r),n="")}return n&&(t.push(n),s.push(r)),{logicalLines:t,lineMap:s}}function G(h,e,t="<",s=">"){if(h[e]!==t)return;let n=1,r=e+1;for(;r<h.length&&n>0;)h[r]===t?n++:h[r]===s&&n--,r++;if(n===0)return h.substring(e+1,r-1)}function R(h,e,t){let s=[];for(let n=e-1;n>=0;n--){let r=h[n].trim();if(r.startsWith(t))s.unshift(r);else{if(r===""||r.startsWith("//")||r.startsWith("*")||r.startsWith("#"))continue;break}}return s}function S(h){let e=[],t=0,s="";for(let n of h)n==="<"||n==="("?t++:(n===">"||n===")")&&t--,n===","&&t===0?(e.push(s.trim()),s=""):s+=n;return s.trim()&&e.push(s.trim()),e}function re(h){let e=0,t=!1,s="";for(let n=0;n<h.length;n++){let r=h[n];if(t){r===s&&h[n-1]!=="\\"&&(t=!1);continue}r==='"'||r==="'"||r==="`"?(t=!0,s=r):r==="{"?e++:r==="}"&&e--}return e}var H=class{language="python";supportedExtensions=[".py"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"python",filePath:t}}extractFunctions(e){let t=[],s=e.split(`
4
4
  `),{logicalLines:n,lineMap:r}=I(e),o=/^(\s*)(async\s+)?def\s+(\w+)\s*\(([^)]*)\)(?:\s*->\s*([^:]*\S))?\s*:/;for(let i=0;i<n.length;i++){if(n[i].length>E)continue;let a=n[i].match(o);if(a){let c=a[1].length,l=!!a[2],d=a[3],u=a[4],m=a[5]?.trim(),g=r[i]-1,f=g+1;for(let y=g+1;y<s.length;y++){let b=s[y];if(b.trim()===""||b.trim().startsWith("#"))continue;if((b.match(/^(\s*)/)?.[1].length??0)<=c&&b.trim()!==""){f=y;break}f=y+1}let x=R(s,g,"@");t.push({name:d,parameters:this.parseParams(u),returnType:m,isAsync:l,isPublic:!d.startsWith("_"),complexity:1,decorators:x,genericParams:[],startLine:r[i],endLine:f})}}return t}extractClasses(e){let t=[],s=e.split(`
5
5
  `),{logicalLines:n,lineMap:r}=I(e),o=/^(\s*)class\s+(\w+)(?:\(([^)]*)\))?\s*:/;for(let i=0;i<n.length;i++){let a=n[i].match(o);if(a){let c=a[1].length,l=a[2],d=a[3]?a[3].split(",").map(y=>y.trim()):[],u=r[i]-1,m=u+1;for(let y=u+1;y<s.length;y++){let b=s[y];if(b.trim()===""||b.trim().startsWith("#"))continue;if((b.match(/^(\s*)/)?.[1].length??0)<=c&&b.trim()!==""){m=y;break}m=y+1}let g=s.slice(u+1,m).join(`
@@ -20,7 +20,7 @@ import{a as ye}from"./chunk-FONTSK2O.js";import{c as oe,d as ce,e as fe}from"./c
20
20
  `),{logicalLines:n,lineMap:r}=I(e),o=/^\s*(public|private|protected|internal)?\s*(suspend)?\s*fun\s+(?:<[^{]*> +)?(\w+)\s*\(([^)]*)\)(?:\s*:\s*([^{=\s]+(?:\s+[^{=\s]+)*))?\s*/,i=0;for(let a=0;a<n.length;a++){let c=n[a];if(c.length>E){i+=(c.match(/\{/g)?.length??0)-(c.match(/\}/g)?.length??0);continue}let l=c.match(o);if(l&&i<=1){let d=l[1]||"public",u=!!l[2],m=l[3],g=l[4],f=l[5]?.trim();if(f&&f.includes("<")){let b=f.indexOf("<"),P=G(f,b);P!==void 0&&(f=f.substring(0,b)+"<"+P+">")}let x=r[a]-1,y=R(s,x,"@");t.push({name:m,parameters:this.parseParams(g),returnType:f,isAsync:u,isPublic:d==="public",complexity:1,decorators:y,genericParams:[],startLine:r[a],endLine:r[a]})}i+=re(c),i<0&&(i=0)}return t}extractClasses(e){let t=[],s=e.split(`
21
21
  `),{logicalLines:n,lineMap:r}=I(e),o=/^\s*(public|private|protected|internal)?\s*(data|sealed|abstract|open)?\s*class\s+(\w+)(?:<[^{]*>)?(?:\s*(?:\([^)]*\))?\s*:\s*([^{\s]+(?:\s+[^{\s]+)*))?\s*\{?/;for(let i=0;i<n.length;i++){if(n[i].length>E)continue;let a=n[i].match(o);if(a){let c=a[3],l=a[4]?a[4].split(",").map(m=>m.trim().split("(")[0].trim()):[],d=r[i]-1,u=R(s,d,"@");t.push({name:c,methods:[],properties:[],isPublic:(a[1]||"public")==="public",implements:l.slice(1),extends:l[0]||void 0,decorators:u,startLine:r[i],endLine:r[i]})}}return t}extractImports(e){let t=[],s=e.split(`
22
22
  `);for(let n of s){let r=n.match(/^\s*import\s+([^\s]+)/);r&&t.push({module:r[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){return e.trim()?S(e).map(t=>{let s=t.indexOf(":");if(s===-1)return{name:t.replace("val ","").replace("var ","").trim(),type:void 0,isOptional:!1,defaultValue:void 0};let n=t.substring(0,s).replace("val ","").replace("var ","").trim(),r=t.substring(s+1).trim(),o=r.indexOf("="),i=o>=0?r.substring(0,o).trim():r,a=o>=0;return{name:n,type:i,isOptional:a||i?.endsWith("?")||!1,defaultValue:void 0}}):[]}},te=class{language="dart";supportedExtensions=[".dart"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"dart",filePath:t}}extractFunctions(e){let t=[],{logicalLines:s,lineMap:n}=I(e),r=/^\s*([\w<>,.?]+(?:\s+[\w<>,.?]+)*)\s+(\w+)\s*\(([^)]*)\)(?:\s*(async))?\s*\{/;for(let o=0;o<s.length;o++){let i=s[o];if(i.includes(" class ")||i.length>E)continue;let a=i.match(r);if(a){let c=a[1].trim(),l=c;if(c&&c.includes("<")){let g=c.indexOf("<"),f=G(c,g);f!==void 0&&(l=c.substring(0,g)+"<"+f+">")}let d=a[2],u=a[3],m=!!a[4]||l.includes("Future");t.push({name:d,parameters:this.parseParams(u),returnType:l==="void"?void 0:l,isAsync:m,isPublic:!d.startsWith("_"),complexity:1,decorators:[],genericParams:[],startLine:n[o],endLine:n[o]})}}return t}extractClasses(e){let t=[],{logicalLines:s,lineMap:n}=I(e),r=/^\s*(abstract +)?class\s+(\w+)(?:<[^{]*>)?(?:\s+extends\s+(\w+))?(?:\s+(?:with|implements)\s+([^{\s]+(?:\s+[^{\s]+)*))?\s*\{/;for(let o=0;o<s.length;o++){if(s[o].length>E)continue;let i=s[o].match(r);if(i){let a=i[2],c=i[3],l=i[4]?i[4].split(",").map(d=>d.trim()):[];t.push({name:a,methods:[],properties:[],isPublic:!a.startsWith("_"),implements:l,extends:c,decorators:[],startLine:n[o],endLine:n[o]})}}return t}extractImports(e){let t=[],s=e.split(`
23
- `);for(let n of s){let r=n.match(/^\s*import\s+'([^']+)'/);r&&t.push({module:r[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){if(!e.trim())return[];let t=e.replace(/[{}[\]]/g,"");return S(t).map(s=>s.trim()).filter(s=>s).map(s=>{let n=s.replace("required ","").trim().split(/\s+/),r=n[n.length-1]||"",o=n.slice(0,-1).join(" ")||void 0;return{name:r,type:o,isOptional:s.includes("?")||s.includes("{"),defaultValue:void 0}})}},$=ce("ParserRegistry"),de=["python","java","csharp","rust","swift"],se=class h{language;supportedExtensions;wasmParser;regexParser;wasmFailCount=0;static MAX_WASM_RETRIES=3;constructor(e,t){this.wasmParser=e,this.regexParser=t,this.language=e.language,this.supportedExtensions=e.supportedExtensions}async parseFile(e,t){if(this.wasmFailCount<h.MAX_WASM_RETRIES)try{return await this.wasmParser.parseFile(e,t)}catch(s){this.wasmFailCount++;let n=s instanceof Error?s.message:String(s),r=this.wasmFailCount>=h.MAX_WASM_RETRIES;$.warn(`[${this.language}] tree-sitter WASM parser failed (attempt ${this.wasmFailCount}/${h.MAX_WASM_RETRIES}): ${n}. Falling back to regex parser (~97-98% accuracy). `+(r?"Set AQE_PARSER_REGEX_ONLY=1 to silence this warning.":"Will retry WASM on next parse."))}return this.regexParser.parseFile(e,t)}},ne=class{parsers=new Map;_wasmInitPromise=null;constructor(){this.register(new H),this.register(new J),this.register(new Q),this.register(new X),this.register(new Y),this.register(new Z),this.register(new ee),this.register(new te),this._wasmInitPromise=this._tryLoadWasmParsers()}async _tryLoadWasmParsers(){try{let e=await import("./tree-sitter-wasm-parser-SUSDXGOP.js");if(!e.isWasmAvailable()){$.info("tree-sitter WASM parsers disabled or unavailable. Using regex parsers (~97-98% accuracy). Set AQE_PARSER_REGEX_ONLY=0 or ensure web-tree-sitter is installed to enable WASM.");return}let t=e.createWasmParsers();for(let s of de){let n=t.get(s),r=this.parsers.get(s);n&&r&&this.parsers.set(s,new se(n,r))}$.info("tree-sitter WASM parsers available for: "+de.join(", "))}catch{$.info("tree-sitter WASM parser module not available. Using regex parsers for all languages.")}}register(e){this.parsers.set(e.language,e)}getParser(e){return this.parsers.get(e)}async parseFile(e,t,s){this._wasmInitPromise&&(await this._wasmInitPromise,this._wasmInitPromise=null);let n=this.parsers.get(s);if(n)return n.parseFile(e,t)}getSupportedLanguages(){return Array.from(this.parsers.keys())}supportsLanguage(e){return this.parsers.has(e)}},De=new ne;import*as M from"node:fs/promises";import*as C from"node:path";var xe=[/\.\./,/%2e%2e/i,/%252e%252e/i,/\.\.%2f/i,/%2f\.\./i,/\.\.%5c/i,/\.\.\\/,/%c0%ae/i,/%c0%2f/i,/%c1%9c/i,/\0/,/%00/i],ve=[/^\/etc\//i,/^\/proc\//i,/^\/sys\//i,/^\/dev\//i,/^\/root\//i,/^\/home\/.+\/\./i,/^[A-Z]:\\Windows/i,/^[A-Z]:\\System/i,/^[A-Z]:\\Users\\.+\\AppData/i],ie=class{name="path-traversal";getRiskLevel(){return"critical"}validate(e,t={}){let{basePath:s="",allowAbsolute:n=!1,allowedExtensions:r=[],deniedExtensions:o=[".exe",".bat",".cmd",".sh",".ps1",".dll",".so"],maxDepth:i=10,maxLength:a=4096}=t;if(e.length>a)return{valid:!1,error:`Path exceeds maximum length of ${a}`,riskLevel:"medium"};for(let g of xe)if(g.test(e))return{valid:!1,error:"Path traversal attempt detected",riskLevel:"critical"};if(!n&&(e.startsWith("/")||/^[A-Z]:/i.test(e)))return{valid:!1,error:"Absolute paths are not allowed",riskLevel:"high"};for(let g of ve)if(g.test(e))return{valid:!1,error:"Access to system paths is not allowed",riskLevel:"critical"};let c=this.normalizePath(e);if(c.includes(".."))return{valid:!1,error:"Path traversal detected after normalization",riskLevel:"critical"};if(c.split("/").filter(Boolean).length>i)return{valid:!1,error:`Path depth exceeds maximum of ${i}`,riskLevel:"low"};let d=this.getExtension(c);if(d){let g=`.${d.toLowerCase()}`,f=d.toLowerCase();if(o.length>0&&o.some(y=>y.toLowerCase()===g||y.toLowerCase()===f))return{valid:!1,error:`File extension '${d}' is not allowed`,riskLevel:"high"};if(r.length>0&&!r.some(y=>y.toLowerCase()===g||y.toLowerCase()===f))return{valid:!1,error:`File extension '${d}' is not in allowed list`,riskLevel:"medium"}}let u=s?this.joinPathsAbsolute(s,c):c,m=s.startsWith("/")?`/${this.normalizePath(s)}`:this.normalizePath(s);return s&&!u.startsWith(m)?{valid:!1,error:"Path escapes base directory",riskLevel:"critical"}:{valid:!0,normalizedPath:u,riskLevel:"none"}}normalizePath(e){let t=e.replace(/\\/g,"/");t=t.replace(/\/+/g,"/");let s=t.split("/"),n=[];for(let r of s)r==="."||r===""||(r===".."?n.length>0&&n[n.length-1]!==".."&&n.pop():n.push(r));return n.join("/")}joinPaths(...e){return e.length===0?"":e.map(t=>t.replace(/^\/+/,"").replace(/\/+$/,"")).filter(Boolean).join("/")}joinPathsAbsolute(...e){if(e.length===0)return"";let t=e[0].startsWith("/"),s=e.map(n=>{for(;n.startsWith("/");)n=n.slice(1);for(;n.endsWith("/");)n=n.slice(0,-1);return n}).filter(Boolean).join("/");return t?`/${s}`:s}getExtension(e){let t=e.match(/\.([^./\\]+)$/);return t?t[1]:null}},Ee=new ie,pe=(h,e)=>Ee.validate(h,e);le();var A=class extends Error{constructor(t,s,n,r){super(t);this.filePath=s;this.code=n;this.cause=r;this.name="FileReadError"}},z=class extends Error{constructor(t,s,n){super(t);this.filePath=s;this.cause=n;this.name="JsonParseError"}},T=class extends Error{constructor(t,s,n){super(`Path traversal detected: ${s.join(", ")}`);this.requestedPath=t;this.issues=s;this.riskLevel=n;this.name="PathTraversalError"}},ae=class{constructor(e,t){this.maxSize=e;this.ttlMs=t}cache=new Map;accessOrder=[];get(e){let t=this.cache.get(e);if(t){if(Date.now()-t.timestamp>this.ttlMs){this.delete(e);return}return this.updateAccessOrder(e),t.value}}set(e,t,s){for(this.cache.has(e)&&this.delete(e);this.cache.size>=this.maxSize&&this.accessOrder.length>0;){let n=this.accessOrder.shift();n&&this.cache.delete(n)}this.cache.set(e,{value:t,timestamp:Date.now(),size:s}),this.accessOrder.push(e)}delete(e){let t=this.cache.delete(e);if(t){let s=this.accessOrder.indexOf(e);s>-1&&this.accessOrder.splice(s,1)}return t}clear(){this.cache.clear(),this.accessOrder=[]}get size(){return this.cache.size}get totalBytes(){let e=0;return this.cache.forEach(t=>{e+=t.size}),e}updateAccessOrder(e){let t=this.accessOrder.indexOf(e);t>-1&&(this.accessOrder.splice(t,1),this.accessOrder.push(e))}prune(){let e=Date.now(),t=0,s=[];return this.cache.forEach((n,r)=>{e-n.timestamp>this.ttlMs&&s.push(r)}),s.forEach(n=>{this.delete(n),t++}),t}};function Ie(h){let e="",t=0;for(;t<h.length;){let s=h[t],n=h[t+1];s==="*"&&n==="*"?h[t+2]==="/"?(e+="(?:.*/)?",t+=3):(e+=".*",t+=2):s==="*"?(e+="[^/]*",t++):s==="?"?(e+="[^/]",t++):".+^${}()|[]\\".includes(s)?(e+="\\"+s,t++):(e+=s,t++)}return new RegExp("^"+e+"$")}async function ue(h,e,t,s){try{let n=await M.readdir(h,{withFileTypes:!0});for(let r of n){let o=C.join(h,r.name),i=C.relative(s,o);if(r.isDirectory())r.name!=="node_modules"&&!r.name.startsWith(".")&&await ue(o,e,t,s);else if(r.isFile()){let a=i.replace(/\\/g,"/");e.test(a)&&t.push(o)}}}catch(n){console.debug("[FileReader] Directory read error:",n instanceof Error?n.message:n)}}var k=class{basePath;cache;enableCache;stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:0,cacheEntries:0};constructor(e={}){this.basePath=e.basePath??process.cwd(),this.enableCache=e.enableCache??!0,this.cache=new ae(e.maxCacheSize??100,e.cacheTtlMs??300*1e3)}resolvePath(e){let t=C.isAbsolute(e),s=pe(e,{basePath:t?"":this.basePath,allowAbsolute:!0,deniedExtensions:[".exe",".bat",".cmd",".ps1",".dll",".so"]});if(!s.valid)throw new T(e,[s.error||"Path validation failed"],s.riskLevel);if(t&&this.basePath){let n=C.resolve(this.basePath),r=C.resolve(e);if(!r.startsWith(n))throw new T(e,["Path escapes base directory"],"critical");return r}return s.normalizedPath?s.normalizedPath:t?e:C.resolve(this.basePath,e)}async readFile(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}if(this.stats.totalReads++,this.enableCache){let s=this.cache.get(t);if(s!==void 0)return this.stats.cacheHits++,this.updateCacheStats(),w(s);this.stats.cacheMisses++}try{let s=await M.readFile(t,"utf-8");return this.enableCache&&(this.cache.set(t,s,Buffer.byteLength(s,"utf-8")),this.updateCacheStats()),w(s)}catch(s){let n=s,r;switch(n.code){case"ENOENT":r="File not found: "+t;break;case"EACCES":r="Permission denied: "+t;break;case"EISDIR":r="Path is a directory: "+t;break;default:r="Failed to read file: "+t}return L(new A(r,t,n.code,n))}}async readJSON(e){let t=await this.readFile(e);if(!t.success)return t;try{let s=N(t.value);return w(s)}catch(s){let n=s,r=e;try{r=this.resolvePath(e)}catch{}return L(new z("Invalid JSON in file: "+r+" - "+n.message,r,n))}}async fileExists(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}try{return await M.access(t,M.constants.F_OK),w(!0)}catch(s){let n=s;return n.code==="ENOENT"?w(!1):L(new A("Cannot check file existence: "+t,t,n.code,n))}}async listFiles(e,t){let s;try{s=t?this.resolvePath(t):this.basePath}catch(n){if(n instanceof T)return L(n);throw n}try{if(!(await M.stat(s)).isDirectory())return L(new A("Base path is not a directory: "+s,s,"ENOTDIR"));let r=Ie(e),o=[];return await ue(s,r,o,s),o.sort(),w(o)}catch(n){let r=n;return L(new A("Failed to list files in: "+s,s,r.code,r))}}invalidateCache(e){let t=this.resolvePath(e);this.cache.delete(t),this.updateCacheStats()}clearCache(){this.cache.clear(),this.updateCacheStats()}pruneCache(){let e=this.cache.prune();return this.updateCacheStats(),e}getStats(){return{...this.stats}}resetStats(){this.stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:this.cache.totalBytes,cacheEntries:this.cache.size}}updateCacheStats(){this.stats.cacheSize=this.cache.totalBytes,this.stats.cacheEntries=this.cache.size}};V();var v={MODEL:"all-MiniLM-L6-v2",DIMENSIONS:384,CONTEXT_WINDOW:8192,BATCH_SIZE:100,MAX_RETRIES:3,RETRY_DELAY_MS:1e3,TIMEOUT_MS:3e4,DEFAULT_OLLAMA_URL:"http://localhost:11434"};var K=class{baseUrl;maxRetries;retryDelayMs;timeoutMs;constructor(e=v.DEFAULT_OLLAMA_URL,t=v.MAX_RETRIES,s=v.RETRY_DELAY_MS,n=v.TIMEOUT_MS){this.baseUrl=e.replace(/\/$/,""),this.maxRetries=t,this.retryDelayMs=s,this.timeoutMs=n}async healthCheck(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);if(!e.ok)return!1;let t=await e.json();return t.models?t.models.some(s=>s.name?.startsWith(v.MODEL)||s.model?.startsWith(v.MODEL)):!1}catch{return!1}}async generateEmbedding(e){let t={model:v.MODEL,prompt:e},s=null;for(let n=0;n<this.maxRetries;n++)try{let r=await this.fetchWithTimeout(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},this.timeoutMs);if(!r.ok){let i=await r.text();throw new Error(`Ollama API error (${r.status}): ${i}`)}let o=await r.json();if(o.embedding.length!==v.DIMENSIONS)throw new Error(`Invalid embedding dimensions: expected ${v.DIMENSIONS}, got ${o.embedding.length}`);return o.embedding}catch(r){if(s=D(r),s.message.includes("Invalid embedding dimensions"))throw s;if(n<this.maxRetries-1){let o=this.retryDelayMs*Math.pow(2,n);await this.sleep(o)}}throw new Error(`Failed to generate embedding after ${this.maxRetries} attempts: ${s?.message}`)}async fetchWithTimeout(e,t,s){let n=new AbortController,r=setTimeout(()=>n.abort(),s);try{return await fetch(e,{...t,signal:n.signal})}finally{clearTimeout(r)}}sleep(e){return new Promise(t=>setTimeout(t,e))}async getServerInfo(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);return e.ok?await e.json():null}catch{return null}}async ensureModelAvailable(){if(!await this.healthCheck())throw new Error(`Ollama model '${v.MODEL}' is not available. Please run: ollama pull ${v.MODEL}`)}};import{createHash as Pe}from"crypto";var U=class{cache;maxSize;hits;misses;constructor(e=1e4){this.cache=new Map,this.maxSize=e,this.hits=0,this.misses=0}hashContent(e,t){return Pe("sha256").update(`${t}:${e}`).digest("hex")}get(e,t){let s=this.hashContent(e,t),n=this.cache.get(s);return n?(this.hits++,this.cache.delete(s),this.cache.set(s,n),n.embedding):(this.misses++,null)}set(e,t,s){let n=this.hashContent(e,t);if(this.cache.size>=this.maxSize&&!this.cache.has(n)){let o=this.cache.keys().next().value;o&&this.cache.delete(o)}let r={embedding:s,timestamp:Date.now(),model:t};this.cache.set(n,r)}has(e,t){let s=this.hashContent(e,t);return this.cache.has(s)}getStats(){let e=this.hits+this.misses,t=e>0?this.hits/e:0;return{size:this.cache.size,hitRate:t,hits:this.hits,misses:this.misses}}clear(){this.cache.clear(),this.hits=0,this.misses=0}evictOlderThan(e){let s=Date.now()-e,n=0;for(let[r,o]of this.cache.entries())o.timestamp<s&&(this.cache.delete(r),n++);return n}getMemoryUsageEstimate(){return this.cache.size*3172}export(){return Array.from(this.cache.entries()).map(([e,t])=>({key:e,entry:t}))}import(e){this.cache.clear();for(let{key:t,entry:s}of e)this.cache.size<this.maxSize&&this.cache.set(t,s)}};V();var _=class{client;cache;batchSize;enableFallback;ollamaAvailable=null;constructor(e={}){this.client=new K(e.ollamaBaseUrl),this.cache=e.cache??new U(e.maxCacheSize),this.batchSize=e.batchSize??v.BATCH_SIZE,this.enableFallback=e.enableFallback??!0}async embed(e){let t=this.cache.get(e,v.MODEL);if(t)return t;let s;if(await this.isOllamaAvailable())s=await this.client.generateEmbedding(e);else if(this.enableFallback)s=this.generatePseudoEmbedding(e);else throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);return this.cache.set(e,v.MODEL,s),s}formatForEmbedding(e){let t=[];e.language&&t.push(e.language),e.type&&t.push(e.type),e.name&&t.push(e.name);let s=t.length>0?`${t.join(" ")}: `:"",n=v.CONTEXT_WINDOW*4,r=e.content.trim();if(s.length+r.length>n){let o=n-s.length-3;r=r.substring(0,o)+"..."}return s+r}async embedBatch(e){let t=[];for(let s of e){let n=await this.embed(s);t.push(n)}return t}async embedCodeChunks(e,t){let s=Date.now(),n=[],r=0,o=0,i=await this.isOllamaAvailable();if(i)await this.client.ensureModelAvailable();else if(!this.enableFallback)throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);for(let c=0;c<e.length;c+=this.batchSize){let l=e.slice(c,Math.min(c+this.batchSize,e.length)),d=await this.processBatch(l,i);n.push(...d);for(let u of d)u.cached?r++:o++;if(t){let u=c+l.length,m=e.length,f=(Date.now()-s)/u,y=(m-u)*f;t({current:u,total:m,percentage:u/m*100,estimatedTimeRemainingMs:y})}}let a=Date.now()-s;return{results:n,stats:{totalChunks:e.length,cachedHits:r,computedNew:o,totalTimeMs:a,avgTimePerChunk:a/e.length}}}async processBatch(e,t){let s=[],n=e.map(async o=>{let i=this.formatForEmbedding(o),a=Date.now(),c=this.cache.get(i,v.MODEL);if(c)return{chunkId:o.id,embedding:c,model:v.MODEL,cached:!0,computeTimeMs:Date.now()-a};try{let l;return t?l=await this.client.generateEmbedding(i):l=this.generatePseudoEmbedding(i),this.cache.set(i,v.MODEL,l),{chunkId:o.id,embedding:l,model:t?v.MODEL:"pseudo-embedding",cached:!1,computeTimeMs:Date.now()-a}}catch(l){throw new Error(`Failed to generate embedding for chunk ${o.id}: ${j(l)}`)}}),r=await Promise.all(n);return s.push(...r),s}async isOllamaAvailable(){return this.ollamaAvailable!==null?this.ollamaAvailable:(this.ollamaAvailable=await this.client.healthCheck(),this.ollamaAvailable)}resetOllamaCheck(){this.ollamaAvailable=null}generatePseudoEmbedding(e){let t=new Array(v.DIMENSIONS).fill(0),s=e.split(/\s+|[^\w]+/).filter(o=>o.length>0);for(let o=0;o<s.length;o++){let i=s[o];for(let a=0;a<i.length&&a<t.length;a++)t[(o+a)%t.length]+=i.charCodeAt(a)/1e3}let n=[[/class\s+\w+/,0],[/function\s+\w+/,1],[/async\s+|await\s+|Promise/,2],[/interface\s+\w+/,3],[/export\s+/,4],[/import\s+/,5],[/try\s*{/,6],[/\.(map|filter|reduce)\(/,7]];for(let[o,i]of n)o.test(e)&&(t[i]+=.5);let r=Math.sqrt(t.reduce((o,i)=>o+i*i,0))||1;return t.map(o=>o/r)}clearCache(){this.cache.clear()}getCacheStats(){return this.cache.getStats()}async healthCheck(){return await this.client.healthCheck()}async getServerInfo(){return await this.client.getServerInfo()}getDimensions(){return v.DIMENSIONS}getConfig(){return{model:v.MODEL,dimensions:v.DIMENSIONS,contextWindow:v.CONTEXT_WINDOW,batchSize:this.batchSize,maxRetries:v.MAX_RETRIES,enableFallback:this.enableFallback}}};V();le();var we={maxNodes:1e5,maxEdgesPerNode:500,namespace:"code-intelligence:kg",enableVectorEmbeddings:!0,embeddingDimension:384,enableLLMExtraction:!0,llmModelTier:2,llmMaxTokens:2048},me=oe.create("code-intelligence/knowledge-graph"),he=class{config;memory;nodeCache=new Map;edgeIndex=new Map;tsParser;fileReader;embedder;llmRouter;constructor(e,t={}){this.config={...we,...t},this.isKnowledgeGraphDependencies(e)?(this.memory=e.memory,this.llmRouter=e.llmRouter):(this.memory=e,this.llmRouter=void 0),this.tsParser=new F,this.fileReader=new k,this.embedder=new _({enableFallback:!0})}isKnowledgeGraphDependencies(e){return e.memory!==void 0}async index(e){let t=Date.now(),s=[],n=0,r=0;try{let{paths:o,incremental:i=!1,includeTests:a=!0,languages:c}=e;i||await this.clear();for(let d of o)try{if(c&&c.length>0){let m=this.getFileExtension(d);if(!this.matchesLanguage(m,c))continue}if(!a&&this.isTestFile(d))continue;let u=await this.indexFile(d);n+=u.nodes,r+=u.edges}catch(u){s.push({file:d,error:j(u)})}let l=Date.now()-t;return await this.storeIndexMetadata({filesIndexed:o.length-s.length,nodesCreated:n,edgesCreated:r,duration:l,indexedAt:new Date().toISOString()}),w({filesIndexed:o.length-s.length,nodesCreated:n,edgesCreated:r,duration:l,errors:s})}catch(o){return L(D(o))}}async query(e){try{let{query:t,type:s,limit:n=100}=e;return s==="cypher"?this.executeCypherQuery(t,n):this.executeNaturalLanguageQuery(t,n)}catch(t){return L(D(t))}}async mapDependencies(e){try{let{files:t,direction:s,depth:n=3}=e,r=[],o=[],i=new Set,a=[];for(let l of t)await this.traverseDependencies(l,s,n,i,r,o,[],a);let c=this.calculateDependencyMetrics(r,o);return w({nodes:r,edges:o,cycles:a,metrics:c})}catch(t){return L(D(t))}}async getNode(e){if(this.nodeCache.has(e))return this.nodeCache.get(e);let t=`${this.config.namespace}:node:${e}`,s=await this.memory.get(t);return s&&this.nodeCache.set(e,s),s}async getEdges(e,t){let s=[],n=this.edgeIndex.get(e);if(n)return this.filterEdgesByDirection(n,e,t);let r=`${this.config.namespace}:edge:*`,o=await this.memory.search(r,this.config.maxEdgesPerNode*2);for(let i of o){let a=await this.memory.get(i);a&&(t!=="outgoing"&&a.target===e||t!=="incoming"&&a.source===e)&&s.push(a)}return s}async clear(){this.nodeCache.clear(),this.edgeIndex.clear()}isLLMExtractionAvailable(){return this.config.enableLLMExtraction===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){case 1:return"claude-3-5-haiku-20241022";case 2:return"claude-sonnet-4-20250514";case 3:return"claude-sonnet-4-20250514";case 4:return"claude-opus-4-5-20251101";default:return"claude-sonnet-4-20250514"}}async extractRelationshipsWithLLM(e,t){if(!this.llmRouter)return{semanticRelationships:[],designPatterns:[],architecturalBoundaries:[],dependencyImpacts:[]};try{let s=this.buildRelationshipExtractionPrompt(e,t),n=this.getModelForTier(this.config.llmModelTier??2),r=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software architect analyzing code structure. Extract:
23
+ `);for(let n of s){let r=n.match(/^\s*import\s+'([^']+)'/);r&&t.push({module:r[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){if(!e.trim())return[];let t=e.replace(/[{}[\]]/g,"");return S(t).map(s=>s.trim()).filter(s=>s).map(s=>{let n=s.replace("required ","").trim().split(/\s+/),r=n[n.length-1]||"",o=n.slice(0,-1).join(" ")||void 0;return{name:r,type:o,isOptional:s.includes("?")||s.includes("{"),defaultValue:void 0}})}},$=ce("ParserRegistry"),de=["python","java","csharp","rust","swift"],se=class h{language;supportedExtensions;wasmParser;regexParser;wasmFailCount=0;static MAX_WASM_RETRIES=3;constructor(e,t){this.wasmParser=e,this.regexParser=t,this.language=e.language,this.supportedExtensions=e.supportedExtensions}async parseFile(e,t){if(this.wasmFailCount<h.MAX_WASM_RETRIES)try{return await this.wasmParser.parseFile(e,t)}catch(s){this.wasmFailCount++;let n=s instanceof Error?s.message:String(s),r=this.wasmFailCount>=h.MAX_WASM_RETRIES;$.warn(`[${this.language}] tree-sitter WASM parser failed (attempt ${this.wasmFailCount}/${h.MAX_WASM_RETRIES}): ${n}. Falling back to regex parser (~97-98% accuracy). `+(r?"Set AQE_PARSER_REGEX_ONLY=1 to silence this warning.":"Will retry WASM on next parse."))}return this.regexParser.parseFile(e,t)}},ne=class{parsers=new Map;_wasmInitPromise=null;constructor(){this.register(new H),this.register(new J),this.register(new Q),this.register(new X),this.register(new Y),this.register(new Z),this.register(new ee),this.register(new te),this._wasmInitPromise=this._tryLoadWasmParsers()}async _tryLoadWasmParsers(){try{let e=await import("./tree-sitter-wasm-parser-KTST5NWH.js");if(!e.isWasmAvailable()){$.info("tree-sitter WASM parsers disabled or unavailable. Using regex parsers (~97-98% accuracy). Set AQE_PARSER_REGEX_ONLY=0 or ensure web-tree-sitter is installed to enable WASM.");return}let t=e.createWasmParsers();for(let s of de){let n=t.get(s),r=this.parsers.get(s);n&&r&&this.parsers.set(s,new se(n,r))}$.info("tree-sitter WASM parsers available for: "+de.join(", "))}catch{$.info("tree-sitter WASM parser module not available. Using regex parsers for all languages.")}}register(e){this.parsers.set(e.language,e)}getParser(e){return this.parsers.get(e)}async parseFile(e,t,s){this._wasmInitPromise&&(await this._wasmInitPromise,this._wasmInitPromise=null);let n=this.parsers.get(s);if(n)return n.parseFile(e,t)}getSupportedLanguages(){return Array.from(this.parsers.keys())}supportsLanguage(e){return this.parsers.has(e)}},De=new ne;import*as M from"node:fs/promises";import*as C from"node:path";var xe=[/\.\./,/%2e%2e/i,/%252e%252e/i,/\.\.%2f/i,/%2f\.\./i,/\.\.%5c/i,/\.\.\\/,/%c0%ae/i,/%c0%2f/i,/%c1%9c/i,/\0/,/%00/i],ve=[/^\/etc\//i,/^\/proc\//i,/^\/sys\//i,/^\/dev\//i,/^\/root\//i,/^\/home\/.+\/\./i,/^[A-Z]:\\Windows/i,/^[A-Z]:\\System/i,/^[A-Z]:\\Users\\.+\\AppData/i],ie=class{name="path-traversal";getRiskLevel(){return"critical"}validate(e,t={}){let{basePath:s="",allowAbsolute:n=!1,allowedExtensions:r=[],deniedExtensions:o=[".exe",".bat",".cmd",".sh",".ps1",".dll",".so"],maxDepth:i=10,maxLength:a=4096}=t;if(e.length>a)return{valid:!1,error:`Path exceeds maximum length of ${a}`,riskLevel:"medium"};for(let g of xe)if(g.test(e))return{valid:!1,error:"Path traversal attempt detected",riskLevel:"critical"};if(!n&&(e.startsWith("/")||/^[A-Z]:/i.test(e)))return{valid:!1,error:"Absolute paths are not allowed",riskLevel:"high"};for(let g of ve)if(g.test(e))return{valid:!1,error:"Access to system paths is not allowed",riskLevel:"critical"};let c=this.normalizePath(e);if(c.includes(".."))return{valid:!1,error:"Path traversal detected after normalization",riskLevel:"critical"};if(c.split("/").filter(Boolean).length>i)return{valid:!1,error:`Path depth exceeds maximum of ${i}`,riskLevel:"low"};let d=this.getExtension(c);if(d){let g=`.${d.toLowerCase()}`,f=d.toLowerCase();if(o.length>0&&o.some(y=>y.toLowerCase()===g||y.toLowerCase()===f))return{valid:!1,error:`File extension '${d}' is not allowed`,riskLevel:"high"};if(r.length>0&&!r.some(y=>y.toLowerCase()===g||y.toLowerCase()===f))return{valid:!1,error:`File extension '${d}' is not in allowed list`,riskLevel:"medium"}}let u=s?this.joinPathsAbsolute(s,c):c,m=s.startsWith("/")?`/${this.normalizePath(s)}`:this.normalizePath(s);return s&&!u.startsWith(m)?{valid:!1,error:"Path escapes base directory",riskLevel:"critical"}:{valid:!0,normalizedPath:u,riskLevel:"none"}}normalizePath(e){let t=e.replace(/\\/g,"/");t=t.replace(/\/+/g,"/");let s=t.split("/"),n=[];for(let r of s)r==="."||r===""||(r===".."?n.length>0&&n[n.length-1]!==".."&&n.pop():n.push(r));return n.join("/")}joinPaths(...e){return e.length===0?"":e.map(t=>t.replace(/^\/+/,"").replace(/\/+$/,"")).filter(Boolean).join("/")}joinPathsAbsolute(...e){if(e.length===0)return"";let t=e[0].startsWith("/"),s=e.map(n=>{for(;n.startsWith("/");)n=n.slice(1);for(;n.endsWith("/");)n=n.slice(0,-1);return n}).filter(Boolean).join("/");return t?`/${s}`:s}getExtension(e){let t=e.match(/\.([^./\\]+)$/);return t?t[1]:null}},Ee=new ie,pe=(h,e)=>Ee.validate(h,e);le();var A=class extends Error{constructor(t,s,n,r){super(t);this.filePath=s;this.code=n;this.cause=r;this.name="FileReadError"}},z=class extends Error{constructor(t,s,n){super(t);this.filePath=s;this.cause=n;this.name="JsonParseError"}},T=class extends Error{constructor(t,s,n){super(`Path traversal detected: ${s.join(", ")}`);this.requestedPath=t;this.issues=s;this.riskLevel=n;this.name="PathTraversalError"}},ae=class{constructor(e,t){this.maxSize=e;this.ttlMs=t}cache=new Map;accessOrder=[];get(e){let t=this.cache.get(e);if(t){if(Date.now()-t.timestamp>this.ttlMs){this.delete(e);return}return this.updateAccessOrder(e),t.value}}set(e,t,s){for(this.cache.has(e)&&this.delete(e);this.cache.size>=this.maxSize&&this.accessOrder.length>0;){let n=this.accessOrder.shift();n&&this.cache.delete(n)}this.cache.set(e,{value:t,timestamp:Date.now(),size:s}),this.accessOrder.push(e)}delete(e){let t=this.cache.delete(e);if(t){let s=this.accessOrder.indexOf(e);s>-1&&this.accessOrder.splice(s,1)}return t}clear(){this.cache.clear(),this.accessOrder=[]}get size(){return this.cache.size}get totalBytes(){let e=0;return this.cache.forEach(t=>{e+=t.size}),e}updateAccessOrder(e){let t=this.accessOrder.indexOf(e);t>-1&&(this.accessOrder.splice(t,1),this.accessOrder.push(e))}prune(){let e=Date.now(),t=0,s=[];return this.cache.forEach((n,r)=>{e-n.timestamp>this.ttlMs&&s.push(r)}),s.forEach(n=>{this.delete(n),t++}),t}};function Ie(h){let e="",t=0;for(;t<h.length;){let s=h[t],n=h[t+1];s==="*"&&n==="*"?h[t+2]==="/"?(e+="(?:.*/)?",t+=3):(e+=".*",t+=2):s==="*"?(e+="[^/]*",t++):s==="?"?(e+="[^/]",t++):".+^${}()|[]\\".includes(s)?(e+="\\"+s,t++):(e+=s,t++)}return new RegExp("^"+e+"$")}async function ue(h,e,t,s){try{let n=await M.readdir(h,{withFileTypes:!0});for(let r of n){let o=C.join(h,r.name),i=C.relative(s,o);if(r.isDirectory())r.name!=="node_modules"&&!r.name.startsWith(".")&&await ue(o,e,t,s);else if(r.isFile()){let a=i.replace(/\\/g,"/");e.test(a)&&t.push(o)}}}catch(n){console.debug("[FileReader] Directory read error:",n instanceof Error?n.message:n)}}var k=class{basePath;cache;enableCache;stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:0,cacheEntries:0};constructor(e={}){this.basePath=e.basePath??process.cwd(),this.enableCache=e.enableCache??!0,this.cache=new ae(e.maxCacheSize??100,e.cacheTtlMs??300*1e3)}resolvePath(e){let t=C.isAbsolute(e),s=pe(e,{basePath:t?"":this.basePath,allowAbsolute:!0,deniedExtensions:[".exe",".bat",".cmd",".ps1",".dll",".so"]});if(!s.valid)throw new T(e,[s.error||"Path validation failed"],s.riskLevel);if(t&&this.basePath){let n=C.resolve(this.basePath),r=C.resolve(e);if(!r.startsWith(n))throw new T(e,["Path escapes base directory"],"critical");return r}return s.normalizedPath?s.normalizedPath:t?e:C.resolve(this.basePath,e)}async readFile(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}if(this.stats.totalReads++,this.enableCache){let s=this.cache.get(t);if(s!==void 0)return this.stats.cacheHits++,this.updateCacheStats(),w(s);this.stats.cacheMisses++}try{let s=await M.readFile(t,"utf-8");return this.enableCache&&(this.cache.set(t,s,Buffer.byteLength(s,"utf-8")),this.updateCacheStats()),w(s)}catch(s){let n=s,r;switch(n.code){case"ENOENT":r="File not found: "+t;break;case"EACCES":r="Permission denied: "+t;break;case"EISDIR":r="Path is a directory: "+t;break;default:r="Failed to read file: "+t}return L(new A(r,t,n.code,n))}}async readJSON(e){let t=await this.readFile(e);if(!t.success)return t;try{let s=N(t.value);return w(s)}catch(s){let n=s,r=e;try{r=this.resolvePath(e)}catch{}return L(new z("Invalid JSON in file: "+r+" - "+n.message,r,n))}}async fileExists(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}try{return await M.access(t,M.constants.F_OK),w(!0)}catch(s){let n=s;return n.code==="ENOENT"?w(!1):L(new A("Cannot check file existence: "+t,t,n.code,n))}}async listFiles(e,t){let s;try{s=t?this.resolvePath(t):this.basePath}catch(n){if(n instanceof T)return L(n);throw n}try{if(!(await M.stat(s)).isDirectory())return L(new A("Base path is not a directory: "+s,s,"ENOTDIR"));let r=Ie(e),o=[];return await ue(s,r,o,s),o.sort(),w(o)}catch(n){let r=n;return L(new A("Failed to list files in: "+s,s,r.code,r))}}invalidateCache(e){let t=this.resolvePath(e);this.cache.delete(t),this.updateCacheStats()}clearCache(){this.cache.clear(),this.updateCacheStats()}pruneCache(){let e=this.cache.prune();return this.updateCacheStats(),e}getStats(){return{...this.stats}}resetStats(){this.stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:this.cache.totalBytes,cacheEntries:this.cache.size}}updateCacheStats(){this.stats.cacheSize=this.cache.totalBytes,this.stats.cacheEntries=this.cache.size}};V();var v={MODEL:"all-MiniLM-L6-v2",DIMENSIONS:384,CONTEXT_WINDOW:8192,BATCH_SIZE:100,MAX_RETRIES:3,RETRY_DELAY_MS:1e3,TIMEOUT_MS:3e4,DEFAULT_OLLAMA_URL:"http://localhost:11434"};var K=class{baseUrl;maxRetries;retryDelayMs;timeoutMs;constructor(e=v.DEFAULT_OLLAMA_URL,t=v.MAX_RETRIES,s=v.RETRY_DELAY_MS,n=v.TIMEOUT_MS){this.baseUrl=e.replace(/\/$/,""),this.maxRetries=t,this.retryDelayMs=s,this.timeoutMs=n}async healthCheck(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);if(!e.ok)return!1;let t=await e.json();return t.models?t.models.some(s=>s.name?.startsWith(v.MODEL)||s.model?.startsWith(v.MODEL)):!1}catch{return!1}}async generateEmbedding(e){let t={model:v.MODEL,prompt:e},s=null;for(let n=0;n<this.maxRetries;n++)try{let r=await this.fetchWithTimeout(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},this.timeoutMs);if(!r.ok){let i=await r.text();throw new Error(`Ollama API error (${r.status}): ${i}`)}let o=await r.json();if(o.embedding.length!==v.DIMENSIONS)throw new Error(`Invalid embedding dimensions: expected ${v.DIMENSIONS}, got ${o.embedding.length}`);return o.embedding}catch(r){if(s=D(r),s.message.includes("Invalid embedding dimensions"))throw s;if(n<this.maxRetries-1){let o=this.retryDelayMs*Math.pow(2,n);await this.sleep(o)}}throw new Error(`Failed to generate embedding after ${this.maxRetries} attempts: ${s?.message}`)}async fetchWithTimeout(e,t,s){let n=new AbortController,r=setTimeout(()=>n.abort(),s);try{return await fetch(e,{...t,signal:n.signal})}finally{clearTimeout(r)}}sleep(e){return new Promise(t=>setTimeout(t,e))}async getServerInfo(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);return e.ok?await e.json():null}catch{return null}}async ensureModelAvailable(){if(!await this.healthCheck())throw new Error(`Ollama model '${v.MODEL}' is not available. Please run: ollama pull ${v.MODEL}`)}};import{createHash as Pe}from"crypto";var U=class{cache;maxSize;hits;misses;constructor(e=1e4){this.cache=new Map,this.maxSize=e,this.hits=0,this.misses=0}hashContent(e,t){return Pe("sha256").update(`${t}:${e}`).digest("hex")}get(e,t){let s=this.hashContent(e,t),n=this.cache.get(s);return n?(this.hits++,this.cache.delete(s),this.cache.set(s,n),n.embedding):(this.misses++,null)}set(e,t,s){let n=this.hashContent(e,t);if(this.cache.size>=this.maxSize&&!this.cache.has(n)){let o=this.cache.keys().next().value;o&&this.cache.delete(o)}let r={embedding:s,timestamp:Date.now(),model:t};this.cache.set(n,r)}has(e,t){let s=this.hashContent(e,t);return this.cache.has(s)}getStats(){let e=this.hits+this.misses,t=e>0?this.hits/e:0;return{size:this.cache.size,hitRate:t,hits:this.hits,misses:this.misses}}clear(){this.cache.clear(),this.hits=0,this.misses=0}evictOlderThan(e){let s=Date.now()-e,n=0;for(let[r,o]of this.cache.entries())o.timestamp<s&&(this.cache.delete(r),n++);return n}getMemoryUsageEstimate(){return this.cache.size*3172}export(){return Array.from(this.cache.entries()).map(([e,t])=>({key:e,entry:t}))}import(e){this.cache.clear();for(let{key:t,entry:s}of e)this.cache.size<this.maxSize&&this.cache.set(t,s)}};V();var _=class{client;cache;batchSize;enableFallback;ollamaAvailable=null;constructor(e={}){this.client=new K(e.ollamaBaseUrl),this.cache=e.cache??new U(e.maxCacheSize),this.batchSize=e.batchSize??v.BATCH_SIZE,this.enableFallback=e.enableFallback??!0}async embed(e){let t=this.cache.get(e,v.MODEL);if(t)return t;let s;if(await this.isOllamaAvailable())s=await this.client.generateEmbedding(e);else if(this.enableFallback)s=this.generatePseudoEmbedding(e);else throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);return this.cache.set(e,v.MODEL,s),s}formatForEmbedding(e){let t=[];e.language&&t.push(e.language),e.type&&t.push(e.type),e.name&&t.push(e.name);let s=t.length>0?`${t.join(" ")}: `:"",n=v.CONTEXT_WINDOW*4,r=e.content.trim();if(s.length+r.length>n){let o=n-s.length-3;r=r.substring(0,o)+"..."}return s+r}async embedBatch(e){let t=[];for(let s of e){let n=await this.embed(s);t.push(n)}return t}async embedCodeChunks(e,t){let s=Date.now(),n=[],r=0,o=0,i=await this.isOllamaAvailable();if(i)await this.client.ensureModelAvailable();else if(!this.enableFallback)throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);for(let c=0;c<e.length;c+=this.batchSize){let l=e.slice(c,Math.min(c+this.batchSize,e.length)),d=await this.processBatch(l,i);n.push(...d);for(let u of d)u.cached?r++:o++;if(t){let u=c+l.length,m=e.length,f=(Date.now()-s)/u,y=(m-u)*f;t({current:u,total:m,percentage:u/m*100,estimatedTimeRemainingMs:y})}}let a=Date.now()-s;return{results:n,stats:{totalChunks:e.length,cachedHits:r,computedNew:o,totalTimeMs:a,avgTimePerChunk:a/e.length}}}async processBatch(e,t){let s=[],n=e.map(async o=>{let i=this.formatForEmbedding(o),a=Date.now(),c=this.cache.get(i,v.MODEL);if(c)return{chunkId:o.id,embedding:c,model:v.MODEL,cached:!0,computeTimeMs:Date.now()-a};try{let l;return t?l=await this.client.generateEmbedding(i):l=this.generatePseudoEmbedding(i),this.cache.set(i,v.MODEL,l),{chunkId:o.id,embedding:l,model:t?v.MODEL:"pseudo-embedding",cached:!1,computeTimeMs:Date.now()-a}}catch(l){throw new Error(`Failed to generate embedding for chunk ${o.id}: ${j(l)}`)}}),r=await Promise.all(n);return s.push(...r),s}async isOllamaAvailable(){return this.ollamaAvailable!==null?this.ollamaAvailable:(this.ollamaAvailable=await this.client.healthCheck(),this.ollamaAvailable)}resetOllamaCheck(){this.ollamaAvailable=null}generatePseudoEmbedding(e){let t=new Array(v.DIMENSIONS).fill(0),s=e.split(/\s+|[^\w]+/).filter(o=>o.length>0);for(let o=0;o<s.length;o++){let i=s[o];for(let a=0;a<i.length&&a<t.length;a++)t[(o+a)%t.length]+=i.charCodeAt(a)/1e3}let n=[[/class\s+\w+/,0],[/function\s+\w+/,1],[/async\s+|await\s+|Promise/,2],[/interface\s+\w+/,3],[/export\s+/,4],[/import\s+/,5],[/try\s*{/,6],[/\.(map|filter|reduce)\(/,7]];for(let[o,i]of n)o.test(e)&&(t[i]+=.5);let r=Math.sqrt(t.reduce((o,i)=>o+i*i,0))||1;return t.map(o=>o/r)}clearCache(){this.cache.clear()}getCacheStats(){return this.cache.getStats()}async healthCheck(){return await this.client.healthCheck()}async getServerInfo(){return await this.client.getServerInfo()}getDimensions(){return v.DIMENSIONS}getConfig(){return{model:v.MODEL,dimensions:v.DIMENSIONS,contextWindow:v.CONTEXT_WINDOW,batchSize:this.batchSize,maxRetries:v.MAX_RETRIES,enableFallback:this.enableFallback}}};V();le();var we={maxNodes:1e5,maxEdgesPerNode:500,namespace:"code-intelligence:kg",enableVectorEmbeddings:!0,embeddingDimension:384,enableLLMExtraction:!0,llmModelTier:2,llmMaxTokens:2048},me=oe.create("code-intelligence/knowledge-graph"),he=class{config;memory;nodeCache=new Map;edgeIndex=new Map;tsParser;fileReader;embedder;llmRouter;constructor(e,t={}){this.config={...we,...t},this.isKnowledgeGraphDependencies(e)?(this.memory=e.memory,this.llmRouter=e.llmRouter):(this.memory=e,this.llmRouter=void 0),this.tsParser=new F,this.fileReader=new k,this.embedder=new _({enableFallback:!0})}isKnowledgeGraphDependencies(e){return e.memory!==void 0}async index(e){let t=Date.now(),s=[],n=0,r=0;try{let{paths:o,incremental:i=!1,includeTests:a=!0,languages:c}=e;i||await this.clear();for(let d of o)try{if(c&&c.length>0){let m=this.getFileExtension(d);if(!this.matchesLanguage(m,c))continue}if(!a&&this.isTestFile(d))continue;let u=await this.indexFile(d);n+=u.nodes,r+=u.edges}catch(u){s.push({file:d,error:j(u)})}let l=Date.now()-t;return await this.storeIndexMetadata({filesIndexed:o.length-s.length,nodesCreated:n,edgesCreated:r,duration:l,indexedAt:new Date().toISOString()}),w({filesIndexed:o.length-s.length,nodesCreated:n,edgesCreated:r,duration:l,errors:s})}catch(o){return L(D(o))}}async query(e){try{let{query:t,type:s,limit:n=100}=e;return s==="cypher"?this.executeCypherQuery(t,n):this.executeNaturalLanguageQuery(t,n)}catch(t){return L(D(t))}}async mapDependencies(e){try{let{files:t,direction:s,depth:n=3}=e,r=[],o=[],i=new Set,a=[];for(let l of t)await this.traverseDependencies(l,s,n,i,r,o,[],a);let c=this.calculateDependencyMetrics(r,o);return w({nodes:r,edges:o,cycles:a,metrics:c})}catch(t){return L(D(t))}}async getNode(e){if(this.nodeCache.has(e))return this.nodeCache.get(e);let t=`${this.config.namespace}:node:${e}`,s=await this.memory.get(t);return s&&this.nodeCache.set(e,s),s}async getEdges(e,t){let s=[],n=this.edgeIndex.get(e);if(n)return this.filterEdgesByDirection(n,e,t);let r=`${this.config.namespace}:edge:*`,o=await this.memory.search(r,this.config.maxEdgesPerNode*2);for(let i of o){let a=await this.memory.get(i);a&&(t!=="outgoing"&&a.target===e||t!=="incoming"&&a.source===e)&&s.push(a)}return s}async clear(){this.nodeCache.clear(),this.edgeIndex.clear()}isLLMExtractionAvailable(){return this.config.enableLLMExtraction===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){case 1:return"claude-3-5-haiku-20241022";case 2:return"claude-sonnet-4-20250514";case 3:return"claude-sonnet-4-20250514";case 4:return"claude-opus-4-5-20251101";default:return"claude-sonnet-4-20250514"}}async extractRelationshipsWithLLM(e,t){if(!this.llmRouter)return{semanticRelationships:[],designPatterns:[],architecturalBoundaries:[],dependencyImpacts:[]};try{let s=this.buildRelationshipExtractionPrompt(e,t),n=this.getModelForTier(this.config.llmModelTier??2),r=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software architect analyzing code structure. Extract:
24
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,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
2
- import{a as I,b as H,c as C,e as S,f as L}from"./chunk-RRELDHZY.js";import{b as T,d as P}from"./chunk-CU36MONI.js";import{a as f,c as O}from"./chunk-OXR2FPHK.js";import{f as x}from"./chunk-EVIXQR4O.js";L();P();var v=["function","module","test","file","class"],w=["calls","imports","tests","depends_on","covers"],E=class{ensureSchema(e){e.transaction(()=>{e.exec(I),e.exec(H),e.exec(C)})()}schemaExists(e){return S(e)}getNodeTypes(){return v}getEdgeTypes(){return w}isValidNodeType(e){return v.includes(e)}isValidEdgeType(e){return w.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 N(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?M(n.embedding):null}}function l(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?T(n.metadata):void 0,embedding:n.embedding?F(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function A(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 b(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?T(n.properties):void 0,createdAt:n.created_at}}function _(n,e,t){return`${n}--${t}-->${e}`}function M(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 F(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}O();var z={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},y=class{config;schemaManager;initialized=!1;constructor(e){this.config={...z,...e},this.schemaManager=new E}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=x(),r={id:t,...e},i=N(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.9.4");process.exit(0)}
2
+ import{a as I,b as H,c as C,e as S,f as L}from"./chunk-7ZXNJT4Q.js";import{b as T,d as P}from"./chunk-4GJAYXB7.js";import{a as f,c as O}from"./chunk-F6AU2MAZ.js";import{f as x}from"./chunk-G72E5DL3.js";L();P();var v=["function","module","test","file","class"],w=["calls","imports","tests","depends_on","covers"],E=class{ensureSchema(e){e.transaction(()=>{e.exec(I),e.exec(H),e.exec(C)})()}schemaExists(e){return S(e)}getNodeTypes(){return v}getEdgeTypes(){return w}isValidNodeType(e){return v.includes(e)}isValidEdgeType(e){return w.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 N(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?M(n.embedding):null}}function l(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?T(n.metadata):void 0,embedding:n.embedding?F(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function A(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 b(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?T(n.properties):void 0,createdAt:n.created_at}}function _(n,e,t){return`${n}--${t}-->${e}`}function M(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 F(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}O();var z={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},y=class{config;schemaManager;initialized=!1;constructor(e){this.config={...z,...e},this.schemaManager=new E}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=x(),r={id:t,...e},i=N(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(i.id,i.type,i.name,i.file_path,i.line_start,i.line_end,i.complexity,i.coverage,i.metadata,i.embedding),t}async addEdge(e){this.ensureInitialized();let t=_(e.sourceId,e.targetId,e.type),r={id:t,...e},i=A(r);return this.config.db.prepare(`
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
2
2
  import*as o from"fs";import*as l from"path";var m=class{cacheDir;keepVersions;constructor(e={}){this.cacheDir=e.cacheDir??l.join(process.cwd(),".agentic-qe","plugins"),this.keepVersions=e.keepVersions??2}has(e,t){let s=this.versionDir(e,t);return o.existsSync(s)&&o.existsSync(l.join(s,"qe-plugin.json"))}get(e,t){if(!this.has(e,t))return;let s=this.versionDir(e,t),i=o.readFileSync(l.join(s,"qe-plugin.json"),"utf-8"),r=JSON.parse(i),c=o.statSync(s);return{manifest:r,path:s,cachedAt:c.birthtime.toISOString()}}store(e,t){let s=this.versionDir(e.name,e.version);return o.existsSync(s)||(o.mkdirSync(s,{recursive:!0}),this.copyDir(t,s),o.writeFileSync(l.join(s,"qe-plugin.json"),JSON.stringify(e,null,2)),this.pruneOldVersions(e.name)),s}remove(e,t){let s=this.versionDir(e,t);return o.existsSync(s)?(o.rmSync(s,{recursive:!0,force:!0}),!0):!1}listVersions(e){let t=l.join(this.cacheDir,e);if(!o.existsSync(t))return[];let s=[],i=o.readdirSync(t);for(let r of i){let c=l.join(t,r),h=l.join(c,"qe-plugin.json");if(o.existsSync(h))try{let a=o.readFileSync(h,"utf-8"),f=JSON.parse(a),u=o.statSync(c);s.push({manifest:f,path:c,cachedAt:u.birthtime.toISOString()})}catch{}}return s}listAll(){if(!o.existsSync(this.cacheDir))return[];let e=[],t=o.readdirSync(this.cacheDir);for(let s of t){let i=this.listVersions(s);i.length>0&&(i.sort((r,c)=>c.manifest.version.localeCompare(r.manifest.version)),e.push(i[0]))}return e}versionDir(e,t){return l.join(this.cacheDir,e,t)}pruneOldVersions(e){let t=this.listVersions(e);if(t.length<=this.keepVersions)return;t.sort((i,r)=>i.cachedAt.localeCompare(r.cachedAt));let s=t.slice(0,t.length-this.keepVersions);for(let i of s)o.rmSync(i.path,{recursive:!0,force:!0})}copyDir(e,t){if(!o.existsSync(e))return;let s=o.readdirSync(e,{withFileTypes:!0});for(let i of s){let r=l.join(e,i.name),c=l.join(t,i.name);if(i.isDirectory()){if(i.name===".git"||i.name==="node_modules")continue;o.mkdirSync(c,{recursive:!0}),this.copyDir(r,c)}else o.copyFileSync(r,c)}}};var R=/^[a-z][a-z0-9-]*$/,S=/^\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?$/,j=["aqe-core-","agentic-qe-core-"];function E(n){let e=[],t=[];if(!n||typeof n!="object")return{valid:!1,errors:["Manifest must be a non-null object"],warnings:[]};let s=n;if(!s.name||typeof s.name!="string"?e.push("name is required and must be a string"):D(s.name,e,t),!s.version||typeof s.version!="string"?e.push("version is required and must be a string"):S.test(s.version)||e.push(`version "${s.version}" is not valid semver (expected: major.minor.patch)`),!s.description||typeof s.description!="string"?e.push("description is required and must be a string"):s.description.length>500&&t.push("description exceeds 500 characters"),(!s.author||typeof s.author!="string")&&e.push("author is required and must be a string"),!Array.isArray(s.domains)||s.domains.length===0)e.push("domains is required and must be a non-empty array");else for(let i of s.domains)if(typeof i!="string"){e.push("Each domain must be a string");break}if(!s.entryPoint||typeof s.entryPoint!="string"?e.push("entryPoint is required and must be a string"):V(s.entryPoint,e),s.dependencies!==void 0)if(typeof s.dependencies!="object"||s.dependencies===null||Array.isArray(s.dependencies))e.push("dependencies must be an object mapping plugin names to semver ranges");else for(let[i,r]of Object.entries(s.dependencies))typeof r!="string"&&e.push(`Dependency "${i}" must have a string version range`);if(s.hooks!==void 0)if(typeof s.hooks!="object"||s.hooks===null||Array.isArray(s.hooks))e.push("hooks must be an object mapping event names to handler paths");else for(let[,i]of Object.entries(s.hooks)){if(typeof i!="string"){e.push("Hook handler paths must be strings");break}i.includes("..")&&e.push(`Hook handler path "${i}" must not contain ".." (path traversal)`)}if(s.minAqeVersion!==void 0&&(typeof s.minAqeVersion!="string"||!S.test(s.minAqeVersion))&&t.push("minAqeVersion should be valid semver"),s.permissions!==void 0){if(!Array.isArray(s.permissions))e.push("permissions must be an array of strings");else for(let i of s.permissions)if(typeof i!="string"){e.push("Each permission must be a string");break}}return{valid:e.length===0,errors:e,warnings:t}}function b(n){let e=typeof n=="string"?JSON.parse(n):n,t=E(e);if(!t.valid)throw new Error(`Invalid plugin manifest:
3
3
  - ${t.errors.join(`
4
4
  - `)}`);return e}function D(n,e,t){n.length>64&&e.push("name must be 64 characters or fewer"),R.test(n)||e.push("name must be lowercase alphanumeric with hyphens, starting with a letter"),/[^\x00-\x7F]/.test(n)&&e.push("name must contain only ASCII characters");for(let s of j)n.startsWith(s)&&e.push(`name cannot start with reserved prefix "${s}"`);["plugin","test","tool"].includes(n)&&t.push(`name "${n}" is very generic \u2014 consider a more descriptive name`)}function V(n,e){n.includes("..")&&e.push('entryPoint must not contain ".." (path traversal)'),(n.startsWith("/")||n.startsWith("\\"))&&e.push("entryPoint must be a relative path"),!n.endsWith(".js")&&!n.endsWith(".ts")&&!n.endsWith(".mjs")&&e.push("entryPoint must end in .js, .ts, or .mjs")}var y=class{resolve(e){let t=new Map;for(let a of e)t.set(a.name,a);let s=[],i=new Set,r=new Set,c=new Map,h=(a,f)=>{if(i.has(a))return;if(r.has(a)){let g=[...f.slice(f.indexOf(a)),a];throw new Error(`Dependency cycle detected: ${g.join(" -> ")}`)}let u=t.get(a);if(!u)return;r.add(a);let k=Object.keys(u.dependencies??{}),P=[];for(let g of k)t.has(g)?h(g,[...f,a]):P.push(g);P.length>0&&c.set(a,P),r.delete(a),i.add(a),s.push(u)};for(let a of e)h(a.name,[]);return{ordered:s.map((a,f)=>({manifest:a,order:f})),missing:c}}canLoad(e,t){let i=Object.keys(e.dependencies??{}).filter(r=>!t.has(r));return{canLoad:i.length===0,missingDeps:i}}};var N=["aqe-core-","agentic-qe-core-","agentic-qe-internal-"],M=new Set(["aqe","agentic-qe","ruflo","claude-flow"]),_=["..","~","/etc/","/proc/","/dev/","node_modules/"];function A(n){let e=[];return $(n.name,e),q(n.entryPoint,e),C(n.hooks,e),I(n.permissions,e),{safe:e.length===0,violations:e}}function $(n,e){/[^\x20-\x7E]/.test(n)&&e.push(`Plugin name "${n}" contains non-ASCII characters`),M.has(n.toLowerCase())&&e.push(`Plugin name "${n}" is a reserved name`);for(let s of N)n.toLowerCase().startsWith(s)&&e.push(`Plugin name "${n}" uses reserved prefix "${s}"`);let t=n.toLowerCase().replace(/[0o]/g,"o").replace(/[1il]/g,"l").replace(/[-_]/g,"");M.has(t)&&e.push(`Plugin name "${n}" is visually similar to a reserved name`)}function q(n,e){w(n,"entryPoint",e),(n.startsWith("/")||n.startsWith("\\"))&&e.push("entryPoint must be a relative path, not absolute")}function C(n,e){if(n)for(let[t,s]of Object.entries(n))w(s,`hook[${t}]`,e)}function w(n,e,t){for(let s of _)n.includes(s)&&t.push(`${e} contains dangerous path pattern "${s}"`);n.includes("\0")&&t.push(`${e} contains null byte (path injection attempt)`)}function I(n,e){if(!n)return;let t=["fs:write-root","net:arbitrary","exec:shell"];for(let s of n)t.includes(s)&&e.push(`Plugin requests dangerous permission: ${s}`)}import*as p from"fs";import*as d from"path";var v=class{type="local";async resolve(e){let t=d.resolve(e),s=d.join(t,"qe-plugin.json");if(!p.existsSync(s))throw new Error(`No qe-plugin.json found at ${s}`);let i=p.readFileSync(s,"utf-8");return b(i)}async getPluginPath(e){let t=d.resolve(e);if(!p.existsSync(t))throw new Error(`Plugin directory does not exist: ${t}`);return t}};var x=class{cache;resolver;sources=new Map;constructor(e={}){this.cache=e.cache??new m,this.resolver=new y;let t=new v;if(this.sources.set("local",t),e.sources)for(let s of e.sources)this.sources.set(s.type,s)}async install(e,t="local"){if(process.env.AQE_PLUGINS_DISABLED==="true")return{success:!1,errors:["Plugin loading is disabled (AQE_PLUGINS_DISABLED=true)"],securityViolations:[]};let s=[],i=this.sources.get(t);if(!i)return{success:!1,errors:[`Unknown source type: ${t}. Available: ${[...this.sources.keys()].join(", ")}`],securityViolations:[]};let r;try{r=await i.resolve(e)}catch(u){return{success:!1,errors:[`Failed to resolve plugin: ${u instanceof Error?u.message:String(u)}`],securityViolations:[]}}let c=E(r);if(!c.valid)return{success:!1,manifest:r,errors:c.errors,securityViolations:[]};let h=A(r);if(!h.safe)return{success:!1,manifest:r,errors:["Plugin failed security checks"],securityViolations:h.violations};if(this.cache.has(r.name,r.version)){let u=this.cache.get(r.name,r.version);return{success:!0,manifest:r,cachePath:u.path,errors:[],securityViolations:[]}}let a;try{a=await i.getPluginPath(e)}catch(u){return{success:!1,manifest:r,errors:[`Failed to get plugin path: ${u instanceof Error?u.message:String(u)}`],securityViolations:[]}}let f=this.cache.store(r,a);return{success:!0,manifest:r,cachePath:f,errors:s,securityViolations:[]}}remove(e,t){if(t)return this.cache.remove(e,t);let s=this.cache.listVersions(e),i=!1;for(let r of s)this.cache.remove(e,r.manifest.version)&&(i=!0);return i}list(){return this.cache.listAll().map(t=>({name:t.manifest.name,version:t.manifest.version,description:t.manifest.description,domains:t.manifest.domains,source:"cached",cachePath:t.path}))}resolveLoadOrder(){let e=this.cache.listAll();return this.resolver.resolve(e.map(t=>t.manifest))}registerSource(e){this.sources.set(e.type,e)}};export{b as a,m as b,x as c};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
2
- import{a as ne,b as oe}from"./chunk-UC3RA5LW.js";import{S as ie,i as j,p as q}from"./chunk-OJKGRB6D.js";import{c as v,e as $,g as W}from"./chunk-7ASGPJWU.js";var R,E=v(()=>{"use strict";R={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}});function ae(){if(V)return k!==null;try{let o=(oe(),W(ne));if(k=o.differentiableSearch,P=o.init,P)try{P()}catch{}return V=!0,!0}catch{return V=!0,!1}}function B(o){let e=0;for(let t=0;t<o.length;t++)e+=o[t]*o[t];return Math.sqrt(e)}function se(o,e,t,r){let n=t*r;if(n===0)return 0;let i=0,a=Math.min(o.length,e.length);for(let s=0;s<a;s++)i+=o[s]*e[s];return i/n}function U(o,e){let t=0,r=Math.min(o.length,e.length);for(let n=0;n<r;n++){let i=o[n]-e[n];t+=i*i}return Math.sqrt(t)}function ce(o,e){if(o.length===e)return o;let t=new Float32Array(e);if(o.length>e){let r=o.length/e;for(let n=0;n<e;n++){let i=Math.floor(n*r),a=Math.floor((n+1)*r),s=0;for(let c=i;c<a;c++)s+=o[c];t[n]=s/(a-i)}}else for(let r=0;r<o.length;r++)t[r]=o[r];return t}var k,P,V,w,O=v(()=>{"use strict";E();k=null,P=null,V=!1;w=class{config;entries=[];idToIndex=new Map;hasRuvector=!1;loaded=!1;constructor(e){this.config={...R,...e}}ensureLoaded(){this.loaded||(this.hasRuvector=ae(),this.loaded=!0)}normalizeVector(e){return e.length===this.config.dimensions?e:ce(e,this.config.dimensions)}add(e,t,r){this.ensureLoaded();let n=this.normalizeVector(t),i=B(n);if(this.idToIndex.has(e)){let s=this.idToIndex.get(e);this.entries[s]={id:e,vector:n,norm:i,metadata:r};return}let a=this.entries.length;this.entries.push({id:e,vector:n,norm:i,metadata:r}),this.idToIndex.set(e,a)}search(e,t){if(this.ensureLoaded(),this.entries.length===0)return[];let r=this.normalizeVector(e),n=B(r),i=Math.min(t,this.entries.length),a=this.entries.length>0?this.entries[0].vector.length:0,s=r.length===a;if(this.config.metric==="cosine")return this.bruteForcSearch(r,n,i);if(this.hasRuvector&&s&&k)try{let c=this.entries.map(u=>u.vector),l=k(r,c,i,1).indices.map(u=>{let h=this.entries[u],p=-U(r,h.vector);return{id:h.id,score:p,metadata:h.metadata}});return l.sort((u,h)=>h.score-u.score),l}catch{}return this.bruteForcSearch(r,n,i)}bruteForcSearch(e,t,r){let n=[];for(let i of this.entries){let a;this.config.metric==="cosine"?a=se(e,i.vector,t,i.norm):a=-U(e,i.vector),n.push({id:i.id,score:a,metadata:i.metadata})}return n.sort((i,a)=>a.score-i.score),n.slice(0,r)}remove(e){let t=this.idToIndex.get(e);if(t===void 0)return!1;let r=this.entries.length-1;if(t!==r){let n=this.entries[r];this.entries[t]=n,this.idToIndex.set(n.id,t)}return this.entries.pop(),this.idToIndex.delete(e),!0}size(){return this.entries.length}dimensions(){return this.config.dimensions}recall(){return this.hasRuvector,1}isRuvectorAvailable(){return this.ensureLoaded(),this.hasRuvector}getConfig(){return{...this.config}}clear(){this.entries=[],this.idToIndex.clear()}dispose(){this.clear()}}});import{createRequire as le}from"module";function ue(){if(K){if(A)return A;throw new b(J??"Unknown load error")}K=!0;try{let o=he("@ruvector/router");if(!o.VectorDb||!o.DistanceMetric)throw new Error("@ruvector/router module missing VectorDb or DistanceMetric exports");return A=o,A}catch(o){let e=o instanceof Error?o.message:String(o);throw J=e,new b(e)}}function D(o){let e=0;for(let t=0;t<o.length;t++)e+=o[t]*o[t];return Math.sqrt(e)}function Q(o,e,t,r){let n=t*r;if(n===0)return 0;let i=0,a=Math.min(o.length,e.length);for(let s=0;s<a;s++)i+=o[s]*e[s];return i/n}function de(o,e){if(o.length===e)return o;let t=new Float32Array(e);if(o.length>e){let r=o.length/e;for(let n=0;n<e;n++){let i=Math.floor(n*r),a=Math.floor((n+1)*r),s=0;for(let c=i;c<a;c++)s+=o[c];t[n]=s/(a-i)}}else for(let r=0;r<o.length;r++)t[r]=o[r];return t}var he,b,A,K,J,x,X=v(()=>{"use strict";E();he=le(import.meta.url),b=class extends Error{constructor(e){super(`Native HNSW backend unavailable: ${e}`),this.name="NativeHnswUnavailableError"}},A=null,K=!1,J=null;x=class{config;nativeDb=null;metadataStore=new Map;vectorStore=new Map;normStore=new Map;operationLock=Promise.resolve();highFallbackWarningEmitted=!1;_metrics={totalSearches:0,totalAdds:0,totalRemoves:0,avgSearchLatencyMs:0,maxSearchLatencyMs:0,lastSearchLatencyMs:0,fallbackSearchCount:0,bruteForceSearchCount:0,nativeSearchCount:0,fallbackRate:0,allSearchesBruteForce:!1};constructor(e){this.config={...R,...e};let t=ue(),r=this.config.metric==="cosine"?t.DistanceMetric.Cosine:t.DistanceMetric.Euclidean;try{this.nativeDb=new t.VectorDb({dimensions:this.config.dimensions,distanceMetric:r,hnswM:this.config.M,hnswEfConstruction:this.config.efConstruction,hnswEfSearch:this.config.efSearch})}catch(n){let i=n instanceof Error?n.message:String(n);throw new b(`VectorDb creation failed: ${i}`)}}add(e,t,r){let n=this.normalizeVector(t),i=D(n);if(this.vectorStore.has(e))try{this.nativeDb.delete(String(e))}catch{}this.nativeDb.insert(String(e),n),this.vectorStore.set(e,n),this.normStore.set(e,i),r&&this.metadataStore.set(e,r),this._metrics.totalAdds++}search(e,t){let r=performance.now();if(this.vectorStore.size===0)return[];let n=this.normalizeVector(e),i=D(n),a=Math.min(t,this.vectorStore.size),s;try{s=this.nativeDb.search(n,a).map(l=>{let u=Number(l.id),h=this.vectorStore.get(u),p=this.normStore.get(u)??0,g;return this.config.metric==="cosine"&&h?g=Q(n,h,i,p):g=-l.score,{id:u,score:g,metadata:this.metadataStore.get(u)}}),s.sort((l,u)=>u.score-l.score),this._metrics.nativeSearchCount++}catch{this._metrics.fallbackSearchCount++,this._metrics.bruteForceSearchCount++,console.warn(`[NativeHNSW] FALLBACK: Using brute-force linear scan (@ruvector/router search failed). Index size: ${this.vectorStore.size}`),s=this.bruteForceSearch(n,i,a)}let c=performance.now()-r;return this.updateSearchMetrics(c),this._metrics.fallbackRate=this._metrics.fallbackSearchCount/this._metrics.totalSearches,this._metrics.allSearchesBruteForce=this._metrics.nativeSearchCount===0&&this._metrics.totalSearches>0,!this.highFallbackWarningEmitted&&this._metrics.fallbackRate>.5&&this._metrics.totalSearches>=10&&(this.highFallbackWarningEmitted=!0,console.error(`[NativeHNSW] WARNING: ${(this._metrics.fallbackRate*100).toFixed(0)}% of searches are using brute-force fallback. Native HNSW may not be functioning correctly. Consider rebuilding the index or checking @ruvector/router installation.`)),c>50&&console.warn(`[NativeHNSW] search took ${c.toFixed(1)}ms (k=${t}, results=${s.length})`),s}remove(e){if(!this.vectorStore.has(e))return!1;try{this.nativeDb.delete(String(e))}catch{}return this.vectorStore.delete(e),this.normStore.delete(e),this.metadataStore.delete(e),this._metrics.totalRemoves++,!0}size(){return this.vectorStore.size}dimensions(){return this.config.dimensions}recall(){let e=this.config.efSearch/this.config.M;return e>=10?.99:e>=5?.97:e>=3?.95:.9}getMetrics(){return{...this._metrics}}get lastSearchLatencyMs(){return this._metrics.lastSearchLatencyMs}getConfig(){return{...this.config}}clear(){if(this.nativeDb){for(let e of this.vectorStore.keys())try{this.nativeDb.delete(String(e))}catch{}this.vectorStore.clear(),this.normStore.clear(),this.metadataStore.clear()}}dispose(){this.vectorStore.clear(),this.normStore.clear(),this.metadataStore.clear(),this.nativeDb=null}isNativeAvailable(){return this.nativeDb!==null}normalizeVector(e){return e.length===this.config.dimensions?e:de(e,this.config.dimensions)}updateSearchMetrics(e){this._metrics.totalSearches++,this._metrics.lastSearchLatencyMs=e,e>this._metrics.maxSearchLatencyMs&&(this._metrics.maxSearchLatencyMs=e);let t=this._metrics.totalSearches;this._metrics.avgSearchLatencyMs=this._metrics.avgSearchLatencyMs*((t-1)/t)+e/t}bruteForceSearch(e,t,r){let n=[];for(let[i,a]of this.vectorStore){let s=this.normStore.get(i)??D(a),c=this.config.metric==="cosine"?Q(e,a,t,s):-(function(){let d=0,l=Math.min(e.length,a.length);for(let u=0;u<l;u++){let h=e[u]-a[u];d+=h*h}return Math.sqrt(d)})();n.push({id:i,score:c,metadata:this.metadataStore.get(i)})}return n.sort((i,a)=>a.score-i.score),n.slice(0,r)}}});function Y(o,e){let t=Array.from({length:e},()=>new Float64Array(e));for(let r=0;r<e;r++){let n=o[r].length;t[r][r]=n;for(let i of o[r])t[r][i]=-1}return t}function F(o,e){let t=e.length,r=new Float64Array(t);for(let n=0;n<t;n++){let i=o[n].length;r[n]=i*e[n];for(let a of o[n])r[n]-=e[a]}return r}function H(o){let e=0;for(let t=0;t<o.length;t++)e+=o[t]*o[t];return Math.sqrt(e)}function I(o){let e=H(o);if(e>0)for(let t=0;t<o.length;t++)o[t]/=e}function y(o,e){let t=0;for(let r=0;r<o.length;r++)t+=o[r]*e[r];for(let r=0;r<o.length;r++)o[r]-=t*e[r]}function S(o,e,t=100,r=1e-6){if(e<=1)return 0;if(e===2)return o[0].includes(1)?2:0;let n=new Float64Array(e).fill(1/Math.sqrt(e)),i=new Float64Array(e);for(let l=0;l<e;l++)i[l]=Math.random()-.5;y(i,n),I(i);let a=0;for(let l=0;l<30;l++){let u=F(o,i);if(y(u,n),a=H(u),a>0)for(let h=0;h<e;h++)i[h]=u[h]/a}if(a<r)return 0;let s=new Float64Array(e);for(let l=0;l<e;l++)s[l]=Math.random()-.5;y(s,n),I(s);let c=0;for(let l=0;l<t;l++){let u=F(o,s),h=new Float64Array(e);for(let m=0;m<e;m++)h[m]=a*s[m]-u[m];y(h,n);let p=H(h);if(p<r)break;let g=p;for(let m=0;m<e;m++)s[m]=h[m]/p;if(Math.abs(g-c)<r)break;c=g}let d=a-c;return Math.max(0,d)}function C(o,e,t=100,r=1e-6){return S(o,e,t,r)}function N(o,e,t=50,r){if(e<=1)return 0;let n=r??S(o,e);if(n<1e-10)return 1/0;let a=2*Math.max(...o.map(d=>d.length),1),c=2*(Math.log(a/n)/(a-n));return Math.max(0,c)}function M(o,e,t){let r=1-Math.exp(-o/.05),n=1-Math.exp(-e/.5),i=t===1/0?0:1/(1+t/5),a=.4*r+.3*n+.3*i;return Math.max(0,Math.min(1,a))}var _=v(()=>{"use strict"});var te={};$(te,{ALERT_THRESHOLDS:()=>me,DEFAULT_HNSW_HEALTH_CONFIG:()=>Z,HnswHealthMonitor:()=>L,_resetNativeLoader:()=>pe,approximateFiedlerValue:()=>S,approximateSpectralGap:()=>C,buildAdjacencyFromIndex:()=>ee,buildLaplacian:()=>Y,computeCoherenceScore:()=>M,createHnswHealthMonitor:()=>be,deflateVector:()=>y,estimateEffectiveResistance:()=>N,laplacianMultiply:()=>F,normalizeInPlace:()=>I,vectorNorm:()=>H});function fe(){return z?T:(z=!0,T=null,null)}function pe(){T=null,z=!1}function ee(o,e=16,t){let r=o.size();if(r===0)return{adjacency:[],nodeCount:0,adjacencySource:"approximate"};let n=Array.from({length:r},()=>[]),i=Math.min(e,r-1);if(i===0)return{adjacency:n,nodeCount:r,adjacencySource:"approximate"};if(t&&t.size>0){let a=Array.from(t.keys()).slice(0,r),s=new Map;for(let c=0;c<a.length;c++)s.set(a[c],c);for(let c=0;c<a.length;c++){let d=t.get(a[c]);if(!d)continue;let l=o.search(d,i+1);for(let u of l){if(u.id===a[c])continue;let h=s.get(u.id);h!==void 0&&(n[c].includes(h)||n[c].push(h),n[h].includes(c)||n[h].push(c))}}return{adjacency:n,nodeCount:r,adjacencySource:"actual-search"}}console.warn("[HnswHealthMonitor] No stored vectors provided \u2014 using approximate circular adjacency. Pass stored vectors for accurate health metrics.");for(let a=0;a<r;a++)for(let s=0;s<i;s++){let c=(a+s+1)%r;n[a].includes(c)||n[a].push(c),n[c].includes(a)||n[c].push(a)}return{adjacency:n,nodeCount:r,adjacencySource:"approximate"}}function be(o){return new L(o)}var Z,me,T,z,L,re=v(()=>{"use strict";_();_();Z={fiedlerThreshold:.01,spectralGapThreshold:.1,resistanceThreshold:10,coherenceThreshold:.3,maxPowerIterations:100,convergenceTolerance:1e-6,resistanceSampleSize:50,maxHistoryEntries:200,minIndexSize:3},me={FragileIndex:.01,PoorExpansion:.1,HighResistance:10,LowCoherence:.3},T=null,z=!1;L=class{config;alerts=[];history=[];lastReport=null;useNative=!1;nativeChecked=!1;constructor(e){this.config={...Z,...e}}checkHealth(e){let t=performance.now(),r=e.size();if(r<this.config.minIndexSize)return this.createSmallIndexReport(r,performance.now()-t);this.nativeChecked||(this.nativeChecked=!0,this.useNative=fe()!==null);let{adjacency:n,nodeCount:i,adjacencySource:a}=ee(e),s=this.useNative?this.computeNativeMetrics(n):this.computeApproximateMetrics(n,i),c=this.generateAlerts(s);this.alerts.length=0,this.alerts.push(...c);let d=performance.now()-t,l={healthy:c.length===0,metrics:s,alerts:c,indexSize:r,usedNativeBackend:this.useNative,adjacencySource:a,checkDurationMs:d,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:s.coherenceScore,fiedlerValue:s.fiedlerValue,indexSize:r,healthy:l.healthy,timestamp:l.checkedAt}),this.lastReport=l,l}getAlerts(){return[...this.alerts]}getMetricsHistory(e){let t=[...this.history];return e!==void 0&&e<t.length?t.slice(-e):t}isHealthy(){return this.lastReport===null?!0:this.lastReport.healthy}getLastReport(){return this.lastReport}clearHistory(){this.history.length=0,this.alerts.length=0,this.lastReport=null}computeNativeMetrics(e){let t=T,r=t.computeFiedlerValue(e),n=t.computeSpectralGap(e),i=t.computeEffectiveResistance(e),a=M(r,n,i);return{fiedlerValue:r,spectralGap:n,effectiveResistance:i,coherenceScore:a}}computeApproximateMetrics(e,t){let r=S(e,t,this.config.maxPowerIterations,this.config.convergenceTolerance),n=C(e,t,this.config.maxPowerIterations,this.config.convergenceTolerance),i=N(e,t,this.config.resistanceSampleSize,r),a=M(r,n,i);return{fiedlerValue:r,spectralGap:n,effectiveResistance:i,coherenceScore:a}}generateAlerts(e){let t=[],r=new Date;return e.fiedlerValue<this.config.fiedlerThreshold&&t.push({type:"FragileIndex",message:`Fiedler value ${e.fiedlerValue.toFixed(6)} is below threshold ${this.config.fiedlerThreshold}. The index graph has weak algebraic connectivity.`,value:e.fiedlerValue,threshold:this.config.fiedlerThreshold,timestamp:r}),e.spectralGap<this.config.spectralGapThreshold&&t.push({type:"PoorExpansion",message:`Spectral gap ${e.spectralGap.toFixed(6)} is below threshold ${this.config.spectralGapThreshold}. The index graph has poor expansion properties.`,value:e.spectralGap,threshold:this.config.spectralGapThreshold,timestamp:r}),e.effectiveResistance>this.config.resistanceThreshold&&t.push({type:"HighResistance",message:`Average effective resistance ${e.effectiveResistance.toFixed(4)} exceeds threshold ${this.config.resistanceThreshold}. Nodes are poorly connected.`,value:e.effectiveResistance,threshold:this.config.resistanceThreshold,timestamp:r}),e.coherenceScore<this.config.coherenceThreshold&&t.push({type:"LowCoherence",message:`Coherence score ${e.coherenceScore.toFixed(4)} is below threshold ${this.config.coherenceThreshold}. Overall index health is degraded.`,value:e.coherenceScore,threshold:this.config.coherenceThreshold,timestamp:r}),t}createSmallIndexReport(e,t){let r={fiedlerValue:e>0?1:0,spectralGap:e>0?1:0,effectiveResistance:e>0?.5:0,coherenceScore:e>0?1:0},n={healthy:!0,metrics:r,alerts:[],indexSize:e,usedNativeBackend:!1,adjacencySource:"approximate",checkDurationMs:t,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:r.coherenceScore,fiedlerValue:r.fiedlerValue,indexSize:e,healthy:!0,timestamp:n.checkedAt}),this.lastReport=n,n}addHistoryPoint(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}}});var ve={};$(ve,{HnswAdapter:()=>G});var ge,f,G,ye=v(()=>{O();X();ie();ge={patterns:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},"qe-memory":{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},learning:{dimensions:384,M:16,efConstruction:200,efSearch:50,metric:"cosine"},coverage:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}},f=new Map,G=class o{backend;_isNativeBackend;indexName;stringToNumericId=new Map;numericToStringId=new Map;nextAutoId=0;healthMonitor=null;healthMonitorLoaded=!1;operationsSinceLastCheck=0;healthCheckFrequency=100;lastHealthReport=null;constructor(e,t){this.indexName=e;let n={...ge[e]??{},...t},{backend:i,isNative:a}=o.createBackend(n);this.backend=i,this._isNativeBackend=a}add(e,t,r){this.backend.add(e,t,r),this.maybeRunHealthCheck()}search(e,t){let r=performance.now(),n=this.backend.search(e,t),i=performance.now()-r;return i>50&&console.warn(`[HNSW] search took ${i.toFixed(1)}ms (k=${t}, results=${n.length})`),this._lastSearchLatencyMs=i,n}_lastSearchLatencyMs=0;get lastSearchLatencyMs(){return this._lastSearchLatencyMs}remove(e){return this.backend.remove(e)}size(){return this.backend.size()}dimensions(){return this.backend.dimensions()}recall(){return this.backend.recall()}addByStringId(e,t){let r=this.stringToNumericId.get(e);r!==void 0?this.backend.remove(r):(r=this.nextAutoId++,this.stringToNumericId.set(e,r),this.numericToStringId.set(r,e)),this.backend.add(r,new Float32Array(t))}searchByArray(e,t){return this.backend.search(new Float32Array(e),t).map(n=>({id:this.numericToStringId.get(n.id)??String(n.id),score:n.score}))}removeByStringId(e){let t=this.stringToNumericId.get(e);if(t===void 0)return!1;let r=this.backend.remove(t);return r&&(this.stringToNumericId.delete(e),this.numericToStringId.delete(t)),r}clear(){this.backend.clear?.(),this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}dispose(){try{this.backend.dispose?.()}catch{}this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}isRuvectorAvailable(){return this.backend instanceof w?this.backend.isRuvectorAvailable():this.backend instanceof x?this.backend.isNativeAvailable():!1}isNativeBackend(){return this._isNativeBackend}getName(){return this.indexName}setHealthCheckFrequency(e){this.healthCheckFrequency=Math.max(1,e)}getHealthCheckFrequency(){return this.healthCheckFrequency}getLastHealthReport(){return this.lastHealthReport}getHealthMonitor(){return this.healthMonitor}maybeRunHealthCheck(){if(q()&&(this.operationsSinceLastCheck++,!(this.operationsSinceLastCheck<this.healthCheckFrequency)&&(this.operationsSinceLastCheck=0,this.ensureHealthMonitor(),this.healthMonitor)))try{this.lastHealthReport=this.healthMonitor.checkHealth(this.backend),this.lastHealthReport.healthy||console.warn(`[HNSW-Health] Index "${this.indexName}" health check failed: ${this.lastHealthReport.alerts.length} alert(s). Coherence: ${this.lastHealthReport.metrics.coherenceScore.toFixed(3)}`)}catch(e){console.warn(`[HNSW-Health] Health check error for "${this.indexName}":`,e)}}ensureHealthMonitor(){if(!this.healthMonitorLoaded){this.healthMonitorLoaded=!0;try{let e=(re(),W(te));this.healthMonitor=e.createHnswHealthMonitor()}catch(e){process.env.DEBUG&&console.debug("[HNSW-Health] Monitor module unavailable:",e instanceof Error?e.message:e),this.healthMonitor=null}}}static createBackend(e){if(j())try{return{backend:new x(e),isNative:!0}}catch(t){t instanceof b?console.info(`[HNSW] Native backend unavailable, falling back to JS: ${t.message}`):console.warn("[HNSW] Unexpected error creating native backend, falling back to JS:",t)}return{backend:new w(e),isNative:!1}}static create(e,t){let r=f.get(e);if(r instanceof o)return r;let n=new o(e,t);return f.set(e,n),n}static get(e){let t=f.get(e);return t instanceof o?t:void 0}static close(e){let t=f.get(e);t instanceof o&&t.dispose(),f.delete(e)}static closeAll(){for(let[e]of f)o.close(e);f.clear()}static listIndexes(){return Array.from(f.keys())}}});export{G as a,ve as b,ye as c};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
2
+ import{a as ne,b as oe}from"./chunk-RE6XD6RI.js";import{S as ie,i as j,p as q}from"./chunk-MN2MYLVW.js";import{c as v,e as $,g as W}from"./chunk-C2HGOUEB.js";var R,E=v(()=>{"use strict";R={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}});function ae(){if(V)return k!==null;try{let o=(oe(),W(ne));if(k=o.differentiableSearch,P=o.init,P)try{P()}catch{}return V=!0,!0}catch{return V=!0,!1}}function B(o){let e=0;for(let t=0;t<o.length;t++)e+=o[t]*o[t];return Math.sqrt(e)}function se(o,e,t,r){let n=t*r;if(n===0)return 0;let i=0,a=Math.min(o.length,e.length);for(let s=0;s<a;s++)i+=o[s]*e[s];return i/n}function U(o,e){let t=0,r=Math.min(o.length,e.length);for(let n=0;n<r;n++){let i=o[n]-e[n];t+=i*i}return Math.sqrt(t)}function ce(o,e){if(o.length===e)return o;let t=new Float32Array(e);if(o.length>e){let r=o.length/e;for(let n=0;n<e;n++){let i=Math.floor(n*r),a=Math.floor((n+1)*r),s=0;for(let c=i;c<a;c++)s+=o[c];t[n]=s/(a-i)}}else for(let r=0;r<o.length;r++)t[r]=o[r];return t}var k,P,V,w,O=v(()=>{"use strict";E();k=null,P=null,V=!1;w=class{config;entries=[];idToIndex=new Map;hasRuvector=!1;loaded=!1;constructor(e){this.config={...R,...e}}ensureLoaded(){this.loaded||(this.hasRuvector=ae(),this.loaded=!0)}normalizeVector(e){return e.length===this.config.dimensions?e:ce(e,this.config.dimensions)}add(e,t,r){this.ensureLoaded();let n=this.normalizeVector(t),i=B(n);if(this.idToIndex.has(e)){let s=this.idToIndex.get(e);this.entries[s]={id:e,vector:n,norm:i,metadata:r};return}let a=this.entries.length;this.entries.push({id:e,vector:n,norm:i,metadata:r}),this.idToIndex.set(e,a)}search(e,t){if(this.ensureLoaded(),this.entries.length===0)return[];let r=this.normalizeVector(e),n=B(r),i=Math.min(t,this.entries.length),a=this.entries.length>0?this.entries[0].vector.length:0,s=r.length===a;if(this.config.metric==="cosine")return this.bruteForcSearch(r,n,i);if(this.hasRuvector&&s&&k)try{let c=this.entries.map(u=>u.vector),l=k(r,c,i,1).indices.map(u=>{let h=this.entries[u],p=-U(r,h.vector);return{id:h.id,score:p,metadata:h.metadata}});return l.sort((u,h)=>h.score-u.score),l}catch{}return this.bruteForcSearch(r,n,i)}bruteForcSearch(e,t,r){let n=[];for(let i of this.entries){let a;this.config.metric==="cosine"?a=se(e,i.vector,t,i.norm):a=-U(e,i.vector),n.push({id:i.id,score:a,metadata:i.metadata})}return n.sort((i,a)=>a.score-i.score),n.slice(0,r)}remove(e){let t=this.idToIndex.get(e);if(t===void 0)return!1;let r=this.entries.length-1;if(t!==r){let n=this.entries[r];this.entries[t]=n,this.idToIndex.set(n.id,t)}return this.entries.pop(),this.idToIndex.delete(e),!0}size(){return this.entries.length}dimensions(){return this.config.dimensions}recall(){return this.hasRuvector,1}isRuvectorAvailable(){return this.ensureLoaded(),this.hasRuvector}getConfig(){return{...this.config}}clear(){this.entries=[],this.idToIndex.clear()}dispose(){this.clear()}}});import{createRequire as le}from"module";function ue(){if(K){if(A)return A;throw new b(J??"Unknown load error")}K=!0;try{let o=he("@ruvector/router");if(!o.VectorDb||!o.DistanceMetric)throw new Error("@ruvector/router module missing VectorDb or DistanceMetric exports");return A=o,A}catch(o){let e=o instanceof Error?o.message:String(o);throw J=e,new b(e)}}function D(o){let e=0;for(let t=0;t<o.length;t++)e+=o[t]*o[t];return Math.sqrt(e)}function Q(o,e,t,r){let n=t*r;if(n===0)return 0;let i=0,a=Math.min(o.length,e.length);for(let s=0;s<a;s++)i+=o[s]*e[s];return i/n}function de(o,e){if(o.length===e)return o;let t=new Float32Array(e);if(o.length>e){let r=o.length/e;for(let n=0;n<e;n++){let i=Math.floor(n*r),a=Math.floor((n+1)*r),s=0;for(let c=i;c<a;c++)s+=o[c];t[n]=s/(a-i)}}else for(let r=0;r<o.length;r++)t[r]=o[r];return t}var he,b,A,K,J,x,X=v(()=>{"use strict";E();he=le(import.meta.url),b=class extends Error{constructor(e){super(`Native HNSW backend unavailable: ${e}`),this.name="NativeHnswUnavailableError"}},A=null,K=!1,J=null;x=class{config;nativeDb=null;metadataStore=new Map;vectorStore=new Map;normStore=new Map;operationLock=Promise.resolve();highFallbackWarningEmitted=!1;_metrics={totalSearches:0,totalAdds:0,totalRemoves:0,avgSearchLatencyMs:0,maxSearchLatencyMs:0,lastSearchLatencyMs:0,fallbackSearchCount:0,bruteForceSearchCount:0,nativeSearchCount:0,fallbackRate:0,allSearchesBruteForce:!1};constructor(e){this.config={...R,...e};let t=ue(),r=this.config.metric==="cosine"?t.DistanceMetric.Cosine:t.DistanceMetric.Euclidean;try{this.nativeDb=new t.VectorDb({dimensions:this.config.dimensions,distanceMetric:r,hnswM:this.config.M,hnswEfConstruction:this.config.efConstruction,hnswEfSearch:this.config.efSearch})}catch(n){let i=n instanceof Error?n.message:String(n);throw new b(`VectorDb creation failed: ${i}`)}}add(e,t,r){let n=this.normalizeVector(t),i=D(n);if(this.vectorStore.has(e))try{this.nativeDb.delete(String(e))}catch{}this.nativeDb.insert(String(e),n),this.vectorStore.set(e,n),this.normStore.set(e,i),r&&this.metadataStore.set(e,r),this._metrics.totalAdds++}search(e,t){let r=performance.now();if(this.vectorStore.size===0)return[];let n=this.normalizeVector(e),i=D(n),a=Math.min(t,this.vectorStore.size),s;try{s=this.nativeDb.search(n,a).map(l=>{let u=Number(l.id),h=this.vectorStore.get(u),p=this.normStore.get(u)??0,g;return this.config.metric==="cosine"&&h?g=Q(n,h,i,p):g=-l.score,{id:u,score:g,metadata:this.metadataStore.get(u)}}),s.sort((l,u)=>u.score-l.score),this._metrics.nativeSearchCount++}catch{this._metrics.fallbackSearchCount++,this._metrics.bruteForceSearchCount++,console.warn(`[NativeHNSW] FALLBACK: Using brute-force linear scan (@ruvector/router search failed). Index size: ${this.vectorStore.size}`),s=this.bruteForceSearch(n,i,a)}let c=performance.now()-r;return this.updateSearchMetrics(c),this._metrics.fallbackRate=this._metrics.fallbackSearchCount/this._metrics.totalSearches,this._metrics.allSearchesBruteForce=this._metrics.nativeSearchCount===0&&this._metrics.totalSearches>0,!this.highFallbackWarningEmitted&&this._metrics.fallbackRate>.5&&this._metrics.totalSearches>=10&&(this.highFallbackWarningEmitted=!0,console.error(`[NativeHNSW] WARNING: ${(this._metrics.fallbackRate*100).toFixed(0)}% of searches are using brute-force fallback. Native HNSW may not be functioning correctly. Consider rebuilding the index or checking @ruvector/router installation.`)),c>50&&console.warn(`[NativeHNSW] search took ${c.toFixed(1)}ms (k=${t}, results=${s.length})`),s}remove(e){if(!this.vectorStore.has(e))return!1;try{this.nativeDb.delete(String(e))}catch{}return this.vectorStore.delete(e),this.normStore.delete(e),this.metadataStore.delete(e),this._metrics.totalRemoves++,!0}size(){return this.vectorStore.size}dimensions(){return this.config.dimensions}recall(){let e=this.config.efSearch/this.config.M;return e>=10?.99:e>=5?.97:e>=3?.95:.9}getMetrics(){return{...this._metrics}}get lastSearchLatencyMs(){return this._metrics.lastSearchLatencyMs}getConfig(){return{...this.config}}clear(){if(this.nativeDb){for(let e of this.vectorStore.keys())try{this.nativeDb.delete(String(e))}catch{}this.vectorStore.clear(),this.normStore.clear(),this.metadataStore.clear()}}dispose(){this.vectorStore.clear(),this.normStore.clear(),this.metadataStore.clear(),this.nativeDb=null}isNativeAvailable(){return this.nativeDb!==null}normalizeVector(e){return e.length===this.config.dimensions?e:de(e,this.config.dimensions)}updateSearchMetrics(e){this._metrics.totalSearches++,this._metrics.lastSearchLatencyMs=e,e>this._metrics.maxSearchLatencyMs&&(this._metrics.maxSearchLatencyMs=e);let t=this._metrics.totalSearches;this._metrics.avgSearchLatencyMs=this._metrics.avgSearchLatencyMs*((t-1)/t)+e/t}bruteForceSearch(e,t,r){let n=[];for(let[i,a]of this.vectorStore){let s=this.normStore.get(i)??D(a),c=this.config.metric==="cosine"?Q(e,a,t,s):-(function(){let d=0,l=Math.min(e.length,a.length);for(let u=0;u<l;u++){let h=e[u]-a[u];d+=h*h}return Math.sqrt(d)})();n.push({id:i,score:c,metadata:this.metadataStore.get(i)})}return n.sort((i,a)=>a.score-i.score),n.slice(0,r)}}});function Y(o,e){let t=Array.from({length:e},()=>new Float64Array(e));for(let r=0;r<e;r++){let n=o[r].length;t[r][r]=n;for(let i of o[r])t[r][i]=-1}return t}function F(o,e){let t=e.length,r=new Float64Array(t);for(let n=0;n<t;n++){let i=o[n].length;r[n]=i*e[n];for(let a of o[n])r[n]-=e[a]}return r}function H(o){let e=0;for(let t=0;t<o.length;t++)e+=o[t]*o[t];return Math.sqrt(e)}function I(o){let e=H(o);if(e>0)for(let t=0;t<o.length;t++)o[t]/=e}function y(o,e){let t=0;for(let r=0;r<o.length;r++)t+=o[r]*e[r];for(let r=0;r<o.length;r++)o[r]-=t*e[r]}function S(o,e,t=100,r=1e-6){if(e<=1)return 0;if(e===2)return o[0].includes(1)?2:0;let n=new Float64Array(e).fill(1/Math.sqrt(e)),i=new Float64Array(e);for(let l=0;l<e;l++)i[l]=Math.random()-.5;y(i,n),I(i);let a=0;for(let l=0;l<30;l++){let u=F(o,i);if(y(u,n),a=H(u),a>0)for(let h=0;h<e;h++)i[h]=u[h]/a}if(a<r)return 0;let s=new Float64Array(e);for(let l=0;l<e;l++)s[l]=Math.random()-.5;y(s,n),I(s);let c=0;for(let l=0;l<t;l++){let u=F(o,s),h=new Float64Array(e);for(let m=0;m<e;m++)h[m]=a*s[m]-u[m];y(h,n);let p=H(h);if(p<r)break;let g=p;for(let m=0;m<e;m++)s[m]=h[m]/p;if(Math.abs(g-c)<r)break;c=g}let d=a-c;return Math.max(0,d)}function C(o,e,t=100,r=1e-6){return S(o,e,t,r)}function N(o,e,t=50,r){if(e<=1)return 0;let n=r??S(o,e);if(n<1e-10)return 1/0;let a=2*Math.max(...o.map(d=>d.length),1),c=2*(Math.log(a/n)/(a-n));return Math.max(0,c)}function M(o,e,t){let r=1-Math.exp(-o/.05),n=1-Math.exp(-e/.5),i=t===1/0?0:1/(1+t/5),a=.4*r+.3*n+.3*i;return Math.max(0,Math.min(1,a))}var _=v(()=>{"use strict"});var te={};$(te,{ALERT_THRESHOLDS:()=>me,DEFAULT_HNSW_HEALTH_CONFIG:()=>Z,HnswHealthMonitor:()=>L,_resetNativeLoader:()=>pe,approximateFiedlerValue:()=>S,approximateSpectralGap:()=>C,buildAdjacencyFromIndex:()=>ee,buildLaplacian:()=>Y,computeCoherenceScore:()=>M,createHnswHealthMonitor:()=>be,deflateVector:()=>y,estimateEffectiveResistance:()=>N,laplacianMultiply:()=>F,normalizeInPlace:()=>I,vectorNorm:()=>H});function fe(){return z?T:(z=!0,T=null,null)}function pe(){T=null,z=!1}function ee(o,e=16,t){let r=o.size();if(r===0)return{adjacency:[],nodeCount:0,adjacencySource:"approximate"};let n=Array.from({length:r},()=>[]),i=Math.min(e,r-1);if(i===0)return{adjacency:n,nodeCount:r,adjacencySource:"approximate"};if(t&&t.size>0){let a=Array.from(t.keys()).slice(0,r),s=new Map;for(let c=0;c<a.length;c++)s.set(a[c],c);for(let c=0;c<a.length;c++){let d=t.get(a[c]);if(!d)continue;let l=o.search(d,i+1);for(let u of l){if(u.id===a[c])continue;let h=s.get(u.id);h!==void 0&&(n[c].includes(h)||n[c].push(h),n[h].includes(c)||n[h].push(c))}}return{adjacency:n,nodeCount:r,adjacencySource:"actual-search"}}console.warn("[HnswHealthMonitor] No stored vectors provided \u2014 using approximate circular adjacency. Pass stored vectors for accurate health metrics.");for(let a=0;a<r;a++)for(let s=0;s<i;s++){let c=(a+s+1)%r;n[a].includes(c)||n[a].push(c),n[c].includes(a)||n[c].push(a)}return{adjacency:n,nodeCount:r,adjacencySource:"approximate"}}function be(o){return new L(o)}var Z,me,T,z,L,re=v(()=>{"use strict";_();_();Z={fiedlerThreshold:.01,spectralGapThreshold:.1,resistanceThreshold:10,coherenceThreshold:.3,maxPowerIterations:100,convergenceTolerance:1e-6,resistanceSampleSize:50,maxHistoryEntries:200,minIndexSize:3},me={FragileIndex:.01,PoorExpansion:.1,HighResistance:10,LowCoherence:.3},T=null,z=!1;L=class{config;alerts=[];history=[];lastReport=null;useNative=!1;nativeChecked=!1;constructor(e){this.config={...Z,...e}}checkHealth(e){let t=performance.now(),r=e.size();if(r<this.config.minIndexSize)return this.createSmallIndexReport(r,performance.now()-t);this.nativeChecked||(this.nativeChecked=!0,this.useNative=fe()!==null);let{adjacency:n,nodeCount:i,adjacencySource:a}=ee(e),s=this.useNative?this.computeNativeMetrics(n):this.computeApproximateMetrics(n,i),c=this.generateAlerts(s);this.alerts.length=0,this.alerts.push(...c);let d=performance.now()-t,l={healthy:c.length===0,metrics:s,alerts:c,indexSize:r,usedNativeBackend:this.useNative,adjacencySource:a,checkDurationMs:d,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:s.coherenceScore,fiedlerValue:s.fiedlerValue,indexSize:r,healthy:l.healthy,timestamp:l.checkedAt}),this.lastReport=l,l}getAlerts(){return[...this.alerts]}getMetricsHistory(e){let t=[...this.history];return e!==void 0&&e<t.length?t.slice(-e):t}isHealthy(){return this.lastReport===null?!0:this.lastReport.healthy}getLastReport(){return this.lastReport}clearHistory(){this.history.length=0,this.alerts.length=0,this.lastReport=null}computeNativeMetrics(e){let t=T,r=t.computeFiedlerValue(e),n=t.computeSpectralGap(e),i=t.computeEffectiveResistance(e),a=M(r,n,i);return{fiedlerValue:r,spectralGap:n,effectiveResistance:i,coherenceScore:a}}computeApproximateMetrics(e,t){let r=S(e,t,this.config.maxPowerIterations,this.config.convergenceTolerance),n=C(e,t,this.config.maxPowerIterations,this.config.convergenceTolerance),i=N(e,t,this.config.resistanceSampleSize,r),a=M(r,n,i);return{fiedlerValue:r,spectralGap:n,effectiveResistance:i,coherenceScore:a}}generateAlerts(e){let t=[],r=new Date;return e.fiedlerValue<this.config.fiedlerThreshold&&t.push({type:"FragileIndex",message:`Fiedler value ${e.fiedlerValue.toFixed(6)} is below threshold ${this.config.fiedlerThreshold}. The index graph has weak algebraic connectivity.`,value:e.fiedlerValue,threshold:this.config.fiedlerThreshold,timestamp:r}),e.spectralGap<this.config.spectralGapThreshold&&t.push({type:"PoorExpansion",message:`Spectral gap ${e.spectralGap.toFixed(6)} is below threshold ${this.config.spectralGapThreshold}. The index graph has poor expansion properties.`,value:e.spectralGap,threshold:this.config.spectralGapThreshold,timestamp:r}),e.effectiveResistance>this.config.resistanceThreshold&&t.push({type:"HighResistance",message:`Average effective resistance ${e.effectiveResistance.toFixed(4)} exceeds threshold ${this.config.resistanceThreshold}. Nodes are poorly connected.`,value:e.effectiveResistance,threshold:this.config.resistanceThreshold,timestamp:r}),e.coherenceScore<this.config.coherenceThreshold&&t.push({type:"LowCoherence",message:`Coherence score ${e.coherenceScore.toFixed(4)} is below threshold ${this.config.coherenceThreshold}. Overall index health is degraded.`,value:e.coherenceScore,threshold:this.config.coherenceThreshold,timestamp:r}),t}createSmallIndexReport(e,t){let r={fiedlerValue:e>0?1:0,spectralGap:e>0?1:0,effectiveResistance:e>0?.5:0,coherenceScore:e>0?1:0},n={healthy:!0,metrics:r,alerts:[],indexSize:e,usedNativeBackend:!1,adjacencySource:"approximate",checkDurationMs:t,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:r.coherenceScore,fiedlerValue:r.fiedlerValue,indexSize:e,healthy:!0,timestamp:n.checkedAt}),this.lastReport=n,n}addHistoryPoint(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}}});var ve={};$(ve,{HnswAdapter:()=>G});var ge,f,G,ye=v(()=>{O();X();ie();ge={patterns:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},"qe-memory":{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},learning:{dimensions:384,M:16,efConstruction:200,efSearch:50,metric:"cosine"},coverage:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}},f=new Map,G=class o{backend;_isNativeBackend;indexName;stringToNumericId=new Map;numericToStringId=new Map;nextAutoId=0;healthMonitor=null;healthMonitorLoaded=!1;operationsSinceLastCheck=0;healthCheckFrequency=100;lastHealthReport=null;constructor(e,t){this.indexName=e;let n={...ge[e]??{},...t},{backend:i,isNative:a}=o.createBackend(n);this.backend=i,this._isNativeBackend=a}add(e,t,r){this.backend.add(e,t,r),this.maybeRunHealthCheck()}search(e,t){let r=performance.now(),n=this.backend.search(e,t),i=performance.now()-r;return i>50&&console.warn(`[HNSW] search took ${i.toFixed(1)}ms (k=${t}, results=${n.length})`),this._lastSearchLatencyMs=i,n}_lastSearchLatencyMs=0;get lastSearchLatencyMs(){return this._lastSearchLatencyMs}remove(e){return this.backend.remove(e)}size(){return this.backend.size()}dimensions(){return this.backend.dimensions()}recall(){return this.backend.recall()}addByStringId(e,t){let r=this.stringToNumericId.get(e);r!==void 0?this.backend.remove(r):(r=this.nextAutoId++,this.stringToNumericId.set(e,r),this.numericToStringId.set(r,e)),this.backend.add(r,new Float32Array(t))}searchByArray(e,t){return this.backend.search(new Float32Array(e),t).map(n=>({id:this.numericToStringId.get(n.id)??String(n.id),score:n.score}))}removeByStringId(e){let t=this.stringToNumericId.get(e);if(t===void 0)return!1;let r=this.backend.remove(t);return r&&(this.stringToNumericId.delete(e),this.numericToStringId.delete(t)),r}clear(){this.backend.clear?.(),this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}dispose(){try{this.backend.dispose?.()}catch{}this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}isRuvectorAvailable(){return this.backend instanceof w?this.backend.isRuvectorAvailable():this.backend instanceof x?this.backend.isNativeAvailable():!1}isNativeBackend(){return this._isNativeBackend}getName(){return this.indexName}setHealthCheckFrequency(e){this.healthCheckFrequency=Math.max(1,e)}getHealthCheckFrequency(){return this.healthCheckFrequency}getLastHealthReport(){return this.lastHealthReport}getHealthMonitor(){return this.healthMonitor}maybeRunHealthCheck(){if(q()&&(this.operationsSinceLastCheck++,!(this.operationsSinceLastCheck<this.healthCheckFrequency)&&(this.operationsSinceLastCheck=0,this.ensureHealthMonitor(),this.healthMonitor)))try{this.lastHealthReport=this.healthMonitor.checkHealth(this.backend),this.lastHealthReport.healthy||console.warn(`[HNSW-Health] Index "${this.indexName}" health check failed: ${this.lastHealthReport.alerts.length} alert(s). Coherence: ${this.lastHealthReport.metrics.coherenceScore.toFixed(3)}`)}catch(e){console.warn(`[HNSW-Health] Health check error for "${this.indexName}":`,e)}}ensureHealthMonitor(){if(!this.healthMonitorLoaded){this.healthMonitorLoaded=!0;try{let e=(re(),W(te));this.healthMonitor=e.createHnswHealthMonitor()}catch(e){process.env.DEBUG&&console.debug("[HNSW-Health] Monitor module unavailable:",e instanceof Error?e.message:e),this.healthMonitor=null}}}static createBackend(e){if(j())try{return{backend:new x(e),isNative:!0}}catch(t){t instanceof b?console.info(`[HNSW] Native backend unavailable, falling back to JS: ${t.message}`):console.warn("[HNSW] Unexpected error creating native backend, falling back to JS:",t)}return{backend:new w(e),isNative:!1}}static create(e,t){let r=f.get(e);if(r instanceof o)return r;let n=new o(e,t);return f.set(e,n),n}static get(e){let t=f.get(e);return t instanceof o?t:void 0}static close(e){let t=f.get(e);t instanceof o&&t.dispose(),f.delete(e)}static closeAll(){for(let[e]of f)o.close(e);f.clear()}static listIndexes(){return Array.from(f.keys())}}});export{G as a,ve as b,ye as c};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
2
- import{c as t}from"./chunk-7ASGPJWU.js";import{randomInt as o}from"node:crypto";function a(){return Math.random()}function m(n,e){return o(n,e)}function c(n,e){return n+Math.random()*(e-n)}var r=t(()=>{"use strict"});export{a,m as b,c,r as d};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
2
+ import{c as t}from"./chunk-C2HGOUEB.js";import{randomInt as o}from"node:crypto";function a(){return Math.random()}function m(n,e){return o(n,e)}function c(n,e){return n+Math.random()*(e-n)}var r=t(()=>{"use strict"});export{a,m as b,c,r as d};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
2
- import{c as h}from"./chunk-7ASGPJWU.js";function i(t,r){if(t.length!==r.length)throw new Error(`Vector length mismatch: ${t.length} vs ${r.length}`);let e=0,o=0,l=0;for(let n=0;n<t.length;n++)e+=t[n]*r[n],o+=t[n]*t[n],l+=r[n]*r[n];let u=Math.sqrt(o)*Math.sqrt(l);return u===0?0:e/u}function c(t){let r=Math.sqrt(t.reduce((e,o)=>e+o*o,0));return r===0?t.slice():t.map(e=>e/r)}function g(t){let r=0;for(let e=0;e<t.length;e++)r+=t[e]*t[e];return Math.sqrt(r)}var m=h(()=>{"use strict"});export{i as a,c as b,g as c,m as d};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
2
+ import{c as h}from"./chunk-C2HGOUEB.js";function i(t,r){if(t.length!==r.length)throw new Error(`Vector length mismatch: ${t.length} vs ${r.length}`);let e=0,o=0,l=0;for(let n=0;n<t.length;n++)e+=t[n]*r[n],o+=t[n]*t[n],l+=r[n]*r[n];let u=Math.sqrt(o)*Math.sqrt(l);return u===0?0:e/u}function c(t){let r=Math.sqrt(t.reduce((e,o)=>e+o*o,0));return r===0?t.slice():t.map(e=>e/r)}function g(t){let r=0;for(let e=0;e<t.length;e++)r+=t[e]*t[e];return Math.sqrt(r)}var m=h(()=>{"use strict"});export{i as a,c as b,g as c,m as d};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
2
- import{c as b,e as v,g as T}from"./chunk-7ASGPJWU.js";var y={};v(y,{DotProductAttention:()=>z,FlashAttention:()=>k,HyperbolicAttention:()=>W,LinearAttention:()=>j,MoEAttention:()=>K,MultiHeadAttention:()=>F,RuvectorLayer:()=>_,SonaEngine:()=>q,TensorCompress:()=>E,default:()=>O,differentiableSearch:()=>L,getCompressionLevel:()=>B,hierarchicalForward:()=>V,init:()=>D,pipeline:()=>J});import{createRequire as A}from"module";var I,g,O,_,E,L,V,B,D,k,z,F,W,j,K,q,J,S=b(()=>{I=A(import.meta.url),g=I("@ruvector/rvf-node"),O=g,{RuvectorLayer:_,TensorCompress:E,differentiableSearch:L,hierarchicalForward:V,getCompressionLevel:B,init:D,FlashAttention:k,DotProductAttention:z,MultiHeadAttention:F,HyperbolicAttention:W,LinearAttention:j,MoEAttention:K,SonaEngine:q,pipeline:J}=g||{}});var Z={};v(Z,{createRvfStore:()=>Q,isRvfNativeAvailable:()=>Y,openRvfStore:()=>U,openRvfStoreReadonly:()=>X});import{readFileSync as C,writeFileSync as H,copyFileSync as $,existsSync as G}from"fs";function l(){if(R)return f;R=!0;try{let i=(S(),T(y));!i.RvfDatabase&&i.default&&i.default.RvfDatabase&&(i=i.default),f=i}catch{f=null}return f}function w(i){return`${i}.idmap.json`}function N(i){let e=w(i),t=new Map,n=new Map,s=1;if(G(e))try{let r=JSON.parse(C(e,"utf-8"));s=r.nextLabel;for(let[a,m]of r.entries)t.set(a,m),n.set(m,a)}catch{}return{strToNum:t,numToStr:n,nextLabel:s}}function h(i,e,t){let n={nextLabel:t,entries:Array.from(e.entries())};H(w(i),JSON.stringify(n),"utf-8")}function Q(i,e){let t=l();if(!t)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let n=t.RvfDatabase.create(i,{dimension:e}),s=n.dimension();return new d(n,i,s,new Map,new Map,1)}function U(i){let e=l();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.open(i),n=t.dimension(),{strToNum:s,numToStr:r,nextLabel:a}=N(i);return new d(t,i,n,s,r,a)}function X(i){let e=l();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.openReadonly(i),n=t.dimension(),{strToNum:s,numToStr:r,nextLabel:a}=N(i);return new d(t,i,n,s,r,a)}function Y(){return l()!==null}var f,R,d,P=b(()=>{f=null,R=!1;d=class i{db;_path;_dimension;strToNum;numToStr;nextLabel;_open;constructor(e,t,n,s,r,a){this.db=e,this._path=t,this._dimension=n,this.strToNum=s,this.numToStr=r,this.nextLabel=a,this._open=!0}ingest(e){if(this.ensureOpen(),e.length===0)return{accepted:0,rejected:0};let t=this._dimension,n=new Float32Array(e.length*t),s=[],r=[];for(let o=0;o<e.length;o++){let{id:u,vector:p,metadata:x}=e[o],c=this.strToNum.get(u);c===void 0&&(c=this.nextLabel++,this.strToNum.set(u,c),this.numToStr.set(c,u)),s.push(c),r.push(x);let M=p instanceof Float32Array?p:new Float32Array(p);n.set(M.subarray(0,t),o*t)}let a;if(r.some(o=>o!==void 0)&&typeof this.db.ingestBatchWithMetadata=="function"){let o=r.map(u=>u?JSON.stringify(u):"");a=this.db.ingestBatchWithMetadata(n,s,o)}else a=this.db.ingestBatch(n,s);return this.persistIdMap(),{accepted:a.accepted,rejected:a.rejected}}search(e,t){this.ensureOpen();let n=e instanceof Float32Array?e:new Float32Array(e);return this.db.query(n,t).map(r=>{let a=this.numToStr.get(r.id);return a===void 0?null:{id:a,distance:r.distance,score:1/(1+r.distance)}}).filter(r=>r!==null)}delete(e){this.ensureOpen();let t=[];for(let s of e){let r=this.strToNum.get(s);r!==void 0&&t.push(r)}if(t.length===0)return 0;let n=this.db.delete(t);for(let s of e){let r=this.strToNum.get(s);r!==void 0&&(this.strToNum.delete(s),this.numToStr.delete(r))}return this.persistIdMap(),n.deleted}fork(e){this.ensureOpen(),$(this._path,e);let t=new Map(this.strToNum),n=new Map(this.numToStr);h(e,t,this.nextLabel);let r=l().RvfDatabase.open(e);return new i(r,e,this._dimension,t,n,this.nextLabel)}status(){this.ensureOpen();let e=this.db.status(),n=this.db.segments().filter(s=>s.segType==="witness");return{totalVectors:e.totalVectors,totalSegments:e.totalSegments,fileSizeBytes:e.fileSize,epoch:e.currentEpoch,witnessValid:n.length>0,witnessEntries:n.length}}dimension(){return this._dimension}size(){return this.ensureOpen(),this.db.status().totalVectors}compact(){this.ensureOpen(),this.db.compact()}close(){this._open&&(this.db.close(),this._open=!1)}isOpen(){return this._open}path(){return this._path}embedKernel(e){return this.ensureOpen(),this.db.embedKernel(0,99,0,e,0,"")}extractKernel(){return this.ensureOpen(),this.db.extractKernel()}verifyWitness(){this.ensureOpen();let e=this.tryNative("verifyWitness");return e?{valid:e.valid??!0,totalEntries:e.totalEntries??0,errors:Array.isArray(e.errors)?e.errors:[]}:{valid:!0,totalEntries:0,errors:[]}}sign(e){this.ensureOpen();let t=this.tryNative("sign",e);return typeof t=="string"?t:null}fileId(){this.ensureOpen();let e=this.tryNative("fileId");return typeof e=="string"?e:null}parentId(){this.ensureOpen();let e=this.tryNative("parentId");return typeof e=="string"?e:null}lineageDepth(){this.ensureOpen();let e=this.tryNative("lineageDepth");return typeof e=="number"?e:0}indexStats(){let e=this.status();return{totalVectors:e.totalVectors,dimension:this._dimension,totalSegments:e.totalSegments,fileSizeBytes:e.fileSizeBytes,epoch:e.epoch,witnessValid:e.witnessValid,witnessEntries:e.witnessEntries,idMapSize:this.strToNum.size}}freeze(){this.ensureOpen();let e=this.tryNative("freeze");return typeof e=="number"?e:0}derive(e){this.ensureOpen();let t=l();if(typeof this.db.derive=="function")try{let n=this.db.derive(e),s=new Map(this.strToNum),r=new Map(this.numToStr);return h(e,s,this.nextLabel),new i(n,e,this._dimension,s,r,this.nextLabel)}catch{}return this.fork(e)}ensureOpen(){if(!this._open)throw new Error("RVF database is closed")}tryNative(e,...t){if(typeof this.db[e]!="function")return null;try{return this.db[e](...t)}catch{return null}}persistIdMap(){h(this._path,this.strToNum,this.nextLabel)}}});export{Q as a,U as b,X as c,Y as d,Z as e,P as f};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
2
+ import{c as b,e as v,g as T}from"./chunk-C2HGOUEB.js";var y={};v(y,{DotProductAttention:()=>z,FlashAttention:()=>k,HyperbolicAttention:()=>W,LinearAttention:()=>j,MoEAttention:()=>K,MultiHeadAttention:()=>F,RuvectorLayer:()=>_,SonaEngine:()=>q,TensorCompress:()=>E,default:()=>O,differentiableSearch:()=>L,getCompressionLevel:()=>B,hierarchicalForward:()=>V,init:()=>D,pipeline:()=>J});import{createRequire as A}from"module";var I,g,O,_,E,L,V,B,D,k,z,F,W,j,K,q,J,S=b(()=>{I=A(import.meta.url),g=I("@ruvector/rvf-node"),O=g,{RuvectorLayer:_,TensorCompress:E,differentiableSearch:L,hierarchicalForward:V,getCompressionLevel:B,init:D,FlashAttention:k,DotProductAttention:z,MultiHeadAttention:F,HyperbolicAttention:W,LinearAttention:j,MoEAttention:K,SonaEngine:q,pipeline:J}=g||{}});var Z={};v(Z,{createRvfStore:()=>Q,isRvfNativeAvailable:()=>Y,openRvfStore:()=>U,openRvfStoreReadonly:()=>X});import{readFileSync as C,writeFileSync as H,copyFileSync as $,existsSync as G}from"fs";function l(){if(R)return f;R=!0;try{let i=(S(),T(y));!i.RvfDatabase&&i.default&&i.default.RvfDatabase&&(i=i.default),f=i}catch{f=null}return f}function w(i){return`${i}.idmap.json`}function N(i){let e=w(i),t=new Map,n=new Map,s=1;if(G(e))try{let r=JSON.parse(C(e,"utf-8"));s=r.nextLabel;for(let[a,m]of r.entries)t.set(a,m),n.set(m,a)}catch{}return{strToNum:t,numToStr:n,nextLabel:s}}function h(i,e,t){let n={nextLabel:t,entries:Array.from(e.entries())};H(w(i),JSON.stringify(n),"utf-8")}function Q(i,e){let t=l();if(!t)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let n=t.RvfDatabase.create(i,{dimension:e}),s=n.dimension();return new d(n,i,s,new Map,new Map,1)}function U(i){let e=l();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.open(i),n=t.dimension(),{strToNum:s,numToStr:r,nextLabel:a}=N(i);return new d(t,i,n,s,r,a)}function X(i){let e=l();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.openReadonly(i),n=t.dimension(),{strToNum:s,numToStr:r,nextLabel:a}=N(i);return new d(t,i,n,s,r,a)}function Y(){return l()!==null}var f,R,d,P=b(()=>{f=null,R=!1;d=class i{db;_path;_dimension;strToNum;numToStr;nextLabel;_open;constructor(e,t,n,s,r,a){this.db=e,this._path=t,this._dimension=n,this.strToNum=s,this.numToStr=r,this.nextLabel=a,this._open=!0}ingest(e){if(this.ensureOpen(),e.length===0)return{accepted:0,rejected:0};let t=this._dimension,n=new Float32Array(e.length*t),s=[],r=[];for(let o=0;o<e.length;o++){let{id:u,vector:p,metadata:x}=e[o],c=this.strToNum.get(u);c===void 0&&(c=this.nextLabel++,this.strToNum.set(u,c),this.numToStr.set(c,u)),s.push(c),r.push(x);let M=p instanceof Float32Array?p:new Float32Array(p);n.set(M.subarray(0,t),o*t)}let a;if(r.some(o=>o!==void 0)&&typeof this.db.ingestBatchWithMetadata=="function"){let o=r.map(u=>u?JSON.stringify(u):"");a=this.db.ingestBatchWithMetadata(n,s,o)}else a=this.db.ingestBatch(n,s);return this.persistIdMap(),{accepted:a.accepted,rejected:a.rejected}}search(e,t){this.ensureOpen();let n=e instanceof Float32Array?e:new Float32Array(e);return this.db.query(n,t).map(r=>{let a=this.numToStr.get(r.id);return a===void 0?null:{id:a,distance:r.distance,score:1/(1+r.distance)}}).filter(r=>r!==null)}delete(e){this.ensureOpen();let t=[];for(let s of e){let r=this.strToNum.get(s);r!==void 0&&t.push(r)}if(t.length===0)return 0;let n=this.db.delete(t);for(let s of e){let r=this.strToNum.get(s);r!==void 0&&(this.strToNum.delete(s),this.numToStr.delete(r))}return this.persistIdMap(),n.deleted}fork(e){this.ensureOpen(),$(this._path,e);let t=new Map(this.strToNum),n=new Map(this.numToStr);h(e,t,this.nextLabel);let r=l().RvfDatabase.open(e);return new i(r,e,this._dimension,t,n,this.nextLabel)}status(){this.ensureOpen();let e=this.db.status(),n=this.db.segments().filter(s=>s.segType==="witness");return{totalVectors:e.totalVectors,totalSegments:e.totalSegments,fileSizeBytes:e.fileSize,epoch:e.currentEpoch,witnessValid:n.length>0,witnessEntries:n.length}}dimension(){return this._dimension}size(){return this.ensureOpen(),this.db.status().totalVectors}compact(){this.ensureOpen(),this.db.compact()}close(){this._open&&(this.db.close(),this._open=!1)}isOpen(){return this._open}path(){return this._path}embedKernel(e){return this.ensureOpen(),this.db.embedKernel(0,99,0,e,0,"")}extractKernel(){return this.ensureOpen(),this.db.extractKernel()}verifyWitness(){this.ensureOpen();let e=this.tryNative("verifyWitness");return e?{valid:e.valid??!0,totalEntries:e.totalEntries??0,errors:Array.isArray(e.errors)?e.errors:[]}:{valid:!0,totalEntries:0,errors:[]}}sign(e){this.ensureOpen();let t=this.tryNative("sign",e);return typeof t=="string"?t:null}fileId(){this.ensureOpen();let e=this.tryNative("fileId");return typeof e=="string"?e:null}parentId(){this.ensureOpen();let e=this.tryNative("parentId");return typeof e=="string"?e:null}lineageDepth(){this.ensureOpen();let e=this.tryNative("lineageDepth");return typeof e=="number"?e:0}indexStats(){let e=this.status();return{totalVectors:e.totalVectors,dimension:this._dimension,totalSegments:e.totalSegments,fileSizeBytes:e.fileSizeBytes,epoch:e.epoch,witnessValid:e.witnessValid,witnessEntries:e.witnessEntries,idMapSize:this.strToNum.size}}freeze(){this.ensureOpen();let e=this.tryNative("freeze");return typeof e=="number"?e:0}derive(e){this.ensureOpen();let t=l();if(typeof this.db.derive=="function")try{let n=this.db.derive(e),s=new Map(this.strToNum),r=new Map(this.numToStr);return h(e,s,this.nextLabel),new i(n,e,this._dimension,s,r,this.nextLabel)}catch{}return this.fork(e)}ensureOpen(){if(!this._open)throw new Error("RVF database is closed")}tryNative(e,...t){if(typeof this.db[e]!="function")return null;try{return this.db[e](...t)}catch{return null}}persistIdMap(){h(this._path,this.strToNum,this.nextLabel)}}});export{Q as a,U as b,X as c,Y as d,Z as e,P as f};
@@ -1 +1 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
2
- import{c as _}from"./chunk-QAXJOCTW.js";import{a as w}from"./chunk-53YFAERL.js";import{k as M,o as U}from"./chunk-LQDAH47F.js";import{b as f,d as F}from"./chunk-CU36MONI.js";import{a as g,c as P}from"./chunk-OXR2FPHK.js";import{randomUUID as Q}from"crypto";U();F();P();var x={alpha:.1,minOutcomes:10,weightFloor:.2,weightCeiling:2},b=class{records=new Map;config;constructor(e){this.config={...x,...e}}recordOutcome(e,t,o){let{alpha:i,minOutcomes:r,weightFloor:s,weightCeiling:n}=this.config,u=this.records.get(e),d=t?1:0,a=Math.max(0,Math.min(1,o)),l,c;u?(l=i*d+(1-i)*u.emaAccuracy,c=i*a+(1-i)*u.emaQuality):(l=d,c=a);let h=(u?.totalOutcomes??0)+1,R;h>=r?R=Math.max(s,Math.min(n,l*2)):R=1;let k={agentId:e,emaAccuracy:l,emaQuality:c,calibratedWeight:R,totalOutcomes:h,lastUpdated:new Date};return this.records.set(e,k),k}getCalibration(e){return this.records.get(e)??null}getCalibratedWeight(e){let t=this.records.get(e);return!t||t.totalOutcomes<this.config.minOutcomes?1:t.calibratedWeight}getAllCalibrations(){return Array.from(this.records.values())}reset(e){e!==void 0?this.records.delete(e):this.records.clear()}serialize(){let e={};for(let[t,o]of this.records)e[t]={...o};return e}deserialize(e){this.records.clear();for(let[t,o]of Object.entries(e))this.records.set(t,{...o,lastUpdated:new Date(o.lastUpdated)})}};var D={escalateAfterFailures:2,deEscalateAfterSuccesses:5,maxTier:"opus",minTier:"haiku"},A=["booster","haiku","sonnet","opus"];function y(m){return A.indexOf(m)}var p=class{config;states=new Map;constructor(e){this.config={...D,...e}}recordOutcome(e,t,o){let i=this.states.get(e);i||(i={agentId:e,currentTier:o,baseTier:o,consecutiveFailures:0,consecutiveSuccesses:0,escalationCount:0,deEscalationCount:0,lastAction:"none",lastActionTimestamp:new Date},this.states.set(e,i));let r=i.currentTier;if(t){if(i.consecutiveSuccesses++,i.consecutiveFailures=0,i.consecutiveSuccesses>=this.config.deEscalateAfterSuccesses){let s=y(i.currentTier),n=y(this.config.minTier);if(s>n)return i.currentTier=A[s-1],i.deEscalationCount++,i.consecutiveSuccesses=0,i.lastAction="de-escalate",i.lastActionTimestamp=new Date,{action:"de-escalate",previousTier:r,newTier:i.currentTier}}}else if(i.consecutiveFailures++,i.consecutiveSuccesses=0,i.consecutiveFailures>=this.config.escalateAfterFailures){let s=y(i.currentTier),n=y(this.config.maxTier);if(s<n)return i.currentTier=A[s+1],i.escalationCount++,i.consecutiveFailures=0,i.lastAction="escalate",i.lastActionTimestamp=new Date,{action:"escalate",previousTier:r,newTier:i.currentTier}}return{action:"none",previousTier:r,newTier:i.currentTier}}getCurrentTier(e){return this.states.get(e)?.currentTier??null}getState(e){return this.states.get(e)??null}getAllStates(){return Array.from(this.states.values())}reset(e){e?this.states.delete(e):this.states.clear()}};var T={booster:{avgInputTokens:0,avgOutputTokens:0,costPerTask:0},haiku:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.0035},sonnet:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.021},opus:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.105}},v=["booster","haiku","sonnet","opus"],E=T.opus.costPerTask,q={qualityWeight:.6,costWeight:.4,budgetPerHourUsd:0,budgetPerDayUsd:0,minQualityThreshold:.5,enabled:!0},I=.15,C=class{config;costTracker;tierQualityEstimates=new Map;tierOutcomeCounts=new Map;constructor(e,t){let o={...q,...t};o.qualityWeight=Math.max(0,Math.min(1,o.qualityWeight)),o.costWeight=Math.max(0,Math.min(1,o.costWeight)),o.minQualityThreshold=Math.max(0,Math.min(1,o.minQualityThreshold)),o.budgetPerHourUsd=Math.max(0,o.budgetPerHourUsd),o.budgetPerDayUsd=Math.max(0,o.budgetPerDayUsd);let i=o.qualityWeight+o.costWeight;i>0&&i!==1&&(o.qualityWeight/=i,o.costWeight/=i),this.config=o,this.costTracker=e,this.tierQualityEstimates.set("booster",.3),this.tierQualityEstimates.set("haiku",.55),this.tierQualityEstimates.set("sonnet",.75),this.tierQualityEstimates.set("opus",.9)}scoreTiers(e){let t=v.map(o=>{let i=this.getQualityEstimate(o,e),r=T[o].costPerTask,s=r>0?i/r:i>0?1/0:0,n=E>0?1-r/E:1,u=this.config.qualityWeight*i+this.config.costWeight*n;return{tier:o,qualityScore:i,estimatedCostUsd:r,qualityPerDollar:s,economicScore:u}});return t.sort((o,i)=>i.economicScore-o.economicScore),t}selectTier(e){let t=this.scoreTiers(e);for(let r of t)if(!(r.qualityScore<this.config.minQualityThreshold)&&!this.wouldExceedBudget(r.tier))return{tier:r.tier,reason:`Best economic score (${r.economicScore.toFixed(3)}): quality=${r.qualityScore.toFixed(2)}, cost=$${r.estimatedCostUsd.toFixed(4)}`,scores:t};let o=t.filter(r=>r.qualityScore>=this.config.minQualityThreshold);if(o.length>0){let r=[...o].sort((s,n)=>s.estimatedCostUsd-n.estimatedCostUsd)[0];return{tier:r.tier,reason:`Budget constrained fallback to ${r.tier}`,scores:t}}let i=[...t].sort((r,s)=>s.qualityScore-r.qualityScore)[0];return{tier:i.tier,reason:`No tier meets quality threshold ${this.config.minQualityThreshold}; using best quality: ${i.tier}`,scores:t}}wouldExceedBudget(e){let t=T[e].costPerTask;if(t===0)return!1;let o=this.costTracker.getCurrentCost("hour"),i=this.costTracker.getCurrentCost("day");return this.config.budgetPerHourUsd>0&&o+t>this.config.budgetPerHourUsd||this.config.budgetPerDayUsd>0&&i+t>this.config.budgetPerDayUsd}updateFromOutcome(e,t){let o=e.outcome.qualityScore,i=this.tierQualityEstimates.get(t)??.5,r=this.tierOutcomeCounts.get(t)??0,s=r<5?.4:I,n=i*(1-s)+o*s;this.tierQualityEstimates.set(t,n),this.tierOutcomeCounts.set(t,r+1)}getEconomicReport(){let e=this.scoreTiers(.5),t=this.costTracker.getCurrentCost("hour"),o=this.costTracker.getCurrentCost("day"),i={hourly:this.config.budgetPerHourUsd>0?Math.max(0,this.config.budgetPerHourUsd-t):null,daily:this.config.budgetPerDayUsd>0?Math.max(0,this.config.budgetPerDayUsd-o):null},r=null,s=[...e].sort((a,l)=>l.qualityPerDollar-a.qualityPerDollar),n=s.find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar)),u=[...s].reverse().find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar));if(n&&u&&n.tier!==u.tier){let a=u.estimatedCostUsd-n.estimatedCostUsd;a>0&&(r={usd:a,description:`Switch from ${u.tier} ($${u.estimatedCostUsd.toFixed(4)}/task) to ${n.tier} ($${n.estimatedCostUsd.toFixed(4)}/task) for comparable tasks to save ~$${a.toFixed(4)}/task`})}let d=this.generateRecommendation(e,i);return{tierEfficiency:e,currentHourlyCostUsd:t,currentDailyCostUsd:o,budgetRemaining:i,recommendation:d,savingsOpportunity:r}}computeCostAdjustedReward(e,t,o){let i=T[t].costPerTask;if(E===0)return e;let r=i/E,s=Math.max(0,o-this.config.minQualityThreshold),n=r*(1-s),u=e-n*this.config.costWeight;return Math.max(-1,Math.min(1,u))}serializeEstimates(){let e={};for(let t of v)e[t]={quality:this.tierQualityEstimates.get(t)??.5,count:this.tierOutcomeCounts.get(t)??0};return e}deserializeEstimates(e){for(let t of v)e[t]&&(this.tierQualityEstimates.set(t,e[t].quality),this.tierOutcomeCounts.set(t,e[t].count))}getConfig(){return{...this.config}}getQualityEstimate(e,t){let o=this.tierQualityEstimates.get(e)??.5,i=e==="booster"?t*.4:e==="haiku"?t*.2:0;return Math.max(0,Math.min(1,o-i))}generateRecommendation(e,t){if(t.hourly!==null&&t.hourly<.01)return"Hourly budget nearly exhausted. Consider increasing budget or routing to cheaper tiers.";if(t.daily!==null&&t.daily<.1)return"Daily budget nearly exhausted. Only critical tasks should use expensive tiers.";let o=e[0];return o?`Most cost-efficient tier: ${o.tier} (score=${o.economicScore.toFixed(3)}, quality=${o.qualityScore.toFixed(2)})`:"No economic data available yet."}};var S=class{outcomes=[];maxOutcomes;constructor(e=1e4){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getByAgent(e,t=100){return this.outcomes.filter(o=>o.usedAgent===e).slice(-t)}getAll(e=1e3){return this.outcomes.slice(-e)}getRecentOverrides(e=50){return this.outcomes.filter(t=>!t.followedRecommendation).slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},O=class m{outcomeStore;router=null;db=null;calibrator=null;escalationTracker=null;economicModel=null;economicPersistCounter=0;static ECONOMIC_PERSIST_INTERVAL=10;persistCount=0;maxOutcomes;static RETENTION_CLEANUP_INTERVAL=100;constructor(e=1e4,t){this.maxOutcomes=e,this.outcomeStore=new S(e),t?.enableEMACalibration&&this.enableCalibration(),t?.enableAutoEscalation&&this.enableAutoEscalation()}async initialize(){try{this.db=M(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb(),this.loadCalibratorState()}catch(e){console.warn("[RoutingFeedbackCollector] DB init failed, using memory-only:",g(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().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.9.4");process.exit(0)}
2
+ import{c as _}from"./chunk-NZ5LY2BT.js";import{a as w}from"./chunk-3SPYUOSS.js";import{k as M,o as U}from"./chunk-G6RTCJFY.js";import{b as f,d as F}from"./chunk-4GJAYXB7.js";import{a as g,c as P}from"./chunk-F6AU2MAZ.js";import{randomUUID as Q}from"crypto";U();F();P();var x={alpha:.1,minOutcomes:10,weightFloor:.2,weightCeiling:2},b=class{records=new Map;config;constructor(e){this.config={...x,...e}}recordOutcome(e,t,o){let{alpha:i,minOutcomes:r,weightFloor:s,weightCeiling:n}=this.config,u=this.records.get(e),d=t?1:0,a=Math.max(0,Math.min(1,o)),l,c;u?(l=i*d+(1-i)*u.emaAccuracy,c=i*a+(1-i)*u.emaQuality):(l=d,c=a);let h=(u?.totalOutcomes??0)+1,R;h>=r?R=Math.max(s,Math.min(n,l*2)):R=1;let k={agentId:e,emaAccuracy:l,emaQuality:c,calibratedWeight:R,totalOutcomes:h,lastUpdated:new Date};return this.records.set(e,k),k}getCalibration(e){return this.records.get(e)??null}getCalibratedWeight(e){let t=this.records.get(e);return!t||t.totalOutcomes<this.config.minOutcomes?1:t.calibratedWeight}getAllCalibrations(){return Array.from(this.records.values())}reset(e){e!==void 0?this.records.delete(e):this.records.clear()}serialize(){let e={};for(let[t,o]of this.records)e[t]={...o};return e}deserialize(e){this.records.clear();for(let[t,o]of Object.entries(e))this.records.set(t,{...o,lastUpdated:new Date(o.lastUpdated)})}};var D={escalateAfterFailures:2,deEscalateAfterSuccesses:5,maxTier:"opus",minTier:"haiku"},A=["booster","haiku","sonnet","opus"];function y(m){return A.indexOf(m)}var p=class{config;states=new Map;constructor(e){this.config={...D,...e}}recordOutcome(e,t,o){let i=this.states.get(e);i||(i={agentId:e,currentTier:o,baseTier:o,consecutiveFailures:0,consecutiveSuccesses:0,escalationCount:0,deEscalationCount:0,lastAction:"none",lastActionTimestamp:new Date},this.states.set(e,i));let r=i.currentTier;if(t){if(i.consecutiveSuccesses++,i.consecutiveFailures=0,i.consecutiveSuccesses>=this.config.deEscalateAfterSuccesses){let s=y(i.currentTier),n=y(this.config.minTier);if(s>n)return i.currentTier=A[s-1],i.deEscalationCount++,i.consecutiveSuccesses=0,i.lastAction="de-escalate",i.lastActionTimestamp=new Date,{action:"de-escalate",previousTier:r,newTier:i.currentTier}}}else if(i.consecutiveFailures++,i.consecutiveSuccesses=0,i.consecutiveFailures>=this.config.escalateAfterFailures){let s=y(i.currentTier),n=y(this.config.maxTier);if(s<n)return i.currentTier=A[s+1],i.escalationCount++,i.consecutiveFailures=0,i.lastAction="escalate",i.lastActionTimestamp=new Date,{action:"escalate",previousTier:r,newTier:i.currentTier}}return{action:"none",previousTier:r,newTier:i.currentTier}}getCurrentTier(e){return this.states.get(e)?.currentTier??null}getState(e){return this.states.get(e)??null}getAllStates(){return Array.from(this.states.values())}reset(e){e?this.states.delete(e):this.states.clear()}};var T={booster:{avgInputTokens:0,avgOutputTokens:0,costPerTask:0},haiku:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.0035},sonnet:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.021},opus:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.105}},v=["booster","haiku","sonnet","opus"],E=T.opus.costPerTask,q={qualityWeight:.6,costWeight:.4,budgetPerHourUsd:0,budgetPerDayUsd:0,minQualityThreshold:.5,enabled:!0},I=.15,C=class{config;costTracker;tierQualityEstimates=new Map;tierOutcomeCounts=new Map;constructor(e,t){let o={...q,...t};o.qualityWeight=Math.max(0,Math.min(1,o.qualityWeight)),o.costWeight=Math.max(0,Math.min(1,o.costWeight)),o.minQualityThreshold=Math.max(0,Math.min(1,o.minQualityThreshold)),o.budgetPerHourUsd=Math.max(0,o.budgetPerHourUsd),o.budgetPerDayUsd=Math.max(0,o.budgetPerDayUsd);let i=o.qualityWeight+o.costWeight;i>0&&i!==1&&(o.qualityWeight/=i,o.costWeight/=i),this.config=o,this.costTracker=e,this.tierQualityEstimates.set("booster",.3),this.tierQualityEstimates.set("haiku",.55),this.tierQualityEstimates.set("sonnet",.75),this.tierQualityEstimates.set("opus",.9)}scoreTiers(e){let t=v.map(o=>{let i=this.getQualityEstimate(o,e),r=T[o].costPerTask,s=r>0?i/r:i>0?1/0:0,n=E>0?1-r/E:1,u=this.config.qualityWeight*i+this.config.costWeight*n;return{tier:o,qualityScore:i,estimatedCostUsd:r,qualityPerDollar:s,economicScore:u}});return t.sort((o,i)=>i.economicScore-o.economicScore),t}selectTier(e){let t=this.scoreTiers(e);for(let r of t)if(!(r.qualityScore<this.config.minQualityThreshold)&&!this.wouldExceedBudget(r.tier))return{tier:r.tier,reason:`Best economic score (${r.economicScore.toFixed(3)}): quality=${r.qualityScore.toFixed(2)}, cost=$${r.estimatedCostUsd.toFixed(4)}`,scores:t};let o=t.filter(r=>r.qualityScore>=this.config.minQualityThreshold);if(o.length>0){let r=[...o].sort((s,n)=>s.estimatedCostUsd-n.estimatedCostUsd)[0];return{tier:r.tier,reason:`Budget constrained fallback to ${r.tier}`,scores:t}}let i=[...t].sort((r,s)=>s.qualityScore-r.qualityScore)[0];return{tier:i.tier,reason:`No tier meets quality threshold ${this.config.minQualityThreshold}; using best quality: ${i.tier}`,scores:t}}wouldExceedBudget(e){let t=T[e].costPerTask;if(t===0)return!1;let o=this.costTracker.getCurrentCost("hour"),i=this.costTracker.getCurrentCost("day");return this.config.budgetPerHourUsd>0&&o+t>this.config.budgetPerHourUsd||this.config.budgetPerDayUsd>0&&i+t>this.config.budgetPerDayUsd}updateFromOutcome(e,t){let o=e.outcome.qualityScore,i=this.tierQualityEstimates.get(t)??.5,r=this.tierOutcomeCounts.get(t)??0,s=r<5?.4:I,n=i*(1-s)+o*s;this.tierQualityEstimates.set(t,n),this.tierOutcomeCounts.set(t,r+1)}getEconomicReport(){let e=this.scoreTiers(.5),t=this.costTracker.getCurrentCost("hour"),o=this.costTracker.getCurrentCost("day"),i={hourly:this.config.budgetPerHourUsd>0?Math.max(0,this.config.budgetPerHourUsd-t):null,daily:this.config.budgetPerDayUsd>0?Math.max(0,this.config.budgetPerDayUsd-o):null},r=null,s=[...e].sort((a,l)=>l.qualityPerDollar-a.qualityPerDollar),n=s.find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar)),u=[...s].reverse().find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar));if(n&&u&&n.tier!==u.tier){let a=u.estimatedCostUsd-n.estimatedCostUsd;a>0&&(r={usd:a,description:`Switch from ${u.tier} ($${u.estimatedCostUsd.toFixed(4)}/task) to ${n.tier} ($${n.estimatedCostUsd.toFixed(4)}/task) for comparable tasks to save ~$${a.toFixed(4)}/task`})}let d=this.generateRecommendation(e,i);return{tierEfficiency:e,currentHourlyCostUsd:t,currentDailyCostUsd:o,budgetRemaining:i,recommendation:d,savingsOpportunity:r}}computeCostAdjustedReward(e,t,o){let i=T[t].costPerTask;if(E===0)return e;let r=i/E,s=Math.max(0,o-this.config.minQualityThreshold),n=r*(1-s),u=e-n*this.config.costWeight;return Math.max(-1,Math.min(1,u))}serializeEstimates(){let e={};for(let t of v)e[t]={quality:this.tierQualityEstimates.get(t)??.5,count:this.tierOutcomeCounts.get(t)??0};return e}deserializeEstimates(e){for(let t of v)e[t]&&(this.tierQualityEstimates.set(t,e[t].quality),this.tierOutcomeCounts.set(t,e[t].count))}getConfig(){return{...this.config}}getQualityEstimate(e,t){let o=this.tierQualityEstimates.get(e)??.5,i=e==="booster"?t*.4:e==="haiku"?t*.2:0;return Math.max(0,Math.min(1,o-i))}generateRecommendation(e,t){if(t.hourly!==null&&t.hourly<.01)return"Hourly budget nearly exhausted. Consider increasing budget or routing to cheaper tiers.";if(t.daily!==null&&t.daily<.1)return"Daily budget nearly exhausted. Only critical tasks should use expensive tiers.";let o=e[0];return o?`Most cost-efficient tier: ${o.tier} (score=${o.economicScore.toFixed(3)}, quality=${o.qualityScore.toFixed(2)})`:"No economic data available yet."}};var S=class{outcomes=[];maxOutcomes;constructor(e=1e4){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getByAgent(e,t=100){return this.outcomes.filter(o=>o.usedAgent===e).slice(-t)}getAll(e=1e3){return this.outcomes.slice(-e)}getRecentOverrides(e=50){return this.outcomes.filter(t=>!t.followedRecommendation).slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},O=class m{outcomeStore;router=null;db=null;calibrator=null;escalationTracker=null;economicModel=null;economicPersistCounter=0;static ECONOMIC_PERSIST_INTERVAL=10;persistCount=0;maxOutcomes;static RETENTION_CLEANUP_INTERVAL=100;constructor(e=1e4,t){this.maxOutcomes=e,this.outcomeStore=new S(e),t?.enableEMACalibration&&this.enableCalibration(),t?.enableAutoEscalation&&this.enableAutoEscalation()}async initialize(){try{this.db=M(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb(),this.loadCalibratorState()}catch(e){console.warn("[RoutingFeedbackCollector] DB init failed, using memory-only:",g(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
3
3
  SELECT * FROM routing_outcomes ORDER BY created_at DESC LIMIT ?
4
4
  `).all(this.maxOutcomes);for(let o of t.reverse()){let i={id:o.id,task:f(o.task_json),decision:f(o.decision_json),usedAgent:o.used_agent,followedRecommendation:!!o.followed_recommendation,outcome:{success:!!o.success,qualityScore:o.quality_score,durationMs:o.duration_ms,error:o.error||void 0},timestamp:new Date(o.created_at)};this.outcomeStore.add(i)}t.length>0&&console.log(`[RoutingFeedbackCollector] Loaded ${t.length} outcomes from DB`)}persistOutcome(e){if(this.db)try{let t=this.db.getDatabase();try{t.prepare("ALTER TABLE routing_outcomes ADD COLUMN model_tier TEXT").run()}catch{}let o=this.inferTier(e.usedAgent);t.prepare(`
5
5
  INSERT OR REPLACE INTO routing_outcomes (
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
2
- import{a as L}from"./chunk-TA454OEB.js";import*as w from"fs";var R={"aqe test generate":{domain:"test-generation",action:"generateTests"},"aqe test execute":{domain:"test-execution",action:"execute"},"aqe coverage analyze":{domain:"coverage-analysis",action:"analyze"},"aqe coverage gaps":{domain:"coverage-analysis",action:"detectGaps"},"aqe quality gate":{domain:"quality-assessment",action:"evaluateGate"},"aqe quality assess":{domain:"quality-assessment",action:"analyzeQuality"},"aqe security scan":{domain:"security-compliance",action:"runSASTScan"},"aqe security audit":{domain:"security-compliance",action:"runAudit"},"aqe defect predict":{domain:"defect-intelligence",action:"predictDefects"},"aqe code index":{domain:"code-intelligence",action:"index"},"aqe code impact":{domain:"code-intelligence",action:"analyzeImpact"},"aqe contract validate":{domain:"contract-testing",action:"validateContract"},"aqe chaos test":{domain:"chaos-resilience",action:"runChaosTest"},"aqe requirements validate":{domain:"requirements-validation",action:"validateRequirements"},"aqe visual test":{domain:"visual-accessibility",action:"runVisualTest"},"aqe accessibility test":{domain:"visual-accessibility",action:"runAccessibilityTest"},"aqe learn optimize":{domain:"learning-optimization",action:"optimizeAllStrategies"}},D={daily:"0 0 * * *",weekly:"0 0 * * 0",hourly:"0 * * * *",minutely:"* * * * *"},S=1e4,x=20,M=1e4,W=["__proto__","constructor","prototype"];function v(t){return!W.includes(t)}function C(t){let n=t.split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.4");process.exit(0)}
2
+ import{a as L}from"./chunk-VBYREHZI.js";import*as w from"fs";var R={"aqe test generate":{domain:"test-generation",action:"generateTests"},"aqe test execute":{domain:"test-execution",action:"execute"},"aqe coverage analyze":{domain:"coverage-analysis",action:"analyze"},"aqe coverage gaps":{domain:"coverage-analysis",action:"detectGaps"},"aqe quality gate":{domain:"quality-assessment",action:"evaluateGate"},"aqe quality assess":{domain:"quality-assessment",action:"analyzeQuality"},"aqe security scan":{domain:"security-compliance",action:"runSASTScan"},"aqe security audit":{domain:"security-compliance",action:"runAudit"},"aqe defect predict":{domain:"defect-intelligence",action:"predictDefects"},"aqe code index":{domain:"code-intelligence",action:"index"},"aqe code impact":{domain:"code-intelligence",action:"analyzeImpact"},"aqe contract validate":{domain:"contract-testing",action:"validateContract"},"aqe chaos test":{domain:"chaos-resilience",action:"runChaosTest"},"aqe requirements validate":{domain:"requirements-validation",action:"validateRequirements"},"aqe visual test":{domain:"visual-accessibility",action:"runVisualTest"},"aqe accessibility test":{domain:"visual-accessibility",action:"runAccessibilityTest"},"aqe learn optimize":{domain:"learning-optimization",action:"optimizeAllStrategies"}},D={daily:"0 0 * * *",weekly:"0 0 * * 0",hourly:"0 * * * *",minutely:"* * * * *"},S=1e4,x=20,M=1e4,W=["__proto__","constructor","prototype"];function v(t){return!W.includes(t)}function C(t){let n=t.split(`
3
3
  `);if(n.length>S)throw new Error(`YAML content exceeds maximum allowed lines (${S}). File has ${n.length} lines.`);for(let i=0;i<n.length;i++)if(n[i].length>M)throw new Error(`YAML line ${i+1} exceeds maximum allowed length (${M} characters).`);let a={};for(let i=0;i<n.length;i++){let e=n[i];if(e.trim()===""||e.trim().startsWith("#")||e.search(/\S/)!==0)continue;let o=e.match(/^([\w_-]+):\s*(.+)$/);if(o){let[,c,u]=o;v(c)&&(a[c]=f(u))}}let r=["tags","stages","triggers"];for(let i of r){let e=new RegExp(`^${i}:\\s*$`),s=-1;for(let l=0;l<n.length;l++){let d=n[l];if(!(d.trim()===""||d.trim().startsWith("#"))&&e.test(d.trim())){s=l;break}}if(s===-1)continue;let o=[];a[i]=o;let c=n[s].search(/\S/),u=s+1;for(;u<n.length;){let l=n[u];if(l.trim()===""||l.trim().startsWith("#")){u++;continue}let d=l.search(/\S/),p=l.trim();if(d<=c&&!p.startsWith("-"))break;if(p.startsWith("- ")){let m=p.slice(2).trim();if(!m.includes(":")){o.push(f(m)),u++;continue}let g={},k=m.match(/^([\w_-]+):\s*(.*)$/);if(k){let[,h,y]=k;g[h]=f(y)}let T=d;for(u++;u<n.length;){let h=n[u];if(h.trim()===""||h.trim().startsWith("#")){u++;continue}let y=h.search(/\S/),q=h.trim();if(y<=T)break;let _=q.match(/^([\w_-]+):\s*(.*)$/);if(_){let[,A,$]=_;if($===""){let b=E(n,u+1,y,1);g[A]=b.value,u=b.nextLine;continue}else g[A]=f($)}u++}o.push(g)}else u++}}return a}function E(t,n,a,r=0){if(r>x)throw new Error(`YAML nesting exceeds maximum allowed depth (${x}).`);let i={},e=null,s=null,o=n;for(;o<t.length;){let u=t[o];if(u.trim()===""||u.trim().startsWith("#")){o++;continue}let l=u.search(/\S/),d=u.trim();if(l<=a)break;if(d.startsWith("- ")){let m=d.slice(2).trim();s&&!Array.isArray(i[s])&&(i[s]=[]),s?i[s].push(f(m)):(e||(e=[]),e.push(f(m))),o++;continue}let p=d.match(/^([\w_-]+):\s*(.*)$/);if(p){let[,m,g]=p;if(!v(m)){o++;continue}g===""?(s=m,i[m]=[]):(i[m]=f(g),s=null)}o++}if(e&&Object.keys(i).length===0)return{value:e,nextLine:o};let c=Object.keys(i);return c.length===1&&Array.isArray(i[c[0]])?{value:i[c[0]],nextLine:o}:{value:i,nextLine:o}}function f(t){if(t==="")return"";if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t==="true")return!0;if(t==="false")return!1;if(t==="null"||t==="~")return null;let n=Number(t);return!isNaN(n)&&t!==""?n:t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1).split(",").map(r=>f(r.trim())):t}function K(t){let n=[];if(!w.existsSync(t))return{success:!1,errors:[`File not found: ${t}`]};let a;try{a=w.readFileSync(t,"utf-8")}catch(r){return{success:!1,errors:[`Failed to read file: ${r}`]}}return Y(a,t)}function Y(t,n){let a=[],r;try{r=C(t)}catch(s){return{success:!1,errors:[`Invalid YAML syntax: ${s}`]}}if((!r.name||typeof r.name!="string")&&a.push('Pipeline must have a "name" field'),(!r.stages||!Array.isArray(r.stages))&&a.push('Pipeline must have a "stages" array'),a.length>0)return{success:!1,errors:a};let i={name:r.name,description:r.description,version:r.version||"1.0.0",schedule:r.schedule,stages:r.stages.map((s,o)=>{let c=s;return{name:c.name||`stage-${o}`,command:c.command,params:c.params,depends_on:c.depends_on,condition:c.condition,timeout:c.timeout,retry:c.retry,continue_on_failure:c.continue_on_failure}}),triggers:r.triggers,tags:r.tags,timeout:r.timeout};for(let s=0;s<i.stages.length;s++){let o=i.stages[s];o.command||a.push(`Stage ${s+1} (${o.name}) must have a "command" field`)}if(a.length>0)return{success:!1,pipeline:i,errors:a};let e=O(i,n);return{success:!0,pipeline:i,workflow:e,errors:[]}}function O(t,n){let a=`pipeline-${t.name.replace(/\s+/g,"-").toLowerCase()}`,r=t.stages.map((e,s)=>{let o=P(e.command),c={};if(e.params)for(let[l,d]of Object.entries(e.params))v(l)&&(c[l]=`input.${l}`);let u={id:`stage-${e.name.replace(/\s+/g,"-").toLowerCase()}`,name:e.name,domain:o.domain,action:o.action,inputMapping:Object.keys(c).length>0?c:void 0,dependsOn:e.depends_on?.map(l=>`stage-${l.replace(/\s+/g,"-").toLowerCase()}`),timeout:e.timeout?e.timeout*1e3:void 0,continueOnFailure:e.continue_on_failure};return e.condition&&(u.condition={path:e.condition.path,operator:e.condition.operator,value:e.condition.value}),e.retry&&(u.retry={maxAttempts:e.retry.max_attempts||3,backoffMs:(e.retry.backoff_seconds||1)*1e3}),u}),i=t.triggers?.map(e=>{let s={eventType:I(e),sourceDomain:e.source_domain};return e.condition&&(s.condition={path:e.condition.path,operator:e.condition.operator,value:e.condition.value}),s});return{id:a,name:t.name,description:t.description||`Pipeline from ${n||"inline YAML"}`,version:t.version||"1.0.0",steps:r,triggers:i,tags:t.tags,timeout:t.timeout?t.timeout*1e3:void 0}}function P(t){let n=t.trim().replace(/\s+/g," ").toLowerCase();for(let[a,r]of Object.entries(R))if(n.startsWith(a.toLowerCase()))return r;return n.includes("test")&&n.includes("generate")?{domain:"test-generation",action:"generateTests"}:n.includes("test")&&(n.includes("execute")||n.includes("run"))?{domain:"test-execution",action:"execute"}:n.includes("coverage")?{domain:"coverage-analysis",action:"analyze"}:n.includes("quality")||n.includes("gate")?{domain:"quality-assessment",action:"evaluateGate"}:n.includes("security")||n.includes("scan")?{domain:"security-compliance",action:"runSASTScan"}:n.includes("defect")||n.includes("predict")?{domain:"defect-intelligence",action:"predictDefects"}:{domain:"learning-optimization",action:"runLearningCycle"}}function I(t){let n=t.event.toLowerCase();return n==="push"?"code-intelligence.CodePushed":n==="pull_request"||n==="pr"?"code-intelligence.PullRequestOpened":n==="schedule"?"workflow.ScheduleTrigger":n==="quality_gate"?"quality-assessment.QualityGateEvaluated":n==="test_complete"?"test-execution.TestRunCompleted":n}function F(t){let n=[],a=[];if(t.name||n.push({path:"name",message:"Pipeline name is required",severity:"error"}),!t.stages||t.stages.length===0)n.push({path:"stages",message:"Pipeline must have at least one stage",severity:"error"});else{let r=new Set;for(let e=0;e<t.stages.length;e++){let s=t.stages[e],o=`stages[${e}]`;if(r.has(s.name)&&n.push({path:`${o}.name`,message:`Duplicate stage name: ${s.name}`,severity:"error"}),r.add(s.name),s.command?P(s.command).domain==="learning-optimization"&&!s.command.toLowerCase().includes("learn")&&a.push({path:`${o}.command`,message:`Command "${s.command}" not recognized, will default to learning-optimization domain`,severity:"warning"}):n.push({path:`${o}.command`,message:"Stage must have a command",severity:"error"}),s.depends_on)for(let c of s.depends_on)t.stages.some(u=>u.name===c)||n.push({path:`${o}.depends_on`,message:`Unknown dependency: ${c}`,severity:"error"});s.timeout!==void 0&&s.timeout<=0&&n.push({path:`${o}.timeout`,message:"Timeout must be a positive number",severity:"error"}),s.retry&&s.retry.max_attempts!==void 0&&s.retry.max_attempts<1&&n.push({path:`${o}.retry.max_attempts`,message:"max_attempts must be at least 1",severity:"error"})}let i=N(t.stages);i&&n.push({path:"stages",message:`Circular dependency detected: ${i}`,severity:"error"})}if(t.schedule&&(z(t.schedule)||n.push({path:"schedule",message:`Invalid cron expression: ${t.schedule}`,severity:"error"})),t.triggers)for(let r=0;r<t.triggers.length;r++){let i=t.triggers[r],e=`triggers[${r}]`;i.event||n.push({path:`${e}.event`,message:"Trigger must have an event type",severity:"error"}),i.source_domain&&!L.includes(i.source_domain)&&a.push({path:`${e}.source_domain`,message:`Unknown domain: ${i.source_domain}`,severity:"warning"})}return{valid:n.length===0,errors:n,warnings:a}}function N(t){let n=new Set,a=new Set,r=(i,e)=>{if(a.has(i))return[...e,i].join(" -> ");if(n.has(i))return null;n.add(i),a.add(i);let s=t.find(o=>o.name===i);if(s?.depends_on)for(let o of s.depends_on){let c=r(o,[...e,i]);if(c)return c}return a.delete(i),null};for(let i of t){let e=r(i.name,[]);if(e)return e}return null}function z(t){if(Object.keys(D).includes(t))return!0;let n=t.trim().split(/\s+/);if(n.length!==5)return!1;let a=[/^(\*|[0-5]?\d)(-[0-5]?\d)?(\/\d+)?$/,/^(\*|1?\d|2[0-3])(-\d+)?(\/\d+)?$/,/^(\*|[1-9]|[12]\d|3[01])(-\d+)?(\/\d+)?$/,/^(\*|[1-9]|1[0-2])(-\d+)?(\/\d+)?$/,/^(\*|[0-7])(-[0-7])?(\/\d+)?$/];for(let r=0;r<5;r++){let i=n[r].split(",");for(let e of i)if(!a[r].test(e)&&e!=="*")return!1}return!0}function G(t){let n={"@daily":"Daily at midnight","@weekly":"Weekly on Sunday at midnight","@hourly":"Every hour","@minutely":"Every minute"};if(n[t])return n[t];if(Object.keys(D).includes(t))return{daily:"Daily at midnight",weekly:"Weekly on Sunday at midnight",hourly:"Every hour",minutely:"Every minute"}[t]||t;let a=t.trim().split(/\s+/);if(a.length!==5)return t;let[r,i,e,s,o]=a;return r==="0"&&i==="0"&&e==="*"&&s==="*"&&o==="*"?"Daily at midnight":r==="0"&&e==="*"&&s==="*"&&o==="*"?`Daily at ${i}:00`:r!=="*"&&i!=="*"&&e==="*"&&s==="*"?`Daily at ${i}:${r.padStart(2,"0")}`:i==="*"&&r==="0"?"Every hour":r!=="*"&&i==="*"?`Every hour at minute ${r}`:t}function H(t,n=new Date){let a=t.trim().split(/\s+/);if(a.length!==5)return new Date(n.getTime()+1440*60*1e3);let[r,i]=a,e=new Date(n);return i!=="*"&&r!=="*"?(e.setHours(parseInt(i,10),parseInt(r,10),0,0),e<=n&&e.setDate(e.getDate()+1)):i!=="*"?(e.setHours(parseInt(i,10),0,0,0),e<=n&&e.setDate(e.getDate()+1)):r!=="*"?(e.setMinutes(parseInt(r,10),0,0),e<=n&&e.setHours(e.getHours()+1)):(e.setSeconds(0,0),e.setMinutes(e.getMinutes()+1)),e}export{C as a,K as b,F as c,G as d,H as e};