agentic-qe 3.15.13 → 3.15.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (426) hide show
  1. package/.claude/agents/v3/templates/qx-report-template.html +1 -1
  2. package/.claude/helpers/brain-checkpoint.cjs +124 -5
  3. package/.claude/skills/skills-manifest.json +1 -1
  4. package/CHANGELOG.md +124 -0
  5. package/assets/agents/v3/templates/qx-report-template.html +1 -1
  6. package/assets/skills/skills-manifest.json +1 -1
  7. package/dist/cli/bundle.js +6 -6
  8. package/dist/cli/chunks/adapter-QU6INSKP.js +2 -0
  9. package/dist/cli/chunks/agent-booster-wasm-EUF4XVUC.js +2 -0
  10. package/dist/cli/chunks/{agent-handler-AOH6TV7W.js → agent-handler-MOX6PSIQ.js} +2 -2
  11. package/dist/cli/chunks/{agent-memory-branch-2P54SF5N.js → agent-memory-branch-AEXKIGDG.js} +2 -2
  12. package/dist/cli/chunks/aqe-learning-engine-PAJPENJD.js +2 -0
  13. package/dist/cli/chunks/{arena-NSVFCAF5.js → arena-IQ5ZZDRF.js} +2 -2
  14. package/dist/cli/chunks/{arena-X6MOGQHA.js → arena-M7GA3CVG.js} +4 -4
  15. package/dist/cli/chunks/{audit-27DJLQNM.js → audit-4IPBMKWB.js} +3 -3
  16. package/dist/cli/chunks/base-OTGSN6IC.js +2 -0
  17. package/dist/cli/chunks/{better-sqlite3-BU5GXILS.js → better-sqlite3-IKDKJ2IE.js} +2 -2
  18. package/dist/cli/chunks/brain-handler-5NQUDH4W.js +95 -0
  19. package/dist/cli/chunks/{branch-enumerator-5CLULOCU.js → branch-enumerator-KSXELWRC.js} +2 -2
  20. package/dist/cli/chunks/{browser-R4DMU3LN.js → browser-6LACARWE.js} +2 -2
  21. package/dist/cli/chunks/browser-workflow-WLZGR6SB.js +2 -0
  22. package/dist/cli/chunks/{chunk-LUZNKJE6.js → chunk-22UKJGGN.js} +3 -3
  23. package/dist/cli/chunks/{chunk-BLSLEVDI.js → chunk-27HE2BHC.js} +2 -2
  24. package/dist/cli/chunks/{chunk-K4CZA77U.js → chunk-2CKERSMB.js} +2 -2
  25. package/dist/cli/chunks/{chunk-YSZ5OE3Z.js → chunk-2IIXCEMS.js} +2 -2
  26. package/dist/cli/chunks/{chunk-F3YS57NF.js → chunk-2LUTPMBO.js} +2 -2
  27. package/dist/cli/chunks/{chunk-GHM6MQNK.js → chunk-2ZFLULL4.js} +2 -2
  28. package/dist/cli/chunks/{chunk-7CMTY45A.js → chunk-337Z52QM.js} +2 -2
  29. package/dist/cli/chunks/{chunk-W26B7ERY.js → chunk-3CYNZFKH.js} +1 -1
  30. package/dist/cli/chunks/chunk-3HVFIITW.js +2 -0
  31. package/dist/cli/chunks/{chunk-K3TLLJMX.js → chunk-3J3RNJNX.js} +1 -1
  32. package/dist/cli/chunks/{chunk-MAMQA43L.js → chunk-4ATQP3PR.js} +1 -1
  33. package/dist/cli/chunks/{chunk-YXRASAPI.js → chunk-4D4CWP72.js} +2 -2
  34. package/dist/cli/chunks/{chunk-GHY6Z6KO.js → chunk-4HKAD25N.js} +3 -3
  35. package/dist/cli/chunks/{chunk-XNBOGCF3.js → chunk-4X3SWKBA.js} +2 -2
  36. package/dist/cli/chunks/{chunk-IJUHSJ2U.js → chunk-5AFVEWMT.js} +2 -2
  37. package/dist/cli/chunks/{chunk-SE4VNN4I.js → chunk-5C62XMJR.js} +3 -3
  38. package/dist/cli/chunks/{chunk-KDNJ4F3P.js → chunk-5G4UFTV4.js} +2 -2
  39. package/dist/cli/chunks/{chunk-DVGRPK7A.js → chunk-5I7357KS.js} +2 -2
  40. package/dist/cli/chunks/{chunk-YZWBNBTW.js → chunk-5KA5TVPR.js} +2 -2
  41. package/dist/cli/chunks/{chunk-JGZ722G3.js → chunk-5PTAFGJT.js} +2 -2
  42. package/dist/cli/chunks/{chunk-SVLQRAMF.js → chunk-6BRQPHMZ.js} +1 -1
  43. package/dist/cli/chunks/{chunk-KDVZND5Q.js → chunk-6KCSKGVY.js} +1 -1
  44. package/dist/cli/chunks/{chunk-LWR3FV3Y.js → chunk-6LE362LZ.js} +2 -2
  45. package/dist/cli/chunks/{chunk-WKGTGOYS.js → chunk-6NBRMD25.js} +3 -3
  46. package/dist/cli/chunks/{chunk-HQZGPJYG.js → chunk-6RBTS3NF.js} +2 -2
  47. package/dist/cli/chunks/{chunk-WOCGL4QP.js → chunk-6YVMX2TC.js} +2 -2
  48. package/dist/cli/chunks/{chunk-I3C7JOXC.js → chunk-73PBAWAF.js} +2 -2
  49. package/dist/cli/chunks/{chunk-75RDHBAX.js → chunk-74YG72NQ.js} +3 -3
  50. package/dist/cli/chunks/{chunk-O6FGXMHD.js → chunk-76P32JVU.js} +1 -1
  51. package/dist/cli/chunks/{chunk-LL7LDPXS.js → chunk-7ACCBHRB.js} +1 -1
  52. package/dist/cli/chunks/{chunk-3LJ7LQMV.js → chunk-7BLZHFKD.js} +1 -1
  53. package/dist/cli/chunks/{chunk-CM4LSLKR.js → chunk-7O45RQHF.js} +2 -2
  54. package/dist/cli/chunks/{chunk-NU3W5WFT.js → chunk-7XB3FCKM.js} +2 -2
  55. package/dist/cli/chunks/{chunk-E56B6IDX.js → chunk-AHMWD6JG.js} +2 -2
  56. package/dist/cli/chunks/{chunk-G2Q66Z23.js → chunk-AJPROCDW.js} +2 -2
  57. package/dist/cli/chunks/{chunk-NW7IBHJA.js → chunk-AKZO6GGG.js} +13 -13
  58. package/dist/cli/chunks/{chunk-IC3TQEOA.js → chunk-AOKKUB5F.js} +1 -1
  59. package/dist/cli/chunks/{chunk-4OVC4RIL.js → chunk-AP2W7Z3A.js} +1 -1
  60. package/dist/cli/chunks/{chunk-PHP5UBT4.js → chunk-BBRROA3Z.js} +2 -2
  61. package/dist/cli/chunks/{chunk-5FKWCZNF.js → chunk-BDKEAGQ2.js} +2 -2
  62. package/dist/cli/chunks/{chunk-BTVEYBW2.js → chunk-BFQTLF5X.js} +2 -2
  63. package/dist/cli/chunks/{chunk-HZ5NXFXH.js → chunk-BLL2XU7A.js} +2 -2
  64. package/dist/cli/chunks/{chunk-UTRV7T2N.js → chunk-BP5T3OEV.js} +2 -2
  65. package/dist/cli/chunks/{chunk-GB6HBNH2.js → chunk-BQ47GQPK.js} +2 -2
  66. package/dist/cli/chunks/{chunk-RFNW2LGD.js → chunk-BU4UQR36.js} +2 -2
  67. package/dist/cli/chunks/{chunk-WO274FRI.js → chunk-BZULJMGH.js} +2 -2
  68. package/dist/cli/chunks/{chunk-GU5HNCWI.js → chunk-C4KLXFJP.js} +1 -1
  69. package/dist/cli/chunks/{chunk-LFJALJOA.js → chunk-C4RTAVC6.js} +2 -2
  70. package/dist/cli/chunks/{chunk-WNQS4WTS.js → chunk-C5CXL3JP.js} +2 -2
  71. package/dist/cli/chunks/{chunk-MGZ5FJUW.js → chunk-CAOUV5GZ.js} +2 -2
  72. package/dist/cli/chunks/{chunk-XPRVF4YE.js → chunk-CBK5CT6T.js} +2 -2
  73. package/dist/cli/chunks/{chunk-JRRXCODW.js → chunk-DEKR3CTS.js} +2 -2
  74. package/dist/cli/chunks/{chunk-AQSVJNEH.js → chunk-DKX4GNRU.js} +2 -2
  75. package/dist/cli/chunks/{chunk-6KATY3KS.js → chunk-DUKE27HC.js} +2 -2
  76. package/dist/cli/chunks/{chunk-W2QWSQVE.js → chunk-DURD37JZ.js} +2 -2
  77. package/dist/cli/chunks/{chunk-KCW47QR5.js → chunk-E3MRDIZF.js} +1 -1
  78. package/dist/cli/chunks/{chunk-6Z7PRBSG.js → chunk-E56PVVWC.js} +2 -2
  79. package/dist/cli/chunks/{chunk-WQL7WCIZ.js → chunk-E5G4WZ2T.js} +1 -1
  80. package/dist/cli/chunks/{chunk-PB6J6HAA.js → chunk-EBTNMQSS.js} +2 -2
  81. package/dist/cli/chunks/{chunk-KADFXPPN.js → chunk-EFUJDMNC.js} +2 -2
  82. package/dist/cli/chunks/{chunk-QPNG5ZN2.js → chunk-EKP2SC77.js} +2 -2
  83. package/dist/cli/chunks/{chunk-U2FUXDDJ.js → chunk-EMSZVUYA.js} +3 -3
  84. package/dist/cli/chunks/{chunk-XEAEYC6Y.js → chunk-ERN56H6S.js} +1 -1
  85. package/dist/cli/chunks/{chunk-DNDL7SOS.js → chunk-FOOW4JVS.js} +2 -2
  86. package/dist/cli/chunks/{chunk-HOAJUIBQ.js → chunk-FTRSS64D.js} +2 -2
  87. package/dist/cli/chunks/{chunk-TOQWL2ZF.js → chunk-G242G224.js} +2 -2
  88. package/dist/cli/chunks/{chunk-VTDFVFST.js → chunk-G6RDCCFV.js} +2 -2
  89. package/dist/cli/chunks/{chunk-TWDW32W2.js → chunk-GCHYOPRZ.js} +2 -2
  90. package/dist/cli/chunks/{chunk-MFW5HSG4.js → chunk-GGQGCT4Y.js} +2 -2
  91. package/dist/cli/chunks/{chunk-G6WDYBLQ.js → chunk-GKSMRBHU.js} +1 -1
  92. package/dist/cli/chunks/{chunk-CCMKSHAT.js → chunk-GQABPCQE.js} +2 -2
  93. package/dist/cli/chunks/{chunk-G77ERMUD.js → chunk-GV2QE5TO.js} +1 -1
  94. package/dist/cli/chunks/{chunk-756CGMEH.js → chunk-H5DER3JY.js} +1 -1
  95. package/dist/cli/chunks/{chunk-W3PPFHI5.js → chunk-HH4ED4F7.js} +52 -50
  96. package/dist/cli/chunks/{chunk-3Y2ROSCL.js → chunk-HL2ANKN3.js} +2 -2
  97. package/dist/cli/chunks/{chunk-T3PGQFDI.js → chunk-HTZSRMHW.js} +2 -2
  98. package/dist/cli/chunks/{chunk-3QZEGE67.js → chunk-IXL5ZHWJ.js} +1 -1
  99. package/dist/cli/chunks/{chunk-5ZGM3RMH.js → chunk-J3FP5UGL.js} +1 -1
  100. package/dist/cli/chunks/{chunk-FZ76G4QJ.js → chunk-JCQGJGGZ.js} +1 -1
  101. package/dist/cli/chunks/chunk-JCZCJE6X.js +86 -0
  102. package/dist/cli/chunks/{chunk-YZEXYO4W.js → chunk-JKJOB65O.js} +1 -1
  103. package/dist/cli/chunks/{chunk-A64JFBWI.js → chunk-JUDUBQHA.js} +2 -2
  104. package/dist/cli/chunks/{chunk-PIDQVU3L.js → chunk-JW74KRBC.js} +2 -2
  105. package/dist/cli/chunks/{chunk-EXGMJFAT.js → chunk-K3WZICFA.js} +1 -1
  106. package/dist/cli/chunks/{chunk-ASQYASNV.js → chunk-K3XBQC3R.js} +1 -1
  107. package/dist/cli/chunks/{chunk-E7CLYGS7.js → chunk-KCQNFBBR.js} +1 -1
  108. package/dist/cli/chunks/chunk-KJBPB7P5.js +3 -0
  109. package/dist/cli/chunks/chunk-KLTMOXIK.js +3 -0
  110. package/dist/cli/chunks/{chunk-5MDERQH3.js → chunk-L32JNNKL.js} +1 -1
  111. package/dist/cli/chunks/{chunk-32ZMWEP3.js → chunk-LB2LGEDP.js} +2 -2
  112. package/dist/cli/chunks/{chunk-42J34YG4.js → chunk-LHMQIZ6B.js} +2 -2
  113. package/dist/cli/chunks/{chunk-NURIILUB.js → chunk-LJMYRTJ7.js} +1 -1
  114. package/dist/cli/chunks/{chunk-M6AAGIG7.js → chunk-LNX74WHQ.js} +1 -1
  115. package/dist/cli/chunks/{chunk-P7A4NKTZ.js → chunk-LTQVUAPH.js} +2 -2
  116. package/dist/cli/chunks/{chunk-3YNLWPBF.js → chunk-LVABQNRF.js} +2 -2
  117. package/dist/cli/chunks/{chunk-2G7TVT6W.js → chunk-LYJHUNBK.js} +2 -2
  118. package/dist/cli/chunks/{chunk-DLD7RUZ4.js → chunk-M4CJCPCQ.js} +2 -2
  119. package/dist/cli/chunks/{chunk-Q3UDLV5Z.js → chunk-M4WMSCAE.js} +1 -1
  120. package/dist/cli/chunks/{chunk-UDQSYWVF.js → chunk-MIA447GY.js} +1 -1
  121. package/dist/cli/chunks/{chunk-RF7HWBHN.js → chunk-MPFPWJTH.js} +2 -2
  122. package/dist/cli/chunks/{chunk-BK577VL7.js → chunk-MV55NXTD.js} +2 -2
  123. package/dist/cli/chunks/{chunk-JQGMW45H.js → chunk-NQS3BWS6.js} +1 -1
  124. package/dist/cli/chunks/{chunk-BEGR4D6N.js → chunk-NWIIYHT6.js} +2 -2
  125. package/dist/cli/chunks/{chunk-SSU73QAX.js → chunk-O6EWL5DQ.js} +2 -2
  126. package/dist/cli/chunks/chunk-OBDONJQM.js +2 -0
  127. package/dist/cli/chunks/chunk-OLZH5LRT.js +141 -0
  128. package/dist/cli/chunks/{chunk-W3INMZZ6.js → chunk-OQG3UQQ7.js} +1 -1
  129. package/dist/cli/chunks/{chunk-72ASBE35.js → chunk-PFQCV6YS.js} +3 -3
  130. package/dist/cli/chunks/{chunk-7YTGHGK4.js → chunk-PS6UMZVK.js} +2 -2
  131. package/dist/cli/chunks/{chunk-OCAEXYFA.js → chunk-PXATBHWN.js} +2 -2
  132. package/dist/cli/chunks/{chunk-ARJW4I2O.js → chunk-PYPS65P7.js} +2 -2
  133. package/dist/cli/chunks/{chunk-SYV2V3PL.js → chunk-Q6I4SIUU.js} +4 -4
  134. package/dist/cli/chunks/{chunk-H4H2YSFH.js → chunk-QFGYH6HD.js} +1 -1
  135. package/dist/cli/chunks/{chunk-526QYFJU.js → chunk-QGBGSQ2E.js} +2 -2
  136. package/dist/cli/chunks/{chunk-YBQH2VOP.js → chunk-QRKTBSZT.js} +2 -2
  137. package/dist/cli/chunks/{chunk-C7JM7CD3.js → chunk-R6LHJ7ME.js} +2 -2
  138. package/dist/cli/chunks/{chunk-TSQC2KKZ.js → chunk-RBKUU7WF.js} +2 -2
  139. package/dist/cli/chunks/{chunk-CE7B5LU7.js → chunk-RDMRY7CT.js} +1 -1
  140. package/dist/cli/chunks/chunk-RIRZHOS2.js +8 -0
  141. package/dist/cli/chunks/{chunk-CRWPZT74.js → chunk-SHRI7TKJ.js} +2 -2
  142. package/dist/cli/chunks/{chunk-KWYH3FI4.js → chunk-SJCKCSN3.js} +1 -1
  143. package/dist/cli/chunks/{chunk-DFUASIKA.js → chunk-SON6ZRH3.js} +2 -2
  144. package/dist/cli/chunks/{chunk-J2ZIFFM6.js → chunk-SZAZQZWI.js} +2 -2
  145. package/dist/cli/chunks/{chunk-HD7YIFOI.js → chunk-T4GE7MPI.js} +2 -2
  146. package/dist/cli/chunks/{chunk-3Y7TJFHU.js → chunk-T66PPF4D.js} +2 -2
  147. package/dist/cli/chunks/{chunk-3RZV5DGO.js → chunk-T67R2MUN.js} +2 -2
  148. package/dist/cli/chunks/{chunk-H4GG2NLO.js → chunk-TDQWTSBS.js} +2 -2
  149. package/dist/cli/chunks/{chunk-TWJTK4CC.js → chunk-TODNOP7C.js} +2 -2
  150. package/dist/cli/chunks/{chunk-NZ3GUMB2.js → chunk-TX2CHQD7.js} +2 -2
  151. package/dist/cli/chunks/{chunk-AL6FBH3E.js → chunk-TZIHDJZD.js} +2 -2
  152. package/dist/cli/chunks/{chunk-GII6UM3F.js → chunk-U62OUXBF.js} +1 -1
  153. package/dist/cli/chunks/{chunk-YQFLQE53.js → chunk-UAQZI6N4.js} +2 -2
  154. package/dist/cli/chunks/{chunk-R7SYRCRP.js → chunk-UE2J6MA5.js} +1 -1
  155. package/dist/cli/chunks/{chunk-VRHRBAEM.js → chunk-UGYM4U44.js} +1 -1
  156. package/dist/cli/chunks/{chunk-NT4DBXSX.js → chunk-UJABDXST.js} +2 -2
  157. package/dist/cli/chunks/{chunk-OFACHK5O.js → chunk-UORB2QDU.js} +9 -9
  158. package/dist/cli/chunks/{chunk-QDEJ4CI2.js → chunk-UQPA33UK.js} +2 -2
  159. package/dist/cli/chunks/{chunk-TCBBNUBP.js → chunk-UUBIQR6A.js} +3 -3
  160. package/dist/cli/chunks/{chunk-NZD4DPSU.js → chunk-UXIY4IAI.js} +2 -2
  161. package/dist/cli/chunks/{chunk-SG3NX7QE.js → chunk-VCXI4XC4.js} +2 -2
  162. package/dist/cli/chunks/{chunk-PSFSPGUD.js → chunk-VMAM46HQ.js} +2 -2
  163. package/dist/cli/chunks/{chunk-3AN5TNGD.js → chunk-VY4U6DPO.js} +3 -3
  164. package/dist/cli/chunks/{chunk-X7N2JF2X.js → chunk-W27AJ5B4.js} +2 -2
  165. package/dist/cli/chunks/{chunk-CT6SAVXQ.js → chunk-W5ZJG2OU.js} +2 -2
  166. package/dist/cli/chunks/{chunk-KV4T4MXK.js → chunk-W62OOK7A.js} +2 -2
  167. package/dist/cli/chunks/{chunk-5K26BEYB.js → chunk-WNTA4YKE.js} +2 -2
  168. package/dist/cli/chunks/{chunk-LZYQHVD4.js → chunk-WUOOX7UG.js} +2 -2
  169. package/dist/cli/chunks/{chunk-7NA7JXNB.js → chunk-WVXJ2QIG.js} +2 -2
  170. package/dist/cli/chunks/{chunk-KB56CPU4.js → chunk-X33CWRDF.js} +2 -2
  171. package/dist/cli/chunks/{chunk-7JUC2MVZ.js → chunk-XG4F4XH4.js} +2 -2
  172. package/dist/cli/chunks/{chunk-ZAKQLAHT.js → chunk-XH4JMX5O.js} +1 -1
  173. package/dist/cli/chunks/{chunk-X2Z7F4EU.js → chunk-XHHWABJV.js} +2 -2
  174. package/dist/cli/chunks/{chunk-7PLIEBY7.js → chunk-XHLYGXYE.js} +2 -2
  175. package/dist/cli/chunks/{chunk-UXZSUMEA.js → chunk-XIVVTYM2.js} +2 -2
  176. package/dist/cli/chunks/{chunk-MVVB7C2E.js → chunk-XM6ZVFM5.js} +156 -156
  177. package/dist/cli/chunks/{chunk-VTOBUZL6.js → chunk-XWIAZG3C.js} +2 -2
  178. package/dist/cli/chunks/{chunk-CV77DMDQ.js → chunk-Y2OX6KGN.js} +2 -2
  179. package/dist/cli/chunks/{chunk-VRVMIPTM.js → chunk-YUS6TWAL.js} +2 -2
  180. package/dist/cli/chunks/{chunk-VU5TBX2V.js → chunk-ZIPAB5J6.js} +2 -2
  181. package/dist/cli/chunks/{chunk-KUAKV3IW.js → chunk-ZSOMUTNL.js} +1 -1
  182. package/dist/cli/chunks/{chunk-UOC3O6RP.js → chunk-ZWBGYJ7K.js} +2 -2
  183. package/dist/cli/chunks/{chunk-5VMAV6T6.js → chunk-ZYJB6FML.js} +1 -1
  184. package/dist/cli/chunks/{ci-ENOASTYB.js → ci-UCUJOSBW.js} +2 -2
  185. package/dist/cli/chunks/{ci-config-B26OXHQM.js → ci-config-2XILD3XG.js} +2 -2
  186. package/dist/cli/chunks/{ci-output-JTCLLNOQ.js → ci-output-BL6KWOHW.js} +2 -2
  187. package/dist/cli/chunks/{circuit-breaker-23JMFNM5.js → circuit-breaker-5XLIOXE5.js} +2 -2
  188. package/dist/cli/chunks/{claude-flow-setup-ON6L462G.js → claude-flow-setup-4IMP6ACS.js} +2 -2
  189. package/dist/cli/chunks/client-KKRNPX4F.js +2 -0
  190. package/dist/cli/chunks/{cline-installer-OWQ4D2FQ.js → cline-installer-RYLHCDK7.js} +2 -2
  191. package/dist/cli/chunks/{code-2ZRL7SEU.js → code-WY3GJXHX.js} +3 -3
  192. package/dist/cli/chunks/{code-index-extractor-JXSQVM67.js → code-index-extractor-Y4MZBZCW.js} +2 -2
  193. package/dist/cli/chunks/{codex-installer-7LXZYBSQ.js → codex-installer-SCJ3T3DX.js} +4 -4
  194. package/dist/cli/chunks/{completions-C2LR623C.js → completions-CN2DXQFU.js} +2 -2
  195. package/dist/cli/chunks/{complexity-analyzer-TGQLHCYJ.js → complexity-analyzer-7MDPPIBH.js} +2 -2
  196. package/dist/cli/chunks/{continuedev-installer-RUGD24D2.js → continuedev-installer-GCEJRK34.js} +2 -2
  197. package/dist/cli/chunks/{copilot-installer-ZLFVLEJP.js → copilot-installer-BHPDSELY.js} +2 -2
  198. package/dist/cli/chunks/core-handlers-47MPMED7.js +2 -0
  199. package/dist/cli/chunks/{cost-tracker-RT4QL745.js → cost-tracker-VO5MFWR6.js} +2 -2
  200. package/dist/cli/chunks/coverage-LYFQYNH6.js +51 -0
  201. package/dist/cli/chunks/cross-domain-router-U6MBFHEC.js +2 -0
  202. package/dist/cli/chunks/{cursor-installer-LJKLNFF6.js → cursor-installer-KP4HA7TV.js} +2 -2
  203. package/dist/cli/chunks/{daemon-BMDXCQT5.js → daemon-7RC7TS57.js} +3 -3
  204. package/dist/cli/chunks/{daemon-FBH3IRYN.js → daemon-AXLVPKVO.js} +4 -4
  205. package/dist/cli/chunks/{dag-attention-scheduler-JGDED55I.js → dag-attention-scheduler-NKA44RSR.js} +2 -2
  206. package/dist/cli/chunks/{detect-SZIHIVCJ.js → detect-CMYAJWYF.js} +2 -2
  207. package/dist/cli/chunks/{dist-node-FV3KWXQ6.js → dist-node-EN3PYEGW.js} +2 -2
  208. package/dist/cli/chunks/{domain-handler-GI5JWQOV.js → domain-handler-EXSZCX7A.js} +2 -2
  209. package/dist/cli/chunks/{domain-plugins-BUWY36TL.js → domain-plugins-HCQFSNL7.js} +2 -2
  210. package/dist/cli/chunks/{domain-transfer-GCY7W5DA.js → domain-transfer-3LGSNTPO.js} +2 -2
  211. package/dist/cli/chunks/dream-76L6EEN7.js +2 -0
  212. package/dist/cli/chunks/{embed-and-insert-pattern-GPRR3ZGD.js → embed-and-insert-pattern-B6MNHICW.js} +2 -2
  213. package/dist/cli/chunks/{eval-XPB3IGAP.js → eval-OQELIWJK.js} +2 -2
  214. package/dist/cli/chunks/{experience-capture-middleware-2E554UB3.js → experience-capture-middleware-SUFILYPW.js} +3 -3
  215. package/dist/cli/chunks/{fast-paths-ZSMWZPUC.js → fast-paths-UV4NDEWM.js} +2 -2
  216. package/dist/cli/chunks/{feature-flags-GIWVDVVC.js → feature-flags-CKTYX67J.js} +2 -2
  217. package/dist/cli/chunks/{feature-flags-N7EOGE5P.js → feature-flags-H7H33B6C.js} +2 -2
  218. package/dist/cli/chunks/file-discovery-VSFKZ3LJ.js +2 -0
  219. package/dist/cli/chunks/{fleet-HCHDOUCX.js → fleet-ZJBCAKRG.js} +3 -3
  220. package/dist/cli/chunks/{gnn-wrapper-CZNCNXXZ.js → gnn-wrapper-RUE2QZRG.js} +2 -2
  221. package/dist/cli/chunks/{heartbeat-handler-6YUIF2YQ.js → heartbeat-handler-XRV327M7.js} +4 -4
  222. package/dist/cli/chunks/heartbeat-scheduler-NIK3KKEH.js +2 -0
  223. package/dist/cli/chunks/hnsw-adapter-WJG7LUJJ.js +2 -0
  224. package/dist/cli/chunks/hnsw-index-D6PRI5HC.js +2 -0
  225. package/dist/cli/chunks/{hnsw-legacy-bridge-J3M3IK24.js → hnsw-legacy-bridge-UJID6ZZ4.js} +2 -2
  226. package/dist/cli/chunks/{hnswlib-node-ULGTGDZW.js → hnswlib-node-WS43R4AX.js} +2 -2
  227. package/dist/cli/chunks/{hooks-C4BUGYUQ.js → hooks-YZNJKXAJ.js} +10 -10
  228. package/dist/cli/chunks/hybrid-backend-RIUR3I7F.js +2 -0
  229. package/dist/cli/chunks/{hypergraph-engine-WINGVMPG.js → hypergraph-engine-XQJSIMTS.js} +2 -2
  230. package/dist/cli/chunks/{hypergraph-handler-GADMWKAU.js → hypergraph-handler-ZD2NYXMR.js} +3 -3
  231. package/dist/cli/chunks/impact-analyzer-C36YYTJ5.js +2 -0
  232. package/dist/cli/chunks/{init-guard-K2T4QWAO.js → init-guard-DSRUAVRT.js} +2 -2
  233. package/dist/cli/chunks/{init-handler-PCZTDZYI.js → init-handler-RJU5QMAP.js} +6 -6
  234. package/dist/cli/chunks/init-wizard-JCKNGIGT.js +2 -0
  235. package/dist/cli/chunks/kernel-F7ILJTYD.js +2 -0
  236. package/dist/cli/chunks/{kilocode-installer-XENXNEIU.js → kilocode-installer-BCPOCVMC.js} +2 -2
  237. package/dist/cli/chunks/{kiro-installer-3PG2TJ67.js → kiro-installer-GFCWCB2S.js} +2 -2
  238. package/dist/cli/chunks/knowledge-graph-VTXDBHB2.js +2 -0
  239. package/dist/cli/chunks/learning-FZTD72CF.js +131 -0
  240. package/dist/cli/chunks/{llm-router-RKVDEWU2.js → llm-router-GJVKGRJL.js} +4 -4
  241. package/dist/cli/chunks/llm-router-service-TNOWQINA.js +2 -0
  242. package/dist/cli/chunks/{load-ITHC564X.js → load-YKTPOYBE.js} +2 -2
  243. package/dist/cli/chunks/load-test-FPVBK2EV.js +2 -0
  244. package/dist/cli/chunks/{mcp-TCL5UW3N.js → mcp-LT6R2IKS.js} +2 -2
  245. package/dist/cli/chunks/{memory-BKDAY2N2.js → memory-4HKKOLRY.js} +5 -5
  246. package/dist/cli/chunks/memory-backend-2QE7O67A.js +2 -0
  247. package/dist/cli/chunks/{memory-handlers-WN4FXFOA.js → memory-handlers-X4CMVBXB.js} +2 -2
  248. package/dist/cli/chunks/{multi-model-executor-VHAT7ZPF.js → multi-model-executor-2YPM2WTK.js} +2 -2
  249. package/dist/cli/chunks/{opencode-installer-E3VM3EEY.js → opencode-installer-WBAJMH5K.js} +2 -2
  250. package/dist/cli/chunks/{orchestrator-BMQ6X762.js → orchestrator-5W5WVMVJ.js} +109 -25
  251. package/dist/cli/chunks/pattern-null-store-UI35ORHW.js +2 -0
  252. package/dist/cli/chunks/{pattern-usage-recorder-GOOR2BV5.js → pattern-usage-recorder-GXRMNPAZ.js} +2 -2
  253. package/dist/cli/chunks/{pipeline-5NSFQQIX.js → pipeline-2NA4DRDA.js} +2 -2
  254. package/dist/cli/chunks/{platform-SQM34J5G.js → platform-BGERNQ5V.js} +2 -2
  255. package/dist/cli/chunks/{plugin-UQJZRMZG.js → plugin-L4EPVENR.js} +2 -2
  256. package/dist/cli/chunks/{prime-radiant-advanced-wasm-WMDJOL4S.js → prime-radiant-advanced-wasm-RTQRTPTM.js} +2 -2
  257. package/dist/cli/chunks/project-root-S7WDFTMU.js +2 -0
  258. package/dist/cli/chunks/protocol-executor-OPANXQVB.js +2 -0
  259. package/dist/cli/chunks/{protocol-handler-OBDCVY6X.js → protocol-handler-SYQXM6JK.js} +2 -2
  260. package/dist/cli/chunks/{prove-XDC7I4XT.js → prove-5O7GPJCU.js} +2 -2
  261. package/dist/cli/chunks/qe-reasoning-bank-3OTF4DYQ.js +2 -0
  262. package/dist/cli/chunks/{quality-L4GQ6WX4.js → quality-KIIDHGNF.js} +2 -2
  263. package/dist/cli/chunks/{quality-gate-MJG66LKN.js → quality-gate-H65VECD3.js} +3 -3
  264. package/dist/cli/chunks/queen-coordinator-WTYH4TAN.js +2 -0
  265. package/dist/cli/chunks/{real-embeddings-HW4G2LWL.js → real-embeddings-DYIOLKQ3.js} +2 -2
  266. package/dist/cli/chunks/{ref-validation-FC7JOJ2C.js → ref-validation-CSBJOMZM.js} +2 -2
  267. package/dist/cli/chunks/{roocode-installer-KWS4CEIC.js → roocode-installer-G7OVYXEN.js} +2 -2
  268. package/dist/cli/chunks/router-DBBW4NC2.js +2 -0
  269. package/dist/cli/chunks/routing-feedback-W35QHCL4.js +2 -0
  270. package/dist/cli/chunks/{routing-handler-QF4WVB2S.js → routing-handler-ZNZPPI5Y.js} +2 -2
  271. package/dist/cli/chunks/{ruvector-commands-2MTCOUK6.js → ruvector-commands-C6IG3OY3.js} +2 -2
  272. package/dist/cli/chunks/rvf-dual-writer-X3NSL25Z.js +2 -0
  273. package/dist/cli/chunks/rvf-migration-adapter-TZR7GDOK.js +2 -0
  274. package/dist/cli/chunks/{rvf-migration-coordinator-BREJCXWN.js → rvf-migration-coordinator-4ATTHGHD.js} +2 -2
  275. package/dist/cli/chunks/rvf-native-adapter-HD25ZYV5.js +2 -0
  276. package/dist/cli/chunks/{rvf-store-integrity-KKC6HOJD.js → rvf-store-integrity-3G6LFLT3.js} +2 -2
  277. package/dist/cli/chunks/safe-db-ZS2QKANY.js +2 -0
  278. package/dist/cli/chunks/schedule-ZH6VNA32.js +2 -0
  279. package/dist/cli/chunks/scheduler-T6CD74B6.js +2 -0
  280. package/dist/cli/chunks/{security-OSAE7VAP.js → security-A3IMVLFM.js} +3 -3
  281. package/dist/cli/chunks/{shared-rvf-adapter-COUOS665.js → shared-rvf-adapter-VHWQ6US5.js} +2 -2
  282. package/dist/cli/chunks/{shared-rvf-dual-writer-YXMPZKQE.js → shared-rvf-dual-writer-JB3QS7IG.js} +2 -2
  283. package/dist/cli/chunks/sqlite-persistence-47WU5EKZ.js +2 -0
  284. package/dist/cli/chunks/{standalone-memory-E6JBMOIL.js → standalone-memory-DDNXCSBD.js} +2 -2
  285. package/dist/cli/chunks/{status-handler-AFTCIYIX.js → status-handler-2HK7XPEK.js} +2 -2
  286. package/dist/cli/chunks/{structural-health-2FROCEI4.js → structural-health-DSJVLEPV.js} +2 -2
  287. package/dist/cli/chunks/{sync-VAYTOWDC.js → sync-3MUV6S5E.js} +2 -2
  288. package/dist/cli/chunks/{sync-YIQYOFGW.js → sync-NTUR53PI.js} +2 -2
  289. package/dist/cli/chunks/{task-handler-KVQHDEX3.js → task-handler-74MZN2EO.js} +2 -2
  290. package/dist/cli/chunks/{task-handlers-MVVECQA6.js → task-handlers-VJR6EHRZ.js} +3 -3
  291. package/dist/cli/chunks/{test-5JSVTOMY.js → test-O6FK3FVF.js} +4 -4
  292. package/dist/cli/chunks/test-runner-process-2NPW3UDQ.js +2 -0
  293. package/dist/cli/chunks/{test-scheduling-HBOHVLI3.js → test-scheduling-Q6QEEOS6.js} +3 -3
  294. package/dist/cli/chunks/{token-bootstrap-5VEPTPFA.js → token-bootstrap-TTRCECLP.js} +2 -2
  295. package/dist/cli/chunks/{token-usage-TBJHDLY6.js → token-usage-YEEFWSSI.js} +2 -2
  296. package/dist/cli/chunks/{transformers-VAWYMHMZ.js → transformers-BZCHJJJT.js} +2 -2
  297. package/dist/cli/chunks/tree-sitter-wasm-parser-RZAND65G.js +2 -0
  298. package/dist/cli/chunks/{types-R5SDZU2E.js → types-4AOKZYOX.js} +2 -2
  299. package/dist/cli/chunks/unified-memory-FZ5K2C7W.js +2 -0
  300. package/dist/cli/chunks/unified-memory-hnsw-VREWX56M.js +2 -0
  301. package/dist/cli/chunks/unified-persistence-YZGMKX6B.js +2 -0
  302. package/dist/cli/chunks/{upgrade-K5PIHXRB.js → upgrade-2MWW6BT2.js} +2 -2
  303. package/dist/cli/chunks/{validate-RPTS7RYJ.js → validate-PAEV3GT5.js} +2 -2
  304. package/dist/cli/chunks/{validate-swarm-B2ZL556X.js → validate-swarm-ZIXACK5K.js} +2 -2
  305. package/dist/cli/chunks/visual-security-GXGSFBVA.js +2 -0
  306. package/dist/cli/chunks/{web-tree-sitter-K4DUJC32.js → web-tree-sitter-VLTXZFAB.js} +2 -2
  307. package/dist/cli/chunks/{windsurf-installer-OK2AJN35.js → windsurf-installer-VELMLOZF.js} +2 -2
  308. package/dist/cli/chunks/witness-chain-MRJKVCOW.js +2 -0
  309. package/dist/cli/chunks/witness-chain-WWHJKITG.js +2 -0
  310. package/dist/cli/chunks/{witness-chain-repair-L6Y5RFXR.js → witness-chain-repair-5SAXPETG.js} +2 -2
  311. package/dist/cli/chunks/{witness-chain-verifier-N4CW7FZX.js → witness-chain-verifier-MIDWD4JS.js} +2 -2
  312. package/dist/cli/chunks/{witness-key-manager-TDNPS3WD.js → witness-key-manager-OSVCWOB2.js} +2 -2
  313. package/dist/cli/chunks/{workflow-XRZA3YCY.js → workflow-MK7A7QCX.js} +4 -4
  314. package/dist/cli/chunks/workflow-orchestrator-SG7DV72E.js +2 -0
  315. package/dist/cli/chunks/{wrappers-5JIFWKN6.js → wrappers-5QFMCKXL.js} +2 -2
  316. package/dist/cli/commands/coverage.js +6 -0
  317. package/dist/cli/commands/learning-prune.d.ts +14 -0
  318. package/dist/cli/commands/learning-prune.js +105 -0
  319. package/dist/cli/commands/learning.js +9 -0
  320. package/dist/cli/handlers/brain-handler.js +12 -1
  321. package/dist/cli/utils/coverage-verdict.js +14 -3
  322. package/dist/context/compaction/index.d.ts +7 -0
  323. package/dist/context/compaction/index.js +30 -6
  324. package/dist/coordination/handlers/coverage-evidence.d.ts +19 -0
  325. package/dist/coordination/handlers/coverage-evidence.js +31 -2
  326. package/dist/coordination/handlers/coverage-handlers.js +5 -1
  327. package/dist/coordination/handlers/coverage-target.js +8 -1
  328. package/dist/coordination/handlers/quality-handlers.js +9 -1
  329. package/dist/coordination/result-saver-adapters.js +1 -0
  330. package/dist/coordination/result-saver.js +9 -5
  331. package/dist/domains/chaos-resilience/services/chaos-engineer.d.ts +1 -0
  332. package/dist/domains/chaos-resilience/services/chaos-engineer.js +23 -45
  333. package/dist/domains/coverage-analysis/collected-metrics.d.ts +22 -6
  334. package/dist/domains/coverage-analysis/collected-metrics.js +37 -12
  335. package/dist/domains/coverage-analysis/services/coverage-analyzer.js +2 -0
  336. package/dist/domains/defect-intelligence/services/defect-predictor.js +3 -6
  337. package/dist/domains/quality-assessment/coverage-report-event.d.ts +8 -0
  338. package/dist/domains/quality-assessment/coverage-report-event.js +22 -1
  339. package/dist/domains/quality-assessment/interfaces.d.ts +6 -0
  340. package/dist/domains/quality-assessment/services/quality-analyzer.d.ts +4 -0
  341. package/dist/domains/quality-assessment/services/quality-analyzer.js +63 -17
  342. package/dist/domains/test-execution/interfaces.d.ts +5 -0
  343. package/dist/domains/test-execution/services/test-executor.js +6 -0
  344. package/dist/init/init-wizard-hooks.d.ts +1 -1
  345. package/dist/init/init-wizard-hooks.js +7 -8
  346. package/dist/init/phases/07-hooks.js +90 -6
  347. package/dist/init/phases/08-mcp.js +9 -0
  348. package/dist/init/settings-merge.d.ts +13 -0
  349. package/dist/init/settings-merge.js +49 -2
  350. package/dist/integrations/agent-booster-wasm/agent_booster_wasm.js +849 -0
  351. package/dist/integrations/agent-booster-wasm/agent_booster_wasm_bg.wasm +0 -0
  352. package/dist/integrations/agent-booster-wasm/index.d.ts +8 -0
  353. package/dist/integrations/agent-booster-wasm/index.js +25 -2
  354. package/dist/integrations/agent-booster-wasm/package.json +16 -0
  355. package/dist/integrations/ruvector/brain-rvf-exporter.d.ts +25 -0
  356. package/dist/integrations/ruvector/brain-rvf-exporter.js +154 -61
  357. package/dist/learning/dream/dream-engine.d.ts +27 -3
  358. package/dist/learning/dream/dream-engine.js +97 -28
  359. package/dist/learning/dream/dream-lock-retry.d.ts +38 -0
  360. package/dist/learning/dream/dream-lock-retry.js +66 -0
  361. package/dist/learning/dream/speculative-dreamer.js +1 -1
  362. package/dist/learning/learning-retention.d.ts +103 -0
  363. package/dist/learning/learning-retention.js +213 -0
  364. package/dist/mcp/bundle.js +501 -496
  365. package/dist/mcp/handlers/domain-handler-configs.d.ts +9 -1
  366. package/dist/mcp/handlers/domain-handler-configs.js +24 -14
  367. package/dist/mcp/protocol-server.js +1 -1
  368. package/dist/mcp/tools/chaos-resilience/inject.d.ts +3 -4
  369. package/dist/mcp/tools/chaos-resilience/inject.js +11 -81
  370. package/dist/mcp/tools/learning-optimization/dream.d.ts +8 -0
  371. package/dist/mcp/tools/learning-optimization/dream.js +4 -0
  372. package/package.json +4 -2
  373. package/dist/cli/chunks/adapter-KCQDVYY2.js +0 -2
  374. package/dist/cli/chunks/agent-booster-wasm-6RRQWMNE.js +0 -2
  375. package/dist/cli/chunks/aqe-learning-engine-SAQOHSGN.js +0 -2
  376. package/dist/cli/chunks/base-WCACU3FN.js +0 -2
  377. package/dist/cli/chunks/brain-handler-GTQNHHZS.js +0 -94
  378. package/dist/cli/chunks/browser-workflow-G6IASEAP.js +0 -2
  379. package/dist/cli/chunks/chunk-C6JTLKG7.js +0 -141
  380. package/dist/cli/chunks/chunk-K65CGKLD.js +0 -8
  381. package/dist/cli/chunks/chunk-MB46UBGY.js +0 -3
  382. package/dist/cli/chunks/chunk-N4CYAKOX.js +0 -79
  383. package/dist/cli/chunks/chunk-PT4FMJPQ.js +0 -3
  384. package/dist/cli/chunks/chunk-S5AZCIZS.js +0 -2
  385. package/dist/cli/chunks/chunk-UT2VZ33P.js +0 -2
  386. package/dist/cli/chunks/client-TV3V2YZ5.js +0 -2
  387. package/dist/cli/chunks/core-handlers-PZT4OLWR.js +0 -2
  388. package/dist/cli/chunks/coverage-NV3C4IMM.js +0 -50
  389. package/dist/cli/chunks/cross-domain-router-QOFCZ7G4.js +0 -2
  390. package/dist/cli/chunks/dream-TRFBGDSQ.js +0 -2
  391. package/dist/cli/chunks/file-discovery-WCKGMSPZ.js +0 -2
  392. package/dist/cli/chunks/heartbeat-scheduler-P44A2OX3.js +0 -2
  393. package/dist/cli/chunks/hnsw-adapter-ZJQIQJKC.js +0 -2
  394. package/dist/cli/chunks/hnsw-index-HMG2GH3Z.js +0 -2
  395. package/dist/cli/chunks/hybrid-backend-B7M74PZG.js +0 -2
  396. package/dist/cli/chunks/impact-analyzer-PZYOVKQO.js +0 -2
  397. package/dist/cli/chunks/init-wizard-TZDJQK3U.js +0 -2
  398. package/dist/cli/chunks/kernel-Y6RRIOKW.js +0 -2
  399. package/dist/cli/chunks/knowledge-graph-BVD5Z66M.js +0 -2
  400. package/dist/cli/chunks/learning-6KDH7FK4.js +0 -122
  401. package/dist/cli/chunks/llm-router-service-KHCAMSUU.js +0 -2
  402. package/dist/cli/chunks/load-test-RUF7DZA5.js +0 -2
  403. package/dist/cli/chunks/memory-backend-7ZLFOVGG.js +0 -2
  404. package/dist/cli/chunks/pattern-null-store-RY6CVYHP.js +0 -2
  405. package/dist/cli/chunks/project-root-IO5KRNGL.js +0 -2
  406. package/dist/cli/chunks/protocol-executor-U2CUDWDE.js +0 -2
  407. package/dist/cli/chunks/qe-reasoning-bank-DQSSX2IP.js +0 -2
  408. package/dist/cli/chunks/queen-coordinator-6FN4BZIX.js +0 -2
  409. package/dist/cli/chunks/router-YUO3I7RU.js +0 -2
  410. package/dist/cli/chunks/routing-feedback-36SLQGJE.js +0 -2
  411. package/dist/cli/chunks/rvf-dual-writer-FRYZH3WZ.js +0 -2
  412. package/dist/cli/chunks/rvf-migration-adapter-XXNITL5I.js +0 -2
  413. package/dist/cli/chunks/rvf-native-adapter-D2WWKJIV.js +0 -2
  414. package/dist/cli/chunks/safe-db-4RRIGRXD.js +0 -2
  415. package/dist/cli/chunks/schedule-25RTO4DQ.js +0 -2
  416. package/dist/cli/chunks/scheduler-BPIOJZ5P.js +0 -2
  417. package/dist/cli/chunks/sqlite-persistence-EDF47DDX.js +0 -2
  418. package/dist/cli/chunks/test-runner-process-LEPF2OSS.js +0 -2
  419. package/dist/cli/chunks/tree-sitter-wasm-parser-TSZTCMFV.js +0 -2
  420. package/dist/cli/chunks/unified-memory-TLGSSLMI.js +0 -2
  421. package/dist/cli/chunks/unified-memory-hnsw-MSUR7ZOO.js +0 -2
  422. package/dist/cli/chunks/unified-persistence-VFFOTWK7.js +0 -2
  423. package/dist/cli/chunks/visual-security-6Q44XNLB.js +0 -2
  424. package/dist/cli/chunks/witness-chain-KDOMXDQX.js +0 -2
  425. package/dist/cli/chunks/witness-chain-N3OY2RMH.js +0 -2
  426. package/dist/cli/chunks/workflow-orchestrator-CVNNT2RJ.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.13");process.exit(0)}
2
- import{a as v,b as I,e as O}from"./chunk-3Y2ROSCL.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-WMDJOL4S.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.15");process.exit(0)}
2
+ import{a as v,b as I,e as O}from"./chunk-HL2ANKN3.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-RTQRTPTM.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};
@@ -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.13");process.exit(0)}
2
- import{a as F,d as C}from"./chunk-S5AZCIZS.js";import{a as E}from"./chunk-JQGMW45H.js";import{a as O,b as P,c as x,e as J}from"./chunk-KDNJ4F3P.js";import{b as W,d as B}from"./chunk-J2ZIFFM6.js";var Q=new Set(["false","0","off","no"]),K=new Set([...Q,"disabled","disable","none","never"]),V=30,G=36500;function pe(l=process.env){let e=l.AQE_WORKERS_ENABLED;return e===void 0?!0:!Q.has(e.trim().toLowerCase())}function ge(l=process.env){let e=l.AQE_DISABLED_WORKERS;if(!e)return[];let t=e.split(",").map(i=>i.trim().toLowerCase()).filter(i=>i.length>0);return Array.from(new Set(t))}function fe(l=process.env){let e=l.AQE_DREAM_INSIGHTS_RETENTION_DAYS;if(e===void 0||e.trim()==="")return{retentionDays:V};let t=e.trim().toLowerCase();if(K.has(t))return{retentionDays:null};if(/^\d+$/.test(t)){let i=Number(t);if(i>=1&&i<=G)return{retentionDays:i}}return{retentionDays:null,warning:`Invalid AQE_DREAM_INSIGHTS_RETENTION_DAYS=${JSON.stringify(e)}; expected a whole number of days (1-${G}), 0 or "off". The dream_insights retention sweep is off until this is fixed; nothing is deleted.`}}var I="quality-daemon",R=class{constructor(e){this.backend=e}backend;async get(e,t){return this.backend.kvGet(e,t?.namespace??I)}async set(e,t){await this.backend.kvSet(e,t,I)}async search(e,t,i){return this.backend.kvSearch(e,i?.namespace??I,t)}};import{cpus as ce,freemem as de,totalmem as he,loadavg as me}from"os";var p=class{queues={now:[],next:[],later:[]};_maxSize;constructor(e=1e3){this._maxSize=e}enqueue(e){return this.size>=this._maxSize&&(this.pruneExpired(),this.size>=this._maxSize)?!1:(this.queues[e.priority].push(e),!0)}dequeue(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(;i.length>0;){let r=i.shift();if(!(r.ttlMs&&e-r.createdAt>r.ttlMs))return r}}}peek(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(let r of i)if(!r.ttlMs||e-r.createdAt<=r.ttlMs)return r}}drainPriority(e){let t=this.queues[e].splice(0),i=Date.now();return t.filter(r=>!r.ttlMs||i-r.createdAt<=r.ttlMs)}pruneExpired(){let e=0,t=Date.now();for(let i of["now","next","later"]){let r=this.queues[i].length;this.queues[i]=this.queues[i].filter(o=>!o.ttlMs||t-o.createdAt<=o.ttlMs),e+=r-this.queues[i].length}return e}get size(){return this.queues.now.length+this.queues.next.length+this.queues.later.length}get depths(){return{now:this.queues.now.length,next:this.queues.next.length,later:this.queues.later.length}}get isEmpty(){return this.size===0}clear(){this.queues.now=[],this.queues.next=[],this.queues.later=[]}};import{watch as Y}from"fs";import{resolve as $,join as X}from"path";import{existsSync as Z,readFileSync as ee}from"fs";var M=1e4,te={repoRoot:process.cwd(),debounceMs:500,maxChangedFiles:200,pollIntervalMs:5e3},g=class{constructor(e,t){this.queue=e;this.options={...te,...t}}queue;watcher;pollTimer;options;lastKnownHeads=new Map;debounceTimer;_running=!1;_polling=!1;get running(){return this._running}async start(){if(this._running)return;let e=$(this.options.repoRoot,".git","refs","heads");if(!Z(e))throw new Error(`Git refs directory not found: ${e}`);await this.snapshotHeads(),process.platform==="darwin"||process.platform==="win32"?this.watcher=Y(e,{recursive:!0},(i,r)=>{r&&this.handleRefChange(r)}):(this.pollTimer=setInterval(()=>{this.poll().catch(i=>{console.debug("[GitWatcher] Poll error:",i)})},this.options.pollIntervalMs),this.pollTimer.unref?.()),this._running=!0}stop(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0),this.watcher&&(this.watcher.close(),this.watcher=void 0),this._running=!1}async poll(){if(this._polling)return[];this._polling=!0;let e=[];try{let t=await C(["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot,timeout:M});for(let i of t.trim().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.15");process.exit(0)}
2
+ import{a as F,d as C}from"./chunk-OBDONJQM.js";import{a as E}from"./chunk-NQS3BWS6.js";import{a as O,b as P,c as x,e as J}from"./chunk-5G4UFTV4.js";import{b as W,d as B}from"./chunk-SZAZQZWI.js";var Q=new Set(["false","0","off","no"]),K=new Set([...Q,"disabled","disable","none","never"]),V=30,G=36500;function pe(l=process.env){let e=l.AQE_WORKERS_ENABLED;return e===void 0?!0:!Q.has(e.trim().toLowerCase())}function ge(l=process.env){let e=l.AQE_DISABLED_WORKERS;if(!e)return[];let t=e.split(",").map(i=>i.trim().toLowerCase()).filter(i=>i.length>0);return Array.from(new Set(t))}function fe(l=process.env){let e=l.AQE_DREAM_INSIGHTS_RETENTION_DAYS;if(e===void 0||e.trim()==="")return{retentionDays:V};let t=e.trim().toLowerCase();if(K.has(t))return{retentionDays:null};if(/^\d+$/.test(t)){let i=Number(t);if(i>=1&&i<=G)return{retentionDays:i}}return{retentionDays:null,warning:`Invalid AQE_DREAM_INSIGHTS_RETENTION_DAYS=${JSON.stringify(e)}; expected a whole number of days (1-${G}), 0 or "off". The dream_insights retention sweep is off until this is fixed; nothing is deleted.`}}var I="quality-daemon",R=class{constructor(e){this.backend=e}backend;async get(e,t){return this.backend.kvGet(e,t?.namespace??I)}async set(e,t){await this.backend.kvSet(e,t,I)}async search(e,t,i){return this.backend.kvSearch(e,i?.namespace??I,t)}};import{cpus as ce,freemem as de,totalmem as he,loadavg as me}from"os";var p=class{queues={now:[],next:[],later:[]};_maxSize;constructor(e=1e3){this._maxSize=e}enqueue(e){return this.size>=this._maxSize&&(this.pruneExpired(),this.size>=this._maxSize)?!1:(this.queues[e.priority].push(e),!0)}dequeue(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(;i.length>0;){let r=i.shift();if(!(r.ttlMs&&e-r.createdAt>r.ttlMs))return r}}}peek(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(let r of i)if(!r.ttlMs||e-r.createdAt<=r.ttlMs)return r}}drainPriority(e){let t=this.queues[e].splice(0),i=Date.now();return t.filter(r=>!r.ttlMs||i-r.createdAt<=r.ttlMs)}pruneExpired(){let e=0,t=Date.now();for(let i of["now","next","later"]){let r=this.queues[i].length;this.queues[i]=this.queues[i].filter(o=>!o.ttlMs||t-o.createdAt<=o.ttlMs),e+=r-this.queues[i].length}return e}get size(){return this.queues.now.length+this.queues.next.length+this.queues.later.length}get depths(){return{now:this.queues.now.length,next:this.queues.next.length,later:this.queues.later.length}}get isEmpty(){return this.size===0}clear(){this.queues.now=[],this.queues.next=[],this.queues.later=[]}};import{watch as Y}from"fs";import{resolve as $,join as X}from"path";import{existsSync as Z,readFileSync as ee}from"fs";var M=1e4,te={repoRoot:process.cwd(),debounceMs:500,maxChangedFiles:200,pollIntervalMs:5e3},g=class{constructor(e,t){this.queue=e;this.options={...te,...t}}queue;watcher;pollTimer;options;lastKnownHeads=new Map;debounceTimer;_running=!1;_polling=!1;get running(){return this._running}async start(){if(this._running)return;let e=$(this.options.repoRoot,".git","refs","heads");if(!Z(e))throw new Error(`Git refs directory not found: ${e}`);await this.snapshotHeads(),process.platform==="darwin"||process.platform==="win32"?this.watcher=Y(e,{recursive:!0},(i,r)=>{r&&this.handleRefChange(r)}):(this.pollTimer=setInterval(()=>{this.poll().catch(i=>{console.debug("[GitWatcher] Poll error:",i)})},this.options.pollIntervalMs),this.pollTimer.unref?.()),this._running=!0}stop(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0),this.watcher&&(this.watcher.close(),this.watcher=void 0),this._running=!1}async poll(){if(this._polling)return[];this._polling=!0;let e=[];try{let t=await C(["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot,timeout:M});for(let i of t.trim().split(`
3
3
  `)){if(!i)continue;let[r,o]=i.split(" "),n=this.lastKnownHeads.get(r);n&&n!==o&&(e.push(r),await this.enqueueCommitAnalysis(r,o)),this.lastKnownHeads.set(r,o)}}catch{}finally{this._polling=!1}return e}handleRefChange(e){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.processRefChange(e).catch(t=>{console.debug("[GitWatcher] Error processing ref change:",t)})},this.options.debounceMs)}async processRefChange(e){let t=e.replace(/\\/g,"/"),i=$(this.options.repoRoot,".git","refs","heads"),r=X(i,e),o;try{o=ee(r,"utf-8").trim()}catch{return}this.lastKnownHeads.get(t)!==o&&(this.lastKnownHeads.set(t,o),await this.enqueueCommitAnalysis(t,o))}async enqueueCommitAnalysis(e,t){if(E(t,"commit hash"))return;let i=[];try{i=(await C(["diff-tree","--no-commit-id","--name-only","-r",t],{cwd:this.options.repoRoot,timeout:M})).trim().split(`
4
4
  `).filter(Boolean).slice(0,this.options.maxChangedFiles)}catch{}let r={type:"git_commit",branch:e,commitHash:t,changedFiles:i},o={id:`git-${t}-${Date.now()}`,priority:"next",payload:r,createdAt:Date.now(),source:"git-watcher",ttlMs:300*1e3};this.queue.enqueue(o)}async snapshotHeads(){try{let e=await C(["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot,timeout:M});for(let t of e.trim().split(`
5
5
  `)){if(!t)continue;let[i,r]=t.split(" ");this.lastKnownHeads.set(i,r)}}catch{}}};function A(l,e){return l===null||e===null?0:l-e}var ie={regressionThreshold:2,gapThreshold:60,memoryPrefix:"quality-daemon:coverage"},f=class{constructor(e,t){this.queue=e;this.options={...ie,...t}}queue;options;async analyze(e,t,i){let r=await t.get(`${this.options.memoryPrefix}:snapshot`);if(await t.set(`${this.options.memoryPrefix}:snapshot`,e),!r)return{regressionDetected:!1,overallDelta:{line:0,branch:0,function:0,statement:0},affectedFiles:[],newGaps:[]};let o=r,n={line:e.overall.line-o.overall.line,branch:A(e.overall.branch,o.overall.branch??null),function:A(e.overall.function,o.overall.function??null),statement:A(e.overall.statement,o.overall.statement??null)},s=n.line<-this.options.regressionThreshold||(n.branch??0)<-this.options.regressionThreshold,a=i??Object.keys(e.files),c=[],d=[];for(let h of a){let u=e.files[h],m=o.files[h];if(!u)continue;let q=m?u.line-m.line:0,N=m?u.branch-m.branch:0,T=m?u.uncoveredLines.filter(_=>!m.uncoveredLines.includes(_)):u.uncoveredLines;if((q!==0||N!==0||T.length>0)&&c.push({file:h,lineDelta:q,branchDelta:N,newUncoveredLines:T}),u.line<this.options.gapThreshold){let _=this.computeRiskScore(u,T.length);d.push({file:h,uncoveredLines:u.uncoveredLines,currentCoverage:u.line,riskScore:_})}}return(s||d.length>0)&&this.enqueueTestSuggestion(e,o,d),await t.set(`${this.options.memoryPrefix}:delta`,{timestamp:Date.now(),overallDelta:n,regressionDetected:s,affectedFileCount:c.length,gapCount:d.length}),{regressionDetected:s,overallDelta:n,affectedFiles:c,newGaps:d}}async buildSnapshot(e){let t=await e.get("coverage:latest"),i=F(t);if(i)return{timestamp:Date.now(),overall:{line:i.line,branch:i.branch,function:i.function,statement:i.statement},files:t&&typeof t.files=="object"?t.files:{}}}computeRiskScore(e,t){let r=1-Math.min(100,Math.max(0,e.line))/100,o=Math.min(t/50,1);return Math.min(1,r*.6+o*.4)}enqueueTestSuggestion(e,t,i){let r={type:"coverage_delta",previousSnapshot:`snapshot-${t.timestamp}`,currentSnapshot:`snapshot-${e.timestamp}`},o={id:`coverage-delta-${Date.now()}`,priority:i.some(n=>n.riskScore>.8)?"now":"next",payload:r,createdAt:Date.now(),source:"coverage-delta",ttlMs:600*1e3};this.queue.enqueue(o)}};J();import{execFile as re}from"child_process";import{promisify as oe}from"util";var ne=oe(re),se={runsPerWorkflow:10,flakyThreshold:3,repo:""},y=class{constructor(e,t){this.queue=e;this.options={...se,...t}}queue;options;async check(){let e=await this.fetchRecentRuns(),t=this.groupByWorkflow(e),i=[],r=[],o=0;for(let[s,a]of Object.entries(t)){let c=a.filter(m=>m.conclusion==="failure").length,d=a.length>0?(a.length-c)/a.length*100:100,h=this.countConsecutiveFailures(a),u=a[0]?.conclusion??"unknown";u==="failure"&&o++,h>=this.options.flakyThreshold&&(r.push(s),this.enqueueFailureAlert(s,a[0])),i.push({name:s,recentRuns:a.length,failedRuns:c,successRate:Math.round(d*10)/10,lastConclusion:u,consecutiveFailures:h})}let n=this.calculateHealthScore(i);return{timestamp:Date.now(),workflows:i,failingWorkflows:o,flakyWorkflows:r,healthScore:n}}async fetchRecentRuns(){try{let e=["run","list","--limit",String(this.options.runsPerWorkflow*5),"--json","name,status,conclusion,headBranch,number,databaseId,createdAt"];this.options.repo&&e.push("--repo",this.options.repo);let{stdout:t}=await ne("gh",e,{timeout:15e3});return JSON.parse(t).map(r=>({name:r.name,status:r.status,conclusion:r.conclusion??"pending",headBranch:r.headBranch,runNumber:r.number,databaseId:r.databaseId,createdAt:r.createdAt}))}catch{return[]}}groupByWorkflow(e){let t=O();for(let i of e){let r=P(t,i.name);r||(r=[],x(t,i.name,r)),r.push(i)}for(let i of Object.keys(t))x(t,i,P(t,i).slice(0,this.options.runsPerWorkflow));return t}countConsecutiveFailures(e){let t=0;for(let i of e)if(i.conclusion==="failure")t++;else break;return t}calculateHealthScore(e){if(e.length===0)return 100;let t=e.reduce((i,r)=>i+r.successRate,0)/e.length;return Math.round(t)}enqueueFailureAlert(e,t){let i={type:"ci_failure",workflowName:e,runId:t.databaseId,conclusion:t.conclusion},r={id:`ci-failure-${e}-${Date.now()}`,priority:"now",payload:i,createdAt:Date.now(),source:"ci-monitor",ttlMs:1800*1e3};this.queue.enqueue(r)}};var ae={memoryPrefix:"quality-daemon:suggestions",maxSuggestions:100,minRiskScore:.3},v=class{options;constructor(e){this.options={...ae,...e}}async suggest(e,t,i){let r=[],o=e.filter(s=>s.riskScore>=this.options.minRiskScore);for(let s of o){let a=t.includes(s.file),c=this.determinePriority(s,a),d=this.determineTestType(s.file),h=this.estimateEffort(s);r.push({id:`suggestion-${Date.now()}-${r.length}`,file:s.file,uncoveredLines:s.uncoveredLines.slice(0,50),suggestedTestType:d,description:this.generateDescription(s,d),priority:c,estimatedEffort:h,createdAt:Date.now(),status:"pending"})}r.sort((s,a)=>{let c={high:0,medium:1,low:2};return c[s.priority]-c[a.priority]});let n=r.slice(0,this.options.maxSuggestions);return await this.storeSuggestions(n,i),n}async getPending(e){return(await e.get(`${this.options.memoryPrefix}:list`)??[]).filter(i=>i.status==="pending")}async updateStatus(e,t,i){let r=await i.get(`${this.options.memoryPrefix}:list`);if(!r)return!1;let o=r.findIndex(s=>s.id===e);if(o===-1)return!1;let n=r.map((s,a)=>a===o?{...s,status:t}:s);return await i.set(`${this.options.memoryPrefix}:list`,n),!0}determinePriority(e,t){return e.riskScore>.8?"high":t||e.riskScore>.5?"medium":"low"}determineTestType(e){return e.includes("/api/")||e.includes("/routes/")||e.includes("/handlers/")?"integration":e.includes("/e2e/")||e.includes("/pages/")||e.includes("/views/")?"e2e":"unit"}estimateEffort(e){return e.uncoveredLines.length<=10?"small":e.uncoveredLines.length<=50?"medium":"large"}generateDescription(e,t){let i=e.uncoveredLines.length,r=Math.round(e.currentCoverage);return`Add ${t} tests for ${e.file} (${i} uncovered lines, ${r}% coverage, risk ${(e.riskScore*100).toFixed(0)}%)`}async storeSuggestions(e,t){let o=[...(await t.get(`${this.options.memoryPrefix}:list`)??[]).filter(n=>n.status!=="pending"),...e].slice(-this.options.maxSuggestions);await t.set(`${this.options.memoryPrefix}:list`,o),await t.set(`${this.options.memoryPrefix}:count`,{pending:e.length,total:o.length,lastUpdated:Date.now()})}};var le={memoryPrefix:"quality-daemon:nightly",maxEntryAge:6048e5,nightlyHour:2},w=class{constructor(e,t){this.queue=e;this.options={...le,...t}}queue;options;lastRunDate;shouldRun(){let e=new Date,t=e.toISOString().split("T")[0];return this.lastRunDate===t?!1:e.getHours()>=this.options.nightlyHour}scheduleIfDue(){if(!this.shouldRun())return!1;let e={type:"nightly",tasks:["consolidate_patterns","prune_expired","generate_report"]},t={id:`nightly-${Date.now()}`,priority:"later",payload:e,createdAt:Date.now(),source:"nightly-consolidation",ttlMs:720*60*1e3};return this.queue.enqueue(t)}async execute(e,t){let i=Date.now(),r=new Date().toISOString().split("T")[0],o=await this.consolidatePatterns(e),n=await this.pruneExpired(e),s=this.generateReport(r,t);await e.set(`${this.options.memoryPrefix}:report:${r}`,s),this.lastRunDate=r;let a={timestamp:Date.now(),patternsConsolidated:o,entriesPruned:n,reportGenerated:!0,durationMs:Date.now()-i};return await e.set(`${this.options.memoryPrefix}:last-result`,a),a}async getLastResult(e){return e.get(`${this.options.memoryPrefix}:last-result`)}async consolidatePatterns(e){let t=await e.search("quality-daemon:*"),i=0;return await e.get("quality-daemon:suggestions:count")&&i++,await e.get("quality-daemon:coverage:delta")&&i++,i}async pruneExpired(e){let t=await e.search("quality-daemon:*"),i=0,r=Date.now();for(let o of t){if(o.endsWith(":snapshot")||o.endsWith(":list"))continue;let n=await e.get(o);n&&typeof n.timestamp=="number"&&r-n.timestamp>this.options.maxEntryAge&&(await e.set(o,{pruned:!0,prunedAt:r}),i++)}return i}generateReport(e,t){return{date:e,coverageHealth:t.coverageHealth??0,ciHealth:t.ciHealth??0,commitsAnalyzed:t.commitsAnalyzed??0,suggestionsGenerated:t.suggestionsGenerated??0,notificationsSent:t.notificationsSent??0,queueDepthAvg:t.queueDepthAvg??0,daemonUptime:t.uptimeSeconds??0}}};B();import{writeFileSync as H,mkdirSync as L,readdirSync as D,readFileSync as U,unlinkSync as z}from"fs";import{join as b}from"path";var ue={maxNotifications:200},k=class{notificationsDir;maxNotifications;webhookUrl;urlValidator;_sentCount=0;constructor(e){this.notificationsDir=e?.notificationsDir??W("notifications"),this.maxNotifications=e?.maxNotifications??ue.maxNotifications,this.webhookUrl=e?.webhookUrl,this.urlValidator=e?.urlValidator}get sentCount(){return this._sentCount}initialize(){L(this.notificationsDir,{recursive:!0})}async send(e){let t={...e,id:`notif-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now(),read:!1};return this.writeToFile(t),this.webhookUrl&&await this.sendWebhook(t),this._sentCount++,this.pruneOldNotifications(),t}list(e){let t=e?.limit??50;try{let i=D(this.notificationsDir).filter(o=>o.endsWith(".json")).sort().reverse(),r=[];for(let o of i){if(r.length>=t)break;try{let n=U(b(this.notificationsDir,o),"utf-8"),s=JSON.parse(n);if(e?.unreadOnly&&s.read||e?.type&&s.type!==e.type)continue;r.push(s)}catch{}}return r}catch{return[]}}markRead(e){try{let t=D(this.notificationsDir).filter(n=>n.endsWith(`-${e}.json`));if(t.length===0)return!1;let i=b(this.notificationsDir,t[0]),o={...JSON.parse(U(i,"utf-8")),read:!0};return H(i,JSON.stringify(o,null,2)),!0}catch{return!1}}clear(){try{let e=D(this.notificationsDir).filter(t=>t.endsWith(".json"));for(let t of e)z(b(this.notificationsDir,t));return e.length}catch{return 0}}writeToFile(e){try{L(this.notificationsDir,{recursive:!0});let t=`${e.timestamp}-${e.id}.json`,i=b(this.notificationsDir,t);H(i,JSON.stringify(e,null,2))}catch(t){console.debug("[NotificationService] Failed to write notification:",t)}}async sendWebhook(e){if(this.webhookUrl){if(this.urlValidator&&!this.urlValidator(this.webhookUrl)){console.warn("[NotificationService] Webhook URL blocked by SSRF guard:",this.webhookUrl);return}try{let t=await fetch(this.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(5e3)});t.ok||console.debug(`[NotificationService] Webhook returned ${t.status}`)}catch(t){console.debug("[NotificationService] Webhook delivery failed:",t)}}}pruneOldNotifications(){try{let e=D(this.notificationsDir).filter(i=>i.endsWith(".json")).sort();if(e.length<=this.maxNotifications)return;let t=e.slice(0,e.length-this.maxNotifications);for(let i of t)z(b(this.notificationsDir,i))}catch{}}};var S={tickIntervalMs:3e4,ciPollIntervalMs:5*6e4,coverageCheckIntervalMs:2*6e4,cpuThreshold:.7,memoryThreshold:.8},j=class{queue;gitWatcher;coverageDelta;ciMonitor;testSuggester;nightlyConsolidation;notificationService;tickTimer;_running=!1;_startedAt=0;_tickCount=0;_lastTickAt;_throttled=!1;_commitsAnalyzed=0;_suggestionsGenerated=0;_ciHealth=100;_coverageHealth=100;_lastCICheck;_lastCoverageCheck;_memory;config;constructor(e){this.config={tickIntervalMs:e?.tickIntervalMs??S.tickIntervalMs,ciPollIntervalMs:e?.ciPollIntervalMs??S.ciPollIntervalMs,coverageCheckIntervalMs:e?.coverageCheckIntervalMs??S.coverageCheckIntervalMs,cpuThreshold:e?.cpuThreshold??S.cpuThreshold,memoryThreshold:e?.memoryThreshold??S.memoryThreshold},this.queue=new p,this.gitWatcher=new g(this.queue,e?.git),this.coverageDelta=new f(this.queue,e?.coverage),this.ciMonitor=new y(this.queue,e?.ci),this.testSuggester=new v(e?.suggestions),this.nightlyConsolidation=new w(this.queue,e?.nightly),this.notificationService=new k(e?.notifications)}get running(){return this._running}async start(e){this._running||(this._memory=e,this._running=!0,this._startedAt=Date.now(),this.notificationService.initialize(),await this.gitWatcher.start().catch(t=>{console.debug("[QualityDaemon] Git watcher failed to start:",t)}),this.scheduleTick())}async stop(){this._running&&(this._running=!1,this.tickTimer&&(clearTimeout(this.tickTimer),this.tickTimer=void 0),this.gitWatcher.stop(),this._memory&&await this._memory.set("quality-daemon:state",{stoppedAt:Date.now(),tickCount:this._tickCount,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated}))}getStatus(){return{running:this._running,uptimeSeconds:this._running?Math.floor((Date.now()-this._startedAt)/1e3):0,tickCount:this._tickCount,queueDepth:this.queue.depths,lastTickAt:this._lastTickAt,throttled:this._throttled,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated,notificationsSent:this.notificationService.sentCount,ciHealth:this._ciHealth,coverageHealth:this._coverageHealth,lastCICheck:this._lastCICheck,lastCoverageCheck:this._lastCoverageCheck}}scheduleTick(){this._running&&(this.tickTimer=setTimeout(()=>this.tick(),this.config.tickIntervalMs),this.tickTimer.unref?.())}async tick(){if(!(!this._running||!this._memory)){if(this._tickCount++,this._lastTickAt=Date.now(),this._throttled=this.isResourceConstrained(),this._throttled){await this.processNowItems(this._memory),this.scheduleTick();return}await this.processQueue(this._memory),await this.runPeriodicChecks(this._memory),this.nightlyConsolidation.scheduleIfDue(),this.queue.pruneExpired(),this.scheduleTick()}}async processQueue(e){let t=0,i=10;for(;t<i&&!this.queue.isEmpty;){let r=this.queue.dequeue();if(!r)break;await this.handleQueueItem(r,e),t++}}async processNowItems(e){let t=this.queue.drainPriority("now");for(let i of t)await this.handleQueueItem(i,e)}async handleQueueItem(e,t){let i=e.payload;switch(i.type){case"git_commit":{this._commitsAnalyzed++;let r=await this.coverageDelta.buildSnapshot(t);if(r){let o=await this.coverageDelta.analyze(r,t,i.changedFiles);if(o.regressionDetected&&await this.notificationService.send({type:"coverage_drop",title:"Coverage Regression Detected",message:`Line coverage delta: ${o.overallDelta.line.toFixed(1)}% (${o.affectedFiles.length} files affected)`,severity:"high",metadata:{delta:o.overallDelta,commit:i.commitHash}}),o.newGaps.length>0){let n=await this.testSuggester.suggest(o.newGaps,i.changedFiles,t);this._suggestionsGenerated+=n.length,n.length>0&&await this.notificationService.send({type:"suggestion_available",title:"New Test Suggestions Available",message:`${n.length} test suggestions generated for uncovered code`,severity:"info",metadata:{count:n.length}})}}break}case"coverage_delta":{let r=await this.testSuggester.getPending(t);r.length>0&&await this.notificationService.send({type:"suggestion_available",title:"Test Suggestions Pending",message:`${r.length} test suggestions awaiting review`,severity:"info",metadata:{count:r.length}});break}case"gate_failure":await this.notificationService.send({type:"gate_failure",title:`Quality Gate Failed: ${i.gateName}`,message:`Score ${i.score} below threshold ${i.threshold}`,severity:"critical",metadata:{gate:i.gateName,score:i.score,threshold:i.threshold}});break;case"ci_failure":await this.notificationService.send({type:"ci_failure",title:`CI Failure: ${i.workflowName}`,message:`Workflow ${i.workflowName} run #${i.runId} concluded: ${i.conclusion}`,severity:"high",metadata:{workflow:i.workflowName,runId:i.runId}});break;case"nightly":{let r={coverageHealth:this._coverageHealth,ciHealth:this._ciHealth,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated,notificationsSent:this.notificationService.sentCount,queueDepthAvg:this.queue.size,uptimeSeconds:Math.floor((Date.now()-this._startedAt)/1e3)};await this.nightlyConsolidation.execute(t,r);break}default:console.warn("[QualityDaemon] Unhandled payload type:",i.type)}}async runPeriodicChecks(e){let t=Date.now();if(!this._lastCICheck||t-this._lastCICheck>=this.config.ciPollIntervalMs)try{let i=await this.ciMonitor.check();this._ciHealth=i.healthScore,this._lastCICheck=t,i.flakyWorkflows.length>0&&await this.notificationService.send({type:"flaky_detected",title:"Flaky Workflows Detected",message:`${i.flakyWorkflows.length} workflows showing repeated failures: ${i.flakyWorkflows.join(", ")}`,severity:"medium",metadata:{workflows:i.flakyWorkflows}})}catch{}if(!this._lastCoverageCheck||t-this._lastCoverageCheck>=this.config.coverageCheckIntervalMs)try{let i=await this.coverageDelta.buildSnapshot(e);if(i){let r=[i.overall.line,i.overall.branch,i.overall.function,i.overall.statement].filter(o=>typeof o=="number");this._coverageHealth=Math.round(r.reduce((o,n)=>o+n,0)/r.length),this._lastCoverageCheck=t}}catch{}}isResourceConstrained(){if(1-de()/he()>this.config.memoryThreshold)return!0;let t=ce().length;return(t>0?me()[0]/t:0)>this.config.cpuThreshold}};export{pe as a,ge as b,fe as c,R as d,j as e};
@@ -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.13");process.exit(0)}
2
- import{s as g}from"./chunk-WKGTGOYS.js";var m={0:"sqlite-only",1:"hybrid",2:"dual-write-sqlite-primary",3:"dual-write-rvf-primary",4:"rvf-primary"},b=class{config;db=null;rvfStore=null;totalWrites=0;totalReads=0;rvfWriteFailures=0;rvfReadFailures=0;fallbacksUsed=0;sqliteLatencies=[];rvfLatencies=[];sqliteWriteLatencies=[];rvfWriteLatencies=[];constructor(e){this.config={rvfPath:".agentic-qe/patterns.rvf",dimensions:384,enableFallback:!0,...e}}setSqliteDb(e){this.db=e}setRvfStore(e){this.rvfStore=e}get stage(){return this.config.stage}setStage(e){this.config={...this.config,stage:e}}write(e,t){this.totalWrites++;let r={sqliteSuccess:!1,rvfSuccess:!1,stage:this.config.stage,fallbackUsed:!1},n=this.db?this.db.prepare("PRAGMA table_info('qe_pattern_embeddings')").all().some(s=>s.name==="space_id"):!1,c=g()?.spaceId??this.config.embeddingSpaceId;if(!n||!c)return r;let o=this.config.stage<4,i=this.config.stage>=2;if(o&&this.db){let s=performance.now();try{let a=Buffer.from(t instanceof Float32Array?t.buffer:new Float32Array(t).buffer);n?this.db.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.15");process.exit(0)}
2
+ import{s as g}from"./chunk-6NBRMD25.js";var m={0:"sqlite-only",1:"hybrid",2:"dual-write-sqlite-primary",3:"dual-write-rvf-primary",4:"rvf-primary"},b=class{config;db=null;rvfStore=null;totalWrites=0;totalReads=0;rvfWriteFailures=0;rvfReadFailures=0;fallbacksUsed=0;sqliteLatencies=[];rvfLatencies=[];sqliteWriteLatencies=[];rvfWriteLatencies=[];constructor(e){this.config={rvfPath:".agentic-qe/patterns.rvf",dimensions:384,enableFallback:!0,...e}}setSqliteDb(e){this.db=e}setRvfStore(e){this.rvfStore=e}get stage(){return this.config.stage}setStage(e){this.config={...this.config,stage:e}}write(e,t){this.totalWrites++;let r={sqliteSuccess:!1,rvfSuccess:!1,stage:this.config.stage,fallbackUsed:!1},n=this.db?this.db.prepare("PRAGMA table_info('qe_pattern_embeddings')").all().some(s=>s.name==="space_id"):!1,c=g()?.spaceId??this.config.embeddingSpaceId;if(!n||!c)return r;let o=this.config.stage<4,i=this.config.stage>=2;if(o&&this.db){let s=performance.now();try{let a=Buffer.from(t instanceof Float32Array?t.buffer:new Float32Array(t).buffer);n?this.db.prepare(`
3
3
  INSERT INTO qe_pattern_embeddings (pattern_id, embedding, dimension, model, space_id, created_at)
4
4
  VALUES (?, ?, ?, 'all-MiniLM-L6-v2', ?, datetime('now'))
5
5
  ON CONFLICT(pattern_id) DO UPDATE SET
@@ -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.13");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.15");process.exit(0)}
2
2
  var i=["qe-pentest-validator","qe-security-auditor","qe-security-scanner","qe-security-reviewer"],s="claude-sonnet-4-6",a=`anthropic/${s.replace("4-6","4.6")}`,u=s,p=new Set(["opus","fable"]),l=/claude-(opus|fable)-(\d+)(?:[-.](\d{1,2})(?!\d))?/,o={major:4,minor:7};function E(e){let r=e.trim().toLowerCase();if(p.has(r))return!0;let n=l.exec(r);if(!n)return!1;let t=Number(n[2]),c=n[3]===void 0?0:Number(n[3]);return t>o.major||t===o.major&&c>=o.minor}function _(e,r=process.env){return r.AQE_CYBER_VERIFIED==="true"?!1:i.includes(e)}function d(e,r,n,t=process.env){return!_(e,t)||!E(r)?r:n}function f(e){switch(e){case"openrouter":return a;case"bedrock":return"anthropic.claude-sonnet-4-6-v1:0";default:return u}}export{a,u as b,E as c,_ as d,d as e,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.13");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.15");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,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.13");process.exit(0)}
2
- import{b as S}from"./chunk-ZAKQLAHT.js";import{createHash as C}from"crypto";import*as a from"fs";import*as c from"os";import*as n from"path";function P(t){try{return a.realpathSync.native(t)}catch{return t}}function i(){let t="",r="";try{t=c.tmpdir()}catch{}try{r=c.homedir()}catch{}return{platform:process.platform,tmpdir:t,homedir:r,env:process.env,realpath:P}}function m(t){return t==="win32"?n.win32:n.posix}function l(t,r=i()){let e=m(r.platform),o=e.resolve(r.realpath(e.resolve(t))),s=e.parse(o).root.length;for(;o.length>s&&/[\\/]$/.test(o);)o=o.slice(0,-1);return r.platform==="win32"?o.toLowerCase():o}function w(t,r=i()){let e=m(r.platform),o=l(t,r);if(r.tmpdir&&o===l(r.tmpdir,r))return!0;if(r.platform==="win32")return o===e.parse(o).root.toLowerCase();let s=e.resolve(t);return y.some(p=>p===s||l(p,r)===o)}function b(t,r=i()){if(r.platform==="win32")return!1;try{return(a.statSync(t).mode&514)===514}catch{return!1}}function k(t,r=i()){return w(t,r)||b(t,r)}function A(t=i()){let r=m(t.platform),e;if(t.platform==="win32")e=t.env.LOCALAPPDATA||r.join(t.homedir,"AppData","Local");else if(t.platform==="darwin")e=r.join(t.homedir,"Library","Caches");else{let o=t.env.XDG_CACHE_HOME;e=o&&r.isAbsolute(o)?o:r.join(t.homedir,".cache")}return r.join(e,"agentic-qe","scratch")}function E(t,r=i()){let e=C("sha256").update(l(t,r)).digest("hex").slice(0,16);return m(r.platform).join(A(r),e)}function u(t){a.mkdirSync(t,{recursive:!0,mode:448}),process.platform!=="win32"&&a.chmodSync(t,448)}function R(t,r=i()){let e=E(t,r);try{return u(e),d(e,t),e}catch(o){let s=typeof process.getuid=="function"?String(process.getuid()):"user",p=n.join(r.tmpdir||c.tmpdir(),`agentic-qe-scratch-${s}`),f=n.join(p,n.basename(e));try{return u(p),u(f),d(f,t),f}catch(v){let g=h=>h instanceof Error?h.message:String(h);throw new Error(`Cannot create a private AQE scratch root for "${t}". User cache "${e}" failed: ${g(o)}. Temporary fallback "${f}" failed: ${g(v)}. Set AQE_PROJECT_ROOT to a project directory or make the user cache writable.`)}}}function d(t,r){let e=n.join(t,"SCRATCH_ROOT_FOR");try{a.existsSync(e)||a.writeFileSync(e,`${n.resolve(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.15");process.exit(0)}
2
+ import{b as S}from"./chunk-XH4JMX5O.js";import{createHash as C}from"crypto";import*as a from"fs";import*as c from"os";import*as n from"path";function P(t){try{return a.realpathSync.native(t)}catch{return t}}function i(){let t="",r="";try{t=c.tmpdir()}catch{}try{r=c.homedir()}catch{}return{platform:process.platform,tmpdir:t,homedir:r,env:process.env,realpath:P}}function m(t){return t==="win32"?n.win32:n.posix}function l(t,r=i()){let e=m(r.platform),o=e.resolve(r.realpath(e.resolve(t))),s=e.parse(o).root.length;for(;o.length>s&&/[\\/]$/.test(o);)o=o.slice(0,-1);return r.platform==="win32"?o.toLowerCase():o}function w(t,r=i()){let e=m(r.platform),o=l(t,r);if(r.tmpdir&&o===l(r.tmpdir,r))return!0;if(r.platform==="win32")return o===e.parse(o).root.toLowerCase();let s=e.resolve(t);return y.some(p=>p===s||l(p,r)===o)}function b(t,r=i()){if(r.platform==="win32")return!1;try{return(a.statSync(t).mode&514)===514}catch{return!1}}function k(t,r=i()){return w(t,r)||b(t,r)}function A(t=i()){let r=m(t.platform),e;if(t.platform==="win32")e=t.env.LOCALAPPDATA||r.join(t.homedir,"AppData","Local");else if(t.platform==="darwin")e=r.join(t.homedir,"Library","Caches");else{let o=t.env.XDG_CACHE_HOME;e=o&&r.isAbsolute(o)?o:r.join(t.homedir,".cache")}return r.join(e,"agentic-qe","scratch")}function E(t,r=i()){let e=C("sha256").update(l(t,r)).digest("hex").slice(0,16);return m(r.platform).join(A(r),e)}function u(t){a.mkdirSync(t,{recursive:!0,mode:448}),process.platform!=="win32"&&a.chmodSync(t,448)}function R(t,r=i()){let e=E(t,r);try{return u(e),d(e,t),e}catch(o){let s=typeof process.getuid=="function"?String(process.getuid()):"user",p=n.join(r.tmpdir||c.tmpdir(),`agentic-qe-scratch-${s}`),f=n.join(p,n.basename(e));try{return u(p),u(f),d(f,t),f}catch(v){let g=h=>h instanceof Error?h.message:String(h);throw new Error(`Cannot create a private AQE scratch root for "${t}". User cache "${e}" failed: ${g(o)}. Temporary fallback "${f}" failed: ${g(v)}. Set AQE_PROJECT_ROOT to a project directory or make the user cache writable.`)}}}function d(t,r){let e=n.join(t,"SCRATCH_ROOT_FOR");try{a.existsSync(e)||a.writeFileSync(e,`${n.resolve(r)}
3
3
  `,{mode:384})}catch{}}var y,O=S(()=>{"use strict";y=["/","/tmp","/var/tmp","/usr/tmp","/dev/shm","/run/shm","/private","/private/tmp","/private/var","/private/var/tmp","/var","/usr","/etc","/opt","/srv","/mnt","/media","/run","/home","/Users","/Volumes"]});export{w as a,b,k as c,E as d,R as e,O as f};
@@ -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.13");process.exit(0)}
2
- import{b as c,d as f,e as g,f as X}from"./chunk-3Y7TJFHU.js";import{createHash as I}from"crypto";import{existsSync as O,readFileSync as b,writeFileSync as D,openSync as F,writeSync as y,closeSync as S}from"fs";X();var U=[`CREATE TABLE IF NOT EXISTS qe_patterns (
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.15");process.exit(0)}
2
+ import{b as c,d as f,e as g,f as X}from"./chunk-T66PPF4D.js";import{createHash as I}from"crypto";import{existsSync as O,readFileSync as b,writeFileSync as D,openSync as F,writeSync as y,closeSync as S}from"fs";X();var U=[`CREATE TABLE IF NOT EXISTS qe_patterns (
3
3
  id TEXT PRIMARY KEY, pattern_type TEXT NOT NULL, qe_domain TEXT NOT NULL,
4
4
  domain TEXT NOT NULL, name TEXT NOT NULL, description TEXT,
5
5
  confidence REAL DEFAULT 0.5, usage_count INTEGER DEFAULT 0,
@@ -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.13");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.15");process.exit(0)}
2
2
  var i=/[\s\x00-\x1f\x7f]/;function e(t,n="git ref"){if(typeof t!="string"||t.length===0)return`Invalid ${n}: must be a non-empty string`;if(t.length>256)return`Invalid ${n}: longer than 256 characters`;if(t.startsWith("-"))return`Invalid ${n} "${t}": must not start with "-"`;if(i.test(t))return`Invalid ${n}: must not contain whitespace or control characters`}function s(t,n="git ref"){let r=e(t,n);if(r)throw new Error(r)}export{e as a,s as b};
@@ -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.13");process.exit(0)}
2
- import{b as L,d as B}from"./chunk-J2ZIFFM6.js";import*as a from"fs";import*as v from"path";import{createRequire as K}from"node:module";var Z=K(import.meta.url),b=Z("semver"),F="3.15.13",y=t=>typeof t=="string"&&b.valid(t)===t.split("+")[0],E=t=>b.validRange(t)!==null,x=(t,e)=>b.satisfies(t,e),C=(t,e)=>b.compare(t,e),N=(t,e)=>C(e,t)||t.localeCompare(e);B();var R=class{cacheDir;keepVersions;constructor(e={}){this.cacheDir=e.cacheDir??L("plugins"),this.keepVersions=e.keepVersions??2}has(e,n){let s=this.versionDir(e,n);return a.existsSync(s)&&a.existsSync(v.join(s,"qe-plugin.json"))}get(e,n){if(!this.has(e,n))return;let s=this.versionDir(e,n),i=a.readFileSync(v.join(s,"qe-plugin.json"),"utf-8"),r=JSON.parse(i),l=a.statSync(s);return{manifest:r,path:s,cachedAt:l.birthtime.toISOString()}}store(e,n){let s=this.versionDir(e.name,e.version);if(a.existsSync(s))return s;a.mkdirSync(s,{recursive:!0});try{this.copyDir(n,s),a.writeFileSync(v.join(s,"qe-plugin.json"),JSON.stringify(e,null,2))}catch(i){throw a.rmSync(s,{recursive:!0,force:!0}),i}return this.pruneOldVersions(e.name),s}remove(e,n){let s=this.versionDir(e,n);return a.existsSync(s)?(a.rmSync(s,{recursive:!0,force:!0}),!0):!1}listVersions(e){let n=v.join(this.cacheDir,e);if(!a.existsSync(n))return[];let s=[],i=a.readdirSync(n);for(let r of i){let l=v.join(n,r),d=v.join(l,"qe-plugin.json");if(a.existsSync(d))try{let p=a.readFileSync(d,"utf-8"),m=JSON.parse(p);if(!y(m.version)){console.warn(`[PluginCache] Skipping cached plugin ${e}@${r}: invalid version ${JSON.stringify(m.version)}`);continue}let c=a.statSync(l);s.push({manifest:m,path:l,cachedAt:c.birthtime.toISOString()})}catch{}}return s}listAll(){if(!a.existsSync(this.cacheDir))return[];let e=[],n=a.readdirSync(this.cacheDir);for(let s of n){let i=this.listVersions(s);i.length>0&&(i.sort((r,l)=>N(r.manifest.version,l.manifest.version)),e.push(i[0]))}return e}listCandidates(){return a.existsSync(this.cacheDir)?a.readdirSync(this.cacheDir).flatMap(e=>this.listVersions(e)):[]}versionDir(e,n){return v.join(this.cacheDir,e,n)}pruneOldVersions(e){let n=this.listVersions(e);if(n.length<=this.keepVersions)return;n.sort((i,r)=>i.cachedAt.localeCompare(r.cachedAt));let s=n.slice(0,n.length-this.keepVersions);for(let i of s)a.rmSync(i.path,{recursive:!0,force:!0})}copyDir(e,n){if(!a.existsSync(e))return;let s=a.readdirSync(e,{withFileTypes:!0});for(let i of s){let r=v.join(e,i.name),l=v.join(n,i.name);if(i.isDirectory()){if(i.name===".git"||i.name==="node_modules")continue;a.mkdirSync(l,{recursive:!0}),this.copyDir(r,l)}else a.copyFileSync(r,l)}}};var ee=/^[a-z][a-z0-9-]*$/,se=["aqe-core-","agentic-qe-core-"],G=64,T=500;function k(t){let e=[],n=[];if(!t||typeof t!="object")return{valid:!1,errors:["Manifest must be a non-null object"],warnings:[]};let s=t;if(!s.name||typeof s.name!="string"?e.push("name is required and must be a string"):ne(s.name,e,n),!s.version||typeof s.version!="string"?e.push("version is required and must be a string"):y(s.version)||e.push(`version "${s.version}" is not valid semver (expected: major.minor.patch)`),!s.description||typeof s.description!="string"?e.push("description is required and must be a string"):s.description.length>T&&n.push(`description exceeds ${T} characters`),(!s.author||typeof s.author!="string")&&e.push("author is required and must be a string"),!Array.isArray(s.domains)||s.domains.length===0)e.push("domains is required and must be a non-empty array");else for(let i of s.domains)if(typeof i!="string"){e.push("Each domain must be a string");break}if(!s.entryPoint||typeof s.entryPoint!="string"?e.push("entryPoint is required and must be a string"):te(s.entryPoint,e),s.dependencies!==void 0)if(typeof s.dependencies!="object"||s.dependencies===null||Array.isArray(s.dependencies))e.push("dependencies must be an object mapping plugin names to semver ranges");else for(let[i,r]of Object.entries(s.dependencies))typeof r!="string"?e.push(`Dependency "${i}" must have a string version range`):E(r)||e.push(`Dependency "${i}" has an invalid semver range`);if(s.hooks!==void 0)if(typeof s.hooks!="object"||s.hooks===null||Array.isArray(s.hooks))e.push("hooks must be an object mapping event names to handler paths");else for(let[,i]of Object.entries(s.hooks)){if(typeof i!="string"){e.push("Hook handler paths must be strings");break}i.includes("..")&&e.push(`Hook handler path "${i}" must not contain ".." (path traversal)`)}if(s.minAqeVersion!==void 0&&(typeof s.minAqeVersion!="string"||!y(s.minAqeVersion))&&e.push("minAqeVersion must be valid semver"),s.permissions!==void 0){if(!Array.isArray(s.permissions))e.push("permissions must be an array of strings");else for(let i of s.permissions)if(typeof i!="string"){e.push("Each permission must be a string");break}}return{valid:e.length===0,errors:e,warnings:n}}function U(t){let e=typeof t=="string"?JSON.parse(t):t,n=k(e);if(!n.valid)throw new Error(`Invalid plugin manifest:
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.15");process.exit(0)}
2
+ import{b as L,d as B}from"./chunk-SZAZQZWI.js";import*as a from"fs";import*as v from"path";import{createRequire as K}from"node:module";var Z=K(import.meta.url),b=Z("semver"),F="3.15.15",y=t=>typeof t=="string"&&b.valid(t)===t.split("+")[0],E=t=>b.validRange(t)!==null,x=(t,e)=>b.satisfies(t,e),C=(t,e)=>b.compare(t,e),N=(t,e)=>C(e,t)||t.localeCompare(e);B();var R=class{cacheDir;keepVersions;constructor(e={}){this.cacheDir=e.cacheDir??L("plugins"),this.keepVersions=e.keepVersions??2}has(e,n){let s=this.versionDir(e,n);return a.existsSync(s)&&a.existsSync(v.join(s,"qe-plugin.json"))}get(e,n){if(!this.has(e,n))return;let s=this.versionDir(e,n),i=a.readFileSync(v.join(s,"qe-plugin.json"),"utf-8"),r=JSON.parse(i),l=a.statSync(s);return{manifest:r,path:s,cachedAt:l.birthtime.toISOString()}}store(e,n){let s=this.versionDir(e.name,e.version);if(a.existsSync(s))return s;a.mkdirSync(s,{recursive:!0});try{this.copyDir(n,s),a.writeFileSync(v.join(s,"qe-plugin.json"),JSON.stringify(e,null,2))}catch(i){throw a.rmSync(s,{recursive:!0,force:!0}),i}return this.pruneOldVersions(e.name),s}remove(e,n){let s=this.versionDir(e,n);return a.existsSync(s)?(a.rmSync(s,{recursive:!0,force:!0}),!0):!1}listVersions(e){let n=v.join(this.cacheDir,e);if(!a.existsSync(n))return[];let s=[],i=a.readdirSync(n);for(let r of i){let l=v.join(n,r),d=v.join(l,"qe-plugin.json");if(a.existsSync(d))try{let p=a.readFileSync(d,"utf-8"),m=JSON.parse(p);if(!y(m.version)){console.warn(`[PluginCache] Skipping cached plugin ${e}@${r}: invalid version ${JSON.stringify(m.version)}`);continue}let c=a.statSync(l);s.push({manifest:m,path:l,cachedAt:c.birthtime.toISOString()})}catch{}}return s}listAll(){if(!a.existsSync(this.cacheDir))return[];let e=[],n=a.readdirSync(this.cacheDir);for(let s of n){let i=this.listVersions(s);i.length>0&&(i.sort((r,l)=>N(r.manifest.version,l.manifest.version)),e.push(i[0]))}return e}listCandidates(){return a.existsSync(this.cacheDir)?a.readdirSync(this.cacheDir).flatMap(e=>this.listVersions(e)):[]}versionDir(e,n){return v.join(this.cacheDir,e,n)}pruneOldVersions(e){let n=this.listVersions(e);if(n.length<=this.keepVersions)return;n.sort((i,r)=>i.cachedAt.localeCompare(r.cachedAt));let s=n.slice(0,n.length-this.keepVersions);for(let i of s)a.rmSync(i.path,{recursive:!0,force:!0})}copyDir(e,n){if(!a.existsSync(e))return;let s=a.readdirSync(e,{withFileTypes:!0});for(let i of s){let r=v.join(e,i.name),l=v.join(n,i.name);if(i.isDirectory()){if(i.name===".git"||i.name==="node_modules")continue;a.mkdirSync(l,{recursive:!0}),this.copyDir(r,l)}else a.copyFileSync(r,l)}}};var ee=/^[a-z][a-z0-9-]*$/,se=["aqe-core-","agentic-qe-core-"],G=64,T=500;function k(t){let e=[],n=[];if(!t||typeof t!="object")return{valid:!1,errors:["Manifest must be a non-null object"],warnings:[]};let s=t;if(!s.name||typeof s.name!="string"?e.push("name is required and must be a string"):ne(s.name,e,n),!s.version||typeof s.version!="string"?e.push("version is required and must be a string"):y(s.version)||e.push(`version "${s.version}" is not valid semver (expected: major.minor.patch)`),!s.description||typeof s.description!="string"?e.push("description is required and must be a string"):s.description.length>T&&n.push(`description exceeds ${T} characters`),(!s.author||typeof s.author!="string")&&e.push("author is required and must be a string"),!Array.isArray(s.domains)||s.domains.length===0)e.push("domains is required and must be a non-empty array");else for(let i of s.domains)if(typeof i!="string"){e.push("Each domain must be a string");break}if(!s.entryPoint||typeof s.entryPoint!="string"?e.push("entryPoint is required and must be a string"):te(s.entryPoint,e),s.dependencies!==void 0)if(typeof s.dependencies!="object"||s.dependencies===null||Array.isArray(s.dependencies))e.push("dependencies must be an object mapping plugin names to semver ranges");else for(let[i,r]of Object.entries(s.dependencies))typeof r!="string"?e.push(`Dependency "${i}" must have a string version range`):E(r)||e.push(`Dependency "${i}" has an invalid semver range`);if(s.hooks!==void 0)if(typeof s.hooks!="object"||s.hooks===null||Array.isArray(s.hooks))e.push("hooks must be an object mapping event names to handler paths");else for(let[,i]of Object.entries(s.hooks)){if(typeof i!="string"){e.push("Hook handler paths must be strings");break}i.includes("..")&&e.push(`Hook handler path "${i}" must not contain ".." (path traversal)`)}if(s.minAqeVersion!==void 0&&(typeof s.minAqeVersion!="string"||!y(s.minAqeVersion))&&e.push("minAqeVersion must be valid semver"),s.permissions!==void 0){if(!Array.isArray(s.permissions))e.push("permissions must be an array of strings");else for(let i of s.permissions)if(typeof i!="string"){e.push("Each permission must be a string");break}}return{valid:e.length===0,errors:e,warnings:n}}function U(t){let e=typeof t=="string"?JSON.parse(t):t,n=k(e);if(!n.valid)throw new Error(`Invalid plugin manifest:
3
3
  - ${n.errors.join(`
4
4
  - `)}`);return e}function ne(t,e,n){t.length>G&&e.push(`name must be ${G} characters or fewer`),ee.test(t)||e.push("name must be lowercase alphanumeric with hyphens, starting with a letter"),/[^\x00-\x7F]/.test(t)&&e.push("name must contain only ASCII characters");for(let s of se)t.startsWith(s)&&e.push(`name cannot start with reserved prefix "${s}"`);["plugin","test","tool"].includes(t)&&n.push(`name "${t}" is very generic \u2014 consider a more descriptive name`)}function te(t,e){t.includes("..")&&e.push('entryPoint must not contain ".." (path traversal)'),(t.startsWith("/")||t.startsWith("\\"))&&e.push("entryPoint must be a relative path"),!t.endsWith(".js")&&!t.endsWith(".ts")&&!t.endsWith(".mjs")&&e.push("entryPoint must end in .js, .ts, or .mjs")}var I=class{constructor(e=F){this.aqeVersion=e}aqeVersion;resolve(e,n){let s=new Map,i=new Map;for(let o of e){let u=s.get(o.name)??[];s.set(o.name,u);let f=this.validateVersions(o);f?i.set(o.name,[...i.get(o.name)??[],f]):u.push(o)}for(let o of s.values())o.sort((u,f)=>N(u.version,f.version));let r=new Map,l=[],d=o=>({ordered:o.map((u,f)=>({manifest:u,order:f})),missing:r,errors:l,selectedVersions:Object.fromEntries(o.map(u=>[u.name,u.version])),aqeVersion:this.aqeVersion}),p=[...n??s.keys()].sort(),m=new Set(p),c=new Map,_=0,h=!1,X=()=>{for(let o of c.values())for(let[u,f]of Object.entries(o.dependencies??{})){let g=c.get(u);if(!(g?[g]:s.get(u)??[]).some(M=>x(M.version,f)))return!1}return!0},A,z=()=>{let o=new Set,u=new Set,f=(g,P)=>{if(u.has(g))return[...P.slice(P.indexOf(g)),g];if(!o.has(g)){u.add(g);for(let M of Object.keys(c.get(g)?.dependencies??{})){let Q=f(M,[...P,g]);if(Q)return Q}u.delete(g),o.add(g)}};for(let g of c.keys()){let P=f(g,[]);if(P)return P}},j=()=>{let o=new Set(p);for(let f of c.values())for(let g of Object.keys(f.dependencies??{}))o.add(g);let u=[...o].sort().find(f=>!c.has(f));if(!u){let f=z();return f?(A=f,!1):!0}m.add(u);for(let f of s.get(u)??[]){if(++_>1e4)return h=!0,!1;if(c.set(u,f),X()&&j())return!0;if(c.delete(u),h)return!1}return!1};if(!j()){if(A&&!h)throw new Error(`Dependency cycle detected: ${A.join(" -> ")}`);for(let o of m)s.get(o)?.length||l.push(...i.get(o)??[]);for(let[o,u]of s){let f=[...new Set(u.flatMap(g=>Object.keys(g.dependencies??{})))].filter(g=>!s.has(g));f.length&&r.set(o,f)}return l.push({code:h?"RESOLUTION_LIMIT":r.size?"MISSING_DEPENDENCY":"UNSATISFIED_DEPENDENCY_RANGE",plugin:p.join(", "),message:h?"Plugin dependency search exceeded 10000 candidates":"No cached plugin selection satisfies all dependency ranges"}),d([])}let O=[],q=new Set,w=new Set,$=(o,u)=>{if(q.has(o))return;if(w.has(o))throw new Error(`Dependency cycle detected: ${[...u.slice(u.indexOf(o)),o].join(" -> ")}`);w.add(o);let f=c.get(o);for(let g of Object.keys(f.dependencies??{}))$(g,[...u,o]);w.delete(o),q.add(o),O.push(f)};for(let o of[...c.keys()].sort())$(o,[]);return d(O)}resolveAvailable(e){let n=[],s=this.resolve(e,[]),i=[],r=new Map;for(let l of[...new Set(e.map(d=>d.name))].sort())try{let d=this.resolve(e,[...n,l]);if(d.errors.length){i.push(...d.errors.map(p=>({...p,plugin:l})));for(let[p,m]of d.missing)r.set(p,m);continue}n.push(l),s=d}catch(d){i.push({code:"DEPENDENCY_CYCLE",plugin:l,message:d instanceof Error?d.message:String(d)})}return{...s,errors:i,missing:r}}canLoad(e,n){let s=Object.entries(e.dependencies??{}).filter(([i,r])=>{let l=n instanceof Set?void 0:n.get(i);return!l||!E(r)||!x(l,r)}).map(([i])=>i);return{canLoad:!this.validateVersions(e)&&s.length===0,missingDeps:s}}validateVersions(e){if(!y(e.version))return{code:"INVALID_PLUGIN_VERSION",plugin:e.name,message:"Invalid plugin version"};for(let n of Object.values(e.dependencies??{}))if(!E(n))return{code:"INVALID_DEPENDENCY_RANGE",plugin:e.name,message:"Invalid dependency range"};if(e.minAqeVersion&&(!y(e.minAqeVersion)||!y(this.aqeVersion)||C(this.aqeVersion,e.minAqeVersion)<0))return{code:"AQE_VERSION_INCOMPATIBLE",plugin:e.name,message:`Requires AQE ${e.minAqeVersion}; running ${this.aqeVersion}`}}};var ie=["aqe-core-","agentic-qe-core-","agentic-qe-internal-"],Y=new Set(["aqe","agentic-qe","ruflo","claude-flow"]),re=["..","~","/etc/","/proc/","/dev/","node_modules/"];function W(t){let e=[];return oe(t.name,e),ae(t.entryPoint,e),ce(t.hooks,e),ue(t.permissions,e),{safe:e.length===0,violations:e}}function oe(t,e){/[^\x20-\x7E]/.test(t)&&e.push(`Plugin name "${t}" contains non-ASCII characters`),Y.has(t.toLowerCase())&&e.push(`Plugin name "${t}" is a reserved name`);for(let s of ie)t.toLowerCase().startsWith(s)&&e.push(`Plugin name "${t}" uses reserved prefix "${s}"`);let n=t.toLowerCase().replace(/[0o]/g,"o").replace(/[1il]/g,"l").replace(/[-_]/g,"");Y.has(n)&&e.push(`Plugin name "${t}" is visually similar to a reserved name`)}function ae(t,e){H(t,"entryPoint",e),(t.startsWith("/")||t.startsWith("\\"))&&e.push("entryPoint must be a relative path, not absolute")}function ce(t,e){if(t)for(let[n,s]of Object.entries(t))H(s,`hook[${n}]`,e)}function H(t,e,n){for(let s of re)t.includes(s)&&n.push(`${e} contains dangerous path pattern "${s}"`);t.includes("\0")&&n.push(`${e} contains null byte (path injection attempt)`)}function ue(t,e){if(!t)return;let n=["fs:write-root","net:arbitrary","exec:shell"];for(let s of t)n.includes(s)&&e.push(`Plugin requests dangerous permission: ${s}`)}import*as S from"fs";import*as V from"path";var D=class{type="local";async resolve(e){let n=V.resolve(e),s=V.join(n,"qe-plugin.json");if(!S.existsSync(s))throw new Error(`No qe-plugin.json found at ${s}`);let i=S.readFileSync(s,"utf-8");return U(i)}async getPluginPath(e){let n=V.resolve(e);if(!S.existsSync(n))throw new Error(`Plugin directory does not exist: ${n}`);return n}};var J=class{cache;resolver;sources=new Map;constructor(e={}){this.cache=e.cache??new R,this.resolver=new I;let n=new D;if(this.sources.set("local",n),e.sources)for(let s of e.sources)this.sources.set(s.type,s)}async install(e,n="local"){if(process.env.AQE_PLUGINS_DISABLED==="true")return{success:!1,errors:["Plugin loading is disabled (AQE_PLUGINS_DISABLED=true)"],securityViolations:[]};let s=[],i=this.sources.get(n);if(!i)return{success:!1,errors:[`Unknown source type: ${n}. Available: ${[...this.sources.keys()].join(", ")}`],securityViolations:[]};let r;try{r=await i.resolve(e)}catch(c){return{success:!1,errors:[`Failed to resolve plugin: ${c instanceof Error?c.message:String(c)}`],securityViolations:[]}}let l=k(r);if(!l.valid)return{success:!1,manifest:r,errors:l.errors,securityViolations:[]};let d=W(r);if(!d.safe)return{success:!1,manifest:r,errors:["Plugin failed security checks"],securityViolations:d.violations};try{let c=this.cache.listCandidates().map(h=>h.manifest).filter(h=>h.name!==r.name),_=this.resolver.resolve([...c,r],[r.name]);if(_.errors.length)return{success:!1,manifest:r,errors:_.errors.map(h=>`${h.code}: ${h.message}`),securityViolations:[]}}catch(c){return{success:!1,manifest:r,errors:[c instanceof Error?c.message:String(c)],securityViolations:[]}}if(this.cache.has(r.name,r.version)){let c=this.cache.get(r.name,r.version);return{success:!0,manifest:r,cachePath:c.path,errors:[],securityViolations:[]}}let p;try{p=await i.getPluginPath(e)}catch(c){return{success:!1,manifest:r,errors:[`Failed to get plugin path: ${c instanceof Error?c.message:String(c)}`],securityViolations:[]}}let m=this.cache.store(r,p);return{success:!0,manifest:r,cachePath:m,errors:s,securityViolations:[]}}remove(e,n){if(n)return this.cache.remove(e,n);let s=this.cache.listVersions(e),i=!1;for(let r of s)this.cache.remove(e,r.manifest.version)&&(i=!0);return i}list(){return this.cache.listAll().map(n=>({name:n.manifest.name,version:n.manifest.version,description:n.manifest.description,domains:n.manifest.domains,source:"cached",cachePath:n.path}))}resolveLoadOrder(){let e=this.cache.listCandidates();return this.resolver.resolveAvailable(e.map(n=>n.manifest))}registerSource(e){this.sources.set(e.type,e)}};export{U as a,R as b,J as c};
@@ -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.13");process.exit(0)}
2
- import{i as b,l as D,n as Q}from"./chunk-P7A4NKTZ.js";import{v as X}from"./chunk-3Y7TJFHU.js";import{d as _,e as Y}from"./chunk-GB6HBNH2.js";import{c as w}from"./chunk-J2ZIFFM6.js";var W=["claude","claude-code","codex","openai","ollama","openrouter","bedrock","azure-openai","gemini","cognitum"];function x(r){return W.includes(r)}function p(r,o,e){let t=new Error(r);return t.name="LLMError",t.code=o,t.provider=e?.provider,t.model=e?.model,t.retryable=e?.retryable??!1,t.retryAfterMs=e?.retryAfterMs,t.cause=e?.cause,t}function Te(r){return r instanceof Error&&"code"in r&&typeof r.code=="string"}var y=new Map,Z=new Set(["anthropic"]),N=/^[a-z0-9][a-z0-9-]{0,62}$/;function M(r){if(typeof r!="string"||r.trim().length===0)return"provider type must be a non-empty string";if(r!==r.toLowerCase())return`provider type "${r}" must be lowercase (AQE_LLM_PROVIDER is matched case-insensitively)`;if(!N.test(r))return`provider type "${r}" must match ${N.source} (lowercase alphanumeric and dashes)`;if(x(r))return`provider type "${r}" is built in and cannot be overridden`;if(Z.has(r))return`provider type "${r}" is reserved`}function ee(r,o,e={}){let t=M(r);if(t)throw p(t,"INVALID_REGISTRATION",{retryable:!1});if(typeof o!="function")throw p(`provider "${r}" must be registered with a factory function`,"INVALID_REGISTRATION",{retryable:!1});y.set(r,{...e,type:r,factory:o,source:e.source??"api"})}function F(r,o,e={}){try{ee(r,o,e);return}catch(t){return t instanceof Error?t.message:String(t)}}function B(r){return y.delete(r)}function $(r){return y.has(r)}function ke(r){return y.get(r)}function h(){return[...y.keys()]}var re=["isAvailable","healthCheck","generate","complete","getConfig","getSupportedModels","getCostPerToken","dispose"];function te(r,o){if(!o||typeof o!="object")return`provider "${r}" factory returned ${o===null?"null":typeof o}, expected an LLMProvider`;let e=o,t=re.filter(i=>typeof e[i]!="function");if(t.length>0)return`provider "${r}" is missing required LLMProvider method(s): ${t.join(", ")}`;if(typeof e.type!="string"||e.type.length===0)return`provider "${r}" must expose a non-empty \`type\``;if(e.type!==r)return`provider "${r}" reports type "${e.type}" \u2014 a provider must not claim an identity other than the one it was registered under`}function Le(r){let o=y.get(r);if(!o)throw p(`Unknown provider type: ${r}`,"PROVIDER_UNAVAILABLE",{retryable:!1});let e=o.factory(o.config),t=te(r,e);if(t)throw p(t,"INVALID_REGISTRATION",{retryable:!1});return e}function Ae(r){let o=y.get(r);if(o)return{mode:o.billingMode??"metered-api",source:o.source,detail:o.sourceDetail}}Q();function q(r){return r==="onnx"||x(r)}var T=["claude","claude-code","codex","openai","ollama","openrouter","gemini","azure-openai","bedrock","cognitum","onnx"];var oe={maxAttempts:3,delayMs:100,trySameProviderAlternateModel:!0,skipOpenCircuits:!0,retryableErrors:["RATE_LIMITED","TIMEOUT","NETWORK_ERROR","PROVIDER_UNAVAILABLE"]},ne=[{provider:"claude",models:[b,D[1]],enabled:!0,priority:100,maxAttempts:2,timeoutMs:3e4},{provider:"openai",models:["gpt-6-sol","gpt-6-luna"],enabled:!0,priority:90,maxAttempts:2,timeoutMs:3e4},{provider:"openrouter",models:["anthropic/claude-sonnet-5","openai/gpt-6-sol"],enabled:!0,priority:85,maxAttempts:2,timeoutMs:3e4},{provider:"ollama",models:["qwen3-coder:30b","qwen3:30b-a3b"],enabled:!0,priority:80,maxAttempts:2,timeoutMs:6e4},{provider:"onnx",models:["phi-4","all-MiniLM-L6-v2"],enabled:!0,priority:70,maxAttempts:1,timeoutMs:12e4}],ie={id:"default-fallback-chain",entries:ne,maxRetries:3,retryDelayMs:100,backoffMultiplier:2,maxDelayMs:5e3},U={mode:"rule-based",rules:[],defaultProvider:"claude",defaultModel:b,fallbackChain:ie,fallbackBehavior:oe,providers:{claude:{enabled:!0,defaultModel:b},"claude-code":{enabled:!1,defaultModel:b},openai:{enabled:!0,defaultModel:"gpt-6-sol"},ollama:{enabled:!0,defaultModel:"qwen3-coder:30b"},openrouter:{enabled:!0,defaultModel:"anthropic/claude-sonnet-5"},gemini:{enabled:!1,defaultModel:"gemini-2.5-flash"},"azure-openai":{enabled:!1},bedrock:{enabled:!1},cognitum:{enabled:!1,defaultModel:"cognitum-auto"},onnx:{enabled:!0,defaultModel:"phi-4"}},enableMetrics:!0,metricsConfig:{enabled:!0,collectionIntervalMs:6e4,retentionMs:864e5,trackPerRequest:!0},maxDecisionTimeMs:10,cacheDecisions:!0,decisionCacheTtlMs:6e4,cacheConfig:{enabled:!0,ttlMs:6e4,maxEntries:1e3,keyStrategy:"agent-domain"},auditConfig:{enabled:!0,maxEntries:1e4,logContent:!1,logResponse:!1}},Ue=[{canonicalId:"claude-opus-5",canonicalName:"Claude Opus 5",providerIds:{claude:"claude-opus-5",openrouter:"anthropic/claude-opus-5"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:5,outputCostPer1M:25},{canonicalId:"claude-sonnet-5",canonicalName:"Claude Sonnet 5",providerIds:{claude:"claude-sonnet-5",openrouter:"anthropic/claude-sonnet-5"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"advanced",family:"claude",inputCostPer1M:2,outputCostPer1M:10},{canonicalId:"claude-opus-5-5",canonicalName:"Claude Opus 5.5",providerIds:{claude:"claude-opus-5-5",openrouter:"anthropic/claude-opus-5.5"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:4,outputCostPer1M:20},{canonicalId:"claude-opus-4-7",canonicalName:"Claude Opus 4.7",providerIds:{claude:"claude-opus-4-7",openrouter:"anthropic/claude-opus-4.7",bedrock:"anthropic.claude-opus-4-7-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:5,outputCostPer1M:25},{canonicalId:"claude-sonnet-4-6",canonicalName:"Claude Sonnet 4.6",providerIds:{claude:"claude-sonnet-4-6",openrouter:"anthropic/claude-sonnet-4.6",bedrock:"anthropic.claude-sonnet-4-6-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"advanced",family:"claude",inputCostPer1M:3,outputCostPer1M:15},{canonicalId:"claude-haiku-4-5",canonicalName:"Claude Haiku 4.5",providerIds:{claude:"claude-haiku-4-5-20251001",openrouter:"anthropic/claude-haiku-4.5",bedrock:"anthropic.claude-haiku-4-5-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:2e5,maxOutputTokens:16384},tier:"standard",family:"claude",inputCostPer1M:1,outputCostPer1M:5},{canonicalId:"gpt-4o",canonicalName:"GPT-4o",providerIds:{openai:"gpt-4o","azure-openai":"gpt-4o",openrouter:"openai/gpt-4o"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:16384},tier:"advanced",family:"gpt",inputCostPer1M:2.5,outputCostPer1M:10},{canonicalId:"gpt-4o-mini",canonicalName:"GPT-4o Mini",providerIds:{openai:"gpt-4o-mini","azure-openai":"gpt-4o-mini",openrouter:"openai/gpt-4o-mini"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:16384},tier:"standard",family:"gpt",inputCostPer1M:.15,outputCostPer1M:.6},{canonicalId:"gemini-pro",canonicalName:"Gemini 2.0 Pro",providerIds:{gemini:"gemini-2.0-pro",openrouter:"google/gemini-2.0-pro"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:2e6,maxOutputTokens:8192},tier:"advanced",family:"gemini",inputCostPer1M:1.25,outputCostPer1M:5},{canonicalId:"llama-3.1-70b",canonicalName:"LLaMA 3.1 70B",providerIds:{ollama:"llama3.1:70b",openrouter:"meta-llama/llama-3.1-70b",bedrock:"meta.llama3-1-70b-instruct-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!1,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:4096},tier:"advanced",family:"llama",inputCostPer1M:.9,outputCostPer1M:.9},{canonicalId:"phi-4",canonicalName:"Microsoft Phi-4",providerIds:{ollama:"phi4",onnx:"phi-4",openrouter:"microsoft/phi-4"},capabilities:{supportsStreaming:!0,supportsTools:!1,supportsMCP:!1,supportsVision:!1,supportsExtendedThinking:!1,supportsJsonMode:!1,maxContextTokens:16e3,maxOutputTokens:4096,requiresNetwork:!1},tier:"efficient",family:"phi",inputCostPer1M:0,outputCostPer1M:0}];import{spawn as se}from"node:child_process";import{accessSync as ae,constants as de,statSync as le}from"node:fs";import{delimiter as ue,join as pe}from"node:path";var ce=18e4,me=2,E="default";function R(r,o){if(!o||typeof o!="object")return`externalProviders["${r}"] must be an object`;let e=o;if(e.kind!=="cli")return`externalProviders["${r}"].kind must be "cli" (got ${JSON.stringify(e.kind)})`;if(!Array.isArray(e.command)||e.command.length===0)return`externalProviders["${r}"].command must be a non-empty string array`;if(!e.command.every(t=>typeof t=="string"&&t.length>0))return`externalProviders["${r}"].command must contain only non-empty strings`;if(e.billingMode!==void 0&&!["subscription","metered-api","metered-capped","local"].includes(e.billingMode))return`externalProviders["${r}"].billingMode "${String(e.billingMode)}" is not a valid billing mode`;if(e.models!==void 0&&(!Array.isArray(e.models)||e.models.some(t=>typeof t!="string")))return`externalProviders["${r}"].models must be a string array`;if(e.timeoutMs!==void 0&&(typeof e.timeoutMs!="number"||e.timeoutMs<=0))return`externalProviders["${r}"].timeoutMs must be a positive number`;if(e.maxConcurrency!==void 0&&(typeof e.maxConcurrency!="number"||e.maxConcurrency<1))return`externalProviders["${r}"].maxConcurrency must be >= 1`;if(e.stripEnv!==void 0&&(!Array.isArray(e.stripEnv)||e.stripEnv.some(t=>typeof t!="string")))return`externalProviders["${r}"].stripEnv must be a string array`;if("apiKey"in e)return`externalProviders["${r}"] must not contain an apiKey \u2014 keys belong in the environment, not in llm-config.json`}var P=class r{type;name;billingMode;config;requestCounter=0;availabilityCache;active=0;queue=[];constructor(o,e){let t=R(o,e);if(t)throw p(t,"INVALID_REGISTRATION",{retryable:!1});this.type=o,this.config=e,this.name=e.displayName??o,this.billingMode=e.billingMode??"metered-api"}async isAvailable(){let o=Date.now();if(this.availabilityCache&&o-this.availabilityCache.at<6e4)return this.availabilityCache.available;let e=ge(this.config.command[0]);return this.availabilityCache={at:o,available:e},e}async healthCheck(){let o=Date.now(),e=await this.isAvailable(),t=Date.now()-o;return e?{healthy:!0,latencyMs:t,models:this.getSupportedModels(),details:{command:this.config.command[0],billing:this.billingMode,external:!0}}:{healthy:!1,latencyMs:t,error:`External provider "${this.type}" could not run "${this.config.command[0]}". Check that the host is installed and on PATH.`}}async generate(o,e){let t=e?.model??this.defaultModel(),i=`${this.type}-${++this.requestCounter}-${Date.now()}`,n=ye(o,e?.systemPrompt),s=e?.timeoutMs??this.config.timeoutMs??ce,l=[];this.config.modelFlag&&t&&t!==E&&l.push(this.config.modelFlag,t);let a=Date.now(),{code:d,stdout:u,stderr:f}=await this.withConcurrency(()=>this.spawnHost(l,n,s)),g=Date.now()-a,v=u.trim();if(d!==0&&!v)throw this.classifyError(f||`${this.type} exited with code ${d}`,t);let c=Math.ceil(n.length/4),S=Math.ceil(v.length/4),J={promptTokens:c,completionTokens:S,totalTokens:c+S};return{content:v,model:t,provider:this.type,usage:J,cost:{inputCost:0,outputCost:0,totalCost:0,currency:"USD",source:"local-estimate"},latencyMs:g,finishReason:"stop",cached:!1,requestId:i}}async embed(o,e){throw p(`External provider "${this.type}" does not support embeddings. Use a provider with an embeddings endpoint (openai, ollama, cognitum).`,"EMBEDDING_UNSUPPORTED",{provider:this.type,retryable:!1})}async complete(o,e){let t=await this.generate(o,{model:e?.model,temperature:e?.temperature,maxTokens:e?.maxTokens});return{completion:t.content,model:t.model,provider:this.type,usage:t.usage,latencyMs:t.latencyMs,cached:t.cached}}getConfig(){return{...this.config}}getSupportedModels(){return[...this.config.models??[E]]}getCostPerToken(){return{input:0,output:0}}async dispose(){}defaultModel(){return this.config.defaultModel??this.config.models?.[0]??E}static childEnv(o=[],e=process.env){let t={...e};for(let i of o)delete t[i];return t}classifyError(o,e){let t=o.toLowerCase();return t.includes("rate limit")||t.includes("usage limit")||t.includes("429")||t.includes("quota")?p(o,"RATE_LIMITED",{provider:this.type,model:e,retryable:!0,retryAfterMs:6e4}):p(o,"PROVIDER_UNAVAILABLE",{provider:this.type,model:e,retryable:!0})}spawnHost(o,e,t){let[i,...n]=this.config.command,s=[...n,...o];return new Promise((l,a)=>{let d=se(i,s,{env:r.childEnv(this.config.stripEnv),stdio:["pipe","pipe","pipe"]}),u="",f="",g=!1,v=setTimeout(()=>{g||(g=!0,d.kill("SIGKILL"),a(p(`${this.type} timed out after ${t}ms`,"TIMEOUT",{provider:this.type,retryable:!0})))},t);d.stdout.on("data",c=>u+=c.toString()),d.stderr.on("data",c=>f+=c.toString()),d.on("error",c=>{g||(g=!0,clearTimeout(v),a(p(`Failed to spawn "${i}" for provider "${this.type}": ${c.message}`,"PROVIDER_UNAVAILABLE",{provider:this.type,retryable:!1,cause:c})))}),d.on("close",c=>{g||(g=!0,clearTimeout(v),l({code:c??0,stdout:u,stderr:f}))}),d.stdin.on("error",()=>{});try{d.stdin.write(e),d.stdin.end()}catch{}})}async withConcurrency(o){let e=this.config.maxConcurrency??me;this.active>=e&&await new Promise(t=>this.queue.push(t)),this.active++;try{return await o()}finally{this.active--;let t=this.queue.shift();t&&t()}}};function ge(r,o=process.env){let e=n=>{try{return ae(n,de.X_OK),le(n).isFile()}catch{return!1}};if(r.includes("/")||r.includes("\\"))return e(r);let t=(o.PATH??"").split(ue).filter(Boolean),i=process.platform==="win32"?["",...(o.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)]:[""];return t.some(n=>i.some(s=>e(pe(n,r+s))))}function ye(r,o){if(typeof r=="string")return o?`${o}
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.15");process.exit(0)}
2
+ import{i as b,l as D,n as Q}from"./chunk-LTQVUAPH.js";import{v as X}from"./chunk-T66PPF4D.js";import{d as _,e as Y}from"./chunk-BQ47GQPK.js";import{c as w}from"./chunk-SZAZQZWI.js";var W=["claude","claude-code","codex","openai","ollama","openrouter","bedrock","azure-openai","gemini","cognitum"];function x(r){return W.includes(r)}function p(r,o,e){let t=new Error(r);return t.name="LLMError",t.code=o,t.provider=e?.provider,t.model=e?.model,t.retryable=e?.retryable??!1,t.retryAfterMs=e?.retryAfterMs,t.cause=e?.cause,t}function Te(r){return r instanceof Error&&"code"in r&&typeof r.code=="string"}var y=new Map,Z=new Set(["anthropic"]),N=/^[a-z0-9][a-z0-9-]{0,62}$/;function M(r){if(typeof r!="string"||r.trim().length===0)return"provider type must be a non-empty string";if(r!==r.toLowerCase())return`provider type "${r}" must be lowercase (AQE_LLM_PROVIDER is matched case-insensitively)`;if(!N.test(r))return`provider type "${r}" must match ${N.source} (lowercase alphanumeric and dashes)`;if(x(r))return`provider type "${r}" is built in and cannot be overridden`;if(Z.has(r))return`provider type "${r}" is reserved`}function ee(r,o,e={}){let t=M(r);if(t)throw p(t,"INVALID_REGISTRATION",{retryable:!1});if(typeof o!="function")throw p(`provider "${r}" must be registered with a factory function`,"INVALID_REGISTRATION",{retryable:!1});y.set(r,{...e,type:r,factory:o,source:e.source??"api"})}function F(r,o,e={}){try{ee(r,o,e);return}catch(t){return t instanceof Error?t.message:String(t)}}function B(r){return y.delete(r)}function $(r){return y.has(r)}function ke(r){return y.get(r)}function h(){return[...y.keys()]}var re=["isAvailable","healthCheck","generate","complete","getConfig","getSupportedModels","getCostPerToken","dispose"];function te(r,o){if(!o||typeof o!="object")return`provider "${r}" factory returned ${o===null?"null":typeof o}, expected an LLMProvider`;let e=o,t=re.filter(i=>typeof e[i]!="function");if(t.length>0)return`provider "${r}" is missing required LLMProvider method(s): ${t.join(", ")}`;if(typeof e.type!="string"||e.type.length===0)return`provider "${r}" must expose a non-empty \`type\``;if(e.type!==r)return`provider "${r}" reports type "${e.type}" \u2014 a provider must not claim an identity other than the one it was registered under`}function Le(r){let o=y.get(r);if(!o)throw p(`Unknown provider type: ${r}`,"PROVIDER_UNAVAILABLE",{retryable:!1});let e=o.factory(o.config),t=te(r,e);if(t)throw p(t,"INVALID_REGISTRATION",{retryable:!1});return e}function Ae(r){let o=y.get(r);if(o)return{mode:o.billingMode??"metered-api",source:o.source,detail:o.sourceDetail}}Q();function q(r){return r==="onnx"||x(r)}var T=["claude","claude-code","codex","openai","ollama","openrouter","gemini","azure-openai","bedrock","cognitum","onnx"];var oe={maxAttempts:3,delayMs:100,trySameProviderAlternateModel:!0,skipOpenCircuits:!0,retryableErrors:["RATE_LIMITED","TIMEOUT","NETWORK_ERROR","PROVIDER_UNAVAILABLE"]},ne=[{provider:"claude",models:[b,D[1]],enabled:!0,priority:100,maxAttempts:2,timeoutMs:3e4},{provider:"openai",models:["gpt-6-sol","gpt-6-luna"],enabled:!0,priority:90,maxAttempts:2,timeoutMs:3e4},{provider:"openrouter",models:["anthropic/claude-sonnet-5","openai/gpt-6-sol"],enabled:!0,priority:85,maxAttempts:2,timeoutMs:3e4},{provider:"ollama",models:["qwen3-coder:30b","qwen3:30b-a3b"],enabled:!0,priority:80,maxAttempts:2,timeoutMs:6e4},{provider:"onnx",models:["phi-4","all-MiniLM-L6-v2"],enabled:!0,priority:70,maxAttempts:1,timeoutMs:12e4}],ie={id:"default-fallback-chain",entries:ne,maxRetries:3,retryDelayMs:100,backoffMultiplier:2,maxDelayMs:5e3},U={mode:"rule-based",rules:[],defaultProvider:"claude",defaultModel:b,fallbackChain:ie,fallbackBehavior:oe,providers:{claude:{enabled:!0,defaultModel:b},"claude-code":{enabled:!1,defaultModel:b},openai:{enabled:!0,defaultModel:"gpt-6-sol"},ollama:{enabled:!0,defaultModel:"qwen3-coder:30b"},openrouter:{enabled:!0,defaultModel:"anthropic/claude-sonnet-5"},gemini:{enabled:!1,defaultModel:"gemini-2.5-flash"},"azure-openai":{enabled:!1},bedrock:{enabled:!1},cognitum:{enabled:!1,defaultModel:"cognitum-auto"},onnx:{enabled:!0,defaultModel:"phi-4"}},enableMetrics:!0,metricsConfig:{enabled:!0,collectionIntervalMs:6e4,retentionMs:864e5,trackPerRequest:!0},maxDecisionTimeMs:10,cacheDecisions:!0,decisionCacheTtlMs:6e4,cacheConfig:{enabled:!0,ttlMs:6e4,maxEntries:1e3,keyStrategy:"agent-domain"},auditConfig:{enabled:!0,maxEntries:1e4,logContent:!1,logResponse:!1}},Ue=[{canonicalId:"claude-opus-5",canonicalName:"Claude Opus 5",providerIds:{claude:"claude-opus-5",openrouter:"anthropic/claude-opus-5"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:5,outputCostPer1M:25},{canonicalId:"claude-sonnet-5",canonicalName:"Claude Sonnet 5",providerIds:{claude:"claude-sonnet-5",openrouter:"anthropic/claude-sonnet-5"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"advanced",family:"claude",inputCostPer1M:2,outputCostPer1M:10},{canonicalId:"claude-opus-5-5",canonicalName:"Claude Opus 5.5",providerIds:{claude:"claude-opus-5-5",openrouter:"anthropic/claude-opus-5.5"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:4,outputCostPer1M:20},{canonicalId:"claude-opus-4-7",canonicalName:"Claude Opus 4.7",providerIds:{claude:"claude-opus-4-7",openrouter:"anthropic/claude-opus-4.7",bedrock:"anthropic.claude-opus-4-7-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:5,outputCostPer1M:25},{canonicalId:"claude-sonnet-4-6",canonicalName:"Claude Sonnet 4.6",providerIds:{claude:"claude-sonnet-4-6",openrouter:"anthropic/claude-sonnet-4.6",bedrock:"anthropic.claude-sonnet-4-6-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"advanced",family:"claude",inputCostPer1M:3,outputCostPer1M:15},{canonicalId:"claude-haiku-4-5",canonicalName:"Claude Haiku 4.5",providerIds:{claude:"claude-haiku-4-5-20251001",openrouter:"anthropic/claude-haiku-4.5",bedrock:"anthropic.claude-haiku-4-5-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:2e5,maxOutputTokens:16384},tier:"standard",family:"claude",inputCostPer1M:1,outputCostPer1M:5},{canonicalId:"gpt-4o",canonicalName:"GPT-4o",providerIds:{openai:"gpt-4o","azure-openai":"gpt-4o",openrouter:"openai/gpt-4o"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:16384},tier:"advanced",family:"gpt",inputCostPer1M:2.5,outputCostPer1M:10},{canonicalId:"gpt-4o-mini",canonicalName:"GPT-4o Mini",providerIds:{openai:"gpt-4o-mini","azure-openai":"gpt-4o-mini",openrouter:"openai/gpt-4o-mini"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:16384},tier:"standard",family:"gpt",inputCostPer1M:.15,outputCostPer1M:.6},{canonicalId:"gemini-pro",canonicalName:"Gemini 2.0 Pro",providerIds:{gemini:"gemini-2.0-pro",openrouter:"google/gemini-2.0-pro"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:2e6,maxOutputTokens:8192},tier:"advanced",family:"gemini",inputCostPer1M:1.25,outputCostPer1M:5},{canonicalId:"llama-3.1-70b",canonicalName:"LLaMA 3.1 70B",providerIds:{ollama:"llama3.1:70b",openrouter:"meta-llama/llama-3.1-70b",bedrock:"meta.llama3-1-70b-instruct-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!1,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:4096},tier:"advanced",family:"llama",inputCostPer1M:.9,outputCostPer1M:.9},{canonicalId:"phi-4",canonicalName:"Microsoft Phi-4",providerIds:{ollama:"phi4",onnx:"phi-4",openrouter:"microsoft/phi-4"},capabilities:{supportsStreaming:!0,supportsTools:!1,supportsMCP:!1,supportsVision:!1,supportsExtendedThinking:!1,supportsJsonMode:!1,maxContextTokens:16e3,maxOutputTokens:4096,requiresNetwork:!1},tier:"efficient",family:"phi",inputCostPer1M:0,outputCostPer1M:0}];import{spawn as se}from"node:child_process";import{accessSync as ae,constants as de,statSync as le}from"node:fs";import{delimiter as ue,join as pe}from"node:path";var ce=18e4,me=2,E="default";function R(r,o){if(!o||typeof o!="object")return`externalProviders["${r}"] must be an object`;let e=o;if(e.kind!=="cli")return`externalProviders["${r}"].kind must be "cli" (got ${JSON.stringify(e.kind)})`;if(!Array.isArray(e.command)||e.command.length===0)return`externalProviders["${r}"].command must be a non-empty string array`;if(!e.command.every(t=>typeof t=="string"&&t.length>0))return`externalProviders["${r}"].command must contain only non-empty strings`;if(e.billingMode!==void 0&&!["subscription","metered-api","metered-capped","local"].includes(e.billingMode))return`externalProviders["${r}"].billingMode "${String(e.billingMode)}" is not a valid billing mode`;if(e.models!==void 0&&(!Array.isArray(e.models)||e.models.some(t=>typeof t!="string")))return`externalProviders["${r}"].models must be a string array`;if(e.timeoutMs!==void 0&&(typeof e.timeoutMs!="number"||e.timeoutMs<=0))return`externalProviders["${r}"].timeoutMs must be a positive number`;if(e.maxConcurrency!==void 0&&(typeof e.maxConcurrency!="number"||e.maxConcurrency<1))return`externalProviders["${r}"].maxConcurrency must be >= 1`;if(e.stripEnv!==void 0&&(!Array.isArray(e.stripEnv)||e.stripEnv.some(t=>typeof t!="string")))return`externalProviders["${r}"].stripEnv must be a string array`;if("apiKey"in e)return`externalProviders["${r}"] must not contain an apiKey \u2014 keys belong in the environment, not in llm-config.json`}var P=class r{type;name;billingMode;config;requestCounter=0;availabilityCache;active=0;queue=[];constructor(o,e){let t=R(o,e);if(t)throw p(t,"INVALID_REGISTRATION",{retryable:!1});this.type=o,this.config=e,this.name=e.displayName??o,this.billingMode=e.billingMode??"metered-api"}async isAvailable(){let o=Date.now();if(this.availabilityCache&&o-this.availabilityCache.at<6e4)return this.availabilityCache.available;let e=ge(this.config.command[0]);return this.availabilityCache={at:o,available:e},e}async healthCheck(){let o=Date.now(),e=await this.isAvailable(),t=Date.now()-o;return e?{healthy:!0,latencyMs:t,models:this.getSupportedModels(),details:{command:this.config.command[0],billing:this.billingMode,external:!0}}:{healthy:!1,latencyMs:t,error:`External provider "${this.type}" could not run "${this.config.command[0]}". Check that the host is installed and on PATH.`}}async generate(o,e){let t=e?.model??this.defaultModel(),i=`${this.type}-${++this.requestCounter}-${Date.now()}`,n=ye(o,e?.systemPrompt),s=e?.timeoutMs??this.config.timeoutMs??ce,l=[];this.config.modelFlag&&t&&t!==E&&l.push(this.config.modelFlag,t);let a=Date.now(),{code:d,stdout:u,stderr:f}=await this.withConcurrency(()=>this.spawnHost(l,n,s)),g=Date.now()-a,v=u.trim();if(d!==0&&!v)throw this.classifyError(f||`${this.type} exited with code ${d}`,t);let c=Math.ceil(n.length/4),S=Math.ceil(v.length/4),J={promptTokens:c,completionTokens:S,totalTokens:c+S};return{content:v,model:t,provider:this.type,usage:J,cost:{inputCost:0,outputCost:0,totalCost:0,currency:"USD",source:"local-estimate"},latencyMs:g,finishReason:"stop",cached:!1,requestId:i}}async embed(o,e){throw p(`External provider "${this.type}" does not support embeddings. Use a provider with an embeddings endpoint (openai, ollama, cognitum).`,"EMBEDDING_UNSUPPORTED",{provider:this.type,retryable:!1})}async complete(o,e){let t=await this.generate(o,{model:e?.model,temperature:e?.temperature,maxTokens:e?.maxTokens});return{completion:t.content,model:t.model,provider:this.type,usage:t.usage,latencyMs:t.latencyMs,cached:t.cached}}getConfig(){return{...this.config}}getSupportedModels(){return[...this.config.models??[E]]}getCostPerToken(){return{input:0,output:0}}async dispose(){}defaultModel(){return this.config.defaultModel??this.config.models?.[0]??E}static childEnv(o=[],e=process.env){let t={...e};for(let i of o)delete t[i];return t}classifyError(o,e){let t=o.toLowerCase();return t.includes("rate limit")||t.includes("usage limit")||t.includes("429")||t.includes("quota")?p(o,"RATE_LIMITED",{provider:this.type,model:e,retryable:!0,retryAfterMs:6e4}):p(o,"PROVIDER_UNAVAILABLE",{provider:this.type,model:e,retryable:!0})}spawnHost(o,e,t){let[i,...n]=this.config.command,s=[...n,...o];return new Promise((l,a)=>{let d=se(i,s,{env:r.childEnv(this.config.stripEnv),stdio:["pipe","pipe","pipe"]}),u="",f="",g=!1,v=setTimeout(()=>{g||(g=!0,d.kill("SIGKILL"),a(p(`${this.type} timed out after ${t}ms`,"TIMEOUT",{provider:this.type,retryable:!0})))},t);d.stdout.on("data",c=>u+=c.toString()),d.stderr.on("data",c=>f+=c.toString()),d.on("error",c=>{g||(g=!0,clearTimeout(v),a(p(`Failed to spawn "${i}" for provider "${this.type}": ${c.message}`,"PROVIDER_UNAVAILABLE",{provider:this.type,retryable:!1,cause:c})))}),d.on("close",c=>{g||(g=!0,clearTimeout(v),l({code:c??0,stdout:u,stderr:f}))}),d.stdin.on("error",()=>{});try{d.stdin.write(e),d.stdin.end()}catch{}})}async withConcurrency(o){let e=this.config.maxConcurrency??me;this.active>=e&&await new Promise(t=>this.queue.push(t)),this.active++;try{return await o()}finally{this.active--;let t=this.queue.shift();t&&t()}}};function ge(r,o=process.env){let e=n=>{try{return ae(n,de.X_OK),le(n).isFile()}catch{return!1}};if(r.includes("/")||r.includes("\\"))return e(r);let t=(o.PATH??"").split(ue).filter(Boolean),i=process.platform==="win32"?["",...(o.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)]:[""];return t.some(n=>i.some(s=>e(pe(n,r+s))))}function ye(r,o){if(typeof r=="string")return o?`${o}
3
3
 
4
4
  ${r}`:r;let e=r.filter(n=>n.role==="system").map(n=>n.content);o&&e.unshift(o);let t=r.filter(n=>n.role!=="system").map(n=>`${n.role==="assistant"?"Assistant":"User"}: ${n.content}`).join(`
5
5
 
@@ -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.15");process.exit(0)}
2
+ import{d as a,e as m}from"./chunk-JUDUBQHA.js";var o=n=>typeof n=="number"&&Number.isFinite(n)&&n>=0&&n<=100,l=n=>n===null||o(n);function f(n){if(!n||typeof n!="object")return null;let e=n;if(e.measured!==!0||!o(e.line)||!l(e.statement)||!l(e.branch)||!l(e.function))return null;let r=typeof e.files=="number"&&Number.isInteger(e.files)&&e.files>=0?e.files:null;return r===null?null:{line:e.line,branch:e.branch,function:e.function,statement:e.statement,files:r,measured:!0,...e.runStatus==="passed"||e.runStatus==="failed"?{runStatus:e.runStatus}:{}}}function b(n){if(!n||typeof n!="object")return null;let e=n;if(e.measured!==!0||!o(e.line))return null;let r=t=>o(t)?t:null,u=c(e.lines,e.line);return{line:e.line,branch:r(e.branch),function:r(e.function),statement:r(e.statement),measured:!0,...u?{lines:u}:{}}}function c(n,e){if(!n||typeof n!="object")return;let{covered:r,total:u}=n;if(!Number.isSafeInteger(r)||!Number.isSafeInteger(u))return;let t=r,i=u;if(!(i<=0||t<0||t>i||Math.abs(t/i*100-e)>.01))return{covered:t,total:i}}m();var s=class extends Error{constructor(e,r){super(`git ${e.join(" ")} timed out after ${Math.max(0,r)}ms`),this.name="GitTimeoutError"}};async function g(n,e){if(e.timeout<=0)throw new s(n,e.timeout);try{return await a("git",n,{cwd:e.cwd,timeout:e.timeout,maxBuffer:e.maxBuffer,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}catch(r){throw r.code==="ETIMEDOUT"?new s(n,e.timeout):r}}export{f as a,b,s as c,g as d};