agentic-qe 3.12.0 → 3.12.2

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 (362) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +83 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/cli/bundle.js +5 -5
  5. package/dist/cli/chunks/adapter-RL6GNUOS.js +2 -0
  6. package/dist/cli/chunks/{agent-booster-wasm-IO54X6IQ.js → agent-booster-wasm-3KYNICBC.js} +2 -2
  7. package/dist/cli/chunks/{agent-handler-A57SZUCW.js → agent-handler-NGPTMI6E.js} +2 -2
  8. package/dist/cli/chunks/{agent-memory-branch-BX7LRFGN.js → agent-memory-branch-GNTQKQMG.js} +2 -2
  9. package/dist/cli/chunks/aqe-learning-engine-UEEW6AQG.js +2 -0
  10. package/dist/cli/chunks/{arena-UTC4YY6Y.js → arena-HQEP2NWI.js} +4 -4
  11. package/dist/cli/chunks/{arena-Y3XTX6O7.js → arena-PA7VIYD4.js} +2 -2
  12. package/dist/cli/chunks/{audit-L4RL2AOY.js → audit-XSDM57GC.js} +3 -3
  13. package/dist/cli/chunks/base-JQA5YULE.js +2 -0
  14. package/dist/cli/chunks/{hnswlib-node-VS6L5VUG.js → better-sqlite3-RQCOOAZC.js} +2 -2
  15. package/dist/cli/chunks/{brain-handler-OHDPI5TQ.js → brain-handler-T7RDPKNM.js} +3 -3
  16. package/dist/cli/chunks/{branch-enumerator-ZRXE2CQ7.js → branch-enumerator-ZW7RNMUF.js} +2 -2
  17. package/dist/cli/chunks/{browser-NT33FG76.js → browser-4LU22CPP.js} +2 -2
  18. package/dist/cli/chunks/browser-workflow-XTKUHTIT.js +2 -0
  19. package/dist/cli/chunks/{chunk-XEYW3V5I.js → chunk-2L7K2J2T.js} +2 -2
  20. package/dist/cli/chunks/{chunk-VWJSWXHG.js → chunk-2R7J4ZGT.js} +1 -1
  21. package/dist/cli/chunks/{chunk-KZMRU7DL.js → chunk-2R7XZ2WP.js} +2 -2
  22. package/dist/cli/chunks/{chunk-2AR4B3DI.js → chunk-327YEKBU.js} +2 -2
  23. package/dist/cli/chunks/{chunk-HDJMD6UH.js → chunk-3AJUJAUJ.js} +1 -1
  24. package/dist/cli/chunks/{chunk-JOBCMNTP.js → chunk-3LELACAQ.js} +2 -2
  25. package/dist/cli/chunks/{chunk-JYX7AZHE.js → chunk-4FHJYJCH.js} +2 -2
  26. package/dist/cli/chunks/{chunk-KJWQ7ENF.js → chunk-4KEOBDEI.js} +2 -2
  27. package/dist/cli/chunks/{chunk-G6LR7FK7.js → chunk-56MXYSYY.js} +2 -2
  28. package/dist/cli/chunks/{chunk-5YGESYBC.js → chunk-5CGTBAVF.js} +1 -1
  29. package/dist/cli/chunks/{chunk-RZDNCTOA.js → chunk-5SM57X4D.js} +2 -2
  30. package/dist/cli/chunks/{chunk-O3C5RRDQ.js → chunk-5YLY2WT2.js} +3 -3
  31. package/dist/cli/chunks/{chunk-PQMLIVGV.js → chunk-6FBXYS6X.js} +2 -2
  32. package/dist/cli/chunks/{chunk-GGMQOEZZ.js → chunk-6N62KS3C.js} +2 -2
  33. package/dist/cli/chunks/{chunk-BB4OVXWF.js → chunk-6SWR2BN7.js} +1 -1
  34. package/dist/cli/chunks/{chunk-7HJHXSYT.js → chunk-6X65BGGK.js} +2 -2
  35. package/dist/cli/chunks/{chunk-P52YORQG.js → chunk-7DV42KFP.js} +2 -2
  36. package/dist/cli/chunks/{chunk-EZE2HRQB.js → chunk-7KMYBRKJ.js} +2 -2
  37. package/dist/cli/chunks/{chunk-335GHVJV.js → chunk-7OD6HFCP.js} +3 -3
  38. package/dist/cli/chunks/chunk-ABHKXMOJ.js +2 -0
  39. package/dist/cli/chunks/{chunk-L5ZLOW3K.js → chunk-ACDZ2CRV.js} +2 -2
  40. package/dist/cli/chunks/{chunk-NW7G57NR.js → chunk-ADZTWGEB.js} +2 -2
  41. package/dist/cli/chunks/{chunk-CC5G3K4X.js → chunk-AJ6DZXKK.js} +2 -2
  42. package/dist/cli/chunks/{chunk-SSXAW3ER.js → chunk-AL5QT6OX.js} +2 -2
  43. package/dist/cli/chunks/{chunk-FKPUPQQT.js → chunk-AMPYON7M.js} +2 -2
  44. package/dist/cli/chunks/{chunk-C4SZSPXY.js → chunk-APVXTHTA.js} +2 -2
  45. package/dist/cli/chunks/{chunk-FEEMJDUF.js → chunk-B7DI76SY.js} +2 -2
  46. package/dist/cli/chunks/{chunk-Q5YRPS4P.js → chunk-BDVOXGY5.js} +1 -1
  47. package/dist/cli/chunks/{chunk-VMP4M5PB.js → chunk-BDX54WJV.js} +1 -1
  48. package/dist/cli/chunks/{chunk-G5JQLUUO.js → chunk-BMRR3MBR.js} +2 -2
  49. package/dist/cli/chunks/{chunk-2UMCB7AH.js → chunk-BOR5MME3.js} +1 -1
  50. package/dist/cli/chunks/{chunk-HW62TB4T.js → chunk-BPSEFLJ6.js} +1 -1
  51. package/dist/cli/chunks/{chunk-DTOE3NYW.js → chunk-BUKGW63B.js} +12 -12
  52. package/dist/cli/chunks/{chunk-V2MD5EDD.js → chunk-C7VNQ4PY.js} +2 -2
  53. package/dist/cli/chunks/{chunk-W766S4SK.js → chunk-CDMAVNV5.js} +1 -1
  54. package/dist/cli/chunks/{chunk-K5SN66B4.js → chunk-CKFZOPZN.js} +2 -2
  55. package/dist/cli/chunks/{chunk-Y2MCIIJD.js → chunk-CMKCPRWX.js} +1 -1
  56. package/dist/cli/chunks/{chunk-DR7PCO3S.js → chunk-CQKEVUMO.js} +2 -2
  57. package/dist/cli/chunks/{chunk-2KHDGC7N.js → chunk-CTFW7CMI.js} +2 -2
  58. package/dist/cli/chunks/{chunk-5FR5GBUT.js → chunk-DGOZ3CGB.js} +2 -2
  59. package/dist/cli/chunks/{chunk-ZVPAFX4I.js → chunk-DTXHRALB.js} +2 -2
  60. package/dist/cli/chunks/{chunk-IJUYHIKN.js → chunk-E5XWCGSX.js} +2 -2
  61. package/dist/cli/chunks/{chunk-7ZIVDGSN.js → chunk-EGU54SNK.js} +1 -1
  62. package/dist/cli/chunks/{chunk-KI5BP4X5.js → chunk-EKTWIEEO.js} +2 -2
  63. package/dist/cli/chunks/{chunk-TJ6N4CCX.js → chunk-ERQL3D2O.js} +2 -2
  64. package/dist/cli/chunks/{chunk-CHO54B34.js → chunk-EZ3JVN6S.js} +2 -2
  65. package/dist/cli/chunks/{chunk-5VBPIJUZ.js → chunk-F3CKOVZM.js} +4 -4
  66. package/dist/cli/chunks/{chunk-RQN4HWGV.js → chunk-FKUH33L3.js} +2 -2
  67. package/dist/cli/chunks/{chunk-WNASEUBW.js → chunk-FTG4ZVTX.js} +11 -11
  68. package/dist/cli/chunks/{chunk-CMGYUCM7.js → chunk-FUBN5GPY.js} +1 -1
  69. package/dist/cli/chunks/{chunk-I6WHYRWB.js → chunk-GCQATSMK.js} +2 -2
  70. package/dist/cli/chunks/{chunk-TED4KOSK.js → chunk-GECWGFRR.js} +2 -2
  71. package/dist/cli/chunks/{chunk-BA6U7NSR.js → chunk-GP7IXYOY.js} +1 -1
  72. package/dist/cli/chunks/{chunk-CSEEGX5T.js → chunk-GUGUYFU5.js} +2 -2
  73. package/dist/cli/chunks/{chunk-KZ37VHMJ.js → chunk-HH5Y4NCR.js} +2 -2
  74. package/dist/cli/chunks/{chunk-DXOMRWDC.js → chunk-HNU32LN3.js} +1 -1
  75. package/dist/cli/chunks/{chunk-3AFNXU45.js → chunk-HU6ETNA7.js} +1 -1
  76. package/dist/cli/chunks/{chunk-KN5GOEYK.js → chunk-IKIKIHFQ.js} +2 -2
  77. package/dist/cli/chunks/{chunk-UGJQJSPB.js → chunk-ILNQPPKB.js} +1 -1
  78. package/dist/cli/chunks/{chunk-MJPYNGZ7.js → chunk-IQ56KMMH.js} +1 -1
  79. package/dist/cli/chunks/{chunk-SCMXIBI7.js → chunk-J6EFAKDQ.js} +2 -2
  80. package/dist/cli/chunks/{chunk-RMFRFING.js → chunk-K43YXI7C.js} +2 -2
  81. package/dist/cli/chunks/{chunk-FOPS6DRZ.js → chunk-KBAXD6PH.js} +1 -1
  82. package/dist/cli/chunks/{chunk-VS4GMNJK.js → chunk-KBXW7S3W.js} +3 -3
  83. package/dist/cli/chunks/{chunk-QJ6H2HQQ.js → chunk-KDGLNJPB.js} +1 -1
  84. package/dist/cli/chunks/{chunk-VA7TEOPM.js → chunk-KJJP446A.js} +1 -1
  85. package/dist/cli/chunks/{chunk-TC2JE5OK.js → chunk-KNOO6TFO.js} +3 -3
  86. package/dist/cli/chunks/{chunk-HAEUPIKW.js → chunk-KPV4N4KT.js} +2 -2
  87. package/dist/cli/chunks/{chunk-IKVNYK7Y.js → chunk-KV5OZ6T3.js} +2 -2
  88. package/dist/cli/chunks/{chunk-RG552ROA.js → chunk-LGEPR7MH.js} +3 -3
  89. package/dist/cli/chunks/{chunk-7WX3MKRS.js → chunk-LIAW5FD7.js} +2 -2
  90. package/dist/cli/chunks/{chunk-MUV56BPK.js → chunk-LOZAUP6L.js} +2 -2
  91. package/dist/cli/chunks/{chunk-BUYPRUNY.js → chunk-LWVUNBZO.js} +2 -2
  92. package/dist/cli/chunks/{chunk-FZRU73M4.js → chunk-M4XVEUUM.js} +2 -2
  93. package/dist/cli/chunks/{chunk-ICK3B24H.js → chunk-MALFTRCT.js} +2 -2
  94. package/dist/cli/chunks/{chunk-MBF3Q7FQ.js → chunk-MF4FULAI.js} +1 -1
  95. package/dist/cli/chunks/{chunk-7F7U2HUH.js → chunk-MNHGBG4D.js} +1 -1
  96. package/dist/cli/chunks/{chunk-XIFPIVZI.js → chunk-MNNNA57O.js} +2 -2
  97. package/dist/cli/chunks/{chunk-BZPF6GTL.js → chunk-N57BKUVE.js} +1 -1
  98. package/dist/cli/chunks/{chunk-TO5PQSDD.js → chunk-NDAJWCXN.js} +2 -2
  99. package/dist/cli/chunks/{chunk-NLHISTL2.js → chunk-OELLHV7S.js} +2 -2
  100. package/dist/cli/chunks/{chunk-PM566XEO.js → chunk-OEZNUXY7.js} +1 -1
  101. package/dist/cli/chunks/{chunk-4GU656WM.js → chunk-OIUIVV2N.js} +1 -1
  102. package/dist/cli/chunks/{chunk-CVGXB7IX.js → chunk-OMIGKGJJ.js} +2 -2
  103. package/dist/cli/chunks/{chunk-62RELCU6.js → chunk-OSAPKOGN.js} +1 -1
  104. package/dist/cli/chunks/{chunk-72VZGAMJ.js → chunk-P2FYRAC5.js} +1 -1
  105. package/dist/cli/chunks/{chunk-W2OMW6UU.js → chunk-P65S7AZA.js} +2 -2
  106. package/dist/cli/chunks/{chunk-VZ67ZDB3.js → chunk-PHIEJAQK.js} +3 -3
  107. package/dist/cli/chunks/chunk-PSA2SOON.js +18 -0
  108. package/dist/cli/chunks/{chunk-USB44IHJ.js → chunk-PXKVW6PT.js} +2 -2
  109. package/dist/cli/chunks/{chunk-64M3FFM4.js → chunk-QYST2TZW.js} +2 -2
  110. package/dist/cli/chunks/{chunk-MUAHFGIX.js → chunk-R554WVIG.js} +2 -2
  111. package/dist/cli/chunks/{chunk-TJEJ4UVX.js → chunk-R5HC6JVJ.js} +2 -2
  112. package/dist/cli/chunks/{chunk-6X3RJBA3.js → chunk-R6LDR3IO.js} +2 -2
  113. package/dist/cli/chunks/{chunk-OPIWFXME.js → chunk-RFQIC6ZF.js} +1 -1
  114. package/dist/cli/chunks/{chunk-EM2JIIAQ.js → chunk-RXEQB4OT.js} +2 -2
  115. package/dist/cli/chunks/{chunk-BGRJZH5Q.js → chunk-RXH2TC2K.js} +2 -2
  116. package/dist/cli/chunks/{chunk-DQDFACYW.js → chunk-SVUWAV6Y.js} +1 -1
  117. package/dist/cli/chunks/{chunk-POKMJTD2.js → chunk-SYLTJKN2.js} +1 -1
  118. package/dist/cli/chunks/{chunk-WJYTLRA5.js → chunk-T6TQPF5P.js} +3 -3
  119. package/dist/cli/chunks/{chunk-FI5SSLEF.js → chunk-T75VH6NT.js} +2 -2
  120. package/dist/cli/chunks/{chunk-EGH3H7QO.js → chunk-TERRRQVY.js} +1 -1
  121. package/dist/cli/chunks/{chunk-2ALNNXFF.js → chunk-TFVWUR2U.js} +2 -2
  122. package/dist/cli/chunks/{chunk-MK3J7JVZ.js → chunk-TLYZPOA7.js} +2 -2
  123. package/dist/cli/chunks/{chunk-RYUSZ43T.js → chunk-TMQ3S7HR.js} +1 -1
  124. package/dist/cli/chunks/{chunk-Z3W3R4CW.js → chunk-TQNNKW7K.js} +2 -2
  125. package/dist/cli/chunks/{chunk-PT3FTGKZ.js → chunk-TRHUH24V.js} +2 -2
  126. package/dist/cli/chunks/{chunk-5XFX25AJ.js → chunk-UEIIIDBJ.js} +2 -2
  127. package/dist/cli/chunks/{chunk-YKOTOCO6.js → chunk-UF3YOGHV.js} +2 -2
  128. package/dist/cli/chunks/{chunk-UUOXV3NS.js → chunk-UFPCNUJA.js} +10 -10
  129. package/dist/cli/chunks/{chunk-FZIHOMGY.js → chunk-V2QYW5KW.js} +2 -2
  130. package/dist/cli/chunks/{chunk-AAATFEIL.js → chunk-VHYACXLN.js} +2 -2
  131. package/dist/cli/chunks/chunk-VM6VBRRU.js +43 -0
  132. package/dist/cli/chunks/{chunk-ZT2WHCVM.js → chunk-VOHYQ6MX.js} +2 -2
  133. package/dist/cli/chunks/{chunk-C6GYLCTX.js → chunk-VQU2JXTK.js} +3 -3
  134. package/dist/cli/chunks/{chunk-FU5RNEXV.js → chunk-W7LBT3BF.js} +2 -2
  135. package/dist/cli/chunks/{chunk-GCF42L7M.js → chunk-WC5PM33J.js} +3 -3
  136. package/dist/cli/chunks/{chunk-WT4ZDDFM.js → chunk-WE5QHYL7.js} +1 -1
  137. package/dist/cli/chunks/chunk-WKWIUS5G.js +3 -0
  138. package/dist/cli/chunks/chunk-WL5VMIO4.js +2 -0
  139. package/dist/cli/chunks/{chunk-OHSVDMF7.js → chunk-WMNGPIP3.js} +1 -1
  140. package/dist/cli/chunks/{chunk-UVVKFBF7.js → chunk-WRMUQVKY.js} +2 -2
  141. package/dist/cli/chunks/{chunk-NNGCUJWQ.js → chunk-WY5CX3VH.js} +2 -2
  142. package/dist/cli/chunks/{chunk-36MPDANH.js → chunk-WYFEVPLO.js} +1 -1
  143. package/dist/cli/chunks/{chunk-RHC7TFPU.js → chunk-X47GHZY3.js} +2 -2
  144. package/dist/cli/chunks/{chunk-TR5GOGH3.js → chunk-XNNYHQLW.js} +5 -5
  145. package/dist/cli/chunks/{chunk-27JCWG5J.js → chunk-YDZIPP3Y.js} +2 -2
  146. package/dist/cli/chunks/{chunk-KDLYTJ5C.js → chunk-YRO7HNS4.js} +2 -2
  147. package/dist/cli/chunks/{chunk-SPEUF7ZL.js → chunk-YSCEUK55.js} +2 -2
  148. package/dist/cli/chunks/chunk-YY4KXDI6.js +2 -0
  149. package/dist/cli/chunks/{chunk-ZWC6CM4R.js → chunk-YYV3FYVB.js} +1 -1
  150. package/dist/cli/chunks/{chunk-AEX75YGI.js → chunk-YZ44FUVJ.js} +2 -2
  151. package/dist/cli/chunks/chunk-Z3FA5KR6.js +316 -0
  152. package/dist/cli/chunks/{chunk-G6RKUEGL.js → chunk-Z63IOTDW.js} +2 -2
  153. package/dist/cli/chunks/{chunk-6JNNZGI2.js → chunk-ZBYMF2QJ.js} +1 -1
  154. package/dist/cli/chunks/{chunk-JYXSVSH2.js → chunk-ZF65VOQH.js} +2 -2
  155. package/dist/cli/chunks/{chunk-4SALW7OT.js → chunk-ZHWXI4SK.js} +2 -2
  156. package/dist/cli/chunks/{chunk-LMJUQWR7.js → chunk-ZL7ZOIHO.js} +1 -1
  157. package/dist/cli/chunks/{ci-RJH5LAL3.js → ci-NT4DUGQ4.js} +2 -2
  158. package/dist/cli/chunks/{ci-output-62SGMGB2.js → ci-output-PXBD2QPH.js} +2 -2
  159. package/dist/cli/chunks/{circuit-breaker-QXTS5ZAW.js → circuit-breaker-ZPCCEEDX.js} +2 -2
  160. package/dist/cli/chunks/{claude-flow-setup-BBCCT5WV.js → claude-flow-setup-CZCDFZOE.js} +2 -2
  161. package/dist/cli/chunks/client-S7DIRNFJ.js +2 -0
  162. package/dist/cli/chunks/{cline-installer-IZCUJJ3I.js → cline-installer-6J2S7GLM.js} +2 -2
  163. package/dist/cli/chunks/{code-AWNVOZ7S.js → code-UTERK5AP.js} +2 -2
  164. package/dist/cli/chunks/{code-index-extractor-MX65BKMI.js → code-index-extractor-O3MJTOS2.js} +2 -2
  165. package/dist/cli/chunks/{codex-installer-EQT6JVLM.js → codex-installer-AZJIVXJR.js} +2 -2
  166. package/dist/cli/chunks/{completions-WOJAM45W.js → completions-A6ANQSZN.js} +2 -2
  167. package/dist/cli/chunks/{complexity-analyzer-3DJB7V3K.js → complexity-analyzer-MRSN7VUP.js} +2 -2
  168. package/dist/cli/chunks/{continuedev-installer-P4KWUTCJ.js → continuedev-installer-6LMKQRUI.js} +2 -2
  169. package/dist/cli/chunks/{copilot-installer-FFZWTMWQ.js → copilot-installer-KP3TWUNO.js} +2 -2
  170. package/dist/cli/chunks/core-handlers-NM2KCI6Z.js +2 -0
  171. package/dist/cli/chunks/{cost-tracker-CYBOV3NI.js → cost-tracker-R3C5IQPZ.js} +2 -2
  172. package/dist/cli/chunks/{coverage-GTZJBSC4.js → coverage-MR4QA2NM.js} +3 -3
  173. package/dist/cli/chunks/cross-domain-router-3TSZMCBM.js +2 -0
  174. package/dist/cli/chunks/{cursor-installer-WZIVXGGB.js → cursor-installer-LPZ7NGOS.js} +2 -2
  175. package/dist/cli/chunks/{daemon-JWMHEJEN.js → daemon-K3KW2UDV.js} +4 -4
  176. package/dist/cli/chunks/{daemon-MSFN2LXY.js → daemon-X5KXHRY3.js} +3 -3
  177. package/dist/cli/chunks/{dag-attention-scheduler-4TWOTTQE.js → dag-attention-scheduler-J4FJSGNN.js} +2 -2
  178. package/dist/cli/chunks/{detect-YZ6AGQPB.js → detect-22TX2NCA.js} +2 -2
  179. package/dist/cli/chunks/{dist-node-3EM2XH54.js → dist-node-QI4I4QPS.js} +2 -2
  180. package/dist/cli/chunks/{domain-handler-4XU5BINU.js → domain-handler-ZYZGPNOQ.js} +2 -2
  181. package/dist/cli/chunks/{domain-transfer-HUFC7I52.js → domain-transfer-2EEQTNIU.js} +2 -2
  182. package/dist/cli/chunks/dream-QIIJONYI.js +2 -0
  183. package/dist/cli/chunks/{embed-and-insert-pattern-J5ZFM6YX.js → embed-and-insert-pattern-LYCTU5BS.js} +2 -2
  184. package/dist/cli/chunks/eval-SOA72GUX.js +17 -0
  185. package/dist/cli/chunks/{experience-capture-middleware-E3RYQB6Z.js → experience-capture-middleware-AFFYOMYM.js} +3 -3
  186. package/dist/cli/chunks/{fast-paths-DKIYN2YS.js → fast-paths-WNMHOSUH.js} +2 -2
  187. package/dist/cli/chunks/{feature-flags-ZB63Z7N5.js → feature-flags-FT4YBZH4.js} +2 -2
  188. package/dist/cli/chunks/{feature-flags-S2RNZATS.js → feature-flags-HAP5IAAY.js} +2 -2
  189. package/dist/cli/chunks/{file-discovery-USJJLYQU.js → file-discovery-B4FFOH3Z.js} +2 -2
  190. package/dist/cli/chunks/{fleet-4MUPHSF5.js → fleet-2ICPYV3J.js} +3 -3
  191. package/dist/cli/chunks/{gnn-wrapper-PYOQZKX6.js → gnn-wrapper-XIBJAHMW.js} +2 -2
  192. package/dist/cli/chunks/{heartbeat-handler-HLO5XCG7.js → heartbeat-handler-NSLSKDOI.js} +4 -4
  193. package/dist/cli/chunks/heartbeat-scheduler-CDNGLJJO.js +2 -0
  194. package/dist/cli/chunks/hnsw-adapter-CR7Y4OAM.js +2 -0
  195. package/dist/cli/chunks/hnsw-index-TEDO4MQC.js +2 -0
  196. package/dist/cli/chunks/{hnsw-legacy-bridge-FZEH2KLM.js → hnsw-legacy-bridge-FTV4CCBB.js} +2 -2
  197. package/dist/cli/chunks/{better-sqlite3-LRDXKYOJ.js → hnswlib-node-BCASOCNU.js} +2 -2
  198. package/dist/cli/chunks/{hooks-R2757K57.js → hooks-SM4EU52N.js} +10 -10
  199. package/dist/cli/chunks/hybrid-router-O24ZDIP5.js +2 -0
  200. package/dist/cli/chunks/{hypergraph-engine-EAV3GJ5D.js → hypergraph-engine-RRMX4N3L.js} +2 -2
  201. package/dist/cli/chunks/{hypergraph-handler-5ERXAVGH.js → hypergraph-handler-MNFGDKAP.js} +3 -3
  202. package/dist/cli/chunks/impact-analyzer-PDM4SDB6.js +2 -0
  203. package/dist/cli/chunks/{init-handler-RXUSEMG7.js → init-handler-BNHIJ5TX.js} +6 -6
  204. package/dist/cli/chunks/init-wizard-F4KODPNW.js +2 -0
  205. package/dist/cli/chunks/kernel-77UM35L6.js +2 -0
  206. package/dist/cli/chunks/{kilocode-installer-ZUBVBHGT.js → kilocode-installer-GFKUKPLY.js} +2 -2
  207. package/dist/cli/chunks/{kiro-installer-TRTRQDGL.js → kiro-installer-YBIYKODN.js} +2 -2
  208. package/dist/cli/chunks/knowledge-graph-R6ZWWV2K.js +2 -0
  209. package/dist/cli/chunks/{learning-UYXWAU5D.js → learning-QEWUPCK6.js} +3 -3
  210. package/dist/cli/chunks/{llm-router-TB5OJPEV.js → llm-router-D5FQIMVQ.js} +5 -5
  211. package/dist/cli/chunks/llm-router-service-7QYCZ66H.js +2 -0
  212. package/dist/cli/chunks/{load-ELPSUIPV.js → load-CLBUCKZQ.js} +2 -2
  213. package/dist/cli/chunks/load-test-AWVA3CAQ.js +2 -0
  214. package/dist/cli/chunks/{mcp-UX7TK3XV.js → mcp-VOMG5DPV.js} +2 -2
  215. package/dist/cli/chunks/{memory-W3LG6H6N.js → memory-WZO63VSC.js} +5 -5
  216. package/dist/cli/chunks/memory-backend-YESSIHFW.js +2 -0
  217. package/dist/cli/chunks/memory-handlers-EOOWSUHI.js +2 -0
  218. package/dist/cli/chunks/{multi-model-executor-227LWZRY.js → multi-model-executor-7UKW43VV.js} +2 -2
  219. package/dist/cli/chunks/{opencode-installer-F4WKVWDL.js → opencode-installer-MLFPRRL2.js} +2 -2
  220. package/dist/cli/chunks/{orchestrator-V4DBMGK6.js → orchestrator-XNYDBGIN.js} +18 -18
  221. package/dist/cli/chunks/pattern-null-store-X3UXLJNL.js +2 -0
  222. package/dist/cli/chunks/{pattern-usage-recorder-BY3HEWSU.js → pattern-usage-recorder-ZAP7ASQI.js} +2 -2
  223. package/dist/cli/chunks/{pipeline-3F5RIESX.js → pipeline-4EJYOPBC.js} +2 -2
  224. package/dist/cli/chunks/{platform-KCGXTZO3.js → platform-ALPOWCOH.js} +2 -2
  225. package/dist/cli/chunks/{plugin-2H552KOV.js → plugin-S2RX3KHR.js} +2 -2
  226. package/dist/cli/chunks/{prime-radiant-advanced-wasm-EFKVL7VN.js → prime-radiant-advanced-wasm-P2JB73XX.js} +2 -2
  227. package/dist/cli/chunks/protocol-executor-KXDCTMWI.js +2 -0
  228. package/dist/cli/chunks/{protocol-handler-ELGYV7D2.js → protocol-handler-ZBJXSESA.js} +2 -2
  229. package/dist/cli/chunks/{prove-AYJCQYNI.js → prove-MYJ5YV45.js} +2 -2
  230. package/dist/cli/chunks/provider-manager-XJZVHYI6.js +2 -0
  231. package/dist/cli/chunks/qe-reasoning-bank-DPHPNIC6.js +2 -0
  232. package/dist/cli/chunks/{quality-HH7L5A7V.js → quality-NIACQC4M.js} +2 -2
  233. package/dist/cli/chunks/{quality-gate-NAQLXE4C.js → quality-gate-OAZ23ON5.js} +3 -3
  234. package/dist/cli/chunks/queen-coordinator-EVGWME5C.js +2 -0
  235. package/dist/cli/chunks/{real-embeddings-IO3F4ZFR.js → real-embeddings-6I4LP7PL.js} +2 -2
  236. package/dist/cli/chunks/{roocode-installer-X4TU5HO4.js → roocode-installer-LRQHP6MK.js} +2 -2
  237. package/dist/cli/chunks/router-R2N7TMAS.js +2 -0
  238. package/dist/cli/chunks/routing-feedback-G6W3H26L.js +2 -0
  239. package/dist/cli/chunks/{routing-handler-ZJKGDDMT.js → routing-handler-A7BW7MV4.js} +2 -2
  240. package/dist/cli/chunks/{ruvector-commands-NXCSUBN2.js → ruvector-commands-ZDRRFSJS.js} +2 -2
  241. package/dist/cli/chunks/{rvf-dual-writer-JMA74SKP.js → rvf-dual-writer-QWE3Z6BB.js} +2 -2
  242. package/dist/cli/chunks/{rvf-migration-adapter-BNTGH2KU.js → rvf-migration-adapter-6UDAP7QB.js} +2 -2
  243. package/dist/cli/chunks/{rvf-migration-coordinator-7T2HHUOH.js → rvf-migration-coordinator-FEW2N4R4.js} +2 -2
  244. package/dist/cli/chunks/rvf-native-adapter-D7R2GWXK.js +2 -0
  245. package/dist/cli/chunks/safe-db-CQZGF2KA.js +2 -0
  246. package/dist/cli/chunks/schedule-UP7E3LRC.js +2 -0
  247. package/dist/cli/chunks/scheduler-ENIZHYSL.js +2 -0
  248. package/dist/cli/chunks/{security-XSK2QHB3.js → security-KFXBV65O.js} +3 -3
  249. package/dist/cli/chunks/{shared-rvf-adapter-WLRKI7RY.js → shared-rvf-adapter-HDDCXCHY.js} +2 -2
  250. package/dist/cli/chunks/{shared-rvf-dual-writer-SZW3J7ZK.js → shared-rvf-dual-writer-CXXTB7CU.js} +2 -2
  251. package/dist/cli/chunks/sqlite-persistence-CEVJVWS5.js +2 -0
  252. package/dist/cli/chunks/status-handler-CXSVM236.js +47 -0
  253. package/dist/cli/chunks/{structural-health-4SJCFX63.js → structural-health-LMHSM7MJ.js} +2 -2
  254. package/dist/cli/chunks/{sync-7WAVNZGL.js → sync-DMOUY2EY.js} +2 -2
  255. package/dist/cli/chunks/{sync-ATR4DUSA.js → sync-REEFKICL.js} +2 -2
  256. package/dist/cli/chunks/{task-handler-O6REL34Y.js → task-handler-DMSNFIH3.js} +2 -2
  257. package/dist/cli/chunks/{task-handlers-WFV2ZYWW.js → task-handlers-3Z3QV7X7.js} +3 -3
  258. package/dist/cli/chunks/{test-4LXUVHEU.js → test-U6CGMDLN.js} +4 -4
  259. package/dist/cli/chunks/{test-scheduling-OTN3DMKY.js → test-scheduling-YHYA3BP5.js} +3 -3
  260. package/dist/cli/chunks/{token-bootstrap-VA7T4P42.js → token-bootstrap-MQCTJURQ.js} +2 -2
  261. package/dist/cli/chunks/{token-usage-TLT6OXXR.js → token-usage-EOOTM7Q3.js} +2 -2
  262. package/dist/cli/chunks/{transformers-JI7LZRQ3.js → transformers-EKDJW2H6.js} +2 -2
  263. package/dist/cli/chunks/{tree-sitter-wasm-parser-QNIMHB4K.js → tree-sitter-wasm-parser-HTGAXDQA.js} +2 -2
  264. package/dist/cli/chunks/{types-DJNWOAC6.js → types-GLRXY4RY.js} +2 -2
  265. package/dist/cli/chunks/unified-memory-PXOQ4N53.js +2 -0
  266. package/dist/cli/chunks/unified-memory-hnsw-VEXD6ASE.js +2 -0
  267. package/dist/cli/chunks/unified-persistence-46G6MZYC.js +2 -0
  268. package/dist/cli/chunks/{upgrade-VEW4FL23.js → upgrade-KU55H77X.js} +2 -2
  269. package/dist/cli/chunks/{validate-O3P6PF7B.js → validate-26VSBOJN.js} +2 -2
  270. package/dist/cli/chunks/{validate-swarm-M2HXHZVC.js → validate-swarm-OIALRDKF.js} +2 -2
  271. package/dist/cli/chunks/{vibium-GOU55LUO.js → vibium-LOTWW25P.js} +2 -2
  272. package/dist/cli/chunks/visual-security-4X3T3MFL.js +2 -0
  273. package/dist/cli/chunks/{web-tree-sitter-MXOI4GH3.js → web-tree-sitter-6LWPPBYU.js} +2 -2
  274. package/dist/cli/chunks/{windsurf-installer-6GKT53IH.js → windsurf-installer-ILOQYENG.js} +2 -2
  275. package/dist/cli/chunks/witness-chain-XW4S3LVW.js +2 -0
  276. package/dist/cli/chunks/{witness-chain-OXGQGL26.js → witness-chain-YBS6OHS4.js} +2 -2
  277. package/dist/cli/chunks/{witness-key-manager-PGFSQXUJ.js → witness-key-manager-SI3WV3ZQ.js} +2 -2
  278. package/dist/cli/chunks/{workflow-ENBWRMBA.js → workflow-GY6SJRQW.js} +4 -4
  279. package/dist/cli/chunks/workflow-orchestrator-IIVV6TCP.js +2 -0
  280. package/dist/cli/chunks/{wrappers-MHLNYANQ.js → wrappers-MMO5YKOZ.js} +2 -2
  281. package/dist/cli/commands/eval.js +73 -3
  282. package/dist/cli/commands/llm-router.js +2 -0
  283. package/dist/cli/handlers/status-handler.d.ts +5 -0
  284. package/dist/cli/handlers/status-handler.js +35 -0
  285. package/dist/coordination/consensus/providers/index.js +11 -0
  286. package/dist/init/init-wizard-hooks.js +11 -25
  287. package/dist/init/phases/07-hooks.js +15 -25
  288. package/dist/init/settings-merge.d.ts +44 -0
  289. package/dist/init/settings-merge.js +119 -4
  290. package/dist/mcp/bundle.js +412 -393
  291. package/dist/shared/llm/billing-modes.d.ts +24 -0
  292. package/dist/shared/llm/billing-modes.js +56 -0
  293. package/dist/shared/llm/cost-tracker.js +2 -0
  294. package/dist/shared/llm/interfaces.d.ts +61 -3
  295. package/dist/shared/llm/provider-manager.d.ts +34 -0
  296. package/dist/shared/llm/provider-manager.js +152 -3
  297. package/dist/shared/llm/providers/claude-code.d.ts +57 -0
  298. package/dist/shared/llm/providers/claude-code.js +312 -0
  299. package/dist/shared/llm/providers/cognitum.d.ts +64 -0
  300. package/dist/shared/llm/providers/cognitum.js +369 -0
  301. package/dist/shared/llm/providers/index.d.ts +2 -0
  302. package/dist/shared/llm/providers/index.js +2 -0
  303. package/dist/shared/llm/router/config-store.d.ts +31 -11
  304. package/dist/shared/llm/router/config-store.js +82 -12
  305. package/dist/shared/llm/router/hybrid-router.js +16 -0
  306. package/dist/shared/llm/router/types.js +7 -0
  307. package/dist/shared/llm/spend-ledger.d.ts +64 -0
  308. package/dist/shared/llm/spend-ledger.js +115 -0
  309. package/dist/shared/llm/translation/message-formatter.js +2 -0
  310. package/dist/shared/llm/translation/prompt-translator.js +2 -0
  311. package/dist/shared/llm/translation/tool-translator.js +2 -0
  312. package/dist/validation/index.d.ts +1 -0
  313. package/dist/validation/index.js +2 -0
  314. package/dist/validation/provider-llm-executor.d.ts +45 -0
  315. package/dist/validation/provider-llm-executor.js +98 -0
  316. package/package.json +1 -1
  317. package/dist/cli/chunks/adapter-6IWRIHF3.js +0 -2
  318. package/dist/cli/chunks/aqe-learning-engine-FSF5U67K.js +0 -2
  319. package/dist/cli/chunks/base-2CKCJU3O.js +0 -2
  320. package/dist/cli/chunks/browser-workflow-UGYJE64S.js +0 -2
  321. package/dist/cli/chunks/chunk-2AOOIAW3.js +0 -316
  322. package/dist/cli/chunks/chunk-3B4XXFKD.js +0 -18
  323. package/dist/cli/chunks/chunk-BBC526PL.js +0 -24
  324. package/dist/cli/chunks/chunk-ESDGCTC4.js +0 -2
  325. package/dist/cli/chunks/chunk-IDLNLSQI.js +0 -3
  326. package/dist/cli/chunks/chunk-MDT3LIXS.js +0 -2
  327. package/dist/cli/chunks/client-E2XUBCLK.js +0 -2
  328. package/dist/cli/chunks/core-handlers-46Z5VOO6.js +0 -2
  329. package/dist/cli/chunks/cross-domain-router-SXQ3HFRY.js +0 -2
  330. package/dist/cli/chunks/dream-R6MQQQ3N.js +0 -2
  331. package/dist/cli/chunks/eval-XYOA3EH2.js +0 -15
  332. package/dist/cli/chunks/heartbeat-scheduler-OSDPJT6A.js +0 -2
  333. package/dist/cli/chunks/hnsw-adapter-KMGSHBIN.js +0 -2
  334. package/dist/cli/chunks/hnsw-index-IMFRAOPE.js +0 -2
  335. package/dist/cli/chunks/hybrid-router-57QSWSWC.js +0 -2
  336. package/dist/cli/chunks/impact-analyzer-OC4MPBGA.js +0 -2
  337. package/dist/cli/chunks/init-wizard-CDBRL4PO.js +0 -2
  338. package/dist/cli/chunks/kernel-CQ7R3AAV.js +0 -2
  339. package/dist/cli/chunks/knowledge-graph-UXNH7RY4.js +0 -2
  340. package/dist/cli/chunks/llm-router-service-UV34YXBE.js +0 -2
  341. package/dist/cli/chunks/load-test-2VEN3PQZ.js +0 -2
  342. package/dist/cli/chunks/memory-backend-TZL5U6F3.js +0 -2
  343. package/dist/cli/chunks/memory-handlers-BNXAYS2P.js +0 -2
  344. package/dist/cli/chunks/pattern-null-store-KLX2RNHM.js +0 -2
  345. package/dist/cli/chunks/protocol-executor-5HJKW6MC.js +0 -2
  346. package/dist/cli/chunks/provider-manager-TRZSBXD3.js +0 -2
  347. package/dist/cli/chunks/qe-reasoning-bank-RCEYSLVV.js +0 -2
  348. package/dist/cli/chunks/queen-coordinator-6JFZD54W.js +0 -2
  349. package/dist/cli/chunks/router-KRLC46NS.js +0 -2
  350. package/dist/cli/chunks/routing-feedback-WW26H6SA.js +0 -2
  351. package/dist/cli/chunks/rvf-native-adapter-OVQKPQUH.js +0 -2
  352. package/dist/cli/chunks/safe-db-UQOCQIH2.js +0 -2
  353. package/dist/cli/chunks/schedule-EUX7ZQUK.js +0 -2
  354. package/dist/cli/chunks/scheduler-MALHQKNR.js +0 -2
  355. package/dist/cli/chunks/sqlite-persistence-OBCLRP4L.js +0 -2
  356. package/dist/cli/chunks/status-handler-HGCKYJX2.js +0 -46
  357. package/dist/cli/chunks/unified-memory-A5BS3LGX.js +0 -2
  358. package/dist/cli/chunks/unified-memory-hnsw-WJLJO5MY.js +0 -2
  359. package/dist/cli/chunks/unified-persistence-CFC2BKI5.js +0 -2
  360. package/dist/cli/chunks/visual-security-VPB6KVYJ.js +0 -2
  361. package/dist/cli/chunks/witness-chain-ZZAUAXDY.js +0 -2
  362. package/dist/cli/chunks/workflow-orchestrator-S4LBFTYD.js +0 -2
@@ -0,0 +1,316 @@
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.12.2");process.exit(0)}
2
+ import{b as P,c as q,d as R,e as D,g as O,h as j,i as x,j as $,k as L,l as N,m as Q,n as M}from"./chunk-BUKGW63B.js";import{b as v,d as T}from"./chunk-CKFZOPZN.js";import{a as y,c as A}from"./chunk-X47GHZY3.js";import{a as _,b as re}from"./chunk-WRMUQVKY.js";T();import{existsSync as f,mkdirSync as U,writeFileSync as b,readFileSync as C,copyFileSync as se}from"fs";import{join as p,dirname as ae}from"path";async function z(t,e){if(!e.hooks.claudeCode)return!1;let n=p(t,".claude");f(n)||U(n,{recursive:!0});let r=p(n,"settings.json"),s={};if(f(r))try{let m=C(r,"utf-8");s=v(m)}catch{s={}}let i={PreToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" guard --file "$TOOL_INPUT_file_path" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-edit --file "$TOOL_INPUT_file_path" --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-command --command "$TOOL_INPUT_command" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-task --description "$TOOL_INPUT_prompt" --json',timeout:5e3,continueOnError:!0}]}],PostToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-edit --file "$TOOL_INPUT_file_path" --success --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-command --command "$TOOL_INPUT_command" --success true --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-task --task-id "$TOOL_RESULT_agent_id" --agent "$TOOL_INPUT_subagent_type" --success true --description "$TOOL_INPUT_prompt" --json',timeout:5e3,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" route --json',timeout:5e3,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-start --session-id "$SESSION_ID" --json',timeout:1e4,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-end --save-state --json',timeout:5e3,continueOnError:!0}]},{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-route --success true --json',timeout:5e3,continueOnError:!0}]}]},u=s.hooks||{};s.hooks=O(u,i);let l=s.env;s.env=j(l,x(e));let d=L(e,t);$(s,d);let a=s.enabledMcpjsonServers||[];return a=a.filter(m=>m!=="aqe"),a.includes("agentic-qe")||a.push("agentic-qe"),s.enabledMcpjsonServers=a,D(r),b(r,JSON.stringify(s,null,2),"utf-8"),await oe(t),!0}async function oe(t){let e=p(t,".claude","hooks");f(e)||U(e,{recursive:!0});let n=p(e,"cross-phase-memory.yaml");if(f(n))return;let r=[p(ae(import.meta.url.replace("file://","")),"..","..","assets","hooks","cross-phase-memory.yaml"),p(process.cwd(),"assets","hooks","cross-phase-memory.yaml"),p(process.cwd(),"v3","assets","hooks","cross-phase-memory.yaml")];for(let i of r)try{if(f(i)){se(i,n),console.log(" \u2713 Cross-phase memory hooks installed");return}}catch{}b(n,`# Cross-Phase Memory Hooks Configuration
3
+ # Generated by aqe init
4
+ # See: https://github.com/anthropics/agentic-qe/docs/cross-phase-memory.md
5
+
6
+ version: "1.0"
7
+ enabled: true
8
+
9
+ hooks:
10
+ # Add custom QCSD feedback loop hooks here
11
+ # See .claude/hooks/cross-phase-memory.yaml in the agentic-qe repo for examples
12
+
13
+ routing:
14
+ authorized_receivers:
15
+ strategic:
16
+ - "qe-risk-assessor"
17
+ - "qe-quality-criteria-recommender"
18
+ tactical:
19
+ - "qe-product-factors-assessor"
20
+ operational:
21
+ - "qe-test-architect"
22
+ - "qe-tdd-specialist"
23
+ quality-criteria:
24
+ - "qe-requirements-validator"
25
+ - "qe-bdd-generator"
26
+ `,"utf-8"),console.log(" \u2713 Cross-phase memory hooks created (minimal config)")}async function F(t){let e=p(t,".mcp.json"),n={};if(f(e))try{let s=C(e,"utf-8");n=v(s)}catch{n={}}n.mcpServers||(n.mcpServers={});let r=n.mcpServers;return r["agentic-qe"]={command:"npx",args:["@anthropics/agentic-qe","mcp","start"],env:{AQE_LEARNING_ENABLED:"true",AQE_VERBOSE:"false"},autoStart:!1},b(e,JSON.stringify(n,null,2),"utf-8"),!0}async function W(t,e){let n=p(t,"CLAUDE.md"),r=ie(e);if(f(n)){let s=C(n,"utf-8");if(s.includes("## Agentic QE v3"))return!0;let i=p(t,"CLAUDE.md.backup");b(i,s,"utf-8"),b(n,s+`
27
+
28
+ `+r,"utf-8")}else b(n,r,"utf-8");return!0}function ie(t){let e=t.domains.enabled.slice(0,6).join(", "),n=Math.max(0,t.domains.enabled.length-6);return`## Agentic QE v3
29
+
30
+ This project uses **Agentic QE v3** - a Domain-Driven Quality Engineering platform with 12 bounded contexts, ReasoningBank learning, and HNSW vector search.
31
+
32
+ ---
33
+
34
+ ## \u{1F41D} AQE FLEET ORCHESTRATION
35
+
36
+ ### Fleet Initialization
37
+
38
+ **For QE-specific tasks, initialize the AQE fleet:**
39
+
40
+ \`\`\`javascript
41
+ // Initialize AQE Fleet with MCP tool
42
+ mcp__agentic-qe__fleet_init({
43
+ config: {
44
+ topology: "hierarchical", // Queen-led for QE coordination
45
+ maxAgents: 15,
46
+ testingFocus: ["unit", "integration", "e2e", "performance"],
47
+ frameworks: ["vitest", "jest", "playwright"],
48
+ environments: ["node", "browser"]
49
+ },
50
+ projectContext: {
51
+ language: "typescript",
52
+ buildSystem: "npm"
53
+ }
54
+ })
55
+ \`\`\`
56
+
57
+ ### 12 DDD Domains \u2192 Agent Mapping
58
+
59
+ | Domain | Primary Agents | Focus Area |
60
+ |--------|---------------|------------|
61
+ | \`test-generation\` | qe-test-architect, qe-tdd-specialist | AI-powered test creation |
62
+ | \`test-execution\` | qe-parallel-executor, qe-flaky-hunter, qe-retry-handler | Parallel execution, flaky detection |
63
+ | \`coverage-analysis\` | qe-coverage-specialist, qe-gap-detector | O(log n) sublinear coverage |
64
+ | \`quality-assessment\` | qe-quality-gate, qe-deployment-advisor | Quality gates, risk scoring |
65
+ | \`defect-intelligence\` | qe-defect-predictor, qe-root-cause-analyzer | ML-powered defect prediction |
66
+ | \`learning-optimization\` | qe-learning-coordinator, qe-pattern-learner | Cross-domain pattern learning |
67
+ | \`requirements-validation\` | qe-tdd-specialist, qe-property-tester | BDD scenarios, property tests |
68
+ | \`code-intelligence\` | qe-knowledge-manager, code-analyzer | Knowledge graphs, 80% token reduction |
69
+ | \`security-compliance\` | qe-security-scanner, qe-security-auditor | OWASP, CVE detection |
70
+ | \`contract-testing\` | qe-contract-validator, qe-api-tester | Pact, schema validation |
71
+ | \`visual-accessibility\` | qe-visual-tester, qe-a11y-validator | Visual regression, WCAG |
72
+ | \`chaos-resilience\` | qe-chaos-engineer, qe-performance-tester | Fault injection, load testing |
73
+
74
+ ### Fleet MCP Tools
75
+
76
+ \`\`\`javascript
77
+ // Spawn specialized QE agent
78
+ mcp__agentic-qe__agent_spawn({
79
+ spec: {
80
+ type: "test-generator",
81
+ capabilities: ["unit-tests", "integration-tests"],
82
+ name: "test-gen-1"
83
+ },
84
+ fleetId: "fleet-123"
85
+ })
86
+
87
+ // AI-enhanced test generation
88
+ mcp__agentic-qe__test_generate_enhanced({
89
+ sourceCode: "...",
90
+ language: "typescript",
91
+ testType: "unit",
92
+ coverageGoal: 90,
93
+ aiEnhancement: true,
94
+ detectAntiPatterns: true
95
+ })
96
+
97
+ // Parallel test execution with retry
98
+ mcp__agentic-qe__test_execute_parallel({
99
+ testFiles: ["tests/**/*.test.ts"],
100
+ parallelism: 4,
101
+ retryFailures: true,
102
+ maxRetries: 3,
103
+ collectCoverage: true
104
+ })
105
+
106
+ // Orchestrate QE task across fleet
107
+ mcp__agentic-qe__task_orchestrate({
108
+ task: {
109
+ type: "comprehensive-testing",
110
+ priority: "high",
111
+ strategy: "adaptive",
112
+ maxAgents: 5
113
+ },
114
+ context: {
115
+ project: "my-project",
116
+ environment: "test"
117
+ },
118
+ fleetId: "fleet-123"
119
+ })
120
+ \`\`\`
121
+
122
+ ### QE Memory Operations
123
+
124
+ \`\`\`javascript
125
+ // Store QE pattern with namespace
126
+ mcp__agentic-qe__memory_store({
127
+ key: "coverage-pattern-auth",
128
+ value: { pattern: "...", successRate: 0.95 },
129
+ namespace: "qe-patterns",
130
+ ttl: 86400,
131
+ persist: true
132
+ })
133
+
134
+ // Query memory with pattern matching
135
+ mcp__agentic-qe__memory_query({
136
+ pattern: "coverage-*",
137
+ namespace: "qe-patterns",
138
+ limit: 10
139
+ })
140
+ \`\`\`
141
+
142
+ ### QE Task Routing by Domain
143
+
144
+ | Task Type | MCP Tool | Agents Spawned |
145
+ |-----------|----------|----------------|
146
+ | Generate tests | \`test_generate_enhanced\` | qe-test-architect, qe-tdd-specialist |
147
+ | Run tests | \`test_execute_parallel\` | qe-parallel-executor, qe-retry-handler |
148
+ | Analyze coverage | \`task_orchestrate\` (coverage) | qe-coverage-specialist, qe-gap-detector |
149
+ | Quality gate | \`task_orchestrate\` (quality-gate) | qe-quality-gate, qe-deployment-advisor |
150
+ | Security scan | \`agent_spawn\` (security-scanner) | qe-security-scanner, qe-security-auditor |
151
+ | Chaos test | \`agent_spawn\` (chaos-engineer) | qe-chaos-engineer, qe-load-tester |
152
+
153
+ ---
154
+
155
+ ## Quick Reference
156
+
157
+ \`\`\`bash
158
+ # Run tests
159
+ npm test -- --run
160
+
161
+ # Check quality
162
+ aqe quality assess
163
+
164
+ # Generate tests
165
+ aqe test generate <file>
166
+
167
+ # Coverage analysis
168
+ aqe coverage <path>
169
+ \`\`\`
170
+
171
+ ### MCP Server
172
+
173
+ The AQE v3 MCP server is configured in \`.claude/mcp.json\`. Available tools:
174
+
175
+ | Tool | Description |
176
+ |------|-------------|
177
+ | \`fleet_init\` | Initialize QE fleet with topology |
178
+ | \`agent_spawn\` | Spawn specialized QE agent |
179
+ | \`test_generate_enhanced\` | AI-powered test generation |
180
+ | \`test_execute_parallel\` | Parallel test execution with retry |
181
+ | \`task_orchestrate\` | Orchestrate multi-agent QE tasks |
182
+ | \`coverage_analyze_sublinear\` | O(log n) coverage analysis |
183
+ | \`quality_assess\` | Quality gate evaluation |
184
+ | \`memory_store\` / \`memory_query\` | Pattern storage with namespacing |
185
+ | \`security_scan_comprehensive\` | SAST/DAST scanning |
186
+ | \`fleet_status\` | Get fleet and agent status |
187
+
188
+ ### Configuration
189
+
190
+ - **Enabled Domains**: ${e}${n>0?` (+${n} more)`:""}
191
+ - **Learning**: ${t.learning.enabled?"Enabled":"Disabled"} (${t.learning.embeddingModel} embeddings)
192
+ - **Max Concurrent Agents**: ${t.agents.maxConcurrent}
193
+ - **Background Workers**: ${t.workers.enabled.length>0?t.workers.enabled.join(", "):"None"}
194
+
195
+ ### V3 QE Agents
196
+
197
+ QE agents are installed in \`.claude/agents/v3/\`. Use with Claude Code's Task tool:
198
+
199
+ \`\`\`javascript
200
+ // Example: Generate tests
201
+ Task({ prompt: "Generate unit tests for auth module", subagent_type: "qe-test-architect", run_in_background: true })
202
+
203
+ // Example: Analyze coverage
204
+ Task({ prompt: "Find coverage gaps in src/", subagent_type: "qe-coverage-specialist", run_in_background: true })
205
+
206
+ // Example: Security scan
207
+ Task({ prompt: "Run security audit", subagent_type: "qe-security-scanner", run_in_background: true })
208
+ \`\`\`
209
+
210
+ ### Integration with Claude Flow
211
+
212
+ **AQE Fleet + Claude Flow work together:**
213
+
214
+ \`\`\`javascript
215
+ // STEP 1: Initialize Claude Flow swarm for coordination
216
+ Bash("npx ruflo swarm init --topology hierarchical --max-agents 15")
217
+
218
+ // STEP 2: Initialize AQE Fleet for QE-specific work
219
+ mcp__agentic-qe__fleet_init({
220
+ config: { topology: "hierarchical", maxAgents: 10, testingFocus: ["unit", "integration"] }
221
+ })
222
+
223
+ // STEP 3: Spawn agents via Claude Code Task tool (do the actual work)
224
+ Task({ prompt: "Generate tests for auth module", subagent_type: "qe-test-architect", run_in_background: true })
225
+ Task({ prompt: "Analyze coverage gaps", subagent_type: "qe-coverage-specialist", run_in_background: true })
226
+
227
+ // STEP 4: Store learnings in both systems
228
+ mcp__agentic-qe__memory_store({ key: "pattern-1", value: "...", namespace: "qe-patterns", persist: true })
229
+ Bash("npx ruflo memory store --key 'qe-pattern-1' --value '...' --namespace patterns")
230
+ \`\`\`
231
+
232
+ ### Data Storage
233
+
234
+ - **Memory Backend**: \`.agentic-qe/memory.db\` (SQLite)
235
+ - **Pattern Storage**: \`.agentic-qe/data/memory.db\` (ReasoningBank)
236
+ - **HNSW Index**: \`.agentic-qe/data/hnsw/index.bin\`
237
+ - **Configuration**: \`.agentic-qe/config.yaml\`
238
+
239
+ ### Best Practices
240
+
241
+ 1. **Test Execution**: Always use \`npm test -- --run\` (not \`npm test\` which runs in watch mode)
242
+ 2. **Coverage Targets**: Aim for 80%+ coverage on critical paths
243
+ 3. **Quality Gates**: Run \`quality_assess\` before merging PRs
244
+ 4. **Pattern Learning**: AQE learns from successful test patterns - consistent naming helps
245
+ 5. **Fleet Coordination**: Use \`fleet_init\` before spawning multiple QE agents
246
+ 6. **Memory Persistence**: Use \`persist: true\` for patterns you want to keep across sessions
247
+
248
+ ### Troubleshooting
249
+
250
+ If MCP tools aren't working:
251
+ \`\`\`bash
252
+ # Verify MCP server is configured
253
+ cat .claude/mcp.json
254
+
255
+ # Check fleet status
256
+ mcp__agentic-qe__fleet_status({ includeAgentDetails: true })
257
+
258
+ # Reinitialize if needed
259
+ aqe init --auto
260
+ \`\`\`
261
+
262
+ ---
263
+ *Generated by AQE v3 init - ${new Date().toISOString()}*
264
+ `}A();import{existsSync as h,mkdirSync as k,writeFileSync as E}from"fs";import{join as o,dirname as le}from"path";A();re();T();async function G(t,e){let n=o(t,".agentic-qe","memory.db");try{let r=le(n);h(r)||k(r,{recursive:!0});let s=_(n);try{s.exec(`
265
+ CREATE TABLE IF NOT EXISTS kv_store (
266
+ key TEXT NOT NULL,
267
+ namespace TEXT NOT NULL,
268
+ value TEXT NOT NULL,
269
+ expires_at INTEGER,
270
+ created_at INTEGER DEFAULT (strftime('%s', 'now') * 1000),
271
+ PRIMARY KEY (namespace, key)
272
+ );
273
+ `);let i=Date.now();return s.prepare(`
274
+ INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
275
+ VALUES (?, '_system', ?, ?)
276
+ `).run("aqe_version",JSON.stringify(e),i),s.prepare(`
277
+ INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
278
+ VALUES (?, '_system', ?, ?)
279
+ `).run("init_timestamp",JSON.stringify(new Date().toISOString()),i),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(i){return s.close(),console.warn(` \u26A0 Could not write version: ${y(i)}`),!1}}catch(r){return console.warn(` \u26A0 Could not open memory.db: ${y(r)}`),!1}}async function V(t){let e=null;try{e=(await import("./better-sqlite3-RQCOOAZC.js")).default}catch{throw new Error(`SQLite persistence REQUIRED but better-sqlite3 is not installed.
280
+ Install it with: npm install better-sqlite3
281
+ If you see native compilation errors, ensure build tools are installed:
282
+ - macOS: xcode-select --install
283
+ - Ubuntu/Debian: sudo apt-get install build-essential python3
284
+ - Alpine: apk add build-base python3`)}let n=o(t,".agentic-qe");h(n)||k(n,{recursive:!0});let r=o(n,"memory.db");try{let s=new e(r);if(s.pragma("journal_mode = WAL"),s.pragma("busy_timeout = 5000"),s.exec(`
285
+ CREATE TABLE IF NOT EXISTS kv_store (
286
+ key TEXT NOT NULL,
287
+ namespace TEXT NOT NULL,
288
+ value TEXT NOT NULL,
289
+ expires_at INTEGER,
290
+ created_at INTEGER DEFAULT (strftime('%s', 'now') * 1000),
291
+ PRIMARY KEY (namespace, key)
292
+ );
293
+ CREATE INDEX IF NOT EXISTS idx_kv_namespace ON kv_store(namespace);
294
+ CREATE INDEX IF NOT EXISTS idx_kv_expires ON kv_store(expires_at) WHERE expires_at IS NOT NULL;
295
+ `),!s.prepare(`
296
+ SELECT name FROM sqlite_master WHERE type='table' AND name='kv_store'
297
+ `).get())throw new Error("Failed to create kv_store table");return s.prepare(`
298
+ INSERT OR REPLACE INTO kv_store (key, namespace, value)
299
+ VALUES (?, ?, ?)
300
+ `).run("_init_test","_system",JSON.stringify({initialized:new Date().toISOString()})),s.close(),console.log(`\u2713 SQLite persistence initialized: ${r}`),!0}catch(s){throw new Error(`SQLite persistence initialization FAILED: ${s}
301
+ Database path: ${r}
302
+ Ensure the directory is writable and has sufficient disk space.`)}}async function J(t){let e=o(t,".agentic-qe","memory.db");if(!h(e))return!1;try{let n=_(e),r=n.prepare(`
303
+ SELECT COUNT(*) as count FROM kv_store
304
+ WHERE namespace = 'code-intelligence:kg'
305
+ `).get();return n.close(),r.count>0}catch{return!1}}async function B(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-R6ZWWV2K.js"),{InMemoryBackend:n}=await import("./memory-backend-YESSIHFW.js"),r=new n;await r.initialize();let s=new e(r,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0}),u=await(await import("fast-glob")).default(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:t,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"]}),l=await s.index({paths:u.map(d=>o(t,d)),incremental:!1,includeTests:!0});return s.destroy(),l.success?{status:"indexed",entries:l.value.nodesCreated+l.value.edgesCreated}:{status:"error",entries:0}}catch(e){return console.warn("Code intelligence scan warning:",y(e)),{status:"skipped",entries:0}}}async function H(t){let e=o(t,".agentic-qe","memory.db");try{let n=_(e),r=n.prepare(`
306
+ SELECT COUNT(*) as count FROM kv_store
307
+ WHERE namespace LIKE 'code-intelligence:kg%'
308
+ `).get();return n.close(),r.count}catch{return 0}}async function X(t,e,n){if(!e.learning.enabled)return 0;let r=o(t,".agentic-qe","data");h(r)||k(r,{recursive:!0});let s=o(r,"hnsw");h(s)||k(s,{recursive:!0});let i=o(r,"learning-config.json"),u={embeddingModel:e.learning.embeddingModel,hnswConfig:e.learning.hnswConfig,qualityThreshold:e.learning.qualityThreshold,promotionThreshold:e.learning.promotionThreshold,databasePath:o(r,"memory.db"),hnswIndexPath:o(s,"index.bin"),initialized:new Date().toISOString()};E(i,JSON.stringify(u,null,2),"utf-8");let l=0;if(e.learning.pretrainedPatterns&&n){let d=n,a=new Map;for(let g of d.patterns){let c=g.domain||"general";a.has(c)||a.set(c,[]),a.get(c).push(g)}let m=o(r,"pretrained-index.json"),S={version:d.version,totalPatterns:d.statistics.totalPatterns,domains:Array.from(a.entries()).map(([g,c])=>({name:g,patternCount:c.length})),loadedAt:new Date().toISOString()};E(m,JSON.stringify(S,null,2),"utf-8");for(let[g,c]of a){let w=o(r,"patterns",g);h(w)||k(w,{recursive:!0});let ne=o(w,"patterns.json");E(ne,JSON.stringify(c,null,2),"utf-8"),l+=c.length}return l}return 0}async function K(t,e){if(!e.workers.daemonAutoStart||e.workers.enabled.length===0)return 0;let n=o(t,".agentic-qe","workers");h(n)||k(n,{recursive:!0});let r={},s={"pattern-consolidator":6e4,"coverage-gap-scanner":3e5,"flaky-test-detector":6e5,"routing-accuracy-monitor":12e4};for(let a of e.workers.enabled)r[a]={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,lastRun:null,status:"pending"};let i=o(n,"registry.json"),u={version:e.version,maxConcurrent:e.workers.maxConcurrent,workers:r,createdAt:new Date().toISOString(),daemonPid:null};E(i,JSON.stringify(u,null,2),"utf-8");for(let a of e.workers.enabled){let m=o(n,`${a}.json`),S={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,projectRoot:t,dataDir:o(t,".agentic-qe","data"),createdAt:new Date().toISOString()};E(m,JSON.stringify(S,null,2),"utf-8")}let l=o(n,"start-daemon.cjs");return E(l,`#!/usr/bin/env node
309
+ // AQE v3 Worker Daemon Startup Script (cross-platform)
310
+ // Generated by aqe init
311
+
312
+ console.log("AQE v3 hooks work via CLI commands (no daemon required)");
313
+ console.log("Use: npx aqe hooks session-start");
314
+ `),e.workers.enabled.length}async function Y(t,e){if(!e.skills.install)return 0;let r=await N({projectRoot:t,installV2Skills:e.skills.installV2,installV3Skills:e.skills.installV3,overwrite:e.skills.overwrite}).install();return r.errors.length>0&&console.warn("Skills installation warnings:",r.errors),r.installed.length}async function Z(t){let n=await Q({projectRoot:t,installQEAgents:!0,installSubagents:!0,overwrite:!1}).install();return n.errors.length>0&&console.warn("Agents installation warnings:",n.errors),n.installed.length}async function ee(t,e,n){let s=await M({projectRoot:t,installAgents:!0,installSkills:!0,overwrite:!1,n8nApiConfig:n}).install();return s.errors.length>0&&console.warn("N8n installation warnings:",s.errors),e.platforms||(e.platforms={}),e.platforms.n8n={enabled:!0,installAgents:!0,installSkills:!0,installTypeScriptAgents:!1,n8nApiConfig:n},{agents:s.agentsInstalled.length,skills:s.skillsInstalled.length}}async function te(t,e){if(!e)throw new Error("No configuration to save");let n=o(t,".agentic-qe");h(n)||k(n,{recursive:!0});let r=ce(e),s=o(n,"config.yaml");E(s,r,"utf-8")}function ce(t){let e=["# Agentic QE v3 Configuration","# Generated by aqe init",`# ${new Date().toISOString()}`,""];e.push(`version: "${t.version}"`),e.push(""),e.push("project:"),e.push(` name: "${t.project.name}"`),e.push(` root: "${t.project.root}"`),e.push(` type: "${t.project.type}"`),e.push(""),e.push("learning:"),e.push(` enabled: ${t.learning.enabled}`),e.push(` embeddingModel: "${t.learning.embeddingModel}"`),e.push(" hnswConfig:"),e.push(` M: ${t.learning.hnswConfig.M}`),e.push(` efConstruction: ${t.learning.hnswConfig.efConstruction}`),e.push(` efSearch: ${t.learning.hnswConfig.efSearch}`),e.push(` qualityThreshold: ${t.learning.qualityThreshold}`),e.push(` promotionThreshold: ${t.learning.promotionThreshold}`),e.push(` pretrainedPatterns: ${t.learning.pretrainedPatterns}`),e.push(""),e.push("routing:"),e.push(` mode: "${t.routing.mode}"`),e.push(` confidenceThreshold: ${t.routing.confidenceThreshold}`),e.push(` feedbackEnabled: ${t.routing.feedbackEnabled}`),e.push(""),e.push("# ADR-092: Advisor Strategy \u2014 agents consult a stronger model for strategic guidance"),e.push("# Set provider/model to override auto-detection from environment API keys"),e.push("advisor:"),e.push(' # provider: "openrouter" # openrouter | claude | ollama (auto-detected if not set)'),e.push(' # model: "anthropic/claude-opus-4.7" # provider-specific model ID'),e.push(' # maxUses: "3" # per-task advisor call cap'),e.push(' redact: "strict" # strict | balanced | off'),e.push(""),e.push("workers:"),e.push(" enabled:");for(let n of t.workers.enabled)e.push(` - "${n}"`);e.push(" intervals:");for(let[n,r]of Object.entries(t.workers.intervals))e.push(` ${n}: ${r}`);e.push(` maxConcurrent: ${t.workers.maxConcurrent}`),e.push(` daemonAutoStart: ${t.workers.daemonAutoStart}`),e.push(""),e.push("hooks:"),e.push(` claudeCode: ${t.hooks.claudeCode}`),e.push(` preCommit: ${t.hooks.preCommit}`),e.push(` ciIntegration: ${t.hooks.ciIntegration}`),e.push(""),e.push("skills:"),e.push(` install: ${t.skills.install}`),e.push(` installV2: ${t.skills.installV2}`),e.push(` installV3: ${t.skills.installV3}`),e.push(` overwrite: ${t.skills.overwrite}`),e.push(""),e.push("autoTuning:"),e.push(` enabled: ${t.autoTuning.enabled}`),e.push(" parameters:");for(let n of t.autoTuning.parameters)e.push(` - "${n}"`);e.push(` evaluationPeriodMs: ${t.autoTuning.evaluationPeriodMs}`),e.push(""),e.push("domains:"),e.push(" enabled:");for(let n of t.domains.enabled)e.push(` - "${n}"`);e.push(" disabled:");for(let n of t.domains.disabled)e.push(` - "${n}"`);return e.push(""),e.push("agents:"),e.push(` maxConcurrent: ${t.agents.maxConcurrent}`),e.push(` defaultTimeout: ${t.agents.defaultTimeout}`),e.push(""),e.join(`
315
+ `)}var ue=[{id:"welcome",title:"Welcome to AQE v3",description:"This wizard will configure Agentic QE for your project.",type:"info"},{id:"project-type",title:"Project Type",description:"What type of project is this?",type:"choice",options:[{value:"auto",label:"Auto-detect",description:"Let AQE analyze your project",recommended:!0},{value:"single",label:"Single Package",description:"Standard single-package project"},{value:"monorepo",label:"Monorepo",description:"Multi-package workspace"},{value:"library",label:"Library",description:"Publishable package/library"}],default:"auto"},{id:"learning-mode",title:"Learning System",description:"How should AQE learn from your project?",type:"choice",options:[{value:"full",label:"Full Learning",description:"Transformer embeddings + SQLite persistence",recommended:!0},{value:"basic",label:"Basic Learning",description:"Hash-based embeddings, in-memory"},{value:"disabled",label:"Disabled",description:"No pattern learning"}],default:"full"},{id:"load-patterns",title:"Pre-trained Patterns",description:"Load pre-trained QE patterns for faster results?",type:"confirm",default:!0},{id:"hooks",title:"Claude Code Integration",description:"Enable Claude Code hooks for seamless integration?",type:"confirm",default:!0},{id:"workers",title:"Background Workers",description:"Start background workers for continuous monitoring?",type:"confirm",default:!0},{id:"skills",title:"Install Skills",description:"Install AQE skills (v2 methodology + v3 domain skills)?",type:"confirm",default:!0},{id:"agents",title:"Install Agents",description:"Install V3 QE agents for Claude Code Task tool?",type:"confirm",default:!0}],I=class{projectRoot;options;analyzer;configurator;steps=[];constructor(e){this.options=e,this.projectRoot=e.projectRoot,this.analyzer=q(e.projectRoot),this.configurator=R({minimal:e.minimal})}async initialize(){let e=Date.now();try{let n=await this.runStep("Project Analysis",async()=>await this.analyzer.analyze()),r=await this.runStep("Configuration Generation",async()=>this.options.autoMode?this.configurator.recommend(n):this.applyWizardAnswers(n));await this.runStep("Persistence Database Setup",async()=>await V(this.projectRoot));let s=await this.runStep("Code Intelligence Pre-Scan",async()=>{if(!await J(this.projectRoot))return console.log(" Building knowledge graph for code intelligence..."),await B(n.projectRoot);let w=await H(this.projectRoot);return console.log(` Using existing code intelligence index (${w} entries)`),{status:"existing",entries:w}}),i=await this.runStep("Learning System Setup",async()=>r.learning.enabled&&!this.options.skipPatterns?await X(this.projectRoot,r,this.options.pretrainedLibrary):0),u=await this.runStep("Hooks Configuration",async()=>r.hooks.claudeCode?await z(this.projectRoot,r):!1),l=await this.runStep("MCP Configuration",async()=>await F(this.projectRoot)),d=await this.runStep("CLAUDE.md Generation",async()=>await W(this.projectRoot,r)),a=await this.runStep("Background Workers",async()=>r.workers.daemonAutoStart?await K(this.projectRoot,r):0),m=await this.runStep("Skills Installation",async()=>r.skills.install?await Y(this.projectRoot,r):0),S=await this.runStep("Agents Installation",async()=>await Z(this.projectRoot)),g;if(this.options.withN8n){let c=await this.runStep("N8n Platform Installation",async()=>await ee(this.projectRoot,r,this.options.n8nApiConfig));c&&(g=c)}return await this.runStep("Save Configuration",async()=>await te(this.projectRoot,r)),await this.runStep("Version Marker",async()=>await G(this.projectRoot,r.version)),{success:!0,config:r,steps:this.steps,summary:{projectAnalyzed:!0,configGenerated:!0,codeIntelligenceIndexed:s?.entries??0,patternsLoaded:i,skillsInstalled:m,agentsInstalled:S,hooksConfigured:u,mcpConfigured:l,claudeMdGenerated:d,workersStarted:a,n8nInstalled:g},totalDurationMs:Date.now()-e,timestamp:new Date}}catch(n){return this.steps.push({step:"Initialization Failed",status:"error",message:y(n),durationMs:0}),{success:!1,config:P("unknown",this.projectRoot),steps:this.steps,summary:{projectAnalyzed:!1,configGenerated:!1,codeIntelligenceIndexed:0,patternsLoaded:0,skillsInstalled:0,agentsInstalled:0,hooksConfigured:!1,mcpConfigured:!1,claudeMdGenerated:!1,workersStarted:0},totalDurationMs:Date.now()-e,timestamp:new Date}}}getWizardSteps(){return ue}async runStep(e,n){let r=Date.now();try{let s=await n();return this.steps.push({step:e,status:"success",message:`${e} completed successfully`,durationMs:Date.now()-r}),s}catch(s){throw this.steps.push({step:e,status:"error",message:y(s),durationMs:Date.now()-r}),s}}applyWizardAnswers(e){let n=this.options.wizardAnswers||{},r=this.configurator.recommend(e);switch(n["project-type"]&&n["project-type"]!=="auto"&&(r.project.type=n["project-type"]),n["learning-mode"]){case"full":r.learning.enabled=!0,r.learning.embeddingModel="transformer";break;case"basic":r.learning.enabled=!0,r.learning.embeddingModel="hash";break;case"disabled":r.learning.enabled=!1;break}return n["load-patterns"]===!1&&(r.learning.pretrainedPatterns=!1),n.hooks===!1&&(r.hooks.claudeCode=!1),n.workers===!1&&(r.workers.daemonAutoStart=!1),n.skills===!1&&(r.skills.install=!1),r}};function de(t){return new I(t)}async function je(t){return await de({projectRoot:t,autoMode:!0}).initialize()}function xe(t){let e=[];e.push(""),e.push("+-------------------------------------------------------------+"),e.push("| AQE v3 Initialization |"),e.push("+-------------------------------------------------------------+");for(let r of t.steps){let s=r.status==="success"?"[OK]":r.status==="error"?"[!!]":"[ ]";e.push(`| ${s} ${r.step.padEnd(50)} ${String(r.durationMs).padStart(4)}ms |`)}e.push("+-------------------------------------------------------------+"),e.push(`| Project: ${t.config.project.name.padEnd(47)} |`),e.push(`| Type: ${t.config.project.type.padEnd(50)} |`),e.push(`| Code Intel Indexed: ${String(t.summary.codeIntelligenceIndexed).padEnd(36)} |`),e.push(`| Patterns Loaded: ${String(t.summary.patternsLoaded).padEnd(39)} |`),e.push(`| Skills Installed: ${String(t.summary.skillsInstalled).padEnd(38)} |`),e.push(`| Agents Installed: ${String(t.summary.agentsInstalled).padEnd(38)} |`),e.push(`| Workers Started: ${String(t.summary.workersStarted).padEnd(39)} |`),e.push(`| Hooks Configured: ${t.summary.hooksConfigured?"Yes":"No".padEnd(38)} |`),e.push(`| MCP Server: ${t.summary.mcpConfigured?"Yes":"No".padEnd(44)} |`),e.push(`| CLAUDE.md: ${t.summary.claudeMdGenerated?"Yes":"No".padEnd(45)} |`),e.push("+-------------------------------------------------------------+");let n=t.success?"[OK] AQE v3 initialized as self-learning platform":"[!!] Initialization failed";return e.push(`| ${n.padEnd(57)} |`),e.push("+-------------------------------------------------------------+"),e.push(""),e.join(`
316
+ `)}export{I as a,de as b,je as c,xe 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.12.0");process.exit(0)}
2
- import{a as p,b as A,c as L}from"./chunk-RHC7TFPU.js";var R={reflexThreshold:.1,retrievalThreshold:.4,heavyThreshold:.7},M={enabled:!0,laneConfig:R,coherenceThreshold:.1,fallbackEnabled:!0,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},m={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},f=class extends Error{constructor(t,i,n){super(t);this.code=i;this.cause=n;this.name="CoherenceError"}code;cause},h=class extends f{constructor(e="WASM module is not loaded",t){super(e,"WASM_NOT_LOADED",t),this.name="WasmNotLoadedError"}};var T=class extends f{constructor(t,i,n){super(t,"WASM_LOAD_FAILED",n);this.attempts=i;this.name="WasmLoadError"}attempts},z={maxAttempts:3,baseDelayMs:100,maxDelayMs:5e3,timeoutMs:1e4};L();function D(u){let e=new Map,t=[],i=new Map,n=new Map,r=0,a=s=>{let l=i.get(s);return l===void 0&&(l=r++,i.set(s,l),n.set(l,s)),l},o=s=>n.get(s)??`unknown-${s}`,d=()=>({nodes:Array.from(e.entries()).map(([s,l])=>({id:a(s),label:s,section:Array.from(l.embedding),weight:1})),edges:t.map(s=>({source:a(s.source),target:a(s.target),weight:s.weight}))});return{add_node(s,l){e.set(s,{embedding:l}),a(s)},add_edge(s,l,c){t.push({source:s,target:l,weight:c}),a(s),a(l)},remove_node(s){e.delete(s);for(let l=t.length-1;l>=0;l--)(t[l].source===s||t[l].target===s)&&t.splice(l,1)},remove_edge(s,l){let c=t.findIndex(g=>g.source===s&&g.target===l);c>=0&&t.splice(c,1)},sheaf_laplacian_energy(){let s=d();return u.consistencyEnergy(s)},detect_contradictions(s){let l=d(),c=u.detectObstructions(l);return c?c.filter(g=>g.energy>s).map(g=>({node1:o(g.node1),node2:o(g.node2),severity:g.energy,distance:g.energy})):[]},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var y=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;nodes=new Map;edges=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CohomologyAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CohomologyAdapter.");let t=await this.wasmLoader.load(),i=new t.CohomologyEngine;this.engine=D(i),this.initialized=!0,this.logger.info("CohomologyAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CohomologyAdapter not initialized. Call initialize() first.")}addNode(e){this.ensureInitialized(),this.nodes.set(e.id,e);let t=new Float64Array(e.embedding);this.engine.add_node(e.id,t),this.logger.debug("Added node to cohomology graph",{nodeId:e.id,embeddingDim:e.embedding.length})}addEdge(e){this.ensureInitialized(),this.edges.push(e),this.engine.add_edge(e.source,e.target,e.weight),this.logger.debug("Added edge to cohomology graph",{source:e.source,target:e.target,weight:e.weight})}removeNode(e){this.ensureInitialized(),this.nodes.delete(e),this.engine.remove_node(e);let t=[];this.edges.forEach((i,n)=>{(i.source===e||i.target===e)&&t.push(n)}),t.reverse().forEach(i=>this.edges.splice(i,1)),this.logger.debug("Removed node from cohomology graph",{nodeId:e})}removeEdge(e,t){this.ensureInitialized();let i=this.edges.findIndex(n=>n.source===e&&n.target===t);i>=0&&this.edges.splice(i,1),this.engine.remove_edge(e,t),this.logger.debug("Removed edge from cohomology graph",{source:e,target:t})}computeEnergy(){this.ensureInitialized();let e=this.engine.sheaf_laplacian_energy();return this.logger.debug("Computed sheaf Laplacian energy",{energy:e}),e}detectContradictions(e=.1){this.ensureInitialized();let i=this.engine.detect_contradictions(e).map(n=>this.transformContradiction(n));return this.logger.debug("Detected contradictions",{count:i.length,threshold:e}),i}transformContradiction(e){return{nodeIds:[e.node1,e.node2],severity:this.severityFromDistance(e.severity),description:this.generateContradictionDescription(e),confidence:1-e.distance,resolution:this.suggestResolution(e)}}severityFromDistance(e){return e>=.9?"critical":e>=.7?"high":e>=.4?"medium":e>=.2?"low":"info"}generateContradictionDescription(e){let t=this.nodes.get(e.node1),i=this.nodes.get(e.node2);return t?.metadata?.statement&&i?.metadata?.statement?`Contradiction detected between "${t.metadata.statement}" and "${i.metadata.statement}"`:`Contradiction detected between nodes '${e.node1}' and '${e.node2}' with distance ${e.distance.toFixed(3)}`}suggestResolution(e){return e.severity>=.9?"Critical contradiction requires manual review. Consider removing one of the conflicting beliefs.":e.severity>=.7?"High-severity contradiction. Recommend gathering additional evidence to determine which belief is correct.":e.severity>=.4?"Moderate contradiction. Consider adding context or constraints to differentiate the beliefs.":"Low-severity contradiction. May be resolved with additional context or can be safely ignored."}clear(){this.ensureInitialized(),this.nodes.clear(),this.edges.length=0,this.engine.clear(),this.logger.debug("Cleared cohomology graph")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.nodes.clear(),this.edges.length=0,this.initialized=!1,this.logger.info("CohomologyAdapter disposed")}getNodeCount(){return this.nodes.size}getEdgeCount(){return this.edges.length}getNode(e){return this.nodes.get(e)}};L();function N(u){let e=new Set,t=[],i=new Map,n=new Map,r=0,a=s=>{let l=i.get(s);return l===void 0&&(l=r++,i.set(s,l),n.set(l,s)),l},o=s=>n.get(s)??`unknown-${s}`,d=()=>({n:e.size,edges:t.map(s=>[a(s.source),a(s.target),s.weight])});return{add_node(s){e.add(s),a(s)},add_edge(s,l,c){t.push({source:s,target:l,weight:c}),a(s),a(l)},remove_node(s){e.delete(s);for(let l=t.length-1;l>=0;l--)(t[l].source===s||t[l].target===s)&&t.splice(l,1)},compute_fiedler_value(){if(e.size<2||t.length===0)return 0;try{let s=d(),l=u.algebraicConnectivity(s);return Number.isFinite(l)&&l>=0?l:0}catch(s){return console.warn("[SpectralAdapter] algebraicConnectivity failed:",s),0}},predict_collapse_risk(){if(e.size<2)return 0;if(t.length===0)return 1;try{let s=d(),l=u.algebraicConnectivity(s),c=Number.isFinite(l)&&l>=0?l:0;return Math.max(0,Math.min(1,1-c))}catch(s){return console.warn("[SpectralAdapter] predict_collapse_risk failed:",s),.8}},get_weak_vertices(s){if(e.size===0)return[];if(t.length===0)return Array.from(e).slice(0,s);try{let l=d(),c=u.predictMinCut(l);return c?.vertices?c.vertices.slice(0,s).map(g=>o(g)):Array.from(e).slice(0,s)}catch(l){return console.warn("[SpectralAdapter] predictMinCut failed:",l),Array.from(e).slice(0,s)}},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var v=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;nodes=new Set;edges=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing SpectralAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize SpectralAdapter.");let t=await this.wasmLoader.load(),i=new t.SpectralEngine;this.engine=N(i),this.initialized=!0,this.logger.info("SpectralAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("SpectralAdapter not initialized. Call initialize() first.")}addNode(e){if(this.ensureInitialized(),this.nodes.has(e)){this.logger.debug("Node already exists",{nodeId:e});return}this.nodes.add(e),this.engine.add_node(e),this.logger.debug("Added node to spectral graph",{nodeId:e})}addEdge(e,t,i){this.ensureInitialized(),this.nodes.has(e)||this.addNode(e),this.nodes.has(t)||this.addNode(t),this.edges.push({source:e,target:t,weight:i}),this.engine.add_edge(e,t,i),this.logger.debug("Added edge to spectral graph",{source:e,target:t,weight:i})}removeNode(e){this.ensureInitialized(),this.nodes.delete(e),this.engine.remove_node(e);for(let t=this.edges.length-1;t>=0;t--){let i=this.edges[t];(i.source===e||i.target===e)&&this.edges.splice(t,1)}this.logger.debug("Removed node from spectral graph",{nodeId:e})}computeFiedlerValue(){if(this.ensureInitialized(),this.nodes.size<2||this.edges.length===0)return 0;try{let e=this.engine.compute_fiedler_value();return this.logger.debug("Computed Fiedler value",{fiedlerValue:e}),e}catch(e){return this.logger.warn("Failed to compute Fiedler value",{error:p(e),nodeCount:this.nodes.size,edgeCount:this.edges.length}),0}}predictCollapseRisk(){if(this.ensureInitialized(),this.nodes.size<2)return 0;if(this.edges.length===0)return 1;try{let e=this.engine.predict_collapse_risk();return this.logger.debug("Predicted collapse risk",{risk:e}),e}catch(e){return this.logger.warn("Failed to predict collapse risk",{error:p(e),nodeCount:this.nodes.size,edgeCount:this.edges.length}),.8}}getWeakVertices(e){if(this.ensureInitialized(),this.nodes.size===0)return[];if(this.edges.length===0)return Array.from(this.nodes).slice(0,e);let t=Math.min(e,this.nodes.size);try{let i=this.engine.get_weak_vertices(t);return this.logger.debug("Retrieved weak vertices",{requested:e,returned:i.length}),i}catch(i){return this.logger.warn("Failed to get weak vertices",{error:p(i),nodeCount:this.nodes.size,edgeCount:this.edges.length}),Array.from(this.nodes).slice(0,e)}}analyzeSwarmState(e){let t=Date.now();this.clear();for(let d of e.agents)this.addNode(d.agentId);this.buildEdgesFromAgents(e.agents);let i=this.predictCollapseRisk(),n=this.computeFiedlerValue(),r=this.getWeakVertices(5),a=Date.now()-t,o={risk:i,fiedlerValue:n,collapseImminent:i>.7,weakVertices:r,recommendations:this.generateRecommendations(i,n,r),durationMs:a,usedFallback:!1};return this.logger.info("Analyzed swarm state",{agentCount:e.agents.length,risk:i,fiedlerValue:n,durationMs:a}),o}buildEdgesFromAgents(e){for(let t=0;t<e.length;t++)for(let i=t+1;i<e.length;i++){let n=this.computeAgentSimilarity(e[t],e[i]);n>.3&&this.addEdge(e[t].agentId,e[i].agentId,n)}}computeAgentSimilarity(e,t){let i=1-Math.abs(e.health-t.health),n=1-Math.abs(e.successRate-t.successRate),r=e.agentType===t.agentType?.2:0,a=0,o=e.beliefs??[],d=t.beliefs??[];return o.length>0&&d.length>0&&(a=this.computeBeliefOverlap(o,d)),i*.3+n*.3+r+a*.2}computeBeliefOverlap(e,t){if(e.length===0||t.length===0)return 0;let i=0,n=0;for(let r of e)for(let a of t)i+=this.cosineSimilarity(r.embedding,a.embedding),n++;return n>0?i/n:0}cosineSimilarity(e,t){if(e.length!==t.length||e.length===0)return 0;let i=0,n=0,r=0;for(let o=0;o<e.length;o++)i+=e[o]*t[o],n+=e[o]*e[o],r+=t[o]*t[o];let a=Math.sqrt(n)*Math.sqrt(r);return a===0?0:i/a}generateRecommendations(e,t,i){let n=[];return e>.7?(n.push("CRITICAL: Immediate action required to prevent swarm collapse."),n.push("Consider spawning additional coordination agents to strengthen connectivity.")):e>.5&&n.push("WARNING: Elevated collapse risk detected. Monitor closely."),t<.1&&n.push("Network connectivity is weak. Consider adding redundant communication channels."),t<.05&&(n.push("ALERT: Near-zero Fiedler value indicates potential false consensus."),n.push("Recommend spawning an independent reviewer to verify decisions.")),i.length>0&&n.push(`At-risk agents: ${i.join(", ")}. Consider reassigning critical tasks.`),n.length===0&&n.push("Swarm health is good. No immediate action required."),n}clear(){this.ensureInitialized(),this.nodes.clear(),this.edges.length=0,this.engine.clear(),this.logger.debug("Cleared spectral graph")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.nodes.clear(),this.edges.length=0,this.initialized=!1,this.logger.info("SpectralAdapter disposed")}getNodeCount(){return this.nodes.size}getEdgeCount(){return this.edges.length}};function O(u){let e=null,t=null,i=new Map,n=()=>({cause:e?Array.from(e):[],effect:t?Array.from(t):[],confounders:Object.fromEntries(Array.from(i.entries()).map(([r,a])=>[r,Array.from(a)]))});return{set_data(r,a){e=r,t=a},add_confounder(r,a){i.set(r,a)},compute_causal_effect(){let r=n();return u.computeCausalEffect(r,"cause","effect",1)?.effect??0},detect_spurious_correlation(){let r=n();return(u.findConfounders(r,"cause","effect")?.length??0)>0},get_confounders(){let r=n();return u.findConfounders(r,"cause","effect")??Array.from(i.keys())},clear(){e=null,t=null,i.clear()}}}var b=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;currentCause="";currentEffect="";async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CausalAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CausalAdapter.");let t=await this.wasmLoader.load(),i=new t.CausalEngine;this.engine=O(i),this.initialized=!0,this.logger.info("CausalAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CausalAdapter not initialized. Call initialize() first.")}verifyCausality(e,t,i){this.ensureInitialized();let n=Date.now();if(this.clear(),this.currentCause=e,this.currentEffect=t,this.setData(i.causeValues,i.effectValues),i.confounders)for(let[g,F]of Object.entries(i.confounders))this.addConfounder(g,F);let r=this.computeCausalEffect(),a=this.detectSpuriousCorrelation(),o=this.getConfounders(),d=this.determineRelationshipType(r,a,o.length>0),s=this.computeConfidence(i.sampleSize,r,a),l=Date.now()-n,c={isCausal:d==="causal",effectStrength:r,relationshipType:d,confidence:s,confounders:o,explanation:this.generateExplanation(e,t,d,r,o),durationMs:l,usedFallback:!1};return this.logger.info("Verified causality",{cause:e,effect:t,isCausal:c.isCausal,relationshipType:d,effectStrength:r,durationMs:l}),c}setData(e,t){if(this.ensureInitialized(),e.length!==t.length)throw new Error(`Cause and effect arrays must have same length. Got ${e.length} and ${t.length}.`);let i=new Float64Array(e),n=new Float64Array(t);this.engine.set_data(i,n),this.logger.debug("Set causal data",{sampleSize:e.length})}addConfounder(e,t){this.ensureInitialized();let i=new Float64Array(t);this.engine.add_confounder(e,i),this.logger.debug("Added confounder",{name:e,valueCount:t.length})}computeCausalEffect(){this.ensureInitialized();let e=this.engine.compute_causal_effect();return this.logger.debug("Computed causal effect",{effect:e}),e}detectSpuriousCorrelation(){this.ensureInitialized();let e=this.engine.detect_spurious_correlation();return this.logger.debug("Detected spurious correlation",{isSpurious:e}),e}getConfounders(){return this.ensureInitialized(),this.engine.get_confounders()}determineRelationshipType(e,t,i){return e<.1?"none":t?"spurious":i?"confounded":e<0?"reverse":"causal"}computeConfidence(e,t,i){let n=Math.min(1,e/100)*.5;return n+=Math.abs(t)*.3,i&&(n+=.15),Math.min(.95,n)}generateExplanation(e,t,i,n,r){switch(i){case"causal":return`Analysis indicates a true causal relationship between '${e}' and '${t}'. Effect strength: ${(n*100).toFixed(1)}%. Changes in '${e}' are likely to cause changes in '${t}'.`;case"spurious":return`The correlation between '${e}' and '${t}' appears to be spurious. No true causal mechanism detected. This may be coincidental or due to a hidden common cause.`;case"reverse":return`Analysis suggests reverse causation: '${t}' may cause '${e}', not the other way around. Consider swapping the direction of your hypothesis.`;case"confounded":return`The relationship between '${e}' and '${t}' is confounded by: ${r.join(", ")}. These variables may explain the observed correlation without direct causation.`;case"none":return`No significant relationship detected between '${e}' and '${t}'. Effect strength is below the detection threshold.`;default:return`Analysis complete for '${e}' -> '${t}'.`}}clear(){this.ensureInitialized(),this.engine.clear(),this.currentCause="",this.currentEffect="",this.logger.debug("Cleared causal engine state")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.initialized=!1,this.logger.info("CausalAdapter disposed")}};function H(u){let e=new Map,t=[],i=()=>({objects:Array.from(e.entries()).map(([n,r])=>({name:n,schema:r})),morphisms:t.map(n=>({source:n.source,target:n.target,name:n.name}))});return{add_type(n,r){e.set(n,r)},add_morphism(n,r,a){t.push({source:n,target:r,name:a})},verify_composition(n){if(n.length<2)return!0;for(let a=0;a<n.length-1;a++){let o=n[a],d=n[a+1];if(!t.some(l=>l.source===o&&l.target===d))return!1}let r=i();return u.verifyCategoryLaws(r)},check_type_consistency(){let n=[];for(let r of t)e.has(r.source)||n.push({location:r.name,expected:"defined type",actual:`undefined type '${r.source}'`}),e.has(r.target)||n.push({location:r.name,expected:"defined type",actual:`undefined type '${r.target}'`});return n},clear(){e.clear(),t.length=0}}}var C=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;types=new Map;morphisms=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CategoryAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CategoryAdapter.");let t=await this.wasmLoader.load(),i=new t.CategoryEngine;this.engine=H(i),this.initialized=!0,this.logger.info("CategoryAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CategoryAdapter not initialized. Call initialize() first.")}addType(e,t){this.ensureInitialized(),this.types.set(e,t),this.engine.add_type(e,t),this.logger.debug("Added type to category",{name:e})}addMorphism(e,t,i){this.ensureInitialized(),this.morphisms.push({source:e,target:t,name:i}),this.engine.add_morphism(e,t,i),this.logger.debug("Added morphism to category",{source:e,target:t,name:i})}verifyComposition(e){if(this.ensureInitialized(),e.length<2)return!0;let t=this.engine.verify_composition(e);return this.logger.debug("Verified composition",{path:e,isValid:t}),t}checkTypeConsistency(){this.ensureInitialized();let t=this.engine.check_type_consistency().map(i=>this.transformMismatch(i));return this.logger.debug("Checked type consistency",{mismatchCount:t.length}),t}verifyPipeline(e){let t=Date.now();this.clear(),this.addType(e.inputType,this.inferSchema(e.inputType)),this.addType(e.outputType,this.inferSchema(e.outputType));for(let s of e.elements)this.addType(s.inputType,this.inferSchema(s.inputType)),this.addType(s.outputType,this.inferSchema(s.outputType));for(let s of e.elements)this.addMorphism(s.inputType,s.outputType,s.name);let i=this.buildCompositionPath(e),n=this.verifyComposition(i),r=this.checkTypeConsistency(),a=this.generateWarnings(e,n,r),o=Date.now()-t,d={isValid:n&&r.length===0,mismatches:r,warnings:a,durationMs:o,usedFallback:!1};return this.logger.info("Verified pipeline",{pipelineId:e.id,isValid:d.isValid,mismatchCount:r.length,warningCount:a.length,durationMs:o}),d}buildCompositionPath(e){let t=[e.inputType];for(let i of e.elements)i.inputType!==t[t.length-1]&&t.push(i.inputType),t.push(i.outputType);return t[t.length-1]!==e.outputType&&t.push(e.outputType),t}inferSchema(e){return e.endsWith("[]")?`{ items: ${e.slice(0,-2)}[] }`:e.includes("|")?`{ union: [${e.split("|").map(t=>`"${t.trim()}"`).join(", ")}] }`:`{ type: "${e}" }`}transformMismatch(e){return{location:e.location,expected:e.expected,actual:e.actual,severity:this.determineMismatchSeverity(e)}}determineMismatchSeverity(e){return e.expected==="never"||e.actual==="never"?"critical":e.actual==="any"||e.actual==="unknown"?"high":e.expected.includes(e.actual)||e.actual.includes(e.expected)?"medium":"low"}generateWarnings(e,t,i){let n=[];t||n.push(`Pipeline '${e.id}' has an invalid composition chain. Types do not connect properly from input to output.`);for(let a of e.elements)(a.inputType==="any"||a.outputType==="any")&&n.push(`Element '${a.name}' uses 'any' type, which bypasses type safety.`);for(let a of e.elements)(a.inputType.includes("<T>")||a.outputType.includes("<T>"))&&n.push(`Element '${a.name}' has unconstrained generic types.`);let r=i.filter(a=>a.severity==="critical");return r.length>0&&n.push(`Found ${r.length} critical type mismatch(es) that will cause runtime errors.`),n}clear(){this.ensureInitialized(),this.types.clear(),this.morphisms.length=0,this.engine.clear(),this.logger.debug("Cleared category")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.types.clear(),this.morphisms.length=0,this.initialized=!1,this.logger.info("CategoryAdapter disposed")}getTypeCount(){return this.types.size}getMorphismCount(){return this.morphisms.length}};function V(u){let e=new Map,t=new Map;return{add_proposition(i,n){e.set(i,{formula:n,proven:!1})},add_proof(i,n){let r=e.get(i);if(!r)return!1;let a={id:i,proof:n},o={formula:r.formula};return u.typeCheck(a,o)?.valid?(r.proven=!0,t.set(i,n),!0):!1},verify_path_equivalence(i,n){let r={steps:i},a={steps:n};return u.checkTypeEquivalence(r,a)},get_unproven_propositions(){let i=[];return e.forEach((n,r)=>{n.proven||i.push(r)}),i},clear(){e.clear(),t.clear()}}}var w=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;propositions=new Map;async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing HomotopyAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize HomotopyAdapter.");let t=await this.wasmLoader.load(),i=new t.HoTTEngine;this.engine=V(i),this.initialized=!0,this.logger.info("HomotopyAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("HomotopyAdapter not initialized. Call initialize() first.")}addProposition(e,t){this.ensureInitialized();let i={id:e,formula:t,proven:!1};this.propositions.set(e,i),this.engine.add_proposition(e,t),this.logger.debug("Added proposition",{id:e,formula:t})}addProof(e,t){this.ensureInitialized();let i=this.propositions.get(e);if(!i)return this.logger.warn("Proposition not found",{propositionId:e}),!1;let n=this.engine.add_proof(e,t);return n?(i.proven=!0,this.logger.info("Proposition proven",{propositionId:e})):this.logger.warn("Proof rejected",{propositionId:e}),n}verifyPathEquivalence(e,t){this.ensureInitialized();let i=this.engine.verify_path_equivalence(e,t),n=this.generateEquivalenceExplanation(e,t,i),r={equivalent:i,path1:e,path2:t,explanation:n};return this.logger.debug("Verified path equivalence",{path1Length:e.length,path2Length:t.length,equivalent:i}),r}generateEquivalenceExplanation(e,t,i){if(i)return e.length===t.length?"The execution paths are homotopically equivalent. Both paths traverse the same abstract structure and will produce equivalent results.":`The execution paths are equivalent despite different lengths. The ${e.length>t.length?"first":"second"} path contains redundant steps that can be contracted without changing the result (homotopy contraction).`;{let n=0,r=Math.min(e.length,t.length);for(;n<r&&e[n]===t[n];)n++;return n===0?`The execution paths diverge immediately. Path 1 starts with '${e[0]}' while Path 2 starts with '${t[0]}'. These lead to fundamentally different computation spaces.`:`The execution paths diverge at step ${n+1}. After '${e[n-1]}', Path 1 proceeds to '${e[n]}' while Path 2 proceeds to '${t[n]}'. No homotopy exists between these paths.`}}getUnprovenPropositions(){return this.ensureInitialized(),this.engine.get_unproven_propositions()}getVerificationStatus(){let e=this.propositions.size,t=Array.from(this.propositions.values()).filter(n=>n.proven).length,i=this.getUnprovenPropositions();return{totalPropositions:e,provenCount:t,unprovenIds:i,verificationPercentage:e>0?t/e*100:100}}getProposition(e){return this.propositions.get(e)}clear(){this.ensureInitialized(),this.propositions.clear(),this.engine.clear(),this.logger.debug("Cleared homotopy engine")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.propositions.clear(),this.initialized=!1,this.logger.info("HomotopyAdapter disposed")}getPropositionCount(){return this.propositions.size}};import{createHash as $}from"crypto";var E=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;witnesses=new Map;decisions=new Map;witnessCounter=0;async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing WitnessAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize WitnessAdapter.");let t=await this.wasmLoader.load();this.engine=this.createWitnessEngine(t),this.initialized=!0,this.logger.info("WitnessAdapter initialized successfully")}createWitnessEngine(e){return this.createFallbackEngine()}createFallbackEngine(){let e=[];return{create_witness:(t,i)=>{let r={hash:this.computeHash(t,i),previousHash:i,position:e.length,timestamp:Date.now()};return e.push(r),r},verify_witness:(t,i)=>{let n=e.find(a=>a.hash===i);return this.computeHash(t,n?.previousHash)===i},verify_chain:t=>{if(t.length===0)return!0;if(t[0].previousHash!==void 0)return!1;for(let i=1;i<t.length;i++)if(t[i].previousHash!==t[i-1].hash)return!1;return!0},get_chain_length:()=>e.length}}computeHash(e,t){let i=$("sha256");return i.update(e),t&&i.update(t,"utf-8"),i.digest("hex")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("WitnessAdapter not initialized. Call initialize() first.")}createWitness(e){this.ensureInitialized();let t=this.serializeDecision(e),i=this.getLastWitness(),n=i?.hash,r=this.engine.create_witness(t,n),a=`witness-${++this.witnessCounter}-${Date.now()}`,o={witnessId:a,decisionId:e.id,hash:r.hash,previousWitnessId:i?.witnessId,chainPosition:r.position,timestamp:new Date(r.timestamp)};return this.witnesses.set(a,o),this.decisions.set(e.id,e),this.logger.info("Created witness",{witnessId:a,decisionId:e.id,chainPosition:o.chainPosition}),o}verifyWitness(e,t){this.ensureInitialized();let i=this.serializeDecision(e),n=this.engine.verify_witness(i,t);return this.logger.debug("Verified witness",{decisionId:e.id,hash:t,isValid:n}),n}verifyChain(e){if(this.ensureInitialized(),e.length===0)return!0;let t=e.map(n=>({hash:n.hash,previousHash:n.previousWitnessId?this.witnesses.get(n.previousWitnessId)?.hash:void 0,position:n.chainPosition,timestamp:n.timestamp.getTime()})),i=this.engine.verify_chain(t);return this.logger.info("Verified witness chain",{chainLength:e.length,isValid:i}),i}replayFromWitness(e){let t=Date.now(),i=this.witnesses.get(e);if(!i)return{success:!1,decision:this.createEmptyDecision(),matchesOriginal:!1,differences:[`Witness not found: ${e}`],durationMs:Date.now()-t};let n=this.decisions.get(i.decisionId);if(!n)return{success:!1,decision:this.createEmptyDecision(),matchesOriginal:!1,differences:[`Decision not found: ${i.decisionId}`],durationMs:Date.now()-t};let r=this.verifyWitness(n,i.hash),a=Date.now()-t,o={success:!0,decision:n,matchesOriginal:r,differences:r?void 0:["Hash mismatch detected"],durationMs:a};return this.logger.info("Replayed from witness",{witnessId:e,decisionId:n.id,matchesOriginal:r,durationMs:a}),o}getChainLength(){return this.ensureInitialized(),this.engine.get_chain_length()}getWitnessChain(){return Array.from(this.witnesses.values()).sort((e,t)=>e.chainPosition-t.chainPosition)}getWitness(e){return this.witnesses.get(e)}getLastWitness(){let e=this.getWitnessChain();return e[e.length-1]}serializeDecision(e){let t=JSON.stringify({id:e.id,type:e.type,inputs:e.inputs,output:e.output,agents:e.agents,timestamp:e.timestamp.toISOString(),reasoning:e.reasoning});return new TextEncoder().encode(t)}createEmptyDecision(){return{id:"",type:"routing",inputs:{},output:null,agents:[],timestamp:new Date}}dispose(){this.witnesses.clear(),this.decisions.clear(),this.witnessCounter=0,this.engine=null,this.initialized=!1,this.logger.info("WitnessAdapter disposed")}};var I=class{constructor(e,t={},i){this.wasmLoader=e;this.config={...M,...t},this.logger=i||m}wasmLoader;config;logger;cohomologyAdapter=null;spectralAdapter=null;causalAdapter=null;categoryAdapter=null;homotopyAdapter=null;witnessAdapter=null;initialized=!1;stats={totalChecks:0,coherentCount:0,incoherentCount:0,averageEnergy:0,averageDurationMs:0,totalContradictions:0,laneDistribution:{reflex:0,retrieval:0,heavy:0,human:0},fallbackCount:0,wasmAvailable:!1};totalEnergySum=0;totalDurationSum=0;async initialize(){if(this.initialized)return;this.logger.info("Initializing CoherenceService");let e=await this.wasmLoader.isAvailable();if(!e&&!this.config.fallbackEnabled)throw new h("WASM module is not available and fallback is disabled. Enable fallbackEnabled in config to use TypeScript fallback.");if(this.stats.wasmAvailable=e,e)try{this.cohomologyAdapter=new y(this.wasmLoader,this.logger),this.spectralAdapter=new v(this.wasmLoader,this.logger),this.causalAdapter=new b(this.wasmLoader,this.logger),this.categoryAdapter=new C(this.wasmLoader,this.logger),this.homotopyAdapter=new w(this.wasmLoader,this.logger),this.witnessAdapter=new E(this.wasmLoader,this.logger),await Promise.all([this.cohomologyAdapter.initialize(),this.spectralAdapter.initialize(),this.causalAdapter.initialize(),this.categoryAdapter.initialize(),this.homotopyAdapter.initialize(),this.witnessAdapter.initialize()]),this.logger.info("All coherence engine adapters initialized")}catch(t){if(!this.config.fallbackEnabled)throw t;this.logger.warn("WASM initialization failed, using fallback",{error:t instanceof Error?t.message:"Unknown error"}),this.stats.wasmAvailable=!1}else this.logger.info("WASM not available, using TypeScript fallback");this.initialized=!0,this.logger.info("CoherenceService initialized",{wasmAvailable:this.stats.wasmAvailable,fallbackEnabled:this.config.fallbackEnabled})}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized)throw new f("CoherenceService not initialized. Call initialize() first.","NOT_INITIALIZED")}async checkCoherence(e){this.ensureInitialized();let t=Date.now();try{return this.cohomologyAdapter?.isInitialized()?await this.checkCoherenceWithWasm(e,t):this.checkCoherenceWithFallback(e,t)}catch(i){return this.logger.error("Coherence check failed",A(i)),{energy:1,isCoherent:!1,lane:"human",contradictions:[],recommendations:["Coherence check failed. Manual review recommended."],durationMs:Date.now()-t,usedFallback:!0}}}async checkCoherenceWithWasm(e,t){this.cohomologyAdapter.clear();for(let o of e)this.cohomologyAdapter.addNode(o);this.buildEdgesFromNodes(e);let i=this.cohomologyAdapter.computeEnergy(),n=this.cohomologyAdapter.detectContradictions(this.config.coherenceThreshold),r=this.computeLane(i),a=Date.now()-t;return this.updateStats(i,a,n.length,r,!1),{energy:i,isCoherent:i<this.config.coherenceThreshold,lane:r,contradictions:n,recommendations:this.generateRecommendations(i,r,n),durationMs:a,usedFallback:!1}}checkCoherenceWithFallback(e,t){this.stats.fallbackCount++;let i=0,n=0,r=[];for(let s=0;s<e.length;s++)for(let l=s+1;l<e.length;l++){let c=this.euclideanDistance(e[s].embedding,e[l].embedding);i+=c,n++,c>1.5&&r.push({nodeIds:[e[s].id,e[l].id],severity:c>2?"critical":"high",description:`High distance (${c.toFixed(2)}) between nodes`,confidence:Math.min(1,c/2)})}let a=n>0?i/n:0,o=this.computeLane(a),d=Date.now()-t;return this.updateStats(a,d,r.length,o,!0),{energy:a,isCoherent:a<this.config.coherenceThreshold,lane:o,contradictions:r,recommendations:this.generateRecommendations(a,o,r),durationMs:d,usedFallback:!0}}buildEdgesFromNodes(e){for(let t=0;t<e.length;t++)for(let i=t+1;i<e.length;i++){let n=this.cosineSimilarity(e[t].embedding,e[i].embedding);n>.3&&this.cohomologyAdapter.addEdge({source:e[t].id,target:e[i].id,weight:n})}}async detectContradictions(e){this.ensureInitialized();let t=e.map(n=>({id:n.id,embedding:n.embedding,weight:n.confidence,metadata:{statement:n.statement,source:n.source}}));return(await this.checkCoherence(t)).contradictions}async predictCollapse(e){if(this.ensureInitialized(),!e.agents||e.agents.length===0)return{risk:0,fiedlerValue:0,collapseImminent:!1,weakVertices:[],recommendations:["No agents to analyze"],durationMs:0,usedFallback:!0};if(this.spectralAdapter?.isInitialized())try{return this.spectralAdapter.analyzeSwarmState(e)}catch(t){return this.logger.warn("Spectral collapse prediction failed, using fallback",{error:p(t),agentCount:e.agents.length}),this.predictCollapseWithFallback(e)}return this.predictCollapseWithFallback(e)}predictCollapseWithFallback(e){let t=Date.now(),i=e.agents.reduce((o,d)=>o+d.health,0)/Math.max(e.agents.length,1),n=e.agents.reduce((o,d)=>o+d.successRate,0)/Math.max(e.agents.length,1),r=0;r+=(1-i)*.3,r+=(1-n)*.3,r+=e.errorRate*.2,r+=e.utilization>.9?.2:e.utilization*.1;let a=e.agents.filter(o=>o.health<.5||o.successRate<.5).map(o=>o.agentId);return{risk:Math.min(1,r),fiedlerValue:i*n,collapseImminent:r>.7,weakVertices:a,recommendations:r>.5?["System health degraded. Consider spawning additional agents."]:["System health is acceptable."],durationMs:Date.now()-t,usedFallback:!0}}async verifyCausality(e,t,i){return this.ensureInitialized(),this.causalAdapter?.isInitialized()?this.causalAdapter.verifyCausality(e,t,i):this.verifyCausalityWithFallback(e,t,i)}verifyCausalityWithFallback(e,t,i){let n=Date.now(),r=this.computeCorrelation(i.causeValues,i.effectValues),a=Math.abs(r);return{isCausal:a>.5,effectStrength:a,relationshipType:a<.2?"none":a>.5?"causal":"spurious",confidence:Math.min(.7,i.sampleSize/100),confounders:[],explanation:`Correlation-based analysis: r=${r.toFixed(3)}. Note: Correlation does not imply causation. This is a fallback analysis without full causal inference.`,durationMs:Date.now()-n,usedFallback:!0}}async verifyTypes(e){return this.ensureInitialized(),this.categoryAdapter?.isInitialized()?this.categoryAdapter.verifyPipeline(e):this.verifyTypesWithFallback(e)}verifyTypesWithFallback(e){let t=Date.now(),i=[],n=e.inputType;for(let r of e.elements)r.inputType!==n&&n!=="any"&&i.push({location:r.name,expected:n,actual:r.inputType,severity:"high"}),n=r.outputType;return n!==e.outputType&&n!=="any"&&i.push({location:"pipeline output",expected:e.outputType,actual:n,severity:"critical"}),{isValid:i.length===0,mismatches:i,warnings:["Using fallback type verification. Full categorical analysis unavailable."],durationMs:Date.now()-t,usedFallback:!0}}async createWitness(e){return this.ensureInitialized(),this.witnessAdapter?.isInitialized()?this.witnessAdapter.createWitness(e):{witnessId:`witness-fallback-${Date.now()}`,decisionId:e.id,hash:this.simpleHash(JSON.stringify(e)),chainPosition:0,timestamp:new Date}}async replayFromWitness(e){return this.ensureInitialized(),this.witnessAdapter?.isInitialized()?this.witnessAdapter.replayFromWitness(e):{success:!1,decision:{id:"",type:"routing",inputs:{},output:null,agents:[],timestamp:new Date},matchesOriginal:!1,differences:["Replay not available in fallback mode"],durationMs:0}}async checkSwarmCoherence(e){this.ensureInitialized();let t=[];return e.forEach((i,n)=>{let r=this.agentHealthToEmbedding(i);t.push({id:n,embedding:r,weight:i.health,metadata:{agentType:i.agentType,successRate:i.successRate,errorCount:i.errorCount}})}),this.checkCoherence(t)}async verifyConsensus(e){this.ensureInitialized();let t=Date.now();if(e.length<2)return{isValid:e.length===1,confidence:e.length===1?e[0].confidence:0,isFalseConsensus:!1,fiedlerValue:e.length===1?1:0,collapseRisk:0,recommendation:e.length===0?"No votes to analyze":"Single vote - consensus trivially achieved",durationMs:Date.now()-t,usedFallback:!0};if(this.spectralAdapter?.isInitialized())try{this.spectralAdapter.clear();for(let a of e)this.spectralAdapter.addNode(a.agentId);let i=0;for(let a=0;a<e.length;a++)for(let o=a+1;o<e.length;o++)e[a].verdict===e[o].verdict&&(this.spectralAdapter.addEdge(e[a].agentId,e[o].agentId,Math.min(e[a].confidence,e[o].confidence)),i++);if(i===0)return this.logger.debug("No agreement edges, using fallback consensus"),this.verifyConsensusWithFallback(e,t);let n=this.spectralAdapter.predictCollapseRisk(),r=this.spectralAdapter.computeFiedlerValue();return{isValid:n<.3&&r>.1,confidence:1-n,isFalseConsensus:r<.05,fiedlerValue:r,collapseRisk:n,recommendation:n>.3?"Spawn independent reviewer":"Consensus verified",durationMs:Date.now()-t,usedFallback:!1}}catch(i){return this.logger.warn("Spectral consensus verification failed, using fallback",{error:p(i),voteCount:e.length}),this.verifyConsensusWithFallback(e,t)}return this.verifyConsensusWithFallback(e,t)}verifyConsensusWithFallback(e,t){let i=new Map;for(let o of e){let d=String(o.verdict);i.set(d,(i.get(d)||0)+1)}let n=0;i.forEach(o=>{n=Math.max(n,o)});let r=n/e.length,a=e.reduce((o,d)=>o+d.confidence,0)/e.length;return{isValid:r>.6,confidence:r*a,isFalseConsensus:i.size===1&&e.length>2,fiedlerValue:r,collapseRisk:1-r,recommendation:r<.6?"No clear majority. Consider spawning additional agents.":r===1&&i.size===1?"Unanimous consensus may indicate false consensus. Consider adding diversity.":"Majority consensus achieved.",durationMs:Date.now()-t,usedFallback:!0}}async filterCoherent(e,t){if(this.ensureInitialized(),e.length===0)return[];if(e.length===1)return e;let i=e.map(a=>({id:a.id,embedding:a.embedding})),n=await this.checkCoherence(i);if(n.isCoherent)return e;let r=new Set;for(let a of n.contradictions)a.nodeIds.forEach(o=>r.add(o));return e.filter(a=>!r.has(a.id))}getStats(){return{...this.stats,averageEnergy:this.stats.totalChecks>0?this.totalEnergySum/this.stats.totalChecks:0,averageDurationMs:this.stats.totalChecks>0?this.totalDurationSum/this.stats.totalChecks:0,lastCheckAt:this.stats.lastCheckAt}}async dispose(){this.cohomologyAdapter?.dispose(),this.spectralAdapter?.dispose(),this.causalAdapter?.dispose(),this.categoryAdapter?.dispose(),this.homotopyAdapter?.dispose(),this.witnessAdapter?.dispose(),this.cohomologyAdapter=null,this.spectralAdapter=null,this.causalAdapter=null,this.categoryAdapter=null,this.homotopyAdapter=null,this.witnessAdapter=null,this.initialized=!1,this.logger.info("CoherenceService disposed")}computeLane(e){let{laneConfig:t}=this.config;return e<t.reflexThreshold?"reflex":e<t.retrievalThreshold?"retrieval":e<t.heavyThreshold?"heavy":"human"}updateStats(e,t,i,n,r){this.stats.totalChecks++,this.totalEnergySum+=e,this.totalDurationSum+=t,this.stats.totalContradictions+=i,this.stats.laneDistribution[n]++,this.stats.lastCheckAt=new Date,e<this.config.coherenceThreshold?this.stats.coherentCount++:this.stats.incoherentCount++,r&&this.stats.fallbackCount++}generateRecommendations(e,t,i){let n=[];if(t==="reflex"?n.push("Low energy detected. Safe to proceed with immediate execution."):t==="retrieval"?n.push("Moderate energy detected. Consider fetching additional context before proceeding."):t==="heavy"?n.push("High energy detected. Deep analysis recommended before proceeding."):n.push("Critical energy level. Escalate to human review (Queen agent)."),i.length>0){let r=i.filter(a=>a.severity==="critical");r.length>0&&n.push(`Found ${r.length} critical contradiction(s) that must be resolved.`)}return n}agentHealthToEmbedding(e){let t=e.beliefs??[];return[e.health,e.successRate,Math.min(1,e.errorCount/10),this.agentTypeToNumber(e.agentType),t.length/10,...t[0]?.embedding.slice(0,5)||[0,0,0,0,0],...t[1]?.embedding.slice(0,5)||[0,0,0,0,0],...t[2]?.embedding.slice(0,5)||[0,0,0,0,0]]}agentTypeToNumber(e){let t=["coordinator","specialist","analyzer","generator","validator","tester","reviewer","optimizer"],i=t.indexOf(e);return i>=0?i/t.length:.5}euclideanDistance(e,t){if(e.length!==t.length)return 1/0;let i=0;for(let n=0;n<e.length;n++)i+=(e[n]-t[n])**2;return Math.sqrt(i)}cosineSimilarity(e,t){if(e.length!==t.length||e.length===0)return 0;let i=0,n=0,r=0;for(let o=0;o<e.length;o++)i+=e[o]*t[o],n+=e[o]*e[o],r+=t[o]*t[o];let a=Math.sqrt(n)*Math.sqrt(r);return a===0?0:i/a}computeCorrelation(e,t){if(e.length!==t.length||e.length<2)return 0;let i=e.length,n=e.reduce((l,c)=>l+c,0)/i,r=t.reduce((l,c)=>l+c,0)/i,a=0,o=0,d=0;for(let l=0;l<i;l++){let c=e[l]-n,g=t[l]-r;a+=c*g,o+=c*c,d+=g*g}let s=Math.sqrt(o*d);return s===0?0:a/s}simpleHash(e){let t=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);t=(t<<5)-t+n,t=t&t}return(t>>>0).toString(16).padStart(8,"0")}};async function Q(u,e,t){let i=new I(u,e,t);return await i.initialize(),i}L();import{createRequire as _}from"node:module";import{fileURLToPath as K}from"node:url";import{dirname as x,join as S}from"node:path";import{readFileSync as X,existsSync as P}from"node:fs";var W=[1e3,2e3,4e3],k=class{state="unloaded";wasmModule=null;engines=null;loadPromise=null;lastError=null;config;version="";fallbackState={mode:"wasm",consecutiveFailures:0,totalActivations:0,nextRetryAt:void 0,lastSuccessfulLoad:void 0};retryTimer=null;degradedModeStartTime=null;eventListeners;constructor(e={}){this.config={...z,...e},this.eventListeners=new Map,this.eventListeners.set("loaded",new Set),this.eventListeners.set("error",new Set),this.eventListeners.set("retry",new Set),this.eventListeners.set("degraded_mode",new Set),this.eventListeners.set("recovered",new Set)}isLoaded(){return this.state==="loaded"&&this.engines!==null}getState(){return this.state}getVersion(){return this.version}getLastError(){return this.lastError}isInDegradedMode(){return this.state==="degraded"||this.fallbackState.mode==="fallback"}getFallbackState(){return{...this.fallbackState}}getFallbackResult(){return{usedFallback:!0,confidence:.5,retryCount:this.fallbackState.consecutiveFailures,lastError:this.lastError?.message,activatedAt:this.degradedModeStartTime??new Date}}async getEngines(){if(this.state==="loaded"&&this.engines)return this.engines;if(this.state==="loading"&&this.loadPromise)return this.loadPromise;this.state="loading",this.loadPromise=this.loadWithRetry();try{return this.engines=await this.loadPromise,this.state="loaded",(this.fallbackState.mode==="fallback"||this.fallbackState.mode==="recovering")&&this.emitRecoveryEvent(),this.fallbackState.mode="wasm",this.fallbackState.consecutiveFailures=0,this.fallbackState.lastSuccessfulLoad=new Date,this.engines}catch(e){throw this.state="failed",this.lastError=A(e),this.enterDegradedMode(this.lastError),e}finally{this.loadPromise=null}}async getEnginesWithFallback(){if(this.state==="loaded"&&this.engines)return{engines:this.engines,fallback:{usedFallback:!1,confidence:1,retryCount:0}};if(this.state==="degraded")return{engines:null,fallback:this.getFallbackResult()};try{return{engines:await this.getEngines(),fallback:{usedFallback:!1,confidence:1,retryCount:0}}}catch{return{engines:null,fallback:this.getFallbackResult()}}}getEnginesSync(){if(!this.engines)throw new h("WASM module is not loaded. Call getEngines() first.");return this.engines}async isAvailable(){if(this.state==="loaded"&&this.wasmModule)return!0;if(this.state==="failed")return!1;try{let e=_(import.meta.url),t=[(()=>{try{let i=e.resolve("prime-radiant-advanced-wasm");return S(x(i),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),S(process.cwd(),"node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm")].filter(i=>i!==null);for(let i of t)if(P(i))return!0;return!1}catch{return!1}}async load(){if(await this.getEngines(),!this.wasmModule)throw new h("WASM module failed to load");return this.wasmModule}getModule(){if(!this.wasmModule)throw new h("WASM module is not loaded. Call load() first.");return this.wasmModule}on(e,t){let i=this.eventListeners.get(e);return i&&i.add(t),()=>{i?.delete(t)}}off(e,t){let i=this.eventListeners.get(e);i&&i.delete(t)}reset(){if(this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.engines)try{this.engines.cohomology.free(),this.engines.spectral.free(),this.engines.causal.free(),this.engines.category.free(),this.engines.hott.free(),this.engines.quantum.free()}catch(e){console.debug("[WASMLoader] Cleanup error during unload:",e instanceof Error?e.message:e)}this.state="unloaded",this.wasmModule=null,this.engines=null,this.loadPromise=null,this.lastError=null,this.version="",this.fallbackState={mode:"wasm",consecutiveFailures:0,totalActivations:0,nextRetryAt:void 0,lastSuccessfulLoad:void 0},this.degradedModeStartTime=null}async forceRetry(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),(this.state==="failed"||this.state==="degraded")&&(this.state="unloaded",this.fallbackState.mode="recovering");try{return await this.getEngines(),!0}catch{return!1}}async loadWithRetry(){let{maxAttempts:e,baseDelayMs:t,maxDelayMs:i}=this.config,n=new Error("Unknown error");for(let r=1;r<=e;r++)try{let a=performance.now(),o=await this.attemptLoad(),d=performance.now()-a;return this.emit("loaded",{version:this.version,loadTimeMs:Math.round(d*100)/100}),o}catch(a){if(n=A(a),this.emit("error",{error:n,fatal:r>=e,attempt:r}),r<e){let o=Math.min(t*Math.pow(2,r-1),i);this.emit("retry",{attempt:r+1,maxAttempts:e,delayMs:o,previousError:n}),await this.sleep(o)}}throw new T(`Failed to load WASM module after ${e} attempts: ${n.message}`,e,n)}async attemptLoad(){let e;try{e=_(import.meta.url)}catch{e=globalThis.require||(await import("module")).createRequire(__filename)}let t;try{t=await import("./prime-radiant-advanced-wasm-EFKVL7VN.js")}catch(r){try{t=e("prime-radiant-advanced-wasm")}catch{throw new Error(`Failed to import prime-radiant-advanced-wasm: ${p(r)}`)}}if(typeof process<"u"&&process.versions!=null&&process.versions.node!=null?await this.initializeForNodeJs(t,e):t.default&&typeof t.default=="function"&&await t.default(),t.initModule&&typeof t.initModule=="function")try{t.initModule()}catch{}return t.getVersion&&typeof t.getVersion=="function"&&(this.version=t.getVersion()),this.wasmModule=t,{cohomology:new t.CohomologyEngine,spectral:new t.SpectralEngine,causal:new t.CausalEngine,category:new t.CategoryEngine,hott:new t.HoTTEngine,quantum:new t.QuantumEngine}}async initializeForNodeJs(e,t){let i=[(()=>{try{let a=t.resolve("prime-radiant-advanced-wasm");return S(x(a),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),S(x(K(import.meta.url)),"../../../../node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm"),S(process.cwd(),"node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm")].filter(a=>a!==null),n=null;for(let a of i)if(P(a)){n=a;break}if(!n)throw new Error(`Could not find WASM binary. Searched paths:
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.12.2");process.exit(0)}
2
+ import{a as p,b as A,c as L}from"./chunk-X47GHZY3.js";var R={reflexThreshold:.1,retrievalThreshold:.4,heavyThreshold:.7},M={enabled:!0,laneConfig:R,coherenceThreshold:.1,fallbackEnabled:!0,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},m={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},f=class extends Error{constructor(t,i,n){super(t);this.code=i;this.cause=n;this.name="CoherenceError"}code;cause},h=class extends f{constructor(e="WASM module is not loaded",t){super(e,"WASM_NOT_LOADED",t),this.name="WasmNotLoadedError"}};var T=class extends f{constructor(t,i,n){super(t,"WASM_LOAD_FAILED",n);this.attempts=i;this.name="WasmLoadError"}attempts},z={maxAttempts:3,baseDelayMs:100,maxDelayMs:5e3,timeoutMs:1e4};L();function D(u){let e=new Map,t=[],i=new Map,n=new Map,r=0,a=s=>{let l=i.get(s);return l===void 0&&(l=r++,i.set(s,l),n.set(l,s)),l},o=s=>n.get(s)??`unknown-${s}`,d=()=>({nodes:Array.from(e.entries()).map(([s,l])=>({id:a(s),label:s,section:Array.from(l.embedding),weight:1})),edges:t.map(s=>({source:a(s.source),target:a(s.target),weight:s.weight}))});return{add_node(s,l){e.set(s,{embedding:l}),a(s)},add_edge(s,l,c){t.push({source:s,target:l,weight:c}),a(s),a(l)},remove_node(s){e.delete(s);for(let l=t.length-1;l>=0;l--)(t[l].source===s||t[l].target===s)&&t.splice(l,1)},remove_edge(s,l){let c=t.findIndex(g=>g.source===s&&g.target===l);c>=0&&t.splice(c,1)},sheaf_laplacian_energy(){let s=d();return u.consistencyEnergy(s)},detect_contradictions(s){let l=d(),c=u.detectObstructions(l);return c?c.filter(g=>g.energy>s).map(g=>({node1:o(g.node1),node2:o(g.node2),severity:g.energy,distance:g.energy})):[]},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var y=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;nodes=new Map;edges=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CohomologyAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CohomologyAdapter.");let t=await this.wasmLoader.load(),i=new t.CohomologyEngine;this.engine=D(i),this.initialized=!0,this.logger.info("CohomologyAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CohomologyAdapter not initialized. Call initialize() first.")}addNode(e){this.ensureInitialized(),this.nodes.set(e.id,e);let t=new Float64Array(e.embedding);this.engine.add_node(e.id,t),this.logger.debug("Added node to cohomology graph",{nodeId:e.id,embeddingDim:e.embedding.length})}addEdge(e){this.ensureInitialized(),this.edges.push(e),this.engine.add_edge(e.source,e.target,e.weight),this.logger.debug("Added edge to cohomology graph",{source:e.source,target:e.target,weight:e.weight})}removeNode(e){this.ensureInitialized(),this.nodes.delete(e),this.engine.remove_node(e);let t=[];this.edges.forEach((i,n)=>{(i.source===e||i.target===e)&&t.push(n)}),t.reverse().forEach(i=>this.edges.splice(i,1)),this.logger.debug("Removed node from cohomology graph",{nodeId:e})}removeEdge(e,t){this.ensureInitialized();let i=this.edges.findIndex(n=>n.source===e&&n.target===t);i>=0&&this.edges.splice(i,1),this.engine.remove_edge(e,t),this.logger.debug("Removed edge from cohomology graph",{source:e,target:t})}computeEnergy(){this.ensureInitialized();let e=this.engine.sheaf_laplacian_energy();return this.logger.debug("Computed sheaf Laplacian energy",{energy:e}),e}detectContradictions(e=.1){this.ensureInitialized();let i=this.engine.detect_contradictions(e).map(n=>this.transformContradiction(n));return this.logger.debug("Detected contradictions",{count:i.length,threshold:e}),i}transformContradiction(e){return{nodeIds:[e.node1,e.node2],severity:this.severityFromDistance(e.severity),description:this.generateContradictionDescription(e),confidence:1-e.distance,resolution:this.suggestResolution(e)}}severityFromDistance(e){return e>=.9?"critical":e>=.7?"high":e>=.4?"medium":e>=.2?"low":"info"}generateContradictionDescription(e){let t=this.nodes.get(e.node1),i=this.nodes.get(e.node2);return t?.metadata?.statement&&i?.metadata?.statement?`Contradiction detected between "${t.metadata.statement}" and "${i.metadata.statement}"`:`Contradiction detected between nodes '${e.node1}' and '${e.node2}' with distance ${e.distance.toFixed(3)}`}suggestResolution(e){return e.severity>=.9?"Critical contradiction requires manual review. Consider removing one of the conflicting beliefs.":e.severity>=.7?"High-severity contradiction. Recommend gathering additional evidence to determine which belief is correct.":e.severity>=.4?"Moderate contradiction. Consider adding context or constraints to differentiate the beliefs.":"Low-severity contradiction. May be resolved with additional context or can be safely ignored."}clear(){this.ensureInitialized(),this.nodes.clear(),this.edges.length=0,this.engine.clear(),this.logger.debug("Cleared cohomology graph")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.nodes.clear(),this.edges.length=0,this.initialized=!1,this.logger.info("CohomologyAdapter disposed")}getNodeCount(){return this.nodes.size}getEdgeCount(){return this.edges.length}getNode(e){return this.nodes.get(e)}};L();function N(u){let e=new Set,t=[],i=new Map,n=new Map,r=0,a=s=>{let l=i.get(s);return l===void 0&&(l=r++,i.set(s,l),n.set(l,s)),l},o=s=>n.get(s)??`unknown-${s}`,d=()=>({n:e.size,edges:t.map(s=>[a(s.source),a(s.target),s.weight])});return{add_node(s){e.add(s),a(s)},add_edge(s,l,c){t.push({source:s,target:l,weight:c}),a(s),a(l)},remove_node(s){e.delete(s);for(let l=t.length-1;l>=0;l--)(t[l].source===s||t[l].target===s)&&t.splice(l,1)},compute_fiedler_value(){if(e.size<2||t.length===0)return 0;try{let s=d(),l=u.algebraicConnectivity(s);return Number.isFinite(l)&&l>=0?l:0}catch(s){return console.warn("[SpectralAdapter] algebraicConnectivity failed:",s),0}},predict_collapse_risk(){if(e.size<2)return 0;if(t.length===0)return 1;try{let s=d(),l=u.algebraicConnectivity(s),c=Number.isFinite(l)&&l>=0?l:0;return Math.max(0,Math.min(1,1-c))}catch(s){return console.warn("[SpectralAdapter] predict_collapse_risk failed:",s),.8}},get_weak_vertices(s){if(e.size===0)return[];if(t.length===0)return Array.from(e).slice(0,s);try{let l=d(),c=u.predictMinCut(l);return c?.vertices?c.vertices.slice(0,s).map(g=>o(g)):Array.from(e).slice(0,s)}catch(l){return console.warn("[SpectralAdapter] predictMinCut failed:",l),Array.from(e).slice(0,s)}},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var v=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;nodes=new Set;edges=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing SpectralAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize SpectralAdapter.");let t=await this.wasmLoader.load(),i=new t.SpectralEngine;this.engine=N(i),this.initialized=!0,this.logger.info("SpectralAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("SpectralAdapter not initialized. Call initialize() first.")}addNode(e){if(this.ensureInitialized(),this.nodes.has(e)){this.logger.debug("Node already exists",{nodeId:e});return}this.nodes.add(e),this.engine.add_node(e),this.logger.debug("Added node to spectral graph",{nodeId:e})}addEdge(e,t,i){this.ensureInitialized(),this.nodes.has(e)||this.addNode(e),this.nodes.has(t)||this.addNode(t),this.edges.push({source:e,target:t,weight:i}),this.engine.add_edge(e,t,i),this.logger.debug("Added edge to spectral graph",{source:e,target:t,weight:i})}removeNode(e){this.ensureInitialized(),this.nodes.delete(e),this.engine.remove_node(e);for(let t=this.edges.length-1;t>=0;t--){let i=this.edges[t];(i.source===e||i.target===e)&&this.edges.splice(t,1)}this.logger.debug("Removed node from spectral graph",{nodeId:e})}computeFiedlerValue(){if(this.ensureInitialized(),this.nodes.size<2||this.edges.length===0)return 0;try{let e=this.engine.compute_fiedler_value();return this.logger.debug("Computed Fiedler value",{fiedlerValue:e}),e}catch(e){return this.logger.warn("Failed to compute Fiedler value",{error:p(e),nodeCount:this.nodes.size,edgeCount:this.edges.length}),0}}predictCollapseRisk(){if(this.ensureInitialized(),this.nodes.size<2)return 0;if(this.edges.length===0)return 1;try{let e=this.engine.predict_collapse_risk();return this.logger.debug("Predicted collapse risk",{risk:e}),e}catch(e){return this.logger.warn("Failed to predict collapse risk",{error:p(e),nodeCount:this.nodes.size,edgeCount:this.edges.length}),.8}}getWeakVertices(e){if(this.ensureInitialized(),this.nodes.size===0)return[];if(this.edges.length===0)return Array.from(this.nodes).slice(0,e);let t=Math.min(e,this.nodes.size);try{let i=this.engine.get_weak_vertices(t);return this.logger.debug("Retrieved weak vertices",{requested:e,returned:i.length}),i}catch(i){return this.logger.warn("Failed to get weak vertices",{error:p(i),nodeCount:this.nodes.size,edgeCount:this.edges.length}),Array.from(this.nodes).slice(0,e)}}analyzeSwarmState(e){let t=Date.now();this.clear();for(let d of e.agents)this.addNode(d.agentId);this.buildEdgesFromAgents(e.agents);let i=this.predictCollapseRisk(),n=this.computeFiedlerValue(),r=this.getWeakVertices(5),a=Date.now()-t,o={risk:i,fiedlerValue:n,collapseImminent:i>.7,weakVertices:r,recommendations:this.generateRecommendations(i,n,r),durationMs:a,usedFallback:!1};return this.logger.info("Analyzed swarm state",{agentCount:e.agents.length,risk:i,fiedlerValue:n,durationMs:a}),o}buildEdgesFromAgents(e){for(let t=0;t<e.length;t++)for(let i=t+1;i<e.length;i++){let n=this.computeAgentSimilarity(e[t],e[i]);n>.3&&this.addEdge(e[t].agentId,e[i].agentId,n)}}computeAgentSimilarity(e,t){let i=1-Math.abs(e.health-t.health),n=1-Math.abs(e.successRate-t.successRate),r=e.agentType===t.agentType?.2:0,a=0,o=e.beliefs??[],d=t.beliefs??[];return o.length>0&&d.length>0&&(a=this.computeBeliefOverlap(o,d)),i*.3+n*.3+r+a*.2}computeBeliefOverlap(e,t){if(e.length===0||t.length===0)return 0;let i=0,n=0;for(let r of e)for(let a of t)i+=this.cosineSimilarity(r.embedding,a.embedding),n++;return n>0?i/n:0}cosineSimilarity(e,t){if(e.length!==t.length||e.length===0)return 0;let i=0,n=0,r=0;for(let o=0;o<e.length;o++)i+=e[o]*t[o],n+=e[o]*e[o],r+=t[o]*t[o];let a=Math.sqrt(n)*Math.sqrt(r);return a===0?0:i/a}generateRecommendations(e,t,i){let n=[];return e>.7?(n.push("CRITICAL: Immediate action required to prevent swarm collapse."),n.push("Consider spawning additional coordination agents to strengthen connectivity.")):e>.5&&n.push("WARNING: Elevated collapse risk detected. Monitor closely."),t<.1&&n.push("Network connectivity is weak. Consider adding redundant communication channels."),t<.05&&(n.push("ALERT: Near-zero Fiedler value indicates potential false consensus."),n.push("Recommend spawning an independent reviewer to verify decisions.")),i.length>0&&n.push(`At-risk agents: ${i.join(", ")}. Consider reassigning critical tasks.`),n.length===0&&n.push("Swarm health is good. No immediate action required."),n}clear(){this.ensureInitialized(),this.nodes.clear(),this.edges.length=0,this.engine.clear(),this.logger.debug("Cleared spectral graph")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.nodes.clear(),this.edges.length=0,this.initialized=!1,this.logger.info("SpectralAdapter disposed")}getNodeCount(){return this.nodes.size}getEdgeCount(){return this.edges.length}};function O(u){let e=null,t=null,i=new Map,n=()=>({cause:e?Array.from(e):[],effect:t?Array.from(t):[],confounders:Object.fromEntries(Array.from(i.entries()).map(([r,a])=>[r,Array.from(a)]))});return{set_data(r,a){e=r,t=a},add_confounder(r,a){i.set(r,a)},compute_causal_effect(){let r=n();return u.computeCausalEffect(r,"cause","effect",1)?.effect??0},detect_spurious_correlation(){let r=n();return(u.findConfounders(r,"cause","effect")?.length??0)>0},get_confounders(){let r=n();return u.findConfounders(r,"cause","effect")??Array.from(i.keys())},clear(){e=null,t=null,i.clear()}}}var b=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;currentCause="";currentEffect="";async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CausalAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CausalAdapter.");let t=await this.wasmLoader.load(),i=new t.CausalEngine;this.engine=O(i),this.initialized=!0,this.logger.info("CausalAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CausalAdapter not initialized. Call initialize() first.")}verifyCausality(e,t,i){this.ensureInitialized();let n=Date.now();if(this.clear(),this.currentCause=e,this.currentEffect=t,this.setData(i.causeValues,i.effectValues),i.confounders)for(let[g,F]of Object.entries(i.confounders))this.addConfounder(g,F);let r=this.computeCausalEffect(),a=this.detectSpuriousCorrelation(),o=this.getConfounders(),d=this.determineRelationshipType(r,a,o.length>0),s=this.computeConfidence(i.sampleSize,r,a),l=Date.now()-n,c={isCausal:d==="causal",effectStrength:r,relationshipType:d,confidence:s,confounders:o,explanation:this.generateExplanation(e,t,d,r,o),durationMs:l,usedFallback:!1};return this.logger.info("Verified causality",{cause:e,effect:t,isCausal:c.isCausal,relationshipType:d,effectStrength:r,durationMs:l}),c}setData(e,t){if(this.ensureInitialized(),e.length!==t.length)throw new Error(`Cause and effect arrays must have same length. Got ${e.length} and ${t.length}.`);let i=new Float64Array(e),n=new Float64Array(t);this.engine.set_data(i,n),this.logger.debug("Set causal data",{sampleSize:e.length})}addConfounder(e,t){this.ensureInitialized();let i=new Float64Array(t);this.engine.add_confounder(e,i),this.logger.debug("Added confounder",{name:e,valueCount:t.length})}computeCausalEffect(){this.ensureInitialized();let e=this.engine.compute_causal_effect();return this.logger.debug("Computed causal effect",{effect:e}),e}detectSpuriousCorrelation(){this.ensureInitialized();let e=this.engine.detect_spurious_correlation();return this.logger.debug("Detected spurious correlation",{isSpurious:e}),e}getConfounders(){return this.ensureInitialized(),this.engine.get_confounders()}determineRelationshipType(e,t,i){return e<.1?"none":t?"spurious":i?"confounded":e<0?"reverse":"causal"}computeConfidence(e,t,i){let n=Math.min(1,e/100)*.5;return n+=Math.abs(t)*.3,i&&(n+=.15),Math.min(.95,n)}generateExplanation(e,t,i,n,r){switch(i){case"causal":return`Analysis indicates a true causal relationship between '${e}' and '${t}'. Effect strength: ${(n*100).toFixed(1)}%. Changes in '${e}' are likely to cause changes in '${t}'.`;case"spurious":return`The correlation between '${e}' and '${t}' appears to be spurious. No true causal mechanism detected. This may be coincidental or due to a hidden common cause.`;case"reverse":return`Analysis suggests reverse causation: '${t}' may cause '${e}', not the other way around. Consider swapping the direction of your hypothesis.`;case"confounded":return`The relationship between '${e}' and '${t}' is confounded by: ${r.join(", ")}. These variables may explain the observed correlation without direct causation.`;case"none":return`No significant relationship detected between '${e}' and '${t}'. Effect strength is below the detection threshold.`;default:return`Analysis complete for '${e}' -> '${t}'.`}}clear(){this.ensureInitialized(),this.engine.clear(),this.currentCause="",this.currentEffect="",this.logger.debug("Cleared causal engine state")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.initialized=!1,this.logger.info("CausalAdapter disposed")}};function H(u){let e=new Map,t=[],i=()=>({objects:Array.from(e.entries()).map(([n,r])=>({name:n,schema:r})),morphisms:t.map(n=>({source:n.source,target:n.target,name:n.name}))});return{add_type(n,r){e.set(n,r)},add_morphism(n,r,a){t.push({source:n,target:r,name:a})},verify_composition(n){if(n.length<2)return!0;for(let a=0;a<n.length-1;a++){let o=n[a],d=n[a+1];if(!t.some(l=>l.source===o&&l.target===d))return!1}let r=i();return u.verifyCategoryLaws(r)},check_type_consistency(){let n=[];for(let r of t)e.has(r.source)||n.push({location:r.name,expected:"defined type",actual:`undefined type '${r.source}'`}),e.has(r.target)||n.push({location:r.name,expected:"defined type",actual:`undefined type '${r.target}'`});return n},clear(){e.clear(),t.length=0}}}var C=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;types=new Map;morphisms=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CategoryAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CategoryAdapter.");let t=await this.wasmLoader.load(),i=new t.CategoryEngine;this.engine=H(i),this.initialized=!0,this.logger.info("CategoryAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CategoryAdapter not initialized. Call initialize() first.")}addType(e,t){this.ensureInitialized(),this.types.set(e,t),this.engine.add_type(e,t),this.logger.debug("Added type to category",{name:e})}addMorphism(e,t,i){this.ensureInitialized(),this.morphisms.push({source:e,target:t,name:i}),this.engine.add_morphism(e,t,i),this.logger.debug("Added morphism to category",{source:e,target:t,name:i})}verifyComposition(e){if(this.ensureInitialized(),e.length<2)return!0;let t=this.engine.verify_composition(e);return this.logger.debug("Verified composition",{path:e,isValid:t}),t}checkTypeConsistency(){this.ensureInitialized();let t=this.engine.check_type_consistency().map(i=>this.transformMismatch(i));return this.logger.debug("Checked type consistency",{mismatchCount:t.length}),t}verifyPipeline(e){let t=Date.now();this.clear(),this.addType(e.inputType,this.inferSchema(e.inputType)),this.addType(e.outputType,this.inferSchema(e.outputType));for(let s of e.elements)this.addType(s.inputType,this.inferSchema(s.inputType)),this.addType(s.outputType,this.inferSchema(s.outputType));for(let s of e.elements)this.addMorphism(s.inputType,s.outputType,s.name);let i=this.buildCompositionPath(e),n=this.verifyComposition(i),r=this.checkTypeConsistency(),a=this.generateWarnings(e,n,r),o=Date.now()-t,d={isValid:n&&r.length===0,mismatches:r,warnings:a,durationMs:o,usedFallback:!1};return this.logger.info("Verified pipeline",{pipelineId:e.id,isValid:d.isValid,mismatchCount:r.length,warningCount:a.length,durationMs:o}),d}buildCompositionPath(e){let t=[e.inputType];for(let i of e.elements)i.inputType!==t[t.length-1]&&t.push(i.inputType),t.push(i.outputType);return t[t.length-1]!==e.outputType&&t.push(e.outputType),t}inferSchema(e){return e.endsWith("[]")?`{ items: ${e.slice(0,-2)}[] }`:e.includes("|")?`{ union: [${e.split("|").map(t=>`"${t.trim()}"`).join(", ")}] }`:`{ type: "${e}" }`}transformMismatch(e){return{location:e.location,expected:e.expected,actual:e.actual,severity:this.determineMismatchSeverity(e)}}determineMismatchSeverity(e){return e.expected==="never"||e.actual==="never"?"critical":e.actual==="any"||e.actual==="unknown"?"high":e.expected.includes(e.actual)||e.actual.includes(e.expected)?"medium":"low"}generateWarnings(e,t,i){let n=[];t||n.push(`Pipeline '${e.id}' has an invalid composition chain. Types do not connect properly from input to output.`);for(let a of e.elements)(a.inputType==="any"||a.outputType==="any")&&n.push(`Element '${a.name}' uses 'any' type, which bypasses type safety.`);for(let a of e.elements)(a.inputType.includes("<T>")||a.outputType.includes("<T>"))&&n.push(`Element '${a.name}' has unconstrained generic types.`);let r=i.filter(a=>a.severity==="critical");return r.length>0&&n.push(`Found ${r.length} critical type mismatch(es) that will cause runtime errors.`),n}clear(){this.ensureInitialized(),this.types.clear(),this.morphisms.length=0,this.engine.clear(),this.logger.debug("Cleared category")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.types.clear(),this.morphisms.length=0,this.initialized=!1,this.logger.info("CategoryAdapter disposed")}getTypeCount(){return this.types.size}getMorphismCount(){return this.morphisms.length}};function V(u){let e=new Map,t=new Map;return{add_proposition(i,n){e.set(i,{formula:n,proven:!1})},add_proof(i,n){let r=e.get(i);if(!r)return!1;let a={id:i,proof:n},o={formula:r.formula};return u.typeCheck(a,o)?.valid?(r.proven=!0,t.set(i,n),!0):!1},verify_path_equivalence(i,n){let r={steps:i},a={steps:n};return u.checkTypeEquivalence(r,a)},get_unproven_propositions(){let i=[];return e.forEach((n,r)=>{n.proven||i.push(r)}),i},clear(){e.clear(),t.clear()}}}var w=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;propositions=new Map;async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing HomotopyAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize HomotopyAdapter.");let t=await this.wasmLoader.load(),i=new t.HoTTEngine;this.engine=V(i),this.initialized=!0,this.logger.info("HomotopyAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("HomotopyAdapter not initialized. Call initialize() first.")}addProposition(e,t){this.ensureInitialized();let i={id:e,formula:t,proven:!1};this.propositions.set(e,i),this.engine.add_proposition(e,t),this.logger.debug("Added proposition",{id:e,formula:t})}addProof(e,t){this.ensureInitialized();let i=this.propositions.get(e);if(!i)return this.logger.warn("Proposition not found",{propositionId:e}),!1;let n=this.engine.add_proof(e,t);return n?(i.proven=!0,this.logger.info("Proposition proven",{propositionId:e})):this.logger.warn("Proof rejected",{propositionId:e}),n}verifyPathEquivalence(e,t){this.ensureInitialized();let i=this.engine.verify_path_equivalence(e,t),n=this.generateEquivalenceExplanation(e,t,i),r={equivalent:i,path1:e,path2:t,explanation:n};return this.logger.debug("Verified path equivalence",{path1Length:e.length,path2Length:t.length,equivalent:i}),r}generateEquivalenceExplanation(e,t,i){if(i)return e.length===t.length?"The execution paths are homotopically equivalent. Both paths traverse the same abstract structure and will produce equivalent results.":`The execution paths are equivalent despite different lengths. The ${e.length>t.length?"first":"second"} path contains redundant steps that can be contracted without changing the result (homotopy contraction).`;{let n=0,r=Math.min(e.length,t.length);for(;n<r&&e[n]===t[n];)n++;return n===0?`The execution paths diverge immediately. Path 1 starts with '${e[0]}' while Path 2 starts with '${t[0]}'. These lead to fundamentally different computation spaces.`:`The execution paths diverge at step ${n+1}. After '${e[n-1]}', Path 1 proceeds to '${e[n]}' while Path 2 proceeds to '${t[n]}'. No homotopy exists between these paths.`}}getUnprovenPropositions(){return this.ensureInitialized(),this.engine.get_unproven_propositions()}getVerificationStatus(){let e=this.propositions.size,t=Array.from(this.propositions.values()).filter(n=>n.proven).length,i=this.getUnprovenPropositions();return{totalPropositions:e,provenCount:t,unprovenIds:i,verificationPercentage:e>0?t/e*100:100}}getProposition(e){return this.propositions.get(e)}clear(){this.ensureInitialized(),this.propositions.clear(),this.engine.clear(),this.logger.debug("Cleared homotopy engine")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.propositions.clear(),this.initialized=!1,this.logger.info("HomotopyAdapter disposed")}getPropositionCount(){return this.propositions.size}};import{createHash as $}from"crypto";var E=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;witnesses=new Map;decisions=new Map;witnessCounter=0;async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing WitnessAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize WitnessAdapter.");let t=await this.wasmLoader.load();this.engine=this.createWitnessEngine(t),this.initialized=!0,this.logger.info("WitnessAdapter initialized successfully")}createWitnessEngine(e){return this.createFallbackEngine()}createFallbackEngine(){let e=[];return{create_witness:(t,i)=>{let r={hash:this.computeHash(t,i),previousHash:i,position:e.length,timestamp:Date.now()};return e.push(r),r},verify_witness:(t,i)=>{let n=e.find(a=>a.hash===i);return this.computeHash(t,n?.previousHash)===i},verify_chain:t=>{if(t.length===0)return!0;if(t[0].previousHash!==void 0)return!1;for(let i=1;i<t.length;i++)if(t[i].previousHash!==t[i-1].hash)return!1;return!0},get_chain_length:()=>e.length}}computeHash(e,t){let i=$("sha256");return i.update(e),t&&i.update(t,"utf-8"),i.digest("hex")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("WitnessAdapter not initialized. Call initialize() first.")}createWitness(e){this.ensureInitialized();let t=this.serializeDecision(e),i=this.getLastWitness(),n=i?.hash,r=this.engine.create_witness(t,n),a=`witness-${++this.witnessCounter}-${Date.now()}`,o={witnessId:a,decisionId:e.id,hash:r.hash,previousWitnessId:i?.witnessId,chainPosition:r.position,timestamp:new Date(r.timestamp)};return this.witnesses.set(a,o),this.decisions.set(e.id,e),this.logger.info("Created witness",{witnessId:a,decisionId:e.id,chainPosition:o.chainPosition}),o}verifyWitness(e,t){this.ensureInitialized();let i=this.serializeDecision(e),n=this.engine.verify_witness(i,t);return this.logger.debug("Verified witness",{decisionId:e.id,hash:t,isValid:n}),n}verifyChain(e){if(this.ensureInitialized(),e.length===0)return!0;let t=e.map(n=>({hash:n.hash,previousHash:n.previousWitnessId?this.witnesses.get(n.previousWitnessId)?.hash:void 0,position:n.chainPosition,timestamp:n.timestamp.getTime()})),i=this.engine.verify_chain(t);return this.logger.info("Verified witness chain",{chainLength:e.length,isValid:i}),i}replayFromWitness(e){let t=Date.now(),i=this.witnesses.get(e);if(!i)return{success:!1,decision:this.createEmptyDecision(),matchesOriginal:!1,differences:[`Witness not found: ${e}`],durationMs:Date.now()-t};let n=this.decisions.get(i.decisionId);if(!n)return{success:!1,decision:this.createEmptyDecision(),matchesOriginal:!1,differences:[`Decision not found: ${i.decisionId}`],durationMs:Date.now()-t};let r=this.verifyWitness(n,i.hash),a=Date.now()-t,o={success:!0,decision:n,matchesOriginal:r,differences:r?void 0:["Hash mismatch detected"],durationMs:a};return this.logger.info("Replayed from witness",{witnessId:e,decisionId:n.id,matchesOriginal:r,durationMs:a}),o}getChainLength(){return this.ensureInitialized(),this.engine.get_chain_length()}getWitnessChain(){return Array.from(this.witnesses.values()).sort((e,t)=>e.chainPosition-t.chainPosition)}getWitness(e){return this.witnesses.get(e)}getLastWitness(){let e=this.getWitnessChain();return e[e.length-1]}serializeDecision(e){let t=JSON.stringify({id:e.id,type:e.type,inputs:e.inputs,output:e.output,agents:e.agents,timestamp:e.timestamp.toISOString(),reasoning:e.reasoning});return new TextEncoder().encode(t)}createEmptyDecision(){return{id:"",type:"routing",inputs:{},output:null,agents:[],timestamp:new Date}}dispose(){this.witnesses.clear(),this.decisions.clear(),this.witnessCounter=0,this.engine=null,this.initialized=!1,this.logger.info("WitnessAdapter disposed")}};var I=class{constructor(e,t={},i){this.wasmLoader=e;this.config={...M,...t},this.logger=i||m}wasmLoader;config;logger;cohomologyAdapter=null;spectralAdapter=null;causalAdapter=null;categoryAdapter=null;homotopyAdapter=null;witnessAdapter=null;initialized=!1;stats={totalChecks:0,coherentCount:0,incoherentCount:0,averageEnergy:0,averageDurationMs:0,totalContradictions:0,laneDistribution:{reflex:0,retrieval:0,heavy:0,human:0},fallbackCount:0,wasmAvailable:!1};totalEnergySum=0;totalDurationSum=0;async initialize(){if(this.initialized)return;this.logger.info("Initializing CoherenceService");let e=await this.wasmLoader.isAvailable();if(!e&&!this.config.fallbackEnabled)throw new h("WASM module is not available and fallback is disabled. Enable fallbackEnabled in config to use TypeScript fallback.");if(this.stats.wasmAvailable=e,e)try{this.cohomologyAdapter=new y(this.wasmLoader,this.logger),this.spectralAdapter=new v(this.wasmLoader,this.logger),this.causalAdapter=new b(this.wasmLoader,this.logger),this.categoryAdapter=new C(this.wasmLoader,this.logger),this.homotopyAdapter=new w(this.wasmLoader,this.logger),this.witnessAdapter=new E(this.wasmLoader,this.logger),await Promise.all([this.cohomologyAdapter.initialize(),this.spectralAdapter.initialize(),this.causalAdapter.initialize(),this.categoryAdapter.initialize(),this.homotopyAdapter.initialize(),this.witnessAdapter.initialize()]),this.logger.info("All coherence engine adapters initialized")}catch(t){if(!this.config.fallbackEnabled)throw t;this.logger.warn("WASM initialization failed, using fallback",{error:t instanceof Error?t.message:"Unknown error"}),this.stats.wasmAvailable=!1}else this.logger.info("WASM not available, using TypeScript fallback");this.initialized=!0,this.logger.info("CoherenceService initialized",{wasmAvailable:this.stats.wasmAvailable,fallbackEnabled:this.config.fallbackEnabled})}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized)throw new f("CoherenceService not initialized. Call initialize() first.","NOT_INITIALIZED")}async checkCoherence(e){this.ensureInitialized();let t=Date.now();try{return this.cohomologyAdapter?.isInitialized()?await this.checkCoherenceWithWasm(e,t):this.checkCoherenceWithFallback(e,t)}catch(i){return this.logger.error("Coherence check failed",A(i)),{energy:1,isCoherent:!1,lane:"human",contradictions:[],recommendations:["Coherence check failed. Manual review recommended."],durationMs:Date.now()-t,usedFallback:!0}}}async checkCoherenceWithWasm(e,t){this.cohomologyAdapter.clear();for(let o of e)this.cohomologyAdapter.addNode(o);this.buildEdgesFromNodes(e);let i=this.cohomologyAdapter.computeEnergy(),n=this.cohomologyAdapter.detectContradictions(this.config.coherenceThreshold),r=this.computeLane(i),a=Date.now()-t;return this.updateStats(i,a,n.length,r,!1),{energy:i,isCoherent:i<this.config.coherenceThreshold,lane:r,contradictions:n,recommendations:this.generateRecommendations(i,r,n),durationMs:a,usedFallback:!1}}checkCoherenceWithFallback(e,t){this.stats.fallbackCount++;let i=0,n=0,r=[];for(let s=0;s<e.length;s++)for(let l=s+1;l<e.length;l++){let c=this.euclideanDistance(e[s].embedding,e[l].embedding);i+=c,n++,c>1.5&&r.push({nodeIds:[e[s].id,e[l].id],severity:c>2?"critical":"high",description:`High distance (${c.toFixed(2)}) between nodes`,confidence:Math.min(1,c/2)})}let a=n>0?i/n:0,o=this.computeLane(a),d=Date.now()-t;return this.updateStats(a,d,r.length,o,!0),{energy:a,isCoherent:a<this.config.coherenceThreshold,lane:o,contradictions:r,recommendations:this.generateRecommendations(a,o,r),durationMs:d,usedFallback:!0}}buildEdgesFromNodes(e){for(let t=0;t<e.length;t++)for(let i=t+1;i<e.length;i++){let n=this.cosineSimilarity(e[t].embedding,e[i].embedding);n>.3&&this.cohomologyAdapter.addEdge({source:e[t].id,target:e[i].id,weight:n})}}async detectContradictions(e){this.ensureInitialized();let t=e.map(n=>({id:n.id,embedding:n.embedding,weight:n.confidence,metadata:{statement:n.statement,source:n.source}}));return(await this.checkCoherence(t)).contradictions}async predictCollapse(e){if(this.ensureInitialized(),!e.agents||e.agents.length===0)return{risk:0,fiedlerValue:0,collapseImminent:!1,weakVertices:[],recommendations:["No agents to analyze"],durationMs:0,usedFallback:!0};if(this.spectralAdapter?.isInitialized())try{return this.spectralAdapter.analyzeSwarmState(e)}catch(t){return this.logger.warn("Spectral collapse prediction failed, using fallback",{error:p(t),agentCount:e.agents.length}),this.predictCollapseWithFallback(e)}return this.predictCollapseWithFallback(e)}predictCollapseWithFallback(e){let t=Date.now(),i=e.agents.reduce((o,d)=>o+d.health,0)/Math.max(e.agents.length,1),n=e.agents.reduce((o,d)=>o+d.successRate,0)/Math.max(e.agents.length,1),r=0;r+=(1-i)*.3,r+=(1-n)*.3,r+=e.errorRate*.2,r+=e.utilization>.9?.2:e.utilization*.1;let a=e.agents.filter(o=>o.health<.5||o.successRate<.5).map(o=>o.agentId);return{risk:Math.min(1,r),fiedlerValue:i*n,collapseImminent:r>.7,weakVertices:a,recommendations:r>.5?["System health degraded. Consider spawning additional agents."]:["System health is acceptable."],durationMs:Date.now()-t,usedFallback:!0}}async verifyCausality(e,t,i){return this.ensureInitialized(),this.causalAdapter?.isInitialized()?this.causalAdapter.verifyCausality(e,t,i):this.verifyCausalityWithFallback(e,t,i)}verifyCausalityWithFallback(e,t,i){let n=Date.now(),r=this.computeCorrelation(i.causeValues,i.effectValues),a=Math.abs(r);return{isCausal:a>.5,effectStrength:a,relationshipType:a<.2?"none":a>.5?"causal":"spurious",confidence:Math.min(.7,i.sampleSize/100),confounders:[],explanation:`Correlation-based analysis: r=${r.toFixed(3)}. Note: Correlation does not imply causation. This is a fallback analysis without full causal inference.`,durationMs:Date.now()-n,usedFallback:!0}}async verifyTypes(e){return this.ensureInitialized(),this.categoryAdapter?.isInitialized()?this.categoryAdapter.verifyPipeline(e):this.verifyTypesWithFallback(e)}verifyTypesWithFallback(e){let t=Date.now(),i=[],n=e.inputType;for(let r of e.elements)r.inputType!==n&&n!=="any"&&i.push({location:r.name,expected:n,actual:r.inputType,severity:"high"}),n=r.outputType;return n!==e.outputType&&n!=="any"&&i.push({location:"pipeline output",expected:e.outputType,actual:n,severity:"critical"}),{isValid:i.length===0,mismatches:i,warnings:["Using fallback type verification. Full categorical analysis unavailable."],durationMs:Date.now()-t,usedFallback:!0}}async createWitness(e){return this.ensureInitialized(),this.witnessAdapter?.isInitialized()?this.witnessAdapter.createWitness(e):{witnessId:`witness-fallback-${Date.now()}`,decisionId:e.id,hash:this.simpleHash(JSON.stringify(e)),chainPosition:0,timestamp:new Date}}async replayFromWitness(e){return this.ensureInitialized(),this.witnessAdapter?.isInitialized()?this.witnessAdapter.replayFromWitness(e):{success:!1,decision:{id:"",type:"routing",inputs:{},output:null,agents:[],timestamp:new Date},matchesOriginal:!1,differences:["Replay not available in fallback mode"],durationMs:0}}async checkSwarmCoherence(e){this.ensureInitialized();let t=[];return e.forEach((i,n)=>{let r=this.agentHealthToEmbedding(i);t.push({id:n,embedding:r,weight:i.health,metadata:{agentType:i.agentType,successRate:i.successRate,errorCount:i.errorCount}})}),this.checkCoherence(t)}async verifyConsensus(e){this.ensureInitialized();let t=Date.now();if(e.length<2)return{isValid:e.length===1,confidence:e.length===1?e[0].confidence:0,isFalseConsensus:!1,fiedlerValue:e.length===1?1:0,collapseRisk:0,recommendation:e.length===0?"No votes to analyze":"Single vote - consensus trivially achieved",durationMs:Date.now()-t,usedFallback:!0};if(this.spectralAdapter?.isInitialized())try{this.spectralAdapter.clear();for(let a of e)this.spectralAdapter.addNode(a.agentId);let i=0;for(let a=0;a<e.length;a++)for(let o=a+1;o<e.length;o++)e[a].verdict===e[o].verdict&&(this.spectralAdapter.addEdge(e[a].agentId,e[o].agentId,Math.min(e[a].confidence,e[o].confidence)),i++);if(i===0)return this.logger.debug("No agreement edges, using fallback consensus"),this.verifyConsensusWithFallback(e,t);let n=this.spectralAdapter.predictCollapseRisk(),r=this.spectralAdapter.computeFiedlerValue();return{isValid:n<.3&&r>.1,confidence:1-n,isFalseConsensus:r<.05,fiedlerValue:r,collapseRisk:n,recommendation:n>.3?"Spawn independent reviewer":"Consensus verified",durationMs:Date.now()-t,usedFallback:!1}}catch(i){return this.logger.warn("Spectral consensus verification failed, using fallback",{error:p(i),voteCount:e.length}),this.verifyConsensusWithFallback(e,t)}return this.verifyConsensusWithFallback(e,t)}verifyConsensusWithFallback(e,t){let i=new Map;for(let o of e){let d=String(o.verdict);i.set(d,(i.get(d)||0)+1)}let n=0;i.forEach(o=>{n=Math.max(n,o)});let r=n/e.length,a=e.reduce((o,d)=>o+d.confidence,0)/e.length;return{isValid:r>.6,confidence:r*a,isFalseConsensus:i.size===1&&e.length>2,fiedlerValue:r,collapseRisk:1-r,recommendation:r<.6?"No clear majority. Consider spawning additional agents.":r===1&&i.size===1?"Unanimous consensus may indicate false consensus. Consider adding diversity.":"Majority consensus achieved.",durationMs:Date.now()-t,usedFallback:!0}}async filterCoherent(e,t){if(this.ensureInitialized(),e.length===0)return[];if(e.length===1)return e;let i=e.map(a=>({id:a.id,embedding:a.embedding})),n=await this.checkCoherence(i);if(n.isCoherent)return e;let r=new Set;for(let a of n.contradictions)a.nodeIds.forEach(o=>r.add(o));return e.filter(a=>!r.has(a.id))}getStats(){return{...this.stats,averageEnergy:this.stats.totalChecks>0?this.totalEnergySum/this.stats.totalChecks:0,averageDurationMs:this.stats.totalChecks>0?this.totalDurationSum/this.stats.totalChecks:0,lastCheckAt:this.stats.lastCheckAt}}async dispose(){this.cohomologyAdapter?.dispose(),this.spectralAdapter?.dispose(),this.causalAdapter?.dispose(),this.categoryAdapter?.dispose(),this.homotopyAdapter?.dispose(),this.witnessAdapter?.dispose(),this.cohomologyAdapter=null,this.spectralAdapter=null,this.causalAdapter=null,this.categoryAdapter=null,this.homotopyAdapter=null,this.witnessAdapter=null,this.initialized=!1,this.logger.info("CoherenceService disposed")}computeLane(e){let{laneConfig:t}=this.config;return e<t.reflexThreshold?"reflex":e<t.retrievalThreshold?"retrieval":e<t.heavyThreshold?"heavy":"human"}updateStats(e,t,i,n,r){this.stats.totalChecks++,this.totalEnergySum+=e,this.totalDurationSum+=t,this.stats.totalContradictions+=i,this.stats.laneDistribution[n]++,this.stats.lastCheckAt=new Date,e<this.config.coherenceThreshold?this.stats.coherentCount++:this.stats.incoherentCount++,r&&this.stats.fallbackCount++}generateRecommendations(e,t,i){let n=[];if(t==="reflex"?n.push("Low energy detected. Safe to proceed with immediate execution."):t==="retrieval"?n.push("Moderate energy detected. Consider fetching additional context before proceeding."):t==="heavy"?n.push("High energy detected. Deep analysis recommended before proceeding."):n.push("Critical energy level. Escalate to human review (Queen agent)."),i.length>0){let r=i.filter(a=>a.severity==="critical");r.length>0&&n.push(`Found ${r.length} critical contradiction(s) that must be resolved.`)}return n}agentHealthToEmbedding(e){let t=e.beliefs??[];return[e.health,e.successRate,Math.min(1,e.errorCount/10),this.agentTypeToNumber(e.agentType),t.length/10,...t[0]?.embedding.slice(0,5)||[0,0,0,0,0],...t[1]?.embedding.slice(0,5)||[0,0,0,0,0],...t[2]?.embedding.slice(0,5)||[0,0,0,0,0]]}agentTypeToNumber(e){let t=["coordinator","specialist","analyzer","generator","validator","tester","reviewer","optimizer"],i=t.indexOf(e);return i>=0?i/t.length:.5}euclideanDistance(e,t){if(e.length!==t.length)return 1/0;let i=0;for(let n=0;n<e.length;n++)i+=(e[n]-t[n])**2;return Math.sqrt(i)}cosineSimilarity(e,t){if(e.length!==t.length||e.length===0)return 0;let i=0,n=0,r=0;for(let o=0;o<e.length;o++)i+=e[o]*t[o],n+=e[o]*e[o],r+=t[o]*t[o];let a=Math.sqrt(n)*Math.sqrt(r);return a===0?0:i/a}computeCorrelation(e,t){if(e.length!==t.length||e.length<2)return 0;let i=e.length,n=e.reduce((l,c)=>l+c,0)/i,r=t.reduce((l,c)=>l+c,0)/i,a=0,o=0,d=0;for(let l=0;l<i;l++){let c=e[l]-n,g=t[l]-r;a+=c*g,o+=c*c,d+=g*g}let s=Math.sqrt(o*d);return s===0?0:a/s}simpleHash(e){let t=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);t=(t<<5)-t+n,t=t&t}return(t>>>0).toString(16).padStart(8,"0")}};async function Q(u,e,t){let i=new I(u,e,t);return await i.initialize(),i}L();import{createRequire as _}from"node:module";import{fileURLToPath as K}from"node:url";import{dirname as x,join as S}from"node:path";import{readFileSync as X,existsSync as P}from"node:fs";var W=[1e3,2e3,4e3],k=class{state="unloaded";wasmModule=null;engines=null;loadPromise=null;lastError=null;config;version="";fallbackState={mode:"wasm",consecutiveFailures:0,totalActivations:0,nextRetryAt:void 0,lastSuccessfulLoad:void 0};retryTimer=null;degradedModeStartTime=null;eventListeners;constructor(e={}){this.config={...z,...e},this.eventListeners=new Map,this.eventListeners.set("loaded",new Set),this.eventListeners.set("error",new Set),this.eventListeners.set("retry",new Set),this.eventListeners.set("degraded_mode",new Set),this.eventListeners.set("recovered",new Set)}isLoaded(){return this.state==="loaded"&&this.engines!==null}getState(){return this.state}getVersion(){return this.version}getLastError(){return this.lastError}isInDegradedMode(){return this.state==="degraded"||this.fallbackState.mode==="fallback"}getFallbackState(){return{...this.fallbackState}}getFallbackResult(){return{usedFallback:!0,confidence:.5,retryCount:this.fallbackState.consecutiveFailures,lastError:this.lastError?.message,activatedAt:this.degradedModeStartTime??new Date}}async getEngines(){if(this.state==="loaded"&&this.engines)return this.engines;if(this.state==="loading"&&this.loadPromise)return this.loadPromise;this.state="loading",this.loadPromise=this.loadWithRetry();try{return this.engines=await this.loadPromise,this.state="loaded",(this.fallbackState.mode==="fallback"||this.fallbackState.mode==="recovering")&&this.emitRecoveryEvent(),this.fallbackState.mode="wasm",this.fallbackState.consecutiveFailures=0,this.fallbackState.lastSuccessfulLoad=new Date,this.engines}catch(e){throw this.state="failed",this.lastError=A(e),this.enterDegradedMode(this.lastError),e}finally{this.loadPromise=null}}async getEnginesWithFallback(){if(this.state==="loaded"&&this.engines)return{engines:this.engines,fallback:{usedFallback:!1,confidence:1,retryCount:0}};if(this.state==="degraded")return{engines:null,fallback:this.getFallbackResult()};try{return{engines:await this.getEngines(),fallback:{usedFallback:!1,confidence:1,retryCount:0}}}catch{return{engines:null,fallback:this.getFallbackResult()}}}getEnginesSync(){if(!this.engines)throw new h("WASM module is not loaded. Call getEngines() first.");return this.engines}async isAvailable(){if(this.state==="loaded"&&this.wasmModule)return!0;if(this.state==="failed")return!1;try{let e=_(import.meta.url),t=[(()=>{try{let i=e.resolve("prime-radiant-advanced-wasm");return S(x(i),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),S(process.cwd(),"node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm")].filter(i=>i!==null);for(let i of t)if(P(i))return!0;return!1}catch{return!1}}async load(){if(await this.getEngines(),!this.wasmModule)throw new h("WASM module failed to load");return this.wasmModule}getModule(){if(!this.wasmModule)throw new h("WASM module is not loaded. Call load() first.");return this.wasmModule}on(e,t){let i=this.eventListeners.get(e);return i&&i.add(t),()=>{i?.delete(t)}}off(e,t){let i=this.eventListeners.get(e);i&&i.delete(t)}reset(){if(this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.engines)try{this.engines.cohomology.free(),this.engines.spectral.free(),this.engines.causal.free(),this.engines.category.free(),this.engines.hott.free(),this.engines.quantum.free()}catch(e){console.debug("[WASMLoader] Cleanup error during unload:",e instanceof Error?e.message:e)}this.state="unloaded",this.wasmModule=null,this.engines=null,this.loadPromise=null,this.lastError=null,this.version="",this.fallbackState={mode:"wasm",consecutiveFailures:0,totalActivations:0,nextRetryAt:void 0,lastSuccessfulLoad:void 0},this.degradedModeStartTime=null}async forceRetry(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),(this.state==="failed"||this.state==="degraded")&&(this.state="unloaded",this.fallbackState.mode="recovering");try{return await this.getEngines(),!0}catch{return!1}}async loadWithRetry(){let{maxAttempts:e,baseDelayMs:t,maxDelayMs:i}=this.config,n=new Error("Unknown error");for(let r=1;r<=e;r++)try{let a=performance.now(),o=await this.attemptLoad(),d=performance.now()-a;return this.emit("loaded",{version:this.version,loadTimeMs:Math.round(d*100)/100}),o}catch(a){if(n=A(a),this.emit("error",{error:n,fatal:r>=e,attempt:r}),r<e){let o=Math.min(t*Math.pow(2,r-1),i);this.emit("retry",{attempt:r+1,maxAttempts:e,delayMs:o,previousError:n}),await this.sleep(o)}}throw new T(`Failed to load WASM module after ${e} attempts: ${n.message}`,e,n)}async attemptLoad(){let e;try{e=_(import.meta.url)}catch{e=globalThis.require||(await import("module")).createRequire(__filename)}let t;try{t=await import("./prime-radiant-advanced-wasm-P2JB73XX.js")}catch(r){try{t=e("prime-radiant-advanced-wasm")}catch{throw new Error(`Failed to import prime-radiant-advanced-wasm: ${p(r)}`)}}if(typeof process<"u"&&process.versions!=null&&process.versions.node!=null?await this.initializeForNodeJs(t,e):t.default&&typeof t.default=="function"&&await t.default(),t.initModule&&typeof t.initModule=="function")try{t.initModule()}catch{}return t.getVersion&&typeof t.getVersion=="function"&&(this.version=t.getVersion()),this.wasmModule=t,{cohomology:new t.CohomologyEngine,spectral:new t.SpectralEngine,causal:new t.CausalEngine,category:new t.CategoryEngine,hott:new t.HoTTEngine,quantum:new t.QuantumEngine}}async initializeForNodeJs(e,t){let i=[(()=>{try{let a=t.resolve("prime-radiant-advanced-wasm");return S(x(a),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),S(x(K(import.meta.url)),"../../../../node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm"),S(process.cwd(),"node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm")].filter(a=>a!==null),n=null;for(let a of i)if(P(a)){n=a;break}if(!n)throw new Error(`Could not find WASM binary. Searched paths:
3
3
  ${i.join(`
4
4
  `)}
5
5
  Ensure prime-radiant-advanced-wasm is installed.`);let r=X(n);if(e.initSync&&typeof e.initSync=="function")e.initSync({module:r});else throw new Error("WASM module does not export initSync function")}emit(e,t){let i=this.eventListeners.get(e);if(i){let n=Array.from(i);for(let r=0;r<n.length;r++)try{n[r](t)}catch{}}}sleep(e){return new Promise(t=>setTimeout(t,e))}enterDegradedMode(e){this.state="degraded",this.fallbackState.mode="fallback",this.fallbackState.consecutiveFailures++,this.fallbackState.totalActivations++,this.degradedModeStartTime||(this.degradedModeStartTime=new Date);let t=Math.min(this.fallbackState.consecutiveFailures-1,W.length-1),i=W[t],n=new Date(Date.now()+i);this.fallbackState.nextRetryAt=n,console.warn(`[WasmLoader] WASM load failed, entering degraded mode. Retry ${this.fallbackState.consecutiveFailures}/3 in ${i}ms. Error: ${e.message}`),this.emit("degraded_mode",{reason:"WASM load failed after retries",retryCount:this.fallbackState.consecutiveFailures,lastError:e.message,activatedAt:this.degradedModeStartTime,nextRetryAt:n}),this.fallbackState.consecutiveFailures<W.length&&this.scheduleBackgroundRetry(i)}scheduleBackgroundRetry(e){this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.fallbackState.mode="recovering",this.attemptBackgroundRecovery()},e)}async attemptBackgroundRecovery(){this.state="unloaded",this.loadPromise=null;try{await this.getEngines()}catch{}}emitRecoveryEvent(){if(!this.degradedModeStartTime)return;let e=Date.now()-this.degradedModeStartTime.getTime();console.info(`[WasmLoader] WASM recovered after ${e}ms in degraded mode. Retry count: ${this.fallbackState.consecutiveFailures}`),this.emit("recovered",{degradedDurationMs:e,retryCount:this.fallbackState.consecutiveFailures,version:this.version}),this.degradedModeStartTime=null}},J=new k;var Z={emaAlpha:.1,minSamplesForCalibration:10,maxHistorySize:1e3,targetFalsePositiveRate:.05,targetFalseNegativeRate:.02,maxAdjustmentPerCycle:.05,autoCalibrate:!1,autoCalibrateInterval:100,defaultThresholds:{...R}};export{Q as a,J as b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.12.0");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.12.2");process.exit(0)}
2
2
  var N="ffffffff-ffff-ffff-ffff-ffffffffffff";var _="00000000-0000-0000-0000-000000000000";var y=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function k(r){return typeof r=="string"&&y.test(r)}var u=k;function q(r){if(!u(r))throw TypeError("Invalid UUID");let n;return Uint8Array.of((n=parseInt(r.slice(0,8),16))>>>24,n>>>16&255,n>>>8&255,n&255,(n=parseInt(r.slice(9,13),16))>>>8,n&255,(n=parseInt(r.slice(14,18),16))>>>8,n&255,(n=parseInt(r.slice(19,23),16))>>>8,n&255,(n=parseInt(r.slice(24,36),16))/1099511627776&255,n/4294967296&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255)}var c=q;var x=[];for(let r=0;r<256;++r)x.push((r+256).toString(16).slice(1));function l(r,n=0){return(x[r[n+0]]+x[r[n+1]]+x[r[n+2]]+x[r[n+3]]+"-"+x[r[n+4]]+x[r[n+5]]+"-"+x[r[n+6]]+x[r[n+7]]+"-"+x[r[n+8]]+x[r[n+9]]+"-"+x[r[n+10]]+x[r[n+11]]+x[r[n+12]]+x[r[n+13]]+x[r[n+14]]+x[r[n+15]]).toLowerCase()}function C(r,n=0){let f=l(r,n);if(!u(f))throw TypeError("Stringified UUID is invalid");return f}var H=C;var v=new Uint8Array(16);function m(){return crypto.getRandomValues(v)}var g={};function X(r,n,f){let e,o=r?._v6??!1;if(r){let t=Object.keys(r);t.length===1&&t[0]==="_v6"&&(r=void 0)}if(r)e=E(r.random??r.rng?.()??m(),r.msecs,r.nsecs,r.clockseq,r.node,n,f);else{let t=Date.now(),i=m();j(g,t,i),e=E(i,g.msecs,g.nsecs,o?void 0:g.clockseq,o?void 0:g.node,n,f)}return n??l(e)}function j(r,n,f){return r.msecs??=-1/0,r.nsecs??=0,n===r.msecs?(r.nsecs++,r.nsecs>=1e4&&(r.node=void 0,r.nsecs=0)):n>r.msecs?r.nsecs=0:n<r.msecs&&(r.node=void 0),r.node||(r.node=f.slice(10,16),r.node[0]|=1,r.clockseq=(f[8]<<8|f[9])&16383),r.msecs=n,r}function E(r,n,f,e,o,t,i=0){if(r.length<16)throw new Error("Random bytes length must be >= 16");if(!t)t=new Uint8Array(16),i=0;else if(i<0||i+16>t.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);n??=Date.now(),f??=0,e??=(r[8]<<8|r[9])&16383,o??=r.slice(10,16),n+=122192928e5;let d=((n&268435455)*1e4+f)%4294967296;t[i++]=d>>>24&255,t[i++]=d>>>16&255,t[i++]=d>>>8&255,t[i++]=d&255;let a=n/4294967296*1e4&268435455;t[i++]=a>>>8&255,t[i++]=a&255,t[i++]=a>>>24&15|16,t[i++]=a>>>16&255,t[i++]=e>>>8|128,t[i++]=e&255;for(let p=0;p<6;++p)t[i++]=o[p];return t}var D=X;function U(r){let n=typeof r=="string"?c(r):r,f=G(n);return typeof r=="string"?l(f):f}function G(r){return Uint8Array.of((r[6]&15)<<4|r[7]>>4&15,(r[7]&15)<<4|(r[4]&240)>>4,(r[4]&15)<<4|(r[5]&240)>>4,(r[5]&15)<<4|(r[0]&240)>>4,(r[0]&15)<<4|(r[1]&240)>>4,(r[1]&15)<<4|(r[2]&240)>>4,96|r[2]&15,r[3],r[8],r[9],r[10],r[11],r[12],r[13],r[14],r[15])}import{createHash as K}from"node:crypto";function M(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),K("md5").update(r).digest()}var T=M;function O(r){r=unescape(encodeURIComponent(r));let n=new Uint8Array(r.length);for(let f=0;f<r.length;++f)n[f]=r.charCodeAt(f);return n}var w="6ba7b810-9dad-11d1-80b4-00c04fd430c8",I="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function h(r,n,f,e,o,t){let i=typeof f=="string"?O(f):f,d=typeof e=="string"?c(e):e;if(typeof e=="string"&&(e=c(e)),e?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+i.length);if(a.set(d),a.set(i,d.length),a=n(a),a[6]=a[6]&15|r,a[8]=a[8]&63|128,o){if(t??=0,t<0||t+16>o.length)throw new RangeError(`UUID byte range ${t}:${t+15} is out of buffer bounds`);for(let p=0;p<16;++p)o[t+p]=a[p];return o}return l(a)}function S(r,n,f,e){return h(48,T,r,n,f,e)}S.DNS=w;S.URL=I;var z=S;function F(r,n,f){return!n&&!r&&crypto.randomUUID?crypto.randomUUID():J(r,n,f)}function J(r,n,f){r=r||{};let e=r.random??r.rng?.()??m();if(e.length<16)throw new Error("Random bytes length must be >= 16");if(e[6]=e[6]&15|64,e[8]=e[8]&63|128,n){if(f=f||0,f<0||f+16>n.length)throw new RangeError(`UUID byte range ${f}:${f+15} is out of buffer bounds`);for(let o=0;o<16;++o)n[f+o]=e[o];return n}return l(e)}var P=F;import{createHash as Q}from"node:crypto";function W(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),Q("sha1").update(r).digest()}var V=W;function R(r,n,f,e){return h(80,V,r,n,f,e)}R.DNS=w;R.URL=I;var Y=R;function Z(r,n,f){r??={},f??=0;let e=D({...r,_v6:!0},new Uint8Array(16));if(e=U(e),n){if(f<0||f+16>n.length)throw new RangeError(`UUID byte range ${f}:${f+15} is out of buffer bounds`);for(let o=0;o<16;o++)n[f+o]=e[o];return n}return l(e)}var s=Z;function $(r){let n=typeof r=="string"?c(r):r,f=b(n);return typeof r=="string"?l(f):f}function b(r){return Uint8Array.of((r[3]&15)<<4|r[4]>>4&15,(r[4]&15)<<4|(r[5]&240)>>4,(r[5]&15)<<4|r[6]&15,r[7],(r[1]&15)<<4|(r[2]&240)>>4,(r[2]&15)<<4|(r[3]&240)>>4,16|(r[0]&240)>>4,(r[0]&15)<<4|(r[1]&240)>>4,r[8],r[9],r[10],r[11],r[12],r[13],r[14],r[15])}var A={};function B(r,n,f){let e;if(r)e=L(r.random??r.rng?.()??m(),r.msecs,r.seq,n,f);else{let o=Date.now(),t=m();r0(A,o,t),e=L(t,A.msecs,A.seq,n,f)}return n??l(e)}function r0(r,n,f){return r.msecs??=-1/0,r.seq??=0,n>r.msecs?(r.seq=f[6]<<23|f[7]<<16|f[8]<<8|f[9],r.msecs=n):(r.seq=r.seq+1|0,r.seq===0&&r.msecs++),r}function L(r,n,f,e,o=0){if(r.length<16)throw new Error("Random bytes length must be >= 16");if(!e)e=new Uint8Array(16),o=0;else if(o<0||o+16>e.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);return n??=Date.now(),f??=r[6]*127<<24|r[7]<<16|r[8]<<8|r[9],e[o++]=n/1099511627776&255,e[o++]=n/4294967296&255,e[o++]=n/16777216&255,e[o++]=n/65536&255,e[o++]=n/256&255,e[o++]=n&255,e[o++]=112|f>>>28&15,e[o++]=f>>>20&255,e[o++]=128|f>>>14&63,e[o++]=f>>>6&255,e[o++]=f<<2&255|r[10]&3,e[o++]=r[11],e[o++]=r[12],e[o++]=r[13],e[o++]=r[14],e[o++]=r[15],e}var n0=B;function f0(r){if(!u(r))throw TypeError("Invalid UUID");return parseInt(r.slice(14,15),16)}var e0=f0;export{N as a,_ as b,u as c,c as d,H as e,D as f,U as g,z as h,P as i,Y as j,s as k,$ as l,n0 as m,e0 as n};