agentic-qe 3.14.0 → 3.14.1

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 (413) hide show
  1. package/.claude/helpers/brain-checkpoint.cjs +2 -1
  2. package/.claude/helpers/validate-v3-config.sh +6 -5
  3. package/.claude/hooks/aqe-hook.cjs +14 -14
  4. package/.claude/skills/qe-browser/evals/qe-browser.yaml +30 -41
  5. package/.claude/skills/qe-browser/fixtures/serve-skills.js +37 -0
  6. package/.claude/skills/qe-browser/scripts/lib/vibium.js +1 -1
  7. package/.claude/skills/qe-browser/scripts/smoke-test.sh +56 -25
  8. package/.claude/skills/qe-browser/scripts/visual-diff.js +24 -15
  9. package/.claude/skills/skills-manifest.json +1 -1
  10. package/CHANGELOG.md +77 -0
  11. package/assets/skills/qe-browser/evals/qe-browser.yaml +30 -41
  12. package/assets/skills/qe-browser/fixtures/serve-skills.js +37 -0
  13. package/assets/skills/qe-browser/scripts/lib/vibium.js +1 -1
  14. package/assets/skills/qe-browser/scripts/smoke-test.sh +56 -25
  15. package/assets/skills/qe-browser/scripts/visual-diff.js +24 -15
  16. package/assets/skills/skills-manifest.json +1 -1
  17. package/dist/cli/bundle.js +7 -7
  18. package/dist/cli/chunks/adapter-I2N7PEKG.js +2 -0
  19. package/dist/cli/chunks/{agent-booster-wasm-JZO6VUW4.js → agent-booster-wasm-OY5Y2CUM.js} +2 -2
  20. package/dist/cli/chunks/{agent-handler-534KFGEJ.js → agent-handler-TUOH55LD.js} +2 -2
  21. package/dist/cli/chunks/{agent-memory-branch-B7KWLWY4.js → agent-memory-branch-XM3IYKT3.js} +2 -2
  22. package/dist/cli/chunks/aqe-learning-engine-U4ALUH6A.js +2 -0
  23. package/dist/cli/chunks/{arena-OW5MELJX.js → arena-DOCLIEBL.js} +4 -4
  24. package/dist/cli/chunks/{arena-7CCD3S3I.js → arena-UMFJZKG7.js} +2 -2
  25. package/dist/cli/chunks/{audit-BHVKN4E2.js → audit-KZLU5VLW.js} +3 -3
  26. package/dist/cli/chunks/base-RCYIBNHM.js +2 -0
  27. package/dist/cli/chunks/{better-sqlite3-P5FA6WFK.js → better-sqlite3-MIEZBNUI.js} +2 -2
  28. package/dist/cli/chunks/{brain-handler-WNW5LOV7.js → brain-handler-6PZN46B7.js} +3 -3
  29. package/dist/cli/chunks/{branch-enumerator-TVZ2ODKH.js → branch-enumerator-XCETHA4F.js} +2 -2
  30. package/dist/cli/chunks/{browser-TCEB2W2F.js → browser-UEXISDCJ.js} +2 -2
  31. package/dist/cli/chunks/browser-workflow-L6TDB5O5.js +2 -0
  32. package/dist/cli/chunks/{chunk-IQ3JFHZN.js → chunk-3AYNHOWS.js} +1 -1
  33. package/dist/cli/chunks/{chunk-3QT6S3A3.js → chunk-3BRR2FLH.js} +3 -3
  34. package/dist/cli/chunks/{chunk-43GPSYAL.js → chunk-3FFMUB3B.js} +2 -2
  35. package/dist/cli/chunks/{chunk-E4NU4BJA.js → chunk-3JMSXOU4.js} +2 -2
  36. package/dist/cli/chunks/{chunk-IQLRA4FV.js → chunk-3TMUCJNJ.js} +1 -1
  37. package/dist/cli/chunks/{chunk-AR6SATU3.js → chunk-3WSH4HD2.js} +2 -2
  38. package/dist/cli/chunks/{chunk-7OUMJCJT.js → chunk-3XRXUVUI.js} +1 -1
  39. package/dist/cli/chunks/{chunk-ZQSXG7FA.js → chunk-45S5553E.js} +2 -2
  40. package/dist/cli/chunks/{chunk-LKR7T3OZ.js → chunk-4MT62HKK.js} +1 -1
  41. package/dist/cli/chunks/{chunk-SUSMHSXT.js → chunk-4ZLFUO4I.js} +2 -2
  42. package/dist/cli/chunks/{chunk-QMMDN4WX.js → chunk-5F5V4QYU.js} +3 -3
  43. package/dist/cli/chunks/{chunk-I3VHXA2W.js → chunk-5KP62DC3.js} +2 -2
  44. package/dist/cli/chunks/{chunk-OONCRNFA.js → chunk-5NSSJUWW.js} +2 -2
  45. package/dist/cli/chunks/{chunk-T3BZAFLP.js → chunk-5T6PAUZD.js} +1 -1
  46. package/dist/cli/chunks/{chunk-VOSISOFD.js → chunk-5TYGSQOL.js} +1 -1
  47. package/dist/cli/chunks/{chunk-L4C42WYI.js → chunk-5Y2QFSVZ.js} +2 -2
  48. package/dist/cli/chunks/{chunk-RKUYVVGJ.js → chunk-6B77GPWL.js} +2 -2
  49. package/dist/cli/chunks/{chunk-LZHTCUCO.js → chunk-6DDMHZWH.js} +2 -2
  50. package/dist/cli/chunks/{chunk-SROZXIMT.js → chunk-6HMNN2Y2.js} +54 -54
  51. package/dist/cli/chunks/{chunk-7RAB2BZY.js → chunk-6YIMLUH6.js} +2 -2
  52. package/dist/cli/chunks/{chunk-NKWO2X3T.js → chunk-6Z6Y3YBX.js} +1 -1
  53. package/dist/cli/chunks/{chunk-4MK2G6TK.js → chunk-75SC3GEX.js} +2 -2
  54. package/dist/cli/chunks/{chunk-ZBOWR4XT.js → chunk-7AF55H2D.js} +2 -2
  55. package/dist/cli/chunks/{chunk-WKNWRDA5.js → chunk-7AYTM426.js} +1 -1
  56. package/dist/cli/chunks/{chunk-JAK5UUWH.js → chunk-7GF6IRSU.js} +2 -2
  57. package/dist/cli/chunks/{chunk-4ZVGSVHV.js → chunk-7XL2D56F.js} +4 -4
  58. package/dist/cli/chunks/{chunk-2NO4H35K.js → chunk-A6RB34Y6.js} +1 -1
  59. package/dist/cli/chunks/{chunk-ZI3UO7QR.js → chunk-AESYVAPH.js} +2 -2
  60. package/dist/cli/chunks/{chunk-GKNDP5VK.js → chunk-AZUC7E5S.js} +2 -2
  61. package/dist/cli/chunks/{chunk-B3H4K7CY.js → chunk-B6Y6AF4M.js} +2 -2
  62. package/dist/cli/chunks/{chunk-ECTPFCON.js → chunk-C3XNFIOM.js} +2 -2
  63. package/dist/cli/chunks/{chunk-QZPFUFZG.js → chunk-CBWF42ET.js} +2 -2
  64. package/dist/cli/chunks/{chunk-JMKMDSXG.js → chunk-CCZZZBAO.js} +2 -2
  65. package/dist/cli/chunks/{chunk-6IZQSLYZ.js → chunk-CGDW47WP.js} +2 -2
  66. package/dist/cli/chunks/chunk-CGZ7LTUK.js +2 -0
  67. package/dist/cli/chunks/{chunk-FRL3X2QA.js → chunk-D6RCRTTR.js} +2 -2
  68. package/dist/cli/chunks/{chunk-DOWCOZDO.js → chunk-DFXQLHQM.js} +2 -2
  69. package/dist/cli/chunks/{chunk-QQCENKCX.js → chunk-DKSLJZVA.js} +1 -1
  70. package/dist/cli/chunks/{chunk-YKWMKRYB.js → chunk-DKUKGBJE.js} +1 -1
  71. package/dist/cli/chunks/{chunk-ENGKLFLY.js → chunk-DKXSJDII.js} +2 -2
  72. package/dist/cli/chunks/chunk-EEJP3WTQ.js +4 -0
  73. package/dist/cli/chunks/{chunk-PEW6FZ47.js → chunk-EHW62JL2.js} +1 -1
  74. package/dist/cli/chunks/{chunk-5LEAGKX5.js → chunk-EPBWFTHH.js} +2 -2
  75. package/dist/cli/chunks/{chunk-ZAAYOENS.js → chunk-ERTGGFXZ.js} +2 -2
  76. package/dist/cli/chunks/{chunk-TKYEP7OR.js → chunk-F7TRO2OM.js} +1 -1
  77. package/dist/cli/chunks/{chunk-HJIAVR6P.js → chunk-FFRKTZYP.js} +2 -2
  78. package/dist/cli/chunks/{chunk-S5YVLPXU.js → chunk-FH7SCX2I.js} +2 -2
  79. package/dist/cli/chunks/{chunk-N2YAUDAV.js → chunk-FHBGALBG.js} +2 -2
  80. package/dist/cli/chunks/{chunk-WWWX76QB.js → chunk-FOAFRC2W.js} +2 -2
  81. package/dist/cli/chunks/{chunk-KTSCZ7AW.js → chunk-FPBQ7BXU.js} +2 -2
  82. package/dist/cli/chunks/{chunk-JTWJR2KY.js → chunk-FRRRDCXY.js} +2 -2
  83. package/dist/cli/chunks/{chunk-2HYVOX6N.js → chunk-FZ47ZCRL.js} +1 -1
  84. package/dist/cli/chunks/{chunk-H3YDDKBW.js → chunk-GH3NJOTC.js} +3 -3
  85. package/dist/cli/chunks/{chunk-5VDVYTO5.js → chunk-GO66DCIZ.js} +2 -2
  86. package/dist/cli/chunks/{chunk-H6NFDOMK.js → chunk-GRVR3Y6I.js} +1 -1
  87. package/dist/cli/chunks/chunk-GYTWUOKU.js +65 -0
  88. package/dist/cli/chunks/{chunk-O2MZZL54.js → chunk-H2DX36SC.js} +2 -2
  89. package/dist/cli/chunks/{chunk-NOPVFBQM.js → chunk-H5LSXVWY.js} +2 -2
  90. package/dist/cli/chunks/{chunk-DDPJUAXQ.js → chunk-HBAQVJDP.js} +2 -2
  91. package/dist/cli/chunks/{chunk-R6WJF4D5.js → chunk-HCCILQGN.js} +2 -2
  92. package/dist/cli/chunks/{chunk-CIZ6LSNV.js → chunk-HJD52N32.js} +2 -2
  93. package/dist/cli/chunks/{chunk-4FEJEVG7.js → chunk-HKU5PPS7.js} +1 -1
  94. package/dist/cli/chunks/{chunk-M3HUZD2I.js → chunk-HPQU6XZH.js} +1 -1
  95. package/dist/cli/chunks/{chunk-IL6QRXRP.js → chunk-HRUQWABO.js} +10 -10
  96. package/dist/cli/chunks/{chunk-BZ4QVFP2.js → chunk-IGRTQ6VT.js} +2 -2
  97. package/dist/cli/chunks/{chunk-HQ7243G3.js → chunk-IIBXGHZT.js} +2 -2
  98. package/dist/cli/chunks/{chunk-LCSVROU7.js → chunk-IYB3GRXF.js} +10 -10
  99. package/dist/cli/chunks/{chunk-CIUOC5F3.js → chunk-IYIMLLUV.js} +1 -1
  100. package/dist/cli/chunks/{chunk-6AOZU3UN.js → chunk-J2VF7ZO7.js} +2 -2
  101. package/dist/cli/chunks/{chunk-2D7UBX5S.js → chunk-J33LKXVH.js} +1 -1
  102. package/dist/cli/chunks/{chunk-JY4VZ6BN.js → chunk-J7VAD4RG.js} +2 -2
  103. package/dist/cli/chunks/{chunk-A2WZEMWT.js → chunk-JJ4GUO4K.js} +1 -1
  104. package/dist/cli/chunks/{chunk-RGVD6ZUX.js → chunk-JMULRLD4.js} +1 -1
  105. package/dist/cli/chunks/{chunk-JRKEBESE.js → chunk-JNSTKE3K.js} +2 -2
  106. package/dist/cli/chunks/{chunk-3RYTAYR6.js → chunk-JZUWPDVS.js} +1 -1
  107. package/dist/cli/chunks/{chunk-5XGVSQS2.js → chunk-KHUO4NCW.js} +2 -2
  108. package/dist/cli/chunks/{chunk-AFGT26NR.js → chunk-KXMW7XTJ.js} +2 -2
  109. package/dist/cli/chunks/{chunk-6DPAMYLU.js → chunk-KXTN3FR4.js} +2 -2
  110. package/dist/cli/chunks/{chunk-VXU53F7Z.js → chunk-L4WATX6B.js} +2 -2
  111. package/dist/cli/chunks/{chunk-SSV6KSFT.js → chunk-L66BWYQH.js} +1 -1
  112. package/dist/cli/chunks/{chunk-FOHYBR3O.js → chunk-LJ63HPPN.js} +1 -1
  113. package/dist/cli/chunks/{chunk-6IJMD2ZL.js → chunk-LMPK63PO.js} +3 -3
  114. package/dist/cli/chunks/{chunk-IL4AEB3J.js → chunk-LQDFWLKK.js} +2 -2
  115. package/dist/cli/chunks/{chunk-IE5LC7MB.js → chunk-LSXQPMPI.js} +2 -2
  116. package/dist/cli/chunks/{chunk-UI6WSPEK.js → chunk-MDLLEUFN.js} +3 -3
  117. package/dist/cli/chunks/{chunk-A7SKM6JL.js → chunk-MFAN5W27.js} +1 -1
  118. package/dist/cli/chunks/{chunk-J3XSHJGK.js → chunk-MZ2PJUN6.js} +2 -2
  119. package/dist/cli/chunks/{chunk-VPVZHJSU.js → chunk-N22LMACN.js} +2 -2
  120. package/dist/cli/chunks/{chunk-XITTURP2.js → chunk-NAJCQJSK.js} +2 -2
  121. package/dist/cli/chunks/{chunk-VYENTZ45.js → chunk-ND6JBUVH.js} +2 -2
  122. package/dist/cli/chunks/{chunk-AVLA5PBJ.js → chunk-NEEZ6M4W.js} +2 -2
  123. package/dist/cli/chunks/{chunk-HNKPLVYS.js → chunk-NNJ63W77.js} +1 -1
  124. package/dist/cli/chunks/{chunk-NDPQ2WPU.js → chunk-O7KF3GBV.js} +1 -1
  125. package/dist/cli/chunks/{chunk-YEAC3DC6.js → chunk-OBKMLOHU.js} +2 -2
  126. package/dist/cli/chunks/{chunk-NYARYONH.js → chunk-OBLHI4HA.js} +1 -1
  127. package/dist/cli/chunks/{chunk-5MZF4N4Q.js → chunk-ODNLKYOM.js} +1 -1
  128. package/dist/cli/chunks/{chunk-6W42XWLL.js → chunk-PMREFRPP.js} +2 -2
  129. package/dist/cli/chunks/{chunk-7BOPFN3Y.js → chunk-PMUF7WU6.js} +2 -2
  130. package/dist/cli/chunks/{chunk-52DFCV57.js → chunk-PS5NIMWJ.js} +2 -2
  131. package/dist/cli/chunks/{chunk-ZBKGX72B.js → chunk-PS6Y662P.js} +3 -3
  132. package/dist/cli/chunks/{chunk-YW4RNZWT.js → chunk-PYAH4K2U.js} +2 -2
  133. package/dist/cli/chunks/{chunk-E722WNWC.js → chunk-PZZX57ZA.js} +2 -2
  134. package/dist/cli/chunks/{chunk-YKZV7O65.js → chunk-QAE4BOIV.js} +2 -2
  135. package/dist/cli/chunks/{chunk-FF43SRP6.js → chunk-QIY43XQJ.js} +1 -1
  136. package/dist/cli/chunks/{chunk-HLNQDRHA.js → chunk-QM6EJHP5.js} +1 -1
  137. package/dist/cli/chunks/{chunk-7RVAHJQZ.js → chunk-QMTBWHGR.js} +3 -3
  138. package/dist/cli/chunks/{chunk-3EM2MK3Z.js → chunk-RCHDSUVU.js} +2 -2
  139. package/dist/cli/chunks/{chunk-K6CGQR5R.js → chunk-RUEHSOE6.js} +1 -1
  140. package/dist/cli/chunks/{chunk-ZNSMVQCG.js → chunk-RVCMZUSJ.js} +2 -2
  141. package/dist/cli/chunks/{chunk-OIYUSWHX.js → chunk-RXHI6CKK.js} +1 -1
  142. package/dist/cli/chunks/{chunk-KDIZQHG5.js → chunk-RXPHQ4ZE.js} +2 -2
  143. package/dist/cli/chunks/{chunk-XXFKN7LB.js → chunk-RYHCYTFE.js} +1 -1
  144. package/dist/cli/chunks/{chunk-WTHAVFIC.js → chunk-S4WIAKPL.js} +1 -1
  145. package/dist/cli/chunks/{chunk-GVEJP5T7.js → chunk-S53ZUAVI.js} +2 -2
  146. package/dist/cli/chunks/{chunk-UUJ5VQJM.js → chunk-SEKOMKNG.js} +1 -1
  147. package/dist/cli/chunks/{chunk-2O4DDPEA.js → chunk-SZRDEPUY.js} +3 -3
  148. package/dist/cli/chunks/{chunk-3GUO4ERR.js → chunk-T7XYQX5G.js} +2 -2
  149. package/dist/cli/chunks/{chunk-U4GZWPKM.js → chunk-TF33GKWA.js} +2 -2
  150. package/dist/cli/chunks/{chunk-6AYO3IR2.js → chunk-TGFJUL6M.js} +2 -2
  151. package/dist/cli/chunks/{chunk-ZCVJCCQQ.js → chunk-TLD727EF.js} +2 -2
  152. package/dist/cli/chunks/{chunk-QSPRQPEL.js → chunk-TQ2JZVZ3.js} +2 -2
  153. package/dist/cli/chunks/{chunk-BQCTO7UB.js → chunk-TT7DF2GX.js} +2 -2
  154. package/dist/cli/chunks/{chunk-DJITEQYS.js → chunk-UCJEAK7D.js} +2 -2
  155. package/dist/cli/chunks/{chunk-4XTHRAUV.js → chunk-UN7EHLRV.js} +1 -1
  156. package/dist/cli/chunks/{chunk-Q73RRTLE.js → chunk-UUE5CBZQ.js} +2 -2
  157. package/dist/cli/chunks/{chunk-JGROLJ33.js → chunk-UWRMPRY5.js} +1 -1
  158. package/dist/cli/chunks/{chunk-EJ6IP7DE.js → chunk-VEWYUEVY.js} +2 -2
  159. package/dist/cli/chunks/{chunk-VESOYP6A.js → chunk-VUXHJPUS.js} +2 -2
  160. package/dist/cli/chunks/{chunk-HQHLHSJO.js → chunk-VVP2ROXD.js} +2 -2
  161. package/dist/cli/chunks/{chunk-H76TV4UU.js → chunk-WFJKLM6Z.js} +3 -3
  162. package/dist/cli/chunks/{chunk-TGOGCA74.js → chunk-X5G3UDWP.js} +2 -2
  163. package/dist/cli/chunks/{chunk-QKQZ4IJF.js → chunk-Y63V33M6.js} +5 -5
  164. package/dist/cli/chunks/{chunk-3JIJBR4V.js → chunk-YXN47QOI.js} +2 -2
  165. package/dist/cli/chunks/{chunk-MO7EITJK.js → chunk-Z5YU2TDS.js} +2 -2
  166. package/dist/cli/chunks/{chunk-TQJE7DNL.js → chunk-ZAHCVRR7.js} +2 -2
  167. package/dist/cli/chunks/{chunk-VRRG66XB.js → chunk-ZC3HC6FO.js} +1 -1
  168. package/dist/cli/chunks/{ci-B432UH6N.js → ci-Q2VX75PS.js} +2 -2
  169. package/dist/cli/chunks/{ci-output-GTHH7WYG.js → ci-output-MD5GTVR2.js} +2 -2
  170. package/dist/cli/chunks/{circuit-breaker-VW75DLME.js → circuit-breaker-JMRLG2XI.js} +2 -2
  171. package/dist/cli/chunks/{claude-flow-setup-RE3IVT7U.js → claude-flow-setup-IMXYALBU.js} +2 -2
  172. package/dist/cli/chunks/client-L4PIXCGV.js +2 -0
  173. package/dist/cli/chunks/{cline-installer-NUBZZ55N.js → cline-installer-HWFASEGE.js} +2 -2
  174. package/dist/cli/chunks/{code-K6JCWKNW.js → code-3V37TCAD.js} +2 -2
  175. package/dist/cli/chunks/{code-index-extractor-I4ILB5JN.js → code-index-extractor-5V54WGFL.js} +2 -2
  176. package/dist/cli/chunks/codex-installer-UCA5AVE6.js +14 -0
  177. package/dist/cli/chunks/{completions-V3KJVJF4.js → completions-2DMRCQU6.js} +2 -2
  178. package/dist/cli/chunks/{complexity-analyzer-HRG7OOY3.js → complexity-analyzer-MMQRXBTD.js} +2 -2
  179. package/dist/cli/chunks/{continuedev-installer-CNTDONWG.js → continuedev-installer-FAARXP3S.js} +2 -2
  180. package/dist/cli/chunks/{copilot-installer-XPWWIWYA.js → copilot-installer-AKQALMB5.js} +2 -2
  181. package/dist/cli/chunks/core-handlers-KROSXP4V.js +2 -0
  182. package/dist/cli/chunks/{cost-tracker-MFNLQ56K.js → cost-tracker-AXWHDND5.js} +2 -2
  183. package/dist/cli/chunks/{coverage-KOIK654V.js → coverage-ZLSKKCG5.js} +3 -3
  184. package/dist/cli/chunks/cross-domain-router-WMTYBOON.js +2 -0
  185. package/dist/cli/chunks/{cursor-installer-S5MKLRQQ.js → cursor-installer-UALCQKVD.js} +2 -2
  186. package/dist/cli/chunks/{daemon-DUS6JYW6.js → daemon-4LNOPJGN.js} +3 -3
  187. package/dist/cli/chunks/{daemon-Z7VPGWHY.js → daemon-K3DFGCXC.js} +4 -4
  188. package/dist/cli/chunks/{dag-attention-scheduler-7CQ3ARNI.js → dag-attention-scheduler-LCQ7MYKC.js} +2 -2
  189. package/dist/cli/chunks/{detect-WORBCAYF.js → detect-P7PEN3MZ.js} +2 -2
  190. package/dist/cli/chunks/{dist-node-KRNI6OYW.js → dist-node-I72BJC2D.js} +2 -2
  191. package/dist/cli/chunks/{domain-handler-KRUR2VQG.js → domain-handler-LROF6KWN.js} +2 -2
  192. package/dist/cli/chunks/{domain-transfer-VEOVLV54.js → domain-transfer-M2ZSSTPV.js} +2 -2
  193. package/dist/cli/chunks/dream-AV63YQ2Y.js +2 -0
  194. package/dist/cli/chunks/{embed-and-insert-pattern-QU3NQVA5.js → embed-and-insert-pattern-MTBPUGO4.js} +2 -2
  195. package/dist/cli/chunks/{eval-AYQ7BSUP.js → eval-O24ALB3W.js} +2 -2
  196. package/dist/cli/chunks/{experience-capture-middleware-AWQBL6LT.js → experience-capture-middleware-7JXEOGRE.js} +3 -3
  197. package/dist/cli/chunks/{fast-paths-V5EL4BYJ.js → fast-paths-4CFYJV4U.js} +2 -2
  198. package/dist/cli/chunks/{feature-flags-P34BPRWU.js → feature-flags-CHPUA7IM.js} +2 -2
  199. package/dist/cli/chunks/{feature-flags-BXX7BP22.js → feature-flags-E6PIM6ZB.js} +2 -2
  200. package/dist/cli/chunks/{file-discovery-MS6BKQ2U.js → file-discovery-2ANIAUCP.js} +2 -2
  201. package/dist/cli/chunks/{fleet-7WVVPA4W.js → fleet-2MQ3OGCP.js} +3 -3
  202. package/dist/cli/chunks/{gnn-wrapper-7WQ3LEPG.js → gnn-wrapper-P7JW3622.js} +2 -2
  203. package/dist/cli/chunks/{heartbeat-handler-P7QD3BZH.js → heartbeat-handler-WWWZSA7V.js} +4 -4
  204. package/dist/cli/chunks/heartbeat-scheduler-5IZUGMC2.js +2 -0
  205. package/dist/cli/chunks/hnsw-adapter-NV2NNBJL.js +2 -0
  206. package/dist/cli/chunks/hnsw-index-GRJ3KA2O.js +2 -0
  207. package/dist/cli/chunks/{hnsw-legacy-bridge-Y3GAR3UP.js → hnsw-legacy-bridge-W634ZOTV.js} +2 -2
  208. package/dist/cli/chunks/{hnswlib-node-5QUXZQWQ.js → hnswlib-node-SLZDLMKM.js} +2 -2
  209. package/dist/cli/chunks/{hooks-2D64KPRY.js → hooks-3BFAZGG7.js} +10 -10
  210. package/dist/cli/chunks/{hypergraph-engine-5INXEZDP.js → hypergraph-engine-XJSGXP2J.js} +2 -2
  211. package/dist/cli/chunks/{hypergraph-handler-YJJJ3ESZ.js → hypergraph-handler-RVUWZMOX.js} +3 -3
  212. package/dist/cli/chunks/impact-analyzer-YM4QUWVH.js +2 -0
  213. package/dist/cli/chunks/{init-handler-QSFYJN5Q.js → init-handler-FYOZNNNO.js} +9 -8
  214. package/dist/cli/chunks/init-wizard-YESXGIK6.js +2 -0
  215. package/dist/cli/chunks/kernel-VH5SKESU.js +2 -0
  216. package/dist/cli/chunks/{kilocode-installer-3N3QGTJU.js → kilocode-installer-MAAKFVSB.js} +2 -2
  217. package/dist/cli/chunks/{kiro-installer-GIWVTFZQ.js → kiro-installer-GX3TLZC5.js} +2 -2
  218. package/dist/cli/chunks/knowledge-graph-F3NL4WJV.js +2 -0
  219. package/dist/cli/chunks/{learning-SGO2DQ5Q.js → learning-T4QZ6C26.js} +3 -3
  220. package/dist/cli/chunks/{llm-router-HBBULO65.js → llm-router-N2M4WXOC.js} +4 -4
  221. package/dist/cli/chunks/llm-router-service-HQYCJMPK.js +2 -0
  222. package/dist/cli/chunks/{load-B5OFYB4H.js → load-6RU3G4P2.js} +2 -2
  223. package/dist/cli/chunks/load-test-GWRGKWMN.js +2 -0
  224. package/dist/cli/chunks/{mcp-FG3LNQR4.js → mcp-EFBO7BAU.js} +2 -2
  225. package/dist/cli/chunks/{memory-SPS7ZWLC.js → memory-AXU2M3DN.js} +5 -5
  226. package/dist/cli/chunks/memory-backend-7A2PFKPV.js +2 -0
  227. package/dist/cli/chunks/{memory-handlers-P7FTPWP3.js → memory-handlers-65CXN76C.js} +2 -2
  228. package/dist/cli/chunks/{multi-model-executor-PUB7E6KH.js → multi-model-executor-W7AFGVNH.js} +2 -2
  229. package/dist/cli/chunks/{opencode-installer-TGCSGVG2.js → opencode-installer-KJE2RLCH.js} +2 -2
  230. package/dist/cli/chunks/{orchestrator-S5FTJFGB.js → orchestrator-CL6MLGVU.js} +22 -21
  231. package/dist/cli/chunks/pattern-null-store-K2WPRYCP.js +2 -0
  232. package/dist/cli/chunks/{pattern-usage-recorder-LCXXGRAB.js → pattern-usage-recorder-7SNSJ7K2.js} +2 -2
  233. package/dist/cli/chunks/{pipeline-ENOSRHKW.js → pipeline-3UU6ON3F.js} +2 -2
  234. package/dist/cli/chunks/platform-SNMPIDIT.js +2 -0
  235. package/dist/cli/chunks/{plugin-JZ5ODJSU.js → plugin-65IIUUCU.js} +2 -2
  236. package/dist/cli/chunks/{prime-radiant-advanced-wasm-DPJUPNCG.js → prime-radiant-advanced-wasm-WWWJRLRP.js} +2 -2
  237. package/dist/cli/chunks/protocol-executor-TJDLEHND.js +2 -0
  238. package/dist/cli/chunks/{protocol-handler-IP4NLVY3.js → protocol-handler-SEBHCLLJ.js} +2 -2
  239. package/dist/cli/chunks/{prove-P6FM4RU7.js → prove-N4X7CCJ4.js} +2 -2
  240. package/dist/cli/chunks/qe-reasoning-bank-CGRMFPDM.js +2 -0
  241. package/dist/cli/chunks/{quality-UHP4XO26.js → quality-LBCJWXMU.js} +2 -2
  242. package/dist/cli/chunks/quality-gate-KZIQI7QT.js +7 -0
  243. package/dist/cli/chunks/queen-coordinator-FKP6QZAQ.js +2 -0
  244. package/dist/cli/chunks/{real-embeddings-6SO5MFRQ.js → real-embeddings-XCZFHFME.js} +2 -2
  245. package/dist/cli/chunks/{roocode-installer-WTWUOFCH.js → roocode-installer-P3O6B7PT.js} +2 -2
  246. package/dist/cli/chunks/router-KZ5BISAM.js +2 -0
  247. package/dist/cli/chunks/routing-feedback-O4Y5TTR6.js +2 -0
  248. package/dist/cli/chunks/{routing-handler-IK7HYERQ.js → routing-handler-OXZ4DOV4.js} +2 -2
  249. package/dist/cli/chunks/{ruvector-commands-THLB4NIM.js → ruvector-commands-PSY5IDSL.js} +2 -2
  250. package/dist/cli/chunks/rvf-dual-writer-NG3UF3D5.js +2 -0
  251. package/dist/cli/chunks/rvf-migration-adapter-PUHVTKQY.js +2 -0
  252. package/dist/cli/chunks/{rvf-migration-coordinator-BUKCSHBD.js → rvf-migration-coordinator-4SUT7GTJ.js} +2 -2
  253. package/dist/cli/chunks/rvf-native-adapter-ODXFKZ6G.js +2 -0
  254. package/dist/cli/chunks/{rvf-store-integrity-ECTADZIN.js → rvf-store-integrity-TCKC22FH.js} +2 -2
  255. package/dist/cli/chunks/safe-db-BUQDNH2R.js +2 -0
  256. package/dist/cli/chunks/schedule-ZXNDZNNB.js +2 -0
  257. package/dist/cli/chunks/scheduler-YUQQWWW3.js +2 -0
  258. package/dist/cli/chunks/{security-HN4UXFXX.js → security-RQGUQGSI.js} +3 -3
  259. package/dist/cli/chunks/{shared-rvf-adapter-XJCPX5SN.js → shared-rvf-adapter-ZJFN52C2.js} +2 -2
  260. package/dist/cli/chunks/{shared-rvf-dual-writer-23X5PNY5.js → shared-rvf-dual-writer-V2R37HWV.js} +2 -2
  261. package/dist/cli/chunks/sqlite-persistence-HVSX46C7.js +2 -0
  262. package/dist/cli/chunks/{status-handler-ZXANTHKT.js → status-handler-XEKWNVDR.js} +2 -2
  263. package/dist/cli/chunks/{structural-health-LR6WI3AH.js → structural-health-QMIW6WUN.js} +2 -2
  264. package/dist/cli/chunks/{sync-4OEI3BC2.js → sync-GDYJ2ULT.js} +2 -2
  265. package/dist/cli/chunks/{sync-I5IUJF33.js → sync-H5SXWXPP.js} +2 -2
  266. package/dist/cli/chunks/{task-handler-R3ATJKU5.js → task-handler-EPLKCQHY.js} +2 -2
  267. package/dist/cli/chunks/{task-handlers-4X357AEW.js → task-handlers-22NTLWTC.js} +3 -3
  268. package/dist/cli/chunks/{test-PR2B5H2F.js → test-WHJFRZ3F.js} +4 -4
  269. package/dist/cli/chunks/{test-scheduling-ZNOSQVLD.js → test-scheduling-KZVFZOQN.js} +3 -3
  270. package/dist/cli/chunks/{token-bootstrap-LYXOI72S.js → token-bootstrap-BW5WA6PY.js} +2 -2
  271. package/dist/cli/chunks/{token-usage-R6EQZBX2.js → token-usage-4A4O57R6.js} +2 -2
  272. package/dist/cli/chunks/{transformers-COQWK27J.js → transformers-FYTBRV46.js} +2 -2
  273. package/dist/cli/chunks/{tree-sitter-wasm-parser-LLIW2X3M.js → tree-sitter-wasm-parser-TZIJPLF3.js} +2 -2
  274. package/dist/cli/chunks/{types-MEYTZITK.js → types-B2L6LKFA.js} +2 -2
  275. package/dist/cli/chunks/unified-memory-AHN4RVBP.js +2 -0
  276. package/dist/cli/chunks/unified-memory-hnsw-XB7JPF74.js +2 -0
  277. package/dist/cli/chunks/unified-persistence-53KWNFQJ.js +2 -0
  278. package/dist/cli/chunks/{upgrade-DVIJ456A.js → upgrade-O6U7EA7V.js} +2 -2
  279. package/dist/cli/chunks/{validate-UYTSMJ5X.js → validate-FHNZ5XL3.js} +2 -2
  280. package/dist/cli/chunks/{validate-swarm-P32WCJR6.js → validate-swarm-YOLLUEHE.js} +2 -2
  281. package/dist/cli/chunks/{vibium-JGVOLM6X.js → vibium-UXRPEIXB.js} +2 -2
  282. package/dist/cli/chunks/visual-security-CRPYS7L7.js +2 -0
  283. package/dist/cli/chunks/{web-tree-sitter-5ZGNCTPN.js → web-tree-sitter-JJ5UIYFD.js} +2 -2
  284. package/dist/cli/chunks/{windsurf-installer-IILSSQAE.js → windsurf-installer-I4QMQPIL.js} +2 -2
  285. package/dist/cli/chunks/witness-chain-5WCR2CAS.js +2 -0
  286. package/dist/cli/chunks/{witness-chain-JZMXCG3B.js → witness-chain-BIJ7WDGS.js} +2 -2
  287. package/dist/cli/chunks/{witness-key-manager-UUTLNUIH.js → witness-key-manager-3SMMLJLP.js} +2 -2
  288. package/dist/cli/chunks/{workflow-NS7HXVHZ.js → workflow-33PUXXJV.js} +4 -4
  289. package/dist/cli/chunks/workflow-orchestrator-RZWCLTT5.js +2 -0
  290. package/dist/cli/chunks/{wrappers-XKEDSV5W.js → wrappers-ASAU36VK.js} +2 -2
  291. package/dist/cli/commands/platform.d.ts +1 -0
  292. package/dist/cli/commands/platform.js +28 -6
  293. package/dist/cli/commands/quality-gate.js +25 -3
  294. package/dist/cli/handlers/init-handler.d.ts +5 -0
  295. package/dist/cli/handlers/init-handler.js +6 -0
  296. package/dist/cli/index.js +4 -1
  297. package/dist/contracts/verdicts.d.ts +625 -0
  298. package/dist/contracts/verdicts.js +202 -14
  299. package/dist/coordination/handlers/coverage-handlers.js +8 -1
  300. package/dist/domains/chaos-resilience/diagnosis/corpus.d.ts +5 -0
  301. package/dist/domains/chaos-resilience/diagnosis/corpus.js +141 -0
  302. package/dist/domains/chaos-resilience/diagnosis/detectors.d.ts +11 -0
  303. package/dist/domains/chaos-resilience/diagnosis/detectors.js +109 -0
  304. package/dist/domains/chaos-resilience/diagnosis/index.d.ts +5 -0
  305. package/dist/domains/chaos-resilience/diagnosis/index.js +5 -0
  306. package/dist/domains/chaos-resilience/diagnosis/scorer.d.ts +8 -0
  307. package/dist/domains/chaos-resilience/diagnosis/scorer.js +128 -0
  308. package/dist/domains/chaos-resilience/diagnosis/types.d.ts +171 -0
  309. package/dist/domains/chaos-resilience/diagnosis/types.js +3 -0
  310. package/dist/domains/chaos-resilience/index.d.ts +1 -0
  311. package/dist/domains/chaos-resilience/index.js +1 -0
  312. package/dist/domains/index.d.ts +1 -0
  313. package/dist/domains/index.js +1 -0
  314. package/dist/early-exit/early-exit-controller.d.ts +4 -2
  315. package/dist/early-exit/early-exit-controller.js +95 -7
  316. package/dist/early-exit/index.d.ts +1 -1
  317. package/dist/early-exit/speculative-executor.js +3 -0
  318. package/dist/early-exit/types.d.ts +51 -0
  319. package/dist/early-exit/types.js +3 -0
  320. package/dist/index.d.ts +4 -2
  321. package/dist/index.js +2 -1
  322. package/dist/init/browser-engine-installer.d.ts +11 -0
  323. package/dist/init/browser-engine-installer.js +35 -5
  324. package/dist/init/codex-installer.d.ts +11 -1
  325. package/dist/init/codex-installer.js +90 -24
  326. package/dist/init/init-wizard-hooks.js +11 -11
  327. package/dist/init/orchestrator.js +2 -0
  328. package/dist/init/phases/07-hooks.d.ts +3 -3
  329. package/dist/init/phases/07-hooks.js +19 -18
  330. package/dist/init/phases/09-assets.d.ts +4 -0
  331. package/dist/init/phases/09-assets.js +13 -10
  332. package/dist/init/phases/phase-interface.d.ts +2 -0
  333. package/dist/init/types.d.ts +4 -0
  334. package/dist/learning/index.d.ts +3 -0
  335. package/dist/learning/index.js +2 -0
  336. package/dist/learning/pattern-mutation-error.d.ts +9 -0
  337. package/dist/learning/pattern-mutation-error.js +14 -0
  338. package/dist/learning/pattern-store.js +24 -2
  339. package/dist/learning/qe-reasoning-bank.js +24 -5
  340. package/dist/learning/rvf-pattern-store.js +23 -5
  341. package/dist/learning/structural-retrieval/corpus.d.ts +5 -0
  342. package/dist/learning/structural-retrieval/corpus.js +97 -0
  343. package/dist/learning/structural-retrieval/evaluate.d.ts +7 -0
  344. package/dist/learning/structural-retrieval/evaluate.js +124 -0
  345. package/dist/learning/structural-retrieval/index.d.ts +6 -0
  346. package/dist/learning/structural-retrieval/index.js +4 -0
  347. package/dist/learning/structural-retrieval/receipt.d.ts +14 -0
  348. package/dist/learning/structural-retrieval/receipt.js +36 -0
  349. package/dist/learning/structural-retrieval/types.d.ts +83 -0
  350. package/dist/learning/structural-retrieval/types.js +2 -0
  351. package/dist/mcp/bundle.js +423 -423
  352. package/dist/mcp/services/session-resume.d.ts +15 -19
  353. package/dist/mcp/services/session-resume.js +204 -194
  354. package/dist/mcp/tools/quality-assessment/gate.d.ts +8 -5
  355. package/dist/mcp/tools/quality-assessment/gate.js +9 -4
  356. package/dist/skills/qe-court/cli.js +0 -0
  357. package/dist/validation/quality-gate-runner.d.ts +27 -4
  358. package/dist/validation/quality-gate-runner.js +33 -4
  359. package/dist/validation/verification-reach.d.ts +90 -0
  360. package/dist/validation/verification-reach.js +187 -0
  361. package/dist/verification/adversarial-verify/index.d.ts +1 -1
  362. package/dist/verification/adversarial-verify/measurement-receipt.d.ts +13 -0
  363. package/dist/verification/adversarial-verify/measurement-receipt.js +136 -0
  364. package/dist/verification/adversarial-verify/synthesize.js +7 -10
  365. package/dist/verification/adversarial-verify/types.d.ts +35 -0
  366. package/dist/verification/adversarial-verify/verify.js +6 -1
  367. package/package.json +7 -4
  368. package/schemas/coverage-gap.schema.json +41 -0
  369. package/schemas/finding-verdict.schema.json +470 -0
  370. package/schemas/risk-decision.schema.json +41 -0
  371. package/dist/cli/chunks/adapter-3VBXL7DO.js +0 -2
  372. package/dist/cli/chunks/aqe-learning-engine-NXRNKJNA.js +0 -2
  373. package/dist/cli/chunks/base-F6GMOKU2.js +0 -2
  374. package/dist/cli/chunks/browser-workflow-QRDC46LR.js +0 -2
  375. package/dist/cli/chunks/chunk-R2B6EE45.js +0 -2
  376. package/dist/cli/chunks/chunk-TRDEULS7.js +0 -4
  377. package/dist/cli/chunks/chunk-WJXHE52V.js +0 -65
  378. package/dist/cli/chunks/client-HNBZUEVV.js +0 -2
  379. package/dist/cli/chunks/codex-installer-AKQ5BCHU.js +0 -15
  380. package/dist/cli/chunks/core-handlers-TB7NLYXL.js +0 -2
  381. package/dist/cli/chunks/cross-domain-router-MDSI553U.js +0 -2
  382. package/dist/cli/chunks/dream-X7ISHFEE.js +0 -2
  383. package/dist/cli/chunks/heartbeat-scheduler-2C5XGFQT.js +0 -2
  384. package/dist/cli/chunks/hnsw-adapter-KCVMXLUL.js +0 -2
  385. package/dist/cli/chunks/hnsw-index-OGWZS6MP.js +0 -2
  386. package/dist/cli/chunks/impact-analyzer-IBJ43GQL.js +0 -2
  387. package/dist/cli/chunks/init-wizard-6XMFD5LP.js +0 -2
  388. package/dist/cli/chunks/kernel-UDUMUPB3.js +0 -2
  389. package/dist/cli/chunks/knowledge-graph-JRYTUG3W.js +0 -2
  390. package/dist/cli/chunks/llm-router-service-KF5ZALUQ.js +0 -2
  391. package/dist/cli/chunks/load-test-LHMBCNCH.js +0 -2
  392. package/dist/cli/chunks/memory-backend-WZHKHBZK.js +0 -2
  393. package/dist/cli/chunks/pattern-null-store-UZSHCRL2.js +0 -2
  394. package/dist/cli/chunks/platform-WCRBO3Z7.js +0 -2
  395. package/dist/cli/chunks/protocol-executor-42NLVDTC.js +0 -2
  396. package/dist/cli/chunks/qe-reasoning-bank-W74RSMMU.js +0 -2
  397. package/dist/cli/chunks/quality-gate-63DDBSGM.js +0 -7
  398. package/dist/cli/chunks/queen-coordinator-XELKSRMS.js +0 -2
  399. package/dist/cli/chunks/router-GTW2EQZV.js +0 -2
  400. package/dist/cli/chunks/routing-feedback-NVOBWEMK.js +0 -2
  401. package/dist/cli/chunks/rvf-dual-writer-5OPVMXNL.js +0 -2
  402. package/dist/cli/chunks/rvf-migration-adapter-5S4YFTX4.js +0 -2
  403. package/dist/cli/chunks/rvf-native-adapter-LYSJHEVX.js +0 -2
  404. package/dist/cli/chunks/safe-db-AEB3JMLD.js +0 -2
  405. package/dist/cli/chunks/schedule-4QNPCQNT.js +0 -2
  406. package/dist/cli/chunks/scheduler-S3DFHX6A.js +0 -2
  407. package/dist/cli/chunks/sqlite-persistence-L2KISU2H.js +0 -2
  408. package/dist/cli/chunks/unified-memory-5KQMA7FV.js +0 -2
  409. package/dist/cli/chunks/unified-memory-hnsw-PQRPTYOD.js +0 -2
  410. package/dist/cli/chunks/unified-persistence-YDONVPJB.js +0 -2
  411. package/dist/cli/chunks/visual-security-RJ7RTNGJ.js +0 -2
  412. package/dist/cli/chunks/witness-chain-YXXXNGAM.js +0 -2
  413. package/dist/cli/chunks/workflow-orchestrator-5KUAVSTH.js +0 -2
@@ -0,0 +1,65 @@
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.1");process.exit(0)}
2
+ import{d as j,e as W,f as ne,g as V}from"./chunk-MFAN5W27.js";import{a as se}from"./chunk-L66BWYQH.js";import{b as Me}from"./chunk-CCZZZBAO.js";import{a as ae}from"./chunk-5KP62DC3.js";import{c as Fe,n as T}from"./chunk-PS6Y662P.js";import{b as De,c as at}from"./chunk-D6RCRTTR.js";import{a as ie,b as Oe,d as _e,f as ot}from"./chunk-HBAQVJDP.js";import{c as Ne}from"./chunk-DKSLJZVA.js";import{b as P,c as v}from"./chunk-UWRMPRY5.js";import{a as S,b as xe,c as Ie}from"./chunk-NAJCQJSK.js";import{i as D}from"./chunk-LJ63HPPN.js";import{B as $,D as L,G as re,P as k,S as O,b as F}from"./chunk-DKXSJDII.js";import{d as B,f as st}from"./chunk-EHW62JL2.js";var Y=B(E=>{var gt=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 yt=Object.prototype.hasOwnProperty;function he(n,e){return yt.call(n,e)}E.hasOwnProperty=he;function Je(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var i in n)he(n,i)&&r.push(i);return r}E._objectKeys=Je;function vt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}E._deepClone=vt;function St(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=St;function de(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}E.escapePathComponent=de;function wt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}E.unescapePathComponent=wt;function fe(n,e){var t;for(var r in n)if(he(n,r)){if(n[r]===e)return de(r)+"/";if(typeof n[r]=="object"&&(t=fe(n[r],e),t!=""))return de(r)+"/"+t}return""}E._getPathRecursive=fe;function Pt(n,e){if(n===e)return"/";var t=fe(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}E.getPath=Pt;function ue(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(ue(n[e]))return!0}else if(typeof n=="object"){for(var r=Je(n),i=r.length,s=0;s<i;s++)if(ue(n[r[s]]))return!0}}return!1}E.hasUndefined=ue;function ze(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 bt=(function(n){gt(e,n);function e(t,r,i,s,a){var c=this.constructor,d=n.call(this,ze(t,{name:r,index:i,operation:s,tree:a}))||this;return d.name=r,d.index=i,d.operation=s,d.tree=a,Object.setPrototypeOf(d,c.prototype),d.message=ze(t,{name:r,index:i,operation:s,tree:a}),d}return e})(Error);E.PatchError=bt});var me=B(g=>{Object.defineProperty(g,"__esModule",{value:!0});var R=Y();g.JsonPatchError=R.PatchError;g.deepClone=R._deepClone;var U={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=K(t,this.path);r&&(r=R._deepClone(r));var i=_(t,{op:"remove",path:this.from}).removed;return _(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=K(t,this.from);return _(t,{op:"add",path:this.path,value:R._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:J(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},Et={add:function(n,e,t){return R.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:U.move,copy:U.copy,test:U.test,_get:U._get};function K(n,e){if(e=="")return n;var t={op:"_get",path:e};return _(n,t),t.value}g.getValueByPointer=K;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):Z(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=K(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=J(n,e.value),a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=R._deepClone(n));var c=e.path||"",d=c.split("/"),o=n,l=1,f=d.length,h=void 0,u=void 0,m=void 0;for(typeof t=="function"?m=t:m=Z;;){if(u=d[l],u&&u.indexOf("~")!=-1&&(u=R.unescapePathComponent(u)),i&&(u=="__proto__"||u=="prototype"&&l>0&&d[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&h===void 0&&(o[u]===void 0?h=d.slice(0,l).join("/"):l==f-1&&(h=e.path),h!==void 0&&m(e,0,n,h)),l++,Array.isArray(o)){if(u==="-")u=o.length;else{if(t&&!R.isInteger(u))throw new g.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);R.isInteger(u)&&(u=~~u)}if(l>=f){if(t&&e.op==="add"&&u>o.length)throw new g.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var a=Et[e.op].call(e,o,u,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(l>=f){var a=U[e.op].call(e,o,u,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[u],t&&l<f&&(!o||typeof o!="object"))throw new g.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}g.applyOperation=_;function Be(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=R._deepClone(n));for(var s=new Array(e.length),a=0,c=e.length;a<c;a++)s[a]=_(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}g.applyPatch=Be;function At(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=At;function Z(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new g.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(U[n.op]){if(typeof n.path!="string")throw new g.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new g.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new g.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&R.hasUndefined(n.value))throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new g.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new g.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a={op:"_get",path:n.from,value:void 0},c=je([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new g.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}g.validator=Z;function je(n,e,t){try{if(!Array.isArray(n))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Be(R._deepClone(e),R._deepClone(n),t||!0);else{t=t||Z;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=je;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,a;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(a=c[i],!J(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}g._areEquals=J});var We=B(q=>{Object.defineProperty(q,"__esModule",{value:!0});var b=Y(),Rt=me(),ge=new WeakMap,Tt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Ct=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function xt(n){return ge.get(n)}function It(n,e){return n.observers.get(e)}function Dt(n,e){n.observers.delete(e.callback)}function Ft(n,e){e.unobserve()}q.unobserve=Ft;function Ot(n,e){var t=[],r,i=xt(n);if(!i)i=new Tt(n),ge.set(n,i);else{var s=It(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 a=function(){pe(r)},c=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return r.patches=t,r.object=n,r.unobserve=function(){pe(r),clearTimeout(r.next),Dt(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 Ct(e,r)),r}q.observe=Ot;function pe(n,e){e===void 0&&(e=!1);var t=ge.get(n.object);ye(t.value,n.object,n.patches,"",e),n.patches.length&&Rt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}q.generate=pe;function ye(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=b._objectKeys(e),a=b._objectKeys(n),c=!1,d=!1,o=a.length-1;o>=0;o--){var l=a[o],f=n[l];if(b.hasOwnProperty(e,l)&&!(e[l]===void 0&&f!==void 0&&Array.isArray(e)===!1)){var h=e[l];typeof f=="object"&&f!=null&&typeof h=="object"&&h!=null&&Array.isArray(f)===Array.isArray(h)?ye(f,h,t,r+"/"+b.escapePathComponent(l),i):f!==h&&(c=!0,i&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),t.push({op:"replace",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(h)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),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==a.length))for(var o=0;o<s.length;o++){var l=s[o];!b.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(e[l])})}}}function _t(n,e,t){t===void 0&&(t=!1);var r=[];return ye(n,e,r,"",t),r}q.compare=_t});var Ve=B(N=>{var Nt=me();Object.assign(N,Nt);var Mt=We();Object.assign(N,Mt);var ee=Y();N.JsonPatchError=ee.PatchError;N.deepClone=ee._deepClone;N.escapePathComponent=ee.escapePathComponent;N.unescapePathComponent=ee.unescapePathComponent});var A=class extends Error{patternId;disposition;cause;constructor(e,t,r){super(`${t}: pattern ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="PatternMutationError",this.patternId=e,this.disposition=t,this.cause=r}};at();import{existsSync as jt}from"node:fs";import{join as rt}from"node:path";Ie();var z=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??X,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1,this.embeddingSpaceId=t?.embeddingSpaceId}createAdapter;config;rvfPath;skipCloseOnDispose;embeddingSpaceId;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){if(this.rvfInitError=null,process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension);let e=T()?.spaceId??this.embeddingSpaceId??null;Fe(this.rvfPath,e,this.adapter.status()?.totalVectors??0),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=S(e);try{this.adapter?.close()}catch{}console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-HVSX46C7.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:i}=await import("node:fs"),s=`${this.rvfPath}.idmap.json`;if(!i(s))return;let a=JSON.parse(r(s,"utf-8")),c=new Set((a.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),d=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!d.has(l));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${S(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=V(e);if(!t.valid)return v(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return v(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(!this.sqliteStore)return v(new A(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let r=T()?.spaceId??this.embeddingSpaceId;if(e.embedding&&!r)return v(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));let i=!1;if(this.sqliteStore)try{let s=this.sqliteStore.storePattern(e,e.embedding,r);s&&s!==e.id&&(e.id=s),i=!0}catch(s){return v(new A(e.id,"FAILED",s))}if(e.embedding&&!this.adapter&&this.rvfInitError)return v(new A(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",new Error(`RVF unavailable ${i?"after":"before"} authoritative pattern commit: ${this.rvfInitError}`)));if(e.embedding&&this.adapter)try{let s=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding),a=this.adapter.ingest([{id:e.id,vector:s}]);if(a.accepted!==1||a.rejected!==0)throw new Error(`RVF rejected pattern vector (accepted=${a.accepted}, rejected=${a.rejected})`)}catch(s){return v(new A(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",s))}return P(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:D(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:j({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?P(i):v(s.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),i=t.limit??10,s=[];if(Array.isArray(e)){let c=T()?.spaceId??this.embeddingSpaceId;if(!c||t.embeddingSpaceId!==c)return v(new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId"))}if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),d=this.adapter.search(c,i*2);for(let o of d){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.score);s.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.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,o=Math.sqrt(d.reduce((l,f)=>l+f*f,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let f=this.sqliteStore.getPattern(l.id),h=f?.embedding;if(!h||h.length!==d.length)continue;let u=0,m=0;for(let w=0;w<d.length;w++)u+=d[w]*h[w],m+=h[w]*h[w];if(m=Math.sqrt(m),m===0)continue;let p=u/(o*m),y=this.calculateReuseInfo(f,p);s.push({pattern:f,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(o=>o.pattern.id));for(let o of c){if(d.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);s.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,i*2),d=new Set(s.map(o=>o.pattern.id));for(let o of c){if(d.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.ftsScore);s.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch{}s.sort((c,d)=>d.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,P(s.slice(0,i))}async recordUsage(e,t,r,i){if(!this.sqliteStore)return v(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t,r,i),P(void 0)}catch(s){return v(new Error(`recordUsage failed: ${S(s)}`))}}async promote(e){if(!this.sqliteStore)return v(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return v(new Error(`promote failed: ${S(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,S(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return v(new Error(`SQLite delete failed: ${S(t)}`))}return P(void 0)}async getStats(){let e=this.adapter?.status(),t=0,r={},i={shortTerm:0,longTerm:0};if(this.sqliteStore)try{let s=this.sqliteStore.getStats();t=s.totalPatterns,r=s.byDomain,i={shortTerm:s.byTier["short-term"]??0,longTerm:s.byTier["long-term"]??0}}catch{}return{totalPatterns:t,byTier:i,byDomain:r,byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=W&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",S(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,i=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:i,estimatedTokenSavings:i?500:0,reuseConfidence:i?t*e.successRate:0}}};ot();Ie();O();function lt(n,e){let r=[n.pattern,n];for(let i of r){let s=e.split("."),a=i;for(let c of s){if(a==null)break;if(typeof a=="object")a=a[c];else{a=void 0;break}}if(a!==void 0)return a}}function dt(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let s=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),c=t[1]instanceof Date?t[1].getTime():Number(t[1]);return s>=a&&s<=c}return!1}let[r,i]=t;return n>=r&&n<=i}default:return!1}}function G(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>G(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>G(n,r))}case"NOT":return e.child?!G(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=lt(n,e.field);return dt(t,e.operator,e.value)}default:return!0}}function He(n,e){return e?n.filter(t=>G(t,e)):n}O();O();var ke=1e4,Ue=2166136261;function qe(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 le=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;le[n]=e}var Le="0123456789abcdef";function ut(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=Le[i>>4]+Le[i&15]}return t}function ht(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 ft(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let i=1;i<n.length;i++)if(n[i].length!==e)throw new Error(`Vector length mismatch at index ${i}: expected ${e}, got ${n[i].length}`);let t=new Uint8Array(e),r=n.length/2;for(let i=0;i<e;i++){let s=0;for(let a=0;a<8;a++){let c=0,d=1<<a;for(let o=0;o<n.length;o++)n[o][i]&d&&c++;c>=r&&(s|=d)}t[i]=s}return t}function mt(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+=le[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function pt(n,e,t){return 1-mt(n,e,t)}var oe=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??ke,this.baseSeed=e?.seed??Ue,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=qe(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=ht(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 ft([r,i])}similarity(e,t){return pt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new se(e),i=0;for(;i<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-i);for(let d=0;d<c;d++)t[i++]=a>>>d*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},ce=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??ke,this.baseSeed=e?.seed??Ue,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=qe(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:ut(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+=le[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 se(e),s=0;for(;s<t;){let c=i.next(),d=t-s,o=d<4?d:4;for(let l=0;l<o;l++)r[s++]=c>>>l*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function Qe(n){return new ce(n)}function $e(n){return $()?new oe(n):null}var Se=st(Ve(),1),ve=Se.default??Se,Ht=`
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 Xe(n,e){let t=ve.compare(n,e),r=ve.compare(e,n);return{forward:t,reverse:r}}function Lt(n,e){let t=JSON.parse(JSON.stringify(n));return ve.applyPatch(t,e).newDocument}function Ge(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 te=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(Ht),this.prepareStatements(),this.initialized=!0)}prepareStatements(){this.prepared.set("insert",this.db.prepare(`
19
+ INSERT INTO pattern_deltas (id, pattern_id, version, timestamp, type, patch, reverse_patch, metadata)
20
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
21
+ `)),this.prepared.set("getHistory",this.db.prepare(`
22
+ SELECT * FROM pattern_deltas
23
+ WHERE pattern_id = ?
24
+ ORDER BY version ASC
25
+ `)),this.prepared.set("currentVersion",this.db.prepare(`
26
+ SELECT MAX(version) as max_version FROM pattern_deltas
27
+ WHERE pattern_id = ?
28
+ `)),this.prepared.set("incrementalSync",this.db.prepare(`
29
+ SELECT * FROM pattern_deltas
30
+ WHERE timestamp > ?
31
+ ORDER BY timestamp ASC
32
+ `)),this.prepared.set("countForPattern",this.db.prepare(`
33
+ SELECT COUNT(*) as cnt FROM pattern_deltas
34
+ WHERE pattern_id = ?
35
+ `)),this.prepared.set("deleteOldest",this.db.prepare(`
36
+ DELETE FROM pattern_deltas
37
+ WHERE pattern_id = ? AND version IN (
38
+ SELECT version FROM pattern_deltas
39
+ WHERE pattern_id = ?
40
+ ORDER BY version ASC
41
+ LIMIT ?
42
+ )
43
+ `))}ensureInitialized(){if(!this.initialized)throw new Error("DeltaTracker not initialized. Call initialize() first.")}createGenesis(e,t,r){this.ensureInitialized();let i=this.getCurrentVersion(e);if(i>=0)throw new Error(`Genesis already exists for pattern ${e} (current version: ${i})`);let s={id:D(),patternId:e,version:0,timestamp:Date.now(),type:"genesis",patch:[],reversePatch:[],metadata:{...r,snapshot:t}};return this.insertEvent(s),s}recordDelta(e,t,r,i){this.ensureInitialized();let s=this.getCurrentVersion(e);if(s<0)throw new Error(`No genesis found for pattern ${e}. Call createGenesis() first.`);let{forward:a,reverse:c}=Xe(t,r),d={id:D(),patternId:e,version:s+1,timestamp:Date.now(),type:"update",patch:a,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),a=this.reconstructState(r,i),{forward:c,reverse:d}=Xe(a,s),o={id:D(),patternId:e,version:i+1,timestamp:Date.now(),type:"rollback",patch:c,reversePatch:d,metadata:{rolledBackTo:t}};return this.insertEvent(o),this.enforceRetention(e),s}getHistory(e){return this.ensureInitialized(),this.prepared.get("getHistory").all(e).map(Ge)}incrementalSync(e){return this.ensureInitialized(),this.prepared.get("incrementalSync").all(e).map(Ge)}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=Lt(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 kt={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},we=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...kt,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let i=this.computeSparseChanges(new Array(t.length).fill(0),t),s={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:i,metadata:r,compressedSize:i.length},a={patternId:e,version:0,fullVector:[...t],timestamp:s.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(s),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(s),s}recordDelta(e,t,r,i){let s=this.versions.get(e);if(s===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=s+1,c=this.computeSparseChanges(t,r),d={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:i,compressedSize:c.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(d),this.buffer.push(d),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,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)||[],a=null;for(let o=s.length-1;o>=0;o--)if(s[o].version<=t){a=s[o];break}if(!a)return null;let c=[...a.fullVector],d=a.version+1;for(let o of r)if(!(o.version<d)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,i=this.history.get(e);if(!i||i.length<=r)return 0;let s=i.length-r,a=i.slice(0,s),c=i.slice(s),d=a.findIndex(f=>f.deltaType==="genesis");d>=0&&(c.unshift(a[d]),a.splice(d,1)),this.history.set(e,c);let o=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(f=>f.version===0||f.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,c=s<t.length?t[s]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:s,oldValue:a,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function Ye(n){return L()?new we(n):null}O();var Ut=128,qt=8,Qt=1e4,Pe=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Ut,this.beta=e?.beta??qt,this.maxPatterns=e?.maxPatterns??Qt,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let i=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:i,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let l=0;l<this.patterns.length;l++)r[l]=this.beta*this.dotProduct(this.patterns[l].pattern,t);let i=this.softmax(r),s=0,a=i[0];for(let l=1;l<i.length;l++)i[l]>a&&(a=i[l],s=l);let c=this.patterns[s],d=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:d,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let i=new Float32Array(this.patterns.length),s=-1/0;for(let o=0;o<this.patterns.length;o++)i[o]=this.beta*r[o],i[o]>s&&(s=i[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(i[o]-s);let c=1/this.beta*(s+Math.log(a)),d=this.dotProduct(t,t);return-c+.5*d}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let s=0;s<e.length;s++)e[s]>r&&(r=e[s]);let i=0;for(let s=0;s<e.length;s++)t[s]=Math.exp(e[s]-r),i+=t[s];if(i>0)for(let s=0;s<t.length;s++)t[s]/=i;return t}dotProduct(e,t){let r=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),i=Math.sqrt(this.dotProduct(e,e)),s=Math.sqrt(this.dotProduct(t,t));return i===0||s===0?0:r/(i*s)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let i=0;i<e.length;i++)r[i]=e[i]/t;return r}assertEnabled(){if(!F().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function Ke(n){return new Pe(n)}O();var $t={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},M=1e-5,Ze=1-M;function zt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function C(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function Jt(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var x=class n{static poincareDistance(e,t){let r=C(Jt(e,t)),i=Math.max(M,1-C(e)),s=Math.max(M,1-C(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=zt(e,t),i=C(e),s=C(t),a=Math.max(M,1+2*r+i*s),c=1+2*r+s,d=1-i,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+d*t[l])/a;return n.project(o)}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),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=s/i*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(C(e));if(t<=Ze)return new Float32Array(e);let r=Ze/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)}},be=class{config;points=new Map;constructor(e){if(this.config={...$t,...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,a)=>s.distance-a.distance),i.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,i=new Map,s=new Map,a=[];for(let d of e)if(s.set(d.id,d),!d.parentId)a.push(d.id);else{let o=i.get(d.parentId);o||(o=[],i.set(d.parentId,o)),o.push(d.id)}let c=a.map((d,o)=>({id:d,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;c.length>0;){let{id:d,depth:o,angOff:l,angSpan:f}=c.shift(),h=Math.tanh(.3*(o+.1)),u=l+f/2,m=new Float32Array(r);m[0]=h*Math.cos(u),m[1]=h*Math.sin(u);let p=s.get(d);if(p&&p.features.length>0){let H=h*.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:o,parentId:p?.parentId}});let w=i.get(d)??[];for(let H=0;H<w.length;H++){let I=f/Math.max(1,w.length);c.push({id:w[H],depth:o+1,angOff:l+H*I,angSpan:I})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function et(n){return Bt()?new be(n):null}function Bt(){return F().useHyperbolicHnsw}O();var Ee=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=et(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(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function tt(n){return new Ee(n)}var Ae=null;function nt(){return Ae||(Ae=Qe({dimensions:1e4})),Ae}var Re;function Wt(){return Re===void 0&&(Re=$e()),Re}var Q=null,Te=0;function it(n){return(!Q||Te!==n)&&(Q=Ke({dimension:n,maxPatterns:1e4}),Te=n),Q}var X={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:W,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},Ce=class{constructor(e,t={}){this.memory=e;this.config={...X,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;nullStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;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 te(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){if(this.hnswIndex!==null){let e=T()?.spaceId??this.config.embeddingSpaceId??null;return this.hnswSpaceId!==e?(console.warn("[PatternStore] VECTOR_SPACE_MISMATCH: active embedder changed; semantic index disabled"),null):this.hnswIndex}return this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(this.hnswSpaceId=T()?.spaceId??this.config.embeddingSpaceId??null,!this.hnswSpaceId)throw new Error("VECTOR_SPACE_UNVERIFIED: cannot initialize HNSW without runtime provenance");if(F().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-W634ZOTV.js"),{HnswAdapter:c}=await import("./hnsw-adapter-NV2NNBJL.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 a(d),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)"),await this.loadEmbeddingsIntoHNSW();return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-GRJ3KA2O.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,i=this.hnswIndex.initialize(),s=new Promise((a,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",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:a,embedding:c,spaceId:d}of e){if(r>=t)break;if(!s||d!==s||!c||c.length!==this.config.embeddingDimension){i++;continue}let o=this.patternCache.get(a);if(!o){i++;continue}try{await this.hnswIndex.insert(a,c,{filePath:o.patternType,lineCoverage:o.confidence*100,branchCoverage:o.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-o.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=Ye()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",S(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=V(e);if(!t.valid)return v(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return v(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));let r=(process.env.AQE_MEMORY_BACKEND??"memory")!=="memory";if(r&&!this.sqliteStore)return v(new A(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let i=T()?.spaceId??this.config.embeddingSpaceId;if(e.embedding&&!i)return v(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let a=this.patternCache.get(e.id)??null,c=!1,d=()=>{this.unindexPattern(e),a&&this.indexPattern(a)};if(this.indexPattern(e),this.sqliteStore)try{let o=this.sqliteStore.storePattern(e,e.embedding,i);o&&o!==e.id&&(this.unindexPattern(e),e.id=o,this.indexPattern(e)),c=!0}catch(o){return d(),v(new A(e.id,"FAILED",o))}if(e.embedding){let o=await this.ensureHNSW();if(!o&&c)return v(new A(e.id,"COMMITTED_PENDING_INDEX",new Error("HNSW unavailable after authoritative pattern commit")));if(!o&&r)return d(),v(new A(e.id,"FAILED",new Error("HNSW unavailable before an authoritative pattern commit")));if(o)try{await o.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(l){return c||d(),v(new A(e.id,c?"COMMITTED_PENDING_INDEX":"FAILED",l))}}if($())try{let l=nt().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,l.vector)}catch(o){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,S(o))}try{let o=Wt();if(o){let l=[e.patternType,e.qeDomain];e.context?.tags&&l.push(...e.context.tags),e.name&&l.push(e.name);let f=o.fingerprintPattern(l);this.hdcTokenCache.set(e.id,f)}}catch(o){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,S(o))}if(re()&&e.embedding)try{it(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(o){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,S(o))}if(L()&&this.deltaTracker)try{let o={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,o)}catch(o){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,S(o))}if(e.embedding)try{let o=this.getVectorDeltaTracker();o&&(a?.embedding?o.recordDelta(e.id,a.embedding,e.embedding):o.getVersion(e.id)<0&&o.recordGenesis(e.id,e.embedding))}catch(o){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,S(o))}try{k()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return P(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:D(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?P(i):v(s.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),i=t.limit||10,s=[];try{if(Array.isArray(e)&&re())try{let h=it(e.length);if(h.getPatternCount()>0){let u=h.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(h){console.debug("[PatternStore] Hopfield recall failed:",S(h))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let h=T()?.spaceId??this.config.embeddingSpaceId;if(!h||t.embeddingSpaceId!==h)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 h=this.sqliteStore.searchFTS(e,i*2);if(h.length>0){let u=new Map(h.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 h){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 h=await this.searchByText(typeof e=="string"?e:"",t,i-s.length),u=new Set(s.map(m=>m.pattern.id));for(let m of h)u.has(m.pattern.id)||s.push(m)}let a=720*60*60*1e3,c=Date.now();for(let h of s){let u=h.pattern.lastUsedAt?.getTime()??h.pattern.createdAt.getTime(),m=c-u,p=Math.pow(.5,m/a),y=h.pattern.usageCount>0?p:.5;h.score=h.score*(.7+.3*y)}let d=this.sqliteStore?.getDatabase();if(d&&s.length>0)try{this.nullStore||(this.nullStore=new ae(d));let h=this.nullStore.getNullSummaries(s.map(u=>u.pattern.id));for(let u of s){let m=h.get(u.pattern.id);m&&(u.nullSummary=m,u.score=ae.applyNullDiscount(u.score,m,t.contextFingerprint))}}catch(h){console.debug("[PatternStore] null discount skipped:",S(h))}s.sort((h,u)=>u.score-h.score);let o=s;t.filter&&(o=He(s,t.filter));let l=o.slice(0,i),f=performance.now()-r;return this.recordSearchLatency(f),P(l)}catch(a){return v(xe(a))}}async searchByText(e,t,r){let i=[],s=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let c=[...a];if($()&&s&&this.hdcCache.size>0)try{let d=nt(),o=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(o.vector,this.hdcCache.get(u))}));l.sort((u,m)=>m.similarity-u.similarity);let f=l.map(u=>u.id),h=c.filter(u=>!this.hdcCache.has(u));c=[...f,...h]}catch{}for(let d of c){if(i.length>=r)break;let o=this.patternCache.get(d);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(s){let f=o.name.toLowerCase(),h=o.description.toLowerCase();f.includes(s)&&(l+=.5),h.includes(s)&&(s.length/h.length>.3?l+=.5:l+=.3);for(let u of o.context.tags)if(u.toLowerCase().includes(s)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!s){let f=this.calculateReuseInfo(o,l);i.push({pattern:o,score:l||o.qualityScore,matchType:s?"exact":"context",similarity:l||o.qualityScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}return i}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,i=t>=r.minSimilarityForReuse,s=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),d=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&d,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,f=t,h=e.successRate,u=Math.min(e.reuseCount/10,1),m=o?f*.4+h*.4+u*.2:0;return{canReuse:o,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 a=new Date,c=s.usageCount+1,d=s.successfulUses+(t?1:0),o=d/c,l=t?.02:-.01,f=Math.max(.1,Math.min(1,s.confidence+l)),h=j({confidence:f,usageCount:c,successRate:o}),u={...s,usageCount:c,successfulUses:d,successRate:o,confidence:f,qualityScore:h,lastUsedAt:a};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=ne(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[o,l]of this.domainIndex)e[o]=l.size;for(let[o,l]of this.typeIndex)t[o]=l.size;let r=0,i=0,s=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,i+=o.qualityScore,s+=o.successRate,a++;let c=await this.ensureHNSW(),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:a>0?r/a:0,avgQualityScore:a>0?i/a:0,avgSuccessRate:a>0?s/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable: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 a=ne(s);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.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(),o=Date.now()-d,l=o>10080*60*1e3,f=s.qualityScore<.2,h=s.usageCount===0&&o>1440*60*1e3;(l&&f||h)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let c=this.patternCache.get(a);c&&r.push(c)}r.sort((a,c)=>a.qualityScore-c.qualityScore);let i=Math.ceil(r.length*.1),s=0;for(let a of r){if(s>=i)break;a.tier==="short-term"&&(await this.delete(a.id),s++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),Q&&(Q.clear(),Q=null,Te=0),this.initialized=!1}indexHyperbolic(e,t,r){if(k())try{this.hyperbolicIndex||(this.hyperbolicIndex=tt({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 a=await this.get(s.patternId);if(!a)continue;let c=Math.exp(-s.distance),d=this.calculateReuseInfo(a,c);i.push({pattern:a,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 rn(n,e){try{if(F().useRVFPatternStore&&_e()){let r=process.env.AQE_PROJECT_ROOT??De(),i=rt(r,".agentic-qe"),s=rt(i,"patterns.rvf");if(jt(i)){let a={...X,...e},c=!1;try{let d=Me(i,a.embeddingDimension);if(d){c=!0;let o=new z(()=>d,{rvfPath:s,base:a,skipCloseOnDispose:!0,embeddingSpaceId:a.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),o}}catch{}if(!c){let d=new z((o,l)=>{let f=()=>{try{return Oe(o)}catch{return null}},h=f();if(h){if(h.dimension()!==l){try{h.close()}catch{}throw new Error(`RVF dimension mismatch (file=${h.dimension()}, requested=${l})`)}return h}try{return ie(o,l)}catch(u){if(h=f(),h&&h.dimension()===l)return h;if(Ne(o,u instanceof Error?u.message:String(u)))return ie(o,l);throw u}},{rvfPath:s,base:a,embeddingSpaceId:a.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 Ce(n,e)}export{A as a,rn as b};
50
+ /*! Bundled license information:
51
+
52
+ fast-json-patch/commonjs/helpers.js:
53
+ (*!
54
+ * https://github.com/Starcounter-Jack/JSON-Patch
55
+ * (c) 2017-2022 Joachim Wester
56
+ * MIT licensed
57
+ *)
58
+
59
+ fast-json-patch/commonjs/duplex.js:
60
+ (*!
61
+ * https://github.com/Starcounter-Jack/JSON-Patch
62
+ * (c) 2017-2021 Joachim Wester
63
+ * MIT license
64
+ *)
65
+ */
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
- import{a as n}from"./chunk-3EM2MK3Z.js";import{a as o}from"./chunk-VYENTZ45.js";import{a,e as c}from"./chunk-JAK5UUWH.js";c();var M=a.CLEANUP_INTERVAL_MS,y=".agentic-qe/memory.db";async function d(r,t=!0){let e;switch(r.type){case"memory":e=new o;break;case"sqlite":e=new n({sqlite:r.sqlite,enableFallback:!0});break;case"agentdb":e=new n({sqlite:{path:r.agentdb?.path??y},enableFallback:!0});break;case"hybrid":e=new n(r.hybrid);break;default:throw new Error(`Unknown memory backend type: ${r.type}`)}return t&&await e.initialize(),{backend:e,type:r.type,initialized:t}}async function u(r=!0){let t=process.env.AQE_MEMORY_BACKEND??"memory",e=process.env.AQE_MEMORY_PATH??".agentic-qe",i={type:t,sqlite:{path:`${e}/memory.db`,walMode:!0},agentdb:{path:`${e}/memory.db`},hybrid:{enableFallback:!0,sqlite:{path:`${e}/memory.db`}}};return d(i,r)}export{d as a,u as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.1");process.exit(0)}
2
+ import{a as n}from"./chunk-RCHDSUVU.js";import{a as o}from"./chunk-ND6JBUVH.js";import{a,e as c}from"./chunk-7GF6IRSU.js";c();var M=a.CLEANUP_INTERVAL_MS,y=".agentic-qe/memory.db";async function d(r,t=!0){let e;switch(r.type){case"memory":e=new o;break;case"sqlite":e=new n({sqlite:r.sqlite,enableFallback:!0});break;case"agentdb":e=new n({sqlite:{path:r.agentdb?.path??y},enableFallback:!0});break;case"hybrid":e=new n(r.hybrid);break;default:throw new Error(`Unknown memory backend type: ${r.type}`)}return t&&await e.initialize(),{backend:e,type:r.type,initialized:t}}async function u(r=!0){let t=process.env.AQE_MEMORY_BACKEND??"memory",e=process.env.AQE_MEMORY_PATH??".agentic-qe",i={type:t,sqlite:{path:`${e}/memory.db`,walMode:!0},agentdb:{path:`${e}/memory.db`},hybrid:{enableFallback:!0,sqlite:{path:`${e}/memory.db`}}};return d(i,r)}export{d as a,u as b};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
- import{a as p,b as A,c as L}from"./chunk-XITTURP2.js";var R={reflexThreshold:.1,retrievalThreshold:.4,heavyThreshold:.7},M={enabled:!0,laneConfig:R,coherenceThreshold:.1,fallbackEnabled:!0,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},m={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},f=class extends Error{constructor(t,i,n){super(t);this.code=i;this.cause=n;this.name="CoherenceError"}code;cause},h=class extends f{constructor(e="WASM module is not loaded",t){super(e,"WASM_NOT_LOADED",t),this.name="WasmNotLoadedError"}};var T=class extends f{constructor(t,i,n){super(t,"WASM_LOAD_FAILED",n);this.attempts=i;this.name="WasmLoadError"}attempts},z={maxAttempts:3,baseDelayMs:100,maxDelayMs:5e3,timeoutMs:1e4};L();function D(u){let e=new Map,t=[],i=new Map,n=new Map,r=0,a=s=>{let l=i.get(s);return l===void 0&&(l=r++,i.set(s,l),n.set(l,s)),l},o=s=>n.get(s)??`unknown-${s}`,d=()=>({nodes:Array.from(e.entries()).map(([s,l])=>({id:a(s),label:s,section:Array.from(l.embedding),weight:1})),edges:t.map(s=>({source:a(s.source),target:a(s.target),weight:s.weight}))});return{add_node(s,l){e.set(s,{embedding:l}),a(s)},add_edge(s,l,c){t.push({source:s,target:l,weight:c}),a(s),a(l)},remove_node(s){e.delete(s);for(let l=t.length-1;l>=0;l--)(t[l].source===s||t[l].target===s)&&t.splice(l,1)},remove_edge(s,l){let c=t.findIndex(g=>g.source===s&&g.target===l);c>=0&&t.splice(c,1)},sheaf_laplacian_energy(){let s=d();return u.consistencyEnergy(s)},detect_contradictions(s){let l=d(),c=u.detectObstructions(l);return c?c.filter(g=>g.energy>s).map(g=>({node1:o(g.node1),node2:o(g.node2),severity:g.energy,distance:g.energy})):[]},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var y=class{constructor(e,t=m){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=D(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: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)}};L();function N(u){let e=new Set,t=[],i=new Map,n=new Map,r=0,a=s=>{let l=i.get(s);return l===void 0&&(l=r++,i.set(s,l),n.set(l,s)),l},o=s=>n.get(s)??`unknown-${s}`,d=()=>({n:e.size,edges:t.map(s=>[a(s.source),a(s.target),s.weight])});return{add_node(s){e.add(s),a(s)},add_edge(s,l,c){t.push({source:s,target:l,weight:c}),a(s),a(l)},remove_node(s){e.delete(s);for(let l=t.length-1;l>=0;l--)(t[l].source===s||t[l].target===s)&&t.splice(l,1)},compute_fiedler_value(){if(e.size<2||t.length===0)return 0;try{let s=d(),l=u.algebraicConnectivity(s);return Number.isFinite(l)&&l>=0?l:0}catch(s){return console.warn("[SpectralAdapter] algebraicConnectivity failed:",s),0}},predict_collapse_risk(){if(e.size<2)return 0;if(t.length===0)return 1;try{let s=d(),l=u.algebraicConnectivity(s),c=Number.isFinite(l)&&l>=0?l:0;return Math.max(0,Math.min(1,1-c))}catch(s){return console.warn("[SpectralAdapter] predict_collapse_risk failed:",s),.8}},get_weak_vertices(s){if(e.size===0)return[];if(t.length===0)return Array.from(e).slice(0,s);try{let l=d(),c=u.predictMinCut(l);return c?.vertices?c.vertices.slice(0,s).map(g=>o(g)):Array.from(e).slice(0,s)}catch(l){return console.warn("[SpectralAdapter] predictMinCut failed:",l),Array.from(e).slice(0,s)}},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var v=class{constructor(e,t=m){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=N(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:p(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:p(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:p(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,o={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}),o}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,o=e.beliefs??[],d=t.beliefs??[];return o.length>0&&d.length>0&&(a=this.computeBeliefOverlap(o,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 o=0;o<e.length;o++)i+=e[o]*t[o],n+=e[o]*e[o],r+=t[o]*t[o];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 O(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 b=class{constructor(e,t=m){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=O(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[g,F]of Object.entries(i.confounders))this.addConfounder(g,F);let r=this.computeCausalEffect(),a=this.detectSpuriousCorrelation(),o=this.getConfounders(),d=this.determineRelationshipType(r,a,o.length>0),s=this.computeConfidence(i.sampleSize,r,a),l=Date.now()-n,c={isCausal:d==="causal",effectStrength:r,relationshipType:d,confidence:s,confounders:o,explanation:this.generateExplanation(e,t,d,r,o),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 H(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 o=n[a],d=n[a+1];if(!t.some(l=>l.source===o&&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 C=class{constructor(e,t=m){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=H(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 s of e.elements)this.addType(s.inputType,this.inferSchema(s.inputType)),this.addType(s.outputType,this.inferSchema(s.outputType));for(let s of e.elements)this.addMorphism(s.inputType,s.outputType,s.name);let i=this.buildCompositionPath(e),n=this.verifyComposition(i),r=this.checkTypeConsistency(),a=this.generateWarnings(e,n,r),o=Date.now()-t,d={isValid:n&&r.length===0,mismatches:r,warnings:a,durationMs:o,usedFallback:!1};return this.logger.info("Verified pipeline",{pipelineId:e.id,isValid:d.isValid,mismatchCount:r.length,warningCount:a.length,durationMs:o}),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 V(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},o={formula:r.formula};return u.typeCheck(a,o)?.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 w=class{constructor(e,t=m){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=V(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 $}from"crypto";var E=class{constructor(e,t=m){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=$("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()}`,o={witnessId:a,decisionId:e.id,hash:r.hash,previousWitnessId:i?.witnessId,chainPosition:r.position,timestamp:new Date(r.timestamp)};return this.witnesses.set(a,o),this.decisions.set(e.id,e),this.logger.info("Created witness",{witnessId:a,decisionId:e.id,chainPosition:o.chainPosition}),o}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,o={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}),o}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 I=class{constructor(e,t={},i){this.wasmLoader=e;this.config={...M,...t},this.logger=i||m}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 y(this.wasmLoader,this.logger),this.spectralAdapter=new v(this.wasmLoader,this.logger),this.causalAdapter=new b(this.wasmLoader,this.logger),this.categoryAdapter=new C(this.wasmLoader,this.logger),this.homotopyAdapter=new w(this.wasmLoader,this.logger),this.witnessAdapter=new E(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 f("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",A(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 o of e)this.cohomologyAdapter.addNode(o);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 s=0;s<e.length;s++)for(let l=s+1;l<e.length;l++){let c=this.euclideanDistance(e[s].embedding,e[l].embedding);i+=c,n++,c>1.5&&r.push({nodeIds:[e[s].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,o=this.computeLane(a),d=Date.now()-t;return this.updateStats(a,d,r.length,o,!0),{energy:a,isCoherent:a<this.config.coherenceThreshold,lane:o,contradictions:r,recommendations:this.generateRecommendations(a,o,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:p(t),agentCount:e.agents.length}),this.predictCollapseWithFallback(e)}return this.predictCollapseWithFallback(e)}predictCollapseWithFallback(e){let t=Date.now(),i=e.agents.reduce((o,d)=>o+d.health,0)/Math.max(e.agents.length,1),n=e.agents.reduce((o,d)=>o+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(o=>o.health<.5||o.successRate<.5).map(o=>o.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 o=a+1;o<e.length;o++)e[a].verdict===e[o].verdict&&(this.spectralAdapter.addEdge(e[a].agentId,e[o].agentId,Math.min(e[a].confidence,e[o].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:p(i),voteCount:e.length}),this.verifyConsensusWithFallback(e,t)}return this.verifyConsensusWithFallback(e,t)}verifyConsensusWithFallback(e,t){let i=new Map;for(let o of e){let d=String(o.verdict);i.set(d,(i.get(d)||0)+1)}let n=0;i.forEach(o=>{n=Math.max(n,o)});let r=n/e.length,a=e.reduce((o,d)=>o+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(o=>r.add(o));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 o=0;o<e.length;o++)i+=e[o]*t[o],n+=e[o]*e[o],r+=t[o]*t[o];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,o=0,d=0;for(let l=0;l<i;l++){let c=e[l]-n,g=t[l]-r;a+=c*g,o+=c*c,d+=g*g}let s=Math.sqrt(o*d);return s===0?0:a/s}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 Q(u,e,t){let i=new I(u,e,t);return await i.initialize(),i}L();import{createRequire as _}from"node:module";import{fileURLToPath as K}from"node:url";import{dirname as x,join as S}from"node:path";import{readFileSync as X,existsSync as P}from"node:fs";var W=[1e3,2e3,4e3],k=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={...z,...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=A(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=_(import.meta.url),t=[(()=>{try{let i=e.resolve("prime-radiant-advanced-wasm");return S(x(i),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),S(process.cwd(),"node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm")].filter(i=>i!==null);for(let i of t)if(P(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(),o=await this.attemptLoad(),d=performance.now()-a;return this.emit("loaded",{version:this.version,loadTimeMs:Math.round(d*100)/100}),o}catch(a){if(n=A(a),this.emit("error",{error:n,fatal:r>=e,attempt:r}),r<e){let o=Math.min(t*Math.pow(2,r-1),i);this.emit("retry",{attempt:r+1,maxAttempts:e,delayMs:o,previousError:n}),await this.sleep(o)}}throw new T(`Failed to load WASM module after ${e} attempts: ${n.message}`,e,n)}async attemptLoad(){let e;try{e=_(import.meta.url)}catch{e=globalThis.require||(await import("module")).createRequire(__filename)}let t;try{t=await import("./prime-radiant-advanced-wasm-DPJUPNCG.js")}catch(r){try{t=e("prime-radiant-advanced-wasm")}catch{throw new Error(`Failed to import prime-radiant-advanced-wasm: ${p(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 S(x(a),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),S(x(K(import.meta.url)),"../../../../node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm"),S(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(P(a)){n=a;break}if(!n)throw new Error(`Could not find WASM binary. Searched paths:
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.1");process.exit(0)}
2
+ import{a as p,b as A,c as L}from"./chunk-NAJCQJSK.js";var R={reflexThreshold:.1,retrievalThreshold:.4,heavyThreshold:.7},M={enabled:!0,laneConfig:R,coherenceThreshold:.1,fallbackEnabled:!0,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},m={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},f=class extends Error{constructor(t,i,n){super(t);this.code=i;this.cause=n;this.name="CoherenceError"}code;cause},h=class extends f{constructor(e="WASM module is not loaded",t){super(e,"WASM_NOT_LOADED",t),this.name="WasmNotLoadedError"}};var T=class extends f{constructor(t,i,n){super(t,"WASM_LOAD_FAILED",n);this.attempts=i;this.name="WasmLoadError"}attempts},z={maxAttempts:3,baseDelayMs:100,maxDelayMs:5e3,timeoutMs:1e4};L();function D(u){let e=new Map,t=[],i=new Map,n=new Map,r=0,a=s=>{let l=i.get(s);return l===void 0&&(l=r++,i.set(s,l),n.set(l,s)),l},o=s=>n.get(s)??`unknown-${s}`,d=()=>({nodes:Array.from(e.entries()).map(([s,l])=>({id:a(s),label:s,section:Array.from(l.embedding),weight:1})),edges:t.map(s=>({source:a(s.source),target:a(s.target),weight:s.weight}))});return{add_node(s,l){e.set(s,{embedding:l}),a(s)},add_edge(s,l,c){t.push({source:s,target:l,weight:c}),a(s),a(l)},remove_node(s){e.delete(s);for(let l=t.length-1;l>=0;l--)(t[l].source===s||t[l].target===s)&&t.splice(l,1)},remove_edge(s,l){let c=t.findIndex(g=>g.source===s&&g.target===l);c>=0&&t.splice(c,1)},sheaf_laplacian_energy(){let s=d();return u.consistencyEnergy(s)},detect_contradictions(s){let l=d(),c=u.detectObstructions(l);return c?c.filter(g=>g.energy>s).map(g=>({node1:o(g.node1),node2:o(g.node2),severity:g.energy,distance:g.energy})):[]},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var y=class{constructor(e,t=m){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=D(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: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)}};L();function N(u){let e=new Set,t=[],i=new Map,n=new Map,r=0,a=s=>{let l=i.get(s);return l===void 0&&(l=r++,i.set(s,l),n.set(l,s)),l},o=s=>n.get(s)??`unknown-${s}`,d=()=>({n:e.size,edges:t.map(s=>[a(s.source),a(s.target),s.weight])});return{add_node(s){e.add(s),a(s)},add_edge(s,l,c){t.push({source:s,target:l,weight:c}),a(s),a(l)},remove_node(s){e.delete(s);for(let l=t.length-1;l>=0;l--)(t[l].source===s||t[l].target===s)&&t.splice(l,1)},compute_fiedler_value(){if(e.size<2||t.length===0)return 0;try{let s=d(),l=u.algebraicConnectivity(s);return Number.isFinite(l)&&l>=0?l:0}catch(s){return console.warn("[SpectralAdapter] algebraicConnectivity failed:",s),0}},predict_collapse_risk(){if(e.size<2)return 0;if(t.length===0)return 1;try{let s=d(),l=u.algebraicConnectivity(s),c=Number.isFinite(l)&&l>=0?l:0;return Math.max(0,Math.min(1,1-c))}catch(s){return console.warn("[SpectralAdapter] predict_collapse_risk failed:",s),.8}},get_weak_vertices(s){if(e.size===0)return[];if(t.length===0)return Array.from(e).slice(0,s);try{let l=d(),c=u.predictMinCut(l);return c?.vertices?c.vertices.slice(0,s).map(g=>o(g)):Array.from(e).slice(0,s)}catch(l){return console.warn("[SpectralAdapter] predictMinCut failed:",l),Array.from(e).slice(0,s)}},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var v=class{constructor(e,t=m){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=N(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:p(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:p(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:p(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,o={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}),o}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,o=e.beliefs??[],d=t.beliefs??[];return o.length>0&&d.length>0&&(a=this.computeBeliefOverlap(o,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 o=0;o<e.length;o++)i+=e[o]*t[o],n+=e[o]*e[o],r+=t[o]*t[o];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 O(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 b=class{constructor(e,t=m){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=O(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[g,F]of Object.entries(i.confounders))this.addConfounder(g,F);let r=this.computeCausalEffect(),a=this.detectSpuriousCorrelation(),o=this.getConfounders(),d=this.determineRelationshipType(r,a,o.length>0),s=this.computeConfidence(i.sampleSize,r,a),l=Date.now()-n,c={isCausal:d==="causal",effectStrength:r,relationshipType:d,confidence:s,confounders:o,explanation:this.generateExplanation(e,t,d,r,o),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 H(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 o=n[a],d=n[a+1];if(!t.some(l=>l.source===o&&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 C=class{constructor(e,t=m){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=H(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 s of e.elements)this.addType(s.inputType,this.inferSchema(s.inputType)),this.addType(s.outputType,this.inferSchema(s.outputType));for(let s of e.elements)this.addMorphism(s.inputType,s.outputType,s.name);let i=this.buildCompositionPath(e),n=this.verifyComposition(i),r=this.checkTypeConsistency(),a=this.generateWarnings(e,n,r),o=Date.now()-t,d={isValid:n&&r.length===0,mismatches:r,warnings:a,durationMs:o,usedFallback:!1};return this.logger.info("Verified pipeline",{pipelineId:e.id,isValid:d.isValid,mismatchCount:r.length,warningCount:a.length,durationMs:o}),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 V(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},o={formula:r.formula};return u.typeCheck(a,o)?.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 w=class{constructor(e,t=m){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=V(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 $}from"crypto";var E=class{constructor(e,t=m){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=$("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()}`,o={witnessId:a,decisionId:e.id,hash:r.hash,previousWitnessId:i?.witnessId,chainPosition:r.position,timestamp:new Date(r.timestamp)};return this.witnesses.set(a,o),this.decisions.set(e.id,e),this.logger.info("Created witness",{witnessId:a,decisionId:e.id,chainPosition:o.chainPosition}),o}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,o={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}),o}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 I=class{constructor(e,t={},i){this.wasmLoader=e;this.config={...M,...t},this.logger=i||m}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 y(this.wasmLoader,this.logger),this.spectralAdapter=new v(this.wasmLoader,this.logger),this.causalAdapter=new b(this.wasmLoader,this.logger),this.categoryAdapter=new C(this.wasmLoader,this.logger),this.homotopyAdapter=new w(this.wasmLoader,this.logger),this.witnessAdapter=new E(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 f("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",A(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 o of e)this.cohomologyAdapter.addNode(o);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 s=0;s<e.length;s++)for(let l=s+1;l<e.length;l++){let c=this.euclideanDistance(e[s].embedding,e[l].embedding);i+=c,n++,c>1.5&&r.push({nodeIds:[e[s].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,o=this.computeLane(a),d=Date.now()-t;return this.updateStats(a,d,r.length,o,!0),{energy:a,isCoherent:a<this.config.coherenceThreshold,lane:o,contradictions:r,recommendations:this.generateRecommendations(a,o,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:p(t),agentCount:e.agents.length}),this.predictCollapseWithFallback(e)}return this.predictCollapseWithFallback(e)}predictCollapseWithFallback(e){let t=Date.now(),i=e.agents.reduce((o,d)=>o+d.health,0)/Math.max(e.agents.length,1),n=e.agents.reduce((o,d)=>o+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(o=>o.health<.5||o.successRate<.5).map(o=>o.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 o=a+1;o<e.length;o++)e[a].verdict===e[o].verdict&&(this.spectralAdapter.addEdge(e[a].agentId,e[o].agentId,Math.min(e[a].confidence,e[o].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:p(i),voteCount:e.length}),this.verifyConsensusWithFallback(e,t)}return this.verifyConsensusWithFallback(e,t)}verifyConsensusWithFallback(e,t){let i=new Map;for(let o of e){let d=String(o.verdict);i.set(d,(i.get(d)||0)+1)}let n=0;i.forEach(o=>{n=Math.max(n,o)});let r=n/e.length,a=e.reduce((o,d)=>o+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(o=>r.add(o));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 o=0;o<e.length;o++)i+=e[o]*t[o],n+=e[o]*e[o],r+=t[o]*t[o];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,o=0,d=0;for(let l=0;l<i;l++){let c=e[l]-n,g=t[l]-r;a+=c*g,o+=c*c,d+=g*g}let s=Math.sqrt(o*d);return s===0?0:a/s}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 Q(u,e,t){let i=new I(u,e,t);return await i.initialize(),i}L();import{createRequire as _}from"node:module";import{fileURLToPath as K}from"node:url";import{dirname as x,join as S}from"node:path";import{readFileSync as X,existsSync as P}from"node:fs";var W=[1e3,2e3,4e3],k=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={...z,...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=A(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=_(import.meta.url),t=[(()=>{try{let i=e.resolve("prime-radiant-advanced-wasm");return S(x(i),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),S(process.cwd(),"node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm")].filter(i=>i!==null);for(let i of t)if(P(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(),o=await this.attemptLoad(),d=performance.now()-a;return this.emit("loaded",{version:this.version,loadTimeMs:Math.round(d*100)/100}),o}catch(a){if(n=A(a),this.emit("error",{error:n,fatal:r>=e,attempt:r}),r<e){let o=Math.min(t*Math.pow(2,r-1),i);this.emit("retry",{attempt:r+1,maxAttempts:e,delayMs:o,previousError:n}),await this.sleep(o)}}throw new T(`Failed to load WASM module after ${e} attempts: ${n.message}`,e,n)}async attemptLoad(){let e;try{e=_(import.meta.url)}catch{e=globalThis.require||(await import("module")).createRequire(__filename)}let t;try{t=await import("./prime-radiant-advanced-wasm-WWWJRLRP.js")}catch(r){try{t=e("prime-radiant-advanced-wasm")}catch{throw new Error(`Failed to import prime-radiant-advanced-wasm: ${p(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 S(x(a),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),S(x(K(import.meta.url)),"../../../../node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm"),S(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(P(a)){n=a;break}if(!n)throw new Error(`Could not find WASM binary. Searched paths:
3
3
  ${i.join(`
4
4
  `)}
5
5
  Ensure prime-radiant-advanced-wasm is installed.`);let r=X(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,W.length-1),i=W[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<W.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}},J=new k;var Z={emaAlpha:.1,minSamplesForCalibration:10,maxHistorySize:1e3,targetFalsePositiveRate:.05,targetFalseNegativeRate:.02,maxAdjustmentPerCycle:.05,autoCalibrate:!1,autoCalibrateInterval:100,defaultThresholds:{...R}};export{Q as a,J as b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
- import{c as h,e as v,g as T}from"./chunk-PEW6FZ47.js";var y={};v(y,{DotProductAttention:()=>z,FlashAttention:()=>k,HyperbolicAttention:()=>C,LinearAttention:()=>j,MoEAttention:()=>W,MultiHeadAttention:()=>F,RuvectorLayer:()=>O,SonaEngine:()=>K,TensorCompress:()=>E,default:()=>I,differentiableSearch:()=>L,getCompressionLevel:()=>B,hierarchicalForward:()=>V,init:()=>D,pipeline:()=>q});import{createRequire as A}from"module";var _,g,I,O,E,L,V,B,D,k,z,F,C,j,W,K,q,R=h(()=>{_=A(import.meta.url),g=_("@ruvector/rvf-node"),I=g,{RuvectorLayer:O,TensorCompress:E,differentiableSearch:L,hierarchicalForward:V,getCompressionLevel:B,init:D,FlashAttention:k,DotProductAttention:z,MultiHeadAttention:F,HyperbolicAttention:C,LinearAttention:j,MoEAttention:W,SonaEngine:K,pipeline:q}=g||{}});var Z={};v(Z,{createRvfStore:()=>$,isRvfNativeAvailable:()=>X,openRvfStore:()=>G,openRvfStoreReadonly:()=>U});import{readFileSync as J,writeFileSync as H,copyFileSync as Q,existsSync as Y}from"fs";function c(){if(S)return m;S=!0;try{let s=(R(),T(y));!s.RvfDatabase&&s.default&&s.default.RvfDatabase&&(s=s.default),m=s}catch{m=null}return m}function w(s){return`${s}.idmap.json`}function N(s){let e=w(s),t=new Map,n=new Map,i=1;if(Y(e))try{let r=JSON.parse(J(e,"utf-8"));i=r.nextLabel;for(let[a,p]of r.entries)t.set(a,p),n.set(p,a)}catch{}return{strToNum:t,numToStr:n,nextLabel:i}}function b(s,e,t){let n={nextLabel:t,entries:Array.from(e.entries())};H(w(s),JSON.stringify(n),"utf-8")}function $(s,e){let t=c();if(!t)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let n=t.RvfDatabase.create(s,{dimension:e}),i=n.dimension();return new d(n,s,i,new Map,new Map,1)}function G(s){let e=c();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.open(s),n=t.dimension(),{strToNum:i,numToStr:r,nextLabel:a}=N(s);return new d(t,s,n,i,r,a)}function U(s){let e=c();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.openReadonly(s),n=t.dimension(),{strToNum:i,numToStr:r,nextLabel:a}=N(s);return new d(t,s,n,i,r,a)}function X(){return process.env.AQE_MEMORY_BACKEND==="memory"?!1:c()!==null}var m,S,d,P=h(()=>{m=null,S=!1;d=class s{db;_path;_dimension;strToNum;numToStr;nextLabel;_open;constructor(e,t,n,i,r,a){this.db=e,this._path=t,this._dimension=n,this.strToNum=i,this.numToStr=r,this.nextLabel=a,this._open=!0}ingest(e){if(this.ensureOpen(),e.length===0)return{accepted:0,rejected:0};let t=this._dimension,n=new Float32Array(e.length*t),i=[],r=[];for(let o=0;o<e.length;o++){let{id:u,vector:f,metadata:x}=e[o],l=this.strToNum.get(u);l===void 0&&(l=this.nextLabel++,this.strToNum.set(u,l),this.numToStr.set(l,u)),i.push(l),r.push(x);let M=f instanceof Float32Array?f:new Float32Array(f);n.set(M.subarray(0,t),o*t)}let a;if(r.some(o=>o!==void 0)&&typeof this.db.ingestBatchWithMetadata=="function"){let o=r.map(u=>u?JSON.stringify(u):"");a=this.db.ingestBatchWithMetadata(n,i,o)}else a=this.db.ingestBatch(n,i);return this.persistIdMap(),{accepted:a.accepted,rejected:a.rejected}}search(e,t){this.ensureOpen();let n=e instanceof Float32Array?e:new Float32Array(e);return this.db.query(n,t).map(r=>{let a=this.numToStr.get(r.id);return a===void 0?null:{id:a,distance:r.distance,score:1/(1+r.distance)}}).filter(r=>r!==null)}delete(e){this.ensureOpen();let t=[];for(let i of e){let r=this.strToNum.get(i);r!==void 0&&t.push(r)}if(t.length===0)return 0;let n=this.db.delete(t);for(let i of e){let r=this.strToNum.get(i);r!==void 0&&(this.strToNum.delete(i),this.numToStr.delete(r))}return this.persistIdMap(),n.deleted}fork(e){this.ensureOpen(),Q(this._path,e);let t=new Map(this.strToNum),n=new Map(this.numToStr);b(e,t,this.nextLabel);let r=c().RvfDatabase.open(e);return new s(r,e,this._dimension,t,n,this.nextLabel)}status(){this.ensureOpen();let e=this.db.status(),n=this.db.segments().filter(i=>i.segType==="witness");return{totalVectors:e.totalVectors,totalSegments:e.totalSegments,fileSizeBytes:e.fileSize,epoch:e.currentEpoch,witnessValid:n.length>0,witnessEntries:n.length,deadSpaceRatio:typeof e.deadSpaceRatio=="number"?e.deadSpaceRatio:0}}dimension(){return this._dimension}size(){return this.ensureOpen(),this.db.status().totalVectors}compact(){this.ensureOpen();try{let e=this.db.compact();return e&&typeof e=="object"?{segmentsCompacted:typeof e.segmentsCompacted=="number"?e.segmentsCompacted:0,bytesReclaimed:typeof e.bytesReclaimed=="number"?e.bytesReclaimed:0,epoch:typeof e.epoch=="number"?e.epoch:0}:{segmentsCompacted:0,bytesReclaimed:0,epoch:0}}catch{return null}}close(){this._open&&(this.db.close(),this._open=!1)}isOpen(){return this._open}path(){return this._path}embedKernel(e){return this.ensureOpen(),this.db.embedKernel(0,99,0,e,0,"")}extractKernel(){return this.ensureOpen(),this.db.extractKernel()}verifyWitness(){this.ensureOpen();let e=this.tryNative("verifyWitness");return e?{valid:e.valid??!0,totalEntries:e.totalEntries??0,errors:Array.isArray(e.errors)?e.errors:[]}:{valid:!0,totalEntries:0,errors:[]}}sign(e){this.ensureOpen();let t=this.tryNative("sign",e);return typeof t=="string"?t:null}fileId(){this.ensureOpen();let e=this.tryNative("fileId");return typeof e=="string"?e:null}parentId(){this.ensureOpen();let e=this.tryNative("parentId");return typeof e=="string"?e:null}lineageDepth(){this.ensureOpen();let e=this.tryNative("lineageDepth");return typeof e=="number"?e:0}indexStats(){let e=this.status();return{totalVectors:e.totalVectors,dimension:this._dimension,totalSegments:e.totalSegments,fileSizeBytes:e.fileSizeBytes,epoch:e.epoch,witnessValid:e.witnessValid,witnessEntries:e.witnessEntries,idMapSize:this.strToNum.size}}freeze(){this.ensureOpen();let e=this.tryNative("freeze");return typeof e=="number"?e:0}derive(e){this.ensureOpen();let t=c();if(typeof this.db.derive=="function")try{let n=this.db.derive(e),i=new Map(this.strToNum),r=new Map(this.numToStr);return b(e,i,this.nextLabel),new s(n,e,this._dimension,i,r,this.nextLabel)}catch{}return this.fork(e)}ensureOpen(){if(!this._open)throw new Error("RVF database is closed")}tryNative(e,...t){if(typeof this.db[e]!="function")return null;try{return this.db[e](...t)}catch{return null}}persistIdMap(){b(this._path,this.strToNum,this.nextLabel)}}});export{$ as a,G as b,U as c,X as d,Z as e,P as f};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.1");process.exit(0)}
2
+ import{c as h,e as v,g as T}from"./chunk-EHW62JL2.js";var y={};v(y,{DotProductAttention:()=>z,FlashAttention:()=>k,HyperbolicAttention:()=>C,LinearAttention:()=>j,MoEAttention:()=>W,MultiHeadAttention:()=>F,RuvectorLayer:()=>O,SonaEngine:()=>K,TensorCompress:()=>E,default:()=>I,differentiableSearch:()=>L,getCompressionLevel:()=>B,hierarchicalForward:()=>V,init:()=>D,pipeline:()=>q});import{createRequire as A}from"module";var _,g,I,O,E,L,V,B,D,k,z,F,C,j,W,K,q,R=h(()=>{_=A(import.meta.url),g=_("@ruvector/rvf-node"),I=g,{RuvectorLayer:O,TensorCompress:E,differentiableSearch:L,hierarchicalForward:V,getCompressionLevel:B,init:D,FlashAttention:k,DotProductAttention:z,MultiHeadAttention:F,HyperbolicAttention:C,LinearAttention:j,MoEAttention:W,SonaEngine:K,pipeline:q}=g||{}});var Z={};v(Z,{createRvfStore:()=>$,isRvfNativeAvailable:()=>X,openRvfStore:()=>G,openRvfStoreReadonly:()=>U});import{readFileSync as J,writeFileSync as H,copyFileSync as Q,existsSync as Y}from"fs";function c(){if(S)return m;S=!0;try{let s=(R(),T(y));!s.RvfDatabase&&s.default&&s.default.RvfDatabase&&(s=s.default),m=s}catch{m=null}return m}function w(s){return`${s}.idmap.json`}function N(s){let e=w(s),t=new Map,n=new Map,i=1;if(Y(e))try{let r=JSON.parse(J(e,"utf-8"));i=r.nextLabel;for(let[a,p]of r.entries)t.set(a,p),n.set(p,a)}catch{}return{strToNum:t,numToStr:n,nextLabel:i}}function b(s,e,t){let n={nextLabel:t,entries:Array.from(e.entries())};H(w(s),JSON.stringify(n),"utf-8")}function $(s,e){let t=c();if(!t)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let n=t.RvfDatabase.create(s,{dimension:e}),i=n.dimension();return new d(n,s,i,new Map,new Map,1)}function G(s){let e=c();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.open(s),n=t.dimension(),{strToNum:i,numToStr:r,nextLabel:a}=N(s);return new d(t,s,n,i,r,a)}function U(s){let e=c();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.openReadonly(s),n=t.dimension(),{strToNum:i,numToStr:r,nextLabel:a}=N(s);return new d(t,s,n,i,r,a)}function X(){return process.env.AQE_MEMORY_BACKEND==="memory"?!1:c()!==null}var m,S,d,P=h(()=>{m=null,S=!1;d=class s{db;_path;_dimension;strToNum;numToStr;nextLabel;_open;constructor(e,t,n,i,r,a){this.db=e,this._path=t,this._dimension=n,this.strToNum=i,this.numToStr=r,this.nextLabel=a,this._open=!0}ingest(e){if(this.ensureOpen(),e.length===0)return{accepted:0,rejected:0};let t=this._dimension,n=new Float32Array(e.length*t),i=[],r=[];for(let o=0;o<e.length;o++){let{id:u,vector:f,metadata:x}=e[o],l=this.strToNum.get(u);l===void 0&&(l=this.nextLabel++,this.strToNum.set(u,l),this.numToStr.set(l,u)),i.push(l),r.push(x);let M=f instanceof Float32Array?f:new Float32Array(f);n.set(M.subarray(0,t),o*t)}let a;if(r.some(o=>o!==void 0)&&typeof this.db.ingestBatchWithMetadata=="function"){let o=r.map(u=>u?JSON.stringify(u):"");a=this.db.ingestBatchWithMetadata(n,i,o)}else a=this.db.ingestBatch(n,i);return this.persistIdMap(),{accepted:a.accepted,rejected:a.rejected}}search(e,t){this.ensureOpen();let n=e instanceof Float32Array?e:new Float32Array(e);return this.db.query(n,t).map(r=>{let a=this.numToStr.get(r.id);return a===void 0?null:{id:a,distance:r.distance,score:1/(1+r.distance)}}).filter(r=>r!==null)}delete(e){this.ensureOpen();let t=[];for(let i of e){let r=this.strToNum.get(i);r!==void 0&&t.push(r)}if(t.length===0)return 0;let n=this.db.delete(t);for(let i of e){let r=this.strToNum.get(i);r!==void 0&&(this.strToNum.delete(i),this.numToStr.delete(r))}return this.persistIdMap(),n.deleted}fork(e){this.ensureOpen(),Q(this._path,e);let t=new Map(this.strToNum),n=new Map(this.numToStr);b(e,t,this.nextLabel);let r=c().RvfDatabase.open(e);return new s(r,e,this._dimension,t,n,this.nextLabel)}status(){this.ensureOpen();let e=this.db.status(),n=this.db.segments().filter(i=>i.segType==="witness");return{totalVectors:e.totalVectors,totalSegments:e.totalSegments,fileSizeBytes:e.fileSize,epoch:e.currentEpoch,witnessValid:n.length>0,witnessEntries:n.length,deadSpaceRatio:typeof e.deadSpaceRatio=="number"?e.deadSpaceRatio:0}}dimension(){return this._dimension}size(){return this.ensureOpen(),this.db.status().totalVectors}compact(){this.ensureOpen();try{let e=this.db.compact();return e&&typeof e=="object"?{segmentsCompacted:typeof e.segmentsCompacted=="number"?e.segmentsCompacted:0,bytesReclaimed:typeof e.bytesReclaimed=="number"?e.bytesReclaimed:0,epoch:typeof e.epoch=="number"?e.epoch:0}:{segmentsCompacted:0,bytesReclaimed:0,epoch:0}}catch{return null}}close(){this._open&&(this.db.close(),this._open=!1)}isOpen(){return this._open}path(){return this._path}embedKernel(e){return this.ensureOpen(),this.db.embedKernel(0,99,0,e,0,"")}extractKernel(){return this.ensureOpen(),this.db.extractKernel()}verifyWitness(){this.ensureOpen();let e=this.tryNative("verifyWitness");return e?{valid:e.valid??!0,totalEntries:e.totalEntries??0,errors:Array.isArray(e.errors)?e.errors:[]}:{valid:!0,totalEntries:0,errors:[]}}sign(e){this.ensureOpen();let t=this.tryNative("sign",e);return typeof t=="string"?t:null}fileId(){this.ensureOpen();let e=this.tryNative("fileId");return typeof e=="string"?e:null}parentId(){this.ensureOpen();let e=this.tryNative("parentId");return typeof e=="string"?e:null}lineageDepth(){this.ensureOpen();let e=this.tryNative("lineageDepth");return typeof e=="number"?e:0}indexStats(){let e=this.status();return{totalVectors:e.totalVectors,dimension:this._dimension,totalSegments:e.totalSegments,fileSizeBytes:e.fileSizeBytes,epoch:e.epoch,witnessValid:e.witnessValid,witnessEntries:e.witnessEntries,idMapSize:this.strToNum.size}}freeze(){this.ensureOpen();let e=this.tryNative("freeze");return typeof e=="number"?e:0}derive(e){this.ensureOpen();let t=c();if(typeof this.db.derive=="function")try{let n=this.db.derive(e),i=new Map(this.strToNum),r=new Map(this.numToStr);return b(e,i,this.nextLabel),new s(n,e,this._dimension,i,r,this.nextLabel)}catch{}return this.fork(e)}ensureOpen(){if(!this._open)throw new Error("RVF database is closed")}tryNative(e,...t){if(typeof this.db[e]!="function")return null;try{return this.db[e](...t)}catch{return null}}persistIdMap(){b(this._path,this.strToNum,this.nextLabel)}}});export{$ as a,G as b,U as c,X as d,Z as e,P as f};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
- import{i as e}from"./chunk-FOHYBR3O.js";function g(t,n,r,a){return{id:e(),type:t,timestamp:new Date,source:n,correlationId:a,payload:r}}var i={TestGenerated:"test-generation.TestGenerated",TestSuiteCreated:"test-generation.TestSuiteCreated",PatternLearned:"test-generation.PatternLearned",GenerationFailed:"test-generation.GenerationFailed"},s={TestRunStarted:"test-execution.TestRunStarted",TestRunCompleted:"test-execution.TestRunCompleted",FlakyTestDetected:"test-execution.FlakyTestDetected",RetryTriggered:"test-execution.RetryTriggered"},o={CoverageReportCreated:"coverage-analysis.CoverageReportCreated",CoverageGapDetected:"coverage-analysis.CoverageGapDetected",RiskZoneIdentified:"coverage-analysis.RiskZoneIdentified"},d={QualityGateEvaluated:"quality-assessment.QualityGateEvaluated",DeploymentApproved:"quality-assessment.DeploymentApproved",DeploymentBlocked:"quality-assessment.DeploymentBlocked"},l={DefectPredicted:"defect-intelligence.DefectPredicted",RootCauseIdentified:"defect-intelligence.RootCauseIdentified",RegressionRiskAnalyzed:"defect-intelligence.RegressionRiskAnalyzed"},c={KnowledgeGraphUpdated:"code-intelligence.KnowledgeGraphUpdated",ImpactAnalysisCompleted:"code-intelligence.ImpactAnalysisCompleted",SemanticSearchCompleted:"code-intelligence.SemanticSearchCompleted",C4DiagramsGenerated:"code-intelligence.C4DiagramsGenerated"},m={VulnerabilityDetected:"security-compliance.VulnerabilityDetected",ComplianceValidated:"security-compliance.ComplianceValidated",SecurityAuditCompleted:"security-compliance.SecurityAuditCompleted"},p={PatternConsolidated:"learning-optimization.PatternConsolidated",TransferCompleted:"learning-optimization.TransferCompleted",OptimizationApplied:"learning-optimization.OptimizationApplied",DreamCycleCompleted:"learning-optimization.dream.completed"},y={...i,...s,...o,...d,...l,...c,...m,...p};export{g as a,i as b,s as c,o as d,d as e,l as f,c as g,m as h,p as i};
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.1");process.exit(0)}
2
+ import{i as e}from"./chunk-LJ63HPPN.js";function g(t,n,r,a){return{id:e(),type:t,timestamp:new Date,source:n,correlationId:a,payload:r}}var i={TestGenerated:"test-generation.TestGenerated",TestSuiteCreated:"test-generation.TestSuiteCreated",PatternLearned:"test-generation.PatternLearned",GenerationFailed:"test-generation.GenerationFailed"},s={TestRunStarted:"test-execution.TestRunStarted",TestRunCompleted:"test-execution.TestRunCompleted",FlakyTestDetected:"test-execution.FlakyTestDetected",RetryTriggered:"test-execution.RetryTriggered"},o={CoverageReportCreated:"coverage-analysis.CoverageReportCreated",CoverageGapDetected:"coverage-analysis.CoverageGapDetected",RiskZoneIdentified:"coverage-analysis.RiskZoneIdentified"},d={QualityGateEvaluated:"quality-assessment.QualityGateEvaluated",DeploymentApproved:"quality-assessment.DeploymentApproved",DeploymentBlocked:"quality-assessment.DeploymentBlocked"},l={DefectPredicted:"defect-intelligence.DefectPredicted",RootCauseIdentified:"defect-intelligence.RootCauseIdentified",RegressionRiskAnalyzed:"defect-intelligence.RegressionRiskAnalyzed"},c={KnowledgeGraphUpdated:"code-intelligence.KnowledgeGraphUpdated",ImpactAnalysisCompleted:"code-intelligence.ImpactAnalysisCompleted",SemanticSearchCompleted:"code-intelligence.SemanticSearchCompleted",C4DiagramsGenerated:"code-intelligence.C4DiagramsGenerated"},m={VulnerabilityDetected:"security-compliance.VulnerabilityDetected",ComplianceValidated:"security-compliance.ComplianceValidated",SecurityAuditCompleted:"security-compliance.SecurityAuditCompleted"},p={PatternConsolidated:"learning-optimization.PatternConsolidated",TransferCompleted:"learning-optimization.TransferCompleted",OptimizationApplied:"learning-optimization.OptimizationApplied",DreamCycleCompleted:"learning-optimization.dream.completed"},y={...i,...s,...o,...d,...l,...c,...m,...p};export{g as a,i as b,s as c,o as d,d as e,l as f,c as g,m as h,p as i};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
- import{c as t}from"./chunk-PEW6FZ47.js";function o(e){try{return e.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.1");process.exit(0)}
2
+ import{c as t}from"./chunk-EHW62JL2.js";function o(e){try{return e.prepare(`
3
3
  SELECT COUNT(*) as count FROM sqlite_master
4
4
  WHERE type='table' AND name IN ('hypergraph_nodes', 'hypergraph_edges')
5
5
  `).get().count===2}catch{return!1}}var r,a,E,n,p=t(()=>{"use strict";r=`
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.1");process.exit(0)}
2
2
  var u="quality-assessment";var o=["coverage","testsPassing","criticalBugs","codeSmells","securityVulnerabilities","technicalDebt","duplications"],d={coverage:{direction:"min",value:80,severity:"high"},testsPassing:{direction:"min",value:95,severity:"critical"},criticalBugs:{direction:"max",value:0,severity:"critical"},codeSmells:{direction:"max",value:20,severity:"medium"},securityVulnerabilities:{direction:"max",value:0,severity:"critical"},technicalDebt:{direction:"max",value:5,severity:"medium"},duplications:{direction:"max",value:5,severity:"low"}};function c(a){return`quality-evidence:${a}:latest`}function l(a,t,e){if(typeof a!="string")throw new Error("Measured quality evidence is malformed: measuredAt is required.");let r=Date.parse(a);if(!Number.isFinite(r))throw new Error("Measured quality evidence is malformed: measuredAt is invalid.");if(r>t+6e4)throw new Error("Measured quality evidence is malformed: measuredAt is in the future.");if(t-r>e)throw new Error("Measured quality evidence is stale. Run the relevant quality analyzers again.");return r}function m(a,t,e,r){if(!a||typeof a!="object")throw new Error(`No measured quality evidence found for ${t}.`);let i=a;if(i.schemaVersion!==1||i.metric!==t||!Number.isFinite(i.value)||i.value<0||typeof i.source!="string"||i.source.trim().length===0)throw new Error(`Measured quality evidence for ${t} is malformed or incomplete.`);l(i.measuredAt,e,r)}async function v(a,t,e){let r=Date.now();if(l(e.measuredAt,r,Number.POSITIVE_INFINITY),e.source.trim().length===0)throw new Error("Quality evidence source is required.");for(let i of o){let n=t[i];if(n===void 0)continue;if(!Number.isFinite(n)||n<0)throw new Error(`Quality evidence value for ${i} must be a non-negative finite number.`);let s={schemaVersion:1,metric:i,value:n,measuredAt:e.measuredAt,source:e.source};await a.set(c(i),s,{namespace:u,persist:!0})}}async function y(a,t={}){let e=t.now??Date.now(),r=t.maxAgeMs??864e5,i={};for(let n of o){let s=await a.get(c(n),{namespace:u});m(s,n,e,r),i[n]=s.value}return i}function E(a){let t=o.map(e=>{let r=d[e],i=a[e];return{name:e,value:i,threshold:r.value,direction:r.direction,severity:r.severity,passed:r.direction==="min"?i>=r.value:i<=r.value}});return{passed:t.every(e=>e.passed),checks:t,recommendations:t.filter(e=>!e.passed).map(e=>`${e.name} failed its measured ${e.direction} threshold.`)}}export{d as a,v as b,y as c,E as d};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.1");process.exit(0)}
2
2
  import r from"chalk";function s(e){switch(e){case"healthy":case"completed":return r.green(e);case"idle":return r.cyan(e);case"degraded":case"running":return r.yellow(e);case"unhealthy":case"failed":return r.red(e);default:return r.gray(e)}}function a(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:e<36e5?`${(e/6e4).toFixed(1)}m`:`${(e/36e5).toFixed(1)}h`}function l(e){let t=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4),o=Math.floor(e%6e4/1e3);return`${t}h ${n}m ${o}s`}export{s as a,a as b,l as c};