agentic-qe 3.14.4 → 3.14.6

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 (486) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +169 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/adapters/ag-ui/event-types.d.ts +1 -1
  5. package/dist/audit/witness-chain-hash.d.ts +18 -0
  6. package/dist/audit/witness-chain-hash.js +37 -0
  7. package/dist/audit/witness-chain-repair.d.ts +71 -0
  8. package/dist/audit/witness-chain-repair.js +203 -0
  9. package/dist/audit/witness-chain-verifier.d.ts +152 -0
  10. package/dist/audit/witness-chain-verifier.js +293 -0
  11. package/dist/audit/witness-chain.d.ts +10 -43
  12. package/dist/audit/witness-chain.js +43 -126
  13. package/dist/audit/witness-findings.js +4 -1
  14. package/dist/cli/bundle.js +13 -10
  15. package/dist/cli/chunks/adapter-UYOJPTOX.js +2 -0
  16. package/dist/cli/chunks/agent-booster-wasm-2YGML6OU.js +2 -0
  17. package/dist/cli/chunks/{agent-handler-RDNTK4CA.js → agent-handler-D5SSQYNU.js} +2 -2
  18. package/dist/cli/chunks/{agent-memory-branch-NAAMBWIR.js → agent-memory-branch-YHPLTITV.js} +2 -2
  19. package/dist/cli/chunks/aqe-learning-engine-JR5AVQXR.js +2 -0
  20. package/dist/cli/chunks/{arena-KXFHRWX4.js → arena-7BGOXGXO.js} +2 -2
  21. package/dist/cli/chunks/{arena-HXTWJ5YY.js → arena-MCE6EU7K.js} +4 -4
  22. package/dist/cli/chunks/audit-BMWTQECB.js +4 -0
  23. package/dist/cli/chunks/base-DRZ2LS6X.js +2 -0
  24. package/dist/cli/chunks/{better-sqlite3-UICJZIDG.js → better-sqlite3-PMUNGASU.js} +2 -2
  25. package/dist/cli/chunks/brain-handler-QPUFYX7F.js +94 -0
  26. package/dist/cli/chunks/{branch-enumerator-SS7UNVIA.js → branch-enumerator-WKFDGRN4.js} +2 -2
  27. package/dist/cli/chunks/{browser-77GI6KBE.js → browser-VY5HKH5X.js} +2 -2
  28. package/dist/cli/chunks/browser-workflow-CJ7T3MXF.js +2 -0
  29. package/dist/cli/chunks/{chunk-PZJOPURC.js → chunk-257E2A5M.js} +5 -5
  30. package/dist/cli/chunks/{chunk-55RWDRJD.js → chunk-2JVWITNK.js} +4 -4
  31. package/dist/cli/chunks/{chunk-BOARZKU3.js → chunk-2NPKIBAZ.js} +2 -2
  32. package/dist/cli/chunks/chunk-2TMWAQQ3.js +13 -0
  33. package/dist/cli/chunks/{chunk-M4WJKGVK.js → chunk-2YXGBZWV.js} +1 -1
  34. package/dist/cli/chunks/{chunk-3VOQRIQM.js → chunk-3EA536JF.js} +2 -2
  35. package/dist/cli/chunks/{chunk-ZZDIMOOV.js → chunk-3EZOZN25.js} +2 -2
  36. package/dist/cli/chunks/{chunk-MNW6QGNJ.js → chunk-3HZS4M3O.js} +2 -2
  37. package/dist/cli/chunks/{chunk-EKQ673SA.js → chunk-3NIG7S5W.js} +1 -1
  38. package/dist/cli/chunks/{chunk-7D777LTF.js → chunk-4N23RFDU.js} +2 -2
  39. package/dist/cli/chunks/{chunk-BOZZYWCR.js → chunk-5J6W7SIA.js} +1 -1
  40. package/dist/cli/chunks/{chunk-HIVA55CJ.js → chunk-5OOMJGFN.js} +1 -1
  41. package/dist/cli/chunks/{chunk-W7BWUTVV.js → chunk-5QQSIGUA.js} +2 -2
  42. package/dist/cli/chunks/{chunk-PAWXJ73E.js → chunk-5VFPCSK7.js} +1 -1
  43. package/dist/cli/chunks/{chunk-KPA7MZ6C.js → chunk-62N4NUJH.js} +2 -2
  44. package/dist/cli/chunks/chunk-64VGZQLB.js +2 -0
  45. package/dist/cli/chunks/{chunk-64PFWE2F.js → chunk-66VWCR67.js} +2 -2
  46. package/dist/cli/chunks/{chunk-XRT2WRMS.js → chunk-6LIHFV7O.js} +2 -2
  47. package/dist/cli/chunks/{chunk-STJCATGN.js → chunk-6OS76PHI.js} +2 -2
  48. package/dist/cli/chunks/{chunk-ZNPKDCZR.js → chunk-6RE3X4V5.js} +2 -2
  49. package/dist/cli/chunks/{chunk-BFP7KO7P.js → chunk-6SH5VZUD.js} +2 -2
  50. package/dist/cli/chunks/chunk-6SQM2MUX.js +4 -0
  51. package/dist/cli/chunks/{chunk-IPR4QP3H.js → chunk-6U7LNMWZ.js} +2 -2
  52. package/dist/cli/chunks/{chunk-MIQTXNBG.js → chunk-72KXSMWI.js} +1 -1
  53. package/dist/cli/chunks/chunk-7CUQCCMD.js +27 -0
  54. package/dist/cli/chunks/chunk-7D3V65N5.js +2 -0
  55. package/dist/cli/chunks/{chunk-JZ3ORVZ3.js → chunk-7J6QC567.js} +3 -3
  56. package/dist/cli/chunks/{chunk-4OYFXLBK.js → chunk-7LPR6HJG.js} +2 -2
  57. package/dist/cli/chunks/{chunk-4MHXCAG2.js → chunk-7NITCZWD.js} +1 -1
  58. package/dist/cli/chunks/{chunk-M5QUBZY6.js → chunk-7Z5LHRC3.js} +2 -2
  59. package/dist/cli/chunks/{chunk-CSU5NYOX.js → chunk-AHKELLIO.js} +4 -4
  60. package/dist/cli/chunks/{chunk-DHJPWQBR.js → chunk-AIRGNL55.js} +2 -2
  61. package/dist/cli/chunks/{chunk-C2WU3533.js → chunk-AJRUJAAK.js} +1 -1
  62. package/dist/cli/chunks/{chunk-HIYXCDEP.js → chunk-AVBJYI5I.js} +1 -1
  63. package/dist/cli/chunks/{chunk-U5K45TFH.js → chunk-B6D2CHEH.js} +1 -1
  64. package/dist/cli/chunks/{chunk-FRH6VAUS.js → chunk-B6MOJC3X.js} +1 -1
  65. package/dist/cli/chunks/{chunk-HUWNIPZ5.js → chunk-BAMN2CHI.js} +1 -1
  66. package/dist/cli/chunks/{chunk-ONII3572.js → chunk-BBT64TII.js} +3 -3
  67. package/dist/cli/chunks/{chunk-KSKEF7LZ.js → chunk-BJTJLJRZ.js} +3 -3
  68. package/dist/cli/chunks/chunk-BMAPORJ7.js +15 -0
  69. package/dist/cli/chunks/{chunk-CIZ5JPDC.js → chunk-BPEDWS6O.js} +3 -3
  70. package/dist/cli/chunks/{chunk-Z3RHREWF.js → chunk-BVR7RMC5.js} +1 -1
  71. package/dist/cli/chunks/{chunk-HDSAM2RE.js → chunk-C6KWXUFJ.js} +2 -2
  72. package/dist/cli/chunks/{chunk-ZBAKA4YB.js → chunk-CCK4BF76.js} +1 -1
  73. package/dist/cli/chunks/{chunk-IFCLB7FJ.js → chunk-CD542DNJ.js} +1 -1
  74. package/dist/cli/chunks/{chunk-6KJABXAR.js → chunk-CF2ISEOJ.js} +2 -2
  75. package/dist/cli/chunks/chunk-CM7U6TAX.js +5 -0
  76. package/dist/cli/chunks/{chunk-3X3DJZJJ.js → chunk-D45SG6CP.js} +1 -1
  77. package/dist/cli/chunks/{chunk-DAEFDCJ4.js → chunk-D6CJIGRU.js} +89 -83
  78. package/dist/cli/chunks/{chunk-MVPCNSPY.js → chunk-DBDPRORT.js} +2 -2
  79. package/dist/cli/chunks/{chunk-AUXFKCQL.js → chunk-DHVX5UB2.js} +2 -2
  80. package/dist/cli/chunks/{chunk-GPLQ6DOK.js → chunk-DK4XN4CU.js} +2 -2
  81. package/dist/cli/chunks/{chunk-SRKETSFF.js → chunk-DPYSUDAO.js} +1 -1
  82. package/dist/cli/chunks/{chunk-CNG6GQEZ.js → chunk-DUYOVM5I.js} +2 -2
  83. package/dist/cli/chunks/{chunk-VIHTL3U2.js → chunk-DZ3AUAAB.js} +2 -2
  84. package/dist/cli/chunks/{chunk-CU46J64M.js → chunk-E6G2RD5H.js} +2 -2
  85. package/dist/cli/chunks/{chunk-5YPYDPBJ.js → chunk-EAY2JMZG.js} +2 -2
  86. package/dist/cli/chunks/{chunk-V3QLFNA2.js → chunk-ELLBS5RP.js} +4 -4
  87. package/dist/cli/chunks/chunk-ENGZ4D5V.js +2 -0
  88. package/dist/cli/chunks/chunk-FBMN7B46.js +4 -0
  89. package/dist/cli/chunks/{chunk-EDJ3O7RH.js → chunk-FWASDOT2.js} +2 -2
  90. package/dist/cli/chunks/{chunk-MDWCE7YW.js → chunk-FZOBD67M.js} +1 -1
  91. package/dist/cli/chunks/{chunk-A4FYONNU.js → chunk-GDSXITFH.js} +2 -2
  92. package/dist/cli/chunks/{chunk-2JW3BCGG.js → chunk-GGRHV6D7.js} +1 -1
  93. package/dist/cli/chunks/{chunk-ISDMD6EU.js → chunk-GPYVDFB3.js} +90 -90
  94. package/dist/cli/chunks/{chunk-CDKG6EI7.js → chunk-GSF6MB64.js} +2 -2
  95. package/dist/cli/chunks/{chunk-WLG5AJ4N.js → chunk-H52HZ67P.js} +2 -2
  96. package/dist/cli/chunks/{chunk-FGYMFUE2.js → chunk-H5BS5VH7.js} +2 -2
  97. package/dist/cli/chunks/{chunk-34WO57CW.js → chunk-H6ZM3PUT.js} +1 -1
  98. package/dist/cli/chunks/{chunk-6CQN24ZK.js → chunk-HM6ZSCPI.js} +1 -1
  99. package/dist/cli/chunks/{chunk-DPFRKBOG.js → chunk-HNFVJP4I.js} +2 -2
  100. package/dist/cli/chunks/{chunk-TPGED2IF.js → chunk-I33ERSGB.js} +2 -2
  101. package/dist/cli/chunks/{chunk-UEM7ZF5K.js → chunk-IAF6T27S.js} +2 -2
  102. package/dist/cli/chunks/{chunk-KCZR45PA.js → chunk-IB27QACC.js} +2 -2
  103. package/dist/cli/chunks/{chunk-SGYJ4NFZ.js → chunk-ICTXTNQZ.js} +1 -1
  104. package/dist/cli/chunks/chunk-IG5GNEC6.js +4 -0
  105. package/dist/cli/chunks/{chunk-KHFNNVJA.js → chunk-IQO7UCFR.js} +2 -2
  106. package/dist/cli/chunks/{chunk-3TW5W5LX.js → chunk-IV5UZOHH.js} +2 -2
  107. package/dist/cli/chunks/{chunk-7ZIOFPL3.js → chunk-JBTPOIAC.js} +2 -2
  108. package/dist/cli/chunks/{chunk-ZNEMGX5O.js → chunk-JIXUMYKZ.js} +1 -1
  109. package/dist/cli/chunks/{chunk-MTZH7AHC.js → chunk-JMONHE4B.js} +1 -1
  110. package/dist/cli/chunks/{chunk-TDZ53WO2.js → chunk-JVNTSNWU.js} +2 -2
  111. package/dist/cli/chunks/{chunk-PFR4G3DJ.js → chunk-JXGFRBUO.js} +2 -2
  112. package/dist/cli/chunks/chunk-JZOS5FCX.js +2 -0
  113. package/dist/cli/chunks/{chunk-STM3UDNO.js → chunk-KNNISEDY.js} +2 -2
  114. package/dist/cli/chunks/{chunk-TWAWHOP7.js → chunk-L4RUBPLR.js} +2 -2
  115. package/dist/cli/chunks/chunk-LL3IGZBI.js +2 -0
  116. package/dist/cli/chunks/{chunk-CIKSHTEQ.js → chunk-MBRHSU6W.js} +10 -10
  117. package/dist/cli/chunks/{chunk-G6T45OIC.js → chunk-MJS53PRX.js} +2 -2
  118. package/dist/cli/chunks/{chunk-PO3IXGMQ.js → chunk-MQROI74N.js} +2 -2
  119. package/dist/cli/chunks/{chunk-DOTK76IJ.js → chunk-MUOG6QXR.js} +2 -2
  120. package/dist/cli/chunks/{chunk-MVNP7GIR.js → chunk-MW2GGZZ5.js} +1 -1
  121. package/dist/cli/chunks/{chunk-FWGOHAAB.js → chunk-NHWGMJAP.js} +2 -2
  122. package/dist/cli/chunks/{chunk-ZBJ4XOOV.js → chunk-NMAIY4PX.js} +4 -4
  123. package/dist/cli/chunks/{chunk-CDHQFHRP.js → chunk-NQZ5AR3D.js} +2 -2
  124. package/dist/cli/chunks/{chunk-FLYOJOKN.js → chunk-P6OYS755.js} +1 -1
  125. package/dist/cli/chunks/{chunk-BGE6FOLM.js → chunk-PI7TJS62.js} +2 -2
  126. package/dist/cli/chunks/chunk-PX5YDCRH.js +4 -0
  127. package/dist/cli/chunks/{chunk-Q5DO24IJ.js → chunk-PZPWRQ2M.js} +3 -3
  128. package/dist/cli/chunks/{chunk-R4VL6E65.js → chunk-Q5XTSMWR.js} +2 -2
  129. package/dist/cli/chunks/{chunk-JBNEE5UH.js → chunk-Q7EAGKAE.js} +2 -2
  130. package/dist/cli/chunks/{chunk-R5NE6B2M.js → chunk-QDFTT3RF.js} +2 -2
  131. package/dist/cli/chunks/{chunk-DFZCKIGY.js → chunk-QGA55PFM.js} +3 -3
  132. package/dist/cli/chunks/{chunk-RJCYCLZV.js → chunk-QW6VMTBR.js} +2 -2
  133. package/dist/cli/chunks/{chunk-6VRA2QGL.js → chunk-QZANMBIT.js} +1 -1
  134. package/dist/cli/chunks/{chunk-MEGDYJPV.js → chunk-RETBYIAC.js} +4 -4
  135. package/dist/cli/chunks/{chunk-XJ7QNVI5.js → chunk-RFNPJK6N.js} +3 -3
  136. package/dist/cli/chunks/{chunk-NJBGXDQ7.js → chunk-RG52OKAM.js} +1 -1
  137. package/dist/cli/chunks/{chunk-DA5K5754.js → chunk-RSXXCL4A.js} +1 -1
  138. package/dist/cli/chunks/{chunk-HV2J7KKQ.js → chunk-RTFO5UQH.js} +2 -2
  139. package/dist/cli/chunks/{chunk-6UWGMOND.js → chunk-RZZCUIAI.js} +2 -2
  140. package/dist/cli/chunks/chunk-SDRHUMJB.js +2 -0
  141. package/dist/cli/chunks/{chunk-TSRSV3LD.js → chunk-SE4WIB26.js} +1 -1
  142. package/dist/cli/chunks/{chunk-ODKLFVYC.js → chunk-SESK3ARK.js} +2 -2
  143. package/dist/cli/chunks/{chunk-AWWNB2T7.js → chunk-SJUXE4IC.js} +2 -2
  144. package/dist/cli/chunks/{chunk-QGIU2WRL.js → chunk-SMDN3BQZ.js} +1 -1
  145. package/dist/cli/chunks/{chunk-VD6QRULW.js → chunk-SNOBH4AZ.js} +2 -2
  146. package/dist/cli/chunks/{chunk-OSLYSG3B.js → chunk-SPV2VKC5.js} +2 -2
  147. package/dist/cli/chunks/chunk-TCHGOB2N.js +2 -0
  148. package/dist/cli/chunks/{chunk-MOBNBMFW.js → chunk-TVYY3OCX.js} +1 -1
  149. package/dist/cli/chunks/{chunk-UGVHCMUN.js → chunk-UCFQALXO.js} +3 -3
  150. package/dist/cli/chunks/{chunk-3QHGWY7T.js → chunk-UKA2KOXE.js} +2 -2
  151. package/dist/cli/chunks/{chunk-MCUJEZT6.js → chunk-UNFFDHER.js} +16 -11
  152. package/dist/cli/chunks/{chunk-6QYNWR7U.js → chunk-UQ32JHES.js} +2 -2
  153. package/dist/cli/chunks/{chunk-OULHKEVH.js → chunk-V4DM6ELU.js} +2 -2
  154. package/dist/cli/chunks/{chunk-M2JBBZQB.js → chunk-VGFFFKGK.js} +2 -2
  155. package/dist/cli/chunks/{chunk-OCWWP5PL.js → chunk-VMNWDJIZ.js} +2 -2
  156. package/dist/cli/chunks/chunk-W6HXLH5G.js +180 -0
  157. package/dist/cli/chunks/{chunk-AIHDEEJO.js → chunk-WCJBU2KI.js} +2 -2
  158. package/dist/cli/chunks/{chunk-ZBQY5GLF.js → chunk-WGM35YWL.js} +2 -2
  159. package/dist/cli/chunks/chunk-WO4QMXIG.js +3 -0
  160. package/dist/cli/chunks/{chunk-3UPAMMCB.js → chunk-XAS3XRYM.js} +1 -1
  161. package/dist/cli/chunks/chunk-Y3LZ35OG.js +2 -0
  162. package/dist/cli/chunks/{chunk-5R3QL7WN.js → chunk-Y3UOUNHM.js} +2 -2
  163. package/dist/cli/chunks/{chunk-ZJ26AQA5.js → chunk-YFBSPLJG.js} +1 -1
  164. package/dist/cli/chunks/{chunk-BDESSCVR.js → chunk-YHKEDEAA.js} +3 -3
  165. package/dist/cli/chunks/{chunk-CXQPR5MY.js → chunk-YS4FCTWF.js} +1 -1
  166. package/dist/cli/chunks/{chunk-CLTMDCSE.js → chunk-YSLL6VSL.js} +2 -2
  167. package/dist/cli/chunks/chunk-Z6GGIRQQ.js +65 -0
  168. package/dist/cli/chunks/{chunk-F3SBRQC6.js → chunk-Z7WODOTH.js} +2 -2
  169. package/dist/cli/chunks/chunk-ZCRTRYXK.js +14 -0
  170. package/dist/cli/chunks/{chunk-XRYF6JV7.js → chunk-ZEV3YTO7.js} +2 -2
  171. package/dist/cli/chunks/{chunk-YNXS6CGV.js → chunk-ZL6SYKUK.js} +1 -1
  172. package/dist/cli/chunks/{chunk-5SJHQ2CO.js → chunk-ZSPU4MOS.js} +2 -2
  173. package/dist/cli/chunks/{chunk-UDHKLT4C.js → chunk-ZVWVV4EX.js} +1 -1
  174. package/dist/cli/chunks/{ci-464KPQNP.js → ci-W6K6G2KZ.js} +2 -2
  175. package/dist/cli/chunks/{ci-output-I7FX2RSO.js → ci-output-LDT24TS3.js} +2 -2
  176. package/dist/cli/chunks/{circuit-breaker-3FW237WW.js → circuit-breaker-F5V4KITU.js} +2 -2
  177. package/dist/cli/chunks/claude-flow-setup-DT6WQQVD.js +2 -0
  178. package/dist/cli/chunks/client-KHWJT6FB.js +2 -0
  179. package/dist/cli/chunks/{cline-installer-UWFHT6VY.js → cline-installer-G7TJOAEX.js} +2 -2
  180. package/dist/cli/chunks/{code-KQSUT3FS.js → code-PGE6A42V.js} +3 -3
  181. package/dist/cli/chunks/{code-index-extractor-PABBNUSC.js → code-index-extractor-RNITH372.js} +2 -2
  182. package/dist/cli/chunks/codex-installer-LBX77AI3.js +14 -0
  183. package/dist/cli/chunks/{completions-7RWHAUAR.js → completions-4AWLAARX.js} +2 -2
  184. package/dist/cli/chunks/{complexity-analyzer-XPOAF33E.js → complexity-analyzer-ZPNSS476.js} +2 -2
  185. package/dist/cli/chunks/{continuedev-installer-V4F2FIZP.js → continuedev-installer-UAPWX6OA.js} +2 -2
  186. package/dist/cli/chunks/{copilot-installer-JMICURQB.js → copilot-installer-BJN2YJGI.js} +2 -2
  187. package/dist/cli/chunks/core-handlers-HING5RRG.js +2 -0
  188. package/dist/cli/chunks/{cost-tracker-5OFHEYFJ.js → cost-tracker-MHP2VJ63.js} +2 -2
  189. package/dist/cli/chunks/{coverage-QKN57JDS.js → coverage-PQB4IEFG.js} +3 -3
  190. package/dist/cli/chunks/cross-domain-router-PQTD6AZN.js +2 -0
  191. package/dist/cli/chunks/{cursor-installer-GBJ7YXSM.js → cursor-installer-ZXBWYAS3.js} +2 -2
  192. package/dist/cli/chunks/{daemon-GKP7CMEK.js → daemon-64C7R6OJ.js} +3 -3
  193. package/dist/cli/chunks/{daemon-IAVSO6HK.js → daemon-N2BEGEFY.js} +4 -4
  194. package/dist/cli/chunks/{dag-attention-scheduler-S225TCI7.js → dag-attention-scheduler-SPZDAPNL.js} +2 -2
  195. package/dist/cli/chunks/{detect-IUYH422U.js → detect-LXJBSSZW.js} +2 -2
  196. package/dist/cli/chunks/{dist-node-2YRE6A7C.js → dist-node-U3TKZ2IZ.js} +2 -2
  197. package/dist/cli/chunks/{domain-handler-PL2TZC6H.js → domain-handler-3DDWUVSR.js} +2 -2
  198. package/dist/cli/chunks/{domain-plugins-HCGLXKIT.js → domain-plugins-JJVWI4OQ.js} +2 -2
  199. package/dist/cli/chunks/domain-transfer-M36KUJ2U.js +2 -0
  200. package/dist/cli/chunks/dream-WUGRSNCV.js +2 -0
  201. package/dist/cli/chunks/embed-and-insert-pattern-JPAR7TXX.js +3 -0
  202. package/dist/cli/chunks/{eval-WCK7KNFN.js → eval-SOLG23EA.js} +2 -2
  203. package/dist/cli/chunks/{experience-capture-middleware-2MSQWSAR.js → experience-capture-middleware-T7G2VOOD.js} +4 -4
  204. package/dist/cli/chunks/{fast-paths-VYOSIBKF.js → fast-paths-32N3ELI4.js} +2 -2
  205. package/dist/cli/chunks/{feature-flags-WCFUKHNQ.js → feature-flags-APJDQ4N7.js} +2 -2
  206. package/dist/cli/chunks/{feature-flags-UJRHFBRX.js → feature-flags-NAHKLDRN.js} +2 -2
  207. package/dist/cli/chunks/{file-discovery-JDGL4ZWS.js → file-discovery-YKVM3MDB.js} +2 -2
  208. package/dist/cli/chunks/{fleet-ROXVMZ2F.js → fleet-55M5CJS4.js} +3 -3
  209. package/dist/cli/chunks/{gnn-wrapper-NIO4ZCO3.js → gnn-wrapper-UD6E6S6Z.js} +2 -2
  210. package/dist/cli/chunks/{heartbeat-handler-PI42WD3C.js → heartbeat-handler-OYVW3VSC.js} +4 -4
  211. package/dist/cli/chunks/heartbeat-scheduler-33XX5XNQ.js +2 -0
  212. package/dist/cli/chunks/hnsw-adapter-XQPERX3H.js +2 -0
  213. package/dist/cli/chunks/hnsw-index-2GNXTWHH.js +2 -0
  214. package/dist/cli/chunks/{hnsw-legacy-bridge-YLC7SPK2.js → hnsw-legacy-bridge-HBYIS3ZW.js} +2 -2
  215. package/dist/cli/chunks/{hnswlib-node-LG6OS3B7.js → hnswlib-node-EQPM42OU.js} +2 -2
  216. package/dist/cli/chunks/{hooks-WVALP5GX.js → hooks-5ZSSJWO6.js} +10 -10
  217. package/dist/cli/chunks/hybrid-backend-CCF7URKI.js +2 -0
  218. package/dist/cli/chunks/{hypergraph-engine-GJEMW3EG.js → hypergraph-engine-XBGVQ4PD.js} +2 -2
  219. package/dist/cli/chunks/{hypergraph-handler-BLF6LXEV.js → hypergraph-handler-CAWAQ673.js} +3 -3
  220. package/dist/cli/chunks/impact-analyzer-HGKAZWIG.js +2 -0
  221. package/dist/cli/chunks/{init-handler-K25RWRYY.js → init-handler-PRHXSARK.js} +6 -6
  222. package/dist/cli/chunks/init-wizard-72MFBI3G.js +2 -0
  223. package/dist/cli/chunks/kernel-BRCBVMSK.js +2 -0
  224. package/dist/cli/chunks/{kilocode-installer-BXN6WZ7G.js → kilocode-installer-F7LXBM7I.js} +2 -2
  225. package/dist/cli/chunks/{kiro-installer-PM362DLN.js → kiro-installer-NM723ZRG.js} +2 -2
  226. package/dist/cli/chunks/knowledge-graph-DG44IPEI.js +2 -0
  227. package/dist/cli/chunks/{learning-CPERDDRG.js → learning-5QYIDHH3.js} +3 -3
  228. package/dist/cli/chunks/{llm-router-GOAV5FPI.js → llm-router-43HKWPSX.js} +4 -4
  229. package/dist/cli/chunks/llm-router-service-24KXFX32.js +2 -0
  230. package/dist/cli/chunks/{load-2BG6SHAK.js → load-5YDBWSCS.js} +2 -2
  231. package/dist/cli/chunks/load-test-N4TAYJY3.js +2 -0
  232. package/dist/cli/chunks/mcp-UMAPMNMY.js +2 -0
  233. package/dist/cli/chunks/{memory-4NHBYT6S.js → memory-FWCPCQFP.js} +6 -6
  234. package/dist/cli/chunks/memory-backend-NVYFYVAU.js +2 -0
  235. package/dist/cli/chunks/memory-handlers-UTWCNCHL.js +2 -0
  236. package/dist/cli/chunks/multi-model-executor-2XTBGLE4.js +14 -0
  237. package/dist/cli/chunks/{opencode-installer-ATZLLK74.js → opencode-installer-GIXOJ6NS.js} +2 -2
  238. package/dist/cli/chunks/orchestrator-VW6BKHLI.js +393 -0
  239. package/dist/cli/chunks/pattern-null-store-SBPNYDBR.js +2 -0
  240. package/dist/cli/chunks/{pattern-usage-recorder-7VE4XDAI.js → pattern-usage-recorder-7CEUC3J7.js} +2 -2
  241. package/dist/cli/chunks/{pipeline-LQZSNDD2.js → pipeline-IGUQPPPO.js} +2 -2
  242. package/dist/cli/chunks/platform-2P636I7B.js +2 -0
  243. package/dist/cli/chunks/{plugin-EJ6K2MGU.js → plugin-NY6SWDPE.js} +2 -2
  244. package/dist/cli/chunks/{prime-radiant-advanced-wasm-OIHTKJMN.js → prime-radiant-advanced-wasm-2UUDTIO2.js} +2 -2
  245. package/dist/cli/chunks/project-root-IOISG5KX.js +2 -0
  246. package/dist/cli/chunks/protocol-executor-IBYEII5Q.js +2 -0
  247. package/dist/cli/chunks/{protocol-handler-NRBROAU7.js → protocol-handler-ZTPCRQ5W.js} +2 -2
  248. package/dist/cli/chunks/{prove-EJOGEGD3.js → prove-SQX5A3IG.js} +2 -2
  249. package/dist/cli/chunks/qe-reasoning-bank-7IETWW6W.js +2 -0
  250. package/dist/cli/chunks/{quality-E55UC73D.js → quality-DROILKRY.js} +2 -2
  251. package/dist/cli/chunks/{quality-gate-OIQATNT3.js → quality-gate-PWKWDJY2.js} +3 -3
  252. package/dist/cli/chunks/queen-coordinator-NHUK2MWJ.js +2 -0
  253. package/dist/cli/chunks/real-embeddings-P5U3MGYC.js +2 -0
  254. package/dist/cli/chunks/{ref-validation-OPO6J7OL.js → ref-validation-KY73NQXD.js} +2 -2
  255. package/dist/cli/chunks/{roocode-installer-ODY5KRWU.js → roocode-installer-6JPPRB3W.js} +2 -2
  256. package/dist/cli/chunks/router-SRSO3IHF.js +2 -0
  257. package/dist/cli/chunks/routing-feedback-PASRE5HY.js +2 -0
  258. package/dist/cli/chunks/{routing-handler-KQM6VWLC.js → routing-handler-VTJIVFUO.js} +2 -2
  259. package/dist/cli/chunks/{ruvector-commands-U2GVV6PF.js → ruvector-commands-C6RPSJJO.js} +2 -2
  260. package/dist/cli/chunks/rvf-dual-writer-4M4J67OU.js +2 -0
  261. package/dist/cli/chunks/rvf-migration-adapter-TSXGT5LF.js +2 -0
  262. package/dist/cli/chunks/rvf-migration-coordinator-R53URRIO.js +2 -0
  263. package/dist/cli/chunks/rvf-native-adapter-MOF3E7BR.js +2 -0
  264. package/dist/cli/chunks/{rvf-store-integrity-KMIHD3LP.js → rvf-store-integrity-MMXN5TEJ.js} +2 -2
  265. package/dist/cli/chunks/safe-db-QJLFO33B.js +2 -0
  266. package/dist/cli/chunks/schedule-YIVXW5O2.js +2 -0
  267. package/dist/cli/chunks/scheduler-AON7DWSJ.js +2 -0
  268. package/dist/cli/chunks/{security-P5NM353C.js → security-3B3R2NL4.js} +3 -3
  269. package/dist/cli/chunks/shared-rvf-adapter-VIJB7JUS.js +2 -0
  270. package/dist/cli/chunks/{shared-rvf-dual-writer-2CSG7C4W.js → shared-rvf-dual-writer-UVWGDUWC.js} +2 -2
  271. package/dist/cli/chunks/sqlite-persistence-75VHKKQB.js +2 -0
  272. package/dist/cli/chunks/standalone-memory-M4LWAAYZ.js +2 -0
  273. package/dist/cli/chunks/{status-handler-6TU6O37R.js → status-handler-YYFV6OZL.js} +2 -2
  274. package/dist/cli/chunks/{structural-health-KBIJSTXJ.js → structural-health-27E6LLKB.js} +2 -2
  275. package/dist/cli/chunks/sync-26CEGSTC.js +2 -0
  276. package/dist/cli/chunks/{sync-LNHI5SB7.js → sync-J3LJ56WN.js} +2 -2
  277. package/dist/cli/chunks/task-handler-4MCEBQZL.js +54 -0
  278. package/dist/cli/chunks/task-handlers-GYBAWKE2.js +9 -0
  279. package/dist/cli/chunks/{test-DHAAI3DU.js → test-MPC5HRH5.js} +4 -4
  280. package/dist/cli/chunks/{test-scheduling-XDBZ3QC2.js → test-scheduling-ZJBFRZ3J.js} +3 -3
  281. package/dist/cli/chunks/token-bootstrap-2Y2XITBX.js +2 -0
  282. package/dist/cli/chunks/{token-usage-Q2YG5YQN.js → token-usage-3X5WMTG2.js} +2 -2
  283. package/dist/cli/chunks/{transformers-F5UQTQCY.js → transformers-MVL4C5IX.js} +2 -2
  284. package/dist/cli/chunks/tree-sitter-wasm-parser-SLW65ZFO.js +2 -0
  285. package/dist/cli/chunks/{types-JQ7EQO5Q.js → types-TG5P3CRS.js} +2 -2
  286. package/dist/cli/chunks/unified-memory-UCQ6AB32.js +2 -0
  287. package/dist/cli/chunks/unified-memory-hnsw-IXYUMKRR.js +2 -0
  288. package/dist/cli/chunks/unified-persistence-7E6JQ4FZ.js +2 -0
  289. package/dist/cli/chunks/{upgrade-TJRVGHGD.js → upgrade-ETBHDEPY.js} +2 -2
  290. package/dist/cli/chunks/{validate-BWPCVHBN.js → validate-C2A73LZK.js} +2 -2
  291. package/dist/cli/chunks/{validate-swarm-QVVKCQLP.js → validate-swarm-67XN42ML.js} +2 -2
  292. package/dist/cli/chunks/{vibium-ZFATIWHO.js → vibium-NILGKHLN.js} +2 -2
  293. package/dist/cli/chunks/visual-security-4VZXPEVG.js +2 -0
  294. package/dist/cli/chunks/{web-tree-sitter-KPLY7ONR.js → web-tree-sitter-USJN77P4.js} +2 -2
  295. package/dist/cli/chunks/{windsurf-installer-H7XM7ISA.js → windsurf-installer-5GGZXGJW.js} +2 -2
  296. package/dist/cli/chunks/witness-chain-IWS5ZHHL.js +2 -0
  297. package/dist/cli/chunks/witness-chain-JQA2VPZI.js +2 -0
  298. package/dist/cli/chunks/witness-chain-repair-4UA7IPS3.js +2 -0
  299. package/dist/cli/chunks/witness-chain-verifier-3GEADWPE.js +2 -0
  300. package/dist/cli/chunks/{witness-key-manager-DFRL42GE.js → witness-key-manager-ZWEIK3VJ.js} +2 -2
  301. package/dist/cli/chunks/{workflow-2ZQO6WYI.js → workflow-KHMVVBBA.js} +4 -4
  302. package/dist/cli/chunks/workflow-orchestrator-GI5NQH7C.js +2 -0
  303. package/dist/cli/chunks/wrappers-N6XIK5PT.js +2 -0
  304. package/dist/cli/commands/audit.d.ts +20 -2
  305. package/dist/cli/commands/audit.js +158 -16
  306. package/dist/cli/commands/claude-flow-setup.js +5 -4
  307. package/dist/cli/commands/mcp.js +6 -0
  308. package/dist/cli/commands/memory.d.ts +1 -1
  309. package/dist/cli/commands/memory.js +8 -8
  310. package/dist/cli/commands/platform.js +15 -2
  311. package/dist/cli/commands/upgrade.d.ts +3 -3
  312. package/dist/cli/commands/upgrade.js +3 -3
  313. package/dist/cli/handlers/init-handler.d.ts +10 -0
  314. package/dist/cli/handlers/task-handler.js +24 -3
  315. package/dist/cli/helpers/standalone-memory.d.ts +12 -0
  316. package/dist/cli/helpers/standalone-memory.js +46 -0
  317. package/dist/cli/index.js +39 -42
  318. package/dist/cli/log-gate.d.ts +66 -0
  319. package/dist/cli/log-gate.js +170 -0
  320. package/dist/init/agents-installer.d.ts +4 -0
  321. package/dist/init/agents-installer.js +24 -11
  322. package/dist/init/codex-installer.js +22 -8
  323. package/dist/init/idempotent-write.d.ts +53 -0
  324. package/dist/init/idempotent-write.js +160 -0
  325. package/dist/init/orchestrator.js +1 -0
  326. package/dist/init/phases/05-learning.js +3 -1
  327. package/dist/init/phases/07-hooks.js +32 -16
  328. package/dist/init/phases/08-mcp.js +4 -2
  329. package/dist/init/phases/09-assets.d.ts +10 -0
  330. package/dist/init/phases/09-assets.js +3 -0
  331. package/dist/init/phases/10-workers.js +7 -5
  332. package/dist/init/phases/12-verification.js +7 -2
  333. package/dist/init/project-analyzer.d.ts +9 -0
  334. package/dist/init/project-analyzer.js +20 -1
  335. package/dist/init/self-configurator.d.ts +5 -3
  336. package/dist/init/self-configurator.js +18 -29
  337. package/dist/init/skills-installer.js +4 -2
  338. package/dist/init/token-bootstrap.d.ts +1 -1
  339. package/dist/init/token-bootstrap.js +12 -2
  340. package/dist/init/types.d.ts +16 -0
  341. package/dist/init/types.js +20 -24
  342. package/dist/integrations/coherence/coherence-service.js +84 -24
  343. package/dist/integrations/coherence/vote-tally.d.ts +38 -0
  344. package/dist/integrations/coherence/vote-tally.js +39 -0
  345. package/dist/integrations/ruvector/brain-exporter.js +17 -0
  346. package/dist/integrations/ruvector/brain-import-audit.d.ts +20 -0
  347. package/dist/integrations/ruvector/brain-import-audit.js +22 -0
  348. package/dist/integrations/ruvector/brain-rvf-exporter.js +16 -0
  349. package/dist/integrations/ruvector/brain-shared.js +1 -1
  350. package/dist/integrations/ruvector/rvf-dual-writer.js +6 -1
  351. package/dist/integrations/ruvector/shared-rvf-adapter.d.ts +23 -0
  352. package/dist/integrations/ruvector/shared-rvf-adapter.js +24 -0
  353. package/dist/kernel/hybrid-backend.d.ts +6 -0
  354. package/dist/kernel/hybrid-backend.js +18 -0
  355. package/dist/kernel/kernel.js +12 -16
  356. package/dist/kernel/project-root.d.ts +1 -1
  357. package/dist/kernel/project-root.js +24 -3
  358. package/dist/learning/embedder-identity-store.js +4 -3
  359. package/dist/learning/pattern-store.d.ts +11 -0
  360. package/dist/learning/pattern-store.js +31 -9
  361. package/dist/learning/qe-patterns.d.ts +6 -0
  362. package/dist/learning/qe-patterns.js +7 -1
  363. package/dist/learning/qe-reasoning-bank.js +3 -0
  364. package/dist/learning/real-embeddings.d.ts +8 -0
  365. package/dist/learning/real-embeddings.js +16 -0
  366. package/dist/learning/rvf-pattern-store.js +30 -10
  367. package/dist/learning/sqlite-persistence.d.ts +8 -1
  368. package/dist/learning/sqlite-persistence.js +49 -9
  369. package/dist/logging/console-logger.d.ts +2 -5
  370. package/dist/logging/console-logger.js +10 -46
  371. package/dist/logging/index.d.ts +2 -0
  372. package/dist/logging/index.js +1 -0
  373. package/dist/logging/redaction.d.ts +27 -0
  374. package/dist/logging/redaction.js +170 -0
  375. package/dist/mcp/bundle.js +463 -449
  376. package/dist/mcp/entry.js +2 -0
  377. package/dist/mcp/handlers/core-handlers.js +5 -4
  378. package/dist/mcp/handlers/memory-handlers.d.ts +6 -1
  379. package/dist/mcp/handlers/memory-handlers.js +44 -22
  380. package/dist/mcp/handlers/task-handlers.js +14 -1
  381. package/dist/mcp/protocol-server.js +3 -1
  382. package/dist/mcp/services/session-store.js +5 -1
  383. package/dist/mcp/tools/base.d.ts +9 -2
  384. package/dist/mcp/tools/base.js +7 -0
  385. package/dist/mcp/tools/coherence/consensus.js +51 -2
  386. package/dist/mcp/tools/planning/goap-plan.d.ts +20 -7
  387. package/dist/mcp/tools/planning/goap-plan.js +92 -20
  388. package/dist/mcp/tools/planning/goap-status.d.ts +37 -12
  389. package/dist/mcp/tools/planning/goap-status.js +52 -23
  390. package/dist/mcp/tools/planning/world-state.d.ts +101 -0
  391. package/dist/mcp/tools/planning/world-state.js +274 -0
  392. package/dist/mcp/types.d.ts +4 -2
  393. package/dist/planning/goap-planner.d.ts +60 -4
  394. package/dist/planning/goap-planner.js +218 -60
  395. package/dist/planning/index.d.ts +1 -1
  396. package/dist/planning/index.js +1 -1
  397. package/dist/planning/plan-executor.d.ts +20 -1
  398. package/dist/planning/plan-executor.js +209 -100
  399. package/dist/planning/types.d.ts +16 -0
  400. package/dist/planning/types.js +17 -0
  401. package/dist/plugins/cache.d.ts +2 -0
  402. package/dist/plugins/cache.js +15 -2
  403. package/dist/plugins/lifecycle.js +15 -2
  404. package/dist/plugins/manifest.js +7 -5
  405. package/dist/plugins/resolver.d.ts +13 -22
  406. package/dist/plugins/resolver.js +169 -61
  407. package/dist/plugins/version-policy.d.ts +13 -0
  408. package/dist/plugins/version-policy.js +18 -0
  409. package/dist/shared/types/index.d.ts +6 -0
  410. package/dist/shared/types/index.js +8 -0
  411. package/package.json +2 -1
  412. package/dist/cli/chunks/adapter-TNNNJRDG.js +0 -2
  413. package/dist/cli/chunks/agent-booster-wasm-5PC7D2FW.js +0 -2
  414. package/dist/cli/chunks/aqe-learning-engine-5ZRMYJLB.js +0 -2
  415. package/dist/cli/chunks/audit-YSGA7UWT.js +0 -3
  416. package/dist/cli/chunks/base-KWZHOPSH.js +0 -2
  417. package/dist/cli/chunks/brain-handler-ET6YAP4B.js +0 -90
  418. package/dist/cli/chunks/browser-workflow-2FZTKDUL.js +0 -2
  419. package/dist/cli/chunks/chunk-33YYYWBQ.js +0 -4
  420. package/dist/cli/chunks/chunk-5Z6XZV7K.js +0 -65
  421. package/dist/cli/chunks/chunk-6J62K3SW.js +0 -2
  422. package/dist/cli/chunks/chunk-6TPKK7LD.js +0 -15
  423. package/dist/cli/chunks/chunk-DEYLEDJN.js +0 -27
  424. package/dist/cli/chunks/chunk-J6GNQS62.js +0 -5
  425. package/dist/cli/chunks/chunk-KGT36Z42.js +0 -14
  426. package/dist/cli/chunks/chunk-NA7B2QYB.js +0 -2
  427. package/dist/cli/chunks/chunk-NDPFGIMJ.js +0 -13
  428. package/dist/cli/chunks/chunk-OBAP2TXZ.js +0 -2
  429. package/dist/cli/chunks/chunk-PEPFCPES.js +0 -2
  430. package/dist/cli/chunks/chunk-T6BVLVI5.js +0 -2
  431. package/dist/cli/chunks/chunk-TT23RRB7.js +0 -2
  432. package/dist/cli/chunks/chunk-XC7DYDSY.js +0 -180
  433. package/dist/cli/chunks/chunk-XWMZ6D6N.js +0 -2
  434. package/dist/cli/chunks/chunk-Y3MW3YBC.js +0 -3
  435. package/dist/cli/chunks/claude-flow-setup-6JKMBPGU.js +0 -2
  436. package/dist/cli/chunks/client-7E4LM2WW.js +0 -2
  437. package/dist/cli/chunks/codex-installer-CQ24DTP5.js +0 -14
  438. package/dist/cli/chunks/core-handlers-IFG3757P.js +0 -2
  439. package/dist/cli/chunks/cross-domain-router-EK7W4PGP.js +0 -2
  440. package/dist/cli/chunks/domain-transfer-KQJRUPXA.js +0 -2
  441. package/dist/cli/chunks/dream-NFSCSLY7.js +0 -2
  442. package/dist/cli/chunks/embed-and-insert-pattern-ZPAG7235.js +0 -3
  443. package/dist/cli/chunks/heartbeat-scheduler-ZATCDJDK.js +0 -2
  444. package/dist/cli/chunks/hnsw-adapter-WXQABRCA.js +0 -2
  445. package/dist/cli/chunks/hnsw-index-TPSWLEA5.js +0 -2
  446. package/dist/cli/chunks/impact-analyzer-HNIU45P5.js +0 -2
  447. package/dist/cli/chunks/init-wizard-JUIPBMHG.js +0 -2
  448. package/dist/cli/chunks/kernel-5BOZQ754.js +0 -2
  449. package/dist/cli/chunks/knowledge-graph-EWDAENWM.js +0 -2
  450. package/dist/cli/chunks/llm-router-service-3YT7JGBS.js +0 -2
  451. package/dist/cli/chunks/load-test-BP2CPLIV.js +0 -2
  452. package/dist/cli/chunks/mcp-5TTB37DC.js +0 -2
  453. package/dist/cli/chunks/memory-backend-4PYQBPRM.js +0 -2
  454. package/dist/cli/chunks/memory-handlers-2B27NITS.js +0 -2
  455. package/dist/cli/chunks/multi-model-executor-KCWSGCDT.js +0 -14
  456. package/dist/cli/chunks/orchestrator-RKB7XJRG.js +0 -393
  457. package/dist/cli/chunks/pattern-null-store-OYOQOV2O.js +0 -2
  458. package/dist/cli/chunks/platform-OD5H5U6G.js +0 -2
  459. package/dist/cli/chunks/protocol-executor-3ATJTXWG.js +0 -2
  460. package/dist/cli/chunks/qe-reasoning-bank-LLMYZT4X.js +0 -2
  461. package/dist/cli/chunks/queen-coordinator-RN7L6KG5.js +0 -2
  462. package/dist/cli/chunks/real-embeddings-FPFFNOSZ.js +0 -2
  463. package/dist/cli/chunks/router-MDHITQ2V.js +0 -2
  464. package/dist/cli/chunks/routing-feedback-5XLNJ3Y3.js +0 -2
  465. package/dist/cli/chunks/rvf-dual-writer-JBW4O3II.js +0 -2
  466. package/dist/cli/chunks/rvf-migration-adapter-BPPQL4XJ.js +0 -2
  467. package/dist/cli/chunks/rvf-migration-coordinator-V2GHCJKN.js +0 -2
  468. package/dist/cli/chunks/rvf-native-adapter-S4562CG5.js +0 -2
  469. package/dist/cli/chunks/safe-db-FIRHSXVF.js +0 -2
  470. package/dist/cli/chunks/schedule-RVXFB4HK.js +0 -2
  471. package/dist/cli/chunks/scheduler-IKKAMAOO.js +0 -2
  472. package/dist/cli/chunks/shared-rvf-adapter-LVIUOO4S.js +0 -2
  473. package/dist/cli/chunks/sqlite-persistence-SQ3HCUQ7.js +0 -2
  474. package/dist/cli/chunks/sync-UHOX6RJW.js +0 -2
  475. package/dist/cli/chunks/task-handler-AVDHMLGI.js +0 -49
  476. package/dist/cli/chunks/task-handlers-KYK4VTRA.js +0 -9
  477. package/dist/cli/chunks/token-bootstrap-GUTTLPZX.js +0 -2
  478. package/dist/cli/chunks/tree-sitter-wasm-parser-DEGOHS6F.js +0 -2
  479. package/dist/cli/chunks/unified-memory-CXHLHB5I.js +0 -2
  480. package/dist/cli/chunks/unified-memory-hnsw-I7WAE54M.js +0 -2
  481. package/dist/cli/chunks/unified-persistence-6CPF65WI.js +0 -2
  482. package/dist/cli/chunks/visual-security-GNPHME5H.js +0 -2
  483. package/dist/cli/chunks/witness-chain-RRN6NDCH.js +0 -2
  484. package/dist/cli/chunks/witness-chain-VT4UHHBR.js +0 -2
  485. package/dist/cli/chunks/workflow-orchestrator-DB3HIECD.js +0 -2
  486. package/dist/cli/chunks/wrappers-SUS6XEJD.js +0 -2
@@ -1,65 +0,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.14.4");process.exit(0)}
2
- import{d as j,e as W,f as ie,g as V}from"./chunk-T6BVLVI5.js";import{a as ae}from"./chunk-ZJ26AQA5.js";import{b as Le}from"./chunk-OBAP2TXZ.js";import{a as oe}from"./chunk-IPR4QP3H.js";import{c as Oe,n as T}from"./chunk-NDPFGIMJ.js";import{b as Fe,c as ct}from"./chunk-PEPFCPES.js";import{a as se,b as _e,d as Ne,f as lt}from"./chunk-TDZ53WO2.js";import{c as X,e as Me,f as He}from"./chunk-QGIU2WRL.js";import{b as P,c as v}from"./chunk-STM3UDNO.js";import{a as S,b as Ie,c as De}from"./chunk-G6T45OIC.js";import{i as D}from"./chunk-SRKETSFF.js";import{B as $,D as L,G as ne,P as k,S as O,b as F}from"./chunk-CNG6GQEZ.js";import{d as B,f as ot}from"./chunk-TT23RRB7.js";var K=B(E=>{var vt=E&&E.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(E,"__esModule",{value:!0});var St=Object.prototype.hasOwnProperty;function fe(n,e){return St.call(n,e)}E.hasOwnProperty=fe;function je(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)fe(n,i)&&r.push(i);return r}E._objectKeys=je;function wt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}E._deepClone=wt;function Pt(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}E.isInteger=Pt;function ue(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}E.escapePathComponent=ue;function bt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}E.unescapePathComponent=bt;function me(n,e){var t;for(var r in n)if(fe(n,r)){if(n[r]===e)return ue(r)+"/";if(typeof n[r]=="object"&&(t=me(n[r],e),t!=""))return ue(r)+"/"+t}return""}E._getPathRecursive=me;function Et(n,e){if(n===e)return"/";var t=me(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}E.getPath=Et;function he(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(he(n[e]))return!0}else if(typeof n=="object"){for(var r=je(n),i=r.length,s=0;s<i;s++)if(he(n[r[s]]))return!0}}return!1}E.hasUndefined=he;function Be(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 At=(function(n){vt(e,n);function e(t,r,i,s,o){var c=this.constructor,d=n.call(this,Be(t,{name:r,index:i,operation:s,tree:o}))||this;return d.name=r,d.index=i,d.operation=s,d.tree=o,Object.setPrototypeOf(d,c.prototype),d.message=Be(t,{name:r,index:i,operation:s,tree:o}),d}return e})(Error);E.PatchError=At});var pe=B(g=>{Object.defineProperty(g,"__esModule",{value:!0});var R=K();g.JsonPatchError=R.PatchError;g.deepClone=R._deepClone;var U={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=Z(t,this.path);r&&(r=R._deepClone(r));var i=_(t,{op:"remove",path:this.from}).removed;return _(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=Z(t,this.from);return _(t,{op:"add",path:this.path,value:R._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:J(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},Rt={add:function(n,e,t){return R.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:U.move,copy:U.copy,test:U.test,_get:U._get};function Z(n,e){if(e=="")return n;var t={op:"_get",path:e};return _(n,t),t.value}g.getValueByPointer=Z;function _(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):ee(e,0)),e.path===""){var o={newDocument:n};if(e.op==="add")return o.newDocument=e.value,o;if(e.op==="replace")return o.newDocument=e.value,o.removed=n,o;if(e.op==="move"||e.op==="copy")return o.newDocument=Z(n,e.from),e.op==="move"&&(o.removed=n),o;if(e.op==="test"){if(o.test=J(n,e.value),o.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return o.newDocument=n,o}else{if(e.op==="remove")return o.removed=n,o.newDocument=null,o;if(e.op==="_get")return e.value=n,o;if(t)throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return o}}else{r||(n=R._deepClone(n));var c=e.path||"",d=c.split("/"),a=n,l=1,h=d.length,f=void 0,u=void 0,m=void 0;for(typeof t=="function"?m=t:m=ee;;){if(u=d[l],u&&u.indexOf("~")!=-1&&(u=R.unescapePathComponent(u)),i&&(u=="__proto__"||u=="prototype"&&l>0&&d[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&f===void 0&&(a[u]===void 0?f=d.slice(0,l).join("/"):l==h-1&&(f=e.path),f!==void 0&&m(e,0,n,f)),l++,Array.isArray(a)){if(u==="-")u=a.length;else{if(t&&!R.isInteger(u))throw new g.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);R.isInteger(u)&&(u=~~u)}if(l>=h){if(t&&e.op==="add"&&u>a.length)throw new g.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var o=Rt[e.op].call(e,a,u,n);if(o.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return o}}else if(l>=h){var o=U[e.op].call(e,a,u,n);if(o.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return o}if(a=a[u],t&&l<h&&(!a||typeof a!="object"))throw new g.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}g.applyOperation=_;function We(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=R._deepClone(n));for(var s=new Array(e.length),o=0,c=e.length;o<c;o++)s[o]=_(n,e[o],t,!0,i,o),n=s[o].newDocument;return s.newDocument=n,s}g.applyPatch=We;function Tt(n,e,t){var r=_(n,e);if(r.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}g.applyReducer=Tt;function ee(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new g.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(U[n.op]){if(typeof n.path!="string")throw new g.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new g.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new g.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&R.hasUndefined(n.value))throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new g.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new g.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var o={op:"_get",path:n.from,value:void 0},c=Ve([o],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new g.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}g.validator=ee;function Ve(n,e,t){try{if(!Array.isArray(n))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)We(R._deepClone(e),R._deepClone(n),t||!0);else{t=t||ee;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof g.JsonPatchError)return i;throw i}}g.validate=Ve;function J(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,o;if(t&&r){if(s=n.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!J(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(o=c[i],!J(n[o],e[o]))return!1;return!0}return n!==n&&e!==e}g._areEquals=J});var Xe=B(q=>{Object.defineProperty(q,"__esModule",{value:!0});var b=K(),Ct=pe(),ye=new WeakMap,xt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),It=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function Dt(n){return ye.get(n)}function Ft(n,e){return n.observers.get(e)}function Ot(n,e){n.observers.delete(e.callback)}function _t(n,e){e.unobserve()}q.unobserve=_t;function Nt(n,e){var t=[],r,i=Dt(n);if(!i)i=new xt(n),ye.set(n,i);else{var s=Ft(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=b._deepClone(n),e){r.callback=e,r.next=null;var o=function(){ge(r)},c=function(){clearTimeout(r.next),r.next=setTimeout(o)};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(){ge(r),clearTimeout(r.next),Ot(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 It(e,r)),r}q.observe=Nt;function ge(n,e){e===void 0&&(e=!1);var t=ye.get(n.object);ve(t.value,n.object,n.patches,"",e),n.patches.length&&Ct.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}q.generate=ge;function ve(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=b._objectKeys(e),o=b._objectKeys(n),c=!1,d=!1,a=o.length-1;a>=0;a--){var l=o[a],h=n[l];if(b.hasOwnProperty(e,l)&&!(e[l]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var f=e[l];typeof h=="object"&&h!=null&&typeof f=="object"&&f!=null&&Array.isArray(h)===Array.isArray(f)?ve(h,f,t,r+"/"+b.escapePathComponent(l),i):h!==f&&(c=!0,i&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(h)}),t.push({op:"replace",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(h)}),t.push({op:"remove",path:r+"/"+b.escapePathComponent(l)}),d=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!d&&s.length==o.length))for(var a=0;a<s.length;a++){var l=s[a];!b.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(e[l])})}}}function Mt(n,e,t){t===void 0&&(t=!1);var r=[];return ve(n,e,r,"",t),r}q.compare=Mt});var Ge=B(N=>{var Ht=pe();Object.assign(N,Ht);var Lt=Xe();Object.assign(N,Lt);var te=K();N.JsonPatchError=te.PatchError;N.deepClone=te._deepClone;N.escapePathComponent=te.escapePathComponent;N.unescapePathComponent=te.unescapePathComponent});var A=class extends Error{patternId;disposition;cause;constructor(e,t,r){super(`${t}: pattern ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="PatternMutationError",this.patternId=e,this.disposition=t,this.cause=r}};ct();import{existsSync as Vt}from"node:fs";import{join as it}from"node:path";De();var z=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??G,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1,this.embeddingSpaceId=t?.embeddingSpaceId}createAdapter;config;rvfPath;skipCloseOnDispose;embeddingSpaceId;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){if(this.rvfInitError=null,process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension);let e=T()?.spaceId??this.embeddingSpaceId??null;Oe(this.rvfPath,e,this.adapter.status()?.totalVectors??0),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=S(e);try{this.adapter?.close()}catch{}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-SQ3HCUQ7.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:i}=await import("node:fs"),s=`${this.rvfPath}.idmap.json`;if(!i(s))return;let o=JSON.parse(r(s,"utf-8")),c=new Set((o.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),d=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),a=[...c].filter(l=>!d.has(l));if(a.length===0)return;this.adapter.delete(a),console.log(`[RvfPatternStore] Removed ${a.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${S(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=V(e);if(!t.valid)return v(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return v(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(!this.sqliteStore)return v(new A(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let r=T()?.spaceId??this.embeddingSpaceId;if(e.embedding&&!r)return v(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));let i=!1;if(this.sqliteStore)try{let s=this.sqliteStore.storePattern(e,e.embedding,r);s&&s!==e.id&&(e.id=s),i=!0}catch(s){return v(new A(e.id,"FAILED",s))}if(e.embedding&&!this.adapter&&this.rvfInitError)return v(new A(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",new Error(`RVF unavailable ${i?"after":"before"} authoritative pattern commit: ${this.rvfInitError}`)));if(e.embedding&&this.adapter)try{let s=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding),o=this.adapter.ingest([{id:e.id,vector:s}]);if(o.accepted!==1||o.rejected!==0)throw new Error(`RVF rejected pattern vector (accepted=${o.accepted}, rejected=${o.rejected})`)}catch(s){return v(new A(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",s))}return P(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:D(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:j({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?P(i):v(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)){let c=T()?.spaceId??this.embeddingSpaceId;if(!c||t.embeddingSpaceId!==c)return v(new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId"))}if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),d=this.adapter.search(c,i*2);for(let a of d){let l=await this.get(a.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,a.score);s.push({pattern:l,score:a.score,matchType:"vector",similarity:a.score,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",S(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let c=this.sqliteStore.getPatterns({limit:i*4}),d=e,a=Math.sqrt(d.reduce((l,h)=>l+h*h,0));if(a>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let h=this.sqliteStore.getPattern(l.id),f=h?.embedding;if(!f||f.length!==d.length)continue;let u=0,m=0;for(let w=0;w<d.length;w++)u+=d[w]*f[w],m+=f[w]*f[w];if(m=Math.sqrt(m),m===0)continue;let p=u/(a*m),y=this.calculateReuseInfo(h,p);s.push({pattern:h,score:p,matchType:"vector",similarity:p,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:i*2}),d=new Set(s.map(a=>a.pattern.id));for(let a of c){if(d.has(a.id)||!this.matchesFilters(a,t))continue;let l=this.calculateReuseInfo(a,a.confidence);s.push({pattern:a,score:a.confidence,matchType:"exact",similarity:a.confidence,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,i*2),d=new Set(s.map(a=>a.pattern.id));for(let a of c){if(d.has(a.id))continue;let l=await this.get(a.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,a.ftsScore);s.push({pattern:l,score:.5*a.ftsScore,matchType:"exact",similarity:a.ftsScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch{}s.sort((c,d)=>d.score-c.score);let o=performance.now()-r;return this.searchOps++,this.totalSearchMs+=o,P(s.slice(0,i))}async recordUsage(e,t,r,i){if(!this.sqliteStore)return v(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t,r,i),P(void 0)}catch(s){return v(new Error(`recordUsage failed: ${S(s)}`))}}async promote(e){if(!this.sqliteStore)return v(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return v(new Error(`promote failed: ${S(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,S(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return v(new Error(`SQLite delete failed: ${S(t)}`))}return P(void 0)}async getStats(){let e=this.adapter?.status(),t=0,r={},i={shortTerm:0,longTerm:0};if(this.sqliteStore)try{let s=this.sqliteStore.getStats();t=s.totalPatterns,r=s.byDomain,i={shortTerm:s.byTier["short-term"]??0,longTerm:s.byTier["long-term"]??0}}catch{}return{totalPatterns:t,byTier:i,byDomain:r,byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=W&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",S(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}}};lt();De();O();function ut(n,e){let r=[n.pattern,n];for(let i of r){let s=e.split("."),o=i;for(let c of s){if(o==null)break;if(typeof o=="object")o=o[c];else{o=void 0;break}}if(o!==void 0)return o}}function ht(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(),o=t[0]instanceof Date?t[0].getTime():Number(t[0]),c=t[1]instanceof Date?t[1].getTime():Number(t[1]);return s>=o&&s<=c}return!1}let[r,i]=t;return n>=r&&n<=i}default:return!1}}function Y(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>Y(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>Y(n,r))}case"NOT":return e.child?!Y(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=ut(n,e.field);return ht(t,e.operator,e.value)}default:return!0}}function ke(n,e){return e?n.filter(t=>Y(t,e)):n}O();O();var qe=1e4,Qe=2166136261;function $e(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 de=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;de[n]=e}var Ue="0123456789abcdef";function ft(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=Ue[i>>4]+Ue[i&15]}return t}function mt(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 pt(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 o=0;o<8;o++){let c=0,d=1<<o;for(let a=0;a<n.length;a++)n[a][i]&d&&c++;c>=r&&(s|=d)}t[i]=s}return t}function gt(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+=de[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function yt(n,e,t){return 1-gt(n,e,t)}var ce=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??qe,this.baseSeed=e?.seed??Qe,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=$e(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=mt(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 pt([r,i])}similarity(e,t){return yt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new ae(e),i=0;for(;i<this.byteLen;){let o=r.next(),c=Math.min(4,this.byteLen-i);for(let d=0;d<c;d++)t[i++]=o>>>d*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},le=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??qe,this.baseSeed=e?.seed??Qe,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=$e(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:ft(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+=de[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 ae(e),s=0;for(;s<t;){let c=i.next(),d=t-s,a=d<4?d:4;for(let l=0;l<a;l++)r[s++]=c>>>l*8&255}let o=this.dimensions%8;return o>0&&(r[t-1]&=(1<<o)-1),r}};function ze(n){return new le(n)}function Je(n){return $()?new ce(n):null}var we=ot(Ge(),1),Se=we.default??we,kt=`
4
- CREATE TABLE IF NOT EXISTS pattern_deltas (
5
- id TEXT PRIMARY KEY,
6
- pattern_id TEXT NOT NULL,
7
- version INTEGER NOT NULL,
8
- timestamp INTEGER NOT NULL,
9
- type TEXT NOT NULL CHECK (type IN ('genesis', 'update', 'rollback')),
10
- patch TEXT NOT NULL DEFAULT '[]',
11
- reverse_patch TEXT NOT NULL DEFAULT '[]',
12
- metadata TEXT
13
- );
14
- CREATE INDEX IF NOT EXISTS idx_pattern_deltas_pid_version
15
- ON pattern_deltas (pattern_id, version);
16
- CREATE INDEX IF NOT EXISTS idx_pattern_deltas_timestamp
17
- ON pattern_deltas (timestamp);
18
- `;function Ye(n,e){let t=Se.compare(n,e),r=Se.compare(e,n);return{forward:t,reverse:r}}function Ut(n,e){let t=JSON.parse(JSON.stringify(n));return Se.applyPatch(t,e).newDocument}function Ke(n){return{id:n.id,patternId:n.pattern_id,version:n.version,timestamp:n.timestamp,type:n.type,patch:JSON.parse(n.patch),reversePatch:JSON.parse(n.reverse_patch),metadata:n.metadata?JSON.parse(n.metadata):void 0}}var re=class{db;config;prepared=new Map;initialized=!1;constructor(e,t){this.db=e,this.config={maxVersionsPerPattern:t?.maxVersionsPerPattern??100,compressDeltas:t?.compressDeltas??!1}}initialize(){this.initialized||(this.db.exec(kt),this.prepareStatements(),this.initialized=!0)}prepareStatements(){this.prepared.set("insert",this.db.prepare(`
19
- INSERT INTO pattern_deltas (id, pattern_id, version, timestamp, type, patch, reverse_patch, metadata)
20
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
21
- `)),this.prepared.set("getHistory",this.db.prepare(`
22
- SELECT * FROM pattern_deltas
23
- WHERE pattern_id = ?
24
- ORDER BY version ASC
25
- `)),this.prepared.set("currentVersion",this.db.prepare(`
26
- SELECT MAX(version) as max_version FROM pattern_deltas
27
- WHERE pattern_id = ?
28
- `)),this.prepared.set("incrementalSync",this.db.prepare(`
29
- SELECT * FROM pattern_deltas
30
- WHERE timestamp > ?
31
- ORDER BY timestamp ASC
32
- `)),this.prepared.set("countForPattern",this.db.prepare(`
33
- SELECT COUNT(*) as cnt FROM pattern_deltas
34
- WHERE pattern_id = ?
35
- `)),this.prepared.set("deleteOldest",this.db.prepare(`
36
- DELETE FROM pattern_deltas
37
- WHERE pattern_id = ? AND version IN (
38
- SELECT version FROM pattern_deltas
39
- WHERE pattern_id = ?
40
- ORDER BY version ASC
41
- LIMIT ?
42
- )
43
- `))}ensureInitialized(){if(!this.initialized)throw new Error("DeltaTracker not initialized. Call initialize() first.")}createGenesis(e,t,r){this.ensureInitialized();let i=this.getCurrentVersion(e);if(i>=0)throw new Error(`Genesis already exists for pattern ${e} (current version: ${i})`);let s={id:D(),patternId:e,version:0,timestamp:Date.now(),type:"genesis",patch:[],reversePatch:[],metadata:{...r,snapshot:t}};return this.insertEvent(s),s}recordDelta(e,t,r,i){this.ensureInitialized();let s=this.getCurrentVersion(e);if(s<0)throw new Error(`No genesis found for pattern ${e}. Call createGenesis() first.`);let{forward:o,reverse:c}=Ye(t,r),d={id:D(),patternId:e,version:s+1,timestamp:Date.now(),type:"update",patch:o,reversePatch:c,metadata:i};return this.insertEvent(d),this.enforceRetention(e),d}rollback(e,t){this.ensureInitialized();let r=this.getHistory(e);if(r.length===0)throw new Error(`No history found for pattern ${e}`);let i=r[r.length-1].version;if(t<0||t>i)throw new Error(`Invalid rollback version ${t}. Valid range: 0-${i}`);if(t===i)return this.reconstructState(r,i);let s=this.reconstructState(r,t),o=this.reconstructState(r,i),{forward:c,reverse:d}=Ye(o,s),a={id:D(),patternId:e,version:i+1,timestamp:Date.now(),type:"rollback",patch:c,reversePatch:d,metadata:{rolledBackTo:t}};return this.insertEvent(a),this.enforceRetention(e),s}getHistory(e){return this.ensureInitialized(),this.prepared.get("getHistory").all(e).map(Ke)}incrementalSync(e){return this.ensureInitialized(),this.prepared.get("incrementalSync").all(e).map(Ke)}getCurrentVersion(e){return this.ensureInitialized(),this.prepared.get("currentVersion").get(e).max_version??-1}insertEvent(e){this.prepared.get("insert").run(e.id,e.patternId,e.version,e.timestamp,e.type,JSON.stringify(e.patch),JSON.stringify(e.reversePatch),e.metadata?JSON.stringify(e.metadata):null)}reconstructState(e,t){let r=e.find(s=>s.type==="genesis");if(!r||!r.metadata?.snapshot)throw new Error("Cannot reconstruct state: no genesis snapshot found");let i=JSON.parse(JSON.stringify(r.metadata.snapshot));for(let s of e)if(s.version!==0){if(s.version>t)break;i=Ut(i,s.patch)}return i}enforceRetention(e){let{maxVersionsPerPattern:t}=this.config,i=this.prepared.get("countForPattern").get(e).cnt;if(i>t){let s=i-t;this.db.prepare(`DELETE FROM pattern_deltas
44
- WHERE pattern_id = ? AND version != 0 AND id IN (
45
- SELECT id FROM pattern_deltas
46
- WHERE pattern_id = ? AND version != 0
47
- ORDER BY version ASC
48
- LIMIT ?
49
- )`).run(e,e,s)}}};O();var qt={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={...qt,...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},o={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(o),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 o=s+1,c=this.computeSparseChanges(t,r),d={patternId:e,version:o,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:i,compressedSize:c.length};return this.versions.set(e,o),this.getOrCreate(this.history,e).push(d),this.buffer.push(d),o%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:o,fullVector:[...r],timestamp:d.timestamp}),this.enforceRetention(e),d}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)||[],o=null;for(let a=s.length-1;a>=0;a--)if(s[a].version<=t){o=s[a];break}if(!o)return null;let c=[...o.fullVector],d=o.version+1;for(let a of r)if(!(a.version<d)){if(a.version>t)break;this.applySparseForward(c,a.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,o=i.slice(0,s),c=i.slice(s),d=o.findIndex(h=>h.deltaType==="genesis");d>=0&&(c.unshift(o[d]),o.splice(d,1)),this.history.set(e,c);let a=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(h=>h.version===0||h.version>=a)),o.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 o=s<e.length?e[s]:0,c=s<t.length?t[s]:0;Math.abs(o-c)>this.config.epsilon&&r.push({index:s,oldValue:o,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 Ze(n){return L()?new Pe(n):null}O();var Qt=128,$t=8,zt=1e4,be=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Qt,this.beta=e?.beta??$t,this.maxPatterns=e?.maxPatterns??zt,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let i=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:i,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let l=0;l<this.patterns.length;l++)r[l]=this.beta*this.dotProduct(this.patterns[l].pattern,t);let i=this.softmax(r),s=0,o=i[0];for(let l=1;l<i.length;l++)i[l]>o&&(o=i[l],s=l);let c=this.patterns[s],d=this.getEnergy(t),a=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:d,similarity:a}}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 a=0;a<this.patterns.length;a++)r[a]=this.dotProduct(this.patterns[a].pattern,t);let i=new Float32Array(this.patterns.length),s=-1/0;for(let a=0;a<this.patterns.length;a++)i[a]=this.beta*r[a],i[a]>s&&(s=i[a]);let o=0;for(let a=0;a<this.patterns.length;a++)o+=Math.exp(i[a]-s);let c=1/this.beta*(s+Math.log(o)),d=this.dotProduct(t,t);return-c+.5*d}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(!F().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function et(n){return new be(n)}O();var Jt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},M=1e-5,tt=1-M;function Bt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function C(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function jt(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 x=class n{static poincareDistance(e,t){let r=C(jt(e,t)),i=Math.max(M,1-C(e)),s=Math.max(M,1-C(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=Bt(e,t),i=C(e),s=C(t),o=Math.max(M,1+2*r+i*s),c=1+2*r+s,d=1-i,a=new Float32Array(e.length);for(let l=0;l<e.length;l++)a[l]=(c*e[l]+d*t[l])/o;return n.project(a)}static expMap(e,t){let r=2/Math.max(M,1-C(e)),i=Math.sqrt(C(t));if(i<M)return new Float32Array(e);let s=Math.tanh(r*i/2),o=new Float32Array(t.length);for(let c=0;c<t.length;c++)o[c]=s/i*t[c];return n.mobiusAdd(e,o)}static project(e){let t=Math.sqrt(C(e));if(t<=tt)return new Float32Array(e);let r=tt/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(C(e));if(t<M)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)}},Ee=class{config;points=new Map;constructor(e){if(this.config={...Jt,...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:x.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=x.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:x.poincareDistance(r,s.coordinates),point:s});return i.sort((s,o)=>s.distance-o.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,o=[];for(let d of e)if(s.set(d.id,d),!d.parentId)o.push(d.id);else{let a=i.get(d.parentId);a||(a=[],i.set(d.parentId,a)),a.push(d.id)}let c=o.map((d,a)=>({id:d,depth:0,angOff:2*Math.PI*a/Math.max(1,o.length),angSpan:2*Math.PI/Math.max(1,o.length)}));for(;c.length>0;){let{id:d,depth:a,angOff:l,angSpan:h}=c.shift(),f=Math.tanh(.3*(a+.1)),u=l+h/2,m=new Float32Array(r);m[0]=f*Math.cos(u),m[1]=f*Math.sin(u);let p=s.get(d);if(p&&p.features.length>0){let H=f*.1;for(let I=2;I<r&&I-2<p.features.length;I++)m[I]=p.features[I-2]*H}let y=x.project(m);t.set(d,y),this.points.set(d,{id:d,coordinates:y,metadata:{depth:a,parentId:p?.parentId}});let w=i.get(d)??[];for(let H=0;H<w.length;H++){let I=h/Math.max(1,w.length);c.push({id:w[H],depth:a+1,angOff:l+H*I,angSpan:I})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function rt(n){return Wt()?new Ee(n):null}function Wt(){return F().useHyperbolicHnsw}O();var Ae=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!k())return!1;try{return this.index=rt(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=x.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=x.euclideanToHyperbolic(r);return this.index.search(i,t).map(o=>({patternId:o.id,distance:o.distance,metadata:o.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 nt(n){return new Ae(n)}var Re=null;function st(){return Re||(Re=ze({dimensions:1e4})),Re}var Te;function Xt(){return Te===void 0&&(Te=Je()),Te}var Q=null,Ce=0;function at(n){return(!Q||Ce!==n)&&(Q=et({dimension:n,maxPatterns:1e4}),Ce=n),Q}var G={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:W,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},xe=class{constructor(e,t={}){this.memory=e;this.config={...G,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;nullStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswSpaceId=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,L()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new re(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(){if(this.hnswIndex!==null){let e=T()?.spaceId??this.config.embeddingSpaceId??null;return this.hnswSpaceId!==e?(console.warn("[PatternStore] VECTOR_SPACE_MISMATCH: active embedder changed; semantic index disabled"),null):this.hnswIndex}return 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(this.hnswSpaceId=T()?.spaceId??this.config.embeddingSpaceId??null,!this.hnswSpaceId)throw new Error("VECTOR_SPACE_UNVERIFIED: cannot initialize HNSW without runtime provenance");if(F().useUnifiedHnsw)try{let{HnswLegacyBridge:o}=await import("./hnsw-legacy-bridge-YLC7SPK2.js"),{HnswAdapter:c}=await import("./hnsw-adapter-WXQABRCA.js"),d=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 o(d),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)"),await this.loadEmbeddingsIntoHNSW();return}catch(o){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",o)}let{HNSWIndex:t}=await import("./hnsw-index-TPSWLEA5.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((o,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",S(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,i=0,s=T()?.spaceId??this.config.embeddingSpaceId;for(let{patternId:o,embedding:c,spaceId:d}of e){if(r>=t)break;if(!s||d!==s||!c||c.length!==this.config.embeddingDimension){i++;continue}let a=this.patternCache.get(o);if(!a){i++;continue}try{await this.hnswIndex.insert(o,c,{filePath:a.patternType,lineCoverage:a.confidence*100,branchCoverage:a.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-a.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{i++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${i})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",S(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Ze()),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:",S(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=V(e);if(!t.valid)return v(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return v(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));let r=(process.env.AQE_MEMORY_BACKEND??"memory")!=="memory";if(r&&!this.sqliteStore)return v(new A(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let i=T()?.spaceId??this.config.embeddingSpaceId;if(e.embedding&&!i)return v(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let o=this.patternCache.get(e.id)??null,c=!1,d=()=>{this.unindexPattern(e),o&&this.indexPattern(o)};if(this.indexPattern(e),this.sqliteStore)try{let a=this.sqliteStore.storePattern(e,e.embedding,i);a&&a!==e.id&&(this.unindexPattern(e),e.id=a,this.indexPattern(e)),c=!0}catch(a){return d(),v(new A(e.id,"FAILED",a))}if(e.embedding){let a=await this.ensureHNSW();if(!a&&c)return v(new A(e.id,"COMMITTED_PENDING_INDEX",new Error("HNSW unavailable after authoritative pattern commit")));if(!a&&r)return d(),v(new A(e.id,"FAILED",new Error("HNSW unavailable before an authoritative pattern commit")));if(a)try{await a.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(l){return c||d(),v(new A(e.id,c?"COMMITTED_PENDING_INDEX":"FAILED",l))}}if($())try{let l=st().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,l.vector)}catch(a){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,S(a))}try{let a=Xt();if(a){let l=[e.patternType,e.qeDomain];e.context?.tags&&l.push(...e.context.tags),e.name&&l.push(e.name);let h=a.fingerprintPattern(l);this.hdcTokenCache.set(e.id,h)}}catch(a){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,S(a))}if(ne()&&e.embedding)try{at(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(a){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,S(a))}if(L()&&this.deltaTracker)try{let a={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,a)}catch(a){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,S(a))}if(e.embedding)try{let a=this.getVectorDeltaTracker();a&&(o?.embedding?a.recordDelta(e.id,o.embedding,e.embedding):a.getVersion(e.id)<0&&a.recordGenesis(e.id,e.embedding))}catch(a){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,S(a))}try{k()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return P(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:D(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?P(i):v(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)&&ne())try{let f=at(e.length);if(f.getPatternCount()>0){let u=f.recall(new Float32Array(e));if(u&&u.similarity>.98){let m=u.metadata.id,p=await this.get(m);if(p&&this.matchesFilters(p,t)){let y=this.calculateReuseInfo(p,u.similarity);s.push({pattern:p,score:u.similarity,matchType:"vector",similarity:u.similarity,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}catch(f){console.debug("[PatternStore] Hopfield recall failed:",S(f))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let f=T()?.spaceId??this.config.embeddingSpaceId;if(!f||t.embeddingSpaceId!==f)throw new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId");let u=await this.ensureHNSW();if(u){let m=await u.search(e,i*2);for(let p of m){let y=await this.get(p.key);if(y&&this.matchesFilters(y,t)){let w=this.calculateReuseInfo(y,p.score);s.push({pattern:y,score:p.score,matchType:"vector",similarity:p.score,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let f=this.sqliteStore.searchFTS(e,i*2);if(f.length>0){let u=new Map(f.map(p=>[p.id,p.ftsScore])),m=new Set(s.map(p=>p.pattern.id));for(let p of s){let y=u.get(p.pattern.id);y!==void 0&&(p.score=.75*p.score+.25*y)}for(let p of f){if(m.has(p.id))continue;let y=await this.get(p.id);if(y&&this.matchesFilters(y,t)){let w=this.calculateReuseInfo(y,p.ftsScore);s.push({pattern:y,score:.5*p.ftsScore,matchType:"exact",similarity:p.ftsScore,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}}}catch{}if(typeof e=="string"||s.length<i){let f=await this.searchByText(typeof e=="string"?e:"",t,i-s.length),u=new Set(s.map(m=>m.pattern.id));for(let m of f)u.has(m.pattern.id)||s.push(m)}let o=720*60*60*1e3,c=Date.now();for(let f of s){let u=f.pattern.lastUsedAt?.getTime()??f.pattern.createdAt.getTime(),m=c-u,p=Math.pow(.5,m/o),y=f.pattern.usageCount>0?p:.5;f.score=f.score*(.7+.3*y)}let d=this.sqliteStore?.getDatabase();if(d&&s.length>0)try{this.nullStore||(this.nullStore=new oe(d));let f=this.nullStore.getNullSummaries(s.map(u=>u.pattern.id));for(let u of s){let m=f.get(u.pattern.id);m&&(u.nullSummary=m,u.score=oe.applyNullDiscount(u.score,m,t.contextFingerprint))}}catch(f){console.debug("[PatternStore] null discount skipped:",S(f))}s.sort((f,u)=>u.score-f.score);let a=s;t.filter&&(a=ke(s,t.filter));let l=a.slice(0,i),h=performance.now()-r;return this.recordSearchLatency(h),P(l)}catch(o){return v(Ie(o))}}async searchByText(e,t,r){let i=[],s=e.toLowerCase(),o;t.domain?o=this.domainIndex.get(t.domain)||new Set:t.patternType?o=this.typeIndex.get(t.patternType)||new Set:t.tier?o=this.tierIndex.get(t.tier)||new Set:o=new Set(this.patternCache.keys());let c=[...o];if($()&&s&&this.hdcCache.size>0)try{let d=st(),a=d.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(u=>this.hdcCache.has(u)).map(u=>({id:u,similarity:d.similarity(a.vector,this.hdcCache.get(u))}));l.sort((u,m)=>m.similarity-u.similarity);let h=l.map(u=>u.id),f=c.filter(u=>!this.hdcCache.has(u));c=[...h,...f]}catch{}for(let d of c){if(i.length>=r)break;let a=this.patternCache.get(d);if(!a||!this.matchesFilters(a,t))continue;let l=0;if(s){let h=a.name.toLowerCase(),f=a.description.toLowerCase();h.includes(s)&&(l+=.5),f.includes(s)&&(s.length/f.length>.3?l+=.5:l+=.3);for(let u of a.context.tags)if(u.toLowerCase().includes(s)){l+=.2;break}l=Math.min(l,1)}else l=a.qualityScore;if(l>0||!s){let h=this.calculateReuseInfo(a,l);i.push({pattern:a,score:l||a.qualityScore,matchType:s?"exact":"context",similarity:l||a.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,o=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),d=(Date.now()-o)/(1e3*60*60*24)<=r.maxAgeForReuse,a=r.enabled&&e.reusable&&i&&s&&d,l=a?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,h=t,f=e.successRate,u=Math.min(e.reuseCount/10,1),m=a?h*.4+f*.4+u*.2:0;return{canReuse:a,estimatedTokenSavings:l,reuseConfidence:m}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t,r,i){let s=await this.get(e);if(!s)return v(new Error(`Pattern not found: ${e}`));let o=new Date,c=s.usageCount+1,d=s.successfulUses+(t?1:0),a=d/c,l=t?.02:-.01,h=Math.max(.1,Math.min(1,s.confidence+l)),f=j({confidence:h,usageCount:c,successRate:a}),u={...s,usageCount:c,successfulUses:d,successRate:a,confidence:h,qualityScore:f,lastUsedAt:o};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t,r,i)}catch(y){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,S(y))}if(L()&&this.deltaTracker)try{let y={id:s.id,name:s.name,confidence:s.confidence,qualityScore:s.qualityScore,usageCount:s.usageCount,successRate:s.successRate,tier:s.tier},w={id:u.id,name:u.name,confidence:u.confidence,qualityScore:u.qualityScore,usageCount:u.usageCount,successRate:u.successRate,tier:u.tier};this.deltaTracker.recordDelta(e,y,w,{success:t})}catch(y){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,S(y))}let m=ie(u);return m.meetsUsageCriteria&&m.meetsQualityCriteria&&m.meetsCoherenceCriteria&&u.tier==="short-term"?await this.promote(e):this.patternCache.set(e,u),P(void 0)}async promote(e){let t=await this.get(e);if(!t)return v(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return P(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(i){console.debug("[PatternStore] SQLite promotion error:",i instanceof Error?i.message:i)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),P(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return v(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return P(void 0)}async getStats(){let e={},t={};for(let[a,l]of this.domainIndex)e[a]=l.size;for(let[a,l]of this.typeIndex)t[a]=l.size;let r=0,i=0,s=0,o=0;for(let a of this.patternCache.values())r+=a.confidence,i+=a.qualityScore,s+=a.successRate,o++;let c=await this.ensureHNSW(),d=c!==null?await c.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:o>0?r/o:0,avgQualityScore:o>0?i/o:0,avgSuccessRate:o>0?s/o:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:d.nativeHNSW,vectorCount:d.vectorCount,indexSizeBytes:d.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],i=[];for(let s of this.patternCache.values()){let o=ie(s);if(o.meetsUsageCriteria&&o.meetsQualityCriteria&&o.meetsCoherenceCriteria){i.push(s.id);continue}if(s.tier==="short-term"){let d=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),a=Date.now()-d,l=a>10080*60*1e3,h=s.qualityScore<.2,f=s.usageCount===0&&a>1440*60*1e3;(l&&h||f)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let o of t){let c=this.patternCache.get(o);c&&r.push(c)}r.sort((o,c)=>o.qualityScore-c.qualityScore);let i=Math.ceil(r.length*.1),s=0;for(let o of r){if(s>=i)break;o.tier==="short-term"&&(await this.delete(o.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),Q&&(Q.clear(),Q=null,Ce=0),this.initialized=!1}indexHyperbolic(e,t,r){if(k())try{this.hyperbolicIndex||(this.hyperbolicIndex=nt({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(!k()||!this.hyperbolicIndex)return P([]);try{let r=this.hyperbolicIndex.search(e,t),i=[];for(let s of r){let o=await this.get(s.patternId);if(!o)continue;let c=Math.exp(-s.distance),d=this.calculateReuseInfo(o,c);i.push({pattern:o,score:c,matchType:"vector",similarity:c,canReuse:d.canReuse,estimatedTokenSavings:d.estimatedTokenSavings,reuseConfidence:d.reuseConfidence})}return P(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function sn(n,e){try{if(F().useRVFPatternStore&&Ne()){let r=process.env.AQE_PROJECT_ROOT??Fe(),i=it(r,".agentic-qe"),s=it(i,"patterns.rvf");if(Vt(i)){let o={...G,...e},c=!1;try{let d=Le(i,o.embeddingDimension);if(d){c=!0;let a=new z(()=>d,{rvfPath:s,base:o,skipCloseOnDispose:!0,embeddingSpaceId:o.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),a}}catch{}if(!c){let d=new z((a,l)=>{let h,f=()=>{try{return _e(a)}catch(m){return h=m,null}},u=f();if(!u&&X(h)&&(!Me(a)||(u=f(),!u&&X(h))))throw h;if(u){let m=u.dimension();if(m!==l){try{u.close()}catch{}throw new Error(`RVF dimension mismatch (file=${m}, requested=${l})`)}return u}try{return se(a,l)}catch(m){if(u=f(),u){if(u.dimension()!==l){let p=u.dimension();try{u.close()}catch{}throw new Error(`RVF dimension mismatch (file=${p}, requested=${l})`)}return u}if(X(h))throw h;if(He(a,m instanceof Error?m.message:String(m),h))return se(a,l);throw m}},{rvfPath:s,base:o,embeddingSpaceId:o.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),d}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new xe(n,e)}export{A as a,sn as b};
50
- /*! Bundled license information:
51
-
52
- fast-json-patch/commonjs/helpers.js:
53
- (*!
54
- * https://github.com/Starcounter-Jack/JSON-Patch
55
- * (c) 2017-2022 Joachim Wester
56
- * MIT licensed
57
- *)
58
-
59
- fast-json-patch/commonjs/duplex.js:
60
- (*!
61
- * https://github.com/Starcounter-Jack/JSON-Patch
62
- * (c) 2017-2021 Joachim Wester
63
- * MIT license
64
- *)
65
- */
@@ -1,2 +0,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.14.4");process.exit(0)}
2
- import{a as S}from"./chunk-NA7B2QYB.js";import{c as g}from"./chunk-Y3MW3YBC.js";import{S as T,b as l}from"./chunk-CNG6GQEZ.js";S();T();import{createRequire as B}from"module";var G=B(import.meta.url),d=class{validateTransfer(e,t){return{approved:!0}}};function R(){if(l().useCoherenceGate)try{let{CoherenceGate:o}=G("./coherence-gate.js");return new o}catch{}return new d}S();var x=g.create("transfer-verification"),A={maxSourceRegression:.05,minTargetImprovement:0,maxSourceConfidenceRegression:.1},b=class{config;constructor(e={}){this.config={...A,...e}}verifyTransfer(e){let t=e.sourcePerformanceAfter.successRate-e.sourcePerformanceBefore.successRate,r=e.targetPerformanceAfter.successRate-e.targetPerformanceBefore.successRate,n=e.sourcePerformanceAfter.avgConfidence-e.sourcePerformanceBefore.avgConfidence,a=e.targetPerformanceAfter.avgConfidence-e.targetPerformanceBefore.avgConfidence,s=t>=-this.config.maxSourceRegression&&n>=-this.config.maxSourceConfidenceRegression,c=r>=this.config.minTargetImprovement,u=s&&c,m;if(!u){let i=[];s||i.push(`source domain regressed: successRate delta=${t.toFixed(4)}, confidence delta=${n.toFixed(4)}`),c||i.push(`target domain did not improve: successRate delta=${r.toFixed(4)}`),m=i.join("; ")}return u?x.debug("Transfer verification passed",{transferId:e.transferId,sourceDelta:t,targetDelta:r}):x.warn("Transfer verification failed",{transferId:e.transferId,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourceDelta:t,targetDelta:r,failureReason:m}),{passed:u,sourceStable:s,targetImproved:c,sourceDelta:t,targetDelta:r,sourceConfidenceDelta:n,targetConfidenceDelta:a,failureReason:m}}getConfig(){return{...this.config}}};function M(o){return new b(o)}T();var p=class{alphas=new Map;betas=new Map;sample(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return this.sampleBeta(t,r)}update(e,t){t?this.alphas.set(e,(this.alphas.get(e)??1)+1):this.betas.set(e,(this.betas.get(e)??1)+1)}getMean(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t/(t+r)}getObservationCount(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t-1+(r-1)}getAlpha(e){return this.alphas.get(e)??1}getBeta(e){return this.betas.get(e)??1}sampleBeta(e,t){let r=this.sampleGamma(e),n=this.sampleGamma(t);return r+n===0?.5:r/(r+n)}sampleGamma(e){if(e<1){let n=Math.random();return this.sampleGamma(e+1)*Math.pow(n,1/e)}let t=e-1/3,r=1/Math.sqrt(9*t);for(;;){let n,a;do n=this.standardNormal(),a=1+r*n;while(a<=0);a=a*a*a;let s=Math.random();if(s<1-.0331*n*n*n*n||Math.log(s)<.5*n*n+t*(1-a+Math.log(a)))return t*a}}standardNormal(){let e=Math.random(),t=Math.random();return Math.sqrt(-2*Math.log(e||1e-10))*Math.cos(2*Math.PI*t)}};var I={threshold:5,slack:.5,resetOnAlarm:!0,warmupSamples:20},h=class{config;states=new Map;constructor(e={}){this.config={...I,...e}}update(e,t){let r=this.getOrCreateState(e);if(r.samplesSinceReset++,r.mu===null)return r.warmupSum+=t,r.warmupCount++,r.warmupCount>=this.config.warmupSamples&&(r.mu=r.warmupSum/r.warmupCount),{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:r.samplesSinceReset};r.sPlus=Math.max(0,r.sPlus+(t-r.mu-this.config.slack)),r.sMinus=Math.max(0,r.sMinus+(-t+r.mu-this.config.slack));let n=Math.max(r.sPlus,r.sMinus),a=!1,s="none";r.sPlus>this.config.threshold?(a=!0,s="positive"):r.sMinus>this.config.threshold&&(a=!0,s="negative");let c={driftDetected:a,cumulativeSum:n,direction:s,samplesSinceReset:r.samplesSinceReset};return a&&this.config.resetOnAlarm&&(r.sPlus=0,r.sMinus=0,r.samplesSinceReset=0),c}reset(e){e?this.states.delete(e):this.states.clear()}getState(e){let t=this.states.get(e);if(!t)return{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:0};let r=Math.max(t.sPlus,t.sMinus),n="none";return t.sPlus>this.config.threshold?n="positive":t.sMinus>this.config.threshold&&(n="negative"),{driftDetected:t.sPlus>this.config.threshold||t.sMinus>this.config.threshold,cumulativeSum:r,direction:n,samplesSinceReset:t.samplesSinceReset}}getOrCreateState(e){let t=this.states.get(e);return t||(t={sPlus:0,sMinus:0,samplesSinceReset:0,warmupSum:0,warmupCount:0,mu:null},this.states.set(e,t)),t}};var w=g.create("domain-transfer"),V={minTransferProbability:.3,explorationWarmup:5,verification:{},maxHistorySize:1e3,useMetaLearningEnhancements:!0},v=class{constructor(e=100){this.decayThreshold=e}decayThreshold;getDecayMultiplier(e){return e<=0?1:Math.pow(.5,e/this.decayThreshold)}applyDecay(e,t,r){return t+(e-t)*this.getDecayMultiplier(r)}},y=class{cusum;outcomes=[];windowSize;constructor(e=20){this.windowSize=e,this.cusum=new h({threshold:3,slack:.1,resetOnAlarm:!1,warmupSamples:Math.min(10,Math.floor(e/2))})}record(e){this.outcomes.push(e),this.outcomes.length>this.windowSize*2&&this.outcomes.splice(0,this.outcomes.length-this.windowSize*2);let t=this.getCurrentRate();this.cusum.update("learn",t)}isPlateaued(){return this.outcomes.length<this.windowSize?!1:!this.cusum.getState("learn").driftDetected}getCurrentRate(){if(this.outcomes.length===0)return 0;let e=this.outcomes.slice(-this.windowSize);return e.filter(Boolean).length/e.length}getOutcomeCount(){return this.outcomes.length}getCusumState(){return this.cusum.getState("learn")}},D=class{front=[];dominates(e,t){let r=e.successRate>=t.successRate&&e.speed>=t.speed&&e.confidence>=t.confidence,n=e.successRate>t.successRate||e.speed>t.speed||e.confidence>t.confidence;return r&&n}add(e){for(let t=this.front.length-1;t>=0;t--)this.dominates(e,this.front[t])&&this.front.splice(t,1);this.front.some(t=>this.dominates(t,e))||this.front.push(e)}getFront(){return[...this.front]}isNonDominated(e){return!this.front.some(t=>this.dominates(t,e))}},C=class{constructor(e=.2){this.bonusScale=e}bonusScale;triedPairs=new Set;markTried(e){this.triedPairs.add(e)}isTried(e){return this.triedPairs.has(e)}getBonus(e){return this.triedPairs.has(e)?0:this.bonusScale}apply(e,t){return Math.min(1,e+this.getBonus(t))}getTriedCount(){return this.triedPairs.size}},P=class{config;sampler;verifier;coherenceGate;transferHistory=[];affinityScores=new Map;performanceProvider=null;transferExecutor=null;nativeModule=null;decayingBeta;plateauDetector;paretoFront;curiosityBonus;constructor(e={}){this.config={...V,...e},this.sampler=new p,this.verifier=M(this.config.verification),this.coherenceGate=R(),this.decayingBeta=new v,this.plateauDetector=new y,this.paretoFront=new D,this.curiosityBonus=new C,this.tryLoadNativeModule()}evaluateTransfer(e,t){if(!this.isEnabled())return this.createRejectedCandidate(e,t);let r=this.makePairKey(e,t),n=this.sampler.sample(r),s=this.sampler.getObservationCount(r)<this.config.explorationWarmup,c=this.getAffinityScore(e,t);if(this.isMetaLearningEnabled()){let u=this.sampler.getMean(r),m=this.sampler.getAlpha(r)-1;n=this.decayingBeta.applyDecay(n,u,m),n=this.curiosityBonus.apply(n,r)}return{sourceDomain:e,targetDomain:t,sampledProbability:n,affinityScore:c,isExploration:s,pairKey:r}}executeTransfer(e){let t=`transfer-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r=this.coherenceGate.validateTransfer({domain:e.sourceDomain},e.targetDomain);if(!r.approved)return w.info("Transfer blocked by coherence gate",{transferId:t,source:e.sourceDomain,target:e.targetDomain,reason:r.rejectionReason}),this.createBlockedResult(t,e,r);let n=this.getPerformanceSnapshot(e.sourceDomain),a=this.getPerformanceSnapshot(e.targetDomain),s=this.computeSqrtDampening(e),c=this.doTransfer(e.sourceDomain,e.targetDomain,s),u=this.getPerformanceSnapshot(e.sourceDomain),m=this.getPerformanceSnapshot(e.targetDomain),i=this.verifier.verifyTransfer({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m}),f=c&&i.passed;if(this.sampler.update(e.pairKey,f),this.updateAffinityScore(e.pairKey,f),this.isMetaLearningEnabled()){this.plateauDetector.record(f),this.curiosityBonus.markTried(e.pairKey);let F=this.sampler.getMean(e.pairKey);this.paretoFront.add({pairKey:e.pairKey,successRate:F,speed:1/(1+s),confidence:this.getAffinityScore(e.sourceDomain,e.targetDomain)})}return this.addToHistory({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,success:f,sampledProbability:e.sampledProbability,dampeningFactor:s,sourceDelta:i.sourceDelta,targetDelta:i.targetDelta,timestamp:Date.now()}),w.info("Transfer completed",{transferId:t,source:e.sourceDomain,target:e.targetDomain,success:f,dampeningFactor:s.toFixed(4),sourceDelta:i.sourceDelta.toFixed(4),targetDelta:i.targetDelta.toFixed(4)}),{transferId:t,candidate:e,success:f,dampeningFactor:s,verification:i,coherenceResult:r,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m,timestamp:Date.now()}}getAffinityScore(e,t){return this.affinityScores.get(this.makePairKey(e,t))??.5}getTransferHistory(){return[...this.transferHistory]}getExpectedSuccessRate(e,t){return this.sampler.getMean(this.makePairKey(e,t))}getObservationCount(e,t){return this.sampler.getObservationCount(this.makePairKey(e,t))}setPerformanceProvider(e){this.performanceProvider=e}setTransferExecutor(e){this.transferExecutor=e}getSampler(){return this.sampler}getCoherenceGate(){return this.coherenceGate}getDecayingBeta(){return this.decayingBeta}getPlateauDetector(){return this.plateauDetector}getParetoFront(){return this.paretoFront}getCuriosityBonus(){return this.curiosityBonus}isLearningPlateaued(){return this.plateauDetector.isPlateaued()}isEnabled(){return l().useCrossDomainTransfer===!0}isMetaLearningEnabled(){return this.config.useMetaLearningEnhancements===!0&&l().useMetaLearningEnhancements!==!1}makePairKey(e,t){return`${e}->${t}`}computeSqrtDampening(e){let t=this.sampler.getObservationCount(e.pairKey);return Math.sqrt(t/(t+this.config.explorationWarmup))}doTransfer(e,t,r){return this.transferExecutor?this.transferExecutor(e,t,r):!0}getPerformanceSnapshot(e){return this.performanceProvider?this.performanceProvider(e):{domain:e,successRate:.5,avgConfidence:.5,patternCount:0,timestamp:Date.now()}}updateAffinityScore(e,t){let r=this.affinityScores.get(e)??.5;this.affinityScores.set(e,.2*(t?1:0)+.8*r)}addToHistory(e){for(this.transferHistory.push(e);this.transferHistory.length>this.config.maxHistorySize;)this.transferHistory.shift()}createBlockedResult(e,t,r){let n={domain:"",successRate:0,avgConfidence:0,patternCount:0,timestamp:Date.now()};return{transferId:e,candidate:t,success:!1,dampeningFactor:0,verification:{passed:!1,sourceStable:!1,targetImproved:!1,sourceDelta:0,targetDelta:0,sourceConfidenceDelta:0,targetConfidenceDelta:0,failureReason:`Coherence gate rejected: ${r.rejectionReason??"unknown"}`},coherenceResult:r,sourcePerformanceBefore:{...n,domain:t.sourceDomain},sourcePerformanceAfter:{...n,domain:t.sourceDomain},targetPerformanceBefore:{...n,domain:t.targetDomain},targetPerformanceAfter:{...n,domain:t.targetDomain},timestamp:Date.now()}}createRejectedCandidate(e,t){return{sourceDomain:e,targetDomain:t,sampledProbability:0,affinityScore:0,isExploration:!1,pairKey:this.makePairKey(e,t)}}tryLoadNativeModule(){this.nativeModule=null}};function J(o){return new P(o)}export{h as a,p as b,V as c,v as d,y as e,D as f,C as g,P as h,J as i};
@@ -1,15 +0,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.14.4");process.exit(0)}
2
- import{h as o,k as l,o as h}from"./chunk-55RWDRJD.js";import{a as m}from"./chunk-NA7B2QYB.js";import{c as s}from"./chunk-Y3MW3YBC.js";import{a as r,e as u}from"./chunk-BFP7KO7P.js";h();u();m();var c=s.create("hybrid-backend"),d=class{unifiedMemory=null;config;cleanupInterval;cleanupCount=0;initialized=!1;constructor(e){this.config={sqlite:{path:e?.sqlite?.path??".agentic-qe/memory.db",walMode:e?.sqlite?.walMode??!0,poolSize:e?.sqlite?.poolSize??5,busyTimeout:e?.sqlite?.busyTimeout??r.BUSY_TIMEOUT_MS,...e?.sqlite},agentdb:{path:e?.agentdb?.path??".agentic-qe/memory.db",...e?.agentdb},enableFallback:e?.enableFallback??!0,defaultNamespace:e?.defaultNamespace??"default",cleanupInterval:e?.cleanupInterval??r.CLEANUP_INTERVAL_MS}}async initialize(e){if(this.initialized)return;let i=e?.signal;i?.throwIfAborted();let t={dbPath:this.config.sqlite.path??o.dbPath,walMode:this.config.sqlite.walMode??!0,busyTimeout:this.config.sqlite.busyTimeout??r.BUSY_TIMEOUT_MS};this.unifiedMemory=l(t),i?.throwIfAborted(),await this.unifiedMemory.initialize({signal:i}),i?.throwIfAborted(),this.cleanupInterval=setInterval(()=>this.cleanup(),this.config.cleanupInterval),this.cleanupInterval.unref&&this.cleanupInterval.unref(),this.initialized=!0,console.log(`[HybridBackend] Initialized with unified memory: ${this.unifiedMemory.getDbPath()}`)}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.initialized=!1}async set(e,i,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;await this.unifiedMemory.kvSet(e,i,n,t?.ttl)}async get(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvGet(e,t)}async delete(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace,n=await this.unifiedMemory.kvDelete(e,t),a=await this.unifiedMemory.vectorDelete(e);return n||a}async has(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvExists(e,t)}async search(e,i=100,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvSearch(e,n,i)}async vectorSearch(e,i,t){return this.ensureInitialized(),(await this.unifiedMemory.vectorSearch(e,i,void 0,t)).map(a=>({key:a.id,score:a.score,metadata:a.metadata}))}getVectorSearchProvenance(){return this.ensureInitialized(),this.unifiedMemory.getVectorSearchProvenance()}async storeVector(e,i,t){this.ensureInitialized(),await this.unifiedMemory.vectorStore(e,i,this.config.defaultNamespace,t)}getHealth(){return{sqlite:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",sqlitePersistent:!0,agentdb:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",fallback:"inactive"}}isPersistent(){return this.unifiedMemory?.isInitialized()??!1}getConfig(){return{...this.config}}async setWithBackend(e,i,t,n){await this.set(e,i,n)}async getVectorStats(){if(!this.unifiedMemory?.isInitialized())return null;let e=await this.unifiedMemory.vectorCount(),i=this.unifiedMemory.getStats();return{vectorCount:e,indexSize:i.vectorIndexSize}}getUnifiedMemory(){return this.unifiedMemory}async count(e){return this.ensureInitialized(),this.unifiedMemory.getDatabase().prepare(`
3
- SELECT COUNT(*) as count FROM kv_store
4
- WHERE namespace LIKE ?
5
- AND (expires_at IS NULL OR expires_at > ?)
6
- `).get(`${e}%`,Date.now()).count}async hasCodeIntelligenceIndex(){return this.ensureInitialized(),this.unifiedMemory.getDatabase().prepare(`
7
- SELECT 1 FROM kv_store
8
- WHERE namespace = 'code-intelligence:kg'
9
- AND (expires_at IS NULL OR expires_at > ?)
10
- LIMIT 1
11
- `).get(Date.now())!==void 0}ensureInitialized(){if(!this.initialized||!this.unifiedMemory)throw new Error("HybridMemoryBackend not initialized. Call initialize() first.")}async cleanup(){if(this.unifiedMemory?.isInitialized())try{await this.unifiedMemory.kvCleanupExpired();let e=this.unifiedMemory.getDatabase();try{let i=e.prepare("DELETE FROM kv_store WHERE expires_at IS NOT NULL AND expires_at < ?").run(Date.now());i.changes>0&&console.log(`[HybridBackend] Expired ${i.changes} kv_store entries`)}catch(i){c.debug("TTL expiration cleanup failed",{error:i instanceof Error?i.message:String(i)})}if(this.cleanupCount++,this.cleanupCount%10===0)try{if(e.prepare("SELECT COUNT(*) as cnt FROM kv_store").get().cnt>5e3){let t=e.prepare(`
12
- DELETE FROM kv_store WHERE rowid NOT IN (
13
- SELECT rowid FROM kv_store ORDER BY rowid DESC LIMIT 5000
14
- )
15
- `).run();t.changes>0&&console.log(`[HybridBackend] kv_store retention: pruned ${t.changes} rows (kept 5000)`)}}catch(i){c.debug("KV store retention pruning failed",{error:i instanceof Error?i.message:String(i)})}}catch(e){console.warn("[HybridBackend] Cleanup failed:",e)}}};export{d as a};
@@ -1,27 +0,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.14.4");process.exit(0)}
2
- import{b as f}from"./chunk-TPGED2IF.js";import{k as g,o as A}from"./chunk-55RWDRJD.js";A();import{createHash as m}from"crypto";var y="0".repeat(64);function R(a){return m("sha256").update(a,"utf-8").digest("hex")}function b(a){try{return m("shake256",{outputLength:32}).update(a,"utf-8").digest("hex")}catch{return R(a)}}function l(a,t){return a==="shake256"?b(t):R(t)}function T(a){return JSON.stringify({id:a.id,prev_hash:a.prev_hash,action_hash:a.action_hash,action_type:a.action_type,action_data:a.action_data,timestamp:a.timestamp,actor:a.actor})}var _=class{constructor(t,i){this.externalDb=t;this.keyManager=i??null}externalDb;db=null;initialized=!1;keyManager=null;async initialize(){if(!this.initialized){if(this.externalDb)this.db=this.externalDb;else{let t=g();await t.initialize(),this.db=t.getDatabase()}this.ensureTable(),this.initialized=!0}}getDatabase(){return this.db}getKeyManager(){return this.keyManager}ensureTable(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
3
- CREATE TABLE IF NOT EXISTS witness_chain (
4
- id INTEGER PRIMARY KEY AUTOINCREMENT,
5
- prev_hash TEXT NOT NULL, action_hash TEXT NOT NULL, action_type TEXT NOT NULL,
6
- action_data TEXT, timestamp TEXT NOT NULL, actor TEXT NOT NULL,
7
- hash_algo TEXT DEFAULT 'sha256', signature TEXT, signer_key_id TEXT
8
- );
9
- CREATE INDEX IF NOT EXISTS idx_witness_action_type ON witness_chain(action_type);
10
- CREATE INDEX IF NOT EXISTS idx_witness_timestamp ON witness_chain(timestamp);
11
- CREATE INDEX IF NOT EXISTS idx_witness_actor ON witness_chain(actor);
12
- `),this.addColumnIfMissing("hash_algo","TEXT DEFAULT 'sha256'"),this.addColumnIfMissing("signature","TEXT"),this.addColumnIfMissing("signer_key_id","TEXT"),this.db.exec(`
13
- CREATE TABLE IF NOT EXISTS witness_chain_archive (
14
- id INTEGER PRIMARY KEY,
15
- prev_hash TEXT NOT NULL, action_hash TEXT NOT NULL, action_type TEXT NOT NULL,
16
- action_data TEXT, timestamp TEXT NOT NULL, actor TEXT NOT NULL,
17
- hash_algo TEXT DEFAULT 'sha256', signature TEXT, signer_key_id TEXT,
18
- archived_at TEXT NOT NULL
19
- );
20
- `)}addColumnIfMissing(t,i){if(!this.db)return;this.db.prepare("SELECT name FROM pragma_table_info('witness_chain')").all().some(s=>s.name===t)||this.db.exec(`ALTER TABLE witness_chain ADD COLUMN ${t} ${i}`)}append(t,i,e){if(!this.db)throw new Error("WitnessChain not initialized");let s=new Date().toISOString(),o=JSON.stringify(i),h="shake256",c=b(o),n=this.db.prepare("SELECT * FROM witness_chain ORDER BY id DESC LIMIT 1").get(),r=n?l(h,T(n)):y,E=null,u=null;if(this.keyManager){let N=Buffer.from(r+c+t+s+e,"utf-8"),p=this.keyManager.sign(N);E=p.signature.toString("hex"),u=p.keyId}return{id:this.db.prepare(`INSERT INTO witness_chain
21
- (prev_hash, action_hash, action_type, action_data, timestamp, actor, hash_algo, signature, signer_key_id)
22
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(r,c,t,o,s,e,h,E,u).lastInsertRowid,prev_hash:r,action_hash:c,action_type:t,action_data:o,timestamp:s,actor:e,hash_algo:h,signature:E,signer_key_id:u}}findEntryById(t){if(this.db)return this.db.prepare("SELECT * FROM witness_chain WHERE id = ?").get(t)??this.db.prepare("SELECT * FROM witness_chain_archive WHERE id = ?").get(t)}checkEntryLink(t,i){let e=t.hash_algo||"sha256";if(t.action_hash!==l(e,t.action_data))return!1;if(t.id===1)return t.prev_hash===y;if(i&&t.prev_hash===l(e,T(i)))return!0;let s=this.findEntryById(t.id-1);return s!==void 0&&t.prev_hash===l(e,T(s))}verify(t){if(!this.db)throw new Error("WitnessChain not initialized");let i=this.db.prepare("SELECT * FROM witness_chain ORDER BY id ASC").all();if(i.length===0)return{valid:!0,entriesChecked:0};let e=0,s=t?.checkSignatures===!0&&this.keyManager!==null,o=n=>{if(s&&n.signature&&n.signer_key_id){let r=Buffer.from(n.prev_hash+n.action_hash+n.action_type+n.timestamp+n.actor,"utf-8");this.keyManager.verify(Buffer.from(r),Buffer.from(n.signature,"hex"),n.signer_key_id)||e++}};for(let n=0;n<i.length;n++){let r=i[n];if(!this.checkEntryLink(r,n>0?i[n-1]:void 0))return{valid:!1,brokenAt:r.id,entriesChecked:n+1,signatureFailures:e};o(r)}let h=i.length;if(t?.includeArchive){let n=this.db.prepare("SELECT * FROM witness_chain_archive ORDER BY id ASC").all();for(let r=0;r<n.length;r++){let E=n[r];if(!this.checkEntryLink(E,r>0?n[r-1]:void 0))return{valid:!1,brokenAt:E.id,entriesChecked:h+r+1,signatureFailures:e};o(E)}h+=n.length}return{valid:e===0,entriesChecked:h,signatureFailures:e,...e>0?{brokenAt:i[0].id}:{}}}getEntries(t){if(!this.db)throw new Error("WitnessChain not initialized");let i=[],e=[];t?.action_type&&(i.push("action_type = ?"),e.push(t.action_type)),t?.since&&(i.push("timestamp >= ?"),e.push(t.since)),t?.until&&(i.push("timestamp <= ?"),e.push(t.until)),t?.actor&&(i.push("actor = ?"),e.push(t.actor));let s=i.length>0?`WHERE ${i.join(" AND ")}`:"",o=t?.limit!=null,h=t?.offset!=null,c=o||h?"LIMIT ?":"",n=h?"OFFSET ?":"";return o?e.push(t.limit):h&&e.push(-1),h&&e.push(t.offset),this.db.prepare(`SELECT * FROM witness_chain ${s} ORDER BY id ASC ${c} ${n}`).all(...e)}getPatternLineage(t){if(!this.db)throw new Error("WitnessChain not initialized");return this.db.prepare(`SELECT * FROM witness_chain
23
- WHERE json_extract(action_data, '$.patternId') = ? OR json_extract(action_data, '$.pattern_id') = ?
24
- ORDER BY id ASC`).all(t,t)}getActorHistory(t,i){if(!this.db)throw new Error("WitnessChain not initialized");return i?this.db.prepare("SELECT * FROM witness_chain WHERE actor = ? AND timestamp >= ? ORDER BY id ASC").all(t,i):this.db.prepare("SELECT * FROM witness_chain WHERE actor = ? ORDER BY id ASC").all(t)}archiveEntries(t){if(!this.db)throw new Error("WitnessChain not initialized");let i=new Date().toISOString(),s=this.db.prepare(`INSERT INTO witness_chain_archive
25
- (id, prev_hash, action_hash, action_type, action_data, timestamp, actor, hash_algo, signature, signer_key_id, archived_at)
26
- SELECT id, prev_hash, action_hash, action_type, action_data, timestamp, actor, hash_algo, signature, signer_key_id, ?
27
- FROM witness_chain WHERE timestamp < ? AND id > 1 AND id NOT IN (SELECT id FROM witness_chain_archive)`).run(i,t).changes;return s>0&&this.db.prepare("DELETE FROM witness_chain WHERE timestamp < ? AND id > 1").run(t),{archived:s}}crossVerifyWithRvf(t){let i=this.verify(),e=t.status(),s=e.witnessValid===!0,o=typeof e.witnessEntries=="number"?e.witnessEntries:0;return{sqliteValid:i.valid,rvfValid:s,rvfEntries:o,bothValid:i.valid&&s}}getChainLength(){if(!this.db)throw new Error("WitnessChain not initialized");return this.db.prepare("SELECT COUNT(*) as count FROM witness_chain").get().count}},d=null;async function I(){return d||(d=new _(void 0,f()),await d.initialize()),d}function S(a,t){return new _(a,t)}function w(){d=null}export{y as a,R as b,b as c,l as d,T as e,_ as f,I as g,S as h,w as i};
@@ -1,5 +0,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.14.4");process.exit(0)}
2
- import{a as v,b as I,c as D}from"./chunk-G6T45OIC.js";var M={reflexThreshold:.1,retrievalThreshold:.4,heavyThreshold:.7},N={enabled:!0,laneConfig:M,coherenceThreshold:.1,fallbackEnabled:!0,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},p={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},b=class extends Error{constructor(t,i,n){super(t);this.code=i;this.cause=n;this.name="CoherenceError"}code;cause},h=class extends b{constructor(e="WASM module is not loaded",t){super(e,"WASM_NOT_LOADED",t),this.name="WasmNotLoadedError"}};var k=class extends b{constructor(t,i,n){super(t,"WASM_LOAD_FAILED",n);this.attempts=i;this.name="WasmLoadError"}attempts},$={maxAttempts:3,baseDelayMs:100,maxDelayMs:5e3,timeoutMs:1e4};D();var O=4*1024*1024,q=32*1024*1024;function G(u){let e=new Map,t=[],i=new Map,n=new Map,r=0,a=o=>{let l=i.get(o);return l===void 0&&(l=r++,i.set(o,l),n.set(l,o)),l},s=o=>n.get(o)??`unknown-${o}`;function*d(){i.clear(),n.clear(),r=0;let o=e.values().next().value?.embedding.length,l=Array.from(e.entries()).map(([g,y])=>{if(y.embedding.length!==o)throw new RangeError("Cohomology graphs require matching embedding dimensions");return{id:a(g),label:g,section:Array.from(y.embedding),weight:1}}),c=0,m=t.map(g=>{let y=e.get(g.source),C=e.get(g.target);if(!y||!C)throw new Error(`Cohomology edge references an unknown node: ${g.source} -> ${g.target}`);let P=y.embedding.length,F=P*P;if(F>O)throw new RangeError(`Cohomology restriction map exceeds ${O} cells`);if(c+=F,c>q)throw new RangeError(`Cohomology graph exceeds ${q} restriction-map cells`);return{...g,dimension:P,cells:F}}),f=[],W=0,z=new Map;for(let g of m){W+g.cells>O&&(yield{nodes:l,edges:f},f=[],W=0,z.clear());let y=z.get(g.dimension);if(!y){y=Array(g.cells).fill(0);for(let C=0;C<g.dimension;C++)y[C*g.dimension+C]=1;z.set(g.dimension,y)}f.push({source:i.get(g.source),target:i.get(g.target),weight:g.weight,restriction_map:y,source_dim:g.dimension,target_dim:g.dimension}),W+=g.cells}(f.length>0||m.length===0)&&(yield{nodes:l,edges:f})}return{add_node(o,l){e.set(o,{embedding:l}),a(o)},add_edge(o,l,c){t.push({source:o,target:l,weight:c}),a(o),a(l)},remove_node(o){e.delete(o);for(let l=t.length-1;l>=0;l--)(t[l].source===o||t[l].target===o)&&t.splice(l,1)},remove_edge(o,l){let c=t.findIndex(m=>m.source===o&&m.target===l);c>=0&&t.splice(c,1)},sheaf_laplacian_energy(){let o=0;for(let l of d())o+=u.consistencyEnergy(l);return o},detect_contradictions(o){let l=[];for(let c of d()){let m=u.detectObstructions(c);for(let f of m??[])f.magnitude>o&&l.push({node1:s(f.source_node),node2:s(f.target_node),severity:f.magnitude,distance:f.magnitude})}return l.sort((c,m)=>m.distance-c.distance)},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var w=class{constructor(e,t=p){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;nodes=new Map;edges=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CohomologyAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CohomologyAdapter.");let t=await this.wasmLoader.load(),i=new t.CohomologyEngine;this.engine=G(i),this.initialized=!0,this.logger.info("CohomologyAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CohomologyAdapter not initialized. Call initialize() first.")}addNode(e){this.ensureInitialized(),this.nodes.set(e.id,e);let t=new Float64Array(e.embedding);this.engine.add_node(e.id,t),this.logger.debug("Added node to cohomology graph",{nodeId:e.id,embeddingDim:e.embedding.length})}addEdge(e){this.ensureInitialized(),this.edges.push(e),this.engine.add_edge(e.source,e.target,e.weight),this.logger.debug("Added edge to cohomology graph",{source:e.source,target:e.target,weight:e.weight})}removeNode(e){this.ensureInitialized(),this.nodes.delete(e),this.engine.remove_node(e);let t=[];this.edges.forEach((i,n)=>{(i.source===e||i.target===e)&&t.push(n)}),t.reverse().forEach(i=>this.edges.splice(i,1)),this.logger.debug("Removed node from cohomology graph",{nodeId:e})}removeEdge(e,t){this.ensureInitialized();let i=this.edges.findIndex(n=>n.source===e&&n.target===t);i>=0&&this.edges.splice(i,1),this.engine.remove_edge(e,t),this.logger.debug("Removed edge from cohomology graph",{source:e,target:t})}computeEnergy(){this.ensureInitialized();let e=this.engine.sheaf_laplacian_energy();return this.logger.debug("Computed sheaf Laplacian energy",{energy:e}),e}detectContradictions(e=.1){this.ensureInitialized();let i=this.engine.detect_contradictions(e).map(n=>this.transformContradiction(n));return this.logger.debug("Detected contradictions",{count:i.length,threshold:e}),i}transformContradiction(e){return{nodeIds:[e.node1,e.node2],severity:this.severityFromDistance(e.severity),description:this.generateContradictionDescription(e),confidence:Math.max(0,1-e.distance),resolution:this.suggestResolution(e)}}severityFromDistance(e){return e>=.9?"critical":e>=.7?"high":e>=.4?"medium":e>=.2?"low":"info"}generateContradictionDescription(e){let t=this.nodes.get(e.node1),i=this.nodes.get(e.node2);return t?.metadata?.statement&&i?.metadata?.statement?`Contradiction detected between "${t.metadata.statement}" and "${i.metadata.statement}"`:`Contradiction detected between nodes '${e.node1}' and '${e.node2}' with distance ${e.distance.toFixed(3)}`}suggestResolution(e){return e.severity>=.9?"Critical contradiction requires manual review. Consider removing one of the conflicting beliefs.":e.severity>=.7?"High-severity contradiction. Recommend gathering additional evidence to determine which belief is correct.":e.severity>=.4?"Moderate contradiction. Consider adding context or constraints to differentiate the beliefs.":"Low-severity contradiction. May be resolved with additional context or can be safely ignored."}clear(){this.ensureInitialized(),this.nodes.clear(),this.edges.length=0,this.engine.clear(),this.logger.debug("Cleared cohomology graph")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.nodes.clear(),this.edges.length=0,this.initialized=!1,this.logger.info("CohomologyAdapter disposed")}getNodeCount(){return this.nodes.size}getEdgeCount(){return this.edges.length}getNode(e){return this.nodes.get(e)}};D();function j(u){let e=new Set,t=[],i=new Map,n=new Map,r=0,a=o=>{let l=i.get(o);return l===void 0&&(l=r++,i.set(o,l),n.set(l,o)),l},s=o=>n.get(o)??`unknown-${o}`,d=()=>({n:e.size,edges:t.map(o=>[a(o.source),a(o.target),o.weight])});return{add_node(o){e.add(o),a(o)},add_edge(o,l,c){t.push({source:o,target:l,weight:c}),a(o),a(l)},remove_node(o){e.delete(o);for(let l=t.length-1;l>=0;l--)(t[l].source===o||t[l].target===o)&&t.splice(l,1)},compute_fiedler_value(){if(e.size<2||t.length===0)return 0;try{let o=d(),l=u.algebraicConnectivity(o);return Number.isFinite(l)&&l>=0?l:0}catch(o){return console.warn("[SpectralAdapter] algebraicConnectivity failed:",o),0}},predict_collapse_risk(){if(e.size<2)return 0;if(t.length===0)return 1;try{let o=d(),l=u.algebraicConnectivity(o),c=Number.isFinite(l)&&l>=0?l:0;return Math.max(0,Math.min(1,1-c))}catch(o){return console.warn("[SpectralAdapter] predict_collapse_risk failed:",o),.8}},get_weak_vertices(o){if(e.size===0)return[];if(t.length===0)return Array.from(e).slice(0,o);try{let l=d(),c=u.predictMinCut(l);return c?.vertices?c.vertices.slice(0,o).map(m=>s(m)):Array.from(e).slice(0,o)}catch(l){return console.warn("[SpectralAdapter] predictMinCut failed:",l),Array.from(e).slice(0,o)}},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var E=class{constructor(e,t=p){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;nodes=new Set;edges=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing SpectralAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize SpectralAdapter.");let t=await this.wasmLoader.load(),i=new t.SpectralEngine;this.engine=j(i),this.initialized=!0,this.logger.info("SpectralAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("SpectralAdapter not initialized. Call initialize() first.")}addNode(e){if(this.ensureInitialized(),this.nodes.has(e)){this.logger.debug("Node already exists",{nodeId:e});return}this.nodes.add(e),this.engine.add_node(e),this.logger.debug("Added node to spectral graph",{nodeId:e})}addEdge(e,t,i){this.ensureInitialized(),this.nodes.has(e)||this.addNode(e),this.nodes.has(t)||this.addNode(t),this.edges.push({source:e,target:t,weight:i}),this.engine.add_edge(e,t,i),this.logger.debug("Added edge to spectral graph",{source:e,target:t,weight:i})}removeNode(e){this.ensureInitialized(),this.nodes.delete(e),this.engine.remove_node(e);for(let t=this.edges.length-1;t>=0;t--){let i=this.edges[t];(i.source===e||i.target===e)&&this.edges.splice(t,1)}this.logger.debug("Removed node from spectral graph",{nodeId:e})}computeFiedlerValue(){if(this.ensureInitialized(),this.nodes.size<2||this.edges.length===0)return 0;try{let e=this.engine.compute_fiedler_value();return this.logger.debug("Computed Fiedler value",{fiedlerValue:e}),e}catch(e){return this.logger.warn("Failed to compute Fiedler value",{error:v(e),nodeCount:this.nodes.size,edgeCount:this.edges.length}),0}}predictCollapseRisk(){if(this.ensureInitialized(),this.nodes.size<2)return 0;if(this.edges.length===0)return 1;try{let e=this.engine.predict_collapse_risk();return this.logger.debug("Predicted collapse risk",{risk:e}),e}catch(e){return this.logger.warn("Failed to predict collapse risk",{error:v(e),nodeCount:this.nodes.size,edgeCount:this.edges.length}),.8}}getWeakVertices(e){if(this.ensureInitialized(),this.nodes.size===0)return[];if(this.edges.length===0)return Array.from(this.nodes).slice(0,e);let t=Math.min(e,this.nodes.size);try{let i=this.engine.get_weak_vertices(t);return this.logger.debug("Retrieved weak vertices",{requested:e,returned:i.length}),i}catch(i){return this.logger.warn("Failed to get weak vertices",{error:v(i),nodeCount:this.nodes.size,edgeCount:this.edges.length}),Array.from(this.nodes).slice(0,e)}}analyzeSwarmState(e){let t=Date.now();this.clear();for(let d of e.agents)this.addNode(d.agentId);this.buildEdgesFromAgents(e.agents);let i=this.predictCollapseRisk(),n=this.computeFiedlerValue(),r=this.getWeakVertices(5),a=Date.now()-t,s={risk:i,fiedlerValue:n,collapseImminent:i>.7,weakVertices:r,recommendations:this.generateRecommendations(i,n,r),durationMs:a,usedFallback:!1};return this.logger.info("Analyzed swarm state",{agentCount:e.agents.length,risk:i,fiedlerValue:n,durationMs:a}),s}buildEdgesFromAgents(e){for(let t=0;t<e.length;t++)for(let i=t+1;i<e.length;i++){let n=this.computeAgentSimilarity(e[t],e[i]);n>.3&&this.addEdge(e[t].agentId,e[i].agentId,n)}}computeAgentSimilarity(e,t){let i=1-Math.abs(e.health-t.health),n=1-Math.abs(e.successRate-t.successRate),r=e.agentType===t.agentType?.2:0,a=0,s=e.beliefs??[],d=t.beliefs??[];return s.length>0&&d.length>0&&(a=this.computeBeliefOverlap(s,d)),i*.3+n*.3+r+a*.2}computeBeliefOverlap(e,t){if(e.length===0||t.length===0)return 0;let i=0,n=0;for(let r of e)for(let a of t)i+=this.cosineSimilarity(r.embedding,a.embedding),n++;return n>0?i/n:0}cosineSimilarity(e,t){if(e.length!==t.length||e.length===0)return 0;let i=0,n=0,r=0;for(let s=0;s<e.length;s++)i+=e[s]*t[s],n+=e[s]*e[s],r+=t[s]*t[s];let a=Math.sqrt(n)*Math.sqrt(r);return a===0?0:i/a}generateRecommendations(e,t,i){let n=[];return e>.7?(n.push("CRITICAL: Immediate action required to prevent swarm collapse."),n.push("Consider spawning additional coordination agents to strengthen connectivity.")):e>.5&&n.push("WARNING: Elevated collapse risk detected. Monitor closely."),t<.1&&n.push("Network connectivity is weak. Consider adding redundant communication channels."),t<.05&&(n.push("ALERT: Near-zero Fiedler value indicates potential false consensus."),n.push("Recommend spawning an independent reviewer to verify decisions.")),i.length>0&&n.push(`At-risk agents: ${i.join(", ")}. Consider reassigning critical tasks.`),n.length===0&&n.push("Swarm health is good. No immediate action required."),n}clear(){this.ensureInitialized(),this.nodes.clear(),this.edges.length=0,this.engine.clear(),this.logger.debug("Cleared spectral graph")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.nodes.clear(),this.edges.length=0,this.initialized=!1,this.logger.info("SpectralAdapter disposed")}getNodeCount(){return this.nodes.size}getEdgeCount(){return this.edges.length}};function Y(u){let e=null,t=null,i=new Map,n=()=>({cause:e?Array.from(e):[],effect:t?Array.from(t):[],confounders:Object.fromEntries(Array.from(i.entries()).map(([r,a])=>[r,Array.from(a)]))});return{set_data(r,a){e=r,t=a},add_confounder(r,a){i.set(r,a)},compute_causal_effect(){let r=n();return u.computeCausalEffect(r,"cause","effect",1)?.effect??0},detect_spurious_correlation(){let r=n();return(u.findConfounders(r,"cause","effect")?.length??0)>0},get_confounders(){let r=n();return u.findConfounders(r,"cause","effect")??Array.from(i.keys())},clear(){e=null,t=null,i.clear()}}}var A=class{constructor(e,t=p){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;currentCause="";currentEffect="";async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CausalAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CausalAdapter.");let t=await this.wasmLoader.load(),i=new t.CausalEngine;this.engine=Y(i),this.initialized=!0,this.logger.info("CausalAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CausalAdapter not initialized. Call initialize() first.")}verifyCausality(e,t,i){this.ensureInitialized();let n=Date.now();if(this.clear(),this.currentCause=e,this.currentEffect=t,this.setData(i.causeValues,i.effectValues),i.confounders)for(let[m,f]of Object.entries(i.confounders))this.addConfounder(m,f);let r=this.computeCausalEffect(),a=this.detectSpuriousCorrelation(),s=this.getConfounders(),d=this.determineRelationshipType(r,a,s.length>0),o=this.computeConfidence(i.sampleSize,r,a),l=Date.now()-n,c={isCausal:d==="causal",effectStrength:r,relationshipType:d,confidence:o,confounders:s,explanation:this.generateExplanation(e,t,d,r,s),durationMs:l,usedFallback:!1};return this.logger.info("Verified causality",{cause:e,effect:t,isCausal:c.isCausal,relationshipType:d,effectStrength:r,durationMs:l}),c}setData(e,t){if(this.ensureInitialized(),e.length!==t.length)throw new Error(`Cause and effect arrays must have same length. Got ${e.length} and ${t.length}.`);let i=new Float64Array(e),n=new Float64Array(t);this.engine.set_data(i,n),this.logger.debug("Set causal data",{sampleSize:e.length})}addConfounder(e,t){this.ensureInitialized();let i=new Float64Array(t);this.engine.add_confounder(e,i),this.logger.debug("Added confounder",{name:e,valueCount:t.length})}computeCausalEffect(){this.ensureInitialized();let e=this.engine.compute_causal_effect();return this.logger.debug("Computed causal effect",{effect:e}),e}detectSpuriousCorrelation(){this.ensureInitialized();let e=this.engine.detect_spurious_correlation();return this.logger.debug("Detected spurious correlation",{isSpurious:e}),e}getConfounders(){return this.ensureInitialized(),this.engine.get_confounders()}determineRelationshipType(e,t,i){return e<.1?"none":t?"spurious":i?"confounded":e<0?"reverse":"causal"}computeConfidence(e,t,i){let n=Math.min(1,e/100)*.5;return n+=Math.abs(t)*.3,i&&(n+=.15),Math.min(.95,n)}generateExplanation(e,t,i,n,r){switch(i){case"causal":return`Analysis indicates a true causal relationship between '${e}' and '${t}'. Effect strength: ${(n*100).toFixed(1)}%. Changes in '${e}' are likely to cause changes in '${t}'.`;case"spurious":return`The correlation between '${e}' and '${t}' appears to be spurious. No true causal mechanism detected. This may be coincidental or due to a hidden common cause.`;case"reverse":return`Analysis suggests reverse causation: '${t}' may cause '${e}', not the other way around. Consider swapping the direction of your hypothesis.`;case"confounded":return`The relationship between '${e}' and '${t}' is confounded by: ${r.join(", ")}. These variables may explain the observed correlation without direct causation.`;case"none":return`No significant relationship detected between '${e}' and '${t}'. Effect strength is below the detection threshold.`;default:return`Analysis complete for '${e}' -> '${t}'.`}}clear(){this.ensureInitialized(),this.engine.clear(),this.currentCause="",this.currentEffect="",this.logger.debug("Cleared causal engine state")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.initialized=!1,this.logger.info("CausalAdapter disposed")}};function Q(u){let e=new Map,t=[],i=()=>({objects:Array.from(e.entries()).map(([n,r])=>({name:n,schema:r})),morphisms:t.map(n=>({source:n.source,target:n.target,name:n.name}))});return{add_type(n,r){e.set(n,r)},add_morphism(n,r,a){t.push({source:n,target:r,name:a})},verify_composition(n){if(n.length<2)return!0;for(let a=0;a<n.length-1;a++){let s=n[a],d=n[a+1];if(!t.some(l=>l.source===s&&l.target===d))return!1}let r=i();return u.verifyCategoryLaws(r)},check_type_consistency(){let n=[];for(let r of t)e.has(r.source)||n.push({location:r.name,expected:"defined type",actual:`undefined type '${r.source}'`}),e.has(r.target)||n.push({location:r.name,expected:"defined type",actual:`undefined type '${r.target}'`});return n},clear(){e.clear(),t.length=0}}}var T=class{constructor(e,t=p){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;types=new Map;morphisms=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CategoryAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CategoryAdapter.");let t=await this.wasmLoader.load(),i=new t.CategoryEngine;this.engine=Q(i),this.initialized=!0,this.logger.info("CategoryAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CategoryAdapter not initialized. Call initialize() first.")}addType(e,t){this.ensureInitialized(),this.types.set(e,t),this.engine.add_type(e,t),this.logger.debug("Added type to category",{name:e})}addMorphism(e,t,i){this.ensureInitialized(),this.morphisms.push({source:e,target:t,name:i}),this.engine.add_morphism(e,t,i),this.logger.debug("Added morphism to category",{source:e,target:t,name:i})}verifyComposition(e){if(this.ensureInitialized(),e.length<2)return!0;let t=this.engine.verify_composition(e);return this.logger.debug("Verified composition",{path:e,isValid:t}),t}checkTypeConsistency(){this.ensureInitialized();let t=this.engine.check_type_consistency().map(i=>this.transformMismatch(i));return this.logger.debug("Checked type consistency",{mismatchCount:t.length}),t}verifyPipeline(e){let t=Date.now();this.clear(),this.addType(e.inputType,this.inferSchema(e.inputType)),this.addType(e.outputType,this.inferSchema(e.outputType));for(let o of e.elements)this.addType(o.inputType,this.inferSchema(o.inputType)),this.addType(o.outputType,this.inferSchema(o.outputType));for(let o of e.elements)this.addMorphism(o.inputType,o.outputType,o.name);let i=this.buildCompositionPath(e),n=this.verifyComposition(i),r=this.checkTypeConsistency(),a=this.generateWarnings(e,n,r),s=Date.now()-t,d={isValid:n&&r.length===0,mismatches:r,warnings:a,durationMs:s,usedFallback:!1};return this.logger.info("Verified pipeline",{pipelineId:e.id,isValid:d.isValid,mismatchCount:r.length,warningCount:a.length,durationMs:s}),d}buildCompositionPath(e){let t=[e.inputType];for(let i of e.elements)i.inputType!==t[t.length-1]&&t.push(i.inputType),t.push(i.outputType);return t[t.length-1]!==e.outputType&&t.push(e.outputType),t}inferSchema(e){return e.endsWith("[]")?`{ items: ${e.slice(0,-2)}[] }`:e.includes("|")?`{ union: [${e.split("|").map(t=>`"${t.trim()}"`).join(", ")}] }`:`{ type: "${e}" }`}transformMismatch(e){return{location:e.location,expected:e.expected,actual:e.actual,severity:this.determineMismatchSeverity(e)}}determineMismatchSeverity(e){return e.expected==="never"||e.actual==="never"?"critical":e.actual==="any"||e.actual==="unknown"?"high":e.expected.includes(e.actual)||e.actual.includes(e.expected)?"medium":"low"}generateWarnings(e,t,i){let n=[];t||n.push(`Pipeline '${e.id}' has an invalid composition chain. Types do not connect properly from input to output.`);for(let a of e.elements)(a.inputType==="any"||a.outputType==="any")&&n.push(`Element '${a.name}' uses 'any' type, which bypasses type safety.`);for(let a of e.elements)(a.inputType.includes("<T>")||a.outputType.includes("<T>"))&&n.push(`Element '${a.name}' has unconstrained generic types.`);let r=i.filter(a=>a.severity==="critical");return r.length>0&&n.push(`Found ${r.length} critical type mismatch(es) that will cause runtime errors.`),n}clear(){this.ensureInitialized(),this.types.clear(),this.morphisms.length=0,this.engine.clear(),this.logger.debug("Cleared category")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.types.clear(),this.morphisms.length=0,this.initialized=!1,this.logger.info("CategoryAdapter disposed")}getTypeCount(){return this.types.size}getMorphismCount(){return this.morphisms.length}};function K(u){let e=new Map,t=new Map;return{add_proposition(i,n){e.set(i,{formula:n,proven:!1})},add_proof(i,n){let r=e.get(i);if(!r)return!1;let a={id:i,proof:n},s={formula:r.formula};return u.typeCheck(a,s)?.valid?(r.proven=!0,t.set(i,n),!0):!1},verify_path_equivalence(i,n){let r={steps:i},a={steps:n};return u.checkTypeEquivalence(r,a)},get_unproven_propositions(){let i=[];return e.forEach((n,r)=>{n.proven||i.push(r)}),i},clear(){e.clear(),t.clear()}}}var R=class{constructor(e,t=p){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;propositions=new Map;async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing HomotopyAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize HomotopyAdapter.");let t=await this.wasmLoader.load(),i=new t.HoTTEngine;this.engine=K(i),this.initialized=!0,this.logger.info("HomotopyAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("HomotopyAdapter not initialized. Call initialize() first.")}addProposition(e,t){this.ensureInitialized();let i={id:e,formula:t,proven:!1};this.propositions.set(e,i),this.engine.add_proposition(e,t),this.logger.debug("Added proposition",{id:e,formula:t})}addProof(e,t){this.ensureInitialized();let i=this.propositions.get(e);if(!i)return this.logger.warn("Proposition not found",{propositionId:e}),!1;let n=this.engine.add_proof(e,t);return n?(i.proven=!0,this.logger.info("Proposition proven",{propositionId:e})):this.logger.warn("Proof rejected",{propositionId:e}),n}verifyPathEquivalence(e,t){this.ensureInitialized();let i=this.engine.verify_path_equivalence(e,t),n=this.generateEquivalenceExplanation(e,t,i),r={equivalent:i,path1:e,path2:t,explanation:n};return this.logger.debug("Verified path equivalence",{path1Length:e.length,path2Length:t.length,equivalent:i}),r}generateEquivalenceExplanation(e,t,i){if(i)return e.length===t.length?"The execution paths are homotopically equivalent. Both paths traverse the same abstract structure and will produce equivalent results.":`The execution paths are equivalent despite different lengths. The ${e.length>t.length?"first":"second"} path contains redundant steps that can be contracted without changing the result (homotopy contraction).`;{let n=0,r=Math.min(e.length,t.length);for(;n<r&&e[n]===t[n];)n++;return n===0?`The execution paths diverge immediately. Path 1 starts with '${e[0]}' while Path 2 starts with '${t[0]}'. These lead to fundamentally different computation spaces.`:`The execution paths diverge at step ${n+1}. After '${e[n-1]}', Path 1 proceeds to '${e[n]}' while Path 2 proceeds to '${t[n]}'. No homotopy exists between these paths.`}}getUnprovenPropositions(){return this.ensureInitialized(),this.engine.get_unproven_propositions()}getVerificationStatus(){let e=this.propositions.size,t=Array.from(this.propositions.values()).filter(n=>n.proven).length,i=this.getUnprovenPropositions();return{totalPropositions:e,provenCount:t,unprovenIds:i,verificationPercentage:e>0?t/e*100:100}}getProposition(e){return this.propositions.get(e)}clear(){this.ensureInitialized(),this.propositions.clear(),this.engine.clear(),this.logger.debug("Cleared homotopy engine")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.propositions.clear(),this.initialized=!1,this.logger.info("HomotopyAdapter disposed")}getPropositionCount(){return this.propositions.size}};import{createHash as X}from"crypto";var S=class{constructor(e,t=p){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;witnesses=new Map;decisions=new Map;witnessCounter=0;async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing WitnessAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize WitnessAdapter.");let t=await this.wasmLoader.load();this.engine=this.createWitnessEngine(t),this.initialized=!0,this.logger.info("WitnessAdapter initialized successfully")}createWitnessEngine(e){return this.createFallbackEngine()}createFallbackEngine(){let e=[];return{create_witness:(t,i)=>{let r={hash:this.computeHash(t,i),previousHash:i,position:e.length,timestamp:Date.now()};return e.push(r),r},verify_witness:(t,i)=>{let n=e.find(a=>a.hash===i);return this.computeHash(t,n?.previousHash)===i},verify_chain:t=>{if(t.length===0)return!0;if(t[0].previousHash!==void 0)return!1;for(let i=1;i<t.length;i++)if(t[i].previousHash!==t[i-1].hash)return!1;return!0},get_chain_length:()=>e.length}}computeHash(e,t){let i=X("sha256");return i.update(e),t&&i.update(t,"utf-8"),i.digest("hex")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("WitnessAdapter not initialized. Call initialize() first.")}createWitness(e){this.ensureInitialized();let t=this.serializeDecision(e),i=this.getLastWitness(),n=i?.hash,r=this.engine.create_witness(t,n),a=`witness-${++this.witnessCounter}-${Date.now()}`,s={witnessId:a,decisionId:e.id,hash:r.hash,previousWitnessId:i?.witnessId,chainPosition:r.position,timestamp:new Date(r.timestamp)};return this.witnesses.set(a,s),this.decisions.set(e.id,e),this.logger.info("Created witness",{witnessId:a,decisionId:e.id,chainPosition:s.chainPosition}),s}verifyWitness(e,t){this.ensureInitialized();let i=this.serializeDecision(e),n=this.engine.verify_witness(i,t);return this.logger.debug("Verified witness",{decisionId:e.id,hash:t,isValid:n}),n}verifyChain(e){if(this.ensureInitialized(),e.length===0)return!0;let t=e.map(n=>({hash:n.hash,previousHash:n.previousWitnessId?this.witnesses.get(n.previousWitnessId)?.hash:void 0,position:n.chainPosition,timestamp:n.timestamp.getTime()})),i=this.engine.verify_chain(t);return this.logger.info("Verified witness chain",{chainLength:e.length,isValid:i}),i}replayFromWitness(e){let t=Date.now(),i=this.witnesses.get(e);if(!i)return{success:!1,decision:this.createEmptyDecision(),matchesOriginal:!1,differences:[`Witness not found: ${e}`],durationMs:Date.now()-t};let n=this.decisions.get(i.decisionId);if(!n)return{success:!1,decision:this.createEmptyDecision(),matchesOriginal:!1,differences:[`Decision not found: ${i.decisionId}`],durationMs:Date.now()-t};let r=this.verifyWitness(n,i.hash),a=Date.now()-t,s={success:!0,decision:n,matchesOriginal:r,differences:r?void 0:["Hash mismatch detected"],durationMs:a};return this.logger.info("Replayed from witness",{witnessId:e,decisionId:n.id,matchesOriginal:r,durationMs:a}),s}getChainLength(){return this.ensureInitialized(),this.engine.get_chain_length()}getWitnessChain(){return Array.from(this.witnesses.values()).sort((e,t)=>e.chainPosition-t.chainPosition)}getWitness(e){return this.witnesses.get(e)}getLastWitness(){let e=this.getWitnessChain();return e[e.length-1]}serializeDecision(e){let t=JSON.stringify({id:e.id,type:e.type,inputs:e.inputs,output:e.output,agents:e.agents,timestamp:e.timestamp.toISOString(),reasoning:e.reasoning});return new TextEncoder().encode(t)}createEmptyDecision(){return{id:"",type:"routing",inputs:{},output:null,agents:[],timestamp:new Date}}dispose(){this.witnesses.clear(),this.decisions.clear(),this.witnessCounter=0,this.engine=null,this.initialized=!1,this.logger.info("WitnessAdapter disposed")}};var x=class{constructor(e,t={},i){this.wasmLoader=e;this.config={...N,...t},this.logger=i||p}wasmLoader;config;logger;cohomologyAdapter=null;spectralAdapter=null;causalAdapter=null;categoryAdapter=null;homotopyAdapter=null;witnessAdapter=null;initialized=!1;stats={totalChecks:0,coherentCount:0,incoherentCount:0,averageEnergy:0,averageDurationMs:0,totalContradictions:0,laneDistribution:{reflex:0,retrieval:0,heavy:0,human:0},fallbackCount:0,wasmAvailable:!1};totalEnergySum=0;totalDurationSum=0;async initialize(){if(this.initialized)return;this.logger.info("Initializing CoherenceService");let e=await this.wasmLoader.isAvailable();if(!e&&!this.config.fallbackEnabled)throw new h("WASM module is not available and fallback is disabled. Enable fallbackEnabled in config to use TypeScript fallback.");if(this.stats.wasmAvailable=e,e)try{this.cohomologyAdapter=new w(this.wasmLoader,this.logger),this.spectralAdapter=new E(this.wasmLoader,this.logger),this.causalAdapter=new A(this.wasmLoader,this.logger),this.categoryAdapter=new T(this.wasmLoader,this.logger),this.homotopyAdapter=new R(this.wasmLoader,this.logger),this.witnessAdapter=new S(this.wasmLoader,this.logger),await Promise.all([this.cohomologyAdapter.initialize(),this.spectralAdapter.initialize(),this.causalAdapter.initialize(),this.categoryAdapter.initialize(),this.homotopyAdapter.initialize(),this.witnessAdapter.initialize()]),this.logger.info("All coherence engine adapters initialized")}catch(t){if(!this.config.fallbackEnabled)throw t;this.logger.warn("WASM initialization failed, using fallback",{error:t instanceof Error?t.message:"Unknown error"}),this.stats.wasmAvailable=!1}else this.logger.info("WASM not available, using TypeScript fallback");this.initialized=!0,this.logger.info("CoherenceService initialized",{wasmAvailable:this.stats.wasmAvailable,fallbackEnabled:this.config.fallbackEnabled})}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized)throw new b("CoherenceService not initialized. Call initialize() first.","NOT_INITIALIZED")}async checkCoherence(e){this.ensureInitialized();let t=Date.now();try{return this.cohomologyAdapter?.isInitialized()?await this.checkCoherenceWithWasm(e,t):this.checkCoherenceWithFallback(e,t)}catch(i){return this.logger.error("Coherence check failed",I(i)),{energy:1,isCoherent:!1,lane:"human",contradictions:[],recommendations:["Coherence check failed. Manual review recommended."],durationMs:Date.now()-t,usedFallback:!0}}}async checkCoherenceWithWasm(e,t){this.cohomologyAdapter.clear();for(let s of e)this.cohomologyAdapter.addNode(s);this.buildEdgesFromNodes(e);let i=this.cohomologyAdapter.computeEnergy(),n=this.cohomologyAdapter.detectContradictions(this.config.coherenceThreshold),r=this.computeLane(i),a=Date.now()-t;return this.updateStats(i,a,n.length,r,!1),{energy:i,isCoherent:i<this.config.coherenceThreshold,lane:r,contradictions:n,recommendations:this.generateRecommendations(i,r,n),durationMs:a,usedFallback:!1}}checkCoherenceWithFallback(e,t){this.stats.fallbackCount++;let i=0,n=0,r=[];for(let o=0;o<e.length;o++)for(let l=o+1;l<e.length;l++){let c=this.euclideanDistance(e[o].embedding,e[l].embedding);i+=c,n++,c>1.5&&r.push({nodeIds:[e[o].id,e[l].id],severity:c>2?"critical":"high",description:`High distance (${c.toFixed(2)}) between nodes`,confidence:Math.min(1,c/2)})}let a=n>0?i/n:0,s=this.computeLane(a),d=Date.now()-t;return this.updateStats(a,d,r.length,s,!0),{energy:a,isCoherent:a<this.config.coherenceThreshold,lane:s,contradictions:r,recommendations:this.generateRecommendations(a,s,r),durationMs:d,usedFallback:!0}}buildEdgesFromNodes(e){for(let t=0;t<e.length;t++)for(let i=t+1;i<e.length;i++){let n=this.cosineSimilarity(e[t].embedding,e[i].embedding);n>.3&&this.cohomologyAdapter.addEdge({source:e[t].id,target:e[i].id,weight:n})}}async detectContradictions(e){this.ensureInitialized();let t=e.map(n=>({id:n.id,embedding:n.embedding,weight:n.confidence,metadata:{statement:n.statement,source:n.source}}));return(await this.checkCoherence(t)).contradictions}async predictCollapse(e){if(this.ensureInitialized(),!e.agents||e.agents.length===0)return{risk:0,fiedlerValue:0,collapseImminent:!1,weakVertices:[],recommendations:["No agents to analyze"],durationMs:0,usedFallback:!0};if(this.spectralAdapter?.isInitialized())try{return this.spectralAdapter.analyzeSwarmState(e)}catch(t){return this.logger.warn("Spectral collapse prediction failed, using fallback",{error:v(t),agentCount:e.agents.length}),this.predictCollapseWithFallback(e)}return this.predictCollapseWithFallback(e)}predictCollapseWithFallback(e){let t=Date.now(),i=e.agents.reduce((s,d)=>s+d.health,0)/Math.max(e.agents.length,1),n=e.agents.reduce((s,d)=>s+d.successRate,0)/Math.max(e.agents.length,1),r=0;r+=(1-i)*.3,r+=(1-n)*.3,r+=e.errorRate*.2,r+=e.utilization>.9?.2:e.utilization*.1;let a=e.agents.filter(s=>s.health<.5||s.successRate<.5).map(s=>s.agentId);return{risk:Math.min(1,r),fiedlerValue:i*n,collapseImminent:r>.7,weakVertices:a,recommendations:r>.5?["System health degraded. Consider spawning additional agents."]:["System health is acceptable."],durationMs:Date.now()-t,usedFallback:!0}}async verifyCausality(e,t,i){return this.ensureInitialized(),this.causalAdapter?.isInitialized()?this.causalAdapter.verifyCausality(e,t,i):this.verifyCausalityWithFallback(e,t,i)}verifyCausalityWithFallback(e,t,i){let n=Date.now(),r=this.computeCorrelation(i.causeValues,i.effectValues),a=Math.abs(r);return{isCausal:a>.5,effectStrength:a,relationshipType:a<.2?"none":a>.5?"causal":"spurious",confidence:Math.min(.7,i.sampleSize/100),confounders:[],explanation:`Correlation-based analysis: r=${r.toFixed(3)}. Note: Correlation does not imply causation. This is a fallback analysis without full causal inference.`,durationMs:Date.now()-n,usedFallback:!0}}async verifyTypes(e){return this.ensureInitialized(),this.categoryAdapter?.isInitialized()?this.categoryAdapter.verifyPipeline(e):this.verifyTypesWithFallback(e)}verifyTypesWithFallback(e){let t=Date.now(),i=[],n=e.inputType;for(let r of e.elements)r.inputType!==n&&n!=="any"&&i.push({location:r.name,expected:n,actual:r.inputType,severity:"high"}),n=r.outputType;return n!==e.outputType&&n!=="any"&&i.push({location:"pipeline output",expected:e.outputType,actual:n,severity:"critical"}),{isValid:i.length===0,mismatches:i,warnings:["Using fallback type verification. Full categorical analysis unavailable."],durationMs:Date.now()-t,usedFallback:!0}}async createWitness(e){return this.ensureInitialized(),this.witnessAdapter?.isInitialized()?this.witnessAdapter.createWitness(e):{witnessId:`witness-fallback-${Date.now()}`,decisionId:e.id,hash:this.simpleHash(JSON.stringify(e)),chainPosition:0,timestamp:new Date}}async replayFromWitness(e){return this.ensureInitialized(),this.witnessAdapter?.isInitialized()?this.witnessAdapter.replayFromWitness(e):{success:!1,decision:{id:"",type:"routing",inputs:{},output:null,agents:[],timestamp:new Date},matchesOriginal:!1,differences:["Replay not available in fallback mode"],durationMs:0}}async checkSwarmCoherence(e){this.ensureInitialized();let t=[];return e.forEach((i,n)=>{let r=this.agentHealthToEmbedding(i);t.push({id:n,embedding:r,weight:i.health,metadata:{agentType:i.agentType,successRate:i.successRate,errorCount:i.errorCount}})}),this.checkCoherence(t)}async verifyConsensus(e){this.ensureInitialized();let t=Date.now();if(e.length<2)return{isValid:e.length===1,confidence:e.length===1?e[0].confidence:0,isFalseConsensus:!1,fiedlerValue:e.length===1?1:0,collapseRisk:0,recommendation:e.length===0?"No votes to analyze":"Single vote - consensus trivially achieved",durationMs:Date.now()-t,usedFallback:!0};if(this.spectralAdapter?.isInitialized())try{this.spectralAdapter.clear();for(let a of e)this.spectralAdapter.addNode(a.agentId);let i=0;for(let a=0;a<e.length;a++)for(let s=a+1;s<e.length;s++)e[a].verdict===e[s].verdict&&(this.spectralAdapter.addEdge(e[a].agentId,e[s].agentId,Math.min(e[a].confidence,e[s].confidence)),i++);if(i===0)return this.logger.debug("No agreement edges, using fallback consensus"),this.verifyConsensusWithFallback(e,t);let n=this.spectralAdapter.predictCollapseRisk(),r=this.spectralAdapter.computeFiedlerValue();return{isValid:n<.3&&r>.1,confidence:1-n,isFalseConsensus:r<.05,fiedlerValue:r,collapseRisk:n,recommendation:n>.3?"Spawn independent reviewer":"Consensus verified",durationMs:Date.now()-t,usedFallback:!1}}catch(i){return this.logger.warn("Spectral consensus verification failed, using fallback",{error:v(i),voteCount:e.length}),this.verifyConsensusWithFallback(e,t)}return this.verifyConsensusWithFallback(e,t)}verifyConsensusWithFallback(e,t){let i=new Map;for(let s of e){let d=String(s.verdict);i.set(d,(i.get(d)||0)+1)}let n=0;i.forEach(s=>{n=Math.max(n,s)});let r=n/e.length,a=e.reduce((s,d)=>s+d.confidence,0)/e.length;return{isValid:r>.6,confidence:r*a,isFalseConsensus:i.size===1&&e.length>2,fiedlerValue:r,collapseRisk:1-r,recommendation:r<.6?"No clear majority. Consider spawning additional agents.":r===1&&i.size===1?"Unanimous consensus may indicate false consensus. Consider adding diversity.":"Majority consensus achieved.",durationMs:Date.now()-t,usedFallback:!0}}async filterCoherent(e,t){if(this.ensureInitialized(),e.length===0)return[];if(e.length===1)return e;let i=e.map(a=>({id:a.id,embedding:a.embedding})),n=await this.checkCoherence(i);if(n.isCoherent)return e;let r=new Set;for(let a of n.contradictions)a.nodeIds.forEach(s=>r.add(s));return e.filter(a=>!r.has(a.id))}getStats(){return{...this.stats,averageEnergy:this.stats.totalChecks>0?this.totalEnergySum/this.stats.totalChecks:0,averageDurationMs:this.stats.totalChecks>0?this.totalDurationSum/this.stats.totalChecks:0,lastCheckAt:this.stats.lastCheckAt}}async dispose(){this.cohomologyAdapter?.dispose(),this.spectralAdapter?.dispose(),this.causalAdapter?.dispose(),this.categoryAdapter?.dispose(),this.homotopyAdapter?.dispose(),this.witnessAdapter?.dispose(),this.cohomologyAdapter=null,this.spectralAdapter=null,this.causalAdapter=null,this.categoryAdapter=null,this.homotopyAdapter=null,this.witnessAdapter=null,this.initialized=!1,this.logger.info("CoherenceService disposed")}computeLane(e){let{laneConfig:t}=this.config;return e<t.reflexThreshold?"reflex":e<t.retrievalThreshold?"retrieval":e<t.heavyThreshold?"heavy":"human"}updateStats(e,t,i,n,r){this.stats.totalChecks++,this.totalEnergySum+=e,this.totalDurationSum+=t,this.stats.totalContradictions+=i,this.stats.laneDistribution[n]++,this.stats.lastCheckAt=new Date,e<this.config.coherenceThreshold?this.stats.coherentCount++:this.stats.incoherentCount++,r&&this.stats.fallbackCount++}generateRecommendations(e,t,i){let n=[];if(t==="reflex"?n.push("Low energy detected. Safe to proceed with immediate execution."):t==="retrieval"?n.push("Moderate energy detected. Consider fetching additional context before proceeding."):t==="heavy"?n.push("High energy detected. Deep analysis recommended before proceeding."):n.push("Critical energy level. Escalate to human review (Queen agent)."),i.length>0){let r=i.filter(a=>a.severity==="critical");r.length>0&&n.push(`Found ${r.length} critical contradiction(s) that must be resolved.`)}return n}agentHealthToEmbedding(e){let t=e.beliefs??[];return[e.health,e.successRate,Math.min(1,e.errorCount/10),this.agentTypeToNumber(e.agentType),t.length/10,...t[0]?.embedding.slice(0,5)||[0,0,0,0,0],...t[1]?.embedding.slice(0,5)||[0,0,0,0,0],...t[2]?.embedding.slice(0,5)||[0,0,0,0,0]]}agentTypeToNumber(e){let t=["coordinator","specialist","analyzer","generator","validator","tester","reviewer","optimizer"],i=t.indexOf(e);return i>=0?i/t.length:.5}euclideanDistance(e,t){if(e.length!==t.length)return 1/0;let i=0;for(let n=0;n<e.length;n++)i+=(e[n]-t[n])**2;return Math.sqrt(i)}cosineSimilarity(e,t){if(e.length!==t.length||e.length===0)return 0;let i=0,n=0,r=0;for(let s=0;s<e.length;s++)i+=e[s]*t[s],n+=e[s]*e[s],r+=t[s]*t[s];let a=Math.sqrt(n)*Math.sqrt(r);return a===0?0:i/a}computeCorrelation(e,t){if(e.length!==t.length||e.length<2)return 0;let i=e.length,n=e.reduce((l,c)=>l+c,0)/i,r=t.reduce((l,c)=>l+c,0)/i,a=0,s=0,d=0;for(let l=0;l<i;l++){let c=e[l]-n,m=t[l]-r;a+=c*m,s+=c*c,d+=m*m}let o=Math.sqrt(s*d);return o===0?0:a/o}simpleHash(e){let t=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);t=(t<<5)-t+n,t=t&t}return(t>>>0).toString(16).padStart(8,"0")}};async function re(u,e,t){let i=new x(u,e,t);return await i.initialize(),i}D();import{createRequire as U}from"node:module";import{fileURLToPath as ae}from"node:url";import{dirname as H,join as L}from"node:path";import{readFileSync as se,existsSync as B}from"node:fs";var V=[1e3,2e3,4e3],_=class{state="unloaded";wasmModule=null;engines=null;loadPromise=null;lastError=null;config;version="";fallbackState={mode:"wasm",consecutiveFailures:0,totalActivations:0,nextRetryAt:void 0,lastSuccessfulLoad:void 0};retryTimer=null;degradedModeStartTime=null;eventListeners;constructor(e={}){this.config={...$,...e},this.eventListeners=new Map,this.eventListeners.set("loaded",new Set),this.eventListeners.set("error",new Set),this.eventListeners.set("retry",new Set),this.eventListeners.set("degraded_mode",new Set),this.eventListeners.set("recovered",new Set)}isLoaded(){return this.state==="loaded"&&this.engines!==null}getState(){return this.state}getVersion(){return this.version}getLastError(){return this.lastError}isInDegradedMode(){return this.state==="degraded"||this.fallbackState.mode==="fallback"}getFallbackState(){return{...this.fallbackState}}getFallbackResult(){return{usedFallback:!0,confidence:.5,retryCount:this.fallbackState.consecutiveFailures,lastError:this.lastError?.message,activatedAt:this.degradedModeStartTime??new Date}}async getEngines(){if(this.state==="loaded"&&this.engines)return this.engines;if(this.state==="loading"&&this.loadPromise)return this.loadPromise;this.state="loading",this.loadPromise=this.loadWithRetry();try{return this.engines=await this.loadPromise,this.state="loaded",(this.fallbackState.mode==="fallback"||this.fallbackState.mode==="recovering")&&this.emitRecoveryEvent(),this.fallbackState.mode="wasm",this.fallbackState.consecutiveFailures=0,this.fallbackState.lastSuccessfulLoad=new Date,this.engines}catch(e){throw this.state="failed",this.lastError=I(e),this.enterDegradedMode(this.lastError),e}finally{this.loadPromise=null}}async getEnginesWithFallback(){if(this.state==="loaded"&&this.engines)return{engines:this.engines,fallback:{usedFallback:!1,confidence:1,retryCount:0}};if(this.state==="degraded")return{engines:null,fallback:this.getFallbackResult()};try{return{engines:await this.getEngines(),fallback:{usedFallback:!1,confidence:1,retryCount:0}}}catch{return{engines:null,fallback:this.getFallbackResult()}}}getEnginesSync(){if(!this.engines)throw new h("WASM module is not loaded. Call getEngines() first.");return this.engines}async isAvailable(){if(this.state==="loaded"&&this.wasmModule)return!0;if(this.state==="failed")return!1;try{let e=U(import.meta.url),t=[(()=>{try{let i=e.resolve("prime-radiant-advanced-wasm");return L(H(i),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),L(process.cwd(),"node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm")].filter(i=>i!==null);for(let i of t)if(B(i))return!0;return!1}catch{return!1}}async load(){if(await this.getEngines(),!this.wasmModule)throw new h("WASM module failed to load");return this.wasmModule}getModule(){if(!this.wasmModule)throw new h("WASM module is not loaded. Call load() first.");return this.wasmModule}on(e,t){let i=this.eventListeners.get(e);return i&&i.add(t),()=>{i?.delete(t)}}off(e,t){let i=this.eventListeners.get(e);i&&i.delete(t)}reset(){if(this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.engines)try{this.engines.cohomology.free(),this.engines.spectral.free(),this.engines.causal.free(),this.engines.category.free(),this.engines.hott.free(),this.engines.quantum.free()}catch(e){console.debug("[WASMLoader] Cleanup error during unload:",e instanceof Error?e.message:e)}this.state="unloaded",this.wasmModule=null,this.engines=null,this.loadPromise=null,this.lastError=null,this.version="",this.fallbackState={mode:"wasm",consecutiveFailures:0,totalActivations:0,nextRetryAt:void 0,lastSuccessfulLoad:void 0},this.degradedModeStartTime=null}async forceRetry(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),(this.state==="failed"||this.state==="degraded")&&(this.state="unloaded",this.fallbackState.mode="recovering");try{return await this.getEngines(),!0}catch{return!1}}async loadWithRetry(){let{maxAttempts:e,baseDelayMs:t,maxDelayMs:i}=this.config,n=new Error("Unknown error");for(let r=1;r<=e;r++)try{let a=performance.now(),s=await this.attemptLoad(),d=performance.now()-a;return this.emit("loaded",{version:this.version,loadTimeMs:Math.round(d*100)/100}),s}catch(a){if(n=I(a),this.emit("error",{error:n,fatal:r>=e,attempt:r}),r<e){let s=Math.min(t*Math.pow(2,r-1),i);this.emit("retry",{attempt:r+1,maxAttempts:e,delayMs:s,previousError:n}),await this.sleep(s)}}throw new k(`Failed to load WASM module after ${e} attempts: ${n.message}`,e,n)}async attemptLoad(){let e;try{e=U(import.meta.url)}catch{e=globalThis.require||(await import("module")).createRequire(__filename)}let t;try{t=await import("./prime-radiant-advanced-wasm-OIHTKJMN.js")}catch(r){try{t=e("prime-radiant-advanced-wasm")}catch{throw new Error(`Failed to import prime-radiant-advanced-wasm: ${v(r)}`)}}if(typeof process<"u"&&process.versions!=null&&process.versions.node!=null?await this.initializeForNodeJs(t,e):t.default&&typeof t.default=="function"&&await t.default(),t.initModule&&typeof t.initModule=="function")try{t.initModule()}catch{}return t.getVersion&&typeof t.getVersion=="function"&&(this.version=t.getVersion()),this.wasmModule=t,{cohomology:new t.CohomologyEngine,spectral:new t.SpectralEngine,causal:new t.CausalEngine,category:new t.CategoryEngine,hott:new t.HoTTEngine,quantum:new t.QuantumEngine}}async initializeForNodeJs(e,t){let i=[(()=>{try{let a=t.resolve("prime-radiant-advanced-wasm");return L(H(a),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),L(H(ae(import.meta.url)),"../../../../node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm"),L(process.cwd(),"node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm")].filter(a=>a!==null),n=null;for(let a of i)if(B(a)){n=a;break}if(!n)throw new Error(`Could not find WASM binary. Searched paths:
3
- ${i.join(`
4
- `)}
5
- Ensure prime-radiant-advanced-wasm is installed.`);let r=se(n);if(e.initSync&&typeof e.initSync=="function")e.initSync({module:r});else throw new Error("WASM module does not export initSync function")}emit(e,t){let i=this.eventListeners.get(e);if(i){let n=Array.from(i);for(let r=0;r<n.length;r++)try{n[r](t)}catch{}}}sleep(e){return new Promise(t=>setTimeout(t,e))}enterDegradedMode(e){this.state="degraded",this.fallbackState.mode="fallback",this.fallbackState.consecutiveFailures++,this.fallbackState.totalActivations++,this.degradedModeStartTime||(this.degradedModeStartTime=new Date);let t=Math.min(this.fallbackState.consecutiveFailures-1,V.length-1),i=V[t],n=new Date(Date.now()+i);this.fallbackState.nextRetryAt=n,console.warn(`[WasmLoader] WASM load failed, entering degraded mode. Retry ${this.fallbackState.consecutiveFailures}/3 in ${i}ms. Error: ${e.message}`),this.emit("degraded_mode",{reason:"WASM load failed after retries",retryCount:this.fallbackState.consecutiveFailures,lastError:e.message,activatedAt:this.degradedModeStartTime,nextRetryAt:n}),this.fallbackState.consecutiveFailures<V.length&&this.scheduleBackgroundRetry(i)}scheduleBackgroundRetry(e){this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.fallbackState.mode="recovering",this.attemptBackgroundRecovery()},e)}async attemptBackgroundRecovery(){this.state="unloaded",this.loadPromise=null;try{await this.getEngines()}catch{}}emitRecoveryEvent(){if(!this.degradedModeStartTime)return;let e=Date.now()-this.degradedModeStartTime.getTime();console.info(`[WasmLoader] WASM recovered after ${e}ms in degraded mode. Retry count: ${this.fallbackState.consecutiveFailures}`),this.emit("recovered",{degradedDurationMs:e,retryCount:this.fallbackState.consecutiveFailures,version:this.version}),this.degradedModeStartTime=null}},oe=new _;var le={emaAlpha:.1,minSamplesForCalibration:10,maxHistorySize:1e3,targetFalsePositiveRate:.05,targetFalseNegativeRate:.02,maxAdjustmentPerCycle:.05,autoCalibrate:!1,autoCalibrateInterval:100,defaultThresholds:{...M}};export{re as a,oe as b};
@@ -1,14 +0,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.14.4");process.exit(0)}
2
- import{c as g,n as S}from"./chunk-NDPFGIMJ.js";function E(i,e){return{ingest(t){i.ingest(t)},search(t,r){return i.search(t,r).map(s=>({id:s.id,score:s.score}))},delete(t){i.delete(t)},status(){let t=i.status();return{totalVectors:t.totalVectors,dimensions:e,totalSegments:t.totalSegments,fileSizeBytes:t.fileSizeBytes,epoch:t.epoch,witnessValid:t.witnessValid,witnessEntries:t.witnessEntries}},close(){i.close()},compact(){return i.compact()}}}function f(i,e){return(i.prepare("SELECT COUNT(*) as cnt FROM sqlite_master WHERE type='table' AND name=?").get(e)?.cnt??0)>0}function m(i,e,t){return i.prepare(`PRAGMA table_info(${e})`).all().some(s=>s.name===t)}var h=class{db;config;rvfStore=null;rvfAvailable=!1;constructor(e,t){this.db=e,this.config={...t,dimensions:t.dimensions??384},f(this.db,"qe_pattern_embeddings")&&!m(this.db,"qe_pattern_embeddings","space_id")&&(this.db.exec("ALTER TABLE qe_pattern_embeddings ADD COLUMN space_id TEXT"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_qe_pattern_embeddings_space ON qe_pattern_embeddings(space_id)"))}activeSpaceId(){return this.config.embeddingSpaceId??S()?.spaceId}async initialize(){if(this.config.mode==="sqlite-only"){this.rvfAvailable=!1;return}try{let e=await import("./rvf-native-adapter-S4562CG5.js");if(!e.isRvfNativeAvailable()){this.rvfAvailable=!1;return}let{isRvfLockHeldError:t,removeStaleRvfLock:r,quarantineUnusableStore:s}=await import("./rvf-store-integrity-KMIHD3LP.js"),l=()=>{try{return{store:e.openRvfStore(this.config.rvfPath),error:null}}catch(o){return{store:null,error:o}}},{store:n,error:a}=l();if(!n&&t(a)&&(!r(this.config.rvfPath)||({store:n,error:a}=l(),!n&&t(a))))throw a;if(!n)try{n=e.createRvfStore(this.config.rvfPath,this.config.dimensions)}catch(o){if({store:n,error:a}=l(),!n){if(t(a))throw a;if(!s(this.config.rvfPath,o instanceof Error?o.message:String(o),a))throw o;n=e.createRvfStore(this.config.rvfPath,this.config.dimensions)}}this.rvfStore=E(n,this.config.dimensions),g(this.config.rvfPath,this.activeSpaceId()??null,this.rvfStore.status().totalVectors),this.rvfAvailable=!0}catch(e){try{this.rvfStore?.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1,console.warn(`[RVF] Dual-writer disabled for ${this.config.rvfPath}; falling back to SQLite: ${e instanceof Error?e.message:String(e)}`)}}setRvfStore(e){this.rvfStore=e,this.rvfAvailable=!0}writePattern(e,t){let r={sqliteSuccess:!1,rvfSuccess:!1};if(!m(this.db,"qe_pattern_embeddings","space_id")||!this.activeSpaceId())return{...r,divergence:"VECTOR_SPACE_UNVERIFIED"};try{this.writeSqliteEmbedding(e,t),r.sqliteSuccess=!0}catch{r.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.ingest([{id:e,vector:t instanceof Float32Array?Array.from(t):t}]),r.rvfSuccess=!0}catch{r.rvfSuccess=!1,r.divergence="rvf-write-failed"}return r}deletePattern(e){let t={sqliteSuccess:!1,rvfSuccess:!1};try{this.deleteSqliteEmbedding(e),t.sqliteSuccess=!0}catch{t.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.delete([e]),t.rvfSuccess=!0}catch{t.rvfSuccess=!1,t.divergence="rvf-delete-failed"}return t}search(e,t){if(!this.hasCompatibleEmbeddingSpace())return[];if(this.config.mode==="rvf-primary"&&this.rvfAvailable&&this.rvfStore)try{return this.rvfStore.search(e,t)}catch{}return this.searchSqlite(e,t)}getDivergenceReport(){let e={totalChecked:0,divergences:0,details:[]},t=this.getSqliteEmbeddingCount();if(e.totalChecked=t,!this.rvfAvailable||!this.rvfStore)return this.config.mode!=="sqlite-only"&&t>0&&(e.divergences=1,e.details.push({patternId:"*",issue:"count-mismatch"})),e;let s=this.rvfStore.status().totalVectors;return t!==s&&(e.divergences=1,e.details.push({patternId:"*",issue:"count-mismatch"})),e}isPromotionSafe(){return this.getDivergenceReport().divergences===0}status(){let e=this.getSqlitePatternCount(),t=this.getSqliteEmbeddingCount(),r=null;if(this.rvfAvailable&&this.rvfStore)try{r=this.rvfStore.status()}catch{r=null}return{sqlite:{patternCount:e,vectorCount:t},rvf:r,mode:this.config.mode}}close(){if(this.rvfStore){try{this.rvfStore.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1}}compact(){if(!this.rvfStore||!this.rvfAvailable||!this.rvfStore.compact)return null;try{return this.rvfStore.compact()??null}catch{return null}}shouldWriteRvf(){return(this.config.mode==="dual-write"||this.config.mode==="rvf-primary")&&this.rvfAvailable&&this.rvfStore!==null}hasCompatibleEmbeddingSpace(){if(!m(this.db,"qe_pattern_embeddings","space_id"))return!1;let e=this.activeSpaceId();return e?(this.db.prepare(`
3
- SELECT COUNT(*) AS incompatible
4
- FROM qe_pattern_embeddings
5
- WHERE space_id IS NULL OR space_id <> ?
6
- `).get(e)?.incompatible??0)===0:!1}writeSqliteEmbedding(e,t){let r=Buffer.from(t instanceof Float32Array?t.buffer:new Float32Array(t).buffer),s=t.length;if(f(this.db,"qe_pattern_embeddings")){let l=this.activeSpaceId();if(m(this.db,"qe_pattern_embeddings","space_id")){if(!l)throw new Error("VECTOR_SPACE_UNVERIFIED: dual writer has no runtime provenance");this.db.prepare(`
7
- INSERT INTO qe_pattern_embeddings (pattern_id, embedding, dimension, model, space_id, created_at)
8
- VALUES (?, ?, ?, 'all-MiniLM-L6-v2', ?, datetime('now'))
9
- ON CONFLICT(pattern_id) DO UPDATE SET
10
- embedding = excluded.embedding,
11
- dimension = excluded.dimension,
12
- space_id = excluded.space_id,
13
- created_at = datetime('now')
14
- `).run(e,r,s,l);return}throw new Error("VECTOR_SPACE_UNVERIFIED: canonical space_id column is unavailable")}}deleteSqliteEmbedding(e){f(this.db,"qe_pattern_embeddings")&&this.db.prepare("DELETE FROM qe_pattern_embeddings WHERE pattern_id = ?").run(e)}getSqliteEmbeddingCount(){return f(this.db,"qe_pattern_embeddings")?this.db.prepare("SELECT COUNT(*) as cnt FROM qe_pattern_embeddings").get()?.cnt??0:0}getSqlitePatternCount(){return f(this.db,"qe_patterns")?this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get()?.cnt??0:0}searchSqlite(e,t){if(!f(this.db,"qe_pattern_embeddings"))return[];let r=this.activeSpaceId();if(!m(this.db,"qe_pattern_embeddings","space_id")||!r)return[];let l=this.db.prepare("SELECT pattern_id, embedding, dimension FROM qe_pattern_embeddings WHERE space_id = ?").all(r),n=e instanceof Float32Array?Array.from(e):e,a=Math.sqrt(n.reduce((c,u)=>c+u*u,0));if(a===0)return[];let o=[];for(let c of l){let u=new Float32Array(c.embedding.buffer,c.embedding.byteOffset,c.dimension),p=Array.from(u),b=0,v=0;for(let d=0;d<p.length&&d<n.length;d++)b+=p[d]*n[d],v+=p[d]*p[d];v=Math.sqrt(v);let _=v>0?b/(a*v):0;o.push({id:c.pattern_id,score:_})}return o.sort((c,u)=>u.score-c.score),o.slice(0,t)}};function y(i,e){return new h(i,e)}export{h as a,y as b};
@@ -1,2 +0,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.14.4");process.exit(0)}
2
- import{a as e,b as g,e as r}from"./chunk-Y3MW3YBC.js";import{c as o}from"./chunk-TT23RRB7.js";var L=o(()=>{"use strict";e();g();r()});export{L as a};
@@ -1,13 +0,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.14.4");process.exit(0)}
2
- import{a as F,c as de}from"./chunk-G6T45OIC.js";import{b as W,d as k}from"./chunk-ODKLFVYC.js";k();de();k();import*as S from"node:http";import*as R from"node:https";import{createHash as le}from"node:crypto";import{URL as G}from"node:url";var A={model:"Xenova/all-MiniLM-L6-v2",expectedDim:384,connectTimeoutMs:5e3,requestTimeoutMs:3e4,failureThreshold:3,failureWindowMs:6e4},pe="AQE embedder endpoint identity canary v1",ce="/v1/embeddings";function j(t){if(t.startsWith("unix:"))return t;try{let e=new G(t);return e.username||e.password?(e.username="",e.password="",e.toString().replace(/\/$/,"")):t}catch{return t}}function me(t){if(t.startsWith("unix:")){let r=t.slice(5);if(!r.startsWith("/"))throw new Error(`unix endpoint must be an absolute path: ${t}`);return{transport:"unix",socketPath:r,safeUrl:t}}let e=new G(t);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`unsupported embedder endpoint protocol: ${e.protocol}`);return(e.username||e.password)&&(console.warn("[EmbedderEndpointClient] endpoint URL contained userinfo; stripping. Use AQE_EMBEDDER_TOKEN env var for credentials."),e.username="",e.password=""),{transport:e.protocol==="https:"?"https":"http",host:e.hostname,port:e.port?Number(e.port):e.protocol==="https:"?443:80,protocol:e.protocol,safeUrl:e.toString().replace(/\/$/,"")}}var z=class{constructor(e,n,r=()=>{}){this.threshold=e;this.windowMs=n;this.onRecover=r}threshold;windowMs;onRecover;failures=[];trippedAt=null;recordSuccess(){this.failures=[],this.trippedAt=null}recordFailure(){let e=Date.now();this.failures=this.failures.filter(n=>e-n<this.windowMs),this.failures.push(e),this.failures.length>=this.threshold&&(this.trippedAt=e)}isOpen(){return this.trippedAt===null?!1:Date.now()-this.trippedAt>=this.windowMs?(this.failures=[],this.trippedAt=null,this.onRecover(),!1):!0}getState(){return{open:this.isOpen(),failures:this.failures.length,trippedAt:this.trippedAt}}},M=class{parsed;agent;breaker;opts;cachedIdentity=null;probeInFlight=null;constructor(e){if(this.opts={endpoint:e.endpoint,token:e.token,model:e.model??A.model,expectedDim:e.expectedDim??A.expectedDim,connectTimeoutMs:e.connectTimeoutMs??A.connectTimeoutMs,requestTimeoutMs:e.requestTimeoutMs??A.requestTimeoutMs,failureThreshold:e.failureThreshold??A.failureThreshold,failureWindowMs:e.failureWindowMs??A.failureWindowMs,tlsOptions:e.tlsOptions},this.parsed=me(e.endpoint),this.parsed.transport==="https"){let n=e.tlsOptions??{};this.agent=new R.Agent({keepAlive:!0,ca:n.ca,cert:n.cert,key:n.key,rejectUnauthorized:n.rejectUnauthorized!==!1,servername:n.servername})}else this.agent=new S.Agent({keepAlive:!0});this.breaker=new z(this.opts.failureThreshold,this.opts.failureWindowMs,()=>{this.cachedIdentity=null})}getSafeEndpoint(){return this.parsed.safeUrl}async embed(e){if(e.length===0)return[];if(this.breaker.isOpen())throw new Error(`[EmbedderEndpointClient] circuit breaker open for ${this.parsed.safeUrl} \u2014 fast-failing`);this.cachedIdentity===null&&await this.ensureProbed();try{let n=await this.postEmbeddings(e),r=this.decodeAndNormalize(n,e.length);return this.breaker.recordSuccess(),r}catch(n){throw this.breaker.recordFailure(),n}}async probe(){return this.probeInFlight?this.probeInFlight:(this.probeInFlight=this.doProbe().finally(()=>{this.probeInFlight=null}),this.probeInFlight)}async ensureProbed(){return this.cachedIdentity?this.cachedIdentity:this.probe()}async doProbe(){let e;try{let a=await this.postEmbeddings([pe]);e=this.decodeAndNormalize(a,1)[0],this.breaker.recordSuccess()}catch(a){throw this.breaker.recordFailure(),a}if(!e||e.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch: expected ${this.opts.expectedDim}, got ${e?.length??0} from ${this.parsed.safeUrl}`);let n=Buffer.alloc(e.length*2);for(let a=0;a<e.length;a++){let i=Math.max(-32768,Math.min(32767,Math.round(e[a]*32767)));n.writeInt16LE(i,a*2)}let r=le("sha256").update(n).digest("hex").slice(0,16);return this.cachedIdentity={dim:e.length,fingerprint:r,endpoint:this.parsed.safeUrl},this.cachedIdentity}getCachedIdentity(){return this.cachedIdentity}getBreakerState(){return this.breaker.getState()}close(){this.agent.destroy()}decodeAndNormalize(e,n){if(!e||typeof e!="object"||!Array.isArray(e.data))throw new Error("[EmbedderEndpointClient] response missing data array");let r=e.data;if(r.length!==n)throw new Error(`[EmbedderEndpointClient] response count mismatch: expected ${n}, got ${r.length}`);let a=r.map((i,s)=>({idx:typeof i.index=="number"?i.index:s,embedding:i.embedding}));return a.sort((i,s)=>i.idx-s.idx),a.map(({embedding:i},s)=>{if(typeof i=="string")throw new Error(`[EmbedderEndpointClient] received base64 embedding at position ${s} \u2014 server ignored encoding_format=float. Configure the server to return float arrays.`);if(!Array.isArray(i))throw new Error(`[EmbedderEndpointClient] missing embedding at position ${s}`);if(i.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch at position ${s}: expected ${this.opts.expectedDim}, got ${i.length}`);return W(i)})}postEmbeddings(e){let n=JSON.stringify({model:this.opts.model,input:e,encoding_format:"float"});return this.request(ce,n)}request(e,n){let r={"content-type":"application/json","content-length":Buffer.byteLength(n),accept:"application/json"};this.opts.token&&(r.authorization=`Bearer ${this.opts.token}`);let a={method:"POST",path:e,headers:r,agent:this.agent},i,s;this.parsed.transport==="unix"?(i={...a,socketPath:this.parsed.socketPath},s=S.request):(i={...a,host:this.parsed.host,port:this.parsed.port,protocol:this.parsed.protocol},s=this.parsed.transport==="https"?R.request:S.request);let o=this.parsed.safeUrl,l=this.opts.connectTimeoutMs,m=this.opts.requestTimeoutMs;return new Promise((b,$)=>{let y=!1,N=d=>{y||(y=!0,b(d))},h=d=>{y||(y=!0,$(d))},w=s(i,d=>{let g=[];d.on("data",u=>g.push(Buffer.from(u))),d.on("end",()=>{let u=Buffer.concat(g).toString("utf-8");if(!d.statusCode||d.statusCode<200||d.statusCode>=300){h(new Error(`[EmbedderEndpointClient] HTTP ${d.statusCode} from ${o}: ${u.slice(0,200)}`));return}try{let E=JSON.parse(u);N(E)}catch(E){h(new Error(`[EmbedderEndpointClient] invalid JSON from ${o}: ${E.message}`))}}),d.on("error",u=>h(u))});w.on("socket",d=>{d.setTimeout(l);let g=()=>{d.setTimeout(m)};d.connecting?d.once("connect",g):g(),d.on("timeout",()=>{let u=d.connecting?"connect":"request",E=d.connecting?l:m,T=new Error(`[EmbedderEndpointClient] ${u} timeout after ${E}ms`);h(T),w.destroy(T)})}),w.on("error",d=>h(d)),w.write(n),w.end()})}};import{join as X}from"node:path";import{existsSync as ue,mkdirSync as fe}from"node:fs";import{createRequire as ge}from"node:module";var he=ge(import.meta.url);function Ee(){let t=process.env.AQE_MEMORY_PATH;return t&&t.length>0?t:X(process.cwd(),".agentic-qe","memory.db")}var J="_system",K="embedder_identity:",x=null,q=!1;function Y(){if(x)return x;if(q)return null;try{let t=he("better-sqlite3"),e=Ee(),n=X(e,"..");ue(n)||fe(n,{recursive:!0});let r=new t(e);return r.pragma("journal_mode = WAL"),r.pragma("busy_timeout = 5000"),r.exec(`
3
- CREATE TABLE IF NOT EXISTS kv_store (
4
- key TEXT NOT NULL,
5
- namespace TEXT NOT NULL,
6
- value TEXT NOT NULL,
7
- expires_at INTEGER,
8
- created_at INTEGER DEFAULT (strftime('%s', 'now') * 1000),
9
- PRIMARY KEY (namespace, key)
10
- );
11
- CREATE INDEX IF NOT EXISTS idx_kv_namespace ON kv_store(namespace);
12
- `),x=r,r}catch{return q=!0,null}}function Q(t){let e=Y();if(!e)return null;try{let n=e.prepare("SELECT value FROM kv_store WHERE namespace = ? AND key = ?").get(J,K+t);if(!n)return null;let r=JSON.parse(n.value);return!r.fingerprint||typeof r.dim!="number"?null:{fingerprint:r.fingerprint,dim:r.dim,endpoint:r.endpoint}}catch{return null}}function Z(t){let e=Y();if(!e)return;let n={fingerprint:t.fingerprint,dim:t.dim,endpoint:t.endpoint,updatedAt:Date.now()};e.prepare("INSERT OR REPLACE INTO kv_store (key, namespace, value) VALUES (?, ?, ?)").run(K+t.endpoint,J,JSON.stringify(n))}function ee(){if(x)try{x.close()}catch{}x=null,q=!1}k();import{createHash as te}from"node:crypto";import{existsSync as ye,readFileSync as we,renameSync as Ie,writeFileSync as ve}from"node:fs";var ne="aqe embedding-space compatibility canary v1";var I=class extends Error{constructor(n,r){super(`${n}: ${r}`);this.code=n;this.name="EmbeddingSpaceError"}code};function Ae(t){return JSON.stringify({provider:t.provider,model:t.model,dimensions:t.dimensions,pooling:t.pooling??null,normalized:t.normalized,preprocessingVersion:t.preprocessingVersion??null,implementation:t.implementation??null,runtimeFingerprint:t.runtimeFingerprint})}function re(t){let e=Buffer.alloc(t.length*2);for(let n=0;n<t.length;n++){let r=Math.max(-32768,Math.min(32767,Math.round(t[n]*32767)));e.writeInt16LE(r,n*2)}return te("sha256").update(e).digest("hex").slice(0,16)}function U(t){if(!t.runtimeFingerprint)throw new Error("Embedding space identity requires executable runtime evidence");let e=te("sha256").update("aqe:embedding-space:v1\0").update(Ae(t)).digest("hex");return{...t,spaceId:e}}function ke(t,e){let n=[...new Set(t.flatMap(o=>o.spaceId?[o.spaceId]:[]))].sort(),r=t.filter(o=>!o.spaceId).length,a=e?t.filter(o=>o.spaceId===e).length:0,i=e?t.filter(o=>o.spaceId!==null&&o.spaceId!==e).length:t.length-r;return{status:r>0||!e?"unverified":i>0||n.length>1?"vector_space_mismatch":"healthy",activeSpaceId:e,storedSpaceIds:n,verifiedVectors:a,mismatchedVectors:i,unverifiedVectors:r}}function xe(t){return`${t}.space.json`}function ze(t,e,n){if(!e)throw new I("VECTOR_SPACE_UNVERIFIED",`cannot open ANN index ${t} without runtime provenance`);let r=xe(t);if(ye(r)){let s;try{s=JSON.parse(we(r,"utf8"))}catch{throw new I("VECTOR_SPACE_UNVERIFIED",`ANN index manifest ${r} is unreadable`)}if(s.version!==1||!s.spaceId)throw new I("VECTOR_SPACE_UNVERIFIED",`ANN index manifest ${r} has no verified space`);if(s.spaceId!==e)throw new I("VECTOR_SPACE_MISMATCH",`ANN index space ${s.spaceId} != active space ${e}`);return}if(n>0)throw new I("VECTOR_SPACE_UNVERIFIED",`populated ANN index ${t} has no embedding-space manifest; rebuild required`);let a={version:1,spaceId:e},i=`${r}.${process.pid}.tmp`;ve(i,`${JSON.stringify(a)}
13
- `,{encoding:"utf8",mode:384}),Ie(i,r)}var V=null,f=null,C=null,P=!1,_="",v=null,p=null,O=null,L={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4,endpoint:process.env.AQE_EMBEDDER_ENDPOINT,endpointToken:process.env.AQE_EMBEDDER_TOKEN},c=new Map,ie=36e5;function B(t){return p?`endpoint:${p.fingerprint}:${t}`:`inproc:${t}`}function oe(t){let e=t.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function se(t={}){if(P)throw new Error(`Transformer initialization previously failed: ${_}`);if(C)return C;let e={...L,...t};return C=(async()=>{try{if(e.endpoint){let l=j(e.endpoint);console.log(`[RealEmbeddings] Using external embedder endpoint: ${l}`),v=new M({endpoint:e.endpoint,token:e.endpointToken,model:e.modelName,expectedDim:D()}),p=await v.probe(),O=U({provider:"openai-compatible-endpoint",model:e.modelName,dimensions:p.dim,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:p.endpoint,runtimeFingerprint:p.fingerprint}),console.log(`[RealEmbeddings] Endpoint identity: dim=${p.dim} fingerprint=${p.fingerprint}`);try{let m=Q(p.endpoint);m&&m.fingerprint!==p.fingerprint&&console.warn(`[RealEmbeddings] WARNING: endpoint identity changed since last run. Previous fingerprint=${m.fingerprint} dim=${m.dim}, current fingerprint=${p.fingerprint} dim=${p.dim}. Vectors written before this change may no longer be comparable.`),Z(p)}catch(m){console.warn(`[RealEmbeddings] Could not persist endpoint identity: ${F(m)}`)}f=Te(v);return}let n;try{n=await import("./transformers-F5UQTQCY.js")}catch{throw new Error('In-process embeddings require the optional package "@huggingface/transformers", which is not installed. Configure an embedding endpoint (EmbeddingConfig.endpoint / AQE_EMBEDDER_ENDPOINT) so no local model is loaded. Installing @huggingface/transformers@4.2.0 is an explicit security opt-in: its compatible dependency chain currently has unresolved HIGH advisories GHSA-xcpc-8h2w-3j85 and GHSA-f88m-g3jw-g9cj.')}V=n.pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let r=performance.now();f=await V("feature-extraction",e.modelName,{quantized:e.quantized});let a=f;if(!a)throw new Error("Transformer pipeline returned no embedding model");let i=await a(ne,{pooling:"mean",normalize:!0}),s=Array.from(i.data);O=U({provider:"huggingface-transformers",model:e.modelName,dimensions:s.length,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:`transformers:${e.quantized?"quantized":"full"}`,runtimeFingerprint:re(s)});let o=performance.now()-r;console.log(`[RealEmbeddings] Model loaded in ${o.toFixed(0)}ms`)}catch(n){throw P=!0,_=F(n),new Error(`Failed to initialize transformer model: ${_}`)}})(),C}function Te(t){return async e=>{let n=Array.isArray(e)?e:[e],r=await t.embed(n),a=r[0]?.length??D(),i=new Float32Array(n.length*a);for(let s=0;s<r.length;s++)i.set(r[s],s*a);return{data:i,dims:[n.length,a]}}}async function He(t,e={}){let n={...L,...e};if(oe(t))return new Array(D()).fill(0);if(f||await se(e),!f)throw new Error("Embedding model failed to initialize");let r=B(t);if(n.enableCache){let l=c.get(r);if(l&&Date.now()-l.timestamp<ie)return l.embedding}let a=performance.now(),i=await f(t,{pooling:"mean",normalize:!0}),s=Array.from(i.data),o=performance.now()-a;if(o>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${o.toFixed(1)}ms for "${t.slice(0,50)}..."`),n.enableCache){if(c.size>=n.maxCacheSize){let l=c.keys().next().value;l&&c.delete(l)}c.set(r,{embedding:s,timestamp:Date.now()})}return s}async function We(t,e={}){let n={...L,...e},r=[],a=[],i=new Array(t.length).fill(null),s=[];for(let o=0;o<t.length;o++)oe(t[o])?i[o]=new Array(D()).fill(0):s.push(o);if(s.length===0)return i;if(f||await se(e),!f)throw new Error("Embedding model failed to initialize");if(n.enableCache)for(let o of s){let l=c.get(B(t[o]));l&&Date.now()-l.timestamp<ie?i[o]=l.embedding:(r.push(t[o]),a.push(o))}else for(let o of s)r.push(t[o]),a.push(o);if(r.length>0){let o=performance.now(),l=32;for(let b=0;b<r.length;b+=l){let $=Math.min(b+l,r.length),y=r.slice(b,$),N=await f(y,{pooling:"mean",normalize:!0}),h=N.dims||[y.length,384],w=h[0],d=h[1];for(let g=0;g<w;g++){let u=g*d,E=Array.from(N.data.slice(u,u+d)),T=b+g,ae=a[T];if(i[ae]=E,n.enableCache){if(c.size>=n.maxCacheSize){let H=c.keys().next().value;H&&c.delete(H)}c.set(B(r[T]),{embedding:E,timestamp:Date.now()})}}}let m=performance.now()-o;console.log(`[RealEmbeddings] Batch computed ${r.length} embeddings in ${m.toFixed(0)}ms`)}return i.filter(o=>o!==null)}function Ge(){c.clear(),console.log("[RealEmbeddings] Cache cleared")}function je(){return{size:c.size,hitRate:0}}function Xe(){return!P&&f!==null}function D(){return 384}function Je(){V=null,f=null,C=null,P=!1,_="",c.clear(),v&&v.close(),v=null,p=null,O=null,ee()}function Ke(){return v!==null}function Ye(){return p}function Qe(){return O}export{ne as a,ke as b,ze as c,L as d,He as e,We as f,Ge as g,je as h,Xe as i,D as j,Je as k,Ke as l,Ye as m,Qe as n};
@@ -1,2 +0,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.14.4");process.exit(0)}
2
- import{b as v,c as S}from"./chunk-PEPFCPES.js";import{e as C,f as $}from"./chunk-TDZ53WO2.js";import{a as g,b as h,c as p,e as b,f as y}from"./chunk-QGIU2WRL.js";import{a as R,g as E}from"./chunk-TT23RRB7.js";S();var i=null,d=!1;function k(r){i=r,d=r!==null}var N=(()=>{let r=process.env.AQE_RVF_SIZE_GUARD_BYTES,t=r?Number(r):NaN;return Number.isFinite(t)&&t>0?t:256*1024*1024})(),B=(()=>{let r=process.env.AQE_RVF_DEAD_RATIO_THRESHOLD,t=r?Number(r):NaN;return Number.isFinite(t)&&t>0&&t<=1?t:.3})();function V(r=".agentic-qe",t=384){if(d)return i;d=!0;try{let{isRvfNativeAvailable:e,createRvfStore:o,openRvfStore:a}=($(),E(C));if(!e())return console.warn("[RVF] Native bindings unavailable \u2014 agent branching and dream COW disabled. Install @ruvector/rvf-node to enable."),null;let s=R("path"),l=s.isAbsolute(r)?r:s.join(process.env.AQE_PROJECT_ROOT??v(),r),n=s.join(l,"patterns.rvf");return i=F(a,o,n,t),w(i,n),i}catch(e){return console.warn("[RVF] Shared adapter init failed:",e instanceof Error?e.message:e),null}}function F(r,t,e,o){let a=()=>{try{return{adapter:r(e),err:null}}catch(n){return{adapter:null,err:n}}},{adapter:s,err:l}=a();if(!s&&p(l))try{let n=R("fs"),c=`${e}.lock`;n.existsSync(c)&&h(e)?console.warn(`[RVF] ${e} is locked by a live process (pid ${g(e)}) \u2014 not breaking the lock; degrading to SQLite for this run.`):b(e)&&(console.warn(`[RVF] Removed stale lock file at ${c} (prior process exited without closing). Retrying open. If you see this repeatedly under live concurrency, file an issue.`),{adapter:s,err:l}=a())}catch(n){process.env.DEBUG&&console.debug("[RVF] stale-lock recovery failed:",n instanceof Error?n.message:n)}if(s){let n=s.dimension();if(n===o)return s;console.warn(`[RVF] patterns.rvf dimension mismatch: file=${n} requested=${o} \u2014 closing and degrading. Delete the .rvf file to recreate at the requested dim.`);try{s.close()}catch{}throw new Error(`RVF dimension mismatch (file=${n}, requested=${o})`)}try{return t(e,o)}catch(n){let c;try{c=r(e)}catch(f){if(p(f))throw f;if(y(e,n instanceof Error?n.message:String(n),f))return t(e,o);throw n instanceof Error?n:new Error(String(n))}let m=c.dimension();if(m!==o){try{c.close()}catch{}throw new Error(`RVF dimension mismatch after race (file=${m}, requested=${o})`)}return c}}function A(r,t){if(t?.force)return{shouldCompact:!0,trigger:"force"};let e=t?.sizeGuardBytes??N,o=t?.deadRatioThreshold??B;return r.fileSizeBytes>=e?{shouldCompact:!0,trigger:"size-guard"}:(r.deadSpaceRatio??0)>=o?{shouldCompact:!0,trigger:"dead-ratio"}:{shouldCompact:!1,trigger:"none"}}function q(r){if(!i)return null;let t;try{t=i.status()}catch{return null}let e=A(t,r);if(!e.shouldCompact)return null;let o=t.fileSizeBytes,a;try{a=i.compact()}catch{return null}return a?((a.bytesReclaimed>0||a.segmentsCompacted>0)&&console.log(`[RVF] compacted patterns.rvf: reclaimed ${u(a.bytesReclaimed)} (${a.segmentsCompacted} segments, fileSize ${u(o)} \u2192 ${u(Math.max(0,o-a.bytesReclaimed))}, trigger: ${e.trigger})`),a):null}function w(r,t){try{let e=r.status(),o=A(e);if(!o.shouldCompact)return null;let a=r.compact();return a&&(a.bytesReclaimed>0||a.segmentsCompacted>0)&&console.log(`[RVF] boot-time compact (${t}): reclaimed ${u(a.bytesReclaimed)} from ${a.segmentsCompacted} segments (trigger: ${o.trigger})`),a}catch(e){return process.env.DEBUG&&console.debug("[RVF] boot-time compact guard skipped:",e instanceof Error?e.message:e),null}}function u(r){if(!Number.isFinite(r)||r<0)return`${r}B`;let t=["B","KB","MB","GB","TB"],e=0,o=r;for(;o>=1024&&e<t.length-1;)o/=1024,e++;return`${o.toFixed(e===0?0:1)}${t[e]}`}function x(){if(i){try{i.close()}catch{}i=null}d=!1}export{k as a,V as b,A as c,q as d,w as e,x as f};
@@ -1,2 +0,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.14.4");process.exit(0)}
2
- import{c as u}from"./chunk-TT23RRB7.js";import*as s from"fs";import*as t from"path";function h(){n=null,c=null}function g(a=process.cwd()){if(process.env.AQE_PROJECT_ROOT)return process.env.AQE_PROJECT_ROOT;let l=t.resolve(a);if(n&&c===l)return n;c=l;let f=t.parse(l).root,e=l,i=null,r=null,o=null;for(;e!==f;)s.existsSync(t.join(e,".agentic-qe"))&&i===null&&(i=e),s.existsSync(t.join(e,".git"))&&r===null&&(r=e),s.existsSync(t.join(e,"package.json"))&&(o=e),e=t.dirname(e);return i?n=i:r?n=r:o?n=o:n=l,n}var n,c,p=u(()=>{"use strict";n=null,c=null});export{h as a,g as b,p as c};
@@ -1,2 +0,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.14.4");process.exit(0)}
2
- var s={"test-generation":/test|spec|describe|it\(|expect|assert|mock|stub|fixture|tdd|bdd/i,"test-execution":/run|execute|parallel|retry|flaky|timeout|worker|orchestrat/i,"coverage-analysis":/coverage|branch|line|uncovered|gap|untested|percentage|sublinear/i,"quality-assessment":/quality|gate|deploy|readiness|metric|threshold|sla|score/i,"defect-intelligence":/defect|bug|predict|root.?cause|regression|failure|incident/i,"requirements-validation":/requirement|bdd|gherkin|testabil|accept|criteri|scenario/i,"code-intelligence":/semantic|knowledge|graph|ast|symbol|reference|impact|depend/i,"security-compliance":/vuln|cve|owasp|xss|sqli|injection|csrf|auth|secret|compliance|sast|dast/i,"contract-testing":/contract|pact|openapi|swagger|graphql|schema|endpoint|api/i,"visual-accessibility":/screenshot|visual|snapshot|pixel|percy|a11y|aria|wcag|screen.?reader|accessible|contrast/i,"chaos-resilience":/chaos|resilience|fault|inject|blast|recover|latency|failure|stress|load/i,"learning-optimization":/learn|pattern|optim|neural|embedding|vector|memory|adapt|train/i};function l(e){for(let[t,a]of Object.entries(s))if(a.test(e))return t;return null}function m(e){let t=[];for(let[a,n]of Object.entries(s))n.test(e)&&t.push(a);return t}function u(e){return e}function d(e){let t=Math.min(e.usageCount/100,1);return e.confidence*.3+t*.2+e.successRate*.5}var c=3;function p(e,t,a=.4){let n=e.tier==="short-term"&&e.successfulUses>=c,r=e.successRate>=.7&&e.confidence>=.6,i=t===void 0||t<a,o;return n?r?i||(o="coherence_violation"):o="low_quality":o="insufficient_usage",{meetsUsageCriteria:n,meetsQualityCriteria:r,meetsCoherenceCriteria:i,blockReason:o}}function y(e){let t=[];if(e.id||t.push("Pattern ID is required"),e.patternType||t.push("Pattern type is required"),e.qeDomain||t.push("QE domain is required"),e.name||t.push("Pattern name is required"),e.template?.content||t.push("Template content is required"),e.confidence!==void 0&&(e.confidence<0||e.confidence>1)&&t.push("Confidence must be between 0 and 1"),e.successRate!==void 0&&(e.successRate<0||e.successRate>1)&&t.push("Success rate must be between 0 and 1"),e.template?.variables){let a=new Set;for(let n of e.template.variables)a.has(n.name)&&t.push(`Duplicate variable name: ${n.name}`),a.add(n.name),e.template.content.includes(`{{${n.name}}}`)||t.push(`Variable ${n.name} not referenced in template`)}return{valid:t.length===0,errors:t}}function f(e,t){let a=e.content;for(let n of e.variables){let r=t[n.name]??n.defaultValue;if(n.required&&r===void 0)throw new Error(`Required variable ${n.name} not provided`);if(r!==void 0){let i=`{{${n.name}}}`,o=typeof r=="object"?JSON.stringify(r):String(r);a=a.split(i).join(o)}}return a}var g=Object.keys(s);export{l as a,m as b,u as c,d,c as e,p as f,y as g,f as h,g as i};
@@ -1,2 +0,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.14.4");process.exit(0)}
2
- var h=Object.create;var f=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var k=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty;var m=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')}),n=a=>b=>{var c=a[b];if(c)return c();throw new Error("Module not found in bundle: "+b)};var o=(a,b,c)=>()=>{if(c)throw c[0];try{return a&&(b=a(a=0)),b}catch(d){throw c=[d],d}};var p=(a,b)=>()=>{try{return b||a((b={exports:{}}).exports,b),b.exports}catch(c){throw b=0,c}},q=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0})},g=(a,b,c,d)=>{if(b&&typeof b=="object"||typeof b=="function")for(let e of j(b))!l.call(a,e)&&e!==c&&f(a,e,{get:()=>b[e],enumerable:!(d=i(b,e))||d.enumerable});return a};var r=(a,b,c)=>(c=a!=null?h(k(a)):{},g(b||!a||!a.__esModule?f(c,"default",{value:a,enumerable:!0}):c,a)),s=a=>g(f({},"__esModule",{value:!0}),a);export{m as a,n as b,o as c,p as d,q as e,r as f,s as g};