agentic-qe 3.10.8 → 3.10.9

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 (354) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +37 -1
  3. package/dist/cli/bundle.js +5 -5
  4. package/dist/cli/chunks/adapter-TRSV37EA.js +2 -0
  5. package/dist/cli/chunks/{agent-booster-wasm-4JSL6LF6.js → agent-booster-wasm-RPAOJXZ3.js} +2 -2
  6. package/dist/cli/chunks/{agent-handler-6YOFH7KL.js → agent-handler-SMD5CAS6.js} +2 -2
  7. package/dist/cli/chunks/{agent-memory-branch-O3IBK4BY.js → agent-memory-branch-3IOQIQ7Y.js} +2 -2
  8. package/dist/cli/chunks/aqe-learning-engine-CVJRJOSO.js +2 -0
  9. package/dist/cli/chunks/{arena-KLGRZTTU.js → arena-AP2J62WO.js} +4 -4
  10. package/dist/cli/chunks/{arena-BLCAZNAY.js → arena-GT3D6EAO.js} +2 -2
  11. package/dist/cli/chunks/{audit-FKKLR22S.js → audit-Q3GJ5354.js} +2 -2
  12. package/dist/cli/chunks/base-BX4A2D4V.js +2 -0
  13. package/dist/cli/chunks/{hnswlib-node-PNPV64M3.js → better-sqlite3-6A6EAXAT.js} +2 -2
  14. package/dist/cli/chunks/{brain-handler-YTGYC2QW.js → brain-handler-2Z4ILQF3.js} +3 -3
  15. package/dist/cli/chunks/{branch-enumerator-KIIBEJ5S.js → branch-enumerator-EZWGL4UM.js} +2 -2
  16. package/dist/cli/chunks/{browser-7YZLTV2C.js → browser-YZELFPLJ.js} +2 -2
  17. package/dist/cli/chunks/browser-workflow-O3RL7EYT.js +2 -0
  18. package/dist/cli/chunks/{chunk-DDMKCHYT.js → chunk-246Z3PH6.js} +2 -2
  19. package/dist/cli/chunks/{chunk-DI7REPYC.js → chunk-2I5QLMQF.js} +2 -2
  20. package/dist/cli/chunks/{chunk-D7IH2A3C.js → chunk-2K2X75UF.js} +2 -2
  21. package/dist/cli/chunks/{chunk-Y4XTPEAC.js → chunk-2WRVNEIR.js} +2 -2
  22. package/dist/cli/chunks/{chunk-FXPAGKVS.js → chunk-2WSEJHFQ.js} +1 -1
  23. package/dist/cli/chunks/{chunk-JQBD4JO2.js → chunk-352W5G4G.js} +2 -2
  24. package/dist/cli/chunks/{chunk-OZDRAKFF.js → chunk-3HT4CT6F.js} +2 -2
  25. package/dist/cli/chunks/{chunk-KTEWRRDZ.js → chunk-3YKJGKOY.js} +4 -4
  26. package/dist/cli/chunks/{chunk-4G2GTX2V.js → chunk-42FBJF73.js} +1 -1
  27. package/dist/cli/chunks/{chunk-MSWBVPVQ.js → chunk-4BB75U6N.js} +2 -2
  28. package/dist/cli/chunks/{chunk-77BVW2CT.js → chunk-4D3LVXUD.js} +2 -2
  29. package/dist/cli/chunks/{chunk-RXWPYY6H.js → chunk-4EJTE5TL.js} +1 -1
  30. package/dist/cli/chunks/{chunk-CP4CSI5R.js → chunk-4MUZGQPE.js} +2 -2
  31. package/dist/cli/chunks/{chunk-CCUUTTTJ.js → chunk-57XCLC55.js} +2 -2
  32. package/dist/cli/chunks/{chunk-ZSMHQENA.js → chunk-5HLOQEKL.js} +1 -1
  33. package/dist/cli/chunks/{chunk-MTWBYHMS.js → chunk-5U5SEO7C.js} +2 -2
  34. package/dist/cli/chunks/{chunk-FWQZZ22V.js → chunk-5X73HV2P.js} +1 -1
  35. package/dist/cli/chunks/{chunk-YUK4KU2B.js → chunk-62MH7QAQ.js} +2 -2
  36. package/dist/cli/chunks/{chunk-WKLI5Z3L.js → chunk-6HPI6YX3.js} +2 -2
  37. package/dist/cli/chunks/{chunk-6B3COND2.js → chunk-6TR3OM7C.js} +2 -2
  38. package/dist/cli/chunks/{chunk-Z57UERQZ.js → chunk-757YHKIJ.js} +2 -2
  39. package/dist/cli/chunks/{chunk-HEC2UWY3.js → chunk-7C5HI4ZA.js} +4 -4
  40. package/dist/cli/chunks/{chunk-O75ODKCX.js → chunk-7D5JE46U.js} +2 -2
  41. package/dist/cli/chunks/{chunk-7NKVEEXD.js → chunk-7NT34MLU.js} +1 -1
  42. package/dist/cli/chunks/{chunk-LZVKR7HV.js → chunk-7PYEJ4NV.js} +2 -2
  43. package/dist/cli/chunks/{chunk-PG7KISET.js → chunk-7S6D5K4X.js} +2 -2
  44. package/dist/cli/chunks/{chunk-SDGRU6SG.js → chunk-ABJPFKHE.js} +1 -1
  45. package/dist/cli/chunks/{chunk-4AG2TQEF.js → chunk-ABVBHH7P.js} +3 -3
  46. package/dist/cli/chunks/{chunk-ALFF4AAM.js → chunk-AHUX7QSE.js} +2 -2
  47. package/dist/cli/chunks/{chunk-54PBHRRW.js → chunk-AU4DQMLJ.js} +4 -4
  48. package/dist/cli/chunks/{chunk-HWJEHXPQ.js → chunk-BG2FN5K2.js} +2 -2
  49. package/dist/cli/chunks/{chunk-SSRMFU4P.js → chunk-BM52ZEAD.js} +2 -2
  50. package/dist/cli/chunks/{chunk-LJEO5R32.js → chunk-BSMUT672.js} +2 -2
  51. package/dist/cli/chunks/{chunk-NL4EKO2J.js → chunk-BVEQPMOF.js} +2 -2
  52. package/dist/cli/chunks/{chunk-PTPGYUT2.js → chunk-BYVARYGB.js} +2 -2
  53. package/dist/cli/chunks/{chunk-UU422SST.js → chunk-C6GQIUKW.js} +2 -2
  54. package/dist/cli/chunks/{chunk-LBR5FXPD.js → chunk-C6JULAWA.js} +2 -2
  55. package/dist/cli/chunks/{chunk-XNFYQRJ2.js → chunk-CDJIYJIA.js} +1 -1
  56. package/dist/cli/chunks/{chunk-2UL4UK6V.js → chunk-CLJNAQXB.js} +2 -2
  57. package/dist/cli/chunks/{chunk-X4CHPEOQ.js → chunk-CLSHSVMY.js} +1 -1
  58. package/dist/cli/chunks/{chunk-SDVL5TZK.js → chunk-CREORFJV.js} +1 -1
  59. package/dist/cli/chunks/{chunk-T2Z3M6HA.js → chunk-CVRTXIYP.js} +1 -1
  60. package/dist/cli/chunks/{chunk-OIU6PKLF.js → chunk-CWRSQQHV.js} +2 -2
  61. package/dist/cli/chunks/{chunk-S6PGWJDK.js → chunk-D2JCSWYM.js} +2 -2
  62. package/dist/cli/chunks/{chunk-4OHLPG6B.js → chunk-D7NWDUY3.js} +2 -2
  63. package/dist/cli/chunks/{chunk-ON6C2OYG.js → chunk-DK6WWNCL.js} +2 -2
  64. package/dist/cli/chunks/{chunk-LCDMB5SP.js → chunk-DNE6MVNA.js} +1 -1
  65. package/dist/cli/chunks/{chunk-X3NEQ3SL.js → chunk-DZWZASDV.js} +1 -1
  66. package/dist/cli/chunks/{chunk-RNJRKFMX.js → chunk-EL6F72JN.js} +2 -2
  67. package/dist/cli/chunks/{chunk-XLQX77KP.js → chunk-EYGRNXQT.js} +1 -1
  68. package/dist/cli/chunks/{chunk-DNEYBK7X.js → chunk-FALB6Z2Y.js} +1 -1
  69. package/dist/cli/chunks/{chunk-PRYSWF6F.js → chunk-FD37QFXW.js} +1 -1
  70. package/dist/cli/chunks/{chunk-K5Y64X2U.js → chunk-G4KVGUQN.js} +2 -2
  71. package/dist/cli/chunks/{chunk-QNNH5TDV.js → chunk-G7V2HDTH.js} +3 -3
  72. package/dist/cli/chunks/{chunk-WYAHOUK2.js → chunk-GPALZJD3.js} +1 -1
  73. package/dist/cli/chunks/{chunk-AGQIJWAD.js → chunk-H4SHHYRD.js} +2 -2
  74. package/dist/cli/chunks/{chunk-Q32LITZL.js → chunk-H7AQ7M3J.js} +1 -1
  75. package/dist/cli/chunks/{chunk-GDHJZPNC.js → chunk-HAC7NB6R.js} +2 -2
  76. package/dist/cli/chunks/{chunk-YMJ5AVVU.js → chunk-HGKZOSAI.js} +1 -1
  77. package/dist/cli/chunks/{chunk-VKLPSPPI.js → chunk-HQZX4XYH.js} +2 -2
  78. package/dist/cli/chunks/{chunk-4B676LUC.js → chunk-HZSYCVLC.js} +2 -2
  79. package/dist/cli/chunks/{chunk-YQYTQRTR.js → chunk-I5C7O5IQ.js} +2 -2
  80. package/dist/cli/chunks/{chunk-7LHN6WBX.js → chunk-I7RTTJH5.js} +2 -2
  81. package/dist/cli/chunks/{chunk-OK6CSJOX.js → chunk-ILPIH4Z6.js} +1 -1
  82. package/dist/cli/chunks/{chunk-6R6RC6YJ.js → chunk-IR7PJUO7.js} +2 -2
  83. package/dist/cli/chunks/{chunk-BALWMVCX.js → chunk-J6GKKXCP.js} +2 -2
  84. package/dist/cli/chunks/{chunk-34LWJDCM.js → chunk-JZNMU63B.js} +2 -2
  85. package/dist/cli/chunks/{chunk-C6TUX7YJ.js → chunk-K23XK33X.js} +2 -2
  86. package/dist/cli/chunks/{chunk-GHIHW3IE.js → chunk-KAMFT25W.js} +2 -2
  87. package/dist/cli/chunks/{chunk-OV3ESWN4.js → chunk-KJA5A3TV.js} +2 -2
  88. package/dist/cli/chunks/{chunk-HE3KLHNO.js → chunk-KRAWWBX5.js} +2 -2
  89. package/dist/cli/chunks/{chunk-LT4OZHMK.js → chunk-L5IO7QNO.js} +2 -2
  90. package/dist/cli/chunks/{chunk-OLOKPY5O.js → chunk-L5NEEGKO.js} +2 -2
  91. package/dist/cli/chunks/{chunk-IFQPGBKQ.js → chunk-LHKQW72O.js} +1 -1
  92. package/dist/cli/chunks/{chunk-6B32USSC.js → chunk-LT6QHDPK.js} +2 -2
  93. package/dist/cli/chunks/{chunk-B3B5QZYN.js → chunk-MDED3HJI.js} +2 -2
  94. package/dist/cli/chunks/{chunk-FPEFIJQ6.js → chunk-NLUWPS2H.js} +3 -3
  95. package/dist/cli/chunks/{chunk-Q7B7T4YK.js → chunk-NMQEU4BG.js} +2 -2
  96. package/dist/cli/chunks/{chunk-4IGSL7CX.js → chunk-NOWGQ6YZ.js} +1 -1
  97. package/dist/cli/chunks/{chunk-M5PBVK3V.js → chunk-NYBAH76S.js} +3 -3
  98. package/dist/cli/chunks/{chunk-LIOK7WBX.js → chunk-O36VC7B7.js} +2 -2
  99. package/dist/cli/chunks/{chunk-WDZT344G.js → chunk-OD4OIPXO.js} +15 -13
  100. package/dist/cli/chunks/{chunk-JZYXYHEE.js → chunk-OF3EMOWN.js} +2 -2
  101. package/dist/cli/chunks/{chunk-2F4VRCT6.js → chunk-OIN3Y4BY.js} +1 -1
  102. package/dist/cli/chunks/chunk-OPKEQYAC.js +2 -0
  103. package/dist/cli/chunks/{chunk-XYXRO7VP.js → chunk-OQUH7657.js} +2 -2
  104. package/dist/cli/chunks/{chunk-R2LWUBET.js → chunk-OSP5AJAB.js} +2 -2
  105. package/dist/cli/chunks/{chunk-XPAH7SEX.js → chunk-PFGH7TWL.js} +2 -2
  106. package/dist/cli/chunks/{chunk-DNC27OP7.js → chunk-PYQZ4OA3.js} +2 -2
  107. package/dist/cli/chunks/{chunk-5KUINS3D.js → chunk-QAP5S7YC.js} +3 -3
  108. package/dist/cli/chunks/{chunk-XKIVOADM.js → chunk-QE3CZGAC.js} +3 -3
  109. package/dist/cli/chunks/{chunk-NKKDO5W4.js → chunk-QFIKEZB5.js} +2 -2
  110. package/dist/cli/chunks/{chunk-5GPOSKGP.js → chunk-QHICG2NI.js} +2 -2
  111. package/dist/cli/chunks/{chunk-HVE3EH36.js → chunk-QHPLU5BU.js} +3 -3
  112. package/dist/cli/chunks/{chunk-XRJH5KXF.js → chunk-QL6ZJ7RV.js} +2 -2
  113. package/dist/cli/chunks/{chunk-3AG2MM7U.js → chunk-QL7OOCPO.js} +2 -2
  114. package/dist/cli/chunks/{chunk-NFZY6ZVY.js → chunk-QWXJRZEH.js} +1 -1
  115. package/dist/cli/chunks/{chunk-E5GUTKET.js → chunk-R2M3RMCN.js} +2 -2
  116. package/dist/cli/chunks/{chunk-2KP5TJS2.js → chunk-RHOBDQXA.js} +2 -2
  117. package/dist/cli/chunks/{chunk-HVFHPDXV.js → chunk-RRSJ7BMF.js} +1 -1
  118. package/dist/cli/chunks/{chunk-KTBBSOZG.js → chunk-RSWQY4NZ.js} +2 -2
  119. package/dist/cli/chunks/{chunk-JITZAJJN.js → chunk-S73EBPI5.js} +2 -2
  120. package/dist/cli/chunks/{chunk-CO6UY7ZU.js → chunk-TIR3Z6TE.js} +1 -1
  121. package/dist/cli/chunks/{chunk-474ZUVGP.js → chunk-TKZABUHO.js} +1 -1
  122. package/dist/cli/chunks/{chunk-2RDWYJJY.js → chunk-TOGD2JH2.js} +2 -2
  123. package/dist/cli/chunks/{chunk-33CLP2NE.js → chunk-TVU6NMO3.js} +3 -3
  124. package/dist/cli/chunks/{chunk-BMSMDD72.js → chunk-TXWUV3S5.js} +2 -2
  125. package/dist/cli/chunks/{chunk-VM5C4DIV.js → chunk-U6TZVACK.js} +2 -2
  126. package/dist/cli/chunks/{chunk-KWKGROPS.js → chunk-UJBIHPU5.js} +1 -1
  127. package/dist/cli/chunks/{chunk-JFTRHS5V.js → chunk-UPGKS6Z3.js} +2 -2
  128. package/dist/cli/chunks/{chunk-H35FNLQJ.js → chunk-UU7OCRZM.js} +2 -2
  129. package/dist/cli/chunks/{chunk-MWAEUJDC.js → chunk-UUA2NVUN.js} +8 -8
  130. package/dist/cli/chunks/{chunk-NWIKNQLJ.js → chunk-UX4UHYLE.js} +1 -1
  131. package/dist/cli/chunks/{chunk-Z4WAJ647.js → chunk-VDL277DX.js} +2 -2
  132. package/dist/cli/chunks/{chunk-VL4MSE3J.js → chunk-VHCHBMZC.js} +2 -2
  133. package/dist/cli/chunks/{chunk-G73PIM7X.js → chunk-VHYNRISI.js} +2 -2
  134. package/dist/cli/chunks/{chunk-TXLLF7XR.js → chunk-VIHFC67B.js} +1 -1
  135. package/dist/cli/chunks/{chunk-QHLENBGB.js → chunk-WOGWIMQK.js} +2 -2
  136. package/dist/cli/chunks/{chunk-H73AA2JI.js → chunk-WPBVLIWQ.js} +10 -10
  137. package/dist/cli/chunks/{chunk-CHPL7TA4.js → chunk-WWGGL3TR.js} +1 -1
  138. package/dist/cli/chunks/{chunk-D7ZVIL3C.js → chunk-X6YUGKMM.js} +1 -1
  139. package/dist/cli/chunks/{chunk-G2J7WGOG.js → chunk-X7677BX3.js} +2 -2
  140. package/dist/cli/chunks/{chunk-GXKCRIHK.js → chunk-XEMP2PNW.js} +2 -2
  141. package/dist/cli/chunks/{chunk-Z7FWPSOK.js → chunk-XLK4GP3I.js} +2 -2
  142. package/dist/cli/chunks/{chunk-YATW2RWQ.js → chunk-XYRJL7YN.js} +2 -2
  143. package/dist/cli/chunks/{chunk-W72CUJRB.js → chunk-YB3PQ3UV.js} +1 -1
  144. package/dist/cli/chunks/{chunk-QHGHWATK.js → chunk-YHFCLJMY.js} +1 -1
  145. package/dist/cli/chunks/{chunk-CDNXXNQM.js → chunk-YQBL5XTM.js} +1 -1
  146. package/dist/cli/chunks/chunk-Z6FRNWQA.js +6 -0
  147. package/dist/cli/chunks/{chunk-NOP5ZJ7E.js → chunk-ZT2DGSIO.js} +2 -2
  148. package/dist/cli/chunks/{chunk-DPSLJ6IW.js → chunk-ZVF7QY4R.js} +1 -1
  149. package/dist/cli/chunks/{ci-2G4BBIQD.js → ci-KDEFR2X3.js} +2 -2
  150. package/dist/cli/chunks/{ci-output-SI3ME52L.js → ci-output-Z3WXRRFI.js} +2 -2
  151. package/dist/cli/chunks/{circuit-breaker-KTICF3EC.js → circuit-breaker-GS44DEW2.js} +2 -2
  152. package/dist/cli/chunks/{claude-flow-setup-F44PULFU.js → claude-flow-setup-OHVMHAAH.js} +2 -2
  153. package/dist/cli/chunks/client-T263ZXVV.js +2 -0
  154. package/dist/cli/chunks/cline-installer-5TCF4MZD.js +4 -0
  155. package/dist/cli/chunks/{code-EDLIBN77.js → code-3KCGTG7Z.js} +2 -2
  156. package/dist/cli/chunks/{code-index-extractor-P4NBWGTV.js → code-index-extractor-LJBI54MZ.js} +2 -2
  157. package/dist/cli/chunks/codex-installer-IB62Z6LA.js +8 -0
  158. package/dist/cli/chunks/{completions-XPCXB5SR.js → completions-JDXX7KKB.js} +2 -2
  159. package/dist/cli/chunks/{complexity-analyzer-LAL5RSB7.js → complexity-analyzer-6JVDXXXP.js} +2 -2
  160. package/dist/cli/chunks/continuedev-installer-PUB45QVR.js +15 -0
  161. package/dist/cli/chunks/copilot-installer-QWJ36P22.js +3 -0
  162. package/dist/cli/chunks/core-handlers-ODKKGCFK.js +2 -0
  163. package/dist/cli/chunks/{cost-tracker-EUJFKHGT.js → cost-tracker-J3KEJDL5.js} +2 -2
  164. package/dist/cli/chunks/{coverage-C75LPZYB.js → coverage-FWKRI2EY.js} +3 -3
  165. package/dist/cli/chunks/cross-domain-router-APU725GC.js +2 -0
  166. package/dist/cli/chunks/cursor-installer-2HYCUCTH.js +3 -0
  167. package/dist/cli/chunks/{daemon-JR2MSTSK.js → daemon-BVP66DIZ.js} +4 -4
  168. package/dist/cli/chunks/{daemon-BPVBZZQO.js → daemon-G3DBRWDQ.js} +3 -3
  169. package/dist/cli/chunks/{dag-attention-scheduler-I5H7DBNU.js → dag-attention-scheduler-2AQLNB4B.js} +2 -2
  170. package/dist/cli/chunks/{detect-O5TMML24.js → detect-RUM5SHNE.js} +2 -2
  171. package/dist/cli/chunks/{dist-node-MDZ6UQ3V.js → dist-node-GX7MJHFT.js} +2 -2
  172. package/dist/cli/chunks/{domain-handler-BGBTZETG.js → domain-handler-OFBGZ2U5.js} +2 -2
  173. package/dist/cli/chunks/{domain-transfer-C2D2IEYV.js → domain-transfer-6CGRPRGR.js} +2 -2
  174. package/dist/cli/chunks/dream-PJ5GKY3J.js +2 -0
  175. package/dist/cli/chunks/{embed-and-insert-pattern-UJREBJF5.js → embed-and-insert-pattern-MUOEVQX2.js} +2 -2
  176. package/dist/cli/chunks/{eval-BDD24HQC.js → eval-SJMG67DE.js} +2 -2
  177. package/dist/cli/chunks/{experience-capture-middleware-KLVXIIYH.js → experience-capture-middleware-ICKN6IXX.js} +3 -3
  178. package/dist/cli/chunks/{fast-paths-5HIKAQZ7.js → fast-paths-HXLBG3J4.js} +2 -2
  179. package/dist/cli/chunks/{feature-flags-YE5SJPDS.js → feature-flags-CRUB2ASU.js} +2 -2
  180. package/dist/cli/chunks/{feature-flags-NM3S7OEW.js → feature-flags-JYZSSQJC.js} +2 -2
  181. package/dist/cli/chunks/{file-discovery-PWRQZNJQ.js → file-discovery-YHHC7NTJ.js} +2 -2
  182. package/dist/cli/chunks/{fleet-UIPKNQX3.js → fleet-2VGDL4YL.js} +3 -3
  183. package/dist/cli/chunks/{gnn-wrapper-GWGKZRTO.js → gnn-wrapper-7ZAGD4S4.js} +2 -2
  184. package/dist/cli/chunks/{heartbeat-handler-GQHJPNAY.js → heartbeat-handler-HAW3JRHN.js} +4 -4
  185. package/dist/cli/chunks/heartbeat-scheduler-4ZHUIW3Q.js +2 -0
  186. package/dist/cli/chunks/hnsw-adapter-UVJJ6TTP.js +2 -0
  187. package/dist/cli/chunks/hnsw-index-K6HS34JZ.js +2 -0
  188. package/dist/cli/chunks/{hnsw-legacy-bridge-NE5JIRG3.js → hnsw-legacy-bridge-BO325POX.js} +2 -2
  189. package/dist/cli/chunks/{better-sqlite3-MROES2Y7.js → hnswlib-node-YTK7S7GL.js} +2 -2
  190. package/dist/cli/chunks/{hooks-3NBBUOB6.js → hooks-HKM3JTFQ.js} +10 -10
  191. package/dist/cli/chunks/hybrid-router-25S7OH2Y.js +2 -0
  192. package/dist/cli/chunks/{hypergraph-engine-6NRFVDV7.js → hypergraph-engine-LGLGHK6B.js} +2 -2
  193. package/dist/cli/chunks/{hypergraph-handler-F3OOGTXF.js → hypergraph-handler-6QDVREZA.js} +3 -3
  194. package/dist/cli/chunks/impact-analyzer-UP4RDMJH.js +2 -0
  195. package/dist/cli/chunks/{init-handler-DOTXTVUI.js → init-handler-XUQ7XHIE.js} +22 -21
  196. package/dist/cli/chunks/init-wizard-2PAJ3GEC.js +2 -0
  197. package/dist/cli/chunks/kernel-7WOQGMMT.js +2 -0
  198. package/dist/cli/chunks/kilocode-installer-6CEZLVIX.js +4 -0
  199. package/dist/cli/chunks/{kiro-installer-WBJDXY7Q.js → kiro-installer-6CJGATOS.js} +4 -4
  200. package/dist/cli/chunks/knowledge-graph-FN2AWHGR.js +2 -0
  201. package/dist/cli/chunks/{learning-BC5N4V3D.js → learning-EIYTYZJY.js} +3 -3
  202. package/dist/cli/chunks/{llm-router-T427WD6R.js → llm-router-J4CI7VHU.js} +4 -4
  203. package/dist/cli/chunks/llm-router-service-C3UPBAS3.js +2 -0
  204. package/dist/cli/chunks/{load-M6SL2O3M.js → load-CQPWGLQQ.js} +2 -2
  205. package/dist/cli/chunks/load-test-PQSGLDXJ.js +2 -0
  206. package/dist/cli/chunks/mcp-THOATWCO.js +2 -0
  207. package/dist/cli/chunks/{memory-FJAO3CSF.js → memory-NZHMHMRK.js} +5 -5
  208. package/dist/cli/chunks/memory-backend-6FR4RT5O.js +2 -0
  209. package/dist/cli/chunks/{memory-handlers-S3W6IQJL.js → memory-handlers-L2J54AQE.js} +2 -2
  210. package/dist/cli/chunks/{multi-model-executor-FYOVZ4OH.js → multi-model-executor-3P5E773H.js} +2 -2
  211. package/dist/cli/chunks/{opencode-installer-APSBE4UR.js → opencode-installer-IRZMKSNG.js} +2 -2
  212. package/dist/cli/chunks/{orchestrator-LN53EQ45.js → orchestrator-UADLXTKP.js} +16 -16
  213. package/dist/cli/chunks/pattern-null-store-B2UX4NZY.js +2 -0
  214. package/dist/cli/chunks/{pipeline-BYWXY2NO.js → pipeline-QEH3XHXJ.js} +2 -2
  215. package/dist/cli/chunks/{platform-CZ774YPS.js → platform-NEZ3NXLT.js} +2 -2
  216. package/dist/cli/chunks/{plugin-72NXRX5Z.js → plugin-O33HR2VO.js} +2 -2
  217. package/dist/cli/chunks/{prime-radiant-advanced-wasm-G4DE6YKJ.js → prime-radiant-advanced-wasm-MBUMFEX7.js} +2 -2
  218. package/dist/cli/chunks/protocol-executor-OQ6SL7SR.js +2 -0
  219. package/dist/cli/chunks/{protocol-handler-UH6CV63V.js → protocol-handler-L455UOUT.js} +2 -2
  220. package/dist/cli/chunks/{prove-V7FAT5HF.js → prove-3XA3SMAA.js} +2 -2
  221. package/dist/cli/chunks/provider-manager-DQWHW2RG.js +2 -0
  222. package/dist/cli/chunks/qe-reasoning-bank-3JS2CZAE.js +2 -0
  223. package/dist/cli/chunks/{quality-N2K62FQM.js → quality-H6Z5JH5B.js} +2 -2
  224. package/dist/cli/chunks/queen-coordinator-KXCWEM3Y.js +2 -0
  225. package/dist/cli/chunks/{real-embeddings-TKHUE2RL.js → real-embeddings-5DNJ4KEM.js} +2 -2
  226. package/dist/cli/chunks/roocode-installer-KHXKR2FK.js +4 -0
  227. package/dist/cli/chunks/router-OVLIKT55.js +2 -0
  228. package/dist/cli/chunks/routing-feedback-2BYCXNXX.js +2 -0
  229. package/dist/cli/chunks/{routing-handler-UUWD4IKG.js → routing-handler-WAMGESEM.js} +2 -2
  230. package/dist/cli/chunks/{ruvector-commands-B4WPTGCI.js → ruvector-commands-4J7XC6XY.js} +2 -2
  231. package/dist/cli/chunks/{rvf-dual-writer-MNRJGNIX.js → rvf-dual-writer-3PZEN6XN.js} +2 -2
  232. package/dist/cli/chunks/{rvf-migration-adapter-P2RDBFA4.js → rvf-migration-adapter-OIUNRQSU.js} +2 -2
  233. package/dist/cli/chunks/{rvf-migration-coordinator-DFESZQSS.js → rvf-migration-coordinator-QZXDI4I5.js} +2 -2
  234. package/dist/cli/chunks/rvf-native-adapter-YNUYOQ5C.js +2 -0
  235. package/dist/cli/chunks/safe-db-6TYYEU7C.js +2 -0
  236. package/dist/cli/chunks/schedule-XVH7RTVY.js +2 -0
  237. package/dist/cli/chunks/scheduler-DHZBN5HA.js +2 -0
  238. package/dist/cli/chunks/{security-MHLTNKFX.js → security-5NY77AMD.js} +3 -3
  239. package/dist/cli/chunks/{shared-rvf-adapter-LR7E2EQI.js → shared-rvf-adapter-MHPUZIMW.js} +2 -2
  240. package/dist/cli/chunks/{shared-rvf-dual-writer-RFFON2F3.js → shared-rvf-dual-writer-ITLDYHCX.js} +2 -2
  241. package/dist/cli/chunks/sqlite-persistence-NR5WXTPN.js +2 -0
  242. package/dist/cli/chunks/{status-handler-ROPTYGQC.js → status-handler-7RBRIXZD.js} +2 -2
  243. package/dist/cli/chunks/{structural-health-YGUFXGJ6.js → structural-health-MQPY6GA6.js} +2 -2
  244. package/dist/cli/chunks/{sync-6JTRTDL3.js → sync-66KCEANE.js} +2 -2
  245. package/dist/cli/chunks/{sync-NZZUMTKC.js → sync-USVQTHKN.js} +2 -2
  246. package/dist/cli/chunks/{task-handler-KYMV3AC6.js → task-handler-4UI4FPPW.js} +2 -2
  247. package/dist/cli/chunks/{task-handlers-Z63YBQVU.js → task-handlers-KRII3GVV.js} +3 -3
  248. package/dist/cli/chunks/{test-O6BQ7FGP.js → test-JHN2MVEG.js} +4 -4
  249. package/dist/cli/chunks/{test-scheduling-T3IOXEFI.js → test-scheduling-ZWTEGS3S.js} +3 -3
  250. package/dist/cli/chunks/{token-bootstrap-CTI2ULJF.js → token-bootstrap-YWXL6AS5.js} +2 -2
  251. package/dist/cli/chunks/{token-usage-TNQTNAVT.js → token-usage-INII2XM3.js} +2 -2
  252. package/dist/cli/chunks/{transformers-CJQDNQER.js → transformers-DVFGDNZC.js} +2 -2
  253. package/dist/cli/chunks/{tree-sitter-wasm-parser-RBZWLEVQ.js → tree-sitter-wasm-parser-W2XJT3XF.js} +2 -2
  254. package/dist/cli/chunks/{types-OMFCO364.js → types-GBZ5Q2GP.js} +2 -2
  255. package/dist/cli/chunks/unified-memory-WJEZ5YAK.js +2 -0
  256. package/dist/cli/chunks/unified-memory-hnsw-6ZA2PMYO.js +2 -0
  257. package/dist/cli/chunks/unified-persistence-SWH6R7MA.js +2 -0
  258. package/dist/cli/chunks/{upgrade-KRVOYWN3.js → upgrade-2JEXEGQX.js} +2 -2
  259. package/dist/cli/chunks/{validate-32FKHMKQ.js → validate-GDCM5YTS.js} +2 -2
  260. package/dist/cli/chunks/{validate-swarm-45RPBPPH.js → validate-swarm-QZ5RSJEU.js} +2 -2
  261. package/dist/cli/chunks/{vibium-LCTNDCKK.js → vibium-I5BMT734.js} +2 -2
  262. package/dist/cli/chunks/visual-security-PH5JQZCZ.js +2 -0
  263. package/dist/cli/chunks/{web-tree-sitter-FX2EFCLH.js → web-tree-sitter-3QY2LMLP.js} +2 -2
  264. package/dist/cli/chunks/windsurf-installer-V7OBPLOB.js +7 -0
  265. package/dist/cli/chunks/{witness-chain-YG2UWTYZ.js → witness-chain-BNJ4VSZX.js} +2 -2
  266. package/dist/cli/chunks/witness-chain-WYMBNGSL.js +2 -0
  267. package/dist/cli/chunks/{workflow-AEJ37RNV.js → workflow-3FJSNLPI.js} +4 -4
  268. package/dist/cli/chunks/workflow-orchestrator-56JIXCI4.js +2 -0
  269. package/dist/cli/chunks/{wrappers-GSU6VNU6.js → wrappers-ERTQNIPK.js} +2 -2
  270. package/dist/cli/commands/mcp.js +28 -28
  271. package/dist/cli/handlers/init-handler.d.ts +2 -0
  272. package/dist/cli/handlers/init-handler.js +22 -1
  273. package/dist/init/cline-installer.d.ts +6 -0
  274. package/dist/init/cline-installer.js +3 -1
  275. package/dist/init/codex-installer.d.ts +6 -0
  276. package/dist/init/codex-installer.js +3 -1
  277. package/dist/init/continuedev-installer.d.ts +6 -0
  278. package/dist/init/continuedev-installer.js +10 -3
  279. package/dist/init/copilot-installer.d.ts +6 -0
  280. package/dist/init/copilot-installer.js +3 -1
  281. package/dist/init/cursor-installer.d.ts +6 -0
  282. package/dist/init/cursor-installer.js +3 -1
  283. package/dist/init/kilocode-installer.d.ts +6 -0
  284. package/dist/init/kilocode-installer.js +3 -1
  285. package/dist/init/kiro-installer.d.ts +5 -0
  286. package/dist/init/kiro-installer.js +4 -4
  287. package/dist/init/orchestrator.js +1 -0
  288. package/dist/init/phases/07-hooks.js +5 -0
  289. package/dist/init/phases/08-mcp.js +34 -7
  290. package/dist/init/phases/09-assets.js +30 -27
  291. package/dist/init/phases/11-claude-md.d.ts +1 -0
  292. package/dist/init/phases/11-claude-md.js +8 -0
  293. package/dist/init/phases/13-governance.js +5 -0
  294. package/dist/init/phases/phase-interface.d.ts +8 -0
  295. package/dist/init/platform-config-generator.d.ts +3 -1
  296. package/dist/init/platform-config-generator.js +31 -17
  297. package/dist/init/roocode-installer.d.ts +6 -0
  298. package/dist/init/roocode-installer.js +3 -1
  299. package/dist/init/windsurf-installer.d.ts +6 -0
  300. package/dist/init/windsurf-installer.js +3 -1
  301. package/dist/mcp/bundle.js +297 -296
  302. package/dist/mcp/entry.js +10 -1
  303. package/dist/mcp/protocol-server.js +17 -0
  304. package/dist/optimization/session-cache.d.ts +11 -0
  305. package/dist/optimization/session-cache.js +31 -0
  306. package/package.json +2 -2
  307. package/dist/cli/chunks/adapter-PAMPC2X7.js +0 -2
  308. package/dist/cli/chunks/aqe-learning-engine-DGKLEC6I.js +0 -2
  309. package/dist/cli/chunks/base-6HJR4VJT.js +0 -2
  310. package/dist/cli/chunks/browser-workflow-OWNU5XK7.js +0 -2
  311. package/dist/cli/chunks/chunk-2B2RLPK3.js +0 -2
  312. package/dist/cli/chunks/chunk-NSI3WL6P.js +0 -6
  313. package/dist/cli/chunks/client-E6GK5NWT.js +0 -2
  314. package/dist/cli/chunks/cline-installer-A7G7OXIS.js +0 -4
  315. package/dist/cli/chunks/codex-installer-JB3ULDQP.js +0 -8
  316. package/dist/cli/chunks/continuedev-installer-GSYBLQV7.js +0 -14
  317. package/dist/cli/chunks/copilot-installer-7B56CNU2.js +0 -3
  318. package/dist/cli/chunks/core-handlers-HJUORTFU.js +0 -2
  319. package/dist/cli/chunks/cross-domain-router-35WVZFAZ.js +0 -2
  320. package/dist/cli/chunks/cursor-installer-WXQFM4KJ.js +0 -3
  321. package/dist/cli/chunks/dream-QTZDMP6D.js +0 -2
  322. package/dist/cli/chunks/heartbeat-scheduler-N433NZCG.js +0 -2
  323. package/dist/cli/chunks/hnsw-adapter-MR6W2OA4.js +0 -2
  324. package/dist/cli/chunks/hnsw-index-XC6EMJA2.js +0 -2
  325. package/dist/cli/chunks/hybrid-router-SH4IEAJA.js +0 -2
  326. package/dist/cli/chunks/impact-analyzer-RUTVXE7P.js +0 -2
  327. package/dist/cli/chunks/init-wizard-56NY5BSP.js +0 -2
  328. package/dist/cli/chunks/kernel-7JAN7WCO.js +0 -2
  329. package/dist/cli/chunks/kilocode-installer-3AXYSZTO.js +0 -4
  330. package/dist/cli/chunks/knowledge-graph-ST4LW3V4.js +0 -2
  331. package/dist/cli/chunks/llm-router-service-JNDF5MVJ.js +0 -2
  332. package/dist/cli/chunks/load-test-I3P3DUS5.js +0 -2
  333. package/dist/cli/chunks/mcp-F2V3KKG6.js +0 -2
  334. package/dist/cli/chunks/memory-backend-27BBT57O.js +0 -2
  335. package/dist/cli/chunks/pattern-null-store-SRBYJRNX.js +0 -2
  336. package/dist/cli/chunks/protocol-executor-WJLJHWO2.js +0 -2
  337. package/dist/cli/chunks/provider-manager-UKUHSHAL.js +0 -2
  338. package/dist/cli/chunks/qe-reasoning-bank-IMUECSFZ.js +0 -2
  339. package/dist/cli/chunks/queen-coordinator-EC4SVNMB.js +0 -2
  340. package/dist/cli/chunks/roocode-installer-DFUA6FXW.js +0 -4
  341. package/dist/cli/chunks/router-TVTOUQLL.js +0 -2
  342. package/dist/cli/chunks/routing-feedback-Y4WDXNXW.js +0 -2
  343. package/dist/cli/chunks/rvf-native-adapter-4YSC6QKO.js +0 -2
  344. package/dist/cli/chunks/safe-db-RGAY54O5.js +0 -2
  345. package/dist/cli/chunks/schedule-KJ4GWLPJ.js +0 -2
  346. package/dist/cli/chunks/scheduler-AONSLVA3.js +0 -2
  347. package/dist/cli/chunks/sqlite-persistence-7RZUEPM4.js +0 -2
  348. package/dist/cli/chunks/unified-memory-G3BYQ3WU.js +0 -2
  349. package/dist/cli/chunks/unified-memory-hnsw-F7XUZMKW.js +0 -2
  350. package/dist/cli/chunks/unified-persistence-V35NXJSO.js +0 -2
  351. package/dist/cli/chunks/visual-security-K47U7KUM.js +0 -2
  352. package/dist/cli/chunks/windsurf-installer-I3TSJCNL.js +0 -7
  353. package/dist/cli/chunks/witness-chain-G6GJXZD3.js +0 -2
  354. package/dist/cli/chunks/workflow-orchestrator-SKF7GC5X.js +0 -2
@@ -1,6 +1,6 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.8");process.exit(0)}
2
- import{d as B,e as j,f as re,g as W}from"./chunk-HVFHPDXV.js";import{a as ne}from"./chunk-CHPL7TA4.js";import{g as nt,h as it}from"./chunk-Z7FWPSOK.js";import{b as Ce,c as tt}from"./chunk-NOP5ZJ7E.js";import{a as De,d as Fe,e as rt,f as Oe}from"./chunk-O75ODKCX.js";import{a as ie}from"./chunk-CP4CSI5R.js";import{b as P,c as w}from"./chunk-D7ZVIL3C.js";import{a as v,b as Te,c as xe}from"./chunk-MTWBYHMS.js";import{i as C}from"./chunk-NFZY6ZVY.js";import{B as q,D as H,G as te,P as M,S as F,b as D}from"./chunk-HE3KLHNO.js";import{a as Re,d as J,f as et,g as Ae}from"./chunk-SDGRU6SG.js";var V=J(E=>{var ft=E&&E.__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(E,"__esModule",{value:!0});var mt=Object.prototype.hasOwnProperty;function ue(n,e){return mt.call(n,e)}E.hasOwnProperty=ue;function qe(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)ue(n,i)&&r.push(i);return r}E._objectKeys=qe;function pt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}E._deepClone=pt;function gt(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}E.isInteger=gt;function ce(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}E.escapePathComponent=ce;function yt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}E.unescapePathComponent=yt;function he(n,e){var t;for(var r in n)if(ue(n,r)){if(n[r]===e)return ce(r)+"/";if(typeof n[r]=="object"&&(t=he(n[r],e),t!=""))return ce(r)+"/"+t}return""}E._getPathRecursive=he;function vt(n,e){if(n===e)return"/";var t=he(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}E.getPath=vt;function le(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(le(n[e]))return!0}else if(typeof n=="object"){for(var r=qe(n),i=r.length,s=0;s<i;s++)if(le(n[r[s]]))return!0}}return!1}E.hasUndefined=le;function Ue(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 Pt=(function(n){ft(e,n);function e(t,r,i,s,a){var c=this.constructor,u=n.call(this,Ue(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=Ue(t,{name:r,index:i,operation:s,tree:a}),u}return e})(Error);E.PatchError=Pt});var de=J(g=>{Object.defineProperty(g,"__esModule",{value:!0});var R=V();g.JsonPatchError=R.PatchError;g.deepClone=R._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=R._deepClone(r));var i=O(t,{op:"remove",path:this.from}).removed;return O(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=Y(t,this.from);return O(t,{op:"add",path:this.path,value:R._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}}},wt={add:function(n,e,t){return R.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 O(n,t),t.value}g.getValueByPointer=Y;function O(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 g.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 g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=R._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,d=u.length,h=void 0,f=void 0,p=void 0;for(typeof t=="function"?p=t:p=K;;){if(f=u[l],f&&f.indexOf("~")!=-1&&(f=R.unescapePathComponent(f)),i&&(f=="__proto__"||f=="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&&h===void 0&&(o[f]===void 0?h=u.slice(0,l).join("/"):l==d-1&&(h=e.path),h!==void 0&&p(e,0,n,h)),l++,Array.isArray(o)){if(f==="-")f=o.length;else{if(t&&!R.isInteger(f))throw new g.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);R.isInteger(f)&&(f=~~f)}if(l>=d){if(t&&e.op==="add"&&f>o.length)throw new g.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=wt[e.op].call(e,o,f,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(l>=d){var a=L[e.op].call(e,o,f,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[f],t&&l<d&&(!o||typeof o!="object"))throw new g.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}g.applyOperation=O;function Qe(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=R._deepClone(n));for(var s=new Array(e.length),a=0,c=e.length;a<c;a++)s[a]=O(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}g.applyPatch=Qe;function St(n,e,t){var r=O(n,e);if(r.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}g.applyReducer=St;function K(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new g.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new g.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 g.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 g.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 g.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")&&R.hasUndefined(n.value))throw new g.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 g.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 g.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=ze([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new g.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}g.validator=K;function ze(n,e,t){try{if(!Array.isArray(n))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Qe(R._deepClone(e),R._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 g.JsonPatchError)return i;throw i}}g.validate=ze;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}g._areEquals=z});var $e=J(k=>{Object.defineProperty(k,"__esModule",{value:!0});var S=V(),bt=de(),me=new WeakMap,Et=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Rt=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function At(n){return me.get(n)}function Tt(n,e){return n.observers.get(e)}function xt(n,e){n.observers.delete(e.callback)}function Ct(n,e){e.unobserve()}k.unobserve=Ct;function Dt(n,e){var t=[],r,i=At(n);if(!i)i=new Et(n),me.set(n,i);else{var s=Tt(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=S._deepClone(n),e){r.callback=e,r.next=null;var a=function(){fe(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(){fe(r),clearTimeout(r.next),xt(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 Rt(e,r)),r}k.observe=Dt;function fe(n,e){e===void 0&&(e=!1);var t=me.get(n.object);pe(t.value,n.object,n.patches,"",e),n.patches.length&&bt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=fe;function pe(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=S._objectKeys(e),a=S._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],d=n[l];if(S.hasOwnProperty(e,l)&&!(e[l]===void 0&&d!==void 0&&Array.isArray(e)===!1)){var h=e[l];typeof d=="object"&&d!=null&&typeof h=="object"&&h!=null&&Array.isArray(d)===Array.isArray(h)?pe(d,h,t,r+"/"+S.escapePathComponent(l),i):d!==h&&(c=!0,i&&t.push({op:"test",path:r+"/"+S.escapePathComponent(l),value:S._deepClone(d)}),t.push({op:"replace",path:r+"/"+S.escapePathComponent(l),value:S._deepClone(h)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+S.escapePathComponent(l),value:S._deepClone(d)}),t.push({op:"remove",path:r+"/"+S.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];!S.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+S.escapePathComponent(l),value:S._deepClone(e[l])})}}}function Ft(n,e,t){t===void 0&&(t=!1);var r=[];return pe(n,e,r,"",t),r}k.compare=Ft});var Je=J(I=>{var Ot=de();Object.assign(I,Ot);var It=$e();Object.assign(I,It);var Z=V();I.JsonPatchError=Z.PatchError;I.deepClone=Z._deepClone;I.escapePathComponent=Z.escapePathComponent;I.unescapePathComponent=Z.unescapePathComponent});tt();xe();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){if(process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}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=v(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-7RZUEPM4.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: ${v(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=W(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}:`,v(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}:`,v(r))}return P(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?P(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 d=this.calculateReuseInfo(l,o.score);s.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:d.canReuse,estimatedTokenSavings:d.estimatedTokenSavings,reuseConfidence:d.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",v(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,d)=>l+d*d,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let d=this.sqliteStore.getPattern(l.id),h=d?.embedding;if(!h||h.length!==u.length)continue;let f=0,p=0;for(let b=0;b<u.length;b++)f+=u[b]*h[b],p+=h[b]*h[b];if(p=Math.sqrt(p),p===0)continue;let m=f/(o*p),y=this.calculateReuseInfo(d,m);s.push({pattern:d,score:m,matchType:"vector",similarity:m,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.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 d=this.calculateReuseInfo(l,o.ftsScore);s.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:d.canReuse,estimatedTokenSavings:d.estimatedTokenSavings,reuseConfidence:d.reuseConfidence})}}}catch{}s.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,P(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),P(void 0)}catch(r){return w(new Error(`recordUsage failed: ${v(r)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return w(new Error(`promote failed: ${v(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,v(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${v(t)}`))}return P(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>=j&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",v(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}}};Oe();xe();F();function at(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 ot(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=at(n,e.field);return ot(t,e.operator,e.value)}default:return!0}}function Ie(n,e){return e?n.filter(t=>G(t,e)):n}F();F();var Ne=1e4,He=2166136261;function Me(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 oe=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;oe[n]=e}var _e="0123456789abcdef";function ct(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=_e[i>>4]+_e[i&15]}return t}function lt(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 ut(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 ht(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+=oe[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function dt(n,e,t){return 1-ht(n,e,t)}var se=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Ne,this.baseSeed=e?.seed??He,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=Me(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=lt(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 ut([r,i])}similarity(e,t){return dt(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}},ae=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Ne,this.baseSeed=e?.seed??He,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=Me(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:ct(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+=oe[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 Le(n){return new ae(n)}function ke(n){return q()?new se(n):null}var $=et(Je(),1),_t=`
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.9");process.exit(0)}
2
+ import{d as B,e as j,f as re,g as W}from"./chunk-RRSJ7BMF.js";import{a as ne}from"./chunk-WWGGL3TR.js";import{g as nt,h as it}from"./chunk-XLK4GP3I.js";import{b as Ce,c as tt}from"./chunk-ZT2DGSIO.js";import{a as De,d as Fe,e as rt,f as Oe}from"./chunk-7D5JE46U.js";import{a as ie}from"./chunk-4MUZGQPE.js";import{b as P,c as w}from"./chunk-X6YUGKMM.js";import{a as v,b as Te,c as xe}from"./chunk-5U5SEO7C.js";import{i as C}from"./chunk-QWXJRZEH.js";import{B as q,D as H,G as te,P as M,S as F,b as D}from"./chunk-KRAWWBX5.js";import{a as Re,d as J,f as et,g as Ae}from"./chunk-ABJPFKHE.js";var V=J(E=>{var ft=E&&E.__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(E,"__esModule",{value:!0});var mt=Object.prototype.hasOwnProperty;function ue(n,e){return mt.call(n,e)}E.hasOwnProperty=ue;function qe(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)ue(n,i)&&r.push(i);return r}E._objectKeys=qe;function pt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}E._deepClone=pt;function gt(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}E.isInteger=gt;function ce(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}E.escapePathComponent=ce;function yt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}E.unescapePathComponent=yt;function he(n,e){var t;for(var r in n)if(ue(n,r)){if(n[r]===e)return ce(r)+"/";if(typeof n[r]=="object"&&(t=he(n[r],e),t!=""))return ce(r)+"/"+t}return""}E._getPathRecursive=he;function vt(n,e){if(n===e)return"/";var t=he(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}E.getPath=vt;function le(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(le(n[e]))return!0}else if(typeof n=="object"){for(var r=qe(n),i=r.length,s=0;s<i;s++)if(le(n[r[s]]))return!0}}return!1}E.hasUndefined=le;function Ue(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 Pt=(function(n){ft(e,n);function e(t,r,i,s,a){var c=this.constructor,u=n.call(this,Ue(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=Ue(t,{name:r,index:i,operation:s,tree:a}),u}return e})(Error);E.PatchError=Pt});var de=J(g=>{Object.defineProperty(g,"__esModule",{value:!0});var R=V();g.JsonPatchError=R.PatchError;g.deepClone=R._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=R._deepClone(r));var i=O(t,{op:"remove",path:this.from}).removed;return O(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=Y(t,this.from);return O(t,{op:"add",path:this.path,value:R._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}}},wt={add:function(n,e,t){return R.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 O(n,t),t.value}g.getValueByPointer=Y;function O(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 g.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 g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=R._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,d=u.length,h=void 0,f=void 0,p=void 0;for(typeof t=="function"?p=t:p=K;;){if(f=u[l],f&&f.indexOf("~")!=-1&&(f=R.unescapePathComponent(f)),i&&(f=="__proto__"||f=="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&&h===void 0&&(o[f]===void 0?h=u.slice(0,l).join("/"):l==d-1&&(h=e.path),h!==void 0&&p(e,0,n,h)),l++,Array.isArray(o)){if(f==="-")f=o.length;else{if(t&&!R.isInteger(f))throw new g.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);R.isInteger(f)&&(f=~~f)}if(l>=d){if(t&&e.op==="add"&&f>o.length)throw new g.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=wt[e.op].call(e,o,f,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(l>=d){var a=L[e.op].call(e,o,f,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[f],t&&l<d&&(!o||typeof o!="object"))throw new g.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}g.applyOperation=O;function Qe(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=R._deepClone(n));for(var s=new Array(e.length),a=0,c=e.length;a<c;a++)s[a]=O(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}g.applyPatch=Qe;function St(n,e,t){var r=O(n,e);if(r.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}g.applyReducer=St;function K(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new g.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new g.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 g.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 g.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 g.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")&&R.hasUndefined(n.value))throw new g.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 g.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 g.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=ze([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new g.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}g.validator=K;function ze(n,e,t){try{if(!Array.isArray(n))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Qe(R._deepClone(e),R._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 g.JsonPatchError)return i;throw i}}g.validate=ze;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}g._areEquals=z});var $e=J(k=>{Object.defineProperty(k,"__esModule",{value:!0});var S=V(),bt=de(),me=new WeakMap,Et=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Rt=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function At(n){return me.get(n)}function Tt(n,e){return n.observers.get(e)}function xt(n,e){n.observers.delete(e.callback)}function Ct(n,e){e.unobserve()}k.unobserve=Ct;function Dt(n,e){var t=[],r,i=At(n);if(!i)i=new Et(n),me.set(n,i);else{var s=Tt(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=S._deepClone(n),e){r.callback=e,r.next=null;var a=function(){fe(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(){fe(r),clearTimeout(r.next),xt(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 Rt(e,r)),r}k.observe=Dt;function fe(n,e){e===void 0&&(e=!1);var t=me.get(n.object);pe(t.value,n.object,n.patches,"",e),n.patches.length&&bt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=fe;function pe(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=S._objectKeys(e),a=S._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],d=n[l];if(S.hasOwnProperty(e,l)&&!(e[l]===void 0&&d!==void 0&&Array.isArray(e)===!1)){var h=e[l];typeof d=="object"&&d!=null&&typeof h=="object"&&h!=null&&Array.isArray(d)===Array.isArray(h)?pe(d,h,t,r+"/"+S.escapePathComponent(l),i):d!==h&&(c=!0,i&&t.push({op:"test",path:r+"/"+S.escapePathComponent(l),value:S._deepClone(d)}),t.push({op:"replace",path:r+"/"+S.escapePathComponent(l),value:S._deepClone(h)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+S.escapePathComponent(l),value:S._deepClone(d)}),t.push({op:"remove",path:r+"/"+S.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];!S.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+S.escapePathComponent(l),value:S._deepClone(e[l])})}}}function Ft(n,e,t){t===void 0&&(t=!1);var r=[];return pe(n,e,r,"",t),r}k.compare=Ft});var Je=J(I=>{var Ot=de();Object.assign(I,Ot);var It=$e();Object.assign(I,It);var Z=V();I.JsonPatchError=Z.PatchError;I.deepClone=Z._deepClone;I.escapePathComponent=Z.escapePathComponent;I.unescapePathComponent=Z.unescapePathComponent});tt();xe();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){if(process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}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=v(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-NR5WXTPN.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: ${v(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=W(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}:`,v(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}:`,v(r))}return P(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?P(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 d=this.calculateReuseInfo(l,o.score);s.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:d.canReuse,estimatedTokenSavings:d.estimatedTokenSavings,reuseConfidence:d.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",v(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,d)=>l+d*d,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let d=this.sqliteStore.getPattern(l.id),h=d?.embedding;if(!h||h.length!==u.length)continue;let f=0,p=0;for(let b=0;b<u.length;b++)f+=u[b]*h[b],p+=h[b]*h[b];if(p=Math.sqrt(p),p===0)continue;let m=f/(o*p),y=this.calculateReuseInfo(d,m);s.push({pattern:d,score:m,matchType:"vector",similarity:m,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.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 d=this.calculateReuseInfo(l,o.ftsScore);s.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:d.canReuse,estimatedTokenSavings:d.estimatedTokenSavings,reuseConfidence:d.reuseConfidence})}}}catch{}s.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,P(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),P(void 0)}catch(r){return w(new Error(`recordUsage failed: ${v(r)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return w(new Error(`promote failed: ${v(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,v(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${v(t)}`))}return P(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>=j&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",v(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}}};Oe();xe();F();function at(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 ot(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=at(n,e.field);return ot(t,e.operator,e.value)}default:return!0}}function Ie(n,e){return e?n.filter(t=>G(t,e)):n}F();F();var Ne=1e4,He=2166136261;function Me(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 oe=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;oe[n]=e}var _e="0123456789abcdef";function ct(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=_e[i>>4]+_e[i&15]}return t}function lt(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 ut(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 ht(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+=oe[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function dt(n,e,t){return 1-ht(n,e,t)}var se=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Ne,this.baseSeed=e?.seed??He,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=Me(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=lt(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 ut([r,i])}similarity(e,t){return dt(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}},ae=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Ne,this.baseSeed=e?.seed??He,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=Me(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:ct(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+=oe[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 Le(n){return new ae(n)}function ke(n){return q()?new se(n):null}var $=et(Je(),1),_t=`
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{d as B,e as j,f as re,g as W}from"./chunk-HVFHPDXV.js";import{a as ne}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 Ht={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},ge=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Ht,...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(d=>d.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(d=>d.version===0||d.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 We(n){return H()?new ge(n):null}F();var Mt=128,Lt=8,kt=1e4,ye=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Mt,this.beta=e?.beta??Lt,this.maxPatterns=e?.maxPatterns??kt,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 Xe(n){return new ye(n)}F();var Ut={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,Ge=1-_;function qt(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 Qt(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(Qt(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=qt(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<=Ge)return new Float32Array(e);let r=Ge/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)}},ve=class{config;points=new Map;constructor(e){if(this.config={...Ut,...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:d}=c.shift(),h=Math.tanh(.3*(o+.1)),f=l+d/2,p=new Float32Array(r);p[0]=h*Math.cos(f),p[1]=h*Math.sin(f);let m=s.get(u);if(m&&m.features.length>0){let N=h*.1;for(let x=2;x<r&&x-2<m.features.length;x++)p[x]=m.features[x-2]*N}let y=T.project(p);t.set(u,y),this.points.set(u,{id:u,coordinates:y,metadata:{depth:o,parentId:m?.parentId}});let b=i.get(u)??[];for(let N=0;N<b.length;N++){let x=d/Math.max(1,b.length);c.push({id:b[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 Ve(n){return zt()?new ve(n):null}function zt(){return D().useHyperbolicHnsw}F();var Pe=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=Ve(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 Ye(n){return new Pe(n)}var we=null;function Ke(){return we||(we=Le({dimensions:1e4})),we}var Se;function $t(){return Se===void 0&&(Se=ke()),Se}var U=null,be=0;function Ze(n){return(!U||be!==n)&&(U=Xe({dimension:n,maxPatterns:1e4}),be=n),U}var X={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:j,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}},Ee=class{constructor(e,t={}){this.memory=e;this.config={...X,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;nullStore=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-NE5JIRG3.js"),{HnswAdapter:c}=await import("./hnsw-adapter-MR6W2OA4.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-XC6EMJA2.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:",v(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:",v(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=We()),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:",v(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=W(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}:`,v(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=Ke().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}:`,v(s))}try{let s=$t();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}:`,v(s))}if(te()&&e.embedding)try{Ze(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}:`,v(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}:`,v(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}:`,v(s))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return P(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?P(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=Ze(e.length);if(h.getPatternCount()>0){let f=h.recall(new Float32Array(e));if(f&&f.similarity>.98){let p=f.metadata.id,m=await this.get(p);if(m&&this.matchesFilters(m,t)){let y=this.calculateReuseInfo(m,f.similarity);s.push({pattern:m,score:f.similarity,matchType:"vector",similarity:f.similarity,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}catch(h){console.debug("[PatternStore] Hopfield recall failed:",v(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 p of f){let m=await this.get(p.key);if(m&&this.matchesFilters(m,t)){let y=this.calculateReuseInfo(m,p.score);s.push({pattern:m,score:p.score,matchType:"vector",similarity:p.score,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let h=this.sqliteStore.searchFTS(e,i*2);if(h.length>0){let f=new Map(h.map(m=>[m.id,m.ftsScore])),p=new Set(s.map(m=>m.pattern.id));for(let m of s){let y=f.get(m.pattern.id);y!==void 0&&(m.score=.75*m.score+.25*y)}for(let m of h){if(p.has(m.id))continue;let y=await this.get(m.id);if(y&&this.matchesFilters(y,t)){let b=this.calculateReuseInfo(y,m.ftsScore);s.push({pattern:y,score:.5*m.ftsScore,matchType:"exact",similarity:m.ftsScore,canReuse:b.canReuse,estimatedTokenSavings:b.estimatedTokenSavings,reuseConfidence:b.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(p=>p.pattern.id));for(let p of h)f.has(p.pattern.id)||s.push(p)}let a=720*60*60*1e3,c=Date.now();for(let h of s){let f=h.pattern.lastUsedAt?.getTime()??h.pattern.createdAt.getTime(),p=c-f,m=Math.pow(.5,p/a),y=h.pattern.usageCount>0?m:.5;h.score=h.score*(.7+.3*y)}let u=this.sqliteStore?.getDatabase();if(u&&s.length>0)try{this.nullStore||(this.nullStore=new ie(u));let h=this.nullStore.getNullSummaries(s.map(f=>f.pattern.id));for(let f of s){let p=h.get(f.pattern.id);p&&(f.nullSummary=p,f.score=ie.applyNullDiscount(f.score,p,t.contextFingerprint))}}catch(h){console.debug("[PatternStore] null discount skipped:",v(h))}s.sort((h,f)=>f.score-h.score);let o=s;t.filter&&(o=Ie(s,t.filter));let l=o.slice(0,i),d=performance.now()-r;return this.recordSearchLatency(d),P(l)}catch(a){return w(Te(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=Ke(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(f=>this.hdcCache.has(f)).map(f=>({id:f,similarity:u.similarity(o.vector,this.hdcCache.get(f))}));l.sort((f,p)=>p.similarity-f.similarity);let d=l.map(f=>f.id),h=c.filter(f=>!this.hdcCache.has(f));c=[...d,...h]}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 d=o.name.toLowerCase(),h=o.description.toLowerCase();d.includes(s)&&(l+=.5),h.includes(s)&&(s.length/h.length>.3?l+=.5:l+=.3);for(let f of o.context.tags)if(f.toLowerCase().includes(s)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!s){let d=this.calculateReuseInfo(o,l);i.push({pattern:o,score:l||o.qualityScore,matchType:s?"exact":"context",similarity:l||o.qualityScore,canReuse:d.canReuse,estimatedTokenSavings:d.estimatedTokenSavings,reuseConfidence:d.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,d=t,h=e.successRate,f=Math.min(e.reuseCount/10,1),p=o?d*.4+h*.4+f*.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}),d={...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}:`,v(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},m={id:d.id,name:d.name,confidence:d.confidence,qualityScore:d.qualityScore,usageCount:d.usageCount,successRate:d.successRate,tier:d.tier};this.deltaTracker.recordDelta(e,p,m,{success:t})}catch(p){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,v(p))}let h=re(d);return h.meetsUsageCriteria&&h.meetsQualityCriteria&&h.meetsCoherenceCriteria&&d.tier==="short-term"?await this.promote(e):this.patternCache.set(e,d),P(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 P(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`),P(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 P(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,d=s.qualityScore<.2,h=s.usageCount===0&&o>1440*60*1e3;(l&&d||h)&&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,be=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ye({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 P([]);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 P(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function zr(n,e){try{if(D().useRVFPatternStore&&Fe()){let{existsSync:r}=Re("fs"),{join:i}=Re("path"),s=process.env.AQE_PROJECT_ROOT??Ce(),a=i(s,".agentic-qe"),c=i(a,"patterns.rvf");if(r(a)){let u={...X,...e},o=!1;try{let{getSharedRvfAdapter:l}=(it(),Ae(nt)),d=l(a,u.embeddingDimension);if(d){o=!0;let h=new Q(()=>d,{rvfPath:c,base:u,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),h}}catch{}if(!o){let l=new Q((d,h)=>{let{openRvfStore:f}=(Oe(),Ae(rt)),p=()=>{try{return f(d)}catch{return null}},m=p();if(m){if(m.dimension()!==h){try{m.close()}catch{}throw new Error(`RVF dimension mismatch (file=${m.dimension()}, requested=${h})`)}return m}try{return De(d,h)}catch(y){if(m=p(),m&&m.dimension()===h)return m;throw y}},{rvfPath:c,base:u});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new Ee(n,e)}export{zr as a};
49
+ )`).run(e,e,s)}}};F();var Ht={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},ge=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Ht,...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(d=>d.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(d=>d.version===0||d.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 We(n){return H()?new ge(n):null}F();var Mt=128,Lt=8,kt=1e4,ye=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Mt,this.beta=e?.beta??Lt,this.maxPatterns=e?.maxPatterns??kt,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 Xe(n){return new ye(n)}F();var Ut={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,Ge=1-_;function qt(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 Qt(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(Qt(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=qt(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<=Ge)return new Float32Array(e);let r=Ge/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)}},ve=class{config;points=new Map;constructor(e){if(this.config={...Ut,...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:d}=c.shift(),h=Math.tanh(.3*(o+.1)),f=l+d/2,p=new Float32Array(r);p[0]=h*Math.cos(f),p[1]=h*Math.sin(f);let m=s.get(u);if(m&&m.features.length>0){let N=h*.1;for(let x=2;x<r&&x-2<m.features.length;x++)p[x]=m.features[x-2]*N}let y=T.project(p);t.set(u,y),this.points.set(u,{id:u,coordinates:y,metadata:{depth:o,parentId:m?.parentId}});let b=i.get(u)??[];for(let N=0;N<b.length;N++){let x=d/Math.max(1,b.length);c.push({id:b[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 Ve(n){return zt()?new ve(n):null}function zt(){return D().useHyperbolicHnsw}F();var Pe=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=Ve(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 Ye(n){return new Pe(n)}var we=null;function Ke(){return we||(we=Le({dimensions:1e4})),we}var Se;function $t(){return Se===void 0&&(Se=ke()),Se}var U=null,be=0;function Ze(n){return(!U||be!==n)&&(U=Xe({dimension:n,maxPatterns:1e4}),be=n),U}var X={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:j,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}},Ee=class{constructor(e,t={}){this.memory=e;this.config={...X,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;nullStore=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-BO325POX.js"),{HnswAdapter:c}=await import("./hnsw-adapter-UVJJ6TTP.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-K6HS34JZ.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:",v(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:",v(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=We()),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:",v(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=W(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}:`,v(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=Ke().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}:`,v(s))}try{let s=$t();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}:`,v(s))}if(te()&&e.embedding)try{Ze(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}:`,v(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}:`,v(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}:`,v(s))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return P(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?P(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=Ze(e.length);if(h.getPatternCount()>0){let f=h.recall(new Float32Array(e));if(f&&f.similarity>.98){let p=f.metadata.id,m=await this.get(p);if(m&&this.matchesFilters(m,t)){let y=this.calculateReuseInfo(m,f.similarity);s.push({pattern:m,score:f.similarity,matchType:"vector",similarity:f.similarity,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}catch(h){console.debug("[PatternStore] Hopfield recall failed:",v(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 p of f){let m=await this.get(p.key);if(m&&this.matchesFilters(m,t)){let y=this.calculateReuseInfo(m,p.score);s.push({pattern:m,score:p.score,matchType:"vector",similarity:p.score,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let h=this.sqliteStore.searchFTS(e,i*2);if(h.length>0){let f=new Map(h.map(m=>[m.id,m.ftsScore])),p=new Set(s.map(m=>m.pattern.id));for(let m of s){let y=f.get(m.pattern.id);y!==void 0&&(m.score=.75*m.score+.25*y)}for(let m of h){if(p.has(m.id))continue;let y=await this.get(m.id);if(y&&this.matchesFilters(y,t)){let b=this.calculateReuseInfo(y,m.ftsScore);s.push({pattern:y,score:.5*m.ftsScore,matchType:"exact",similarity:m.ftsScore,canReuse:b.canReuse,estimatedTokenSavings:b.estimatedTokenSavings,reuseConfidence:b.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(p=>p.pattern.id));for(let p of h)f.has(p.pattern.id)||s.push(p)}let a=720*60*60*1e3,c=Date.now();for(let h of s){let f=h.pattern.lastUsedAt?.getTime()??h.pattern.createdAt.getTime(),p=c-f,m=Math.pow(.5,p/a),y=h.pattern.usageCount>0?m:.5;h.score=h.score*(.7+.3*y)}let u=this.sqliteStore?.getDatabase();if(u&&s.length>0)try{this.nullStore||(this.nullStore=new ie(u));let h=this.nullStore.getNullSummaries(s.map(f=>f.pattern.id));for(let f of s){let p=h.get(f.pattern.id);p&&(f.nullSummary=p,f.score=ie.applyNullDiscount(f.score,p,t.contextFingerprint))}}catch(h){console.debug("[PatternStore] null discount skipped:",v(h))}s.sort((h,f)=>f.score-h.score);let o=s;t.filter&&(o=Ie(s,t.filter));let l=o.slice(0,i),d=performance.now()-r;return this.recordSearchLatency(d),P(l)}catch(a){return w(Te(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=Ke(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(f=>this.hdcCache.has(f)).map(f=>({id:f,similarity:u.similarity(o.vector,this.hdcCache.get(f))}));l.sort((f,p)=>p.similarity-f.similarity);let d=l.map(f=>f.id),h=c.filter(f=>!this.hdcCache.has(f));c=[...d,...h]}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 d=o.name.toLowerCase(),h=o.description.toLowerCase();d.includes(s)&&(l+=.5),h.includes(s)&&(s.length/h.length>.3?l+=.5:l+=.3);for(let f of o.context.tags)if(f.toLowerCase().includes(s)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!s){let d=this.calculateReuseInfo(o,l);i.push({pattern:o,score:l||o.qualityScore,matchType:s?"exact":"context",similarity:l||o.qualityScore,canReuse:d.canReuse,estimatedTokenSavings:d.estimatedTokenSavings,reuseConfidence:d.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,d=t,h=e.successRate,f=Math.min(e.reuseCount/10,1),p=o?d*.4+h*.4+f*.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}),d={...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}:`,v(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},m={id:d.id,name:d.name,confidence:d.confidence,qualityScore:d.qualityScore,usageCount:d.usageCount,successRate:d.successRate,tier:d.tier};this.deltaTracker.recordDelta(e,p,m,{success:t})}catch(p){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,v(p))}let h=re(d);return h.meetsUsageCriteria&&h.meetsQualityCriteria&&h.meetsCoherenceCriteria&&d.tier==="short-term"?await this.promote(e):this.patternCache.set(e,d),P(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 P(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`),P(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 P(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,d=s.qualityScore<.2,h=s.usageCount===0&&o>1440*60*1e3;(l&&d||h)&&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,be=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ye({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 P([]);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 P(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function zr(n,e){try{if(D().useRVFPatternStore&&Fe()){let{existsSync:r}=Re("fs"),{join:i}=Re("path"),s=process.env.AQE_PROJECT_ROOT??Ce(),a=i(s,".agentic-qe"),c=i(a,"patterns.rvf");if(r(a)){let u={...X,...e},o=!1;try{let{getSharedRvfAdapter:l}=(it(),Ae(nt)),d=l(a,u.embeddingDimension);if(d){o=!0;let h=new Q(()=>d,{rvfPath:c,base:u,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),h}}catch{}if(!o){let l=new Q((d,h)=>{let{openRvfStore:f}=(Oe(),Ae(rt)),p=()=>{try{return f(d)}catch{return null}},m=p();if(m){if(m.dimension()!==h){try{m.close()}catch{}throw new Error(`RVF dimension mismatch (file=${m.dimension()}, requested=${h})`)}return m}try{return De(d,h)}catch(y){if(m=p(),m&&m.dimension()===h)return m;throw y}},{rvfPath:c,base:u});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new Ee(n,e)}export{zr 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.10.8");process.exit(0)}
2
- import{c as h,e as v,g as T}from"./chunk-SDGRU6SG.js";var y={};v(y,{DotProductAttention:()=>z,FlashAttention:()=>k,HyperbolicAttention:()=>C,LinearAttention:()=>j,MoEAttention:()=>W,MultiHeadAttention:()=>F,RuvectorLayer:()=>O,SonaEngine:()=>K,TensorCompress:()=>E,default:()=>I,differentiableSearch:()=>L,getCompressionLevel:()=>B,hierarchicalForward:()=>V,init:()=>D,pipeline:()=>q});import{createRequire as A}from"module";var _,g,I,O,E,L,V,B,D,k,z,F,C,j,W,K,q,R=h(()=>{_=A(import.meta.url),g=_("@ruvector/rvf-node"),I=g,{RuvectorLayer:O,TensorCompress:E,differentiableSearch:L,hierarchicalForward:V,getCompressionLevel:B,init:D,FlashAttention:k,DotProductAttention:z,MultiHeadAttention:F,HyperbolicAttention:C,LinearAttention:j,MoEAttention:W,SonaEngine:K,pipeline:q}=g||{}});var Z={};v(Z,{createRvfStore:()=>$,isRvfNativeAvailable:()=>X,openRvfStore:()=>G,openRvfStoreReadonly:()=>U});import{readFileSync as J,writeFileSync as H,copyFileSync as Q,existsSync as Y}from"fs";function c(){if(S)return m;S=!0;try{let s=(R(),T(y));!s.RvfDatabase&&s.default&&s.default.RvfDatabase&&(s=s.default),m=s}catch{m=null}return m}function w(s){return`${s}.idmap.json`}function N(s){let e=w(s),t=new Map,n=new Map,i=1;if(Y(e))try{let r=JSON.parse(J(e,"utf-8"));i=r.nextLabel;for(let[a,p]of r.entries)t.set(a,p),n.set(p,a)}catch{}return{strToNum:t,numToStr:n,nextLabel:i}}function b(s,e,t){let n={nextLabel:t,entries:Array.from(e.entries())};H(w(s),JSON.stringify(n),"utf-8")}function $(s,e){let t=c();if(!t)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let n=t.RvfDatabase.create(s,{dimension:e}),i=n.dimension();return new d(n,s,i,new Map,new Map,1)}function G(s){let e=c();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.open(s),n=t.dimension(),{strToNum:i,numToStr:r,nextLabel:a}=N(s);return new d(t,s,n,i,r,a)}function U(s){let e=c();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.openReadonly(s),n=t.dimension(),{strToNum:i,numToStr:r,nextLabel:a}=N(s);return new d(t,s,n,i,r,a)}function X(){return process.env.AQE_MEMORY_BACKEND==="memory"?!1:c()!==null}var m,S,d,P=h(()=>{m=null,S=!1;d=class s{db;_path;_dimension;strToNum;numToStr;nextLabel;_open;constructor(e,t,n,i,r,a){this.db=e,this._path=t,this._dimension=n,this.strToNum=i,this.numToStr=r,this.nextLabel=a,this._open=!0}ingest(e){if(this.ensureOpen(),e.length===0)return{accepted:0,rejected:0};let t=this._dimension,n=new Float32Array(e.length*t),i=[],r=[];for(let o=0;o<e.length;o++){let{id:u,vector:f,metadata:x}=e[o],l=this.strToNum.get(u);l===void 0&&(l=this.nextLabel++,this.strToNum.set(u,l),this.numToStr.set(l,u)),i.push(l),r.push(x);let M=f instanceof Float32Array?f:new Float32Array(f);n.set(M.subarray(0,t),o*t)}let a;if(r.some(o=>o!==void 0)&&typeof this.db.ingestBatchWithMetadata=="function"){let o=r.map(u=>u?JSON.stringify(u):"");a=this.db.ingestBatchWithMetadata(n,i,o)}else a=this.db.ingestBatch(n,i);return this.persistIdMap(),{accepted:a.accepted,rejected:a.rejected}}search(e,t){this.ensureOpen();let n=e instanceof Float32Array?e:new Float32Array(e);return this.db.query(n,t).map(r=>{let a=this.numToStr.get(r.id);return a===void 0?null:{id:a,distance:r.distance,score:1/(1+r.distance)}}).filter(r=>r!==null)}delete(e){this.ensureOpen();let t=[];for(let i of e){let r=this.strToNum.get(i);r!==void 0&&t.push(r)}if(t.length===0)return 0;let n=this.db.delete(t);for(let i of e){let r=this.strToNum.get(i);r!==void 0&&(this.strToNum.delete(i),this.numToStr.delete(r))}return this.persistIdMap(),n.deleted}fork(e){this.ensureOpen(),Q(this._path,e);let t=new Map(this.strToNum),n=new Map(this.numToStr);b(e,t,this.nextLabel);let r=c().RvfDatabase.open(e);return new s(r,e,this._dimension,t,n,this.nextLabel)}status(){this.ensureOpen();let e=this.db.status(),n=this.db.segments().filter(i=>i.segType==="witness");return{totalVectors:e.totalVectors,totalSegments:e.totalSegments,fileSizeBytes:e.fileSize,epoch:e.currentEpoch,witnessValid:n.length>0,witnessEntries:n.length,deadSpaceRatio:typeof e.deadSpaceRatio=="number"?e.deadSpaceRatio:0}}dimension(){return this._dimension}size(){return this.ensureOpen(),this.db.status().totalVectors}compact(){this.ensureOpen();try{let e=this.db.compact();return e&&typeof e=="object"?{segmentsCompacted:typeof e.segmentsCompacted=="number"?e.segmentsCompacted:0,bytesReclaimed:typeof e.bytesReclaimed=="number"?e.bytesReclaimed:0,epoch:typeof e.epoch=="number"?e.epoch:0}:{segmentsCompacted:0,bytesReclaimed:0,epoch:0}}catch{return null}}close(){this._open&&(this.db.close(),this._open=!1)}isOpen(){return this._open}path(){return this._path}embedKernel(e){return this.ensureOpen(),this.db.embedKernel(0,99,0,e,0,"")}extractKernel(){return this.ensureOpen(),this.db.extractKernel()}verifyWitness(){this.ensureOpen();let e=this.tryNative("verifyWitness");return e?{valid:e.valid??!0,totalEntries:e.totalEntries??0,errors:Array.isArray(e.errors)?e.errors:[]}:{valid:!0,totalEntries:0,errors:[]}}sign(e){this.ensureOpen();let t=this.tryNative("sign",e);return typeof t=="string"?t:null}fileId(){this.ensureOpen();let e=this.tryNative("fileId");return typeof e=="string"?e:null}parentId(){this.ensureOpen();let e=this.tryNative("parentId");return typeof e=="string"?e:null}lineageDepth(){this.ensureOpen();let e=this.tryNative("lineageDepth");return typeof e=="number"?e:0}indexStats(){let e=this.status();return{totalVectors:e.totalVectors,dimension:this._dimension,totalSegments:e.totalSegments,fileSizeBytes:e.fileSizeBytes,epoch:e.epoch,witnessValid:e.witnessValid,witnessEntries:e.witnessEntries,idMapSize:this.strToNum.size}}freeze(){this.ensureOpen();let e=this.tryNative("freeze");return typeof e=="number"?e:0}derive(e){this.ensureOpen();let t=c();if(typeof this.db.derive=="function")try{let n=this.db.derive(e),i=new Map(this.strToNum),r=new Map(this.numToStr);return b(e,i,this.nextLabel),new s(n,e,this._dimension,i,r,this.nextLabel)}catch{}return this.fork(e)}ensureOpen(){if(!this._open)throw new Error("RVF database is closed")}tryNative(e,...t){if(typeof this.db[e]!="function")return null;try{return this.db[e](...t)}catch{return null}}persistIdMap(){b(this._path,this.strToNum,this.nextLabel)}}});export{$ as a,G as b,U as c,X as d,Z as e,P as f};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.9");process.exit(0)}
2
+ import{c as h,e as v,g as T}from"./chunk-ABJPFKHE.js";var y={};v(y,{DotProductAttention:()=>z,FlashAttention:()=>k,HyperbolicAttention:()=>C,LinearAttention:()=>j,MoEAttention:()=>W,MultiHeadAttention:()=>F,RuvectorLayer:()=>O,SonaEngine:()=>K,TensorCompress:()=>E,default:()=>I,differentiableSearch:()=>L,getCompressionLevel:()=>B,hierarchicalForward:()=>V,init:()=>D,pipeline:()=>q});import{createRequire as A}from"module";var _,g,I,O,E,L,V,B,D,k,z,F,C,j,W,K,q,R=h(()=>{_=A(import.meta.url),g=_("@ruvector/rvf-node"),I=g,{RuvectorLayer:O,TensorCompress:E,differentiableSearch:L,hierarchicalForward:V,getCompressionLevel:B,init:D,FlashAttention:k,DotProductAttention:z,MultiHeadAttention:F,HyperbolicAttention:C,LinearAttention:j,MoEAttention:W,SonaEngine:K,pipeline:q}=g||{}});var Z={};v(Z,{createRvfStore:()=>$,isRvfNativeAvailable:()=>X,openRvfStore:()=>G,openRvfStoreReadonly:()=>U});import{readFileSync as J,writeFileSync as H,copyFileSync as Q,existsSync as Y}from"fs";function c(){if(S)return m;S=!0;try{let s=(R(),T(y));!s.RvfDatabase&&s.default&&s.default.RvfDatabase&&(s=s.default),m=s}catch{m=null}return m}function w(s){return`${s}.idmap.json`}function N(s){let e=w(s),t=new Map,n=new Map,i=1;if(Y(e))try{let r=JSON.parse(J(e,"utf-8"));i=r.nextLabel;for(let[a,p]of r.entries)t.set(a,p),n.set(p,a)}catch{}return{strToNum:t,numToStr:n,nextLabel:i}}function b(s,e,t){let n={nextLabel:t,entries:Array.from(e.entries())};H(w(s),JSON.stringify(n),"utf-8")}function $(s,e){let t=c();if(!t)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let n=t.RvfDatabase.create(s,{dimension:e}),i=n.dimension();return new d(n,s,i,new Map,new Map,1)}function G(s){let e=c();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.open(s),n=t.dimension(),{strToNum:i,numToStr:r,nextLabel:a}=N(s);return new d(t,s,n,i,r,a)}function U(s){let e=c();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.openReadonly(s),n=t.dimension(),{strToNum:i,numToStr:r,nextLabel:a}=N(s);return new d(t,s,n,i,r,a)}function X(){return process.env.AQE_MEMORY_BACKEND==="memory"?!1:c()!==null}var m,S,d,P=h(()=>{m=null,S=!1;d=class s{db;_path;_dimension;strToNum;numToStr;nextLabel;_open;constructor(e,t,n,i,r,a){this.db=e,this._path=t,this._dimension=n,this.strToNum=i,this.numToStr=r,this.nextLabel=a,this._open=!0}ingest(e){if(this.ensureOpen(),e.length===0)return{accepted:0,rejected:0};let t=this._dimension,n=new Float32Array(e.length*t),i=[],r=[];for(let o=0;o<e.length;o++){let{id:u,vector:f,metadata:x}=e[o],l=this.strToNum.get(u);l===void 0&&(l=this.nextLabel++,this.strToNum.set(u,l),this.numToStr.set(l,u)),i.push(l),r.push(x);let M=f instanceof Float32Array?f:new Float32Array(f);n.set(M.subarray(0,t),o*t)}let a;if(r.some(o=>o!==void 0)&&typeof this.db.ingestBatchWithMetadata=="function"){let o=r.map(u=>u?JSON.stringify(u):"");a=this.db.ingestBatchWithMetadata(n,i,o)}else a=this.db.ingestBatch(n,i);return this.persistIdMap(),{accepted:a.accepted,rejected:a.rejected}}search(e,t){this.ensureOpen();let n=e instanceof Float32Array?e:new Float32Array(e);return this.db.query(n,t).map(r=>{let a=this.numToStr.get(r.id);return a===void 0?null:{id:a,distance:r.distance,score:1/(1+r.distance)}}).filter(r=>r!==null)}delete(e){this.ensureOpen();let t=[];for(let i of e){let r=this.strToNum.get(i);r!==void 0&&t.push(r)}if(t.length===0)return 0;let n=this.db.delete(t);for(let i of e){let r=this.strToNum.get(i);r!==void 0&&(this.strToNum.delete(i),this.numToStr.delete(r))}return this.persistIdMap(),n.deleted}fork(e){this.ensureOpen(),Q(this._path,e);let t=new Map(this.strToNum),n=new Map(this.numToStr);b(e,t,this.nextLabel);let r=c().RvfDatabase.open(e);return new s(r,e,this._dimension,t,n,this.nextLabel)}status(){this.ensureOpen();let e=this.db.status(),n=this.db.segments().filter(i=>i.segType==="witness");return{totalVectors:e.totalVectors,totalSegments:e.totalSegments,fileSizeBytes:e.fileSize,epoch:e.currentEpoch,witnessValid:n.length>0,witnessEntries:n.length,deadSpaceRatio:typeof e.deadSpaceRatio=="number"?e.deadSpaceRatio:0}}dimension(){return this._dimension}size(){return this.ensureOpen(),this.db.status().totalVectors}compact(){this.ensureOpen();try{let e=this.db.compact();return e&&typeof e=="object"?{segmentsCompacted:typeof e.segmentsCompacted=="number"?e.segmentsCompacted:0,bytesReclaimed:typeof e.bytesReclaimed=="number"?e.bytesReclaimed:0,epoch:typeof e.epoch=="number"?e.epoch:0}:{segmentsCompacted:0,bytesReclaimed:0,epoch:0}}catch{return null}}close(){this._open&&(this.db.close(),this._open=!1)}isOpen(){return this._open}path(){return this._path}embedKernel(e){return this.ensureOpen(),this.db.embedKernel(0,99,0,e,0,"")}extractKernel(){return this.ensureOpen(),this.db.extractKernel()}verifyWitness(){this.ensureOpen();let e=this.tryNative("verifyWitness");return e?{valid:e.valid??!0,totalEntries:e.totalEntries??0,errors:Array.isArray(e.errors)?e.errors:[]}:{valid:!0,totalEntries:0,errors:[]}}sign(e){this.ensureOpen();let t=this.tryNative("sign",e);return typeof t=="string"?t:null}fileId(){this.ensureOpen();let e=this.tryNative("fileId");return typeof e=="string"?e:null}parentId(){this.ensureOpen();let e=this.tryNative("parentId");return typeof e=="string"?e:null}lineageDepth(){this.ensureOpen();let e=this.tryNative("lineageDepth");return typeof e=="number"?e:0}indexStats(){let e=this.status();return{totalVectors:e.totalVectors,dimension:this._dimension,totalSegments:e.totalSegments,fileSizeBytes:e.fileSizeBytes,epoch:e.epoch,witnessValid:e.witnessValid,witnessEntries:e.witnessEntries,idMapSize:this.strToNum.size}}freeze(){this.ensureOpen();let e=this.tryNative("freeze");return typeof e=="number"?e:0}derive(e){this.ensureOpen();let t=c();if(typeof this.db.derive=="function")try{let n=this.db.derive(e),i=new Map(this.strToNum),r=new Map(this.numToStr);return b(e,i,this.nextLabel),new s(n,e,this._dimension,i,r,this.nextLabel)}catch{}return this.fork(e)}ensureOpen(){if(!this._open)throw new Error("RVF database is closed")}tryNative(e,...t){if(typeof this.db[e]!="function")return null;try{return this.db[e](...t)}catch{return null}}persistIdMap(){b(this._path,this.strToNum,this.nextLabel)}}});export{$ as a,G as b,U as c,X as d,Z as e,P as f};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.8");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.9");process.exit(0)}
2
2
  function c(r,e,o){let n=new Error(r);return n.name="LLMError",n.code=e,n.provider=o?.provider,n.model=o?.model,n.retryable=o?.retryable??!1,n.retryAfterMs=o?.retryAfterMs,n.cause=o?.cause,n}function p(r){return r instanceof Error&&"code"in r&&typeof r.code=="string"}var a={"claude-sonnet-4-5":{canonical:"Claude Sonnet 4.5",family:"claude",tier:"standard",providers:{anthropic:"claude-sonnet-4-5-20250929",openrouter:"anthropic/claude-sonnet-4.5",bedrock:"anthropic.claude-sonnet-4-5-v2:0"}},"claude-opus-4":{canonical:"Claude Opus 4",family:"claude",tier:"flagship",providers:{anthropic:"claude-opus-4-20250514",openrouter:"anthropic/claude-opus-4",bedrock:"anthropic.claude-opus-4-v1:0"}},"claude-opus-4-5":{canonical:"Claude Opus 4.5",family:"claude",tier:"flagship",providers:{anthropic:"claude-opus-4-5-20251101",openrouter:"anthropic/claude-opus-4.5",bedrock:"anthropic.claude-opus-4-5-v1:0"}},"claude-haiku-3-5":{canonical:"Claude Haiku 3.5",family:"claude",tier:"economy",providers:{anthropic:"claude-3-5-haiku-20241022",openrouter:"anthropic/claude-3.5-haiku",bedrock:"anthropic.claude-3-5-haiku-v1:0"}},"claude-sonnet-4":{canonical:"Claude Sonnet 4",family:"claude",tier:"standard",providers:{anthropic:"claude-sonnet-4-20250514",openrouter:"anthropic/claude-sonnet-4",bedrock:"anthropic.claude-sonnet-4-v1:0"}},"claude-opus-4-7":{canonical:"Claude Opus 4.7",family:"claude",tier:"flagship",providers:{anthropic:"claude-opus-4-7",openrouter:"anthropic/claude-opus-4.7",bedrock:"anthropic.claude-opus-4-7-v1:0"}},"claude-sonnet-4-6":{canonical:"Claude Sonnet 4.6",family:"claude",tier:"standard",providers:{anthropic:"claude-sonnet-4-6",openrouter:"anthropic/claude-sonnet-4.6",bedrock:"anthropic.claude-sonnet-4-6-v1:0"}},"claude-haiku-4-5":{canonical:"Claude Haiku 4.5",family:"claude",tier:"economy",providers:{anthropic:"claude-haiku-4-5-20251001",openrouter:"anthropic/claude-haiku-4.5",bedrock:"anthropic.claude-haiku-4-5-v1:0"}},"gpt-4o":{canonical:"GPT-4o",family:"gpt",tier:"standard",providers:{openai:"gpt-4o",azure:"gpt-4o",openrouter:"openai/gpt-4o"}},"gpt-4o-mini":{canonical:"GPT-4o Mini",family:"gpt",tier:"economy",providers:{openai:"gpt-4o-mini",azure:"gpt-4o-mini",openrouter:"openai/gpt-4o-mini"}},"gpt-4-turbo":{canonical:"GPT-4 Turbo",family:"gpt",tier:"premium",providers:{openai:"gpt-4-turbo",azure:"gpt-4-turbo",openrouter:"openai/gpt-4-turbo"}},"gpt-4":{canonical:"GPT-4",family:"gpt",tier:"premium",providers:{openai:"gpt-4",azure:"gpt-4",openrouter:"openai/gpt-4"}},o1:{canonical:"OpenAI o1",family:"gpt",tier:"flagship",providers:{openai:"o1",azure:"o1",openrouter:"openai/o1"}},"o1-mini":{canonical:"OpenAI o1 Mini",family:"gpt",tier:"standard",providers:{openai:"o1-mini",azure:"o1-mini",openrouter:"openai/o1-mini"}},"gemini-pro":{canonical:"Gemini Pro",family:"gemini",tier:"standard",providers:{gemini:"gemini-pro",openrouter:"google/gemini-pro"}},"gemini-pro-1.5":{canonical:"Gemini Pro 1.5",family:"gemini",tier:"standard",providers:{gemini:"gemini-1.5-pro",openrouter:"google/gemini-pro-1.5"}},"gemini-flash-1.5":{canonical:"Gemini Flash 1.5",family:"gemini",tier:"economy",providers:{gemini:"gemini-1.5-flash",openrouter:"google/gemini-flash-1.5"}},"gemini-ultra":{canonical:"Gemini Ultra",family:"gemini",tier:"flagship",providers:{gemini:"gemini-ultra",openrouter:"google/gemini-ultra"}},llama3:{canonical:"Llama 3",family:"llama",tier:"economy",providers:{ollama:"llama3",openrouter:"meta-llama/llama-3-8b-instruct"}},"llama3.1":{canonical:"Llama 3.1",family:"llama",tier:"economy",providers:{ollama:"llama3.1",openrouter:"meta-llama/llama-3.1-8b-instruct"}},codellama:{canonical:"CodeLlama",family:"llama",tier:"economy",providers:{ollama:"codellama",openrouter:"meta-llama/codellama-34b-instruct"}},mistral:{canonical:"Mistral",family:"mistral",tier:"economy",providers:{ollama:"mistral",openrouter:"mistralai/mistral-7b-instruct"}},mixtral:{canonical:"Mixtral",family:"mistral",tier:"standard",providers:{ollama:"mixtral",openrouter:"mistralai/mixtral-8x7b-instruct"}},phi3:{canonical:"Phi-3",family:"phi",tier:"economy",providers:{ollama:"phi3",azure:"phi-3-mini-128k-instruct"}},qwen2:{canonical:"Qwen 2",family:"qwen",tier:"economy",providers:{ollama:"qwen2",openrouter:"qwen/qwen-2-7b-instruct"}}};function l(){let r=new Map;for(let[e,o]of Object.entries(a)){r.set(e,e),r.set(e.toLowerCase(),e);for(let[n,t]of Object.entries(o.providers))t&&(r.set(t,e),r.set(t.toLowerCase(),e),r.set(`${n}/${t}`,e),r.set(`${n}/${t}`.toLowerCase(),e))}return r}var i=l();function m(r,e){let o=s(r),n=a[o];if(!n)throw new Error(`Unknown model: ${r}`);let t=n.providers[e];if(!t)throw new Error(`Model '${o}' (${n.canonical}) is not available on provider '${e}'`);return t}function s(r){let e=i.get(r);if(e||(e=i.get(r.toLowerCase()),e))return e;let o=[/^anthropic\//i,/^openai\//i,/^google\//i,/^meta-llama\//i,/^mistralai\//i,/^qwen\//i];for(let n of o){let t=r.replace(n,"");if(e=i.get(t),e||(e=i.get(t.toLowerCase()),e))return e}throw new Error(`Unknown model ID: ${r}`)}function d(r){try{let e=s(r);return a[e]}catch{return}}export{c as a,p as b,m as c,s as d,d as e};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.8");process.exit(0)}
2
- import{e as a}from"./chunk-YQYTQRTR.js";import{b as w,d as y}from"./chunk-DDMKCHYT.js";import{a as f,c as P}from"./chunk-MTWBYHMS.js";import{randomUUID as v}from"crypto";import*as i from"fs";import*as n from"path";import*as c from"os";y();P();var k=".aqe",b="schedules.json",F="1.0.0",g=5e3,x=50,p=10*1024*1024,d=class{schedulesPath;debug;lockFile;initialized=!1;constructor(e={}){e.schedulesPath&&this.validateSchedulesPath(e.schedulesPath),this.schedulesPath=e.schedulesPath??this.getDefaultSchedulesPath(),this.lockFile=`${this.schedulesPath}.lock`,this.debug=e.debug??!1}validateSchedulesPath(e){let s=c.homedir(),t=n.resolve(e),r=n.resolve(s);if(t.startsWith(r+n.sep)||t===r)return;let l=process.cwd(),h=n.resolve(l);if(t.startsWith(h+n.sep)||t===h)return;let u=c.tmpdir(),S=n.resolve(u);if(!(t.startsWith(S+n.sep)||t===S))throw new Error(`Security: Custom schedulesPath must be within home directory (${s}), current working directory (${l}), or temp directory (${u}). Provided path: ${e}`)}getDefaultSchedulesPath(){let e=c.homedir();return n.join(e,k,b)}async initialize(){if(this.initialized)return;let e=n.dirname(this.schedulesPath);i.existsSync(e)||(i.mkdirSync(e,{recursive:!0}),this.log(`Created directory: ${e}`)),this.initialized=!0}async loadSchedules(){if(await this.initialize(),!i.existsSync(this.schedulesPath))return this.log("Schedules file does not exist, returning empty array"),[];try{let e=i.readFileSync(this.schedulesPath,"utf-8"),s=this.parseSchedulesFile(e);return this.log(`Loaded ${s.schedules.length} schedules`),s.schedules}catch(e){return await this.handleCorruptFile(e),[]}}async saveSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.findIndex(r=>r.id===e.id);t>=0?(s[t]=e,this.log(`Updated schedule: ${e.id}`)):(s.push(e),this.log(`Added schedule: ${e.id}`)),await this.writeSchedules(s)})}async removeSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.filter(r=>r.id!==e);if(t.length===s.length){this.log(`Schedule not found: ${e}`);return}await this.writeSchedules(t),this.log(`Removed schedule: ${e}`)})}async getSchedules(){return this.loadSchedules()}async getSchedule(e){return(await this.loadSchedules()).find(t=>t.id===e)}async getDueSchedules(){let e=await this.loadSchedules(),s=new Date;return e.filter(t=>t.enabled?new Date(t.nextRun)<=s:!1)}async markExecuted(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.find(l=>l.id===e);if(!t)throw new Error(`Schedule not found: ${e}`);let r=new Date;t.lastRun=r.toISOString(),t.nextRun=a(t.schedule,r).toISOString(),await this.writeSchedules(s),this.log(`Marked executed: ${e}, next run: ${t.nextRun}`)})}async setEnabled(e,s){await this.initialize(),await this.withFileLock(async()=>{let t=await this.loadSchedulesUnsafe(),r=t.find(l=>l.id===e);if(!r)throw new Error(`Schedule not found: ${e}`);r.enabled=s,s&&(r.nextRun=a(r.schedule,new Date).toISOString()),await this.writeSchedules(t),this.log(`Set enabled=${s}: ${e}`)})}async getEnabledSchedules(){return(await this.loadSchedules()).filter(s=>s.enabled)}async getSchedulesByWorkflow(e){return(await this.loadSchedules()).filter(t=>t.workflowId===e)}async clearAll(){await this.initialize(),await this.withFileLock(async()=>{await this.writeSchedules([]),this.log("Cleared all schedules")})}async getStats(){let e=await this.loadSchedules(),s=new Date;return{total:e.length,enabled:e.filter(t=>t.enabled).length,disabled:e.filter(t=>!t.enabled).length,due:e.filter(t=>t.enabled&&new Date(t.nextRun)<=s).length}}async loadSchedulesUnsafe(){if(!i.existsSync(this.schedulesPath))return[];try{let e=i.readFileSync(this.schedulesPath,"utf-8");return this.parseSchedulesFile(e).schedules}catch{return[]}}parseSchedulesFile(e){let s=Buffer.byteLength(e,"utf-8");if(s>p)throw new Error(`Schedules file exceeds maximum allowed size (${p/(1024*1024)}MB). File is ${(s/(1024*1024)).toFixed(2)}MB.`);let t=w(e);if(!t.schedules||!Array.isArray(t.schedules))throw new Error("Invalid schedules file: missing schedules array");for(let r of t.schedules)if(!r.id||!r.workflowId||!r.schedule)throw new Error("Invalid schedule entry: missing required fields");return t}async writeSchedules(e){let s={version:F,updatedAt:new Date().toISOString(),schedules:e},t=JSON.stringify(s,null,2);i.writeFileSync(this.schedulesPath,t,"utf-8"),this.log(`Wrote ${e.length} schedules to disk`)}async handleCorruptFile(e){let s=f(e);this.log(`Corrupt schedules file detected: ${s}`);let t=`${this.schedulesPath}.corrupt.${Date.now()}`;try{i.existsSync(this.schedulesPath)&&(i.copyFileSync(this.schedulesPath,t),this.log(`Backed up corrupt file to: ${t}`))}catch(r){this.log(`Failed to backup corrupt file: ${r}`)}try{i.existsSync(this.schedulesPath)&&(i.unlinkSync(this.schedulesPath),this.log("Removed corrupt schedules file"))}catch(r){this.log(`Failed to remove corrupt file: ${r}`)}}async withFileLock(e){await this.acquireLock();try{return await e()}finally{this.releaseLock()}}async acquireLock(){let e=Date.now();for(;i.existsSync(this.lockFile);){try{let s=i.statSync(this.lockFile);if(Date.now()-s.mtimeMs>g){i.unlinkSync(this.lockFile),this.log("Removed stale lock file");break}}catch{break}if(Date.now()-e>g)throw new Error("Timeout waiting for scheduler lock");await this.sleep(x)}try{i.writeFileSync(this.lockFile,`${process.pid}:${Date.now()}`,{flag:"wx"})}catch(s){if(s.code==="EEXIST")return this.acquireLock();throw s}}releaseLock(){try{i.existsSync(this.lockFile)&&i.unlinkSync(this.lockFile)}catch(e){console.debug("[PersistentScheduler] Lock release error:",e instanceof Error?e.message:e)}}sleep(e){return new Promise(s=>setTimeout(s,e))}log(e){this.debug&&console.log(`[PersistentScheduler] ${e}`)}};function E(o={}){return new d(o)}function m(){let o=Date.now().toString(36),e=v().slice(0,8);return`sched-${o}-${e}`}function $(o){let e=new Date;return{id:m(),workflowId:o.workflowId,pipelinePath:o.pipelinePath,schedule:o.schedule,scheduleDescription:o.scheduleDescription,nextRun:a(o.schedule,e).toISOString(),enabled:o.enabled??!0,createdAt:e.toISOString()}}export{d as a,E as b,m as c,$ as d};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.9");process.exit(0)}
2
+ import{e as a}from"./chunk-I5C7O5IQ.js";import{b as w,d as y}from"./chunk-246Z3PH6.js";import{a as f,c as P}from"./chunk-5U5SEO7C.js";import{randomUUID as v}from"crypto";import*as i from"fs";import*as n from"path";import*as c from"os";y();P();var k=".aqe",b="schedules.json",F="1.0.0",g=5e3,x=50,p=10*1024*1024,d=class{schedulesPath;debug;lockFile;initialized=!1;constructor(e={}){e.schedulesPath&&this.validateSchedulesPath(e.schedulesPath),this.schedulesPath=e.schedulesPath??this.getDefaultSchedulesPath(),this.lockFile=`${this.schedulesPath}.lock`,this.debug=e.debug??!1}validateSchedulesPath(e){let s=c.homedir(),t=n.resolve(e),r=n.resolve(s);if(t.startsWith(r+n.sep)||t===r)return;let l=process.cwd(),h=n.resolve(l);if(t.startsWith(h+n.sep)||t===h)return;let u=c.tmpdir(),S=n.resolve(u);if(!(t.startsWith(S+n.sep)||t===S))throw new Error(`Security: Custom schedulesPath must be within home directory (${s}), current working directory (${l}), or temp directory (${u}). Provided path: ${e}`)}getDefaultSchedulesPath(){let e=c.homedir();return n.join(e,k,b)}async initialize(){if(this.initialized)return;let e=n.dirname(this.schedulesPath);i.existsSync(e)||(i.mkdirSync(e,{recursive:!0}),this.log(`Created directory: ${e}`)),this.initialized=!0}async loadSchedules(){if(await this.initialize(),!i.existsSync(this.schedulesPath))return this.log("Schedules file does not exist, returning empty array"),[];try{let e=i.readFileSync(this.schedulesPath,"utf-8"),s=this.parseSchedulesFile(e);return this.log(`Loaded ${s.schedules.length} schedules`),s.schedules}catch(e){return await this.handleCorruptFile(e),[]}}async saveSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.findIndex(r=>r.id===e.id);t>=0?(s[t]=e,this.log(`Updated schedule: ${e.id}`)):(s.push(e),this.log(`Added schedule: ${e.id}`)),await this.writeSchedules(s)})}async removeSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.filter(r=>r.id!==e);if(t.length===s.length){this.log(`Schedule not found: ${e}`);return}await this.writeSchedules(t),this.log(`Removed schedule: ${e}`)})}async getSchedules(){return this.loadSchedules()}async getSchedule(e){return(await this.loadSchedules()).find(t=>t.id===e)}async getDueSchedules(){let e=await this.loadSchedules(),s=new Date;return e.filter(t=>t.enabled?new Date(t.nextRun)<=s:!1)}async markExecuted(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.find(l=>l.id===e);if(!t)throw new Error(`Schedule not found: ${e}`);let r=new Date;t.lastRun=r.toISOString(),t.nextRun=a(t.schedule,r).toISOString(),await this.writeSchedules(s),this.log(`Marked executed: ${e}, next run: ${t.nextRun}`)})}async setEnabled(e,s){await this.initialize(),await this.withFileLock(async()=>{let t=await this.loadSchedulesUnsafe(),r=t.find(l=>l.id===e);if(!r)throw new Error(`Schedule not found: ${e}`);r.enabled=s,s&&(r.nextRun=a(r.schedule,new Date).toISOString()),await this.writeSchedules(t),this.log(`Set enabled=${s}: ${e}`)})}async getEnabledSchedules(){return(await this.loadSchedules()).filter(s=>s.enabled)}async getSchedulesByWorkflow(e){return(await this.loadSchedules()).filter(t=>t.workflowId===e)}async clearAll(){await this.initialize(),await this.withFileLock(async()=>{await this.writeSchedules([]),this.log("Cleared all schedules")})}async getStats(){let e=await this.loadSchedules(),s=new Date;return{total:e.length,enabled:e.filter(t=>t.enabled).length,disabled:e.filter(t=>!t.enabled).length,due:e.filter(t=>t.enabled&&new Date(t.nextRun)<=s).length}}async loadSchedulesUnsafe(){if(!i.existsSync(this.schedulesPath))return[];try{let e=i.readFileSync(this.schedulesPath,"utf-8");return this.parseSchedulesFile(e).schedules}catch{return[]}}parseSchedulesFile(e){let s=Buffer.byteLength(e,"utf-8");if(s>p)throw new Error(`Schedules file exceeds maximum allowed size (${p/(1024*1024)}MB). File is ${(s/(1024*1024)).toFixed(2)}MB.`);let t=w(e);if(!t.schedules||!Array.isArray(t.schedules))throw new Error("Invalid schedules file: missing schedules array");for(let r of t.schedules)if(!r.id||!r.workflowId||!r.schedule)throw new Error("Invalid schedule entry: missing required fields");return t}async writeSchedules(e){let s={version:F,updatedAt:new Date().toISOString(),schedules:e},t=JSON.stringify(s,null,2);i.writeFileSync(this.schedulesPath,t,"utf-8"),this.log(`Wrote ${e.length} schedules to disk`)}async handleCorruptFile(e){let s=f(e);this.log(`Corrupt schedules file detected: ${s}`);let t=`${this.schedulesPath}.corrupt.${Date.now()}`;try{i.existsSync(this.schedulesPath)&&(i.copyFileSync(this.schedulesPath,t),this.log(`Backed up corrupt file to: ${t}`))}catch(r){this.log(`Failed to backup corrupt file: ${r}`)}try{i.existsSync(this.schedulesPath)&&(i.unlinkSync(this.schedulesPath),this.log("Removed corrupt schedules file"))}catch(r){this.log(`Failed to remove corrupt file: ${r}`)}}async withFileLock(e){await this.acquireLock();try{return await e()}finally{this.releaseLock()}}async acquireLock(){let e=Date.now();for(;i.existsSync(this.lockFile);){try{let s=i.statSync(this.lockFile);if(Date.now()-s.mtimeMs>g){i.unlinkSync(this.lockFile),this.log("Removed stale lock file");break}}catch{break}if(Date.now()-e>g)throw new Error("Timeout waiting for scheduler lock");await this.sleep(x)}try{i.writeFileSync(this.lockFile,`${process.pid}:${Date.now()}`,{flag:"wx"})}catch(s){if(s.code==="EEXIST")return this.acquireLock();throw s}}releaseLock(){try{i.existsSync(this.lockFile)&&i.unlinkSync(this.lockFile)}catch(e){console.debug("[PersistentScheduler] Lock release error:",e instanceof Error?e.message:e)}}sleep(e){return new Promise(s=>setTimeout(s,e))}log(e){this.debug&&console.log(`[PersistentScheduler] ${e}`)}};function E(o={}){return new d(o)}function m(){let o=Date.now().toString(36),e=v().slice(0,8);return`sched-${o}-${e}`}function $(o){let e=new Date;return{id:m(),workflowId:o.workflowId,pipelinePath:o.pipelinePath,schedule:o.schedule,scheduleDescription:o.scheduleDescription,nextRun:a(o.schedule,e).toISOString(),enabled:o.enabled??!0,createdAt:e.toISOString()}}export{d as a,E as b,m as c,$ as d};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.8");process.exit(0)}
2
- import{o as me}from"./chunk-X3NEQ3SL.js";import{b as w,c as E,d as k,i as de,m as ue}from"./chunk-OLOKPY5O.js";import{a as v}from"./chunk-2B2RLPK3.js";import{c as b}from"./chunk-G73PIM7X.js";import{b as j}from"./chunk-NOP5ZJ7E.js";import{a as Re,b as _,d as ee}from"./chunk-DDMKCHYT.js";import{a as d,b as L,c as P}from"./chunk-MTWBYHMS.js";import{i as I}from"./chunk-NFZY6ZVY.js";import{a as T,b as z}from"./chunk-4OHLPG6B.js";import{a as le,d as Te}from"./chunk-UU422SST.js";import{f as Ce}from"./chunk-SDGRU6SG.js";var A={cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},environment:process.env.AQE_ENV||"all",batchSize:1e3,sources:[{name:"qe-patterns",cloudTable:"aqe.qe_patterns",localTable:"qe_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","embedding","sync_version"],transforms:{reusable:"boolean-to-int"}},{name:"sona-patterns",cloudTable:"aqe.sona_patterns",localTable:"sona_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],transforms:{is_active:"boolean-to-int",requires_fine_tuning:"boolean-to-int"}},{name:"goap-actions",cloudTable:"aqe.goap_actions",localTable:"goap_actions",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{duration_estimate:"estimated_duration_ms"}},{name:"goap-plans",cloudTable:"aqe.goap_plans",localTable:"goap_plans",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{estimated_duration:"estimated_duration_ms"}},{name:"memory-entries",cloudTable:"aqe.memory_entries",localTable:"kv_store",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}},{name:"learning-experiences",cloudTable:"aqe.learning_experiences",localTable:"captured_experiences",enabled:!0,priority:"high",mode:"append",dropColumns:["id","source_env","sync_version"],columnMap:{agent_id:"agent",task_id:"task",task_type:"domain",state:"result_json",action:"steps_json",reward:"quality",next_state:"routing_json",episode_id:"tags",created_at:"started_at"}},{name:"qlearning-patterns",cloudTable:"aqe.qlearning_patterns",localTable:"rl_q_values",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{state:"state_key",action:"action_key",last_update:"updated_at"}},{name:"routing-outcomes",cloudTable:"aqe.routing_outcomes",localTable:"routing_outcomes",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version"]},{name:"qe-trajectories",cloudTable:"aqe.qe_trajectories",localTable:"qe_trajectories",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version","embedding"]},{name:"dream-insights",cloudTable:"aqe.dream_insights",localTable:"dream_insights",enabled:!0,priority:"low",mode:"append",dropColumns:["source_env","sync_version"]},{name:"claude-flow-memory",cloudTable:"aqe.claude_flow_memory",localTable:"kv_store",enabled:!0,priority:"low",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}}]},Pe={TEXT:"TEXT",INTEGER:"INTEGER",REAL:"REAL",BLOB:"BYTEA",NULL:"NULL"},x={local:{v3MemoryDb:"./.agentic-qe/memory.db",rootMemoryDb:"./.agentic-qe/memory.db",claudeFlowMemory:"./.claude-flow/memory/store.json",claudeFlowDaemon:"./.claude-flow/daemon-state.json",claudeFlowMetrics:"./.claude-flow/metrics/",intelligenceJson:"./.ruvector/intelligence.json",swarmMemoryDb:"./.swarm/memory.db",v2PatternsDb:""},cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},sync:{mode:"incremental",interval:"1h",batchSize:1e3,conflictResolution:"newer-wins",sourcePriority:{qePatterns:1,sonaPatterns:2,goapActions:3,kvStore:4,experiences:5,claudeFlowMemory:6,intelligenceJson:7},sources:[{name:"root-qe-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_patterns",priority:"high",mode:"incremental",query:"SELECT id, pattern_type, qe_domain, domain, name, description, confidence, usage_count, success_rate, quality_score, tier, template_json, context_json, successful_uses, created_at, updated_at, last_used_at, tokens_used, input_tokens, output_tokens, latency_ms, reusable, reuse_count, average_token_savings, total_tokens_saved FROM qe_patterns",enabled:!0},{name:"root-sona-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.sona_patterns",priority:"high",mode:"incremental",query:"SELECT * FROM sona_patterns",enabled:!0},{name:"root-goap-actions",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_actions",priority:"high",mode:"incremental",query:"SELECT * FROM goap_actions",enabled:!0},{name:"root-kv-store",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.memory_entries",priority:"high",mode:"incremental",query:"SELECT key, namespace as partition, CASE WHEN json_valid(value) THEN value ELSE json_quote(value) END as value, created_at, expires_at FROM kv_store WHERE json_valid(value) OR json_valid(json_quote(value))",enabled:!0},{name:"root-captured-experiences",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.learning_experiences",priority:"high",mode:"append",query:"SELECT agent as agent_id, task as task_id, domain as task_type, COALESCE(result_json, '{}') as state, COALESCE(steps_json, '{}') as action, quality as reward, COALESCE(routing_json, '{}') as next_state, tags as episode_id, started_at as created_at FROM captured_experiences",enabled:!0},{name:"root-goap-plans",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_plans",priority:"medium",mode:"incremental",query:"SELECT id, goal_id, action_sequence as sequence, initial_state, goal_state, action_sequence, total_cost, estimated_duration_ms as estimated_duration, status, created_at, completed_at FROM goap_plans",enabled:!0},{name:"root-rl-q-values",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qlearning_patterns",priority:"medium",mode:"incremental",query:"SELECT DISTINCT state_key as state, action_key as action, q_value, visits, updated_at as last_update, created_at FROM rl_q_values GROUP BY state_key, action_key",enabled:!0},{name:"root-routing-outcomes",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.routing_outcomes",priority:"medium",mode:"append",query:"SELECT * FROM routing_outcomes",enabled:!0},{name:"root-qe-trajectories",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_trajectories",priority:"medium",mode:"append",query:"SELECT * FROM qe_trajectories",enabled:!0},{name:"root-dream-insights",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.dream_insights",priority:"low",mode:"append",query:"SELECT * FROM dream_insights",enabled:!0},{name:"claude-flow-memory",type:"json",path:"./.claude-flow/memory/store.json",targetTable:"aqe.claude_flow_memory",priority:"medium",mode:"full",enabled:!0},{name:"intelligence-qlearning",type:"json",path:"./.ruvector/intelligence.json",targetTable:"aqe.qlearning_patterns",priority:"low",mode:"full",jsonPath:"$.qvalues",enabled:!0}]},environment:process.env.AQE_ENV||"devpod"};z();k();ee();P();v();import*as te from"fs";import*as ge from"path";var F=b.create("sqlite-reader"),W=class{name;type="sqlite";db=null;config;dbPath;constructor(e){this.config=e,this.name=e.source.name,this.dbPath=ge.resolve(e.baseDir,e.source.path)}async initialize(){if(!this.db){if(!te.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}`);try{this.db=T(this.dbPath,{readonly:!0}),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),console.log(`[SQLiteReader:${this.name}] Initialized: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${d(e)}`)}}}async readAll(){if(!this.db)throw new Error("Reader not initialized");let e=this.config.source.query||`SELECT * FROM ${w(this.getTableName())}`;try{return this.tableExists(this.getTableName())?this.db.prepare(e).all().map(r=>this.transformRecord(r)):(console.warn(`[SQLiteReader:${this.name}] Table not found, returning empty`),[])}catch(t){throw new Error(`Failed to read from ${this.name}: ${d(t)}`)}}async readChanged(e){if(!this.db)throw new Error("Reader not initialized");let t=this.findTimestampColumn();if(!t)return console.warn(`[SQLiteReader:${this.name}] No timestamp column found, falling back to readAll`),this.readAll();let n=this.getTableName();if(!this.tableExists(n))return[];let r=e.toISOString(),i=`SELECT * FROM ${w(n)} WHERE ${t} > ?`;try{return this.db.prepare(i).all(r).map(a=>this.transformRecord(a))}catch{return console.warn(`[SQLiteReader:${this.name}] Changed query failed, falling back to readAll`),this.readAll()}}async count(){if(!this.db)throw new Error("Reader not initialized");let e=this.getTableName();if(!this.tableExists(e))return 0;try{return this.db.prepare(`SELECT COUNT(*) as count FROM ${w(e)}`).get().count}catch(t){return F.debug("Record count query failed",{table:e,error:d(t)}),0}}async close(){this.db&&(this.db.close(),this.db=null,console.log(`[SQLiteReader:${this.name}] Closed`))}getTableName(){let e=this.config.source.query;if(e){let r=e.match(/FROM\s+(\w+)/i);if(r)return r[1]}let n=this.config.source.targetTable.split(".");return n[n.length-1]}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch(t){return F.debug("Table existence check failed",{table:e,error:t instanceof Error?t.message:String(t)}),!1}}findTimestampColumn(){if(!this.db)return null;let e=this.getTableName(),t=["updated_at","created_at","timestamp","last_used_at","modified_at"];try{let i=this.db.prepare(`PRAGMA table_info(${w(e)})`).all().map(o=>o.name.toLowerCase());for(let o of t)if(i.includes(o))return o}catch(n){return F.debug("Timestamp column detection failed",{table:e,error:n instanceof Error?n.message:String(n)}),null}return null}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t)){if(typeof r=="string"&&this.looksLikeJson(r))try{t[n]=_(r)}catch(i){F.debug("JSON parse failed for record field",{key:n,error:i instanceof Error?i.message:String(i)})}if(n.endsWith("_at")&&typeof r=="number"&&(t[n]=new Date(r).toISOString()),r instanceof Buffer)if(n.includes("embedding")){let i=e.dimension||384;t[n]=Array.from(new Float32Array(r.buffer,r.byteOffset,i))}else t[n]=r.toString("base64")}return t}looksLikeJson(e){if(!e)return!1;let t=e.trim();return t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")}getInfo(){let e=te.existsSync(this.dbPath),t=[];if(e&&this.db)try{t=this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all().map(r=>r.name)}catch(n){console.debug("[SQLiteReader] Table listing error:",n instanceof Error?n.message:n)}return{path:this.dbPath,exists:e,tables:t}}};function re(l){return new W(l)}var he=Ce(Re(),1);P();import{randomUUID as ve}from"crypto";import*as C from"fs";import*as pe from"path";var U=class{name;type="json";config;filePath;data=null;fileModTime=null;constructor(e){this.config=e,this.name=e.source.name,this.filePath=pe.resolve(e.baseDir,e.source.path)}async initialize(){if(!C.existsSync(this.filePath)){console.warn(`[JSONReader:${this.name}] File not found: ${this.filePath}`),this.data=[];return}let e=C.statSync(this.filePath);this.fileModTime=e.mtime,console.log(`[JSONReader:${this.name}] Initialized: ${this.filePath}`)}async readAll(){if(!C.existsSync(this.filePath))return[];try{let e=C.readFileSync(this.filePath,"utf-8"),t=he.default.parse(e);return this.extractRecords(t).map(r=>this.transformRecord(r))}catch(e){return console.error(`[JSONReader:${this.name}] Failed to read: ${d(e)}`),[]}}async readChanged(e){return C.existsSync(this.filePath)?C.statSync(this.filePath).mtime<=e?[]:this.readAll():[]}async count(){return(await this.readAll()).length}async close(){this.data=null,this.fileModTime=null,console.log(`[JSONReader:${this.name}] Closed`)}extractRecords(e){return this.config.source.jsonPath?this.extractByPath(e,this.config.source.jsonPath):this.name.includes("claude-flow-memory")?this.extractClaudeFlowMemory(e):this.name.includes("intelligence")||this.name.includes("qlearning")?this.extractIntelligence(e):this.name.includes("daemon")?this.extractDaemonState(e):Array.isArray(e)?e:typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]}extractByPath(e,t){let n=t.replace(/^\$\./,"").split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return[];return Array.isArray(r)?r:typeof r=="object"&&r!==null?Object.entries(r).map(([i,o])=>({state:i,...typeof o=="object"?o:{value:o}})):[]}extractClaudeFlowMemory(e){if(!e||typeof e!="object")return[];let t=[],n=e;for(let[r,i]of Object.entries(n)){if(r.startsWith("_"))continue;let o="general";r.includes("adr")?o="adr-analysis":r.includes("agent")?o="agent-patterns":r.includes("pattern")?o="patterns":r.includes("metric")&&(o="metrics"),t.push({key:r,value:typeof i=="object"?i:{data:i},category:o})}return t}extractIntelligence(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.qvalues&&typeof n.qvalues=="object"){let r=n.qvalues;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null)for(let[s,a]of Object.entries(o)){let c=typeof a=="object"?a:{value:a};t.push({state:i,action:s,q_value:c.value||c.q_value||0,visits:c.visits||0,last_update:c.lastUpdate||c.last_update})}}if(n.memories&&Array.isArray(n.memories)){for(let r of n.memories)if(typeof r=="object"&&r!==null){let i=r;t.push({id:i.id||`mem_${Date.now()}_${ve().slice(0,12)}`,memory_type:i.type||"file_access",content:i.content||i.path,embedding:i.embedding,metadata:i.metadata,timestamp:i.timestamp})}}return t}extractDaemonState(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.workers&&typeof n.workers=="object"){let r=n.workers;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null){let s=o;t.push({worker_type:i,run_count:s.runCount||s.runs||0,success_count:s.successCount||s.successes||0,failure_count:s.failureCount||s.failures||0,avg_duration_ms:s.avgDuration||s.averageDurationMs,last_run:s.lastRun})}}return t}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t))(n.includes("timestamp")||n.endsWith("_at")||n==="last_update")&&(typeof r=="number"?t[n]=new Date(r).toISOString():typeof r=="string"&&!isNaN(Date.parse(r))&&(t[n]=new Date(r).toISOString())),typeof r=="object"&&r!==null&&!Array.isArray(r)&&["value","metadata","embedding"].includes(n);return t.created_at||(t.created_at=new Date().toISOString()),t}getInfo(){let e=C.existsSync(this.filePath),t=0,n=null;if(e){let r=C.statSync(this.filePath);t=r.size,n=r.mtime}return{path:this.filePath,exists:e,modTime:n,size:t}}};function ne(l){return new U(l)}v();import{spawn as _e}from"child_process";import{createConnection as xe}from"net";var ke=b.create("tunnel-manager");function fe(l){try{let e=new URL(l);return e.password&&(e.password="***"),e.toString()}catch(e){return ke.debug("URL parse failed during redaction, using regex fallback",{error:e instanceof Error?e.message:String(e)}),l.replace(/:\/\/([^:]+):([^@]+)@/,"://$1:***@")}}var M=class{process=null;connection=null;config;constructor(e){this.config=e}checkPort(e,t,n=2e3){return new Promise(r=>{let i=xe({host:e,port:t}),o=setTimeout(()=>{i.destroy(),r(!1)},n);i.on("connect",()=>{clearTimeout(o),i.destroy(),r(!0)}),i.on("error",()=>{clearTimeout(o),i.destroy(),r(!1)})})}async start(){return this.process&&this.connection?(console.log("[TunnelManager] Tunnel already running"),this.connection):await this.checkPort("localhost",this.config.tunnelPort)?(console.log(`[TunnelManager] External tunnel detected on port ${this.config.tunnelPort}, reusing`),this.connection={host:"localhost",port:this.config.tunnelPort,startedAt:new Date},this.connection):new Promise((t,n)=>{let r=["compute","start-iap-tunnel",this.config.instance,"5432",`--local-host-port=localhost:${this.config.tunnelPort}`,`--zone=${this.config.zone}`,`--project=${this.config.project}`];console.log(`[TunnelManager] Starting IAP tunnel: gcloud ${r.join(" ")}`),this.process=_e("gcloud",r,{stdio:["ignore","pipe","pipe"]});let i=!1,o="",s=!1;this.process.stderr?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`),["Listening on port","tunnel is running","Testing if tunnel connection works"].some(m=>c.includes(m))&&!i&&!s&&(s=!0,setTimeout(async()=>{for(let g=0;g<10;g++){if(console.log(`[TunnelManager] Checking port connectivity (attempt ${g+1}/10)...`),await this.checkPort("localhost",this.config.tunnelPort)){i=!0,this.connection={host:"localhost",port:this.config.tunnelPort,pid:this.process?.pid,startedAt:new Date},console.log(`[TunnelManager] Tunnel ready on port ${this.config.tunnelPort}`),t(this.connection);return}await new Promise(y=>setTimeout(y,1e3))}s=!1},2e3)),o+=c}),this.process.stdout?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`)}),this.process.on("error",a=>{console.error(`[TunnelManager] Process error: ${a.message}`),i||n(new Error(`Failed to start tunnel: ${a.message}`))}),this.process.on("close",a=>{console.log(`[TunnelManager] Process closed with code ${a}`),this.process=null,this.connection=null,i||n(new Error(`Tunnel process exited with code ${a}: ${o}`))}),setTimeout(()=>{i||(this.stop(),n(new Error("Tunnel connection timeout")))},6e4)})}async stop(){this.process&&(console.log("[TunnelManager] Stopping tunnel"),this.process.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),this.process&&this.process.kill("SIGKILL"),this.process=null,this.connection=null)}isActive(){return this.process!==null&&this.connection!==null}getConnection(){return this.connection}getConnectionString(){if(!this.connection)throw new Error("Tunnel not active");let{database:e,user:t}=this.config,n=process.env.PGPASSWORD||"",r=this.connection.host,i=this.connection.port;return`postgresql://${t}:${n}@${r}:${i}/${e}`}getRedactedConnectionString(){return fe(this.getConnectionString())}};function Ae(l){return new M(l)}var B=class{connection=null;connectionString;constructor(e){this.connectionString=e}async start(){let e=new URL(this.connectionString);return this.connection={host:e.hostname,port:parseInt(e.port||"5432",10),startedAt:new Date},this.connection}async stop(){this.connection=null}isActive(){return this.connection!==null}getConnection(){return this.connection}getConnectionString(){return this.connectionString}getRedactedConnectionString(){return fe(this.connectionString)}};function $(l){return l.connectionString?new B(l.connectionString):new M(l)}k();P();v();import{createRequire as Me}from"module";var N=b.create("postgres-writer"),$e=Me(import.meta.url),J=class{client=null;config;inTransaction=!1;connected=!1;constructor(e){this.config=e}async connect(){if(this.connected)return;this.config.tunnelManager.isActive()||await this.config.tunnelManager.start();let e=this.config.tunnelManager.getConnection();if(!e)throw new Error("No tunnel connection available");let t;try{t=$e("pg")}catch(o){N.debug("pg module not installed, using mock mode",{error:o instanceof Error?o.message:String(o)}),console.warn("[PostgresWriter] pg module not installed, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let n=t.default,r=t.Client||n?.Client;if(!r){console.warn("[PostgresWriter] pg.Client not found in module, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let i={host:e.host,port:e.port,database:this.config.cloud.database,user:this.config.cloud.user,password:process.env.PGPASSWORD||"",connectionTimeoutMillis:this.config.connectionTimeout||1e4};this.client=new r(i),await this.client.connect(),this.connected=!0,console.log(`[PostgresWriter] Connected to ${e.host}:${e.port}/${this.config.cloud.database}`)}async beginTransaction(){if(!this.client)throw new Error("Not connected");await this.client.query("BEGIN"),this.inTransaction=!0}async commit(){if(!this.client||!this.inTransaction)throw new Error("No active transaction");await this.client.query("COMMIT"),this.inTransaction=!1}async rollback(){!this.client||!this.inTransaction||(await this.client.query("ROLLBACK"),this.inTransaction=!1)}async upsert(e,t,n){if(!this.client)throw new Error("Not connected");if(t.length===0)return 0;let r=t[0],i=Object.keys(r),o=n?.conflictColumns||this.inferConflictColumns(e,i),s=n?.updateColumns||i.filter(u=>!o.includes(u)),a=0,c=100;for(let u=0;u<t.length;u+=c){let p=t.slice(u,u+c);try{let m=await this.upsertBatch(e,p,i,o,s,n?.skipIfExists);a+=m}catch(m){let g=Math.floor(u/c)+1,h=Math.ceil(t.length/c);N.debug(`Batch ${g}/${h} failed for ${e}, retrying individually`,{error:d(m)});let y=0;for(let f of p)try{let S=await this.upsertBatch(e,[f],i,o,s,n?.skipIfExists);y+=S}catch(S){let R=f.id||f.key||"?";N.debug(`Skipped record ${String(R).slice(0,50)} in ${e}`,{error:d(S)})}a+=y,y<p.length&&console.warn(`[PostgresWriter] Batch ${g}/${h} for ${e}: ${y}/${p.length} recovered (${p.length-y} skipped)`)}}return a}async upsertBatch(e,t,n,r,i,o){if(!this.client)return 0;let s=[],a=[],c=1;for(let f of t){let S=[];for(let R of n){let Ee=f[R];S.push(`$${c++}`),a.push(this.serializeValue(Ee,R))}s.push(`(${S.join(", ")})`)}let u=E(e),p=n.map(E),m=r.map(E),g=i.map(E),h="";if(m.length>0){if(o)h=`ON CONFLICT (${m.join(", ")}) DO NOTHING`;else if(g.length>0){let f=g.map(S=>`${S} = EXCLUDED.${S}`).join(", ");h=`ON CONFLICT (${m.join(", ")}) DO UPDATE SET ${f}`}}let y=`
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.9");process.exit(0)}
2
+ import{o as me}from"./chunk-DZWZASDV.js";import{b as w,c as E,d as k,i as de,m as ue}from"./chunk-L5NEEGKO.js";import{a as v}from"./chunk-OPKEQYAC.js";import{c as b}from"./chunk-VHYNRISI.js";import{b as j}from"./chunk-ZT2DGSIO.js";import{a as Re,b as _,d as ee}from"./chunk-246Z3PH6.js";import{a as d,b as L,c as P}from"./chunk-5U5SEO7C.js";import{i as I}from"./chunk-QWXJRZEH.js";import{a as T,b as z}from"./chunk-D7NWDUY3.js";import{a as le,d as Te}from"./chunk-C6GQIUKW.js";import{f as Ce}from"./chunk-ABJPFKHE.js";var A={cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},environment:process.env.AQE_ENV||"all",batchSize:1e3,sources:[{name:"qe-patterns",cloudTable:"aqe.qe_patterns",localTable:"qe_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","embedding","sync_version"],transforms:{reusable:"boolean-to-int"}},{name:"sona-patterns",cloudTable:"aqe.sona_patterns",localTable:"sona_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],transforms:{is_active:"boolean-to-int",requires_fine_tuning:"boolean-to-int"}},{name:"goap-actions",cloudTable:"aqe.goap_actions",localTable:"goap_actions",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{duration_estimate:"estimated_duration_ms"}},{name:"goap-plans",cloudTable:"aqe.goap_plans",localTable:"goap_plans",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{estimated_duration:"estimated_duration_ms"}},{name:"memory-entries",cloudTable:"aqe.memory_entries",localTable:"kv_store",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}},{name:"learning-experiences",cloudTable:"aqe.learning_experiences",localTable:"captured_experiences",enabled:!0,priority:"high",mode:"append",dropColumns:["id","source_env","sync_version"],columnMap:{agent_id:"agent",task_id:"task",task_type:"domain",state:"result_json",action:"steps_json",reward:"quality",next_state:"routing_json",episode_id:"tags",created_at:"started_at"}},{name:"qlearning-patterns",cloudTable:"aqe.qlearning_patterns",localTable:"rl_q_values",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{state:"state_key",action:"action_key",last_update:"updated_at"}},{name:"routing-outcomes",cloudTable:"aqe.routing_outcomes",localTable:"routing_outcomes",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version"]},{name:"qe-trajectories",cloudTable:"aqe.qe_trajectories",localTable:"qe_trajectories",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version","embedding"]},{name:"dream-insights",cloudTable:"aqe.dream_insights",localTable:"dream_insights",enabled:!0,priority:"low",mode:"append",dropColumns:["source_env","sync_version"]},{name:"claude-flow-memory",cloudTable:"aqe.claude_flow_memory",localTable:"kv_store",enabled:!0,priority:"low",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}}]},Pe={TEXT:"TEXT",INTEGER:"INTEGER",REAL:"REAL",BLOB:"BYTEA",NULL:"NULL"},x={local:{v3MemoryDb:"./.agentic-qe/memory.db",rootMemoryDb:"./.agentic-qe/memory.db",claudeFlowMemory:"./.claude-flow/memory/store.json",claudeFlowDaemon:"./.claude-flow/daemon-state.json",claudeFlowMetrics:"./.claude-flow/metrics/",intelligenceJson:"./.ruvector/intelligence.json",swarmMemoryDb:"./.swarm/memory.db",v2PatternsDb:""},cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},sync:{mode:"incremental",interval:"1h",batchSize:1e3,conflictResolution:"newer-wins",sourcePriority:{qePatterns:1,sonaPatterns:2,goapActions:3,kvStore:4,experiences:5,claudeFlowMemory:6,intelligenceJson:7},sources:[{name:"root-qe-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_patterns",priority:"high",mode:"incremental",query:"SELECT id, pattern_type, qe_domain, domain, name, description, confidence, usage_count, success_rate, quality_score, tier, template_json, context_json, successful_uses, created_at, updated_at, last_used_at, tokens_used, input_tokens, output_tokens, latency_ms, reusable, reuse_count, average_token_savings, total_tokens_saved FROM qe_patterns",enabled:!0},{name:"root-sona-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.sona_patterns",priority:"high",mode:"incremental",query:"SELECT * FROM sona_patterns",enabled:!0},{name:"root-goap-actions",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_actions",priority:"high",mode:"incremental",query:"SELECT * FROM goap_actions",enabled:!0},{name:"root-kv-store",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.memory_entries",priority:"high",mode:"incremental",query:"SELECT key, namespace as partition, CASE WHEN json_valid(value) THEN value ELSE json_quote(value) END as value, created_at, expires_at FROM kv_store WHERE json_valid(value) OR json_valid(json_quote(value))",enabled:!0},{name:"root-captured-experiences",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.learning_experiences",priority:"high",mode:"append",query:"SELECT agent as agent_id, task as task_id, domain as task_type, COALESCE(result_json, '{}') as state, COALESCE(steps_json, '{}') as action, quality as reward, COALESCE(routing_json, '{}') as next_state, tags as episode_id, started_at as created_at FROM captured_experiences",enabled:!0},{name:"root-goap-plans",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_plans",priority:"medium",mode:"incremental",query:"SELECT id, goal_id, action_sequence as sequence, initial_state, goal_state, action_sequence, total_cost, estimated_duration_ms as estimated_duration, status, created_at, completed_at FROM goap_plans",enabled:!0},{name:"root-rl-q-values",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qlearning_patterns",priority:"medium",mode:"incremental",query:"SELECT DISTINCT state_key as state, action_key as action, q_value, visits, updated_at as last_update, created_at FROM rl_q_values GROUP BY state_key, action_key",enabled:!0},{name:"root-routing-outcomes",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.routing_outcomes",priority:"medium",mode:"append",query:"SELECT * FROM routing_outcomes",enabled:!0},{name:"root-qe-trajectories",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_trajectories",priority:"medium",mode:"append",query:"SELECT * FROM qe_trajectories",enabled:!0},{name:"root-dream-insights",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.dream_insights",priority:"low",mode:"append",query:"SELECT * FROM dream_insights",enabled:!0},{name:"claude-flow-memory",type:"json",path:"./.claude-flow/memory/store.json",targetTable:"aqe.claude_flow_memory",priority:"medium",mode:"full",enabled:!0},{name:"intelligence-qlearning",type:"json",path:"./.ruvector/intelligence.json",targetTable:"aqe.qlearning_patterns",priority:"low",mode:"full",jsonPath:"$.qvalues",enabled:!0}]},environment:process.env.AQE_ENV||"devpod"};z();k();ee();P();v();import*as te from"fs";import*as ge from"path";var F=b.create("sqlite-reader"),W=class{name;type="sqlite";db=null;config;dbPath;constructor(e){this.config=e,this.name=e.source.name,this.dbPath=ge.resolve(e.baseDir,e.source.path)}async initialize(){if(!this.db){if(!te.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}`);try{this.db=T(this.dbPath,{readonly:!0}),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),console.log(`[SQLiteReader:${this.name}] Initialized: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${d(e)}`)}}}async readAll(){if(!this.db)throw new Error("Reader not initialized");let e=this.config.source.query||`SELECT * FROM ${w(this.getTableName())}`;try{return this.tableExists(this.getTableName())?this.db.prepare(e).all().map(r=>this.transformRecord(r)):(console.warn(`[SQLiteReader:${this.name}] Table not found, returning empty`),[])}catch(t){throw new Error(`Failed to read from ${this.name}: ${d(t)}`)}}async readChanged(e){if(!this.db)throw new Error("Reader not initialized");let t=this.findTimestampColumn();if(!t)return console.warn(`[SQLiteReader:${this.name}] No timestamp column found, falling back to readAll`),this.readAll();let n=this.getTableName();if(!this.tableExists(n))return[];let r=e.toISOString(),i=`SELECT * FROM ${w(n)} WHERE ${t} > ?`;try{return this.db.prepare(i).all(r).map(a=>this.transformRecord(a))}catch{return console.warn(`[SQLiteReader:${this.name}] Changed query failed, falling back to readAll`),this.readAll()}}async count(){if(!this.db)throw new Error("Reader not initialized");let e=this.getTableName();if(!this.tableExists(e))return 0;try{return this.db.prepare(`SELECT COUNT(*) as count FROM ${w(e)}`).get().count}catch(t){return F.debug("Record count query failed",{table:e,error:d(t)}),0}}async close(){this.db&&(this.db.close(),this.db=null,console.log(`[SQLiteReader:${this.name}] Closed`))}getTableName(){let e=this.config.source.query;if(e){let r=e.match(/FROM\s+(\w+)/i);if(r)return r[1]}let n=this.config.source.targetTable.split(".");return n[n.length-1]}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch(t){return F.debug("Table existence check failed",{table:e,error:t instanceof Error?t.message:String(t)}),!1}}findTimestampColumn(){if(!this.db)return null;let e=this.getTableName(),t=["updated_at","created_at","timestamp","last_used_at","modified_at"];try{let i=this.db.prepare(`PRAGMA table_info(${w(e)})`).all().map(o=>o.name.toLowerCase());for(let o of t)if(i.includes(o))return o}catch(n){return F.debug("Timestamp column detection failed",{table:e,error:n instanceof Error?n.message:String(n)}),null}return null}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t)){if(typeof r=="string"&&this.looksLikeJson(r))try{t[n]=_(r)}catch(i){F.debug("JSON parse failed for record field",{key:n,error:i instanceof Error?i.message:String(i)})}if(n.endsWith("_at")&&typeof r=="number"&&(t[n]=new Date(r).toISOString()),r instanceof Buffer)if(n.includes("embedding")){let i=e.dimension||384;t[n]=Array.from(new Float32Array(r.buffer,r.byteOffset,i))}else t[n]=r.toString("base64")}return t}looksLikeJson(e){if(!e)return!1;let t=e.trim();return t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")}getInfo(){let e=te.existsSync(this.dbPath),t=[];if(e&&this.db)try{t=this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all().map(r=>r.name)}catch(n){console.debug("[SQLiteReader] Table listing error:",n instanceof Error?n.message:n)}return{path:this.dbPath,exists:e,tables:t}}};function re(l){return new W(l)}var he=Ce(Re(),1);P();import{randomUUID as ve}from"crypto";import*as C from"fs";import*as pe from"path";var U=class{name;type="json";config;filePath;data=null;fileModTime=null;constructor(e){this.config=e,this.name=e.source.name,this.filePath=pe.resolve(e.baseDir,e.source.path)}async initialize(){if(!C.existsSync(this.filePath)){console.warn(`[JSONReader:${this.name}] File not found: ${this.filePath}`),this.data=[];return}let e=C.statSync(this.filePath);this.fileModTime=e.mtime,console.log(`[JSONReader:${this.name}] Initialized: ${this.filePath}`)}async readAll(){if(!C.existsSync(this.filePath))return[];try{let e=C.readFileSync(this.filePath,"utf-8"),t=he.default.parse(e);return this.extractRecords(t).map(r=>this.transformRecord(r))}catch(e){return console.error(`[JSONReader:${this.name}] Failed to read: ${d(e)}`),[]}}async readChanged(e){return C.existsSync(this.filePath)?C.statSync(this.filePath).mtime<=e?[]:this.readAll():[]}async count(){return(await this.readAll()).length}async close(){this.data=null,this.fileModTime=null,console.log(`[JSONReader:${this.name}] Closed`)}extractRecords(e){return this.config.source.jsonPath?this.extractByPath(e,this.config.source.jsonPath):this.name.includes("claude-flow-memory")?this.extractClaudeFlowMemory(e):this.name.includes("intelligence")||this.name.includes("qlearning")?this.extractIntelligence(e):this.name.includes("daemon")?this.extractDaemonState(e):Array.isArray(e)?e:typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]}extractByPath(e,t){let n=t.replace(/^\$\./,"").split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return[];return Array.isArray(r)?r:typeof r=="object"&&r!==null?Object.entries(r).map(([i,o])=>({state:i,...typeof o=="object"?o:{value:o}})):[]}extractClaudeFlowMemory(e){if(!e||typeof e!="object")return[];let t=[],n=e;for(let[r,i]of Object.entries(n)){if(r.startsWith("_"))continue;let o="general";r.includes("adr")?o="adr-analysis":r.includes("agent")?o="agent-patterns":r.includes("pattern")?o="patterns":r.includes("metric")&&(o="metrics"),t.push({key:r,value:typeof i=="object"?i:{data:i},category:o})}return t}extractIntelligence(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.qvalues&&typeof n.qvalues=="object"){let r=n.qvalues;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null)for(let[s,a]of Object.entries(o)){let c=typeof a=="object"?a:{value:a};t.push({state:i,action:s,q_value:c.value||c.q_value||0,visits:c.visits||0,last_update:c.lastUpdate||c.last_update})}}if(n.memories&&Array.isArray(n.memories)){for(let r of n.memories)if(typeof r=="object"&&r!==null){let i=r;t.push({id:i.id||`mem_${Date.now()}_${ve().slice(0,12)}`,memory_type:i.type||"file_access",content:i.content||i.path,embedding:i.embedding,metadata:i.metadata,timestamp:i.timestamp})}}return t}extractDaemonState(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.workers&&typeof n.workers=="object"){let r=n.workers;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null){let s=o;t.push({worker_type:i,run_count:s.runCount||s.runs||0,success_count:s.successCount||s.successes||0,failure_count:s.failureCount||s.failures||0,avg_duration_ms:s.avgDuration||s.averageDurationMs,last_run:s.lastRun})}}return t}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t))(n.includes("timestamp")||n.endsWith("_at")||n==="last_update")&&(typeof r=="number"?t[n]=new Date(r).toISOString():typeof r=="string"&&!isNaN(Date.parse(r))&&(t[n]=new Date(r).toISOString())),typeof r=="object"&&r!==null&&!Array.isArray(r)&&["value","metadata","embedding"].includes(n);return t.created_at||(t.created_at=new Date().toISOString()),t}getInfo(){let e=C.existsSync(this.filePath),t=0,n=null;if(e){let r=C.statSync(this.filePath);t=r.size,n=r.mtime}return{path:this.filePath,exists:e,modTime:n,size:t}}};function ne(l){return new U(l)}v();import{spawn as _e}from"child_process";import{createConnection as xe}from"net";var ke=b.create("tunnel-manager");function fe(l){try{let e=new URL(l);return e.password&&(e.password="***"),e.toString()}catch(e){return ke.debug("URL parse failed during redaction, using regex fallback",{error:e instanceof Error?e.message:String(e)}),l.replace(/:\/\/([^:]+):([^@]+)@/,"://$1:***@")}}var M=class{process=null;connection=null;config;constructor(e){this.config=e}checkPort(e,t,n=2e3){return new Promise(r=>{let i=xe({host:e,port:t}),o=setTimeout(()=>{i.destroy(),r(!1)},n);i.on("connect",()=>{clearTimeout(o),i.destroy(),r(!0)}),i.on("error",()=>{clearTimeout(o),i.destroy(),r(!1)})})}async start(){return this.process&&this.connection?(console.log("[TunnelManager] Tunnel already running"),this.connection):await this.checkPort("localhost",this.config.tunnelPort)?(console.log(`[TunnelManager] External tunnel detected on port ${this.config.tunnelPort}, reusing`),this.connection={host:"localhost",port:this.config.tunnelPort,startedAt:new Date},this.connection):new Promise((t,n)=>{let r=["compute","start-iap-tunnel",this.config.instance,"5432",`--local-host-port=localhost:${this.config.tunnelPort}`,`--zone=${this.config.zone}`,`--project=${this.config.project}`];console.log(`[TunnelManager] Starting IAP tunnel: gcloud ${r.join(" ")}`),this.process=_e("gcloud",r,{stdio:["ignore","pipe","pipe"]});let i=!1,o="",s=!1;this.process.stderr?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`),["Listening on port","tunnel is running","Testing if tunnel connection works"].some(m=>c.includes(m))&&!i&&!s&&(s=!0,setTimeout(async()=>{for(let g=0;g<10;g++){if(console.log(`[TunnelManager] Checking port connectivity (attempt ${g+1}/10)...`),await this.checkPort("localhost",this.config.tunnelPort)){i=!0,this.connection={host:"localhost",port:this.config.tunnelPort,pid:this.process?.pid,startedAt:new Date},console.log(`[TunnelManager] Tunnel ready on port ${this.config.tunnelPort}`),t(this.connection);return}await new Promise(y=>setTimeout(y,1e3))}s=!1},2e3)),o+=c}),this.process.stdout?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`)}),this.process.on("error",a=>{console.error(`[TunnelManager] Process error: ${a.message}`),i||n(new Error(`Failed to start tunnel: ${a.message}`))}),this.process.on("close",a=>{console.log(`[TunnelManager] Process closed with code ${a}`),this.process=null,this.connection=null,i||n(new Error(`Tunnel process exited with code ${a}: ${o}`))}),setTimeout(()=>{i||(this.stop(),n(new Error("Tunnel connection timeout")))},6e4)})}async stop(){this.process&&(console.log("[TunnelManager] Stopping tunnel"),this.process.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),this.process&&this.process.kill("SIGKILL"),this.process=null,this.connection=null)}isActive(){return this.process!==null&&this.connection!==null}getConnection(){return this.connection}getConnectionString(){if(!this.connection)throw new Error("Tunnel not active");let{database:e,user:t}=this.config,n=process.env.PGPASSWORD||"",r=this.connection.host,i=this.connection.port;return`postgresql://${t}:${n}@${r}:${i}/${e}`}getRedactedConnectionString(){return fe(this.getConnectionString())}};function Ae(l){return new M(l)}var B=class{connection=null;connectionString;constructor(e){this.connectionString=e}async start(){let e=new URL(this.connectionString);return this.connection={host:e.hostname,port:parseInt(e.port||"5432",10),startedAt:new Date},this.connection}async stop(){this.connection=null}isActive(){return this.connection!==null}getConnection(){return this.connection}getConnectionString(){return this.connectionString}getRedactedConnectionString(){return fe(this.connectionString)}};function $(l){return l.connectionString?new B(l.connectionString):new M(l)}k();P();v();import{createRequire as Me}from"module";var N=b.create("postgres-writer"),$e=Me(import.meta.url),J=class{client=null;config;inTransaction=!1;connected=!1;constructor(e){this.config=e}async connect(){if(this.connected)return;this.config.tunnelManager.isActive()||await this.config.tunnelManager.start();let e=this.config.tunnelManager.getConnection();if(!e)throw new Error("No tunnel connection available");let t;try{t=$e("pg")}catch(o){N.debug("pg module not installed, using mock mode",{error:o instanceof Error?o.message:String(o)}),console.warn("[PostgresWriter] pg module not installed, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let n=t.default,r=t.Client||n?.Client;if(!r){console.warn("[PostgresWriter] pg.Client not found in module, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let i={host:e.host,port:e.port,database:this.config.cloud.database,user:this.config.cloud.user,password:process.env.PGPASSWORD||"",connectionTimeoutMillis:this.config.connectionTimeout||1e4};this.client=new r(i),await this.client.connect(),this.connected=!0,console.log(`[PostgresWriter] Connected to ${e.host}:${e.port}/${this.config.cloud.database}`)}async beginTransaction(){if(!this.client)throw new Error("Not connected");await this.client.query("BEGIN"),this.inTransaction=!0}async commit(){if(!this.client||!this.inTransaction)throw new Error("No active transaction");await this.client.query("COMMIT"),this.inTransaction=!1}async rollback(){!this.client||!this.inTransaction||(await this.client.query("ROLLBACK"),this.inTransaction=!1)}async upsert(e,t,n){if(!this.client)throw new Error("Not connected");if(t.length===0)return 0;let r=t[0],i=Object.keys(r),o=n?.conflictColumns||this.inferConflictColumns(e,i),s=n?.updateColumns||i.filter(u=>!o.includes(u)),a=0,c=100;for(let u=0;u<t.length;u+=c){let p=t.slice(u,u+c);try{let m=await this.upsertBatch(e,p,i,o,s,n?.skipIfExists);a+=m}catch(m){let g=Math.floor(u/c)+1,h=Math.ceil(t.length/c);N.debug(`Batch ${g}/${h} failed for ${e}, retrying individually`,{error:d(m)});let y=0;for(let f of p)try{let S=await this.upsertBatch(e,[f],i,o,s,n?.skipIfExists);y+=S}catch(S){let R=f.id||f.key||"?";N.debug(`Skipped record ${String(R).slice(0,50)} in ${e}`,{error:d(S)})}a+=y,y<p.length&&console.warn(`[PostgresWriter] Batch ${g}/${h} for ${e}: ${y}/${p.length} recovered (${p.length-y} skipped)`)}}return a}async upsertBatch(e,t,n,r,i,o){if(!this.client)return 0;let s=[],a=[],c=1;for(let f of t){let S=[];for(let R of n){let Ee=f[R];S.push(`$${c++}`),a.push(this.serializeValue(Ee,R))}s.push(`(${S.join(", ")})`)}let u=E(e),p=n.map(E),m=r.map(E),g=i.map(E),h="";if(m.length>0){if(o)h=`ON CONFLICT (${m.join(", ")}) DO NOTHING`;else if(g.length>0){let f=g.map(S=>`${S} = EXCLUDED.${S}`).join(", ");h=`ON CONFLICT (${m.join(", ")}) DO UPDATE SET ${f}`}}let y=`
3
3
  INSERT INTO ${u} (${p.join(", ")})
4
4
  VALUES ${s.join(", ")}
5
5
  ${h}
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.8");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.9");process.exit(0)}
2
2
  var h=Object.create;var f=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,c)=>()=>{if(c)throw c[0];try{return a&&(b=a(a=0)),b}catch(d){throw c=[d],d}};var p=(a,b)=>()=>{try{return b||a((b={exports:{}}).exports,b),b.exports}catch(c){throw b=0,c}},q=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0})},g=(a,b,c,d)=>{if(b&&typeof b=="object"||typeof b=="function")for(let e of j(b))!l.call(a,e)&&e!==c&&f(a,e,{get:()=>b[e],enumerable:!(d=i(b,e))||d.enumerable});return a};var r=(a,b,c)=>(c=a!=null?h(k(a)):{},g(b||!a||!a.__esModule?f(c,"default",{value:a,enumerable:!0}):c,a)),s=a=>g(f({},"__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};