agentic-qe 3.14.5 → 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 (426) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +76 -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 +16 -106
  13. package/dist/audit/witness-findings.js +4 -1
  14. package/dist/cli/bundle.js +7 -7
  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-V6CZ7Q6S.js → agent-handler-D5SSQYNU.js} +2 -2
  18. package/dist/cli/chunks/{agent-memory-branch-ZMD6ULC3.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-QLSBESC7.js → arena-7BGOXGXO.js} +2 -2
  21. package/dist/cli/chunks/{arena-4UPAEHFT.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-4DSBPDRH.js → better-sqlite3-PMUNGASU.js} +2 -2
  25. package/dist/cli/chunks/{brain-handler-GBY4EZ4P.js → brain-handler-QPUFYX7F.js} +3 -3
  26. package/dist/cli/chunks/{branch-enumerator-XYBVXCNO.js → branch-enumerator-WKFDGRN4.js} +2 -2
  27. package/dist/cli/chunks/{browser-32F6MREU.js → browser-VY5HKH5X.js} +2 -2
  28. package/dist/cli/chunks/browser-workflow-CJ7T3MXF.js +2 -0
  29. package/dist/cli/chunks/{chunk-C3Z4VVHP.js → chunk-257E2A5M.js} +5 -5
  30. package/dist/cli/chunks/{chunk-EFV4ADMO.js → chunk-2JVWITNK.js} +2 -2
  31. package/dist/cli/chunks/{chunk-IGBEJ4UJ.js → chunk-2NPKIBAZ.js} +2 -2
  32. package/dist/cli/chunks/{chunk-KIP6WZGV.js → chunk-2TMWAQQ3.js} +3 -3
  33. package/dist/cli/chunks/{chunk-DLF5BOJD.js → chunk-2YXGBZWV.js} +1 -1
  34. package/dist/cli/chunks/{chunk-KEY43ANX.js → chunk-3EA536JF.js} +2 -2
  35. package/dist/cli/chunks/{chunk-WX6RRIGW.js → chunk-3EZOZN25.js} +2 -2
  36. package/dist/cli/chunks/{chunk-BYG36QC5.js → chunk-3HZS4M3O.js} +2 -2
  37. package/dist/cli/chunks/{chunk-G3L5L6YQ.js → chunk-3NIG7S5W.js} +1 -1
  38. package/dist/cli/chunks/{chunk-CZO4BJG5.js → chunk-4N23RFDU.js} +2 -2
  39. package/dist/cli/chunks/{chunk-QWUXCG2L.js → chunk-5J6W7SIA.js} +1 -1
  40. package/dist/cli/chunks/{chunk-RD2VGOUH.js → chunk-5OOMJGFN.js} +1 -1
  41. package/dist/cli/chunks/{chunk-YDFL445W.js → chunk-5QQSIGUA.js} +2 -2
  42. package/dist/cli/chunks/{chunk-TUSSPKRM.js → chunk-5VFPCSK7.js} +1 -1
  43. package/dist/cli/chunks/{chunk-WLXK2KNU.js → chunk-62N4NUJH.js} +2 -2
  44. package/dist/cli/chunks/{chunk-JSZ663MU.js → chunk-64VGZQLB.js} +1 -1
  45. package/dist/cli/chunks/{chunk-UMGFMKDW.js → chunk-66VWCR67.js} +2 -2
  46. package/dist/cli/chunks/{chunk-6ITZZIQX.js → chunk-6LIHFV7O.js} +2 -2
  47. package/dist/cli/chunks/{chunk-DKUBQQFG.js → chunk-6OS76PHI.js} +2 -2
  48. package/dist/cli/chunks/{chunk-Y5L3ES4L.js → chunk-6RE3X4V5.js} +2 -2
  49. package/dist/cli/chunks/{chunk-CVMNJSCB.js → chunk-6SH5VZUD.js} +2 -2
  50. package/dist/cli/chunks/chunk-6SQM2MUX.js +4 -0
  51. package/dist/cli/chunks/{chunk-6CR4VQBQ.js → chunk-6U7LNMWZ.js} +2 -2
  52. package/dist/cli/chunks/{chunk-HYEJJJY3.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-K7NJHFLZ.js → chunk-7J6QC567.js} +3 -3
  56. package/dist/cli/chunks/{chunk-6LKDHEBY.js → chunk-7LPR6HJG.js} +2 -2
  57. package/dist/cli/chunks/{chunk-RGGK6VZ7.js → chunk-7NITCZWD.js} +1 -1
  58. package/dist/cli/chunks/{chunk-IYTLXUBO.js → chunk-7Z5LHRC3.js} +2 -2
  59. package/dist/cli/chunks/{chunk-ZCWERUYB.js → chunk-AHKELLIO.js} +3 -3
  60. package/dist/cli/chunks/{chunk-IJHCIXJC.js → chunk-AIRGNL55.js} +2 -2
  61. package/dist/cli/chunks/{chunk-2OMLTYQK.js → chunk-AJRUJAAK.js} +1 -1
  62. package/dist/cli/chunks/{chunk-QYOGD2VW.js → chunk-AVBJYI5I.js} +1 -1
  63. package/dist/cli/chunks/{chunk-PSPKSUF6.js → chunk-B6D2CHEH.js} +1 -1
  64. package/dist/cli/chunks/{chunk-M23ZOZVY.js → chunk-B6MOJC3X.js} +1 -1
  65. package/dist/cli/chunks/{chunk-VD5IO5EO.js → chunk-BAMN2CHI.js} +1 -1
  66. package/dist/cli/chunks/{chunk-KO4FNAUR.js → chunk-BBT64TII.js} +3 -3
  67. package/dist/cli/chunks/{chunk-7JZJJA7U.js → chunk-BJTJLJRZ.js} +3 -3
  68. package/dist/cli/chunks/{chunk-LULD4JV2.js → chunk-BMAPORJ7.js} +2 -2
  69. package/dist/cli/chunks/{chunk-GTKCGPJZ.js → chunk-BPEDWS6O.js} +2 -2
  70. package/dist/cli/chunks/{chunk-3DDXWYMO.js → chunk-BVR7RMC5.js} +1 -1
  71. package/dist/cli/chunks/{chunk-52L77RMG.js → chunk-C6KWXUFJ.js} +2 -2
  72. package/dist/cli/chunks/{chunk-BJPL6THQ.js → chunk-CCK4BF76.js} +1 -1
  73. package/dist/cli/chunks/{chunk-RP2ZKPYV.js → chunk-CD542DNJ.js} +1 -1
  74. package/dist/cli/chunks/{chunk-AFEDJ3RU.js → chunk-CF2ISEOJ.js} +2 -2
  75. package/dist/cli/chunks/chunk-CM7U6TAX.js +5 -0
  76. package/dist/cli/chunks/{chunk-R74ZKREV.js → chunk-D45SG6CP.js} +1 -1
  77. package/dist/cli/chunks/{chunk-YXP6BKGS.js → chunk-D6CJIGRU.js} +89 -83
  78. package/dist/cli/chunks/{chunk-NVYBM3R4.js → chunk-DBDPRORT.js} +2 -2
  79. package/dist/cli/chunks/{chunk-CYE2TJFV.js → chunk-DHVX5UB2.js} +2 -2
  80. package/dist/cli/chunks/{chunk-XUR2M2WB.js → chunk-DK4XN4CU.js} +2 -2
  81. package/dist/cli/chunks/{chunk-W2XCZU62.js → chunk-DPYSUDAO.js} +1 -1
  82. package/dist/cli/chunks/{chunk-WJHWH5D2.js → chunk-DUYOVM5I.js} +2 -2
  83. package/dist/cli/chunks/{chunk-XLAUGSW7.js → chunk-DZ3AUAAB.js} +2 -2
  84. package/dist/cli/chunks/{chunk-37TUN44F.js → chunk-E6G2RD5H.js} +2 -2
  85. package/dist/cli/chunks/{chunk-ELBZON4V.js → chunk-EAY2JMZG.js} +2 -2
  86. package/dist/cli/chunks/{chunk-HSVKZ5KI.js → chunk-ELLBS5RP.js} +2 -2
  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-F34OAHOM.js → chunk-FWASDOT2.js} +2 -2
  90. package/dist/cli/chunks/{chunk-E4AZXCT5.js → chunk-FZOBD67M.js} +1 -1
  91. package/dist/cli/chunks/{chunk-QZMUXJHZ.js → chunk-GDSXITFH.js} +2 -2
  92. package/dist/cli/chunks/{chunk-LSUILON7.js → chunk-GGRHV6D7.js} +1 -1
  93. package/dist/cli/chunks/{chunk-3YUB5HER.js → chunk-GPYVDFB3.js} +101 -101
  94. package/dist/cli/chunks/{chunk-4FWTLJEP.js → chunk-GSF6MB64.js} +2 -2
  95. package/dist/cli/chunks/{chunk-3KDL6QDK.js → chunk-H52HZ67P.js} +2 -2
  96. package/dist/cli/chunks/{chunk-2JGEZHWY.js → chunk-H5BS5VH7.js} +2 -2
  97. package/dist/cli/chunks/{chunk-SQF6HRXR.js → chunk-H6ZM3PUT.js} +1 -1
  98. package/dist/cli/chunks/{chunk-OEIQTWQP.js → chunk-HM6ZSCPI.js} +1 -1
  99. package/dist/cli/chunks/{chunk-URVHZPWY.js → chunk-HNFVJP4I.js} +2 -2
  100. package/dist/cli/chunks/{chunk-RD6TEZ64.js → chunk-I33ERSGB.js} +2 -2
  101. package/dist/cli/chunks/{chunk-IUDWEOLX.js → chunk-IAF6T27S.js} +2 -2
  102. package/dist/cli/chunks/{chunk-XZSMZHM2.js → chunk-IB27QACC.js} +2 -2
  103. package/dist/cli/chunks/{chunk-I6X3EGJI.js → chunk-ICTXTNQZ.js} +1 -1
  104. package/dist/cli/chunks/chunk-IG5GNEC6.js +4 -0
  105. package/dist/cli/chunks/{chunk-6A44AOGN.js → chunk-IQO7UCFR.js} +2 -2
  106. package/dist/cli/chunks/{chunk-R6IU3EWP.js → chunk-IV5UZOHH.js} +2 -2
  107. package/dist/cli/chunks/{chunk-VTOVWHEM.js → chunk-JBTPOIAC.js} +2 -2
  108. package/dist/cli/chunks/{chunk-KLTP5IDB.js → chunk-JIXUMYKZ.js} +1 -1
  109. package/dist/cli/chunks/{chunk-3VIXOHMS.js → chunk-JMONHE4B.js} +1 -1
  110. package/dist/cli/chunks/{chunk-SX4JLSLV.js → chunk-JVNTSNWU.js} +2 -2
  111. package/dist/cli/chunks/{chunk-JVQBWYHW.js → chunk-JXGFRBUO.js} +2 -2
  112. package/dist/cli/chunks/{chunk-HVXJC3OC.js → chunk-JZOS5FCX.js} +2 -2
  113. package/dist/cli/chunks/{chunk-XEZIIQYJ.js → chunk-KNNISEDY.js} +1 -1
  114. package/dist/cli/chunks/{chunk-73EI4C2E.js → chunk-L4RUBPLR.js} +2 -2
  115. package/dist/cli/chunks/{chunk-AF4XKLXO.js → chunk-LL3IGZBI.js} +2 -2
  116. package/dist/cli/chunks/{chunk-UJWAWIRV.js → chunk-MBRHSU6W.js} +10 -10
  117. package/dist/cli/chunks/{chunk-J5UNP6W3.js → chunk-MJS53PRX.js} +2 -2
  118. package/dist/cli/chunks/{chunk-EOR2UT72.js → chunk-MQROI74N.js} +2 -2
  119. package/dist/cli/chunks/{chunk-BXVAVFGU.js → chunk-MUOG6QXR.js} +2 -2
  120. package/dist/cli/chunks/{chunk-O3JTQ7N4.js → chunk-MW2GGZZ5.js} +1 -1
  121. package/dist/cli/chunks/{chunk-IIAR5S7Q.js → chunk-NHWGMJAP.js} +2 -2
  122. package/dist/cli/chunks/{chunk-WOIGKU2N.js → chunk-NMAIY4PX.js} +3 -3
  123. package/dist/cli/chunks/{chunk-QIRL6B3C.js → chunk-NQZ5AR3D.js} +2 -2
  124. package/dist/cli/chunks/{chunk-6TU7FEMD.js → chunk-P6OYS755.js} +1 -1
  125. package/dist/cli/chunks/{chunk-HVU64GP5.js → chunk-PI7TJS62.js} +2 -2
  126. package/dist/cli/chunks/{chunk-N7H767TP.js → chunk-PX5YDCRH.js} +2 -2
  127. package/dist/cli/chunks/{chunk-3EZ5DR2R.js → chunk-PZPWRQ2M.js} +2 -2
  128. package/dist/cli/chunks/{chunk-RKOUXVZZ.js → chunk-Q5XTSMWR.js} +2 -2
  129. package/dist/cli/chunks/{chunk-K27SU3RE.js → chunk-Q7EAGKAE.js} +2 -2
  130. package/dist/cli/chunks/{chunk-M5AEL7IS.js → chunk-QDFTT3RF.js} +2 -2
  131. package/dist/cli/chunks/{chunk-TY5WC3FT.js → chunk-QGA55PFM.js} +3 -3
  132. package/dist/cli/chunks/{chunk-NQI7FWCS.js → chunk-QW6VMTBR.js} +2 -2
  133. package/dist/cli/chunks/{chunk-BHFR2EXL.js → chunk-QZANMBIT.js} +1 -1
  134. package/dist/cli/chunks/{chunk-5D36YHS3.js → chunk-RETBYIAC.js} +4 -4
  135. package/dist/cli/chunks/{chunk-UKGXWW64.js → chunk-RFNPJK6N.js} +3 -3
  136. package/dist/cli/chunks/{chunk-G3W6BMVJ.js → chunk-RG52OKAM.js} +1 -1
  137. package/dist/cli/chunks/{chunk-DO6EI5KB.js → chunk-RSXXCL4A.js} +1 -1
  138. package/dist/cli/chunks/{chunk-E3W6XQ57.js → chunk-RTFO5UQH.js} +2 -2
  139. package/dist/cli/chunks/{chunk-DDCIYOGT.js → chunk-RZZCUIAI.js} +2 -2
  140. package/dist/cli/chunks/{chunk-C3HQL6S4.js → chunk-SDRHUMJB.js} +2 -2
  141. package/dist/cli/chunks/{chunk-KYA5LARK.js → chunk-SE4WIB26.js} +1 -1
  142. package/dist/cli/chunks/{chunk-NU7UTXMP.js → chunk-SESK3ARK.js} +2 -2
  143. package/dist/cli/chunks/{chunk-YQGPQBCX.js → chunk-SJUXE4IC.js} +2 -2
  144. package/dist/cli/chunks/{chunk-HBCGYMQU.js → chunk-SMDN3BQZ.js} +1 -1
  145. package/dist/cli/chunks/{chunk-D6OUCB2H.js → chunk-SNOBH4AZ.js} +2 -2
  146. package/dist/cli/chunks/{chunk-QRCIZFNK.js → chunk-SPV2VKC5.js} +2 -2
  147. package/dist/cli/chunks/chunk-TCHGOB2N.js +2 -0
  148. package/dist/cli/chunks/{chunk-2KJQ2UQE.js → chunk-TVYY3OCX.js} +1 -1
  149. package/dist/cli/chunks/{chunk-RIZVC4XY.js → chunk-UCFQALXO.js} +2 -2
  150. package/dist/cli/chunks/{chunk-XFPPERA2.js → chunk-UKA2KOXE.js} +2 -2
  151. package/dist/cli/chunks/{chunk-UTBYJ4RF.js → chunk-UNFFDHER.js} +16 -11
  152. package/dist/cli/chunks/{chunk-6VAZAHQG.js → chunk-UQ32JHES.js} +2 -2
  153. package/dist/cli/chunks/{chunk-CPC7FN52.js → chunk-V4DM6ELU.js} +2 -2
  154. package/dist/cli/chunks/{chunk-67YV75XP.js → chunk-VGFFFKGK.js} +2 -2
  155. package/dist/cli/chunks/{chunk-WK7B4B6Y.js → chunk-VMNWDJIZ.js} +2 -2
  156. package/dist/cli/chunks/chunk-W6HXLH5G.js +180 -0
  157. package/dist/cli/chunks/{chunk-7VFY7TUR.js → chunk-WCJBU2KI.js} +2 -2
  158. package/dist/cli/chunks/{chunk-JROVR6YS.js → chunk-WGM35YWL.js} +2 -2
  159. package/dist/cli/chunks/{chunk-IUHB5GVS.js → chunk-WO4QMXIG.js} +2 -2
  160. package/dist/cli/chunks/{chunk-JES6R5KP.js → chunk-XAS3XRYM.js} +1 -1
  161. package/dist/cli/chunks/chunk-Y3LZ35OG.js +2 -0
  162. package/dist/cli/chunks/{chunk-75QJ5HWE.js → chunk-Y3UOUNHM.js} +2 -2
  163. package/dist/cli/chunks/{chunk-WJTSY5MC.js → chunk-YFBSPLJG.js} +1 -1
  164. package/dist/cli/chunks/{chunk-DPBRWP4J.js → chunk-YHKEDEAA.js} +3 -3
  165. package/dist/cli/chunks/{chunk-NRE4NAVA.js → chunk-YS4FCTWF.js} +1 -1
  166. package/dist/cli/chunks/{chunk-I2NENQ44.js → chunk-YSLL6VSL.js} +2 -2
  167. package/dist/cli/chunks/chunk-Z6GGIRQQ.js +65 -0
  168. package/dist/cli/chunks/{chunk-E4EYPYR3.js → chunk-Z7WODOTH.js} +2 -2
  169. package/dist/cli/chunks/{chunk-7DETTOPZ.js → chunk-ZCRTRYXK.js} +2 -2
  170. package/dist/cli/chunks/{chunk-FUNGTIF2.js → chunk-ZEV3YTO7.js} +2 -2
  171. package/dist/cli/chunks/{chunk-SQKW3B6B.js → chunk-ZL6SYKUK.js} +1 -1
  172. package/dist/cli/chunks/{chunk-AMMQOV35.js → chunk-ZSPU4MOS.js} +2 -2
  173. package/dist/cli/chunks/{chunk-KKHYJF5U.js → chunk-ZVWVV4EX.js} +1 -1
  174. package/dist/cli/chunks/{ci-RACDAJMR.js → ci-W6K6G2KZ.js} +2 -2
  175. package/dist/cli/chunks/{ci-output-EHRSZBKG.js → ci-output-LDT24TS3.js} +2 -2
  176. package/dist/cli/chunks/{circuit-breaker-GBV7M5XG.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-W4NMXJSG.js → cline-installer-G7TJOAEX.js} +2 -2
  180. package/dist/cli/chunks/{code-JWXJMYXB.js → code-PGE6A42V.js} +3 -3
  181. package/dist/cli/chunks/{code-index-extractor-RVI2IFTM.js → code-index-extractor-RNITH372.js} +2 -2
  182. package/dist/cli/chunks/{codex-installer-3BORJINH.js → codex-installer-LBX77AI3.js} +6 -6
  183. package/dist/cli/chunks/{completions-A55NCTAO.js → completions-4AWLAARX.js} +2 -2
  184. package/dist/cli/chunks/{complexity-analyzer-JCXHGGLY.js → complexity-analyzer-ZPNSS476.js} +2 -2
  185. package/dist/cli/chunks/{continuedev-installer-PUVFMGYW.js → continuedev-installer-UAPWX6OA.js} +2 -2
  186. package/dist/cli/chunks/{copilot-installer-4DCMYWHB.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-5TV2GGKY.js → cost-tracker-MHP2VJ63.js} +2 -2
  189. package/dist/cli/chunks/{coverage-NNWM7TX3.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-4NCHGJGK.js → cursor-installer-ZXBWYAS3.js} +2 -2
  192. package/dist/cli/chunks/{daemon-T4JO4IXP.js → daemon-64C7R6OJ.js} +3 -3
  193. package/dist/cli/chunks/{daemon-QIKCXKWO.js → daemon-N2BEGEFY.js} +4 -4
  194. package/dist/cli/chunks/{dag-attention-scheduler-RPAAIDAD.js → dag-attention-scheduler-SPZDAPNL.js} +2 -2
  195. package/dist/cli/chunks/{detect-SBEEVDSN.js → detect-LXJBSSZW.js} +2 -2
  196. package/dist/cli/chunks/{dist-node-ZHI6NCSU.js → dist-node-U3TKZ2IZ.js} +2 -2
  197. package/dist/cli/chunks/{domain-handler-LBC3GJ7Z.js → domain-handler-3DDWUVSR.js} +2 -2
  198. package/dist/cli/chunks/{domain-plugins-H6IZ5USZ.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-AHTR7CRU.js → embed-and-insert-pattern-JPAR7TXX.js} +2 -2
  202. package/dist/cli/chunks/{eval-DZU2KISM.js → eval-SOLG23EA.js} +2 -2
  203. package/dist/cli/chunks/{experience-capture-middleware-5IQCWKSL.js → experience-capture-middleware-T7G2VOOD.js} +3 -3
  204. package/dist/cli/chunks/{fast-paths-2KLDUWCY.js → fast-paths-32N3ELI4.js} +2 -2
  205. package/dist/cli/chunks/{feature-flags-N6UAEZY4.js → feature-flags-APJDQ4N7.js} +2 -2
  206. package/dist/cli/chunks/{feature-flags-7AC3XDZA.js → feature-flags-NAHKLDRN.js} +2 -2
  207. package/dist/cli/chunks/{file-discovery-5SDIW4V2.js → file-discovery-YKVM3MDB.js} +2 -2
  208. package/dist/cli/chunks/{fleet-ZIQCAZ2Y.js → fleet-55M5CJS4.js} +3 -3
  209. package/dist/cli/chunks/{gnn-wrapper-DUMBZJEV.js → gnn-wrapper-UD6E6S6Z.js} +2 -2
  210. package/dist/cli/chunks/{heartbeat-handler-6HVM6ZMR.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-5DRL5FLX.js → hnsw-legacy-bridge-HBYIS3ZW.js} +2 -2
  215. package/dist/cli/chunks/{hnswlib-node-GW67GTCL.js → hnswlib-node-EQPM42OU.js} +2 -2
  216. package/dist/cli/chunks/{hooks-QHH6FVO4.js → hooks-5ZSSJWO6.js} +10 -10
  217. package/dist/cli/chunks/hybrid-backend-CCF7URKI.js +2 -0
  218. package/dist/cli/chunks/{hypergraph-engine-7XDCCVG2.js → hypergraph-engine-XBGVQ4PD.js} +2 -2
  219. package/dist/cli/chunks/{hypergraph-handler-QHF7NOU5.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-5UIVOM7K.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-TGGV6K5Q.js → kilocode-installer-F7LXBM7I.js} +2 -2
  225. package/dist/cli/chunks/{kiro-installer-4XYBHZWW.js → kiro-installer-NM723ZRG.js} +2 -2
  226. package/dist/cli/chunks/knowledge-graph-DG44IPEI.js +2 -0
  227. package/dist/cli/chunks/{learning-STE5W6BS.js → learning-5QYIDHH3.js} +3 -3
  228. package/dist/cli/chunks/{llm-router-NKF7J3RI.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-B2T77UJQ.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-WRFZKG56.js → memory-FWCPCQFP.js} +5 -5
  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-J36EMQU7.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-BVMTWI3E.js → pattern-usage-recorder-7CEUC3J7.js} +2 -2
  241. package/dist/cli/chunks/{pipeline-OWAHDUAQ.js → pipeline-IGUQPPPO.js} +2 -2
  242. package/dist/cli/chunks/{platform-ANGBFWBV.js → platform-2P636I7B.js} +2 -2
  243. package/dist/cli/chunks/{plugin-OO7ON2YW.js → plugin-NY6SWDPE.js} +2 -2
  244. package/dist/cli/chunks/{prime-radiant-advanced-wasm-HFG3BXWU.js → prime-radiant-advanced-wasm-2UUDTIO2.js} +2 -2
  245. package/dist/cli/chunks/{project-root-LNOYVTYY.js → project-root-IOISG5KX.js} +2 -2
  246. package/dist/cli/chunks/protocol-executor-IBYEII5Q.js +2 -0
  247. package/dist/cli/chunks/{protocol-handler-CE3Q6LY4.js → protocol-handler-ZTPCRQ5W.js} +2 -2
  248. package/dist/cli/chunks/{prove-7XPN53PY.js → prove-SQX5A3IG.js} +2 -2
  249. package/dist/cli/chunks/qe-reasoning-bank-7IETWW6W.js +2 -0
  250. package/dist/cli/chunks/{quality-TT23JRFX.js → quality-DROILKRY.js} +2 -2
  251. package/dist/cli/chunks/{quality-gate-PPPRP255.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-EYNZIFJE.js → real-embeddings-P5U3MGYC.js} +2 -2
  254. package/dist/cli/chunks/{ref-validation-QQR64ZXD.js → ref-validation-KY73NQXD.js} +2 -2
  255. package/dist/cli/chunks/{roocode-installer-UIGS7ZJD.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-6AENUIRG.js → routing-handler-VTJIVFUO.js} +2 -2
  259. package/dist/cli/chunks/{ruvector-commands-5AWMEV34.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-NWRJ7C22.js → rvf-migration-coordinator-R53URRIO.js} +2 -2
  263. package/dist/cli/chunks/rvf-native-adapter-MOF3E7BR.js +2 -0
  264. package/dist/cli/chunks/{rvf-store-integrity-ISKRP563.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-325A7FMB.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-THFDYS2Z.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-UD4MJ6GZ.js → standalone-memory-M4LWAAYZ.js} +2 -2
  273. package/dist/cli/chunks/{status-handler-CPFTN4XL.js → status-handler-YYFV6OZL.js} +2 -2
  274. package/dist/cli/chunks/{structural-health-2MG2IVBL.js → structural-health-27E6LLKB.js} +2 -2
  275. package/dist/cli/chunks/sync-26CEGSTC.js +2 -0
  276. package/dist/cli/chunks/{sync-EE4VVKOW.js → sync-J3LJ56WN.js} +2 -2
  277. package/dist/cli/chunks/{task-handler-7H5OYJG4.js → task-handler-4MCEBQZL.js} +2 -2
  278. package/dist/cli/chunks/{task-handlers-NH4GJHCJ.js → task-handlers-GYBAWKE2.js} +3 -3
  279. package/dist/cli/chunks/{test-MPHGT4T6.js → test-MPC5HRH5.js} +4 -4
  280. package/dist/cli/chunks/{test-scheduling-CHQ4ZLLJ.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-EBXUJNRB.js → token-usage-3X5WMTG2.js} +2 -2
  283. package/dist/cli/chunks/{transformers-ZEKS2OJZ.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-KYAA5VLV.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-UJBJ5AYM.js → upgrade-ETBHDEPY.js} +2 -2
  290. package/dist/cli/chunks/{validate-RUV6YMWS.js → validate-C2A73LZK.js} +2 -2
  291. package/dist/cli/chunks/{validate-swarm-IVEVMGVM.js → validate-swarm-67XN42ML.js} +2 -2
  292. package/dist/cli/chunks/{vibium-HOGMFJ2Z.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-AVWA6HKE.js → web-tree-sitter-USJN77P4.js} +2 -2
  295. package/dist/cli/chunks/{windsurf-installer-DAH7HI2W.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-JSTBMG43.js → witness-key-manager-ZWEIK3VJ.js} +2 -2
  301. package/dist/cli/chunks/{workflow-TWOIA6LZ.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/index.js +2 -1
  308. package/dist/init/agents-installer.d.ts +4 -0
  309. package/dist/init/agents-installer.js +24 -11
  310. package/dist/init/codex-installer.js +4 -2
  311. package/dist/init/idempotent-write.d.ts +53 -0
  312. package/dist/init/idempotent-write.js +160 -0
  313. package/dist/init/phases/05-learning.js +3 -1
  314. package/dist/init/phases/07-hooks.js +32 -16
  315. package/dist/init/phases/08-mcp.js +4 -2
  316. package/dist/init/phases/10-workers.js +7 -5
  317. package/dist/init/phases/12-verification.js +7 -2
  318. package/dist/init/project-analyzer.d.ts +9 -0
  319. package/dist/init/project-analyzer.js +20 -1
  320. package/dist/init/self-configurator.d.ts +5 -3
  321. package/dist/init/self-configurator.js +18 -29
  322. package/dist/init/skills-installer.js +4 -2
  323. package/dist/init/types.d.ts +6 -0
  324. package/dist/init/types.js +20 -24
  325. package/dist/integrations/coherence/coherence-service.js +84 -24
  326. package/dist/integrations/coherence/vote-tally.d.ts +38 -0
  327. package/dist/integrations/coherence/vote-tally.js +39 -0
  328. package/dist/integrations/ruvector/shared-rvf-adapter.d.ts +23 -0
  329. package/dist/integrations/ruvector/shared-rvf-adapter.js +24 -0
  330. package/dist/kernel/kernel.js +3 -2
  331. package/dist/learning/pattern-store.d.ts +11 -0
  332. package/dist/learning/pattern-store.js +26 -8
  333. package/dist/learning/qe-patterns.d.ts +6 -0
  334. package/dist/learning/qe-patterns.js +7 -1
  335. package/dist/learning/qe-reasoning-bank.js +3 -0
  336. package/dist/learning/rvf-pattern-store.js +20 -7
  337. package/dist/learning/sqlite-persistence.d.ts +8 -1
  338. package/dist/learning/sqlite-persistence.js +49 -9
  339. package/dist/logging/console-logger.d.ts +2 -5
  340. package/dist/logging/console-logger.js +10 -46
  341. package/dist/logging/index.d.ts +2 -0
  342. package/dist/logging/index.js +1 -0
  343. package/dist/logging/redaction.d.ts +27 -0
  344. package/dist/logging/redaction.js +170 -0
  345. package/dist/mcp/bundle.js +435 -421
  346. package/dist/mcp/handlers/core-handlers.js +5 -4
  347. package/dist/mcp/protocol-server.js +2 -1
  348. package/dist/mcp/tools/base.d.ts +9 -2
  349. package/dist/mcp/tools/base.js +7 -0
  350. package/dist/mcp/tools/coherence/consensus.js +51 -2
  351. package/dist/mcp/tools/planning/goap-plan.d.ts +20 -7
  352. package/dist/mcp/tools/planning/goap-plan.js +92 -20
  353. package/dist/mcp/tools/planning/goap-status.d.ts +37 -12
  354. package/dist/mcp/tools/planning/goap-status.js +52 -23
  355. package/dist/mcp/tools/planning/world-state.d.ts +101 -0
  356. package/dist/mcp/tools/planning/world-state.js +274 -0
  357. package/dist/mcp/types.d.ts +4 -2
  358. package/dist/planning/goap-planner.d.ts +60 -4
  359. package/dist/planning/goap-planner.js +218 -60
  360. package/dist/planning/index.d.ts +1 -1
  361. package/dist/planning/index.js +1 -1
  362. package/dist/planning/plan-executor.d.ts +20 -1
  363. package/dist/planning/plan-executor.js +209 -100
  364. package/dist/planning/types.d.ts +16 -0
  365. package/dist/planning/types.js +17 -0
  366. package/package.json +1 -1
  367. package/dist/cli/chunks/adapter-IYC62SXA.js +0 -2
  368. package/dist/cli/chunks/agent-booster-wasm-EDNKP3SP.js +0 -2
  369. package/dist/cli/chunks/aqe-learning-engine-LLOU2IXD.js +0 -2
  370. package/dist/cli/chunks/audit-CVZQMF55.js +0 -3
  371. package/dist/cli/chunks/base-P3Z4IKCT.js +0 -2
  372. package/dist/cli/chunks/browser-workflow-YYHQQ25X.js +0 -2
  373. package/dist/cli/chunks/chunk-5WOSWNDN.js +0 -2
  374. package/dist/cli/chunks/chunk-7CD7PBHY.js +0 -3
  375. package/dist/cli/chunks/chunk-7X7JYWT4.js +0 -27
  376. package/dist/cli/chunks/chunk-J27F4NSB.js +0 -2
  377. package/dist/cli/chunks/chunk-MI5Q55DG.js +0 -65
  378. package/dist/cli/chunks/chunk-UDHVCKGA.js +0 -5
  379. package/dist/cli/chunks/chunk-XQSIRBKT.js +0 -180
  380. package/dist/cli/chunks/chunk-ZBABIZ2D.js +0 -2
  381. package/dist/cli/chunks/claude-flow-setup-5LVJOFKP.js +0 -2
  382. package/dist/cli/chunks/client-HUVFA5PF.js +0 -2
  383. package/dist/cli/chunks/core-handlers-UEXO3VAA.js +0 -2
  384. package/dist/cli/chunks/cross-domain-router-ODU5IZD6.js +0 -2
  385. package/dist/cli/chunks/domain-transfer-JZA5TMW3.js +0 -2
  386. package/dist/cli/chunks/dream-HE3OX42F.js +0 -2
  387. package/dist/cli/chunks/heartbeat-scheduler-QUIFGGLX.js +0 -2
  388. package/dist/cli/chunks/hnsw-adapter-42KB37KP.js +0 -2
  389. package/dist/cli/chunks/hnsw-index-T2PGO77J.js +0 -2
  390. package/dist/cli/chunks/hybrid-backend-FRNWYRKH.js +0 -2
  391. package/dist/cli/chunks/impact-analyzer-A5QYOYBR.js +0 -2
  392. package/dist/cli/chunks/init-wizard-XBU674YH.js +0 -2
  393. package/dist/cli/chunks/kernel-DV5MTNZD.js +0 -2
  394. package/dist/cli/chunks/knowledge-graph-4ACGVJQK.js +0 -2
  395. package/dist/cli/chunks/llm-router-service-PSMASERT.js +0 -2
  396. package/dist/cli/chunks/load-test-MRUO2VPF.js +0 -2
  397. package/dist/cli/chunks/mcp-JGSFCEMH.js +0 -2
  398. package/dist/cli/chunks/memory-backend-2MPGI6JW.js +0 -2
  399. package/dist/cli/chunks/memory-handlers-XT4HMITB.js +0 -2
  400. package/dist/cli/chunks/multi-model-executor-26Q5BSVG.js +0 -14
  401. package/dist/cli/chunks/orchestrator-D5IFV65I.js +0 -393
  402. package/dist/cli/chunks/pattern-null-store-TGWUL237.js +0 -2
  403. package/dist/cli/chunks/protocol-executor-GEVH5KD6.js +0 -2
  404. package/dist/cli/chunks/qe-reasoning-bank-DJ2JL6QB.js +0 -2
  405. package/dist/cli/chunks/queen-coordinator-F7E3AS26.js +0 -2
  406. package/dist/cli/chunks/router-OZH3QSAU.js +0 -2
  407. package/dist/cli/chunks/routing-feedback-J2E3ADZB.js +0 -2
  408. package/dist/cli/chunks/rvf-dual-writer-HK525Y5Y.js +0 -2
  409. package/dist/cli/chunks/rvf-migration-adapter-Q7FB3BKR.js +0 -2
  410. package/dist/cli/chunks/rvf-native-adapter-5ZRCGUI6.js +0 -2
  411. package/dist/cli/chunks/safe-db-3OYEPVEH.js +0 -2
  412. package/dist/cli/chunks/schedule-AG4C2EIQ.js +0 -2
  413. package/dist/cli/chunks/scheduler-SQS2CZFZ.js +0 -2
  414. package/dist/cli/chunks/shared-rvf-adapter-NFL6QSZ6.js +0 -2
  415. package/dist/cli/chunks/sqlite-persistence-MAKDFSHC.js +0 -2
  416. package/dist/cli/chunks/sync-MBTW5XBF.js +0 -2
  417. package/dist/cli/chunks/token-bootstrap-SSDCYEKK.js +0 -2
  418. package/dist/cli/chunks/tree-sitter-wasm-parser-J6ZMAK37.js +0 -2
  419. package/dist/cli/chunks/unified-memory-DDWMC435.js +0 -2
  420. package/dist/cli/chunks/unified-memory-hnsw-4JA7SGBK.js +0 -2
  421. package/dist/cli/chunks/unified-persistence-F6OSNTXY.js +0 -2
  422. package/dist/cli/chunks/visual-security-25SMBIYT.js +0 -2
  423. package/dist/cli/chunks/witness-chain-PJOQPFUX.js +0 -2
  424. package/dist/cli/chunks/witness-chain-ZW6KKUZU.js +0 -2
  425. package/dist/cli/chunks/workflow-orchestrator-UKSIDM7Q.js +0 -2
  426. package/dist/cli/chunks/wrappers-UR7BLXKV.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.5");process.exit(0)}
2
- import{d as W,e as V,f as se,g as X}from"./chunk-5WOSWNDN.js";import{a as oe}from"./chunk-WJTSY5MC.js";import{b as ke}from"./chunk-ZBABIZ2D.js";import{a as ae,b as Ne,d as Me,f as dt}from"./chunk-SX4JLSLV.js";import{c as G,e as He,f as Le}from"./chunk-HBCGYMQU.js";import{a as ce}from"./chunk-6CR4VQBQ.js";import{c as _e,n as T,o as j}from"./chunk-KIP6WZGV.js";import{b as Oe,c as lt}from"./chunk-C3HQL6S4.js";import{c as P,d as v}from"./chunk-XEZIIQYJ.js";import{a as S,b as De,c as Fe}from"./chunk-J5UNP6W3.js";import{i as F}from"./chunk-W2XCZU62.js";import{B as $,D as L,G as ie,P as k,S as O,b as D}from"./chunk-WJHWH5D2.js";import{c as B,e as ct}from"./chunk-JSZ663MU.js";var Z=B(E=>{var St=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 wt=Object.prototype.hasOwnProperty;function me(n,e){return wt.call(n,e)}E.hasOwnProperty=me;function We(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)me(n,i)&&r.push(i);return r}E._objectKeys=We;function Pt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}E._deepClone=Pt;function bt(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=bt;function he(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}E.escapePathComponent=he;function Et(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}E.unescapePathComponent=Et;function pe(n,e){var t;for(var r in n)if(me(n,r)){if(n[r]===e)return he(r)+"/";if(typeof n[r]=="object"&&(t=pe(n[r],e),t!=""))return he(r)+"/"+t}return""}E._getPathRecursive=pe;function Rt(n,e){if(n===e)return"/";var t=pe(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}E.getPath=Rt;function fe(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(fe(n[e]))return!0}else if(typeof n=="object"){for(var r=We(n),i=r.length,s=0;s<i;s++)if(fe(n[r[s]]))return!0}}return!1}E.hasUndefined=fe;function je(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){St(e,n);function e(t,r,i,s,o){var c=this.constructor,d=n.call(this,je(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=je(t,{name:r,index:i,operation:s,tree:o}),d}return e})(Error);E.PatchError=At});var ge=B(g=>{Object.defineProperty(g,"__esModule",{value:!0});var A=Z();g.JsonPatchError=A.PatchError;g.deepClone=A._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=ee(t,this.path);r&&(r=A._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=ee(t,this.from);return _(t,{op:"add",path:this.path,value:A._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}}},Tt={add:function(n,e,t){return A.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 ee(n,e){if(e=="")return n;var t={op:"_get",path:e};return _(n,t),t.value}g.getValueByPointer=ee;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):te(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=ee(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=A._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=te;;){if(u=d[l],u&&u.indexOf("~")!=-1&&(u=A.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&&!A.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);A.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=Tt[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 Ve(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=A._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=Ve;function Ct(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=Ct;function te(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")&&A.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=Xe([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=te;function Xe(n,e,t){try{if(!Array.isArray(n))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Ve(A._deepClone(e),A._deepClone(n),t||!0);else{t=t||te;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=Xe;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 Ge=B(q=>{Object.defineProperty(q,"__esModule",{value:!0});var b=Z(),xt=ge(),ve=new WeakMap,It=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Dt=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function Ft(n){return ve.get(n)}function Ot(n,e){return n.observers.get(e)}function _t(n,e){n.observers.delete(e.callback)}function Nt(n,e){e.unobserve()}q.unobserve=Nt;function Mt(n,e){var t=[],r,i=Ft(n);if(!i)i=new It(n),ve.set(n,i);else{var s=Ot(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(){ye(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(){ye(r),clearTimeout(r.next),_t(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 Dt(e,r)),r}q.observe=Mt;function ye(n,e){e===void 0&&(e=!1);var t=ve.get(n.object);Se(t.value,n.object,n.patches,"",e),n.patches.length&&xt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}q.generate=ye;function Se(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)?Se(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 Ht(n,e,t){t===void 0&&(t=!1);var r=[];return Se(n,e,r,"",t),r}q.compare=Ht});var Ye=B(N=>{var Lt=ge();Object.assign(N,Lt);var kt=Ge();Object.assign(N,kt);var re=Z();N.JsonPatchError=re.PatchError;N.deepClone=re._deepClone;N.escapePathComponent=re.escapePathComponent;N.unescapePathComponent=re.unescapePathComponent});var R=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}};lt();import{existsSync as Xt}from"node:fs";import{join as st}from"node:path";Fe();var z=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??Y,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.embeddingSpaceId&&!T()&&await j(),this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension);let e=T()?.spaceId??this.embeddingSpaceId??null;_e(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 initialization failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: check the embedder endpoint and @ruvector/rvf-node binding, or set RUVECTOR_USE_RVF_PATTERN_STORE=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-MAKDFSHC.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=X(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 R(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 R(e.id,"FAILED",s))}if(e.embedding&&!this.adapter&&this.rvfInitError)return v(new R(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 R(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:F(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:W({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>=V&&(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}}};dt();Fe();O();function ht(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 ft(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 K(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>K(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>K(n,r))}case"NOT":return e.child?!K(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=ht(n,e.field);return ft(t,e.operator,e.value)}default:return!0}}function Ue(n,e){return e?n.filter(t=>K(t,e)):n}O();O();var Qe=1e4,$e=2166136261;function ze(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 ue=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;ue[n]=e}var qe="0123456789abcdef";function mt(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=qe[i>>4]+qe[i&15]}return t}function pt(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 gt(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 yt(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+=ue[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function vt(n,e,t){return 1-yt(n,e,t)}var le=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Qe,this.baseSeed=e?.seed??$e,this.byteLen=Math.ceil(this.dimensions/8),this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}tokenToHypervector(e){let t=this.tokenCache.get(e);if(t)return new Uint8Array(t);let r=ze(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=pt(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 gt([r,i])}similarity(e,t){return vt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new oe(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}},de=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Qe,this.baseSeed=e?.seed??$e,this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}fingerprint(e){let t=`${e.id}|${e.domain}|${e.type}|${e.content??""}`,r=ze(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:mt(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+=ue[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 oe(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 Je(n){return new de(n)}function Be(n){return $()?new le(n):null}var Pe=ct(Ye(),1),we=Pe.default??Pe,Ut=`
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 Ke(n,e){let t=we.compare(n,e),r=we.compare(e,n);return{forward:t,reverse:r}}function qt(n,e){let t=JSON.parse(JSON.stringify(n));return we.applyPatch(t,e).newDocument}function Ze(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 ne=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(Ut),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:F(),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}=Ke(t,r),d={id:F(),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}=Ke(o,s),a={id:F(),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(Ze)}incrementalSync(e){return this.ensureInitialized(),this.prepared.get("incrementalSync").all(e).map(Ze)}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=qt(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},be=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 et(n){return L()?new be(n):null}O();var $t=128,zt=8,Jt=1e4,Ee=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??$t,this.beta=e?.beta??zt,this.maxPatterns=e?.maxPatterns??Jt,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(!D().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function tt(n){return new Ee(n)}O();var Bt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},M=1e-5,rt=1-M;function jt(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 Wt(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(Wt(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=jt(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<=rt)return new Float32Array(e);let r=rt/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)}},Re=class{config;points=new Map;constructor(e){if(this.config={...Bt,...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 nt(n){return Vt()?new Re(n):null}function Vt(){return D().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=nt(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 it(n){return new Ae(n)}var Te=null;function at(){return Te||(Te=Je({dimensions:1e4})),Te}var Ce;function Gt(){return Ce===void 0&&(Ce=Be()),Ce}var Q=null,xe=0;function ot(n){return(!Q||xe!==n)&&(Q=tt({dimension:n,maxPatterns:1e4}),xe=n),Q}var Y={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:V,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}},Ie=class{constructor(e,t={}){this.memory=e;this.config={...Y,...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 ne(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(!T()&&!this.config.embeddingSpaceId&&await j(),this.hnswSpaceId=T()?.spaceId??this.config.embeddingSpaceId??null,!this.hnswSpaceId)throw new Error("VECTOR_SPACE_UNVERIFIED: cannot initialize HNSW without runtime provenance");if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:o}=await import("./hnsw-legacy-bridge-5DRL5FLX.js"),{HnswAdapter:c}=await import("./hnsw-adapter-42KB37KP.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-T2PGO77J.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=et()),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=X(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 R(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 R(e.id,"FAILED",a))}if(e.embedding){let a=await this.ensureHNSW();if(!a&&c)return v(new R(e.id,"COMMITTED_PENDING_INDEX",new Error("HNSW unavailable after authoritative pattern commit")));if(!a&&r)return d(),v(new R(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 R(e.id,c?"COMMITTED_PENDING_INDEX":"FAILED",l))}}if($())try{let l=at().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=Gt();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(ie()&&e.embedding)try{ot(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:F(),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)&&ie())try{let f=ot(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 ce(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=ce.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=Ue(s,t.filter));let l=a.slice(0,i),h=performance.now()-r;return this.recordSearchLatency(h),P(l)}catch(o){return v(De(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=at(),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=W({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=se(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=se(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,xe=0),this.initialized=!1}indexHyperbolic(e,t,r){if(k())try{this.hyperbolicIndex||(this.hyperbolicIndex=it({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 an(n,e){try{if(D().useRVFPatternStore&&Me()){let r=process.env.AQE_PROJECT_ROOT??Oe(),i=st(r,".agentic-qe"),s=st(i,"patterns.rvf");if(Xt(i)){let o={...Y,...e},c=!1;try{let d=ke(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 Ne(a)}catch(m){return h=m,null}},u=f();if(!u&&G(h)&&(!He(a)||(u=f(),!u&&G(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 ae(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(G(h))throw h;if(Le(a,m instanceof Error?m.message:String(m),h))return ae(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 Ie(n,e)}export{R as a,an 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,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.5");process.exit(0)}
2
- import{a as v,b as I,c as D}from"./chunk-J5UNP6W3.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-HFG3BXWU.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};