agentic-qe 3.9.8 → 3.9.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (335) hide show
  1. package/.claude/skills/README.md +4 -3
  2. package/.claude/skills/a11y-ally/SKILL.md +40 -18
  3. package/.claude/skills/accessibility-testing/SKILL.md +4 -0
  4. package/.claude/skills/compatibility-testing/SKILL.md +23 -0
  5. package/.claude/skills/e2e-flow-verifier/SKILL.md +87 -52
  6. package/.claude/skills/enterprise-integration-testing/SKILL.md +4 -0
  7. package/.claude/skills/localization-testing/SKILL.md +14 -0
  8. package/.claude/skills/observability-testing-patterns/SKILL.md +16 -0
  9. package/.claude/skills/qe-browser/SKILL.md +409 -0
  10. package/.claude/skills/qe-browser/evals/qe-browser.yaml +291 -0
  11. package/.claude/skills/qe-browser/fixtures/package.json +7 -0
  12. package/.claude/skills/qe-browser/fixtures/serve-skills.js +130 -0
  13. package/.claude/skills/qe-browser/references/assertion-kinds.md +132 -0
  14. package/.claude/skills/qe-browser/references/migration-from-playwright.md +195 -0
  15. package/.claude/skills/qe-browser/schemas/output.json +188 -0
  16. package/.claude/skills/qe-browser/scripts/assert.js +378 -0
  17. package/.claude/skills/qe-browser/scripts/batch.js +292 -0
  18. package/.claude/skills/qe-browser/scripts/check-injection.js +267 -0
  19. package/.claude/skills/qe-browser/scripts/intent-score.js +325 -0
  20. package/.claude/skills/qe-browser/scripts/lib/vibium.js +330 -0
  21. package/.claude/skills/qe-browser/scripts/package.json +7 -0
  22. package/.claude/skills/qe-browser/scripts/smoke-test.sh +212 -0
  23. package/.claude/skills/qe-browser/scripts/validate-config.json +46 -0
  24. package/.claude/skills/qe-browser/scripts/visual-diff.js +276 -0
  25. package/.claude/skills/qe-visual-accessibility/SKILL.md +31 -1
  26. package/.claude/skills/security-visual-testing/SKILL.md +18 -0
  27. package/.claude/skills/skills-manifest.json +20 -13
  28. package/.claude/skills/testability-scoring/SKILL.md +23 -0
  29. package/.claude/skills/trust-tier-manifest.json +14 -3
  30. package/.claude/skills/visual-testing-advanced/SKILL.md +41 -1
  31. package/CHANGELOG.md +53 -0
  32. package/README.md +5 -3
  33. package/assets/skills/README.md +4 -3
  34. package/assets/skills/a11y-ally/SKILL.md +40 -18
  35. package/assets/skills/accessibility-testing/SKILL.md +4 -0
  36. package/assets/skills/compatibility-testing/SKILL.md +23 -0
  37. package/assets/skills/e2e-flow-verifier/SKILL.md +87 -52
  38. package/assets/skills/enterprise-integration-testing/SKILL.md +4 -0
  39. package/assets/skills/localization-testing/SKILL.md +14 -0
  40. package/assets/skills/observability-testing-patterns/SKILL.md +16 -0
  41. package/assets/skills/qe-browser/SKILL.md +409 -0
  42. package/assets/skills/qe-browser/evals/qe-browser.yaml +291 -0
  43. package/assets/skills/qe-browser/fixtures/package.json +7 -0
  44. package/assets/skills/qe-browser/fixtures/serve-skills.js +130 -0
  45. package/assets/skills/qe-browser/references/assertion-kinds.md +132 -0
  46. package/assets/skills/qe-browser/references/migration-from-playwright.md +195 -0
  47. package/assets/skills/qe-browser/schemas/output.json +188 -0
  48. package/assets/skills/qe-browser/scripts/assert.js +378 -0
  49. package/assets/skills/qe-browser/scripts/batch.js +292 -0
  50. package/assets/skills/qe-browser/scripts/check-injection.js +267 -0
  51. package/assets/skills/qe-browser/scripts/intent-score.js +325 -0
  52. package/assets/skills/qe-browser/scripts/lib/vibium.js +330 -0
  53. package/assets/skills/qe-browser/scripts/package.json +7 -0
  54. package/assets/skills/qe-browser/scripts/smoke-test.sh +212 -0
  55. package/assets/skills/qe-browser/scripts/validate-config.json +46 -0
  56. package/assets/skills/qe-browser/scripts/visual-diff.js +276 -0
  57. package/assets/skills/qe-visual-accessibility/SKILL.md +31 -1
  58. package/assets/skills/security-visual-testing/SKILL.md +18 -0
  59. package/assets/skills/skills-manifest.json +211 -15
  60. package/assets/skills/testability-scoring/SKILL.md +23 -0
  61. package/assets/skills/trust-tier-manifest.json +14 -3
  62. package/assets/skills/visual-testing-advanced/SKILL.md +41 -1
  63. package/dist/cli/bundle.js +5 -5
  64. package/dist/cli/chunks/adapter-XKXEZEMM.js +2 -0
  65. package/dist/cli/chunks/{agent-booster-wasm-LAE4NTVX.js → agent-booster-wasm-QEN7W6VC.js} +2 -2
  66. package/dist/cli/chunks/{agent-handler-FVXHR6XN.js → agent-handler-F3RLG42J.js} +2 -2
  67. package/dist/cli/chunks/{agent-memory-branch-Q7LLBA7C.js → agent-memory-branch-U3PZ3CPL.js} +2 -2
  68. package/dist/cli/chunks/aqe-learning-engine-K7XGBDMZ.js +2 -0
  69. package/dist/cli/chunks/{audit-YRLKHJLX.js → audit-FF6SP7Q2.js} +2 -2
  70. package/dist/cli/chunks/base-NUF35LIJ.js +2 -0
  71. package/dist/cli/chunks/{better-sqlite3-XFGOGICB.js → better-sqlite3-CVXRDGQX.js} +2 -2
  72. package/dist/cli/chunks/{brain-handler-KIUSNVSS.js → brain-handler-AMTRZ35W.js} +3 -3
  73. package/dist/cli/chunks/{branch-enumerator-VKZ4L3FH.js → branch-enumerator-Y4A34YFT.js} +2 -2
  74. package/dist/cli/chunks/{browser-GZVIYFIB.js → browser-ETSF5GZR.js} +2 -2
  75. package/dist/cli/chunks/browser-workflow-MWPELXFA.js +2 -0
  76. package/dist/cli/chunks/{chunk-LPRHYSXN.js → chunk-22HQFULR.js} +1 -1
  77. package/dist/cli/chunks/{chunk-677V67MR.js → chunk-2BSVGL35.js} +1 -1
  78. package/dist/cli/chunks/{chunk-TDPHLQ2M.js → chunk-2HFPJPQW.js} +2 -2
  79. package/dist/cli/chunks/{chunk-EKDFIYV5.js → chunk-2JAYDTSE.js} +2 -2
  80. package/dist/cli/chunks/{chunk-AVKDT3UL.js → chunk-2KY5B4ON.js} +8 -8
  81. package/dist/cli/chunks/{chunk-NHXFAXEV.js → chunk-2O3WZ6E3.js} +1 -1
  82. package/dist/cli/chunks/{chunk-PBPOSPTY.js → chunk-2UP3DYNH.js} +2 -2
  83. package/dist/cli/chunks/{chunk-3WOQMFTD.js → chunk-2X7LDTVD.js} +2 -2
  84. package/dist/cli/chunks/{chunk-A4DJMFDM.js → chunk-2ZHA6ORO.js} +1 -1
  85. package/dist/cli/chunks/{chunk-TN72MXLI.js → chunk-3F666FYP.js} +2 -2
  86. package/dist/cli/chunks/{chunk-UGJNR52C.js → chunk-3FAEM5M7.js} +1 -1
  87. package/dist/cli/chunks/{chunk-GHJRX7PV.js → chunk-3JCZTTFY.js} +1 -1
  88. package/dist/cli/chunks/{chunk-7PHNHFZI.js → chunk-3NU4C62D.js} +3 -3
  89. package/dist/cli/chunks/{chunk-YDW522M7.js → chunk-3XR7ARS6.js} +2 -2
  90. package/dist/cli/chunks/{chunk-NCXVOOA7.js → chunk-4CDSEZD6.js} +2 -2
  91. package/dist/cli/chunks/{chunk-7L64UC5U.js → chunk-4CSINHCB.js} +1 -1
  92. package/dist/cli/chunks/{chunk-6ZMM7MXA.js → chunk-4HDG7OS4.js} +2 -2
  93. package/dist/cli/chunks/{chunk-SP3ZBJ63.js → chunk-52RZZV4M.js} +3 -3
  94. package/dist/cli/chunks/{chunk-LOANEFGZ.js → chunk-5DU4YW2S.js} +2 -2
  95. package/dist/cli/chunks/{chunk-6A4FEIE2.js → chunk-5HM66R4W.js} +3 -3
  96. package/dist/cli/chunks/{chunk-BXMIQRF3.js → chunk-5L3EUZJA.js} +2 -2
  97. package/dist/cli/chunks/{chunk-2V5VKOJ2.js → chunk-5SWY75MJ.js} +2 -2
  98. package/dist/cli/chunks/{chunk-ZCKNGICX.js → chunk-65XCVUP7.js} +1 -1
  99. package/dist/cli/chunks/{chunk-R4VOIXJQ.js → chunk-6KQLF3ZO.js} +2 -2
  100. package/dist/cli/chunks/{chunk-SQ6XZGR4.js → chunk-6LTJP3DO.js} +4 -4
  101. package/dist/cli/chunks/{chunk-WXEDVKJS.js → chunk-6PJUDLCT.js} +2 -2
  102. package/dist/cli/chunks/{chunk-JK6JBNGL.js → chunk-74FBSJVC.js} +2 -2
  103. package/dist/cli/chunks/{chunk-XPL3BXLM.js → chunk-A6GYFTIA.js} +1 -1
  104. package/dist/cli/chunks/{chunk-DLKRK2GU.js → chunk-ADJGMTIW.js} +1 -1
  105. package/dist/cli/chunks/{chunk-W4IRWGGR.js → chunk-AHOP227C.js} +4 -4
  106. package/dist/cli/chunks/{chunk-FKODRXOU.js → chunk-ANLFEGDG.js} +2 -2
  107. package/dist/cli/chunks/{chunk-ZJ4PMOIZ.js → chunk-AT2VD2ZP.js} +2 -2
  108. package/dist/cli/chunks/{chunk-7CFEGUEH.js → chunk-AYMIF4W5.js} +2 -2
  109. package/dist/cli/chunks/{chunk-KMGAJRQ6.js → chunk-B3DA4SCL.js} +1 -1
  110. package/dist/cli/chunks/{chunk-4KX6TMKB.js → chunk-BSES27JE.js} +3 -3
  111. package/dist/cli/chunks/{chunk-TWDWDKOI.js → chunk-BVKS3X2I.js} +1 -1
  112. package/dist/cli/chunks/{chunk-PG7CZ6Q4.js → chunk-BVOGMK6N.js} +2 -2
  113. package/dist/cli/chunks/{chunk-RGCCSAHI.js → chunk-BYJEK6LX.js} +2 -2
  114. package/dist/cli/chunks/{chunk-QVGSD25D.js → chunk-BYPBKVTC.js} +1 -1
  115. package/dist/cli/chunks/{chunk-2QI5RYVR.js → chunk-C7YD7O74.js} +2 -2
  116. package/dist/cli/chunks/{chunk-UAI5NPPQ.js → chunk-CCCBGKVY.js} +2 -2
  117. package/dist/cli/chunks/{chunk-OGFGNAKQ.js → chunk-CJQLJEO4.js} +2 -2
  118. package/dist/cli/chunks/{chunk-TSDTRJOG.js → chunk-CXWA34RL.js} +2 -2
  119. package/dist/cli/chunks/{chunk-5TGK7VTS.js → chunk-CZYTPNUI.js} +2 -2
  120. package/dist/cli/chunks/{chunk-HE2NWYHK.js → chunk-DI6R2AVP.js} +1 -1
  121. package/dist/cli/chunks/{chunk-UOSKMAAY.js → chunk-DNS7DP2O.js} +1 -1
  122. package/dist/cli/chunks/{chunk-Q5PARJC6.js → chunk-ECNPBD4Y.js} +2 -2
  123. package/dist/cli/chunks/{chunk-2K3DJ3EK.js → chunk-ENG5UF7M.js} +2 -2
  124. package/dist/cli/chunks/{chunk-JVH7753D.js → chunk-EV2NMWJV.js} +1 -1
  125. package/dist/cli/chunks/{chunk-X66IXWSO.js → chunk-FGW5W3YK.js} +2 -2
  126. package/dist/cli/chunks/{chunk-IP2Z4Z6X.js → chunk-FTF34UME.js} +1 -1
  127. package/dist/cli/chunks/{chunk-YIJDCZVX.js → chunk-GYNGJHYF.js} +2 -2
  128. package/dist/cli/chunks/{chunk-AYKMWP7F.js → chunk-HDM43P7H.js} +1 -1
  129. package/dist/cli/chunks/{chunk-ECYDMBDA.js → chunk-HOWZFW7G.js} +2 -2
  130. package/dist/cli/chunks/{chunk-Y67OXEUM.js → chunk-IZC5NPHD.js} +1 -1
  131. package/dist/cli/chunks/{chunk-P7APAQD6.js → chunk-J2DNMVB5.js} +3 -3
  132. package/dist/cli/chunks/{chunk-HTL2WT64.js → chunk-J62N66ZH.js} +1 -1
  133. package/dist/cli/chunks/{chunk-IHJXFWUL.js → chunk-JIPU4YQK.js} +2 -2
  134. package/dist/cli/chunks/{chunk-MGX2BZWE.js → chunk-JK4K4EH3.js} +2 -2
  135. package/dist/cli/chunks/{chunk-WUCWFDBE.js → chunk-JQJHRQRX.js} +2 -2
  136. package/dist/cli/chunks/{chunk-IFIYNCT2.js → chunk-KSJCMXAJ.js} +2 -2
  137. package/dist/cli/chunks/{chunk-W45FANJG.js → chunk-MDTF7LE6.js} +2 -2
  138. package/dist/cli/chunks/{chunk-DDDEGBBJ.js → chunk-MUCFC3YG.js} +2 -2
  139. package/dist/cli/chunks/{chunk-BZB5D4BO.js → chunk-MUIJVPGB.js} +2 -2
  140. package/dist/cli/chunks/{chunk-VVNR4R22.js → chunk-MWZN4PYF.js} +2 -2
  141. package/dist/cli/chunks/{chunk-XVXSQOQG.js → chunk-MXMKHI2I.js} +2 -2
  142. package/dist/cli/chunks/{chunk-U62WL3WZ.js → chunk-MZOYBHJ3.js} +3 -3
  143. package/dist/cli/chunks/{chunk-TZMKO6PC.js → chunk-NLKJI73E.js} +2 -2
  144. package/dist/cli/chunks/{chunk-66DCG6RO.js → chunk-NQ3WHTLT.js} +4 -4
  145. package/dist/cli/chunks/{chunk-JBQ4WGB4.js → chunk-NVVF5ROM.js} +2 -2
  146. package/dist/cli/chunks/{chunk-HYACMUUR.js → chunk-OEZA7Q2Z.js} +2 -2
  147. package/dist/cli/chunks/{chunk-ELZ5SKEN.js → chunk-OFOFXJ3M.js} +2 -2
  148. package/dist/cli/chunks/{chunk-HN7HYUW6.js → chunk-OMRZUYXN.js} +9 -9
  149. package/dist/cli/chunks/{chunk-IIYXSWJN.js → chunk-P6YMECV2.js} +2 -2
  150. package/dist/cli/chunks/{chunk-R2LWLZ3Y.js → chunk-PEEN4AAK.js} +1 -1
  151. package/dist/cli/chunks/{chunk-4EAAHMVM.js → chunk-PRJUO2OQ.js} +2 -2
  152. package/dist/cli/chunks/{chunk-LFEBTWFS.js → chunk-PYTXZMXR.js} +2 -2
  153. package/dist/cli/chunks/{chunk-I25KIHQE.js → chunk-Q2ZBPOUX.js} +1 -1
  154. package/dist/cli/chunks/{chunk-76UL224Z.js → chunk-QHATTMJC.js} +2 -2
  155. package/dist/cli/chunks/{chunk-KJZU3E5G.js → chunk-QMNAELZG.js} +2 -2
  156. package/dist/cli/chunks/{chunk-3ZAGYTEC.js → chunk-QQLQEQJM.js} +2 -2
  157. package/dist/cli/chunks/{chunk-GOPE5OB5.js → chunk-QSA23PJ6.js} +1 -1
  158. package/dist/cli/chunks/{chunk-MVW7AACO.js → chunk-QTYTM7C7.js} +2 -2
  159. package/dist/cli/chunks/{chunk-6DBYVKGA.js → chunk-QZMBJ67L.js} +2 -2
  160. package/dist/cli/chunks/{chunk-S72TSJS4.js → chunk-R23PJGH7.js} +2 -2
  161. package/dist/cli/chunks/{chunk-YSUMQBMY.js → chunk-R5ZKFJ3H.js} +1 -1
  162. package/dist/cli/chunks/{chunk-JD3GH47Z.js → chunk-RLLDZNLF.js} +2 -2
  163. package/dist/cli/chunks/{chunk-F5VLJFVU.js → chunk-RZYTJSQT.js} +1 -1
  164. package/dist/cli/chunks/{chunk-JCROLOP6.js → chunk-S6VT7VAO.js} +2 -2
  165. package/dist/cli/chunks/{chunk-237NNDKL.js → chunk-SVLO2DVL.js} +2 -2
  166. package/dist/cli/chunks/{chunk-A2QLTNN5.js → chunk-TTENF6AH.js} +1 -1
  167. package/dist/cli/chunks/{chunk-CG3HIYF4.js → chunk-UEKDDUGV.js} +2 -2
  168. package/dist/cli/chunks/{chunk-E4D36LGH.js → chunk-UYKIPSRX.js} +1 -1
  169. package/dist/cli/chunks/{chunk-M2JBQVBP.js → chunk-VIIUJRKA.js} +2 -2
  170. package/dist/cli/chunks/chunk-VRH3YLO2.js +2 -0
  171. package/dist/cli/chunks/{chunk-I7OH6RAC.js → chunk-VTX4NAWB.js} +2 -2
  172. package/dist/cli/chunks/{chunk-P2H5ARHM.js → chunk-VWHALAEO.js} +1 -1
  173. package/dist/cli/chunks/{chunk-OZTSMI7P.js → chunk-W4VDPHWC.js} +1 -1
  174. package/dist/cli/chunks/{chunk-266SKKFM.js → chunk-W57I57M4.js} +2 -2
  175. package/dist/cli/chunks/{chunk-YOKRSFGA.js → chunk-WDWIJDQR.js} +2 -2
  176. package/dist/cli/chunks/{chunk-IZTUAI5T.js → chunk-WEJJWJ5M.js} +2 -2
  177. package/dist/cli/chunks/{chunk-ETXK25IY.js → chunk-WZR4CKR4.js} +1 -1
  178. package/dist/cli/chunks/{chunk-WJDOOT2M.js → chunk-XZ2JYMFT.js} +2 -2
  179. package/dist/cli/chunks/{chunk-SDMGF3KD.js → chunk-YISXT54V.js} +2 -2
  180. package/dist/cli/chunks/{chunk-N2L7RWNX.js → chunk-YRORPSPA.js} +2 -2
  181. package/dist/cli/chunks/{chunk-JNJYWWBG.js → chunk-YXE67VME.js} +6 -6
  182. package/dist/cli/chunks/{chunk-SSURIMCL.js → chunk-Z7AFNZMI.js} +2 -2
  183. package/dist/cli/chunks/{chunk-4GMV6Z7Y.js → chunk-ZEUORIH2.js} +2 -2
  184. package/dist/cli/chunks/{chunk-VHZ653XS.js → chunk-ZKXA4VBK.js} +3 -3
  185. package/dist/cli/chunks/{chunk-6KWX7A3R.js → chunk-ZTI3BATG.js} +2 -2
  186. package/dist/cli/chunks/{ci-A5ZXOEC4.js → ci-4QYE6JBM.js} +2 -2
  187. package/dist/cli/chunks/{ci-output-S47BMRYC.js → ci-output-MV75HUK7.js} +2 -2
  188. package/dist/cli/chunks/{claude-flow-setup-F5WBEBVK.js → claude-flow-setup-CZITY7SG.js} +2 -2
  189. package/dist/cli/chunks/client-VXVVUQDV.js +2 -0
  190. package/dist/cli/chunks/{cline-installer-HLKR4QDR.js → cline-installer-ZLQKCPFF.js} +2 -2
  191. package/dist/cli/chunks/{code-MTZWS6JT.js → code-NYEXOJVP.js} +2 -2
  192. package/dist/cli/chunks/{code-index-extractor-BALTZ2WQ.js → code-index-extractor-TITXUC44.js} +2 -2
  193. package/dist/cli/chunks/{codex-installer-LI2VIGET.js → codex-installer-TWT4LIL2.js} +2 -2
  194. package/dist/cli/chunks/{completions-TOF4GTNF.js → completions-2KNV2MZG.js} +2 -2
  195. package/dist/cli/chunks/{complexity-analyzer-IPFXIT6T.js → complexity-analyzer-2U3OVRDX.js} +2 -2
  196. package/dist/cli/chunks/{continuedev-installer-KWI66RBI.js → continuedev-installer-BWQBRVTC.js} +2 -2
  197. package/dist/cli/chunks/{copilot-installer-REFOE6UF.js → copilot-installer-CYN33NMG.js} +2 -2
  198. package/dist/cli/chunks/{cost-tracker-M2MZQXCN.js → cost-tracker-2GUCBYLK.js} +2 -2
  199. package/dist/cli/chunks/{coverage-UR2XSJCR.js → coverage-BAVD66VL.js} +3 -3
  200. package/dist/cli/chunks/cross-domain-router-HUJG6CFC.js +2 -0
  201. package/dist/cli/chunks/{cursor-installer-X4PXCVYH.js → cursor-installer-ZQAUD47B.js} +2 -2
  202. package/dist/cli/chunks/{daemon-5R6ZEEBB.js → daemon-VY2LZPIM.js} +3 -3
  203. package/dist/cli/chunks/{dag-attention-scheduler-RUY2RJZA.js → dag-attention-scheduler-JNQWWXSW.js} +2 -2
  204. package/dist/cli/chunks/{detect-PX2AYBHM.js → detect-Y7BBW4LI.js} +2 -2
  205. package/dist/cli/chunks/{domain-handler-5JXWEO3E.js → domain-handler-473WNSR2.js} +2 -2
  206. package/dist/cli/chunks/{domain-transfer-6M2YLBJY.js → domain-transfer-R4VK7CRR.js} +2 -2
  207. package/dist/cli/chunks/dream-QQDRI2EQ.js +2 -0
  208. package/dist/cli/chunks/esm-node-Y3HIFLTX.js +2 -0
  209. package/dist/cli/chunks/{eval-L6ZBG462.js → eval-TJAZGRCM.js} +2 -2
  210. package/dist/cli/chunks/{fast-paths-WIFDALFK.js → fast-paths-LMN542IB.js} +2 -2
  211. package/dist/cli/chunks/{feature-flags-YLBXFUCN.js → feature-flags-IMFZ7KED.js} +2 -2
  212. package/dist/cli/chunks/{feature-flags-GRHF5MTK.js → feature-flags-WMXIDTXL.js} +2 -2
  213. package/dist/cli/chunks/{file-discovery-4HXUB4HN.js → file-discovery-GXXWQJV3.js} +2 -2
  214. package/dist/cli/chunks/{fleet-RPLJXOEP.js → fleet-WIC7RHJV.js} +3 -3
  215. package/dist/cli/chunks/{gnn-wrapper-2D5IOGAT.js → gnn-wrapper-PVKCXV25.js} +2 -2
  216. package/dist/cli/chunks/{heartbeat-handler-D5SWZZGA.js → heartbeat-handler-BJ6ZZP7Q.js} +4 -4
  217. package/dist/cli/chunks/{heartbeat-scheduler-WSG4Y3M2.js → heartbeat-scheduler-3SQXTFYU.js} +2 -2
  218. package/dist/cli/chunks/hnsw-adapter-VKS7ORL2.js +2 -0
  219. package/dist/cli/chunks/hnsw-index-GPUBY6EQ.js +2 -0
  220. package/dist/cli/chunks/{hnsw-legacy-bridge-UH6RWE74.js → hnsw-legacy-bridge-23HFWIPK.js} +2 -2
  221. package/dist/cli/chunks/{hnswlib-node-BJ4ZJPMP.js → hnswlib-node-4GRFMUPD.js} +2 -2
  222. package/dist/cli/chunks/{hooks-KGDQNB5T.js → hooks-IXH5454I.js} +6 -6
  223. package/dist/cli/chunks/{hypergraph-engine-LARQCK7V.js → hypergraph-engine-TEQMJFJJ.js} +2 -2
  224. package/dist/cli/chunks/{hypergraph-handler-RACF4AOX.js → hypergraph-handler-3ECUWIG3.js} +3 -3
  225. package/dist/cli/chunks/impact-analyzer-D6MBGRKX.js +2 -0
  226. package/dist/cli/chunks/{init-handler-64AOFMJD.js → init-handler-TZRKW3NZ.js} +6 -6
  227. package/dist/cli/chunks/init-wizard-S6P2MFJF.js +2 -0
  228. package/dist/cli/chunks/kernel-EFDDMNXJ.js +2 -0
  229. package/dist/cli/chunks/{kilocode-installer-4ICIP6QN.js → kilocode-installer-IPH3O3ZS.js} +2 -2
  230. package/dist/cli/chunks/{kiro-installer-J2GOV2OB.js → kiro-installer-VROMOOQO.js} +2 -2
  231. package/dist/cli/chunks/knowledge-graph-4PM4DFH3.js +2 -0
  232. package/dist/cli/chunks/{learning-QD4JVH3K.js → learning-JYQLD66S.js} +3 -3
  233. package/dist/cli/chunks/{llm-router-4K4IT2PQ.js → llm-router-CIICNICY.js} +2 -2
  234. package/dist/cli/chunks/{load-EXKUJMBK.js → load-DMAQB4NC.js} +2 -2
  235. package/dist/cli/chunks/load-test-PPSWF3TO.js +2 -0
  236. package/dist/cli/chunks/{mcp-NSNDZSMH.js → mcp-K6CSUBMU.js} +2 -2
  237. package/dist/cli/chunks/{memory-63JTNVZN.js → memory-5BSXKHSK.js} +5 -5
  238. package/dist/cli/chunks/memory-backend-3E6BA2JU.js +2 -0
  239. package/dist/cli/chunks/{memory-handlers-2335MVQJ.js → memory-handlers-APOLXPNH.js} +2 -2
  240. package/dist/cli/chunks/{opencode-installer-244LFSPN.js → opencode-installer-IUWO2QV6.js} +2 -2
  241. package/dist/cli/chunks/{orchestrator-TZB457J6.js → orchestrator-Z2EM76CR.js} +22 -19
  242. package/dist/cli/chunks/{pipeline-YLBD2Z5Q.js → pipeline-OL5SI2RI.js} +2 -2
  243. package/dist/cli/chunks/{platform-53PWFZSE.js → platform-VNJIKIHZ.js} +2 -2
  244. package/dist/cli/chunks/{plugin-6GUQEFJU.js → plugin-SJJUE47D.js} +2 -2
  245. package/dist/cli/chunks/{prime-radiant-advanced-wasm-VCOK7FV5.js → prime-radiant-advanced-wasm-ZLVTCNSH.js} +2 -2
  246. package/dist/cli/chunks/protocol-executor-2RD52J5J.js +2 -0
  247. package/dist/cli/chunks/{protocol-handler-25UEGTE2.js → protocol-handler-HTX44YTW.js} +2 -2
  248. package/dist/cli/chunks/{prove-CTOU5F6G.js → prove-MGFLVZNS.js} +2 -2
  249. package/dist/cli/chunks/qe-reasoning-bank-OGKT52EN.js +2 -0
  250. package/dist/cli/chunks/{quality-PB7H5UEF.js → quality-FMFKPICZ.js} +2 -2
  251. package/dist/cli/chunks/queen-coordinator-B63YXNI6.js +2 -0
  252. package/dist/cli/chunks/{real-embeddings-RWWYCIE5.js → real-embeddings-2BMEEOA2.js} +2 -2
  253. package/dist/cli/chunks/{roocode-installer-U4AGYVKL.js → roocode-installer-2PA3B5JI.js} +2 -2
  254. package/dist/cli/chunks/router-NDQCJQC6.js +2 -0
  255. package/dist/cli/chunks/routing-feedback-PSN2RLDO.js +2 -0
  256. package/dist/cli/chunks/{routing-handler-NTDKDEBE.js → routing-handler-SNGSQ757.js} +2 -2
  257. package/dist/cli/chunks/{ruvector-commands-RQKOLQSW.js → ruvector-commands-54MYLF63.js} +2 -2
  258. package/dist/cli/chunks/{rvf-dual-writer-6EZ7S7OG.js → rvf-dual-writer-6Q44XJOJ.js} +2 -2
  259. package/dist/cli/chunks/{rvf-migration-adapter-EBTV6FV2.js → rvf-migration-adapter-JECN625C.js} +2 -2
  260. package/dist/cli/chunks/{rvf-migration-coordinator-MERU7VLY.js → rvf-migration-coordinator-MEAVIHQY.js} +2 -2
  261. package/dist/cli/chunks/rvf-native-adapter-F56HQKLS.js +2 -0
  262. package/dist/cli/chunks/safe-db-LMRMNROL.js +2 -0
  263. package/dist/cli/chunks/schedule-OZSUYPPC.js +2 -0
  264. package/dist/cli/chunks/scheduler-GFXCQ6ZA.js +2 -0
  265. package/dist/cli/chunks/{security-JPDLGHMC.js → security-CXLXTNIV.js} +3 -3
  266. package/dist/cli/chunks/shared-rvf-adapter-RZPF4WWK.js +2 -0
  267. package/dist/cli/chunks/{shared-rvf-dual-writer-7OGLQE5Y.js → shared-rvf-dual-writer-SOQDKE6S.js} +2 -2
  268. package/dist/cli/chunks/sqlite-persistence-VP67CJPK.js +2 -0
  269. package/dist/cli/chunks/{status-handler-3TI3DHEL.js → status-handler-NNEF4SQV.js} +2 -2
  270. package/dist/cli/chunks/{structural-health-WCZKXVWS.js → structural-health-FY6QIA55.js} +2 -2
  271. package/dist/cli/chunks/{sync-AM5T4GYO.js → sync-2QMSZ67Q.js} +2 -2
  272. package/dist/cli/chunks/{task-handler-VHDTXPVP.js → task-handler-GZJPE2QW.js} +2 -2
  273. package/dist/cli/chunks/{task-handlers-GEJ36WNB.js → task-handlers-AHM37D4I.js} +2 -2
  274. package/dist/cli/chunks/{test-G6P5XGHM.js → test-JVA2S2R2.js} +4 -4
  275. package/dist/cli/chunks/{test-scheduling-37RBUN4E.js → test-scheduling-PRMP4H6X.js} +3 -3
  276. package/dist/cli/chunks/{token-bootstrap-JPE3LWXQ.js → token-bootstrap-YJEHCBV2.js} +2 -2
  277. package/dist/cli/chunks/{token-usage-5XGVBLFR.js → token-usage-G73L32OF.js} +2 -2
  278. package/dist/cli/chunks/{transformers-JTKWAZJU.js → transformers-U3TSLEGO.js} +2 -2
  279. package/dist/cli/chunks/{tree-sitter-wasm-parser-KW2GWIIQ.js → tree-sitter-wasm-parser-QXP2MNSX.js} +2 -2
  280. package/dist/cli/chunks/{types-7R72BACI.js → types-BIQ7O5VR.js} +2 -2
  281. package/dist/cli/chunks/unified-memory-JB4KPMPI.js +2 -0
  282. package/dist/cli/chunks/unified-memory-hnsw-RPSZZIWP.js +2 -0
  283. package/dist/cli/chunks/unified-persistence-L23T4C5C.js +2 -0
  284. package/dist/cli/chunks/{validate-TYB4ZTUL.js → validate-CTBEA4BZ.js} +2 -2
  285. package/dist/cli/chunks/{validate-swarm-3TFI6PLT.js → validate-swarm-PHT6XW3A.js} +2 -2
  286. package/dist/cli/chunks/{vibium-3YELURJT.js → vibium-CRCYAH3V.js} +2 -2
  287. package/dist/cli/chunks/visual-security-F2I524IQ.js +2 -0
  288. package/dist/cli/chunks/{web-tree-sitter-7Q77A27Y.js → web-tree-sitter-2MH3G7K7.js} +2 -2
  289. package/dist/cli/chunks/{windsurf-installer-ASARRM2X.js → windsurf-installer-LBRNYFSI.js} +2 -2
  290. package/dist/cli/chunks/witness-chain-CN6FCWRY.js +2 -0
  291. package/dist/cli/chunks/{witness-chain-WZ6PNXEY.js → witness-chain-HNFQLO7Q.js} +2 -2
  292. package/dist/cli/chunks/{workflow-JDTEE6TY.js → workflow-DNAF6BQ2.js} +4 -4
  293. package/dist/cli/chunks/workflow-orchestrator-JJBCCNYI.js +2 -0
  294. package/dist/cli/chunks/{wrappers-X7WZLBZD.js → wrappers-U7AO6ZZN.js} +2 -2
  295. package/dist/init/browser-engine-installer.d.ts +60 -0
  296. package/dist/init/browser-engine-installer.js +92 -0
  297. package/dist/init/phases/09-assets.d.ts +2 -0
  298. package/dist/init/phases/09-assets.js +65 -0
  299. package/dist/init/skills-installer.js +1 -0
  300. package/dist/mcp/bundle.js +1 -1
  301. package/package.json +1 -1
  302. package/dist/cli/chunks/adapter-D4XQUIJD.js +0 -2
  303. package/dist/cli/chunks/aqe-learning-engine-CGIWYLIP.js +0 -2
  304. package/dist/cli/chunks/base-BYVP2STR.js +0 -2
  305. package/dist/cli/chunks/browser-workflow-PC4N5TKL.js +0 -2
  306. package/dist/cli/chunks/chunk-OT4JADWW.js +0 -2
  307. package/dist/cli/chunks/client-56BU3GAX.js +0 -2
  308. package/dist/cli/chunks/cross-domain-router-XQT52BTB.js +0 -2
  309. package/dist/cli/chunks/dream-LFZCN5WK.js +0 -2
  310. package/dist/cli/chunks/esm-node-EBDIEPKS.js +0 -2
  311. package/dist/cli/chunks/hnsw-adapter-BMXTVGZB.js +0 -2
  312. package/dist/cli/chunks/hnsw-index-YX6XLICT.js +0 -2
  313. package/dist/cli/chunks/impact-analyzer-MGSI2WBK.js +0 -2
  314. package/dist/cli/chunks/init-wizard-TBDWRRMC.js +0 -2
  315. package/dist/cli/chunks/kernel-NV7TO2FK.js +0 -2
  316. package/dist/cli/chunks/knowledge-graph-7REGYH6A.js +0 -2
  317. package/dist/cli/chunks/load-test-RYQK44TT.js +0 -2
  318. package/dist/cli/chunks/memory-backend-3EBE2DEX.js +0 -2
  319. package/dist/cli/chunks/protocol-executor-MR37S7GX.js +0 -2
  320. package/dist/cli/chunks/qe-reasoning-bank-DANGLPTH.js +0 -2
  321. package/dist/cli/chunks/queen-coordinator-4YJPYF5F.js +0 -2
  322. package/dist/cli/chunks/router-F4IPY4RQ.js +0 -2
  323. package/dist/cli/chunks/routing-feedback-VGHFIJ5S.js +0 -2
  324. package/dist/cli/chunks/rvf-native-adapter-2P75WF5A.js +0 -2
  325. package/dist/cli/chunks/safe-db-47NEO2RS.js +0 -2
  326. package/dist/cli/chunks/schedule-L5GJW25Z.js +0 -2
  327. package/dist/cli/chunks/scheduler-NGGGSZMO.js +0 -2
  328. package/dist/cli/chunks/shared-rvf-adapter-NKNTYGHO.js +0 -2
  329. package/dist/cli/chunks/sqlite-persistence-TE2ZRHKA.js +0 -2
  330. package/dist/cli/chunks/unified-memory-KSBLUZT4.js +0 -2
  331. package/dist/cli/chunks/unified-memory-hnsw-V3EOMQIZ.js +0 -2
  332. package/dist/cli/chunks/unified-persistence-URIRJ4BM.js +0 -2
  333. package/dist/cli/chunks/visual-security-DJOOVCBZ.js +0 -2
  334. package/dist/cli/chunks/witness-chain-ZWJUCXCJ.js +0 -2
  335. package/dist/cli/chunks/workflow-orchestrator-5CKA6Q74.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.9.8");process.exit(0)}
2
- import{a as p,b as A,c as L}from"./chunk-PG7CZ6Q4.js";var S={reflexThreshold:.1,retrievalThreshold:.4,heavyThreshold:.7},M={enabled:!0,laneConfig:S,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"}},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"}},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}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}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}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,P]of Object.entries(i.confounders))this.addConfounder(g,P);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}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}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}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}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 R}from"node:path";import{readFileSync as X,existsSync as F}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 R(x(i),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),R(process.cwd(),"node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm")].filter(i=>i!==null);for(let i of t)if(F(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-VCOK7FV5.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 R(x(a),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),R(x(K(import.meta.url)),"../../../../node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm"),R(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(F(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.9.9");process.exit(0)}
2
+ import{a as p,b as A,c as L}from"./chunk-BVOGMK6N.js";var S={reflexThreshold:.1,retrievalThreshold:.4,heavyThreshold:.7},M={enabled:!0,laneConfig:S,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"}},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"}},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}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}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}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,P]of Object.entries(i.confounders))this.addConfounder(g,P);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}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}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}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}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 R}from"node:path";import{readFileSync as X,existsSync as F}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 R(x(i),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),R(process.cwd(),"node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm")].filter(i=>i!==null);for(let i of t)if(F(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-ZLVTCNSH.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 R(x(a),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),R(x(K(import.meta.url)),"../../../../node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm"),R(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(F(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:{...S}};export{Q as a,J as b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.8");process.exit(0)}
2
- import{h as s,k as o,m as c,o as m}from"./chunk-BZB5D4BO.js";import{a,c as d}from"./chunk-PG7CZ6Q4.js";import{a as r,e as l}from"./chunk-6DBYVKGA.js";d();m();l();var u={dbPath:s.dbPath,walMode:!0,mmapSize:r.MMAP_SIZE_BYTES,cacheSize:r.CACHE_SIZE_KB,busyTimeout:r.BUSY_TIMEOUT_MS},n=class e{static instance=null;static instancePromise=null;unifiedMemory=null;config;initialized=!1;initPromise=null;constructor(i){this.config={...u,...i}}static getInstance(i){return e.instance||(e.instance=new e(i)),e.instance}static async getInstanceAsync(i){return e.instance?.initialized?e.instance:(e.instancePromise||(e.instancePromise=(async()=>{let t=e.getInstance(i);return await t.initialize(),t})()),e.instancePromise)}static resetInstance(){e.instance&&(e.instance.close(),e.instance=null),e.instancePromise=null,c()}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{let i={dbPath:this.config.dbPath,walMode:this.config.walMode,busyTimeout:this.config.busyTimeout,mmapSize:this.config.mmapSize,cacheSize:this.config.cacheSize};this.unifiedMemory=o(i),await this.unifiedMemory.initialize(),this.initialized=!0,console.log(`[UnifiedPersistence] Initialized via UnifiedMemoryManager: ${this.config.dbPath}`)}catch(i){throw this.initPromise=null,new Error(`Failed to initialize UnifiedPersistenceManager: ${a(i)}`)}}getDatabase(){if(!this.unifiedMemory||!this.initialized)throw new Error("UnifiedPersistenceManager not initialized");return this.unifiedMemory.getDatabase()}isInitialized(){return this.initialized}getDbPath(){return this.config.dbPath}prepare(i,t){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.prepare(i,t)}transaction(i){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.transaction(i)}getStats(){if(!this.unifiedMemory)throw new Error("Database not initialized");let i=this.unifiedMemory.getStats();return{tables:i.tables,fileSize:i.fileSize,walSize:i.walSize}}vacuum(){this.getDatabase().exec("VACUUM")}checkpoint(){this.getDatabase().pragma("wal_checkpoint(TRUNCATE)")}close(){this.initialized=!1,console.log("[UnifiedPersistence] Facade closed")}};function g(e){return n.getInstance(e)}async function U(e){let i=g(e);return await i.initialize(),i}function z(){n.resetInstance()}var f=!1;function h(){if(f)return;f=!0;let e=()=>{try{let i=n.instance;i&&i.close()}catch(i){console.debug("[UnifiedPersistence] Cleanup error:",i instanceof Error?i.message:i)}};process.on("beforeExit",e),process.on("SIGINT",()=>{e(),process.exit(0)}),process.on("SIGTERM",()=>{e(),process.exit(0)})}h();export{u as a,n as b,g as c,U as d,z as e};
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.9.9");process.exit(0)}
2
+ import{h as s,k as o,m as c,o as m}from"./chunk-MUIJVPGB.js";import{a,c as d}from"./chunk-BVOGMK6N.js";import{a as r,e as l}from"./chunk-QZMBJ67L.js";d();m();l();var u={dbPath:s.dbPath,walMode:!0,mmapSize:r.MMAP_SIZE_BYTES,cacheSize:r.CACHE_SIZE_KB,busyTimeout:r.BUSY_TIMEOUT_MS},n=class e{static instance=null;static instancePromise=null;unifiedMemory=null;config;initialized=!1;initPromise=null;constructor(i){this.config={...u,...i}}static getInstance(i){return e.instance||(e.instance=new e(i)),e.instance}static async getInstanceAsync(i){return e.instance?.initialized?e.instance:(e.instancePromise||(e.instancePromise=(async()=>{let t=e.getInstance(i);return await t.initialize(),t})()),e.instancePromise)}static resetInstance(){e.instance&&(e.instance.close(),e.instance=null),e.instancePromise=null,c()}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{let i={dbPath:this.config.dbPath,walMode:this.config.walMode,busyTimeout:this.config.busyTimeout,mmapSize:this.config.mmapSize,cacheSize:this.config.cacheSize};this.unifiedMemory=o(i),await this.unifiedMemory.initialize(),this.initialized=!0,console.log(`[UnifiedPersistence] Initialized via UnifiedMemoryManager: ${this.config.dbPath}`)}catch(i){throw this.initPromise=null,new Error(`Failed to initialize UnifiedPersistenceManager: ${a(i)}`)}}getDatabase(){if(!this.unifiedMemory||!this.initialized)throw new Error("UnifiedPersistenceManager not initialized");return this.unifiedMemory.getDatabase()}isInitialized(){return this.initialized}getDbPath(){return this.config.dbPath}prepare(i,t){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.prepare(i,t)}transaction(i){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.transaction(i)}getStats(){if(!this.unifiedMemory)throw new Error("Database not initialized");let i=this.unifiedMemory.getStats();return{tables:i.tables,fileSize:i.fileSize,walSize:i.walSize}}vacuum(){this.getDatabase().exec("VACUUM")}checkpoint(){this.getDatabase().pragma("wal_checkpoint(TRUNCATE)")}close(){this.initialized=!1,console.log("[UnifiedPersistence] Facade closed")}};function g(e){return n.getInstance(e)}async function U(e){let i=g(e);return await i.initialize(),i}function z(){n.resetInstance()}var f=!1;function h(){if(f)return;f=!0;let e=()=>{try{let i=n.instance;i&&i.close()}catch(i){console.debug("[UnifiedPersistence] Cleanup error:",i instanceof Error?i.message:i)}};process.on("beforeExit",e),process.on("SIGINT",()=>{e(),process.exit(0)}),process.on("SIGTERM",()=>{e(),process.exit(0)})}h();export{u as a,n as b,g as c,U as d,z as e};
@@ -1,12 +1,12 @@
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.9.8");process.exit(0)}
2
- import{a as E}from"./chunk-UGJNR52C.js";import{a as b}from"./chunk-OT4JADWW.js";import{c as y}from"./chunk-CG3HIYF4.js";import{a as f,c as k}from"./chunk-PG7CZ6Q4.js";k();b();var l=y.create("qe-hooks"),u={PreTestGeneration:"qe:pre-test-generation",PostTestGeneration:"qe:post-test-generation",TestExecutionResult:"qe:test-execution-result",PreCoverageAnalysis:"qe:pre-coverage-analysis",PostCoverageAnalysis:"qe:post-coverage-analysis",CoverageGapIdentified:"qe:coverage-gap-identified",QEAgentRouting:"qe:agent-routing",QEAgentCompletion:"qe:agent-completion",QualityScoreCalculated:"qe:quality-score",RiskAssessmentComplete:"qe:risk-assessment",PatternLearned:"qe:pattern-learned",PatternApplied:"qe:pattern-applied",PatternPromoted:"qe:pattern-promoted",PreCompaction:"qe:pre-compaction"};function h(i){return{[u.PreTestGeneration]:async t=>{let{targetFile:s,testType:a,framework:e,language:r}=t.data,n=await i.routeTask({task:`Generate ${a} tests for ${s}`,taskType:"test-generation",context:{framework:e,language:r,testType:a}});if(!n.success)return{success:!1,error:n.error.message};let o=[];try{let{getUnifiedMemory:c}=await import("./unified-memory-KSBLUZT4.js");o=c().getDatabase().prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.9");process.exit(0)}
2
+ import{a as E}from"./chunk-3FAEM5M7.js";import{a as b}from"./chunk-VRH3YLO2.js";import{c as y}from"./chunk-UEKDDUGV.js";import{a as f,c as k}from"./chunk-BVOGMK6N.js";k();b();var l=y.create("qe-hooks"),u={PreTestGeneration:"qe:pre-test-generation",PostTestGeneration:"qe:post-test-generation",TestExecutionResult:"qe:test-execution-result",PreCoverageAnalysis:"qe:pre-coverage-analysis",PostCoverageAnalysis:"qe:post-coverage-analysis",CoverageGapIdentified:"qe:coverage-gap-identified",QEAgentRouting:"qe:agent-routing",QEAgentCompletion:"qe:agent-completion",QualityScoreCalculated:"qe:quality-score",RiskAssessmentComplete:"qe:risk-assessment",PatternLearned:"qe:pattern-learned",PatternApplied:"qe:pattern-applied",PatternPromoted:"qe:pattern-promoted",PreCompaction:"qe:pre-compaction"};function h(i){return{[u.PreTestGeneration]:async t=>{let{targetFile:s,testType:a,framework:e,language:r}=t.data,n=await i.routeTask({task:`Generate ${a} tests for ${s}`,taskType:"test-generation",context:{framework:e,language:r,testType:a}});if(!n.success)return{success:!1,error:n.error.message};let o=[];try{let{getUnifiedMemory:c}=await import("./unified-memory-JB4KPMPI.js");o=c().getDatabase().prepare(`
3
3
  SELECT u.pattern_id, u.success, u.feedback
4
4
  FROM qe_pattern_usage u
5
5
  JOIN qe_patterns p ON u.pattern_id = p.id
6
6
  WHERE p.qe_domain = 'test-generation'
7
7
  ORDER BY u.created_at DESC
8
8
  LIMIT 10
9
- `).all()}catch{}return{success:!0,routing:n.value,guidance:n.value.guidance,data:{recommendedAgent:n.value.recommendedAgent,patterns:n.value.patterns.map(c=>c.id),recentExperiences:o}}},[u.PostTestGeneration]:async t=>{let{targetFile:s,generatedTests:a,testCount:e,framework:r,language:n,success:o,patternId:c}=t.data,p=0;if(c&&await i.recordOutcome({patternId:c,success:o,metrics:{testsPassed:0,testsFailed:0}}),o&&a&&e>0)try{(await i.storePattern({patternType:"test-template",name:`Generated tests for ${s.split("/").pop()}`,description:`Test template extracted from successful test generation for ${s}`,template:{type:"code",content:a,variables:[]},context:{framework:r,language:n,testType:"unit",tags:["generated","test-template",r,n]}})).success&&(p=1)}catch(d){l.debug("Pattern learning failed",{error:d instanceof Error?d.message:String(d)})}return{success:!0,patternsLearned:p,data:{learned:p>0}}},[u.TestExecutionResult]:async t=>{let{runId:s,patternId:a,passed:e,failed:r,duration:n,flaky:o}=t.data;if(a){let c=e+r>0?e/(e+r):0;await i.recordOutcome({patternId:a,success:c>.8&&!o,metrics:{testsPassed:e,testsFailed:r,executionTimeMs:n}})}return{success:!0,data:{runId:s,successRate:e+r>0?e/(e+r):0}}},[u.PreCoverageAnalysis]:async t=>{let{targetPath:s,currentCoverage:a}=t.data,e=await i.routeTask({task:`Analyze coverage gaps for ${s} (current: ${a}%)`,taskType:"analysis",domain:"coverage-analysis"});if(!e.success)return{success:!1,error:e.error.message};let r=[];try{let{getUnifiedMemory:n}=await import("./unified-memory-KSBLUZT4.js");r=n().getDatabase().prepare(`
9
+ `).all()}catch{}return{success:!0,routing:n.value,guidance:n.value.guidance,data:{recommendedAgent:n.value.recommendedAgent,patterns:n.value.patterns.map(c=>c.id),recentExperiences:o}}},[u.PostTestGeneration]:async t=>{let{targetFile:s,generatedTests:a,testCount:e,framework:r,language:n,success:o,patternId:c}=t.data,p=0;if(c&&await i.recordOutcome({patternId:c,success:o,metrics:{testsPassed:0,testsFailed:0}}),o&&a&&e>0)try{(await i.storePattern({patternType:"test-template",name:`Generated tests for ${s.split("/").pop()}`,description:`Test template extracted from successful test generation for ${s}`,template:{type:"code",content:a,variables:[]},context:{framework:r,language:n,testType:"unit",tags:["generated","test-template",r,n]}})).success&&(p=1)}catch(d){l.debug("Pattern learning failed",{error:d instanceof Error?d.message:String(d)})}return{success:!0,patternsLearned:p,data:{learned:p>0}}},[u.TestExecutionResult]:async t=>{let{runId:s,patternId:a,passed:e,failed:r,duration:n,flaky:o}=t.data;if(a){let c=e+r>0?e/(e+r):0;await i.recordOutcome({patternId:a,success:c>.8&&!o,metrics:{testsPassed:e,testsFailed:r,executionTimeMs:n}})}return{success:!0,data:{runId:s,successRate:e+r>0?e/(e+r):0}}},[u.PreCoverageAnalysis]:async t=>{let{targetPath:s,currentCoverage:a}=t.data,e=await i.routeTask({task:`Analyze coverage gaps for ${s} (current: ${a}%)`,taskType:"analysis",domain:"coverage-analysis"});if(!e.success)return{success:!1,error:e.error.message};let r=[];try{let{getUnifiedMemory:n}=await import("./unified-memory-JB4KPMPI.js");r=n().getDatabase().prepare(`
10
10
  SELECT u.pattern_id, u.success, u.feedback
11
11
  FROM qe_pattern_usage u
12
12
  JOIN qe_patterns p ON u.pattern_id = p.id
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.8");process.exit(0)}
2
- import{b as d,d as c}from"./chunk-VVNR4R22.js";import{a as l,c as g}from"./chunk-PG7CZ6Q4.js";g();c();import{existsSync as y,readFileSync as p}from"node:fs";import{join as o,dirname as u}from"node:path";import{fileURLToPath as m}from"node:url";var i=class extends Error{constructor(t,n,r){super(t);this.code=n;this.cause=r;this.name="PatternLoaderError"}},s=class a{static instance=null;config;patterns;isLoading=!1;constructor(e={}){this.config={basePath:e.basePath??this.getDefaultBasePath(),throwOnMissing:e.throwOnMissing??!1,validatePatterns:e.validatePatterns??!0},this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]}}static getInstance(e){return a.instance||(a.instance=new a(e)),a.instance}static resetInstance(){a.instance=null}getDefaultBasePath(){try{let e=import.meta.url,t=m(e),n=u(t),r=o(n,"..","..","..");return o(r,"assets","patterns")}catch{return o(process.cwd(),"assets","patterns")}}async loadPatterns(){if(!this.isLoading){this.isLoading=!0,this.patterns.errors=[];try{this.patterns.index=this.loadJsonFile("index.json");let[e,t,n,r]=await Promise.all([Promise.resolve(this.loadJsonFile("adr-051-booster-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-router-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-embedding-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-reasoning-patterns.json"))]);this.patterns.booster=e,this.patterns.router=t,this.patterns.embedding=n,this.patterns.reasoning=r,this.patterns.loadedAt=new Date,this.config.validatePatterns&&this.validateLoadedPatterns()}finally{this.isLoading=!1}}}loadJsonFile(e){let t=o(this.config.basePath,e);try{if(!y(t)){let r=`Pattern file not found: ${t}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"FILE_NOT_FOUND");return null}let n=p(t,"utf-8");return d(n)}catch(n){if(n instanceof i)throw n;let r=`Failed to load pattern file ${e}: ${l(n)}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"PARSE_ERROR",n instanceof Error?n:void 0);return null}}validateLoadedPatterns(){this.patterns.booster&&(Array.isArray(this.patterns.booster.patterns)||this.patterns.errors.push("Booster patterns file missing patterns array")),this.patterns.router&&(Array.isArray(this.patterns.router.patterns)||this.patterns.errors.push("Router patterns file missing patterns array")),this.patterns.embedding&&(Array.isArray(this.patterns.embedding.patterns)||this.patterns.errors.push("Embedding patterns file missing patterns array")),this.patterns.reasoning&&(Array.isArray(this.patterns.reasoning.patterns)||this.patterns.errors.push("Reasoning patterns file missing patterns array"))}async ensureLoaded(){this.patterns.loadedAt||await this.loadPatterns()}async getIndex(){return await this.ensureLoaded(),this.patterns.index}async getBoosterPatterns(){return await this.ensureLoaded(),this.patterns.booster}async getRouterPatterns(){return await this.ensureLoaded(),this.patterns.router}async getEmbeddingPatterns(){return await this.ensureLoaded(),this.patterns.embedding}async getReasoningPatterns(){return await this.ensureLoaded(),this.patterns.reasoning}async getBoosterPatternByKey(e){let t=await this.getBoosterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getRouterPatternByKey(e){let t=await this.getRouterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEmbeddingPatternByKey(e){let t=await this.getEmbeddingPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getReasoningPatternByKey(e){let t=await this.getReasoningPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEligibleBoosterTransforms(){let e=await this.getBoosterPatternByKey("booster-transform-eligibility");return e?e.eligibility_criteria.simple_transforms:[]}async getTierHierarchy(){let e=await this.getRouterPatternByKey("router-5tier-complexity");return e?e.tier_hierarchy:null}async getQualityGateThresholds(){let e=await this.getReasoningPatternByKey("reasoning-pattern-quality-gates");return e?e.gate_thresholds:null}isLoaded(){return this.patterns.loadedAt!==null}getLoadedAt(){return this.patterns.loadedAt}getErrors(){return[...this.patterns.errors]}async getStatistics(){let e=await this.getIndex();return e?e.pattern_statistics:null}async reload(){this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]},await this.loadPatterns()}async getAllPatterns(){return await this.ensureLoaded(),{...this.patterns}}};function x(){return s.getInstance()}export{x as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.9");process.exit(0)}
2
+ import{b as d,d as c}from"./chunk-MWZN4PYF.js";import{a as l,c as g}from"./chunk-BVOGMK6N.js";g();c();import{existsSync as y,readFileSync as p}from"node:fs";import{join as o,dirname as u}from"node:path";import{fileURLToPath as m}from"node:url";var i=class extends Error{constructor(t,n,r){super(t);this.code=n;this.cause=r;this.name="PatternLoaderError"}},s=class a{static instance=null;config;patterns;isLoading=!1;constructor(e={}){this.config={basePath:e.basePath??this.getDefaultBasePath(),throwOnMissing:e.throwOnMissing??!1,validatePatterns:e.validatePatterns??!0},this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]}}static getInstance(e){return a.instance||(a.instance=new a(e)),a.instance}static resetInstance(){a.instance=null}getDefaultBasePath(){try{let e=import.meta.url,t=m(e),n=u(t),r=o(n,"..","..","..");return o(r,"assets","patterns")}catch{return o(process.cwd(),"assets","patterns")}}async loadPatterns(){if(!this.isLoading){this.isLoading=!0,this.patterns.errors=[];try{this.patterns.index=this.loadJsonFile("index.json");let[e,t,n,r]=await Promise.all([Promise.resolve(this.loadJsonFile("adr-051-booster-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-router-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-embedding-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-reasoning-patterns.json"))]);this.patterns.booster=e,this.patterns.router=t,this.patterns.embedding=n,this.patterns.reasoning=r,this.patterns.loadedAt=new Date,this.config.validatePatterns&&this.validateLoadedPatterns()}finally{this.isLoading=!1}}}loadJsonFile(e){let t=o(this.config.basePath,e);try{if(!y(t)){let r=`Pattern file not found: ${t}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"FILE_NOT_FOUND");return null}let n=p(t,"utf-8");return d(n)}catch(n){if(n instanceof i)throw n;let r=`Failed to load pattern file ${e}: ${l(n)}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"PARSE_ERROR",n instanceof Error?n:void 0);return null}}validateLoadedPatterns(){this.patterns.booster&&(Array.isArray(this.patterns.booster.patterns)||this.patterns.errors.push("Booster patterns file missing patterns array")),this.patterns.router&&(Array.isArray(this.patterns.router.patterns)||this.patterns.errors.push("Router patterns file missing patterns array")),this.patterns.embedding&&(Array.isArray(this.patterns.embedding.patterns)||this.patterns.errors.push("Embedding patterns file missing patterns array")),this.patterns.reasoning&&(Array.isArray(this.patterns.reasoning.patterns)||this.patterns.errors.push("Reasoning patterns file missing patterns array"))}async ensureLoaded(){this.patterns.loadedAt||await this.loadPatterns()}async getIndex(){return await this.ensureLoaded(),this.patterns.index}async getBoosterPatterns(){return await this.ensureLoaded(),this.patterns.booster}async getRouterPatterns(){return await this.ensureLoaded(),this.patterns.router}async getEmbeddingPatterns(){return await this.ensureLoaded(),this.patterns.embedding}async getReasoningPatterns(){return await this.ensureLoaded(),this.patterns.reasoning}async getBoosterPatternByKey(e){let t=await this.getBoosterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getRouterPatternByKey(e){let t=await this.getRouterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEmbeddingPatternByKey(e){let t=await this.getEmbeddingPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getReasoningPatternByKey(e){let t=await this.getReasoningPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEligibleBoosterTransforms(){let e=await this.getBoosterPatternByKey("booster-transform-eligibility");return e?e.eligibility_criteria.simple_transforms:[]}async getTierHierarchy(){let e=await this.getRouterPatternByKey("router-5tier-complexity");return e?e.tier_hierarchy:null}async getQualityGateThresholds(){let e=await this.getReasoningPatternByKey("reasoning-pattern-quality-gates");return e?e.gate_thresholds:null}isLoaded(){return this.patterns.loadedAt!==null}getLoadedAt(){return this.patterns.loadedAt}getErrors(){return[...this.patterns.errors]}async getStatistics(){let e=await this.getIndex();return e?e.pattern_statistics:null}async reload(){this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]},await this.loadPatterns()}async getAllPatterns(){return await this.ensureLoaded(),{...this.patterns}}};function x(){return s.getInstance()}export{x as a};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.8");process.exit(0)}
2
- import{a as D}from"./chunk-HE2NWYHK.js";import{c as x,d as $}from"./chunk-DLKRK2GU.js";import{a as j}from"./chunk-5TGK7VTS.js";import"./chunk-R2LWLZ3Y.js";import"./chunk-E4D36LGH.js";import{Command as U}from"commander";import o from"chalk";import*as I from"fs";import*as p from"path";import*as F from"fs";import*as R from"path";var P={version:"1",name:"aqe-ci",phases:[{name:"Test Generation",type:"test",enabled:!0,config:{target:".",framework:"vitest",type:"unit"},continueOnFailure:!1,timeout:300},{name:"Coverage Analysis",type:"coverage",enabled:!0,config:{target:".",threshold:80},continueOnFailure:!0,timeout:300},{name:"Security Scan",type:"security",enabled:!0,config:{sast:!0},continueOnFailure:!0,timeout:300},{name:"Quality Gate",type:"quality-gate",enabled:!0,config:{},continueOnFailure:!1,timeout:60}],output:{format:"json",directory:".aqe-ci-output",combinedReport:!0},qualityGate:{enforced:!0,thresholds:{coverage:80,security:"medium",quality:70}}},Q=[".aqe-ci.yml",".aqe-ci.yaml","aqe-ci.yml","aqe-ci.yaml"];function G(s=process.cwd()){let n=R.resolve(s);for(let r=0;r<10;r++){for(let a of Q){let e=R.join(n,a);if(F.existsSync(e))return e}let l=R.dirname(n);if(l===n)break;n=l}return null}function T(s){if(!F.existsSync(s))return{success:!1,errors:[`Config file not found: ${s}`]};let n;try{n=F.readFileSync(s,"utf-8")}catch(r){return{success:!1,errors:[`Failed to read config: ${r}`]}}return N(n,s)}function N(s,n){let r=[],l;try{l=j(s)}catch(e){return{success:!1,errors:[`Invalid YAML: ${e}`]}}let a={version:l.version||P.version,name:l.name||P.name,phases:[],output:{...P.output},qualityGate:{...P.qualityGate,thresholds:{...P.qualityGate.thresholds}}};if(l.output&&typeof l.output=="object"){let e=l.output;e.format&&(a.output.format=e.format),e.directory&&(a.output.directory=e.directory),e.combined_report!==void 0&&(a.output.combinedReport=e.combined_report)}if(l.quality_gate&&typeof l.quality_gate=="object"){let e=l.quality_gate;if(e.enforced!==void 0&&(a.qualityGate.enforced=e.enforced),e.thresholds&&typeof e.thresholds=="object"){let t=e.thresholds;t.coverage!==void 0&&(a.qualityGate.thresholds.coverage=t.coverage),t.security!==void 0&&(a.qualityGate.thresholds.security=t.security),t.quality!==void 0&&(a.qualityGate.thresholds.quality=t.quality)}}if(l.phases&&Array.isArray(l.phases))for(let e=0;e<l.phases.length;e++){let t=l.phases[e];if(!t.name){r.push(`Phase ${e+1} must have a "name" field`);continue}if(!t.type){r.push(`Phase "${t.name}" must have a "type" field`);continue}let i=["test","coverage","security","quality-gate","code-intelligence","custom"];if(!i.includes(t.type)){r.push(`Phase "${t.name}" has invalid type "${t.type}". Valid: ${i.join(", ")}`);continue}let h={name:t.name,type:t.type,enabled:t.enabled!==!1,config:t.config||{},continueOnFailure:t.continue_on_failure||!1,timeout:t.timeout||300};a.phases.push(h)}else a.phases=[...P.phases];return a.phases.length===0&&r.push("Config must have at least one phase"),r.length>0?{success:!1,config:a,errors:r}:{success:!0,config:a,errors:[],configPath:n}}function E(){return{...P,phases:P.phases.map(s=>({...s,config:{...s.config}})),output:{...P.output},qualityGate:{...P.qualityGate,thresholds:{...P.qualityGate.thresholds}}}}async function W(s,n,r,l){let a=Date.now(),e=[];if(!s.enabled)return{phase:s.name,type:s.type,status:"skipped",duration:0,exitCode:0,summary:"Phase disabled",artifacts:[]};try{let t={},i="passed",h="";switch(s.type){case"test":{let f=await n.kernel.getDomainAPIAsync("test-generation");if(!f)return A(s,a,"failed",1,"Test generation domain not available",e);let C=s.config.target||".",{walkSourceFiles:m}=await import("./file-discovery-4HXUB4HN.js"),w=p.resolve(C),v=m(w,{includeTests:!1}),y=await f.generateTests({sourceFiles:v,testType:s.config.type||"unit",framework:s.config.framework||"vitest",coverageTarget:80});if(y.success&&y.value){let g=y.value;t={testsGenerated:g.tests.length,coverageEstimate:g.coverageEstimate},h=`Generated ${g.tests.length} tests (est. ${g.coverageEstimate}% coverage)`;let d=p.join(r,"test-generation.json");I.writeFileSync(d,$(g),"utf-8"),e.push(d)}else i="failed",h=y.error?.message||"Test generation failed";break}case"coverage":{let f=await n.kernel.getDomainAPIAsync("coverage-analysis");if(!f)return A(s,a,"failed",1,"Coverage analysis domain not available",e);let C=s.config.target||".",m=s.config.threshold||80,{walkSourceFiles:w}=await import("./file-discovery-4HXUB4HN.js"),v=p.resolve(C),y=w(v,{includeTests:!1}),g=D(y),d=await f.analyze({coverageData:g,threshold:m,includeFileDetails:!0});if(d.success&&d.value){let b=d.value;t={...b.summary,meetsThreshold:b.meetsThreshold,threshold:m},i=b.meetsThreshold?"passed":"warning",h=`Line: ${b.summary.line}%, Branch: ${b.summary.branch}% \u2014 ${b.meetsThreshold?"meets":"below"} ${m}% threshold`;let q=p.join(r,"coverage.json");I.writeFileSync(q,$(d.value),"utf-8"),e.push(q)}else i="failed",h=d.error?.message||"Coverage analysis failed";break}case"security":{let f=await n.kernel.getDomainAPIAsync("security-compliance");if(!f)return A(s,a,"failed",1,"Security domain not available",e);let C=s.config.target||".",{walkSourceFiles:m}=await import("./file-discovery-4HXUB4HN.js"),w=p.resolve(C),v=m(w,{includeTests:!0}),y=await f.runSASTScan(v);if(y.success&&y.value){let g=y.value,d=g.vulnerabilities||[],b=d.filter(S=>S.severity==="high"||S.severity==="critical").length;t={vulnerabilities:d.length,high:b},i=b>0?"failed":d.length>0?"warning":"passed",h=d.length===0?"No vulnerabilities found":`${d.length} vulnerabilities (${b} high/critical)`;let{toSARIF:q}=await import("./ci-output-S47BMRYC.js"),c=p.join(r,"security.sarif");I.writeFileSync(c,q({vulnerabilities:d,target:C,scanType:"SAST"}),"utf-8"),e.push(c);let u=p.join(r,"security.json");I.writeFileSync(u,$(g),"utf-8"),e.push(u)}else i="failed",h=y.error?.message||"Security scan failed";break}case"quality-gate":{let f=await n.kernel.getDomainAPIAsync("quality-assessment");if(!f)return A(s,a,"failed",1,"Quality assessment domain not available",e);let C=await f.evaluate({runGate:!0,includeAdvice:!0});if(C.success&&C.value){let m=C.value,w=m.passed??m.meetsThreshold??!0;t={passed:w,score:m.score||m.grade,checks:m.checks},i=w?"passed":"failed",h=`Quality gate: ${w?"PASSED":"FAILED"} (score: ${m.score||m.grade||"N/A"})`;let v=p.join(r,"quality-gate.json");I.writeFileSync(v,$(m),"utf-8"),e.push(v)}else i="failed",h=C.error?.message||"Quality gate evaluation failed";break}case"code-intelligence":{let f=await n.kernel.getDomainAPIAsync("code-intelligence");if(!f)return A(s,a,"failed",1,"Code intelligence domain not available",e);let C=s.config.target||".",{walkSourceFiles:m}=await import("./file-discovery-4HXUB4HN.js"),w=p.resolve(C),v=m(w,{includeTests:!1}),y=await f.index({paths:v,incremental:!0});if(y.success&&y.value){let g=y.value;t=g,h=`Indexed ${g.filesIndexed} files, ${g.nodesCreated} nodes`;let d=p.join(r,"code-intelligence.json");I.writeFileSync(d,$(g),"utf-8"),e.push(d)}else i="warning",h=y.error?.message||"Code intelligence indexing incomplete";break}default:h=`Custom phase "${s.name}" \u2014 no built-in handler`,i="warning"}let k=Date.now()-a;return{phase:s.name,type:s.type,status:i,duration:k,exitCode:i==="failed"?1:0,summary:h,artifacts:e,details:t}}catch(t){let i=Date.now()-a;return{phase:s.name,type:s.type,status:"failed",duration:i,exitCode:1,summary:`Error: ${t instanceof Error?t.message:String(t)}`,artifacts:e}}}function A(s,n,r,l,a,e){return{phase:s.name,type:s.type,status:r,duration:Date.now()-n,exitCode:l,summary:a,artifacts:e}}function _(s){let n=`# AQE CI/CD Report
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.9.9");process.exit(0)}
2
+ import{a as D}from"./chunk-DI6R2AVP.js";import{c as x,d as $}from"./chunk-ADJGMTIW.js";import{a as j}from"./chunk-CZYTPNUI.js";import"./chunk-PEEN4AAK.js";import"./chunk-UYKIPSRX.js";import{Command as U}from"commander";import o from"chalk";import*as I from"fs";import*as p from"path";import*as F from"fs";import*as R from"path";var P={version:"1",name:"aqe-ci",phases:[{name:"Test Generation",type:"test",enabled:!0,config:{target:".",framework:"vitest",type:"unit"},continueOnFailure:!1,timeout:300},{name:"Coverage Analysis",type:"coverage",enabled:!0,config:{target:".",threshold:80},continueOnFailure:!0,timeout:300},{name:"Security Scan",type:"security",enabled:!0,config:{sast:!0},continueOnFailure:!0,timeout:300},{name:"Quality Gate",type:"quality-gate",enabled:!0,config:{},continueOnFailure:!1,timeout:60}],output:{format:"json",directory:".aqe-ci-output",combinedReport:!0},qualityGate:{enforced:!0,thresholds:{coverage:80,security:"medium",quality:70}}},Q=[".aqe-ci.yml",".aqe-ci.yaml","aqe-ci.yml","aqe-ci.yaml"];function G(s=process.cwd()){let n=R.resolve(s);for(let r=0;r<10;r++){for(let a of Q){let e=R.join(n,a);if(F.existsSync(e))return e}let l=R.dirname(n);if(l===n)break;n=l}return null}function T(s){if(!F.existsSync(s))return{success:!1,errors:[`Config file not found: ${s}`]};let n;try{n=F.readFileSync(s,"utf-8")}catch(r){return{success:!1,errors:[`Failed to read config: ${r}`]}}return N(n,s)}function N(s,n){let r=[],l;try{l=j(s)}catch(e){return{success:!1,errors:[`Invalid YAML: ${e}`]}}let a={version:l.version||P.version,name:l.name||P.name,phases:[],output:{...P.output},qualityGate:{...P.qualityGate,thresholds:{...P.qualityGate.thresholds}}};if(l.output&&typeof l.output=="object"){let e=l.output;e.format&&(a.output.format=e.format),e.directory&&(a.output.directory=e.directory),e.combined_report!==void 0&&(a.output.combinedReport=e.combined_report)}if(l.quality_gate&&typeof l.quality_gate=="object"){let e=l.quality_gate;if(e.enforced!==void 0&&(a.qualityGate.enforced=e.enforced),e.thresholds&&typeof e.thresholds=="object"){let t=e.thresholds;t.coverage!==void 0&&(a.qualityGate.thresholds.coverage=t.coverage),t.security!==void 0&&(a.qualityGate.thresholds.security=t.security),t.quality!==void 0&&(a.qualityGate.thresholds.quality=t.quality)}}if(l.phases&&Array.isArray(l.phases))for(let e=0;e<l.phases.length;e++){let t=l.phases[e];if(!t.name){r.push(`Phase ${e+1} must have a "name" field`);continue}if(!t.type){r.push(`Phase "${t.name}" must have a "type" field`);continue}let i=["test","coverage","security","quality-gate","code-intelligence","custom"];if(!i.includes(t.type)){r.push(`Phase "${t.name}" has invalid type "${t.type}". Valid: ${i.join(", ")}`);continue}let h={name:t.name,type:t.type,enabled:t.enabled!==!1,config:t.config||{},continueOnFailure:t.continue_on_failure||!1,timeout:t.timeout||300};a.phases.push(h)}else a.phases=[...P.phases];return a.phases.length===0&&r.push("Config must have at least one phase"),r.length>0?{success:!1,config:a,errors:r}:{success:!0,config:a,errors:[],configPath:n}}function E(){return{...P,phases:P.phases.map(s=>({...s,config:{...s.config}})),output:{...P.output},qualityGate:{...P.qualityGate,thresholds:{...P.qualityGate.thresholds}}}}async function W(s,n,r,l){let a=Date.now(),e=[];if(!s.enabled)return{phase:s.name,type:s.type,status:"skipped",duration:0,exitCode:0,summary:"Phase disabled",artifacts:[]};try{let t={},i="passed",h="";switch(s.type){case"test":{let f=await n.kernel.getDomainAPIAsync("test-generation");if(!f)return A(s,a,"failed",1,"Test generation domain not available",e);let C=s.config.target||".",{walkSourceFiles:m}=await import("./file-discovery-GXXWQJV3.js"),w=p.resolve(C),v=m(w,{includeTests:!1}),y=await f.generateTests({sourceFiles:v,testType:s.config.type||"unit",framework:s.config.framework||"vitest",coverageTarget:80});if(y.success&&y.value){let g=y.value;t={testsGenerated:g.tests.length,coverageEstimate:g.coverageEstimate},h=`Generated ${g.tests.length} tests (est. ${g.coverageEstimate}% coverage)`;let d=p.join(r,"test-generation.json");I.writeFileSync(d,$(g),"utf-8"),e.push(d)}else i="failed",h=y.error?.message||"Test generation failed";break}case"coverage":{let f=await n.kernel.getDomainAPIAsync("coverage-analysis");if(!f)return A(s,a,"failed",1,"Coverage analysis domain not available",e);let C=s.config.target||".",m=s.config.threshold||80,{walkSourceFiles:w}=await import("./file-discovery-GXXWQJV3.js"),v=p.resolve(C),y=w(v,{includeTests:!1}),g=D(y),d=await f.analyze({coverageData:g,threshold:m,includeFileDetails:!0});if(d.success&&d.value){let b=d.value;t={...b.summary,meetsThreshold:b.meetsThreshold,threshold:m},i=b.meetsThreshold?"passed":"warning",h=`Line: ${b.summary.line}%, Branch: ${b.summary.branch}% \u2014 ${b.meetsThreshold?"meets":"below"} ${m}% threshold`;let q=p.join(r,"coverage.json");I.writeFileSync(q,$(d.value),"utf-8"),e.push(q)}else i="failed",h=d.error?.message||"Coverage analysis failed";break}case"security":{let f=await n.kernel.getDomainAPIAsync("security-compliance");if(!f)return A(s,a,"failed",1,"Security domain not available",e);let C=s.config.target||".",{walkSourceFiles:m}=await import("./file-discovery-GXXWQJV3.js"),w=p.resolve(C),v=m(w,{includeTests:!0}),y=await f.runSASTScan(v);if(y.success&&y.value){let g=y.value,d=g.vulnerabilities||[],b=d.filter(S=>S.severity==="high"||S.severity==="critical").length;t={vulnerabilities:d.length,high:b},i=b>0?"failed":d.length>0?"warning":"passed",h=d.length===0?"No vulnerabilities found":`${d.length} vulnerabilities (${b} high/critical)`;let{toSARIF:q}=await import("./ci-output-MV75HUK7.js"),c=p.join(r,"security.sarif");I.writeFileSync(c,q({vulnerabilities:d,target:C,scanType:"SAST"}),"utf-8"),e.push(c);let u=p.join(r,"security.json");I.writeFileSync(u,$(g),"utf-8"),e.push(u)}else i="failed",h=y.error?.message||"Security scan failed";break}case"quality-gate":{let f=await n.kernel.getDomainAPIAsync("quality-assessment");if(!f)return A(s,a,"failed",1,"Quality assessment domain not available",e);let C=await f.evaluate({runGate:!0,includeAdvice:!0});if(C.success&&C.value){let m=C.value,w=m.passed??m.meetsThreshold??!0;t={passed:w,score:m.score||m.grade,checks:m.checks},i=w?"passed":"failed",h=`Quality gate: ${w?"PASSED":"FAILED"} (score: ${m.score||m.grade||"N/A"})`;let v=p.join(r,"quality-gate.json");I.writeFileSync(v,$(m),"utf-8"),e.push(v)}else i="failed",h=C.error?.message||"Quality gate evaluation failed";break}case"code-intelligence":{let f=await n.kernel.getDomainAPIAsync("code-intelligence");if(!f)return A(s,a,"failed",1,"Code intelligence domain not available",e);let C=s.config.target||".",{walkSourceFiles:m}=await import("./file-discovery-GXXWQJV3.js"),w=p.resolve(C),v=m(w,{includeTests:!1}),y=await f.index({paths:v,incremental:!0});if(y.success&&y.value){let g=y.value;t=g,h=`Indexed ${g.filesIndexed} files, ${g.nodesCreated} nodes`;let d=p.join(r,"code-intelligence.json");I.writeFileSync(d,$(g),"utf-8"),e.push(d)}else i="warning",h=y.error?.message||"Code intelligence indexing incomplete";break}default:h=`Custom phase "${s.name}" \u2014 no built-in handler`,i="warning"}let k=Date.now()-a;return{phase:s.name,type:s.type,status:i,duration:k,exitCode:i==="failed"?1:0,summary:h,artifacts:e,details:t}}catch(t){let i=Date.now()-a;return{phase:s.name,type:s.type,status:"failed",duration:i,exitCode:1,summary:`Error: ${t instanceof Error?t.message:String(t)}`,artifacts:e}}}function A(s,n,r,l,a,e){return{phase:s.name,type:s.type,status:r,duration:Date.now()-n,exitCode:l,summary:a,artifacts:e}}function _(s){let n=`# AQE CI/CD Report
3
3
 
4
4
  `;n+=`**Status:** ${s.overallStatus==="passed"?"PASSED":s.overallStatus==="warning"?"WARNING":"FAILED"}
5
5
  `,n+=`**Duration:** ${(s.duration/1e3).toFixed(1)}s
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.8");process.exit(0)}
2
- import{a,b,c,d,e,f,g,h,i,j}from"./chunk-DLKRK2GU.js";import"./chunk-E4D36LGH.js";export{a as FORMAT_OPTION,b as OUTPUT_OPTION,g as coverageToMarkdown,h as qualityGateToMarkdown,i as securityToMarkdown,j as testRunToMarkdown,d as toJSON,f as toJUnit,e as toSARIF,c as writeOutput};
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.9.9");process.exit(0)}
2
+ import{a,b,c,d,e,f,g,h,i,j}from"./chunk-ADJGMTIW.js";import"./chunk-UYKIPSRX.js";export{a as FORMAT_OPTION,b as OUTPUT_OPTION,g as coverageToMarkdown,h as qualityGateToMarkdown,i as securityToMarkdown,j as testRunToMarkdown,d as toJSON,f as toJUnit,e as toSARIF,c as writeOutput};
@@ -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.9.8");process.exit(0)}
2
- import{b as p}from"./chunk-NCXVOOA7.js";import{b as f,d as h}from"./chunk-VVNR4R22.js";import{a as c,c as b}from"./chunk-PG7CZ6Q4.js";import{a as v}from"./chunk-E4D36LGH.js";h();b();import{existsSync as u,writeFileSync as g,readFileSync as m}from"node:fs";import{join as a}from"node:path";import{execSync as C}from"node:child_process";async function y(t,e){let o=p(t);if(e&&o.available&&console.log(`[ClaudeFlow] Detected via ${o.method}${o.version?`: v${o.version}`:""}`),!o.available)return{available:!1};let n={"mcp-config":"mcp","local-binary":"cli","npx-cached":"cli","npm-dependency":"npm"};return{available:!0,version:o.version,method:o.method?n[o.method]:void 0}}async function F(t){return{trajectories:!0,modelRouting:!0,pretrain:!0,workers:!0,patternSearch:!0}}function S(t,e){return{version:"1.0",projectRoot:t,integration:{enabled:!0,features:{trajectories:e.trajectories,modelRouting:e.modelRouting,pretrain:e.pretrain,workers:e.workers}},learning:{trajectoryStorage:e.trajectories?"claude-flow":"local",patternSearch:e.patternSearch?"claude-flow":"local"},routing:{modelRouting:e.modelRouting?"claude-flow":"rule-based",preferences:{simple:"haiku",standard:"sonnet",complex:"opus"}},pretrain:{enabled:e.pretrain,depth:"medium",autoRun:!0},workers:{enabled:e.workers,autoDispatch:["optimize","consolidate"]}}}function R(t){let e=a(t,".claude","settings.json"),o={};if(u(e))try{o=f(m(e,"utf-8"))}catch{}o.mcpServers||(o.mcpServers={});let n=o.mcpServers;!n.ruflo&&!n["claude-flow"]&&(n.ruflo={command:"npx",args:["ruflo@3.5.18","mcp"],env:{}}),g(e,JSON.stringify(o,null,2))}async function j(t,e){try{e&&console.log("[ClaudeFlow] Running pretrain analysis..."),C("npx --no-install ruflo hooks pretrain --depth medium",{encoding:"utf-8",timeout:12e4,cwd:t,stdio:["pipe","pipe","pipe"]}),e&&console.log("[ClaudeFlow] Pretrain analysis complete")}catch(o){e&&console.log("[ClaudeFlow] Pretrain analysis skipped:",c(o))}}async function D(t){let{projectRoot:e,force:o,checkOnly:n,debug:s}=t,r=await y(e,s);if(!r.available&&!o)return{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,workers:!1,patternSearch:!1}};let i=await F(e);if(n)return{available:r.available,version:r.version,features:i};let w=a(e,".agentic-qe"),d=a(w,"claude-flow-integration.json");try{let l=S(e,i);g(d,JSON.stringify(l,null,2)),s&&console.log(`[ClaudeFlow] Config written to: ${d}`)}catch(l){return{available:r.available,version:r.version,features:i,error:`Failed to write config: ${c(l)}`}}try{R(e)}catch(l){s&&console.log("[ClaudeFlow] MCP config update failed:",c(l))}return i.pretrain&&await j(e,s),{available:!0,version:r.version,features:i,configPath:d}}function J(t){let e=a(t,".agentic-qe","claude-flow-integration.json");return u(e)}function N(t){let e=a(t,".agentic-qe","claude-flow-integration.json");if(!u(e))return null;try{return f(m(e,"utf-8"))}catch{return null}}function I(t){let e=a(t,".agentic-qe","claude-flow-integration.json");if(u(e))try{return v("node:fs").rmSync(e),!0}catch{return!1}return!0}export{N as getClaudeFlowConfig,J as isClaudeFlowConfigured,I as removeClaudeFlowIntegration,D as setupClaudeFlowIntegration};
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.9.9");process.exit(0)}
2
+ import{b as p}from"./chunk-4CDSEZD6.js";import{b as f,d as h}from"./chunk-MWZN4PYF.js";import{a as c,c as b}from"./chunk-BVOGMK6N.js";import{a as v}from"./chunk-UYKIPSRX.js";h();b();import{existsSync as u,writeFileSync as g,readFileSync as m}from"node:fs";import{join as a}from"node:path";import{execSync as C}from"node:child_process";async function y(t,e){let o=p(t);if(e&&o.available&&console.log(`[ClaudeFlow] Detected via ${o.method}${o.version?`: v${o.version}`:""}`),!o.available)return{available:!1};let n={"mcp-config":"mcp","local-binary":"cli","npx-cached":"cli","npm-dependency":"npm"};return{available:!0,version:o.version,method:o.method?n[o.method]:void 0}}async function F(t){return{trajectories:!0,modelRouting:!0,pretrain:!0,workers:!0,patternSearch:!0}}function S(t,e){return{version:"1.0",projectRoot:t,integration:{enabled:!0,features:{trajectories:e.trajectories,modelRouting:e.modelRouting,pretrain:e.pretrain,workers:e.workers}},learning:{trajectoryStorage:e.trajectories?"claude-flow":"local",patternSearch:e.patternSearch?"claude-flow":"local"},routing:{modelRouting:e.modelRouting?"claude-flow":"rule-based",preferences:{simple:"haiku",standard:"sonnet",complex:"opus"}},pretrain:{enabled:e.pretrain,depth:"medium",autoRun:!0},workers:{enabled:e.workers,autoDispatch:["optimize","consolidate"]}}}function R(t){let e=a(t,".claude","settings.json"),o={};if(u(e))try{o=f(m(e,"utf-8"))}catch{}o.mcpServers||(o.mcpServers={});let n=o.mcpServers;!n.ruflo&&!n["claude-flow"]&&(n.ruflo={command:"npx",args:["ruflo@3.5.18","mcp"],env:{}}),g(e,JSON.stringify(o,null,2))}async function j(t,e){try{e&&console.log("[ClaudeFlow] Running pretrain analysis..."),C("npx --no-install ruflo hooks pretrain --depth medium",{encoding:"utf-8",timeout:12e4,cwd:t,stdio:["pipe","pipe","pipe"]}),e&&console.log("[ClaudeFlow] Pretrain analysis complete")}catch(o){e&&console.log("[ClaudeFlow] Pretrain analysis skipped:",c(o))}}async function D(t){let{projectRoot:e,force:o,checkOnly:n,debug:s}=t,r=await y(e,s);if(!r.available&&!o)return{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,workers:!1,patternSearch:!1}};let i=await F(e);if(n)return{available:r.available,version:r.version,features:i};let w=a(e,".agentic-qe"),d=a(w,"claude-flow-integration.json");try{let l=S(e,i);g(d,JSON.stringify(l,null,2)),s&&console.log(`[ClaudeFlow] Config written to: ${d}`)}catch(l){return{available:r.available,version:r.version,features:i,error:`Failed to write config: ${c(l)}`}}try{R(e)}catch(l){s&&console.log("[ClaudeFlow] MCP config update failed:",c(l))}return i.pretrain&&await j(e,s),{available:!0,version:r.version,features:i,configPath:d}}function J(t){let e=a(t,".agentic-qe","claude-flow-integration.json");return u(e)}function N(t){let e=a(t,".agentic-qe","claude-flow-integration.json");if(!u(e))return null;try{return f(m(e,"utf-8"))}catch{return null}}function I(t){let e=a(t,".agentic-qe","claude-flow-integration.json");if(u(e))try{return v("node:fs").rmSync(e),!0}catch{return!1}return!0}export{N as getClaudeFlowConfig,J as isClaudeFlowConfigured,I as removeClaudeFlowIntegration,D as setupClaudeFlowIntegration};
@@ -0,0 +1,2 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.9");process.exit(0)}
2
+ import{c as a,d as b,e as c}from"./chunk-MZOYBHJ3.js";import"./chunk-QQLQEQJM.js";import"./chunk-BVOGMK6N.js";import"./chunk-UYKIPSRX.js";c();export{a as VibiumClientImpl,b as VibiumClientProvider};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.8");process.exit(0)}
2
- import{b as p}from"./chunk-LPRHYSXN.js";import{a as f,c as v}from"./chunk-PG7CZ6Q4.js";import"./chunk-E4D36LGH.js";v();import{existsSync as s,mkdirSync as m,readFileSync as u,writeFileSync as a}from"fs";import{join as h,dirname as d}from"path";var l=class{projectRoot;overwrite;generator;constructor(r){this.projectRoot=r.projectRoot,this.overwrite=r.overwrite??!1,this.generator=p()}async install(){let r={success:!0,mcpConfigured:!1,modeInstalled:!1,errors:[],configPath:"",modePath:""};try{let t=this.generator.generateMcpConfig("cline"),e=h(this.projectRoot,t.path);if(r.configPath=e,!s(e)||this.overwrite){let o=d(e);if(s(o)||m(o,{recursive:!0}),s(e)&&this.overwrite){let c=this.mergeExistingConfig(e,t.content);a(e,c)}else a(e,t.content);r.mcpConfigured=!0}let n=this.generator.generateBehavioralRules("cline"),i=h(this.projectRoot,n.path);if(r.modePath=i,!s(i)||this.overwrite){let o=d(i);if(s(o)||m(o,{recursive:!0}),s(i)&&this.overwrite){let c=this.mergeExistingModes(i,n.content);a(i,c)}else a(i,n.content);r.modeInstalled=!0}}catch(t){r.success=!1,r.errors.push(`Cline installation failed: ${f(t)}`)}return r}mergeExistingConfig(r,t){try{let e=JSON.parse(u(r,"utf-8")),n=JSON.parse(t);return e.mcpServers||(e.mcpServers={}),Object.assign(e.mcpServers,n.mcpServers),JSON.stringify(e,null,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.9.9");process.exit(0)}
2
+ import{b as p}from"./chunk-22HQFULR.js";import{a as f,c as v}from"./chunk-BVOGMK6N.js";import"./chunk-UYKIPSRX.js";v();import{existsSync as s,mkdirSync as m,readFileSync as u,writeFileSync as a}from"fs";import{join as h,dirname as d}from"path";var l=class{projectRoot;overwrite;generator;constructor(r){this.projectRoot=r.projectRoot,this.overwrite=r.overwrite??!1,this.generator=p()}async install(){let r={success:!0,mcpConfigured:!1,modeInstalled:!1,errors:[],configPath:"",modePath:""};try{let t=this.generator.generateMcpConfig("cline"),e=h(this.projectRoot,t.path);if(r.configPath=e,!s(e)||this.overwrite){let o=d(e);if(s(o)||m(o,{recursive:!0}),s(e)&&this.overwrite){let c=this.mergeExistingConfig(e,t.content);a(e,c)}else a(e,t.content);r.mcpConfigured=!0}let n=this.generator.generateBehavioralRules("cline"),i=h(this.projectRoot,n.path);if(r.modePath=i,!s(i)||this.overwrite){let o=d(i);if(s(o)||m(o,{recursive:!0}),s(i)&&this.overwrite){let c=this.mergeExistingModes(i,n.content);a(i,c)}else a(i,n.content);r.modeInstalled=!0}}catch(t){r.success=!1,r.errors.push(`Cline installation failed: ${f(t)}`)}return r}mergeExistingConfig(r,t){try{let e=JSON.parse(u(r,"utf-8")),n=JSON.parse(t);return e.mcpServers||(e.mcpServers={}),Object.assign(e.mcpServers,n.mcpServers),JSON.stringify(e,null,2)+`
3
3
  `}catch{return t}}mergeExistingModes(r,t){try{let e=JSON.parse(u(r,"utf-8")),n=JSON.parse(t);if(!Array.isArray(e))return t;let i=e.filter(o=>o.slug!=="qe-engineer");return i.push(...n),JSON.stringify(i,null,2)+`
4
4
  `}catch{return t}}};function x(g){return new l(g)}export{l as ClineInstaller,x as createClineInstaller};
@@ -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.9.8");process.exit(0)}
2
- import{a as A,b as $}from"./chunk-HTL2WT64.js";import{c as b,d as x}from"./chunk-DLKRK2GU.js";import"./chunk-E4D36LGH.js";import{Command as z}from"commander";import e from"chalk";function j(S,w,P){return new z("code").description("Code intelligence analysis").argument("<action>","Action (index|search|impact|deps|complexity)").argument("[target]","Target path or query").option("--depth <depth>","Analysis depth","3").option("--include-tests","Include test files").option("--incremental","Incremental indexing (index action only)").option("--git-since <ref>","Index changes since git ref (index action only)").option("-F, --format <format>","Output format (text|json)","text").option("-o, --output <path>","Write output to file").addHelpText("after",`
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.9.9");process.exit(0)}
2
+ import{a as A,b as $}from"./chunk-J62N66ZH.js";import{c as b,d as x}from"./chunk-ADJGMTIW.js";import"./chunk-UYKIPSRX.js";import{Command as z}from"commander";import e from"chalk";function j(S,w,P){return new z("code").description("Code intelligence analysis").argument("<action>","Action (index|search|impact|deps|complexity)").argument("[target]","Target path or query").option("--depth <depth>","Analysis depth","3").option("--include-tests","Include test files").option("--incremental","Incremental indexing (index action only)").option("--git-since <ref>","Index changes since git ref (index action only)").option("-F, --format <format>","Output format (text|json)","text").option("-o, --output <path>","Write output to file").addHelpText("after",`
3
3
  Examples:
4
4
  aqe code index src/ Index source files into knowledge graph
5
5
  aqe code index src/ --incremental Incremental index (only changed files)
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.8");process.exit(0)}
2
- import"./chunk-E4D36LGH.js";import{readFile as m}from"fs/promises";var d=new Set(["if","for","while","switch","catch","return","new","throw","import","export","constructor"]),h=50;function x(o,c){let n=c.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.9.9");process.exit(0)}
2
+ import"./chunk-UYKIPSRX.js";import{readFile as m}from"fs/promises";var d=new Set(["if","for","while","switch","catch","return","new","throw","import","export","constructor"]),h=50;function x(o,c){let n=c.split(`
3
3
  `),e=[],i=[];for(let t=0;t<n.length;t++){let s=n[t],a=s.match(/(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+(\w+)/);if(a){e.push({type:"function",name:a[1],lineStart:t+1});continue}let l=s.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[a-zA-Z_]\w*)\s*(?::\s*[^=]+)?\s*=>/);if(l){e.push({type:"function",name:l[1],lineStart:t+1});continue}let u=s.match(/(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+(\w+)/);if(u){e.push({type:"class",name:u[1],lineStart:t+1});continue}let f=s.match(/(?:export\s+)?interface\s+(\w+)/);if(f){e.push({type:"interface",name:f[1],lineStart:t+1});continue}let r=s.match(/^\s+(?:(?:public|private|protected|static|readonly|override|abstract|async)\s+)*(\w+)\s*(?:<[^>]*>)?\s*\([^)]*\)\s*(?::\s*[^{]+)?\s*\{?\s*$/);if(r&&!d.has(r[1])){e.push({type:"function",name:r[1],lineStart:t+1});continue}let p=s.match(/(?:import|from)\s+['"](\.[^'"]+)['"]/);p&&i.push(p[1])}return{path:o,entities:e,imports:i}}async function y(o){let c=[];for(let n=0;n<o.length;n+=h){let e=o.slice(n,n+h),i=await Promise.allSettled(e.map(async t=>{let s=await m(t,"utf-8");return x(t,s)}));for(let t of i)t.status==="fulfilled"&&c.push(t.value)}return{files:c}}export{y as extractCodeIndex};
@@ -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.9.8");process.exit(0)}
2
- import{b as f}from"./chunk-LPRHYSXN.js";import{a as l,c as m}from"./chunk-PG7CZ6Q4.js";import"./chunk-E4D36LGH.js";m();import{existsSync as o,mkdirSync as h,readFileSync as d,writeFileSync as s}from"fs";import{join as u,dirname as x}from"path";var c=class{projectRoot;overwrite;generator;constructor(t){this.projectRoot=t.projectRoot,this.overwrite=t.overwrite??!1,this.generator=f()}async install(){let t={success:!0,mcpConfigured:!1,agentsMdInstalled:!1,errors:[],configPath:"",agentsMdPath:""};try{let r=this.generator.generateMcpConfig("codex"),e=u(this.projectRoot,r.path);if(t.configPath=e,!o(e)||this.overwrite){let i=x(e);if(o(i)||h(i,{recursive:!0}),o(e)&&this.overwrite){let p=this.mergeExistingTomlConfig(e,r.content);s(e,p)}else s(e,r.content);t.mcpConfigured=!0}let a=this.generator.generateBehavioralRules("codex"),n=u(this.projectRoot,a.path);if(t.agentsMdPath=n,!o(n)||this.overwrite){if(o(n)&&this.overwrite){let i=this.mergeExistingAgentsMd(n,a.content);s(n,i)}else s(n,a.content);t.agentsMdInstalled=!0}}catch(r){t.success=!1,t.errors.push(`Codex installation failed: ${l(r)}`)}return t}mergeExistingTomlConfig(t,r){try{let e=d(t,"utf-8");return e.includes("[mcp_servers.agentic-qe]")?e:e.trimEnd()+`
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.9.9");process.exit(0)}
2
+ import{b as f}from"./chunk-22HQFULR.js";import{a as l,c as m}from"./chunk-BVOGMK6N.js";import"./chunk-UYKIPSRX.js";m();import{existsSync as o,mkdirSync as h,readFileSync as d,writeFileSync as s}from"fs";import{join as u,dirname as x}from"path";var c=class{projectRoot;overwrite;generator;constructor(t){this.projectRoot=t.projectRoot,this.overwrite=t.overwrite??!1,this.generator=f()}async install(){let t={success:!0,mcpConfigured:!1,agentsMdInstalled:!1,errors:[],configPath:"",agentsMdPath:""};try{let r=this.generator.generateMcpConfig("codex"),e=u(this.projectRoot,r.path);if(t.configPath=e,!o(e)||this.overwrite){let i=x(e);if(o(i)||h(i,{recursive:!0}),o(e)&&this.overwrite){let p=this.mergeExistingTomlConfig(e,r.content);s(e,p)}else s(e,r.content);t.mcpConfigured=!0}let a=this.generator.generateBehavioralRules("codex"),n=u(this.projectRoot,a.path);if(t.agentsMdPath=n,!o(n)||this.overwrite){if(o(n)&&this.overwrite){let i=this.mergeExistingAgentsMd(n,a.content);s(n,i)}else s(n,a.content);t.agentsMdInstalled=!0}}catch(r){t.success=!1,t.errors.push(`Codex installation failed: ${l(r)}`)}return t}mergeExistingTomlConfig(t,r){try{let e=d(t,"utf-8");return e.includes("[mcp_servers.agentic-qe]")?e:e.trimEnd()+`
3
3
 
4
4
  `+r}catch{return r}}mergeExistingAgentsMd(t,r){try{let e=d(t,"utf-8");return e.includes("Agentic QE")||e.includes("fleet_init")?e:e.trimEnd()+`
5
5
 
@@ -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.9.8");process.exit(0)}
2
- import"./chunk-E4D36LGH.js";import{Command as N}from"commander";import o from"chalk";var c=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization"],a=["qe-tdd-specialist","qe-test-architect","qe-parallel-executor","qe-flaky-hunter","qe-retry-handler","qe-coverage-specialist","qe-gap-detector","qe-quality-gate","qe-deployment-advisor","qe-code-complexity","qe-qx-partner","qe-security-scanner","qe-security-auditor","qe-contract-validator","qe-integration-tester","qe-graphql-tester","qe-visual-tester","qe-accessibility-auditor","qe-responsive-tester","qe-performance-tester","qe-load-tester","qe-chaos-engineer","qe-code-intelligence","qe-dependency-mapper","qe-kg-builder","qe-requirements-validator","qe-bdd-generator","qe-defect-predictor","qe-root-cause-analyzer","qe-regression-analyzer","qe-impact-analyzer","qe-risk-assessor","qe-learning-coordinator","qe-pattern-learner","qe-transfer-specialist","qe-metrics-optimizer","qe-fleet-commander","qe-queen-coordinator","qe-property-tester","qe-mutation-tester","qe-tdd-red","qe-tdd-green","qe-tdd-refactor","qe-code-reviewer","qe-integration-reviewer","qe-performance-reviewer","qe-security-reviewer"],i=["tester","reviewer","security-auditor","security-architect","performance-engineer","code-analyzer","cicd-engineer","reasoningbank-learner","adr-architect","ddd-domain-expert","v3-integration-architect","memory-specialist","claims-authorizer","sparc-orchestrator","sona-learning-optimizer","safla-neural","production-validator","tdd-london-swarm","queen-coordinator","swarm-memory-manager","worker-specialist","collective-intelligence-coordinator","scout-explorer","adaptive-coordinator","mesh-coordinator","hierarchical-coordinator","consensus-coordinator","byzantine-coordinator","raft-manager","crdt-synchronizer","n8n-workflow-executor","n8n-unit-tester","n8n-integration-test","n8n-trigger-test","n8n-security-auditor"],S=[...a,...i];var p=["generate-tests","execute-tests","analyze-coverage","assess-quality","predict-defects","validate-requirements","analyze-code","scan-security","validate-contracts","test-accessibility","chaos-test","optimize-learning"],b=["p0","p1","p2","p3"],y=["pending","running","completed","failed","cancelled"],d=["jest","vitest","pytest","junit","playwright","cypress","go-test","node-test"],w=["unit","integration","e2e"],C=["sqlite","agentdb","hybrid"];function q(){return`#!/bin/bash
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.9.9");process.exit(0)}
2
+ import"./chunk-UYKIPSRX.js";import{Command as N}from"commander";import o from"chalk";var c=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization"],a=["qe-tdd-specialist","qe-test-architect","qe-parallel-executor","qe-flaky-hunter","qe-retry-handler","qe-coverage-specialist","qe-gap-detector","qe-quality-gate","qe-deployment-advisor","qe-code-complexity","qe-qx-partner","qe-security-scanner","qe-security-auditor","qe-contract-validator","qe-integration-tester","qe-graphql-tester","qe-visual-tester","qe-accessibility-auditor","qe-responsive-tester","qe-performance-tester","qe-load-tester","qe-chaos-engineer","qe-code-intelligence","qe-dependency-mapper","qe-kg-builder","qe-requirements-validator","qe-bdd-generator","qe-defect-predictor","qe-root-cause-analyzer","qe-regression-analyzer","qe-impact-analyzer","qe-risk-assessor","qe-learning-coordinator","qe-pattern-learner","qe-transfer-specialist","qe-metrics-optimizer","qe-fleet-commander","qe-queen-coordinator","qe-property-tester","qe-mutation-tester","qe-tdd-red","qe-tdd-green","qe-tdd-refactor","qe-code-reviewer","qe-integration-reviewer","qe-performance-reviewer","qe-security-reviewer"],i=["tester","reviewer","security-auditor","security-architect","performance-engineer","code-analyzer","cicd-engineer","reasoningbank-learner","adr-architect","ddd-domain-expert","v3-integration-architect","memory-specialist","claims-authorizer","sparc-orchestrator","sona-learning-optimizer","safla-neural","production-validator","tdd-london-swarm","queen-coordinator","swarm-memory-manager","worker-specialist","collective-intelligence-coordinator","scout-explorer","adaptive-coordinator","mesh-coordinator","hierarchical-coordinator","consensus-coordinator","byzantine-coordinator","raft-manager","crdt-synchronizer","n8n-workflow-executor","n8n-unit-tester","n8n-integration-test","n8n-trigger-test","n8n-security-auditor"],S=[...a,...i];var p=["generate-tests","execute-tests","analyze-coverage","assess-quality","predict-defects","validate-requirements","analyze-code","scan-security","validate-contracts","test-accessibility","chaos-test","optimize-learning"],b=["p0","p1","p2","p3"],y=["pending","running","completed","failed","cancelled"],d=["jest","vitest","pytest","junit","playwright","cypress","go-test","node-test"],w=["unit","integration","e2e"],C=["sqlite","agentdb","hybrid"];function q(){return`#!/bin/bash
3
3
  # AQE CLI Bash Completion Script
4
4
  # Generated by aqe completions bash
5
5
  # ADR-041: Shell Completions for Enhanced Developer Experience
@@ -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.9.8");process.exit(0)}
2
- import{a,b,c,d,e,f,g,h,i}from"./chunk-266SKKFM.js";import"./chunk-UOSKMAAY.js";import"./chunk-QVGSD25D.js";import"./chunk-E4D36LGH.js";export{g as ComplexityAnalyzer,c as ScoreCalculator,a as SignalCollector,e as TierRecommender,h as createComplexityAnalyzer,i as createComplexityAnalyzerWithDependencies,d as createScoreCalculator,b as createSignalCollector,f as createTierRecommender};
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.9.9");process.exit(0)}
2
+ import{a,b,c,d,e,f,g,h,i}from"./chunk-W57I57M4.js";import"./chunk-DNS7DP2O.js";import"./chunk-BYPBKVTC.js";import"./chunk-UYKIPSRX.js";export{g as ComplexityAnalyzer,c as ScoreCalculator,a as SignalCollector,e as TierRecommender,h as createComplexityAnalyzer,i as createComplexityAnalyzerWithDependencies,d as createScoreCalculator,b as createSignalCollector,f as createTierRecommender};
@@ -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.9.8");process.exit(0)}
2
- import{b as g}from"./chunk-LPRHYSXN.js";import{a as u,c as h}from"./chunk-PG7CZ6Q4.js";import"./chunk-E4D36LGH.js";h();import{existsSync as o,mkdirSync as f,readFileSync as d,writeFileSync as a}from"fs";import{join as m,dirname as p}from"path";var c=class{projectRoot;overwrite;generator;constructor(t){this.projectRoot=t.projectRoot,this.overwrite=t.overwrite??!1,this.generator=g()}async install(){let t={success:!0,mcpConfigured:!1,rulesInstalled:!1,errors:[],configPath:"",rulesPath:""};try{let r=this.generator.generateMcpConfig("continuedev"),e=m(this.projectRoot,r.path);if(t.configPath=e,!o(e)||this.overwrite){let n=p(e);if(o(n)||f(n,{recursive:!0}),o(e)&&this.overwrite){let v=this.mergeExistingYamlConfig(e,r.content);a(e,v)}else a(e,r.content);t.mcpConfigured=!0}let s=this.generator.generateBehavioralRules("continuedev"),i=m(this.projectRoot,s.path);if(t.rulesPath=i,!o(i)||this.overwrite){let n=p(i);o(n)||f(n,{recursive:!0}),a(i,s.content),t.rulesInstalled=!0}}catch(r){t.success=!1,t.errors.push(`Continue.dev installation failed: ${u(r)}`)}return t}mergeExistingYamlConfig(t,r){try{let e=d(t,"utf-8");return e.includes("agentic-qe")?e:e.includes("mcpServers:")?e.trimEnd()+`
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.9.9");process.exit(0)}
2
+ import{b as g}from"./chunk-22HQFULR.js";import{a as u,c as h}from"./chunk-BVOGMK6N.js";import"./chunk-UYKIPSRX.js";h();import{existsSync as o,mkdirSync as f,readFileSync as d,writeFileSync as a}from"fs";import{join as m,dirname as p}from"path";var c=class{projectRoot;overwrite;generator;constructor(t){this.projectRoot=t.projectRoot,this.overwrite=t.overwrite??!1,this.generator=g()}async install(){let t={success:!0,mcpConfigured:!1,rulesInstalled:!1,errors:[],configPath:"",rulesPath:""};try{let r=this.generator.generateMcpConfig("continuedev"),e=m(this.projectRoot,r.path);if(t.configPath=e,!o(e)||this.overwrite){let n=p(e);if(o(n)||f(n,{recursive:!0}),o(e)&&this.overwrite){let v=this.mergeExistingYamlConfig(e,r.content);a(e,v)}else a(e,r.content);t.mcpConfigured=!0}let s=this.generator.generateBehavioralRules("continuedev"),i=m(this.projectRoot,s.path);if(t.rulesPath=i,!o(i)||this.overwrite){let n=p(i);o(n)||f(n,{recursive:!0}),a(i,s.content),t.rulesInstalled=!0}}catch(r){t.success=!1,t.errors.push(`Continue.dev installation failed: ${u(r)}`)}return t}mergeExistingYamlConfig(t,r){try{let e=d(t,"utf-8");return e.includes("agentic-qe")?e:e.includes("mcpServers:")?e.trimEnd()+`
3
3
  `+` - name: agentic-qe
4
4
  command: npx
5
5
  args:
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.8");process.exit(0)}
2
- import{b as g}from"./chunk-LPRHYSXN.js";import{a as p,c as v}from"./chunk-PG7CZ6Q4.js";import"./chunk-E4D36LGH.js";v();import{existsSync as s,mkdirSync as f,readFileSync as C,writeFileSync as l}from"fs";import{join as u,dirname as h}from"path";var a=class{projectRoot;overwrite;generator;constructor(t){this.projectRoot=t.projectRoot,this.overwrite=t.overwrite??!1,this.generator=g()}async install(){let t={success:!0,mcpConfigured:!1,rulesInstalled:!1,errors:[],configPath:"",rulesPath:""};try{let r=this.generator.generateMcpConfig("copilot"),e=u(this.projectRoot,r.path);if(t.configPath=e,!s(e)||this.overwrite){let o=h(e);if(s(o)||f(o,{recursive:!0}),s(e)&&this.overwrite){let m=this.mergeExistingConfig(e,r.content);l(e,m)}else l(e,r.content);t.mcpConfigured=!0}let i=this.generator.generateBehavioralRules("copilot"),n=u(this.projectRoot,i.path);if(t.rulesPath=n,!s(n)||this.overwrite){let o=h(n);s(o)||f(o,{recursive:!0}),l(n,i.content),t.rulesInstalled=!0}}catch(r){t.success=!1,t.errors.push(`Copilot installation failed: ${p(r)}`)}return t}mergeExistingConfig(t,r){try{let e=JSON.parse(C(t,"utf-8")),i=JSON.parse(r);return e.servers||(e.servers={}),Object.assign(e.servers,i.servers),JSON.stringify(e,null,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.9.9");process.exit(0)}
2
+ import{b as g}from"./chunk-22HQFULR.js";import{a as p,c as v}from"./chunk-BVOGMK6N.js";import"./chunk-UYKIPSRX.js";v();import{existsSync as s,mkdirSync as f,readFileSync as C,writeFileSync as l}from"fs";import{join as u,dirname as h}from"path";var a=class{projectRoot;overwrite;generator;constructor(t){this.projectRoot=t.projectRoot,this.overwrite=t.overwrite??!1,this.generator=g()}async install(){let t={success:!0,mcpConfigured:!1,rulesInstalled:!1,errors:[],configPath:"",rulesPath:""};try{let r=this.generator.generateMcpConfig("copilot"),e=u(this.projectRoot,r.path);if(t.configPath=e,!s(e)||this.overwrite){let o=h(e);if(s(o)||f(o,{recursive:!0}),s(e)&&this.overwrite){let m=this.mergeExistingConfig(e,r.content);l(e,m)}else l(e,r.content);t.mcpConfigured=!0}let i=this.generator.generateBehavioralRules("copilot"),n=u(this.projectRoot,i.path);if(t.rulesPath=n,!s(n)||this.overwrite){let o=h(n);s(o)||f(o,{recursive:!0}),l(n,i.content),t.rulesInstalled=!0}}catch(r){t.success=!1,t.errors.push(`Copilot installation failed: ${p(r)}`)}return t}mergeExistingConfig(t,r){try{let e=JSON.parse(C(t,"utf-8")),i=JSON.parse(r);return e.servers||(e.servers={}),Object.assign(e.servers,i.servers),JSON.stringify(e,null,2)+`
3
3
  `}catch{return r}}};function y(c){return new a(c)}export{a as CopilotInstaller,y as createCopilotInstaller};
@@ -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.9.8");process.exit(0)}
2
- import{a,b,c,d}from"./chunk-NHXFAXEV.js";import"./chunk-E4D36LGH.js";export{b as CostTracker,a as MODEL_PRICING,c as getGlobalCostTracker,d as resetGlobalCostTracker};
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.9.9");process.exit(0)}
2
+ import{a,b,c,d}from"./chunk-2O3WZ6E3.js";import"./chunk-UYKIPSRX.js";export{b as CostTracker,a as MODEL_PRICING,c as getGlobalCostTracker,d as resetGlobalCostTracker};