agentic-qe 3.9.7 → 3.9.8

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 (270) hide show
  1. package/.claude/skills/skills-manifest.json +2 -2
  2. package/CHANGELOG.md +26 -0
  3. package/dist/cli/bundle.js +5 -5
  4. package/dist/cli/chunks/adapter-D4XQUIJD.js +2 -0
  5. package/dist/cli/chunks/{agent-booster-wasm-MXTWTD4D.js → agent-booster-wasm-LAE4NTVX.js} +2 -2
  6. package/dist/cli/chunks/{agent-handler-6NEP2BOA.js → agent-handler-FVXHR6XN.js} +2 -2
  7. package/dist/cli/chunks/{agent-memory-branch-SAPEIGE2.js → agent-memory-branch-Q7LLBA7C.js} +2 -2
  8. package/dist/cli/chunks/aqe-learning-engine-CGIWYLIP.js +2 -0
  9. package/dist/cli/chunks/{audit-53LCI6R3.js → audit-YRLKHJLX.js} +2 -2
  10. package/dist/cli/chunks/base-BYVP2STR.js +2 -0
  11. package/dist/cli/chunks/{better-sqlite3-UZSKFGCK.js → better-sqlite3-XFGOGICB.js} +2 -2
  12. package/dist/cli/chunks/{brain-handler-67NDDXVO.js → brain-handler-KIUSNVSS.js} +3 -3
  13. package/dist/cli/chunks/{branch-enumerator-IUIGYEK5.js → branch-enumerator-VKZ4L3FH.js} +2 -2
  14. package/dist/cli/chunks/{browser-UFUF65LQ.js → browser-GZVIYFIB.js} +2 -2
  15. package/dist/cli/chunks/browser-workflow-PC4N5TKL.js +2 -0
  16. package/dist/cli/chunks/{chunk-QI5VGEKC.js → chunk-237NNDKL.js} +2 -2
  17. package/dist/cli/chunks/{chunk-CDFYF33M.js → chunk-266SKKFM.js} +2 -2
  18. package/dist/cli/chunks/{chunk-7OPVTN5W.js → chunk-2K3DJ3EK.js} +2 -2
  19. package/dist/cli/chunks/{chunk-IQLFWO5U.js → chunk-2QI5RYVR.js} +2 -2
  20. package/dist/cli/chunks/{chunk-TD2WOW75.js → chunk-2V5VKOJ2.js} +2 -2
  21. package/dist/cli/chunks/{chunk-DS3XAGGL.js → chunk-3WOQMFTD.js} +2 -2
  22. package/dist/cli/chunks/{chunk-KZSZHP32.js → chunk-3ZAGYTEC.js} +2 -2
  23. package/dist/cli/chunks/{chunk-6ULPQTIE.js → chunk-4EAAHMVM.js} +2 -2
  24. package/dist/cli/chunks/{chunk-52MUZGZF.js → chunk-4GMV6Z7Y.js} +2 -2
  25. package/dist/cli/chunks/{chunk-FBVEHGNE.js → chunk-4KX6TMKB.js} +3 -3
  26. package/dist/cli/chunks/{chunk-HFPT7QXQ.js → chunk-5TGK7VTS.js} +2 -2
  27. package/dist/cli/chunks/{chunk-D2C4XNF5.js → chunk-66DCG6RO.js} +4 -4
  28. package/dist/cli/chunks/{chunk-W4Y4GFRB.js → chunk-677V67MR.js} +1 -1
  29. package/dist/cli/chunks/{chunk-6MMRZYYS.js → chunk-6A4FEIE2.js} +3 -3
  30. package/dist/cli/chunks/{chunk-YR5ZNQT2.js → chunk-6DBYVKGA.js} +2 -2
  31. package/dist/cli/chunks/{chunk-EL2WLSUI.js → chunk-6KWX7A3R.js} +2 -2
  32. package/dist/cli/chunks/{chunk-YTF5G3RQ.js → chunk-6ZMM7MXA.js} +2 -2
  33. package/dist/cli/chunks/{chunk-XY5FMZRA.js → chunk-76UL224Z.js} +2 -2
  34. package/dist/cli/chunks/{chunk-KLLHSXIC.js → chunk-7CFEGUEH.js} +2 -2
  35. package/dist/cli/chunks/{chunk-OURDPRGM.js → chunk-7L64UC5U.js} +1 -1
  36. package/dist/cli/chunks/{chunk-BPYWDM2Y.js → chunk-7PHNHFZI.js} +3 -3
  37. package/dist/cli/chunks/{chunk-SURZYSSL.js → chunk-A2QLTNN5.js} +1 -1
  38. package/dist/cli/chunks/{chunk-NJ5IC6ZR.js → chunk-A4DJMFDM.js} +1 -1
  39. package/dist/cli/chunks/{chunk-RGJ4RMUR.js → chunk-AVKDT3UL.js} +8 -8
  40. package/dist/cli/chunks/{chunk-AHB2F42G.js → chunk-AYKMWP7F.js} +1 -1
  41. package/dist/cli/chunks/{chunk-BTZEKSWH.js → chunk-BXMIQRF3.js} +2 -2
  42. package/dist/cli/chunks/{chunk-JRHKFRUB.js → chunk-BZB5D4BO.js} +2 -2
  43. package/dist/cli/chunks/{chunk-6OKXGDT3.js → chunk-CG3HIYF4.js} +2 -2
  44. package/dist/cli/chunks/{chunk-PFTR6XAO.js → chunk-DDDEGBBJ.js} +2 -2
  45. package/dist/cli/chunks/{chunk-3KX7CQEM.js → chunk-DLKRK2GU.js} +1 -1
  46. package/dist/cli/chunks/{chunk-UEFAPTBV.js → chunk-E4D36LGH.js} +1 -1
  47. package/dist/cli/chunks/{chunk-ZWAJV4SN.js → chunk-ECYDMBDA.js} +2 -2
  48. package/dist/cli/chunks/{chunk-LPLCT2HH.js → chunk-EKDFIYV5.js} +2 -2
  49. package/dist/cli/chunks/{chunk-LHGZRKPO.js → chunk-ELZ5SKEN.js} +2 -2
  50. package/dist/cli/chunks/{chunk-A5VULTCD.js → chunk-ETXK25IY.js} +1 -1
  51. package/dist/cli/chunks/{chunk-ZLQYGO6N.js → chunk-F5VLJFVU.js} +1 -1
  52. package/dist/cli/chunks/{chunk-UXCEJ3AV.js → chunk-FKODRXOU.js} +2 -2
  53. package/dist/cli/chunks/{chunk-TLTRL32T.js → chunk-GHJRX7PV.js} +1 -1
  54. package/dist/cli/chunks/{chunk-7GPYOMVY.js → chunk-GOPE5OB5.js} +1 -1
  55. package/dist/cli/chunks/{chunk-YIVZ5Z4V.js → chunk-HE2NWYHK.js} +1 -1
  56. package/dist/cli/chunks/{chunk-2SJQ3CYN.js → chunk-HN7HYUW6.js} +9 -9
  57. package/dist/cli/chunks/{chunk-SP3X35XC.js → chunk-HTL2WT64.js} +1 -1
  58. package/dist/cli/chunks/{chunk-STASZVMY.js → chunk-HYACMUUR.js} +2 -2
  59. package/dist/cli/chunks/{chunk-4NHE7AJE.js → chunk-I25KIHQE.js} +1 -1
  60. package/dist/cli/chunks/{chunk-YHZWNT45.js → chunk-I7OH6RAC.js} +2 -2
  61. package/dist/cli/chunks/{chunk-FOCGOVIM.js → chunk-IFIYNCT2.js} +2 -2
  62. package/dist/cli/chunks/{chunk-QKJ4LUAM.js → chunk-IHJXFWUL.js} +2 -2
  63. package/dist/cli/chunks/{chunk-KHEAWN23.js → chunk-IIYXSWJN.js} +2 -2
  64. package/dist/cli/chunks/{chunk-SMKRBNO7.js → chunk-IP2Z4Z6X.js} +1 -1
  65. package/dist/cli/chunks/{chunk-W4HUWBPK.js → chunk-IZTUAI5T.js} +2 -2
  66. package/dist/cli/chunks/{chunk-BJKRAFS2.js → chunk-JBQ4WGB4.js} +2 -2
  67. package/dist/cli/chunks/{chunk-ZV7FGZNJ.js → chunk-JCROLOP6.js} +2 -2
  68. package/dist/cli/chunks/{chunk-KO5HO6MY.js → chunk-JD3GH47Z.js} +2 -2
  69. package/dist/cli/chunks/{chunk-2TRWUJWG.js → chunk-JK6JBNGL.js} +2 -2
  70. package/dist/cli/chunks/{chunk-T7R5NXJW.js → chunk-JNJYWWBG.js} +2 -2
  71. package/dist/cli/chunks/{chunk-EIGXGMOR.js → chunk-JVH7753D.js} +1 -1
  72. package/dist/cli/chunks/{chunk-HE5VY2BI.js → chunk-KJZU3E5G.js} +2 -2
  73. package/dist/cli/chunks/{chunk-JJSJSQNJ.js → chunk-KMGAJRQ6.js} +1 -1
  74. package/dist/cli/chunks/{chunk-ECRYU5XG.js → chunk-LFEBTWFS.js} +2 -2
  75. package/dist/cli/chunks/{chunk-GOG6L2F7.js → chunk-LOANEFGZ.js} +2 -2
  76. package/dist/cli/chunks/{chunk-XD4UFF2Y.js → chunk-LPRHYSXN.js} +1 -1
  77. package/dist/cli/chunks/{chunk-WS4OVAWU.js → chunk-M2JBQVBP.js} +2 -2
  78. package/dist/cli/chunks/{chunk-4B5IYFKE.js → chunk-MGX2BZWE.js} +2 -2
  79. package/dist/cli/chunks/{chunk-GGPGY5QT.js → chunk-MVW7AACO.js} +2 -2
  80. package/dist/cli/chunks/{chunk-HWDE4RB3.js → chunk-N2L7RWNX.js} +2 -2
  81. package/dist/cli/chunks/{chunk-FHBIJBZ3.js → chunk-NCXVOOA7.js} +2 -2
  82. package/dist/cli/chunks/{chunk-XB2GVTY6.js → chunk-NHXFAXEV.js} +1 -1
  83. package/dist/cli/chunks/{chunk-SIIYQLKH.js → chunk-OGFGNAKQ.js} +2 -2
  84. package/dist/cli/chunks/chunk-OT4JADWW.js +2 -0
  85. package/dist/cli/chunks/{chunk-BWNH22V2.js → chunk-OZTSMI7P.js} +1 -1
  86. package/dist/cli/chunks/{chunk-APPVAGD5.js → chunk-P2H5ARHM.js} +1 -1
  87. package/dist/cli/chunks/{chunk-HEENVPYF.js → chunk-P7APAQD6.js} +3 -3
  88. package/dist/cli/chunks/{chunk-5EOM3W6Q.js → chunk-PBPOSPTY.js} +2 -2
  89. package/dist/cli/chunks/{chunk-MR7V7QVL.js → chunk-PG7CZ6Q4.js} +2 -2
  90. package/dist/cli/chunks/{chunk-DKBXIBRS.js → chunk-Q5PARJC6.js} +2 -2
  91. package/dist/cli/chunks/{chunk-YV2PVXJE.js → chunk-QVGSD25D.js} +1 -1
  92. package/dist/cli/chunks/{chunk-ZSXSUUBS.js → chunk-R2LWLZ3Y.js} +1 -1
  93. package/dist/cli/chunks/{chunk-VMWLVRJO.js → chunk-R4VOIXJQ.js} +2 -2
  94. package/dist/cli/chunks/{chunk-PHBE2VBN.js → chunk-RGCCSAHI.js} +2 -2
  95. package/dist/cli/chunks/{chunk-URBXUDY3.js → chunk-S72TSJS4.js} +2 -2
  96. package/dist/cli/chunks/{chunk-WAP7ROO5.js → chunk-SDMGF3KD.js} +2 -2
  97. package/dist/cli/chunks/{chunk-PMZJ54WX.js → chunk-SP3ZBJ63.js} +3 -3
  98. package/dist/cli/chunks/{chunk-HVJXXGB4.js → chunk-SQ6XZGR4.js} +4 -4
  99. package/dist/cli/chunks/{chunk-UDBSEFUT.js → chunk-SSURIMCL.js} +2 -2
  100. package/dist/cli/chunks/{chunk-KHH5UJXY.js → chunk-TDPHLQ2M.js} +2 -2
  101. package/dist/cli/chunks/{chunk-FKJ4XZ6E.js → chunk-TN72MXLI.js} +2 -2
  102. package/dist/cli/chunks/{chunk-AT6LBLUV.js → chunk-TSDTRJOG.js} +2 -2
  103. package/dist/cli/chunks/{chunk-MUEFXLGX.js → chunk-TWDWDKOI.js} +1 -1
  104. package/dist/cli/chunks/{chunk-WV3R5JFE.js → chunk-TZMKO6PC.js} +2 -2
  105. package/dist/cli/chunks/{chunk-XOHRM3M7.js → chunk-U62WL3WZ.js} +3 -3
  106. package/dist/cli/chunks/{chunk-ZEFDSMF4.js → chunk-UAI5NPPQ.js} +2 -2
  107. package/dist/cli/chunks/{chunk-7TKZ6LK6.js → chunk-UGJNR52C.js} +1 -1
  108. package/dist/cli/chunks/{chunk-JNEG6DKU.js → chunk-UOSKMAAY.js} +1 -1
  109. package/dist/cli/chunks/{chunk-SQZ3H6WR.js → chunk-VHZ653XS.js} +3 -3
  110. package/dist/cli/chunks/{chunk-WLYSZV5U.js → chunk-VVNR4R22.js} +2 -2
  111. package/dist/cli/chunks/{chunk-EFHR7LML.js → chunk-W45FANJG.js} +2 -2
  112. package/dist/cli/chunks/{chunk-TT2YXNHH.js → chunk-W4IRWGGR.js} +4 -4
  113. package/dist/cli/chunks/{chunk-DL46KSFX.js → chunk-WJDOOT2M.js} +2 -2
  114. package/dist/cli/chunks/{chunk-LP6EQI2P.js → chunk-WUCWFDBE.js} +2 -2
  115. package/dist/cli/chunks/{chunk-FJEIX3IS.js → chunk-WXEDVKJS.js} +2 -2
  116. package/dist/cli/chunks/{chunk-426OO3RH.js → chunk-X66IXWSO.js} +2 -2
  117. package/dist/cli/chunks/{chunk-D3KORDD5.js → chunk-XPL3BXLM.js} +1 -1
  118. package/dist/cli/chunks/{chunk-JZYCZMHN.js → chunk-XVXSQOQG.js} +2 -2
  119. package/dist/cli/chunks/{chunk-INJPS7RF.js → chunk-Y67OXEUM.js} +1 -1
  120. package/dist/cli/chunks/{chunk-ZETZATNY.js → chunk-YDW522M7.js} +2 -2
  121. package/dist/cli/chunks/{chunk-VAKJOTGU.js → chunk-YIJDCZVX.js} +2 -2
  122. package/dist/cli/chunks/{chunk-LZ34CKYE.js → chunk-YOKRSFGA.js} +2 -2
  123. package/dist/cli/chunks/{chunk-NKX2Z546.js → chunk-YSUMQBMY.js} +1 -1
  124. package/dist/cli/chunks/{chunk-3DXO5CWI.js → chunk-ZCKNGICX.js} +1 -1
  125. package/dist/cli/chunks/{chunk-SQQ57TSJ.js → chunk-ZJ4PMOIZ.js} +2 -2
  126. package/dist/cli/chunks/{ci-F4F3SDHP.js → ci-A5ZXOEC4.js} +2 -2
  127. package/dist/cli/chunks/{ci-output-4SUMOQGO.js → ci-output-S47BMRYC.js} +2 -2
  128. package/dist/cli/chunks/{claude-flow-setup-NKXPDFMJ.js → claude-flow-setup-F5WBEBVK.js} +2 -2
  129. package/dist/cli/chunks/client-56BU3GAX.js +2 -0
  130. package/dist/cli/chunks/{cline-installer-3FMNXEKM.js → cline-installer-HLKR4QDR.js} +2 -2
  131. package/dist/cli/chunks/{code-5QEDZNKI.js → code-MTZWS6JT.js} +2 -2
  132. package/dist/cli/chunks/{code-index-extractor-RD5EAOLE.js → code-index-extractor-BALTZ2WQ.js} +2 -2
  133. package/dist/cli/chunks/{codex-installer-UU4O2FIE.js → codex-installer-LI2VIGET.js} +2 -2
  134. package/dist/cli/chunks/{completions-CS6RJLYZ.js → completions-TOF4GTNF.js} +2 -2
  135. package/dist/cli/chunks/{complexity-analyzer-U4DE2QTP.js → complexity-analyzer-IPFXIT6T.js} +2 -2
  136. package/dist/cli/chunks/{continuedev-installer-E55EG2TB.js → continuedev-installer-KWI66RBI.js} +2 -2
  137. package/dist/cli/chunks/{copilot-installer-TVJUX3AZ.js → copilot-installer-REFOE6UF.js} +2 -2
  138. package/dist/cli/chunks/{cost-tracker-IAKDLDJH.js → cost-tracker-M2MZQXCN.js} +2 -2
  139. package/dist/cli/chunks/{coverage-LX7UIEKV.js → coverage-UR2XSJCR.js} +3 -3
  140. package/dist/cli/chunks/cross-domain-router-XQT52BTB.js +2 -0
  141. package/dist/cli/chunks/{cursor-installer-2NJ7MK23.js → cursor-installer-X4PXCVYH.js} +2 -2
  142. package/dist/cli/chunks/{daemon-T4CPOFHM.js → daemon-5R6ZEEBB.js} +3 -3
  143. package/dist/cli/chunks/{dag-attention-scheduler-GAPYYUHZ.js → dag-attention-scheduler-RUY2RJZA.js} +2 -2
  144. package/dist/cli/chunks/{detect-RU5LBCCI.js → detect-PX2AYBHM.js} +2 -2
  145. package/dist/cli/chunks/{domain-handler-LKPDVPF6.js → domain-handler-5JXWEO3E.js} +2 -2
  146. package/dist/cli/chunks/{domain-transfer-Q76ITWBK.js → domain-transfer-6M2YLBJY.js} +2 -2
  147. package/dist/cli/chunks/dream-LFZCN5WK.js +2 -0
  148. package/dist/cli/chunks/esm-node-EBDIEPKS.js +2 -0
  149. package/dist/cli/chunks/{eval-TFFIZGTW.js → eval-L6ZBG462.js} +2 -2
  150. package/dist/cli/chunks/{fast-paths-V6KA3VWH.js → fast-paths-WIFDALFK.js} +2 -2
  151. package/dist/cli/chunks/{feature-flags-DWS4XL2P.js → feature-flags-GRHF5MTK.js} +2 -2
  152. package/dist/cli/chunks/{feature-flags-MYSY53UU.js → feature-flags-YLBXFUCN.js} +2 -2
  153. package/dist/cli/chunks/{file-discovery-AMKZRFLT.js → file-discovery-4HXUB4HN.js} +2 -2
  154. package/dist/cli/chunks/{fleet-B2BJFKEV.js → fleet-RPLJXOEP.js} +3 -3
  155. package/dist/cli/chunks/{gnn-wrapper-SOJHQ7VC.js → gnn-wrapper-2D5IOGAT.js} +2 -2
  156. package/dist/cli/chunks/{heartbeat-handler-O7FF6NRE.js → heartbeat-handler-D5SWZZGA.js} +4 -4
  157. package/dist/cli/chunks/{heartbeat-scheduler-WOGW5R7J.js → heartbeat-scheduler-WSG4Y3M2.js} +2 -2
  158. package/dist/cli/chunks/hnsw-adapter-BMXTVGZB.js +2 -0
  159. package/dist/cli/chunks/hnsw-index-YX6XLICT.js +2 -0
  160. package/dist/cli/chunks/{hnsw-legacy-bridge-CC5YS47X.js → hnsw-legacy-bridge-UH6RWE74.js} +2 -2
  161. package/dist/cli/chunks/{hnswlib-node-FTWYRETS.js → hnswlib-node-BJ4ZJPMP.js} +2 -2
  162. package/dist/cli/chunks/{hooks-ETOFFBMV.js → hooks-KGDQNB5T.js} +6 -6
  163. package/dist/cli/chunks/{hypergraph-engine-FGAHFWFO.js → hypergraph-engine-LARQCK7V.js} +2 -2
  164. package/dist/cli/chunks/{hypergraph-handler-GNWJD7E3.js → hypergraph-handler-RACF4AOX.js} +3 -3
  165. package/dist/cli/chunks/impact-analyzer-MGSI2WBK.js +2 -0
  166. package/dist/cli/chunks/{init-handler-BEYOLKQO.js → init-handler-64AOFMJD.js} +6 -6
  167. package/dist/cli/chunks/init-wizard-TBDWRRMC.js +2 -0
  168. package/dist/cli/chunks/kernel-NV7TO2FK.js +2 -0
  169. package/dist/cli/chunks/{kilocode-installer-ED6LYSEM.js → kilocode-installer-4ICIP6QN.js} +2 -2
  170. package/dist/cli/chunks/{kiro-installer-NG77T5YR.js → kiro-installer-J2GOV2OB.js} +2 -2
  171. package/dist/cli/chunks/knowledge-graph-7REGYH6A.js +2 -0
  172. package/dist/cli/chunks/{learning-P3WY3LTI.js → learning-QD4JVH3K.js} +3 -3
  173. package/dist/cli/chunks/{llm-router-ETSFMOWS.js → llm-router-4K4IT2PQ.js} +2 -2
  174. package/dist/cli/chunks/{load-PP3GVQT7.js → load-EXKUJMBK.js} +2 -2
  175. package/dist/cli/chunks/load-test-RYQK44TT.js +2 -0
  176. package/dist/cli/chunks/{mcp-B2VX7EKL.js → mcp-NSNDZSMH.js} +2 -2
  177. package/dist/cli/chunks/{memory-SBZQ6MZ4.js → memory-63JTNVZN.js} +5 -5
  178. package/dist/cli/chunks/memory-backend-3EBE2DEX.js +2 -0
  179. package/dist/cli/chunks/{memory-handlers-5RMGG2CR.js → memory-handlers-2335MVQJ.js} +2 -2
  180. package/dist/cli/chunks/{opencode-installer-PIDIFO2L.js → opencode-installer-244LFSPN.js} +2 -2
  181. package/dist/cli/chunks/{orchestrator-FSGUODZI.js → orchestrator-TZB457J6.js} +5 -5
  182. package/dist/cli/chunks/{pipeline-BQ5MWZPT.js → pipeline-YLBD2Z5Q.js} +2 -2
  183. package/dist/cli/chunks/{platform-6EJK4QMD.js → platform-53PWFZSE.js} +2 -2
  184. package/dist/cli/chunks/{plugin-EDGOMUJY.js → plugin-6GUQEFJU.js} +2 -2
  185. package/dist/cli/chunks/{prime-radiant-advanced-wasm-4S6FYKPP.js → prime-radiant-advanced-wasm-VCOK7FV5.js} +2 -2
  186. package/dist/cli/chunks/protocol-executor-MR37S7GX.js +2 -0
  187. package/dist/cli/chunks/{protocol-handler-ETM7PMQU.js → protocol-handler-25UEGTE2.js} +2 -2
  188. package/dist/cli/chunks/{prove-YUBORZAP.js → prove-CTOU5F6G.js} +2 -2
  189. package/dist/cli/chunks/qe-reasoning-bank-DANGLPTH.js +2 -0
  190. package/dist/cli/chunks/{quality-XPZDC5FJ.js → quality-PB7H5UEF.js} +2 -2
  191. package/dist/cli/chunks/queen-coordinator-4YJPYF5F.js +2 -0
  192. package/dist/cli/chunks/{real-embeddings-KTDUTUJL.js → real-embeddings-RWWYCIE5.js} +2 -2
  193. package/dist/cli/chunks/{roocode-installer-WADVKI3P.js → roocode-installer-U4AGYVKL.js} +2 -2
  194. package/dist/cli/chunks/router-F4IPY4RQ.js +2 -0
  195. package/dist/cli/chunks/routing-feedback-VGHFIJ5S.js +2 -0
  196. package/dist/cli/chunks/{routing-handler-OOPOYHEV.js → routing-handler-NTDKDEBE.js} +2 -2
  197. package/dist/cli/chunks/{ruvector-commands-UPEZL4OK.js → ruvector-commands-RQKOLQSW.js} +2 -2
  198. package/dist/cli/chunks/{rvf-dual-writer-TOBBCJ7K.js → rvf-dual-writer-6EZ7S7OG.js} +2 -2
  199. package/dist/cli/chunks/{rvf-migration-adapter-U7UM2U36.js → rvf-migration-adapter-EBTV6FV2.js} +2 -2
  200. package/dist/cli/chunks/{rvf-migration-coordinator-CUX3EU2X.js → rvf-migration-coordinator-MERU7VLY.js} +2 -2
  201. package/dist/cli/chunks/rvf-native-adapter-2P75WF5A.js +2 -0
  202. package/dist/cli/chunks/safe-db-47NEO2RS.js +2 -0
  203. package/dist/cli/chunks/schedule-L5GJW25Z.js +2 -0
  204. package/dist/cli/chunks/scheduler-NGGGSZMO.js +2 -0
  205. package/dist/cli/chunks/{security-AQ4N5YKV.js → security-JPDLGHMC.js} +3 -3
  206. package/dist/cli/chunks/shared-rvf-adapter-NKNTYGHO.js +2 -0
  207. package/dist/cli/chunks/{shared-rvf-dual-writer-OKRIHVSY.js → shared-rvf-dual-writer-7OGLQE5Y.js} +2 -2
  208. package/dist/cli/chunks/sqlite-persistence-TE2ZRHKA.js +2 -0
  209. package/dist/cli/chunks/{status-handler-HSJLJPNG.js → status-handler-3TI3DHEL.js} +2 -2
  210. package/dist/cli/chunks/{structural-health-KWZAS7ON.js → structural-health-WCZKXVWS.js} +2 -2
  211. package/dist/cli/chunks/{sync-6L5Z4IWH.js → sync-AM5T4GYO.js} +2 -2
  212. package/dist/cli/chunks/{task-handler-KEAIPB6G.js → task-handler-VHDTXPVP.js} +2 -2
  213. package/dist/cli/chunks/{task-handlers-BPDN6OSM.js → task-handlers-GEJ36WNB.js} +2 -2
  214. package/dist/cli/chunks/{test-PICO6RLU.js → test-G6P5XGHM.js} +4 -4
  215. package/dist/cli/chunks/{test-scheduling-BI3R3DX5.js → test-scheduling-37RBUN4E.js} +3 -3
  216. package/dist/cli/chunks/{token-bootstrap-KMQC6ALU.js → token-bootstrap-JPE3LWXQ.js} +2 -2
  217. package/dist/cli/chunks/{token-usage-QGDX7MLB.js → token-usage-5XGVBLFR.js} +2 -2
  218. package/dist/cli/chunks/{transformers-UNRYJSIU.js → transformers-JTKWAZJU.js} +2 -2
  219. package/dist/cli/chunks/{tree-sitter-wasm-parser-U22JYPOG.js → tree-sitter-wasm-parser-KW2GWIIQ.js} +2 -2
  220. package/dist/cli/chunks/{types-CYXAGOY5.js → types-7R72BACI.js} +2 -2
  221. package/dist/cli/chunks/unified-memory-KSBLUZT4.js +2 -0
  222. package/dist/cli/chunks/unified-memory-hnsw-V3EOMQIZ.js +2 -0
  223. package/dist/cli/chunks/unified-persistence-URIRJ4BM.js +2 -0
  224. package/dist/cli/chunks/{validate-IUY5BWAV.js → validate-TYB4ZTUL.js} +2 -2
  225. package/dist/cli/chunks/{validate-swarm-FXFKSEOI.js → validate-swarm-3TFI6PLT.js} +2 -2
  226. package/dist/cli/chunks/{vibium-DKZ64NR3.js → vibium-3YELURJT.js} +2 -2
  227. package/dist/cli/chunks/visual-security-DJOOVCBZ.js +2 -0
  228. package/dist/cli/chunks/{web-tree-sitter-WQDTN5CV.js → web-tree-sitter-7Q77A27Y.js} +2 -2
  229. package/dist/cli/chunks/{windsurf-installer-O5WOBFOQ.js → windsurf-installer-ASARRM2X.js} +2 -2
  230. package/dist/cli/chunks/{witness-chain-F7WXEVJA.js → witness-chain-WZ6PNXEY.js} +2 -2
  231. package/dist/cli/chunks/witness-chain-ZWJUCXCJ.js +2 -0
  232. package/dist/cli/chunks/{workflow-47524I5G.js → workflow-JDTEE6TY.js} +4 -4
  233. package/dist/cli/chunks/workflow-orchestrator-5CKA6Q74.js +2 -0
  234. package/dist/cli/chunks/{wrappers-MP2HWQD7.js → wrappers-X7WZLBZD.js} +2 -2
  235. package/dist/mcp/bundle.js +1 -1
  236. package/package.json +1 -1
  237. package/dist/cli/chunks/adapter-GE3RSG32.js +0 -2
  238. package/dist/cli/chunks/aqe-learning-engine-IYL6TK6E.js +0 -2
  239. package/dist/cli/chunks/base-L3G3GEZY.js +0 -2
  240. package/dist/cli/chunks/browser-workflow-7KTCY5FI.js +0 -2
  241. package/dist/cli/chunks/chunk-N5SLJOBK.js +0 -2
  242. package/dist/cli/chunks/client-3DPPDO2H.js +0 -2
  243. package/dist/cli/chunks/cross-domain-router-JOYTUBFT.js +0 -2
  244. package/dist/cli/chunks/dream-IF2HCRW4.js +0 -2
  245. package/dist/cli/chunks/esm-node-LNRP5BNU.js +0 -2
  246. package/dist/cli/chunks/hnsw-adapter-UPX4AXOQ.js +0 -2
  247. package/dist/cli/chunks/hnsw-index-CSI2EXXR.js +0 -2
  248. package/dist/cli/chunks/impact-analyzer-2YVBHMES.js +0 -2
  249. package/dist/cli/chunks/init-wizard-V6GZQMMR.js +0 -2
  250. package/dist/cli/chunks/kernel-EHJ4SP2Y.js +0 -2
  251. package/dist/cli/chunks/knowledge-graph-ZYXBWGKL.js +0 -2
  252. package/dist/cli/chunks/load-test-VDZEYGKV.js +0 -2
  253. package/dist/cli/chunks/memory-backend-IB3BU4VM.js +0 -2
  254. package/dist/cli/chunks/protocol-executor-H2ZG7JBJ.js +0 -2
  255. package/dist/cli/chunks/qe-reasoning-bank-ZCSHSKZU.js +0 -2
  256. package/dist/cli/chunks/queen-coordinator-NEC373VS.js +0 -2
  257. package/dist/cli/chunks/router-3PP5XRTD.js +0 -2
  258. package/dist/cli/chunks/routing-feedback-JNUFV2X3.js +0 -2
  259. package/dist/cli/chunks/rvf-native-adapter-PTOZXG4W.js +0 -2
  260. package/dist/cli/chunks/safe-db-CGYNYUES.js +0 -2
  261. package/dist/cli/chunks/schedule-NRN4WOHX.js +0 -2
  262. package/dist/cli/chunks/scheduler-DRAQGYLL.js +0 -2
  263. package/dist/cli/chunks/shared-rvf-adapter-6UVVDOHK.js +0 -2
  264. package/dist/cli/chunks/sqlite-persistence-3WG7PBPL.js +0 -2
  265. package/dist/cli/chunks/unified-memory-EXRANFUS.js +0 -2
  266. package/dist/cli/chunks/unified-memory-hnsw-GB752D44.js +0 -2
  267. package/dist/cli/chunks/unified-persistence-V2B3YWFD.js +0 -2
  268. package/dist/cli/chunks/visual-security-YMPI7X7V.js +0 -2
  269. package/dist/cli/chunks/witness-chain-7LIPUVMI.js +0 -2
  270. package/dist/cli/chunks/workflow-orchestrator-QPIAR4LI.js +0 -2
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.7");process.exit(0)}
2
- import{c as u}from"./chunk-UEFAPTBV.js";function t(){return{...e}}function o(r){e={...e,...r}}function i(){e={...s}}function a(){return e.useBrowserMode}function E(){return e.useScreenshotCapture}function l(){return e.useVisualRegression}function c(){return e.useE2EExecution}function f(){return e.defaultHeadless}function d(){return e.useAutoRetry}function _(){return e.logPerformanceMetrics}function I(){return e.useAxeCore}function p(){let r={};process.env.VIBIUM_USE_BROWSER_MODE!==void 0&&(r.useBrowserMode=process.env.VIBIUM_USE_BROWSER_MODE==="true"),process.env.VIBIUM_USE_SCREENSHOT_CAPTURE!==void 0&&(r.useScreenshotCapture=process.env.VIBIUM_USE_SCREENSHOT_CAPTURE==="true"),process.env.VIBIUM_USE_VISUAL_REGRESSION!==void 0&&(r.useVisualRegression=process.env.VIBIUM_USE_VISUAL_REGRESSION==="true"),process.env.VIBIUM_USE_E2E_EXECUTION!==void 0&&(r.useE2EExecution=process.env.VIBIUM_USE_E2E_EXECUTION==="true"),process.env.VIBIUM_DEFAULT_HEADLESS!==void 0&&(r.defaultHeadless=process.env.VIBIUM_DEFAULT_HEADLESS==="true"),process.env.VIBIUM_USE_AUTO_RETRY!==void 0&&(r.useAutoRetry=process.env.VIBIUM_USE_AUTO_RETRY==="true"),process.env.VIBIUM_LOG_PERFORMANCE_METRICS!==void 0&&(r.logPerformanceMetrics=process.env.VIBIUM_LOG_PERFORMANCE_METRICS==="true"),process.env.VIBIUM_USE_AXE_CORE!==void 0&&(r.useAxeCore=process.env.VIBIUM_USE_AXE_CORE==="true"),o(r)}function U(){o({defaultHeadless:!0,useAutoRetry:!0,logPerformanceMetrics:!0})}function R(){o({defaultHeadless:!1,logPerformanceMetrics:!0})}function S(){o({useBrowserMode:!1,useScreenshotCapture:!1,useVisualRegression:!1,useE2EExecution:!1,useAxeCore:!1})}var s,e,n=u(()=>{s={useBrowserMode:!0,useScreenshotCapture:!0,useVisualRegression:!0,useE2EExecution:!0,defaultHeadless:!1,useAutoRetry:!0,logPerformanceMetrics:!0,useAxeCore:!0},e={...s}});export{s as a,t as b,o as c,i as d,a as e,E as f,l as g,c as h,f as i,d as j,_ as k,I as l,p as m,U as n,R as o,S as p,n as q};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.8");process.exit(0)}
2
+ import{c as u}from"./chunk-E4D36LGH.js";function t(){return{...e}}function o(r){e={...e,...r}}function i(){e={...s}}function a(){return e.useBrowserMode}function E(){return e.useScreenshotCapture}function l(){return e.useVisualRegression}function c(){return e.useE2EExecution}function f(){return e.defaultHeadless}function d(){return e.useAutoRetry}function _(){return e.logPerformanceMetrics}function I(){return e.useAxeCore}function p(){let r={};process.env.VIBIUM_USE_BROWSER_MODE!==void 0&&(r.useBrowserMode=process.env.VIBIUM_USE_BROWSER_MODE==="true"),process.env.VIBIUM_USE_SCREENSHOT_CAPTURE!==void 0&&(r.useScreenshotCapture=process.env.VIBIUM_USE_SCREENSHOT_CAPTURE==="true"),process.env.VIBIUM_USE_VISUAL_REGRESSION!==void 0&&(r.useVisualRegression=process.env.VIBIUM_USE_VISUAL_REGRESSION==="true"),process.env.VIBIUM_USE_E2E_EXECUTION!==void 0&&(r.useE2EExecution=process.env.VIBIUM_USE_E2E_EXECUTION==="true"),process.env.VIBIUM_DEFAULT_HEADLESS!==void 0&&(r.defaultHeadless=process.env.VIBIUM_DEFAULT_HEADLESS==="true"),process.env.VIBIUM_USE_AUTO_RETRY!==void 0&&(r.useAutoRetry=process.env.VIBIUM_USE_AUTO_RETRY==="true"),process.env.VIBIUM_LOG_PERFORMANCE_METRICS!==void 0&&(r.logPerformanceMetrics=process.env.VIBIUM_LOG_PERFORMANCE_METRICS==="true"),process.env.VIBIUM_USE_AXE_CORE!==void 0&&(r.useAxeCore=process.env.VIBIUM_USE_AXE_CORE==="true"),o(r)}function U(){o({defaultHeadless:!0,useAutoRetry:!0,logPerformanceMetrics:!0})}function R(){o({defaultHeadless:!1,logPerformanceMetrics:!0})}function S(){o({useBrowserMode:!1,useScreenshotCapture:!1,useVisualRegression:!1,useE2EExecution:!1,useAxeCore:!1})}var s,e,n=u(()=>{s={useBrowserMode:!0,useScreenshotCapture:!0,useVisualRegression:!0,useE2EExecution:!0,defaultHeadless:!1,useAutoRetry:!0,logPerformanceMetrics:!0,useAxeCore:!0},e={...s}});export{s as a,t as b,o as c,i as d,a as e,E as f,l as g,c as h,f as i,d as j,_ as k,I as l,p as m,U as n,R as o,S as p,n as q};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.7");process.exit(0)}
2
- import{a as G}from"./chunk-D3KORDD5.js";import{a as q,e as C,f as z}from"./chunk-ZV7FGZNJ.js";import{a as I}from"./chunk-NJ5IC6ZR.js";import{a as H,b as _,c as U,d as j}from"./chunk-3DXO5CWI.js";import{a as A,b as W,f as N,i as O}from"./chunk-7TKZ6LK6.js";import{d as B}from"./chunk-GOG6L2F7.js";import{b as v,d as L,f as M,g as P}from"./chunk-426OO3RH.js";import{a as K}from"./chunk-N5SLJOBK.js";import{c as D}from"./chunk-6OKXGDT3.js";import{b as w,d as Y}from"./chunk-WLYSZV5U.js";import{b as f,c as h}from"./chunk-ZSXSUUBS.js";import{a as Q,b,c as J}from"./chunk-MR7V7QVL.js";import{f as T}from"./chunk-SMKRBNO7.js";K();J();Y();var o=D.create("RealQEReasoningBank"),V={sqlite:{dbPath:".agentic-qe/memory.db",walMode:!0,useUnified:!0},embeddings:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0},enableLearning:!0,enableRouting:!0,enableGuidance:!0,hnsw:{M:16,efConstruction:200,efSearch:100},routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4},R=class{constructor(e={},t){this.coherenceService=t;this.qeConfig={...V,...e},this.sqliteStore=B(this.qeConfig.sqlite),this.asymmetricEngine=new G}qeConfig;sqliteStore;hnswIndex=null;patternIdMap=new Map;initialized=!1;stats={routingRequests:0,totalRoutingLatency:0,learningOutcomes:0,successfulOutcomes:0};routingLatencies=new I(1e3);asymmetricEngine;agentCapabilities={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}};async initialize(){if(this.initialized)return;let e=performance.now();await this.sqliteStore.initialize(),o.info("SQLite persistence initialized"),await this.initializeHNSW(),o.info("HNSW index initialized"),await this.loadPatternsIntoHNSW(),this.sqliteStore.getStats().totalPatterns===0&&(this.sqliteStore.hasAnyHistoricalData?.()??!1?o.error("qe_patterns table is EMPTY but historical data exists \u2014 possible data loss! Restore from backup instead of loading seed patterns. Skipping foundational pattern load to avoid masking data loss."):await this.loadFoundationalPatterns()),this.initialized=!0;let i=performance.now()-e;o.info("Fully initialized",{durationMs:Math.round(i)})}async initializeHNSW(){try{let e=await import("./hnswlib-node-FTWYRETS.js"),i=e.default?.HierarchicalNSW||e.HierarchicalNSW;if(typeof i!="function")throw new Error("HierarchicalNSW not found in hnswlib-node module");let n=i,a=P();this.hnswIndex=new n("cosine",a),this.hnswIndex.initIndex(1e5,this.qeConfig.hnsw.M,this.qeConfig.hnsw.efConstruction),this.hnswIndex.setEf(this.qeConfig.hnsw.efSearch),o.info("HNSW initialized",{dimension:a,M:this.qeConfig.hnsw.M})}catch(e){throw o.error("HNSW initialization failed",e instanceof Error?e:void 0),e}}async loadPatternsIntoHNSW(){if(!this.hnswIndex)return;let e=this.sqliteStore.getAllEmbeddings(),t=P(),i=0,n=0;for(let{patternId:a,embedding:s}of e){if(!s||!Array.isArray(s)||s.length!==t){n++;continue}let r=this.hnswIndex.getCurrentCount();this.hnswIndex.addPoint(s,r),this.patternIdMap.set(r,a),i++}n>0&&o.warn("Skipped invalid embeddings",{skipped:n,expectedDim:t}),o.info("Loaded patterns into HNSW index",{count:i})}async loadFoundationalPatterns(){let e=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.8");process.exit(0)}
2
+ import{a as G}from"./chunk-XPL3BXLM.js";import{a as q,e as C,f as z}from"./chunk-JCROLOP6.js";import{a as I}from"./chunk-A4DJMFDM.js";import{a as H,b as _,c as U,d as j}from"./chunk-ZCKNGICX.js";import{a as A,b as W,f as N,i as O}from"./chunk-UGJNR52C.js";import{d as B}from"./chunk-LOANEFGZ.js";import{b as v,d as L,f as M,g as P}from"./chunk-X66IXWSO.js";import{a as K}from"./chunk-OT4JADWW.js";import{c as D}from"./chunk-CG3HIYF4.js";import{b as w,d as Y}from"./chunk-VVNR4R22.js";import{b as f,c as h}from"./chunk-R2LWLZ3Y.js";import{a as Q,b,c as J}from"./chunk-PG7CZ6Q4.js";import{f as T}from"./chunk-IP2Z4Z6X.js";K();J();Y();var o=D.create("RealQEReasoningBank"),V={sqlite:{dbPath:".agentic-qe/memory.db",walMode:!0,useUnified:!0},embeddings:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0},enableLearning:!0,enableRouting:!0,enableGuidance:!0,hnsw:{M:16,efConstruction:200,efSearch:100},routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4},R=class{constructor(e={},t){this.coherenceService=t;this.qeConfig={...V,...e},this.sqliteStore=B(this.qeConfig.sqlite),this.asymmetricEngine=new G}qeConfig;sqliteStore;hnswIndex=null;patternIdMap=new Map;initialized=!1;stats={routingRequests:0,totalRoutingLatency:0,learningOutcomes:0,successfulOutcomes:0};routingLatencies=new I(1e3);asymmetricEngine;agentCapabilities={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}};async initialize(){if(this.initialized)return;let e=performance.now();await this.sqliteStore.initialize(),o.info("SQLite persistence initialized"),await this.initializeHNSW(),o.info("HNSW index initialized"),await this.loadPatternsIntoHNSW(),this.sqliteStore.getStats().totalPatterns===0&&(this.sqliteStore.hasAnyHistoricalData?.()??!1?o.error("qe_patterns table is EMPTY but historical data exists \u2014 possible data loss! Restore from backup instead of loading seed patterns. Skipping foundational pattern load to avoid masking data loss."):await this.loadFoundationalPatterns()),this.initialized=!0;let i=performance.now()-e;o.info("Fully initialized",{durationMs:Math.round(i)})}async initializeHNSW(){try{let e=await import("./hnswlib-node-BJ4ZJPMP.js"),i=e.default?.HierarchicalNSW||e.HierarchicalNSW;if(typeof i!="function")throw new Error("HierarchicalNSW not found in hnswlib-node module");let n=i,a=P();this.hnswIndex=new n("cosine",a),this.hnswIndex.initIndex(1e5,this.qeConfig.hnsw.M,this.qeConfig.hnsw.efConstruction),this.hnswIndex.setEf(this.qeConfig.hnsw.efSearch),o.info("HNSW initialized",{dimension:a,M:this.qeConfig.hnsw.M})}catch(e){throw o.error("HNSW initialization failed",e instanceof Error?e:void 0),e}}async loadPatternsIntoHNSW(){if(!this.hnswIndex)return;let e=this.sqliteStore.getAllEmbeddings(),t=P(),i=0,n=0;for(let{patternId:a,embedding:s}of e){if(!s||!Array.isArray(s)||s.length!==t){n++;continue}let r=this.hnswIndex.getCurrentCount();this.hnswIndex.addPoint(s,r),this.patternIdMap.set(r,a),i++}n>0&&o.warn("Skipped invalid embeddings",{skipped:n,expectedDim:t}),o.info("Loaded patterns into HNSW index",{count:i})}async loadFoundationalPatterns(){let e=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
3
3
  describe('{{methodName}}', () => {
4
4
  it('should {{expectedBehavior}}', {{async}} () => {
5
5
  // Arrange
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.7");process.exit(0)}
2
- import{h as s,k as o,m as c,o as m}from"./chunk-JRHKFRUB.js";import{a,c as d}from"./chunk-MR7V7QVL.js";import{a as r,e as l}from"./chunk-YR5ZNQT2.js";d();m();l();var u={dbPath:s.dbPath,walMode:!0,mmapSize:r.MMAP_SIZE_BYTES,cacheSize:r.CACHE_SIZE_KB,busyTimeout:r.BUSY_TIMEOUT_MS},n=class e{static instance=null;static instancePromise=null;unifiedMemory=null;config;initialized=!1;initPromise=null;constructor(i){this.config={...u,...i}}static getInstance(i){return e.instance||(e.instance=new e(i)),e.instance}static async getInstanceAsync(i){return e.instance?.initialized?e.instance:(e.instancePromise||(e.instancePromise=(async()=>{let t=e.getInstance(i);return await t.initialize(),t})()),e.instancePromise)}static resetInstance(){e.instance&&(e.instance.close(),e.instance=null),e.instancePromise=null,c()}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{let i={dbPath:this.config.dbPath,walMode:this.config.walMode,busyTimeout:this.config.busyTimeout,mmapSize:this.config.mmapSize,cacheSize:this.config.cacheSize};this.unifiedMemory=o(i),await this.unifiedMemory.initialize(),this.initialized=!0,console.log(`[UnifiedPersistence] Initialized via UnifiedMemoryManager: ${this.config.dbPath}`)}catch(i){throw this.initPromise=null,new Error(`Failed to initialize UnifiedPersistenceManager: ${a(i)}`)}}getDatabase(){if(!this.unifiedMemory||!this.initialized)throw new Error("UnifiedPersistenceManager not initialized");return this.unifiedMemory.getDatabase()}isInitialized(){return this.initialized}getDbPath(){return this.config.dbPath}prepare(i,t){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.prepare(i,t)}transaction(i){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.transaction(i)}getStats(){if(!this.unifiedMemory)throw new Error("Database not initialized");let i=this.unifiedMemory.getStats();return{tables:i.tables,fileSize:i.fileSize,walSize:i.walSize}}vacuum(){this.getDatabase().exec("VACUUM")}checkpoint(){this.getDatabase().pragma("wal_checkpoint(TRUNCATE)")}close(){this.initialized=!1,console.log("[UnifiedPersistence] Facade closed")}};function g(e){return n.getInstance(e)}async function U(e){let i=g(e);return await i.initialize(),i}function z(){n.resetInstance()}var f=!1;function h(){if(f)return;f=!0;let e=()=>{try{let i=n.instance;i&&i.close()}catch(i){console.debug("[UnifiedPersistence] Cleanup error:",i instanceof Error?i.message:i)}};process.on("beforeExit",e),process.on("SIGINT",()=>{e(),process.exit(0)}),process.on("SIGTERM",()=>{e(),process.exit(0)})}h();export{u as a,n as b,g as c,U as d,z as e};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.8");process.exit(0)}
2
+ import{h as s,k as o,m as c,o as m}from"./chunk-BZB5D4BO.js";import{a,c as d}from"./chunk-PG7CZ6Q4.js";import{a as r,e as l}from"./chunk-6DBYVKGA.js";d();m();l();var u={dbPath:s.dbPath,walMode:!0,mmapSize:r.MMAP_SIZE_BYTES,cacheSize:r.CACHE_SIZE_KB,busyTimeout:r.BUSY_TIMEOUT_MS},n=class e{static instance=null;static instancePromise=null;unifiedMemory=null;config;initialized=!1;initPromise=null;constructor(i){this.config={...u,...i}}static getInstance(i){return e.instance||(e.instance=new e(i)),e.instance}static async getInstanceAsync(i){return e.instance?.initialized?e.instance:(e.instancePromise||(e.instancePromise=(async()=>{let t=e.getInstance(i);return await t.initialize(),t})()),e.instancePromise)}static resetInstance(){e.instance&&(e.instance.close(),e.instance=null),e.instancePromise=null,c()}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{let i={dbPath:this.config.dbPath,walMode:this.config.walMode,busyTimeout:this.config.busyTimeout,mmapSize:this.config.mmapSize,cacheSize:this.config.cacheSize};this.unifiedMemory=o(i),await this.unifiedMemory.initialize(),this.initialized=!0,console.log(`[UnifiedPersistence] Initialized via UnifiedMemoryManager: ${this.config.dbPath}`)}catch(i){throw this.initPromise=null,new Error(`Failed to initialize UnifiedPersistenceManager: ${a(i)}`)}}getDatabase(){if(!this.unifiedMemory||!this.initialized)throw new Error("UnifiedPersistenceManager not initialized");return this.unifiedMemory.getDatabase()}isInitialized(){return this.initialized}getDbPath(){return this.config.dbPath}prepare(i,t){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.prepare(i,t)}transaction(i){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.transaction(i)}getStats(){if(!this.unifiedMemory)throw new Error("Database not initialized");let i=this.unifiedMemory.getStats();return{tables:i.tables,fileSize:i.fileSize,walSize:i.walSize}}vacuum(){this.getDatabase().exec("VACUUM")}checkpoint(){this.getDatabase().pragma("wal_checkpoint(TRUNCATE)")}close(){this.initialized=!1,console.log("[UnifiedPersistence] Facade closed")}};function g(e){return n.getInstance(e)}async function U(e){let i=g(e);return await i.initialize(),i}function z(){n.resetInstance()}var f=!1;function h(){if(f)return;f=!0;let e=()=>{try{let i=n.instance;i&&i.close()}catch(i){console.debug("[UnifiedPersistence] Cleanup error:",i instanceof Error?i.message:i)}};process.on("beforeExit",e),process.on("SIGINT",()=>{e(),process.exit(0)}),process.on("SIGTERM",()=>{e(),process.exit(0)})}h();export{u as a,n as b,g as c,U as d,z as e};
@@ -1,6 +1,6 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.7");process.exit(0)}
2
- import{a as F}from"./chunk-EL2WLSUI.js";import{a as b,b as E,c as z,d as M,e as C,f as P,g as B}from"./chunk-JNEG6DKU.js";function W(s,e){let n=s.slice(0,e).split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.8");process.exit(0)}
2
+ import{a as F}from"./chunk-6KWX7A3R.js";import{a as b,b as E,c as z,d as M,e as C,f as P,g as B}from"./chunk-UOSKMAAY.js";function W(s,e){let n=s.slice(0,e).split(`
3
3
  `),r=n.length,o=(n[n.length-1]||"").length;return{line:r,column:o,offset:e}}function p(s,e,n,r,o){return{start:W(s,e),end:W(s,n),oldText:s.slice(e,n),newText:r,description:o}}function _(s,e){let n=[...e].sort((o,t)=>t.start.offset-o.start.offset),r=s;for(let o of n)r=r.slice(0,o.start.offset)+o.newText+r.slice(o.end.offset);return r}function U(s,e){if(s.length===0)return 1;let n=s.reduce((t,a)=>t+Math.abs(a.newText.length-a.oldText.length),0)/s.length,r=Math.max(.5,1-n/1e3),o=Math.max(.7,1-s.length/100);return Math.min(1,e*r*o)}function T(s,e,n,r,o=.9){let t=_(s,n),a=Date.now()-r;return{success:!0,transformType:e,originalCode:s,transformedCode:t,edits:n,changeCount:n.length,confidence:U(n,o),durationMs:a,implementationUsed:"typescript",usedFallback:!1,warnings:[]}}function w(s,e,n,r){return{success:!1,transformType:e,originalCode:s,transformedCode:s,edits:[],changeCount:0,confidence:0,durationMs:Date.now()-r,implementationUsed:"typescript",usedFallback:!1,error:n,warnings:[]}}function Z(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/\bvar\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,a=/([a-zA-Z_$][a-zA-Z0-9_$]*)\s*(?:\+\+|--|[+\-*/%&|^]=|\?\?=|&&=|\|\|=|=(?!=))/g,i=[],l;for(;(l=t.exec(s))!==null;)i.push({name:l[1],offset:l.index});let m=new Set;for(;(l=a.exec(s))!==null;)m.add(l[1]);let u=/\bfor\s*\(\s*var\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,c=new Set;for(;(l=u.exec(s))!==null;)c.add(l[1]);for(let g of i){let d=c.has(g.name)||m.has(g.name)?"let":"const";r.push(p(s,g.offset,g.offset+3,d,`Convert var ${g.name} to ${d}`))}e.debug("var-to-const transform completed",{declarations:i.length,reassigned:m.size,loopVars:c.size});let f=T(s,"var-to-const",r,n,.95);return f.warnings=o,f}catch(t){return e.error("var-to-const transform failed",t),w(s,"var-to-const",t instanceof Error?t.message:"Unknown error",n)}}function O(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(([^)]*)\)/g,a=/(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*\(([^)]*)\)\s*=>/g,i=/([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(([^)]*)\)\s*(?::\s*[^{]+)?\s*\{/g,l;for(;(l=t.exec(s))!==null;){let u=l[2].trim();if(u&&!u.includes(":")){let c=u.split(",").map(d=>{let h=d.trim().replace(/\s*=.*$/,"");return h&&!h.includes(":")?`${h}: unknown`:d.trim()}).join(", "),f=l.index+l[0].indexOf("(")+1,g=f+l[2].length;r.push(p(s,f,g,c,`Add types to function ${l[1]} parameters`))}}for(;(l=a.exec(s))!==null;){let u=l[2].trim();if(u&&!u.includes(":")){let c=u.split(",").map(d=>{let h=d.trim().replace(/\s*=.*$/,"");return h&&!h.includes(":")?`${h}: unknown`:d.trim()}).join(", "),f=l.index+l[0].indexOf("(")+1,g=f+l[2].length;r.push(p(s,f,g,c,`Add types to arrow function ${l[1]} parameters`))}}e.debug("add-types transform completed",{edits:r.length});let m=T(s,"add-types",r,n,.7);return m.warnings=o,r.length>0&&m.warnings.push('Type annotations use "unknown" - manual review recommended'),m}catch(t){return e.error("add-types transform failed",t),w(s,"add-types",t instanceof Error?t.message:"Unknown error",n)}}function I(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/^\s*console\.(log|warn|error|info|debug|trace|dir|table|time|timeEnd|group|groupEnd|assert)\s*\([^)]*\);?\s*$/gm,a=/console\.(log|warn|error|info|debug|trace|dir|table|time|timeEnd|group|groupEnd|assert)\s*\([^)]*\)/g,i,l=new Set;for(;(i=t.exec(s))!==null;)l.has(i.index)||(l.add(i.index),r.push(p(s,i.index,i.index+i[0].length,"",`Remove console.${i[1]}() statement`)));for(;(i=a.exec(s))!==null;){if(l.has(i.index))continue;let u=s.lastIndexOf(`
4
4
  `,i.index)+1,c=s.indexOf(`
5
5
  `,i.index),f=s.slice(u,c===-1?void 0:c);/^\s*console\./.test(f)||(l.add(i.index),o.push(`Inline console.${i[1]}() at offset ${i.index} - consider manual review`))}e.debug("remove-console transform completed",{removed:r.length,warnings:o.length});let m=T(s,"remove-console",r,n,.95);return m.warnings=o,m}catch(t){return e.error("remove-console transform failed",t),w(s,"remove-console",t instanceof Error?t.message:"Unknown error",n)}}function j(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/([a-zA-Z_$][a-zA-Z0-9_$]*(?:\([^)]*\))?)\s*\.then\s*\(\s*(?:async\s*)?\(?\s*([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\)?\s*=>\s*([^)]+)\)/g,a;for(;(a=t.exec(s))!==null;){let[l,m,u,c]=a;if(c.includes(".then")||c.includes(".catch")){o.push(`Complex promise chain at offset ${a.index} - manual review recommended`);continue}let f=`const ${u} = await ${m};
6
- ${c.trim()}`;r.push(p(s,a.index,a.index+l.length,f,"Convert .then() to await"))}e.debug("promise-to-async transform completed",{converted:r.length,warnings:o.length});let i=T(s,"promise-to-async",r,n,.65);return i.warnings=o,r.length>0&&i.warnings.push("Promise chains converted to await - ensure containing function is async"),i}catch(t){return e.error("promise-to-async transform failed",t),w(s,"promise-to-async",t instanceof Error?t.message:"Unknown error",n)}}function N(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t,a=/(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*require\s*\(\s*(['"`][^'"`]+['"`])\s*\)\s*;?/g;for(;(t=a.exec(s))!==null;){let[c,f,g]=t,d=`import ${f} from ${g};`;r.push(p(s,t.index,t.index+c.length,d,"Convert require to import"))}let i=/(?:const|let|var)\s+\{\s*([^}]+)\s*\}\s*=\s*require\s*\(\s*(['"`][^'"`]+['"`])\s*\)\s*;?/g;for(;(t=i.exec(s))!==null;){let[c,f,g]=t,d=`import { ${f.trim()} } from ${g};`;r.push(p(s,t.index,t.index+c.length,d,"Convert destructured require to import"))}let l=/module\.exports\s*=\s*([^;]+);?/g;for(;(t=l.exec(s))!==null;){let[c,f]=t,g=`export default ${f.trim()};`;r.push(p(s,t.index,t.index+c.length,g,"Convert module.exports to export default"))}let m=/exports\.([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*([^;]+);?/g;for(;(t=m.exec(s))!==null;){let[c,f,g]=t,d=g.trim(),h;d.startsWith("function")||d.startsWith("class")?h=`export ${d}`:d.startsWith("async function")?h=`export ${d}`:h=`export const ${f} = ${d};`,r.push(p(s,t.index,t.index+c.length,h,`Convert exports.${f} to named export`))}e.debug("cjs-to-esm transform completed",{edits:r.length});let u=T(s,"cjs-to-esm",r,n,.85);return u.warnings=o,u}catch(t){return e.error("cjs-to-esm transform failed",t),w(s,"cjs-to-esm",t instanceof Error?t.message:"Unknown error",n)}}function H(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/(const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*function\s*\(([^)]*)\)\s*\{/g,a;for(;(a=t.exec(s))!==null;){let[m,u,c,f]=a,g=a.index,d=1,h=g+m.length;for(;d>0&&h<s.length;)s[h]==="{"&&d++,s[h]==="}"&&d--,h++;let S=s.slice(g,h);if(/\bthis\b/.test(S)){o.push(`Function ${c} uses 'this' - skipping arrow conversion (would change binding)`);continue}if(/\barguments\b/.test(S)){o.push(`Function ${c} uses 'arguments' - skipping arrow conversion (not available in arrow functions)`);continue}let D=`${u} ${c} = (${f}) => {`;r.push(p(s,a.index,a.index+m.length,D,`Convert function ${c} to arrow function`))}let i=/function\s*\(([^)]*)\)\s*\{\s*return\s+([^;]+);\s*\}/g;for(;(a=i.exec(s))!==null;){let[m,u,c]=a;if(/\b(this|arguments)\b/.test(m))continue;let f=u.includes(",")||u.trim()===""?`(${u}) => ${c}`:`${u.trim()} => ${c}`;r.push(p(s,a.index,a.index+m.length,f,"Convert callback to arrow function"))}e.debug("func-to-arrow transform completed",{converted:r.length,warnings:o.length});let l=T(s,"func-to-arrow",r,n,.85);return l.warnings=o,l}catch(t){return e.error("func-to-arrow transform failed",t),w(s,"func-to-arrow",t instanceof Error?t.message:"Unknown error",n)}}var V={"var-to-const":Z,"add-types":O,"remove-console":I,"promise-to-async":j,"cjs-to-esm":N,"func-to-arrow":H};function $(s,e,n){let r=V[e];return r?r(s,n):{success:!1,transformType:e,originalCode:s,transformedCode:s,edits:[],changeCount:0,confidence:0,durationMs:0,implementationUsed:"typescript",usedFallback:!1,error:`Unknown transform type: ${e}`,warnings:[]}}var q={JavaScript:0,TypeScript:1,Python:2,Rust:3,Go:4,Java:5,C:6,Cpp:7},y=null,A=null,x=null,R=!1,k=null;async function G(){if(R)return k===null;if(k)return!1;try{let s=await import("./agent-booster-wasm-MXTWTD4D.js");return y=s.transform,A=s.warmup,x=s.isWasmAvailable,R=!0,!0}catch(s){return k=s,R=!0,!1}}function K(s){return q.TypeScript}var L=class{cache=new Map;ttlMs;enabled;constructor(e,n){this.enabled=e,this.ttlMs=n}generateKey(e,n){let r=0;for(let o=0;o<e.length;o++){let t=e.charCodeAt(o);r=(r<<5)-r+t,r=r&r}return`${n}:${r}:${e.length}`}get(e,n){if(!this.enabled)return null;let r=this.generateKey(e,n),o=this.cache.get(r);return o?Date.now()>o.expiresAt?(this.cache.delete(r),null):o.result:null}set(e,n,r){if(!this.enabled)return;let o=this.generateKey(e,n);this.cache.set(o,{result:r,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},v=class{config;logger;cache;enabledTransforms;metricsTracker;initialized=!1;wasmAvailable=!1;wasmModule=null;patternsLoaded=!1;totalTransforms=0;successfulTransforms=0;totalDurationMs=0;cacheHits=0;cacheMisses=0;constructor(e={},n,r){this.config={...z,...e},this.logger=n||{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.metricsTracker=r,this.cache=new L(this.config.cacheEnabled,this.config.cacheTtlMs),this.config.transforms.length===0?this.enabledTransforms=new Set(b):this.enabledTransforms=new Set(this.config.transforms)}setMetricsTracker(e){this.metricsTracker=e}async initialize(){this.initialized||(this.logger.info("Initializing Agent Booster adapter",{enabled:this.config.enabled,transforms:Array.from(this.enabledTransforms)}),this.config.transforms.length===0&&await this.loadEligibleTransformsFromPatterns(),this.config.enabled&&await this.tryLoadWasm(),this.initialized=!0,this.logger.info("Agent Booster adapter initialized",{wasmAvailable:this.wasmAvailable,enabledTransforms:Array.from(this.enabledTransforms),patternsLoaded:this.patternsLoaded}))}async loadEligibleTransformsFromPatterns(){try{let n=await F().getEligibleBoosterTransforms();if(n.length>0){let r=n.filter(o=>b.includes(o));if(r.length>0){this.enabledTransforms=new Set(r),this.patternsLoaded=!0,this.logger.info("Loaded eligible transforms from PatternLoader",{fromPatterns:r,invalidIgnored:n.length-r.length});return}}this.logger.debug("PatternLoader returned empty transforms, using defaults")}catch(e){this.logger.warn("Failed to load transforms from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.enabledTransforms=new Set(b),this.patternsLoaded=!1}async tryLoadWasm(){try{if(this.logger.debug("Loading WASM module"),!await G()||!x){this.logger.debug("WASM module could not be loaded, using TypeScript fallback"),this.wasmAvailable=!1;return}this.logger.debug("Checking WASM availability from local module"),await x()&&y&&A?(this.logger.debug("Warming up WASM module"),await A(),this.wasmModule={transform:y,warmup:A,isAvailable:x},this.wasmAvailable=!0,this.logger.info("WASM Agent Booster loaded and warmed up successfully",{source:"local-module"})):(this.logger.debug("WASM not available from local module, using TypeScript fallback"),this.wasmAvailable=!1)}catch(e){this.logger.warn("Failed to load WASM module",{error:e instanceof Error?e.message:"Unknown error"}),this.wasmAvailable=!1}}async dispose(){this.cache.clear(),this.wasmModule=null,this.wasmAvailable=!1,this.initialized=!1,this.logger.info("Agent Booster adapter disposed")}async transform(e,n){this.ensureInitialized(),this.ensureEnabled();let r=Date.now();if(this.totalTransforms++,!this.enabledTransforms.has(n))return this.createErrorResult(e,n,`Transform type '${n}' is not enabled`,r);let o=this.cache.get(e,n);if(o)return this.cacheHits++,this.logger.debug("Cache hit for transform",{type:n}),{...o,durationMs:Date.now()-r};this.cacheMisses++;let t;try{t=await this.executeWithFallback(e,n,r)}catch(a){return this.createErrorResult(e,n,a instanceof Error?a.message:"Unknown error",r)}return t.success&&(this.successfulTransforms++,this.cache.set(e,n,t)),this.totalDurationMs+=t.durationMs,await this.recordMetrics(t,n),t}async recordMetrics(e,n){if(this.metricsTracker)try{let r=`booster-${n}-${Date.now()}`;await this.metricsTracker.recordOutcome("booster",r,e.success,e.durationMs,{subType:n,confidence:e.confidence,usedFallback:e.usedFallback,implementationUsed:e.implementationUsed,itemCount:e.changeCount,errorMessage:e.error})}catch(r){this.logger.warn("Failed to record metrics",{error:r instanceof Error?r.message:"Unknown error"})}}async executeWithFallback(e,n,r){if(this.wasmAvailable)try{let t=await this.executeWasmTransform(e,n,r);if(t.success&&t.confidence>=this.config.confidenceThreshold)return t;this.logger.debug("WASM transform low confidence, trying TypeScript",{confidence:t.confidence,threshold:this.config.confidenceThreshold})}catch(t){this.logger.warn("WASM transform failed, falling back to TypeScript",{error:t instanceof Error?t.message:"Unknown error"})}let o=$(e,n,this.logger);return o.durationMs=Date.now()-r,this.config.fallbackToLLM&&o.confidence<this.config.confidenceThreshold&&(this.logger.debug("TypeScript transform low confidence, LLM fallback available",{confidence:o.confidence,threshold:this.config.confidenceThreshold}),o.warnings.push(`Confidence ${o.confidence.toFixed(2)} is below threshold ${this.config.confidenceThreshold}. LLM fallback recommended for review.`),o.usedFallback=!0),o}async executeWasmTransform(e,n,r){if(!this.wasmAvailable)throw new C;let o=K(n),t=$(e,n,this.logger);if(t.changeCount===0)return{...t,durationMs:Date.now()-r,implementationUsed:"wasm"};if(!y)throw new C("WASM transform function not loaded");let a=await Promise.race([y(e,t.transformedCode,o,{confidenceThreshold:this.config.confidenceThreshold,allowFallback:!0}),new Promise((m,u)=>setTimeout(()=>u(new P("WASM transform timed out",n,this.config.timeoutMs)),this.config.timeoutMs))]),i=Date.now()-r,l=a.success&&a.mergedCode!==e?t.changeCount:0;return{success:a.success,transformType:n,originalCode:e,transformedCode:a.mergedCode,edits:t.edits,changeCount:l,confidence:a.confidence,durationMs:i,implementationUsed:a.source==="wasm"?"wasm":"typescript",usedFallback:a.source!=="wasm",error:a.error,warnings:a.syntaxValid?[]:["WASM reported syntax may be invalid"]}}async batchTransform(e,n){this.ensureInitialized(),this.ensureEnabled();let r=Date.now(),o=[],t=[],a=0,i=0,l=0,m=0;for(let u of e){if(u.content.length>this.config.maxFileSizeBytes){let c=new B(u.path,u.content.length,this.config.maxFileSizeBytes);t.push({path:u.path,error:c.message}),i++;continue}try{let c=await this.transform(u.content,n);o.push({path:u.path,result:c}),c.success?c.changeCount>0?(a++,m+=c.changeCount):l++:(i++,c.error&&t.push({path:u.path,error:c.error}))}catch(c){i++,t.push({path:u.path,error:c instanceof Error?c.message:"Unknown error"})}}return{success:i===0,transformType:n,files:o,totalFiles:e.length,successCount:a,failureCount:i,noChangeCount:l,totalChanges:m,durationMs:Date.now()-r,errors:t}}async detectTransformOpportunities(e){this.ensureInitialized(),this.ensureEnabled();let n=Date.now(),r=[],o={},t=[];for(let a of b)o[a]=0;for(let a of Array.from(this.enabledTransforms))try{let i=await this.transform(e,a);if(i.changeCount>0)for(let l of i.edits){let m={type:a,confidence:i.confidence,location:l.start,codeSnippet:l.oldText.slice(0,100)+(l.oldText.length>100?"...":""),suggestedCode:l.newText.slice(0,100)+(l.newText.length>100?"...":""),reason:l.description,risk:this.confidenceToRisk(i.confidence),estimatedDurationMs:E[a].typicalLatencyMs};r.push(m),o[a]++}}catch(i){t.push(`Failed to analyze for ${a}: ${i instanceof Error?i.message:"Unknown error"}`)}return r.sort((a,i)=>i.confidence-a.confidence),{opportunities:r,totalCount:r.length,byType:o,durationMs:Date.now()-n,complete:t.length===0,warnings:t}}isTransformAvailable(e){return this.enabledTransforms.has(e)}getTransformMetadata(e){return E[e]}getAvailableTransforms(){return Array.from(this.enabledTransforms)}isWasmAvailable(){return this.wasmAvailable}getHealth(){let e=this.totalTransforms>0?this.totalDurationMs/this.totalTransforms:0,n=this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0,r=[];return this.initialized||r.push("Adapter not initialized"),this.config.enabled||r.push("Adapter is disabled"),this.wasmAvailable||r.push("WASM module not loaded (using TypeScript fallback)"),this.patternsLoaded||r.push("Patterns not loaded from PatternLoader (using defaults)"),{ready:this.initialized&&this.config.enabled,wasmAvailable:this.wasmAvailable,patternsLoaded:this.patternsLoaded,availableTransforms:Array.from(this.enabledTransforms),lastChecked:new Date,issues:r,metrics:{totalTransforms:this.totalTransforms,successfulTransforms:this.successfulTransforms,averageDurationMs:e,cacheHitRate:n}}}ensureInitialized(){if(!this.initialized)throw new M("AgentBoosterAdapter not initialized. Call initialize() first.","var-to-const")}ensureEnabled(){if(!this.config.enabled)throw new M("AgentBoosterAdapter is disabled. Set enabled: true in config.","var-to-const")}createErrorResult(e,n,r,o){return{success:!1,transformType:n,originalCode:e,transformedCode:e,edits:[],changeCount:0,confidence:0,durationMs:Date.now()-o,implementationUsed:"typescript",usedFallback:!1,error:r,warnings:[]}}confidenceToRisk(e){return e>=.95?"info":e>=.85?"low":e>=.7?"medium":e>=.5?"high":"critical"}};async function ee(s={},e,n){let r=new v(s,e,n);return await r.initialize(),r}function re(s={},e,n){return new v(s,e,n)}export{v as a,ee as b,re as c};
6
+ ${c.trim()}`;r.push(p(s,a.index,a.index+l.length,f,"Convert .then() to await"))}e.debug("promise-to-async transform completed",{converted:r.length,warnings:o.length});let i=T(s,"promise-to-async",r,n,.65);return i.warnings=o,r.length>0&&i.warnings.push("Promise chains converted to await - ensure containing function is async"),i}catch(t){return e.error("promise-to-async transform failed",t),w(s,"promise-to-async",t instanceof Error?t.message:"Unknown error",n)}}function N(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t,a=/(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*require\s*\(\s*(['"`][^'"`]+['"`])\s*\)\s*;?/g;for(;(t=a.exec(s))!==null;){let[c,f,g]=t,d=`import ${f} from ${g};`;r.push(p(s,t.index,t.index+c.length,d,"Convert require to import"))}let i=/(?:const|let|var)\s+\{\s*([^}]+)\s*\}\s*=\s*require\s*\(\s*(['"`][^'"`]+['"`])\s*\)\s*;?/g;for(;(t=i.exec(s))!==null;){let[c,f,g]=t,d=`import { ${f.trim()} } from ${g};`;r.push(p(s,t.index,t.index+c.length,d,"Convert destructured require to import"))}let l=/module\.exports\s*=\s*([^;]+);?/g;for(;(t=l.exec(s))!==null;){let[c,f]=t,g=`export default ${f.trim()};`;r.push(p(s,t.index,t.index+c.length,g,"Convert module.exports to export default"))}let m=/exports\.([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*([^;]+);?/g;for(;(t=m.exec(s))!==null;){let[c,f,g]=t,d=g.trim(),h;d.startsWith("function")||d.startsWith("class")?h=`export ${d}`:d.startsWith("async function")?h=`export ${d}`:h=`export const ${f} = ${d};`,r.push(p(s,t.index,t.index+c.length,h,`Convert exports.${f} to named export`))}e.debug("cjs-to-esm transform completed",{edits:r.length});let u=T(s,"cjs-to-esm",r,n,.85);return u.warnings=o,u}catch(t){return e.error("cjs-to-esm transform failed",t),w(s,"cjs-to-esm",t instanceof Error?t.message:"Unknown error",n)}}function H(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/(const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*function\s*\(([^)]*)\)\s*\{/g,a;for(;(a=t.exec(s))!==null;){let[m,u,c,f]=a,g=a.index,d=1,h=g+m.length;for(;d>0&&h<s.length;)s[h]==="{"&&d++,s[h]==="}"&&d--,h++;let S=s.slice(g,h);if(/\bthis\b/.test(S)){o.push(`Function ${c} uses 'this' - skipping arrow conversion (would change binding)`);continue}if(/\barguments\b/.test(S)){o.push(`Function ${c} uses 'arguments' - skipping arrow conversion (not available in arrow functions)`);continue}let D=`${u} ${c} = (${f}) => {`;r.push(p(s,a.index,a.index+m.length,D,`Convert function ${c} to arrow function`))}let i=/function\s*\(([^)]*)\)\s*\{\s*return\s+([^;]+);\s*\}/g;for(;(a=i.exec(s))!==null;){let[m,u,c]=a;if(/\b(this|arguments)\b/.test(m))continue;let f=u.includes(",")||u.trim()===""?`(${u}) => ${c}`:`${u.trim()} => ${c}`;r.push(p(s,a.index,a.index+m.length,f,"Convert callback to arrow function"))}e.debug("func-to-arrow transform completed",{converted:r.length,warnings:o.length});let l=T(s,"func-to-arrow",r,n,.85);return l.warnings=o,l}catch(t){return e.error("func-to-arrow transform failed",t),w(s,"func-to-arrow",t instanceof Error?t.message:"Unknown error",n)}}var V={"var-to-const":Z,"add-types":O,"remove-console":I,"promise-to-async":j,"cjs-to-esm":N,"func-to-arrow":H};function $(s,e,n){let r=V[e];return r?r(s,n):{success:!1,transformType:e,originalCode:s,transformedCode:s,edits:[],changeCount:0,confidence:0,durationMs:0,implementationUsed:"typescript",usedFallback:!1,error:`Unknown transform type: ${e}`,warnings:[]}}var q={JavaScript:0,TypeScript:1,Python:2,Rust:3,Go:4,Java:5,C:6,Cpp:7},y=null,A=null,x=null,R=!1,k=null;async function G(){if(R)return k===null;if(k)return!1;try{let s=await import("./agent-booster-wasm-LAE4NTVX.js");return y=s.transform,A=s.warmup,x=s.isWasmAvailable,R=!0,!0}catch(s){return k=s,R=!0,!1}}function K(s){return q.TypeScript}var L=class{cache=new Map;ttlMs;enabled;constructor(e,n){this.enabled=e,this.ttlMs=n}generateKey(e,n){let r=0;for(let o=0;o<e.length;o++){let t=e.charCodeAt(o);r=(r<<5)-r+t,r=r&r}return`${n}:${r}:${e.length}`}get(e,n){if(!this.enabled)return null;let r=this.generateKey(e,n),o=this.cache.get(r);return o?Date.now()>o.expiresAt?(this.cache.delete(r),null):o.result:null}set(e,n,r){if(!this.enabled)return;let o=this.generateKey(e,n);this.cache.set(o,{result:r,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},v=class{config;logger;cache;enabledTransforms;metricsTracker;initialized=!1;wasmAvailable=!1;wasmModule=null;patternsLoaded=!1;totalTransforms=0;successfulTransforms=0;totalDurationMs=0;cacheHits=0;cacheMisses=0;constructor(e={},n,r){this.config={...z,...e},this.logger=n||{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.metricsTracker=r,this.cache=new L(this.config.cacheEnabled,this.config.cacheTtlMs),this.config.transforms.length===0?this.enabledTransforms=new Set(b):this.enabledTransforms=new Set(this.config.transforms)}setMetricsTracker(e){this.metricsTracker=e}async initialize(){this.initialized||(this.logger.info("Initializing Agent Booster adapter",{enabled:this.config.enabled,transforms:Array.from(this.enabledTransforms)}),this.config.transforms.length===0&&await this.loadEligibleTransformsFromPatterns(),this.config.enabled&&await this.tryLoadWasm(),this.initialized=!0,this.logger.info("Agent Booster adapter initialized",{wasmAvailable:this.wasmAvailable,enabledTransforms:Array.from(this.enabledTransforms),patternsLoaded:this.patternsLoaded}))}async loadEligibleTransformsFromPatterns(){try{let n=await F().getEligibleBoosterTransforms();if(n.length>0){let r=n.filter(o=>b.includes(o));if(r.length>0){this.enabledTransforms=new Set(r),this.patternsLoaded=!0,this.logger.info("Loaded eligible transforms from PatternLoader",{fromPatterns:r,invalidIgnored:n.length-r.length});return}}this.logger.debug("PatternLoader returned empty transforms, using defaults")}catch(e){this.logger.warn("Failed to load transforms from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.enabledTransforms=new Set(b),this.patternsLoaded=!1}async tryLoadWasm(){try{if(this.logger.debug("Loading WASM module"),!await G()||!x){this.logger.debug("WASM module could not be loaded, using TypeScript fallback"),this.wasmAvailable=!1;return}this.logger.debug("Checking WASM availability from local module"),await x()&&y&&A?(this.logger.debug("Warming up WASM module"),await A(),this.wasmModule={transform:y,warmup:A,isAvailable:x},this.wasmAvailable=!0,this.logger.info("WASM Agent Booster loaded and warmed up successfully",{source:"local-module"})):(this.logger.debug("WASM not available from local module, using TypeScript fallback"),this.wasmAvailable=!1)}catch(e){this.logger.warn("Failed to load WASM module",{error:e instanceof Error?e.message:"Unknown error"}),this.wasmAvailable=!1}}async dispose(){this.cache.clear(),this.wasmModule=null,this.wasmAvailable=!1,this.initialized=!1,this.logger.info("Agent Booster adapter disposed")}async transform(e,n){this.ensureInitialized(),this.ensureEnabled();let r=Date.now();if(this.totalTransforms++,!this.enabledTransforms.has(n))return this.createErrorResult(e,n,`Transform type '${n}' is not enabled`,r);let o=this.cache.get(e,n);if(o)return this.cacheHits++,this.logger.debug("Cache hit for transform",{type:n}),{...o,durationMs:Date.now()-r};this.cacheMisses++;let t;try{t=await this.executeWithFallback(e,n,r)}catch(a){return this.createErrorResult(e,n,a instanceof Error?a.message:"Unknown error",r)}return t.success&&(this.successfulTransforms++,this.cache.set(e,n,t)),this.totalDurationMs+=t.durationMs,await this.recordMetrics(t,n),t}async recordMetrics(e,n){if(this.metricsTracker)try{let r=`booster-${n}-${Date.now()}`;await this.metricsTracker.recordOutcome("booster",r,e.success,e.durationMs,{subType:n,confidence:e.confidence,usedFallback:e.usedFallback,implementationUsed:e.implementationUsed,itemCount:e.changeCount,errorMessage:e.error})}catch(r){this.logger.warn("Failed to record metrics",{error:r instanceof Error?r.message:"Unknown error"})}}async executeWithFallback(e,n,r){if(this.wasmAvailable)try{let t=await this.executeWasmTransform(e,n,r);if(t.success&&t.confidence>=this.config.confidenceThreshold)return t;this.logger.debug("WASM transform low confidence, trying TypeScript",{confidence:t.confidence,threshold:this.config.confidenceThreshold})}catch(t){this.logger.warn("WASM transform failed, falling back to TypeScript",{error:t instanceof Error?t.message:"Unknown error"})}let o=$(e,n,this.logger);return o.durationMs=Date.now()-r,this.config.fallbackToLLM&&o.confidence<this.config.confidenceThreshold&&(this.logger.debug("TypeScript transform low confidence, LLM fallback available",{confidence:o.confidence,threshold:this.config.confidenceThreshold}),o.warnings.push(`Confidence ${o.confidence.toFixed(2)} is below threshold ${this.config.confidenceThreshold}. LLM fallback recommended for review.`),o.usedFallback=!0),o}async executeWasmTransform(e,n,r){if(!this.wasmAvailable)throw new C;let o=K(n),t=$(e,n,this.logger);if(t.changeCount===0)return{...t,durationMs:Date.now()-r,implementationUsed:"wasm"};if(!y)throw new C("WASM transform function not loaded");let a=await Promise.race([y(e,t.transformedCode,o,{confidenceThreshold:this.config.confidenceThreshold,allowFallback:!0}),new Promise((m,u)=>setTimeout(()=>u(new P("WASM transform timed out",n,this.config.timeoutMs)),this.config.timeoutMs))]),i=Date.now()-r,l=a.success&&a.mergedCode!==e?t.changeCount:0;return{success:a.success,transformType:n,originalCode:e,transformedCode:a.mergedCode,edits:t.edits,changeCount:l,confidence:a.confidence,durationMs:i,implementationUsed:a.source==="wasm"?"wasm":"typescript",usedFallback:a.source!=="wasm",error:a.error,warnings:a.syntaxValid?[]:["WASM reported syntax may be invalid"]}}async batchTransform(e,n){this.ensureInitialized(),this.ensureEnabled();let r=Date.now(),o=[],t=[],a=0,i=0,l=0,m=0;for(let u of e){if(u.content.length>this.config.maxFileSizeBytes){let c=new B(u.path,u.content.length,this.config.maxFileSizeBytes);t.push({path:u.path,error:c.message}),i++;continue}try{let c=await this.transform(u.content,n);o.push({path:u.path,result:c}),c.success?c.changeCount>0?(a++,m+=c.changeCount):l++:(i++,c.error&&t.push({path:u.path,error:c.error}))}catch(c){i++,t.push({path:u.path,error:c instanceof Error?c.message:"Unknown error"})}}return{success:i===0,transformType:n,files:o,totalFiles:e.length,successCount:a,failureCount:i,noChangeCount:l,totalChanges:m,durationMs:Date.now()-r,errors:t}}async detectTransformOpportunities(e){this.ensureInitialized(),this.ensureEnabled();let n=Date.now(),r=[],o={},t=[];for(let a of b)o[a]=0;for(let a of Array.from(this.enabledTransforms))try{let i=await this.transform(e,a);if(i.changeCount>0)for(let l of i.edits){let m={type:a,confidence:i.confidence,location:l.start,codeSnippet:l.oldText.slice(0,100)+(l.oldText.length>100?"...":""),suggestedCode:l.newText.slice(0,100)+(l.newText.length>100?"...":""),reason:l.description,risk:this.confidenceToRisk(i.confidence),estimatedDurationMs:E[a].typicalLatencyMs};r.push(m),o[a]++}}catch(i){t.push(`Failed to analyze for ${a}: ${i instanceof Error?i.message:"Unknown error"}`)}return r.sort((a,i)=>i.confidence-a.confidence),{opportunities:r,totalCount:r.length,byType:o,durationMs:Date.now()-n,complete:t.length===0,warnings:t}}isTransformAvailable(e){return this.enabledTransforms.has(e)}getTransformMetadata(e){return E[e]}getAvailableTransforms(){return Array.from(this.enabledTransforms)}isWasmAvailable(){return this.wasmAvailable}getHealth(){let e=this.totalTransforms>0?this.totalDurationMs/this.totalTransforms:0,n=this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0,r=[];return this.initialized||r.push("Adapter not initialized"),this.config.enabled||r.push("Adapter is disabled"),this.wasmAvailable||r.push("WASM module not loaded (using TypeScript fallback)"),this.patternsLoaded||r.push("Patterns not loaded from PatternLoader (using defaults)"),{ready:this.initialized&&this.config.enabled,wasmAvailable:this.wasmAvailable,patternsLoaded:this.patternsLoaded,availableTransforms:Array.from(this.enabledTransforms),lastChecked:new Date,issues:r,metrics:{totalTransforms:this.totalTransforms,successfulTransforms:this.successfulTransforms,averageDurationMs:e,cacheHitRate:n}}}ensureInitialized(){if(!this.initialized)throw new M("AgentBoosterAdapter not initialized. Call initialize() first.","var-to-const")}ensureEnabled(){if(!this.config.enabled)throw new M("AgentBoosterAdapter is disabled. Set enabled: true in config.","var-to-const")}createErrorResult(e,n,r,o){return{success:!1,transformType:n,originalCode:e,transformedCode:e,edits:[],changeCount:0,confidence:0,durationMs:Date.now()-o,implementationUsed:"typescript",usedFallback:!1,error:r,warnings:[]}}confidenceToRisk(e){return e>=.95?"info":e>=.85?"low":e>=.7?"medium":e>=.5?"high":"critical"}};async function ee(s={},e,n){let r=new v(s,e,n);return await r.initialize(),r}function re(s={},e,n){return new v(s,e,n)}export{v as a,ee as b,re as c};
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.7");process.exit(0)}
2
- import{a as L}from"./chunk-ZSXSUUBS.js";import*as w from"fs";var R={"aqe test generate":{domain:"test-generation",action:"generateTests"},"aqe test execute":{domain:"test-execution",action:"execute"},"aqe coverage analyze":{domain:"coverage-analysis",action:"analyze"},"aqe coverage gaps":{domain:"coverage-analysis",action:"detectGaps"},"aqe quality gate":{domain:"quality-assessment",action:"evaluateGate"},"aqe quality assess":{domain:"quality-assessment",action:"analyzeQuality"},"aqe security scan":{domain:"security-compliance",action:"runSASTScan"},"aqe security audit":{domain:"security-compliance",action:"runAudit"},"aqe defect predict":{domain:"defect-intelligence",action:"predictDefects"},"aqe code index":{domain:"code-intelligence",action:"index"},"aqe code impact":{domain:"code-intelligence",action:"analyzeImpact"},"aqe contract validate":{domain:"contract-testing",action:"validateContract"},"aqe chaos test":{domain:"chaos-resilience",action:"runChaosTest"},"aqe requirements validate":{domain:"requirements-validation",action:"validateRequirements"},"aqe visual test":{domain:"visual-accessibility",action:"runVisualTest"},"aqe accessibility test":{domain:"visual-accessibility",action:"runAccessibilityTest"},"aqe learn optimize":{domain:"learning-optimization",action:"optimizeAllStrategies"}},D={daily:"0 0 * * *",weekly:"0 0 * * 0",hourly:"0 * * * *",minutely:"* * * * *"},S=1e4,x=20,M=1e4,W=["__proto__","constructor","prototype"];function v(t){return!W.includes(t)}function C(t){let n=t.split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.8");process.exit(0)}
2
+ import{a as L}from"./chunk-R2LWLZ3Y.js";import*as w from"fs";var R={"aqe test generate":{domain:"test-generation",action:"generateTests"},"aqe test execute":{domain:"test-execution",action:"execute"},"aqe coverage analyze":{domain:"coverage-analysis",action:"analyze"},"aqe coverage gaps":{domain:"coverage-analysis",action:"detectGaps"},"aqe quality gate":{domain:"quality-assessment",action:"evaluateGate"},"aqe quality assess":{domain:"quality-assessment",action:"analyzeQuality"},"aqe security scan":{domain:"security-compliance",action:"runSASTScan"},"aqe security audit":{domain:"security-compliance",action:"runAudit"},"aqe defect predict":{domain:"defect-intelligence",action:"predictDefects"},"aqe code index":{domain:"code-intelligence",action:"index"},"aqe code impact":{domain:"code-intelligence",action:"analyzeImpact"},"aqe contract validate":{domain:"contract-testing",action:"validateContract"},"aqe chaos test":{domain:"chaos-resilience",action:"runChaosTest"},"aqe requirements validate":{domain:"requirements-validation",action:"validateRequirements"},"aqe visual test":{domain:"visual-accessibility",action:"runVisualTest"},"aqe accessibility test":{domain:"visual-accessibility",action:"runAccessibilityTest"},"aqe learn optimize":{domain:"learning-optimization",action:"optimizeAllStrategies"}},D={daily:"0 0 * * *",weekly:"0 0 * * 0",hourly:"0 * * * *",minutely:"* * * * *"},S=1e4,x=20,M=1e4,W=["__proto__","constructor","prototype"];function v(t){return!W.includes(t)}function C(t){let n=t.split(`
3
3
  `);if(n.length>S)throw new Error(`YAML content exceeds maximum allowed lines (${S}). File has ${n.length} lines.`);for(let i=0;i<n.length;i++)if(n[i].length>M)throw new Error(`YAML line ${i+1} exceeds maximum allowed length (${M} characters).`);let a={};for(let i=0;i<n.length;i++){let e=n[i];if(e.trim()===""||e.trim().startsWith("#")||e.search(/\S/)!==0)continue;let o=e.match(/^([\w_-]+):\s*(.+)$/);if(o){let[,c,u]=o;v(c)&&(a[c]=f(u))}}let r=["tags","stages","triggers"];for(let i of r){let e=new RegExp(`^${i}:\\s*$`),s=-1;for(let l=0;l<n.length;l++){let d=n[l];if(!(d.trim()===""||d.trim().startsWith("#"))&&e.test(d.trim())){s=l;break}}if(s===-1)continue;let o=[];a[i]=o;let c=n[s].search(/\S/),u=s+1;for(;u<n.length;){let l=n[u];if(l.trim()===""||l.trim().startsWith("#")){u++;continue}let d=l.search(/\S/),p=l.trim();if(d<=c&&!p.startsWith("-"))break;if(p.startsWith("- ")){let m=p.slice(2).trim();if(!m.includes(":")){o.push(f(m)),u++;continue}let g={},k=m.match(/^([\w_-]+):\s*(.*)$/);if(k){let[,h,y]=k;g[h]=f(y)}let T=d;for(u++;u<n.length;){let h=n[u];if(h.trim()===""||h.trim().startsWith("#")){u++;continue}let y=h.search(/\S/),q=h.trim();if(y<=T)break;let _=q.match(/^([\w_-]+):\s*(.*)$/);if(_){let[,A,$]=_;if($===""){let b=E(n,u+1,y,1);g[A]=b.value,u=b.nextLine;continue}else g[A]=f($)}u++}o.push(g)}else u++}}return a}function E(t,n,a,r=0){if(r>x)throw new Error(`YAML nesting exceeds maximum allowed depth (${x}).`);let i={},e=null,s=null,o=n;for(;o<t.length;){let u=t[o];if(u.trim()===""||u.trim().startsWith("#")){o++;continue}let l=u.search(/\S/),d=u.trim();if(l<=a)break;if(d.startsWith("- ")){let m=d.slice(2).trim();s&&!Array.isArray(i[s])&&(i[s]=[]),s?i[s].push(f(m)):(e||(e=[]),e.push(f(m))),o++;continue}let p=d.match(/^([\w_-]+):\s*(.*)$/);if(p){let[,m,g]=p;if(!v(m)){o++;continue}g===""?(s=m,i[m]=[]):(i[m]=f(g),s=null)}o++}if(e&&Object.keys(i).length===0)return{value:e,nextLine:o};let c=Object.keys(i);return c.length===1&&Array.isArray(i[c[0]])?{value:i[c[0]],nextLine:o}:{value:i,nextLine:o}}function f(t){if(t==="")return"";if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t==="true")return!0;if(t==="false")return!1;if(t==="null"||t==="~")return null;let n=Number(t);return!isNaN(n)&&t!==""?n:t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1).split(",").map(r=>f(r.trim())):t}function K(t){let n=[];if(!w.existsSync(t))return{success:!1,errors:[`File not found: ${t}`]};let a;try{a=w.readFileSync(t,"utf-8")}catch(r){return{success:!1,errors:[`Failed to read file: ${r}`]}}return Y(a,t)}function Y(t,n){let a=[],r;try{r=C(t)}catch(s){return{success:!1,errors:[`Invalid YAML syntax: ${s}`]}}if((!r.name||typeof r.name!="string")&&a.push('Pipeline must have a "name" field'),(!r.stages||!Array.isArray(r.stages))&&a.push('Pipeline must have a "stages" array'),a.length>0)return{success:!1,errors:a};let i={name:r.name,description:r.description,version:r.version||"1.0.0",schedule:r.schedule,stages:r.stages.map((s,o)=>{let c=s;return{name:c.name||`stage-${o}`,command:c.command,params:c.params,depends_on:c.depends_on,condition:c.condition,timeout:c.timeout,retry:c.retry,continue_on_failure:c.continue_on_failure}}),triggers:r.triggers,tags:r.tags,timeout:r.timeout};for(let s=0;s<i.stages.length;s++){let o=i.stages[s];o.command||a.push(`Stage ${s+1} (${o.name}) must have a "command" field`)}if(a.length>0)return{success:!1,pipeline:i,errors:a};let e=O(i,n);return{success:!0,pipeline:i,workflow:e,errors:[]}}function O(t,n){let a=`pipeline-${t.name.replace(/\s+/g,"-").toLowerCase()}`,r=t.stages.map((e,s)=>{let o=P(e.command),c={};if(e.params)for(let[l,d]of Object.entries(e.params))v(l)&&(c[l]=`input.${l}`);let u={id:`stage-${e.name.replace(/\s+/g,"-").toLowerCase()}`,name:e.name,domain:o.domain,action:o.action,inputMapping:Object.keys(c).length>0?c:void 0,dependsOn:e.depends_on?.map(l=>`stage-${l.replace(/\s+/g,"-").toLowerCase()}`),timeout:e.timeout?e.timeout*1e3:void 0,continueOnFailure:e.continue_on_failure};return e.condition&&(u.condition={path:e.condition.path,operator:e.condition.operator,value:e.condition.value}),e.retry&&(u.retry={maxAttempts:e.retry.max_attempts||3,backoffMs:(e.retry.backoff_seconds||1)*1e3}),u}),i=t.triggers?.map(e=>{let s={eventType:I(e),sourceDomain:e.source_domain};return e.condition&&(s.condition={path:e.condition.path,operator:e.condition.operator,value:e.condition.value}),s});return{id:a,name:t.name,description:t.description||`Pipeline from ${n||"inline YAML"}`,version:t.version||"1.0.0",steps:r,triggers:i,tags:t.tags,timeout:t.timeout?t.timeout*1e3:void 0}}function P(t){let n=t.trim().replace(/\s+/g," ").toLowerCase();for(let[a,r]of Object.entries(R))if(n.startsWith(a.toLowerCase()))return r;return n.includes("test")&&n.includes("generate")?{domain:"test-generation",action:"generateTests"}:n.includes("test")&&(n.includes("execute")||n.includes("run"))?{domain:"test-execution",action:"execute"}:n.includes("coverage")?{domain:"coverage-analysis",action:"analyze"}:n.includes("quality")||n.includes("gate")?{domain:"quality-assessment",action:"evaluateGate"}:n.includes("security")||n.includes("scan")?{domain:"security-compliance",action:"runSASTScan"}:n.includes("defect")||n.includes("predict")?{domain:"defect-intelligence",action:"predictDefects"}:{domain:"learning-optimization",action:"runLearningCycle"}}function I(t){let n=t.event.toLowerCase();return n==="push"?"code-intelligence.CodePushed":n==="pull_request"||n==="pr"?"code-intelligence.PullRequestOpened":n==="schedule"?"workflow.ScheduleTrigger":n==="quality_gate"?"quality-assessment.QualityGateEvaluated":n==="test_complete"?"test-execution.TestRunCompleted":n}function F(t){let n=[],a=[];if(t.name||n.push({path:"name",message:"Pipeline name is required",severity:"error"}),!t.stages||t.stages.length===0)n.push({path:"stages",message:"Pipeline must have at least one stage",severity:"error"});else{let r=new Set;for(let e=0;e<t.stages.length;e++){let s=t.stages[e],o=`stages[${e}]`;if(r.has(s.name)&&n.push({path:`${o}.name`,message:`Duplicate stage name: ${s.name}`,severity:"error"}),r.add(s.name),s.command?P(s.command).domain==="learning-optimization"&&!s.command.toLowerCase().includes("learn")&&a.push({path:`${o}.command`,message:`Command "${s.command}" not recognized, will default to learning-optimization domain`,severity:"warning"}):n.push({path:`${o}.command`,message:"Stage must have a command",severity:"error"}),s.depends_on)for(let c of s.depends_on)t.stages.some(u=>u.name===c)||n.push({path:`${o}.depends_on`,message:`Unknown dependency: ${c}`,severity:"error"});s.timeout!==void 0&&s.timeout<=0&&n.push({path:`${o}.timeout`,message:"Timeout must be a positive number",severity:"error"}),s.retry&&s.retry.max_attempts!==void 0&&s.retry.max_attempts<1&&n.push({path:`${o}.retry.max_attempts`,message:"max_attempts must be at least 1",severity:"error"})}let i=N(t.stages);i&&n.push({path:"stages",message:`Circular dependency detected: ${i}`,severity:"error"})}if(t.schedule&&(z(t.schedule)||n.push({path:"schedule",message:`Invalid cron expression: ${t.schedule}`,severity:"error"})),t.triggers)for(let r=0;r<t.triggers.length;r++){let i=t.triggers[r],e=`triggers[${r}]`;i.event||n.push({path:`${e}.event`,message:"Trigger must have an event type",severity:"error"}),i.source_domain&&!L.includes(i.source_domain)&&a.push({path:`${e}.source_domain`,message:`Unknown domain: ${i.source_domain}`,severity:"warning"})}return{valid:n.length===0,errors:n,warnings:a}}function N(t){let n=new Set,a=new Set,r=(i,e)=>{if(a.has(i))return[...e,i].join(" -> ");if(n.has(i))return null;n.add(i),a.add(i);let s=t.find(o=>o.name===i);if(s?.depends_on)for(let o of s.depends_on){let c=r(o,[...e,i]);if(c)return c}return a.delete(i),null};for(let i of t){let e=r(i.name,[]);if(e)return e}return null}function z(t){if(Object.keys(D).includes(t))return!0;let n=t.trim().split(/\s+/);if(n.length!==5)return!1;let a=[/^(\*|[0-5]?\d)(-[0-5]?\d)?(\/\d+)?$/,/^(\*|1?\d|2[0-3])(-\d+)?(\/\d+)?$/,/^(\*|[1-9]|[12]\d|3[01])(-\d+)?(\/\d+)?$/,/^(\*|[1-9]|1[0-2])(-\d+)?(\/\d+)?$/,/^(\*|[0-7])(-[0-7])?(\/\d+)?$/];for(let r=0;r<5;r++){let i=n[r].split(",");for(let e of i)if(!a[r].test(e)&&e!=="*")return!1}return!0}function G(t){let n={"@daily":"Daily at midnight","@weekly":"Weekly on Sunday at midnight","@hourly":"Every hour","@minutely":"Every minute"};if(n[t])return n[t];if(Object.keys(D).includes(t))return{daily:"Daily at midnight",weekly:"Weekly on Sunday at midnight",hourly:"Every hour",minutely:"Every minute"}[t]||t;let a=t.trim().split(/\s+/);if(a.length!==5)return t;let[r,i,e,s,o]=a;return r==="0"&&i==="0"&&e==="*"&&s==="*"&&o==="*"?"Daily at midnight":r==="0"&&e==="*"&&s==="*"&&o==="*"?`Daily at ${i}:00`:r!=="*"&&i!=="*"&&e==="*"&&s==="*"?`Daily at ${i}:${r.padStart(2,"0")}`:i==="*"&&r==="0"?"Every hour":r!=="*"&&i==="*"?`Every hour at minute ${r}`:t}function H(t,n=new Date){let a=t.trim().split(/\s+/);if(a.length!==5)return new Date(n.getTime()+1440*60*1e3);let[r,i]=a,e=new Date(n);return i!=="*"&&r!=="*"?(e.setHours(parseInt(i,10),parseInt(r,10),0,0),e<=n&&e.setDate(e.getDate()+1)):i!=="*"?(e.setHours(parseInt(i,10),0,0,0),e<=n&&e.setDate(e.getDate()+1)):r!=="*"?(e.setMinutes(parseInt(r,10),0,0),e<=n&&e.setHours(e.getHours()+1)):(e.setSeconds(0,0),e.setMinutes(e.getMinutes()+1)),e}export{C as a,K as b,F as c,G as d,H as e};
@@ -1,6 +1,6 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.7");process.exit(0)}
2
- import{a as ne}from"./chunk-APPVAGD5.js";import{d as B,e as j,f as re,g as W}from"./chunk-7TKZ6LK6.js";import{c as Ze,d as et}from"./chunk-DL46KSFX.js";import{a as Ae,d as xe,f as Ve}from"./chunk-DS3XAGGL.js";import{b as v,c as P}from"./chunk-ZSXSUUBS.js";import{a as y,b as Te,c as Re}from"./chunk-MR7V7QVL.js";import{f as C}from"./chunk-SMKRBNO7.js";import{B as Q,D as H,G as te,P as M,S as F,b as D}from"./chunk-WV3R5JFE.js";import{a as Ee,d as J,f as Ye,g as Ke}from"./chunk-UEFAPTBV.js";var Y=J(S=>{var lt=S&&S.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(S,"__esModule",{value:!0});var ut=Object.prototype.hasOwnProperty;function le(n,e){return ut.call(n,e)}S.hasOwnProperty=le;function Me(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var i in n)le(n,i)&&r.push(i);return r}S._objectKeys=Me;function ht(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}S._deepClone=ht;function dt(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}S.isInteger=dt;function oe(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}S.escapePathComponent=oe;function ft(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}S.unescapePathComponent=ft;function ue(n,e){var t;for(var r in n)if(le(n,r)){if(n[r]===e)return oe(r)+"/";if(typeof n[r]=="object"&&(t=ue(n[r],e),t!=""))return oe(r)+"/"+t}return""}S._getPathRecursive=ue;function mt(n,e){if(n===e)return"/";var t=ue(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}S.getPath=mt;function ce(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(ce(n[e]))return!0}else if(typeof n=="object"){for(var r=Me(n),i=r.length,s=0;s<i;s++)if(ce(n[r[s]]))return!0}}return!1}S.hasUndefined=ce;function He(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){lt(e,n);function e(t,r,i,s,a){var c=this.constructor,l=n.call(this,He(t,{name:r,index:i,operation:s,tree:a}))||this;return l.name=r,l.index=i,l.operation=s,l.tree=a,Object.setPrototypeOf(l,c.prototype),l.message=He(t,{name:r,index:i,operation:s,tree:a}),l}return e})(Error);S.PatchError=pt});var he=J(p=>{Object.defineProperty(p,"__esModule",{value:!0});var b=Y();p.JsonPatchError=b.PatchError;p.deepClone=b._deepClone;var L={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=K(t,this.path);r&&(r=b._deepClone(r));var i=I(t,{op:"remove",path:this.from}).removed;return I(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=K(t,this.from);return I(t,{op:"add",path:this.path,value:b._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:q(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},gt={add:function(n,e,t){return b.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:L.move,copy:L.copy,test:L.test,_get:L._get};function K(n,e){if(e=="")return n;var t={op:"_get",path:e};return I(n,t),t.value}p.getValueByPointer=K;function I(n,e,t,r,i,s){if(t===void 0&&(t=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),s===void 0&&(s=0),t&&(typeof t=="function"?t(e,0,n,e.path):V(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=K(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=q(n,e.value),a.test===!1)throw new p.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new p.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=b._deepClone(n));var c=e.path||"",l=c.split("/"),o=n,u=1,h=l.length,f=void 0,d=void 0,m=void 0;for(typeof t=="function"?m=t:m=V;;){if(d=l[u],d&&d.indexOf("~")!=-1&&(d=b.unescapePathComponent(d)),i&&(d=="__proto__"||d=="prototype"&&u>0&&l[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&f===void 0&&(o[d]===void 0?f=l.slice(0,u).join("/"):u==h-1&&(f=e.path),f!==void 0&&m(e,0,n,f)),u++,Array.isArray(o)){if(d==="-")d=o.length;else{if(t&&!b.isInteger(d))throw new p.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);b.isInteger(d)&&(d=~~d)}if(u>=h){if(t&&e.op==="add"&&d>o.length)throw new p.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var a=gt[e.op].call(e,o,d,n);if(a.test===!1)throw new p.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(u>=h){var a=L[e.op].call(e,o,d,n);if(a.test===!1)throw new p.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[d],t&&u<h&&(!o||typeof o!="object"))throw new p.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}p.applyOperation=I;function Le(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new p.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=b._deepClone(n));for(var s=new Array(e.length),a=0,c=e.length;a<c;a++)s[a]=I(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}p.applyPatch=Le;function yt(n,e,t){var r=I(n,e);if(r.test===!1)throw new p.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}p.applyReducer=yt;function V(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new p.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new p.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new p.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new p.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new p.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&b.hasUndefined(n.value))throw new p.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new p.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new p.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a={op:"_get",path:n.from,value:void 0},c=ke([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new p.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new p.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}p.validator=V;function ke(n,e,t){try{if(!Array.isArray(n))throw new p.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Le(b._deepClone(e),b._deepClone(n),t||!0);else{t=t||V;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof p.JsonPatchError)return i;throw i}}p.validate=ke;function q(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(!q(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],!q(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}p._areEquals=q});var Ue=J(k=>{Object.defineProperty(k,"__esModule",{value:!0});var w=Y(),vt=he(),fe=new WeakMap,Pt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),wt=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function St(n){return fe.get(n)}function bt(n,e){return n.observers.get(e)}function Et(n,e){n.observers.delete(e.callback)}function Tt(n,e){e.unobserve()}k.unobserve=Tt;function Rt(n,e){var t=[],r,i=St(n);if(!i)i=new Pt(n),fe.set(n,i);else{var s=bt(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=w._deepClone(n),e){r.callback=e,r.next=null;var a=function(){de(r)},c=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return r.patches=t,r.object=n,r.unobserve=function(){de(r),clearTimeout(r.next),Et(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 wt(e,r)),r}k.observe=Rt;function de(n,e){e===void 0&&(e=!1);var t=fe.get(n.object);me(t.value,n.object,n.patches,"",e),n.patches.length&&vt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=de;function me(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=w._objectKeys(e),a=w._objectKeys(n),c=!1,l=!1,o=a.length-1;o>=0;o--){var u=a[o],h=n[u];if(w.hasOwnProperty(e,u)&&!(e[u]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var f=e[u];typeof h=="object"&&h!=null&&typeof f=="object"&&f!=null&&Array.isArray(h)===Array.isArray(f)?me(h,f,t,r+"/"+w.escapePathComponent(u),i):h!==f&&(c=!0,i&&t.push({op:"test",path:r+"/"+w.escapePathComponent(u),value:w._deepClone(h)}),t.push({op:"replace",path:r+"/"+w.escapePathComponent(u),value:w._deepClone(f)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+w.escapePathComponent(u),value:w._deepClone(h)}),t.push({op:"remove",path:r+"/"+w.escapePathComponent(u)}),l=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!l&&s.length==a.length))for(var o=0;o<s.length;o++){var u=s[o];!w.hasOwnProperty(n,u)&&e[u]!==void 0&&t.push({op:"add",path:r+"/"+w.escapePathComponent(u),value:w._deepClone(e[u])})}}}function At(n,e,t){t===void 0&&(t=!1);var r=[];return me(n,e,r,"",t),r}k.compare=At});var Qe=J(O=>{var xt=he();Object.assign(O,xt);var Ct=Ue();Object.assign(O,Ct);var Z=Y();O.JsonPatchError=Z.PatchError;O.deepClone=Z._deepClone;O.escapePathComponent=Z.escapePathComponent;O.unescapePathComponent=Z.unescapePathComponent});Re();var z=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}config;rvfPath;skipCloseOnDispose;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=y(e),console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-3WG7PBPL.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}}}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 P(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return P(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{this.sqliteStore.storePattern(e,e.embedding)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,y(r))}if(e.embedding&&this.adapter)try{let r=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding);this.adapter.ingest([{id:e.id,vector:r}])}catch(r){console.warn(`[RvfPatternStore] RVF ingest failed for ${e.id}:`,y(r))}return v(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:B({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?v(i):P(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),l=this.adapter.search(c,i*2);for(let o of l){let u=await this.get(o.id);if(u&&this.matchesFilters(u,t)){let h=this.calculateReuseInfo(u,o.score);s.push({pattern:u,score:o.score,matchType:"vector",similarity:o.score,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",y(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let c=this.sqliteStore.getPatterns({limit:i*4}),l=e,o=Math.sqrt(l.reduce((u,h)=>u+h*h,0));if(o>0)for(let u of c){if(!this.matchesFilters(u,t))continue;let h=this.sqliteStore.getPattern(u.id),f=h?.embedding;if(!f||f.length!==l.length)continue;let d=0,m=0;for(let T=0;T<l.length;T++)d+=l[T]*f[T],m+=f[T]*f[T];if(m=Math.sqrt(m),m===0)continue;let g=d/(o*m),E=this.calculateReuseInfo(h,g);s.push({pattern:h,score:g,matchType:"vector",similarity:g,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:i*2}),l=new Set(s.map(o=>o.pattern.id));for(let o of c){if(l.has(o.id)||!this.matchesFilters(o,t))continue;let u=this.calculateReuseInfo(o,o.confidence);s.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,i*2),l=new Set(s.map(o=>o.pattern.id));for(let o of c){if(l.has(o.id))continue;let u=await this.get(o.id);if(u&&this.matchesFilters(u,t)){let h=this.calculateReuseInfo(u,o.ftsScore);s.push({pattern:u,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch{}s.sort((c,l)=>l.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,v(s.slice(0,i))}async recordUsage(e,t){if(!this.sqliteStore)return P(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t),v(void 0)}catch(r){return P(new Error(`recordUsage failed: ${y(r)}`))}}async promote(e){if(!this.sqliteStore)return P(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),v(void 0)}catch(t){return P(new Error(`promote failed: ${y(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,y(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return P(new Error(`SQLite delete failed: ${y(t)}`))}return v(void 0)}async getStats(){let e=this.adapter?.status(),t=e?.totalVectors??0;if(t===0&&this.sqliteStore)try{t=this.sqliteStore.getStats().totalPatterns}catch{}return{totalPatterns:t,byTier:{shortTerm:0,longTerm:0},byDomain:{},byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=j&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",y(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,i=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:i,estimatedTokenSavings:i?500:0,reuseConfidence:i?t*e.successRate:0}}};Ve();Re();F();function rt(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 nt(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=rt(n,e.field);return nt(t,e.operator,e.value)}default:return!0}}function Ce(n,e){return e?n.filter(t=>G(t,e)):n}F();F();var Fe=1e4,Ie=2166136261;function Oe(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var ae=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;ae[n]=e}var De="0123456789abcdef";function it(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=De[i>>4]+De[i&15]}return t}function st(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 at(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,l=1<<a;for(let o=0;o<n.length;o++)n[o][i]&l&&c++;c>=r&&(s|=l)}t[i]=s}return t}function ot(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let s=0;s<n.length;s++)r+=ae[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function ct(n,e,t){return 1-ot(n,e,t)}var ie=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Fe,this.baseSeed=e?.seed??Ie,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=Oe(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=st(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 at([r,i])}similarity(e,t){return ct(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 l=0;l<c;l++)t[i++]=a>>>l*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},se=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Fe,this.baseSeed=e?.seed??Ie,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=Oe(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:it(i)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let i=0;i<e.length;i++)r+=ae[e[i]^t[i]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),i=new ne(e),s=0;for(;s<t;){let c=i.next(),l=t-s,o=l<4?l:4;for(let u=0;u<o;u++)r[s++]=c>>>u*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function _e(n){return new se(n)}function Ne(n){return Q()?new ie(n):null}var $=Ye(Qe(),1),Dt=`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.8");process.exit(0)}
2
+ import{a as ne}from"./chunk-P2H5ARHM.js";import{d as B,e as j,f as re,g as W}from"./chunk-UGJNR52C.js";import{c as Ze,d as et}from"./chunk-WJDOOT2M.js";import{a as Ae,d as xe,f as Ve}from"./chunk-3WOQMFTD.js";import{b as v,c as P}from"./chunk-R2LWLZ3Y.js";import{a as y,b as Te,c as Re}from"./chunk-PG7CZ6Q4.js";import{f as C}from"./chunk-IP2Z4Z6X.js";import{B as Q,D as H,G as te,P as M,S as F,b as D}from"./chunk-TZMKO6PC.js";import{a as Ee,d as J,f as Ye,g as Ke}from"./chunk-E4D36LGH.js";var Y=J(S=>{var lt=S&&S.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(S,"__esModule",{value:!0});var ut=Object.prototype.hasOwnProperty;function le(n,e){return ut.call(n,e)}S.hasOwnProperty=le;function Me(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var i in n)le(n,i)&&r.push(i);return r}S._objectKeys=Me;function ht(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}S._deepClone=ht;function dt(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}S.isInteger=dt;function oe(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}S.escapePathComponent=oe;function ft(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}S.unescapePathComponent=ft;function ue(n,e){var t;for(var r in n)if(le(n,r)){if(n[r]===e)return oe(r)+"/";if(typeof n[r]=="object"&&(t=ue(n[r],e),t!=""))return oe(r)+"/"+t}return""}S._getPathRecursive=ue;function mt(n,e){if(n===e)return"/";var t=ue(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}S.getPath=mt;function ce(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(ce(n[e]))return!0}else if(typeof n=="object"){for(var r=Me(n),i=r.length,s=0;s<i;s++)if(ce(n[r[s]]))return!0}}return!1}S.hasUndefined=ce;function He(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){lt(e,n);function e(t,r,i,s,a){var c=this.constructor,l=n.call(this,He(t,{name:r,index:i,operation:s,tree:a}))||this;return l.name=r,l.index=i,l.operation=s,l.tree=a,Object.setPrototypeOf(l,c.prototype),l.message=He(t,{name:r,index:i,operation:s,tree:a}),l}return e})(Error);S.PatchError=pt});var he=J(p=>{Object.defineProperty(p,"__esModule",{value:!0});var b=Y();p.JsonPatchError=b.PatchError;p.deepClone=b._deepClone;var L={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=K(t,this.path);r&&(r=b._deepClone(r));var i=I(t,{op:"remove",path:this.from}).removed;return I(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=K(t,this.from);return I(t,{op:"add",path:this.path,value:b._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:q(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},gt={add:function(n,e,t){return b.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:L.move,copy:L.copy,test:L.test,_get:L._get};function K(n,e){if(e=="")return n;var t={op:"_get",path:e};return I(n,t),t.value}p.getValueByPointer=K;function I(n,e,t,r,i,s){if(t===void 0&&(t=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),s===void 0&&(s=0),t&&(typeof t=="function"?t(e,0,n,e.path):V(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=K(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=q(n,e.value),a.test===!1)throw new p.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new p.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=b._deepClone(n));var c=e.path||"",l=c.split("/"),o=n,u=1,h=l.length,f=void 0,d=void 0,m=void 0;for(typeof t=="function"?m=t:m=V;;){if(d=l[u],d&&d.indexOf("~")!=-1&&(d=b.unescapePathComponent(d)),i&&(d=="__proto__"||d=="prototype"&&u>0&&l[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&f===void 0&&(o[d]===void 0?f=l.slice(0,u).join("/"):u==h-1&&(f=e.path),f!==void 0&&m(e,0,n,f)),u++,Array.isArray(o)){if(d==="-")d=o.length;else{if(t&&!b.isInteger(d))throw new p.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);b.isInteger(d)&&(d=~~d)}if(u>=h){if(t&&e.op==="add"&&d>o.length)throw new p.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var a=gt[e.op].call(e,o,d,n);if(a.test===!1)throw new p.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(u>=h){var a=L[e.op].call(e,o,d,n);if(a.test===!1)throw new p.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[d],t&&u<h&&(!o||typeof o!="object"))throw new p.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}p.applyOperation=I;function Le(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new p.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=b._deepClone(n));for(var s=new Array(e.length),a=0,c=e.length;a<c;a++)s[a]=I(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}p.applyPatch=Le;function yt(n,e,t){var r=I(n,e);if(r.test===!1)throw new p.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}p.applyReducer=yt;function V(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new p.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new p.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new p.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new p.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new p.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&b.hasUndefined(n.value))throw new p.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new p.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new p.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a={op:"_get",path:n.from,value:void 0},c=ke([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new p.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new p.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}p.validator=V;function ke(n,e,t){try{if(!Array.isArray(n))throw new p.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Le(b._deepClone(e),b._deepClone(n),t||!0);else{t=t||V;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof p.JsonPatchError)return i;throw i}}p.validate=ke;function q(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(!q(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],!q(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}p._areEquals=q});var Ue=J(k=>{Object.defineProperty(k,"__esModule",{value:!0});var w=Y(),vt=he(),fe=new WeakMap,Pt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),wt=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function St(n){return fe.get(n)}function bt(n,e){return n.observers.get(e)}function Et(n,e){n.observers.delete(e.callback)}function Tt(n,e){e.unobserve()}k.unobserve=Tt;function Rt(n,e){var t=[],r,i=St(n);if(!i)i=new Pt(n),fe.set(n,i);else{var s=bt(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=w._deepClone(n),e){r.callback=e,r.next=null;var a=function(){de(r)},c=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return r.patches=t,r.object=n,r.unobserve=function(){de(r),clearTimeout(r.next),Et(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 wt(e,r)),r}k.observe=Rt;function de(n,e){e===void 0&&(e=!1);var t=fe.get(n.object);me(t.value,n.object,n.patches,"",e),n.patches.length&&vt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=de;function me(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=w._objectKeys(e),a=w._objectKeys(n),c=!1,l=!1,o=a.length-1;o>=0;o--){var u=a[o],h=n[u];if(w.hasOwnProperty(e,u)&&!(e[u]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var f=e[u];typeof h=="object"&&h!=null&&typeof f=="object"&&f!=null&&Array.isArray(h)===Array.isArray(f)?me(h,f,t,r+"/"+w.escapePathComponent(u),i):h!==f&&(c=!0,i&&t.push({op:"test",path:r+"/"+w.escapePathComponent(u),value:w._deepClone(h)}),t.push({op:"replace",path:r+"/"+w.escapePathComponent(u),value:w._deepClone(f)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+w.escapePathComponent(u),value:w._deepClone(h)}),t.push({op:"remove",path:r+"/"+w.escapePathComponent(u)}),l=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!l&&s.length==a.length))for(var o=0;o<s.length;o++){var u=s[o];!w.hasOwnProperty(n,u)&&e[u]!==void 0&&t.push({op:"add",path:r+"/"+w.escapePathComponent(u),value:w._deepClone(e[u])})}}}function At(n,e,t){t===void 0&&(t=!1);var r=[];return me(n,e,r,"",t),r}k.compare=At});var Qe=J(O=>{var xt=he();Object.assign(O,xt);var Ct=Ue();Object.assign(O,Ct);var Z=Y();O.JsonPatchError=Z.PatchError;O.deepClone=Z._deepClone;O.escapePathComponent=Z.escapePathComponent;O.unescapePathComponent=Z.unescapePathComponent});Re();var z=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}config;rvfPath;skipCloseOnDispose;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=y(e),console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-TE2ZRHKA.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}}}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 P(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return P(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{this.sqliteStore.storePattern(e,e.embedding)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,y(r))}if(e.embedding&&this.adapter)try{let r=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding);this.adapter.ingest([{id:e.id,vector:r}])}catch(r){console.warn(`[RvfPatternStore] RVF ingest failed for ${e.id}:`,y(r))}return v(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:B({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?v(i):P(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),l=this.adapter.search(c,i*2);for(let o of l){let u=await this.get(o.id);if(u&&this.matchesFilters(u,t)){let h=this.calculateReuseInfo(u,o.score);s.push({pattern:u,score:o.score,matchType:"vector",similarity:o.score,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",y(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let c=this.sqliteStore.getPatterns({limit:i*4}),l=e,o=Math.sqrt(l.reduce((u,h)=>u+h*h,0));if(o>0)for(let u of c){if(!this.matchesFilters(u,t))continue;let h=this.sqliteStore.getPattern(u.id),f=h?.embedding;if(!f||f.length!==l.length)continue;let d=0,m=0;for(let T=0;T<l.length;T++)d+=l[T]*f[T],m+=f[T]*f[T];if(m=Math.sqrt(m),m===0)continue;let g=d/(o*m),E=this.calculateReuseInfo(h,g);s.push({pattern:h,score:g,matchType:"vector",similarity:g,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:i*2}),l=new Set(s.map(o=>o.pattern.id));for(let o of c){if(l.has(o.id)||!this.matchesFilters(o,t))continue;let u=this.calculateReuseInfo(o,o.confidence);s.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,i*2),l=new Set(s.map(o=>o.pattern.id));for(let o of c){if(l.has(o.id))continue;let u=await this.get(o.id);if(u&&this.matchesFilters(u,t)){let h=this.calculateReuseInfo(u,o.ftsScore);s.push({pattern:u,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch{}s.sort((c,l)=>l.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,v(s.slice(0,i))}async recordUsage(e,t){if(!this.sqliteStore)return P(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t),v(void 0)}catch(r){return P(new Error(`recordUsage failed: ${y(r)}`))}}async promote(e){if(!this.sqliteStore)return P(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),v(void 0)}catch(t){return P(new Error(`promote failed: ${y(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,y(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return P(new Error(`SQLite delete failed: ${y(t)}`))}return v(void 0)}async getStats(){let e=this.adapter?.status(),t=e?.totalVectors??0;if(t===0&&this.sqliteStore)try{t=this.sqliteStore.getStats().totalPatterns}catch{}return{totalPatterns:t,byTier:{shortTerm:0,longTerm:0},byDomain:{},byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=j&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",y(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,i=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:i,estimatedTokenSavings:i?500:0,reuseConfidence:i?t*e.successRate:0}}};Ve();Re();F();function rt(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 nt(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=rt(n,e.field);return nt(t,e.operator,e.value)}default:return!0}}function Ce(n,e){return e?n.filter(t=>G(t,e)):n}F();F();var Fe=1e4,Ie=2166136261;function Oe(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var ae=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;ae[n]=e}var De="0123456789abcdef";function it(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=De[i>>4]+De[i&15]}return t}function st(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 at(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,l=1<<a;for(let o=0;o<n.length;o++)n[o][i]&l&&c++;c>=r&&(s|=l)}t[i]=s}return t}function ot(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let s=0;s<n.length;s++)r+=ae[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function ct(n,e,t){return 1-ot(n,e,t)}var ie=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Fe,this.baseSeed=e?.seed??Ie,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=Oe(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=st(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 at([r,i])}similarity(e,t){return ct(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 l=0;l<c;l++)t[i++]=a>>>l*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},se=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Fe,this.baseSeed=e?.seed??Ie,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=Oe(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:it(i)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let i=0;i<e.length;i++)r+=ae[e[i]^t[i]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),i=new ne(e),s=0;for(;s<t;){let c=i.next(),l=t-s,o=l<4?l:4;for(let u=0;u<o;u++)r[s++]=c>>>u*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function _e(n){return new se(n)}function Ne(n){return Q()?new ie(n):null}var $=Ye(Qe(),1),Dt=`
4
4
  CREATE TABLE IF NOT EXISTS pattern_deltas (
5
5
  id TEXT PRIMARY KEY,
6
6
  pattern_id TEXT NOT NULL,
@@ -46,7 +46,7 @@ import{a as ne}from"./chunk-APPVAGD5.js";import{d as B,e as j,f as re,g as W}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 It={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},pe=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...It,...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),l={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(l),this.buffer.push(l),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:l.timestamp}),this.enforceRetention(e),l}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],l=a.version+1;for(let o of r)if(!(o.version<l)){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),l=a.findIndex(h=>h.deltaType==="genesis");l>=0&&(c.unshift(a[l]),a.splice(l,1)),this.history.set(e,c);let o=c[0]?.version??0,u=this.snapshots.get(e);return u&&this.snapshots.set(e,u.filter(h=>h.version===0||h.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,c=s<t.length?t[s]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:s,oldValue:a,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function $e(n){return H()?new pe(n):null}F();var Ot=128,_t=8,Nt=1e4,ge=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Ot,this.beta=e?.beta??_t,this.maxPatterns=e?.maxPatterns??Nt,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 u=0;u<this.patterns.length;u++)r[u]=this.beta*this.dotProduct(this.patterns[u].pattern,t);let i=this.softmax(r),s=0,a=i[0];for(let u=1;u<i.length;u++)i[u]>a&&(a=i[u],s=u);let c=this.patterns[s],l=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:l,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)),l=this.dotProduct(t,t);return-c+.5*l}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 Je(n){return new ge(n)}F();var Ht={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,Be=1-_;function Mt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function R(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function Lt(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 A=class n{static poincareDistance(e,t){let r=R(Lt(e,t)),i=Math.max(_,1-R(e)),s=Math.max(_,1-R(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=Mt(e,t),i=R(e),s=R(t),a=Math.max(_,1+2*r+i*s),c=1+2*r+s,l=1-i,o=new Float32Array(e.length);for(let u=0;u<e.length;u++)o[u]=(c*e[u]+l*t[u])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(_,1-R(e)),i=Math.sqrt(R(t));if(i<_)return new Float32Array(e);let s=Math.tanh(r*i/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=s/i*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(R(e));if(t<=Be)return new Float32Array(e);let r=Be/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return i}static euclideanToHyperbolic(e){let t=Math.sqrt(R(e));if(t<_)return new Float32Array(e.length);let r=Math.tanh(t)/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return n.project(i)}},ye=class{config;points=new Map;constructor(e){if(this.config={...Ht,...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:A.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=A.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:A.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 l of e)if(s.set(l.id,l),!l.parentId)a.push(l.id);else{let o=i.get(l.parentId);o||(o=[],i.set(l.parentId,o)),o.push(l.id)}let c=a.map((l,o)=>({id:l,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:l,depth:o,angOff:u,angSpan:h}=c.shift(),f=Math.tanh(.3*(o+.1)),d=u+h/2,m=new Float32Array(r);m[0]=f*Math.cos(d),m[1]=f*Math.sin(d);let g=s.get(l);if(g&&g.features.length>0){let N=f*.1;for(let x=2;x<r&&x-2<g.features.length;x++)m[x]=g.features[x-2]*N}let E=A.project(m);t.set(l,E),this.points.set(l,{id:l,coordinates:E,metadata:{depth:o,parentId:g?.parentId}});let T=i.get(l)??[];for(let N=0;N<T.length;N++){let x=h/Math.max(1,T.length);c.push({id:T[N],depth:o+1,angOff:u+N*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function je(n){return kt()?new ye(n):null}function kt(){return D().useHyperbolicHnsw}F();var ve=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!M())return!1;try{return this.index=je(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=A.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=A.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 We(n){return new ve(n)}var Pe=null;function Xe(){return Pe||(Pe=_e({dimensions:1e4})),Pe}var we;function Ut(){return we===void 0&&(we=Ne()),we}var U=null,Se=0;function Ge(n){return(!U||Se!==n)&&(U=Je({dimension:n,maxPatterns:1e4}),Se=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}},be=class{constructor(e,t={}){this.memory=e;this.config={...X,...t}}config;initialized=!1;cleanupTimer;sqliteStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,H()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new ee(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){return this.hnswIndex!==null?this.hnswIndex:this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-CC5YS47X.js"),{HnswAdapter:c}=await import("./hnsw-adapter-UPX4AXOQ.js"),l=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(l),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)");return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-CSI2EXXR.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));if(await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),this.sqliteStore)try{let a=this.sqliteStore.getAllEmbeddings(),c=this.config.hnsw.maxElements,l=0;for(let{patternId:o,embedding:u}of a){if(l>=c)break;if(!u||u.length!==this.config.embeddingDimension)continue;let h=this.patternCache.get(o);if(h)try{await this.hnswIndex.insert(o,u,{filePath:h.patternType,lineCoverage:h.confidence*100,branchCoverage:h.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-h.confidence,lastUpdated:Date.now(),totalLines:0}),l++}catch{}}l>0&&console.log(`[PatternStore] Loaded ${l} embeddings from SQLite into HNSW`)}catch(a){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",y(a))}console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",y(e)),this.hnswIndex=null,this.hnswAvailable=!1}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=$e()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",y(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=W(e);if(!t.valid)return P(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return P(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let i=this.patternCache.get(e.id)??null;if(this.indexPattern(e),this.sqliteStore)try{this.sqliteStore.storePattern(e,e.embedding)}catch(s){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,y(s))}if(e.embedding){let s=await this.ensureHNSW();if(s)try{await s.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(a){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,a)}}if(Q())try{let a=Xe().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,a.vector)}catch(s){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,y(s))}try{let s=Ut();if(s){let a=[e.patternType,e.qeDomain];e.context?.tags&&a.push(...e.context.tags),e.name&&a.push(e.name);let c=s.fingerprintPattern(a);this.hdcTokenCache.set(e.id,c)}}catch(s){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,y(s))}if(te()&&e.embedding)try{Ge(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(s){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,y(s))}if(H()&&this.deltaTracker)try{let s={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,s)}catch(s){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,y(s))}if(e.embedding)try{let s=this.getVectorDeltaTracker();s&&(i?.embedding?s.recordDelta(e.id,i.embedding,e.embedding):s.getVersion(e.id)<0&&s.recordGenesis(e.id,e.embedding))}catch(s){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,y(s))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return v(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?v(i):P(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=Ge(e.length);if(h.getPatternCount()>0){let f=h.recall(new Float32Array(e));if(f&&f.similarity>.98){let d=f.metadata.id,m=await this.get(d);if(m&&this.matchesFilters(m,t)){let g=this.calculateReuseInfo(m,f.similarity);s.push({pattern:m,score:f.similarity,matchType:"vector",similarity:f.similarity,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}catch(h){console.debug("[PatternStore] Hopfield recall failed:",y(h))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let h=await this.ensureHNSW();if(h){let f=await h.search(e,i*2);for(let d of f){let m=await this.get(d.key);if(m&&this.matchesFilters(m,t)){let g=this.calculateReuseInfo(m,d.score);s.push({pattern:m,score:d.score,matchType:"vector",similarity:d.score,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let h=this.sqliteStore.searchFTS(e,i*2);if(h.length>0){let f=new Map(h.map(m=>[m.id,m.ftsScore])),d=new Set(s.map(m=>m.pattern.id));for(let m of s){let g=f.get(m.pattern.id);g!==void 0&&(m.score=.75*m.score+.25*g)}for(let m of h){if(d.has(m.id))continue;let g=await this.get(m.id);if(g&&this.matchesFilters(g,t)){let E=this.calculateReuseInfo(g,m.ftsScore);s.push({pattern:g,score:.5*m.ftsScore,matchType:"exact",similarity:m.ftsScore,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}}}catch{}if(typeof e=="string"||s.length<i){let h=await this.searchByText(typeof e=="string"?e:"",t,i-s.length),f=new Set(s.map(d=>d.pattern.id));for(let d of h)f.has(d.pattern.id)||s.push(d)}let a=720*60*60*1e3,c=Date.now();for(let h of s){let f=h.pattern.lastUsedAt?.getTime()??h.pattern.createdAt.getTime(),d=c-f,m=Math.pow(.5,d/a),g=h.pattern.usageCount>0?m:.5;h.score=h.score*(.7+.3*g)}s.sort((h,f)=>f.score-h.score);let l=s;t.filter&&(l=Ce(s,t.filter));let o=l.slice(0,i),u=performance.now()-r;return this.recordSearchLatency(u),v(o)}catch(a){return P(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 l=Xe(),o=l.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),u=c.filter(d=>this.hdcCache.has(d)).map(d=>({id:d,similarity:l.similarity(o.vector,this.hdcCache.get(d))}));u.sort((d,m)=>m.similarity-d.similarity);let h=u.map(d=>d.id),f=c.filter(d=>!this.hdcCache.has(d));c=[...h,...f]}catch{}for(let l of c){if(i.length>=r)break;let o=this.patternCache.get(l);if(!o||!this.matchesFilters(o,t))continue;let u=0;if(s){let h=o.name.toLowerCase(),f=o.description.toLowerCase();h.includes(s)&&(u+=.5),f.includes(s)&&(s.length/f.length>.3?u+=.5:u+=.3);for(let d of o.context.tags)if(d.toLowerCase().includes(s)){u+=.2;break}u=Math.min(u,1)}else u=o.qualityScore;if(u>0||!s){let h=this.calculateReuseInfo(o,u);i.push({pattern:o,score:u||o.qualityScore,matchType:s?"exact":"context",similarity:u||o.qualityScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}return i}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,i=t>=r.minSimilarityForReuse,s=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),l=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&l,u=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,h=t,f=e.successRate,d=Math.min(e.reuseCount/10,1),m=o?h*.4+f*.4+d*.2:0;return{canReuse:o,estimatedTokenSavings:u,reuseConfidence:m}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t){let r=await this.get(e);if(!r)return P(new Error(`Pattern not found: ${e}`));let i=new Date,s=r.usageCount+1,a=r.successfulUses+(t?1:0),c=a/s,l=t?.02:-.01,o=Math.max(.1,Math.min(1,r.confidence+l)),u=B({confidence:o,usageCount:s,successRate:c}),h={...r,usageCount:s,successfulUses:a,successRate:c,confidence:o,qualityScore:u,lastUsedAt:i};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t)}catch(m){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,y(m))}if(H()&&this.deltaTracker)try{let m={id:r.id,name:r.name,confidence:r.confidence,qualityScore:r.qualityScore,usageCount:r.usageCount,successRate:r.successRate,tier:r.tier},g={id:h.id,name:h.name,confidence:h.confidence,qualityScore:h.qualityScore,usageCount:h.usageCount,successRate:h.successRate,tier:h.tier};this.deltaTracker.recordDelta(e,m,g,{success:t})}catch(m){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,y(m))}let f=re(h);return f.meetsUsageCriteria&&f.meetsQualityCriteria&&f.meetsCoherenceCriteria&&h.tier==="short-term"?await this.promote(e):this.patternCache.set(e,h),v(void 0)}async promote(e){let t=await this.get(e);if(!t)return P(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return v(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(i){console.debug("[PatternStore] SQLite promotion error:",i instanceof Error?i.message:i)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),v(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return P(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return v(void 0)}async getStats(){let e={},t={};for(let[l,o]of this.domainIndex)e[l]=o.size;for(let[l,o]of this.typeIndex)t[l]=o.size;let r=0,i=0,s=0,a=0;for(let l of this.patternCache.values())r+=l.confidence,i+=l.qualityScore,s+=l.successRate,a++;let c=this.hnswIndex!==null?await this.hnswIndex.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:c.nativeHNSW,vectorCount:c.vectorCount,indexSizeBytes:c.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 l=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-l,u=o>10080*60*1e3,h=s.qualityScore<.2,f=s.usageCount===0&&o>1440*60*1e3;(u&&h||f)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let c=this.patternCache.get(a);c&&r.push(c)}r.sort((a,c)=>a.qualityScore-c.qualityScore);let i=Math.ceil(r.length*.1),s=0;for(let a of r){if(s>=i)break;a.tier==="short-term"&&(await this.delete(a.id),s++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),U&&(U.clear(),U=null,Se=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=We({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(i){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,i instanceof Error?i.message:i)}}async searchHyperbolic(e,t=10){if(!M()||!this.hyperbolicIndex)return v([]);try{let r=this.hyperbolicIndex.search(e,t),i=[];for(let s of r){let a=await this.get(s.patternId);if(!a)continue;let c=Math.exp(-s.distance),l=this.calculateReuseInfo(a,c);i.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}return v(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),v([])}}};function Lr(n,e){try{if(D().useRVFPatternStore&&xe()){let{existsSync:r}=Ee("fs"),i=".agentic-qe/patterns.rvf",s=Ee("path").dirname(i);if(r(s)){let a={...X,...e},c=!1;try{let{getSharedRvfAdapter:l}=(et(),Ke(Ze)),o=l(s,a.embeddingDimension);if(o){c=!0;let u=new z(()=>o,{rvfPath:i,base:a,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),u}}catch{}if(!c){let l=new z((o,u)=>Ae(o,u),{rvfPath:i,base:a});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 be(n,e)}export{Lr as a};
49
+ )`).run(e,e,s)}}};F();var It={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},pe=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...It,...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),l={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(l),this.buffer.push(l),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:l.timestamp}),this.enforceRetention(e),l}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],l=a.version+1;for(let o of r)if(!(o.version<l)){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),l=a.findIndex(h=>h.deltaType==="genesis");l>=0&&(c.unshift(a[l]),a.splice(l,1)),this.history.set(e,c);let o=c[0]?.version??0,u=this.snapshots.get(e);return u&&this.snapshots.set(e,u.filter(h=>h.version===0||h.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,c=s<t.length?t[s]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:s,oldValue:a,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function $e(n){return H()?new pe(n):null}F();var Ot=128,_t=8,Nt=1e4,ge=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Ot,this.beta=e?.beta??_t,this.maxPatterns=e?.maxPatterns??Nt,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 u=0;u<this.patterns.length;u++)r[u]=this.beta*this.dotProduct(this.patterns[u].pattern,t);let i=this.softmax(r),s=0,a=i[0];for(let u=1;u<i.length;u++)i[u]>a&&(a=i[u],s=u);let c=this.patterns[s],l=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:l,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)),l=this.dotProduct(t,t);return-c+.5*l}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 Je(n){return new ge(n)}F();var Ht={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,Be=1-_;function Mt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function R(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function Lt(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 A=class n{static poincareDistance(e,t){let r=R(Lt(e,t)),i=Math.max(_,1-R(e)),s=Math.max(_,1-R(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=Mt(e,t),i=R(e),s=R(t),a=Math.max(_,1+2*r+i*s),c=1+2*r+s,l=1-i,o=new Float32Array(e.length);for(let u=0;u<e.length;u++)o[u]=(c*e[u]+l*t[u])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(_,1-R(e)),i=Math.sqrt(R(t));if(i<_)return new Float32Array(e);let s=Math.tanh(r*i/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=s/i*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(R(e));if(t<=Be)return new Float32Array(e);let r=Be/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return i}static euclideanToHyperbolic(e){let t=Math.sqrt(R(e));if(t<_)return new Float32Array(e.length);let r=Math.tanh(t)/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return n.project(i)}},ye=class{config;points=new Map;constructor(e){if(this.config={...Ht,...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:A.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=A.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:A.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 l of e)if(s.set(l.id,l),!l.parentId)a.push(l.id);else{let o=i.get(l.parentId);o||(o=[],i.set(l.parentId,o)),o.push(l.id)}let c=a.map((l,o)=>({id:l,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:l,depth:o,angOff:u,angSpan:h}=c.shift(),f=Math.tanh(.3*(o+.1)),d=u+h/2,m=new Float32Array(r);m[0]=f*Math.cos(d),m[1]=f*Math.sin(d);let g=s.get(l);if(g&&g.features.length>0){let N=f*.1;for(let x=2;x<r&&x-2<g.features.length;x++)m[x]=g.features[x-2]*N}let E=A.project(m);t.set(l,E),this.points.set(l,{id:l,coordinates:E,metadata:{depth:o,parentId:g?.parentId}});let T=i.get(l)??[];for(let N=0;N<T.length;N++){let x=h/Math.max(1,T.length);c.push({id:T[N],depth:o+1,angOff:u+N*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function je(n){return kt()?new ye(n):null}function kt(){return D().useHyperbolicHnsw}F();var ve=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!M())return!1;try{return this.index=je(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=A.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=A.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 We(n){return new ve(n)}var Pe=null;function Xe(){return Pe||(Pe=_e({dimensions:1e4})),Pe}var we;function Ut(){return we===void 0&&(we=Ne()),we}var U=null,Se=0;function Ge(n){return(!U||Se!==n)&&(U=Je({dimension:n,maxPatterns:1e4}),Se=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}},be=class{constructor(e,t={}){this.memory=e;this.config={...X,...t}}config;initialized=!1;cleanupTimer;sqliteStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,H()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new ee(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){return this.hnswIndex!==null?this.hnswIndex:this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-UH6RWE74.js"),{HnswAdapter:c}=await import("./hnsw-adapter-BMXTVGZB.js"),l=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(l),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)");return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-YX6XLICT.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));if(await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),this.sqliteStore)try{let a=this.sqliteStore.getAllEmbeddings(),c=this.config.hnsw.maxElements,l=0;for(let{patternId:o,embedding:u}of a){if(l>=c)break;if(!u||u.length!==this.config.embeddingDimension)continue;let h=this.patternCache.get(o);if(h)try{await this.hnswIndex.insert(o,u,{filePath:h.patternType,lineCoverage:h.confidence*100,branchCoverage:h.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-h.confidence,lastUpdated:Date.now(),totalLines:0}),l++}catch{}}l>0&&console.log(`[PatternStore] Loaded ${l} embeddings from SQLite into HNSW`)}catch(a){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",y(a))}console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",y(e)),this.hnswIndex=null,this.hnswAvailable=!1}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=$e()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",y(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=W(e);if(!t.valid)return P(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return P(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let i=this.patternCache.get(e.id)??null;if(this.indexPattern(e),this.sqliteStore)try{this.sqliteStore.storePattern(e,e.embedding)}catch(s){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,y(s))}if(e.embedding){let s=await this.ensureHNSW();if(s)try{await s.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(a){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,a)}}if(Q())try{let a=Xe().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,a.vector)}catch(s){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,y(s))}try{let s=Ut();if(s){let a=[e.patternType,e.qeDomain];e.context?.tags&&a.push(...e.context.tags),e.name&&a.push(e.name);let c=s.fingerprintPattern(a);this.hdcTokenCache.set(e.id,c)}}catch(s){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,y(s))}if(te()&&e.embedding)try{Ge(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(s){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,y(s))}if(H()&&this.deltaTracker)try{let s={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,s)}catch(s){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,y(s))}if(e.embedding)try{let s=this.getVectorDeltaTracker();s&&(i?.embedding?s.recordDelta(e.id,i.embedding,e.embedding):s.getVersion(e.id)<0&&s.recordGenesis(e.id,e.embedding))}catch(s){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,y(s))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return v(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?v(i):P(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=Ge(e.length);if(h.getPatternCount()>0){let f=h.recall(new Float32Array(e));if(f&&f.similarity>.98){let d=f.metadata.id,m=await this.get(d);if(m&&this.matchesFilters(m,t)){let g=this.calculateReuseInfo(m,f.similarity);s.push({pattern:m,score:f.similarity,matchType:"vector",similarity:f.similarity,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}catch(h){console.debug("[PatternStore] Hopfield recall failed:",y(h))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let h=await this.ensureHNSW();if(h){let f=await h.search(e,i*2);for(let d of f){let m=await this.get(d.key);if(m&&this.matchesFilters(m,t)){let g=this.calculateReuseInfo(m,d.score);s.push({pattern:m,score:d.score,matchType:"vector",similarity:d.score,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let h=this.sqliteStore.searchFTS(e,i*2);if(h.length>0){let f=new Map(h.map(m=>[m.id,m.ftsScore])),d=new Set(s.map(m=>m.pattern.id));for(let m of s){let g=f.get(m.pattern.id);g!==void 0&&(m.score=.75*m.score+.25*g)}for(let m of h){if(d.has(m.id))continue;let g=await this.get(m.id);if(g&&this.matchesFilters(g,t)){let E=this.calculateReuseInfo(g,m.ftsScore);s.push({pattern:g,score:.5*m.ftsScore,matchType:"exact",similarity:m.ftsScore,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}}}catch{}if(typeof e=="string"||s.length<i){let h=await this.searchByText(typeof e=="string"?e:"",t,i-s.length),f=new Set(s.map(d=>d.pattern.id));for(let d of h)f.has(d.pattern.id)||s.push(d)}let a=720*60*60*1e3,c=Date.now();for(let h of s){let f=h.pattern.lastUsedAt?.getTime()??h.pattern.createdAt.getTime(),d=c-f,m=Math.pow(.5,d/a),g=h.pattern.usageCount>0?m:.5;h.score=h.score*(.7+.3*g)}s.sort((h,f)=>f.score-h.score);let l=s;t.filter&&(l=Ce(s,t.filter));let o=l.slice(0,i),u=performance.now()-r;return this.recordSearchLatency(u),v(o)}catch(a){return P(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 l=Xe(),o=l.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),u=c.filter(d=>this.hdcCache.has(d)).map(d=>({id:d,similarity:l.similarity(o.vector,this.hdcCache.get(d))}));u.sort((d,m)=>m.similarity-d.similarity);let h=u.map(d=>d.id),f=c.filter(d=>!this.hdcCache.has(d));c=[...h,...f]}catch{}for(let l of c){if(i.length>=r)break;let o=this.patternCache.get(l);if(!o||!this.matchesFilters(o,t))continue;let u=0;if(s){let h=o.name.toLowerCase(),f=o.description.toLowerCase();h.includes(s)&&(u+=.5),f.includes(s)&&(s.length/f.length>.3?u+=.5:u+=.3);for(let d of o.context.tags)if(d.toLowerCase().includes(s)){u+=.2;break}u=Math.min(u,1)}else u=o.qualityScore;if(u>0||!s){let h=this.calculateReuseInfo(o,u);i.push({pattern:o,score:u||o.qualityScore,matchType:s?"exact":"context",similarity:u||o.qualityScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}return i}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,i=t>=r.minSimilarityForReuse,s=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),l=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&l,u=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,h=t,f=e.successRate,d=Math.min(e.reuseCount/10,1),m=o?h*.4+f*.4+d*.2:0;return{canReuse:o,estimatedTokenSavings:u,reuseConfidence:m}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t){let r=await this.get(e);if(!r)return P(new Error(`Pattern not found: ${e}`));let i=new Date,s=r.usageCount+1,a=r.successfulUses+(t?1:0),c=a/s,l=t?.02:-.01,o=Math.max(.1,Math.min(1,r.confidence+l)),u=B({confidence:o,usageCount:s,successRate:c}),h={...r,usageCount:s,successfulUses:a,successRate:c,confidence:o,qualityScore:u,lastUsedAt:i};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t)}catch(m){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,y(m))}if(H()&&this.deltaTracker)try{let m={id:r.id,name:r.name,confidence:r.confidence,qualityScore:r.qualityScore,usageCount:r.usageCount,successRate:r.successRate,tier:r.tier},g={id:h.id,name:h.name,confidence:h.confidence,qualityScore:h.qualityScore,usageCount:h.usageCount,successRate:h.successRate,tier:h.tier};this.deltaTracker.recordDelta(e,m,g,{success:t})}catch(m){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,y(m))}let f=re(h);return f.meetsUsageCriteria&&f.meetsQualityCriteria&&f.meetsCoherenceCriteria&&h.tier==="short-term"?await this.promote(e):this.patternCache.set(e,h),v(void 0)}async promote(e){let t=await this.get(e);if(!t)return P(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return v(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(i){console.debug("[PatternStore] SQLite promotion error:",i instanceof Error?i.message:i)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),v(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return P(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return v(void 0)}async getStats(){let e={},t={};for(let[l,o]of this.domainIndex)e[l]=o.size;for(let[l,o]of this.typeIndex)t[l]=o.size;let r=0,i=0,s=0,a=0;for(let l of this.patternCache.values())r+=l.confidence,i+=l.qualityScore,s+=l.successRate,a++;let c=this.hnswIndex!==null?await this.hnswIndex.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:c.nativeHNSW,vectorCount:c.vectorCount,indexSizeBytes:c.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 l=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-l,u=o>10080*60*1e3,h=s.qualityScore<.2,f=s.usageCount===0&&o>1440*60*1e3;(u&&h||f)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let c=this.patternCache.get(a);c&&r.push(c)}r.sort((a,c)=>a.qualityScore-c.qualityScore);let i=Math.ceil(r.length*.1),s=0;for(let a of r){if(s>=i)break;a.tier==="short-term"&&(await this.delete(a.id),s++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),U&&(U.clear(),U=null,Se=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=We({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(i){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,i instanceof Error?i.message:i)}}async searchHyperbolic(e,t=10){if(!M()||!this.hyperbolicIndex)return v([]);try{let r=this.hyperbolicIndex.search(e,t),i=[];for(let s of r){let a=await this.get(s.patternId);if(!a)continue;let c=Math.exp(-s.distance),l=this.calculateReuseInfo(a,c);i.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}return v(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),v([])}}};function Lr(n,e){try{if(D().useRVFPatternStore&&xe()){let{existsSync:r}=Ee("fs"),i=".agentic-qe/patterns.rvf",s=Ee("path").dirname(i);if(r(s)){let a={...X,...e},c=!1;try{let{getSharedRvfAdapter:l}=(et(),Ke(Ze)),o=l(s,a.embeddingDimension);if(o){c=!0;let u=new z(()=>o,{rvfPath:i,base:a,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),u}}catch{}if(!c){let l=new z((o,u)=>Ae(o,u),{rvfPath:i,base:a});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 be(n,e)}export{Lr as a};
50
50
  /*! Bundled license information:
51
51
 
52
52
  fast-json-patch/commonjs/helpers.js:
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.7");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.8");process.exit(0)}
2
2
  import{existsSync as c,readFileSync as f}from"fs";import{join as p,dirname as i}from"path";import{fileURLToPath as s}from"url";function u(o,a=10){let t=i(s(o));for(let r=0;r<a;r++){let n=p(t,"package.json");if(c(n))try{if(JSON.parse(f(n,"utf-8")).name==="agentic-qe")return t}catch{}let e=i(t);if(e===t)break;t=e}return null}export{u as a};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.7");process.exit(0)}
2
- import{a as V}from"./chunk-D2C4XNF5.js";import{a as k,b as A,c as W,d as q}from"./chunk-3DXO5CWI.js";import{b as x,f as z,i as j}from"./chunk-7TKZ6LK6.js";import{d as G}from"./chunk-GOG6L2F7.js";import{g as P}from"./chunk-FKJ4XZ6E.js";import{a as M}from"./chunk-N5SLJOBK.js";import{c as E}from"./chunk-6OKXGDT3.js";import{b as T,c as S}from"./chunk-ZSXSUUBS.js";import{a as h,b as L,c as F}from"./chunk-MR7V7QVL.js";import{S as Y,b as B}from"./chunk-WV3R5JFE.js";M();F();var C={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var w=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.8");process.exit(0)}
2
+ import{a as V}from"./chunk-66DCG6RO.js";import{a as k,b as A,c as W,d as q}from"./chunk-ZCKNGICX.js";import{b as x,f as z,i as j}from"./chunk-UGJNR52C.js";import{d as G}from"./chunk-LOANEFGZ.js";import{g as P}from"./chunk-TN72MXLI.js";import{a as M}from"./chunk-OT4JADWW.js";import{c as E}from"./chunk-CG3HIYF4.js";import{b as T,c as S}from"./chunk-R2LWLZ3Y.js";import{a as h,b as L,c as F}from"./chunk-PG7CZ6Q4.js";import{S as Y,b as B}from"./chunk-TZMKO6PC.js";M();F();var C={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var w=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
3
3
  describe('{{methodName}}', () => {
4
4
  it('should {{expectedBehavior}}', {{async}} () => {
5
5
  // Arrange
@@ -311,4 +311,4 @@ On promotion:
311
311
  `).all(),o=this.db.prepare(`
312
312
  INSERT OR IGNORE INTO pattern_citations (source_pattern_id, target_pattern_id, weight, relationship)
313
313
  VALUES (?, ?, 2.0, 'derivation')
314
- `);for(let l of c)o.run(l.source_pattern_id,l.target_pattern_id).changes>0&&e++;return e}getEdgeCount(){return this.ensureSchema(),this.db.prepare("SELECT COUNT(*) as cnt FROM pattern_citations").get().cnt}};var g=E.create("QEReasoningBank"),Q=class{constructor(e,r,t={},a){this.memory=e;this.eventBus=r;this.coherenceService=a;this.config={...C,...t},t.rvfDualWriter&&(this.rvfDualWriter=t.rvfDualWriter),this.patternStore=V(e,{embeddingDimension:this.config.embeddingDimension,...t.patternStore})}config;patternStore;initialized=!1;sqliteStore=null;rvfDualWriter=null;getSqliteStore(){return this.sqliteStore||(this.sqliteStore=G(),this.sqliteStore.initialize().catch(e=>{g.warn("SQLitePatternStore init failed",{error:h(e)})})),this.sqliteStore}setRvfDualWriter(e){this.rvfDualWriter=e}stats={routingRequests:0,totalRoutingConfidence:0,learningOutcomes:0,successfulOutcomes:0};async initialize(){if(!this.initialized){await this.patternStore.initialize();try{let e=this.getSqliteStore();await e.initialize(),this.patternStore.setSqliteStore?.(e)}catch(e){g.warn("Failed to wire SQLitePatternStore into PatternStore",{error:h(e)})}await this.loadPretrainedPatterns(),this.initialized=!0;try{let e="reasoning-bank:cross-domain-seeded";if(!await this.memory.get(e))await this.memory.set(e,!0),await this.seedCrossDomainPatterns();else{let t=await this.patternStore.getStats();g.info("Cross-domain transfer already complete",{totalPatterns:t.totalPatterns})}}catch(e){g.warn("Cross-domain seeding failed (non-fatal)",{error:e})}g.info("Initialized")}}async loadPretrainedPatterns(){let e=await this.patternStore.getStats();if(e.totalPatterns>0){g.info("Found existing patterns",{totalPatterns:e.totalPatterns});return}for(let r of w)try{await this.patternStore.create(r)}catch(t){g.warn("Failed to load pattern",{name:r.name,error:t})}g.info("Loaded foundational patterns",{count:w.length})}async seedCrossDomainPatterns(){return this.initialized||await this.initialize(),K({searchPatterns:this.searchPatterns.bind(this),storePattern:this.storePattern.bind(this),patternStore:this.patternStore})}async storePattern(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return S(new Error("Pattern learning is disabled"));if(!e.embedding){let t=await this.embed(`${e.name} ${e.description} ${e.context?.tags?.join(" ")||""}`);e={...e,embedding:t}}let r=await this.patternStore.create(e);if(r.success&&(P().then(t=>t.append("PATTERN_CREATE",{patternId:r.value.id,domain:r.value.qeDomain,confidence:r.value.confidence,name:r.value.name},"reasoning-bank")).catch(t=>{g.warn("Witness chain PATTERN_CREATE failed",{error:h(t)})}),this.rvfDualWriter&&r.value.embedding&&r.value.embedding.length>0))try{this.rvfDualWriter.writePattern(r.value.id,r.value.embedding)}catch(t){g.warn("RVF dual-write failed (non-fatal)",{patternId:r.value.id,error:h(t)})}return r}async searchPatterns(e,r){this.initialized||await this.initialize();let t=e,a=!0;return typeof e=="string"&&(e.trim()===""?(a=!1,t=""):t=await this.embed(e)),this.patternStore.search(t,{...r,useVectorSearch:a})}async getPattern(e){return this.initialized||await this.initialize(),this.patternStore.get(e)}async recordOutcome(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return T(void 0);let r=await this.patternStore.recordUsage(e.patternId,e.success);try{this.getSqliteStore().recordUsage(e.patternId,e.success,e.metrics,e.feedback)}catch(t){g.warn("SQLite pattern usage persist failed",{error:h(t)})}if(r.success){this.stats.learningOutcomes++,e.success&&this.stats.successfulOutcomes++,P().then(s=>s.append("PATTERN_UPDATE",{patternId:e.patternId,success:e.success},"reasoning-bank")).catch(s=>{g.warn("Witness chain PATTERN_UPDATE failed",{error:h(s)})});let t=await this.getPattern(e.patternId),a=this.getPromotionDeps();t&&await X(t,a)&&(await H(e.patternId,a),g.info("Pattern promoted to long-term",{name:t.name}))}return r}getPromotionDeps(){return{patternStore:this.patternStore,coherenceService:this.coherenceService,eventBus:this.eventBus,coherenceThreshold:this.config.coherenceThreshold||.4,getSqliteStore:this.getSqliteStore.bind(this),rvfDualWriter:this.rvfDualWriter,searchPatterns:this.searchPatterns.bind(this),getPattern:this.getPattern.bind(this)}}async routeTask(e){if(this.initialized||await this.initialize(),!this.config.enableRouting)return S(new Error("Task routing is disabled"));this.stats.routingRequests++;try{let r=e.domain?[e.domain]:x(e.task);r.length===0&&r.push("test-generation");let t=await this.embed(e.task),a=await this.patternStore.search(t,{limit:this.config.maxRoutingCandidates,domain:r[0],useVectorSearch:!0}),s=a.success?a.value.map(d=>d.pattern):[],i=new Map;for(let[d,f]of Object.entries(R)){let m=s.filter(y=>f.domains.includes(y.qeDomain)).length;m>0&&i.set(d,m)}let c=D(r,e.capabilities,i,this.config.routingWeights),o=c[0],l=c.slice(1,4),p=[];if(this.config.enableGuidance&&r.length>0){let d=A(r[0],{framework:e.context?.framework,language:e.context?.language,includeAntiPatterns:!0});p.push(...d.slice(0,5))}this.stats.totalRoutingConfidence+=o.score;let u={recommendedAgent:o.agent,confidence:o.score,alternatives:l.map(d=>({agent:d.agent,score:d.score})),domains:r,patterns:s,guidance:p,reasoning:o.reasoning.join("; ")};return T(u)}catch(r){return S(L(r))}}getGuidance(e,r){return k(e)}generateContext(e,r){return q(e,r||{})}checkAntiPatterns(e,r){return W(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-KTDUTUJL.js"),t=await r(e);return t.length!==this.config.embeddingDimension?U(t,this.config.embeddingDimension):t}catch(r){process.env.DEBUG&&g.warn("ONNX embeddings unavailable, using hash fallback",{error:h(r)})}return $(e,this.config.embeddingDimension)}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let t of j)r[t]=e.byDomain[t]||0;return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:this.stats.routingRequests,avgRoutingConfidence:this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,learningOutcomes:this.stats.learningOutcomes,patternSuccessRate:this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0,patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function Ge(n,e,r,t){return new Q(n,e,r,t)}export{C as a,w as b,R as c,D as d,_ as e,Q as f,Ge as g};
314
+ `);for(let l of c)o.run(l.source_pattern_id,l.target_pattern_id).changes>0&&e++;return e}getEdgeCount(){return this.ensureSchema(),this.db.prepare("SELECT COUNT(*) as cnt FROM pattern_citations").get().cnt}};var g=E.create("QEReasoningBank"),Q=class{constructor(e,r,t={},a){this.memory=e;this.eventBus=r;this.coherenceService=a;this.config={...C,...t},t.rvfDualWriter&&(this.rvfDualWriter=t.rvfDualWriter),this.patternStore=V(e,{embeddingDimension:this.config.embeddingDimension,...t.patternStore})}config;patternStore;initialized=!1;sqliteStore=null;rvfDualWriter=null;getSqliteStore(){return this.sqliteStore||(this.sqliteStore=G(),this.sqliteStore.initialize().catch(e=>{g.warn("SQLitePatternStore init failed",{error:h(e)})})),this.sqliteStore}setRvfDualWriter(e){this.rvfDualWriter=e}stats={routingRequests:0,totalRoutingConfidence:0,learningOutcomes:0,successfulOutcomes:0};async initialize(){if(!this.initialized){await this.patternStore.initialize();try{let e=this.getSqliteStore();await e.initialize(),this.patternStore.setSqliteStore?.(e)}catch(e){g.warn("Failed to wire SQLitePatternStore into PatternStore",{error:h(e)})}await this.loadPretrainedPatterns(),this.initialized=!0;try{let e="reasoning-bank:cross-domain-seeded";if(!await this.memory.get(e))await this.memory.set(e,!0),await this.seedCrossDomainPatterns();else{let t=await this.patternStore.getStats();g.info("Cross-domain transfer already complete",{totalPatterns:t.totalPatterns})}}catch(e){g.warn("Cross-domain seeding failed (non-fatal)",{error:e})}g.info("Initialized")}}async loadPretrainedPatterns(){let e=await this.patternStore.getStats();if(e.totalPatterns>0){g.info("Found existing patterns",{totalPatterns:e.totalPatterns});return}for(let r of w)try{await this.patternStore.create(r)}catch(t){g.warn("Failed to load pattern",{name:r.name,error:t})}g.info("Loaded foundational patterns",{count:w.length})}async seedCrossDomainPatterns(){return this.initialized||await this.initialize(),K({searchPatterns:this.searchPatterns.bind(this),storePattern:this.storePattern.bind(this),patternStore:this.patternStore})}async storePattern(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return S(new Error("Pattern learning is disabled"));if(!e.embedding){let t=await this.embed(`${e.name} ${e.description} ${e.context?.tags?.join(" ")||""}`);e={...e,embedding:t}}let r=await this.patternStore.create(e);if(r.success&&(P().then(t=>t.append("PATTERN_CREATE",{patternId:r.value.id,domain:r.value.qeDomain,confidence:r.value.confidence,name:r.value.name},"reasoning-bank")).catch(t=>{g.warn("Witness chain PATTERN_CREATE failed",{error:h(t)})}),this.rvfDualWriter&&r.value.embedding&&r.value.embedding.length>0))try{this.rvfDualWriter.writePattern(r.value.id,r.value.embedding)}catch(t){g.warn("RVF dual-write failed (non-fatal)",{patternId:r.value.id,error:h(t)})}return r}async searchPatterns(e,r){this.initialized||await this.initialize();let t=e,a=!0;return typeof e=="string"&&(e.trim()===""?(a=!1,t=""):t=await this.embed(e)),this.patternStore.search(t,{...r,useVectorSearch:a})}async getPattern(e){return this.initialized||await this.initialize(),this.patternStore.get(e)}async recordOutcome(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return T(void 0);let r=await this.patternStore.recordUsage(e.patternId,e.success);try{this.getSqliteStore().recordUsage(e.patternId,e.success,e.metrics,e.feedback)}catch(t){g.warn("SQLite pattern usage persist failed",{error:h(t)})}if(r.success){this.stats.learningOutcomes++,e.success&&this.stats.successfulOutcomes++,P().then(s=>s.append("PATTERN_UPDATE",{patternId:e.patternId,success:e.success},"reasoning-bank")).catch(s=>{g.warn("Witness chain PATTERN_UPDATE failed",{error:h(s)})});let t=await this.getPattern(e.patternId),a=this.getPromotionDeps();t&&await X(t,a)&&(await H(e.patternId,a),g.info("Pattern promoted to long-term",{name:t.name}))}return r}getPromotionDeps(){return{patternStore:this.patternStore,coherenceService:this.coherenceService,eventBus:this.eventBus,coherenceThreshold:this.config.coherenceThreshold||.4,getSqliteStore:this.getSqliteStore.bind(this),rvfDualWriter:this.rvfDualWriter,searchPatterns:this.searchPatterns.bind(this),getPattern:this.getPattern.bind(this)}}async routeTask(e){if(this.initialized||await this.initialize(),!this.config.enableRouting)return S(new Error("Task routing is disabled"));this.stats.routingRequests++;try{let r=e.domain?[e.domain]:x(e.task);r.length===0&&r.push("test-generation");let t=await this.embed(e.task),a=await this.patternStore.search(t,{limit:this.config.maxRoutingCandidates,domain:r[0],useVectorSearch:!0}),s=a.success?a.value.map(d=>d.pattern):[],i=new Map;for(let[d,f]of Object.entries(R)){let m=s.filter(y=>f.domains.includes(y.qeDomain)).length;m>0&&i.set(d,m)}let c=D(r,e.capabilities,i,this.config.routingWeights),o=c[0],l=c.slice(1,4),p=[];if(this.config.enableGuidance&&r.length>0){let d=A(r[0],{framework:e.context?.framework,language:e.context?.language,includeAntiPatterns:!0});p.push(...d.slice(0,5))}this.stats.totalRoutingConfidence+=o.score;let u={recommendedAgent:o.agent,confidence:o.score,alternatives:l.map(d=>({agent:d.agent,score:d.score})),domains:r,patterns:s,guidance:p,reasoning:o.reasoning.join("; ")};return T(u)}catch(r){return S(L(r))}}getGuidance(e,r){return k(e)}generateContext(e,r){return q(e,r||{})}checkAntiPatterns(e,r){return W(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-RWWYCIE5.js"),t=await r(e);return t.length!==this.config.embeddingDimension?U(t,this.config.embeddingDimension):t}catch(r){process.env.DEBUG&&g.warn("ONNX embeddings unavailable, using hash fallback",{error:h(r)})}return $(e,this.config.embeddingDimension)}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let t of j)r[t]=e.byDomain[t]||0;return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:this.stats.routingRequests,avgRoutingConfidence:this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,learningOutcomes:this.stats.learningOutcomes,patternSuccessRate:this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0,patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function Ge(n,e,r,t){return new Q(n,e,r,t)}export{C as a,w as b,R as c,D as d,_ as e,Q as f,Ge as g};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.7");process.exit(0)}
2
- import{c as T}from"./chunk-UEFAPTBV.js";var S,E,t,N,_=T(()=>{"use strict";S={MMAP_SIZE_BYTES:67108864,CACHE_SIZE_KB:-32e3,BUSY_TIMEOUT_MS:5e3,DEFAULT_VECTOR_DIMENSIONS:384,DEFAULT_SEARCH_LIMIT:100,CLEANUP_INTERVAL_MS:6e4,TTL_MULTIPLIER_MS:1e3},E={M_CONNECTIONS:16,EF_CONSTRUCTION:200,EF_SEARCH:100,DEFAULT_K_NEIGHBORS:10,COVERAGE_VECTOR_DIMENSION:384},t={MAX_CONCURRENT_AGENTS:15,DEFAULT_AGENT_TTL_MS:36e5,DEFAULT_AGENT_TIMEOUT_MS:12e4,MAX_POOL_SIZE:10},N={MAX_HISTORY_SIZE:1e4}});export{S as a,E as b,t as c,N as d,_ as e};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.8");process.exit(0)}
2
+ import{c as T}from"./chunk-E4D36LGH.js";var S,E,t,N,_=T(()=>{"use strict";S={MMAP_SIZE_BYTES:67108864,CACHE_SIZE_KB:-32e3,BUSY_TIMEOUT_MS:5e3,DEFAULT_VECTOR_DIMENSIONS:384,DEFAULT_SEARCH_LIMIT:100,CLEANUP_INTERVAL_MS:6e4,TTL_MULTIPLIER_MS:1e3},E={M_CONNECTIONS:16,EF_CONSTRUCTION:200,EF_SEARCH:100,DEFAULT_K_NEIGHBORS:10,COVERAGE_VECTOR_DIMENSION:384},t={MAX_CONCURRENT_AGENTS:15,DEFAULT_AGENT_TTL_MS:36e5,DEFAULT_AGENT_TIMEOUT_MS:12e4,MAX_POOL_SIZE:10},N={MAX_HISTORY_SIZE:1e4}});export{S as a,E as b,t as c,N as 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.9.7");process.exit(0)}
2
- import{b as d,d as c}from"./chunk-WLYSZV5U.js";import{a as l,c as g}from"./chunk-MR7V7QVL.js";g();c();import{existsSync as y,readFileSync as p}from"node:fs";import{join as o,dirname as u}from"node:path";import{fileURLToPath as m}from"node:url";var i=class extends Error{constructor(t,n,r){super(t);this.code=n;this.cause=r;this.name="PatternLoaderError"}},s=class a{static instance=null;config;patterns;isLoading=!1;constructor(e={}){this.config={basePath:e.basePath??this.getDefaultBasePath(),throwOnMissing:e.throwOnMissing??!1,validatePatterns:e.validatePatterns??!0},this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]}}static getInstance(e){return a.instance||(a.instance=new a(e)),a.instance}static resetInstance(){a.instance=null}getDefaultBasePath(){try{let e=import.meta.url,t=m(e),n=u(t),r=o(n,"..","..","..");return o(r,"assets","patterns")}catch{return o(process.cwd(),"assets","patterns")}}async loadPatterns(){if(!this.isLoading){this.isLoading=!0,this.patterns.errors=[];try{this.patterns.index=this.loadJsonFile("index.json");let[e,t,n,r]=await Promise.all([Promise.resolve(this.loadJsonFile("adr-051-booster-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-router-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-embedding-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-reasoning-patterns.json"))]);this.patterns.booster=e,this.patterns.router=t,this.patterns.embedding=n,this.patterns.reasoning=r,this.patterns.loadedAt=new Date,this.config.validatePatterns&&this.validateLoadedPatterns()}finally{this.isLoading=!1}}}loadJsonFile(e){let t=o(this.config.basePath,e);try{if(!y(t)){let r=`Pattern file not found: ${t}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"FILE_NOT_FOUND");return null}let n=p(t,"utf-8");return d(n)}catch(n){if(n instanceof i)throw n;let r=`Failed to load pattern file ${e}: ${l(n)}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"PARSE_ERROR",n instanceof Error?n:void 0);return null}}validateLoadedPatterns(){this.patterns.booster&&(Array.isArray(this.patterns.booster.patterns)||this.patterns.errors.push("Booster patterns file missing patterns array")),this.patterns.router&&(Array.isArray(this.patterns.router.patterns)||this.patterns.errors.push("Router patterns file missing patterns array")),this.patterns.embedding&&(Array.isArray(this.patterns.embedding.patterns)||this.patterns.errors.push("Embedding patterns file missing patterns array")),this.patterns.reasoning&&(Array.isArray(this.patterns.reasoning.patterns)||this.patterns.errors.push("Reasoning patterns file missing patterns array"))}async ensureLoaded(){this.patterns.loadedAt||await this.loadPatterns()}async getIndex(){return await this.ensureLoaded(),this.patterns.index}async getBoosterPatterns(){return await this.ensureLoaded(),this.patterns.booster}async getRouterPatterns(){return await this.ensureLoaded(),this.patterns.router}async getEmbeddingPatterns(){return await this.ensureLoaded(),this.patterns.embedding}async getReasoningPatterns(){return await this.ensureLoaded(),this.patterns.reasoning}async getBoosterPatternByKey(e){let t=await this.getBoosterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getRouterPatternByKey(e){let t=await this.getRouterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEmbeddingPatternByKey(e){let t=await this.getEmbeddingPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getReasoningPatternByKey(e){let t=await this.getReasoningPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEligibleBoosterTransforms(){let e=await this.getBoosterPatternByKey("booster-transform-eligibility");return e?e.eligibility_criteria.simple_transforms:[]}async getTierHierarchy(){let e=await this.getRouterPatternByKey("router-5tier-complexity");return e?e.tier_hierarchy:null}async getQualityGateThresholds(){let e=await this.getReasoningPatternByKey("reasoning-pattern-quality-gates");return e?e.gate_thresholds:null}isLoaded(){return this.patterns.loadedAt!==null}getLoadedAt(){return this.patterns.loadedAt}getErrors(){return[...this.patterns.errors]}async getStatistics(){let e=await this.getIndex();return e?e.pattern_statistics:null}async reload(){this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]},await this.loadPatterns()}async getAllPatterns(){return await this.ensureLoaded(),{...this.patterns}}};function x(){return s.getInstance()}export{x as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.8");process.exit(0)}
2
+ import{b as d,d as c}from"./chunk-VVNR4R22.js";import{a as l,c as g}from"./chunk-PG7CZ6Q4.js";g();c();import{existsSync as y,readFileSync as p}from"node:fs";import{join as o,dirname as u}from"node:path";import{fileURLToPath as m}from"node:url";var i=class extends Error{constructor(t,n,r){super(t);this.code=n;this.cause=r;this.name="PatternLoaderError"}},s=class a{static instance=null;config;patterns;isLoading=!1;constructor(e={}){this.config={basePath:e.basePath??this.getDefaultBasePath(),throwOnMissing:e.throwOnMissing??!1,validatePatterns:e.validatePatterns??!0},this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]}}static getInstance(e){return a.instance||(a.instance=new a(e)),a.instance}static resetInstance(){a.instance=null}getDefaultBasePath(){try{let e=import.meta.url,t=m(e),n=u(t),r=o(n,"..","..","..");return o(r,"assets","patterns")}catch{return o(process.cwd(),"assets","patterns")}}async loadPatterns(){if(!this.isLoading){this.isLoading=!0,this.patterns.errors=[];try{this.patterns.index=this.loadJsonFile("index.json");let[e,t,n,r]=await Promise.all([Promise.resolve(this.loadJsonFile("adr-051-booster-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-router-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-embedding-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-reasoning-patterns.json"))]);this.patterns.booster=e,this.patterns.router=t,this.patterns.embedding=n,this.patterns.reasoning=r,this.patterns.loadedAt=new Date,this.config.validatePatterns&&this.validateLoadedPatterns()}finally{this.isLoading=!1}}}loadJsonFile(e){let t=o(this.config.basePath,e);try{if(!y(t)){let r=`Pattern file not found: ${t}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"FILE_NOT_FOUND");return null}let n=p(t,"utf-8");return d(n)}catch(n){if(n instanceof i)throw n;let r=`Failed to load pattern file ${e}: ${l(n)}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"PARSE_ERROR",n instanceof Error?n:void 0);return null}}validateLoadedPatterns(){this.patterns.booster&&(Array.isArray(this.patterns.booster.patterns)||this.patterns.errors.push("Booster patterns file missing patterns array")),this.patterns.router&&(Array.isArray(this.patterns.router.patterns)||this.patterns.errors.push("Router patterns file missing patterns array")),this.patterns.embedding&&(Array.isArray(this.patterns.embedding.patterns)||this.patterns.errors.push("Embedding patterns file missing patterns array")),this.patterns.reasoning&&(Array.isArray(this.patterns.reasoning.patterns)||this.patterns.errors.push("Reasoning patterns file missing patterns array"))}async ensureLoaded(){this.patterns.loadedAt||await this.loadPatterns()}async getIndex(){return await this.ensureLoaded(),this.patterns.index}async getBoosterPatterns(){return await this.ensureLoaded(),this.patterns.booster}async getRouterPatterns(){return await this.ensureLoaded(),this.patterns.router}async getEmbeddingPatterns(){return await this.ensureLoaded(),this.patterns.embedding}async getReasoningPatterns(){return await this.ensureLoaded(),this.patterns.reasoning}async getBoosterPatternByKey(e){let t=await this.getBoosterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getRouterPatternByKey(e){let t=await this.getRouterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEmbeddingPatternByKey(e){let t=await this.getEmbeddingPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getReasoningPatternByKey(e){let t=await this.getReasoningPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEligibleBoosterTransforms(){let e=await this.getBoosterPatternByKey("booster-transform-eligibility");return e?e.eligibility_criteria.simple_transforms:[]}async getTierHierarchy(){let e=await this.getRouterPatternByKey("router-5tier-complexity");return e?e.tier_hierarchy:null}async getQualityGateThresholds(){let e=await this.getReasoningPatternByKey("reasoning-pattern-quality-gates");return e?e.gate_thresholds:null}isLoaded(){return this.patterns.loadedAt!==null}getLoadedAt(){return this.patterns.loadedAt}getErrors(){return[...this.patterns.errors]}async getStatistics(){let e=await this.getIndex();return e?e.pattern_statistics:null}async reload(){this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]},await this.loadPatterns()}async getAllPatterns(){return await this.ensureLoaded(),{...this.patterns}}};function x(){return s.getInstance()}export{x as a};