agentic-qe 3.9.36 → 3.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (302) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +75 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/cli/bundle.js +5 -5
  5. package/dist/cli/chunks/adapter-WTE6UVGP.js +2 -0
  6. package/dist/cli/chunks/{agent-booster-wasm-L6D36M77.js → agent-booster-wasm-5UDM2PWG.js} +2 -2
  7. package/dist/cli/chunks/{agent-handler-3JNKP4OI.js → agent-handler-JSYER5YC.js} +2 -2
  8. package/dist/cli/chunks/{agent-memory-branch-QBRBX7O4.js → agent-memory-branch-T2SAHI4F.js} +2 -2
  9. package/dist/cli/chunks/aqe-learning-engine-LCLEBU7D.js +2 -0
  10. package/dist/cli/chunks/{audit-M4W43TXQ.js → audit-HIBRVGXG.js} +2 -2
  11. package/dist/cli/chunks/base-73I73HBF.js +2 -0
  12. package/dist/cli/chunks/{hnswlib-node-NN6GB2YD.js → better-sqlite3-Y6GX6CGB.js} +2 -2
  13. package/dist/cli/chunks/{brain-handler-WQN7C55Z.js → brain-handler-N6AWIMXG.js} +3 -3
  14. package/dist/cli/chunks/{branch-enumerator-BOTGLI7M.js → branch-enumerator-VYQGBVEJ.js} +2 -2
  15. package/dist/cli/chunks/{browser-ZFZCR7LP.js → browser-2X4WKZPT.js} +2 -2
  16. package/dist/cli/chunks/browser-workflow-2NSV5O6W.js +2 -0
  17. package/dist/cli/chunks/{chunk-FSDUNGYM.js → chunk-27ACATRH.js} +2 -2
  18. package/dist/cli/chunks/{chunk-SJ3SHZUC.js → chunk-2GL4GH52.js} +4 -4
  19. package/dist/cli/chunks/{chunk-F5IVWV2P.js → chunk-2POXDKUB.js} +1 -1
  20. package/dist/cli/chunks/chunk-3BO7EKGO.js +12 -0
  21. package/dist/cli/chunks/{chunk-BUVY7IGM.js → chunk-3OSCWD7Z.js} +1 -1
  22. package/dist/cli/chunks/{chunk-GW7HWFWQ.js → chunk-3QULDB7K.js} +1 -1
  23. package/dist/cli/chunks/{chunk-PYCYZYIL.js → chunk-3U77XX6J.js} +4 -4
  24. package/dist/cli/chunks/{chunk-EXBJCDFM.js → chunk-4NQ6KANC.js} +2 -2
  25. package/dist/cli/chunks/{chunk-6M44C43I.js → chunk-4UUDFWOP.js} +2 -2
  26. package/dist/cli/chunks/{chunk-FYJE4QLL.js → chunk-4WYGUTSF.js} +2 -2
  27. package/dist/cli/chunks/{chunk-SCBWRKPE.js → chunk-55JPAF56.js} +1 -1
  28. package/dist/cli/chunks/{chunk-TU2PSEDW.js → chunk-5QJDH4Z5.js} +2 -2
  29. package/dist/cli/chunks/{chunk-YMB4YVFX.js → chunk-5RQT7EJP.js} +3 -3
  30. package/dist/cli/chunks/{chunk-X6UGFKHW.js → chunk-5UOV7T36.js} +2 -2
  31. package/dist/cli/chunks/{chunk-KI6RXKP4.js → chunk-66GIKUI2.js} +2 -2
  32. package/dist/cli/chunks/{chunk-BI54GWTK.js → chunk-6F3WJOU2.js} +2 -2
  33. package/dist/cli/chunks/{chunk-OO2JHVMS.js → chunk-6H5MRVJS.js} +3 -3
  34. package/dist/cli/chunks/{chunk-O5JNHH2D.js → chunk-6HCHW5TS.js} +2 -2
  35. package/dist/cli/chunks/{chunk-JD3VV2BD.js → chunk-6MONUYQ5.js} +2 -2
  36. package/dist/cli/chunks/{chunk-RDXIRE2I.js → chunk-7Y54QZKF.js} +2 -2
  37. package/dist/cli/chunks/{chunk-P7IOH7L4.js → chunk-7ZIRDBXH.js} +1 -1
  38. package/dist/cli/chunks/{chunk-AWC7G2D3.js → chunk-AFFYJSW2.js} +2 -2
  39. package/dist/cli/chunks/{chunk-I7BXATQ6.js → chunk-ALCQRJDY.js} +2 -2
  40. package/dist/cli/chunks/{chunk-VENEJ3UI.js → chunk-BQT4J3BD.js} +2 -2
  41. package/dist/cli/chunks/{chunk-5OAAJUGO.js → chunk-BQX5QDU5.js} +1 -1
  42. package/dist/cli/chunks/{chunk-CJQT3MYN.js → chunk-BTIVIWIG.js} +1 -1
  43. package/dist/cli/chunks/{chunk-6M2POFDF.js → chunk-BXCS55GB.js} +1 -1
  44. package/dist/cli/chunks/{chunk-MJJAHA2T.js → chunk-C5QESAYA.js} +1 -1
  45. package/dist/cli/chunks/{chunk-NYU4YD5V.js → chunk-CU4IUJ2K.js} +2 -2
  46. package/dist/cli/chunks/{chunk-LPVRFVSC.js → chunk-DQJJS4AX.js} +2 -2
  47. package/dist/cli/chunks/{chunk-GFMSAL5Y.js → chunk-DQLEZBWV.js} +2 -2
  48. package/dist/cli/chunks/{chunk-5SYH5QMQ.js → chunk-DXV6NRG3.js} +2 -2
  49. package/dist/cli/chunks/{chunk-EAMKH35X.js → chunk-DY7IRNE2.js} +1 -1
  50. package/dist/cli/chunks/{chunk-4R3WXD4U.js → chunk-F363JJUI.js} +1 -1
  51. package/dist/cli/chunks/{chunk-JFDNNXIX.js → chunk-FCSJ7GIZ.js} +2 -2
  52. package/dist/cli/chunks/{chunk-QMUTKI34.js → chunk-FEBXP74Y.js} +1 -1
  53. package/dist/cli/chunks/{chunk-EXUT2LCP.js → chunk-FQ5FT7IE.js} +1 -1
  54. package/dist/cli/chunks/{chunk-MEQ4OPSL.js → chunk-FX4SYT6Y.js} +3 -3
  55. package/dist/cli/chunks/{chunk-ZK6GXL5J.js → chunk-G2HA2O3R.js} +2 -2
  56. package/dist/cli/chunks/{chunk-TCDGJYM2.js → chunk-GPKZ4MMH.js} +1 -1
  57. package/dist/cli/chunks/{chunk-66636UWH.js → chunk-GXCD7GNH.js} +2 -2
  58. package/dist/cli/chunks/{chunk-CAGRQR2U.js → chunk-HD5NQDOL.js} +2 -2
  59. package/dist/cli/chunks/{chunk-5ZTY5JJX.js → chunk-HD6CZBZV.js} +2 -2
  60. package/dist/cli/chunks/{chunk-JA7YARLP.js → chunk-HIWBW4IQ.js} +1 -1
  61. package/dist/cli/chunks/{chunk-YUFUGGXY.js → chunk-HZPXOAFW.js} +2 -2
  62. package/dist/cli/chunks/{chunk-3CIQ6CQ4.js → chunk-I4E6CLC4.js} +2 -2
  63. package/dist/cli/chunks/{chunk-FK4B2HIW.js → chunk-I4T4JPR2.js} +1 -1
  64. package/dist/cli/chunks/{chunk-X6IEQVSF.js → chunk-IBXNBLGM.js} +2 -2
  65. package/dist/cli/chunks/{chunk-GLI5EN6O.js → chunk-IQNR662U.js} +2 -2
  66. package/dist/cli/chunks/{chunk-YKZ3ZJWT.js → chunk-J5RJYFRM.js} +2 -2
  67. package/dist/cli/chunks/{chunk-27FNROZ2.js → chunk-JCKX2LEJ.js} +9 -9
  68. package/dist/cli/chunks/{chunk-IMP43AXO.js → chunk-JKVNZASH.js} +2 -2
  69. package/dist/cli/chunks/{chunk-Z5A2ENBC.js → chunk-JUICZG3T.js} +2 -2
  70. package/dist/cli/chunks/{chunk-MFPVS2KP.js → chunk-KCHFF4IE.js} +9 -9
  71. package/dist/cli/chunks/{chunk-TG44VKO3.js → chunk-KDFW7MVM.js} +2 -2
  72. package/dist/cli/chunks/{chunk-O4C3JEOR.js → chunk-KNL3QWVA.js} +2 -2
  73. package/dist/cli/chunks/{chunk-ZBY4HSHR.js → chunk-KOSKGZK4.js} +2 -2
  74. package/dist/cli/chunks/{chunk-G7YDYXQH.js → chunk-KYLJERZ3.js} +2 -2
  75. package/dist/cli/chunks/{chunk-7ZCDG3IM.js → chunk-L2AIES7X.js} +1 -1
  76. package/dist/cli/chunks/{chunk-6DACR7QY.js → chunk-L3IFZ4IX.js} +2 -2
  77. package/dist/cli/chunks/{chunk-2AANIKDG.js → chunk-L4N6PTIC.js} +2 -2
  78. package/dist/cli/chunks/{chunk-BNFW4LMD.js → chunk-LDMG4372.js} +2 -2
  79. package/dist/cli/chunks/{chunk-QH7K2UPP.js → chunk-LQ3TA22E.js} +2 -2
  80. package/dist/cli/chunks/{chunk-EDG4NEET.js → chunk-LRISVDVO.js} +1 -1
  81. package/dist/cli/chunks/{chunk-XNXFEMWT.js → chunk-LXHA55EB.js} +1 -1
  82. package/dist/cli/chunks/{chunk-AJ2VFSLX.js → chunk-LYVFC7C7.js} +2 -2
  83. package/dist/cli/chunks/{chunk-U6QAKKNB.js → chunk-M3M7HXDH.js} +2 -2
  84. package/dist/cli/chunks/{chunk-PY4B37U3.js → chunk-M4HDBRVJ.js} +1 -1
  85. package/dist/cli/chunks/{chunk-6BHUKCLI.js → chunk-M73IL7FA.js} +2 -2
  86. package/dist/cli/chunks/{chunk-F57OUXHJ.js → chunk-MF3XRML3.js} +2 -2
  87. package/dist/cli/chunks/{chunk-NKA3X6VT.js → chunk-MJBXQXSX.js} +1 -1
  88. package/dist/cli/chunks/{chunk-D5CLABLM.js → chunk-NLCUQMUR.js} +2 -2
  89. package/dist/cli/chunks/{chunk-IF4ZZ2HD.js → chunk-NT4PI5HI.js} +2 -2
  90. package/dist/cli/chunks/{chunk-74DA4P5K.js → chunk-NWHSEXHA.js} +1 -1
  91. package/dist/cli/chunks/{chunk-Y4ERDIPP.js → chunk-O3NAUNFC.js} +2 -2
  92. package/dist/cli/chunks/{chunk-AH3UC4IV.js → chunk-OGT45MZN.js} +2 -2
  93. package/dist/cli/chunks/{chunk-HOZNVDFF.js → chunk-OKGK7DBT.js} +2 -2
  94. package/dist/cli/chunks/{chunk-U7B4WCBY.js → chunk-OUJJ34JH.js} +1 -1
  95. package/dist/cli/chunks/{chunk-P4VQTIJE.js → chunk-OWMGD7FO.js} +3 -3
  96. package/dist/cli/chunks/{chunk-PGRDHDEJ.js → chunk-P6XYFDXN.js} +1 -1
  97. package/dist/cli/chunks/{chunk-NMHULQAV.js → chunk-PNDO4W4L.js} +2 -2
  98. package/dist/cli/chunks/{chunk-MAHLTWGV.js → chunk-QL3U5VSM.js} +2 -2
  99. package/dist/cli/chunks/{chunk-RCU5L7FF.js → chunk-QU54GUEA.js} +2 -2
  100. package/dist/cli/chunks/{chunk-OLBYILKU.js → chunk-QWBO76AU.js} +2 -2
  101. package/dist/cli/chunks/{chunk-QYUWWTE3.js → chunk-RARSTEUO.js} +1 -1
  102. package/dist/cli/chunks/{chunk-PUZAIRMY.js → chunk-RF6QKV7M.js} +2 -2
  103. package/dist/cli/chunks/{chunk-7TO7NTLT.js → chunk-RGONSQ44.js} +8 -8
  104. package/dist/cli/chunks/{chunk-A3TOJ4KN.js → chunk-RH3PHCJT.js} +2 -2
  105. package/dist/cli/chunks/{chunk-5M63H6RY.js → chunk-S33246T4.js} +1 -1
  106. package/dist/cli/chunks/{chunk-ESIE3MT5.js → chunk-S4CNA6Z5.js} +3 -3
  107. package/dist/cli/chunks/{chunk-GWLLNJ64.js → chunk-SCYF5CQA.js} +1 -1
  108. package/dist/cli/chunks/{chunk-DTJHO3WI.js → chunk-SGONA5GS.js} +2 -2
  109. package/dist/cli/chunks/{chunk-CLATNP57.js → chunk-T7DLX3LS.js} +3 -3
  110. package/dist/cli/chunks/{chunk-QAGAEAKM.js → chunk-TEJPHJMW.js} +2 -2
  111. package/dist/cli/chunks/{chunk-W2DF6FNE.js → chunk-TR7BZLB6.js} +1 -1
  112. package/dist/cli/chunks/{chunk-L3JJ52N6.js → chunk-U56TIYGP.js} +2 -2
  113. package/dist/cli/chunks/{chunk-TOZ6WUAB.js → chunk-UCIJCRPB.js} +2 -2
  114. package/dist/cli/chunks/{chunk-AH3TKDVW.js → chunk-UCXQQCIP.js} +2 -2
  115. package/dist/cli/chunks/{chunk-5MSZREOD.js → chunk-UE3XXKLN.js} +2 -2
  116. package/dist/cli/chunks/{chunk-556GYKN5.js → chunk-UGX4EHT5.js} +2 -2
  117. package/dist/cli/chunks/{chunk-2EWOYVH3.js → chunk-URVDWF2Y.js} +2 -2
  118. package/dist/cli/chunks/{chunk-DCXFHBHS.js → chunk-V5TRAL57.js} +2 -2
  119. package/dist/cli/chunks/{chunk-LIE24NRL.js → chunk-VEOQH4W6.js} +2 -2
  120. package/dist/cli/chunks/{chunk-AY2LLGZN.js → chunk-VMJXNTJT.js} +4 -4
  121. package/dist/cli/chunks/{chunk-FZA674BT.js → chunk-VTIXFHZR.js} +2 -2
  122. package/dist/cli/chunks/{chunk-GAC4MD6S.js → chunk-VTO5O7DA.js} +1 -1
  123. package/dist/cli/chunks/{chunk-G6Q66YLG.js → chunk-W6U7SIIK.js} +3 -3
  124. package/dist/cli/chunks/{chunk-CSDGFQKW.js → chunk-WC6KZDPM.js} +2 -2
  125. package/dist/cli/chunks/{chunk-2KMCRASK.js → chunk-WG6I7YF3.js} +1 -1
  126. package/dist/cli/chunks/{chunk-TK7TGVVQ.js → chunk-WLLE54TA.js} +1 -1
  127. package/dist/cli/chunks/{chunk-HHGZ4LXC.js → chunk-WVCIZIKH.js} +1 -1
  128. package/dist/cli/chunks/{chunk-NKBCAW27.js → chunk-X4U5NYB6.js} +1 -1
  129. package/dist/cli/chunks/chunk-X73CRYF4.js +2 -0
  130. package/dist/cli/chunks/{chunk-5ECOD4O6.js → chunk-XFMSHTXG.js} +1 -1
  131. package/dist/cli/chunks/{chunk-LUFY3GGI.js → chunk-XFUU2RCA.js} +2 -2
  132. package/dist/cli/chunks/{chunk-QXM3PRVR.js → chunk-Y4I5JBOL.js} +2 -2
  133. package/dist/cli/chunks/{chunk-C2JK5O55.js → chunk-YHNEBCYQ.js} +2 -2
  134. package/dist/cli/chunks/{chunk-5RPHV7Y3.js → chunk-YYDHTBHE.js} +1 -1
  135. package/dist/cli/chunks/{chunk-DKBBMZWB.js → chunk-Z2SCTEZD.js} +2 -2
  136. package/dist/cli/chunks/{chunk-CK5TGFII.js → chunk-Z6JLPPAY.js} +1 -1
  137. package/dist/cli/chunks/{chunk-TXSVZYFA.js → chunk-ZCNVFULO.js} +2 -2
  138. package/dist/cli/chunks/{chunk-YE42UTLT.js → chunk-ZFBMBCKN.js} +2 -2
  139. package/dist/cli/chunks/{chunk-BGD65PL4.js → chunk-ZYZWBNKT.js} +1 -1
  140. package/dist/cli/chunks/{ci-YA6SQ3PU.js → ci-7TR4NQ5I.js} +2 -2
  141. package/dist/cli/chunks/{ci-output-KKHXCQI4.js → ci-output-SLTICF3O.js} +2 -2
  142. package/dist/cli/chunks/{circuit-breaker-RTBCXGKA.js → circuit-breaker-7GVVTMBY.js} +2 -2
  143. package/dist/cli/chunks/{claude-flow-setup-CRV3Y6LO.js → claude-flow-setup-TYCWYEMM.js} +2 -2
  144. package/dist/cli/chunks/client-7GB4WWUD.js +2 -0
  145. package/dist/cli/chunks/{cline-installer-IS2VLXQS.js → cline-installer-ESIAJOLK.js} +2 -2
  146. package/dist/cli/chunks/{code-3CSNTK5O.js → code-I42JGOVI.js} +2 -2
  147. package/dist/cli/chunks/{code-index-extractor-P2YXEJGV.js → code-index-extractor-2CCXPCQW.js} +2 -2
  148. package/dist/cli/chunks/{codex-installer-QGDV2CAQ.js → codex-installer-HEZRDNUT.js} +2 -2
  149. package/dist/cli/chunks/{completions-TYECEYHY.js → completions-44HLIZGI.js} +2 -2
  150. package/dist/cli/chunks/{complexity-analyzer-GA5KSFF2.js → complexity-analyzer-SOCSFDVO.js} +2 -2
  151. package/dist/cli/chunks/{continuedev-installer-NW5Y4ZMI.js → continuedev-installer-Q7O4HLIM.js} +2 -2
  152. package/dist/cli/chunks/{copilot-installer-E5BIBYG6.js → copilot-installer-GIWCVLCS.js} +2 -2
  153. package/dist/cli/chunks/{cost-tracker-JLSEY4ID.js → cost-tracker-G7BONKEV.js} +2 -2
  154. package/dist/cli/chunks/{coverage-4TH275AN.js → coverage-5TWVP7KY.js} +3 -3
  155. package/dist/cli/chunks/cross-domain-router-7HQ74TLE.js +2 -0
  156. package/dist/cli/chunks/{cursor-installer-4SXSE5YT.js → cursor-installer-43EQZSB5.js} +2 -2
  157. package/dist/cli/chunks/{daemon-U6MP4P6S.js → daemon-QQZE4BU2.js} +4 -4
  158. package/dist/cli/chunks/{daemon-7T4RZQH6.js → daemon-ZXHFRDKG.js} +3 -3
  159. package/dist/cli/chunks/{dag-attention-scheduler-DT2V46XR.js → dag-attention-scheduler-GOZAVAZQ.js} +2 -2
  160. package/dist/cli/chunks/{detect-WHSTB4QT.js → detect-X777GVJ4.js} +2 -2
  161. package/dist/cli/chunks/{dist-node-4LC2RJXW.js → dist-node-EZZK46TB.js} +2 -2
  162. package/dist/cli/chunks/{domain-handler-A2LOOU7Y.js → domain-handler-ZT32DKYY.js} +2 -2
  163. package/dist/cli/chunks/{domain-transfer-4RJTMB3Y.js → domain-transfer-LHQVSLJW.js} +2 -2
  164. package/dist/cli/chunks/dream-G5SEFHI4.js +2 -0
  165. package/dist/cli/chunks/{embed-and-insert-pattern-PR3KTT24.js → embed-and-insert-pattern-XFYPPWG7.js} +2 -2
  166. package/dist/cli/chunks/{eval-2HRBMOOB.js → eval-V4NYJZUZ.js} +2 -2
  167. package/dist/cli/chunks/{experience-capture-middleware-X46IYOSD.js → experience-capture-middleware-HXX2W4GL.js} +3 -3
  168. package/dist/cli/chunks/{fast-paths-LYYYU362.js → fast-paths-RBPWQSFJ.js} +2 -2
  169. package/dist/cli/chunks/{feature-flags-TKDXIHOH.js → feature-flags-INJJZBMN.js} +2 -2
  170. package/dist/cli/chunks/{feature-flags-RNAMQPUN.js → feature-flags-NX5EXRO3.js} +2 -2
  171. package/dist/cli/chunks/{file-discovery-MKGGMDIW.js → file-discovery-SNFSG6NK.js} +2 -2
  172. package/dist/cli/chunks/{fleet-OY4IBCZG.js → fleet-6SDN4UWE.js} +3 -3
  173. package/dist/cli/chunks/{gnn-wrapper-G5OGHVAQ.js → gnn-wrapper-2JDRTDDK.js} +2 -2
  174. package/dist/cli/chunks/{heartbeat-handler-N7IUATSD.js → heartbeat-handler-QLK6E7KA.js} +4 -4
  175. package/dist/cli/chunks/heartbeat-scheduler-NG7BY3FR.js +2 -0
  176. package/dist/cli/chunks/hnsw-adapter-TDSLUI7K.js +2 -0
  177. package/dist/cli/chunks/hnsw-index-OWLQSOQH.js +2 -0
  178. package/dist/cli/chunks/{hnsw-legacy-bridge-TMCMZDVF.js → hnsw-legacy-bridge-Q2ZEZQKB.js} +2 -2
  179. package/dist/cli/chunks/{better-sqlite3-SPABZYYQ.js → hnswlib-node-TA4DZV62.js} +2 -2
  180. package/dist/cli/chunks/{hooks-5QDXEZ25.js → hooks-D4YENHO2.js} +10 -10
  181. package/dist/cli/chunks/{hybrid-router-IY62NN7G.js → hybrid-router-URU2XLBD.js} +2 -2
  182. package/dist/cli/chunks/{hypergraph-engine-QQYKS2F3.js → hypergraph-engine-G72U446M.js} +2 -2
  183. package/dist/cli/chunks/{hypergraph-handler-YXFNXMRF.js → hypergraph-handler-TRZ5FDRH.js} +3 -3
  184. package/dist/cli/chunks/impact-analyzer-NMTN75KA.js +2 -0
  185. package/dist/cli/chunks/{init-handler-SFFSDGEF.js → init-handler-3ZD4GCT4.js} +6 -6
  186. package/dist/cli/chunks/init-wizard-SHBFYGBV.js +2 -0
  187. package/dist/cli/chunks/kernel-7KVY2JGO.js +2 -0
  188. package/dist/cli/chunks/{kilocode-installer-QFRYXQYY.js → kilocode-installer-AXSIW3XW.js} +2 -2
  189. package/dist/cli/chunks/{kiro-installer-7L2EYEOR.js → kiro-installer-JQGIFWBK.js} +2 -2
  190. package/dist/cli/chunks/knowledge-graph-V4G5J5B7.js +2 -0
  191. package/dist/cli/chunks/{learning-7TVVL5UH.js → learning-SPO7TGWX.js} +3 -3
  192. package/dist/cli/chunks/{llm-router-S3HHVPH4.js → llm-router-G6N2OKDA.js} +4 -4
  193. package/dist/cli/chunks/{load-Y46RO7BF.js → load-XIDDK64U.js} +2 -2
  194. package/dist/cli/chunks/load-test-N4RNPLG4.js +2 -0
  195. package/dist/cli/chunks/{mcp-PYNP2S5O.js → mcp-3JXRGXO4.js} +2 -2
  196. package/dist/cli/chunks/{memory-DAVXW5OP.js → memory-A66KRS2P.js} +5 -5
  197. package/dist/cli/chunks/memory-backend-HPGJ5YDQ.js +2 -0
  198. package/dist/cli/chunks/{memory-handlers-6COHVON7.js → memory-handlers-K33YVCVQ.js} +2 -2
  199. package/dist/cli/chunks/{multi-model-executor-7ECJRCM3.js → multi-model-executor-XCDGUVCE.js} +2 -2
  200. package/dist/cli/chunks/{opencode-installer-H7QOONUC.js → opencode-installer-GELXWLF2.js} +2 -2
  201. package/dist/cli/chunks/{orchestrator-TSJ2F3MG.js → orchestrator-CCS3K6NH.js} +5 -5
  202. package/dist/cli/chunks/{pipeline-SXR4MRY7.js → pipeline-Z5C72H5S.js} +2 -2
  203. package/dist/cli/chunks/{platform-7NOS56VD.js → platform-4AK7XJ3Y.js} +2 -2
  204. package/dist/cli/chunks/{plugin-VLSWBGJN.js → plugin-7RYBIZI7.js} +2 -2
  205. package/dist/cli/chunks/{prime-radiant-advanced-wasm-7ZHSOP7H.js → prime-radiant-advanced-wasm-E5PARKRX.js} +2 -2
  206. package/dist/cli/chunks/protocol-executor-GNVWUJUP.js +2 -0
  207. package/dist/cli/chunks/{protocol-handler-LWNYDM4D.js → protocol-handler-R6QJQFNL.js} +2 -2
  208. package/dist/cli/chunks/{prove-JYFW3OBB.js → prove-7ESQ2YAL.js} +2 -2
  209. package/dist/cli/chunks/{provider-manager-VPS4W7KG.js → provider-manager-HV55NIIO.js} +2 -2
  210. package/dist/cli/chunks/qe-reasoning-bank-DDSBHO6D.js +2 -0
  211. package/dist/cli/chunks/{quality-FCAOFXZ2.js → quality-4UE345QA.js} +2 -2
  212. package/dist/cli/chunks/queen-coordinator-BQJ5O63C.js +2 -0
  213. package/dist/cli/chunks/real-embeddings-TYIVN3N5.js +2 -0
  214. package/dist/cli/chunks/{roocode-installer-ZVGJSAWD.js → roocode-installer-2KOANC47.js} +2 -2
  215. package/dist/cli/chunks/router-C2RKWB7J.js +2 -0
  216. package/dist/cli/chunks/routing-feedback-RHATTSJ6.js +2 -0
  217. package/dist/cli/chunks/{routing-handler-AGDHK3A2.js → routing-handler-JFEYTN7T.js} +2 -2
  218. package/dist/cli/chunks/{ruvector-commands-UGZINDCN.js → ruvector-commands-KSLSZRJX.js} +2 -2
  219. package/dist/cli/chunks/{rvf-dual-writer-PW7H6G4V.js → rvf-dual-writer-EPBL226J.js} +2 -2
  220. package/dist/cli/chunks/{rvf-migration-adapter-ZKOTVCHJ.js → rvf-migration-adapter-25KSI6SF.js} +2 -2
  221. package/dist/cli/chunks/{rvf-migration-coordinator-SCBEMOP3.js → rvf-migration-coordinator-2XBYHPZP.js} +2 -2
  222. package/dist/cli/chunks/rvf-native-adapter-QG4CXHLL.js +2 -0
  223. package/dist/cli/chunks/safe-db-A4KQ2IDB.js +2 -0
  224. package/dist/cli/chunks/schedule-O7MLASQT.js +2 -0
  225. package/dist/cli/chunks/scheduler-HT7RNYQ2.js +2 -0
  226. package/dist/cli/chunks/{security-H7QX46VA.js → security-4XWYKI4O.js} +3 -3
  227. package/dist/cli/chunks/{shared-rvf-adapter-LWYHWJIA.js → shared-rvf-adapter-WRZ3HGDQ.js} +2 -2
  228. package/dist/cli/chunks/{shared-rvf-dual-writer-P2U424FB.js → shared-rvf-dual-writer-DX2N5STR.js} +2 -2
  229. package/dist/cli/chunks/sqlite-persistence-4NNKJ6CQ.js +2 -0
  230. package/dist/cli/chunks/{status-handler-UNX3RA3S.js → status-handler-V75OSXMQ.js} +2 -2
  231. package/dist/cli/chunks/{structural-health-65YV3M5E.js → structural-health-TLX3JHZ6.js} +2 -2
  232. package/dist/cli/chunks/{sync-OZ7CHYYO.js → sync-DXZFMVZQ.js} +2 -2
  233. package/dist/cli/chunks/{sync-B4O3NDJ6.js → sync-KGBEXUF7.js} +2 -2
  234. package/dist/cli/chunks/{task-handler-NIG3USPG.js → task-handler-T3OJ6R7H.js} +2 -2
  235. package/dist/cli/chunks/{task-handlers-Z2PI7BTO.js → task-handlers-NJYR54AS.js} +3 -3
  236. package/dist/cli/chunks/{test-MNLYS3WS.js → test-KMVDNNQA.js} +4 -4
  237. package/dist/cli/chunks/{test-scheduling-VCL6D6T7.js → test-scheduling-R5EQ2XGV.js} +3 -3
  238. package/dist/cli/chunks/{token-bootstrap-DGMEU3W4.js → token-bootstrap-PFKVV3RO.js} +2 -2
  239. package/dist/cli/chunks/{token-usage-IXTYAV5K.js → token-usage-ZLOGA6LR.js} +2 -2
  240. package/dist/cli/chunks/{transformers-5CWLXT2M.js → transformers-TNPSPQI3.js} +2 -2
  241. package/dist/cli/chunks/{tree-sitter-wasm-parser-W3FKJLJG.js → tree-sitter-wasm-parser-A2EEB5BF.js} +2 -2
  242. package/dist/cli/chunks/{types-NVOCAZCQ.js → types-DIXPI4NR.js} +2 -2
  243. package/dist/cli/chunks/unified-memory-CMNJVHOJ.js +2 -0
  244. package/dist/cli/chunks/unified-memory-hnsw-JQLU2KI6.js +2 -0
  245. package/dist/cli/chunks/unified-persistence-I25TEDIU.js +2 -0
  246. package/dist/cli/chunks/{upgrade-VJYD4U4X.js → upgrade-LX5KP6VO.js} +2 -2
  247. package/dist/cli/chunks/{validate-CAKTCZ3T.js → validate-3L6F7M36.js} +2 -2
  248. package/dist/cli/chunks/{validate-swarm-H24JHUTN.js → validate-swarm-FD42ZKAQ.js} +2 -2
  249. package/dist/cli/chunks/{vibium-247XN6V3.js → vibium-GSBSJR53.js} +2 -2
  250. package/dist/cli/chunks/visual-security-AJJIEV5V.js +2 -0
  251. package/dist/cli/chunks/{web-tree-sitter-3DOMHLRH.js → web-tree-sitter-TXHMO4BW.js} +2 -2
  252. package/dist/cli/chunks/{windsurf-installer-S2MOA5TQ.js → windsurf-installer-3EUZ6RD3.js} +2 -2
  253. package/dist/cli/chunks/witness-chain-762QQBTN.js +2 -0
  254. package/dist/cli/chunks/{witness-chain-CKLVPFLG.js → witness-chain-ONAUEJ4M.js} +2 -2
  255. package/dist/cli/chunks/{workflow-GU3IV2OD.js → workflow-E7A6BV4C.js} +4 -4
  256. package/dist/cli/chunks/workflow-orchestrator-ZGPYISKY.js +2 -0
  257. package/dist/cli/chunks/{wrappers-74Y4EKW3.js → wrappers-AHHAQJM3.js} +2 -2
  258. package/dist/learning/embedder-endpoint-client.d.ts +133 -0
  259. package/dist/learning/embedder-endpoint-client.js +426 -0
  260. package/dist/learning/embedder-identity-store.d.ts +30 -0
  261. package/dist/learning/embedder-identity-store.js +136 -0
  262. package/dist/learning/qe-reasoning-bank.js +11 -3
  263. package/dist/learning/real-embeddings.d.ts +28 -0
  264. package/dist/learning/real-embeddings.js +130 -19
  265. package/dist/learning/sqlite-persistence.js +16 -3
  266. package/dist/mcp/bundle.js +399 -389
  267. package/package.json +1 -1
  268. package/dist/cli/chunks/adapter-MISKG4JY.js +0 -2
  269. package/dist/cli/chunks/aqe-learning-engine-NDLBNM6C.js +0 -2
  270. package/dist/cli/chunks/base-OMDJAHGF.js +0 -2
  271. package/dist/cli/chunks/browser-workflow-XUG5Z5CJ.js +0 -2
  272. package/dist/cli/chunks/chunk-USLHYNYG.js +0 -2
  273. package/dist/cli/chunks/chunk-ZYPSXPQ5.js +0 -2
  274. package/dist/cli/chunks/client-VXJRAW3W.js +0 -2
  275. package/dist/cli/chunks/cross-domain-router-AKHC7TFO.js +0 -2
  276. package/dist/cli/chunks/dream-FPWIC7KF.js +0 -2
  277. package/dist/cli/chunks/heartbeat-scheduler-WHGMTRT7.js +0 -2
  278. package/dist/cli/chunks/hnsw-adapter-IA2M5KDH.js +0 -2
  279. package/dist/cli/chunks/hnsw-index-UBXTXXLQ.js +0 -2
  280. package/dist/cli/chunks/impact-analyzer-6PVCOS33.js +0 -2
  281. package/dist/cli/chunks/init-wizard-XHP5C6RD.js +0 -2
  282. package/dist/cli/chunks/kernel-YM5PY5SS.js +0 -2
  283. package/dist/cli/chunks/knowledge-graph-LTUOUHO7.js +0 -2
  284. package/dist/cli/chunks/load-test-CYCAQI3F.js +0 -2
  285. package/dist/cli/chunks/memory-backend-RW2OPAJU.js +0 -2
  286. package/dist/cli/chunks/protocol-executor-CREUYOBZ.js +0 -2
  287. package/dist/cli/chunks/qe-reasoning-bank-J4DLHRJY.js +0 -2
  288. package/dist/cli/chunks/queen-coordinator-MGLNSTPY.js +0 -2
  289. package/dist/cli/chunks/real-embeddings-LE6YXNPZ.js +0 -2
  290. package/dist/cli/chunks/router-CXGPFUT2.js +0 -2
  291. package/dist/cli/chunks/routing-feedback-MZ73LFBP.js +0 -2
  292. package/dist/cli/chunks/rvf-native-adapter-T6JBPHTE.js +0 -2
  293. package/dist/cli/chunks/safe-db-DS4SKPYB.js +0 -2
  294. package/dist/cli/chunks/schedule-H2Q7XWAK.js +0 -2
  295. package/dist/cli/chunks/scheduler-PMZMKQIF.js +0 -2
  296. package/dist/cli/chunks/sqlite-persistence-ONKEAMTQ.js +0 -2
  297. package/dist/cli/chunks/unified-memory-PNHI6I3R.js +0 -2
  298. package/dist/cli/chunks/unified-memory-hnsw-CDV3UMBD.js +0 -2
  299. package/dist/cli/chunks/unified-persistence-FMCHCEZV.js +0 -2
  300. package/dist/cli/chunks/visual-security-3WRJQDUY.js +0 -2
  301. package/dist/cli/chunks/witness-chain-5ZKCKNRJ.js +0 -2
  302. package/dist/cli/chunks/workflow-orchestrator-OBSFY7YK.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.9.36");process.exit(0)}
2
- import{a as ne}from"./chunk-BUVY7IGM.js";import{d as B,e as W,f as re,g as j}from"./chunk-4R3WXD4U.js";import{g as et,h as tt}from"./chunk-LIE24NRL.js";import{a as xe,d as Ce,e as Ze,f as De}from"./chunk-5SYH5QMQ.js";import{b as v,c as w}from"./chunk-QMUTKI34.js";import{a as y,b as Ae,c as Te}from"./chunk-O4C3JEOR.js";import{i as C}from"./chunk-NKA3X6VT.js";import{B as q,D as H,G as te,P as M,S as F,b as D}from"./chunk-ZBY4HSHR.js";import{a as Ee,d as J,f as Ke,g as Re}from"./chunk-SCBWRKPE.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-ONKEAMTQ.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.0");process.exit(0)}
2
+ import{a as ne}from"./chunk-3OSCWD7Z.js";import{d as B,e as W,f as re,g as j}from"./chunk-F363JJUI.js";import{g as et,h as tt}from"./chunk-VEOQH4W6.js";import{a as xe,d as Ce,e as Ze,f as De}from"./chunk-DXV6NRG3.js";import{b as v,c as w}from"./chunk-FEBXP74Y.js";import{a as y,b as Ae,c as Te}from"./chunk-KNL3QWVA.js";import{i as C}from"./chunk-MJBXQXSX.js";import{B as q,D as H,G as te,P as M,S as F,b as D}from"./chunk-KOSKGZK4.js";import{a as Ee,d as J,f as Ke,g as Re}from"./chunk-55JPAF56.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-4NNKJ6CQ.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=`
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-BUVY7IGM.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-TMCMZDVF.js"),{HnswAdapter:c}=await import("./hnsw-adapter-IA2M5KDH.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-UBXTXXLQ.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},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-Q2ZEZQKB.js"),{HnswAdapter:c}=await import("./hnsw-adapter-TDSLUI7K.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-OWLQSOQH.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};
50
50
  /*! Bundled license information:
51
51
 
52
52
  fast-json-patch/commonjs/helpers.js:
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.36");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.0");process.exit(0)}
2
2
  var l=["ECONNREFUSED","ETIMEOUT","ENOMEM","ENOSPC"];var s={successRate:.1,failureRate:1,viabilityThreshold:.3,rehabilitationThreshold:10,maxQuarantineDurationMs:6048e5,domainOverrides:{"security-compliance":{successRate:.05,failureRate:1,viabilityThreshold:.5},"test-generation":{successRate:.15,failureRate:1,viabilityThreshold:.2},"quality-assessment":{successRate:.1,failureRate:1,viabilityThreshold:.4}}},a=class{config;_witnessChain=null;set witnessChain(e){this._witnessChain=e}constructor(e={}){this.config={...s,...e,domainOverrides:{...s.domainOverrides,...e.domainOverrides}}}computeConfidenceUpdate(e,r,i){let{successRate:u,failureRate:o}=this.getConfigForDomain(i),n=r==="success"?u:-o;if(r==="failure")try{this._witnessChain?.append("HEBBIAN_PENALTY",{previousConfidence:e,delta:n,domain:i},"asymmetric-learning")}catch{}return c(e+n,0,1)}shouldQuarantine(e,r){let{viabilityThreshold:i}=this.getConfigForDomain(r);return{shouldQuarantine:e<i,confidence:e,viabilityThreshold:i,domain:r}}classifyFailure(e){if(e.infrastructureHealthy===!1||e.durationMs!==void 0&&e.durationMs>3e4)return"infrastructure";if(e.errorMessage){let r=e.errorMessage.toUpperCase();for(let i of l)if(r.includes(i))return"infrastructure"}return e.failureCategory==="infrastructure"?"infrastructure":(e.failureCategory==="pattern","pattern")}checkRehabilitation(e,r){let i=this.config.rehabilitationThreshold;return{canRehabilitate:e>=i,consecutiveSuccesses:e,requiredSuccesses:i,domain:r}}getConfigForDomain(e){return e&&this.config.domainOverrides?.[e]?this.config.domainOverrides[e]:{successRate:this.config.successRate,failureRate:this.config.failureRate,viabilityThreshold:this.config.viabilityThreshold}}getAsymmetryRatio(e){let{successRate:r,failureRate:i}=this.getConfigForDomain(e);return r===0?1/0:i/r}};function c(t,e,r){return t<e?e:t>r?r:t}export{a};
@@ -0,0 +1,12 @@
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.0");process.exit(0)}
2
+ import{a as N,c as ee}from"./chunk-KNL3QWVA.js";import{b as L,d as B}from"./chunk-66GIKUI2.js";B();ee();B();import*as x from"node:http";import*as R from"node:https";import{createHash as te}from"node:crypto";import{URL as W}from"node:url";var T={model:"Xenova/all-MiniLM-L6-v2",expectedDim:384,connectTimeoutMs:5e3,requestTimeoutMs:3e4,failureThreshold:3,failureWindowMs:6e4},ne="AQE embedder endpoint identity canary v1",re="/v1/embeddings";function X(n){if(n.startsWith("unix:"))return n;try{let e=new W(n);return e.username||e.password?(e.username="",e.password="",e.toString().replace(/\/$/,"")):n}catch{return n}}function ie(n){if(n.startsWith("unix:")){let r=n.slice(5);if(!r.startsWith("/"))throw new Error(`unix endpoint must be an absolute path: ${n}`);return{transport:"unix",socketPath:r,safeUrl:n}}let e=new W(n);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`unsupported embedder endpoint protocol: ${e.protocol}`);return(e.username||e.password)&&(console.warn("[EmbedderEndpointClient] endpoint URL contained userinfo; stripping. Use AQE_EMBEDDER_TOKEN env var for credentials."),e.username="",e.password=""),{transport:e.protocol==="https:"?"https":"http",host:e.hostname,port:e.port?Number(e.port):e.protocol==="https:"?443:80,protocol:e.protocol,safeUrl:e.toString().replace(/\/$/,"")}}var D=class{constructor(e,t,r=()=>{}){this.threshold=e;this.windowMs=t;this.onRecover=r}threshold;windowMs;onRecover;failures=[];trippedAt=null;recordSuccess(){this.failures=[],this.trippedAt=null}recordFailure(){let e=Date.now();this.failures=this.failures.filter(t=>e-t<this.windowMs),this.failures.push(e),this.failures.length>=this.threshold&&(this.trippedAt=e)}isOpen(){return this.trippedAt===null?!1:Date.now()-this.trippedAt>=this.windowMs?(this.failures=[],this.trippedAt=null,this.onRecover(),!1):!0}getState(){return{open:this.isOpen(),failures:this.failures.length,trippedAt:this.trippedAt}}},P=class{parsed;agent;breaker;opts;cachedIdentity=null;probeInFlight=null;constructor(e){if(this.opts={endpoint:e.endpoint,token:e.token,model:e.model??T.model,expectedDim:e.expectedDim??T.expectedDim,connectTimeoutMs:e.connectTimeoutMs??T.connectTimeoutMs,requestTimeoutMs:e.requestTimeoutMs??T.requestTimeoutMs,failureThreshold:e.failureThreshold??T.failureThreshold,failureWindowMs:e.failureWindowMs??T.failureWindowMs,tlsOptions:e.tlsOptions},this.parsed=ie(e.endpoint),this.parsed.transport==="https"){let t=e.tlsOptions??{};this.agent=new R.Agent({keepAlive:!0,ca:t.ca,cert:t.cert,key:t.key,rejectUnauthorized:t.rejectUnauthorized!==!1,servername:t.servername})}else this.agent=new x.Agent({keepAlive:!0});this.breaker=new D(this.opts.failureThreshold,this.opts.failureWindowMs,()=>{this.cachedIdentity=null})}getSafeEndpoint(){return this.parsed.safeUrl}async embed(e){if(e.length===0)return[];if(this.breaker.isOpen())throw new Error(`[EmbedderEndpointClient] circuit breaker open for ${this.parsed.safeUrl} \u2014 fast-failing`);this.cachedIdentity===null&&await this.ensureProbed();try{let t=await this.postEmbeddings(e),r=this.decodeAndNormalize(t,e.length);return this.breaker.recordSuccess(),r}catch(t){throw this.breaker.recordFailure(),t}}async probe(){return this.probeInFlight?this.probeInFlight:(this.probeInFlight=this.doProbe().finally(()=>{this.probeInFlight=null}),this.probeInFlight)}async ensureProbed(){return this.cachedIdentity?this.cachedIdentity:this.probe()}async doProbe(){let e;try{let s=await this.postEmbeddings([ne]);e=this.decodeAndNormalize(s,1)[0],this.breaker.recordSuccess()}catch(s){throw this.breaker.recordFailure(),s}if(!e||e.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch: expected ${this.opts.expectedDim}, got ${e?.length??0} from ${this.parsed.safeUrl}`);let t=Buffer.alloc(e.length*2);for(let s=0;s<e.length;s++){let o=Math.max(-32768,Math.min(32767,Math.round(e[s]*32767)));t.writeInt16LE(o,s*2)}let r=te("sha256").update(t).digest("hex").slice(0,16);return this.cachedIdentity={dim:e.length,fingerprint:r,endpoint:this.parsed.safeUrl},this.cachedIdentity}getCachedIdentity(){return this.cachedIdentity}getBreakerState(){return this.breaker.getState()}close(){this.agent.destroy()}decodeAndNormalize(e,t){if(!e||typeof e!="object"||!Array.isArray(e.data))throw new Error("[EmbedderEndpointClient] response missing data array");let r=e.data;if(r.length!==t)throw new Error(`[EmbedderEndpointClient] response count mismatch: expected ${t}, got ${r.length}`);let s=r.map((o,i)=>({idx:typeof o.index=="number"?o.index:i,embedding:o.embedding}));return s.sort((o,i)=>o.idx-i.idx),s.map(({embedding:o},i)=>{if(typeof o=="string")throw new Error(`[EmbedderEndpointClient] received base64 embedding at position ${i} \u2014 server ignored encoding_format=float. Configure the server to return float arrays.`);if(!Array.isArray(o))throw new Error(`[EmbedderEndpointClient] missing embedding at position ${i}`);if(o.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch at position ${i}: expected ${this.opts.expectedDim}, got ${o.length}`);return L(o)})}postEmbeddings(e){let t=JSON.stringify({model:this.opts.model,input:e,encoding_format:"float"});return this.request(re,t)}request(e,t){let r={"content-type":"application/json","content-length":Buffer.byteLength(t),accept:"application/json"};this.opts.token&&(r.authorization=`Bearer ${this.opts.token}`);let s={method:"POST",path:e,headers:r,agent:this.agent},o,i;this.parsed.transport==="unix"?(o={...s,socketPath:this.parsed.socketPath},i=x.request):(o={...s,host:this.parsed.host,port:this.parsed.port,protocol:this.parsed.protocol},i=this.parsed.transport==="https"?R.request:x.request);let l=this.parsed.safeUrl,c=this.opts.connectTimeoutMs,h=this.opts.requestTimeoutMs;return new Promise((S,I)=>{let E=!1,C=a=>{E||(E=!0,S(a))},y=a=>{E||(E=!0,I(a))},f=i(o,a=>{let g=[];a.on("data",u=>g.push(Buffer.from(u))),a.on("end",()=>{let u=Buffer.concat(g).toString("utf-8");if(!a.statusCode||a.statusCode<200||a.statusCode>=300){y(new Error(`[EmbedderEndpointClient] HTTP ${a.statusCode} from ${l}: ${u.slice(0,200)}`));return}try{let b=JSON.parse(u);C(b)}catch(b){y(new Error(`[EmbedderEndpointClient] invalid JSON from ${l}: ${b.message}`))}}),a.on("error",u=>y(u))});f.on("socket",a=>{a.setTimeout(c);let g=()=>{a.setTimeout(h)};a.connecting?a.once("connect",g):g(),a.on("timeout",()=>{let u=a.connecting?"connect":"request",b=a.connecting?c:h,M=new Error(`[EmbedderEndpointClient] ${u} timeout after ${b}ms`);y(M),f.destroy(M)})}),f.on("error",a=>y(a)),f.write(t),f.end()})}};import{join as H}from"node:path";import{existsSync as oe,mkdirSync as se}from"node:fs";import{createRequire as ae}from"node:module";var de=ae(import.meta.url);function le(){let n=process.env.AQE_MEMORY_PATH;return n&&n.length>0?n:H(process.cwd(),".agentic-qe","memory.db")}var j="_system",K="embedder_identity:",v=null,$=!1;function G(){if(v)return v;if($)return null;try{let n=de("better-sqlite3"),e=le(),t=H(e,"..");oe(t)||se(t,{recursive:!0});let r=new n(e);return r.pragma("journal_mode = WAL"),r.pragma("busy_timeout = 5000"),r.exec(`
3
+ CREATE TABLE IF NOT EXISTS kv_store (
4
+ key TEXT NOT NULL,
5
+ namespace TEXT NOT NULL,
6
+ value TEXT NOT NULL,
7
+ expires_at INTEGER,
8
+ created_at INTEGER DEFAULT (strftime('%s', 'now') * 1000),
9
+ PRIMARY KEY (namespace, key)
10
+ );
11
+ CREATE INDEX IF NOT EXISTS idx_kv_namespace ON kv_store(namespace);
12
+ `),v=r,r}catch{return $=!0,null}}function J(n){let e=G();if(!e)return null;try{let t=e.prepare("SELECT value FROM kv_store WHERE namespace = ? AND key = ?").get(j,K+n);if(!t)return null;let r=JSON.parse(t.value);return!r.fingerprint||typeof r.dim!="number"?null:{fingerprint:r.fingerprint,dim:r.dim,endpoint:r.endpoint}}catch{return null}}function Q(n){let e=G();if(!e)return;let t={fingerprint:n.fingerprint,dim:n.dim,endpoint:n.endpoint,updatedAt:Date.now()};e.prepare("INSERT OR REPLACE INTO kv_store (key, namespace, value) VALUES (?, ?, ?)").run(K+n.endpoint,j,JSON.stringify(t))}function Y(){if(v)try{v.close()}catch{}v=null,$=!1}var z=null,m=null,A=null,k=!1,O="",w=null,p=null,F={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4,endpoint:process.env.AQE_EMBEDDER_ENDPOINT,endpointToken:process.env.AQE_EMBEDDER_TOKEN},d=new Map,V=36e5;function _(n){return p?`endpoint:${p.fingerprint}:${n}`:`inproc:${n}`}function pe(n){let e=n.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function Z(n={}){if(k)throw new Error(`Transformer initialization previously failed: ${O}`);if(A)return A;let e={...F,...n};return A=(async()=>{try{if(e.endpoint){let o=X(e.endpoint);console.log(`[RealEmbeddings] Using external embedder endpoint: ${o}`),w=new P({endpoint:e.endpoint,token:e.endpointToken,model:e.modelName,expectedDim:q()}),p=await w.probe(),console.log(`[RealEmbeddings] Endpoint identity: dim=${p.dim} fingerprint=${p.fingerprint}`);try{let i=J(p.endpoint);i&&i.fingerprint!==p.fingerprint&&console.warn(`[RealEmbeddings] WARNING: endpoint identity changed since last run. Previous fingerprint=${i.fingerprint} dim=${i.dim}, current fingerprint=${p.fingerprint} dim=${p.dim}. Vectors written before this change may no longer be comparable.`),Q(p)}catch(i){console.warn(`[RealEmbeddings] Could not persist endpoint identity: ${N(i)}`)}m=ce(w);return}z=(await import("./transformers-TNPSPQI3.js")).pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let r=performance.now();m=await z("feature-extraction",e.modelName,{quantized:e.quantized});let s=performance.now()-r;console.log(`[RealEmbeddings] Model loaded in ${s.toFixed(0)}ms`)}catch(t){throw k=!0,O=N(t),new Error(`Failed to initialize transformer model: ${O}`)}})(),A}function ce(n){return async e=>{let t=Array.isArray(e)?e:[e],r=await n.embed(t),s=r[0]?.length??q(),o=new Float32Array(t.length*s);for(let i=0;i<r.length;i++)o.set(r[i],i*s);return{data:o,dims:[t.length,s]}}}async function Ae(n,e={}){let t={...F,...e};if(pe(n))return new Array(q()).fill(0);if(m||await Z(e),!m)throw new Error("Embedding model failed to initialize");let r=_(n);if(t.enableCache){let c=d.get(r);if(c&&Date.now()-c.timestamp<V)return c.embedding}let s=performance.now(),o=await m(n,{pooling:"mean",normalize:!0}),i=Array.from(o.data),l=performance.now()-s;if(l>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${l.toFixed(1)}ms for "${n.slice(0,50)}..."`),t.enableCache){if(d.size>=t.maxCacheSize){let c=d.keys().next().value;c&&d.delete(c)}d.set(r,{embedding:i,timestamp:Date.now()})}return i}async function Ie(n,e={}){let t={...F,...e},r=[],s=[],o=new Array(n.length).fill(null);if(m||await Z(e),!m)throw new Error("Embedding model failed to initialize");if(t.enableCache)for(let i=0;i<n.length;i++){let l=d.get(_(n[i]));l&&Date.now()-l.timestamp<V?o[i]=l.embedding:(r.push(n[i]),s.push(i))}else{r.push(...n);for(let i=0;i<n.length;i++)s.push(i)}if(r.length>0){let i=performance.now(),l=32;for(let h=0;h<r.length;h+=l){let S=Math.min(h+l,r.length),I=r.slice(h,S),E=await m(I,{pooling:"mean",normalize:!0}),C=E.dims||[I.length,384],y=C[0],f=C[1];for(let a=0;a<y;a++){let g=a*f,u=Array.from(E.data.slice(g,g+f)),b=h+a,M=s[b];if(o[M]=u,t.enableCache){if(d.size>=t.maxCacheSize){let U=d.keys().next().value;U&&d.delete(U)}d.set(_(r[b]),{embedding:u,timestamp:Date.now()})}}}let c=performance.now()-i;console.log(`[RealEmbeddings] Batch computed ${r.length} embeddings in ${c.toFixed(0)}ms`)}return o.filter(i=>i!==null)}function Ce(){d.clear(),console.log("[RealEmbeddings] Cache cleared")}function Me(){return{size:d.size,hitRate:0}}function Pe(){return!k&&m!==null}function q(){return 384}function Re(){z=null,m=null,A=null,k=!1,O="",d.clear(),w&&w.close(),w=null,p=null,Y()}function Oe(){return w!==null}function ke(){return p}export{F as a,Ae as b,Ie as c,Ce as d,Me as e,Pe as f,q as g,Re as h,Oe as i,ke as j};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.36");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.0");process.exit(0)}
2
2
  var i=class{s0;s1;s2;s3;constructor(s){this.s0=this.splitmix32(s),this.s1=this.splitmix32(this.s0),this.s2=this.splitmix32(this.s1),this.s3=this.splitmix32(this.s2)}splitmix32(s){return s=s+2654435769|0,s=Math.imul(s^s>>>16,2246822507),s=Math.imul(s^s>>>13,3266489909),(s^s>>>16)>>>0}next(){let s=this.s3,t=this.s0;return this.s3=this.s2,this.s2=this.s1,this.s1=t,t^=t<<11,t^=t>>>8,this.s0=t^s^s>>>19,this.s0>>>0}nextFloat(){return this.next()/4294967296}nextGaussian(){let s=this.nextFloat()||1e-10,t=this.nextFloat();return Math.sqrt(-2*Math.log(s))*Math.cos(2*Math.PI*t)}};export{i as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.36");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.0");process.exit(0)}
2
2
  function r(e,f){if(e==null)return e;let n={...e};for(let t of f){let o=n[t];typeof o=="string"&&(n[t]=new Date(o))}return n}export{r as a};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.36");process.exit(0)}
2
- import{b as P,c as x,d as R,f as O,g as j,h as D,i as $,j as L,k as N}from"./chunk-YE42UTLT.js";import{b as _,d as T}from"./chunk-HOZNVDFF.js";import{a as k,c as q}from"./chunk-O4C3JEOR.js";import{a as v,b as ee}from"./chunk-TXSVZYFA.js";T();import{existsSync as w,mkdirSync as Q,writeFileSync as S,readFileSync as I,copyFileSync as te}from"fs";import{join as g,dirname as ne}from"path";async function M(t,e){if(!e.hooks.claudeCode)return!1;let n=g(t,".claude");w(n)||Q(n,{recursive:!0});let r=g(n,"settings.json"),s={};if(w(r))try{let u=I(r,"utf-8");s=_(u)}catch{s={}}let i={PreToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks guard --file "$TOOL_INPUT_file_path" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-edit --file "$TOOL_INPUT_file_path" --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-command --command "$TOOL_INPUT_command" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-task --description "$TOOL_INPUT_prompt" --json',timeout:5e3,continueOnError:!0}]}],PostToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks post-edit --file "$TOOL_INPUT_file_path" --success --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'npx agentic-qe hooks post-command --command "$TOOL_INPUT_command" --success --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'npx agentic-qe hooks post-task --task-id "$TOOL_RESULT_agent_id" --success --json',timeout:5e3,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:"npx agentic-qe hooks route --json",timeout:5e3,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'npx agentic-qe hooks session-start --session-id "$SESSION_ID" --json',timeout:1e4,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:"npx agentic-qe hooks session-end --save-state --json",timeout:5e3,continueOnError:!0}]},{hooks:[{type:"command",command:"npx agentic-qe hooks post-route --success true --json",timeout:5e3,continueOnError:!0}]}]},d=s.hooks||{};s.hooks=O(d,i);let c=s.env||{};s.env={...c,...j(e)};let m=D(e,t);for(let[u,h]of Object.entries(m))if(u==="_aqePermissions"){let p=s.permissions||{},l=p.allow||[],y=h,C=[...new Set([...l,...y])];s.permissions={...p,allow:C}}else s[u]=h;let a=s.enabledMcpjsonServers||[];return a=a.filter(u=>u!=="aqe"),a.includes("agentic-qe")||a.push("agentic-qe"),s.enabledMcpjsonServers=a,S(r,JSON.stringify(s,null,2),"utf-8"),await re(t),!0}async function re(t){let e=g(t,".claude","hooks");w(e)||Q(e,{recursive:!0});let n=g(e,"cross-phase-memory.yaml");if(w(n))return;let r=[g(ne(import.meta.url.replace("file://","")),"..","..","assets","hooks","cross-phase-memory.yaml"),g(process.cwd(),"assets","hooks","cross-phase-memory.yaml"),g(process.cwd(),"v3","assets","hooks","cross-phase-memory.yaml")];for(let i of r)try{if(w(i)){te(i,n),console.log(" \u2713 Cross-phase memory hooks installed");return}}catch{}S(n,`# Cross-Phase Memory Hooks Configuration
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.0");process.exit(0)}
2
+ import{b as P,c as x,d as R,f as O,g as j,h as D,i as $,j as L,k as N}from"./chunk-ZFBMBCKN.js";import{b as _,d as T}from"./chunk-OKGK7DBT.js";import{a as k,c as q}from"./chunk-KNL3QWVA.js";import{a as v,b as ee}from"./chunk-ZCNVFULO.js";T();import{existsSync as w,mkdirSync as Q,writeFileSync as S,readFileSync as I,copyFileSync as te}from"fs";import{join as g,dirname as ne}from"path";async function M(t,e){if(!e.hooks.claudeCode)return!1;let n=g(t,".claude");w(n)||Q(n,{recursive:!0});let r=g(n,"settings.json"),s={};if(w(r))try{let u=I(r,"utf-8");s=_(u)}catch{s={}}let i={PreToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks guard --file "$TOOL_INPUT_file_path" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-edit --file "$TOOL_INPUT_file_path" --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-command --command "$TOOL_INPUT_command" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-task --description "$TOOL_INPUT_prompt" --json',timeout:5e3,continueOnError:!0}]}],PostToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks post-edit --file "$TOOL_INPUT_file_path" --success --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'npx agentic-qe hooks post-command --command "$TOOL_INPUT_command" --success --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'npx agentic-qe hooks post-task --task-id "$TOOL_RESULT_agent_id" --success --json',timeout:5e3,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:"npx agentic-qe hooks route --json",timeout:5e3,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'npx agentic-qe hooks session-start --session-id "$SESSION_ID" --json',timeout:1e4,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:"npx agentic-qe hooks session-end --save-state --json",timeout:5e3,continueOnError:!0}]},{hooks:[{type:"command",command:"npx agentic-qe hooks post-route --success true --json",timeout:5e3,continueOnError:!0}]}]},d=s.hooks||{};s.hooks=O(d,i);let c=s.env||{};s.env={...c,...j(e)};let m=D(e,t);for(let[u,h]of Object.entries(m))if(u==="_aqePermissions"){let p=s.permissions||{},l=p.allow||[],y=h,C=[...new Set([...l,...y])];s.permissions={...p,allow:C}}else s[u]=h;let a=s.enabledMcpjsonServers||[];return a=a.filter(u=>u!=="aqe"),a.includes("agentic-qe")||a.push("agentic-qe"),s.enabledMcpjsonServers=a,S(r,JSON.stringify(s,null,2),"utf-8"),await re(t),!0}async function re(t){let e=g(t,".claude","hooks");w(e)||Q(e,{recursive:!0});let n=g(e,"cross-phase-memory.yaml");if(w(n))return;let r=[g(ne(import.meta.url.replace("file://","")),"..","..","assets","hooks","cross-phase-memory.yaml"),g(process.cwd(),"assets","hooks","cross-phase-memory.yaml"),g(process.cwd(),"v3","assets","hooks","cross-phase-memory.yaml")];for(let i of r)try{if(w(i)){te(i,n),console.log(" \u2713 Cross-phase memory hooks installed");return}}catch{}S(n,`# Cross-Phase Memory Hooks Configuration
3
3
  # Generated by aqe init
4
4
  # See: https://github.com/anthropics/agentic-qe/docs/cross-phase-memory.md
5
5
 
@@ -276,7 +276,7 @@ aqe init --auto
276
276
  `).run("aqe_version",JSON.stringify(e),i),s.prepare(`
277
277
  INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
278
278
  VALUES (?, '_system', ?, ?)
279
- `).run("init_timestamp",JSON.stringify(new Date().toISOString()),i),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(i){return s.close(),console.warn(` \u26A0 Could not write version: ${k(i)}`),!1}}catch(r){return console.warn(` \u26A0 Could not open memory.db: ${k(r)}`),!1}}async function W(t){let e=null;try{e=(await import("./better-sqlite3-SPABZYYQ.js")).default}catch{throw new Error(`SQLite persistence REQUIRED but better-sqlite3 is not installed.
279
+ `).run("init_timestamp",JSON.stringify(new Date().toISOString()),i),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(i){return s.close(),console.warn(` \u26A0 Could not write version: ${k(i)}`),!1}}catch(r){return console.warn(` \u26A0 Could not open memory.db: ${k(r)}`),!1}}async function W(t){let e=null;try{e=(await import("./better-sqlite3-Y6GX6CGB.js")).default}catch{throw new Error(`SQLite persistence REQUIRED but better-sqlite3 is not installed.
280
280
  Install it with: npm install better-sqlite3
281
281
  If you see native compilation errors, ensure build tools are installed:
282
282
  - macOS: xcode-select --install
@@ -302,7 +302,7 @@ Database path: ${r}
302
302
  Ensure the directory is writable and has sufficient disk space.`)}}async function G(t){let e=o(t,".agentic-qe","memory.db");if(!f(e))return!1;try{let n=v(e),r=n.prepare(`
303
303
  SELECT COUNT(*) as count FROM kv_store
304
304
  WHERE namespace = 'code-intelligence:kg'
305
- `).get();return n.close(),r.count>0}catch{return!1}}async function V(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-LTUOUHO7.js"),{InMemoryBackend:n}=await import("./memory-backend-RW2OPAJU.js"),r=new n;await r.initialize();let s=new e(r,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0}),d=await(await import("fast-glob")).default(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:t,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"]}),c=await s.index({paths:d.map(m=>o(t,m)),incremental:!1,includeTests:!0});return s.destroy(),c.success?{status:"indexed",entries:c.value.nodesCreated+c.value.edgesCreated}:{status:"error",entries:0}}catch(e){return console.warn("Code intelligence scan warning:",k(e)),{status:"skipped",entries:0}}}async function B(t){let e=o(t,".agentic-qe","memory.db");try{let n=v(e),r=n.prepare(`
305
+ `).get();return n.close(),r.count>0}catch{return!1}}async function V(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-V4G5J5B7.js"),{InMemoryBackend:n}=await import("./memory-backend-HPGJ5YDQ.js"),r=new n;await r.initialize();let s=new e(r,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0}),d=await(await import("fast-glob")).default(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:t,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"]}),c=await s.index({paths:d.map(m=>o(t,m)),incremental:!1,includeTests:!0});return s.destroy(),c.success?{status:"indexed",entries:c.value.nodesCreated+c.value.edgesCreated}:{status:"error",entries:0}}catch(e){return console.warn("Code intelligence scan warning:",k(e)),{status:"skipped",entries:0}}}async function B(t){let e=o(t,".agentic-qe","memory.db");try{let n=v(e),r=n.prepare(`
306
306
  SELECT COUNT(*) as count FROM kv_store
307
307
  WHERE namespace LIKE 'code-intelligence:kg%'
308
308
  `).get();return n.close(),r.count}catch{return 0}}async function H(t,e,n){if(!e.learning.enabled)return 0;let r=o(t,".agentic-qe","data");f(r)||b(r,{recursive:!0});let s=o(r,"hnsw");f(s)||b(s,{recursive:!0});let i=o(r,"learning-config.json"),d={embeddingModel:e.learning.embeddingModel,hnswConfig:e.learning.hnswConfig,qualityThreshold:e.learning.qualityThreshold,promotionThreshold:e.learning.promotionThreshold,databasePath:o(r,"memory.db"),hnswIndexPath:o(s,"index.bin"),initialized:new Date().toISOString()};E(i,JSON.stringify(d,null,2),"utf-8");let c=0;if(e.learning.pretrainedPatterns&&n){let m=n,a=new Map;for(let p of m.patterns){let l=p.domain||"general";a.has(l)||a.set(l,[]),a.get(l).push(p)}let u=o(r,"pretrained-index.json"),h={version:m.version,totalPatterns:m.statistics.totalPatterns,domains:Array.from(a.entries()).map(([p,l])=>({name:p,patternCount:l.length})),loadedAt:new Date().toISOString()};E(u,JSON.stringify(h,null,2),"utf-8");for(let[p,l]of a){let y=o(r,"patterns",p);f(y)||b(y,{recursive:!0});let C=o(y,"patterns.json");E(C,JSON.stringify(l,null,2),"utf-8"),c+=l.length}return c}return 0}async function J(t,e){if(!e.workers.daemonAutoStart||e.workers.enabled.length===0)return 0;let n=o(t,".agentic-qe","workers");f(n)||b(n,{recursive:!0});let r={},s={"pattern-consolidator":6e4,"coverage-gap-scanner":3e5,"flaky-test-detector":6e5,"routing-accuracy-monitor":12e4};for(let a of e.workers.enabled)r[a]={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,lastRun:null,status:"pending"};let i=o(n,"registry.json"),d={version:e.version,maxConcurrent:e.workers.maxConcurrent,workers:r,createdAt:new Date().toISOString(),daemonPid:null};E(i,JSON.stringify(d,null,2),"utf-8");for(let a of e.workers.enabled){let u=o(n,`${a}.json`),h={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,projectRoot:t,dataDir:o(t,".agentic-qe","data"),createdAt:new Date().toISOString()};E(u,JSON.stringify(h,null,2),"utf-8")}let c=o(n,"start-daemon.cjs");return E(c,`#!/usr/bin/env node
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.36");process.exit(0)}
2
- import{a as n}from"./chunk-QH7K2UPP.js";import{a as o}from"./chunk-6M44C43I.js";import{a,e as c}from"./chunk-IF4ZZ2HD.js";c();var M=a.CLEANUP_INTERVAL_MS,y=".agentic-qe/memory.db";async function d(r,t=!0){let e;switch(r.type){case"memory":e=new o;break;case"sqlite":e=new n({sqlite:r.sqlite,enableFallback:!0});break;case"agentdb":e=new n({sqlite:{path:r.agentdb?.path??y},enableFallback:!0});break;case"hybrid":e=new n(r.hybrid);break;default:throw new Error(`Unknown memory backend type: ${r.type}`)}return t&&await e.initialize(),{backend:e,type:r.type,initialized:t}}async function u(r=!0){let t=process.env.AQE_MEMORY_BACKEND??"memory",e=process.env.AQE_MEMORY_PATH??".agentic-qe",i={type:t,sqlite:{path:`${e}/memory.db`,walMode:!0},agentdb:{path:`${e}/memory.db`},hybrid:{enableFallback:!0,sqlite:{path:`${e}/memory.db`}}};return d(i,r)}export{d as a,u as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.0");process.exit(0)}
2
+ import{a as n}from"./chunk-LQ3TA22E.js";import{a as o}from"./chunk-4UUDFWOP.js";import{a,e as c}from"./chunk-NT4PI5HI.js";c();var M=a.CLEANUP_INTERVAL_MS,y=".agentic-qe/memory.db";async function d(r,t=!0){let e;switch(r.type){case"memory":e=new o;break;case"sqlite":e=new n({sqlite:r.sqlite,enableFallback:!0});break;case"agentdb":e=new n({sqlite:{path:r.agentdb?.path??y},enableFallback:!0});break;case"hybrid":e=new n(r.hybrid);break;default:throw new Error(`Unknown memory backend type: ${r.type}`)}return t&&await e.initialize(),{backend:e,type:r.type,initialized:t}}async function u(r=!0){let t=process.env.AQE_MEMORY_BACKEND??"memory",e=process.env.AQE_MEMORY_PATH??".agentic-qe",i={type:t,sqlite:{path:`${e}/memory.db`,walMode:!0},agentdb:{path:`${e}/memory.db`},hybrid:{enableFallback:!0,sqlite:{path:`${e}/memory.db`}}};return d(i,r)}export{d as a,u as b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.36");process.exit(0)}
2
- import{a as o,e as p}from"./chunk-IF4ZZ2HD.js";import{a as l,d}from"./chunk-KI6RXKP4.js";d();p();var u=class{store=new Map;vectors=new Map;cleanupInterval;async initialize(){this.cleanupInterval=setInterval(()=>this.cleanup(),o.CLEANUP_INTERVAL_MS),this.cleanupInterval.unref&&this.cleanupInterval.unref()}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.store.clear(),this.vectors.clear()}async set(t,r,e){let s={value:r,namespace:e?.namespace??"default",createdAt:Date.now()};e?.ttl&&(s.expiresAt=Date.now()+e.ttl*o.TTL_MULTIPLIER_MS);let n=this.buildKey(t,e?.namespace);this.store.set(n,s)}async get(t,r){let e=this.buildKey(t,r?.namespace),s=this.store.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.store.delete(e);return}return s.value}}async delete(t,r){let e=this.buildKey(t,r?.namespace);return this.store.delete(e)}async has(t,r){return await this.get(t,r)!==void 0}async search(t,r=o.DEFAULT_SEARCH_LIMIT,e){let s=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(s.replace(/\*/g,".*")),i=[],c=e?.namespace?`${e.namespace}:`:void 0;for(let a of this.store.keys())if(!(c&&!a.startsWith(c))&&n.test(a)&&(i.push(a),i.length>=r))break;return i}async vectorSearch(t,r){let e=[];for(let[s,n]of this.vectors.entries()){let i=l(t,n.embedding);e.push({key:s,score:i,metadata:n.metadata})}return e.sort((s,n)=>n.score-s.score).slice(0,r)}async storeVector(t,r,e){this.vectors.set(t,{embedding:r,metadata:e})}buildKey(t,r){return r?`${r}:${t}`:t}cleanup(){let t=Date.now();for(let[r,e]of this.store.entries())e.expiresAt&&t>e.expiresAt&&this.store.delete(r)}getStats(){return{entries:this.store.size,vectors:this.vectors.size}}async clear(t){if(t){let r=`${t}:`;for(let e of this.store.keys())e.startsWith(r)&&this.store.delete(e)}else this.store.clear()}async count(t){let r=0,e=`${t}:`;for(let s of this.store.keys())if(s.startsWith(e)){let n=this.store.get(s);n&&(!n.expiresAt||Date.now()<=n.expiresAt)&&r++}return r}async hasCodeIntelligenceIndex(){return await this.count("code-intelligence:kg")>0}};export{u as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.0");process.exit(0)}
2
+ import{a as o,e as p}from"./chunk-NT4PI5HI.js";import{a as l,d}from"./chunk-66GIKUI2.js";d();p();var u=class{store=new Map;vectors=new Map;cleanupInterval;async initialize(){this.cleanupInterval=setInterval(()=>this.cleanup(),o.CLEANUP_INTERVAL_MS),this.cleanupInterval.unref&&this.cleanupInterval.unref()}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.store.clear(),this.vectors.clear()}async set(t,r,e){let s={value:r,namespace:e?.namespace??"default",createdAt:Date.now()};e?.ttl&&(s.expiresAt=Date.now()+e.ttl*o.TTL_MULTIPLIER_MS);let n=this.buildKey(t,e?.namespace);this.store.set(n,s)}async get(t,r){let e=this.buildKey(t,r?.namespace),s=this.store.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.store.delete(e);return}return s.value}}async delete(t,r){let e=this.buildKey(t,r?.namespace);return this.store.delete(e)}async has(t,r){return await this.get(t,r)!==void 0}async search(t,r=o.DEFAULT_SEARCH_LIMIT,e){let s=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(s.replace(/\*/g,".*")),i=[],c=e?.namespace?`${e.namespace}:`:void 0;for(let a of this.store.keys())if(!(c&&!a.startsWith(c))&&n.test(a)&&(i.push(a),i.length>=r))break;return i}async vectorSearch(t,r){let e=[];for(let[s,n]of this.vectors.entries()){let i=l(t,n.embedding);e.push({key:s,score:i,metadata:n.metadata})}return e.sort((s,n)=>n.score-s.score).slice(0,r)}async storeVector(t,r,e){this.vectors.set(t,{embedding:r,metadata:e})}buildKey(t,r){return r?`${r}:${t}`:t}cleanup(){let t=Date.now();for(let[r,e]of this.store.entries())e.expiresAt&&t>e.expiresAt&&this.store.delete(r)}getStats(){return{entries:this.store.size,vectors:this.vectors.size}}async clear(t){if(t){let r=`${t}:`;for(let e of this.store.keys())e.startsWith(r)&&this.store.delete(e)}else this.store.clear()}async count(t){let r=0,e=`${t}:`;for(let s of this.store.keys())if(s.startsWith(e)){let n=this.store.get(s);n&&(!n.expiresAt||Date.now()<=n.expiresAt)&&r++}return r}async hasCodeIntelligenceIndex(){return await this.count("code-intelligence:kg")>0}};export{u as a};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.36");process.exit(0)}
2
- import{a as w,b as A,c as O,e as D,f as z}from"./chunk-QAGAEAKM.js";import{b as S,d as $}from"./chunk-HOZNVDFF.js";import{a as N,c as F}from"./chunk-O4C3JEOR.js";import{i as v}from"./chunk-NKA3X6VT.js";import*as I from"node:path";z();$();var P=["function","module","test","file","class"],L=["calls","imports","tests","depends_on","covers"],b=class{ensureSchema(e){e.transaction(()=>{e.exec(w),e.exec(A),e.exec(O)})()}schemaExists(e){return D(e)}getNodeTypes(){return P}getEdgeTypes(){return L}isValidNodeType(e){return P.includes(e)}isValidEdgeType(e){return L.includes(e)}getStats(e){if(!this.schemaExists(e))return{nodeCount:0,edgeCount:0};let t=e.prepare("SELECT COUNT(*) as count FROM hypergraph_nodes").get().count,r=e.prepare("SELECT COUNT(*) as count FROM hypergraph_edges").get().count;return{nodeCount:t,edgeCount:r}}dropSchema(e){let t=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_nodes").get()?.cnt??0,r=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_edges").get()?.cnt??0;if(t>0||r>0)throw new Error(`REFUSING to drop hypergraph schema: tables contain data (${t} nodes, ${r} edges). Backup and manually drop if needed.`);e.transaction(()=>{e.exec("DROP TABLE IF EXISTS hypergraph_edges"),e.exec("DROP TABLE IF EXISTS hypergraph_nodes")})()}};function C(n){return{id:n.id,type:n.type,name:n.name,file_path:n.filePath??null,line_start:n.lineStart??null,line_end:n.lineEnd??null,complexity:n.complexity??null,coverage:n.coverage??null,metadata:n.metadata?JSON.stringify(n.metadata):null,embedding:n.embedding?U(n.embedding):null}}function T(n){return{id:n.id,type:n.type,name:n.name,filePath:n.file_path??void 0,lineStart:n.line_start??void 0,lineEnd:n.line_end??void 0,complexity:n.complexity??void 0,coverage:n.coverage??void 0,metadata:n.metadata?S(n.metadata):void 0,embedding:n.embedding?W(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function M(n){return{id:n.id,source_id:n.sourceId,target_id:n.targetId,type:n.type,weight:n.weight??1,properties:n.properties?JSON.stringify(n.properties):null}}function H(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?S(n.properties):void 0,createdAt:n.created_at}}function x(n,e,t){return`${n}--${t}-->${e}`}function U(n){let e=Buffer.alloc(n.length*4);for(let t=0;t<n.length;t++)e.writeFloatLE(n[t],t*4);return e}function W(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}F();var B={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},R=class{config;schemaManager;initialized=!1;constructor(e){this.config={...B,...e},this.schemaManager=new b}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=v(),r={id:t,...e},s=C(r);return this.config.db.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.0");process.exit(0)}
2
+ import{a as w,b as A,c as O,e as D,f as z}from"./chunk-TEJPHJMW.js";import{b as S,d as $}from"./chunk-OKGK7DBT.js";import{a as N,c as F}from"./chunk-KNL3QWVA.js";import{i as v}from"./chunk-MJBXQXSX.js";import*as I from"node:path";z();$();var P=["function","module","test","file","class"],L=["calls","imports","tests","depends_on","covers"],b=class{ensureSchema(e){e.transaction(()=>{e.exec(w),e.exec(A),e.exec(O)})()}schemaExists(e){return D(e)}getNodeTypes(){return P}getEdgeTypes(){return L}isValidNodeType(e){return P.includes(e)}isValidEdgeType(e){return L.includes(e)}getStats(e){if(!this.schemaExists(e))return{nodeCount:0,edgeCount:0};let t=e.prepare("SELECT COUNT(*) as count FROM hypergraph_nodes").get().count,r=e.prepare("SELECT COUNT(*) as count FROM hypergraph_edges").get().count;return{nodeCount:t,edgeCount:r}}dropSchema(e){let t=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_nodes").get()?.cnt??0,r=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_edges").get()?.cnt??0;if(t>0||r>0)throw new Error(`REFUSING to drop hypergraph schema: tables contain data (${t} nodes, ${r} edges). Backup and manually drop if needed.`);e.transaction(()=>{e.exec("DROP TABLE IF EXISTS hypergraph_edges"),e.exec("DROP TABLE IF EXISTS hypergraph_nodes")})()}};function C(n){return{id:n.id,type:n.type,name:n.name,file_path:n.filePath??null,line_start:n.lineStart??null,line_end:n.lineEnd??null,complexity:n.complexity??null,coverage:n.coverage??null,metadata:n.metadata?JSON.stringify(n.metadata):null,embedding:n.embedding?U(n.embedding):null}}function T(n){return{id:n.id,type:n.type,name:n.name,filePath:n.file_path??void 0,lineStart:n.line_start??void 0,lineEnd:n.line_end??void 0,complexity:n.complexity??void 0,coverage:n.coverage??void 0,metadata:n.metadata?S(n.metadata):void 0,embedding:n.embedding?W(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function M(n){return{id:n.id,source_id:n.sourceId,target_id:n.targetId,type:n.type,weight:n.weight??1,properties:n.properties?JSON.stringify(n.properties):null}}function H(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?S(n.properties):void 0,createdAt:n.created_at}}function x(n,e,t){return`${n}--${t}-->${e}`}function U(n){let e=Buffer.alloc(n.length*4);for(let t=0;t<n.length;t++)e.writeFloatLE(n[t],t*4);return e}function W(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}F();var B={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},R=class{config;schemaManager;initialized=!1;constructor(e){this.config={...B,...e},this.schemaManager=new b}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=v(),r={id:t,...e},s=C(r);return this.config.db.prepare(`
3
3
  INSERT INTO hypergraph_nodes (id, type, name, file_path, line_start, line_end, complexity, coverage, metadata, embedding)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5
5
  `).run(s.id,s.type,s.name,s.file_path,s.line_start,s.line_end,s.complexity,s.coverage,s.metadata,s.embedding),t}async addEdge(e){this.ensureInitialized();let t=x(e.sourceId,e.targetId,e.type),r={id:t,...e},s=M(r);return this.config.db.prepare(`
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.36");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.0");process.exit(0)}
2
2
  var h=Object.create;var e=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var k=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty;var m=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')}),n=a=>b=>{var c=a[b];if(c)return c();throw new Error("Module not found in bundle: "+b)};var o=(a,b)=>()=>(a&&(b=a(a=0)),b);var p=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports),q=(a,b)=>{for(var c in b)e(a,c,{get:b[c],enumerable:!0})},g=(a,b,c,f)=>{if(b&&typeof b=="object"||typeof b=="function")for(let d of j(b))!l.call(a,d)&&d!==c&&e(a,d,{get:()=>b[d],enumerable:!(f=i(b,d))||f.enumerable});return a};var r=(a,b,c)=>(c=a!=null?h(k(a)):{},g(b||!a||!a.__esModule?e(c,"default",{value:a,enumerable:!0}):c,a)),s=a=>g(e({},"__esModule",{value:!0}),a);export{m as a,n as b,o as c,p as d,q as e,r as f,s as g};