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,6 +1,6 @@
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 ne}from"./chunk-WS4XVJHI.js";import{d as B,e as W,f as re,g as j}from"./chunk-NRLT44YB.js";import{g as et,h as tt}from"./chunk-YPOTBXPU.js";import{a as xe,d as Ce,e as Ze,f as De}from"./chunk-P7T5Y735.js";import{b as v,c as w}from"./chunk-Y2DPXMOR.js";import{a as y,b as Ae,c as Te}from"./chunk-2TDWCXZ6.js";import{i as C}from"./chunk-IK6AJX3C.js";import{B as q,D as H,G as te,P as M,S as F,b as D}from"./chunk-ELZ67OHQ.js";import{a as Ee,d as J,f as Ke,g as Re}from"./chunk-4AWJ5PE4.js";var V=J(S=>{var ut=S&&S.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(S,"__esModule",{value:!0});var ht=Object.prototype.hasOwnProperty;function le(n,e){return ht.call(n,e)}S.hasOwnProperty=le;function ke(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var i in n)le(n,i)&&r.push(i);return r}S._objectKeys=ke;function dt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}S._deepClone=dt;function ft(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}S.isInteger=ft;function oe(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}S.escapePathComponent=oe;function pt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}S.unescapePathComponent=pt;function ue(n,e){var t;for(var r in n)if(le(n,r)){if(n[r]===e)return oe(r)+"/";if(typeof n[r]=="object"&&(t=ue(n[r],e),t!=""))return oe(r)+"/"+t}return""}S._getPathRecursive=ue;function mt(n,e){if(n===e)return"/";var t=ue(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}S.getPath=mt;function ce(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(ce(n[e]))return!0}else if(typeof n=="object"){for(var r=ke(n),i=r.length,s=0;s<i;s++)if(ce(n[r[s]]))return!0}}return!1}S.hasUndefined=ce;function Le(n,e){var t=[n];for(var r in e){var i=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof i<"u"&&t.push(r+": "+i)}return t.join(`
3
- `)}var gt=(function(n){ut(e,n);function e(t,r,i,s,a){var c=this.constructor,u=n.call(this,Le(t,{name:r,index:i,operation:s,tree:a}))||this;return u.name=r,u.index=i,u.operation=s,u.tree=a,Object.setPrototypeOf(u,c.prototype),u.message=Le(t,{name:r,index:i,operation:s,tree:a}),u}return e})(Error);S.PatchError=gt});var he=J(m=>{Object.defineProperty(m,"__esModule",{value:!0});var b=V();m.JsonPatchError=b.PatchError;m.deepClone=b._deepClone;var L={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=Y(t,this.path);r&&(r=b._deepClone(r));var i=I(t,{op:"remove",path:this.from}).removed;return I(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=Y(t,this.from);return I(t,{op:"add",path:this.path,value:b._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:z(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},yt={add:function(n,e,t){return b.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:L.move,copy:L.copy,test:L.test,_get:L._get};function Y(n,e){if(e=="")return n;var t={op:"_get",path:e};return I(n,t),t.value}m.getValueByPointer=Y;function I(n,e,t,r,i,s){if(t===void 0&&(t=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),s===void 0&&(s=0),t&&(typeof t=="function"?t(e,0,n,e.path):K(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=Y(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=z(n,e.value),a.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new m.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=b._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,h=u.length,f=void 0,d=void 0,p=void 0;for(typeof t=="function"?p=t:p=K;;){if(d=u[l],d&&d.indexOf("~")!=-1&&(d=b.unescapePathComponent(d)),i&&(d=="__proto__"||d=="prototype"&&l>0&&u[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&f===void 0&&(o[d]===void 0?f=u.slice(0,l).join("/"):l==h-1&&(f=e.path),f!==void 0&&p(e,0,n,f)),l++,Array.isArray(o)){if(d==="-")d=o.length;else{if(t&&!b.isInteger(d))throw new m.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);b.isInteger(d)&&(d=~~d)}if(l>=h){if(t&&e.op==="add"&&d>o.length)throw new m.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var a=yt[e.op].call(e,o,d,n);if(a.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(l>=h){var a=L[e.op].call(e,o,d,n);if(a.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[d],t&&l<h&&(!o||typeof o!="object"))throw new m.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}m.applyOperation=I;function Ue(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new m.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=b._deepClone(n));for(var s=new Array(e.length),a=0,c=e.length;a<c;a++)s[a]=I(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}m.applyPatch=Ue;function vt(n,e,t){var r=I(n,e);if(r.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}m.applyReducer=vt;function K(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new m.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new m.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new m.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new m.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new m.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&b.hasUndefined(n.value))throw new m.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new m.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new m.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a={op:"_get",path:n.from,value:void 0},c=qe([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new m.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new m.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}m.validator=K;function qe(n,e,t){try{if(!Array.isArray(n))throw new m.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Ue(b._deepClone(e),b._deepClone(n),t||!0);else{t=t||K;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof m.JsonPatchError)return i;throw i}}m.validate=qe;function z(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),i,s,a;if(t&&r){if(s=n.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!z(n[i],e[i]))return!1;return!0}if(t!=r)return!1;var c=Object.keys(n);if(s=c.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(c[i]))return!1;for(i=s;i--!==0;)if(a=c[i],!z(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}m._areEquals=z});var Qe=J(k=>{Object.defineProperty(k,"__esModule",{value:!0});var P=V(),wt=he(),fe=new WeakMap,Pt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),St=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function bt(n){return fe.get(n)}function Et(n,e){return n.observers.get(e)}function Rt(n,e){n.observers.delete(e.callback)}function At(n,e){e.unobserve()}k.unobserve=At;function Tt(n,e){var t=[],r,i=bt(n);if(!i)i=new Pt(n),fe.set(n,i);else{var s=Et(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=P._deepClone(n),e){r.callback=e,r.next=null;var a=function(){de(r)},c=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return r.patches=t,r.object=n,r.unobserve=function(){de(r),clearTimeout(r.next),Rt(i,r),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},i.observers.set(e,new St(e,r)),r}k.observe=Tt;function de(n,e){e===void 0&&(e=!1);var t=fe.get(n.object);pe(t.value,n.object,n.patches,"",e),n.patches.length&&wt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=de;function pe(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=P._objectKeys(e),a=P._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],h=n[l];if(P.hasOwnProperty(e,l)&&!(e[l]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var f=e[l];typeof h=="object"&&h!=null&&typeof f=="object"&&f!=null&&Array.isArray(h)===Array.isArray(f)?pe(h,f,t,r+"/"+P.escapePathComponent(l),i):h!==f&&(c=!0,i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"replace",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(f)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"remove",path:r+"/"+P.escapePathComponent(l)}),u=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!u&&s.length==a.length))for(var o=0;o<s.length;o++){var l=s[o];!P.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(e[l])})}}}function xt(n,e,t){t===void 0&&(t=!1);var r=[];return pe(n,e,r,"",t),r}k.compare=xt});var ze=J(O=>{var Ct=he();Object.assign(O,Ct);var Dt=Qe();Object.assign(O,Dt);var Z=V();O.JsonPatchError=Z.PatchError;O.deepClone=Z._deepClone;O.escapePathComponent=Z.escapePathComponent;O.unescapePathComponent=Z.unescapePathComponent});Te();var Q=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??X,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1}createAdapter;config;rvfPath;skipCloseOnDispose;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=y(e),console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-TPXJK34J.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:i}=await import("node:fs"),s=`${this.rvfPath}.idmap.json`;if(!i(s))return;let a=JSON.parse(r(s,"utf-8")),c=new Set((a.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),u=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!u.has(l));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${y(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{let r=this.sqliteStore.storePattern(e,e.embedding);r&&r!==e.id&&(e.id=r)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,y(r))}if(e.embedding&&this.adapter)try{let r=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding);this.adapter.ingest([{id:e.id,vector:r}])}catch(r){console.warn(`[RvfPatternStore] RVF ingest failed for ${e.id}:`,y(r))}return v(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:B({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?v(i):w(s.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),i=t.limit??10,s=[];if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),u=this.adapter.search(c,i*2);for(let o of u){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,o.score);s.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",y(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let c=this.sqliteStore.getPatterns({limit:i*4}),u=e,o=Math.sqrt(u.reduce((l,h)=>l+h*h,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let h=this.sqliteStore.getPattern(l.id),f=h?.embedding;if(!f||f.length!==u.length)continue;let d=0,p=0;for(let R=0;R<u.length;R++)d+=u[R]*f[R],p+=f[R]*f[R];if(p=Math.sqrt(p),p===0)continue;let g=d/(o*p),E=this.calculateReuseInfo(h,g);s.push({pattern:h,score:g,matchType:"vector",similarity:g,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:i*2}),u=new Set(s.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);s.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,i*2),u=new Set(s.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,o.ftsScore);s.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch{}s.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,v(s.slice(0,i))}async recordUsage(e,t){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t),v(void 0)}catch(r){return w(new Error(`recordUsage failed: ${y(r)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),v(void 0)}catch(t){return w(new Error(`promote failed: ${y(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,y(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${y(t)}`))}return v(void 0)}async getStats(){let e=this.adapter?.status(),t=e?.totalVectors??0;if(t===0&&this.sqliteStore)try{t=this.sqliteStore.getStats().totalPatterns}catch{}return{totalPatterns:t,byTier:{shortTerm:0,longTerm:0},byDomain:{},byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=W&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",y(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,i=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:i,estimatedTokenSavings:i?500:0,reuseConfidence:i?t*e.successRate:0}}};De();Te();F();function nt(n,e){let r=[n.pattern,n];for(let i of r){let s=e.split("."),a=i;for(let c of s){if(a==null)break;if(typeof a=="object")a=a[c];else{a=void 0;break}}if(a!==void 0)return a}}function it(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let s=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),c=t[1]instanceof Date?t[1].getTime():Number(t[1]);return s>=a&&s<=c}return!1}let[r,i]=t;return n>=r&&n<=i}default:return!1}}function G(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>G(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>G(n,r))}case"NOT":return e.child?!G(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=nt(n,e.field);return it(t,e.operator,e.value)}default:return!0}}function Fe(n,e){return e?n.filter(t=>G(t,e)):n}F();F();var Oe=1e4,_e=2166136261;function Ne(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var ae=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;ae[n]=e}var Ie="0123456789abcdef";function st(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=Ie[i>>4]+Ie[i&15]}return t}function at(n,e){if(n.length!==e.length)throw new Error(`Cannot bind vectors of different lengths: ${n.length} vs ${e.length}`);let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function ot(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let i=1;i<n.length;i++)if(n[i].length!==e)throw new Error(`Vector length mismatch at index ${i}: expected ${e}, got ${n[i].length}`);let t=new Uint8Array(e),r=n.length/2;for(let i=0;i<e;i++){let s=0;for(let a=0;a<8;a++){let c=0,u=1<<a;for(let o=0;o<n.length;o++)n[o][i]&u&&c++;c>=r&&(s|=u)}t[i]=s}return t}function ct(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let s=0;s<n.length;s++)r+=ae[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function lt(n,e,t){return 1-ct(n,e,t)}var ie=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Oe,this.baseSeed=e?.seed??_e,this.byteLen=Math.ceil(this.dimensions/8),this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}tokenToHypervector(e){let t=this.tokenCache.get(e);if(t)return new Uint8Array(t);let r=Ne(e)^this.baseSeed,i=this.generateSeededVector(r);return this.tokenCache.set(e,i),new Uint8Array(i)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=at(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let i=this.fingerprintPattern(t);return ot([r,i])}similarity(e,t){return lt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new ne(e),i=0;for(;i<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-i);for(let u=0;u<c;u++)t[i++]=a>>>u*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},se=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Oe,this.baseSeed=e?.seed??_e,this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}fingerprint(e){let t=`${e.id}|${e.domain}|${e.type}|${e.content??""}`,r=Ne(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:st(i)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let i=0;i<e.length;i++)r+=ae[e[i]^t[i]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),i=new ne(e),s=0;for(;s<t;){let c=i.next(),u=t-s,o=u<4?u:4;for(let l=0;l<o;l++)r[s++]=c>>>l*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function He(n){return new se(n)}function Me(n){return q()?new ie(n):null}var $=Ke(ze(),1),Ft=`
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 ne}from"./chunk-UDV4YB42.js";import{d as B,e as W,f as re,g as j}from"./chunk-NXPFGPHV.js";import{g as et,h as tt}from"./chunk-JOLDCS6X.js";import{a as xe,d as Ce,e as Ze,f as De}from"./chunk-UHDBM7QS.js";import{b as v,c as w}from"./chunk-JD2PG4KS.js";import{a as y,b as Re,c as Te}from"./chunk-3LRK7PYN.js";import{i as C}from"./chunk-RTDHWOAG.js";import{B as q,D as H,G as te,P as M,S as F,b as D}from"./chunk-YIYV2JB6.js";import{a as Ee,d as J,f as Ke,g as Ae}from"./chunk-CAMEFWRK.js";var V=J(S=>{var ut=S&&S.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(S,"__esModule",{value:!0});var ht=Object.prototype.hasOwnProperty;function le(n,e){return ht.call(n,e)}S.hasOwnProperty=le;function ke(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var i in n)le(n,i)&&r.push(i);return r}S._objectKeys=ke;function dt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}S._deepClone=dt;function ft(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}S.isInteger=ft;function oe(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}S.escapePathComponent=oe;function mt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}S.unescapePathComponent=mt;function ue(n,e){var t;for(var r in n)if(le(n,r)){if(n[r]===e)return oe(r)+"/";if(typeof n[r]=="object"&&(t=ue(n[r],e),t!=""))return oe(r)+"/"+t}return""}S._getPathRecursive=ue;function pt(n,e){if(n===e)return"/";var t=ue(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}S.getPath=pt;function ce(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(ce(n[e]))return!0}else if(typeof n=="object"){for(var r=ke(n),i=r.length,s=0;s<i;s++)if(ce(n[r[s]]))return!0}}return!1}S.hasUndefined=ce;function Le(n,e){var t=[n];for(var r in e){var i=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof i<"u"&&t.push(r+": "+i)}return t.join(`
3
+ `)}var gt=(function(n){ut(e,n);function e(t,r,i,s,a){var c=this.constructor,u=n.call(this,Le(t,{name:r,index:i,operation:s,tree:a}))||this;return u.name=r,u.index=i,u.operation=s,u.tree=a,Object.setPrototypeOf(u,c.prototype),u.message=Le(t,{name:r,index:i,operation:s,tree:a}),u}return e})(Error);S.PatchError=gt});var he=J(p=>{Object.defineProperty(p,"__esModule",{value:!0});var b=V();p.JsonPatchError=b.PatchError;p.deepClone=b._deepClone;var L={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=Y(t,this.path);r&&(r=b._deepClone(r));var i=I(t,{op:"remove",path:this.from}).removed;return I(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=Y(t,this.from);return I(t,{op:"add",path:this.path,value:b._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:z(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},yt={add:function(n,e,t){return b.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:L.move,copy:L.copy,test:L.test,_get:L._get};function Y(n,e){if(e=="")return n;var t={op:"_get",path:e};return I(n,t),t.value}p.getValueByPointer=Y;function I(n,e,t,r,i,s){if(t===void 0&&(t=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),s===void 0&&(s=0),t&&(typeof t=="function"?t(e,0,n,e.path):K(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=Y(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=z(n,e.value),a.test===!1)throw new p.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new p.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=b._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,h=u.length,f=void 0,d=void 0,m=void 0;for(typeof t=="function"?m=t:m=K;;){if(d=u[l],d&&d.indexOf("~")!=-1&&(d=b.unescapePathComponent(d)),i&&(d=="__proto__"||d=="prototype"&&l>0&&u[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&f===void 0&&(o[d]===void 0?f=u.slice(0,l).join("/"):l==h-1&&(f=e.path),f!==void 0&&m(e,0,n,f)),l++,Array.isArray(o)){if(d==="-")d=o.length;else{if(t&&!b.isInteger(d))throw new p.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);b.isInteger(d)&&(d=~~d)}if(l>=h){if(t&&e.op==="add"&&d>o.length)throw new p.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var a=yt[e.op].call(e,o,d,n);if(a.test===!1)throw new p.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(l>=h){var a=L[e.op].call(e,o,d,n);if(a.test===!1)throw new p.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[d],t&&l<h&&(!o||typeof o!="object"))throw new p.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}p.applyOperation=I;function Ue(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new p.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=b._deepClone(n));for(var s=new Array(e.length),a=0,c=e.length;a<c;a++)s[a]=I(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}p.applyPatch=Ue;function vt(n,e,t){var r=I(n,e);if(r.test===!1)throw new p.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}p.applyReducer=vt;function K(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new p.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new p.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new p.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new p.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new p.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&b.hasUndefined(n.value))throw new p.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new p.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new p.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a={op:"_get",path:n.from,value:void 0},c=qe([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new p.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new p.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}p.validator=K;function qe(n,e,t){try{if(!Array.isArray(n))throw new p.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Ue(b._deepClone(e),b._deepClone(n),t||!0);else{t=t||K;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof p.JsonPatchError)return i;throw i}}p.validate=qe;function z(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),i,s,a;if(t&&r){if(s=n.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!z(n[i],e[i]))return!1;return!0}if(t!=r)return!1;var c=Object.keys(n);if(s=c.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(c[i]))return!1;for(i=s;i--!==0;)if(a=c[i],!z(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}p._areEquals=z});var Qe=J(k=>{Object.defineProperty(k,"__esModule",{value:!0});var P=V(),wt=he(),fe=new WeakMap,Pt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),St=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function bt(n){return fe.get(n)}function Et(n,e){return n.observers.get(e)}function At(n,e){n.observers.delete(e.callback)}function Rt(n,e){e.unobserve()}k.unobserve=Rt;function Tt(n,e){var t=[],r,i=bt(n);if(!i)i=new Pt(n),fe.set(n,i);else{var s=Et(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=P._deepClone(n),e){r.callback=e,r.next=null;var a=function(){de(r)},c=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return r.patches=t,r.object=n,r.unobserve=function(){de(r),clearTimeout(r.next),At(i,r),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},i.observers.set(e,new St(e,r)),r}k.observe=Tt;function de(n,e){e===void 0&&(e=!1);var t=fe.get(n.object);me(t.value,n.object,n.patches,"",e),n.patches.length&&wt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=de;function me(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=P._objectKeys(e),a=P._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],h=n[l];if(P.hasOwnProperty(e,l)&&!(e[l]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var f=e[l];typeof h=="object"&&h!=null&&typeof f=="object"&&f!=null&&Array.isArray(h)===Array.isArray(f)?me(h,f,t,r+"/"+P.escapePathComponent(l),i):h!==f&&(c=!0,i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"replace",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(f)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"remove",path:r+"/"+P.escapePathComponent(l)}),u=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!u&&s.length==a.length))for(var o=0;o<s.length;o++){var l=s[o];!P.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(e[l])})}}}function xt(n,e,t){t===void 0&&(t=!1);var r=[];return me(n,e,r,"",t),r}k.compare=xt});var ze=J(O=>{var Ct=he();Object.assign(O,Ct);var Dt=Qe();Object.assign(O,Dt);var Z=V();O.JsonPatchError=Z.PatchError;O.deepClone=Z._deepClone;O.escapePathComponent=Z.escapePathComponent;O.unescapePathComponent=Z.unescapePathComponent});Te();var Q=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??X,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1}createAdapter;config;rvfPath;skipCloseOnDispose;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=y(e),console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-CYESP7NG.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:i}=await import("node:fs"),s=`${this.rvfPath}.idmap.json`;if(!i(s))return;let a=JSON.parse(r(s,"utf-8")),c=new Set((a.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),u=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!u.has(l));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${y(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{let r=this.sqliteStore.storePattern(e,e.embedding);r&&r!==e.id&&(e.id=r)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,y(r))}if(e.embedding&&this.adapter)try{let r=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding);this.adapter.ingest([{id:e.id,vector:r}])}catch(r){console.warn(`[RvfPatternStore] RVF ingest failed for ${e.id}:`,y(r))}return v(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:B({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?v(i):w(s.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),i=t.limit??10,s=[];if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),u=this.adapter.search(c,i*2);for(let o of u){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,o.score);s.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",y(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let c=this.sqliteStore.getPatterns({limit:i*4}),u=e,o=Math.sqrt(u.reduce((l,h)=>l+h*h,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let h=this.sqliteStore.getPattern(l.id),f=h?.embedding;if(!f||f.length!==u.length)continue;let d=0,m=0;for(let A=0;A<u.length;A++)d+=u[A]*f[A],m+=f[A]*f[A];if(m=Math.sqrt(m),m===0)continue;let g=d/(o*m),E=this.calculateReuseInfo(h,g);s.push({pattern:h,score:g,matchType:"vector",similarity:g,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:i*2}),u=new Set(s.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);s.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,i*2),u=new Set(s.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,o.ftsScore);s.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch{}s.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,v(s.slice(0,i))}async recordUsage(e,t){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t),v(void 0)}catch(r){return w(new Error(`recordUsage failed: ${y(r)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),v(void 0)}catch(t){return w(new Error(`promote failed: ${y(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,y(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${y(t)}`))}return v(void 0)}async getStats(){let e=this.adapter?.status(),t=e?.totalVectors??0;if(t===0&&this.sqliteStore)try{t=this.sqliteStore.getStats().totalPatterns}catch{}return{totalPatterns:t,byTier:{shortTerm:0,longTerm:0},byDomain:{},byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=W&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",y(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,i=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:i,estimatedTokenSavings:i?500:0,reuseConfidence:i?t*e.successRate:0}}};De();Te();F();function nt(n,e){let r=[n.pattern,n];for(let i of r){let s=e.split("."),a=i;for(let c of s){if(a==null)break;if(typeof a=="object")a=a[c];else{a=void 0;break}}if(a!==void 0)return a}}function it(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let s=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),c=t[1]instanceof Date?t[1].getTime():Number(t[1]);return s>=a&&s<=c}return!1}let[r,i]=t;return n>=r&&n<=i}default:return!1}}function G(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>G(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>G(n,r))}case"NOT":return e.child?!G(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=nt(n,e.field);return it(t,e.operator,e.value)}default:return!0}}function Fe(n,e){return e?n.filter(t=>G(t,e)):n}F();F();var Oe=1e4,_e=2166136261;function Ne(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var ae=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;ae[n]=e}var Ie="0123456789abcdef";function st(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=Ie[i>>4]+Ie[i&15]}return t}function at(n,e){if(n.length!==e.length)throw new Error(`Cannot bind vectors of different lengths: ${n.length} vs ${e.length}`);let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function ot(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let i=1;i<n.length;i++)if(n[i].length!==e)throw new Error(`Vector length mismatch at index ${i}: expected ${e}, got ${n[i].length}`);let t=new Uint8Array(e),r=n.length/2;for(let i=0;i<e;i++){let s=0;for(let a=0;a<8;a++){let c=0,u=1<<a;for(let o=0;o<n.length;o++)n[o][i]&u&&c++;c>=r&&(s|=u)}t[i]=s}return t}function ct(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let s=0;s<n.length;s++)r+=ae[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function lt(n,e,t){return 1-ct(n,e,t)}var ie=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Oe,this.baseSeed=e?.seed??_e,this.byteLen=Math.ceil(this.dimensions/8),this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}tokenToHypervector(e){let t=this.tokenCache.get(e);if(t)return new Uint8Array(t);let r=Ne(e)^this.baseSeed,i=this.generateSeededVector(r);return this.tokenCache.set(e,i),new Uint8Array(i)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=at(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let i=this.fingerprintPattern(t);return ot([r,i])}similarity(e,t){return lt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new ne(e),i=0;for(;i<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-i);for(let u=0;u<c;u++)t[i++]=a>>>u*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},se=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Oe,this.baseSeed=e?.seed??_e,this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}fingerprint(e){let t=`${e.id}|${e.domain}|${e.type}|${e.content??""}`,r=Ne(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:st(i)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let i=0;i<e.length;i++)r+=ae[e[i]^t[i]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),i=new ne(e),s=0;for(;s<t;){let c=i.next(),u=t-s,o=u<4?u:4;for(let l=0;l<o;l++)r[s++]=c>>>l*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function He(n){return new se(n)}function Me(n){return q()?new ie(n):null}var $=Ke(ze(),1),Ft=`
4
4
  CREATE TABLE IF NOT EXISTS pattern_deltas (
5
5
  id TEXT PRIMARY KEY,
6
6
  pattern_id TEXT NOT NULL,
@@ -46,7 +46,7 @@ import{a as ne}from"./chunk-WS4XVJHI.js";import{d as B,e as W,f as re,g as j}fro
46
46
  WHERE pattern_id = ? AND version != 0
47
47
  ORDER BY version ASC
48
48
  LIMIT ?
49
- )`).run(e,e,s)}}};F();var Ot={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},me=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Ot,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let i=this.computeSparseChanges(new Array(t.length).fill(0),t),s={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:i,metadata:r,compressedSize:i.length},a={patternId:e,version:0,fullVector:[...t],timestamp:s.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(s),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(s),s}recordDelta(e,t,r,i){let s=this.versions.get(e);if(s===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=s+1,c=this.computeSparseChanges(t,r),u={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:i,compressedSize:c.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(u),this.buffer.push(u),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:u.timestamp}),this.enforceRetention(e),u}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let i=[...r].reverse();return t!==void 0&&t>0?i.slice(0,t):i}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let i=this.versions.get(e);if(t<0||t>i)return null;let s=this.snapshots.get(e)||[],a=null;for(let o=s.length-1;o>=0;o--)if(s[o].version<=t){a=s[o];break}if(!a)return null;let c=[...a.fullVector],u=a.version+1;for(let o of r)if(!(o.version<u)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,i=this.history.get(e);if(!i||i.length<=r)return 0;let s=i.length-r,a=i.slice(0,s),c=i.slice(s),u=a.findIndex(h=>h.deltaType==="genesis");u>=0&&(c.unshift(a[u]),a.splice(u,1)),this.history.set(e,c);let o=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(h=>h.version===0||h.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,c=s<t.length?t[s]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:s,oldValue:a,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function Be(n){return H()?new me(n):null}F();var _t=128,Nt=8,Ht=1e4,ge=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??_t,this.beta=e?.beta??Nt,this.maxPatterns=e?.maxPatterns??Ht,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let i=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:i,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let l=0;l<this.patterns.length;l++)r[l]=this.beta*this.dotProduct(this.patterns[l].pattern,t);let i=this.softmax(r),s=0,a=i[0];for(let l=1;l<i.length;l++)i[l]>a&&(a=i[l],s=l);let c=this.patterns[s],u=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:u,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let i=new Float32Array(this.patterns.length),s=-1/0;for(let o=0;o<this.patterns.length;o++)i[o]=this.beta*r[o],i[o]>s&&(s=i[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(i[o]-s);let c=1/this.beta*(s+Math.log(a)),u=this.dotProduct(t,t);return-c+.5*u}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let s=0;s<e.length;s++)e[s]>r&&(r=e[s]);let i=0;for(let s=0;s<e.length;s++)t[s]=Math.exp(e[s]-r),i+=t[s];if(i>0)for(let s=0;s<t.length;s++)t[s]/=i;return t}dotProduct(e,t){let r=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),i=Math.sqrt(this.dotProduct(e,e)),s=Math.sqrt(this.dotProduct(t,t));return i===0||s===0?0:r/(i*s)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let i=0;i<e.length;i++)r[i]=e[i]/t;return r}assertEnabled(){if(!D().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function We(n){return new ge(n)}F();var Mt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,je=1-_;function Lt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function A(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function kt(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var T=class n{static poincareDistance(e,t){let r=A(kt(e,t)),i=Math.max(_,1-A(e)),s=Math.max(_,1-A(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=Lt(e,t),i=A(e),s=A(t),a=Math.max(_,1+2*r+i*s),c=1+2*r+s,u=1-i,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+u*t[l])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(_,1-A(e)),i=Math.sqrt(A(t));if(i<_)return new Float32Array(e);let s=Math.tanh(r*i/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=s/i*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(A(e));if(t<=je)return new Float32Array(e);let r=je/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return i}static euclideanToHyperbolic(e){let t=Math.sqrt(A(e));if(t<_)return new Float32Array(e.length);let r=Math.tanh(t)/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return n.project(i)}},ye=class{config;points=new Map;constructor(e){if(this.config={...Mt,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:T.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=T.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:T.poincareDistance(r,s.coordinates),point:s});return i.sort((s,a)=>s.distance-a.distance),i.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,i=new Map,s=new Map,a=[];for(let u of e)if(s.set(u.id,u),!u.parentId)a.push(u.id);else{let o=i.get(u.parentId);o||(o=[],i.set(u.parentId,o)),o.push(u.id)}let c=a.map((u,o)=>({id:u,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;c.length>0;){let{id:u,depth:o,angOff:l,angSpan:h}=c.shift(),f=Math.tanh(.3*(o+.1)),d=l+h/2,p=new Float32Array(r);p[0]=f*Math.cos(d),p[1]=f*Math.sin(d);let g=s.get(u);if(g&&g.features.length>0){let N=f*.1;for(let x=2;x<r&&x-2<g.features.length;x++)p[x]=g.features[x-2]*N}let E=T.project(p);t.set(u,E),this.points.set(u,{id:u,coordinates:E,metadata:{depth:o,parentId:g?.parentId}});let R=i.get(u)??[];for(let N=0;N<R.length;N++){let x=h/Math.max(1,R.length);c.push({id:R[N],depth:o+1,angOff:l+N*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function Xe(n){return Ut()?new ye(n):null}function Ut(){return D().useHyperbolicHnsw}F();var ve=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!M())return!1;try{return this.index=Xe(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let i=t instanceof Float32Array?t:new Float32Array(t),s=T.euclideanToHyperbolic(i);this.index.insert(e,s,r)}catch(i){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,i instanceof Error?i.message:i)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),i=T.euclideanToHyperbolic(r);return this.index.search(i,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function Ge(n){return new ve(n)}var we=null;function Ve(){return we||(we=He({dimensions:1e4})),we}var Pe;function qt(){return Pe===void 0&&(Pe=Me()),Pe}var U=null,Se=0;function Ye(n){return(!U||Se!==n)&&(U=We({dimension:n,maxPatterns:1e4}),Se=n),U}var X={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:W,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},be=class{constructor(e,t={}){this.memory=e;this.config={...X,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,H()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new ee(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){return this.hnswIndex!==null?this.hnswIndex:this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-C7FG6YGW.js"),{HnswAdapter:c}=await import("./hnsw-adapter-2TCEG5M2.js"),u=new c("patterns",{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,metric:"cosine"});this.hnswIndex=new a(u),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)"),await this.loadEmbeddingsIntoHNSW();return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-VDPUTEES.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,i=this.hnswIndex.initialize(),s=new Promise((a,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",y(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,i=0;for(let{patternId:s,embedding:a}of e){if(r>=t)break;if(!a||a.length!==this.config.embeddingDimension){i++;continue}let c=this.patternCache.get(s);if(!c){i++;continue}try{await this.hnswIndex.insert(s,a,{filePath:c.patternType,lineCoverage:c.confidence*100,branchCoverage:c.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-c.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{i++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${i})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",y(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Be()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",y(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let i=this.patternCache.get(e.id)??null;if(this.indexPattern(e),this.sqliteStore)try{this.sqliteStore.storePattern(e,e.embedding)}catch(s){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,y(s))}if(e.embedding){let s=await this.ensureHNSW();if(s)try{await s.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(a){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,a)}}if(q())try{let a=Ve().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,a.vector)}catch(s){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,y(s))}try{let s=qt();if(s){let a=[e.patternType,e.qeDomain];e.context?.tags&&a.push(...e.context.tags),e.name&&a.push(e.name);let c=s.fingerprintPattern(a);this.hdcTokenCache.set(e.id,c)}}catch(s){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,y(s))}if(te()&&e.embedding)try{Ye(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(s){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,y(s))}if(H()&&this.deltaTracker)try{let s={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,s)}catch(s){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,y(s))}if(e.embedding)try{let s=this.getVectorDeltaTracker();s&&(i?.embedding?s.recordDelta(e.id,i.embedding,e.embedding):s.getVersion(e.id)<0&&s.recordGenesis(e.id,e.embedding))}catch(s){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,y(s))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return v(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?v(i):w(s.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),i=t.limit||10,s=[];try{if(Array.isArray(e)&&te())try{let h=Ye(e.length);if(h.getPatternCount()>0){let f=h.recall(new Float32Array(e));if(f&&f.similarity>.98){let d=f.metadata.id,p=await this.get(d);if(p&&this.matchesFilters(p,t)){let g=this.calculateReuseInfo(p,f.similarity);s.push({pattern:p,score:f.similarity,matchType:"vector",similarity:f.similarity,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}catch(h){console.debug("[PatternStore] Hopfield recall failed:",y(h))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let h=await this.ensureHNSW();if(h){let f=await h.search(e,i*2);for(let d of f){let p=await this.get(d.key);if(p&&this.matchesFilters(p,t)){let g=this.calculateReuseInfo(p,d.score);s.push({pattern:p,score:d.score,matchType:"vector",similarity:d.score,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let h=this.sqliteStore.searchFTS(e,i*2);if(h.length>0){let f=new Map(h.map(p=>[p.id,p.ftsScore])),d=new Set(s.map(p=>p.pattern.id));for(let p of s){let g=f.get(p.pattern.id);g!==void 0&&(p.score=.75*p.score+.25*g)}for(let p of h){if(d.has(p.id))continue;let g=await this.get(p.id);if(g&&this.matchesFilters(g,t)){let E=this.calculateReuseInfo(g,p.ftsScore);s.push({pattern:g,score:.5*p.ftsScore,matchType:"exact",similarity:p.ftsScore,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}}}catch{}if(typeof e=="string"||s.length<i){let h=await this.searchByText(typeof e=="string"?e:"",t,i-s.length),f=new Set(s.map(d=>d.pattern.id));for(let d of h)f.has(d.pattern.id)||s.push(d)}let a=720*60*60*1e3,c=Date.now();for(let h of s){let f=h.pattern.lastUsedAt?.getTime()??h.pattern.createdAt.getTime(),d=c-f,p=Math.pow(.5,d/a),g=h.pattern.usageCount>0?p:.5;h.score=h.score*(.7+.3*g)}s.sort((h,f)=>f.score-h.score);let u=s;t.filter&&(u=Fe(s,t.filter));let o=u.slice(0,i),l=performance.now()-r;return this.recordSearchLatency(l),v(o)}catch(a){return w(Ae(a))}}async searchByText(e,t,r){let i=[],s=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let c=[...a];if(q()&&s&&this.hdcCache.size>0)try{let u=Ve(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(d=>this.hdcCache.has(d)).map(d=>({id:d,similarity:u.similarity(o.vector,this.hdcCache.get(d))}));l.sort((d,p)=>p.similarity-d.similarity);let h=l.map(d=>d.id),f=c.filter(d=>!this.hdcCache.has(d));c=[...h,...f]}catch{}for(let u of c){if(i.length>=r)break;let o=this.patternCache.get(u);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(s){let h=o.name.toLowerCase(),f=o.description.toLowerCase();h.includes(s)&&(l+=.5),f.includes(s)&&(s.length/f.length>.3?l+=.5:l+=.3);for(let d of o.context.tags)if(d.toLowerCase().includes(s)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!s){let h=this.calculateReuseInfo(o,l);i.push({pattern:o,score:l||o.qualityScore,matchType:s?"exact":"context",similarity:l||o.qualityScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}return i}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,i=t>=r.minSimilarityForReuse,s=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),u=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&u,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,h=t,f=e.successRate,d=Math.min(e.reuseCount/10,1),p=o?h*.4+f*.4+d*.2:0;return{canReuse:o,estimatedTokenSavings:l,reuseConfidence:p}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t){let r=await this.get(e);if(!r)return w(new Error(`Pattern not found: ${e}`));let i=new Date,s=r.usageCount+1,a=r.successfulUses+(t?1:0),c=a/s,u=t?.02:-.01,o=Math.max(.1,Math.min(1,r.confidence+u)),l=B({confidence:o,usageCount:s,successRate:c}),h={...r,usageCount:s,successfulUses:a,successRate:c,confidence:o,qualityScore:l,lastUsedAt:i};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t)}catch(p){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,y(p))}if(H()&&this.deltaTracker)try{let p={id:r.id,name:r.name,confidence:r.confidence,qualityScore:r.qualityScore,usageCount:r.usageCount,successRate:r.successRate,tier:r.tier},g={id:h.id,name:h.name,confidence:h.confidence,qualityScore:h.qualityScore,usageCount:h.usageCount,successRate:h.successRate,tier:h.tier};this.deltaTracker.recordDelta(e,p,g,{success:t})}catch(p){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,y(p))}let f=re(h);return f.meetsUsageCriteria&&f.meetsQualityCriteria&&f.meetsCoherenceCriteria&&h.tier==="short-term"?await this.promote(e):this.patternCache.set(e,h),v(void 0)}async promote(e){let t=await this.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return v(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(i){console.debug("[PatternStore] SQLite promotion error:",i instanceof Error?i.message:i)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),v(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return v(void 0)}async getStats(){let e={},t={};for(let[o,l]of this.domainIndex)e[o]=l.size;for(let[o,l]of this.typeIndex)t[o]=l.size;let r=0,i=0,s=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,i+=o.qualityScore,s+=o.successRate,a++;let c=await this.ensureHNSW(),u=c!==null?await c.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?i/a:0,avgSuccessRate:a>0?s/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:u.nativeHNSW,vectorCount:u.vectorCount,indexSizeBytes:u.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],i=[];for(let s of this.patternCache.values()){let a=re(s);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){i.push(s.id);continue}if(s.tier==="short-term"){let u=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-u,l=o>10080*60*1e3,h=s.qualityScore<.2,f=s.usageCount===0&&o>1440*60*1e3;(l&&h||f)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let c=this.patternCache.get(a);c&&r.push(c)}r.sort((a,c)=>a.qualityScore-c.qualityScore);let i=Math.ceil(r.length*.1),s=0;for(let a of r){if(s>=i)break;a.tier==="short-term"&&(await this.delete(a.id),s++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),U&&(U.clear(),U=null,Se=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ge({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(i){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,i instanceof Error?i.message:i)}}async searchHyperbolic(e,t=10){if(!M()||!this.hyperbolicIndex)return v([]);try{let r=this.hyperbolicIndex.search(e,t),i=[];for(let s of r){let a=await this.get(s.patternId);if(!a)continue;let c=Math.exp(-s.distance),u=this.calculateReuseInfo(a,c);i.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}return v(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),v([])}}};function kr(n,e){try{if(D().useRVFPatternStore&&Ce()){let{existsSync:r}=Ee("fs"),i=".agentic-qe/patterns.rvf",s=Ee("path").dirname(i);if(r(s)){let a={...X,...e},c=!1;try{let{getSharedRvfAdapter:u}=(tt(),Re(et)),o=u(s,a.embeddingDimension);if(o){c=!0;let l=new Q(()=>o,{rvfPath:i,base:a,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}catch{}if(!c){let u=new Q((o,l)=>{let{openRvfStore:h}=(De(),Re(Ze)),f=()=>{try{return h(o)}catch{return null}},d=f();if(d){if(d.dimension()!==l){try{d.close()}catch{}throw new Error(`RVF dimension mismatch (file=${d.dimension()}, requested=${l})`)}return d}try{return xe(o,l)}catch(p){if(d=f(),d&&d.dimension()===l)return d;throw p}},{rvfPath:i,base:a});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),u}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new be(n,e)}export{kr as a};
49
+ )`).run(e,e,s)}}};F();var Ot={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},pe=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Ot,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let i=this.computeSparseChanges(new Array(t.length).fill(0),t),s={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:i,metadata:r,compressedSize:i.length},a={patternId:e,version:0,fullVector:[...t],timestamp:s.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(s),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(s),s}recordDelta(e,t,r,i){let s=this.versions.get(e);if(s===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=s+1,c=this.computeSparseChanges(t,r),u={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:i,compressedSize:c.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(u),this.buffer.push(u),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:u.timestamp}),this.enforceRetention(e),u}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let i=[...r].reverse();return t!==void 0&&t>0?i.slice(0,t):i}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let i=this.versions.get(e);if(t<0||t>i)return null;let s=this.snapshots.get(e)||[],a=null;for(let o=s.length-1;o>=0;o--)if(s[o].version<=t){a=s[o];break}if(!a)return null;let c=[...a.fullVector],u=a.version+1;for(let o of r)if(!(o.version<u)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,i=this.history.get(e);if(!i||i.length<=r)return 0;let s=i.length-r,a=i.slice(0,s),c=i.slice(s),u=a.findIndex(h=>h.deltaType==="genesis");u>=0&&(c.unshift(a[u]),a.splice(u,1)),this.history.set(e,c);let o=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(h=>h.version===0||h.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,c=s<t.length?t[s]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:s,oldValue:a,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function Be(n){return H()?new pe(n):null}F();var _t=128,Nt=8,Ht=1e4,ge=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??_t,this.beta=e?.beta??Nt,this.maxPatterns=e?.maxPatterns??Ht,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let i=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:i,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let l=0;l<this.patterns.length;l++)r[l]=this.beta*this.dotProduct(this.patterns[l].pattern,t);let i=this.softmax(r),s=0,a=i[0];for(let l=1;l<i.length;l++)i[l]>a&&(a=i[l],s=l);let c=this.patterns[s],u=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:u,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let i=new Float32Array(this.patterns.length),s=-1/0;for(let o=0;o<this.patterns.length;o++)i[o]=this.beta*r[o],i[o]>s&&(s=i[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(i[o]-s);let c=1/this.beta*(s+Math.log(a)),u=this.dotProduct(t,t);return-c+.5*u}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let s=0;s<e.length;s++)e[s]>r&&(r=e[s]);let i=0;for(let s=0;s<e.length;s++)t[s]=Math.exp(e[s]-r),i+=t[s];if(i>0)for(let s=0;s<t.length;s++)t[s]/=i;return t}dotProduct(e,t){let r=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),i=Math.sqrt(this.dotProduct(e,e)),s=Math.sqrt(this.dotProduct(t,t));return i===0||s===0?0:r/(i*s)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let i=0;i<e.length;i++)r[i]=e[i]/t;return r}assertEnabled(){if(!D().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function We(n){return new ge(n)}F();var Mt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,je=1-_;function Lt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function R(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function kt(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var T=class n{static poincareDistance(e,t){let r=R(kt(e,t)),i=Math.max(_,1-R(e)),s=Math.max(_,1-R(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=Lt(e,t),i=R(e),s=R(t),a=Math.max(_,1+2*r+i*s),c=1+2*r+s,u=1-i,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+u*t[l])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(_,1-R(e)),i=Math.sqrt(R(t));if(i<_)return new Float32Array(e);let s=Math.tanh(r*i/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=s/i*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(R(e));if(t<=je)return new Float32Array(e);let r=je/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return i}static euclideanToHyperbolic(e){let t=Math.sqrt(R(e));if(t<_)return new Float32Array(e.length);let r=Math.tanh(t)/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return n.project(i)}},ye=class{config;points=new Map;constructor(e){if(this.config={...Mt,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:T.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=T.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:T.poincareDistance(r,s.coordinates),point:s});return i.sort((s,a)=>s.distance-a.distance),i.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,i=new Map,s=new Map,a=[];for(let u of e)if(s.set(u.id,u),!u.parentId)a.push(u.id);else{let o=i.get(u.parentId);o||(o=[],i.set(u.parentId,o)),o.push(u.id)}let c=a.map((u,o)=>({id:u,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;c.length>0;){let{id:u,depth:o,angOff:l,angSpan:h}=c.shift(),f=Math.tanh(.3*(o+.1)),d=l+h/2,m=new Float32Array(r);m[0]=f*Math.cos(d),m[1]=f*Math.sin(d);let g=s.get(u);if(g&&g.features.length>0){let N=f*.1;for(let x=2;x<r&&x-2<g.features.length;x++)m[x]=g.features[x-2]*N}let E=T.project(m);t.set(u,E),this.points.set(u,{id:u,coordinates:E,metadata:{depth:o,parentId:g?.parentId}});let A=i.get(u)??[];for(let N=0;N<A.length;N++){let x=h/Math.max(1,A.length);c.push({id:A[N],depth:o+1,angOff:l+N*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function Xe(n){return Ut()?new ye(n):null}function Ut(){return D().useHyperbolicHnsw}F();var ve=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!M())return!1;try{return this.index=Xe(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let i=t instanceof Float32Array?t:new Float32Array(t),s=T.euclideanToHyperbolic(i);this.index.insert(e,s,r)}catch(i){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,i instanceof Error?i.message:i)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),i=T.euclideanToHyperbolic(r);return this.index.search(i,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function Ge(n){return new ve(n)}var we=null;function Ve(){return we||(we=He({dimensions:1e4})),we}var Pe;function qt(){return Pe===void 0&&(Pe=Me()),Pe}var U=null,Se=0;function Ye(n){return(!U||Se!==n)&&(U=We({dimension:n,maxPatterns:1e4}),Se=n),U}var X={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:W,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},be=class{constructor(e,t={}){this.memory=e;this.config={...X,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,H()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new ee(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){return this.hnswIndex!==null?this.hnswIndex:this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-LVHQ5SG7.js"),{HnswAdapter:c}=await import("./hnsw-adapter-K62GEHIL.js"),u=new c("patterns",{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,metric:"cosine"});this.hnswIndex=new a(u),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)"),await this.loadEmbeddingsIntoHNSW();return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-VCAK3TWN.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,i=this.hnswIndex.initialize(),s=new Promise((a,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",y(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,i=0;for(let{patternId:s,embedding:a}of e){if(r>=t)break;if(!a||a.length!==this.config.embeddingDimension){i++;continue}let c=this.patternCache.get(s);if(!c){i++;continue}try{await this.hnswIndex.insert(s,a,{filePath:c.patternType,lineCoverage:c.confidence*100,branchCoverage:c.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-c.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{i++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${i})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",y(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Be()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",y(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let i=this.patternCache.get(e.id)??null;if(this.indexPattern(e),this.sqliteStore)try{this.sqliteStore.storePattern(e,e.embedding)}catch(s){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,y(s))}if(e.embedding){let s=await this.ensureHNSW();if(s)try{await s.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(a){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,a)}}if(q())try{let a=Ve().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,a.vector)}catch(s){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,y(s))}try{let s=qt();if(s){let a=[e.patternType,e.qeDomain];e.context?.tags&&a.push(...e.context.tags),e.name&&a.push(e.name);let c=s.fingerprintPattern(a);this.hdcTokenCache.set(e.id,c)}}catch(s){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,y(s))}if(te()&&e.embedding)try{Ye(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(s){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,y(s))}if(H()&&this.deltaTracker)try{let s={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,s)}catch(s){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,y(s))}if(e.embedding)try{let s=this.getVectorDeltaTracker();s&&(i?.embedding?s.recordDelta(e.id,i.embedding,e.embedding):s.getVersion(e.id)<0&&s.recordGenesis(e.id,e.embedding))}catch(s){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,y(s))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return v(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?v(i):w(s.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),i=t.limit||10,s=[];try{if(Array.isArray(e)&&te())try{let h=Ye(e.length);if(h.getPatternCount()>0){let f=h.recall(new Float32Array(e));if(f&&f.similarity>.98){let d=f.metadata.id,m=await this.get(d);if(m&&this.matchesFilters(m,t)){let g=this.calculateReuseInfo(m,f.similarity);s.push({pattern:m,score:f.similarity,matchType:"vector",similarity:f.similarity,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}catch(h){console.debug("[PatternStore] Hopfield recall failed:",y(h))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let h=await this.ensureHNSW();if(h){let f=await h.search(e,i*2);for(let d of f){let m=await this.get(d.key);if(m&&this.matchesFilters(m,t)){let g=this.calculateReuseInfo(m,d.score);s.push({pattern:m,score:d.score,matchType:"vector",similarity:d.score,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let h=this.sqliteStore.searchFTS(e,i*2);if(h.length>0){let f=new Map(h.map(m=>[m.id,m.ftsScore])),d=new Set(s.map(m=>m.pattern.id));for(let m of s){let g=f.get(m.pattern.id);g!==void 0&&(m.score=.75*m.score+.25*g)}for(let m of h){if(d.has(m.id))continue;let g=await this.get(m.id);if(g&&this.matchesFilters(g,t)){let E=this.calculateReuseInfo(g,m.ftsScore);s.push({pattern:g,score:.5*m.ftsScore,matchType:"exact",similarity:m.ftsScore,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}}}catch{}if(typeof e=="string"||s.length<i){let h=await this.searchByText(typeof e=="string"?e:"",t,i-s.length),f=new Set(s.map(d=>d.pattern.id));for(let d of h)f.has(d.pattern.id)||s.push(d)}let a=720*60*60*1e3,c=Date.now();for(let h of s){let f=h.pattern.lastUsedAt?.getTime()??h.pattern.createdAt.getTime(),d=c-f,m=Math.pow(.5,d/a),g=h.pattern.usageCount>0?m:.5;h.score=h.score*(.7+.3*g)}s.sort((h,f)=>f.score-h.score);let u=s;t.filter&&(u=Fe(s,t.filter));let o=u.slice(0,i),l=performance.now()-r;return this.recordSearchLatency(l),v(o)}catch(a){return w(Re(a))}}async searchByText(e,t,r){let i=[],s=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let c=[...a];if(q()&&s&&this.hdcCache.size>0)try{let u=Ve(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(d=>this.hdcCache.has(d)).map(d=>({id:d,similarity:u.similarity(o.vector,this.hdcCache.get(d))}));l.sort((d,m)=>m.similarity-d.similarity);let h=l.map(d=>d.id),f=c.filter(d=>!this.hdcCache.has(d));c=[...h,...f]}catch{}for(let u of c){if(i.length>=r)break;let o=this.patternCache.get(u);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(s){let h=o.name.toLowerCase(),f=o.description.toLowerCase();h.includes(s)&&(l+=.5),f.includes(s)&&(s.length/f.length>.3?l+=.5:l+=.3);for(let d of o.context.tags)if(d.toLowerCase().includes(s)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!s){let h=this.calculateReuseInfo(o,l);i.push({pattern:o,score:l||o.qualityScore,matchType:s?"exact":"context",similarity:l||o.qualityScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}return i}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,i=t>=r.minSimilarityForReuse,s=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),u=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&u,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,h=t,f=e.successRate,d=Math.min(e.reuseCount/10,1),m=o?h*.4+f*.4+d*.2:0;return{canReuse:o,estimatedTokenSavings:l,reuseConfidence:m}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t){let r=await this.get(e);if(!r)return w(new Error(`Pattern not found: ${e}`));let i=new Date,s=r.usageCount+1,a=r.successfulUses+(t?1:0),c=a/s,u=t?.02:-.01,o=Math.max(.1,Math.min(1,r.confidence+u)),l=B({confidence:o,usageCount:s,successRate:c}),h={...r,usageCount:s,successfulUses:a,successRate:c,confidence:o,qualityScore:l,lastUsedAt:i};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t)}catch(m){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,y(m))}if(H()&&this.deltaTracker)try{let m={id:r.id,name:r.name,confidence:r.confidence,qualityScore:r.qualityScore,usageCount:r.usageCount,successRate:r.successRate,tier:r.tier},g={id:h.id,name:h.name,confidence:h.confidence,qualityScore:h.qualityScore,usageCount:h.usageCount,successRate:h.successRate,tier:h.tier};this.deltaTracker.recordDelta(e,m,g,{success:t})}catch(m){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,y(m))}let f=re(h);return f.meetsUsageCriteria&&f.meetsQualityCriteria&&f.meetsCoherenceCriteria&&h.tier==="short-term"?await this.promote(e):this.patternCache.set(e,h),v(void 0)}async promote(e){let t=await this.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return v(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(i){console.debug("[PatternStore] SQLite promotion error:",i instanceof Error?i.message:i)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),v(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return v(void 0)}async getStats(){let e={},t={};for(let[o,l]of this.domainIndex)e[o]=l.size;for(let[o,l]of this.typeIndex)t[o]=l.size;let r=0,i=0,s=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,i+=o.qualityScore,s+=o.successRate,a++;let c=await this.ensureHNSW(),u=c!==null?await c.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?i/a:0,avgSuccessRate:a>0?s/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:u.nativeHNSW,vectorCount:u.vectorCount,indexSizeBytes:u.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],i=[];for(let s of this.patternCache.values()){let a=re(s);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){i.push(s.id);continue}if(s.tier==="short-term"){let u=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-u,l=o>10080*60*1e3,h=s.qualityScore<.2,f=s.usageCount===0&&o>1440*60*1e3;(l&&h||f)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let c=this.patternCache.get(a);c&&r.push(c)}r.sort((a,c)=>a.qualityScore-c.qualityScore);let i=Math.ceil(r.length*.1),s=0;for(let a of r){if(s>=i)break;a.tier==="short-term"&&(await this.delete(a.id),s++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),U&&(U.clear(),U=null,Se=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ge({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(i){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,i instanceof Error?i.message:i)}}async searchHyperbolic(e,t=10){if(!M()||!this.hyperbolicIndex)return v([]);try{let r=this.hyperbolicIndex.search(e,t),i=[];for(let s of r){let a=await this.get(s.patternId);if(!a)continue;let c=Math.exp(-s.distance),u=this.calculateReuseInfo(a,c);i.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}return v(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),v([])}}};function Lr(n,e){try{if(D().useRVFPatternStore&&Ce()){let{existsSync:r}=Ee("fs"),i=".agentic-qe/patterns.rvf",s=Ee("path").dirname(i);if(r(s)){let a={...X,...e},c=!1;try{let{getSharedRvfAdapter:u}=(tt(),Ae(et)),o=u(s,a.embeddingDimension);if(o){c=!0;let l=new Q(()=>o,{rvfPath:i,base:a,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}catch{}if(!c){let u=new Q((o,l)=>{let{openRvfStore:h}=(De(),Ae(Ze)),f=()=>{try{return h(o)}catch{return null}},d=f();if(d){if(d.dimension()!==l){try{d.close()}catch{}throw new Error(`RVF dimension mismatch (file=${d.dimension()}, requested=${l})`)}return d}try{return xe(o,l)}catch(m){if(d=f(),d&&d.dimension()===l)return d;throw m}},{rvfPath:i,base:a});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),u}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new be(n,e)}export{Lr as a};
50
50
  /*! Bundled license information:
51
51
 
52
52
  fast-json-patch/commonjs/helpers.js:
@@ -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{k as p,o as N}from"./chunk-Q24OJX44.js";N();import{createHash as y}from"crypto";var g="0".repeat(64);function m(s){return y("sha256").update(s,"utf-8").digest("hex")}function R(s){try{return y("shake256",{outputLength:32}).update(s,"utf-8").digest("hex")}catch{return m(s)}}function _(s,t){return s==="shake256"?R(t):m(t)}function f(s){return JSON.stringify({id:s.id,prev_hash:s.prev_hash,action_hash:s.action_hash,action_type:s.action_type,action_data:s.action_data,timestamp:s.timestamp,actor:s.actor})}var d=class{constructor(t,i){this.externalDb=t;this.keyManager=i??null}externalDb;db=null;initialized=!1;keyManager=null;async initialize(){if(!this.initialized){if(this.externalDb)this.db=this.externalDb;else{let t=p();await t.initialize(),this.db=t.getDatabase()}this.ensureTable(),this.initialized=!0}}getDatabase(){return this.db}getKeyManager(){return this.keyManager}ensureTable(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.3");process.exit(0)}
2
+ import{k as p,o as N}from"./chunk-USFZ4IJD.js";N();import{createHash as y}from"crypto";var g="0".repeat(64);function m(s){return y("sha256").update(s,"utf-8").digest("hex")}function R(s){try{return y("shake256",{outputLength:32}).update(s,"utf-8").digest("hex")}catch{return m(s)}}function _(s,t){return s==="shake256"?R(t):m(t)}function f(s){return JSON.stringify({id:s.id,prev_hash:s.prev_hash,action_hash:s.action_hash,action_type:s.action_type,action_data:s.action_data,timestamp:s.timestamp,actor:s.actor})}var d=class{constructor(t,i){this.externalDb=t;this.keyManager=i??null}externalDb;db=null;initialized=!1;keyManager=null;async initialize(){if(!this.initialized){if(this.externalDb)this.db=this.externalDb;else{let t=p();await t.initialize(),this.db=t.getDatabase()}this.ensureTable(),this.initialized=!0}}getDatabase(){return this.db}getKeyManager(){return this.keyManager}ensureTable(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
3
3
  CREATE TABLE IF NOT EXISTS witness_chain (
4
4
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5
5
  prev_hash TEXT NOT NULL, action_hash TEXT NOT NULL, action_type TEXT NOT NULL,
@@ -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{a as x}from"./chunk-UU2Q6XWF.js";import{a as D}from"./chunk-2KTRRSKD.js";import{c as _}from"./chunk-KEC5FBAW.js";import{k as w,o as I}from"./chunk-Q24OJX44.js";import{b as f,d as U}from"./chunk-QNW335PD.js";import{a as g,c as q}from"./chunk-2TDWCXZ6.js";import{a as v}from"./chunk-4AWJ5PE4.js";import{randomUUID as Q}from"crypto";I();U();q();var F={alpha:.1,minOutcomes:10,weightFloor:.2,weightCeiling:2},p=class{records=new Map;config;constructor(e){this.config={...F,...e}}recordOutcome(e,t,o){let{alpha:i,minOutcomes:r,weightFloor:s,weightCeiling:n}=this.config,c=this.records.get(e),d=t?1:0,a=Math.max(0,Math.min(1,o)),l,u;c?(l=i*d+(1-i)*c.emaAccuracy,u=i*a+(1-i)*c.emaQuality):(l=d,u=a);let h=(c?.totalOutcomes??0)+1,R;h>=r?R=Math.max(s,Math.min(n,l*2)):R=1;let k={agentId:e,emaAccuracy:l,emaQuality:u,calibratedWeight:R,totalOutcomes:h,lastUpdated:new Date};return this.records.set(e,k),k}getCalibration(e){return this.records.get(e)??null}getCalibratedWeight(e){let t=this.records.get(e);return!t||t.totalOutcomes<this.config.minOutcomes?1:t.calibratedWeight}getAllCalibrations(){return Array.from(this.records.values())}reset(e){e!==void 0?this.records.delete(e):this.records.clear()}serialize(){let e={};for(let[t,o]of this.records)e[t]={...o};return e}deserialize(e){this.records.clear();for(let[t,o]of Object.entries(e))this.records.set(t,{...o,lastUpdated:new Date(o.lastUpdated)})}};var P={escalateAfterFailures:2,deEscalateAfterSuccesses:5,maxTier:"opus",minTier:"haiku"},A=["booster","haiku","sonnet","opus"];function y(m){return A.indexOf(m)}var b=class{config;states=new Map;constructor(e){this.config={...P,...e}}recordOutcome(e,t,o){let i=this.states.get(e);i||(i={agentId:e,currentTier:o,baseTier:o,consecutiveFailures:0,consecutiveSuccesses:0,escalationCount:0,deEscalationCount:0,lastAction:"none",lastActionTimestamp:new Date},this.states.set(e,i));let r=i.currentTier;if(t){if(i.consecutiveSuccesses++,i.consecutiveFailures=0,i.consecutiveSuccesses>=this.config.deEscalateAfterSuccesses){let s=y(i.currentTier),n=y(this.config.minTier);if(s>n)return i.currentTier=A[s-1],i.deEscalationCount++,i.consecutiveSuccesses=0,i.lastAction="de-escalate",i.lastActionTimestamp=new Date,{action:"de-escalate",previousTier:r,newTier:i.currentTier}}}else if(i.consecutiveFailures++,i.consecutiveSuccesses=0,i.consecutiveFailures>=this.config.escalateAfterFailures){let s=y(i.currentTier),n=y(this.config.maxTier);if(s<n)return i.currentTier=A[s+1],i.escalationCount++,i.consecutiveFailures=0,i.lastAction="escalate",i.lastActionTimestamp=new Date,{action:"escalate",previousTier:r,newTier:i.currentTier}}return{action:"none",previousTier:r,newTier:i.currentTier}}getCurrentTier(e){return this.states.get(e)?.currentTier??null}getState(e){return this.states.get(e)??null}getAllStates(){return Array.from(this.states.values())}reset(e){e?this.states.delete(e):this.states.clear()}};var T={booster:{avgInputTokens:0,avgOutputTokens:0,costPerTask:0},haiku:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.0035},sonnet:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.021},opus:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.105}},S=["booster","haiku","sonnet","opus"],E=T.opus.costPerTask,N={qualityWeight:.6,costWeight:.4,budgetPerHourUsd:0,budgetPerDayUsd:0,minQualityThreshold:.5,enabled:!0},L=.15,C=class{config;costTracker;tierQualityEstimates=new Map;tierOutcomeCounts=new Map;constructor(e,t){let o={...N,...t};o.qualityWeight=Math.max(0,Math.min(1,o.qualityWeight)),o.costWeight=Math.max(0,Math.min(1,o.costWeight)),o.minQualityThreshold=Math.max(0,Math.min(1,o.minQualityThreshold)),o.budgetPerHourUsd=Math.max(0,o.budgetPerHourUsd),o.budgetPerDayUsd=Math.max(0,o.budgetPerDayUsd);let i=o.qualityWeight+o.costWeight;i>0&&i!==1&&(o.qualityWeight/=i,o.costWeight/=i),this.config=o,this.costTracker=e,this.tierQualityEstimates.set("booster",.3),this.tierQualityEstimates.set("haiku",.55),this.tierQualityEstimates.set("sonnet",.75),this.tierQualityEstimates.set("opus",.9)}scoreTiers(e){let t=S.map(o=>{let i=this.getQualityEstimate(o,e),r=T[o].costPerTask,s=r>0?i/r:i>0?1/0:0,n=E>0?1-r/E:1,c=this.config.qualityWeight*i+this.config.costWeight*n;return{tier:o,qualityScore:i,estimatedCostUsd:r,qualityPerDollar:s,economicScore:c}});return t.sort((o,i)=>i.economicScore-o.economicScore),t}selectTier(e){let t=this.scoreTiers(e);for(let r of t)if(!(r.qualityScore<this.config.minQualityThreshold)&&!this.wouldExceedBudget(r.tier))return{tier:r.tier,reason:`Best economic score (${r.economicScore.toFixed(3)}): quality=${r.qualityScore.toFixed(2)}, cost=$${r.estimatedCostUsd.toFixed(4)}`,scores:t};let o=t.filter(r=>r.qualityScore>=this.config.minQualityThreshold);if(o.length>0){let r=[...o].sort((s,n)=>s.estimatedCostUsd-n.estimatedCostUsd)[0];return{tier:r.tier,reason:`Budget constrained fallback to ${r.tier}`,scores:t}}let i=[...t].sort((r,s)=>s.qualityScore-r.qualityScore)[0];return{tier:i.tier,reason:`No tier meets quality threshold ${this.config.minQualityThreshold}; using best quality: ${i.tier}`,scores:t}}wouldExceedBudget(e){let t=T[e].costPerTask;if(t===0)return!1;let o=this.costTracker.getCurrentCost("hour"),i=this.costTracker.getCurrentCost("day");return this.config.budgetPerHourUsd>0&&o+t>this.config.budgetPerHourUsd||this.config.budgetPerDayUsd>0&&i+t>this.config.budgetPerDayUsd}updateFromOutcome(e,t){let o=e.outcome.qualityScore,i=this.tierQualityEstimates.get(t)??.5,r=this.tierOutcomeCounts.get(t)??0,s=r<5?.4:L,n=i*(1-s)+o*s;this.tierQualityEstimates.set(t,n),this.tierOutcomeCounts.set(t,r+1)}getEconomicReport(){let e=this.scoreTiers(.5),t=this.costTracker.getCurrentCost("hour"),o=this.costTracker.getCurrentCost("day"),i={hourly:this.config.budgetPerHourUsd>0?Math.max(0,this.config.budgetPerHourUsd-t):null,daily:this.config.budgetPerDayUsd>0?Math.max(0,this.config.budgetPerDayUsd-o):null},r=null,s=[...e].sort((a,l)=>l.qualityPerDollar-a.qualityPerDollar),n=s.find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar)),c=[...s].reverse().find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar));if(n&&c&&n.tier!==c.tier){let a=c.estimatedCostUsd-n.estimatedCostUsd;a>0&&(r={usd:a,description:`Switch from ${c.tier} ($${c.estimatedCostUsd.toFixed(4)}/task) to ${n.tier} ($${n.estimatedCostUsd.toFixed(4)}/task) for comparable tasks to save ~$${a.toFixed(4)}/task`})}let d=this.generateRecommendation(e,i);return{tierEfficiency:e,currentHourlyCostUsd:t,currentDailyCostUsd:o,budgetRemaining:i,recommendation:d,savingsOpportunity:r}}computeCostAdjustedReward(e,t,o){let i=T[t].costPerTask;if(E===0)return e;let r=i/E,s=Math.max(0,o-this.config.minQualityThreshold),n=r*(1-s),c=e-n*this.config.costWeight;return Math.max(-1,Math.min(1,c))}serializeEstimates(){let e={};for(let t of S)e[t]={quality:this.tierQualityEstimates.get(t)??.5,count:this.tierOutcomeCounts.get(t)??0};return e}deserializeEstimates(e){for(let t of S)e[t]&&(this.tierQualityEstimates.set(t,e[t].quality),this.tierOutcomeCounts.set(t,e[t].count))}getConfig(){return{...this.config}}getQualityEstimate(e,t){let o=this.tierQualityEstimates.get(e)??.5,i=e==="booster"?t*.4:e==="haiku"?t*.2:0;return Math.max(0,Math.min(1,o-i))}generateRecommendation(e,t){if(t.hourly!==null&&t.hourly<.01)return"Hourly budget nearly exhausted. Consider increasing budget or routing to cheaper tiers.";if(t.daily!==null&&t.daily<.1)return"Daily budget nearly exhausted. Only critical tasks should use expensive tiers.";let o=e[0];return o?`Most cost-efficient tier: ${o.tier} (score=${o.economicScore.toFixed(3)}, quality=${o.qualityScore.toFixed(2)})`:"No economic data available yet."}};var O=class{outcomes=[];maxOutcomes;constructor(e=1e4){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getByAgent(e,t=100){return this.outcomes.filter(o=>o.usedAgent===e).slice(-t)}getAll(e=1e3){return this.outcomes.slice(-e)}getRecentOverrides(e=50){return this.outcomes.filter(t=>!t.followedRecommendation).slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},M=class m{static schemaMigrated=!1;outcomeStore;router=null;db=null;calibrator=null;escalationTracker=null;economicModel=null;economicPersistCounter=0;static ECONOMIC_PERSIST_INTERVAL=10;persistCount=0;maxOutcomes;static RETENTION_CLEANUP_INTERVAL=100;constructor(e=1e4,t){this.maxOutcomes=e,this.outcomeStore=new O(e),t?.enableEMACalibration&&this.enableCalibration(),t?.enableAutoEscalation&&this.enableAutoEscalation()}async initialize(){try{this.db=w(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb(),this.loadCalibratorState()}catch(e){console.warn("[RoutingFeedbackCollector] DB init failed, using memory-only:",g(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.3");process.exit(0)}
2
+ import{a as x}from"./chunk-7YYTTWGY.js";import{a as D}from"./chunk-OX4R55T3.js";import{c as _}from"./chunk-DY5KEOHX.js";import{k as w,o as I}from"./chunk-USFZ4IJD.js";import{b as f,d as U}from"./chunk-KTRB3L53.js";import{a as g,c as q}from"./chunk-3LRK7PYN.js";import{a as v}from"./chunk-CAMEFWRK.js";import{randomUUID as Q}from"crypto";I();U();q();var F={alpha:.1,minOutcomes:10,weightFloor:.2,weightCeiling:2},p=class{records=new Map;config;constructor(e){this.config={...F,...e}}recordOutcome(e,t,o){let{alpha:i,minOutcomes:r,weightFloor:s,weightCeiling:n}=this.config,c=this.records.get(e),d=t?1:0,a=Math.max(0,Math.min(1,o)),l,u;c?(l=i*d+(1-i)*c.emaAccuracy,u=i*a+(1-i)*c.emaQuality):(l=d,u=a);let h=(c?.totalOutcomes??0)+1,R;h>=r?R=Math.max(s,Math.min(n,l*2)):R=1;let k={agentId:e,emaAccuracy:l,emaQuality:u,calibratedWeight:R,totalOutcomes:h,lastUpdated:new Date};return this.records.set(e,k),k}getCalibration(e){return this.records.get(e)??null}getCalibratedWeight(e){let t=this.records.get(e);return!t||t.totalOutcomes<this.config.minOutcomes?1:t.calibratedWeight}getAllCalibrations(){return Array.from(this.records.values())}reset(e){e!==void 0?this.records.delete(e):this.records.clear()}serialize(){let e={};for(let[t,o]of this.records)e[t]={...o};return e}deserialize(e){this.records.clear();for(let[t,o]of Object.entries(e))this.records.set(t,{...o,lastUpdated:new Date(o.lastUpdated)})}};var P={escalateAfterFailures:2,deEscalateAfterSuccesses:5,maxTier:"opus",minTier:"haiku"},A=["booster","haiku","sonnet","opus"];function y(m){return A.indexOf(m)}var b=class{config;states=new Map;constructor(e){this.config={...P,...e}}recordOutcome(e,t,o){let i=this.states.get(e);i||(i={agentId:e,currentTier:o,baseTier:o,consecutiveFailures:0,consecutiveSuccesses:0,escalationCount:0,deEscalationCount:0,lastAction:"none",lastActionTimestamp:new Date},this.states.set(e,i));let r=i.currentTier;if(t){if(i.consecutiveSuccesses++,i.consecutiveFailures=0,i.consecutiveSuccesses>=this.config.deEscalateAfterSuccesses){let s=y(i.currentTier),n=y(this.config.minTier);if(s>n)return i.currentTier=A[s-1],i.deEscalationCount++,i.consecutiveSuccesses=0,i.lastAction="de-escalate",i.lastActionTimestamp=new Date,{action:"de-escalate",previousTier:r,newTier:i.currentTier}}}else if(i.consecutiveFailures++,i.consecutiveSuccesses=0,i.consecutiveFailures>=this.config.escalateAfterFailures){let s=y(i.currentTier),n=y(this.config.maxTier);if(s<n)return i.currentTier=A[s+1],i.escalationCount++,i.consecutiveFailures=0,i.lastAction="escalate",i.lastActionTimestamp=new Date,{action:"escalate",previousTier:r,newTier:i.currentTier}}return{action:"none",previousTier:r,newTier:i.currentTier}}getCurrentTier(e){return this.states.get(e)?.currentTier??null}getState(e){return this.states.get(e)??null}getAllStates(){return Array.from(this.states.values())}reset(e){e?this.states.delete(e):this.states.clear()}};var T={booster:{avgInputTokens:0,avgOutputTokens:0,costPerTask:0},haiku:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.0035},sonnet:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.021},opus:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.105}},S=["booster","haiku","sonnet","opus"],E=T.opus.costPerTask,N={qualityWeight:.6,costWeight:.4,budgetPerHourUsd:0,budgetPerDayUsd:0,minQualityThreshold:.5,enabled:!0},L=.15,C=class{config;costTracker;tierQualityEstimates=new Map;tierOutcomeCounts=new Map;constructor(e,t){let o={...N,...t};o.qualityWeight=Math.max(0,Math.min(1,o.qualityWeight)),o.costWeight=Math.max(0,Math.min(1,o.costWeight)),o.minQualityThreshold=Math.max(0,Math.min(1,o.minQualityThreshold)),o.budgetPerHourUsd=Math.max(0,o.budgetPerHourUsd),o.budgetPerDayUsd=Math.max(0,o.budgetPerDayUsd);let i=o.qualityWeight+o.costWeight;i>0&&i!==1&&(o.qualityWeight/=i,o.costWeight/=i),this.config=o,this.costTracker=e,this.tierQualityEstimates.set("booster",.3),this.tierQualityEstimates.set("haiku",.55),this.tierQualityEstimates.set("sonnet",.75),this.tierQualityEstimates.set("opus",.9)}scoreTiers(e){let t=S.map(o=>{let i=this.getQualityEstimate(o,e),r=T[o].costPerTask,s=r>0?i/r:i>0?1/0:0,n=E>0?1-r/E:1,c=this.config.qualityWeight*i+this.config.costWeight*n;return{tier:o,qualityScore:i,estimatedCostUsd:r,qualityPerDollar:s,economicScore:c}});return t.sort((o,i)=>i.economicScore-o.economicScore),t}selectTier(e){let t=this.scoreTiers(e);for(let r of t)if(!(r.qualityScore<this.config.minQualityThreshold)&&!this.wouldExceedBudget(r.tier))return{tier:r.tier,reason:`Best economic score (${r.economicScore.toFixed(3)}): quality=${r.qualityScore.toFixed(2)}, cost=$${r.estimatedCostUsd.toFixed(4)}`,scores:t};let o=t.filter(r=>r.qualityScore>=this.config.minQualityThreshold);if(o.length>0){let r=[...o].sort((s,n)=>s.estimatedCostUsd-n.estimatedCostUsd)[0];return{tier:r.tier,reason:`Budget constrained fallback to ${r.tier}`,scores:t}}let i=[...t].sort((r,s)=>s.qualityScore-r.qualityScore)[0];return{tier:i.tier,reason:`No tier meets quality threshold ${this.config.minQualityThreshold}; using best quality: ${i.tier}`,scores:t}}wouldExceedBudget(e){let t=T[e].costPerTask;if(t===0)return!1;let o=this.costTracker.getCurrentCost("hour"),i=this.costTracker.getCurrentCost("day");return this.config.budgetPerHourUsd>0&&o+t>this.config.budgetPerHourUsd||this.config.budgetPerDayUsd>0&&i+t>this.config.budgetPerDayUsd}updateFromOutcome(e,t){let o=e.outcome.qualityScore,i=this.tierQualityEstimates.get(t)??.5,r=this.tierOutcomeCounts.get(t)??0,s=r<5?.4:L,n=i*(1-s)+o*s;this.tierQualityEstimates.set(t,n),this.tierOutcomeCounts.set(t,r+1)}getEconomicReport(){let e=this.scoreTiers(.5),t=this.costTracker.getCurrentCost("hour"),o=this.costTracker.getCurrentCost("day"),i={hourly:this.config.budgetPerHourUsd>0?Math.max(0,this.config.budgetPerHourUsd-t):null,daily:this.config.budgetPerDayUsd>0?Math.max(0,this.config.budgetPerDayUsd-o):null},r=null,s=[...e].sort((a,l)=>l.qualityPerDollar-a.qualityPerDollar),n=s.find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar)),c=[...s].reverse().find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar));if(n&&c&&n.tier!==c.tier){let a=c.estimatedCostUsd-n.estimatedCostUsd;a>0&&(r={usd:a,description:`Switch from ${c.tier} ($${c.estimatedCostUsd.toFixed(4)}/task) to ${n.tier} ($${n.estimatedCostUsd.toFixed(4)}/task) for comparable tasks to save ~$${a.toFixed(4)}/task`})}let d=this.generateRecommendation(e,i);return{tierEfficiency:e,currentHourlyCostUsd:t,currentDailyCostUsd:o,budgetRemaining:i,recommendation:d,savingsOpportunity:r}}computeCostAdjustedReward(e,t,o){let i=T[t].costPerTask;if(E===0)return e;let r=i/E,s=Math.max(0,o-this.config.minQualityThreshold),n=r*(1-s),c=e-n*this.config.costWeight;return Math.max(-1,Math.min(1,c))}serializeEstimates(){let e={};for(let t of S)e[t]={quality:this.tierQualityEstimates.get(t)??.5,count:this.tierOutcomeCounts.get(t)??0};return e}deserializeEstimates(e){for(let t of S)e[t]&&(this.tierQualityEstimates.set(t,e[t].quality),this.tierOutcomeCounts.set(t,e[t].count))}getConfig(){return{...this.config}}getQualityEstimate(e,t){let o=this.tierQualityEstimates.get(e)??.5,i=e==="booster"?t*.4:e==="haiku"?t*.2:0;return Math.max(0,Math.min(1,o-i))}generateRecommendation(e,t){if(t.hourly!==null&&t.hourly<.01)return"Hourly budget nearly exhausted. Consider increasing budget or routing to cheaper tiers.";if(t.daily!==null&&t.daily<.1)return"Daily budget nearly exhausted. Only critical tasks should use expensive tiers.";let o=e[0];return o?`Most cost-efficient tier: ${o.tier} (score=${o.economicScore.toFixed(3)}, quality=${o.qualityScore.toFixed(2)})`:"No economic data available yet."}};var O=class{outcomes=[];maxOutcomes;constructor(e=1e4){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getByAgent(e,t=100){return this.outcomes.filter(o=>o.usedAgent===e).slice(-t)}getAll(e=1e3){return this.outcomes.slice(-e)}getRecentOverrides(e=50){return this.outcomes.filter(t=>!t.followedRecommendation).slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},M=class m{static schemaMigrated=!1;outcomeStore;router=null;db=null;calibrator=null;escalationTracker=null;economicModel=null;economicPersistCounter=0;static ECONOMIC_PERSIST_INTERVAL=10;persistCount=0;maxOutcomes;static RETENTION_CLEANUP_INTERVAL=100;constructor(e=1e4,t){this.maxOutcomes=e,this.outcomeStore=new O(e),t?.enableEMACalibration&&this.enableCalibration(),t?.enableAutoEscalation&&this.enableAutoEscalation()}async initialize(){try{this.db=w(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb(),this.loadCalibratorState()}catch(e){console.warn("[RoutingFeedbackCollector] DB init failed, using memory-only:",g(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
3
3
  SELECT * FROM routing_outcomes ORDER BY created_at DESC LIMIT ?
4
4
  `).all(this.maxOutcomes);for(let o of t.reverse()){let i={id:o.id,task:f(o.task_json),decision:f(o.decision_json),usedAgent:o.used_agent,followedRecommendation:!!o.followed_recommendation,outcome:{success:!!o.success,qualityScore:o.quality_score,durationMs:o.duration_ms,error:o.error||void 0},timestamp:new Date(o.created_at),advisorConsultation:o.advisor_consultation_json?f(o.advisor_consultation_json):void 0};this.outcomeStore.add(i)}t.length>0&&console.log(`[RoutingFeedbackCollector] Loaded ${t.length} outcomes from DB`)}persistOutcome(e){if(this.db)try{let t=this.db.getDatabase();if(!m.schemaMigrated){for(let r of["ALTER TABLE routing_outcomes ADD COLUMN model_tier TEXT","ALTER TABLE routing_outcomes ADD COLUMN advisor_consultation_json TEXT"])try{t.prepare(r).run()}catch{}x(t),m.schemaMigrated=!0}let o=this.inferTier(e.usedAgent),i=e.advisorConsultation?JSON.stringify(e.advisorConsultation):null;t.prepare(`
5
5
  INSERT OR REPLACE INTO routing_outcomes (
@@ -11,4 +11,4 @@ import{a as x}from"./chunk-UU2Q6XWF.js";import{a as D}from"./chunk-2KTRRSKD.js";
11
11
  DELETE FROM routing_outcomes WHERE id NOT IN (
12
12
  SELECT id FROM routing_outcomes ORDER BY created_at DESC LIMIT ?
13
13
  )
14
- `).run(t)}catch(t){console.warn("[RoutingFeedbackCollector] Retention cleanup failed:",g(t))}}loadCalibratorState(){if(!(!this.db||!this.calibrator))try{let t=this.db.getDatabase().prepare("SELECT value FROM kv_store WHERE key = 'routing:ema_calibrator_state'").get();if(t){let o=f(t.value);o&&typeof o=="object"&&(this.calibrator.deserialize(o),console.log("[RoutingFeedbackCollector] Loaded EMA calibrator state from DB"))}}catch(e){console.warn("[RoutingFeedbackCollector] Failed to load calibrator state:",g(e))}}persistCalibratorState(){if(!(!this.db||!this.calibrator))try{let e=this.db.getDatabase(),t=JSON.stringify(this.calibrator.serialize());e.prepare("INSERT OR REPLACE INTO kv_store (key, value, updated_at) VALUES (?, ?, datetime('now'))").run("routing:ema_calibrator_state",t)}catch(e){console.warn("[RoutingFeedbackCollector] Failed to persist calibrator state:",g(e))}}loadEconomicState(){if(!(!this.db||!this.economicModel))try{let t=this.db.getDatabase().prepare("SELECT value FROM kv_store WHERE key = 'routing:economic_quality_estimates'").get();if(t){let o=f(t.value);o&&typeof o=="object"&&(this.economicModel.deserializeEstimates(o),console.log("[RoutingFeedbackCollector] Loaded economic quality estimates from DB"))}}catch(e){console.warn("[RoutingFeedbackCollector] Failed to load economic state:",g(e))}}persistEconomicState(){if(!(!this.db||!this.economicModel))try{let e=this.db.getDatabase(),t=JSON.stringify(this.economicModel.serializeEstimates());e.prepare("INSERT OR REPLACE INTO kv_store (key, value, updated_at) VALUES (?, ?, datetime('now'))").run("routing:economic_quality_estimates",t)}catch(e){console.warn("[RoutingFeedbackCollector] Failed to persist economic state:",g(e))}}connectRouter(e){this.router=e}enableCalibration(e){this.calibrator=new p(e)}getCalibratedWeight(e){return this.calibrator?.getCalibratedWeight(e)??1}enableAutoEscalation(e){this.escalationTracker=new b(e)}getEscalationState(e){return this.escalationTracker?.getState(e)??null}enableEconomicRouting(e,t){let o=t??_();this.economicModel=new C(o,e),this.loadEconomicState()}getEconomicReport(){return this.economicModel?.getEconomicReport()??null}getEconomicScore(e){return this.economicModel?.scoreTiers(e)??null}recordOutcome(e,t,o,i,r){let s=r;s||(s=this.loadAdvisorConsultationSidecar(e));let n={id:`outcome-${Date.now()}-${Q().slice(0,8)}`,task:e,decision:t,usedAgent:o,followedRecommendation:o===t.recommended,outcome:i,timestamp:new Date,advisorConsultation:s};if(this.outcomeStore.add(n),this.persistOutcome(n),this.router&&this.router.updateAgentPerformance(o,i.success,i.qualityScore,i.durationMs),this.calibrator&&(this.calibrator.recordOutcome(o,i.success,i.qualityScore),this.persistCount%10===0&&this.persistCalibratorState()),this.escalationTracker){let c=t.recommended===o?"sonnet":"haiku",d=this.escalationTracker.recordOutcome(o,i.success,c);d.action!=="none"&&console.log(`[RoutingFeedbackCollector] Agent "${o}" ${d.action}d: ${d.previousTier} \u2192 ${d.newTier}`)}if(this.economicModel){let c=this.inferTier(o);this.economicModel.updateFromOutcome(n,c),this.economicPersistCounter++,this.economicPersistCounter%m.ECONOMIC_PERSIST_INTERVAL===0&&this.persistEconomicState()}return n}getAgentMetrics(e){let t=this.outcomeStore.getByAgent(e);if(t.length===0)return null;let o=t.filter(u=>u.outcome.success).length,i=t.reduce((u,h)=>u+h.outcome.durationMs,0),r=t.reduce((u,h)=>u+h.outcome.qualityScore,0),s=t.filter(u=>u.decision.recommended!==u.usedAgent&&u.decision.recommended===e).length,n=t.filter(u=>u.decision.recommended!==u.usedAgent&&u.usedAgent===e).length,c=t.slice(-10),d=c.filter(u=>u.outcome.success).length/c.length,a=o/t.length,l;return d>a+.1?l="improving":d<a-.1?l="declining":l="stable",{agentId:e,totalTasks:t.length,successfulTasks:o,successRate:o/t.length,avgQualityScore:r/t.length,avgDurationMs:i/t.length,overriddenCount:s,selectedOverOthersCount:n,trend:l,updatedAt:new Date}}getAllAgentMetrics(){let e=[];for(let t of D){let o=this.getAgentMetrics(t.id);o&&e.push(o)}return e.sort((t,o)=>o.successRate-t.successRate)}analyzeRoutingAccuracy(){let e=this.outcomeStore.getAll();if(e.length===0)return{totalOutcomes:0,followedRecommendations:0,overrideRate:0,recommendationSuccessRate:0,overrideSuccessRate:0,confidenceCorrelation:0};let t=e.filter(n=>n.followedRecommendation),o=e.filter(n=>!n.followedRecommendation),i=t.filter(n=>n.outcome.success).length,r=o.filter(n=>n.outcome.success).length,s=this.calculateConfidenceCorrelation(e);return{totalOutcomes:e.length,followedRecommendations:t.length,overrideRate:o.length/e.length,recommendationSuccessRate:t.length>0?i/t.length:0,overrideSuccessRate:o.length>0?r/o.length:0,confidenceCorrelation:s}}calculateConfidenceCorrelation(e){if(e.length<2)return 0;let t=e.map(a=>a.decision.confidence),o=e.map(a=>a.outcome.success?1:0),i=t.reduce((a,l)=>a+l,0)/t.length,r=o.reduce((a,l)=>a+l,0)/o.length,s=0,n=0,c=0;for(let a=0;a<e.length;a++){let l=t[a]-i,u=o[a]-r;s+=l*u,n+=l*l,c+=u*u}let d=Math.sqrt(n*c);return d===0?0:s/d}getImprovementRecommendations(){let e=[],t=this.analyzeRoutingAccuracy();if(t.totalOutcomes<50)return e.push("Collect more routing outcomes for reliable analysis (at least 50)"),e;t.overrideRate>.3&&t.overrideSuccessRate>t.recommendationSuccessRate&&e.push("Users are frequently overriding recommendations with better results. Consider adjusting routing weights or updating agent capabilities."),t.confidenceCorrelation<.3&&e.push("Low correlation between confidence and success. Consider improving semantic matching or adjusting weight distribution.");let o=this.getAllAgentMetrics(),i=o.filter(s=>s.successRate<.5&&s.totalTasks>=10);i.length>0&&e.push(`Agents with low success rates: ${i.map(s=>s.agentId).join(", ")}. Consider reviewing their capability mappings.`);let r=o.filter(s=>s.trend==="declining"&&s.totalTasks>=10);return r.length>0&&e.push(`Agents with declining performance: ${r.map(s=>s.agentId).join(", ")}. Monitor for potential issues.`),e.length===0&&e.push("Routing performance is healthy. Continue collecting feedback."),e}exportOutcomes(){return this.outcomeStore.getAll()}importOutcomes(e){for(let t of e)this.outcomeStore.add(t)}getStats(){let e=this.outcomeStore.getAll(),t=new Set(e.map(o=>o.usedAgent));return{totalOutcomes:this.outcomeStore.size,uniqueAgentsUsed:t.size,recentOverrides:this.outcomeStore.getRecentOverrides().length}}clear(){this.outcomeStore.clear()}};function ne(m=1e4,e){return new M(m,e)}export{M as a,ne as b};
14
+ `).run(t)}catch(t){console.warn("[RoutingFeedbackCollector] Retention cleanup failed:",g(t))}}loadCalibratorState(){if(!(!this.db||!this.calibrator))try{let t=this.db.getDatabase().prepare("SELECT value FROM kv_store WHERE key = 'routing:ema_calibrator_state'").get();if(t){let o=f(t.value);o&&typeof o=="object"&&(this.calibrator.deserialize(o),console.log("[RoutingFeedbackCollector] Loaded EMA calibrator state from DB"))}}catch(e){console.warn("[RoutingFeedbackCollector] Failed to load calibrator state:",g(e))}}persistCalibratorState(){if(!(!this.db||!this.calibrator))try{let e=this.db.getDatabase(),t=JSON.stringify(this.calibrator.serialize());e.prepare("INSERT OR REPLACE INTO kv_store (key, value, updated_at) VALUES (?, ?, datetime('now'))").run("routing:ema_calibrator_state",t)}catch(e){console.warn("[RoutingFeedbackCollector] Failed to persist calibrator state:",g(e))}}loadEconomicState(){if(!(!this.db||!this.economicModel))try{let t=this.db.getDatabase().prepare("SELECT value FROM kv_store WHERE key = 'routing:economic_quality_estimates'").get();if(t){let o=f(t.value);o&&typeof o=="object"&&(this.economicModel.deserializeEstimates(o),console.log("[RoutingFeedbackCollector] Loaded economic quality estimates from DB"))}}catch(e){console.warn("[RoutingFeedbackCollector] Failed to load economic state:",g(e))}}persistEconomicState(){if(!(!this.db||!this.economicModel))try{let e=this.db.getDatabase(),t=JSON.stringify(this.economicModel.serializeEstimates());e.prepare("INSERT OR REPLACE INTO kv_store (key, value, updated_at) VALUES (?, ?, datetime('now'))").run("routing:economic_quality_estimates",t)}catch(e){console.warn("[RoutingFeedbackCollector] Failed to persist economic state:",g(e))}}connectRouter(e){this.router=e}enableCalibration(e){this.calibrator=new p(e)}getCalibratedWeight(e){return this.calibrator?.getCalibratedWeight(e)??1}enableAutoEscalation(e){this.escalationTracker=new b(e)}getEscalationState(e){return this.escalationTracker?.getState(e)??null}enableEconomicRouting(e,t){let o=t??_();this.economicModel=new C(o,e),this.loadEconomicState()}getEconomicReport(){return this.economicModel?.getEconomicReport()??null}getEconomicScore(e){return this.economicModel?.scoreTiers(e)??null}recordOutcome(e,t,o,i,r){let s=r;s||(s=this.loadAdvisorConsultationSidecar(e));let n={id:`outcome-${Date.now()}-${Q().slice(0,8)}`,task:e,decision:t,usedAgent:o,followedRecommendation:o===t.recommended,outcome:i,timestamp:new Date,advisorConsultation:s};if(this.outcomeStore.add(n),this.persistOutcome(n),this.router&&this.router.updateAgentPerformance(o,i.success,i.qualityScore,i.durationMs),this.calibrator&&(this.calibrator.recordOutcome(o,i.success,i.qualityScore),this.persistCount%10===0&&this.persistCalibratorState()),this.escalationTracker){let c=t.recommended===o?"sonnet":"haiku",d=this.escalationTracker.recordOutcome(o,i.success,c);d.action!=="none"&&console.log(`[RoutingFeedbackCollector] Agent "${o}" ${d.action}d: ${d.previousTier} \u2192 ${d.newTier}`)}if(this.economicModel){let c=this.inferTier(o);this.economicModel.updateFromOutcome(n,c),this.economicPersistCounter++,this.economicPersistCounter%m.ECONOMIC_PERSIST_INTERVAL===0&&this.persistEconomicState()}return n}getAgentMetrics(e){let t=this.outcomeStore.getByAgent(e);if(t.length===0)return null;let o=t.filter(u=>u.outcome.success).length,i=t.reduce((u,h)=>u+h.outcome.durationMs,0),r=t.reduce((u,h)=>u+h.outcome.qualityScore,0),s=t.filter(u=>u.decision.recommended!==u.usedAgent&&u.decision.recommended===e).length,n=t.filter(u=>u.decision.recommended!==u.usedAgent&&u.usedAgent===e).length,c=t.slice(-10),d=c.filter(u=>u.outcome.success).length/c.length,a=o/t.length,l;return d>a+.1?l="improving":d<a-.1?l="declining":l="stable",{agentId:e,totalTasks:t.length,successfulTasks:o,successRate:o/t.length,avgQualityScore:r/t.length,avgDurationMs:i/t.length,overriddenCount:s,selectedOverOthersCount:n,trend:l,updatedAt:new Date}}getAllAgentMetrics(){let e=[];for(let t of D){let o=this.getAgentMetrics(t.id);o&&e.push(o)}return e.sort((t,o)=>o.successRate-t.successRate)}analyzeRoutingAccuracy(){let e=this.outcomeStore.getAll();if(e.length===0)return{totalOutcomes:0,followedRecommendations:0,overrideRate:0,recommendationSuccessRate:0,overrideSuccessRate:0,confidenceCorrelation:0};let t=e.filter(n=>n.followedRecommendation),o=e.filter(n=>!n.followedRecommendation),i=t.filter(n=>n.outcome.success).length,r=o.filter(n=>n.outcome.success).length,s=this.calculateConfidenceCorrelation(e);return{totalOutcomes:e.length,followedRecommendations:t.length,overrideRate:o.length/e.length,recommendationSuccessRate:t.length>0?i/t.length:0,overrideSuccessRate:o.length>0?r/o.length:0,confidenceCorrelation:s}}calculateConfidenceCorrelation(e){if(e.length<2)return 0;let t=e.map(a=>a.decision.confidence),o=e.map(a=>a.outcome.success?1:0),i=t.reduce((a,l)=>a+l,0)/t.length,r=o.reduce((a,l)=>a+l,0)/o.length,s=0,n=0,c=0;for(let a=0;a<e.length;a++){let l=t[a]-i,u=o[a]-r;s+=l*u,n+=l*l,c+=u*u}let d=Math.sqrt(n*c);return d===0?0:s/d}getImprovementRecommendations(){let e=[],t=this.analyzeRoutingAccuracy();if(t.totalOutcomes<50)return e.push("Collect more routing outcomes for reliable analysis (at least 50)"),e;t.overrideRate>.3&&t.overrideSuccessRate>t.recommendationSuccessRate&&e.push("Users are frequently overriding recommendations with better results. Consider adjusting routing weights or updating agent capabilities."),t.confidenceCorrelation<.3&&e.push("Low correlation between confidence and success. Consider improving semantic matching or adjusting weight distribution.");let o=this.getAllAgentMetrics(),i=o.filter(s=>s.successRate<.5&&s.totalTasks>=10);i.length>0&&e.push(`Agents with low success rates: ${i.map(s=>s.agentId).join(", ")}. Consider reviewing their capability mappings.`);let r=o.filter(s=>s.trend==="declining"&&s.totalTasks>=10);return r.length>0&&e.push(`Agents with declining performance: ${r.map(s=>s.agentId).join(", ")}. Monitor for potential issues.`),e.length===0&&e.push("Routing performance is healthy. Continue collecting feedback."),e}exportOutcomes(){return this.outcomeStore.getAll()}importOutcomes(e){for(let t of e)this.outcomeStore.add(t)}getStats(){let e=this.outcomeStore.getAll(),t=new Set(e.map(o=>o.usedAgent));return{totalOutcomes:this.outcomeStore.size,uniqueAgentsUsed:t.size,recentOverrides:this.outcomeStore.getRecentOverrides().length}}clear(){this.outcomeStore.clear()}};function se(m=1e4,e){return new M(m,e)}export{M as a,se as b};
@@ -0,0 +1,2 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.3");process.exit(0)}
2
+ import{d as D,e as V}from"./chunk-2L73WXA4.js";V();import*as A from"node:fs";import B from"node:module";import*as N from"node:path";import{fileURLToPath as J}from"node:url";var b=D("TreeSitterWASM"),O={python:{wasmFile:"tree-sitter-python.wasm",nodeTypes:{functionDecl:["function_definition"],classDecl:["class_definition"],importDecl:["import_statement","import_from_statement"]}},java:{wasmFile:"tree-sitter-java.wasm",nodeTypes:{functionDecl:["method_declaration","constructor_declaration"],classDecl:["class_declaration","interface_declaration"],importDecl:["import_declaration"]}},csharp:{wasmFile:"tree-sitter-c_sharp.wasm",nodeTypes:{functionDecl:["method_declaration","constructor_declaration"],classDecl:["class_declaration","interface_declaration"],importDecl:["using_directive"]}},rust:{wasmFile:"tree-sitter-rust.wasm",nodeTypes:{functionDecl:["function_item"],classDecl:[],importDecl:["use_declaration"],implBlock:"impl_item",structDecl:"struct_item"}},swift:{wasmFile:"tree-sitter-swift.wasm",nodeTypes:{functionDecl:["function_declaration"],classDecl:["class_declaration"],importDecl:["import_declaration"],structDecl:"struct_declaration",protocolDecl:"protocol_declaration"}}},y=null,g=null,F=0,P=3,w=new Map;function I(i){let e=J(new URL(".",import.meta.url)),t=[N.resolve(e,"..","..","..","assets","grammars",i),N.resolve(e,"..","..","assets","grammars",i),N.resolve(process.cwd(),"assets","grammars",i),N.resolve(e,"..","assets","grammars",i)];for(let n of t)if(A.existsSync(n))return n;throw new Error(`Grammar file ${i} not found. Searched: ${t.join(", ")}`)}async function E(){if(F>=P)throw new Error(`web-tree-sitter failed to initialize after ${P} attempts`);if(!y)return g||(g=(async()=>{try{let i=await import("./web-tree-sitter-2YPGYLWK.js"),e=i.default??i;await(e.Parser?.init??e.init).call(e.Parser??e),y=e,F=0,b.info("web-tree-sitter WASM runtime initialized")}catch(i){F++,g=null;let e=i instanceof Error?i.message:String(i);throw b.warn(`web-tree-sitter WASM init failed (attempt ${F}/${P}): ${e}. `+(F<P?"Will retry on next parse.":"Falling back to regex permanently.")),i}})()),g}async function X(i){let e=w.get(i);if(e)return e;await E();let t=O[i];if(!t)throw new Error(`No WASM grammar config for ${i}`);try{let n=I(t.wasmFile),s=await y.Language.load(n);return w.set(i,s),b.info(`Loaded tree-sitter WASM grammar for ${i}`),s}catch(n){let s=n instanceof Error?n.message:String(n);throw b.warn(`Failed to load WASM grammar for ${i}: ${s}. Falling back to regex parser.`),n}}function u(i,e){let t=[];for(let n=0;n<i.childCount;n++){let s=i.child(n);e.includes(s.type)&&t.push(s)}return t}function h(i,e,t=10){let n=[];function s(r,o){if(!(o>t))for(let a=0;a<r.childCount;a++){let c=r.child(a);e.includes(c.type)&&n.push(c),s(c,o+1)}}return s(i,0),n}function x(i){let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);(n.type==="modifiers"||n.type==="modifier"||n.type==="visibility_modifier")&&e.push(n.text.trim())}return e}function C(i,e){return x(i).some(t=>t.includes(e))}var Y=new Set(["if_statement","if_expression","if_let_statement","while_statement","while_expression","for_statement","for_in_statement","for_expression","enhanced_for_statement","match_expression","switch_statement","switch_expression","case_clause","match_arm","switch_entry","catch_clause","except_clause","catch_block","binary_expression","conditional_expression","ternary_expression"]),q=new Set(["&&","||","and","or"]);function _(i){if(!i)return 1;let e=1;function t(n){if(Y.has(n.type))if(n.type==="binary_expression"){let s=n.childForFieldName("operator");s&&q.has(s.text)&&e++}else e++;for(let s=0;s<n.childCount;s++)t(n.child(s))}return t(i),e}function S(i,e){if(!i)return[];let t=[];for(let n=0;n<i.childCount;n++){let s=i.child(n);switch(e){case"java":if(s.type==="field_declaration"){let r=x(s),o=s.childForFieldName("type")?.text?.trim(),a=s.childForFieldName("declarator"),c=a?.childForFieldName("name")?.text??a?.text?.split(/[=;]/)[0]?.trim()??"";c&&t.push({name:c,type:o||void 0,isPublic:r.some(l=>l.includes("public")),isReadonly:r.some(l=>l.includes("final"))})}break;case"csharp":if(s.type==="field_declaration"||s.type==="property_declaration"){let r=x(s),o=s.childForFieldName("type")?.text?.trim(),a=s.childForFieldName("name")?.text??"";a&&t.push({name:a,type:o||void 0,isPublic:r.some(c=>c.includes("public")),isReadonly:r.some(c=>c.includes("readonly"))})}break;case"rust":if(s.type==="field_declaration"){let r=s.childForFieldName("name")?.text??"",o=s.childForFieldName("type")?.text?.trim(),a=C(s,"pub");r&&t.push({name:r,type:o||void 0,isPublic:a,isReadonly:!1})}break;case"swift":if(s.type==="property_declaration"){let r=L(s),o=s.childForFieldName("name")?.text??"",a=s.childForFieldName("type")?.text?.trim(),c=r.includes("public")||r.includes("open"),l=s.text.includes("let ");o&&t.push({name:o,type:a||void 0,isPublic:c,isReadonly:l})}break;case"python":if(s.type==="expression_statement"){let r=s.child(0);if(r?.type==="assignment"){let o=r.childForFieldName("left");if(o?.type==="attribute"||o?.type==="identifier"){let a=o.text.replace("self.","");t.push({name:a,type:void 0,isPublic:!a.startsWith("_"),isReadonly:!1})}}}break}}return t}function k(i){return i.map(e=>{let t=e.childForFieldName("name")?.text??"",n=e.childForFieldName("parameters"),s=e.childForFieldName("return_type"),r=e.childForFieldName("body"),o=e.text.trimStart().startsWith("async"),a=W(e);return{name:t,parameters:z(n),returnType:s?.text?.trim()||void 0,isAsync:o,isPublic:!t.startsWith("_"),complexity:_(r),decorators:a,genericParams:[],startLine:e.startPosition.row+1,endLine:e.endPosition.row+1}})}function z(i){if(!i)return[];let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n.type==="identifier"){let s=n.text;if(s==="self"||s==="cls")continue;e.push({name:s,type:void 0,isOptional:!1,defaultValue:void 0})}else if(n.type==="typed_parameter"){let s=n.child(0)?.text??"";if(s==="self"||s==="cls")continue;let r=n.childForFieldName("type")?.text?.trim();e.push({name:s,type:r||void 0,isOptional:!1,defaultValue:void 0})}else if(n.type==="default_parameter"||n.type==="typed_default_parameter"){let s=n.childForFieldName("name")?.text??n.child(0)?.text??"";if(s==="self"||s==="cls")continue;let r=n.childForFieldName("type")?.text?.trim(),o=n.childForFieldName("value")?.text?.trim();e.push({name:s,type:r||void 0,isOptional:!0,defaultValue:o||void 0})}else if(n.type==="list_splat_pattern"||n.type==="dictionary_splat_pattern"){let s=n.text;e.push({name:s,type:void 0,isOptional:!0,defaultValue:void 0})}}return e}function W(i){let e=[],t=i.parent;if(!t)return e;if(t.type==="decorated_definition")for(let n=0;n<t.childCount;n++){let s=t.child(n);s.type==="decorator"&&e.push(s.text.trim())}return e}function Q(i){return i.map(e=>{let t=e.childForFieldName("name")?.text??"",n=e.childForFieldName("body"),s=e.childForFieldName("superclasses"),r=[];if(s)for(let l=0;l<s.childCount;l++){let d=s.child(l);d.isNamed&&r.push(d.text)}let o=n?h(n,["function_definition"],2):[],a=k(o),c=W(e);return{name:t,methods:a,properties:S(n,"python"),isPublic:!t.startsWith("_"),implements:[],extends:r[0]||void 0,decorators:c,startLine:e.startPosition.row+1,endLine:e.endPosition.row+1}})}function H(i){return i.map(e=>{if(e.type==="import_from_statement"){let n=e.childForFieldName("module_name")?.text??"",s=[];for(let r=0;r<e.childCount;r++){let o=e.child(r);e.fieldNameForChild(r)==="name"&&o.isNamed&&s.push(o.text)}return{module:n,namedImports:s,isTypeOnly:!1}}return{module:e.childForFieldName("name")?.text??"",namedImports:[],isTypeOnly:!1}})}function T(i){return i.map(e=>{let t=e.childForFieldName("name")?.text??"",n=e.childForFieldName("type"),s=e.childForFieldName("parameters"),r=e.childForFieldName("body"),a=x(e).some(d=>d.includes("public")),c=n?.text?.includes("CompletableFuture")??!1,l=M(e);return{name:t,parameters:K(s),returnType:n?.text==="void"?void 0:n?.text?.trim(),isAsync:c,isPublic:a,complexity:_(r),decorators:l,genericParams:[],startLine:e.startPosition.row+1,endLine:e.endPosition.row+1}})}function K(i){if(!i)return[];let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n.type==="formal_parameter"||n.type==="spread_parameter"){let s=n.childForFieldName("name")?.text??"",r=n.childForFieldName("type")?.text?.trim();e.push({name:s,type:r||void 0,isOptional:!1,defaultValue:void 0})}}return e}function M(i){let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n.type==="modifiers")for(let s=0;s<n.childCount;s++){let r=n.child(s);(r.type==="marker_annotation"||r.type==="annotation")&&e.push(r.text.trim())}}return e}function Z(i){return i.map(e=>{let t=e.childForFieldName("name")?.text??"",n=e.childForFieldName("body"),r=x(e).some(p=>p.includes("public")),o=e.childForFieldName("superclass")?.text,a=e.childForFieldName("interfaces"),c=[];if(a)for(let p=0;p<a.childCount;p++){let f=a.child(p);f.isNamed&&c.push(f.text)}let l=n?u(n,["method_declaration","constructor_declaration"]):[],d=T(l),m=M(e);return{name:t,methods:d,properties:S(n,"java"),isPublic:r,implements:c,extends:o||void 0,decorators:m,startLine:e.startPosition.row+1,endLine:e.endPosition.row+1}})}function ee(i){return i.map(e=>{let t=e.text.replace(/^\s*import\s+(static\s+)?/,"").replace(/;\s*$/,"").trim(),n=t.split("."),s=n[n.length-1];return{module:t,namedImports:s==="*"?[]:[s],isTypeOnly:!1}})}function te(i){return h(i,["method_declaration","constructor_declaration"]).map(t=>{let n=t.childForFieldName("name")?.text??"",s=t.childForFieldName("type"),r=t.childForFieldName("parameters"),o=x(t),a=o.some(d=>d.includes("public")),c=o.some(d=>d.includes("async"))||s?.text?.includes("Task")||!1,l=j(t);return{name:n,parameters:ne(r),returnType:s?.text==="void"?void 0:s?.text?.trim(),isAsync:c,isPublic:a,complexity:_(t.childForFieldName("body")),decorators:l,genericParams:[],startLine:t.startPosition.row+1,endLine:t.endPosition.row+1}})}function ne(i){if(!i)return[];let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n.type==="parameter"){let s=n.childForFieldName("name")?.text??"",r=n.childForFieldName("type")?.text?.trim();e.push({name:s,type:r||void 0,isOptional:r?.endsWith("?")||!1,defaultValue:void 0})}}return e}function j(i){let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);n.type==="attribute_list"&&e.push(n.text.trim())}return e}function se(i){return h(i,["class_declaration","interface_declaration"]).map(t=>{let n=t.childForFieldName("name")?.text??"",s=t.childForFieldName("body"),o=x(t).some(p=>p.includes("public")),a=t.childForFieldName("bases"),c=[];if(a)for(let p=0;p<a.childCount;p++){let f=a.child(p);f.isNamed&&c.push(f.text)}let l=s?u(s,["method_declaration","constructor_declaration"]):[],d=T(l),m=j(t);return{name:n,methods:d,properties:S(s,"csharp"),isPublic:o,implements:c.slice(1),extends:c[0]||void 0,decorators:m,startLine:t.startPosition.row+1,endLine:t.endPosition.row+1}})}function ie(i){return h(i,["using_directive"]).map(t=>({module:t.text.replace(/^\s*using\s+(static\s+)?/,"").replace(/;\s*$/,"").trim(),namedImports:[],isTypeOnly:!1}))}function re(i,e){let t=[],n=u(i,e.nodeTypes.functionDecl);if(t.push(...n.map(U)),e.nodeTypes.implBlock){let s=u(i,[e.nodeTypes.implBlock]);for(let r of s){let o=r.childForFieldName("body");if(o){let a=u(o,e.nodeTypes.functionDecl);t.push(...a.map(U))}}}return t}function U(i){let e=i.childForFieldName("name")?.text??"",t=i.childForFieldName("parameters"),n=i.childForFieldName("return_type"),s=i.childForFieldName("body"),r=C(i,"pub"),o=i.text.trimStart().startsWith("pub async")||i.text.trimStart().startsWith("async"),a=G(i);return{name:e,parameters:oe(t),returnType:n?.text?.trim()||void 0,isAsync:o,isPublic:r,complexity:_(s),decorators:a,genericParams:[],startLine:i.startPosition.row+1,endLine:i.endPosition.row+1}}function oe(i){if(!i)return[];let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n.type==="parameter"){let s=n.childForFieldName("pattern"),r=n.childForFieldName("type"),o=s?.text??"",a=r?.text?.trim();e.push({name:o,type:a||void 0,isOptional:!1,defaultValue:void 0})}else if(n.type==="self_parameter")continue}return e}function G(i){let e=[],t=i.previousNamedSibling;for(;t&&t.type==="attribute_item";)e.unshift(t.text.trim()),t=t.previousNamedSibling;return e}function ae(i){let e=[],t=u(i,["struct_item","enum_item","trait_item"]);for(let n of t){let s=n.childForFieldName("name")?.text??"",r=C(n,"pub"),o=G(n),a=n.childForFieldName("body");e.push({name:s,methods:[],properties:S(a,"rust"),isPublic:r,implements:[],extends:void 0,decorators:o,startLine:n.startPosition.row+1,endLine:n.endPosition.row+1})}return e}function ce(i){return u(i,["use_declaration"]).map(t=>({module:t.childForFieldName("argument")?.text??t.text.replace(/^\s*use\s+/,"").replace(/;\s*$/,"").trim(),namedImports:[],isTypeOnly:!1}))}function $(i){return i.map(e=>{let t="",n=[],s,r=L(e),o=r.includes("public")||r.includes("open"),a=!1;for(let l=0;l<e.childCount;l++){let d=e.child(l);e.fieldNameForChild(l)==="name"&&(d.type==="simple_identifier"?t=d.text:t||(s=d.text)),d.type==="parameter"&&n.push(d),(d.type==="async"||d.text==="async")&&(a=!0)}if(!t){for(let l=0;l<e.childCount;l++)if(e.child(l).type==="simple_identifier"){t=e.child(l).text;break}}let c=null;for(let l=0;l<e.childCount;l++)if(e.child(l).type==="function_body"){c=e.child(l);break}return{name:t,parameters:le(n),returnType:s,isAsync:a,isPublic:o,complexity:_(c),decorators:[],genericParams:[],startLine:e.startPosition.row+1,endLine:e.endPosition.row+1}})}function L(i){let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n.type==="modifiers")for(let s=0;s<n.childCount;s++)e.push(n.child(s).text.trim())}return e}function le(i){return i.map(e=>{let n=e.text.split(":"),s=n[0]?.trim().split(/\s+/)??[],r=s[s.length-1]||"",o=n.slice(1).join(":").trim()||void 0;return{name:r,type:o,isOptional:o?.endsWith("?")||!1,defaultValue:void 0}})}function de(i){return u(i,["class_declaration","struct_declaration","protocol_declaration"]).map(n=>{let s=n.childForFieldName("name"),r=s?.text??"",o=L(n),a=o.includes("public")||o.includes("open"),c=[];for(let p=0;p<n.childCount;p++){let f=n.child(p);f.type==="type_identifier"&&f!==s&&c.push(f.text),(f.type==="inheritance_specifier"||f.type==="user_type")&&c.push(f.text)}let l=n.childForFieldName("body"),d=l?h(l,["function_declaration"],2):[],m=$(d);return{name:r,methods:m,properties:S(l,"swift"),isPublic:a,implements:c.slice(1),extends:c[0]||void 0,decorators:[],startLine:n.startPosition.row+1,endLine:n.endPosition.row+1}})}function ue(i){return u(i,["import_declaration"]).map(t=>{let n="";for(let s=0;s<t.childCount;s++){let r=t.child(s);(r.type==="identifier"||r.type==="simple_identifier")&&(n=r.text)}return{module:n,namedImports:[],isTypeOnly:!1}})}var v=class{language;supportedExtensions;constructor(e,t){this.language=e,this.supportedExtensions=t}async parseFile(e,t){let n=await X(this.language),s=y.Parser??y,r=new s;r.setLanguage(n);let o=r.parse(e),a=o.rootNode;try{return{...this.extractFromAST(a),language:this.language,filePath:t}}finally{o.delete(),r.delete()}}extractFromAST(e){let t=O[this.language];switch(this.language){case"python":{let n=u(e,t.nodeTypes.functionDecl),s=u(e,["decorated_definition"]).map(d=>{for(let m=0;m<d.childCount;m++)if(t.nodeTypes.functionDecl.includes(d.child(m).type))return d.child(m);return null}).filter(Boolean),r=[...n,...s],o=u(e,t.nodeTypes.classDecl),a=u(e,["decorated_definition"]).map(d=>{for(let m=0;m<d.childCount;m++)if(t.nodeTypes.classDecl.includes(d.child(m).type))return d.child(m);return null}).filter(Boolean),c=[...o,...a],l=u(e,t.nodeTypes.importDecl);return{functions:k(r),classes:Q(c),imports:H(l)}}case"java":{let n=h(e,t.nodeTypes.classDecl),s=u(e,t.nodeTypes.importDecl),o=[...u(e,t.nodeTypes.functionDecl)];for(let a of n){let c=a.childForFieldName("body");c&&o.push(...u(c,t.nodeTypes.functionDecl))}return{functions:T(o),classes:Z(n),imports:ee(s)}}case"csharp":return{functions:te(e),classes:se(e),imports:ie(e)};case"rust":return{functions:re(e,t),classes:ae(e),imports:ce(e)};case"swift":{let n=h(e,t.nodeTypes.functionDecl);return{functions:$(n),classes:de(e),imports:ue(e)}}default:return{functions:[],classes:[],imports:[]}}}},me={python:[".py"],java:[".java"],csharp:[".cs"],rust:[".rs"],swift:[".swift"]};function xe(){let i=new Map;for(let[e,t]of Object.entries(me))i.set(e,new v(e,t));return i}function pe(){if(process.env.AQE_PARSER_REGEX_ONLY==="1"||process.env.AQE_PARSER_REGEX_ONLY==="true")return!1;try{let{createRequire:i}=B;return i(import.meta.url).resolve("web-tree-sitter"),I("tree-sitter-python.wasm"),!0}catch{return!1}}var R=new Map;async function Fe(i){if(!pe())return null;try{await E();let e=R.get(i);return e||(e=await y.Language.load(I(i)),R.set(i,e)),{parse:t=>{let n=y.Parser??y,s=new n;s.setLanguage(e);let r=s.parse(t);return s.delete?.(),r}}}catch{return null}}function Ne(){y=null,g=null,F=0,w.clear()}export{v as a,xe as b,pe as c,Fe as d,Ne as e};