agentic-qe 3.15.12 → 3.15.13

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 (467) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +118 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/cli/bundle.js +6 -6
  5. package/dist/cli/chunks/adapter-KCQDVYY2.js +2 -0
  6. package/dist/cli/chunks/{agent-booster-wasm-5VZCKTIJ.js → agent-booster-wasm-6RRQWMNE.js} +2 -2
  7. package/dist/cli/chunks/{agent-handler-K3C6CQCD.js → agent-handler-AOH6TV7W.js} +2 -2
  8. package/dist/cli/chunks/{agent-memory-branch-NVFQ25WS.js → agent-memory-branch-2P54SF5N.js} +2 -2
  9. package/dist/cli/chunks/aqe-learning-engine-SAQOHSGN.js +2 -0
  10. package/dist/cli/chunks/{arena-QGWIJADQ.js → arena-NSVFCAF5.js} +2 -2
  11. package/dist/cli/chunks/{arena-TSZVDSXS.js → arena-X6MOGQHA.js} +4 -4
  12. package/dist/cli/chunks/{audit-KIEE2SHJ.js → audit-27DJLQNM.js} +3 -3
  13. package/dist/cli/chunks/base-WCACU3FN.js +2 -0
  14. package/dist/cli/chunks/{better-sqlite3-BNB32NW3.js → better-sqlite3-BU5GXILS.js} +2 -2
  15. package/dist/cli/chunks/{brain-handler-MPC5SPYI.js → brain-handler-GTQNHHZS.js} +3 -3
  16. package/dist/cli/chunks/{branch-enumerator-LZ7UXKAY.js → branch-enumerator-5CLULOCU.js} +2 -2
  17. package/dist/cli/chunks/{browser-VDHAW4RK.js → browser-R4DMU3LN.js} +2 -2
  18. package/dist/cli/chunks/browser-workflow-G6IASEAP.js +2 -0
  19. package/dist/cli/chunks/{chunk-QUJJYTJH.js → chunk-2G7TVT6W.js} +2 -2
  20. package/dist/cli/chunks/{chunk-FAGKBOX2.js → chunk-32ZMWEP3.js} +2 -2
  21. package/dist/cli/chunks/{chunk-FNUFTWEO.js → chunk-3AN5TNGD.js} +3 -3
  22. package/dist/cli/chunks/{chunk-JOWUS2X5.js → chunk-3LJ7LQMV.js} +1 -1
  23. package/dist/cli/chunks/{chunk-O4QJMANM.js → chunk-3QZEGE67.js} +1 -1
  24. package/dist/cli/chunks/{chunk-ICKUINKD.js → chunk-3RZV5DGO.js} +2 -2
  25. package/dist/cli/chunks/{chunk-W4II6SIH.js → chunk-3Y2ROSCL.js} +2 -2
  26. package/dist/cli/chunks/{chunk-L7NGKANW.js → chunk-3Y7TJFHU.js} +2 -2
  27. package/dist/cli/chunks/{chunk-UUZZXHUF.js → chunk-3YNLWPBF.js} +2 -2
  28. package/dist/cli/chunks/{chunk-JR6CUKAI.js → chunk-42J34YG4.js} +2 -2
  29. package/dist/cli/chunks/{chunk-65TH6RPD.js → chunk-4OVC4RIL.js} +1 -1
  30. package/dist/cli/chunks/{chunk-DRCBRUGN.js → chunk-526QYFJU.js} +2 -2
  31. package/dist/cli/chunks/{chunk-MCPXNUDK.js → chunk-5FKWCZNF.js} +2 -2
  32. package/dist/cli/chunks/{chunk-NX4BCSOZ.js → chunk-5K26BEYB.js} +2 -2
  33. package/dist/cli/chunks/{chunk-MCPEC6OO.js → chunk-5MDERQH3.js} +1 -1
  34. package/dist/cli/chunks/{chunk-7JFDLL2F.js → chunk-5VMAV6T6.js} +1 -1
  35. package/dist/cli/chunks/{chunk-5TAEW5OV.js → chunk-5ZGM3RMH.js} +1 -1
  36. package/dist/cli/chunks/{chunk-SG2TX72G.js → chunk-6KATY3KS.js} +2 -2
  37. package/dist/cli/chunks/{chunk-KA5SHLMW.js → chunk-6Z7PRBSG.js} +2 -2
  38. package/dist/cli/chunks/{chunk-LFBA735S.js → chunk-72ASBE35.js} +3 -3
  39. package/dist/cli/chunks/{chunk-TOWOJGEI.js → chunk-756CGMEH.js} +1 -1
  40. package/dist/cli/chunks/{chunk-IVTQF55W.js → chunk-75RDHBAX.js} +3 -3
  41. package/dist/cli/chunks/{chunk-66PXR3NI.js → chunk-7CMTY45A.js} +2 -2
  42. package/dist/cli/chunks/{chunk-WLRU6ESI.js → chunk-7JUC2MVZ.js} +2 -2
  43. package/dist/cli/chunks/{chunk-SBHM5X2S.js → chunk-7NA7JXNB.js} +2 -2
  44. package/dist/cli/chunks/{chunk-HZBXJFGN.js → chunk-7PLIEBY7.js} +2 -2
  45. package/dist/cli/chunks/{chunk-2ASQRBK2.js → chunk-7YTGHGK4.js} +2 -2
  46. package/dist/cli/chunks/{chunk-SQVZ3TRU.js → chunk-A64JFBWI.js} +2 -2
  47. package/dist/cli/chunks/{chunk-2PPSS4JD.js → chunk-AL6FBH3E.js} +2 -2
  48. package/dist/cli/chunks/{chunk-3IU4LDZR.js → chunk-AQSVJNEH.js} +2 -2
  49. package/dist/cli/chunks/{chunk-C74M4WUI.js → chunk-ARJW4I2O.js} +2 -2
  50. package/dist/cli/chunks/{chunk-VF7FTD64.js → chunk-ASQYASNV.js} +1 -1
  51. package/dist/cli/chunks/{chunk-HLGFHHWV.js → chunk-BEGR4D6N.js} +2 -2
  52. package/dist/cli/chunks/{chunk-EN7GRVEQ.js → chunk-BK577VL7.js} +2 -2
  53. package/dist/cli/chunks/{chunk-KGA7VAI4.js → chunk-BLSLEVDI.js} +2 -2
  54. package/dist/cli/chunks/{chunk-HM3LSFTY.js → chunk-BTVEYBW2.js} +2 -2
  55. package/dist/cli/chunks/{chunk-J7Y7ZBIT.js → chunk-C6JTLKG7.js} +5 -5
  56. package/dist/cli/chunks/{chunk-PTBOLBM4.js → chunk-C7JM7CD3.js} +2 -2
  57. package/dist/cli/chunks/{chunk-IL7GQNNE.js → chunk-CCMKSHAT.js} +2 -2
  58. package/dist/cli/chunks/{chunk-23PQF7NN.js → chunk-CE7B5LU7.js} +1 -1
  59. package/dist/cli/chunks/{chunk-BMG2JLSQ.js → chunk-CM4LSLKR.js} +2 -2
  60. package/dist/cli/chunks/chunk-CRWPZT74.js +62 -0
  61. package/dist/cli/chunks/{chunk-4HWUECVD.js → chunk-CT6SAVXQ.js} +2 -2
  62. package/dist/cli/chunks/chunk-CV77DMDQ.js +2 -0
  63. package/dist/cli/chunks/{chunk-CU36D7TN.js → chunk-DFUASIKA.js} +2 -2
  64. package/dist/cli/chunks/{chunk-T4EN5VVK.js → chunk-DLD7RUZ4.js} +2 -2
  65. package/dist/cli/chunks/{chunk-IA55PFLG.js → chunk-DNDL7SOS.js} +2 -2
  66. package/dist/cli/chunks/{chunk-6QRI3JVE.js → chunk-DVGRPK7A.js} +2 -2
  67. package/dist/cli/chunks/{chunk-UREDS662.js → chunk-E56B6IDX.js} +2 -2
  68. package/dist/cli/chunks/{chunk-ZGROHCOW.js → chunk-E7CLYGS7.js} +1 -1
  69. package/dist/cli/chunks/{chunk-YNVEDFPQ.js → chunk-EXGMJFAT.js} +1 -1
  70. package/dist/cli/chunks/{chunk-JRYWLOBD.js → chunk-F3YS57NF.js} +2 -2
  71. package/dist/cli/chunks/{chunk-ZYOYR3UR.js → chunk-FZ76G4QJ.js} +1 -1
  72. package/dist/cli/chunks/{chunk-UIKQPO4Y.js → chunk-G2Q66Z23.js} +2 -2
  73. package/dist/cli/chunks/{chunk-5S4UIDFK.js → chunk-G6WDYBLQ.js} +1 -1
  74. package/dist/cli/chunks/{chunk-4SA7M34P.js → chunk-G77ERMUD.js} +1 -1
  75. package/dist/cli/chunks/{chunk-ADUAJIAU.js → chunk-GB6HBNH2.js} +2 -2
  76. package/dist/cli/chunks/{chunk-IETBWYHW.js → chunk-GHM6MQNK.js} +2 -2
  77. package/dist/cli/chunks/{chunk-QWG3SILX.js → chunk-GHY6Z6KO.js} +5 -5
  78. package/dist/cli/chunks/{chunk-AJEXPFAB.js → chunk-GII6UM3F.js} +1 -1
  79. package/dist/cli/chunks/{chunk-SDRJJUPO.js → chunk-GU5HNCWI.js} +1 -1
  80. package/dist/cli/chunks/{chunk-ULCW6IVQ.js → chunk-H4GG2NLO.js} +2 -2
  81. package/dist/cli/chunks/{chunk-7TA5MUPW.js → chunk-H4H2YSFH.js} +1 -1
  82. package/dist/cli/chunks/{chunk-5A66EGEW.js → chunk-HD7YIFOI.js} +2 -2
  83. package/dist/cli/chunks/{chunk-CDA5Z74H.js → chunk-HOAJUIBQ.js} +2 -2
  84. package/dist/cli/chunks/{chunk-4KUOYDY2.js → chunk-HQZGPJYG.js} +2 -2
  85. package/dist/cli/chunks/{chunk-G3AABG4Q.js → chunk-HZ5NXFXH.js} +2 -2
  86. package/dist/cli/chunks/{chunk-U6IXYQO4.js → chunk-I3C7JOXC.js} +2 -2
  87. package/dist/cli/chunks/{chunk-MAJXZYGK.js → chunk-IC3TQEOA.js} +1 -1
  88. package/dist/cli/chunks/{chunk-RYHG3I7J.js → chunk-IJUHSJ2U.js} +2 -2
  89. package/dist/cli/chunks/{chunk-DZGPUGUG.js → chunk-J2ZIFFM6.js} +2 -2
  90. package/dist/cli/chunks/{chunk-NA3F6FEO.js → chunk-JGZ722G3.js} +2 -2
  91. package/dist/cli/chunks/{chunk-PX5OPXY6.js → chunk-JQGMW45H.js} +1 -1
  92. package/dist/cli/chunks/{chunk-WGTEZT7G.js → chunk-JRRXCODW.js} +2 -2
  93. package/dist/cli/chunks/{chunk-4Y6OEBJZ.js → chunk-K3TLLJMX.js} +1 -1
  94. package/dist/cli/chunks/{chunk-RCOLPF3B.js → chunk-K4CZA77U.js} +2 -2
  95. package/dist/cli/chunks/{chunk-YIDAXOUX.js → chunk-K65CGKLD.js} +2 -2
  96. package/dist/cli/chunks/{chunk-5ADXFUMO.js → chunk-KADFXPPN.js} +2 -2
  97. package/dist/cli/chunks/{chunk-P5E26N2X.js → chunk-KB56CPU4.js} +2 -2
  98. package/dist/cli/chunks/{chunk-YLKIXEPP.js → chunk-KCW47QR5.js} +1 -1
  99. package/dist/cli/chunks/{chunk-SPC4RBLF.js → chunk-KDNJ4F3P.js} +2 -2
  100. package/dist/cli/chunks/{chunk-P7UFJ6DO.js → chunk-KDVZND5Q.js} +1 -1
  101. package/dist/cli/chunks/{chunk-TLRHAMX5.js → chunk-KUAKV3IW.js} +1 -1
  102. package/dist/cli/chunks/{chunk-ZROAMFX2.js → chunk-KV4T4MXK.js} +2 -2
  103. package/dist/cli/chunks/{chunk-UZED4YZ5.js → chunk-KWYH3FI4.js} +1 -1
  104. package/dist/cli/chunks/{chunk-33I2ZP6E.js → chunk-LFJALJOA.js} +2 -2
  105. package/dist/cli/chunks/{chunk-TXEUVUMO.js → chunk-LL7LDPXS.js} +1 -1
  106. package/dist/cli/chunks/{chunk-W5HQIYQU.js → chunk-LUZNKJE6.js} +3 -3
  107. package/dist/cli/chunks/{chunk-GKFV6CUD.js → chunk-LWR3FV3Y.js} +2 -2
  108. package/dist/cli/chunks/{chunk-TVA5GRIU.js → chunk-LZYQHVD4.js} +2 -2
  109. package/dist/cli/chunks/{chunk-2JYUA27M.js → chunk-M6AAGIG7.js} +1 -1
  110. package/dist/cli/chunks/{chunk-PT2NXS43.js → chunk-MAMQA43L.js} +1 -1
  111. package/dist/cli/chunks/chunk-MB46UBGY.js +3 -0
  112. package/dist/cli/chunks/{chunk-ZPVGX4DI.js → chunk-MFW5HSG4.js} +2 -2
  113. package/dist/cli/chunks/{chunk-47RMGDG4.js → chunk-MGZ5FJUW.js} +2 -2
  114. package/dist/cli/chunks/{chunk-G24SWTAX.js → chunk-MVVB7C2E.js} +410 -410
  115. package/dist/cli/chunks/{chunk-XZOYKB22.js → chunk-N4CYAKOX.js} +2 -2
  116. package/dist/cli/chunks/{chunk-QCPVUNN3.js → chunk-NT4DBXSX.js} +2 -2
  117. package/dist/cli/chunks/{chunk-3EWQN37E.js → chunk-NU3W5WFT.js} +2 -2
  118. package/dist/cli/chunks/{chunk-VZBC6DP7.js → chunk-NURIILUB.js} +1 -1
  119. package/dist/cli/chunks/{chunk-6E6HB4N4.js → chunk-NW7IBHJA.js} +4 -4
  120. package/dist/cli/chunks/{chunk-K3A3NWT3.js → chunk-NZ3GUMB2.js} +2 -2
  121. package/dist/cli/chunks/{chunk-GJKZ7UQO.js → chunk-NZD4DPSU.js} +2 -2
  122. package/dist/cli/chunks/{chunk-7QEUHNKO.js → chunk-O6FGXMHD.js} +1 -1
  123. package/dist/cli/chunks/{chunk-YVJEUX3I.js → chunk-OCAEXYFA.js} +2 -2
  124. package/dist/cli/chunks/{chunk-BOSMELJX.js → chunk-OFACHK5O.js} +2 -2
  125. package/dist/cli/chunks/{chunk-PGSJBXTD.js → chunk-P7A4NKTZ.js} +2 -2
  126. package/dist/cli/chunks/{chunk-HSA5IGGW.js → chunk-PB6J6HAA.js} +2 -2
  127. package/dist/cli/chunks/{chunk-TGMXUZZC.js → chunk-PHP5UBT4.js} +2 -2
  128. package/dist/cli/chunks/{chunk-NV74SICL.js → chunk-PIDQVU3L.js} +2 -2
  129. package/dist/cli/chunks/{chunk-TSOQ2QLT.js → chunk-PSFSPGUD.js} +2 -2
  130. package/dist/cli/chunks/{chunk-4A76VPU4.js → chunk-PT4FMJPQ.js} +2 -2
  131. package/dist/cli/chunks/{chunk-U7ZHDGXG.js → chunk-Q3UDLV5Z.js} +1 -1
  132. package/dist/cli/chunks/{chunk-BYRCB5JT.js → chunk-QDEJ4CI2.js} +2 -2
  133. package/dist/cli/chunks/{chunk-CA5UNWQF.js → chunk-QPNG5ZN2.js} +2 -2
  134. package/dist/cli/chunks/{chunk-W7H55PY4.js → chunk-R7SYRCRP.js} +1 -1
  135. package/dist/cli/chunks/{chunk-4LWMAAWK.js → chunk-RF7HWBHN.js} +2 -2
  136. package/dist/cli/chunks/{chunk-MMEALJ4D.js → chunk-RFNW2LGD.js} +2 -2
  137. package/dist/cli/chunks/{chunk-UCSK2RMI.js → chunk-S5AZCIZS.js} +2 -2
  138. package/dist/cli/chunks/{chunk-JW5PDJ5O.js → chunk-SE4VNN4I.js} +3 -3
  139. package/dist/cli/chunks/{chunk-URSTP3WI.js → chunk-SG3NX7QE.js} +2 -2
  140. package/dist/cli/chunks/{chunk-N7O3PF6Y.js → chunk-SSU73QAX.js} +2 -2
  141. package/dist/cli/chunks/{chunk-7DNR4KKR.js → chunk-SVLQRAMF.js} +1 -1
  142. package/dist/cli/chunks/{chunk-BC4T6SCV.js → chunk-SYV2V3PL.js} +4 -4
  143. package/dist/cli/chunks/{chunk-4CB3QPZM.js → chunk-T3PGQFDI.js} +2 -2
  144. package/dist/cli/chunks/{chunk-OHVYINGM.js → chunk-TCBBNUBP.js} +3 -3
  145. package/dist/cli/chunks/{chunk-YWWMNTBF.js → chunk-TOQWL2ZF.js} +2 -2
  146. package/dist/cli/chunks/{chunk-SITL5YZV.js → chunk-TSQC2KKZ.js} +2 -2
  147. package/dist/cli/chunks/{chunk-YUA6ZKKY.js → chunk-TWDW32W2.js} +2 -2
  148. package/dist/cli/chunks/{chunk-SUX5XB2Z.js → chunk-TWJTK4CC.js} +2 -2
  149. package/dist/cli/chunks/{chunk-32UTHIY5.js → chunk-U2FUXDDJ.js} +3 -3
  150. package/dist/cli/chunks/{chunk-ENGL7FIJ.js → chunk-UDQSYWVF.js} +1 -1
  151. package/dist/cli/chunks/{chunk-7OEFBWAG.js → chunk-UOC3O6RP.js} +2 -2
  152. package/dist/cli/chunks/chunk-UT2VZ33P.js +2 -0
  153. package/dist/cli/chunks/{chunk-MYF5CNGV.js → chunk-UTRV7T2N.js} +2 -2
  154. package/dist/cli/chunks/{chunk-KJDI5CHX.js → chunk-UXZSUMEA.js} +2 -2
  155. package/dist/cli/chunks/{chunk-DAUEK66C.js → chunk-VRHRBAEM.js} +1 -1
  156. package/dist/cli/chunks/{chunk-FZJCBSN4.js → chunk-VRVMIPTM.js} +2 -2
  157. package/dist/cli/chunks/{chunk-26672ISV.js → chunk-VTDFVFST.js} +2 -2
  158. package/dist/cli/chunks/{chunk-WTAUF6O4.js → chunk-VTOBUZL6.js} +2 -2
  159. package/dist/cli/chunks/{chunk-4PU5GTZW.js → chunk-VU5TBX2V.js} +2 -2
  160. package/dist/cli/chunks/{chunk-C3YOVASQ.js → chunk-W26B7ERY.js} +1 -1
  161. package/dist/cli/chunks/{chunk-CPIBIR3X.js → chunk-W2QWSQVE.js} +2 -2
  162. package/dist/cli/chunks/{chunk-L3PV7VXK.js → chunk-W3INMZZ6.js} +1 -1
  163. package/dist/cli/chunks/{chunk-5Z23ZMXZ.js → chunk-W3PPFHI5.js} +54 -54
  164. package/dist/cli/chunks/{chunk-NVRYELCY.js → chunk-WKGTGOYS.js} +3 -3
  165. package/dist/cli/chunks/{chunk-35NW676P.js → chunk-WNQS4WTS.js} +2 -2
  166. package/dist/cli/chunks/{chunk-O3IM4WRZ.js → chunk-WO274FRI.js} +2 -2
  167. package/dist/cli/chunks/{chunk-35MIUSXQ.js → chunk-WOCGL4QP.js} +2 -2
  168. package/dist/cli/chunks/{chunk-EF6OERRR.js → chunk-WQL7WCIZ.js} +1 -1
  169. package/dist/cli/chunks/{chunk-INZARYUD.js → chunk-X2Z7F4EU.js} +2 -2
  170. package/dist/cli/chunks/{chunk-2E2QO44T.js → chunk-X7N2JF2X.js} +2 -2
  171. package/dist/cli/chunks/{chunk-2IVE5AR3.js → chunk-XEAEYC6Y.js} +1 -1
  172. package/dist/cli/chunks/{chunk-IPA7K556.js → chunk-XNBOGCF3.js} +2 -2
  173. package/dist/cli/chunks/{chunk-A2JCRXTK.js → chunk-XPRVF4YE.js} +2 -2
  174. package/dist/cli/chunks/{chunk-VUR5THML.js → chunk-YBQH2VOP.js} +2 -2
  175. package/dist/cli/chunks/{chunk-A5Y7DAVQ.js → chunk-YQFLQE53.js} +2 -2
  176. package/dist/cli/chunks/{chunk-JGIJPDGD.js → chunk-YSZ5OE3Z.js} +2 -2
  177. package/dist/cli/chunks/{chunk-JNXK47OL.js → chunk-YXRASAPI.js} +2 -2
  178. package/dist/cli/chunks/{chunk-MYUMJ2ZI.js → chunk-YZEXYO4W.js} +1 -1
  179. package/dist/cli/chunks/{chunk-NNBQZR73.js → chunk-YZWBNBTW.js} +2 -2
  180. package/dist/cli/chunks/{chunk-WDEXOLK2.js → chunk-ZAKQLAHT.js} +1 -1
  181. package/dist/cli/chunks/{ci-BZNWW3I3.js → ci-ENOASTYB.js} +2 -2
  182. package/dist/cli/chunks/{ci-config-LOHNXOKV.js → ci-config-B26OXHQM.js} +2 -2
  183. package/dist/cli/chunks/{ci-output-LCOQBSJL.js → ci-output-JTCLLNOQ.js} +2 -2
  184. package/dist/cli/chunks/{circuit-breaker-7LRXTLFE.js → circuit-breaker-23JMFNM5.js} +2 -2
  185. package/dist/cli/chunks/{claude-flow-setup-HBU4VWC3.js → claude-flow-setup-ON6L462G.js} +2 -2
  186. package/dist/cli/chunks/client-TV3V2YZ5.js +2 -0
  187. package/dist/cli/chunks/{cline-installer-CO6MLH6X.js → cline-installer-OWQ4D2FQ.js} +2 -2
  188. package/dist/cli/chunks/{code-SIXBS6JM.js → code-2ZRL7SEU.js} +19 -18
  189. package/dist/cli/chunks/{code-index-extractor-GWJKZ2IQ.js → code-index-extractor-JXSQVM67.js} +2 -2
  190. package/dist/cli/chunks/{codex-installer-6NINVWXJ.js → codex-installer-7LXZYBSQ.js} +2 -2
  191. package/dist/cli/chunks/{completions-7VIX3GML.js → completions-C2LR623C.js} +2 -2
  192. package/dist/cli/chunks/{complexity-analyzer-FBQR6ZP2.js → complexity-analyzer-TGQLHCYJ.js} +2 -2
  193. package/dist/cli/chunks/{continuedev-installer-VA7RIXW5.js → continuedev-installer-RUGD24D2.js} +2 -2
  194. package/dist/cli/chunks/{copilot-installer-4QEBC4MU.js → copilot-installer-ZLFVLEJP.js} +2 -2
  195. package/dist/cli/chunks/core-handlers-PZT4OLWR.js +2 -0
  196. package/dist/cli/chunks/{cost-tracker-GRYKHPWL.js → cost-tracker-RT4QL745.js} +2 -2
  197. package/dist/cli/chunks/{coverage-USPMNKOU.js → coverage-NV3C4IMM.js} +3 -3
  198. package/dist/cli/chunks/cross-domain-router-QOFCZ7G4.js +2 -0
  199. package/dist/cli/chunks/{cursor-installer-ZXIPSZVH.js → cursor-installer-LJKLNFF6.js} +2 -2
  200. package/dist/cli/chunks/{daemon-D7F3RGI5.js → daemon-BMDXCQT5.js} +3 -3
  201. package/dist/cli/chunks/{daemon-N2VRHPSJ.js → daemon-FBH3IRYN.js} +4 -4
  202. package/dist/cli/chunks/{dag-attention-scheduler-NL6BA7BY.js → dag-attention-scheduler-JGDED55I.js} +2 -2
  203. package/dist/cli/chunks/{detect-XC2HCIIT.js → detect-SZIHIVCJ.js} +2 -2
  204. package/dist/cli/chunks/{dist-node-A3Y26MEI.js → dist-node-FV3KWXQ6.js} +2 -2
  205. package/dist/cli/chunks/{domain-handler-WV6SFXRB.js → domain-handler-GI5JWQOV.js} +2 -2
  206. package/dist/cli/chunks/{domain-plugins-KJIF6Z2B.js → domain-plugins-BUWY36TL.js} +2 -2
  207. package/dist/cli/chunks/domain-transfer-GCY7W5DA.js +2 -0
  208. package/dist/cli/chunks/dream-TRFBGDSQ.js +2 -0
  209. package/dist/cli/chunks/{embed-and-insert-pattern-PA3Y4KGO.js → embed-and-insert-pattern-GPRR3ZGD.js} +2 -2
  210. package/dist/cli/chunks/{eval-YGEZNUVE.js → eval-XPB3IGAP.js} +2 -2
  211. package/dist/cli/chunks/{experience-capture-middleware-D4T7NW6B.js → experience-capture-middleware-2E554UB3.js} +3 -3
  212. package/dist/cli/chunks/{fast-paths-6JYK7RYQ.js → fast-paths-ZSMWZPUC.js} +2 -2
  213. package/dist/cli/chunks/{feature-flags-RBH2GDSR.js → feature-flags-GIWVDVVC.js} +2 -2
  214. package/dist/cli/chunks/{feature-flags-DKXMDVPE.js → feature-flags-N7EOGE5P.js} +2 -2
  215. package/dist/cli/chunks/file-discovery-WCKGMSPZ.js +2 -0
  216. package/dist/cli/chunks/fleet-HCHDOUCX.js +44 -0
  217. package/dist/cli/chunks/{gnn-wrapper-MV54UC4C.js → gnn-wrapper-CZNCNXXZ.js} +2 -2
  218. package/dist/cli/chunks/{heartbeat-handler-7DKMVQQH.js → heartbeat-handler-6YUIF2YQ.js} +4 -4
  219. package/dist/cli/chunks/heartbeat-scheduler-P44A2OX3.js +2 -0
  220. package/dist/cli/chunks/hnsw-adapter-ZJQIQJKC.js +2 -0
  221. package/dist/cli/chunks/hnsw-index-HMG2GH3Z.js +2 -0
  222. package/dist/cli/chunks/{hnsw-legacy-bridge-6IWREDQC.js → hnsw-legacy-bridge-J3M3IK24.js} +2 -2
  223. package/dist/cli/chunks/{hnswlib-node-5BIESSCK.js → hnswlib-node-ULGTGDZW.js} +2 -2
  224. package/dist/cli/chunks/{hooks-3EETRM62.js → hooks-C4BUGYUQ.js} +10 -10
  225. package/dist/cli/chunks/hybrid-backend-B7M74PZG.js +2 -0
  226. package/dist/cli/chunks/{hypergraph-engine-RSWCB2D3.js → hypergraph-engine-WINGVMPG.js} +2 -2
  227. package/dist/cli/chunks/{hypergraph-handler-552LXKL3.js → hypergraph-handler-GADMWKAU.js} +3 -3
  228. package/dist/cli/chunks/impact-analyzer-PZYOVKQO.js +2 -0
  229. package/dist/cli/chunks/{init-guard-OTDBJ5HD.js → init-guard-K2T4QWAO.js} +2 -2
  230. package/dist/cli/chunks/{init-handler-3FK3TKEA.js → init-handler-PCZTDZYI.js} +6 -6
  231. package/dist/cli/chunks/init-wizard-TZDJQK3U.js +2 -0
  232. package/dist/cli/chunks/kernel-Y6RRIOKW.js +2 -0
  233. package/dist/cli/chunks/{kilocode-installer-KZ2O4LF3.js → kilocode-installer-XENXNEIU.js} +2 -2
  234. package/dist/cli/chunks/{kiro-installer-MLCCXRF7.js → kiro-installer-3PG2TJ67.js} +2 -2
  235. package/dist/cli/chunks/knowledge-graph-BVD5Z66M.js +2 -0
  236. package/dist/cli/chunks/{learning-QUCMBD77.js → learning-6KDH7FK4.js} +3 -3
  237. package/dist/cli/chunks/{llm-router-PDEV3UP2.js → llm-router-RKVDEWU2.js} +4 -4
  238. package/dist/cli/chunks/llm-router-service-KHCAMSUU.js +2 -0
  239. package/dist/cli/chunks/{load-XFVVLO7E.js → load-ITHC564X.js} +2 -2
  240. package/dist/cli/chunks/load-test-RUF7DZA5.js +2 -0
  241. package/dist/cli/chunks/{mcp-74G3CL2S.js → mcp-TCL5UW3N.js} +2 -2
  242. package/dist/cli/chunks/{memory-XIFM6JNX.js → memory-BKDAY2N2.js} +5 -5
  243. package/dist/cli/chunks/memory-backend-7ZLFOVGG.js +2 -0
  244. package/dist/cli/chunks/{memory-handlers-ZCKURV6S.js → memory-handlers-WN4FXFOA.js} +2 -2
  245. package/dist/cli/chunks/{multi-model-executor-7L4W3O2Q.js → multi-model-executor-VHAT7ZPF.js} +2 -2
  246. package/dist/cli/chunks/{opencode-installer-BPG422LF.js → opencode-installer-E3VM3EEY.js} +2 -2
  247. package/dist/cli/chunks/{orchestrator-OEAFLAEV.js → orchestrator-BMQ6X762.js} +5 -5
  248. package/dist/cli/chunks/pattern-null-store-RY6CVYHP.js +2 -0
  249. package/dist/cli/chunks/{pattern-usage-recorder-LOPNCULT.js → pattern-usage-recorder-GOOR2BV5.js} +2 -2
  250. package/dist/cli/chunks/{pipeline-VWTYUZB7.js → pipeline-5NSFQQIX.js} +2 -2
  251. package/dist/cli/chunks/{platform-WFJJ3X2E.js → platform-SQM34J5G.js} +2 -2
  252. package/dist/cli/chunks/{plugin-744TPUSG.js → plugin-UQJZRMZG.js} +2 -2
  253. package/dist/cli/chunks/{prime-radiant-advanced-wasm-BD5BLNDR.js → prime-radiant-advanced-wasm-WMDJOL4S.js} +2 -2
  254. package/dist/cli/chunks/project-root-IO5KRNGL.js +2 -0
  255. package/dist/cli/chunks/protocol-executor-U2CUDWDE.js +2 -0
  256. package/dist/cli/chunks/{protocol-handler-JIBILI74.js → protocol-handler-OBDCVY6X.js} +2 -2
  257. package/dist/cli/chunks/{prove-MNOL5FYW.js → prove-XDC7I4XT.js} +2 -2
  258. package/dist/cli/chunks/qe-reasoning-bank-DQSSX2IP.js +2 -0
  259. package/dist/cli/chunks/{quality-JEGBDGGX.js → quality-L4GQ6WX4.js} +2 -2
  260. package/dist/cli/chunks/{quality-gate-SYJ6ROMI.js → quality-gate-MJG66LKN.js} +3 -3
  261. package/dist/cli/chunks/queen-coordinator-6FN4BZIX.js +2 -0
  262. package/dist/cli/chunks/{real-embeddings-ZWXS5ZFV.js → real-embeddings-HW4G2LWL.js} +2 -2
  263. package/dist/cli/chunks/{ref-validation-RRHUFW2N.js → ref-validation-FC7JOJ2C.js} +2 -2
  264. package/dist/cli/chunks/{roocode-installer-XFO6JSVN.js → roocode-installer-KWS4CEIC.js} +2 -2
  265. package/dist/cli/chunks/router-YUO3I7RU.js +2 -0
  266. package/dist/cli/chunks/routing-feedback-36SLQGJE.js +2 -0
  267. package/dist/cli/chunks/{routing-handler-L2K3JASE.js → routing-handler-QF4WVB2S.js} +2 -2
  268. package/dist/cli/chunks/{ruvector-commands-A6CINHGM.js → ruvector-commands-2MTCOUK6.js} +2 -2
  269. package/dist/cli/chunks/rvf-dual-writer-FRYZH3WZ.js +2 -0
  270. package/dist/cli/chunks/rvf-migration-adapter-XXNITL5I.js +2 -0
  271. package/dist/cli/chunks/{rvf-migration-coordinator-T4RY7L53.js → rvf-migration-coordinator-BREJCXWN.js} +2 -2
  272. package/dist/cli/chunks/rvf-native-adapter-D2WWKJIV.js +2 -0
  273. package/dist/cli/chunks/{rvf-store-integrity-IR33TGQS.js → rvf-store-integrity-KKC6HOJD.js} +2 -2
  274. package/dist/cli/chunks/safe-db-4RRIGRXD.js +2 -0
  275. package/dist/cli/chunks/schedule-25RTO4DQ.js +2 -0
  276. package/dist/cli/chunks/scheduler-BPIOJZ5P.js +2 -0
  277. package/dist/cli/chunks/{security-Z5GDE2IH.js → security-OSAE7VAP.js} +3 -3
  278. package/dist/cli/chunks/{shared-rvf-adapter-SIZMEHPM.js → shared-rvf-adapter-COUOS665.js} +2 -2
  279. package/dist/cli/chunks/{shared-rvf-dual-writer-HLM65RDS.js → shared-rvf-dual-writer-YXMPZKQE.js} +2 -2
  280. package/dist/cli/chunks/sqlite-persistence-EDF47DDX.js +2 -0
  281. package/dist/cli/chunks/{standalone-memory-SKSZG7P5.js → standalone-memory-E6JBMOIL.js} +2 -2
  282. package/dist/cli/chunks/{status-handler-766YOOMJ.js → status-handler-AFTCIYIX.js} +2 -2
  283. package/dist/cli/chunks/{structural-health-M45FNOLT.js → structural-health-2FROCEI4.js} +2 -2
  284. package/dist/cli/chunks/{sync-B2U366I3.js → sync-VAYTOWDC.js} +2 -2
  285. package/dist/cli/chunks/{sync-6CJ24B5T.js → sync-YIQYOFGW.js} +2 -2
  286. package/dist/cli/chunks/task-handler-KVQHDEX3.js +62 -0
  287. package/dist/cli/chunks/task-handlers-MVVECQA6.js +9 -0
  288. package/dist/cli/chunks/{test-TODH7KRF.js → test-5JSVTOMY.js} +4 -4
  289. package/dist/cli/chunks/test-runner-process-LEPF2OSS.js +2 -0
  290. package/dist/cli/chunks/{test-scheduling-VMVMVRHT.js → test-scheduling-HBOHVLI3.js} +3 -3
  291. package/dist/cli/chunks/{token-bootstrap-XQW7BMCK.js → token-bootstrap-5VEPTPFA.js} +2 -2
  292. package/dist/cli/chunks/{token-usage-JCZEIRKO.js → token-usage-TBJHDLY6.js} +2 -2
  293. package/dist/cli/chunks/{transformers-U2ML3OHE.js → transformers-VAWYMHMZ.js} +2 -2
  294. package/dist/cli/chunks/tree-sitter-wasm-parser-TSZTCMFV.js +2 -0
  295. package/dist/cli/chunks/{types-GGEPCHP6.js → types-R5SDZU2E.js} +2 -2
  296. package/dist/cli/chunks/unified-memory-TLGSSLMI.js +2 -0
  297. package/dist/cli/chunks/unified-memory-hnsw-MSUR7ZOO.js +2 -0
  298. package/dist/cli/chunks/unified-persistence-VFFOTWK7.js +2 -0
  299. package/dist/cli/chunks/{upgrade-T5GRM7HS.js → upgrade-K5PIHXRB.js} +2 -2
  300. package/dist/cli/chunks/{validate-XMUJPLP3.js → validate-RPTS7RYJ.js} +2 -2
  301. package/dist/cli/chunks/{validate-swarm-KJLF7JEH.js → validate-swarm-B2ZL556X.js} +2 -2
  302. package/dist/cli/chunks/visual-security-6Q44XNLB.js +2 -0
  303. package/dist/cli/chunks/{web-tree-sitter-LOHVZ7G5.js → web-tree-sitter-K4DUJC32.js} +2 -2
  304. package/dist/cli/chunks/{windsurf-installer-33FBTXJU.js → windsurf-installer-OK2AJN35.js} +2 -2
  305. package/dist/cli/chunks/witness-chain-KDOMXDQX.js +2 -0
  306. package/dist/cli/chunks/witness-chain-N3OY2RMH.js +2 -0
  307. package/dist/cli/chunks/{witness-chain-repair-VWBO4NXE.js → witness-chain-repair-L6Y5RFXR.js} +2 -2
  308. package/dist/cli/chunks/{witness-chain-verifier-BHJ3ZAEK.js → witness-chain-verifier-N4CW7FZX.js} +2 -2
  309. package/dist/cli/chunks/{witness-key-manager-WNVPH2Z3.js → witness-key-manager-TDNPS3WD.js} +2 -2
  310. package/dist/cli/chunks/{workflow-6QR5MQTO.js → workflow-XRZA3YCY.js} +4 -4
  311. package/dist/cli/chunks/workflow-orchestrator-CVNNT2RJ.js +2 -0
  312. package/dist/cli/chunks/{wrappers-EHOL62TS.js → wrappers-5JIFWKN6.js} +2 -2
  313. package/dist/cli/commands/code.js +6 -0
  314. package/dist/cli/commands/fleet-run.d.ts +12 -0
  315. package/dist/cli/commands/fleet-run.js +175 -0
  316. package/dist/cli/commands/fleet.js +2 -117
  317. package/dist/cli/handlers/task-handler.d.ts +5 -0
  318. package/dist/cli/handlers/task-handler.js +20 -0
  319. package/dist/cli/utils/fleet-operation.d.ts +5 -2
  320. package/dist/cli/utils/fleet-operation.js +13 -2
  321. package/dist/cli/utils/fleet-result.d.ts +16 -2
  322. package/dist/cli/utils/fleet-result.js +26 -21
  323. package/dist/cli/utils/fleet-shard.d.ts +36 -0
  324. package/dist/cli/utils/fleet-shard.js +110 -0
  325. package/dist/coordination/handlers/code-intelligence-handlers.js +21 -1
  326. package/dist/coordination/handlers/handler-types.d.ts +2 -2
  327. package/dist/coordination/handlers/handler-utils.d.ts +6 -0
  328. package/dist/coordination/handlers/handler-utils.js +14 -4
  329. package/dist/coordination/handlers/misc-handlers.js +5 -2
  330. package/dist/coordination/handlers/quality-handlers.js +2 -2
  331. package/dist/coordination/handlers/security-handlers.js +12 -2
  332. package/dist/coordination/protocols/security-audit.js +11 -1
  333. package/dist/coordination/task-executor.js +7 -2
  334. package/dist/domains/code-intelligence/coordinator-gnn.d.ts +2 -16
  335. package/dist/domains/code-intelligence/coordinator-gnn.js +1 -62
  336. package/dist/domains/code-intelligence/coordinator.d.ts +12 -6
  337. package/dist/domains/code-intelligence/coordinator.js +24 -27
  338. package/dist/domains/code-intelligence/interfaces.d.ts +9 -0
  339. package/dist/domains/code-intelligence/services/semantic-analyzer.d.ts +43 -5
  340. package/dist/domains/code-intelligence/services/semantic-analyzer.js +134 -71
  341. package/dist/domains/coverage-analysis/collected-metrics.d.ts +10 -0
  342. package/dist/domains/coverage-analysis/collected-metrics.js +29 -0
  343. package/dist/domains/coverage-analysis/services/coverage-analyzer.js +11 -3
  344. package/dist/domains/coverage-analysis/services/coverage-parser.d.ts +2 -0
  345. package/dist/domains/coverage-analysis/services/coverage-parser.js +18 -2
  346. package/dist/domains/quality-assessment/coherence/gate-controller.js +16 -4
  347. package/dist/domains/quality-assessment/coherence/lambda-calculator.d.ts +8 -0
  348. package/dist/domains/quality-assessment/coherence/lambda-calculator.js +57 -14
  349. package/dist/domains/quality-assessment/coherence/types.d.ts +12 -7
  350. package/dist/domains/quality-assessment/coordinator-gate-evaluation.js +3 -1
  351. package/dist/domains/quality-assessment/coordinator-reports.d.ts +30 -10
  352. package/dist/domains/quality-assessment/coordinator-reports.js +93 -57
  353. package/dist/domains/quality-assessment/coordinator.d.ts +14 -40
  354. package/dist/domains/quality-assessment/coordinator.js +10 -4
  355. package/dist/domains/quality-assessment/interfaces.d.ts +2 -0
  356. package/dist/domains/quality-assessment/services/coherence-gate.js +15 -2
  357. package/dist/domains/quality-assessment/services/quality-gate.js +6 -4
  358. package/dist/domains/security-compliance/index.d.ts +1 -1
  359. package/dist/domains/security-compliance/interfaces.d.ts +46 -5
  360. package/dist/domains/security-compliance/services/scanners/dast-auth-testing.d.ts +3 -3
  361. package/dist/domains/security-compliance/services/scanners/dast-auth-testing.js +15 -14
  362. package/dist/domains/security-compliance/services/scanners/dast-helpers.d.ts +8 -9
  363. package/dist/domains/security-compliance/services/scanners/dast-helpers.js +19 -44
  364. package/dist/domains/security-compliance/services/scanners/dast-injection-testing.d.ts +3 -3
  365. package/dist/domains/security-compliance/services/scanners/dast-injection-testing.js +13 -9
  366. package/dist/domains/security-compliance/services/scanners/dast-requests.d.ts +54 -0
  367. package/dist/domains/security-compliance/services/scanners/dast-requests.js +125 -0
  368. package/dist/domains/security-compliance/services/scanners/dast-scanner.d.ts +5 -1
  369. package/dist/domains/security-compliance/services/scanners/dast-scanner.js +125 -155
  370. package/dist/domains/security-compliance/services/scanners/index.d.ts +1 -1
  371. package/dist/domains/security-compliance/services/scanners/index.js +1 -1
  372. package/dist/domains/security-compliance/services/scanners/scanner-types.d.ts +2 -2
  373. package/dist/domains/security-compliance/services/security-auditor-dast.js +183 -212
  374. package/dist/domains/security-compliance/services/security-auditor-reports.js +5 -1
  375. package/dist/domains/security-compliance/services/security-auditor.d.ts +11 -3
  376. package/dist/domains/security-compliance/services/security-auditor.js +106 -65
  377. package/dist/domains/test-execution/coordinator.d.ts +2 -1
  378. package/dist/domains/test-execution/coordinator.js +33 -27
  379. package/dist/domains/test-execution/interfaces.d.ts +5 -0
  380. package/dist/domains/test-execution/services/test-executor.d.ts +6 -0
  381. package/dist/domains/test-execution/services/test-executor.js +16 -4
  382. package/dist/domains/visual-accessibility/coordinator.js +34 -9
  383. package/dist/domains/visual-accessibility/interfaces.d.ts +27 -0
  384. package/dist/domains/visual-accessibility/plugin.js +5 -0
  385. package/dist/domains/visual-accessibility/services/accessibility-tester-heuristics.d.ts +13 -21
  386. package/dist/domains/visual-accessibility/services/accessibility-tester-heuristics.js +13 -297
  387. package/dist/domains/visual-accessibility/services/accessibility-tester.d.ts +13 -5
  388. package/dist/domains/visual-accessibility/services/accessibility-tester.js +96 -73
  389. package/dist/integrations/embeddings/index/HNSWIndex.js +8 -4
  390. package/dist/integrations/ruvector/transfer-coherence-stub.js +5 -10
  391. package/dist/mcp/bundle.js +480 -480
  392. package/dist/mcp/handlers/domain-handler-configs.d.ts +8 -0
  393. package/dist/mcp/handlers/domain-handler-configs.js +9 -2
  394. package/dist/mcp/handlers/handler-factory.js +3 -0
  395. package/dist/mcp/handlers/model-route-handlers.d.ts +107 -0
  396. package/dist/mcp/handlers/model-route-handlers.js +139 -0
  397. package/dist/mcp/handlers/orchestrate-routes.js +41 -3
  398. package/dist/mcp/handlers/task-handlers.d.ts +3 -251
  399. package/dist/mcp/handlers/task-handlers.js +6 -828
  400. package/dist/mcp/handlers/task-inference.d.ts +26 -0
  401. package/dist/mcp/handlers/task-inference.js +156 -0
  402. package/dist/mcp/handlers/task-learning-handlers.d.ts +92 -0
  403. package/dist/mcp/handlers/task-learning-handlers.js +230 -0
  404. package/dist/mcp/handlers/task-orchestrate-handler.d.ts +73 -0
  405. package/dist/mcp/handlers/task-orchestrate-handler.js +361 -0
  406. package/dist/mcp/protocol-server.js +12 -2
  407. package/dist/mcp/tools/code-intelligence/analyze.js +3 -6
  408. package/dist/mcp/tools/coverage-analysis/index.d.ts +4 -0
  409. package/dist/mcp/tools/coverage-analysis/index.js +8 -2
  410. package/dist/mcp/tools/visual-accessibility/index.d.ts +7 -0
  411. package/dist/mcp/tools/visual-accessibility/index.js +29 -13
  412. package/dist/shared/events/domain-events.d.ts +2 -0
  413. package/dist/shared/metrics/code-metrics.js +21 -3
  414. package/dist/shared/parsers/typescript-parser.d.ts +6 -0
  415. package/dist/shared/parsers/typescript-parser.js +13 -1
  416. package/package.json +1 -1
  417. package/dist/cli/chunks/adapter-HL7MOCQN.js +0 -2
  418. package/dist/cli/chunks/aqe-learning-engine-OZ2DXB4G.js +0 -2
  419. package/dist/cli/chunks/base-WIM7G3HC.js +0 -2
  420. package/dist/cli/chunks/browser-workflow-QRKCFVR3.js +0 -2
  421. package/dist/cli/chunks/chunk-QSGEBCDB.js +0 -62
  422. package/dist/cli/chunks/chunk-UJNGGFGX.js +0 -2
  423. package/dist/cli/chunks/chunk-VXVTFKRA.js +0 -2
  424. package/dist/cli/chunks/chunk-XCNSGSKV.js +0 -3
  425. package/dist/cli/chunks/client-4PNYDFYS.js +0 -2
  426. package/dist/cli/chunks/core-handlers-ODO6LUWQ.js +0 -2
  427. package/dist/cli/chunks/cross-domain-router-DT4MHJKK.js +0 -2
  428. package/dist/cli/chunks/domain-transfer-L3F6AES2.js +0 -2
  429. package/dist/cli/chunks/dream-QOB3JCOM.js +0 -2
  430. package/dist/cli/chunks/file-discovery-BN76S2PR.js +0 -2
  431. package/dist/cli/chunks/fleet-43YMXACN.js +0 -46
  432. package/dist/cli/chunks/heartbeat-scheduler-3NNP4WCP.js +0 -2
  433. package/dist/cli/chunks/hnsw-adapter-MZR7Y4WF.js +0 -2
  434. package/dist/cli/chunks/hnsw-index-HE4AX22U.js +0 -2
  435. package/dist/cli/chunks/hybrid-backend-IHUHB3Y2.js +0 -2
  436. package/dist/cli/chunks/impact-analyzer-FI6GI6PD.js +0 -2
  437. package/dist/cli/chunks/init-wizard-WLQKH5Y5.js +0 -2
  438. package/dist/cli/chunks/kernel-2WZOQEZS.js +0 -2
  439. package/dist/cli/chunks/knowledge-graph-G3LVKK6P.js +0 -2
  440. package/dist/cli/chunks/llm-router-service-MM75HKWJ.js +0 -2
  441. package/dist/cli/chunks/load-test-BEWEE44J.js +0 -2
  442. package/dist/cli/chunks/memory-backend-NYKBBKZR.js +0 -2
  443. package/dist/cli/chunks/pattern-null-store-QGPUIV6M.js +0 -2
  444. package/dist/cli/chunks/project-root-C7ELXZRK.js +0 -2
  445. package/dist/cli/chunks/protocol-executor-SUVE33BM.js +0 -2
  446. package/dist/cli/chunks/qe-reasoning-bank-YWZMMGJB.js +0 -2
  447. package/dist/cli/chunks/queen-coordinator-ZFAKXRN7.js +0 -2
  448. package/dist/cli/chunks/router-4FTAVYLJ.js +0 -2
  449. package/dist/cli/chunks/routing-feedback-IO2KOWMJ.js +0 -2
  450. package/dist/cli/chunks/rvf-dual-writer-KCIRNE7C.js +0 -2
  451. package/dist/cli/chunks/rvf-migration-adapter-MFC5WTJU.js +0 -2
  452. package/dist/cli/chunks/rvf-native-adapter-I3KWHE7X.js +0 -2
  453. package/dist/cli/chunks/safe-db-QXDZ6QY3.js +0 -2
  454. package/dist/cli/chunks/schedule-CZKD6RIY.js +0 -2
  455. package/dist/cli/chunks/scheduler-BLA3Q4CH.js +0 -2
  456. package/dist/cli/chunks/sqlite-persistence-XIUYDJC4.js +0 -2
  457. package/dist/cli/chunks/task-handler-P6IFLCKP.js +0 -62
  458. package/dist/cli/chunks/task-handlers-DPWMUKFC.js +0 -9
  459. package/dist/cli/chunks/test-runner-process-46IPK3GH.js +0 -2
  460. package/dist/cli/chunks/tree-sitter-wasm-parser-MOI2WWNJ.js +0 -2
  461. package/dist/cli/chunks/unified-memory-FL26RTV3.js +0 -2
  462. package/dist/cli/chunks/unified-memory-hnsw-E2BPTH3U.js +0 -2
  463. package/dist/cli/chunks/unified-persistence-5ZOUPKHF.js +0 -2
  464. package/dist/cli/chunks/visual-security-IJVPO5FA.js +0 -2
  465. package/dist/cli/chunks/witness-chain-5FAFCQKP.js +0 -2
  466. package/dist/cli/chunks/witness-chain-V2M32W5D.js +0 -2
  467. package/dist/cli/chunks/workflow-orchestrator-3JLF3IX7.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.12");process.exit(0)}
2
- import{a as v,b as I,e as O}from"./chunk-W4II6SIH.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-BD5BLNDR.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.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:
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,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.12");process.exit(0)}
2
- import{d as m}from"./chunk-ZROAMFX2.js";import{d as T}from"./chunk-6QRI3JVE.js";T();function p(t,r,o){let e=0,n=t.length;for(;e<n;){let i=e+n>>>1;o(t[i],r)<=0?e=i+1:n=i}return e}function a(t,r,o){let e=p(t,r,o);return t.splice(e,0,r),e}function s(){return(t,r)=>t.createdAt.getTime()-r.createdAt.getTime()}m();export{a,s as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.13");process.exit(0)}
2
+ import{d as m}from"./chunk-KV4T4MXK.js";import{d as T}from"./chunk-DVGRPK7A.js";T();function p(t,r,o){let e=0,n=t.length;for(;e<n;){let i=e+n>>>1;o(t[i],r)<=0?e=i+1:n=i}return e}function a(t,r,o){let e=p(t,r,o);return t.splice(e,0,r),e}function s(){return(t,r)=>t.createdAt.getTime()-r.createdAt.getTime()}m();export{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.12");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.13");process.exit(0)}
2
2
  function l(s,e){let t=s.prepare("SELECT confidence, usage_count, successful_uses FROM qe_patterns WHERE id = ?").get(e.patternId);if(!t)return{updated:!1};let u=e.success?1:0,n=t.usage_count+1,a=t.successful_uses+u,c=a/n,r=Math.min(1,n/100),o=t.confidence*.3+r*.2+c*.5,i=s.prepare(`
3
3
  INSERT INTO qe_pattern_usage (pattern_id, success, metrics_json, feedback)
4
4
  VALUES (?, ?, ?, ?)
@@ -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.12");process.exit(0)}
2
- import{e as g,f as S,s as E,t as _}from"./chunk-NVRYELCY.js";function R(i,e){return{ingest(t){i.ingest(t)},search(t,r){return i.search(t,r).map(s=>({id:s.id,score:s.score}))},delete(t){i.delete(t)},status(){let t=i.status();return{totalVectors:t.totalVectors,dimensions:e,totalSegments:t.totalSegments,fileSizeBytes:t.fileSizeBytes,epoch:t.epoch,witnessValid:t.witnessValid,witnessEntries:t.witnessEntries}},close(){i.close()},compact(){return i.compact()}}}function f(i,e){return(i.prepare("SELECT COUNT(*) as cnt FROM sqlite_master WHERE type='table' AND name=?").get(e)?.cnt??0)>0}function m(i,e,t){return i.prepare(`PRAGMA table_info(${e})`).all().some(s=>s.name===t)}var h=class{db;config;rvfStore=null;rvfAvailable=!1;constructor(e,t){this.db=e,this.config={...t,dimensions:t.dimensions??384},f(this.db,"qe_pattern_embeddings")&&!m(this.db,"qe_pattern_embeddings","space_id")&&(this.db.exec("ALTER TABLE qe_pattern_embeddings ADD COLUMN space_id TEXT"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_qe_pattern_embeddings_space ON qe_pattern_embeddings(space_id)"))}activeSpaceId(){return this.config.embeddingSpaceId??E()?.spaceId}async initialize(){if(this.config.mode==="sqlite-only"){this.rvfAvailable=!1;return}try{let e=await import("./rvf-native-adapter-I3KWHE7X.js");if(!e.isRvfNativeAvailable()){this.rvfAvailable=!1;return}if(this.activeSpaceId()||await _(),!this.activeSpaceId()){this.rvfAvailable=!1,g();return}let{isRvfLockHeldError:t,removeStaleRvfLock:r,quarantineUnusableStore:s}=await import("./rvf-store-integrity-IR33TGQS.js"),l=()=>{try{return{store:e.openRvfStore(this.config.rvfPath),error:null}}catch(o){return{store:null,error:o}}},{store:n,error:a}=l();if(!n&&t(a)&&(!r(this.config.rvfPath)||({store:n,error:a}=l(),!n&&t(a))))throw a;if(!n)try{n=e.createRvfStore(this.config.rvfPath,this.config.dimensions)}catch(o){if({store:n,error:a}=l(),!n){if(t(a))throw a;if(!s(this.config.rvfPath,o instanceof Error?o.message:String(o),a))throw o;n=e.createRvfStore(this.config.rvfPath,this.config.dimensions)}}this.rvfStore=R(n,this.config.dimensions),S(this.config.rvfPath,this.activeSpaceId()??null,this.rvfStore.status().totalVectors),this.rvfAvailable=!0}catch(e){try{this.rvfStore?.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1,console.warn(`[RVF] Dual-writer disabled for ${this.config.rvfPath}; falling back to SQLite: ${e instanceof Error?e.message:String(e)}`)}}setRvfStore(e){this.rvfStore=e,this.rvfAvailable=!0}writePattern(e,t){let r={sqliteSuccess:!1,rvfSuccess:!1};if(!m(this.db,"qe_pattern_embeddings","space_id")||!this.activeSpaceId())return{...r,divergence:"VECTOR_SPACE_UNVERIFIED"};try{this.writeSqliteEmbedding(e,t),r.sqliteSuccess=!0}catch{r.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.ingest([{id:e,vector:t instanceof Float32Array?Array.from(t):t}]),r.rvfSuccess=!0}catch{r.rvfSuccess=!1,r.divergence="rvf-write-failed"}return r}deletePattern(e){let t={sqliteSuccess:!1,rvfSuccess:!1};try{this.deleteSqliteEmbedding(e),t.sqliteSuccess=!0}catch{t.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.delete([e]),t.rvfSuccess=!0}catch{t.rvfSuccess=!1,t.divergence="rvf-delete-failed"}return t}search(e,t){if(!this.hasCompatibleEmbeddingSpace())return[];if(this.config.mode==="rvf-primary"&&this.rvfAvailable&&this.rvfStore)try{return this.rvfStore.search(e,t)}catch{}return this.searchSqlite(e,t)}getDivergenceReport(){let e={totalChecked:0,divergences:0,details:[]},t=this.getSqliteEmbeddingCount();if(e.totalChecked=t,!this.rvfAvailable||!this.rvfStore)return this.config.mode!=="sqlite-only"&&t>0&&(e.divergences=1,e.details.push({patternId:"*",issue:"count-mismatch"})),e;let s=this.rvfStore.status().totalVectors;return t!==s&&(e.divergences=1,e.details.push({patternId:"*",issue:"count-mismatch"})),e}isPromotionSafe(){return this.getDivergenceReport().divergences===0}status(){let e=this.getSqlitePatternCount(),t=this.getSqliteEmbeddingCount(),r=null;if(this.rvfAvailable&&this.rvfStore)try{r=this.rvfStore.status()}catch{r=null}return{sqlite:{patternCount:e,vectorCount:t},rvf:r,mode:this.config.mode}}close(){if(this.rvfStore){try{this.rvfStore.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1}}compact(){if(!this.rvfStore||!this.rvfAvailable||!this.rvfStore.compact)return null;try{return this.rvfStore.compact()??null}catch{return null}}shouldWriteRvf(){return(this.config.mode==="dual-write"||this.config.mode==="rvf-primary")&&this.rvfAvailable&&this.rvfStore!==null}hasCompatibleEmbeddingSpace(){if(!m(this.db,"qe_pattern_embeddings","space_id"))return!1;let e=this.activeSpaceId();return e?(this.db.prepare(`
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{e as g,f as S,s as E,t as _}from"./chunk-WKGTGOYS.js";function R(i,e){return{ingest(t){i.ingest(t)},search(t,r){return i.search(t,r).map(s=>({id:s.id,score:s.score}))},delete(t){i.delete(t)},status(){let t=i.status();return{totalVectors:t.totalVectors,dimensions:e,totalSegments:t.totalSegments,fileSizeBytes:t.fileSizeBytes,epoch:t.epoch,witnessValid:t.witnessValid,witnessEntries:t.witnessEntries}},close(){i.close()},compact(){return i.compact()}}}function f(i,e){return(i.prepare("SELECT COUNT(*) as cnt FROM sqlite_master WHERE type='table' AND name=?").get(e)?.cnt??0)>0}function m(i,e,t){return i.prepare(`PRAGMA table_info(${e})`).all().some(s=>s.name===t)}var h=class{db;config;rvfStore=null;rvfAvailable=!1;constructor(e,t){this.db=e,this.config={...t,dimensions:t.dimensions??384},f(this.db,"qe_pattern_embeddings")&&!m(this.db,"qe_pattern_embeddings","space_id")&&(this.db.exec("ALTER TABLE qe_pattern_embeddings ADD COLUMN space_id TEXT"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_qe_pattern_embeddings_space ON qe_pattern_embeddings(space_id)"))}activeSpaceId(){return this.config.embeddingSpaceId??E()?.spaceId}async initialize(){if(this.config.mode==="sqlite-only"){this.rvfAvailable=!1;return}try{let e=await import("./rvf-native-adapter-D2WWKJIV.js");if(!e.isRvfNativeAvailable()){this.rvfAvailable=!1;return}if(this.activeSpaceId()||await _(),!this.activeSpaceId()){this.rvfAvailable=!1,g();return}let{isRvfLockHeldError:t,removeStaleRvfLock:r,quarantineUnusableStore:s}=await import("./rvf-store-integrity-KKC6HOJD.js"),l=()=>{try{return{store:e.openRvfStore(this.config.rvfPath),error:null}}catch(o){return{store:null,error:o}}},{store:n,error:a}=l();if(!n&&t(a)&&(!r(this.config.rvfPath)||({store:n,error:a}=l(),!n&&t(a))))throw a;if(!n)try{n=e.createRvfStore(this.config.rvfPath,this.config.dimensions)}catch(o){if({store:n,error:a}=l(),!n){if(t(a))throw a;if(!s(this.config.rvfPath,o instanceof Error?o.message:String(o),a))throw o;n=e.createRvfStore(this.config.rvfPath,this.config.dimensions)}}this.rvfStore=R(n,this.config.dimensions),S(this.config.rvfPath,this.activeSpaceId()??null,this.rvfStore.status().totalVectors),this.rvfAvailable=!0}catch(e){try{this.rvfStore?.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1,console.warn(`[RVF] Dual-writer disabled for ${this.config.rvfPath}; falling back to SQLite: ${e instanceof Error?e.message:String(e)}`)}}setRvfStore(e){this.rvfStore=e,this.rvfAvailable=!0}writePattern(e,t){let r={sqliteSuccess:!1,rvfSuccess:!1};if(!m(this.db,"qe_pattern_embeddings","space_id")||!this.activeSpaceId())return{...r,divergence:"VECTOR_SPACE_UNVERIFIED"};try{this.writeSqliteEmbedding(e,t),r.sqliteSuccess=!0}catch{r.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.ingest([{id:e,vector:t instanceof Float32Array?Array.from(t):t}]),r.rvfSuccess=!0}catch{r.rvfSuccess=!1,r.divergence="rvf-write-failed"}return r}deletePattern(e){let t={sqliteSuccess:!1,rvfSuccess:!1};try{this.deleteSqliteEmbedding(e),t.sqliteSuccess=!0}catch{t.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.delete([e]),t.rvfSuccess=!0}catch{t.rvfSuccess=!1,t.divergence="rvf-delete-failed"}return t}search(e,t){if(!this.hasCompatibleEmbeddingSpace())return[];if(this.config.mode==="rvf-primary"&&this.rvfAvailable&&this.rvfStore)try{return this.rvfStore.search(e,t)}catch{}return this.searchSqlite(e,t)}getDivergenceReport(){let e={totalChecked:0,divergences:0,details:[]},t=this.getSqliteEmbeddingCount();if(e.totalChecked=t,!this.rvfAvailable||!this.rvfStore)return this.config.mode!=="sqlite-only"&&t>0&&(e.divergences=1,e.details.push({patternId:"*",issue:"count-mismatch"})),e;let s=this.rvfStore.status().totalVectors;return t!==s&&(e.divergences=1,e.details.push({patternId:"*",issue:"count-mismatch"})),e}isPromotionSafe(){return this.getDivergenceReport().divergences===0}status(){let e=this.getSqlitePatternCount(),t=this.getSqliteEmbeddingCount(),r=null;if(this.rvfAvailable&&this.rvfStore)try{r=this.rvfStore.status()}catch{r=null}return{sqlite:{patternCount:e,vectorCount:t},rvf:r,mode:this.config.mode}}close(){if(this.rvfStore){try{this.rvfStore.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1}}compact(){if(!this.rvfStore||!this.rvfAvailable||!this.rvfStore.compact)return null;try{return this.rvfStore.compact()??null}catch{return null}}shouldWriteRvf(){return(this.config.mode==="dual-write"||this.config.mode==="rvf-primary")&&this.rvfAvailable&&this.rvfStore!==null}hasCompatibleEmbeddingSpace(){if(!m(this.db,"qe_pattern_embeddings","space_id"))return!1;let e=this.activeSpaceId();return e?(this.db.prepare(`
3
3
  SELECT COUNT(*) AS incompatible
4
4
  FROM qe_pattern_embeddings
5
5
  WHERE space_id IS NULL OR space_id <> ?
@@ -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.12");process.exit(0)}
2
- var e=null,f=null,t=null,u=!1;async function W(){return u&&!t?e:t||(t=(async()=>{try{if(process.env.AQE_RVF_MODE==="sqlite-only"||process.env.AQE_MEMORY_BACKEND==="memory")return null;let{isRvfNativeAvailable:d}=await import("./rvf-native-adapter-I3KWHE7X.js");if(!d())return null;let{getUnifiedMemory:v,findProjectRoot:p}=await import("./unified-memory-FL26RTV3.js"),o=v().getDatabase();if(!o)return null;let{join:m}=await import("node:path"),g=m(process.env.AQE_PROJECT_ROOT??p(),".agentic-qe","brain.rvf"),{RvfDualWriter:R}=await import("./rvf-dual-writer-KCIRNE7C.js"),l=new R(o,{rvfPath:g,mode:"dual-write",dimensions:384});await l.initialize(),e=l;try{let{getRvfMigrationStage:y}=await import("./feature-flags-DKXMDVPE.js"),a=y();if(a>=2){let{RvfMigrationAdapter:A}=await import("./rvf-migration-adapter-MFC5WTJU.js"),s=new A({stage:a});s.setSqliteDb(o);let{getSharedRvfAdapter:D}=await import("./shared-rvf-adapter-SIZMEHPM.js"),i=D();if(i){let h={ingest:n=>i.ingest(n),search:(n,M)=>i.search(n,M).map(c=>({id:c.id,score:c.score})),delete:n=>i.delete(n),status:()=>i.status(),close:()=>{}};s.setRvfStore(h)}f=s,console.log(`[RVF] Migration adapter active at stage ${a} (${["sqlite-only","hybrid","dual-sqlite","dual-rvf","rvf-primary"][a]})`)}}catch{}return l}catch(r){return(process.env.DEBUG||process.env.AQE_VERBOSE)&&console.debug("[RVF] Dual-writer init failed, degrading to sqlite-only:",r instanceof Error?r.message:r),null}finally{u=!0,t=null,import("./base-WIM7G3HC.js").then(({registerRvfResetFn:r})=>r(w)).catch(()=>{})}})(),t)}function S(){return e}function b(){return f}function w(){if(e){try{e.close()}catch{}e=null}f=null,t=null,u=!1}export{W as a,S as b,b as c,w as d};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.13");process.exit(0)}
2
+ var e=null,f=null,t=null,u=!1;async function W(){return u&&!t?e:t||(t=(async()=>{try{if(process.env.AQE_RVF_MODE==="sqlite-only"||process.env.AQE_MEMORY_BACKEND==="memory")return null;let{isRvfNativeAvailable:d}=await import("./rvf-native-adapter-D2WWKJIV.js");if(!d())return null;let{getUnifiedMemory:v,findProjectRoot:p}=await import("./unified-memory-TLGSSLMI.js"),o=v().getDatabase();if(!o)return null;let{join:m}=await import("node:path"),g=m(process.env.AQE_PROJECT_ROOT??p(),".agentic-qe","brain.rvf"),{RvfDualWriter:R}=await import("./rvf-dual-writer-FRYZH3WZ.js"),l=new R(o,{rvfPath:g,mode:"dual-write",dimensions:384});await l.initialize(),e=l;try{let{getRvfMigrationStage:y}=await import("./feature-flags-N7EOGE5P.js"),a=y();if(a>=2){let{RvfMigrationAdapter:A}=await import("./rvf-migration-adapter-XXNITL5I.js"),s=new A({stage:a});s.setSqliteDb(o);let{getSharedRvfAdapter:D}=await import("./shared-rvf-adapter-COUOS665.js"),i=D();if(i){let h={ingest:n=>i.ingest(n),search:(n,M)=>i.search(n,M).map(c=>({id:c.id,score:c.score})),delete:n=>i.delete(n),status:()=>i.status(),close:()=>{}};s.setRvfStore(h)}f=s,console.log(`[RVF] Migration adapter active at stage ${a} (${["sqlite-only","hybrid","dual-sqlite","dual-rvf","rvf-primary"][a]})`)}}catch{}return l}catch(r){return(process.env.DEBUG||process.env.AQE_VERBOSE)&&console.debug("[RVF] Dual-writer init failed, degrading to sqlite-only:",r instanceof Error?r.message:r),null}finally{u=!0,t=null,import("./base-WCACU3FN.js").then(({registerRvfResetFn:r})=>r(w)).catch(()=>{})}})(),t)}function S(){return e}function b(){return f}function w(){if(e){try{e.close()}catch{}e=null}f=null,t=null,u=!1}export{W as a,S as b,b as c,w 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.12");process.exit(0)}
2
- import{a as _}from"./chunk-DAUEK66C.js";import{a as w}from"./chunk-RYHG3I7J.js";import{d as k,f as q}from"./chunk-TGMXUZZC.js";import{r as M,v as U}from"./chunk-L7NGKANW.js";import{b as f,d as P}from"./chunk-WTAUF6O4.js";import{a as g,e as F}from"./chunk-W4II6SIH.js";import{a as R}from"./chunk-WDEXOLK2.js";import{randomUUID as Q}from"crypto";U();P();F();var x={alpha:.1,minOutcomes:10,weightFloor:.2,weightCeiling:2},p=class{records=new Map;config;constructor(e){this.config={...x,...e}}recordOutcome(e,t,o){let{alpha:i,minOutcomes:r,weightFloor:s,weightCeiling:n}=this.config,c=this.records.get(e),d=t?1:0,a=Math.max(0,Math.min(1,o)),l,u;c?(l=i*d+(1-i)*c.emaAccuracy,u=i*a+(1-i)*c.emaQuality):(l=d,u=a);let h=(c?.totalOutcomes??0)+1,C;h>=r?C=Math.max(s,Math.min(n,l*2)):C=1;let S={agentId:e,emaAccuracy:l,emaQuality:u,calibratedWeight:C,totalOutcomes:h,lastUpdated:new Date};return this.records.set(e,S),S}getCalibration(e){return this.records.get(e)??null}getCalibratedWeight(e){let t=this.records.get(e);return!t||t.totalOutcomes<this.config.minOutcomes?1:t.calibratedWeight}getAllCalibrations(){return Array.from(this.records.values())}reset(e){e!==void 0?this.records.delete(e):this.records.clear()}serialize(){let e=Object.create(null);for(let[t,o]of this.records)e[t]={...o};return e}deserialize(e){this.records.clear();for(let[t,o]of Object.entries(e))this.records.set(t,{...o,lastUpdated:new Date(o.lastUpdated)})}};var D={escalateAfterFailures:2,deEscalateAfterSuccesses:5,maxTier:"opus",minTier:"haiku"},I=["booster","haiku","sonnet","opus"],b=class{config;tierOrder;states=new Map;constructor(e){this.config={...D,...e},this.tierOrder=this.config.tierOrder??I}tierIndex(e){return this.tierOrder.indexOf(e)}recordOutcome(e,t,o){let i=this.states.get(e);i||(i={agentId:e,currentTier:o,baseTier:o,consecutiveFailures:0,consecutiveSuccesses:0,escalationCount:0,deEscalationCount:0,lastAction:"none",lastActionTimestamp:new Date},this.states.set(e,i));let r=i.currentTier;if(t){if(i.consecutiveSuccesses++,i.consecutiveFailures=0,i.consecutiveSuccesses>=this.config.deEscalateAfterSuccesses){let s=this.tierIndex(i.currentTier),n=this.tierIndex(this.config.minTier);if(s>n)return i.currentTier=this.tierOrder[s-1],i.deEscalationCount++,i.consecutiveSuccesses=0,i.lastAction="de-escalate",i.lastActionTimestamp=new Date,{action:"de-escalate",previousTier:r,newTier:i.currentTier}}}else if(i.consecutiveFailures++,i.consecutiveSuccesses=0,i.consecutiveFailures>=this.config.escalateAfterFailures){let s=this.tierIndex(i.currentTier),n=this.tierIndex(this.config.maxTier);if(s>=0&&s<n)return i.currentTier=this.tierOrder[s+1],i.escalationCount++,i.consecutiveFailures=0,i.lastAction="escalate",i.lastActionTimestamp=new Date,{action:"escalate",previousTier:r,newTier:i.currentTier}}return{action:"none",previousTier:r,newTier:i.currentTier}}getCurrentTier(e){return this.states.get(e)?.currentTier??null}getState(e){return this.states.get(e)??null}getAllStates(){return Array.from(this.states.values())}reset(e){e?this.states.delete(e):this.states.clear()}};var T={booster:{avgInputTokens:0,avgOutputTokens:0,costPerTask:0},haiku:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.0035},sonnet:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.021},opus:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.105}},v=["booster","haiku","sonnet","opus"],y=T.opus.costPerTask,L={qualityWeight:.6,costWeight:.4,budgetPerHourUsd:0,budgetPerDayUsd:0,minQualityThreshold:.5,enabled:!0},N=.15,E=class{config;costTracker;tierQualityEstimates=new Map;tierOutcomeCounts=new Map;constructor(e,t){let o={...L,...t};o.qualityWeight=Math.max(0,Math.min(1,o.qualityWeight)),o.costWeight=Math.max(0,Math.min(1,o.costWeight)),o.minQualityThreshold=Math.max(0,Math.min(1,o.minQualityThreshold)),o.budgetPerHourUsd=Math.max(0,o.budgetPerHourUsd),o.budgetPerDayUsd=Math.max(0,o.budgetPerDayUsd);let i=o.qualityWeight+o.costWeight;i>0&&i!==1&&(o.qualityWeight/=i,o.costWeight/=i),this.config=o,this.costTracker=e,this.tierQualityEstimates.set("booster",.3),this.tierQualityEstimates.set("haiku",.55),this.tierQualityEstimates.set("sonnet",.75),this.tierQualityEstimates.set("opus",.9)}scoreTiers(e){let t=v.map(o=>{let i=this.getQualityEstimate(o,e),r=T[o].costPerTask,s=r>0?i/r:i>0?1/0:0,n=y>0?1-r/y:1,c=this.config.qualityWeight*i+this.config.costWeight*n;return{tier:o,qualityScore:i,estimatedCostUsd:r,qualityPerDollar:s,economicScore:c}});return t.sort((o,i)=>i.economicScore-o.economicScore),t}selectTier(e){let t=this.scoreTiers(e);for(let r of t)if(!(r.qualityScore<this.config.minQualityThreshold)&&!this.wouldExceedBudget(r.tier))return{tier:r.tier,reason:`Best economic score (${r.economicScore.toFixed(3)}): quality=${r.qualityScore.toFixed(2)}, cost=$${r.estimatedCostUsd.toFixed(4)}`,scores:t};let o=t.filter(r=>r.qualityScore>=this.config.minQualityThreshold);if(o.length>0){let r=[...o].sort((s,n)=>s.estimatedCostUsd-n.estimatedCostUsd)[0];return{tier:r.tier,reason:`Budget constrained fallback to ${r.tier}`,scores:t}}let i=[...t].sort((r,s)=>s.qualityScore-r.qualityScore)[0];return{tier:i.tier,reason:`No tier meets quality threshold ${this.config.minQualityThreshold}; using best quality: ${i.tier}`,scores:t}}wouldExceedBudget(e){let t=T[e].costPerTask;if(t===0)return!1;let o=this.costTracker.getCurrentCost("hour"),i=this.costTracker.getCurrentCost("day");return this.config.budgetPerHourUsd>0&&o+t>this.config.budgetPerHourUsd||this.config.budgetPerDayUsd>0&&i+t>this.config.budgetPerDayUsd}updateFromOutcome(e,t){let o=e.outcome.qualityScore,i=this.tierQualityEstimates.get(t)??.5,r=this.tierOutcomeCounts.get(t)??0,s=r<5?.4:N,n=i*(1-s)+o*s;this.tierQualityEstimates.set(t,n),this.tierOutcomeCounts.set(t,r+1)}getEconomicReport(){let e=this.scoreTiers(.5),t=this.costTracker.getCurrentCost("hour"),o=this.costTracker.getCurrentCost("day"),i={hourly:this.config.budgetPerHourUsd>0?Math.max(0,this.config.budgetPerHourUsd-t):null,daily:this.config.budgetPerDayUsd>0?Math.max(0,this.config.budgetPerDayUsd-o):null},r=null,s=[...e].sort((a,l)=>l.qualityPerDollar-a.qualityPerDollar),n=s.find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar)),c=[...s].reverse().find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar));if(n&&c&&n.tier!==c.tier){let a=c.estimatedCostUsd-n.estimatedCostUsd;a>0&&(r={usd:a,description:`Switch from ${c.tier} ($${c.estimatedCostUsd.toFixed(4)}/task) to ${n.tier} ($${n.estimatedCostUsd.toFixed(4)}/task) for comparable tasks to save ~$${a.toFixed(4)}/task`})}let d=this.generateRecommendation(e,i);return{tierEfficiency:e,currentHourlyCostUsd:t,currentDailyCostUsd:o,budgetRemaining:i,recommendation:d,savingsOpportunity:r}}computeCostAdjustedReward(e,t,o){let i=T[t].costPerTask;if(y===0)return e;let r=i/y,s=Math.max(0,o-this.config.minQualityThreshold),n=r*(1-s),c=e-n*this.config.costWeight;return Math.max(-1,Math.min(1,c))}serializeEstimates(){let e={};for(let t of v)e[t]={quality:this.tierQualityEstimates.get(t)??.5,count:this.tierOutcomeCounts.get(t)??0};return e}deserializeEstimates(e){for(let t of v)e[t]&&(this.tierQualityEstimates.set(t,e[t].quality),this.tierOutcomeCounts.set(t,e[t].count))}getConfig(){return{...this.config}}getQualityEstimate(e,t){let o=this.tierQualityEstimates.get(e)??.5,i=e==="booster"?t*.4:e==="haiku"?t*.2:0;return Math.max(0,Math.min(1,o-i))}generateRecommendation(e,t){if(t.hourly!==null&&t.hourly<.01)return"Hourly budget nearly exhausted. Consider increasing budget or routing to cheaper tiers.";if(t.daily!==null&&t.daily<.1)return"Daily budget nearly exhausted. Only critical tasks should use expensive tiers.";let o=e[0];return o?`Most cost-efficient tier: ${o.tier} (score=${o.economicScore.toFixed(3)}, quality=${o.qualityScore.toFixed(2)})`:"No economic data available yet."}};q();var A=class{outcomes=[];maxOutcomes;constructor(e=1e4){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getByAgent(e,t=100){return this.outcomes.filter(o=>o.usedAgent===e).slice(-t)}getAll(e=1e3){return this.outcomes.slice(-e)}getRecentOverrides(e=50){return this.outcomes.filter(t=>!t.followedRecommendation).slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},O=class m{static schemaMigrated=!1;outcomeStore;router=null;db=null;calibrator=null;escalationTracker=null;economicModel=null;economicPersistCounter=0;static ECONOMIC_PERSIST_INTERVAL=10;persistCount=0;maxOutcomes;static RETENTION_CLEANUP_INTERVAL=100;constructor(e=1e4,t){this.maxOutcomes=e,this.outcomeStore=new A(e),t?.enableEMACalibration&&this.enableCalibration(),t?.enableAutoEscalation&&this.enableAutoEscalation()}async initialize(){try{this.db=M(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb(),this.loadCalibratorState()}catch(e){console.warn("[RoutingFeedbackCollector] DB init failed, using memory-only:",g(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().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.13");process.exit(0)}
2
+ import{a as _}from"./chunk-VRHRBAEM.js";import{a as w}from"./chunk-IJUHSJ2U.js";import{d as k,f as q}from"./chunk-PHP5UBT4.js";import{r as M,v as U}from"./chunk-3Y7TJFHU.js";import{b as f,d as P}from"./chunk-VTOBUZL6.js";import{a as g,e as F}from"./chunk-3Y2ROSCL.js";import{a as R}from"./chunk-ZAKQLAHT.js";import{randomUUID as Q}from"crypto";U();P();F();var x={alpha:.1,minOutcomes:10,weightFloor:.2,weightCeiling:2},p=class{records=new Map;config;constructor(e){this.config={...x,...e}}recordOutcome(e,t,o){let{alpha:i,minOutcomes:r,weightFloor:s,weightCeiling:n}=this.config,c=this.records.get(e),d=t?1:0,a=Math.max(0,Math.min(1,o)),l,u;c?(l=i*d+(1-i)*c.emaAccuracy,u=i*a+(1-i)*c.emaQuality):(l=d,u=a);let h=(c?.totalOutcomes??0)+1,C;h>=r?C=Math.max(s,Math.min(n,l*2)):C=1;let S={agentId:e,emaAccuracy:l,emaQuality:u,calibratedWeight:C,totalOutcomes:h,lastUpdated:new Date};return this.records.set(e,S),S}getCalibration(e){return this.records.get(e)??null}getCalibratedWeight(e){let t=this.records.get(e);return!t||t.totalOutcomes<this.config.minOutcomes?1:t.calibratedWeight}getAllCalibrations(){return Array.from(this.records.values())}reset(e){e!==void 0?this.records.delete(e):this.records.clear()}serialize(){let e=Object.create(null);for(let[t,o]of this.records)e[t]={...o};return e}deserialize(e){this.records.clear();for(let[t,o]of Object.entries(e))this.records.set(t,{...o,lastUpdated:new Date(o.lastUpdated)})}};var D={escalateAfterFailures:2,deEscalateAfterSuccesses:5,maxTier:"opus",minTier:"haiku"},I=["booster","haiku","sonnet","opus"],b=class{config;tierOrder;states=new Map;constructor(e){this.config={...D,...e},this.tierOrder=this.config.tierOrder??I}tierIndex(e){return this.tierOrder.indexOf(e)}recordOutcome(e,t,o){let i=this.states.get(e);i||(i={agentId:e,currentTier:o,baseTier:o,consecutiveFailures:0,consecutiveSuccesses:0,escalationCount:0,deEscalationCount:0,lastAction:"none",lastActionTimestamp:new Date},this.states.set(e,i));let r=i.currentTier;if(t){if(i.consecutiveSuccesses++,i.consecutiveFailures=0,i.consecutiveSuccesses>=this.config.deEscalateAfterSuccesses){let s=this.tierIndex(i.currentTier),n=this.tierIndex(this.config.minTier);if(s>n)return i.currentTier=this.tierOrder[s-1],i.deEscalationCount++,i.consecutiveSuccesses=0,i.lastAction="de-escalate",i.lastActionTimestamp=new Date,{action:"de-escalate",previousTier:r,newTier:i.currentTier}}}else if(i.consecutiveFailures++,i.consecutiveSuccesses=0,i.consecutiveFailures>=this.config.escalateAfterFailures){let s=this.tierIndex(i.currentTier),n=this.tierIndex(this.config.maxTier);if(s>=0&&s<n)return i.currentTier=this.tierOrder[s+1],i.escalationCount++,i.consecutiveFailures=0,i.lastAction="escalate",i.lastActionTimestamp=new Date,{action:"escalate",previousTier:r,newTier:i.currentTier}}return{action:"none",previousTier:r,newTier:i.currentTier}}getCurrentTier(e){return this.states.get(e)?.currentTier??null}getState(e){return this.states.get(e)??null}getAllStates(){return Array.from(this.states.values())}reset(e){e?this.states.delete(e):this.states.clear()}};var T={booster:{avgInputTokens:0,avgOutputTokens:0,costPerTask:0},haiku:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.0035},sonnet:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.021},opus:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.105}},v=["booster","haiku","sonnet","opus"],y=T.opus.costPerTask,L={qualityWeight:.6,costWeight:.4,budgetPerHourUsd:0,budgetPerDayUsd:0,minQualityThreshold:.5,enabled:!0},N=.15,E=class{config;costTracker;tierQualityEstimates=new Map;tierOutcomeCounts=new Map;constructor(e,t){let o={...L,...t};o.qualityWeight=Math.max(0,Math.min(1,o.qualityWeight)),o.costWeight=Math.max(0,Math.min(1,o.costWeight)),o.minQualityThreshold=Math.max(0,Math.min(1,o.minQualityThreshold)),o.budgetPerHourUsd=Math.max(0,o.budgetPerHourUsd),o.budgetPerDayUsd=Math.max(0,o.budgetPerDayUsd);let i=o.qualityWeight+o.costWeight;i>0&&i!==1&&(o.qualityWeight/=i,o.costWeight/=i),this.config=o,this.costTracker=e,this.tierQualityEstimates.set("booster",.3),this.tierQualityEstimates.set("haiku",.55),this.tierQualityEstimates.set("sonnet",.75),this.tierQualityEstimates.set("opus",.9)}scoreTiers(e){let t=v.map(o=>{let i=this.getQualityEstimate(o,e),r=T[o].costPerTask,s=r>0?i/r:i>0?1/0:0,n=y>0?1-r/y:1,c=this.config.qualityWeight*i+this.config.costWeight*n;return{tier:o,qualityScore:i,estimatedCostUsd:r,qualityPerDollar:s,economicScore:c}});return t.sort((o,i)=>i.economicScore-o.economicScore),t}selectTier(e){let t=this.scoreTiers(e);for(let r of t)if(!(r.qualityScore<this.config.minQualityThreshold)&&!this.wouldExceedBudget(r.tier))return{tier:r.tier,reason:`Best economic score (${r.economicScore.toFixed(3)}): quality=${r.qualityScore.toFixed(2)}, cost=$${r.estimatedCostUsd.toFixed(4)}`,scores:t};let o=t.filter(r=>r.qualityScore>=this.config.minQualityThreshold);if(o.length>0){let r=[...o].sort((s,n)=>s.estimatedCostUsd-n.estimatedCostUsd)[0];return{tier:r.tier,reason:`Budget constrained fallback to ${r.tier}`,scores:t}}let i=[...t].sort((r,s)=>s.qualityScore-r.qualityScore)[0];return{tier:i.tier,reason:`No tier meets quality threshold ${this.config.minQualityThreshold}; using best quality: ${i.tier}`,scores:t}}wouldExceedBudget(e){let t=T[e].costPerTask;if(t===0)return!1;let o=this.costTracker.getCurrentCost("hour"),i=this.costTracker.getCurrentCost("day");return this.config.budgetPerHourUsd>0&&o+t>this.config.budgetPerHourUsd||this.config.budgetPerDayUsd>0&&i+t>this.config.budgetPerDayUsd}updateFromOutcome(e,t){let o=e.outcome.qualityScore,i=this.tierQualityEstimates.get(t)??.5,r=this.tierOutcomeCounts.get(t)??0,s=r<5?.4:N,n=i*(1-s)+o*s;this.tierQualityEstimates.set(t,n),this.tierOutcomeCounts.set(t,r+1)}getEconomicReport(){let e=this.scoreTiers(.5),t=this.costTracker.getCurrentCost("hour"),o=this.costTracker.getCurrentCost("day"),i={hourly:this.config.budgetPerHourUsd>0?Math.max(0,this.config.budgetPerHourUsd-t):null,daily:this.config.budgetPerDayUsd>0?Math.max(0,this.config.budgetPerDayUsd-o):null},r=null,s=[...e].sort((a,l)=>l.qualityPerDollar-a.qualityPerDollar),n=s.find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar)),c=[...s].reverse().find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar));if(n&&c&&n.tier!==c.tier){let a=c.estimatedCostUsd-n.estimatedCostUsd;a>0&&(r={usd:a,description:`Switch from ${c.tier} ($${c.estimatedCostUsd.toFixed(4)}/task) to ${n.tier} ($${n.estimatedCostUsd.toFixed(4)}/task) for comparable tasks to save ~$${a.toFixed(4)}/task`})}let d=this.generateRecommendation(e,i);return{tierEfficiency:e,currentHourlyCostUsd:t,currentDailyCostUsd:o,budgetRemaining:i,recommendation:d,savingsOpportunity:r}}computeCostAdjustedReward(e,t,o){let i=T[t].costPerTask;if(y===0)return e;let r=i/y,s=Math.max(0,o-this.config.minQualityThreshold),n=r*(1-s),c=e-n*this.config.costWeight;return Math.max(-1,Math.min(1,c))}serializeEstimates(){let e={};for(let t of v)e[t]={quality:this.tierQualityEstimates.get(t)??.5,count:this.tierOutcomeCounts.get(t)??0};return e}deserializeEstimates(e){for(let t of v)e[t]&&(this.tierQualityEstimates.set(t,e[t].quality),this.tierOutcomeCounts.set(t,e[t].count))}getConfig(){return{...this.config}}getQualityEstimate(e,t){let o=this.tierQualityEstimates.get(e)??.5,i=e==="booster"?t*.4:e==="haiku"?t*.2:0;return Math.max(0,Math.min(1,o-i))}generateRecommendation(e,t){if(t.hourly!==null&&t.hourly<.01)return"Hourly budget nearly exhausted. Consider increasing budget or routing to cheaper tiers.";if(t.daily!==null&&t.daily<.1)return"Daily budget nearly exhausted. Only critical tasks should use expensive tiers.";let o=e[0];return o?`Most cost-efficient tier: ${o.tier} (score=${o.economicScore.toFixed(3)}, quality=${o.qualityScore.toFixed(2)})`:"No economic data available yet."}};q();var A=class{outcomes=[];maxOutcomes;constructor(e=1e4){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getByAgent(e,t=100){return this.outcomes.filter(o=>o.usedAgent===e).slice(-t)}getAll(e=1e3){return this.outcomes.slice(-e)}getRecentOverrides(e=50){return this.outcomes.filter(t=>!t.followedRecommendation).slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},O=class m{static schemaMigrated=!1;outcomeStore;router=null;db=null;calibrator=null;escalationTracker=null;economicModel=null;economicPersistCounter=0;static ECONOMIC_PERSIST_INTERVAL=10;persistCount=0;maxOutcomes;static RETENTION_CLEANUP_INTERVAL=100;constructor(e=1e4,t){this.maxOutcomes=e,this.outcomeStore=new A(e),t?.enableEMACalibration&&this.enableCalibration(),t?.enableAutoEscalation&&this.enableAutoEscalation()}async initialize(){try{this.db=M(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb(),this.loadCalibratorState()}catch(e){console.warn("[RoutingFeedbackCollector] DB init failed, using memory-only:",g(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
3
3
  SELECT * FROM routing_outcomes ORDER BY created_at DESC LIMIT ?
4
4
  `).all(this.maxOutcomes);for(let o of t.reverse()){let i={id:o.id,task:f(o.task_json),decision:f(o.decision_json),usedAgent:o.used_agent,followedRecommendation:!!o.followed_recommendation,outcome:{success:!!o.success,qualityScore:o.quality_score,durationMs:o.duration_ms,error:o.error||void 0},timestamp:new Date(o.created_at),advisorConsultation:o.advisor_consultation_json?f(o.advisor_consultation_json):void 0};this.outcomeStore.add(i)}t.length>0&&console.log(`[RoutingFeedbackCollector] Loaded ${t.length} outcomes from DB`)}persistOutcome(e){if(this.db)try{let t=this.db.getDatabase();if(!m.schemaMigrated){for(let r of["ALTER TABLE routing_outcomes ADD COLUMN model_tier TEXT","ALTER TABLE routing_outcomes ADD COLUMN advisor_consultation_json TEXT"])try{t.prepare(r).run()}catch{}_(t),m.schemaMigrated=!0}let o=this.inferTier(e.usedAgent),i=e.advisorConsultation?JSON.stringify(e.advisorConsultation):null;t.prepare(`
5
5
  INSERT OR REPLACE INTO routing_outcomes (
@@ -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.12");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.13");process.exit(0)}
2
2
  import{existsSync as u,readdirSync as l}from"fs";import{join as i}from"path";var f=".agentic-qe",o=".claude";function x(s,t,a){return t===f?!0:t===o?a||u(i(s,f)):!1}function d(s,t=[],a=12){let y=new Set(t),g=[],m=(r,e,c)=>{if(u(i(r,o))&&(c===0||u(i(r,f)))&&g.push(e?`${e}/${o}`:o),c>=a)return;let p;try{p=l(r,{withFileTypes:!0})}catch{return}for(let n of p)!n.isDirectory()||n.name.startsWith(".")||y.has(n.name)||m(i(r,n.name),e?`${e}/${n.name}`:n.name,c+1)};return m(s,"",0),g}export{f as a,o as b,x as c,d};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.12");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.13");process.exit(0)}
2
2
  var i=class{s0;s1;s2;s3;constructor(s){this.s0=this.splitmix32(s),this.s1=this.splitmix32(this.s0),this.s2=this.splitmix32(this.s1),this.s3=this.splitmix32(this.s2)}splitmix32(s){return s=s+2654435769|0,s=Math.imul(s^s>>>16,2246822507),s=Math.imul(s^s>>>13,3266489909),(s^s>>>16)>>>0}next(){let s=this.s3,t=this.s0;return this.s3=this.s2,this.s2=this.s1,this.s1=t,t^=t<<11,t^=t>>>8,this.s0=t^s^s>>>19,this.s0>>>0}nextFloat(){return this.next()/4294967296}nextGaussian(){let s=this.nextFloat()||1e-10,t=this.nextFloat();return Math.sqrt(-2*Math.log(s))*Math.cos(2*Math.PI*t)}};export{i 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.12");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.13");process.exit(0)}
2
2
  import{readFileSync as R,existsSync as v,readdirSync as y}from"fs";import{join as S}from"path";var M=100*1024,b=/mcp__([a-z][a-z0-9-]*)__([a-z][a-z0-9_]*)/g,x=/^```/;function w(e,r){let n=e.length>M?e.slice(0,M):e,o=[],i=n.split(`
3
3
  `),a=!1;for(let s=0;s<i.length;s++){let p=i[s];if(x.test(p.trim())){a=!a;continue}let l,c=new RegExp(b.source,"g");for(;(l=c.exec(p))!==null;){let t=l[1],g=l[2],f=l[0],d=a?"code-block":"prose",u=d==="prose"?.9:.5;o.push({toolName:f,serverName:t,actionName:g,confidence:u,context:d,lineNumber:s+1})}}return o}function E(e){let r=new Map;for(let n of e)r.has(n.serverName)||r.set(n.serverName,[]),r.get(n.serverName).push(n);return r}function N(e){let r=[],n=[S(e,".claude","mcp.json"),S(e,".mcp.json")],o=process.env.HOME||process.env.USERPROFILE||"";o&&n.push(S(o,".claude","mcp.json"));for(let i of n)if(v(i))try{let a=R(i,"utf-8"),s=JSON.parse(a);s.mcpServers&&typeof s.mcpServers=="object"&&r.push(...Object.keys(s.mcpServers))}catch{}return[...new Set(r)]}function h(e,r,n){if(!v(e))return{agentName:r,references:[],requiredServers:[],availableServers:n,missingServers:[],warnings:[`Agent file not found: ${e}`],allSatisfied:!0};let o;try{o=R(e,"utf-8")}catch{return{agentName:r,references:[],requiredServers:[],availableServers:n,missingServers:[],warnings:[`Failed to read agent file: ${e}`],allSatisfied:!0}}let i=w(o,r),a=E(i),s=[...a.keys()],p=new Set(n),l=s.filter(t=>!p.has(t)),c=[];for(let t of l){let g=a.get(t)||[],f=Math.max(...g.map(m=>m.confidence)),d=g.length,u=[...new Set(g.map(m=>m.context))].join(", ");c.push(`[advisory] Agent "${r}" references MCP server "${t}" (${d} tool ref${d>1?"s":""}, confidence: ${f}, context: ${u}) but server is not configured. Agent may have reduced capabilities.`)}return{agentName:r,references:i,requiredServers:s,availableServers:n,missingServers:l,warnings:c,allSatisfied:l.length===0}}function C(e,r){let n=Date.now(),o=[],i=[],a=N(r);if(!v(e))return{agents:[],totalServersReferenced:0,globalMissingServers:[],agentsWithMissingDeps:[],warnings:[`Agents directory not found: ${e}`],durationMs:Date.now()-n};try{let c=y(e);for(let g of c){if(!g.endsWith(".md"))continue;let f=g.replace(".md",""),d=S(e,g),u=h(d,f,a);o.push(u),i.push(...u.warnings)}let t=S(e,"subagents");if(v(t)){let g=y(t);for(let f of g){if(!f.endsWith(".md"))continue;let d=f.replace(".md",""),u=S(t,f),m=h(u,d,a);o.push(m),i.push(...m.warnings)}}}catch(c){i.push(`Error scanning agents directory: ${c.message}`)}let s=new Set,p=new Set,l=[];for(let c of o){for(let t of c.requiredServers)s.add(t);for(let t of c.missingServers)p.add(t);c.missingServers.length>0&&l.push(c.agentName)}return{agents:o,totalServersReferenced:s.size,globalMissingServers:[...p],agentsWithMissingDeps:l,warnings:i,durationMs:Date.now()-n}}export{N as a,C as b};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.12");process.exit(0)}
2
- import{o as c,r as d,v as f}from"./chunk-L7NGKANW.js";import{a as r,e as p}from"./chunk-YUA6ZKKY.js";import{a as h}from"./chunk-UJNGGFGX.js";import{c as l}from"./chunk-ADUAJIAU.js";f();p();h();import*as m from"path";var u=l.create("hybrid-backend"),s=class{unifiedMemory=null;config;cleanupInterval;cleanupCount=0;initialized=!1;constructor(e){this.config={sqlite:{path:e?.sqlite?.path??".agentic-qe/memory.db",walMode:e?.sqlite?.walMode??!0,poolSize:e?.sqlite?.poolSize??5,busyTimeout:e?.sqlite?.busyTimeout??r.BUSY_TIMEOUT_MS,...e?.sqlite},agentdb:{path:e?.agentdb?.path??".agentic-qe/memory.db",...e?.agentdb},enableFallback:e?.enableFallback??!0,defaultNamespace:e?.defaultNamespace??"default",cleanupInterval:e?.cleanupInterval??r.CLEANUP_INTERVAL_MS}}async initialize(e){if(this.initialized)return;let i=e?.signal;i?.throwIfAborted();let t={dbPath:this.config.sqlite.path??c.dbPath,walMode:this.config.sqlite.walMode??!0,busyTimeout:this.config.sqlite.busyTimeout??r.BUSY_TIMEOUT_MS};this.unifiedMemory=d(t),i?.throwIfAborted(),await this.unifiedMemory.initialize({signal:i}),i?.throwIfAborted(),this.cleanupInterval=setInterval(()=>this.cleanup(),this.config.cleanupInterval),this.cleanupInterval.unref&&this.cleanupInterval.unref(),this.initialized=!0,console.log(`[HybridBackend] Initialized with unified memory: ${this.unifiedMemory.getDbPath()}`)}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.initialized=!1}async set(e,i,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;await this.unifiedMemory.kvSet(e,i,n,t?.ttl)}async get(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvGet(e,t)}async delete(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace,n=await this.unifiedMemory.kvDelete(e,t),a=await this.unifiedMemory.vectorDelete(e);return n||a}async has(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvExists(e,t)}async search(e,i=100,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvSearch(e,n,i)}async vectorSearch(e,i,t){return this.ensureInitialized(),(await this.unifiedMemory.vectorSearch(e,i,void 0,t)).map(a=>({key:a.id,score:a.score,metadata:a.metadata}))}getVectorSearchProvenance(){return this.ensureInitialized(),this.unifiedMemory.getVectorSearchProvenance()}async storeVector(e,i,t){this.ensureInitialized(),await this.unifiedMemory.vectorStore(e,i,this.config.defaultNamespace,t)}getHealth(){return{sqlite:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",sqlitePersistent:!0,agentdb:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",fallback:"inactive"}}isPersistent(){return this.unifiedMemory?.isInitialized()??!1}getConfig(){return{...this.config}}async setWithBackend(e,i,t,n){await this.set(e,i,n)}async getVectorStats(){if(!this.unifiedMemory?.isInitialized())return null;let e=await this.unifiedMemory.vectorCount(),i=this.unifiedMemory.getStats();return{vectorCount:e,indexSize:i.vectorIndexSize}}getUnifiedMemory(){return this.unifiedMemory}async count(e){return this.ensureInitialized(),this.unifiedMemory.getDatabase().prepare(`
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{o as c,r as d,v as f}from"./chunk-3Y7TJFHU.js";import{a as r,e as p}from"./chunk-TWDW32W2.js";import{a as h}from"./chunk-UT2VZ33P.js";import{c as l}from"./chunk-GB6HBNH2.js";f();p();h();import*as m from"path";var u=l.create("hybrid-backend"),s=class{unifiedMemory=null;config;cleanupInterval;cleanupCount=0;initialized=!1;constructor(e){this.config={sqlite:{path:e?.sqlite?.path??".agentic-qe/memory.db",walMode:e?.sqlite?.walMode??!0,poolSize:e?.sqlite?.poolSize??5,busyTimeout:e?.sqlite?.busyTimeout??r.BUSY_TIMEOUT_MS,...e?.sqlite},agentdb:{path:e?.agentdb?.path??".agentic-qe/memory.db",...e?.agentdb},enableFallback:e?.enableFallback??!0,defaultNamespace:e?.defaultNamespace??"default",cleanupInterval:e?.cleanupInterval??r.CLEANUP_INTERVAL_MS}}async initialize(e){if(this.initialized)return;let i=e?.signal;i?.throwIfAborted();let t={dbPath:this.config.sqlite.path??c.dbPath,walMode:this.config.sqlite.walMode??!0,busyTimeout:this.config.sqlite.busyTimeout??r.BUSY_TIMEOUT_MS};this.unifiedMemory=d(t),i?.throwIfAborted(),await this.unifiedMemory.initialize({signal:i}),i?.throwIfAborted(),this.cleanupInterval=setInterval(()=>this.cleanup(),this.config.cleanupInterval),this.cleanupInterval.unref&&this.cleanupInterval.unref(),this.initialized=!0,console.log(`[HybridBackend] Initialized with unified memory: ${this.unifiedMemory.getDbPath()}`)}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.initialized=!1}async set(e,i,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;await this.unifiedMemory.kvSet(e,i,n,t?.ttl)}async get(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvGet(e,t)}async delete(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace,n=await this.unifiedMemory.kvDelete(e,t),a=await this.unifiedMemory.vectorDelete(e);return n||a}async has(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvExists(e,t)}async search(e,i=100,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvSearch(e,n,i)}async vectorSearch(e,i,t){return this.ensureInitialized(),(await this.unifiedMemory.vectorSearch(e,i,void 0,t)).map(a=>({key:a.id,score:a.score,metadata:a.metadata}))}getVectorSearchProvenance(){return this.ensureInitialized(),this.unifiedMemory.getVectorSearchProvenance()}async storeVector(e,i,t){this.ensureInitialized(),await this.unifiedMemory.vectorStore(e,i,this.config.defaultNamespace,t)}getHealth(){return{sqlite:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",sqlitePersistent:!0,agentdb:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",fallback:"inactive"}}isPersistent(){return this.unifiedMemory?.isInitialized()??!1}getConfig(){return{...this.config}}async setWithBackend(e,i,t,n){await this.set(e,i,n)}async getVectorStats(){if(!this.unifiedMemory?.isInitialized())return null;let e=await this.unifiedMemory.vectorCount(),i=this.unifiedMemory.getStats();return{vectorCount:e,indexSize:i.vectorIndexSize}}getUnifiedMemory(){return this.unifiedMemory}async count(e){return this.ensureInitialized(),this.unifiedMemory.getDatabase().prepare(`
3
3
  SELECT COUNT(*) as count FROM kv_store
4
4
  WHERE namespace LIKE ?
5
5
  AND (expires_at IS NULL OR expires_at > ?)
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.12");process.exit(0)}
2
- import{c as m}from"./chunk-MCPEC6OO.js";import{existsSync as g,readFileSync as _,readdirSync as w,statSync as T}from"fs";import{join as c,extname as E}from"path";var v=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".pyw",".go",".rs",".java",".kt",".kts",".rb",".cs",".php",".swift",".c",".h",".cpp",".hpp",".cc",".scala"]),F=[".test.",".spec.","_test.","_spec."],b=new Set(["node_modules","dist","build","coverage",".git","__pycache__",".venv","venv",".tox",".mypy_cache","target",".gradle","vendor",".bundle",".next",".nuxt",".output"]);function W(s,n={}){let{maxDepth:r=6,includeTests:x=!1,testsOnly:y=!1,extraExtensions:S=[]}=n;if(!g(s))return[];let a=T(s);if(a.isFile())return[s];if(!a.isDirectory())return[];let h=new Set(S.map(e=>e.startsWith(".")?e:`.${e}`)),i=[];function u(e,o){if(o>r)return;let l;try{l=w(e,{withFileTypes:!0})}catch{return}for(let t of l)if(t.isDirectory()){if(b.has(t.name)||m(e,t.name,o===0))continue;u(c(e,t.name),o+1)}else if(t.isFile()){let f=E(t.name).toLowerCase();if(!(v.has(f)||h.has(f))||t.name.endsWith(".d.ts"))continue;let p=F.some(d=>t.name.includes(d))||t.name.startsWith("test_");y?p&&i.push(c(e,t.name)):(x||!p)&&i.push(c(e,t.name))}}return u(s,0),i}function I(s,n){return n!=="node"&&n!=="node-test"?s:s.filter(r=>{try{return!/@playwright\/test|require\(\s*['"]playwright['"]\s*\)/.test(_(r,"utf8"))}catch{return!0}})}export{v as a,W as b,I as c};
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{c as m}from"./chunk-5MDERQH3.js";import{existsSync as g,readFileSync as _,readdirSync as w,statSync as T}from"fs";import{join as c,extname as E}from"path";var v=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".pyw",".go",".rs",".java",".kt",".kts",".rb",".cs",".php",".swift",".c",".h",".cpp",".hpp",".cc",".scala"]),F=[".test.",".spec.","_test.","_spec."],b=new Set(["node_modules","dist","build","coverage",".git","__pycache__",".venv","venv",".tox",".mypy_cache","target",".gradle","vendor",".bundle",".next",".nuxt",".output"]);function W(s,n={}){let{maxDepth:r=6,includeTests:x=!1,testsOnly:y=!1,extraExtensions:S=[]}=n;if(!g(s))return[];let a=T(s);if(a.isFile())return[s];if(!a.isDirectory())return[];let h=new Set(S.map(e=>e.startsWith(".")?e:`.${e}`)),i=[];function u(e,o){if(o>r)return;let l;try{l=w(e,{withFileTypes:!0})}catch{return}for(let t of l)if(t.isDirectory()){if(b.has(t.name)||m(e,t.name,o===0))continue;u(c(e,t.name),o+1)}else if(t.isFile()){let f=E(t.name).toLowerCase();if(!(v.has(f)||h.has(f))||t.name.endsWith(".d.ts"))continue;let p=F.some(d=>t.name.includes(d))||t.name.startsWith("test_");y?p&&i.push(c(e,t.name)):(x||!p)&&i.push(c(e,t.name))}}return u(s,0),i}function I(s,n){return n!=="node"&&n!=="node-test"?s:s.filter(r=>{try{return!/@playwright\/test|require\(\s*['"]playwright['"]\s*\)/.test(_(r,"utf8"))}catch{return!0}})}export{v as a,W as b,I 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.12");process.exit(0)}
2
- import{a as I,b as _,c as X,d as M,f as ee,h as ae}from"./chunk-SITL5YZV.js";import{a as K,e as Z}from"./chunk-BC4T6SCV.js";import{c as te,d as re,e as ne,f as ie}from"./chunk-GJKZ7UQO.js";import{b as D,g as $,j as H}from"./chunk-ZGROHCOW.js";import{b as k}from"./chunk-SUX5XB2Z.js";import{c as Y,i as J}from"./chunk-FZJCBSN4.js";import{r as U,v as ve}from"./chunk-L7NGKANW.js";import{s as T}from"./chunk-NVRYELCY.js";import{c as C,d as E}from"./chunk-VZBC6DP7.js";import{a as G}from"./chunk-UJNGGFGX.js";import{c as A}from"./chunk-ADUAJIAU.js";import{S as ye,b as j}from"./chunk-35MIUSXQ.js";import{a as f,b as B,e as z}from"./chunk-W4II6SIH.js";G();z();function oe(i,e,r,t){let n={missing:0,ingested:0,rejected:0,capped:!1};if(typeof i.has!="function")return n;let a=d=>d.filter(h=>!i.has(h)),o=a(e.getEmbeddingIdsInSpace(r));if(o.length===0)return n;let s=Number.isFinite(t)&&t>0?Math.floor(t):1e3;o.length>s&&(o=a(e.getEmbeddingIdsInSpace(r,{ordered:!0})));let l=o.slice(0,s),u=e.getEmbeddingsByIds(l).filter(({embedding:d})=>d&&d.length>0).map(({patternId:d,embedding:h})=>({id:d,vector:new Float32Array(h)})),{accepted:c,rejected:g}=u.length>0?i.ingest(u):{accepted:0,rejected:0};return{missing:o.length,ingested:c,rejected:g,capped:o.length>s}}var N={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var q=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
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 I,b as _,c as X,d as M,f as ee,h as ae}from"./chunk-TSQC2KKZ.js";import{a as K,e as Z}from"./chunk-SYV2V3PL.js";import{c as te,d as re,e as ne,f as ie}from"./chunk-NZD4DPSU.js";import{b as D,g as $,j as H}from"./chunk-E7CLYGS7.js";import{b as k}from"./chunk-TWJTK4CC.js";import{c as Y,i as J}from"./chunk-VRVMIPTM.js";import{r as U,v as ve}from"./chunk-3Y7TJFHU.js";import{s as T}from"./chunk-WKGTGOYS.js";import{c as C,d as E}from"./chunk-NURIILUB.js";import{a as G}from"./chunk-UT2VZ33P.js";import{c as A}from"./chunk-GB6HBNH2.js";import{S as ye,b as j}from"./chunk-WOCGL4QP.js";import{a as f,b as B,e as z}from"./chunk-3Y2ROSCL.js";G();z();function oe(i,e,r,t){let n={missing:0,ingested:0,rejected:0,capped:!1};if(typeof i.has!="function")return n;let a=d=>d.filter(h=>!i.has(h)),o=a(e.getEmbeddingIdsInSpace(r));if(o.length===0)return n;let s=Number.isFinite(t)&&t>0?Math.floor(t):1e3;o.length>s&&(o=a(e.getEmbeddingIdsInSpace(r,{ordered:!0})));let l=o.slice(0,s),u=e.getEmbeddingsByIds(l).filter(({embedding:d})=>d&&d.length>0).map(({patternId:d,embedding:h})=>({id:d,vector:new Float32Array(h)})),{accepted:c,rejected:g}=u.length>0?i.ingest(u):{accepted:0,rejected:0};return{missing:o.length,ingested:c,rejected:g,capped:o.length>s}}var N={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var q=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
3
3
  describe('{{methodName}}', () => {
4
4
  it('should {{expectedBehavior}}', {{async}} () => {
5
5
  // Arrange
@@ -317,4 +317,4 @@ On promotion:
317
317
  AND agent_id = 'aqe-hook-router'
318
318
  AND state_key = ?
319
319
  AND action_key = ?
320
- `);return o=>{try{let s=a.get(e,o);return s?{qValue:s.q_value,visits:s.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return I(e)}generateContext(e,r){return M(e,r||{})}checkAntiPatterns(e,r){return X(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-ZWXS5ZFV.js"),t=await r(e);if(t.length!==this.config.embeddingDimension)return me(t,this.config.embeddingDimension);let n=T()?.spaceId;return n&&this.embeddingProvenance.set(t,n),t}catch(r){let{isUsingEndpoint:t}=await import("./real-embeddings-ZWXS5ZFV.js");if(t())throw r;process.env.DEBUG&&m.warn("ONNX embeddings unavailable, using hash fallback",{error:f(r)})}return ge(e,this.config.embeddingDimension)}async embedForPatterns(e){if(!this.embedderRecovery.isAvailable())return null;try{return await this.embed(e)}catch(r){let t=f(r),n="Embedder failed: storing and searching patterns by text only";return this.embedderRecovery.markUnavailable(t)?m.warn(n,{error:t}):m.debug(n,{error:t}),null}}getEmbedderFailure(){return this.embedderRecovery.unavailableReason}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let c of H)r[c]=e.byDomain[c]||0;let t=this.stats.routingRequests,n=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,a=this.stats.learningOutcomes,o=this.stats.measuredOutcomes,s=this.stats.learningOutcomes-this.stats.measuredOutcomes,l=this.stats.successfulOutcomes;try{let c=this.getSqliteStore().getAggregateOutcomeStats();c.routingRequests>t&&(t=c.routingRequests,n=c.avgRoutingConfidence),c.learningOutcomes>a&&(a=c.learningOutcomes,o=c.measuredOutcomes,s=c.unmeasuredOutcomes,l=c.successfulOutcomes)}catch{}let u=o>0?l/o:null;return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:n,learningOutcomes:a,measuredOutcomes:o,unmeasuredOutcomes:s,patternSuccessRate:u,...u===null?{evidenceStatus:"insufficient-evidence"}:{},patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function Dt(i,e,r,t){return new W(i,e,r,t)}export{N as a,q as b,x as c,ue as d,O as e,Q as f,W as g,Dt as h};
320
+ `);return o=>{try{let s=a.get(e,o);return s?{qValue:s.q_value,visits:s.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return I(e)}generateContext(e,r){return M(e,r||{})}checkAntiPatterns(e,r){return X(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-HW4G2LWL.js"),t=await r(e);if(t.length!==this.config.embeddingDimension)return me(t,this.config.embeddingDimension);let n=T()?.spaceId;return n&&this.embeddingProvenance.set(t,n),t}catch(r){let{isUsingEndpoint:t}=await import("./real-embeddings-HW4G2LWL.js");if(t())throw r;process.env.DEBUG&&m.warn("ONNX embeddings unavailable, using hash fallback",{error:f(r)})}return ge(e,this.config.embeddingDimension)}async embedForPatterns(e){if(!this.embedderRecovery.isAvailable())return null;try{return await this.embed(e)}catch(r){let t=f(r),n="Embedder failed: storing and searching patterns by text only";return this.embedderRecovery.markUnavailable(t)?m.warn(n,{error:t}):m.debug(n,{error:t}),null}}getEmbedderFailure(){return this.embedderRecovery.unavailableReason}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let c of H)r[c]=e.byDomain[c]||0;let t=this.stats.routingRequests,n=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,a=this.stats.learningOutcomes,o=this.stats.measuredOutcomes,s=this.stats.learningOutcomes-this.stats.measuredOutcomes,l=this.stats.successfulOutcomes;try{let c=this.getSqliteStore().getAggregateOutcomeStats();c.routingRequests>t&&(t=c.routingRequests,n=c.avgRoutingConfidence),c.learningOutcomes>a&&(a=c.learningOutcomes,o=c.measuredOutcomes,s=c.unmeasuredOutcomes,l=c.successfulOutcomes)}catch{}let u=o>0?l/o:null;return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:n,learningOutcomes:a,measuredOutcomes:o,unmeasuredOutcomes:s,patternSuccessRate:u,...u===null?{evidenceStatus:"insufficient-evidence"}:{},patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function Dt(i,e,r,t){return new W(i,e,r,t)}export{N as a,q as b,x as c,ue as d,O as e,Q as f,W as g,Dt as h};
@@ -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.12");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.13");process.exit(0)}
2
2
  var i=class r{constructor(e){this._value=e;if(!e||e.trim()==="")throw new Error("FilePath cannot be empty")}_value;get value(){return this._value}get extension(){let e=this._value.split(".");return e.length>1?e[e.length-1]:""}get directory(){let e=this._value.lastIndexOf("/");return e>0?this._value.substring(0,e):""}get filename(){let e=this._value.lastIndexOf("/");return e>=0?this._value.substring(e+1):this._value}equals(e){return this._value===e._value}static create(e){return new r(e)}};var s=class r{constructor(e){this._value=e;if(e<0||e>1)throw new Error("RiskScore must be between 0 and 1")}_value;get value(){return this._value}get percentage(){return this._value*100}get level(){return this._value>=.8?"critical":this._value>=.6?"high":this._value>=.3?"medium":"low"}isHigherThan(e){return this._value>e._value}equals(e){return this._value===e._value}static create(e){return new r(e)}static fromPercentage(e){return new r(e/100)}},u=class r{constructor(e,t){this._start=e;this._end=t;if(e>t)throw new Error("Start date cannot be after end date")}_start;_end;get start(){return this._start}get end(){return this._end}get durationMs(){return this._end.getTime()-this._start.getTime()}get durationSeconds(){return this.durationMs/1e3}contains(e){return e>=this._start&&e<=this._end}overlaps(e){return this._start<=e._end&&e._start<=this._end}equals(e){return this._start.getTime()===e._start.getTime()&&this._end.getTime()===e._end.getTime()}static create(e,t){return new r(e,t)}static lastNDays(e){let t=new Date,n=new Date(t.getTime()-e*24*60*60*1e3);return new r(n,t)}},o=class r{constructor(e,t,n,a){this._major=e;this._minor=t;this._patch=n;this._prerelease=a}_major;_minor;_patch;_prerelease;get major(){return this._major}get minor(){return this._minor}get patch(){return this._patch}get prerelease(){return this._prerelease}toString(){let e=`${this._major}.${this._minor}.${this._patch}`;return this._prerelease?`${e}-${this._prerelease}`:e}isNewerThan(e){return this._major!==e._major?this._major>e._major:this._minor!==e._minor?this._minor>e._minor:this._patch>e._patch}equals(e){return this._major===e._major&&this._minor===e._minor&&this._patch===e._patch&&this._prerelease===e._prerelease}static create(e,t,n,a){return new r(e,t,n,a)}static parse(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(!t)throw new Error(`Invalid version format: ${e}`);return new r(parseInt(t[1]),parseInt(t[2]),parseInt(t[3]),t[4])}};export{i as a,s as b,u as c,o as d};
@@ -1,6 +1,6 @@
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.12");process.exit(0)}
2
- import{a as F}from"./chunk-FAGKBOX2.js";import{a as b,b as E,c as z,d as M,e as C,f as P,g as B}from"./chunk-W7H55PY4.js";function W(s,e){let n=s.slice(0,e).split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.13");process.exit(0)}
2
+ import{a as F}from"./chunk-32ZMWEP3.js";import{a as b,b as E,c as z,d as M,e as C,f as P,g as B}from"./chunk-R7SYRCRP.js";function W(s,e){let n=s.slice(0,e).split(`
3
3
  `),r=n.length,o=(n[n.length-1]||"").length;return{line:r,column:o,offset:e}}function p(s,e,n,r,o){return{start:W(s,e),end:W(s,n),oldText:s.slice(e,n),newText:r,description:o}}function _(s,e){let n=[...e].sort((o,t)=>t.start.offset-o.start.offset),r=s;for(let o of n)r=r.slice(0,o.start.offset)+o.newText+r.slice(o.end.offset);return r}function U(s,e){if(s.length===0)return 1;let n=s.reduce((t,a)=>t+Math.abs(a.newText.length-a.oldText.length),0)/s.length,r=Math.max(.5,1-n/1e3),o=Math.max(.7,1-s.length/100);return Math.min(1,e*r*o)}function T(s,e,n,r,o=.9){let t=_(s,n),a=Date.now()-r;return{success:!0,transformType:e,originalCode:s,transformedCode:t,edits:n,changeCount:n.length,confidence:U(n,o),durationMs:a,implementationUsed:"typescript",usedFallback:!1,warnings:[]}}function w(s,e,n,r){return{success:!1,transformType:e,originalCode:s,transformedCode:s,edits:[],changeCount:0,confidence:0,durationMs:Date.now()-r,implementationUsed:"typescript",usedFallback:!1,error:n,warnings:[]}}function Z(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/\bvar\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,a=/([a-zA-Z_$][a-zA-Z0-9_$]*)\s*(?:\+\+|--|[+\-*/%&|^]=|\?\?=|&&=|\|\|=|=(?!=))/g,i=[],l;for(;(l=t.exec(s))!==null;)i.push({name:l[1],offset:l.index});let m=new Set;for(;(l=a.exec(s))!==null;)m.add(l[1]);let u=/\bfor\s*\(\s*var\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,c=new Set;for(;(l=u.exec(s))!==null;)c.add(l[1]);for(let g of i){let d=c.has(g.name)||m.has(g.name)?"let":"const";r.push(p(s,g.offset,g.offset+3,d,`Convert var ${g.name} to ${d}`))}e.debug("var-to-const transform completed",{declarations:i.length,reassigned:m.size,loopVars:c.size});let f=T(s,"var-to-const",r,n,.95);return f.warnings=o,f}catch(t){return e.error("var-to-const transform failed",t),w(s,"var-to-const",t instanceof Error?t.message:"Unknown error",n)}}function O(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(([^)]*)\)/g,a=/(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*\(([^)]*)\)\s*=>/g,i=/([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(([^)]*)\)\s*(?::\s*[^{]+)?\s*\{/g,l;for(;(l=t.exec(s))!==null;){let u=l[2].trim();if(u&&!u.includes(":")){let c=u.split(",").map(d=>{let h=d.trim().replace(/\s*=.*$/,"");return h&&!h.includes(":")?`${h}: unknown`:d.trim()}).join(", "),f=l.index+l[0].indexOf("(")+1,g=f+l[2].length;r.push(p(s,f,g,c,`Add types to function ${l[1]} parameters`))}}for(;(l=a.exec(s))!==null;){let u=l[2].trim();if(u&&!u.includes(":")){let c=u.split(",").map(d=>{let h=d.trim().replace(/\s*=.*$/,"");return h&&!h.includes(":")?`${h}: unknown`:d.trim()}).join(", "),f=l.index+l[0].indexOf("(")+1,g=f+l[2].length;r.push(p(s,f,g,c,`Add types to arrow function ${l[1]} parameters`))}}e.debug("add-types transform completed",{edits:r.length});let m=T(s,"add-types",r,n,.7);return m.warnings=o,r.length>0&&m.warnings.push('Type annotations use "unknown" - manual review recommended'),m}catch(t){return e.error("add-types transform failed",t),w(s,"add-types",t instanceof Error?t.message:"Unknown error",n)}}function I(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/^\s*console\.(log|warn|error|info|debug|trace|dir|table|time|timeEnd|group|groupEnd|assert)\s*\([^)]*\);?\s*$/gm,a=/console\.(log|warn|error|info|debug|trace|dir|table|time|timeEnd|group|groupEnd|assert)\s*\([^)]*\)/g,i,l=new Set;for(;(i=t.exec(s))!==null;)l.has(i.index)||(l.add(i.index),r.push(p(s,i.index,i.index+i[0].length,"",`Remove console.${i[1]}() statement`)));for(;(i=a.exec(s))!==null;){if(l.has(i.index))continue;let u=s.lastIndexOf(`
4
4
  `,i.index)+1,c=s.indexOf(`
5
5
  `,i.index),f=s.slice(u,c===-1?void 0:c);/^\s*console\./.test(f)||(l.add(i.index),o.push(`Inline console.${i[1]}() at offset ${i.index} - consider manual review`))}e.debug("remove-console transform completed",{removed:r.length,warnings:o.length});let m=T(s,"remove-console",r,n,.95);return m.warnings=o,m}catch(t){return e.error("remove-console transform failed",t),w(s,"remove-console",t instanceof Error?t.message:"Unknown error",n)}}function j(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/([a-zA-Z_$][a-zA-Z0-9_$]*(?:\([^)]*\))?)\s*\.then\s*\(\s*(?:async\s*)?\(?\s*([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\)?\s*=>\s*([^)]+)\)/g,a;for(;(a=t.exec(s))!==null;){let[l,m,u,c]=a;if(c.includes(".then")||c.includes(".catch")){o.push(`Complex promise chain at offset ${a.index} - manual review recommended`);continue}let f=`const ${u} = await ${m};
6
- ${c.trim()}`;r.push(p(s,a.index,a.index+l.length,f,"Convert .then() to await"))}e.debug("promise-to-async transform completed",{converted:r.length,warnings:o.length});let i=T(s,"promise-to-async",r,n,.65);return i.warnings=o,r.length>0&&i.warnings.push("Promise chains converted to await - ensure containing function is async"),i}catch(t){return e.error("promise-to-async transform failed",t),w(s,"promise-to-async",t instanceof Error?t.message:"Unknown error",n)}}function N(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t,a=/(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*require\s*\(\s*(['"`][^'"`]+['"`])\s*\)\s*;?/g;for(;(t=a.exec(s))!==null;){let[c,f,g]=t,d=`import ${f} from ${g};`;r.push(p(s,t.index,t.index+c.length,d,"Convert require to import"))}let i=/(?:const|let|var)\s+\{\s*([^}]+)\s*\}\s*=\s*require\s*\(\s*(['"`][^'"`]+['"`])\s*\)\s*;?/g;for(;(t=i.exec(s))!==null;){let[c,f,g]=t,d=`import { ${f.trim()} } from ${g};`;r.push(p(s,t.index,t.index+c.length,d,"Convert destructured require to import"))}let l=/module\.exports\s*=\s*([^;]+);?/g;for(;(t=l.exec(s))!==null;){let[c,f]=t,g=`export default ${f.trim()};`;r.push(p(s,t.index,t.index+c.length,g,"Convert module.exports to export default"))}let m=/exports\.([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*([^;]+);?/g;for(;(t=m.exec(s))!==null;){let[c,f,g]=t,d=g.trim(),h;d.startsWith("function")||d.startsWith("class")?h=`export ${d}`:d.startsWith("async function")?h=`export ${d}`:h=`export const ${f} = ${d};`,r.push(p(s,t.index,t.index+c.length,h,`Convert exports.${f} to named export`))}e.debug("cjs-to-esm transform completed",{edits:r.length});let u=T(s,"cjs-to-esm",r,n,.85);return u.warnings=o,u}catch(t){return e.error("cjs-to-esm transform failed",t),w(s,"cjs-to-esm",t instanceof Error?t.message:"Unknown error",n)}}function H(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/(const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*function\s*\(([^)]*)\)\s*\{/g,a;for(;(a=t.exec(s))!==null;){let[m,u,c,f]=a,g=a.index,d=1,h=g+m.length;for(;d>0&&h<s.length;)s[h]==="{"&&d++,s[h]==="}"&&d--,h++;let S=s.slice(g,h);if(/\bthis\b/.test(S)){o.push(`Function ${c} uses 'this' - skipping arrow conversion (would change binding)`);continue}if(/\barguments\b/.test(S)){o.push(`Function ${c} uses 'arguments' - skipping arrow conversion (not available in arrow functions)`);continue}let D=`${u} ${c} = (${f}) => {`;r.push(p(s,a.index,a.index+m.length,D,`Convert function ${c} to arrow function`))}let i=/function\s*\(([^)]*)\)\s*\{\s*return\s+([^;]+);\s*\}/g;for(;(a=i.exec(s))!==null;){let[m,u,c]=a;if(/\b(this|arguments)\b/.test(m))continue;let f=u.includes(",")||u.trim()===""?`(${u}) => ${c}`:`${u.trim()} => ${c}`;r.push(p(s,a.index,a.index+m.length,f,"Convert callback to arrow function"))}e.debug("func-to-arrow transform completed",{converted:r.length,warnings:o.length});let l=T(s,"func-to-arrow",r,n,.85);return l.warnings=o,l}catch(t){return e.error("func-to-arrow transform failed",t),w(s,"func-to-arrow",t instanceof Error?t.message:"Unknown error",n)}}var V={"var-to-const":Z,"add-types":O,"remove-console":I,"promise-to-async":j,"cjs-to-esm":N,"func-to-arrow":H};function $(s,e,n){let r=V[e];return r?r(s,n):{success:!1,transformType:e,originalCode:s,transformedCode:s,edits:[],changeCount:0,confidence:0,durationMs:0,implementationUsed:"typescript",usedFallback:!1,error:`Unknown transform type: ${e}`,warnings:[]}}var q={JavaScript:0,TypeScript:1,Python:2,Rust:3,Go:4,Java:5,C:6,Cpp:7},y=null,A=null,x=null,k=!1,R=null;async function G(){if(k)return R===null;if(R)return!1;try{let s=await import("./agent-booster-wasm-5VZCKTIJ.js");return y=s.transform,A=s.warmup,x=s.isWasmAvailable,k=!0,!0}catch(s){return R=s,k=!0,!1}}function K(s){return q.TypeScript}var L=class{cache=new Map;ttlMs;enabled;constructor(e,n){this.enabled=e,this.ttlMs=n}generateKey(e,n){let r=0;for(let o=0;o<e.length;o++){let t=e.charCodeAt(o);r=(r<<5)-r+t,r=r&r}return`${n}:${r}:${e.length}`}get(e,n){if(!this.enabled)return null;let r=this.generateKey(e,n),o=this.cache.get(r);return o?Date.now()>o.expiresAt?(this.cache.delete(r),null):o.result:null}set(e,n,r){if(!this.enabled)return;let o=this.generateKey(e,n);this.cache.set(o,{result:r,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},v=class{config;logger;cache;enabledTransforms;metricsTracker;initialized=!1;wasmAvailable=!1;wasmModule=null;patternsLoaded=!1;totalTransforms=0;successfulTransforms=0;totalDurationMs=0;cacheHits=0;cacheMisses=0;constructor(e={},n,r){this.config={...z,...e},this.logger=n||{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.metricsTracker=r,this.cache=new L(this.config.cacheEnabled,this.config.cacheTtlMs),this.config.transforms.length===0?this.enabledTransforms=new Set(b):this.enabledTransforms=new Set(this.config.transforms)}setMetricsTracker(e){this.metricsTracker=e}async initialize(){this.initialized||(this.logger.info("Initializing Agent Booster adapter",{enabled:this.config.enabled,transforms:Array.from(this.enabledTransforms)}),this.config.transforms.length===0&&await this.loadEligibleTransformsFromPatterns(),this.config.enabled&&await this.tryLoadWasm(),this.initialized=!0,this.logger.info("Agent Booster adapter initialized",{wasmAvailable:this.wasmAvailable,enabledTransforms:Array.from(this.enabledTransforms),patternsLoaded:this.patternsLoaded}))}async loadEligibleTransformsFromPatterns(){try{let n=await F().getEligibleBoosterTransforms();if(n.length>0){let r=n.filter(o=>b.includes(o));if(r.length>0){this.enabledTransforms=new Set(r),this.patternsLoaded=!0,this.logger.info("Loaded eligible transforms from PatternLoader",{fromPatterns:r,invalidIgnored:n.length-r.length});return}}this.logger.debug("PatternLoader returned empty transforms, using defaults")}catch(e){this.logger.warn("Failed to load transforms from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.enabledTransforms=new Set(b),this.patternsLoaded=!1}async tryLoadWasm(){try{if(this.logger.debug("Loading WASM module"),!await G()||!x){this.logger.debug("WASM module could not be loaded, using TypeScript fallback"),this.wasmAvailable=!1;return}this.logger.debug("Checking WASM availability from local module"),await x()&&y&&A?(this.logger.debug("Warming up WASM module"),await A(),this.wasmModule={transform:y,warmup:A,isAvailable:x},this.wasmAvailable=!0,this.logger.info("WASM Agent Booster loaded and warmed up successfully",{source:"local-module"})):(this.logger.debug("WASM not available from local module, using TypeScript fallback"),this.wasmAvailable=!1)}catch(e){this.logger.warn("Failed to load WASM module",{error:e instanceof Error?e.message:"Unknown error"}),this.wasmAvailable=!1}}async dispose(){this.cache.clear(),this.wasmModule=null,this.wasmAvailable=!1,this.initialized=!1,this.logger.info("Agent Booster adapter disposed")}async transform(e,n){this.ensureInitialized(),this.ensureEnabled();let r=Date.now();if(this.totalTransforms++,!this.enabledTransforms.has(n))return this.createErrorResult(e,n,`Transform type '${n}' is not enabled`,r);let o=this.cache.get(e,n);if(o)return this.cacheHits++,this.logger.debug("Cache hit for transform",{type:n}),{...o,durationMs:Date.now()-r};this.cacheMisses++;let t;try{t=await this.executeWithFallback(e,n,r)}catch(a){return this.createErrorResult(e,n,a instanceof Error?a.message:"Unknown error",r)}return t.success&&(this.successfulTransforms++,this.cache.set(e,n,t)),this.totalDurationMs+=t.durationMs,await this.recordMetrics(t,n),t}async recordMetrics(e,n){if(this.metricsTracker)try{let r=`booster-${n}-${Date.now()}`;await this.metricsTracker.recordOutcome("booster",r,e.success,e.durationMs,{subType:n,confidence:e.confidence,usedFallback:e.usedFallback,implementationUsed:e.implementationUsed,itemCount:e.changeCount,errorMessage:e.error})}catch(r){this.logger.warn("Failed to record metrics",{error:r instanceof Error?r.message:"Unknown error"})}}async executeWithFallback(e,n,r){if(this.wasmAvailable)try{let t=await this.executeWasmTransform(e,n,r);if(t.success&&t.confidence>=this.config.confidenceThreshold)return t;this.logger.debug("WASM transform low confidence, trying TypeScript",{confidence:t.confidence,threshold:this.config.confidenceThreshold})}catch(t){this.logger.warn("WASM transform failed, falling back to TypeScript",{error:t instanceof Error?t.message:"Unknown error"})}let o=$(e,n,this.logger);return o.durationMs=Date.now()-r,this.config.fallbackToLLM&&o.confidence<this.config.confidenceThreshold&&(this.logger.debug("TypeScript transform low confidence, LLM fallback available",{confidence:o.confidence,threshold:this.config.confidenceThreshold}),o.warnings.push(`Confidence ${o.confidence.toFixed(2)} is below threshold ${this.config.confidenceThreshold}. LLM fallback recommended for review.`),o.usedFallback=!0),o}async executeWasmTransform(e,n,r){if(!this.wasmAvailable)throw new C;let o=K(n),t=$(e,n,this.logger);if(t.changeCount===0)return{...t,durationMs:Date.now()-r,implementationUsed:"wasm"};if(!y)throw new C("WASM transform function not loaded");let a=await Promise.race([y(e,t.transformedCode,o,{confidenceThreshold:this.config.confidenceThreshold,allowFallback:!0}),new Promise((m,u)=>setTimeout(()=>u(new P("WASM transform timed out",n,this.config.timeoutMs)),this.config.timeoutMs))]),i=Date.now()-r,l=a.success&&a.mergedCode!==e?t.changeCount:0;return{success:a.success,transformType:n,originalCode:e,transformedCode:a.mergedCode,edits:t.edits,changeCount:l,confidence:a.confidence,durationMs:i,implementationUsed:a.source==="wasm"?"wasm":"typescript",usedFallback:a.source!=="wasm",error:a.error,warnings:a.syntaxValid?[]:["WASM reported syntax may be invalid"]}}async batchTransform(e,n){this.ensureInitialized(),this.ensureEnabled();let r=Date.now(),o=[],t=[],a=0,i=0,l=0,m=0;for(let u of e){if(u.content.length>this.config.maxFileSizeBytes){let c=new B(u.path,u.content.length,this.config.maxFileSizeBytes);t.push({path:u.path,error:c.message}),i++;continue}try{let c=await this.transform(u.content,n);o.push({path:u.path,result:c}),c.success?c.changeCount>0?(a++,m+=c.changeCount):l++:(i++,c.error&&t.push({path:u.path,error:c.error}))}catch(c){i++,t.push({path:u.path,error:c instanceof Error?c.message:"Unknown error"})}}return{success:i===0,transformType:n,files:o,totalFiles:e.length,successCount:a,failureCount:i,noChangeCount:l,totalChanges:m,durationMs:Date.now()-r,errors:t}}async detectTransformOpportunities(e){this.ensureInitialized(),this.ensureEnabled();let n=Date.now(),r=[],o={},t=[];for(let a of b)o[a]=0;for(let a of Array.from(this.enabledTransforms))try{let i=await this.transform(e,a);if(i.changeCount>0)for(let l of i.edits){let m={type:a,confidence:i.confidence,location:l.start,codeSnippet:l.oldText.slice(0,100)+(l.oldText.length>100?"...":""),suggestedCode:l.newText.slice(0,100)+(l.newText.length>100?"...":""),reason:l.description,risk:this.confidenceToRisk(i.confidence),estimatedDurationMs:E[a].typicalLatencyMs};r.push(m),o[a]++}}catch(i){t.push(`Failed to analyze for ${a}: ${i instanceof Error?i.message:"Unknown error"}`)}return r.sort((a,i)=>i.confidence-a.confidence),{opportunities:r,totalCount:r.length,byType:o,durationMs:Date.now()-n,complete:t.length===0,warnings:t}}isTransformAvailable(e){return this.enabledTransforms.has(e)}getTransformMetadata(e){return E[e]}getAvailableTransforms(){return Array.from(this.enabledTransforms)}isWasmAvailable(){return this.wasmAvailable}getHealth(){let e=this.totalTransforms>0?this.totalDurationMs/this.totalTransforms:0,n=this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0,r=[];return this.initialized||r.push("Adapter not initialized"),this.config.enabled||r.push("Adapter is disabled"),this.wasmAvailable||r.push("WASM module not loaded (using TypeScript fallback)"),this.patternsLoaded||r.push("Patterns not loaded from PatternLoader (using defaults)"),{ready:this.initialized&&this.config.enabled,wasmAvailable:this.wasmAvailable,patternsLoaded:this.patternsLoaded,availableTransforms:Array.from(this.enabledTransforms),lastChecked:new Date,issues:r,metrics:{totalTransforms:this.totalTransforms,successfulTransforms:this.successfulTransforms,averageDurationMs:e,cacheHitRate:n}}}ensureInitialized(){if(!this.initialized)throw new M("AgentBoosterAdapter not initialized. Call initialize() first.","var-to-const")}ensureEnabled(){if(!this.config.enabled)throw new M("AgentBoosterAdapter is disabled. Set enabled: true in config.","var-to-const")}createErrorResult(e,n,r,o){return{success:!1,transformType:n,originalCode:e,transformedCode:e,edits:[],changeCount:0,confidence:0,durationMs:Date.now()-o,implementationUsed:"typescript",usedFallback:!1,error:r,warnings:[]}}confidenceToRisk(e){return e>=.95?"info":e>=.85?"low":e>=.7?"medium":e>=.5?"high":"critical"}};async function ee(s={},e,n){let r=new v(s,e,n);return await r.initialize(),r}function re(s={},e,n){return new v(s,e,n)}export{v as a,ee as b,re as c};
6
+ ${c.trim()}`;r.push(p(s,a.index,a.index+l.length,f,"Convert .then() to await"))}e.debug("promise-to-async transform completed",{converted:r.length,warnings:o.length});let i=T(s,"promise-to-async",r,n,.65);return i.warnings=o,r.length>0&&i.warnings.push("Promise chains converted to await - ensure containing function is async"),i}catch(t){return e.error("promise-to-async transform failed",t),w(s,"promise-to-async",t instanceof Error?t.message:"Unknown error",n)}}function N(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t,a=/(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*require\s*\(\s*(['"`][^'"`]+['"`])\s*\)\s*;?/g;for(;(t=a.exec(s))!==null;){let[c,f,g]=t,d=`import ${f} from ${g};`;r.push(p(s,t.index,t.index+c.length,d,"Convert require to import"))}let i=/(?:const|let|var)\s+\{\s*([^}]+)\s*\}\s*=\s*require\s*\(\s*(['"`][^'"`]+['"`])\s*\)\s*;?/g;for(;(t=i.exec(s))!==null;){let[c,f,g]=t,d=`import { ${f.trim()} } from ${g};`;r.push(p(s,t.index,t.index+c.length,d,"Convert destructured require to import"))}let l=/module\.exports\s*=\s*([^;]+);?/g;for(;(t=l.exec(s))!==null;){let[c,f]=t,g=`export default ${f.trim()};`;r.push(p(s,t.index,t.index+c.length,g,"Convert module.exports to export default"))}let m=/exports\.([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*([^;]+);?/g;for(;(t=m.exec(s))!==null;){let[c,f,g]=t,d=g.trim(),h;d.startsWith("function")||d.startsWith("class")?h=`export ${d}`:d.startsWith("async function")?h=`export ${d}`:h=`export const ${f} = ${d};`,r.push(p(s,t.index,t.index+c.length,h,`Convert exports.${f} to named export`))}e.debug("cjs-to-esm transform completed",{edits:r.length});let u=T(s,"cjs-to-esm",r,n,.85);return u.warnings=o,u}catch(t){return e.error("cjs-to-esm transform failed",t),w(s,"cjs-to-esm",t instanceof Error?t.message:"Unknown error",n)}}function H(s,e={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}){let n=Date.now(),r=[],o=[];try{let t=/(const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*function\s*\(([^)]*)\)\s*\{/g,a;for(;(a=t.exec(s))!==null;){let[m,u,c,f]=a,g=a.index,d=1,h=g+m.length;for(;d>0&&h<s.length;)s[h]==="{"&&d++,s[h]==="}"&&d--,h++;let S=s.slice(g,h);if(/\bthis\b/.test(S)){o.push(`Function ${c} uses 'this' - skipping arrow conversion (would change binding)`);continue}if(/\barguments\b/.test(S)){o.push(`Function ${c} uses 'arguments' - skipping arrow conversion (not available in arrow functions)`);continue}let D=`${u} ${c} = (${f}) => {`;r.push(p(s,a.index,a.index+m.length,D,`Convert function ${c} to arrow function`))}let i=/function\s*\(([^)]*)\)\s*\{\s*return\s+([^;]+);\s*\}/g;for(;(a=i.exec(s))!==null;){let[m,u,c]=a;if(/\b(this|arguments)\b/.test(m))continue;let f=u.includes(",")||u.trim()===""?`(${u}) => ${c}`:`${u.trim()} => ${c}`;r.push(p(s,a.index,a.index+m.length,f,"Convert callback to arrow function"))}e.debug("func-to-arrow transform completed",{converted:r.length,warnings:o.length});let l=T(s,"func-to-arrow",r,n,.85);return l.warnings=o,l}catch(t){return e.error("func-to-arrow transform failed",t),w(s,"func-to-arrow",t instanceof Error?t.message:"Unknown error",n)}}var V={"var-to-const":Z,"add-types":O,"remove-console":I,"promise-to-async":j,"cjs-to-esm":N,"func-to-arrow":H};function $(s,e,n){let r=V[e];return r?r(s,n):{success:!1,transformType:e,originalCode:s,transformedCode:s,edits:[],changeCount:0,confidence:0,durationMs:0,implementationUsed:"typescript",usedFallback:!1,error:`Unknown transform type: ${e}`,warnings:[]}}var q={JavaScript:0,TypeScript:1,Python:2,Rust:3,Go:4,Java:5,C:6,Cpp:7},y=null,A=null,x=null,k=!1,R=null;async function G(){if(k)return R===null;if(R)return!1;try{let s=await import("./agent-booster-wasm-6RRQWMNE.js");return y=s.transform,A=s.warmup,x=s.isWasmAvailable,k=!0,!0}catch(s){return R=s,k=!0,!1}}function K(s){return q.TypeScript}var L=class{cache=new Map;ttlMs;enabled;constructor(e,n){this.enabled=e,this.ttlMs=n}generateKey(e,n){let r=0;for(let o=0;o<e.length;o++){let t=e.charCodeAt(o);r=(r<<5)-r+t,r=r&r}return`${n}:${r}:${e.length}`}get(e,n){if(!this.enabled)return null;let r=this.generateKey(e,n),o=this.cache.get(r);return o?Date.now()>o.expiresAt?(this.cache.delete(r),null):o.result:null}set(e,n,r){if(!this.enabled)return;let o=this.generateKey(e,n);this.cache.set(o,{result:r,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},v=class{config;logger;cache;enabledTransforms;metricsTracker;initialized=!1;wasmAvailable=!1;wasmModule=null;patternsLoaded=!1;totalTransforms=0;successfulTransforms=0;totalDurationMs=0;cacheHits=0;cacheMisses=0;constructor(e={},n,r){this.config={...z,...e},this.logger=n||{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.metricsTracker=r,this.cache=new L(this.config.cacheEnabled,this.config.cacheTtlMs),this.config.transforms.length===0?this.enabledTransforms=new Set(b):this.enabledTransforms=new Set(this.config.transforms)}setMetricsTracker(e){this.metricsTracker=e}async initialize(){this.initialized||(this.logger.info("Initializing Agent Booster adapter",{enabled:this.config.enabled,transforms:Array.from(this.enabledTransforms)}),this.config.transforms.length===0&&await this.loadEligibleTransformsFromPatterns(),this.config.enabled&&await this.tryLoadWasm(),this.initialized=!0,this.logger.info("Agent Booster adapter initialized",{wasmAvailable:this.wasmAvailable,enabledTransforms:Array.from(this.enabledTransforms),patternsLoaded:this.patternsLoaded}))}async loadEligibleTransformsFromPatterns(){try{let n=await F().getEligibleBoosterTransforms();if(n.length>0){let r=n.filter(o=>b.includes(o));if(r.length>0){this.enabledTransforms=new Set(r),this.patternsLoaded=!0,this.logger.info("Loaded eligible transforms from PatternLoader",{fromPatterns:r,invalidIgnored:n.length-r.length});return}}this.logger.debug("PatternLoader returned empty transforms, using defaults")}catch(e){this.logger.warn("Failed to load transforms from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.enabledTransforms=new Set(b),this.patternsLoaded=!1}async tryLoadWasm(){try{if(this.logger.debug("Loading WASM module"),!await G()||!x){this.logger.debug("WASM module could not be loaded, using TypeScript fallback"),this.wasmAvailable=!1;return}this.logger.debug("Checking WASM availability from local module"),await x()&&y&&A?(this.logger.debug("Warming up WASM module"),await A(),this.wasmModule={transform:y,warmup:A,isAvailable:x},this.wasmAvailable=!0,this.logger.info("WASM Agent Booster loaded and warmed up successfully",{source:"local-module"})):(this.logger.debug("WASM not available from local module, using TypeScript fallback"),this.wasmAvailable=!1)}catch(e){this.logger.warn("Failed to load WASM module",{error:e instanceof Error?e.message:"Unknown error"}),this.wasmAvailable=!1}}async dispose(){this.cache.clear(),this.wasmModule=null,this.wasmAvailable=!1,this.initialized=!1,this.logger.info("Agent Booster adapter disposed")}async transform(e,n){this.ensureInitialized(),this.ensureEnabled();let r=Date.now();if(this.totalTransforms++,!this.enabledTransforms.has(n))return this.createErrorResult(e,n,`Transform type '${n}' is not enabled`,r);let o=this.cache.get(e,n);if(o)return this.cacheHits++,this.logger.debug("Cache hit for transform",{type:n}),{...o,durationMs:Date.now()-r};this.cacheMisses++;let t;try{t=await this.executeWithFallback(e,n,r)}catch(a){return this.createErrorResult(e,n,a instanceof Error?a.message:"Unknown error",r)}return t.success&&(this.successfulTransforms++,this.cache.set(e,n,t)),this.totalDurationMs+=t.durationMs,await this.recordMetrics(t,n),t}async recordMetrics(e,n){if(this.metricsTracker)try{let r=`booster-${n}-${Date.now()}`;await this.metricsTracker.recordOutcome("booster",r,e.success,e.durationMs,{subType:n,confidence:e.confidence,usedFallback:e.usedFallback,implementationUsed:e.implementationUsed,itemCount:e.changeCount,errorMessage:e.error})}catch(r){this.logger.warn("Failed to record metrics",{error:r instanceof Error?r.message:"Unknown error"})}}async executeWithFallback(e,n,r){if(this.wasmAvailable)try{let t=await this.executeWasmTransform(e,n,r);if(t.success&&t.confidence>=this.config.confidenceThreshold)return t;this.logger.debug("WASM transform low confidence, trying TypeScript",{confidence:t.confidence,threshold:this.config.confidenceThreshold})}catch(t){this.logger.warn("WASM transform failed, falling back to TypeScript",{error:t instanceof Error?t.message:"Unknown error"})}let o=$(e,n,this.logger);return o.durationMs=Date.now()-r,this.config.fallbackToLLM&&o.confidence<this.config.confidenceThreshold&&(this.logger.debug("TypeScript transform low confidence, LLM fallback available",{confidence:o.confidence,threshold:this.config.confidenceThreshold}),o.warnings.push(`Confidence ${o.confidence.toFixed(2)} is below threshold ${this.config.confidenceThreshold}. LLM fallback recommended for review.`),o.usedFallback=!0),o}async executeWasmTransform(e,n,r){if(!this.wasmAvailable)throw new C;let o=K(n),t=$(e,n,this.logger);if(t.changeCount===0)return{...t,durationMs:Date.now()-r,implementationUsed:"wasm"};if(!y)throw new C("WASM transform function not loaded");let a=await Promise.race([y(e,t.transformedCode,o,{confidenceThreshold:this.config.confidenceThreshold,allowFallback:!0}),new Promise((m,u)=>setTimeout(()=>u(new P("WASM transform timed out",n,this.config.timeoutMs)),this.config.timeoutMs))]),i=Date.now()-r,l=a.success&&a.mergedCode!==e?t.changeCount:0;return{success:a.success,transformType:n,originalCode:e,transformedCode:a.mergedCode,edits:t.edits,changeCount:l,confidence:a.confidence,durationMs:i,implementationUsed:a.source==="wasm"?"wasm":"typescript",usedFallback:a.source!=="wasm",error:a.error,warnings:a.syntaxValid?[]:["WASM reported syntax may be invalid"]}}async batchTransform(e,n){this.ensureInitialized(),this.ensureEnabled();let r=Date.now(),o=[],t=[],a=0,i=0,l=0,m=0;for(let u of e){if(u.content.length>this.config.maxFileSizeBytes){let c=new B(u.path,u.content.length,this.config.maxFileSizeBytes);t.push({path:u.path,error:c.message}),i++;continue}try{let c=await this.transform(u.content,n);o.push({path:u.path,result:c}),c.success?c.changeCount>0?(a++,m+=c.changeCount):l++:(i++,c.error&&t.push({path:u.path,error:c.error}))}catch(c){i++,t.push({path:u.path,error:c instanceof Error?c.message:"Unknown error"})}}return{success:i===0,transformType:n,files:o,totalFiles:e.length,successCount:a,failureCount:i,noChangeCount:l,totalChanges:m,durationMs:Date.now()-r,errors:t}}async detectTransformOpportunities(e){this.ensureInitialized(),this.ensureEnabled();let n=Date.now(),r=[],o={},t=[];for(let a of b)o[a]=0;for(let a of Array.from(this.enabledTransforms))try{let i=await this.transform(e,a);if(i.changeCount>0)for(let l of i.edits){let m={type:a,confidence:i.confidence,location:l.start,codeSnippet:l.oldText.slice(0,100)+(l.oldText.length>100?"...":""),suggestedCode:l.newText.slice(0,100)+(l.newText.length>100?"...":""),reason:l.description,risk:this.confidenceToRisk(i.confidence),estimatedDurationMs:E[a].typicalLatencyMs};r.push(m),o[a]++}}catch(i){t.push(`Failed to analyze for ${a}: ${i instanceof Error?i.message:"Unknown error"}`)}return r.sort((a,i)=>i.confidence-a.confidence),{opportunities:r,totalCount:r.length,byType:o,durationMs:Date.now()-n,complete:t.length===0,warnings:t}}isTransformAvailable(e){return this.enabledTransforms.has(e)}getTransformMetadata(e){return E[e]}getAvailableTransforms(){return Array.from(this.enabledTransforms)}isWasmAvailable(){return this.wasmAvailable}getHealth(){let e=this.totalTransforms>0?this.totalDurationMs/this.totalTransforms:0,n=this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0,r=[];return this.initialized||r.push("Adapter not initialized"),this.config.enabled||r.push("Adapter is disabled"),this.wasmAvailable||r.push("WASM module not loaded (using TypeScript fallback)"),this.patternsLoaded||r.push("Patterns not loaded from PatternLoader (using defaults)"),{ready:this.initialized&&this.config.enabled,wasmAvailable:this.wasmAvailable,patternsLoaded:this.patternsLoaded,availableTransforms:Array.from(this.enabledTransforms),lastChecked:new Date,issues:r,metrics:{totalTransforms:this.totalTransforms,successfulTransforms:this.successfulTransforms,averageDurationMs:e,cacheHitRate:n}}}ensureInitialized(){if(!this.initialized)throw new M("AgentBoosterAdapter not initialized. Call initialize() first.","var-to-const")}ensureEnabled(){if(!this.config.enabled)throw new M("AgentBoosterAdapter is disabled. Set enabled: true in config.","var-to-const")}createErrorResult(e,n,r,o){return{success:!1,transformType:n,originalCode:e,transformedCode:e,edits:[],changeCount:0,confidence:0,durationMs:Date.now()-o,implementationUsed:"typescript",usedFallback:!1,error:r,warnings:[]}}confidenceToRisk(e){return e>=.95?"info":e>=.85?"low":e>=.7?"medium":e>=.5?"high":"critical"}};async function ee(s={},e,n){let r=new v(s,e,n);return await r.initialize(),r}function re(s={},e,n){return new v(s,e,n)}export{v as a,ee as b,re 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.12");process.exit(0)}
2
- import{b as t}from"./chunk-WDEXOLK2.js";function o(e){try{return e.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.13");process.exit(0)}
2
+ import{b as t}from"./chunk-ZAKQLAHT.js";function o(e){try{return e.prepare(`
3
3
  SELECT COUNT(*) as count FROM sqlite_master
4
4
  WHERE type='table' AND name IN ('hypergraph_nodes', 'hypergraph_edges')
5
5
  `).get().count===2}catch{return!1}}var r,a,E,n,p=t(()=>{"use strict";r=`