agentic-qe 3.15.8 → 3.15.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (479) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +183 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/agents/claim-verifier/claim-verifier-service.js +13 -8
  5. package/dist/bridge/captured-experience-bridge.js +12 -13
  6. package/dist/cli/bundle.js +6 -6
  7. package/dist/cli/chunks/adapter-R2Q4QGXQ.js +2 -0
  8. package/dist/cli/chunks/{agent-booster-wasm-W3V5P7LE.js → agent-booster-wasm-427FRKWG.js} +2 -2
  9. package/dist/cli/chunks/{agent-handler-2NQFHAWE.js → agent-handler-RIYHTHVZ.js} +2 -2
  10. package/dist/cli/chunks/{agent-memory-branch-457ECHHK.js → agent-memory-branch-WSUCUHOO.js} +2 -2
  11. package/dist/cli/chunks/aqe-learning-engine-3RENLQWP.js +2 -0
  12. package/dist/cli/chunks/{arena-JV3WSEHU.js → arena-KRIBMIXX.js} +2 -2
  13. package/dist/cli/chunks/{arena-IYBQ3GPY.js → arena-YAJZX6MC.js} +4 -4
  14. package/dist/cli/chunks/{audit-5OS3T3K6.js → audit-7ZNOXWP3.js} +3 -3
  15. package/dist/cli/chunks/base-67DXSAYM.js +2 -0
  16. package/dist/cli/chunks/{better-sqlite3-IQKBFVAO.js → better-sqlite3-ZQAT4I6H.js} +2 -2
  17. package/dist/cli/chunks/{brain-handler-KA3SGAFM.js → brain-handler-452WCPZC.js} +3 -3
  18. package/dist/cli/chunks/{branch-enumerator-QZDU2VOQ.js → branch-enumerator-IJFXJRPN.js} +2 -2
  19. package/dist/cli/chunks/{browser-ZL7OLKJQ.js → browser-CT3MTV6G.js} +2 -2
  20. package/dist/cli/chunks/browser-workflow-NDXRROWZ.js +2 -0
  21. package/dist/cli/chunks/{chunk-IJSFZO7P.js → chunk-2BA45H64.js} +2 -2
  22. package/dist/cli/chunks/{chunk-6GIC2263.js → chunk-2HL3UM5P.js} +2 -2
  23. package/dist/cli/chunks/{chunk-KVMKYUOE.js → chunk-2I2UPJS7.js} +2 -2
  24. package/dist/cli/chunks/{chunk-22DOS3PM.js → chunk-2TDIS6YK.js} +2 -2
  25. package/dist/cli/chunks/{chunk-5MBNRTT5.js → chunk-2URBI52G.js} +2 -2
  26. package/dist/cli/chunks/{chunk-A6GCO6ZU.js → chunk-2XITOPYV.js} +2 -2
  27. package/dist/cli/chunks/{chunk-I77D65X5.js → chunk-2YH62JCN.js} +2 -2
  28. package/dist/cli/chunks/{chunk-2JCLACCS.js → chunk-32UTLDNY.js} +2 -2
  29. package/dist/cli/chunks/{chunk-UTNKMPTC.js → chunk-37BIGMJI.js} +1 -1
  30. package/dist/cli/chunks/{chunk-767SR7WH.js → chunk-3CJCROMW.js} +2 -2
  31. package/dist/cli/chunks/{chunk-LVHZK7GW.js → chunk-3LYU7BLY.js} +2 -2
  32. package/dist/cli/chunks/{chunk-5DZDLOY6.js → chunk-47TYABPD.js} +3 -3
  33. package/dist/cli/chunks/{chunk-SWY6KGMF.js → chunk-47V7FQGX.js} +2 -2
  34. package/dist/cli/chunks/{chunk-KMZW2P3R.js → chunk-4JCY45KV.js} +2 -2
  35. package/dist/cli/chunks/{chunk-D4IBIMWI.js → chunk-4SUOVLJ6.js} +2 -2
  36. package/dist/cli/chunks/{chunk-J7RCI25Q.js → chunk-4URT6JO2.js} +1 -1
  37. package/dist/cli/chunks/{chunk-SHEVM5PF.js → chunk-4V27J6YN.js} +2 -2
  38. package/dist/cli/chunks/{chunk-JWPYMRIX.js → chunk-4W4DYVSH.js} +1 -1
  39. package/dist/cli/chunks/chunk-55HRSNGN.js +2 -0
  40. package/dist/cli/chunks/{chunk-R2NHGESM.js → chunk-5D2I7JUP.js} +2 -2
  41. package/dist/cli/chunks/{chunk-GGSTLKY5.js → chunk-5JWGCIQW.js} +1 -1
  42. package/dist/cli/chunks/chunk-5LAAZLUC.js +4 -0
  43. package/dist/cli/chunks/{chunk-YNQPHRUZ.js → chunk-5NS3USRW.js} +1 -1
  44. package/dist/cli/chunks/{chunk-4YUBWU3E.js → chunk-6EPHNJTL.js} +1 -1
  45. package/dist/cli/chunks/{chunk-ZBI7PJFX.js → chunk-6OOYIO3W.js} +2 -2
  46. package/dist/cli/chunks/{chunk-ST7ASEJO.js → chunk-6PXA2BQJ.js} +58 -58
  47. package/dist/cli/chunks/{chunk-LPSMVBB3.js → chunk-6YL6JOQB.js} +2 -2
  48. package/dist/cli/chunks/{chunk-DY37YMMQ.js → chunk-72AMFDC7.js} +1 -1
  49. package/dist/cli/chunks/{chunk-OWBFVAEH.js → chunk-763SUL4B.js} +2 -2
  50. package/dist/cli/chunks/{chunk-4GYFONJB.js → chunk-7DMA5NYL.js} +1 -1
  51. package/dist/cli/chunks/{chunk-4GUVVGJX.js → chunk-7JKB3Q7O.js} +1 -1
  52. package/dist/cli/chunks/{chunk-DN3AKAPY.js → chunk-7KII4CQG.js} +2 -2
  53. package/dist/cli/chunks/{chunk-VKFVJCIH.js → chunk-7QGYJ5OY.js} +1 -1
  54. package/dist/cli/chunks/{chunk-HNGNRIZZ.js → chunk-7QTB5VJZ.js} +2 -2
  55. package/dist/cli/chunks/{chunk-GSOK4M6V.js → chunk-7X2Y727E.js} +1 -1
  56. package/dist/cli/chunks/{chunk-PZ7FJ4UG.js → chunk-A4RU67VX.js} +2 -2
  57. package/dist/cli/chunks/{chunk-VWSGWYRB.js → chunk-A6YIH4C4.js} +2 -2
  58. package/dist/cli/chunks/{chunk-4I35ARWW.js → chunk-ABFDB4X3.js} +1 -1
  59. package/dist/cli/chunks/{chunk-NQDYOF35.js → chunk-AJ4YDSOI.js} +2 -2
  60. package/dist/cli/chunks/{chunk-CDLG3Q2O.js → chunk-AOFO4N32.js} +2 -2
  61. package/dist/cli/chunks/{chunk-WAWKAYPY.js → chunk-AQTVVLNP.js} +1 -1
  62. package/dist/cli/chunks/chunk-AR2E4B7K.js +6 -0
  63. package/dist/cli/chunks/{chunk-HXCGV5UJ.js → chunk-AVB5QY2Q.js} +2 -2
  64. package/dist/cli/chunks/{chunk-JFWQFB3S.js → chunk-BHKXMIWX.js} +2 -2
  65. package/dist/cli/chunks/{chunk-BEVWCF3Q.js → chunk-BXO536GT.js} +3 -3
  66. package/dist/cli/chunks/{chunk-IMSRWNWF.js → chunk-C6RTMTEH.js} +1 -1
  67. package/dist/cli/chunks/{chunk-UKKFZJME.js → chunk-CTZJUV5I.js} +1 -1
  68. package/dist/cli/chunks/{chunk-MV4S3TEC.js → chunk-D6XVGFTI.js} +2 -2
  69. package/dist/cli/chunks/{chunk-5YOO5QSE.js → chunk-DDPPSSHW.js} +1 -1
  70. package/dist/cli/chunks/{chunk-NHOMVBCI.js → chunk-DGTLJNJH.js} +2 -2
  71. package/dist/cli/chunks/{chunk-NWFBF3KT.js → chunk-DINZR5CF.js} +1 -1
  72. package/dist/cli/chunks/{chunk-RG42LDOB.js → chunk-EFBLP43U.js} +2 -2
  73. package/dist/cli/chunks/chunk-ETG7O5E5.js +5 -0
  74. package/dist/cli/chunks/{chunk-KNHLOANK.js → chunk-F2SQPP6U.js} +2 -2
  75. package/dist/cli/chunks/{chunk-62T7U25U.js → chunk-F3PQZX44.js} +1 -1
  76. package/dist/cli/chunks/{chunk-X3HM7SV4.js → chunk-F4JYIRW2.js} +2 -2
  77. package/dist/cli/chunks/{chunk-NZATJ2C6.js → chunk-FJ4VTLLK.js} +2 -2
  78. package/dist/cli/chunks/{chunk-TMNEK7TP.js → chunk-FL3OYGCS.js} +2 -2
  79. package/dist/cli/chunks/{chunk-HI6OBDDY.js → chunk-FLASM2XB.js} +2 -2
  80. package/dist/cli/chunks/{chunk-GENNJRNK.js → chunk-FV3NHVC7.js} +22 -22
  81. package/dist/cli/chunks/{chunk-PICEGWGB.js → chunk-FV7VAG74.js} +1 -1
  82. package/dist/cli/chunks/{chunk-PWA6XBW4.js → chunk-G3BKZNFL.js} +5 -5
  83. package/dist/cli/chunks/{chunk-T2TDTBFV.js → chunk-GBUIG3FS.js} +1 -1
  84. package/dist/cli/chunks/{chunk-QFYUZYRA.js → chunk-GCWSX2NY.js} +4 -4
  85. package/dist/cli/chunks/{chunk-KJNUETCB.js → chunk-GII5WVAK.js} +1 -1
  86. package/dist/cli/chunks/{chunk-YVWMJZ6O.js → chunk-GKPQ2GRR.js} +2 -2
  87. package/dist/cli/chunks/chunk-GR3JYE5A.js +2 -0
  88. package/dist/cli/chunks/{chunk-CQ5G64EA.js → chunk-H3KBIWTO.js} +2 -2
  89. package/dist/cli/chunks/{chunk-V4QJ3MMT.js → chunk-HAROIAJE.js} +1 -1
  90. package/dist/cli/chunks/{chunk-OJWEZYLR.js → chunk-HCYQHWI2.js} +2 -2
  91. package/dist/cli/chunks/{chunk-FAYXES7R.js → chunk-HGTWAZWU.js} +2 -2
  92. package/dist/cli/chunks/{chunk-LHRVSK44.js → chunk-HTZJSQ3C.js} +2 -2
  93. package/dist/cli/chunks/{chunk-DAFMHM64.js → chunk-HWK5L7IJ.js} +2 -2
  94. package/dist/cli/chunks/{chunk-K5R3WUJP.js → chunk-HZ5NC6U5.js} +1 -1
  95. package/dist/cli/chunks/{chunk-Y5ZBF7MA.js → chunk-I6S35FRO.js} +2 -2
  96. package/dist/cli/chunks/{chunk-UDCYQLTD.js → chunk-ICP2ORGI.js} +2 -2
  97. package/dist/cli/chunks/{chunk-KMVFBYJO.js → chunk-IFEIY3NQ.js} +2 -2
  98. package/dist/cli/chunks/{chunk-NW7HTOSN.js → chunk-J3DTDJDT.js} +2 -2
  99. package/dist/cli/chunks/chunk-J3WGK22W.js +2 -0
  100. package/dist/cli/chunks/{chunk-5ONJ7AV6.js → chunk-J5KNRVXR.js} +1 -1
  101. package/dist/cli/chunks/{chunk-G77Q22EN.js → chunk-JAV5WPSY.js} +2 -2
  102. package/dist/cli/chunks/{chunk-VVK4ECVJ.js → chunk-JEP4ULR6.js} +2 -2
  103. package/dist/cli/chunks/{chunk-TC52M542.js → chunk-JK2ME6IT.js} +2 -2
  104. package/dist/cli/chunks/chunk-JNNZK7KH.js +2 -0
  105. package/dist/cli/chunks/{chunk-NLYUC63R.js → chunk-JP4P3P3D.js} +2 -2
  106. package/dist/cli/chunks/{chunk-BTMEOZYY.js → chunk-JUVHZG7I.js} +1 -1
  107. package/dist/cli/chunks/{chunk-PUYQ6EKC.js → chunk-JWGRWMZP.js} +2 -2
  108. package/dist/cli/chunks/{chunk-OCLAMZJG.js → chunk-K5DJXMAA.js} +2 -2
  109. package/dist/cli/chunks/{chunk-X7ZQIFES.js → chunk-KFUUIAR4.js} +2 -2
  110. package/dist/cli/chunks/chunk-KHSRIPBP.js +180 -0
  111. package/dist/cli/chunks/{chunk-U3BWBP6B.js → chunk-KIKWJM6J.js} +2 -2
  112. package/dist/cli/chunks/{chunk-MUDBF2JC.js → chunk-KIXYKUCI.js} +1 -1
  113. package/dist/cli/chunks/{chunk-P4UT4LBE.js → chunk-KLGYIEJK.js} +3 -3
  114. package/dist/cli/chunks/{chunk-G6CLO74Q.js → chunk-KR3M44CF.js} +3 -3
  115. package/dist/cli/chunks/chunk-KTSLTZSG.js +2 -0
  116. package/dist/cli/chunks/{chunk-FJAO4UX2.js → chunk-KVBEGOJE.js} +2 -2
  117. package/dist/cli/chunks/{chunk-BLZEOGQE.js → chunk-L42JPFCC.js} +2 -2
  118. package/dist/cli/chunks/{chunk-ZOVAZTXE.js → chunk-LCJTEUDC.js} +370 -370
  119. package/dist/cli/chunks/{chunk-JLTGO5BB.js → chunk-LEAKYZ37.js} +2 -2
  120. package/dist/cli/chunks/{chunk-RSMPJWQH.js → chunk-LMU5DUDK.js} +1 -1
  121. package/dist/cli/chunks/{chunk-FEN2DHFM.js → chunk-MZS32SYS.js} +1 -1
  122. package/dist/cli/chunks/{chunk-J7FLNP5L.js → chunk-N3KEY4XJ.js} +2 -2
  123. package/dist/cli/chunks/{chunk-ZG7UKWBB.js → chunk-N3NP6PTT.js} +2 -2
  124. package/dist/cli/chunks/{chunk-2DPHFCMW.js → chunk-N5PDFGCQ.js} +2 -2
  125. package/dist/cli/chunks/{chunk-BQUIZ5QT.js → chunk-NDKLQW6N.js} +2 -2
  126. package/dist/cli/chunks/{chunk-52YRSWPS.js → chunk-NHZIWIQZ.js} +2 -2
  127. package/dist/cli/chunks/{chunk-ZOHS32SI.js → chunk-NTAD5UX4.js} +2 -2
  128. package/dist/cli/chunks/{chunk-7H3GNRNA.js → chunk-O3JLOVZX.js} +2 -2
  129. package/dist/cli/chunks/{chunk-7XGM7Q2N.js → chunk-OCESWNAZ.js} +3 -3
  130. package/dist/cli/chunks/{chunk-7SLEUVPZ.js → chunk-OG2UI6A3.js} +2 -2
  131. package/dist/cli/chunks/{chunk-4TZLZRZ4.js → chunk-OXTFSIGN.js} +1 -1
  132. package/dist/cli/chunks/{chunk-2QRGIEQV.js → chunk-OXZLKP6C.js} +1 -1
  133. package/dist/cli/chunks/{chunk-FEPFXXI7.js → chunk-P2CXVNKK.js} +2 -2
  134. package/dist/cli/chunks/{chunk-P2EA62YS.js → chunk-P73W2K7T.js} +1 -1
  135. package/dist/cli/chunks/{chunk-V7VZSNDK.js → chunk-PBZI2ZPV.js} +3 -3
  136. package/dist/cli/chunks/{chunk-MMY52Y6R.js → chunk-PMCRCEW5.js} +2 -2
  137. package/dist/cli/chunks/{chunk-FWXNFPLS.js → chunk-PVIA2FPD.js} +2 -2
  138. package/dist/cli/chunks/{chunk-NF63NHJH.js → chunk-PX2B5TS2.js} +2 -2
  139. package/dist/cli/chunks/{chunk-SFPGLUXS.js → chunk-Q3JVJRVJ.js} +1 -1
  140. package/dist/cli/chunks/{chunk-XOOBLZXR.js → chunk-QQ5SZH4D.js} +2 -2
  141. package/dist/cli/chunks/{chunk-KITKQUBX.js → chunk-QTVWUQTB.js} +1 -1
  142. package/dist/cli/chunks/{chunk-2UN4JOTN.js → chunk-REUFWGMA.js} +2 -2
  143. package/dist/cli/chunks/{chunk-CQ3SBRDP.js → chunk-SNBYYO6F.js} +2 -2
  144. package/dist/cli/chunks/{chunk-A2UGPKCS.js → chunk-SVHUYVUR.js} +2 -2
  145. package/dist/cli/chunks/{chunk-PIEKGKW6.js → chunk-THAY7WHO.js} +2 -2
  146. package/dist/cli/chunks/{chunk-WLXGUQOZ.js → chunk-TNMQVG4A.js} +2 -2
  147. package/dist/cli/chunks/{chunk-2GSAAUW3.js → chunk-TSYQDRNK.js} +1 -1
  148. package/dist/cli/chunks/{chunk-7DHSHD5B.js → chunk-TUYJ53V4.js} +2 -2
  149. package/dist/cli/chunks/{chunk-U7CIY3YR.js → chunk-UNUTC6TX.js} +2 -2
  150. package/dist/cli/chunks/{chunk-CRUQ6RXU.js → chunk-UOJBR4J3.js} +2 -2
  151. package/dist/cli/chunks/{chunk-3LFLO2WK.js → chunk-UOWHE77F.js} +2 -2
  152. package/dist/cli/chunks/{chunk-O4RRVTXN.js → chunk-UYLYMWV5.js} +2 -2
  153. package/dist/cli/chunks/{chunk-D4O3TJI7.js → chunk-V5PXQSFS.js} +2 -2
  154. package/dist/cli/chunks/{chunk-VQRBBR27.js → chunk-VCMINU7K.js} +2 -2
  155. package/dist/cli/chunks/{chunk-3N627QRU.js → chunk-VQHVHVSF.js} +2 -2
  156. package/dist/cli/chunks/{chunk-J6LL25QJ.js → chunk-VRGCKBF7.js} +2 -2
  157. package/dist/cli/chunks/{chunk-VWRNG3UK.js → chunk-VU2EL424.js} +1 -1
  158. package/dist/cli/chunks/{chunk-KNQUHGNY.js → chunk-VXZJOKOX.js} +2 -2
  159. package/dist/cli/chunks/{chunk-EUVSSIGR.js → chunk-VYLM2YV5.js} +3 -3
  160. package/dist/cli/chunks/{chunk-PJGQ2TKN.js → chunk-W32YU3VI.js} +2 -2
  161. package/dist/cli/chunks/{chunk-YRH7KMTU.js → chunk-W5VJRDDG.js} +2 -2
  162. package/dist/cli/chunks/{chunk-PPIM7B5G.js → chunk-WGDR2KIR.js} +2 -2
  163. package/dist/cli/chunks/{chunk-2ZRNXEVI.js → chunk-WRRCQ2UE.js} +1 -1
  164. package/dist/cli/chunks/{chunk-7C6FMLQR.js → chunk-XDBD4GXO.js} +2 -2
  165. package/dist/cli/chunks/{chunk-W5A36V3Z.js → chunk-XOLDMK23.js} +2 -2
  166. package/dist/cli/chunks/{chunk-DCYUHCPK.js → chunk-XOVNZT7F.js} +1 -1
  167. package/dist/cli/chunks/{chunk-4C7KE2EL.js → chunk-XQ3DDY7X.js} +2 -2
  168. package/dist/cli/chunks/{chunk-K4N2MBCE.js → chunk-XUIA5KMS.js} +2 -2
  169. package/dist/cli/chunks/{chunk-YUP3APSN.js → chunk-XWIUFYM3.js} +1 -1
  170. package/dist/cli/chunks/{chunk-SJMZZMHP.js → chunk-XYCKHYBM.js} +2 -2
  171. package/dist/cli/chunks/{chunk-4NTLGGXO.js → chunk-XZJ2O3VC.js} +1 -1
  172. package/dist/cli/chunks/{chunk-UQLAN5TX.js → chunk-YRBBBUJX.js} +5 -5
  173. package/dist/cli/chunks/{chunk-XZQVC3GD.js → chunk-YZGSJG34.js} +1 -1
  174. package/dist/cli/chunks/{chunk-7CVMT64N.js → chunk-YZYDTABJ.js} +1 -1
  175. package/dist/cli/chunks/{chunk-4C3RYBTT.js → chunk-ZANDSVCK.js} +2 -2
  176. package/dist/cli/chunks/{chunk-6E7EOHMN.js → chunk-ZBDRLF43.js} +2 -2
  177. package/dist/cli/chunks/{chunk-UTFMMZ57.js → chunk-ZVSLCEVC.js} +3 -3
  178. package/dist/cli/chunks/{chunk-DKFSCJEF.js → chunk-ZXBCCO2H.js} +2 -2
  179. package/dist/cli/chunks/{ci-7NUCRGWO.js → ci-7SGRCFPS.js} +2 -2
  180. package/dist/cli/chunks/{ci-config-VQVECCFI.js → ci-config-MX3URPZA.js} +2 -2
  181. package/dist/cli/chunks/{ci-output-P7GQ6TKF.js → ci-output-M47NJY6D.js} +2 -2
  182. package/dist/cli/chunks/{circuit-breaker-5YP6N6HE.js → circuit-breaker-5GAK45SW.js} +2 -2
  183. package/dist/cli/chunks/{claude-flow-setup-W5H7CMU6.js → claude-flow-setup-YXYSRH4Y.js} +2 -2
  184. package/dist/cli/chunks/client-ZP3CTVRF.js +2 -0
  185. package/dist/cli/chunks/{cline-installer-OYANSZ54.js → cline-installer-DLJ5QD5N.js} +2 -2
  186. package/dist/cli/chunks/{code-OMT4UEZI.js → code-ONKLMVQ2.js} +25 -24
  187. package/dist/cli/chunks/{code-index-extractor-M2JEWKNF.js → code-index-extractor-2232LGZN.js} +2 -2
  188. package/dist/cli/chunks/{codex-installer-YBS6N5O3.js → codex-installer-UOWLYCMH.js} +2 -2
  189. package/dist/cli/chunks/{completions-U7GS5RG6.js → completions-MHX7GCC7.js} +2 -2
  190. package/dist/cli/chunks/{complexity-analyzer-QSXPIUIU.js → complexity-analyzer-43ZUJKZU.js} +2 -2
  191. package/dist/cli/chunks/{continuedev-installer-W5TTT743.js → continuedev-installer-6Q5JR4FF.js} +2 -2
  192. package/dist/cli/chunks/{copilot-installer-KC2RT24C.js → copilot-installer-CZUMVHSI.js} +2 -2
  193. package/dist/cli/chunks/core-handlers-JSRXQWPE.js +2 -0
  194. package/dist/cli/chunks/{cost-tracker-OQPVR6V4.js → cost-tracker-VS5ZW3XN.js} +2 -2
  195. package/dist/cli/chunks/{coverage-TCO2A2NX.js → coverage-VWKTWZ6D.js} +3 -3
  196. package/dist/cli/chunks/cross-domain-router-7UKODQWG.js +2 -0
  197. package/dist/cli/chunks/{cursor-installer-MH7GWD4L.js → cursor-installer-YIFEMORH.js} +2 -2
  198. package/dist/cli/chunks/{daemon-UJEARJZ2.js → daemon-SHWJSJW5.js} +7 -7
  199. package/dist/cli/chunks/daemon-YIFT46FH.js +34 -0
  200. package/dist/cli/chunks/{dag-attention-scheduler-F3SUJU5O.js → dag-attention-scheduler-TCC2WM46.js} +2 -2
  201. package/dist/cli/chunks/{detect-5QTCRB32.js → detect-IGTWSQMA.js} +2 -2
  202. package/dist/cli/chunks/{dist-node-XKZPHDBO.js → dist-node-TCOTJVQX.js} +2 -2
  203. package/dist/cli/chunks/{domain-handler-V3UEADKW.js → domain-handler-55ZVYODR.js} +2 -2
  204. package/dist/cli/chunks/{domain-plugins-7PES4UHZ.js → domain-plugins-GJRWOHQP.js} +2 -2
  205. package/dist/cli/chunks/{domain-transfer-NF7UJW7B.js → domain-transfer-6EF75EKU.js} +2 -2
  206. package/dist/cli/chunks/dream-UDLM6M55.js +2 -0
  207. package/dist/cli/chunks/{embed-and-insert-pattern-D2HWORHF.js → embed-and-insert-pattern-XAMNIKQL.js} +2 -2
  208. package/dist/cli/chunks/{eval-UF2UBAUC.js → eval-GO22R4OZ.js} +2 -2
  209. package/dist/cli/chunks/{experience-capture-middleware-2OUCEHHM.js → experience-capture-middleware-F2BRMJ3Y.js} +3 -3
  210. package/dist/cli/chunks/{fast-paths-KV5DKKHC.js → fast-paths-6RGPYALD.js} +2 -2
  211. package/dist/cli/chunks/{feature-flags-6YWMTNO5.js → feature-flags-MIWQIOHU.js} +2 -2
  212. package/dist/cli/chunks/{feature-flags-MTW6NMR3.js → feature-flags-ZGS3KLPH.js} +2 -2
  213. package/dist/cli/chunks/file-discovery-THWOUQ7Z.js +2 -0
  214. package/dist/cli/chunks/fleet-ADL57COA.js +44 -0
  215. package/dist/cli/chunks/{gnn-wrapper-52V6ANOY.js → gnn-wrapper-ALBJVW6T.js} +2 -2
  216. package/dist/cli/chunks/{heartbeat-handler-X7NHNRC7.js → heartbeat-handler-ZMM53NDY.js} +4 -4
  217. package/dist/cli/chunks/heartbeat-scheduler-HGOC5KH3.js +2 -0
  218. package/dist/cli/chunks/hnsw-adapter-EPSA6AP7.js +2 -0
  219. package/dist/cli/chunks/hnsw-index-RMFOPYGY.js +2 -0
  220. package/dist/cli/chunks/{hnsw-legacy-bridge-DZBE3KMK.js → hnsw-legacy-bridge-RYUJPA7B.js} +2 -2
  221. package/dist/cli/chunks/{hnswlib-node-2AWWUJAZ.js → hnswlib-node-XM6XF3YV.js} +2 -2
  222. package/dist/cli/chunks/{hooks-XLPVROL3.js → hooks-X62O7TJO.js} +10 -10
  223. package/dist/cli/chunks/hybrid-backend-NZ3G4WBX.js +2 -0
  224. package/dist/cli/chunks/{hypergraph-engine-6TI7YP6P.js → hypergraph-engine-ZBWUPTVD.js} +2 -2
  225. package/dist/cli/chunks/{hypergraph-handler-DBIBBOXS.js → hypergraph-handler-DUMF6SJV.js} +3 -3
  226. package/dist/cli/chunks/impact-analyzer-WZC6NHFP.js +2 -0
  227. package/dist/cli/chunks/{init-guard-OSO6MIDD.js → init-guard-S4I2R46S.js} +2 -2
  228. package/dist/cli/chunks/{init-handler-7S7IHMUF.js → init-handler-L4KJHVWS.js} +6 -6
  229. package/dist/cli/chunks/init-wizard-422UZYQ5.js +2 -0
  230. package/dist/cli/chunks/kernel-N7PJ6FCE.js +2 -0
  231. package/dist/cli/chunks/{kilocode-installer-2KBRFXMA.js → kilocode-installer-GNNB5FCZ.js} +2 -2
  232. package/dist/cli/chunks/{kiro-installer-5VFR4OQZ.js → kiro-installer-HR6ZAH7T.js} +2 -2
  233. package/dist/cli/chunks/knowledge-graph-SZCVQF37.js +2 -0
  234. package/dist/cli/chunks/{learning-G5NHL3DV.js → learning-4IEEOHJS.js} +3 -3
  235. package/dist/cli/chunks/{llm-router-4EAPPMHS.js → llm-router-ZFMORP36.js} +4 -4
  236. package/dist/cli/chunks/llm-router-service-4DE5WDUZ.js +2 -0
  237. package/dist/cli/chunks/{load-UYMZPEY6.js → load-ZM43WGDO.js} +2 -2
  238. package/dist/cli/chunks/load-test-POMIF4Q4.js +2 -0
  239. package/dist/cli/chunks/{mcp-NOTDZBW5.js → mcp-CRZKZE37.js} +2 -2
  240. package/dist/cli/chunks/{memory-QL53YIHP.js → memory-W5FZGVAD.js} +5 -5
  241. package/dist/cli/chunks/memory-backend-4P6AHSOY.js +2 -0
  242. package/dist/cli/chunks/memory-handlers-NK6NV3GE.js +2 -0
  243. package/dist/cli/chunks/{multi-model-executor-PDDDXF2B.js → multi-model-executor-SXXGAQ2G.js} +2 -2
  244. package/dist/cli/chunks/{opencode-installer-75D2SKOT.js → opencode-installer-PIRBUAB5.js} +2 -2
  245. package/dist/cli/chunks/{orchestrator-3WIZBV4T.js → orchestrator-H5SQCQTB.js} +11 -10
  246. package/dist/cli/chunks/pattern-null-store-CCHQHGQG.js +2 -0
  247. package/dist/cli/chunks/{pattern-usage-recorder-TEX2JGHA.js → pattern-usage-recorder-XZTWDI2T.js} +2 -2
  248. package/dist/cli/chunks/{pipeline-7ATPA6LU.js → pipeline-5LMLBIJ7.js} +2 -2
  249. package/dist/cli/chunks/{platform-WPSKRJE7.js → platform-KJDABL5C.js} +2 -2
  250. package/dist/cli/chunks/{plugin-UUFOVVMU.js → plugin-V4KSBVVM.js} +2 -2
  251. package/dist/cli/chunks/{prime-radiant-advanced-wasm-PDFSYWKZ.js → prime-radiant-advanced-wasm-JDHTKQAT.js} +2 -2
  252. package/dist/cli/chunks/project-root-X72FSM2F.js +2 -0
  253. package/dist/cli/chunks/protocol-executor-QW6XN6QN.js +2 -0
  254. package/dist/cli/chunks/{protocol-handler-3VRYRIQB.js → protocol-handler-BNRONTQV.js} +2 -2
  255. package/dist/cli/chunks/{prove-2NAUROGF.js → prove-ELLL6XMX.js} +2 -2
  256. package/dist/cli/chunks/qe-reasoning-bank-ZD3WF647.js +2 -0
  257. package/dist/cli/chunks/{quality-ZIEI2WGA.js → quality-NH2QA4D4.js} +2 -2
  258. package/dist/cli/chunks/{quality-gate-KWJO4SWQ.js → quality-gate-JTKLF7GW.js} +3 -3
  259. package/dist/cli/chunks/queen-coordinator-S4U4MKK2.js +2 -0
  260. package/dist/cli/chunks/{real-embeddings-TSZ4UIAE.js → real-embeddings-J3KCKLPB.js} +2 -2
  261. package/dist/cli/chunks/{ref-validation-DWFFRETJ.js → ref-validation-HNXQRP4F.js} +2 -2
  262. package/dist/cli/chunks/{roocode-installer-XTZHLUBO.js → roocode-installer-COJ6CX6S.js} +2 -2
  263. package/dist/cli/chunks/router-CXZKOOTR.js +2 -0
  264. package/dist/cli/chunks/routing-feedback-IYFANYY5.js +2 -0
  265. package/dist/cli/chunks/{routing-handler-GG525TDM.js → routing-handler-WM33ZILE.js} +2 -2
  266. package/dist/cli/chunks/{ruvector-commands-QKRJDM7Z.js → ruvector-commands-BBLXEA7A.js} +2 -2
  267. package/dist/cli/chunks/rvf-dual-writer-HCLQ5WUQ.js +2 -0
  268. package/dist/cli/chunks/rvf-migration-adapter-XCLUWOO3.js +2 -0
  269. package/dist/cli/chunks/{rvf-migration-coordinator-FF52OS6Q.js → rvf-migration-coordinator-P7H6HCAG.js} +2 -2
  270. package/dist/cli/chunks/rvf-native-adapter-MRT5H3IP.js +2 -0
  271. package/dist/cli/chunks/{rvf-store-integrity-M6DXTAZ4.js → rvf-store-integrity-R5SPVRFP.js} +2 -2
  272. package/dist/cli/chunks/safe-db-WFODRGVZ.js +2 -0
  273. package/dist/cli/chunks/schedule-RO55OQXG.js +2 -0
  274. package/dist/cli/chunks/scheduler-XXMJCH24.js +2 -0
  275. package/dist/cli/chunks/{security-EHXSW22U.js → security-AUDTRX3I.js} +3 -3
  276. package/dist/cli/chunks/{shared-rvf-adapter-6EH7UVJL.js → shared-rvf-adapter-PVDGBGI2.js} +2 -2
  277. package/dist/cli/chunks/{shared-rvf-dual-writer-WML274E7.js → shared-rvf-dual-writer-LZ2GMSS2.js} +2 -2
  278. package/dist/cli/chunks/sqlite-persistence-AWRIS4MK.js +2 -0
  279. package/dist/cli/chunks/{standalone-memory-C7QKAXS4.js → standalone-memory-XNOAI4G4.js} +2 -2
  280. package/dist/cli/chunks/{status-handler-VLI7MRLM.js → status-handler-K72XZE4T.js} +2 -2
  281. package/dist/cli/chunks/{structural-health-3LPG6MQN.js → structural-health-NF3YY7U5.js} +2 -2
  282. package/dist/cli/chunks/{sync-4IMMQEPT.js → sync-UVXA6CT2.js} +2 -2
  283. package/dist/cli/chunks/{sync-JFJEJBVK.js → sync-VBD5Y3E2.js} +2 -2
  284. package/dist/cli/chunks/{task-handler-IED3K6E4.js → task-handler-24S3WFVJ.js} +13 -7
  285. package/dist/cli/chunks/task-handlers-GUYW2EPJ.js +9 -0
  286. package/dist/cli/chunks/{test-GPKT3CKZ.js → test-XFSGQELD.js} +4 -4
  287. package/dist/cli/chunks/{test-scheduling-Z42XXZP6.js → test-scheduling-VYUQ4CDE.js} +3 -3
  288. package/dist/cli/chunks/{token-bootstrap-HMM3AHXM.js → token-bootstrap-EDK6FNQ3.js} +2 -2
  289. package/dist/cli/chunks/{token-usage-6Y2ERYIY.js → token-usage-VLQ6WO2L.js} +2 -2
  290. package/dist/cli/chunks/{transformers-MB63T2XO.js → transformers-TOFMWWNM.js} +2 -2
  291. package/dist/cli/chunks/{tree-sitter-wasm-parser-56GDQCMR.js → tree-sitter-wasm-parser-MI3NZKUD.js} +2 -2
  292. package/dist/cli/chunks/{types-J4J6QV3I.js → types-JTWLBAZJ.js} +2 -2
  293. package/dist/cli/chunks/unified-memory-6JWHV6EF.js +2 -0
  294. package/dist/cli/chunks/unified-memory-hnsw-4UANU6NU.js +2 -0
  295. package/dist/cli/chunks/unified-persistence-KGGNA46H.js +2 -0
  296. package/dist/cli/chunks/{upgrade-U4XU7LFM.js → upgrade-4ABM72T4.js} +2 -2
  297. package/dist/cli/chunks/{validate-B57HA4YK.js → validate-UDJCWKXI.js} +2 -2
  298. package/dist/cli/chunks/{validate-swarm-UPPA4M6T.js → validate-swarm-TODOUWNN.js} +2 -2
  299. package/dist/cli/chunks/visual-security-6VZNQLH7.js +2 -0
  300. package/dist/cli/chunks/{web-tree-sitter-GDZMUKOZ.js → web-tree-sitter-WBMAJPM5.js} +2 -2
  301. package/dist/cli/chunks/{windsurf-installer-VJRWCHXP.js → windsurf-installer-BTT53TUL.js} +2 -2
  302. package/dist/cli/chunks/witness-chain-AKKHWEWU.js +2 -0
  303. package/dist/cli/chunks/{witness-chain-LFASSMZK.js → witness-chain-TATPXQRK.js} +2 -2
  304. package/dist/cli/chunks/{witness-chain-repair-TPHN4DXN.js → witness-chain-repair-2HGJGE7O.js} +2 -2
  305. package/dist/cli/chunks/{witness-chain-verifier-Z23FVABW.js → witness-chain-verifier-FRY3LMGH.js} +2 -2
  306. package/dist/cli/chunks/{witness-key-manager-745MJ7WO.js → witness-key-manager-X7QHQQWL.js} +2 -2
  307. package/dist/cli/chunks/{workflow-T245QNQM.js → workflow-QMZPAWQW.js} +4 -4
  308. package/dist/cli/chunks/workflow-orchestrator-4GAW7HNZ.js +2 -0
  309. package/dist/cli/chunks/{wrappers-WCAYIQUX.js → wrappers-ZD5NBHYI.js} +2 -2
  310. package/dist/cli/commands/code.js +8 -0
  311. package/dist/cli/commands/daemon.js +8 -0
  312. package/dist/cli/commands/fleet.js +14 -9
  313. package/dist/cli/handlers/task-handler.js +21 -1
  314. package/dist/coordination/handlers/code-intelligence-handlers.js +14 -2
  315. package/dist/coordination/handlers/coverage-collection.js +9 -10
  316. package/dist/coordination/handlers/coverage-handlers.js +21 -3
  317. package/dist/coordination/handlers/coverage-runner.d.ts +2 -1
  318. package/dist/coordination/handlers/coverage-runner.js +9 -2
  319. package/dist/coordination/handlers/coverage-target.d.ts +13 -3
  320. package/dist/coordination/handlers/coverage-target.js +224 -7
  321. package/dist/coordination/handlers/handler-types.d.ts +2 -0
  322. package/dist/coordination/handlers/test-execution-handlers.js +32 -5
  323. package/dist/coordination/index.d.ts +2 -2
  324. package/dist/coordination/index.js +1 -1
  325. package/dist/coordination/protocols/learning-consolidation-archive.d.ts +39 -0
  326. package/dist/coordination/protocols/learning-consolidation-archive.js +57 -0
  327. package/dist/coordination/protocols/learning-consolidation.d.ts +38 -3
  328. package/dist/coordination/protocols/learning-consolidation.js +128 -50
  329. package/dist/coordination/queen-coordinator.d.ts +12 -1
  330. package/dist/coordination/queen-coordinator.js +24 -1
  331. package/dist/coordination/queen-event-handlers.js +2 -1
  332. package/dist/coordination/queen-lifecycle.js +9 -0
  333. package/dist/coordination/queen-task-management.js +113 -40
  334. package/dist/coordination/queen-types.d.ts +10 -0
  335. package/dist/coordination/queen-types.js +8 -0
  336. package/dist/coordination/task-dag/dag-algorithms.d.ts +33 -0
  337. package/dist/coordination/task-dag/dag-algorithms.js +162 -0
  338. package/dist/coordination/task-dag/dag-obligations.d.ts +21 -0
  339. package/dist/coordination/task-dag/dag-obligations.js +83 -0
  340. package/dist/coordination/task-dag/dag.d.ts +69 -19
  341. package/dist/coordination/task-dag/dag.js +215 -269
  342. package/dist/coordination/task-dag/index.d.ts +12 -4
  343. package/dist/coordination/task-dag/index.js +11 -3
  344. package/dist/coordination/task-dag/prerequisite-ledger.d.ts +84 -0
  345. package/dist/coordination/task-dag/prerequisite-ledger.js +252 -0
  346. package/dist/coordination/task-dag/scheduler.d.ts +19 -9
  347. package/dist/coordination/task-dag/scheduler.js +36 -12
  348. package/dist/coordination/task-dag/types.d.ts +160 -1
  349. package/dist/coordination/task-dag/types.js +2 -1
  350. package/dist/coordination/task-executability.d.ts +18 -0
  351. package/dist/coordination/task-executability.js +31 -0
  352. package/dist/coordination/task-executor.d.ts +1 -0
  353. package/dist/coordination/task-executor.js +5 -0
  354. package/dist/domains/code-intelligence/coordinator.js +35 -9
  355. package/dist/domains/code-intelligence/index-path-guard.d.ts +49 -0
  356. package/dist/domains/code-intelligence/index-path-guard.js +125 -0
  357. package/dist/domains/code-intelligence/interfaces.d.ts +12 -0
  358. package/dist/domains/code-intelligence/services/knowledge-graph.d.ts +6 -0
  359. package/dist/domains/code-intelligence/services/knowledge-graph.js +42 -5
  360. package/dist/domains/contract-testing/coordinator.js +3 -1
  361. package/dist/domains/defect-intelligence/services/defect-predictor.js +4 -2
  362. package/dist/domains/learning-optimization/active-patterns.d.ts +12 -12
  363. package/dist/domains/learning-optimization/active-patterns.js +15 -12
  364. package/dist/domains/learning-optimization/coordinator-helpers.js +2 -3
  365. package/dist/domains/learning-optimization/coordinator.d.ts +0 -3
  366. package/dist/domains/learning-optimization/coordinator.js +43 -102
  367. package/dist/domains/learning-optimization/index.d.ts +1 -1
  368. package/dist/domains/learning-optimization/interfaces.d.ts +56 -4
  369. package/dist/domains/learning-optimization/plugin.js +11 -1
  370. package/dist/domains/learning-optimization/reward-source.d.ts +37 -0
  371. package/dist/domains/learning-optimization/reward-source.js +58 -0
  372. package/dist/domains/learning-optimization/services/learning-coordinator.d.ts +4 -4
  373. package/dist/domains/learning-optimization/services/learning-coordinator.js +59 -23
  374. package/dist/domains/learning-optimization/services/metrics-optimizer.d.ts +14 -4
  375. package/dist/domains/learning-optimization/services/metrics-optimizer.js +129 -63
  376. package/dist/domains/learning-optimization/services/transfer-specialist.js +25 -15
  377. package/dist/domains/test-execution/interfaces.d.ts +16 -0
  378. package/dist/domains/test-execution/services/runner-test-cases.d.ts +21 -0
  379. package/dist/domains/test-execution/services/runner-test-cases.js +69 -0
  380. package/dist/domains/test-execution/services/test-executor.d.ts +5 -0
  381. package/dist/domains/test-execution/services/test-executor.js +24 -2
  382. package/dist/init/fleet-integration.js +2 -0
  383. package/dist/init/init-wizard-steps.js +2 -0
  384. package/dist/init/phases/06-code-intelligence.js +2 -0
  385. package/dist/init/phases/10-workers.js +2 -1
  386. package/dist/kernel/anti-drift-middleware.d.ts +44 -5
  387. package/dist/kernel/anti-drift-middleware.js +147 -11
  388. package/dist/kernel/interfaces.d.ts +5 -0
  389. package/dist/learning/dream/dream-insights-pruner.d.ts +18 -4
  390. package/dist/learning/dream/dream-insights-pruner.js +99 -11
  391. package/dist/learning/skill-validation-learner.d.ts +2 -0
  392. package/dist/learning/skill-validation-learner.js +29 -21
  393. package/dist/mcp/background-workers.js +8 -2
  394. package/dist/mcp/bundle.js +507 -483
  395. package/dist/mcp/handlers/domain-handler-configs.d.ts +14 -0
  396. package/dist/mcp/handlers/domain-handler-configs.js +68 -30
  397. package/dist/mcp/handlers/handler-factory.js +1 -0
  398. package/dist/mcp/handlers/task-handlers.js +37 -1
  399. package/dist/mcp/metrics/metrics-collector.d.ts +11 -9
  400. package/dist/mcp/metrics/metrics-collector.js +13 -26
  401. package/dist/mcp/protocol-server.js +8 -3
  402. package/dist/mcp/tools/learning-optimization/optimize.d.ts +34 -3
  403. package/dist/mcp/tools/learning-optimization/optimize.js +106 -70
  404. package/dist/memory/crdt/lww-register.js +11 -1
  405. package/dist/routing/calibration/ema-calibrator.js +3 -1
  406. package/dist/shared/base-domain-plugin.d.ts +4 -0
  407. package/dist/shared/base-domain-plugin.js +6 -0
  408. package/dist/shared/llm/cache.js +4 -1
  409. package/dist/shared/security/compliance-patterns.js +3 -1
  410. package/dist/shared/test-runner-process.d.ts +26 -0
  411. package/dist/shared/test-runner-process.js +91 -0
  412. package/dist/shared/types/index.d.ts +9 -0
  413. package/dist/shared/types/index.js +13 -0
  414. package/dist/shared/utils/namespaced-search.d.ts +42 -0
  415. package/dist/shared/utils/namespaced-search.js +53 -0
  416. package/dist/strange-loop/infra-healing/infra-action-executor.js +7 -3
  417. package/dist/strange-loop/infra-healing/infra-healing-orchestrator.js +10 -9
  418. package/dist/workers/daemon.d.ts +2 -0
  419. package/dist/workers/daemon.js +10 -5
  420. package/dist/workers/namespaced-keys.d.ts +4 -7
  421. package/dist/workers/namespaced-keys.js +4 -15
  422. package/dist/workers/quality-daemon/ci-monitor.js +9 -5
  423. package/dist/workers/worker-env.d.ts +16 -8
  424. package/dist/workers/worker-env.js +25 -12
  425. package/dist/workers/worker-manager.js +4 -0
  426. package/dist/workers/workers/learning-consolidation.d.ts +1 -1
  427. package/dist/workers/workers/learning-consolidation.js +11 -8
  428. package/package.json +1 -1
  429. package/dist/cli/chunks/adapter-FC4EY447.js +0 -2
  430. package/dist/cli/chunks/aqe-learning-engine-AUAL6UBL.js +0 -2
  431. package/dist/cli/chunks/base-2XML4WH7.js +0 -2
  432. package/dist/cli/chunks/browser-workflow-2IFEUAAK.js +0 -2
  433. package/dist/cli/chunks/chunk-6CKTLVYV.js +0 -2
  434. package/dist/cli/chunks/chunk-I4U7YCXG.js +0 -180
  435. package/dist/cli/chunks/chunk-LZWBUVCK.js +0 -5
  436. package/dist/cli/chunks/chunk-X6VYQVUM.js +0 -2
  437. package/dist/cli/chunks/chunk-YTYS2XSY.js +0 -2
  438. package/dist/cli/chunks/chunk-Z3LDUPLQ.js +0 -6
  439. package/dist/cli/chunks/chunk-ZWMFKZEQ.js +0 -3
  440. package/dist/cli/chunks/client-RFUSQRUZ.js +0 -2
  441. package/dist/cli/chunks/core-handlers-ZC7QB432.js +0 -2
  442. package/dist/cli/chunks/cross-domain-router-GRBK7YFZ.js +0 -2
  443. package/dist/cli/chunks/daemon-JER6HE2J.js +0 -12
  444. package/dist/cli/chunks/dream-VALD726W.js +0 -2
  445. package/dist/cli/chunks/file-discovery-VL73ASNI.js +0 -2
  446. package/dist/cli/chunks/fleet-GJ66QFXK.js +0 -43
  447. package/dist/cli/chunks/heartbeat-scheduler-FSX7A3ZA.js +0 -2
  448. package/dist/cli/chunks/hnsw-adapter-UX2QT6RL.js +0 -2
  449. package/dist/cli/chunks/hnsw-index-WRDDAMXH.js +0 -2
  450. package/dist/cli/chunks/hybrid-backend-O67NGIB5.js +0 -2
  451. package/dist/cli/chunks/impact-analyzer-6VXWWYWM.js +0 -2
  452. package/dist/cli/chunks/init-wizard-VH34J4TL.js +0 -2
  453. package/dist/cli/chunks/kernel-KJD24NO7.js +0 -2
  454. package/dist/cli/chunks/knowledge-graph-343O2HEZ.js +0 -2
  455. package/dist/cli/chunks/llm-router-service-2M4BT2AO.js +0 -2
  456. package/dist/cli/chunks/load-test-OTQ2JQ5F.js +0 -2
  457. package/dist/cli/chunks/memory-backend-4QSNRRV6.js +0 -2
  458. package/dist/cli/chunks/memory-handlers-YFFYRSM6.js +0 -2
  459. package/dist/cli/chunks/pattern-null-store-5USH5MNR.js +0 -2
  460. package/dist/cli/chunks/project-root-SRTA6TBL.js +0 -2
  461. package/dist/cli/chunks/protocol-executor-4WYPCNBS.js +0 -2
  462. package/dist/cli/chunks/qe-reasoning-bank-I4D6SFS4.js +0 -2
  463. package/dist/cli/chunks/queen-coordinator-24UMTZTE.js +0 -2
  464. package/dist/cli/chunks/router-AUD4GATI.js +0 -2
  465. package/dist/cli/chunks/routing-feedback-2FE6SIKQ.js +0 -2
  466. package/dist/cli/chunks/rvf-dual-writer-P5LEUF25.js +0 -2
  467. package/dist/cli/chunks/rvf-migration-adapter-ZCYD5YJS.js +0 -2
  468. package/dist/cli/chunks/rvf-native-adapter-QGV6BW2W.js +0 -2
  469. package/dist/cli/chunks/safe-db-Q6JUKG2A.js +0 -2
  470. package/dist/cli/chunks/schedule-44OSMGE5.js +0 -2
  471. package/dist/cli/chunks/scheduler-V3HO2QQT.js +0 -2
  472. package/dist/cli/chunks/sqlite-persistence-N5T7DWMR.js +0 -2
  473. package/dist/cli/chunks/task-handlers-FH6DNTHW.js +0 -9
  474. package/dist/cli/chunks/unified-memory-RQ3Q4CU3.js +0 -2
  475. package/dist/cli/chunks/unified-memory-hnsw-ZOP5FEYX.js +0 -2
  476. package/dist/cli/chunks/unified-persistence-72OCJJKK.js +0 -2
  477. package/dist/cli/chunks/visual-security-7F5UV23J.js +0 -2
  478. package/dist/cli/chunks/witness-chain-KZ57QUFE.js +0 -2
  479. package/dist/cli/chunks/workflow-orchestrator-ZNWEUYBN.js +0 -2
@@ -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.15.8");process.exit(0)}
2
- import{a as L,b as z,c as K,d as _,e as ie,f as W,g as G,h as A,i as Ce,j as se,k as Q,l as xe,m as J,n as le,o as Ie,p as P,q as Y,r as X,s as Z,t as ee}from"./chunk-PJGQ2TKN.js";import{c as Ee}from"./chunk-MV4S3TEC.js";import{b as ve}from"./chunk-J6LL25QJ.js";import{a as Se,d as ae,e as _e}from"./chunk-4GUVVGJX.js";import"./chunk-7XGM7Q2N.js";import"./chunk-UDCYQLTD.js";import{b as k,d as oe}from"./chunk-FWXNFPLS.js";import"./chunk-7SLEUVPZ.js";import"./chunk-D4O3TJI7.js";import"./chunk-R2NHGESM.js";import"./chunk-RG42LDOB.js";import"./chunk-DN3AKAPY.js";import"./chunk-D4IBIMWI.js";import"./chunk-DKFSCJEF.js";import"./chunk-A2UGPKCS.js";import"./chunk-IJSFZO7P.js";import"./chunk-X6VYQVUM.js";import"./chunk-7H3GNRNA.js";import"./chunk-NHOMVBCI.js";import"./chunk-J7FLNP5L.js";import"./chunk-KVMKYUOE.js";import"./chunk-SHEVM5PF.js";import"./chunk-CQ5G64EA.js";import{a as we,b as Re,c as H,d as V,f as nn}from"./chunk-CQ3SBRDP.js";import{a as F,b as tn}from"./chunk-LPSMVBB3.js";import"./chunk-ZBI7PJFX.js";import"./chunk-K5R3WUJP.js";import $ from"path";import o from"chalk";tn();oe();import{existsSync as te,mkdirSync as rn,writeFileSync as on,readFileSync as ce}from"fs";import{join as D,resolve as de}from"path";function ne(e,n){let r="shake256",t=JSON.stringify(n),a=e.prepare("SELECT * FROM witness_chain ORDER BY id DESC LIMIT 1").get(),i=a?ae(r,_e(a)):Se;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.15.9");process.exit(0)}
2
+ import{a as L,b as z,c as K,d as _,e as ie,f as W,g as G,h as A,i as Ce,j as se,k as Q,l as xe,m as J,n as le,o as Ie,p as P,q as Y,r as X,s as Z,t as ee}from"./chunk-W32YU3VI.js";import{c as Ee}from"./chunk-D6XVGFTI.js";import{b as ve}from"./chunk-VRGCKBF7.js";import{a as Se,d as ae,e as _e}from"./chunk-7JKB3Q7O.js";import"./chunk-OCESWNAZ.js";import"./chunk-ICP2ORGI.js";import{b as k,d as oe}from"./chunk-PVIA2FPD.js";import"./chunk-OG2UI6A3.js";import"./chunk-V5PXQSFS.js";import"./chunk-5D2I7JUP.js";import"./chunk-EFBLP43U.js";import"./chunk-7KII4CQG.js";import"./chunk-4SUOVLJ6.js";import"./chunk-ZXBCCO2H.js";import"./chunk-SVHUYVUR.js";import"./chunk-2BA45H64.js";import"./chunk-KTSLTZSG.js";import"./chunk-O3JLOVZX.js";import"./chunk-DGTLJNJH.js";import"./chunk-N3KEY4XJ.js";import"./chunk-2I2UPJS7.js";import"./chunk-4V27J6YN.js";import"./chunk-H3KBIWTO.js";import{a as we,b as Re,c as H,d as V,f as nn}from"./chunk-SNBYYO6F.js";import{a as F,b as tn}from"./chunk-6YL6JOQB.js";import"./chunk-6OOYIO3W.js";import"./chunk-HZ5NC6U5.js";import $ from"path";import o from"chalk";tn();oe();import{existsSync as te,mkdirSync as rn,writeFileSync as on,readFileSync as ce}from"fs";import{join as D,resolve as de}from"path";function ne(e,n){let r="shake256",t=JSON.stringify(n),a=e.prepare("SELECT * FROM witness_chain ORDER BY id DESC LIMIT 1").get(),i=a?ae(r,_e(a)):Se;e.prepare(`
3
3
  INSERT INTO witness_chain
4
4
  (prev_hash, action_hash, action_type, action_data, timestamp, actor, hash_algo)
5
5
  VALUES (?, ?, 'BRAIN_IMPORT', ?, ?, 'brain-import', ?)
@@ -79,7 +79,7 @@ Examples:
79
79
  aqe brain diff ./brain-a ./brain-b --verbose
80
80
  aqe brain search -i ./brain-export --query oauth --domain test-generation
81
81
  aqe brain search -i ./brain-export --since 2026-03-01 --limit 50 --json
82
- `}};async function ye(e){if(e)return e;let{findProjectRoot:n}=await import("./unified-memory-RQ3Q4CU3.js");return $.join(n(),".agentic-qe","memory.db")}function Ze(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Wn(e){let n=Number.parseInt(e,10);return!Number.isFinite(n)||n<1?20:n}function Jn(e){if(e===void 0)return;let n=Array.isArray(e)?e:[e],r=[];for(let t of n)for(let a of t.split(",")){let i=a.trim();i&&r.push(i)}return r.length>0?r:void 0}function Un(e,n){console.log(o.blue(`
82
+ `}};async function ye(e){if(e)return e;let{findProjectRoot:n}=await import("./unified-memory-6JWHV6EF.js");return $.join(n(),".agentic-qe","memory.db")}function Ze(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Wn(e){let n=Number.parseInt(e,10);return!Number.isFinite(n)||n<1?20:n}function Jn(e){if(e===void 0)return;let n=Array.isArray(e)?e:[e],r=[];for(let t of n)for(let a of t.split(",")){let i=a.trim();i&&r.push(i)}return r.length>0?r:void 0}function Un(e,n){console.log(o.blue(`
83
83
  Brain Diff
84
84
  `)),console.log(` A: ${o.cyan(e.pathA)} (${e.formatA})`),console.log(` B: ${o.cyan(e.pathB)} (${e.formatB})`),console.log(` Versions: ${o.cyan(e.manifestA.version)} \u2192 ${o.cyan(e.manifestB.version)}`+(e.versionMatch?o.gray(" (match)"):o.yellow(" (differ)"))),console.log(` Checksums: ${o.gray(e.manifestA.checksum.slice(0,12))}\u2026 \u2192 ${o.gray(e.manifestB.checksum.slice(0,12))}\u2026`+(e.checksumMatch?o.gray(" (match)"):o.yellow(" (differ)"))),console.log(` Exported: ${o.gray(e.manifestA.exportedAt)} \u2192 ${o.gray(e.manifestB.exportedAt)}`),console.log(` Records: ${o.cyan(e.manifestA.totalRecords)} \u2192 ${o.cyan(e.manifestB.totalRecords)} `+en(e.manifestB.totalRecords-e.manifestA.totalRecords)),(e.domainsOnlyInA.length>0||e.domainsOnlyInB.length>0)&&(console.log(o.blue(`
85
85
  Domains:`)),e.domainsOnlyInA.length>0&&console.log(` Only in A: ${o.yellow(e.domainsOnlyInA.join(", "))}`),e.domainsOnlyInB.length>0&&console.log(` Only in B: ${o.yellow(e.domainsOnlyInB.join(", "))}`)),e.recordLevel||console.log(o.gray(`
@@ -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.15.8");process.exit(0)}
2
- import"./chunk-K5R3WUJP.js";var f=class{language;constructor(e="typescript"){this.language=e}enumerate(e,s){let r=[],n=e.split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.9");process.exit(0)}
2
+ import"./chunk-HZ5NC6U5.js";var f=class{language;constructor(e="typescript"){this.language=e}enumerate(e,s){let r=[],n=e.split(`
3
3
  `),l=!1;for(let i=0;i<n.length;i++){let d=n[i],t=d.trim(),c=i+1,u=d.length-d.trimStart().length+1;if(l){t.includes("*/")&&(l=!1);continue}if(t.startsWith("/*")){l=!t.includes("*/");continue}if(t.startsWith("//"))continue;if(/^\s*if\s*\(/.test(d)&&(this.findMatchingElse(n,i)||r.push({file:s,line:c,column:u,language:this.language,construct:"if-without-else",triggerCondition:"when condition is false",currentHandling:"falls through \u2014 no else branch",suggestedGuard:"Add else branch or document why falsy path is safe",severity:"medium"})),/^\s*switch\s*\(/.test(d)){let a=this.extractBlock(n,i);if(a&&!a.includes("default:")&&!a.includes("default :")&&r.push({file:s,line:c,column:u,language:this.language,construct:"switch-no-default",triggerCondition:"when value matches no case",currentHandling:"falls through \u2014 no default case",suggestedGuard:"Add default case with error handling or exhaustive check",severity:"high"}),a){let g=a.match(/case\s+[^:]+:/g)||[],h=a.match(/\b(break|return|throw|continue)\b/g)||[];g.length>0&&h.length<g.length&&r.push({file:s,line:c,column:u,language:this.language,construct:"switch-missing-break",triggerCondition:"when case falls through to next case",currentHandling:"fall-through \u2014 may execute unintended cases",suggestedGuard:"Add break/return to each case or add explicit // falls through comment",severity:"medium"})}}if(/\bcatch\s*\(/.test(t)||/\bcatch\s*\{/.test(t)){let a=this.extractBlock(n,i);if(a!==null){let g=a.replace(/[{}]/g,"").trim();(g.length===0||/^\s*\/\//.test(g))&&r.push({file:s,line:c,column:u,language:this.language,construct:"try-empty-catch",triggerCondition:"when exception is thrown",currentHandling:"exception silently swallowed",suggestedGuard:"Log the error or rethrow with context",severity:"high"})}}if(/\btry\s*\{/.test(t)&&this.extractBlock(n,i)&&(n.slice(i,Math.min(i+30,n.length)).join(`
4
4
  `).includes("finally")||r.push({file:s,line:c,column:u,language:this.language,construct:"try-no-finally",triggerCondition:"when cleanup is needed regardless of success/failure",currentHandling:"no finally block \u2014 cleanup may be skipped on exception",suggestedGuard:"Add finally block for resource cleanup if applicable",severity:"low"})),t.includes("?.")){let a=t.match(/(\w+(?:\.\w+)*)\?\./g)||[];for(let g of a)if(!t.includes("??")&&!t.includes("|| ")&&!t.includes("if")){r.push({file:s,line:c,column:u,language:this.language,construct:"optional-chaining-null-path",triggerCondition:`when ${g.replace("?.","")} is null/undefined`,currentHandling:"returns undefined \u2014 may propagate",suggestedGuard:"Add ?? fallback or explicit null check",severity:"low"});break}}if(t.includes("??")&&!t.includes("?.")&&r.push({file:s,line:c,column:u,language:this.language,construct:"nullish-coalescing-fallback",triggerCondition:"when left side is null/undefined",currentHandling:"uses fallback value",suggestedGuard:"Verify fallback value is appropriate for all null cases",severity:"low"}),/\.\s*then\s*\(/.test(t)&&!t.includes(".catch")&&!t.includes("await")){let a=n.slice(i,Math.min(i+5,n.length)).join(" ");!a.includes(".catch")&&!a.includes("try")&&r.push({file:s,line:c,column:u,language:this.language,construct:"promise-no-catch",triggerCondition:"when promise rejects",currentHandling:"unhandled rejection \u2014 may crash process",suggestedGuard:"Add .catch() handler or use try/catch with await",severity:"high"})}let p=["map","filter","reduce","forEach","find","some","every","flatMap"];for(let a of p)if(new RegExp(`\\.${a}\\s*\\(`).test(t)){let h=n.slice(Math.max(0,i-3),i).join(" ");if(!h.includes(".length")&&!h.includes("if (")&&!h.includes("?.")){r.push({file:s,line:c,column:u,language:this.language,construct:"array-callback-empty",triggerCondition:`when array is empty before .${a}()`,currentHandling:a==="reduce"?"may throw without initial value":"returns empty result \u2014 may cause downstream issues",suggestedGuard:a==="reduce"?"Provide initial value or check array length":"Check array length or handle empty result",severity:a==="reduce"?"high":"low"});break}}/\|\|\s*['"`\d]/.test(t)&&!t.includes("??")&&r.push({file:s,line:c,column:u,language:this.language,construct:"logical-or-falsy",triggerCondition:'when left side is falsy (0, "", false, null, undefined)',currentHandling:'uses fallback \u2014 may unintentionally override 0, "", or false',suggestedGuard:"Use ?? instead of || if only null/undefined should trigger fallback",severity:"medium"}),/&&\s*\w+\s*\(/.test(t)&&!t.includes("if")&&!t.includes("while")&&r.push({file:s,line:c,column:u,language:this.language,construct:"logical-and-short-circuit",triggerCondition:"when left side is falsy \u2014 right side never executes",currentHandling:"short-circuits \u2014 function call skipped silently",suggestedGuard:"Use explicit if-statement for clarity when side effects matter",severity:"low"}),(t.match(/\?/g)||[]).length>=2&&t.includes(":")&&r.push({file:s,line:c,column:u,language:this.language,construct:"ternary-complex",triggerCondition:"when nested ternary conditions interact",currentHandling:"nested ternary \u2014 hard to read and maintain",suggestedGuard:"Refactor to if/else or switch for readability",severity:"medium"}),(/\btypeof\s+\w+\s*===?\s*['"]/.test(t)||/\binstanceof\b/.test(t))&&!t.includes("else")&&!this.findMatchingElse(n,i)&&r.push({file:s,line:c,column:u,language:this.language,construct:"type-guard-unhandled",triggerCondition:"when value does not match the guarded type",currentHandling:"unguarded type path \u2014 may cause runtime type errors",suggestedGuard:"Add else branch or exhaustive type checking",severity:"medium"})}return r}findMatchingElse(e,s){let r={depth:0};for(let n=s;n<Math.min(s+30,e.length);n++){let l=e[n];for(let i of l)i==="{"&&r.depth++,i==="}"&&r.depth--;if(r.depth===0&&n>s){if((e[n+1]?.trim()||"").startsWith("else")||e[n].trim().endsWith("else")||e[n].trim().endsWith("else {")||e[n].includes("} else"))return!0;break}}return!1}extractBlock(e,s){let r=0,n=!1,l=[];for(let i=s;i<Math.min(s+50,e.length);i++){let d=e[i];for(let t of d)t==="{"&&(r++,n=!0),t==="}"&&r--;if(n&&(l.push(d),r===0))return l.join(`
5
5
  `)}return null}};function y(o,e,s){let r=Date.now(),n=s||(e.endsWith(".ts")||e.endsWith(".tsx")?"typescript":"javascript"),i=new f(n).enumerate(o,e);return{file:e,language:n,branches:i,totalConstructs:i.length,unhandledCount:i.length,duration:Date.now()-r}}function b(o){let e=[];if(e.push(`# Branch Enumeration Report: ${o.file}`),e.push(""),e.push(`**Language**: ${o.language} | **Branches**: ${o.unhandledCount} | **Duration**: ${o.duration}ms`),e.push(""),o.branches.length===0)return e.push("No unhandled branches detected."),e.join(`
@@ -1,4 +1,4 @@
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.15.8");process.exit(0)}
2
- import{a as p}from"./chunk-2GSAAUW3.js";import"./chunk-K5R3WUJP.js";import{readFile as m,readdir as k}from"fs/promises";import{join as c,basename as y,dirname as W}from"path";import{fileURLToPath as v}from"url";import{parse as d}from"yaml";var b=v(import.meta.url),E=W(b),l=class{templatesDir;cache=new Map;constructor(r){this.templatesDir=r||c(E,"templates")}async load(r){if(this.cache.has(r))return this.cache.get(r);try{let e=c(this.templatesDir,`${r}.yaml`),n=await m(e,"utf-8"),o=d(n),i=await this.validate(o);if(!i.valid)throw new Error(`Invalid workflow template ${r}:
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.15.9");process.exit(0)}
2
+ import{a as p}from"./chunk-TSYQDRNK.js";import"./chunk-HZ5NC6U5.js";import{readFile as m,readdir as k}from"fs/promises";import{join as c,basename as y,dirname as W}from"path";import{fileURLToPath as v}from"url";import{parse as d}from"yaml";var b=v(import.meta.url),E=W(b),l=class{templatesDir;cache=new Map;constructor(r){this.templatesDir=r||c(E,"templates")}async load(r){if(this.cache.has(r))return this.cache.get(r);try{let e=c(this.templatesDir,`${r}.yaml`),n=await m(e,"utf-8"),o=d(n),i=await this.validate(o);if(!i.valid)throw new Error(`Invalid workflow template ${r}:
3
3
  ${i.errors.join(`
4
4
  `)}`);return this.cache.set(r,o),o}catch(e){throw e.code==="ENOENT"?new Error(`Workflow template not found: ${r}`):e}}async list(){try{return(await k(this.templatesDir)).filter(e=>e.endsWith(".yaml")||e.endsWith(".yml")).map(e=>y(e,e.endsWith(".yaml")?".yaml":".yml")).sort()}catch(r){if(r.code==="ENOENT")return[];throw r}}async validate(r){let e=[],n=[];if(r.name||e.push("Workflow must have a name"),r.version||e.push("Workflow must have a version"),r.description||n.push("Workflow should have a description"),Array.isArray(r.variables)?r.variables.forEach((o,i)=>{o.name||e.push(`Variable at index ${i} must have a name`),o.type||e.push(`Variable ${o.name} must have a type`),o.required===void 0&&n.push(`Variable ${o.name} should specify if it's required`)}):e.push("Workflow must have a variables array"),!Array.isArray(r.steps))e.push("Workflow must have a steps array");else if(r.steps.length===0)e.push("Workflow must have at least one step");else{r.steps.forEach((t,s)=>{t.name||e.push(`Step at index ${s} must have a name`),t.action||e.push(`Step ${t.name||s} must have an action`),(!t.config||typeof t.config!="object")&&e.push(`Step ${t.name||s} must have a config object`),t.assertions&&Array.isArray(t.assertions)&&t.assertions.forEach((f,u)=>{f.condition||e.push(`Assertion ${u} in step ${t.name||s} must have a condition`),f.message||n.push(`Assertion ${u} in step ${t.name||s} should have a message`)})});let o=r.steps.map(t=>t.name),i=o.filter((t,s)=>o.indexOf(t)!==s);i.length>0&&e.push(`Duplicate step names found: ${i.join(", ")}`)}return{valid:e.length===0,errors:e,warnings:n}}async createContext(r,e){let n=await this.load(r),o=n.variables.filter(t=>t.required&&!(t.name in e)).map(t=>t.name);if(o.length>0)throw new Error(`Missing required variables: ${o.join(", ")}`);let i={};return n.variables.forEach(t=>{t.name in e?i[t.name]=e[t.name]:"default"in t&&(i[t.name]=t.default)}),{variables:i,results:new Map,metadata:{startTime:Date.now(),workflow:n.name,templateName:r}}}async getMetadata(r){try{let e=c(this.templatesDir,`${r}.yaml`),n=await m(e,"utf-8"),o=d(n);return{name:o.name,version:o.version,description:o.description}}catch(e){throw e.code==="ENOENT"?new Error(`Workflow template not found: ${r}`):e}}clearCache(){this.cache.clear()}async reload(r){return this.cache.delete(r),this.load(r)}},x=new l;function w(a,r){return a.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=n.trim().split("."),t=r;for(let s of i)if(t&&typeof t=="object"&&s in t)t=t[s];else return e;return t!=null?String(t):e})}function T(a,r){let e={...r.variables,result:r.results.get("__last_result__")},n=w(a,e);return p(n,e,!1)}var g=["login-flow","oauth-flow","scraping-workflow","visual-regression","form-validation","navigation-flow","api-integration","performance-audit","accessibility-audit"],A={"login-flow":"Authentication testing workflow for login forms with credential validation","oauth-flow":"OAuth2/OIDC authentication testing workflow with provider integration","scraping-workflow":"Data extraction workflow for web scraping with pagination and structured output","visual-regression":"Screenshot comparison workflow for visual regression testing across breakpoints","form-validation":"Input validation testing workflow for form fields with error handling","navigation-flow":"Multi-page navigation workflow for testing user journeys and state persistence","api-integration":"Browser-API hybrid testing workflow for validating frontend-backend integration","performance-audit":"Lighthouse-style performance audit workflow with Core Web Vitals","accessibility-audit":"WCAG 2.1 Level AA compliance audit workflow with automated accessibility testing"},h={authentication:["login-flow","oauth-flow"],testing:["form-validation","navigation-flow","api-integration"],quality:["visual-regression","performance-audit","accessibility-audit"],automation:["scraping-workflow"]};function _(a){return h[a]}function P(a){return g.includes(a)}function L(){return g.map(a=>{let r=Object.entries(h).find(([e,n])=>n.includes(a))?.[0]||"other";return{name:a,description:A[a],category:r}})}export{h as WORKFLOW_CATEGORIES,A as WORKFLOW_DESCRIPTIONS,g as WORKFLOW_TEMPLATES,l as WorkflowLoader,x as defaultWorkflowLoader,T as evaluateCondition,L as getAllWorkflowTemplates,_ as getWorkflowsByCategory,w as interpolateVariables,P as isValidWorkflowTemplate};
@@ -0,0 +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.15.9");process.exit(0)}
2
+ import{a}from"./chunk-763SUL4B.js";import"./chunk-JK2ME6IT.js";import"./chunk-IFEIY3NQ.js";import"./chunk-3CJCROMW.js";import"./chunk-OCESWNAZ.js";import"./chunk-ICP2ORGI.js";import"./chunk-PVIA2FPD.js";import"./chunk-OG2UI6A3.js";import"./chunk-V5PXQSFS.js";import"./chunk-5D2I7JUP.js";import"./chunk-EFBLP43U.js";import"./chunk-7KII4CQG.js";import"./chunk-4SUOVLJ6.js";import"./chunk-ZXBCCO2H.js";import"./chunk-SVHUYVUR.js";import"./chunk-FV7VAG74.js";import"./chunk-2BA45H64.js";import"./chunk-KTSLTZSG.js";import"./chunk-O3JLOVZX.js";import"./chunk-DGTLJNJH.js";import"./chunk-N3KEY4XJ.js";import"./chunk-2I2UPJS7.js";import"./chunk-4V27J6YN.js";import"./chunk-H3KBIWTO.js";import"./chunk-6YL6JOQB.js";import"./chunk-6OOYIO3W.js";import"./chunk-HZ5NC6U5.js";export{a as BrowserWorkflowTool};
@@ -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.15.8");process.exit(0)}
2
- import{b as t}from"./chunk-K5R3WUJP.js";function r(){let e=globalThis;return e[n]??=[]}function a(e){return r().push(e),()=>{let o=r(),s=o.indexOf(e);s>=0&&o.splice(s,1)}}function f(){for(let e of[...r()].reverse())try{e()}catch{}}function i(){return globalThis[c]}function u(e){let o=i();if(!o)return!1;try{return o.shutdown(e),!0}catch{return!1}}var c,n,l=t(()=>{"use strict";c=Symbol.for("agentic-qe.process-lifecycle-owner"),n=Symbol.for("agentic-qe.process-lifecycle-store-closers")});export{a,f as b,u as c,l as d};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.9");process.exit(0)}
2
+ import{b as t}from"./chunk-HZ5NC6U5.js";function r(){let e=globalThis;return e[n]??=[]}function a(e){return r().push(e),()=>{let o=r(),s=o.indexOf(e);s>=0&&o.splice(s,1)}}function f(){for(let e of[...r()].reverse())try{e()}catch{}}function i(){return globalThis[c]}function u(e){let o=i();if(!o)return!1;try{return o.shutdown(e),!0}catch{return!1}}var c,n,l=t(()=>{"use strict";c=Symbol.for("agentic-qe.process-lifecycle-owner"),n=Symbol.for("agentic-qe.process-lifecycle-store-closers")});export{a,f as b,u as c,l 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.15.8");process.exit(0)}
2
- import{l as d}from"./chunk-TC52M542.js";import{a as u,e as g}from"./chunk-J7FLNP5L.js";g();var m=[{type:"email",pattern:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,mask:n=>n[0]+"***@"+n.split("@")[1]},{type:"ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g,mask:()=>"***-**-****"},{type:"credit-card",pattern:/\b(?:\d[ -]*?){13,19}\b/g,mask:n=>"****-****-****-"+n.replace(/\D/g,"").slice(-4)},{type:"phone",pattern:/\b(?:\+?1[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}\b/g,mask:n=>n.slice(0,3)+"***"+n.slice(-2)},{type:"api-key",pattern:/(?:key|token|api_key|apikey|secret|password|passwd|auth)=([A-Za-z0-9_\-]{16,})/gi,mask:()=>"***REDACTED***"}],y=class extends d{config={name:"qe/security/url-validate",description:"Validate URL security: checks for XSS/injection patterns, unsafe protocols, and scans URL query parameters for PII exposure (emails, SSNs, credit cards, API keys).",domain:"security-compliance",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{url:{type:"string",description:"URL to validate for security threats and PII exposure"},enablePII:{type:"boolean",description:"Enable PII exposure scanning in URL and query parameters",default:!0}},required:["url"]}}async execute(s,r){try{let e=this.validateURLSecurity(s.url),t=s.enablePII!==!1?this.scanForPII(s.url):{scanned:!1,found:!1,types:[],details:[]},c=e.issues.length+(t.found?t.types.length:0)===0?`URL passed all checks (security: clean, PII: ${t.scanned?"none found":"not scanned"})`:`URL has ${e.issues.length} security issue(s)${t.found?` and ${t.types.length} PII type(s) exposed in URL`:""}`;return{success:!0,data:{url:s.url,urlSecurity:e,piiExposure:t,summary:c}}}catch(e){return{success:!1,error:u(e)}}}validateURLSecurity(s){let r=[],e="none";try{let t=new URL(s);["http:","https:"].includes(t.protocol)||(r.push({type:"unsafe-protocol",description:`Protocol ${t.protocol} is not allowed`,severity:"high"}),e="high");let o=[/<script/i,/javascript:/i,/on\w+=/i,/data:text\/html/i];for(let i of o)if(i.test(s)){r.push({type:"xss",description:"Potential XSS pattern detected in URL",severity:"critical"}),e="critical";break}let c=[/'.*or.*'/i,/union.*select/i,/drop.*table/i,/;\s*--/i];for(let i of c)if(i.test(s)){r.push({type:"sql-injection",description:"Potential SQL injection pattern detected in URL",severity:"critical"}),e="critical";break}/\.\.[/\\]/.test(s)&&(r.push({type:"path-traversal",description:"Potential path traversal pattern (../) detected",severity:"high"}),e!=="critical"&&(e="high"));let a=["redirect","url","next","return","returnUrl","goto"];for(let i of a){let l=t.searchParams.get(i);l&&/^https?:\/\//.test(l)&&(r.push({type:"open-redirect",description:`Query parameter "${i}" contains an external URL \u2014 potential open redirect`,severity:"medium"}),e==="none"&&(e="medium"))}}catch{r.push({type:"invalid-url",description:"URL could not be parsed",severity:"critical"}),e="critical"}return{valid:r.length===0,riskLevel:e,issues:r}}scanForPII(s){let r=[],e=new Set,t;try{t=decodeURIComponent(s)}catch{t=s}let o="",c="";try{let a=new URL(t);o=a.search,c=a.pathname}catch{o=t}for(let{type:a,pattern:i,mask:l}of m){i.lastIndex=0;let p;for(;(p=i.exec(t))!==null;){e.add(a);let h=o.includes(p[0])?"query-parameter":c.includes(p[0])?"path":"url";r.push({type:a,location:h,masked:l(p[0])})}}return{scanned:!0,found:e.size>0,types:Array.from(e),details:r}}};export{y as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.9");process.exit(0)}
2
+ import{l as d}from"./chunk-JK2ME6IT.js";import{a as u,e as g}from"./chunk-N3KEY4XJ.js";g();var m=[{type:"email",pattern:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,mask:n=>n[0]+"***@"+n.split("@")[1]},{type:"ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g,mask:()=>"***-**-****"},{type:"credit-card",pattern:/\b(?:\d[ -]*?){13,19}\b/g,mask:n=>"****-****-****-"+n.replace(/\D/g,"").slice(-4)},{type:"phone",pattern:/\b(?:\+?1[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}\b/g,mask:n=>n.slice(0,3)+"***"+n.slice(-2)},{type:"api-key",pattern:/(?:key|token|api_key|apikey|secret|password|passwd|auth)=([A-Za-z0-9_\-]{16,})/gi,mask:()=>"***REDACTED***"}],y=class extends d{config={name:"qe/security/url-validate",description:"Validate URL security: checks for XSS/injection patterns, unsafe protocols, and scans URL query parameters for PII exposure (emails, SSNs, credit cards, API keys).",domain:"security-compliance",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{url:{type:"string",description:"URL to validate for security threats and PII exposure"},enablePII:{type:"boolean",description:"Enable PII exposure scanning in URL and query parameters",default:!0}},required:["url"]}}async execute(s,r){try{let e=this.validateURLSecurity(s.url),t=s.enablePII!==!1?this.scanForPII(s.url):{scanned:!1,found:!1,types:[],details:[]},c=e.issues.length+(t.found?t.types.length:0)===0?`URL passed all checks (security: clean, PII: ${t.scanned?"none found":"not scanned"})`:`URL has ${e.issues.length} security issue(s)${t.found?` and ${t.types.length} PII type(s) exposed in URL`:""}`;return{success:!0,data:{url:s.url,urlSecurity:e,piiExposure:t,summary:c}}}catch(e){return{success:!1,error:u(e)}}}validateURLSecurity(s){let r=[],e="none";try{let t=new URL(s);["http:","https:"].includes(t.protocol)||(r.push({type:"unsafe-protocol",description:`Protocol ${t.protocol} is not allowed`,severity:"high"}),e="high");let o=[/<script/i,/javascript:/i,/on\w+=/i,/data:text\/html/i];for(let i of o)if(i.test(s)){r.push({type:"xss",description:"Potential XSS pattern detected in URL",severity:"critical"}),e="critical";break}let c=[/'.*or.*'/i,/union.*select/i,/drop.*table/i,/;\s*--/i];for(let i of c)if(i.test(s)){r.push({type:"sql-injection",description:"Potential SQL injection pattern detected in URL",severity:"critical"}),e="critical";break}/\.\.[/\\]/.test(s)&&(r.push({type:"path-traversal",description:"Potential path traversal pattern (../) detected",severity:"high"}),e!=="critical"&&(e="high"));let a=["redirect","url","next","return","returnUrl","goto"];for(let i of a){let l=t.searchParams.get(i);l&&/^https?:\/\//.test(l)&&(r.push({type:"open-redirect",description:`Query parameter "${i}" contains an external URL \u2014 potential open redirect`,severity:"medium"}),e==="none"&&(e="medium"))}}catch{r.push({type:"invalid-url",description:"URL could not be parsed",severity:"critical"}),e="critical"}return{valid:r.length===0,riskLevel:e,issues:r}}scanForPII(s){let r=[],e=new Set,t;try{t=decodeURIComponent(s)}catch{t=s}let o="",c="";try{let a=new URL(t);o=a.search,c=a.pathname}catch{o=t}for(let{type:a,pattern:i,mask:l}of m){i.lastIndex=0;let p;for(;(p=i.exec(t))!==null;){e.add(a);let h=o.includes(p[0])?"query-parameter":c.includes(p[0])?"path":"url";r.push({type:a,location:h,masked:l(p[0])})}}return{scanned:!0,found:e.size>0,types:Array.from(e),details:r}}};export{y as a};
@@ -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.15.8");process.exit(0)}
2
- import{b as s,d as t}from"./chunk-K5R3WUJP.js";var K={};t(K,{DEFAULT_FEATURE_FLAGS:()=>r,getRuVectorFeatureFlags:()=>u,getRvfMigrationStage:()=>H,initFeatureFlagsFromEnv:()=>z,isAgentMemoryBranchingEnabled:()=>I,isCNNVisualRegressionEnabled:()=>b,isCognitiveRoutingEnabled:()=>Y,isCoherenceActionGateEnabled:()=>A,isCoherenceGateEnabled:()=>f,isColdTierGNNEnabled:()=>P,isCrossDomainTransferEnabled:()=>N,isCusumDriftDetectionEnabled:()=>F,isDAGAttentionEnabled:()=>g,isDeltaEventSourcingEnabled:()=>M,isDeterministicDitherEnabled:()=>T,isEpropOnlineLearningEnabled:()=>Q,isEwcPlusPlusEnabled:()=>L,isFlashAttentionEnabled:()=>E,isGNNIndexEnabled:()=>R,isGrangerCausalityEnabled:()=>B,isGraphMAEEnabled:()=>x,isHDCFingerprintingEnabled:()=>D,isHnswHealthMonitorEnabled:()=>U,isHopfieldMemoryEnabled:()=>h,isHyperbolicHnswEnabled:()=>k,isMetaLearningEnabled:()=>m,isMetadataFilteringEnabled:()=>S,isNativeHNSWEnabled:()=>_,isNeuralRoutingEnabled:()=>C,isRVFPatternStoreEnabled:()=>V,isReasoningQECEnabled:()=>v,isRegretTrackingEnabled:()=>O,isReservoirReplayEnabled:()=>w,isSONAEnabled:()=>a,isSONAThreeLoopEnabled:()=>p,isSpectralSparsificationEnabled:()=>W,isSublinearSolverEnabled:()=>y,isTemporalCompressionEnabled:()=>c,isUnifiedHnswEnabled:()=>G,isWitnessChainEnabled:()=>d,resetRuVectorFeatureFlags:()=>i,setRuVectorFeatureFlags:()=>o,shouldLogMigrationMetrics:()=>l});function u(){return{...e}}function o(n){e={...e,...n}}function i(){e={...r}}function a(){return e.useQESONA}function E(){return e.useQEFlashAttention}function R(){return e.useQEGNNIndex}function l(){return e.logMigrationMetrics}function _(){return e.useNativeHNSW}function c(){return e.useTemporalCompression}function S(){return e.useMetadataFiltering}function T(){return e.useDeterministicDither}function C(){return e.useNeuralRouting}function p(){return e.useSONAThreeLoop}function N(){return e.useCrossDomainTransfer}function U(){return e.useHnswHealthMonitor}function O(){return e.useRegretTracking}function f(){return e.useCoherenceGate}function d(){return e.useWitnessChain}function b(){return e.useCNNVisualRegression}function g(){return e.useDAGAttention}function A(){return e.useCoherenceActionGate}function v(){return e.useReasoningQEC}function V(){return e.useRVFPatternStore}function I(){return e.useAgentMemoryBranching}function G(){return e.useUnifiedHnsw}function H(){return e.rvfMigrationStage}function D(){return e.useHDCFingerprinting}function F(){return e.useCusumDriftDetection}function M(){return e.useDeltaEventSourcing}function L(){return e.useEwcPlusPlusRegularization}function x(){return e.useGraphMAEEmbeddings}function h(){return e.useHopfieldMemory}function P(){return e.useColdTierGNN}function m(){return e.useMetaLearningEnhancements}function y(){return e.useSublinearSolver}function W(){return e.useSpectralSparsification}function w(){return e.useReservoirReplay}function Q(){return e.useEpropOnlineLearning}function B(){return e.useGrangerCausality}function Y(){return e.useCognitiveRouting}function k(){return e.useHyperbolicHnsw}function z(){let n={};process.env.RUVECTOR_USE_RVF_PATTERN_STORE!==void 0&&(n.useRVFPatternStore=process.env.RUVECTOR_USE_RVF_PATTERN_STORE==="true"),process.env.RUVECTOR_USE_SONA!==void 0&&(n.useQESONA=process.env.RUVECTOR_USE_SONA==="true"),process.env.RUVECTOR_USE_FLASH_ATTENTION!==void 0&&(n.useQEFlashAttention=process.env.RUVECTOR_USE_FLASH_ATTENTION==="true"),process.env.RUVECTOR_USE_GNN_INDEX!==void 0&&(n.useQEGNNIndex=process.env.RUVECTOR_USE_GNN_INDEX==="true"),process.env.RUVECTOR_LOG_MIGRATION_METRICS!==void 0&&(n.logMigrationMetrics=process.env.RUVECTOR_LOG_MIGRATION_METRICS==="true"),process.env.RUVECTOR_USE_NATIVE_HNSW!==void 0&&(n.useNativeHNSW=process.env.RUVECTOR_USE_NATIVE_HNSW==="true"),process.env.RUVECTOR_USE_TEMPORAL_COMPRESSION!==void 0&&(n.useTemporalCompression=process.env.RUVECTOR_USE_TEMPORAL_COMPRESSION==="true"),process.env.RUVECTOR_USE_METADATA_FILTERING!==void 0&&(n.useMetadataFiltering=process.env.RUVECTOR_USE_METADATA_FILTERING==="true"),process.env.RUVECTOR_USE_DETERMINISTIC_DITHER!==void 0&&(n.useDeterministicDither=process.env.RUVECTOR_USE_DETERMINISTIC_DITHER==="true"),process.env.RUVECTOR_USE_NEURAL_ROUTING!==void 0&&(n.useNeuralRouting=process.env.RUVECTOR_USE_NEURAL_ROUTING==="true"),process.env.RUVECTOR_USE_SONA_THREE_LOOP!==void 0&&(n.useSONAThreeLoop=process.env.RUVECTOR_USE_SONA_THREE_LOOP==="true"),process.env.RUVECTOR_USE_CROSS_DOMAIN_TRANSFER!==void 0&&(n.useCrossDomainTransfer=process.env.RUVECTOR_USE_CROSS_DOMAIN_TRANSFER==="true"),process.env.RUVECTOR_USE_HNSW_HEALTH_MONITOR!==void 0&&(n.useHnswHealthMonitor=process.env.RUVECTOR_USE_HNSW_HEALTH_MONITOR==="true"),process.env.RUVECTOR_USE_REGRET_TRACKING!==void 0&&(n.useRegretTracking=process.env.RUVECTOR_USE_REGRET_TRACKING==="true"),process.env.RUVECTOR_USE_COHERENCE_GATE!==void 0&&(n.useCoherenceGate=process.env.RUVECTOR_USE_COHERENCE_GATE==="true"),process.env.RUVECTOR_USE_WITNESS_CHAIN!==void 0&&(n.useWitnessChain=process.env.RUVECTOR_USE_WITNESS_CHAIN==="true"),process.env.RUVECTOR_USE_CNN_VISUAL_REGRESSION!==void 0&&(n.useCNNVisualRegression=process.env.RUVECTOR_USE_CNN_VISUAL_REGRESSION==="true"),process.env.RUVECTOR_USE_DAG_ATTENTION!==void 0&&(n.useDAGAttention=process.env.RUVECTOR_USE_DAG_ATTENTION==="true"),process.env.RUVECTOR_USE_COHERENCE_ACTION_GATE!==void 0&&(n.useCoherenceActionGate=process.env.RUVECTOR_USE_COHERENCE_ACTION_GATE==="true"),process.env.RUVECTOR_USE_REASONING_QEC!==void 0&&(n.useReasoningQEC=process.env.RUVECTOR_USE_REASONING_QEC==="true"),process.env.RUVECTOR_USE_HDC_FINGERPRINTING!==void 0&&(n.useHDCFingerprinting=process.env.RUVECTOR_USE_HDC_FINGERPRINTING==="true"),process.env.RUVECTOR_USE_CUSUM_DRIFT_DETECTION!==void 0&&(n.useCusumDriftDetection=process.env.RUVECTOR_USE_CUSUM_DRIFT_DETECTION==="true"),process.env.RUVECTOR_USE_DELTA_EVENT_SOURCING!==void 0&&(n.useDeltaEventSourcing=process.env.RUVECTOR_USE_DELTA_EVENT_SOURCING==="true"),process.env.RUVECTOR_USE_EWC_PLUS_PLUS!==void 0&&(n.useEwcPlusPlusRegularization=process.env.RUVECTOR_USE_EWC_PLUS_PLUS==="true"),process.env.RUVECTOR_USE_META_LEARNING!==void 0&&(n.useMetaLearningEnhancements=process.env.RUVECTOR_USE_META_LEARNING==="true"),process.env.RUVECTOR_USE_SUBLINEAR_SOLVER!==void 0&&(n.useSublinearSolver=process.env.RUVECTOR_USE_SUBLINEAR_SOLVER==="true"),process.env.RUVECTOR_USE_SPECTRAL_SPARSIFICATION!==void 0&&(n.useSpectralSparsification=process.env.RUVECTOR_USE_SPECTRAL_SPARSIFICATION==="true"),process.env.RUVECTOR_USE_RESERVOIR_REPLAY!==void 0&&(n.useReservoirReplay=process.env.RUVECTOR_USE_RESERVOIR_REPLAY==="true"),process.env.RUVECTOR_USE_EPROP_ONLINE_LEARNING!==void 0&&(n.useEpropOnlineLearning=process.env.RUVECTOR_USE_EPROP_ONLINE_LEARNING==="true"),process.env.RUVECTOR_USE_GRANGER_CAUSALITY!==void 0&&(n.useGrangerCausality=process.env.RUVECTOR_USE_GRANGER_CAUSALITY==="true"),process.env.RUVECTOR_USE_COGNITIVE_ROUTING!==void 0&&(n.useCognitiveRouting=process.env.RUVECTOR_USE_COGNITIVE_ROUTING==="true"),process.env.RUVECTOR_USE_HYPERBOLIC_HNSW!==void 0&&(n.useHyperbolicHnsw=process.env.RUVECTOR_USE_HYPERBOLIC_HNSW==="true"),o(n)}var r,e,X=s(()=>{r={useQESONA:!0,useQEFlashAttention:!0,useQEGNNIndex:!0,logMigrationMetrics:!0,useNativeHNSW:!0,useTemporalCompression:!0,useMetadataFiltering:!0,useDeterministicDither:!0,useNeuralRouting:!0,useSONAThreeLoop:!0,useCrossDomainTransfer:!0,useHnswHealthMonitor:!0,useRegretTracking:!0,useCoherenceGate:!0,useWitnessChain:!0,useCNNVisualRegression:!0,useDAGAttention:!0,useCoherenceActionGate:!0,useReasoningQEC:!0,useRVFPatternStore:!0,useAgentMemoryBranching:!0,useUnifiedHnsw:!0,rvfMigrationStage:2,useHDCFingerprinting:!0,useCusumDriftDetection:!0,useDeltaEventSourcing:!0,useEwcPlusPlusRegularization:!0,useGraphMAEEmbeddings:!0,useHopfieldMemory:!0,useColdTierGNN:!0,useMetaLearningEnhancements:!0,useSublinearSolver:!0,useSpectralSparsification:!0,useReservoirReplay:!0,useEpropOnlineLearning:!0,useGrangerCausality:!0,useCognitiveRouting:!1,useHyperbolicHnsw:!1},e={...r}});export{r as a,u as b,o as c,i as d,a as e,E as f,R as g,l as h,_ as i,c as j,S as k,T as l,C as m,p as n,N as o,U as p,O as q,f as r,d as s,b as t,g as u,A as v,v as w,V as x,I as y,G as z,H as A,D as B,F as C,M as D,L as E,x as F,h as G,P as H,m as I,y as J,W as K,w as L,Q as M,B as N,Y as O,k as P,z as Q,K as R,X as S};
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.15.9");process.exit(0)}
2
+ import{b as s,d as t}from"./chunk-HZ5NC6U5.js";var K={};t(K,{DEFAULT_FEATURE_FLAGS:()=>r,getRuVectorFeatureFlags:()=>u,getRvfMigrationStage:()=>H,initFeatureFlagsFromEnv:()=>z,isAgentMemoryBranchingEnabled:()=>I,isCNNVisualRegressionEnabled:()=>b,isCognitiveRoutingEnabled:()=>Y,isCoherenceActionGateEnabled:()=>A,isCoherenceGateEnabled:()=>f,isColdTierGNNEnabled:()=>P,isCrossDomainTransferEnabled:()=>N,isCusumDriftDetectionEnabled:()=>F,isDAGAttentionEnabled:()=>g,isDeltaEventSourcingEnabled:()=>M,isDeterministicDitherEnabled:()=>T,isEpropOnlineLearningEnabled:()=>Q,isEwcPlusPlusEnabled:()=>L,isFlashAttentionEnabled:()=>E,isGNNIndexEnabled:()=>R,isGrangerCausalityEnabled:()=>B,isGraphMAEEnabled:()=>x,isHDCFingerprintingEnabled:()=>D,isHnswHealthMonitorEnabled:()=>U,isHopfieldMemoryEnabled:()=>h,isHyperbolicHnswEnabled:()=>k,isMetaLearningEnabled:()=>m,isMetadataFilteringEnabled:()=>S,isNativeHNSWEnabled:()=>_,isNeuralRoutingEnabled:()=>C,isRVFPatternStoreEnabled:()=>V,isReasoningQECEnabled:()=>v,isRegretTrackingEnabled:()=>O,isReservoirReplayEnabled:()=>w,isSONAEnabled:()=>a,isSONAThreeLoopEnabled:()=>p,isSpectralSparsificationEnabled:()=>W,isSublinearSolverEnabled:()=>y,isTemporalCompressionEnabled:()=>c,isUnifiedHnswEnabled:()=>G,isWitnessChainEnabled:()=>d,resetRuVectorFeatureFlags:()=>i,setRuVectorFeatureFlags:()=>o,shouldLogMigrationMetrics:()=>l});function u(){return{...e}}function o(n){e={...e,...n}}function i(){e={...r}}function a(){return e.useQESONA}function E(){return e.useQEFlashAttention}function R(){return e.useQEGNNIndex}function l(){return e.logMigrationMetrics}function _(){return e.useNativeHNSW}function c(){return e.useTemporalCompression}function S(){return e.useMetadataFiltering}function T(){return e.useDeterministicDither}function C(){return e.useNeuralRouting}function p(){return e.useSONAThreeLoop}function N(){return e.useCrossDomainTransfer}function U(){return e.useHnswHealthMonitor}function O(){return e.useRegretTracking}function f(){return e.useCoherenceGate}function d(){return e.useWitnessChain}function b(){return e.useCNNVisualRegression}function g(){return e.useDAGAttention}function A(){return e.useCoherenceActionGate}function v(){return e.useReasoningQEC}function V(){return e.useRVFPatternStore}function I(){return e.useAgentMemoryBranching}function G(){return e.useUnifiedHnsw}function H(){return e.rvfMigrationStage}function D(){return e.useHDCFingerprinting}function F(){return e.useCusumDriftDetection}function M(){return e.useDeltaEventSourcing}function L(){return e.useEwcPlusPlusRegularization}function x(){return e.useGraphMAEEmbeddings}function h(){return e.useHopfieldMemory}function P(){return e.useColdTierGNN}function m(){return e.useMetaLearningEnhancements}function y(){return e.useSublinearSolver}function W(){return e.useSpectralSparsification}function w(){return e.useReservoirReplay}function Q(){return e.useEpropOnlineLearning}function B(){return e.useGrangerCausality}function Y(){return e.useCognitiveRouting}function k(){return e.useHyperbolicHnsw}function z(){let n={};process.env.RUVECTOR_USE_RVF_PATTERN_STORE!==void 0&&(n.useRVFPatternStore=process.env.RUVECTOR_USE_RVF_PATTERN_STORE==="true"),process.env.RUVECTOR_USE_SONA!==void 0&&(n.useQESONA=process.env.RUVECTOR_USE_SONA==="true"),process.env.RUVECTOR_USE_FLASH_ATTENTION!==void 0&&(n.useQEFlashAttention=process.env.RUVECTOR_USE_FLASH_ATTENTION==="true"),process.env.RUVECTOR_USE_GNN_INDEX!==void 0&&(n.useQEGNNIndex=process.env.RUVECTOR_USE_GNN_INDEX==="true"),process.env.RUVECTOR_LOG_MIGRATION_METRICS!==void 0&&(n.logMigrationMetrics=process.env.RUVECTOR_LOG_MIGRATION_METRICS==="true"),process.env.RUVECTOR_USE_NATIVE_HNSW!==void 0&&(n.useNativeHNSW=process.env.RUVECTOR_USE_NATIVE_HNSW==="true"),process.env.RUVECTOR_USE_TEMPORAL_COMPRESSION!==void 0&&(n.useTemporalCompression=process.env.RUVECTOR_USE_TEMPORAL_COMPRESSION==="true"),process.env.RUVECTOR_USE_METADATA_FILTERING!==void 0&&(n.useMetadataFiltering=process.env.RUVECTOR_USE_METADATA_FILTERING==="true"),process.env.RUVECTOR_USE_DETERMINISTIC_DITHER!==void 0&&(n.useDeterministicDither=process.env.RUVECTOR_USE_DETERMINISTIC_DITHER==="true"),process.env.RUVECTOR_USE_NEURAL_ROUTING!==void 0&&(n.useNeuralRouting=process.env.RUVECTOR_USE_NEURAL_ROUTING==="true"),process.env.RUVECTOR_USE_SONA_THREE_LOOP!==void 0&&(n.useSONAThreeLoop=process.env.RUVECTOR_USE_SONA_THREE_LOOP==="true"),process.env.RUVECTOR_USE_CROSS_DOMAIN_TRANSFER!==void 0&&(n.useCrossDomainTransfer=process.env.RUVECTOR_USE_CROSS_DOMAIN_TRANSFER==="true"),process.env.RUVECTOR_USE_HNSW_HEALTH_MONITOR!==void 0&&(n.useHnswHealthMonitor=process.env.RUVECTOR_USE_HNSW_HEALTH_MONITOR==="true"),process.env.RUVECTOR_USE_REGRET_TRACKING!==void 0&&(n.useRegretTracking=process.env.RUVECTOR_USE_REGRET_TRACKING==="true"),process.env.RUVECTOR_USE_COHERENCE_GATE!==void 0&&(n.useCoherenceGate=process.env.RUVECTOR_USE_COHERENCE_GATE==="true"),process.env.RUVECTOR_USE_WITNESS_CHAIN!==void 0&&(n.useWitnessChain=process.env.RUVECTOR_USE_WITNESS_CHAIN==="true"),process.env.RUVECTOR_USE_CNN_VISUAL_REGRESSION!==void 0&&(n.useCNNVisualRegression=process.env.RUVECTOR_USE_CNN_VISUAL_REGRESSION==="true"),process.env.RUVECTOR_USE_DAG_ATTENTION!==void 0&&(n.useDAGAttention=process.env.RUVECTOR_USE_DAG_ATTENTION==="true"),process.env.RUVECTOR_USE_COHERENCE_ACTION_GATE!==void 0&&(n.useCoherenceActionGate=process.env.RUVECTOR_USE_COHERENCE_ACTION_GATE==="true"),process.env.RUVECTOR_USE_REASONING_QEC!==void 0&&(n.useReasoningQEC=process.env.RUVECTOR_USE_REASONING_QEC==="true"),process.env.RUVECTOR_USE_HDC_FINGERPRINTING!==void 0&&(n.useHDCFingerprinting=process.env.RUVECTOR_USE_HDC_FINGERPRINTING==="true"),process.env.RUVECTOR_USE_CUSUM_DRIFT_DETECTION!==void 0&&(n.useCusumDriftDetection=process.env.RUVECTOR_USE_CUSUM_DRIFT_DETECTION==="true"),process.env.RUVECTOR_USE_DELTA_EVENT_SOURCING!==void 0&&(n.useDeltaEventSourcing=process.env.RUVECTOR_USE_DELTA_EVENT_SOURCING==="true"),process.env.RUVECTOR_USE_EWC_PLUS_PLUS!==void 0&&(n.useEwcPlusPlusRegularization=process.env.RUVECTOR_USE_EWC_PLUS_PLUS==="true"),process.env.RUVECTOR_USE_META_LEARNING!==void 0&&(n.useMetaLearningEnhancements=process.env.RUVECTOR_USE_META_LEARNING==="true"),process.env.RUVECTOR_USE_SUBLINEAR_SOLVER!==void 0&&(n.useSublinearSolver=process.env.RUVECTOR_USE_SUBLINEAR_SOLVER==="true"),process.env.RUVECTOR_USE_SPECTRAL_SPARSIFICATION!==void 0&&(n.useSpectralSparsification=process.env.RUVECTOR_USE_SPECTRAL_SPARSIFICATION==="true"),process.env.RUVECTOR_USE_RESERVOIR_REPLAY!==void 0&&(n.useReservoirReplay=process.env.RUVECTOR_USE_RESERVOIR_REPLAY==="true"),process.env.RUVECTOR_USE_EPROP_ONLINE_LEARNING!==void 0&&(n.useEpropOnlineLearning=process.env.RUVECTOR_USE_EPROP_ONLINE_LEARNING==="true"),process.env.RUVECTOR_USE_GRANGER_CAUSALITY!==void 0&&(n.useGrangerCausality=process.env.RUVECTOR_USE_GRANGER_CAUSALITY==="true"),process.env.RUVECTOR_USE_COGNITIVE_ROUTING!==void 0&&(n.useCognitiveRouting=process.env.RUVECTOR_USE_COGNITIVE_ROUTING==="true"),process.env.RUVECTOR_USE_HYPERBOLIC_HNSW!==void 0&&(n.useHyperbolicHnsw=process.env.RUVECTOR_USE_HYPERBOLIC_HNSW==="true"),o(n)}var r,e,X=s(()=>{r={useQESONA:!0,useQEFlashAttention:!0,useQEGNNIndex:!0,logMigrationMetrics:!0,useNativeHNSW:!0,useTemporalCompression:!0,useMetadataFiltering:!0,useDeterministicDither:!0,useNeuralRouting:!0,useSONAThreeLoop:!0,useCrossDomainTransfer:!0,useHnswHealthMonitor:!0,useRegretTracking:!0,useCoherenceGate:!0,useWitnessChain:!0,useCNNVisualRegression:!0,useDAGAttention:!0,useCoherenceActionGate:!0,useReasoningQEC:!0,useRVFPatternStore:!0,useAgentMemoryBranching:!0,useUnifiedHnsw:!0,rvfMigrationStage:2,useHDCFingerprinting:!0,useCusumDriftDetection:!0,useDeltaEventSourcing:!0,useEwcPlusPlusRegularization:!0,useGraphMAEEmbeddings:!0,useHopfieldMemory:!0,useColdTierGNN:!0,useMetaLearningEnhancements:!0,useSublinearSolver:!0,useSpectralSparsification:!0,useReservoirReplay:!0,useEpropOnlineLearning:!0,useGrangerCausality:!0,useCognitiveRouting:!1,useHyperbolicHnsw:!1},e={...r}});export{r as a,u as b,o as c,i as d,a as e,E as f,R as g,l as h,_ as i,c as j,S as k,T as l,C as m,p as n,N as o,U as p,O as q,f as r,d as s,b as t,g as u,A as v,v as w,V as x,I as y,G as z,H as A,D as B,F as C,M as D,L as E,x as F,h as G,P as H,m as I,y as J,W as K,w as L,Q as M,B as N,Y as O,k as P,z as Q,K as R,X as S};
@@ -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.15.8");process.exit(0)}
2
- import{b as y,d as p}from"./chunk-YUP3APSN.js";import{i as h}from"./chunk-PICEGWGB.js";var f={healthyThreshold:3,warningThreshold:2,checkIntervalMs:5e3,maxHistoryEntries:100,alertsEnabled:!0,alertCooldownMs:6e4,selfHealingEnabled:!1,maxHealingActionsPerMinute:5};var g=class{calculator;config;eventBus;persistence;graph;history=[];alerts=new Map;lastAlertTime=new Map;monitoringInterval=null;isMonitoring=!1;constructor(e,t={},r,i){this.graph=e,this.config={...f,...t},this.calculator=p(),this.eventBus=r,this.persistence=i}start(){this.isMonitoring||(this.isMonitoring=!0,this.monitoringInterval=setInterval(()=>this.checkHealth(),this.config.checkIntervalMs),this.checkHealth())}stop(){this.monitoringInterval&&(clearInterval(this.monitoringInterval),this.monitoringInterval=null),this.isMonitoring=!1}updateGraph(e){this.graph=e,this.isMonitoring&&this.checkHealth()}isEmptyTopology(){return this.graph.getVerticesByType("agent").length===0}checkHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph),r=this.isEmptyTopology()?"idle":this.determineStatus(e),i=this.calculateTrend();return this.recordHistory(e),this.isEmptyTopology()||this.checkAlertConditions(e,t,r),this.persistence&&t.length>0&&this.persistence.saveWeakVertices(t).catch(n=>console.warn("[MinCutHealthMonitor] Failed to persist weak vertices:",n)),this.emitEvent("mincut.updated",e,{status:r,weakVertexCount:t.length}),{status:r,minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:i,history:this.history.slice(-20),lastUpdated:new Date}}getHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph);return{status:this.isEmptyTopology()?"idle":this.determineStatus(e),minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:this.calculateTrend(),history:this.history.slice(-20),lastUpdated:new Date}}getMinCutValue(){return this.calculator.getMinCutValue(this.graph)}getWeakVertices(){return this.calculator.findWeakVertices(this.graph)}isCritical(){return this.calculator.getMinCutValue(this.graph)<this.config.warningThreshold}isHealthy(){return this.calculator.getMinCutValue(this.graph)>=this.config.healthyThreshold}getActiveAlerts(){return Array.from(this.alerts.values()).filter(e=>!e.acknowledged).sort((e,t)=>{let r={critical:0,high:1,medium:2,low:3,info:4};return r[e.severity]-r[t.severity]})}getAllAlerts(){return Array.from(this.alerts.values())}acknowledgeAlert(e){let t=this.alerts.get(e);return t?(t.acknowledged=!0,!0):!1}clearAcknowledgedAlerts(){let e=[];for(let[t,r]of this.alerts)r.acknowledged&&e.push(t);for(let t of e)this.alerts.delete(t);return e.length}getHistory(){return[...this.history]}getTrend(){return this.calculateTrend()}getStats(e=6e4){let t=Date.now()-e,r=this.history.filter(n=>n.timestamp.getTime()>t);if(r.length===0){let n=this.calculator.getMinCutValue(this.graph);return{min:n,max:n,average:n,count:0}}let i=r.map(n=>n.value);return{min:Math.min(...i),max:Math.max(...i),average:i.reduce((n,a)=>n+a,0)/i.length,count:r.length}}updateConfig(e){Object.assign(this.config,e),e.checkIntervalMs&&this.isMonitoring&&(this.stop(),this.start())}getConfig(){return{...this.config}}determineStatus(e){return e>=this.config.healthyThreshold?"healthy":e>=this.config.warningThreshold?"warning":"critical"}calculateTrend(){if(this.history.length<3)return"stable";let e=this.history.slice(-5),t=e[0].value,i=e[e.length-1].value-t,a=e.reduce((o,c)=>o+c.value,0)/e.length*.1;return i>a?"improving":i<-a?"degrading":"stable"}recordHistory(e){let t={timestamp:new Date,value:e,vertexCount:this.graph.vertexCount,edgeCount:this.graph.edgeCount};for(this.history.push(t);this.history.length>this.config.maxHistoryEntries;)this.history.shift()}checkAlertConditions(e,t,r){if(!this.config.alertsEnabled)return;let i=Date.now();r==="critical"?this.maybeGenerateAlert("critical-threshold","critical",`MinCut value (${e.toFixed(2)}) is below critical threshold (${this.config.warningThreshold})`,e,this.config.warningThreshold,t):r==="warning"&&this.maybeGenerateAlert("warning-threshold","high",`MinCut value (${e.toFixed(2)}) is below healthy threshold (${this.config.healthyThreshold})`,e,this.config.healthyThreshold,t);let n=t.filter(o=>o.weightedDegree===0);n.length>0&&this.maybeGenerateAlert("isolated-vertices","high",`${n.length} isolated vertex(es) detected`,e,0,n);let a=t.filter(o=>o.riskScore>.8);a.length>0&&this.maybeGenerateAlert("critical-vertices","medium",`${a.length} critical vertex(es) with high risk score`,e,0,a)}maybeGenerateAlert(e,t,r,i,n,a){let o=Date.now(),c=this.lastAlertTime.get(e)||0;if(o-c<this.config.alertCooldownMs)return;let s={id:h(),severity:t,message:r,minCutValue:i,threshold:n,affectedVertices:a.map(l=>l.vertexId),timestamp:new Date,acknowledged:!1,remediations:a.flatMap(l=>l.suggestions).slice(0,5)};this.alerts.set(s.id,s),this.persistence&&this.persistence.saveAlert(s).catch(l=>console.warn("[MinCutHealthMonitor] Failed to persist alert:",l)),this.lastAlertTime.set(e,o),this.emitEvent("mincut.alert.generated",i,{alert:s})}emitEvent(e,t,r){if(!this.eventBus)return;let i={id:h(),type:e,source:"coordination",timestamp:new Date,correlationId:h(),payload:{minCutValue:t,...r}};this.eventBus.publish(i).catch(n=>{console.error("Failed to publish MinCut event:",n)})}};function v(m,e,t,r){return new g(m,e,t,r)}var d=null,u=null;function C(){return d||(d=y()),d}function P(){return u||(u=v(C())),u}function B(){return d!==null}function F(){return u!==null}export{f as a,v as b,C as c,P as d,B as e,F 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.15.9");process.exit(0)}
2
+ import{b as y,d as p}from"./chunk-XWIUFYM3.js";import{i as h}from"./chunk-FV7VAG74.js";var f={healthyThreshold:3,warningThreshold:2,checkIntervalMs:5e3,maxHistoryEntries:100,alertsEnabled:!0,alertCooldownMs:6e4,selfHealingEnabled:!1,maxHealingActionsPerMinute:5};var g=class{calculator;config;eventBus;persistence;graph;history=[];alerts=new Map;lastAlertTime=new Map;monitoringInterval=null;isMonitoring=!1;constructor(e,t={},r,i){this.graph=e,this.config={...f,...t},this.calculator=p(),this.eventBus=r,this.persistence=i}start(){this.isMonitoring||(this.isMonitoring=!0,this.monitoringInterval=setInterval(()=>this.checkHealth(),this.config.checkIntervalMs),this.checkHealth())}stop(){this.monitoringInterval&&(clearInterval(this.monitoringInterval),this.monitoringInterval=null),this.isMonitoring=!1}updateGraph(e){this.graph=e,this.isMonitoring&&this.checkHealth()}isEmptyTopology(){return this.graph.getVerticesByType("agent").length===0}checkHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph),r=this.isEmptyTopology()?"idle":this.determineStatus(e),i=this.calculateTrend();return this.recordHistory(e),this.isEmptyTopology()||this.checkAlertConditions(e,t,r),this.persistence&&t.length>0&&this.persistence.saveWeakVertices(t).catch(n=>console.warn("[MinCutHealthMonitor] Failed to persist weak vertices:",n)),this.emitEvent("mincut.updated",e,{status:r,weakVertexCount:t.length}),{status:r,minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:i,history:this.history.slice(-20),lastUpdated:new Date}}getHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph);return{status:this.isEmptyTopology()?"idle":this.determineStatus(e),minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:this.calculateTrend(),history:this.history.slice(-20),lastUpdated:new Date}}getMinCutValue(){return this.calculator.getMinCutValue(this.graph)}getWeakVertices(){return this.calculator.findWeakVertices(this.graph)}isCritical(){return this.calculator.getMinCutValue(this.graph)<this.config.warningThreshold}isHealthy(){return this.calculator.getMinCutValue(this.graph)>=this.config.healthyThreshold}getActiveAlerts(){return Array.from(this.alerts.values()).filter(e=>!e.acknowledged).sort((e,t)=>{let r={critical:0,high:1,medium:2,low:3,info:4};return r[e.severity]-r[t.severity]})}getAllAlerts(){return Array.from(this.alerts.values())}acknowledgeAlert(e){let t=this.alerts.get(e);return t?(t.acknowledged=!0,!0):!1}clearAcknowledgedAlerts(){let e=[];for(let[t,r]of this.alerts)r.acknowledged&&e.push(t);for(let t of e)this.alerts.delete(t);return e.length}getHistory(){return[...this.history]}getTrend(){return this.calculateTrend()}getStats(e=6e4){let t=Date.now()-e,r=this.history.filter(n=>n.timestamp.getTime()>t);if(r.length===0){let n=this.calculator.getMinCutValue(this.graph);return{min:n,max:n,average:n,count:0}}let i=r.map(n=>n.value);return{min:Math.min(...i),max:Math.max(...i),average:i.reduce((n,a)=>n+a,0)/i.length,count:r.length}}updateConfig(e){Object.assign(this.config,e),e.checkIntervalMs&&this.isMonitoring&&(this.stop(),this.start())}getConfig(){return{...this.config}}determineStatus(e){return e>=this.config.healthyThreshold?"healthy":e>=this.config.warningThreshold?"warning":"critical"}calculateTrend(){if(this.history.length<3)return"stable";let e=this.history.slice(-5),t=e[0].value,i=e[e.length-1].value-t,a=e.reduce((o,c)=>o+c.value,0)/e.length*.1;return i>a?"improving":i<-a?"degrading":"stable"}recordHistory(e){let t={timestamp:new Date,value:e,vertexCount:this.graph.vertexCount,edgeCount:this.graph.edgeCount};for(this.history.push(t);this.history.length>this.config.maxHistoryEntries;)this.history.shift()}checkAlertConditions(e,t,r){if(!this.config.alertsEnabled)return;let i=Date.now();r==="critical"?this.maybeGenerateAlert("critical-threshold","critical",`MinCut value (${e.toFixed(2)}) is below critical threshold (${this.config.warningThreshold})`,e,this.config.warningThreshold,t):r==="warning"&&this.maybeGenerateAlert("warning-threshold","high",`MinCut value (${e.toFixed(2)}) is below healthy threshold (${this.config.healthyThreshold})`,e,this.config.healthyThreshold,t);let n=t.filter(o=>o.weightedDegree===0);n.length>0&&this.maybeGenerateAlert("isolated-vertices","high",`${n.length} isolated vertex(es) detected`,e,0,n);let a=t.filter(o=>o.riskScore>.8);a.length>0&&this.maybeGenerateAlert("critical-vertices","medium",`${a.length} critical vertex(es) with high risk score`,e,0,a)}maybeGenerateAlert(e,t,r,i,n,a){let o=Date.now(),c=this.lastAlertTime.get(e)||0;if(o-c<this.config.alertCooldownMs)return;let s={id:h(),severity:t,message:r,minCutValue:i,threshold:n,affectedVertices:a.map(l=>l.vertexId),timestamp:new Date,acknowledged:!1,remediations:a.flatMap(l=>l.suggestions).slice(0,5)};this.alerts.set(s.id,s),this.persistence&&this.persistence.saveAlert(s).catch(l=>console.warn("[MinCutHealthMonitor] Failed to persist alert:",l)),this.lastAlertTime.set(e,o),this.emitEvent("mincut.alert.generated",i,{alert:s})}emitEvent(e,t,r){if(!this.eventBus)return;let i={id:h(),type:e,source:"coordination",timestamp:new Date,correlationId:h(),payload:{minCutValue:t,...r}};this.eventBus.publish(i).catch(n=>{console.error("Failed to publish MinCut event:",n)})}};function v(m,e,t,r){return new g(m,e,t,r)}var d=null,u=null;function C(){return d||(d=y()),d}function P(){return u||(u=v(C())),u}function B(){return d!==null}function F(){return u!==null}export{f as a,v as b,C as c,P as d,B as e,F 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.15.8");process.exit(0)}
2
- import{e as l,l as c}from"./chunk-TC52M542.js";import{a as i}from"./chunk-V4QJ3MMT.js";import{a as n,e as h}from"./chunk-J7FLNP5L.js";h();var d=class extends c{config={name:"qe/tests/schedule",description:"Schedule and execute tests using phase-based pipeline with git-aware selection and flaky tracking. Runs tests in phases (unit, integration, e2e), selects affected tests from git changes, and tracks flaky tests.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{cwd:{type:"string",description:"Working directory for test execution (defaults to project root)"},gitRef:{type:"string",description:'Git ref to compare for affected test selection (e.g., "main", "HEAD~3")'},useGitAware:{type:"boolean",description:"Enable git-aware test selection to only run affected tests",default:!0},trackFlaky:{type:"boolean",description:"Enable flaky test tracking and quarantine",default:!0}}}}async execute(s,o){if(s.gitRef!==void 0){let a=i(s.gitRef,"gitRef");if(a)return{success:!1,error:a}}try{let{runTestPipeline:a}=await import("./test-scheduling-Z42XXZP6.js"),u=await l(o),t=await a({cwd:s.cwd||process.cwd(),memory:u,baseRef:s.gitRef,flakyHistoryPath:s.trackFlaky!==!1?".agentic-qe/flaky-history.json":void 0,runAllTests:s.useGitAware===!1}),f=t.phaseResults.reduce((e,r)=>e+r.totalTests,0),p=t.phaseResults.reduce((e,r)=>e+r.passed,0),g=t.phaseResults.reduce((e,r)=>e+r.failed,0);return{success:!0,data:{pipelineId:o.requestId,phases:t.phaseResults.map(e=>({phaseId:e.phaseId,phaseName:e.phaseName,totalTests:e.totalTests,passed:e.passed,failed:e.failed,passRate:e.passRate,durationMs:e.durationMs})),gitAware:{enabled:!t.ranAllTests,selectedTests:t.selectedTests.length,gitRef:s.gitRef},flakyTracking:{enabled:s.trackFlaky!==!1},totalDuration:t.totalDurationMs,ranAllTests:t.ranAllTests,summary:`Executed ${t.phaseResults.length} phases, ${f} tests (${p} passed, ${g} failed) in ${t.totalDurationMs}ms`}}}catch(a){return{success:!1,error:n(a)}}}};export{d as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.9");process.exit(0)}
2
+ import{e as l,l as c}from"./chunk-JK2ME6IT.js";import{a as i}from"./chunk-HAROIAJE.js";import{a as n,e as h}from"./chunk-N3KEY4XJ.js";h();var d=class extends c{config={name:"qe/tests/schedule",description:"Schedule and execute tests using phase-based pipeline with git-aware selection and flaky tracking. Runs tests in phases (unit, integration, e2e), selects affected tests from git changes, and tracks flaky tests.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{cwd:{type:"string",description:"Working directory for test execution (defaults to project root)"},gitRef:{type:"string",description:'Git ref to compare for affected test selection (e.g., "main", "HEAD~3")'},useGitAware:{type:"boolean",description:"Enable git-aware test selection to only run affected tests",default:!0},trackFlaky:{type:"boolean",description:"Enable flaky test tracking and quarantine",default:!0}}}}async execute(s,o){if(s.gitRef!==void 0){let a=i(s.gitRef,"gitRef");if(a)return{success:!1,error:a}}try{let{runTestPipeline:a}=await import("./test-scheduling-VYUQ4CDE.js"),u=await l(o),t=await a({cwd:s.cwd||process.cwd(),memory:u,baseRef:s.gitRef,flakyHistoryPath:s.trackFlaky!==!1?".agentic-qe/flaky-history.json":void 0,runAllTests:s.useGitAware===!1}),f=t.phaseResults.reduce((e,r)=>e+r.totalTests,0),p=t.phaseResults.reduce((e,r)=>e+r.passed,0),g=t.phaseResults.reduce((e,r)=>e+r.failed,0);return{success:!0,data:{pipelineId:o.requestId,phases:t.phaseResults.map(e=>({phaseId:e.phaseId,phaseName:e.phaseName,totalTests:e.totalTests,passed:e.passed,failed:e.failed,passRate:e.passRate,durationMs:e.durationMs})),gitAware:{enabled:!t.ranAllTests,selectedTests:t.selectedTests.length,gitRef:s.gitRef},flakyTracking:{enabled:s.trackFlaky!==!1},totalDuration:t.totalDurationMs,ranAllTests:t.ranAllTests,summary:`Executed ${t.phaseResults.length} phases, ${f} tests (${p} passed, ${g} failed) in ${t.totalDurationMs}ms`}}}catch(a){return{success:!1,error:n(a)}}}};export{d as a};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
2
- import{e as P}from"./chunk-QFYUZYRA.js";import{a as w}from"./chunk-62T7U25U.js";import{a as T,b as S}from"./chunk-BLZEOGQE.js";import{r as M,s as I}from"./chunk-7XGM7Q2N.js";import{a as k,e as D}from"./chunk-J7FLNP5L.js";import{c as C,d as F}from"./chunk-SHEVM5PF.js";import{f as A}from"./chunk-K5R3WUJP.js";F();import{createHash as $}from"crypto";import*as x from"path";function H(){let o="3.15.8",e=(process.env.AQE_SESSION_CACHE_SALT??"").trim();return e?`${o}+${e}`:o}var L={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function Q(o){let e=JSON.parse(JSON.stringify(o));function t(r){if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r))return"["+r.map(t).join(",")+"]";let i=r;return"{"+Object.keys(i).sort().map(n=>JSON.stringify(n)+":"+t(i[n])).join(",")+"}"}return t(e)}function U(o){let e=o?.projectRoot;if(!e)try{e=C()}catch{e=""}let t=o?.cwd;if(!t)try{t=process.cwd()}catch{t=""}return{projectRoot:e?x.resolve(e):"",cwd:t?x.resolve(t):"",inputs:o?.inputs??{}}}var v=class{cache=new Map;config;hits=0;misses=0;generation=0;constructor(e){this.config={...L,...e}}computeFingerprint(e,t,r,i){let n=Q({action:t,build:H(),domain:e,input:r,scope:U(i)});return $("sha256").update(n).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,r,i,n){if(!this.config.enabled)return;!this.cache.has(e)&&this.cache.size>=this.config.maxEntries&&this.evictOldest();let s={fingerprint:e,domain:t,action:r,result:i,tokensSaved:n,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,s),this.config.persistToDb&&this.persistEntry(s)}loadFromDb(){try{let e=d();if(!e)return;let t=Date.now()-this.config.ttlMs,r=e.prepare(`SELECT key, value FROM kv_store
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.15.9");process.exit(0)}
2
+ import{e as P}from"./chunk-GCWSX2NY.js";import{a as w}from"./chunk-F3PQZX44.js";import{a as T,b as S}from"./chunk-L42JPFCC.js";import{r as M,s as I}from"./chunk-OCESWNAZ.js";import{a as k,e as D}from"./chunk-N3KEY4XJ.js";import{c as C,d as F}from"./chunk-4V27J6YN.js";import{f as A}from"./chunk-HZ5NC6U5.js";F();import{createHash as $}from"crypto";import*as x from"path";function H(){let o="3.15.9",e=(process.env.AQE_SESSION_CACHE_SALT??"").trim();return e?`${o}+${e}`:o}var L={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function Q(o){let e=JSON.parse(JSON.stringify(o));function t(r){if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r))return"["+r.map(t).join(",")+"]";let i=r;return"{"+Object.keys(i).sort().map(n=>JSON.stringify(n)+":"+t(i[n])).join(",")+"}"}return t(e)}function U(o){let e=o?.projectRoot;if(!e)try{e=C()}catch{e=""}let t=o?.cwd;if(!t)try{t=process.cwd()}catch{t=""}return{projectRoot:e?x.resolve(e):"",cwd:t?x.resolve(t):"",inputs:o?.inputs??{}}}var v=class{cache=new Map;config;hits=0;misses=0;generation=0;constructor(e){this.config={...L,...e}}computeFingerprint(e,t,r,i){let n=Q({action:t,build:H(),domain:e,input:r,scope:U(i)});return $("sha256").update(n).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,r,i,n){if(!this.config.enabled)return;!this.cache.has(e)&&this.cache.size>=this.config.maxEntries&&this.evictOldest();let s={fingerprint:e,domain:t,action:r,result:i,tokensSaved:n,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,s),this.config.persistToDb&&this.persistEntry(s)}loadFromDb(){try{let e=d();if(!e)return;let t=Date.now()-this.config.ttlMs,r=e.prepare(`SELECT key, value FROM kv_store
3
3
  WHERE namespace = 'session_cache'
4
4
  AND created_at > ?
5
5
  ORDER BY created_at DESC LIMIT ?`).all(t,this.config.maxEntries);for(let i of r)try{let n=JSON.parse(i.value);Date.now()-n.cachedAt<=this.config.ttlMs&&this.cache.set(n.fingerprint,n)}catch{}}catch{}}getStats(){let e=this.hits+this.misses,t=0;for(let r of this.cache.values())t+=r.tokensSaved*r.hitCount;return{size:this.cache.size,hits:this.hits,misses:this.misses,hitRate:e>0?this.hits/e:0,estimatedTokensSaved:t}}clear(){this.cache.clear(),this.hits=0,this.misses=0,this.generation++}getGeneration(){return this.generation}invalidateAll(){let e=this.cache.size;if(this.cache.clear(),this.generation++,this.config.persistToDb)try{d()?.prepare("DELETE FROM kv_store WHERE namespace = 'session_cache'").run()}catch{}return e}invalidateDomain(e){this.generation++;let t=0;for(let[r,i]of this.cache)i.domain===e&&(this.cache.delete(r),this.deletePersisted(i.fingerprint),t++);return t}evictOldest(){let e=null,t=1/0;for(let[r,i]of this.cache)i.cachedAt<t&&(t=i.cachedAt,e=r);e&&this.cache.delete(e)}persistEntry(e){try{let t=d();if(!t)return;t.prepare(`INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
@@ -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.15.8");process.exit(0)}
2
- import{a as v,b as k}from"./chunk-3N627QRU.js";import{o as g,s as P}from"./chunk-7XGM7Q2N.js";import{a as d,b as y,e as R}from"./chunk-J7FLNP5L.js";R();import{randomUUID as M}from"crypto";var p=class{constructor(e){this.config=e}config;_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let r=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let n,t;for(let a=0;a<=this.config.retryCount;a++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");t=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(u){n=y(u),e.logger.warn(`Worker ${this.config.id} attempt ${a+1} failed: ${n.message}`),a<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let o=Date.now()-r;return t?(this._successfulExecutions++,this._lastResult=t):(this._failedExecutions++,t=this.createErrorResult(n,o),this._lastResult=t),this._executionDurations.push(o),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:t.success,durationMs:o}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=t.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:t.success,durationMs:o,findingsCount:t.findings.length,healthScore:t.metrics.healthScore}}),t}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((n,t)=>n+t,0)/this._executionDurations.length:0,r=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(r*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,r,n){return new Promise((t,o)=>{let a=setTimeout(()=>{o(new Error(`Worker execution timed out after ${r}ms`))},r),u=()=>{clearTimeout(a),o(new Error("Worker execution aborted"))};n.addEventListener("abort",u,{once:!0}),e().then(c=>{clearTimeout(a),n.removeEventListener("abort",u),t(c)}).catch(c=>{clearTimeout(a),n.removeEventListener("abort",u),o(c)})})}createErrorResult(e,r){return{workerId:this.config.id,timestamp:new Date,durationMs:r,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,r,n,t){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:r,findings:n,recommendations:t}}delay(e){return new Promise(r=>setTimeout(r,e))}generateId(){return`${Date.now()}-${M().slice(0,9)}`}};P();R();var W={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},b=class extends p{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(W),this.dailyLogger=new k}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=g();await e.initialize();let r=e.getDatabase();return this.lifecycleManager=v(r,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return g().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let r=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let n=[],t=[],o=await this.getLifecycleManager();if(!o)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-r,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let a=0,u=0;try{let s=o.promoteEligiblePatterns();a=s.promoted,u=s.checked,a>0&&n.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${a} of ${u} short-term patterns promoted to long-term`})}catch(s){e.logger.warn("Pattern promotion failed",{error:d(s)})}let c=0,h=0;try{let s=o.deprecateStalePatterns();c=s.deprecated,h=s.checked,c>0&&n.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${c} of ${h} patterns deprecated (stale, failed, or low confidence)`})}catch(s){e.logger.warn("Stale pattern detection failed",{error:d(s)})}let l=0;try{let s=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;l=o.applyConfidenceDecay(Math.min(s,7)).decayed}catch(s){e.logger.warn("Confidence decay failed",{error:d(s)})}let m=this.getPendingExperienceCount(),i={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{i=o.getStats()}catch(s){e.logger.warn("Stats retrieval failed",{error:d(s)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${a} promoted, ${c} deprecated, ${l} decayed, ${m} pending exp, ${i.activePatterns} active patterns (avg conf: ${i.avgConfidence.toFixed(2)})`,details:{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,totalPatterns:i.totalPatterns,activePatterns:i.activePatterns,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}),this.dailyLogger.flush()}catch(s){e.logger.warn("Daily log write failed",{error:d(s)})}this.lastRunTimestamp=Date.now(),i.activePatterns>0&&i.patternsNearDeprecation/i.activePatterns>.5&&t.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${i.patternsNearDeprecation} of ${i.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let f=this.calculateHealthScore(i,a,c),D=this.determineTrend(a,c,i.activePatterns),_=Math.max(u,h),x=a+c+i.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,healthScore:f}),this.createResult(Date.now()-r,{itemsAnalyzed:_,issuesFound:x,healthScore:f,trend:D,domainMetrics:{promoted:a,deprecated:c,decayed:l,stalePatterns:i.patternsNearDeprecation,pendingExperiences:m,avgConfidence:Number(i.avgConfidence.toFixed(3)),avgSuccessRate:Number(i.avgSuccessRate.toFixed(3))}},n,t)}calculateHealthScore(e,r,n){let t=70;if(t+=Math.min(15,r*5),e.avgConfidence>0&&(t+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let o=n/e.activePatterns;t-=Math.round(o*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(t-=10),Math.max(0,Math.min(100,Math.round(t)))}determineTrend(e,r,n){return n===0?"stable":e>r?"improving":r>e&&r/n>.1?"degrading":"stable"}};export{p as a,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.15.9");process.exit(0)}
2
+ import{a as v,b as k}from"./chunk-VQHVHVSF.js";import{o as g,s as P}from"./chunk-OCESWNAZ.js";import{a as d,b as y,e as R}from"./chunk-N3KEY4XJ.js";R();import{randomUUID as M}from"crypto";var p=class{constructor(e){this.config=e}config;_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let r=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let n,t;for(let a=0;a<=this.config.retryCount;a++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");t=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(u){n=y(u),e.logger.warn(`Worker ${this.config.id} attempt ${a+1} failed: ${n.message}`),a<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let o=Date.now()-r;return t?(this._successfulExecutions++,this._lastResult=t):(this._failedExecutions++,t=this.createErrorResult(n,o),this._lastResult=t),this._executionDurations.push(o),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:t.success,durationMs:o}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=t.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:t.success,durationMs:o,findingsCount:t.findings.length,healthScore:t.metrics.healthScore}}),t}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((n,t)=>n+t,0)/this._executionDurations.length:0,r=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(r*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,r,n){return new Promise((t,o)=>{let a=setTimeout(()=>{o(new Error(`Worker execution timed out after ${r}ms`))},r),u=()=>{clearTimeout(a),o(new Error("Worker execution aborted"))};n.addEventListener("abort",u,{once:!0}),e().then(c=>{clearTimeout(a),n.removeEventListener("abort",u),t(c)}).catch(c=>{clearTimeout(a),n.removeEventListener("abort",u),o(c)})})}createErrorResult(e,r){return{workerId:this.config.id,timestamp:new Date,durationMs:r,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,r,n,t){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:r,findings:n,recommendations:t}}delay(e){return new Promise(r=>setTimeout(r,e))}generateId(){return`${Date.now()}-${M().slice(0,9)}`}};P();R();var W={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},b=class extends p{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(W),this.dailyLogger=new k}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=g();await e.initialize();let r=e.getDatabase();return this.lifecycleManager=v(r,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return g().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let r=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let n=[],t=[],o=await this.getLifecycleManager();if(!o)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-r,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let a=0,u=0;try{let s=o.promoteEligiblePatterns();a=s.promoted,u=s.checked,a>0&&n.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${a} of ${u} short-term patterns promoted to long-term`})}catch(s){e.logger.warn("Pattern promotion failed",{error:d(s)})}let c=0,h=0;try{let s=o.deprecateStalePatterns();c=s.deprecated,h=s.checked,c>0&&n.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${c} of ${h} patterns deprecated (stale, failed, or low confidence)`})}catch(s){e.logger.warn("Stale pattern detection failed",{error:d(s)})}let l=0;try{let s=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;l=o.applyConfidenceDecay(Math.min(s,7)).decayed}catch(s){e.logger.warn("Confidence decay failed",{error:d(s)})}let m=this.getPendingExperienceCount(),i={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{i=o.getStats()}catch(s){e.logger.warn("Stats retrieval failed",{error:d(s)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${a} promoted, ${c} deprecated, ${l} decayed, ${m} pending exp, ${i.activePatterns} active patterns (avg conf: ${i.avgConfidence.toFixed(2)})`,details:{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,totalPatterns:i.totalPatterns,activePatterns:i.activePatterns,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}),this.dailyLogger.flush()}catch(s){e.logger.warn("Daily log write failed",{error:d(s)})}this.lastRunTimestamp=Date.now(),i.activePatterns>0&&i.patternsNearDeprecation/i.activePatterns>.5&&t.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${i.patternsNearDeprecation} of ${i.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let f=this.calculateHealthScore(i,a,c),D=this.determineTrend(a,c,i.activePatterns),_=Math.max(u,h),x=a+c+i.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,healthScore:f}),this.createResult(Date.now()-r,{itemsAnalyzed:_,issuesFound:x,healthScore:f,trend:D,domainMetrics:{promoted:a,deprecated:c,decayed:l,stalePatterns:i.patternsNearDeprecation,pendingExperiences:m,avgConfidence:Number(i.avgConfidence.toFixed(3)),avgSuccessRate:Number(i.avgSuccessRate.toFixed(3))}},n,t)}calculateHealthScore(e,r,n){let t=70;if(t+=Math.min(15,r*5),e.avgConfidence>0&&(t+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let o=n/e.activePatterns;t-=Math.round(o*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(t-=10),Math.max(0,Math.min(100,Math.round(t)))}determineTrend(e,r,n){return n===0?"stable":e>r?"improving":r>e&&r/n>.1?"degrading":"stable"}};export{p as a,b};
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
2
- import{a as p}from"./chunk-X6VYQVUM.js";import{e as g}from"./chunk-7H3GNRNA.js";p();import{format as R}from"node:util";var c=2,E={debug:0,info:1,warn:2,warning:2,error:3,silent:4,none:4,off:4},C=new Set(["1","true","yes","on"]),b=/\x1b\[[0-9;]*m/g,N=/^\[(?:\d{2}:\d{2}:\d{2}\.\d{3}|\d{4}-\d{2}-\d{2}T[^\]]+)\]\s+\[(DEBUG|INFO|WARN|ERROR)\s*\]/,O=/^\[[A-Za-z][\w./:-]*\]\s/,S={debug:0,log:1,info:1,warn:2,error:3},d=c;function s(o){if(o)return E[o.trim().toLowerCase()]}function _(o=process.env,e=c){let t=s(o.AQE_LOG_LEVEL)??s(o.LOG_LEVEL);return t!==void 0?t:o.AQE_VERBOSE&&C.has(o.AQE_VERBOSE.trim().toLowerCase())?1:e}function x(o,e){if(typeof e!="string")return null;let t=e.replace(b,""),r=N.exec(t.trimStart());return r?E[r[1].toLowerCase()]:O.test(t)?S[o]:null}function I(o=process.env){return s(o.AQE_LOG_LEVEL)!==void 0||s(o.LOG_LEVEL)!==void 0}function m(o,e=process.env){return o.verbose!==!0||I(e)||a(1)?!1:(f(1),!0)}function a(o){return o>=d&&d!==4}function f(o){d=o,g.setLevel(o)}function k(o={}){let e=o.target??console,t=o.writeStderr??(n=>{process.stderr.write(n)});f(o.level??_());let r={log:e.log.bind(e),info:e.info.bind(e),debug:e.debug.bind(e),warn:e.warn.bind(e),error:e.error.bind(e)},l=n=>t(R(...n)+`
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.15.9");process.exit(0)}
2
+ import{a as p}from"./chunk-KTSLTZSG.js";import{e as g}from"./chunk-O3JLOVZX.js";p();import{format as R}from"node:util";var c=2,E={debug:0,info:1,warn:2,warning:2,error:3,silent:4,none:4,off:4},C=new Set(["1","true","yes","on"]),b=/\x1b\[[0-9;]*m/g,N=/^\[(?:\d{2}:\d{2}:\d{2}\.\d{3}|\d{4}-\d{2}-\d{2}T[^\]]+)\]\s+\[(DEBUG|INFO|WARN|ERROR)\s*\]/,O=/^\[[A-Za-z][\w./:-]*\]\s/,S={debug:0,log:1,info:1,warn:2,error:3},d=c;function s(o){if(o)return E[o.trim().toLowerCase()]}function _(o=process.env,e=c){let t=s(o.AQE_LOG_LEVEL)??s(o.LOG_LEVEL);return t!==void 0?t:o.AQE_VERBOSE&&C.has(o.AQE_VERBOSE.trim().toLowerCase())?1:e}function x(o,e){if(typeof e!="string")return null;let t=e.replace(b,""),r=N.exec(t.trimStart());return r?E[r[1].toLowerCase()]:O.test(t)?S[o]:null}function I(o=process.env){return s(o.AQE_LOG_LEVEL)!==void 0||s(o.LOG_LEVEL)!==void 0}function m(o,e=process.env){return o.verbose!==!0||I(e)||a(1)?!1:(f(1),!0)}function a(o){return o>=d&&d!==4}function f(o){d=o,g.setLevel(o)}function k(o={}){let e=o.target??console,t=o.writeStderr??(n=>{process.stderr.write(n)});f(o.level??_());let r={log:e.log.bind(e),info:e.info.bind(e),debug:e.debug.bind(e),warn:e.warn.bind(e),error:e.error.bind(e)},l=n=>t(R(...n)+`
3
3
  `),i=(n,v,w)=>(...L)=>{let u=x(n,L[0]);u===null?v(L):a(u)&&w(L)};return e.log=i("log",n=>r.log(...n),l),e.debug=i("debug",n=>r.debug(...n),l),e.info=i("info",l,l),e.warn=i("warn",n=>r.warn(...n),n=>r.warn(...n)),e.error=i("error",n=>r.error(...n),n=>r.error(...n)),()=>{e.log=r.log,e.info=r.info,e.debug=r.debug,e.warn=r.warn,e.error=r.error}}export{_ as a,m as b,a as c,f as d,k as e};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.9");process.exit(0)}
2
2
  var n=class{constructor(t){this.capacity=t;this.buffer=new Array(t)}capacity;buffer;head=0;tail=0;count=0;push(t){this.buffer[this.tail]=t,this.tail=(this.tail+1)%this.capacity,this.count<this.capacity?this.count++:this.head=(this.head+1)%this.capacity}toArray(){let t=[];for(let e=0;e<this.count;e++){let i=(this.head+e)%this.capacity;t.push(this.buffer[i])}return t}get length(){return this.count}get size(){return this.count}clear(){this.buffer=new Array(this.capacity),this.head=0,this.tail=0,this.count=0}last(t){let e=[],i=Math.max(0,this.count-t);for(let s=i;s<this.count;s++){let r=(this.head+s)%this.capacity;e.push(this.buffer[r])}return e}percentile(t){if(this.count===0)return;let e=this.toArray().sort((s,r)=>Number(s)-Number(r)),i=Math.floor(t/100*(e.length-1));return e[i]}reduce(t,e){let i=e;for(let s=0;s<this.count;s++){let r=(this.head+s)%this.capacity;i=t(i,this.buffer[r])}return i}average(){return this.count===0?0:this.reduce((e,i)=>e+i,0)/this.count}};export{n as a};
@@ -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.15.8");process.exit(0)}
2
- import{a as c,e as h}from"./chunk-DN3AKAPY.js";import{a as l,d}from"./chunk-A2UGPKCS.js";d();h();var u=class{store=new Map;vectors=new Map;cleanupInterval;async initialize(){this.cleanupInterval=setInterval(()=>this.cleanup(),c.CLEANUP_INTERVAL_MS),this.cleanupInterval.unref&&this.cleanupInterval.unref()}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.store.clear(),this.vectors.clear()}async set(t,r,e){let s={value:r,namespace:e?.namespace??"default",createdAt:Date.now()};e?.ttl&&(s.expiresAt=Date.now()+e.ttl*c.TTL_MULTIPLIER_MS);let n=this.buildKey(t,e?.namespace);this.store.set(n,s)}async get(t,r){let e=this.buildKey(t,r?.namespace),s=this.store.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.store.delete(e);return}return s.value}}async delete(t,r){let e=this.buildKey(t,r?.namespace);return this.store.delete(e)}async has(t,r){return await this.get(t,r)!==void 0}async search(t,r=c.DEFAULT_SEARCH_LIMIT,e){let s=t.replace(/[.+^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^${s.replace(/\*/g,".*").replace(/\?/g,".")}$`,"su"),i=[],o=e?.namespace?`${e.namespace}:`:void 0;for(let a of this.store.keys()){if(o&&!a.startsWith(o))continue;let p=o?a.slice(o.length):a;if(n.test(p)&&(i.push(a),i.length>=r))break}return i}async vectorSearch(t,r,e){let s=[];for(let[n,i]of this.vectors.entries()){if(e&&!n.startsWith(e))continue;let o=l(t,i.embedding);s.push({key:n,score:o,metadata:i.metadata})}return s.sort((n,i)=>i.score-n.score).slice(0,r)}getVectorSearchProvenance(){return{backend:"in-memory",indexType:"flat",approximate:!1,estimatedRecall:1}}async storeVector(t,r,e){this.vectors.set(t,{embedding:r,metadata:e})}buildKey(t,r){return r?`${r}:${t}`:t}cleanup(){let t=Date.now();for(let[r,e]of this.store.entries())e.expiresAt&&t>e.expiresAt&&this.store.delete(r)}getStats(){return{entries:this.store.size,vectors:this.vectors.size}}async clear(t){if(t){let r=`${t}:`;for(let e of this.store.keys())e.startsWith(r)&&this.store.delete(e)}else this.store.clear()}async count(t){let r=0,e=`${t}:`;for(let s of this.store.keys())if(s.startsWith(e)){let n=this.store.get(s);n&&(!n.expiresAt||Date.now()<=n.expiresAt)&&r++}return r}async hasCodeIntelligenceIndex(){return await this.count("code-intelligence:kg")>0}};export{u as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.9");process.exit(0)}
2
+ import{a as c,e as h}from"./chunk-7KII4CQG.js";import{a as l,d}from"./chunk-SVHUYVUR.js";d();h();var u=class{store=new Map;vectors=new Map;cleanupInterval;async initialize(){this.cleanupInterval=setInterval(()=>this.cleanup(),c.CLEANUP_INTERVAL_MS),this.cleanupInterval.unref&&this.cleanupInterval.unref()}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.store.clear(),this.vectors.clear()}async set(t,r,e){let s={value:r,namespace:e?.namespace??"default",createdAt:Date.now()};e?.ttl&&(s.expiresAt=Date.now()+e.ttl*c.TTL_MULTIPLIER_MS);let n=this.buildKey(t,e?.namespace);this.store.set(n,s)}async get(t,r){let e=this.buildKey(t,r?.namespace),s=this.store.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.store.delete(e);return}return s.value}}async delete(t,r){let e=this.buildKey(t,r?.namespace);return this.store.delete(e)}async has(t,r){return await this.get(t,r)!==void 0}async search(t,r=c.DEFAULT_SEARCH_LIMIT,e){let s=t.replace(/[.+^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^${s.replace(/\*/g,".*").replace(/\?/g,".")}$`,"su"),i=[],o=e?.namespace?`${e.namespace}:`:void 0;for(let a of this.store.keys()){if(o&&!a.startsWith(o))continue;let p=o?a.slice(o.length):a;if(n.test(p)&&(i.push(a),i.length>=r))break}return i}async vectorSearch(t,r,e){let s=[];for(let[n,i]of this.vectors.entries()){if(e&&!n.startsWith(e))continue;let o=l(t,i.embedding);s.push({key:n,score:o,metadata:i.metadata})}return s.sort((n,i)=>i.score-n.score).slice(0,r)}getVectorSearchProvenance(){return{backend:"in-memory",indexType:"flat",approximate:!1,estimatedRecall:1}}async storeVector(t,r,e){this.vectors.set(t,{embedding:r,metadata:e})}buildKey(t,r){return r?`${r}:${t}`:t}cleanup(){let t=Date.now();for(let[r,e]of this.store.entries())e.expiresAt&&t>e.expiresAt&&this.store.delete(r)}getStats(){return{entries:this.store.size,vectors:this.vectors.size}}async clear(t){if(t){let r=`${t}:`;for(let e of this.store.keys())e.startsWith(r)&&this.store.delete(e)}else this.store.clear()}async count(t){let r=0,e=`${t}:`;for(let s of this.store.keys())if(s.startsWith(e)){let n=this.store.get(s);n&&(!n.expiresAt||Date.now()<=n.expiresAt)&&r++}return r}async hasCodeIntelligenceIndex(){return await this.count("code-intelligence:kg")>0}};export{u as a};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
2
- import{a as v,b as I,e as O}from"./chunk-J7FLNP5L.js";var x={reflexThreshold:.1,retrievalThreshold:.4,heavyThreshold:.7},V={enabled:!0,laneConfig:x,coherenceThreshold:.1,fallbackEnabled:!0,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},p={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},b=class extends Error{constructor(t,i,n){super(t);this.code=i;this.cause=n;this.name="CoherenceError"}code;cause},h=class extends b{constructor(e="WASM module is not loaded",t){super(e,"WASM_NOT_LOADED",t),this.name="WasmNotLoadedError"}};var k=class extends b{constructor(t,i,n){super(t,"WASM_LOAD_FAILED",n);this.attempts=i;this.name="WasmLoadError"}attempts},G={maxAttempts:3,baseDelayMs:100,maxDelayMs:5e3,timeoutMs:1e4};O();var H=4*1024*1024,j=32*1024*1024;function J(d){let e=new Map,t=[],i=new Map,n=new Map,r=0,a=s=>{let o=i.get(s);return o===void 0&&(o=r++,i.set(s,o),n.set(o,s)),o},l=s=>n.get(s)??`unknown-${s}`;function*c(){i.clear(),n.clear(),r=0;let s=e.values().next().value?.embedding.length,o=Array.from(e.entries()).map(([g,y])=>{if(y.embedding.length!==s)throw new RangeError("Cohomology graphs require matching embedding dimensions");return{id:a(g),label:g,section:Array.from(y.embedding),weight:1}}),u=0,m=t.map(g=>{let y=e.get(g.source),C=e.get(g.target);if(!y||!C)throw new Error(`Cohomology edge references an unknown node: ${g.source} -> ${g.target}`);let D=y.embedding.length,N=D*D;if(N>H)throw new RangeError(`Cohomology restriction map exceeds ${H} cells`);if(u+=N,u>j)throw new RangeError(`Cohomology graph exceeds ${j} restriction-map cells`);return{...g,dimension:D,cells:N}}),f=[],F=0,P=new Map;for(let g of m){F+g.cells>H&&(yield{nodes:o,edges:f},f=[],F=0,P.clear());let y=P.get(g.dimension);if(!y){y=Array(g.cells).fill(0);for(let C=0;C<g.dimension;C++)y[C*g.dimension+C]=1;P.set(g.dimension,y)}f.push({source:i.get(g.source),target:i.get(g.target),weight:g.weight,restriction_map:y,source_dim:g.dimension,target_dim:g.dimension}),F+=g.cells}(f.length>0||m.length===0)&&(yield{nodes:o,edges:f})}return{add_node(s,o){e.set(s,{embedding:o}),a(s)},add_edge(s,o,u){t.push({source:s,target:o,weight:u}),a(s),a(o)},remove_node(s){e.delete(s);for(let o=t.length-1;o>=0;o--)(t[o].source===s||t[o].target===s)&&t.splice(o,1)},remove_edge(s,o){let u=t.findIndex(m=>m.source===s&&m.target===o);u>=0&&t.splice(u,1)},sheaf_laplacian_energy(){let s=0;for(let o of c())s+=d.consistencyEnergy(o);return s},detect_contradictions(s){let o=[];for(let u of c()){let m=d.detectObstructions(u);for(let f of m??[])f.magnitude>s&&o.push({node1:l(f.source_node),node2:l(f.target_node),severity:f.magnitude,distance:f.magnitude})}return o.sort((u,m)=>m.distance-u.distance)},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var w=class{constructor(e,t=p){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;nodes=new Map;edges=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CohomologyAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CohomologyAdapter.");let t=await this.wasmLoader.load(),i=new t.CohomologyEngine;this.engine=J(i),this.initialized=!0,this.logger.info("CohomologyAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CohomologyAdapter not initialized. Call initialize() first.")}addNode(e){this.ensureInitialized(),this.nodes.set(e.id,e);let t=new Float64Array(e.embedding);this.engine.add_node(e.id,t),this.logger.debug("Added node to cohomology graph",{nodeId:e.id,embeddingDim:e.embedding.length})}addEdge(e){this.ensureInitialized(),this.edges.push(e),this.engine.add_edge(e.source,e.target,e.weight),this.logger.debug("Added edge to cohomology graph",{source:e.source,target:e.target,weight:e.weight})}removeNode(e){this.ensureInitialized(),this.nodes.delete(e),this.engine.remove_node(e);let t=[];this.edges.forEach((i,n)=>{(i.source===e||i.target===e)&&t.push(n)}),t.reverse().forEach(i=>this.edges.splice(i,1)),this.logger.debug("Removed node from cohomology graph",{nodeId:e})}removeEdge(e,t){this.ensureInitialized();let i=this.edges.findIndex(n=>n.source===e&&n.target===t);i>=0&&this.edges.splice(i,1),this.engine.remove_edge(e,t),this.logger.debug("Removed edge from cohomology graph",{source:e,target:t})}computeEnergy(){this.ensureInitialized();let e=this.engine.sheaf_laplacian_energy();return this.logger.debug("Computed sheaf Laplacian energy",{energy:e}),e}detectContradictions(e=.1){this.ensureInitialized();let i=this.engine.detect_contradictions(e).map(n=>this.transformContradiction(n));return this.logger.debug("Detected contradictions",{count:i.length,threshold:e}),i}transformContradiction(e){return{nodeIds:[e.node1,e.node2],severity:this.severityFromDistance(e.severity),description:this.generateContradictionDescription(e),confidence:Math.max(0,1-e.distance),resolution:this.suggestResolution(e)}}severityFromDistance(e){return e>=.9?"critical":e>=.7?"high":e>=.4?"medium":e>=.2?"low":"info"}generateContradictionDescription(e){let t=this.nodes.get(e.node1),i=this.nodes.get(e.node2);return t?.metadata?.statement&&i?.metadata?.statement?`Contradiction detected between "${t.metadata.statement}" and "${i.metadata.statement}"`:`Contradiction detected between nodes '${e.node1}' and '${e.node2}' with distance ${e.distance.toFixed(3)}`}suggestResolution(e){return e.severity>=.9?"Critical contradiction requires manual review. Consider removing one of the conflicting beliefs.":e.severity>=.7?"High-severity contradiction. Recommend gathering additional evidence to determine which belief is correct.":e.severity>=.4?"Moderate contradiction. Consider adding context or constraints to differentiate the beliefs.":"Low-severity contradiction. May be resolved with additional context or can be safely ignored."}clear(){this.ensureInitialized(),this.nodes.clear(),this.edges.length=0,this.engine.clear(),this.logger.debug("Cleared cohomology graph")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.nodes.clear(),this.edges.length=0,this.initialized=!1,this.logger.info("CohomologyAdapter disposed")}getNodeCount(){return this.nodes.size}getEdgeCount(){return this.edges.length}getNode(e){return this.nodes.get(e)}};O();function Z(d){let e=new Set,t=[],i=new Map,n=new Map,r=0,a=s=>{let o=i.get(s);return o===void 0&&(o=r++,i.set(s,o),n.set(o,s)),o},l=s=>n.get(s)??`unknown-${s}`,c=()=>({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,o,u){t.push({source:s,target:o,weight:u}),a(s),a(o)},remove_node(s){e.delete(s);for(let o=t.length-1;o>=0;o--)(t[o].source===s||t[o].target===s)&&t.splice(o,1)},compute_fiedler_value(){if(e.size<2||t.length===0)return 0;try{let s=c(),o=d.algebraicConnectivity(s);return Number.isFinite(o)&&o>=0?o: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=c(),o=d.algebraicConnectivity(s),u=Number.isFinite(o)&&o>=0?o:0;return Math.max(0,Math.min(1,1-u))}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 o=c(),u=d.predictMinCut(o);return u?.vertices?u.vertices.slice(0,s).map(m=>l(m)):Array.from(e).slice(0,s)}catch(o){return console.warn("[SpectralAdapter] predictMinCut failed:",o),Array.from(e).slice(0,s)}},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var E=class{constructor(e,t=p){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;nodes=new Set;edges=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing SpectralAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize SpectralAdapter.");let t=await this.wasmLoader.load(),i=new t.SpectralEngine;this.engine=Z(i),this.initialized=!0,this.logger.info("SpectralAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("SpectralAdapter not initialized. Call initialize() first.")}addNode(e){if(this.ensureInitialized(),this.nodes.has(e)){this.logger.debug("Node already exists",{nodeId:e});return}this.nodes.add(e),this.engine.add_node(e),this.logger.debug("Added node to spectral graph",{nodeId:e})}addEdge(e,t,i){this.ensureInitialized(),this.nodes.has(e)||this.addNode(e),this.nodes.has(t)||this.addNode(t),this.edges.push({source:e,target:t,weight:i}),this.engine.add_edge(e,t,i),this.logger.debug("Added edge to spectral graph",{source:e,target:t,weight:i})}removeNode(e){this.ensureInitialized(),this.nodes.delete(e),this.engine.remove_node(e);for(let t=this.edges.length-1;t>=0;t--){let i=this.edges[t];(i.source===e||i.target===e)&&this.edges.splice(t,1)}this.logger.debug("Removed node from spectral graph",{nodeId:e})}computeFiedlerValue(){if(this.ensureInitialized(),this.nodes.size<2||this.edges.length===0)return 0;try{let e=this.engine.compute_fiedler_value();return this.logger.debug("Computed Fiedler value",{fiedlerValue:e}),e}catch(e){return this.logger.warn("Failed to compute Fiedler value",{error:v(e),nodeCount:this.nodes.size,edgeCount:this.edges.length}),0}}predictCollapseRisk(){if(this.ensureInitialized(),this.nodes.size<2)return 0;if(this.edges.length===0)return 1;try{let e=this.engine.predict_collapse_risk();return this.logger.debug("Predicted collapse risk",{risk:e}),e}catch(e){return this.logger.warn("Failed to predict collapse risk",{error:v(e),nodeCount:this.nodes.size,edgeCount:this.edges.length}),.8}}getWeakVertices(e){if(this.ensureInitialized(),this.nodes.size===0)return[];if(this.edges.length===0)return Array.from(this.nodes).slice(0,e);let t=Math.min(e,this.nodes.size);try{let i=this.engine.get_weak_vertices(t);return this.logger.debug("Retrieved weak vertices",{requested:e,returned:i.length}),i}catch(i){return this.logger.warn("Failed to get weak vertices",{error:v(i),nodeCount:this.nodes.size,edgeCount:this.edges.length}),Array.from(this.nodes).slice(0,e)}}analyzeSwarmState(e){let t=Date.now();this.clear();for(let c of e.agents)this.addNode(c.agentId);this.buildEdgesFromAgents(e.agents);let i=this.predictCollapseRisk(),n=this.computeFiedlerValue(),r=this.getWeakVertices(5),a=Date.now()-t,l={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}),l}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,l=e.beliefs??[],c=t.beliefs??[];return l.length>0&&c.length>0&&(a=this.computeBeliefOverlap(l,c)),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 l=0;l<e.length;l++)i+=e[l]*t[l],n+=e[l]*e[l],r+=t[l]*t[l];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 ee(d){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 d.computeCausalEffect(r,"cause","effect",1)?.effect??0},detect_spurious_correlation(){let r=n();return(d.findConfounders(r,"cause","effect")?.length??0)>0},get_confounders(){let r=n();return d.findConfounders(r,"cause","effect")??Array.from(i.keys())},clear(){e=null,t=null,i.clear()}}}var A=class{constructor(e,t=p){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;currentCause="";currentEffect="";async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CausalAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CausalAdapter.");let t=await this.wasmLoader.load(),i=new t.CausalEngine;this.engine=ee(i),this.initialized=!0,this.logger.info("CausalAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CausalAdapter not initialized. Call initialize() first.")}verifyCausality(e,t,i){this.ensureInitialized();let n=Date.now();if(this.clear(),this.currentCause=e,this.currentEffect=t,this.setData(i.causeValues,i.effectValues),i.confounders)for(let[m,f]of Object.entries(i.confounders))this.addConfounder(m,f);let r=this.computeCausalEffect(),a=this.detectSpuriousCorrelation(),l=this.getConfounders(),c=this.determineRelationshipType(r,a,l.length>0),s=this.computeConfidence(i.sampleSize,r,a),o=Date.now()-n,u={isCausal:c==="causal",effectStrength:r,relationshipType:c,confidence:s,confounders:l,explanation:this.generateExplanation(e,t,c,r,l),durationMs:o,usedFallback:!1};return this.logger.info("Verified causality",{cause:e,effect:t,isCausal:u.isCausal,relationshipType:c,effectStrength:r,durationMs:o}),u}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 te(d){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 l=n[a],c=n[a+1];if(!t.some(o=>o.source===l&&o.target===c))return!1}let r=i();return d.verifyCategoryLaws(r)},check_type_consistency(){let n=[];for(let r of t)e.has(r.source)||n.push({location:r.name,expected:"defined type",actual:`undefined type '${r.source}'`}),e.has(r.target)||n.push({location:r.name,expected:"defined type",actual:`undefined type '${r.target}'`});return n},clear(){e.clear(),t.length=0}}}var T=class{constructor(e,t=p){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;types=new Map;morphisms=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CategoryAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CategoryAdapter.");let t=await this.wasmLoader.load(),i=new t.CategoryEngine;this.engine=te(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),l=Date.now()-t,c={isValid:n&&r.length===0,mismatches:r,warnings:a,durationMs:l,usedFallback:!1};return this.logger.info("Verified pipeline",{pipelineId:e.id,isValid:c.isValid,mismatchCount:r.length,warningCount:a.length,durationMs:l}),c}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 ie(d){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},l={formula:r.formula};return d.typeCheck(a,l)?.valid?(r.proven=!0,t.set(i,n),!0):!1},verify_path_equivalence(i,n){let r={steps:i},a={steps:n};return d.checkTypeEquivalence(r,a)},get_unproven_propositions(){let i=[];return e.forEach((n,r)=>{n.proven||i.push(r)}),i},clear(){e.clear(),t.clear()}}}var R=class{constructor(e,t=p){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;propositions=new Map;async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing HomotopyAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize HomotopyAdapter.");let t=await this.wasmLoader.load(),i=new t.HoTTEngine;this.engine=ie(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 ne}from"crypto";var S=class{constructor(e,t=p){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;witnesses=new Map;decisions=new Map;witnessCounter=0;async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing WitnessAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize WitnessAdapter.");let t=await this.wasmLoader.load();this.engine=this.createWitnessEngine(t),this.initialized=!0,this.logger.info("WitnessAdapter initialized successfully")}createWitnessEngine(e){return this.createFallbackEngine()}createFallbackEngine(){let e=[];return{create_witness:(t,i)=>{let r={hash:this.computeHash(t,i),previousHash:i,position:e.length,timestamp:Date.now()};return e.push(r),r},verify_witness:(t,i)=>{let n=e.find(a=>a.hash===i);return this.computeHash(t,n?.previousHash)===i},verify_chain:t=>{if(t.length===0)return!0;if(t[0].previousHash!==void 0)return!1;for(let i=1;i<t.length;i++)if(t[i].previousHash!==t[i-1].hash)return!1;return!0},get_chain_length:()=>e.length}}computeHash(e,t){let i=ne("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()}`,l={witnessId:a,decisionId:e.id,hash:r.hash,previousWitnessId:i?.witnessId,chainPosition:r.position,timestamp:new Date(r.timestamp)};return this.witnesses.set(a,l),this.decisions.set(e.id,e),this.logger.info("Created witness",{witnessId:a,decisionId:e.id,chainPosition:l.chainPosition}),l}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,l={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}),l}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")}};function $(d){let e=new Map;for(let r of d){let a=String(r.verdict);e.set(a,(e.get(a)??0)+1)}let t=[...e.entries()].map(([r,a])=>({verdict:r,count:a})).sort((r,a)=>a.count-r.count||r.verdict.localeCompare(a.verdict)),i=t[0]??{verdict:"",count:0},n=d.length;return{total:n,counts:t,topVerdict:i.verdict,topCount:i.count,majorityRatio:n>0?i.count/n:0,isUnanimous:t.length===1}}function L(d){return`${d.topCount} of ${d.total} votes '${d.topVerdict}'`}function U(d){return d.counts.map(({verdict:e,count:t})=>`${t} '${e}'`).join(" / ")}var Y=.6,ce=3;function Q(d){return d.isUnanimous&&d.total>=ce}function _(d){return d.isUnanimous?L(d):`${L(d)}; ${U(d)}`}var W=class{constructor(e,t={},i){this.wasmLoader=e;this.config={...V,...t},this.logger=i||p}wasmLoader;config;logger;cohomologyAdapter=null;spectralAdapter=null;causalAdapter=null;categoryAdapter=null;homotopyAdapter=null;witnessAdapter=null;initialized=!1;stats={totalChecks:0,coherentCount:0,incoherentCount:0,averageEnergy:0,averageDurationMs:0,totalContradictions:0,laneDistribution:{reflex:0,retrieval:0,heavy:0,human:0},fallbackCount:0,wasmAvailable:!1};totalEnergySum=0;totalDurationSum=0;async initialize(){if(this.initialized)return;this.logger.info("Initializing CoherenceService");let e=await this.wasmLoader.isAvailable();if(!e&&!this.config.fallbackEnabled)throw new h("WASM module is not available and fallback is disabled. Enable fallbackEnabled in config to use TypeScript fallback.");if(this.stats.wasmAvailable=e,e)try{this.cohomologyAdapter=new w(this.wasmLoader,this.logger),this.spectralAdapter=new E(this.wasmLoader,this.logger),this.causalAdapter=new A(this.wasmLoader,this.logger),this.categoryAdapter=new T(this.wasmLoader,this.logger),this.homotopyAdapter=new R(this.wasmLoader,this.logger),this.witnessAdapter=new S(this.wasmLoader,this.logger),await Promise.all([this.cohomologyAdapter.initialize(),this.spectralAdapter.initialize(),this.causalAdapter.initialize(),this.categoryAdapter.initialize(),this.homotopyAdapter.initialize(),this.witnessAdapter.initialize()]),this.logger.info("All coherence engine adapters initialized")}catch(t){if(!this.config.fallbackEnabled)throw t;this.logger.warn("WASM initialization failed, using fallback",{error:t instanceof Error?t.message:"Unknown error"}),this.stats.wasmAvailable=!1}else this.logger.info("WASM not available, using TypeScript fallback");this.initialized=!0,this.logger.info("CoherenceService initialized",{wasmAvailable:this.stats.wasmAvailable,fallbackEnabled:this.config.fallbackEnabled})}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized)throw new b("CoherenceService not initialized. Call initialize() first.","NOT_INITIALIZED")}async checkCoherence(e){this.ensureInitialized();let t=Date.now();try{return this.cohomologyAdapter?.isInitialized()?await this.checkCoherenceWithWasm(e,t):this.checkCoherenceWithFallback(e,t)}catch(i){return this.logger.error("Coherence check failed",I(i)),{energy:1,isCoherent:!1,lane:"human",contradictions:[],recommendations:["Coherence check failed. Manual review recommended."],durationMs:Date.now()-t,usedFallback:!0}}}async checkCoherenceWithWasm(e,t){this.cohomologyAdapter.clear();for(let l of e)this.cohomologyAdapter.addNode(l);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 o=s+1;o<e.length;o++){let u=this.euclideanDistance(e[s].embedding,e[o].embedding);i+=u,n++,u>1.5&&r.push({nodeIds:[e[s].id,e[o].id],severity:u>2?"critical":"high",description:`High distance (${u.toFixed(2)}) between nodes`,confidence:Math.min(1,u/2)})}let a=n>0?i/n:0,l=this.computeLane(a),c=Date.now()-t;return this.updateStats(a,c,r.length,l,!0),{energy:a,isCoherent:a<this.config.coherenceThreshold,lane:l,contradictions:r,recommendations:this.generateRecommendations(a,l,r),durationMs:c,usedFallback:!0}}buildEdgesFromNodes(e){for(let t=0;t<e.length;t++)for(let i=t+1;i<e.length;i++){let n=this.cosineSimilarity(e[t].embedding,e[i].embedding);n>.3&&this.cohomologyAdapter.addEdge({source:e[t].id,target:e[i].id,weight:n})}}async detectContradictions(e){this.ensureInitialized();let t=e.map(n=>({id:n.id,embedding:n.embedding,weight:n.confidence,metadata:{statement:n.statement,source:n.source}}));return(await this.checkCoherence(t)).contradictions}async predictCollapse(e){if(this.ensureInitialized(),!e.agents||e.agents.length===0)return{risk:0,fiedlerValue:0,collapseImminent:!1,weakVertices:[],recommendations:["No agents to analyze"],durationMs:0,usedFallback:!0};if(this.spectralAdapter?.isInitialized())try{return this.spectralAdapter.analyzeSwarmState(e)}catch(t){return this.logger.warn("Spectral collapse prediction failed, using fallback",{error:v(t),agentCount:e.agents.length}),this.predictCollapseWithFallback(e)}return this.predictCollapseWithFallback(e)}predictCollapseWithFallback(e){let t=Date.now(),i=e.agents.reduce((l,c)=>l+c.health,0)/Math.max(e.agents.length,1),n=e.agents.reduce((l,c)=>l+c.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(l=>l.health<.5||l.successRate<.5).map(l=>l.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 o of e)this.spectralAdapter.addNode(o.agentId);let i=0;for(let o=0;o<e.length;o++)for(let u=o+1;u<e.length;u++)e[o].verdict===e[u].verdict&&(this.spectralAdapter.addEdge(e[o].agentId,e[u].agentId,Math.min(e[o].confidence,e[u].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(),a=$(e);if(a.isUnanimous&&e.every(o=>o.confidence>0)&&!(r>0))return this.logger.warn("Spectral engine returned a zero Fiedler value for a connected agreement graph, using fallback",{fiedlerValue:r,voteCount:e.length}),this.verifyConsensusWithFallback(e,t);let l=n<.3&&r>.1,c=Q(a),s;return l?c?s=`Consensus verified (${_(a)}), but unanimous agreement may indicate false consensus. Consider adding diversity.`:s=`Consensus verified (${_(a)}).`:s=`No verified consensus (${_(a)}): agreement-graph Fiedler value ${r.toFixed(3)}, collapse risk ${n.toFixed(2)}. Spawn independent reviewer.`,{isValid:l,confidence:1-n,isFalseConsensus:c,fiedlerValue:r,collapseRisk:n,recommendation:s,durationMs:Date.now()-t,usedFallback:!1}}catch(i){return this.logger.warn("Spectral consensus verification failed, using fallback",{error:v(i),voteCount:e.length}),this.verifyConsensusWithFallback(e,t)}return this.verifyConsensusWithFallback(e,t)}verifyConsensusWithFallback(e,t){let i=$(e),{majorityRatio:n}=i,r=e.reduce((s,o)=>s+o.confidence,0)/e.length,a=n>Y,l=Q(i),c;return a?l?c=`Unanimous consensus (${L(i)}) may indicate false consensus. Consider adding diversity.`:i.isUnanimous?c=`Unanimous consensus achieved (${L(i)}).`:c=`Majority consensus achieved (${_(i)}).`:c=`No clear majority: ${U(i)} across ${i.total} votes (needs more than ${Math.round(Y*100)}% agreeing). Consider spawning additional agents.`,{isValid:a,confidence:n*r,isFalseConsensus:l,fiedlerValue:n,collapseRisk:1-n,recommendation:c,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(l=>r.add(l));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 l=0;l<e.length;l++)i+=e[l]*t[l],n+=e[l]*e[l],r+=t[l]*t[l];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((o,u)=>o+u,0)/i,r=t.reduce((o,u)=>o+u,0)/i,a=0,l=0,c=0;for(let o=0;o<i;o++){let u=e[o]-n,m=t[o]-r;a+=u*m,l+=u*u,c+=m*m}let s=Math.sqrt(l*c);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 ue(d,e,t){let i=new W(d,e,t);return await i.initialize(),i}O();import{createRequire as K}from"node:module";import{fileURLToPath as he}from"node:url";import{dirname as q,join as M}from"node:path";import{readFileSync as ge,existsSync as X}from"node:fs";var B=[1e3,2e3,4e3],z=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={...G,...e},this.eventListeners=new Map,this.eventListeners.set("loaded",new Set),this.eventListeners.set("error",new Set),this.eventListeners.set("retry",new Set),this.eventListeners.set("degraded_mode",new Set),this.eventListeners.set("recovered",new Set)}isLoaded(){return this.state==="loaded"&&this.engines!==null}getState(){return this.state}getVersion(){return this.version}getLastError(){return this.lastError}isInDegradedMode(){return this.state==="degraded"||this.fallbackState.mode==="fallback"}getFallbackState(){return{...this.fallbackState}}getFallbackResult(){return{usedFallback:!0,confidence:.5,retryCount:this.fallbackState.consecutiveFailures,lastError:this.lastError?.message,activatedAt:this.degradedModeStartTime??new Date}}async getEngines(){if(this.state==="loaded"&&this.engines)return this.engines;if(this.state==="loading"&&this.loadPromise)return this.loadPromise;this.state="loading",this.loadPromise=this.loadWithRetry();try{return this.engines=await this.loadPromise,this.state="loaded",(this.fallbackState.mode==="fallback"||this.fallbackState.mode==="recovering")&&this.emitRecoveryEvent(),this.fallbackState.mode="wasm",this.fallbackState.consecutiveFailures=0,this.fallbackState.lastSuccessfulLoad=new Date,this.engines}catch(e){throw this.state="failed",this.lastError=I(e),this.enterDegradedMode(this.lastError),e}finally{this.loadPromise=null}}async getEnginesWithFallback(){if(this.state==="loaded"&&this.engines)return{engines:this.engines,fallback:{usedFallback:!1,confidence:1,retryCount:0}};if(this.state==="degraded")return{engines:null,fallback:this.getFallbackResult()};try{return{engines:await this.getEngines(),fallback:{usedFallback:!1,confidence:1,retryCount:0}}}catch{return{engines:null,fallback:this.getFallbackResult()}}}getEnginesSync(){if(!this.engines)throw new h("WASM module is not loaded. Call getEngines() first.");return this.engines}async isAvailable(){if(this.state==="loaded"&&this.wasmModule)return!0;if(this.state==="failed")return!1;try{let e=K(import.meta.url),t=[(()=>{try{let i=e.resolve("prime-radiant-advanced-wasm");return M(q(i),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),M(process.cwd(),"node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm")].filter(i=>i!==null);for(let i of t)if(X(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(),l=await this.attemptLoad(),c=performance.now()-a;return this.emit("loaded",{version:this.version,loadTimeMs:Math.round(c*100)/100}),l}catch(a){if(n=I(a),this.emit("error",{error:n,fatal:r>=e,attempt:r}),r<e){let l=Math.min(t*Math.pow(2,r-1),i);this.emit("retry",{attempt:r+1,maxAttempts:e,delayMs:l,previousError:n}),await this.sleep(l)}}throw new k(`Failed to load WASM module after ${e} attempts: ${n.message}`,e,n)}async attemptLoad(){let e;try{e=K(import.meta.url)}catch{e=globalThis.require||(await import("module")).createRequire(__filename)}let t;try{t=await import("./prime-radiant-advanced-wasm-PDFSYWKZ.js")}catch(r){try{t=e("prime-radiant-advanced-wasm")}catch{throw new Error(`Failed to import prime-radiant-advanced-wasm: ${v(r)}`)}}if(typeof process<"u"&&process.versions!=null&&process.versions.node!=null?await this.initializeForNodeJs(t,e):t.default&&typeof t.default=="function"&&await t.default(),t.initModule&&typeof t.initModule=="function")try{t.initModule()}catch{}return t.getVersion&&typeof t.getVersion=="function"&&(this.version=t.getVersion()),this.wasmModule=t,{cohomology:new t.CohomologyEngine,spectral:new t.SpectralEngine,causal:new t.CausalEngine,category:new t.CategoryEngine,hott:new t.HoTTEngine,quantum:new t.QuantumEngine}}async initializeForNodeJs(e,t){let i=[(()=>{try{let a=t.resolve("prime-radiant-advanced-wasm");return M(q(a),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),M(q(he(import.meta.url)),"../../../../node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm"),M(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(X(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.15.9");process.exit(0)}
2
+ import{a as v,b as I,e as O}from"./chunk-N3KEY4XJ.js";var x={reflexThreshold:.1,retrievalThreshold:.4,heavyThreshold:.7},V={enabled:!0,laneConfig:x,coherenceThreshold:.1,fallbackEnabled:!0,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},p={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},b=class extends Error{constructor(t,i,n){super(t);this.code=i;this.cause=n;this.name="CoherenceError"}code;cause},h=class extends b{constructor(e="WASM module is not loaded",t){super(e,"WASM_NOT_LOADED",t),this.name="WasmNotLoadedError"}};var k=class extends b{constructor(t,i,n){super(t,"WASM_LOAD_FAILED",n);this.attempts=i;this.name="WasmLoadError"}attempts},G={maxAttempts:3,baseDelayMs:100,maxDelayMs:5e3,timeoutMs:1e4};O();var H=4*1024*1024,j=32*1024*1024;function J(d){let e=new Map,t=[],i=new Map,n=new Map,r=0,a=s=>{let o=i.get(s);return o===void 0&&(o=r++,i.set(s,o),n.set(o,s)),o},l=s=>n.get(s)??`unknown-${s}`;function*c(){i.clear(),n.clear(),r=0;let s=e.values().next().value?.embedding.length,o=Array.from(e.entries()).map(([g,y])=>{if(y.embedding.length!==s)throw new RangeError("Cohomology graphs require matching embedding dimensions");return{id:a(g),label:g,section:Array.from(y.embedding),weight:1}}),u=0,m=t.map(g=>{let y=e.get(g.source),C=e.get(g.target);if(!y||!C)throw new Error(`Cohomology edge references an unknown node: ${g.source} -> ${g.target}`);let D=y.embedding.length,N=D*D;if(N>H)throw new RangeError(`Cohomology restriction map exceeds ${H} cells`);if(u+=N,u>j)throw new RangeError(`Cohomology graph exceeds ${j} restriction-map cells`);return{...g,dimension:D,cells:N}}),f=[],F=0,P=new Map;for(let g of m){F+g.cells>H&&(yield{nodes:o,edges:f},f=[],F=0,P.clear());let y=P.get(g.dimension);if(!y){y=Array(g.cells).fill(0);for(let C=0;C<g.dimension;C++)y[C*g.dimension+C]=1;P.set(g.dimension,y)}f.push({source:i.get(g.source),target:i.get(g.target),weight:g.weight,restriction_map:y,source_dim:g.dimension,target_dim:g.dimension}),F+=g.cells}(f.length>0||m.length===0)&&(yield{nodes:o,edges:f})}return{add_node(s,o){e.set(s,{embedding:o}),a(s)},add_edge(s,o,u){t.push({source:s,target:o,weight:u}),a(s),a(o)},remove_node(s){e.delete(s);for(let o=t.length-1;o>=0;o--)(t[o].source===s||t[o].target===s)&&t.splice(o,1)},remove_edge(s,o){let u=t.findIndex(m=>m.source===s&&m.target===o);u>=0&&t.splice(u,1)},sheaf_laplacian_energy(){let s=0;for(let o of c())s+=d.consistencyEnergy(o);return s},detect_contradictions(s){let o=[];for(let u of c()){let m=d.detectObstructions(u);for(let f of m??[])f.magnitude>s&&o.push({node1:l(f.source_node),node2:l(f.target_node),severity:f.magnitude,distance:f.magnitude})}return o.sort((u,m)=>m.distance-u.distance)},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var w=class{constructor(e,t=p){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;nodes=new Map;edges=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CohomologyAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CohomologyAdapter.");let t=await this.wasmLoader.load(),i=new t.CohomologyEngine;this.engine=J(i),this.initialized=!0,this.logger.info("CohomologyAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CohomologyAdapter not initialized. Call initialize() first.")}addNode(e){this.ensureInitialized(),this.nodes.set(e.id,e);let t=new Float64Array(e.embedding);this.engine.add_node(e.id,t),this.logger.debug("Added node to cohomology graph",{nodeId:e.id,embeddingDim:e.embedding.length})}addEdge(e){this.ensureInitialized(),this.edges.push(e),this.engine.add_edge(e.source,e.target,e.weight),this.logger.debug("Added edge to cohomology graph",{source:e.source,target:e.target,weight:e.weight})}removeNode(e){this.ensureInitialized(),this.nodes.delete(e),this.engine.remove_node(e);let t=[];this.edges.forEach((i,n)=>{(i.source===e||i.target===e)&&t.push(n)}),t.reverse().forEach(i=>this.edges.splice(i,1)),this.logger.debug("Removed node from cohomology graph",{nodeId:e})}removeEdge(e,t){this.ensureInitialized();let i=this.edges.findIndex(n=>n.source===e&&n.target===t);i>=0&&this.edges.splice(i,1),this.engine.remove_edge(e,t),this.logger.debug("Removed edge from cohomology graph",{source:e,target:t})}computeEnergy(){this.ensureInitialized();let e=this.engine.sheaf_laplacian_energy();return this.logger.debug("Computed sheaf Laplacian energy",{energy:e}),e}detectContradictions(e=.1){this.ensureInitialized();let i=this.engine.detect_contradictions(e).map(n=>this.transformContradiction(n));return this.logger.debug("Detected contradictions",{count:i.length,threshold:e}),i}transformContradiction(e){return{nodeIds:[e.node1,e.node2],severity:this.severityFromDistance(e.severity),description:this.generateContradictionDescription(e),confidence:Math.max(0,1-e.distance),resolution:this.suggestResolution(e)}}severityFromDistance(e){return e>=.9?"critical":e>=.7?"high":e>=.4?"medium":e>=.2?"low":"info"}generateContradictionDescription(e){let t=this.nodes.get(e.node1),i=this.nodes.get(e.node2);return t?.metadata?.statement&&i?.metadata?.statement?`Contradiction detected between "${t.metadata.statement}" and "${i.metadata.statement}"`:`Contradiction detected between nodes '${e.node1}' and '${e.node2}' with distance ${e.distance.toFixed(3)}`}suggestResolution(e){return e.severity>=.9?"Critical contradiction requires manual review. Consider removing one of the conflicting beliefs.":e.severity>=.7?"High-severity contradiction. Recommend gathering additional evidence to determine which belief is correct.":e.severity>=.4?"Moderate contradiction. Consider adding context or constraints to differentiate the beliefs.":"Low-severity contradiction. May be resolved with additional context or can be safely ignored."}clear(){this.ensureInitialized(),this.nodes.clear(),this.edges.length=0,this.engine.clear(),this.logger.debug("Cleared cohomology graph")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.nodes.clear(),this.edges.length=0,this.initialized=!1,this.logger.info("CohomologyAdapter disposed")}getNodeCount(){return this.nodes.size}getEdgeCount(){return this.edges.length}getNode(e){return this.nodes.get(e)}};O();function Z(d){let e=new Set,t=[],i=new Map,n=new Map,r=0,a=s=>{let o=i.get(s);return o===void 0&&(o=r++,i.set(s,o),n.set(o,s)),o},l=s=>n.get(s)??`unknown-${s}`,c=()=>({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,o,u){t.push({source:s,target:o,weight:u}),a(s),a(o)},remove_node(s){e.delete(s);for(let o=t.length-1;o>=0;o--)(t[o].source===s||t[o].target===s)&&t.splice(o,1)},compute_fiedler_value(){if(e.size<2||t.length===0)return 0;try{let s=c(),o=d.algebraicConnectivity(s);return Number.isFinite(o)&&o>=0?o: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=c(),o=d.algebraicConnectivity(s),u=Number.isFinite(o)&&o>=0?o:0;return Math.max(0,Math.min(1,1-u))}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 o=c(),u=d.predictMinCut(o);return u?.vertices?u.vertices.slice(0,s).map(m=>l(m)):Array.from(e).slice(0,s)}catch(o){return console.warn("[SpectralAdapter] predictMinCut failed:",o),Array.from(e).slice(0,s)}},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var E=class{constructor(e,t=p){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;nodes=new Set;edges=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing SpectralAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize SpectralAdapter.");let t=await this.wasmLoader.load(),i=new t.SpectralEngine;this.engine=Z(i),this.initialized=!0,this.logger.info("SpectralAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("SpectralAdapter not initialized. Call initialize() first.")}addNode(e){if(this.ensureInitialized(),this.nodes.has(e)){this.logger.debug("Node already exists",{nodeId:e});return}this.nodes.add(e),this.engine.add_node(e),this.logger.debug("Added node to spectral graph",{nodeId:e})}addEdge(e,t,i){this.ensureInitialized(),this.nodes.has(e)||this.addNode(e),this.nodes.has(t)||this.addNode(t),this.edges.push({source:e,target:t,weight:i}),this.engine.add_edge(e,t,i),this.logger.debug("Added edge to spectral graph",{source:e,target:t,weight:i})}removeNode(e){this.ensureInitialized(),this.nodes.delete(e),this.engine.remove_node(e);for(let t=this.edges.length-1;t>=0;t--){let i=this.edges[t];(i.source===e||i.target===e)&&this.edges.splice(t,1)}this.logger.debug("Removed node from spectral graph",{nodeId:e})}computeFiedlerValue(){if(this.ensureInitialized(),this.nodes.size<2||this.edges.length===0)return 0;try{let e=this.engine.compute_fiedler_value();return this.logger.debug("Computed Fiedler value",{fiedlerValue:e}),e}catch(e){return this.logger.warn("Failed to compute Fiedler value",{error:v(e),nodeCount:this.nodes.size,edgeCount:this.edges.length}),0}}predictCollapseRisk(){if(this.ensureInitialized(),this.nodes.size<2)return 0;if(this.edges.length===0)return 1;try{let e=this.engine.predict_collapse_risk();return this.logger.debug("Predicted collapse risk",{risk:e}),e}catch(e){return this.logger.warn("Failed to predict collapse risk",{error:v(e),nodeCount:this.nodes.size,edgeCount:this.edges.length}),.8}}getWeakVertices(e){if(this.ensureInitialized(),this.nodes.size===0)return[];if(this.edges.length===0)return Array.from(this.nodes).slice(0,e);let t=Math.min(e,this.nodes.size);try{let i=this.engine.get_weak_vertices(t);return this.logger.debug("Retrieved weak vertices",{requested:e,returned:i.length}),i}catch(i){return this.logger.warn("Failed to get weak vertices",{error:v(i),nodeCount:this.nodes.size,edgeCount:this.edges.length}),Array.from(this.nodes).slice(0,e)}}analyzeSwarmState(e){let t=Date.now();this.clear();for(let c of e.agents)this.addNode(c.agentId);this.buildEdgesFromAgents(e.agents);let i=this.predictCollapseRisk(),n=this.computeFiedlerValue(),r=this.getWeakVertices(5),a=Date.now()-t,l={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}),l}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,l=e.beliefs??[],c=t.beliefs??[];return l.length>0&&c.length>0&&(a=this.computeBeliefOverlap(l,c)),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 l=0;l<e.length;l++)i+=e[l]*t[l],n+=e[l]*e[l],r+=t[l]*t[l];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 ee(d){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 d.computeCausalEffect(r,"cause","effect",1)?.effect??0},detect_spurious_correlation(){let r=n();return(d.findConfounders(r,"cause","effect")?.length??0)>0},get_confounders(){let r=n();return d.findConfounders(r,"cause","effect")??Array.from(i.keys())},clear(){e=null,t=null,i.clear()}}}var A=class{constructor(e,t=p){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;currentCause="";currentEffect="";async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CausalAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CausalAdapter.");let t=await this.wasmLoader.load(),i=new t.CausalEngine;this.engine=ee(i),this.initialized=!0,this.logger.info("CausalAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CausalAdapter not initialized. Call initialize() first.")}verifyCausality(e,t,i){this.ensureInitialized();let n=Date.now();if(this.clear(),this.currentCause=e,this.currentEffect=t,this.setData(i.causeValues,i.effectValues),i.confounders)for(let[m,f]of Object.entries(i.confounders))this.addConfounder(m,f);let r=this.computeCausalEffect(),a=this.detectSpuriousCorrelation(),l=this.getConfounders(),c=this.determineRelationshipType(r,a,l.length>0),s=this.computeConfidence(i.sampleSize,r,a),o=Date.now()-n,u={isCausal:c==="causal",effectStrength:r,relationshipType:c,confidence:s,confounders:l,explanation:this.generateExplanation(e,t,c,r,l),durationMs:o,usedFallback:!1};return this.logger.info("Verified causality",{cause:e,effect:t,isCausal:u.isCausal,relationshipType:c,effectStrength:r,durationMs:o}),u}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 te(d){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 l=n[a],c=n[a+1];if(!t.some(o=>o.source===l&&o.target===c))return!1}let r=i();return d.verifyCategoryLaws(r)},check_type_consistency(){let n=[];for(let r of t)e.has(r.source)||n.push({location:r.name,expected:"defined type",actual:`undefined type '${r.source}'`}),e.has(r.target)||n.push({location:r.name,expected:"defined type",actual:`undefined type '${r.target}'`});return n},clear(){e.clear(),t.length=0}}}var T=class{constructor(e,t=p){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;types=new Map;morphisms=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CategoryAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CategoryAdapter.");let t=await this.wasmLoader.load(),i=new t.CategoryEngine;this.engine=te(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),l=Date.now()-t,c={isValid:n&&r.length===0,mismatches:r,warnings:a,durationMs:l,usedFallback:!1};return this.logger.info("Verified pipeline",{pipelineId:e.id,isValid:c.isValid,mismatchCount:r.length,warningCount:a.length,durationMs:l}),c}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 ie(d){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},l={formula:r.formula};return d.typeCheck(a,l)?.valid?(r.proven=!0,t.set(i,n),!0):!1},verify_path_equivalence(i,n){let r={steps:i},a={steps:n};return d.checkTypeEquivalence(r,a)},get_unproven_propositions(){let i=[];return e.forEach((n,r)=>{n.proven||i.push(r)}),i},clear(){e.clear(),t.clear()}}}var R=class{constructor(e,t=p){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;propositions=new Map;async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing HomotopyAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize HomotopyAdapter.");let t=await this.wasmLoader.load(),i=new t.HoTTEngine;this.engine=ie(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 ne}from"crypto";var S=class{constructor(e,t=p){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;witnesses=new Map;decisions=new Map;witnessCounter=0;async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing WitnessAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize WitnessAdapter.");let t=await this.wasmLoader.load();this.engine=this.createWitnessEngine(t),this.initialized=!0,this.logger.info("WitnessAdapter initialized successfully")}createWitnessEngine(e){return this.createFallbackEngine()}createFallbackEngine(){let e=[];return{create_witness:(t,i)=>{let r={hash:this.computeHash(t,i),previousHash:i,position:e.length,timestamp:Date.now()};return e.push(r),r},verify_witness:(t,i)=>{let n=e.find(a=>a.hash===i);return this.computeHash(t,n?.previousHash)===i},verify_chain:t=>{if(t.length===0)return!0;if(t[0].previousHash!==void 0)return!1;for(let i=1;i<t.length;i++)if(t[i].previousHash!==t[i-1].hash)return!1;return!0},get_chain_length:()=>e.length}}computeHash(e,t){let i=ne("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()}`,l={witnessId:a,decisionId:e.id,hash:r.hash,previousWitnessId:i?.witnessId,chainPosition:r.position,timestamp:new Date(r.timestamp)};return this.witnesses.set(a,l),this.decisions.set(e.id,e),this.logger.info("Created witness",{witnessId:a,decisionId:e.id,chainPosition:l.chainPosition}),l}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,l={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}),l}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")}};function $(d){let e=new Map;for(let r of d){let a=String(r.verdict);e.set(a,(e.get(a)??0)+1)}let t=[...e.entries()].map(([r,a])=>({verdict:r,count:a})).sort((r,a)=>a.count-r.count||r.verdict.localeCompare(a.verdict)),i=t[0]??{verdict:"",count:0},n=d.length;return{total:n,counts:t,topVerdict:i.verdict,topCount:i.count,majorityRatio:n>0?i.count/n:0,isUnanimous:t.length===1}}function L(d){return`${d.topCount} of ${d.total} votes '${d.topVerdict}'`}function U(d){return d.counts.map(({verdict:e,count:t})=>`${t} '${e}'`).join(" / ")}var Y=.6,ce=3;function Q(d){return d.isUnanimous&&d.total>=ce}function _(d){return d.isUnanimous?L(d):`${L(d)}; ${U(d)}`}var W=class{constructor(e,t={},i){this.wasmLoader=e;this.config={...V,...t},this.logger=i||p}wasmLoader;config;logger;cohomologyAdapter=null;spectralAdapter=null;causalAdapter=null;categoryAdapter=null;homotopyAdapter=null;witnessAdapter=null;initialized=!1;stats={totalChecks:0,coherentCount:0,incoherentCount:0,averageEnergy:0,averageDurationMs:0,totalContradictions:0,laneDistribution:{reflex:0,retrieval:0,heavy:0,human:0},fallbackCount:0,wasmAvailable:!1};totalEnergySum=0;totalDurationSum=0;async initialize(){if(this.initialized)return;this.logger.info("Initializing CoherenceService");let e=await this.wasmLoader.isAvailable();if(!e&&!this.config.fallbackEnabled)throw new h("WASM module is not available and fallback is disabled. Enable fallbackEnabled in config to use TypeScript fallback.");if(this.stats.wasmAvailable=e,e)try{this.cohomologyAdapter=new w(this.wasmLoader,this.logger),this.spectralAdapter=new E(this.wasmLoader,this.logger),this.causalAdapter=new A(this.wasmLoader,this.logger),this.categoryAdapter=new T(this.wasmLoader,this.logger),this.homotopyAdapter=new R(this.wasmLoader,this.logger),this.witnessAdapter=new S(this.wasmLoader,this.logger),await Promise.all([this.cohomologyAdapter.initialize(),this.spectralAdapter.initialize(),this.causalAdapter.initialize(),this.categoryAdapter.initialize(),this.homotopyAdapter.initialize(),this.witnessAdapter.initialize()]),this.logger.info("All coherence engine adapters initialized")}catch(t){if(!this.config.fallbackEnabled)throw t;this.logger.warn("WASM initialization failed, using fallback",{error:t instanceof Error?t.message:"Unknown error"}),this.stats.wasmAvailable=!1}else this.logger.info("WASM not available, using TypeScript fallback");this.initialized=!0,this.logger.info("CoherenceService initialized",{wasmAvailable:this.stats.wasmAvailable,fallbackEnabled:this.config.fallbackEnabled})}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized)throw new b("CoherenceService not initialized. Call initialize() first.","NOT_INITIALIZED")}async checkCoherence(e){this.ensureInitialized();let t=Date.now();try{return this.cohomologyAdapter?.isInitialized()?await this.checkCoherenceWithWasm(e,t):this.checkCoherenceWithFallback(e,t)}catch(i){return this.logger.error("Coherence check failed",I(i)),{energy:1,isCoherent:!1,lane:"human",contradictions:[],recommendations:["Coherence check failed. Manual review recommended."],durationMs:Date.now()-t,usedFallback:!0}}}async checkCoherenceWithWasm(e,t){this.cohomologyAdapter.clear();for(let l of e)this.cohomologyAdapter.addNode(l);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 o=s+1;o<e.length;o++){let u=this.euclideanDistance(e[s].embedding,e[o].embedding);i+=u,n++,u>1.5&&r.push({nodeIds:[e[s].id,e[o].id],severity:u>2?"critical":"high",description:`High distance (${u.toFixed(2)}) between nodes`,confidence:Math.min(1,u/2)})}let a=n>0?i/n:0,l=this.computeLane(a),c=Date.now()-t;return this.updateStats(a,c,r.length,l,!0),{energy:a,isCoherent:a<this.config.coherenceThreshold,lane:l,contradictions:r,recommendations:this.generateRecommendations(a,l,r),durationMs:c,usedFallback:!0}}buildEdgesFromNodes(e){for(let t=0;t<e.length;t++)for(let i=t+1;i<e.length;i++){let n=this.cosineSimilarity(e[t].embedding,e[i].embedding);n>.3&&this.cohomologyAdapter.addEdge({source:e[t].id,target:e[i].id,weight:n})}}async detectContradictions(e){this.ensureInitialized();let t=e.map(n=>({id:n.id,embedding:n.embedding,weight:n.confidence,metadata:{statement:n.statement,source:n.source}}));return(await this.checkCoherence(t)).contradictions}async predictCollapse(e){if(this.ensureInitialized(),!e.agents||e.agents.length===0)return{risk:0,fiedlerValue:0,collapseImminent:!1,weakVertices:[],recommendations:["No agents to analyze"],durationMs:0,usedFallback:!0};if(this.spectralAdapter?.isInitialized())try{return this.spectralAdapter.analyzeSwarmState(e)}catch(t){return this.logger.warn("Spectral collapse prediction failed, using fallback",{error:v(t),agentCount:e.agents.length}),this.predictCollapseWithFallback(e)}return this.predictCollapseWithFallback(e)}predictCollapseWithFallback(e){let t=Date.now(),i=e.agents.reduce((l,c)=>l+c.health,0)/Math.max(e.agents.length,1),n=e.agents.reduce((l,c)=>l+c.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(l=>l.health<.5||l.successRate<.5).map(l=>l.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 o of e)this.spectralAdapter.addNode(o.agentId);let i=0;for(let o=0;o<e.length;o++)for(let u=o+1;u<e.length;u++)e[o].verdict===e[u].verdict&&(this.spectralAdapter.addEdge(e[o].agentId,e[u].agentId,Math.min(e[o].confidence,e[u].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(),a=$(e);if(a.isUnanimous&&e.every(o=>o.confidence>0)&&!(r>0))return this.logger.warn("Spectral engine returned a zero Fiedler value for a connected agreement graph, using fallback",{fiedlerValue:r,voteCount:e.length}),this.verifyConsensusWithFallback(e,t);let l=n<.3&&r>.1,c=Q(a),s;return l?c?s=`Consensus verified (${_(a)}), but unanimous agreement may indicate false consensus. Consider adding diversity.`:s=`Consensus verified (${_(a)}).`:s=`No verified consensus (${_(a)}): agreement-graph Fiedler value ${r.toFixed(3)}, collapse risk ${n.toFixed(2)}. Spawn independent reviewer.`,{isValid:l,confidence:1-n,isFalseConsensus:c,fiedlerValue:r,collapseRisk:n,recommendation:s,durationMs:Date.now()-t,usedFallback:!1}}catch(i){return this.logger.warn("Spectral consensus verification failed, using fallback",{error:v(i),voteCount:e.length}),this.verifyConsensusWithFallback(e,t)}return this.verifyConsensusWithFallback(e,t)}verifyConsensusWithFallback(e,t){let i=$(e),{majorityRatio:n}=i,r=e.reduce((s,o)=>s+o.confidence,0)/e.length,a=n>Y,l=Q(i),c;return a?l?c=`Unanimous consensus (${L(i)}) may indicate false consensus. Consider adding diversity.`:i.isUnanimous?c=`Unanimous consensus achieved (${L(i)}).`:c=`Majority consensus achieved (${_(i)}).`:c=`No clear majority: ${U(i)} across ${i.total} votes (needs more than ${Math.round(Y*100)}% agreeing). Consider spawning additional agents.`,{isValid:a,confidence:n*r,isFalseConsensus:l,fiedlerValue:n,collapseRisk:1-n,recommendation:c,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(l=>r.add(l));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 l=0;l<e.length;l++)i+=e[l]*t[l],n+=e[l]*e[l],r+=t[l]*t[l];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((o,u)=>o+u,0)/i,r=t.reduce((o,u)=>o+u,0)/i,a=0,l=0,c=0;for(let o=0;o<i;o++){let u=e[o]-n,m=t[o]-r;a+=u*m,l+=u*u,c+=m*m}let s=Math.sqrt(l*c);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 ue(d,e,t){let i=new W(d,e,t);return await i.initialize(),i}O();import{createRequire as K}from"node:module";import{fileURLToPath as he}from"node:url";import{dirname as q,join as M}from"node:path";import{readFileSync as ge,existsSync as X}from"node:fs";var B=[1e3,2e3,4e3],z=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={...G,...e},this.eventListeners=new Map,this.eventListeners.set("loaded",new Set),this.eventListeners.set("error",new Set),this.eventListeners.set("retry",new Set),this.eventListeners.set("degraded_mode",new Set),this.eventListeners.set("recovered",new Set)}isLoaded(){return this.state==="loaded"&&this.engines!==null}getState(){return this.state}getVersion(){return this.version}getLastError(){return this.lastError}isInDegradedMode(){return this.state==="degraded"||this.fallbackState.mode==="fallback"}getFallbackState(){return{...this.fallbackState}}getFallbackResult(){return{usedFallback:!0,confidence:.5,retryCount:this.fallbackState.consecutiveFailures,lastError:this.lastError?.message,activatedAt:this.degradedModeStartTime??new Date}}async getEngines(){if(this.state==="loaded"&&this.engines)return this.engines;if(this.state==="loading"&&this.loadPromise)return this.loadPromise;this.state="loading",this.loadPromise=this.loadWithRetry();try{return this.engines=await this.loadPromise,this.state="loaded",(this.fallbackState.mode==="fallback"||this.fallbackState.mode==="recovering")&&this.emitRecoveryEvent(),this.fallbackState.mode="wasm",this.fallbackState.consecutiveFailures=0,this.fallbackState.lastSuccessfulLoad=new Date,this.engines}catch(e){throw this.state="failed",this.lastError=I(e),this.enterDegradedMode(this.lastError),e}finally{this.loadPromise=null}}async getEnginesWithFallback(){if(this.state==="loaded"&&this.engines)return{engines:this.engines,fallback:{usedFallback:!1,confidence:1,retryCount:0}};if(this.state==="degraded")return{engines:null,fallback:this.getFallbackResult()};try{return{engines:await this.getEngines(),fallback:{usedFallback:!1,confidence:1,retryCount:0}}}catch{return{engines:null,fallback:this.getFallbackResult()}}}getEnginesSync(){if(!this.engines)throw new h("WASM module is not loaded. Call getEngines() first.");return this.engines}async isAvailable(){if(this.state==="loaded"&&this.wasmModule)return!0;if(this.state==="failed")return!1;try{let e=K(import.meta.url),t=[(()=>{try{let i=e.resolve("prime-radiant-advanced-wasm");return M(q(i),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),M(process.cwd(),"node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm")].filter(i=>i!==null);for(let i of t)if(X(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(),l=await this.attemptLoad(),c=performance.now()-a;return this.emit("loaded",{version:this.version,loadTimeMs:Math.round(c*100)/100}),l}catch(a){if(n=I(a),this.emit("error",{error:n,fatal:r>=e,attempt:r}),r<e){let l=Math.min(t*Math.pow(2,r-1),i);this.emit("retry",{attempt:r+1,maxAttempts:e,delayMs:l,previousError:n}),await this.sleep(l)}}throw new k(`Failed to load WASM module after ${e} attempts: ${n.message}`,e,n)}async attemptLoad(){let e;try{e=K(import.meta.url)}catch{e=globalThis.require||(await import("module")).createRequire(__filename)}let t;try{t=await import("./prime-radiant-advanced-wasm-JDHTKQAT.js")}catch(r){try{t=e("prime-radiant-advanced-wasm")}catch{throw new Error(`Failed to import prime-radiant-advanced-wasm: ${v(r)}`)}}if(typeof process<"u"&&process.versions!=null&&process.versions.node!=null?await this.initializeForNodeJs(t,e):t.default&&typeof t.default=="function"&&await t.default(),t.initModule&&typeof t.initModule=="function")try{t.initModule()}catch{}return t.getVersion&&typeof t.getVersion=="function"&&(this.version=t.getVersion()),this.wasmModule=t,{cohomology:new t.CohomologyEngine,spectral:new t.SpectralEngine,causal:new t.CausalEngine,category:new t.CategoryEngine,hott:new t.HoTTEngine,quantum:new t.QuantumEngine}}async initializeForNodeJs(e,t){let i=[(()=>{try{let a=t.resolve("prime-radiant-advanced-wasm");return M(q(a),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),M(q(he(import.meta.url)),"../../../../node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm"),M(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(X(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=ge(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,B.length-1),i=B[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<B.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}},me=new z;var pe={emaAlpha:.1,minSamplesForCalibration:10,maxHistorySize:1e3,targetFalsePositiveRate:.05,targetFalseNegativeRate:.02,maxAdjustmentPerCycle:.05,autoCalibrate:!1,autoCalibrateInterval:100,defaultThresholds:{...x}};export{$ as a,U as b,ue as c,me as d};