agentic-qe 3.10.1 → 3.10.3

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 (412) hide show
  1. package/.claude/hooks/README.txt +17 -0
  2. package/.claude/hooks/aqe-hook.cjs +98 -0
  3. package/.claude/hooks/cross-phase-memory.yaml +296 -0
  4. package/.claude/hooks/post-task-sync.sh +113 -0
  5. package/.claude/hooks/v3-domain-workers.json +121 -0
  6. package/.claude/skills/release/SKILL.md +10 -10
  7. package/.claude/skills/skills-manifest.json +1 -1
  8. package/CHANGELOG.md +131 -0
  9. package/assets/grammars/tree-sitter-c_sharp.wasm +0 -0
  10. package/assets/grammars/tree-sitter-java.wasm +0 -0
  11. package/assets/grammars/tree-sitter-javascript.wasm +0 -0
  12. package/assets/grammars/tree-sitter-python.wasm +0 -0
  13. package/assets/grammars/tree-sitter-rust.wasm +0 -0
  14. package/assets/grammars/tree-sitter-swift.wasm +0 -0
  15. package/assets/grammars/tree-sitter-tsx.wasm +0 -0
  16. package/assets/grammars/tree-sitter-typescript.wasm +0 -0
  17. package/assets/skills/skills-manifest.json +1 -1
  18. package/dist/agents/claim-verifier/claim-verifier-service.js +4 -2
  19. package/dist/agents/claim-verifier/verifiers/test-verifier.js +31 -23
  20. package/dist/agents/devils-advocate/agent.js +1 -1
  21. package/dist/cli/bundle.js +5 -5
  22. package/dist/cli/chunks/adapter-BHPUKMJ5.js +2 -0
  23. package/dist/cli/chunks/{agent-booster-wasm-FZLWOPSX.js → agent-booster-wasm-NGC6LSQP.js} +2 -2
  24. package/dist/cli/chunks/{agent-handler-KAGRVCKS.js → agent-handler-P2IJE4GK.js} +2 -2
  25. package/dist/cli/chunks/{agent-memory-branch-JJKFEXQW.js → agent-memory-branch-JXRJ5GKQ.js} +2 -2
  26. package/dist/cli/chunks/aqe-learning-engine-JQ5WD2HM.js +2 -0
  27. package/dist/cli/chunks/{audit-DN5SY4JJ.js → audit-BMQ3VESB.js} +2 -2
  28. package/dist/cli/chunks/base-E32WLGY2.js +2 -0
  29. package/dist/cli/chunks/{hnswlib-node-YX6OOBN6.js → better-sqlite3-HP4JZS6K.js} +2 -2
  30. package/dist/cli/chunks/{brain-handler-O7MP5BGY.js → brain-handler-SACNDFSW.js} +3 -3
  31. package/dist/cli/chunks/{branch-enumerator-ZPTN5J6V.js → branch-enumerator-LFOTVUDA.js} +2 -2
  32. package/dist/cli/chunks/{browser-PAZE2JSD.js → browser-FK7PRF3W.js} +2 -2
  33. package/dist/cli/chunks/browser-workflow-LNNXXAJG.js +2 -0
  34. package/dist/cli/chunks/{chunk-BF7MUYWC.js → chunk-2EQVYYBF.js} +2 -2
  35. package/dist/cli/chunks/{chunk-BGBSYF3K.js → chunk-2L73WXA4.js} +2 -2
  36. package/dist/cli/chunks/{chunk-W2DT3CDE.js → chunk-2ULVCLOW.js} +2 -2
  37. package/dist/cli/chunks/{chunk-FJSR2U65.js → chunk-3HBWDG62.js} +2 -2
  38. package/dist/cli/chunks/{chunk-WPNZSL4S.js → chunk-3JAOFKEU.js} +2 -2
  39. package/dist/cli/chunks/{chunk-2TDWCXZ6.js → chunk-3LRK7PYN.js} +2 -2
  40. package/dist/cli/chunks/{chunk-MVGVD6LS.js → chunk-3RZL4QTT.js} +2 -2
  41. package/dist/cli/chunks/chunk-3VF3HCG4.js +2 -0
  42. package/dist/cli/chunks/{chunk-6E7GI2UB.js → chunk-3X2ZQ55B.js} +4 -4
  43. package/dist/cli/chunks/{chunk-6QFONVEE.js → chunk-4CYLSXA6.js} +2 -2
  44. package/dist/cli/chunks/{chunk-VOIWDPIU.js → chunk-4OUAHZX2.js} +2 -2
  45. package/dist/cli/chunks/{chunk-EIROAH6N.js → chunk-4QFAUSWQ.js} +2 -2
  46. package/dist/cli/chunks/{chunk-ZEMXMDD3.js → chunk-5ER3COX3.js} +2 -2
  47. package/dist/cli/chunks/{chunk-ECPB7IAH.js → chunk-5EWWA4QP.js} +4 -4
  48. package/dist/cli/chunks/{chunk-AUVC3DDB.js → chunk-5G5AAEFF.js} +2 -2
  49. package/dist/cli/chunks/{chunk-RRLQFFCO.js → chunk-5IBJURYB.js} +3 -3
  50. package/dist/cli/chunks/chunk-5LON3MLI.js +2 -0
  51. package/dist/cli/chunks/{chunk-WMG5F6R6.js → chunk-5SGEOO2F.js} +2 -2
  52. package/dist/cli/chunks/{chunk-SQBB2DC6.js → chunk-6B4S7PKP.js} +3 -3
  53. package/dist/cli/chunks/{chunk-H44WD7QX.js → chunk-6FL3GN4T.js} +2 -2
  54. package/dist/cli/chunks/{chunk-7MSYTHZM.js → chunk-6GCOIIHY.js} +2 -2
  55. package/dist/cli/chunks/{chunk-KKNBYXYA.js → chunk-6Q2PPOOF.js} +1 -1
  56. package/dist/cli/chunks/{chunk-K4T3RDCB.js → chunk-6ZK24V2Y.js} +2 -2
  57. package/dist/cli/chunks/{chunk-G3BQU3Q6.js → chunk-72LE6PHL.js} +3 -3
  58. package/dist/cli/chunks/{chunk-F3OVFA6W.js → chunk-7RMZAVGO.js} +2 -2
  59. package/dist/cli/chunks/{chunk-YYWIA5FX.js → chunk-7SEHQTYD.js} +1 -1
  60. package/dist/cli/chunks/{chunk-UU2Q6XWF.js → chunk-7YYTTWGY.js} +1 -1
  61. package/dist/cli/chunks/{chunk-XKOKMS5A.js → chunk-7ZSPCGTI.js} +2 -2
  62. package/dist/cli/chunks/{chunk-RWYW573C.js → chunk-ADV4DH3W.js} +5 -5
  63. package/dist/cli/chunks/{chunk-OC3OJWLB.js → chunk-AEJVOJPT.js} +2 -2
  64. package/dist/cli/chunks/{chunk-2UN4DOBJ.js → chunk-B5MMDMH6.js} +2 -2
  65. package/dist/cli/chunks/{chunk-WQEZKAUR.js → chunk-BO2OV2RH.js} +2 -2
  66. package/dist/cli/chunks/{chunk-NPSBMDVU.js → chunk-BT3QLWII.js} +2 -2
  67. package/dist/cli/chunks/{chunk-6VQ5MFJ6.js → chunk-BWP3UVPE.js} +7 -7
  68. package/dist/cli/chunks/{chunk-SLNGJW4G.js → chunk-C6BBRM2J.js} +1 -1
  69. package/dist/cli/chunks/{chunk-4AWJ5PE4.js → chunk-CAMEFWRK.js} +1 -1
  70. package/dist/cli/chunks/{chunk-BECU52UY.js → chunk-CNEWYJKT.js} +4 -4
  71. package/dist/cli/chunks/{chunk-EO4B5GS4.js → chunk-CTDO2UB2.js} +1 -1
  72. package/dist/cli/chunks/{chunk-GTGONWGX.js → chunk-D2FBUOAR.js} +1 -1
  73. package/dist/cli/chunks/{chunk-OQP5OFRR.js → chunk-DF3MJ2YL.js} +1 -1
  74. package/dist/cli/chunks/{chunk-KEC5FBAW.js → chunk-DY5KEOHX.js} +1 -1
  75. package/dist/cli/chunks/{chunk-EBQ6YKP2.js → chunk-E2BJT6A7.js} +3 -3
  76. package/dist/cli/chunks/{chunk-WDTCCPK4.js → chunk-EETVN2OJ.js} +1 -1
  77. package/dist/cli/chunks/{chunk-UDVX34ZG.js → chunk-ERYMAYJW.js} +20 -17
  78. package/dist/cli/chunks/{chunk-ELUERFGA.js → chunk-FJGSEPFL.js} +2 -2
  79. package/dist/cli/chunks/{chunk-BN7ERYXI.js → chunk-FLTPHVZ3.js} +1 -1
  80. package/dist/cli/chunks/{chunk-OVENSL64.js → chunk-FND6V2RV.js} +22 -22
  81. package/dist/cli/chunks/{chunk-5ZCVMR5E.js → chunk-FU77CDEM.js} +2 -2
  82. package/dist/cli/chunks/{chunk-VKRMVTWU.js → chunk-GELF4ILR.js} +37 -37
  83. package/dist/cli/chunks/{chunk-H22MMMYY.js → chunk-GHNNJHH3.js} +2 -2
  84. package/dist/cli/chunks/{chunk-32R7EA7B.js → chunk-GJUGSH7T.js} +3 -3
  85. package/dist/cli/chunks/{chunk-HPNEZ7YN.js → chunk-GL3HZN3O.js} +1 -1
  86. package/dist/cli/chunks/{chunk-WL2J6ECN.js → chunk-H56AROF2.js} +2 -2
  87. package/dist/cli/chunks/{chunk-GTRXZJNX.js → chunk-HAO3SPOE.js} +2 -2
  88. package/dist/cli/chunks/{chunk-PUXDXIUE.js → chunk-HM523MTQ.js} +1 -1
  89. package/dist/cli/chunks/{chunk-KRXKU54J.js → chunk-HMFEPKAR.js} +2 -2
  90. package/dist/cli/chunks/{chunk-3YOPJ7DY.js → chunk-HQJMCTWN.js} +2 -2
  91. package/dist/cli/chunks/{chunk-LF7URN2X.js → chunk-HRLXU4LH.js} +2 -2
  92. package/dist/cli/chunks/{chunk-TL5F2S3Z.js → chunk-HWM2XJ3P.js} +24 -24
  93. package/dist/cli/chunks/{chunk-6A2NIR2E.js → chunk-I42R57ON.js} +2 -2
  94. package/dist/cli/chunks/chunk-IL2KOW5W.js +2 -0
  95. package/dist/cli/chunks/{chunk-CR4ERDS2.js → chunk-IRR7YA3Q.js} +2 -2
  96. package/dist/cli/chunks/{chunk-Y2DPXMOR.js → chunk-JD2PG4KS.js} +1 -1
  97. package/dist/cli/chunks/{chunk-TFNLXAK5.js → chunk-JE3C7JYN.js} +1 -1
  98. package/dist/cli/chunks/{chunk-ZTMWJQTZ.js → chunk-JLL27IGU.js} +2 -2
  99. package/dist/cli/chunks/{chunk-YPOTBXPU.js → chunk-JOLDCS6X.js} +2 -2
  100. package/dist/cli/chunks/chunk-JP63XACW.js +62 -0
  101. package/dist/cli/chunks/{chunk-AABKTWXC.js → chunk-JSFYPLMQ.js} +2 -2
  102. package/dist/cli/chunks/{chunk-KCTH5MHE.js → chunk-JTF6D2RJ.js} +4 -4
  103. package/dist/cli/chunks/{chunk-GRG3OP34.js → chunk-JTZ3Q2QS.js} +2 -2
  104. package/dist/cli/chunks/chunk-JXIPRMAY.js +95 -0
  105. package/dist/cli/chunks/{chunk-TNGGVMPQ.js → chunk-KG5SM36Y.js} +1 -1
  106. package/dist/cli/chunks/{chunk-QNW335PD.js → chunk-KTRB3L53.js} +2 -2
  107. package/dist/cli/chunks/{chunk-XRK7FBTY.js → chunk-L74CHKFR.js} +2 -2
  108. package/dist/cli/chunks/{chunk-IHDUWPFY.js → chunk-LZ6TNTGO.js} +2 -2
  109. package/dist/cli/chunks/{chunk-Y357YFLF.js → chunk-M5CDW2ZH.js} +2 -2
  110. package/dist/cli/chunks/{chunk-GRYXNWPF.js → chunk-MBSJ5G4I.js} +12 -12
  111. package/dist/cli/chunks/{chunk-IPRDHKSI.js → chunk-MC7K44M4.js} +2 -2
  112. package/dist/cli/chunks/{chunk-TP77PNN6.js → chunk-MQOFFRTA.js} +2 -2
  113. package/dist/cli/chunks/{chunk-JLKHPIQF.js → chunk-N7IBYDW5.js} +1 -1
  114. package/dist/cli/chunks/{chunk-G5DTENO3.js → chunk-NEYYLAYS.js} +5 -5
  115. package/dist/cli/chunks/{chunk-TNVYKYTO.js → chunk-NNVXHC74.js} +3 -3
  116. package/dist/cli/chunks/{chunk-HRDGN3OK.js → chunk-NNZMEYLT.js} +1 -1
  117. package/dist/cli/chunks/{chunk-25QGPRWN.js → chunk-NRCL3WCP.js} +2 -2
  118. package/dist/cli/chunks/{chunk-NRLT44YB.js → chunk-NXPFGPHV.js} +1 -1
  119. package/dist/cli/chunks/{chunk-PXFQSVA2.js → chunk-NZHOKLII.js} +3 -3
  120. package/dist/cli/chunks/{chunk-7SQD2TTQ.js → chunk-OG7CWWFR.js} +1 -1
  121. package/dist/cli/chunks/{chunk-XGUQYVJR.js → chunk-OPDTDKN3.js} +2 -2
  122. package/dist/cli/chunks/{chunk-2KTRRSKD.js → chunk-OX4R55T3.js} +2 -2
  123. package/dist/cli/chunks/{chunk-COZDJLIL.js → chunk-PFCAMX6H.js} +1 -1
  124. package/dist/cli/chunks/{chunk-UDFLR7GR.js → chunk-PL5SLO2W.js} +1 -1
  125. package/dist/cli/chunks/{chunk-6ZRMQXVL.js → chunk-PZHZPX3O.js} +4 -4
  126. package/dist/cli/chunks/{chunk-57NJQV57.js → chunk-Q7EBD24B.js} +1 -1
  127. package/dist/cli/chunks/{chunk-6D57DWQ6.js → chunk-QEODION5.js} +2 -2
  128. package/dist/cli/chunks/{chunk-K22TPWOJ.js → chunk-QM65UGPV.js} +2 -2
  129. package/dist/cli/chunks/{chunk-2ETDES5W.js → chunk-QWG76RHA.js} +2 -2
  130. package/dist/cli/chunks/{chunk-GXJ4BCGC.js → chunk-R5ONQAQL.js} +2 -2
  131. package/dist/cli/chunks/{chunk-KZJXVIAW.js → chunk-RNF47IJ5.js} +4 -4
  132. package/dist/cli/chunks/{chunk-IK6AJX3C.js → chunk-RTDHWOAG.js} +1 -1
  133. package/dist/cli/chunks/{chunk-NQZYUH6S.js → chunk-RZCAA2PZ.js} +1 -1
  134. package/dist/cli/chunks/{chunk-DQIS6J77.js → chunk-SL6YZAT4.js} +2 -2
  135. package/dist/cli/chunks/{chunk-RPL6K623.js → chunk-SNTMAVPH.js} +5 -5
  136. package/dist/cli/chunks/{chunk-MQYTW2IN.js → chunk-SWOG3PBD.js} +2 -2
  137. package/dist/cli/chunks/{chunk-DMIYWPQQ.js → chunk-T63EK6GH.js} +2 -2
  138. package/dist/cli/chunks/chunk-U6UK3UMX.js +59 -0
  139. package/dist/cli/chunks/{chunk-2S4XHK26.js → chunk-U7NMPZE2.js} +2 -2
  140. package/dist/cli/chunks/{chunk-WS4XVJHI.js → chunk-UDV4YB42.js} +1 -1
  141. package/dist/cli/chunks/{chunk-P7T5Y735.js → chunk-UHDBM7QS.js} +2 -2
  142. package/dist/cli/chunks/{chunk-5EU2VQK3.js → chunk-UIJFU4KD.js} +2 -2
  143. package/dist/cli/chunks/{chunk-Q24OJX44.js → chunk-USFZ4IJD.js} +2 -2
  144. package/dist/cli/chunks/{chunk-Q5VHBI4U.js → chunk-UZL366ZI.js} +1 -1
  145. package/dist/cli/chunks/{chunk-GMKGLZJU.js → chunk-VDTFRMES.js} +2 -2
  146. package/dist/cli/chunks/{chunk-EUJHHXE6.js → chunk-VIWIO27R.js} +3 -3
  147. package/dist/cli/chunks/{chunk-PLRSKAFZ.js → chunk-VRXY4T22.js} +2 -2
  148. package/dist/cli/chunks/{chunk-NDCPEXDN.js → chunk-WPVCSFDA.js} +2 -2
  149. package/dist/cli/chunks/{chunk-TX7SNQKL.js → chunk-WWD5IWTV.js} +1 -1
  150. package/dist/cli/chunks/{chunk-T3UXMPXX.js → chunk-X2B7SANM.js} +1 -1
  151. package/dist/cli/chunks/{chunk-7CKVAYP3.js → chunk-X3RJ6SFC.js} +1 -1
  152. package/dist/cli/chunks/{chunk-6LRCMFLV.js → chunk-XTP2GHI7.js} +2 -2
  153. package/dist/cli/chunks/{chunk-W6ZF2CPN.js → chunk-YDDZJCKY.js} +1 -1
  154. package/dist/cli/chunks/{chunk-5KFCH7RH.js → chunk-YDKYLNKZ.js} +1 -1
  155. package/dist/cli/chunks/{chunk-ELZ67OHQ.js → chunk-YIYV2JB6.js} +2 -2
  156. package/dist/cli/chunks/{chunk-PW6MOFXG.js → chunk-YX2HY4MX.js} +2 -2
  157. package/dist/cli/chunks/{chunk-DVOH75S4.js → chunk-YXH2CVAF.js} +1 -1
  158. package/dist/cli/chunks/{chunk-IITKJCPK.js → chunk-YYAPO3CU.js} +3 -3
  159. package/dist/cli/chunks/{chunk-5OTYBWRL.js → chunk-Z2K5IZM6.js} +2 -2
  160. package/dist/cli/chunks/{chunk-NOCYYXK4.js → chunk-ZG4P3DTL.js} +2 -2
  161. package/dist/cli/chunks/{chunk-YGRTMAWB.js → chunk-ZXQNE4QV.js} +1 -1
  162. package/dist/cli/chunks/{ci-EHRUN7O6.js → ci-AWZ3S5OT.js} +6 -6
  163. package/dist/cli/chunks/{ci-output-EXDXVXKB.js → ci-output-JLCYTIMT.js} +2 -2
  164. package/dist/cli/chunks/{circuit-breaker-LM4QRAAL.js → circuit-breaker-BJDKBDIL.js} +2 -2
  165. package/dist/cli/chunks/{claude-flow-setup-ZHUCZVW7.js → claude-flow-setup-KKOP5ZMO.js} +2 -2
  166. package/dist/cli/chunks/client-2UKBYFX4.js +2 -0
  167. package/dist/cli/chunks/{cline-installer-WMFLQOW2.js → cline-installer-7M525SEA.js} +2 -2
  168. package/dist/cli/chunks/{code-L7KRLU5E.js → code-27SUVJDO.js} +20 -19
  169. package/dist/cli/chunks/{code-index-extractor-FTMUYQC6.js → code-index-extractor-TTQQZLAK.js} +2 -2
  170. package/dist/cli/chunks/{codex-installer-B3F6WI3Z.js → codex-installer-GHNGNPKP.js} +2 -2
  171. package/dist/cli/chunks/{completions-3JZQRNB6.js → completions-JPJD24DG.js} +2 -2
  172. package/dist/cli/chunks/{complexity-analyzer-LB2FFEKX.js → complexity-analyzer-Q74EJV33.js} +2 -2
  173. package/dist/cli/chunks/{continuedev-installer-WH6IMV7R.js → continuedev-installer-ULTRDIML.js} +2 -2
  174. package/dist/cli/chunks/{copilot-installer-NOIEOFJM.js → copilot-installer-EK52X4CG.js} +2 -2
  175. package/dist/cli/chunks/{cost-tracker-IKX2VYSA.js → cost-tracker-2GKBRYXL.js} +2 -2
  176. package/dist/cli/chunks/{coverage-TD37CYSY.js → coverage-YCLC3W2A.js} +3 -3
  177. package/dist/cli/chunks/cross-domain-router-FPM3L27L.js +2 -0
  178. package/dist/cli/chunks/{cursor-installer-4NSVGRM5.js → cursor-installer-B3ALFW5E.js} +2 -2
  179. package/dist/cli/chunks/{daemon-UWEBUIDT.js → daemon-YWINEHG4.js} +4 -4
  180. package/dist/cli/chunks/{daemon-LYDV7NRW.js → daemon-ZKEBVLJA.js} +3 -3
  181. package/dist/cli/chunks/{dag-attention-scheduler-NECJGCHC.js → dag-attention-scheduler-OQPJ6ULA.js} +2 -2
  182. package/dist/cli/chunks/{detect-4XGC7ILO.js → detect-YMYIQH3Q.js} +2 -2
  183. package/dist/cli/chunks/{dist-node-GGJDXRKJ.js → dist-node-R4FAYQRY.js} +2 -2
  184. package/dist/cli/chunks/{domain-handler-UOFONAUT.js → domain-handler-IGWXLF2S.js} +2 -2
  185. package/dist/cli/chunks/{domain-transfer-6JLNOYPA.js → domain-transfer-A7YNO76C.js} +2 -2
  186. package/dist/cli/chunks/dream-XM33US3V.js +2 -0
  187. package/dist/cli/chunks/{embed-and-insert-pattern-ZM75DQ4J.js → embed-and-insert-pattern-KODZAS7Y.js} +2 -2
  188. package/dist/cli/chunks/{eval-CYZJTHEB.js → eval-ALQW7Q2S.js} +3 -3
  189. package/dist/cli/chunks/{experience-capture-middleware-RBOJLDUB.js → experience-capture-middleware-3WK4RXWK.js} +3 -3
  190. package/dist/cli/chunks/{fast-paths-S5BWZR3L.js → fast-paths-PQWDFIJZ.js} +2 -2
  191. package/dist/cli/chunks/{feature-flags-DUNQPDU3.js → feature-flags-6X33B3WX.js} +2 -2
  192. package/dist/cli/chunks/{feature-flags-6E7H3NYP.js → feature-flags-JRUAZCND.js} +2 -2
  193. package/dist/cli/chunks/{file-discovery-PFFKDGYG.js → file-discovery-SA3YU3IH.js} +2 -2
  194. package/dist/cli/chunks/{fleet-RCDZZFXN.js → fleet-7TXCAOKQ.js} +3 -3
  195. package/dist/cli/chunks/{gnn-wrapper-5AG3WDWF.js → gnn-wrapper-ZKNYACEC.js} +2 -2
  196. package/dist/cli/chunks/{heartbeat-handler-O2KAEX4Y.js → heartbeat-handler-KRZRZ23F.js} +4 -4
  197. package/dist/cli/chunks/heartbeat-scheduler-GM3M2MTG.js +2 -0
  198. package/dist/cli/chunks/hnsw-adapter-K62GEHIL.js +2 -0
  199. package/dist/cli/chunks/hnsw-index-VCAK3TWN.js +2 -0
  200. package/dist/cli/chunks/{hnsw-legacy-bridge-C7FG6YGW.js → hnsw-legacy-bridge-LVHQ5SG7.js} +2 -2
  201. package/dist/cli/chunks/{better-sqlite3-XGPW4HK5.js → hnswlib-node-64EGGWIC.js} +2 -2
  202. package/dist/cli/chunks/{hooks-FUHNE2P7.js → hooks-6Y3UHYI2.js} +14 -14
  203. package/dist/cli/chunks/hybrid-router-432QNCNG.js +2 -0
  204. package/dist/cli/chunks/{hypergraph-engine-LQRYBNPV.js → hypergraph-engine-2EZBZMFK.js} +2 -2
  205. package/dist/cli/chunks/{hypergraph-handler-AFFNLZVD.js → hypergraph-handler-GLPWYII2.js} +3 -3
  206. package/dist/cli/chunks/impact-analyzer-VTSISNN4.js +2 -0
  207. package/dist/cli/chunks/{init-handler-BQ6IDBX4.js → init-handler-ZSDO5VMA.js} +6 -6
  208. package/dist/cli/chunks/init-wizard-COB5AH7Q.js +2 -0
  209. package/dist/cli/chunks/kernel-ROK7X5FM.js +2 -0
  210. package/dist/cli/chunks/{kilocode-installer-KS72HUSG.js → kilocode-installer-ATYSDWIV.js} +2 -2
  211. package/dist/cli/chunks/{kiro-installer-2ZEFLGRX.js → kiro-installer-K66YT6PC.js} +2 -2
  212. package/dist/cli/chunks/knowledge-graph-YUWIDIWW.js +2 -0
  213. package/dist/cli/chunks/{learning-GGHGJ6B6.js → learning-BVYCC4RI.js} +3 -3
  214. package/dist/cli/chunks/{llm-router-LP6K5BJF.js → llm-router-VBCXE6DN.js} +12 -12
  215. package/dist/cli/chunks/llm-router-service-7VLXJ7VE.js +2 -0
  216. package/dist/cli/chunks/{load-2MLKXOT2.js → load-AREDQE2U.js} +2 -2
  217. package/dist/cli/chunks/load-test-32524DL3.js +2 -0
  218. package/dist/cli/chunks/{mcp-CDJBJG5H.js → mcp-NG6H6UC5.js} +2 -2
  219. package/dist/cli/chunks/{memory-4LAX7JZS.js → memory-Y65EHG6N.js} +5 -5
  220. package/dist/cli/chunks/memory-backend-BI2V5AAB.js +2 -0
  221. package/dist/cli/chunks/memory-handlers-NSOFWVFN.js +2 -0
  222. package/dist/cli/chunks/{multi-model-executor-SLJV73HE.js → multi-model-executor-VRPRFUZT.js} +2 -2
  223. package/dist/cli/chunks/{opencode-installer-M76SONWV.js → opencode-installer-CKQXPM5R.js} +3 -3
  224. package/dist/cli/chunks/{orchestrator-TJPUDJMP.js → orchestrator-I7JBKD6G.js} +19 -19
  225. package/dist/cli/chunks/{pipeline-2PVNFT6J.js → pipeline-MV2RWCBI.js} +2 -2
  226. package/dist/cli/chunks/{platform-KCSEDKEE.js → platform-VU5P3SOG.js} +2 -2
  227. package/dist/cli/chunks/{plugin-QX47QF5U.js → plugin-6TERLKCB.js} +2 -2
  228. package/dist/cli/chunks/{prime-radiant-advanced-wasm-L6VWL7VR.js → prime-radiant-advanced-wasm-WIUIN2DL.js} +2 -2
  229. package/dist/cli/chunks/protocol-executor-2UPB7SPI.js +2 -0
  230. package/dist/cli/chunks/{protocol-handler-WDNJDEUE.js → protocol-handler-HKWBGARO.js} +2 -2
  231. package/dist/cli/chunks/{prove-3B75DA3S.js → prove-7CQPHBRJ.js} +2 -2
  232. package/dist/cli/chunks/provider-manager-PDT37MIJ.js +2 -0
  233. package/dist/cli/chunks/qe-reasoning-bank-AQQ2BI4V.js +2 -0
  234. package/dist/cli/chunks/{quality-UGASS5WM.js → quality-VLUVXKVG.js} +2 -2
  235. package/dist/cli/chunks/queen-coordinator-6DVDVEU4.js +2 -0
  236. package/dist/cli/chunks/{real-embeddings-COBP2LHS.js → real-embeddings-JPZ64KK2.js} +2 -2
  237. package/dist/cli/chunks/{roocode-installer-TOZ4VLFT.js → roocode-installer-NONVB3UE.js} +2 -2
  238. package/dist/cli/chunks/router-O2G4KQ6L.js +2 -0
  239. package/dist/cli/chunks/routing-feedback-TAGTD3KQ.js +2 -0
  240. package/dist/cli/chunks/{routing-handler-5TDVSILX.js → routing-handler-YYXDT4J2.js} +2 -2
  241. package/dist/cli/chunks/{ruvector-commands-AM63KWQN.js → ruvector-commands-5PFMNDLR.js} +2 -2
  242. package/dist/cli/chunks/{rvf-dual-writer-UANIFE2M.js → rvf-dual-writer-TF6H7AXH.js} +2 -2
  243. package/dist/cli/chunks/{rvf-migration-adapter-LNPYWAPI.js → rvf-migration-adapter-VNGIUZCO.js} +2 -2
  244. package/dist/cli/chunks/{rvf-migration-coordinator-U47L63DQ.js → rvf-migration-coordinator-VA52YAIY.js} +2 -2
  245. package/dist/cli/chunks/rvf-native-adapter-46GRWQJR.js +2 -0
  246. package/dist/cli/chunks/safe-db-LNIPXXHH.js +2 -0
  247. package/dist/cli/chunks/schedule-AUH3ZALY.js +2 -0
  248. package/dist/cli/chunks/scheduler-KK3OYPWW.js +2 -0
  249. package/dist/cli/chunks/{security-KDQ2AH7G.js → security-62HEETBF.js} +3 -3
  250. package/dist/cli/chunks/{shared-rvf-adapter-5MAGLLYJ.js → shared-rvf-adapter-XWTQPGCT.js} +2 -2
  251. package/dist/cli/chunks/{shared-rvf-dual-writer-GF2OPPM5.js → shared-rvf-dual-writer-JTZK7LRD.js} +2 -2
  252. package/dist/cli/chunks/sqlite-persistence-CYESP7NG.js +2 -0
  253. package/dist/cli/chunks/{status-handler-XZKEL7LO.js → status-handler-LSUPUKRF.js} +2 -2
  254. package/dist/cli/chunks/{structural-health-27QKWW25.js → structural-health-Z75A666N.js} +2 -2
  255. package/dist/cli/chunks/{sync-INNKS6UK.js → sync-M3O4T3A3.js} +2 -2
  256. package/dist/cli/chunks/{sync-V3HGPEJT.js → sync-VI37UHHH.js} +2 -2
  257. package/dist/cli/chunks/{task-handler-LDUVOM6G.js → task-handler-AQBSZAQC.js} +2 -2
  258. package/dist/cli/chunks/{task-handlers-HTCPV7OO.js → task-handlers-BOZP247V.js} +3 -3
  259. package/dist/cli/chunks/{test-PCUVGVJL.js → test-FTEGPNN2.js} +4 -4
  260. package/dist/cli/chunks/{test-scheduling-GYVXWCAA.js → test-scheduling-IGR4U2VQ.js} +4 -4
  261. package/dist/cli/chunks/{token-bootstrap-MJ2ANC4P.js → token-bootstrap-2DFRVMBM.js} +2 -2
  262. package/dist/cli/chunks/{token-usage-ZREHROTF.js → token-usage-VCHV47EO.js} +3 -3
  263. package/dist/cli/chunks/{transformers-6B3FWFYL.js → transformers-M27QSNFH.js} +2 -2
  264. package/dist/cli/chunks/tree-sitter-wasm-parser-IIGEJYFU.js +2 -0
  265. package/dist/cli/chunks/{types-MVZTJI2F.js → types-RQFPUUKA.js} +2 -2
  266. package/dist/cli/chunks/unified-memory-RISHEANP.js +2 -0
  267. package/dist/cli/chunks/unified-memory-hnsw-2IKXGMNZ.js +2 -0
  268. package/dist/cli/chunks/unified-persistence-ZTTUJNTU.js +2 -0
  269. package/dist/cli/chunks/{upgrade-MKTFEILD.js → upgrade-VJMYX3AL.js} +2 -2
  270. package/dist/cli/chunks/{validate-IABGALSW.js → validate-ML7HUAU5.js} +4 -4
  271. package/dist/cli/chunks/{validate-swarm-RHF53RF6.js → validate-swarm-RCR6EYRC.js} +7 -7
  272. package/dist/cli/chunks/{vibium-RAKW6FMF.js → vibium-ZOOS3W5L.js} +2 -2
  273. package/dist/cli/chunks/visual-security-D66DTAO5.js +2 -0
  274. package/dist/cli/chunks/{web-tree-sitter-PYK7F4JZ.js → web-tree-sitter-2YPGYLWK.js} +2 -2
  275. package/dist/cli/chunks/{windsurf-installer-S3U2HWZ4.js → windsurf-installer-GOJWUWC5.js} +2 -2
  276. package/dist/cli/chunks/{witness-chain-435NKQLB.js → witness-chain-3MGSS3Q4.js} +2 -2
  277. package/dist/cli/chunks/witness-chain-RHWHHDLV.js +2 -0
  278. package/dist/cli/chunks/{workflow-5UHJCZ6J.js → workflow-B5Q77BI4.js} +4 -4
  279. package/dist/cli/chunks/workflow-orchestrator-OQMFW2TC.js +2 -0
  280. package/dist/cli/chunks/{wrappers-RD3NCMLK.js → wrappers-MM5VLEPG.js} +2 -2
  281. package/dist/cli/commands/code.js +6 -0
  282. package/dist/cli/commands/hooks-handlers/command-hooks.js +1 -1
  283. package/dist/cli/commands/hooks-handlers/routing-hooks.js +1 -1
  284. package/dist/cli/commands/hooks-handlers/task-hooks.js +1 -1
  285. package/dist/cli/commands/learning.js +5 -5
  286. package/dist/cli/commands/llm-router.js +1 -1
  287. package/dist/cli/commands/workflow.js +1 -0
  288. package/dist/coordination/consensus/providers/native-learning-provider.d.ts +1 -1
  289. package/dist/coordination/consensus/providers/ollama-provider.d.ts +1 -1
  290. package/dist/coordination/consensus/providers/openrouter-provider.d.ts +1 -1
  291. package/dist/coordination/handlers/code-intelligence-handlers.js +6 -0
  292. package/dist/coordination/mincut/neural-goap.js +24 -20
  293. package/dist/coordination/protocols/code-intelligence-index.js +31 -25
  294. package/dist/coordination/queen-coordinator.js +4 -0
  295. package/dist/coordination/queen-work-stealing.js +1 -2
  296. package/dist/domains/chaos-resilience/coordinator.js +19 -15
  297. package/dist/domains/chaos-resilience/services/chaos-engineer.js +5 -2
  298. package/dist/domains/chaos-resilience/services/load-tester.js +15 -11
  299. package/dist/domains/code-intelligence/interfaces.d.ts +5 -0
  300. package/dist/domains/code-intelligence/services/c4-model/index.js +12 -6
  301. package/dist/domains/code-intelligence/services/impact-analyzer.js +6 -2
  302. package/dist/domains/code-intelligence/services/knowledge-graph.d.ts +42 -0
  303. package/dist/domains/code-intelligence/services/knowledge-graph.js +278 -93
  304. package/dist/domains/code-intelligence/services/semantic-analyzer.js +8 -2
  305. package/dist/domains/contract-testing/coordinator.js +1 -1
  306. package/dist/domains/coverage-analysis/coordinator.js +4 -2
  307. package/dist/domains/learning-optimization/coordinator.js +1 -0
  308. package/dist/domains/quality-assessment/coherence/gate-controller.js +32 -26
  309. package/dist/domains/requirements-validation/coordinator.js +1 -0
  310. package/dist/domains/test-execution/services/e2e/wait-condition-handler.js +1 -1
  311. package/dist/domains/test-execution/services/retry-handler.js +18 -12
  312. package/dist/domains/test-generation/coordinator.js +1 -1
  313. package/dist/domains/test-generation/services/pattern-matcher.js +7 -5
  314. package/dist/domains/test-generation/services/test-generator.js +3 -2
  315. package/dist/domains/visual-accessibility/coordinator.js +24 -20
  316. package/dist/index.d.ts +2 -2
  317. package/dist/index.js +2 -2
  318. package/dist/init/init-wizard-hooks.js +271 -271
  319. package/dist/init/phases/07-hooks.d.ts +7 -0
  320. package/dist/init/phases/07-hooks.js +132 -96
  321. package/dist/init/phases/12-verification.js +3 -3
  322. package/dist/integrations/agentic-flow/model-router/router.js +1 -1
  323. package/dist/integrations/embeddings/base/EmbeddingGenerator.js +11 -7
  324. package/dist/integrations/ruvector/hypergraph-engine.js +2 -2
  325. package/dist/integrations/ruvector/spectral-math.js +2 -2
  326. package/dist/integrations/ruvector/spectral-sparsifier.js +1 -1
  327. package/dist/kernel/kernel.js +1 -1
  328. package/dist/kernel/unified-memory-hnsw.js +1 -0
  329. package/dist/learning/agent-routing.d.ts +19 -0
  330. package/dist/learning/agent-routing.js +27 -1
  331. package/dist/learning/dream/dream-scheduler.d.ts +11 -36
  332. package/dist/learning/dream/dream-scheduler.js +44 -0
  333. package/dist/learning/experience-capture.js +1 -1
  334. package/dist/learning/experience-consolidation.d.ts +16 -0
  335. package/dist/learning/experience-consolidation.js +55 -11
  336. package/dist/learning/pattern-lifecycle.d.ts +21 -0
  337. package/dist/learning/pattern-lifecycle.js +70 -6
  338. package/dist/learning/qe-reasoning-bank.js +9 -1
  339. package/dist/learning/qe-unified-memory.js +8 -6
  340. package/dist/mcp/bundle.js +371 -368
  341. package/dist/mcp/handlers/core-handlers.js +2 -2
  342. package/dist/mcp/handlers/cross-phase-handlers.js +5 -3
  343. package/dist/mcp/handlers/handler-factory.d.ts +5 -0
  344. package/dist/mcp/handlers/handler-factory.js +44 -4
  345. package/dist/mcp/http-server.js +1 -0
  346. package/dist/mcp/protocol-server.js +15 -16
  347. package/dist/mcp/tools/code-intelligence/analyze.js +1 -1
  348. package/dist/mcp/tools/learning-optimization/optimize.js +1 -1
  349. package/dist/mcp/tools/qx-analysis/heuristics-engine.js +195 -173
  350. package/dist/mcp/tools/visual-accessibility/index.js +1 -1
  351. package/dist/mcp/transport/stdio.d.ts +20 -0
  352. package/dist/mcp/transport/stdio.js +35 -2
  353. package/dist/mcp/transport/websocket/websocket-transport.js +1 -0
  354. package/dist/optimization/auto-tuner.js +1 -1
  355. package/dist/planning/goap-planner.js +1 -0
  356. package/dist/routing/agent-dependency-graph.js +4 -1
  357. package/dist/shared/llm/router/config-store.js +1 -1
  358. package/dist/shared/metrics/system-metrics.js +6 -4
  359. package/dist/shared/parsers/tree-sitter-wasm-parser.d.ts +12 -0
  360. package/dist/shared/parsers/tree-sitter-wasm-parser.js +35 -0
  361. package/dist/shared/parsers/treesitter-ts-extractor.d.ts +39 -0
  362. package/dist/shared/parsers/treesitter-ts-extractor.js +196 -0
  363. package/dist/shared/utils/rabitq.d.ts +133 -0
  364. package/dist/shared/utils/rabitq.js +201 -0
  365. package/dist/shared/utils/safe-expression-evaluator.js +8 -5
  366. package/dist/sync/cloud/postgres-writer.js +2 -0
  367. package/dist/sync/readers/json-reader.js +1 -1
  368. package/dist/test-scheduling/git-aware/test-selector.js +1 -1
  369. package/dist/workers/quality-daemon/index.js +26 -24
  370. package/package.json +12 -5
  371. package/dist/cli/chunks/adapter-3JS2CN7C.js +0 -2
  372. package/dist/cli/chunks/aqe-learning-engine-Q4GFNGU6.js +0 -2
  373. package/dist/cli/chunks/base-Q3MAL22Y.js +0 -2
  374. package/dist/cli/chunks/browser-workflow-JX3M2UWG.js +0 -2
  375. package/dist/cli/chunks/chunk-622MIAOR.js +0 -59
  376. package/dist/cli/chunks/chunk-CKECJH2A.js +0 -2
  377. package/dist/cli/chunks/chunk-IJ4BUSJN.js +0 -95
  378. package/dist/cli/chunks/chunk-VPCE5CIT.js +0 -2
  379. package/dist/cli/chunks/chunk-WO7KYT3X.js +0 -62
  380. package/dist/cli/chunks/client-PA3UJIHH.js +0 -2
  381. package/dist/cli/chunks/cross-domain-router-BVJRP2ZX.js +0 -2
  382. package/dist/cli/chunks/dream-BXZUEIW2.js +0 -2
  383. package/dist/cli/chunks/heartbeat-scheduler-LEKAWFJF.js +0 -2
  384. package/dist/cli/chunks/hnsw-adapter-2TCEG5M2.js +0 -2
  385. package/dist/cli/chunks/hnsw-index-VDPUTEES.js +0 -2
  386. package/dist/cli/chunks/hybrid-router-2EMDIYIG.js +0 -2
  387. package/dist/cli/chunks/impact-analyzer-HFD6CPWC.js +0 -2
  388. package/dist/cli/chunks/init-wizard-552QIVRC.js +0 -2
  389. package/dist/cli/chunks/kernel-5DN6O6EE.js +0 -2
  390. package/dist/cli/chunks/knowledge-graph-76Y77MB6.js +0 -2
  391. package/dist/cli/chunks/llm-router-service-4O6GCEFH.js +0 -2
  392. package/dist/cli/chunks/load-test-FCI2IWRJ.js +0 -2
  393. package/dist/cli/chunks/memory-backend-MKNCBNDE.js +0 -2
  394. package/dist/cli/chunks/memory-handlers-OBAFR4WV.js +0 -2
  395. package/dist/cli/chunks/protocol-executor-IA7WNT23.js +0 -2
  396. package/dist/cli/chunks/provider-manager-3K5KB5A6.js +0 -2
  397. package/dist/cli/chunks/qe-reasoning-bank-V5Z3BBYY.js +0 -2
  398. package/dist/cli/chunks/queen-coordinator-QOMPA27Z.js +0 -2
  399. package/dist/cli/chunks/router-P5RZUPC4.js +0 -2
  400. package/dist/cli/chunks/routing-feedback-3PS3OZQC.js +0 -2
  401. package/dist/cli/chunks/rvf-native-adapter-TT7OJPKM.js +0 -2
  402. package/dist/cli/chunks/safe-db-PEW7VBAE.js +0 -2
  403. package/dist/cli/chunks/schedule-QHOTHBQE.js +0 -2
  404. package/dist/cli/chunks/scheduler-KXJBYTRT.js +0 -2
  405. package/dist/cli/chunks/sqlite-persistence-TPXJK34J.js +0 -2
  406. package/dist/cli/chunks/tree-sitter-wasm-parser-JVV234MN.js +0 -2
  407. package/dist/cli/chunks/unified-memory-ROS2NKR5.js +0 -2
  408. package/dist/cli/chunks/unified-memory-hnsw-FLEUF3XO.js +0 -2
  409. package/dist/cli/chunks/unified-persistence-QC5L7UNQ.js +0 -2
  410. package/dist/cli/chunks/visual-security-NLIOUQCR.js +0 -2
  411. package/dist/cli/chunks/witness-chain-U7X6JX5J.js +0 -2
  412. package/dist/cli/chunks/workflow-orchestrator-APE6BAXH.js +0 -2
@@ -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.10.1");process.exit(0)}
2
- import{a as h}from"./chunk-BN7ERYXI.js";import{a as C,f as x}from"./chunk-DVOH75S4.js";var d={mechanical:["convert var to const","add types","remove console","convert to async","convert to esm","arrow function","rename variable","format code"],simple:["fix typo","update comment","fix simple bug","add documentation","format","rename","simple refactor","basic test"],moderate:["implement feature","implement","refactor","complex refactor","performance optimization","optimize","test generation","generate test","error handling","validation logic","api integration","code index","coverage analysis","quality assessment","defect prediction","predict defect","analyze coverage","analyze","assess","scan","detect"],complex:["multi-file refactor","orchestrate","coordinate","large codebase","migration","cross-domain","workflow","system design","analyze security","security scan","security analysis","vulnerability scan","chaos test","resilience test","contract validation"],critical:["architecture","security audit","critical bug","algorithm design","system-wide","vulnerability","cryptography","performance critical","hardcoded secret","cve","owasp","penetration test","exploit"]},f={architecture:/\b(architect|design|system design|overall structure|component design)\b/i,security:/\b(security|vulnerability|audit|xss|sql injection|csrf|encryption|auth|authentication|authorization)\b/i,multiStep:/\b(orchestrate|coordinate|workflow|pipeline|multi[- ]step)\b/i,crossDomain:/\b(cross[- ]domain|across (domains|modules)|integrate|coordination)\b/i},m=class{config;agentBoosterAdapter;constructor(e,t){this.config=e,this.agentBoosterAdapter=t}async collectSignals(e){let t=e.task.toLowerCase(),r=await this.checkAgentBoosterEligibility(e),o={simple:this.findKeywordMatches(t,d.simple),moderate:this.findKeywordMatches(t,d.moderate),complex:this.findKeywordMatches(t,d.complex),critical:this.findKeywordMatches(t,d.critical)},c=e.codeContext?e.codeContext.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.10.3");process.exit(0)}
2
+ import{a as h}from"./chunk-FLTPHVZ3.js";import{a as C,f as x}from"./chunk-YXH2CVAF.js";var d={mechanical:["convert var to const","add types","remove console","convert to async","convert to esm","arrow function","rename variable","format code"],simple:["fix typo","update comment","fix simple bug","add documentation","format","rename","simple refactor","basic test"],moderate:["implement feature","implement","refactor","complex refactor","performance optimization","optimize","test generation","generate test","error handling","validation logic","api integration","code index","coverage analysis","quality assessment","defect prediction","predict defect","analyze coverage","analyze","assess","scan","detect"],complex:["multi-file refactor","orchestrate","coordinate","large codebase","migration","cross-domain","workflow","system design","analyze security","security scan","security analysis","vulnerability scan","chaos test","resilience test","contract validation"],critical:["architecture","security audit","critical bug","algorithm design","system-wide","vulnerability","cryptography","performance critical","hardcoded secret","cve","owasp","penetration test","exploit"]},f={architecture:/\b(architect|design|system design|overall structure|component design)\b/i,security:/\b(security|vulnerability|audit|xss|sql injection|csrf|encryption|auth|authentication|authorization)\b/i,multiStep:/\b(orchestrate|coordinate|workflow|pipeline|multi[- ]step)\b/i,crossDomain:/\b(cross[- ]domain|across (domains|modules)|integrate|coordination)\b/i},m=class{config;agentBoosterAdapter;constructor(e,t){this.config=e,this.agentBoosterAdapter=t}async collectSignals(e){let t=e.task.toLowerCase(),r=await this.checkAgentBoosterEligibility(e),o={simple:this.findKeywordMatches(t,d.simple),moderate:this.findKeywordMatches(t,d.moderate),complex:this.findKeywordMatches(t,d.complex),critical:this.findKeywordMatches(t,d.critical)},c=e.codeContext?e.codeContext.split(`
3
3
  `).length:void 0,n=e.filePaths?e.filePaths.length:void 0,i=f.architecture.test(t),a=f.security.test(t),l=f.multiStep.test(t),g=f.crossDomain.test(t),b=this.detectCreativityRequirement(t),S=this.estimateLanguageComplexity(e.codeContext,e.filePaths),T=e.codeContext?this.estimateCyclomaticComplexity(e.codeContext):void 0;return{linesOfCode:c,fileCount:n,hasArchitectureScope:i,hasSecurityScope:a,requiresMultiStepReasoning:l,requiresCrossDomainCoordination:g,isMechanicalTransform:r.eligible,languageComplexity:S,cyclomaticComplexity:T,dependencyCount:this.countDependencies(e.codeContext),requiresCreativity:b,detectedTransformType:r.transformType,keywordMatches:o}}async checkAgentBoosterEligibility(e){if(!this.config.enableAgentBooster)return{eligible:!1,confidence:0,reason:"Agent Booster is disabled"};let t=e.task.toLowerCase(),r,o=0;for(let n of h){let i=this.getTransformKeywords(n),a=0;for(let l of i)t.includes(l.toLowerCase())&&(a=a===0?.5:a+.25);for(let l of d.mechanical)t.includes(l.toLowerCase())&&(a=Math.max(a,.6));a>o&&(o=a,r=n)}if(e.codeContext&&r&&this.agentBoosterAdapter)try{let i=(await this.agentBoosterAdapter.detectTransformOpportunities(e.codeContext)).opportunities.find(a=>a.type===r);if(i)return{eligible:i.confidence>=this.config.agentBoosterThreshold,transformType:r,confidence:i.confidence,reason:i.reason}}catch(n){console.debug("[SignalCollector] WASM analysis error:",n instanceof Error?n.message:n)}let c=o>=this.config.agentBoosterThreshold&&r!==void 0;return{eligible:c,transformType:r,confidence:Math.min(o,1),reason:c?`Detected ${r} transform pattern`:"No mechanical transform pattern detected"}}findKeywordMatches(e,t){let r=[];for(let o of t)e.includes(o.toLowerCase())&&r.push(o);return r}detectCreativityRequirement(e){return e.includes("design")||e.includes("creative")||e.includes("innovative")||e.includes("novel")}estimateLanguageComplexity(e,t){if(!e&&(!t||t.length===0))return;let r=[".ts",".tsx",".rs",".cpp",".c",".go"],o=[".js",".jsx",".py",".java"],c=[".json",".yaml",".md",".txt",".css",".html"];if(t){for(let n of t)if(r.some(i=>n.endsWith(i)))return"high";for(let n of t)if(o.some(i=>n.endsWith(i)))return"medium";for(let n of t)if(c.some(i=>n.endsWith(i)))return"low"}if(e){let n=/<[A-Z][^>]*>/.test(e),i=/\b(async|await)\b/.test(e),a=/\b(interface|type|class)\b/.test(e);return n&&a?"high":i||a?"medium":"low"}return"medium"}estimateCyclomaticComplexity(e){let t=[/\bif\b/g,/\bfor\b/g,/\bwhile\b/g,/\bcase\b/g,/\bcatch\b/g,/&&/g,/\|\|/g,/\?/g],r=1;for(let o of t){let c=e.match(o);c&&(r+=c.length)}return r}countDependencies(e){if(!e)return;let t=e.match(/\b(import|require|from)\b.*['"].*['"]/g);return t?t.length:0}getTransformKeywords(e){return{"var-to-const":["var to const","convert var","var declaration","var to let","convert var to const","change var to const"],"add-types":["add types","add type","typescript types","type annotations","type annotation","add type annotations"],"remove-console":["remove console","delete console","console.log","remove console.log","strip console"],"promise-to-async":["promise to async","async await",".then to async","convert to async","convert function to async"],"cjs-to-esm":["commonjs to esm","require to import","convert to esm","cjs to esm","module conversion"],"func-to-arrow":["arrow function","function to arrow","convert to arrow","convert function to arrow"]}[e]||[]}};function v(s,e){return new m(s,e)}var u=class{calculateCodeComplexity(e){let t=0;return t+=this.calculateLinesOfCodeContribution(e.linesOfCode),t+=this.calculateFileCountContribution(e.fileCount),t+=this.calculateCyclomaticContribution(e.cyclomaticComplexity),t+=this.calculateLanguageContribution(e.languageComplexity),Math.min(t,100)}calculateReasoningComplexity(e){let t=0;return t+=this.calculateKeywordScore(e.keywordMatches),e.requiresMultiStepReasoning&&(t+=20),e.requiresCreativity&&(t+=20),Math.min(t,100)}calculateScopeComplexity(e){let t=0;return e.hasArchitectureScope&&(t+=40),e.hasSecurityScope&&(t+=30),e.requiresCrossDomainCoordination&&(t+=20),t+=this.calculateDependencyContribution(e.dependencyCount),Math.min(t,100)}calculateOverallComplexity(e,t,r,o){if(o.isMechanicalTransform&&!o.hasSecurityScope&&!o.hasArchitectureScope&&!o.requiresMultiStepReasoning&&!o.requiresCrossDomainCoordination&&e===0&&t===0&&r===0)return 5;let c=e*.3+t*.4+r*.3,n=0;return o.hasSecurityScope&&(n=Math.max(n,50)),o.hasArchitectureScope&&(n=Math.max(n,55)),o.requiresCrossDomainCoordination&&(n=Math.max(n,35)),o.requiresMultiStepReasoning&&(n=Math.max(n,30)),o.keywordMatches.simple.length+o.keywordMatches.moderate.length+o.keywordMatches.complex.length+o.keywordMatches.critical.length===0&&!o.isMechanicalTransform&&c<15&&(n=Math.max(n,15)),Math.min(Math.max(Math.round(c),n),100)}calculateConfidence(e,t){let r=.5;return t.codeContext&&(r+=.2),t.filePaths&&t.filePaths.length>0&&(r+=.1),r+=this.calculateKeywordConfidenceBoost(e.keywordMatches),e.isMechanicalTransform&&(r+=.15),Math.min(r,1)}calculateLinesOfCodeContribution(e){return e===void 0||e<10?0:e<50?10:e<200?20:30}calculateFileCountContribution(e){return e===void 0||e===1?0:e<5?10:20}calculateCyclomaticContribution(e){return e===void 0||e<5?0:e<10?10:e<20?20:30}calculateLanguageContribution(e){return e==="low"?0:e==="medium"?10:e==="high"?20:0}calculateKeywordScore(e){let t=e.simple.length*5+e.moderate.length*15+e.complex.length*25+e.critical.length*35;return Math.min(t,60)}calculateDependencyContribution(e){return e===void 0||e<3?0:e<10?5:10}calculateKeywordConfidenceBoost(e){let t=e.simple.length+e.moderate.length+e.complex.length+e.critical.length;return t>=3?.1:t>=1?.05:0}};function M(){return new u}var p=class{getRecommendedTier(e){for(let t of[0,1,2,3,4]){let[r,o]=C[t].complexityRange;if(e>=r&&e<=o)return t}return 2}findAlternateTiers(e,t){let r=[];return t>0&&r.push(t-1),t<4&&r.push(t+1),t<3&&!r.includes(4)&&r.push(4),r}generateExplanation(e,t,r){let o=[];return o.push(`Complexity score: ${e}/100 (Tier ${t})`),r.isMechanicalTransform&&o.push(this.formatMechanicalTransformInfo(r.detectedTransformType)),o.push(...this.formatScopeExplanations(r)),o.push(...this.formatCodeMetricsExplanations(r)),o.join(". ")}formatMechanicalTransformInfo(e){return`Detected mechanical transform: ${e}`}formatScopeExplanations(e){let t=[];return e.hasArchitectureScope&&t.push("Architecture scope detected"),e.hasSecurityScope&&t.push("Security scope detected"),e.requiresMultiStepReasoning&&t.push("Multi-step reasoning required"),e.requiresCrossDomainCoordination&&t.push("Cross-domain coordination required"),t}formatCodeMetricsExplanations(e){let t=[];return e.linesOfCode!==void 0&&e.linesOfCode>100&&t.push(`Large code change: ${e.linesOfCode} lines`),e.fileCount!==void 0&&e.fileCount>3&&t.push(`Multi-file change: ${e.fileCount} files`),t}};function w(){return new p}var y=class{config;signalCollector;scoreCalculator;tierRecommender;constructor(e,t,r,o){this.config=e,this.signalCollector=t,this.scoreCalculator=r,this.tierRecommender=o}async analyze(e){try{let t=await this.signalCollector.collectSignals(e),r=this.scoreCalculator.calculateCodeComplexity(t),o=this.scoreCalculator.calculateReasoningComplexity(t),c=this.scoreCalculator.calculateScopeComplexity(t),n=this.scoreCalculator.calculateOverallComplexity(r,o,c,t),i=this.tierRecommender.getRecommendedTier(n),a=this.tierRecommender.findAlternateTiers(n,i),l=this.scoreCalculator.calculateConfidence(t,e),g=this.tierRecommender.generateExplanation(n,i,t);return{overall:n,codeComplexity:r,reasoningComplexity:o,scopeComplexity:c,confidence:l,signals:t,recommendedTier:i,alternateTiers:a,explanation:g}}catch(t){throw new x(`Failed to analyze task complexity: ${t instanceof Error?t.message:"Unknown error"}`,t instanceof Error?t:void 0)}}async checkAgentBoosterEligibility(e){return this.signalCollector.checkAgentBoosterEligibility(e)}getRecommendedTier(e){return this.tierRecommender.getRecommendedTier(e)}};function L(s,e){let t=new m(s,e),r=new u,o=new p;return new y(s,t,r,o)}function z(s,e,t,r){return new y(s,e,t,r)}export{m as a,v as b,u as c,M as d,p as e,w as f,y as g,L as h,z as i};
@@ -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.10.1");process.exit(0)}
2
- import{a as u,c as v,d as p}from"./chunk-K22TPWOJ.js";import{b as l}from"./chunk-KZJXVIAW.js";import{a}from"./chunk-WMG5F6R6.js";var P=["ollama","onnx","gemini","openrouter","openai","claude","azure-openai","bedrock"];async function x(e={}){if(e.providerManager){let d=v({projectRoot:e.projectRoot,override:e.override,env:e.env}),f=new a(e.providerManager,d);return await f.initialize(),{router:f,resolvedConfig:d,enabledProviders:y(d)}}if(!p({projectRoot:e.projectRoot,env:e.env}))return null;let r=v({projectRoot:e.projectRoot,override:e.override,env:e.env}),o=g(r,e.env??process.env);if(o.length===0)return null;let{primary:n,fallbacks:t}=R(r,o),i={primary:n,fallbacks:t,providers:m(r,o),loadBalancing:"round-robin",global:{enableCostTracking:!0,enableMetrics:!0}},c=new l(i),s=new a(c,r);return await s.initialize(),{router:s,resolvedConfig:r,enabledProviders:o}}function g(e,r=process.env){let o=u(r),n=[],t=i=>{n.includes(i)||!e.providers?.[i]?.enabled||o.has(i)&&n.push(i)};t(e.defaultProvider);for(let i of e.fallbackChain?.entries??[])t(i.provider);for(let i of P)t(i);return n}function y(e){let r=new Set([e.defaultProvider]);for(let o of e.fallbackChain?.entries??[])r.add(o.provider);return Array.from(r)}function R(e,r){if(r.length===0)throw new Error("pickPrimaryAndFallbacks: no enabled providers");let o=r.includes(e.defaultProvider)?e.defaultProvider:r[0],n=r.filter(t=>t!==o);return{primary:o,fallbacks:n}}function m(e,r){let o={};for(let n of r){let t=e.providers?.[n];t&&(o[n]=t)}return o}export{x as a,g as b,R 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.10.3");process.exit(0)}
2
+ import{a as u,c as v,d as p}from"./chunk-QM65UGPV.js";import{b as l}from"./chunk-RNF47IJ5.js";import{a}from"./chunk-5SGEOO2F.js";var P=["ollama","onnx","gemini","openrouter","openai","claude","azure-openai","bedrock"];async function x(e={}){if(e.providerManager){let d=v({projectRoot:e.projectRoot,override:e.override,env:e.env}),f=new a(e.providerManager,d);return await f.initialize(),{router:f,resolvedConfig:d,enabledProviders:y(d)}}if(!p({projectRoot:e.projectRoot,env:e.env}))return null;let r=v({projectRoot:e.projectRoot,override:e.override,env:e.env}),o=g(r,e.env??process.env);if(o.length===0)return null;let{primary:n,fallbacks:t}=R(r,o),i={primary:n,fallbacks:t,providers:m(r,o),loadBalancing:"round-robin",global:{enableCostTracking:!0,enableMetrics:!0}},c=new l(i),s=new a(c,r);return await s.initialize(),{router:s,resolvedConfig:r,enabledProviders:o}}function g(e,r=process.env){let o=u(r),n=[],t=i=>{n.includes(i)||!e.providers?.[i]?.enabled||o.has(i)&&n.push(i)};t(e.defaultProvider);for(let i of e.fallbackChain?.entries??[])t(i.provider);for(let i of P)t(i);return n}function y(e){let r=new Set([e.defaultProvider]);for(let o of e.fallbackChain?.entries??[])r.add(o.provider);return Array.from(r)}function R(e,r){if(r.length===0)throw new Error("pickPrimaryAndFallbacks: no enabled providers");let o=r.includes(e.defaultProvider)?e.defaultProvider:r[0],n=r.filter(t=>t!==o);return{primary:o,fallbacks:n}}function m(e,r){let o={};for(let n of r){let t=e.providers?.[n];t&&(o[n]=t)}return o}export{x as a,g as b,R as c};
@@ -0,0 +1,59 @@
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.10.3");process.exit(0)}
2
+ import{d as be}from"./chunk-5LON3MLI.js";import{b as D,d as ye}from"./chunk-KTRB3L53.js";import{a as Le}from"./chunk-3VF3HCG4.js";import{c as fe,d as ge,e as Pe}from"./chunk-2L73WXA4.js";import{b as P,c as L}from"./chunk-JD2PG4KS.js";import{a as G,b as A,c as J}from"./chunk-3LRK7PYN.js";Le();import{createRequire as Ce}from"module";var O;function W(){if(!O){let u=Ce(import.meta.url);try{O=u("typescript")}catch{try{O=u("typescript/lib/typescript.js")}catch{O=new Proxy({},{get(e,t){if(!(t==="__esModule"||typeof t=="symbol"))throw new Error("TypeScript is required for code analysis. Install it: npm install -g typescript")}})}}}return O}var m=new Proxy({},{get(u,e){return W()[e]},has(u,e){return e in W()},ownKeys(){return Object.keys(W())},getOwnPropertyDescriptor(u,e){let t=W()[e];if(t!==void 0)return{configurable:!0,enumerable:!0,value:t}}});var N=class{parseFile(e,t){return m.createSourceFile(e,t,m.ScriptTarget.Latest,!0,this.getScriptKind(e))}extractFunctions(e){let t=[],s=n=>{m.isFunctionDeclaration(n)&&n.name?t.push(this.extractFunctionDeclaration(n,e)):m.isVariableStatement(n)&&this.extractArrowFunctions(n,e,t),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractClasses(e){let t=[],s=n=>{m.isClassDeclaration(n)&&n.name&&t.push(this.extractClassDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractImports(e){let t=[],s=n=>{m.isImportDeclaration(n)&&t.push(this.extractImportDeclaration(n)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractExports(e){let t=[],s=n=>{if(m.isExportDeclaration(n))this.extractExportDeclaration(n,t);else if(m.isExportAssignment(n))t.push({name:this.getExportAssignmentName(n),type:"unknown",isDefault:!0,isReexport:!1,sourceModule:void 0});else if(m.isFunctionDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"function",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(m.isClassDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"class",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(m.isVariableStatement(n)&&this.hasExportModifier(n))for(let i of n.declarationList.declarations)m.isIdentifier(i.name)&&t.push({name:i.name.text,type:"variable",isDefault:!1,isReexport:!1,sourceModule:void 0});else m.isInterfaceDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"interface",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isTypeAliasDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"type",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isEnumDeclaration(n)&&this.hasExportModifier(n)&&t.push({name:n.name.text,type:"enum",isDefault:!1,isReexport:!1,sourceModule:void 0});m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractInterfaces(e){let t=[],s=n=>{m.isInterfaceDeclaration(n)&&t.push(this.extractInterfaceDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractEntities(e,t){let s=this.parseFile(t,e),n=[],i=this.extractFunctions(s);for(let a of i)n.push({name:a.name,type:"function",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:a.isAsync,isExported:a.isExported,parameters:a.parameters,returnType:a.returnType});let o=this.extractClasses(s);for(let a of o)n.push({name:a.name,type:"class",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported,extends:a.extends,implements:a.implements});let r=this.extractInterfaces(s);for(let a of r)n.push({name:a.name,type:"interface",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported});return n}getScriptKind(e){return e.endsWith(".tsx")?m.ScriptKind.TSX:e.endsWith(".ts")?m.ScriptKind.TS:e.endsWith(".jsx")?m.ScriptKind.JSX:e.endsWith(".js")?m.ScriptKind.JS:m.ScriptKind.TS}extractFunctionDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:e.name?.text??"anonymous",parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,startLine:s+1,endLine:n+1,isAsync:this.hasAsyncModifier(e),isExported:this.hasExportModifier(e),isGenerator:!!e.asteriskToken,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractArrowFunctions(e,t,s){for(let n of e.declarationList.declarations)if(m.isIdentifier(n.name)&&n.initializer&&m.isArrowFunction(n.initializer)){let i=n.initializer,{line:o}=t.getLineAndCharacterOfPosition(e.getStart()),{line:r}=t.getLineAndCharacterOfPosition(e.getEnd());s.push({name:n.name.text,parameters:this.extractParameters(i.parameters),returnType:i.type?i.type.getText(t):void 0,startLine:o+1,endLine:r+1,isAsync:this.hasAsyncModifier(i),isExported:this.hasExportModifier(e),isGenerator:!1,typeParameters:this.extractTypeParameters(i.typeParameters)})}}extractClassDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),i=[],o=[];for(let c of e.members)m.isMethodDeclaration(c)&&c.name?i.push(this.extractMethodDeclaration(c,t)):m.isPropertyDeclaration(c)&&c.name?o.push(this.extractPropertyDeclaration(c,t)):m.isConstructorDeclaration(c)&&(i.push(this.extractConstructor(c,t)),this.extractParameterProperties(c,o,t));let r,a=[];if(e.heritageClauses){for(let c of e.heritageClauses)if(c.token===m.SyntaxKind.ExtendsKeyword)r=c.types[0]?.expression.getText(t);else if(c.token===m.SyntaxKind.ImplementsKeyword)for(let l of c.types)a.push(l.expression.getText(t))}return{name:e.name?.text??"anonymous",methods:i,properties:o,extends:r,implements:a,isAbstract:this.hasAbstractModifier(e),isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractMethodDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:this.getPropertyName(e.name,t),parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,isAsync:this.hasAsyncModifier(e),isStatic:this.hasStaticModifier(e),isAbstract:this.hasAbstractModifier(e),visibility:this.getVisibility(e),startLine:s+1,endLine:n+1}}extractConstructor(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:"constructor",parameters:this.extractParameters(e.parameters),returnType:void 0,isAsync:!1,isStatic:!1,isAbstract:!1,visibility:"public",startLine:s+1,endLine:n+1}}extractParameterProperties(e,t,s){for(let n of e.parameters)this.isParameterProperty(n)&&t.push({name:m.isIdentifier(n.name)?n.name.text:n.name.getText(s),type:n.type?n.type.getText(s):void 0,isStatic:!1,isReadonly:this.hasReadonlyModifier(n),visibility:this.getVisibility(n),hasInitializer:!!n.initializer})}isParameterProperty(e){return!!e.modifiers?.some(t=>t.kind===m.SyntaxKind.PublicKeyword||t.kind===m.SyntaxKind.PrivateKeyword||t.kind===m.SyntaxKind.ProtectedKeyword||t.kind===m.SyntaxKind.ReadonlyKeyword)}extractPropertyDeclaration(e,t){return{name:this.getPropertyName(e.name,t),type:e.type?e.type.getText(t):void 0,isStatic:this.hasStaticModifier(e),isReadonly:this.hasReadonlyModifier(e),visibility:this.getVisibility(e),hasInitializer:!!e.initializer}}extractImportDeclaration(e){let t=e.moduleSpecifier.text,s=[],n,i,o=e.importClause?.isTypeOnly??!1;if(e.importClause&&(e.importClause.name&&(n=e.importClause.name.text),e.importClause.namedBindings)){if(m.isNamespaceImport(e.importClause.namedBindings))i=e.importClause.namedBindings.name.text;else if(m.isNamedImports(e.importClause.namedBindings))for(let r of e.importClause.namedBindings.elements)s.push({name:r.propertyName?.text??r.name.text,alias:r.propertyName?r.name.text:void 0})}return{module:t,namedImports:s,defaultImport:n,namespaceImport:i,isTypeOnly:o}}extractExportDeclaration(e,t){let s=e.moduleSpecifier?e.moduleSpecifier.text:void 0;if(e.exportClause&&m.isNamedExports(e.exportClause))for(let n of e.exportClause.elements)t.push({name:n.name.text,type:"unknown",isDefault:!1,isReexport:!!s,sourceModule:s});else!e.exportClause&&s&&t.push({name:"*",type:"unknown",isDefault:!1,isReexport:!0,sourceModule:s})}extractInterfaceDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),i=[],o=[];for(let a of e.members)m.isPropertySignature(a)&&a.name?i.push({name:this.getPropertyName(a.name,t),type:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken,isReadonly:this.hasReadonlyModifier(a)}):m.isMethodSignature(a)&&a.name&&o.push({name:this.getPropertyName(a.name,t),parameters:this.extractParameters(a.parameters),returnType:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken});let r=[];if(e.heritageClauses){for(let a of e.heritageClauses)if(a.token===m.SyntaxKind.ExtendsKeyword)for(let c of a.types)r.push(c.expression.getText(t))}return{name:e.name.text,properties:i,methods:o,extends:r,isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractParameters(e){return e.map(t=>{let s=t.getSourceFile();return{name:m.isIdentifier(t.name)?t.name.text:t.name.getText(s),type:t.type?t.type.getText(s):void 0,isOptional:!!t.questionToken||!!t.initializer,isRest:!!t.dotDotDotToken,defaultValue:t.initializer?t.initializer.getText(s):void 0}})}extractTypeParameters(e){return e?e.map(t=>t.name.text):[]}getPropertyName(e,t){return m.isIdentifier(e)||m.isStringLiteral(e)||m.isNumericLiteral(e)?e.text:e.getText(t)}getExportAssignmentName(e){return m.isIdentifier(e.expression)?e.expression.text:"default"}hasExportModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ExportKeyword)}hasDefaultModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.DefaultKeyword)}hasAsyncModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AsyncKeyword)}hasStaticModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.StaticKeyword)}hasAbstractModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AbstractKeyword)}hasReadonlyModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ReadonlyKeyword)}getVisibility(e){if(!m.canHaveModifiers(e))return"public";let t=m.getModifiers(e);return t?t.some(s=>s.kind===m.SyntaxKind.PrivateKeyword)?"private":t.some(s=>s.kind===m.SyntaxKind.ProtectedKeyword)?"protected":"public":"public"}},We=new N,Q=class{language="typescript";supportedExtensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];parser=new N;async parseFile(e,t){let s=this.parser.parseFile(t,e),n=this.parser.extractFunctions(s),i=this.parser.extractClasses(s),o=this.parser.extractImports(s);return{functions:n.map(r=>this.mapFunction(r)),classes:i.map(r=>this.mapClass(r)),imports:o.map(r=>this.mapImport(r)),language:t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":"typescript",filePath:t}}mapFunction(e){return{name:e.name,parameters:e.parameters.map(t=>({name:t.name,type:t.type,isOptional:t.isOptional,defaultValue:t.defaultValue})),returnType:e.returnType,isAsync:e.isAsync,isPublic:e.isExported,complexity:1,decorators:[],genericParams:e.typeParameters,startLine:e.startLine,endLine:e.endLine}}mapClass(e){return{name:e.name,methods:e.methods.map(t=>({name:t.name,parameters:t.parameters.map(s=>({name:s.name,type:s.type,isOptional:s.isOptional,defaultValue:s.defaultValue})),returnType:t.returnType,isAsync:t.isAsync,isPublic:t.visibility==="public",complexity:1,decorators:[],genericParams:[],startLine:t.startLine,endLine:t.endLine})),properties:e.properties.map(t=>this.mapProperty(t)),isPublic:e.isExported,implements:e.implements,extends:e.extends,decorators:[],startLine:e.startLine,endLine:e.endLine}}mapProperty(e){return{name:e.name,type:e.type,isPublic:e.visibility==="public",isReadonly:e.isReadonly}}mapImport(e){return{module:e.module,namedImports:e.namedImports.map(t=>t.alias||t.name),isTypeOnly:e.isTypeOnly}}},ze=new Q;Pe();var E=1e3;function I(u){let e=u.split(`
3
+ `),t=[],s=[],n="",i=0,o=0,r=0,a=0;for(let c=0;c<e.length;c++){let l=e[c],d=l.trim();if(d===""||d.startsWith("//")||d.startsWith("#")||d.startsWith("*")){if(n){n+=" "+d;continue}t.push(l),s.push(c+1);continue}n||(i=c+1),n=n?n+" "+d:l;for(let p of d)p==="("?o++:p===")"?o=Math.max(0,o-1):p==="<"?r++:p===">"?r=Math.max(0,r-1):p==="["?a++:p==="]"&&(a=Math.max(0,a-1));o===0&&r===0&&a===0&&(t.push(n),s.push(i),n="")}return n&&(t.push(n),s.push(i)),{logicalLines:t,lineMap:s}}function B(u,e,t="<",s=">"){if(u[e]!==t)return;let n=1,i=e+1;for(;i<u.length&&n>0;)u[i]===t?n++:u[i]===s&&n--,i++;if(n===0)return u.substring(e+1,i-1)}function C(u,e,t){let s=[];for(let n=e-1;n>=0;n--){let i=u[n].trim();if(i.startsWith(t))s.unshift(i);else{if(i===""||i.startsWith("//")||i.startsWith("*")||i.startsWith("#"))continue;break}}return s}function M(u){let e=[],t=0,s="";for(let n of u)n==="<"||n==="("?t++:(n===">"||n===")")&&t--,n===","&&t===0?(e.push(s.trim()),s=""):s+=n;return s.trim()&&e.push(s.trim()),e}function ce(u){let e=0,t=!1,s="";for(let n=0;n<u.length;n++){let i=u[n];if(t){i===s&&u[n-1]!=="\\"&&(t=!1);continue}i==='"'||i==="'"||i==="`"?(t=!0,s=i):i==="{"?e++:i==="}"&&e--}return e}var Y=class{language="python";supportedExtensions=[".py"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"python",filePath:t}}extractFunctions(e){let t=[],s=e.split(`
4
+ `),{logicalLines:n,lineMap:i}=I(e),o=/^(\s*)(async\s+)?def\s+(\w+)\s*\(([^)]*)\)(?:\s*->\s*([^:]*\S))?\s*:/;for(let r=0;r<n.length;r++){if(n[r].length>E)continue;let a=n[r].match(o);if(a){let c=a[1].length,l=!!a[2],d=a[3],p=a[4],h=a[5]?.trim(),f=i[r]-1,g=f+1;for(let y=f+1;y<s.length;y++){let x=s[y];if(x.trim()===""||x.trim().startsWith("#"))continue;if((x.match(/^(\s*)/)?.[1].length??0)<=c&&x.trim()!==""){g=y;break}g=y+1}let b=C(s,f,"@");t.push({name:d,parameters:this.parseParams(p),returnType:h,isAsync:l,isPublic:!d.startsWith("_"),complexity:1,decorators:b,genericParams:[],startLine:i[r],endLine:g})}}return t}extractClasses(e){let t=[],s=e.split(`
5
+ `),{logicalLines:n,lineMap:i}=I(e),o=/^(\s*)class\s+(\w+)(?:\(([^)]*)\))?\s*:/;for(let r=0;r<n.length;r++){let a=n[r].match(o);if(a){let c=a[1].length,l=a[2],d=a[3]?a[3].split(",").map(y=>y.trim()):[],p=i[r]-1,h=p+1;for(let y=p+1;y<s.length;y++){let x=s[y];if(x.trim()===""||x.trim().startsWith("#"))continue;if((x.match(/^(\s*)/)?.[1].length??0)<=c&&x.trim()!==""){h=y;break}h=y+1}let f=s.slice(p+1,h).join(`
6
+ `),g=this.extractFunctions(f).map(y=>({...y,startLine:y.startLine+p,endLine:y.endLine+p})),b=C(s,p,"@");t.push({name:l,methods:g,properties:[],isPublic:!l.startsWith("_"),implements:[],extends:d[0]||void 0,decorators:b,startLine:i[r],endLine:h})}}return t}extractImports(e){let t=[],s=e.split(`
7
+ `);for(let n of s){if(n.length>E)continue;let i=n.match(/^\s*from\s+(\S+)\s+import\s+(.+)/);if(i){let r=i[2].split(",").map(a=>a.trim().split(" as ")[0]);t.push({module:i[1],namedImports:r,isTypeOnly:!1});continue}let o=n.match(/^\s*import\s+(\S+)/);o&&t.push({module:o[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){return e.trim()?M(e).map(t=>t.trim()).filter(t=>t&&t!=="self"&&t!=="cls").map(t=>{let[s,n]=t.split(":").map(r=>r.trim()),[i,o]=s.split("=").map(r=>r.trim());return{name:i,type:n?.split("=")[0].trim()||void 0,isOptional:!!o||i.startsWith("*"),defaultValue:o||void 0}}):[]}},Z=class{language="java";supportedExtensions=[".java"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"java",filePath:t}}extractFunctions(e){let t=[],s=e.split(`
8
+ `),{logicalLines:n,lineMap:i}=I(e),o=/^\s*(public|private|protected)?\s*(static)?\s*(async)?\s*(?:<\S+>\s+)?([\w<>,.[\]?]+(?:\s+[\w<>,.[\]?]+)*)\s+(\w+)\s*\(([^)]*)\)/;for(let r=0;r<n.length;r++){let a=n[r];if(a.includes(" class ")||a.includes(" interface ")||a.length>E)continue;let c=a.match(o);if(c){let l=c[1]||"default",d=c[5],p=c[6],h=c[4]?.trim(),f=h;if(h&&h.includes("<")){let y=h.indexOf("<"),x=B(h,y);x!==void 0&&(f=h.substring(0,y)+"<"+x+">")}let g=i[r]-1,b=C(s,g,"@");t.push({name:d,parameters:this.parseParams(p),returnType:f==="void"?void 0:f,isAsync:f?.includes("CompletableFuture")||!1,isPublic:l==="public",complexity:1,decorators:b,genericParams:[],startLine:i[r],endLine:i[r]})}}return t}extractClasses(e){let t=[],s=e.split(`
9
+ `),{logicalLines:n,lineMap:i}=I(e),o=/^\s*(public|private|protected)?\s*(abstract)?\s*class\s+(\w+)(?:<[^{]*>)?(?:\s+extends\s+(\w+))?(?:\s+implements\s+([^{\s]+(?:\s+[^{\s]+)*))?\s*\{?/;for(let r=0;r<n.length;r++){if(n[r].length>E)continue;let a=n[r].match(o);if(a){let c=a[3],l=a[4],d=a[5]?a[5].split(",").map(f=>f.trim()):[],p=i[r]-1,h=C(s,p,"@");t.push({name:c,methods:[],properties:[],isPublic:(a[1]||"default")==="public",implements:d,extends:l,decorators:h,startLine:i[r],endLine:i[r]})}}return t}extractImports(e){let t=[],s=e.split(`
10
+ `);for(let n of s){if(n.length>E)continue;let i=n.match(/^\s*import +(static +)?(\S[^;]*);/);if(i){let o=i[2].trim(),r=o.split("."),a=r[r.length-1];t.push({module:o,namedImports:a==="*"?[]:[a],isTypeOnly:!1})}}return t}parseParams(e){return e.trim()?M(e).map(t=>{let n=t.trim().split(/\s+/).filter(r=>!r.startsWith("@")),i=n[n.length-1]||"",o=n.slice(0,-1).join(" ")||void 0;return{name:i,type:o,isOptional:!1,defaultValue:void 0}}):[]}},ee=class{language="csharp";supportedExtensions=[".cs"];async parseFile(e,t){return{functions:this.extractMethods(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"csharp",filePath:t}}extractMethods(e){let t=[],s=e.split(`
11
+ `),{logicalLines:n,lineMap:i}=I(e),o=/^\s*(public|private|protected|internal)?\s*(static)?\s*(async)?\s*([\w<>,.[\]?]+(?:\s+[\w<>,.[\]?]+)*)\s+(\w+)\s*\(([^)]*)\)/;for(let r=0;r<n.length;r++){let a=n[r];if(a.includes(" class ")||a.includes(" interface ")||a.includes(" namespace ")||a.length>E)continue;let c=a.match(o);if(c){let l=c[1]||"private",d=!!c[3]||c[4]?.includes("Task")||!1,p=c[4]?.trim(),h=p;if(p&&p.includes("<")){let x=p.indexOf("<"),w=B(p,x);w!==void 0&&(h=p.substring(0,x)+"<"+w+">")}let f=c[5],g=c[6],b=i[r]-1,y=C(s,b,"[");t.push({name:f,parameters:this.parseParams(g),returnType:h==="void"?void 0:h,isAsync:d,isPublic:l==="public",complexity:1,decorators:y,genericParams:[],startLine:i[r],endLine:i[r]})}}return t}extractClasses(e){let t=[],s=e.split(`
12
+ `),{logicalLines:n,lineMap:i}=I(e),o=/^\s*(public|private|protected|internal)?\s*(abstract|sealed|static|partial)?\s*class\s+(\w+)(?:<[^{]*>)?(?:\s*:\s*([^{\s]+(?:\s+[^{\s]+)*))?\s*\{?/;for(let r=0;r<n.length;r++){if(n[r].length>E)continue;let a=n[r].match(o);if(a){let c=a[3],l=a[4]?a[4].split(",").map(h=>h.trim()):[],d=i[r]-1,p=C(s,d,"[");t.push({name:c,methods:[],properties:[],isPublic:(a[1]||"internal")==="public",implements:l.slice(1),extends:l[0]||void 0,decorators:p,startLine:i[r],endLine:i[r]})}}return t}extractImports(e){let t=[],s=e.split(`
13
+ `);for(let n of s){if(n.length>E)continue;let i=n.match(/^\s*using +(static +)?(\S[^;]*);/);i&&t.push({module:i[2].trim(),namedImports:[],isTypeOnly:!1})}return t}parseParams(e){return e.trim()?M(e).map(t=>{let s=t.trim().split(/\s+/),n=s[s.length-1]||"",i=s.slice(0,-1).join(" ")||void 0;return{name:n,type:i,isOptional:i?.endsWith("?")||!1,defaultValue:void 0}}):[]}},te=class{language="go";supportedExtensions=[".go"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractStructs(e),imports:this.extractImports(e),language:"go",filePath:t}}extractFunctions(e){let t=[],s=e.split(`
14
+ `),{logicalLines:n,lineMap:i}=I(e),o=/^\s*func\s+(?:\((\w+)\s+\*?(\w+)\)\s+)?(\w+)\s*\(([^)]*)\)\s*([\w*[\](),\s]*)\s*\{?/,r=0;for(let a=0;a<n.length;a++){let c=n[a];if(c.length>E){r+=(c.match(/\{/g)?.length??0)-(c.match(/\}/g)?.length??0);continue}let l=c.match(o);if(l&&r===0){let d=l[3],p=l[4],h=l[5]?.trim()||void 0;t.push({name:d,parameters:this.parseParams(p),returnType:h||void 0,isAsync:!1,isPublic:d[0]===d[0].toUpperCase(),complexity:1,decorators:[],genericParams:[],startLine:i[a],endLine:i[a]})}r+=ce(c),r<0&&(r=0)}return t}extractStructs(e){let t=[],{logicalLines:s,lineMap:n}=I(e),i=/^\s*type\s+(\w+)\s+struct\s*\{/;for(let o=0;o<s.length;o++){let r=s[o].match(i);if(r){let a=r[1];t.push({name:a,methods:[],properties:[],isPublic:a[0]===a[0].toUpperCase(),implements:[],extends:void 0,decorators:[],startLine:n[o],endLine:n[o]})}}return t}extractImports(e){let t=[],s=/^\s*import\s+"([^"]+)"/,n=/^\s*import\s*\(/,i=/^\s*"([^"]+)"/,o=e.split(`
15
+ `),r=!1;for(let a of o)if(r){if(a.includes(")")){r=!1;continue}let c=a.match(i);c&&t.push({module:c[1],namedImports:[],isTypeOnly:!1})}else{let c=a.match(s);c?t.push({module:c[1],namedImports:[],isTypeOnly:!1}):n.test(a)&&(r=!0)}return t}parseParams(e){return e.trim()?M(e).map(t=>{let s=t.trim().split(/\s+/),n=s[0]||"",i=s.slice(1).join(" ")||void 0;return{name:n,type:i,isOptional:!1,defaultValue:void 0}}):[]}},se=class{language="rust";supportedExtensions=[".rs"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractStructsAndImpls(e),imports:this.extractImports(e),language:"rust",filePath:t}}extractFunctions(e){let t=[],s=e.split(`
16
+ `),{logicalLines:n,lineMap:i}=I(e),o=/^\s*(pub(?:\(crate\))? +)?(async +)?fn\s+(\w+)(?:<[^{]*>)?\s*\(([^)]*)\)(?:\s*->\s*([^{\s]+(?:\s+[^{\s]+)*))?\s*(?:where\s+[^{\s]+(?:\s+[^{\s]+)*)?\s*\{?/,r=0;for(let a=0;a<n.length;a++){let c=n[a],l=c.match(o);if(l&&r<=1){let d=!!l[1],p=!!l[2],h=l[3],f=l[4],g=l[5]?.trim(),b=i[a]-1,y=C(s,b,"#[");t.push({name:h,parameters:this.parseParams(f),returnType:g,isAsync:p,isPublic:d,complexity:1,decorators:y,genericParams:[],startLine:i[a],endLine:i[a]})}r+=ce(c),r<0&&(r=0)}return t}extractStructsAndImpls(e){let t=[],s=e.split(`
17
+ `),{logicalLines:n,lineMap:i}=I(e),o=/^\s*(pub(?:\(crate\))?\s+)?struct\s+(\w+)(?:<[^{]*>)?\s*/;for(let r=0;r<n.length;r++){let a=n[r].match(o);if(a){let c=i[r]-1,l=C(s,c,"#[");t.push({name:a[2],methods:[],properties:[],isPublic:!!a[1],implements:[],extends:void 0,decorators:l,startLine:i[r],endLine:i[r]})}}return t}extractImports(e){let t=[],s=e.split(`
18
+ `);for(let n of s){if(n.length>E)continue;let i=n.match(/^\s*use +(\S[^;]*);/);i&&t.push({module:i[1].trim(),namedImports:[],isTypeOnly:!1})}return t}parseParams(e){return e.trim()?M(e).map(t=>t.trim()).filter(t=>t&&t!=="&self"&&t!=="&mut self"&&t!=="self").map(t=>{let s=t.indexOf(":");if(s===-1)return{name:t,type:void 0,isOptional:!1,defaultValue:void 0};let n=t.substring(0,s).trim(),i=t.substring(s+1).trim();return{name:n,type:i,isOptional:!1,defaultValue:void 0}}):[]}},ne=class{language="swift";supportedExtensions=[".swift"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"swift",filePath:t}}extractFunctions(e){let t=[],{logicalLines:s,lineMap:n}=I(e),i=/^\s*(public|private|internal|open)?\s*(static)?\s*func\s+(\w+)(?:<[^{]*>)?\s*\(([^)]*)\)(?:\s*(async))?\s*(?:throws +)?(?:->\s*([^{\s]+(?:\s+[^{\s]+)*))?\s*\{?/;for(let o=0;o<s.length;o++){if(s[o].length>E)continue;let r=s[o].match(i);if(r){let a=r[1]||"internal",c=!!r[5],l=r[3],d=r[4],p=r[6]?.trim();t.push({name:l,parameters:this.parseParams(d),returnType:p,isAsync:c,isPublic:a==="public"||a==="open",complexity:1,decorators:[],genericParams:[],startLine:n[o],endLine:n[o]})}}return t}extractClasses(e){let t=[],{logicalLines:s,lineMap:n}=I(e),i=/^\s*(public|private|internal|open)?\s*(class|struct|protocol)\s+(\w+)(?:<[^{]*>)?(?:\s*:\s*([^{\s]+(?:\s+[^{\s]+)*))?\s*\{?/;for(let o=0;o<s.length;o++){if(s[o].length>E)continue;let r=s[o].match(i);if(r){let a=r[3],c=r[4]?r[4].split(",").map(l=>l.trim()):[];t.push({name:a,methods:[],properties:[],isPublic:(r[1]||"internal")==="public"||r[1]==="open",implements:c.slice(1),extends:c[0]||void 0,decorators:[],startLine:n[o],endLine:n[o]})}}return t}extractImports(e){let t=[],s=e.split(`
19
+ `);for(let n of s){let i=n.match(/^\s*import\s+(\w+)/);i&&t.push({module:i[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){return e.trim()?M(e).map(t=>{let s=t.trim().split(":"),n=s[0]?.trim().split(/\s+/)||[],i=n[n.length-1]||"",o=s.slice(1).join(":").trim();return{name:i,type:o||void 0,isOptional:o?.endsWith("?")||!1,defaultValue:void 0}}):[]}},ie=class{language="kotlin";supportedExtensions=[".kt",".kts"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"kotlin",filePath:t}}extractFunctions(e){let t=[],s=e.split(`
20
+ `),{logicalLines:n,lineMap:i}=I(e),o=/^\s*(public|private|protected|internal)?\s*(suspend)?\s*fun\s+(?:<[^{]*> +)?(\w+)\s*\(([^)]*)\)(?:\s*:\s*([^{=\s]+(?:\s+[^{=\s]+)*))?\s*/,r=0;for(let a=0;a<n.length;a++){let c=n[a];if(c.length>E){r+=(c.match(/\{/g)?.length??0)-(c.match(/\}/g)?.length??0);continue}let l=c.match(o);if(l&&r<=1){let d=l[1]||"public",p=!!l[2],h=l[3],f=l[4],g=l[5]?.trim();if(g&&g.includes("<")){let x=g.indexOf("<"),w=B(g,x);w!==void 0&&(g=g.substring(0,x)+"<"+w+">")}let b=i[a]-1,y=C(s,b,"@");t.push({name:h,parameters:this.parseParams(f),returnType:g,isAsync:p,isPublic:d==="public",complexity:1,decorators:y,genericParams:[],startLine:i[a],endLine:i[a]})}r+=ce(c),r<0&&(r=0)}return t}extractClasses(e){let t=[],s=e.split(`
21
+ `),{logicalLines:n,lineMap:i}=I(e),o=/^\s*(public|private|protected|internal)?\s*(data|sealed|abstract|open)?\s*class\s+(\w+)(?:<[^{]*>)?(?:\s*(?:\([^)]*\))?\s*:\s*([^{\s]+(?:\s+[^{\s]+)*))?\s*\{?/;for(let r=0;r<n.length;r++){if(n[r].length>E)continue;let a=n[r].match(o);if(a){let c=a[3],l=a[4]?a[4].split(",").map(h=>h.trim().split("(")[0].trim()):[],d=i[r]-1,p=C(s,d,"@");t.push({name:c,methods:[],properties:[],isPublic:(a[1]||"public")==="public",implements:l.slice(1),extends:l[0]||void 0,decorators:p,startLine:i[r],endLine:i[r]})}}return t}extractImports(e){let t=[],s=e.split(`
22
+ `);for(let n of s){let i=n.match(/^\s*import\s+([^\s]+)/);i&&t.push({module:i[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){return e.trim()?M(e).map(t=>{let s=t.indexOf(":");if(s===-1)return{name:t.replace("val ","").replace("var ","").trim(),type:void 0,isOptional:!1,defaultValue:void 0};let n=t.substring(0,s).replace("val ","").replace("var ","").trim(),i=t.substring(s+1).trim(),o=i.indexOf("="),r=o>=0?i.substring(0,o).trim():i,a=o>=0;return{name:n,type:r,isOptional:a||r?.endsWith("?")||!1,defaultValue:void 0}}):[]}},re=class{language="dart";supportedExtensions=[".dart"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"dart",filePath:t}}extractFunctions(e){let t=[],{logicalLines:s,lineMap:n}=I(e),i=/^\s*([\w<>,.?]+(?:\s+[\w<>,.?]+)*)\s+(\w+)\s*\(([^)]*)\)(?:\s*(async))?\s*\{/;for(let o=0;o<s.length;o++){let r=s[o];if(r.includes(" class ")||r.length>E)continue;let a=r.match(i);if(a){let c=a[1].trim(),l=c;if(c&&c.includes("<")){let f=c.indexOf("<"),g=B(c,f);g!==void 0&&(l=c.substring(0,f)+"<"+g+">")}let d=a[2],p=a[3],h=!!a[4]||l.includes("Future");t.push({name:d,parameters:this.parseParams(p),returnType:l==="void"?void 0:l,isAsync:h,isPublic:!d.startsWith("_"),complexity:1,decorators:[],genericParams:[],startLine:n[o],endLine:n[o]})}}return t}extractClasses(e){let t=[],{logicalLines:s,lineMap:n}=I(e),i=/^\s*(abstract +)?class\s+(\w+)(?:<[^{]*>)?(?:\s+extends\s+(\w+))?(?:\s+(?:with|implements)\s+([^{\s]+(?:\s+[^{\s]+)*))?\s*\{/;for(let o=0;o<s.length;o++){if(s[o].length>E)continue;let r=s[o].match(i);if(r){let a=r[2],c=r[3],l=r[4]?r[4].split(",").map(d=>d.trim()):[];t.push({name:a,methods:[],properties:[],isPublic:!a.startsWith("_"),implements:l,extends:c,decorators:[],startLine:n[o],endLine:n[o]})}}return t}extractImports(e){let t=[],s=e.split(`
23
+ `);for(let n of s){let i=n.match(/^\s*import\s+'([^']+)'/);i&&t.push({module:i[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){if(!e.trim())return[];let t=e.replace(/[{}[\]]/g,"");return M(t).map(s=>s.trim()).filter(s=>s).map(s=>{let n=s.replace("required ","").trim().split(/\s+/),i=n[n.length-1]||"",o=n.slice(0,-1).join(" ")||void 0;return{name:i,type:o,isOptional:s.includes("?")||s.includes("{"),defaultValue:void 0}})}},z=ge("ParserRegistry"),xe=["python","java","csharp","rust","swift"],ae=class u{language;supportedExtensions;wasmParser;regexParser;wasmFailCount=0;static MAX_WASM_RETRIES=3;constructor(e,t){this.wasmParser=e,this.regexParser=t,this.language=e.language,this.supportedExtensions=e.supportedExtensions}async parseFile(e,t){if(this.wasmFailCount<u.MAX_WASM_RETRIES)try{return await this.wasmParser.parseFile(e,t)}catch(s){this.wasmFailCount++;let n=s instanceof Error?s.message:String(s),i=this.wasmFailCount>=u.MAX_WASM_RETRIES;z.warn(`[${this.language}] tree-sitter WASM parser failed (attempt ${this.wasmFailCount}/${u.MAX_WASM_RETRIES}): ${n}. Falling back to regex parser (~97-98% accuracy). `+(i?"Set AQE_PARSER_REGEX_ONLY=1 to silence this warning.":"Will retry WASM on next parse."))}return this.regexParser.parseFile(e,t)}},oe=class{parsers=new Map;_wasmInitPromise=null;constructor(){this.register(new Y),this.register(new Z),this.register(new ee),this.register(new te),this.register(new se),this.register(new ne),this.register(new ie),this.register(new re),this._wasmInitPromise=this._tryLoadWasmParsers()}async _tryLoadWasmParsers(){try{let e=await import("./tree-sitter-wasm-parser-IIGEJYFU.js");if(!e.isWasmAvailable()){z.info("tree-sitter WASM parsers disabled or unavailable. Using regex parsers (~97-98% accuracy). Set AQE_PARSER_REGEX_ONLY=0 or ensure web-tree-sitter is installed to enable WASM.");return}let t=e.createWasmParsers();for(let s of xe){let n=t.get(s),i=this.parsers.get(s);n&&i&&this.parsers.set(s,new ae(n,i))}z.info("tree-sitter WASM parsers available for: "+xe.join(", "))}catch{z.info("tree-sitter WASM parser module not available. Using regex parsers for all languages.")}}register(e){this.parsers.set(e.language,e)}getParser(e){return this.parsers.get(e)}async parseFile(e,t,s){this._wasmInitPromise&&(await this._wasmInitPromise,this._wasmInitPromise=null);let n=this.parsers.get(s);if(n)return n.parseFile(e,t)}getSupportedLanguages(){return Array.from(this.parsers.keys())}supportsLanguage(e){return this.parsers.has(e)}},qe=new oe;import*as S from"node:fs/promises";import*as R from"node:path";var Re=[/\.\./,/%2e%2e/i,/%252e%252e/i,/\.\.%2f/i,/%2f\.\./i,/\.\.%5c/i,/\.\.\\/,/%c0%ae/i,/%c0%2f/i,/%c1%9c/i,/\0/,/%00/i],Se=[/^\/etc\//i,/^\/proc\//i,/^\/sys\//i,/^\/dev\//i,/^\/root\//i,/^\/home\/.+\/\./i,/^[A-Z]:\\Windows/i,/^[A-Z]:\\System/i,/^[A-Z]:\\Users\\.+\\AppData/i],le=class{name="path-traversal";getRiskLevel(){return"critical"}validate(e,t={}){let{basePath:s="",allowAbsolute:n=!1,allowedExtensions:i=[],deniedExtensions:o=[".exe",".bat",".cmd",".sh",".ps1",".dll",".so"],maxDepth:r=10,maxLength:a=4096}=t;if(e.length>a)return{valid:!1,error:`Path exceeds maximum length of ${a}`,riskLevel:"medium"};for(let f of Re)if(f.test(e))return{valid:!1,error:"Path traversal attempt detected",riskLevel:"critical"};if(!n&&(e.startsWith("/")||/^[A-Z]:/i.test(e)))return{valid:!1,error:"Absolute paths are not allowed",riskLevel:"high"};for(let f of Se)if(f.test(e))return{valid:!1,error:"Access to system paths is not allowed",riskLevel:"critical"};let c=this.normalizePath(e);if(c.includes(".."))return{valid:!1,error:"Path traversal detected after normalization",riskLevel:"critical"};if(c.split("/").filter(Boolean).length>r)return{valid:!1,error:`Path depth exceeds maximum of ${r}`,riskLevel:"low"};let d=this.getExtension(c);if(d){let f=`.${d.toLowerCase()}`,g=d.toLowerCase();if(o.length>0&&o.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not allowed`,riskLevel:"high"};if(i.length>0&&!i.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not in allowed list`,riskLevel:"medium"}}let p=s?this.joinPathsAbsolute(s,c):c,h=s.startsWith("/")?`/${this.normalizePath(s)}`:this.normalizePath(s);return s&&!p.startsWith(h)?{valid:!1,error:"Path escapes base directory",riskLevel:"critical"}:{valid:!0,normalizedPath:p,riskLevel:"none"}}normalizePath(e){let t=e.replace(/\\/g,"/");t=t.replace(/\/+/g,"/");let s=t.split("/"),n=[];for(let i of s)i==="."||i===""||(i===".."?n.length>0&&n[n.length-1]!==".."&&n.pop():n.push(i));return n.join("/")}joinPaths(...e){return e.length===0?"":e.map(t=>t.replace(/^\/+/,"").replace(/\/+$/,"")).filter(Boolean).join("/")}joinPathsAbsolute(...e){if(e.length===0)return"";let t=e[0].startsWith("/"),s=e.map(n=>{for(;n.startsWith("/");)n=n.slice(1);for(;n.endsWith("/");)n=n.slice(0,-1);return n}).filter(Boolean).join("/");return t?`/${s}`:s}getExtension(e){let t=e.match(/\.([^./\\]+)$/);return t?t[1]:null}},Me=new le,ve=(u,e)=>Me.validate(u,e);ye();var F=class extends Error{constructor(t,s,n,i){super(t);this.filePath=s;this.code=n;this.cause=i;this.name="FileReadError"}filePath;code;cause},V=class extends Error{constructor(t,s,n){super(t);this.filePath=s;this.cause=n;this.name="JsonParseError"}filePath;cause},T=class extends Error{constructor(t,s,n){super(`Path traversal detected: ${s.join(", ")}`);this.requestedPath=t;this.issues=s;this.riskLevel=n;this.name="PathTraversalError"}requestedPath;issues;riskLevel},de=class{constructor(e,t){this.maxSize=e;this.ttlMs=t}maxSize;ttlMs;cache=new Map;accessOrder=[];get(e){let t=this.cache.get(e);if(t){if(Date.now()-t.timestamp>this.ttlMs){this.delete(e);return}return this.updateAccessOrder(e),t.value}}set(e,t,s){for(this.cache.has(e)&&this.delete(e);this.cache.size>=this.maxSize&&this.accessOrder.length>0;){let n=this.accessOrder.shift();n&&this.cache.delete(n)}this.cache.set(e,{value:t,timestamp:Date.now(),size:s}),this.accessOrder.push(e)}delete(e){let t=this.cache.delete(e);if(t){let s=this.accessOrder.indexOf(e);s>-1&&this.accessOrder.splice(s,1)}return t}clear(){this.cache.clear(),this.accessOrder=[]}get size(){return this.cache.size}get totalBytes(){let e=0;return this.cache.forEach(t=>{e+=t.size}),e}updateAccessOrder(e){let t=this.accessOrder.indexOf(e);t>-1&&(this.accessOrder.splice(t,1),this.accessOrder.push(e))}prune(){let e=Date.now(),t=0,s=[];return this.cache.forEach((n,i)=>{e-n.timestamp>this.ttlMs&&s.push(i)}),s.forEach(n=>{this.delete(n),t++}),t}};function Te(u){let e="",t=0;for(;t<u.length;){let s=u[t],n=u[t+1];s==="*"&&n==="*"?u[t+2]==="/"?(e+="(?:.*/)?",t+=3):(e+=".*",t+=2):s==="*"?(e+="[^/]*",t++):s==="?"?(e+="[^/]",t++):".+^${}()|[]\\".includes(s)?(e+="\\"+s,t++):(e+=s,t++)}return new RegExp("^"+e+"$")}async function Ee(u,e,t,s){try{let n=await S.readdir(u,{withFileTypes:!0});for(let i of n){let o=R.join(u,i.name),r=R.relative(s,o);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&await Ee(o,e,t,s);else if(i.isFile()){let a=r.replace(/\\/g,"/");e.test(a)&&t.push(o)}}}catch(n){console.debug("[FileReader] Directory read error:",n instanceof Error?n.message:n)}}var k=class{basePath;cache;enableCache;stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:0,cacheEntries:0};constructor(e={}){this.basePath=e.basePath??process.cwd(),this.enableCache=e.enableCache??!0,this.cache=new de(e.maxCacheSize??100,e.cacheTtlMs??300*1e3)}resolvePath(e){let t=R.isAbsolute(e),s=ve(e,{basePath:t?"":this.basePath,allowAbsolute:!0,deniedExtensions:[".exe",".bat",".cmd",".ps1",".dll",".so"]});if(!s.valid)throw new T(e,[s.error||"Path validation failed"],s.riskLevel);if(t&&this.basePath){let n=R.resolve(this.basePath),i=R.resolve(e);if(!i.startsWith(n))throw new T(e,["Path escapes base directory"],"critical");return i}return s.normalizedPath?s.normalizedPath:t?e:R.resolve(this.basePath,e)}async readFile(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}if(this.stats.totalReads++,this.enableCache){let s=this.cache.get(t);if(s!==void 0)return this.stats.cacheHits++,this.updateCacheStats(),P(s);this.stats.cacheMisses++}try{let s=await S.readFile(t,"utf-8");return this.enableCache&&(this.cache.set(t,s,Buffer.byteLength(s,"utf-8")),this.updateCacheStats()),P(s)}catch(s){let n=s,i;switch(n.code){case"ENOENT":i="File not found: "+t;break;case"EACCES":i="Permission denied: "+t;break;case"EISDIR":i="Path is a directory: "+t;break;default:i="Failed to read file: "+t}return L(new F(i,t,n.code,n))}}async readJSON(e){let t=await this.readFile(e);if(!t.success)return t;try{let s=D(t.value);return P(s)}catch(s){let n=s,i=e;try{i=this.resolvePath(e)}catch{}return L(new V("Invalid JSON in file: "+i+" - "+n.message,i,n))}}async fileExists(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}try{return await S.access(t,S.constants.F_OK),P(!0)}catch(s){let n=s;return n.code==="ENOENT"?P(!1):L(new F("Cannot check file existence: "+t,t,n.code,n))}}async listFiles(e,t){let s;try{s=t?this.resolvePath(t):this.basePath}catch(n){if(n instanceof T)return L(n);throw n}try{if(!(await S.stat(s)).isDirectory())return L(new F("Base path is not a directory: "+s,s,"ENOTDIR"));let i=Te(e),o=[];return await Ee(s,i,o,s),o.sort(),P(o)}catch(n){let i=n;return L(new F("Failed to list files in: "+s,s,i.code,i))}}invalidateCache(e){let t=this.resolvePath(e);this.cache.delete(t),this.updateCacheStats()}clearCache(){this.cache.clear(),this.updateCacheStats()}pruneCache(){let e=this.cache.prune();return this.updateCacheStats(),e}getStats(){return{...this.stats}}resetStats(){this.stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:this.cache.totalBytes,cacheEntries:this.cache.size}}updateCacheStats(){this.stats.cacheSize=this.cache.totalBytes,this.stats.cacheEntries=this.cache.size}};J();var v={MODEL:"all-MiniLM-L6-v2",DIMENSIONS:384,CONTEXT_WINDOW:8192,BATCH_SIZE:100,MAX_RETRIES:3,RETRY_DELAY_MS:1e3,TIMEOUT_MS:3e4,DEFAULT_OLLAMA_URL:"http://localhost:11434"};var _=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 i=await this.fetchWithTimeout(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},this.timeoutMs);if(!i.ok){let r=await i.text();throw new Error(`Ollama API error (${i.status}): ${r}`)}let o=await i.json();if(o.embedding.length!==v.DIMENSIONS)throw new Error(`Invalid embedding dimensions: expected ${v.DIMENSIONS}, got ${o.embedding.length}`);return o.embedding}catch(i){if(s=A(i),s.message.includes("Invalid embedding dimensions"))throw s;if(n<this.maxRetries-1){let o=this.retryDelayMs*Math.pow(2,n);await this.sleep(o)}}throw new Error(`Failed to generate embedding after ${this.maxRetries} attempts: ${s?.message}`)}async fetchWithTimeout(e,t,s){let n=new AbortController,i=setTimeout(()=>n.abort(),s);try{return await fetch(e,{...t,signal:n.signal})}finally{clearTimeout(i)}}sleep(e){return new Promise(t=>setTimeout(t,e))}async getServerInfo(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);return e.ok?await e.json():null}catch{return null}}async ensureModelAvailable(){if(!await this.healthCheck())throw new Error(`Ollama model '${v.MODEL}' is not available. Please run: ollama pull ${v.MODEL}`)}};import{createHash as Fe}from"crypto";var $=class{cache;maxSize;hits;misses;constructor(e=1e4){this.cache=new Map,this.maxSize=e,this.hits=0,this.misses=0}hashContent(e,t){return Fe("sha256").update(`${t}:${e}`).digest("hex")}get(e,t){let s=this.hashContent(e,t),n=this.cache.get(s);return n?(this.hits++,this.cache.delete(s),this.cache.set(s,n),n.embedding):(this.misses++,null)}set(e,t,s){let n=this.hashContent(e,t);if(this.cache.size>=this.maxSize&&!this.cache.has(n)){let o=this.cache.keys().next().value;o&&this.cache.delete(o)}let i={embedding:s,timestamp:Date.now(),model:t};this.cache.set(n,i)}has(e,t){let s=this.hashContent(e,t);return this.cache.has(s)}getStats(){let e=this.hits+this.misses,t=e>0?this.hits/e:0;return{size:this.cache.size,hitRate:t,hits:this.hits,misses:this.misses}}clear(){this.cache.clear(),this.hits=0,this.misses=0}evictOlderThan(e){let s=Date.now()-e,n=0;for(let[i,o]of this.cache.entries())o.timestamp<s&&(this.cache.delete(i),n++);return n}getMemoryUsageEstimate(){return this.cache.size*3172}export(){return Array.from(this.cache.entries()).map(([e,t])=>({key:e,entry:t}))}import(e){this.cache.clear();for(let{key:t,entry:s}of e)this.cache.size<this.maxSize&&this.cache.set(t,s)}};J();var K=class{client;cache;batchSize;enableFallback;ollamaAvailable=null;constructor(e={}){this.client=new _(e.ollamaBaseUrl),this.cache=e.cache??new $(e.maxCacheSize),this.batchSize=e.batchSize??v.BATCH_SIZE,this.enableFallback=e.enableFallback??!0}async embed(e){let t=this.cache.get(e,v.MODEL);if(t)return t;let s;if(await this.isOllamaAvailable())s=await this.client.generateEmbedding(e);else if(this.enableFallback)s=this.generatePseudoEmbedding(e);else throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);return this.cache.set(e,v.MODEL,s),s}formatForEmbedding(e){let t=[];e.language&&t.push(e.language),e.type&&t.push(e.type),e.name&&t.push(e.name);let s=t.length>0?`${t.join(" ")}: `:"",n=v.CONTEXT_WINDOW*4,i=e.content.trim();if(s.length+i.length>n){let o=n-s.length-3;i=i.substring(0,o)+"..."}return s+i}async embedBatch(e){let t=[];for(let s of e){let n=await this.embed(s);t.push(n)}return t}async embedCodeChunks(e,t){let s=Date.now(),n=[],i=0,o=0,r=await this.isOllamaAvailable();if(r)await this.client.ensureModelAvailable();else if(!this.enableFallback)throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);for(let c=0;c<e.length;c+=this.batchSize){let l=e.slice(c,Math.min(c+this.batchSize,e.length)),d=await this.processBatch(l,r);n.push(...d);for(let p of d)p.cached?i++:o++;if(t){let p=c+l.length,h=e.length,g=(Date.now()-s)/p,y=(h-p)*g;t({current:p,total:h,percentage:p/h*100,estimatedTimeRemainingMs:y})}}let a=Date.now()-s;return{results:n,stats:{totalChunks:e.length,cachedHits:i,computedNew:o,totalTimeMs:a,avgTimePerChunk:a/e.length}}}async processBatch(e,t){let s=[],n=e.map(async o=>{let r=this.formatForEmbedding(o),a=Date.now(),c=this.cache.get(r,v.MODEL);if(c)return{chunkId:o.id,embedding:c,model:v.MODEL,cached:!0,computeTimeMs:Date.now()-a};try{let l;return t?l=await this.client.generateEmbedding(r):l=this.generatePseudoEmbedding(r),this.cache.set(r,v.MODEL,l),{chunkId:o.id,embedding:l,model:t?v.MODEL:"pseudo-embedding",cached:!1,computeTimeMs:Date.now()-a}}catch(l){throw new Error(`Failed to generate embedding for chunk ${o.id}: ${G(l)}`)}}),i=await Promise.all(n);return s.push(...i),s}async isOllamaAvailable(){return this.ollamaAvailable!==null?this.ollamaAvailable:(this.ollamaAvailable=await this.client.healthCheck(),this.ollamaAvailable)}resetOllamaCheck(){this.ollamaAvailable=null}generatePseudoEmbedding(e){let t=new Array(v.DIMENSIONS).fill(0),s=e.split(/\s+|[^\w]+/).filter(o=>o.length>0);for(let o=0;o<s.length;o++){let r=s[o];for(let a=0;a<r.length&&a<t.length;a++)t[(o+a)%t.length]+=r.charCodeAt(a)/1e3}let n=[[/class\s+\w+/,0],[/function\s+\w+/,1],[/async\s+|await\s+|Promise/,2],[/interface\s+\w+/,3],[/export\s+/,4],[/import\s+/,5],[/try\s*{/,6],[/\.(map|filter|reduce)\(/,7]];for(let[o,r]of n)o.test(e)&&(t[r]+=.5);let i=Math.sqrt(t.reduce((o,r)=>o+r*r,0))||1;return t.map(o=>o/i)}clearCache(){this.cache.clear()}getCacheStats(){return this.cache.getStats()}async healthCheck(){return await this.client.healthCheck()}async getServerInfo(){return await this.client.getServerInfo()}getDimensions(){return v.DIMENSIONS}getConfig(){return{model:v.MODEL,dimensions:v.DIMENSIONS,contextWindow:v.CONTEXT_WINDOW,batchSize:this.batchSize,maxRetries:v.MAX_RETRIES,enableFallback:this.enableFallback}}};J();ye();import{existsSync as Oe,statSync as ke}from"fs";import{dirname as _e,resolve as $e,join as q}from"path";function Ae(u){switch(u){case"ts":case"mts":case"cts":return"tree-sitter-typescript.wasm";case"tsx":return"tree-sitter-tsx.wasm";case"js":case"jsx":case"mjs":case"cjs":return"tree-sitter-javascript.wasm";default:return null}}var U=u=>u.startPosition.row+1,j=(u,e)=>u.childForFieldName(e)?.text??"";function ue(u){for(let e=0;e<u.childCount;e++){let t=u.child(e);if(t){if(t.type==="async")return!0;if(t.type==="function"||t.type==="function_declaration")break}}return!1}function Ne(u){for(let e=0;e<u.childCount;e++)if(u.child(e)?.type==="accessibility_modifier"){let s=u.child(e).text;if(s==="private")return"private";if(s==="protected")return"protected"}return"public"}function De(u){let e=j(u,"name")||"(anonymous)",t=u.childForFieldName("body"),s=[];if(t)for(let n=0;n<t.childCount;n++){let i=t.child(n);i&&i.type==="method_definition"&&s.push({name:j(i,"name"),startLine:U(i),isAsync:ue(i),visibility:Ne(i)})}return{name:e,startLine:U(u),methods:s}}function pe(u){return u.replace(/^['"`]|['"`]$/g,"")}async function me(u,e){let t=Ae(e);if(!t)return null;let s=await be(t);if(!s)return null;let n=null;try{let i=s.parse(u);n=i;let o=i.rootNode;if(!o)return null;let r={functions:[],classes:[],interfaces:[],imports:[]},a=[o];for(;a.length;){let c=a.pop(),l=!0;switch(c.type){case"function_declaration":case"generator_function_declaration":r.functions.push({name:j(c,"name"),startLine:U(c),isAsync:ue(c),visibility:"public"}),l=!1;break;case"class_declaration":case"class":r.classes.push(De(c)),l=!1;break;case"interface_declaration":r.interfaces.push({name:j(c,"name"),startLine:U(c)}),l=!1;break;case"lexical_declaration":case"variable_declaration":{for(let d=0;d<c.childCount;d++){let p=c.child(d);if(!p||p.type!=="variable_declarator")continue;let h=p.childForFieldName("value");if(h&&(h.type==="arrow_function"||h.type==="function"||h.type==="function_expression"))r.functions.push({name:j(p,"name"),startLine:U(p),isAsync:ue(h),visibility:"public"});else if(h&&h.type==="call_expression"&&h.child(0)?.text==="require"){let f=h.childForFieldName("arguments")?.child(1);f&&f.type==="string"&&r.imports.push(pe(f.text))}}l=!1;break}case"import_statement":{let d=c.childForFieldName("source");d&&r.imports.push(pe(d.text)),l=!1;break}case"call_expression":{let d=c.child(0);if(d&&d.text==="require"){let h=c.childForFieldName("arguments")?.child(1);h&&h.type==="string"&&r.imports.push(pe(h.text))}break}}if(l)for(let d=c.childCount-1;d>=0;d--){let p=c.child(d);p&&a.push(p)}}return r}catch{return null}finally{n?.delete?.()}}var Ke={maxNodes:1e5,maxEdgesPerNode:500,namespace:"code-intelligence:kg",enableVectorEmbeddings:!0,embeddingDimension:384,enableLLMExtraction:!0,llmModelTier:2,llmMaxTokens:2048},he=fe.create("code-intelligence/knowledge-graph"),H=new Set(["ts","tsx","js","jsx"]),Ie=class{config;memory;nodeCache=new Map;edgeIndex=new Map;allEdgesCache;tsParser;fileReader;embedder;llmRouter;constructor(e,t={}){this.config={...Ke,...t},this.isKnowledgeGraphDependencies(e)?(this.memory=e.memory,this.llmRouter=e.llmRouter):(this.memory=e,this.llmRouter=void 0),this.tsParser=new N,this.fileReader=new k,this.embedder=new K({enableFallback:!0})}isKnowledgeGraphDependencies(e){return e.memory!==void 0}get nsOpts(){return{namespace:this.config.namespace}}async index(e){let t=Date.now(),s=[],n=0,i=0,o=new Map;try{let{paths:r,incremental:a=!1,includeTests:c=!0,languages:l}=e;a||await this.clear();for(let h of r)try{if(l&&l.length>0){let b=this.getFileExtension(h);if(!this.matchesLanguage(b,l))continue}if(!c&&this.isTestFile(h))continue;let f=this.getFileExtension(h);H.has(f)||o.set(f||"(none)",(o.get(f||"(none)")??0)+1);let g=await this.indexFile(h,a);n+=g.nodes,i+=g.edges}catch(f){s.push({file:h,error:G(f)})}let d=Date.now()-t,p=[];if(o.size>0){let h=Array.from(H).join(", ");for(let[f,g]of o){let b=`${g} file(s) with extension '.${f}' were indexed as plain nodes: no dependency extractor for this language, so 'deps'/'impact' will report 0 edges for them. Supported: ${h}.`;p.push(b),he.warn(b)}}return await this.storeIndexMetadata({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,indexedAt:new Date().toISOString()}),P({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,errors:s,warnings:p})}catch(r){return L(A(r))}}async query(e){try{let{query:t,type:s,limit:n=100}=e;return s==="cypher"?this.executeCypherQuery(t,n):this.executeNaturalLanguageQuery(t,n)}catch(t){return L(A(t))}}async mapDependencies(e){try{let{files:t,direction:s,depth:n=3}=e,i=[],o=[],r=new Set,a=[];for(let l of t)await this.traverseDependencies(l,s,n,r,i,o,[],a);let c=this.calculateDependencyMetrics(i,o);return P({nodes:i,edges:o,cycles:a,metrics:c})}catch(t){return L(A(t))}}async getNode(e){if(this.nodeCache.has(e))return this.nodeCache.get(e);let t=`${this.config.namespace}:node:${e}`,s=await this.memory.get(t,this.nsOpts);return s&&this.nodeCache.set(e,s),s}async getEdges(e,t){let s=await this.loadAllEdges();return this.filterEdgesByDirection(s,e,t)}async loadAllEdges(){if(this.allEdgesCache)return this.allEdgesCache;let e=[],t=`${this.config.namespace}:edge:*`,s=await this.memory.search(t,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let n of s){let i=await this.memory.get(n,this.nsOpts);i&&e.push(i)}return this.allEdgesCache=e,e}async clear(){this.nodeCache.clear(),this.edgeIndex.clear(),this.allEdgesCache=void 0;for(let e of[`${this.config.namespace}:node:`,`${this.config.namespace}:edge:`]){let t=await this.memory.search(`${e}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let s of t)await this.memory.delete(s,this.nsOpts)}}async removeFileFromGraph(e){let t=this.pathToNodeId(e),s=this.config.namespace,n=await this.memory.search(`${s}:node:${t}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of n)await this.memory.delete(o,this.nsOpts),this.nodeCache.delete(o.slice(`${s}:node:`.length));let i=await this.memory.search(`${s}:edge:*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of i){let r=await this.memory.get(o,this.nsOpts);r&&(r.source===t||r.source.startsWith(`${t}:`))&&await this.memory.delete(o,this.nsOpts)}this.edgeIndex.delete(t),this.allEdgesCache=void 0}isLLMExtractionAvailable(){return this.config.enableLLMExtraction===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){case 1:return"claude-haiku-4-5-20251001";case 2:return"claude-sonnet-4-6";case 3:return"claude-sonnet-4-6";case 4:return"claude-opus-4-7";default:return"claude-sonnet-4-6"}}async extractRelationshipsWithLLM(e,t){if(!this.llmRouter)return{semanticRelationships:[],designPatterns:[],architecturalBoundaries:[],dependencyImpacts:[]};try{let s=this.buildRelationshipExtractionPrompt(e,t),n=this.getModelForTier(this.config.llmModelTier??2),i=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software architect analyzing code structure. Extract:
24
+ 1. Semantic relationships between code entities (inheritance, composition, dependency, collaboration)
25
+ 2. Design patterns used (Factory, Singleton, Observer, Strategy, etc.)
26
+ 3. Architectural boundaries (layers, modules, domains)
27
+ 4. Dependency impact analysis (which changes would affect which components)
28
+
29
+ Return a JSON object with:
30
+ {
31
+ "semanticRelationships": [{"source": "...", "target": "...", "type": "...", "description": "..."}],
32
+ "designPatterns": [{"pattern": "...", "participants": ["..."], "location": "...", "confidence": 0.0-1.0}],
33
+ "architecturalBoundaries": [{"name": "...", "type": "layer|module|domain", "entities": ["..."]}],
34
+ "dependencyImpacts": [{"entity": "...", "impactedBy": ["..."], "impacts": ["..."], "severity": "low|medium|high"}]
35
+ }
36
+
37
+ Be precise and only report high-confidence findings.`},{role:"user",content:s}],model:n,maxTokens:this.config.llmMaxTokens??2048,temperature:.2});return i.content?this.parseLLMRelationshipResponse(i.content):{semanticRelationships:[],designPatterns:[],architecturalBoundaries:[],dependencyImpacts:[]}}catch{return he.warn("LLM relationship extraction failed:"),{semanticRelationships:[],designPatterns:[],architecturalBoundaries:[],dependencyImpacts:[]}}}buildRelationshipExtractionPrompt(e,t){let s=`## Code to Analyze:
38
+ \`\`\`typescript
39
+ ${e}
40
+ \`\`\`
41
+
42
+ `;if(t.length>0){s+=`## Already Identified Entities:
43
+ `;for(let n of t)s+=`- ${n.type}: ${n.name} (line ${n.line}, ${n.visibility})
44
+ `;s+=`
45
+ `}return s+=`## Analysis Requirements:
46
+ `,s+=`1. Identify semantic relationships between the entities above
47
+ `,s+=`2. Detect any design patterns in use
48
+ `,s+=`3. Identify architectural boundaries or layers
49
+ `,s+=`4. Analyze which entities would be impacted by changes to others
50
+ `,s}parseLLMRelationshipResponse(e){try{let t=e.match(/\{[\s\S]*\}/);if(t){let s=D(t[0]);return{semanticRelationships:Array.isArray(s.semanticRelationships)?s.semanticRelationships:[],designPatterns:Array.isArray(s.designPatterns)?s.designPatterns:[],architecturalBoundaries:Array.isArray(s.architecturalBoundaries)?s.architecturalBoundaries:[],dependencyImpacts:Array.isArray(s.dependencyImpacts)?s.dependencyImpacts:[]}}}catch{}return{semanticRelationships:[],designPatterns:[],architecturalBoundaries:[],dependencyImpacts:[]}}async enhanceQueryWithLLM(e,t){if(!this.llmRouter||t.length===0)return{enhancedResults:t,insights:[]};try{let s=this.getModelForTier(this.config.llmModelTier??2),n=await this.llmRouter.chat({messages:[{role:"system",content:`You are a code intelligence assistant. Given a query and search results from a knowledge graph, provide:
51
+ 1. Ranking of results by relevance to the query
52
+ 2. Key insights about how the results relate to the query
53
+ 3. Suggestions for related code to explore
54
+
55
+ Return JSON: { "rankedIds": ["id1", "id2", ...], "insights": ["insight1", "insight2", ...] }`},{role:"user",content:`Query: "${e}"
56
+
57
+ Results:
58
+ ${JSON.stringify(t.map(i=>({id:i.id,label:i.label,properties:i.properties})),null,2)}`}],model:s,maxTokens:1024,temperature:.3});if(n.content)try{let i=n.content.match(/\{[\s\S]*\}/);if(i){let o=D(i[0]),r=o.rankedIds||[],a=o.insights||[],c=new Map(t.map(d=>[d.id,d])),l=[];for(let d of r){let p=c.get(d);p&&(l.push(p),c.delete(d))}return l.push(...Array.from(c.values())),{enhancedResults:l,insights:a}}}catch{}return{enhancedResults:t,insights:[]}}catch{return he.warn("LLM query enhancement failed:"),{enhancedResults:t,insights:[]}}}async indexFile(e,t=!1){let s=0,n=0;this.fileReader.invalidateCache(e),t&&await this.removeFileFromGraph(e);let i=await this.createFileNode(e);s++;let o=await this.extractEntities(e);for(let a of o){let c=await this.createEntityNode(a,e);s++,await this.createEdge(i.id,c.id,"contains"),n++}let r=await this.extractImports(e);for(let a of r){let c=this.resolveImportPath(a,e),l=this.pathToNodeId(c);await this.createEdge(i.id,l,"import"),n++}if(this.isLLMExtractionAvailable()){let a=await this.fileReader.readFile(e);if(a.success){let c=await this.extractRelationshipsWithLLM(a.value,o);n+=await this.storeLLMRelationships(i.id,c)}}return{nodes:s,edges:n}}async storeLLMRelationships(e,t){let s=0;for(let i of t.semanticRelationships){let o=`${e}:*:${i.source}`,r=`${e}:*:${i.target}`;await this.createEdge(o,r,i.type),s++}let n=this.nodeCache.get(e);return n&&(t.designPatterns.length>0&&(n.properties.designPatterns=t.designPatterns),t.architecturalBoundaries.length>0&&(n.properties.architecturalBoundaries=t.architecturalBoundaries),t.dependencyImpacts.length>0&&(n.properties.dependencyImpacts=t.dependencyImpacts),this.nodeCache.set(e,n)),s}async createFileNode(e){let s={id:this.pathToNodeId(e),label:"File",properties:{path:e,name:this.getFileName(e),extension:this.getFileExtension(e),type:this.getFileType(e)}};return await this.storeNode(s),s}async createEntityNode(e,t){let s=`${this.pathToNodeId(t)}:${e.type}:${e.name}`,n={id:s,label:e.type,properties:{name:e.name,file:t,line:e.line,visibility:e.visibility,async:e.isAsync}};if(await this.storeNode(n),this.config.enableVectorEmbeddings){let i=await this.generateEmbedding(e);await this.memory.storeVector(`${this.config.namespace}:node:${s}`,i,{nodeId:s,type:e.type,name:e.name})}return n}async createEdge(e,t,s){let n=`${e}--${s}-->${t}`,i={source:e,target:t,type:s},o=this.edgeIndex.get(e)||[];return o.push(i),this.edgeIndex.set(e,o),await this.memory.set(`${this.config.namespace}:edge:${n}`,i,this.nsOpts),this.allEdgesCache=void 0,i}async storeNode(e){if(this.nodeCache.size>=this.config.maxNodes){let t=this.nodeCache.keys().next().value;t&&(this.nodeCache.delete(t),this.edgeIndex.delete(t))}this.nodeCache.set(e.id,e),await this.memory.set(`${this.config.namespace}:node:${e.id}`,e,this.nsOpts)}async extractEntities(e){let t=this.getFileExtension(e),s=[];if(H.has(t)){let n=await this.fileReader.readFile(e),i=this.getFileName(e);if(n.success){let o=!1;try{let r=await me(n.value,t);if(r){for(let a of r.functions)s.push({type:"function",name:a.name,line:a.startLine,visibility:a.visibility,isAsync:a.isAsync});for(let a of r.classes){s.push({type:"class",name:a.name,line:a.startLine,visibility:"public",isAsync:!1});for(let c of a.methods)s.push({type:"function",name:`${a.name}.${c.name}`,line:c.startLine,visibility:c.visibility,isAsync:c.isAsync})}for(let a of r.interfaces)s.push({type:"interface",name:a.name,line:a.startLine,visibility:"public",isAsync:!1});o=!0}}catch{}if(!o)try{let r=this.tsParser.parseFile(i,n.value);for(let a of this.tsParser.extractFunctions(r))s.push({type:"function",name:a.name,line:a.startLine,visibility:"public",isAsync:a.isAsync});for(let a of this.tsParser.extractClasses(r)){s.push({type:"class",name:a.name,line:a.startLine,visibility:"public",isAsync:!1});for(let c of a.methods)s.push({type:"function",name:`${a.name}.${c.name}`,line:c.startLine,visibility:c.visibility,isAsync:c.isAsync})}for(let a of this.tsParser.extractInterfaces(r))s.push({type:"interface",name:a.name,line:a.startLine,visibility:"public",isAsync:!1})}catch{}s.length===0&&s.push({type:"module",name:i.replace(/\.[^.]+$/,""),line:1,visibility:"public",isAsync:!1})}else s.push({type:"module",name:this.getFileName(e).replace(/\.[^.]+$/,""),line:1,visibility:"public",isAsync:!1})}else if(t==="py"){let n=await this.fileReader.readFile(e);if(n.success){let o=n.value.split(`
59
+ `),r=/^class\s+(\w+)\s*(?:\([^)]*\))?\s*:/,a=/^(async\s+)?def\s+(\w+)\s*\(/,c=null,l=0;for(let d=0;d<o.length;d++){let p=o[d],h=d+1,f=p.trimStart(),g=p.length-f.length;c&&g<=l&&(c=null);let b=f.match(r);if(b){let x=b[1];s.push({type:"class",name:x,line:h,visibility:x.startsWith("_")?"private":"public",isAsync:!1}),c=x,l=g;continue}let y=f.match(a);if(y){let x=!!y[1],w=y[2],we=c!==null&&g>l,X="public";w.startsWith("__")&&!w.endsWith("__")?X="private":w.startsWith("_")&&(X="protected"),s.push({type:"function",name:we?`${c}.${w}`:w,line:h,visibility:X,isAsync:x})}}s.length===0&&s.push({type:"module",name:this.getFileName(e).replace(".py",""),line:1,visibility:"public",isAsync:!1})}else s.push({type:"module",name:this.getFileName(e).replace(".py",""),line:1,visibility:"public",isAsync:!1})}return s}async extractImports(e){let t=this.getFileExtension(e),s=[];if(H.has(t)){let n=await this.fileReader.readFile(e);if(n.success){let i=this.getFileName(e),o=null;try{let r=await me(n.value,t);r&&(o=r.imports)}catch{o=null}if(o===null)try{let r=this.tsParser.parseFile(i,n.value);o=this.tsParser.extractImports(r).map(a=>a.module)}catch{o=[]}for(let r of o)r.startsWith("node:")||s.push(r)}}return s}async executeCypherQuery(e,t){let s=[],n=[],i=new Map,o=/MATCH\s+\((\w+):(\w+)\)\s*-\[(\w+)?:?(\w+)?\]\s*->\s*\((\w+):(\w+)\)/i.exec(e);if(o){let[,a,c,,l,d,p]=o,h=await this.findNodesByLabel(c,t*2);i.set(a,h);for(let f of h.slice(0,t)){let g=await this.getEdges(f.id,"outgoing");for(let b of g){if(l&&b.type!==l)continue;let y=await this.getNode(b.target);y&&y.label===p&&(s.some(x=>x.id===f.id)||s.push(f),s.some(x=>x.id===y.id)||s.push(y),n.some(x=>x.source===b.source&&x.target===b.target&&x.type===b.type)||n.push(b))}}d&&i.set(d,s.filter(f=>f.label===p))}else{let a=/MATCH\s+\((\w+):(\w+)\)/i.exec(e);if(a){let[,c,l]=a,d=await this.findNodesByLabel(l,t);i.set(c,d),s.push(...d)}}let r=/WHERE\s+(\w+)\.(\w+)\s*=\s*['"]?([^'")\s]+)['"]?/i.exec(e);if(r){let[,a,c,l]=r,p=(i.get(a)||s).filter(g=>{let b=g.properties[c];return b!==void 0&&String(b)===l});s.length=0,s.push(...p.slice(0,t));let h=new Set(s.map(g=>g.id)),f=n.filter(g=>h.has(g.source)&&h.has(g.target));n.length=0,n.push(...f)}return P({nodes:s.slice(0,t),edges:n,metadata:{query:e,type:"cypher",resultCount:s.length,edgeCount:n.length}})}async findNodesByLabel(e,t){let s=[],n=`${this.config.namespace}:node:*`,i=await this.memory.search(n,t*2,this.nsOpts);for(let o of i){let r=await this.memory.get(o,this.nsOpts);if(r&&r.label===e&&(s.push(r),s.length>=t))break}return s}async executeNaturalLanguageQuery(e,t){if(this.config.enableVectorEmbeddings){let r=await this.generateQueryEmbedding(e),a=await this.memory.vectorSearch(r,t),c=[];for(let l of a){let d=l.metadata?.nodeId;if(d){let p=await this.getNode(d);p&&c.push(p)}}return P({nodes:c,edges:[],metadata:{query:e,type:"natural-language",resultCount:c.length,searchScores:a.map(l=>l.score)}})}let s=e.toLowerCase().split(/\s+/),n=`${this.config.namespace}:node:*`,i=await this.memory.search(n,t*3,this.nsOpts),o=[];for(let r of i){let a=await this.memory.get(r,this.nsOpts);if(a){let c=JSON.stringify(a.properties).toLowerCase();if(s.some(l=>c.includes(l))&&(o.push(a),o.length>=t))break}}return P({nodes:o,edges:[],metadata:{query:e,type:"keyword",resultCount:o.length}})}async traverseDependencies(e,t,s,n,i,o,r,a){if(s<=0||n.has(e)){let f=r.indexOf(e);f>=0&&a.push([...r.slice(f),e]);return}n.add(e),r.push(e);let c=this.pathToNodeId(e),l=new Set(["import","call","extends","implements"]),d=(await this.getEdges(c,t)).filter(f=>l.has(f.type)),p=d.filter(f=>f.target===c).length,h=d.filter(f=>f.source===c).length;i.push({id:c,path:e,type:"file",inDegree:p,outDegree:h});for(let f of d){let g={source:f.source,target:f.target,type:f.type};if(o.some(y=>y.source===g.source&&y.target===g.target)||o.push(g),f.source!==c)continue;let b=this.nodeIdToPath(f.target);b&&await this.traverseDependencies(b,t,s-1,n,i,o,r,a)}r.pop()}calculateDependencyMetrics(e,t){let s=e.length,n=t.length,i=s>0?e.reduce((a,c)=>a+c.inDegree+c.outDegree,0)/s:0,o=0;if(e.length>0){let a=new Map;for(let l of t){let d=a.get(l.source)||[];d.push(l.target),a.set(l.source,d)}let c=new Map;for(let l of e)c.has(l.id)||this.bfsDepth(l.id,a,c),o=Math.max(o,c.get(l.id)||0)}let r=n-s+2;return{totalNodes:s,totalEdges:n,avgDegree:Math.round(i*100)/100,maxDepth:o,cyclomaticComplexity:Math.max(1,r)}}bfsDepth(e,t,s){let n=[{id:e,depth:0}];for(;n.length>0;){let i=n.shift(),o=s.get(i.id)??-1;i.depth>o&&s.set(i.id,i.depth);let r=t.get(i.id)||[];for(let a of r)(!s.has(a)||(s.get(a)??0)<i.depth+1)&&n.push({id:a,depth:i.depth+1})}}filterEdgesByDirection(e,t,s){return e.filter(n=>s==="incoming"?n.target===t:s==="outgoing"?n.source===t:n.source===t||n.target===t)}async storeIndexMetadata(e){}async generateEmbedding(e){let t=`${e.type} ${e.name} ${e.visibility}${e.isAsync?" async":""}`;try{return await this.embedder.embed(t)}catch{return this.fallbackEmbedding(t)}}async generateQueryEmbedding(e){try{return await this.embedder.embed(e)}catch{return this.fallbackEmbedding(e)}}fallbackEmbedding(e){let t=new Array(this.config.embeddingDimension).fill(0),s=e.toLowerCase().split(/\s+/);for(let i=0;i<s.length;i++){let o=s[i];for(let r=0;r<o.length&&r<t.length;r++)t[(i+r)%t.length]+=o.charCodeAt(r)/1e3}let n=Math.sqrt(t.reduce((i,o)=>i+o*o,0))||1;return t.map(i=>i/n)}pathToNodeId(e){return e.replace(/[/\\]/g,":").replace(/\./g,"_")}resolveImportPath(e,t){if(!e.startsWith("."))return e;let s=$e(_e(t),e),n=[s,`${s}.ts`,`${s}.tsx`,`${s}.js`,`${s}.jsx`,`${s}.mjs`,`${s}.cjs`,q(s,"index.ts"),q(s,"index.tsx"),q(s,"index.js"),q(s,"index.jsx")];for(let i of n)try{if(Oe(i)&&ke(i).isFile())return i}catch{}return`${s}.ts`}nodeIdToPath(e){let t=e.replace(/:/g,"/").replace(/_(?=[^_]*$)/,".");return t.includes("/")?t:null}getFileName(e){return e.split(/[/\\]/).pop()||e}getFileExtension(e){let s=this.getFileName(e).split(".");return s.length>1?s.pop():""}getFileType(e){let t=this.getFileExtension(e);return{ts:"typescript",tsx:"typescript-react",js:"javascript",jsx:"javascript-react",py:"python",go:"go",java:"java",rs:"rust",rb:"ruby",cs:"csharp",swift:"swift"}[t]||"unknown"}matchesLanguage(e,t){let s={typescript:["ts","tsx"],javascript:["js","jsx"],python:["py"],go:["go"],java:["java"],rust:["rs"],csharp:["cs"],swift:["swift"]};return t.some(n=>(s[n.toLowerCase()]||[n]).includes(e))}isTestFile(e){return[/\.test\.[tj]sx?$/,/\.spec\.[tj]sx?$/,/_test\.[tj]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/].some(s=>s.test(e))}destroy(){this.nodeCache.clear(),this.edgeIndex.clear()}};export{m as a,qe as b,v as c,K as d,N as e,k as f,Ie as g};
@@ -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.10.1");process.exit(0)}
2
- import{j as d}from"./chunk-BF7MUYWC.js";import{a as u,c as g}from"./chunk-2TDWCXZ6.js";g();var m=[{type:"email",pattern:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,mask:n=>n[0]+"***@"+n.split("@")[1]},{type:"ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g,mask:()=>"***-**-****"},{type:"credit-card",pattern:/\b(?:\d[ -]*?){13,19}\b/g,mask:n=>"****-****-****-"+n.replace(/\D/g,"").slice(-4)},{type:"phone",pattern:/\b(?:\+?1[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}\b/g,mask:n=>n.slice(0,3)+"***"+n.slice(-2)},{type:"api-key",pattern:/(?:key|token|api_key|apikey|secret|password|passwd|auth)=([A-Za-z0-9_\-]{16,})/gi,mask:()=>"***REDACTED***"}],y=class extends d{config={name:"qe/security/url-validate",description:"Validate URL security: checks for XSS/injection patterns, unsafe protocols, and scans URL query parameters for PII exposure (emails, SSNs, credit cards, API keys).",domain:"security-compliance",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{url:{type:"string",description:"URL to validate for security threats and PII exposure"},enablePII:{type:"boolean",description:"Enable PII exposure scanning in URL and query parameters",default:!0}},required:["url"]}}async execute(s,r){try{let e=this.validateURLSecurity(s.url),t=s.enablePII!==!1?this.scanForPII(s.url):{scanned:!1,found:!1,types:[],details:[]},c=e.issues.length+(t.found?t.types.length:0)===0?`URL passed all checks (security: clean, PII: ${t.scanned?"none found":"not scanned"})`:`URL has ${e.issues.length} security issue(s)${t.found?` and ${t.types.length} PII type(s) exposed in URL`:""}`;return{success:!0,data:{url:s.url,urlSecurity:e,piiExposure:t,summary:c}}}catch(e){return{success:!1,error:u(e)}}}validateURLSecurity(s){let r=[],e="none";try{let t=new URL(s);["http:","https:"].includes(t.protocol)||(r.push({type:"unsafe-protocol",description:`Protocol ${t.protocol} is not allowed`,severity:"high"}),e="high");let o=[/<script/i,/javascript:/i,/on\w+=/i,/data:text\/html/i];for(let i of o)if(i.test(s)){r.push({type:"xss",description:"Potential XSS pattern detected in URL",severity:"critical"}),e="critical";break}let c=[/'.*or.*'/i,/union.*select/i,/drop.*table/i,/;\s*--/i];for(let i of c)if(i.test(s)){r.push({type:"sql-injection",description:"Potential SQL injection pattern detected in URL",severity:"critical"}),e="critical";break}/\.\.[/\\]/.test(s)&&(r.push({type:"path-traversal",description:"Potential path traversal pattern (../) detected",severity:"high"}),e!=="critical"&&(e="high"));let a=["redirect","url","next","return","returnUrl","goto"];for(let i of a){let l=t.searchParams.get(i);l&&/^https?:\/\//.test(l)&&(r.push({type:"open-redirect",description:`Query parameter "${i}" contains an external URL \u2014 potential open redirect`,severity:"medium"}),e==="none"&&(e="medium"))}}catch{r.push({type:"invalid-url",description:"URL could not be parsed",severity:"critical"}),e="critical"}return{valid:r.length===0,riskLevel:e,issues:r}}scanForPII(s){let r=[],e=new Set,t;try{t=decodeURIComponent(s)}catch{t=s}let o="",c="";try{let a=new URL(t);o=a.search,c=a.pathname}catch{o=t}for(let{type:a,pattern:i,mask:l}of m){i.lastIndex=0;let p;for(;(p=i.exec(t))!==null;){e.add(a);let h=o.includes(p[0])?"query-parameter":c.includes(p[0])?"path":"url";r.push({type:a,location:h,masked:l(p[0])})}}return{scanned:!0,found:e.size>0,types:Array.from(e),details:r}}};export{y as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.3");process.exit(0)}
2
+ import{j as d}from"./chunk-2EQVYYBF.js";import{a as u,c as g}from"./chunk-3LRK7PYN.js";g();var m=[{type:"email",pattern:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,mask:n=>n[0]+"***@"+n.split("@")[1]},{type:"ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g,mask:()=>"***-**-****"},{type:"credit-card",pattern:/\b(?:\d[ -]*?){13,19}\b/g,mask:n=>"****-****-****-"+n.replace(/\D/g,"").slice(-4)},{type:"phone",pattern:/\b(?:\+?1[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}\b/g,mask:n=>n.slice(0,3)+"***"+n.slice(-2)},{type:"api-key",pattern:/(?:key|token|api_key|apikey|secret|password|passwd|auth)=([A-Za-z0-9_\-]{16,})/gi,mask:()=>"***REDACTED***"}],y=class extends d{config={name:"qe/security/url-validate",description:"Validate URL security: checks for XSS/injection patterns, unsafe protocols, and scans URL query parameters for PII exposure (emails, SSNs, credit cards, API keys).",domain:"security-compliance",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{url:{type:"string",description:"URL to validate for security threats and PII exposure"},enablePII:{type:"boolean",description:"Enable PII exposure scanning in URL and query parameters",default:!0}},required:["url"]}}async execute(s,r){try{let e=this.validateURLSecurity(s.url),t=s.enablePII!==!1?this.scanForPII(s.url):{scanned:!1,found:!1,types:[],details:[]},c=e.issues.length+(t.found?t.types.length:0)===0?`URL passed all checks (security: clean, PII: ${t.scanned?"none found":"not scanned"})`:`URL has ${e.issues.length} security issue(s)${t.found?` and ${t.types.length} PII type(s) exposed in URL`:""}`;return{success:!0,data:{url:s.url,urlSecurity:e,piiExposure:t,summary:c}}}catch(e){return{success:!1,error:u(e)}}}validateURLSecurity(s){let r=[],e="none";try{let t=new URL(s);["http:","https:"].includes(t.protocol)||(r.push({type:"unsafe-protocol",description:`Protocol ${t.protocol} is not allowed`,severity:"high"}),e="high");let o=[/<script/i,/javascript:/i,/on\w+=/i,/data:text\/html/i];for(let i of o)if(i.test(s)){r.push({type:"xss",description:"Potential XSS pattern detected in URL",severity:"critical"}),e="critical";break}let c=[/'.*or.*'/i,/union.*select/i,/drop.*table/i,/;\s*--/i];for(let i of c)if(i.test(s)){r.push({type:"sql-injection",description:"Potential SQL injection pattern detected in URL",severity:"critical"}),e="critical";break}/\.\.[/\\]/.test(s)&&(r.push({type:"path-traversal",description:"Potential path traversal pattern (../) detected",severity:"high"}),e!=="critical"&&(e="high"));let a=["redirect","url","next","return","returnUrl","goto"];for(let i of a){let l=t.searchParams.get(i);l&&/^https?:\/\//.test(l)&&(r.push({type:"open-redirect",description:`Query parameter "${i}" contains an external URL \u2014 potential open redirect`,severity:"medium"}),e==="none"&&(e="medium"))}}catch{r.push({type:"invalid-url",description:"URL could not be parsed",severity:"critical"}),e="critical"}return{valid:r.length===0,riskLevel:e,issues:r}}scanForPII(s){let r=[],e=new Set,t;try{t=decodeURIComponent(s)}catch{t=s}let o="",c="";try{let a=new URL(t);o=a.search,c=a.pathname}catch{o=t}for(let{type:a,pattern:i,mask:l}of m){i.lastIndex=0;let p;for(;(p=i.exec(t))!==null;){e.add(a);let h=o.includes(p[0])?"query-parameter":c.includes(p[0])?"path":"url";r.push({type:a,location:h,masked:l(p[0])})}}return{scanned:!0,found:e.size>0,types:Array.from(e),details:r}}};export{y as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.1");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.10.3");process.exit(0)}
2
2
  var i=class{s0;s1;s2;s3;constructor(s){this.s0=this.splitmix32(s),this.s1=this.splitmix32(this.s0),this.s2=this.splitmix32(this.s1),this.s3=this.splitmix32(this.s2)}splitmix32(s){return s=s+2654435769|0,s=Math.imul(s^s>>>16,2246822507),s=Math.imul(s^s>>>13,3266489909),(s^s>>>16)>>>0}next(){let s=this.s3,t=this.s0;return this.s3=this.s2,this.s2=this.s1,this.s1=t,t^=t<<11,t^=t>>>8,this.s0=t^s^s>>>19,this.s0>>>0}nextFloat(){return this.next()/4294967296}nextGaussian(){let s=this.nextFloat()||1e-10,t=this.nextFloat();return Math.sqrt(-2*Math.log(s))*Math.cos(2*Math.PI*t)}};export{i as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.1");process.exit(0)}
2
- import{c as h,e as v,g as T}from"./chunk-4AWJ5PE4.js";var y={};v(y,{DotProductAttention:()=>z,FlashAttention:()=>k,HyperbolicAttention:()=>C,LinearAttention:()=>j,MoEAttention:()=>W,MultiHeadAttention:()=>F,RuvectorLayer:()=>_,SonaEngine:()=>K,TensorCompress:()=>E,default:()=>O,differentiableSearch:()=>L,getCompressionLevel:()=>B,hierarchicalForward:()=>V,init:()=>D,pipeline:()=>q});import{createRequire as A}from"module";var I,g,O,_,E,L,V,B,D,k,z,F,C,j,W,K,q,R=h(()=>{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:C,LinearAttention:j,MoEAttention:W,SonaEngine:K,pipeline:q}=g||{}});var Z={};v(Z,{createRvfStore:()=>Q,isRvfNativeAvailable:()=>Y,openRvfStore:()=>U,openRvfStoreReadonly:()=>X});import{readFileSync as J,writeFileSync as H,copyFileSync as $,existsSync as G}from"fs";function c(){if(S)return m;S=!0;try{let i=(R(),T(y));!i.RvfDatabase&&i.default&&i.default.RvfDatabase&&(i=i.default),m=i}catch{m=null}return m}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(J(e,"utf-8"));s=r.nextLabel;for(let[a,p]of r.entries)t.set(a,p),n.set(p,a)}catch{}return{strToNum:t,numToStr:n,nextLabel:s}}function b(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=c();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=c();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=c();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 c()!==null}var m,S,d,P=h(()=>{m=null,S=!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:f,metadata:x}=e[o],l=this.strToNum.get(u);l===void 0&&(l=this.nextLabel++,this.strToNum.set(u,l),this.numToStr.set(l,u)),s.push(l),r.push(x);let M=f instanceof Float32Array?f:new Float32Array(f);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);b(e,t,this.nextLabel);let r=c().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,deadSpaceRatio:typeof e.deadSpaceRatio=="number"?e.deadSpaceRatio:0}}dimension(){return this._dimension}size(){return this.ensureOpen(),this.db.status().totalVectors}compact(){this.ensureOpen();try{let e=this.db.compact();return e&&typeof e=="object"?{segmentsCompacted:typeof e.segmentsCompacted=="number"?e.segmentsCompacted:0,bytesReclaimed:typeof e.bytesReclaimed=="number"?e.bytesReclaimed:0,epoch:typeof e.epoch=="number"?e.epoch:0}:{segmentsCompacted:0,bytesReclaimed:0,epoch:0}}catch{return null}}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=c();if(typeof this.db.derive=="function")try{let n=this.db.derive(e),s=new Map(this.strToNum),r=new Map(this.numToStr);return b(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(){b(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.10.3");process.exit(0)}
2
+ import{c as h,e as v,g as T}from"./chunk-CAMEFWRK.js";var y={};v(y,{DotProductAttention:()=>z,FlashAttention:()=>k,HyperbolicAttention:()=>C,LinearAttention:()=>j,MoEAttention:()=>W,MultiHeadAttention:()=>F,RuvectorLayer:()=>_,SonaEngine:()=>K,TensorCompress:()=>E,default:()=>O,differentiableSearch:()=>L,getCompressionLevel:()=>B,hierarchicalForward:()=>V,init:()=>D,pipeline:()=>q});import{createRequire as A}from"module";var I,g,O,_,E,L,V,B,D,k,z,F,C,j,W,K,q,R=h(()=>{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:C,LinearAttention:j,MoEAttention:W,SonaEngine:K,pipeline:q}=g||{}});var Z={};v(Z,{createRvfStore:()=>Q,isRvfNativeAvailable:()=>Y,openRvfStore:()=>U,openRvfStoreReadonly:()=>X});import{readFileSync as J,writeFileSync as H,copyFileSync as $,existsSync as G}from"fs";function c(){if(S)return m;S=!0;try{let i=(R(),T(y));!i.RvfDatabase&&i.default&&i.default.RvfDatabase&&(i=i.default),m=i}catch{m=null}return m}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(J(e,"utf-8"));s=r.nextLabel;for(let[a,p]of r.entries)t.set(a,p),n.set(p,a)}catch{}return{strToNum:t,numToStr:n,nextLabel:s}}function b(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=c();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=c();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=c();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 c()!==null}var m,S,d,P=h(()=>{m=null,S=!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:f,metadata:x}=e[o],l=this.strToNum.get(u);l===void 0&&(l=this.nextLabel++,this.strToNum.set(u,l),this.numToStr.set(l,u)),s.push(l),r.push(x);let M=f instanceof Float32Array?f:new Float32Array(f);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);b(e,t,this.nextLabel);let r=c().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,deadSpaceRatio:typeof e.deadSpaceRatio=="number"?e.deadSpaceRatio:0}}dimension(){return this._dimension}size(){return this.ensureOpen(),this.db.status().totalVectors}compact(){this.ensureOpen();try{let e=this.db.compact();return e&&typeof e=="object"?{segmentsCompacted:typeof e.segmentsCompacted=="number"?e.segmentsCompacted:0,bytesReclaimed:typeof e.bytesReclaimed=="number"?e.bytesReclaimed:0,epoch:typeof e.epoch=="number"?e.epoch:0}:{segmentsCompacted:0,bytesReclaimed:0,epoch:0}}catch{return null}}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=c();if(typeof this.db.derive=="function")try{let n=this.db.derive(e),s=new Map(this.strToNum),r=new Map(this.numToStr);return b(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(){b(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,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.10.1");process.exit(0)}
2
- import{b as A,d as M}from"./chunk-QNW335PD.js";import{a as S,b as D}from"./chunk-KRXKU54J.js";import{S as Q,l as E}from"./chunk-ELZ67OHQ.js";import{g as C}from"./chunk-4AWJ5PE4.js";M();Q();var v=(1+Math.sqrt(5))/2,R=1/v;function k(t,e=0){if(t<0||!Number.isFinite(t))throw new Error(`Invalid dither sequence length: ${t}`);if(!Number.isFinite(e))throw new Error(`Invalid dither seed: ${e}`);let n=new Float32Array(t),r=(e*R%1+1)%1;for(let i=0;i<t;i++)n[i]=((r+(i+1)*v)%1+1)%1;return n}function I(t,e,n=0){if(!(t instanceof Float32Array))throw new Error("Input vector must be a Float32Array");if(t.length===0)return{quantized:new Int32Array(0),dequantized:new Float32Array(0),bitDepth:e,seed:n,stepSize:0,minValue:0,maxValue:0};if(e<1||e>32||!Number.isInteger(e))throw new Error(`Invalid bit depth: ${e}. Must be an integer in [1, 32].`);let r=t[0],i=t[0];for(let d=1;d<t.length;d++)t[d]<r&&(r=t[d]),t[d]>i&&(i=t[d]);let s=(1<<e)-1,a=i-r,o=a===0?1:a/s,m=k(t.length,n),l=new Int32Array(t.length),u=new Float32Array(t.length);for(let d=0;d<t.length;d++){if(a===0)l[d]=Math.round(s/2);else{let L=(t[d]-r)/o+(m[d]-.5);l[d]=Math.max(0,Math.min(s,Math.round(L)))}u[d]=l[d]*o+r}return{quantized:l,dequantized:u,bitDepth:e,seed:n,stepSize:o,minValue:r,maxValue:i}}var h=null,b=null,p=null,g=null,f=null,w=null,x=!1;try{let t=(D(),C(S));h=t.RuvectorLayer,b=t.TensorCompress,p=t.differentiableSearch,g=t.hierarchicalForward,f=t.getCompressionLevel,w=t.init,x=!0}catch{}function H(){return x}function c(){if(!x)throw new Error("@ruvector/gnn native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var F=!1;function V(){if(!F){c();let t=w();return F=!0,t}return"@ruvector/gnn already initialized"}var y=class{indexes;config;nextId;gnnLayers;compressor;constructor(e={}){this.config={M:e.M||16,efConstruction:e.efConstruction||200,efSearch:e.efSearch||50,dimension:e.dimension||384,metric:e.metric||"cosine",quantization:e.quantization||"none"},this.indexes=new Map,this.nextId=new Map,this.gnnLayers=new Map,c(),this.compressor=new b,V()}initializeIndex(e){this.indexes.has(e)||(this.indexes.set(e,new Map),this.nextId.set(e,0))}addEmbedding(e,n){let r=e.namespace;this.indexes.has(r)||this.initializeIndex(r);let i=this.indexes.get(r),s=n??this.nextId.get(r);return n===void 0&&this.nextId.set(r,s+1),i.set(s,e),s}addEmbeddingsBatch(e){let n=[];for(let r of e){let i=this.addEmbedding(r.embedding,r.id);n.push(i)}return n}search(e,n={}){let r=n.namespace||e.namespace;if(!this.indexes.has(r))return[];let i=this.indexes.get(r),s=n.limit||10,a=[];for(let[u,d]of i.entries())a.push({id:u,vector:Array.from(d.vector)});if(a.length===0)return[];let o=new Float32Array(e.vector),m=a.map(u=>new Float32Array(u.vector)),l=p(o,m,Math.min(s,a.length),1);return l.indices.map((u,d)=>({id:a[u]?.id??u,distance:1-l.weights[d]}))}differentiableSearchWithWeights(e,n,r,i=1){let s=new Float32Array(e.vector),a=n.map(m=>new Float32Array(m.embedding.vector)),o=p(s,a,Math.min(r,n.length),i);return{indices:o.indices.map(m=>n[m]?.id??m),weights:o.weights}}hierarchicalForward(e,n,r){let i=r.map(l=>`${l.inputDim}-${l.hiddenDim}`).join(",");if(!this.gnnLayers.has(i)){let l=[];for(let u of r){let d=new h(u.inputDim,u.hiddenDim,u.heads,u.dropout);l.push(d)}this.gnnLayers.set(i,l[0])}let a=this.gnnLayers.get(i).toJson(),o=new Float32Array(e),m=n.map(l=>l.map(u=>new Float32Array(u)));return Array.from(g(o,m,[a]))}compressEmbedding(e,n){let r=f(n),s={none:"none",half:"half",pq8:"pq8",pq4:"pq4",binary:"binary"}[r]??"none",a=new Float32Array(e.vector),o=this.compressor.compress(a,n);return{dimension:Array.from(e.vector).length,level:s,data:o,accessFreq:n}}decompressEmbedding(e){let n=this.compressor.decompress(e.data),r={none:"none",half:"fp16",pq8:"int8",pq4:"int8",binary:"binary"};return{vector:n,dimension:e.dimension,namespace:"code",text:"",timestamp:Date.now(),quantization:r[e.level]??"none"}}getCompressionLevelForFrequency(e){return c(),f(e)}getIndexStats(e){return this.indexes.has(e)?{size:this.indexes.get(e).size,maxElements:1e4,dimension:this.config.dimension,metric:this.config.metric}:null}clearIndex(e){this.indexes.delete(e),this.nextId.delete(e)}clearAll(){this.indexes.clear(),this.nextId.clear()}resizeIndex(e){}setEfSearch(e){this.config.efSearch=e}getConfig(){return{...this.config}}isInitialized(e){return this.indexes.has(e)}getInitializedNamespaces(){return Array.from(this.indexes.keys())}getSize(e){return this.indexes.get(e)?.size??0}async saveIndex(e,n){let r=this.indexes.get(e);if(!r)throw new Error(`Namespace ${e} not initialized`);let i=Array.from(r.entries()).map(([a,o])=>({id:a,vector:Array.from(o.vector),metadata:o.metadata}));await(await import("fs/promises")).writeFile(n,JSON.stringify(i,null,2))}async loadIndex(e,n){let i=await(await import("fs/promises")).readFile(n,"utf-8"),s=A(i);this.initializeIndex(e);for(let a of s){let o={vector:a.vector,dimension:a.vector.length,namespace:e,text:"",timestamp:Date.now(),quantization:"none",metadata:a.metadata};this.addEmbedding(o,a.id)}}},q=class{static instances=new Map;static getInstance(e,n){return this.instances.has(e)||this.instances.set(e,new y(n)),this.instances.get(e)}static closeInstance(e){let n=this.instances.get(e);n&&(n.clearAll(),this.instances.delete(e))}static closeAll(){for(let e of this.instances.values())e.clearAll();this.instances.clear()}},z=class{static layers=new Map;static getLayer(e){let n=`${e.inputDim}-${e.hiddenDim}-${e.heads}-${e.dropout}`;if(!this.layers.has(n)){c();let r=new h(e.inputDim,e.hiddenDim,e.heads,e.dropout);this.layers.set(n,r)}return this.layers.get(n)}static layerFromJson(e){return c(),h.fromJson(e)}static clearCache(){this.layers.clear()}},N=class{static _compressor=null;static get compressor(){return this._compressor||(c(),this._compressor=new b),this._compressor}static compressWithLevel(e,n){let r={levelType:n,scale:1,subvectors:n==="pq8"?8:n==="pq4"?16:void 0,centroids:n==="pq8"?256:void 0,outlierThreshold:n==="pq4"?3:void 0,threshold:n==="binary"?0:void 0},i=e instanceof Float32Array?e:new Float32Array(e);return this.compressor.compressWithLevel(i,r)}static decompress(e){return this.compressor.decompress(e)}static getLevel(e){return c(),f(e)}static compressWithDither(e,n,r){let i=e instanceof Float32Array?e:new Float32Array(e),s;if(E()){let o={none:32,half:16,pq8:8,pq4:4,binary:1},m=r?.bitDepth??o[n]??8,l=r?.seed??0;s=I(i,m,l)}return{compressed:this.compressWithLevel(s?s.dequantized:e,n),ditherResult:s}}};function G(){return c(),h}function J(){return c(),b}function O(){return c(),p}function j(){return c(),g}function B(){return c(),f}function K(){return c(),w}function U(t){return t instanceof Float32Array?t:"vector"in t?t.vector instanceof Float32Array?t.vector:new Float32Array(t.vector):new Float32Array(t)}function X(t){return"vector"in t?Array.from(t.vector):Array.from(t)}function Y(t,e="code"){return{vector:t,dimension:t.length,namespace:e,text:"",timestamp:Date.now(),quantization:"none"}}function Z(t,e,n,r=1){let i=[],s=e.map(a=>a instanceof Float32Array?a:new Float32Array(a));for(let a of t){let o=a instanceof Float32Array?a:new Float32Array(a),m=p(o,s,n,r);i.push({indices:m.indices,weights:m.weights})}return i}export{H as a,V as b,y as c,q as d,z as e,N as f,G as g,J as h,O as i,j,B as k,K as l,U as m,X as n,Y as o,Z as p};
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.10.3");process.exit(0)}
2
+ import{b as A,d as M}from"./chunk-KTRB3L53.js";import{a as S,b as D}from"./chunk-HMFEPKAR.js";import{S as Q,l as E}from"./chunk-YIYV2JB6.js";import{g as C}from"./chunk-CAMEFWRK.js";M();Q();var v=(1+Math.sqrt(5))/2,R=1/v;function k(t,e=0){if(t<0||!Number.isFinite(t))throw new Error(`Invalid dither sequence length: ${t}`);if(!Number.isFinite(e))throw new Error(`Invalid dither seed: ${e}`);let n=new Float32Array(t),r=(e*R%1+1)%1;for(let i=0;i<t;i++)n[i]=((r+(i+1)*v)%1+1)%1;return n}function I(t,e,n=0){if(!(t instanceof Float32Array))throw new Error("Input vector must be a Float32Array");if(t.length===0)return{quantized:new Int32Array(0),dequantized:new Float32Array(0),bitDepth:e,seed:n,stepSize:0,minValue:0,maxValue:0};if(e<1||e>32||!Number.isInteger(e))throw new Error(`Invalid bit depth: ${e}. Must be an integer in [1, 32].`);let r=t[0],i=t[0];for(let d=1;d<t.length;d++)t[d]<r&&(r=t[d]),t[d]>i&&(i=t[d]);let s=(1<<e)-1,a=i-r,o=a===0?1:a/s,m=k(t.length,n),l=new Int32Array(t.length),u=new Float32Array(t.length);for(let d=0;d<t.length;d++){if(a===0)l[d]=Math.round(s/2);else{let L=(t[d]-r)/o+(m[d]-.5);l[d]=Math.max(0,Math.min(s,Math.round(L)))}u[d]=l[d]*o+r}return{quantized:l,dequantized:u,bitDepth:e,seed:n,stepSize:o,minValue:r,maxValue:i}}var h=null,b=null,p=null,g=null,f=null,w=null,x=!1;try{let t=(D(),C(S));h=t.RuvectorLayer,b=t.TensorCompress,p=t.differentiableSearch,g=t.hierarchicalForward,f=t.getCompressionLevel,w=t.init,x=!0}catch{}function H(){return x}function c(){if(!x)throw new Error("@ruvector/gnn native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var F=!1;function V(){if(!F){c();let t=w();return F=!0,t}return"@ruvector/gnn already initialized"}var y=class{indexes;config;nextId;gnnLayers;compressor;constructor(e={}){this.config={M:e.M||16,efConstruction:e.efConstruction||200,efSearch:e.efSearch||50,dimension:e.dimension||384,metric:e.metric||"cosine",quantization:e.quantization||"none"},this.indexes=new Map,this.nextId=new Map,this.gnnLayers=new Map,c(),this.compressor=new b,V()}initializeIndex(e){this.indexes.has(e)||(this.indexes.set(e,new Map),this.nextId.set(e,0))}addEmbedding(e,n){let r=e.namespace;this.indexes.has(r)||this.initializeIndex(r);let i=this.indexes.get(r),s=n??this.nextId.get(r);return n===void 0&&this.nextId.set(r,s+1),i.set(s,e),s}addEmbeddingsBatch(e){let n=[];for(let r of e){let i=this.addEmbedding(r.embedding,r.id);n.push(i)}return n}search(e,n={}){let r=n.namespace||e.namespace;if(!this.indexes.has(r))return[];let i=this.indexes.get(r),s=n.limit||10,a=[];for(let[u,d]of i.entries())a.push({id:u,vector:Array.from(d.vector)});if(a.length===0)return[];let o=new Float32Array(e.vector),m=a.map(u=>new Float32Array(u.vector)),l=p(o,m,Math.min(s,a.length),1);return l.indices.map((u,d)=>({id:a[u]?.id??u,distance:1-l.weights[d]}))}differentiableSearchWithWeights(e,n,r,i=1){let s=new Float32Array(e.vector),a=n.map(m=>new Float32Array(m.embedding.vector)),o=p(s,a,Math.min(r,n.length),i);return{indices:o.indices.map(m=>n[m]?.id??m),weights:o.weights}}hierarchicalForward(e,n,r){let i=r.map(l=>`${l.inputDim}-${l.hiddenDim}`).join(",");if(!this.gnnLayers.has(i)){let l=[];for(let u of r){let d=new h(u.inputDim,u.hiddenDim,u.heads,u.dropout);l.push(d)}this.gnnLayers.set(i,l[0])}let a=this.gnnLayers.get(i).toJson(),o=new Float32Array(e),m=n.map(l=>l.map(u=>new Float32Array(u)));return Array.from(g(o,m,[a]))}compressEmbedding(e,n){let r=f(n),s={none:"none",half:"half",pq8:"pq8",pq4:"pq4",binary:"binary"}[r]??"none",a=new Float32Array(e.vector),o=this.compressor.compress(a,n);return{dimension:Array.from(e.vector).length,level:s,data:o,accessFreq:n}}decompressEmbedding(e){let n=this.compressor.decompress(e.data),r={none:"none",half:"fp16",pq8:"int8",pq4:"int8",binary:"binary"};return{vector:n,dimension:e.dimension,namespace:"code",text:"",timestamp:Date.now(),quantization:r[e.level]??"none"}}getCompressionLevelForFrequency(e){return c(),f(e)}getIndexStats(e){return this.indexes.has(e)?{size:this.indexes.get(e).size,maxElements:1e4,dimension:this.config.dimension,metric:this.config.metric}:null}clearIndex(e){this.indexes.delete(e),this.nextId.delete(e)}clearAll(){this.indexes.clear(),this.nextId.clear()}resizeIndex(e){}setEfSearch(e){this.config.efSearch=e}getConfig(){return{...this.config}}isInitialized(e){return this.indexes.has(e)}getInitializedNamespaces(){return Array.from(this.indexes.keys())}getSize(e){return this.indexes.get(e)?.size??0}async saveIndex(e,n){let r=this.indexes.get(e);if(!r)throw new Error(`Namespace ${e} not initialized`);let i=Array.from(r.entries()).map(([a,o])=>({id:a,vector:Array.from(o.vector),metadata:o.metadata}));await(await import("fs/promises")).writeFile(n,JSON.stringify(i,null,2))}async loadIndex(e,n){let i=await(await import("fs/promises")).readFile(n,"utf-8"),s=A(i);this.initializeIndex(e);for(let a of s){let o={vector:a.vector,dimension:a.vector.length,namespace:e,text:"",timestamp:Date.now(),quantization:"none",metadata:a.metadata};this.addEmbedding(o,a.id)}}},q=class{static instances=new Map;static getInstance(e,n){return this.instances.has(e)||this.instances.set(e,new y(n)),this.instances.get(e)}static closeInstance(e){let n=this.instances.get(e);n&&(n.clearAll(),this.instances.delete(e))}static closeAll(){for(let e of this.instances.values())e.clearAll();this.instances.clear()}},z=class{static layers=new Map;static getLayer(e){let n=`${e.inputDim}-${e.hiddenDim}-${e.heads}-${e.dropout}`;if(!this.layers.has(n)){c();let r=new h(e.inputDim,e.hiddenDim,e.heads,e.dropout);this.layers.set(n,r)}return this.layers.get(n)}static layerFromJson(e){return c(),h.fromJson(e)}static clearCache(){this.layers.clear()}},N=class{static _compressor=null;static get compressor(){return this._compressor||(c(),this._compressor=new b),this._compressor}static compressWithLevel(e,n){let r={levelType:n,scale:1,subvectors:n==="pq8"?8:n==="pq4"?16:void 0,centroids:n==="pq8"?256:void 0,outlierThreshold:n==="pq4"?3:void 0,threshold:n==="binary"?0:void 0},i=e instanceof Float32Array?e:new Float32Array(e);return this.compressor.compressWithLevel(i,r)}static decompress(e){return this.compressor.decompress(e)}static getLevel(e){return c(),f(e)}static compressWithDither(e,n,r){let i=e instanceof Float32Array?e:new Float32Array(e),s;if(E()){let o={none:32,half:16,pq8:8,pq4:4,binary:1},m=r?.bitDepth??o[n]??8,l=r?.seed??0;s=I(i,m,l)}return{compressed:this.compressWithLevel(s?s.dequantized:e,n),ditherResult:s}}};function G(){return c(),h}function J(){return c(),b}function O(){return c(),p}function j(){return c(),g}function B(){return c(),f}function K(){return c(),w}function U(t){return t instanceof Float32Array?t:"vector"in t?t.vector instanceof Float32Array?t.vector:new Float32Array(t.vector):new Float32Array(t)}function X(t){return"vector"in t?Array.from(t.vector):Array.from(t)}function Y(t,e="code"){return{vector:t,dimension:t.length,namespace:e,text:"",timestamp:Date.now(),quantization:"none"}}function Z(t,e,n,r=1){let i=[],s=e.map(a=>a instanceof Float32Array?a:new Float32Array(a));for(let a of t){let o=a instanceof Float32Array?a:new Float32Array(a),m=p(o,s,n,r);i.push({indices:m.indices,weights:m.weights})}return i}export{H as a,V as b,y as c,q as d,z as e,N as f,G as g,J as h,O as i,j,B as k,K as l,U as m,X as n,Y as o,Z as p};
@@ -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.10.1");process.exit(0)}
2
- import{d as k,f as we}from"./chunk-GXJ4BCGC.js";import{b as C,d as Z}from"./chunk-QNW335PD.js";import{a as ye}from"./chunk-VPCE5CIT.js";import{c as Q}from"./chunk-BGBSYF3K.js";import{a as V,c as ve}from"./chunk-2TDWCXZ6.js";import{a as J,b as Xe}from"./chunk-XRK7FBTY.js";import{a as ee,d as v,e as te,f as ne}from"./chunk-GRG3OP34.js";import{a as b,e as De}from"./chunk-2ETDES5W.js";import{c as R,e as be}from"./chunk-4AWJ5PE4.js";function A(i){if(!q.has(i))throw new Error(`Invalid table name: "${i}" is not in the allowlist`);return i}function ze(i){let e=i.split(".");if(e.length>2)throw new Error(`Invalid SQL identifier: "${i}" has too many parts (max: schema.table)`);for(let t of e)if(!re.test(t))throw new Error(`Invalid SQL identifier: "${i}" \u2014 part "${t}" does not match pattern ${re}`);return i}var q,re,z=R(()=>{"use strict";q=new Set(["schema_version","kv_store","vectors","rl_q_values","goap_goals","goap_actions","goap_plans","goap_plan_signatures","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","sona_patterns","sona_fisher_matrices","test_outcomes","routing_outcomes","coverage_sessions","patterns","hypergraph_nodes","hypergraph_edges","hypergraph_vertices","hypergraph_hyperedges","hypergraph_edge_vertices","hypergraph_vertex_properties","hypergraph_edge_properties","captured_experiences","experience_applications","witness_chain","witness_chain_receipts","witness_chain_archive","trajectories","trajectory_steps","pattern_evolution_events","pattern_relationships","pattern_versions","learning_daily_snapshots","metrics_outcomes","experience_consolidation_log","qe_pattern_reuse","qe_agent_co_execution"]);re=/^[a-z_][a-z0-9_]{0,62}$/});var D,se,oe,ie,ae,ce,Te,Ee,de,ue,le,pe,ge=R(()=>{"use strict";we();D=9,se=`
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.10.3");process.exit(0)}
2
+ import{d as k,f as we}from"./chunk-R5ONQAQL.js";import{b as C,d as Z}from"./chunk-KTRB3L53.js";import{a as ye}from"./chunk-3VF3HCG4.js";import{c as Q}from"./chunk-2L73WXA4.js";import{a as V,c as ve}from"./chunk-3LRK7PYN.js";import{a as J,b as Xe}from"./chunk-L74CHKFR.js";import{a as ee,d as v,e as te,f as ne}from"./chunk-JTZ3Q2QS.js";import{a as b,e as De}from"./chunk-QWG76RHA.js";import{c as R,e as be}from"./chunk-CAMEFWRK.js";function A(i){if(!q.has(i))throw new Error(`Invalid table name: "${i}" is not in the allowlist`);return i}function ze(i){let e=i.split(".");if(e.length>2)throw new Error(`Invalid SQL identifier: "${i}" has too many parts (max: schema.table)`);for(let t of e)if(!re.test(t))throw new Error(`Invalid SQL identifier: "${i}" \u2014 part "${t}" does not match pattern ${re}`);return i}var q,re,z=R(()=>{"use strict";q=new Set(["schema_version","kv_store","vectors","rl_q_values","goap_goals","goap_actions","goap_plans","goap_plan_signatures","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","sona_patterns","sona_fisher_matrices","test_outcomes","routing_outcomes","coverage_sessions","patterns","hypergraph_nodes","hypergraph_edges","hypergraph_vertices","hypergraph_hyperedges","hypergraph_edge_vertices","hypergraph_vertex_properties","hypergraph_edge_properties","captured_experiences","experience_applications","witness_chain","witness_chain_receipts","witness_chain_archive","trajectories","trajectory_steps","pattern_evolution_events","pattern_relationships","pattern_versions","learning_daily_snapshots","metrics_outcomes","experience_consolidation_log","qe_pattern_reuse","qe_agent_co_execution"]);re=/^[a-z_][a-z0-9_]{0,62}$/});var D,se,oe,ie,ae,ce,Te,Ee,de,ue,le,pe,ge=R(()=>{"use strict";we();D=9,se=`
3
3
  CREATE TABLE IF NOT EXISTS schema_version (
4
4
  id INTEGER PRIMARY KEY CHECK (id = 1),
5
5
  version INTEGER NOT NULL,
@@ -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.10.1");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.10.3");process.exit(0)}
2
2
  function M(u){let e=u|0;return()=>{e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}var A=2,y=10,x=200,p=1e-8,b=class{epsilon;seed;constructor(e){if(this.epsilon=e?.epsilon??.3,this.seed=e?.seed,this.epsilon<=0||this.epsilon>=1)throw new Error("SparsifierConfig.epsilon must be in (0, 1)")}sparsify(e){if(e.nodeCount<=0||e.edges.length===0)return{nodeCount:e.nodeCount,edges:[]};let n=this.seed!==void 0?M(this.seed):Math.random,t=this.approximateEffectiveResistances(e),i=e.nodeCount,r=e.edges.length,o=Math.max(1,Math.log(i)),m=this.epsilon*this.epsilon,l=Math.min(r,Math.max(i-1,A*(i-1)*(1-this.epsilon))),s=new Float64Array(r),c=0;for(let a=0;a<r;a++){let d=e.edges[a][2];s[a]=d*t[a],c+=s[a]}if(c<=0)return{nodeCount:e.nodeCount,edges:[]};let f=[];for(let a=0;a<r;a++){let[d,C,E]=e.edges[a],g=Math.min(1,s[a]/c*l);if(n()<g){let w=E/g;f.push([d,C,w])}}return{nodeCount:e.nodeCount,edges:f}}validateSpectral(e,n){let t=Math.min(y,Math.max(1,e.nodeCount-1)),i=this.computeLaplacian(e),r=this.computeLaplacian(n),o=this.computeTopEigenvalues(i,t),m=this.computeTopEigenvalues(r,t),l=[],s=!0,c=this.epsilon;for(let f=0;f<o.length;f++){if(o[f]<1e-10)continue;let a=m[f]/o[f];l.push(a),(a<1-c||a>1+c)&&(s=!1)}return{isValid:s,eigenvalueRatios:l,originalEdgeCount:e.edges.length,sparsifiedEdgeCount:n.edges.length,compressionRatio:e.edges.length>0?n.edges.length/e.edges.length:0}}computeLaplacian(e){let n=e.nodeCount,t=Array.from({length:n},()=>new Array(n).fill(0));for(let[i,r,o]of e.edges)i<0||i>=n||r<0||r>=n||(t[i][i]+=o,t[r][r]+=o,t[i][r]-=o,t[r][i]-=o);return t}computeTopEigenvalues(e,n){let t=e.length;if(t===0)return[];let i=[],r=[],o=e.map(m=>[...m]);for(let m=0;m<Math.min(n,t);m++){let l=this.powerIteration(o,t,r);if(l===null)break;i.push(l.eigenvalue),r.push(l.eigenvector),V(o,l.eigenvalue,l.eigenvector)}return i}approximateEffectiveResistances(e){let n=e.nodeCount,t=new Float64Array(n);for(let[r,o,m]of e.edges)r>=0&&r<n&&(t[r]+=m),o>=0&&o<n&&(t[o]+=m);let i=new Array(e.edges.length);for(let r=0;r<e.edges.length;r++){let[o,m]=e.edges[r],l=t[o]||1,s=t[m]||1;i[r]=1/l+1/s}return i}powerIteration(e,n,t){let i=0;for(let s=0;s<n;s++)for(let c=0;c<n;c++)i+=e[s][c]*e[s][c];if(i<p*p)return null;let r=t.length,o=new Array(n);for(let s=0;s<n;s++)o[s]=Math.sin((s+1)*(r+1)*1.618033988749895)+.1*(s-n/2);for(let s of t)h(o,s);if(R(o)<p)return null;let l=0;for(let s=0;s<x;s++){let c=L(e,o);for(let d of t)h(c,d);let f=S(c,o),a=v(c);if(a<p)return{eigenvalue:0,eigenvector:o};for(let d=0;d<n;d++)o[d]=c[d]/a;if(Math.abs(f-l)<p){l=f;break}l=f}return{eigenvalue:Math.abs(l),eigenvector:o}}};function L(u,e){let n=u.length,t=new Array(n).fill(0);for(let i=0;i<n;i++){let r=0;for(let o=0;o<n;o++)r+=u[i][o]*e[o];t[i]=r}return t}function v(u){let e=0;for(let n=0;n<u.length;n++)e+=u[n]*u[n];return Math.sqrt(e)}function R(u){let e=v(u);if(e>0)for(let n=0;n<u.length;n++)u[n]/=e;return e}function S(u,e){let n=0;for(let t=0;t<u.length;t++)n+=u[t]*e[t];return n}function h(u,e){let n=S(u,e);for(let t=0;t<u.length;t++)u[t]-=n*e[t]}function V(u,e,n){let t=n.length;for(let i=0;i<t;i++)for(let r=0;r<t;r++)u[i][r]-=e*n[i]*n[r]}export{b as a};
@@ -1,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.10.1");process.exit(0)}
2
- import{k as K,o as ot}from"./chunk-Q24OJX44.js";import{a as rt}from"./chunk-VPCE5CIT.js";import{c as U}from"./chunk-BGBSYF3K.js";import{a as j,c as et}from"./chunk-2TDWCXZ6.js";import{a as G,d as at}from"./chunk-XKOKMS5A.js";import{a as nt,b as it}from"./chunk-KRXKU54J.js";import{c as H,e as V,g as w}from"./chunk-4AWJ5PE4.js";var Z={};V(Z,{DotProductAttention:()=>yt,FlashAttention:()=>ft,HyperbolicAttention:()=>bt,LinearAttention:()=>vt,MoEAttention:()=>Et,MultiHeadAttention:()=>At,RuvectorLayer:()=>ut,SonaEngine:()=>P,TensorCompress:()=>mt,default:()=>ct,differentiableSearch:()=>ht,getCompressionLevel:()=>pt,hierarchicalForward:()=>dt,init:()=>gt,pipeline:()=>Ft});import{createRequire as st}from"module";var lt,$,ct,ut,mt,ht,dt,pt,gt,ft,yt,At,bt,vt,Et,P,Ft,k=H(()=>{lt=st(import.meta.url),$=lt("@ruvector/sona"),ct=$,{RuvectorLayer:ut,TensorCompress:mt,differentiableSearch:ht,hierarchicalForward:dt,getCompressionLevel:pt,init:gt,FlashAttention:ft,DotProductAttention:yt,MultiHeadAttention:At,HyperbolicAttention:bt,LinearAttention:vt,MoEAttention:Et,SonaEngine:P,pipeline:Ft}=$||{}});var N={};V(N,{DotProductAttention:()=>It,FlashAttention:()=>zt,HyperbolicAttention:()=>_t,LinearAttention:()=>Ht,MoEAttention:()=>Vt,MultiHeadAttention:()=>qt,RuvectorLayer:()=>Qt,SonaEngine:()=>jt,TensorCompress:()=>Nt,default:()=>xt,differentiableSearch:()=>Ot,getCompressionLevel:()=>Wt,hierarchicalForward:()=>Dt,init:()=>Bt,pipeline:()=>Ut});import{createRequire as kt}from"module";var Rt,X,xt,Qt,Nt,Ot,Dt,Wt,Bt,zt,It,qt,_t,Ht,Vt,jt,Ut,O=H(()=>{Rt=kt(import.meta.url),X=Rt("@ruvector/attention"),xt=X,{RuvectorLayer:Qt,TensorCompress:Nt,differentiableSearch:Ot,hierarchicalForward:Dt,getCompressionLevel:Wt,init:Bt,FlashAttention:zt,DotProductAttention:It,MultiHeadAttention:qt,HyperbolicAttention:_t,LinearAttention:Ht,MoEAttention:Vt,SonaEngine:jt,pipeline:Ut}=X||{}});k();at();import{randomUUID as Ct}from"crypto";rt();import{createRequire as wt}from"module";var f=U.create("sona-three-loop"),S=wt(import.meta.url),M=null,J=!1;function St(){if(J)return M;J=!0;try{let l=S("@ruvector/learning-wasm"),t=S("fs"),e=S("path"),r=e.join(e.dirname(S.resolve("@ruvector/learning-wasm")),"ruvector_learning_wasm_bg.wasm");l.initSync({module:t.readFileSync(r)}),M=l,f.info("WASM MicroLoRA loaded from @ruvector/learning-wasm (6.4x faster than TS)")}catch{M=null,f.debug("@ruvector/learning-wasm not available, using TypeScript MicroLoRA")}return M}var Mt={dimension:384,microLoraLr:.001,consolidationInterval:100,ewcLambda:1e3,taskBoundaryZScoreThreshold:2.5,fisherDecay:.9,fisherSampleSize:200,importanceThreshold:.01},R=class{adaptationVector;baseWeights;lr;adaptationCount=0;constructor(t,e=.001){this.adaptationVector=new Float32Array(t),this.baseWeights=new Float32Array(t),this.lr=e}adapt(t){let e=this.baseWeights.length,r=new Float32Array(e),a=Math.min(t.length,e);for(let n=0;n<e;n++){let o=n<a?t[n]:0;r[n]=this.baseWeights[n]+this.adaptationVector[n]+this.lr*o}for(let n=0;n<a;n++)this.adaptationVector[n]+=this.lr*t[n];return this.adaptationCount++,r}consolidate(){let t=this.adaptationCount,e=this.baseWeights.length;for(let r=0;r<e;r++)this.baseWeights[r]+=this.adaptationVector[r],this.adaptationVector[r]=0;return this.adaptationCount=0,t}getAdaptationCount(){return this.adaptationCount}getEffectiveWeights(){let t=this.baseWeights.length,e=new Float32Array(t);for(let r=0;r<t;r++)e[r]=this.baseWeights[r]+this.adaptationVector[r];return e}getAdaptationMagnitude(){let t=0;for(let e=0;e<this.adaptationVector.length;e++)t+=this.adaptationVector[e]*this.adaptationVector[e];return Math.sqrt(t)}resetAdaptation(){this.adaptationVector.fill(0),this.adaptationCount=0}},x=class{fisherMatrix;optimalParams;lambda;fisherDecay;zScoreThreshold;importanceThreshold;gradientHistory=[];gradientMean=0;gradientVariance=0;taskBoundaryCount=0;consolidationCount=0;constructor(t,e=1e3,r=.9,a=2.5,n=.01){this.fisherMatrix=new Float32Array(t),this.optimalParams=new Float32Array(t),this.lambda=e,this.fisherDecay=r,this.zScoreThreshold=a,this.importanceThreshold=n}detectTaskBoundary(t){let e=0;for(let i=0;i<t.length;i++)e+=t[i]*t[i];if(e=Math.sqrt(e),this.gradientHistory.length<5)return this.gradientHistory.push(e),this.updateGradientStats(),!1;let r=Math.sqrt(this.gradientVariance),a=0,n=Math.abs(e-this.gradientMean);return r>1e-10?a=n/r:n>1e-10&&this.gradientMean>1e-10&&(a=n/(this.gradientMean*.01+1e-10)),this.gradientHistory.push(e),this.gradientHistory.length>100&&this.gradientHistory.shift(),this.updateGradientStats(),a>this.zScoreThreshold?(this.taskBoundaryCount++,!0):!1}computeLoss(t){let e=0,r=Math.min(t.length,this.fisherMatrix.length,this.optimalParams.length);for(let a=0;a<r;a++){let n=t[a]-this.optimalParams[a];e+=this.fisherMatrix[a]*n*n}return this.lambda/2*e}updateFisher(t,e){if(t.length===0)return;let r=this.fisherMatrix.length,a=new Float32Array(r);for(let s of t){let u=Math.min(s.length,r);for(let c=0;c<u;c++)a[c]+=s[c]*s[c]}let n=t.length;for(let s=0;s<r;s++)a[s]/=n;let o=this.fisherDecay;for(let s=0;s<r;s++)this.fisherMatrix[s]=o*this.fisherMatrix[s]+(1-o)*a[s];let i=Math.min(e.length,r);for(let s=0;s<i;s++)this.optimalParams[s]=e[s];this.consolidationCount++}getMetrics(){let t=this.fisherMatrix.length,e=0,r=0,a=0;for(let n=0;n<t;n++)e+=this.fisherMatrix[n],this.fisherMatrix[n]>r&&(r=this.fisherMatrix[n]),this.fisherMatrix[n]>this.importanceThreshold&&a++;return{regularizationLoss:0,taskBoundariesDetected:this.taskBoundaryCount,fisherTrace:e,avgFisherImportance:t>0?e/t:0,maxFisherImportance:r,protectedParams:a,consolidationCycles:this.consolidationCount,lambda:this.lambda}}getTaskBoundaryCount(){return this.taskBoundaryCount}getFisherDiagonal(){return new Float32Array(this.fisherMatrix)}getOptimalParams(){return new Float32Array(this.optimalParams)}loadFisher(t,e){let r=this.fisherMatrix.length,a=Math.min(t.length,r),n=Math.min(e.length,r);for(let o=0;o<a;o++)this.fisherMatrix[o]=t[o];for(let o=0;o<n;o++)this.optimalParams[o]=e[o]}updateGradientStats(){let t=this.gradientHistory.length;if(t===0)return;let e=0;for(let a of this.gradientHistory)e+=a;e/=t;let r=0;for(let a of this.gradientHistory){let n=a-e;r+=n*n}r=t>1?r/(t-1):0,this.gradientMean=e,this.gradientVariance=r}},C=class{config;microLora;ewc;nativeEngine;wasmLora=null;requestCount=0;lastConsolidationRequest=0;peerStates=new Map;gradientBuffer=[];lastFeatures=null;constructor(t={},e){this.config={...Mt,...t},this.nativeEngine=e??null,this.microLora=new R(this.config.dimension,this.config.microLoraLr),this.ewc=new x(this.config.dimension,this.config.ewcLambda,this.config.fisherDecay,this.config.taskBoundaryZScoreThreshold,this.config.importanceThreshold);let r=St();if(r)try{this.wasmLora=new r.WasmMicroLoRA(this.config.dimension,1,this.config.microLoraLr),f.info("SONA Three-Loop using WASM MicroLoRA (0.07us/adapt)")}catch(a){f.debug("WASM MicroLoRA creation failed, falling back",{error:String(a)}),this.wasmLora=null}!this.wasmLora&&this.nativeEngine&&f.info("SONA Three-Loop using native @ruvector/sona engine for MicroLoRA delegation")}instantAdapt(t){let e=performance.now(),r;if(this.wasmLora)try{let o=new Float32Array(t),i=this.wasmLora.adapt(o);i&&i.length>0?(r=i,this.microLora.adapt(t)):r=this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else if(this.nativeEngine)try{let o=this.nativeEngine.applyMicroLora(t);r=new Float32Array(o),this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else r=this.microLora.adapt(t);let a=this.microLora.getAdaptationMagnitude();this.requestCount++,this.lastFeatures=[...t];let n=(performance.now()-e)*1e3;return{adaptedWeights:r,latencyUs:n,applied:!0,magnitude:a,requestIndex:this.requestCount}}recordOutcome(t,e){if(this.lastFeatures===null){f.warn("recordOutcome called without a preceding instantAdapt()");return}let r=this.lastFeatures.length,a=new Float32Array(r);for(let n=0;n<r;n++)a[n]=t*this.lastFeatures[n];this.gradientBuffer.push(a),this.gradientBuffer.length>this.config.fisherSampleSize&&this.gradientBuffer.shift(),this.lastFeatures=null}backgroundConsolidate(){let t=performance.now();if(this.nativeEngine)try{this.nativeEngine.forceLearn(),this.nativeEngine.tick()}catch(i){f.warn("Native SONA background learning failed, continuing with TypeScript",{error:String(i)})}let e=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),r=!1;if(this.gradientBuffer.length>0){let i=this.gradientBuffer[this.gradientBuffer.length-1];r=this.ewc.detectTaskBoundary(i)}if(r&&this.gradientBuffer.length>0&&(this.ewc.updateFisher(this.gradientBuffer,this.microLora.getEffectiveWeights()),f.info("Task boundary detected, Fisher updated",{boundaries:this.ewc.getTaskBoundaryCount(),requestCount:this.requestCount})),this.gradientBuffer.length>1){let i=!1,s=this.gradientBuffer[0];for(let u=1;u<this.gradientBuffer.length&&!i;u++)for(let c=0;c<s.length;c++)if(Math.abs(this.gradientBuffer[u][c]-s[c])>1e-8){i=!0;break}i||f.warn("All gradient samples identical \u2014 Fisher estimate may be poor. Ensure recordOutcome() is called with diverse rewards.")}let a=this.microLora.consolidate();this.applyEWCRegularization();let n=this.ewc.computeLoss(this.microLora.getEffectiveWeights());this.lastConsolidationRequest=this.requestCount,this.gradientBuffer=[];let o=performance.now()-t;return{consolidated:a>0||r,adaptationsMerged:a,ewcLossBefore:e,ewcLossAfter:n,taskBoundaryDetected:r,durationMs:o}}shouldConsolidate(){return this.requestCount-this.lastConsolidationRequest>=this.config.consolidationInterval}syncWithPeers(t){if(t.length===0)return;for(let i of t)this.peerStates.set(i.peerId,i);let e=this.config.dimension,r=new Float32Array(e),a=new Float32Array(e),n=this.ewc.getFisherDiagonal(),o=this.microLora.adaptationVector;for(let i=0;i<e;i++){let s=n[i]+1e-10;r[i]+=s*o[i],a[i]+=s}for(let i of t){let s=Math.min(i.adaptationVector.length,e);for(let u=0;u<s;u++){let c=(u<i.fisherDiagonal.length?i.fisherDiagonal[u]:0)+1e-10;r[u]+=c*i.adaptationVector[u],a[u]+=c}}for(let i=0;i<e;i++)this.microLora.adaptationVector[i]=r[i]/a[i];f.debug("Synced with peers",{peerCount:t.length,peersStored:this.peerStates.size})}getLocalPeerState(t,e){return{peerId:t,domain:e,adaptationVector:new Float32Array(this.microLora.adaptationVector),fisherDiagonal:this.ewc.getFisherDiagonal(),requestCount:this.requestCount,lastUpdateMs:Date.now()}}getEWCMetrics(){let t=this.ewc.getMetrics();return t.regularizationLoss=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),t}getFisherDiagonal(){return this.ewc.getFisherDiagonal()}getOptimalParams(){return this.ewc.getOptimalParams()}loadFisher(t,e){this.ewc.loadFisher(t,e)}getBaseWeights(){return new Float32Array(this.microLora.baseWeights)}setBaseWeights(t){let e=Math.min(t.length,this.microLora.baseWeights.length);for(let r=0;r<e;r++)this.microLora.baseWeights[r]=t[r]}getEffectiveWeights(){return this.microLora.getEffectiveWeights()}getRequestCount(){return this.requestCount}getConfig(){return{...this.config}}getPeerStates(){return new Map(this.peerStates)}getMicroLoRA(){return this.microLora}getEWC(){return this.ewc}applyEWCRegularization(){let t=this.config.dimension,e=this.ewc.fisherMatrix,r=this.ewc.optimalParams,a=this.microLora.baseWeights,n=.01;for(let o=0;o<t;o++)if(e[o]>this.config.importanceThreshold){let i=a[o]-r[o];a[o]-=n*e[o]*i}}persistFisher(t,e){let r=this.ewc.getMetrics();t(e,this.ewc.getFisherDiagonal(),this.ewc.getOptimalParams(),this.getBaseWeights(),{taskBoundaries:r.taskBoundariesDetected,consolidationCycles:r.consolidationCycles,requestCount:this.requestCount,ewcLambda:r.lambda}),f.info("Fisher matrix persisted to SQLite",{domain:e,requestCount:this.requestCount,taskBoundaries:r.taskBoundariesDetected})}restoreFisher(t){this.ewc.loadFisher(t.fisherDiagonal,t.optimalParams),t.baseWeights&&this.setBaseWeights(t.baseWeights),this.requestCount=t.requestCount,f.info("Fisher matrix restored from SQLite",{requestCount:t.requestCount,dimension:t.fisherDiagonal.length})}};var Lt={hiddenDim:256,embeddingDim:384,microLoraRank:1,baseLoraRank:8,microLoraLr:.001,baseLoraLr:1e-4,ewcLambda:1e3,patternClusters:50,trajectoryCapacity:1e4,backgroundIntervalMs:36e5,qualityThreshold:.5,enableSimd:!0,minConfidence:.5,maxPatterns:1e4},Q=class{patterns;trajectoryMap;maxPatterns;constructor(t=1e4){this.patterns=new Map,this.trajectoryMap=new Map,this.maxPatterns=t}register(t){if(this.patterns.size>=this.maxPatterns&&!this.patterns.has(t.id)){let e=Array.from(this.patterns.entries()).sort(([,r],[,a])=>(r.lastUsedAt?.getTime()??r.createdAt.getTime())-(a.lastUsedAt?.getTime()??a.createdAt.getTime()))[0];e&&this.patterns.delete(e[0])}this.patterns.set(t.id,t)}get(t){return this.patterns.get(t)}getByTrajectory(t){let e=this.trajectoryMap.get(t);return e?this.patterns.get(e):void 0}associateTrajectory(t,e){this.trajectoryMap.set(t,e)}update(t,e){let r=this.patterns.get(t);return r?(this.patterns.set(t,{...r,...e}),!0):!1}getAll(){return Array.from(this.patterns.values())}getByType(t){return Array.from(this.patterns.values()).filter(e=>e.type===t)}getByDomain(t){return Array.from(this.patterns.values()).filter(e=>e.domain===t)}clear(){this.patterns.clear(),this.trajectoryMap.clear()}size(){return this.patterns.size}},v=class{engine;registry;config;adaptationTimes=[];cacheHits=0;totalAdaptations=0;threeLoopEngine=null;fisherPersistFn=null;fisherDomain="default";constructor(t={}){this.config={...Lt,...t};let e={hiddenDim:this.config.hiddenDim,embeddingDim:this.config.embeddingDim,microLoraRank:this.config.microLoraRank,baseLoraRank:this.config.baseLoraRank,microLoraLr:this.config.microLoraLr,baseLoraLr:this.config.baseLoraLr,ewcLambda:this.config.ewcLambda,patternClusters:this.config.patternClusters,trajectoryCapacity:this.config.trajectoryCapacity,backgroundIntervalMs:this.config.backgroundIntervalMs,qualityThreshold:this.config.qualityThreshold,enableSimd:this.config.enableSimd};this.engine=P.withConfig(e),this.registry=new Q(this.config.maxPatterns??1e4)}async adaptPattern(t,e,r){let a=performance.now();try{let n=this.createStateEmbedding(t),o=this.engine.findPatterns(n,5),i=[];for(let m of o){let g=this.findByRawPattern(m);if(g||(g=this.createQEPatternFromRaw(m,e,r)),g.type===e&&g.domain===r&&g.confidence>=(this.config.minConfidence??.5)){let h=this.calculateSimilarity(n,m.centroid);i.push({pattern:g,similarity:h})}}if(i.length===0){let m=performance.now()-a;return this.recordAdaptation(m),{success:!1,pattern:null,adaptationTimeMs:m,similarity:0,reasoning:"No suitable pattern found"}}let s=i[0],u={...s.pattern,usageCount:s.pattern.usageCount+1,lastUsedAt:new Date};this.registry.update(u.id,u);let c=performance.now()-a;return this.recordAdaptation(c),{success:!0,pattern:u,adaptationTimeMs:c,similarity:s.similarity,reasoning:`Pattern adapted from @ruvector/sona with ${s.similarity.toFixed(3)} similarity`}}catch(n){let o=performance.now()-a;return this.recordAdaptation(o),{success:!1,pattern:null,adaptationTimeMs:o,similarity:0,reasoning:`Adaptation failed: ${n.message}`}}}recallPattern(t,e,r){let a=this.createStateEmbedding(t),n=this.engine.findPatterns(a,1);for(let o of n){let i=this.findByRawPattern(o);if(i&&i.type===e&&i.domain===r)return i}return null}storePattern(t){this.registry.register(t);let e=this.engine.beginTrajectory(t.stateEmbedding),r=this.createActionEmbedding(t.action),a=new Array(r.length).fill(1),n=t.outcome.success?t.outcome.quality:-t.outcome.quality;this.engine.addTrajectoryStep(e,r,a,n),this.engine.endTrajectory(e,t.outcome.quality),this.registry.associateTrajectory(e,t.id)}storePatternsBatch(t){for(let e of t)this.storePattern(e)}createPattern(t,e,r,a,n,o){let i={id:`qesona-${Date.now()}-${Ct().slice(0,7)}`,type:a,domain:n,stateEmbedding:this.createStateEmbedding(t),action:e,outcome:r,confidence:.5,usageCount:0,createdAt:new Date,metadata:o};return this.storePattern(i),i}updatePattern(t,e,r){let a=this.registry.get(t);if(!a)return!1;let n=e?r:-r,i=a.confidence+.1*(n-a.confidence),s={...a,confidence:Math.max(0,Math.min(1,i)),usageCount:a.usageCount+1,lastUsedAt:new Date};return this.registry.update(t,s)}applyMicroLora(t){return this.engine.applyMicroLora(t)}applyBaseLora(t,e){return this.engine.applyBaseLora(t,e)}forceLearn(){return this.engine.forceLearn()}tick(){return this.engine.tick()}getAllPatterns(){return this.registry.getAll()}getPatternsByType(t){return this.registry.getByType(t)}getPatternsByDomain(t){return this.registry.getByDomain(t)}getStats(){let t=this.registry.getAll(),e=this.engine.getStats(),r={"test-generation":0,"defect-prediction":0,"coverage-optimization":0,"quality-assessment":0,"resource-allocation":0};for(let a of t)r[a.type]++;return{totalPatterns:t.length,patternsByType:r,avgAdaptationTimeMs:this.avgAdaptationTime(),minAdaptationTimeMs:this.minAdaptationTime(),maxAdaptationTimeMs:this.maxAdaptationTime(),totalAdaptations:this.totalAdaptations,cacheHitRate:this.totalAdaptations>0?this.cacheHits/this.totalAdaptations:0,engineStats:e}}clear(){this.registry.clear(),this.adaptationTimes=[],this.cacheHits=0,this.totalAdaptations=0}exportPatterns(){return this.registry.getAll()}importPatterns(t){this.clear(),this.storePatternsBatch(t)}getConfig(){return{...this.config}}setEnabled(t){this.engine.setEnabled(t)}isEnabled(){return this.engine.isEnabled()}createStateEmbedding(t){let e=t.features;if(e.length===0)return new Array(this.config.embeddingDim??384).fill(0);let r=Math.max(...e.map(Math.abs));if(r===0)return[...e];let a=e.map(o=>o/r),n=this.config.embeddingDim??384;return a.length>=n?a.slice(0,n):[...a,...new Array(n-a.length).fill(0)]}createActionEmbedding(t){let e=[],r=this.hashCode(t.type);if(e.push(r%1e3/1e3),typeof t.value=="number")e.push(Math.min(1,Math.max(-1,t.value)));else if(typeof t.value=="string"){let n=this.hashCode(t.value);e.push(n%1e3/1e3)}else if(Array.isArray(t.value))for(let n of t.value.slice(0,10))typeof n=="number"&&e.push(Math.min(1,Math.max(-1,n)));let a=this.config.embeddingDim??384;for(;e.length<a;)e.push(0);return e.slice(0,a)}findByRawPattern(t){let e=this.registry.getAll();for(let r of e)if(r.rawPattern?.patternType===t.id)return r}createQEPatternFromRaw(t,e,r){let a={centroid:t.centroid,clusterSize:1,totalWeight:1,avgQuality:t.avgQuality,createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString(),accessCount:0,patternType:t.patternType};return{id:`qesona-${t.id}`,type:e,domain:r,stateEmbedding:t.centroid,action:{type:"learned",value:t.patternType},outcome:{reward:t.avgQuality,success:t.avgQuality>.5,quality:t.avgQuality},confidence:t.avgQuality,usageCount:0,createdAt:new Date,rawPattern:a}}calculateSimilarity(t,e){let r=Math.min(t.length,e.length),a=0,n=0,o=0;for(let s=0;s<r;s++)a+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return(a/(Math.sqrt(n)*Math.sqrt(o)+1e-10)+1)/2}hashCode(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e=e|0;return Math.abs(e)}recordAdaptation(t){this.adaptationTimes.push(t),this.totalAdaptations++,this.adaptationTimes.length>1e3&&this.adaptationTimes.shift()}avgAdaptationTime(){return this.adaptationTimes.length===0?0:this.adaptationTimes.reduce((e,r)=>e+r,0)/this.adaptationTimes.length}minAdaptationTime(){return this.adaptationTimes.length===0?0:Math.min(...this.adaptationTimes)}maxAdaptationTime(){return this.adaptationTimes.length===0?0:Math.max(...this.adaptationTimes)}initThreeLoopEngine(t){this.threeLoopEngine=new C({dimension:this.config.embeddingDim??384,microLoraLr:this.config.microLoraLr??.001,ewcLambda:this.config.ewcLambda??1e3,...t},this.engine)}getThreeLoopEngine(){return this.threeLoopEngine}instantAdapt(t){return this.threeLoopEngine?this.threeLoopEngine.instantAdapt(t):null}recordOutcome(t,e){this.threeLoopEngine&&this.threeLoopEngine.recordOutcome(t,e)}backgroundConsolidate(){if(!this.threeLoopEngine)return null;let t=this.threeLoopEngine.backgroundConsolidate();if(t&&(t.consolidated||t.taskBoundaryDetected)&&this.fisherPersistFn)try{this.threeLoopEngine.persistFisher(this.fisherPersistFn,this.fisherDomain)}catch(e){console.warn("[QESONA] Fisher persistence failed:",e instanceof Error?e.message:e)}return t}setFisherPersistence(t,e){this.fisherPersistFn=t,this.fisherDomain=e}syncWithPeers(t){this.threeLoopEngine&&this.threeLoopEngine.syncWithPeers(t)}getEWCMetrics(){return this.threeLoopEngine?this.threeLoopEngine.getEWCMetrics():null}shouldConsolidate(){return this.threeLoopEngine?this.threeLoopEngine.shouldConsolidate():!1}getLocalPeerState(t,e){return this.threeLoopEngine?this.threeLoopEngine.getLocalPeerState(t,e):null}isThreeLoopEnabled(){return this.threeLoopEngine!==null}async verifyPerformance(t=1e3){let e=[],r={id:"test-state",features:new Array(384).fill(0).map(()=>G())};for(let s=0;s<t;s++){let u=performance.now();await this.adaptPattern(r,"test-generation","test-generation");let c=performance.now();e.push({iteration:s,timeMs:c-u})}let a=e.map(s=>s.timeMs),n=a.reduce((s,u)=>s+u,0)/a.length,o=Math.min(...a),i=Math.max(...a);return{targetMet:n<.05,avgTimeMs:n,minTimeMs:o,maxTimeMs:i,details:e}}};function Tt(l){return new v(l)}function Pt(l,t){return new v({...t,maxPatterns:t?.maxPatterns||5e3})}ot();et();var F=null,D=null,W=null,B=null,z=null,I=null,q=!1;try{let l=(O(),w(N));F=l.FlashAttention,D=l.DotProductAttention,W=l.MultiHeadAttention,B=l.HyperbolicAttention,z=l.LinearAttention,I=l.MoEAttention,q=!0}catch{}function Gt(){return q}function A(){if(!q)throw new Error("@ruvector/attention native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var T={"test-similarity":{dim:384,strategy:"flash",blockSize:64},"code-embedding":{dim:512,strategy:"flash",blockSize:128},"defect-matching":{dim:384,strategy:"flash",blockSize:64},"coverage-analysis":{dim:384,strategy:"flash",blockSize:256},"pattern-adaptation":{dim:256,strategy:"flash",blockSize:32}},Kt={"test-similarity":{enabled:!0,microLoRARank:4,targetAdaptationMs:.05,patternCacheSize:1e3},"code-embedding":{enabled:!0,microLoRARank:2,targetAdaptationMs:.03,patternCacheSize:5e3},"defect-matching":{enabled:!0,microLoRARank:8,targetAdaptationMs:.05,patternCacheSize:2e3},"coverage-analysis":{enabled:!1,microLoRARank:2,targetAdaptationMs:.01,patternCacheSize:100},"pattern-adaptation":{enabled:!0,microLoRARank:2,targetAdaptationMs:.05,patternCacheSize:1e4}},$t={"test-similarity":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:1e3}},"code-embedding":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:2e3}},"defect-matching":{latency:{before:20,after:5},memory:{before:150,after:50},throughput:{min:500}},"coverage-analysis":{latency:{before:100,after:1},memory:{before:100,after:30},throughput:{min:1e4}},"pattern-adaptation":{latency:{before:2,after:.05},memory:{before:50,after:20},throughput:{min:2e4}}};function Zt(l){return l<=128?{queryChunkSize:128,kvChunkSize:128}:l<=256?{queryChunkSize:256,kvChunkSize:256}:l<=512?{queryChunkSize:512,kvChunkSize:512}:l<=1024?{queryChunkSize:1024,kvChunkSize:1024}:{queryChunkSize:1024,kvChunkSize:2048}}var E=class{static create(t){switch(A(),t.strategy){case"flash":return new F(t.dim,t.blockSize);case"dot-product":return new D(t.dim);case"multi-head":return new W(t.dim,t.numHeads??8);case"hyperbolic":return new B(t.dim,t.curvature);case"linear":return new z(t.dim,t.features);case"moe":return I.simple(t.dim,t.moeConfig?.numExperts??8,t.moeConfig?.topK??2);default:return new F(t.dim,t.blockSize)}}},L=class l{attention;config;workload;metrics=[];db=null;persistCount=0;static KV_NAMESPACE="attention-metrics";static KV_TTL=3600;static PERSIST_INTERVAL=10;constructor(t,e){this.workload=t;let r=T[t];this.config={...r,...e},this.attention=E.create(this.config)}async initialize(){try{this.db=K(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[QEFlashAttention] DB init failed, using memory-only:",j(t)),this.db=null}}async computeFlashAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=this.toFloat32Array(t,a,n),u=this.splitMatrix(e,a,n),c=this.splitMatrix(r,a,n),m,g=this.attention;typeof g.compute=="function"?m=g.compute(s,u,c):(A(),m=new F(this.config.dim).compute(s,u,c));let h=performance.now(),d=process.memoryUsage().heapUsed/1024/1024;return this.metrics.push({timeMs:h-o,memoryMB:d-i,speedup:1,throughput:a*a/((h-o)/1e3),peakMemoryMB:d}),this.maybePersistToKv(),m}async computeBaselineAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=new Float32Array(a*a),u=1/Math.sqrt(n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=0;for(let p=0;p<n;p++)b+=t[h*n+p]*e[d*n+p];s[h*a+d]=b*u}for(let h=0;h<a;h++){let d=h*a,b=d+a,p=s.subarray(d,b),tt=Math.max(...p),_=0;for(let y=0;y<a;y++)p[y]=Math.exp(p[y]-tt),_+=p[y];for(let y=0;y<a;y++)p[y]/=_}let c=new Float32Array(a*n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=s[h*a+d];for(let p=0;p<n;p++)c[h*n+p]+=b*r[d*n+p]}let m=performance.now(),g=process.memoryUsage().heapUsed/1024/1024;return c}async computeTestSimilarity(t,e,r=5){let a=e.length,n=t.length,o=new Float32Array(a*n),i=new Float32Array(a*n);for(let m=0;m<a;m++)o.set(t,m*n),i.set(e[m],m*n);let s=new Float32Array(a*n),u=await this.computeFlashAttention(o,i,s,a,n),c=[];for(let m=0;m<a;m++)c.push({index:m,similarity:u[m*n]});return c.sort((m,g)=>g.similarity-m.similarity),c.slice(0,r)}async generateCodeEmbedding(t,e){let r=t.length/e.length,a=e.length;return await this.computeFlashAttention(t,e,t,r,a)}async matchDefectPattern(t,e){let r=e.length,a=t.length,n=new Float32Array(r*a),o=new Float32Array(r*a);for(let c=0;c<r;c++)n.set(t,c*a),o.set(e[c],c*a);let i=new Float32Array(r*a),s=await this.computeFlashAttention(n,o,i,r,a),u=[];for(let c=0;c<r;c++)u.push({pattern:c,score:s[c*a]});return u.sort((c,m)=>m.score-c.score),u}getMetrics(){return[...this.metrics]}getAverageSpeedup(){return this.metrics.length===0?1:this.metrics.reduce((t,e)=>t+e.speedup,0)/this.metrics.length}getConfig(){return{...this.config}}updateConfig(t){this.config={...this.config,...t},this.attention=E.create(this.config)}changeStrategy(t){this.config.strategy=t,this.attention=E.create(this.config)}resetMetrics(){this.metrics=[]}getWorkload(){return this.workload}dispose(){this.metrics=[]}async persistToKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e={workload:this.workload,metrics:this.metrics.slice(-50),savedAt:Date.now()};await this.db.kvSet(t,e,l.KV_NAMESPACE,l.KV_TTL)}async loadFromKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e=await this.db.kvGet(t,l.KV_NAMESPACE);e?.metrics?.length&&(this.metrics=e.metrics)}maybePersistToKv(){this.persistCount++,this.persistCount>=l.PERSIST_INTERVAL&&(this.persistCount=0,this.persistToKv().catch(()=>{}))}toFloat32Array(t,e,r){return t.slice(0,r)}splitMatrix(t,e,r){let a=[];for(let n=0;n<e;n++)a.push(t.slice(n*r,(n+1)*r));return a}};async function Y(l,t){let e=new L(l,t);return await e.initialize(),e}function Jt(l){return{...T[l]}}function Xt(){return Object.keys(T)}function Yt(){return A(),F}function te(){return A(),D}function ee(){return A(),W}function re(){return A(),B}function ae(){return A(),z}function ne(){return A(),I}function ie(l){return l instanceof Float32Array?l:new Float32Array(l)}function oe(l){return Array.from(l)}async function se(l,t,e,r){let a=await Y(l),n=[],o=t[0].length,i=e.length;for(let s of t){let u=new Float32Array(i*o),c=new Float32Array(i*o),m=new Float32Array(i*o);u.set(s,0);for(let h=0;h<i;h++)c.set(e[h],h*o),m.set(r[h],h*o);let g=await a.computeFlashAttention(u,c,m,i,o);n.push(g.slice(0,o))}return a.dispose(),n}function We(){return{"@ruvector/sona":"^0.1.5","@ruvector/attention":"^0.1.4","@ruvector/gnn":"^0.1.22"}}function Be(){let l={sona:!1,attention:!1,gnn:!1,all:!1};try{k(),l.sona=!0}catch{}try{O(),l.attention=!0}catch{}try{let t=(it(),w(nt));t.init();let e=new Float32Array([.1,.2,.3]),r=[new Float32Array([.1,.2,.3]),new Float32Array([.4,.5,.6])],a=t.differentiableSearch(e,r,1,1);a&&Array.isArray(a.indices)&&Array.isArray(a.weights)&&(l.gnn=!0)}catch{}return l.all=l.sona&&l.attention&&l.gnn,l}async function ze(){let{initGNN:l}=await import("./gnn-wrapper-5AG3WDWF.js");return[l(),"SONA: Ready (no initialization required)","Attention: Ready (no initialization required)"]}export{v as a,Tt as b,Pt as c,Gt as d,T as e,Kt as f,$t as g,Zt as h,L as i,Y as j,Jt as k,Xt as l,Yt as m,te as n,ee as o,re as p,ae as q,ne as r,ie as s,oe as t,se as u,We as v,Be as w,ze as x};
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.10.3");process.exit(0)}
2
+ import{k as K,o as ot}from"./chunk-USFZ4IJD.js";import{a as rt}from"./chunk-3VF3HCG4.js";import{c as U}from"./chunk-2L73WXA4.js";import{a as j,c as et}from"./chunk-3LRK7PYN.js";import{a as G,d as at}from"./chunk-7ZSPCGTI.js";import{a as nt,b as it}from"./chunk-HMFEPKAR.js";import{c as H,e as V,g as w}from"./chunk-CAMEFWRK.js";var Z={};V(Z,{DotProductAttention:()=>yt,FlashAttention:()=>ft,HyperbolicAttention:()=>bt,LinearAttention:()=>vt,MoEAttention:()=>Et,MultiHeadAttention:()=>At,RuvectorLayer:()=>ut,SonaEngine:()=>P,TensorCompress:()=>mt,default:()=>ct,differentiableSearch:()=>ht,getCompressionLevel:()=>pt,hierarchicalForward:()=>dt,init:()=>gt,pipeline:()=>Ft});import{createRequire as st}from"module";var lt,$,ct,ut,mt,ht,dt,pt,gt,ft,yt,At,bt,vt,Et,P,Ft,k=H(()=>{lt=st(import.meta.url),$=lt("@ruvector/sona"),ct=$,{RuvectorLayer:ut,TensorCompress:mt,differentiableSearch:ht,hierarchicalForward:dt,getCompressionLevel:pt,init:gt,FlashAttention:ft,DotProductAttention:yt,MultiHeadAttention:At,HyperbolicAttention:bt,LinearAttention:vt,MoEAttention:Et,SonaEngine:P,pipeline:Ft}=$||{}});var N={};V(N,{DotProductAttention:()=>It,FlashAttention:()=>zt,HyperbolicAttention:()=>_t,LinearAttention:()=>Ht,MoEAttention:()=>Vt,MultiHeadAttention:()=>qt,RuvectorLayer:()=>Qt,SonaEngine:()=>jt,TensorCompress:()=>Nt,default:()=>xt,differentiableSearch:()=>Ot,getCompressionLevel:()=>Wt,hierarchicalForward:()=>Dt,init:()=>Bt,pipeline:()=>Ut});import{createRequire as kt}from"module";var Rt,X,xt,Qt,Nt,Ot,Dt,Wt,Bt,zt,It,qt,_t,Ht,Vt,jt,Ut,O=H(()=>{Rt=kt(import.meta.url),X=Rt("@ruvector/attention"),xt=X,{RuvectorLayer:Qt,TensorCompress:Nt,differentiableSearch:Ot,hierarchicalForward:Dt,getCompressionLevel:Wt,init:Bt,FlashAttention:zt,DotProductAttention:It,MultiHeadAttention:qt,HyperbolicAttention:_t,LinearAttention:Ht,MoEAttention:Vt,SonaEngine:jt,pipeline:Ut}=X||{}});k();at();import{randomUUID as Ct}from"crypto";rt();import{createRequire as wt}from"module";var f=U.create("sona-three-loop"),S=wt(import.meta.url),M=null,J=!1;function St(){if(J)return M;J=!0;try{let l=S("@ruvector/learning-wasm"),t=S("fs"),e=S("path"),r=e.join(e.dirname(S.resolve("@ruvector/learning-wasm")),"ruvector_learning_wasm_bg.wasm");l.initSync({module:t.readFileSync(r)}),M=l,f.info("WASM MicroLoRA loaded from @ruvector/learning-wasm (6.4x faster than TS)")}catch{M=null,f.debug("@ruvector/learning-wasm not available, using TypeScript MicroLoRA")}return M}var Mt={dimension:384,microLoraLr:.001,consolidationInterval:100,ewcLambda:1e3,taskBoundaryZScoreThreshold:2.5,fisherDecay:.9,fisherSampleSize:200,importanceThreshold:.01},R=class{adaptationVector;baseWeights;lr;adaptationCount=0;constructor(t,e=.001){this.adaptationVector=new Float32Array(t),this.baseWeights=new Float32Array(t),this.lr=e}adapt(t){let e=this.baseWeights.length,r=new Float32Array(e),a=Math.min(t.length,e);for(let n=0;n<e;n++){let o=n<a?t[n]:0;r[n]=this.baseWeights[n]+this.adaptationVector[n]+this.lr*o}for(let n=0;n<a;n++)this.adaptationVector[n]+=this.lr*t[n];return this.adaptationCount++,r}consolidate(){let t=this.adaptationCount,e=this.baseWeights.length;for(let r=0;r<e;r++)this.baseWeights[r]+=this.adaptationVector[r],this.adaptationVector[r]=0;return this.adaptationCount=0,t}getAdaptationCount(){return this.adaptationCount}getEffectiveWeights(){let t=this.baseWeights.length,e=new Float32Array(t);for(let r=0;r<t;r++)e[r]=this.baseWeights[r]+this.adaptationVector[r];return e}getAdaptationMagnitude(){let t=0;for(let e=0;e<this.adaptationVector.length;e++)t+=this.adaptationVector[e]*this.adaptationVector[e];return Math.sqrt(t)}resetAdaptation(){this.adaptationVector.fill(0),this.adaptationCount=0}},x=class{fisherMatrix;optimalParams;lambda;fisherDecay;zScoreThreshold;importanceThreshold;gradientHistory=[];gradientMean=0;gradientVariance=0;taskBoundaryCount=0;consolidationCount=0;constructor(t,e=1e3,r=.9,a=2.5,n=.01){this.fisherMatrix=new Float32Array(t),this.optimalParams=new Float32Array(t),this.lambda=e,this.fisherDecay=r,this.zScoreThreshold=a,this.importanceThreshold=n}detectTaskBoundary(t){let e=0;for(let i=0;i<t.length;i++)e+=t[i]*t[i];if(e=Math.sqrt(e),this.gradientHistory.length<5)return this.gradientHistory.push(e),this.updateGradientStats(),!1;let r=Math.sqrt(this.gradientVariance),a=0,n=Math.abs(e-this.gradientMean);return r>1e-10?a=n/r:n>1e-10&&this.gradientMean>1e-10&&(a=n/(this.gradientMean*.01+1e-10)),this.gradientHistory.push(e),this.gradientHistory.length>100&&this.gradientHistory.shift(),this.updateGradientStats(),a>this.zScoreThreshold?(this.taskBoundaryCount++,!0):!1}computeLoss(t){let e=0,r=Math.min(t.length,this.fisherMatrix.length,this.optimalParams.length);for(let a=0;a<r;a++){let n=t[a]-this.optimalParams[a];e+=this.fisherMatrix[a]*n*n}return this.lambda/2*e}updateFisher(t,e){if(t.length===0)return;let r=this.fisherMatrix.length,a=new Float32Array(r);for(let s of t){let u=Math.min(s.length,r);for(let c=0;c<u;c++)a[c]+=s[c]*s[c]}let n=t.length;for(let s=0;s<r;s++)a[s]/=n;let o=this.fisherDecay;for(let s=0;s<r;s++)this.fisherMatrix[s]=o*this.fisherMatrix[s]+(1-o)*a[s];let i=Math.min(e.length,r);for(let s=0;s<i;s++)this.optimalParams[s]=e[s];this.consolidationCount++}getMetrics(){let t=this.fisherMatrix.length,e=0,r=0,a=0;for(let n=0;n<t;n++)e+=this.fisherMatrix[n],this.fisherMatrix[n]>r&&(r=this.fisherMatrix[n]),this.fisherMatrix[n]>this.importanceThreshold&&a++;return{regularizationLoss:0,taskBoundariesDetected:this.taskBoundaryCount,fisherTrace:e,avgFisherImportance:t>0?e/t:0,maxFisherImportance:r,protectedParams:a,consolidationCycles:this.consolidationCount,lambda:this.lambda}}getTaskBoundaryCount(){return this.taskBoundaryCount}getFisherDiagonal(){return new Float32Array(this.fisherMatrix)}getOptimalParams(){return new Float32Array(this.optimalParams)}loadFisher(t,e){let r=this.fisherMatrix.length,a=Math.min(t.length,r),n=Math.min(e.length,r);for(let o=0;o<a;o++)this.fisherMatrix[o]=t[o];for(let o=0;o<n;o++)this.optimalParams[o]=e[o]}updateGradientStats(){let t=this.gradientHistory.length;if(t===0)return;let e=0;for(let a of this.gradientHistory)e+=a;e/=t;let r=0;for(let a of this.gradientHistory){let n=a-e;r+=n*n}r=t>1?r/(t-1):0,this.gradientMean=e,this.gradientVariance=r}},C=class{config;microLora;ewc;nativeEngine;wasmLora=null;requestCount=0;lastConsolidationRequest=0;peerStates=new Map;gradientBuffer=[];lastFeatures=null;constructor(t={},e){this.config={...Mt,...t},this.nativeEngine=e??null,this.microLora=new R(this.config.dimension,this.config.microLoraLr),this.ewc=new x(this.config.dimension,this.config.ewcLambda,this.config.fisherDecay,this.config.taskBoundaryZScoreThreshold,this.config.importanceThreshold);let r=St();if(r)try{this.wasmLora=new r.WasmMicroLoRA(this.config.dimension,1,this.config.microLoraLr),f.info("SONA Three-Loop using WASM MicroLoRA (0.07us/adapt)")}catch(a){f.debug("WASM MicroLoRA creation failed, falling back",{error:String(a)}),this.wasmLora=null}!this.wasmLora&&this.nativeEngine&&f.info("SONA Three-Loop using native @ruvector/sona engine for MicroLoRA delegation")}instantAdapt(t){let e=performance.now(),r;if(this.wasmLora)try{let o=new Float32Array(t),i=this.wasmLora.adapt(o);i&&i.length>0?(r=i,this.microLora.adapt(t)):r=this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else if(this.nativeEngine)try{let o=this.nativeEngine.applyMicroLora(t);r=new Float32Array(o),this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else r=this.microLora.adapt(t);let a=this.microLora.getAdaptationMagnitude();this.requestCount++,this.lastFeatures=[...t];let n=(performance.now()-e)*1e3;return{adaptedWeights:r,latencyUs:n,applied:!0,magnitude:a,requestIndex:this.requestCount}}recordOutcome(t,e){if(this.lastFeatures===null){f.warn("recordOutcome called without a preceding instantAdapt()");return}let r=this.lastFeatures.length,a=new Float32Array(r);for(let n=0;n<r;n++)a[n]=t*this.lastFeatures[n];this.gradientBuffer.push(a),this.gradientBuffer.length>this.config.fisherSampleSize&&this.gradientBuffer.shift(),this.lastFeatures=null}backgroundConsolidate(){let t=performance.now();if(this.nativeEngine)try{this.nativeEngine.forceLearn(),this.nativeEngine.tick()}catch(i){f.warn("Native SONA background learning failed, continuing with TypeScript",{error:String(i)})}let e=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),r=!1;if(this.gradientBuffer.length>0){let i=this.gradientBuffer[this.gradientBuffer.length-1];r=this.ewc.detectTaskBoundary(i)}if(r&&this.gradientBuffer.length>0&&(this.ewc.updateFisher(this.gradientBuffer,this.microLora.getEffectiveWeights()),f.info("Task boundary detected, Fisher updated",{boundaries:this.ewc.getTaskBoundaryCount(),requestCount:this.requestCount})),this.gradientBuffer.length>1){let i=!1,s=this.gradientBuffer[0];for(let u=1;u<this.gradientBuffer.length&&!i;u++)for(let c=0;c<s.length;c++)if(Math.abs(this.gradientBuffer[u][c]-s[c])>1e-8){i=!0;break}i||f.warn("All gradient samples identical \u2014 Fisher estimate may be poor. Ensure recordOutcome() is called with diverse rewards.")}let a=this.microLora.consolidate();this.applyEWCRegularization();let n=this.ewc.computeLoss(this.microLora.getEffectiveWeights());this.lastConsolidationRequest=this.requestCount,this.gradientBuffer=[];let o=performance.now()-t;return{consolidated:a>0||r,adaptationsMerged:a,ewcLossBefore:e,ewcLossAfter:n,taskBoundaryDetected:r,durationMs:o}}shouldConsolidate(){return this.requestCount-this.lastConsolidationRequest>=this.config.consolidationInterval}syncWithPeers(t){if(t.length===0)return;for(let i of t)this.peerStates.set(i.peerId,i);let e=this.config.dimension,r=new Float32Array(e),a=new Float32Array(e),n=this.ewc.getFisherDiagonal(),o=this.microLora.adaptationVector;for(let i=0;i<e;i++){let s=n[i]+1e-10;r[i]+=s*o[i],a[i]+=s}for(let i of t){let s=Math.min(i.adaptationVector.length,e);for(let u=0;u<s;u++){let c=(u<i.fisherDiagonal.length?i.fisherDiagonal[u]:0)+1e-10;r[u]+=c*i.adaptationVector[u],a[u]+=c}}for(let i=0;i<e;i++)this.microLora.adaptationVector[i]=r[i]/a[i];f.debug("Synced with peers",{peerCount:t.length,peersStored:this.peerStates.size})}getLocalPeerState(t,e){return{peerId:t,domain:e,adaptationVector:new Float32Array(this.microLora.adaptationVector),fisherDiagonal:this.ewc.getFisherDiagonal(),requestCount:this.requestCount,lastUpdateMs:Date.now()}}getEWCMetrics(){let t=this.ewc.getMetrics();return t.regularizationLoss=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),t}getFisherDiagonal(){return this.ewc.getFisherDiagonal()}getOptimalParams(){return this.ewc.getOptimalParams()}loadFisher(t,e){this.ewc.loadFisher(t,e)}getBaseWeights(){return new Float32Array(this.microLora.baseWeights)}setBaseWeights(t){let e=Math.min(t.length,this.microLora.baseWeights.length);for(let r=0;r<e;r++)this.microLora.baseWeights[r]=t[r]}getEffectiveWeights(){return this.microLora.getEffectiveWeights()}getRequestCount(){return this.requestCount}getConfig(){return{...this.config}}getPeerStates(){return new Map(this.peerStates)}getMicroLoRA(){return this.microLora}getEWC(){return this.ewc}applyEWCRegularization(){let t=this.config.dimension,e=this.ewc.fisherMatrix,r=this.ewc.optimalParams,a=this.microLora.baseWeights,n=.01;for(let o=0;o<t;o++)if(e[o]>this.config.importanceThreshold){let i=a[o]-r[o];a[o]-=n*e[o]*i}}persistFisher(t,e){let r=this.ewc.getMetrics();t(e,this.ewc.getFisherDiagonal(),this.ewc.getOptimalParams(),this.getBaseWeights(),{taskBoundaries:r.taskBoundariesDetected,consolidationCycles:r.consolidationCycles,requestCount:this.requestCount,ewcLambda:r.lambda}),f.info("Fisher matrix persisted to SQLite",{domain:e,requestCount:this.requestCount,taskBoundaries:r.taskBoundariesDetected})}restoreFisher(t){this.ewc.loadFisher(t.fisherDiagonal,t.optimalParams),t.baseWeights&&this.setBaseWeights(t.baseWeights),this.requestCount=t.requestCount,f.info("Fisher matrix restored from SQLite",{requestCount:t.requestCount,dimension:t.fisherDiagonal.length})}};var Lt={hiddenDim:256,embeddingDim:384,microLoraRank:1,baseLoraRank:8,microLoraLr:.001,baseLoraLr:1e-4,ewcLambda:1e3,patternClusters:50,trajectoryCapacity:1e4,backgroundIntervalMs:36e5,qualityThreshold:.5,enableSimd:!0,minConfidence:.5,maxPatterns:1e4},Q=class{patterns;trajectoryMap;maxPatterns;constructor(t=1e4){this.patterns=new Map,this.trajectoryMap=new Map,this.maxPatterns=t}register(t){if(this.patterns.size>=this.maxPatterns&&!this.patterns.has(t.id)){let e=Array.from(this.patterns.entries()).sort(([,r],[,a])=>(r.lastUsedAt?.getTime()??r.createdAt.getTime())-(a.lastUsedAt?.getTime()??a.createdAt.getTime()))[0];e&&this.patterns.delete(e[0])}this.patterns.set(t.id,t)}get(t){return this.patterns.get(t)}getByTrajectory(t){let e=this.trajectoryMap.get(t);return e?this.patterns.get(e):void 0}associateTrajectory(t,e){this.trajectoryMap.set(t,e)}update(t,e){let r=this.patterns.get(t);return r?(this.patterns.set(t,{...r,...e}),!0):!1}getAll(){return Array.from(this.patterns.values())}getByType(t){return Array.from(this.patterns.values()).filter(e=>e.type===t)}getByDomain(t){return Array.from(this.patterns.values()).filter(e=>e.domain===t)}clear(){this.patterns.clear(),this.trajectoryMap.clear()}size(){return this.patterns.size}},v=class{engine;registry;config;adaptationTimes=[];cacheHits=0;totalAdaptations=0;threeLoopEngine=null;fisherPersistFn=null;fisherDomain="default";constructor(t={}){this.config={...Lt,...t};let e={hiddenDim:this.config.hiddenDim,embeddingDim:this.config.embeddingDim,microLoraRank:this.config.microLoraRank,baseLoraRank:this.config.baseLoraRank,microLoraLr:this.config.microLoraLr,baseLoraLr:this.config.baseLoraLr,ewcLambda:this.config.ewcLambda,patternClusters:this.config.patternClusters,trajectoryCapacity:this.config.trajectoryCapacity,backgroundIntervalMs:this.config.backgroundIntervalMs,qualityThreshold:this.config.qualityThreshold,enableSimd:this.config.enableSimd};this.engine=P.withConfig(e),this.registry=new Q(this.config.maxPatterns??1e4)}async adaptPattern(t,e,r){let a=performance.now();try{let n=this.createStateEmbedding(t),o=this.engine.findPatterns(n,5),i=[];for(let m of o){let g=this.findByRawPattern(m);if(g||(g=this.createQEPatternFromRaw(m,e,r)),g.type===e&&g.domain===r&&g.confidence>=(this.config.minConfidence??.5)){let h=this.calculateSimilarity(n,m.centroid);i.push({pattern:g,similarity:h})}}if(i.length===0){let m=performance.now()-a;return this.recordAdaptation(m),{success:!1,pattern:null,adaptationTimeMs:m,similarity:0,reasoning:"No suitable pattern found"}}let s=i[0],u={...s.pattern,usageCount:s.pattern.usageCount+1,lastUsedAt:new Date};this.registry.update(u.id,u);let c=performance.now()-a;return this.recordAdaptation(c),{success:!0,pattern:u,adaptationTimeMs:c,similarity:s.similarity,reasoning:`Pattern adapted from @ruvector/sona with ${s.similarity.toFixed(3)} similarity`}}catch(n){let o=performance.now()-a;return this.recordAdaptation(o),{success:!1,pattern:null,adaptationTimeMs:o,similarity:0,reasoning:`Adaptation failed: ${n.message}`}}}recallPattern(t,e,r){let a=this.createStateEmbedding(t),n=this.engine.findPatterns(a,1);for(let o of n){let i=this.findByRawPattern(o);if(i&&i.type===e&&i.domain===r)return i}return null}storePattern(t){this.registry.register(t);let e=this.engine.beginTrajectory(t.stateEmbedding),r=this.createActionEmbedding(t.action),a=new Array(r.length).fill(1),n=t.outcome.success?t.outcome.quality:-t.outcome.quality;this.engine.addTrajectoryStep(e,r,a,n),this.engine.endTrajectory(e,t.outcome.quality),this.registry.associateTrajectory(e,t.id)}storePatternsBatch(t){for(let e of t)this.storePattern(e)}createPattern(t,e,r,a,n,o){let i={id:`qesona-${Date.now()}-${Ct().slice(0,7)}`,type:a,domain:n,stateEmbedding:this.createStateEmbedding(t),action:e,outcome:r,confidence:.5,usageCount:0,createdAt:new Date,metadata:o};return this.storePattern(i),i}updatePattern(t,e,r){let a=this.registry.get(t);if(!a)return!1;let n=e?r:-r,i=a.confidence+.1*(n-a.confidence),s={...a,confidence:Math.max(0,Math.min(1,i)),usageCount:a.usageCount+1,lastUsedAt:new Date};return this.registry.update(t,s)}applyMicroLora(t){return this.engine.applyMicroLora(t)}applyBaseLora(t,e){return this.engine.applyBaseLora(t,e)}forceLearn(){return this.engine.forceLearn()}tick(){return this.engine.tick()}getAllPatterns(){return this.registry.getAll()}getPatternsByType(t){return this.registry.getByType(t)}getPatternsByDomain(t){return this.registry.getByDomain(t)}getStats(){let t=this.registry.getAll(),e=this.engine.getStats(),r={"test-generation":0,"defect-prediction":0,"coverage-optimization":0,"quality-assessment":0,"resource-allocation":0};for(let a of t)r[a.type]++;return{totalPatterns:t.length,patternsByType:r,avgAdaptationTimeMs:this.avgAdaptationTime(),minAdaptationTimeMs:this.minAdaptationTime(),maxAdaptationTimeMs:this.maxAdaptationTime(),totalAdaptations:this.totalAdaptations,cacheHitRate:this.totalAdaptations>0?this.cacheHits/this.totalAdaptations:0,engineStats:e}}clear(){this.registry.clear(),this.adaptationTimes=[],this.cacheHits=0,this.totalAdaptations=0}exportPatterns(){return this.registry.getAll()}importPatterns(t){this.clear(),this.storePatternsBatch(t)}getConfig(){return{...this.config}}setEnabled(t){this.engine.setEnabled(t)}isEnabled(){return this.engine.isEnabled()}createStateEmbedding(t){let e=t.features;if(e.length===0)return new Array(this.config.embeddingDim??384).fill(0);let r=Math.max(...e.map(Math.abs));if(r===0)return[...e];let a=e.map(o=>o/r),n=this.config.embeddingDim??384;return a.length>=n?a.slice(0,n):[...a,...new Array(n-a.length).fill(0)]}createActionEmbedding(t){let e=[],r=this.hashCode(t.type);if(e.push(r%1e3/1e3),typeof t.value=="number")e.push(Math.min(1,Math.max(-1,t.value)));else if(typeof t.value=="string"){let n=this.hashCode(t.value);e.push(n%1e3/1e3)}else if(Array.isArray(t.value))for(let n of t.value.slice(0,10))typeof n=="number"&&e.push(Math.min(1,Math.max(-1,n)));let a=this.config.embeddingDim??384;for(;e.length<a;)e.push(0);return e.slice(0,a)}findByRawPattern(t){let e=this.registry.getAll();for(let r of e)if(r.rawPattern?.patternType===t.id)return r}createQEPatternFromRaw(t,e,r){let a={centroid:t.centroid,clusterSize:1,totalWeight:1,avgQuality:t.avgQuality,createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString(),accessCount:0,patternType:t.patternType};return{id:`qesona-${t.id}`,type:e,domain:r,stateEmbedding:t.centroid,action:{type:"learned",value:t.patternType},outcome:{reward:t.avgQuality,success:t.avgQuality>.5,quality:t.avgQuality},confidence:t.avgQuality,usageCount:0,createdAt:new Date,rawPattern:a}}calculateSimilarity(t,e){let r=Math.min(t.length,e.length),a=0,n=0,o=0;for(let s=0;s<r;s++)a+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return(a/(Math.sqrt(n)*Math.sqrt(o)+1e-10)+1)/2}hashCode(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e=e|0;return Math.abs(e)}recordAdaptation(t){this.adaptationTimes.push(t),this.totalAdaptations++,this.adaptationTimes.length>1e3&&this.adaptationTimes.shift()}avgAdaptationTime(){return this.adaptationTimes.length===0?0:this.adaptationTimes.reduce((e,r)=>e+r,0)/this.adaptationTimes.length}minAdaptationTime(){return this.adaptationTimes.length===0?0:Math.min(...this.adaptationTimes)}maxAdaptationTime(){return this.adaptationTimes.length===0?0:Math.max(...this.adaptationTimes)}initThreeLoopEngine(t){this.threeLoopEngine=new C({dimension:this.config.embeddingDim??384,microLoraLr:this.config.microLoraLr??.001,ewcLambda:this.config.ewcLambda??1e3,...t},this.engine)}getThreeLoopEngine(){return this.threeLoopEngine}instantAdapt(t){return this.threeLoopEngine?this.threeLoopEngine.instantAdapt(t):null}recordOutcome(t,e){this.threeLoopEngine&&this.threeLoopEngine.recordOutcome(t,e)}backgroundConsolidate(){if(!this.threeLoopEngine)return null;let t=this.threeLoopEngine.backgroundConsolidate();if(t&&(t.consolidated||t.taskBoundaryDetected)&&this.fisherPersistFn)try{this.threeLoopEngine.persistFisher(this.fisherPersistFn,this.fisherDomain)}catch(e){console.warn("[QESONA] Fisher persistence failed:",e instanceof Error?e.message:e)}return t}setFisherPersistence(t,e){this.fisherPersistFn=t,this.fisherDomain=e}syncWithPeers(t){this.threeLoopEngine&&this.threeLoopEngine.syncWithPeers(t)}getEWCMetrics(){return this.threeLoopEngine?this.threeLoopEngine.getEWCMetrics():null}shouldConsolidate(){return this.threeLoopEngine?this.threeLoopEngine.shouldConsolidate():!1}getLocalPeerState(t,e){return this.threeLoopEngine?this.threeLoopEngine.getLocalPeerState(t,e):null}isThreeLoopEnabled(){return this.threeLoopEngine!==null}async verifyPerformance(t=1e3){let e=[],r={id:"test-state",features:new Array(384).fill(0).map(()=>G())};for(let s=0;s<t;s++){let u=performance.now();await this.adaptPattern(r,"test-generation","test-generation");let c=performance.now();e.push({iteration:s,timeMs:c-u})}let a=e.map(s=>s.timeMs),n=a.reduce((s,u)=>s+u,0)/a.length,o=Math.min(...a),i=Math.max(...a);return{targetMet:n<.05,avgTimeMs:n,minTimeMs:o,maxTimeMs:i,details:e}}};function Tt(l){return new v(l)}function Pt(l,t){return new v({...t,maxPatterns:t?.maxPatterns||5e3})}ot();et();var F=null,D=null,W=null,B=null,z=null,I=null,q=!1;try{let l=(O(),w(N));F=l.FlashAttention,D=l.DotProductAttention,W=l.MultiHeadAttention,B=l.HyperbolicAttention,z=l.LinearAttention,I=l.MoEAttention,q=!0}catch{}function Gt(){return q}function A(){if(!q)throw new Error("@ruvector/attention native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var T={"test-similarity":{dim:384,strategy:"flash",blockSize:64},"code-embedding":{dim:512,strategy:"flash",blockSize:128},"defect-matching":{dim:384,strategy:"flash",blockSize:64},"coverage-analysis":{dim:384,strategy:"flash",blockSize:256},"pattern-adaptation":{dim:256,strategy:"flash",blockSize:32}},Kt={"test-similarity":{enabled:!0,microLoRARank:4,targetAdaptationMs:.05,patternCacheSize:1e3},"code-embedding":{enabled:!0,microLoRARank:2,targetAdaptationMs:.03,patternCacheSize:5e3},"defect-matching":{enabled:!0,microLoRARank:8,targetAdaptationMs:.05,patternCacheSize:2e3},"coverage-analysis":{enabled:!1,microLoRARank:2,targetAdaptationMs:.01,patternCacheSize:100},"pattern-adaptation":{enabled:!0,microLoRARank:2,targetAdaptationMs:.05,patternCacheSize:1e4}},$t={"test-similarity":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:1e3}},"code-embedding":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:2e3}},"defect-matching":{latency:{before:20,after:5},memory:{before:150,after:50},throughput:{min:500}},"coverage-analysis":{latency:{before:100,after:1},memory:{before:100,after:30},throughput:{min:1e4}},"pattern-adaptation":{latency:{before:2,after:.05},memory:{before:50,after:20},throughput:{min:2e4}}};function Zt(l){return l<=128?{queryChunkSize:128,kvChunkSize:128}:l<=256?{queryChunkSize:256,kvChunkSize:256}:l<=512?{queryChunkSize:512,kvChunkSize:512}:l<=1024?{queryChunkSize:1024,kvChunkSize:1024}:{queryChunkSize:1024,kvChunkSize:2048}}var E=class{static create(t){switch(A(),t.strategy){case"flash":return new F(t.dim,t.blockSize);case"dot-product":return new D(t.dim);case"multi-head":return new W(t.dim,t.numHeads??8);case"hyperbolic":return new B(t.dim,t.curvature);case"linear":return new z(t.dim,t.features);case"moe":return I.simple(t.dim,t.moeConfig?.numExperts??8,t.moeConfig?.topK??2);default:return new F(t.dim,t.blockSize)}}},L=class l{attention;config;workload;metrics=[];db=null;persistCount=0;static KV_NAMESPACE="attention-metrics";static KV_TTL=3600;static PERSIST_INTERVAL=10;constructor(t,e){this.workload=t;let r=T[t];this.config={...r,...e},this.attention=E.create(this.config)}async initialize(){try{this.db=K(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[QEFlashAttention] DB init failed, using memory-only:",j(t)),this.db=null}}async computeFlashAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=this.toFloat32Array(t,a,n),u=this.splitMatrix(e,a,n),c=this.splitMatrix(r,a,n),m,g=this.attention;typeof g.compute=="function"?m=g.compute(s,u,c):(A(),m=new F(this.config.dim).compute(s,u,c));let h=performance.now(),d=process.memoryUsage().heapUsed/1024/1024;return this.metrics.push({timeMs:h-o,memoryMB:d-i,speedup:1,throughput:a*a/((h-o)/1e3),peakMemoryMB:d}),this.maybePersistToKv(),m}async computeBaselineAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=new Float32Array(a*a),u=1/Math.sqrt(n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=0;for(let p=0;p<n;p++)b+=t[h*n+p]*e[d*n+p];s[h*a+d]=b*u}for(let h=0;h<a;h++){let d=h*a,b=d+a,p=s.subarray(d,b),tt=Math.max(...p),_=0;for(let y=0;y<a;y++)p[y]=Math.exp(p[y]-tt),_+=p[y];for(let y=0;y<a;y++)p[y]/=_}let c=new Float32Array(a*n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=s[h*a+d];for(let p=0;p<n;p++)c[h*n+p]+=b*r[d*n+p]}let m=performance.now(),g=process.memoryUsage().heapUsed/1024/1024;return c}async computeTestSimilarity(t,e,r=5){let a=e.length,n=t.length,o=new Float32Array(a*n),i=new Float32Array(a*n);for(let m=0;m<a;m++)o.set(t,m*n),i.set(e[m],m*n);let s=new Float32Array(a*n),u=await this.computeFlashAttention(o,i,s,a,n),c=[];for(let m=0;m<a;m++)c.push({index:m,similarity:u[m*n]});return c.sort((m,g)=>g.similarity-m.similarity),c.slice(0,r)}async generateCodeEmbedding(t,e){let r=t.length/e.length,a=e.length;return await this.computeFlashAttention(t,e,t,r,a)}async matchDefectPattern(t,e){let r=e.length,a=t.length,n=new Float32Array(r*a),o=new Float32Array(r*a);for(let c=0;c<r;c++)n.set(t,c*a),o.set(e[c],c*a);let i=new Float32Array(r*a),s=await this.computeFlashAttention(n,o,i,r,a),u=[];for(let c=0;c<r;c++)u.push({pattern:c,score:s[c*a]});return u.sort((c,m)=>m.score-c.score),u}getMetrics(){return[...this.metrics]}getAverageSpeedup(){return this.metrics.length===0?1:this.metrics.reduce((t,e)=>t+e.speedup,0)/this.metrics.length}getConfig(){return{...this.config}}updateConfig(t){this.config={...this.config,...t},this.attention=E.create(this.config)}changeStrategy(t){this.config.strategy=t,this.attention=E.create(this.config)}resetMetrics(){this.metrics=[]}getWorkload(){return this.workload}dispose(){this.metrics=[]}async persistToKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e={workload:this.workload,metrics:this.metrics.slice(-50),savedAt:Date.now()};await this.db.kvSet(t,e,l.KV_NAMESPACE,l.KV_TTL)}async loadFromKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e=await this.db.kvGet(t,l.KV_NAMESPACE);e?.metrics?.length&&(this.metrics=e.metrics)}maybePersistToKv(){this.persistCount++,this.persistCount>=l.PERSIST_INTERVAL&&(this.persistCount=0,this.persistToKv().catch(()=>{}))}toFloat32Array(t,e,r){return t.slice(0,r)}splitMatrix(t,e,r){let a=[];for(let n=0;n<e;n++)a.push(t.slice(n*r,(n+1)*r));return a}};async function Y(l,t){let e=new L(l,t);return await e.initialize(),e}function Jt(l){return{...T[l]}}function Xt(){return Object.keys(T)}function Yt(){return A(),F}function te(){return A(),D}function ee(){return A(),W}function re(){return A(),B}function ae(){return A(),z}function ne(){return A(),I}function ie(l){return l instanceof Float32Array?l:new Float32Array(l)}function oe(l){return Array.from(l)}async function se(l,t,e,r){let a=await Y(l),n=[],o=t[0].length,i=e.length;for(let s of t){let u=new Float32Array(i*o),c=new Float32Array(i*o),m=new Float32Array(i*o);u.set(s,0);for(let h=0;h<i;h++)c.set(e[h],h*o),m.set(r[h],h*o);let g=await a.computeFlashAttention(u,c,m,i,o);n.push(g.slice(0,o))}return a.dispose(),n}function We(){return{"@ruvector/sona":"^0.1.5","@ruvector/attention":"^0.1.4","@ruvector/gnn":"^0.1.22"}}function Be(){let l={sona:!1,attention:!1,gnn:!1,all:!1};try{k(),l.sona=!0}catch{}try{O(),l.attention=!0}catch{}try{let t=(it(),w(nt));t.init();let e=new Float32Array([.1,.2,.3]),r=[new Float32Array([.1,.2,.3]),new Float32Array([.4,.5,.6])],a=t.differentiableSearch(e,r,1,1);a&&Array.isArray(a.indices)&&Array.isArray(a.weights)&&(l.gnn=!0)}catch{}return l.all=l.sona&&l.attention&&l.gnn,l}async function ze(){let{initGNN:l}=await import("./gnn-wrapper-ZKNYACEC.js");return[l(),"SONA: Ready (no initialization required)","Attention: Ready (no initialization required)"]}export{v as a,Tt as b,Pt as c,Gt as d,T as e,Kt as f,$t as g,Zt as h,L as i,Y as j,Jt as k,Xt as l,Yt as m,te as n,ee as o,re as p,ae as q,ne as r,ie as s,oe as t,se as u,We as v,Be as w,ze as x};