agentic-qe 3.11.5 → 3.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (374) hide show
  1. package/.claude/helpers/.helpers-version +1 -0
  2. package/.claude/helpers/auto-memory-hook.mjs +35 -3
  3. package/.claude/helpers/brain-checkpoint.cjs +16 -1
  4. package/.claude/helpers/helpers.manifest.json +12 -0
  5. package/.claude/helpers/hook-handler.cjs +26 -5
  6. package/.claude/helpers/intelligence.cjs +14 -1
  7. package/.claude/hooks/aqe-hook.cjs +14 -1
  8. package/.claude/skills/skills-manifest.json +1 -1
  9. package/CHANGELOG.md +87 -0
  10. package/assets/skills/skills-manifest.json +1 -1
  11. package/dist/adapters/a2a/auth/routes.js +59 -28
  12. package/dist/cli/bundle.js +6 -6
  13. package/dist/cli/chunks/adapter-X4UEC6UJ.js +2 -0
  14. package/dist/cli/chunks/{agent-booster-wasm-CSTBLNYZ.js → agent-booster-wasm-P4VYM5KK.js} +2 -2
  15. package/dist/cli/chunks/{agent-handler-M4W4GTXN.js → agent-handler-PBQ7L2TO.js} +2 -2
  16. package/dist/cli/chunks/{agent-memory-branch-VGXFYLSQ.js → agent-memory-branch-UPWO3X6V.js} +2 -2
  17. package/dist/cli/chunks/aqe-learning-engine-5FG7JCY7.js +2 -0
  18. package/dist/cli/chunks/{arena-IQBRGWAG.js → arena-LEUTILZ7.js} +2 -2
  19. package/dist/cli/chunks/{arena-FKSD3LLM.js → arena-QYTP3FG6.js} +4 -4
  20. package/dist/cli/chunks/{audit-7NSGRR4Z.js → audit-TB6M2YLK.js} +3 -3
  21. package/dist/cli/chunks/base-CWPMFSZG.js +2 -0
  22. package/dist/cli/chunks/{hnswlib-node-E6NSZPP2.js → better-sqlite3-IPKCAVLS.js} +2 -2
  23. package/dist/cli/chunks/{brain-handler-M6A3UB66.js → brain-handler-JF3OK35F.js} +3 -3
  24. package/dist/cli/chunks/{branch-enumerator-2JGKY4BB.js → branch-enumerator-WEIP3DXB.js} +2 -2
  25. package/dist/cli/chunks/{browser-J43WQPJL.js → browser-HY6VLXHZ.js} +2 -2
  26. package/dist/cli/chunks/browser-workflow-A77OFBVY.js +2 -0
  27. package/dist/cli/chunks/{chunk-7BCRULCP.js → chunk-2PQ7YADF.js} +2 -2
  28. package/dist/cli/chunks/{chunk-XKQY2Z3Q.js → chunk-3I3Z4C5X.js} +1 -1
  29. package/dist/cli/chunks/{chunk-MCHEUSY4.js → chunk-3W2FZXFD.js} +1 -1
  30. package/dist/cli/chunks/{chunk-WMZ2QGGS.js → chunk-42GFB7VX.js} +2 -2
  31. package/dist/cli/chunks/{chunk-UBI2EOS3.js → chunk-42PYEEYQ.js} +1 -1
  32. package/dist/cli/chunks/{chunk-HJWT4KME.js → chunk-45QNHMTP.js} +1 -1
  33. package/dist/cli/chunks/{chunk-AGJOGUP5.js → chunk-4KI72C2E.js} +1 -1
  34. package/dist/cli/chunks/{chunk-5WMU7XCF.js → chunk-4LKQZW2H.js} +1 -1
  35. package/dist/cli/chunks/{chunk-SUL3I6QZ.js → chunk-4U5MJX2H.js} +2 -2
  36. package/dist/cli/chunks/{chunk-DFRRWOEX.js → chunk-55MQ2SFP.js} +2 -2
  37. package/dist/cli/chunks/{chunk-KP3R2M2G.js → chunk-5H5A74U2.js} +1 -1
  38. package/dist/cli/chunks/{chunk-YBPLJRVT.js → chunk-5HMGDB7B.js} +2 -2
  39. package/dist/cli/chunks/{chunk-YZSTZUGJ.js → chunk-6432JORM.js} +1 -1
  40. package/dist/cli/chunks/{chunk-CDJP6COA.js → chunk-6BCVKCG5.js} +2 -2
  41. package/dist/cli/chunks/{chunk-TBT3OFRW.js → chunk-6ONUCDVL.js} +2 -2
  42. package/dist/cli/chunks/{chunk-3LY7OCSO.js → chunk-6RX5QZMU.js} +1 -1
  43. package/dist/cli/chunks/chunk-74VIADSJ.js +2 -0
  44. package/dist/cli/chunks/{chunk-K4I7UIU5.js → chunk-75AVUS5U.js} +1 -1
  45. package/dist/cli/chunks/{chunk-KVVJVMDM.js → chunk-774X6OJY.js} +2 -2
  46. package/dist/cli/chunks/chunk-7KHIOWBN.js +2 -0
  47. package/dist/cli/chunks/{chunk-62OTU2AP.js → chunk-7KK6XSYK.js} +2 -2
  48. package/dist/cli/chunks/{chunk-RFLHPLET.js → chunk-7N2SCRWJ.js} +1 -1
  49. package/dist/cli/chunks/{chunk-OS2HHJTM.js → chunk-AGWKCY42.js} +2 -2
  50. package/dist/cli/chunks/chunk-BAHXVVX3.js +4 -0
  51. package/dist/cli/chunks/{chunk-6T65OKUM.js → chunk-BALFQQB7.js} +2 -2
  52. package/dist/cli/chunks/{chunk-I3ANRYQ6.js → chunk-BBNQDHGF.js} +2 -2
  53. package/dist/cli/chunks/{chunk-LOE2JETO.js → chunk-BCBITOMT.js} +2 -2
  54. package/dist/cli/chunks/{chunk-FII3WCCY.js → chunk-BKKJEKNT.js} +2 -2
  55. package/dist/cli/chunks/{chunk-TTJJ4DQE.js → chunk-BLU7OLQZ.js} +2 -2
  56. package/dist/cli/chunks/{chunk-AL5VJJN4.js → chunk-BNMV5DCM.js} +1 -1
  57. package/dist/cli/chunks/{chunk-4XJ2A3HY.js → chunk-BPM7NEHS.js} +4 -4
  58. package/dist/cli/chunks/{chunk-3V36WMIO.js → chunk-BWNMAXV7.js} +1 -1
  59. package/dist/cli/chunks/{chunk-EDOGRFAG.js → chunk-BXIJY6SB.js} +1 -1
  60. package/dist/cli/chunks/{chunk-ZXEWTZFR.js → chunk-C2K4LQI5.js} +1 -1
  61. package/dist/cli/chunks/{chunk-3WR35GFF.js → chunk-C7HGYLNF.js} +2 -2
  62. package/dist/cli/chunks/{chunk-7YSBATSN.js → chunk-CDVKFAYP.js} +2 -2
  63. package/dist/cli/chunks/{chunk-JBKZ5TUM.js → chunk-CJTXZI37.js} +2 -2
  64. package/dist/cli/chunks/{chunk-VMWRMINE.js → chunk-CP4GSICY.js} +1 -1
  65. package/dist/cli/chunks/{chunk-2XPMATEK.js → chunk-CXUHD2O5.js} +2 -2
  66. package/dist/cli/chunks/{chunk-W7TYKPLY.js → chunk-CYYT6YEV.js} +2 -2
  67. package/dist/cli/chunks/{chunk-SO6G4IX3.js → chunk-D72N5V2S.js} +2 -2
  68. package/dist/cli/chunks/{chunk-4LODYRNV.js → chunk-DQ3J7ZT6.js} +2 -2
  69. package/dist/cli/chunks/{chunk-PVDXNQPL.js → chunk-DSNFOX22.js} +2 -2
  70. package/dist/cli/chunks/{chunk-LPR2R3AN.js → chunk-EOBZJDJR.js} +3 -3
  71. package/dist/cli/chunks/{chunk-6R3YOAKO.js → chunk-FBYFDD7L.js} +2 -2
  72. package/dist/cli/chunks/{chunk-ZPP57WQU.js → chunk-FFSS3Y6W.js} +2 -2
  73. package/dist/cli/chunks/chunk-FNMEVLSN.js +2 -0
  74. package/dist/cli/chunks/{chunk-7KXPNNMR.js → chunk-GASACVTU.js} +2 -2
  75. package/dist/cli/chunks/{chunk-ABU64UWB.js → chunk-GGF5FZWS.js} +1 -1
  76. package/dist/cli/chunks/{chunk-M6FW56MV.js → chunk-GLO53MUQ.js} +2 -2
  77. package/dist/cli/chunks/{chunk-52U5BFZP.js → chunk-GW3M7GQH.js} +2 -2
  78. package/dist/cli/chunks/chunk-GXMNCW2M.js +2 -0
  79. package/dist/cli/chunks/{chunk-D45QLJEL.js → chunk-HDI3FD4G.js} +1 -1
  80. package/dist/cli/chunks/{chunk-26WEI3P4.js → chunk-HGKSU4QV.js} +2 -2
  81. package/dist/cli/chunks/{chunk-B2VBDMDI.js → chunk-HHMTQQUE.js} +2 -2
  82. package/dist/cli/chunks/{chunk-4Y3LGBKJ.js → chunk-HZGFER4N.js} +3 -3
  83. package/dist/cli/chunks/{chunk-AXKWV5NF.js → chunk-I4BZLVFE.js} +3 -3
  84. package/dist/cli/chunks/{chunk-JDSHUECG.js → chunk-IC6SOVGO.js} +2 -2
  85. package/dist/cli/chunks/{chunk-YFCULQBP.js → chunk-IE6FDICX.js} +2 -2
  86. package/dist/cli/chunks/{chunk-FGD6HINU.js → chunk-IHWWZOHP.js} +1 -1
  87. package/dist/cli/chunks/{chunk-HC6KTVFR.js → chunk-J4IAMQZI.js} +2 -2
  88. package/dist/cli/chunks/{chunk-VMFAANWX.js → chunk-J6ZCULWG.js} +2 -2
  89. package/dist/cli/chunks/{chunk-YGVDP6X7.js → chunk-JDZIBSMY.js} +1 -1
  90. package/dist/cli/chunks/{chunk-WPSK237F.js → chunk-JIM4VSLF.js} +3 -3
  91. package/dist/cli/chunks/{chunk-EK3HPH6A.js → chunk-JRHRC2MP.js} +1 -1
  92. package/dist/cli/chunks/{chunk-3JF5A72M.js → chunk-JRNDFC23.js} +2 -2
  93. package/dist/cli/chunks/chunk-JWZNWVLG.js +153 -0
  94. package/dist/cli/chunks/{chunk-Q5TR6ETB.js → chunk-KQV5644J.js} +3 -3
  95. package/dist/cli/chunks/{chunk-4RTWPR3X.js → chunk-LAJHHR3Q.js} +1 -1
  96. package/dist/cli/chunks/{chunk-AOXJFDH5.js → chunk-LF5XOYR7.js} +10 -10
  97. package/dist/cli/chunks/{chunk-I3NWKPXJ.js → chunk-LRWBOJ5Y.js} +2 -2
  98. package/dist/cli/chunks/{chunk-354367AP.js → chunk-LZ6TJ7XL.js} +2 -2
  99. package/dist/cli/chunks/{chunk-4QOI5JS7.js → chunk-M5P5WNXA.js} +1 -1
  100. package/dist/cli/chunks/{chunk-SE3JFUKP.js → chunk-MCUILJ33.js} +1 -1
  101. package/dist/cli/chunks/{chunk-ZG5UAEEO.js → chunk-MIAY35K6.js} +2 -2
  102. package/dist/cli/chunks/{chunk-6Q57K4YD.js → chunk-N3PSRG6F.js} +2 -2
  103. package/dist/cli/chunks/{chunk-FMNXHVIN.js → chunk-NEXJUTHF.js} +2 -2
  104. package/dist/cli/chunks/{chunk-RJN2RM76.js → chunk-NHRBKOYD.js} +2 -2
  105. package/dist/cli/chunks/{chunk-BJLA2IX7.js → chunk-NK2Z6FGF.js} +2 -2
  106. package/dist/cli/chunks/{chunk-Y25PO65W.js → chunk-NOCPO55P.js} +2 -2
  107. package/dist/cli/chunks/{chunk-XT4TDLOB.js → chunk-NTMN2ZJY.js} +2 -2
  108. package/dist/cli/chunks/{chunk-7DTMENY6.js → chunk-NVXSM7UO.js} +2 -2
  109. package/dist/cli/chunks/{chunk-CKOF27L7.js → chunk-O65OPAZH.js} +2 -2
  110. package/dist/cli/chunks/{chunk-OGNTCZKK.js → chunk-OEXSBR72.js} +1 -1
  111. package/dist/cli/chunks/{chunk-Y6DWJKHU.js → chunk-OJORNYN3.js} +3 -3
  112. package/dist/cli/chunks/{chunk-DPL762HU.js → chunk-ONSNNY6J.js} +1 -1
  113. package/dist/cli/chunks/{chunk-IBDQWKI3.js → chunk-OXVAGR64.js} +2 -2
  114. package/dist/cli/chunks/{chunk-C5C4W572.js → chunk-P7G5LGUE.js} +2 -2
  115. package/dist/cli/chunks/{chunk-XLT3FYS7.js → chunk-PDS5P5QD.js} +2 -2
  116. package/dist/cli/chunks/{chunk-IU5RSN6M.js → chunk-PQ4NSXZM.js} +2 -2
  117. package/dist/cli/chunks/{chunk-4MHN7JWC.js → chunk-PRA73XZY.js} +12 -12
  118. package/dist/cli/chunks/{chunk-2XQHG56O.js → chunk-PZ3Q34OT.js} +2 -2
  119. package/dist/cli/chunks/{chunk-EEKG35K5.js → chunk-PZZDAECU.js} +3 -3
  120. package/dist/cli/chunks/{chunk-J6PFPY7V.js → chunk-QJXUK54J.js} +2 -2
  121. package/dist/cli/chunks/{chunk-7P6X4BFO.js → chunk-QOAI6ETC.js} +3 -3
  122. package/dist/cli/chunks/{chunk-53YOYZW5.js → chunk-QORWBION.js} +2 -2
  123. package/dist/cli/chunks/{chunk-OS62Y77J.js → chunk-QXZOUETY.js} +2 -2
  124. package/dist/cli/chunks/{chunk-G2ZIJZJ7.js → chunk-QZBPXJ5C.js} +2 -2
  125. package/dist/cli/chunks/{chunk-WHHQIL4F.js → chunk-R4A6PY5D.js} +2 -2
  126. package/dist/cli/chunks/{chunk-ZLBY25MB.js → chunk-R7XEACKR.js} +1 -1
  127. package/dist/cli/chunks/{chunk-K4C25BWV.js → chunk-RAS7WRN5.js} +2 -2
  128. package/dist/cli/chunks/{chunk-MHMQ6MCT.js → chunk-REJGZP27.js} +2 -2
  129. package/dist/cli/chunks/{chunk-PW72M2FE.js → chunk-RIASOMB2.js} +2 -2
  130. package/dist/cli/chunks/{chunk-TEIWJ3GJ.js → chunk-RJ7TU2MP.js} +1 -1
  131. package/dist/cli/chunks/{chunk-W72FJA2H.js → chunk-S42RFOZJ.js} +2 -2
  132. package/dist/cli/chunks/chunk-SFQFBLWQ.js +2 -0
  133. package/dist/cli/chunks/{chunk-O7J54OHN.js → chunk-SHKOPOPD.js} +1 -1
  134. package/dist/cli/chunks/{chunk-QKK7VBVB.js → chunk-TGIKKD43.js} +2 -2
  135. package/dist/cli/chunks/chunk-TMPRR3FZ.js +2 -0
  136. package/dist/cli/chunks/{chunk-GW6XWMX2.js → chunk-U55X2ZUM.js} +2 -2
  137. package/dist/cli/chunks/{chunk-C4EZNOWK.js → chunk-U5ITD7ZD.js} +1 -1
  138. package/dist/cli/chunks/{chunk-RKXZLTWR.js → chunk-UBPJQKYS.js} +2 -2
  139. package/dist/cli/chunks/{chunk-DVW66FPU.js → chunk-UBWSYDO5.js} +1 -1
  140. package/dist/cli/chunks/chunk-UEC53US3.js +316 -0
  141. package/dist/cli/chunks/{chunk-UBY322ED.js → chunk-UGPBL7LX.js} +2 -2
  142. package/dist/cli/chunks/{chunk-MMEXHZUC.js → chunk-UKF4V7LE.js} +5 -5
  143. package/dist/cli/chunks/{chunk-FIPKIIMS.js → chunk-UR655D4K.js} +2 -2
  144. package/dist/cli/chunks/{chunk-GODAWJMZ.js → chunk-USTUWUCE.js} +2 -2
  145. package/dist/cli/chunks/{chunk-FGSIID5C.js → chunk-UZXDYT6O.js} +2 -2
  146. package/dist/cli/chunks/{chunk-JATLFS6A.js → chunk-VFRWLSQO.js} +1 -1
  147. package/dist/cli/chunks/{chunk-AF6P5RWY.js → chunk-VHJCQBD2.js} +2 -2
  148. package/dist/cli/chunks/{chunk-J5XDKVI7.js → chunk-VTFYY4SH.js} +2 -2
  149. package/dist/cli/chunks/{chunk-BTLUWH4R.js → chunk-W52R3G22.js} +2 -2
  150. package/dist/cli/chunks/{chunk-AOQYORVA.js → chunk-WBDV4V3H.js} +2 -2
  151. package/dist/cli/chunks/{chunk-3I4TCMOJ.js → chunk-WPEGG6DX.js} +1 -1
  152. package/dist/cli/chunks/{chunk-KQVIWE3W.js → chunk-WPG5LXR7.js} +2 -2
  153. package/dist/cli/chunks/{chunk-DLBVADWQ.js → chunk-X2CEX4KC.js} +42 -42
  154. package/dist/cli/chunks/{chunk-MTBGOWJA.js → chunk-X2K3BTI4.js} +2 -2
  155. package/dist/cli/chunks/{chunk-NCSXLMDL.js → chunk-XDRAU3W6.js} +2 -2
  156. package/dist/cli/chunks/{chunk-URP75DL4.js → chunk-XJTGLG7G.js} +1 -1
  157. package/dist/cli/chunks/{chunk-TRNBQFFG.js → chunk-XS6BIOPQ.js} +2 -2
  158. package/dist/cli/chunks/{chunk-MEIU7457.js → chunk-XTAXSKPC.js} +2 -2
  159. package/dist/cli/chunks/{chunk-VN2HHBZN.js → chunk-XYV6YUWS.js} +2 -2
  160. package/dist/cli/chunks/{chunk-UORTQXJ2.js → chunk-YGB3MT3R.js} +1 -1
  161. package/dist/cli/chunks/{chunk-37ZUF5NX.js → chunk-YNXQMJGJ.js} +1 -1
  162. package/dist/cli/chunks/{chunk-BLPWJQTY.js → chunk-ZCDGLNJ7.js} +2 -2
  163. package/dist/cli/chunks/{chunk-62UM7Q5N.js → chunk-ZNITDSWL.js} +1 -1
  164. package/dist/cli/chunks/{ci-CBNVLOOQ.js → ci-IU5HVUL5.js} +2 -2
  165. package/dist/cli/chunks/{ci-output-I4HY2FYJ.js → ci-output-CLI4A43F.js} +2 -2
  166. package/dist/cli/chunks/{circuit-breaker-5VRBKGWL.js → circuit-breaker-ZR5OFMW7.js} +2 -2
  167. package/dist/cli/chunks/{claude-flow-setup-XPJPKHIO.js → claude-flow-setup-UBMA6ZHJ.js} +2 -2
  168. package/dist/cli/chunks/client-KKCFGD7R.js +2 -0
  169. package/dist/cli/chunks/{cline-installer-OFRDUUWZ.js → cline-installer-EWYELOBI.js} +2 -2
  170. package/dist/cli/chunks/{code-QIZQVB3E.js → code-YSPF4MXN.js} +2 -2
  171. package/dist/cli/chunks/{code-index-extractor-LMUUWEX4.js → code-index-extractor-WW5OKSTN.js} +2 -2
  172. package/dist/cli/chunks/{codex-installer-N2MKIZ2S.js → codex-installer-GLADK5PY.js} +2 -2
  173. package/dist/cli/chunks/{completions-Y36S3C5J.js → completions-2KTWZ3AK.js} +2 -2
  174. package/dist/cli/chunks/{complexity-analyzer-73YS3WUD.js → complexity-analyzer-KMX4OWKB.js} +2 -2
  175. package/dist/cli/chunks/{continuedev-installer-SAOTP6J3.js → continuedev-installer-4FHU4OEJ.js} +2 -2
  176. package/dist/cli/chunks/{copilot-installer-A4HXF6HE.js → copilot-installer-AKR4WE7B.js} +2 -2
  177. package/dist/cli/chunks/core-handlers-KRSSJEO5.js +2 -0
  178. package/dist/cli/chunks/{cost-tracker-P26XUVZS.js → cost-tracker-BUJ6WEWY.js} +2 -2
  179. package/dist/cli/chunks/{coverage-HVNHSMVJ.js → coverage-OB6HVQS4.js} +3 -3
  180. package/dist/cli/chunks/cross-domain-router-27QGWU27.js +2 -0
  181. package/dist/cli/chunks/{cursor-installer-46BQFTYZ.js → cursor-installer-3AOE4O3Q.js} +2 -2
  182. package/dist/cli/chunks/{daemon-Y54O3FLT.js → daemon-4RAL5URG.js} +3 -3
  183. package/dist/cli/chunks/{daemon-YE7K2AZF.js → daemon-JGSPLYGO.js} +4 -4
  184. package/dist/cli/chunks/{dag-attention-scheduler-ETA7YY52.js → dag-attention-scheduler-DSBTHIMH.js} +2 -2
  185. package/dist/cli/chunks/{detect-5WLQ2J3E.js → detect-6CVW2VUQ.js} +2 -2
  186. package/dist/cli/chunks/{dist-node-45WW6I7J.js → dist-node-EWPKBTYA.js} +2 -2
  187. package/dist/cli/chunks/{domain-handler-J7DQV74M.js → domain-handler-HLVIJU25.js} +2 -2
  188. package/dist/cli/chunks/{domain-transfer-GD2EGQVR.js → domain-transfer-7Y3BR3YU.js} +2 -2
  189. package/dist/cli/chunks/dream-M6K47Q4H.js +2 -0
  190. package/dist/cli/chunks/{embed-and-insert-pattern-JELNEA2D.js → embed-and-insert-pattern-ZMJ3263X.js} +2 -2
  191. package/dist/cli/chunks/{eval-A4PA5G2U.js → eval-73XW2WJD.js} +2 -2
  192. package/dist/cli/chunks/{experience-capture-middleware-MLHTYWTA.js → experience-capture-middleware-OGJ3JOSQ.js} +3 -3
  193. package/dist/cli/chunks/{fast-paths-QYDTITRV.js → fast-paths-5XCY3Y6U.js} +2 -2
  194. package/dist/cli/chunks/{feature-flags-H4MSY26Z.js → feature-flags-R5V2FRJR.js} +2 -2
  195. package/dist/cli/chunks/{feature-flags-MQYYRHIK.js → feature-flags-VULQI6KY.js} +2 -2
  196. package/dist/cli/chunks/{file-discovery-RMFVJNGL.js → file-discovery-HW33C3HC.js} +2 -2
  197. package/dist/cli/chunks/{fleet-7KZQOTAC.js → fleet-NH3XR5OY.js} +3 -3
  198. package/dist/cli/chunks/{gnn-wrapper-NMZFTGVH.js → gnn-wrapper-L3XMLPTG.js} +2 -2
  199. package/dist/cli/chunks/{heartbeat-handler-7BQDK7MG.js → heartbeat-handler-TIQFBT4D.js} +4 -4
  200. package/dist/cli/chunks/heartbeat-scheduler-URXBF5RW.js +2 -0
  201. package/dist/cli/chunks/hnsw-adapter-WWAGM6HK.js +2 -0
  202. package/dist/cli/chunks/hnsw-index-UFV2HSZE.js +2 -0
  203. package/dist/cli/chunks/{hnsw-legacy-bridge-TPPGBPKF.js → hnsw-legacy-bridge-YL2SUIPA.js} +2 -2
  204. package/dist/cli/chunks/{better-sqlite3-2KR4LQRU.js → hnswlib-node-62RTSHAY.js} +2 -2
  205. package/dist/cli/chunks/{hooks-CYZIUYSH.js → hooks-UR2ZF54G.js} +10 -10
  206. package/dist/cli/chunks/hybrid-router-3U6Q6OTL.js +2 -0
  207. package/dist/cli/chunks/{hypergraph-engine-WC6DMTYQ.js → hypergraph-engine-NX45AOPY.js} +2 -2
  208. package/dist/cli/chunks/{hypergraph-handler-GTGA3TXJ.js → hypergraph-handler-LUM4YI4K.js} +3 -3
  209. package/dist/cli/chunks/impact-analyzer-EUEX6ZRO.js +2 -0
  210. package/dist/cli/chunks/{init-handler-N3Z72JNI.js → init-handler-YTKKNTVV.js} +6 -6
  211. package/dist/cli/chunks/init-wizard-POKY2LRY.js +2 -0
  212. package/dist/cli/chunks/kernel-HPAONLZY.js +2 -0
  213. package/dist/cli/chunks/{kilocode-installer-FUX4V6II.js → kilocode-installer-ZW7DVH7T.js} +2 -2
  214. package/dist/cli/chunks/{kiro-installer-ZSNZT7ZR.js → kiro-installer-IA7INW4N.js} +2 -2
  215. package/dist/cli/chunks/knowledge-graph-2WCUFG63.js +2 -0
  216. package/dist/cli/chunks/{learning-UQY64COU.js → learning-4AZ5PGTT.js} +3 -3
  217. package/dist/cli/chunks/{llm-router-CMHGGX6N.js → llm-router-WQ4E3AOP.js} +4 -4
  218. package/dist/cli/chunks/llm-router-service-D5VMG6SD.js +2 -0
  219. package/dist/cli/chunks/{load-E6WH4QN2.js → load-4FAH7CZO.js} +2 -2
  220. package/dist/cli/chunks/load-test-DHG26REU.js +2 -0
  221. package/dist/cli/chunks/{mcp-UM5VTW6N.js → mcp-KLLHI6DG.js} +2 -2
  222. package/dist/cli/chunks/{memory-7Q3XDUE5.js → memory-Q5HLIUC6.js} +5 -5
  223. package/dist/cli/chunks/memory-backend-GLWQ4DAL.js +2 -0
  224. package/dist/cli/chunks/memory-handlers-P72I4VV4.js +2 -0
  225. package/dist/cli/chunks/{multi-model-executor-LZENWVRR.js → multi-model-executor-ABI73AFV.js} +2 -2
  226. package/dist/cli/chunks/{opencode-installer-O2JAIPLF.js → opencode-installer-KRPQ6JOJ.js} +2 -2
  227. package/dist/cli/chunks/{orchestrator-DKZWXDRI.js → orchestrator-SUPEONRG.js} +18 -18
  228. package/dist/cli/chunks/pattern-null-store-Y2YFTE3V.js +2 -0
  229. package/dist/cli/chunks/{pattern-usage-recorder-CLUL4M55.js → pattern-usage-recorder-R4GKK6RZ.js} +2 -2
  230. package/dist/cli/chunks/{pipeline-2VDLTR5J.js → pipeline-LCUETNGD.js} +2 -2
  231. package/dist/cli/chunks/{platform-4N4Q5XYX.js → platform-WJDIB4X3.js} +2 -2
  232. package/dist/cli/chunks/{plugin-GY5AU5CS.js → plugin-2X5NY2RF.js} +2 -2
  233. package/dist/cli/chunks/{prime-radiant-advanced-wasm-TQ4DKDZS.js → prime-radiant-advanced-wasm-3T665QC6.js} +2 -2
  234. package/dist/cli/chunks/protocol-executor-HNT67NN5.js +2 -0
  235. package/dist/cli/chunks/{protocol-handler-T3LZ3WRG.js → protocol-handler-JTXRF7GU.js} +2 -2
  236. package/dist/cli/chunks/{prove-OV7S5J4W.js → prove-BFPWWPOC.js} +2 -2
  237. package/dist/cli/chunks/provider-manager-5YGPZIEZ.js +2 -0
  238. package/dist/cli/chunks/qe-reasoning-bank-Z5UGOA3F.js +2 -0
  239. package/dist/cli/chunks/{quality-AXD4NLQA.js → quality-F7UZU4RN.js} +2 -2
  240. package/dist/cli/chunks/quality-gate-R5L4UZIX.js +7 -0
  241. package/dist/cli/chunks/queen-coordinator-P5LU5NWI.js +2 -0
  242. package/dist/cli/chunks/{real-embeddings-2PUCC7FG.js → real-embeddings-LZD6HTQF.js} +2 -2
  243. package/dist/cli/chunks/{roocode-installer-WJ5ARGLW.js → roocode-installer-6TTG7VSH.js} +2 -2
  244. package/dist/cli/chunks/router-CRGHUAVR.js +2 -0
  245. package/dist/cli/chunks/routing-feedback-BVX5ZBCF.js +2 -0
  246. package/dist/cli/chunks/{routing-handler-CU6657SZ.js → routing-handler-SW442GK7.js} +2 -2
  247. package/dist/cli/chunks/{ruvector-commands-IIF6VSFW.js → ruvector-commands-CLFGKXMW.js} +2 -2
  248. package/dist/cli/chunks/{rvf-dual-writer-YMQI7XO2.js → rvf-dual-writer-EVPPXXXS.js} +2 -2
  249. package/dist/cli/chunks/{rvf-migration-adapter-HDE3PR2W.js → rvf-migration-adapter-NOHDIRIP.js} +2 -2
  250. package/dist/cli/chunks/{rvf-migration-coordinator-MQV5OA7K.js → rvf-migration-coordinator-BYJ3M7WZ.js} +2 -2
  251. package/dist/cli/chunks/rvf-native-adapter-FZJSQOJM.js +2 -0
  252. package/dist/cli/chunks/safe-db-USYNEOC6.js +2 -0
  253. package/dist/cli/chunks/schedule-KCRCQ3PS.js +2 -0
  254. package/dist/cli/chunks/scheduler-CX3UHI4U.js +2 -0
  255. package/dist/cli/chunks/{security-UM3IGDSM.js → security-IXDKBPSG.js} +3 -3
  256. package/dist/cli/chunks/{shared-rvf-adapter-I3SOJ6M4.js → shared-rvf-adapter-VCOK3OVD.js} +2 -2
  257. package/dist/cli/chunks/{shared-rvf-dual-writer-KQGC2UO7.js → shared-rvf-dual-writer-FFKBKYNL.js} +2 -2
  258. package/dist/cli/chunks/sqlite-persistence-K23C4TFH.js +2 -0
  259. package/dist/cli/chunks/{status-handler-OX4CJZME.js → status-handler-M5W64S5U.js} +2 -2
  260. package/dist/cli/chunks/{structural-health-PYUMVBXJ.js → structural-health-55X6BTLT.js} +2 -2
  261. package/dist/cli/chunks/{sync-VALFNTA6.js → sync-BUGDXW3Y.js} +2 -2
  262. package/dist/cli/chunks/{sync-2TED3YTY.js → sync-NUG67HGK.js} +2 -2
  263. package/dist/cli/chunks/{task-handler-VPGAJVPC.js → task-handler-T6ZKXV4S.js} +2 -2
  264. package/dist/cli/chunks/{task-handlers-IB4UAMU6.js → task-handlers-H63TB2UI.js} +3 -3
  265. package/dist/cli/chunks/{test-OMRJOZB6.js → test-VEK76SBT.js} +4 -4
  266. package/dist/cli/chunks/{test-scheduling-ZL3YFPBU.js → test-scheduling-QZM6PNZH.js} +3 -3
  267. package/dist/cli/chunks/{token-bootstrap-DNWZI7SH.js → token-bootstrap-W5IAMJW4.js} +2 -2
  268. package/dist/cli/chunks/{token-usage-IYO7RGFF.js → token-usage-OBY6UEUR.js} +2 -2
  269. package/dist/cli/chunks/{transformers-53ALC34T.js → transformers-EFNY2MRX.js} +2 -2
  270. package/dist/cli/chunks/{tree-sitter-wasm-parser-WUKJ2I2Q.js → tree-sitter-wasm-parser-EU2S5NVM.js} +2 -2
  271. package/dist/cli/chunks/{types-47FTEPMV.js → types-3DYRKX23.js} +2 -2
  272. package/dist/cli/chunks/unified-memory-NCDBQLLF.js +2 -0
  273. package/dist/cli/chunks/unified-memory-hnsw-T7NSGQ2H.js +2 -0
  274. package/dist/cli/chunks/unified-persistence-XUAYDCMM.js +2 -0
  275. package/dist/cli/chunks/{upgrade-QPLMJA5Z.js → upgrade-H5V53FRF.js} +2 -2
  276. package/dist/cli/chunks/{validate-3GVKZOVF.js → validate-IL22VB5I.js} +2 -2
  277. package/dist/cli/chunks/{validate-swarm-XCRTLVM6.js → validate-swarm-WZKECK3W.js} +2 -2
  278. package/dist/cli/chunks/{vibium-CH4VPKVZ.js → vibium-KKM23OTQ.js} +2 -2
  279. package/dist/cli/chunks/visual-security-3TUC4GPP.js +2 -0
  280. package/dist/cli/chunks/{web-tree-sitter-JDBNAZTV.js → web-tree-sitter-NJM5YBOY.js} +2 -2
  281. package/dist/cli/chunks/{windsurf-installer-3MNPVJBP.js → windsurf-installer-SLP43TVT.js} +2 -2
  282. package/dist/cli/chunks/witness-chain-QLOKUZXC.js +2 -0
  283. package/dist/cli/chunks/{witness-chain-HR5UBV5J.js → witness-chain-XBEPT4XD.js} +2 -2
  284. package/dist/cli/chunks/{witness-key-manager-G5SQTIBZ.js → witness-key-manager-DAAMNYOW.js} +2 -2
  285. package/dist/cli/chunks/{workflow-43EMD5FY.js → workflow-SZOOU6D3.js} +4 -4
  286. package/dist/cli/chunks/workflow-orchestrator-6JAYTZ7L.js +2 -0
  287. package/dist/cli/chunks/{wrappers-3N7AYNM3.js → wrappers-I2CBKWGF.js} +2 -2
  288. package/dist/cli/commands/quality-gate.d.ts +24 -0
  289. package/dist/cli/commands/quality-gate.js +135 -0
  290. package/dist/cli/index.js +5 -0
  291. package/dist/coordination/mincut/dream-integration.d.ts +11 -0
  292. package/dist/coordination/mincut/dream-integration.js +39 -12
  293. package/dist/init/init-wizard-hooks.js +11 -25
  294. package/dist/init/phases/07-hooks.js +15 -25
  295. package/dist/init/settings-merge.d.ts +44 -0
  296. package/dist/init/settings-merge.js +119 -4
  297. package/dist/integrations/ruvector/feature-flags.js +7 -0
  298. package/dist/learning/pattern-lifecycle.d.ts +16 -0
  299. package/dist/learning/pattern-lifecycle.js +77 -1
  300. package/dist/learning/provenance-tier.d.ts +52 -0
  301. package/dist/learning/provenance-tier.js +64 -0
  302. package/dist/learning/qe-flywheel/corpus-scorer.d.ts +55 -0
  303. package/dist/learning/qe-flywheel/corpus-scorer.js +293 -0
  304. package/dist/learning/qe-flywheel/coupled-anchor.d.ts +91 -0
  305. package/dist/learning/qe-flywheel/coupled-anchor.js +181 -0
  306. package/dist/learning/qe-flywheel/generation.d.ts +121 -0
  307. package/dist/learning/qe-flywheel/generation.js +167 -0
  308. package/dist/learning/qe-flywheel/policy.d.ts +37 -0
  309. package/dist/learning/qe-flywheel/policy.js +66 -0
  310. package/dist/learning/qe-flywheel/receipt-store.d.ts +31 -0
  311. package/dist/learning/qe-flywheel/receipt-store.js +89 -0
  312. package/dist/learning/qe-flywheel/receipt.d.ts +62 -0
  313. package/dist/learning/qe-flywheel/receipt.js +97 -0
  314. package/dist/mcp/bundle.js +396 -390
  315. package/dist/mcp/tools/quality-assessment/gate.d.ts +38 -0
  316. package/dist/mcp/tools/quality-assessment/gate.js +86 -0
  317. package/dist/mcp/tools/registry.d.ts +1 -0
  318. package/dist/mcp/tools/registry.js +3 -0
  319. package/dist/shared/safe-db.js +23 -4
  320. package/dist/validation/anchor-set.d.ts +74 -0
  321. package/dist/validation/anchor-set.js +78 -0
  322. package/dist/validation/frontier-judge.d.ts +99 -0
  323. package/dist/validation/frontier-judge.js +234 -0
  324. package/dist/validation/gate-reexecute.d.ts +165 -0
  325. package/dist/validation/gate-reexecute.js +255 -0
  326. package/dist/validation/quality-gate-runner.d.ts +49 -0
  327. package/dist/validation/quality-gate-runner.js +62 -0
  328. package/dist/validation/quality-verdict.d.ts +94 -0
  329. package/dist/validation/quality-verdict.js +120 -0
  330. package/package.json +1 -1
  331. package/dist/cli/chunks/adapter-KNM5R47J.js +0 -2
  332. package/dist/cli/chunks/aqe-learning-engine-MXPJLVR3.js +0 -2
  333. package/dist/cli/chunks/base-X4EXQ2AS.js +0 -2
  334. package/dist/cli/chunks/browser-workflow-4HX6RP5F.js +0 -2
  335. package/dist/cli/chunks/chunk-FHTYEAQ3.js +0 -2
  336. package/dist/cli/chunks/chunk-MIU5RUBJ.js +0 -149
  337. package/dist/cli/chunks/chunk-SK754ZSH.js +0 -316
  338. package/dist/cli/chunks/chunk-V6NAB5UZ.js +0 -2
  339. package/dist/cli/chunks/chunk-YR2JKBZO.js +0 -2
  340. package/dist/cli/chunks/chunk-ZMPAM4DY.js +0 -2
  341. package/dist/cli/chunks/client-AHXNCOHK.js +0 -2
  342. package/dist/cli/chunks/core-handlers-EEFLLMAZ.js +0 -2
  343. package/dist/cli/chunks/cross-domain-router-LT3H4SNJ.js +0 -2
  344. package/dist/cli/chunks/dream-4K3BK4IG.js +0 -2
  345. package/dist/cli/chunks/heartbeat-scheduler-IMPPGQUK.js +0 -2
  346. package/dist/cli/chunks/hnsw-adapter-EIAA6R2L.js +0 -2
  347. package/dist/cli/chunks/hnsw-index-ZXXP6AXZ.js +0 -2
  348. package/dist/cli/chunks/hybrid-router-LXWG4MLH.js +0 -2
  349. package/dist/cli/chunks/impact-analyzer-TP5LRFYH.js +0 -2
  350. package/dist/cli/chunks/init-wizard-AIOA5KOY.js +0 -2
  351. package/dist/cli/chunks/kernel-SQALRU6Q.js +0 -2
  352. package/dist/cli/chunks/knowledge-graph-JFVT6SNN.js +0 -2
  353. package/dist/cli/chunks/llm-router-service-XHFKTH3I.js +0 -2
  354. package/dist/cli/chunks/load-test-JEIFJKNN.js +0 -2
  355. package/dist/cli/chunks/memory-backend-NT7I37CP.js +0 -2
  356. package/dist/cli/chunks/memory-handlers-746D7NE7.js +0 -2
  357. package/dist/cli/chunks/pattern-null-store-6QU6WHDW.js +0 -2
  358. package/dist/cli/chunks/protocol-executor-GT2MZYUU.js +0 -2
  359. package/dist/cli/chunks/provider-manager-OATJ7R3D.js +0 -2
  360. package/dist/cli/chunks/qe-reasoning-bank-IJXNQ67O.js +0 -2
  361. package/dist/cli/chunks/queen-coordinator-6RBHWCUG.js +0 -2
  362. package/dist/cli/chunks/router-XKQRT5JK.js +0 -2
  363. package/dist/cli/chunks/routing-feedback-ACPSD4LW.js +0 -2
  364. package/dist/cli/chunks/rvf-native-adapter-SIWRKE33.js +0 -2
  365. package/dist/cli/chunks/safe-db-LCPUYMX4.js +0 -2
  366. package/dist/cli/chunks/schedule-HIQJCWXG.js +0 -2
  367. package/dist/cli/chunks/scheduler-QE5EJ5LE.js +0 -2
  368. package/dist/cli/chunks/sqlite-persistence-EU54UTMH.js +0 -2
  369. package/dist/cli/chunks/unified-memory-CJLMC2I4.js +0 -2
  370. package/dist/cli/chunks/unified-memory-hnsw-FDGR4D2J.js +0 -2
  371. package/dist/cli/chunks/unified-persistence-UFH5GLDN.js +0 -2
  372. package/dist/cli/chunks/visual-security-4ARJ7J2Y.js +0 -2
  373. package/dist/cli/chunks/witness-chain-73QC33ED.js +0 -2
  374. package/dist/cli/chunks/workflow-orchestrator-RKMMPXNA.js +0 -2
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.5");process.exit(0)}
2
- import{c as t}from"./chunk-C4EZNOWK.js";function o(e){try{return e.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.12.1");process.exit(0)}
2
+ import{c as t}from"./chunk-U5ITD7ZD.js";function o(e){try{return e.prepare(`
3
3
  SELECT COUNT(*) as count FROM sqlite_master
4
4
  WHERE type='table' AND name IN ('hypergraph_nodes', 'hypergraph_edges')
5
5
  `).get().count===2}catch{return!1}}var r,a,E,n,p=t(()=>{"use strict";r=`
@@ -1,10 +1,10 @@
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.11.5");process.exit(0)}
2
- import{a as k}from"./chunk-37ZUF5NX.js";import{a as te,b as ne}from"./chunk-4RTWPR3X.js";import{b as ee}from"./chunk-O7J54OHN.js";import{b as E,d as fe}from"./chunk-CKOF27L7.js";import{a as b,c as T}from"./chunk-RKXZLTWR.js";var he={M:16,efConstruction:200,efSearch:100},P={enabled:!0,pretrainedPatterns:!0,hnswConfig:he,promotionThreshold:3,qualityThreshold:.7,embeddingModel:"auto"},_={mode:"hybrid",confidenceThreshold:.7,feedbackEnabled:!0,cacheEnabled:!0,cacheTTLMs:300*1e3},F={enabled:["pattern-consolidator","coverage-gap-scanner","flaky-test-detector","routing-accuracy-monitor"],intervals:{"pattern-consolidator":1800*1e3,"coverage-gap-scanner":3600*1e3,"flaky-test-detector":7200*1e3,"routing-accuracy-monitor":900*1e3},maxConcurrent:4,daemonAutoStart:!0},N={claudeCode:!0,preCommit:!1,ciIntegration:!1},$={install:!0,installV2:!0,installV3:!0,overwrite:!1},O={enabled:!0,parameters:["hnsw.efSearch","routing.confidenceThreshold","pattern.promotionThreshold","testGen.complexityLimit"],tuningIntervalMs:10080*60*1e3,evaluationPeriodMs:5e3};var L=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization","enterprise-integration"];function M(){return"3.11.5"}function Fe(r,e){return{version:M(),project:{name:r,root:e,type:"single"},learning:P,routing:_,workers:F,hooks:N,skills:$,autoTuning:O,domains:{enabled:L,disabled:[]},agents:{maxConcurrent:15,defaultTimeout:6e4}}}fe();import{readFileSync as w,existsSync as p,statSync as ye,readdirSync as ve}from"fs";import{join as u,basename as re,extname as ie,relative as V}from"path";var be=[{name:"jest",detect:r=>{let e=["jest.config.js","jest.config.ts","jest.config.mjs","jest.config.cjs"];for(let n of e)if(p(u(r,n)))return{name:"jest",version:A(r,"jest"),configFile:n,confidence:1};let t=S(r);return t?.jest?{name:"jest",version:A(r,"jest"),configFile:"package.json",confidence:.9}:t?.devDependencies?.jest||t?.dependencies?.jest?{name:"jest",version:t.devDependencies?.jest||t.dependencies?.jest,confidence:.7}:null}},{name:"vitest",detect:r=>{let e=["vitest.config.ts","vitest.config.js","vitest.config.mts","vite.config.ts"];for(let n of e)if(p(u(r,n)))return{name:"vitest",version:A(r,"vitest"),configFile:n,confidence:1};let t=S(r);return t?.devDependencies?.vitest||t?.dependencies?.vitest?{name:"vitest",version:t.devDependencies?.vitest,confidence:.8}:null}},{name:"mocha",detect:r=>{let e=[".mocharc.js",".mocharc.json",".mocharc.yaml",".mocharc.yml"];for(let n of e)if(p(u(r,n)))return{name:"mocha",version:A(r,"mocha"),configFile:n,confidence:1};let t=S(r);return t?.devDependencies?.mocha?{name:"mocha",version:t.devDependencies?.mocha,confidence:.8}:null}},{name:"pytest",detect:r=>{let e=["pytest.ini","pyproject.toml","setup.cfg"];for(let n of e){let i=u(r,n);if(p(i))try{let s=w(i,"utf-8");if(s.includes("[pytest]")||s.includes("[tool.pytest]"))return{name:"pytest",configFile:n,confidence:1}}catch(s){console.debug("[ProjectAnalyzer] Config read failed:",s instanceof Error?s.message:s)}}let t=u(r,"requirements.txt");if(p(t))try{if(w(t,"utf-8").includes("pytest"))return{name:"pytest",configFile:"requirements.txt",confidence:.8}}catch(n){console.debug("[ProjectAnalyzer] requirements.txt read failed:",n instanceof Error?n.message:n)}return null}},{name:"playwright",detect:r=>{let e=["playwright.config.ts","playwright.config.js"];for(let n of e)if(p(u(r,n)))return{name:"playwright",version:A(r,"@playwright/test"),configFile:n,confidence:1};let t=S(r);return t?.devDependencies?.["@playwright/test"]?{name:"playwright",version:t.devDependencies["@playwright/test"],confidence:.8}:null}},{name:"cypress",detect:r=>{let e=["cypress.config.ts","cypress.config.js","cypress.json"];for(let t of e)if(p(u(r,t)))return{name:"cypress",version:A(r,"cypress"),configFile:t,confidence:1};return p(u(r,"cypress"))?{name:"cypress",configFile:"cypress/",confidence:.9}:null}}],ke=[{name:"typescript",extensions:[".ts",".tsx",".mts",".cts"]},{name:"javascript",extensions:[".js",".jsx",".mjs",".cjs"]},{name:"python",extensions:[".py",".pyw"]},{name:"java",extensions:[".java"]},{name:"go",extensions:[".go"]},{name:"rust",extensions:[".rs"]},{name:"csharp",extensions:[".cs"]},{name:"ruby",extensions:[".rb"]},{name:"php",extensions:[".php"]},{name:"kotlin",extensions:[".kt",".kts"]},{name:"swift",extensions:[".swift"]}];function S(r){let e=u(r,"package.json");if(!p(e))return null;try{return E(w(e,"utf-8"))}catch{return null}}function A(r,e){let t=S(r);if(t)return t.devDependencies?.[e]||t.dependencies?.[e]}function Q(r,e,t={}){let{maxDepth:n=10,exclude:i=["node_modules",".git","dist","build","coverage",".next","__pycache__"]}=t;function s(o,a){if(a>n)return;let l;try{l=ve(o)}catch{return}for(let g of l){if(i.includes(g))continue;let c=u(o,g),x;try{x=ye(c)}catch{continue}x.isDirectory()?s(c,a+1):x.isFile()&&e(c)}}s(r,0)}var W=class{projectRoot;constructor(e){this.projectRoot=e}async analyze(){let e=Date.now(),[t,n,i,s,o]=await Promise.all([this.detectFrameworks(),this.detectLanguages(),this.detectExistingTests(),this.analyzeComplexity(),this.measureCoverage()]);return{projectName:S(this.projectRoot)?.name||re(this.projectRoot),projectRoot:this.projectRoot,projectType:this.detectProjectType(),frameworks:t,languages:n,existingTests:i,codeComplexity:s,coverage:o,packageManager:this.detectPackageManager(),hasTypeScript:p(u(this.projectRoot,"tsconfig.json")),hasCIConfig:this.detectCIConfig(),ciProvider:this.detectCIProvider(),analysisTimestamp:new Date,analysisDurationMs:Date.now()-e}}async detectFrameworks(){let e=[];for(let t of be){let n=t.detect(this.projectRoot);n&&e.push(n)}return e.sort((t,n)=>n.confidence-t.confidence)}async detectLanguages(){let e=new Map,t=0;Q(this.projectRoot,i=>{let s=ie(i).toLowerCase();if(s){for(let o of ke)if(o.extensions.includes(s)){let a=e.get(o.name)||{count:0,extensions:new Set};a.count++,a.extensions.add(s),e.set(o.name,a),t++;break}}});let n=[];for(let[i,s]of e)n.push({name:i,percentage:t>0?Math.round(s.count/t*100):0,fileCount:s.count,extensions:Array.from(s.extensions)});return n.sort((i,s)=>s.fileCount-i.fileCount)}async detectExistingTests(){let e={totalCount:0,byFramework:{},byType:{unit:0,integration:0,e2e:0,unknown:0},directories:[]},t=new Set,n=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/_test\.[jt]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/,/.*Test\.java$/];return Q(this.projectRoot,i=>{let s=re(i);if(n.some(a=>a.test(s))){e.totalCount++;let a=V(this.projectRoot,i).toLowerCase();a.includes("e2e")||a.includes("cypress")||a.includes("playwright")?e.byType.e2e++:a.includes("integration")||a.includes("int-test")?e.byType.integration++:a.includes("unit")||a.includes("__tests__")||a.includes("test/")?e.byType.unit++:e.byType.unknown++;let l=V(this.projectRoot,u(i,".."));t.add(l)}}),e.directories=Array.from(t).slice(0,10),e}async analyzeComplexity(){let e=[],t=[],n=0,i=0;Q(this.projectRoot,a=>{let l=ie(a);if([".ts",".tsx",".js",".jsx",".py",".java",".go"].includes(l))try{let g=w(a,"utf-8"),c=this.calculateFileComplexity(g,l);t.push(...c.functionComplexities),c.maxComplexity>n&&(n=c.maxComplexity),i++,c.maxComplexity>10&&e.push(V(this.projectRoot,a))}catch(g){console.debug("[ProjectAnalyzer] Complexity analysis read failed:",g instanceof Error?g.message:g)}});let s=t.reduce((a,l)=>a+l,0),o=t.length>0?s/t.length:0;return{averageCyclomatic:Math.round(o*10)/10,maxCyclomatic:n,totalFiles:i,complexFiles:e.slice(0,20),recommendation:o<5?"simple":o<15?"medium":"complex"}}calculateFileComplexity(e,t){let n=this.stripCommentsAndStrings(e,t),i=this.calculateComplexity(n);return{functionComplexities:[i],maxComplexity:i}}removeDelimitedBlocks(e,t,n){let i="",s=0;for(;s<e.length;){let o=e.indexOf(t,s);if(o===-1){i+=e.slice(s);break}i+=e.slice(s,o);let a=e.indexOf(n,o+t.length);if(a===-1)break;s=a+n.length}return i}stripCommentsAndStrings(e,t){let n=e;return[".ts",".tsx",".js",".jsx",".java",".go"].includes(t)?(n=n.split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.12.1");process.exit(0)}
2
+ import{a as b}from"./chunk-YNXQMJGJ.js";import{a as te,b as ne}from"./chunk-LAJHHR3Q.js";import{b as ee}from"./chunk-SHKOPOPD.js";import{b as E,d as ve}from"./chunk-O65OPAZH.js";import{a as k,c as T}from"./chunk-UBPJQKYS.js";var ke={M:16,efConstruction:200,efSearch:100},P={enabled:!0,pretrainedPatterns:!0,hnswConfig:ke,promotionThreshold:3,qualityThreshold:.7,embeddingModel:"auto"},_={mode:"hybrid",confidenceThreshold:.7,feedbackEnabled:!0,cacheEnabled:!0,cacheTTLMs:300*1e3},F={enabled:["pattern-consolidator","coverage-gap-scanner","flaky-test-detector","routing-accuracy-monitor"],intervals:{"pattern-consolidator":1800*1e3,"coverage-gap-scanner":3600*1e3,"flaky-test-detector":7200*1e3,"routing-accuracy-monitor":900*1e3},maxConcurrent:4,daemonAutoStart:!0},$={claudeCode:!0,preCommit:!1,ciIntegration:!1},N={install:!0,installV2:!0,installV3:!0,overwrite:!1},O={enabled:!0,parameters:["hnsw.efSearch","routing.confidenceThreshold","pattern.promotionThreshold","testGen.complexityLimit"],tuningIntervalMs:10080*60*1e3,evaluationPeriodMs:5e3};var L=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization","enterprise-integration"];function M(){return"3.12.1"}function Ve(r,e){return{version:M(),project:{name:r,root:e,type:"single"},learning:P,routing:_,workers:F,hooks:$,skills:N,autoTuning:O,domains:{enabled:L,disabled:[]},agents:{maxConcurrent:15,defaultTimeout:6e4}}}ve();import{readFileSync as C,existsSync as p,statSync as be,readdirSync as xe}from"fs";import{join as g,basename as re,extname as ie,relative as V}from"path";var Se=[{name:"jest",detect:r=>{let e=["jest.config.js","jest.config.ts","jest.config.mjs","jest.config.cjs"];for(let n of e)if(p(g(r,n)))return{name:"jest",version:A(r,"jest"),configFile:n,confidence:1};let t=S(r);return t?.jest?{name:"jest",version:A(r,"jest"),configFile:"package.json",confidence:.9}:t?.devDependencies?.jest||t?.dependencies?.jest?{name:"jest",version:t.devDependencies?.jest||t.dependencies?.jest,confidence:.7}:null}},{name:"vitest",detect:r=>{let e=["vitest.config.ts","vitest.config.js","vitest.config.mts","vite.config.ts"];for(let n of e)if(p(g(r,n)))return{name:"vitest",version:A(r,"vitest"),configFile:n,confidence:1};let t=S(r);return t?.devDependencies?.vitest||t?.dependencies?.vitest?{name:"vitest",version:t.devDependencies?.vitest,confidence:.8}:null}},{name:"mocha",detect:r=>{let e=[".mocharc.js",".mocharc.json",".mocharc.yaml",".mocharc.yml"];for(let n of e)if(p(g(r,n)))return{name:"mocha",version:A(r,"mocha"),configFile:n,confidence:1};let t=S(r);return t?.devDependencies?.mocha?{name:"mocha",version:t.devDependencies?.mocha,confidence:.8}:null}},{name:"pytest",detect:r=>{let e=["pytest.ini","pyproject.toml","setup.cfg"];for(let n of e){let i=g(r,n);if(p(i))try{let s=C(i,"utf-8");if(s.includes("[pytest]")||s.includes("[tool.pytest]"))return{name:"pytest",configFile:n,confidence:1}}catch(s){console.debug("[ProjectAnalyzer] Config read failed:",s instanceof Error?s.message:s)}}let t=g(r,"requirements.txt");if(p(t))try{if(C(t,"utf-8").includes("pytest"))return{name:"pytest",configFile:"requirements.txt",confidence:.8}}catch(n){console.debug("[ProjectAnalyzer] requirements.txt read failed:",n instanceof Error?n.message:n)}return null}},{name:"playwright",detect:r=>{let e=["playwright.config.ts","playwright.config.js"];for(let n of e)if(p(g(r,n)))return{name:"playwright",version:A(r,"@playwright/test"),configFile:n,confidence:1};let t=S(r);return t?.devDependencies?.["@playwright/test"]?{name:"playwright",version:t.devDependencies["@playwright/test"],confidence:.8}:null}},{name:"cypress",detect:r=>{let e=["cypress.config.ts","cypress.config.js","cypress.json"];for(let t of e)if(p(g(r,t)))return{name:"cypress",version:A(r,"cypress"),configFile:t,confidence:1};return p(g(r,"cypress"))?{name:"cypress",configFile:"cypress/",confidence:.9}:null}}],Ae=[{name:"typescript",extensions:[".ts",".tsx",".mts",".cts"]},{name:"javascript",extensions:[".js",".jsx",".mjs",".cjs"]},{name:"python",extensions:[".py",".pyw"]},{name:"java",extensions:[".java"]},{name:"go",extensions:[".go"]},{name:"rust",extensions:[".rs"]},{name:"csharp",extensions:[".cs"]},{name:"ruby",extensions:[".rb"]},{name:"php",extensions:[".php"]},{name:"kotlin",extensions:[".kt",".kts"]},{name:"swift",extensions:[".swift"]}];function S(r){let e=g(r,"package.json");if(!p(e))return null;try{return E(C(e,"utf-8"))}catch{return null}}function A(r,e){let t=S(r);if(t)return t.devDependencies?.[e]||t.dependencies?.[e]}function Q(r,e,t={}){let{maxDepth:n=10,exclude:i=["node_modules",".git","dist","build","coverage",".next","__pycache__"]}=t;function s(o,a){if(a>n)return;let l;try{l=xe(o)}catch{return}for(let u of l){if(i.includes(u))continue;let c=g(o,u),x;try{x=be(c)}catch{continue}x.isDirectory()?s(c,a+1):x.isFile()&&e(c)}}s(r,0)}var W=class{projectRoot;constructor(e){this.projectRoot=e}async analyze(){let e=Date.now(),[t,n,i,s,o]=await Promise.all([this.detectFrameworks(),this.detectLanguages(),this.detectExistingTests(),this.analyzeComplexity(),this.measureCoverage()]);return{projectName:S(this.projectRoot)?.name||re(this.projectRoot),projectRoot:this.projectRoot,projectType:this.detectProjectType(),frameworks:t,languages:n,existingTests:i,codeComplexity:s,coverage:o,packageManager:this.detectPackageManager(),hasTypeScript:p(g(this.projectRoot,"tsconfig.json")),hasCIConfig:this.detectCIConfig(),ciProvider:this.detectCIProvider(),analysisTimestamp:new Date,analysisDurationMs:Date.now()-e}}async detectFrameworks(){let e=[];for(let t of Se){let n=t.detect(this.projectRoot);n&&e.push(n)}return e.sort((t,n)=>n.confidence-t.confidence)}async detectLanguages(){let e=new Map,t=0;Q(this.projectRoot,i=>{let s=ie(i).toLowerCase();if(s){for(let o of Ae)if(o.extensions.includes(s)){let a=e.get(o.name)||{count:0,extensions:new Set};a.count++,a.extensions.add(s),e.set(o.name,a),t++;break}}});let n=[];for(let[i,s]of e)n.push({name:i,percentage:t>0?Math.round(s.count/t*100):0,fileCount:s.count,extensions:Array.from(s.extensions)});return n.sort((i,s)=>s.fileCount-i.fileCount)}async detectExistingTests(){let e={totalCount:0,byFramework:{},byType:{unit:0,integration:0,e2e:0,unknown:0},directories:[]},t=new Set,n=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/_test\.[jt]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/,/.*Test\.java$/];return Q(this.projectRoot,i=>{let s=re(i);if(n.some(a=>a.test(s))){e.totalCount++;let a=V(this.projectRoot,i).toLowerCase();a.includes("e2e")||a.includes("cypress")||a.includes("playwright")?e.byType.e2e++:a.includes("integration")||a.includes("int-test")?e.byType.integration++:a.includes("unit")||a.includes("__tests__")||a.includes("test/")?e.byType.unit++:e.byType.unknown++;let l=V(this.projectRoot,g(i,".."));t.add(l)}}),e.directories=Array.from(t).slice(0,10),e}async analyzeComplexity(){let e=[],t=[],n=0,i=0;Q(this.projectRoot,a=>{let l=ie(a);if([".ts",".tsx",".js",".jsx",".py",".java",".go"].includes(l))try{let u=C(a,"utf-8"),c=this.calculateFileComplexity(u,l);t.push(...c.functionComplexities),c.maxComplexity>n&&(n=c.maxComplexity),i++,c.maxComplexity>10&&e.push(V(this.projectRoot,a))}catch(u){console.debug("[ProjectAnalyzer] Complexity analysis read failed:",u instanceof Error?u.message:u)}});let s=t.reduce((a,l)=>a+l,0),o=t.length>0?s/t.length:0;return{averageCyclomatic:Math.round(o*10)/10,maxCyclomatic:n,totalFiles:i,complexFiles:e.slice(0,20),recommendation:o<5?"simple":o<15?"medium":"complex"}}calculateFileComplexity(e,t){let n=this.stripCommentsAndStrings(e,t),i=this.calculateComplexity(n);return{functionComplexities:[i],maxComplexity:i}}removeDelimitedBlocks(e,t,n){let i="",s=0;for(;s<e.length;){let o=e.indexOf(t,s);if(o===-1){i+=e.slice(s);break}i+=e.slice(s,o);let a=e.indexOf(n,o+t.length);if(a===-1)break;s=a+n.length}return i}stripCommentsAndStrings(e,t){let n=e;return[".ts",".tsx",".js",".jsx",".java",".go"].includes(t)?(n=n.split(`
3
3
  `).map(i=>{let s=i.indexOf("//");return s>=0?i.slice(0,s):i}).join(`
4
4
  `),n=this.removeDelimitedBlocks(n,"/*","*/"),n=this.removeDelimitedBlocks(n,"`","`"),n=this.removeDelimitedBlocks(n,'"','"'),n=this.removeDelimitedBlocks(n,"'","'")):t===".py"&&(n=n.split(`
5
5
  `).map(i=>{let s=i.indexOf("#");return s>=0?i.slice(0,s):i}).join(`
6
- `),n=this.removeDelimitedBlocks(n,'"""','"""'),n=this.removeDelimitedBlocks(n,"'''","'''"),n=this.removeDelimitedBlocks(n,'"','"'),n=this.removeDelimitedBlocks(n,"'","'")),n}calculateComplexity(e){let t=1,n=[{pattern:/(?<![a-zA-Z])if\s*\(/g,name:"if"},{pattern:/\bfor\s*\(/g,name:"for"},{pattern:/\bwhile\s*\(/g,name:"while"},{pattern:/\bcase\s+[^:]+:/g,name:"case"},{pattern:/\bcatch\s*\(/g,name:"catch"},{pattern:/&&/g,name:"&&"},{pattern:/\|\|/g,name:"||"},{pattern:/\?[^?:]+:/g,name:"ternary"},{pattern:/\belif\s+/g,name:"elif"},{pattern:/\bexcept\s*(?:\w+)?:/g,name:"except"},{pattern:/\bfor\s+\w+\s+in\s+/g,name:"for-in"},{pattern:/\bselect\s*\{/g,name:"select"}];for(let{pattern:i}of n){let s=e.match(i);s&&(t+=s.length)}return t}async measureCoverage(){let e=["coverage/lcov-report/index.html","coverage/coverage-summary.json","coverage/clover.xml","coverage/lcov.info","htmlcov/index.html"];for(let t of e){let n=u(this.projectRoot,t);if(p(n)){if(t.endsWith(".json"))try{let s=E(w(n,"utf-8")).total||{};return{lines:s.lines?.pct||0,branches:s.branches?.pct||0,functions:s.functions?.pct||0,statements:s.statements?.pct||0,hasReport:!0,reportPath:t}}catch(i){console.debug("[ProjectAnalyzer] Coverage report parse failed:",i instanceof Error?i.message:i)}return{lines:0,branches:0,functions:0,statements:0,hasReport:!0,reportPath:t}}}return{lines:0,branches:0,functions:0,statements:0,hasReport:!1}}detectProjectType(){if(p(u(this.projectRoot,"lerna.json"))||p(u(this.projectRoot,"pnpm-workspace.yaml"))||p(u(this.projectRoot,"packages")))return"monorepo";let e=S(this.projectRoot);return e?.workspaces?"monorepo":e?.main||e?.module||e?.exports?"library":"single"}detectPackageManager(){return p(u(this.projectRoot,"bun.lockb"))?"bun":p(u(this.projectRoot,"pnpm-lock.yaml"))?"pnpm":p(u(this.projectRoot,"yarn.lock"))?"yarn":p(u(this.projectRoot,"package-lock.json"))?"npm":"unknown"}detectCIConfig(){return[".github/workflows",".gitlab-ci.yml","Jenkinsfile",".circleci/config.yml",".travis.yml","azure-pipelines.yml"].some(t=>p(u(this.projectRoot,t)))}detectCIProvider(){if(p(u(this.projectRoot,".github/workflows")))return"github-actions";if(p(u(this.projectRoot,".gitlab-ci.yml")))return"gitlab-ci";if(p(u(this.projectRoot,"Jenkinsfile")))return"jenkins";if(p(u(this.projectRoot,".circleci/config.yml")))return"circleci";if(this.detectCIConfig())return"other"}};function Me(r){return new W(r)}var se=[{name:"typescript-vitest",condition:r=>r.hasTypeScript&&r.frameworks.some(e=>e.name==="vitest"),apply:r=>{r.learning.embeddingModel="transformer",r.routing.confidenceThreshold=.75}},{name:"large-codebase",condition:r=>r.codeComplexity.totalFiles>500,apply:r=>{r.learning.hnswConfig.M=32,r.learning.hnswConfig.efConstruction=400,r.learning.hnswConfig.efSearch=200,r.agents.maxConcurrent=15}},{name:"small-project",condition:r=>r.codeComplexity.totalFiles<50,apply:r=>{r.learning.hnswConfig.M=8,r.learning.hnswConfig.efConstruction=100,r.workers.enabled=["pattern-consolidator","routing-accuracy-monitor"],r.workers.maxConcurrent=2,r.agents.maxConcurrent=5}},{name:"high-complexity",condition:r=>r.codeComplexity.recommendation==="complex",apply:r=>{r.autoTuning.parameters.push("complexity.analysisDepth"),r.domains.enabled=L}},{name:"low-coverage",condition:r=>r.coverage.hasReport&&r.coverage.lines<50,apply:r=>{r.workers.enabled.push("coverage-gap-scanner"),r.workers.intervals["coverage-gap-scanner"]=1800*1e3}},{name:"monorepo",condition:r=>r.projectType==="monorepo",apply:r=>{r.agents.maxConcurrent=15,r.workers.maxConcurrent=6,r.domains.enabled=[...new Set([...r.domains.enabled,"code-intelligence"])]}},{name:"has-e2e",condition:r=>r.frameworks.some(e=>["playwright","cypress"].includes(e.name))||r.existingTests.byType.e2e>0,apply:r=>{r.domains.enabled=[...new Set([...r.domains.enabled,"visual-accessibility","chaos-resilience"])]}},{name:"has-ci",condition:r=>r.hasCIConfig,apply:r=>{r.hooks.ciIntegration=!0,r.domains.enabled=[...new Set([...r.domains.enabled,"quality-assessment"])]}},{name:"github-actions",condition:r=>r.ciProvider==="github-actions",apply:r=>{r.hooks.ciIntegration=!0,r.hooks.claudeCode=!0}},{name:"python-project",condition:r=>r.languages.some(e=>e.name==="python"&&e.percentage>30),apply:r=>{r.routing.mode="hybrid",r.domains.enabled=[...new Set([...r.domains.enabled,"security-compliance"])]}},{name:"java-project",condition:r=>r.languages.some(e=>e.name==="java"&&e.percentage>30),apply:r=>{r.agents.defaultTimeout=12e4}},{name:"no-tests",condition:r=>r.existingTests.totalCount===0,apply:r=>{r.workers.enabled=["pattern-consolidator"],r.learning.qualityThreshold=.5,r.learning.promotionThreshold=2}},{name:"many-tests",condition:r=>r.existingTests.totalCount>500,apply:r=>{r.workers.enabled=[...new Set([...r.workers.enabled,"flaky-test-detector"])],r.domains.enabled=[...new Set([...r.domains.enabled,"test-execution"])]}},{name:"security-focus",condition:r=>r.codeComplexity.totalFiles>100,apply:r=>{r.domains.enabled=[...new Set([...r.domains.enabled,"security-compliance"])]}}],z=class{rules;constructor(e={}){this.rules=e.minimal?se.filter(t=>["typescript-vitest","large-codebase","small-project"].includes(t.name)):[...se,...e.customRules||[]]}recommend(e){let t={version:M(),project:{name:e.projectName,root:e.projectRoot,type:e.projectType==="unknown"?"single":e.projectType},learning:this.recommendLearning(e),routing:this.recommendRouting(e),workers:this.recommendWorkers(e),hooks:this.recommendHooks(e),skills:this.recommendSkills(e),autoTuning:this.recommendAutoTuning(e),domains:{enabled:this.recommendDomains(e),disabled:[]},agents:{maxConcurrent:this.recommendMaxAgents(e),defaultTimeout:6e4}},n=[];for(let i of this.rules)i.condition(e)&&(i.apply(t,e),n.push(i.name));return t.domains.enabled=[...new Set(t.domains.enabled)],t.workers.enabled=[...new Set(t.workers.enabled)],t}getApplicableRules(e){return this.rules.filter(t=>t.condition(e)).map(t=>t.name)}recommendLearning(e){let t={...P};return e.codeComplexity.totalFiles>1e3?t.hnswConfig={M:32,efConstruction:400,efSearch:200}:e.codeComplexity.totalFiles<100&&(t.hnswConfig={M:8,efConstruction:100,efSearch:50}),e.languages.some(n=>["typescript","javascript"].includes(n.name))&&(t.embeddingModel="transformer"),t}recommendRouting(e){let t={..._};return e.codeComplexity.recommendation==="simple"?t.mode="rules":e.codeComplexity.recommendation==="complex"?t.mode="ml":t.mode="hybrid",t}recommendWorkers(e){let t={...F},n=new Set(["pattern-consolidator","routing-accuracy-monitor"]);return(!e.coverage.hasReport||e.coverage.lines<70)&&n.add("coverage-gap-scanner"),e.existingTests.totalCount>100&&n.add("flaky-test-detector"),t.enabled=Array.from(n),e.codeComplexity.totalFiles>500?t.maxConcurrent=6:e.codeComplexity.totalFiles<50&&(t.maxConcurrent=2),t}recommendHooks(e){let t={...N};return t.ciIntegration=e.hasCIConfig,t.preCommit=e.existingTests.totalCount>50,t}recommendSkills(e){let t={...$};return t.install=!0,t.installV2=!0,t.installV3=!0,t}recommendAutoTuning(e){let t={...O};return e.codeComplexity.totalFiles<20&&(t.enabled=!1),t}recommendDomains(e){return["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization"]}recommendMaxAgents(e){return e.projectType==="monorepo"?15:e.codeComplexity.totalFiles>500?12:e.codeComplexity.totalFiles>100?8:5}};function We(r){return new z(r)}var xe=[/\baqe\b/i,/\bagentic-qe\b/i,/\bnpx\s+agentic-qe\b/i,/\bnpx\s+@anthropics\/agentic-qe\b/i,/brain-checkpoint\.cjs/i,/\.claude\/helpers\//i,/\bruflo\b/i,/dist\/cli\/bundle\.js/i];function Se(r){let e=r;return!e?.hooks||!Array.isArray(e.hooks)?!1:e.hooks.some(t=>!t.command||typeof t.command!="string"?!1:xe.some(n=>n.test(t.command)))}function Ge(r,e){let t={};for(let[n,i]of Object.entries(e)){let s=r[n]||[],o=Array.isArray(s)?s.filter(a=>!Se(a)):[];t[n]=[...i,...o]}for(let[n,i]of Object.entries(r))t[n]||(t[n]=i);return t}function Ue(r){let e=r.domains?.enabled||[];return{AQE_MEMORY_PATH:".agentic-qe/memory.db",AQE_MEMORY_ENABLED:"true",AQE_LEARNING_ENABLED:r.learning?.enabled?"true":"false",AQE_V3_MODE:"true",AQE_V3_DDD_ENABLED:"true",AQE_V3_DOMAINS:e.join(","),AQE_V3_SWARM_SIZE:String(r.agents?.maxConcurrent??15),AQE_V3_TOPOLOGY:"hierarchical",AQE_V3_SUBLINEAR_ENABLED:"true",AQE_V3_HNSW_ENABLED:r.learning?.hnswConfig?"true":"false",AQE_V3_HOOKS_ENABLED:"true",AQE_V3_AISP_ENABLED:"true",AQE_V3_REASONING_BANK:".agentic-qe/memory.db",AQE_V3_PATTERN_PROMOTION_THRESHOLD:String(r.learning?.promotionThreshold??3),AQE_V3_SUCCESS_RATE_THRESHOLD:String(r.learning?.qualityThreshold??.7)}}function He(r,e){let t=r.domains?.enabled||[];return{aqe:{version:r.version??"3.0.0",initialized:new Date().toISOString(),hooksConfigured:!0},statusLine:{type:"command",command:`sh -c 'node "\${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/statusline-v3.cjs" 2>/dev/null || echo "\u258A Agentic QE v3"'`,refreshMs:5e3,enabled:!0},_aqePermissions:["Bash(npx agentic-qe:*)","Bash(npx @anthropics/agentic-qe:*)","mcp__agentic-qe__*"],includeCoAuthoredBy:!0,v3Configuration:{domains:{total:t.length,names:t},swarm:{totalAgents:r.agents?.maxConcurrent??15,topology:"hierarchical",coordination:"queen-led"}},v3Learning:{enabled:r.learning?.enabled??!0,reasoningBank:{dbPath:".agentic-qe/memory.db",enableHNSW:!!r.learning?.hnswConfig},patternPromotion:{threshold:r.learning?.promotionThreshold??3,successRateMin:r.learning?.qualityThreshold??.7}}}}T();import{existsSync as h,mkdirSync as j,readdirSync as R,statSync as G,readFileSync as Ae,writeFileSync as Ce,copyFileSync as we,unlinkSync as De,rmdirSync as je}from"fs";import{join as m}from"path";var U=["qe-test-generation","qe-test-execution","qe-coverage-analysis","qe-quality-assessment","qe-defect-intelligence","qe-requirements-validation","qe-code-intelligence","qe-browser","pentest-validation","qe-visual-accessibility","qe-chaos-resilience","qe-learning-optimization","qe-iterative-loop","strict-tdd","no-skip","coverage-guard","freeze-tests","security-watch","skill-stats","test-failure-investigator","coverage-drop-investigator","e2e-flow-verifier","test-metrics-dashboard"],H=["v3-core-implementation","v3-cli-modernization","v3-ddd-architecture","v3-integration-deep","v3-mcp-optimization","v3-memory-unification","v3-performance-optimization","v3-security-overhaul","v3-swarm-coordination","v3-qe-core-implementation","v3-qe-ddd-architecture","v3-qe-cli","v3-qe-memory-system","v3-qe-performance","v3-qe-security","v3-qe-mcp","v3-qe-mcp-optimization","v3-qe-memory-unification","v3-qe-integration","v3-qe-agentic-flow-integration","v3-qe-fleet-coordination","agentdb-advanced","agentdb-learning","agentdb-memory-patterns","agentdb-optimization","agentdb-vector-search","github-code-review","github-multi-repo","github-project-management","github-release-management","github-workflow-automation","flow-nexus-neural","flow-nexus-platform","flow-nexus-swarm","reasoningbank-agentdb","reasoningbank-intelligence","swarm-orchestration","swarm-advanced","sparc-methodology","hooks-automation","hive-mind-advanced","stream-chain","agentic-jujutsu","iterative-loop","performance-analysis","skill-builder","qe-agentic-flow-integration","release"],Re=["qe-contract-testing","qe-security-compliance","aqe-v2-v3-migration"],B=class{projectRoot;options;sourceSkillsDir;constructor(e){this.projectRoot=e.projectRoot,this.options={installV2Skills:!0,installV3Skills:!0,overwrite:!1,exclude:[],include:void 0,...e},this.sourceSkillsDir=this.findSourceSkillsDir()}findSourceSkillsDir(){let e=k(import.meta.url),t=[];e&&(t.push(m(e,"assets/skills")),t.push(m(e,".claude/skills"))),t.push(m(this.projectRoot,"node_modules/agentic-qe/assets/skills"));for(let n of t)if(h(n))return n;return t[0]}async install(){let e={installed:[],skipped:[],removed:[],errors:[],totalCount:0,skillsDir:m(this.projectRoot,".claude","skills"),validationInstalled:!1};if(!h(this.sourceSkillsDir))return e.errors.push(`Source skills directory not found: ${this.sourceSkillsDir}`),e;let t=m(this.projectRoot,".claude","skills");h(t)||j(t,{recursive:!0});let n=this.getAvailableSkills();e.totalCount=n.length;let i=this.filterSkills(n);for(let s of i)try{let o=await this.installSkill(s,t);o?e.installed.push(o):e.skipped.push(s)}catch(o){e.errors.push(`Failed to install ${s}: ${b(o)}`)}return this.options.overwrite&&(e.removed=this.removeDeprecatedSkills(t)),e.validationInstalled=this.installValidationInfrastructure(t),await this.createSkillsIndex(t,e.installed),e}installValidationInfrastructure(e){let t=m(this.sourceSkillsDir,".validation"),n=m(e,".validation");if(!h(t))return console.debug("[SkillsInstaller] Validation infrastructure not found in source"),!1;if(h(n)&&!this.options.overwrite)return console.debug("[SkillsInstaller] Validation infrastructure already exists, skipping"),!0;try{return h(n)||j(n,{recursive:!0}),this.copyDirectoryRecursive(t,n),console.debug("[SkillsInstaller] Validation infrastructure installed successfully"),!0}catch(i){return console.error("[SkillsInstaller] Failed to install validation infrastructure:",i instanceof Error?i.message:i),!1}}removeDeprecatedSkills(e){let t=[];for(let n of Re){let i=m(e,n);if(h(i))try{this.removeDirectoryRecursive(i),t.push(n)}catch(s){console.error(`[SkillsInstaller] Failed to remove deprecated skill ${n}:`,s instanceof Error?s.message:s)}}return t.length>0&&console.debug(`[SkillsInstaller] Removed ${t.length} deprecated skills: ${t.join(", ")}`),t}removeDirectoryRecursive(e){let t=R(e,{withFileTypes:!0});for(let n of t){let i=m(e,n.name);n.isDirectory()?this.removeDirectoryRecursive(i):De(i)}je(e)}getAvailableSkills(){try{return R(this.sourceSkillsDir).filter(t=>{let n=m(this.sourceSkillsDir,t);return G(n).isDirectory()&&!t.startsWith(".")})}catch{return[]}}filterSkills(e){let t=e;return t=t.filter(n=>!H.includes(n)),this.options.include&&this.options.include.length>0&&(t=t.filter(n=>this.options.include.includes(n))),this.options.exclude&&this.options.exclude.length>0&&(t=t.filter(n=>!this.options.exclude.some(i=>n.includes(i)||n.match(new RegExp(i))))),this.options.installV3Skills||(t=t.filter(n=>!U.includes(n))),this.options.installV2Skills||(t=t.filter(n=>U.includes(n))),t}async installSkill(e,t){let n=m(this.sourceSkillsDir,e),i=m(t,e);if(h(i)&&!this.options.overwrite)return null;h(i)||j(i,{recursive:!0}),this.copyDirectoryRecursive(n,i);let s=this.getSkillType(e),o=this.getSkillDescription(i),a=h(m(i,"resources"));return{name:e,type:s,description:o,hasResources:a}}copyDirectoryRecursive(e,t){let n=R(e);for(let i of n){let s=m(e,i),o=m(t,i);G(s).isDirectory()?(h(o)||j(o,{recursive:!0}),this.copyDirectoryRecursive(s,o)):we(s,o)}}getSkillType(e){return U.includes(e)?"v3-domain":"v2-methodology"}getSkillDescription(e){let t=m(e,"SKILL.md");if(h(t))try{let n=Ae(t,"utf-8"),i=n.match(/description:\s*["']?([^"'\n]+)["']?/i);if(i)return i[1].trim();let s=n.split(`
7
- `);for(let o of s){let a=o.trim();if(a&&!a.startsWith("#")&&!a.startsWith("-")&&!a.startsWith("```"))return a.slice(0,100)+(a.length>100?"...":"")}}catch(n){console.debug("[SkillsInstaller] Failed to read skill description:",n instanceof Error?n.message:n)}}async createSkillsIndex(e,t){let n=this.scanSkillsDirectory(e),i=n.filter(c=>!H.includes(c.name)),s=i.filter(c=>c.type==="v2-methodology"),o=i.filter(c=>c.type==="v3-domain"),a=n.filter(c=>H.includes(c.name)),l=h(m(e,".validation")),g=`# AQE Skills Index
6
+ `),n=this.removeDelimitedBlocks(n,'"""','"""'),n=this.removeDelimitedBlocks(n,"'''","'''"),n=this.removeDelimitedBlocks(n,'"','"'),n=this.removeDelimitedBlocks(n,"'","'")),n}calculateComplexity(e){let t=1,n=[{pattern:/(?<![a-zA-Z])if\s*\(/g,name:"if"},{pattern:/\bfor\s*\(/g,name:"for"},{pattern:/\bwhile\s*\(/g,name:"while"},{pattern:/\bcase\s+[^:]+:/g,name:"case"},{pattern:/\bcatch\s*\(/g,name:"catch"},{pattern:/&&/g,name:"&&"},{pattern:/\|\|/g,name:"||"},{pattern:/\?[^?:]+:/g,name:"ternary"},{pattern:/\belif\s+/g,name:"elif"},{pattern:/\bexcept\s*(?:\w+)?:/g,name:"except"},{pattern:/\bfor\s+\w+\s+in\s+/g,name:"for-in"},{pattern:/\bselect\s*\{/g,name:"select"}];for(let{pattern:i}of n){let s=e.match(i);s&&(t+=s.length)}return t}async measureCoverage(){let e=["coverage/lcov-report/index.html","coverage/coverage-summary.json","coverage/clover.xml","coverage/lcov.info","htmlcov/index.html"];for(let t of e){let n=g(this.projectRoot,t);if(p(n)){if(t.endsWith(".json"))try{let s=E(C(n,"utf-8")).total||{};return{lines:s.lines?.pct||0,branches:s.branches?.pct||0,functions:s.functions?.pct||0,statements:s.statements?.pct||0,hasReport:!0,reportPath:t}}catch(i){console.debug("[ProjectAnalyzer] Coverage report parse failed:",i instanceof Error?i.message:i)}return{lines:0,branches:0,functions:0,statements:0,hasReport:!0,reportPath:t}}}return{lines:0,branches:0,functions:0,statements:0,hasReport:!1}}detectProjectType(){if(p(g(this.projectRoot,"lerna.json"))||p(g(this.projectRoot,"pnpm-workspace.yaml"))||p(g(this.projectRoot,"packages")))return"monorepo";let e=S(this.projectRoot);return e?.workspaces?"monorepo":e?.main||e?.module||e?.exports?"library":"single"}detectPackageManager(){return p(g(this.projectRoot,"bun.lockb"))?"bun":p(g(this.projectRoot,"pnpm-lock.yaml"))?"pnpm":p(g(this.projectRoot,"yarn.lock"))?"yarn":p(g(this.projectRoot,"package-lock.json"))?"npm":"unknown"}detectCIConfig(){return[".github/workflows",".gitlab-ci.yml","Jenkinsfile",".circleci/config.yml",".travis.yml","azure-pipelines.yml"].some(t=>p(g(this.projectRoot,t)))}detectCIProvider(){if(p(g(this.projectRoot,".github/workflows")))return"github-actions";if(p(g(this.projectRoot,".gitlab-ci.yml")))return"gitlab-ci";if(p(g(this.projectRoot,"Jenkinsfile")))return"jenkins";if(p(g(this.projectRoot,".circleci/config.yml")))return"circleci";if(this.detectCIConfig())return"other"}};function Ue(r){return new W(r)}var se=[{name:"typescript-vitest",condition:r=>r.hasTypeScript&&r.frameworks.some(e=>e.name==="vitest"),apply:r=>{r.learning.embeddingModel="transformer",r.routing.confidenceThreshold=.75}},{name:"large-codebase",condition:r=>r.codeComplexity.totalFiles>500,apply:r=>{r.learning.hnswConfig.M=32,r.learning.hnswConfig.efConstruction=400,r.learning.hnswConfig.efSearch=200,r.agents.maxConcurrent=15}},{name:"small-project",condition:r=>r.codeComplexity.totalFiles<50,apply:r=>{r.learning.hnswConfig.M=8,r.learning.hnswConfig.efConstruction=100,r.workers.enabled=["pattern-consolidator","routing-accuracy-monitor"],r.workers.maxConcurrent=2,r.agents.maxConcurrent=5}},{name:"high-complexity",condition:r=>r.codeComplexity.recommendation==="complex",apply:r=>{r.autoTuning.parameters.push("complexity.analysisDepth"),r.domains.enabled=L}},{name:"low-coverage",condition:r=>r.coverage.hasReport&&r.coverage.lines<50,apply:r=>{r.workers.enabled.push("coverage-gap-scanner"),r.workers.intervals["coverage-gap-scanner"]=1800*1e3}},{name:"monorepo",condition:r=>r.projectType==="monorepo",apply:r=>{r.agents.maxConcurrent=15,r.workers.maxConcurrent=6,r.domains.enabled=[...new Set([...r.domains.enabled,"code-intelligence"])]}},{name:"has-e2e",condition:r=>r.frameworks.some(e=>["playwright","cypress"].includes(e.name))||r.existingTests.byType.e2e>0,apply:r=>{r.domains.enabled=[...new Set([...r.domains.enabled,"visual-accessibility","chaos-resilience"])]}},{name:"has-ci",condition:r=>r.hasCIConfig,apply:r=>{r.hooks.ciIntegration=!0,r.domains.enabled=[...new Set([...r.domains.enabled,"quality-assessment"])]}},{name:"github-actions",condition:r=>r.ciProvider==="github-actions",apply:r=>{r.hooks.ciIntegration=!0,r.hooks.claudeCode=!0}},{name:"python-project",condition:r=>r.languages.some(e=>e.name==="python"&&e.percentage>30),apply:r=>{r.routing.mode="hybrid",r.domains.enabled=[...new Set([...r.domains.enabled,"security-compliance"])]}},{name:"java-project",condition:r=>r.languages.some(e=>e.name==="java"&&e.percentage>30),apply:r=>{r.agents.defaultTimeout=12e4}},{name:"no-tests",condition:r=>r.existingTests.totalCount===0,apply:r=>{r.workers.enabled=["pattern-consolidator"],r.learning.qualityThreshold=.5,r.learning.promotionThreshold=2}},{name:"many-tests",condition:r=>r.existingTests.totalCount>500,apply:r=>{r.workers.enabled=[...new Set([...r.workers.enabled,"flaky-test-detector"])],r.domains.enabled=[...new Set([...r.domains.enabled,"test-execution"])]}},{name:"security-focus",condition:r=>r.codeComplexity.totalFiles>100,apply:r=>{r.domains.enabled=[...new Set([...r.domains.enabled,"security-compliance"])]}}],z=class{rules;constructor(e={}){this.rules=e.minimal?se.filter(t=>["typescript-vitest","large-codebase","small-project"].includes(t.name)):[...se,...e.customRules||[]]}recommend(e){let t={version:M(),project:{name:e.projectName,root:e.projectRoot,type:e.projectType==="unknown"?"single":e.projectType},learning:this.recommendLearning(e),routing:this.recommendRouting(e),workers:this.recommendWorkers(e),hooks:this.recommendHooks(e),skills:this.recommendSkills(e),autoTuning:this.recommendAutoTuning(e),domains:{enabled:this.recommendDomains(e),disabled:[]},agents:{maxConcurrent:this.recommendMaxAgents(e),defaultTimeout:6e4}},n=[];for(let i of this.rules)i.condition(e)&&(i.apply(t,e),n.push(i.name));return t.domains.enabled=[...new Set(t.domains.enabled)],t.workers.enabled=[...new Set(t.workers.enabled)],t}getApplicableRules(e){return this.rules.filter(t=>t.condition(e)).map(t=>t.name)}recommendLearning(e){let t={...P};return e.codeComplexity.totalFiles>1e3?t.hnswConfig={M:32,efConstruction:400,efSearch:200}:e.codeComplexity.totalFiles<100&&(t.hnswConfig={M:8,efConstruction:100,efSearch:50}),e.languages.some(n=>["typescript","javascript"].includes(n.name))&&(t.embeddingModel="transformer"),t}recommendRouting(e){let t={..._};return e.codeComplexity.recommendation==="simple"?t.mode="rules":e.codeComplexity.recommendation==="complex"?t.mode="ml":t.mode="hybrid",t}recommendWorkers(e){let t={...F},n=new Set(["pattern-consolidator","routing-accuracy-monitor"]);return(!e.coverage.hasReport||e.coverage.lines<70)&&n.add("coverage-gap-scanner"),e.existingTests.totalCount>100&&n.add("flaky-test-detector"),t.enabled=Array.from(n),e.codeComplexity.totalFiles>500?t.maxConcurrent=6:e.codeComplexity.totalFiles<50&&(t.maxConcurrent=2),t}recommendHooks(e){let t={...$};return t.ciIntegration=e.hasCIConfig,t.preCommit=e.existingTests.totalCount>50,t}recommendSkills(e){let t={...N};return t.install=!0,t.installV2=!0,t.installV3=!0,t}recommendAutoTuning(e){let t={...O};return e.codeComplexity.totalFiles<20&&(t.enabled=!1),t}recommendDomains(e){return["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization"]}recommendMaxAgents(e){return e.projectType==="monorepo"?15:e.codeComplexity.totalFiles>500?12:e.codeComplexity.totalFiles>100?8:5}};function Ke(r){return new z(r)}import{existsSync as oe,readFileSync as we,writeFileSync as Ce}from"fs";function Ze(r){if(!oe(r))return null;let e=`${r}.backup`;if(oe(e))return null;try{return Ce(e,we(r,"utf-8"),"utf-8"),e}catch{return null}}var De=[/\baqe\b/i,/\bagentic-qe\b/i,/\bnpx\s+agentic-qe\b/i,/\bnpx\s+@anthropics\/agentic-qe\b/i,/aqe-hook\.cjs/i,/brain-checkpoint\.cjs/i,/statusline-v3\.cjs/i];function je(r){let e=r;return!e?.hooks||!Array.isArray(e.hooks)?!1:e.hooks.some(t=>!t.command||typeof t.command!="string"?!1:De.some(n=>n.test(t.command)))}function Xe(r,e){let t={};for(let[n,i]of Object.entries(e)){let s=r[n]||[],o=Array.isArray(s)?s.filter(a=>!je(a)):[];t[n]=[...i,...o]}for(let[n,i]of Object.entries(r))t[n]||(t[n]=i);return t}function et(r,e){return{...e,...r||{}}}function tt(r){let e=r.domains?.enabled||[];return{AQE_MEMORY_PATH:".agentic-qe/memory.db",AQE_MEMORY_ENABLED:"true",AQE_LEARNING_ENABLED:r.learning?.enabled?"true":"false",AQE_V3_MODE:"true",AQE_V3_DDD_ENABLED:"true",AQE_V3_DOMAINS:e.join(","),AQE_V3_SWARM_SIZE:String(r.agents?.maxConcurrent??15),AQE_V3_TOPOLOGY:"hierarchical",AQE_V3_SUBLINEAR_ENABLED:"true",AQE_V3_HNSW_ENABLED:r.learning?.hnswConfig?"true":"false",AQE_V3_HOOKS_ENABLED:"true",AQE_V3_AISP_ENABLED:"true",AQE_V3_REASONING_BANK:".agentic-qe/memory.db",AQE_V3_PATTERN_PROMOTION_THRESHOLD:String(r.learning?.promotionThreshold??3),AQE_V3_SUCCESS_RATE_THRESHOLD:String(r.learning?.qualityThreshold??.7)}}function Re(r){let e=r?.command;return typeof e=="string"&&/statusline-v3\.cjs|Agentic QE v3/.test(e)}function le(r,e){if(!ae(r)||!ae(e))return e;let t={...r};for(let[n,i]of Object.entries(e))t[n]=le(t[n],i);return t}function ae(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function nt(r,e){for(let[t,n]of Object.entries(e))if(t==="_aqePermissions"){let i=r.permissions||{},s=i.allow||[],o=[...new Set([...s,...n])];r.permissions={...i,allow:o}}else t==="statusLine"?(r.statusLine===void 0||Re(r.statusLine))&&(r.statusLine=n):t==="includeCoAuthoredBy"?r.includeCoAuthoredBy===void 0&&(r.includeCoAuthoredBy=n):r[t]=le(r[t],n);return r}function rt(r,e){let t=r.domains?.enabled||[];return{aqe:{version:r.version??"3.0.0",initialized:new Date().toISOString(),hooksConfigured:!0},statusLine:{type:"command",command:`sh -c 'node "\${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/statusline-v3.cjs" 2>/dev/null || echo "\u258A Agentic QE v3"'`,refreshMs:5e3,enabled:!0},_aqePermissions:["Bash(npx agentic-qe:*)","Bash(npx @anthropics/agentic-qe:*)","mcp__agentic-qe__*"],includeCoAuthoredBy:!0,v3Configuration:{domains:{total:t.length,names:t},swarm:{totalAgents:r.agents?.maxConcurrent??15,topology:"hierarchical",coordination:"queen-led"}},v3Learning:{enabled:r.learning?.enabled??!0,reasoningBank:{dbPath:".agentic-qe/memory.db",enableHNSW:!!r.learning?.hnswConfig},patternPromotion:{threshold:r.learning?.promotionThreshold??3,successRateMin:r.learning?.qualityThreshold??.7}}}}T();import{existsSync as h,mkdirSync as j,readdirSync as R,statSync as G,readFileSync as Ie,writeFileSync as qe,copyFileSync as Te,unlinkSync as Ee,rmdirSync as Pe}from"fs";import{join as m}from"path";var U=["qe-test-generation","qe-test-execution","qe-coverage-analysis","qe-quality-assessment","qe-defect-intelligence","qe-requirements-validation","qe-code-intelligence","qe-browser","pentest-validation","qe-visual-accessibility","qe-chaos-resilience","qe-learning-optimization","qe-iterative-loop","strict-tdd","no-skip","coverage-guard","freeze-tests","security-watch","skill-stats","test-failure-investigator","coverage-drop-investigator","e2e-flow-verifier","test-metrics-dashboard"],H=["v3-core-implementation","v3-cli-modernization","v3-ddd-architecture","v3-integration-deep","v3-mcp-optimization","v3-memory-unification","v3-performance-optimization","v3-security-overhaul","v3-swarm-coordination","v3-qe-core-implementation","v3-qe-ddd-architecture","v3-qe-cli","v3-qe-memory-system","v3-qe-performance","v3-qe-security","v3-qe-mcp","v3-qe-mcp-optimization","v3-qe-memory-unification","v3-qe-integration","v3-qe-agentic-flow-integration","v3-qe-fleet-coordination","agentdb-advanced","agentdb-learning","agentdb-memory-patterns","agentdb-optimization","agentdb-vector-search","github-code-review","github-multi-repo","github-project-management","github-release-management","github-workflow-automation","flow-nexus-neural","flow-nexus-platform","flow-nexus-swarm","reasoningbank-agentdb","reasoningbank-intelligence","swarm-orchestration","swarm-advanced","sparc-methodology","hooks-automation","hive-mind-advanced","stream-chain","agentic-jujutsu","iterative-loop","performance-analysis","skill-builder","qe-agentic-flow-integration","release"],_e=["qe-contract-testing","qe-security-compliance","aqe-v2-v3-migration"],B=class{projectRoot;options;sourceSkillsDir;constructor(e){this.projectRoot=e.projectRoot,this.options={installV2Skills:!0,installV3Skills:!0,overwrite:!1,exclude:[],include:void 0,...e},this.sourceSkillsDir=this.findSourceSkillsDir()}findSourceSkillsDir(){let e=b(import.meta.url),t=[];e&&(t.push(m(e,"assets/skills")),t.push(m(e,".claude/skills"))),t.push(m(this.projectRoot,"node_modules/agentic-qe/assets/skills"));for(let n of t)if(h(n))return n;return t[0]}async install(){let e={installed:[],skipped:[],removed:[],errors:[],totalCount:0,skillsDir:m(this.projectRoot,".claude","skills"),validationInstalled:!1};if(!h(this.sourceSkillsDir))return e.errors.push(`Source skills directory not found: ${this.sourceSkillsDir}`),e;let t=m(this.projectRoot,".claude","skills");h(t)||j(t,{recursive:!0});let n=this.getAvailableSkills();e.totalCount=n.length;let i=this.filterSkills(n);for(let s of i)try{let o=await this.installSkill(s,t);o?e.installed.push(o):e.skipped.push(s)}catch(o){e.errors.push(`Failed to install ${s}: ${k(o)}`)}return this.options.overwrite&&(e.removed=this.removeDeprecatedSkills(t)),e.validationInstalled=this.installValidationInfrastructure(t),await this.createSkillsIndex(t,e.installed),e}installValidationInfrastructure(e){let t=m(this.sourceSkillsDir,".validation"),n=m(e,".validation");if(!h(t))return console.debug("[SkillsInstaller] Validation infrastructure not found in source"),!1;if(h(n)&&!this.options.overwrite)return console.debug("[SkillsInstaller] Validation infrastructure already exists, skipping"),!0;try{return h(n)||j(n,{recursive:!0}),this.copyDirectoryRecursive(t,n),console.debug("[SkillsInstaller] Validation infrastructure installed successfully"),!0}catch(i){return console.error("[SkillsInstaller] Failed to install validation infrastructure:",i instanceof Error?i.message:i),!1}}removeDeprecatedSkills(e){let t=[];for(let n of _e){let i=m(e,n);if(h(i))try{this.removeDirectoryRecursive(i),t.push(n)}catch(s){console.error(`[SkillsInstaller] Failed to remove deprecated skill ${n}:`,s instanceof Error?s.message:s)}}return t.length>0&&console.debug(`[SkillsInstaller] Removed ${t.length} deprecated skills: ${t.join(", ")}`),t}removeDirectoryRecursive(e){let t=R(e,{withFileTypes:!0});for(let n of t){let i=m(e,n.name);n.isDirectory()?this.removeDirectoryRecursive(i):Ee(i)}Pe(e)}getAvailableSkills(){try{return R(this.sourceSkillsDir).filter(t=>{let n=m(this.sourceSkillsDir,t);return G(n).isDirectory()&&!t.startsWith(".")})}catch{return[]}}filterSkills(e){let t=e;return t=t.filter(n=>!H.includes(n)),this.options.include&&this.options.include.length>0&&(t=t.filter(n=>this.options.include.includes(n))),this.options.exclude&&this.options.exclude.length>0&&(t=t.filter(n=>!this.options.exclude.some(i=>n.includes(i)||n.match(new RegExp(i))))),this.options.installV3Skills||(t=t.filter(n=>!U.includes(n))),this.options.installV2Skills||(t=t.filter(n=>U.includes(n))),t}async installSkill(e,t){let n=m(this.sourceSkillsDir,e),i=m(t,e);if(h(i)&&!this.options.overwrite)return null;h(i)||j(i,{recursive:!0}),this.copyDirectoryRecursive(n,i);let s=this.getSkillType(e),o=this.getSkillDescription(i),a=h(m(i,"resources"));return{name:e,type:s,description:o,hasResources:a}}copyDirectoryRecursive(e,t){let n=R(e);for(let i of n){let s=m(e,i),o=m(t,i);G(s).isDirectory()?(h(o)||j(o,{recursive:!0}),this.copyDirectoryRecursive(s,o)):Te(s,o)}}getSkillType(e){return U.includes(e)?"v3-domain":"v2-methodology"}getSkillDescription(e){let t=m(e,"SKILL.md");if(h(t))try{let n=Ie(t,"utf-8"),i=n.match(/description:\s*["']?([^"'\n]+)["']?/i);if(i)return i[1].trim();let s=n.split(`
7
+ `);for(let o of s){let a=o.trim();if(a&&!a.startsWith("#")&&!a.startsWith("-")&&!a.startsWith("```"))return a.slice(0,100)+(a.length>100?"...":"")}}catch(n){console.debug("[SkillsInstaller] Failed to read skill description:",n instanceof Error?n.message:n)}}async createSkillsIndex(e,t){let n=this.scanSkillsDirectory(e),i=n.filter(c=>!H.includes(c.name)),s=i.filter(c=>c.type==="v2-methodology"),o=i.filter(c=>c.type==="v3-domain"),a=n.filter(c=>H.includes(c.name)),l=h(m(e,".validation")),u=`# AQE Skills Index
8
8
 
9
9
  This directory contains Quality Engineering skills managed by Agentic QE.
10
10
 
@@ -54,12 +54,12 @@ See \`.validation/README.md\` for usage instructions.
54
54
  ---
55
55
 
56
56
  *Generated by AQE v3 init on ${new Date().toISOString()}*
57
- `;Ce(m(e,"README.md"),g,"utf-8")}scanSkillsDirectory(e){let t=[];try{let n=R(e);for(let i of n){if(i.startsWith("."))continue;let s=m(e,i);if(!G(s).isDirectory())continue;let o=m(s,"SKILL.md");if(!h(o))continue;let a=this.getSkillType(i),l=this.getSkillDescription(s),g=h(m(s,"resources"));t.push({name:i,type:a,description:l,hasResources:g})}}catch(n){console.debug("[SkillsInstaller] Failed to scan skills directory:",n instanceof Error?n.message:n)}return t.sort((n,i)=>n.name.localeCompare(i.name))}};function Xe(r){return new B(r)}T();import{existsSync as f,mkdirSync as D,readdirSync as K,statSync as oe,readFileSync as ae,writeFileSync as le,copyFileSync as J}from"fs";import{join as d}from"path";function Ie(r){let e=new Date().toISOString().slice(0,10),t=r.match(/^---\n([\s\S]*?)\n---/);if(!t)return r;let n=t[1],i;return/^updated:/m.test(n)?i=n.replace(/^updated:.*$/m,`updated: ${e}`):/^created:/m.test(n)?i=n.replace(/^(created:.*$)/m,`$1
57
+ `;qe(m(e,"README.md"),u,"utf-8")}scanSkillsDirectory(e){let t=[];try{let n=R(e);for(let i of n){if(i.startsWith("."))continue;let s=m(e,i);if(!G(s).isDirectory())continue;let o=m(s,"SKILL.md");if(!h(o))continue;let a=this.getSkillType(i),l=this.getSkillDescription(s),u=h(m(s,"resources"));t.push({name:i,type:a,description:l,hasResources:u})}}catch(n){console.debug("[SkillsInstaller] Failed to scan skills directory:",n instanceof Error?n.message:n)}return t.sort((n,i)=>n.name.localeCompare(i.name))}};function ct(r){return new B(r)}T();import{existsSync as f,mkdirSync as D,readdirSync as K,statSync as ce,readFileSync as ue,writeFileSync as ge,copyFileSync as J}from"fs";import{join as d}from"path";function Fe(r){let e=new Date().toISOString().slice(0,10),t=r.match(/^---\n([\s\S]*?)\n---/);if(!t)return r;let n=t[1],i;return/^updated:/m.test(n)?i=n.replace(/^updated:.*$/m,`updated: ${e}`):/^created:/m.test(n)?i=n.replace(/^(created:.*$)/m,`$1
58
58
  updated: ${e}`):i=n+`
59
59
  updated: ${e}`,r.replace(/^---\n[\s\S]*?\n---/,`---
60
60
  ${i}
61
- ---`)}var qe=["qe-test-architect","qe-bdd-generator","qe-property-tester","qe-mutation-tester","qe-test-idea-rewriter","qe-quality-criteria-recommender","qe-parallel-executor","qe-flaky-hunter","qe-retry-handler","qe-coverage-specialist","qe-gap-detector","qe-quality-gate","qe-code-complexity","qe-deployment-advisor","qe-risk-assessor","qe-defect-predictor","qe-regression-analyzer","qe-root-cause-analyzer","qe-impact-analyzer","qe-requirements-validator","qe-qx-partner","qe-product-factors-assessor","qe-code-intelligence","qe-kg-builder","qe-dependency-mapper","qe-security-scanner","qe-security-auditor","qe-pentest-validator","qe-contract-validator","qe-graphql-tester","qe-visual-tester","qe-accessibility-auditor","qe-responsive-tester","qe-chaos-engineer","qe-load-tester","qe-performance-tester","qe-learning-coordinator","qe-pattern-learner","qe-metrics-optimizer","qe-transfer-specialist","qe-soap-tester","qe-sap-rfc-tester","qe-sap-idoc-tester","qe-odata-contract-tester","qe-middleware-validator","qe-message-broker-tester","qe-sod-analyzer","qe-fleet-commander","qe-queen-coordinator","qe-tdd-specialist","qe-integration-tester","qe-integration-architect"],Te=["qe-code-reviewer","qe-integration-reviewer","qe-performance-reviewer","qe-security-reviewer","qe-tdd-red","qe-tdd-green","qe-tdd-refactor"],Y=class{projectRoot;options;sourceAgentsDir;constructor(e){this.projectRoot=e.projectRoot,this.options={installQEAgents:!0,installSubagents:!0,overwrite:!1,exclude:[],include:void 0,...e},this.sourceAgentsDir=this.findSourceAgentsDir()}findSourceAgentsDir(){let e=k(import.meta.url),t=[];e&&(t.push(d(e,"assets/agents/v3")),t.push(d(e,".claude/agents/v3"))),t.push(d(this.projectRoot,"node_modules/agentic-qe/assets/agents/v3"));for(let n of t)if(f(n))return n;return t[0]}preserveOverridesDir(){let e=d(this.projectRoot,".claude","agent-overrides");f(e)||D(e,{recursive:!0});let t=d(e,"_example.yaml");if(!f(t))try{let n=k(import.meta.url),i=[...n?[d(n,"assets","templates","agent-override-example.yaml")]:[],d(this.projectRoot,"node_modules","agentic-qe","assets","templates","agent-override-example.yaml")];for(let s of i)if(f(s)){J(s,t);break}}catch{}}async install(){let e={installed:[],skipped:[],errors:[],totalCount:0,agentsDir:d(this.projectRoot,".claude","agents","v3"),overlaysApplied:[],overlayWarnings:[]};if(this.preserveOverridesDir(),!f(this.sourceAgentsDir))return e.errors.push(`Source agents directory not found: ${this.sourceAgentsDir}`),e;let t=d(this.projectRoot,".claude","agents","v3");f(t)||D(t,{recursive:!0});let n=d(t,"subagents");f(n)||D(n,{recursive:!0}),await this.copyHelpersDirectory(t),await this.copyTemplatesDirectory(t);let i=this.getAvailableAgents();e.totalCount=i.length;let s=this.filterAgents(i);for(let l of s)try{let g=await this.installAgent(l,t,n);g?e.installed.push(g):e.skipped.push(l)}catch(g){e.errors.push(`Failed to install ${l}: ${b(g)}`)}let o=te(this.projectRoot);if(o.warnings.length>0){e.overlayWarnings=o.warnings;for(let l of o.warnings)console.error(`[AgentsInstaller] Overlay warning: ${l}`)}if(o.errors.length>0)for(let l of o.errors)e.errors.push(`Overlay error: ${l}`);for(let l of o.overlays){let g=l.agent,x=Te.includes(g)?d(n,`${g}.md`):d(t,`${g}.md`);if(!f(x)){e.overlayWarnings.push(`Overlay for "${g}" found but agent file does not exist. Skipping.`);continue}try{let I=ae(x,"utf-8"),{content:de,applied:q}=ne(I,l),pe=Ie(de);le(x,pe,"utf-8"),e.overlaysApplied.push(g);let me=[...q.replacedFields.map(C=>`replaced:${C}`),...q.appendedFields.map(C=>`appended:${C}`),...q.configOverrides.map(C=>`config:${C}`)];console.error(`[AgentsInstaller] Applied overlay for ${g}: ${me.join(", ")}`)}catch(I){e.overlayWarnings.push(`Failed to apply overlay for "${g}": ${b(I)}`)}}e.overlaysApplied.length>0&&console.error(`[AgentsInstaller] Applied ${e.overlaysApplied.length} agent overlay(s): ${e.overlaysApplied.join(", ")}`);let a=ee(t,this.projectRoot);if(e.mcpValidationWarnings=a.warnings,a.warnings.length>0){console.error(`[AgentsInstaller] MCP dependency warnings (${a.agentsWithMissingDeps.length} agents affected):`);for(let l of a.warnings.slice(0,10))console.error(` ${l}`);a.warnings.length>10&&console.error(` ... and ${a.warnings.length-10} more warnings`)}return await this.createAgentsIndex(t,e.installed),e}getAvailableAgents(){let e=[];try{let t=K(this.sourceAgentsDir);for(let n of t){let i=d(this.sourceAgentsDir,n),s=oe(i);if(s.isFile()&&n.endsWith(".md"))e.push(n.replace(".md",""));else if(s.isDirectory()&&n==="subagents"){let o=K(i);for(let a of o)a.endsWith(".md")&&e.push(`subagents/${a.replace(".md","")}`)}}}catch{return[]}return e}filterAgents(e){let t=e.filter(n=>(n.includes("/")?n.split("/")[1]:n).startsWith("qe-"));return this.options.include&&this.options.include.length>0&&(t=t.filter(n=>{let i=n.includes("/")?n.split("/")[1]:n;return this.options.include.includes(i)})),this.options.exclude&&this.options.exclude.length>0&&(t=t.filter(n=>{let i=n.includes("/")?n.split("/")[1]:n;return!this.options.exclude.some(s=>i.includes(s)||i.match(new RegExp(s)))})),this.options.installQEAgents||(t=t.filter(n=>{let i=n.includes("/")?n.split("/")[1]:n;return!qe.includes(i)})),this.options.installSubagents||(t=t.filter(n=>!n.startsWith("subagents/"))),t}async installAgent(e,t,n){let i=e.startsWith("subagents/"),s=i?e.split("/")[1]:e,o=d(this.sourceAgentsDir,`${e}.md`),a=i?d(n,`${s}.md`):d(t,`${s}.md`);if(f(a)&&!this.options.overwrite)return null;if(f(o))J(o,a);else throw new Error(`Source file not found: ${o}`);let l=this.getAgentType(s,i),g=this.getAgentDescription(a),c=this.getAgentDomain(s);return{name:s,type:l,description:g,domain:c}}getAgentType(e,t){return t?"v3-subagent":"v3-qe"}copyDirectoryRecursive(e,t){if(!f(e))return;f(t)||D(t,{recursive:!0});let n=K(e);for(let i of n){let s=d(e,i),o=d(t,i);oe(s).isDirectory()?this.copyDirectoryRecursive(s,o):(!f(o)||this.options.overwrite)&&J(s,o)}}async copyHelpersDirectory(e){let t=d(this.sourceAgentsDir,"helpers"),n=d(this.projectRoot,".claude","helpers","v3");f(t)?this.copyDirectoryRecursive(t,n):console.error(`[AgentsInstaller] Helpers source not found: ${t}`)}async copyTemplatesDirectory(e){let t=d(this.sourceAgentsDir,"templates"),n=d(e,"templates");f(t)?this.copyDirectoryRecursive(t,n):console.error(`[AgentsInstaller] Templates source not found: ${t}`)}getAgentDescription(e){if(f(e))try{let t=ae(e,"utf-8"),n=t.match(/description:\s*["']?([^"'\n]+)["']?/i);if(n)return n[1].trim();let i=t.split(`
62
- `);for(let s of i){let o=s.trim();if(o&&!o.startsWith("#")&&!o.startsWith("-")&&!o.startsWith("```")&&!o.startsWith("---"))return o.slice(0,100)+(o.length>100?"...":"")}}catch(t){console.debug("[AgentsInstaller] Failed to read agent description:",t instanceof Error?t.message:t)}}getAgentDomain(e){let t={"test-architect":"test-generation","bdd-generator":"test-generation","property-tester":"test-generation","mutation-tester":"test-generation","parallel-executor":"test-execution","flaky-hunter":"test-execution","retry-handler":"test-execution","coverage-specialist":"coverage-analysis","gap-detector":"coverage-analysis","quality-gate":"quality-assessment","code-complexity":"quality-assessment","deployment-advisor":"quality-assessment","risk-assessor":"quality-assessment","defect-predictor":"defect-intelligence","regression-analyzer":"defect-intelligence","root-cause-analyzer":"defect-intelligence","impact-analyzer":"defect-intelligence","requirements-validator":"requirements-validation","qx-partner":"requirements-validation","product-factors-assessor":"requirements-validation","quality-criteria-recommender":"requirements-validation","test-idea-rewriter":"test-generation","code-intelligence":"code-intelligence","kg-builder":"code-intelligence","dependency-mapper":"code-intelligence","security-scanner":"security-compliance","security-auditor":"security-compliance","pentest-validator":"security-compliance","contract-validator":"contract-testing","graphql-tester":"contract-testing","visual-tester":"visual-accessibility","accessibility-auditor":"visual-accessibility","responsive-tester":"visual-accessibility","chaos-engineer":"chaos-resilience","load-tester":"chaos-resilience","performance-tester":"chaos-resilience","learning-coordinator":"learning-optimization","pattern-learner":"learning-optimization","metrics-optimizer":"learning-optimization","transfer-specialist":"learning-optimization","soap-tester":"enterprise-integration","sap-rfc-tester":"enterprise-integration","sap-idoc-tester":"enterprise-integration","odata-contract-tester":"enterprise-integration","middleware-validator":"enterprise-integration","message-broker-tester":"enterprise-integration","sod-analyzer":"enterprise-integration"},n=e.replace(/^(v3-)?qe-/,"");return t[n]}async createAgentsIndex(e,t){let n=t.filter(l=>l.type==="v3-qe"),i=t.filter(l=>l.type==="v3-subagent"),s=new Map;for(let l of n){let g=l.domain||"general";s.has(g)||s.set(g,[]),s.get(g).push(l)}let o=`# AQE V3 Agents Index
61
+ ---`)}var $e=["qe-test-architect","qe-bdd-generator","qe-property-tester","qe-mutation-tester","qe-test-idea-rewriter","qe-quality-criteria-recommender","qe-parallel-executor","qe-flaky-hunter","qe-retry-handler","qe-coverage-specialist","qe-gap-detector","qe-quality-gate","qe-code-complexity","qe-deployment-advisor","qe-risk-assessor","qe-defect-predictor","qe-regression-analyzer","qe-root-cause-analyzer","qe-impact-analyzer","qe-requirements-validator","qe-qx-partner","qe-product-factors-assessor","qe-code-intelligence","qe-kg-builder","qe-dependency-mapper","qe-security-scanner","qe-security-auditor","qe-pentest-validator","qe-contract-validator","qe-graphql-tester","qe-visual-tester","qe-accessibility-auditor","qe-responsive-tester","qe-chaos-engineer","qe-load-tester","qe-performance-tester","qe-learning-coordinator","qe-pattern-learner","qe-metrics-optimizer","qe-transfer-specialist","qe-soap-tester","qe-sap-rfc-tester","qe-sap-idoc-tester","qe-odata-contract-tester","qe-middleware-validator","qe-message-broker-tester","qe-sod-analyzer","qe-fleet-commander","qe-queen-coordinator","qe-tdd-specialist","qe-integration-tester","qe-integration-architect"],Ne=["qe-code-reviewer","qe-integration-reviewer","qe-performance-reviewer","qe-security-reviewer","qe-tdd-red","qe-tdd-green","qe-tdd-refactor"],Y=class{projectRoot;options;sourceAgentsDir;constructor(e){this.projectRoot=e.projectRoot,this.options={installQEAgents:!0,installSubagents:!0,overwrite:!1,exclude:[],include:void 0,...e},this.sourceAgentsDir=this.findSourceAgentsDir()}findSourceAgentsDir(){let e=b(import.meta.url),t=[];e&&(t.push(d(e,"assets/agents/v3")),t.push(d(e,".claude/agents/v3"))),t.push(d(this.projectRoot,"node_modules/agentic-qe/assets/agents/v3"));for(let n of t)if(f(n))return n;return t[0]}preserveOverridesDir(){let e=d(this.projectRoot,".claude","agent-overrides");f(e)||D(e,{recursive:!0});let t=d(e,"_example.yaml");if(!f(t))try{let n=b(import.meta.url),i=[...n?[d(n,"assets","templates","agent-override-example.yaml")]:[],d(this.projectRoot,"node_modules","agentic-qe","assets","templates","agent-override-example.yaml")];for(let s of i)if(f(s)){J(s,t);break}}catch{}}async install(){let e={installed:[],skipped:[],errors:[],totalCount:0,agentsDir:d(this.projectRoot,".claude","agents","v3"),overlaysApplied:[],overlayWarnings:[]};if(this.preserveOverridesDir(),!f(this.sourceAgentsDir))return e.errors.push(`Source agents directory not found: ${this.sourceAgentsDir}`),e;let t=d(this.projectRoot,".claude","agents","v3");f(t)||D(t,{recursive:!0});let n=d(t,"subagents");f(n)||D(n,{recursive:!0}),await this.copyHelpersDirectory(t),await this.copyTemplatesDirectory(t);let i=this.getAvailableAgents();e.totalCount=i.length;let s=this.filterAgents(i);for(let l of s)try{let u=await this.installAgent(l,t,n);u?e.installed.push(u):e.skipped.push(l)}catch(u){e.errors.push(`Failed to install ${l}: ${k(u)}`)}let o=te(this.projectRoot);if(o.warnings.length>0){e.overlayWarnings=o.warnings;for(let l of o.warnings)console.error(`[AgentsInstaller] Overlay warning: ${l}`)}if(o.errors.length>0)for(let l of o.errors)e.errors.push(`Overlay error: ${l}`);for(let l of o.overlays){let u=l.agent,x=Ne.includes(u)?d(n,`${u}.md`):d(t,`${u}.md`);if(!f(x)){e.overlayWarnings.push(`Overlay for "${u}" found but agent file does not exist. Skipping.`);continue}try{let I=ue(x,"utf-8"),{content:fe,applied:q}=ne(I,l),he=Fe(fe);ge(x,he,"utf-8"),e.overlaysApplied.push(u);let ye=[...q.replacedFields.map(w=>`replaced:${w}`),...q.appendedFields.map(w=>`appended:${w}`),...q.configOverrides.map(w=>`config:${w}`)];console.error(`[AgentsInstaller] Applied overlay for ${u}: ${ye.join(", ")}`)}catch(I){e.overlayWarnings.push(`Failed to apply overlay for "${u}": ${k(I)}`)}}e.overlaysApplied.length>0&&console.error(`[AgentsInstaller] Applied ${e.overlaysApplied.length} agent overlay(s): ${e.overlaysApplied.join(", ")}`);let a=ee(t,this.projectRoot);if(e.mcpValidationWarnings=a.warnings,a.warnings.length>0){console.error(`[AgentsInstaller] MCP dependency warnings (${a.agentsWithMissingDeps.length} agents affected):`);for(let l of a.warnings.slice(0,10))console.error(` ${l}`);a.warnings.length>10&&console.error(` ... and ${a.warnings.length-10} more warnings`)}return await this.createAgentsIndex(t,e.installed),e}getAvailableAgents(){let e=[];try{let t=K(this.sourceAgentsDir);for(let n of t){let i=d(this.sourceAgentsDir,n),s=ce(i);if(s.isFile()&&n.endsWith(".md"))e.push(n.replace(".md",""));else if(s.isDirectory()&&n==="subagents"){let o=K(i);for(let a of o)a.endsWith(".md")&&e.push(`subagents/${a.replace(".md","")}`)}}}catch{return[]}return e}filterAgents(e){let t=e.filter(n=>(n.includes("/")?n.split("/")[1]:n).startsWith("qe-"));return this.options.include&&this.options.include.length>0&&(t=t.filter(n=>{let i=n.includes("/")?n.split("/")[1]:n;return this.options.include.includes(i)})),this.options.exclude&&this.options.exclude.length>0&&(t=t.filter(n=>{let i=n.includes("/")?n.split("/")[1]:n;return!this.options.exclude.some(s=>i.includes(s)||i.match(new RegExp(s)))})),this.options.installQEAgents||(t=t.filter(n=>{let i=n.includes("/")?n.split("/")[1]:n;return!$e.includes(i)})),this.options.installSubagents||(t=t.filter(n=>!n.startsWith("subagents/"))),t}async installAgent(e,t,n){let i=e.startsWith("subagents/"),s=i?e.split("/")[1]:e,o=d(this.sourceAgentsDir,`${e}.md`),a=i?d(n,`${s}.md`):d(t,`${s}.md`);if(f(a)&&!this.options.overwrite)return null;if(f(o))J(o,a);else throw new Error(`Source file not found: ${o}`);let l=this.getAgentType(s,i),u=this.getAgentDescription(a),c=this.getAgentDomain(s);return{name:s,type:l,description:u,domain:c}}getAgentType(e,t){return t?"v3-subagent":"v3-qe"}copyDirectoryRecursive(e,t){if(!f(e))return;f(t)||D(t,{recursive:!0});let n=K(e);for(let i of n){let s=d(e,i),o=d(t,i);ce(s).isDirectory()?this.copyDirectoryRecursive(s,o):(!f(o)||this.options.overwrite)&&J(s,o)}}async copyHelpersDirectory(e){let t=d(this.sourceAgentsDir,"helpers"),n=d(this.projectRoot,".claude","helpers","v3");f(t)?this.copyDirectoryRecursive(t,n):console.error(`[AgentsInstaller] Helpers source not found: ${t}`)}async copyTemplatesDirectory(e){let t=d(this.sourceAgentsDir,"templates"),n=d(e,"templates");f(t)?this.copyDirectoryRecursive(t,n):console.error(`[AgentsInstaller] Templates source not found: ${t}`)}getAgentDescription(e){if(f(e))try{let t=ue(e,"utf-8"),n=t.match(/description:\s*["']?([^"'\n]+)["']?/i);if(n)return n[1].trim();let i=t.split(`
62
+ `);for(let s of i){let o=s.trim();if(o&&!o.startsWith("#")&&!o.startsWith("-")&&!o.startsWith("```")&&!o.startsWith("---"))return o.slice(0,100)+(o.length>100?"...":"")}}catch(t){console.debug("[AgentsInstaller] Failed to read agent description:",t instanceof Error?t.message:t)}}getAgentDomain(e){let t={"test-architect":"test-generation","bdd-generator":"test-generation","property-tester":"test-generation","mutation-tester":"test-generation","parallel-executor":"test-execution","flaky-hunter":"test-execution","retry-handler":"test-execution","coverage-specialist":"coverage-analysis","gap-detector":"coverage-analysis","quality-gate":"quality-assessment","code-complexity":"quality-assessment","deployment-advisor":"quality-assessment","risk-assessor":"quality-assessment","defect-predictor":"defect-intelligence","regression-analyzer":"defect-intelligence","root-cause-analyzer":"defect-intelligence","impact-analyzer":"defect-intelligence","requirements-validator":"requirements-validation","qx-partner":"requirements-validation","product-factors-assessor":"requirements-validation","quality-criteria-recommender":"requirements-validation","test-idea-rewriter":"test-generation","code-intelligence":"code-intelligence","kg-builder":"code-intelligence","dependency-mapper":"code-intelligence","security-scanner":"security-compliance","security-auditor":"security-compliance","pentest-validator":"security-compliance","contract-validator":"contract-testing","graphql-tester":"contract-testing","visual-tester":"visual-accessibility","accessibility-auditor":"visual-accessibility","responsive-tester":"visual-accessibility","chaos-engineer":"chaos-resilience","load-tester":"chaos-resilience","performance-tester":"chaos-resilience","learning-coordinator":"learning-optimization","pattern-learner":"learning-optimization","metrics-optimizer":"learning-optimization","transfer-specialist":"learning-optimization","soap-tester":"enterprise-integration","sap-rfc-tester":"enterprise-integration","sap-idoc-tester":"enterprise-integration","odata-contract-tester":"enterprise-integration","middleware-validator":"enterprise-integration","message-broker-tester":"enterprise-integration","sod-analyzer":"enterprise-integration"},n=e.replace(/^(v3-)?qe-/,"");return t[n]}async createAgentsIndex(e,t){let n=t.filter(l=>l.type==="v3-qe"),i=t.filter(l=>l.type==="v3-subagent"),s=new Map;for(let l of n){let u=l.domain||"general";s.has(u)||s.set(u,[]),s.get(u).push(l)}let o=`# AQE V3 Agents Index
63
63
 
64
64
  This directory contains V3 QE agents installed by \`aqe init\`.
65
65
 
@@ -87,10 +87,10 @@ Task("Run security scan", "...", "v3-qe-security-scanner")
87
87
 
88
88
  Quality Engineering agents mapped to the 12 DDD bounded contexts.
89
89
 
90
- ${Array.from(s.entries()).map(([l,g])=>`
90
+ ${Array.from(s.entries()).map(([l,u])=>`
91
91
  ### ${l.split("-").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join(" ")}
92
92
 
93
- ${g.map(c=>`- **${c.name}**${c.description?`: ${c.description}`:""}`).join(`
93
+ ${u.map(c=>`- **${c.name}**${c.description?`: ${c.description}`:""}`).join(`
94
94
  `)}
95
95
  `).join(`
96
96
  `)}
@@ -105,7 +105,7 @@ ${i.map(l=>`- **${l.name}**${l.description?`: ${l.description}`:""}`).join(`
105
105
  ---
106
106
 
107
107
  *Generated by AQE v3 init on ${new Date().toISOString()}*
108
- `,a=d(this.projectRoot,".claude","docs");f(a)||D(a,{recursive:!0}),le(d(a,"v3-agents-index.md"),o,"utf-8")}};function at(r){return new Y(r)}T();import{existsSync as v,mkdirSync as Z,readdirSync as ce,readFileSync as Ee,writeFileSync as Pe,copyFileSync as ge}from"fs";import{join as y}from"path";var ue={core:[{name:"workflow-executor",filename:"n8n-workflow-executor.md",category:"core"},{name:"node-validator",filename:"n8n-node-validator.md",category:"core"},{name:"trigger-test",filename:"n8n-trigger-test.md",category:"core"},{name:"expression-validator",filename:"n8n-expression-validator.md",category:"core"},{name:"integration-test",filename:"n8n-integration-test.md",category:"core"},{name:"security-auditor",filename:"n8n-security-auditor.md",category:"core"}],advanced:[{name:"unit-tester",filename:"n8n-unit-tester.md",category:"advanced"},{name:"performance-tester",filename:"n8n-performance-tester.md",category:"advanced"},{name:"ci-orchestrator",filename:"n8n-ci-orchestrator.md",category:"advanced"}],quality:[{name:"version-comparator",filename:"n8n-version-comparator.md",category:"quality"},{name:"bdd-scenario-tester",filename:"n8n-bdd-scenario-tester.md",category:"quality"},{name:"monitoring-validator",filename:"n8n-monitoring-validator.md",category:"quality"}],enterprise:[{name:"compliance-validator",filename:"n8n-compliance-validator.md",category:"enterprise"},{name:"chaos-tester",filename:"n8n-chaos-tester.md",category:"enterprise"}],reliability:[{name:"base-agent",filename:"n8n-base-agent.md",category:"reliability"}]},_e=["n8n-expression-testing","n8n-integration-testing-patterns","n8n-security-testing","n8n-trigger-testing-strategies","n8n-workflow-testing-fundamentals"],X=class{projectRoot;options;sourceAgentsDir;sourceSkillsDir;constructor(e){this.projectRoot=e.projectRoot,this.options={installAgents:!0,installSkills:!0,overwrite:!1,...e},this.sourceAgentsDir=this.findSourceAgentsDir(),this.sourceSkillsDir=this.findSourceSkillsDir()}findSourceAgentsDir(){let e=k(import.meta.url),t=[];e&&t.push(y(e,".claude/agents/n8n")),t.push(y(this.projectRoot,"node_modules/agentic-qe/.claude/agents/n8n"));for(let n of t)if(v(n))return n;return t[0]}findSourceSkillsDir(){let e=k(import.meta.url),t=[];e&&(t.push(y(e,"assets/skills")),t.push(y(e,".claude/skills"))),t.push(y(this.projectRoot,"node_modules/agentic-qe/assets/skills"));for(let n of t)if(v(n))return n;return t[0]}async install(){let e={success:!0,agentsInstalled:[],skillsInstalled:[],configGenerated:!1,errors:[],agentsDir:y(this.projectRoot,".claude/agents/n8n"),skillsDir:y(this.projectRoot,".claude/skills")};try{if(this.options.installAgents){let t=await this.installAgents(e.agentsDir);e.agentsInstalled=t.installed,e.errors.push(...t.errors)}if(this.options.installSkills){let t=await this.installSkills(e.skillsDir);e.skillsInstalled=t.installed,e.errors.push(...t.errors)}this.options.n8nApiConfig&&(e.configGenerated=!0),e.agentsInstalled.length>0&&this.createAgentsIndex(e.agentsDir,e.agentsInstalled)}catch(t){e.success=!1,e.errors.push(`Installation failed: ${b(t)}`)}return e}async installAgents(e){let t=[],n=[];if(v(e)||Z(e,{recursive:!0}),!v(this.sourceAgentsDir))return n.push(`Source agents directory not found: ${this.sourceAgentsDir}`),{installed:t,errors:n};let i=ce(this.sourceAgentsDir).filter(s=>s.endsWith(".md"));for(let s of Object.keys(ue))for(let o of ue[s]){let a=y(this.sourceAgentsDir,o.filename),l=y(e,o.filename);if(i.includes(o.filename)&&!(v(l)&&!this.options.overwrite))try{ge(a,l);let c=Ee(a,"utf-8").match(/description:\s*["']?(.+?)["']?\n/);o.description=c?.[1]||`n8n ${o.name} agent`,t.push(o)}catch(g){n.push(`Failed to install ${o.name}: ${b(g)}`)}}return{installed:t,errors:n}}async installSkills(e){let t=[],n=[];if(v(e)||Z(e,{recursive:!0}),!v(this.sourceSkillsDir))return n.push(`Source skills directory not found: ${this.sourceSkillsDir}`),{installed:t,errors:n};for(let i of _e){let s=y(this.sourceSkillsDir,i),o=y(e,i);if(v(s)&&!(v(o)&&!this.options.overwrite))try{this.copyDirectory(s,o),t.push(i)}catch(a){n.push(`Failed to install skill ${i}: ${b(a)}`)}}return{installed:t,errors:n}}copyDirectory(e,t){v(t)||Z(t,{recursive:!0});let n=ce(e,{withFileTypes:!0});for(let i of n){let s=y(e,i.name),o=y(t,i.name);i.isDirectory()?this.copyDirectory(s,o):ge(s,o)}}createAgentsIndex(e,t){let n=y(e,"README.md"),i={core:t.filter(o=>o.category==="core"),advanced:t.filter(o=>o.category==="advanced"),quality:t.filter(o=>o.category==="quality"),enterprise:t.filter(o=>o.category==="enterprise"),reliability:t.filter(o=>o.category==="reliability")},s=`# N8n Testing Agents
108
+ `,a=d(this.projectRoot,".claude","docs");f(a)||D(a,{recursive:!0}),ge(d(a,"v3-agents-index.md"),o,"utf-8")}};function yt(r){return new Y(r)}T();import{existsSync as v,mkdirSync as Z,readdirSync as de,readFileSync as Oe,writeFileSync as Le,copyFileSync as pe}from"fs";import{join as y}from"path";var me={core:[{name:"workflow-executor",filename:"n8n-workflow-executor.md",category:"core"},{name:"node-validator",filename:"n8n-node-validator.md",category:"core"},{name:"trigger-test",filename:"n8n-trigger-test.md",category:"core"},{name:"expression-validator",filename:"n8n-expression-validator.md",category:"core"},{name:"integration-test",filename:"n8n-integration-test.md",category:"core"},{name:"security-auditor",filename:"n8n-security-auditor.md",category:"core"}],advanced:[{name:"unit-tester",filename:"n8n-unit-tester.md",category:"advanced"},{name:"performance-tester",filename:"n8n-performance-tester.md",category:"advanced"},{name:"ci-orchestrator",filename:"n8n-ci-orchestrator.md",category:"advanced"}],quality:[{name:"version-comparator",filename:"n8n-version-comparator.md",category:"quality"},{name:"bdd-scenario-tester",filename:"n8n-bdd-scenario-tester.md",category:"quality"},{name:"monitoring-validator",filename:"n8n-monitoring-validator.md",category:"quality"}],enterprise:[{name:"compliance-validator",filename:"n8n-compliance-validator.md",category:"enterprise"},{name:"chaos-tester",filename:"n8n-chaos-tester.md",category:"enterprise"}],reliability:[{name:"base-agent",filename:"n8n-base-agent.md",category:"reliability"}]},Me=["n8n-expression-testing","n8n-integration-testing-patterns","n8n-security-testing","n8n-trigger-testing-strategies","n8n-workflow-testing-fundamentals"],X=class{projectRoot;options;sourceAgentsDir;sourceSkillsDir;constructor(e){this.projectRoot=e.projectRoot,this.options={installAgents:!0,installSkills:!0,overwrite:!1,...e},this.sourceAgentsDir=this.findSourceAgentsDir(),this.sourceSkillsDir=this.findSourceSkillsDir()}findSourceAgentsDir(){let e=b(import.meta.url),t=[];e&&t.push(y(e,".claude/agents/n8n")),t.push(y(this.projectRoot,"node_modules/agentic-qe/.claude/agents/n8n"));for(let n of t)if(v(n))return n;return t[0]}findSourceSkillsDir(){let e=b(import.meta.url),t=[];e&&(t.push(y(e,"assets/skills")),t.push(y(e,".claude/skills"))),t.push(y(this.projectRoot,"node_modules/agentic-qe/assets/skills"));for(let n of t)if(v(n))return n;return t[0]}async install(){let e={success:!0,agentsInstalled:[],skillsInstalled:[],configGenerated:!1,errors:[],agentsDir:y(this.projectRoot,".claude/agents/n8n"),skillsDir:y(this.projectRoot,".claude/skills")};try{if(this.options.installAgents){let t=await this.installAgents(e.agentsDir);e.agentsInstalled=t.installed,e.errors.push(...t.errors)}if(this.options.installSkills){let t=await this.installSkills(e.skillsDir);e.skillsInstalled=t.installed,e.errors.push(...t.errors)}this.options.n8nApiConfig&&(e.configGenerated=!0),e.agentsInstalled.length>0&&this.createAgentsIndex(e.agentsDir,e.agentsInstalled)}catch(t){e.success=!1,e.errors.push(`Installation failed: ${k(t)}`)}return e}async installAgents(e){let t=[],n=[];if(v(e)||Z(e,{recursive:!0}),!v(this.sourceAgentsDir))return n.push(`Source agents directory not found: ${this.sourceAgentsDir}`),{installed:t,errors:n};let i=de(this.sourceAgentsDir).filter(s=>s.endsWith(".md"));for(let s of Object.keys(me))for(let o of me[s]){let a=y(this.sourceAgentsDir,o.filename),l=y(e,o.filename);if(i.includes(o.filename)&&!(v(l)&&!this.options.overwrite))try{pe(a,l);let c=Oe(a,"utf-8").match(/description:\s*["']?(.+?)["']?\n/);o.description=c?.[1]||`n8n ${o.name} agent`,t.push(o)}catch(u){n.push(`Failed to install ${o.name}: ${k(u)}`)}}return{installed:t,errors:n}}async installSkills(e){let t=[],n=[];if(v(e)||Z(e,{recursive:!0}),!v(this.sourceSkillsDir))return n.push(`Source skills directory not found: ${this.sourceSkillsDir}`),{installed:t,errors:n};for(let i of Me){let s=y(this.sourceSkillsDir,i),o=y(e,i);if(v(s)&&!(v(o)&&!this.options.overwrite))try{this.copyDirectory(s,o),t.push(i)}catch(a){n.push(`Failed to install skill ${i}: ${k(a)}`)}}return{installed:t,errors:n}}copyDirectory(e,t){v(t)||Z(t,{recursive:!0});let n=de(e,{withFileTypes:!0});for(let i of n){let s=y(e,i.name),o=y(t,i.name);i.isDirectory()?this.copyDirectory(s,o):pe(s,o)}}createAgentsIndex(e,t){let n=y(e,"README.md"),i={core:t.filter(o=>o.category==="core"),advanced:t.filter(o=>o.category==="advanced"),quality:t.filter(o=>o.category==="quality"),enterprise:t.filter(o=>o.category==="enterprise"),reliability:t.filter(o=>o.category==="reliability")},s=`# N8n Testing Agents
109
109
 
110
110
  > Auto-generated by \`aqe init --with-n8n\`
111
111
 
@@ -138,7 +138,7 @@ Task("Run security audit on workflow", "n8n-security-auditor")
138
138
  `;s+=`
139
139
  `}s+=`---
140
140
  Generated: ${new Date().toISOString()}
141
- `,Pe(n,s)}generateConfigSection(){return{n8n:{enabled:!0,installAgents:this.options.installAgents,installSkills:this.options.installSkills,apiConfig:this.options.n8nApiConfig||null}}}generateClaudeMdSection(){return`
141
+ `,Le(n,s)}generateConfigSection(){return{n8n:{enabled:!0,installAgents:this.options.installAgents,installSkills:this.options.installSkills,apiConfig:this.options.n8nApiConfig||null}}}generateClaudeMdSection(){return`
142
142
  ## N8n Workflow Testing
143
143
 
144
144
  This project includes n8n workflow testing agents. Use them with Claude Code:
@@ -177,4 +177,4 @@ N8n agents map to v3 domains:
177
177
  - Compliance agents \u2192 security-compliance domain
178
178
  - Chaos agents \u2192 chaos-resilience domain
179
179
 
180
- `}};function pt(r){return new X(r)}export{M as a,Fe as b,Me as c,We as d,Se as e,Ge as f,Ue as g,He as h,Xe as i,at as j,pt as k};
180
+ `}};function At(r){return new X(r)}export{M as a,Ve as b,Ue as c,Ke as d,Ze as e,je as f,Xe as g,et as h,tt as i,nt as j,rt as k,ct as l,yt as m,At as n};
@@ -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.11.5");process.exit(0)}
2
- import{c as h}from"./chunk-C4EZNOWK.js";function i(t,r){if(t.length!==r.length)throw new Error(`Vector length mismatch: ${t.length} vs ${r.length}`);let e=0,o=0,l=0;for(let n=0;n<t.length;n++)e+=t[n]*r[n],o+=t[n]*t[n],l+=r[n]*r[n];let u=Math.sqrt(o)*Math.sqrt(l);return u===0?0:e/u}function c(t){let r=Math.sqrt(t.reduce((e,o)=>e+o*o,0));return r===0?t.slice():t.map(e=>e/r)}function g(t){let r=0;for(let e=0;e<t.length;e++)r+=t[e]*t[e];return Math.sqrt(r)}var m=h(()=>{"use strict"});export{i as a,c as b,g as c,m as d};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.12.1");process.exit(0)}
2
+ import{c as h}from"./chunk-U5ITD7ZD.js";function i(t,r){if(t.length!==r.length)throw new Error(`Vector length mismatch: ${t.length} vs ${r.length}`);let e=0,o=0,l=0;for(let n=0;n<t.length;n++)e+=t[n]*r[n],o+=t[n]*t[n],l+=r[n]*r[n];let u=Math.sqrt(o)*Math.sqrt(l);return u===0?0:e/u}function c(t){let r=Math.sqrt(t.reduce((e,o)=>e+o*o,0));return r===0?t.slice():t.map(e=>e/r)}function g(t){let r=0;for(let e=0;e<t.length;e++)r+=t[e]*t[e];return Math.sqrt(r)}var m=h(()=>{"use strict"});export{i as a,c as b,g as c,m 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.11.5");process.exit(0)}
2
- import{a as D,b as _,c as $,d as I}from"./chunk-UORTQXJ2.js";import{a as X}from"./chunk-4XJ2A3HY.js";import{c as K,d as Y,e as J,f as Z}from"./chunk-PW72M2FE.js";import{b as C,f as G,i as U}from"./chunk-MCHEUSY4.js";import{g as R}from"./chunk-W7TYKPLY.js";import{d as H}from"./chunk-TRNBQFFG.js";import{i as j,m as de}from"./chunk-NCSXLMDL.js";import{a as z}from"./chunk-ZMPAM4DY.js";import{c as T}from"./chunk-Y25PO65W.js";import{b as k,c as A}from"./chunk-5WMU7XCF.js";import{a as h,b as V,c as W}from"./chunk-RKXZLTWR.js";import{S as pe,b as B}from"./chunk-GODAWJMZ.js";z();W();var N={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var q=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.12.1");process.exit(0)}
2
+ import{a as D,b as _,c as $,d as I}from"./chunk-YGB3MT3R.js";import{a as X}from"./chunk-BPM7NEHS.js";import{c as K,d as Y,e as J,f as Z}from"./chunk-RIASOMB2.js";import{b as C,f as G,i as U}from"./chunk-3W2FZXFD.js";import{g as R}from"./chunk-CYYT6YEV.js";import{d as H}from"./chunk-XS6BIOPQ.js";import{i as j,m as de}from"./chunk-XDRAU3W6.js";import{a as z}from"./chunk-FNMEVLSN.js";import{c as T}from"./chunk-NOCPO55P.js";import{b as k,c as A}from"./chunk-4LKQZW2H.js";import{a as h,b as V,c as W}from"./chunk-UBPJQKYS.js";import{S as pe,b as B}from"./chunk-USTUWUCE.js";z();W();var N={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var q=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
3
3
  describe('{{methodName}}', () => {
4
4
  it('should {{expectedBehavior}}', {{async}} () => {
5
5
  // Arrange
@@ -317,4 +317,4 @@ On promotion:
317
317
  AND agent_id = 'aqe-hook-router'
318
318
  AND state_key = ?
319
319
  AND action_key = ?
320
- `);return s=>{try{let a=o.get(e,s);return a?{qValue:a.q_value,visits:a.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return D(e)}generateContext(e,r){return I(e,r||{})}checkAntiPatterns(e,r){return $(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-2PUCC7FG.js"),t=await r(e);return t.length!==this.config.embeddingDimension?oe(t,this.config.embeddingDimension):t}catch(r){let{isUsingEndpoint:t}=await import("./real-embeddings-2PUCC7FG.js");if(t())throw r;process.env.DEBUG&&f.warn("ONNX embeddings unavailable, using hash fallback",{error:h(r)})}return se(e,this.config.embeddingDimension)}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let a of U)r[a]=e.byDomain[a]||0;let t=this.stats.routingRequests,i=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,o=this.stats.learningOutcomes,s=this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0;try{let a=this.getSqliteStore().getAggregateOutcomeStats();a.routingRequests>t&&(t=a.routingRequests,i=a.avgRoutingConfidence),a.learningOutcomes>o&&(o=a.learningOutcomes,s=a.learningOutcomes>0?a.successfulOutcomes/a.learningOutcomes:a.avgPatternSuccessRate)}catch{}return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:i,learningOutcomes:o,patternSuccessRate:s,patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function pt(n,e,r,t){return new L(n,e,r,t)}export{N as a,q as b,x as c,ne as d,Q as e,M as f,L as g,pt as h};
320
+ `);return s=>{try{let a=o.get(e,s);return a?{qValue:a.q_value,visits:a.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return D(e)}generateContext(e,r){return I(e,r||{})}checkAntiPatterns(e,r){return $(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-LZD6HTQF.js"),t=await r(e);return t.length!==this.config.embeddingDimension?oe(t,this.config.embeddingDimension):t}catch(r){let{isUsingEndpoint:t}=await import("./real-embeddings-LZD6HTQF.js");if(t())throw r;process.env.DEBUG&&f.warn("ONNX embeddings unavailable, using hash fallback",{error:h(r)})}return se(e,this.config.embeddingDimension)}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let a of U)r[a]=e.byDomain[a]||0;let t=this.stats.routingRequests,i=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,o=this.stats.learningOutcomes,s=this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0;try{let a=this.getSqliteStore().getAggregateOutcomeStats();a.routingRequests>t&&(t=a.routingRequests,i=a.avgRoutingConfidence),a.learningOutcomes>o&&(o=a.learningOutcomes,s=a.learningOutcomes>0?a.successfulOutcomes/a.learningOutcomes:a.avgPatternSuccessRate)}catch{}return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:i,learningOutcomes:o,patternSuccessRate:s,patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function pt(n,e,r,t){return new L(n,e,r,t)}export{N as a,q as b,x as c,ne as d,Q as e,M as f,L as g,pt as h};
@@ -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.11.5");process.exit(0)}
2
- import{a as p,b as A,c as L}from"./chunk-RKXZLTWR.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-TQ4DKDZS.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.1");process.exit(0)}
2
+ import{a as p,b as A,c as L}from"./chunk-UBPJQKYS.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-3T665QC6.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};